fix: report truncated `.olean` files as errors

This PR makes loading a truncated `.olean` file fail with an error message instead of reading beyond the end of the file.

Note that Lean ultimately still has to trust in the overall integrity of `.olean` files.

`lean_compacted_region_read` now checks the section framing against the file size: `data_size`, the closure offset table, and the library relocation table in `read_lib_table_from_buffer` must lie within the file, and each closure offset must lie within the compacted data.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
diff --git a/src/library/module.cpp b/src/library/module.cpp
index e1e3b75..6f1362b 100644
--- a/src/library/module.cpp
+++ b/src/library/module.cpp
@@ -229,24 +229,29 @@
 }
 
 
+// Copies `n` bytes at `p` to `dst` and advances `p`, checking that they lie before `end`.
+static void read_bytes(char const * & p, char const * end, void * dst, size_t n) {
+    if (static_cast<size_t>(end - p) < n)
+        throw exception("unexpected end of file");
+    memcpy(dst, p, n);
+    p += n;
+}
+
 // Parse the closure fn-pointer relocation table from `p` (pointing at `num_libs` in the loaded
-// file) into sorted `(saved_base, delta)` pairs. `memcpy` keeps the loads alignment-safe.
-static std::vector<std::pair<size_t, ptrdiff_t>> read_lib_table_from_buffer(char const * p) {
+// file, which ends at `end`) into sorted `(saved_base, delta)` pairs.
+static std::vector<std::pair<size_t, ptrdiff_t>> read_lib_table_from_buffer(char const * p, char const * end) {
     std::vector<std::pair<size_t, ptrdiff_t>> relocs;
     uint32_t n;
-    memcpy(&n, p, sizeof(n));
-    p += sizeof(n);
+    read_bytes(p, end, &n, sizeof(n));
     if (n == 0) return relocs;
     std::vector<lib_info> current_libs = get_loaded_libs();
     for (uint32_t i = 0; i < n; i++) {
         size_t old_base;
-        memcpy(&old_base, p, sizeof(old_base));
-        p += sizeof(old_base);
+        read_bytes(p, end, &old_base, sizeof(old_base));
         uint32_t len;
-        memcpy(&len, p, sizeof(len));
-        p += sizeof(len);
-        std::string id(p, len);
-        p += len;
+        read_bytes(p, end, &len, sizeof(len));
+        std::string id(len, '\0');
+        read_bytes(p, end, &id[0], len);
         size_t new_base = 0;
         bool found = false;
         for (lib_info const & lib : current_libs) {
@@ -575,23 +580,31 @@
 
         std::vector<std::pair<size_t, ptrdiff_t>> lib_relocs;
         std::vector<size_t> closure_offsets;
+        // The checks below only validate the section framing against the file size, which detects
+        // truncated files. The compacted data itself is trusted.
+        char const * p = buffer + sizeof(olean_header);
+        char const * end = buffer + size;
         size_t data_size;
-        memcpy(&data_size, buffer + sizeof(olean_header), sizeof(data_size));
+        read_bytes(p, end, &data_size, sizeof(data_size));
+        if (data_size > static_cast<size_t>(end - p))
+            throw exception("unexpected end of file");
         size_t data_section_off = sizeof(olean_header) + sizeof(size_t);
         size_t data_section_sz = data_size;
-        char const * p = buffer + data_section_off + data_size;
+        p += data_size;
         uint32_t num_closure_offsets;
-        memcpy(&num_closure_offsets, p, sizeof(num_closure_offsets));
-        p += sizeof(num_closure_offsets);
+        read_bytes(p, end, &num_closure_offsets, sizeof(num_closure_offsets));
         if (num_closure_offsets > 0) {
+            if (num_closure_offsets > static_cast<size_t>(end - p) / sizeof(uint64_t))
+                throw exception("unexpected end of file");
             closure_offsets.reserve(num_closure_offsets);
             for (uint32_t i = 0; i < num_closure_offsets; i++) {
                 uint64_t off;
-                memcpy(&off, p, sizeof(off));
-                p += sizeof(off);
+                read_bytes(p, end, &off, sizeof(off));
+                if (data_size < sizeof(void*) || off > data_size - sizeof(void*))
+                    throw exception("closure offset out of bounds");
                 closure_offsets.push_back(static_cast<size_t>(off));
             }
-            lib_relocs = read_lib_table_from_buffer(p);
+            lib_relocs = read_lib_table_from_buffer(p, end);
         }
 
         region_reader reader(
diff --git a/tests/compile/olean_truncated.lean b/tests/compile/olean_truncated.lean
new file mode 100644
index 0000000..4b2490b
--- /dev/null
+++ b/tests/compile/olean_truncated.lean
@@ -0,0 +1,55 @@
+import Lean.CompactedRegion
+
+open Lean
+
+/-!
+Tests that `CompactedRegion.read` reports an error for a truncated file and for a closure offset
+that points outside the compacted data.
+-/
+
+/-- `sizeof(olean_header)` in `src/library/module.cpp`. -/
+def headerSize : Nat := 88
+
+def getUInt64LE (bs : ByteArray) (pos : Nat) : Nat := Id.run do
+  let mut r := 0
+  for i in [0:8] do
+    r := r + bs[pos + i]!.toNat <<< (8 * i)
+  return r
+
+def setUInt64LE (bs : ByteArray) (pos : Nat) (v : Nat) : ByteArray := Id.run do
+  let mut bs := bs
+  for i in [0:8] do
+    bs := bs.set! (pos + i) (v >>> (8 * i)).toUInt8
+  return bs
+
+unsafe def tryRead (file : System.FilePath) : IO (Option String) := do
+  try
+    let _ ← CompactedRegion.read (α := Nat → String) file #[]
+    return none
+  catch e =>
+    return some (toString e)
+
+unsafe def main : IO Unit := do
+  let file : System.FilePath := "./_tmp_olean_truncated.olean"
+  let captured := "hello"
+  let f : Nat → String := fun n => s!"{captured} {n}"
+  let _ ← CompactedRegion.save file `test f #[] none true
+  let bytes ← IO.FS.readBinFile file
+
+  let mut accepted := #[]
+  for len in [0:bytes.size] do
+    IO.FS.writeBinFile file (bytes.extract 0 len)
+    if (← tryRead file).isNone then
+      accepted := accepted.push len
+  IO.println s!"truncated lengths accepted: {accepted}"
+
+  let dataSize := getUInt64LE bytes headerSize
+  let firstOffsetPos := headerSize + 8 + dataSize + 4
+  for (descr, off) in [("last word", dataSize - 8), ("straddles end", dataSize - 4),
+      ("at end", dataSize), ("max", 2^64 - 1)] do
+    IO.FS.writeBinFile file (setUInt64LE bytes firstOffsetPos off)
+    IO.println s!"closure offset {descr}: {← tryRead file}"
+
+  IO.FS.writeBinFile file bytes
+  IO.println s!"intact: {← tryRead file}"
+  IO.FS.removeFile file
diff --git a/tests/compile/olean_truncated.lean.no_interpret_test b/tests/compile/olean_truncated.lean.no_interpret_test
new file mode 100644
index 0000000..e69de29
--- /dev/null
+++ b/tests/compile/olean_truncated.lean.no_interpret_test
diff --git a/tests/compile/olean_truncated.lean.out.expected b/tests/compile/olean_truncated.lean.out.expected
new file mode 100644
index 0000000..ef6ee28
--- /dev/null
+++ b/tests/compile/olean_truncated.lean.out.expected
@@ -0,0 +1,6 @@
+truncated lengths accepted: #[]
+closure offset last word: none
+closure offset straddles end: (some (failed to read './_tmp_olean_truncated.olean': closure offset out of bounds))
+closure offset at end: (some (failed to read './_tmp_olean_truncated.olean': closure offset out of bounds))
+closure offset max: (some (failed to read './_tmp_olean_truncated.olean': closure offset out of bounds))
+intact: none