libdd-crashtracker 3.0.0

Detects program crashes and reports them to datadog backend.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
// Copyright 2025-Present Datadog, Inc. https://www.datadoghq.com/
// SPDX-License-Identifier: Apache-2.0

//! Runtime callback registration system for enhanced crash tracing
//!
//! This module provides APIs for runtime languages (Ruby, Python, PHP, etc.) to register
//! callbacks that can provide runtime-specific stack traces during crash handling.

use crate::crash_info::StackFrame;
use core::ffi::c_char;
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};

#[cfg(unix)]
use core::{
    ptr,
    sync::atomic::{AtomicPtr, Ordering},
};
use thiserror::Error;

#[cfg(unix)]
static FRAME_CSTR: &core::ffi::CStr = c"frame";
#[cfg(unix)]
static STACKTRACE_STRING_CSTR: &core::ffi::CStr = c"stacktrace_string";

#[cfg(unix)]
#[derive(Debug)]
pub enum CallbackData {
    Frame(RuntimeFrameCallback),
    StacktraceString(RuntimeStacktraceStringCallback),
}

/// Global storage for the runtime callback
#[cfg(unix)]
static RUNTIME_CALLBACK: AtomicPtr<CallbackData> = AtomicPtr::new(ptr::null_mut());

#[derive(Debug, Clone)]
pub struct RuntimeStackFrame<'a> {
    /// Line number in source file (0 if unknown)
    pub line: u32,
    /// Column number in source file (0 if unknown)
    pub column: u32,
    /// Function name (fully qualified if possible)
    pub function: &'a [u8],
    /// Source file name
    pub file: &'a [u8],
    /// Type name (class/module/namespace/etc.)
    pub type_name: &'a [u8],
}

/// Function signature for runtime frame collection callbacks
///
/// This callback is invoked during crash handling in a signal context, so it must be signal-safe:
///
/// # Parameters
/// - `emit_frame`: Function to call for each runtime frame (takes frame pointer)
///
/// # Safety
/// The callback function is marked unsafe because:
/// - It receives function pointers that take raw pointers as parameters
/// - The callback must ensure any pointers it passes to these functions are valid
pub type RuntimeFrameCallback =
    unsafe extern "C" fn(emit_frame: unsafe extern "C" fn(&RuntimeStackFrame));

/// Function signature for runtime stacktrace string collection callbacks
///
/// This callback is invoked during crash handling in a signal context, so it must be signal-safe:
///
/// # Parameters
/// - `emit_stacktrace_string`: Function to call for complete stacktrace string (takes C string)
///
/// # Safety
/// The callback function is marked unsafe because:
/// - It receives function pointers that take raw pointers as parameters
/// - All C strings passed must be null-terminated and remain valid for the call duration
pub type RuntimeStacktraceStringCallback =
    unsafe extern "C" fn(emit_stacktrace_string: unsafe extern "C" fn(*const c_char));

/// Runtime stack representation for JSON serialization
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
pub struct RuntimeStack {
    pub format: String,
    /// Array of runtime-specific stack frames (optional, mutually exclusive with
    /// stacktrace_string)
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub frames: Vec<StackFrame>,
    /// Raw stacktrace string (optional, mutually exclusive with frames)
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub stacktrace_string: Option<String>,
}

#[derive(Debug, Error)]
pub enum CallbackError {
    #[error("Null callback function provided")]
    NullCallback,
}

#[cfg(unix)]
pub fn register_runtime_frame_callback(
    callback: RuntimeFrameCallback,
) -> Result<(), CallbackError> {
    if callback as usize == 0 {
        return Err(CallbackError::NullCallback);
    }

    let callback_data = Box::into_raw(Box::new(CallbackData::Frame(callback)));
    let previous = RUNTIME_CALLBACK.swap(callback_data, Ordering::SeqCst);

    if !previous.is_null() {
        // Safety: previous was returned by Box::into_raw() above,
        // so it's guaranteed to be a valid Box pointer. We reconstruct the Box to drop it.
        let _ = unsafe { Box::from_raw(previous) };
    }

    Ok(())
}

#[cfg(unix)]
pub fn register_runtime_stacktrace_string_callback(
    callback: RuntimeStacktraceStringCallback,
) -> Result<(), CallbackError> {
    if callback as usize == 0 {
        return Err(CallbackError::NullCallback);
    }

    let callback_data = Box::into_raw(Box::new(CallbackData::StacktraceString(callback)));
    let previous = RUNTIME_CALLBACK.swap(callback_data, Ordering::SeqCst);

    if !previous.is_null() {
        // Safety: previous was returned by Box::into_raw() above,
        // so it's guaranteed to be a valid Box pointer. We reconstruct the Box to drop it.
        let _ = unsafe { Box::from_raw(previous) };
    }

    Ok(())
}

/// Returns true if a callback is registered, false otherwise
#[cfg(unix)]
pub fn is_runtime_callback_registered() -> bool {
    !RUNTIME_CALLBACK.load(Ordering::SeqCst).is_null()
}

/// Internal function to get the callback
///
/// # Safety
/// This function loads from an atomic pointer and dereferences it.
/// The caller must ensure that no other thread is calling `clear_runtime_callback`
/// or registration functions concurrently, as those could invalidate
/// the pointer between the null check and dereferencing.
#[cfg(all(unix, feature = "collector"))]
pub(crate) unsafe fn get_registered_callback() -> Option<CallbackData> {
    let callback_ptr = RUNTIME_CALLBACK.load(Ordering::SeqCst);
    if callback_ptr.is_null() {
        return None;
    }

    // Safety: callback_ptr was checked to be non-null above, and was created by
    // Box::into_raw() in registration functions, so it's a valid pointer
    // to a properly aligned, initialized CallbackData.
    Some(callback_ptr.read())
}

/// Get the callback type C string pointer from the currently registered callback
///
/// # Safety
/// This function loads from an atomic pointer and dereferences it.
/// The caller must ensure that no other thread is calling `clear_runtime_callback`
/// or registration functions concurrently, as those could invalidate
/// the pointer between the null check and dereferencing.
#[cfg(unix)]
pub unsafe fn get_registered_callback_type_ptr() -> *const core::ffi::c_char {
    let callback_ptr = RUNTIME_CALLBACK.load(Ordering::SeqCst);
    if callback_ptr.is_null() {
        return core::ptr::null();
    }

    // Safety: callback_ptr was checked to be non-null above, and was created by
    // Box::into_raw() in registration functions, so it's a valid pointer
    // to a properly aligned, initialized CallbackData. The returned C string pointer
    // points to static string literals, so it's always valid.
    let callback_data = &*callback_ptr;
    match callback_data {
        CallbackData::Frame(_) => FRAME_CSTR.as_ptr(),
        CallbackData::StacktraceString(_) => STACKTRACE_STRING_CSTR.as_ptr(),
    }
}

/// Clear the registered runtime callback
///
/// # Safety
/// This function should only be called when it's safe to clear the callback,
/// like during testing or application shutdown. The caller must ensure:
/// - No other thread is concurrently calling functions that dereference the callback pointer
/// - No signal handlers are currently executing that might invoke the callback
/// - The callback is not being used in any other way
#[cfg(unix)]
pub unsafe fn clear_runtime_callback() {
    let old_ptr = RUNTIME_CALLBACK.swap(core::ptr::null_mut(), Ordering::SeqCst);
    if !old_ptr.is_null() {
        // Safety: old_ptr was created by Box::into_raw() in register_runtime_stack_callback(),
        // so it's a valid Box pointer. We reconstruct the Box to properly drop the tuple.
        let _ = Box::from_raw(old_ptr);
    }
}

/// Internal function to invoke the registered runtime callback with direct pipe writing
///
/// # Safety
/// This function is intended to be called from signal handlers and must maintain
/// signal safety. It does not perform any dynamic allocation. The caller must ensure:
/// - No other thread is calling `clear_runtime_callback` concurrently
/// - The registered callback function is signal-safe
/// - The writer parameter remains valid for the duration of the call
#[cfg(all(unix, feature = "collector"))]
pub(crate) unsafe fn invoke_runtime_callback_with_writer<W: std::io::Write>(
    writer: &mut W,
) -> Result<(), std::io::Error> {
    static mut CURRENT_WRITER: Option<&'static mut dyn std::io::Write> = None;

    let callback_ptr = RUNTIME_CALLBACK.load(Ordering::SeqCst);
    if callback_ptr.is_null() {
        return Err(std::io::Error::other("No runtime callback registered"));
    }
    let callback_data = &*callback_ptr;

    CURRENT_WRITER = Some(core::mem::transmute::<
        &mut dyn std::io::Write,
        &'static mut dyn std::io::Write,
    >(writer));

    unsafe extern "C" fn emit_frame_collector(frame: &RuntimeStackFrame) {
        if let Some(ref mut writer) = CURRENT_WRITER {
            let _ = emit_frame_as_json(writer, frame);
            let _ = writer.flush();
        }
    }

    unsafe extern "C" fn emit_stacktrace_string_collector(stacktrace_string: *const c_char) {
        if stacktrace_string.is_null() {
            return;
        }

        if let Some(ref mut writer) = CURRENT_WRITER {
            // SAFETY: the runtime guarantees a valid, null-terminated C string.
            let cstr = core::ffi::CStr::from_ptr(stacktrace_string);
            let bytes = cstr.to_bytes();
            let _ = writer.write_all(bytes);
            let _ = writeln!(writer);
            let _ = writer.flush();
        }
    }

    match callback_data {
        CallbackData::Frame(cb) => cb(emit_frame_collector),
        CallbackData::StacktraceString(cb) => cb(emit_stacktrace_string_collector),
    }

    CURRENT_WRITER = None;

    Ok(())
}

/// Emit a single runtime frame as JSON to the writer
///
/// # Safety
/// The caller must ensure that `frame` is either null or points to a valid, properly
/// initialized RuntimeStackFrame. All C string pointers within the frame must be either
/// null or point to valid, null-terminated C strings.
#[cfg(all(unix, feature = "collector"))]
unsafe fn emit_frame_as_json(
    writer: &mut dyn std::io::Write,
    frame: &RuntimeStackFrame,
) -> std::io::Result<()> {
    // `function`, `type_name`, `file` fields can have invalid utf8 characters
    // Converting them to str might error, and we can't use from_utf8_lossy because
    // it's not signal safe. So we just write the raw bytes and convert on the
    // receiver side
    write!(writer, "{{")?;

    let mut first_field = true;

    if !frame.function.is_empty() {
        if !first_field {
            write!(writer, ", ")?;
        }
        write!(writer, "\"function\": {:?}", frame.function)?;
        first_field = false;
    }

    if !frame.type_name.is_empty() {
        if !first_field {
            write!(writer, ", ")?;
        }
        write!(writer, "\"type_name\": {:?}", frame.type_name)?;
        first_field = false;
    }

    if !frame.file.is_empty() {
        if !first_field {
            write!(writer, ", ")?;
        }
        write!(writer, "\"file\": {:?}", frame.file)?;
        first_field = false;
    }

    if frame.line != 0 {
        if !first_field {
            write!(writer, ", ")?;
        }
        write!(writer, "\"line\": {}", frame.line)?;
        first_field = false;
    }

    if frame.column != 0 {
        if !first_field {
            write!(writer, ", ")?;
        }
        write!(writer, "\"column\": {}", frame.column)?;
    }

    writeln!(writer, "}}")?;
    Ok(())
}

#[cfg(all(test, unix))]
mod tests {
    use super::*;
    use std::sync::Mutex;

    // So we don't have race conditions with global static variable
    static TEST_MUTEX: Mutex<()> = Mutex::new(());

    unsafe extern "C" fn test_emit_frame_callback(
        emit_frame: unsafe extern "C" fn(&RuntimeStackFrame),
    ) {
        let type_name = "TestModule.TestClass";
        let function_name = "test_function";
        let file_name = "test.rb";

        let frame = RuntimeStackFrame {
            type_name: type_name.as_bytes(),
            function: function_name.as_bytes(),
            file: file_name.as_bytes(),
            line: 42,
            column: 10,
        };

        emit_frame(&frame);
    }

    #[cfg(feature = "collector")]
    unsafe extern "C" fn test_emit_stacktrace_string_callback(
        emit_stacktrace_string: unsafe extern "C" fn(*const c_char),
    ) {
        let stacktrace_string = alloc::ffi::CString::new("test_stacktrace_string").unwrap();

        emit_stacktrace_string(stacktrace_string.as_ptr());
    }

    fn ensure_callback_cleared() {
        let old_ptr = RUNTIME_CALLBACK.swap(ptr::null_mut(), Ordering::SeqCst);
        if !old_ptr.is_null() {
            let _ = unsafe { Box::from_raw(old_ptr) };
        }
    }

    #[test]
    fn test_callback_registration() {
        let _guard = TEST_MUTEX.lock().unwrap();
        ensure_callback_cleared();

        let result = register_runtime_frame_callback(test_emit_frame_callback);
        assert!(result.is_ok(), "Failed to register callback: {:?}", result);

        let result = register_runtime_frame_callback(test_emit_frame_callback);
        assert!(
            result.is_ok(),
            "Failed to re-register callback: {:?}",
            result
        );
    }

    #[test]
    #[cfg_attr(miri, ignore)]
    #[cfg(feature = "collector")]
    fn test_frame_collection() {
        let _guard = TEST_MUTEX.lock().unwrap();
        ensure_callback_cleared();

        let result = register_runtime_frame_callback(test_emit_frame_callback);
        assert!(result.is_ok(), "Failed to register callback: {:?}", result);

        let mut buffer = Vec::new();
        let invocation_result = unsafe { invoke_runtime_callback_with_writer(&mut buffer) };
        assert!(
            invocation_result.is_ok(),
            "Failed to invoke callback with writer"
        );

        let json_output = String::from_utf8(buffer).expect("Invalid UTF-8 in output");

        // Should contain the frame data as JSON with string fields as UTF-8 byte arrays
        assert!(
            json_output.contains("\"function\""),
            "Missing function field"
        );

        let function_bytes = format!("{:?}", "test_function".as_bytes());
        assert!(
            json_output.contains(&function_bytes),
            "Missing function name as byte array"
        );

        assert!(
            json_output.contains("\"type_name\""),
            "Missing type_name field"
        );

        let type_name_bytes = format!("{:?}", "TestModule.TestClass".as_bytes());
        assert!(
            json_output.contains(&type_name_bytes),
            "Missing type_name as byte array"
        );

        assert!(json_output.contains("\"file\""), "Missing file field");

        let file_bytes = format!("{:?}", "test.rb".as_bytes());
        assert!(
            json_output.contains(&file_bytes),
            "Missing file name as byte array"
        );
        assert!(json_output.contains("\"line\": 42"), "Missing line number");
        assert!(
            json_output.contains("\"column\": 10"),
            "Missing column number"
        );
    }

    #[test]
    #[cfg_attr(miri, ignore)]
    #[cfg(feature = "collector")]
    fn test_stacktrace_string_collection() {
        let _guard = TEST_MUTEX.lock().unwrap();
        ensure_callback_cleared();

        let result =
            register_runtime_stacktrace_string_callback(test_emit_stacktrace_string_callback);
        assert!(result.is_ok(), "Failed to register callback: {:?}", result);

        let mut buffer = Vec::new();
        let invocation_result = unsafe { invoke_runtime_callback_with_writer(&mut buffer) };
        assert!(
            invocation_result.is_ok(),
            "Failed to invoke callback with writer"
        );

        let json_output = String::from_utf8(buffer).expect("Invalid UTF-8 in output");
        // Should contain the stacktrace string
        assert!(
            json_output.contains("test_stacktrace_string"),
            "Missing stacktrace string"
        );
    }

    #[test]
    #[cfg(feature = "collector")]
    fn test_no_callback_registered() {
        let _guard = TEST_MUTEX.lock().unwrap();
        ensure_callback_cleared();

        // Test that invoking callback returns 0 frames
        let mut buffer = Vec::new();
        let invocation_result = unsafe { invoke_runtime_callback_with_writer(&mut buffer) };

        #[allow(clippy::std_instead_of_core)]
        // Clippy tries to make us import from core::io which is nightly only
        {
            assert_eq!(
                invocation_result.unwrap_err().kind(),
                std::io::ErrorKind::Other,
                "Expected Other error when no callback registered"
            );
        }

        assert!(
            buffer.is_empty(),
            "Expected empty buffer when no callback registered"
        );
    }

    #[test]
    #[cfg_attr(miri, ignore)]
    #[cfg(feature = "collector")]
    fn test_direct_pipe_writing() {
        let _guard = TEST_MUTEX.lock().unwrap();
        ensure_callback_cleared();

        let result = register_runtime_frame_callback(test_emit_frame_callback);
        assert!(result.is_ok(), "Failed to register callback: {:?}", result);

        // Test writing directly to a buffer
        let mut buffer = Vec::new();
        let invocation_result = unsafe { invoke_runtime_callback_with_writer(&mut buffer) };
        assert!(
            invocation_result.is_ok(),
            "Failed to invoke callback with writer"
        );

        // Convert buffer to string and check JSON format with string fields as UTF-8 byte arrays
        let json_output = String::from_utf8(buffer).expect("Invalid UTF-8 in output");

        assert!(
            json_output.contains("\"function\""),
            "Missing function field"
        );

        let function_bytes = format!("{:?}", "test_function".as_bytes());
        assert!(
            json_output.contains(&function_bytes),
            "Missing function name as byte array"
        );

        assert!(
            json_output.contains("\"type_name\""),
            "Missing type_name field"
        );

        let type_name_bytes = format!("{:?}", "TestModule.TestClass".as_bytes());
        assert!(
            json_output.contains(&type_name_bytes),
            "Missing type name as byte array"
        );

        assert!(json_output.contains("\"file\""), "Missing file field");

        let file_bytes = format!("{:?}", "test.rb".as_bytes());
        assert!(
            json_output.contains(&file_bytes),
            "Missing file name as byte array"
        );
        assert!(json_output.contains("\"line\": 42"), "Missing line number");
        assert!(
            json_output.contains("\"column\": 10"),
            "Missing column number"
        );
    }
}