第 72 / 187 篇

6. 在 C 之下:潜入汇编

说明

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

6. Under the C: Diving into Assembly

在 C 之下,在 C 之下

Under the C, under the C

难道你不知道这样更好

Don’t you know it’s better

跟寄存器

Dealing with registers

和汇编打交道?

And assembly?

译注

这几句套用了迪士尼动画《小美人鱼》中螃蟹 Sebastian 演唱的《Under the Sea》(在海底)的歌词,把 sea 换成了同音的 C。下一行的「—— Sebastian(大概吧)」就是在调侃这一点。

—— Sebastian(大概吧)

-Sebastian, probably

在计算机发展的早期、编译器发明之前,许多程序员用汇编语言(assembly language)编写代码,它直接规定了计算机在执行过程中遵循的指令集合。汇编语言是程序员在不直接写 1 和 0 的前提下,最接近机器层面的编程方式,它是机器码(machine code)的一种可读形式。要写出高效的汇编代码,程序员必须深入理解底层机器体系结构的运作方式。

Prior to the invention of the compiler in the early days of computing, many programmers coded in assembly language, which directly specifies the set of instructions that a computer follows during execution. Assembly language is the closest a programmer gets to coding at the machine level without writing code directly in 1s and 0s, and is a readable form of machine code. To write efficient assembly code, programmers must intimately understand the operation of the underlying machine architecture.

编译器的发明从根本上改变了程序员编写代码的方式。编译器(compiler)把人类可读的编程语言(通常用英文单词写成)翻译成计算机能理解的语言(即机器码)。编译器依据编程语言的规则、操作系统的规范以及机器的指令集,把人类可读的代码翻译成机器码,并在这个过程中提供一定的错误检测和类型检查。大多数现代编译器生成的汇编代码,与过去手写的汇编代码一样高效。

The invention of the compiler fundamentally changed the way programmers write code. A compiler translates a human-readable programming language (usually written using English words) into a language that a computer understands (i.e., machine code). Compilers translate the human-readable code into machine code using the rules of the programming language, the specification of the operating system, and the instruction set of the machine, and provide some error detection and type checking in the process. Most modern compilers produce assembly code that is as efficient as the handwritten assembly code of yesteryear.

学习汇编的好处

The Benefits of Learning Assembly

编译器有这么多好处,学习汇编有什么用可能就不那么显而易见了。然而,学习和理解汇编代码有几个很有说服力的理由。下面举几个例子。

Given all the benefits of compilers, it may not be obvious why learning assembly is useful. However, there are several compelling reasons to learn and understand assembly code. Here are a few examples.

1. 更高层的抽象隐藏了有价值的程序细节

1. Higher-Level Abstraction Hides Valuable Program Details

高级编程语言提供的抽象对降低编程的复杂度大有裨益。但与此同时,这种简化让程序员很容易在没有完全理解其选择在机器层面产生何种影响的情况下做出设计决策。缺乏汇编知识,常常使程序员无法了解程序如何运行的宝贵信息,也限制了他们理解自己的代码实际在做什么的能力。

The abstraction provided by high-level programming languages is a boon for reducing the complexity of programming. At the same time, this simplification makes it easy for programmers to make design decisions without fully understanding the ramifications of their choices at the machine level. Lacking knowledge of assembly often prevents a programmer from understanding valuable information on how a program runs, and limits their ability to understand what their code is actually doing.

举个例子,看看下面这个程序:

As an example, take a look at the following program:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <stdio.h>

int adder() {
int a;
return a + 2;
}

int assign() {
int y = 40;
return y;
}

int main(void) {
int x;
assign();
x = adder();
printf("x is: %d\n", x);
return 0;
}

这个程序的输出是什么?乍一看,assign 函数似乎没有任何作用,因为 main 中没有任何变量保存它的返回值。adder 函数返回 a + 2 的值,尽管变量 a 没有初始化(不过在某些机器上编译器会把 a 初始化为 0)。打印 x 应该得到一个不确定的值。然而,在大多数 64 位机器上编译并运行它,得到的结果始终是 42:

What is the program’s output? At first glance, the assign function appears to have no effect, as its return value is not stored by any variable in main. The adder function returns the value of a + 2, although the variable a is uninitialized (though on some machines the compiler will initialize a to 0). Printing out x should result in an undefined value. However, compiling and running it on most 64-bit machines consistently produces an answer of 42:

译注

读取未初始化的局部变量是未定义行为,42 只是在不开优化时、两个函数的栈帧恰好重叠在同一块内存上的结果。译者在 Apple Silicon Mac 上试过:默认(-O0)编译输出 x is: 42,加上 -O2 优化后输出的就是一个毫无规律的值。所以这个例子是用来理解栈帧的,千万别在真实代码里依赖这种行为。

1
2
3
$ gcc -o example example.c
$ ./example
x is: 42

乍一看,这个程序的输出似乎毫无道理,因为 adder 和 assign 函数看起来毫不相干。理解栈帧以及函数在底层如何执行,会帮助你明白答案为什么是 42。我们会在接下来的几章中再次讨论这个例子。

The output of this program seems nonsensical at first glance, as the adder and assign functions appear to be disconnected. Understanding stack frames and how functions execute under the hood will help you understand why the answer is 42. We will revisit this example in the upcoming chapters.

2. 有些计算系统的资源太有限,无法使用编译器

2. Some Computing Systems Are Too Resource-Constrained for Compilers

最常见的「计算机」,是那些我们不容易认出是计算机的设备。这些设备无处不在,从汽车、咖啡机到洗衣机和智能手表。传感器、微控制器和其他嵌入式处理器在我们的生活中扮演着越来越重要的角色,它们都需要软件才能运转。然而,这类设备中的处理器往往太小,无法执行用高级编程语言编写并编译出的代码。在许多情况下,这些设备需要独立的汇编程序,不依赖常见编程语言所需的运行时库。

The most common types of “computer” are those we cannot readily identify as computers. These devices exist everywhere from cars and coffee makers to washing machines and smart watches. Sensors, microcontrollers, and other embedded processors play an increasingly dominant role in our lives, and all require software to operate. However, the processors contained in such devices are often so small that they cannot execute the compiled code written by higher-level programming languages. In many cases, these devices require standalone assembly programs that are not dependent on the runtime libraries required by common programming languages.

3. 漏洞分析

3. Vulnerability Analysis

有一部分安全专业人员每天都在设法找出各类计算机系统中的漏洞。许多攻击程序的途径都与程序存储其运行时信息的方式有关。学习汇编能让安全专业人员理解漏洞是如何产生的,以及它们可能被如何利用。

A subset of security professionals spend their days trying to identify vulnerabilities in various types of computer systems. Many avenues for attacking a program involve the way the program stores its runtime information. Learning assembly enables security professionals to understand how vulnerabilities arise and how they can be exploited.

另一些安全专业人员则花时间对恶意软件中的恶意代码进行「逆向工程」。掌握汇编的实用知识,对这些软件工程师迅速开发出保护系统免受攻击的对策至关重要。最后,不了解自己写的代码如何被翻译成汇编的开发者,可能会在不知不觉中写出有漏洞的代码。

Other security professionals spend time “reverse engineering” malicious code in malware and other malicious software. A working knowledge of assembly is essential to enable these software engineers to quickly develop countermeasures to protect systems against attack. Lastly, developers who lack an understanding of how the code they write translates to assembly may end up unwittingly writing vulnerable code.

4. 系统级软件中的关键代码序列

4. Critical Code Sequences in System-Level Software

最后,计算机系统中有些部件无法被编译器充分优化,需要手写汇编。在某些系统层面,对性能至关重要、需要针对具体机器进行细致优化的地方,存在手写的汇编代码。例如,所有计算机的启动序列都是用汇编代码编写的。操作系统中用于线程或进程上下文切换的部分常常包含手写的汇编。对于这些短小而对性能至关重要的代码序列,人往往能写出比编译器优化得更好的汇编代码。

Lastly, there are some components of a computer system that just cannot be optimized sufficiently by compilers and require handwritten assembly. Some system levels have handwritten assembly code in areas where detailed machine-specific optimizations are critical for performance. For example, the boot sequence on all computers is written in assembly code. Operating systems often contain handwritten assembly for thread or process context-switching. Humans are often able to produce better-optimized assembly code than compilers for these short and performance-critical sequences.

接下来几章你将学到什么

What You Will Learn in the Coming Chapters

接下来的三章介绍三种不同风格的汇编。第 7 章和第 8 章介绍 x86_64 及其早期形式 IA32。第 9 章介绍 ARMv8-A 汇编,它是大多数现代 ARM 设备采用的 ISA,包括树莓派这样的单板计算机。第 10 章给出学习汇编的小结和一些关键要点。

The next three chapters cover three different flavors of assembly. Chapter 7 and Chapter 8 cover x86_64 and its earlier form, IA32. Chapter 9 covers ARMv8-A assembly, which is the ISA found on most modern ARM devices, including single-board computers like the Raspberry Pi. Chapter 10 contains a summary and some key takeaways for learning assembly.

译注 · 用 Mac 学汇编的建议

Apple Silicon Mac 的 CPU 是 ARM64,第 9 章(ARMv8-A)的内容最贴近你手头的机器(不过 macOS 的汇编语法和调用约定在细节上与 Linux 略有不同);第 7、8 章的 x86 汇编则需要 x86 Linux 环境才能运行,或者至少用 gcc -S -target x86_64-linux-gnu 交叉生成汇编来对照阅读。

每种汇编风格实现的是不同的指令集架构(ISA)。回想一下,ISA 定义了指令集合及其二进制编码、CPU 寄存器集合,以及执行指令对 CPU 和存储器状态的影响。

Each of these different flavors of assembly implement different instruction set architectures (ISAs). Recall that an ISA defines the set of instructions and their binary encoding, the set of CPU registers, and the effects of executing instructions on the state of the CPU and memory.

在接下来的三章中,你会看到所有 ISA 之间的总体相似之处,包括都把 CPU 寄存器用作许多指令的操作数,以及每种 ISA 都提供类似类型的指令:

In the following three chapters, you will see general similarities across all the ISAs, including that CPU registers are used as operands of many instructions, and that each ISA provides similar types of instructions:

  1. 执行算术和逻辑运算(如加法或按位与)的指令
  1. instructions for computing arithmetic and logic operations, such as addition or bitwise AND
  1. 控制流指令,用于实现分支,如 if-else、循环以及函数调用和返回
  1. instructions for control flow that are used to implement branching such as if-else, loops, and function call and return
  1. 数据移动指令,用于在 CPU 寄存器和存储器之间加载和存储值
  1. instructions for data movement that load and store values between CPU registers and memory
  1. 向栈中压入和从栈中弹出值的指令。这些指令用来实现执行调用栈:函数调用时,一个新的栈帧(存放正在运行的函数的局部变量和参数)被加到栈顶;函数返回时,一个栈帧从栈顶移除。
  1. instructions for pushing and popping values from the stack. These instructions are used to implement the execution call stack, where a new frame of stack memory (that stores a running function’s local variables and parameters) is added to the top of the stack on a function call, and a frame is removed from the top of the stack on a function return.

C 编译器把 C 源代码翻译成某种特定 ISA 的指令集。编译器把 C 语句(包括循环、if-else、函数调用和变量访问)翻译成由该 ISA 定义、并由设计来执行该 ISA 指令的 CPU 所实现的一组特定指令。例如,编译器把 C 翻译成 x86 指令,在 Intel x86 处理器上执行;或者把 C 翻译成 ARM 指令,在 ARM 处理器上执行。

A C compiler translates C source code to a specific ISA instruction set. The compiler translates C statements, including loops, if-else, function calls, and variable access, to a specific set of instructions that are defined by the ISA and implemented by a CPU that is designed to execute instructions from the specific ISA. For example, a compiler translates C to x86 instructions for execution on an Intel x86 processor, or translates C to ARM instructions for execution on an ARM processor.

现代更新(截至 2026-11)· 在浏览器里看 C 被编译成什么汇编

读接下来几章时,可以配合开源网站 Compiler Explorer(https://godbolt.org/)做练习。它在 GitHub 上的项目说明是「在浏览器里交互式地运行编译器,并与生成的汇编交互」(Run compilers interactively from your web browser and interact with the assembly)。
在网页里输入一段 C 代码,旁边就会显示编译器为它生成的汇编。2026 年 11 月抓取时,页面默认的编译器是 x86-64 gcc 16.2。用户可以换用别的编译器、填写编译选项,也可以设置成源码一改动就自动重新编译,还能生成 godbolt.org/z/… 形式的链接,把代码和输出分享给别人。
本书的 C 示例可以直接贴进去,把生成的汇编和书中的清单逐行对照。要注意,编译器版本和优化选项不同,生成的汇编也会不同。
来源:Compiler Explorer;GitHub:compiler-explorer/compiler-explorer

在阅读本书汇编部分的各章时,你可能会注意到一些关键术语被重新定义了一遍,一些插图也被重复使用。为了更好地帮助其他计算机科学教师,我们把每一章都设计成可以在特定的学院和大学中独立使用。虽然每章的大部分内容都是独有的,但我们希望各章之间的共同之处,能帮助读者加深对不同汇编风格之间相似性的印象。

As you read the chapters in the assembly part of the book, you may notice that some key terms are defined again and that some figures are reproduced. To best aid other CS educators, we designed each chapter to be used independently at particular colleges and universities. While most of the material in each chapter is unique, we hope the commonalities between the chapters help reinforce the similarities between the different flavors of assembly in the mind of readers.

准备好学习汇编了吗?让我们直接潜下去!点击下面的链接访问你感兴趣的章节:

Ready to learn assembly? Let’s dive right in! Follow the links below to visit particular chapters of interest: