Skip to content

Store exact element count for unsafe-model array new[] and delete[] - #703

Open
perfloop-agent wants to merge 1 commit into
Cpp2Rust:masterfrom
perfloop-oss:perfloop-pr-open-ay0zktnvwn
Open

perfloop-agent wants to merge 1 commit into
Cpp2Rust:masterfrom
perfloop-oss:perfloop-pr-open-ay0zktnvwn

Conversation

@perfloop-agent

Copy link
Copy Markdown
Contributor

In --model=unsafe, translating C++ delete[] infers the array length from malloc_usable_size(p) / sizeof(T) instead of the allocated element count. Because allocators round up to size classes and Box::leak on an empty Box<[T]> returns a non-null dangling sentinel, delete[] runs destructors on uninitialized tail slots, passes a mismatched slice Layout to Box::from_raw, and segfaults on new T[0] / delete[]. For a 4-byte struct S with a destructor, new S[1]; delete[] p; runs 6 destructors instead of 1 on glibc, and new int[0]; delete[] p; crashes with SIGSEGV.

libcc2rs/src/alloc.rs adds alloc_array_unsafe, alloc_array_from_unsafe, array_len_unsafe, and dealloc_array_unsafe to store the exact element count at the allocation base in an alignment-padded header preceding the payload pointer (including zero-length allocations, so new T[0] returns a valid distinct non-null pointer) and free that exact layout after dropping len elements in reverse order. Converter emits these helpers for unsafe-model raw array new[]/delete[] while keeping std::unique_ptr<T[]> construction and reset() on leaked Box<[T]>.

This fixes paired new[]/delete[] allocations produced by the unsafe model; calling delete[] on an unheaded pointer (such as from malloc or C FFI) remains unsupported.

Generated output changes only at unsafe-model raw array new[]/delete[] sites (25 regenerated out/unsafe/*.rs expectations; 0 existing out/refcount/*.rs changes). The new tests/unit/delete_array_exact_len.cpp fails on base in unsafe output and passes in both models with this change; scoped Release/Debug lit runs (51/51 each), libcc2rs (86/86) and libcc2rs-macros (24/24) tests, formatting, and clippy pass.

cc @nunoplopes @lucic71

Implementation and testing details
  • Allocator layout (libcc2rs/src/alloc.rs): allocates a single block of size max(size_of::<usize>(), align_of::<T>()) + len * size_of::<T>() with alignment max(align_of::<usize>(), align_of::<T>()), writes len at base.cast::<usize>(), and returns base.add(header_size). array_len_unsafe and dealloc_array_unsafe recover the header by subtracting the full header size; ArrayInitGuard and DeallocGuard handle panic unwinding. Includes 6 new unit tests covering reverse drop order, null deallocation, distinct non-null zero-length pointers, panic cleanup during initialization, alloc_array_from_unsafe, over-aligned types, and ZST Drop layouts.
  • Converter (cpp2rust/converter/converter.h, cpp2rust/converter/converter.cpp): updates VisitCXXNewExpr, VisitCXXDeleteExpr, and EmitDeallocation to emit the new helpers in unsafe mode and propagates array_new_as_box_ across value-forwarding expressions into std::unique_ptr<T[]> constructors and reset().
  • Tests (tests/unit/delete_array_exact_len.cpp and tests/unit/out/{refcount,unsafe}/delete_array_exact_len.rs): covers small non-bucket-aligned structs, zero-length arrays, null/const/2D delete[], Rust Drop fields, and std::unique_ptr<T[]> forwarding forms (emplace_back, std::pair, std::move, std::forward, reference casts, compound literals, conditionals, and nested raw new[]). Regenerated 25 existing out/unsafe/*.rs expectations (15 in tests/unit, 9 in tests/ub, 1 in tests/std).
  • Additional checks: cargo fmt --check, cargo clippy --all-targets -- -D warnings, clang-format-23, and full Release lit (670/704 passed, 32 expected failures; unit/socket_ip_addrlen.c and unit/socket_recvfrom_name.c unvalidated here and left to CI).

Case and evidence


Made by Perfloop. Human sponsor: Tomás Senart.

Signed-off-by: Perfloop Agent <agent@perfloop.ai>
targs[0].getAsType()->isArrayType();
};

auto get_unique_ptr_array_ptr_arg_idx = [&]() -> std::optional<size_t> {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is not ok. It checks model != kUnsafe and hardcodes the name of the unique_ptr::reset method

We should stop embedding rule-specific information in the converter

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.

2 participants