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

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

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

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

Checks that the segment descriptor is a code, data, LDT, or TSS segmentdescriptor type.4. If the segment is not a conforming code segment, checks if the segmentdescriptor is visible at the CPL (that is, if the CPL and the RPL of the segmentselector less than or equal to the DPL).5. If the privilege level and type checks pass, loads the unscrambled limit (the limitscaled according to the setting of the G flag in the segment descriptor) into the4-36 Vol.

3PROTECTIONdestination register and sets the ZF flag in the EFLAGS register. If the segmentselector is not visible at the current privilege level or is an invalid type for the LSLinstruction, the instruction does not modify the destination register and clearsthe ZF flag.Once loaded in the destination register, software can compare the segment limit withthe offset of a pointer.4.10.4Checking Caller Access Privileges (ARPL Instruction)The requestor’s privilege level (RPL) field of a segment selector is intended to carrythe privilege level of a calling procedure (the calling procedure’s CPL) to a calledprocedure.

The called procedure then uses the RPL to determine if access to asegment is allowed. The RPL is said to “weaken” the privilege level of the calledprocedure to that of the RPL.Operating-system procedures typically use the RPL to prevent less privileged application programs from accessing data located in more privileged segments. When anoperating-system procedure (the called procedure) receives a segment selector froman application program (the calling procedure), it sets the segment selector’s RPL tothe privilege level of the calling procedure. Then, when the operating system usesthe segment selector to access its associated segment, the processor performs privilege checks using the calling procedure’s privilege level (stored in the RPL) ratherthan the numerically lower privilege level (the CPL) of the operating-system procedure.

The RPL thus insures that the operating system does not access a segment onbehalf of an application program unless that program itself has access to thesegment.Figure 4-15 shows an example of how the processor uses the RPL field. In thisexample, an application program (located in code segment A) possesses a segmentselector (segment selector D1) that points to a privileged data structure (that is, adata structure located in a data segment D at privilege level 0).The application program cannot access data segment D, because it does not havesufficient privilege, but the operating system (located in code segment C) can.

So, inan attempt to access data segment D, the application program executes a call to theoperating system and passes segment selector D1 to the operating system as aparameter on the stack. Before passing the segment selector, the (well behaved)application program sets the RPL of the segment selector to its current privilege level(which in this example is 3). If the operating system attempts to access datasegment D using segment selector D1, the processor compares the CPL (which isnow 0 following the call), the RPL of segment selector D1, and the DPL of datasegment D (which is 0).

Since the RPL is greater than the DPL, access to datasegment D is denied. The processor’s protection mechanism thus protects datasegment D from access by the operating system, because application program’s privilege level (represented by the RPL of segment selector B) is greater than the DPL ofdata segment D.Vol.

3 4-37PROTECTIONPassed as aparameter onthe stack.Application ProgramCodeSegment ACPL=33Gate Selector BRPL=3CallGate BSegment Sel. D1RPL=3DPL=3Lowest Privilege2Accessnotallowed1CodeOperating Segment CSystemDPL=00Highest PrivilegeSegment Sel. D2RPL=0AccessallowedDataSegment DDPL=0Figure 4-15. Use of RPL to Weaken Privilege Level of Called ProcedureNow assume that instead of setting the RPL of the segment selector to 3, the application program sets the RPL to 0 (segment selector D2).

The operating system cannow access data segment D, because its CPL and the RPL of segment selector D2 areboth equal to the DPL of data segment D.Because the application program is able to change the RPL of a segment selector toany value, it can potentially use a procedure operating at a numerically lower privilege level to access a protected data structure. This ability to lower the RPL of asegment selector breaches the processor’s protection mechanism.Because a called procedure cannot rely on the calling procedure to set the RPLcorrectly, operating-system procedures (executing at numerically lower privilegelevels) that receive segment selectors from numerically higher privilege-level procedures need to test the RPL of the segment selector to determine if it is at the appropriate level.

The ARPL (adjust requested privilege level) instruction is provided forthis purpose. This instruction adjusts the RPL of one segment selector to match thatof another segment selector.4-38 Vol. 3PROTECTIONThe example in Figure 4-15 demonstrates how the ARPL instruction is intended to beused. When the operating-system receives segment selector D2 from the applicationprogram, it uses the ARPL instruction to compare the RPL of the segment selectorwith the privilege level of the application program (represented by the code-segmentselector pushed onto the stack). If the RPL is less than application program’s privilege level, the ARPL instruction changes the RPL of the segment selector to match theprivilege level of the application program (segment selector D1).

Using this instruction thus prevents a procedure running at a numerically higher privilege level fromaccessing numerically lower privilege-level (more privileged) segments by loweringthe RPL of a segment selector.Note that the privilege level of the application program can be determined by readingthe RPL field of the segment selector for the application-program’s code segment.This segment selector is stored on the stack as part of the call to the operatingsystem.

The operating system can copy the segment selector from the stack into aregister for use as an operand for the ARPL instruction.4.10.5Checking AlignmentWhen the CPL is 3, alignment of memory references can be checked by setting theAM flag in the CR0 register and the AC flag in the EFLAGS register. Unaligned memoryreferences generate alignment exceptions (#AC). The processor does not generatealignment exceptions when operating at privilege level 0, 1, or 2. See Table 5-7 for adescription of the alignment requirements when alignment checking is enabled.4.11PAGE-LEVEL PROTECTIONPage-level protection can be used alone or applied to segments.

When page-levelprotection is used with the flat memory model, it allows supervisor code and data(the operating system or executive) to be protected from user code and data (application programs). It also allows pages containing code to be write protected. Whenthe segment- and page-level protection are combined, page-level read/write protection allows more protection granularity within segments.With page-level protection (as with segment-level protection) each memory reference is checked to verify that protection checks are satisfied. All checks are madebefore the memory cycle is started, and any violation prevents the cycle fromstarting and results in a page-fault exception being generated.

Because checks areperformed in parallel with address translation, there is no performance penalty.The processor performs two page-level protection checks:••Restriction of addressable domain (supervisor and user modes).Page type (read only or read/write).Violations of either of these checks results in a page-fault exception being generated.See Chapter 5, “Interrupt 14—Page-Fault Exception (#PF),” for an explanation of theVol.

3 4-39PROTECTIONpage-fault exception mechanism. This chapter describes the protection violationswhich lead to page-fault exceptions.4.11.1Page-Protection FlagsProtection information for pages is contained in two flags in a page-directory or pagetable entry (see Figure 3-14): the read/write flag (bit 1) and the user/supervisor flag(bit 2). The protection checks are applied to both first- and second-level page tables(that is, page directories and page tables).4.11.2Restricting Addressable DomainThe page-level protection mechanism allows restricting access to pages based ontwo privilege levels:•Supervisor mode (U/S flag is 0)—(Most privileged) For the operating system orexecutive, other system software (such as device drivers), and protected systemdata (such as page tables).•User mode (U/S flag is 1)—(Least privileged) For application code and data.The segment privilege levels map to the page privilege levels as follows.

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

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

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

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