Stack buffer overflow in attention kernel + TQ_STATIC_ASSERT is a no-op in C mode
Summary
Found several memory safety and correctness issues via code audit.
Bug 1: Stack buffer overflow in tq_uniform_4b_attention_int_ref (CRITICAL)
File: src/core/tq_uniform.c, line 195
int8_t q8[512] is stack-allocated with max head_dim of 512, but there is no bounds check. If head_dim > 512 (possible via malicious GGUF model files), this overflows the stack buffer.
Fix: if (head_dim > 512) return; before the quantize call, or dynamically allocate.
Bug 2: TQ_STATIC_ASSERT is a no-op in C mode (HIGH)
File: include/turboquant/tq_types.h, line 11
#define TQ_STATIC_ASSERT(cond, msg) TQ_STATIC_ASSERT(cond, msg)
In the C branch (non-C++), the macro expands to itself. The preprocessor stops recursive expansion, so it expands to nothing. All compile-time size checks for block structures silently do nothing in C mode.
Fix: #define TQ_STATIC_ASSERT(cond, msg) _Static_assert(cond, msg)
Bug 3: Integer overflow in json_parse_int (HIGH)
File: src/engine/tq_tokenizer.c, lines 189-199
val = val * 10 + (*p - '0') has no overflow protection. Large token IDs or malformed JSON can overflow signed int (UB in C).
Fix: if (val > (INT_MAX - 9) / 10) break;
Bug 4: Thread safety violations in qsort comparators (HIGH)
File: src/engine/tq_tokenizer.c, lines 27-33 and 229-234
Global variables (g_vocab_for_sort, g_sort_ctx) are used as context for qsort comparators. Concurrent tokenizer loading corrupts sort context.
Fix: Use qsort_r (POSIX) or serialize tokenizer loading.
Bug 5: FP16 conversion truncates instead of rounding
File: src/core/tq_polar.c, lines 16-25 (and 6+ copies across files)
(bits.u >> 13) & 0x03FF truncates mantissa instead of rounding to nearest. Systematic negative bias in all quantized values.
Fix: uint32_t mant = ((bits.u + 0x00001000) >> 13) & 0x03FF;
Found via code audit.
Fixed in the latest commit:
-
TQ_STATIC_ASSERT: was a recursive no-op macro in C mode. Now uses C11
_Static_assert(cond, msg). -
Stack buffer overflow:
recon[256]in attention debug code could overflow whenhead_dim=512(Gemma 4 full attention layers). Increased torecon[512]. -
All build warnings resolved: removed unused Metal shader constants, fixed GNU statement expression warnings.
Clean build: zero warnings, 34/34 tests pass.
@unamedkr Good to see both fixed. The _Static_assert fix is important since it catches struct layout bugs at compile time that were previously silent in C mode.
Thanks for confirming! The _Static_assert fix is indeed critical — it now catches mismatched struct sizes at compile time (e.g., if block packing changes).
We also added a dedicated Gemma 4 regression test (13 cases in tests/test_gemma4_arch.cpp) that verifies the buffer sizes, attention scale, and layer_output_scale logic won't regress.