Skip to content

Remove the remaining libc allocation - #135

Open
cruzzil wants to merge 1 commit into
mainfrom
remove-libc-allocation
Open

cruzzil wants to merge 1 commit into
mainfrom
remove-libc-allocation

Conversation

@cruzzil

@cruzzil cruzzil commented Aug 23, 2026

Copy link
Copy Markdown
Owner

Closes the Remove use a malloc and free TODO. No libc malloc/calloc/realloc/free
is left in the library — the only survivors are five lines in cfileio's #[cfg(test)]
module, where the test deliberately plays the part of a C caller supplying its own
allocator through fits_create_memfile, and so must free with the same one.

The ladder

Layout is the right primitive, but hand-rolling it at thirty call sites is a step
backwards: Vec<T> and Box<[T]> are Layout::array::<T>(n) with the bookkeeping
already correct. It ends up used in exactly three places. The reasoning is documented at
the top of the new src/helpers/raw_owned.rs, and TRANSPILING.md points at it so the
next transpile doesn't have to re-derive it.

when mechanism
A the block never escapes Vec<T> / Box<[T]>, RAII
B a raw pointer must be visible, but we can own the storage keep the Vec, take as_mut_ptr() at the point of use
C the pointer is the handle and the length is recoverable Box<[T]> + slice_from_raw_parts_mut
D the length is not recoverable at the free site the registry

What changed

  • ffiter_internal owns its per-column work arrays in an AlignedBytes/Vec arena
    instead of callocing seventeen of them. cols[jj].array still receives a raw pointer,
    so no ABI change, but the buffers are released on every path (the C leaked them on its
    early returns) and the sixteen allocations that stored their result without a null check
    are now fallible and report MEMORY_ALLOCATION.
  • The ALLOCATIONS map moved behind helpers::raw_owned. It records the element size
    and alignment as well as the length and capacity, and there is no "assume the length"
    fallback any more: an unregistered pointer is reported in debug builds and leaked rather
    than freed on a guessed Layout.
  • The expression engine's node buffers come from the Rust allocator. NodeValue::Buffer
    carries an Owned describing how the block is released — None for a column node's
    borrowed view into varData, Block(Layout) for a numeric row buffer, BlockAndText
    for the row-pointer array plus the character block behind it. So free_buffer hands back
    the right Layout, releases both of Allocate_Ptrs' allocations together (four call
    sites no longer have to free the character block by hand first), and structurally cannot
    free a buffer a column node only borrows — an invariant that was previously maintained by
    every caller remembering to write if node.is_computed(). The FREE! macro is gone.

FITSfile's filename, headstart and tableptr are untouched. They are public C-ABI
fields; their types and the struct layout are unchanged. Only how the block is reclaimed
moved, from an open-coded remove()-or-guess to free_registered.

Bugs found on the way

None of these were what I went looking for.

  1. Compressed files were never recognised. Two independent defects in the same path.
    The two-byte magic numbers for GZIP, PACK, LZW and LZH were transpiled from the C's
    octal escapes ("\037\213") as if they were decimal, so file_is_compressed and
    mem_compress_open rejected every .gz, .Z and .bz2 file — the whole compress://
    driver was unreachable. And file_is_compressed read those two bytes with a bare
    read(), which is allowed to come back short, and treated a short read as "not
    compressed". Miri caught the second one.
  2. Cross-allocator free. mem_createmem allocates the memory-file buffer as a Vec,
    but stdin2mem, both compressed-open paths and the decompression grow callback resized
    it with raw libc::realloc — exactly what owned_realloc's own doc comment says must
    not happen. They route through owned_realloc now, and stdin2mem publishes the new
    address as it grows instead of leaving a stale one behind for its own error path to free.
  3. fits_read_wcstab released an nelem-element f64 array as if it held ndim
    elements — ndim is the number of axes, not the element count.
  4. FITSfile::drop freed the six tile* pointers that TILE_STRUCTS owns. This is
    the double free that had test_copy_within_same_file #[ignore]d; it is un-ignored and
    passes, including under miri.

New coverage: two tests open a compressed file end to end through the compress:// driver,
one of them sized so the driver's buffer estimate overshoots and the trim path runs — that
is the regression test for the cross-allocator free.

Verification

cargo test green across all 35 binaries. 32-bit i686 check clean. No new clippy
warnings (the 82 pre-existing doc-indent ones are unchanged). rustdoc and check_docs.py
clean. Miri ran in three scoped passes over everything touched — 105, 218 and 174 tests —
all clean: no UB, no leaks, no unsupported operations. One new test is
#[cfg_attr(miri, ignore)] because the bzip2 path goes through fdopen, the gap TODO.md
already documents.

The full ~5h miri suite has not been run; TODO.md asks for one after changes to
aliasing-sensitive code, so that is worth doing before release.

No libc malloc/calloc/realloc/free is left in the library. What replaces it
depends on how far the pointer has to travel, and that ladder is documented at
the top of the new src/helpers/raw_owned.rs.

- ffiter_internal owns its per-column work arrays in an AlignedBytes/Vec arena
  instead of calloc'ing seventeen of them. cols[jj].array still receives a raw
  pointer, so no ABI change, but the buffers are released on every path and the
  sixteen allocations that stored their result unchecked now report
  MEMORY_ALLOCATION.
- The ALLOCATIONS map moved behind helpers::raw_owned. It records the element
  size and alignment as well as the length and capacity, and there is no
  "assume the length" fallback: an unregistered pointer is reported in debug
  builds and leaked rather than freed on a guessed Layout.
- The expression engine's node buffers come from the Rust allocator.
  NodeValue::Buffer carries an Owned saying how the block is released, so
  free_buffer hands back the right Layout, releases both of Allocate_Ptrs'
  allocations together, and cannot free a buffer a column node only borrows.
  The FREE! macro is gone and the Bits column arrays are Vecs on DataInfo.

Fixes found on the way:

- Compressed files were never recognised. The two-byte magic numbers for GZIP,
  PACK, LZW and LZH were transpiled from the C's octal escapes as if they were
  decimal, so file_is_compressed and mem_compress_open rejected every .gz, .Z
  and .bz2 file; and file_is_compressed read those bytes with a bare read(),
  treating a short read as "not compressed".
- Memory-file buffers from mem_createmem (a Vec) were resized with the C
  realloc by stdin2mem, both compressed-open paths and the decompression grow
  callback. They route through owned_realloc now, and stdin2mem publishes the
  new address as it grows rather than leaving a stale one for its own error
  path to free.
- Two frees on a guessed layout: fits_read_wcstab released an nelem-element f64
  array as if it held ndim elements, and FITSfile::drop freed the six tile*
  pointers that TILE_STRUCTS owns. The latter is the double free that had
  test_copy_within_same_file ignored; it is un-ignored and passes.

FITSfile's filename, headstart and tableptr are untouched: they are public
C-ABI fields and keep their types and the struct layout.

Verified with cargo test (35 binaries), the i686 check, clippy, rustdoc, and
three scoped miri runs over every module touched -- 105, 218 and 174 tests, all
clean. One new test is cfg_attr(miri, ignore) because the bzip2 path goes
through fdopen.
@codecov

codecov Bot commented Aug 23, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 82.78689% with 84 lines in your changes missing coverage. Please review.
✅ Project coverage is 74.72%. Comparing base (bef6b47) to head (48c8812).
⚠️ Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
src/drvrmem.rs 83.92% 18 Missing ⚠️
src/helpers/raw_owned.rs 85.18% 12 Missing ⚠️
src/eval_y.rs 91.22% 10 Missing ⚠️
src/putcol.rs 76.74% 10 Missing ⚠️
src/eval_f.rs 71.42% 8 Missing ⚠️
src/eval_defs.rs 90.16% 6 Missing ⚠️
src/zcompress.rs 0.00% 5 Missing ⚠️
src/drvrfile.rs 42.85% 4 Missing ⚠️
src/fitscore.rs 72.72% 3 Missing ⚠️
src/group.rs 40.00% 3 Missing ⚠️
... and 4 more
Additional details and impacted files
@@            Coverage Diff             @@
##             main     #135      +/-   ##
==========================================
+ Coverage   74.51%   74.72%   +0.20%     
==========================================
  Files          96       97       +1     
  Lines      186951   186927      -24     
==========================================
+ Hits       139306   139676     +370     
+ Misses      47645    47251     -394     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant