调试理论:应用

调试理论:应用

2024 南京大学《操作系统:设计与实现》
调试理论:应用

调试理论:应用 (Again)

需求 → 设计 → 代码 → Fault → Error → Failure

  • “Technical Debt”: 每当你写出不好维护的代码,你都在给你未来的调试/需求变更挖坑

中枪了?

  • 《计算机系统基础》为了赶紧实现指令,随手写的代码
  • 《操作系统》为了快点跑程序,随便写的 klib
  • 《我读研了》为了应付老板,随便写的系统实现
2024 南京大学《操作系统:设计与实现》
调试理论:应用

调试理论:推论 (1)

需求 → 设计 → 代码 → Fault → Error → Failure

  • 写好代码:不要在写代码的时候忘记需求和设计
  • 不言自明 (Self-explanatory)
    • 能通过字面知道需求 (流程)
  • 不言自证 (Self-evident)
    • 能通过字面确认代码和需求一致

一个评判标准

  • AI 是否能正确理解/维护你的代码: toybox

Programs are meant to be read by humans and only incidentally for computers to execute. (Donald E. Knuth)

2024 南京大学《操作系统:设计与实现》
调试理论:应用

调试理论:推论 (2)

需求 → 设计 → 代码 → Fault → Error → Failure

  • 做好测试:未测代码永远是错的
    • 残酷的现实:相信自己写不对代码
    • LLM 一样经常犯 “傻” 错

Small Scope Hypothesis

If a system does not have a counterexample (i.e., an error or a bug) for a certain property within a small scope (a limited size or configuration), then it is unlikely to have a counterexample in a larger scope. (Daniel Jackson)

2024 南京大学《操作系统:设计与实现》
调试理论:应用

调试理论:推论 (3)

需求 → 设计 → 代码 → Fault → Error → Failure

  • 多写断言:把代码中的 “隐藏性质” 写出来
    • Error 暴露的越晚,调试越困难
    • 追溯导致 assert failure 的变量值 (slice) 通常可以快速定位到 bug

“There are two ways of constructing a software design: One way is to make it so simple that there are obviously no deficiencies, and the other way is to make it so complicated that there are no obvious deficiencies” (Tony Hoare)

2024 南京大学《操作系统:设计与实现》
调试理论:应用

例子:维护父亲节点的平衡树

center

// 结构约束
assert(u == u->parent ||
       u == u->parent->left ||
       u == u->parent->right);
assert(!u->left  || u->left->parent  == u);
assert(!u->right || u->right->parent == u);

// 数值约束
assert(!u->left  || u->left->val  < u->val);
assert(!u->right || u->right->val > u->val);
2024 南京大学《操作系统:设计与实现》
调试理论:应用

写很多很多断言

有些 “明显” 的断言,写起来会彻底破坏代码的可读性

assert(first(obj) <= ptr && ptr < last(obj));
*ptr = 1; // Assumes ptr is valid.
  • 但如果有这样的断言,你就不用担心数组越界了!
    • Bad practice: int elements[MaxN + 100];

一个神奇的编译选项

  • -fsanitize=address
    • Address Sanitizer; asan “动态程序分析”
2024 南京大学《操作系统:设计与实现》