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.

2 changes: 1 addition & 1 deletion examples/ffi/build-examples.sh
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,6 @@ echo "Configuring example build..."
cmake -S examples/ffi -B examples/ffi/build -D Datadog_ROOT=./release

echo "Building examples..."
cmake --build ./examples/ffi/build
cmake --build ./examples/ffi/build --target profiles

echo "Done! Example executables are available in examples/ffi/build/"
115 changes: 104 additions & 11 deletions examples/ffi/profiles.c
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,9 @@
#include <stdio.h>
#include <stdlib.h>

// Number of samples to add with each API
#define NUM_SAMPLES 5000000

int main(void) {
const ddog_prof_ValueType wall_time = {
.type_ = DDOG_CHARSLICE_C("wall-time"),
Expand All @@ -14,16 +17,27 @@ int main(void) {
const ddog_prof_Slice_ValueType sample_types = {&wall_time, 1};
const ddog_prof_Period period = {wall_time, 60};

ddog_prof_Profile_NewResult new_result = ddog_prof_Profile_new(sample_types, &period);
if (new_result.tag != DDOG_PROF_PROFILE_NEW_RESULT_OK) {
ddog_CharSlice message = ddog_Error_message(&new_result.err);
fprintf(stderr, "%.*s", (int)message.len, message.ptr);
ddog_Error_drop(&new_result.err);
// Create a ProfilesDictionary for the new API
ddog_prof_ProfilesDictionaryHandle dict = {0};
ddog_prof_Status dict_status = ddog_prof_ProfilesDictionary_new(&dict);
if (dict_status.flags != 0) {
fprintf(stderr, "Failed to create dictionary: %s\n", dict_status.err);
ddog_prof_Status_drop(&dict_status);
exit(EXIT_FAILURE);
}

ddog_prof_Profile *profile = &new_result.ok;
// Create profile using the dictionary
ddog_prof_Profile profile = {0};
ddog_prof_Status profile_status =
ddog_prof_Profile_with_dictionary(&profile, &dict, sample_types, &period);
if (profile_status.flags != 0) {
fprintf(stderr, "Failed to create profile: %s\n", profile_status.err);
ddog_prof_Status_drop(&profile_status);
ddog_prof_ProfilesDictionary_drop(&dict);
exit(EXIT_FAILURE);
}

// Original API sample
ddog_prof_Location root_location = {
// yes, a zero-initialized mapping is valid
.mapping = (ddog_prof_Mapping){0},
Expand All @@ -44,28 +58,107 @@ int main(void) {
.labels = {&label, 1},
};

for (int i = 0; i < 10000000; i++) {
for (int i = 0; i < NUM_SAMPLES; i++) {
label.num = i;

ddog_prof_Profile_Result add_result = ddog_prof_Profile_add(profile, sample, 0);
ddog_prof_Profile_Result add_result = ddog_prof_Profile_add(&profile, sample, 0);
if (add_result.tag != DDOG_PROF_PROFILE_RESULT_OK) {
ddog_CharSlice message = ddog_Error_message(&add_result.err);
fprintf(stderr, "%.*s", (int)message.len, message.ptr);
ddog_Error_drop(&add_result.err);
}
}

// New API sample using the dictionary
// Insert strings into the dictionary
ddog_prof_StringId2 function_name_id, filename_id, label_key_id;

dict_status = ddog_prof_ProfilesDictionary_insert_str(
&function_name_id, dict, DDOG_CHARSLICE_C("{main}"), DDOG_PROF_UTF8_OPTION_ASSUME);
if (dict_status.flags != 0) {
fprintf(stderr, "Failed to insert function name: %s\n", dict_status.err);
ddog_prof_Status_drop(&dict_status);
goto cleanup;
}

dict_status = ddog_prof_ProfilesDictionary_insert_str(&filename_id, dict,
DDOG_CHARSLICE_C("/srv/example/index.php"),
DDOG_PROF_UTF8_OPTION_ASSUME);
if (dict_status.flags != 0) {
fprintf(stderr, "Failed to insert filename: %s\n", dict_status.err);
ddog_prof_Status_drop(&dict_status);
goto cleanup;
}

dict_status = ddog_prof_ProfilesDictionary_insert_str(
&label_key_id, dict, DDOG_CHARSLICE_C("unique_counter"), DDOG_PROF_UTF8_OPTION_ASSUME);
if (dict_status.flags != 0) {
fprintf(stderr, "Failed to insert label key: %s\n", dict_status.err);
ddog_prof_Status_drop(&dict_status);
goto cleanup;
}

// Create a function using the dictionary IDs
ddog_prof_FunctionId2 function_id;
ddog_prof_Function2 function2 = {
.name = function_name_id,
.system_name = DDOG_PROF_STRINGID2_EMPTY,
.file_name = filename_id,
};

dict_status = ddog_prof_ProfilesDictionary_insert_function(&function_id, dict, &function2);
if (dict_status.flags != 0) {
fprintf(stderr, "Failed to insert function: %s\n", dict_status.err);
ddog_prof_Status_drop(&dict_status);
goto cleanup;
}

// Create a location using the dictionary IDs
ddog_prof_Location2 location2 = {
.mapping = (ddog_prof_MappingId2){0}, // null mapping is valid
.function = function_id,
.address = 0,
.line = 0,
};

// New API sample using dictionary IDs
ddog_prof_Label2 label2 = {
.key = label_key_id,
.str = DDOG_CHARSLICE_C(""),
.num = 0,
.num_unit = DDOG_CHARSLICE_C(""),
};
const ddog_prof_Sample2 sample2 = {
.locations = {&location2, 1},
.values = {&value, 1},
.labels = {&label2, 1},
};

for (int i = 0; i < NUM_SAMPLES; i++) {
label2.num = i;

ddog_prof_Status add2_status = ddog_prof_Profile_add2(&profile, sample2, 0);
if (add2_status.flags != 0) {
fprintf(stderr, "add2 error: %s\n", add2_status.err);
ddog_prof_Status_drop(&add2_status);
}
}

// printf("Press any key to reset and drop...");
// getchar();

ddog_prof_Profile_Result reset_result = ddog_prof_Profile_reset(profile);
cleanup:
; // Can't have a declaration after a label pre-C23, so use an empty statement.
ddog_prof_Profile_Result reset_result = ddog_prof_Profile_reset(&profile);
if (reset_result.tag != DDOG_PROF_PROFILE_RESULT_OK) {
ddog_CharSlice message = ddog_Error_message(&reset_result.err);
fprintf(stderr, "%.*s", (int)message.len, message.ptr);
ddog_Error_drop(&reset_result.err);
}
ddog_prof_Profile_drop(profile);
ddog_prof_Profile_drop(&profile);

// Drop the dictionary
ddog_prof_ProfilesDictionary_drop(&dict);

return 0;
}
}
2 changes: 1 addition & 1 deletion libdd-common/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
/// 2. It must be valid UTF-8.
/// 3. It must not allocate to achieve the static bounds.
///
/// Using a c-str literal in Rust achieves all these requirements:
/// Using a c-str literal in Rust generally achieves all these requirements:
///
/// ```
/// c"this string is compatible with FfiSafeErrorMessage";
Expand Down
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
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
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
Loading
Loading