Return a non_null::dangling() for 0-sized allocations.

PiperOrigin-RevId: 606980834
pull/15822/head
Protobuf Team Bot 10 months ago committed by Copybara-Service
parent 89bea36856
commit e0942c8f29
  1. 3
      rust/cpp_kernel/cpp_api.h
  2. 10
      rust/cpp_kernel/rust_alloc_for_cpp_api.rs

@ -42,6 +42,9 @@ extern "C" void* __pb_rust_alloc(size_t size, size_t align);
inline SerializedData SerializeMsg(const google::protobuf::Message* msg) { inline SerializedData SerializeMsg(const google::protobuf::Message* msg) {
size_t len = msg->ByteSizeLong(); size_t len = msg->ByteSizeLong();
void* bytes = __pb_rust_alloc(len, alignof(char)); 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<int>(len))) { if (!msg->SerializeToArray(bytes, static_cast<int>(len))) {
ABSL_LOG(FATAL) << "Couldn't serialize the message."; ABSL_LOG(FATAL) << "Couldn't serialize the message.";
} }

@ -9,6 +9,12 @@ use std::alloc::{alloc, Layout};
#[no_mangle] #[no_mangle]
extern "C" fn __pb_rust_alloc(size: usize, align: usize) -> *mut u8 { extern "C" fn __pb_rust_alloc(size: usize, align: usize) -> *mut u8 {
let layout = Layout::from_size_align(size, align).unwrap(); if size == 0 {
unsafe { alloc(layout) } // 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::<u8>().wrapping_add(align)
} else {
let layout = Layout::from_size_align(size, 1).unwrap();
unsafe { alloc(layout) }
}
} }

Loading…
Cancel
Save