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

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

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

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

The new SS is forced to NULL and the SS selector’sRPL field is forced to the new CPL. The new SS is set to NULL in order to handlenested far transfers (CALLF, INTn, interrupts and exceptions). The old SS and RSPare saved on the new stack.On a subsequent RETF, the old SS is popped from the stack and loaded into the SSregister. See Table 4-2.Table 4-2. 64-Bit-Mode Stack Layout After CALLF with CPL Change32-bit ModeIA-32e modeOld SS Selector+12+24Old SS SelectorOld ESP+8+16Old RSPCS Selector+4+8Old CS SelectorEIP00RIPESPRSP< 4 Bytes >< 8 Bytes >In 64-bit mode, stack operations resulting from a privilege-level-changing far call orfar return are eight-bytes wide and change the RSP by eight.

The mode does notsupport the automatic parameter-copy feature found in 32-bit mode. The call-gatecount field is ignored. Software can access the old stack, if necessary, by referencingthe old stack-segment selector and stack pointer saved on the new process stack.In 64-bit mode, RETF is allowed to load a NULL SS under certain conditions. If thetarget mode is 64-bit mode and the target CPL< >3, IRET allows SS to be loaded witha NULL selector. If the called procedure itself is interrupted, the NULL SS is pushed onthe stack frame.

On the subsequent RETF, the NULL SS on the stack acts as a flag totell the processor not to load a new SS descriptor.4.8.6Returning from a Called ProcedureThe RET instruction can be used to perform a near return, a far return at the sameprivilege level, and a far return to a different privilege level. This instruction is4-28 Vol. 3PROTECTIONintended to execute returns from procedures that were called with a CALL instruction. It does not support returns from a JMP instruction, because the JMP instructiondoes not save a return instruction pointer on the stack.A near return only transfers program control within the current code segment; therefore, the processor performs only a limit check. When the processor pops the returninstruction pointer from the stack into the EIP register, it checks that the pointer doesnot exceed the limit of the current code segment.On a far return at the same privilege level, the processor pops both a segmentselector for the code segment being returned to and a return instruction pointer fromthe stack.

Under normal conditions, these pointers should be valid, because theywere pushed on the stack by the CALL instruction. However, the processor performsprivilege checks to detect situations where the current procedure might have alteredthe pointer or failed to maintain the stack properly.A far return that requires a privilege-level change is only allowed when returning to aless privileged level (that is, the DPL of the return code segment is numericallygreater than the CPL).

The processor uses the RPL field from the CS register valuesaved for the calling procedure (see Figure 4-13) to determine if a return to a numerically higher privilege level is required. If the RPL is numerically greater (less privileged) than the CPL, a return across privilege levels occurs.The processor performs the following steps when performing a far return to a callingprocedure (see Figures 6-2 and 6-4 in the Intel® 64 and IA-32 Architectures Software Developer’s Manual, Volume 1, for an illustration of the stack contents prior toand after a return):1. Checks the RPL field of the saved CS register value to determine if a privilegelevel change is required on the return.2. Loads the CS and EIP registers with the values on the called procedure’s stack.(Type and privilege level checks are performed on the code-segment descriptorand RPL of the code- segment selector.)3.

(If the RET instruction includes a parameter count operand and the returnrequires a privilege level change.) Adds the parameter count (in bytes obtainedfrom the RET instruction) to the current ESP register value (after popping the CSand EIP values), to step past the parameters on the called procedure’s stack. Theresulting value in the ESP register points to the saved SS and ESP values for thecalling procedure’s stack. (Note that the byte count in the RET instruction mustbe chosen to match the parameter count in the call gate that the callingprocedure referenced when it made the original call multiplied by the size of theparameters.)4.

(If the return requires a privilege level change.) Loads the SS and ESP registerswith the saved SS and ESP values and switches back to the calling procedure’sstack. The SS and ESP values for the called procedure’s stack are discarded. Anylimit violations detected while loading the stack-segment selector or stackpointer cause a general-protection exception (#GP) to be generated. The newstack-segment descriptor is also checked for type and privilege violations.Vol. 3 4-29PROTECTION5.

(If the RET instruction includes a parameter count operand.) Adds the parametercount (in bytes obtained from the RET instruction) to the current ESP registervalue, to step past the parameters on the calling procedure’s stack. The resultingESP value is not checked against the limit of the stack segment. If the ESP valueis beyond the limit, that fact is not recognized until the next stack operation.6. (If the return requires a privilege level change.) Checks the contents of the DS,ES, FS, and GS segment registers.

If any of these registers refer to segmentswhose DPL is less than the new CPL (excluding conforming code segments), thesegment register is loaded with a null segment selector.See the description of the RET instruction in Chapter 4 of the Intel® 64 and IA-32Architectures Software Developer’s Manual, Volume 2B, for a detailed description ofthe privilege level checks and other protection checks that the processor performs ona far return.4.8.7Performing Fast Calls to System Procedures with theSYSENTER and SYSEXIT InstructionsThe SYSENTER and SYSEXIT instructions were introduced into the IA-32 architecturein the Pentium II processors for the purpose of providing a fast (low overhead) mechanism for calling operating system or executive procedures.

SYSENTER is intendedfor use by user code running at privilege level 3 to access operating system or executive procedures running at privilege level 0. SYSEXIT is intended for use by privilegelevel 0 operating system or executive procedures for fast returns to privilege level 3user code. SYSENTER can be executed from privilege levels 3, 2, 1, or 0; SYSEXITcan only be executed from privilege level 0.The SYSENTER and SYSEXIT instructions are companion instructions, but they do notconstitute a call/return pair.

This is because SYSENTER does not save any state information for use by SYSEXIT on a return.The target instruction and stack pointer for these instructions are not specifiedthrough instruction operands. Instead, they are specified through parametersentered in MSRs and general-purpose registers.For SYSENTER, target fields are generated using the following sources:••••Target code segment — Reads this from IA32_SYSENTER_CS.Target instruction — Reads this from IA32_SYSENTER_EIP.Stack segment — Computed by adding 8 to the value in IA32_SYSENTER_CS.Stack pointer — Reads this from the IA32_SYSENTER_ESP.For SYSEXIT, target fields are generated using the following sources:•Target code segment — Computed by adding 16 to the value in theIA32_SYSENTER_CS.•Target instruction — Reads this from EDX.4-30 Vol.

3PROTECTION••Stack segment — Computed by adding 24 to the value in IA32_SYSENTER_CS.Stack pointer — Reads this from ECX.The SYSENTER and SYSEXIT instructions preform “fast” calls and returns becausethey force the processor into a predefined privilege level 0 state when SYSENTER isexecuted and into a predefined privilege level 3 state when SYSEXIT is executed. Byforcing predefined and consistent processor states, the number of privilege checksordinarily required to perform a far call to another privilege levels are greatlyreduced.

Also, by predefining the target context state in MSRs and general-purposeregisters eliminates all memory accesses except when fetching the target code.Any additional state that needs to be saved to allow a return to the calling proceduremust be saved explicitly by the calling procedure or be predefined through programming conventions.4.8.7.1SYSENTER and SYSEXIT Instructions in IA-32e ModeFor Intel 64 processors, the SYSENTER and SYSEXIT instructions are enhanced toallow fast system calls from user code running at privilege level 3 (in compatibilitymode or 64-bit mode) to 64-bit executive procedures running at privilege level 0.IA32_SYSENTER_EIP MSR and IA32_SYSENTER_ESP MSR are expanded to hold64-bit addresses.

If IA-32e mode is inactive, only the lower 32-bit addresses storedin these MSRs are used. If 64-bit mode is active, addresses stored inIA32_SYSENTER_EIP and IA32_SYSENTER_ESP must be canonical. Note that, in64-bit mode, IA32_SYSENTER_CS must not contain a NULL selector.When SYSENTER transfers control, the following fields are generated and bits set:•••Target code segment — Reads non-NULL selector from IA32_SYSENTER_CS.•Stack segment — Computed by adding 8 to the value fromIA32_SYSENTER_CS.••Stack pointer — Reads 64-bit canonical address from IA32_SYSENTER_ESP.New CS attributes — CS base = 0, CS limit = FFFFFFFFH.Target instruction — Reads 64-bit canonical address fromIA32_SYSENTER_EIP.New SS attributes — SS base = 0, SS limit = FFFFFFFFH.When the SYSEXIT instruction transfers control to 64-bit mode user code usingREX.W, the following fields are generated and bits set:•Target code segment — Computed by adding 32 to the value inIA32_SYSENTER_CS.••••New CS attributes — L-bit = 1 (go to 64-bit mode).Target instruction — Reads 64-bit canonical address in RDX.Stack segment — Computed by adding 40 to the value of IA32_SYSENTER_CS.Stack pointer — Update RSP using 64-bit canonical address in RCX.Vol.

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

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

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

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