说明
本文是个人学习用的非官方中英对照译文,原文:https://diveintosystems.org/book/C8-IA32/basics.html。
原书采用 CC BY-NC-ND 4.0 许可(禁止演绎),请勿公开传播本译文。
标为「译注」「现代更新」的内容是译者补充,不代表原书作者观点;代码与原文逐字一致,未作改动。
8.1. Diving into Assembly: Basics
为了初步了解汇编,我们修改本章开头的 adder 函数,简化它的行为。修改后的函数(adder2)如下:
For a first look at assembly, we modify the
adderfunction from the beginning of the chapter to simplify its behavior. Here’s the modified function (adder2):
1 | #include <stdio.h> |
要编译这段代码,使用以下命令:
To compile this code, use the following command:
1 | $ gcc -m32 -o modified modified.c |
-m32 选项告诉 GCC 把代码编译成 32 位可执行文件。忘了加这个选项,得到的汇编可能与本章所示的大相径庭;GCC 默认编译成 x86-64 汇编,即 x86 的 64 位变体。不过,几乎所有 64 位体系结构都有一个用于向后兼容的 32 位运行模式。本章介绍 IA32;其他章节介绍 x86-64 和 ARM。尽管年代久远,IA32 对于理解程序如何工作以及如何优化代码仍然非常有用。
The
-m32flag tells GCC to compile the code to a 32-bit executable. Forgetting to include this flag may result in assembly that is wildly different from the examples shown in this chapter; by default, GCC compiles to x86-64 assembly, the 64-bit variant of x86. However, virtually all 64-bit architectures have a 32-bit operating mode for backward compatibility. This chapter covers IA32; other chapters cover x86-64 and ARM. Despite its age, IA32 is still extremely useful for understanding how programs work and how to optimize code.
接下来,输入以下命令查看这段代码对应的汇编:
Next, let’s view the corresponding assembly of this code by typing the following command:
1 | $ objdump -d modified > output |
用 less 查看文件 output 时,输入 /adder2 搜索与 adder2 相关的代码片段。与 adder2 相关的部分应该类似下面这样:
Search for the code snippet associated with
adder2by typing/adder2while examining the fileoutputusingless. The section associated withadder2should look similar to the following:
adder2 函数的汇编输出
Assembly output for the
adder2function
1 | 0804840b <adder2>: |
如果你还不明白这是怎么回事,不必担心。我们会在后面的小节中更详细地介绍汇编。目前,我们先来研究一下这些单独指令的结构。
Don’t worry if you don’t understand what’s going on just yet. We will cover assembly in greater detail in later sections. For now, we will study the structure of these individual instructions.
上例中的每一行都包含一条指令在程序内存中的地址、与这条指令对应的字节,以及指令本身的文本表示。例如,55 是指令 push %ebp 的机器码表示,这条指令位于程序内存中的地址 0x804840b 处。
Each line in the preceding example contains an instruction’s address in program memory, the bytes corresponding to the instruction, and the plaintext representation of the instruction itself. For example,
55is the machine code representation of the instructionpush %ebp, and the instruction occurs at address0x804840bin program memory.
译注
0x08048000 一带是非 PIE 的 32 位 x86 Linux 程序的传统加载地址。与第 7 章的译注一样,较新的 GCC 和发行版默认生成位置无关可执行文件(PIE),你用 objdump 看到的多半是从很小的值开始的相对地址,函数开头也可能多出 endbr32 等指令,不影响理解。
要注意,一行 C 代码常常会被翻译成多条汇编指令。运算 a + 2 用 mov 0x8(%ebp), %eax 和 add $0x2, %eax 两条指令表示。
It is important to note that a single line of C code often translates to multiple instructions in assembly. The operation
a + 2is represented by the two instructionsmov 0x8(%ebp), %eaxandadd $0x2, %eax.
原书警示 · 你的汇编可能看起来不一样!(Your assembly may look different!)
如果你一边读一边跟着编译代码,可能会注意到你得到的一些汇编示例与书中所示的不同。任何编译器输出的确切汇编指令,都取决于编译器的版本和底层的操作系统。本书中的大多数汇编示例是在运行 Ubuntu 或红帽企业版 Linux(RHEL)的系统上生成的。
在接下来的示例中,我们不使用任何优化选项。例如,编译任何示例文件(example.c)都使用命令 gcc -m32 -o example example.c。因此,接下来的示例中会有许多看似多余的指令。记住,编译器并不「聪明」——它只是遵循一系列规则,把人类可读的代码翻译成机器语言。在这个翻译过程中,出现一些冗余并不罕见。优化编译器在优化过程中会去掉许多这样的冗余,我们会在后面的章节中介绍优化。
If you are compiling your code along with us, you may notice that some of your assembly examples look different from what is shown in this book. The precise assembly instructions that are output by any compiler depend on that compiler’s version and the underlying operating system. Most of the assembly examples in this book were generated on systems running Ubuntu or Red Hat Enterprise Linux (RHEL).
In the examples that follow, we do not use any optimization flags. For example, we compile any example file (
example.c) using the commandgcc -m32 -o example example.c. Consequently, there are many seemingly redundant instructions in the examples that follow. Remember that the compiler is not “smart” — it simply follows a series of rules to translate human-readable code into machine language. During this translation process, it is not uncommon for some redundancy to occur. Optimizing compilers remove many of these redundancies during optimization, which is covered in a later chapter.
8.1.1. 寄存器
8.1.1. Registers
回想一下,寄存器是直接位于 CPU 上的、字大小的存储单元。可能会有分别用于数据、指令和地址的寄存器。例如,Intel CPU 共有八个用于存储 32 位数据的寄存器:
Recall that a register is a word-sized storage unit located directly on the CPU. There may be separate registers for data, instructions, and addresses. For example, the Intel CPU has a total of eight registers for storing 32-bit data:
%eax、%ebx、%ecx、%edx、%edi、%esi、%esp 和 %ebp。
%eax,%ebx,%ecx,%edx,%edi,%esi,%esp, and%ebp.
程序可以读写全部八个寄存器。前六个寄存器都存放通用数据,而后两个通常由编译器保留,用来存放地址数据。尽管程序可能会把通用寄存器的内容解释为整数或地址,但寄存器本身并不加以区分。后两个寄存器(%esp 和 %ebp)分别称为栈指针(stack pointer)和帧指针(frame pointer)。编译器把这两个寄存器保留给维护程序栈布局的操作。通常,%esp 指向程序栈的栈顶,而 %ebp 指向当前栈帧的底部。我们会在讨论函数时更详细地介绍栈帧和这两个寄存器。
Programs can read from or write to all eight of these registers. The first six registers all hold general-purpose data, whereas the last two are typically reserved by the compiler to hold address data. While a program may interpret a general-purpose register’s contents as integers or as addresses, the register itself makes no distinction. The last two registers (
%espand%ebp) are known as the stack pointer and the frame pointer, respectively. The compiler reserves these registers for operations that maintain the layout of the program stack. Typically,%esppoints to the top of the program stack, whereas%ebppoints to the base of the current stack frame. We discuss stack frames and these two registers in greater detail in our discussion on functions.
最后一个值得一提的寄存器是 %eip,即指令指针(instruction pointer),有时也称为程序计数器(PC)。它指向 CPU 要执行的下一条指令。与前面提到的八个寄存器不同,程序不能直接写寄存器 %eip。
The last register worth mentioning is
%eipor the instruction pointer, sometimes called the program counter (PC). It points to the next instruction to be executed by the CPU. Unlike the eight registers mentioned previously, programs cannot write directly to register%eip.
8.1.2. 寄存器的进阶记法
8.1.2. Advanced Register Notation
对于前面提到的前六个寄存器,ISA 提供了访问每个寄存器低 16 位的机制。对于其中前四个寄存器,ISA 还另外提供了访问其低 16 位中各个 8 位部分的机制。表 1 列出了这六个寄存器,以及(如果有的话)访问其组成字节的 ISA 机制。
For the first six registers mentioned, the ISA provides a mechanism to access the lower 16 bits of each register. The ISA also provides a separate mechanism to access the 8-bit components of the lower 16 bits of the first four of these registers. Table 1 lists each of the six registers and the ISA mechanisms (if available) to access their component bytes.
表 1. x86 寄存器及访问其低位字节的方式
Table 1. x86 Registers and Mechanisms for Accessing Lower Bytes.
| 32 位寄存器(第 31–0 位) | 低 16 位(第 15–0 位) | 第 15–8 位 | 第 7–0 位 |
|---|---|---|---|
%eax |
%ax |
%ah |
%al |
%ebx |
%bx |
%bh |
%bl |
%ecx |
%cx |
%ch |
%cl |
%edx |
%dx |
%dh |
%dl |
%edi |
%di |
||
%esi |
%si |
32-bit register (bits 31-0) Lower 16 bits (bits 15-0) Bits 15-8 Bits 7-0 %eax%ax%ah%al%ebx%bx%bh%bl%ecx%cx%ch%cl%edx%dx%dh%dl%edi%di%esi%si
要访问上述任一寄存器的低 16 位,就取寄存器名的最后两个字母。例如,用 %ax 访问 %eax 的低 16 位。
The lower 16 bits for any of the aforementioned registers can be accessed by referencing the last two letters in the register’s name. For example, use
%axto access the lower 16 bits of%eax.
要访问前四个寄存器低 16 位中的高字节和低字节,就取寄存器名的最后两个字母,并根据想要哪个字节,把最后一个字母换成 h(表示高)或 l(表示低)。例如,%al 引用寄存器 %ax 的低八位,而 %ah 引用寄存器 %ax 的高八位。编译器常用这些八位寄存器在某些运算中存放单字节的值,比如移位(32 位寄存器移位不能超过 32 位,而数字 32 只需要一个字节就能存下)。一般来说,编译器会使用完成运算所需的最小的组成部分寄存器。
The higher and lower bytes within the lower 16 bits of the first four listed registers can be accessed by taking the last two letters of the register name and replacing the last letter with either an
h(for higher) or anl(for lower) depending on which byte is desired. For example,%alreferences the lower eight bits of register%ax, whereas%ahreferences the higher eight bits of register%ax. These eight bit registers are commonly used by the compiler for storing single-byte values for certain operations, such as bitwise shifts (a 32-bit register cannot be shifted more than 32 places and the number 32 requires only a single byte of storage). In general, the compiler will use the smallest component register needed to complete an operation.
8.1.3. 指令的结构
8.1.3. Instruction Structure
每条指令由一个指明它做什么的操作码(opcode)和一个或多个告诉指令如何去做的操作数(operand)组成。例如,指令 add $0x2, %eax 的操作码是 add,操作数是 $0x2 和 %eax。
Each instruction consists of an operation code (or opcode) that specifies what it does, and one or more operands that tell the instruction how to do it. For example, the instruction
add $0x2, %eaxhas the opcodeaddand the operands$0x2and%eax.
每个操作数对应于某个特定运算的源位置或目标位置。操作数有多种类型:
Each operand corresponds to a source or destination location for a specific operation. There are multiple types of operands:
- 常数(字面量)值前面带有
$符号。例如,在指令add $0x2, %eax中,$0x2是一个字面值,对应于十六进制值 0x2。
- Constant (literal) values are preceded by the
$sign. For example in the instructionadd $0x2, %eax,$0x2is a literal value that corresponds to the hexadecimal value 0x2.
- 寄存器形式指单个寄存器。指令
add $0x2, %eax指定寄存器%eax为目标位置,add运算的结果将存放在那里。
- Register forms refer to individual registers. The instruction
add $0x2, %eaxspecifies register%eaxas the destination location where the result %of theaddoperation will be stored.
- 内存形式对应于主存(RAM)中的某个值,常用于地址查找。内存地址形式可以包含寄存器和常数值的组合。例如,在指令
mov 0x8(%ebp),%eax中,操作数0x8(%ebp)就是内存形式的一个例子。它大致可以翻译为:「把 0x8 加到寄存器%ebp中的值上,然后执行一次内存查找」。如果这听起来像是指针解引用,那是因为它就是!
- Memory forms correspond to some value inside main memory (RAM) and are commonly used for address lookups. Memory address forms can contain a combination of registers and constant values. For example, in the instruction
mov 0x8(%ebp),%eax, the operand0x8(%ebp)is an example of a memory form. It loosely translates to “add 0x8 to the value in register%ebp, and then perform a memory lookup.” If this sounds like a pointer dereference, that’s because it is!
8.1.4. 一个关于操作数的例子
8.1.4. An Example with Operands
详细解释操作数的最好方式是举一个简短的例子。假设内存中包含以下值:
The best way to explain operands in detail is to present a quick example. Suppose that memory contains the following values:
| 地址 | 值 |
|---|---|
| 0x804 | 0xCA |
| 0x808 | 0xFD |
| 0x80c | 0x12 |
| 0x810 | 0x1E |
Address Value 0x804 0xCA 0x808 0xFD 0x80c 0x12 0x810 0x1E
我们再假设下面这些寄存器中存放着所示的值:
Let’s also assume that the following registers contain values:
| 寄存器 | 值 |
|---|---|
| %eax | 0x804 |
| %ebx | 0x10 |
| %ecx | 0x4 |
| %edx | 0x1 |
Register Value %eax 0x804 %ebx 0x10 %ecx 0x4 %edx 0x1
那么,表 2 中的操作数会求值为表中所示的值。表中的每一行把一个操作数与它的形式(例如常数、寄存器、内存)、它的含义以及它的值对应起来。注意,在这里记号 M[x] 表示由地址 x 指定的内存位置上的值。
Then the operands in Table 2 evaluate to the values shown. Each row of the table matches an operand with its form (e.g. constant, register, memory), how it is translated, and its value. Note that the notation M[x] in this context denotes the value at the memory location specified by address x.
表 2. 操作数示例
Table 2. Example operands
| 操作数 | 形式 | 含义 | 值 |
|---|---|---|---|
| %ecx | 寄存器 | %ecx | 0x4 |
| (%eax) | 内存 | M[%eax] 即 M[0x804] | 0xCA |
| $0x808 | 常数 | 0x808 | 0x808 |
| 0x808 | 内存 | M[0x808] | 0xFD |
| 0x8(%eax) | 内存 | M[%eax + 8] 即 M[0x80c] | 0x12 |
| (%eax, %ecx) | 内存 | M[%eax + %ecx] 即 M[0x808] | 0xFD |
| 0x4(%eax, %ecx) | 内存 | M[%eax + %ecx + 4] 即 M[0x80c] | 0x12 |
| 0x800(,%edx,4) | 内存 | M[0x800 + %edx*4] 即 M[0x804] | 0xCA |
| (%eax, %edx, 8) | 内存 | M[%eax + %edx*8] 即 M[0x80c] | 0x12 |
Operand Form Translation Value %ecx Register %ecx 0x4 (%eax) Memory M[%eax] or M[0x804] 0xCA $0x808 Constant 0x808 0x808 0x808 Memory M[0x808] 0xFD 0x8(%eax) Memory M[%eax + 8] or M[0x80c] 0x12 (%eax, %ecx) Memory M[%eax + %ecx] or M[0x808] 0xFD 0x4(%eax, %ecx) Memory M[%eax + %ecx + 4] or M[0x80c] 0x12 0x800(,%edx,4) Memory M[0x800 + %edx*4] or M[0x804] 0xCA (%eax, %edx, 8) Memory M[%eax + %edx*8] or M[0x80c] 0x12
在表 2 中,记号 %ecx 表示寄存器 %ecx 中存放的值。与之不同,M[%eax] 表示应当把 %eax 中的值当作一个地址,并对它解引用(查找该地址处的值)。因此,操作数 (%eax) 对应于 M[0x804],也就是值 0xCA。
In Table 2, the notation
%ecxindicates the value stored in register%ecx. In contrast, M[%eax] indicates that the value inside%eaxshould be treated as an address, and to dereference (look up) the value at that address. Therefore, the operand(%eax)corresponds to M[0x804], which corresponds to the value 0xCA.
在继续之前,有几点重要说明。尽管表 2 列出了许多合法的操作数形式,但并不是所有形式在所有情况下都可以互换使用。
A few important notes before continuing. While Table 2 shows many valid operand forms, not all forms can be used interchangeably in all circumstances.
具体来说:
Specifically:
- 常数形式不能作为目标操作数。
- Constant forms cannot serve as destination operands.
- 在同一条指令中,内存形式不能同时作为源操作数和目标操作数。
- Memory forms cannot serve both as the source and destination operand in a single instruction.
- 在有比例因子的运算中(见表 2 的最后两个操作数),比例因子只能是 1、2、4 或 8 之一。
- In cases of scaling operations (see the last two operands in Table 2), the scaling factor must be one of 1, 2, 4, or 8.
表 2 是供参考的;不过,理解关键的操作数形式会帮助读者更快地读懂汇编语言。
Table 2 is provided as a reference; however, understanding key operand forms will help improve the reader’s speed in parsing assembly language.
8.1.5. 指令后缀
8.1.5. Instruction Suffixes
在接下来的例子中,有几处常见指令和算术指令带有一个后缀,表示在代码层面被操作的数据的大小(与类型相关)。编译器会自动把代码翻译成带有相应后缀的指令。表 3 列出了 x86 指令的常见后缀。
In several cases in upcoming examples, common and arithmetic instructions have a suffix that indicates the size (associated with the type) of the data being operated on at the code level. The compiler automatically translates code to instructions with the appropriate suffix. Table 3 shows the common suffixes for x86 instructions.
表 3. 指令后缀示例
Table 3. Example Instruction Suffixes
| 后缀 | C 类型 | 大小(字节) |
|---|---|---|
| b | char |
1 |
| w | short |
2 |
| l | int、long、unsigned |
4 |
Suffix C Type Size (bytes) b char1 w short2 l int,long,unsigned4
译注
在 32 位 x86 Linux 上,int、long 和指针都是 4 字节,所以它们都用后缀 l(译者用 clang -target i386-linux-gnu 编译 _Static_assert(sizeof(long)==4 && sizeof(void*)==4, "") 确认);而在 64 位 Linux 上,long 和指针是 8 字节,对应第 7 章的后缀 q。
注意,与条件执行有关的指令会根据求值的条件带有不同的后缀。我们会在后面的小节中介绍与条件执行相关的指令。
Note that instructions involved with conditional execution have different suffixes based on the evaluated condition. We cover instructions associated with conditional instructions in a later section.