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
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
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
// Copyright 2023-Present Datadog, Inc. https://www.datadoghq.com/
// SPDX-License-Identifier: Apache-2.0

use crate::collector::additional_tags::consume_and_emit_additional_tags;
use crate::collector::counters::emit_counters;
use crate::collector::spans::{emit_spans, emit_traces};
use crate::runtime_callback::{
    get_registered_callback, invoke_runtime_callback_with_writer, is_runtime_callback_registered,
    CallbackData,
};
use crate::shared::constants::*;
use crate::{
    translate_si_code, CrashtrackerConfiguration, ErrorKind, SignalNames, StackTrace,
    StacktraceCollection,
};
use libc::{siginfo_t, ucontext_t};
use std::{
    fs::File,
    io::{Read, Write},
};
use thiserror::Error;

#[derive(Debug, Error)]
pub enum EmitterError {
    #[error("Failed to write to output: {0}")]
    WriteError(#[from] std::io::Error),
    #[error("Failed to open file: {0}")]
    FileOpenError(std::io::Error),
    #[error("Null pointer provided for ucontext")]
    NullUcontext,
    #[error("Null pointer provided for siginfo")]
    NullSiginfo,
    #[error("Counter error: {0}")]
    CounterError(#[from] crate::collector::counters::CounterError),
    #[error("Atomic set error: {0}")]
    AtomicSetError(#[from] crate::collector::atomic_set::AtomicSetError),
    #[error("Serialization error: {0}")]
    SerializationError(#[from] serde_json::Error),
}

/// Crash-kind-specific data passed to `emit_crashreport`.
///
/// Each variant carries exactly the fields that are meaningful for that crash
/// origin. the shared fields (config, metadata, procinfo, …) remain as plain
/// function parameters
pub(crate) enum CrashKindData {
    UnixSignal {
        sig_info: *const siginfo_t,
        ucontext: *const ucontext_t,
    },
    UnhandledException {
        stacktrace: StackTrace,
    },
}

impl CrashKindData {
    fn error_kind(&self) -> ErrorKind {
        match self {
            CrashKindData::UnixSignal { .. } => ErrorKind::UnixSignal,
            CrashKindData::UnhandledException { .. } => ErrorKind::UnhandledException,
        }
    }
}

#[allow(clippy::too_many_arguments)]
pub(crate) fn emit_crashreport(
    pipe: &mut impl Write,
    config: &CrashtrackerConfiguration,
    config_str: &str,
    metadata_string: &str,
    message: Option<&str>,
    crash: CrashKindData,
    ppid: i32,
    crashing_tid: libc::pid_t,
) -> Result<(), EmitterError> {
    // Crash-ping
    // The receiver dispatches the crash ping as soon as it sees the metadata
    // section, so try to emit message, siginfo, and kind before it to make sure
    // we have an enhanced crash ping message
    emit_config(pipe, config_str)?;
    emit_message(pipe, message)?;

    match &crash {
        CrashKindData::UnixSignal { sig_info, .. } => {
            emit_siginfo(pipe, *sig_info)?;
        }
        CrashKindData::UnhandledException { .. } => {
            // Unhandled exceptions have no signal info
        }
    }

    emit_kind(pipe, &crash.error_kind())?;
    emit_metadata(pipe, metadata_string)?;

    // Shared process context
    emit_procinfo(pipe, ppid, crashing_tid)?;
    emit_counters(pipe)?;
    emit_spans(pipe)?;
    consume_and_emit_additional_tags(pipe)?;
    emit_traces(pipe)?;

    #[cfg(target_os = "linux")]
    emit_proc_self_maps(pipe)?;

    // Stack trace emission
    match crash {
        CrashKindData::UnixSignal { ucontext, .. } => {
            emit_ucontext(pipe, ucontext)?;
            if config.resolve_frames() != StacktraceCollection::Disabled {
                // SAFETY: `ucontext` comes from the signal handler and points to
                // valid kernel-saved registers. This is called last so that even
                // if the unwinder crashes, the other crash data has already been
                // written. The crash handler is non-reentrant and single-threaded
                unsafe { emit_backtrace_by_frames(pipe, config.resolve_frames(), ucontext)? };
            }
            if is_runtime_callback_registered() {
                emit_runtime_stack(pipe)?;
            }
        }
        CrashKindData::UnhandledException { stacktrace } => {
            // SAFETY: This branch only executes for unhandled exceptions, never
            // from a signal handler
            unsafe { emit_whole_stacktrace(pipe, stacktrace)? };
        }
    }

    writeln!(pipe, "{DD_CRASHTRACK_DONE}")?;
    pipe.flush()?;
    Ok(())
}

/// Emit a stacktrace onto the given handle as formatted json.
/// 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.
unsafe fn emit_backtrace_by_frames(
    w: &mut impl Write,
    resolve_frames: StacktraceCollection,
    ucontext: *const ucontext_t,
) -> Result<(), EmitterError> {
    writeln!(w, "{DD_CRASHTRACK_BEGIN_STACKTRACE}")?;

    // On macOS, backtrace::trace_unsynchronized fails in forked children because
    // macOS restricts many APIs after fork-without-exec. Walk the frame pointer
    // chain directly from the saved ucontext registers instead. The parent's
    // stack memory is still readable in the forked child.
    #[cfg(target_os = "macos")]
    {
        let _ = resolve_frames;
        // SAFETY: `ucontext` originates from the signal handler and points to
        // the kernel-saved register snapshot. The caller guarantees we are in a
        // crash-handling context where the parent's stack is still readable
        // (copy-on-write after fork)
        unsafe { emit_macos_backtrace_from_ucontext(w, ucontext)? };
    }

    // On Linux, use the bundled libunwind. unw_init_local2(cursor, ucontext, 0)
    // seeds the unwinder from the saved CPU context that the OS captured at the
    // moment of the crash, so we start already past the signal frame at the
    // actual faulting instruction. This is essential on musl libc (Alpine
    // Linux), where the signal trampoline provides no DWARF unwind info and
    // libgcc's unwinder cannot cross the signal frame boundary.
    #[cfg(target_os = "linux")]
    // SAFETY: `ucontext` originates from the signal handler and points to the
    // kernel-saved register snapshot. The caller guarantees single-threaded,
    // non-reentrant crash-handler execution
    unsafe {
        emit_backtrace_via_libunwind(w, resolve_frames, ucontext)?
    };
    writeln!(w, "{DD_CRASHTRACK_END_STACKTRACE}")?;
    w.flush()?;
    Ok(())
}

/// Unwind the stack using the bundled libunwind, seeded from the OS-captured
/// ucontext.
///
/// `unw_init_local2(cursor, ucontext, 0)` initialises the cursor from the
/// register snapshot that the kernel saved at the moment of the fault. The
/// unwinder therefore starts directly at the faulting instruction; it never
/// has to walk backward through the signal trampoline frame.
///
/// This matters on musl libc (Alpine Linux x86_64): musl's signal trampoline
/// does not carry DWARF unwind info, so libgcc's unwinder (used by the
/// `backtrace` crate) cannot cross the frame boundary and gets stuck inside
/// the signal handler. libunwind's local unwinder has no such limitation.
///
/// We choose to use step instead of backtrace2, because we want to eagerly flush
/// frame by frame
///
/// For each frame we emit:
///   - `ip`  / `sp`                             — always
///   - `module_base_address` / `symbol_address` — when `dladdr` succeeds
///   - `function`                               — for `EnabledWithInprocessSymbols`
#[cfg(target_os = "linux")]
unsafe fn emit_backtrace_via_libunwind(
    w: &mut impl Write,
    resolve_frames: StacktraceCollection,
    ucontext: *const ucontext_t,
) -> Result<(), EmitterError> {
    use libdd_libunwind_sys::{
        unw_get_proc_name, unw_get_reg, unw_init_local2, unw_step, UnwCursor, UnwWord, UNW_REG_FP,
        UNW_REG_IP, UNW_REG_SP,
    };

    if ucontext.is_null() {
        return Ok(());
    }

    // SAFETY: UnwCursor is a repr(C) struct of plain integers (`[u64; 127]`);
    // all-zeros is a valid bit pattern
    let mut cursor: UnwCursor = unsafe { core::mem::zeroed() };

    // SAFETY: `cursor` is zeroed and is valid for initialization.
    // `ucontext` was checked non-null above and points to the kernel-saved
    // register snapshot captured by the signal handler. The const-to-mut cast
    // is ok: libunwind only reads the context to seed the cursor
    let ret = unsafe { unw_init_local2(&mut cursor, ucontext as *mut _, 1) };
    if ret != 0 {
        return Ok(());
    }

    const MAX_FRAMES: usize = 512;
    for _ in 0..MAX_FRAMES {
        let mut ip: UnwWord = 0;
        let mut sp: UnwWord = 0;
        let mut fp: UnwWord = 0;

        // SAFETY: `cursor` was successfully initialized by `unw_init_local2`
        // and is advanced by `unw_step` at the end of each iteration.
        // UNW_REG_IP and UNW_REG_SP are valid libunwind register constants
        if unsafe { unw_get_reg(&mut cursor, UNW_REG_IP, &mut ip) } != 0 || ip == 0 {
            break;
        }
        let _ = unsafe { unw_get_reg(&mut cursor, UNW_REG_SP, &mut sp) };
        let _ = unsafe { unw_get_reg(&mut cursor, UNW_REG_FP, &mut fp) };

        write!(w, "{{\"ip\": \"0x{ip:x}\"")?;
        write!(w, ", \"sp\": \"0x{sp:x}\"")?;
        write!(w, ", \"fp\": \"0x{fp:x}\"")?;

        // SAFETY: Dl_info is a repr(C) struct of pointers and integers;
        // all-zeros (null pointers, zero integers) is a valid representation
        let mut dl_info: libc::Dl_info = unsafe { core::mem::zeroed() };
        // SAFETY: `ip` is a code address obtained from the unwinder.
        // dladdr only reads ld.so internal tables (no allocation, no locks)
        // making it safe to call from a signal handler
        if unsafe { libc::dladdr(ip as *const libc::c_void, &mut dl_info) } != 0 {
            if !dl_info.dli_fbase.is_null() {
                write!(w, ", \"module_base_address\": \"{:?}\"", dl_info.dli_fbase)?;
            }
            if !dl_info.dli_saddr.is_null() {
                write!(w, ", \"symbol_address\": \"{:?}\"", dl_info.dli_saddr)?;
            }
        }

        if resolve_frames == StacktraceCollection::EnabledWithInprocessSymbols {
            let mut name_buf: [libc::c_char; 256] = [0; 256];
            // SAFETY: `cursor` is in a valid state (unw_get_reg succeeded).
            // `name_buf` is a valid stack-allocated buffer with known length.
            if unsafe {
                unw_get_proc_name(
                    &mut cursor,
                    name_buf.as_mut_ptr(),
                    name_buf.len(),
                    core::ptr::null_mut(),
                )
            } == 0
            {
                // SAFETY: unw_get_proc_name returned 0 (success), guaranteeing
                // a NUL-terminated string was written into name_buf.
                let name = unsafe { core::ffi::CStr::from_ptr(name_buf.as_ptr()) };
                if let Ok(s) = name.to_str() {
                    write!(w, ", \"function\": \"{s}\"")?;
                }
            }
        }

        writeln!(w, "}}")?;
        w.flush()?;

        // SAFETY: `cursor` is in a valid state; unw_step advances to the next
        // frame or returns <= 0 when no more frames remain.
        if unsafe { unw_step(&mut cursor) } <= 0 {
            break;
        }
    }

    Ok(())
}

/// Walk the frame pointer chain from the ucontext's saved registers.
///
/// After fork(), the child process has a copy-on-write view of the parent's
/// stack memory, so the frame pointer chain from the crashed thread is still
/// readable. This avoids depending on `backtrace::trace_unsynchronized` which
/// uses macOS APIs that don't work in forked-but-not-exec'd children.
///
/// For each IP we call `dladdr` to resolve the symbol name, symbol address,
/// and containing shared-object path. `dladdr` is safe here because it only
/// reads dyld's internal data structures (no allocation, no Mach IPC).
#[cfg(target_os = "macos")]
unsafe fn emit_macos_backtrace_from_ucontext(
    w: &mut impl Write,
    ucontext: *const ucontext_t,
) -> Result<(), EmitterError> {
    if ucontext.is_null() {
        return Ok(());
    }
    let mcontext = unsafe { (*ucontext).uc_mcontext };
    if mcontext.is_null() {
        return Ok(());
    }

    // SAFETY: pthread_self and pthread_get_stack{addr,size}_np are
    // async-signal-safe on macOS and always succeed for the calling thread.
    let thread = unsafe { libc::pthread_self() };
    let stack_top = unsafe { libc::pthread_get_stackaddr_np(thread) } as usize;
    let stack_size = unsafe { libc::pthread_get_stacksize_np(thread) };
    let stack_bottom = stack_top.saturating_sub(stack_size);

    let in_stack_bounds = |addr: usize, len: usize| -> bool {
        let end = addr.saturating_add(len);
        addr >= stack_bottom && end <= stack_top
    };

    // SAFETY: `mcontext` was checked non-null above and is the kernel-provided
    // machine context from the signal handler's ucontext.
    let ss = unsafe { &(*mcontext).__ss };
    #[cfg(target_arch = "aarch64")]
    let (pc, mut fp) = (ss.__pc as usize, ss.__fp as usize);
    #[cfg(target_arch = "x86_64")]
    let (pc, mut fp) = (ss.__rip as usize, ss.__rbp as usize);

    // SAFETY: `pc` is a valid code address from the kernel-saved register state.
    unsafe { emit_frame_with_dladdr(w, pc)? };

    const MAX_FRAMES: usize = 512;
    for _ in 0..MAX_FRAMES {
        if fp == 0 || fp % core::mem::align_of::<usize>() != 0 {
            break;
        }
        if !in_stack_bounds(fp, 2 * core::mem::size_of::<usize>()) {
            break;
        }
        // SAFETY: `fp` is non-zero, properly aligned, and the two-word frame
        // record [saved_fp, return_addr] lies within the validated thread stack
        // bounds (checked by in_stack_bounds above). After fork(), the child
        // has a copy-on-write view of the parent's stack memory.
        let next_fp = unsafe { *(fp as *const usize) };
        let return_addr = unsafe { *((fp + core::mem::size_of::<usize>()) as *const usize) };
        if return_addr == 0 {
            break;
        }
        // SAFETY: `return_addr` is a code address read from a validated
        // in-bounds frame record on the thread stack.
        unsafe { emit_frame_with_dladdr(w, return_addr)? };
        if next_fp <= fp {
            break;
        }
        fp = next_fp;
    }

    Ok(())
}

/// Emit a single stack frame, enriched with `dladdr` symbol information.
#[cfg(target_os = "macos")]
unsafe fn emit_frame_with_dladdr(w: &mut impl Write, ip: usize) -> Result<(), EmitterError> {
    // SAFETY: Dl_info is a repr(C) struct of pointers and integers;
    // all-zeros (null pointers, zero integers) is a valid representation.
    let mut info: libc::Dl_info = unsafe { core::mem::zeroed() };
    // SAFETY: dladdr only reads dyld's internal data structures (no
    // allocation, no Mach IPC) making it async-signal-safe. `ip` is a code
    // address from the unwound stack or kernel-saved registers.
    let resolved = unsafe { libc::dladdr(ip as *const libc::c_void, &mut info) } != 0;

    write!(w, "{{\"ip\": \"0x{ip:x}\"")?;

    if resolved {
        if !info.dli_fbase.is_null() {
            write!(w, ", \"module_base_address\": \"{:?}\"", info.dli_fbase)?;
        }
        if !info.dli_saddr.is_null() {
            write!(w, ", \"symbol_address\": \"{:?}\"", info.dli_saddr)?;
        }
        if !info.dli_sname.is_null() {
            // SAFETY: dladdr returned non-zero and dli_sname is non-null, so
            // it points to a valid NUL-terminated C string in the shared
            // library's string table (static lifetime, read-only).
            let name = unsafe { core::ffi::CStr::from_ptr(info.dli_sname) };
            if let Ok(s) = name.to_str() {
                write!(w, ", \"function\": \"{s}\"")?;
            }
        }
    }

    writeln!(w, "}}")?;
    w.flush()?;
    Ok(())
}

/// SAFETY:
///    This function is not safe to call from a signal handler.
///    Although `serde_json::to_writer` does not technically allocate memory
///    itself, it takes in `StackTrace` which is allocated and is only intended
///    to be used in a non-signal-handler context
unsafe fn emit_whole_stacktrace(
    w: &mut impl Write,
    stacktrace: StackTrace,
) -> Result<(), EmitterError> {
    writeln!(w, "{DD_CRASHTRACK_BEGIN_WHOLE_STACKTRACE}")?;
    let _ = serde_json::to_writer(&mut *w, &stacktrace);
    writeln!(w)?;
    writeln!(w, "{DD_CRASHTRACK_END_WHOLE_STACKTRACE}")?;
    w.flush()?;
    Ok(())
}

fn emit_config(w: &mut impl Write, config_str: &str) -> Result<(), EmitterError> {
    writeln!(w, "{DD_CRASHTRACK_BEGIN_CONFIG}")?;
    writeln!(w, "{config_str}")?;
    writeln!(w, "{DD_CRASHTRACK_END_CONFIG}")?;
    w.flush()?;
    Ok(())
}

fn emit_kind<W: std::io::Write>(w: &mut W, kind: &ErrorKind) -> Result<(), EmitterError> {
    writeln!(w, "{DD_CRASHTRACK_BEGIN_KIND}")?;
    let _ = serde_json::to_writer(&mut *w, kind);
    writeln!(w)?;
    writeln!(w, "{DD_CRASHTRACK_END_KIND}")?;
    w.flush()?;
    Ok(())
}

fn emit_metadata(w: &mut impl Write, metadata_str: &str) -> Result<(), EmitterError> {
    writeln!(w, "{DD_CRASHTRACK_BEGIN_METADATA}")?;
    writeln!(w, "{metadata_str}")?;
    writeln!(w, "{DD_CRASHTRACK_END_METADATA}")?;
    w.flush()?;
    Ok(())
}

/// Write message content to the wire, escaping newlines and neutralizing sentinel
/// prefixes with no allocation, as this is called in the signal handler path.
///
/// The receiver's state machine splits input on newlines and treats any line
/// starting with `DD_CRASHTRACK_` as a protocol sentinel. If unsanitized
/// user-controlled content (an exception message passed through the FFI)
/// contains embedded newlines or sentinel-like text, it can break out of the
/// message block and inject arbitrary protocol sections, including a config
/// section that controls which endpoint receives the crash upload and arbitrary files
/// to include in the crash report.
///
/// This function streams directly to `w`:
/// 1. Escapes real `\n`/`\r` to `\\n`/`\\r` so the content stays on one wire line (the receiver
///    reverses this by replacing `\\n`/`\\r` with `\n`/`\r`)
/// 2. Prefixes with a space if the content starts with `DD_CRASHTRACK_` to prevent the receiver
///    from matching it as a sentinel
/// 3. Terminates with a newline
fn write_sanitized_message_line(w: &mut impl Write, message: &str) -> Result<(), EmitterError> {
    if message.starts_with("DD_CRASHTRACK_") {
        w.write_all(b" ")?;
    }
    let bytes = message.as_bytes();
    let mut start = 0;
    for (i, &byte) in bytes.iter().enumerate() {
        let escape: Option<&[u8]> = match byte {
            b'\n' => Some(b"\\n"),
            b'\r' => Some(b"\\r"),
            _ => None,
        };
        if let Some(replacement) = escape {
            if start < i {
                w.write_all(&bytes[start..i])?;
            }
            w.write_all(replacement)?;
            start = i + 1;
        }
    }
    if start < bytes.len() {
        w.write_all(&bytes[start..])?;
    }
    w.write_all(b"\n")?;
    Ok(())
}

fn emit_message(w: &mut impl Write, message: Option<&str>) -> Result<(), EmitterError> {
    if let Some(msg) = message {
        if !msg.trim().is_empty() {
            writeln!(w, "{DD_CRASHTRACK_BEGIN_MESSAGE}")?;
            write_sanitized_message_line(w, msg)?;
            writeln!(w, "{DD_CRASHTRACK_END_MESSAGE}")?;
            w.flush()?;
        }
    }
    Ok(())
}

fn emit_procinfo(w: &mut impl Write, pid: i32, tid: libc::pid_t) -> Result<(), EmitterError> {
    writeln!(w, "{DD_CRASHTRACK_BEGIN_PROCINFO}")?;
    writeln!(w, "{{\"pid\": {pid}, \"tid\": {tid} }}")?;
    writeln!(w, "{DD_CRASHTRACK_END_PROCINFO}")?;
    w.flush()?;
    Ok(())
}

#[cfg(target_os = "linux")]
/// Assumes that the memory layout of the current process (child) is identical to
/// the layout of the target process (parent), which should always be true.
fn emit_proc_self_maps(w: &mut impl Write) -> Result<(), EmitterError> {
    emit_text_file(w, "/proc/self/maps")?;
    Ok(())
}

#[cfg(target_os = "linux")]
fn emit_ucontext(w: &mut impl Write, ucontext: *const ucontext_t) -> Result<(), EmitterError> {
    if ucontext.is_null() {
        return Err(EmitterError::NullUcontext);
    }
    writeln!(w, "{DD_CRASHTRACK_BEGIN_UCONTEXT}")?;
    // SAFETY: the pointer is given to us by the signal handler, and is non-null.
    let uc = unsafe { &*ucontext };

    #[cfg(target_arch = "x86_64")]
    {
        let gregs = &uc.uc_mcontext.gregs;
        write!(w, "{{\"arch\": \"x86_64\", \"registers\": {{")?;
        write!(w, "\"rip\": \"0x{:016x}\"", gregs[libc::REG_RIP as usize])?;
        write!(w, ", \"rsp\": \"0x{:016x}\"", gregs[libc::REG_RSP as usize])?;
        write!(w, ", \"rbp\": \"0x{:016x}\"", gregs[libc::REG_RBP as usize])?;
        write!(w, ", \"rax\": \"0x{:016x}\"", gregs[libc::REG_RAX as usize])?;
        write!(w, ", \"rbx\": \"0x{:016x}\"", gregs[libc::REG_RBX as usize])?;
        write!(w, ", \"rcx\": \"0x{:016x}\"", gregs[libc::REG_RCX as usize])?;
        write!(w, ", \"rdx\": \"0x{:016x}\"", gregs[libc::REG_RDX as usize])?;
        write!(w, ", \"rsi\": \"0x{:016x}\"", gregs[libc::REG_RSI as usize])?;
        write!(w, ", \"rdi\": \"0x{:016x}\"", gregs[libc::REG_RDI as usize])?;
        write!(w, ", \"r8\": \"0x{:016x}\"", gregs[libc::REG_R8 as usize])?;
        write!(w, ", \"r9\": \"0x{:016x}\"", gregs[libc::REG_R9 as usize])?;
        write!(w, ", \"r10\": \"0x{:016x}\"", gregs[libc::REG_R10 as usize])?;
        write!(w, ", \"r11\": \"0x{:016x}\"", gregs[libc::REG_R11 as usize])?;
        write!(w, ", \"r12\": \"0x{:016x}\"", gregs[libc::REG_R12 as usize])?;
        write!(w, ", \"r13\": \"0x{:016x}\"", gregs[libc::REG_R13 as usize])?;
        write!(w, ", \"r14\": \"0x{:016x}\"", gregs[libc::REG_R14 as usize])?;
        write!(w, ", \"r15\": \"0x{:016x}\"", gregs[libc::REG_R15 as usize])?;
        // Preserve the full ucontext as a raw Debug string so that FPU state,
        // signal mask, and alternate-stack info are not lost.
        write!(w, "}}, \"raw\": \"{:?}\"", uc)?;
        writeln!(w, "}}")?;
    }

    #[cfg(target_arch = "aarch64")]
    {
        let mc = &uc.uc_mcontext;
        write!(w, "{{\"arch\": \"aarch64\", \"registers\": {{")?;
        write!(w, "\"pc\": \"0x{:016x}\"", mc.pc)?;
        write!(w, ", \"sp\": \"0x{:016x}\"", mc.sp)?;
        for i in 0..31 {
            write!(w, ", \"x{}\": \"0x{:016x}\"", i, mc.regs[i])?;
        }
        write!(w, "}}, \"raw\": \"{:?}\"", uc)?;
        writeln!(w, "}}")?;
    }

    writeln!(w, "{DD_CRASHTRACK_END_UCONTEXT}")?;
    w.flush()?;
    Ok(())
}

/// Emit runtime stack frames collected from registered runtime callback
///
/// This function invokes any registered runtime callback to collect runtime-specific
/// stack traces
///
/// If runtime stacks are being emitted frame by frame, this function writes structured JSON.
/// If not, it writes a single line with the stacktrace string.
///
/// SAFETY:
///     Crash-tracking functions are not reentrant.
///     No other crash-handler functions should be called concurrently.
/// SIGNAL SAFETY:
///     This function attempts to be signal safe by only invoking user-registered
///     callbacks and writing to the provided stream. The runtime callback itself
///     must be signal safe.
fn emit_runtime_stack(w: &mut impl Write) -> Result<(), EmitterError> {
    // SAFETY: Reads from a global atomic pointer set during crashtracker
    // initialization. The crash handler's non-reentrant execution model
    // guarantees no concurrent modification.
    let callback = unsafe { get_registered_callback() };

    let callback = match callback {
        Some(callback) => callback,
        None => return Ok(()),
    };

    match callback {
        CallbackData::Frame(_) => emit_runtime_stack_by_frames(w),
        CallbackData::StacktraceString(_) => emit_runtime_stack_by_stacktrace_string(w),
    }
}

fn emit_runtime_stack_by_frames(w: &mut impl Write) -> Result<(), EmitterError> {
    writeln!(w, "{DD_CRASHTRACK_BEGIN_RUNTIME_STACK_FRAME}")?;
    // SAFETY: The runtime callback was registered during initialization and
    // must be signal-safe per its API contract. The crash handler's
    // non-reentrant model ensures no concurrent invocation.
    unsafe { invoke_runtime_callback_with_writer(w)? };
    writeln!(w, "{DD_CRASHTRACK_END_RUNTIME_STACK_FRAME}")?;
    w.flush()?;
    Ok(())
}

fn emit_runtime_stack_by_stacktrace_string(w: &mut impl Write) -> Result<(), EmitterError> {
    writeln!(w, "{DD_CRASHTRACK_BEGIN_RUNTIME_STACK_STRING}")?;
    // SAFETY: Same contract as emit_runtime_stack_by_frames — the callback
    // was registered at init time and the crash handler runs non-reentrantly.
    unsafe { invoke_runtime_callback_with_writer(w)? };
    writeln!(w, "{DD_CRASHTRACK_END_RUNTIME_STACK_STRING}")?;
    w.flush()?;
    Ok(())
}

#[cfg(target_os = "macos")]
fn emit_ucontext(w: &mut impl Write, ucontext: *const ucontext_t) -> Result<(), EmitterError> {
    if ucontext.is_null() {
        return Err(EmitterError::NullUcontext);
    }
    // On MacOS, the actual machine context is behind a second pointer.
    // SAFETY: the pointer is given to us by the signal handler, and is non-null.
    let uc = unsafe { &*ucontext };
    let mcontext = uc.uc_mcontext;
    writeln!(w, "{DD_CRASHTRACK_BEGIN_UCONTEXT}")?;

    if mcontext.is_null() {
        // Fall back to raw Debug output if mcontext pointer is null.
        write!(w, "{{\"arch\": \"")?;
        #[cfg(target_arch = "x86_64")]
        write!(w, "x86_64")?;
        #[cfg(target_arch = "aarch64")]
        write!(w, "aarch64")?;
        write!(w, "\", \"registers\": {{}}")?;
        write!(w, ", \"raw\": \"{:?}\"", uc)?;
        writeln!(w, "}}")?;
    } else {
        // SAFETY: mcontext is non-null, provided by the signal handler.
        let mc = unsafe { &*mcontext };
        let ss = &mc.__ss;

        #[cfg(target_arch = "x86_64")]
        {
            write!(w, "{{\"arch\": \"x86_64\", \"registers\": {{")?;
            write!(w, "\"rip\": \"0x{:016x}\"", ss.__rip)?;
            write!(w, ", \"rsp\": \"0x{:016x}\"", ss.__rsp)?;
            write!(w, ", \"rbp\": \"0x{:016x}\"", ss.__rbp)?;
            write!(w, ", \"rax\": \"0x{:016x}\"", ss.__rax)?;
            write!(w, ", \"rbx\": \"0x{:016x}\"", ss.__rbx)?;
            write!(w, ", \"rcx\": \"0x{:016x}\"", ss.__rcx)?;
            write!(w, ", \"rdx\": \"0x{:016x}\"", ss.__rdx)?;
            write!(w, ", \"rsi\": \"0x{:016x}\"", ss.__rsi)?;
            write!(w, ", \"rdi\": \"0x{:016x}\"", ss.__rdi)?;
            write!(w, ", \"r8\": \"0x{:016x}\"", ss.__r8)?;
            write!(w, ", \"r9\": \"0x{:016x}\"", ss.__r9)?;
            write!(w, ", \"r10\": \"0x{:016x}\"", ss.__r10)?;
            write!(w, ", \"r11\": \"0x{:016x}\"", ss.__r11)?;
            write!(w, ", \"r12\": \"0x{:016x}\"", ss.__r12)?;
            write!(w, ", \"r13\": \"0x{:016x}\"", ss.__r13)?;
            write!(w, ", \"r14\": \"0x{:016x}\"", ss.__r14)?;
            write!(w, ", \"r15\": \"0x{:016x}\"", ss.__r15)?;
            write!(w, "}}, \"raw\": \"{:?}, {:?}\"", uc, mc)?;
            writeln!(w, "}}")?;
        }

        #[cfg(target_arch = "aarch64")]
        {
            write!(w, "{{\"arch\": \"aarch64\", \"registers\": {{")?;
            write!(w, "\"pc\": \"0x{:016x}\"", ss.__pc)?;
            write!(w, ", \"sp\": \"0x{:016x}\"", ss.__sp)?;
            write!(w, ", \"fp\": \"0x{:016x}\"", ss.__fp)?;
            write!(w, ", \"lr\": \"0x{:016x}\"", ss.__lr)?;
            for i in 0..29 {
                write!(w, ", \"x{}\": \"0x{:016x}\"", i, ss.__x[i])?;
            }
            write!(w, "}}, \"raw\": \"{:?}, {:?}\"", uc, mc)?;
            writeln!(w, "}}")?;
        }
    }

    writeln!(w, "{DD_CRASHTRACK_END_UCONTEXT}")?;
    w.flush()?;
    Ok(())
}

fn emit_siginfo(w: &mut impl Write, sig_info: *const siginfo_t) -> Result<(), EmitterError> {
    if sig_info.is_null() {
        return Err(EmitterError::NullSiginfo);
    }

    // SAFETY: `sig_info` was checked non-null above and points to the
    // kernel-provided siginfo_t from the signal handler.
    let si_signo = unsafe { (*sig_info).si_signo };
    let si_signo_human_readable: SignalNames = si_signo.into();

    // Derive the faulting address from `sig_info`
    // https://man7.org/linux/man-pages/man2/sigaction.2.html
    // SIGILL, SIGFPE, SIGSEGV, SIGBUS, and SIGTRAP fill in si_addr with the address of the fault.
    let si_addr: Option<usize> = match si_signo {
        libc::SIGILL | libc::SIGFPE | libc::SIGSEGV | libc::SIGBUS | libc::SIGTRAP => {
            // SAFETY: for these signal types, si_addr is defined and valid
            // per sigaction(2). `sig_info` was checked non-null above.
            Some(unsafe { (*sig_info).si_addr() as usize })
        }
        _ => None,
    };

    // SAFETY: `sig_info` was checked non-null and points to valid kernel data.
    let si_code = unsafe { (*sig_info).si_code };
    let si_code_human_readable = translate_si_code(si_signo, si_code);

    writeln!(w, "{DD_CRASHTRACK_BEGIN_SIGINFO}")?;
    write!(w, "{{")?;
    write!(w, "\"si_code\": {si_code}")?;
    write!(
        w,
        ", \"si_code_human_readable\": \"{si_code_human_readable:?}\""
    )?;
    write!(w, ", \"si_signo\": {si_signo}")?;
    write!(
        w,
        ", \"si_signo_human_readable\": \"{si_signo_human_readable:?}\""
    )?;
    if let Some(si_addr) = si_addr {
        write!(w, ", \"si_addr\": \"{si_addr:#018x}\"")?;
    }
    writeln!(w, "}}")?;
    writeln!(w, "{DD_CRASHTRACK_END_SIGINFO}")?;
    w.flush()?;
    Ok(())
}

/// Emit a file onto the given handle.
/// The file will be emitted in the format
///
/// DD_CRASHTRACK_BEGIN_FILE
/// <FILE BYTES>
/// DD_CRASHTRACK_END_FILE
///
/// PRECONDITIONS:
///     This function assumes that the crash-tracker is initialized.
///     The receiver expects the file to contain valid UTF-8 compatible text.
/// 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.
/// SIGNAL SAFETY:
///     This function is careful to only write to the handle, without doing any
///     unnecessary mutexes or memory allocation.
#[allow(dead_code)]
fn emit_text_file(w: &mut impl Write, path: &str) -> Result<(), EmitterError> {
    // open is signal safe
    // https://man7.org/linux/man-pages/man7/signal-safety.7.html
    let mut file = File::open(path).map_err(EmitterError::FileOpenError)?;

    // Reading the file into a fixed buffer is signal safe.
    // Doing anything more complicated may involve allocation which is not.
    // So, just read it in, and then immediately push it out to the pipe.
    const BUFFER_LEN: usize = 512;
    let mut buffer = [0u8; BUFFER_LEN];

    writeln!(w, "{DD_CRASHTRACK_BEGIN_FILE} {path}")?;

    loop {
        let read_count = file.read(&mut buffer)?;
        w.write_all(&buffer[..read_count])?;
        if read_count == 0 {
            break;
        }
    }
    writeln!(w, "\n{DD_CRASHTRACK_END_FILE} \"{path}\"")?;
    w.flush()?;
    Ok(())
}

#[cfg(test)]
mod tests {
    use crate::StackFrame;

    use super::*;
    use alloc::str;

    #[test]
    fn test_emit_complete_stacktrace() {
        // new_incomplete() starts with incomplete: true, which push_frame requires
        let mut stacktrace = StackTrace::new_incomplete();
        let mut stackframe1 = StackFrame::new();
        stackframe1.with_ip(1234);
        stackframe1.with_function("test_function1".to_string());
        stackframe1.with_file("test_file1".to_string());

        let mut stackframe2 = StackFrame::new();
        stackframe2.with_ip(5678);
        stackframe2.with_function("test_function2".to_string());
        stackframe2.with_file("test_file2".to_string());

        stacktrace.push_frame(stackframe1, true).unwrap();
        stacktrace.push_frame(stackframe2, true).unwrap();

        stacktrace.set_complete().unwrap();

        let mut buf = Vec::new();
        unsafe { emit_whole_stacktrace(&mut buf, stacktrace).expect("to work ;-)") };
        let out = str::from_utf8(&buf).expect("to be valid UTF8");

        assert!(out.contains("\"ip\":\"0x4d2\""));
        assert!(out.contains("\"function\":\"test_function1\""));
        assert!(out.contains("\"file\":\"test_file1\""));
        assert!(out.contains("\"ip\":\"0x162e\""));
        assert!(out.contains("\"function\":\"test_function2\""));
        assert!(out.contains("\"file\":\"test_file2\""));
    }

    #[test]
    fn test_emit_message_none() {
        let mut buf = Vec::new();
        emit_message(&mut buf, None).expect("to work ;-)");
        assert!(buf.is_empty());
    }

    #[test]
    fn test_emit_message() {
        let message = "test message";
        let mut buf = Vec::new();
        emit_message(&mut buf, Some(message)).expect("to work ;-)");
        let out = str::from_utf8(&buf).expect("to be valid UTF8");
        assert!(out.contains("BEGIN_MESSAGE"));
        assert!(out.contains("END_MESSAGE"));
        assert!(out.contains(message));
    }

    #[test]
    fn test_emit_message_empty_string() {
        let mut buf = Vec::new();

        emit_message(&mut buf, Some("")).expect("to work");

        // Empty messages should not emit anything
        assert!(buf.is_empty());
    }

    #[test]
    fn test_emit_message_whitespace_only() {
        // Whitespace-only messages should not be emitted
        let mut buf = Vec::new();

        emit_message(&mut buf, Some("   \n\t  ")).expect("to work");

        // Whitespace-only messages should not emit anything
        assert!(buf.is_empty());
    }

    #[test]
    fn test_emit_message_with_leading_trailing_whitespace() {
        // Messages with content and whitespace should be emitted (with the whitespace)
        let message_with_whitespace = "  error message  ";
        let mut buf = Vec::new();

        emit_message(&mut buf, Some(message_with_whitespace)).expect("to work");
        let out = str::from_utf8(&buf).expect("to be valid UTF8");

        // Should emit markers and preserve whitespace in content
        assert!(out.contains("BEGIN_MESSAGE"));
        assert!(out.contains("END_MESSAGE"));
        assert!(out.contains(message_with_whitespace));
    }

    #[test]
    fn test_emit_message_with_newlines() {
        let mut buf = Vec::new();

        emit_message(&mut buf, Some("line1\nline2\nline3")).expect("to work");
        let out = str::from_utf8(&buf).expect("to be valid UTF8");

        assert!(out.contains("line1"));
        assert!(out.contains("line2"));
        assert!(out.contains("line3"));

        // Newlines must be escaped on the wire so the message stays on one
        // protocol line and cannot inject sentinel-delimited sections.
        let lines: Vec<&str> = out.lines().collect();
        assert_eq!(lines.len(), 3, "BEGIN_MESSAGE, content, END_MESSAGE");
        assert!(lines[1].contains("line1\\nline2\\nline3"));
    }

    #[test]
    fn test_emit_message_unicode() {
        let unicode_message = "Hello 世界 🦀 Rust!";
        let mut buf = Vec::new();

        emit_message(&mut buf, Some(unicode_message)).expect("to work");
        let out = str::from_utf8(&buf).expect("to be valid UTF8");

        assert!(out.contains(unicode_message));
    }

    #[test]
    #[cfg(target_os = "linux")]
    // #[cfg_attr(miri, ignore)]
    fn test_emit_procinfo() {
        let pid = unsafe { libc::getpid() };
        let tid = unsafe { libc::syscall(libc::SYS_gettid) as libc::pid_t };
        let mut buf = Vec::new();

        emit_procinfo(&mut buf, pid, tid).expect("procinfo to emit");
        let proc_info_block = str::from_utf8(&buf).expect("to be valid UTF8");
        assert!(proc_info_block.contains(DD_CRASHTRACK_BEGIN_PROCINFO));
        assert!(proc_info_block.contains(DD_CRASHTRACK_END_PROCINFO));

        assert!(proc_info_block.contains(&format!("\"pid\": {pid}")));
        assert!(proc_info_block.contains(&format!("\"tid\": {tid}")));
    }

    #[test]
    fn test_emit_message_sentinel_injection_via_newline() {
        // An attacker-controlled error_type/message containing newlines and sentinel
        // strings could break out of the MESSAGE block and inject a CONFIG section
        // that controls the crash upload endpoint.
        let malicious = format!(
            "innocent prefix\n{}\n{}\n{{\"endpoint\":\"https://evil.example\"}}\n{}\n{}",
            DD_CRASHTRACK_END_MESSAGE,
            DD_CRASHTRACK_BEGIN_CONFIG,
            DD_CRASHTRACK_END_CONFIG,
            DD_CRASHTRACK_DONE,
        );
        let mut buf = Vec::new();

        emit_message(&mut buf, Some(&malicious)).expect("to work");
        let out = str::from_utf8(&buf).expect("to be valid UTF8");

        let lines: Vec<&str> = out.lines().collect();
        // Must be exactly 3 wire lines: BEGIN, content, END
        assert_eq!(
            lines.len(),
            3,
            "sentinel injection must not create extra lines"
        );
        assert_eq!(lines[0], DD_CRASHTRACK_BEGIN_MESSAGE);
        assert_eq!(lines[2], DD_CRASHTRACK_END_MESSAGE);

        // The injected sentinels must NOT appear as separate lines
        assert!(
            !lines.contains(&DD_CRASHTRACK_BEGIN_CONFIG),
            "injected BEGIN_CONFIG must not appear as a wire line"
        );
        assert!(
            !lines.contains(&DD_CRASHTRACK_DONE),
            "injected DONE must not appear as a wire line"
        );
    }

    #[test]
    fn test_emit_message_content_starting_with_sentinel_prefix() {
        let sentinel_message = format!("{} extra data", DD_CRASHTRACK_END_MESSAGE);
        let mut buf = Vec::new();

        emit_message(&mut buf, Some(&sentinel_message)).expect("to work");
        let out = str::from_utf8(&buf).expect("to be valid UTF8");

        let lines: Vec<&str> = out.lines().collect();
        assert_eq!(lines.len(), 3);
        // The content line shouldn't start with the sentinel
        assert!(
            !lines[1].starts_with(DD_CRASHTRACK_END_MESSAGE),
            "content line must not start with DD_CRASHTRACK_END_MESSAGE, got: {}",
            lines[1]
        );
    }

    #[test]
    fn test_write_sanitized_message_line_basic() {
        let mut buf = Vec::new();
        write_sanitized_message_line(&mut buf, "hello").unwrap();
        assert_eq!(buf, b"hello\n");

        buf.clear();
        write_sanitized_message_line(&mut buf, "line1\nline2").unwrap();
        assert_eq!(buf, b"line1\\nline2\n");

        buf.clear();
        write_sanitized_message_line(&mut buf, "a\r\nb").unwrap();
        assert_eq!(buf, b"a\\r\\nb\n");
    }

    #[test]
    fn test_write_sanitized_message_line_sentinel_prefix() {
        let input = format!("{} injected", DD_CRASHTRACK_END_MESSAGE);
        let mut buf = Vec::new();
        write_sanitized_message_line(&mut buf, &input).unwrap();
        let out = str::from_utf8(&buf).unwrap();
        assert!(!out.starts_with(DD_CRASHTRACK_END_MESSAGE));
        assert!(out.starts_with(' '));
    }

    #[test]
    fn test_emit_message_very_long() {
        let long_message = "x".repeat(100000); // 100KB
        let mut buf = Vec::new();

        emit_message(&mut buf, Some(&long_message)).expect("to work");
        let out = str::from_utf8(&buf).expect("to be valid UTF8");

        assert!(out.contains(&long_message[..100])); // At least first 100 chars
    }

    // We only test edge cases specific to this wrapper function here.
    // The core unwinding logic is tested in the libunwind crate.
    #[test]
    #[cfg(target_os = "linux")]
    fn test_emit_backtrace_via_libunwind_null_ucontext() {
        let mut buf = Vec::new();
        unsafe {
            emit_backtrace_via_libunwind(
                &mut buf,
                StacktraceCollection::WithoutSymbols,
                core::ptr::null(),
            )
            .expect("should handle null ucontext gracefully");
        }
        // With null ucontext, function should return early and emit nothing
        assert!(buf.is_empty());
    }

    #[test]
    #[cfg(target_os = "linux")]
    #[cfg_attr(miri, ignore)]
    fn test_emit_backtrace_via_libunwind_unw_init_failure() {
        // Test that when unw_init_local2 fails (e.g., with invalid context),
        // the function returns Ok(()) gracefully without writing anything
        let context: libc::ucontext_t = unsafe { core::mem::zeroed() };
        let mut buf = Vec::new();

        unsafe {
            emit_backtrace_via_libunwind(&mut buf, StacktraceCollection::WithoutSymbols, &context)
                .expect("should handle unw_init_local2 failure gracefully");
        }

        // When unw_init_local2 fails, function should return early without error
        // Buffer should be empty since no frames were written
        assert!(
            buf.is_empty(),
            "Function should return early on unw_init_local2 failure"
        );
    }

    #[test]
    fn test_emit_ucontext_null_pointer() {
        let mut buf = Vec::new();
        let result = emit_ucontext(&mut buf, core::ptr::null());

        assert!(result.is_err());
        assert!(matches!(result.unwrap_err(), EmitterError::NullUcontext));
        assert!(buf.is_empty());
    }

    #[test]
    #[cfg(target_os = "linux")]
    fn test_emit_ucontext_linux_valid() {
        // Create a minimal valid ucontext_t with zeroed register values
        let mut context: libc::ucontext_t = unsafe { core::mem::zeroed() };

        // Set up some test register values
        #[cfg(target_arch = "x86_64")]
        {
            // Set some register values for testing
            context.uc_mcontext.gregs[libc::REG_RIP as usize] = 0x12345678;
            context.uc_mcontext.gregs[libc::REG_RSP as usize] = 0x87654321;
            context.uc_mcontext.gregs[libc::REG_RBP as usize] = 0xABCDEF00;
        }

        #[cfg(target_arch = "aarch64")]
        {
            // Set some register values for testing
            context.uc_mcontext.pc = 0x12345678;
            context.uc_mcontext.sp = 0x87654321;
            context.uc_mcontext.regs[0] = 0xABCDEF00;
        }

        let mut buf = Vec::new();
        emit_ucontext(&mut buf, &context).expect("emit_ucontext should succeed");

        let output = str::from_utf8(&buf).expect("output should be valid UTF-8");

        // Check that proper markers are present
        assert!(output.contains(crate::shared::constants::DD_CRASHTRACK_BEGIN_UCONTEXT));
        assert!(output.contains(crate::shared::constants::DD_CRASHTRACK_END_UCONTEXT));

        // Check architecture is correct
        #[cfg(target_arch = "x86_64")]
        {
            assert!(output.contains("\"arch\": \"x86_64\""));
            assert!(output.contains("\"registers\""));

            // Check specific registers are present
            assert!(output.contains("\"rip\""));
            assert!(output.contains("\"rsp\""));
            assert!(output.contains("\"rbp\""));
            assert!(output.contains("\"rax\""));

            // Check our test values are formatted correctly
            assert!(output.contains("0x0000000012345678")); // rip
            assert!(output.contains("0x0000000087654321")); // rsp
            assert!(output.contains("0x00000000abcdef00")); // rbp
        }

        #[cfg(target_arch = "aarch64")]
        {
            assert!(output.contains("\"arch\": \"aarch64\""));
            assert!(output.contains("\"registers\""));

            // Check specific registers are present
            assert!(output.contains("\"pc\""));
            assert!(output.contains("\"sp\""));
            assert!(output.contains("\"x0\""));

            // Check our test values are formatted correctly
            assert!(output.contains("0x0000000012345678")); // pc
            assert!(output.contains("0x0000000087654321")); // sp
            assert!(output.contains("0x00000000abcdef00")); // x0
        }

        // Check that raw debug output is included
        assert!(output.contains("\"raw\""));

        // Verify it's valid JSON between the markers
        let start_marker = crate::shared::constants::DD_CRASHTRACK_BEGIN_UCONTEXT;
        let end_marker = crate::shared::constants::DD_CRASHTRACK_END_UCONTEXT;

        let start_pos = output.find(start_marker).unwrap() + start_marker.len() + 1; // +1 for newline
        let end_pos = output.find(end_marker).unwrap();
        let json_part = output[start_pos..end_pos].trim();

        let parsed: serde_json::Value =
            serde_json::from_str(json_part).expect("JSON between markers should be valid");

        // Verify the JSON structure
        assert!(parsed.is_object());
        assert!(parsed["arch"].is_string());
        assert!(parsed["registers"].is_object());
        assert!(parsed["raw"].is_string());
    }

    #[test]
    #[cfg(target_os = "macos")]
    #[cfg_attr(miri, ignore)]
    fn test_emit_ucontext_macos_valid() {
        use libc::__darwin_ucontext;
        // Create a minimal valid ucontext_t for macOS
        let mut context: __darwin_ucontext = unsafe { core::mem::zeroed() };

        // On macOS, we need to allocate mcontext and set up the pointer
        let mut mcontext: libc::__darwin_mcontext64 = unsafe { core::mem::zeroed() };
        context.uc_mcontext = &mut mcontext as *mut libc::__darwin_mcontext64;

        // Set up some test register values
        #[cfg(target_arch = "x86_64")]
        {
            unsafe {
                (*context.uc_mcontext).__ss.__rip = 0x12345678;
                (*context.uc_mcontext).__ss.__rsp = 0x87654321;
                (*context.uc_mcontext).__ss.__rbp = 0xABCDEF00;
            }
        }

        #[cfg(target_arch = "aarch64")]
        {
            unsafe {
                (*context.uc_mcontext).__ss.__pc = 0x12345678;
                (*context.uc_mcontext).__ss.__sp = 0x87654321;
                (*context.uc_mcontext).__ss.__fp = 0xABCDEF00;
            }
        }

        let mut buf = Vec::new();
        emit_ucontext(&mut buf, &context as *const __darwin_ucontext)
            .expect("emit_ucontext should succeed");

        let output = str::from_utf8(&buf).expect("output should be valid UTF-8");

        // Check that proper markers are present
        assert!(output.contains(crate::shared::constants::DD_CRASHTRACK_BEGIN_UCONTEXT));
        assert!(output.contains(crate::shared::constants::DD_CRASHTRACK_END_UCONTEXT));

        // Check architecture is correct
        #[cfg(target_arch = "x86_64")]
        {
            assert!(output.contains("\"arch\": \"x86_64\""));
            assert!(output.contains("\"registers\""));

            // Check specific registers are present
            assert!(output.contains("\"rip\""));
            assert!(output.contains("\"rsp\""));
            assert!(output.contains("\"rbp\""));

            // Check our test values are formatted correctly
            assert!(output.contains("0x0000000012345678")); // rip
            assert!(output.contains("0x0000000087654321")); // rsp
            assert!(output.contains("0x00000000abcdef00")); // rbp
        }

        #[cfg(target_arch = "aarch64")]
        {
            assert!(output.contains("\"arch\": \"aarch64\""));
            assert!(output.contains("\"registers\""));

            // Check specific registers are present
            assert!(output.contains("\"pc\""));
            assert!(output.contains("\"sp\""));
            assert!(output.contains("\"fp\""));

            // Check our test values are formatted correctly
            assert!(output.contains("0x0000000012345678")); // pc
            assert!(output.contains("0x0000000087654321")); // sp
            assert!(output.contains("0x00000000abcdef00")); // fp
        }

        // Check that raw debug output is included
        assert!(output.contains("\"raw\""));
    }

    #[test]
    #[cfg(target_os = "macos")]
    #[cfg_attr(miri, ignore)]
    fn test_emit_ucontext_macos_null_mcontext() {
        // Test the fallback case when mcontext is null
        let mut context: libc::ucontext_t = unsafe { core::mem::zeroed() };
        context.uc_mcontext = core::ptr::null_mut(); // Explicitly set to null

        let mut buf = Vec::new();
        emit_ucontext(&mut buf, &context).expect("emit_ucontext should succeed with null mcontext");

        let output = str::from_utf8(&buf).expect("output should be valid UTF-8");

        // Check that proper markers are present
        assert!(output.contains(crate::shared::constants::DD_CRASHTRACK_BEGIN_UCONTEXT));
        assert!(output.contains(crate::shared::constants::DD_CRASHTRACK_END_UCONTEXT));

        // Should contain fallback information
        assert!(output.contains("\"registers\": {}"));
        assert!(output.contains("\"raw\""));

        #[cfg(target_arch = "x86_64")]
        assert!(output.contains("\"arch\": \"x86_64\""));

        #[cfg(target_arch = "aarch64")]
        assert!(output.contains("\"arch\": \"aarch64\""));
    }
}