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

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

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

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

Unlike the CSregister, the SS register can be loaded explicitly, which permits application programsto set up multiple stacks and switch among them.Vol. 1 3-19BASIC EXECUTION ENVIRONMENTSee Section 3.3, “Memory Organization,” for an overview of how the segment registers are used in real-address mode.The four segment registers CS, DS, SS, and ES are the same as the segment registers found in the Intel 8086 and Intel 286 processors and the FS and GS registerswere introduced into the IA-32 Architecture with the Intel386™ family of processors.3.4.2.1Segment Registers in 64-Bit ModeIn 64-bit mode: CS, DS, ES, SS are treated as if each segment base is 0, regardlessof the value of the associated segment descriptor base.

This creates a flat addressspace for code, data, and stack. FS and GS are exceptions. Both segment registersmay be used as additional base registers in linear address calculations (in theaddressing of local data and certain operating system data structures).Even though segmentation is generally disabled, segment register loads may causethe processor to perform segment access assists. During these activities, enabledprocessors will still perform most of the legacy checks on loaded values (even if thechecks are not applicable in 64-bit mode). Such checks are needed because asegment register loaded in 64-bit mode may be used by an application running incompatibility mode.Limit checks for CS, DS, ES, SS, FS, and GS are disabled in 64-bit mode.3.4.3EFLAGS RegisterThe 32-bit EFLAGS register contains a group of status flags, a control flag, and agroup of system flags.

Figure 3-8 defines the flags within this register. Followinginitialization of the processor (either by asserting the RESET pin or the INIT pin), thestate of the EFLAGS register is 00000002H. Bits 1, 3, 5, 15, and 22 through 31 of thisregister are reserved. Software should not use or depend on the states of any ofthese bits.Some of the flags in the EFLAGS register can be modified directly, using specialpurpose instructions (described in the following sections). There are no instructionsthat allow the whole register to be examined or modified directly.The following instructions can be used to move groups of flags to and from the procedure stack or the EAX register: LAHF, SAHF, PUSHF, PUSHFD, POPF, and POPFD.

Afterthe contents of the EFLAGS register have been transferred to the procedure stack orEAX register, the flags can be examined and modified using the processor’s bitmanipulation instructions (BT, BTS, BTR, and BTC).When suspending a task (using the processor’s multitasking facilities), the processorautomatically saves the state of the EFLAGS register in the task state segment (TSS)for the task being suspended.

When binding itself to a new task, the processor loadsthe EFLAGS register with data from the new task’s TSS.When a call is made to an interrupt or exception handler procedure, the processorautomatically saves the state of the EFLAGS registers on the procedure stack. When3-20 Vol. 1BASIC EXECUTION ENVIRONMENTan interrupt or exception is handled with a task switch, the state of the EFLAGSregister is saved in the TSS for the task being suspended.31 30 29 28 27 26 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0V VI I I A V R 0 N0 0 0 0 0 0 0 0 0 0TC M FDP FXXXXXXXXSCXXSSSSSIOPLO D I T S ZPCAF F F F F F 0 F 0 F 1 FID Flag (ID)Virtual Interrupt Pending (VIP)Virtual Interrupt Flag (VIF)Alignment Check (AC)Virtual-8086 Mode (VM)Resume Flag (RF)Nested Task (NT)I/O Privilege Level (IOPL)Overflow Flag (OF)Direction Flag (DF)Interrupt Enable Flag (IF)Trap Flag (TF)Sign Flag (SF)Zero Flag (ZF)Auxiliary Carry Flag (AF)Parity Flag (PF)Carry Flag (CF)S Indicates a Status FlagC Indicates a Control FlagX Indicates a System FlagReserved bit positions.

DO NOT USE.Always set to values previously read.Figure 3-8. EFLAGS RegisterAs the IA-32 Architecture has evolved, flags have been added to the EFLAGS register,but the function and placement of existing flags have remained the same from onefamily of the IA-32 processors to the next. As a result, code that accesses or modifiesthese flags for one family of IA-32 processors works as expected when run on laterfamilies of processors.3.4.3.1Status FlagsThe status flags (bits 0, 2, 4, 6, 7, and 11) of the EFLAGS register indicate the resultsof arithmetic instructions, such as the ADD, SUB, MUL, and DIV instructions.

Thestatus flag functions are:CF (bit 0)Carry flag — Set if an arithmetic operation generates a carry ora borrow out of the most-significant bit of the result; clearedVol. 1 3-21BASIC EXECUTION ENVIRONMENTotherwise. This flag indicates an overflow condition forunsigned-integer arithmetic. It is also used in multiple-precisionarithmetic.PF (bit 2)Parity flag — Set if the least-significant byte of the resultcontains an even number of 1 bits; cleared otherwise.AF (bit 4)Adjust flag — Set if an arithmetic operation generates a carryor a borrow out of bit 3 of the result; cleared otherwise.

This flagis used in binary-coded decimal (BCD) arithmetic.ZF (bit 6)Zero flag — Set if the result is zero; cleared otherwise.SF (bit 7)Sign flag — Set equal to the most-significant bit of the result,which is the sign bit of a signed integer. (0 indicates a positivevalue and 1 indicates a negative value.)OF (bit 11)Overflow flag — Set if the integer result is too large a positivenumber or too small a negative number (excluding the sign-bit)to fit in the destination operand; cleared otherwise. This flagindicates an overflow condition for signed-integer (two’scomplement) arithmetic.Of these status flags, only the CF flag can be modified directly, using the STC, CLC,and CMC instructions.

Also the bit instructions (BT, BTS, BTR, and BTC) copy a specified bit into the CF flag.The status flags allow a single arithmetic operation to produce results for threedifferent data types: unsigned integers, signed integers, and BCD integers. If theresult of an arithmetic operation is treated as an unsigned integer, the CF flag indicates an out-of-range condition (carry or a borrow); if treated as a signed integer(two’s complement number), the OF flag indicates a carry or borrow; and if treatedas a BCD digit, the AF flag indicates a carry or borrow.

The SF flag indicates the signof a signed integer. The ZF flag indicates either a signed- or an unsigned-integerzero.When performing multiple-precision arithmetic on integers, the CF flag is used inconjunction with the add with carry (ADC) and subtract with borrow (SBB) instructions to propagate a carry or borrow from one computation to the next.The condition instructions Jcc (jump on condition code cc), SETcc (byte set on condition code cc), LOOPcc, and CMOVcc (conditional move) use one or more of the statusflags as condition codes and test them for branch, set-byte, or end-loop conditions.3.4.3.2DF FlagThe direction flag (DF, located in bit 10 of the EFLAGS register) controls stringinstructions (MOVS, CMPS, SCAS, LODS, and STOS).

Setting the DF flag causes thestring instructions to auto-decrement (to process strings from high addresses to lowaddresses). Clearing the DF flag causes the string instructions to auto-increment(process strings from low addresses to high addresses).The STD and CLD instructions set and clear the DF flag, respectively.3-22 Vol. 1BASIC EXECUTION ENVIRONMENT3.4.3.3System Flags and IOPL FieldThe system flags and IOPL field in the EFLAGS register control operating-system orexecutive operations.

They should not be modified by application programs.The functions of the system flags are as follows:TF (bit 8)Trap flag — Set to enable single-step mode for debugging;clear to disable single-step mode.IF (bit 9)Interrupt enable flag — Controls the response of theprocessor to maskable interrupt requests. Set to respond tomaskable interrupts; cleared to inhibit maskable interrupts.IOPL (bits 12 and 13)I/O privilege level field — Indicates the I/O privilege level ofthe currently running program or task. The current privilegelevel (CPL) of the currently running program or task must beless than or equal to the I/O privilege level to access the I/Oaddress space.

This field can only be modified by the POPF andIRET instructions when operating at a CPL of 0.NT (bit 14)Nested task flag — Controls the chaining of interrupted andcalled tasks. Set when the current task is linked to the previously executed task; cleared when the current task is not linkedto another task.RF (bit 16)Resume flag — Controls the processor’s response to debugexceptions.VM (bit 17)Virtual-8086 mode flag — Set to enable virtual-8086 mode;clear to return to protected mode without virtual-8086 modesemantics.AC (bit 18)Alignment check flag — Set this flag and the AM bit in the CR0register to enable alignment checking of memory references;clear the AC flag and/or the AM bit to disable alignmentchecking.VIF (bit 19)Virtual interrupt flag — Virtual image of the IF flag. Used inconjunction with the VIP flag.

(To use this flag and the VIP flagthe virtual mode extensions are enabled by setting the VME flagin control register CR4.)VIP (bit 20)Virtual interrupt pending flag — Set to indicate that an interrupt is pending; clear when no interrupt is pending.

(Softwaresets and clears this flag; the processor only reads it.) Used inconjunction with the VIF flag.ID (bit 21)Identification flag — The ability of a program to set or clearthis flag indicates support for the CPUID instruction.For a detailed description of these flags: see Chapter 3, “Protected-Mode MemoryManagement,” in the Intel® 64 and IA-32 Architectures Software Developer’sManual, Volume 3A.Vol.

1 3-23BASIC EXECUTION ENVIRONMENT3.4.3.4RFLAGS Register in 64-Bit ModeIn 64-bit mode, EFLAGS is extended to 64 bits and called RFLAGS. The upper 32 bitsof RFLAGS register is reserved. The lower 32 bits of RFLAGS is the same as EFLAGS.3.5INSTRUCTION POINTERThe instruction pointer (EIP) register contains the offset in the current code segmentfor the next instruction to be executed. It is advanced from one instruction boundaryto the next in straight-line code or it is moved ahead or backwards by a number ofinstructions when executing JMP, Jcc, CALL, RET, and IRET instructions.The EIP register cannot be accessed directly by software; it is controlled implicitly bycontrol-transfer instructions (such as JMP, Jcc, CALL, and RET), interrupts, andexceptions.

The only way to read the EIP register is to execute a CALL instruction andthen read the value of the return instruction pointer from the procedure stack. TheEIP register can be loaded indirectly by modifying the value of a return instructionpointer on the procedure stack and executing a return instruction (RET or IRET). SeeSection 6.2.4.2, “Return Instruction Pointer.”All IA-32 processors prefetch instructions. Because of instruction prefetching, aninstruction address read from the bus during an instruction load does not match thevalue in the EIP register.

Even though different processor generations use differentprefetching mechanisms, the function of the EIP register to direct program flowremains fully compatible with all software written to run on IA-32 processors.3.5.1Instruction Pointer in 64-Bit ModeIn 64-bit mode, the RIP register becomes the instruction pointer. This register holdsthe 64-bit offset of the next instruction to be executed. 64-bit mode also supports atechnique called RIP-relative addressing. Using this technique, the effective addressis determined by adding a displacement to the RIP of the next instruction.3.6OPERAND-SIZE AND ADDRESS-SIZE ATTRIBUTESWhen the processor is executing in protected mode, every code segment has adefault operand-size attribute and address-size attribute.

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

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

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

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