From 98012b9f2e8adaca00bc015d5534d5a1fc6f6017 Mon Sep 17 00:00:00 2001 From: Perfloop Agent Date: Thu, 3 Dec 2026 22:19:09 +0000 Subject: [PATCH] Store exact element count for unsafe-model array new/delete Signed-off-by: Perfloop Agent --- cpp2rust/converter/converter.cpp | 219 +++-- cpp2rust/converter/converter.h | 6 + libcc2rs/src/alloc.rs | 326 +++++++ .../dcl.init/out/unsafe/dcl.init.general.rs | 9 +- tests/ub/out/unsafe/int_to_ptr_dangling.rs | 8 +- tests/ub/out/unsafe/ub10.rs | 9 +- tests/ub/out/unsafe/ub14.rs | 9 +- tests/ub/out/unsafe/ub15.rs | 9 +- tests/ub/out/unsafe/ub16.rs | 9 +- tests/ub/out/unsafe/ub18.rs | 6 +- tests/ub/out/unsafe/ub19.rs | 6 +- tests/ub/out/unsafe/ub20.rs | 3 +- tests/ub/out/unsafe/ub9.rs | 9 +- tests/unit/delete_array_exact_len.cpp | 259 ++++++ .../out/refcount/delete_array_exact_len.rs | 631 +++++++++++++ tests/unit/out/unsafe/06_new_array.rs | 23 +- tests/unit/out/unsafe/cast.rs | 21 +- tests/unit/out/unsafe/default.rs | 42 +- .../unit/out/unsafe/delete_array_exact_len.rs | 843 ++++++++++++++++++ tests/unit/out/unsafe/delete_array_order.rs | 16 +- .../unsafe/immutable-deref-on-func-call.rs | 13 +- tests/unit/out/unsafe/memset.rs | 9 +- tests/unit/out/unsafe/new_alloc_array.rs | 9 +- tests/unit/out/unsafe/new_array.rs | 18 +- tests/unit/out/unsafe/new_array_var_size.rs | 18 +- tests/unit/out/unsafe/pointer_call_offset.rs | 9 +- .../unsafe/reinterpret_cast_large_array.rs | 9 +- .../out/unsafe/reinterpret_cast_new_array.rs | 9 +- tests/unit/out/unsafe/struct_default_ctor.rs | 28 +- tests/unit/out/unsafe/swap_extended.rs | 8 +- .../unit/out/unsafe/vector_with_allocator.rs | 16 +- 31 files changed, 2299 insertions(+), 310 deletions(-) create mode 100644 tests/unit/delete_array_exact_len.cpp create mode 100644 tests/unit/out/refcount/delete_array_exact_len.rs create mode 100644 tests/unit/out/unsafe/delete_array_exact_len.rs diff --git a/cpp2rust/converter/converter.cpp b/cpp2rust/converter/converter.cpp index 16b7aebe2e..50d9ccb2f0 100644 --- a/cpp2rust/converter/converter.cpp +++ b/cpp2rust/converter/converter.cpp @@ -1705,6 +1705,7 @@ static bool IsaSemiColonStmt(const clang::Stmt *stmt) { } bool Converter::Convert(clang::Stmt *stmt) { + ScopedValue clear_box(array_new_as_box_, false); PushExprKind push(*this, ExprKind::Void); bool exited_visit = false; if (stmt && @@ -1804,6 +1805,7 @@ bool Converter::VisitGotoStmt(clang::GotoStmt *stmt) { } void Converter::ConvertCondition(clang::Expr *cond) { + ScopedValue clear_box(array_new_as_box_, false); PushExprKind push(*this, ExprKind::RValue); ConvertFullExpression([&] { Convert(NormalizeToBool(cond, ctx_)); }); } @@ -2017,12 +2019,14 @@ bool Converter::Convert(clang::Expr *expr, ScopedValue pointee(new_pointee_, std::optional(to->getPointeeType())); return Convert(expr); } + ScopedValue clear_box(array_new_as_box_, false); StrCat(ConvertPointeeCast(ToString(expr), expr, to)); return false; } auto from = IgnoreTransparentStdCall(ctx_, expr)->IgnoreImplicit()->getType(); if (NeedsImplicitScalarCast(ctx_, from, to)) { + ScopedValue clear_box(array_new_as_box_, false); std::string str; { Buffer buf(*this); @@ -2355,6 +2359,8 @@ void Converter::ConvertVAArgCall(clang::CallExpr *expr) { } bool Converter::VisitCallExpr(clang::CallExpr *expr) { + ScopedValue clear_box(array_new_as_box_, + IsTransparentStdCall(ctx_, expr) && array_new_as_box_); if (IsReturnSlotCall(expr) && in_place_.expr != expr) { PushBrace block(*this); StrCat(CreatePlacementStorage( @@ -3277,6 +3283,7 @@ bool Converter::VisitImplicitCastExpr(clang::ImplicitCastExpr *expr) { break; } case clang::CastKind::CK_BitCast: { + ScopedValue clear_box(array_new_as_box_, false); PushParen paren(*this); Convert(sub_expr); ConvertCast(type); @@ -3292,6 +3299,7 @@ bool Converter::VisitImplicitCastExpr(clang::ImplicitCastExpr *expr) { type_changed = !suffix && !IsCastRedundantInRust(sub_expr, type); } if (type_changed) { + ScopedValue clear_box(array_new_as_box_, false); PushParen paren(*this); Convert(sub_expr); ConvertCast(type); @@ -3299,6 +3307,7 @@ bool Converter::VisitImplicitCastExpr(clang::ImplicitCastExpr *expr) { } else { { PushParen paren(*this, suffix); + ScopedValue clear_box(array_new_as_box_, !suffix && array_new_as_box_); Convert(sub_expr); } if (suffix) { @@ -3323,10 +3332,12 @@ bool Converter::VisitImplicitCastExpr(clang::ImplicitCastExpr *expr) { ConvertIntegralToBooleanCast(expr); break; case clang::CastKind::CK_PointerToBoolean: - case clang::CastKind::CK_MemberPointerToBoolean: + case clang::CastKind::CK_MemberPointerToBoolean: { + ScopedValue clear_box(array_new_as_box_, false); StrCat(token::kNot); ConvertEqualsNullPtr(sub_expr); break; + } case clang::CastKind::CK_NullToPointer: EmitFresh(GetDefaultAsString(type)); break; @@ -3354,10 +3365,12 @@ bool Converter::VisitImplicitCastExpr(clang::ImplicitCastExpr *expr) { break; } if (type->isEnumeralType() && !sub_expr->getType()->isEnumeralType()) { + ScopedValue clear_box(array_new_as_box_, false); ConvertIntegerToEnumeralCast(expr, sub_expr); break; } { + ScopedValue clear_box(array_new_as_box_, false); PushParen outer(*this); { // as binds tighter than binary operators. @@ -3376,6 +3389,7 @@ bool Converter::VisitExplicitCastExpr(clang::ExplicitCastExpr *expr) { auto type = expr->getTypeAsWritten(); auto *sub_expr = expr->getSubExpr(); if (type->isVoidType()) { + ScopedValue clear_box(array_new_as_box_, false); if (!sub_expr->HasSideEffects(ctx_)) { EmitFresh(isVoid() ? "" : "()"); return false; @@ -3394,6 +3408,7 @@ bool Converter::VisitExplicitCastExpr(clang::ExplicitCastExpr *expr) { !isAddrOf() && sub_expr->isLValue() && !to.isConstQualified() && sub_expr->getType().isConstQualified() && ctx_.hasSameUnqualifiedType(to, sub_expr->getType())) { + ScopedValue clear_box(array_new_as_box_, false); std::string object; { ScopedValue no_autoref(autoref_mut_, std::nullopt); @@ -3409,6 +3424,7 @@ bool Converter::VisitExplicitCastExpr(clang::ExplicitCastExpr *expr) { : nullptr; { PushParen paren(*this, suffix); + ScopedValue clear_box(array_new_as_box_, !suffix && array_new_as_box_); Convert(sub_expr); } if (suffix) { @@ -3418,6 +3434,7 @@ bool Converter::VisitExplicitCastExpr(clang::ExplicitCastExpr *expr) { } if (type->isEnumeralType() && !sub_expr->getType()->isEnumeralType()) { + ScopedValue clear_box(array_new_as_box_, false); ConvertIntegerToEnumeralCast(expr, sub_expr); return false; } @@ -3446,33 +3463,36 @@ bool Converter::VisitExplicitCastExpr(clang::ExplicitCastExpr *expr) { (expr->getCastKind() == clang::CK_NoOp && type->isRecordType())) { return Convert(sub_expr); } - if (type->isFunctionPointerType() || - sub_expr->getType()->isFunctionPointerType()) { - ConvertFunctionPointerTransmute(sub_expr, type); - return false; - } - if (type->isBooleanType() && sub_expr->getType()->isIntegerType() && - !sub_expr->getType()->isBooleanType()) { - PushParen paren(*this); - Convert(sub_expr); - StrCat(token::kDiff, token::kZero); - return false; - } { - PushParen paren(*this); - { - PushParen inner(*this, Mapper::Contains(ctx_, sub_expr)); + ScopedValue clear_box(array_new_as_box_, false); + if (type->isFunctionPointerType() || + sub_expr->getType()->isFunctionPointerType()) { + ConvertFunctionPointerTransmute(sub_expr, type); + return false; + } + if (type->isBooleanType() && sub_expr->getType()->isIntegerType() && + !sub_expr->getType()->isBooleanType()) { + PushParen paren(*this); Convert(sub_expr); + StrCat(token::kDiff, token::kZero); + return false; } - if (auto *unary_oper = clang::dyn_cast(sub_expr); - unary_oper && unary_oper->getOpcode() == clang::UO_AddrOf && - clang::isa( - unary_oper->getSubExpr())) { - ConvertCast(sub_expr->getType()); + { + PushParen paren(*this); + { + PushParen inner(*this, Mapper::Contains(ctx_, sub_expr)); + Convert(sub_expr); + } + if (auto *unary_oper = clang::dyn_cast(sub_expr); + unary_oper && unary_oper->getOpcode() == clang::UO_AddrOf && + clang::isa( + unary_oper->getSubExpr())) { + ConvertCast(sub_expr->getType()); + } + ConvertCast(type, sub_expr->getType()); } - ConvertCast(type, sub_expr->getType()); + return false; } - return false; default: Convert(sub_expr); return false; @@ -3493,6 +3513,8 @@ bool Converter::VisitCXXRewrittenBinaryOperator( } bool Converter::VisitBinaryOperator(clang::BinaryOperator *expr) { + ScopedValue clear_box(array_new_as_box_, + expr->isCommaOp() && array_new_as_box_); if (expr->isPtrMemOp()) { ConvertMemberPtrAccess(expr); return false; @@ -3719,6 +3741,7 @@ void Converter::ConvertBinaryOperator(clang::BinaryOperator *expr) { } else if (expr->isCommaOp()) { std::string effect; { + ScopedValue clear_box(array_new_as_box_, false); PushExprKind push(*this, ExprKind::Void); effect = ToString(lhs); } @@ -3947,6 +3970,10 @@ bool Converter::ConvertIncAndDec(clang::UnaryOperator *expr) { } bool Converter::VisitUnaryOperator(clang::UnaryOperator *expr) { + auto opcode = expr->getOpcode(); + ScopedValue clear_box(array_new_as_box_, (opcode == clang::UO_Extension || + opcode == clang::UO_Plus) && + array_new_as_box_); if (auto str = GetMappedAsString(expr); !str.empty()) { EmitFresh(str); return false; @@ -3956,7 +3983,6 @@ bool Converter::VisitUnaryOperator(clang::UnaryOperator *expr) { return false; } - auto opcode = expr->getOpcode(); auto *sub_expr = expr->getSubExpr(); switch (opcode) { case clang::UO_Extension: @@ -4347,6 +4373,7 @@ bool Converter::ConvertCXXOperatorCallExpr(clang::CXXOperatorCallExpr *expr) { } bool Converter::VisitMemberExpr(clang::MemberExpr *expr) { + ScopedValue clear_box(array_new_as_box_, false); auto *member = expr->getMemberDecl(); if (!member->isCXXInstanceMember()) { ConvertDeclRefValue(expr, member); @@ -4622,7 +4649,12 @@ void Converter::ConvertScalarInitList(clang::InitListExpr *expr) { assert(expr->getNumInits() < 2 && "Excess elements in scalar initializer"); if (expr->getNumInits() > 0) { auto init = expr->getInit(0); - ConvertVarInit(init->getType(), init); + if (array_new_as_box_) { + PushExprKind push(*this, ExprKind::FreshRValue); + Convert(init, init->getType()); + } else { + ConvertVarInit(init->getType(), init); + } } else { StrCat(GetDefaultAsString(expr->getType())); } @@ -4751,6 +4783,7 @@ bool Converter::VisitCompoundLiteralExpr(clang::CompoundLiteralExpr *expr) { } bool Converter::VisitArraySubscriptExpr(clang::ArraySubscriptExpr *expr) { + ScopedValue clear_box(array_new_as_box_, false); auto *base = expr->getBase(); if (base->IgnoreCasts()->getType()->isPointerType() || clang::isa(base->IgnoreCasts())) { @@ -4795,27 +4828,50 @@ bool Converter::VisitGNUNullExpr(clang::GNUNullExpr *expr) { } bool Converter::VisitCXXNewExpr(clang::CXXNewExpr *expr) { + bool as_box = array_new_as_box_; + ScopedValue clear_box(array_new_as_box_, false); auto pointee = std::exchange(new_pointee_, std::nullopt); if (expr->isArray()) { - if (auto *init = llvm::dyn_cast_or_null( - expr->getInitializer())) { - StrCat("Box::leak(Box::new("); + auto *init = + llvm::dyn_cast_or_null(expr->getInitializer()); + bool use_init_list = + init && (init->getNumInits() > 0 || !expr->getArraySize().has_value()); + if (as_box) { + if (use_init_list) { + StrCat("Box::leak"); + PushParen outer(*this); + StrCat("Box::new"); + PushParen inner(*this); + Convert(init); + } else { + assert(expr->getArraySize().has_value()); + auto array_size_as_string = ToString(*expr->getArraySize()); + auto alloc_type_as_string = ToString(expr->getAllocatedType()); + auto default_alloc_type_as_string = + GetDefaultAsString(expr->getAllocatedType()); + auto new_array_as_string = + std::format("Box::leak((0..{}).map(|_| {}).collect::>())", + array_size_as_string, default_alloc_type_as_string, + alloc_type_as_string); + StrCat(new_array_as_string); + } + } else if (use_init_list) { + auto alloc_type_as_string = ToString(expr->getAllocatedType()); + StrCat(std::format("libcc2rs::alloc_array_from_unsafe::<{}, _>", + alloc_type_as_string)); + PushParen paren(*this); Convert(init); - StrCat("))"); } else { assert(expr->getArraySize().has_value()); auto array_size_as_string = ToString(*expr->getArraySize()); auto alloc_type_as_string = ToString(expr->getAllocatedType()); auto default_alloc_type_as_string = GetDefaultAsString(expr->getAllocatedType()); - auto new_array_as_string = - std::format("Box::leak((0..{}).map(|_| {}).collect::>())", - array_size_as_string, default_alloc_type_as_string, - alloc_type_as_string); - StrCat(new_array_as_string); - } - if (!curr_init_type_.empty() && curr_init_type_.back()->isPointerType()) { - StrCat(".as_mut_ptr()"); + StrCat(std::format("libcc2rs::alloc_array_unsafe::<{}>", + alloc_type_as_string)); + PushParen paren(*this); + StrCat(array_size_as_string, token::kComma, "|| ", + default_alloc_type_as_string); } } else if (auto *construct = expr->getInitializer() @@ -4850,6 +4906,7 @@ bool Converter::VisitCXXNewExpr(clang::CXXNewExpr *expr) { } bool Converter::VisitCXXDeleteExpr(clang::CXXDeleteExpr *expr) { + ScopedValue clear_box(array_new_as_box_, false); auto *argument = expr->getArgument(); auto destroyed_type = expr->getDestroyedType(); PushBrace brace(*this); @@ -4861,13 +4918,12 @@ bool Converter::VisitCXXDeleteExpr(clang::CXXDeleteExpr *expr) { EmitDeallocation(expr, "__p"); return false; } - auto record_name = GetRecordName(destroyed_type->getAsCXXRecordDecl()); if (expr->isArrayForm()) { - StrCat( - std::format("for __i in (0..libcc2rs::malloc_usable_size(__p as *mut " - "::libc::c_void) / ::std::mem::size_of::<{0}>()).rev() {{ " - "DestructibleUnsafe::destroy(__p.add(__i)); }}", - record_name)); + std::string ptr = + !IsMut(destroyed_type) ? "__p.cast_mut()" : std::string("__p"); + StrCat(std::format("for __i in (0..libcc2rs::array_len_unsafe({0})).rev() " + "{{ DestructibleUnsafe::destroy({0}.add(__i)); }}", + ptr)); } else { StrCat("DestructibleUnsafe::destroy(__p)", token::kSemiColon); } @@ -4877,20 +4933,15 @@ bool Converter::VisitCXXDeleteExpr(clang::CXXDeleteExpr *expr) { void Converter::EmitDeallocation(clang::CXXDeleteExpr *expr, const std::string &argument_as_string) { + bool cast_mut = !IsMut(expr->getDestroyedType()); if (expr->isArrayForm()) { - auto destroyed_type = expr->getDestroyedType(); - auto type = ToString(destroyed_type); - bool is_const = destroyed_type.isConstQualified(); - StrCat(std::format( - R"( - ::std::mem::drop(Box::from_raw( - ::std::slice::from_raw_parts{0}({1}, - libcc2rs::malloc_usable_size({1} as *mut ::libc::c_void) / - ::std::mem::size_of::<{2}>()){3})))", - is_const ? "" : "_mut", argument_as_string, type, - is_const ? std::format(" as *const [{0}] as *mut [{0}]", type) : "")); + StrCat("libcc2rs::dealloc_array_unsafe"); + { + PushParen paren(*this); + StrCat(argument_as_string, cast_mut ? ".cast_mut()" : ""); + } + StrCat(token::kSemiColon); } else { - bool cast_mut = !IsMut(expr->getDestroyedType()); StrCat(std::format("::std::mem::drop(Box::from_raw({}{}))", argument_as_string, cast_mut ? ".cast_mut()" : "")); } @@ -5081,6 +5132,7 @@ bool Converter::VisitCXXConstructExpr(clang::CXXConstructExpr *expr) { Convert(expr->getArg(0)); return false; } + ScopedValue clear_box(array_new_as_box_, false); auto *ctor = expr->getConstructor(); bool trivial_move = ctor->isMoveConstructor() && ctor->isTrivial(); @@ -5651,6 +5703,7 @@ std::string Converter::GetUnsafeTypeAsString(clang::QualType qual_type) const { } void Converter::ConvertVarInit(clang::QualType qual_type, clang::Expr *expr) { + ScopedValue clear_box(array_new_as_box_, false); // The temporaries of the initializer of a reference end after the // reference is made to the object, which outlives them. if (auto *cleanups = clang::dyn_cast(expr); @@ -6949,6 +7002,53 @@ std::string Converter::GetMappedAsString(clang::Expr *expr, clang::Expr **args, } } + auto is_unique_ptr_array_type = [](clang::QualType type) { + type = type.getNonReferenceType(); + if (type->isPointerType()) { + type = type->getPointeeType(); + } + auto *spec = + clang::dyn_cast_or_null( + type->getAsCXXRecordDecl()); + if (!spec || !IsStdDecl(spec, "unique_ptr")) { + return false; + } + const auto &targs = spec->getTemplateArgs(); + return targs.size() >= 1 && + targs[0].getKind() == clang::TemplateArgument::Type && + targs[0].getAsType()->isArrayType(); + }; + + auto get_unique_ptr_array_ptr_arg_idx = [&]() -> std::optional { + if (!expr || RuleRegistry::CurrentModel() != Model::kUnsafe) { + return std::nullopt; + } + if (clang::isa(expr) && all_args.size() >= 1 && + is_unique_ptr_array_type(expr->getType()) && + all_args[0]->getType()->isPointerType()) { + return 0; + } + if (auto *call = clang::dyn_cast(expr); + call && all_args.size() >= 2) { + auto *method = call->getMethodDecl(); + if (method && method->getDeclName().isIdentifier() && + method->getName() == "reset" && + is_unique_ptr_array_type( + call->getImplicitObjectArgument()->getType()) && + all_args[1]->getType()->isPointerType()) { + return 1; + } + } + return std::nullopt; + }; + + auto box_array_arg_idx = get_unique_ptr_array_ptr_arg_idx(); + ScopedValue box_arg_scope( + box_array_arg_, + box_array_arg_idx ? std::optional>( + {expr, *box_array_arg_idx}) + : std::nullopt); + for (size_t i = 0; binding_context && i < all_args.size(); ++i) { if ((!bind[i] && !first[i]) || (init_first && i >= num_params)) { continue; @@ -6992,6 +7092,7 @@ std::string Converter::GetMappedAsString(clang::Expr *expr, clang::Expr **args, // one of the translated argument, e.g., size_t and unsigned long for // std::move(x). if (by_value) { + ScopedValue box_arg(array_new_as_box_, box_array_arg_idx == i); values.push_back( std::format("{{ {} }}", ConvertFreshRValue(arg, var_type))); } else { @@ -7270,7 +7371,13 @@ std::string Converter::ConvertIRFragment( // accesses what they borrow, unless it may point to a temporary, which // would end too. auto outer_borrows = std::exchange(borrows_, false); - auto value = ConvertPlaceholder(expr, arg, ph_ctx); + std::string value; + { + ScopedValue box_arg(array_new_as_box_, + box_array_arg_ && box_array_arg_->first == expr && + box_array_arg_->second == arg_idx); + value = ConvertPlaceholder(expr, arg, ph_ctx); + } if (borrows_ && isFresh() && !CreatesTemporary(arg)) { value = std::format("({{ {} }})", value); borrows_ = false; diff --git a/cpp2rust/converter/converter.h b/cpp2rust/converter/converter.h index c180fceaf0..1e158a5a64 100644 --- a/cpp2rust/converter/converter.h +++ b/cpp2rust/converter/converter.h @@ -1294,6 +1294,12 @@ class Converter : public clang::RecursiveASTVisitor { // converts the pointer to it to a pointer to that type. std::optional new_pointee_; + // Controls whether an array new expression emits a leaked Box<[T]> (for + // std::unique_ptr construction and reset in unsafe mode) instead of a + // raw header-prefixed array pointer. + bool array_new_as_box_ = false; + std::optional> box_array_arg_; + // Converts a full expression with convert, in a block that declares the // temporaries that live through it, if there are any. void ConvertFullExpression(llvm::function_ref convert); diff --git a/libcc2rs/src/alloc.rs b/libcc2rs/src/alloc.rs index 82fabee0cf..fa4480c057 100644 --- a/libcc2rs/src/alloc.rs +++ b/libcc2rs/src/alloc.rs @@ -70,3 +70,329 @@ pub unsafe fn calloc_unsafe(a0: usize, a1: usize) -> *mut libc::c_void { pub unsafe fn strdup_unsafe(a0: *const libc::c_char) -> *mut libc::c_char { unsafe { libc::strdup(a0) } } + +const fn array_header_size() -> usize { + let align = if std::mem::align_of::() > std::mem::align_of::() { + std::mem::align_of::() + } else { + std::mem::align_of::() + }; + std::mem::size_of::().next_multiple_of(align) +} + +fn array_layout_unsafe(len: usize) -> (std::alloc::Layout, usize) { + let align = std::mem::align_of::().max(std::mem::align_of::()); + let header_size = array_header_size::(); + let payload_size = len + .checked_mul(std::mem::size_of::()) + .expect("array allocation size overflow"); + let total_size = header_size + .checked_add(payload_size) + .expect("array allocation size overflow"); + let layout = std::alloc::Layout::from_size_align(total_size, align) + .expect("invalid array allocation layout"); + (layout, header_size) +} + +struct ArrayInitGuard { + base: *mut u8, + layout: std::alloc::Layout, + data: *mut T, + initialized: usize, +} + +impl Drop for ArrayInitGuard { + fn drop(&mut self) { + unsafe { + if std::mem::needs_drop::() { + for i in (0..self.initialized).rev() { + std::ptr::drop_in_place(self.data.add(i)); + } + } + std::alloc::dealloc(self.base, self.layout); + } + } +} + +fn alloc_array_raw_unsafe(len: usize) -> (*mut u8, std::alloc::Layout, *mut T) { + let (layout, header_size) = array_layout_unsafe::(len); + let base = unsafe { std::alloc::alloc(layout) }; + if base.is_null() { + std::alloc::handle_alloc_error(layout); + } + unsafe { + base.cast::().write(len); + let data = base.add(header_size).cast::(); + (base, layout, data) + } +} + +pub fn alloc_array_unsafe(len: usize, mut init: impl FnMut() -> T) -> *mut T { + let (base, layout, data) = alloc_array_raw_unsafe::(len); + let mut guard = ArrayInitGuard { + base, + layout, + data, + initialized: 0, + }; + for i in 0..len { + unsafe { + data.add(i).write(init()); + } + guard.initialized = i + 1; + } + std::mem::forget(guard); + data +} + +pub fn alloc_array_from_unsafe(elems: [T; N]) -> *mut T { + let (_, _, data) = alloc_array_raw_unsafe::(N); + let elems = std::mem::ManuallyDrop::new(elems); + unsafe { + std::ptr::copy_nonoverlapping(elems.as_ptr(), data, N); + } + data +} + +/// # Safety +/// +/// `ptr` must be a non-null pointer returned by [`alloc_array_unsafe`] or +/// [`alloc_array_from_unsafe`] for the same element type `T`, and must not have +/// been deallocated. +pub unsafe fn array_len_unsafe(ptr: *mut T) -> usize { + let header_size = array_header_size::(); + unsafe { ptr.cast::().sub(header_size).cast::().read() } +} + +/// # Safety +/// +/// `ptr` must be null or a pointer returned by [`alloc_array_unsafe`] or +/// [`alloc_array_from_unsafe`] for the same element type `T`, and must not have +/// been deallocated. +pub unsafe fn dealloc_array_unsafe(ptr: *mut T) { + if ptr.is_null() { + return; + } + let header_size = array_header_size::(); + let base = unsafe { ptr.cast::().sub(header_size) }; + let len = unsafe { base.cast::().read() }; + let (layout, _) = array_layout_unsafe::(len); + struct DeallocGuard { + base: *mut u8, + layout: std::alloc::Layout, + } + impl Drop for DeallocGuard { + fn drop(&mut self) { + unsafe { + std::alloc::dealloc(self.base, self.layout); + } + } + } + let _guard = DeallocGuard { base, layout }; + if std::mem::needs_drop::() { + for i in (0..len).rev() { + unsafe { + std::ptr::drop_in_place(ptr.add(i)); + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::cell::RefCell; + use std::rc::Rc; + + struct DropTracker { + id: usize, + log: Rc>>, + } + + impl Drop for DropTracker { + fn drop(&mut self) { + self.log.borrow_mut().push(self.id); + } + } + + #[repr(align(64))] + struct Aligned64 { + id: usize, + log: Rc>>, + } + + impl Drop for Aligned64 { + fn drop(&mut self) { + self.log.borrow_mut().push(self.id); + } + } + + thread_local! { + static ZST_DROPS: RefCell = const { RefCell::new(0) }; + } + + struct ZstDrop; + + impl Drop for ZstDrop { + fn drop(&mut self) { + ZST_DROPS.with(|c| *c.borrow_mut() += 1); + } + } + + #[test] + fn alloc_and_dealloc_reverse_drop_order() { + let log = Rc::new(RefCell::new(Vec::new())); + let mut next = 1usize; + let ptr = alloc_array_unsafe(3, || { + let id = next; + next += 1; + DropTracker { + id, + log: Rc::clone(&log), + } + }); + assert!(!ptr.is_null()); + unsafe { + assert_eq!(array_len_unsafe(ptr), 3); + assert_eq!((*ptr.add(0)).id, 1); + assert_eq!((*ptr.add(1)).id, 2); + assert_eq!((*ptr.add(2)).id, 3); + dealloc_array_unsafe(ptr); + } + assert_eq!(*log.borrow(), vec![3, 2, 1]); + } + + #[test] + fn dealloc_null_is_noop() { + unsafe { + dealloc_array_unsafe(std::ptr::null_mut::()); + } + } + + #[test] + fn zero_length_allocations_are_non_null_and_distinct() { + let log = Rc::new(RefCell::new(Vec::new())); + let p1 = alloc_array_unsafe(0, || DropTracker { + id: 99, + log: Rc::clone(&log), + }); + let p2 = alloc_array_unsafe(0, || DropTracker { + id: 100, + log: Rc::clone(&log), + }); + assert!(!p1.is_null()); + assert!(!p2.is_null()); + assert_ne!(p1, p2); + unsafe { + assert_eq!(array_len_unsafe(p1), 0); + assert_eq!(array_len_unsafe(p2), 0); + dealloc_array_unsafe(p1); + dealloc_array_unsafe(p2); + } + assert!(log.borrow().is_empty()); + } + + #[test] + fn init_panic_drops_initialized_prefix_in_reverse() { + let log = Rc::new(RefCell::new(Vec::new())); + let log_clone = Rc::clone(&log); + let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(move || { + let mut idx = 0usize; + let _ = alloc_array_unsafe(5, || { + if idx == 2 { + panic!("init failed at 2"); + } + let id = idx; + idx += 1; + DropTracker { + id, + log: Rc::clone(&log_clone), + } + }); + })); + assert!(result.is_err()); + assert_eq!(*log.borrow(), vec![1, 0]); + } + + #[test] + fn alloc_array_from_non_empty_and_empty() { + let log = Rc::new(RefCell::new(Vec::new())); + let ptr = alloc_array_from_unsafe([ + DropTracker { + id: 10, + log: Rc::clone(&log), + }, + DropTracker { + id: 20, + log: Rc::clone(&log), + }, + DropTracker { + id: 30, + log: Rc::clone(&log), + }, + ]); + assert!(!ptr.is_null()); + unsafe { + assert_eq!(array_len_unsafe(ptr), 3); + assert_eq!((*ptr.add(0)).id, 10); + assert_eq!((*ptr.add(2)).id, 30); + dealloc_array_unsafe(ptr); + } + assert_eq!(*log.borrow(), vec![30, 20, 10]); + + let empty: *mut DropTracker = alloc_array_from_unsafe([]); + assert!(!empty.is_null()); + unsafe { + assert_eq!(array_len_unsafe(empty), 0); + dealloc_array_unsafe(empty); + } + assert_eq!(*log.borrow(), vec![30, 20, 10]); + } + + #[test] + fn over_aligned_and_zst_drop_layouts() { + let log = Rc::new(RefCell::new(Vec::new())); + let mut next = 1usize; + let ptr = alloc_array_unsafe(2, || { + let id = next; + next += 1; + Aligned64 { + id, + log: Rc::clone(&log), + } + }); + assert!(!ptr.is_null()); + assert_eq!((ptr as usize) % 64, 0); + unsafe { + assert_eq!(array_len_unsafe(ptr), 2); + dealloc_array_unsafe(ptr); + } + assert_eq!(*log.borrow(), vec![2, 1]); + + let empty_aligned = alloc_array_unsafe(0, || Aligned64 { + id: 0, + log: Rc::clone(&log), + }); + assert!(!empty_aligned.is_null()); + assert_eq!((empty_aligned as usize) % 64, 0); + unsafe { + assert_eq!(array_len_unsafe(empty_aligned), 0); + dealloc_array_unsafe(empty_aligned); + } + + ZST_DROPS.with(|c| *c.borrow_mut() = 0); + let z0 = alloc_array_unsafe(0, || ZstDrop); + let z4 = alloc_array_unsafe(4, || ZstDrop); + assert!(!z0.is_null()); + assert!(!z4.is_null()); + assert_ne!(z0, z4); + unsafe { + assert_eq!(array_len_unsafe(z0), 0); + assert_eq!(array_len_unsafe(z4), 4); + dealloc_array_unsafe(z0); + assert_eq!(ZST_DROPS.with(|c| *c.borrow()), 0); + dealloc_array_unsafe(z4); + assert_eq!(ZST_DROPS.with(|c| *c.borrow()), 4); + } + } +} diff --git a/tests/std/dcl.dcl/dcl.decl/dcl.init/out/unsafe/dcl.init.general.rs b/tests/std/dcl.dcl/dcl.decl/dcl.init/out/unsafe/dcl.init.general.rs index 8b2c7d2d64..210de9e19b 100644 --- a/tests/std/dcl.dcl/dcl.decl/dcl.init/out/unsafe/dcl.init.general.rs +++ b/tests/std/dcl.dcl/dcl.decl/dcl.init/out/unsafe/dcl.init.general.rs @@ -304,8 +304,7 @@ pub unsafe fn test_21() { i.prefix_inc(); } } - let mut heap_numbers: *mut i32 = - Box::leak((0..3_usize).map(|_| 0_i32).collect::>()).as_mut_ptr(); + let mut heap_numbers: *mut i32 = libcc2rs::alloc_array_unsafe::(3_usize, || 0_i32); { let mut i: i32 = 0; 'loop_: while ((i) < (3)) { @@ -318,11 +317,7 @@ pub unsafe fn test_21() { { let __p = heap_numbers; if !__p.is_null() { - ::std::mem::drop(Box::from_raw(::std::slice::from_raw_parts_mut( - __p, - libcc2rs::malloc_usable_size(__p as *mut ::libc::c_void) - / ::std::mem::size_of::(), - ))) + libcc2rs::dealloc_array_unsafe(__p); } }; } diff --git a/tests/ub/out/unsafe/int_to_ptr_dangling.rs b/tests/ub/out/unsafe/int_to_ptr_dangling.rs index 037b02dca9..e2812c86c8 100644 --- a/tests/ub/out/unsafe/int_to_ptr_dangling.rs +++ b/tests/ub/out/unsafe/int_to_ptr_dangling.rs @@ -13,16 +13,12 @@ pub fn main() { } } unsafe fn main_0() -> i32 { - let mut p: *mut i32 = Box::leak(Box::new([1, 2])).as_mut_ptr(); + let mut p: *mut i32 = libcc2rs::alloc_array_from_unsafe::([1, 2]); let mut i: usize = (p as usize); { let __p = p; if !__p.is_null() { - ::std::mem::drop(Box::from_raw(::std::slice::from_raw_parts_mut( - __p, - libcc2rs::malloc_usable_size(__p as *mut ::libc::c_void) - / ::std::mem::size_of::(), - ))) + libcc2rs::dealloc_array_unsafe(__p); } }; return (*(i as *mut i32).offset((1) as isize)); diff --git a/tests/ub/out/unsafe/ub10.rs b/tests/ub/out/unsafe/ub10.rs index 163d5ccc91..a7c6d86b3f 100644 --- a/tests/ub/out/unsafe/ub10.rs +++ b/tests/ub/out/unsafe/ub10.rs @@ -13,18 +13,13 @@ pub fn main() { } } unsafe fn main_0() -> i32 { - let mut arr: *mut i32 = - Box::leak((0..10_usize).map(|_| 0_i32).collect::>()).as_mut_ptr(); + let mut arr: *mut i32 = libcc2rs::alloc_array_unsafe::(10_usize, || 0_i32); let mut ptr: *mut i32 = arr.offset((1) as isize); let mut out: i32 = (*ptr); { let __p = ptr; if !__p.is_null() { - ::std::mem::drop(Box::from_raw(::std::slice::from_raw_parts_mut( - __p, - libcc2rs::malloc_usable_size(__p as *mut ::libc::c_void) - / ::std::mem::size_of::(), - ))) + libcc2rs::dealloc_array_unsafe(__p); } }; return out; diff --git a/tests/ub/out/unsafe/ub14.rs b/tests/ub/out/unsafe/ub14.rs index 3e29576340..d29d1f751c 100644 --- a/tests/ub/out/unsafe/ub14.rs +++ b/tests/ub/out/unsafe/ub14.rs @@ -13,17 +13,12 @@ pub fn main() { } } unsafe fn main_0() -> i32 { - let mut arr1: *mut i32 = - Box::leak((0..100_usize).map(|_| 0_i32).collect::>()).as_mut_ptr(); + let mut arr1: *mut i32 = libcc2rs::alloc_array_unsafe::(100_usize, || 0_i32); (*arr1.offset((100) as isize)) = 1; { let __p = arr1; if !__p.is_null() { - ::std::mem::drop(Box::from_raw(::std::slice::from_raw_parts_mut( - __p, - libcc2rs::malloc_usable_size(__p as *mut ::libc::c_void) - / ::std::mem::size_of::(), - ))) + libcc2rs::dealloc_array_unsafe(__p); } }; return 0; diff --git a/tests/ub/out/unsafe/ub15.rs b/tests/ub/out/unsafe/ub15.rs index 62192111d1..a27501b0ba 100644 --- a/tests/ub/out/unsafe/ub15.rs +++ b/tests/ub/out/unsafe/ub15.rs @@ -13,18 +13,13 @@ pub fn main() { } } unsafe fn main_0() -> i32 { - let mut arr: *mut i32 = - Box::leak((0..15_usize).map(|_| 0_i32).collect::>()).as_mut_ptr(); + let mut arr: *mut i32 = libcc2rs::alloc_array_unsafe::(15_usize, || 0_i32); let mut ptr: *mut i32 = arr.offset((15) as isize); let mut out: i32 = (*ptr); { let __p = arr; if !__p.is_null() { - ::std::mem::drop(Box::from_raw(::std::slice::from_raw_parts_mut( - __p, - libcc2rs::malloc_usable_size(__p as *mut ::libc::c_void) - / ::std::mem::size_of::(), - ))) + libcc2rs::dealloc_array_unsafe(__p); } }; return out; diff --git a/tests/ub/out/unsafe/ub16.rs b/tests/ub/out/unsafe/ub16.rs index 7c2fdebd2b..4257212ceb 100644 --- a/tests/ub/out/unsafe/ub16.rs +++ b/tests/ub/out/unsafe/ub16.rs @@ -16,18 +16,13 @@ pub fn main() { } } unsafe fn main_0() -> i32 { - let mut p1: *mut i32 = - Box::leak((0..10_usize).map(|_| 0_i32).collect::>()).as_mut_ptr(); + let mut p1: *mut i32 = libcc2rs::alloc_array_unsafe::(10_usize, || 0_i32); let mut out: i32 = (*(unsafe { foo_0((&mut (*p1.offset((1) as isize)) as *mut i32)) }).offset((4) as isize)); { let __p = p1; if !__p.is_null() { - ::std::mem::drop(Box::from_raw(::std::slice::from_raw_parts_mut( - __p, - libcc2rs::malloc_usable_size(__p as *mut ::libc::c_void) - / ::std::mem::size_of::(), - ))) + libcc2rs::dealloc_array_unsafe(__p); } }; return 0; diff --git a/tests/ub/out/unsafe/ub18.rs b/tests/ub/out/unsafe/ub18.rs index 75a185e259..c38cc1bbf2 100644 --- a/tests/ub/out/unsafe/ub18.rs +++ b/tests/ub/out/unsafe/ub18.rs @@ -18,11 +18,7 @@ unsafe fn main_0() -> i32 { { let __p = p; if !__p.is_null() { - ::std::mem::drop(Box::from_raw(::std::slice::from_raw_parts_mut( - __p, - libcc2rs::malloc_usable_size(__p as *mut ::libc::c_void) - / ::std::mem::size_of::(), - ))) + libcc2rs::dealloc_array_unsafe(__p); } }; return 0; diff --git a/tests/ub/out/unsafe/ub19.rs b/tests/ub/out/unsafe/ub19.rs index ed4f66ced9..e3637838d2 100644 --- a/tests/ub/out/unsafe/ub19.rs +++ b/tests/ub/out/unsafe/ub19.rs @@ -10,11 +10,7 @@ pub unsafe fn foo_0(mut array: *mut i32) { { let __p = array; if !__p.is_null() { - ::std::mem::drop(Box::from_raw(::std::slice::from_raw_parts_mut( - __p, - libcc2rs::malloc_usable_size(__p as *mut ::libc::c_void) - / ::std::mem::size_of::(), - ))) + libcc2rs::dealloc_array_unsafe(__p); } }; } diff --git a/tests/ub/out/unsafe/ub20.rs b/tests/ub/out/unsafe/ub20.rs index 73603e50cc..2484d180c1 100644 --- a/tests/ub/out/unsafe/ub20.rs +++ b/tests/ub/out/unsafe/ub20.rs @@ -21,8 +21,7 @@ pub fn main() { } } unsafe fn main_0() -> i32 { - let mut x: *mut i32 = - Box::leak((0..10_usize).map(|_| 0_i32).collect::>()).as_mut_ptr(); + let mut x: *mut i32 = libcc2rs::alloc_array_unsafe::(10_usize, || 0_i32); (unsafe { foo_0(x) }); return 0; } diff --git a/tests/ub/out/unsafe/ub9.rs b/tests/ub/out/unsafe/ub9.rs index b0635490ec..07956f2364 100644 --- a/tests/ub/out/unsafe/ub9.rs +++ b/tests/ub/out/unsafe/ub9.rs @@ -13,17 +13,12 @@ pub fn main() { } } unsafe fn main_0() -> i32 { - let mut arr: *mut i32 = - Box::leak((0..10_usize).map(|_| 0_i32).collect::>()).as_mut_ptr(); + let mut arr: *mut i32 = libcc2rs::alloc_array_unsafe::(10_usize, || 0_i32); let mut out: i32 = (*arr.offset((10) as isize)); { let __p = arr; if !__p.is_null() { - ::std::mem::drop(Box::from_raw(::std::slice::from_raw_parts_mut( - __p, - libcc2rs::malloc_usable_size(__p as *mut ::libc::c_void) - / ::std::mem::size_of::(), - ))) + libcc2rs::dealloc_array_unsafe(__p); } }; return out; diff --git a/tests/unit/delete_array_exact_len.cpp b/tests/unit/delete_array_exact_len.cpp new file mode 100644 index 0000000000..f967fc824b --- /dev/null +++ b/tests/unit/delete_array_exact_len.cpp @@ -0,0 +1,259 @@ +#include +#include +#include +#include +#include +#include + +int g_byte_dtors = 0; +int g_byte_sum = 0; + +struct Byte { + unsigned char v; + Byte() : v(7) {} + ~Byte() { + ++g_byte_dtors; + g_byte_sum += v; + } +}; + +int g_next_id = 1; +int g_log[32]; +int g_log_len = 0; + +struct Small { + int id; + Small() : id(g_next_id++) {} + ~Small() { g_log[g_log_len++] = id; } +}; + +int g_empty_ctors = 0; +int g_empty_dtors = 0; + +struct Empty { + Empty() { ++g_empty_ctors; } + ~Empty() { ++g_empty_dtors; } +}; + +struct WithVec { + std::vector items; + WithVec() { items.push_back(42); } + int first() const { return items[0]; } +}; + +static bool check_and_delete(int *p) { + bool ok = p != nullptr; + delete[] p; + return ok; +} + +static std::unique_ptr &get_u_after_delete(std::unique_ptr &u, + int *raw) { + delete[] raw; + return u; +} + +static int size_from_delete(int *p) { + int n = p[0]; + delete[] p; + return n; +} + +int main() { + // Small non-bucket-aligned arrays must destroy only the allocated elements. + Byte *b1 = new Byte[1]; + delete[] b1; + assert(g_byte_dtors == 1); + assert(g_byte_sum == 7); + + Byte *b3 = new Byte[3]; + delete[] b3; + assert(g_byte_dtors == 4); + assert(g_byte_sum == 28); + + // Zero-length arrays must return non-null distinct pointers and delete + // safely. + int *z1 = new int[0]; + int *z2 = new int[0]; + assert(z1 != nullptr && z2 != nullptr && z1 != z2); + delete[] z1; + delete[] z2; + + Small *zs = new Small[0]; + assert(zs != nullptr); + delete[] zs; + assert(g_next_id == 1 && g_log_len == 0); + + // Deleting a null pointer is a no-op. + Small *np = nullptr; + delete[] np; + assert(g_log_len == 0); + + // Reverse destruction order and exact element count for 4-byte structs. + Small *s1 = new Small[1]; + delete[] s1; + Small *s3 = new Small[3]; + delete[] s3; + assert(g_log_len == 4); + assert(g_log[0] == 1 && g_log[1] == 4 && g_log[2] == 3 && g_log[3] == 2); + + // Empty structs (zero-sized in Rust) must destroy the exact count. + Empty *e0 = new Empty[0]; + delete[] e0; + assert(g_empty_ctors == 0 && g_empty_dtors == 0); + Empty *e4 = new Empty[4]; + delete[] e4; + assert(g_empty_ctors == 4 && g_empty_dtors == 4); + + // Const-pointer array delete and 2D array with destructor. + const Small *cs = new Small[2]; + delete[] cs; + assert(g_log_len == 6 && g_log[4] == 6 && g_log[5] == 5); + + Small(*a2d)[2] = new Small[2][2]; + delete[] a2d; + assert(g_log_len == 10 && g_log[6] == 10 && g_log[7] == 9 && g_log[8] == 8 && + g_log[9] == 7); + + // Struct with a Rust Drop field (Vec) via delete[]. + WithVec *wv = new WithVec[2]; + assert(wv[0].first() == 42 && wv[1].first() == 42); + delete[] wv; + + // Assignment, temporary delete[], and zero-length/runtime initializer lists. + int *ap = nullptr; + ap = new int[3]; + ap[2] = 9; + assert(ap[2] == 9); + delete[] ap; + delete[] (new Small[1]); + assert(g_log_len == 11 && g_log[10] == 11); + + int *ci = new int[4]{10, 20}; + assert(ci[0] == 10 && ci[1] == 20 && ci[2] == 0 && ci[3] == 0); + delete[] ci; + + // std::unique_ptr with direct, conditional, cast, binary-conditional, + // statement-expression, and init-list array-new expressions. + bool cond = true; + std::unique_ptr u1(cond ? new int[2] : new int[3]); + u1[1] = 17; + assert(u1[1] == 17); + u1.reset(!cond ? new int[2] : new int[3]); + u1[2] = 29; + assert(u1[2] == 29); + + std::unique_ptr u2 = std::unique_ptr( + check_and_delete(new int[1]) ? new int[2] : new int[3]); + u2[0] = 31; + assert(u2[0] == 31); + + std::unique_ptr u3(static_cast(new int[2])); + u3[1] = 41; + assert(u3[1] == 41); + + std::unique_ptr u4((int *)new int[2]); + u4[0] = 53; + assert(u4[0] == 53); + + std::unique_ptr u5(new int[2]{11, 22}); + assert(u5[0] == 11 && u5[1] == 22); + + std::unique_ptr u6(const_cast(new int[2]{3, 4})); + assert(u6[0] == 3 && u6[1] == 4); + u6.reset(const_cast(new int[2]{7, 8})); + assert(u6[0] == 7 && u6[1] == 8); + + std::unique_ptr u7(const_cast(new const int[2]{5, 6})); + assert(u7[0] == 5 && u7[1] == 6); + + using IntPtr = int *; + std::unique_ptr u8(IntPtr(new int[3])); + u8[2] = 61; + assert(u8[2] == 61); + u8.reset(IntPtr(new int[2]{62, 63})); + assert(u8[0] == 62 && u8[1] == 63); + + std::unique_ptr u9(new int[2] ?: new int[3]); + u9[1] = 71; + assert(u9[1] == 71); + u9.reset(new int[2] ?: new int[3]); + u9[1] = 72; + assert(u9[1] == 72); + + std::unique_ptr u10(({ + int *tmp = new int[1]; + tmp[0] = 3; + int n = tmp[0]; + delete[] tmp; + new int[n]; + })); + u10[2] = 81; + assert(u10[2] == 81); + u10.reset(({ + int n = 4; + new int[n]; + })); + u10[3] = 82; + assert(u10[3] == 82); + + get_u_after_delete(u10, new int[1]).reset(new int[3]{91, 92, 93}); + assert(u10[0] == 91 && u10[2] == 93); + + std::unique_ptr u11(new int[size_from_delete(new int[1]{3})]); + u11[2] = 99; + assert(u11[2] == 99); + + // Forwarding paths into std::unique_ptr construction and reset. + std::vector> vec_u; + vec_u.emplace_back(new int[3]); + vec_u[0][2] = 101; + assert(vec_u[0][2] == 101); + + std::deque> deq_u; + deq_u.emplace_back(new int[3]); + deq_u.front()[2] = 102; + assert(deq_u.front()[2] == 102); + + std::pair> pair_u(1, new int[3]); + pair_u.second[2] = 103; + assert(pair_u.second[2] == 103); + + std::unique_ptr u12(std::move(new int[3])); + u12[2] = 104; + assert(u12[2] == 104); + u12.reset(std::move(new int[3])); + u12[2] = 105; + assert(u12[2] == 105); + + std::unique_ptr u13(std::forward(new int[3])); + u13[1] = 106; + assert(u13[1] == 106); + + std::unique_ptr u14(cond ? std::move(new int[2]{107, 108}) + : std::move(new int[2]{109, 110})); + assert(u14[0] == 107 && u14[1] == 108); + + std::unique_ptr u15(static_cast(new int[2]{111, 112})); + assert(u15[0] == 111 && u15[1] == 112); + + std::unique_ptr u16(static_cast(new int[2]{113, 114})); + assert(u16[0] == 113 && u16[1] == 114); + + std::unique_ptr u17((int *&&)new int[2]{115, 116}); + assert(u17[0] == 115 && u17[1] == 116); + + std::unique_ptr u18((int *){new int[3]}); + u18[2] = 117; + assert(u18[2] == 117); + + // Nested raw array allocations inside unique_ptr initializers. + std::unique_ptr u19( + new int *[2]{new int[3]{1, 2, 3}, new int[2]{4, 5}}); + assert(u19[0][2] == 3 && u19[1][1] == 5); + delete[] u19[0]; + delete[] u19[1]; + + std::printf("ok\n"); + return 0; +} diff --git a/tests/unit/out/refcount/delete_array_exact_len.rs b/tests/unit/out/refcount/delete_array_exact_len.rs new file mode 100644 index 0000000000..4d341877c0 --- /dev/null +++ b/tests/unit/out/refcount/delete_array_exact_len.rs @@ -0,0 +1,631 @@ +extern crate libcc2rs; +use libcc2rs::*; +use std::cell::RefCell; +use std::collections::BTreeMap; +use std::io::prelude::*; +use std::io::{Read, Seek, Write}; +use std::os::fd::AsFd; +use std::rc::{Rc, Weak}; +thread_local!( + pub static g_byte_dtors_0: Value = Rc::new(RefCell::new(0)); +); +thread_local!( + pub static g_byte_sum_1: Value = Rc::new(RefCell::new(0)); +); +#[derive( + Clone, + Record, + ByteRepr, + ZeroInitialization, + VaArg, + FnPtrArg, + Memberwise, + CopyConstructible, + Movable, +)] +#[memberwise(copy_assign)] +#[byte_size(1)] +pub struct Byte { + #[offset(0)] + pub v: u8, +} +impl DefaultConstructible for Byte { + fn default_constructor(this: Ptr) { + field!(this, v).write(7_u8); + } +} +impl Destructible for Byte { + fn destroy(this: Ptr) { + (*g_byte_dtors_0.with(Value::clone).borrow_mut()).prefix_inc(); + g_byte_sum_1.with(|rc| *rc.borrow_mut() += (this.with(|__s| __s.v) as i32)); + } +} +thread_local!( + pub static g_next_id_2: Value = Rc::new(RefCell::new(1)); +); +thread_local!( + pub static g_log_3: Value> = + Rc::new(RefCell::new((0..32).map(|_| 0_i32).collect::>())); +); +thread_local!( + pub static g_log_len_4: Value = Rc::new(RefCell::new(0)); +); +#[derive( + Clone, + Record, + ByteRepr, + ZeroInitialization, + VaArg, + FnPtrArg, + Memberwise, + CopyConstructible, + Movable, +)] +#[memberwise(copy_assign)] +#[byte_size(4)] +pub struct Small { + #[offset(0)] + pub id: i32, +} +impl DefaultConstructible for Small { + fn default_constructor(this: Ptr) { + field!(this, id).write((*g_next_id_2.with(Value::clone).borrow_mut()).postfix_inc()); + } +} +impl Destructible for Small { + fn destroy(this: Ptr) { + (*g_log_3.with(Value::clone).borrow_mut()) + [((*g_log_len_4.with(Value::clone).borrow_mut()).postfix_inc()) as usize] = + this.with(|__s| __s.id); + } +} +thread_local!( + pub static g_empty_ctors_5: Value = Rc::new(RefCell::new(0)); +); +thread_local!( + pub static g_empty_dtors_6: Value = Rc::new(RefCell::new(0)); +); +#[derive( + Clone, + Record, + ByteRepr, + ZeroInitialization, + VaArg, + FnPtrArg, + Memberwise, + CopyConstructible, + Movable, +)] +#[memberwise(copy_assign)] +#[byte_size(1)] +pub struct Empty {} +impl DefaultConstructible for Empty { + fn default_constructor(this: Ptr) { + (*g_empty_ctors_5.with(Value::clone).borrow_mut()).prefix_inc(); + } +} +impl Destructible for Empty { + fn destroy(this: Ptr) { + (*g_empty_dtors_6.with(Value::clone).borrow_mut()).prefix_inc(); + } +} +#[derive( + Clone, + Record, + ByteRepr, + ZeroInitialization, + VaArg, + FnPtrArg, + Destructible, + Memberwise, + CopyConstructible, + Swappable, +)] +#[memberwise(move_constructor, copy_assign, move_assign)] +#[byte_size(24)] +pub struct WithVec { + #[offset(0)] + #[byte_size(24)] + pub items: Vec, +} +impl WithVec { + pub fn first(this: Ptr) -> i32 { + return (vec_elem!(this, items, 0_usize).read()); + } +} +impl DefaultConstructible for WithVec { + fn default_constructor(this: Ptr) { + field!(this, items).write(Vec::new()); + ({ + let __tmp_0: Value = Rc::new(RefCell::new(42)); + MoveConstructible::push_moved( + &field_ref!(this, items).as_pointer(), + __tmp_0.as_pointer(), + ) + }); + } +} +impl Default for WithVec { + fn default() -> Self { + { + { + let __v: Value = Rc::new(RefCell::new(::zero_init())); + DefaultConstructible::default_constructor(__v.as_pointer()); + Rc::try_unwrap(__v).ok().unwrap().into_inner() + } + } + } +} +pub fn check_and_delete_7(mut p: Ptr) -> bool { + let mut ok: bool = !((p).is_null()); + p.delete(); + return ok; +} +pub fn get_u_after_delete_8( + u: Ptr>>>, + mut raw_: Ptr, +) -> Ptr>>> { + raw_.delete(); + return (u).clone(); +} +pub fn size_from_delete_9(mut p: Ptr) -> i32 { + let mut n: i32 = (elem!(p, 0).read()); + p.delete(); + return n; +} +pub fn main() { + __cpp2rust_init_globals(); + libcc2rs::cpp2rust_exit(main_0()); +} +fn main_0() -> i32 { + let mut b1: Ptr = Ptr::alloc_array( + (0..1_usize) + .map(|_| ::default_constructed()) + .collect::>(), + ); + { + let __p = b1; + for __i in (0..__p.len()).rev() { + Destructible::destroy(__p.offset(__i as isize)); + } + __p.delete(); + }; + assert!((g_byte_dtors_0.with(|rc| *rc.borrow()) == 1)); + assert!((g_byte_sum_1.with(|rc| *rc.borrow()) == 7)); + let mut b3: Ptr = Ptr::alloc_array( + (0..3_usize) + .map(|_| ::default_constructed()) + .collect::>(), + ); + { + let __p = b3; + for __i in (0..__p.len()).rev() { + Destructible::destroy(__p.offset(__i as isize)); + } + __p.delete(); + }; + assert!((g_byte_dtors_0.with(|rc| *rc.borrow()) == 4)); + assert!((g_byte_sum_1.with(|rc| *rc.borrow()) == 28)); + let mut z1: Ptr = Ptr::alloc_array((0..0_usize).map(|_| 0_i32).collect::>()); + let mut z2: Ptr = Ptr::alloc_array((0..0_usize).map(|_| 0_i32).collect::>()); + assert!(((!((z1).is_null())) && (!((z2).is_null()))) && ({ (z1).clone() } != { (z2).clone() })); + z1.delete(); + z2.delete(); + let mut zs: Ptr = Ptr::alloc_array( + (0..0_usize) + .map(|_| ::default_constructed()) + .collect::>(), + ); + assert!(!((zs).is_null())); + { + let __p = zs; + for __i in (0..__p.len()).rev() { + Destructible::destroy(__p.offset(__i as isize)); + } + __p.delete(); + }; + assert!( + (g_next_id_2.with(|rc| *rc.borrow()) == 1) && (g_log_len_4.with(|rc| *rc.borrow()) == 0) + ); + let mut np: Ptr = Ptr::::null(); + { + let __p = np; + for __i in (0..__p.len()).rev() { + Destructible::destroy(__p.offset(__i as isize)); + } + __p.delete(); + }; + assert!((g_log_len_4.with(|rc| *rc.borrow()) == 0)); + let mut s1: Ptr = Ptr::alloc_array( + (0..1_usize) + .map(|_| ::default_constructed()) + .collect::>(), + ); + { + let __p = s1; + for __i in (0..__p.len()).rev() { + Destructible::destroy(__p.offset(__i as isize)); + } + __p.delete(); + }; + let mut s3: Ptr = Ptr::alloc_array( + (0..3_usize) + .map(|_| ::default_constructed()) + .collect::>(), + ); + { + let __p = s3; + for __i in (0..__p.len()).rev() { + Destructible::destroy(__p.offset(__i as isize)); + } + __p.delete(); + }; + assert!((g_log_len_4.with(|rc| *rc.borrow()) == 4)); + assert!( + (((({ + let __idx0 = (0) as usize; + g_log_3.with(|rc| rc.borrow()[__idx0]) + }) == 1) + && (({ + let __idx0 = (1) as usize; + g_log_3.with(|rc| rc.borrow()[__idx0]) + }) == 4)) + && (({ + let __idx0 = (2) as usize; + g_log_3.with(|rc| rc.borrow()[__idx0]) + }) == 3)) + && (({ + let __idx0 = (3) as usize; + g_log_3.with(|rc| rc.borrow()[__idx0]) + }) == 2) + ); + let mut e0: Ptr = Ptr::alloc_array( + (0..0_usize) + .map(|_| ::default_constructed()) + .collect::>(), + ); + { + let __p = e0; + for __i in (0..__p.len()).rev() { + Destructible::destroy(__p.offset(__i as isize)); + } + __p.delete(); + }; + assert!( + (g_empty_ctors_5.with(|rc| *rc.borrow()) == 0) + && (g_empty_dtors_6.with(|rc| *rc.borrow()) == 0) + ); + let mut e4: Ptr = Ptr::alloc_array( + (0..4_usize) + .map(|_| ::default_constructed()) + .collect::>(), + ); + { + let __p = e4; + for __i in (0..__p.len()).rev() { + Destructible::destroy(__p.offset(__i as isize)); + } + __p.delete(); + }; + assert!( + (g_empty_ctors_5.with(|rc| *rc.borrow()) == 4) + && (g_empty_dtors_6.with(|rc| *rc.borrow()) == 4) + ); + let mut cs: Ptr = Ptr::alloc_array( + (0..2_usize) + .map(|_| ::default_constructed()) + .collect::>(), + ); + { + let __p = cs; + for __i in (0..__p.len()).rev() { + Destructible::destroy(__p.offset(__i as isize)); + } + __p.delete(); + }; + assert!( + ((g_log_len_4.with(|rc| *rc.borrow()) == 6) + && (({ + let __idx0 = (4) as usize; + g_log_3.with(|rc| rc.borrow()[__idx0]) + }) == 6)) + && (({ + let __idx0 = (5) as usize; + g_log_3.with(|rc| rc.borrow()[__idx0]) + }) == 5) + ); + let mut a2d: Ptr> = Ptr::alloc_array( + (0..2_usize) + .map(|_| { + (0..2) + .map(|_| ::default_constructed()) + .collect::>() + }) + .collect::]>>(), + ); + { + let __p = a2d; + for __i in (0..__p.len()).rev() { + Destructible::destroy(__p.offset(__i as isize)); + } + __p.delete(); + }; + assert!( + ((((g_log_len_4.with(|rc| *rc.borrow()) == 10) + && (({ + let __idx0 = (6) as usize; + g_log_3.with(|rc| rc.borrow()[__idx0]) + }) == 10)) + && (({ + let __idx0 = (7) as usize; + g_log_3.with(|rc| rc.borrow()[__idx0]) + }) == 9)) + && (({ + let __idx0 = (8) as usize; + g_log_3.with(|rc| rc.borrow()[__idx0]) + }) == 8)) + && (({ + let __idx0 = (9) as usize; + g_log_3.with(|rc| rc.borrow()[__idx0]) + }) == 7) + ); + let mut wv: Ptr = Ptr::alloc_array( + (0..2_usize) + .map(|_| ::default()) + .collect::>(), + ); + assert!( + (({ WithVec::first(wv.offset((0) as isize),) }) == 42) + && (({ WithVec::first(wv.offset((1) as isize),) }) == 42) + ); + wv.delete(); + let mut ap: Ptr = Ptr::::null(); + ap = Ptr::alloc_array((0..3_usize).map(|_| 0_i32).collect::>()); + elem!(ap, 2).write(9); + assert!(((elem!(ap, 2).read()) == 9)); + ap.delete(); + { + let __p = (Ptr::alloc_array( + (0..1_usize) + .map(|_| ::default_constructed()) + .collect::>(), + )); + for __i in (0..__p.len()).rev() { + Destructible::destroy(__p.offset(__i as isize)); + } + __p.delete(); + }; + assert!( + (g_log_len_4.with(|rc| *rc.borrow()) == 11) + && (({ + let __idx0 = (10) as usize; + g_log_3.with(|rc| rc.borrow()[__idx0]) + }) == 11) + ); + let mut ci: Ptr = Ptr::alloc_array(Box::new([10, 20, 0_i32, 0_i32])); + assert!( + ((((elem!(ci, 0).read()) == 10) && ((elem!(ci, 1).read()) == 20)) + && ((elem!(ci, 2).read()) == 0)) + && ((elem!(ci, 3).read()) == 0) + ); + ci.delete(); + let mut cond: bool = true; + let u1: Value>>> = Rc::new(RefCell::new( + if cond { + Ptr::alloc_array((0..2_usize).map(|_| 0_i32).collect::>()) + } else { + Ptr::alloc_array((0..3_usize).map(|_| 0_i32).collect::>()) + } + .to_owned_opt(), + )); + ({ (*u1.borrow()).decay().offset(1_usize) }).write(17); + assert!(((({ (*u1.borrow()).decay().offset(1_usize) }).read()) == 17)); + u1.as_pointer().write( + if !(cond) { + Ptr::alloc_array((0..2_usize).map(|_| 0_i32).collect::>()) + } else { + Ptr::alloc_array((0..3_usize).map(|_| 0_i32).collect::>()) + } + .to_owned_opt(), + ); + ({ (*u1.borrow()).decay().offset(2_usize) }).write(29); + assert!(((({ (*u1.borrow()).decay().offset(2_usize) }).read()) == 29)); + let mut u2: Option>> = if ({ + check_and_delete_7(Ptr::alloc_array( + (0..1_usize).map(|_| 0_i32).collect::>(), + )) + }) { + Ptr::alloc_array((0..2_usize).map(|_| 0_i32).collect::>()) + } else { + Ptr::alloc_array((0..3_usize).map(|_| 0_i32).collect::>()) + } + .to_owned_opt(); + u2.decay().offset(0_usize).write(31); + assert!(((u2.decay().offset(0_usize).read()) == 31)); + let mut u3: Option>> = + Ptr::alloc_array((0..2_usize).map(|_| 0_i32).collect::>()) + .reinterpret_cast::() + .to_owned_opt(); + u3.decay().offset(1_usize).write(41); + assert!(((u3.decay().offset(1_usize).read()) == 41)); + let mut u4: Option>> = + Ptr::alloc_array((0..2_usize).map(|_| 0_i32).collect::>()) + .reinterpret_cast::() + .to_owned_opt(); + u4.decay().offset(0_usize).write(53); + assert!(((u4.decay().offset(0_usize).read()) == 53)); + let mut u5: Option>> = Ptr::alloc_array(Box::new([11, 22])).to_owned_opt(); + assert!( + ((u5.decay().offset(0_usize).read()) == 11) && ((u5.decay().offset(1_usize).read()) == 22) + ); + let u6: Value>>> = Rc::new(RefCell::new( + Ptr::alloc_array(Box::new([3, 4])).to_owned_opt(), + )); + assert!( + ((({ (*u6.borrow()).decay().offset(0_usize) }).read()) == 3) + && ((({ (*u6.borrow()).decay().offset(1_usize) }).read()) == 4) + ); + u6.as_pointer() + .write(Ptr::alloc_array(Box::new([7, 8])).to_owned_opt()); + assert!( + ((({ (*u6.borrow()).decay().offset(0_usize) }).read()) == 7) + && ((({ (*u6.borrow()).decay().offset(1_usize) }).read()) == 8) + ); + let mut u7: Option>> = Ptr::alloc_array(Box::new([5, 6])).to_owned_opt(); + assert!( + ((u7.decay().offset(0_usize).read()) == 5) && ((u7.decay().offset(1_usize).read()) == 6) + ); + let u8: Value>>> = Rc::new(RefCell::new( + Ptr::alloc_array((0..3_usize).map(|_| 0_i32).collect::>()).to_owned_opt(), + )); + ({ (*u8.borrow()).decay().offset(2_usize) }).write(61); + assert!(((({ (*u8.borrow()).decay().offset(2_usize) }).read()) == 61)); + u8.as_pointer() + .write(Ptr::alloc_array(Box::new([62, 63])).to_owned_opt()); + assert!( + ((({ (*u8.borrow()).decay().offset(0_usize) }).read()) == 62) + && ((({ (*u8.borrow()).decay().offset(1_usize) }).read()) == 63) + ); + let u9: Value>>> = Rc::new(RefCell::new( + Ptr::alloc_array((0..2_usize).map(|_| 0_i32).collect::>()).to_owned_opt(), + )); + ({ (*u9.borrow()).decay().offset(1_usize) }).write(71); + assert!(((({ (*u9.borrow()).decay().offset(1_usize) }).read()) == 71)); + u9.as_pointer().write( + Ptr::alloc_array((0..2_usize).map(|_| 0_i32).collect::>()).to_owned_opt(), + ); + ({ (*u9.borrow()).decay().offset(1_usize) }).write(72); + assert!(((({ (*u9.borrow()).decay().offset(1_usize) }).read()) == 72)); + let u10: Value>>> = Rc::new(RefCell::new( + { + let mut tmp: Ptr = + Ptr::alloc_array((0..1_usize).map(|_| 0_i32).collect::>()); + elem!(tmp, 0).write(3); + let mut n: i32 = (elem!(tmp, 0).read()); + tmp.delete(); + Ptr::alloc_array((0..(n as usize)).map(|_| 0_i32).collect::>()) + } + .to_owned_opt(), + )); + ({ (*u10.borrow()).decay().offset(2_usize) }).write(81); + assert!(((({ (*u10.borrow()).decay().offset(2_usize) }).read()) == 81)); + u10.as_pointer().write( + { + let mut n: i32 = 4; + Ptr::alloc_array((0..(n as usize)).map(|_| 0_i32).collect::>()) + } + .to_owned_opt(), + ); + ({ (*u10.borrow()).decay().offset(3_usize) }).write(82); + assert!(((({ (*u10.borrow()).decay().offset(3_usize) }).read()) == 82)); + ({ + get_u_after_delete_8( + u10.as_pointer(), + Ptr::alloc_array((0..1_usize).map(|_| 0_i32).collect::>()), + ) + }) + .write(Ptr::alloc_array(Box::new([91, 92, 93])).to_owned_opt()); + assert!( + ((({ (*u10.borrow()).decay().offset(0_usize) }).read()) == 91) + && ((({ (*u10.borrow()).decay().offset(2_usize) }).read()) == 93) + ); + let mut u11: Option>> = Ptr::alloc_array( + (0..(({ size_from_delete_9(Ptr::alloc_array(Box::new([3]))) }) as usize)) + .map(|_| 0_i32) + .collect::>(), + ) + .to_owned_opt(); + u11.decay().offset(2_usize).write(99); + assert!(((u11.decay().offset(2_usize).read()) == 99)); + let vec_u: Value>>>> = Rc::new(RefCell::new(Vec::new())); + { + let mut __tmp_1 = { + Ptr::alloc_array((0..3_usize).map(|_| 0_i32).collect::>()).to_owned_opt() + }; + (*vec_u.borrow_mut()).push(__tmp_1); + }; + ({ (*vec_u.borrow())[0_usize].decay().offset(2_usize) }).write(101); + assert!(((({ (*vec_u.borrow())[0_usize].decay().offset(2_usize) }).read()) == 101)); + let deq_u: Value>>>> = Rc::new(RefCell::new(Vec::new())); + { + let mut __tmp_2 = { + Ptr::alloc_array((0..3_usize).map(|_| 0_i32).collect::>()).to_owned_opt() + }; + (*deq_u.borrow_mut()).push(__tmp_2); + }; + ({ (*deq_u.decay().upgrade().deref()).decay().offset(2_usize) }).write(102); + assert!(((({ (*deq_u.decay().upgrade().deref()).decay().offset(2_usize) }).read()) == 102)); + let pair_u: Value<(Value, Value>>>)> = Rc::new(RefCell::new(( + Rc::new(RefCell::new(1)), + Rc::new(RefCell::new( + Ptr::alloc_array((0..3_usize).map(|_| 0_i32).collect::>()).to_owned_opt(), + )), + ))); + ({ (*(*pair_u.borrow()).1.borrow()).decay().offset(2_usize) }).write(103); + assert!(((({ (*(*pair_u.borrow()).1.borrow()).decay().offset(2_usize) }).read()) == 103)); + let u12: Value>>> = Rc::new(RefCell::new( + Ptr::alloc_array((0..3_usize).map(|_| 0_i32).collect::>()).to_owned_opt(), + )); + ({ (*u12.borrow()).decay().offset(2_usize) }).write(104); + assert!(((({ (*u12.borrow()).decay().offset(2_usize) }).read()) == 104)); + u12.as_pointer().write( + Ptr::alloc_array((0..3_usize).map(|_| 0_i32).collect::>()).to_owned_opt(), + ); + ({ (*u12.borrow()).decay().offset(2_usize) }).write(105); + assert!(((({ (*u12.borrow()).decay().offset(2_usize) }).read()) == 105)); + let mut u13: Option>> = + Ptr::alloc_array((0..3_usize).map(|_| 0_i32).collect::>()).to_owned_opt(); + u13.decay().offset(1_usize).write(106); + assert!(((u13.decay().offset(1_usize).read()) == 106)); + let mut u14: Option>> = if cond { + Ptr::alloc_array(Box::new([107, 108])) + } else { + Ptr::alloc_array(Box::new([109, 110])) + } + .to_owned_opt(); + assert!( + ((u14.decay().offset(0_usize).read()) == 107) + && ((u14.decay().offset(1_usize).read()) == 108) + ); + let mut u15: Option>> = Ptr::alloc_array(Box::new([111, 112])).to_owned_opt(); + assert!( + ((u15.decay().offset(0_usize).read()) == 111) + && ((u15.decay().offset(1_usize).read()) == 112) + ); + let mut u16: Option>> = Ptr::alloc_array(Box::new([113, 114])).to_owned_opt(); + assert!( + ((u16.decay().offset(0_usize).read()) == 113) + && ((u16.decay().offset(1_usize).read()) == 114) + ); + let mut u17: Option>> = Ptr::alloc_array(Box::new([115, 116])).to_owned_opt(); + assert!( + ((u17.decay().offset(0_usize).read()) == 115) + && ((u17.decay().offset(1_usize).read()) == 116) + ); + let mut u18: Option>> = + Ptr::alloc_array((0..3_usize).map(|_| 0_i32).collect::>()).to_owned_opt(); + u18.decay().offset(2_usize).write(117); + assert!(((u18.decay().offset(2_usize).read()) == 117)); + let mut u19: Option]>>> = Ptr::alloc_array(Box::new([ + Ptr::alloc_array(Box::new([1, 2, 3])), + Ptr::alloc_array(Box::new([4, 5])), + ])) + .to_owned_opt(); + assert!( + ((elem!((u19.decay().offset(0_usize).read()), 2).read()) == 3) + && ((elem!((u19.decay().offset(1_usize).read()), 1).read()) == 5) + ); + (u19.decay().offset(0_usize).read()).delete(); + (u19.decay().offset(1_usize).read()).delete(); + printf!(b"ok\n"); + return 0; +} +pub fn __cpp2rust_init_globals() { + let _ = g_byte_dtors_0.with(|_| ()); + let _ = g_byte_sum_1.with(|_| ()); + let _ = g_next_id_2.with(|_| ()); + let _ = g_log_3.with(|_| ()); + let _ = g_log_len_4.with(|_| ()); + let _ = g_empty_ctors_5.with(|_| ()); + let _ = g_empty_dtors_6.with(|_| ()); +} diff --git a/tests/unit/out/unsafe/06_new_array.rs b/tests/unit/out/unsafe/06_new_array.rs index d7881ef69c..9303fd7a46 100644 --- a/tests/unit/out/unsafe/06_new_array.rs +++ b/tests/unit/out/unsafe/06_new_array.rs @@ -12,11 +12,7 @@ pub unsafe fn take_0(p: *mut *mut libc::c_char) -> libc::c_char { { let __p = (*p); if !__p.is_null() { - ::std::mem::drop(Box::from_raw(::std::slice::from_raw_parts_mut( - __p, - libcc2rs::malloc_usable_size(__p as *mut ::libc::c_void) - / ::std::mem::size_of::(), - ))) + libcc2rs::dealloc_array_unsafe(__p); } }; return c; @@ -28,27 +24,18 @@ pub fn main() { } } unsafe fn main_0() -> i32 { - let mut e: *mut i32 = - Box::leak((0..2_usize).map(|_| 0_i32).collect::>()).as_mut_ptr(); + let mut e: *mut i32 = libcc2rs::alloc_array_unsafe::(2_usize, || 0_i32); (*e.offset((0) as isize)) = 6; (*e.offset((1) as isize)) = 7; { let __p = e; if !__p.is_null() { - ::std::mem::drop(Box::from_raw(::std::slice::from_raw_parts_mut( - __p, - libcc2rs::malloc_usable_size(__p as *mut ::libc::c_void) - / ::std::mem::size_of::(), - ))) + libcc2rs::dealloc_array_unsafe(__p); } }; let mut c: libc::c_char = (unsafe { - let mut _p: *mut libc::c_char = Box::leak( - (0..4_usize) - .map(|_| (0 as libc::c_char)) - .collect::>(), - ) - .as_mut_ptr(); + let mut _p: *mut libc::c_char = + libcc2rs::alloc_array_unsafe::(4_usize, || (0 as libc::c_char)); take_0(&mut _p) }); return 0; diff --git a/tests/unit/out/unsafe/cast.rs b/tests/unit/out/unsafe/cast.rs index 0ebeef59cb..8a3a22a77c 100644 --- a/tests/unit/out/unsafe/cast.rs +++ b/tests/unit/out/unsafe/cast.rs @@ -218,23 +218,14 @@ pub unsafe fn over_aligned_3() { ((((&mut w[(1) as usize] as *mut Wide) as *mut Wide as usize).wrapping_sub(iw)) == (::std::mem::size_of::())) ); - let mut h: *mut Wide = Box::leak( - (0..2_usize) - .map(|_| ::default()) - .collect::>(), - ) - .as_mut_ptr(); + let mut h: *mut Wide = libcc2rs::alloc_array_unsafe::(2_usize, || ::default()); assert!( ((((h as usize) as u64).wrapping_rem((::std::mem::align_of::() as u64))) == (0_u64)) ); { let __p = h; if !__p.is_null() { - ::std::mem::drop(Box::from_raw(::std::slice::from_raw_parts_mut( - __p, - libcc2rs::malloc_usable_size(__p as *mut ::libc::c_void) - / ::std::mem::size_of::(), - ))) + libcc2rs::dealloc_array_unsafe(__p); } }; } @@ -394,18 +385,14 @@ pub unsafe fn struct_fields_6() { assert!(((pp) == (&mut pr as *mut Pair))); } pub unsafe fn heap_7() { - let mut h: *mut i32 = Box::leak(Box::new([1, 2, 3])).as_mut_ptr(); + let mut h: *mut i32 = libcc2rs::alloc_array_from_unsafe::([1, 2, 3]); let mut ih: usize = (h as usize); (*(ih as *mut i32).offset((2) as isize)) = 9; assert!(((*h.offset((2) as isize)) == (9))); { let __p = (ih as *mut i32); if !__p.is_null() { - ::std::mem::drop(Box::from_raw(::std::slice::from_raw_parts_mut( - __p, - libcc2rs::malloc_usable_size(__p as *mut ::libc::c_void) - / ::std::mem::size_of::(), - ))) + libcc2rs::dealloc_array_unsafe(__p); } }; let mut l: *mut i64 = diff --git a/tests/unit/out/unsafe/default.rs b/tests/unit/out/unsafe/default.rs index a192846a4e..b3e71cf02e 100644 --- a/tests/unit/out/unsafe/default.rs +++ b/tests/unit/out/unsafe/default.rs @@ -66,52 +66,28 @@ pub fn main() { } } unsafe fn main_0() -> i32 { - let mut default_pointers: *mut Pointers = Box::leak( - (0..10_usize) - .map(|_| ::default()) - .collect::>(), - ) - .as_mut_ptr(); + let mut default_pointers: *mut Pointers = + libcc2rs::alloc_array_unsafe::(10_usize, || ::default()); { let __p = default_pointers; if !__p.is_null() { - ::std::mem::drop(Box::from_raw(::std::slice::from_raw_parts_mut( - __p, - libcc2rs::malloc_usable_size(__p as *mut ::libc::c_void) - / ::std::mem::size_of::(), - ))) + libcc2rs::dealloc_array_unsafe(__p); } }; - let mut small: *mut SmallArrays = Box::leak( - (0..2_usize) - .map(|_| ::default()) - .collect::>(), - ) - .as_mut_ptr(); + let mut small: *mut SmallArrays = + libcc2rs::alloc_array_unsafe::(2_usize, || ::default()); { let __p = small; if !__p.is_null() { - ::std::mem::drop(Box::from_raw(::std::slice::from_raw_parts_mut( - __p, - libcc2rs::malloc_usable_size(__p as *mut ::libc::c_void) - / ::std::mem::size_of::(), - ))) + libcc2rs::dealloc_array_unsafe(__p); } }; - let mut big: *mut BigArray = Box::leak( - (0..2_usize) - .map(|_| ::default()) - .collect::>(), - ) - .as_mut_ptr(); + let mut big: *mut BigArray = + libcc2rs::alloc_array_unsafe::(2_usize, || ::default()); { let __p = big; if !__p.is_null() { - ::std::mem::drop(Box::from_raw(::std::slice::from_raw_parts_mut( - __p, - libcc2rs::malloc_usable_size(__p as *mut ::libc::c_void) - / ::std::mem::size_of::(), - ))) + libcc2rs::dealloc_array_unsafe(__p); } }; return 0; diff --git a/tests/unit/out/unsafe/delete_array_exact_len.rs b/tests/unit/out/unsafe/delete_array_exact_len.rs new file mode 100644 index 0000000000..3ac5c8bd4c --- /dev/null +++ b/tests/unit/out/unsafe/delete_array_exact_len.rs @@ -0,0 +1,843 @@ +extern crate libc; +use libc::*; +extern crate libcc2rs; +use libcc2rs::*; +use std::collections::BTreeMap; +use std::io::{Read, Seek, Write}; +use std::os::fd::{AsFd, FromRawFd, IntoRawFd}; +use std::rc::Rc; +pub static mut g_byte_dtors_0: std::cell::LazyCell = std::cell::LazyCell::new(|| unsafe { 0 }); +pub static mut g_byte_sum_1: std::cell::LazyCell = std::cell::LazyCell::new(|| unsafe { 0 }); +#[repr(C)] +#[derive( + Clone, + VaArg, + FnPtrArg, + ZeroInitializationUnsafe, + MemberwiseUnsafe, + CopyConstructibleUnsafe, + MovableUnsafe, +)] +#[memberwise(copy_assign)] +pub struct Byte { + pub v: u8, +} +impl DefaultConstructibleUnsafe for Byte { + unsafe fn default_constructor(this: *mut Self) { + (&raw mut (*this).v).write(7_u8); + } +} +impl DestructibleUnsafe for Byte { + unsafe fn destroy(this: *mut Self) { + (*std::cell::LazyCell::force_mut(&mut *&raw mut g_byte_dtors_0)).prefix_inc(); + (*std::cell::LazyCell::force_mut(&mut *&raw mut g_byte_sum_1)) += ((*this).v as i32); + } +} +pub static mut g_next_id_2: std::cell::LazyCell = std::cell::LazyCell::new(|| unsafe { 1 }); +pub static mut g_log_3: std::cell::LazyCell<[i32; 32]> = + std::cell::LazyCell::new(|| unsafe { [0_i32; 32] }); +pub static mut g_log_len_4: std::cell::LazyCell = std::cell::LazyCell::new(|| unsafe { 0 }); +#[repr(C)] +#[derive( + Clone, + VaArg, + FnPtrArg, + ZeroInitializationUnsafe, + MemberwiseUnsafe, + CopyConstructibleUnsafe, + MovableUnsafe, +)] +#[memberwise(copy_assign)] +pub struct Small { + pub id: i32, +} +impl DefaultConstructibleUnsafe for Small { + unsafe fn default_constructor(this: *mut Self) { + (&raw mut (*this).id) + .write((*std::cell::LazyCell::force_mut(&mut *&raw mut g_next_id_2)).postfix_inc()); + } +} +impl DestructibleUnsafe for Small { + unsafe fn destroy(this: *mut Self) { + (*std::cell::LazyCell::force_mut(&mut *&raw mut g_log_3)) + [((*std::cell::LazyCell::force_mut(&mut *&raw mut g_log_len_4)).postfix_inc()) + as usize] = (*this).id; + } +} +pub static mut g_empty_ctors_5: std::cell::LazyCell = + std::cell::LazyCell::new(|| unsafe { 0 }); +pub static mut g_empty_dtors_6: std::cell::LazyCell = + std::cell::LazyCell::new(|| unsafe { 0 }); +#[repr(C)] +#[derive( + Clone, + VaArg, + FnPtrArg, + ZeroInitializationUnsafe, + MemberwiseUnsafe, + CopyConstructibleUnsafe, + MovableUnsafe, +)] +#[memberwise(copy_assign)] +pub struct Empty {} +impl DefaultConstructibleUnsafe for Empty { + unsafe fn default_constructor(this: *mut Self) { + (*std::cell::LazyCell::force_mut(&mut *&raw mut g_empty_ctors_5)).prefix_inc(); + } +} +impl DestructibleUnsafe for Empty { + unsafe fn destroy(this: *mut Self) { + (*std::cell::LazyCell::force_mut(&mut *&raw mut g_empty_dtors_6)).prefix_inc(); + } +} +#[repr(C)] +#[derive( + Clone, + VaArg, + FnPtrArg, + ZeroInitializationUnsafe, + DestructibleUnsafe, + MemberwiseUnsafe, + CopyConstructibleUnsafe, + SwappableUnsafe, +)] +#[memberwise(move_constructor, copy_assign, move_assign)] +pub struct WithVec { + pub items: Vec, +} +impl WithVec { + pub unsafe fn first(this: *const Self) -> i32 { + return (&(*this)).items[(0_usize)]; + } +} +impl DefaultConstructibleUnsafe for WithVec { + unsafe fn default_constructor(this: *mut Self) { + (&raw mut (*this).items).write(Vec::new()); + { + let mut __tmp_0: i32 = 42; + (*this).items.push_moved(&mut __tmp_0) + }; + } +} +impl Default for WithVec { + fn default() -> Self { + unsafe { + { + let mut __v: WithVec = ::zero_init(); + DefaultConstructibleUnsafe::default_constructor(&raw mut __v); + __v + } + } + } +} +pub unsafe fn check_and_delete_7(mut p: *mut i32) -> bool { + let mut ok: bool = !((p).is_null()); + { + let __p = p; + if !__p.is_null() { + libcc2rs::dealloc_array_unsafe(__p); + } + }; + return ok; +} +pub unsafe fn get_u_after_delete_8( + u: *mut Option>, + mut raw_: *mut i32, +) -> *mut Option> { + { + let __p = raw_; + if !__p.is_null() { + libcc2rs::dealloc_array_unsafe(__p); + } + }; + return u; +} +pub unsafe fn size_from_delete_9(mut p: *mut i32) -> i32 { + let mut n: i32 = (*p.offset((0) as isize)); + { + let __p = p; + if !__p.is_null() { + libcc2rs::dealloc_array_unsafe(__p); + } + }; + return n; +} +pub fn main() { + unsafe { + __cpp2rust_init_globals(); + libcc2rs::cpp2rust_exit(main_0() as i32); + } +} +unsafe fn main_0() -> i32 { + let mut b1: *mut Byte = + libcc2rs::alloc_array_unsafe::(1_usize, || ::default_constructed()); + { + let __p = b1; + if !__p.is_null() { + for __i in (0..libcc2rs::array_len_unsafe(__p)).rev() { + DestructibleUnsafe::destroy(__p.add(__i)); + } + libcc2rs::dealloc_array_unsafe(__p); + } + }; + assert!(((*std::cell::LazyCell::force_mut(&mut *&raw mut g_byte_dtors_0)) == (1))); + assert!(((*std::cell::LazyCell::force_mut(&mut *&raw mut g_byte_sum_1)) == (7))); + let mut b3: *mut Byte = + libcc2rs::alloc_array_unsafe::(3_usize, || ::default_constructed()); + { + let __p = b3; + if !__p.is_null() { + for __i in (0..libcc2rs::array_len_unsafe(__p)).rev() { + DestructibleUnsafe::destroy(__p.add(__i)); + } + libcc2rs::dealloc_array_unsafe(__p); + } + }; + assert!(((*std::cell::LazyCell::force_mut(&mut *&raw mut g_byte_dtors_0)) == (4))); + assert!(((*std::cell::LazyCell::force_mut(&mut *&raw mut g_byte_sum_1)) == (28))); + let mut z1: *mut i32 = libcc2rs::alloc_array_unsafe::(0_usize, || 0_i32); + let mut z2: *mut i32 = libcc2rs::alloc_array_unsafe::(0_usize, || 0_i32); + assert!(((!((z1).is_null())) && (!((z2).is_null()))) && ((z1) != (z2))); + { + let __p = z1; + if !__p.is_null() { + libcc2rs::dealloc_array_unsafe(__p); + } + }; + { + let __p = z2; + if !__p.is_null() { + libcc2rs::dealloc_array_unsafe(__p); + } + }; + let mut zs: *mut Small = + libcc2rs::alloc_array_unsafe::(0_usize, || ::default_constructed()); + assert!(!((zs).is_null())); + { + let __p = zs; + if !__p.is_null() { + for __i in (0..libcc2rs::array_len_unsafe(__p)).rev() { + DestructibleUnsafe::destroy(__p.add(__i)); + } + libcc2rs::dealloc_array_unsafe(__p); + } + }; + assert!( + ((*std::cell::LazyCell::force_mut(&mut *&raw mut g_next_id_2)) == (1)) + && ((*std::cell::LazyCell::force_mut(&mut *&raw mut g_log_len_4)) == (0)) + ); + let mut np: *mut Small = std::ptr::null_mut(); + { + let __p = np; + if !__p.is_null() { + for __i in (0..libcc2rs::array_len_unsafe(__p)).rev() { + DestructibleUnsafe::destroy(__p.add(__i)); + } + libcc2rs::dealloc_array_unsafe(__p); + } + }; + assert!(((*std::cell::LazyCell::force_mut(&mut *&raw mut g_log_len_4)) == (0))); + let mut s1: *mut Small = + libcc2rs::alloc_array_unsafe::(1_usize, || ::default_constructed()); + { + let __p = s1; + if !__p.is_null() { + for __i in (0..libcc2rs::array_len_unsafe(__p)).rev() { + DestructibleUnsafe::destroy(__p.add(__i)); + } + libcc2rs::dealloc_array_unsafe(__p); + } + }; + let mut s3: *mut Small = + libcc2rs::alloc_array_unsafe::(3_usize, || ::default_constructed()); + { + let __p = s3; + if !__p.is_null() { + for __i in (0..libcc2rs::array_len_unsafe(__p)).rev() { + DestructibleUnsafe::destroy(__p.add(__i)); + } + libcc2rs::dealloc_array_unsafe(__p); + } + }; + assert!(((*std::cell::LazyCell::force_mut(&mut *&raw mut g_log_len_4)) == (4))); + assert!( + (((((*std::cell::LazyCell::force_mut(&mut *&raw mut g_log_3))[(0) as usize]) == (1)) + && (((*std::cell::LazyCell::force_mut(&mut *&raw mut g_log_3))[(1) as usize]) == (4))) + && (((*std::cell::LazyCell::force_mut(&mut *&raw mut g_log_3))[(2) as usize]) == (3))) + && (((*std::cell::LazyCell::force_mut(&mut *&raw mut g_log_3))[(3) as usize]) == (2)) + ); + let mut e0: *mut Empty = + libcc2rs::alloc_array_unsafe::(0_usize, || ::default_constructed()); + { + let __p = e0; + if !__p.is_null() { + for __i in (0..libcc2rs::array_len_unsafe(__p)).rev() { + DestructibleUnsafe::destroy(__p.add(__i)); + } + libcc2rs::dealloc_array_unsafe(__p); + } + }; + assert!( + ((*std::cell::LazyCell::force_mut(&mut *&raw mut g_empty_ctors_5)) == (0)) + && ((*std::cell::LazyCell::force_mut(&mut *&raw mut g_empty_dtors_6)) == (0)) + ); + let mut e4: *mut Empty = + libcc2rs::alloc_array_unsafe::(4_usize, || ::default_constructed()); + { + let __p = e4; + if !__p.is_null() { + for __i in (0..libcc2rs::array_len_unsafe(__p)).rev() { + DestructibleUnsafe::destroy(__p.add(__i)); + } + libcc2rs::dealloc_array_unsafe(__p); + } + }; + assert!( + ((*std::cell::LazyCell::force_mut(&mut *&raw mut g_empty_ctors_5)) == (4)) + && ((*std::cell::LazyCell::force_mut(&mut *&raw mut g_empty_dtors_6)) == (4)) + ); + let mut cs: *const Small = + (libcc2rs::alloc_array_unsafe::(2_usize, || ::default_constructed())) + .cast_const(); + { + let __p = cs; + if !__p.is_null() { + for __i in (0..libcc2rs::array_len_unsafe(__p.cast_mut())).rev() { + DestructibleUnsafe::destroy(__p.cast_mut().add(__i)); + } + libcc2rs::dealloc_array_unsafe(__p.cast_mut()); + } + }; + assert!( + (((*std::cell::LazyCell::force_mut(&mut *&raw mut g_log_len_4)) == (6)) + && (((*std::cell::LazyCell::force_mut(&mut *&raw mut g_log_3))[(4) as usize]) == (6))) + && (((*std::cell::LazyCell::force_mut(&mut *&raw mut g_log_3))[(5) as usize]) == (5)) + ); + let mut a2d: *mut [Small; 2] = libcc2rs::alloc_array_unsafe::<[Small; 2]>(2_usize, || { + std::array::from_fn::<_, 2, _>(|_| ::default_constructed()) + }); + { + let __p = a2d; + if !__p.is_null() { + for __i in (0..libcc2rs::array_len_unsafe(__p)).rev() { + DestructibleUnsafe::destroy(__p.add(__i)); + } + libcc2rs::dealloc_array_unsafe(__p); + } + }; + assert!( + (((((*std::cell::LazyCell::force_mut(&mut *&raw mut g_log_len_4)) == (10)) + && (((*std::cell::LazyCell::force_mut(&mut *&raw mut g_log_3))[(6) as usize]) + == (10))) + && (((*std::cell::LazyCell::force_mut(&mut *&raw mut g_log_3))[(7) as usize]) == (9))) + && (((*std::cell::LazyCell::force_mut(&mut *&raw mut g_log_3))[(8) as usize]) == (8))) + && (((*std::cell::LazyCell::force_mut(&mut *&raw mut g_log_3))[(9) as usize]) == (7)) + ); + let mut wv: *mut WithVec = + libcc2rs::alloc_array_unsafe::(2_usize, || ::default()); + assert!( + ((unsafe { WithVec::first(&raw const (*wv.offset((0) as isize)),) }) == (42)) + && ((unsafe { WithVec::first(&raw const (*wv.offset((1) as isize)),) }) == (42)) + ); + { + let __p = wv; + if !__p.is_null() { + libcc2rs::dealloc_array_unsafe(__p); + } + }; + let mut ap: *mut i32 = std::ptr::null_mut(); + ap = libcc2rs::alloc_array_unsafe::(3_usize, || 0_i32); + (*ap.offset((2) as isize)) = 9; + assert!(((*ap.offset((2) as isize)) == (9))); + { + let __p = ap; + if !__p.is_null() { + libcc2rs::dealloc_array_unsafe(__p); + } + }; + { + let __p = + (libcc2rs::alloc_array_unsafe::(1_usize, || ::default_constructed())); + if !__p.is_null() { + for __i in (0..libcc2rs::array_len_unsafe(__p)).rev() { + DestructibleUnsafe::destroy(__p.add(__i)); + } + libcc2rs::dealloc_array_unsafe(__p); + } + }; + assert!( + ((*std::cell::LazyCell::force_mut(&mut *&raw mut g_log_len_4)) == (11)) + && (((*std::cell::LazyCell::force_mut(&mut *&raw mut g_log_3))[(10) as usize]) == (11)) + ); + let mut ci: *mut i32 = libcc2rs::alloc_array_from_unsafe::([10, 20, 0_i32, 0_i32]); + assert!( + ((((*ci.offset((0) as isize)) == (10)) && ((*ci.offset((1) as isize)) == (20))) + && ((*ci.offset((2) as isize)) == (0))) + && ((*ci.offset((3) as isize)) == (0)) + ); + { + let __p = ci; + if !__p.is_null() { + libcc2rs::dealloc_array_unsafe(__p); + } + }; + let mut cond: bool = true; + let mut u1: Option> = Some(Box::from_raw(if cond { + Box::leak((0..2_usize).map(|_| 0_i32).collect::>()) + } else { + Box::leak((0..3_usize).map(|_| 0_i32).collect::>()) + })); + (*u1.as_deref() + .map_or(::std::ptr::null_mut(), |s| s.as_ptr() as *mut i32) + .add(1_usize)) = 17; + assert!( + ((*u1 + .as_deref() + .map_or(::std::ptr::null_mut(), |s| s.as_ptr() as *mut i32) + .add(1_usize)) + == (17)) + ); + u1 = Some(Box::from_raw(if !(cond) { + Box::leak((0..2_usize).map(|_| 0_i32).collect::>()) + } else { + Box::leak((0..3_usize).map(|_| 0_i32).collect::>()) + })); + (*u1.as_deref() + .map_or(::std::ptr::null_mut(), |s| s.as_ptr() as *mut i32) + .add(2_usize)) = 29; + assert!( + ((*u1 + .as_deref() + .map_or(::std::ptr::null_mut(), |s| s.as_ptr() as *mut i32) + .add(2_usize)) + == (29)) + ); + let mut u2: Option> = Some(Box::from_raw( + if (unsafe { check_and_delete_7(libcc2rs::alloc_array_unsafe::(1_usize, || 0_i32)) }) { + Box::leak((0..2_usize).map(|_| 0_i32).collect::>()) + } else { + Box::leak((0..3_usize).map(|_| 0_i32).collect::>()) + }, + )); + (*u2.as_deref() + .map_or(::std::ptr::null_mut(), |s| s.as_ptr() as *mut i32) + .add(0_usize)) = 31; + assert!( + ((*u2 + .as_deref() + .map_or(::std::ptr::null_mut(), |s| s.as_ptr() as *mut i32) + .add(0_usize)) + == (31)) + ); + let mut u3: Option> = Some(Box::from_raw(Box::leak( + (0..2_usize).map(|_| 0_i32).collect::>(), + ))); + (*u3.as_deref() + .map_or(::std::ptr::null_mut(), |s| s.as_ptr() as *mut i32) + .add(1_usize)) = 41; + assert!( + ((*u3 + .as_deref() + .map_or(::std::ptr::null_mut(), |s| s.as_ptr() as *mut i32) + .add(1_usize)) + == (41)) + ); + let mut u4: Option> = Some(Box::from_raw(Box::leak( + (0..2_usize).map(|_| 0_i32).collect::>(), + ))); + (*u4.as_deref() + .map_or(::std::ptr::null_mut(), |s| s.as_ptr() as *mut i32) + .add(0_usize)) = 53; + assert!( + ((*u4 + .as_deref() + .map_or(::std::ptr::null_mut(), |s| s.as_ptr() as *mut i32) + .add(0_usize)) + == (53)) + ); + let mut u5: Option> = Some(Box::from_raw(Box::leak(Box::new([11, 22])))); + assert!( + ((*u5 + .as_deref() + .map_or(::std::ptr::null_mut(), |s| s.as_ptr() as *mut i32) + .add(0_usize)) + == (11)) + && ((*u5 + .as_deref() + .map_or(::std::ptr::null_mut(), |s| s.as_ptr() as *mut i32) + .add(1_usize)) + == (22)) + ); + let mut u6: Option> = Some(Box::from_raw(Box::leak(Box::new([3, 4])))); + assert!( + ((*u6 + .as_deref() + .map_or(::std::ptr::null_mut(), |s| s.as_ptr() as *mut i32) + .add(0_usize)) + == (3)) + && ((*u6 + .as_deref() + .map_or(::std::ptr::null_mut(), |s| s.as_ptr() as *mut i32) + .add(1_usize)) + == (4)) + ); + u6 = Some(Box::from_raw(Box::leak(Box::new([7, 8])))); + assert!( + ((*u6 + .as_deref() + .map_or(::std::ptr::null_mut(), |s| s.as_ptr() as *mut i32) + .add(0_usize)) + == (7)) + && ((*u6 + .as_deref() + .map_or(::std::ptr::null_mut(), |s| s.as_ptr() as *mut i32) + .add(1_usize)) + == (8)) + ); + let mut u7: Option> = Some(Box::from_raw(Box::leak(Box::new([5, 6])))); + assert!( + ((*u7 + .as_deref() + .map_or(::std::ptr::null_mut(), |s| s.as_ptr() as *mut i32) + .add(0_usize)) + == (5)) + && ((*u7 + .as_deref() + .map_or(::std::ptr::null_mut(), |s| s.as_ptr() as *mut i32) + .add(1_usize)) + == (6)) + ); + let mut u8: Option> = Some(Box::from_raw(Box::leak( + (0..3_usize).map(|_| 0_i32).collect::>(), + ))); + (*u8.as_deref() + .map_or(::std::ptr::null_mut(), |s| s.as_ptr() as *mut i32) + .add(2_usize)) = 61; + assert!( + ((*u8 + .as_deref() + .map_or(::std::ptr::null_mut(), |s| s.as_ptr() as *mut i32) + .add(2_usize)) + == (61)) + ); + u8 = Some(Box::from_raw(Box::leak(Box::new([62, 63])))); + assert!( + ((*u8 + .as_deref() + .map_or(::std::ptr::null_mut(), |s| s.as_ptr() as *mut i32) + .add(0_usize)) + == (62)) + && ((*u8 + .as_deref() + .map_or(::std::ptr::null_mut(), |s| s.as_ptr() as *mut i32) + .add(1_usize)) + == (63)) + ); + let mut u9: Option> = Some(Box::from_raw(Box::leak( + (0..2_usize).map(|_| 0_i32).collect::>(), + ))); + (*u9.as_deref() + .map_or(::std::ptr::null_mut(), |s| s.as_ptr() as *mut i32) + .add(1_usize)) = 71; + assert!( + ((*u9 + .as_deref() + .map_or(::std::ptr::null_mut(), |s| s.as_ptr() as *mut i32) + .add(1_usize)) + == (71)) + ); + u9 = Some(Box::from_raw(Box::leak( + (0..2_usize).map(|_| 0_i32).collect::>(), + ))); + (*u9.as_deref() + .map_or(::std::ptr::null_mut(), |s| s.as_ptr() as *mut i32) + .add(1_usize)) = 72; + assert!( + ((*u9 + .as_deref() + .map_or(::std::ptr::null_mut(), |s| s.as_ptr() as *mut i32) + .add(1_usize)) + == (72)) + ); + let mut u10: Option> = Some(Box::from_raw({ + let mut tmp: *mut i32 = libcc2rs::alloc_array_unsafe::(1_usize, || 0_i32); + (*tmp.offset((0) as isize)) = 3; + let mut n: i32 = (*tmp.offset((0) as isize)); + { + let __p = tmp; + if !__p.is_null() { + libcc2rs::dealloc_array_unsafe(__p); + } + }; + Box::leak((0..(n as usize)).map(|_| 0_i32).collect::>()) + })); + (*u10 + .as_deref() + .map_or(::std::ptr::null_mut(), |s| s.as_ptr() as *mut i32) + .add(2_usize)) = 81; + assert!( + ((*u10 + .as_deref() + .map_or(::std::ptr::null_mut(), |s| s.as_ptr() as *mut i32) + .add(2_usize)) + == (81)) + ); + u10 = Some(Box::from_raw({ + let mut n: i32 = 4; + Box::leak((0..(n as usize)).map(|_| 0_i32).collect::>()) + })); + (*u10 + .as_deref() + .map_or(::std::ptr::null_mut(), |s| s.as_ptr() as *mut i32) + .add(3_usize)) = 82; + assert!( + ((*u10 + .as_deref() + .map_or(::std::ptr::null_mut(), |s| s.as_ptr() as *mut i32) + .add(3_usize)) + == (82)) + ); + (*(unsafe { + get_u_after_delete_8( + &mut u10, + libcc2rs::alloc_array_unsafe::(1_usize, || 0_i32), + ) + })) = Some(Box::from_raw(Box::leak(Box::new([91, 92, 93])))); + assert!( + ((*u10 + .as_deref() + .map_or(::std::ptr::null_mut(), |s| s.as_ptr() as *mut i32) + .add(0_usize)) + == (91)) + && ((*u10 + .as_deref() + .map_or(::std::ptr::null_mut(), |s| s.as_ptr() as *mut i32) + .add(2_usize)) + == (93)) + ); + let mut u11: Option> = Some(Box::from_raw(Box::leak( + (0..((unsafe { size_from_delete_9(libcc2rs::alloc_array_from_unsafe::([3])) }) + as usize)) + .map(|_| 0_i32) + .collect::>(), + ))); + (*u11 + .as_deref() + .map_or(::std::ptr::null_mut(), |s| s.as_ptr() as *mut i32) + .add(2_usize)) = 99; + assert!( + ((*u11 + .as_deref() + .map_or(::std::ptr::null_mut(), |s| s.as_ptr() as *mut i32) + .add(2_usize)) + == (99)) + ); + let mut vec_u: Vec>> = Vec::new(); + vec_u.push_mut(Some(Box::from_raw(Box::leak( + (0..3_usize).map(|_| 0_i32).collect::>(), + )))); + (*vec_u[(0_usize)] + .as_deref() + .map_or(::std::ptr::null_mut(), |s| s.as_ptr() as *mut i32) + .add(2_usize)) = 101; + assert!( + ((*vec_u[(0_usize)] + .as_deref() + .map_or(::std::ptr::null_mut(), |s| s.as_ptr() as *mut i32) + .add(2_usize)) + == (101)) + ); + let mut deq_u: Vec>> = Vec::new(); + deq_u.push_mut(Some(Box::from_raw(Box::leak( + (0..3_usize).map(|_| 0_i32).collect::>(), + )))); + (*deq_u[0] + .as_deref() + .map_or(::std::ptr::null_mut(), |s| s.as_ptr() as *mut i32) + .add(2_usize)) = 102; + assert!( + ((*deq_u[0] + .as_deref() + .map_or(::std::ptr::null_mut(), |s| s.as_ptr() as *mut i32) + .add(2_usize)) + == (102)) + ); + let mut pair_u: (i32, Option>) = ( + 1, + Some(Box::from_raw(Box::leak( + (0..3_usize).map(|_| 0_i32).collect::>(), + ))), + ); + (*pair_u + .1 + .as_deref() + .map_or(::std::ptr::null_mut(), |s| s.as_ptr() as *mut i32) + .add(2_usize)) = 103; + assert!( + ((*pair_u + .1 + .as_deref() + .map_or(::std::ptr::null_mut(), |s| s.as_ptr() as *mut i32) + .add(2_usize)) + == (103)) + ); + let mut u12: Option> = Some(Box::from_raw(Box::leak( + (0..3_usize).map(|_| 0_i32).collect::>(), + ))); + (*u12 + .as_deref() + .map_or(::std::ptr::null_mut(), |s| s.as_ptr() as *mut i32) + .add(2_usize)) = 104; + assert!( + ((*u12 + .as_deref() + .map_or(::std::ptr::null_mut(), |s| s.as_ptr() as *mut i32) + .add(2_usize)) + == (104)) + ); + u12 = Some(Box::from_raw(Box::leak( + (0..3_usize).map(|_| 0_i32).collect::>(), + ))); + (*u12 + .as_deref() + .map_or(::std::ptr::null_mut(), |s| s.as_ptr() as *mut i32) + .add(2_usize)) = 105; + assert!( + ((*u12 + .as_deref() + .map_or(::std::ptr::null_mut(), |s| s.as_ptr() as *mut i32) + .add(2_usize)) + == (105)) + ); + let mut u13: Option> = Some(Box::from_raw(Box::leak( + (0..3_usize).map(|_| 0_i32).collect::>(), + ))); + (*u13 + .as_deref() + .map_or(::std::ptr::null_mut(), |s| s.as_ptr() as *mut i32) + .add(1_usize)) = 106; + assert!( + ((*u13 + .as_deref() + .map_or(::std::ptr::null_mut(), |s| s.as_ptr() as *mut i32) + .add(1_usize)) + == (106)) + ); + let mut u14: Option> = Some(Box::from_raw(if cond { + Box::leak(Box::new([107, 108])) + } else { + Box::leak(Box::new([109, 110])) + })); + assert!( + ((*u14 + .as_deref() + .map_or(::std::ptr::null_mut(), |s| s.as_ptr() as *mut i32) + .add(0_usize)) + == (107)) + && ((*u14 + .as_deref() + .map_or(::std::ptr::null_mut(), |s| s.as_ptr() as *mut i32) + .add(1_usize)) + == (108)) + ); + let mut u15: Option> = Some(Box::from_raw(Box::leak(Box::new([111, 112])))); + assert!( + ((*u15 + .as_deref() + .map_or(::std::ptr::null_mut(), |s| s.as_ptr() as *mut i32) + .add(0_usize)) + == (111)) + && ((*u15 + .as_deref() + .map_or(::std::ptr::null_mut(), |s| s.as_ptr() as *mut i32) + .add(1_usize)) + == (112)) + ); + let mut u16: Option> = Some(Box::from_raw(Box::leak(Box::new([113, 114])))); + assert!( + ((*u16 + .as_deref() + .map_or(::std::ptr::null_mut(), |s| s.as_ptr() as *mut i32) + .add(0_usize)) + == (113)) + && ((*u16 + .as_deref() + .map_or(::std::ptr::null_mut(), |s| s.as_ptr() as *mut i32) + .add(1_usize)) + == (114)) + ); + let mut u17: Option> = Some(Box::from_raw(Box::leak(Box::new([115, 116])))); + assert!( + ((*u17 + .as_deref() + .map_or(::std::ptr::null_mut(), |s| s.as_ptr() as *mut i32) + .add(0_usize)) + == (115)) + && ((*u17 + .as_deref() + .map_or(::std::ptr::null_mut(), |s| s.as_ptr() as *mut i32) + .add(1_usize)) + == (116)) + ); + let mut u18: Option> = Some(Box::from_raw(Box::leak( + (0..3_usize).map(|_| 0_i32).collect::>(), + ))); + (*u18 + .as_deref() + .map_or(::std::ptr::null_mut(), |s| s.as_ptr() as *mut i32) + .add(2_usize)) = 117; + assert!( + ((*u18 + .as_deref() + .map_or(::std::ptr::null_mut(), |s| s.as_ptr() as *mut i32) + .add(2_usize)) + == (117)) + ); + let mut u19: Option> = Some(Box::from_raw(Box::leak(Box::new([ + libcc2rs::alloc_array_from_unsafe::([1, 2, 3]), + libcc2rs::alloc_array_from_unsafe::([4, 5]), + ])))); + assert!( + ((*(*u19 + .as_deref() + .map_or(::std::ptr::null_mut(), |s| s.as_ptr() as *mut *mut i32) + .add(0_usize)) + .offset((2) as isize)) + == (3)) + && ((*(*u19 + .as_deref() + .map_or(::std::ptr::null_mut(), |s| s.as_ptr() as *mut *mut i32) + .add(1_usize)) + .offset((1) as isize)) + == (5)) + ); + { + let __p = (*u19 + .as_deref() + .map_or(::std::ptr::null_mut(), |s| s.as_ptr() as *mut *mut i32) + .add(0_usize)); + if !__p.is_null() { + libcc2rs::dealloc_array_unsafe(__p); + } + }; + { + let __p = (*u19 + .as_deref() + .map_or(::std::ptr::null_mut(), |s| s.as_ptr() as *mut *mut i32) + .add(1_usize)); + if !__p.is_null() { + libcc2rs::dealloc_array_unsafe(__p); + } + }; + (unsafe { libc::printf(c"ok\n".as_ptr() as *const libc::c_char) }); + return 0; +} +pub unsafe fn __cpp2rust_init_globals() { + std::cell::LazyCell::force(&*&raw const g_byte_dtors_0); + std::cell::LazyCell::force(&*&raw const g_byte_sum_1); + std::cell::LazyCell::force(&*&raw const g_next_id_2); + std::cell::LazyCell::force(&*&raw const g_log_3); + std::cell::LazyCell::force(&*&raw const g_log_len_4); + std::cell::LazyCell::force(&*&raw const g_empty_ctors_5); + std::cell::LazyCell::force(&*&raw const g_empty_dtors_6); +} diff --git a/tests/unit/out/unsafe/delete_array_order.rs b/tests/unit/out/unsafe/delete_array_order.rs index 37887d77ab..0a10a5139c 100644 --- a/tests/unit/out/unsafe/delete_array_order.rs +++ b/tests/unit/out/unsafe/delete_array_order.rs @@ -40,7 +40,7 @@ pub fn main() { } } unsafe fn main_0() -> i32 { - let mut a: *mut Element = Box::leak(Box::new([ + let mut a: *mut Element = libcc2rs::alloc_array_from_unsafe::([ Element { id: 1_i64, value: 10_i64, @@ -53,22 +53,14 @@ unsafe fn main_0() -> i32 { id: 3_i64, value: 30_i64, }, - ])) - .as_mut_ptr(); + ]); { let __p = a; if !__p.is_null() { - for __i in (0..libcc2rs::malloc_usable_size(__p as *mut ::libc::c_void) - / ::std::mem::size_of::()) - .rev() - { + for __i in (0..libcc2rs::array_len_unsafe(__p)).rev() { DestructibleUnsafe::destroy(__p.add(__i)); } - ::std::mem::drop(Box::from_raw(::std::slice::from_raw_parts_mut( - __p, - libcc2rs::malloc_usable_size(__p as *mut ::libc::c_void) - / ::std::mem::size_of::(), - ))) + libcc2rs::dealloc_array_unsafe(__p); } }; (unsafe { libc::printf(c"\n".as_ptr() as *const libc::c_char) }); diff --git a/tests/unit/out/unsafe/immutable-deref-on-func-call.rs b/tests/unit/out/unsafe/immutable-deref-on-func-call.rs index f3768f61ff..244fc1fec2 100644 --- a/tests/unit/out/unsafe/immutable-deref-on-func-call.rs +++ b/tests/unit/out/unsafe/immutable-deref-on-func-call.rs @@ -32,12 +32,7 @@ pub fn main() { } } unsafe fn main_0() -> i32 { - let mut arr: *mut Item = Box::leak( - (0..2_usize) - .map(|_| ::default()) - .collect::>(), - ) - .as_mut_ptr(); + let mut arr: *mut Item = libcc2rs::alloc_array_unsafe::(2_usize, || ::default()); (*arr.offset((0) as isize)).value = 1; (*arr.offset((1) as isize)).value = 2; (unsafe { @@ -49,11 +44,7 @@ unsafe fn main_0() -> i32 { { let __p = arr; if !__p.is_null() { - ::std::mem::drop(Box::from_raw(::std::slice::from_raw_parts_mut( - __p, - libcc2rs::malloc_usable_size(__p as *mut ::libc::c_void) - / ::std::mem::size_of::(), - ))) + libcc2rs::dealloc_array_unsafe(__p); } }; assert!(((result) == (11))); diff --git a/tests/unit/out/unsafe/memset.rs b/tests/unit/out/unsafe/memset.rs index d5f8fe1e9d..d1b4cd0d8e 100644 --- a/tests/unit/out/unsafe/memset.rs +++ b/tests/unit/out/unsafe/memset.rs @@ -14,8 +14,7 @@ pub fn main() { } unsafe fn main_0() -> i32 { let N: i32 = 3; - let mut arr: *mut i32 = - Box::leak((0..(N as usize)).map(|_| 0_i32).collect::>()).as_mut_ptr(); + let mut arr: *mut i32 = libcc2rs::alloc_array_unsafe::((N as usize), || 0_i32); { let mut __tmp_0 = { (arr as *mut ::libc::c_void) }; let byte_0 = __tmp_0 as *mut u8; @@ -37,11 +36,7 @@ unsafe fn main_0() -> i32 { { let __p = arr; if !__p.is_null() { - ::std::mem::drop(Box::from_raw(::std::slice::from_raw_parts_mut( - __p, - libcc2rs::malloc_usable_size(__p as *mut ::libc::c_void) - / ::std::mem::size_of::(), - ))) + libcc2rs::dealloc_array_unsafe(__p); } }; assert!(((sum) == (50529027))); diff --git a/tests/unit/out/unsafe/new_alloc_array.rs b/tests/unit/out/unsafe/new_alloc_array.rs index cecf376704..83c477dc57 100644 --- a/tests/unit/out/unsafe/new_alloc_array.rs +++ b/tests/unit/out/unsafe/new_alloc_array.rs @@ -13,8 +13,7 @@ pub fn main() { } } unsafe fn main_0() -> i32 { - let mut array: *mut i32 = - Box::leak((0..100_usize).map(|_| 0_i32).collect::>()).as_mut_ptr(); + let mut array: *mut i32 = libcc2rs::alloc_array_unsafe::(100_usize, || 0_i32); { let mut __tmp_0 = { (array as *mut ::libc::c_void) }; let byte_0 = __tmp_0 as *mut u8; @@ -47,11 +46,7 @@ unsafe fn main_0() -> i32 { { let __p = p2; if !__p.is_null() { - ::std::mem::drop(Box::from_raw(::std::slice::from_raw_parts_mut( - __p, - libcc2rs::malloc_usable_size(__p as *mut ::libc::c_void) - / ::std::mem::size_of::(), - ))) + libcc2rs::dealloc_array_unsafe(__p); } }; assert!(((out) == (99))); diff --git a/tests/unit/out/unsafe/new_array.rs b/tests/unit/out/unsafe/new_array.rs index d552aaf792..52da6e986e 100644 --- a/tests/unit/out/unsafe/new_array.rs +++ b/tests/unit/out/unsafe/new_array.rs @@ -26,20 +26,14 @@ pub fn main() { } } unsafe fn main_0() -> i32 { - let mut array: *mut i32 = - Box::leak((0..100_usize).map(|_| 0_i32).collect::>()).as_mut_ptr(); + let mut array: *mut i32 = libcc2rs::alloc_array_unsafe::(100_usize, || 0_i32); { let __p = array; if !__p.is_null() { - ::std::mem::drop(Box::from_raw(::std::slice::from_raw_parts_mut( - __p, - libcc2rs::malloc_usable_size(__p as *mut ::libc::c_void) - / ::std::mem::size_of::(), - ))) + libcc2rs::dealloc_array_unsafe(__p); } }; - let mut filled: *mut i32 = - Box::leak((0..4_usize).map(|_| 0_i32).collect::>()).as_mut_ptr(); + let mut filled: *mut i32 = libcc2rs::alloc_array_unsafe::(4_usize, || 0_i32); { let mut i: i32 = 0; 'loop_: while ((i) < (4)) { @@ -55,11 +49,7 @@ unsafe fn main_0() -> i32 { { let __p = filled; if !__p.is_null() { - ::std::mem::drop(Box::from_raw(::std::slice::from_raw_parts_mut( - __p, - libcc2rs::malloc_usable_size(__p as *mut ::libc::c_void) - / ::std::mem::size_of::(), - ))) + libcc2rs::dealloc_array_unsafe(__p); } }; return 0; diff --git a/tests/unit/out/unsafe/new_array_var_size.rs b/tests/unit/out/unsafe/new_array_var_size.rs index 9455c52624..cc600e49cf 100644 --- a/tests/unit/out/unsafe/new_array_var_size.rs +++ b/tests/unit/out/unsafe/new_array_var_size.rs @@ -14,29 +14,19 @@ pub fn main() { } unsafe fn main_0() -> i32 { let mut N: i32 = 5; - let mut A: *mut i32 = - Box::leak((0..(N as usize)).map(|_| 0_i32).collect::>()).as_mut_ptr(); + let mut A: *mut i32 = libcc2rs::alloc_array_unsafe::((N as usize), || 0_i32); { let __p = A; if !__p.is_null() { - ::std::mem::drop(Box::from_raw(::std::slice::from_raw_parts_mut( - __p, - libcc2rs::malloc_usable_size(__p as *mut ::libc::c_void) - / ::std::mem::size_of::(), - ))) + libcc2rs::dealloc_array_unsafe(__p); } }; let N2: *mut i32 = &mut N; - let mut A2: *mut i32 = - Box::leak((0..((*N2) as usize)).map(|_| 0_i32).collect::>()).as_mut_ptr(); + let mut A2: *mut i32 = libcc2rs::alloc_array_unsafe::(((*N2) as usize), || 0_i32); { let __p = A2; if !__p.is_null() { - ::std::mem::drop(Box::from_raw(::std::slice::from_raw_parts_mut( - __p, - libcc2rs::malloc_usable_size(__p as *mut ::libc::c_void) - / ::std::mem::size_of::(), - ))) + libcc2rs::dealloc_array_unsafe(__p); } }; return 0; diff --git a/tests/unit/out/unsafe/pointer_call_offset.rs b/tests/unit/out/unsafe/pointer_call_offset.rs index 4cb62ec6f0..50f15152b6 100644 --- a/tests/unit/out/unsafe/pointer_call_offset.rs +++ b/tests/unit/out/unsafe/pointer_call_offset.rs @@ -16,8 +16,7 @@ pub fn main() { } } unsafe fn main_0() -> i32 { - let mut p1: *mut i32 = - Box::leak((0..10_usize).map(|_| 0_i32).collect::>()).as_mut_ptr(); + let mut p1: *mut i32 = libcc2rs::alloc_array_unsafe::(10_usize, || 0_i32); { let mut i: u32 = 0_u32; 'loop_: while ((i) < (10_u32)) { @@ -32,11 +31,7 @@ unsafe fn main_0() -> i32 { { let __p = p1; if !__p.is_null() { - ::std::mem::drop(Box::from_raw(::std::slice::from_raw_parts_mut( - __p, - libcc2rs::malloc_usable_size(__p as *mut ::libc::c_void) - / ::std::mem::size_of::(), - ))) + libcc2rs::dealloc_array_unsafe(__p); } }; assert!(((out) == (9))); diff --git a/tests/unit/out/unsafe/reinterpret_cast_large_array.rs b/tests/unit/out/unsafe/reinterpret_cast_large_array.rs index 3224ccbbaa..75ae7b1aaf 100644 --- a/tests/unit/out/unsafe/reinterpret_cast_large_array.rs +++ b/tests/unit/out/unsafe/reinterpret_cast_large_array.rs @@ -14,8 +14,7 @@ pub fn main() { } unsafe fn main_0() -> i32 { let N: i32 = 10000; - let mut arr: *mut u32 = - Box::leak((0..(N as usize)).map(|_| 0_u32).collect::>()).as_mut_ptr(); + let mut arr: *mut u32 = libcc2rs::alloc_array_unsafe::((N as usize), || 0_u32); { let mut i: i32 = 0; 'loop_: while ((i) < (N)) { @@ -32,11 +31,7 @@ unsafe fn main_0() -> i32 { { let __p = arr; if !__p.is_null() { - ::std::mem::drop(Box::from_raw(::std::slice::from_raw_parts_mut( - __p, - libcc2rs::malloc_usable_size(__p as *mut ::libc::c_void) - / ::std::mem::size_of::(), - ))) + libcc2rs::dealloc_array_unsafe(__p); } }; return 0; diff --git a/tests/unit/out/unsafe/reinterpret_cast_new_array.rs b/tests/unit/out/unsafe/reinterpret_cast_new_array.rs index df7912d9bc..834b40cb3b 100644 --- a/tests/unit/out/unsafe/reinterpret_cast_new_array.rs +++ b/tests/unit/out/unsafe/reinterpret_cast_new_array.rs @@ -13,8 +13,7 @@ pub fn main() { } } unsafe fn main_0() -> i32 { - let mut arr: *mut u32 = - Box::leak((0..2_usize).map(|_| 0_u32).collect::>()).as_mut_ptr(); + let mut arr: *mut u32 = libcc2rs::alloc_array_unsafe::(2_usize, || 0_u32); (*arr.offset((0) as isize)) = 67305985_u32; (*arr.offset((1) as isize)) = 134678021_u32; let mut bytes: *mut u8 = (arr as *mut u8); @@ -28,11 +27,7 @@ unsafe fn main_0() -> i32 { { let __p = arr; if !__p.is_null() { - ::std::mem::drop(Box::from_raw(::std::slice::from_raw_parts_mut( - __p, - libcc2rs::malloc_usable_size(__p as *mut ::libc::c_void) - / ::std::mem::size_of::(), - ))) + libcc2rs::dealloc_array_unsafe(__p); } }; return 0; diff --git a/tests/unit/out/unsafe/struct_default_ctor.rs b/tests/unit/out/unsafe/struct_default_ctor.rs index 17a3f53270..676e307fec 100644 --- a/tests/unit/out/unsafe/struct_default_ctor.rs +++ b/tests/unit/out/unsafe/struct_default_ctor.rs @@ -84,38 +84,22 @@ unsafe fn main_0() -> i32 { object_unsafe!(s, S); assert!(((s.a) == (11))); assert!(((s.b as i32) == (true as i32))); - let mut h: *mut Holder = Box::leak( - (0..1_usize) - .map(|_| ::default()) - .collect::>(), - ) - .as_mut_ptr(); + let mut h: *mut Holder = + libcc2rs::alloc_array_unsafe::(1_usize, || ::default()); assert!((((*h.offset((0) as isize)).items[(1) as usize].a) == (11))); { let __p = h; if !__p.is_null() { - ::std::mem::drop(Box::from_raw(::std::slice::from_raw_parts_mut( - __p, - libcc2rs::malloc_usable_size(__p as *mut ::libc::c_void) - / ::std::mem::size_of::(), - ))) + libcc2rs::dealloc_array_unsafe(__p); } }; - let mut fs: *mut FromStatic = Box::leak( - (0..2_usize) - .map(|_| ::default()) - .collect::>(), - ) - .as_mut_ptr(); + let mut fs: *mut FromStatic = + libcc2rs::alloc_array_unsafe::(2_usize, || ::default()); assert!((((*fs.offset((1) as isize)).v) == (3))); { let __p = fs; if !__p.is_null() { - ::std::mem::drop(Box::from_raw(::std::slice::from_raw_parts_mut( - __p, - libcc2rs::malloc_usable_size(__p as *mut ::libc::c_void) - / ::std::mem::size_of::(), - ))) + libcc2rs::dealloc_array_unsafe(__p); } }; return 0; diff --git a/tests/unit/out/unsafe/swap_extended.rs b/tests/unit/out/unsafe/swap_extended.rs index eb50719e0f..9b6806b540 100644 --- a/tests/unit/out/unsafe/swap_extended.rs +++ b/tests/unit/out/unsafe/swap_extended.rs @@ -48,7 +48,7 @@ unsafe fn main_0() -> i32 { ::std::mem::drop(Box::from_raw(__p)) } }; - let mut i: *mut i32 = Box::leak(Box::new([7, 8, 0_i32])).as_mut_ptr(); + let mut i: *mut i32 = libcc2rs::alloc_array_from_unsafe::([7, 8, 0_i32]); write!( (*libcc2rs::cout_unsafe()), "{:} {:}\n", @@ -58,11 +58,7 @@ unsafe fn main_0() -> i32 { { let __p = i; if !__p.is_null() { - ::std::mem::drop(Box::from_raw(::std::slice::from_raw_parts_mut( - __p, - libcc2rs::malloc_usable_size(__p as *mut ::libc::c_void) - / ::std::mem::size_of::(), - ))) + libcc2rs::dealloc_array_unsafe(__p); } }; (unsafe { diff --git a/tests/unit/out/unsafe/vector_with_allocator.rs b/tests/unit/out/unsafe/vector_with_allocator.rs index fce95b321f..a874671381 100644 --- a/tests/unit/out/unsafe/vector_with_allocator.rs +++ b/tests/unit/out/unsafe/vector_with_allocator.rs @@ -20,17 +20,13 @@ use std::rc::Rc; pub struct TestAllocator_int_ {} impl TestAllocator_int_ { pub unsafe fn allocate(this: *mut Self, mut n: usize) -> *mut i32 { - return Box::leak((0..n).map(|_| 0_i32).collect::>()).as_mut_ptr(); + return libcc2rs::alloc_array_unsafe::(n, || 0_i32); } pub unsafe fn deallocate(this: *mut Self, mut p: *mut i32, mut _a1: usize) { { let __p = p; if !__p.is_null() { - ::std::mem::drop(Box::from_raw(::std::slice::from_raw_parts_mut( - __p, - libcc2rs::malloc_usable_size(__p as *mut ::libc::c_void) - / ::std::mem::size_of::(), - ))) + libcc2rs::dealloc_array_unsafe(__p); } }; } @@ -49,17 +45,13 @@ impl TestAllocator_int_ { pub struct TestAllocator_double_ {} impl TestAllocator_double_ { pub unsafe fn allocate(this: *mut Self, mut n: usize) -> *mut f64 { - return Box::leak((0..n).map(|_| 0_f64).collect::>()).as_mut_ptr(); + return libcc2rs::alloc_array_unsafe::(n, || 0_f64); } pub unsafe fn deallocate(this: *mut Self, mut p: *mut f64, mut _a1: usize) { { let __p = p; if !__p.is_null() { - ::std::mem::drop(Box::from_raw(::std::slice::from_raw_parts_mut( - __p, - libcc2rs::malloc_usable_size(__p as *mut ::libc::c_void) - / ::std::mem::size_of::(), - ))) + libcc2rs::dealloc_array_unsafe(__p); } }; }