Now put the ESP, GDT and other content into the kernel, we can now use C language, as long as we can use C, we avoid the assembly.
Here's a look at the key code for switching stacks and GDT:
; Import function Externcstart; Import global variable externgdt_ptr[section. BSS]STACKSPACERESB2 * 1024StackTop:; Top of the stack; Move esp from LOADER to Kernelmovesp, Stacktop; The stack is sgdt[gdt_ptr in the BSS section]; Gdt_ptrcallcstart will be used in Cstart (); Change the gdt_ptr in this function to point to the new gdtlgdt[gdt_ptr]; Using the new GDT
The last 4 statements complete the task of switching the stack and changing the GDT. Stacktop is defined in the. BSS segment, and the stack size is 2KB.
publicvoid*memcpy (void* pDst, void* pSrc, int isize); Publicvoiddisp_str (char * pszinfo); publicu8gdt_ptr[6];/* 0~15:limit 16~47:base */publicdescriptorgdt[gdt_size]; public void Cstart () {disp_str ("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n" "-----\" cstart\ "begins-----\ n");/* Will LOADER the GDT Copy to the new GDT */memcpy (&GDT,/* new GDT */ (void*) (* ((u32*) (&gdt_ptr[2))),/* Base of the old GDT */< c5/>* ((u16*) (&gdt_ptr[0)) + 1// Limit of old GDT */);/* gdt_ptr[6] Total 6 bytes: 0~15:limit 16~47:base. The parameter to use as a SGDT/LGDT. */u16* p_gdt_limit = (u16*) (&gdt_ptr[0]); u32* p_gdt_base = (u32*) (&gdt_ptr[2]); *p_gdt_limit = GDT_SIZE * sizeof (descriptor)-1;*p_gdt_base = (u32) &gdt;}
The function first copies all the original GDT in the loader to the new GDT, and then replaces the contents of the gdt_ptr with the new GDT's base address and bounds. sgdt--holds the global descriptor, the value of gdt_ptr[2] is itself an address, so the front strap (void*) represents a pointer. memcpy is used with void* because it requires a byte copy of one byte.
Compile:
NASM Boot.asm-o Boot.bin
NASM Loader.asm-o Loader.bin
Nasm-f Elf-o KERNEL.O kernel.asm
Nasm-f Elf-o STRING.O string.asm
Nasm-f Elf-o KLIBA.O kliba.asm
Gcc-m32-c-fno-builtin-o START.O start.c
----
DD if=boot.bin of=a.img bs=512 count=1 conv=notrunc
sudo mount-o loop a.img/mnt/hgfs/
sudo cp loader.bin/mnt/hgfs/-V
sudo umount/mnt/hgfs/
----
Ld-m elf_i386-s-ttext 0x30400-o kernel.bin kernel.o string.o start.o KLIBA.O
sudo mount-o loop a.img/mnt/hgfs/
sudo cp kernel.bin/mnt/hgfs/-V
sudo umount/mnt/hgfs/
The results of the operation are as follows:
" Source "
Linux kernel family -12.d. Expansion kernel for operating system development