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

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

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

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

Branches are used to iterate through loops and move through conditionalprogram logic. Branches cause a new instruction pointer to be loaded into the rIP register, andsometimes cause the CS register to point to a different code segment. The CS:rIP values can bespecified as part of a branch instruction, or they can be read from a register or memory.Branches can also be used to transfer control to another program or procedure running at a differentprivilege level. In such cases, the processor automatically checks the source program and targetprogram privileges to ensure that the transfer is allowed before loading CS:rIP with the new values.3.7.2 Privilege LevelsThe processor’s protected modes include legacy protected mode and long mode (both compatibilitymode and 64-bit mode).

In all protected modes and virtual x86 mode, privilege levels are used toisolate and protect programs and data from each other. The privilege levels are designated with anumerical value from 0 to 3, with 0 being the most privileged and 3 being the least privileged. Privilege0 is normally reserved for critical system-software components that require direct access to, andcontrol over, all processor and system resources. Privilege 3 is used by application software. Theintermediate privilege levels (1 and 2) are used, for example, by device drivers and library routines thataccess and control a limited set of processor and system resources.76General-Purpose Programming24592—Rev.

3.13—July 2007AMD64 TechnologyFigure 3-9 shows the relationship of the four privilege-levels to each other. The protection scheme isimplemented using the segmented memory-management mechanism described in “Segmented VirtualMemory” in Volume 2.Memory ManagementFile AllocationInterrupt HandlingPrivilege0Device-DriversLibrary RoutinesPrivilege 1Privilege 2513-236.epsPrivilege 3Application ProgramsFigure 3-9.

Privilege-Level Relationships3.7.3 Procedure StackA procedure stack is often used by control transfer operations, particularly those that change privilegelevels. Information from the calling program is passed to the target program on the procedure stack.CALL instructions, interrupts, and exceptions all push information onto the procedure stack. Thepushed information includes a return pointer to the calling program and, for call instructions,optionally includes parameters. When a privilege-level change occurs, the calling program’s stackpointer (the pointer to the top of the stack) is pushed onto the stack. Interrupts and exceptions also pusha copy of the calling program’s rFLAGs register and, in some cases, an error code associated with theinterrupt or exception.The RET or IRET control-transfer instructions reverse the operation of CALLs, interrupts, andexceptions.

These return instructions pop the return pointer off the stack and transfer control back tothe calling program. If the calling program’s stack pointer was pushed, it is restored by popping thesaved values off the stack and into the SS and rSP registers.Stack Alignment. Control-transfer performance can degrade significantly when the stack pointer isnot aligned properly. Stack pointers should be word aligned in 16-bit segments, doubleword aligned in32-bit segments, and quadword aligned in 64-bit mode.Stack Operand-Size in 64-Bit Mode.

In 64-bit mode, the stack pointer size is always 64 bits. Thestack size is not controlled by the default-size (B) bit in the SS descriptor, as it is in compatibility andlegacy modes, nor can it be overridden by an instruction prefix. Address-size overrides are ignored forimplicit stack references.General-Purpose Programming77AMD64 Technology24592—Rev. 3.13—July 2007Except for far branches, all instructions that implicitly reference the stack pointer default to 64-bitoperand size in 64-bit mode.

Table 3-8 on page 79 lists these instructions.The default 64-bit operand size eliminates the need for a REX prefix with these instructions. However,a REX prefix is still required if R8–R15 (the extended set of eight GPRs) are used as operands,because the prefix is required to address the extended registers. Pushes and pops of 32-bit stack valuesare not possible in 64-bit mode with these instructions, because there is no 32-bit operand-sizeoverride prefix for 64-bit mode.3.7.4 JumpsJump instructions provide a simple means for transferring program control from one location toanother. Jumps do not affect the procedure stack, and return instructions cannot transfer control back tothe instruction following a jump.

Two general types of jump instruction are available: unconditional(JMP) and conditional (Jcc).There are two types of unconditional jumps (JMP):••Near Jumps—When the target address is within the current code segment.Far Jumps—When the target address is outside the current code segment.Although unconditional jumps can be used to change code segments, they cannot be used to changeprivilege levels.Conditional jumps (Jcc) test the state of various bits in the rFLAGS register (or rCX) and jump to atarget location based on the results of that test. Only near forms of conditional jumps are available, soJcc cannot be used to transfer control to another code segment.78General-Purpose Programming24592—Rev. 3.13—July 2007Table 3-8.AMD64 TechnologyInstructions that Implicitly Reference RSP in 64-Bit ModeOperand Size (bits)MnemonicCALLOpcode(hex)E8, FF /2DescriptionC8Create Procedure Stack FrameLEAVEC9Delete Procedure Stack Frame8F /0Pop Stack (register or memory)POP reg58 to 5FPOP FS0F A1Pop Stack into FS Segment RegisterPOP GS0F A9Pop Stack into GS Segment RegisterPOPFPOPFQ9DPop to EFLAGS Word or QuadwordPUSH imm3268Push onto Stack (sign-extended doubleword)PUSH imm86APush onto Stack (sign-extended byte)PUSH reg/memFF /6Push onto Stack (register or memory)PUSH reg50–57Push onto Stack (register)PUSH FS0F A0Push FS Segment Register onto StackPUSH GS0F A8Push GS Segment Register onto StackPUSHFPUSHFQ9CRETC2, C3PossibleOverrides16416Call Procedure NearENTERPOP reg/memDefaultPop Stack (register)Push rFLAGS Word or Quadword onto StackReturn From Call (near)Note:1.

There is no 32-bit operand-size override prefix in 64-bit mode.3.7.5 Procedure CallsThe CALL instruction transfers control unconditionally to a new address, but unlike jump instructions,it saves a return pointer (CS:rIP) on the stack. The called procedure can use the RET instruction to popthe return pointers to the calling procedure from the stack and continue execution with the instructionfollowing the CALL.There are four types of CALL:••••Near Call—When the target address is within the current code segment.Far Call—When the target address is outside the current code segment.Interprivilege-Level Far Call—A far call that changes privilege level.Task Switch—A call to a target address in another task.Near Call.

When a near CALL is executed, only the calling procedure’s rIP (the return offset) ispushed onto the stack. After the rIP is pushed, control is transferred to the new rIP value specified byGeneral-Purpose Programming79AMD64 Technology24592—Rev. 3.13—July 2007the CALL instruction. Parameters can be pushed onto the stack by the calling procedure prior toexecuting the CALL instruction.

Figure 3-10 shows the stack pointer before (old rSP value) and after(new rSP value) the CALL. The stack segment (SS) is not changed.ProcedureStackParameters...Return rIPOld rSPNew rSP513-175.epsFigure 3-10. Procedure Stack, Near CallFar Call, Same Privilege. A far CALL changes the code segment, so the full return pointer (CS:rIP)is pushed onto the stack.

After the return pointer is pushed, control is transferred to the new CS:rIPvalue specified by the CALL instruction. Parameters can be pushed onto the stack by the callingprocedure prior to executing the CALL instruction. Figure 3-11 shows the stack pointer before (oldrSP value) and after (new rSP value) the CALL. The stack segment (SS) is not changed.ProcedureStackParameters...Old rSPReturn CSReturn rIPNew rSP513-176.epsFigure 3-11.Procedure Stack, Far Call to Same PrivilegeFar Call, Greater Privilege. A far CALL to a more-privileged procedure performs a stack switchprior to transferring control to the called procedure.

Switching stacks isolates the more-privilegedprocedure’s stack from the less-privileged procedure’s stack, and it provides a mechanism for savingthe return pointer back to the procedure that initiated the call.Calls to more-privileged software can only take place through a system descriptor called a call-gatedescriptor.

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

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

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

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