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

Volume 2 System Programming (794096), страница 38

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

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

If they are equal, the processor performs the next check. If theyare not equal, a general-protection exception (#GP) occurs.2. RPL ≤ CPL Check—The processor compares the target code-segment selector RPL with thecurrently executing program CPL. If the RPL is less than or equal to the CPL, access is allowed.

Ifthe RPL is greater than the CPL, a #GP exception occurs.If access is allowed, the processor loads the CS and rIP registers with their new values and beginsexecuting from the target location. The CPL is not changed—the target-CS selector RPL value isdisregarded when the selector is loaded into the CS register.Figure 4-28 on page 100 shows three examples of privilege checks performed as a result of a farcontrol transfer to a nonconforming code-segment. In Example 1, access is allowed because CPL =DPL and RPL ≤ CPL. In Example 2, access is denied because CPL ≠ DPL.

In Example 3, access isdenied because RPL > CPL.Segmented Virtual Memory99AMD64 TechnologyCodeSelector24593—Rev. 3.13—July 2007RPL=0≤CSAccessAllowedAccess AllowedCPL=2?=DPL=2CodeSegmentAccessAllowedDescriptorExample 1: Privilege Check PassesCodeSelectorRPL=0≤CSAccessAllowedAccess DeniedCPL=2?=DPL=3CodeSegmentAccessDeniedDescriptorExample 2: Privilege Check FailsCodeSelectorRPL=3≤CSCPL=2Access Denied?=DPL=2AccessDeniedAccessAllowedCodeSegmentDescriptorExample 3: Privilege Check FailsFigure 4-28.513-230.epsNonconforming Code-Segment Privilege-Check ExamplesConforming Code Segments.

On a direct control transfer to a conforming code segment, the targetcode-segment descriptor DPL can be lower than (at a greater privilege) the CPL. Before loading the100Segmented Virtual Memory24593—Rev. 3.13—July 2007AMD64 TechnologyCS register with a conforming code-segment selector, the processor compares the target code-segmentdescriptor DPL with the currently-executing program CPL. If the DPL is less than or equal to the CPL,access is allowed. If the DPL is greater than the CPL, a #GP exception occurs.On an access to a conforming code segment, the RPL is ignored and not involved in the privilegecheck.When access is allowed, the processor loads the CS and rIP registers with their new values and beginsexecuting from the target location. The CPL is not changed—the target CS-descriptor DPL value isdisregarded when the selector is loaded into the CS register.

The target program runs at the sameprivilege as the program that called it.Figure 4-29 shows two examples of privilege checks performed as a result of a direct control transferto a conforming code segment. In Example 1, access is allowed because the CPL of 3 is greater thanthe DPL of 0. As the target code selector is loaded into the CS register, the old CPL value of 3 replacesthe target-code selector RPL value, and the target program executes with CPL=3.

In Example 2, accessis denied because CPL < DPL.CodeSelectorCSCPL=3≥Access AllowedDPL=0CodeSegmentDescriptorExample 1: Privilege Check PassesCodeSelectorCSCPL=0≥Access DeniedDPL=3CodeSegmentDescriptorExample 2: Privilege Check Fails513-231.epsFigure 4-29. Conforming Code-Segment Privilege-Check ExamplesSegmented Virtual Memory101AMD64 Technology24593—Rev. 3.13—July 20074.11.2 Control Transfers Through Call GatesControl transfers to more-privileged code segments are accomplished through the use of call gates.Call gates are a type of descriptor that contain pointers to code-segment descriptors and control accessto those descriptors. System software uses call gates to establish protected entry points into systemservice routines.Transfer Mechanism. The pointer operand of a far-CALL or far-JMP instruction consists of twopieces: a code-segment selector (CS) and a code-segment offset (rIP).

In a call-gate transfer, the CSselector points to a call-gate descriptor rather than a code-segment descriptor, and the rIP is ignored(but required by the instruction).Figure 4-30 shows a call-gate control transfer in legacy mode. The call-gate descriptor containssegment-selector and segment-offset fields (see “Gate Descriptors” on page 84 for a detaileddescription of the call-gate format and fields). These two fields perform the same function as thepointer operand in a direct control-transfer instruction.

The segment-selector field points to the targetcode-segment descriptor, and the segment-offset field is the instruction-pointer offset into the targetcode-segment. The code-segment base taken from the code-segment descriptor is added to the offsetfield in the call-gate descriptor to create the target virtual address (linear address).Virtual-AddressSpaceFar PointerSegment SelectorInstruction OffsetDescriptor TableCall-GateDescriptorDPL Code-Segment SelectorCode-Segment Offset+Virtual AddressCode SegmentDPLCode-Segment LimitCode-Segment BaseCode-SegmentDescriptor513-233.epsFigure 4-30.102Legacy-Mode Call-Gate Transfer MechanismSegmented Virtual Memory24593—Rev.

3.13—July 2007AMD64 TechnologyFigure 4-31 shows a call-gate control transfer in long mode. The long-mode call-gate descriptorformat is expanded by 64 bits to hold a full 64-bit offset into the virtual-address space. Only longmode call gates can be referenced in long mode (64-bit mode and compatibility mode). The legacymode 32-bit call-gate types are redefined in long mode as 64-bit types, and 16-bit call-gate types areillegal.Far PointerVirtual-AddressSpaceSegment SelectorInstruction OffsetDescriptor TableCall-GateDescriptorCode-Segment Offset (63:32)DPL Code-Segment SelectorVirtual AddressCode-Segment Offset (31:0)DPLCode-Segment LimitCode-Segment BaseCode-SegmentDescriptorFlat Code-SegmentUnusedFigure 4-31.513-234.epsLong-Mode Call-Gate Access MechanismA long-mode call gate must reference a 64-bit code-segment descriptor.

In 64-bit mode, the codesegment descriptor base-address and limit fields are ignored. The target virtual-address is the 64-bitoffset field in the expanded call-gate descriptor.Privilege Checks. Before loading the CS register with the code-segment selector located in the callgate, the processor performs three privilege checks. The following checks are performed when eitherconforming or nonconforming code segments are referenced:1.

The processor compares the CPL with the call-gate DPL from the call-gate descriptor (DPLG).The CPL must be numerically less than or equal to DPLG for this check to pass. In other words,the following expression must be true: CPL ≤ DPLG.Segmented Virtual Memory103AMD64 Technology24593—Rev. 3.13—July 20072. The processor compares the RPL in the call-gate selector with DPLG. The RPL must benumerically less than or equal to DPLG for this check to pass. In other words, the followingexpression must be true: RPL ≤ DPLG.3. The processor compares the CPL with the target code-segment DPL from the code-segmentdescriptor (DPLS).

The type of comparison varies depending on the type of control transfer.- When a call—or a jump to a conforming code segment—is used to transfer control through acall gate, the CPL must be numerically greater than or equal to DPLS for this check to pass.(This check prevents control transfers to less-privileged programs.) In other words, thefollowing expression must be true: CPL ≥ DPLS.- When a JMP instruction is used to transfer control through a call gate to a nonconforming codesegment, the CPL must be numerically equal to DPLS for this check to pass.

(JMP instructionscannot change CPL.) In other words, the following expression must be true: CPL = DPLS.Figure 4-32 on page 105 shows two examples of call-gate privilege checks. In Example 1, all privilegechecks pass as follows:•••The call-gate DPL (DPLG) is at the lowest privilege (3), specifying that software running at anyprivilege level (CPL) can access the gate.The selector referencing the call gate passes its privilege check because the RPL is numericallyless than or equal to DPLG.The target code segment is at the highest privilege level (DPLS = 0). This means software runningat any privilege level can access the target code segment through the call gate.104Segmented Virtual Memory24593—Rev. 3.13—July 2007CSCPL=2Call-GateSelectorRPL=3AMD64 TechnologyDPLG=3CodeSegmentCall-Gate DescriptorDPLS=0Access AllowedCode-Segment DescriptorExample 1: Privilege Check PassesCSCPL=2Call-GateSelectorRPL=3DPLG=0CodeSegmentCall-Gate DescriptorDPLS=3Access DeniedCode-Segment DescriptorExample 2: Privilege Check FailsFigure 4-32.513-232.epsPrivilege-Check Examples for Call GatesIn Example 2, all privilege checks fail as follows:••The call-gate DPL (DPLG) specifies that only software at privilege-level 0 can access the gate.

Thecurrent program does not have enough privilege to access the call gate because its CPL is 2.The selector referencing the call-gate descriptor does not have enough privilege to complete thereference. Its RPL is numerically greater than DPLG.Segmented Virtual Memory105AMD64 Technology•24593—Rev. 3.13—July 2007The target code segment is at a lower privilege (DPLS = 3) than the currently running software(CPL = 2).

Transitions from more-privileged software to less-privileged software are not allowed,so this privilege check fails as well.Although all three privilege checks failed in Example 2, failing only one check is sufficient to denyaccess into the target code segment.Stack Switching. The processor performs an automatic stack switch when a control transfer causes achange in privilege levels to occur. Switching stacks isolates more-privileged software stacks fromless-privileged software stacks and provides a mechanism for saving the return pointer back to theprogram that initiated the call.When switching to more-privileged software, as is done when transferring control using a call gate, theprocessor uses the corresponding stack pointer (privilege-level 0, 1, or 2) stored in the task-statesegment (TSS).

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

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

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

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