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

Volume 1 Application Programming (794095), страница 27

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

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

Call-gate descriptors are created and maintained by system software. In 64-bit mode, onlyindirect far calls (those whose target memory address is in a register or other memory location) are80General-Purpose Programming24592—Rev. 3.13—July 2007AMD64 Technologysupported. Absolute far calls (those that reference the base of the code segment) are not supported in64-bit mode.When a call to a more-privileged procedure occurs, the processor locates the new procedure’s stackpointer from its task-state segment (TSS). The old stack pointer (SS:rSP) is pushed onto the new stack,and (in legacy mode only) any parameters specified by the count field in the call-gate descriptor arecopied from the old stack to the new stack (long mode does not support this automatic parametercopying). The return pointer (CS:rIP) is then pushed, and control is transferred to the new procedure.Figure 3-12 shows an example of a stack switch resulting from a call to a more-privileged procedure.“Segmented Virtual Memory” in Volume 2 provides additional information on privilege-changingCALLs.CalledProcedureStackOldProcedureStackParametersReturn SSReturn rSP...Parameters *...Old SS:rSPReturn CSReturn rIP* Parameters are copied only inLegacy Mode, not in Long Mode.New SS:rSP513-177.epsFigure 3-12.

Procedure Stack, Far Call to Greater PrivilegeTask Switch. In legacy mode, when a call to a new task occurs, the processor suspends the currentlyexecuting task and stores the processor-state information at the point of suspension in the current task’stask-state segment (TSS). The new task’s state information is loaded from its TSS, and the processorresumes execution within the new task.In long mode, hardware task switching is disabled. Task switching is fully described in “SegmentedVirtual Memory” in Volume 2.3.7.6 Returning from ProceduresThe RET instruction reverses the effect of a CALL instruction. The return address is popped off theprocedure stack, transferring control unconditionally back to the calling procedure at the instructionfollowing the CALL.

A return that changes privilege levels also switches stacks.The three types of RET are:General-Purpose Programming81AMD64 Technology•••24592—Rev. 3.13—July 2007Near Return—Transfers control back to the calling procedure within the current code segment.Far Return—Transfers control back to the calling procedure outside the current code segment.Interprivilege-Level Far Return—A far return that changes privilege levels.All of the RET instruction types can be used with an immediate operand indicating the number ofparameter bytes present on the stack.

These parameters are released from the stack—that is, the stackpointer is adjusted by the value of the immediate operand—but the parameter bytes are not actuallypopped off of the stack (i.e., read into a register or memory location).Near Return. When a near RET is executed, the calling procedure’s return offset is popped off of thestack and into the rIP register. Execution begins from the newly-loaded offset. If an immediate operandis included with the RET instruction, the stack pointer is adjusted by the number of bytes indicated.Figure 3-13 shows the stack pointer before (old rSP value) and after (new rSP value) the RET.

Thestack segment (SS) is not changed.ProcedureStackNew rSPParameters...Return rIPOld rSP513-178.epsFigure 3-13.Procedure Stack, Near ReturnFar Return, Same Privilege. A far RET changes the code segment, so the full return pointer ispopped off the stack and into the CS and rIP registers. Execution begins from the newly-loadedsegment and offset. If an immediate operand is included with the RET instruction, the stack pointer isadjusted by the number of bytes indicated. Figure 3-14 on page 83 shows the stack pointer before (oldrSP value) and after (new rSP value) the RET.

The stack segment (SS) is not changed.82General-Purpose Programming24592—Rev. 3.13—July 2007AMD64 TechnologyProcedureStackNew rSPParameters...Return CSReturn rIPOld rSP513-179.epsFigure 3-14. Procedure Stack, Far Return from Same PrivilegeFar Return, Less Privilege. Privilege-changing far RETs can only return to less-privileged codesegments, otherwise a general-protection exception occurs. The full return pointer is popped off thestack and into the CS and rIP registers, and execution begins from the newly-loaded segment andoffset.

A far RET that changes privilege levels also switches stacks. The return procedure’s stackpointer is popped off the stack and into the SS and rSP registers. If an immediate operand is includedwith the RET instruction, the newly-loaded stack pointer is adjusted by the number of bytes indicated.Figure 3-15 shows the stack pointer before (old SS:rSP value) and after (new SS:rSP value) the RET.“Segmented Virtual Memory” in Volume 2 provides additional information on privilege-changingRETs.OldProcedureStackReturnProcedureStackReturn SSReturn rSPParametersNew SS:rSP...ParametersReturn CSReturn rIP...Old SS:rSP513-180.epsFigure 3-15.

Procedure Stack, Far Return from Less PrivilegeGeneral-Purpose Programming83AMD64 Technology24592—Rev. 3.13—July 20073.7.7 System CallsA disadvantage of far CALLs and far RETs is that they use segment-based protection and privilegechecking. This involves significant overhead associated with loading new segment selectors and theircorresponding descriptors into the segment registers. The overhead includes not only the time requiredto load the descriptors from memory but also the time required to perform the privilege, type, and limitchecks. Privilege-changing CALLs to the operating system are slowed further by the control transferthrough a gate descriptor.SYSCALL and SYSRET.

SYSCALL and SYSRET are low-latency system-call and system-returncontrol-transfer instructions. They can be used in protected mode. These instructions eliminatesegment-based privilege checking by using pre-determined target and return code segments and stacksegments. The operating system sets up and maintains the predetermined segments using specialregisters within the processor, so the segment descriptors do not need to be fetched from memory whenthe instructions are used. The simplifications made to privilege checking allow SYSCALL andSYSRET to complete in far fewer processor clock cycles than CALL and RET.SYSRET can only be used to return from CPL = 0 procedures and is not available to applicationsoftware.

SYSCALL can be used by applications to call operating system service routines running atCPL = 0. The SYSCALL instruction does not take operands. Linkage conventions are initialized andmaintained by the operating system. “System-Management Instructions” in Volume 2 containsdetailed information on the operation of SYSCALL and SYSRET.SYSENTER and SYSEXIT. The SYSENTER and SYSEXIT instructions provide similar capabilitiesto SYSCALL and SYSRET. However, these instructions can be used only in legacy mode and are notsupported in long mode. SYSCALL and SYSRET are the preferred instructions for calling privilegedsoftware. See “System-Management Instructions” in Volume 2 for further information on SYSENTERand SYSEXIT.3.7.8 General Considerations for BranchingBranching causes delays which are a function of the hardware-implementation’s branch-predictioncapabilities.

Sequential flow avoids the delays caused by branching but is still exposed to delayscaused by cache misses, memory bus bandwidth, and other factors.In general, branching code should be replaced with sequential code whenever practical. This isespecially important if the branch body is small (resulting in frequent branching) and when branchesdepend on random data (resulting in frequent mispredictions of the branch target). In certain hardwareimplementations, far branches (as opposed to near branches) may not be predictable by the hardware,and recursive functions (those that call themselves) may overflow a return-address stack.All calls and returns should be paired for optimal performance. Hardware implementations thatinclude a return-address stack can lose stack synchronization if calls and returns are not paired.84General-Purpose Programming24592—Rev. 3.13—July 2007AMD64 Technology3.7.9 Branching in 64-Bit ModeNear Branches in 64-Bit Mode.

The long-mode architecture expands the near-branch mechanismsto accommodate branches in the full 64-bit virtual-address space. In 64-bit mode, the operand size forall near branches defaults to 64 bits, so these instructions update the full 64-bit RIP.Table 3-9 lists the near-branch instructions.Table 3-9.Near Branches in 64-Bit ModeOperand Size (bits)MnemonicCALLOpcode (hex)E8, FF /2DescriptionDefaultPossibleOverrides16416Call Procedure Near70 to 7F,Jump Conditional0F 80 to 0F 8FJccJCXZJECXZJRCXZJMPLOOPE3Jump on CX/ECX/RCX ZeroEB, E9, FF /4 Jump NearE2LoopLOOPccE0, E1Loop if Zero/Equal or Not Zero/EqualRETC2, C3Return From Call (near)Note:1.

There is no 32-bit operand-size override prefix in 64-bit mode.The default 64-bit operand size eliminates the need for a REX prefix with these instructions whenregisters RAX–RSP (the first set of eight GPRs) are used as operands. A REX prefix is still required ifR8–R15 (the extended set of eight GPRs) are used as operands, because the prefix is required toaddress the extended registers.The following aspects of near branches are controlled by the effective operand size:••••Truncation of the instruction pointer.Size of a stack pop or push, resulting from a CALL or RET.Size of a stack-pointer increment or decrement, resulting from a CALL or RET.Indirect-branch operand size.In 64-bit mode, all of the above actions are forced to 64 bits.

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

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

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

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