Make your own OS in 30 days – day3: 32bit mode and OS in C

We only wrote 16bit assembly language on day 1 and 2.
Day 3 started with Floppy Disk architecture by illustrating cylinder, header, sector and drive, then how to read from there.

MOV		AX,0x0820 		; loads it at 0x8200 (ES x 16 + BX)
MOV		CH,0			; cylinder 0
MOV		DH,0			; head 0
MOV		CL,2			; sector 2

MOV		AH,0x02			; AH=0x02 : read disk
MOV		AL,1			; read 1 sector
MOV		DL,0x00			; A drive
INT		0x13			; Disk BIOS call
JC		error

Int 13H is described here.
It explains segment registers, how to retry when error (if the carry flag is set), read 18 sectors, and read 18 sectors x 2 heads x 10 cylinders into memory.

When you compile this very simple OS code

    JMP		fin

It’ll be compiled to the 3 byte code.

f4 eb fd

Then when you make a disk image file, it’ll be placed at 0x4200.

0004200: f4eb fd00 0000 0000 0000 0000 0000 0000
0004210: 0000 0000 0000 0000 0000 0000 0000 0000
0004220: 0000 0000 0000 0000 0000 0000 0000 0000
0004230: 0000 0000 0000 0000 0000 0000 0000 0000

Since the bootstrap loads the first byte of sector 2 at 0x8200 (first byte of sector 1 is at 0x8000), the 3byte OS code at 0x4200 will be loaded at 0x8000 + 0x4200 = 0xc200.

So, “ORG 0xc200” is added to the OS code,

    ORG 0xc200

    JMP		fin

then it adds “JMP 0xc200” at the end of the IPL. Then the IPS will JMP to the OS (HLT code) after loading the sectors into memory.

Just doing HLT is not interesting. The book changes the OS to this which fills the screen in black.

CYLS	EQU		0x0ff0			; set by the bootsector
LEDS	EQU		0x0ff1
VMODE	EQU		0x0ff2			; color bitness
SCRNX	EQU		0x0ff4			; X resolution
SCRNY	EQU		0x0ff6			; Y resolution
VRAM	EQU		0x0ff8			; VRAM

	ORG		0xc200
	MOV		AL,0x13			; VGA,3 20x200x8bit color
	MOV		AH,0x00
	INT		0x10
	MOV		BYTE [VMODE],8	; screen mode
	MOV		DWORD [VRAM],0x000a0000

; Get Keyboard's LED state from BIOS
	MOV		AH,0x02
	INT		0x16 			; keyboard BIOS

	JMP		fin

We are getting into 32bit mode & C language from here. Now we have 4 source files.
ipl10.nas: bootstrap code (x86 16bit assembly)
asmhead.nas: OS loader called by bootstrap (x86 32bit assembly, it’s moving into 32bit mode and loads OS code written in C. Not explained as of Day 3.)
bootpack.c: OS code (C)
nasfunc.nas: functions called by boot pack.c (x86 32bit assembly)


void io_hlt(void);

void HariMain(void)
	io_hlt(); /* calls _io_hlt in naskfunc.nas */
	goto fin;



; naskfunc
; TAB=4

[FORMAT "WCOFF"]				; create an object file
[BITS 32]						; 32bit mode

[FILE "naskfunc.nas"]			; source file name
		GLOBAL	_io_hlt			; function name included in this file

[SECTION .text]		; text section

_io_hlt:	; void io_hlt(void);

When you boot it, ipl10 loads the image into memory and JPM to 0xC200 (asmhead.nas) fills in the screen in black and calls bootpack.c which halts.


Day 4 will do more in C 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *