SlideShare una empresa de Scribd logo
1 de 38
Roll your own toy UNIX-clone OS By Ahmed Essam www.eramax.org
Table of contents 	1. Environment setup2. Genesis3. The Screen4. The GDT and IDT
Setting Environment To compile and run the sample code we need to have  ,[object Object]
Ld
NASM
GNU Make,[object Object]
Qemu
Bochs ,[object Object]
(VM setup)1. Environment setup We will use Bochs (an open-source x86-64 emulator). We need a bochs configuration file (bochsrc.txt). megs: 32floppya: 1_44="myOs2.bin", status=insertedboot: floppylog: bochsout.txtclock: sync=realtimecpu: ips=500000  keyboard_paste_delay: 100000
Useful scripts Makefile 	making (compiling) our project. Link.ld 	link files together into one ELF binary (Kernel). update_image.sh 	poke your new kernel binary into the floppy image file. run_bochs.sh 	mounts the correct loopback device, runs bochs, then unmounts.
2. Genesis2.1 - The boot code MBOOT_PAGE_ALIGN    equ 1<<0    ; Load kernel and modules on a page boundaryMBOOT_MEM_INFO      equ 1<<1    ; Provide your kernel with memory infoMBOOT_HEADER_MAGIC  equ 0x1BADB002 ; Multiboot Magic value; NOTE: We do not use MBOOT_AOUT_KLUDGE. It means that GRUB does not; pass us a symbol table.MBOOT_HEADER_FLAGS  equ MBOOT_PAGE_ALIGN | MBOOT_MEM_INFOMBOOT_CHECKSUM      equ -(MBOOT_HEADER_MAGIC + MBOOT_HEADER_FLAGS)[BITS 32]                       ; All instructions should be 32-bit.[GLOBAL mboot]                  ; Make 'mboot' accessible from C.[EXTERN code]                   ; Start of the '.text' section.[EXTERN bss]                    ; Start of the .bss section.[EXTERN end]                    ; End of the last loadable section.mboot:  dd  MBOOT_HEADER_MAGIC        ; GRUB will search for this value on each                                ; 4-byte boundary in your kernel file  dd  MBOOT_HEADER_FLAGS        ; How GRUB should load your file / settings  dd  MBOOT_CHECKSUM            ; To ensure that the above values are correct   
2.1 - The boot code (Cont)   dd  mboot                     ; Location of this descriptor  dd  code                      ; Start of kernel '.text' (code) section.  dd  bss                       ; End of kernel '.data' section.  dd  end                       ; End of kernel.  dd  start                     ; Kernel entry point (initial EIP).[GLOBAL start]                  ; Kernel entry point.[EXTERN main]                   ; This is the entry point of our C codestart:  push    ebx                   ; Load multiboot header location  ; Execute the kernel:  cli                         ; Disable interrupts.  call main                   ; call our main() function.  jmp $                       ; Enter an infinite loop, to stop the processor                              ; executing whatever rubbish is in the memory                              ; after our kernel!
2.3. Adding some C code // main.c int main(struct multiboot *mboot_ptr){  // Kernel Code.  return 0xDEADBABA;}
common.c  functions for writing to and reading from the I/O bus, and some typedefs : typedef unsigned int   u32int;typedef          int   s32int;typedef unsigned short u16int;typedef          short s16int;typedef unsigned char  u8int;typedef          char  s8int; void outb(u16int port, u8int value){asm volatile ("outb %1, %0" : : "dN" (port), "a" (value)); }u8int inb(u16int port){   u8int ret;   asm volatile("inb %1, %0" : "=a" (ret) : "dN" (port));   return ret;}u16int inw(u16int port){   u16int ret;   asm volatile ("inw %1, %0" : "=a" (ret) : "dN" (port));   return ret;}
3. The Screen 3.1. The theory Your kernel gets booted by GRUB in text mode. That is, it has available to it a framebuffer (area of memory) that controls a screen of characters (not pixels) 80 wide by 25 high, at address 0xB8000. Framebuffer is not actually normal RAM. It is part of the VGA controller's dedicated video memory that has been memory-mapped via hardware into your linear address space.
3.1. The theory (Cont) The framebuffer is just an array of 16-bit words, each 16-bit value representing the display of one character. The offset from the start of the framebuffer of the word that specifies a character at position x, y is: (y * 80 + x) * 2  8 bits are used to represent a character. foreground and background colours (4 bits each).
3.1. The theory (Cont)
3.2.2. The monitor code Moving the cursor 		static void move_cursor() Scrolling the screen 		 static void scroll() Writing a character to the screen 		 void monitor_put(char c) location = video_memory + (cursor_y*80 + cursor_x);*location = c | attribute;  Clearing the screen 	u16int blank = 0x20 /* space */ | (attributeByte << 8);  	 for (i = 0; i < 80*25; i++)	   {  	        video_memory[i] = blank;	   }
3.2.2. The monitor code (Cont) Writing a string 	void monitor_write(char *c){	   int i = 0;	   while (c[i])	   { 	      monitor_put(c[i++]); 	   }}  //-------- Kernel Code : 	monitor_clear();monitor_write("Hello, world!");
The monitor
4. The GDT and IDT 4.1. The Global Descriptor Table (theory) 	are arrays of flags and bit values describing the operation of the segmentation system. Every memory access is evaluated with respect to a segment. That is, the memory address is added to the segment's base address, and checked against the segment's length.
GDT  there is one thing that segmentation can do that paging can't, and that's set the ring levels.  A ring is a privilege level - zero being the most privileged, and three being the least. Processes in ring zero are said to be running in kernel-mode, or supervisor-mode, because they can use instructions like sti and cli, something which most processes can't. A segment descriptor carries inside it a number representing the ring level it applies to.
The Global Descriptor Table (practical) A GDT entry looks like struct gdt_entry_struct{   u16int limit_low;           // The lower 16 bits of the limit.   u16int base_low;            // The lower 16 bits of the base.   u8int  base_middle;         // The next 8 bits of the base.   u8int  access;              // Access flags, determine what ring 			        //this segment can be used in.   u8int  granularity;   u8int  base_high;           // The last 8 bits of the base.} __attribute__((packed));
GDT u8int  access;      P    Is segment present? (1 = Yes)DPL    Descriptor privilege level - Ring 0 - 3.DT    Descriptor typeType    Segment type : code segment / data segment.
GDT To pass the GDT Table ,we pass the Pointer to this table to the CPU and pass its limit(length). So we must use this struct : struct gdt_ptr_struct{   u16int limit;               // The upper 16 bits of all selector limits.   u32int base;                // The address of the first gdt_entry_t }
GDT gdt_entry_t gdt_entries[5];gdt_ptr_t   gdt_ptr; static void init_gdt(){   gdt_ptr.limit = (sizeof(gdt_entry_t) * 5) - 1;   gdt_ptr.base  = (u32int)&gdt_entries;   gdt_set_gate(0, 0, 0, 0, 0);                // Null segment   gdt_set_gate(1, 0, 0xFFFFFFFF, 0x9A, 0xCF); // Code segment   gdt_set_gate(2, 0, 0xFFFFFFFF, 0x92, 0xCF); // Data segment   gdt_set_gate(3, 0, 0xFFFFFFFF, 0xFA, 0xCF); // User mode code segment   gdt_set_gate(4, 0, 0xFFFFFFFF, 0xF2, 0xCF); // User mode data segment   gdt_flush((u32int)&gdt_ptr);}
GDT static void gdt_set_gate(s32int num, u32int base, u32int limit, u8int access, u8int gran){   gdt_entries[num].base_low    = (base & 0xFFFF);   gdt_entries[num].base_middle = (base >> 16) & 0xFF;   gdt_entries[num].base_high   = (base >> 24) & 0xFF;   gdt_entries[num].limit_low   = (limit & 0xFFFF);   gdt_entries[num].granularity = (limit >> 16) & 0x0F;   gdt_entries[num].granularity |= gran & 0xF0;   gdt_entries[num].access      = access;} [GLOBAL gdt_flush]    ; Allows the C code to call gdt_flush().gdt_flush:   mov eax, [esp+4]  ; Get the pointer to the GDT, passed as a parameter.   lgdt [eax]        ; Load the new GDT pointer
4.3. The Interrupt Descriptor Table (theory) There are times when you want to interrupt the processor. You want to stop it doing what it is doing, and force it to do something different. An example of this is when an timer or keyboard interrupt request (IRQ) fires. The processor can register 'signal handlers' (interrupt handlers) that deal with the interrupt, then return to the code that was running before it fired. Interrupts can be fired externally, via IRQs, or internally, via the 'int n' instruction.  The Interrupt Descriptor Table tells the processor where to find handlers for each interrupt. It is very similar to the GDT. It is just an array of entries, each one corresponding to an interrupt number.  There are 256 possible interrupt numbers, so 256 must be defined. If an interrupt occurs and there is no entry for it (even a NULL entry is fine), the processor will panic and reset.
Faults, traps and exceptions The special, CPU-dedicated 32 interrupts : 0 - Division by zero exception 1 - Debug exception 2 - Non maskable interrupt 3 - Breakpoint exception 4 - 'Into detected overflow' 5 - Out of bounds exception 6 - Invalid opcode exception 7 - No coprocessor exception 8 - Double fault (pushes an error code) 9 - Coprocessor segment overrun 10 - Bad TSS (pushes an error code) 11 - Segment not present (pushes an error code) 12 - Stack fault (pushes an error code) 13 - General protection fault (pushes an error code) 14 - Page fault (pushes an error code) 15 - Unknown interrupt exception 16 - Coprocessor fault 17 - Alignment check exception 18 - Machine check exception 19-31 - Reserved
4.4. The Interrupt Descriptor Table (practice) // A struct describing an interrupt gate.struct idt_entry_struct{   u16int base_lo;             // The lower 16 bits of the address to 					//jump to when this interrupt fires.   u16int sel;                 // Kernel segment selector.   u8int  always0;             // This must always be zero.   u8int  flags;               // More flags. See documentation.   u16int base_hi;     // The upper 16 bits of the address to jump to.} __attribute__((packed)); struct idt_ptr_struct{   u16int limit;   u32int base; // The address of the first element in our idt_entry_t array.} __attribute__((packed));
IDT The DPL describes the privilege level we expect to be called from. The P bit signifies the entry is present. 	Any descriptor with this bit clear will cause a "Interrupt Not Handled" exception.
IDT extern void isr0 ();...extern void isr31(); idt_entry_t idt_entries[256];idt_ptr_t   idt_ptr; static void init_idt(){   idt_ptr.limit = sizeof(idt_entry_t) * 256 -1;   idt_ptr.base  = (u32int)&idt_entries;   memset(&idt_entries, 0, sizeof(idt_entry_t)*256);//set all to null.   idt_set_gate( 0, (u32int)isr0 , 0x08, 0x8E);   idt_set_gate( 1, (u32int)isr1 , 0x08, 0x8E);   ...   idt_set_gate(31, (u32int)isr32, 0x08, 0x8E);   idt_flush((u32int)&idt_ptr); }
IDT [GLOBAL idt_flush]    ; Allows the C code to call idt_flush().idt_flush:   mov eax, [esp+4]  ; Get the pointer to the IDT, passed as a parameter.    lidt [eax]        ; Load the IDT pointer.   ret
IDT Great! We've got code that will tell the CPU where to find our interrupt handlers - but we haven't written any yet!  When the processor receives an interrupt, it saves the contents of the essential registers (instruction pointer, stack pointer, code and data segments, flags register) to the stack. It then finds the interrupt handler location from our IDT and jumps to it.  some interrupts also push an error code onto the stack. We can't call a common function without a common stack frame, so for those that don't push an error code, we push a dummy one, so the stack is the same.
interrupt.s ISR_NOERRCODE 0ISR_NOERRCODE 1...
interrupt.s ASM common handler function to handle interrupts : ; In isr.c[EXTERN isr_handler]; This is our common ISR stub. It saves the processor state, sets; up for kernel mode segments, calls the C-level fault handler,; and finally restores the stack frame.isr_common_stub:   pusha                    ; Pushes edi,esi,ebp,esp,ebx,edx,ecx,eax   mov ax, ds               ; Lower 16-bits of eax = ds.   push eax                 ; save the data segment descriptor   mov ax, 0x10  ; load the kernel data segment descriptor   mov ds, ax   mov es, ax   mov fs, ax   mov gs, ax   call isr_handler   pop eax        ; reload the original data segment descriptor   mov ds, ax   mov es, ax   mov fs, ax   mov gs, ax   popa                     ; Pops edi,esi,ebp...   add esp, 8     ; Cleans up the pushed error code and pushed ISR number   sti   iret           ; pops 5 things at once: CS, EIP, EFLAGS, SS, and ESP
isr.c typedef struct registers{   u32int ds;                  // Data segment selector   u32int edi, esi, ebp, esp, ebx, edx, ecx, eax; // Pushed by pusha.   u32int int_no, err_code;    // Interrupt number and error code (if applicable)   u32int eip, cs, eflags, useresp, ss; // Pushed by the processor automatically.} registers_t;  // This gets called from our ASM interrupt handler stub.void isr_handler(registers_t regs){   monitor_write("recieved interrupt: ");   monitor_write_dec(regs.int_no);   monitor_put('');}
Testing // Kernel Code: asm volatile ("int $0x3");asm volatile ("int $0x4");  Output:

Más contenido relacionado

La actualidad más candente

Code GPU with CUDA - Identifying performance limiters
Code GPU with CUDA - Identifying performance limitersCode GPU with CUDA - Identifying performance limiters
Code GPU with CUDA - Identifying performance limitersMarina Kolpakova
 
ELC-E Linux Awareness
ELC-E Linux AwarenessELC-E Linux Awareness
ELC-E Linux AwarenessPeter Griffin
 
QEMU - Binary Translation
QEMU - Binary Translation QEMU - Binary Translation
QEMU - Binary Translation Jiann-Fuh Liaw
 
Exploiting the Linux Kernel via Intel's SYSRET Implementation
Exploiting the Linux Kernel via Intel's SYSRET ImplementationExploiting the Linux Kernel via Intel's SYSRET Implementation
Exploiting the Linux Kernel via Intel's SYSRET Implementationnkslides
 
Multiplatform JIT Code Generator for NetBSD by Alexander Nasonov
Multiplatform JIT Code Generator for NetBSD by Alexander NasonovMultiplatform JIT Code Generator for NetBSD by Alexander Nasonov
Multiplatform JIT Code Generator for NetBSD by Alexander Nasonoveurobsdcon
 
CONFidence 2017: Escaping the (sand)box: The promises and pitfalls of modern ...
CONFidence 2017: Escaping the (sand)box: The promises and pitfalls of modern ...CONFidence 2017: Escaping the (sand)box: The promises and pitfalls of modern ...
CONFidence 2017: Escaping the (sand)box: The promises and pitfalls of modern ...PROIDEA
 
Understanding eBPF in a Hurry!
Understanding eBPF in a Hurry!Understanding eBPF in a Hurry!
Understanding eBPF in a Hurry!Ray Jenkins
 
C++ amp on linux
C++ amp on linuxC++ amp on linux
C++ amp on linuxMiller Lee
 
Spectre(v1%2 fv2%2fv4) v.s. meltdown(v3)
Spectre(v1%2 fv2%2fv4) v.s. meltdown(v3)Spectre(v1%2 fv2%2fv4) v.s. meltdown(v3)
Spectre(v1%2 fv2%2fv4) v.s. meltdown(v3)Gavin Guo
 
Geep networking stack-linuxkernel
Geep networking stack-linuxkernelGeep networking stack-linuxkernel
Geep networking stack-linuxkernelKiran Divekar
 
LLVM Register Allocation
LLVM Register AllocationLLVM Register Allocation
LLVM Register AllocationWang Hsiangkai
 
TinyML - 4 speech recognition
TinyML - 4 speech recognition TinyML - 4 speech recognition
TinyML - 4 speech recognition 艾鍗科技
 
netfilter and iptables
netfilter and iptablesnetfilter and iptables
netfilter and iptablesKernel TLV
 
LINUX RS232程式設計
LINUX RS232程式設計LINUX RS232程式設計
LINUX RS232程式設計艾鍗科技
 
CUDA lab's slides of "parallel programming" course
CUDA lab's slides of "parallel programming" courseCUDA lab's slides of "parallel programming" course
CUDA lab's slides of "parallel programming" courseShuai Yuan
 
Code GPU with CUDA - Memory Subsystem
Code GPU with CUDA - Memory SubsystemCode GPU with CUDA - Memory Subsystem
Code GPU with CUDA - Memory SubsystemMarina Kolpakova
 
Implementing Lightweight Networking
Implementing Lightweight NetworkingImplementing Lightweight Networking
Implementing Lightweight Networkingguest6972eaf
 
Cs423 raw sockets_bw
Cs423 raw sockets_bwCs423 raw sockets_bw
Cs423 raw sockets_bwjktjpc
 

La actualidad más candente (20)

Code GPU with CUDA - Identifying performance limiters
Code GPU with CUDA - Identifying performance limitersCode GPU with CUDA - Identifying performance limiters
Code GPU with CUDA - Identifying performance limiters
 
eBPF maps 101
eBPF maps 101eBPF maps 101
eBPF maps 101
 
ELC-E Linux Awareness
ELC-E Linux AwarenessELC-E Linux Awareness
ELC-E Linux Awareness
 
QEMU - Binary Translation
QEMU - Binary Translation QEMU - Binary Translation
QEMU - Binary Translation
 
Exploiting the Linux Kernel via Intel's SYSRET Implementation
Exploiting the Linux Kernel via Intel's SYSRET ImplementationExploiting the Linux Kernel via Intel's SYSRET Implementation
Exploiting the Linux Kernel via Intel's SYSRET Implementation
 
Programar para GPUs
Programar para GPUsProgramar para GPUs
Programar para GPUs
 
Multiplatform JIT Code Generator for NetBSD by Alexander Nasonov
Multiplatform JIT Code Generator for NetBSD by Alexander NasonovMultiplatform JIT Code Generator for NetBSD by Alexander Nasonov
Multiplatform JIT Code Generator for NetBSD by Alexander Nasonov
 
CONFidence 2017: Escaping the (sand)box: The promises and pitfalls of modern ...
CONFidence 2017: Escaping the (sand)box: The promises and pitfalls of modern ...CONFidence 2017: Escaping the (sand)box: The promises and pitfalls of modern ...
CONFidence 2017: Escaping the (sand)box: The promises and pitfalls of modern ...
 
Understanding eBPF in a Hurry!
Understanding eBPF in a Hurry!Understanding eBPF in a Hurry!
Understanding eBPF in a Hurry!
 
C++ amp on linux
C++ amp on linuxC++ amp on linux
C++ amp on linux
 
Spectre(v1%2 fv2%2fv4) v.s. meltdown(v3)
Spectre(v1%2 fv2%2fv4) v.s. meltdown(v3)Spectre(v1%2 fv2%2fv4) v.s. meltdown(v3)
Spectre(v1%2 fv2%2fv4) v.s. meltdown(v3)
 
Geep networking stack-linuxkernel
Geep networking stack-linuxkernelGeep networking stack-linuxkernel
Geep networking stack-linuxkernel
 
LLVM Register Allocation
LLVM Register AllocationLLVM Register Allocation
LLVM Register Allocation
 
TinyML - 4 speech recognition
TinyML - 4 speech recognition TinyML - 4 speech recognition
TinyML - 4 speech recognition
 
netfilter and iptables
netfilter and iptablesnetfilter and iptables
netfilter and iptables
 
LINUX RS232程式設計
LINUX RS232程式設計LINUX RS232程式設計
LINUX RS232程式設計
 
CUDA lab's slides of "parallel programming" course
CUDA lab's slides of "parallel programming" courseCUDA lab's slides of "parallel programming" course
CUDA lab's slides of "parallel programming" course
 
Code GPU with CUDA - Memory Subsystem
Code GPU with CUDA - Memory SubsystemCode GPU with CUDA - Memory Subsystem
Code GPU with CUDA - Memory Subsystem
 
Implementing Lightweight Networking
Implementing Lightweight NetworkingImplementing Lightweight Networking
Implementing Lightweight Networking
 
Cs423 raw sockets_bw
Cs423 raw sockets_bwCs423 raw sockets_bw
Cs423 raw sockets_bw
 

Destacado

Social Issues
Social IssuesSocial Issues
Social Issuesmpurri
 
Expeditie mont blanc
Expeditie mont blancExpeditie mont blanc
Expeditie mont blancIlse7
 
Debatderbatter
DebatderbatterDebatderbatter
DebatderbatterMusehjerte
 
Los Angeles HTML5 User Group Meeting Ask the Expert Session
Los Angeles HTML5 User Group Meeting Ask the Expert SessionLos Angeles HTML5 User Group Meeting Ask the Expert Session
Los Angeles HTML5 User Group Meeting Ask the Expert SessionPeter Lubbers
 

Destacado (7)

Social Issues
Social IssuesSocial Issues
Social Issues
 
Kunst
KunstKunst
Kunst
 
Expeditie mont blanc
Expeditie mont blancExpeditie mont blanc
Expeditie mont blanc
 
Debatderbatter
DebatderbatterDebatderbatter
Debatderbatter
 
Kunst
KunstKunst
Kunst
 
Los Angeles HTML5 User Group Meeting Ask the Expert Session
Los Angeles HTML5 User Group Meeting Ask the Expert SessionLos Angeles HTML5 User Group Meeting Ask the Expert Session
Los Angeles HTML5 User Group Meeting Ask the Expert Session
 
Sports exhibition 2
Sports exhibition 2Sports exhibition 2
Sports exhibition 2
 

Similar a Roll your own toy unix clone os

Let's trace Linux Lernel with KGDB @ COSCUP 2021
Let's trace Linux Lernel with KGDB @ COSCUP 2021Let's trace Linux Lernel with KGDB @ COSCUP 2021
Let's trace Linux Lernel with KGDB @ COSCUP 2021Jian-Hong Pan
 
Working with core dump
Working with core dumpWorking with core dump
Working with core dumpThierry Gayet
 
Bootstrap process of u boot (NDS32 RISC CPU)
Bootstrap process of u boot (NDS32 RISC CPU)Bootstrap process of u boot (NDS32 RISC CPU)
Bootstrap process of u boot (NDS32 RISC CPU)Macpaul Lin
 
U-Boot presentation 2013
U-Boot presentation  2013U-Boot presentation  2013
U-Boot presentation 2013Wave Digitech
 
LAS16-403 - GDB Linux Kernel Awareness
LAS16-403 - GDB Linux Kernel Awareness LAS16-403 - GDB Linux Kernel Awareness
LAS16-403 - GDB Linux Kernel Awareness Peter Griffin
 
LAS16-403: GDB Linux Kernel Awareness
LAS16-403: GDB Linux Kernel AwarenessLAS16-403: GDB Linux Kernel Awareness
LAS16-403: GDB Linux Kernel AwarenessLinaro
 
[2007 CodeEngn Conference 01] dual5651 - Windows 커널단의 후킹
[2007 CodeEngn Conference 01] dual5651 - Windows 커널단의 후킹[2007 CodeEngn Conference 01] dual5651 - Windows 커널단의 후킹
[2007 CodeEngn Conference 01] dual5651 - Windows 커널단의 후킹GangSeok Lee
 
Vpu technology &gpgpu computing
Vpu technology &gpgpu computingVpu technology &gpgpu computing
Vpu technology &gpgpu computingArka Ghosh
 
U-Boot Porting on New Hardware
U-Boot Porting on New HardwareU-Boot Porting on New Hardware
U-Boot Porting on New HardwareRuggedBoardGroup
 
Tema3_Introduction_to_CUDA_C.pdf
Tema3_Introduction_to_CUDA_C.pdfTema3_Introduction_to_CUDA_C.pdf
Tema3_Introduction_to_CUDA_C.pdfpepe464163
 
Track c-High speed transaction-based hw-sw coverification -eve
Track c-High speed transaction-based hw-sw coverification -eveTrack c-High speed transaction-based hw-sw coverification -eve
Track c-High speed transaction-based hw-sw coverification -evechiportal
 
Virtual platform
Virtual platformVirtual platform
Virtual platformsean chen
 
Vpu technology &gpgpu computing
Vpu technology &gpgpu computingVpu technology &gpgpu computing
Vpu technology &gpgpu computingArka Ghosh
 
Vpu technology &gpgpu computing
Vpu technology &gpgpu computingVpu technology &gpgpu computing
Vpu technology &gpgpu computingArka Ghosh
 
Vpu technology &gpgpu computing
Vpu technology &gpgpu computingVpu technology &gpgpu computing
Vpu technology &gpgpu computingArka Ghosh
 
Intro to GPGPU with CUDA (DevLink)
Intro to GPGPU with CUDA (DevLink)Intro to GPGPU with CUDA (DevLink)
Intro to GPGPU with CUDA (DevLink)Rob Gillen
 
LCU14 302- How to port OP-TEE to another platform
LCU14 302- How to port OP-TEE to another platformLCU14 302- How to port OP-TEE to another platform
LCU14 302- How to port OP-TEE to another platformLinaro
 
Comp 129 final exam 100% correct answers
Comp 129 final exam 100% correct answersComp 129 final exam 100% correct answers
Comp 129 final exam 100% correct answersProfessorLance
 
CUDA by Example : CUDA C on Multiple GPUs : Notes
CUDA by Example : CUDA C on Multiple GPUs : NotesCUDA by Example : CUDA C on Multiple GPUs : Notes
CUDA by Example : CUDA C on Multiple GPUs : NotesSubhajit Sahu
 

Similar a Roll your own toy unix clone os (20)

Let's trace Linux Lernel with KGDB @ COSCUP 2021
Let's trace Linux Lernel with KGDB @ COSCUP 2021Let's trace Linux Lernel with KGDB @ COSCUP 2021
Let's trace Linux Lernel with KGDB @ COSCUP 2021
 
Working with core dump
Working with core dumpWorking with core dump
Working with core dump
 
Bootstrap process of u boot (NDS32 RISC CPU)
Bootstrap process of u boot (NDS32 RISC CPU)Bootstrap process of u boot (NDS32 RISC CPU)
Bootstrap process of u boot (NDS32 RISC CPU)
 
U-Boot presentation 2013
U-Boot presentation  2013U-Boot presentation  2013
U-Boot presentation 2013
 
LAS16-403 - GDB Linux Kernel Awareness
LAS16-403 - GDB Linux Kernel Awareness LAS16-403 - GDB Linux Kernel Awareness
LAS16-403 - GDB Linux Kernel Awareness
 
LAS16-403: GDB Linux Kernel Awareness
LAS16-403: GDB Linux Kernel AwarenessLAS16-403: GDB Linux Kernel Awareness
LAS16-403: GDB Linux Kernel Awareness
 
[2007 CodeEngn Conference 01] dual5651 - Windows 커널단의 후킹
[2007 CodeEngn Conference 01] dual5651 - Windows 커널단의 후킹[2007 CodeEngn Conference 01] dual5651 - Windows 커널단의 후킹
[2007 CodeEngn Conference 01] dual5651 - Windows 커널단의 후킹
 
Vpu technology &gpgpu computing
Vpu technology &gpgpu computingVpu technology &gpgpu computing
Vpu technology &gpgpu computing
 
U-Boot Porting on New Hardware
U-Boot Porting on New HardwareU-Boot Porting on New Hardware
U-Boot Porting on New Hardware
 
Tema3_Introduction_to_CUDA_C.pdf
Tema3_Introduction_to_CUDA_C.pdfTema3_Introduction_to_CUDA_C.pdf
Tema3_Introduction_to_CUDA_C.pdf
 
Track c-High speed transaction-based hw-sw coverification -eve
Track c-High speed transaction-based hw-sw coverification -eveTrack c-High speed transaction-based hw-sw coverification -eve
Track c-High speed transaction-based hw-sw coverification -eve
 
Virtual platform
Virtual platformVirtual platform
Virtual platform
 
Vpu technology &gpgpu computing
Vpu technology &gpgpu computingVpu technology &gpgpu computing
Vpu technology &gpgpu computing
 
Vpu technology &gpgpu computing
Vpu technology &gpgpu computingVpu technology &gpgpu computing
Vpu technology &gpgpu computing
 
Vpu technology &gpgpu computing
Vpu technology &gpgpu computingVpu technology &gpgpu computing
Vpu technology &gpgpu computing
 
Intro to GPGPU with CUDA (DevLink)
Intro to GPGPU with CUDA (DevLink)Intro to GPGPU with CUDA (DevLink)
Intro to GPGPU with CUDA (DevLink)
 
LCU14 302- How to port OP-TEE to another platform
LCU14 302- How to port OP-TEE to another platformLCU14 302- How to port OP-TEE to another platform
LCU14 302- How to port OP-TEE to another platform
 
Comp 129 final exam 100% correct answers
Comp 129 final exam 100% correct answersComp 129 final exam 100% correct answers
Comp 129 final exam 100% correct answers
 
CUDA by Example : CUDA C on Multiple GPUs : Notes
CUDA by Example : CUDA C on Multiple GPUs : NotesCUDA by Example : CUDA C on Multiple GPUs : Notes
CUDA by Example : CUDA C on Multiple GPUs : Notes
 
Linux Kernel Debugging
Linux Kernel DebuggingLinux Kernel Debugging
Linux Kernel Debugging
 

Último

Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3JemimahLaneBuaron
 
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...Sapna Thakur
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13Steve Thomason
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationnomboosow
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdfQucHHunhnh
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104misteraugie
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdfQucHHunhnh
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajanpragatimahajan3
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
Russian Call Girls in Andheri Airport Mumbai WhatsApp 9167673311 💞 Full Nigh...
Russian Call Girls in Andheri Airport Mumbai WhatsApp  9167673311 💞 Full Nigh...Russian Call Girls in Andheri Airport Mumbai WhatsApp  9167673311 💞 Full Nigh...
Russian Call Girls in Andheri Airport Mumbai WhatsApp 9167673311 💞 Full Nigh...Pooja Nehwal
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
9548086042 for call girls in Indira Nagar with room service
9548086042  for call girls in Indira Nagar  with room service9548086042  for call girls in Indira Nagar  with room service
9548086042 for call girls in Indira Nagar with room servicediscovermytutordmt
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsTechSoup
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfchloefrazer622
 
Disha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfDisha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfchloefrazer622
 

Último (20)

Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3
 
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communication
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajan
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
Russian Call Girls in Andheri Airport Mumbai WhatsApp 9167673311 💞 Full Nigh...
Russian Call Girls in Andheri Airport Mumbai WhatsApp  9167673311 💞 Full Nigh...Russian Call Girls in Andheri Airport Mumbai WhatsApp  9167673311 💞 Full Nigh...
Russian Call Girls in Andheri Airport Mumbai WhatsApp 9167673311 💞 Full Nigh...
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
9548086042 for call girls in Indira Nagar with room service
9548086042  for call girls in Indira Nagar  with room service9548086042  for call girls in Indira Nagar  with room service
9548086042 for call girls in Indira Nagar with room service
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdf
 
Disha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfDisha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdf
 

Roll your own toy unix clone os

  • 1. Roll your own toy UNIX-clone OS By Ahmed Essam www.eramax.org
  • 2. Table of contents 1. Environment setup2. Genesis3. The Screen4. The GDT and IDT
  • 3.
  • 4. Ld
  • 6.
  • 8.
  • 9. (VM setup)1. Environment setup We will use Bochs (an open-source x86-64 emulator). We need a bochs configuration file (bochsrc.txt). megs: 32floppya: 1_44="myOs2.bin", status=insertedboot: floppylog: bochsout.txtclock: sync=realtimecpu: ips=500000 keyboard_paste_delay: 100000
  • 10. Useful scripts Makefile making (compiling) our project. Link.ld link files together into one ELF binary (Kernel). update_image.sh poke your new kernel binary into the floppy image file. run_bochs.sh mounts the correct loopback device, runs bochs, then unmounts.
  • 11. 2. Genesis2.1 - The boot code MBOOT_PAGE_ALIGN    equ 1<<0    ; Load kernel and modules on a page boundaryMBOOT_MEM_INFO      equ 1<<1    ; Provide your kernel with memory infoMBOOT_HEADER_MAGIC  equ 0x1BADB002 ; Multiboot Magic value; NOTE: We do not use MBOOT_AOUT_KLUDGE. It means that GRUB does not; pass us a symbol table.MBOOT_HEADER_FLAGS  equ MBOOT_PAGE_ALIGN | MBOOT_MEM_INFOMBOOT_CHECKSUM      equ -(MBOOT_HEADER_MAGIC + MBOOT_HEADER_FLAGS)[BITS 32]                       ; All instructions should be 32-bit.[GLOBAL mboot]                  ; Make 'mboot' accessible from C.[EXTERN code]                   ; Start of the '.text' section.[EXTERN bss]                    ; Start of the .bss section.[EXTERN end]                    ; End of the last loadable section.mboot:  dd  MBOOT_HEADER_MAGIC        ; GRUB will search for this value on each                                ; 4-byte boundary in your kernel file  dd  MBOOT_HEADER_FLAGS        ; How GRUB should load your file / settings  dd  MBOOT_CHECKSUM            ; To ensure that the above values are correct   
  • 12. 2.1 - The boot code (Cont)   dd  mboot                     ; Location of this descriptor  dd  code                      ; Start of kernel '.text' (code) section.  dd  bss                       ; End of kernel '.data' section.  dd  end                       ; End of kernel.  dd  start                     ; Kernel entry point (initial EIP).[GLOBAL start]                  ; Kernel entry point.[EXTERN main]                   ; This is the entry point of our C codestart:  push    ebx                   ; Load multiboot header location  ; Execute the kernel:  cli                         ; Disable interrupts.  call main                   ; call our main() function.  jmp $                       ; Enter an infinite loop, to stop the processor                              ; executing whatever rubbish is in the memory                              ; after our kernel!
  • 13. 2.3. Adding some C code // main.c int main(struct multiboot *mboot_ptr){  // Kernel Code.  return 0xDEADBABA;}
  • 14. common.c functions for writing to and reading from the I/O bus, and some typedefs : typedef unsigned int   u32int;typedef          int   s32int;typedef unsigned short u16int;typedef          short s16int;typedef unsigned char  u8int;typedef          char  s8int; void outb(u16int port, u8int value){asm volatile ("outb %1, %0" : : "dN" (port), "a" (value)); }u8int inb(u16int port){   u8int ret;   asm volatile("inb %1, %0" : "=a" (ret) : "dN" (port));   return ret;}u16int inw(u16int port){   u16int ret;   asm volatile ("inw %1, %0" : "=a" (ret) : "dN" (port));   return ret;}
  • 15. 3. The Screen 3.1. The theory Your kernel gets booted by GRUB in text mode. That is, it has available to it a framebuffer (area of memory) that controls a screen of characters (not pixels) 80 wide by 25 high, at address 0xB8000. Framebuffer is not actually normal RAM. It is part of the VGA controller's dedicated video memory that has been memory-mapped via hardware into your linear address space.
  • 16. 3.1. The theory (Cont) The framebuffer is just an array of 16-bit words, each 16-bit value representing the display of one character. The offset from the start of the framebuffer of the word that specifies a character at position x, y is: (y * 80 + x) * 2 8 bits are used to represent a character. foreground and background colours (4 bits each).
  • 17. 3.1. The theory (Cont)
  • 18. 3.2.2. The monitor code Moving the cursor static void move_cursor() Scrolling the screen static void scroll() Writing a character to the screen void monitor_put(char c) location = video_memory + (cursor_y*80 + cursor_x);*location = c | attribute; Clearing the screen u16int blank = 0x20 /* space */ | (attributeByte << 8);    for (i = 0; i < 80*25; i++)    {         video_memory[i] = blank;    }
  • 19. 3.2.2. The monitor code (Cont) Writing a string void monitor_write(char *c){    int i = 0;    while (c[i])    {        monitor_put(c[i++]);    }} //-------- Kernel Code : monitor_clear();monitor_write("Hello, world!");
  • 21. 4. The GDT and IDT 4.1. The Global Descriptor Table (theory) are arrays of flags and bit values describing the operation of the segmentation system. Every memory access is evaluated with respect to a segment. That is, the memory address is added to the segment's base address, and checked against the segment's length.
  • 22. GDT there is one thing that segmentation can do that paging can't, and that's set the ring levels. A ring is a privilege level - zero being the most privileged, and three being the least. Processes in ring zero are said to be running in kernel-mode, or supervisor-mode, because they can use instructions like sti and cli, something which most processes can't. A segment descriptor carries inside it a number representing the ring level it applies to.
  • 23. The Global Descriptor Table (practical) A GDT entry looks like struct gdt_entry_struct{   u16int limit_low;           // The lower 16 bits of the limit.   u16int base_low;            // The lower 16 bits of the base.   u8int  base_middle;         // The next 8 bits of the base.   u8int  access;              // Access flags, determine what ring //this segment can be used in.   u8int  granularity;   u8int  base_high;           // The last 8 bits of the base.} __attribute__((packed));
  • 24. GDT u8int  access;      P    Is segment present? (1 = Yes)DPL    Descriptor privilege level - Ring 0 - 3.DT    Descriptor typeType    Segment type : code segment / data segment.
  • 25. GDT To pass the GDT Table ,we pass the Pointer to this table to the CPU and pass its limit(length). So we must use this struct : struct gdt_ptr_struct{   u16int limit;               // The upper 16 bits of all selector limits.   u32int base;                // The address of the first gdt_entry_t }
  • 26. GDT gdt_entry_t gdt_entries[5];gdt_ptr_t   gdt_ptr; static void init_gdt(){   gdt_ptr.limit = (sizeof(gdt_entry_t) * 5) - 1;   gdt_ptr.base  = (u32int)&gdt_entries;   gdt_set_gate(0, 0, 0, 0, 0);                // Null segment   gdt_set_gate(1, 0, 0xFFFFFFFF, 0x9A, 0xCF); // Code segment   gdt_set_gate(2, 0, 0xFFFFFFFF, 0x92, 0xCF); // Data segment   gdt_set_gate(3, 0, 0xFFFFFFFF, 0xFA, 0xCF); // User mode code segment   gdt_set_gate(4, 0, 0xFFFFFFFF, 0xF2, 0xCF); // User mode data segment   gdt_flush((u32int)&gdt_ptr);}
  • 28. 4.3. The Interrupt Descriptor Table (theory) There are times when you want to interrupt the processor. You want to stop it doing what it is doing, and force it to do something different. An example of this is when an timer or keyboard interrupt request (IRQ) fires. The processor can register 'signal handlers' (interrupt handlers) that deal with the interrupt, then return to the code that was running before it fired. Interrupts can be fired externally, via IRQs, or internally, via the 'int n' instruction. The Interrupt Descriptor Table tells the processor where to find handlers for each interrupt. It is very similar to the GDT. It is just an array of entries, each one corresponding to an interrupt number. There are 256 possible interrupt numbers, so 256 must be defined. If an interrupt occurs and there is no entry for it (even a NULL entry is fine), the processor will panic and reset.
  • 29. Faults, traps and exceptions The special, CPU-dedicated 32 interrupts : 0 - Division by zero exception 1 - Debug exception 2 - Non maskable interrupt 3 - Breakpoint exception 4 - 'Into detected overflow' 5 - Out of bounds exception 6 - Invalid opcode exception 7 - No coprocessor exception 8 - Double fault (pushes an error code) 9 - Coprocessor segment overrun 10 - Bad TSS (pushes an error code) 11 - Segment not present (pushes an error code) 12 - Stack fault (pushes an error code) 13 - General protection fault (pushes an error code) 14 - Page fault (pushes an error code) 15 - Unknown interrupt exception 16 - Coprocessor fault 17 - Alignment check exception 18 - Machine check exception 19-31 - Reserved
  • 30. 4.4. The Interrupt Descriptor Table (practice) // A struct describing an interrupt gate.struct idt_entry_struct{   u16int base_lo;             // The lower 16 bits of the address to //jump to when this interrupt fires.   u16int sel;                 // Kernel segment selector.   u8int  always0;             // This must always be zero.   u8int  flags;               // More flags. See documentation.   u16int base_hi;     // The upper 16 bits of the address to jump to.} __attribute__((packed)); struct idt_ptr_struct{   u16int limit;   u32int base; // The address of the first element in our idt_entry_t array.} __attribute__((packed));
  • 31. IDT The DPL describes the privilege level we expect to be called from. The P bit signifies the entry is present. Any descriptor with this bit clear will cause a "Interrupt Not Handled" exception.
  • 32. IDT extern void isr0 ();...extern void isr31(); idt_entry_t idt_entries[256];idt_ptr_t   idt_ptr; static void init_idt(){   idt_ptr.limit = sizeof(idt_entry_t) * 256 -1;   idt_ptr.base  = (u32int)&idt_entries;   memset(&idt_entries, 0, sizeof(idt_entry_t)*256);//set all to null.   idt_set_gate( 0, (u32int)isr0 , 0x08, 0x8E);   idt_set_gate( 1, (u32int)isr1 , 0x08, 0x8E);   ...   idt_set_gate(31, (u32int)isr32, 0x08, 0x8E);   idt_flush((u32int)&idt_ptr); }
  • 33. IDT [GLOBAL idt_flush]    ; Allows the C code to call idt_flush().idt_flush:   mov eax, [esp+4]  ; Get the pointer to the IDT, passed as a parameter.    lidt [eax]        ; Load the IDT pointer.   ret
  • 34. IDT Great! We've got code that will tell the CPU where to find our interrupt handlers - but we haven't written any yet! When the processor receives an interrupt, it saves the contents of the essential registers (instruction pointer, stack pointer, code and data segments, flags register) to the stack. It then finds the interrupt handler location from our IDT and jumps to it. some interrupts also push an error code onto the stack. We can't call a common function without a common stack frame, so for those that don't push an error code, we push a dummy one, so the stack is the same.
  • 36. interrupt.s ASM common handler function to handle interrupts : ; In isr.c[EXTERN isr_handler]; This is our common ISR stub. It saves the processor state, sets; up for kernel mode segments, calls the C-level fault handler,; and finally restores the stack frame.isr_common_stub:   pusha                    ; Pushes edi,esi,ebp,esp,ebx,edx,ecx,eax   mov ax, ds               ; Lower 16-bits of eax = ds.   push eax                 ; save the data segment descriptor   mov ax, 0x10  ; load the kernel data segment descriptor   mov ds, ax   mov es, ax   mov fs, ax   mov gs, ax   call isr_handler   pop eax        ; reload the original data segment descriptor   mov ds, ax   mov es, ax   mov fs, ax   mov gs, ax   popa                     ; Pops edi,esi,ebp...   add esp, 8     ; Cleans up the pushed error code and pushed ISR number   sti   iret           ; pops 5 things at once: CS, EIP, EFLAGS, SS, and ESP
  • 37. isr.c typedef struct registers{   u32int ds;                  // Data segment selector   u32int edi, esi, ebp, esp, ebx, edx, ecx, eax; // Pushed by pusha.   u32int int_no, err_code;    // Interrupt number and error code (if applicable)   u32int eip, cs, eflags, useresp, ss; // Pushed by the processor automatically.} registers_t; // This gets called from our ASM interrupt handler stub.void isr_handler(registers_t regs){   monitor_write("recieved interrupt: ");   monitor_write_dec(regs.int_no);   monitor_put('');}
  • 38. Testing // Kernel Code: asm volatile ("int $0x3");asm volatile ("int $0x4"); Output:
  • 39.
  • 42. Intel® 64 and IA-32 Architectures Software Developer's Manuals http://www.intel.com/products/processor/manuals/
  • 43. Memory Modes : Real Mode and Protected Mode http://3asfh.net/vb/showthread.php?t=37922
  • 44. References(2) Making a Simple C kernel with Basic printf and clearscreen Functions http://www.osdever.net/tutorials/basickernel.php