writing boot loader with gas in at&t x86 assembly
DESCRIPTION
Writing Boot Loader with GAS in AT&T X86 Assembly. Dennis Chen. Outline. Introduction Conceptual Flow Prerequisites Implementation Debugging Techniques Demo. Introduction. Scope Load file from floppy image of FAT12 format Execute in real mode No 32-bit addressing - PowerPoint PPT PresentationTRANSCRIPT
Writing Boot Loader with Writing Boot Loader with GAS in AT&T X86 GAS in AT&T X86
AssemblyAssemblyDennis ChenDennis Chen
OutlineOutline► IntroductionIntroduction
Conceptual FlowConceptual Flow PrerequisitesPrerequisites
► ImplementationImplementation►Debugging TechniquesDebugging Techniques►DemoDemo
IntroductionIntroduction► ScopeScope
Load file from floppy image of FAT12 formatLoad file from floppy image of FAT12 format Execute in real modeExecute in real mode
►No 32-bit addressingNo 32-bit addressing►No protected mode enabledNo protected mode enabled
►GoalGoal Use minimal tools available on LinuxUse minimal tools available on Linux Require no root privilegesRequire no root privileges Modulize as possible as it canModulize as possible as it can
►Kept in small footprint (of 512 bytes)Kept in small footprint (of 512 bytes)
IntroductionIntroduction►Development EnvironmentDevelopment Environment
Ubuntu 10.10 LTSUbuntu 10.10 LTS Vim + xxdVim + xxd gmake + binutilsgmake + binutils
►as, ld, objcopy, objdumpas, ld, objcopy, objdump gdbgdb
Conceptual FlowConceptual Flow► 1. BIOS finds the bootable disk1. BIOS finds the bootable disk► 2. BIOS loads boot loader:2. BIOS loads boot loader:
from the first sector (512 bytes) of the diskfrom the first sector (512 bytes) of the disk to logical address 0000:7c00hto logical address 0000:7c00h
► 3. Jump to the start of boot loader (0000:7c00h)3. Jump to the start of boot loader (0000:7c00h)► 4. Boot loader loads FAT and root directory in memory4. Boot loader loads FAT and root directory in memory► 5. Boot loader finds specific name 5. Boot loader finds specific name ““kernel.binkernel.bin””
by looking up root directoryby looking up root directory for the first cluster# if itfor the first cluster# if it’’s availables available
► 6. Boot loader loads first cluster of 6. Boot loader loads first cluster of ““kernel.binkernel.bin”” in memory in memory e.g., 0050:0000h or 9000:0100he.g., 0050:0000h or 9000:0100h
► 7. Boot loader queries FAT entry7. Boot loader queries FAT entry to get the next cluster#to get the next cluster# Go to step 6 if itGo to step 6 if it’’s available; otherwise, go to step 8.s available; otherwise, go to step 8.
► 8. Jump to the start of 8. Jump to the start of ““kernel.binkernel.bin”” in memory in memory e.g., 0050:0000h or 9000:0100he.g., 0050:0000h or 9000:0100h
PrerequisitesPrerequisites► X86 Assembly LanguageX86 Assembly Language
AT&T Syntax: GASAT&T Syntax: GAS Intel Syntax: MASM, NASMIntel Syntax: MASM, NASM
► Addressing in Real ModeAddressing in Real Mode X86 Memory LayoutX86 Memory Layout
► Locating Data in FloppyLocating Data in Floppy LBA vs. CHSLBA vs. CHS FAT12 SpecificationFAT12 Specification
► ToolsTools Binutils: as, ld, objdump, objcopyBinutils: as, ld, objdump, objcopy Emulator: qemu or bochsEmulator: qemu or bochs Debugger: gdbDebugger: gdb
X86 Assembly LanguageX86 Assembly Language► Examples:Examples:
AT&T SyntaxAT&T Syntax►mov %ax, %bxmov %ax, %bx►mov $0x1234, %axmov $0x1234, %ax►movw (%bx), %axmovw (%bx), %ax
Intel SyntaxIntel Syntax►mov bx, axmov bx, ax►mov ax, 1234hmov ax, 1234h►mov ax, word ptr [bx]mov ax, word ptr [bx]
Addressing in Real ModeAddressing in Real Mode► Logical AddressLogical Address
Syntax: <segment>:<offset>Syntax: <segment>:<offset> Range: 1 MiB (2Range: 1 MiB (22020)) e.g., 0000:7c00h = 07c0:0000he.g., 0000:7c00h = 07c0:0000h
► Linear AddressLinear Address Translation from Logical AddressTranslation from Logical Address
►<segment> * 16 + <offset><segment> * 16 + <offset> e.g., 9000:0100h = 90100he.g., 9000:0100h = 90100h
X86 Memory LayoutX86 Memory Layout► Low Memory Area (<=1 MiB)Low Memory Area (<=1 MiB)
Start End Size Type Description
0x00000000 0x000003FF 1 KiB RAM (SYS) Real Mode IVT (Interrupt Vector Table)
0x00000400 0x000004FF 256 Bytes RAM (BIOS) BDA (BIOS Data Area)
0x00000500 0x00007BFF ~30 KiB RAM Conventional Memory
0x00007C00 0x00007DFF 512 Bytes RAM (SYS) OS Boot Sector
0x00007E00 0x0007FFFF 480.5 KiB RAM Conventional Memory
0x00080000 0x0009FBFF ~120 KiB RAM Conventional Memory (if it exists)
0x0009FC00 0x0009FFFF 1 KiB RAM (BIOS) EBDA (Extended BIOS Data Area)
0x000A0000 0x000AFFFF 64 KiB RAM (VIDEO) Video RAM for VGA Graphics Mode
0x000B0000 0x000B7FFF 32 KiB RAM (VIDEO) Video RAM for Monochrome Text Mode
0x000B8000 0x000BFFFF 32 KiB RAM (VIDEO) Video RAM for Color Text Mode
0x000C0000 0x000C7FFF 32 KiB ROM (VIDEO) Standard Video ROM
0x000C8000 0x000EFFFF 160 KiB ROM (HW) Mapped Hardware
0x000F0000 0x000FFFFD ~64 KiB ROM (BIOS) BIOS
0x000FFFFE 0x000FFFFF 2 Bytes ROM System Identification (Model/Submodel)
Units for Locating Disk DataUnits for Locating Disk Data► LBALBA
Logical Block AddressingLogical Block Addressing► CHSCHS
Cylinder-Head-SectorCylinder-Head-Sector► TrackTrack
Track #0 is located at outer most circleTrack #0 is located at outer most circle► CylinderCylinder
Same track# spanning plattersSame track# spanning platters► HeadHead
2 Heads for 3.52 Heads for 3.5”” 1.44 Floppy 1.44 Floppy► SectorSector
#1#1 to #63 (26 - 1) to #63 (26 - 1) Off-by-one defect in BIOSOff-by-one defect in BIOS 512 bytes per sector as regularly used512 bytes per sector as regularly used
► ClusterCluster A set of sectorsA set of sectors
FAT12 SpecificationFAT12 Specification► Boot Sector FormatBoot Sector Format► Root DirectoryRoot Directory► FAT12 EntryFAT12 Entry
Boot Sector
FAT #1
FAT #2
Root Directory
Data
Boot Sector FormatBoot Sector Formatjmp start (0x003d)
BPB (BIOS Parameter Block)
start: (0x0040 – 3)
Boot Code
End of Boot Sector (0xaa55)
Boot Sector FormatBoot Sector Format► Byte 0x000~0x002Byte 0x000~0x002
jmp startjmp start►eb xx 90eb xx 90
Short jump with small offset (-128 ~127)Short jump with small offset (-128 ~127) Padded with NOP (0x90)Padded with NOP (0x90)
►e9 xx xxe9 xx xx Short jump with offset (-32768 ~ 32767)Short jump with offset (-32768 ~ 32767)
► Byte 0x003~0x03dByte 0x003~0x03d BPB (BIOS Parameter Block)BPB (BIOS Parameter Block)
Boot Sector FormatBoot Sector Format► BPB (BIOS Parameter Block) for FAT12BPB (BIOS Parameter Block) for FAT12
Offset
Size Name Default Value Description
0 3 jmp start(nop)
e9 <offset_16>eb <offset_8> 90
3 8 BS_OEMName "MSWIN4.1" OEM name (use MSWIN4.1 for compatibility)11 2 BPB_BytsPerSe
c512 Bytes per sector (possible values are 512, 1024, 2048, and 4096)
13 1 BPB_SecPerClus
1 Sectors per cluster (n^2: 1, 2, 4, 8, 16, 32, 64, and 128)
14 2 BPB_RsvdSecCnt
1 Reserved sector count (1 for FAT12/FAT16, 32 for FAT32)
16 1 BPB_NumFATs 2 Number of FATs17 2 BPB_RootEntCn
t224 Root entry count (512 for FAT16, 0 for FAT32)
19 2 BPB_TotSec16 2880 Total sectors.21 1 BPB_Media 0xf0 0xf0 for removal media, 0xf8 for fixed media (available values: 0xf0 - 0xff)22 2 BPB_FATSz16 9 Sectors per FAT (16-bit) for FAT12/FAT16. 0 for FAT32.24 2 BPB_SecPerTrk 18 Sectors per track26 2 BPB_NumHead
s2 Number of heads (2 for 1.44 MB 3.5-inch floppy)
28 4 BPB_HiddSec 0 Hidden sectors (0 for non-partitioned media)32 4 BPB_TotSec32 0 Total sector (32-bit) (BPB_TotSec32 >= 0x10000 when BPB_TotSec16 == 0)36 1 BS_DrvNum 0 Drive number (0x00 for FDD, 0x80 for HDD)37 1 BS_Reserved1 0 Reserved (used by WindowsNT) (= 0)38 1 BS_BootSig 0x29 Boot signature (= 0x29) indicating the following 3 fields are present.39 4 BS_VolID Any integer
numberVolume serial number. (It is usually assigned with timestamp.)
43 11 BS_VolLab “NO NAME “ Volume label (11 bytes = 8 + 3). It's likely to use "NO NAME " by default.54 8 BS_FileSysTyp
e“FAT12 “ File system type: "FAT12 ", "FAT16 ", or "FAT "
Boot Sector FormatBoot Sector Format► Byte 0x03e~0x1fdByte 0x03e~0x1fd
Boot codeBoot code Maximum size: 448 bytesMaximum size: 448 bytes
► Byte 0x1fe~0x1ffByte 0x1fe~0x1ff Signature for end of boot codeSignature for end of boot code 0x55, 0xaa (= 0xaa55)0x55, 0xaa (= 0xaa55)
Root Root DirectoryDirectory►32 bytes per entry32 bytes per entry►Short file name entryShort file name entry►Long file name entryLong file name entry
0002600: 416b 0065 0072 006e 0065 000f 00da 6c00 Ak.e.r.n.e....l.0002610: 2e00 6200 6900 6e00 0000 0000 ffff ffff ..b.i.n.........
0002620: 4b45 524e 454c 2020 4249 4e20 1800 b355 KERNEL BIN ...U0002630: 253f 253f 0000 b355 253f 0200 8504 0000 %?%?...U%?......
Entry for long file name
Entry for short file name
Root DirectoryRoot DirectoryOffset
Size Description
0 11 8.3 file name11 1 Attributes of the file.
R (0x01), H (0X02), S (0x04), VOL (0x08), D (0x10), A (0x20)Never be 0x0F, which indicates the long file name entries
12 1 Reserved for use by Windows NT13 1 Creation time in tenths of a second14 2 Creation time (Hour: 5 bits, Minute: 6 bits, Second: 5
bits)16 2 Creation date (Year: 7 bits, Month: 4 bits, Day: 5 bits)18 2 Last accessed date, referred to the format of creation
date20 2 High 16-bit of the first cluster# of this entry (always 0
for FAT12)22 2 Last modification time, referred to the format of creation
time24 2 Last modification date, referred to the format of creation
date26 2 Low 16-bit of the first cluster# of this entry28 4 Size of the file in bytes
FAT12 EntryFAT12 Entry►Every FAT entryEvery FAT entry
occupies 12 bits of a word (2 bytes)occupies 12 bits of a word (2 bytes)
can be indexed by current cluster#can be indexed by current cluster# contains the next cluster# or EOCcontains the next cluster# or EOC byte offset# = (cluster# - 2) * 3 / 2byte offset# = (cluster# - 2) * 3 / 2 even_or_odd = (cluster# - 2) * 3 % 2even_or_odd = (cluster# - 2) * 3 % 2
►FAT Entry (even) = [Byte 0-1] & 0x0fffFAT Entry (even) = [Byte 0-1] & 0x0fff►FAT Entry (odd) = [Byte 1-2] >> 4FAT Entry (odd) = [Byte 1-2] >> 4
0 1 2 3 4 5 6 7 8 9 A B 0 1 2 3 4 5 6 7 8 9 A B
Byte 0
Byte 1
Byte 2
FAT Entry (even)
FAT Entry (odd)
FAT12 EntryFAT12 Entry►Value of FAT entryValue of FAT entry
Value Description0x000 Free cluster0x001 Reserved0x002 ~ 0xFEF Used cluster, pointing to next cluster0xFF0 ~ 0xFF5 Reserved0xFF6 Reserved0xFF7 Bad sector in cluster or reserved cluster0xFF8 ~ 0xFFF Last cluster in file (EOC)
ImplementationImplementation►Boot codeBoot code
bpb.sbpb.s►BPB header and trailing signatureBPB header and trailing signature
boot.sboot.s►Main boot codeMain boot code
console.sconsole.s►Utility of Console printing using INT 10hUtility of Console printing using INT 10h
disk.sdisk.s►Utility of disk accessing using INT 13hUtility of disk accessing using INT 13h
kernel.skernel.s►Mock kernel for loadingMock kernel for loading
ImplementationImplementation►ScriptScript
boot.ldboot.ld
kernel.ldkernel.ld
SECTIONS { . = 0x7c00; .text : { .begin = .; bpb.o (.text); boot.o (.text); * (.text); . = .begin + 510; bpb.o (.signature); }}
SECTIONS { . = 0x0000; .text : { kernel.o (.text) * (.text) }}
ImplementationImplementation►Generated TargetsGenerated Targets
boot.imgboot.img►Bootable disk imageBootable disk image
boot.binboot.bin►Bare boot codeBare boot code
boot.elfboot.elf►Boot code with ELF header and debug informationBoot code with ELF header and debug information
kernel.binkernel.bin►Bare kernel binaryBare kernel binary
kernel.elfkernel.elf►Kernel binary with ELF header and debug informationKernel binary with ELF header and debug information
Debugging TechniquesDebugging Techniques► INT 10h BIOS callINT 10h BIOS call
Print asciiz stringPrint asciiz string Print characterPrint character It requires further impl. to output numbersIt requires further impl. to output numbers
►Remote debugging with gdbRemote debugging with gdb Turn on debug symbol with -g option for as and ldTurn on debug symbol with -g option for as and ld Edit .gdbinit file:Edit .gdbinit file:
►target remote | exec qemu -gdb stdio -fda boot.imgtarget remote | exec qemu -gdb stdio -fda boot.img►symbol-file boot.elf kernel.elfsymbol-file boot.elf kernel.elf
Enter Enter ““gdbgdb”” at command line at command line
Debugging TechniquesDebugging Techniques►Launch QEMU directlyLaunch QEMU directly
Enter Enter ““qemu -fda boot.imgqemu -fda boot.img”” at command at command lineline
►Launch Bochs directlyLaunch Bochs directly Edit bochsrc.txt file:Edit bochsrc.txt file:
►boot: floppyboot: floppy►floppya: type=1_44, 1_44=floppya: type=1_44, 1_44=““boot.imgboot.img””, inserted, inserted
Enter Enter ““bochsbochs”” at command line at command line
ReferenceReference► OrangeOrange’’ss 一個作業系統的實現 一個作業系統的實現 (ISBN 978-986-7309-52-2)(ISBN 978-986-7309-52-2)► 使用开源软件自己动手写操作系统
http://code.google.com/p/writeos/downloads/list► X86 Memory MapX86 Memory Map
http://wiki.osdev.org/Memory_Map_(x86)http://wiki.osdev.org/Memory_Map_(x86)► Disk ManipulationDisk Manipulation
http://en.wikipedia.org/wiki/INT_13Hhttp://en.wikipedia.org/wiki/INT_13H http://zh.wikipedia.org/wiki/LBAhttp://zh.wikipedia.org/wiki/LBA http://en.wikipedia.org/wiki/Cylinder-head-sectorhttp://en.wikipedia.org/wiki/Cylinder-head-sector
► Boot Sector & FATBoot Sector & FAT http://wiki.osdev.org/MBRhttp://wiki.osdev.org/MBR http://wiki.osdev.org/FAThttp://wiki.osdev.org/FAT http://en.wikipedia.org/wiki/File_Allocation_Tablehttp://en.wikipedia.org/wiki/File_Allocation_Table http://www.microsoft.com/whdc/system/platform/firmware/http://www.microsoft.com/whdc/system/platform/firmware/
fatgen.mspxfatgen.mspx