Главная » Просмотр файлов » Volume 2 System Programming

Volume 2 System Programming (794096), страница 39

Файл №794096 Volume 2 System Programming (Intel and AMD manuals) 39 страницаVolume 2 System Programming (794096) страница 392019-04-28СтудИзба
Просмтор этого файла доступен только зарегистрированным пользователям. Но у нас супер быстрая регистрация: достаточно только электронной почты!

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

The format of the stack pointer stored in the TSS depends on the system-softwareoperating mode:••Legacy-mode system software stores a 32-bit ESP value (stack offset) and 16-bit SS selectorregister value in the TSS for each of three privilege levels 0, 1, and 2.Long-mode system software stores a 64-bit RSP value in the TSS for privilege levels 0, 1, and 2.No SS register value is stored in the TSS because in long mode a call gate must reference a 64-bitcode-segment descriptor. 64-bit mode does not use segmentation, and the stack pointer consistssolely of the 64-bit RSP.

Any value loaded in the SS register is ignored.See “Task-Management Resources” on page 306 for more information on the legacy-mode and longmode TSS formats.Figure 4-33 on page 107 shows a 32-bit stack in legacy mode before and after the automatic stackswitch. This particular example assumes that parameters are passed from the current program to thetarget program. The process followed by legacy mode in switching stacks and copying parameters is:1.

The target code-segment DPL is read by the processor and used as an index into the TSS forselecting the new stack pointer (SS:ESP). For example, if DPL=1 the processor selects theSS:ESP for privilege-level 1 from the TSS.2. The SS and ESP registers are loaded with the new SS:ESP values read from the TSS.3. The old values of the SS and ESP registers are pushed onto the stack pointed to by the newSS:ESP.4. The 5-bit count field is read from the call-gate descriptor.5. The number of parameters specified in the count field (up to 31) are copied from the old stack tothe new stack.

The size of the parameters copied by the processor depends on the call-gate size:32-bit call gates copy 4-byte parameters and 16-bit call gates copy 2-byte parameters.6. The return pointer is pushed onto the stack. The return pointer consists of the current CS-registervalue and the EIP of the instruction following the calling instruction.106Segmented Virtual Memory24593—Rev. 3.13—July 2007AMD64 Technology7. The CS register is loaded from the segment-selector field in the call-gate descriptor, and the EIP isloaded from the offset field in the call-gate descriptor.8. The target program begins executing with the instruction referenced by new CS:EIP.Old32-Bit StackBefore CALLNew32-Bit StackAfter CALLParameter 1Parameter 2...Parameter nOld SSOld ESPParameter 1Parameter 2...Parameter nOld CSOld EIP+(n-1)*4+(n-2)*4Old SS:ESP+(n*4)+12+(n*4)+8+(n*4)+4+(n*4)+8+4New SS:ESPStack Switch513-224.epsFigure 4-33.

Legacy-Mode 32-Bit Stack Switch, with ParametersFigure 4-34 shows a 32-bit stack in legacy mode before and after the automatic stack switch when noparameters are passed (count=0). Most software does not use the call-gate descriptor count-field topass parameters. System software typically defines linkage mechanisms that do not rely on automaticparameter copying.Old32-Bit StackBefore CALLNew32-Bit StackAfter CALLOld SS:ESPOld SSOld ESPOld CSOld EIPStack Switch+12+8+4New SS:ESP513-225.epsFigure 4-34.

32-Bit Stack Switch, No Parameters—Legacy ModeFigure 4-35 on page 108 shows a long-mode stack switch. In long mode, all call gates must reference64-bit code-segment descriptors, so a long-mode stack switch uses a 64-bit stack. The process ofSegmented Virtual Memory107AMD64 Technology24593—Rev. 3.13—July 2007switching stacks in long mode is similar to switching in legacy mode when no parameters are passed.The process is as follows:1. The target code-segment DPL is read by the processor and used as an index into the 64-bit TSSfor selecting the new stack pointer (RSP).2. The RSP register is loaded with the new RSP value read from the TSS.

The SS register is loadedwith a null selector (SS=0). Setting the new SS selector to null allows proper handling of nestedcontrol transfers in 64-bit mode. See “Nested Returns to 64-Bit Mode Procedures” on page 110for additional information.As in legacy mode, it is desirable to keep the stack-segment requestor privilege-level (SS.RPL)equal to the current privilege-level (CPL). When using a call gate to change privilege levels, theSS.RPL is updated to reflect the new CPL. The SS.RPL is restored from the return-target CS.RPLon the subsequent privilege-level-changing far return.3.

The old values of the SS and RSP registers are pushed onto the stack pointed to by the new RSP.The old SS value is popped on a subsequent far return. This allows system software to set up theSS selector for a compatibility-mode process by executing a RET (or IRET) that changes theprivilege level.4. The return pointer is pushed onto the stack. The return pointer consists of the current CS-registervalue and the RIP of the instruction following the calling instruction.5.

The CS register is loaded from the segment-selector field in the long-mode call-gate descriptor,and the RIP is loaded from the offset field in the long-mode call-gate descriptor.The target program begins execution with the instruction referenced by the new RIP.Old64-Bit StackBefore CALLNew64-Bit StackAfter CALLOld SS:RSPOld SSOld RSPOld CSOld RIP+24+16+8New RSP(SS=0 + new_CPL)Stack SwitchFigure 4-35. Stack Switch—Long ModeAll long-mode stack pushes resulting from a privilege-level-changing far call are eight-bytes wide andincrement the RSP by eight. Long mode ignores the call-gate count field and does not support theautomatic parameter-copy feature found in legacy mode. Software can access parameters on the oldstack, if necessary, by referencing the old stack segment selector and stack pointer saved on the newprocess stack.108Segmented Virtual Memory24593—Rev. 3.13—July 2007AMD64 Technology4.11.3 Return Control TransfersReturns to calling programs can be performed by using the RET instruction.

The following types ofreturns are possible:•••Near Return—Near returns perform control transfers within the same code segment, so the CSregister is unchanged. The new offset is popped off the stack and into the rIP register. No privilegechecks are performed.Far Return, Same Privilege—A far return transfers control from one code segment to another.When the original code segment is at the same privilege level as the target code segment, a farpointer (CS:rIP) is popped off the stack and the RPL of the new code segment (CS) is checked. Ifthe requested privilege level (RPL) matches the current privilege level (CPL), then a return is madeto the same privilege level.

This prevents software from changing the CS value on the stack in anattempt to return to higher-privilege software.Far Return, Less Privilege—Far returns can change privilege levels, but only to a lower-privilegelevel. In this case a stack switch is performed between the current, higher-privilege program andthe lower-privilege return program. The CS-register and rIP-register values are popped off thestack.

The lower-privilege stack pointer is also popped off the stack and into the SS register andrSP register. The processor checks both the CS and SS privilege levels to ensure they are equal andat a lesser privilege than the current CS.In the case of nested returns to 64-bit mode, a null selector can be popped into the SS register. See“Nested Returns to 64-Bit Mode Procedures” on page 110.Far returns also check the privilege levels of the DS, ES, FS and GS selector registers. If any ofthese segment registers have a selector with a higher privilege than the return program, the segmentregister is loaded with the null selector.Stack Switching.

The stack switch performed by a far return to a lower-privilege level reverses thestack switch of a call gate to a higher-privilege level, except that parameters are never automaticallycopied as part of a return. The process followed by a far-return stack switch in long mode and legacymode is:1. The return code-segment RPL is read by the processor from the CS value stored on the stack todetermine that a lower-privilege control transfer is occurring.2.

The return-program instruction pointer is popped off the current-program (higher privilege) stackand loaded into the CS and rIP registers.3. The return instruction can include an immediate operand that specifies the number of additionalbytes to be popped off of the stack. These bytes may correspond to the parameters pushed onto thestack previously by a call through a call gate containing a non-zero parameter-count field. If thereturn includes the immediate operand, then the stack pointer is adjusted upward by adding thespecified number of bytes to the rSP.4.

The return-program stack pointer is popped off the current-program (higher privilege) stack andloaded into the SS and rSP registers. In the case of nested returns to 64-bit mode, a null selectorcan be popped into the SS register.Segmented Virtual Memory109AMD64 Technology24593—Rev. 3.13—July 2007The operand size of a far return determines the size of stack pops when switching stacks. If a far returnis used in 64-bit mode to return from a prior call through a long-mode call gate, the far return must usea 64-bit operand size. The 64-bit operand size allows the far return to properly read the stackestablished previously by the far call.Nested Returns to 64-Bit Mode Procedures. In long mode, a far call that changes privilege levelscauses the SS register to be loaded with a null selector (this is the same action taken by an interrupt inlong mode). If the called procedure performs another far call to a higher-privileged procedure, or isinterrupted, the null SS selector is pushed onto the stack frame, and another null selector is loaded intothe SS register.

Using a null selector in this way allows the processor to properly handle returns nestedwithin 64-bit-mode procedures and interrupt handlers.Normally, a RET that pops a null selector into the SS register causes a general-protection exception(#GP) to occur. However, in long mode, the null selector acts as a flag indicating the existence ofnested interrupt handlers or other privileged software in 64-bit mode.

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

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

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

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