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

Volume 1 Basic Architecture (794100), страница 38

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

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

Pushes the current value of the EIP register on the stack.2. Loads the offset of the called procedure in the EIP register.3. Begins execution of the called procedure.When executing a near return, the processor performs these actions:1. Pops the top-of-stack value (the return instruction pointer) into the EIP register.2. If the RET instruction has an optional n argument, increments the stack pointerby the number of bytes specified with the n operand to release parameters fromthe stack.3. Resumes execution of the calling procedure.Vol. 2 6-5PROCEDURE CALLS, INTERRUPTS, AND EXCEPTIONS6.3.2Far CALL and RET OperationWhen executing a far call, the processor performs these actions (see Figure 6-2):1. Pushes the current value of the CS register on the stack.2.

Pushes the current value of the EIP register on the stack.3. Loads the segment selector of the segment that contains the called procedure inthe CS register.4. Loads the offset of the called procedure in the EIP register.5. Begins execution of the called procedure.When executing a far return, the processor does the following:1. Pops the top-of-stack value (the return instruction pointer) into the EIP register.2. Pops the top-of-stack value (the segment selector for the code segment beingreturned to) into the CS register.3. If the RET instruction has an optional n argument, increments the stack pointerby the number of bytes specified with the n operand to release parameters fromthe stack.4.

Resumes execution of the calling procedure.6-6 Vol. 2PROCEDURE CALLS, INTERRUPTS, AND EXCEPTIONSStackFrameBeforeCallStackFrameAfterCallStack DuringNear CallParam 1Param 2Param 3Calling EIPStack DuringNear ReturnStackFrameBeforeCallESP Before CallESP After CallStackFrameAfterCallStack DuringFar CallParam 1Param 2Param 3Calling CSCalling EIPESP After CallStack DuringFar ReturnESP After ReturnParam 1Param 2Param 3Calling EIPESP Before CallESP Before ReturnESP After ReturnParam 1Param 2Param 3Calling CSCalling EIPESP Before ReturnNote: On a near or far return, parameters arereleased from the stack based on theoptional n operand in the RET n instruction.Figure 6-2. Stack on Near and Far Calls6.3.3Parameter PassingParameters can be passed between procedures in any of three ways: throughgeneral-purpose registers, in an argument list, or on the stack.6.3.3.1Passing Parameters Through the General-Purpose RegistersThe processor does not save the state of the general-purpose registers on procedurecalls.

A calling procedure can thus pass up to six parameters to the called procedureby copying the parameters into any of these registers (except the ESP and EBP registers) prior to executing the CALL instruction. The called procedure can likewise passparameters back to the calling procedure through general-purpose registers.6.3.3.2Passing Parameters on the StackTo pass a large number of parameters to the called procedure, the parameters can beplaced on the stack, in the stack frame for the calling procedure. Here, it is useful toVol. 2 6-7PROCEDURE CALLS, INTERRUPTS, AND EXCEPTIONSuse the stack-frame base pointer (in the EBP register) to make a frame boundary foreasy access to the parameters.The stack can also be used to pass parameters back from the called procedure to thecalling procedure.6.3.3.3Passing Parameters in an Argument ListAn alternate method of passing a larger number of parameters (or a data structure)to the called procedure is to place the parameters in an argument list in one of thedata segments in memory.

A pointer to the argument list can then be passed to thecalled procedure through a general-purpose register or the stack. Parameters canalso be passed back to the calling procedure in this same manner.6.3.4Saving Procedure State InformationThe processor does not save the contents of the general-purpose registers, segmentregisters, or the EFLAGS register on a procedure call. A calling procedure shouldexplicitly save the values in any of the general-purpose registers that it will needwhen it resumes execution after a return. These values can be saved on the stack orin memory in one of the data segments.The PUSHA and POPA instructions facilitate saving and restoring the contents of thegeneral-purpose registers. PUSHA pushes the values in all the general-purposeregisters on the stack in the following order: EAX, ECX, EDX, EBX, ESP (the valueprior to executing the PUSHA instruction), EBP, ESI, and EDI. The POPA instructionpops all the register values saved with a PUSHA instruction (except the ESP value)from the stack to their respective registers.If a called procedure changes the state of any of the segment registers explicitly, itshould restore them to their former values before executing a return to the callingprocedure.If a calling procedure needs to maintain the state of the EFLAGS register, it can saveand restore all or part of the register using the PUSHF/PUSHFD and POPF/POPFDinstructions.

The PUSHF instruction pushes the lower word of the EFLAGS register onthe stack, while the PUSHFD instruction pushes the entire register. The POPF instruction pops a word from the stack into the lower word of the EFLAGS register, while thePOPFD instruction pops a double word from the stack into the register.6.3.5Calls to Other Privilege LevelsThe IA-32 architecture’s protection mechanism recognizes four privilege levels,numbered from 0 to 3, where a greater number mean less privilege.

The reason touse privilege levels is to improve the reliability of operating systems. For example,Figure 6-3 shows how privilege levels can be interpreted as rings of protection.6-8 Vol. 2PROCEDURE CALLS, INTERRUPTS, AND EXCEPTIONSProtection RingsOperatingSystemKernelLevel 0Operating SystemServices (DeviceDrivers, Etc.)Level 1ApplicationsLevel 2Level 3Highest012Lowest3Privilege LevelsFigure 6-3. Protection RingsIn this example, the highest privilege level 0 (at the center of the diagram) is used forsegments that contain the most critical code modules in the system, usually thekernel of an operating system.

The outer rings (with progressively lower privileges)are used for segments that contain code modules for less critical software.Code modules in lower privilege segments can only access modules operating athigher privilege segments by means of a tightly controlled and protected interfacecalled a gate. Attempts to access higher privilege segments without going through aprotection gate and without having sufficient access rights causes a general-protection exception (#GP) to be generated.If an operating system or executive uses this multilevel protection mechanism, a callto a procedure that is in a more privileged protection level than the calling procedureis handled in a similar manner as a far call (see Section 6.3.2, “Far CALL and RETOperation”). The differences are as follows:•The segment selector provided in the CALL instruction references a special datastructure called a call gate descriptor.

Among other things, the call gatedescriptor provides the following:— access rights information— the segment selector for the code segment of the called procedure— an offset into the code segment (that is, the instruction pointer for the calledprocedure)Vol.

2 6-9PROCEDURE CALLS, INTERRUPTS, AND EXCEPTIONS•The processor switches to a new stack to execute the called procedure. Eachprivilege level has its own stack. The segment selector and stack pointer for theprivilege level 3 stack are stored in the SS and ESP registers, respectively, andare automatically saved when a call to a more privileged level occurs.

Thesegment selectors and stack pointers for the privilege level 2, 1, and 0 stacks arestored in a system segment called the task state segment (TSS).The use of a call gate and the TSS during a stack switch are transparent to the callingprocedure, except when a general-protection exception is raised.6.3.6CALL and RET Operation Between Privilege LevelsWhen making a call to a more privileged protection level, the processor does thefollowing (see Figure 6-4):1. Performs an access rights check (privilege check).2. Temporarily saves (internally) the current contents of the SS, ESP, CS, and EIPregisters.Stack FrameBefore CallStack forCalling ProcedureStack forCalled ProcedureParam 1Param 2Param 3Calling SSCalling ESPParam 1Param 2Param 3Calling CSCalling EIPESP Before CallESP After CallESP After ReturnParam 1Param 2Param 3ESP Before ReturnStack FrameAfter CallCalling SSCalling ESPParam 1Param 2Param 3Calling CSCalling EIPNote: On a return, parameters arereleased on both stacks based on theoptional n operand in the RET n instruction.Figure 6-4.

Stack Switch on a Call to a Different Privilege Level6-10 Vol. 2PROCEDURE CALLS, INTERRUPTS, AND EXCEPTIONS3. Loads the segment selector and stack pointer for the new stack (that is, the stackfor the privilege level being called) from the TSS into the SS and ESP registersand switches to the new stack.4.

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

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

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

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