Guest User

Code

a guest
Jun 21st, 2012
12
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.68 KB | None | 0 0
  1. #define GDT_ENTRIES 5
  2.  
  3. uint64_t gdt[GDT_ENTRIES];
  4.  
  5. #define GDT_FLAG_DATASEG 0x02
  6. #define GDT_FLAG_CODESEG 0x0a
  7. #define GDT_FLAG_TSS     0x09
  8.  
  9. #define GDT_FLAG_SEGMENT 0x10
  10. #define GDT_FLAG_RING0   0x00
  11. #define GDT_FLAG_RING3   0x60
  12. #define GDT_FLAG_PRESENT 0x80
  13.  
  14. #define GDT_FLAG_4K_GRAN 0x800
  15. #define GDT_FLAG_32_BIT  0x400
  16.  
  17. void init_gdt(void)
  18. {
  19.     set_entry(0, 0, 0, 0);
  20.     set_entry(1, 0, 0xfffff, GDT_FLAG_SEGMENT | GDT_FLAG_32_BIT |
  21.         GDT_FLAG_CODESEG | GDT_FLAG_4K_GRAN | GDT_FLAG_PRESENT);
  22.     set_entry(2, 0, 0xfffff, GDT_FLAG_SEGMENT | GDT_FLAG_32_BIT |
  23.         GDT_FLAG_DATASEG | GDT_FLAG_4K_GRAN | GDT_FLAG_PRESENT);
  24.     set_entry(3, 0, 0xfffff, GDT_FLAG_SEGMENT | GDT_FLAG_32_BIT |
  25.         GDT_FLAG_CODESEG | GDT_FLAG_4K_GRAN | GDT_FLAG_PRESENT | GDT_FLAG_RING3);
  26.     set_entry(4, 0, 0xfffff, GDT_FLAG_SEGMENT | GDT_FLAG_32_BIT |
  27.         GDT_FLAG_DATASEG | GDT_FLAG_4K_GRAN | GDT_FLAG_PRESENT | GDT_FLAG_RING3);
  28.  
  29.     load_gdt();
  30. }
  31.  
  32. void load_gdt() {
  33.     struct {
  34.           uint16_t limit;
  35.           void* pointer;
  36.     } __attribute__((packed)) gdtp = {
  37.           .limit = GDT_ENTRIES * 8 - 1,
  38.           .pointer = gdt,
  39.     };
  40.     asm volatile("lgdt %0" : : "m" (gdtp));
  41.  
  42.     __asm__ ("mov $0x10, %ax"
  43.                      "mov %ax, %ds"
  44.                      "mov %ax, %es"
  45.                      "mov %ax, %fs"
  46.                "mov %ax, %gs"
  47.                "mov %ax, %ss"
  48.                "ljmp $0x8, $.1"
  49.                ".1:")
  50. }
  51.  
  52. void set_entry(int i, unsigned int base, unsigned int limit, int flags)
  53. {
  54.     gdt[i] = limit & 0xffffLL;
  55.     gdt[i] |= (base & 0xffffffLL) << 16;
  56.     gdt[i] |= (flags & 0xffLL) << 40;
  57.     gdt[i] |= ((limit >> 16) & 0xfLL) << 48;
  58.     gdt[i] |= ((flags >> 8 )& 0xffLL) << 52;
  59.     gdt[i] |= ((base >> 24) & 0xffLL) << 56;
  60. }
Advertisement
Add Comment
Please, Sign In to add comment