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