Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions libdd-profiling-ffi/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ datadog-ffe-ffi = ["dep:datadog-ffe-ffi"]
build_common = { path = "../build-common" }

[dependencies]
allocator-api2 = { version = "0.2.21", default-features = false, features = ["alloc"] }
anyhow = "1.0"
libdd-data-pipeline-ffi = { path = "../libdd-data-pipeline-ffi", default-features = false, optional = true }
libdd-crashtracker-ffi = { path = "../libdd-crashtracker-ffi", default-features = false, optional = true}
Expand Down
78 changes: 78 additions & 0 deletions libdd-profiling-ffi/src/arc_handle.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
// Copyright 2025-Present Datadog, Inc. https://www.datadoghq.com/
// SPDX-License-Identifier: Apache-2.0

use crate::profile_error::ProfileError;
use crate::EmptyHandleError;
use libdd_profiling::profiles::collections::Arc;
use std::ptr::{null_mut, NonNull};

/// Opaque FFI handle to an `Arc<T>`'s inner `T`.
///
/// Safety rules for implementors/callers:
/// - Do not create multiple owning `Arc<T>`s from the same raw pointer.
/// - Always restore the original `Arc` with `into_raw` after any `from_raw`.
/// - Use `as_inner()` to validate non-null before performing raw round-trips.
///
/// From Rust, use [`ArcHandle::try_clone`] to make a reference-counted copy.
/// From the C FFI, the handle should probably be renamed to avoid generics
/// bloat garbage, and a *_try_clone API should be provided.
///
/// Use [`ArcHandle::drop_resource`] to drop the resource and move this handle
/// into the empty handle state, which is the default state.
#[repr(transparent)]
#[derive(Debug)]
pub struct ArcHandle<T>(*mut T);

impl<T> Default for ArcHandle<T> {
fn default() -> Self {
Self(null_mut())
}
}

impl<T> ArcHandle<T> {
/// Constructs a new handle by allocating an `ArcHandle<T>` and returning
/// its inner pointer as a handle.
///
/// Returns OutOfMemory on allocation failure.
pub fn new(value: T) -> Result<Self, ProfileError> {
let arc = Arc::try_new(value)?;
let ptr = Arc::into_raw(arc).as_ptr();
Ok(Self(ptr))
}

pub fn try_clone_into_arc(&self) -> Result<Arc<T>, ProfileError> {
let clone = self.try_clone()?;
// SAFETY: try_clone succeeded so it must not be null.
let nn = unsafe { NonNull::new_unchecked(clone.0) };
// SAFETY: validated that it isn't null, should otherwise be an Arc.
Ok(unsafe { Arc::from_raw(nn) })
}

#[inline]
pub fn as_inner(&self) -> Result<&T, EmptyHandleError> {
unsafe { self.0.as_ref() }.ok_or(EmptyHandleError)
}

/// Tries to clone the resource this handle points to, and returns a new
/// handle to it.
pub fn try_clone(&self) -> Result<Self, ProfileError> {
let nn = NonNull::new(self.0).ok_or(EmptyHandleError)?;
// SAFETY: ArcHandle uses a pointer to T as its repr, and as long as
// callers have upheld safety requirements elsewhere, including the
// FFI, then there will be a valid object with refcount > 0.
unsafe { Arc::try_increment_count(nn.as_ptr())? };
Ok(Self(self.0))
}

/// Drops the resource that this handle refers to. It will remain alive if
/// there are other handles to the resource which were created by
/// successful calls to try_clone. This handle will now be empty and
/// operations on it will fail.
pub fn drop_resource(&mut self) {
// pointers aren't default until Rust 1.88.
let ptr = core::mem::replace(&mut self.0, null_mut());
if let Some(nn) = NonNull::new(ptr) {
drop(unsafe { Arc::from_raw(nn) });
}
}
}
7 changes: 7 additions & 0 deletions libdd-profiling-ffi/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,17 @@
#![cfg_attr(not(test), deny(clippy::todo))]
#![cfg_attr(not(test), deny(clippy::unimplemented))]

mod arc_handle;
mod exporter;
mod profile_error;
mod profile_status;
mod profiles;
mod string_storage;

pub use arc_handle::*;
pub use profile_error::*;
pub use profile_status::*;

#[cfg(all(feature = "symbolizer", not(target_os = "windows")))]
pub use symbolizer_ffi::*;

Expand Down
157 changes: 157 additions & 0 deletions libdd-profiling-ffi/src/profile_error.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,157 @@
// Copyright 2025-Present Datadog, Inc. https://www.datadoghq.com/
// SPDX-License-Identifier: Apache-2.0

use crate::profile_status::{string_try_shrink_to_fit, ProfileStatus};
use libdd_common::error::FfiSafeErrorMessage;
use libdd_common_ffi::slice::SliceConversionError;
use libdd_profiling::profiles::collections::{ArcOverflow, SetError};
use libdd_profiling::profiles::FallibleStringWriter;
use std::borrow::Cow;
use std::ffi::{CStr, CString};
use std::fmt;
use std::io::ErrorKind;

/// Represents errors which can occur in the profiling FFI. Its main purpose
/// is to hold a more Rust-friendly version of [`ProfileStatus`].
#[derive(Debug)]
pub enum ProfileError {
AllocError,
CapacityOverflow,
ReferenceCountOverflow,

Other(Cow<'static, CStr>),
}

/// Represents an error that means the handle is empty, meaning it doesn't
/// point to a resource.
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
pub struct EmptyHandleError;

impl From<&'static CStr> for ProfileError {
fn from(s: &'static CStr) -> ProfileError {
Self::Other(Cow::Borrowed(s))
}
}

impl From<CString> for ProfileError {
fn from(s: CString) -> ProfileError {
Self::Other(Cow::Owned(s))
}
}

impl From<ProfileError> for Cow<'static, CStr> {
fn from(err: ProfileError) -> Cow<'static, CStr> {
match err {
ProfileError::AllocError => Cow::Borrowed(c"memory allocation failed because the memory allocator returned an error"),
ProfileError::CapacityOverflow => Cow::Borrowed(c"memory allocation failed because the computed capacity exceeded the collection's maximum"),
ProfileError::ReferenceCountOverflow => Cow::Borrowed(c"reference count overflow"),
ProfileError::Other(msg) => msg,
}
}
}

impl From<ProfileError> for ProfileStatus {
fn from(err: ProfileError) -> ProfileStatus {
let cow = <Cow<'static, CStr>>::from(err);
match cow {
Cow::Borrowed(borrowed) => ProfileStatus::from(borrowed),
Cow::Owned(owned) => ProfileStatus::from(owned),
}
}
}

impl From<ArcOverflow> for ProfileError {
fn from(_: ArcOverflow) -> ProfileError {
ProfileError::ReferenceCountOverflow
}
}

impl From<allocator_api2::collections::TryReserveError> for ProfileError {
fn from(err: allocator_api2::collections::TryReserveError) -> ProfileError {
match err.kind() {
allocator_api2::collections::TryReserveErrorKind::CapacityOverflow => {
ProfileError::CapacityOverflow
}
allocator_api2::collections::TryReserveErrorKind::AllocError { .. } => {
ProfileError::AllocError
}
}
}
}

impl From<allocator_api2::alloc::AllocError> for ProfileError {
fn from(_: allocator_api2::alloc::AllocError) -> ProfileError {
ProfileError::AllocError
}
}

impl From<std::collections::TryReserveError> for ProfileError {
fn from(_: std::collections::TryReserveError) -> ProfileError {
// We just assume it's out of memory since kind isn't stable.
ProfileError::AllocError
}
}

impl From<SetError> for ProfileError {
fn from(err: SetError) -> ProfileError {
ProfileError::Other(Cow::Borrowed(err.as_ffi_str()))
}
}

impl From<EmptyHandleError> for ProfileError {
fn from(err: EmptyHandleError) -> ProfileError {
ProfileError::from(err.as_ffi_str())
}
}

impl From<SliceConversionError> for ProfileError {
fn from(err: SliceConversionError) -> ProfileError {
ProfileError::from(err.as_ffi_str())
}
}

/// # Safety
///
/// Uses c-str literal to ensure valid UTF-8 and null termination.
unsafe impl FfiSafeErrorMessage for EmptyHandleError {
fn as_ffi_str(&self) -> &'static CStr {
c"handle used with an interior null pointer"
}
}

impl fmt::Display for EmptyHandleError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.as_rust_str().fmt(f)
}
}

impl core::error::Error for EmptyHandleError {}

impl From<std::io::Error> for ProfileError {
fn from(err: std::io::Error) -> ProfileError {
match err.kind() {
ErrorKind::StorageFull => ProfileError::CapacityOverflow,
ErrorKind::WriteZero | ErrorKind::OutOfMemory => ProfileError::AllocError,
e => {
let mut writer = FallibleStringWriter::new();
use core::fmt::Write;
// Add null terminator that from_vec_with_nul expects.
if write!(&mut writer, "{e}\0").is_ok() {
return ProfileError::Other(Cow::Borrowed(
c"memory allocation failed while trying to create an error message",
));
}
let mut string = String::from(writer);
// We do this to avoid the potential panic case of failed
// allocation in CString::from_vec_with_nul.
if string_try_shrink_to_fit(&mut string).is_err() {
return ProfileError::Other(Cow::Borrowed(c"memory allocation failed while trying to shrink a vec to create an error message"));
}
match CString::from_vec_with_nul(string.into_bytes()) {
Ok(cstring) => ProfileError::Other(Cow::Owned(cstring)),
Err(_) => ProfileError::Other(Cow::Borrowed(c"encountered an interior null byte while converting a std::io::Error into a ProfileError"))
}
}
}
}
}
Loading
Loading