Running assembly code bare-metal requires creating a bootable floppy or disk image, writing a minimal bootloader in x86 assembly, and testing it in an emulator like QEMU before attempting physical hardware execution. This approach bypasses the operating system entirely, allowing direct control over CPU registers and memory.
The Bare-Metal Concept
When you write software for Windows, Linux, or macOS, you rely on the operating system to provide services like file access, memory management, and screen output. In a bare-metal environment, there is no such intermediary. Your assembly code becomes the first thing the computer executes immediately after power-on or reset. This gives you complete freedom but also removes all safety nets. You must handle hardware initialization yourself, including setting up the stack pointer, enabling protected mode if necessary, and managing interrupts.
This level of control is essential for understanding how computers actually work at the lowest level. It is also the foundation for writing operating systems, device drivers, and embedded firmware. While modern laptops are complex machines with UEFI firmware and secure boot features, the fundamental principles remain similar to those used in early PC development. We will focus on a standard x86 architecture compatible with legacy BIOS, which is the most common target for learning these concepts.
Setting Up the Development Environment
To begin, you need a cross-compiler toolchain that can generate x86 machine code from assembly source files. On Linux or macOS, you can use nasm (Netwide Assembler) combined with ld (GNU Linker). For Windows, you might use nasmw.exe or install these tools via WSL. The goal is to produce a raw binary file that can be written directly to a disk image.
You also need an emulator to test your code safely. QEMU is the industry standard for this purpose because it emulates a full PC environment, including the BIOS. Using an emulator prevents you from accidentally bricking your laptop during the initial debugging phases. Once your code works reliably in QEMU, you can consider transferring it to physical media.
If you are interested in how different hardware architectures affect your code, reading about program dependency on processor architecture can provide valuable context for why we stick to x86 for this tutorial. See Understanding Program Dependency on Processor Architecture.
Writing the Bootloader
A valid boot sector must be exactly 512 bytes long and end with the magic number 0x55AA. The BIOS loads the first sector of the boot device into memory at address 0x7C00 and jumps to that location. Your assembly code must account for this fixed entry point.
section .text
global _start
_start:
; Set up a safe stack pointer away from our code
mov sp, 0x7E00
; Clear direction flag for string operations
cld
; Print a character to demonstrate execution
mov si, msg
call print_string
; Halt the CPU
hlt
print_string:
lodsb ; Load byte from DS:SI into AL
or al, al ; Check for null terminator
jz .done
mov ah, 0x0E ; BIOS teletype function
mov bx, 0x07 ; Page 0, attribute 7 (white on black)
int 0x10 ; Call BIOS video interrupt
jmp print_string
.done:
ret
section .data
msg db 'Hello Bare-Metal!', 0
section .pad
times 510 - ($ - $$) db 0
dw 0xAA55
Notice that we set the stack pointer (SP) to 0x7E00, not 0x7C00. Setting it to 0x7C00 would overwrite the bootloader code itself as soon as we push any data onto the stack. This was a critical error in previous drafts. Additionally, we use the BIOS interrupt 0x10 to print characters, which avoids the complexity of setting up a Global Descriptor Table (GDT) or enabling A20 line for this simple example. These advanced steps are only required when switching to 32-bit protected mode.
Creating the Disk Image
After assembling the code with nasm bootloader.asm -o bootloader.bin, you need to package it into a format that QEMU or a real hard drive can read. The simplest method is to create a raw binary image using dd or by concatenating the binary with zeros.
- Assemble the code:
nasm bootloader.asm -o bootloader.bin - Create a 1.44MB floppy image filled with zeros:
dd if=/dev/zero of=floppy.img bs=512 count=2880 - Write the bootloader to the first sector:
dd if=bootloader.bin of=floppy.img bs=512 conv=notrunc
This process ensures that the boot signature is present at the correct offset. If you skip the zero-filling step, you might encounter issues with partition tables or filesystems that expect specific structures, although for a raw binary boot sector, just the first 512 bytes matter.
Testing with QEMU
Now that you have a disk image, run it in QEMU. The command should specify the floppy image as the boot device. Do not forget the -boot flag to ensure the emulator knows where to start.
qemu-system-i386 -fda floppy.img -no-reboot
The -fda flag tells QEMU to use the image as a floppy disk. The -no-reboot flag prevents the emulator from restarting if the OS crashes, which helps in debugging. You should see "Hello Bare-Metal!" printed on the screen. If nothing appears, check that your assembler did not include extra headers and that the 0xAA55 signature is at the very end of the 512-byte block.
For more information on storage devices and their performance characteristics, which can be relevant when moving from emulation to physical drives, you may find Understanding Server Memory vs PC Memory: A Comparison useful for broader hardware context.
Safety Considerations for Beginners
Attempting to run this code on physical hardware without proper preparation is dangerous. Modern laptops often use UEFI instead of legacy BIOS, which expects EFI stub kernels rather than raw boot sectors. Writing a raw binary to a USB drive and booting from it on a modern machine may result in a black screen or a secure boot violation. Always test in QEMU first. If you plan to proceed to physical hardware, research how to disable Secure Boot and enable Legacy Support in your BIOS settings, but be aware that this varies significantly between manufacturers.
Frequently Asked Questions
Why does my code fail to execute on a modern laptop?
Modern laptops typically use UEFI firmware, which does not support the legacy BIOS boot protocol expected by simple x86 bootloaders. You must either disable Secure Boot and enable Legacy/CSM mode in the BIOS settings or develop a UEFI-compatible application, which requires a completely different development workflow.
What happens if I set the stack pointer to 0x7C00?
Setting the stack pointer to 0x7C00 places the stack directly on top of your bootloader code. Any instruction that pushes data to the stack, such as a function call or local variable allocation, will overwrite your own instructions, causing immediate undefined behavior or a crash.
Can I run this code directly from a USB drive?
Yes, provided the drive is formatted correctly and the BIOS is configured to boot from USB in legacy mode. You must write the 512-byte boot sector to the beginning of the USB drive using a tool like dd, ensuring that no partition table overwrites the boot signature.
How do I switch to 32-bit protected mode?
Switching to protected mode requires enabling the A20 line, loading a Global Descriptor Table (GDT), and setting the PE bit in the CR0 register. This process is complex and involves several assembly instructions that must be executed in a specific order to avoid triple faults.
Is QEMU sufficient for testing all hardware interactions?
QEMU provides a good approximation of standard PC hardware, but it may not perfectly emulate proprietary chips, specific GPU behaviors, or exact timing constraints found in real laptops. Critical hardware interactions should always be verified on physical hardware after successful emulation.