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.

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) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This should probably be a named constant to be clearer

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Or a helper function?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You specifically mean the 0 for the name? It was chosen specifically because environments like Java and sometimes .NET don't get to use the C macros--the detail needs to be concrete.

But we can still add a constant, it just needs to be guaranteed to also be zero or else there could be issues.

To be honest, we could probably simplify this stuff. Rely on null to mean no error, and then use the lowest bit for "allocated or not".

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;
}
}
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
Loading
Loading