rustc_codegen_llvm/debuginfo/
gdb.rs

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