]> git.lizzy.rs Git - rust.git/blob - src/debuginfo/emit.rs
Sync from rust f2a11a25378293e41cfcb00dbf67c524ffd79b39
[rust.git] / src / debuginfo / emit.rs
1 //! Write the debuginfo into an object file.
2
3 use rustc_data_structures::fx::FxHashMap;
4
5 use gimli::write::{Address, AttributeValue, EndianVec, Result, Sections, Writer};
6 use gimli::{RunTimeEndian, SectionId};
7
8 use crate::backend::WriteDebugInfo;
9
10 use super::DebugContext;
11
12 impl DebugContext<'_> {
13     pub(crate) fn emit<P: WriteDebugInfo>(&mut self, product: &mut P) {
14         let unit_range_list_id = self.dwarf.unit.ranges.add(self.unit_range_list.clone());
15         let root = self.dwarf.unit.root();
16         let root = self.dwarf.unit.get_mut(root);
17         root.set(
18             gimli::DW_AT_ranges,
19             AttributeValue::RangeListRef(unit_range_list_id),
20         );
21
22         let mut sections = Sections::new(WriterRelocate::new(self.endian));
23         self.dwarf.write(&mut sections).unwrap();
24
25         let mut section_map = FxHashMap::default();
26         let _: Result<()> = sections.for_each_mut(|id, section| {
27             if !section.writer.slice().is_empty() {
28                 let section_id = product.add_debug_section(id, section.writer.take());
29                 section_map.insert(id, section_id);
30             }
31             Ok(())
32         });
33
34         let _: Result<()> = sections.for_each(|id, section| {
35             if let Some(section_id) = section_map.get(&id) {
36                 for reloc in &section.relocs {
37                     product.add_debug_reloc(&section_map, section_id, reloc);
38                 }
39             }
40             Ok(())
41         });
42     }
43 }
44
45 #[derive(Clone)]
46 pub(crate) struct DebugReloc {
47     pub(crate) offset: u32,
48     pub(crate) size: u8,
49     pub(crate) name: DebugRelocName,
50     pub(crate) addend: i64,
51     pub(crate) kind: object::RelocationKind,
52 }
53
54 #[derive(Clone)]
55 pub(crate) enum DebugRelocName {
56     Section(SectionId),
57     Symbol(usize),
58 }
59
60 /// A [`Writer`] that collects all necessary relocations.
61 #[derive(Clone)]
62 pub(super) struct WriterRelocate {
63     pub(super) relocs: Vec<DebugReloc>,
64     pub(super) writer: EndianVec<RunTimeEndian>,
65 }
66
67 impl WriterRelocate {
68     pub(super) fn new(endian: RunTimeEndian) -> Self {
69         WriterRelocate {
70             relocs: Vec::new(),
71             writer: EndianVec::new(endian),
72         }
73     }
74
75     /// Perform the collected relocations to be usable for JIT usage.
76     #[cfg(feature = "jit")]
77     pub(super) fn relocate_for_jit(
78         mut self,
79         jit_module: &cranelift_simplejit::SimpleJITModule,
80     ) -> Vec<u8> {
81         use std::convert::TryInto;
82
83         for reloc in self.relocs.drain(..) {
84             match reloc.name {
85                 super::DebugRelocName::Section(_) => unreachable!(),
86                 super::DebugRelocName::Symbol(sym) => {
87                     let addr = jit_module.get_finalized_function(
88                         cranelift_module::FuncId::from_u32(sym.try_into().unwrap()),
89                     );
90                     let val = (addr as u64 as i64 + reloc.addend) as u64;
91                     self.writer
92                         .write_udata_at(reloc.offset as usize, val, reloc.size)
93                         .unwrap();
94                 }
95             }
96         }
97         self.writer.into_vec()
98     }
99 }
100
101 impl Writer for WriterRelocate {
102     type Endian = RunTimeEndian;
103
104     fn endian(&self) -> Self::Endian {
105         self.writer.endian()
106     }
107
108     fn len(&self) -> usize {
109         self.writer.len()
110     }
111
112     fn write(&mut self, bytes: &[u8]) -> Result<()> {
113         self.writer.write(bytes)
114     }
115
116     fn write_at(&mut self, offset: usize, bytes: &[u8]) -> Result<()> {
117         self.writer.write_at(offset, bytes)
118     }
119
120     fn write_address(&mut self, address: Address, size: u8) -> Result<()> {
121         match address {
122             Address::Constant(val) => self.write_udata(val, size),
123             Address::Symbol { symbol, addend } => {
124                 let offset = self.len() as u64;
125                 self.relocs.push(DebugReloc {
126                     offset: offset as u32,
127                     size,
128                     name: DebugRelocName::Symbol(symbol),
129                     addend: addend as i64,
130                     kind: object::RelocationKind::Absolute,
131                 });
132                 self.write_udata(0, size)
133             }
134         }
135     }
136
137     fn write_offset(&mut self, val: usize, section: SectionId, size: u8) -> Result<()> {
138         let offset = self.len() as u32;
139         self.relocs.push(DebugReloc {
140             offset,
141             size,
142             name: DebugRelocName::Section(section),
143             addend: val as i64,
144             kind: object::RelocationKind::Absolute,
145         });
146         self.write_udata(0, size)
147     }
148
149     fn write_offset_at(
150         &mut self,
151         offset: usize,
152         val: usize,
153         section: SectionId,
154         size: u8,
155     ) -> Result<()> {
156         self.relocs.push(DebugReloc {
157             offset: offset as u32,
158             size,
159             name: DebugRelocName::Section(section),
160             addend: val as i64,
161             kind: object::RelocationKind::Absolute,
162         });
163         self.write_udata_at(offset, 0, size)
164     }
165
166     fn write_eh_pointer(&mut self, address: Address, eh_pe: gimli::DwEhPe, size: u8) -> Result<()> {
167         match address {
168             // Address::Constant arm copied from gimli
169             Address::Constant(val) => {
170                 // Indirect doesn't matter here.
171                 let val = match eh_pe.application() {
172                     gimli::DW_EH_PE_absptr => val,
173                     gimli::DW_EH_PE_pcrel => {
174                         // TODO: better handling of sign
175                         let offset = self.len() as u64;
176                         offset.wrapping_sub(val)
177                     }
178                     _ => {
179                         return Err(gimli::write::Error::UnsupportedPointerEncoding(eh_pe));
180                     }
181                 };
182                 self.write_eh_pointer_data(val, eh_pe.format(), size)
183             }
184             Address::Symbol { symbol, addend } => match eh_pe.application() {
185                 gimli::DW_EH_PE_pcrel => {
186                     let size = match eh_pe.format() {
187                         gimli::DW_EH_PE_sdata4 => 4,
188                         _ => return Err(gimli::write::Error::UnsupportedPointerEncoding(eh_pe)),
189                     };
190                     self.relocs.push(DebugReloc {
191                         offset: self.len() as u32,
192                         size,
193                         name: DebugRelocName::Symbol(symbol),
194                         addend,
195                         kind: object::RelocationKind::Relative,
196                     });
197                     self.write_udata(0, size)
198                 }
199                 _ => Err(gimli::write::Error::UnsupportedPointerEncoding(eh_pe)),
200             },
201         }
202     }
203 }