Running Assembly Code Directly on a Laptop Without an Operating System

Abstract: This article solves the problem of executing assembly code directly on hardware by providing a guide to writing a 512-byte bare-metal bootloader for x86 systems.

Created: 2026-10-09 by

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.

  1. Assemble the code: nasm bootloader.asm -o bootloader.bin
  2. Create a 1.44MB floppy image filled with zeros: dd if=/dev/zero of=floppy.img bs=512 count=2880
  3. 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.

Latest News

How to Display Output of xterm Command in Terminal Screen using Cron

Resolve the inability to display xterm output in a terminal screen from cron by redirecting logs or using wall instead of insecure X11 workarounds.

Read More
Expose Local Server on VPS Preserving Real Client IPs (OS Level)

Resolve VPS logging showing only gateway IPs by configuring reverse proxies to forward real client addresses via X-Forwarded-For headers.

Read More
How to Clear Recent Files History in Linux without Deleting Actual Files?

Clear recent files history in Linux by deleting ~/.local/share/recently-used.xbel without removing the actual files.

Read More
Best HDD Copy Strategy: Manually Syncing and Rewriting Scratch

Resolve data drift between two 4TB hard drives by using rsync with the --delete flag to manually sync and rewrite scratch data for an exact mirror.

Read More
Understanding Bash Prompt Abbreviations: An Overview

Resolve repetitive typing errors by creating and persisting Bash aliases in the .bashrc file for improved command-line efficiency.

Read More
Free Tools and Methods to Log Real-Time Performance Details in Task Manager

Log real-time CPU and memory metrics to CSV files using Windows Performance Monitor Data Collector Sets to troubleshoot system slowness.

Read More
Contact Qatar Airways Customer Service: Phone Number, Help Center, and More

Resolve urgent Qatar Airways reservation issues like flight changes and baggage claims using the US phone number +1801-855-5905 or online self-service tools.

Read More
Windows 11: Alt Codes Displaying Wrong Characters - Solutions

Resolve Windows 11 Alt codes showing wrong characters by verifying the US keyboard layout and enabling Num Lock.

Read More
Run Programs with Elevated Privileges: A Comprehensive Guide

Eliminates the need to type sudo for frequent administrative tasks by configuring .bashrc aliases or functions.

Read More
Dynamically Changing Dates in Excel Formulas Using Cells

Eliminate manual date updates in Excel by using cell references to create dynamic formulas that automatically adjust calculations when input dates change.

Read More
Granting Edit Access to a Specific Excel Sheet in an Office 365 User Email ID-Based Login

Excel Online lacks native sheet-level permissions, so users must split workbooks or use worksheet protection to isolate edit access for specific tabs.

Read More
Creating Network Load on Local Wi-Fi from One PC

Generate sustained Wi-Fi bandwidth load from a single PC using a VM SFTP server to test router stability and throughput.

Read More
Changing the Default Editor for Batch Files in Windows 11's File Explorer

Resolve the issue of batch files opening in Notepad by changing the default editor to a preferred application like VS Code.

Read More
Gain WiFi Connection Minutes Before Losing it by Changing MAC Address

Bypass MAC address filtering to restore WiFi connectivity temporarily when a device is blocked by network administrators.

Read More
Photos Folders Turned Black: Troubleshooting Picture Applications on Windows

Resolve black screens in Windows Photos by resetting the app, updating graphics drivers, and repairing system files.

Read More
Troubleshooting High CPU Temperature Values: A Step-by-Step Guide

Resolve high CPU temperatures and thermal throttling by monitoring with Speedfan, cleaning dust from cooling components, and replacing degraded thermal paste.

Read More
Make cURL establish TLS connection with CA unknown

Resolve cURL TLS connection failures with unknown or self-signed certificates by using the --insecure flag to bypass CA validation.

Read More
Troubleshooting Incorrect Network Metrics Values in Grafana, Prometheus, InfluxDB, and Telegraf

Fix incorrect network metrics in Grafana, Prometheus, InfluxDB, and Telegraf by verifying interface selection, resolving unit mismatches, and handling counter resets.

Read More
Start Another Terminal Window (cmd.exe) Windows Repair/Troubleshoot

Provides step-by-step instructions to access the Windows Command Prompt via bootable media for advanced system repair and troubleshooting.

Read More
Thinkpad P1 Gen 6: Sudden Thunderbolt 3 Dock USB-C Charging Stopped Working

Resolve sudden Thunderbolt 3 dock USB-C charging and internet failure on ThinkPad P1 Gen 6 by updating firmware, resetting the dock, and adjusting power settings.

Read More
ASUS Windows 11 Laptop: Internet Connection Issue with Hotspot

Resolve ASUS Windows 11 laptop spinning wheel issue when connecting to mobile hotspot by resetting network stack, disabling IPv6, and adjusting power settings.

Read More
Developing iOS Project with Firebase: Logging in and Sending Push Notifications

Integrates Firebase to enable secure user authentication and push notifications in iOS applications.

Read More
Troubleshooting Bash Script with Suspected Issues of Spaces, Dashes, Filenames and Quoting

Resolve Bash script failures caused by word splitting, globbing, and special characters in filenames by applying proper quoting techniques.

Read More
Populating OneDrive Folder for Local Backup without Affecting Remote Files

Prevent OneDrive from deleting remote files during Windows reinstallation by unlinking the account or using symbolic links to isolate local data.

Read More
Force First Frame as Keyframe Without Re-encoding: A Quick Solution

Resolve inaccurate seeking and playback glitches by re-encoding video to ensure the first frame is a valid keyframe.

Read More
Find Information in Database Using WSL (Ubuntu) on Windows-10

Resolve database connection issues from WSL Ubuntu on Windows 10 by configuring client tools and network access to query remote or local servers.

Read More
Configuring a New Router with Different Networks: One Family, One Guest

Resolve IP conflicts and isolate guest traffic by configuring a second router with a distinct subnet via its WAN port.

Read More
Quickly Open Multiple Stock Websites with a Single Command

Solve the problem of manually opening multiple stock research websites by creating a single command to launch them simultaneously on Windows, macOS, or Linux.

Read More
Improved Adobe Acrobat Search Experience: Access Advanced Search with Ease

Access advanced search filters like case sensitivity and regex in Adobe Acrobat by clicking More Options in the Find bar.

Read More
Port Forwarding VM via OpenVPN: A Comprehensive Guide

Configure OpenVPN server and iptables to forward specific ports from VPN clients to a virtual machine's internal IP address.

Read More
Understanding Partitions in the 1980s: A Look Back at MS-DOS and Master Boot Record

Explains how the Master Boot Record and partition table enabled MS-DOS to manage multiple disk volumes on a single physical drive.

Read More
Windows 10 Enterprise: Keyboard Not Detected in Managed Organization with Admin Privileges

Resolve Windows 10 Enterprise keyboard detection failures caused by Group Policy restrictions, driver corruption, or USB enumeration errors.

Read More
Can't Find x86_64 Versions of Applications on MacOS arm64 (M1)

Resolve missing x86_64 app issues on M1 Macs by installing Rosetta 2 and reinstalling apps as universal binaries.

Read More
How to Hide Installation Source for an Android App

Manage Android app installation source visibility by using USB transfers or file managers to reduce browser traces and isolate data via work profiles.

Read More
Connecting Momentus 4200.2 ST9808210A Hard Drive via USB Cable

Resolve inability to access Seagate Momentus 4200.2 ST9808210A hard drive by connecting it via USB using a compatible SATA-to-USB adapter and configuring the disk in Windows.

Read More