Make it run

A file prog.elf, containing executable code which is generated as described in Section From source to binary, from source code as shown in Figure 1 and from assembly code as shown in Figure 2, can be executed from a bootable media.

A bootable media, in the form of a bootable USB stick, can be created. It is possible to do this, for example, by following instructions on how to create a bootable USB stick with GRUB.

Assuming that a bootable USB stick has been created, the file prog.elf can be copied to the USB stick. This can be done by first inserting the USB stick into a computer, and then giving the command

cp prog.elf /media/ola/EC25-4633/boot/kernel.bin

The above command copies the file prog.elf to a directory named boot, while at the same time renaming the file to kernel.bin. The reason for renaming the file is that the name kernel.bin has been given in the startup file for GRUB, as the name of the file where the program to be started is located.

In a larger example, a file, corresponding to the file kernel.bin used here, may contain an operating system, e.g. a Linux kernel.

The program can now be executed by starting the computer, after having ensured that the computer will boot from the USB stick.

A successful start is indicated by the string, as specified in the source code in Figure 1, being printed. An example of a successful start is shown in Figure 4.

Figure 4. Screenshot of a computer after boot and start of a bare metal C program. The screenshot in Figure 4 indicates that the call to the function console_put_string in Figure 1 works as intended.

It can be noted that the program cannot be stopped. However, the computer can be reset, and the boot procedure can then be repeated.

The program in Figure 1, combined in the same way as shown above with assembly code from Figure 2, can be executed in a simulator. The simulator QEMU can be used. Instructions for installing QEMU can be found in this article.

The program is compiled and linked as described in Section From source to binary. The program can be loaded, and started, using the QEMU command

qemu-system-x86_64 -kernel prog.elf

The above command starts the QEMU simulator. The name prog.elf is given as an argument to the command. The argument -kernel is also given, which means that the program is stored at a predefined address in the simulated computer, and then executed from that adress. As a result, a window showing the screen of the simulated computer is shown, including a printout of the text

Hello from a bare metal C-program!

which shows that the call to the function console_put_string in Figure 1 works as intended.

  • Intel-x86
  • ARM