Skip to main content

rustc_codegen_llvm/debuginfo/
gdb.rs

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