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

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

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

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

The flags tested by a specific Jcc instruction depend on theopcode. In several cases, multiple mnemonics correspond to one opcode.Table 3-6 shows the rFLAGS values required for each Jcc instruction.Table 3-6. rFLAGS for Jcc InstructionsMnemonicRequired Flag StateDescriptionJOOF = 1Jump near if overflowJNOOF = 0Jump near if not overflowJBJCJNAECF = 1Jump near if belowJump near if carryJump near if not above or equalJNBJNCJAECF = 0Jump near if not belowJump near if not carryJump near if above or equalJZJEZF = 1Jump near if 0Jump near if equalJNZJNEZF = 0Jump near if not zeroJump near if not equalJNAJBECF = 1 or ZF = 1Jump near if not aboveJump near if below or equalJNBEJACF = 0 and ZF = 0Jump near if not below or equalJump near if aboveJSSF = 1Jump near if signJNSSF = 0Jump near if not signJPJPEPF = 1Jump near if parityJump near if parity evenJNPJPOPF = 0Jump near if not parityJump near if parity oddJLJNGESF <> OFJump near if lessJump near if not greater or equalGeneral-Purpose Programming59AMD64 Technology24592—Rev.

3.13—July 2007Table 3-6. rFLAGS for Jcc Instructions (continued)MnemonicRequired Flag StateDescriptionJGEJNLSF = OFJump near if greater or equalJump near if not lessJNGJLEZF = 1 or SF <> OFJump near if not greaterJump near if less or equalJNLEJGZF = 0 and SF = OFJump near if not less or equalJump near if greaterUnlike the unconditional jump (JMP), conditional jump instructions have only two forms—nearconditional jumps and short conditional jumps. To create a far-conditional-jump code sequencecorresponding to a high-level language statement like:IF A = B THEN GOTO FarLabelwhere FarLabel is located in another code segment, use the opposite condition in a conditional shortjump before the unconditional far jump.

For example:cmpjnejmpNextInstr:A,BNextInstrfar ptr WhenNE;;;;compare operandscontinue program if not equalfar jump if operands are equalcontinue programThree special conditional jump instructions use the rCX register instead of flags. The JCXZ, JECXZ,and JRCXZ instructions check the value of the CX, ECX, and RCX registers, respectively, and passcontrol to the target instruction when the value of rCX register reaches 0. These instructions are oftenused to control safe cycles, preventing execution when the value in rCX reaches 0.Loop• LOOPcc—Loop if conditionThe LOOPcc instructions include LOOPE, LOOPNE, LOOPNZ, and LOOPZ.

These instructionsdecrement the rCX register by 1 without changing any flags, and then check to see if the loop conditionis met. If the condition is met, the program jumps to the specified target code.LOOPE and LOOPZ are synonyms. Their loop condition is met if the value of the rCX register is nonzero and the zero flag (ZF) is set to 1 when the instruction starts. LOOPNE and LOOPNZ are alsosynonyms. Their loop condition is met if the value of the rCX register is non-zero and the ZF flag iscleared to 0 when the instruction starts. LOOP, unlike the other mnemonics, does not check the ZFflag. Its loop condition is met if the value of the rCX register is non-zero.Call• CALL—Procedure CallThe CALL instruction performs a call to a procedure whose address is specified in the operand.

Thereturn address is placed on the stack by the CALL, and points to the instruction immediately following60General-Purpose Programming24592—Rev. 3.13—July 2007AMD64 Technologythe CALL. When the called procedure finishes execution and is exited using a return instruction,control is transferred to the return address saved on the stack.The CALL instruction has the same forms as the JMP instruction, except that CALL lacks the shortrelative (1-byte offset) form.••••Relative Near Call—These specify an offset relative to the instruction following the CALLinstruction.

The operand is an immediate 16-bit or 32-bit offset from the called procedure, withinthe same code segment.Register-Indirect and Memory-Indirect Near Call—These specify a target address contained in aregister or memory location.Direct Far Call—These specify a target address outside the current code segment. The address ispointed to by a 32-bit or 48-bit far-pointer specified by the instruction, which consists of a 16-bitcode selector and a 16-bit or 32-bit offset. The direct far call form is invalid in 64-bit mode.Memory-Indirect Far Call—These specify a target address outside the current code segment.

Theaddress is pointed to by a 32-bit or 48-bit far pointer in a specified memory location.The size of the rIP is in all cases determined by the operand-size attribute of the CALL instruction.CALLs push the return address to the stack. The data pushed on the stack depends on whether a near orfar call is performed, and whether a privilege change occurs. See Section 3.7.5, “Procedure Calls,” onpage 79 for further information.For far CALLs, the selector portion of the target address can specify a code-segment selector (in whichcase the selector is loaded into the CS register), or a call-gate selector, (used for calls that changeprivilege level), or a task-state-segment (TSS) selector (used for task switches).

In the latter two cases,the offset portion of the CALL instruction’s target address is ignored, and the new values loaded intoCS and rIP are taken from the call gate or TSS.Return• RET—Return from CallThe RET instruction returns from a procedure originally called using the CALL instruction. CALLplaces a return address (which points to the instruction following the CALL) on the stack. RET takesthe return address from the stack and transfers control to the instruction located at that address.Like CALL instructions, RET instructions have both a near and far form.

An optional immediateoperand for the RET specifies the number of bytes to be popped from the procedure stack forparameters placed on the stack. See Section 3.7.6, “Returning from Procedures,” on page 81 foradditional information.Interrupts and Exceptions.•••INT—Interrupt to Vector NumberINTO—Interrupt to Overflow VectorIRET—Interrupt Return WordGeneral-Purpose Programming61AMD64 Technology••24592—Rev. 3.13—July 2007IRETD—Interrupt Return DoublewordIRETQ—Interrupt Return QuadwordThe INT instruction implements a software interrupt by calling an interrupt handler. The operand ofthe INT instruction is an immediate byte value specifying an index in the interrupt descriptor table(IDT), which contains addresses of interrupt handlers (see Section 3.7.10, “Interrupts and Exceptions,”on page 86 for further information on the IDT).The 1-byte INTO instruction calls interrupt 4 (the overflow exception, #OF), if the overflow flag inRFLAGS is set to 1, otherwise it does nothing.

Signed arithmetic instructions can be followed by theINTO instruction if the result of the arithmetic operation can potentially overflow. (The 1-byte INT 3instruction is considered a system instruction and is therefore not described in this volume).IRET, IRETD, and IRETQ perform a return from an interrupt handler. The mnemonic specifies theoperand size, which determines the format of the return addresses popped from the stack (IRET for 16bit operand size, IRETD for 32-bit operand size, and IRETQ for 64-bit operand size). However, someassemblers can use the IRET mnemonic for all operand sizes.

Actions performed by IRET are oppositeto actions performed by an interrupt or exception. In real and protected mode, IRET pops the rIP, CS,and RFLAGS contents from the stack, and it pops SS:rSP if a privilege-level change occurs or if itexecutes from 64-bit mode. In protected mode, the IRET instruction can also cause a task switch if thenested task (NT) bit in the RFLAGS register is set. For details on using IRET to switch tasks, see “TaskManagement” in Volume 2.3.3.12 FlagsThe flags instructions read and write bits of the RFLAGS register that are visible to applicationsoftware. “Flags Register” on page 33 illustrates the RFLAGS register.Push and Pop Flags• POPF—Pop to FLAGS Word• POPFD—Pop to EFLAGS Doubleword• POPFQ—Pop to RFLAGS Quadword• PUSHF—Push FLAGS Word onto Stack• PUSHFD—Push EFLAGS Doubleword onto Stack• PUSHFQ—Push RFLAGS Quadword onto StackThe push and pop flags instructions copy data between the rFLAGS register and the stack.

POPF andPUSHF copy 16 bits of data between the stack and the FLAGS register (the low 16 bits of EFLAGS),leaving the high 48 bits of RFLAGS unchanged. POPFD and PUSHFD copy 32 bits between the stackand the RFLAGS register. POPFQ and PUSHFQ copy 64 bits between the stack and the RFLAGSregister. Only the bits illustrated in Figure 3-5 on page 34 are affected. Reserved bits and bits whosewritability is prevented by the current values of system flags, current privilege level (CPL), or currentoperating mode, are unaffected by the POPF, POPFQ, and POPFD instructions.62General-Purpose Programming24592—Rev.

3.13—July 2007AMD64 TechnologyFor details on stack operations, see “Control Transfers” on page 76.Set and Clear Flags•••••••CLC—Clear Carry FlagCMC—Complement Carry FlagSTC—Set Carry FlagCLD—Clear Direction FlagSTD—Set Direction FlagCLI—Clear Interrupt FlagSTI—Set Interrupt FlagThese instructions change the value of a flag in the rFLAGS register that is visible to applicationsoftware. Each instruction affects only one specific flag.The CLC, CMC, and STC instructions change the carry flag (CF). CLC clears the flag to 0, STC setsthe flag to 1, and CMC inverts the flag. These instructions are useful prior to executing instructionswhose behavior depends on the CF flag—for example, shift and rotate instructions.The CLD and STD instructions change the direction flag (DF) and influence the function of stringinstructions (CMPSx, SCASx, MOVSx, LODSx, STOSx, INSx, OUTSx).

CLD clears the flag to 0,and STD sets the flag to 1. A cleared DF flag indicates the forward direction in string sequences, and aset DF flag indicates the backward direction. Thus, in string instructions, the rSI and/or rDI registervalues are auto-incremented when DF = 0 and auto-decremented when DF = 1.Two other instructions, CLI and STI, clear and set the interrupt flag (IF). CLI clears the flag, causingthe processor to ignore external maskable interrupts.

STI sets the flag, allowing the processor torecognize maskable external interrupts. These instructions are used primarily by system software—especially, interrupt handlers—and are described in “Exceptions and Interrupts” in Volume 2.Load and Store Flags• LAHF—Load Status Flags into AH Register• SAHF—Store AH into FlagsLAHF loads the lowest byte of the RFLAGS register into the AH register. This byte contains the carryflag (CF), parity flag (PF), auxiliary flag (AF), zero flag (ZF), and sign flag (SF). SAHF stores the AHregister into the lowest byte of the RFLAGS register.3.3.13 Input/OutputThe I/O instructions perform reads and writes of bytes, words, and doublewords from and to the I/Oaddress space. This address space can be used to access and manage external devices, and isindependent of the main-memory address space.

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

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

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

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