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

Volume 1 Application Programming (794095), страница 13

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

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

In memory, the REX prefix byte (48) would be stored at the lowestaddress, and the first immediate byte (11) would be stored at the highest instruction address.1109h2208h3307h4406h5505h6604h7703h8802hB801h4800hHigh (most-significant)Low (least-significant)513-186.epsFigure 2-6. Example of 10-Byte Instruction in Memory2.2.2 64-Bit Canonical AddressesLong mode defines 64 bits of virtual address, but implementations of the AMD64 architecture maysupport fewer bits of virtual address. Although implementations might not use all 64 bits of the virtualaddress, they check bits 63 through the most-significant implemented bit to see if those bits are allzeros or all ones.

An address that complies with this property is said to be in canonical address form. Ifa virtual-memory reference is not in canonical form, the implementation causes a general-protectionexception or stack fault.2.2.3 Effective AddressesPrograms provide effective addresses to the hardware prior to segmentation and paging translations.Long-mode effective addresses are a maximum of 64 bits wide, as shown in Figure 2-3 on page 12.Programs running in compatibility mode generate (by default) 32-bit effective addresses, which thehardware zero-extends to 64 bits.

Legacy-mode effective addresses, with no address-size override, are32 or 16 bits wide, as shown in Figure 2-4 on page 13. These sizes can be overridden with an addresssize instruction prefix, as described in “Instruction Prefixes” on page 71.There are five methods for generating effective addresses, depending on the specific instructionencoding:•Absolute Addresses—These addresses are given as displacements (or offsets) from the base addressof a data segment.

They point directly to a memory location in the data segment.Memory Model15AMD64 Technology••24592—Rev. 3.13—July 2007Instruction-Relative Addresses—These addresses are given as displacements (or offsets) from thecurrent instruction pointer (IP), also called the program counter (PC). They are generated bycontrol-transfer instructions. A displacement in the instruction encoding, or one read frommemory, serves as an offset from the address that follows the transfer.

See “RIP-RelativeAddressing” on page 18 for details about RIP-relative addressing in 64-bit mode.ModR/M Addressing—These addresses are calculated using a scale, index, base, and displacement.Instruction encodings contain two bytes—MODR/M and optional SIB (scale, index, base) and avariable length displacement—that specify the variables for the calculation. The base and indexvalues are contained in general-purpose registers specified by the SIB byte.

The scale anddisplacement values are specified directly in the instruction encoding. Figure 2-7 shows thecomponents of a complex-address calculation. The resultant effective address is added to the datasegment base address to form a linear address, as described in “Segmented Virtual Memory” inVolume 2. “Instruction Formats” in Volume 3 gives further details on specifying this form ofaddress. The encoding of instructions specifies how the address is calculated.BaseIndex*DisplacementScale by 1, 2, 4, or 8+Effective Address513-108.epsFigure 2-7.

Complex Address Calculation (Protected Mode)••Stack Addresses—PUSH, POP, CALL, RET, IRET, and INT instructions implicitly use the stackpointer, which contains the address of the procedure stack. See “Stack Operation” on page 19 fordetails about the size of the stack pointer.String Addresses—String instructions generate sequential addresses using the rDI and rSI registers,as described in “Implicit Uses of GPRs” on page 30.In 64-bit mode, with no address-size override, the size of effective-address calculations is 64 bits. Aneffective-address calculation uses 64-bit base and index registers and sign-extends displacements to 64bits. Due to the flat address space in 64-bit mode, virtual addresses are equal to effective addresses.(For an exception to this general rule, see “FS and GS as Base of Address Calculation” on page 17.)Long-Mode Zero-Extension of 16-Bit and 32-Bit Addresses.

In long mode, all 16-bit and 32-bitaddress calculations are zero-extended to form 64-bit addresses. Address calculations are first16Memory Model24592—Rev. 3.13—July 2007AMD64 Technologytruncated to the effective-address size of the current mode (64-bit mode or compatibility mode), asoverridden by any address-size prefix. The result is then zero-extended to the full 64-bit address width.Because of this, 16-bit and 32-bit applications running in compatibility mode can access only the low4GB of the long-mode virtual-address space.

Likewise, a 32-bit address generated in 64-bit mode canaccess only the low 4GB of the long-mode virtual-address space.Displacements and Immediates. In general, the maximum size of address displacements andimmediate operands is 32 bits. They can be 8, 16, or 32 bits in size, depending on the instruction or, fordisplacements, the effective address size. In 64-bit mode, displacements are sign-extended to 64 bitsduring use, but their actual size (for value representation) remains a maximum of 32 bits.

The same istrue for immediates in 64-bit mode, when the operand size is 64 bits. However, support is provided in64-bit mode for some 64-bit displacement and immediate forms of the MOV instruction.FS and GS as Base of Address Calculation. In 64-bit mode, the FS and GS segment-base registers(unlike the DS, ES, and SS segment-base registers) can be used as non-zero data-segment baseregisters for address calculations, as described in “Segmented Virtual Memory” in Volume 2.

64-bitmode assumes all other data-segment registers (DS, ES, and SS) have a base address of 0.2.2.4 Address-Size PrefixThe default address size of an instruction is determined by the default-size (D) bit and long-mode (L)bit in the current code-segment descriptor (for details, see “Segmented Virtual Memory” in Volume 2).Application software can override the default address size in any operating mode by using the 67haddress-size instruction prefix byte. The address-size prefix allows mixing 32-bit and 64-bit addresseson an instruction-by-instruction basis.Table 2-1 on page 18 shows the effects of using the address-size prefix in all operating modes.

In 64bit mode, the default address size is 64 bits. The address size can be overridden to 32 bits. 16-bitaddresses are not supported in 64-bit mode. In compatibility and legacy modes, the address-size prefixworks the same as in the legacy x86 architecture.Memory Model17AMD64 Technology24592—Rev. 3.13—July 2007Table 2-1.Address-Size PrefixesOperating Mode64-Bit ModeDefaultAddressSize (Bits)AddressEffectiveSize PrefixAddress Size(67h)1(Bits)Required?6432Long ModeCompatibility Mode16Legacy Mode(Protected, Virtual-8086, or RealMode)321664no32yes32no16yes32yes16no32no16yes32yes16noNote:1. “No” indicates that the default address size is used.2.2.5 RIP-Relative AddressingRIP-relative addressing—that is, addressing relative to the 64-bit instruction pointer (also calledprogram counter)—is available in 64-bit mode.

The effective address is formed by adding thedisplacement to the 64-bit RIP of the next instruction.In the legacy x86 architecture, addressing relative to the instruction pointer (IP or EIP) is availableonly in control-transfer instructions. In the 64-bit mode, any instruction that uses ModRM addressing(see “ModRM and SIB Bytes” in Volume 3) can use RIP-relative addressing. The feature isparticularly useful for addressing data in position-independent code and for code that addresses globaldata.Programs usually have many references to data, especially global data, that are not register-based. Toload such a program, the loader typically selects a location for the program in memory and then adjuststhe program’s references to global data based on the load location.

RIP-relative addressing of datamakes this adjustment unnecessary.Range of RIP-Relative Addressing. Without RIP-relative addressing, instructions encoded with aModRM byte address memory relative to zero. With RIP-relative addressing, instructions with aModRM byte can address memory relative to the 64-bit RIP using a signed 32-bit displacement. Thisprovides an offset range of ±2 GBytes from the RIP.Effect of Address-Size Prefix on RIP-Relative Addressing. RIP-relative addressing is enabled by64-bit mode, not by a 64-bit address-size. Conversely, use of the address-size prefix does not disable18Memory Model24592—Rev.

3.13—July 2007AMD64 TechnologyRIP-relative addressing. The effect of the address-size prefix is to truncate and zero-extend thecomputed effective address to 32 bits, like any other addressing mode.Encoding. For details on instruction encoding of RIP-relative addressing, see in “RIP-RelativeAddressing” in Volume 3.2.3PointersPointers are variables that contain addresses rather than data. They are used by instructions toreference memory.

Instructions access data using near and far pointers. Stack pointers locate thecurrent stack.2.3.1 Near and Far PointersNear pointers contain only an effective address, which is used as an offset into the current segment. Farpointers contain both an effective address and a segment selector that specifies one of severalsegments. Figure 2-8 illustrates the two types of pointers.Near PointerEffective Address (EA)Far PointerSelectorEffective Address (EA)513-109.epsFigure 2-8. Near and Far PointersIn 64-bit mode, the AMD64 architecture supports only the flat-memory model in which there is onlyone data segment, so the effective address is used as the virtual (linear) address and far pointers are notneeded.

In compatibility mode and legacy protected mode, the AMD64 architecture supports multiplememory segments, so effective addresses can be combined with segment selectors to form far pointers,and the terms logical address (segment selector and effective address) and far pointer are synonyms.Near pointers can also be used in compatibility mode and legacy mode.2.4Stack OperationA stack is a portion of a stack segment in memory that is used to link procedures. Software conventionstypically define stacks using a stack frame, which consists of two registers—a stack-frame basepointer (rBP) and a stack pointer (rSP)—as shown in Figure 2-9 on page 20. These stack pointers canbe either near pointers or far pointers.The stack-segment (SS) register, points to the base address of the current stack segment.

The stackpointers contain offsets from the base address of the current stack segment. All instructions thataddress memory using the rBP or rSP registers cause the processor to access the current stack segment.Memory Model19AMD64 Technology24592—Rev. 3.13—July 2007Stack Frame Before Procedure CallStack-Frame Base Pointer (rBP)and Stack Pointer (rSP)Stack-Segment (SS) Base AddressStack Frame After Procedure CallStack-Frame Base Pointer (rBP)Stack Pointer (rSP)passed dataStack-Segment (SS) Base Address513-110.epsFigure 2-9.

Stack Pointer MechanismIn typical APIs, the stack-frame base pointer and the stack pointer point to the same location before aprocedure call (the top-of-stack of the prior stack frame). After data is pushed onto the stack, the stackframe base pointer remains where it was and the stack pointer advances downward to the addressbelow the pushed data, where it becomes the new top-of-stack.In legacy and compatibility modes, the default stack pointer size is 16 bits (SP) or 32 bits (ESP),depending on the default-size (B) bit in the stack-segment descriptor, and multiple stacks can bemaintained in separate stack segments. In 64-bit mode, stack pointers are always 64 bits wide (RSP).Further application-programming details on the stack mechanism are described in “Control Transfers”on page 76.

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

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

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

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