From e0942c8f298e9edad5a2d6f94cdd2dab87efcae2 Mon Sep 17 00:00:00 2001 From: Protobuf Team Bot Date: Wed, 14 Feb 2024 07:38:34 -0800 Subject: [PATCH] Return a non_null::dangling() for 0-sized allocations. PiperOrigin-RevId: 606980834 --- rust/cpp_kernel/cpp_api.h | 3 +++ rust/cpp_kernel/rust_alloc_for_cpp_api.rs | 10 ++++++++-- 2 files changed, 11 insertions(+), 2 deletions(-) diff --git a/rust/cpp_kernel/cpp_api.h b/rust/cpp_kernel/cpp_api.h index e1557cc115..5bb468d050 100644 --- a/rust/cpp_kernel/cpp_api.h +++ b/rust/cpp_kernel/cpp_api.h @@ -42,6 +42,9 @@ extern "C" void* __pb_rust_alloc(size_t size, size_t align); inline SerializedData SerializeMsg(const google::protobuf::Message* msg) { size_t len = msg->ByteSizeLong(); void* bytes = __pb_rust_alloc(len, alignof(char)); + if (bytes == nullptr) { + ABSL_LOG(FATAL) << "Rust allocator failed to allocate memory."; + } if (!msg->SerializeToArray(bytes, static_cast(len))) { ABSL_LOG(FATAL) << "Couldn't serialize the message."; } diff --git a/rust/cpp_kernel/rust_alloc_for_cpp_api.rs b/rust/cpp_kernel/rust_alloc_for_cpp_api.rs index 4055141247..9d9937cda9 100644 --- a/rust/cpp_kernel/rust_alloc_for_cpp_api.rs +++ b/rust/cpp_kernel/rust_alloc_for_cpp_api.rs @@ -9,6 +9,12 @@ use std::alloc::{alloc, Layout}; #[no_mangle] extern "C" fn __pb_rust_alloc(size: usize, align: usize) -> *mut u8 { - let layout = Layout::from_size_align(size, align).unwrap(); - unsafe { alloc(layout) } + if size == 0 { + // A 0-sized layout is legal but the global allocator isn't required to support + // it so return a dangling pointer instead. + std::ptr::null_mut::().wrapping_add(align) + } else { + let layout = Layout::from_size_align(size, 1).unwrap(); + unsafe { alloc(layout) } + } }