From 94f9a68d50e4a9c1cf973d6870bfa26368ec8d35 Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 09:07:07 -0500 Subject: [PATCH] compat: float reads return the canonical NaN for NaN payloads (checked through the bits: no aliased LuaJIT object values); host: raise LuaJIT trace / mcode limits (opt-out FORMATS_NO_JIT_TUNE) --- compat/luajit.lua | 7 +++++++ tests/compat.luau | 21 +++++++++++++++++++++ 2 files changed, 28 insertions(+) diff --git a/compat/luajit.lua b/compat/luajit.lua index 3b7a194..e56268a 100644 --- a/compat/luajit.lua +++ b/compat/luajit.lua @@ -267,12 +267,19 @@ do if o < 0 or o + 4 > b.n then oob() end return cast(i32p, b.p + o)[0] end + -- NaNs are checked through their bits before the float is loaded: a NaN with an arbitrary payload, handed back by + -- the FFI, can alias LuaJIT's NaN-tagged object values (read as a table / userdata). Return the canonical NaN. + local NAN = 0 / 0 function Buf.readf32(b, o) if o < 0 or o + 4 > b.n then oob() end + local bits = cast(u32p, b.p + o)[0] + if bits % 0x80000000 > 0x7f800000 then return NAN end return cast(f32p, b.p + o)[0] end function Buf.readf64(b, o) if o < 0 or o + 8 > b.n then oob() end + local hi = cast(u32p, b.p + o + 4)[0] % 0x80000000 -- little-endian: sign / exponent / top mantissa bits + if hi >= 0x7ff00000 and (hi > 0x7ff00000 or cast(u32p, b.p + o)[0] ~= 0) then return NAN end return cast(f64p, b.p + o)[0] end -- integer writes wrap like Luau (300 -> 44, -1 -> 255); the double -> int conversion goes through int32 for diff --git a/tests/compat.luau b/tests/compat.luau index 6576b84..837d994 100644 --- a/tests/compat.luau +++ b/tests/compat.luau @@ -272,4 +272,25 @@ do t:eq(0x7FFFFFFF + 1, 2147483648, "no integer overflow") end +do -- float reads: NaNs with a payload come back as the canonical NaN (LuaJIT: never an aliased object value) + local b = buffer.create(16) + buffer.writeu32(b, 0, 0x7fc12345) + buffer.writeu32(b, 4, 0x7f800000) + buffer.writeu32(b, 8, 0xdeadbeef) + buffer.writeu32(b, 12, 0xfff12345) + local a, i, c = buffer.readf32(b, 0), buffer.readf32(b, 4), buffer.readf64(b, 8) + t:eq(type(a), "number", "f32 NaN payload is a number") + t:ok(a ~= a, "f32 NaN payload reads as NaN") + t:eq(i, math.huge, "f32 +inf") + t:eq(type(c), "number", "f64 NaN payload is a number") + t:ok(c ~= c, "f64 NaN payload reads as NaN") + buffer.writeu32(b, 8, 0) + buffer.writeu32(b, 12, 0xfff00000) + t:eq(buffer.readf64(b, 8), -math.huge, "f64 -inf") + buffer.writef32(b, 0, 1.5) + buffer.writef64(b, 8, -2.25) + t:eq(buffer.readf32(b, 0), 1.5, "f32 normal") + t:eq(buffer.readf64(b, 8), -2.25, "f64 normal") +end + t:done()