第 85 / 187 篇

7.9. 汇编中的结构体

说明

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

7.9. structs in Assembly

结构体是在 C 中创建数据类型集合的另一种方式。与数组不同,结构体可以把不同的数据类型组合在一起。C 像存放一维数组那样存放 struct,其数据元素(字段)连续存放。

A struct is another way to create a collection of data types in C. Unlike arrays, structs enable different data types to be grouped together. C stores a struct like a single-dimension array, where the data elements (fields) are stored contiguously.

我们再来看第 1 章中的 struct studentT:

Let’s revisit struct studentT from Chapter 1:

1
2
3
4
5
6
7
8
struct studentT {
char name[64];
int age;
int grad_yr;
float gpa;
};

struct studentT student;

图 1 展示了 student 在内存中的布局。每个 xi 表示某个字段的地址。

Figure 1 shows how student is laid out in memory. Each xi denotes the address of a particular field.

structArray

图 1. struct studentT 的内存布局

Figure 1. The memory layout of a struct studentT

各字段按照声明的顺序在内存中一个挨一个地连续存放。在图 1 中,age 字段被分配在紧跟 name 字段之后的内存位置(字节偏移 x64),后面依次是 grad_yr(字节偏移 x68)和 gpa(字节偏移 x72)字段。这种组织方式使访问字段既节省内存又高效。

The fields are stored contiguously next to one another in memory in the order in which they are declared. In Figure 1, the age field is allocated at the memory location directly after the name field (at byte offset x64) and is followed by the grad_yr (byte offset x68) and gpa (byte offset x72) fields. This organization enables memory-efficient access to the fields.

为了理解编译器如何生成处理 struct 的汇编代码,考虑函数 initStudent:

To understand how the compiler generates assembly code to work with a struct, consider the function initStudent:

1
2
3
4
5
6
void initStudent(struct studentT *s, char *nm, int ag, int gr, float g) {
strncpy(s->name, nm, 64);
s->grad_yr = gr;
s->age = ag;
s->gpa = g;
}

initStudent 函数以一个 struct studentT 的基地址作为第一个参数,以各字段想要设置的值作为其余参数。下面的清单给出了这个函数的汇编:

The initStudent function uses the base address of a struct studentT as its first parameter, and the desired values for each field as its remaining parameters. The following listing depicts this function in assembly:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
Dump of assembler code for function initStudent:
0x4006aa <+0>: push %rbp #save rbp
0x4006ab <+1>: mov %rsp,%rbp #update rbp (new stack frame)
0x4006ae <+4>: sub $0x20,%rsp #add 32 bytes to stack frame
0x4006b2 <+8>: mov %rdi,-0x8(%rbp) #copy 1st param to %rbp-0x8 (s)
0x4006b6 <+12>: mov %rsi,-0x10(%rbp) #copy 2nd param to %rpb-0x10 (nm)
0x4006ba <+16>: mov %edx,-0x14(%rbp) #copy 3rd param to %rbp-0x14 (ag)
0x4006bd <+19>: mov %ecx,-0x18(%rbp) #copy 4th param to %rbp-0x18 (gr)
0x4006c0 <+22>: movss %xmm0,-0x1c(%rbp) #copy 5th param to %rbp-0x1c (g)
0x4006c5 <+27>: mov -0x8(%rbp),%rax #copy s to %rax
0x4006c9 <+31>: mov -0x10(%rbp),%rcx #copy nm to %rcx
0x4006cd <+35>: mov $0x40,%edx #copy 0x40 (or 64) to %edx
0x4006d2 <+40>: mov %rcx,%rsi #copy nm to %rsi
0x4006d5 <+43>: mov %rax,%rdi #copy s to %rdi
0x4006d8 <+46>: callq 0x400460 <strncpy@plt> #call strcnpy(s->name, nm, 64)
0x4006dd <+51>: mov -0x8(%rbp),%rax #copy s to %rax
0x4006e1 <+55>: mov -0x18(%rbp),%edx #copy gr to %edx
0x4006e4 <+58>: mov %edx,0x44(%rax) #copy gr to %rax+0x44 (s->grad_yr)
0x4006e7 <+61>: mov -0x8(%rbp),%rax #copy s to %rax
0x4006eb <+65>: mov -0x14(%rbp),%edx #copy ag to %edx
0x4006ee <+68>: mov %edx,0x40(%rax) #copy ag to %rax+0x40 (s->age)
0x4006f1 <+71>: mov -0x8(%rbp),%rax #copy s to %rax
0x4006f5 <+75>: movss -0x1c(%rbp),%xmm0 #copy g to %xmm0
0x4006fa <+80>: movss %xmm0,0x48(%rax) #copy g to %rax+0x48
0x400700 <+86>: leaveq #prepare stack to exit function
0x400701 <+87>: retq #return (void func, %rax ignored)

留意每个字段的字节偏移,是理解这段代码的关键。下面是几点需要记住的事情。

Being mindful of the byte offsets of each field is key to understanding this code. Here are a few things to keep in mind.

  • strncpy 调用以 s 的 name 字段的基地址、数组 nm 的地址和一个长度说明作为它的三个实参。回想一下,由于 name 是 struct studentT 中的第一个字段,s 的地址与 s→name 的地址是同一个。
  • The strncpy call takes the base address of the name field of s, the address of array nm, and a length specifier as its three arguments. Recall that because name is the first field in the struct studentT, the address of s is synonymous with the address of s→name.

译注

原书网页把 -> 自动排版成了箭头「→」,代码中要写作 s->name(第 2 章也提到过这个问题)。

1
2
3
4
5
6
7
8
9
10
11
0x4006b2 <+8>:  mov   %rdi,-0x8(%rbp)        #copy 1st param to %rbp-0x8 (s)
0x4006b6 <+12>: mov %rsi,-0x10(%rbp) #copy 2nd param to %rpb-0x10 (nm)
0x4006ba <+16>: mov %edx,-0x14(%rbp) #copy 3rd param to %rbp-0x14 (ag)
0x4006bd <+19>: mov %ecx,-0x18(%rbp) #copy 4th param to %rbp-0x18 (gr)
0x4006c0 <+22>: movss %xmm0,-0x1c(%rbp) #copy 5th param to %rbp-0x1c (g)
0x4006c5 <+27>: mov -0x8(%rbp),%rax #copy s to %rax
0x4006c9 <+31>: mov -0x10(%rbp),%rcx #copy nm to %rcx
0x4006cd <+35>: mov $0x40,%edx #copy 0x40 (or 64) to %edx
0x4006d2 <+40>: mov %rcx,%rsi #copy nm to %rsi
0x4006d5 <+43>: mov %rax,%rdi #copy s to %rdi
0x4006d8 <+46>: callq 0x400460 <strncpy@plt> #call strcnpy(s->name, nm, 64)
  • 这段代码包含了之前没有讨论过的寄存器(%xmm0)和指令(movss)。%xmm0 寄存器是专门用于浮点值的寄存器的一个例子。movss 指令表示被移到调用栈上的数据是单精度浮点类型。
  • This code snippet contains the previously undiscussed register (%xmm0) and instruction (movss). The %xmm0 register is an example of a register reserved for floating-point values. The movss instruction indicates that the data being moved onto the call stack is of type single-precision floating point.

译注

在 x86-64 System V 调用约定中,前 8 个浮点参数通过 %xmm0–%xmm7 传递,浮点返回值放在 %xmm0 中;它们与整数参数各自独立编号。所以这里第五个参数 g 是 float,就用了第一个浮点寄存器 %xmm0。

  • 代码的下一部分(指令 <initStudent+51> 到 <initStudent+58>)把参数 gr 的值放到距 s 起始处偏移 0x44(即 68)的位置。回顾一下图 1 中的内存布局可以看出,这个地址对应于 s→grad_yr:
  • The next part of the code (instructions <initStudent+51> thru <initStudent+58>) places the value of the gr parameter at an offset of 0x44 (or 68) from the start of s. Revisiting the memory layout in Figure 1 shows that this address corresponds to s→grad_yr:
1
2
3
0x4006dd <+51>: mov   -0x8(%rbp),%rax        #copy s to %rax
0x4006e1 <+55>: mov -0x18(%rbp),%edx #copy gr to %edx
0x4006e4 <+58>: mov %edx,0x44(%rax) #copy gr to %rax+0x44 (s->grad_yr)
  • 下一段代码(指令 <initStudent+61> 到 <initStudent+68>)把参数 ag 复制到 struct 的 s→age 字段,它位于距 s 的地址偏移 0x40(即 64)字节处:
  • The next section of code (instructions <initStudent+61> thru <initStudent+68>) copies the ag parameter to the s→age field of the struct, which is located at an offset of 0x40 (or 64) bytes from the address of s:
1
2
3
0x4006e7 <+61>: mov   -0x8(%rbp),%rax        #copy s to %rax
0x4006eb <+65>: mov -0x14(%rbp),%edx #copy ag to %edx
0x4006ee <+68>: mov %edx,0x40(%rax) #copy ag to %rax+0x40 (s->age)
  • 最后,参数 g 的值被复制到 struct 的 s→gpa 字段(字节偏移 72,即 0x48)。注意这里使用了 %xmm0 寄存器,因为位置 %rbp-0x1c 处存放的数据是单精度浮点数:
  • Lastly, the g parameter value is copied to the s→gpa field (byte offset 72 or 0x48) of the struct. Notice the use of the %xmm0 register since the data contained at location %rbp-0x1c is single-precision floating point:
1
2
3
0x4006f1 <+71>: mov   -0x8(%rbp),%rax        #copy s to %rax
0x4006f5 <+75>: movss -0x1c(%rbp),%xmm0 #copy g to %xmm0
0x4006fa <+80>: movss %xmm0,0x48(%rax) #copy g to %rax+0x48

7.9.1. 数据对齐与结构体

7.9.1. Data Alignment and structs

考虑下面这个修改过的 struct studentT 声明:

Consider the following modified declaration of struct studentT:

1
2
3
4
5
6
7
8
struct studentTM {
char name[63]; //updated to 63 instead of 64
int age;
int grad_yr;
float gpa;
};

struct studentTM student2;

name 字段的大小被改成了 63 字节,而不是原来的 64 字节。想想这会如何影响 struct 在内存中的布局。你可能会想当然地把它想象成图 2 那样。

The size of the name field is modified to be 63 bytes, instead of the original 64. Consider how this affects the way the struct is laid out in memory. It may be tempting to visualize it as in Figure 2.

struct2wrong

图 2. 更新后的 struct studentTM 的一种错误内存布局。注意结构体的「name」字段从 64 字节减少到了 63 字节。

Figure 2. An incorrect memory layout for the updated struct studentTM. Note that the struct’s “name” field is reduced from 64 to 63 bytes.

在这种描绘中,age 字段出现在紧跟 name 字段之后的那个字节。但这是错误的。图 3 描绘了实际的内存布局。

In this depiction, the age field occurs in the byte immediately following the name field. But this is incorrect. Figure 3 depicts the actual layout in memory.

struct2right

图 3. 更新后的 struct studentTM 的正确内存布局。字节 x63 是编译器为满足内存对齐约束而添加的,它不对应任何字段。

Figure 3. The correct memory layout for the updated struct studentTM. Byte x63 is added by the compiler to satisfy memory alignment constraints, but it doesn’t correspond to any of the fields.

x64 的对齐策略要求:两字节的数据类型(即 short)位于两字节对齐的地址上,四字节的数据类型(即 int、float 和 unsigned)位于四字节对齐的地址上,而更大的数据类型(long、double 和指针数据)位于八字节对齐的地址上。对于 struct,编译器会在字段之间添加空字节作为填充(padding),以确保每个字段都满足其对齐要求。例如,在图 3 所声明的 struct 中,编译器在字节 x63 处添加了一个字节的填充,确保 age 字段从一个四的倍数的地址开始。在内存中正确对齐的值可以在单次操作中被读取或写入,从而提高效率。

x64’s alignment policy requires that two-byte data types (i.e., short) reside at a two-byte-aligned address, four-byte data types (i.e., int, float, and unsigned) reside at four-byte-aligned addresses, whereas larger data types (long, double, and pointer data) reside at eight-byte-aligned addresses. For a struct, the compiler adds empty bytes as padding between fields to ensure that each field satisfies its alignment requirements. For example, in the struct declared in Figure 3, the compiler adds a byte of padding at byte x63 to ensure that the age field starts at an address that is at a multiple of four. Values aligned properly in memory can be read or written in a single operation, enabling greater efficiency.

考虑把 struct 定义成下面这样时会发生什么:

Consider what happens when a struct is defined as follows:

1
2
3
4
5
6
7
8
struct studentTM {
int age;
int grad_yr;
float gpa;
char name[63];
};

struct studentTM student3;

把 name 数组移到最后,就把那个填充字节移到了结构体的末尾,确保 age、grad_yr 和 gpa 都是四字节对齐的。

Moving the name array to the end moves the byte of padding to the end of the struct, ensuring that age, grad_yr, and gpa are four-byte aligned.

译注

结构体的总大小还会被补齐为其最大对齐要求的整数倍(这里是 4),所以这两种排列的 sizeof 都是 76:区别只是填充字节的位置。字段顺序真正影响大小的典型例子是 char、double、char 这样大小穿插的排列,可以用 sizeof 和 offsetof(<stddef.h>)自己试验。