第 73 / 187 篇

7. 64 位 x86 汇编(x86-64)

说明

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

7. 64-bit x86 Assembly (x86-64)

本章介绍 64 位 Intel 体系结构(x86-64)的指令集架构。回想一下,指令集架构(ISA)定义了机器级程序的指令集合和二进制编码。要运行本章的示例,你需要一台装有 64 位 x86 处理器的机器。「x86」这个术语常被用作 IA-32 体系结构的同义词。这种体系结构的 64 位扩展称为 x86-64(或 x64),在现代计算机中无处不在。IA32 和 x86-64 都属于 x86 体系结构家族。

In this chapter, we cover the Intel Architecture 64-bit (x86-64) instruction set architecture. Recall that an instruction set architecture (or ISA) defines the set of instructions and binary encodings of a machine-level program. To run the examples in this chapter, you will need access to a machine with a 64-bit x86 processor. The term “x86” is often used synonymously with the IA-32 architecture. The 64-bit extension of this architecture is referred to as x86-64 (or x64) and is ubiquitous in modern computers. Both IA32 and x86-64 belong to the x86 architecture family.

要检查你的 Linux 机器上是否装有 64 位 Intel 处理器,运行 uname -m 命令。如果是 x86-64 系统,你应该会看到类似下面的输出:

To check to see if you have a 64-bit Intel processor on your Linux machine, run the uname -m command. If you have an x86-64 system, you should see output like the following:

译注

在 Apple Silicon Mac 上,uname -m 输出的是 arm64,本章的程序无法直接在上面运行。可以用 x86-64 的 Linux 虚拟机或云服务器,或者至少用 gcc -S -O0 -target x86_64-linux-gnu 文件.c 让 Clang 交叉生成 x86-64 汇编来对照阅读(只能看,不能链接运行)。

1
2
$ uname -m
x86_64

由于 x86-64 是较小的 IA32 ISA 的扩展,有些读者可能更想看关于 IA32 的讨论。想进一步了解 IA32,请点击这个链接进入第 8 章。

Since x86-64 is an extension of the smaller IA32 ISA, some readers may prefer a discussion of IA32. To read more about IA32, follow this link to Chapter 8.

原书旁注 · x86 语法的分支(x86 Syntax Branches)

x86 体系结构通常遵循两种不同的语法分支之一。UNIX 机器通常使用 AT&T 语法,因为 UNIX 是在 AT&T 贝尔实验室开发的,对应的汇编器是 GNU 汇编器(GAS)。由于本书的大多数示例使用 GCC,本章介绍的是 AT&T 语法。Windows 机器通常使用 Intel 语法,微软的宏汇编器(MASM)使用的就是这种语法。Netwide 汇编器(NASM)是 Linux 上使用 Intel 语法的汇编器的一个例子。两种语法孰优孰劣的争论,是这个领域的「圣战」之一。不过,熟悉两种语法都是有价值的,因为程序员在不同场合可能会遇到其中任何一种。

x86 architectures typically follow one of two different syntax branches. UNIX machines commonly use the AT&T syntax, given that UNIX was developed at AT&T Bell Labs. The corresponding assembler is GNU Assembler (GAS). Since we use GCC for most examples in this book, we cover AT&T syntax in this chapter. Windows machines commonly use Intel syntax, which is used by Microsoft’s Macro Assembler (MASM). The Netwide Assembler (NASM) is an example of a Linux assembler that uses Intel syntax. The argument regarding the superiority of one syntax over the other is one of the “holy wars” of the discipline. However, there is value in being familiar with both syntaxes, as a programmer may encounter either in various circumstances.

译注

两种语法最显眼的区别是操作数顺序相反:AT&T 语法写作 mov %rax, %rbx(源在前、目的在后),Intel 语法写作 mov rbx, rax(目的在前);AT&T 语法的寄存器名前带 %、立即数前带 $。GDB 中可以用 set disassembly-flavor intel 切换,objdump 可以加 -M intel。