Главная » Просмотр файлов » Volume 3A System Programming Guide_ Part 1

Volume 3A System Programming Guide_ Part 1 (794103), страница 49

Файл №794103 Volume 3A System Programming Guide_ Part 1 (Intel and AMD manuals) 49 страницаVolume 3A System Programming Guide_ Part 1 (794103) страница 492019-04-28СтудИзба
Просмтор этого файла доступен только зарегистрированным пользователям. Но у нас супер быстрая регистрация: достаточно только электронной почты!

Текст из файла (страница 49)

3 4-31PROTECTIONWhen SYSEXIT transfers control to compatibility mode user code when the operandsize attribute is 32 bits, the following fields are generated and bits set:•Target code segment — Computed by adding 16 to the value inIA32_SYSENTER_CS.••••New CS attributes — L-bit = 0 (go to compatibility mode).Target instruction — Fetch the target instruction from 32-bit address in EDX.Stack segment — Computed by adding 24 to the value in IA32_SYSENTER_CS.Stack pointer — Update ESP from 32-bit address in ECX.4.8.8Fast System Calls in 64-bit ModeThe SYSCALL and SYSRET instructions are designed for operating systems that use aflat memory model (segmentation is not used).

The instructions, along withSYSENTER and SYSEXIT, are suited for IA-32e mode operation. SYSCALL andSYSRET, however, are not supported in compatibility mode. Use CPUID to check ifSYSCALL and SYSRET are available (CPUID.80000001H.EDX[bit 11] = 1).SYSCALL is intended for use by user code running at privilege level 3 to access operating system or executive procedures running at privilege level 0. SYSRET isintended for use by privilege level 0 operating system or executive procedures forfast returns to privilege level 3 user code.Stack pointers for SYSCALL/SYSRET are not specified through model specific registers. The clearing of bits in RFLAGS is programmable rather than fixed.SYSCALL/SYSRET save and restore the RFLAGS register.For SYSCALL, the processor saves the RIP of the instruction in RCX and gets the privilege level 0 target instruction and stack pointer from:••••Target code segment — Reads a non-NULL selector from IA32_STAR[47:32].Target instruction — Reads a 64-bit canonical address from IA32_LSTAR.Stack segment — Computed by adding 8 to the value in IA32_STAR[47:32].System flags — The processor uses a mask derived from IA32_FMASK toperform a logical-AND operation with the lower 32-bits of RFLAGS.

The result issaved into R11. The mask is the complement of the value supplied by privilegedexecutives using the IA32_FMASK MSR.When SYSRET transfers control to 64-bit mode user code using REX.W, the processorgets the privilege level 3 target instruction and stack pointer from:•Target code segment — Reads a non-NULL selector from IA32_STAR[63:48] +16.•••Target instruction — Copies the value in RCX into RIP.Stack segment — IA32_STAR[63:48] + 8.EFLAGS — Loaded from R11.4-32 Vol. 3PROTECTIONWhen SYSRET transfers control to 32-bit mode user code using a 32-bit operand size,the processor gets the privilege level 3 target instruction and stack pointer from:••••Target code segment — Reads a non-NULL selector from IA32_STAR[63:48].Target instruction — Copies the value in ECX into EIP.Stack segment — IA32_STAR[63:48] + 8.EFLAGS — Loaded from R11.It is the responsibility of the OS to ensure the descriptors in the GDT/LDT correspondto the selectors loaded by SYSCALL/SYSRET (consistent with the base, limit, andattribute values forced by the instructions).Any address written to IA32_LSTAR is first checked by WRMSR to ensure canonicalform.

If an address is not canonical, an exception is generated (#GP).See Figure 4-14 for the layout of IA32_STAR, IA32_LSTAR and IA32_FMASK.63032 31SYSCALL EFLAGS MaskReservedIA32_FMASK630Target RIP for 64-bit Mode Calling ProgramIA32_LSTAR6332 3148 47SYSRET CS and SSSYSCALL CS and SS0ReservedIA32_STARFigure 4-14. MSRs Used by SYSCALL and SYSRET4.9PRIVILEGED INSTRUCTIONSSome of the system instructions (called “privileged instructions”) are protected fromuse by application programs.

The privileged instructions control system functions(such as the loading of system registers). They can be executed only when the CPL is0 (most privileged). If one of these instructions is executed when the CPL is not 0, aVol. 3 4-33PROTECTIONgeneral-protection exception (#GP) is generated. The following system instructionsare privileged instructions:••••••••••••••••LGDT — Load GDT register.LLDT — Load LDT register.LTR — Load task register.LIDT — Load IDT register.MOV (control registers) — Load and store control registers.LMSW — Load machine status word.CLTS — Clear task-switched flag in register CR0.MOV (debug registers) — Load and store debug registers.INVD — Invalidate cache, without writeback.WBINVD — Invalidate cache, with writeback.INVLPG —Invalidate TLB entry.HLT— Halt processor.RDMSR — Read Model-Specific Registers.WRMSR —Write Model-Specific Registers.RDPMC — Read Performance-Monitoring Counter.RDTSC — Read Time-Stamp Counter.Some of the privileged instructions are available only in the more recent families ofIntel 64 and IA-32 processors (see Section 17.12, “New Instructions In the Pentiumand Later IA-32 Processors”).The PCE and TSD flags in register CR4 (bits 4 and 2, respectively) enable the RDPMCand RDTSC instructions, respectively, to be executed at any CPL.4.10POINTER VALIDATIONWhen operating in protected mode, the processor validates all pointers to enforceprotection between segments and maintain isolation between privilege levels.Pointer validation consists of the following checks:1.

Checking access rights to determine if the segment type is compatible with itsuse.2. Checking read/write rights.3. Checking if the pointer offset exceeds the segment limit.4. Checking if the supplier of the pointer is allowed to access the segment.5. Checking the offset alignment.4-34 Vol. 3PROTECTIONThe processor automatically performs first, second, and third checks during instruction execution. Software must explicitly request the fourth check by issuing an ARPLinstruction.

The fifth check (offset alignment) is performed automatically at privilegelevel 3 if alignment checking is turned on. Offset alignment does not affect isolationof privilege levels.4.10.1Checking Access Rights (LAR Instruction)When the processor accesses a segment using a far pointer, it performs an accessrights check on the segment descriptor pointed to by the far pointer. This check isperformed to determine if type and privilege level (DPL) of the segment descriptorare compatible with the operation to be performed. For example, when making a farcall in protected mode, the segment-descriptor type must be for a conforming ornonconforming code segment, a call gate, a task gate, or a TSS.

Then, if the call is toa nonconforming code segment, the DPL of the code segment must be equal to theCPL, and the RPL of the code segment’s segment selector must be less than or equalto the DPL. If type or privilege level are found to be incompatible, the appropriateexception is generated.To prevent type incompatibility exceptions from being generated, software can checkthe access rights of a segment descriptor using the LAR (load access rights) instruction.

The LAR instruction specifies the segment selector for the segment descriptorwhose access rights are to be checked and a destination register. The instruction thenperforms the following operations:1. Check that the segment selector is not null.2. Checks that the segment selector points to a segment descriptor that is withinthe descriptor table limit (GDT or LDT).3. Checks that the segment descriptor is a code, data, LDT, call gate, task gate, orTSS segment-descriptor type.4.

If the segment is not a conforming code segment, checks if the segmentdescriptor is visible at the CPL (that is, if the CPL and the RPL of the segmentselector are less than or equal to the DPL).5. If the privilege level and type checks pass, loads the second doubleword of thesegment descriptor into the destination register (masked by the value00FXFF00H, where X indicates that the corresponding 4 bits are undefined) andsets the ZF flag in the EFLAGS register. If the segment selector is not visible atthe current privilege level or is an invalid type for the LAR instruction, theinstruction does not modify the destination register and clears the ZF flag.Once loaded in the destination register, software can preform additional checks onthe access rights information.Vol.

3 4-35PROTECTION4.10.2Checking Read/Write Rights (VERR and VERW Instructions)When the processor accesses any code or data segment it checks the read/write privileges assigned to the segment to verify that the intended read or write operation isallowed. Software can check read/write rights using the VERR (verify for reading)and VERW (verify for writing) instructions. Both these instructions specify thesegment selector for the segment being checked. The instructions then perform thefollowing operations:1.

Check that the segment selector is not null.2. Checks that the segment selector points to a segment descriptor that is withinthe descriptor table limit (GDT or LDT).3. Checks that the segment descriptor is a code or data-segment descriptor type.4. If the segment is not a conforming code segment, checks if the segmentdescriptor is visible at the CPL (that is, if the CPL and the RPL of the segmentselector are less than or equal to the DPL).5. Checks that the segment is readable (for the VERR instruction) or writable (forthe VERW) instruction.The VERR instruction sets the ZF flag in the EFLAGS register if the segment is visibleat the CPL and readable; the VERW sets the ZF flag if the segment is visible and writable.

(Code segments are never writable.) The ZF flag is cleared if any of thesechecks fail.4.10.3Checking That the Pointer Offset Is Within Limits (LSLInstruction)When the processor accesses any segment it performs a limit check to insure that theoffset is within the limit of the segment. Software can perform this limit check usingthe LSL (load segment limit) instruction.

Like the LAR instruction, the LSL instructionspecifies the segment selector for the segment descriptor whose limit is to bechecked and a destination register. The instruction then performs the following operations:1. Check that the segment selector is not null.2. Checks that the segment selector points to a segment descriptor that is withinthe descriptor table limit (GDT or LDT).3.

Характеристики

Тип файла
PDF-файл
Размер
3,12 Mb
Материал
Тип материала
Высшее учебное заведение

Список файлов книги

Свежие статьи
Популярно сейчас
Почему делать на заказ в разы дороже, чем купить готовую учебную работу на СтудИзбе? Наши учебные работы продаются каждый год, тогда как большинство заказов выполняются с нуля. Найдите подходящий учебный материал на СтудИзбе!
Ответы на популярные вопросы
Да! Наши авторы собирают и выкладывают те работы, которые сдаются в Вашем учебном заведении ежегодно и уже проверены преподавателями.
Да! У нас любой человек может выложить любую учебную работу и зарабатывать на её продажах! Но каждый учебный материал публикуется только после тщательной проверки администрацией.
Вернём деньги! А если быть более точными, то автору даётся немного времени на исправление, а если не исправит или выйдет время, то вернём деньги в полном объёме!
Да! На равне с готовыми студенческими работами у нас продаются услуги. Цены на услуги видны сразу, то есть Вам нужно только указать параметры и сразу можно оплачивать.
Отзывы студентов
Ставлю 10/10
Все нравится, очень удобный сайт, помогает в учебе. Кроме этого, можно заработать самому, выставляя готовые учебные материалы на продажу здесь. Рейтинги и отзывы на преподавателей очень помогают сориентироваться в начале нового семестра. Спасибо за такую функцию. Ставлю максимальную оценку.
Лучшая платформа для успешной сдачи сессии
Познакомился со СтудИзбой благодаря своему другу, очень нравится интерфейс, количество доступных файлов, цена, в общем, все прекрасно. Даже сам продаю какие-то свои работы.
Студизба ван лав ❤
Очень офигенный сайт для студентов. Много полезных учебных материалов. Пользуюсь студизбой с октября 2021 года. Серьёзных нареканий нет. Хотелось бы, что бы ввели подписочную модель и сделали материалы дешевле 300 рублей в рамках подписки бесплатными.
Отличный сайт
Лично меня всё устраивает - и покупка, и продажа; и цены, и возможность предпросмотра куска файла, и обилие бесплатных файлов (в подборках по авторам, читай, ВУЗам и факультетам). Есть определённые баги, но всё решаемо, да и администраторы реагируют в течение суток.
Маленький отзыв о большом помощнике!
Студизба спасает в те моменты, когда сроки горят, а работ накопилось достаточно. Довольно удобный сайт с простой навигацией и огромным количеством материалов.
Студ. Изба как крупнейший сборник работ для студентов
Тут дофига бывает всего полезного. Печально, что бывают предметы по которым даже одного бесплатного решения нет, но это скорее вопрос к студентам. В остальном всё здорово.
Спасательный островок
Если уже не успеваешь разобраться или застрял на каком-то задание поможет тебе быстро и недорого решить твою проблему.
Всё и так отлично
Всё очень удобно. Особенно круто, что есть система бонусов и можно выводить остатки денег. Очень много качественных бесплатных файлов.
Отзыв о системе "Студизба"
Отличная платформа для распространения работ, востребованных студентами. Хорошо налаженная и качественная работа сайта, огромная база заданий и аудитория.
Отличный помощник
Отличный сайт с кучей полезных файлов, позволяющий найти много методичек / учебников / отзывов о вузах и преподователях.
Отлично помогает студентам в любой момент для решения трудных и незамедлительных задач
Хотелось бы больше конкретной информации о преподавателях. А так в принципе хороший сайт, всегда им пользуюсь и ни разу не было желания прекратить. Хороший сайт для помощи студентам, удобный и приятный интерфейс. Из недостатков можно выделить только отсутствия небольшого количества файлов.
Спасибо за шикарный сайт
Великолепный сайт на котором студент за не большие деньги может найти помощь с дз, проектами курсовыми, лабораторными, а также узнать отзывы на преподавателей и бесплатно скачать пособия.
Популярные преподаватели
Добавляйте материалы
и зарабатывайте!
Продажи идут автоматически
6430
Авторов
на СтудИзбе
307
Средний доход
с одного платного файла
Обучение Подробнее