starnix_core/execution/
crash_reporter.rs1use crate::signals::SignalInfo;
6use crate::task::CurrentTask;
7use crash_throttling::{CrashThrottler, PendingCrashReport};
8use fidl_fuchsia_feedback::{
9 Annotation, CrashReport, CrashReporterProxy, MAX_ANNOTATION_VALUE_LENGTH,
10 MAX_CRASH_SIGNATURE_LENGTH, NativeCrashReport, SpecificCrashReport,
11};
12use fuchsia_inspect::Node;
13use starnix_logging::{
14 CATEGORY_STARNIX, CoreDumpInfo, CoreDumpList, TraceScope, log_error, log_info, log_warn,
15 trace_instant,
16};
17
18pub struct CrashReporter {
19 core_dumps: CoreDumpList,
21
22 throttler: CrashThrottler,
24
25 proxy: Option<CrashReporterProxy>,
27}
28
29impl CrashReporter {
30 pub fn new(
31 inspect_node: &Node,
32 proxy: Option<CrashReporterProxy>,
33 crash_loop_age_out: zx::MonotonicDuration,
34 enable_throttling: bool,
35 ) -> Self {
36 Self {
37 core_dumps: CoreDumpList::new(inspect_node.create_child("coredumps")),
38 throttler: CrashThrottler::new(inspect_node, crash_loop_age_out, enable_throttling),
39 proxy,
40 }
41 }
42
43 pub fn begin_crash_report(&self, current_task: &CurrentTask) -> Option<PendingCrashReport> {
46 let argv = current_task
47 .read_argv(MAX_ANNOTATION_VALUE_LENGTH as usize)
48 .unwrap_or_else(|_| vec!["<unknown>".into()])
49 .into_iter()
50 .map(|a| a.to_string())
51 .collect::<Vec<_>>();
52 let argv0 = argv.get(0).map(AsRef::as_ref).unwrap_or_else(|| "<unknown>");
53
54 let argv0 = argv0.rsplit_once("/").unwrap_or(("", &argv0)).1.to_string();
56
57 self.throttler.should_report(argv, argv0, zx::MonotonicInstant::get())
58 }
59
60 pub fn handle_core_dump(
62 &self,
63 current_task: &CurrentTask,
64 signal_info: &SignalInfo,
65 pending_crash_report: PendingCrashReport,
66 ) {
67 trace_instant!(CATEGORY_STARNIX, "RecordCoreDump", TraceScope::Process);
68
69 let argv = pending_crash_report.argv;
70 let argv0 = pending_crash_report.argv0;
71 let process_koid = current_task
72 .thread_group()
73 .process
74 .koid()
75 .expect("handles for processes with crashing threads are still valid");
76 let thread_koid = current_task
77 .live()
78 .thread
79 .read()
80 .koid()
81 .expect("handles for crashing threads are still valid");
82 let linux_pid = current_task.thread_group().leader as i64;
83 let thread_name = current_task.command().to_string();
84
85 let uptime = zx::MonotonicInstant::get() - current_task.thread_group().start_time;
87
88 let dump_info = CoreDumpInfo {
89 process_koid,
90 thread_koid,
91 linux_pid,
92 uptime: uptime.into_nanos(),
93 argv: argv.clone(),
94 thread_name: thread_name.clone(),
95 signal: signal_info.signal.to_string(),
96 };
97 self.core_dumps.record_core_dump(dump_info);
98
99 let mut argv_joined = argv.join(" ");
100 truncate_with_ellipsis(&mut argv_joined, MAX_ANNOTATION_VALUE_LENGTH as usize);
101
102 let mut env_joined = current_task
103 .read_env(MAX_ANNOTATION_VALUE_LENGTH as usize)
104 .unwrap_or_else(|_| vec![])
105 .into_iter()
106 .map(|a| a.to_string())
107 .collect::<Vec<_>>()
108 .join(" ");
109 truncate_with_ellipsis(&mut env_joined, MAX_ANNOTATION_VALUE_LENGTH as usize);
110
111 let signal_str = signal_info.signal.to_string();
112
113 let max_signature_prefix_len = MAX_CRASH_SIGNATURE_LENGTH as usize - (signal_str.len() + 1);
115 let mut crash_signature = argv0.clone();
116 truncate_with_ellipsis(&mut crash_signature, max_signature_prefix_len);
117 crash_signature.push(' ');
118 crash_signature.push_str(&signal_str);
119
120 let crash_report = CrashReport {
121 crash_signature: Some(crash_signature),
122 program_name: Some(argv0.clone()),
123 program_uptime: Some(uptime.into_nanos()),
124 specific_report: Some(SpecificCrashReport::Native(NativeCrashReport {
125 process_koid: Some(process_koid.raw_koid()),
126 process_name: Some(argv0),
127 thread_koid: Some(thread_koid.raw_koid()),
128 thread_name: Some(thread_name),
129 ..Default::default()
130 })),
131 annotations: Some(vec![
132 Annotation { key: "linux.pid".to_string(), value: linux_pid.to_string() },
136 Annotation { key: "linux.argv".to_string(), value: argv_joined },
137 Annotation { key: "linux.env".to_string(), value: env_joined },
138 Annotation { key: "linux.signal".to_string(), value: signal_str },
139 ]),
140 is_fatal: Some(true),
141 weight: Some(pending_crash_report.weight),
142 ..Default::default()
143 };
144
145 if let Some(reporter) = &self.proxy {
146 let reporter = reporter.clone();
147 current_task.kernel().kthreads.spawn_future(
149 move || async move {
150 match reporter.file_report(crash_report).await {
151 Ok(Ok(_)) => (),
152 Ok(Err(filing_error)) => {
153 log_error!(filing_error:?; "Couldn't file crash report.");
154 }
155 Err(fidl_error) => log_warn!(
156 fidl_error:?;
157 "Couldn't file crash report due to error on underlying channel."
158 ),
159 };
160 },
161 "crash-filing",
162 );
163 } else {
164 log_info!(crash_report:?; "no crash reporter available for crash");
165 }
166 }
167}
168
169fn truncate_with_ellipsis(s: &mut String, max_len: usize) {
170 if s.len() <= max_len {
171 return;
172 }
173
174 let max_content_len = max_len - 3;
176
177 let mut new_len = 0;
180 let mut iter = s.char_indices();
181 while let Some((offset, _)) = iter.next() {
182 if offset > max_content_len {
183 break;
184 }
185 new_len = offset;
186 }
187
188 s.truncate(new_len);
189 s.push_str("...");
190}
191
192#[cfg(test)]
193mod tests {
194 use super::*;
195
196 #[test]
197 fn truncate_noop_on_max_length_string() {
198 let mut s = String::from("1234567890");
199 let before = s.clone();
200 truncate_with_ellipsis(&mut s, 10);
201 assert_eq!(s, before);
202 }
203
204 #[test]
205 fn truncate_adds_ellipsis() {
206 let mut s = String::from("1234567890");
207 truncate_with_ellipsis(&mut s, 9);
208 assert_eq!(s.len(), 9);
209 assert_eq!(s, "123456...", "truncate must add ellipsis and still fit under max len");
210 }
211
212 #[test]
213 fn truncate_is_sensible_in_middle_of_multibyte_chars() {
214 let mut s = String::from("æææææææææ");
215 truncate_with_ellipsis(&mut s, 8);
219 assert_eq!(s.len(), 7, "may end up shorter than provided max length w/ multi-byte chars");
220 assert_eq!(s, "ææ...", "truncate must remove whole characters and add ellipsis");
221 }
222}