Thursday, 28 November 2013

Get address and size of Global Descriptor Table

I just read about GDT which translates logical address into linear address in linux. Out of curiosity, Let's find out the address and size of GDT.

Global Descriptor Table (GDT) use for memory segmentation in protected mode. GDT is array contains segment descriptors, local descriptors table and task state descriptor. GDT holds 8-byte long descriptors which has information about segment's base address, limit and access privileges.
In uniprocessor systems there is only one GDT, while in multiprocessor systems there is one GDT for every CPU in the system.
gdtr control register holds the 16-bit size and 32-bit address of GDT. gdtr has 48-bit fields.

|-----SIZE-----|------------ADDRESS------------|

#include <stdio.h>

struct gdtr {
        unsigned short size;
        unsigned int addr __attribute__((packed));
} gdtr;

int main(void)
{
        asm("sgdt %0" :"+m" (gdtr));
        printf("limit: %u\nbase: %x\n", gdtr.size, gdtr.addr);
        return 0;
}
Note:
(1) copy the content of gdtr control register to memory address gdtr using sgdtr instruction in inline assembly.
(2) __attribute__((packed)) ensures that structure fields align on one-byte boundaries.