`object_compactor::insert_mpz` truncates large MPZ sizes in `m_cs_sz`, and object size functions lack `LeanMPZ` handling

Open
#16,895 0 comments 0 reactions 0 assignees View on GitHub

Maintainers usually reply within 1 day

Nobody has claimed this yet.

Assessment

Difficulty
4/5
Estimated time
3-5 days
Newbie friendliness
46/100
Issue type
Bug
Clarity
Clearly specified
Activity status
Active
Domain
backend

Research direction

Start with src/runtime/compact.cpp at object_compactor::insert_mpz and src/runtime/object.cpp at lean_object_byte_size and lean_object_data_byte_size; the issue includes a reproducible Lean snippet that saves a large Nat to a compacted region. Check how large LeanMPZ objects are serialized and sized. Done when sizes at and above 65536 bytes serialize without truncation and both size functions report the correct compacted object size.

Written by the indexing model from the issue text.

Description

bug
Prerequisites
  • Check that your issue is not already filed:
    https://github.com/leanprover/lean4/issues
  • Reduce the issue to a minimal, self-contained, reproducible test case.
    Avoid dependencies to Mathlib or Batteries.
  • Test your test case against the latest nightly release, for example on
    https://live.lean-lang.org/#project=lean-nightly
    (You can also use the settings there to switch to “Lean nightly”)
  • When reporting a perceived soundness bug: Does it affect lake check --paranoid?
    If in doubt, please reach out on [email protected] for responsible disclosure.
Description

When serializing a multi-precision integer (LeanMPZ, m_tag = 250) into a compacted region, object_compactor::insert_mpz (src/runtime/compact.cpp:399, 414) computes sz = sizeof(mpz_object) + data_sz and unconditionally calls lean_set_non_heap_header((lean_object*)new_o, sz, LeanMPZ, 0):

Because lean_set_non_heap_header (src/include/lean/lean.h:832–840) stores sz in the 16-bit uint16_t m_cs_sz field (as opposed to lean_set_non_heap_header_for_big, which sets m_cs_sz = 1), any valid Nat / Int literal whose compacted mpz_object plus limb array reaches sz >= 65536 ($\ge 2^{524032}$, i.e., 8,189 64-bit GMP limbs: 24 + 8189 * 8 = 65536 bytes):

  1. Triggers an assertion failure in Debug builds during .olean / CompactedRegion serialization (assert(sz < (1ull << 16)) at lean.h:834).
  2. Silently truncates m_cs_sz modulo $2^{16}$ in Release builds. In particular, when sz is a multiple of 65536 (e.g., 2^524032), m_cs_sz becomes 0 in the emitted .olean.
  3. Returns bogus or out-of-bounds object sizes in lean_object_byte_size / lean_object_data_byte_size (src/runtime/object.cpp:220–262): neither function has a case LeanMPZ: arm. When m_cs_sz wraps to a non-zero 16-bit value (sz > 65536), the compacted branch returns the truncated o->m_cs_sz; when m_cs_sz == 0 (sz % 65536 == 0), it enters the heap branch if (o->m_cs_sz == 0) and calls lean_small_object_size(o), which reads *((size_t*)o - 1) when LEAN_MIMALLOC is disabled (or returns 0 with LEAN_MIMALLOC).
Context

Discovered while auditing src/runtime/compact.cpp and src/runtime/object.cpp.

Steps to Reproduce
  1. Paste the following snippet into https://live.lean-lang.org/#project=lean-nightly (or run locally with lean --stdin):
import Lean
open Lean

#eval show IO Unit from IO.FS.withTempFile fun _ file => do
  let n : Nat := (1 : Nat) <<< 524032 -- 8189 limbs -> sz = 24 + 8189*8 = 65536
  let _ ← unsafe CompactedRegion.save file `MpzTest n #[] none false
  let bs ← IO.FS.readBinFile file
  for i in [88 : bs.size - 16] do
    if bs[i + 7]! == 250 && bs[i + 8]! == 0xfd && bs[i + 9]! == 0x1f then
      let m_cs_sz := bs[i + 4]!.toNat + (bs[i + 5]!.toNat <<< 8)
      IO.println s!"offset={i} m_tag=250 _mp_size=8189 m_cs_sz={m_cs_sz}"

Expected behavior: insert_mpz uses lean_set_non_heap_header_for_big (m_cs_sz = 1) when sz >= (1ull << 16) (without failing assert(sz < 65536) in Debug builds), and lean_object_byte_size / lean_object_data_byte_size handle compacted LeanMPZ objects by computing sizeof(mpz_object) plus limb array bytes.

Actual behavior: Release builds emit offset=104 m_tag=250 _mp_size=8189 m_cs_sz=0 (truncating 65536 to 0), and Debug builds fail assert(sz < (1ull << 16)) in lean_set_non_heap_header.

Versions
Lean (version 4.38.0-nightly-2026-11-26, x86_64-unknown-linux-gnu, commit e1228b8b45918ece1a00d68e5fc5e6a685ca59ee, Release)
Lean (version 4.36.0, x86_64-unknown-linux-gnu, commit 611c117bfaf7b7ae1cfcf246ce6fba31e8f509e9, Release)
Ubuntu 24.04.4 LTS (Linux 6.17.0-1022-azure x86_64)
Additional Information

Suggested fix:

  • In src/runtime/compact.cpp (object_compactor::insert_mpz, both #ifdef LEAN_USE_GMP and #else branches), call lean_set_non_heap_header_for_big((lean_object*)new_o, LeanMPZ, 0) when sz >= (1ull << 16).
  • In src/runtime/object.cpp (lean_object_byte_size and lean_object_data_byte_size, compacted else branch where o->m_cs_sz != 0), add case LeanMPZ: returning sizeof(mpz_object) + sizeof(mp_limb_t) * mpz_size(to_mpz(o)->m_value.m_val) (or sizeof(mpz_object) + sizeof(mpn_digit) * to_mpz(o)->m_value.m_size when !LEAN_USE_GMP).
fix.patch
diff --git a/src/runtime/compact.cpp b/src/runtime/compact.cpp
index ed68cbb1..5089262f 100644
--- a/src/runtime/compact.cpp
+++ b/src/runtime/compact.cpp
@@ -396,7 +396,10 @@ object_offset object_compactor::insert_mpz(object * o) {
     size_t sz = lean_usize_add_checked(sizeof(mpz_object), data_sz);
     mpz_object * new_o = (mpz_object *)alloc(sz);
     memcpy((void*)new_o, to_mpz(o), sizeof(mpz_object));
-    lean_set_non_heap_header((lean_object*)new_o, sz, LeanMPZ, 0);
+    if (sz < (1ull << 16))
+        lean_set_non_heap_header((lean_object*)new_o, sz, LeanMPZ, 0);
+    else
+        lean_set_non_heap_header_for_big((lean_object*)new_o, LeanMPZ, 0);
     __mpz_struct & m = new_o->m_value.m_val[0];
     // we assume the limb array is the only indirection in an `__mpz_struct` and everything else can be bitcopied
     void * data = reinterpret_cast<char*>(new_o) + sizeof(mpz_object);
@@ -414,7 +417,10 @@ object_offset object_compactor::insert_mpz(object * o) {
     new_o->m_header = to_mpz(o)->m_header;
     new_o->m_value.m_sign = to_mpz(o)->m_value.m_sign;
     new_o->m_value.m_size = to_mpz(o)->m_value.m_size;
-    lean_set_non_heap_header((lean_object*)new_o, sz, LeanMPZ, 0);
+    if (sz < (1ull << 16))
+        lean_set_non_heap_header((lean_object*)new_o, sz, LeanMPZ, 0);
+    else
+        lean_set_non_heap_header_for_big((lean_object*)new_o, LeanMPZ, 0);
     void * data = reinterpret_cast<char*>(new_o) + sizeof(mpz_object);
     memcpy(data, to_mpz(o)->m_value.m_digits, data_sz);
     new_o->m_value.m_digits = reinterpret_cast<mpn_digit *>(reinterpret_cast<char *>(data) - reinterpret_cast<char *>(m_begin) + reinterpret_cast<ptrdiff_t>(m_base_addr));
diff --git a/src/runtime/object.cpp b/src/runtime/object.cpp
index 780a9c66..fbc915de 100644
--- a/src/runtime/object.cpp
+++ b/src/runtime/object.cpp
@@ -235,6 +235,11 @@ extern "C" LEAN_EXPORT size_t lean_object_byte_size(lean_object * o) {
         case LeanScalarArray: return lean_sarray_byte_size(o);
         case LeanString:      return lean_string_byte_size(o);
         case LeanClosure:     return lean_closure_byte_size(o);
+#ifdef LEAN_USE_GMP
+        case LeanMPZ:         return sizeof(mpz_object) + sizeof(mp_limb_t) * mpz_size(to_mpz(o)->m_value.m_val);
+#else
+        case LeanMPZ:         return sizeof(mpz_object) + sizeof(mpn_digit) * to_mpz(o)->m_value.m_size;
+#endif
         default:              return o->m_cs_sz;
         }
     }
@@ -259,6 +264,11 @@ extern "C" LEAN_EXPORT size_t lean_object_data_byte_size(lean_object * o) {
         case LeanScalarArray: return lean_sarray_data_byte_size(o);
         case LeanString:      return lean_string_data_byte_size(o);
         case LeanClosure:     return lean_closure_data_byte_size(o);
+#ifdef LEAN_USE_GMP
+        case LeanMPZ:         return sizeof(mpz_object) + sizeof(mp_limb_t) * mpz_size(to_mpz(o)->m_value.m_val);
+#else
+        case LeanMPZ:         return sizeof(mpz_object) + sizeof(mpn_digit) * to_mpz(o)->m_value.m_size;
+#endif
         default:              return o->m_cs_sz;
         }
     }
Dominant language
Lean
Stars
10.5k
Forks
1.2k
Avg merge
19h 36m
Merged PRs (30d)
323

Getting set up

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

More from leanprover/lean4

All issues in leanprover/lean4

Similar issues

More Backend & API Design issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.