A boot loader in C++

nosedive25 picture nosedive25 · Jul 17, 2010 · Viewed 7k times · Source

I have messed around a few times by making a small assembly boot loader on a floppy disk and was wondering if it's possible to make a boot loader in c++ and if so where might I begin? For all I know im not sure it would even use int main().

Thanks for any help.

Answer

Matthew Slattery picture Matthew Slattery · Jul 18, 2010

If you're writing a boot loader, you're essentially starting from nothing: a small chunk of code is loaded into memory, and executed. You can write the majority of your boot loader in C++, but you will need to bootstrap your own C++ runtime environment first.

Assembly is really the only option for the first stage, as you need to set up a sensible environment for running anything higher-level. Doing enough to run C code is fairly straightforward -- you need:

  • code and data loaded in the right place;
  • there may be an additional part of the data area which must be zero-initialised;
  • you need to point the stack pointer at a suitable area of memory for the stack.

Then you can jump into the code at an appropriate point (e.g. main()) and expect that the basic language features will work. (It's possible that any features of the standard library that may have been implemented or linked in might require additional initialisation at this stage.)

Getting a suitable environment going for C++ requires more effort, as it needs more initialisation here, and also has core language features which require runtime support (again, this is before considering library features). These include:

  • running static constructors;
  • memory allocation to support new and delete;
  • support for run-time type information (RTTI);
  • support for exceptions;
  • probably some other things I've forgotten to mention.

None of these are required until the C environment is up and running, so the code that handles these can be written in C rather than assembler (or even in a subset of C++ that does not make use of the above features).

(The same principles apply in embedded systems, and it's not uncommon for such systems to make use of C++, but only in a limited way -- e.g. no exceptions and/or RTTI because the runtime support isn't implemented.)