rustc_codegen_llvm/debuginfo/
gdb.rs

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