compiletest/runtest/
debuginfo.rs

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};
13
14impl TestCx<'_> {
15    pub(super) fn run_debuginfo_test(&self) {
16        match self.config.debugger.unwrap() {
17            Debugger::Cdb => self.run_debuginfo_cdb_test(),
18            Debugger::Gdb => self.run_debuginfo_gdb_test(),
19            Debugger::Lldb => self.run_debuginfo_lldb_test(),
20        }
21    }
22
23    fn run_debuginfo_cdb_test(&self) {
24        let config = Config {
25            target_rustcflags: self.cleanup_debug_info_options(&self.config.target_rustcflags),
26            host_rustcflags: self.cleanup_debug_info_options(&self.config.host_rustcflags),
27            ..self.config.clone()
28        };
29
30        let test_cx = TestCx { config: &config, ..*self };
31
32        test_cx.run_debuginfo_cdb_test_no_opt();
33    }
34
35    fn run_debuginfo_cdb_test_no_opt(&self) {
36        let exe_file = self.make_exe_name();
37
38        // Existing PDB files are update in-place. When changing the debuginfo
39        // the compiler generates for something, this can lead to the situation
40        // where both the old and the new version of the debuginfo for the same
41        // type is present in the PDB, which is very confusing.
42        // Therefore we delete any existing PDB file before compiling the test
43        // case.
44        // FIXME: If can reliably detect that MSVC's link.exe is used, then
45        //        passing `/INCREMENTAL:NO` might be a cleaner way to do this.
46        let pdb_file = exe_file.with_extension(".pdb");
47        if pdb_file.exists() {
48            std::fs::remove_file(pdb_file).unwrap();
49        }
50
51        // compile test file (it should have 'compile-flags:-g' in the directive)
52        let should_run = self.run_if_enabled();
53        let compile_result = self.compile_test(should_run, Emit::None);
54        if !compile_result.status.success() {
55            self.fatal_proc_rec("compilation failed!", &compile_result);
56        }
57        if let WillExecute::Disabled = should_run {
58            return;
59        }
60
61        // Parse debugger commands etc from test files
62        let dbg_cmds = DebuggerCommands::parse_from(&self.testpaths.file, self.config, "cdb")
63            .unwrap_or_else(|e| self.fatal(&e));
64
65        // https://docs.microsoft.com/en-us/windows-hardware/drivers/debugger/debugger-commands
66        let mut script_str = String::with_capacity(2048);
67        script_str.push_str("version\n"); // List CDB (and more) version info in test output
68        script_str.push_str(".nvlist\n"); // List loaded `*.natvis` files, bulk of custom MSVC debug
69
70        // If a .js file exists next to the source file being tested, then this is a JavaScript
71        // debugging extension that needs to be loaded.
72        let mut js_extension = self.testpaths.file.clone();
73        js_extension.set_extension("cdb.js");
74        if js_extension.exists() {
75            script_str.push_str(&format!(".scriptload \"{}\"\n", js_extension));
76        }
77
78        // Set breakpoints on every line that contains the string "#break"
79        let source_file_name = self.testpaths.file.file_name().unwrap();
80        for line in &dbg_cmds.breakpoint_lines {
81            script_str.push_str(&format!("bp `{}:{}`\n", source_file_name, line));
82        }
83
84        // Append the other `cdb-command:`s
85        for line in &dbg_cmds.commands {
86            script_str.push_str(line);
87            script_str.push('\n');
88        }
89
90        script_str.push_str("qq\n"); // Quit the debugger (including remote debugger, if any)
91
92        // Write the script into a file
93        debug!("script_str = {}", script_str);
94        self.dump_output_file(&script_str, "debugger.script");
95        let debugger_script = self.make_out_name("debugger.script");
96
97        let cdb_path = &self.config.cdb.as_ref().unwrap();
98        let mut cdb = Command::new(cdb_path);
99        cdb.arg("-lines") // Enable source line debugging.
100            .arg("-cf")
101            .arg(&debugger_script)
102            .arg(&exe_file);
103
104        let debugger_run_result = self.compose_and_run(
105            cdb,
106            self.config.run_lib_path.as_path(),
107            None, // aux_path
108            None, // input
109        );
110
111        if !debugger_run_result.status.success() {
112            self.fatal_proc_rec("Error while running CDB", &debugger_run_result);
113        }
114
115        if let Err(e) = dbg_cmds.check_output(&debugger_run_result) {
116            self.fatal_proc_rec(&e, &debugger_run_result);
117        }
118    }
119
120    fn run_debuginfo_gdb_test(&self) {
121        let config = Config {
122            target_rustcflags: self.cleanup_debug_info_options(&self.config.target_rustcflags),
123            host_rustcflags: self.cleanup_debug_info_options(&self.config.host_rustcflags),
124            ..self.config.clone()
125        };
126
127        let test_cx = TestCx { config: &config, ..*self };
128
129        test_cx.run_debuginfo_gdb_test_no_opt();
130    }
131
132    fn run_debuginfo_gdb_test_no_opt(&self) {
133        let dbg_cmds = DebuggerCommands::parse_from(&self.testpaths.file, self.config, "gdb")
134            .unwrap_or_else(|e| self.fatal(&e));
135        let mut cmds = dbg_cmds.commands.join("\n");
136
137        // compile test file (it should have 'compile-flags:-g' in the directive)
138        let should_run = self.run_if_enabled();
139        let compiler_run_result = self.compile_test(should_run, Emit::None);
140        if !compiler_run_result.status.success() {
141            self.fatal_proc_rec("compilation failed!", &compiler_run_result);
142        }
143        if let WillExecute::Disabled = should_run {
144            return;
145        }
146
147        let exe_file = self.make_exe_name();
148
149        let debugger_run_result;
150        if is_android_gdb_target(&self.config.target) {
151            cmds = cmds.replace("run", "continue");
152
153            // write debugger script
154            let mut script_str = String::with_capacity(2048);
155            script_str.push_str(&format!("set charset {}\n", Self::charset()));
156            script_str.push_str(&format!("set sysroot {}\n", &self.config.android_cross_path));
157            script_str.push_str(&format!("file {}\n", exe_file));
158            script_str.push_str("target remote :5039\n");
159            script_str.push_str(&format!(
160                "set solib-search-path \
161                 ./{}/stage2/lib/rustlib/{}/lib/\n",
162                self.config.host, self.config.target
163            ));
164            for line in &dbg_cmds.breakpoint_lines {
165                script_str.push_str(
166                    format!("break {}:{}\n", self.testpaths.file.file_name().unwrap(), *line)
167                        .as_str(),
168                );
169            }
170            script_str.push_str(&cmds);
171            script_str.push_str("\nquit\n");
172
173            debug!("script_str = {}", script_str);
174            self.dump_output_file(&script_str, "debugger.script");
175
176            let adb_path = &self.config.adb_path;
177
178            Command::new(adb_path)
179                .arg("push")
180                .arg(&exe_file)
181                .arg(&self.config.adb_test_dir)
182                .status()
183                .unwrap_or_else(|e| panic!("failed to exec `{adb_path:?}`: {e:?}"));
184
185            Command::new(adb_path)
186                .args(&["forward", "tcp:5039", "tcp:5039"])
187                .status()
188                .unwrap_or_else(|e| panic!("failed to exec `{adb_path:?}`: {e:?}"));
189
190            let adb_arg = format!(
191                "export LD_LIBRARY_PATH={}; \
192                 gdbserver{} :5039 {}/{}",
193                self.config.adb_test_dir.clone(),
194                if self.config.target.contains("aarch64") { "64" } else { "" },
195                self.config.adb_test_dir.clone(),
196                exe_file.file_name().unwrap()
197            );
198
199            debug!("adb arg: {}", adb_arg);
200            let mut adb = Command::new(adb_path)
201                .args(&["shell", &adb_arg])
202                .stdout(Stdio::piped())
203                .stderr(Stdio::inherit())
204                .spawn()
205                .unwrap_or_else(|e| panic!("failed to exec `{adb_path:?}`: {e:?}"));
206
207            // Wait for the gdbserver to print out "Listening on port ..."
208            // at which point we know that it's started and then we can
209            // execute the debugger below.
210            let mut stdout = BufReader::new(adb.stdout.take().unwrap());
211            let mut line = String::new();
212            loop {
213                line.truncate(0);
214                stdout.read_line(&mut line).unwrap();
215                if line.starts_with("Listening on port 5039") {
216                    break;
217                }
218            }
219            drop(stdout);
220
221            let mut debugger_script = OsString::from("-command=");
222            debugger_script.push(self.make_out_name("debugger.script"));
223            let debugger_opts: &[&OsStr] =
224                &["-quiet".as_ref(), "-batch".as_ref(), "-nx".as_ref(), &debugger_script];
225
226            let gdb_path = self.config.gdb.as_ref().unwrap();
227            let Output { status, stdout, stderr } = Command::new(&gdb_path)
228                .args(debugger_opts)
229                .output()
230                .unwrap_or_else(|e| panic!("failed to exec `{gdb_path:?}`: {e:?}"));
231            let cmdline = {
232                let mut gdb = Command::new(&format!("{}-gdb", self.config.target));
233                gdb.args(debugger_opts);
234                // FIXME(jieyouxu): don't pass an empty Path
235                let cmdline = self.make_cmdline(&gdb, Utf8Path::new(""));
236                self.logv(format_args!("executing {cmdline}"));
237                cmdline
238            };
239
240            debugger_run_result = ProcRes {
241                status,
242                stdout: String::from_utf8(stdout).unwrap(),
243                stderr: String::from_utf8(stderr).unwrap(),
244                truncated: Truncated::No,
245                cmdline,
246            };
247            if adb.kill().is_err() {
248                println!("Adb process is already finished.");
249            }
250        } else {
251            let rust_pp_module_abs_path = self.config.src_root.join("src").join("etc");
252            // write debugger script
253            let mut script_str = String::with_capacity(2048);
254            script_str.push_str(&format!("set charset {}\n", Self::charset()));
255            script_str.push_str("show version\n");
256
257            match self.config.gdb_version {
258                Some(version) => {
259                    println!("NOTE: compiletest thinks it is using GDB version {}", version);
260
261                    if !self.props.disable_gdb_pretty_printers
262                        && version > extract_gdb_version("7.4").unwrap()
263                    {
264                        // Add the directory containing the pretty printers to
265                        // GDB's script auto loading safe path
266                        script_str.push_str(&format!(
267                            "add-auto-load-safe-path {}\n",
268                            rust_pp_module_abs_path.as_str().replace(r"\", r"\\")
269                        ));
270
271                        // Add the directory containing the output binary to
272                        // include embedded pretty printers to GDB's script
273                        // auto loading safe path
274                        script_str.push_str(&format!(
275                            "add-auto-load-safe-path {}\n",
276                            self.output_base_dir().as_str().replace(r"\", r"\\")
277                        ));
278                    }
279                }
280                _ => {
281                    println!(
282                        "NOTE: compiletest does not know which version of \
283                         GDB it is using"
284                    );
285                }
286            }
287
288            // The following line actually doesn't have to do anything with
289            // pretty printing, it just tells GDB to print values on one line:
290            script_str.push_str("set print pretty off\n");
291
292            // Add the pretty printer directory to GDB's source-file search path
293            script_str.push_str(&format!(
294                "directory {}\n",
295                rust_pp_module_abs_path.as_str().replace(r"\", r"\\")
296            ));
297
298            // Load the target executable
299            script_str.push_str(&format!("file {}\n", exe_file.as_str().replace(r"\", r"\\")));
300
301            // Force GDB to print values in the Rust format.
302            script_str.push_str("set language rust\n");
303
304            // Add line breakpoints
305            for line in &dbg_cmds.breakpoint_lines {
306                script_str.push_str(&format!(
307                    "break '{}':{}\n",
308                    self.testpaths.file.file_name().unwrap(),
309                    *line
310                ));
311            }
312
313            script_str.push_str(&cmds);
314            script_str.push_str("\nquit\n");
315
316            debug!("script_str = {}", script_str);
317            self.dump_output_file(&script_str, "debugger.script");
318
319            let mut debugger_script = OsString::from("-command=");
320            debugger_script.push(self.make_out_name("debugger.script"));
321
322            let debugger_opts: &[&OsStr] =
323                &["-quiet".as_ref(), "-batch".as_ref(), "-nx".as_ref(), &debugger_script];
324
325            let mut gdb = Command::new(self.config.gdb.as_ref().unwrap());
326
327            // FIXME: we are propagating `PYTHONPATH` from the environment, not a compiletest flag!
328            let pythonpath = if let Ok(pp) = std::env::var("PYTHONPATH") {
329                format!("{pp}:{rust_pp_module_abs_path}")
330            } else {
331                rust_pp_module_abs_path.to_string()
332            };
333            gdb.args(debugger_opts).env("PYTHONPATH", pythonpath);
334
335            debugger_run_result =
336                self.compose_and_run(gdb, self.config.run_lib_path.as_path(), None, None);
337        }
338
339        if !debugger_run_result.status.success() {
340            self.fatal_proc_rec("gdb failed to execute", &debugger_run_result);
341        }
342
343        if let Err(e) = dbg_cmds.check_output(&debugger_run_result) {
344            self.fatal_proc_rec(&e, &debugger_run_result);
345        }
346    }
347
348    fn run_debuginfo_lldb_test(&self) {
349        if self.config.lldb_python_dir.is_none() {
350            self.fatal("Can't run LLDB test because LLDB's python path is not set.");
351        }
352
353        let config = Config {
354            target_rustcflags: self.cleanup_debug_info_options(&self.config.target_rustcflags),
355            host_rustcflags: self.cleanup_debug_info_options(&self.config.host_rustcflags),
356            ..self.config.clone()
357        };
358
359        let test_cx = TestCx { config: &config, ..*self };
360
361        test_cx.run_debuginfo_lldb_test_no_opt();
362    }
363
364    fn run_debuginfo_lldb_test_no_opt(&self) {
365        // compile test file (it should have 'compile-flags:-g' in the directive)
366        let should_run = self.run_if_enabled();
367        let compile_result = self.compile_test(should_run, Emit::None);
368        if !compile_result.status.success() {
369            self.fatal_proc_rec("compilation failed!", &compile_result);
370        }
371        if let WillExecute::Disabled = should_run {
372            return;
373        }
374
375        let exe_file = self.make_exe_name();
376
377        match self.config.lldb_version {
378            Some(ref version) => {
379                println!("NOTE: compiletest thinks it is using LLDB version {}", version);
380            }
381            _ => {
382                println!(
383                    "NOTE: compiletest does not know which version of \
384                     LLDB it is using"
385                );
386            }
387        }
388
389        // Parse debugger commands etc from test files
390        let dbg_cmds = DebuggerCommands::parse_from(&self.testpaths.file, self.config, "lldb")
391            .unwrap_or_else(|e| self.fatal(&e));
392
393        // Write debugger script:
394        // We don't want to hang when calling `quit` while the process is still running
395        let mut script_str = String::from("settings set auto-confirm true\n");
396
397        // macOS has a system for restricting access to files and peripherals
398        // called Transparency, Consent, and Control (TCC), which can be
399        // configured using the "Security & Privacy" tab in your settings.
400        //
401        // This system is provenance-based: if Terminal.app is given access to
402        // your Desktop, and you launch a binary within Terminal.app, the new
403        // binary also has access to the files on your Desktop.
404        //
405        // By default though, LLDB launches binaries in very isolated
406        // contexts. This includes resetting any TCC grants that might
407        // otherwise have been inherited.
408        //
409        // In effect, this means that if the developer has placed the rust
410        // repository under one of the system-protected folders, they will get
411        // a pop-up _for each binary_ asking for permissions to access the
412        // folder - quite annoying.
413        //
414        // To avoid this, we tell LLDB to spawn processes with TCC grants
415        // inherited from the parent process.
416        //
417        // Setting this also avoids unnecessary overhead from XprotectService
418        // when running with the Developer Tool grant.
419        //
420        // TIP: If you want to allow launching `lldb ~/Desktop/my_binary`
421        // without being prompted, you can put this in your `~/.lldbinit` too.
422        if self.config.host.contains("darwin") {
423            script_str.push_str("settings set target.inherit-tcc true\n");
424        }
425
426        // Make LLDB emit its version, so we have it documented in the test output
427        script_str.push_str("version\n");
428
429        // Switch LLDB into "Rust mode".
430        let rust_pp_module_abs_path = self.config.src_root.join("src/etc");
431
432        script_str.push_str(&format!(
433            "command script import {}/lldb_lookup.py\n",
434            rust_pp_module_abs_path
435        ));
436        File::open(rust_pp_module_abs_path.join("lldb_commands"))
437            .and_then(|mut file| file.read_to_string(&mut script_str))
438            .expect("Failed to read lldb_commands");
439
440        // Set breakpoints on every line that contains the string "#break"
441        let source_file_name = self.testpaths.file.file_name().unwrap();
442        for line in &dbg_cmds.breakpoint_lines {
443            script_str.push_str(&format!(
444                "breakpoint set --file '{}' --line {}\n",
445                source_file_name, line
446            ));
447        }
448
449        // Append the other commands
450        for line in &dbg_cmds.commands {
451            script_str.push_str(line);
452            script_str.push('\n');
453        }
454
455        // Finally, quit the debugger
456        script_str.push_str("\nquit\n");
457
458        // Write the script into a file
459        debug!("script_str = {}", script_str);
460        self.dump_output_file(&script_str, "debugger.script");
461        let debugger_script = self.make_out_name("debugger.script");
462
463        // Let LLDB execute the script via lldb_batchmode.py
464        let debugger_run_result = self.run_lldb(&exe_file, &debugger_script);
465
466        if !debugger_run_result.status.success() {
467            self.fatal_proc_rec("Error while running LLDB", &debugger_run_result);
468        }
469
470        if let Err(e) = dbg_cmds.check_output(&debugger_run_result) {
471            self.fatal_proc_rec(&e, &debugger_run_result);
472        }
473    }
474
475    fn run_lldb(&self, test_executable: &Utf8Path, debugger_script: &Utf8Path) -> ProcRes {
476        // Prepare the lldb_batchmode which executes the debugger script
477        let lldb_script_path = self.config.src_root.join("src/etc/lldb_batchmode.py");
478
479        // FIXME: `PYTHONPATH` takes precedence over the flag...?
480        let pythonpath = if let Ok(pp) = std::env::var("PYTHONPATH") {
481            format!("{pp}:{}", self.config.lldb_python_dir.as_ref().unwrap())
482        } else {
483            self.config.lldb_python_dir.clone().unwrap()
484        };
485        self.run_command_to_procres(
486            Command::new(&self.config.python)
487                .arg(&lldb_script_path)
488                .arg(test_executable)
489                .arg(debugger_script)
490                .env("PYTHONUNBUFFERED", "1") // Help debugging #78665
491                .env("PYTHONPATH", pythonpath),
492        )
493    }
494
495    fn cleanup_debug_info_options(&self, options: &Vec<String>) -> Vec<String> {
496        // Remove options that are either unwanted (-O) or may lead to duplicates due to RUSTFLAGS.
497        let options_to_remove = ["-O".to_owned(), "-g".to_owned(), "--debuginfo".to_owned()];
498
499        options.iter().filter(|x| !options_to_remove.contains(x)).cloned().collect()
500    }
501}