code wiki / _hdl_build / nx_recycler_intguard.nx
nx_recycler_intguard.nx source
↩ module page · 32 lines · 1738 B
1// nx_recycler_intguard.nx -- a checked-arithmetic primitive RECYCLED FROM the integer-overflow CVE class (the real
2// intake artifact is knowledge/fetched/recyc_intoverflow.raw; the recycler's assess engine scored this NEEDS-GATE,
3// cross-linked to our own LM-005 integer landmine). Nishi is integer-only (i64) -> overflow IS our surface: sizes,
4// counts, money-in-cents (the inventory/estate engines) and seg-store offsets can silently wrap. These detect i64
5// overflow WITHOUT needing huge literals (sign-rule for add, division-check for mul), so load-bearing arithmetic can
6// fail LOUD instead of wrapping to garbage. The 4th recycler CONVERT (after bounds/sovereignty/ubscan). ORIGINAL
7import "nx_syscalls.nx"
8
9// 1 iff a+b overflows i64. Same-sign operands whose sum flips sign = overflow (no MAX/MIN literal needed).
10func ig_add_ovf(a: i64, b: i64) -> i64 {
11 let s: i64 = a + b
12 if a >= 0 { if b >= 0 { if s < 0 { return 1 } return 0 } }
13 if a < 0 { if b < 0 { if s >= 0 { return 1 } return 0 } }
14 return 0 // opposite signs can never overflow
15}
16// 1 iff a*b overflows i64. Division-check: if (a*b)/a != b the product wrapped.
17func ig_mul_ovf(a: i64, b: i64) -> i64 {
18 if a == 0 { return 0 }
19 if b == 0 { return 0 }
20 let p: i64 = a * b
21 if p / a != b { return 1 }
22 return 0
23}
24// checked add: returns a+b, writes 1 to ok[0] if SAFE, 0 if it overflowed (the caller must check before trusting it).
25func ig_add_checked(a: i64, b: i64, ok: *i64) -> i64 {
26 if ig_add_ovf(a, b) == 1 { ok[0] = 0 } else { ok[0] = 1 }
27 return a + b
28}
29func ig_mul_checked(a: i64, b: i64, ok: *i64) -> i64 {
30 if ig_mul_ovf(a, b) == 1 { ok[0] = 0 } else { ok[0] = 1 }
31 return a * b
32}