[{"categories":["学习"],"collections":["算法"],"content":" Preface 贪心是一种智慧 — 2026/11/26 ","date":"2026-11-26","heading":"","objectID":"/posts/algorithm-greedy/:0:0","tags":["greedy","algorithm"],"title":"算法学习 贪心算法","uri":"/posts/algorithm-greedy/#"},{"categories":["学习"],"collections":["算法"],"content":"贪心算法 贪心算法的总体思想是每步局部最优，得到整体最优。 注意：局部最优未必整体最优，需要严格的数学证明，推荐阅读贪心 ","date":"2026-11-26","heading":"贪心算法","objectID":"/posts/algorithm-greedy/:1:0","tags":["greedy","algorithm"],"title":"算法学习 贪心算法","uri":"/posts/algorithm-greedy/#贪心算法"},{"categories":["学习"],"collections":["算法"],"content":"相邻交换 相邻交换（Exchange Argument）是一种贪心策略，一般在排队问题中使用 当考虑一个队伍如何排列时，可以先考虑局部，考虑相邻的两个元素交换后是否影响最终结果，当相邻两个元素取到最优时，整体就取到最优解。 例： 有$ n $个人排队接水，第$ i $ 个人接水需要 $ T_i $ 分钟。怎么排队，能让所有人的平均等待时间最短？ 我们假设 A，B 两人相邻，A 接水时长为 $T_A$，B 排队接水为 $T_B$，在前面的人的排队时长为 $T_S$。那么，当 A 在 B 之前时，A、B 排队时长之和为 $$T_1 = T_S \u0026#43; T_S \u0026#43; T_A = 2 T_S \u0026#43; T_A$$ 同理，当 B 在 A 之前时，排队时长之和为 $$T_1 = T_S \u0026#43; T_S \u0026#43; T_B = 2 T_S \u0026#43; T_B$$ 假设 A 拍在 B 之前为最优解，那么 $$ T_1 \u0026lt; T_2 $$ 则 $$T_A \u0026lt; T_B$$ 所以，应该让接水时间短的人排在前面，这样就找到了最优解。 练习：P1080 国王游戏 ","date":"2026-11-26","heading":"相邻交换","objectID":"/posts/algorithm-greedy/:2:0","tags":["greedy","algorithm"],"title":"算法学习 贪心算法","uri":"/posts/algorithm-greedy/#相邻交换"},{"categories":["学习"],"collections":["算法"],"content":"区间调度 给定若干区间（任务），每个区间有开始时间与结束时间，目标是选择最多数量的互不重叠区间 论证思路： 选择最早结束的区间能最大限度为后续区间留除空间 若最优解未选择该区间，也可将其替换为结束更早的区间而不减少可选数量 这里运用了交换论证的思想 ℹ 交换论证 所谓交换论证，就是将贪心解与最优解的某一个步骤进行交换，证明交换后的最优解仍然成立。那么贪心解也是最优解 比如有一个排队问题，我们得到贪心解 $G(g_1,g_2,...,g_n)$，最优解为$ O（o_1,o_2,..,o_n）$ 将最优解的第一步替换，得到$ O\u0026#39;（g_1,o_2,..,o_n）$,证明替换后的$O\u0026#39;$不弱于$O$。如果证明每一步替换都不弱于$O$，则贪心解为最优解 如果区间带有权重，贪心策略会失效，需使用动态规划 ","date":"2026-11-26","heading":"区间调度","objectID":"/posts/algorithm-greedy/:3:0","tags":["greedy","algorithm"],"title":"算法学习 贪心算法","uri":"/posts/algorithm-greedy/#区间调度"},{"categories":["学习"],"collections":["算法"],"content":"Johnson法则 Johnson法则用于解决两台机器流水作业问题 适用限制：适用于两台机器，且每个作业都必须先M1，后M2 结论：单个作业如果M1时间短于M2，M1上时间短的往前排，如果M1时间长于M2，M2上时间长的往前排 ","date":"2026-11-26","heading":"Johnson法则","objectID":"/posts/algorithm-greedy/:4:0","tags":["greedy","algorithm"],"title":"算法学习 贪心算法","uri":"/posts/algorithm-greedy/#johnson法则"},{"categories":["学习"],"collections":["算法"],"content":"例题 ","date":"2026-11-26","heading":"例题","objectID":"/posts/algorithm-greedy/:0:0","tags":["greedy","algorithm"],"title":"算法学习 贪心算法","uri":"/posts/algorithm-greedy/#例题"},{"categories":["学习"],"collections":["算法"],"content":"P1842 奶牛玩杂技 每头牛都有自己的体重以及力量，编号为 $i $的奶牛的体重为 $W_i$，力量为 $S_i$ 当某头牛身上站着另一些牛时它就会在一定程度上被压扁，我们不妨把它被压扁的程度叫做它的压扁指数。对于任意的牛，她的压扁指数等于摞在她上面的所有奶牛的总重（当然不包括她自己）减去她的力量。奶牛们按照一定的顺序摞在一起后，她们的总压扁指数就是被压得最扁的那头奶牛的压扁指数。 你的任务就是帮助奶牛们找出一个摞在一起的顺序，使得总压扁指数最小。 假设有两只候选牛 A,B 最有可能被压得最扁，假设 A,B 两头牛把牛分成了三部分，最上面重量为 $W_u$，中间为 $W_m$，最下面为 $W_d$ 当 A 在 B 上方时，总压扁指数为 $$ P_1 = max(W_u- S_A,W_u \u0026#43; W_m \u0026#43; W_A- S_B) $$ 当 B 在 A 上方时，总压扁指数为 $$ P_2 = max(W_u- S_B,W_u \u0026#43; W_m \u0026#43; W_B- S_A) $$ 假设 A 在上方时的总压扁指数最小，则 $$ max(W_u- S_A,W_u \u0026#43; W_m \u0026#43; W_A- S_B) \u0026lt; max(W_u- S_B,W_u \u0026#43; W_m \u0026#43; W_B- S_A) $$ 然后分类讨论，可以得到 $$ W_A\u0026#43;S_A \u0026lt; W_B\u0026#43;S_B $$ 但是分类讨论太麻烦了，我们可以假设 A，B 相邻，问题简化为 $$ max(W_s- S_A,W_s \u0026#43; W_A- S_B) \u0026lt; max(W_s- S_B,W_s \u0026#43; W_B- S_A) $$ 然后再分类讨论，也能得到正确结果 ","date":"2026-11-26","heading":"P1842","objectID":"/posts/algorithm-greedy/:1:0","tags":["greedy","algorithm"],"title":"算法学习 贪心算法","uri":"/posts/algorithm-greedy/#p1842-奶牛玩杂技"},{"categories":["学习"],"collections":["算法"],"content":"二进制串构造 给定一个长度为 n的01串$S=S_1S_2...S_n$。你需要在每两个相邻的数字$Si$ 与$Si\u0026#43;1$ 之间（共$n−1$个位置）各插入一个位运算符，使生成的表达式最终运算结果为0。 可供选择的运算符有三种，其运算规则如下： • 按位与（\u0026amp;）：对于表达式a\u0026amp;b，此表达式的值为 1当且仅当a=b=1，否则为 0。 • 按位异或（^）：对于表达式a^b，此表达式的值为 1当且仅当a=1,b=0或a=0,b=1，否 则为 0。 • 按位或（|）：对于表达式a|b，此表达式的值为 0当且仅当a=b=0，否则为 1。 注意，本题中位运算的优先级与C语言一致，规则如下： 按位与（\u0026amp;）的优先级最高。 按位异或（^）的优先级低于按位与，但高于按位或。 按位或（|）的优先级最低。 对于优先级相同的运算，按照自左向右的顺序结合计算。 你需要构造出一组合法的运算符序列，使得整个表达式最终的运算结果等于0。如果存在多种方案，输 出任意一种即可。可以证明对于所有合法的输入总能找到至少一组合法的构造方案。 通过回溯来解题，我们需要的最终结果为0 如何得到0呢 $$ \\begin{align} 0 {\\ \\ \\ }\\\u0026amp;{\\ \\ \\ } 0 = 0 \\\\\\\\ 1 {\\ \\ }\\oplus{\\ \\ } 1 = 0 \\\\\\\\ 1 {\\ \\ \\ }\\\u0026amp;{\\ \\ \\ } 0 = 0 \\\\\\\\ \\end{align} $$ 我们发现,0，1总有办法得到0，所以 贪心策略为，假定前面的总能得到0 比如：000，设前两个零得到的是0，很容易得到 $$ 0 = 0 \\\u0026amp; 0 \\\u0026amp; 0 $$","date":"2026-11-26","heading":"二进制串构造","objectID":"/posts/algorithm-greedy/:2:0","tags":["greedy","algorithm"],"title":"算法学习 贪心算法","uri":"/posts/algorithm-greedy/#二进制串构造"},{"categories":["学习"],"collections":["xv6"],"content":" Preface 你掉进陷阱啦！ — 2026/11/23 ","date":"2026-11-23","heading":"","objectID":"/posts/xv6-lab-trap/:0:0","tags":["xv6"],"title":"xv6 Lab Trap","uri":"/posts/xv6-lab-trap/#"},{"categories":["学习"],"collections":["xv6"],"content":"RISC-V 在学习 RISC-V，我会将其与 x86 进行对比学习 ","date":"2026-11-23","heading":"RISC-V","objectID":"/posts/xv6-lab-trap/:1:0","tags":["xv6"],"title":"xv6 Lab Trap","uri":"/posts/xv6-lab-trap/#risc-v"},{"categories":["学习"],"collections":["xv6"],"content":"寄存器 RISC-V 有 32 个通用寄存器 分别是 zero ra sp s0 t0~t6 a0 ~ a7 s1 ~ s11 硬接线为 0 返回地址 栈指针 帧指针 临时寄存器 存放参数和返回值 保存寄存器 调用者保存寄存器 被调用者保存寄存器 ra,t0~t6 sp,s0,s1~s11 而 x86 中有 16 个通用寄存器 rax rbx rdx rcx rsp rbp rdi rsi r8~r15 存放返回值 常用作基址 参数 3 参数 4 栈指针 帧指针 参数 1 参数 2 r8 和 r9 作为参数 5 和参数 6 调用者保存寄存器 被调用者保存寄存器 rax,rdx,rcx,rdi,rsi,r8,r9,r10,r11 rbx,rbp,r12~r15 ","date":"2026-11-23","heading":"寄存器","objectID":"/posts/xv6-lab-trap/:1:1","tags":["xv6"],"title":"xv6 Lab Trap","uri":"/posts/xv6-lab-trap/#寄存器"},{"categories":["学习"],"collections":["xv6"],"content":"函数调用 函数调用使用 call 伪指令，之所以是伪指令，是因为实际上 call func 会展开为 auipc ra, %pcrel_hi(func) jalr ra, %pcrel_lo(func)(ra) 实际上做的事情就是 将当前指令下一条指令的地址写入 ra 将目标地址写入 pc 这与 x86 的一个显著区别就是在 x86 中返回地址是要压栈的，而这里是把返回地址放入 ra 寄存器中 进入被调用函数之后，也就是函数序言 addi sp, sp, -16 sd ra, -8(sp) sd s0, -16(sp) addi s0, sp, 16 所做的事情也就是 分配栈空间，也就是栈指针向下移动（记得 16 字节对齐） 将返回地址压栈 保存帧指针 保存被调用寄存器在栈内 可以看出，帧指针是相对于返回地址是在低地址的，这一点与 x86 一致，不过 risc-v 中，返回地址压栈是手动的 在函数尾声中 lw ra, 28(sp) lw s0, 24(sp) lw s1, 20(sp) lw s2, 16(sp) addi sp, sp, 32 ret 恢复返回地址 恢复被调用保存寄存器 释放帧指针 释放栈帧 ","date":"2026-11-23","heading":"函数调用","objectID":"/posts/xv6-lab-trap/:1:2","tags":["xv6"],"title":"xv6 Lab Trap","uri":"/posts/xv6-lab-trap/#函数调用"},{"categories":["学习"],"collections":["xv6"],"content":"Backtrace xv6 栈帧布局 (Stack Frame) 高地址 (High) ... 低地址 (sp) Caller's Frame 调用者栈帧 ra (Return Address) 返回地址 fp (Frame Pointer) 前一个帧指针 s0-s11 (Saved Regs) 保存的寄存器 Local Variables 局部变量 Callee's Frame 被调用者栈帧 (向下增长) * 各段高度仅为示意，实际依赖架构（如 RISC-V）的对齐要求。 在函数序言之后，s0 中存放就是函数栈帧底部的地址，往下 8 个字节就是返回地址，再往下 8 个字节就是上一个函数栈帧底部的地址，所以说，我们总可以通过当前函数帧指针找到上一个函数的帧指针，这就类似于链表。 那我们如何确定栈帧形成的链表已经结束了呢？ 在内核分配内核栈时，应该遵循页对齐的，也就是说，如果在同一个内核栈的函数栈帧，它们帧指针应该是在同一页的 #define PGROUNDDOWN(a) (((a)) \u0026 ~(PGSIZE - 1)) riscv.h 提供了这样一个 PGROUNDDOWN 宏，它的作用是截取地址的前 52 位，如果地址前 52 位相同，那么它们就在同一页 ℹ Note 可能有人会有疑问，如果内核栈大小超过1页了，怎么办呢？其实在xv6中，内核栈的大小就刚好是一页，所以不会出现这个问题 在Linux上，backtrace的实现并不是靠帧指针，而是会有一张专门的表来存放调用链的元数据 在实际写 backtrace 的过程中，打印地址可能会对结果一脸茫然，这里可以大致了解一下不同区域的范围 在内核虚拟地址空间中，最大地址为 0x4000000000 最上方是 Trampoline，然后是多个 kernel stack 和 guard page，这些都不是直接映射的 其次是在PHYSTOP与KERNBASE之间的区域，这部分内存用于保存内核数据（也就是全局变量和静态变量）和代码段。这些内存都是直接映射的 ℹ Note PHYSTOP是指的是Physical Stop，表示这是物理内存的结束地址，KERNBASE = 0x80000000 , PHYSTOP = 0x88000000,这中间夹着128MB的内存大小 最后一部分是 0x0~0x80000000，这一步分都是驱动，也是采取直接映射的 ","date":"2026-11-23","heading":"Backtrace","objectID":"/posts/xv6-lab-trap/:2:0","tags":["xv6"],"title":"xv6 Lab Trap","uri":"/posts/xv6-lab-trap/#backtrace"},{"categories":["学习"],"collections":["xv6"],"content":"alarm 这题首先我们要弄懂我们要做什么 简单来说，需要完成两个系统调用 sigalarm 和 sigreturn 它们的用户层接口分别是 int sigalarm(int interval, void (*handler)()); int sigreturn(void); sigalarm 接收两个参数，作用是每过 interval 个 tick 后，就调用一次 handler ","date":"2026-11-23","heading":"alarm","objectID":"/posts/xv6-lab-trap/:3:0","tags":["xv6"],"title":"xv6 Lab Trap","uri":"/posts/xv6-lab-trap/#alarm"},{"categories":["学习"],"collections":["xv6"],"content":"时钟机制 在 risc-v 中，有一个 time 寄存器，是一个由硬件管理不断自增的计时器，而 xv6 提供了 r_time 接口来获取其值 time 寄存器自增的单位是cycle，1s = 1000000 cycles,time 的自增是由硬件控制的，软件无法干预，也不用干预 而本实验中的 ticks 是一个全局变量，它有内核进行维护，其维护的主要函数是 clockintr void clockintr() { if (cpuid() == 0) { acquire(\u0026tickslock); ticks++; wakeup(\u0026ticks); release(\u0026tickslock); } w_stimecmp(r_time() + 1000000); } 由于可能有多核 CPU，只让 cpu0 对 ticks 的值进行更新，这段代码的重点在于 w_stimecmp(r_time() + 1000000); 原理是 cpu 中还有个寄存器 stimecmp，w_stimecmp 表示将 stimecmp 修改为 当前cycles + 1000000 每次 time 寄存器自增时，都会于 stimecmp 寄存器内的值进行比较，如果相等，则会触发一次时钟中断，每次触发时钟中断都会调用 clockintr 函数，更新 ticks 和 stimecmp 可以看出，每次更新 ticks 的间隔为 1000000cycles，也就是说 $$ 0.1 s = 1 tick = 1000000 cycles $$ 回到 sigalarm，每过 interval 个 ticks，我们就需要调用 handler。考虑到需要检测 ticks，所以需要把检测和调用 handler 的代码放在时钟中断的相关逻辑中。最重要也是最困难的是如何安全的调用 handler 考虑相关需求 在调用 handler 前后，我们需要保证在用户态的上下文不改变，也就是说在发生 alarm，调用 handler 之后，原代码继续执行 在 handler 结束之前，不能再次调用 handler，所以我们需要一个变量维护 handler 调用状态 每次 handler 结束后，会调用 sigreturn 为返回到原位置做准备 看起来有点困难，实际上一点也不简单，先梳理一下常见的坑 在获得 handler 的用户虚拟地址后，通过 walkaddr 得到物理地址进行调用 解决方法 这是函数指针于变量指针一个很大的区别，变量我们获得其物理地址之后直接访问就可以了，但函数指令却不行，因为缺少函数执行的上下文。所以如果要执行handler，我们还是需要回到用户虚拟空间进行执行，方法也是很简单的，那就是改变当前proc的trapframe的epc字段为handler的用户虚拟地址 忽略 sigreturn 的返回值 解决方法 这里就涉及到了一个很重要的点:系统调用在内核层面的封装函数一定有是以uint64为返回值且不含参数的，在syscall分发函数中，会将封装函数的返回值赋值给trapframe的a0寄存器，作为用户层系统调用的返回值，假设在实际实现为void，那么最后在赋给a0的值就是垃圾值了，所以一定要返回原本存的a0 在实现的过程中我们需要在 struct proc 中增加一些字段，并且记得在 allocproc 中初始化。在对每个进程都需要做一些处理时，逻辑应写在 allocproc 函数，而不是 kfork 函数，因为第一个进程不是通过 kfork 创建，但需要经过 allocproc 函数 ","date":"2026-11-23","heading":"时钟机制","objectID":"/posts/xv6-lab-trap/:3:1","tags":["xv6"],"title":"xv6 Lab Trap","uri":"/posts/xv6-lab-trap/#时钟机制"},{"categories":["学习"],"collections":["xv6"],"content":" Preface 虚拟地址如何找到物理地址呢？ — 2026/11/16 ","date":"2026-11-16","heading":"","objectID":"/posts/xv6-lab-pagetable/:0:0","tags":["xv6"],"title":"xv6 Lab Page Table","uri":"/posts/xv6-lab-pagetable/#"},{"categories":["学习"],"collections":["xv6"],"content":"三级索引机制 xv6 中，64 位虚拟地址只有低 39 位被使用，低 39 位中的前 27 位被拆成 3 个 9 位的索引，也就是三级索引。之所以每级索引占 9 位，是因为这个索引索引的是页表项（PTE），每个 PTE 占 8 个字节，故每页有 512 个 PTE 后 12 位表示页内偏移量，因为一页大小为 4096bytes，故 offset 需要 12 位表示 satp 寄存器保存着根页表的物理地址 在实际使用中，xv6 将虚拟地址限制在 38 位，在 kernel/riscv.h 中定义了 #define MAXVA (1L \u0026lt;\u0026lt; (9 + 9 + 9 + 12 - 1))。在 RISC-V 标准中，第 39 位作为符号位出现，标记位不同的区域，用户地址空间位于正半区，而内核地址空间位于负半区。但 xv6 为了简化设计，弃用了负半区，转而在 kernel/memlayout.h 中设定了 #define KERNBASE 0x80000000L，高于 KERNBASE 的空间就是内核地址空间了 index index VPN[2] VPN[2] VPN[1] VPN[1] VPN[0] VPN[0] offset offset 9 bits 9 bits 9 bits 9 bits index index 9 bits 9 bits 12 bits 12 bits Virtual Address Virtual Address 25 bits 25 bits Page of PTE Page of PTE Page of PTE Page of PTE Page of PTE Page of PTE satp satp Pagetable Pagetable PNN PNN Physical Address Physical AddressText is not SVG - cannot display ","date":"2026-11-16","heading":"三级索引机制","objectID":"/posts/xv6-lab-pagetable/:1:0","tags":["xv6"],"title":"xv6 Lab Page Table","uri":"/posts/xv6-lab-pagetable/#三级索引机制"},{"categories":["学习"],"collections":["xv6"],"content":"PTE PTE 即 Page Table Entry 译为页表项，每个 PTE 占 8 个字节。PTE 是页表的基本组成单元 PTE 是一个 64 位的整数，但 64 并非全部使用，部分留作未来扩展，有效的主要由两部分组成。 PPN(Physical Page Number) PPN 是物理页号，占 44 位，这是 PTE 的核心，存储着映射的物理页的起始地址 Flags Flags 记着该页的访问权限和状态，其中被 xv6 系统使用的有： V 第零位，作为有效位 R 第一位，作为可读权限位 W 第二位，作为可写权限位 X 第三位，作为可执行权限位 U 第四位，作为用户态权限位 xv6 定义了一些宏于 kernel/riscv.h，以方便访问 #define PTE_V (1L \u003c\u003c 0) // valid #define PTE_R (1L \u003c\u003c 1) #define PTE_W (1L \u003c\u003c 2) #define PTE_X (1L \u003c\u003c 3) #define PTE_U (1L \u003c\u003c 4) // user can access 另外还有 PTE_G（标记全局映射），PTE_A（访问位）和 PTE_D（脏位），xv6 使用较少 当 PTE 表示的下一级索引而非叶子时，标志位 V 位为 1，R/W/X 全为 0，这也是非叶子 PTE 的标志 当访问虚拟地址时，通过页表将虚拟地址映射为物理地址 $$ Physical Address(56bits) = PPN(44bits) + Offset(12bits) $$ ","date":"2026-11-16","heading":"PTE","objectID":"/posts/xv6-lab-pagetable/:2:0","tags":["xv6"],"title":"xv6 Lab Page Table","uri":"/posts/xv6-lab-pagetable/#pte"},{"categories":["学习"],"collections":["xv6"],"content":"walk 函数 walk 函数位于 kernel/vm.c 中，其主要作用就是按照三级索引下降，最终返回叶子 PTE 的指针 // Return the address of the PTE in page table pagetable // that corresponds to virtual address va. If alloc!=0, // create any required page-table pages. // // The risc-v Sv39 scheme has three levels of page-table // pages. A page-table page contains 512 64-bit PTEs. // A 64-bit virtual address is split into five fields: // 39..63 -- must be zero. // 30..38 -- 9 bits of level-2 index. // 21..29 -- 9 bits of level-1 index. // 12..20 -- 9 bits of level-0 index. // 0..11 -- 12 bits of byte offset within the page. pte_t * walk(pagetable_t pagetable, uint64 va, int alloc) { if (va \u003e= MAXVA) //判断传入的虚拟地址是否超过最大虚拟地址 panic(\"walk\"); //如果超过就触发恐慌 //遍历三级索引 for (int level = 2; level \u003e 0; level--) { //提取索引 pte_t *pte = \u0026pagetable[PX(level, va)]; //检查有效位 if (*pte \u0026 PTE_V) { //将PTE转化为物理地址 pagetable = (pagetable_t)PTE2PA(*pte); #ifdef LAB_PGTBL if (PTE_LEAF(*pte)) { return pte; } #endif //有效位为0，判断是否分配新的物理页 } else { //只查找，不分配 if (!alloc || (pagetable = (pde_t *)kalloc()) == 0) return 0; //缺失是分配新的物理页 memset(pagetable, 0, PGSIZE); *pte = PA2PTE(pagetable) | PTE_V; } } //返回物理页号 return \u0026pagetable[PX(0, va)]; } 其中： PX 宏定义在 kernel/riscv.h 中，用于提取每一级 VPN（Virtual Page Number），即每一级索引 // extract the three 9-bit page table indices from a virtual address. #define PXMASK 0x1FF // 9 bits #define PXSHIFT(level) (PGSHIFT + (9 * (level))) #define PX(level, va) ((((uint64)(va)) \u003e\u003e PXSHIFT(level)) \u0026 PXMASK) PA2PTE 与 PTE2PA 是 PTE 与物理地址互相转化的工具(这里的 two 是 to)，同样定义在 kernel/riscv.h 中 // shift a physical address to the right place for a PTE. #define PA2PTE(pa) ((((uint64)pa) \u003e\u003e 12) \u003c\u003c 10) #define PTE2PA(pte) (((pte) \u003e\u003e 10) \u003c\u003c 12) 转化原理 PTE与PA结构如下 物理地址 PA（56 位） PPN (44 位) Offset (12 位) bit 55 … 12 bit 11 … 0 页表项 PTE（64 位） Resv PPN (44 位) RSW D A G U X W R V 63…54 53…10 9-8 7 … 0 PPN 在 PA 里从 bit 12 开始，在 PTE 里从 bit 10 开始 —— 中间差 2 位。这就是为什么提取时 `\u003e\u003e10`，放回时 `\u003c\u003c12` ","date":"2026-11-16","heading":"","objectID":"/posts/xv6-lab-pagetable/:3:0","tags":["xv6"],"title":"xv6 Lab Page Table","uri":"/posts/xv6-lab-pagetable/#walk-函数"},{"categories":["学习"],"collections":["xv6"],"content":"mappages 函数 mappages 用于建立 物理内存 与虚拟地址之间的联系 // Create PTEs for virtual addresses starting at va that refer to // physical addresses starting at pa. // va and size MUST be page-aligned. // Returns 0 on success, -1 if walk() couldn't // allocate a needed page-table page. int mappages(pagetable_t pagetable, uint64 va, uint64 size, uint64 pa, int perm) { uint64 a, last; pte_t *pte; //检查对齐 if ((va % PGSIZE) != 0) panic(\"mappages: va not aligned\"); if ((size % PGSIZE) != 0) panic(\"mappages: size not aligned\"); if (size == 0) panic(\"mappages: size\"); a = va; last = va + size - PGSIZE; //for循环实现批量映射 for (;;) { if ((pte = walk(pagetable, a, 1)) == 0) return -1; if (*pte \u0026 PTE_V) panic(\"mappages: remap\"); //将地址和权限写入pte *pte = PA2PTE(pa) | perm | PTE_V; if (a == last) break; //移动至下一页 a += PGSIZE; pa += PGSIZE; } return 0; } ","date":"2026-11-16","heading":"","objectID":"/posts/xv6-lab-pagetable/:4:0","tags":["xv6"],"title":"xv6 Lab Page Table","uri":"/posts/xv6-lab-pagetable/#mappages-函数"},{"categories":["学习"],"collections":["xv6"],"content":"用户地址空间与内核地址空间 用户地址空间 xv6 用户地址空间布局 MAXVA TRAMPOLINE TRAPFRAME p-\u0026gt;sz 0 trampoline 内核跳板代码 trapframe 保存用户上下文 用户栈 stack 向低地址增长 guard page 不可访问 heap (堆) ↑ sbrk() 向上增长 data (.data + .bss) 全局/静态变量 text (代码段) 只读、可执行 * 各段高度仅为示意，实际依赖页面（PGSIZE）对齐。 ","date":"2026-11-16","heading":"用户地址空间与内核地址空间","objectID":"/posts/xv6-lab-pagetable/:5:0","tags":["xv6"],"title":"xv6 Lab Page Table","uri":"/posts/xv6-lab-pagetable/#用户地址空间与内核地址空间"},{"categories":["学习"],"collections":["xv6"],"content":"区域功能详解 进程地址空间布局 · 低地址 ↑ 高地址 text 代码段 · R-X 实际上是编译后的机器指令，只读、可执行，pc 所指向的常常就是这个区域。值得了解的是，在 RISC-V 中许多指令占 4 字节，而在 x86 中许多指令占 2 字节。 rodata 只读数据段 · R-- 存储着只读数据，夹在 text 和 data 之间（图中未画出）。 data 数据段 · RW- 包括 .data 和 .bss：.data 是已初始化的数据，.bss 是未初始化或初始化为 0 的数据。 heap 堆区 · RW- 向高地址方向增长，使用 .sbrk() 增大或缩小。 guard page 保护页 · --- 不可访问，访问此区域时触发缺页异常（Page Fault），内核杀死该进程。常用来检测栈溢出；当然，当堆区过高时也会访问到这个区域。 stack 栈 · RW- 可以说是最重要且最容易出错的区域之一，向低地址增长。值得一提的是，xv6 的栈相当小，可能申请 4096 个 bytes 就爆栈了。 trapframe 陷阱帧 · RW- 保存系统调用时的上下文，在系统调用的 Lab 中已详细了解了该区域。每个 struct proc 都有一个 trapframe 字段，用于访问该进程上下文内容。 trampoline 跳板页 · R-X 保存着系统调用时的内核跳转机器指令，也就是 trampoline.S 中所呈现的汇编指令。它同时被映射在用户页表和内核页表的同一虚拟地址上，因为陷入内核态时也需要访问该区域 ","date":"2026-11-16","heading":"区域功能详解","objectID":"/posts/xv6-lab-pagetable/:5:1","tags":["xv6"],"title":"xv6 Lab Page Table","uri":"/posts/xv6-lab-pagetable/#区域功能详解"},{"categories":["学习"],"collections":["xv6"],"content":"内核地址空间 xv6 内核地址空间 (虚拟 \u0026rarr; 物理映射) Virtual Addresses Physical Addresses MAXVA (0x4000000000) PHYSTOP (0x88000000) KERNBASE (0x80000000) 0x10001000 0x10000000 0x0C000000 0 2^56-1 0x88000000 0x80000000 0x02000000 0x1000 0 Trampoline Guard page Kstack 0 Guard page Kstack 1 ... Free memory Kernel data Kernel text VIRTIO disk UART0 PLIC Unused Physical memory (RAM) Unused and other I/O devices VIRTIO disk UART0 PLIC CLINT Unused boot ROM Unused * 左右地址空间通过页表映射对应 内核地址空间多采用直接映射，内核空间从 KERNBASE 开始 值得一提的是，每个进程都有一个内核栈，但内核栈并不保存在进程的用户地址空间中，而是保存在内核地址空间中，内核地址空间为所有进程共享，但只有当 CPU 处于 Supervisor Mode 时才可以访问。内核栈之间也会插入guard page，以防止栈溢出 ","date":"2026-11-16","heading":"内核地址空间","objectID":"/posts/xv6-lab-pagetable/:5:2","tags":["xv6"],"title":"xv6 Lab Page Table","uri":"/posts/xv6-lab-pagetable/#内核地址空间"},{"categories":["学习"],"collections":["xv6"],"content":"物理页的分配 在 walk 函数中，若 alloc ≠ 0 时，会通过 kalloc() 函数新分配物理页，kalloc 实现在 kernel/kalloc.c 中 // Allocate one 4096-byte page of physical memory. // Returns a pointer that the kernel can use. // Returns 0 if the memory cannot be allocated. void * kalloc(void) { struct run *r; acquire(\u0026kmem.lock); r = kmem.freelist; if (r) kmem.freelist = r-\u003enext; release(\u0026kmem.lock); if (r) memset((char *)r, 5, PGSIZE); // fill with junk return (void *)r; } 显然，kalloc 维护着一个链表，freelist 始终指向一个空闲页，当拿到空闲页时，会用 0x5 填充空闲页垃圾数据 kalloc 功用 功能上，kalloc返回一个物理地址，但从实现上看，它返回的是一个指针，似乎更像是虚拟地址。实际上，kalloc只能由在内核态运行，由于内核采用直接映射，故虚拟地址等同于物理地址。当用户地址空间需要物理页时，由内核地址空间调用kalloc申请，然后通过mappages将物理页与虚拟地址产生联系 ","date":"2026-11-16","heading":"物理页的分配","objectID":"/posts/xv6-lab-pagetable/:6:0","tags":["xv6"],"title":"xv6 Lab Page Table","uri":"/posts/xv6-lab-pagetable/#物理页的分配"},{"categories":["学习"],"collections":["xv6"],"content":"从虚拟地址到物理地址 我们以虚拟地址 0x0000_0000_0000_1004 为例串联起从虚拟地址到物理地址全过程 1 拆分地址 将虚拟地址后39位拆分，得到 VPN[0] 1 VPN[1] 0 VPN[2] 0 Offset 4 2 用户态访问 通过*访问虚拟地址，此时CPU处于用户态 1. 先从 satp 拿到根页表基址，找到第 VPN[2] = 0 个PTE，发现它是有效的，从这个PTE中提取出出中间级页表的物理地址 2. 再在前面的物理地址基址中，找到第 VPN[1] = 0 个PTE，发现它是有效的，从这个PTE中提取出叶子级页表的物理地址 3. 再在前面的物理地址基址，找到第 VPN[0] = 1 个PTE，发现它是有效的，从这个PTE中提取物理页号，再拼上12位的offset , 得到物理地址 4. 最后去相应物理地址出读出数据 3 分配新内存 假设用户程序调用了malloc函数申请堆内存 malloc 会触发 sbrk系统调用，然后进入内核态，内核调用kalloc函数申请物理页，再调用mappages将物理内存与用户的虚拟地址产生映射关系，最后返回物理页对应的虚拟地址 ","date":"2026-11-16","heading":"从虚拟地址到物理地址","objectID":"/posts/xv6-lab-pagetable/:7:0","tags":["xv6"],"title":"xv6 Lab Page Table","uri":"/posts/xv6-lab-pagetable/#从虚拟地址到物理地址"},{"categories":["学习"],"collections":["xv6"],"content":"用户虚拟地址，内核虚拟地址与物理地址 三者极易弄混，在习惯上，能直接访问的地址用指针表示，不能直接访问的地址用 uint64 表示 我们不能在内核态访问用户虚拟地址，因为在访问虚拟地址时，实际上是MMU根据 satp 寄存器中存放的物理地址读取，每个进程都有自己的页表。而内核的页表是一个定义在 kernel/vm.c 中的全局变量，在学习 syscall 时，我们已经知道，在汇编函数 uservec，会将 satp 从用户页表切换至内核页表，所以在系统调用时访问用户虚拟空间也是行不通的 因此，在编写系统调用实现函数，比如 int open(char* file,int flags)，我们需要接收一个字符串指针，但显然，在 sys_open 中，万万不能对拿到的指针进行解引用的，为了便于使用，xv6 实现了 copyin 和 copyout 来实现 kernel 和 user 数据复制，我们来看看 xv6 是怎么做的 // Copy from user to kernel. // Copy len bytes to dst from virtual address srcva in a given page table. // Return 0 on success, -1 on error. int copyin(pagetable_t pagetable, uint64 psz, char *dst, uint64 srcva, uint64 len) { uint64 n, va0, pa0; while (len \u003e 0) { va0 = PGROUNDDOWN(srcva); pa0 = walkaddr(pagetable, va0); if (pa0 == 0) { if ((pa0 = vmfault(pagetable, psz, va0, 1)) == 0) { return -1; } } n = PGSIZE - (srcva - va0); if (n \u003e len) n = len; memmove(dst, (void *)(pa0 + (srcva - va0)), n); len -= n; dst += n; srcva = va0 + PGSIZE; } return 0; } // Copy from kernel to user. // Copy len bytes from src to virtual address dstva in a given page table. // Return 0 on success, -1 on error. int copyout(pagetable_t pagetable, uint64 psz, uint64 dstva, char *src, uint64 len) { uint64 n, va0, pa0; pte_t *pte; while (len \u003e 0) { va0 = PGROUNDDOWN(dstva); if (va0 \u003e= MAXVA) return -1; pa0 = walkaddr(pagetable, va0); if (pa0 == 0) { if ((pa0 = vmfault(pagetable, psz, va0, 0)) == 0) { return -1; } } if ((pte = walk(pagetable, va0, 0)) == 0) { // printk(\"copyout: pte should exist %lx %ld\\n\", dstva, len); return -1; } // forbid copyout over read-only user text pages. if ((*pte \u0026 PTE_W) == 0) return -1; n = PGSIZE - (dstva - va0); if (n \u003e len) n = len; memmove((void *)(pa0 + (dstva - va0)), src, n); len -= n; src += n; dstva = va0 + PGSIZE; } return 0; } 其实核心就是通过 walkaddr 函数手动地把 CPU 访问虚拟内存得到物理内存的工作做一遍，这里的in和out都是相较于内核而言 ℹ 提示 walk和walkaddr大差不差，区别在于walk返回的是指向叶子PTE的内核虚拟地址，walkaddr返回的是传入虚拟地址通过页表找到的物理地址(但不带偏移量) ","date":"2026-11-16","heading":"用户虚拟地址，内核虚拟地址与物理地址","objectID":"/posts/xv6-lab-pagetable/:8:0","tags":["xv6"],"title":"xv6 Lab Page Table","uri":"/posts/xv6-lab-pagetable/#用户虚拟地址内核虚拟地址与物理地址"},{"categories":["学习"],"collections":["xv6"],"content":"最后 虚拟内存机制是操作系统的重要机制，虚拟内存给进程提供连续、独立的虚拟地址空间，同时，物理页的申请由内核管理，保障了系统的安全。由于每个进程间虚拟内存的独立，保障了物理内存访问的安全性，也有利于实现进程间隔离。 当然，虚拟内存并不只是软件的设计，更有 CPU 硬件的约束。在 CPU 中， MMU（Memory Management Unit） 作为硬件模块，遵循特定的索引访问机制。更确切地说，内核负责建立和维护页表、管理物理页框和映射策略；MMU 按硬件规定的页表格式和遍历规则完成地址转换与权限检查；缺页时 MMU 触发异常，由内核处理。 ","date":"2026-11-16","heading":"最后","objectID":"/posts/xv6-lab-pagetable/:9:0","tags":["xv6"],"title":"xv6 Lab Page Table","uri":"/posts/xv6-lab-pagetable/#最后"},{"categories":["学习"],"collections":["xv6"],"content":" Preface 系统调用的流程到底是怎样的？ — 2026/11/13 ","date":"2026-11-13","heading":"","objectID":"/posts/xv6-lab-syscalls/:0:0","tags":["xv6"],"title":"xv6 Lab System calls","uri":"/posts/xv6-lab-syscalls/#"},{"categories":["学习"],"collections":["xv6"],"content":"Lab System calls 本 Lab 主要以完成 interpose 为例，让读者了解 xv6 中系统调用的全流程 ","date":"2026-11-13","heading":"Lab System calls","objectID":"/posts/xv6-lab-syscalls/:0:0","tags":["xv6"],"title":"xv6 Lab System calls","uri":"/posts/xv6-lab-syscalls/#lab-system-calls"},{"categories":["学习"],"collections":["xv6"],"content":"用户接口 以 interpose 为例子 我们会在用户层提供接口 interpose(int syscall,char* name)， 这个接口的由汇编完成实现，汇编代码由 usys.pl 自动生成，我们只需要在 usys.pl 中添加 entry(\u0026quot;interpose\u0026quot;) 即可 生成的汇编如下： .global interpose # 外部链接interpose，表示对interpose函数的实现 interpose: li a7, SYS_interpose # li表示load immediate，加载立即数到a7寄存器中 ecall # 触发系统调用 ret # 返回 需要说明的是，ecall 就相当于 x86 中的 syscall，而系统调用号是被放在 a7 中。 ","date":"2026-11-13","heading":"用户接口","objectID":"/posts/xv6-lab-syscalls/:1:0","tags":["xv6"],"title":"xv6 Lab System calls","uri":"/posts/xv6-lab-syscalls/#用户接口"},{"categories":["学习"],"collections":["xv6"],"content":"RISC-V 后续会涉及到 RISC-V 汇编知识，让我们简单了解一下相关知识 寄存器 zero 硬接线为 0，表示值恒为 0 ra Return Address 用于存放返回地址 sp Stack Pointer 栈指针 a0~a7 存放整数参数，多余参数由调用者压栈，返回值保存在 a0 在 ecall 时，a0~a5 用于从存放参数，a7 用于放系统调用号，返回值存在 a0 RISC-V 与 x86 一个显著的区别就是有个特殊的 ra 寄存器存放返回地址，当一个函数调用另一个函数时，会将 ra 保存起来 本 lab 关于 RISC-V 学习到这儿就足够了 ","date":"2026-11-13","heading":"RISC-V","objectID":"/posts/xv6-lab-syscalls/:2:0","tags":["xv6"],"title":"xv6 Lab System calls","uri":"/posts/xv6-lab-syscalls/#risc-v"},{"categories":["学习"],"collections":["xv6"],"content":"syscall 当使用 ecall 之后会发生什么呢？ ecall 属于 trap 的一种，主要分为四个步骤 ","date":"2026-11-13","heading":"syscall","objectID":"/posts/xv6-lab-syscalls/:3:0","tags":["xv6"],"title":"xv6 Lab System calls","uri":"/posts/xv6-lab-syscalls/#syscall"},{"categories":["学习"],"collections":["xv6"],"content":"CPU 硬件执行原子操作 CPU 做的事情主要是更改 pc，改变硬件控制寄存器（Hardware control registers）和改变特权级，硬件控制寄存器有许多个 将 pc 中的值保存到 sepc（Supervisor Exception Program Counter），保存函数调用后能返回到正确的位置 记录 trap 的原因，在 scause（Supervisor Cause）写入一个数字，表明 trap 原因，因为 trap 不仅限于系统调用 关闭中断，改变 sstatus（Supervisor Status），禁用中断，防止处理系统调用时被打断 在 sstatus 中写入当前特权级，以便返回时后续该回到哪个权级 改变特权级，将当前 CPU 的特权级设置为 Supervisor mode 跳转 将 pc 设置为 stvec 寄存器中预先配置好的地址，这个地址式 Trap handler 的入口 ","date":"2026-11-13","heading":"CPU 硬件执行原子操作","objectID":"/posts/xv6-lab-syscalls/:3:1","tags":["xv6"],"title":"xv6 Lab System calls","uri":"/posts/xv6-lab-syscalls/#cpu-硬件执行原子操作"},{"categories":["学习"],"collections":["xv6"],"content":"汇编层的软件处理 stvec 中的跳转地址已被内核修改为 uservec 的地址，uservec 位于 trampoline.S 文件中 实现如下： uservec: # trap.c sets stvec to point here, so # traps from user space start here, # in supervisor mode, but with a # user page table. # # save user a0 in sscratch so # a0 can be used to get at TRAPFRAME. csrw sscratch, a0 # each process has a separate p-\u003etrapframe memory area, # but it's mapped to the same virtual address # (TRAPFRAME) in every process's user page table. li a0, TRAPFRAME # save the user registers in TRAPFRAME sd ra, 40(a0) sd sp, 48(a0) sd gp, 56(a0) sd tp, 64(a0) sd t0, 72(a0) sd t1, 80(a0) sd t2, 88(a0) sd s0, 96(a0) sd s1, 104(a0) sd a1, 120(a0) sd a2, 128(a0) sd a3, 136(a0) sd a4, 144(a0) sd a5, 152(a0) sd a6, 160(a0) sd a7, 168(a0) sd s2, 176(a0) sd s3, 184(a0) sd s4, 192(a0) sd s5, 200(a0) sd s6, 208(a0) sd s7, 216(a0) sd s8, 224(a0) sd s9, 232(a0) sd s10, 240(a0) sd s11, 248(a0) sd t3, 256(a0) sd t4, 264(a0) sd t5, 272(a0) sd t6, 280(a0) # save the user a0 in p-\u003etrapframe-\u003ea0 csrr t0, sscratch sd t0, 112(a0) # initialize kernel stack pointer, from p-\u003etrapframe-\u003ekernel_sp ld sp, 8(a0) # make tp hold the current hartid, from p-\u003etrapframe-\u003ekernel_hartid ld tp, 32(a0) # load the address of usertrap(), from p-\u003etrapframe-\u003ekernel_trap ld t0, 16(a0) # fetch the kernel page table address, from p-\u003etrapframe-\u003ekernel_satp. ld t1, 0(a0) # wait for any previous memory operations to complete, so that # they use the user page table. sfence.vma zero, zero # install the kernel page table. csrw satp, t1 # flush now-stale user entries from the TLB. sfence.vma zero, zero # call usertrap() jalr t0 trapframe 实现 struct trapframe { /* 0 */ uint64 kernel_satp; // kernel page table /* 8 */ uint64 kernel_sp; // top of process's kernel stack /* 16 */ uint64 kernel_trap; // usertrap() /* 24 */ uint64 epc; // saved user program counter /* 32 */ uint64 kernel_hartid; // saved kernel tp /* 40 */ uint64 ra; /* 48 */ uint64 sp; /* 56 */ uint64 gp; /* 64 */ uint64 tp; /* 72 */ uint64 t0; /* 80 */ uint64 t1; /* 88 */ uint64 t2; /* 96 */ uint64 s0; /* 104 */ uint64 s1; /* 112 */ uint64 a0; /* 120 */ uint64 a1; /* 128 */ uint64 a2; /* 136 */ uint64 a3; /* 144 */ uint64 a4; /* 152 */ uint64 a5; /* 160 */ uint64 a6; /* 168 */ uint64 a7; /* 176 */ uint64 s2; /* 184 */ uint64 s3; /* 192 */ uint64 s4; /* 200 */ uint64 s5; /* 208 */ uint64 s6; /* 216 */ uint64 s7; /* 224 */ uint64 s8; /* 232 */ uint64 s9; /* 240 */ uint64 s10; /* 248 */ uint64 s11; /* 256 */ uint64 t3; /* 264 */ uint64 t4; /* 272 */ uint64 t5; /* 280 */ uint64 t6; }; sd（Store Doubleword）表示将寄存器中值存到指定内存中去 uservec 所做的事情： 保存用户寄存器到 trapframe 中 trapframe 是进程虚拟内存空间的一个特殊区域，专门保存 trap 时的用户寄存器 切换到内核栈 将 sp 设置为当前进程的内核栈 内核栈不同于用户栈，用户栈是在当前进程的虚拟地址空间当中。每个进程都有自己的内核栈，但内核栈属于内核虚拟地址空间，内核地址空间有所有进程共享。在 proc 中 kstack 字段专门存放内核栈的虚拟地址 切换内核页表 将 satp 设置为内核页表的地址 内核页表是全局变量，定义在 vm.c 中 pagetable_t kernel_pagetable; 这个页表映射内核代码，内核数据，每个进程的 trapframe 等等。每个进程都有独立的内核栈，但都映射到同一个内核页表中 跳转到 C 代码 从 uservec 跳转到 usertrap() 函数 ","date":"2026-11-13","heading":"汇编层的软件处理","objectID":"/posts/xv6-lab-syscalls/:3:2","tags":["xv6"],"title":"xv6 Lab System calls","uri":"/posts/xv6-lab-syscalls/#汇编层的软件处理"},{"categories":["学习"],"collections":["xv6"],"content":"C 的软件处理 usertrap() 是内核中处理用户态 Trap 的核心 C 函数，位于 kernel/trap.c uint64 usertrap(void) { int which_dev = 0; if ((r_sstatus() \u0026 SSTATUS_SPP) != 0) panic(\"usertrap: not from user mode\"); // send interrupts and exceptions to kerneltrap(), // since we're now in the kernel. w_stvec((uint64)kernelvec); //DOC: kernelvec struct proc *p = myproc(); // save user program counter. p-\u003etrapframe-\u003eepc = r_sepc(); if (r_scause() == 8) { // system call if (killed(p)) kexit(-1); // sepc points to the ecall instruction, // but we want to return to the next instruction. p-\u003etrapframe-\u003eepc += 4; // an interrupt will change sepc, scause, and sstatus, // so enable only now that we're done with those registers. intr_on(); syscall(); } else if ((which_dev = devintr()) != 0) { // ok } else if ((r_scause() == 15 || r_scause() == 13) \u0026\u0026 vmfault(p-\u003epagetable, p-\u003esz, r_stval(), (r_scause() == 13) ? 1 : 0) != 0) { // page fault on lazily-allocated page } else { printk(\"usertrap(): unexpected scause 0x%lx pid=%d\\n\", r_scause(), p-\u003epid); printk(\" sepc=0x%lx stval=0x%lx\\n\", r_sepc(), r_stval()); setkilled(p); } if (killed(p)) kexit(-1); // give up the CPU if this is a timer interrupt. if (which_dev == 2) yield(); prepare_return(); // the user page table to switch to, for trampoline.S uint64 satp = MAKE_SATP(p-\u003epagetable); // return to trampoline.S; satp value in a0. return satp; } usertrap 所做的事情 将 sepc 中的返回地址保存到 trapframe 不依赖寄存器长期保存地址。此外若为系统调用，还要将 epc += 4，这是因为，sepc 存的是 ecall 之前 pc 中的值，pc 保存下一条指令的地址，也就是 ecall，但我们想要的是系统调用返回后执行 ecall 的下一条指令，因此偏移 4 个字节 至于为什么是加 4，而不是加 8，这是因为 ecall 指令占 4 个字节 重启系统中断 调用 intr_on() 函数重启中断 分发处理 依据 scause 中的值判断 trap 的原因，并进行相应处理，对于系统调用，并调用 syscall 函数 除了系统调用，还可能是设备中断（Device Interrupt）或者异常（Exception），Expcetion 时，usertrap 会打印错误信息（包括 scause,sepc,stval 等） ","date":"2026-11-13","heading":"C 的软件处理","objectID":"/posts/xv6-lab-syscalls/:3:3","tags":["xv6"],"title":"xv6 Lab System calls","uri":"/posts/xv6-lab-syscalls/#c-的软件处理"},{"categories":["学习"],"collections":["xv6"],"content":"syscall 分发系统调用 syscall() 位于 kernel/syscall.c void syscall(void) { int num; struct proc *p = myproc(); num = p-\u003etrapframe-\u003ea7; if (num \u003e 0 \u0026\u0026 num \u003c NELEM(syscalls) \u0026\u0026 syscalls[num]) { // Use num to lookup the system call function for num, call it, // and store its return value in p-\u003etrapframe-\u003ea0 p-\u003etrapframe-\u003ea0 = syscalls[num](); } else { printk(\"%d %s: unknown sys call %d\\n\", p-\u003epid, p-\u003ename, num); p-\u003etrapframe-\u003ea0 = -1; } } 其功能显而易见，读取 a7 中系统调用号，分发系统调用，并保存返回值到 a0 寄存器中 那么系统调用处理函数怎么工作呢？ 在开始是我们在用户层定义了 interpose 函数接口 在调用 interpose 接口函数时，有两个参数被传入，根据函数调用约定，这个两个参数被存放在寄存器 a0 和 a1 中，然后这两个参数在汇编处理阶段被存入 trapframe 中，所以在具体实现中，我们需要去 trapframe 中找这两个参数 好消息是，在 kernel/syscall.c 为我们提供了相关接口获取参数 argraw 极其衍生函数，如 argint 和 argstr ","date":"2026-11-13","heading":"","objectID":"/posts/xv6-lab-syscalls/:3:4","tags":["xv6"],"title":"xv6 Lab System calls","uri":"/posts/xv6-lab-syscalls/#syscall-分发系统调用"},{"categories":["学习"],"collections":["xv6"],"content":"返回用户态 在 syscall 函数完毕后，进入 prepare_return() 函数 void prepare_return(void) { struct proc *p = myproc(); // we're about to switch the destination of traps from // kerneltrap() to usertrap(). because a trap from kernel // code to usertrap would be a disaster, turn off interrupts. intr_off(); // send syscalls, interrupts, and exceptions to uservec in trampoline.S uint64 trampoline_uservec = TRAMPOLINE + (uservec - trampoline); w_stvec(trampoline_uservec); // set up trapframe values that uservec will need when // the process next traps into the kernel. p-\u003etrapframe-\u003ekernel_satp = r_satp(); // kernel page table p-\u003etrapframe-\u003ekernel_sp = p-\u003ekstack + PGSIZE; // process's kernel stack p-\u003etrapframe-\u003ekernel_trap = (uint64)usertrap; p-\u003etrapframe-\u003ekernel_hartid = r_tp(); // hartid for cpuid() // set up the registers that trampoline.S's sret will use // to get to user space. // set S Previous Privilege mode to User. unsigned long x = r_sstatus(); x \u0026= ~SSTATUS_SPP; // clear SPP to 0 for user mode x |= SSTATUS_SPIE; // enable interrupts in user mode w_sstatus(x); // set S Exception Program Counter to the saved user pc. w_sepc(p-\u003etrapframe-\u003eepc); } prepare 重新关闭中断；修改 stvec 为 trap 入口，保证下次 trap 时正常进入 uservec；调整 trapframe 的内核信息；修改 sstatus。最后在 usertrap 中返回 satp usertrap 返回在 userret 中 userret 实现如下 userret: # usertrap() returns here, with user satp in a0. # return from kernel to user. # flush icache, in case this is the first time # we're running this proc on this hart. fence.i # switch to the user page table. sfence.vma zero, zero csrw satp, a0 sfence.vma zero, zero li a0, TRAPFRAME # restore all but a0 from TRAPFRAME ld ra, 40(a0) ld sp, 48(a0) ld gp, 56(a0) ld tp, 64(a0) ld t0, 72(a0) ld t1, 80(a0) ld t2, 88(a0) ld s0, 96(a0) ld s1, 104(a0) ld a1, 120(a0) ld a2, 128(a0) ld a3, 136(a0) ld a4, 144(a0) ld a5, 152(a0) ld a6, 160(a0) ld a7, 168(a0) ld s2, 176(a0) ld s3, 184(a0) ld s4, 192(a0) ld s5, 200(a0) ld s6, 208(a0) ld s7, 216(a0) ld s8, 224(a0) ld s9, 232(a0) ld s10, 240(a0) ld s11, 248(a0) ld t3, 256(a0) ld t4, 264(a0) ld t5, 272(a0) ld t6, 280(a0) # restore user a0 ld a0, 112(a0) # return to user mode and user pc. # prepare_return() sets up sstatus and sepc. sret 基本就是在将 trapframe 中的值重新写入寄存器中，最后 sret 返回，硬件自动将特权级切换至 User Mode. 整体调用链： flowchart LR A[\"CPU硬件处理 ecall 触发 trap\"] --\u003e B[\"uservec trampoline.S\"] B --\u003e C[\"usertrap trap.c\"] C --\u003e D[\"syscall syscall.c\"] D --\u003e E[\"prepare_return trap.c\"] E --\u003e F[\"userret trampoline.S\"] F --\u003e G[\"返回用户态继续执行\"] 这便是系统调用的全流程 ","date":"2026-11-13","heading":"返回用户态","objectID":"/posts/xv6-lab-syscalls/:3:5","tags":["xv6"],"title":"xv6 Lab System calls","uri":"/posts/xv6-lab-syscalls/#返回用户态"},{"categories":["学习"],"collections":["xv6"],"content":" Preface The operating system will help you manage your programs. — 2026/11/11 ","date":"2026-11-12","heading":"","objectID":"/posts/xv6-chapter-2/:0:0","tags":["xv6"],"title":"xv6 chapter2","uri":"/posts/xv6-chapter-2/#"},{"categories":["学习"],"collections":["xv6"],"content":"Operating system organization An operating system should satisfy three requirements: multiplexing The operating system must support several activities at once,sharing resources such as CUPs and memory among them. isolation The operating system should ensure that when a process occurs bugs,it won\u0026rsquo;t affect other processes. interaction Different processes need to interact,such as pipelines. ","date":"2026-11-12","heading":"Operating system organization","objectID":"/posts/xv6-chapter-2/:0:0","tags":["xv6"],"title":"xv6 chapter2","uri":"/posts/xv6-chapter-2/#operating-system-organization"},{"categories":["学习"],"collections":["xv6"],"content":"Why operating systems? achieve strong ioslation.Avoid the influence among processes. provide abstract resources and interface such as open,readand write,so that operating system take the responsibility of manage the disk. transparently switches CPUs among process.Save the state of registers. ","date":"2026-11-12","heading":"Why operating systems?","objectID":"/posts/xv6-chapter-2/:1:0","tags":["xv6"],"title":"xv6 chapter2","uri":"/posts/xv6-chapter-2/#why-operating-systems"},{"categories":["学习"],"collections":["xv6"],"content":"User mode,supervisor mode and system calls To achieve string isolation,CPUs provide hardware support.RISC-V has three privilege levels which constrain what code can do: machine mode, supervisor mode, user mode. machine mode has full privilege,which is mostly intended for setting up the computer during boot.Xv6 executes briefly in machine mode and then changes to supervisor mode. In supervisor mode,the CPU is allowed ti execute privileged instructions such as system calls.If in user mode,CPU doesn\u0026rsquo;t execute the priviledge instruction,but \u0026ldquo;traps\u0026rdquo; to special code in supervisor mode. An application can execute only user-mode instructions and is said to be running in user space,while the software in supervisor mode can also execute privileged instructions and is said to be running in kernel space.The software running in kernel space is called the kernel ","date":"2026-11-12","heading":"User mode,supervisor mode and system calls","objectID":"/posts/xv6-chapter-2/:2:0","tags":["xv6"],"title":"xv6 chapter2","uri":"/posts/xv6-chapter-2/#user-modesupervisor-mode-and-system-calls"},{"categories":["学习"],"collections":["xv6"],"content":"xv6 organization monolithic kernel The entire operating system resides in the kernel space. **microkernel Parts of operating system retains in the user space. xv6 is implemented as a monolithic kernel like Linux and most Unix operating systems. The xv6 kernel source is in the kernel/ sub-directory.Files are divided into major areas of kernel responsibility: starting the system(booting) creating and controlling process handling traps allocating memory and configuring virtual addresses controlling devices managing the file-system ","date":"2026-11-12","heading":"xv6 organization","objectID":"/posts/xv6-chapter-2/:3:0","tags":["xv6"],"title":"xv6 chapter2","uri":"/posts/xv6-chapter-2/#xv6-organization"},{"categories":["学习"],"collections":["xv6"],"content":"Process overview Process is regarded as an instance of program, which provides kits with program. Xv6 use page tables(which are implemented by handware) to give each process its own address space.The RISC-V page table translate a virtual address to physical address. Xv6 maintains a seperate page tabe for each process that defines that process\u0026rsquo;s address space. The layout of virutal address space is like following: Instructions -\u0026gt; global variables -\u0026gt; stack -\u0026gt; heap When looking up virtual addresses in page tables,the handware uses only the low 39 bits;and xv6 uses only 38 of those 39 bits. Thus,the maximum address is 0x3fffffffff,which is MAXVA(maximum virtual address). At the top of the address space, xv6 places a trampoline page and a trapframe page,which are used to transition into the kernel and back. The page contains the code to transition in and out of the kernel, and the trapframe os where the kernel saves the process\u0026rsquo;s user registers. The xv6 kernel maintains many pieces of state for each process which is gathered into a struct proc. The significant pieces of the proc: page table kernel stack run state Each process has a thread of control that holds the state needed to execute and process.Concretely,to switch a CPU among processes, the kernel suspends the thread currently running on that CPU and save its state and restore the state of another process\u0026rsquo;s prevously-suspended thread. Each thread has two stacks: a user stack and a kernel stack.When the process is executing user instructions,only the user stack is in use while the kernel stack is empty;when the process enters the kernel,the kernel code executes on the process\u0026rsquo;s kernel stack;while a process is in the kernel,its user stack still contains saved data but not actively used.And the kernel stack is seperate from the user stack. A process\u0026rsquo;s user code can make a system call by executing the RISC-V ecall instruction.This instruction switches to supervisor mode and changes the program counter to a kernel-defined entry point. The code at the entry point switches to the kernel stack and executes the code the system call implements. When system call completes,the kernel returns to user space by executing the sret instruction. typedef int pagetable_t enum procstate { UNUSED, USED, SLEEPING, RUNNABLE, RUNNING, ZOMBIE }; struct proc{ uint64 kstack;//the virtual address of the kernel stack pagetable_t pagetable;//user page table enum proctstate state; //the state of the process /*other fields*/ } state indicates the state of the process. pagetable holds the process\u0026rsquo;s page table. ","date":"2026-11-12","heading":"Process overview","objectID":"/posts/xv6-chapter-2/:4:0","tags":["xv6"],"title":"xv6 chapter2","uri":"/posts/xv6-chapter-2/#process-overview"},{"categories":["学习"],"collections":["xv6"],"content":" Preface Let us go to the world of xv6. — 2026/11/11 ","date":"2026-11-11","heading":"","objectID":"/posts/xv6-chapter-1/:0:0","tags":["xv6"],"title":"xv6 chapter1","uri":"/posts/xv6-chapter-1/#"},{"categories":["学习"],"collections":["xv6"],"content":"Operating System An operating system is designed to manages and abstracts the low-level hardware. To keep each process isolated, the kernel use hardware protection mechanisms provided by CPU.When more permissions are needed(the function-like calling is known as system call),the user program invokes a system call,the hardware raises the privilege level ","date":"2026-11-11","heading":"Operating System","objectID":"/posts/xv6-chapter-1/:1:0","tags":["xv6"],"title":"xv6 chapter1","uri":"/posts/xv6-chapter-1/#operating-system"},{"categories":["学习"],"collections":["xv6"],"content":"Process and memory An xv6 process consists of user-space memory. All C library are not allowed to use.Because it depends on the x86/AMD assembly while the xv6 operating system is based on risc-v. Luckily,most of useful functions are provided.We can check all functions ,which is able to be called freely,in user/user.h All right.Let us gain an inspection on some of functions provided fork function signature int fork() fork is used to create a child process which possess a exact copy of the calling process\u0026rsquo;s memory.fork copy everything of calling process into the new process\u0026rsquo;s memory. Just like we know,fork returns in both original and new processes.In the original process,it returns the new process\u0026rsquo;s PID,while in the new process,it returns zero.If receiving a negative number,it means that fork failed. exit function signature int exit(int status) exit system call causes the calling process to stop and release resource such as memory and file descriptor When calling exit,a status argument is reuquired.Convetionally,0 indicates success and 1 stands for failure wait function signature int wait(int* status) Unlike wait in Linux,wait in xv6 is similar to waitpid(-1,\u0026amp;status,0) in Linux. it returns the PID of an exited child process and copies the exit status of the child to the address passed to wait. if none of the caller\u0026rsquo;s children has exited,wait waits for one to do so.If the caller has no children,wait returns -1 immediately. Supposing the caller have no interest in the status of a child,passing 0(also NULL) is allowed. exec function signature int exec(char *file, char *argv[]) Just like the execve in Linux,exec system call replaces the calling process\u0026rsquo;s memory with a new memory image loaded from a file stored in the file system.Xv6 operating system uses ELF format as executable program. Considering exec succeeds,it does not return.If it returns,we can ensure exec has failed When calling exec,two arguments are passed:the path of the executable file and an array of string arguments(the path included). ","date":"2026-11-11","heading":"Process and memory","objectID":"/posts/xv6-chapter-1/:2:0","tags":["xv6"],"title":"xv6 chapter1","uri":"/posts/xv6-chapter-1/#process-and-memory"},{"categories":["学习"],"collections":["xv6"],"content":"I/O and File descriptors file descriptor is a small integer representing a kernel-managed object that a process may read from or write to. To clarify it,a file descriptor is obtained while opening a file,directory,device or by creating a pipe. The xv6 kernel uses descriptor as an index into a per-process table.Every process has a private space of file descriptor starting at zero. By convention,a process reads file descriptor 0(standard input),writes output to file descriptor 1(standard output),writes error messages to file desciptor 2(standard error). read and write function signature int read(int fd, char *buf, int n) int write(int fd, char *buf, int n) read is used to read n bytes at most from the file descriptor and store them into buf. NOTICE: read always not ensure n bytes are read read returns the number of byte read as a matter of fact. So,when calling read,we always need to use while,if continuing calling read,read reads data from the current file offset.(the offest is stored by struct file) In xv6,read is not only used to read file but directory.When reading the directory,the files(including directory) are abstracted as a array of dirent. struct dirent { ushort inum; char name[DIRSIZ] __attribute__((nonstring)); }; Each read just reads one single dirent,so it is a good choice to use while to read all files in current directory. So,what is file descriptor in fact? We can regard a file descriptor as an index of the files kept in kernel. In fact, the profile of file is in struct file,including reference count, flags ,file offset and so on.Check it in linux/fs.h open and close function signature int open(char *file, int flags) int close(int fd) The second parameter of open is flags,which includes O_RDOLNY,O_WRONLY,O_RDWR,O_CREATE,O_TRUNC.They are defined in fcntl.h and obvious. The kernel will choose a smallest usable number as file descriptor. close system call is used to close the file descriptor instead of the file.In a word,We just change the reference count of file.When the count of reference is zero,the struct file is released. dup function signature int dup(int fd) dup is the short for \u0026ldquo;duplicate\u0026rdquo;,which works as duplicating the file descriptor pointing the same file and increasing the count of reference. When calling fork,everything is almost copied to the new process,and the struct file included. ","date":"2026-11-11","heading":"I/O and File descriptors","objectID":"/posts/xv6-chapter-1/:3:0","tags":["xv6"],"title":"xv6 chapter1","uri":"/posts/xv6-chapter-1/#io-and-file-descriptors"},{"categories":["学习"],"collections":["xv6"],"content":"Pipes pipe is small kernel buffer exposed to processes as a pair of file descriptors,one for reading and one for writing.Pipes provide a way for interprocess communication. function signature int pipe(int pipefd[2]); pipe system call initialize a two-element array,one for reading and another for writing. Let us have a look an example provided by Linux documentation. #include #include #include #include #include int main(int argc, char *argv[]) { int pipefd[2]; char buf; pid_t cpid; if (argc != 2) { fprintf(stderr, \"Usage: %s \\n\", argv[0]); exit(EXIT_FAILURE); } if (pipe(pipefd) == -1) { perror(\"pipe\"); exit(EXIT_FAILURE); } cpid = fork(); if (cpid == -1) { perror(\"fork\"); exit(EXIT_FAILURE); } if (cpid == 0) { /* Child reads from pipe */ close(pipefd[1]); /* Close unused write end */ while (read(pipefd[0], \u0026buf, 1) \u003e 0) write(STDOUT_FILENO, \u0026buf, 1); write(STDOUT_FILENO, \"\\n\", 1); close(pipefd[0]); _exit(EXIT_SUCCESS); } else { /* Parent writes argv[1] to pipe */ close(pipefd[0]); /* Close unused read end */ write(pipefd[1], argv[1], strlen(argv[1])); close(pipefd[1]); /* Reader will see EOF */ wait(NULL); /* Wait for child */ exit(EXIT_SUCCESS); } } How does it work? We call pipe to initialize two file descriptor,one for writing and another for reading.And when forking, the pair of file descriptors are copied.For safety,it is a must to close the useless end(1 indicates writing end ,0 indicates reading end). When we call write on write-end,the data is written into pipe blocked. When we call read on read-end,the data is read into buffer.However, if there is no data in the stream,read will wait for either data to be written or for all file descriptors referring to the write end to be closed.In the latter case,read will return 0,just as if the EOF had been reached. In the xv6 shell | is regarded as pipelines because it works just like a pipe and pass the output current instruction to next instruction as the input. ","date":"2026-11-11","heading":"Pipes","objectID":"/posts/xv6-chapter-1/:4:0","tags":["xv6"],"title":"xv6 chapter1","uri":"/posts/xv6-chapter-1/#pipes"},{"categories":["学习"],"collections":["CSAPP学习笔记"],"content":" Preface 这些笔记写于大一加入凌睿工作室招新期间，更多的是知识的回顾，我将这些笔记记录下来，纪念那段奋斗的时光 — 2026/11/9 ","date":"2026-11-09","heading":"","objectID":"/posts/cssapp-chapter-3/:0:0","tags":["汇编","CSAPP"],"title":"深入理解计算机系统 第三章","uri":"/posts/cssapp-chapter-3/#"},{"categories":["学习"],"collections":["CSAPP学习笔记"],"content":"栈 ","date":"2026-11-09","heading":"栈","objectID":"/posts/cssapp-chapter-3/:1:0","tags":["汇编","CSAPP"],"title":"深入理解计算机系统 第三章","uri":"/posts/cssapp-chapter-3/#栈"},{"categories":["学习"],"collections":["CSAPP学习笔记"],"content":"栈基础知识 栈是一种后进先出的数据结构。理解栈帧，有助于跟踪汇编中的函数调用、局部变量与返回过程。 栈的特点： 向下增长，也就是从高地址到低地址 栈的空间有限，一般只有几 MB，所以当声明过大数组或者深递归时可能会导致爆栈 栈顶是低地址，栈底是高地址 rbp 寄存器内存储指向函数栈帧栈底的指针（地址），rsp 寄存器内存储指向栈顶的指针 当在栈中读取数据时，是从低地址向高地址读取 如 movq (%rsp), %rax，读取地址 0(%rsp) 至 7(%rsp) 的八个字节，写入 rax 寄存器 当调用函数时，一般会创建一个函数栈帧 pushq %rbp movq %rsp, %rbp 增长栈：subq $Imme, %rsp 回收栈：addq $Imme, %rsp 当函数结束，函数栈帧会被回收 leave ret leave 所做的事情相当于 movq %rbp, %rsp popq %rbp ","date":"2026-11-09","heading":"栈基础知识","objectID":"/posts/cssapp-chapter-3/:1:1","tags":["汇编","CSAPP"],"title":"深入理解计算机系统 第三章","uri":"/posts/cssapp-chapter-3/#栈基础知识"},{"categories":["学习"],"collections":["CSAPP学习笔记"],"content":"栈安全 我们知道，每次产生一个函数栈帧时，会在这之前，压返回地址入栈，设想这种情况，假设在改动栈时，将返回地址修改了，那么当返回函数时，rip 内会被修改为一个无法确定甚至是被恶意修改的地址。这就是缓冲区溢出所带来的巨大风险，为了避免这种风险，在编写代码时尽量不使用不检查边界的函数，如 strcpy 栈保护机制 栈随机化 每次运行程序时，栈的起始地址随机变化 Stack Canary（栈金丝雀） 栈金丝雀是编译器放在缓冲区和返回地址之间的一个随机值（具体位置有编译器确定），在返回函数前，检查栈金丝雀是否被修改，若被修改，则调用 __stack_chk_fail 函数，立即终止程序 不可执行栈 栈被标记为不可执行的，避免攻击者将攻击代码放到栈上执行 ","date":"2026-11-09","heading":"栈安全","objectID":"/posts/cssapp-chapter-3/:1:2","tags":["汇编","CSAPP"],"title":"深入理解计算机系统 第三章","uri":"/posts/cssapp-chapter-3/#栈安全"},{"categories":["学习"],"collections":["CSAPP学习笔记"],"content":"栈安全 我们知道，每次产生一个函数栈帧时，会在这之前，压返回地址入栈，设想这种情况，假设在改动栈时，将返回地址修改了，那么当返回函数时，rip 内会被修改为一个无法确定甚至是被恶意修改的地址。这就是缓冲区溢出所带来的巨大风险，为了避免这种风险，在编写代码时尽量不使用不检查边界的函数，如 strcpy 栈保护机制 栈随机化 每次运行程序时，栈的起始地址随机变化 Stack Canary（栈金丝雀） 栈金丝雀是编译器放在缓冲区和返回地址之间的一个随机值（具体位置有编译器确定），在返回函数前，检查栈金丝雀是否被修改，若被修改，则调用 __stack_chk_fail 函数，立即终止程序 不可执行栈 栈被标记为不可执行的，避免攻击者将攻击代码放到栈上执行 ","date":"2026-11-09","heading":"","objectID":"/posts/cssapp-chapter-3/:1:2","tags":["汇编","CSAPP"],"title":"深入理解计算机系统 第三章","uri":"/posts/cssapp-chapter-3/#栈保护机制"},{"categories":["学习"],"collections":["CSAPP学习笔记"],"content":"函数调用 函数调用使用 call \u0026lt;func\u0026gt; 执行 call 时发生了以下几件事 压栈 将 call 的接下来一条指令压入栈中，为函数执行完毕后继续运行做准备 准备进入函数 将被调用函数的第一条指令的地址复制到 rip 中 寄存器 rip 是程序计数器，专门存储下一条指令的内存地址，在介绍寄存器时，详细介绍 另外，在使用 call 指令时，需要对齐，即保证 rsp 为 16 的整数倍 一般而言，函数需要创建自己的栈帧，但是叶子函数则不需要，叶子函数是不调用其他函数的函数 ","date":"2026-11-09","heading":"函数调用","objectID":"/posts/cssapp-chapter-3/:2:0","tags":["汇编","CSAPP"],"title":"深入理解计算机系统 第三章","uri":"/posts/cssapp-chapter-3/#函数调用"},{"categories":["学习"],"collections":["CSAPP学习笔记"],"content":"函数传参 前六个参数分别存储在六个寄存器中：rdi，rsi，rdx，rcx，r8，r9，当然，这六个寄存器只能存储整数和内存地址。更多参数存储在栈中，规则是按照从右往左的顺序压栈，这样就可以从左往右出栈 除此以外，还有一些其他规则。当传浮点数时，使用 8 个 SSE 寄存器（xmm0~xmm7），这种寄存器可存储 16 字节 所以说，并不是说函数传参超过 6 个就会压栈，而是要更根据参数参数的具体类型决定 可变参数 当使用可变参数时，还需设置 al 寄存器来表明用了多少个浮点数以优化速度 可变参数在返回地址的上方，callee 函数只负责读取，而 caller 函数需要负责清理 ","date":"2026-11-09","heading":"函数传参","objectID":"/posts/cssapp-chapter-3/:2:1","tags":["汇编","CSAPP"],"title":"深入理解计算机系统 第三章","uri":"/posts/cssapp-chapter-3/#函数传参"},{"categories":["学习"],"collections":["CSAPP学习笔记"],"content":"函数传参 前六个参数分别存储在六个寄存器中：rdi，rsi，rdx，rcx，r8，r9，当然，这六个寄存器只能存储整数和内存地址。更多参数存储在栈中，规则是按照从右往左的顺序压栈，这样就可以从左往右出栈 除此以外，还有一些其他规则。当传浮点数时，使用 8 个 SSE 寄存器（xmm0~xmm7），这种寄存器可存储 16 字节 所以说，并不是说函数传参超过 6 个就会压栈，而是要更根据参数参数的具体类型决定 可变参数 当使用可变参数时，还需设置 al 寄存器来表明用了多少个浮点数以优化速度 可变参数在返回地址的上方，callee 函数只负责读取，而 caller 函数需要负责清理 ","date":"2026-11-09","heading":"可变参数","objectID":"/posts/cssapp-chapter-3/:2:1","tags":["汇编","CSAPP"],"title":"深入理解计算机系统 第三章","uri":"/posts/cssapp-chapter-3/#可变参数"},{"categories":["学习"],"collections":["CSAPP学习笔记"],"content":"函数返回 函数的返回值大多数时候存储在 rax 寄存器中，但并非没有意外 寄存器类型限制 前面已经知道，rax 这类寄存器只能存储整数和内存地址，那么显然，如果返回浮点数，就需要 SSE 寄存器了，这是会将返回值存储到 xmm0 中 寄存器大小限制 这个需要分为两类，基础类型和复合类型： 基础类型 当存储 128 位整数时没有寄存器能胜任这个任务，所以采取的方案时，拼装两个寄存器 rdx 和 rax，rdx 存储高 64 位，rax 存储低 64 位 复合类型 当存储结构体时，采取的做法是将结构体拆分到 rax，rdx，xmm0，xmm1 中，若结构过大，则会采取，由 caller 分配内存，rax 存储其内存地址的方式 在函数的末尾，使用 ret 指令，其作用是将存放栈中的返回地址弹出，写入 rip 中 ","date":"2026-11-09","heading":"函数返回","objectID":"/posts/cssapp-chapter-3/:2:2","tags":["汇编","CSAPP"],"title":"深入理解计算机系统 第三章","uri":"/posts/cssapp-chapter-3/#函数返回"},{"categories":["学习"],"collections":["CSAPP学习笔记"],"content":"寄存器 寄存器是真实存在的物理实体，它是 CPU 的一种速度极快的存储器 ","date":"2026-11-09","heading":"寄存器","objectID":"/posts/cssapp-chapter-3/:3:0","tags":["汇编","CSAPP"],"title":"深入理解计算机系统 第三章","uri":"/posts/cssapp-chapter-3/#寄存器"},{"categories":["学习"],"collections":["CSAPP学习笔记"],"content":"通用寄存器 在 64 位系统中，前 8 个寄存器有自己的名字，它们分别是 rax，rbx，rcx，rdx，rsp，rbp，rdi，rsi，后 8 个寄存器就是 r8~r15，重点学习前 8 个寄存器 我们已经 rax，rcx，rdx，rsp，rbp，rdi，rsi 各有 ABI 为他们分配的任务，唯独 rbx 貌似没什么作用——事实上，它确实没有特殊作用。在习惯上，它常被用于数组的基址，但并非强制 ","date":"2026-11-09","heading":"通用寄存器","objectID":"/posts/cssapp-chapter-3/:3:1","tags":["汇编","CSAPP"],"title":"深入理解计算机系统 第三章","uri":"/posts/cssapp-chapter-3/#通用寄存器"},{"categories":["学习"],"collections":["CSAPP学习笔记"],"content":"调用者保存寄存器 调用者保存寄存器：即调用者负责保存的寄存器，所以被调用的函数可以随意对其进行修改，调用前后不保证寄存器内数据不变，有：rax,rdx,rcx,rsi,rdi,r8,r9,r10,r11,xmm0~xmm15 可以发现，调用者保存寄存器包括了参数存放和函数返回的寄存器，这些量是在函数调用前后才有意义的，而r10和r11是专门留作临时工的，特殊记忆即可 一个典型的误区是调用者保存不意味着调用者就会去保存，只是当需要保存时有调用者负责而已，其实大多数时候不会特意保存，故是易失的 ","date":"2026-11-09","heading":"调用者保存寄存器","objectID":"/posts/cssapp-chapter-3/:3:2","tags":["汇编","CSAPP"],"title":"深入理解计算机系统 第三章","uri":"/posts/cssapp-chapter-3/#调用者保存寄存器"},{"categories":["学习"],"collections":["CSAPP学习笔记"],"content":"被调用者保存寄存器 被调用者保存：即被调用者负责保存的寄存器，所以在函数调用前后可以保证其内数据不变，可以看作不易失的，包括rbx,rbp,r12,r13,r14,r15。从这里可以看出rbx的特殊之处 ","date":"2026-11-09","heading":"被调用者保存寄存器","objectID":"/posts/cssapp-chapter-3/:3:3","tags":["汇编","CSAPP"],"title":"深入理解计算机系统 第三章","uri":"/posts/cssapp-chapter-3/#被调用者保存寄存器"},{"categories":["学习"],"collections":["CSAPP学习笔记"],"content":"特殊寄存器 rsp：由调用者和被调用共同维护，并且作为栈的实际栈顶 虽然我们常常将 rbp 寄存器认为是当前函数栈底，但这不是严格的，只是约定俗称。而 rsp 确实严格为栈顶 rip：由 call/ret 隐式管理，无法显式地修改 rip ","date":"2026-11-09","heading":"特殊寄存器","objectID":"/posts/cssapp-chapter-3/:3:4","tags":["汇编","CSAPP"],"title":"深入理解计算机系统 第三章","uri":"/posts/cssapp-chapter-3/#特殊寄存器"},{"categories":["学习"],"collections":["CSAPP学习笔记"],"content":"寄存器命名 在 64 位操作系统上，寄存器的命令法则有三套 rax, rbx, rdx, rcx 大小 64 位 32 位 16 位 高 8 位 低 8 位 rax 类 rax eax ax ah al rbx 类 rbx ebx bx bh bl rcx 类 rcx ecx cx ch cl rdx 类 rdx edx dx dh dl rdi, rsi, rsp, rbp 大小 64 位 32 位 16 位 低 8 位 rdi 类 rdi edi di dil rsi 类 rsi esi si sil rsp 类 rsp esp sp spl rbp 类 rbp ebp bp bpl r8 ~ r15 大小 64 位 32 位 16 位 低 8 位 名称 r8~r15 r8d~r15d r8w~r15w r8b~r15b 关键规则：当写入32位寄存器时，会把高32位清零。但写入16位和8位并不会改变其他的数位 ","date":"2026-11-09","heading":"寄存器命名","objectID":"/posts/cssapp-chapter-3/:3:5","tags":["汇编","CSAPP"],"title":"深入理解计算机系统 第三章","uri":"/posts/cssapp-chapter-3/#寄存器命名"},{"categories":["学习"],"collections":["CSAPP学习笔记"],"content":"rflags 寄存器 rflags 寄存器是一个特殊的寄存器，它的每一位都都是特殊的标志位（高 32 位保留） 下面看常见的标志位： ZF（Zero Flag）：结果为 0 时为 1 SF（Sign Flag）：最高位为 1 就为 1 OF（Overflow Flag）：有符号溢出则为 1 CF（Carry Flag）：无符号进位/借位则为 1 ","date":"2026-11-09","heading":"","objectID":"/posts/cssapp-chapter-3/:3:6","tags":["汇编","CSAPP"],"title":"深入理解计算机系统 第三章","uri":"/posts/cssapp-chapter-3/#rflags-寄存器"},{"categories":["学习"],"collections":["CSAPP学习笔记"],"content":"常用指令 指令是汇编中的核心操作，主要是通过操作栈和寄存器进行的。在编写时牢记以下几点： 在 AT\u0026amp;T 语法中，一律为 指令 源操作数, 目的操作数 每条指令最多访问一次内存，但可以多次访问寄存器 目的操作数不能是立即数 下面介绍以下常用指令： ","date":"2026-11-09","heading":"常用指令","objectID":"/posts/cssapp-chapter-3/:4:0","tags":["汇编","CSAPP"],"title":"深入理解计算机系统 第三章","uri":"/posts/cssapp-chapter-3/#常用指令"},{"categories":["学习"],"collections":["CSAPP学习笔记"],"content":"数据传送指令 mov mov 是最常用的指令之一，它的作用是把源操作数中的数据复制到目的操作数 如：movq %rax, %rbx 表示把 rax 中存储的数据移动到 rbx 中，如果给 rax 加一层括号，就类似于 C 中的解引用操作 movq (%rax), %rbx 表示以 rax 中存储的数据为内存地址寻找数据，将找到的数据存储在 rbx 中 lea lea 非常容易与 mov 搞混，它代表直接读取源操作数的地址到目的操作数中 leaq (%rax), %rbx 表示将 rax 中存储的地址读取到 rbx 中 值得注意的是，这里的 (%rax) 并非代表与上面类似的解引用操作，而是表明 rax 内存储着地址 leaq %rax, %rbx是不合法的 正是以为 leaq 的特性，常常被用作高效乘法，具体后面介绍 push 与 pop push 的原理等同于 sub + mov，即先存储空间，再将目的操作数的数据复制到栈中 pop 的原理等于同 mov + add，即先将栈中内容复制到目的操作数中 ","date":"2026-11-09","heading":"数据传送指令","objectID":"/posts/cssapp-chapter-3/:4:1","tags":["汇编","CSAPP"],"title":"深入理解计算机系统 第三章","uri":"/posts/cssapp-chapter-3/#数据传送指令"},{"categories":["学习"],"collections":["CSAPP学习笔记"],"content":"算术与逻辑指令 一元操作算术 inc，dec，neg 三者分别对应自增，自减，取负 二元操作算术 add，sub 两者分别对应加，减 lea 可以完成同等功能，但并非取代，在不同场景下有不同的最优解，一个比较明显的区别是 lea 并不会修改 rflags 逻辑操作算术 and，or，xor 分别表示与、或、异或 移位操作算术 sal, shl, sar, shr 分别是算数左移（Shift Arithmetic Left），逻辑左移（Shift Logical Left），算数右移（Shift Arithmetic Right），逻辑右移（Shift Logical Right） 其中逻辑表明直接执行位移操作而不进行额外判断 算数表明执行位移操作时，会尽量使负数维持为负数，正数维持为正数。但左移必定破坏最高位符号位，所以逻辑左移等同算数左移 另外对于源操作数有特殊要求，必须是立即数，或是存储在 cl 寄存器（rcx 的低 8 位）中 以上的指令都有显著特征：即会改变 rflags 寄存器，且在算数逻辑单元中执行运算 ","date":"2026-11-09","heading":"算术与逻辑指令","objectID":"/posts/cssapp-chapter-3/:4:2","tags":["汇编","CSAPP"],"title":"深入理解计算机系统 第三章","uri":"/posts/cssapp-chapter-3/#算术与逻辑指令"},{"categories":["学习"],"collections":["CSAPP学习笔记"],"content":"控制流指令 cmp 与 test cmp 的原理是，进行运算：目的操作数 - 源操作数，类似于 sub，但 cmp 不会保存运算结果，仅设置条件码 test 与 cmp 类似，执行 and 操作，但不保留结果，仅设置条件码 jmp jmp 指令很简单 jmp Label 将 rip 内地址修改为 Label 地址 jmp *%rax：表示跳转到 %rax 中存储的地址 jmp *(%rax)：表示跳转到以 (%rax) 中存储的地址指向的数据为地址的内存地址 难点在jmp 类指令，这类指令根据条件码的情况进行跳转操作，有以下几种 je（jump if equal） ZF = 1 时跳转 jne（jump if not equal） ZF = 0 时跳转 jg（jump if greater） 用于有符号比较，需要综合考虑 SF，OF，ZF，类似的还有 jge，与 jg/jge 对应的是 jl/jle（jump if less/jump if less or equal） ja（jump if above） 用于无符号比较，需要综合考虑 CF，ZF，类似的还有 jae，与 ja/jae 对应的是 jb/jbe（jump if less/jump if less or equal） 记忆这几个的方法是记住，所有的大或者小都是相对于目的操作数而言的 流程控制的主要目的是模拟 C 中的 for，while，do-while ","date":"2026-11-09","heading":"控制流指令","objectID":"/posts/cssapp-chapter-3/:4:3","tags":["汇编","CSAPP"],"title":"深入理解计算机系统 第三章","uri":"/posts/cssapp-chapter-3/#控制流指令"},{"categories":["学习"],"collections":["CSAPP学习笔记"],"content":"函数调用与栈帧指令 call，ret，leave 这三个指令在上面已经介绍得很清楚了，不加赘述 ","date":"2026-11-09","heading":"函数调用与栈帧指令","objectID":"/posts/cssapp-chapter-3/:4:4","tags":["汇编","CSAPP"],"title":"深入理解计算机系统 第三章","uri":"/posts/cssapp-chapter-3/#函数调用与栈帧指令"},{"categories":["学习"],"collections":["CSAPP学习笔记"],"content":"数据声明与访问 ","date":"2026-11-09","heading":"数据声明与访问","objectID":"/posts/cssapp-chapter-3/:5:0","tags":["汇编","CSAPP"],"title":"深入理解计算机系统 第三章","uri":"/posts/cssapp-chapter-3/#数据声明与访问"},{"categories":["学习"],"collections":["CSAPP学习笔记"],"content":"内存布局 ","date":"2026-11-09","heading":"内存布局","objectID":"/posts/cssapp-chapter-3/:5:1","tags":["汇编","CSAPP"],"title":"深入理解计算机系统 第三章","uri":"/posts/cssapp-chapter-3/#内存布局"},{"categories":["学习"],"collections":["CSAPP学习笔记"],"content":"全局变量与静态变量 两者都存储在 .bss 和 .data 段内，不同的是普通全局变量是外部链接，通过伪指令 .global 声明；而静态全局变量是内部链接，通过伪指令 .local 声明 如 int a = 10; static int b = 10; 对应的汇编如下 .section .data a: .long 10 b: .long 10 .local b .global a .bss 和 .data 的区别在于，.bss 中存储的是未初始化或初始化为 0 的变量，.data 则不是这样的 在声明时，一般格式为 名称: 伪指令 常见的有 .byte，.word，.long，.quad 这四个分别对应 1 字节，2 字节，4 字节，8 字节 .string 表示自动加 \\0 的字符串，.ascii 表示不会自动加 \\0 的字符串 .zero N 表示预留 N 字节空间，并初始化为 0，.space N 表示预留 N 字节空间，不初始化 除了 .bss 和 .data 段，还有 .rodata 段，表示 Read-only Data，一般存放字符串。一个典型的例子就是 printf(\u0026quot;%d\u0026quot;,number);，其中这个 %d 就会被存放到 rodata 段 C 中的一个常见的坑就是 char* str = \u0026quot;Hello\u0026quot;;，不能使用 str[0] 来修改字符串，这是因为 str 指向的字符串是在 rodata 段上的 因为每次程序加载的地址都不一样，所以使用 .bss/.data/.rodata 时应使用 RIP 相对地址：变量名(%rip) ","date":"2026-11-09","heading":"全局变量与静态变量","objectID":"/posts/cssapp-chapter-3/:6:0","tags":["汇编","CSAPP"],"title":"深入理解计算机系统 第三章","uri":"/posts/cssapp-chapter-3/#全局变量与静态变量"},{"categories":["学习"],"collections":["CSAPP学习笔记"],"content":"数组 全局（静态）变量数组 其声明方法与其他全局变量类似： nums: .long 1 .long 2 .long 3 .space 308 等同于 int nums[80] = {1,2,3}; 访问方法也很简单 movl nums+4(%rip), %eax 等同于 int num = nums[1]; 局部变量数组 相较于全部变量数组，局部变量数组更加常用，也更复杂 所谓局部变量，默认是存储在栈上的变量，其访问格式为： $$ offset(base, index, scale) = base \u0026#43; index * scale \u0026#43; offset $$ 其中 base 必须为寄存器，index 必须为通用寄存器（不能为 %rsp）或为空，scale 只能为 1,2,4,8，且 base 和 index 必须为相同大小的寄存器 正是因为在这个取址运算中用到了乘法，所以常常使用 lea 来实现高效的乘法 结构体和联合体访问与数组类似。不过结构体是不同数据类型的集合，并且需要考虑内存对齐，联合体所占字节为最大成员变量所占字节数 ","date":"2026-11-09","heading":"数组","objectID":"/posts/cssapp-chapter-3/:6:1","tags":["汇编","CSAPP"],"title":"深入理解计算机系统 第三章","uri":"/posts/cssapp-chapter-3/#数组"},{"categories":["学习"],"collections":["CSAPP学习笔记"],"content":"数组 全局（静态）变量数组 其声明方法与其他全局变量类似： nums: .long 1 .long 2 .long 3 .space 308 等同于 int nums[80] = {1,2,3}; 访问方法也很简单 movl nums+4(%rip), %eax 等同于 int num = nums[1]; 局部变量数组 相较于全部变量数组，局部变量数组更加常用，也更复杂 所谓局部变量，默认是存储在栈上的变量，其访问格式为： $$ offset(base, index, scale) = base \u0026#43; index * scale \u0026#43; offset $$ 其中 base 必须为寄存器，index 必须为通用寄存器（不能为 %rsp）或为空，scale 只能为 1,2,4,8，且 base 和 index 必须为相同大小的寄存器 正是因为在这个取址运算中用到了乘法，所以常常使用 lea 来实现高效的乘法 结构体和联合体访问与数组类似。不过结构体是不同数据类型的集合，并且需要考虑内存对齐，联合体所占字节为最大成员变量所占字节数 ","date":"2026-11-09","heading":"全局（静态）变量数组","objectID":"/posts/cssapp-chapter-3/:6:1","tags":["汇编","CSAPP"],"title":"深入理解计算机系统 第三章","uri":"/posts/cssapp-chapter-3/#全局静态变量数组"},{"categories":["学习"],"collections":["CSAPP学习笔记"],"content":"数组 全局（静态）变量数组 其声明方法与其他全局变量类似： nums: .long 1 .long 2 .long 3 .space 308 等同于 int nums[80] = {1,2,3}; 访问方法也很简单 movl nums+4(%rip), %eax 等同于 int num = nums[1]; 局部变量数组 相较于全部变量数组，局部变量数组更加常用，也更复杂 所谓局部变量，默认是存储在栈上的变量，其访问格式为： $$ offset(base, index, scale) = base \u0026#43; index * scale \u0026#43; offset $$ 其中 base 必须为寄存器，index 必须为通用寄存器（不能为 %rsp）或为空，scale 只能为 1,2,4,8，且 base 和 index 必须为相同大小的寄存器 正是因为在这个取址运算中用到了乘法，所以常常使用 lea 来实现高效的乘法 结构体和联合体访问与数组类似。不过结构体是不同数据类型的集合，并且需要考虑内存对齐，联合体所占字节为最大成员变量所占字节数 ","date":"2026-11-09","heading":"局部变量数组","objectID":"/posts/cssapp-chapter-3/:6:1","tags":["汇编","CSAPP"],"title":"深入理解计算机系统 第三章","uri":"/posts/cssapp-chapter-3/#局部变量数组"},{"categories":["学习"],"collections":["CSAPP学习笔记"],"content":"GDB 使用技巧 ","date":"2026-11-09","heading":"GDB 使用技巧","objectID":"/posts/cssapp-chapter-3/:7:0","tags":["汇编","CSAPP"],"title":"深入理解计算机系统 第三章","uri":"/posts/cssapp-chapter-3/#gdb-使用技巧"},{"categories":["学习"],"collections":["CSAPP学习笔记"],"content":"基本指令 break 作用：打断点 usage break 行号 break 函数名 break 文件名:行号 break *地址 break 对象 if 条件 rbreak 正则表达式 用 tbreak 替代 break 代表临时断点 watch 作用观察变量是否被修改 usage watch 变量名 //当变量值发生改变时暂停 rwatch 变量名 //当变量值被读取时暂停 awatch 变量名 //当变量值被读取或写入时暂停 watch 变量名 if 条件 disas 反汇编命令 usage disas //反汇编当前栈帧对应函数 disas 函数名 //反汇编此函数 disas $pc //反汇编$pc所在函数 disas 地址 //反汇编地址所在函数 disas 起始地址, 终止地址 //反汇编此地址区间 disas 起始地址, 偏移量 //从起始地址开始反汇编指定偏移量 disas /s //混合显示C源码和汇编代码 disas /b //显示汇编源码和机器指令 examine usage 标准语法：x/\u0026lt;N\u0026gt;\u0026lt;F\u0026gt;\u0026lt;U\u0026gt; \u0026lt;ADDR\u0026gt; N 表示重复次数，连续往后查找 U 表示单位大小 可选 b(byte)，h(halfword)，w(word)，g(giant word)，分别对应 1 字节，2 字节，4 字节，8 字节 需要注意的是，在汇编中，w（double word）代表 4 字节 F 表示显示格式 x d u o t f c s a 十六进制数 有符号十进制 无符号十进制 八进制 二进制 浮点数 字符 字符串 地址 例如：x/8gx 代表 8 个 8 字节的 16 进制数（一般就是地址） ","date":"2026-11-09","heading":"基本指令","objectID":"/posts/cssapp-chapter-3/:7:1","tags":["汇编","CSAPP"],"title":"深入理解计算机系统 第三章","uri":"/posts/cssapp-chapter-3/#基本指令"},{"categories":["学习"],"collections":["CSAPP学习笔记"],"content":" Preface 这些笔记写于大一加入凌睿工作室招新期间，更多的是知识的回顾，我将这些笔记记录下来，纪念那段奋斗的时光 — 2026/11/9 ","date":"2026-11-09","heading":"","objectID":"/posts/csapp-chapter-6/:0:0","tags":["CSAPP"],"title":"深入理解计算机系统 第六章","uri":"/posts/csapp-chapter-6/#"},{"categories":["学习"],"collections":["CSAPP学习笔记"],"content":"进程 进程是程序的一次执行实例 每个进程都有独属于自己的内存区域（相互独立的堆栈等） 每个进程都有独属于自己的自己的进程 ID（PID） ","date":"2026-11-09","heading":"进程","objectID":"/posts/csapp-chapter-6/:0:0","tags":["CSAPP"],"title":"深入理解计算机系统 第六章","uri":"/posts/csapp-chapter-6/#进程"},{"categories":["学习"],"collections":["CSAPP学习笔记"],"content":"创建进程 使用 fork() 函数可以创建子进程，物理页先共享并设为只读，任一进程写入时触发缺页异常，内核再复制该页。这就是 写时复制 COW ","date":"2026-11-09","heading":"创建进程","objectID":"/posts/csapp-chapter-6/:1:0","tags":["CSAPP"],"title":"深入理解计算机系统 第六章","uri":"/posts/csapp-chapter-6/#创建进程"},{"categories":["学习"],"collections":["CSAPP学习笔记"],"content":"覆盖进程 使用 exec 类函数能够将硬盘中指定的可执行文件加载到当前进程中，覆盖掉几乎全部内容。当以下内容不变 PID，进程所在进程组和会话 打开的文件描述符 信号掩码 特别注意：信号处理函数会被重置 系统调用：execve int execve(const char *pathname, char *const argv[], char *const envp[]); pathname：为程序的绝对路径或相对路径，不回去找 PATH argv：表示命名行参数数组，以 NULL 结尾 envp：是环境变量数组，以 NULL 结尾 返回值：失败时返回-1，并设置errno 剩余 5 个 exec 的类函数都是由 execve 函数包装而成 可以通过后缀字母窥见其含义： l(list)：参数以列表（可变参数）的形式传递 v(vector)：参数以字符串数组的形式传递 e(environment)：自定义环境变量 p(path)：当 path 参数为以 / 起始时，运行指定路径程序，当 path 参数不以 / 起始的，从 PATH 中搜索 规则如下： 当指定环境变量时，使用自定义的环境变量，否则使用当前进程中的 environ 每个进程中都有一个全局变量 char** environ，当 fork 时，创建的子进程会复制父进程的 environ PATH 是一个环境变量，其一般格式： PATH=/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin 当使用含 p 后缀的函数时，且 path 参数不以 / 起始时(如 ls)，会依次尝试 /usr/local/bin/ls /usr/bin/ls ... 其余 5 个函数分别为 execl，execvp，execlp，execv，execle ","date":"2026-11-09","heading":"覆盖进程","objectID":"/posts/csapp-chapter-6/:2:0","tags":["CSAPP"],"title":"深入理解计算机系统 第六章","uri":"/posts/csapp-chapter-6/#覆盖进程"},{"categories":["学习"],"collections":["CSAPP学习笔记"],"content":"进程组 进程组是一个进程的集合，通常表示一个作业（job） 每个进程只属于一个进程组，在使用 fork 创建子进程时，默认子进程属于父进程所在进程组 多个进程组组成一个Session（会话） ","date":"2026-11-09","heading":"进程组","objectID":"/posts/csapp-chapter-6/:0:0","tags":["CSAPP"],"title":"深入理解计算机系统 第六章","uri":"/posts/csapp-chapter-6/#进程组"},{"categories":["学习"],"collections":["CSAPP学习笔记"],"content":"前台进程组 前台进程组是一个重要的概念，它是当前 Session 中唯一被赋予控制终端并独占访问权的进程组 在同一时刻，只有一个进程组能被设为前台进程组，如果不是前台进程组，那就是后台进程组 ","date":"2026-11-09","heading":"前台进程组","objectID":"/posts/csapp-chapter-6/:1:0","tags":["CSAPP"],"title":"深入理解计算机系统 第六章","uri":"/posts/csapp-chapter-6/#前台进程组"},{"categories":["学习"],"collections":["CSAPP学习笔记"],"content":"特性 接收键盘产生的信号 当在当前 Session 按下对应的键时，会把信号发送给前台进程组中的全体成员 读取终端 前台进程组可以不受限制地从终端读取输入，而后台进程组一旦尝试读取终端，终端会向该进程组发送 SIGTTIN，暂停该进程组 向终端写入时，终端驱动有一个 TOSTOP 标志，默认关闭，当该标志关闭时，后台进程组可以向控制终端写入而不被阻止 ","date":"2026-11-09","heading":"特性","objectID":"/posts/csapp-chapter-6/:1:1","tags":["CSAPP"],"title":"深入理解计算机系统 第六章","uri":"/posts/csapp-chapter-6/#特性"},{"categories":["学习"],"collections":["CSAPP学习笔记"],"content":"shell 进程组 交互式 shell 本身就是一个进程，所在进程组默认时其就为前台进程组 ","date":"2026-11-09","heading":"shell 进程组","objectID":"/posts/csapp-chapter-6/:2:0","tags":["CSAPP"],"title":"深入理解计算机系统 第六章","uri":"/posts/csapp-chapter-6/#shell-进程组"},{"categories":["学习"],"collections":["CSAPP学习笔记"],"content":"特殊之处 信号处理特殊 会忽略信号：SIGINT，SIGQUIT，SIGTSTP，SIGTTIN，SIGTTOU 作业控制特殊 不在 jobs 输出中 不能被 fg/bg 管理 不能被 Ctrl-Z 观其 ","date":"2026-11-09","heading":"特殊之处","objectID":"/posts/csapp-chapter-6/:2:1","tags":["CSAPP"],"title":"深入理解计算机系统 第六章","uri":"/posts/csapp-chapter-6/#特殊之处"},{"categories":["学习"],"collections":["CSAPP学习笔记"],"content":"前后台进程组切换 挂起前台作业 在前台进程组使用 Ctrl-Z 向其发送 SIGTSTP 信号，使其挂起，该作业变为后台作业 后台/挂起作业变为前台作业 使用 fg 会将指定作业设为前台作业，并向其发送 SIGCONT 信号 fg 背后调用的是 tcsetpgrp（terminal control set process group），其能够设置前台进程组，与之对应的函数还有 tcgetpgrp（terminal control get process group），获取前台进程组 继续后台运行挂起作业 使用 bg 向指定挂起作业发送 SIGCONT，并让其在后台运行 ","date":"2026-11-09","heading":"前后台进程组切换","objectID":"/posts/csapp-chapter-6/:3:0","tags":["CSAPP"],"title":"深入理解计算机系统 第六章","uri":"/posts/csapp-chapter-6/#前后台进程组切换"},{"categories":["学习"],"collections":["CSAPP学习笔记"],"content":"进程生命周期 每个进程都有一个（Process Control Block），其记录着进程的状态，标识信息等，可以说，PCB 是进程的档案袋 在 Linux 中，PCB 的具体实现是 task_struct，这是一个复杂且庞大的结构体，后面在深入再学习 ","date":"2026-11-09","heading":"进程生命周期","objectID":"/posts/csapp-chapter-6/:0:0","tags":["CSAPP"],"title":"深入理解计算机系统 第六章","uri":"/posts/csapp-chapter-6/#进程生命周期"},{"categories":["学习"],"collections":["CSAPP学习笔记"],"content":"创建 使用 fork 函数创建，一般呢，会调用 execv 类函数 ","date":"2026-11-09","heading":"","objectID":"/posts/csapp-chapter-6/:1:0","tags":["CSAPP"],"title":"深入理解计算机系统 第六章","uri":"/posts/csapp-chapter-6/#创建"},{"categories":["学习"],"collections":["CSAPP学习笔记"],"content":"阻塞 当进程内调用 wait，sleep，read 等函数时，会进入阻塞状态，待到指定事件完成后，会自动恢复为运行状态 阻塞分为两种： Interruptible Sleep（S） 能被信号唤醒，大多数阻塞属于这一类型 Disk Sleep（D） 不能被信号唤醒，一般是 I/O 操作 ","date":"2026-11-09","heading":"","objectID":"/posts/csapp-chapter-6/:2:0","tags":["CSAPP"],"title":"深入理解计算机系统 第六章","uri":"/posts/csapp-chapter-6/#阻塞"},{"categories":["学习"],"collections":["CSAPP学习笔记"],"content":"暂停 当进程收到 SIGTSTP 或 SIGSTOP 信号时，进程暂停，当接收到 SIGCONT 信号时，进程恢复到 R 态 ","date":"2026-11-09","heading":"","objectID":"/posts/csapp-chapter-6/:3:0","tags":["CSAPP"],"title":"深入理解计算机系统 第六章","uri":"/posts/csapp-chapter-6/#暂停"},{"categories":["学习"],"collections":["CSAPP学习笔记"],"content":"终止 终止分为两类 正常终止 通过 main 函数正常返回或通过 exit/_exit 终止，退出状态码通过 wait 交给父进程 异常终止 接收到触发异常终止的信号：SIGINT，SIGQUIT，SIGSEGV，SIGTERM，SIGKILL 等，可以通过 wait 获取 status 查看终止信号 当进程终止后，会进入僵尸状态（Z），等待父进程收尸 ","date":"2026-11-09","heading":"","objectID":"/posts/csapp-chapter-6/:4:0","tags":["CSAPP"],"title":"深入理解计算机系统 第六章","uri":"/posts/csapp-chapter-6/#终止"},{"categories":["学习"],"collections":["CSAPP学习笔记"],"content":"回收 当子进程变为僵尸进程后，需要父进程使用 wait/waitpid 为子进程收尸 pid_t wait(int *_Nullable wstatus); pid_t waitpid(pid_t pid, int *_Nullable wstatus, int options); waitpid 函数是 wait 的上位替代，所以这里重点讲解 waitpid 参数： pid：详细规则如下表 \u0026lt;-1 -1 0 \u0026gt;0 等待与 pid 绝对值相等的进程组内所有子进程 等待所有子进程 等待同进程组内所有子进程 等待 pid 所对应的子进程 options 使用掩码进行传参 有三种选择 WNOHANG WUNTRACED WCONTINUED 如果没有子进程为僵尸进程则立即返回 如果一个子进程在暂停状态也会返回，且会记录在 status 中 如果子进程被 SIGCONT 信号恢复了也会返回 当不使用 WNOHANG 时，waitpid 会一直等待指定子进程终止并收尸才返回，使用后如果就把等待变成询问，问一下子进程是否终止，终止就收尸，否则立即返回 当不使用 WUNTRACED 时，waitpid 会对不关心进程是否暂停，使用后，如果暂停，waitpid 也会立即返回，而且可以通过 status 得到是因为暂停返回还是终止返回 WCONTINUED 与 WUNTRACED 类似 wstatus wstatus 需要传一个 int 指针，wait 函数会把僵尸进程的信息写入 wstatus 中，并通过指定宏读取 wstatus 以获取信息，下面是常见宏 WIFEXITED WEXITSTATUS WIFSIGNALED WTERMSIG WIFSTOPPED WSTOPSIG WIFCONTINUED 判断进程是否正常终止 获取正常终止时的退出状态码 判断进程是否是由于信号终止 获取使进程终止的信号 判断进程是否是在暂停（options 必须使用 WUNTRACED） 获取让进程暂停的信号 判断进程是否被 SIGCONT 恢复了 wait(wstatus) == waitpid(-1,wstatus,0) waitpid 函数每次返回只会处理一个子进程 返回值： -1 0 \u0026gt;0 无法找到对应子进程或被信号中断 只有在 WNOHANG 的条件下才可能返回 0，代表没有找到了子进程，但其不为可报告的进程 成功，返回对应处理的子进程的 pid waitpid 能够回收僵尸进程，但必须要父进程调用才行了，那么问题来了，如果一个进程没有父进程，该怎么回收呢？这种没有父进程（或者说父进程已经终止）的进程称为孤儿进程 孤儿进程不需要我们操心了，内核会给孤儿找养父，让养父来为孤儿收尸，所以孤儿一般不会长期僵尸 ","date":"2026-11-09","heading":"","objectID":"/posts/csapp-chapter-6/:5:0","tags":["CSAPP"],"title":"深入理解计算机系统 第六章","uri":"/posts/csapp-chapter-6/#回收"},{"categories":["学习"],"collections":["CSAPP学习笔记"],"content":"信号 在上面我们已经知道信号与进程紧密相连的，能够实现进程间的简单通信 ","date":"2026-11-09","heading":"信号","objectID":"/posts/csapp-chapter-6/:0:0","tags":["CSAPP"],"title":"深入理解计算机系统 第六章","uri":"/posts/csapp-chapter-6/#信号"},{"categories":["学习"],"collections":["CSAPP学习笔记"],"content":"信号的生命周期 ","date":"2026-11-09","heading":"信号的生命周期","objectID":"/posts/csapp-chapter-6/:1:0","tags":["CSAPP"],"title":"深入理解计算机系统 第六章","uri":"/posts/csapp-chapter-6/#信号的生命周期"},{"categories":["学习"],"collections":["CSAPP学习笔记"],"content":"产生 可由硬件，终端和内核产生，也可通过 kill，raise 方法手动发送信号 ","date":"2026-11-09","heading":"产生","objectID":"/posts/csapp-chapter-6/:1:1","tags":["CSAPP"],"title":"深入理解计算机系统 第六章","uri":"/posts/csapp-chapter-6/#产生"},{"categories":["学习"],"collections":["CSAPP学习笔记"],"content":"阻塞 进程设置信号掩码，表示该进程暂不接收某些信号 sigset_t new_mask, old_mask; // 初始化新信号集，只包含 SIGINT sigemptyset(\u0026new_mask); sigaddset(\u0026new_mask, SIGINT); // 设置新的信号屏蔽字，阻塞 SIGINT 信号 sigprocmask(SIG_BLOCK, \u0026new_mask, \u0026old_mask); 解除信号屏蔽 sigprocmask(SIG_UNBLOCK, \u0026new_mask, \u0026old_mask); ","date":"2026-11-09","heading":"阻塞","objectID":"/posts/csapp-chapter-6/:1:2","tags":["CSAPP"],"title":"深入理解计算机系统 第六章","uri":"/posts/csapp-chapter-6/#阻塞-1"},{"categories":["学习"],"collections":["CSAPP学习笔记"],"content":"处理 进程接收到信号后，调用对应的信号处理函数进行处理，如果没有注册则会调用默认的处理函数，否则调用用户注册的函数 注册信号处理函数一般使用 sigaction 函数 函数原型 int sigaction(int signum, const struct sigaction *_Nullable restrict act, struct sigaction *_Nullable restrict oldact); 其中： signum：表示需要注册函数的信号码（不可以是 SIGKILL 或 SIGSTOP，不能为这两个信号注册函数） act：新的信号处理指针，可为 NULL，表示不修改 oldact：保存旧的信号处理指针，可为 NULL，表示不保存 两个信号处理指针都是 sigaction 结构体指针 struct sigaction { void (*sa_handler)(int); void (*sa_sigaction)(int, siginfo_t *, void *); sigset_t sa_mask; int sa_flags; void (*sa_restorer)(void); }; 其中 sa_handler 和 sa_sigaction 是二选一 ","date":"2026-11-09","heading":"处理","objectID":"/posts/csapp-chapter-6/:1:3","tags":["CSAPP"],"title":"深入理解计算机系统 第六章","uri":"/posts/csapp-chapter-6/#处理"},{"categories":["学习"],"collections":["CSAPP学习笔记"],"content":"常见信号 SIGINT SIGKILL SIGSTOP SIGTSTP SIGCHLD SIGCONT Terminated Terminated Stopped Stopped Ignore Continue 重点在SIGCHLD信号，在子进程终止，暂停和继续时，父进程都会收到SIGCHLD信号，一般我们通过waitpid方法获得子进程相关信息进行收尸处理 信号的一大特点是：信号不排队，也没有引用计数 这也就意味着，当多个子进程终止时，父进程只会收到一个SIGCHLD信号，因此，在为子进程收尸时，我们会使用循环保证处理所有需要的子进程 ","date":"2026-11-09","heading":"常见信号","objectID":"/posts/csapp-chapter-6/:2:0","tags":["CSAPP"],"title":"深入理解计算机系统 第六章","uri":"/posts/csapp-chapter-6/#常见信号"},{"categories":null,"collections":null,"content":"电子科技大学软件工程专业大一学生，关注计算机系统、操作系统与逆向工程。","date":"2026-11-09","objectID":"/about/","tags":null,"title":"关于我","uri":"/about/"},{"categories":null,"collections":null,"content":" 电子科技大学 软件工程 从问题出发，通过阅读、实验和复盘理解计算机系统如何工作。 这里保存学习的轨迹：留下思路，也留下暂时还没有答案的问题 01 ","date":"2026-11-09","heading":"","objectID":"/about/:0:0","tags":null,"title":"关于我","uri":"/about/#"},{"categories":null,"collections":null,"content":"Learning 01 / SYSTEMS CSAPP 从程序表示、编译到运行，建立对计算机系统的整体认识 02 / OS xv6 理解操作系统的核心机制与实现方式 03 / RESEARCH Reversing 探索程序、二进制与底层运行机制之间的联系 02 ","date":"2026-11-09","heading":"Learning","objectID":"/about/:1:0","tags":null,"title":"关于我","uri":"/about/#about-focus-title"},{"categories":null,"collections":null,"content":"Education 现在 电子科技大学 软件工程 本科在读 ↗ 此前 内江六中 高中 学校官网 ↗ 03 ","date":"2026-11-09","heading":"Education","objectID":"/about/:2:0","tags":null,"title":"关于我","uri":"/about/#about-education-title"},{"categories":null,"collections":null,"content":"Goal 这里主要整理计算机系统、编程实践和学习中遇到的问题。 文章从问题与验证过程开始，逐步补充结论；仍在学习的内容，也保留它原本的阶段性 04 ","date":"2026-11-09","heading":"Goal","objectID":"/about/:3:0","tags":null,"title":"关于我","uri":"/about/#about-blog-title"},{"categories":null,"collections":null,"content":"Contact 一起聊聊技术 交个朋友吧 QQ QQ：337809631 GitHub ","date":"2026-11-09","heading":"Contact","objectID":"/about/:4:0","tags":null,"title":"关于我","uri":"/about/#about-contact-title"}]