Применение искинов - шоссе империализма (Стенгазета русификаторов ИТ)

Информация о пользователе

Привет, Гость! Войдите или зарегистрируйтесь.



Команда "вычисли_адрес" (lea)

Сообщений 1 страница 8 из 8

1

Opcode

Instruction

Op/En

64-Bit Mode

Compat/Leg Mode

Description

REX.W + 8D /r

LEA r64,m

RM

Valid

N.E.

Store effective address for m in register r64.

Op/En

Operand 1

Operand 2

Operand 3

Operand 4

RM

ModRM:reg (w)

ModRM:r/m (r)

NA

NA

Иван в своей программе использовал загрузку константы командой mov.
У меня в программе было не так, я использовал lea.
А есть ли разница?

https://www.felixcloutier.com/x86/lea

В таблицах, описывающих инструкции Интел64 есть странная колонка:
Instruction Operand Encoding
Op/En
Значения в этой колонке могут быть:
RM
MR: Memory/Register (Память/Регистр) - обратный формат RM.
MI: Memory/Immediate (Память/Немедленное значение) - инструкция принимает операнд из памяти и немедленное значение.
RI: Register/Immediate (Регистр/Немедленное значение) - инструкция принимает операнд из регистра и немедленное значение.
I: Immediate (Немедленное значение) - инструкция принимает только немедленное значение.

В формате RM инструкция может использовать один из следующих способов адресации:
    Регистр (R): операнд находится в регистре.
    Память (M): операнд находится в памяти, и его адрес определяется регистром или комбинацией регистров.

В официальной документации Intel64, в частности, в документе
"Intel 64 and IA-32 Architectures Software Developer's Manual" (том 2, раздел 3),
есть раздел "Instruction Format" (Формат инструкций), где описывается формат инструкций и кодирование операндов.

3.1 INTERPRETING THE INSTRUCTION REFERENCE PAGES
This section describes the format of information contained in the instruction reference pages in this chapter. It
explains notational conventions and abbreviations used in these sections.
3.1.1 Instruction Format
The following is an example of the format used for each instruction description in this chapter. The heading below
introduces the example. The table below provides an example summary table.

REX.W — Indicates the use of a REX prefix that affects operand size or instruction semantics. The ordering of
the REX prefix and other optional/mandatory instruction prefixes are discussed Chapter 2. Note that REX
prefixes that promote legacy instructions to 64-bit behavior are not listed explicitly in the opcode column.

/r — Indicates that the ModR/M byte of the instruction contains a register operand and an r/m operand.

VEX префикс был введен в архитектуру Intel Sandy Bridge (2011 год) и AMD Bulldozer (2011 год) для поддержки новых SIMD инструкций, таких как AVX (Advanced Vector Extensions) и FMA (Fused Multiply-Add).
VEX (Vector Extension) prefix - это префикс, используемый в инструкциях x86-64 для расширения функциональности SIMD (Single Instruction, Multiple Data) инструкций.
Такое нам пока не нужно и делать мы его пока не будем.

#UD
If source operand is not a memory location.
If the LOCK prefix is used.

#UD пока не будем генерировать, а LOCK prefix использовать (хотя интересно было бы, но после).

Vol. 2A 3-537 (Страница 1108 в моём документе):

The source operand is a memory address (offset part) specified with one of the processors addressing modes;

Мне во всём этом описании непонятно:
1) почему они когда описывали код инструкции ничего не написали про константу?
Об эмуляторе Интел64 в Сказочной Колеснице

# 0x48    0x8d    0xb6    0x2b    0x00    0x00    0x00
        lea distance(%rsi), %rsi

2) где это описано в официальной документации?
3) почему константа такая короткая (всего 4 байта)
4) почему реальный код другой:
Об эмуляторе Интел64 в Сказочной Колеснице

00000000  488D3523000000    lea rsi,[rel 0x2a]

Отредактировано Лис (2024-08-22 18:16:30)

0

2

«непосредственная константа может быть закодирована в виде:
    1-байтовой константы (byte immediate)
    2-байтовой константы (word immediate)
    4-байтовой константы (dword immediate)
    8-байтовой константы (qword immediate)»

3-8 Vol. 2A

3.1.1.4 Operand Encoding Column in the Instruction Summary Table
The “operand encoding” column is abbreviated as Op/En in the Instruction Summary table heading. Instruction
operand encoding information is provided for each assembly instruction syntax using a letter to cross reference to
a row entry in the operand encoding definition table that follows the instruction summary table. The operand
encoding table in each instruction reference page lists each instruction operand (according to each instruction
syntax and operand ordering shown in the instruction column) relative to the ModRM byte, VEX.vvvv field or addi-
tional operand encoding placement.
EVEX encoded instructions employ compressed disp8*N encoding of the displacement bytes, where N is defined in
Table 2-34 and Table 2-35, according to tupletypes. The tupletype for an instruction is listed in the operand
encoding definition table where applicable.
NOTES
• The letters in the Op/En column of an instruction apply ONLY to the encoding definition table
immediately following the instruction summary table.
• In the encoding definition table, the letter ‘r’ within a pair of parenthesis denotes the content of
the operand will be read by the processor. The letter ‘w’ within a pair of parenthesis denotes the
content of the operand will be updated by the processor.

3.1.1.5 64/32-bit Mode Column in the Instruction Summary Table
The “64/32-bit Mode” column indicates whether the opcode sequence is supported in (a) 64-bit mode or (b) the
Compatibility mode and other IA-32 modes that apply in conjunction with the CPUID feature flag associated specific
instruction extensions.
The 64-bit mode support is to the left of the ‘slash’ and has the following notation:
• V — Supported.
• I — Not supported.
• N.E. — Indicates an instruction syntax is not encodable in 64-bit mode (it may represent part of a sequence of
valid instructions in other modes).
• N.P. — Indicates the REX prefix does not affect the legacy instruction in 64-bit mode.
• N.I. — Indicates the opcode is treated as a new instruction in 64-bit mode.
• N.S. — Indicates an instruction syntax that requires an address override prefix in 64-bit mode and is not
supported. Using an address override prefix in 64-bit mode may result in model-specific execution behavior.

«В документации Intel64, байт ModRM описан в разделе "3.1.1.1 ModR/M Byte" (Байт ModR/M) в томе 2 "Instruction Set Reference" (Справочник по набору инструкций).
В этом разделе описано, как байт ModRM используется для кодирования информации о типе операнда и регистре-назначения в инструкциях.»

хм. это 3-2 Vol. 2A (страница 574), и не вижу я там ничего такого.

A.4 OPCODE EXTENSIONS FOR ONE-BYTE AND TWO-BYTE OPCODES
Some 1-byte and 2-byte opcodes use bits 3-5 of the ModR/M byte (the nnn field in Figure A-1) as an extension of
the opcode.

mod

nnn

R/M

---

B-2 Vol. 2D (страница 2566)

B.1.3 Opcode Fields
The primary opcode for an instruction is encoded in one to three bytes of the instruction. Within the primary
opcode, smaller encoding fields may be defined. These fields vary according to the class of operation being
performed.
Almost all instructions that refer to a register and/or memory operand have a register and/or address mode byte
following the opcode. This byte, the ModR/M byte, consists of the mod field (2 bits), the reg field (3 bits; this field
is sometimes an opcode extension), and the R/M field (3 bits). Certain encodings of the ModR/M byte indicate that
a second address mode byte, the SIB byte, must be used.

If the addressing mode specifies a displacement, the displacement value is placed immediately following the
ModR/M byte or SIB byte. Possible sizes are 8, 16, or 32 bits. If the instruction specifies an immediate value, the
immediate value follows any displacement bytes. The immediate, if specified, is always the last field of the instruction.

«Биты 5-3: 100 (регистр-индекс - не используется)»
тут не ясно.

«
"r/m operand" (регистр/память операнд) - это операнд, который может быть либо регистром, либо адресом в памяти.
SIB-байт (Scale-Index-Base) - это байт, который используется для кодирования информации о типе адреса и регистре-индексе.
"Displacement" (смещение) - это значение, которое добавляется к базовому адресу для получения фактического адреса в памяти.

SIB-байт добавляется в следующих случаях:
    Когда операнд является адресом в памяти и требует использования регистра-индекса.
    Когда операнд является адресом в памяти и требует использования масштаба (scale).
Если SIB-байт не требуется, то операнд может быть закодирован только ModRM-байтом.

SIB-байт добавляется после ModRM-байта и содержит информацию о типе адреса, регистре-индексе и масштабе.
»

«Биты 7-6: 01 (модификатор режима адресации - регистр-индекс)»
«Биты 2-0: 101 (тип операнда - адрес в памяти с регистром-индексом)»

Отредактировано Лис (2024-08-22 18:43:51)

0

3

Лис написал(а):

Мне во всём этом описании непонятно:
1) почему они когда описывали код инструкции ничего не написали про константу?
Об эмуляторе Интел64 в Сказочной Колеснице

    # 0x48    0x8d    0xb6    0x2b    0x00    0x00    0x00
            lea distance(%rsi), %rsi

2) где это описано в официальной документации?
3) почему константа такая короткая (всего 4 байта)
4) почему реальный код другой:

Значит величина отступа задается 4 байтами для этого машинного кода, возможно есть и другие машинные коды той же операции.
А вы зачем этим сейчас занимаетесь?

Отредактировано Ivan (2024-08-22 18:23:57)

0

4

Ivan написал(а):

А вы зачем этим сейчас занимаетесь?

документация нужна. Думаю, как её сделать.

0

5

Лис написал(а):

документация нужна. Думаю, как её сделать.

Сначала, примитивно просто - прогнать 1-2 простейших команды, потом больше.
Документацию лучше строить на примерах работы.
Но пока бинарника нет - запустить нечего, будет сложно документацию строить.

Отредактировано Ivan (2024-08-22 18:44:26)

0

6

Лис написал(а):

почему реальный код другой:

А как вы смотрите машинный код, соответствующий определённой инструкции?
Я знаю несколько способов, но вдруг ваш способ более удобный.

0

7

https://www.google.com/search?q=online+assembler

FASM:
https://www.jdoodle.com/execute-fasm-online

GAS:
https://www.onlinegdb.com/online_gcc_assembler

NASM:
https://ideone.com/l/assembler-64bit-nasm

Отредактировано Лис (2024-09-20 08:17:21)

0

8

Благодарю за ответ, но как увидеть машинный код по этим ссылкам я не нашёл...
(Может, уже старый стал :).)

0