Skip to content

Instantly share code, notes, and snippets.

@gwoplock
Created May 12, 2017 00:22
Show Gist options
  • Save gwoplock/2e2d68dbecce8e0ad9f91c7c78a977ad to your computer and use it in GitHub Desktop.
Save gwoplock/2e2d68dbecce8e0ad9f91c7c78a977ad to your computer and use it in GitHub Desktop.
c++ GDT
/*
* GDT.c
*
* Created on: Sep 15, 2016
* Author: garrett
*/
#include "GDT.h"
gdtEntry encodeGdtEntry(uint32_t size, uint32_t baseAddr, uint8_t access,
uint8_t flags) {
//get me some of those GDTs
gdtEntry toReturn;
//lower part of lim
toReturn.limit_1 = size & 0xFFFF;
//lower base
toReturn.base_1 = baseAddr & 0xFFFF;
//mid base
toReturn.base_2 |= ((baseAddr & 0xFF0000) >> 16);
//who can get in
toReturn.access = access;
//upper limit FUCK YOU INTEL
toReturn.limit_2_flags = (size & 0xF0000) >> 16;
//flags. (attached to upper lim b/c intel)
toReturn.limit_2_flags |= (flags << 4) & 0xF0;
//upper base
toReturn.base_3 = ((baseAddr & 0xFF000000) >> 24);
return toReturn;
}
gdtEntry gdt[3];
void loadGdt(gdtEntry* toLoad, size_t lengthOfArr) {
//get size, -1 because intell hates you
size_t sizeOfGdt = lengthOfArr * sizeof(gdtEntry) - 1;
//get the info to tell cpu about the GDT
static gdtDiescriptor gdtd;
gdtd.size = sizeOfGdt;
gdtd.offset = (uint32_t) toLoad;
//load that shit
asm ("LGDT %[gdt]" : : [gdt] "m" (gdtd));
}
void buildGdt(){
//null. just rember you need this because intel hates you
gdt[0] = encodeGdtEntry(0, 0, 0, 0);
//code
gdt[1] = encodeGdtEntry(0xffffffff, 0, 0x9A, 0xCF);
//data
gdt[2] = encodeGdtEntry(0xffffffff, 0, 0x92, 0xCF);
}
/*
* GDT.h
*
* Created on: Sep 15, 2016
* Author: garrett
*/
#ifndef GDT_H_
#define GDT_H_
#include "../global.h"
typedef struct __attribute__((__packed__)) {
uint16_t limit_1;
uint16_t base_1;
uint8_t base_2;
uint8_t access;
uint8_t limit_2_flags;
uint8_t base_3;
} gdtEntry;
typedef struct __attribute__((__packed__)) {
uint16_t size;
uint32_t offset;
} gdtDiescriptor;
gdtEntry gdt[3];
gdtEntry encodeGdtEntry(uint32_t maxAddr, uint32_t baseAddr, uint8_t access,
uint8_t flags);
void loadGdt(gdtEntry* toLoad, size_t size);
void buildGdt();
#endif /* GDT_H_ */
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment