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

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

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

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

However, the size of the displacementfield for relative branches is still limited to 32 bits.The operand size of near branches is fixed at 64 bits without the need for a REX prefix. However, theaddress size of near branches is not forced in 64-bit mode. Such addresses are 64 bits by default, butthey can be overridden to 32 bits by a prefix.General-Purpose Programming85AMD64 Technology24592—Rev. 3.13—July 2007Branches to 64-Bit Offsets. Because immediates are generally limited to 32 bits, the only way a full64-bit absolute RIP can be specified in 64-bit mode is with an indirect branch. For this reason, directforms of far branches are invalid in 64-bit mode.3.7.10 Interrupts and ExceptionsInterrupts and exceptions are a form of control transfer operation.

They are used to call special systemservice routines, called interrupt handlers, which are designed to respond to the interrupt or exceptioncondition. Pointers to the interrupt handlers are stored by the operating system in an interruptdescriptor table, or IDT. In legacy real mode, the IDT contains an array of 4-byte far pointers tointerrupt handlers.

In legacy protected mode, the IDT contains an array of 8-byte gate descriptors. Inlong mode, the gate descriptors are 16 bytes. Interrupt gates, task gates, and trap gates can be stored inthe IDT, but not call gates.Interrupt handlers are usually privileged software because they typically require access to restrictedsystem resources. System software is responsible for creating the interrupt gates and storing them inthe IDT. “Exceptions and Interrupts” in Volume 2 contains detailed information on the interruptmechanism and the requirements on system software for managing the mechanism.The IDT is indexed using the interrupt number, or vector. How the vector is specified depends on thesource, as described below.

The first 32 of the available 256 interrupt vectors are reserved for internaluse by the processor—for exceptions (as described below) and other purposes.Interrupts are caused either by software or hardware. The INT, INT3, and INTO instructionsimplement a software interrupt by calling an interrupt handler directly. These are general-purpose(privilege-level-3) instructions.

The operand of the INT instruction is an immediate byte valuespecifying the interrupt vector used to index the IDT. INT3 and INTO are specific forms of softwareinterrupts used to call interrupt 3 and interrupt 4, respectively. External interrupts are produced bysystem logic which passes the IDT index to the processor via input signals. External interrupts can beeither maskable or non-maskable.Exceptions usually occur as a result of software execution errors or other internal-processor errors.Exceptions can also occur in non-error situations, such as debug-program single-stepping or addressbreakpoint detection. In the case of exceptions, the processor produces the IDT index based on thedetected condition.

The handlers for interrupts and exceptions are identical for a given vector.The processor’s response to an exception depends on the type of the exception. For all exceptionsexcept 128-bit-media and x87 floating-point exceptions, control automatically transfers to the handler(or service routine) for that exception, as defined by the exceptions vector.

For 128-bit-media and x87floating-point exceptions, there is both a masked and unmasked response. When unmasked, theseexceptions invoke their exception handler. When masked, a default masked response is providedinstead of invoking the exception handler.Exceptions and software-initiated interrupts occur synchronously with respect to the processor clock.There are three types of exceptions:86General-Purpose Programming24592—Rev.

3.13—July 2007•••AMD64 TechnologyFaults—A fault is a precise exception that is reported on the boundary before the interruptedinstruction. Generally, faults are caused by an undesirable error condition involving the interruptedinstruction, although some faults (such as page faults) are common and normal occurrences. Afterthe service routine completes, the machine state prior to the faulting instruction is restored, and theinstruction is retried.Traps—A trap is a precise exception that is reported on the boundary following the interruptedinstruction.

The instruction causing the exception finishes before the service routine is invoked.Software interrupts and certain breakpoint exceptions used in debugging are traps.Aborts—Aborts are imprecise exceptions. The instruction causing the exception, and possibly anindeterminate additional number of instructions, complete execution before the service routine isinvoked. Because they are imprecise, aborts typically do not allow reliable program restart.Table 3-10 shows the interrupts and exceptions that can occur, together with their vector numbers,mnemonics, source, and causes. For a detailed description of interrupts and exceptions, see“Exceptions and Interrupts” in Volume 2.Control transfers to interrupt handlers are similar to far calls, except that for the former, the rFLAGSregister is pushed onto the stack before the return address.

Interrupts and exceptions to several of thefirst 32 interrupts can also push an error code onto the stack. No parameters are passed by an interrupt.As with CALLs, interrupts that cause a privilege change also perform a stack switch.Table 3-10. Interrupts and ExceptionsVectorInterrupt (Exception)MnemonicSourceCauseGeneratedBy GeneralPurposeInstructions0Divide-By-Zero-Error#DESoftware DIV, IDIV instructions1Debug#DBInternalInstruction accesses anddata accessesyes2Non-Maskable-InterruptNMIExternalExternal NMI signalno3Breakpoint#BPSoftware INT3 instructionyes4Overflow#OFSoftware INTO instructionyes5Bound-Range#BRSoftware BOUND instructionyes6Invalid-Opcode#UDInternalInvalid instructionsyes7Device-Not-Available#NMInternalx87 instructionsno8Double-Fault#DFInternalInterrupt during an interruptyes9Coprocessor-SegmentOverrun—ExternalUnsupported (reserved)10Invalid-TSS#TSInternalTask-state segment accessand task switchyes11Segment-Not-Present#NPInternalSegment access through adescriptoryesGeneral-Purpose Programmingyes87AMD64 Technology24592—Rev.

3.13—July 2007Table 3-10. Interrupts and Exceptions (continued)VectorInterrupt (Exception)MnemonicSourceCauseGeneratedBy GeneralPurposeInstructions12Stack#SSInternalSS register loads and stackreferencesyes13General-Protection#GPInternalMemory accesses andprotection checksyes14Page-Fault#PFInternalMemory accesses whenpaging enabledyes15Reserved16x87 Floating-PointException-Pending#MFx87 floating-point and 64-bitSoftware media floating-pointinstructionsno17Alignment-Check#ACInternalMemory accessesyes18Machine-Check#MCInternalExternalModel specificyes19SIMD Floating-Point#XFInternal128-bit media floating-pointinstructionsno—20—31Reserved (Internal andExternal)32—255External Interrupts(Maskable)—External0—255 Software Interrupts—Software INT instruction—External interrupt signallingnoyesInterrupt to Same Privilege in Legacy Mode. When an interrupt to a handler running at the sameprivilege occurs, the processor pushes a copy of the rFLAGS register, followed by the return pointer(CS:rIP), onto the stack.

If the interrupt generates an error code, it is pushed onto the stack as the lastitem. Control is then transferred to the interrupt handler. Figure 3-16 on page 89 shows the stackpointer before (old rSP value) and after (new rSP value) the interrupt. The stack segment (SS) is notchanged.88General-Purpose Programming24592—Rev. 3.13—July 2007AMD64 TechnologyInterruptHandlerStackOld rSPrFLAGSReturn CSReturn rIPError CodeNew rSP513-182.epsFigure 3-16.Procedure Stack, Interrupt to Same PrivilegeInterrupt to More Privilege or in Long Mode. When an interrupt to a more-privileged handleroccurs or the processor is operating in long mode the processor locates the handler’s stack pointer fromthe TSS.

The old stack pointer (SS:rSP) is pushed onto the new stack, along with a copy of therFLAGS register. The return pointer (CS:rIP) to the interrupted program is then copied to the stack. Ifthe interrupt generates an error code, it is pushed onto the stack as the last item. Control is thentransferred to the interrupt handler. Figure 3-17 shows an example of a stack switch resulting from aninterrupt with a change in privilege.InterruptHandlerStackOldProcedureStackOld SS:rSPReturn SSReturn rSPrFLAGSReturn CSReturn rIPError CodeNew SS:rSP513-181.epsFigure 3-17.Procedure Stack, Interrupt to Higher PrivilegeInterrupt Returns. The IRET, IRETD, and IRETQ instructions are used to return from an interrupthandler.

Prior to executing an IRET, the interrupt handler must pop the error code off of the stack if onewas pushed by the interrupt or exception. IRET restores the interrupted program’s rIP, CS, andrFLAGS by popping their saved values off of the stack and into their respective registers. If a privilegechange occurs or IRET is executed in 64-bit mode, the interrupted program’s stack pointer (SS:rSP) isalso popped off of the stack. Control is then transferred back to the interrupted program.General-Purpose Programming89AMD64 Technology3.824592—Rev.

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

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

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

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