libdd-crashtracker 2.0.1

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
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
// Copyright 2023-Present Datadog, Inc. https://www.datadoghq.com/
// SPDX-License-Identifier: Apache-2.0

#![cfg(unix)]

use super::collector_manager::Collector;
use super::receiver_manager::Receiver;
use super::saguard::{SaGuard, SuppressionMode};
use super::signal_handler_manager::chain_signal_handler;
use crate::crash_info::Metadata;
use crate::shared::configuration::CrashtrackerConfiguration;
use crate::StackTrace;
use core::ptr;
use core::sync::atomic::Ordering::{Acquire, Relaxed, SeqCst};
use core::sync::atomic::{AtomicBool, AtomicI32, AtomicPtr, AtomicU64};
use errno::{errno, set_errno};
use libc::{c_void, pid_t, siginfo_t, ucontext_t};
use libdd_common::timeout::TimeoutManager;
use std::os::fd::OwnedFd;
use std::os::unix::io::{AsRawFd, FromRawFd};
use std::os::unix::net::UnixStream;
use std::panic;
use std::panic::PanicHookInfo;

// Note that this file makes use the following async-signal safe functions in a signal handler.
// <https://man7.org/linux/man-pages/man7/signal-safety.7.html>
// - clock_gettime
// - close (although Rust may call `free` because we call the higher-level nix interface)
// - dup2
// - fork (on MacOS; Linux calls `fork()` directly as syscall)
// - kill
// - poll
// - raise
// - read
// - sigaction
// - write

// These represent data used by the crashtracker.
// Using mutexes inside a signal handler is not allowed, so use `AtomicPtr`
// instead to get atomicity.
// These should always be either: null_mut, or `Box::into_raw()`
// This means that we can always clean up the memory inside one of these using
// `Box::from_raw` to recreate the box, then dropping it.
static METADATA: AtomicPtr<(Metadata, String)> = AtomicPtr::new(ptr::null_mut());
static CONFIG: AtomicPtr<(CrashtrackerConfiguration, String)> = AtomicPtr::new(ptr::null_mut());
static PANIC_MESSAGE: AtomicPtr<String> = AtomicPtr::new(ptr::null_mut());

type PanicHook = Box<dyn Fn(&PanicHookInfo<'_>) + Send + Sync>;
static PREVIOUS_PANIC_HOOK: AtomicPtr<PanicHook> = AtomicPtr::new(ptr::null_mut());

/// Expected PID of the socket-based receiver (sidecar), set during trusted
/// initialization. A value of 0 means "not set" and will cause the signal handler
/// to skip granting ptrace permission
static EXPECTED_RECEIVER_PID: AtomicI32 = AtomicI32::new(0);

/// Register the expected receiver PID for socket-based crash receivers.
///
/// When `collect_all_threads` is enabled and the receiver is reached via a Unix
/// socket (not a forked child), the signal handler will only grant ptrace
/// permission (`PR_SET_PTRACER`) if the socket peer's PID (via `SO_PEERCRED`)
/// matches this value.
///
/// Call this during trusted initialization (after connecting to or spawning
/// the sidecar) with the sidecar's PID
///
/// SAFETY:
///     This function is safe to call from any context, its a single atomic store.
pub fn set_expected_receiver_pid(pid: pid_t) {
    EXPECTED_RECEIVER_PID.store(pid, Relaxed);
}

/// Returns the currently registered expected receiver PID, or 0 if unset.
pub fn get_expected_receiver_pid() -> pid_t {
    EXPECTED_RECEIVER_PID.load(Relaxed)
}

#[derive(Debug, thiserror::Error)]
pub enum CrashHandlerError {
    #[error("No crashtracking config available")]
    NoConfig,
    #[error("No crashtracking metadata available")]
    NoMetadata,
    #[error("Failed to spawn receiver: {0}")]
    ReceiverSpawnError(#[from] super::receiver_manager::ReceiverError),
    #[error("Failed to spawn collector: {0}")]
    CollectorSpawnError(#[from] super::collector_manager::CollectorSpawnError),
}

/// Updates the crashtracker metadata for this process
/// Metadata is stored in a global variable and sent to the crashtracking
/// receiver when a crash occurs.
///
/// PRECONDITIONS:
///     None
/// SAFETY:
///     Crash-tracking functions are not guaranteed to be reentrant.
///     No other crash-handler functions should be called concurrently.
/// ATOMICITY:
///     This function uses a swap on an atomic pointer.
pub fn update_metadata(metadata: Metadata) -> anyhow::Result<()> {
    let metadata_string = serde_json::to_string(&metadata)?;
    let box_ptr = Box::into_raw(Box::new((metadata, metadata_string)));
    let old = METADATA.swap(box_ptr, SeqCst);
    if !old.is_null() {
        // Safety: This can only come from a box above.
        unsafe {
            core::mem::drop(Box::from_raw(old));
        }
    }
    Ok(())
}

/// Format a panic message with optional location information.
fn format_message(
    category: &str,
    panic_message: &str,
    location: Option<&panic::Location>,
) -> String {
    let base = if panic_message.is_empty() {
        format!("Process panicked with {}", category)
    } else {
        format!("Process panicked with {} \"{}\"", category, panic_message)
    };

    match location {
        Some(loc) => format!("{} ({}:{}:{})", base, loc.file(), loc.line(), loc.column()),
        None => base,
    }
}

/// Register the panic hook.
///
/// This function is used to register the panic hook and store the previous hook.
/// PRECONDITIONS:
///     None
/// SAFETY:
///     Crash-tracking functions are not guaranteed to be reentrant.
///     No other crash-handler functions should be called concurrently.
/// ATOMICITY:
///     This function uses a swap on an atomic pointer.
pub fn register_panic_hook() -> anyhow::Result<()> {
    // register only once, if it is already registered, do nothing
    if !PREVIOUS_PANIC_HOOK.load(SeqCst).is_null() {
        return Ok(());
    }

    let old_hook = panic::take_hook();
    let old_hook_ptr = Box::into_raw(Box::new(old_hook));
    PREVIOUS_PANIC_HOOK.swap(old_hook_ptr, SeqCst);
    panic::set_hook(Box::new(|panic_info| {
        // Extract panic message from payload (supports &str and String)
        let message = if let Some(&s) = panic_info.payload().downcast_ref::<&str>() {
            format_message("message", s, panic_info.location())
        } else if let Some(s) = panic_info.payload().downcast_ref::<String>() {
            format_message("message", s.as_str(), panic_info.location())
        } else {
            // For non-string types, use a generic message
            format_message("unknown type", "", panic_info.location())
        };

        // Store the message, cleaning up any old message
        let message_ptr = PANIC_MESSAGE.swap(Box::into_raw(Box::new(message)), SeqCst);
        // message_ptr should be null, but just in case.
        if !message_ptr.is_null() {
            unsafe {
                core::mem::drop(Box::from_raw(message_ptr));
            }
        }

        call_previous_panic_hook(panic_info);
    }));
    Ok(())
}

/// Call the previous panic hook.
///
/// This function is used to call the previous panic hook.
/// PRECONDITIONS:
///     None
/// SAFETY:
///     Crash-tracking functions are not guaranteed to be reentrant.
///     No other crash-handler functions should be called concurrently.
fn call_previous_panic_hook(panic_info: &PanicHookInfo<'_>) {
    let old_hook_ptr = PREVIOUS_PANIC_HOOK.load(SeqCst);
    if !old_hook_ptr.is_null() {
        // Safety: This pointer can only come from Box::into_raw above in register_panic_hook.
        // We borrow it here without taking ownership so it remains valid for future calls.
        unsafe {
            let old_hook = &*old_hook_ptr;
            old_hook(panic_info);
        }
    }
}

/// Updates the crashtracker config for this process
/// Config is stored in a global variable and sent to the crashtracking
/// receiver when a crash occurs.
///
/// PRECONDITIONS:
///     None
/// SAFETY:
///     Crash-tracking functions are not guaranteed to be reentrant.
///     No other crash-handler functions should be called concurrently.
/// ATOMICITY:
///     This function uses a swap on an atomic pointer.
pub fn update_config(config: CrashtrackerConfiguration) -> anyhow::Result<()> {
    let config_string = serde_json::to_string(&config)?;
    let box_ptr = Box::into_raw(Box::new((config, config_string)));
    let old = CONFIG.swap(box_ptr, SeqCst);
    if !old.is_null() {
        // Safety: This can only come from a box above.
        unsafe {
            core::mem::drop(Box::from_raw(old));
        }
    }
    Ok(())
}

pub(crate) extern "C" fn handle_posix_sigaction(
    signum: i32,
    sig_info: *mut siginfo_t,
    ucontext: *mut c_void,
) {
    // Save errno
    let errno = errno();

    // Handle the signal.  Note this has a guard to ensure that we only generate
    // one crash report per process.
    let _ = handle_posix_signal_impl(sig_info, ucontext as *mut ucontext_t);

    // Restore errno
    set_errno(errno);
    // SAFETY: No preconditions.

    unsafe { chain_signal_handler(signum, sig_info, ucontext) };
}

static ENABLED: AtomicBool = AtomicBool::new(true);

/// Disables the crashtracker.
/// Note that this does not restore the old signal handlers, but rather turns crash-tracking into a
/// no-op, and then chains the old handlers.  This means that handlers registered after the
/// crashtracker will continue to work as expected.
///
/// # Preconditions
///   None
/// # Safety
///   None
/// # Atomicity
///   This function is atomic and idempotent.  Calling it multiple times is allowed.
pub fn disable() {
    ENABLED.store(false, SeqCst);
}

/// Enables the crashtracker, if had been previously disabled.
/// If crashtracking has not been initialized, this function will have no effect.
///
/// # Preconditions
///   None
/// # Safety
///   None
/// # Atomicity
///   This function is atomic and idempotent.  Calling it multiple times is allowed.
pub fn enable() {
    ENABLED.store(true, SeqCst);
}

fn handle_posix_signal_impl(
    sig_info: *const siginfo_t,
    ucontext: *const ucontext_t,
) -> Result<(), CrashHandlerError> {
    if !ENABLED.load(SeqCst) {
        return Ok(());
    }

    // If this code hits a stack overflow, then it will result in a segfault.  That situation is
    // protected by the one-time guard.

    // One-time guard to guarantee at most one crash per process
    static NUM_TIMES_CALLED: AtomicU64 = AtomicU64::new(0);
    if NUM_TIMES_CALLED.fetch_add(1, SeqCst) > 0 {
        // In the case where some lower-level signal handler recovered the error
        // we don't want to spam the system with calls.  Make this one shot.
        return Ok(());
    }

    #[cfg(target_os = "linux")]
    {
        super::api::mark_preload_logger_collector();
    }

    // Suppress SIGPIPE and defer SIGCHLD during crash handling.
    // SIGCHLD is block-only because SIG_IGN changes child reaping semantics (waitpid/ECHILD),
    // which can interfere with receiver/collector process cleanup.
    let _sa_guard = SaGuard::new_with_modes(&[
        (
            nix::sys::signal::Signal::SIGCHLD,
            SuppressionMode::BlockOnly,
        ),
        (
            nix::sys::signal::Signal::SIGPIPE,
            SuppressionMode::IgnoreAndBlock,
        ),
    ]);

    // Take config and metadata out of global storage.
    // We borrow via raw pointer and intentionally leak (do not reconstruct the Box) to avoid
    // calling `drop`, and therefore `free`, inside a signal handler, which is not
    // async-signal-safe.  Once the one-time guard is passed, this storage is never updated again.
    let config_ptr = take_config_ptr();
    if config_ptr.is_null() {
        return Err(CrashHandlerError::NoConfig);
    }
    let (config, config_str) = unsafe { &*config_ptr };

    let metadata_ptr = take_metadata_ptr();
    if metadata_ptr.is_null() {
        return Err(CrashHandlerError::NoMetadata);
    }
    let (_metadata, metadata_string) = unsafe { &*metadata_ptr };

    // Take the panic message pointer. We borrow via raw pointer and
    // intentionally leak (do not reconstruct the Box) to avoid calling
    // `free` in the signal handler.
    let panic_message_ptr = PANIC_MESSAGE.swap(ptr::null_mut(), Acquire);

    // Prefer the panic message; fall back to a stored assert-failure
    // message (captured by our __assert_fail GOT hook on SIGABRT).
    let message: Option<&str> = if !panic_message_ptr.is_null() {
        // SAFETY: the pointer was created by `Box::into_raw(Box::new(String))`
        // in the panic hook and has not been freed.
        Some(unsafe { &*panic_message_ptr })
    } else {
        #[cfg(all(target_os = "linux", target_pointer_width = "64"))]
        {
            super::assert_interceptor::take_assert_message()
        }
        #[cfg(not(all(target_os = "linux", target_pointer_width = "64")))]
        {
            None
        }
    };

    let timeout_manager = TimeoutManager::new(config.timeout());

    let receiver = Receiver::from_crashtracker_config(config)?;

    // Enable ptrace permissions for receiver if multi-thread collection is enabled.
    // For fork/exec receivers, we have the child PID directly (trusted: we spawned it).
    // For socket-based receivers (PHP sidecar), verify the peer PID matches the
    // expected receiver PID that was registered during trusted initialization
    #[cfg(target_os = "linux")]
    if config.collect_all_threads() {
        grant_ptracer_permission(&receiver);
    }

    let collector = Collector::spawn(
        &receiver,
        config,
        config_str,
        metadata_string,
        message,
        sig_info,
        ucontext,
    )?;

    // We're done. Wrap up our interaction with the receiver.
    collector.finish(&timeout_manager);
    receiver.finish(&timeout_manager);

    Ok(())
}

/// Atomically swaps the metadata pointer to null and returns the old raw pointer.
/// Async-signal-safe (only performs an atomic swap).
///
/// Callers are responsible for the returned memory:
/// - Signal handlers: borrow via `&*ptr` and intentionally leak (avoids signal-unsafe `free`).
fn take_metadata_ptr() -> *mut (crate::crash_info::Metadata, String) {
    METADATA.swap(ptr::null_mut(), SeqCst)
}

/// Atomically swaps the config pointer to null and returns the old raw pointer.
/// Async-signal-safe (only performs an atomic swap).
///
/// Callers are responsible for the returned memory:
/// - Signal handlers: borrow via `&*ptr` and intentionally leak (avoids signal-unsafe `free`).
fn take_config_ptr() -> *mut (
    crate::shared::configuration::CrashtrackerConfiguration,
    String,
) {
    CONFIG.swap(ptr::null_mut(), SeqCst)
}

/// Takes the current metadata out of global storage, leaving it unset.
/// The returned value is properly owned and will be dropped by the caller.
/// Do NOT call from a signal handler; use `take_metadata_ptr` instead.
fn take_metadata() -> Option<(crate::crash_info::Metadata, String)> {
    let ptr = take_metadata_ptr();
    if ptr.is_null() {
        None
    } else {
        // Safety: ptr was created by Box::into_raw in update_metadata
        Some(*unsafe { Box::from_raw(ptr) })
    }
}

/// Takes the current config out of global storage, leaving it unset.
/// The returned value is properly owned and will be dropped by the caller.
/// Do NOT call from a signal handler; use `take_config_ptr` instead.
fn take_config() -> Option<(
    crate::shared::configuration::CrashtrackerConfiguration,
    String,
)> {
    let ptr = take_config_ptr();
    if ptr.is_null() {
        None
    } else {
        // Safety: ptr was created by Box::into_raw in update_config
        Some(*unsafe { Box::from_raw(ptr) })
    }
}

/// Grant the receiver process permission to ptrace this process via `PR_SET_PTRACER`.
///
/// For fork/exec receivers we have the child PID directly (trusted: we spawned it).
/// For socket-based receivers (e.g. PHP sidecar), we verify the peer PID via
/// `SO_PEERCRED` matches the expected receiver PID registered during initialization.
///
/// This is async-signal-safe: only calls `getsockopt` and `prctl`.
#[cfg(target_os = "linux")]
fn grant_ptracer_permission(receiver: &Receiver) {
    let ptracer_pid = match receiver.handle.pid {
        Some(pid) => pid,
        None => {
            let expected_pid = get_expected_receiver_pid();
            if expected_pid <= 0 {
                0
            } else {
                let mut cred: libc::ucred = unsafe { core::mem::zeroed() };
                let mut len = core::mem::size_of::<libc::ucred>() as libc::socklen_t;
                // SAFETY: getsockopt is async-signal-safe
                let ret = unsafe {
                    libc::getsockopt(
                        receiver.handle.uds_fd,
                        libc::SOL_SOCKET,
                        libc::SO_PEERCRED,
                        &mut cred as *mut _ as *mut libc::c_void,
                        &mut len,
                    )
                };
                if ret == 0 && cred.pid == expected_pid {
                    cred.pid
                } else {
                    0
                }
            }
        }
    };
    if ptracer_pid > 0 {
        // SAFETY: prctl is async-signal-safe
        unsafe {
            libc::prctl(libc::PR_SET_PTRACER, ptracer_pid as libc::c_ulong);
        }
    }
}

/// This function is designed to be when a program is at a terminal state
/// and the application wants to report an unhandled exception to the crashtracker
/// If this crashes, then the application will also crash. Ensure that this API is
/// called when the application is at a terminal state and exit quickly after.
///
/// This API handles reporting both the crash ping and the crash report for the
/// unhandled exception.
///
/// Preconditions:
/// - The crashtracker must be started
/// - The stacktrace must be valid
///
///  This function will spawn the receiver process and call an emit function to pipe over
///  the crash data. We don't use the collector process because we are not in a signal handler
///  Rather, we call emit_crashreport directly and pipe over data to the receiver
pub fn report_unhandled_exception(
    exception_type: Option<&str>,
    exception_message: Option<&str>,
    stacktrace: StackTrace,
) -> Result<(), CrashHandlerError> {
    // Although both report_unhandled_exception and handle_posix_signal_impl do similar things of
    //   1. Getting config and metadata
    //   2. Spawn receiver
    //   3. Set timeout
    //   4. Emit report
    //   5. Finish logic
    // It is not worth going out of the way to combine these because:
    //   1. The signal handler borrows and leaks (async-signal-safe); unifying them would require a
    //      generic or trait just to paper over a deliberate constraint, making the split harder to
    //      see.
    //   2. The emit + finish: completely different mechanisms (fork vs. direct IO, Collector vs.
    //      raw ProcessHandle).
    //   3. TimeoutManager::new(config.timeout()); one line, not worth extracting.

    // Turn crashtracker off to prevent a recursive crash report emission
    // We do not turn it back on because this function is not intended to be used as
    // a recurring mechanism to report exceptions. We expect the application to exit
    // after
    disable();

    let (config, config_str) = take_config().ok_or(CrashHandlerError::NoConfig)?;
    let (_metadata, metadata_str) = take_metadata().ok_or(CrashHandlerError::NoMetadata)?;

    let receiver = Receiver::from_crashtracker_config(&config)?;

    #[cfg(target_os = "linux")]
    if config.collect_all_threads() {
        grant_ptracer_permission(&receiver);
    }

    let timeout_manager = TimeoutManager::new(config.timeout());

    let pid = unsafe { libc::getpid() };
    let tid = libdd_common::threading::get_current_thread_id() as libc::pid_t;

    // This allocates but that is okay because we are not in the signal handling path
    // Both error type and error message are user-controlled and may contain newlines or protocol
    // sentinel strings (DD_CRASHTRACK_*). We need to escape newlines here, as the receiver treats
    // new lines as separate sections in the crash report, and this allows consumers to
    // potentially inject artitrary configuration and other sections into the crash report.
    // emit_message adds a second sanitization pass as defense-in-depth at the protocol
    // boundary.
    let error_type_str = exception_type
        .unwrap_or("<unknown>")
        .replace('\n', "\\n")
        .replace('\r', "\\r");
    let error_message_str = exception_message
        .unwrap_or("<no message>")
        .replace('\n', "\\n")
        .replace('\r', "\\r");
    let message = format!(
        "Process was terminated due to an unhandled exception of type '{error_type_str}'. \
         Message: {error_message_str}"
    );

    // Duplicate the socket fd before handing it to UnixStream so we retain an fd to poll on after
    // the write end is closed.  OwnedFd is the scope guard: it closes poll_fd on any exit path.
    //
    // SAFETY: dup() returns a fresh fd; we are its sole owner.  ProcessHandle only polls it
    // (wait_for_pollhup) and has no Drop impl, so it never closes the fd. Closing it here
    // after finish() returns is the first and only close
    let poll_fd = unsafe { OwnedFd::from_raw_fd(libc::dup(receiver.handle.uds_fd)) };
    let receiver_pid = receiver.handle.pid;

    {
        let mut unix_stream = unsafe { UnixStream::from_raw_fd(receiver.handle.uds_fd) };
        let _ = super::emitters::emit_crashreport(
            &mut unix_stream,
            &config,
            &config_str,
            &metadata_str,
            Some(message.as_str()),
            super::emitters::CrashKindData::UnhandledException { stacktrace },
            pid,
            tid,
        );
        // unix_stream is dropped here, closing the write end of the socket.
        // This signals EOF to the receiver so it can finish writing the crash report.
    }

    // Wait for the receiver to signal it is done (POLLHUP on the dup'd fd), then reap it.
    // poll_fd is dropped at the end of this function, closing the fd.
    let finish_handle =
        super::process_handle::ProcessHandle::new(poll_fd.as_raw_fd(), receiver_pid);
    finish_handle.finish(&timeout_manager);

    Ok(())
}
#[cfg(test)]
mod tests {
    use super::*;
    use core::time::Duration;

    fn make_test_metadata() -> Metadata {
        Metadata {
            library_name: "test-lib".to_string(),
            library_version: "1.0.0".to_string(),
            family: "test-family".to_string(),
            tags: vec![],
        }
    }

    fn make_test_config() -> CrashtrackerConfiguration {
        let builder = CrashtrackerConfiguration::builder();
        builder.timeout(Duration::from_secs(1)).build().unwrap()
    }

    /// Clears METADATA global, properly freeing any existing Box
    fn clear_metadata() {
        let ptr = METADATA.swap(ptr::null_mut(), SeqCst);
        if !ptr.is_null() {
            unsafe { drop(Box::from_raw(ptr)) };
        }
    }

    /// Clears CONFIG global, properly freeing any existing Box
    fn clear_config() {
        let ptr = CONFIG.swap(ptr::null_mut(), SeqCst);
        if !ptr.is_null() {
            unsafe { drop(Box::from_raw(ptr)) };
        }
    }

    #[test]
    fn test_register_panic_hook() {
        assert!(PREVIOUS_PANIC_HOOK.load(SeqCst).is_null());

        let result = register_panic_hook();
        assert!(result.is_ok());

        assert!(!PREVIOUS_PANIC_HOOK.load(SeqCst).is_null());
    }

    #[test]
    fn test_panic_message_storage_and_retrieval() {
        // Test that panic messages can be stored and retrieved via atomic pointer
        let test_message = "test panic message".to_string();
        let message_ptr = Box::into_raw(Box::new(test_message.clone()));

        // Store the message
        let old_ptr = PANIC_MESSAGE.swap(message_ptr, SeqCst);
        assert!(old_ptr.is_null()); // Should be null initially

        // Retrieve and verify
        let retrieved_ptr = PANIC_MESSAGE.swap(ptr::null_mut(), SeqCst);
        assert!(!retrieved_ptr.is_null());

        unsafe {
            let retrieved_message = *Box::from_raw(retrieved_ptr);
            assert_eq!(retrieved_message, test_message);
        }
    }

    #[test]
    fn test_panic_message_null_handling() {
        // Test that null message pointers are handled correctly
        PANIC_MESSAGE.store(ptr::null_mut(), SeqCst);

        let message_ptr = PANIC_MESSAGE.load(SeqCst);
        assert!(message_ptr.is_null());

        // Swapping null with null should be safe
        let old_ptr = PANIC_MESSAGE.swap(ptr::null_mut(), SeqCst);
        assert!(old_ptr.is_null());
    }

    #[test]
    fn test_panic_message_replacement() {
        // Test that replacing an existing message cleans up the old one
        let message1 = "first message".to_string();
        let message2 = "second message".to_string();

        let ptr1 = Box::into_raw(Box::new(message1));
        let ptr2 = Box::into_raw(Box::new(message2.clone()));

        PANIC_MESSAGE.store(ptr1, SeqCst);
        let old_ptr = PANIC_MESSAGE.swap(ptr2, SeqCst);

        // Old pointer should be the first one
        assert_eq!(old_ptr, ptr1);

        // Clean up both
        unsafe {
            drop(Box::from_raw(old_ptr));
            let final_ptr = PANIC_MESSAGE.swap(ptr::null_mut(), SeqCst);
            let final_message = *Box::from_raw(final_ptr);
            assert_eq!(final_message, message2);
        }
    }

    #[test]
    fn test_metadata_update_atomic() {
        // Test that metadata updates are atomic
        let metadata = Metadata {
            library_name: "test".to_string(),
            library_version: "1.0.0".to_string(),
            family: "test_family".to_string(),
            tags: vec![],
        };

        let result = update_metadata(metadata.clone());
        assert!(result.is_ok());

        // Verify metadata was stored
        let metadata_ptr = METADATA.load(SeqCst);
        assert!(!metadata_ptr.is_null());

        unsafe {
            let (stored_metadata, _) = &*metadata_ptr;
            assert_eq!(stored_metadata.library_name, "test");
        }
    }

    #[test]
    fn test_format_message_with_message_and_location() {
        let location = panic::Location::caller();
        let result = format_message("message", "test panic", Some(location));

        assert!(result.starts_with("Process panicked with message \"test panic\" ("));
        assert!(result.contains(&format!("{}:", location.file())));
        assert!(result.contains(&format!(":{}", location.line())));
        assert!(result.ends_with(&format!("{})", location.column())));
    }

    #[test]
    fn test_format_message_with_message_no_location() {
        let result = format_message("message", "test panic", None);
        assert_eq!(result, "Process panicked with message \"test panic\"");
    }

    #[test]
    fn test_format_message_empty_message_with_location() {
        let location = panic::Location::caller();
        let result = format_message("unknown type", "", Some(location));

        assert!(result.starts_with("Process panicked with unknown type ("));
        assert!(result.contains(&format!("{}:", location.file())));
        assert!(result.ends_with(&format!("{})", location.column())));
    }

    #[test]
    fn test_format_message_empty_message_no_location() {
        let result = format_message("unknown type", "", None);
        assert_eq!(result, "Process panicked with unknown type");
    }

    #[test]
    fn test_format_message_different_categories() {
        let result1 = format_message("message", "test", None);
        assert_eq!(result1, "Process panicked with message \"test\"");

        let result2 = format_message("unknown type", "", None);
        assert_eq!(result2, "Process panicked with unknown type");

        let result3 = format_message("custom category", "content", None);
        assert_eq!(result3, "Process panicked with custom category \"content\"");
    }

    #[test]
    fn test_format_message_with_special_characters() {
        let result = format_message("message", "test \"quoted\" 'text'", None);
        assert_eq!(
            result,
            "Process panicked with message \"test \"quoted\" 'text'\""
        );
    }

    // take_metadata_ptr

    #[test]
    fn test_take_metadata_ptr_returns_null_when_unset() {
        clear_metadata();
        assert!(take_metadata_ptr().is_null());
    }

    #[test]
    fn test_take_metadata_ptr_takes_value_and_leaves_null() {
        clear_metadata();
        update_metadata(make_test_metadata()).unwrap();

        let ptr = take_metadata_ptr();
        assert!(!ptr.is_null());

        // Storage is now null; a second take returns null.
        assert!(take_metadata_ptr().is_null());

        // Reconstruct the Box to avoid a leak.
        unsafe { drop(Box::from_raw(ptr)) };
    }

    #[test]
    fn test_take_metadata_ptr_preserves_data() {
        clear_metadata();
        let metadata = make_test_metadata();
        update_metadata(metadata.clone()).unwrap();

        let ptr = take_metadata_ptr();
        assert!(!ptr.is_null());

        let (stored_metadata, stored_json) = unsafe { &*ptr };
        assert_eq!(stored_metadata.library_name, metadata.library_name);
        assert_eq!(stored_metadata.library_version, metadata.library_version);
        assert_eq!(stored_metadata.family, metadata.family);
        // The serialised string must be valid non-empty JSON.
        assert!(!stored_json.is_empty());
        assert!(serde_json::from_str::<serde_json::Value>(stored_json).is_ok());

        unsafe { drop(Box::from_raw(ptr)) };
    }

    // take_config_ptr

    #[test]
    fn test_take_config_ptr_returns_null_when_unset() {
        clear_config();
        assert!(take_config_ptr().is_null());
    }

    #[test]
    fn test_take_config_ptr_takes_value_and_leaves_null() {
        clear_config();
        update_config(make_test_config()).unwrap();

        let ptr = take_config_ptr();
        assert!(!ptr.is_null());

        // Storage is now null; a second take returns null.
        assert!(take_config_ptr().is_null());

        unsafe { drop(Box::from_raw(ptr)) };
    }

    // take_metadata

    #[test]
    fn test_take_metadata_returns_none_when_unset() {
        clear_metadata();
        assert!(take_metadata().is_none());
    }

    #[test]
    fn test_take_metadata_returns_value_and_leaves_none() {
        clear_metadata();
        let metadata = make_test_metadata();
        update_metadata(metadata.clone()).unwrap();

        let (taken_metadata, taken_json) = take_metadata().expect("should return Some");
        assert_eq!(taken_metadata.library_name, metadata.library_name);
        assert_eq!(taken_metadata.library_version, metadata.library_version);
        assert_eq!(taken_metadata.family, metadata.family);
        assert!(!taken_json.is_empty());

        // Second take: storage is empty.
        assert!(take_metadata().is_none());
    }

    // take_config

    #[test]
    fn test_take_config_returns_none_when_unset() {
        clear_config();
        assert!(take_config().is_none());
    }

    #[test]
    fn test_take_config_returns_value_and_leaves_none() {
        clear_config();
        let config = make_test_config();
        update_config(config.clone()).unwrap();

        let (taken_config, taken_json) = take_config().expect("should return Some");
        assert_eq!(taken_config, config);
        assert!(!taken_json.is_empty());
        assert!(serde_json::from_str::<serde_json::Value>(&taken_json).is_ok());

        // Second take: storage is empty.
        assert!(take_config().is_none());
    }
}