1use super::{KEPT, Ordering};
2use std::{path::Path, sync::OnceLock};
3
4pub(super) static HEADING: OnceLock<String> = OnceLock::new();
5// Encoding the path before a fault keeps allocation out of the handler.
6#[cfg(unix)]
7static PATH: OnceLock<std::ffi::CString> = OnceLock::new();
8#[cfg(windows)]
9static PATH: OnceLock<Vec<u16>> = OnceLock::new();
10
11pub(super) fn prepare(path: &Path) -> std::io::Result<()> {
12 #[cfg(unix)]
13 {
14 use std::os::unix::ffi::OsStrExt;
15 let path = std::ffi::CString::new(path.as_os_str().as_bytes())?;
16 let _ = PATH.set(path);
17 // Linux forwards its existing signal handler, preserving its symbolized log. A Swift
18 // runtime failure (a force unwrap of nil, an index out of range) traps as SIGTRAP.
19 #[cfg(any(target_os = "macos", target_os = "ios"))]
20 for signal in [
21 libc::SIGSEGV,
22 libc::SIGBUS,
23 libc::SIGILL,
24 libc::SIGFPE,
25 libc::SIGABRT,
26 libc::SIGTRAP,
27 ] {
28 let mut action: libc::sigaction = unsafe { std::mem::zeroed() };
29 action.sa_sigaction = fatal as *const () as libc::sighandler_t;
30 action.sa_flags = libc::SA_SIGINFO | libc::SA_RESETHAND;
31 unsafe {
32 libc::sigemptyset(&mut action.sa_mask);
33 libc::sigaction(signal, &action, std::ptr::null_mut());
34 }
35 }
36 }
37 #[cfg(windows)]
38 {
39 use std::os::windows::ffi::OsStrExt;
40 let path: Vec<_> = path.as_os_str().encode_wide().chain([0]).collect();
41 if path[..path.len() - 1].contains(&0) {
42 return Err(std::io::ErrorKind::InvalidInput.into());
43 }
44 let _ = PATH.set(path);
45 unsafe {
46 windows_sys::Win32::System::Diagnostics::Debug::SetUnhandledExceptionFilter(Some(
47 fault,
48 ));
49 }
50 }
51 Ok(())
52}
53
54fn hex(mut value: u64) -> [u8; 16] {
55 let mut digits = [b'0'; 16];
56 for digit in digits.iter_mut().rev() {
57 *digit = b"0123456789abcdef"[(value & 15) as usize];
58 value >>= 4;
59 }
60 digits
61}
62
63/// Records the fatal signal without allocating, locking, or reading note data.
64///
65/// # Safety
66/// `info` is the live `siginfo_t` supplied to a fatal signal handler.
67#[cfg(unix)]
68pub unsafe fn record_signal(signal: i32, info: *const libc::siginfo_t) {
69 if PATH.get().is_none() || KEPT.swap(true, Ordering::Relaxed) {
70 return;
71 }
72 let Some(path) = PATH.get() else {
73 return;
74 };
75 let fd = unsafe {
76 libc::open(
77 path.as_ptr(),
78 libc::O_WRONLY | libc::O_CREAT | libc::O_TRUNC | libc::O_NOFOLLOW,
79 0o600,
80 )
81 };
82 if fd < 0 {
83 return;
84 }
85 let code = hex(signal as u64);
86 let write = |parts: &[&[u8]]| {
87 for mut bytes in parts.iter().copied() {
88 while !bytes.is_empty() {
89 let wrote = unsafe { libc::write(fd, bytes.as_ptr().cast(), bytes.len()) };
90 if wrote <= 0 {
91 break;
92 }
93 bytes = &bytes[wrote as usize..];
94 }
95 }
96 };
97 write(&[
98 HEADING
99 .get()
100 .map_or(&b"Snowbound\n"[..], |heading| heading.as_bytes()),
101 b"Native signal: 0x",
102 &code,
103 b"\n",
104 ]);
105 if unsafe { (*info).si_code } > 0
106 && matches!(
107 signal,
108 libc::SIGSEGV | libc::SIGBUS | libc::SIGILL | libc::SIGFPE
109 )
110 {
111 let address = hex(unsafe { (*info).si_addr() } as usize as u64);
112 write(&[b"Fault address: 0x", &address, b"\n"]);
113 }
114 unsafe {
115 libc::fsync(fd);
116 libc::close(fd);
117 }
118}
119
120#[cfg(any(target_os = "macos", target_os = "ios"))]
121extern "C" fn fatal(signal: i32, info: *mut libc::siginfo_t, _: *mut libc::c_void) {
122 unsafe {
123 record_signal(signal, info);
124 // SA_RESETHAND leaves SIGILL and SIGTRAP caught, which would come straight back here.
125 libc::signal(signal, libc::SIG_DFL);
126 libc::raise(signal);
127 }
128}
129
130#[cfg(windows)]
131unsafe extern "system" fn fault(
132 pointers: *const windows_sys::Win32::System::Diagnostics::Debug::EXCEPTION_POINTERS,
133) -> i32 {
134 use windows_sys::Win32::{
135 Foundation::{GENERIC_WRITE, INVALID_HANDLE_VALUE},
136 Storage::FileSystem::{
137 CREATE_ALWAYS, CreateFileW, FILE_ATTRIBUTE_NORMAL, FILE_FLAG_WRITE_THROUGH, WriteFile,
138 },
139 };
140 let Some(path) = PATH.get() else {
141 return 0;
142 };
143 if KEPT.swap(true, Ordering::Relaxed) {
144 return 0;
145 }
146 let file = unsafe {
147 CreateFileW(
148 path.as_ptr(),
149 GENERIC_WRITE,
150 0,
151 std::ptr::null(),
152 CREATE_ALWAYS,
153 FILE_ATTRIBUTE_NORMAL | FILE_FLAG_WRITE_THROUGH,
154 std::ptr::null_mut(),
155 )
156 };
157 if file == INVALID_HANDLE_VALUE {
158 return 0;
159 }
160 let record = unsafe { &*(*pointers).ExceptionRecord };
161 let code = hex(record.ExceptionCode as u32 as u64);
162 let address = hex(record.ExceptionAddress as usize as u64);
163 for bytes in [
164 HEADING
165 .get()
166 .map_or(&b"Snowbound\n"[..], |heading| heading.as_bytes()),
167 b"Native exception: 0x",
168 &code,
169 b"\nInstruction address: 0x",
170 &address,
171 b"\n",
172 ] {
173 let mut wrote = 0;
174 unsafe {
175 WriteFile(
176 file,
177 bytes.as_ptr(),
178 bytes.len() as u32,
179 &mut wrote,
180 std::ptr::null_mut(),
181 );
182 }
183 }
184 unsafe {
185 windows_sys::Win32::Foundation::CloseHandle(file);
186 }
187 0
188}