理论很美好,现实很残酷
另一种思路 (rule of thumb)
Canary (金丝雀) 对一氧化碳非常敏感
计算机系统中的 canary
#define MAGIC 0x55555555
#define BOTTOM (STK_SZ / sizeof(u32) - 1)
struct stack { char data[STK_SZ]; };
void canary_init(struct stack *s) {
u32 *ptr = (u32 *)s;
for (int i = 0; i < CANARY_SZ; i++)
ptr[BOTTOM - i] = ptr[i] = MAGIC;
}
void canary_check(struct stack *s) {
u32 *ptr = (u32 *)s;
for (int i = 0; i < CANARY_SZ; i++) {
panic_on(ptr[BOTTOM - i] != MAGIC, "underflow");
panic_on(ptr[i] != MAGIC, "overflow");
}
}
msvc 中 debug mode 的 guard/fence/canary
0xcccccccc
0xcdcdcdcd
0xfdfdfdfd
0xdddddddd
(b'\xcc' * 80).decode('gb2312')
不必大费周章记录什么上锁顺序
int count = 0;
while (xchg(&lk, LOCKED) == LOCKED) {
if (count++ > SPIN_LIMIT) {
panic("Spin limit exceeded @ %s:%d\n", __FILE__, __LINE__);
}
}
内存分配要求:已分配内存 $S = [\ell_0, r_0) \cup [\ell_1, r_1) \cup \ldots$
// allocation
for (int i = 0; (i + 1) * sizeof(u32) <= size; i++) {
panic_on(((u32 *)ptr)[i] == MAGIC, "double-allocation");
arr[i] = MAGIC;
}
// free
for (int i = 0; (i + 1) * sizeof(u32) <= alloc_size(ptr); i++) {
panic_on(((u32 *)ptr)[i] == 0, "double-free");
arr[i] = 0;
}