0% found this document useful (0 votes)
202 views

Boot Sector Programming

This document provides an overview of boot sector programming. It discusses how the BIOS loads the boot sector program and describes some key tasks a basic boot sector program performs, such as enabling A20 line and entering protected mode. It also lists the tools needed - NASM assembler to compile assembly programs and Bochs emulator to test boot sectors without rebooting. A simple example boot sector that hangs the system is provided, as well as a slightly more advanced boot sector that loads a small kernel into memory.

Uploaded by

Andrej Radulovic
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
202 views

Boot Sector Programming

This document provides an overview of boot sector programming. It discusses how the BIOS loads the boot sector program and describes some key tasks a basic boot sector program performs, such as enabling A20 line and entering protected mode. It also lists the tools needed - NASM assembler to compile assembly programs and Bochs emulator to test boot sectors without rebooting. A simple example boot sector that hangs the system is provided, as well as a slightly more advanced boot sector that loads a small kernel into memory.

Uploaded by

Andrej Radulovic
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

See discussions, stats, and author profiles for this publication at: https://www.researchgate.

net/publication/236619512

Boot Sector Programming

Article · July 2007

CITATIONS READS
0 5,945

1 author:

Budhaditya Majumdar
Robo Helix
29 PUBLICATIONS   47 CITATIONS   

SEE PROFILE

Some of the authors of this publication are also working on these related projects:

3D Printed Submarine View project

Design and Modelling of Tunnel FET based bio-sensors and gas-sensors View project

All content following this page was uploaded by Budhaditya Majumdar on 01 July 2015.

The user has requested enhancement of the downloaded file.


SOFTWARE
SECTION

BOOT SECTOR SANI TH


EO

PROGRAMMING
 BUDHADITYA MAJUMDAR order to restore the lost data. All of 4. Setting up an extremely simple
these applications demand the knowl- interrupt table (IDT for kernel-based

T
wo methods have been pre- edge of the bootstrap, i.e., how a com- interrupts).
sented here to boot your PC puter functions when PC is switched 5. Initialising a 32bit stack (Pro-
using ‘Assembly’ and ‘C’ pro- on. tected mode requires a 32bit address-
grams, respectively. A word of cau- At the completion of your system’s able stack).
tion though: Tampering with the boot POST, INT 0x13 is called. Usually INT 6. Jumping to the address that con-
sector program of a computer can ren- 0x13 tries to read a boot sector pro- tains the loaded data. This runs the
der the machine inoperable. So it is gram from the first floppy drive. If a data.
advised to test the programs using boot sector program is found on the
floppy disks or non-critical hard drives floppy disk, the boot sector program Getting started!
prior to transferring your boot sector is read into memory at location The boot sector programs presented
program onto a live system. ‘0000:7C00’ and INT 0x13 jumps to here are not OS loaders, but programs
The bootstrap or bootloader is a memory location ‘0000:7C00.’ How- that show the working on bootloaders.
small program loaded by the BIOS ever, if no boot sector program is Writing your own boot sector program
(Basic Input Output System) upon found on the first floppy drive, INT is probably actually easier than you
system startup. The BIOS loads the 0x13 tries to read the MBR from the think. All you really need to know is
bootstrap from a known location first hard drive. how the Intel processor boots up.
and transfers control. It is the If an MBR is found it is read into A valid boot sector program has
bootstrap’s responsibility to load code memory at location ‘0000:7C00’ and a ‘Boot Signature.’ When the BIOS
and build an appropriate operating INT 0x13 jumps to memory location checks the first sector of the disks, it
environment. ‘0000:7C00.’ The small program in looks for a specific signature denot-
The bootloader program is stored the MBR will attempt to locate an ing a valid boot sector. This signa-
in the very first sector of a bootable active (bootable) partition in its par- ture is ‘0AA55h’ located at the offset
device. For example, the first sector of tition table. If such a partition is 1FEh (or 510 dec). So to make a valid
the floppy disk drive would be where found, the boot sector program of boot sector program, you must make
you would put the code of the that partition is read into memory at sure that it is 512-byte long and
bootloader. This sector is known as the location ‘0000:7C00’ and the MBR ‘0AA55h’ is present at the offset 510
‘boot sector.’ The boot sector program program jumps to memory location and located in the very first sector of
is read by the system and loaded into ‘0000:7C00.’ the disk.
memory at ‘0x0:0x7C0’ after the Each operating system has its own The BIOS simply checks drive ‘0’
power-on self-test (POST). boot sector program format. The small (floppy drive ‘A:’) for this code. If not
There are many reasons for writ- program in the boot sector program found, it then checks drive ‘128’ (hard
ing a custom bootstrap program. First must locate the first part of the oper- disk ‘C:’). If a valid boot sector pro-
of all, it helps to understand how a ating system’s kernel loader program gram is found, it is loaded into
computer operates in its rawest form. (or perhaps the kernel itself or a boot the memory at address location
Second, programmers who want to manager program) and read that into 0000:7C00h. So, all you have to do
write their own operating systems will the memory. is write a boot sector program, as-
generally utilise custom bootstrap code A few things which the boot sector semble it into a plain binary file (there
to load and initialise their system. program does are: is no format or header to a boot sec-
Utilities that allow users to select dif- 1. Enabling the A20 line. This al- tor) and write it to the first sector of
ferent operating systems to run at boot lows access to ‘full’ memory space. your disk.
time require a fundamental knowledge 2. Entering Protected mode. This
of the computer boot sequence. Data allows 32-bit addressing for x86-com- Tools required for the
recovery service providers performing patible systems. basic task
digital forensics must understand dif- 3. Setting up basic memory protec- 1. The Assembly programs are com-
ferent boot sector program formats in tion (called GDT). piled using NASM (Netwide assem-

100 • JULY 2007 • ELECTRONICS FOR YOU WWW.EFYMAG.COM


SOFTWARE
SECTION
bler). It is freely available at ‘http:// ; HANG.ASM tor program that boots and loads a
nasm.sourceforge.net/ .’ The Netwide ; A minimal boot sector program small kernel into memory and hands
assembler produces plain binary files hang: ; Hang! over the control to the kernel is:
which are used to boot the system. jmp hang
times 510-($-$$) db 0 ; Fill the file with 0’s ; BOOT.ASM
2. A very interesting tool that can dw 0AA55h ; End the file with AA55 ; Load a program off the disk and jump to
be used is ‘Bochs’ to test your boot it
disk or boot sectors without rebooting The line starting with ‘times’ is a ; Tell the compiler that this is offset 0.
command that only NASM under- ; It isn’t offset 0, but it will be after the
your machine. Bochs is a highly por- jump.
table, open-source IA-32 (x86) PC emu- stands. The line will insert 0’s until the
[ORG 0]
lator written in ‘C++’ that runs on most file size is 510 bytes. The whole file jmp 07C0h:start ; Goto segment 07C0
popular platforms. It includes emula- will therefore be 512 bytes. The last start:
instruction puts ‘AA55’ at the end of ; Update the segment registers
tion of the Intel x86 CPU, common I/ mov ax, cs
O devices and a custom BIOS. Bochs the file (boot signature). mov ds, ax
is capable of running most operating NASM supports two special tokens mov es, ax
in expressions—the $ and $$ tokens— reset: ; Reset the floppy drive
systems inside the emulation includ- mov ax, 0 ;
ing Linux, DOS, Windows 95/98 and allowing calculations to involve the
mov dl, 0 ; Drive=0 (=A)
Windows NT/2000/XP. Details of current assembly position. ‘$’ evalu- int 13h ;
Bochs and configuration will be dis- ates the assembly position at the be- jc reset ; ERROR => reset again
ginning of the line containing the ex- read:
cussed later. mov ax, 1000h ; ES:BX = 1000:0000
3. If you are going to use a pression, so you can code an infinite mov es, ax ;
DOS-based ‘boot.exe’ file, you loop using JMP $. ‘$$’ evaluates the mov bx, 0 ;
need a program that will strip the beginning of the current section, so mov ah, 2 ; Load disk data to ES:BX
you can tell how far into the section mov al, 5 ; Load 5 sectors
first 512 bytes from the .exe file as mov ch, 0 ; Cylinder=0
the header file in ‘.exe’ is not required. you are by using ‘($-$$).’ mov cl, 2 ; Sector=2
C programs (strip_head.c and Convert this ‘.asm’ file into ‘.bin’ mov dh, 0 ; Head=0
file as follows: mov dl, 0 ; Drive=0
write_sector_1.c) have been used int 13h ; Read!
here to do this job. These programs nasm -f bin hang.asm -o hang.bin
Jc read ; ERROR => Try again
can be compiled using ‘Turbo C 2.0,’ The ‘-f bin’ specifies the format to jmp 1000h:0000 ; Jump to the program
‘Turbo C++ 3.0’ or DJGPP. DJGPP is plain binary. Now write the ‘hang.bin’ times 510-($-$$) db 0
to the first sector of a floppy and reboot dw 0AA55h
the Win32 port of GCC Compiler,
which can be downloaded for free the system with the floppy to see a The boot sector program will read
from the website ‘www.delorie.com/ hang. the floppy and copy five sectors start-
djgpp/.’ Example 2 (hello.asm). The code to ing from sector 2 to the memory loca-
Note. If you are not familiar with print “Hello, World!” is: tion 1000:0000 (segment:offset). To
NASM, please visit ‘http:// ; Tell the compiler that this is offset 0. achieve this, boot sector program uses
nasm.sourceforge.net/doc/html/ ; It isn’t offset 0, but it will be after the BIOS interrupt 13h.
nasmdoc0.html’ for NASM manual jump. ‘prog.asm’ is a small loadable pro-
[ORG 0]
and go through Chapter 3 (The NASM gram that prints ten “=”:
jmp 07C0h:start ; Goto segment 07C0
Language) and Chapter 5 (Assembler ; Declare the string that will be printed ; PROG.ASM
Directives). Warnings messages can be msg db “Hello World!”, 10,13,0 ;Decimal mov ah, 9
10 is Line Feed , 13 is Carriage Return mov al, ‘=’
ignored while compiling ‘C’ programs. start: mov bx, 7
; Update the segment registers mov cx, 10
Boot sector program in mov ax, cs int 10h
Assembly language mov ds, ax hang:
mov es, ax jmp hang
The things to be kept in mind while mov si, msg ; SI =address of msg
programming are: print: The image.asm program creates a
1. The BIOS will load your boot- lodsb ; AL=memory contents at DS:SI, SI disk image file that contains both the
is incremented
strap to address ’07C00h.’ bootstrap and the small loadable pro-
cmp al, 0 ; If AL=0 then hang
2. Bootstraps must be compiled as je hang gram:
plain binary files. mov ah, 0Eh ; Print AL
; IMAGE.ASM
3. The file size for the plain binary mov bx, 7
; Disk image
int 10h
file must be 512 bytes. jmp print ; Print next character
%include ‘boot.asm’
4. The file must end with ‘AA55h’ %include ‘prog.asm’
hang: ; Hang!
(boot signature). Jmp hang ‘image.asm,’ when compiled,
Example 1 (hang.asm). A minimal times 510-($-$$) db 0
places both the programs simulta-
dw 0AA55h
boot-sector code to halt or hang the neously, so you can read the prog.asm
system after booting is: Example 3 (boot.asm). A boot sec- code from sector 2.

102 • JULY 2007 • ELECTRONICS FOR YOU WWW.EFYMAG.COM


SOFTWARE
SECTION
You can convert these programs ; | (currently 2.5 kb, mov si, msg2 ;
into binary files using NASM as “ ; | 5 sectors are call _print ; Print “”=============”
nasm –f bin image.asm –o image.bin.” ; | loaded from mov si, crlf
; | floppy) call _print ; Carriage Return, Line Feed
Copy all the binary files into a com- ; ——————————————— ;Looping of Kernel
mon folder and run using Bochs as de- _loop:
scribed below. ; Load a program off the disk and jump to mov si, msg3
Install Bochs and make a folder un- it call _print ;Print the prompt “”Prompt$ “”
; Tell the compiler that this is offset 0. mov di, arr ; DI= address of arr
der the parent directory of Bochs. ; It isn’t offset 0, but it will be after the mov cx, 25 ; max input characters = 25
Choose the folder name as ‘boot.’ Now jump. call _scan ; Input from Keyboard
copy the following code to a text file [ORG 0] mov si, arr ; SI = address of arr
jmp 07C0h:start ; Goto segment 07C0 call _print ; Print again the Input by user
and rename it to ‘bochsrc.bxrc’: start: jmp _loop
# You may now use double quotes around ; Update the segment registers ;=============================
pathnames, in case mov ax, cs ; AX = Code Segment ;Procedures ..........
# the pathname include spaces. mov ds, ax ; Data Segment = AX ;Procedure PRINT to print a string.
Romimage: file=../BIOS-bochs-latest, mov es, ax ; Extra Segment = AX ;pointer of string should be placed in SI
address=0xf0000 mov ss, ax ; Stack Segment = AX _print:
vgaromimage: file=../VGABIOS-elpin-2.40 mov sp, 03feh ; Stack Pointer = 0x03FE cld ; Clear Direction Flag
megs: 32 reset: ; Reset the floppy drive _loopA:
floppya: 1_44=Image.bin, status=inserted mov ax, 0 ; lodsb ; AL=memory contents at DS:SI, SI
boot: a mov dl, 0 ; Drive=0 (=A) is incremented
log: bochsout.txt int 13h ; cmp al, 0 ; If AL=0 then end procedure
panic: action=ask jc reset ; ERROR => reset again je _end
error: action=report read: mov ah, 0Eh ; Print AL
info: action=report mov ax, 1000h ; ES:BX = 1000:0000 mov bx, 7
debug: action=ignore mov es, ax ; int 10h ; BIOS Interrupt 10h for Display
vga_update_interval: 300000 mov bx, 0 ; Services
keyboard_serial_delay: 250 mov ah, 2 ; Load disk data to ES:BX jmp _loopA ; Print next character
keyboard_paste_delay: 100000 mov al, 5 ; Load 5 sectors _end:
floppy_command_delay: 500 mov ch, 0 ; Cylinder=0 ret
ips: 1000000 mov cl, 2 ; Sector=2 ;Procedure PRINT End.
mouse: enabled=0 mov dh, 0 ; Head=0 ;Procedure SCAN to input a string. Pointer
private_colormap: enabled=0 mov dl, 0 ; Drive=0 to string should placed in DI
fullscreen: enabled=0 int 13h ; Read! ;number of characters to scan should be
screenmode: name=”sample” JJc read ; ERROR => Try again placed in CX
keyboard_mapping: enabled=0, map= jmp 1000h:0000 ; Jump to the program _scan:
#keyboard_type: at times 510-($-$$) db 0 cld ; Clear Direction Flag
dw 0AA55h _loopB:
In the above code, lines starting mov ah, 00h ; Function 00 for Keyboard
with ‘#’ mean that they are comment The kernel, after it gets control Character Input
lines. Change the name in line “ from the boot-sector program, waits int 16h ; BIOS Interrupt 16h for Keyboard
for input at the prompt, accepts simple Functions
floppya: 1_44=Image.bin, mov ah, 0Eh ; Display Character Function
status=inserted” if you have a differ- strings entered by the user and dis-
0E
ent file name. plays on the monitor screen. The code int 10h ; BIOS Interrupt 10h for Display
The image.bin and bochsrc.bxrc for the same (simplekernel.asm) fol- Services
lows: stosb ; ES:DI <- AL, DI Incremented
files must be stored in the same folder cmp al, 13 ; Check if ENTER is pressed
under the path ‘C:/Program Files/ [ORG 0] je _jm1 ; If ENTER pressed Goto _jm1
Bochs- 2.3.’ Double-click the mov ax, cs dec cx ; CX = CX – 1
mov ds, ax jnz _loopB ; Get next Input
bochsrc.bxrc file to run it and see how mov es, ax _jm1:
your first boot sector program works! jmp _start mov ah, 0Eh ; Display Character Function
Note. Example 3 was not tested at ;======================== 0E
;Data Section mov al, 10 ; ASCII value for Line Feed
EFY Lab.
msg db “”Simple Kernel”, 10, 13, 0 int 10h ; BIOS Interrupt 10h for Display
Example 4 (bootfinal.asm). An- msg2 db “”=============”, 10, 13, 0 Service, print LF
other code for booting the system from crlf db 10, 13, 0 mov ah, 0Eh ; Display Character Function
a floppy is as follows: msg3 db “”Prompt$ “”, 0 0E
arr db mov al, 13 ; ASCII value for Carriage Re-
; memory table (hex): “”ABCDEFGHIJKLMNOPQRSTUVWXYZ turn
; ——————————————— “”,10,13,0 int 10h ; BIOS Interrupt 10h for Display
; 07c0:0000 | boot sector ;arr has 30 bytes space in which max us- Service, print CR
; 07c0:01FF | (512 bytes) able is 27 mov al, 13
; ——————————————— ;last 3 should be 10, 13, 0 stosb ; Store into end of array CR, incre-
; 07c0:0200 | stack ;Data Section End ment DI
; 07c0:03FF | (255 words) ;============================== mov al, 10
; ——————————————— _start: stosb ; Store into end of array LF, incre-
; 1000:0000 | kernel mov si, msg ; SI =address of msg ment DI
; 1000:0A00 | call _print ; Print “”Simple Kernel” mov al, 0

WWW.EFYMAG.COM ELECTRONICS FOR YOU • JULY 2007 • 103


SOFTWARE
SECTION
no special format is provided, ‘exe’ is
generated. For example, ‘nasm
boot.asm –o boot.exe.’
Use ‘strip_head.exe’ in the follow-
ing way:
c:\>strip_head boot.exe boot.bin
header.bin
After execution, you will see
that you have two more files in the
folder: ‘boot.bin’ and ‘header.bin.’ Dis-
card ‘header.bin’ and use only
‘boot.bin.’ Note that the header.bin
file being stripped is 512 bytes long.
The program output is shown in
Screenshot 2.
The strip_head.c code follows:
/* strip_head.c
* Strips the header of an exe file. Creates
two files, one the stripped exe and the
other the header file.*/
Screenshot 1: Program output of example 4
# include <stdlib.h>
# include <conio.h>
stosb ; Store into end of array NULL, in- From the command mode, enter # include <stdio.h>
crement DI the following: int main(int argc,char *argv[])
ret {
nasm -f bin simplekernel.asm -o
; Procedure SCAN End /* The File Handles */
simplekernel.bin FILE *srcFile , *dstFile , *hdrFile;
This simple kernel reprints any image.bin unsigned char buffer[512];
string which the user types at the From the command mode, enter if(argc<=2)
{ printf(“\n%s <sourcefile(.exe)>
prompt. Two inbuilt functions ‘_print’ the following: <strippedfilename> <headerfile>”,argv[0]);
and ‘_scan’ are used by the kernel. copy/B bootfinal.bin/B + exit(0);
The ‘_print’ function prints char- simplekernel.bin/B image.bin/B }
acter by character using BIOS inter- Rename the file name at sixth line printf(“Opening source file %s”,argv[1]);
if((srcFile = fopen(argv[1],”rb”))==NULL)
rupt ’10h’ which has display functions. in ‘bochsrc.bxrc’ to ‘image.bin.’ Save { printf(“\nfatal-error: file (%s) not
The address of the memory, where the file and double-click to run it. found. exiting..”,argv[1]);
the string is stored, is copied into SI The program output is shown in exit(1);
}
register before the function call Screenshot 1. printf(“\nCreating destination files
(_print). %s.bin and header.bin”,argv[1]);
The ‘_scan’ function takes input Boot sector program in ‘C’ if((dstFile= fopen(argv[2],”wb”))==
character by character for a certain Let us take a DOS-based boot.exe pro- NULL)
{ printf(“\nfatal-error: output file
limit which is to be given in ‘CX’ reg- gram (compiled to ‘exe’ instead of (%s) could not be created.
ister. The address where the values are ‘bin’). ‘exe’ is the default format for exiting..”,argv[1]);
to be stored is to be copied into ‘DI’ any assembler including NASM. When
register.
In both the above cases, the Direc-
tion Flag should be ‘0’ so that both SI
and DI registers are incremented after
loading or storing the data, respec-
tively.
Testing steps. The programs should
be assembled individually and then
merged into a single binary file so that
it can be run with Bochs.
bootfinal.asm
From the command mode, enter
the following:
nasm -f bin bootfinal.asm -o
bootfinal.bin
simplekernel.asm Screenshot 2: Program output of strip_head.exe

104 • JULY 2007 • ELECTRONICS FOR YOU WWW.EFYMAG.COM


SOFTWARE
SECTION
exit(1);
}
if((hdrFile = fopen(argv[3],”wb”))==
NULL)
{ printf(“\nfatal-error : header out-
put could not be created.”);
exit(1);
}
printf(“\nStripping EXE header..”);
fread (buffer,512,sizeof(char),srcFile);
fwrite(buffer,sizeof(char),512,hdrFile);
fclose(hdrFile);
printf(“\nWriting rest of the binary
to %s”,argv[2]);
while(!feof(srcFile))
{ fputc(fgetc(srcFile),dstFile); }
printf(“\nDone.”);
fclose(dstFile);
fclose(srcFile); Screenshot 3: Program output of write_sector_1.exe
return 0;
}
#include <stdio.h> {
The write_sector_1.c program #include <stdlib.h> int i = -1, j, k, ch;
given below is required only when you #include <string.h> int drive = _floppy1;
place the boot code directly to a floppy /* Different Drives */ unsigned char buf0[512], buf1[512];
(if you simulate using Bochs, this pro- #define _floppy1 0x0 FILE *fp;
#define _floppy2 0x1 memset((unsigned char *) buf1, 0, 512);
gram is not required). The program if (argc < 2)
output is shown in Screenshot 3. #define _hd1 0x80 {
#define _hd2 0x81 printf(“%s <bin_file>\n”, argv[0]);
/* write_sector_1.c */ #define _hd3 0x82 exit(0);
}
#include <bios.h> int main(int argc, char *argv[]) /* read actual sector */
if((ch = biosdisk(2,drive,0,0,1,1,buf0)))
{
Glossary printf(“Cannot Read Sector 0\n”);
exit(1);
1. MBR. In the IBM PC architecture, the master boot record (MBR), or partition sector, is a }
512-byte boot sector, i.e., the sector on the logical beginning of a hard disk that contains the if ((fp = fopen(argv[1], “rb”)) == NULL)
sequence of commands necessary for booting the operating systems. {
The MBR of a drive usually includes the drive’s partition table, which the PC uses to load printf(“Cannot open %s\n”, argv[1]);
and run the boot record of the partition that is marked with the active flag. This design allows exit(2);
}
the BIOS to load any OS without knowing exactly where to start inside its partition. Because
while(!feof(fp))
the MBR is read almost immediately when the computer is started, many computer viruses {
made in the era before virus scanner software became widespread operated by changing the i++;
code within the MBR. buf1[i] = fgetc(fp);
2. A20 gate. The 8086 microprocessor (the processor that came before the 286, 386, }
486, Pentium, etc) could only access 1 MB of address space. For that address range, 20 fclose(fp);
address bits (A0 through A19) are sufficient. buf0[0] = 0xEB;
buf0[1] = 0x3E;
Then, Intel invented the 80286 (often called just the ‘286’). The 80286 could access up to printf(“%d Bytes in %s\n”, i, argv[1]);
16 MB of address space, but the 80286 had to be compatible with the 8086 (programs that /* Modify actual sector by writing
were made for the 8086 had to be able to run on the 80286). The solution was to give the your boot-code */
80286 more address gates for the address range, but some programs depended on the fact for (j = 64, k = 0; k < i && j < 512; j++, k++)
that the addresses wrapped around at 1 MB. buf0[j] = buf1[k];
Let’s see it in the way the 8086 saw it: You have the address ‘11111111111111111111’ /* Boot Signature */
buf0[510] = 0x55;
(20 bits) in dual system and add ‘1’ to it. The result is ‘0’ as you don’t have a 21st bit (A20).
buf0[511] = 0xAA;
But the 80286 actually had more bits. To solve the problem, Intel made the 80286 disable if (!(ch = biosdisk(3,drive,0,0,1,1,buf0)))
the A20-gate, and then limit the address range to 20 bits. So, to access more than 1MB printf(“Done\n”);
memory, you need to enable the A20-gate. else
3. GDT. The GDT or global descriptor table is a data structure used by Intel x86-family printf(“Error writing Sector 0\n”);
processors starting with the 80286 in order to define the characteristics of the various return 0;
memory areas used during program execution, for example, the base address, the size and }
access privileges like executability and writability. This program preserves the BIOS
4. IDT. The interrupt descriptor table (IDT) is an array of 8-byte interrupt descriptors in
parameter block, so Windows or DOS
memory devoted to specifying (at most) 256 interrupt service routines. The first 32 entries
can recognise the floppy. Assuming
are reserved for processor exceptions and any 16 of the remaining entries can be used for
hardware interrupts. The rest are available for software interrupts. that the boot code is in floppy ‘A’
drive, type the following in ‘C’ drive:

WWW.EFYMAG.COM ELECTRONICS FOR YOU • JULY 2007 • 105


SOFTWARE
SECTION
c:\>write_sector_1 boot.bin. After this, with caching and paging disabled. other required registers (DS and ES)
the floppy can be used to boot the sys- And the A20 gate might be closed. keeping the offset zero and start
tem. Use any of the Assembly pro- As the boot code is compiled into your program. The ‘JMP 07C0h:STAR’
grams given as examples above to plain binary files, memory address instructs the processor to force the
make a boot.bin file and test using checks and proper address conversion CS to change to ’07C0h’ because Intel
floppy. are not done. So what happens during processors always refer the CS to
(Note. This program can write memory operations? Suppose you fetch instructions. So during execu-
only one sector, so Examples 3 and 4 have the following code that you place tion, all memory access refers to the
cannot be tested using this program in your boot sector: modified CS register, preventing
as they contain more than one sec- Mov ax, [label] memory fault.
tor.) label: 2. [ORG 0x7C00] is placed at the
For Turbo C users, absread( ) and dw 0 beginning of the code. The bin for-
abswrite( ) functions can also be used The assembler converts ‘ mov ax, mat in NASM provides an additional
instead of biosdisk( ) in the above [label]’ into ‘mov ax, 0x0003’ because assembler directive ORG. The func-
cases. Biosdisk( ) uses BIOS disk no segment address is provided in the tion of the ORG directive is to specify
dervices (interrupt ‘0x13’). The func- above code. When the boot sector pro- the origin address which NASM will
tion assumes a sector size of 512 bytes. gram is executing, the address should assume the program begins at when
The format is: be ‘mov ax, 0x7C03.’ Since the boot it is loaded into memory. Its sole func-
int biosdisk(int cmd, int drive, int head, sector program is read and placed into tion is to specify one offset which is
int track, int sector, int nsects, void *buffer); memory location 0000:7C00, you have added to all internal address refer-
a memory fault. ences within the section. The solutions
The memory problem You can address this problem in can be explored after going through
At boot time, the BIOS loads the boot two ways: the detail of segment-offset address-
sector program into memory at 1. Begin bootstrap by jumping to ing.
‘0x7C00’ and jumps to address your boot sector, but jump to a EFY note. All the relevant source
‘0x7C00.’ CS, DS, ES, FS and GS are all known segment. That is, modify the codes have been included in this
set to ‘0.’ The CPU is then in real mode, CS (Code Section) register, and month’s EFY-CD. 

106 • JULY 2007 • ELECTRONICS FOR YOU WWW.EFYMAG.COM

View publication stats

You might also like