Skip to content
Merged
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 @@ -56,5 +56,6 @@ hyper = { workspace = true}
libc = "0.2"
serde_json = { version = "1.0" }
symbolizer-ffi = { path = "../symbolizer-ffi", optional = true, default-features = false }
thiserror = "2"
tokio-util = "0.7.1"
datadog-ffe-ffi = { path = "../datadog-ffe-ffi", default-features = false, optional = true }
3 changes: 3 additions & 0 deletions libdd-profiling-ffi/cbindgen.toml
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,9 @@ renaming_overrides_prefixing = true
"CancellationToken" = "struct ddog_OpaqueCancellationToken"
"Handle_TokioCancellationToken" = "ddog_CancellationToken"

"ArcHandle_ProfilesDictionary" = "ddog_prof_ProfilesDictionaryHandle"
"ProfileStatus" = "ddog_prof_Status"

[export.mangle]
rename_types = "PascalCase"

Expand Down
80 changes: 80 additions & 0 deletions libdd-profiling-ffi/src/arc_handle.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
// 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> {
// SAFETY: If non-null, self.0 was created from Arc and remains valid,
// at least as long as we can trust the C side to not do insane things.
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) });
}
}
}
2 changes: 2 additions & 0 deletions libdd-profiling-ffi/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,14 @@
#![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::*;

Expand Down
22 changes: 22 additions & 0 deletions libdd-profiling-ffi/src/profiles/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,25 @@

mod datatypes;
mod interning_api;
mod profiles_dictionary;
mod utf8;

#[macro_export]
macro_rules! ensure_non_null_out_parameter {
($expr:expr) => {
if $expr.is_null() {
return $crate::ProfileStatus::from(c"null pointer used as out parameter");
}
};
}

#[macro_export]
macro_rules! ensure_non_null_insert {
($expr:expr) => {
if $expr.is_null() {
return $crate::ProfileStatus::from(c"tried to insert a null pointer");
}
};
}

pub(crate) use {ensure_non_null_insert, ensure_non_null_out_parameter};
Loading
Loading