Guest User

GDT C code

a guest
Sep 26th, 2016
201
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.83 KB | None | 0 0
  1. #include <stdint.h>
  2. #include "gdt.h"
  3.  
  4. /* defines a GDT entry */
  5.  
  6. struct gdt_descriptor {
  7.     uint16_t limit_low;         /* bits 0-15 of segment limit */
  8.     uint16_t base_low;          /* bits 0-23 */
  9.     uint8_t base_middle;        /* of base address */
  10.     uint8_t access;             /* access byte */
  11.     uint8_t granularity;            /* granularity */
  12.     uint8_t base_high;          /* bits 24-32 of base address */
  13. } __attribute__ ((packed));
  14.  
  15. /* defined GDT pointer including limit:
  16.  * the max bytes taken up by the GDT - 1
  17. */
  18.  
  19. struct gdt_pointer {
  20.     uint16_t limit;             /* size of GDT */
  21.     uint32_t base;              /* base address of GDT */
  22. } __attribute__ ((packed));
  23.  
  24. struct gdt_descriptor  gdt_desc[MAX_DESCRIPTORS];
  25. struct gdt_pointer     gdt_p;
  26.  
  27. int gdt_set_descriptor(uint32_t i, uint64_t base, uint64_t limit, uint8_t access, uint8_t granularity)
  28. {
  29.     if (i > MAX_DESCRIPTORS)
  30.         return
  31.    
  32.     /* null out the descriptor */
  33.    
  34.     memset((void *) gdt_desc, 0, sizeof(gdt_desc));
  35.    
  36.     /* Setup the descriptor base address */
  37.     gdt_desc[i].base_low     = (base & 0xFFFF);
  38.     gdt_desc[i].base_middle  = (base >> 16) & 0xFF;
  39.     gdt_desc[i].base_high    = (base >> 24) & 0xFF;
  40.  
  41.     /* Setup the descriptor limits */
  42.     gdt_desc[i].limit_low    = (limit & 0xFFFF);
  43.     gdt_desc[i].granularity  = ((limit >> 16) & 0x0F);
  44.  
  45.     /* Finally, set up the granularity and access flags */
  46.     gdt_desc[i].granularity |= (granularity & 0xF0);
  47.     gdt_desc[i].access       = access;
  48. }
  49.  
  50. int gdt_install()
  51. {
  52.     gdt_p.limit = (sizeof(gdt_desc) * MAX_DESCRIPTORS) - 1;
  53.     gdt_p.base  = (uint32_t) &gdt_desc;
  54.    
  55.     /* set null descriptor */
  56.    
  57.     gdt_set_descriptor(0, 0, 0, 0, 0);
  58.    
  59.     /* set code descriptor */
  60.    
  61.     gdt_set_descriptor(1, 0, 0xFFFFFFFF, 0x9A, 0xCF);
  62.    
  63.     /* set data descriptor */
  64.    
  65.     gdt_set_descriptor(2, 0, 0xFFFFFFFF, 0x92, 0xCF);
  66.    
  67.     /* install the GDT */
  68.    
  69.     _gdt_install();
  70. }
Advertisement
Add Comment
Please, Sign In to add comment