rustc_codegen_llvm/debuginfo/
gdb.rs

1// .debug_gdb_scripts binary section.
2
3use rustc_ast::attr;
4use rustc_codegen_ssa::base::collect_debugger_visualizers_transitive;
5use rustc_codegen_ssa::traits::*;
6use rustc_hir::def_id::LOCAL_CRATE;
7use rustc_middle::bug;
8use rustc_middle::middle::debugger_visualizer::DebuggerVisualizerType;
9use rustc_session::config::{CrateType, DebugInfo};
10use rustc_span::sym;
11
12use crate::builder::Builder;
13use crate::common::CodegenCx;
14use crate::llvm;
15use crate::value::Value;
16
17/// Inserts a side-effect free instruction sequence that makes sure that the
18/// .debug_gdb_scripts global is referenced, so it isn't removed by the linker.
19pub(crate) fn insert_reference_to_gdb_debug_scripts_section_global(bx: &mut Builder<'_, '_, '_>) {
20    if needs_gdb_debug_scripts_section(bx) {
21        let gdb_debug_scripts_section = get_or_insert_gdb_debug_scripts_section_global(bx);
22        // Load just the first byte as that's all that's necessary to force
23        // LLVM to keep around the reference to the global.
24        let volatile_load_instruction = bx.volatile_load(bx.type_i8(), gdb_debug_scripts_section);
25        unsafe {
26            llvm::LLVMSetAlignment(volatile_load_instruction, 1);
27        }
28    }
29}
30
31/// Allocates the global variable responsible for the .debug_gdb_scripts binary
32/// section.
33pub(crate) fn get_or_insert_gdb_debug_scripts_section_global<'ll>(
34    cx: &CodegenCx<'ll, '_>,
35) -> &'ll Value {
36    let c_section_var_name = c"__rustc_debug_gdb_scripts_section__";
37    let section_var_name = c_section_var_name.to_str().unwrap();
38
39    let section_var = unsafe { llvm::LLVMGetNamedGlobal(cx.llmod, c_section_var_name.as_ptr()) };
40
41    section_var.unwrap_or_else(|| {
42        let mut section_contents = Vec::new();
43
44        // Add the pretty printers for the standard library first.
45        section_contents.extend_from_slice(b"\x01gdb_load_rust_pretty_printers.py\0");
46
47        // Next, add the pretty printers that were specified via the `#[debugger_visualizer]`
48        // attribute.
49        let visualizers = collect_debugger_visualizers_transitive(
50            cx.tcx,
51            DebuggerVisualizerType::GdbPrettyPrinter,
52        );
53        let crate_name = cx.tcx.crate_name(LOCAL_CRATE);
54        for (index, visualizer) in visualizers.iter().enumerate() {
55            // The initial byte `4` instructs GDB that the following pretty printer
56            // is defined inline as opposed to in a standalone file.
57            section_contents.extend_from_slice(b"\x04");
58            let vis_name = format!("pretty-printer-{crate_name}-{index}\n");
59            section_contents.extend_from_slice(vis_name.as_bytes());
60            section_contents.extend_from_slice(&visualizer.src);
61
62            // The final byte `0` tells GDB that the pretty printer has been
63            // fully defined and can continue searching for additional
64            // pretty printers.
65            section_contents.extend_from_slice(b"\0");
66        }
67
68        unsafe {
69            let section_contents = section_contents.as_slice();
70            let llvm_type = cx.type_array(cx.type_i8(), section_contents.len() as u64);
71
72            let section_var = cx
73                .define_global(section_var_name, llvm_type)
74                .unwrap_or_else(|| bug!("symbol `{}` is already defined", section_var_name));
75            llvm::set_section(section_var, c".debug_gdb_scripts");
76            llvm::set_initializer(section_var, cx.const_bytes(section_contents));
77            llvm::LLVMSetGlobalConstant(section_var, llvm::True);
78            llvm::LLVMSetUnnamedAddress(section_var, llvm::UnnamedAddr::Global);
79            llvm::set_linkage(section_var, llvm::Linkage::LinkOnceODRLinkage);
80            // This should make sure that the whole section is not larger than
81            // the string it contains. Otherwise we get a warning from GDB.
82            llvm::LLVMSetAlignment(section_var, 1);
83            section_var
84        }
85    })
86}
87
88pub(crate) fn needs_gdb_debug_scripts_section(cx: &CodegenCx<'_, '_>) -> bool {
89    let omit_gdb_pretty_printer_section =
90        attr::contains_name(cx.tcx.hir().krate_attrs(), sym::omit_gdb_pretty_printer_section);
91
92    // To ensure the section `__rustc_debug_gdb_scripts_section__` will not create
93    // ODR violations at link time, this section will not be emitted for rlibs since
94    // each rlib could produce a different set of visualizers that would be embedded
95    // in the `.debug_gdb_scripts` section. For that reason, we make sure that the
96    // section is only emitted for leaf crates.
97    let embed_visualizers = cx.tcx.crate_types().iter().any(|&crate_type| match crate_type {
98        CrateType::Executable | CrateType::Dylib | CrateType::Cdylib | CrateType::Staticlib => {
99            // These are crate types for which we will embed pretty printers since they
100            // are treated as leaf crates.
101            true
102        }
103        CrateType::ProcMacro => {
104            // We could embed pretty printers for proc macro crates too but it does not
105            // seem like a good default, since this is a rare use case and we don't
106            // want to slow down the common case.
107            false
108        }
109        CrateType::Rlib => {
110            // As per the above description, embedding pretty printers for rlibs could
111            // lead to ODR violations so we skip this crate type as well.
112            false
113        }
114    });
115
116    !omit_gdb_pretty_printer_section
117        && cx.sess().opts.debuginfo != DebugInfo::None
118        && cx.sess().target.emit_debug_gdb_scripts
119        && embed_visualizers
120}