Главная » Просмотр файлов » Volume 3A System Programming Guide_ Part 1

Volume 3A System Programming Guide_ Part 1 (794103), страница 47

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

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

For example, in Figure 4-15, call gate A has a DPL of 3. So calling procedures atall CPLs (0 through 3) can access this call gate, which includes calling procedures incode segments A, B, and C. Call gate B has a DPL of 2, so only calling procedures ata CPL or 0, 1, or 2 can access call gate B, which includes calling procedures in codeVol. 3 4-23PROTECTIONsegments B and C. The dotted line shows that a calling procedure in code segment Acannot access call gate B.The RPL of the segment selector to a call gate must satisfy the same test as the CPLof the calling procedure; that is, the RPL must be less than or equal to the DPL of thecall gate. In the example in Figure 4-15, a calling procedure in code segment C canaccess call gate B using gate selector B2 or B1, but it could not use gate selector B3to access call gate B.If the privilege checks between the calling procedure and call gate are successful, theprocessor then checks the DPL of the code-segment descriptor against the CPL of thecalling procedure.

Here, the privilege check rules vary between CALL and JMPinstructions. Only CALL instructions can use call gates to transfer program control tomore privileged (numerically lower privilege level) nonconforming code segments;that is, to nonconforming code segments with a DPL less than the CPL. A JMP instruction can use a call gate only to transfer program control to a nonconforming codesegment with a DPL equal to the CPL. CALL and JMP instruction can both transferprogram control to a more privileged conforming code segment; that is, to aconforming code segment with a DPL less than or equal to the CPL.If a call is made to a more privileged (numerically lower privilege level) nonconforming destination code segment, the CPL is lowered to the DPL of the destinationcode segment and a stack switch occurs (see Section 4.8.5, “Stack Switching”).

If acall or jump is made to a more privileged conforming destination code segment, theCPL is not changed and no stack switch occurs.4-24 Vol. 3PROTECTION3CodeSegment AGate Selector ARPL=3CPL=3Gate Selector B3RPL=3CallGate ADPL=3Lowest PrivilegeCodeSegment BCPL=2Gate Selector B1RPL=2CallGate BDPL=22CodeSegment CCPL=1Gate Selector B2RPL=1No StackSwitch Occurs1Stack SwitchOccursCodeSegment DDPL=00Highest PrivilegeConformingCode SegmentCodeSegment EDPL=0NonconformingCode SegmentFigure 4-12.

Example of Accessing Call Gates At Various Privilege LevelsCall gates allow a single code segment to have procedures that can be accessed atdifferent privilege levels. For example, an operating system located in a codesegment may have some services which are intended to be used by both the operating system and application software (such as procedures for handling characterI/O). Call gates for these procedures can be set up that allow access at all privilegelevels (0 through 3). More privileged call gates (with DPLs of 0 or 1) can then be setup for other operating system services that are intended to be used only by the operating system (such as procedures that initialize device drivers).4.8.5Stack SwitchingWhenever a call gate is used to transfer program control to a more privilegednonconforming code segment (that is, when the DPL of the nonconforming destination code segment is less than the CPL), the processor automatically switches to thestack for the destination code segment’s privilege level.

This stack switching iscarried out to prevent more privileged procedures from crashing due to insufficientstack space. It also prevents less privileged procedures from interfering (by accidentor intent) with more privileged procedures through a shared stack.Vol. 3 4-25PROTECTIONEach task must define up to 4 stacks: one for applications code (running at privilegelevel 3) and one for each of the privilege levels 2, 1, and 0 that are used. (If only twoprivilege levels are used [3 and 0], then only two stacks must be defined.) Each ofthese stacks is located in a separate segment and is identified with a segmentselector and an offset into the stack segment (a stack pointer).The segment selector and stack pointer for the privilege level 3 stack is located in theSS and ESP registers, respectively, when privilege-level-3 code is being executed andis automatically stored on the called procedure’s stack when a stack switch occurs.Pointers to the privilege level 0, 1, and 2 stacks are stored in the TSS for the currentlyrunning task (see Figure 6-2).

Each of these pointers consists of a segment selectorand a stack pointer (loaded into the ESP register). These initial pointers are strictlyread-only values. The processor does not change them while the task is running.They are used only to create new stacks when calls are made to more privilegedlevels (numerically lower privilege levels). These stacks are disposed of when areturn is made from the called procedure. The next time the procedure is called, anew stack is created using the initial stack pointer.

(The TSS does not specify a stackfor privilege level 3 because the processor does not allow a transfer of programcontrol from a procedure running at a CPL of 0, 1, or 2 to a procedure running at aCPL of 3, except on a return.)The operating system is responsible for creating stacks and stack-segment descriptors for all the privilege levels to be used and for loading initial pointers for thesestacks into the TSS.

Each stack must be read/write accessible (as specified in thetype field of its segment descriptor) and must contain enough space (as specified inthe limit field) to hold the following items:•••The contents of the SS, ESP, CS, and EIP registers for the calling procedure.The parameters and temporary variables required by the called procedure.The EFLAGS register and error code, when implicit calls are made to an exceptionor interrupt handler.The stack will need to require enough space to contain many frames of these items,because procedures often call other procedures, and an operating system maysupport nesting of multiple interrupts. Each stack should be large enough to allow forthe worst case nesting scenario at its privilege level.(If the operating system does not use the processor’s multitasking mechanism, it stillmust create at least one TSS for this stack-related purpose.)When a procedure call through a call gate results in a change in privilege level, theprocessor performs the following steps to switch stacks and begin execution of thecalled procedure at a new privilege level:1.

Uses the DPL of the destination code segment (the new CPL) to select a pointerto the new stack (segment selector and stack pointer) from the TSS.2. Reads the segment selector and stack pointer for the stack to be switched to fromthe current TSS. Any limit violations detected while reading the stack-segmentselector, stack pointer, or stack-segment descriptor cause an invalid TSS (#TS)exception to be generated.4-26 Vol. 3PROTECTION3. Checks the stack-segment descriptor for the proper privileges and type andgenerates an invalid TSS (#TS) exception if violations are detected.4. Temporarily saves the current values of the SS and ESP registers.5. Loads the segment selector and stack pointer for the new stack in the SS and ESPregisters.6. Pushes the temporarily saved values for the SS and ESP registers (for the callingprocedure) onto the new stack (see Figure 4-13).7.

Copies the number of parameter specified in the parameter count field of the callgate from the calling procedure’s stack to the new stack. If the count is 0, noparameters are copied.8. Pushes the return instruction pointer (the current contents of the CS and EIPregisters) onto the new stack.9. Loads the segment selector for the new code segment and the new instructionpointer from the call gate into the CS and EIP registers, respectively, and beginsexecution of the called procedure.See the description of the CALL instruction in Chapter 3, Instruction Set Reference, inthe IA-32 Intel Architecture Software Developer’s Manual, Volume 2, for a detaileddescription of the privilege level checks and other protection checks that theprocessor performs on a far call through a call gate.Called Procedure’s StackCalling Procedure’s StackCalling SSParameter 1Calling ESPParameter 2Parameter 1Parameter 3ESPParameter 2Parameter 3Calling CSCalling EIPESPFigure 4-13.

Stack Switching During an Interprivilege-Level CallThe parameter count field in a call gate specifies the number of data items (up to 31)that the processor should copy from the calling procedure’s stack to the stack of thecalled procedure. If more than 31 data items need to be passed to the called proce-Vol. 3 4-27PROTECTIONdure, one of the parameters can be a pointer to a data structure, or the savedcontents of the SS and ESP registers may be used to access parameters in the oldstack space.

The size of the data items passed to the called procedure depends onthe call gate size, as described in Section 4.8.3, “Call Gates.”4.8.5.1Stack Switching in 64-bit ModeAlthough protection-check rules for call gates are unchanged from 32-bit mode,stack-switch changes in 64-bit mode are different.When stacks are switched as part of a 64-bit mode privilege-level change through acall gate, a new SS (stack segment) descriptor is not loaded; 64-bit mode only loadsan inner-level RSP from the TSS.

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

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

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

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