1use std::ffi::{OsStr, OsString};
2use std::fs::File;
3use std::io::{BufRead, BufReader, Read};
4use std::process::{Command, Output, Stdio};
5
6use camino::Utf8Path;
7use tracing::debug;
8
9use super::debugger::DebuggerCommands;
10use super::{Debugger, Emit, ProcRes, TestCx, Truncated, WillExecute};
11use crate::common::Config;
12use crate::debuggers::{extract_gdb_version, is_android_gdb_target};
13use crate::util::logv;
14
15impl TestCx<'_> {
16 pub(super) fn run_debuginfo_test(&self) {
17 match self.config.debugger.unwrap() {
18 Debugger::Cdb => self.run_debuginfo_cdb_test(),
19 Debugger::Gdb => self.run_debuginfo_gdb_test(),
20 Debugger::Lldb => self.run_debuginfo_lldb_test(),
21 }
22 }
23
24 fn run_debuginfo_cdb_test(&self) {
25 let config = Config {
26 target_rustcflags: self.cleanup_debug_info_options(&self.config.target_rustcflags),
27 host_rustcflags: self.cleanup_debug_info_options(&self.config.host_rustcflags),
28 ..self.config.clone()
29 };
30
31 let test_cx = TestCx { config: &config, ..*self };
32
33 test_cx.run_debuginfo_cdb_test_no_opt();
34 }
35
36 fn run_debuginfo_cdb_test_no_opt(&self) {
37 let exe_file = self.make_exe_name();
38
39 let pdb_file = exe_file.with_extension(".pdb");
48 if pdb_file.exists() {
49 std::fs::remove_file(pdb_file).unwrap();
50 }
51
52 let should_run = self.run_if_enabled();
54 let compile_result = self.compile_test(should_run, Emit::None);
55 if !compile_result.status.success() {
56 self.fatal_proc_rec("compilation failed!", &compile_result);
57 }
58 if let WillExecute::Disabled = should_run {
59 return;
60 }
61
62 let dbg_cmds = DebuggerCommands::parse_from(&self.testpaths.file, self.config, "cdb")
64 .unwrap_or_else(|e| self.fatal(&e));
65
66 let mut script_str = String::with_capacity(2048);
68 script_str.push_str("version\n"); script_str.push_str(".nvlist\n"); let mut js_extension = self.testpaths.file.clone();
74 js_extension.set_extension("cdb.js");
75 if js_extension.exists() {
76 script_str.push_str(&format!(".scriptload \"{}\"\n", js_extension));
77 }
78
79 let source_file_name = self.testpaths.file.file_name().unwrap();
81 for line in &dbg_cmds.breakpoint_lines {
82 script_str.push_str(&format!("bp `{}:{}`\n", source_file_name, line));
83 }
84
85 for line in &dbg_cmds.commands {
87 script_str.push_str(line);
88 script_str.push('\n');
89 }
90
91 script_str.push_str("qq\n"); debug!("script_str = {}", script_str);
95 self.dump_output_file(&script_str, "debugger.script");
96 let debugger_script = self.make_out_name("debugger.script");
97
98 let cdb_path = &self.config.cdb.as_ref().unwrap();
99 let mut cdb = Command::new(cdb_path);
100 cdb.arg("-lines") .arg("-cf")
102 .arg(&debugger_script)
103 .arg(&exe_file);
104
105 let debugger_run_result = self.compose_and_run(
106 cdb,
107 self.config.run_lib_path.as_path(),
108 None, None, );
111
112 if !debugger_run_result.status.success() {
113 self.fatal_proc_rec("Error while running CDB", &debugger_run_result);
114 }
115
116 if let Err(e) = dbg_cmds.check_output(&debugger_run_result) {
117 self.fatal_proc_rec(&e, &debugger_run_result);
118 }
119 }
120
121 fn run_debuginfo_gdb_test(&self) {
122 let config = Config {
123 target_rustcflags: self.cleanup_debug_info_options(&self.config.target_rustcflags),
124 host_rustcflags: self.cleanup_debug_info_options(&self.config.host_rustcflags),
125 ..self.config.clone()
126 };
127
128 let test_cx = TestCx { config: &config, ..*self };
129
130 test_cx.run_debuginfo_gdb_test_no_opt();
131 }
132
133 fn run_debuginfo_gdb_test_no_opt(&self) {
134 let dbg_cmds = DebuggerCommands::parse_from(&self.testpaths.file, self.config, "gdb")
135 .unwrap_or_else(|e| self.fatal(&e));
136 let mut cmds = dbg_cmds.commands.join("\n");
137
138 let should_run = self.run_if_enabled();
140 let compiler_run_result = self.compile_test(should_run, Emit::None);
141 if !compiler_run_result.status.success() {
142 self.fatal_proc_rec("compilation failed!", &compiler_run_result);
143 }
144 if let WillExecute::Disabled = should_run {
145 return;
146 }
147
148 let exe_file = self.make_exe_name();
149
150 let debugger_run_result;
151 if is_android_gdb_target(&self.config.target) {
152 cmds = cmds.replace("run", "continue");
153
154 let mut script_str = String::with_capacity(2048);
156 script_str.push_str(&format!("set charset {}\n", Self::charset()));
157 script_str.push_str(&format!("set sysroot {}\n", &self.config.android_cross_path));
158 script_str.push_str(&format!("file {}\n", exe_file));
159 script_str.push_str("target remote :5039\n");
160 script_str.push_str(&format!(
161 "set solib-search-path \
162 ./{}/stage2/lib/rustlib/{}/lib/\n",
163 self.config.host, self.config.target
164 ));
165 for line in &dbg_cmds.breakpoint_lines {
166 script_str.push_str(
167 format!("break {}:{}\n", self.testpaths.file.file_name().unwrap(), *line)
168 .as_str(),
169 );
170 }
171 script_str.push_str(&cmds);
172 script_str.push_str("\nquit\n");
173
174 debug!("script_str = {}", script_str);
175 self.dump_output_file(&script_str, "debugger.script");
176
177 let adb_path = &self.config.adb_path;
178
179 Command::new(adb_path)
180 .arg("push")
181 .arg(&exe_file)
182 .arg(&self.config.adb_test_dir)
183 .status()
184 .unwrap_or_else(|e| panic!("failed to exec `{adb_path:?}`: {e:?}"));
185
186 Command::new(adb_path)
187 .args(&["forward", "tcp:5039", "tcp:5039"])
188 .status()
189 .unwrap_or_else(|e| panic!("failed to exec `{adb_path:?}`: {e:?}"));
190
191 let adb_arg = format!(
192 "export LD_LIBRARY_PATH={}; \
193 gdbserver{} :5039 {}/{}",
194 self.config.adb_test_dir.clone(),
195 if self.config.target.contains("aarch64") { "64" } else { "" },
196 self.config.adb_test_dir.clone(),
197 exe_file.file_name().unwrap()
198 );
199
200 debug!("adb arg: {}", adb_arg);
201 let mut adb = Command::new(adb_path)
202 .args(&["shell", &adb_arg])
203 .stdout(Stdio::piped())
204 .stderr(Stdio::inherit())
205 .spawn()
206 .unwrap_or_else(|e| panic!("failed to exec `{adb_path:?}`: {e:?}"));
207
208 let mut stdout = BufReader::new(adb.stdout.take().unwrap());
212 let mut line = String::new();
213 loop {
214 line.truncate(0);
215 stdout.read_line(&mut line).unwrap();
216 if line.starts_with("Listening on port 5039") {
217 break;
218 }
219 }
220 drop(stdout);
221
222 let mut debugger_script = OsString::from("-command=");
223 debugger_script.push(self.make_out_name("debugger.script"));
224 let debugger_opts: &[&OsStr] =
225 &["-quiet".as_ref(), "-batch".as_ref(), "-nx".as_ref(), &debugger_script];
226
227 let gdb_path = self.config.gdb.as_ref().unwrap();
228 let Output { status, stdout, stderr } = Command::new(&gdb_path)
229 .args(debugger_opts)
230 .output()
231 .unwrap_or_else(|e| panic!("failed to exec `{gdb_path:?}`: {e:?}"));
232 let cmdline = {
233 let mut gdb = Command::new(&format!("{}-gdb", self.config.target));
234 gdb.args(debugger_opts);
235 let cmdline = self.make_cmdline(&gdb, Utf8Path::new(""));
237 logv(self.config, format!("executing {}", cmdline));
238 cmdline
239 };
240
241 debugger_run_result = ProcRes {
242 status,
243 stdout: String::from_utf8(stdout).unwrap(),
244 stderr: String::from_utf8(stderr).unwrap(),
245 truncated: Truncated::No,
246 cmdline,
247 };
248 if adb.kill().is_err() {
249 println!("Adb process is already finished.");
250 }
251 } else {
252 let rust_pp_module_abs_path = self.config.src_root.join("src").join("etc");
253 let mut script_str = String::with_capacity(2048);
255 script_str.push_str(&format!("set charset {}\n", Self::charset()));
256 script_str.push_str("show version\n");
257
258 match self.config.gdb_version {
259 Some(version) => {
260 println!("NOTE: compiletest thinks it is using GDB version {}", version);
261
262 if version > extract_gdb_version("7.4").unwrap() {
263 script_str.push_str(&format!(
266 "add-auto-load-safe-path {}\n",
267 rust_pp_module_abs_path.as_str().replace(r"\", r"\\")
268 ));
269
270 script_str.push_str(&format!(
274 "add-auto-load-safe-path {}\n",
275 self.output_base_dir().as_str().replace(r"\", r"\\")
276 ));
277 }
278 }
279 _ => {
280 println!(
281 "NOTE: compiletest does not know which version of \
282 GDB it is using"
283 );
284 }
285 }
286
287 script_str.push_str("set print pretty off\n");
290
291 script_str.push_str(&format!(
293 "directory {}\n",
294 rust_pp_module_abs_path.as_str().replace(r"\", r"\\")
295 ));
296
297 script_str.push_str(&format!("file {}\n", exe_file.as_str().replace(r"\", r"\\")));
299
300 script_str.push_str("set language rust\n");
302
303 for line in &dbg_cmds.breakpoint_lines {
305 script_str.push_str(&format!(
306 "break '{}':{}\n",
307 self.testpaths.file.file_name().unwrap(),
308 *line
309 ));
310 }
311
312 script_str.push_str(&cmds);
313 script_str.push_str("\nquit\n");
314
315 debug!("script_str = {}", script_str);
316 self.dump_output_file(&script_str, "debugger.script");
317
318 let mut debugger_script = OsString::from("-command=");
319 debugger_script.push(self.make_out_name("debugger.script"));
320
321 let debugger_opts: &[&OsStr] =
322 &["-quiet".as_ref(), "-batch".as_ref(), "-nx".as_ref(), &debugger_script];
323
324 let mut gdb = Command::new(self.config.gdb.as_ref().unwrap());
325
326 let pythonpath = if let Ok(pp) = std::env::var("PYTHONPATH") {
328 format!("{pp}:{rust_pp_module_abs_path}")
329 } else {
330 rust_pp_module_abs_path.to_string()
331 };
332 gdb.args(debugger_opts).env("PYTHONPATH", pythonpath);
333
334 debugger_run_result =
335 self.compose_and_run(gdb, self.config.run_lib_path.as_path(), None, None);
336 }
337
338 if !debugger_run_result.status.success() {
339 self.fatal_proc_rec("gdb failed to execute", &debugger_run_result);
340 }
341
342 if let Err(e) = dbg_cmds.check_output(&debugger_run_result) {
343 self.fatal_proc_rec(&e, &debugger_run_result);
344 }
345 }
346
347 fn run_debuginfo_lldb_test(&self) {
348 if self.config.lldb_python_dir.is_none() {
349 self.fatal("Can't run LLDB test because LLDB's python path is not set.");
350 }
351
352 let config = Config {
353 target_rustcflags: self.cleanup_debug_info_options(&self.config.target_rustcflags),
354 host_rustcflags: self.cleanup_debug_info_options(&self.config.host_rustcflags),
355 ..self.config.clone()
356 };
357
358 let test_cx = TestCx { config: &config, ..*self };
359
360 test_cx.run_debuginfo_lldb_test_no_opt();
361 }
362
363 fn run_debuginfo_lldb_test_no_opt(&self) {
364 let should_run = self.run_if_enabled();
366 let compile_result = self.compile_test(should_run, Emit::None);
367 if !compile_result.status.success() {
368 self.fatal_proc_rec("compilation failed!", &compile_result);
369 }
370 if let WillExecute::Disabled = should_run {
371 return;
372 }
373
374 let exe_file = self.make_exe_name();
375
376 match self.config.lldb_version {
377 Some(ref version) => {
378 println!("NOTE: compiletest thinks it is using LLDB version {}", version);
379 }
380 _ => {
381 println!(
382 "NOTE: compiletest does not know which version of \
383 LLDB it is using"
384 );
385 }
386 }
387
388 let dbg_cmds = DebuggerCommands::parse_from(&self.testpaths.file, self.config, "lldb")
390 .unwrap_or_else(|e| self.fatal(&e));
391
392 let mut script_str = String::from("settings set auto-confirm true\n");
395
396 script_str.push_str("version\n");
398
399 let rust_pp_module_abs_path = self.config.src_root.join("src/etc");
401
402 script_str.push_str(&format!(
403 "command script import {}/lldb_lookup.py\n",
404 rust_pp_module_abs_path
405 ));
406 File::open(rust_pp_module_abs_path.join("lldb_commands"))
407 .and_then(|mut file| file.read_to_string(&mut script_str))
408 .expect("Failed to read lldb_commands");
409
410 let source_file_name = self.testpaths.file.file_name().unwrap();
412 for line in &dbg_cmds.breakpoint_lines {
413 script_str.push_str(&format!(
414 "breakpoint set --file '{}' --line {}\n",
415 source_file_name, line
416 ));
417 }
418
419 for line in &dbg_cmds.commands {
421 script_str.push_str(line);
422 script_str.push('\n');
423 }
424
425 script_str.push_str("\nquit\n");
427
428 debug!("script_str = {}", script_str);
430 self.dump_output_file(&script_str, "debugger.script");
431 let debugger_script = self.make_out_name("debugger.script");
432
433 let debugger_run_result = self.run_lldb(&exe_file, &debugger_script);
435
436 if !debugger_run_result.status.success() {
437 self.fatal_proc_rec("Error while running LLDB", &debugger_run_result);
438 }
439
440 if let Err(e) = dbg_cmds.check_output(&debugger_run_result) {
441 self.fatal_proc_rec(&e, &debugger_run_result);
442 }
443 }
444
445 fn run_lldb(&self, test_executable: &Utf8Path, debugger_script: &Utf8Path) -> ProcRes {
446 let lldb_script_path = self.config.src_root.join("src/etc/lldb_batchmode.py");
448
449 let pythonpath = if let Ok(pp) = std::env::var("PYTHONPATH") {
451 format!("{pp}:{}", self.config.lldb_python_dir.as_ref().unwrap())
452 } else {
453 self.config.lldb_python_dir.clone().unwrap()
454 };
455 self.run_command_to_procres(
456 Command::new(&self.config.python)
457 .arg(&lldb_script_path)
458 .arg(test_executable)
459 .arg(debugger_script)
460 .env("PYTHONUNBUFFERED", "1") .env("PYTHONPATH", pythonpath),
462 )
463 }
464
465 fn cleanup_debug_info_options(&self, options: &Vec<String>) -> Vec<String> {
466 let options_to_remove = ["-O".to_owned(), "-g".to_owned(), "--debuginfo".to_owned()];
468
469 options.iter().filter(|x| !options_to_remove.contains(x)).cloned().collect()
470 }
471}