15
× highlights off Not quite what you are looking for? You may want to try: Clean and quick cancellation of I/O operations A Practical Approach to Computer Systems Design and Architecture 7,682,156 members and growing! (28,124 online) Email Password Sign in Join Remember me? Lost password? Home Articles Questions & Answers Learning Zones Features Help! The Lounge how to create OPERATING SYSTEM 102 Article Browse Code Stats Revisions Sponsored Links Prize winner in Competition "MFC/C++ Sep 2006" » General Reading » Hardware & System » General Licence CPOL First Posted 6 Oct 2006 Views 215,867 Downloads 2,542 Bookmarked 298 times By S Keller | 11 Oct 2006 C++ C Windows Visual-Studio Dev ASM Intermediate Writing your own operating system. See Also More like this More by this author 4.78 (181 votes) Download project files - 4.51 Kb Download BOOT sector utility - 41.4 Kb See Also... Building your own operating system - CodeProject http://www.codeproject.com/KB/system/MakingOS.aspx 1 of 15 4/5/2011 4:47 AM

Building Your Own Operating System - Code Project

Embed Size (px)

Citation preview

Page 1: Building Your Own Operating System - Code Project

×

highlights off

Not quite what you are looking for? You may want to try:

Clean and quick cancellation of I/O operationsA Practical Approach to Computer Systems Design and Architecture

7,682,156 members and growing! (28,124 online)

Email Password Sign in Join Remember me? Lost password?

Home Articles Questions & Answers Learning Zones

Features Help! The Loungehow to create OPERATING SYSTEM

102

Article Browse Code Stats Revisions

Sponsored Links

Prize winner in Competition "MFC/C++ Sep 2006"

» General Reading » Hardware & System » General

Licence CPOLFirst Posted 6 Oct 2006Views 215,867Downloads 2,542Bookmarked 298 times

By S Keller | 11 Oct 2006

C++ C Windows Visual-Studio Dev ASM Intermediate

Writing your own operating system.

See AlsoMore like thisMore by this author

4.78 (181 votes)

Download project files - 4.51 KbDownload BOOT sector utility - 41.4 Kb

See Also...

Building your own operating system - CodeProject http://www.codeproject.com/KB/system/MakingOS.aspx

1 of 15 4/5/2011 4:47 AM

Page 2: Building Your Own Operating System - Code Project

Introduction

If you know how an operating system works, it will help you a lotin programming, especially for system programs like device drivers;even for non-system-programming, it can help a lot. And also, I'msure every one would like to have their own operating system.

You would also learn from this article how to read and write rawsectors from a disk.

Background

In this article, I would explain the first part of building an operatingsystem.

Here is what happens when you start your computer:

The BIOS (Basic Input Output System � this is a programthat comes with any mother board and it is placed in a chip onthe mother board) checks all the computer components tomake sure that they are all working.

1.

If all the components are working, the BIOS starts searchingfor a drive that might have an operating system. (The BIOScan look in hard drives, floppy drives, CD-ROM drives etc. Theorder the BIOS checks can be set it in the BIOS setupprogram. To get to the BIOS setup, right when the computerturns on, press the DELETE key until you see the BIOS setupprogram; in some computers, it can be a different button thanDELETE, so look in your mother board specification to find howto get to the BIOS setup program. And also look up (if youdon�t now how to do it) how to change the search search ofBIOS while looking for an operating system.)

2.

The BIOS checks the first drive to see if he has a valid BOOTsector. (A disk is divided into little regions that are namedsectors. The BOOT sector size is 512 bytes in most drives.) Ifthe drive has a valid BOOT sector, the BIOS loads that sectorin to the memory at address 0:7c00 (=31,744) and givescontrol to that area of the memory.

3.

Cosmos - C# Open Source ManagedOperating SystemBuild your own OS in Visual Studioand C#.

How to develop your own BootLoaderThis article describes the first stepsin...

Beginning Operating SystemDevelopment, Part OneIntroduction and environment setup

Develop Your Own Operating Systemin C# or VB.NETDevelop your own operating systemusing C# (or...

The Daily Insider

30 free programming booksDaily News: Signup now.

Building your own operating system - CodeProject http://www.codeproject.com/KB/system/MakingOS.aspx

2 of 15 4/5/2011 4:47 AM

Page 3: Building Your Own Operating System - Code Project

Now this little program that was loaded from the BOOT sectorcontinues to load the operating system, and after theoperating system is loaded, it initializes the operatingsystem and gives the control to the operating system.

4.

Making a bootable disk

The steps would be like this:

Take a floppy diskette that you don't need.1.Use the program that comes with this article,BOOTSectorUtility.exe, to copy the file BOOT.bin to the floppydiskette BOOT sector.

2.

Make sure that your BIOS is set to BOOT from the floppy drivefirst, so that our operating system would be loaded.

3.

Restart your computer (make sure that the floppy diskette is inthe drive), and watch what our BOOT sector does.

4.

With BOOTSectorUtility.exe, you can also search your regularoperating system, by saving the boot sector of the drive of youroperating system to a file.

And to read that file, start the command line and type Debug <filepath> (if you have a Microsoft operating system).

The Debug command starts a 16 bit debugger (any boot sector is in16 bit code, because when the computer starts, it is in 16 bit mode,and only after the boot sector is run, can it change the CPU to 32 bitmode or 64 bit mode). Press u <Enter> (u = unassemble) tounassemble the file. Figure 1 shows an example.

Figure 1 Unassembeling 16 bit code.

Reading raw bytes from a drive

You can read raw sectors from a drive like this:

Collapse

//

Building your own operating system - CodeProject http://www.codeproject.com/KB/system/MakingOS.aspx

3 of 15 4/5/2011 4:47 AM

Page 4: Building Your Own Operating System - Code Project

// Reading/writing raw sectors.

//

//pBuffer has to be at least 512 bytes wide.

BOOL ReadSector(char chDriveName,char *pBuffer,DWORD nSector){ char Buffer[256]; HANDLE hDevice; DWORD dwBytesReaden;

//Init the drive name (as a Driver name).

sprintf(Buffer,"\\\\.\\%c:",chDriveName);

hDevice = CreateFile(Buffer, // drive to open.

GENERIC_READ, FILE_SHARE_READ | // share mode.

FILE_SHARE_WRITE, NULL, // default security attributes.

OPEN_EXISTING, // disposition.

0, // file attributes.

NULL); //

if(hDrive==INVALID_HANDLE_VALUE)//if Error Openning a drive.

{ return FALSE; } //Move the read pointer to the right sector.

if(SetFilePointer(hDevice, nSector*512, NULL, FILE_BEGIN)==0xFFFFFFFF) return FALSE;

//Read the Sector.

ReadFile(hDevice, pBuffer, 512, &dwBytesReaden, 0);

//if Error reading the sector.

if(dwBytesReaden!=512) return FALSE;

return TRUE;}

Making a BOOT program

Now, I will explain the basics of a boot program (to understand this,

Building your own operating system - CodeProject http://www.codeproject.com/KB/system/MakingOS.aspx

4 of 15 4/5/2011 4:47 AM

Page 5: Building Your Own Operating System - Code Project

you need to be familiar with Assembler and Interrupts and Interruptsvector table).

[Interrupts vector table = From Address 0 -> 1,024 holds 256structures (4 bytes in size) that holds an address in the form: CS:IP= xxxx:xxxx. So you have addresses from INT 1 -> INT 256. Eachinterrupt has an index into that table. This table is used like this: ifyou, for example, use the instruction INT 10h, the CPU checks inindex 10h in the interrupt table were the address of the routine isthat handles INT 10h, and the CPU jumps to that address to executeit].

Now, I will explain how to print a string, read sectors, and wait for akey press using only the BIOS.

To print a string, I use the INT 10h function 0Ah (AH = 0Ah). Tomove the cursor, I use the INT 10h function 2h (AH = 2h). To readsectors, I use the INT 13h function 2h (AH = 2h). To wait for a keystroke, use the INT 16h function 0h (AH = 0h).

I used TASM v3.1 and TLINK to make my boot sector, but you canuse any x86 16 bit assembler compiler.

(If you can't get a copy of TASM and TLINK, you can send me ane-mail and if it is legal, I would send you a copy of them).

(TASM and TLINK v3.1 were released in 1992 by BorlandInternational).

Now I would explain the steps the BOOT program does.

Make a stack frame (if not you don't have any stack).1.Set the DS (data segment) so you can access the data.2.In my boot sector, I added this: (Display a message to the user,Wait for a key stroke, Continue).

3.

Set up the Disk Parameter Block (the Disk Parameter Block is astructure that holds information about the drive, like howmuch sectors it has etc., the drive controller uses it forknowing how to read the disk in the drive).

4.

To set the Disk Parameter Block, get its address (its address ispointed by INT 1Eh (in the memory, this is 1E x 4 bytes =78h = 30 x 4 bytes = 120).

This is an example of how to initialize the Disk ParameterBlock for a 3.5 inch (1.44 MB) floppy Disk.

Collapse

StepRateAndHeadUnloadTime db 0DFhHeadLoadTimeAndDMAModeFlag db 2hDelayForMotorTurnOff db 25hBytesPerSector db 2h SectorsPerTrack db 12h IntersectorGapLength db 1bhDataLength db 0FFhIntersectorGapLengthDuringFormat db 54h

5.

Building your own operating system - CodeProject http://www.codeproject.com/KB/system/MakingOS.aspx

5 of 15 4/5/2011 4:47 AM

Page 6: Building Your Own Operating System - Code Project

FormatByteValue db 0F6hHeadSettlingTime db 0FhDelayUntilMotorAtNormalSpeed db 8h DisketteSectorAddress(as LBA)OfTheDataArea db 0CylinderNumberToReadFrom db 0SectorNumberToReadFrom db 0DisketteSectorAddress (as LBA) OfTheRootDirectory db 0

And set the address that INT 1E points at to the address ofthe Disk Parameter Block you set up.

6.

Reset the drive (by using the INT 13h function 0).7.Start reading the diskette by using the INT 13h function 2h.8.Give control to the loaded operating system (this is done byinserting in the code the op code of a jump to were you loadedthe operating system. Let's say you loaded the operatingsystem 512 bytes from were the BIOS loaded the BOOT sector(0:7c00h).

Collapse

db 0E9h ; FAR JMP op code.

db 512 ; 512 bytes

or you can use another way: call some address, and there,change the return address in the stack to were you want thejump to, like this:

Collapse

call GiveControlToOS GiveControlToOS: Pop ax Pop ax Mov ax,CodeSegement ;Push the new CS to return.

Push ax mov ax,InstructionPointer ;Push the new IP to return.

Push ax ret ;Return to the modified address.

9.

In the end of the boot sector the bytes would be 0x55h0x0AAh. If the boot sector doesn�t have this value, the BIOSwould not load that boot sector.

10.

After this, the BOOT sector finishes its job and the operatingsystem starts running.

You can download the files I used for my boot sector here, the filesare BOOT.asm, BOOT.bin (this is the sector itself).

The BOOT sector program

Collapse

.MODEL SMALL

Building your own operating system - CodeProject http://www.codeproject.com/KB/system/MakingOS.aspx

6 of 15 4/5/2011 4:47 AM

Page 7: Building Your Own Operating System - Code Project

.CODE

ORG 7c00h ;Because BIOS loades the OS at

; address 0:7C00h so ORG 7C00h

; makes that the refrence to date

; are with the right offset (7c00h).

ProgramStart:

; CS = 0 / IP = 7C00h // SS = ? / SP = ?

; You are now at address 7c00.

jmp start ;Here we start the, BIOS gave us now the control.

;///////////////////////////////////////////

;//Here goes all the data of the program.

;///////////////////////////////////////////

xCursor db 0yCursor db 0

nSector db 0nTrack db 0nSide db 0nDrive db 0

nTrays db 0

'Are You Ready to start Loading the OS...',0szReady db'Error Reading Drive, Press any Key to reboot...',0szErrorReadingDrive db;//Done Reading a track.

szPlaceMarker db '~~~~',0szDone db 'Done',0

pOS dw 7E00h;//Points to were to download the Operating System.

;//Disk Paremeter Table.

StepRateAndHeadUnloadTime db 0DFhHeadLoadTimeAndDMAModeFlag db 2hDelayForMotorTurnOff db 25h;// (1 = 256) //(2 = 512 bytes)

BytesPerSector db 2h;// 18 sectors in a track.

SectorsPerTrack db 18IntersectorGapLength db 1BhDataLength db 0FFhIntersectorGapLengthDuringFormat db 54hFormatByteValue db 0F6hHeadSettlingTime db 0Fh

Building your own operating system - CodeProject http://www.codeproject.com/KB/system/MakingOS.aspx

7 of 15 4/5/2011 4:47 AM

Page 8: Building Your Own Operating System - Code Project

DelayUntilMotorAtNormalSpeed db 8h

DisketteSectorAddress_as_LBA_OfTheDataArea db 0CylinderNumberToReadFrom db 0SectorNumberToReadFrom db 0DisketteSectorAddress_as_LBA_OfTheRootDirectory db 0

;/////////////////////////////////

;//Here the program starts.

;/////////////////////////////////

Start:

CLI ;Clear Interupt Flag so while setting

;up the stack any intrupt would not be fired.

mov AX,7B0h ;lets have the stack start at 7c00h-256 = 7B00h

mov SS,ax ;SS:SP = 7B0h:256 = 7B00h:256

mov SP,256 ;Lets make the stack 256 bytes.

Mov ax,CS ;Set the data segment = CS = 0

mov DS,ax XOR AX,AX ;Makes AX=0.

MOV ES,AX ;Make ES=0

STI ;Set Back the Interupt Flag after

;we finished setting a stack fram.

Call ClearScreen ;ClearScreen()

LEA AX,szReady ;Get Address of szReady.

CALL PrintMessage ;Call PrintfMessage()

CALL GetKey ;Call GetKey()

CALL SetNewDisketteParameterTable ;SetNewDisketteParameterTable()

CALL DownloadOS CALL GetKey ;Call GetKey()

CALL FAR PTR GiveControlToOS ;Give Control To OS.

ret

;/////////////////////////////////////

;//Prints a message to the screen.

;/////////////////////////////////////

Building your own operating system - CodeProject http://www.codeproject.com/KB/system/MakingOS.aspx

8 of 15 4/5/2011 4:47 AM

Page 9: Building Your Own Operating System - Code Project

PrintMessage PROC

mov DI,AX ;AX holds the address of the string to Display.

Mov xCursor,1 ;Column.

ContinuPrinting:

cmp byte ptr [DI],0 ;Did we get to the End of String.

JE EndPrintingMessage ;if you gat to the end of the string return.

mov AH,2 ;Move Cursor

mov DH,yCursor ;row.

mov DL,xCursor ;column.

mov BH,0 ;page number.

INT 10h INC xCursor mov AH,0Ah ;Display Character Function.

mov AL,[DI] ;character to display.

mov BH,0 ;page number.

mov CX,1 ;number of times to write character

INT 10h INC DI ;Go to next character.

JMP ContinuPrinting ;go to Print Next Character.

EndPrintingMessage: Inc yCursor ;So Next time the message would

;be printed in the second line.

cmp yCursor,25 JNE dontMoveCorsurToBegin Mov yCursor,0 dontMoveCorsurToBegin: ret PrintMessage EndP ;//////////////////////////////////////

;//Watis for the user to press a key.

;//////////////////////////////////////

GetKey PROC

Building your own operating system - CodeProject http://www.codeproject.com/KB/system/MakingOS.aspx

9 of 15 4/5/2011 4:47 AM

Page 10: Building Your Own Operating System - Code Project

mov ah,0 int 16h ;Wait for a key press.

Ret GetKey EndP ;///////////////////////////////////////////

;//Gives Control To Second Part Loader.

;///////////////////////////////////////////

GiveControlToOS PROC

LEA AX,szDone Call PrintMessage CALL GetKey db 0e9h ;Far JMP op code.

dw 512 ;JMP 512 bytes ahead.

; POP AX ;//Another why to make

;the CPU jump to a new place.

; POP AX

; Push 7E0h ;Push New CS address.

; Push 0 ;Push New IP address.

;The address that comes out is 7E00:0000.

;(512 bytes Higher from were BIOS Put us.)

; ret

GiveControlToOS EndP ;///////////////////////////////////

;//Clear Screen.

;///////////////////////////////////

ClearScreen PROC

mov ax,0600h ;//Scroll All Screen UP to Clear Screen.

mov bh,07 mov cx,0 mov dx,184fh int 10h Mov xCursor,0 ;//Set Corsur Position So next

//write would start in //the beginning of screen. Mov yCursor,0

Ret ClearScreen EndP;/////////////////////////////////

;//PrintPlaceMarker.

Building your own operating system - CodeProject http://www.codeproject.com/KB/system/MakingOS.aspx

10 of 15 4/5/2011 4:47 AM

Page 11: Building Your Own Operating System - Code Project

;/////////////////////////////////

PrintPlaceMarker PROC

LEA AX,szPlaceMarker CALL PrintMessage ;Call PrintfMessage()

CALL GetKey ;Call GetKey()

ret PrintPlaceMarker EndP;/////////////////////////////////////////

;//Set New Disk Parameter Table

;/////////////////////////////////////////

SetNewDisketteParameterTable PROC

LEA DX,StepRateAndHeadUnloadTime ;//Get the address of the Disk Parameters Block.

;//Int 1E (that is in address 0:78h)

;//holds the address of the disk parametrs

;//block, so now change it to

;//our parametr black.

;//DX holds the address of our Parameters block.

MOV WORD PTR CS:[0078h],DX MOV WORD PTR CS:[007Ah],0000 ;Reset Drive To Update the DisketteParameterTable.

MOV AH,0 INT 13H ret SetNewDisketteParameterTable EndP;///////////////////////////////////

;//DownloadOS

;///////////////////////////////////

DownloadOS PROC

mov nDrive,0 mov nSide,0 mov nTrack,0 mov nSector,1 ContinueDownload: INC nSector ;Read Next Sector.

cmp nSector,19 ;Did we get to end of track.

JNE StayInTrack CALL PrintPlaceMarker ;Print now '~~~~' so the user would

;now that we finished reding a

Building your own operating system - CodeProject http://www.codeproject.com/KB/system/MakingOS.aspx

11 of 15 4/5/2011 4:47 AM

Page 12: Building Your Own Operating System - Code Project

track

INC nTrack ;If we gat to end of track Move to next track.

mov nSector,1 ;And Read Next Sector.

CMP nTrack,5 ;Read 5 Tracks (Modify this value

;to how much Tracks you want to read).

JE EndDownloadingOS StayInTrack: ;ReadSector();

Call ReadSector JMP ContinueDownload ;If diden't yet finish Loading OS.

EndDownloadingOS:

ret DownloadOS EndP ;////////////////////////////////////////

;//Read Sector.

;////////////////////////////////////////

ReadSector PROC

mov nTrays,0 TryAgain:

mov AH,2 ;//Read Function.

mov AL,1 ;//1 Sector.

mov CH,nTrack mov CL,nSector ;//Remember: Sectors start with 1, not 0.

mov DH,nSide mov DL,nDrive Mov BX,pOS ;//ES:BX points to the address

;to were to store the sector.

INT 13h

CMP AH,0 ;Int 13 return Code is in AH.

JE EndReadSector ;if 'Sucsess' (AH = 0) End function.

mov AH,0 ;Else Reset Drive . And Try Again...

INT 13h cmp nTrays,3 ;Chack if you tryed reading

Building your own operating system - CodeProject http://www.codeproject.com/KB/system/MakingOS.aspx

12 of 15 4/5/2011 4:47 AM

Page 13: Building Your Own Operating System - Code Project

;more then 3 times.

JE DisplayError ; if tryed 3 Times Display Error.

INC nTrays jmp TryAgain ;Try Reading again.

DisplayError: LEA AX,szErrorReadingDrive Call PrintMessage Call GetKey mov AH,0 ;Reboot Computer.

INT 19h

EndReadSector: ;ADD WORD PTR pOS,512 ;//Move the pointer

;(ES:BX = ES:pOS = 0:pOS) 512 bytes.

;//Here you set the varible

;pOS (pOS points to were BIOS

;//Would load the Next Sector).

Ret ReadSector EndP ;////////////////////////////////////

;//

;////////////////////////////////////

END ProgramStart

Points of interest

It took some time until I got a running boot sector. I would list acouple of bugs I had in the beginning while writing my boot sector.

I didn�t set up a right stack frame.1.I didn�t modify the Disk Parameter Block.2.I loaded the operating system to areas that are used byBIOS routines (and even to the Interpret table).

3.

In the end of the boot sector, it must have the bytes 0x55h0x0AAh (this is a signature that it is a valid bootable sector).

(For using BOOTSectorUtility.exe, you would need the .NET 2.0Framework installed on your computer. To download the .NET2.0 Framework, click here.)

4.

If I see that this article interests people, I would write some morearticles on this subject.

License

Building your own operating system - CodeProject http://www.codeproject.com/KB/system/MakingOS.aspx

13 of 15 4/5/2011 4:47 AM

Page 14: Building Your Own Operating System - Code Project

ArticleTop

Sign Up to vote for this article

This article, along with any associated source code and files, islicensed under The Code Project Open License (CPOL)

About the Author

S Keller

Systems Engineer

United States

Member

Comments and Discussions

You must Sign In to use this message board. (secure sign-in)

FAQ Search

Noise Tolerance Medium Layout Normal Per page 25 Update

Msgs 1 to 25 of 102 (Total in Forum: 102) (Refresh) First Prev Next

saxena durgesh 21:18 14 Dec '10

cameleon_fr 7:35 16 Sep '10

ShariqDON 12:19 1 May '10

Shanay 23:21 29 Apr '10

Shanay 21:45 29 Apr '10

Shanay 21:35 29 Apr '10

taheri 2:51 21 Dec '09

Colin Geek 18:47 6 Nov '09

Bright Mazura 23:38 7 Oct '09

Carllbrando23 16:58 15 Mar '10

tuan111119:04 12 May '09

Gogeta_ulti 21:55 1 May '09

Dilip Jamkhandi 6:52 16 Apr '09

Tirtesh 2:25 26 Aug '09

soft_man 1:30 4 Feb '09

Carllbrando23 16:59 15 Mar '10

JimB121 18:53 23 Dec '08

non-bugging Errors 20:22 17 Dec '08

My vote of 5

My vote of 5

Suppose If User try it InHis Local Drive

DiskParameterBlock(DPB)

view the dump

DPB details information

BOOTSectorUtility.exe

hi

The Tasm and Tlink?

Re: The Tasm and Tlink?

[email protected]

Operating System

MY OPERATING SYSTEM.

Re: MY OPERATINGSYSTEM.

Hi

Re: Hi

Problem with"BOOTSectorUtility"

Boot sector

Building your own operating system - CodeProject http://www.codeproject.com/KB/system/MakingOS.aspx

14 of 15 4/5/2011 4:47 AM

Page 15: Building Your Own Operating System - Code Project

link | Privacy | Terms of Use | Mobile

Last Updated: 11 Oct 2006

Copyright 2006 by S Keller

Everything else Copyright © CodeProject, 1999-2011

Web24 | Advertise on the Code Project

Jaeman 13:11 13 Jun '08

S Keller 18:26 5 Aug '08

Jaeman 22:27 6 Aug '08

S Keller 1:42 11 Aug '08

muncheez123 19:30 7 Jun '08

S Keller 18:24 5 Aug '08

muncheez123 11:56 31 Jan '09

Last Visit: 19:00 31 Dec '99 Last Update: 0:50 5 Apr '11 12 3 4 5 Next »

General News Question Answer Joke Rant Admin

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads,Ctrl+PgUp/PgDown to switch pages.

New article...

Re: New article...

Re: New article...

Re: New article...

help

Re: help

Re: help

Building your own operating system - CodeProject http://www.codeproject.com/KB/system/MakingOS.aspx

15 of 15 4/5/2011 4:47 AM