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