第 108 / 187 篇

9.4.1. 预备知识

说明

本文是个人学习用的非官方中英对照译文,原文:https://diveintosystems.org/book/C9-ARM64/preliminaries.html。
原书采用 CC BY-NC-ND 4.0 许可(禁止演绎),请勿公开传播本译文。
标为「译注」「现代更新」的内容是译者补充,不代表原书作者观点;代码与原文逐字一致,未作改动。

9.4.1. Preliminaries

条件比较指令

Conditional Comparison Instructions

比较指令执行一次算术运算,目的是引导程序的条件执行。表 1 列出了与条件控制相关的基本指令。

Comparison instructions perform an arithmetic operation for the purpose of guiding the conditional execution of a program. Table 1 lists the basic instructions associated with conditional control.

表 1. 条件控制指令

Table 1. Conditional Control Instructions

指令 含义
cmp O1, O2 比较 O1 与 O2(计算 O1 - O2)
tst O1, O2 计算 O1 & O2
Instruction Translation
cmp O1, O2 Compares O1 with O2 (computes O1 - O2)
tst O1, O2 Computes O1 & O2

cmp 指令比较两个操作数 O1 和 O2 的值,具体来说,就是从 O1 中减去 O2。tst 指令执行按位与。常常会看到这样一条指令:

The cmp instruction compares the value of two operands, O1 and O2. Specifically, it subtracts O2 from O1. The tst instruction performs bitwise AND. It is common to see an instruction like:

1
tst x0, x0

在这个例子中,x0 与自身按位与的结果,只有在 x0 为零时才为零。换句话说,这是检测值是否为零,等价于:

In this example, the bitwise AND of x0 with itself is zero only when x0 contains zero. In other words, this is a test for a zero value and is equivalent to:

1
cmp x0, #0

与迄今介绍的算术指令不同,cmp 和 tst 不修改目标寄存器,而是修改一系列称为条件码标志(condition code flag)的单位值。例如,cmp 会根据 O1 - O2 的结果是正(大于)、负(小于)还是零(等于)来修改条件码标志。回想一下,条件码的值编码了 ALU 中一次运算的相关信息。条件码标志是 ARM 处理器状态(PSTATE)的一部分,PSTATE 取代了 ARMv7-A 系统中的当前程序状态寄存器(CPSR)。

Unlike the arithmetic instructions covered thus far, cmp and tst do not modify a destination register. Instead, both instructions modify a series of single-bit values known as condition code flags. For example, cmp will modify condition code flags based on whether the value O1 - O2 results in a positive (greater), negative (less), or zero (equal) value. Recall that condition code values encode information about an operation in the ALU. The condition code flags are part of the ARM processor state (PSTATE), which replaces the current program status register (CPSR) from ARMv7-A systems.

表 2. 常用的条件码标志

Table 2. Common Condition Code Flags

标志 含义
Z 是否等于零(1:是,0:否)
N 是否为负(1:是,0:否)
V 是否发生了有符号溢出(1:是,0:否)
C 是否发生了算术进位/无符号溢出(1:是,0:否)
Flag Translation
Z Is equal to zero (1: yes, 0: no)
N Is negative (1: yes, 0: no)
V Signed overflow has occurred (1: yes, 0: no)
C Arithmetic carry/unsigned overflow has occurred (1: yes, 0: no)

表 2 描绘了用于条件码运算的常用标志。回到 cmp O1, O2 指令:

Table 2 depicts the common flags used for condition code operations. Revisiting the cmp O1, O2 instruction:

  • 如果 O1 和 O2 相等,Z 标志被置为 1。
  • The Z flag is set to 1 if O1 and O2 are equal.
  • 如果 O1 小于 O2(即 O1 - O2 的结果为负),N 标志被置为 1。
  • The N flag is set to 1 if O1 is less than O2 (i.e. O1 - O2 results in a negative value).
  • 如果运算 O1 - O2 导致溢出,V 标志被置为 1(用于有符号比较)。
  • The V flag is set to 1 if the operation O1 - O2 results in overflow (useful for signed comparisons).
  • 如果运算 O1 - O2 产生算术进位,C 标志被置为 1(用于无符号比较)。
  • The C flag is set to 1 if the operation O1 - O2 results in an arithmetic carry operation (useful for unsigned comparisons).

译注 · ARM 的 C 标志与 x86 相反

做减法(包括 cmp)时,ARM 的 C 标志表示「没有借位」:当 O1 ≥ O2(按无符号比较)时 C = 1,O1 < O2 时 C = 0。这与 x86 恰好相反(x86 的 CF = 1 表示发生了借位)。下面表 4 中无符号「大于或等于」对应的后缀 cs(carry set)就是这个原因。译者在 Apple Silicon Mac 上用内联汇编执行 cmp 后再用 cset ..., cs 读出 C:cmp 5,3 得 1,cmp 4,4 得 1,cmp 3,5 得 0。

尽管深入讨论条件码标志超出了本书的范围,但正是 cmp 和 tst 对这些标志的设置,使我们接下来要介绍的那组指令(分支指令)能够正确运作。

While an in-depth discussion of condition code flags is beyond the scope of this book, the setting of these registers by cmp and tst enables the next set of instructions we cover (the branch instructions) to operate correctly.

分支指令

The Branch Instructions

分支指令让程序的执行能「跳」到代码中的一个新位置。在我们迄今跟踪过的汇编程序中,pc 总是指向程序内存中的下一条指令。分支指令使 pc 能被设置为一条还没见过的新指令(例如 if 语句的情形),或者一条之前执行过的指令(例如循环的情形)。

A branch instruction enables a program’s execution to “jump” to a new position in the code. In the assembly programs we have traced through thus far, pc always points to the next instruction in program memory. The branch instructions enable pc to be set to either a new instruction not yet seen (as in the case of an if statement) or to a previously executed instruction (as in the case of a loop).

直接分支指令

Direct branch instructions

表 3. 常用的分支指令

Table 3. Common Branch Instructions

指令 说明
b addr L pc = addr
br A pc = A
cbz R, addr L 如果 R 等于 0,pc = addr(条件分支)
cbnz R, addr L 如果 R 不等于 0,pc = addr(条件分支)
b.c addr L 如果条件 c 成立,pc = addr(条件分支)
Instruction Description
b addr L pc = addr
br A pc = A
cbz R, addr L If R is equal to 0, pc = addr (conditional branch)
cbnz R, addr L If R is not equal to 0, pc = addr (conditional branch)
b.c addr L If c, pc = addr (conditional branch)

表 3 列出了常用的分支指令;L 指一个符号标签(symbolic label),它在程序的目标文件中充当标识符。所有标签都由一些字母和数字后跟一个冒号组成。标签相对于目标文件的作用域可以是局部的或全局的。函数标签通常是全局的,一般由函数名加冒号组成。例如,main:(或 <main>:)用来标记用户定义的 main 函数。按照惯例,作用域为局部的标签通常以句点开头。在 if 语句或循环中,可能会遇到名为 .L1 这样的局部标签。

Table 3 lists the set of common branch instructions; L refers to a symbolic label, which serves as an identifier in the program’s object file. All labels consist of some letters and digits followed by a colon. Labels can be local or global to an object file’s scope. Function labels tend to be global and usually consist of the function name and a colon. For example, main: (or <main>:) is used to label a user-defined main function. By convention, labels whose scope are local are typically preceded by a period. One may encounter a local label with a name like .L1 in the context of an if statement or loop.

所有标签都有一个对应的地址(即表 3 中的 addr)。当 CPU 执行 b 指令时,它把 pc 寄存器设为 addr。b 指令只能让程序计数器在当前位置前后 128 MB 的范围内改变;编写汇编的程序员也可以用 br 指令指定一个要分支到的具体地址。与 b 指令不同,br 对地址范围没有限制。

All labels have an associated address (addr in Table 3). When the CPU executes a b instruction, it sets the pc register to addr. The b instruction enables the program counter to change within 128 MB of its current location; a programmer writing assembly can also specify a particular address to branch to by using the br instruction. Unlike the b instruction, there are no restrictions on the address range of br.

译注

范围限制来自定长编码:A64 指令只有 32 位,b 指令中留给偏移量的只有 26 位,以 4 字节(一条指令)为单位,正负各 2²⁵ × 4 字节 = 128 MB。下文条件分支的偏移量只有 19 位,所以范围只有 ±1 MB。br 的目标地址放在 64 位寄存器里,因此没有这种限制。

有时,局部标签也显示为相对于函数起始处的偏移量。因此,地址距离 main 起始处 28 字节的指令可能用标签 <main+28> 表示。例如,指令 b 0x7d0 <main+28> 表示分支到地址 0x7d0,与之关联的标签是 <main+28>,意思是它距离 main 函数的起始地址 28 字节。执行这条指令会把 pc 设为 0x7d0。

Sometimes, local labels also are shown as an offset from the start of a function. Therefore, an instruction whose address is 28 bytes away from the start of main may be represented with the label <main+28>. For example, the instruction b 0x7d0 <main+28> indicates a branch to address 0x7d0, which has the associated label <main+28>, meaning that it is 28 bytes away from the starting address of the main function. Executing this instruction sets pc to 0x7d0.

最后三条指令是条件分支指令。换句话说,只有当给定条件求值为真时,程序计数器寄存器才会被设为 addr。cbz 和 cbnz 指令除了地址之外还需要一个寄存器。对于 cbz,如果 R 为零,就走分支,pc 被设为 addr。对于 cbnz,如果 R 不为零,就走分支,pc 被设为 addr。

The last three instructions are conditional branch instructions. In other words, the program counter register is set to addr only if the given condition evaluates to true. The cbz and cbnz instructions require a register in addition to an address. In the case of cbz, if R is zero, the branch is taken and pc is set to addr. In the case of cbnz, if R is nonzero, the branch is taken and pc is set to addr.

条件分支指令中最强大的是 b.c 指令,它让编译器或汇编程序员能挑选一个自定义的后缀,指明走分支的条件。

The most powerful of the conditional branch instructions are the b.c instructions, which enable the compiler or assembly writer to pick a custom suffix that indicates the condition on which a branch is taken.

条件分支指令的后缀

Conditional branch instruction suffixes

表 4 列出了常用的条件分支后缀(c)。与分支一起使用时,每条指令都以字母 b 和一个点开头,表示它是一条分支指令。每条指令的后缀(c)表示分支的条件。分支指令的后缀还决定了把数值比较解释为有符号还是无符号。注意,条件分支指令的范围(1 MB)比 b 指令有限得多。这些后缀也用于条件选择指令(csel),我们会在下一节介绍它。

Table 4 lists the set of common conditional branch suffixes (c). When used in conjunction with a branch, each instruction starts with the letter b and a dot, denoting that it is a branch instruction. The suffix of each instruction (c) indicates the condition for the branch. The branch instruction suffixes also determine whether to interpret numerical comparisons as signed or unsigned. Note that conditional branch instructions have a much more limited range (1 MB) than the b instruction. These suffixes are also used for the conditional select instruction (csel), which is covered in the next section.

表 4. 条件分支指令后缀(括号中为同义后缀)

Table 4. Conditional Branch Instruction Suffixes (synonyms shown in parentheses)

有符号比较 无符号比较 说明
eq eq 相等(==)或为零时分支
ne ne 不相等(!=)时分支
mi mi 为负(minus)时分支
pl pl 非负(>= 0)时分支
gt hi 大于(higher,高于)(>)时分支
ge cs (hs) 大于或等于(>=)时分支
lt lo (cc) 小于(<)时分支
le ls 小于或等于(<=)时分支
Signed Comparison Unsigned Comparison Description
eq eq branch if equal (==) or branch if zero
ne ne branch if not equal (!=)
mi mi branch if minus (negative)
pl pl branch if non-negative (>= 0)
gt hi branch if greater than (higher) (>)
ge cs (hs) branch if greater than or equal (>=)
lt lo (cc) branch if less than (<)
le ls branch if less than or equal (<=)

goto 语句

The goto Statement

在接下来的几个小节中,我们会考察汇编中的条件语句和循环,并把它们逆向还原成 C。把条件语句和循环的汇编代码翻译回 C 时,理解对应的 C 语言 goto 形式会很有帮助。goto 语句是 C 的一种原语,它强制程序的执行切换到代码中的另一行。与 goto 语句对应的汇编指令是 b。

In the following subsections, we look at conditionals and loops in assembly and reverse engineer them back to C. When translating assembly code of conditionals and loops back into C, it is useful to understand their corresponding C language goto forms. The goto statement is a C primitive that forces program execution to switch to another line in the code. The assembly instruction associated with the goto statement is b.

goto 语句由 goto 关键字后跟一个 goto 标签(goto label)组成,goto 标签是一种指明执行应当在哪里继续的程序标签。所以,goto done 表示程序的执行应当分支到标记为 done 的那一行。C 中程序标签的其他例子包括第 2 章介绍过的 switch 语句标签。

The goto statement consists of the goto keyword followed by a goto label, a type of program label that indicates that execution should continue at the corresponding label. So, goto done means that the program execution should branch to the line marked by label done. Other examples of program labels in C include the switch statement labels previously covered in Chapter 2.

下面的代码清单描绘了用普通 C 代码编写的函数 getSmallest(左),以及它在 C 中对应的 goto 形式(右)。getSmallest 函数比较两个整数(x 和 y)的值,并把较小的值赋给变量 smallest。

The following code listings depict a function getSmallest written in regular C code (left) and its associated goto form in C (right). The getSmallest function compares the value of two integers (x and y), and assigns the smaller value to variable smallest.

表 5. 一个 C 函数与其对应的 goto 形式的比较

Table 5. Comparison of a C function and its associated goto form.

普通的 C 版本

Regular C version

1
2
3
4
5
6
7
8
9
10
int getSmallest(int x, int y) {
int smallest;
if ( x > y ) { //if (conditional)
smallest = y; //then statement
}
else {
smallest = x; //else statement
}
return smallest;
}

goto 版本

Goto version

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
int getSmallest(int x, int y) {
int smallest;

if (x <= y ) { //if (!conditional)
goto else_statement;
}
smallest = y; //then statement
goto done;

else_statement:
smallest = x; //else statement

done:
return smallest;
}

这个函数的 goto 形式可能显得有违直觉,我们来讨论一下到底发生了什么。条件检查变量 x 是否小于或等于 y。

The goto form of this function may seem counterintuitive, but let’s discuss what exactly is going on. The conditional checks to see whether variable x is less than or equal to y.

  • 如果 x 小于或等于 y,程序把控制转移到标记为 else_statement 的标签处,那里只有一条语句 smallest = x。由于程序是线性执行的,程序接着执行标签 done 下面的代码,返回 smallest 的值(x)。
  • If x is less than or equal to y, the program transfers control to the label marked by else_statement, which contains the single statement smallest = x. Since the program executes linearly, the program continues on to execute the code under the label done, which returns the value of smallest (x).
  • 如果 x 大于 y,smallest 被设为 y。接着程序执行语句 goto done,把控制转移到 done 标签处,返回 smallest 的值(y)。
  • If x is greater than y, then smallest is set to y. The program then executes the statement goto done, which transfers control to the done label, which returns the value of smallest (y).

虽然在编程的早期 goto 语句很常用,但在现代代码中使用 goto 语句被认为是不好的做法,因为它降低了代码整体的可读性。事实上,计算机科学家艾兹格·迪杰斯特拉(Edsger Dijkstra)写过一篇抨击使用 goto 语句的著名文章,题为《Go To 语句有害论》(Go To Statement Considered Harmful)1。

While goto statements were commonly used in the early days of programming, their use in modern code is considered bad practice, because it reduces the overall readability of code. In fact, computer scientist Edsger Dijkstra wrote a famous paper lambasting the use of goto statements called Go To Statement Considered Harmful1.

一般来说,设计良好的 C 程序不使用 goto 语句,程序员也不被鼓励使用它,以免写出难以阅读、调试和维护的代码。不过,理解 C 的 goto 语句很重要,因为 GCC 在把含有条件语句的 C 代码(包括含有 if 语句和循环的代码)翻译成汇编之前,通常会先把它改写成 goto 形式。

In general, well-designed C programs do not use goto statements and programmers are discouraged from using it to avoid writing code that is difficult to read, debug, and maintain. However, the C goto statement is important to understand, as GCC typically changes C code with conditionals into a goto form prior to translating it to assembly, including code that contains if statements and loops.

接下来的几个小节更详细地介绍 if 语句和循环的汇编表示。

The following subsections cover the assembly representation of if statements and loops in greater detail.

参考文献

References

  1. Edsger Dijkstra. “Go To Statement Considered Harmful”. Communications of the ACM 11(3) pp. 147—​148. 1968.