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

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

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

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

Not available (reserved) in legacy mode.4.9Segment-Protection OverviewThe AMD64 architecture is designed to fully support the legacy segment-protection mechanism. Thesegment-protection mechanism provides system software with the ability to restrict program accessinto other software routines and data.Segment-level protection remains enabled in compatibility mode. 64-bit mode eliminates most typechecking, and limit checking is not performed, except on accesses to system-descriptor tables.The preferred method of implementing memory protection in a long-mode operating system is to relyon the page-protection mechanism as described in “Page-Protection Checks” on page 141. Systemsoftware still needs to create basic segment-protection data structures for 64-bit mode.

Thesestructures are simplified, however, by the use of the flat-memory model in 64-bit mode, and the limitedsegmentation checks performed when executing in 64-bit mode.Segmented Virtual Memory93AMD64 Technology24593—Rev. 3.13—July 20074.9.1 Privilege-Level ConceptSegment protection is used to isolate and protect programs and data from each other. The segmentprotection mechanism supports four privilege levels in protected mode. The privilege levels aredesignated with a numerical value from 0 to 3, with 0 being the most privileged and 3 being the leastprivileged. System software typically assigns the privilege levels in the following manner:•••Privilege-level 0 (most privilege)—This level is used by critical system-software components thatrequire direct access to, and control over, all processor and system resources.

This can includeBIOS, memory-management functions, and interrupt handlers.Privilege-levels 1 and 2 (moderate privilege)—These levels are used by less-critical systemsoftware services that can access and control a limited scope of processor and system resources.Software running at these privilege levels might include some device drivers and library routines.These software routines can call more-privileged system-software services to perform functionssuch as memory garbage-collection and file allocation.Privilege-level 3 (least privilege)—This level is used by application software.

Software running atprivilege-level 3 is normally prevented from directly accessing most processor and systemresources. Instead, applications request access to the protected processor and system resources bycalling more-privileged service routines to perform the accesses.Figure 4-25 shows the relationship of the four privilege levels to each other.Memory ManagementFile AllocationInterrupt HandlingPrivilege0Device-DriversLibrary RoutinesPrivilege 1Privilege 2513-236.epsPrivilege 3Figure 4-25.Application ProgramsPrivilege-Level Relationships4.9.2 Privilege-Level TypesThere are three types of privilege levels the processor uses to control access to segments. These areCPL, DPL, and RPL.Current Privilege-Level. The current privilege-level (CPL) is the privilege level at which theprocessor is currently executing.

The CPL is stored in an internal processor register that is invisible to94Segmented Virtual Memory24593—Rev. 3.13—July 2007AMD64 Technologysoftware. Software changes the CPL by performing a control transfer to a different code segment witha new privilege level.Descriptor Privilege-Level. The descriptor privilege-level (DPL) is the privilege level that systemsoftware assigns to individual segments. The DPL is used in privilege checks to determine whethersoftware can access the segment referenced by the descriptor.

In the case of gate descriptors, the DPLdetermines whether software can access the descriptor reference by the gate. The DPL is stored in thesegment (or gate) descriptor.Requestor Privilege-Level. The requestor privilege-level (RPL) reflects the privilege level of theprogram that created the selector. The RPL can be used to let a called program know the privilege levelof the program that initiated the call. The RPL is stored in the selector used to reference the segment(or gate) descriptor.The following sections describe how the CPL, DPL, and RPL are used by the processor in performingprivilege checks on data accesses and control transfers.

Failure to pass a protection check generallycauses an exception to occur.4.10Data-Access Privilege Checks4.10.1 Accessing Data SegmentsBefore loading a data-segment register (DS, ES, FS, or GS) with a segment selector, the processorchecks the privilege levels as follows to see if access is allowed:1. The processor compares the CPL with the RPL in the data-segment selector and determines theeffective privilege level for the data access. The processor sets the effective privilege level to thelowest privilege (numerically-higher value) indicated by the comparison.2. The processor compares the effective privilege level with the DPL in the descriptor-table entryreferenced by the segment selector.

If the effective privilege level is greater than or equal to(numerically lower-than or equal-to) the DPL, then the processor loads the segment register withthe data-segment selector. The processor automatically loads the corresponding descriptor-tableentry into the hidden portion of the segment register.If the effective privilege level is lower than (numerically greater-than) the DPL, a generalprotection exception (#GP) occurs and the segment register is not loaded.Figure 4-26 on page 96 shows two examples of data-access privilege checks.Segmented Virtual Memory95AMD64 TechnologyCS24593—Rev. 3.13—July 2007EffectivePrivilegeCPL=3MaxDataSelector3RPL=0Access Denied≤DataSegmentDPL=2DescriptorExample 1: Privilege Check FailsCSEffectivePrivilegeCPL=0MaxDataSelector0RPL=0Access Allowed≤DataSegmentDPL=2DescriptorExample 2: Privilege Check PassesFigure 4-26.513-229.epsData-Access Privilege-Check ExamplesExample 1 in Figure 4-26 shows a failing data-access privilege check.

The effective privilege level is 3because CPL=3. This value is greater than the descriptor DPL, so access to the data segment is denied.Example 2 in Figure 4-26 shows a passing data-access privilege check. Here, the effective privilegelevel is 0 because both the CPL and RPL have values of 0.

This value is less than the descriptor DPL,so access to the data segment is allowed, and the data-segment register is successfully loaded.4.10.2 Accessing Stack SegmentsBefore loading the stack segment register (SS) with a segment selector, the processor checks theprivilege levels as follows to see if access is allowed:96Segmented Virtual Memory24593—Rev. 3.13—July 2007AMD64 Technology1. The processor checks that the CPL and the stack-selector RPL are equal. If they are not equal, ageneral-protection exception (#GP) occurs and the SS register is not loaded.2. The processor compares the CPL with the DPL in the descriptor-table entry referenced by thesegment selector.

The two values must be equal. If they are not equal, a #GP occurs and the SSregister is not loaded.Figure 4-27 shows two examples of stack-access privilege checks. In Example 1 the CPL, stackselector RPL, and stack segment-descriptor DPL are all equal, so access to the stack segment using theSS register is allowed. In Example 2, the stack-selector RPL and stack segment-descriptor DPL areboth equal. However, the CPL is not equal to the stack segment-descriptor DPL, and access to the stacksegment through the SS register is denied.CSCPL=3=StackSelectorRPL=3Access AllowedStackSegmentDPL=3DescriptorExample 1: Privilege Check PassesCSCPL=2=StackSelectorRPL=3Access DeniedStackSegmentDPL=3DescriptorExample 2: Privilege Check FailsFigure 4-27.Segmented Virtual Memory513-235.epsStack-Access Privilege-Check Examples97AMD64 Technology4.1124593—Rev.

3.13—July 2007Control-Transfer Privilege ChecksControl transfers between code segments (also called far control transfers) cause the processor toperform privilege checks to determine whether the source program is allowed to transfer control to thetarget program. If the privilege checks pass, access to the target code-segment is granted.

When accessis granted, the target code-segment selector is loaded into the CS register. The rIP register is updatedwith the target CS offset taken from either the far-pointer operand or the gate descriptor. Privilegechecks are not performed during near control transfers because such transfers do not changesegments.The following mechanisms can be used by software to perform far control transfers:••••••System-software control transfers using the system-call and system-return instructions. See“SYSCALL and SYSRET” on page 148 and “SYSENTER and SYSEXIT (Legacy Mode Only)”on page 150 for more information on these instructions. SYSCALL and SYSRET are the preferredmethod of performing control transfers in long mode.

SYSENTER and SYSEXIT are not supportedin long mode.Direct control transfers using CALL and JMP instructions. These are discussed in the next section,“Direct Control Transfers.”Call-gate control transfers using CALL and JMP instructions. These are discussed in “ControlTransfers Through Call Gates” on page 102.Return control transfers using the RET instruction. These are discussed in “Return ControlTransfers” on page 109.Interrupts and exceptions, including the INTn and IRET instructions.

These are discussed inChapter 8, “Exceptions and Interrupts.”Task switches initiated by CALL and JMP instructions. Task switches are discussed in Chapter 12,“Task Management.” The hardware task-switch mechanism is not supported in long mode.4.11.1 Direct Control TransfersA direct control transfer occurs when software executes a far-CALL or a far-JMP instruction withoutusing a call gate. The privilege checks and type of access allowed as a result of a direct control transferdepends on whether the target code segment is conforming or nonconforming.

The code-segmentdescriptor conforming (C) bit indicates whether or not the target code-segment is conforming (see“Conforming (C) Bit” on page 80 for more information on the conforming bit).Privilege levels are not changed as a result of a direct control transfer. Program stacks are notautomatically switched by the processor as they are with privilege-changing control transfers throughcall gates (see “Stack Switching” on page 106 for more information on automatic stack switchingduring privilege-changing control transfers).Nonconforming Code Segments. S o f t w a r e c a n p e r f o r m a d i r e c t c o n t r o l t r a n s f e r t o anonconforming code segment only if the target code-segment descriptor DPL and the CPL are equaland the RPL is less than or equal to the CPL.

Software must use a call gate to transfer control to a98Segmented Virtual Memory24593—Rev. 3.13—July 2007AMD64 Technologymore-privileged, nonconforming code segment (see “Control Transfers Through Call Gates” onpage 102 for more information).In far calls and jumps, the far pointer (CS:rIP) references the target code-segment descriptor. Beforeloading the CS register with a nonconforming code-segment selector, the processor checks as followsto see if access is allowed:1. DPL = CPL Check—The processor compares the target code-segment descriptor DPL with thecurrently executing program CPL.

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

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

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

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