1 //! Abstraction around the object writing crate
3 use std::convert::{TryFrom, TryInto};
5 use rustc_data_structures::fx::FxHashMap;
6 use rustc_session::Session;
8 use cranelift_module::FuncId;
11 use object::{RelocationEncoding, SectionKind, SymbolFlags};
13 use cranelift_object::{ObjectBuilder, ObjectModule, ObjectProduct};
17 use crate::debuginfo::{DebugReloc, DebugRelocName};
19 pub(crate) trait WriteMetadata {
20 fn add_rustc_section(&mut self, symbol_name: String, data: Vec<u8>, is_like_osx: bool);
23 impl WriteMetadata for object::write::Object {
24 fn add_rustc_section(&mut self, symbol_name: String, data: Vec<u8>, _is_like_osx: bool) {
26 .segment_name(object::write::StandardSegment::Data)
28 let section_id = self.add_section(segment, b".rustc".to_vec(), object::SectionKind::Data);
29 let offset = self.append_section_data(section_id, &data, 1);
30 // For MachO and probably PE this is necessary to prevent the linker from throwing away the
31 // .rustc section. For ELF this isn't necessary, but it also doesn't harm.
32 self.add_symbol(object::write::Symbol {
33 name: symbol_name.into_bytes(),
35 size: data.len() as u64,
36 kind: object::SymbolKind::Data,
37 scope: object::SymbolScope::Dynamic,
39 section: SymbolSection::Section(section_id),
40 flags: SymbolFlags::None,
45 pub(crate) trait WriteDebugInfo {
48 fn add_debug_section(&mut self, name: SectionId, data: Vec<u8>) -> Self::SectionId;
51 section_map: &FxHashMap<SectionId, Self::SectionId>,
52 from: &Self::SectionId,
57 impl WriteDebugInfo for ObjectProduct {
58 type SectionId = (object::write::SectionId, object::write::SymbolId);
64 ) -> (object::write::SectionId, object::write::SymbolId) {
65 let name = if self.object.format() == object::BinaryFormat::MachO {
66 id.name().replace('.', "__") // machO expects __debug_info instead of .debug_info
72 let segment = self.object.segment_name(StandardSegment::Debug).to_vec();
73 // FIXME use SHT_X86_64_UNWIND for .eh_frame
74 let section_id = self.object.add_section(
77 if id == SectionId::EhFrame {
78 SectionKind::ReadOnlyData
84 .section_mut(section_id)
85 .set_data(data, if id == SectionId::EhFrame { 8 } else { 1 });
86 let symbol_id = self.object.section_symbol(section_id);
87 (section_id, symbol_id)
92 section_map: &FxHashMap<SectionId, Self::SectionId>,
93 from: &Self::SectionId,
96 let (symbol, symbol_offset) = match reloc.name {
97 DebugRelocName::Section(id) => (section_map.get(&id).unwrap().1, 0),
98 DebugRelocName::Symbol(id) => {
99 let symbol_id = self.function_symbol(FuncId::from_u32(id.try_into().unwrap()));
101 .symbol_section_and_offset(symbol_id)
102 .expect("Debug reloc for undef sym???")
109 offset: u64::from(reloc.offset),
112 encoding: RelocationEncoding::Generic,
113 size: reloc.size * 8,
114 addend: i64::try_from(symbol_offset).unwrap() + reloc.addend,
121 pub(crate) fn with_object(sess: &Session, name: &str, f: impl FnOnce(&mut Object)) -> Vec<u8> {
122 let triple = crate::build_isa(sess).triple().clone();
124 let binary_format = match triple.binary_format {
125 target_lexicon::BinaryFormat::Elf => object::BinaryFormat::Elf,
126 target_lexicon::BinaryFormat::Coff => object::BinaryFormat::Coff,
127 target_lexicon::BinaryFormat::Macho => object::BinaryFormat::MachO,
128 binary_format => sess.fatal(&format!("binary format {} is unsupported", binary_format)),
130 let architecture = match triple.architecture {
131 target_lexicon::Architecture::X86_32(_) => object::Architecture::I386,
132 target_lexicon::Architecture::X86_64 => object::Architecture::X86_64,
133 target_lexicon::Architecture::Arm(_) => object::Architecture::Arm,
134 target_lexicon::Architecture::Aarch64(_) => object::Architecture::Aarch64,
135 architecture => sess.fatal(&format!(
136 "target architecture {:?} is unsupported",
140 let endian = match triple.endianness().unwrap() {
141 target_lexicon::Endianness::Little => object::Endianness::Little,
142 target_lexicon::Endianness::Big => object::Endianness::Big,
145 let mut metadata_object = object::write::Object::new(binary_format, architecture, endian);
146 metadata_object.add_file_symbol(name.as_bytes().to_vec());
147 f(&mut metadata_object);
148 metadata_object.write().unwrap()
151 pub(crate) fn make_module(sess: &Session, name: String) -> ObjectModule {
152 let mut builder = ObjectBuilder::new(
153 crate::build_isa(sess),
155 cranelift_module::default_libcall_names(),
158 // Unlike cg_llvm, cg_clif defaults to disabling -Zfunction-sections. For cg_llvm binary size
159 // is important, while cg_clif cares more about compilation times. Enabling -Zfunction-sections
160 // can easily double the amount of time necessary to perform linking.
161 builder.per_function_section(sess.opts.debugging_opts.function_sections.unwrap_or(false));
162 ObjectModule::new(builder)