Search     or:     and:
 LINUX 
 Language 
 Kernel 
 Package 
 Book 
 Test 
 OS 
 Forum 
 iakovlev.org 
 OS
 osjournal 
 Protected Mode 
 Hardware 
 Kernels
  Dark Fiber
  BOS
  QNX
  OS Dev
  Lecture notes
  MINIX
  OS
  Solaris
  История UNIX
  История FreeBSD
  Сетунь
  Эльбрус
NEWS
Последние статьи :
  Тренажёр 16.01   
  Эльбрус 05.12   
  Алгоритмы 12.04   
  Rust 07.11   
  Go 25.12   
  EXT4 10.11   
  FS benchmark 15.09   
  Сетунь 23.07   
  Trees 25.06   
  Apache 03.02   
 
TOP 20
 Linux Kernel 2.6...2334 
 Trees...1465 
 William Gropp...1422 
 Ethreal 3...1401 
 Ethreal 4...1383 
 C++ Patterns 3...1380 
 Максвелл 3...1367 
 Rodriguez 6...1366 
 Httpd-> История Ap...1366 
 Robert Love 5...1365 
 Go Web ...1364 
 Максвелл 5...1363 
 OS ->Intel Manual 1...1362 
 Ext4 FS...1362 
 K&R 1...1361 
 Kamran Husain...1360 
 Rubni-Corbet -> Глав...1358 
 Perl OOP...1355 
 Erlang...1354 
 Сетунь...1353 
 
  01.01.2024 : 3621733 посещений 

iakovlev.org

Дескрипторные таблицы: GDT, IDT, LDT

Content by: johnfine@erols.com

Формат дескрипторов

Есть 2 формата :

  • Gates
  • nonGates

Гейт-дескриптор включает :

  • Смещение
  • Селектор
  • Атрибуты
7 6 5 4 3 2 1 0
63............. 48 47..............32 31..............16 15...............0
Offset
31..............16
Attributes Selector Offset
15...............0

Негейтовый дескриптор включает :

  • База
  • Ограничение
  • Атрибуты
7 6 5 4 3 2 1 0
63........56 55..52 51..48 47........40 39................................16 15.....................0
Base
31........24
Attr Limit
19..16
Attr Base
23.................................0
Limit
15.....................0

Т.о. дескрипторы имеют фрагментарную структуру - (для совместимости)

  • База (base) - 32-битное значение , которое разбито на 2 части , первая часть лежит в битах 16-39 , вторая - в битах 56-63.
  • Ограничение (limit) - 20-битное значение , разбито на 2 части , первая лежит в битах 0-15 , вторая - в битах 48-51 .
  • смещение (offset) - 32-битное значение , разбито на 2 части , первая лежит в 0-15 , вторая - в 48-63.
  • Селектор (selector) - 16-битное значение , лежит в битах 16-31.
  • Атрибуты (attributes) - коллекция битов в диапазоне 32-47 либо 40-47 либо 52-55 of.

Атрибуты

В отличие от базы,ограничения и смещения , биты атрибутов фиксированы к определенной позиции.

  • Биты с 8 по 15 - дескрипторные биты с 40 по 47
  • Биты с 0 по 7 для гейта - дескрипторные биты с 32 по 39
  • Биты с 4 по 7 для не-гейта - дескрипторные биты с 52 по 55
  • Биты с 0 по 3 для не-гейта не существуют - их у него всего 12
Descriptor byte 6 5 4
Descriptor bits 55..52 51..48 47..........40 39..........32
Gate Attribute bits 15..........................0
nonGate Attribute bits 7....4 15..........8

Это дает возможность обьединить все атрибуты в одно 16-битное значение для передачи функции или макросу , которые строят дескрипторную таблицу. Это также дает возможность определить символические константы для атрибутивных значений , которые могут быть скомбинированы независимо от их битового порядка расположения.

Descriptor bit number555453524746454443424140 39..3736..32
Attribute bit number765415141312111098 7....54....0
Gate Task Gate P
r
e
s
e
n
t
D
P
L
0 Z 1 0 1 ?
Call Gate 3
2
B
i
t
0 Z count
Interrupt Gate 1 0 ?
Trap Gate 1
nonGate TSS G
r
a
n
? Z A
v
a
i
l
0 B 1
LDT Z 1 0
Code Segment B
i
g
1 1 C R A
c
c
Data Segment 0 E W

Биты , отмеченные как "Z", "?", "Avail" - недокументированы. Эти биты должны быть обнулены. Дескриптор в принципе может работать корректно , если какой-то из этих бит не обнулен. Биты зарезервированы интелом.

Attribute бит 15, "Present" - должен быть установлен в 1, иначе фолт. Его очистка может понадобиться при реализации виртуальной памяти.

Attribute биты 13 и 14, "dpl" - 2 бита на уровень привилегий.

Attribute бит 11 - для TSS. При возникновении прерывания этот бит решает , в какой стек сохраняются регистры eip,cs,flags - в 16-битный или в 32-битный.

Attribute биты с 0 с 4 для call gate - parameter count.

Attribute бит 7 для nongate - бит гранулярности. Если бит=0 , размер страницы произволен. Если бит установлен , размер страницы вычисляется по формуле :
limit = ( limit_field SHL 12 ) + 0xFFF

Attribute бит 9 для TSS, если бит установлен , TSS занят.

Attribute бит 6 для code или data segment, "big" - указывает на размер по умолчанию В CS он контролирует размер операнда. В SS он контролирует выбор sp или esp для push, pop.

Attribute бит 10 code segment, "C" - подтверждение code segments.

Attribute bit 10 data segment, "E" - расширение вниз - "expand down" для data segments.

Attribute бит 9 в code segment, "R" - сегмент на выполнение или чтение.

Attribute бит 9 в data segment, "W" - сегмент может быть прочитан или записан , не execute.

Attribute бит 8 для code или data segment, "Acc" - сигнал о доступе к сегменту.

GDT.INC

Следующий код включает константы и макросы для создания GDT, LDT, IDT . Он помогает в создании читабельности кода , создающего дескрипторы.

; gdtn.inc   symbols and macros for building descriptors
 ;
 ;  This is an HTML version of a subset of my GDT.INC file.
 ;  This GDTN.INC subset does not require my linker JLOC, it does require
 ;  NASM version 0.98-J4 or later.
 ;
 ;  You can find (nonHTML) GDTN.INC here and you can find other
 ;  versions of GDT.INC in various .ZIP files at
 ;  http://www.execpc.com/~geezer/johnfine/index.htm
 ;  The versions that require JLOC support some features that the nonJLOC
 ;  versions can't support.
 ;_____________________________________________________________________________
 ;
 ; The start_gdt macro marks the beginning of a GDT and uses the first 8 bytes
 ; of the GDT as a psuedo-descriptor for the LGDT instruction.
 ;_____________________________________________________________________________
 ;
 ; The end_gdt macro marks the end of a GDT and computes the limit value.
 ;_____________________________________________________________________________
 ;
 ; The desc macro pieces together a segment descriptor.
 ;
 ; SLCTR  desc  OFFSET, SELECTOR, ATTRIB      ;For gate descriptors
 ; SLCTR  desc  BASE, LIMIT, ATTRIB           ;For all other descriptors
 ;
 ;  SLCTR    (optional) is a label.  Unlike an ordinary label, it will not be
 ;           defined as the address of the descriptor.  Instead it will be
 ;           defined as the selector used to access the descriptor.
 ;  OFFSET   is the offset of the routine pointed to by a gate.
 ;  SELECTOR is the selector of the routine pointed to by a gate. 
 ;  BASE     is the full 32 bit base address of the segment
 ;  LIMIT    is one less than the segment length in 1 or 4K byte units
 ;  ATTRIB   the sum of all the "D_" equates which apply (for call gates, you
 ;           also add the "parameter dword count" to ATTRIB).
 ;_____________________________________________________________________________
 
 ;Each descriptor should have exactly one of next 8 codes to define the type of
 ;descriptor (see attribute bit numbering)
 D_LDT		EQU	 200h	;LDT segment
 D_TASK		EQU	 500h	;Task gate
 D_TSS		EQU	 900h	;TSS
 D_CALL		EQU	0C00h	;386 call gate
 D_INT		EQU	0E00h	;386 interrupt gate
 D_TRAP		EQU	0F00h	;386 trap gate
 D_DATA		EQU	1000h	;Data segment
 D_CODE		EQU	1800h	;Code segment
 
 ;Descriptors may include the following as appropriate:
 D_DPL3		EQU	6000h	;DPL3 or mask for DPL
 D_DPL2		EQU	4000h
 D_DPL1		EQU	2000h
 D_DPL0		EQU	0000h
 D_PRESENT	EQU	8000h	;Present
 D_NOT_PRESENT	EQU	8000h	;Not Present
 				;Note, the PRESENT bit is set by default
 				;Include NOT_PRESENT to turn it off
 				;Do not specify D_PRESENT
 
 ;Segment descriptors (not gates) may include:
 D_ACC		EQU	 100h	;Accessed (Data or Code)
 
 D_WRITE		EQU	 200h	;Writable (Data segments only)
 D_READ		EQU	 200h	;Readable (Code segments only)
 D_BUSY		EQU	 200h	;Busy (TSS only)
 
 D_EXDOWN	EQU	 400h	;Expand down (Data segments only)
 D_CONFORM	EQU	 400h	;Conforming (Code segments only)
 
 D_BIG		EQU	  40h	;Default to 32 bit mode (USE32)
 D_BIG_LIM	EQU	  80h	;Limit is in 4K units
 
 %macro start_gdt 0
 %push table
 %$startoftable:
 	dw	%$limitoftable
 	dd	%$startoftable
 	dw	0
 %endmacro
 
 %macro end_gdt 0
 %$limitoftable	equ	$-%$startoftable-1
 %pop
 %endmacro
 
 %macro desc 3
 %ifid %00
 %00 equ $-%$startoftable	;Define selector
 %endif
 %if (%3) & (~(%3)>>2) & 0x400   ;Gate
 	dw	%1
 	dw	%2
 	dw	(%3)+D_PRESENT
 	dw	(%1) >> 16
 %else                           ;Not a gate
 	dw	%2
 	dw	%1
 	db	(%1) >> 16
 	db	((%3)+D_PRESENT) >> 8
 	db	(%3) + ((%2) >> 16)
 	db	(%1) >> 24
 %endif
 %endmacro
 
 ;-----------------------------------------------------------------------------
 ;
 ;  A gate is identified as any descriptor whose attributes has bit 10 set and 
 ;  bit 12 clear.
 ;
 ;  For a gate, the following rearrangement occurs:
 ;
 ;  subField                Final location
 ;  ------------------      --------------
 ;  Selector[0..15]             16..31
 ;  Minor attribute bits        32..39
 ;  Major attribute bits        40..47
 ;  Offset[0..15]                0..15
 ;  Offset[16..31]              48..63
 ;
 ;  For non-gates the following rearrangement occurs:
 ;
 ;  subField                Final location
 ;  ------------------      --------------
 ;  Limit[0..15]                 0..15
 ;  Limit[16..19]               48..51
 ;  Minor attribute bits        52..55
 ;  Major attribute bits        40..47
 ;  Base[0..23]                 16..39
 ;  Base[24..31]                56..63
 ;
 ;  The last parameter to the desc macro contains all the attribute bits
 ;  combined.  It is generated by adding together the appropriate
 ;  D_ constants.  For all descriptors, it has the major attribute bits in D_
 ;  bits 8 to 15.  The minor attribute bits are in either D_ bits 0 to 7 or
 ;  bits 4 to 7 depending on the type of descriptor.
 ;_____________________________________________________________________________
 

Первые 8 байт GDT

Процессор не использует первые 8 байт GDT. Эти байты например можно использовать как псевдо-дескриптор для LGDT. Адрес псевдо-дескриптора - это тот же самый адрес самой GDT.

Оставьте свой комментарий !

Ваше имя:
Комментарий:
Оба поля являются обязательными

 Автор  Комментарий к данной статье