assert(nest == 1);
assert(u->prev->next == u);
if (holding(&lk)) panic();
#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"); } }
int foo() { // 一段连续内存;位于局部变量和返回地址之前 u32 canary = SOME_VALUE; ... // 实际函数 canary ^= SOME_VALUE; // 如果程序被攻击或出错 // canary 就不会归零了 assert(canary == 0); return ret; }
0xcccccccc
0xcdcdcdcd
0xfdfdfdfd
0xdddddddd
for i in [0xcc, 0xcd, 0xdd, 0xfd]: print((bytes([i]) * 80).decode('gbk'))
int spin_cnt = 0; while (xchg(&lk, ) == ) { if (spin_cnt++ > SPIN_LIMIT) { panic("Spin limit exceeded @ %s:%d\n", __FILE__, __LINE__); } }
// 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; }
// Suppose x is lock-protected ... int observe1 = x; delay(); int observe2 = x; assert(observe1 == observe2); ...
#define CHECK_INT(x, cond) \ ({ panic_on(!((x) cond), \ "int check fail: " \ #x " " #cond); \ })
#define CHECK_HEAP(ptr) \ ({ panic_on(!IN_RANGE((ptr), heap)); })
CHECK_INT(waitlist->count, >= 0);
CHECK_INT(pid, < MAX_PROCS);
CHECK_HEAP(ctx->rip); CHECK_HEAP(ctx->cr3);
CHECK_INT(count, >= 0);
CHECK_INT(count, <= 10000);