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
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
// Copyright 2023-Present Datadog, Inc. https://www.datadoghq.com/
// SPDX-License-Identifier: Apache-2.0
#![cfg(unix)]

use super::{crash_handler::enable, receiver_manager::Receiver};
use crate::{
    clear_spans, clear_traces, collector::crash_handler::register_panic_hook,
    collector::signal_handler_manager::register_crash_handlers, crash_info::Metadata,
    reset_counters, shared::configuration::CrashtrackerReceiverConfig, update_config,
    update_metadata, CrashtrackerConfiguration,
};

pub static DEFAULT_SYMBOLS: [libc::c_int; 4] =
    [libc::SIGBUS, libc::SIGABRT, libc::SIGSEGV, libc::SIGILL];

pub fn default_signals() -> Vec<libc::c_int> {
    Vec::from(DEFAULT_SYMBOLS)
}

#[cfg(target_os = "linux")]
pub(super) fn mark_preload_logger_collector() {
    // This function is specific only for LD_PRELOAD testing
    // Best effort; this symbol exists only when the preload logger preload is present.
    const SYMBOL: &[u8] = b"dd_preload_logger_mark_collector\0";
    unsafe {
        let sym = libc::dlsym(libc::RTLD_DEFAULT, SYMBOL.as_ptr() as *const _);
        if !sym.is_null() {
            let func: extern "C" fn() = core::mem::transmute(sym);
            func();
        }
    }
}

/// Reinitialize the crash-tracking infrastructure after a fork.
/// This should be one of the first things done after a fork, to minimize the
/// chance that a crash occurs between the fork, and this call.
/// In particular, reset the counters that track the profiler state machine.
///
/// PRECONDITIONS:
///     This function assumes that the crash-tracker has previously been
///     initialized.
/// SAFETY:
///     Crash-tracking functions are not reentrant.
///     No other crash-handler functions should be called concurrently.
/// ATOMICITY:
///     This function is not atomic. A crash during its execution may lead to
///     unexpected crash-handling behaviour.
pub fn on_fork(
    config: CrashtrackerConfiguration,
    receiver_config: CrashtrackerReceiverConfig,
    metadata: Metadata,
) -> anyhow::Result<()> {
    clear_spans()?;
    clear_traces()?;
    reset_counters()?;
    // Leave the old signal handler in place: they are unaffected by fork.
    // https://man7.org/linux/man-pages/man2/sigaction.2.html
    // The altstack (if any) is similarly unaffected by fork:
    // https://man7.org/linux/man-pages/man2/sigaltstack.2.html

    // panic hook is unaffected by fork.

    update_metadata(metadata)?;
    update_config(config)?;
    Receiver::update_stored_config(receiver_config)?;
    Ok(())
}

/// Initialize the crash-tracking infrastructure.
///
/// PRECONDITIONS:
///     None.
/// SAFETY:
///     Crash-tracking functions are not reentrant.
///     No other crash-handler functions should be called concurrently.
/// ATOMICITY:
///     This function is not atomic. A crash during its execution may lead to
///     unexpected crash-handling behaviour.
pub fn init(
    config: CrashtrackerConfiguration,
    receiver_config: CrashtrackerReceiverConfig,
    metadata: Metadata,
) -> anyhow::Result<()> {
    update_metadata(metadata)?;
    update_config(config.clone())?;
    Receiver::update_stored_config(receiver_config)?;
    register_crash_handlers(&config)?;
    register_panic_hook()?;
    #[cfg(all(target_os = "linux", target_pointer_width = "64"))]
    super::assert_interceptor::install_assert_hook();
    enable();
    Ok(())
}

/// Reconfigure the crash-tracking infrastructure.
///
/// PRECONDITIONS:
///     None.
/// SAFETY:
///     Crash-tracking functions are not reentrant.
///     No other crash-handler functions should be called concurrently.
/// ATOMICITY:
///     This function is not atomic. A crash during its execution may lead to
///     unexpected crash-handling behaviour.
pub fn reconfigure(
    config: CrashtrackerConfiguration,
    receiver_config: CrashtrackerReceiverConfig,
    metadata: Metadata,
) -> anyhow::Result<()> {
    update_metadata(metadata)?;
    update_config(config.clone())?;
    Receiver::update_stored_config(receiver_config)?;
    enable();
    Ok(())
}

#[cfg(test)]
mod single_threaded_tests {
    use super::*;
    use crate::{
        begin_op, insert_span, insert_trace, CrashtrackerConfigurationBuilder, StacktraceCollection,
    };
    use chrono::Utc;
    use core::time::Duration;
    use libdd_common::tag;

    const PATH_TO_RECEIVER: &str = "/tmp/libdatadog/bin/libdatadog-crashtracking-receiver";
    // We can't run this in the main test runner because it (deliberately) crashes,
    // and would make all following tests unrunable.
    // To run this test,
    // ./build-profiling-ffi /tmp/libdatadog
    // mkdir /tmp/crashreports
    // look in /tmp/crashreports for the crash reports and output files
    #[ignore]
    #[test]
    fn test_crash() {
        let time = Utc::now().to_rfc3339();
        let dir = "/tmp/crashreports/";
        let output_url = format!("file://{dir}{time}.txt");

        let receiver_config = CrashtrackerReceiverConfig::new(
            vec![],
            vec![],
            PATH_TO_RECEIVER.to_string(),
            Some(format!("{dir}/stderr_{time}.txt")),
            Some(format!("{dir}/stdout_{time}.txt")),
        )
        .unwrap();
        let config = CrashtrackerConfigurationBuilder::default()
            .create_alt_stack(true)
            .demangle_names(true)
            .endpoint_url(output_url.as_str())
            .resolve_frames(StacktraceCollection::EnabledWithInprocessSymbols)
            .signals(default_signals())
            .timeout(Duration::from_secs(10))
            .use_alt_stack(true)
            .build()
            .unwrap();
        let metadata = Metadata::new(
            "libname".to_string(),
            "version".to_string(),
            "family".to_string(),
            vec![],
        );
        init(config, receiver_config, metadata).unwrap();
        begin_op(crate::OpTypes::ProfilerCollectingSample).unwrap();
        insert_span(42).unwrap();
        insert_trace(u128::MAX).unwrap();
        insert_span(12).unwrap();
        insert_trace(99399939399939393993).unwrap();

        let tag = tag!("apple", "banana");
        let metadata2 = Metadata::new(
            "libname".to_string(),
            "version".to_string(),
            "family".to_string(),
            vec![tag.to_string()],
        );
        update_metadata(metadata2).expect("metadata");

        std::thread::sleep(Duration::from_secs(2));

        let p: *const u32 = core::ptr::null();
        let q = unsafe { *p };
        assert_eq!(q, 3);
    }

    #[test]
    fn test_altstack_paradox() {
        let time = Utc::now().to_rfc3339();
        let dir = "/tmp/crashreports/";
        let output_url = format!("file://{dir}{time}.txt");

        // This should return an error, because we're creating an altstack without using it
        let config = CrashtrackerConfigurationBuilder::default()
            .create_alt_stack(true)
            .demangle_names(true)
            .endpoint_url(output_url.as_str())
            .resolve_frames(StacktraceCollection::EnabledWithInprocessSymbols)
            .timeout(Duration::from_secs(10))
            .build();

        // This is slightly over-tuned to the language of the error message, but it'd require some
        // novel engineering just for this test in order to tighten this up.
        let err = config.unwrap_err();
        assert_eq!(
            err.to_string(),
            "Cannot create an altstack without using it"
        );
    }

    #[cfg(target_os = "linux")]
    fn get_sigaltstack() -> Option<libc::stack_t> {
        let mut sigaltstack = libc::stack_t {
            ss_sp: core::ptr::null_mut(),
            ss_flags: 0,
            ss_size: 0,
        };
        let res = unsafe { libc::sigaltstack(core::ptr::null(), &mut sigaltstack) };
        if res == 0 {
            Some(sigaltstack)
        } else {
            None
        }
    }

    #[cfg_attr(miri, ignore)]
    #[cfg(target_os = "linux")]
    #[test]
    fn test_altstack_use_create() {
        // This test initializes crashtracking in a fork, then waits on the exit status of the
        // child. We check for an atypical exit status in order to ensure that only our
        // desired exit path is taken.

        let time = Utc::now().to_rfc3339();
        let dir = "/tmp/crashreports/";
        let output_url = format!("file://{dir}{time}.txt");

        let receiver_config = CrashtrackerReceiverConfig::new(
            vec![],
            vec![],
            PATH_TO_RECEIVER.to_string(),
            Some(format!("{dir}/stderr_{time}.txt")),
            Some(format!("{dir}/stdout_{time}.txt")),
        )
        .unwrap();
        let config = CrashtrackerConfigurationBuilder::default()
            .create_alt_stack(true)
            .use_alt_stack(true)
            .endpoint_url(output_url.as_str())
            .resolve_frames(StacktraceCollection::EnabledWithInprocessSymbols)
            .signals(default_signals())
            .timeout(Duration::from_secs(10))
            .demangle_names(true)
            .build()
            .unwrap();
        let metadata = Metadata::new(
            "libname".to_string(),
            "version".to_string(),
            "family".to_string(),
            vec![],
        );

        // At this point we fork, because we're going to be looking at process-level state
        match unsafe { libc::fork() } {
            -1 => {
                panic!("Failed to fork");
            }
            0 => {
                // Child process
                // Get the current state of the altstack
                let initial_sigaltstack = get_sigaltstack();
                assert!(
                    initial_sigaltstack.is_some(),
                    "Failed to get initial sigaltstack"
                );

                // Initialize crashtracking.  This will
                // - create a new altstack
                // - set the SIGUBS/SIGSEGV handlers with SA_ONSTACK
                init(config, receiver_config, metadata).unwrap();

                // Get the state of the altstack after initialization
                let after_init_sigaltstack = get_sigaltstack();

                // Compare the initial and after-init sigaltstacks
                if initial_sigaltstack == after_init_sigaltstack {
                    eprintln!("Initial sigaltstack: {initial_sigaltstack:?}");
                    std::process::exit(-5);
                }

                // Check the SIGBUS and SIGSEGV handlers are set with SA_ONSTACK
                let mut sigaction = libc::sigaction {
                    sa_sigaction: 0,
                    sa_mask: unsafe { core::mem::zeroed::<libc::sigset_t>() },
                    sa_flags: 0,
                    sa_restorer: None,
                };

                let mut exit_code = -5;

                for signal in default_signals() {
                    let signame = crate::signal_from_signum(signal).unwrap();
                    exit_code -= 1;
                    let res = unsafe { libc::sigaction(signal, core::ptr::null(), &mut sigaction) };
                    if res != 0 {
                        eprintln!("Failed to get {signame:?} handler");
                        std::process::exit(exit_code);
                    }

                    exit_code -= 1;
                    if sigaction.sa_flags & libc::SA_ONSTACK != libc::SA_ONSTACK {
                        eprintln!("Expected {signame:?} handler to have SA_ONSTACK");
                        std::process::exit(exit_code);
                    }
                }

                // OK, we're done
                std::process::exit(42);
            }
            pid => {
                // Parent process
                let mut status = 0;
                let _ = unsafe { libc::waitpid(pid, &mut status, 0) };

                // `status` is not the exit code, gotta unwrap some layers
                if libc::WIFEXITED(status) {
                    let exit_code = libc::WEXITSTATUS(status);
                    assert_eq!(exit_code, 42, "Child process exited with unexpected status");
                } else {
                    panic!("Child process did not exit normally");
                }
            }
        }
    }

    #[cfg_attr(miri, ignore)]
    #[cfg(target_os = "linux")]
    #[test]
    fn test_altstack_use_nocreate() {
        // Similar to the other test, this one operates inside of a fork in order to prevent
        // poisoning the main process state.

        let time = Utc::now().to_rfc3339();
        let dir = "/tmp/crashreports/";
        let output_url = format!("file://{dir}{time}.txt");

        let receiver_config = CrashtrackerReceiverConfig::new(
            vec![],
            vec![],
            PATH_TO_RECEIVER.to_string(),
            Some(format!("{dir}/stderr_{time}.txt")),
            Some(format!("{dir}/stdout_{time}.txt")),
        )
        .unwrap();
        let config = CrashtrackerConfigurationBuilder::default()
            .use_alt_stack(true)
            .endpoint_url(output_url.as_str())
            .resolve_frames(StacktraceCollection::EnabledWithInprocessSymbols)
            .signals(default_signals())
            .timeout(Duration::from_secs(10))
            .demangle_names(true)
            .build()
            .unwrap();
        let metadata = Metadata::new(
            "libname".to_string(),
            "version".to_string(),
            "family".to_string(),
            vec![],
        );

        // At this point we fork, because we're going to be looking at process-level state
        match unsafe { libc::fork() } {
            -1 => {
                panic!("Failed to fork");
            }
            0 => {
                // Child process
                // Get the current state of the altstack
                let initial_sigaltstack = get_sigaltstack();
                assert!(
                    initial_sigaltstack.is_some(),
                    "Failed to get initial sigaltstack"
                );

                // Initialize crashtracking.  This will
                // - create a new altstack
                // - set the SIGUBS/SIGSEGV handlers with SA_ONSTACK
                init(config, receiver_config, metadata).unwrap();

                // Get the state of the altstack after initialization
                let after_init_sigaltstack = get_sigaltstack();

                // Compare the initial and after-init sigaltstacks:  they should be the same!
                if initial_sigaltstack != after_init_sigaltstack {
                    eprintln!("Initial sigaltstack: {initial_sigaltstack:?}");
                    std::process::exit(-5);
                }

                // Even though the other test checks for the SA_ONSTACK flag on the signal handlers,
                // we double-check here because the options need to be decoupled
                let mut sigaction = libc::sigaction {
                    sa_sigaction: 0,
                    sa_mask: unsafe { core::mem::zeroed::<libc::sigset_t>() },
                    sa_flags: 0,
                    sa_restorer: None,
                };

                // First, SIGBUS
                let res =
                    unsafe { libc::sigaction(libc::SIGBUS, core::ptr::null(), &mut sigaction) };
                if res != 0 {
                    eprintln!("Failed to get SIGBUS handler");
                    std::process::exit(-6);
                }
                if sigaction.sa_flags & libc::SA_ONSTACK != libc::SA_ONSTACK {
                    eprintln!("Expected SIGBUS handler to have SA_ONSTACK");
                    std::process::exit(-7);
                }

                // Second, SIGSEGV
                let res =
                    unsafe { libc::sigaction(libc::SIGSEGV, core::ptr::null(), &mut sigaction) };
                if res != 0 {
                    eprintln!("Failed to get SIGSEGV handler");
                    std::process::exit(-8);
                }
                if sigaction.sa_flags & libc::SA_ONSTACK != libc::SA_ONSTACK {
                    eprintln!("Expected SIGSEGV handler to have SA_ONSTACK");
                    std::process::exit(-9);
                }

                // OK, we're done
                std::process::exit(42);
            }
            pid => {
                // Parent process
                let mut status = 0;
                let _ = unsafe { libc::waitpid(pid, &mut status, 0) };

                // `status` is not the exit code, gotta unwrap some layers
                if libc::WIFEXITED(status) {
                    let exit_code = libc::WEXITSTATUS(status);
                    assert_eq!(exit_code, 42, "Child process exited with unexpected status");
                } else {
                    panic!("Child process did not exit normally");
                }
            }
        }
    }

    #[cfg_attr(miri, ignore)]
    #[cfg(target_os = "linux")]
    #[test]
    fn test_altstack_nouse() {
        // This checks that when we do not request the altstack, we do not get the altstack

        let time = Utc::now().to_rfc3339();
        let dir = "/tmp/crashreports/";
        let output_url = format!("file://{dir}{time}.txt");

        let receiver_config = CrashtrackerReceiverConfig::new(
            vec![],
            vec![],
            PATH_TO_RECEIVER.to_string(),
            Some(format!("{dir}/stderr_{time}.txt")),
            Some(format!("{dir}/stdout_{time}.txt")),
        )
        .unwrap();
        let config = CrashtrackerConfigurationBuilder::default()
            .demangle_names(true)
            .endpoint_url(output_url.as_str())
            .resolve_frames(StacktraceCollection::EnabledWithInprocessSymbols)
            .signals(default_signals())
            .timeout(Duration::from_secs(10))
            .build()
            .unwrap();
        let metadata = Metadata::new(
            "libname".to_string(),
            "version".to_string(),
            "family".to_string(),
            vec![],
        );

        // At this point we fork, because we're going to be looking at process-level state
        match unsafe { libc::fork() } {
            -1 => {
                panic!("Failed to fork");
            }
            0 => {
                // Child process
                // Get the current state of the altstack
                let initial_sigaltstack = get_sigaltstack();
                assert!(
                    initial_sigaltstack.is_some(),
                    "Failed to get initial sigaltstack"
                );

                // Initialize crashtracking.  This will
                // - create a new altstack
                // - set the SIGUBS/SIGSEGV handlers with SA_ONSTACK
                init(config, receiver_config, metadata).unwrap();

                // Get the state of the altstack after initialization
                let after_init_sigaltstack = get_sigaltstack();

                // Compare the initial and after-init sigaltstacks:  they should be the same because
                // we did not enable anything!  This checks that we don't
                // erroneously build the altstack.
                if initial_sigaltstack != after_init_sigaltstack {
                    eprintln!("Initial sigaltstack: {initial_sigaltstack:?}");
                    std::process::exit(-5);
                }

                // Similarly, we need to be extra sure that SA_ONSTACK is not present.
                let mut sigaction = libc::sigaction {
                    sa_sigaction: 0,
                    sa_mask: unsafe { core::mem::zeroed::<libc::sigset_t>() },
                    sa_flags: 0,
                    sa_restorer: None,
                };

                // First, SIGBUS
                let res =
                    unsafe { libc::sigaction(libc::SIGBUS, core::ptr::null(), &mut sigaction) };
                if res != 0 {
                    eprintln!("Failed to get SIGBUS handler");
                    std::process::exit(-6);
                }
                if sigaction.sa_flags & libc::SA_ONSTACK == libc::SA_ONSTACK {
                    eprintln!("Expected SIGBUS handler not to have SA_ONSTACK");
                    std::process::exit(-7);
                }

                // Second, SIGSEGV
                let res =
                    unsafe { libc::sigaction(libc::SIGSEGV, core::ptr::null(), &mut sigaction) };
                if res != 0 {
                    eprintln!("Failed to get SIGSEGV handler");
                    std::process::exit(-8);
                }
                if sigaction.sa_flags & libc::SA_ONSTACK == libc::SA_ONSTACK {
                    eprintln!("Expected SIGSEGV handler not to have SA_ONSTACK");
                    std::process::exit(-9);
                }

                // OK, we're done
                std::process::exit(42);
            }
            pid => {
                // Parent process
                let mut status = 0;
                let _ = unsafe { libc::waitpid(pid, &mut status, 0) };

                // `status` is not the exit code, gotta unwrap some layers
                if libc::WIFEXITED(status) {
                    let exit_code = libc::WEXITSTATUS(status);
                    assert_eq!(exit_code, 42, "Child process exited with unexpected status");
                } else {
                    panic!("Child process did not exit normally");
                }
            }
        }
    }

    #[cfg_attr(miri, ignore)]
    #[cfg(target_os = "linux")]
    #[test]
    fn test_waitall_nohang() {
        // This test checks whether the crashtracking implementation can cause malformed `waitall()`
        // idioms to hang.
        // Consider the following code from the Ruby runtime:
        //
        //   static VALUE
        //   proc_waitall(VALUE _)
        //   {
        //       VALUE result;
        //       rb_pid_t pid;
        //       int status;
        //
        //       result = rb_ary_new();
        //       rb_last_status_clear();
        //
        //       for (pid = -1;;) {
        //           pid = rb_waitpid(-1, &status, 0);
        //           if (pid == -1) {
        //               int e = errno;
        //               if (e == ECHILD)
        //                   break;
        //               rb_syserr_fail(e, 0);
        //           }
        //           rb_ary_push(result, rb_assoc_new(PIDT2NUM(pid), rb_last_status_get()));
        //       }
        //       return result;
        //   }
        //
        // The intent here is to wait for all of one's child processes to exit.  This is a pretty
        // standard operation in multi-process situations, with one important caveat:  usually you
        // know your children ahead of time and can wait on them in a controlled,
        // intentional matter. Previous versions of crashtracking, which spawned long-lived
        // receiver processes, would interfere with this
        //
        // This implements the inner behavior of a test which allows the caller to control which
        // options are used.

        let time = Utc::now().to_rfc3339();
        let dir = "/tmp/crashreports/";
        let output_url = format!("file://{dir}{time}.txt");

        let receiver_config = CrashtrackerReceiverConfig::new(
            vec![],
            vec![],
            PATH_TO_RECEIVER.to_string(),
            Some(format!("{dir}/stderr_{time}.txt")),
            Some(format!("{dir}/stdout_{time}.txt")),
        )
        .unwrap();
        let config = CrashtrackerConfigurationBuilder::default()
            .create_alt_stack(true)
            .demangle_names(true)
            .endpoint_url(output_url.as_str())
            .resolve_frames(StacktraceCollection::EnabledWithInprocessSymbols)
            .signals(default_signals())
            .timeout(Duration::from_secs(10))
            .use_alt_stack(true)
            .build()
            .unwrap();

        let metadata = Metadata::new(
            "libname".to_string(),
            "version".to_string(),
            "family".to_string(),
            vec![],
        );

        // Since this test ultimately mutates process state, it's done inside of a fork just like
        // the other tests of the same ilk.
        match unsafe { libc::fork() } {
            -1 => {
                panic!("Failed to fork");
            }
            0 => {
                // Child process
                // This is where the test actually happens!
                init(config, receiver_config, metadata).unwrap();

                // Now spawn some short-lived child processes.
                // Note:  it's easy to confirm this test actually works by cranking the sleep
                // duration up past the timeout duration. At such a point, the test
                // should fail.
                let mut children = vec![];
                let sleep_duration = Duration::from_millis(100);
                let timeout_duration = Duration::from_millis(500);
                for _ in 0..10 {
                    match unsafe { libc::fork() } {
                        -1 => {
                            panic!("Failed to fork");
                        }
                        0 => {
                            // Grandchild process
                            std::thread::sleep(sleep_duration);
                            std::process::exit(0); // normal exit, since we're testing waitall
                        }
                        pid => {
                            // Parent process
                            children.push(pid); // unused in this test
                        }
                    }
                }

                // Now, do the equivalent of the waitall loop.
                // One caveat is that we do not want to hang the test, so rather than an unbounded
                // `waitpid()`, use WNOHANG within a timer loop.
                let start_time = std::time::Instant::now();
                loop {
                    if start_time.elapsed() > timeout_duration {
                        eprintln!("Timed out waiting for children to exit");
                        std::process::exit(-6);
                    }

                    // Call waitpid with WNOHANG
                    let mut status = 0;
                    let pid = unsafe { libc::waitpid(-1, &mut status, libc::WNOHANG) };
                    let errno = std::io::Error::last_os_error().raw_os_error().unwrap();

                    if pid == -1 && errno == libc::ECHILD {
                        // No more children!  Done!
                        std::process::exit(42);
                    }
                }
            }
            pid => {
                // Parent process
                let mut status = 0;
                let _ = unsafe { libc::waitpid(pid, &mut status, 0) };

                // `status` is not the exit code, gotta unwrap some layers
                if libc::WIFEXITED(status) {
                    let exit_code = libc::WEXITSTATUS(status);
                    assert_eq!(exit_code, 42, "Child process exited with unexpected status");
                } else {
                    panic!("Child process did not exit normally");
                }
            }
        }
    }
}