Search This Blog

Friday, July 25, 2008

ULK note (1):Segment in linux

According to ULK,linux uses segmentation in a very limit way,namely,linux uses 4 segments,two for user mode and two for kernel mode.Linux also defines macros as segment selectors of these 4 segments:__USER_CS,__USER_DS,__KERNEL_CS,__KERNEL_DS.

I lookup the definition in include/asm-i386/segment.h(crash here for details),let's take a look at __USER_CS and __KERNEL_CS:

#define GDT_ENTRY_DEFAULT_USER_CS 14
#define __USER_CS (GDT_ENTRY_DEFAULT_USER_CS * 8 + 3)

#define GDT_ENTRY_KERNEL_BASE 12
#define GDT_ENTRY_KERNEL_CS (GDT_ENTYY_KERNEL_BASE + 0)
#define __KERNEL_CS (GDT_ENTRY_KERNEL_CS * 8)

well,14(GDT_ENTRY_DEFAULT_USER_CS) is the user data segment descriptor's offset in GDT.

8 is the length of segment descriptor,easy to understand,huh(it's my first thought)?But what is the "+ 3"?

In fact,8 is (1000) in binary,so multiplying 8 left shift GDT_ENTRY_DEFAULT_USER_CS by 3 bits.aha!It's the TI and RPL fields in segment selector!so what the red "+ 3" turns out:it means this segment is in GDT(TI cleared) and it's in user mode(RPL=11).

Similar to __USER_CS,RPL of __KERNEL_CS is set to 00 to indicate that the segment is in kernel mode,so nothing needs to be added.

1 comment:

ducbh said...

Thank you for the explanation!