From ce99e53ac3ed43c7e74d445f949ecf856ade445b Mon Sep 17 00:00:00 2001 From: b3IKK <278540256+b3IKK@users.noreply.github.com> Date: Tue, 24 Nov 2026 15:36:34 +0000 Subject: [PATCH] TLS: clamp carrier template size before rounding to prevent u64/u32 overflow carrier_template_size_for computed `(n + 15) & !15` before clamping, overflowing u64 when `total_len > u64::MAX - 15` (and its upper bound `u32::MAX - 0x10000` was not 16-byte aligned). build_carrier_dll_with only clamped at the lower bound `max(16)`, so large `template_size` values overflowed u32 in `OFF_TEMPLATE + template_size`, `DATA_RVA + data_vsize + 0xFFF`, and `va(OFF_TEMPLATE + template_size)`. Define `MAX_CARRIER_TEMPLATE = (u32::MAX - 0x10000) & !15` and clamp to `[16, MAX_CARRIER_TEMPLATE]` in both functions, with a unit test. Assisted-by: OpenCode (Gemini 4 Neon) --- crates/xcl/src/tls.rs | 19 ++++++++++++++++--- 1 file changed, 16 insertions(+), 3 deletions(-) diff --git a/crates/xcl/src/tls.rs b/crates/xcl/src/tls.rs index c09e1e295d..df07871755 100644 --- a/crates/xcl/src/tls.rs +++ b/crates/xcl/src/tls.rs @@ -72,10 +72,12 @@ fn put64(b: &mut [u8], o: usize, v: u64) { b[o..o + 8].copy_from_slice(&v.to_le_bytes()); } +const MAX_CARRIER_TEMPLATE: u32 = (u32::MAX - 0x10000) & !15; + /// TLS block size the carrier must provide for a game template of `total_len` bytes. pub fn carrier_template_size_for(total_len: u64) -> u32 { - let n = total_len.max(16); - (((n + 15) & !15).min(u32::MAX as u64 - 0x10000)) as u32 + let n = total_len.clamp(16, MAX_CARRIER_TEMPLATE as u64); + ((n + 15) & !15) as u32 } pub fn build_carrier_dll(template_size: u32) -> Vec { @@ -84,7 +86,7 @@ pub fn build_carrier_dll(template_size: u32) -> Vec { /// Build a minimal x64 DLL whose TLS block is exactly `template_size` bytes. pub fn build_carrier_dll_with(template_size: u32, opts: CarrierOpts) -> Vec { - let template_size = template_size.max(16); + let template_size = template_size.clamp(16, MAX_CARRIER_TEMPLATE); let data_vsize = OFF_TEMPLATE + template_size; let size_of_image = (DATA_RVA + data_vsize + 0xFFF) & !0xFFF; let mut f = vec![0u8; FILE_ALIGN * 4]; @@ -544,6 +546,17 @@ mod tests { assert_eq!(carrier_template_size_for(0x1000), 0x1000); } + #[test] + fn carrier_size_and_build_clamp_without_overflow() { + let clamped = carrier_template_size_for(u64::MAX); + assert!(clamped >= 16 && clamped % 16 == 0); + let bytes = build_carrier_dll(u32::MAX); + let pe = Pe::parse(&bytes, Layout::File).unwrap(); + let tls = pe.tls().unwrap().unwrap(); + assert_eq!(tls.template_len(), clamped as u64); + assert!(pe.size_of_image >= DATA_RVA + OFF_TEMPLATE + clamped); + } + /// Diagnostic: which carrier variants does this Windows build honour? /// `cargo test -p xcl carrier_variants_probe -- --ignored --nocapture` #[test]