cranelift_object/
backend.rs

1//! Defines `ObjectModule`.
2
3use anyhow::anyhow;
4use cranelift_codegen::binemit::{Addend, CodeOffset, Reloc};
5use cranelift_codegen::entity::SecondaryMap;
6use cranelift_codegen::isa::{OwnedTargetIsa, TargetIsa};
7use cranelift_codegen::{ir, FinalizedMachReloc};
8use cranelift_control::ControlPlane;
9use cranelift_module::{
10    DataDescription, DataId, FuncId, Init, Linkage, Module, ModuleDeclarations, ModuleError,
11    ModuleReloc, ModuleRelocTarget, ModuleResult,
12};
13use log::info;
14use object::write::{
15    Object, Relocation, SectionId, StandardSection, Symbol, SymbolId, SymbolSection,
16};
17use object::{
18    RelocationEncoding, RelocationFlags, RelocationKind, SectionKind, SymbolFlags, SymbolKind,
19    SymbolScope,
20};
21use std::collections::hash_map::Entry;
22use std::collections::HashMap;
23use std::mem;
24use target_lexicon::PointerWidth;
25
26/// A builder for `ObjectModule`.
27pub struct ObjectBuilder {
28    isa: OwnedTargetIsa,
29    binary_format: object::BinaryFormat,
30    architecture: object::Architecture,
31    flags: object::FileFlags,
32    endian: object::Endianness,
33    name: Vec<u8>,
34    libcall_names: Box<dyn Fn(ir::LibCall) -> String + Send + Sync>,
35    per_function_section: bool,
36    per_data_object_section: bool,
37}
38
39impl ObjectBuilder {
40    /// Create a new `ObjectBuilder` using the given Cranelift target, that
41    /// can be passed to [`ObjectModule::new`].
42    ///
43    /// The `libcall_names` function provides a way to translate `cranelift_codegen`'s [`ir::LibCall`]
44    /// enum to symbols. LibCalls are inserted in the IR as part of the legalization for certain
45    /// floating point instructions, and for stack probes. If you don't know what to use for this
46    /// argument, use [`cranelift_module::default_libcall_names`].
47    pub fn new<V: Into<Vec<u8>>>(
48        isa: OwnedTargetIsa,
49        name: V,
50        libcall_names: Box<dyn Fn(ir::LibCall) -> String + Send + Sync>,
51    ) -> ModuleResult<Self> {
52        let mut file_flags = object::FileFlags::None;
53        let binary_format = match isa.triple().binary_format {
54            target_lexicon::BinaryFormat::Elf => object::BinaryFormat::Elf,
55            target_lexicon::BinaryFormat::Coff => object::BinaryFormat::Coff,
56            target_lexicon::BinaryFormat::Macho => object::BinaryFormat::MachO,
57            target_lexicon::BinaryFormat::Wasm => {
58                return Err(ModuleError::Backend(anyhow!(
59                    "binary format wasm is unsupported",
60                )))
61            }
62            target_lexicon::BinaryFormat::Unknown => {
63                return Err(ModuleError::Backend(anyhow!("binary format is unknown")))
64            }
65            other => {
66                return Err(ModuleError::Backend(anyhow!(
67                    "binary format {} not recognized",
68                    other
69                )))
70            }
71        };
72        let architecture = match isa.triple().architecture {
73            target_lexicon::Architecture::X86_32(_) => object::Architecture::I386,
74            target_lexicon::Architecture::X86_64 => object::Architecture::X86_64,
75            target_lexicon::Architecture::Arm(_) => object::Architecture::Arm,
76            target_lexicon::Architecture::Aarch64(_) => object::Architecture::Aarch64,
77            target_lexicon::Architecture::Riscv64(_) => {
78                if binary_format != object::BinaryFormat::Elf {
79                    return Err(ModuleError::Backend(anyhow!(
80                        "binary format {:?} is not supported for riscv64",
81                        binary_format,
82                    )));
83                }
84
85                // FIXME(#4994): Get the right float ABI variant from the TargetIsa
86                let mut eflags = object::elf::EF_RISCV_FLOAT_ABI_DOUBLE;
87
88                // Set the RVC eflag if we have the C extension enabled.
89                let has_c = isa
90                    .isa_flags()
91                    .iter()
92                    .filter(|f| f.name == "has_zca" || f.name == "has_zcd")
93                    .all(|f| f.as_bool().unwrap_or_default());
94                if has_c {
95                    eflags |= object::elf::EF_RISCV_RVC;
96                }
97
98                file_flags = object::FileFlags::Elf {
99                    os_abi: object::elf::ELFOSABI_NONE,
100                    abi_version: 0,
101                    e_flags: eflags,
102                };
103                object::Architecture::Riscv64
104            }
105            target_lexicon::Architecture::S390x => object::Architecture::S390x,
106            architecture => {
107                return Err(ModuleError::Backend(anyhow!(
108                    "target architecture {:?} is unsupported",
109                    architecture,
110                )))
111            }
112        };
113        let endian = match isa.triple().endianness().unwrap() {
114            target_lexicon::Endianness::Little => object::Endianness::Little,
115            target_lexicon::Endianness::Big => object::Endianness::Big,
116        };
117        Ok(Self {
118            isa,
119            binary_format,
120            architecture,
121            flags: file_flags,
122            endian,
123            name: name.into(),
124            libcall_names,
125            per_function_section: false,
126            per_data_object_section: false,
127        })
128    }
129
130    /// Set if every function should end up in their own section.
131    pub fn per_function_section(&mut self, per_function_section: bool) -> &mut Self {
132        self.per_function_section = per_function_section;
133        self
134    }
135
136    /// Set if every data object should end up in their own section.
137    pub fn per_data_object_section(&mut self, per_data_object_section: bool) -> &mut Self {
138        self.per_data_object_section = per_data_object_section;
139        self
140    }
141}
142
143/// An `ObjectModule` implements `Module` and emits ".o" files using the `object` library.
144///
145/// See the `ObjectBuilder` for a convenient way to construct `ObjectModule` instances.
146pub struct ObjectModule {
147    isa: OwnedTargetIsa,
148    object: Object<'static>,
149    declarations: ModuleDeclarations,
150    functions: SecondaryMap<FuncId, Option<(SymbolId, bool)>>,
151    data_objects: SecondaryMap<DataId, Option<(SymbolId, bool)>>,
152    relocs: Vec<SymbolRelocs>,
153    libcalls: HashMap<ir::LibCall, SymbolId>,
154    libcall_names: Box<dyn Fn(ir::LibCall) -> String + Send + Sync>,
155    known_symbols: HashMap<ir::KnownSymbol, SymbolId>,
156    known_labels: HashMap<(FuncId, CodeOffset), SymbolId>,
157    per_function_section: bool,
158    per_data_object_section: bool,
159}
160
161impl ObjectModule {
162    /// Create a new `ObjectModule` using the given Cranelift target.
163    pub fn new(builder: ObjectBuilder) -> Self {
164        let mut object = Object::new(builder.binary_format, builder.architecture, builder.endian);
165        object.flags = builder.flags;
166        object.set_subsections_via_symbols();
167        object.add_file_symbol(builder.name);
168        Self {
169            isa: builder.isa,
170            object,
171            declarations: ModuleDeclarations::default(),
172            functions: SecondaryMap::new(),
173            data_objects: SecondaryMap::new(),
174            relocs: Vec::new(),
175            libcalls: HashMap::new(),
176            libcall_names: builder.libcall_names,
177            known_symbols: HashMap::new(),
178            known_labels: HashMap::new(),
179            per_function_section: builder.per_function_section,
180            per_data_object_section: builder.per_data_object_section,
181        }
182    }
183}
184
185fn validate_symbol(name: &str) -> ModuleResult<()> {
186    // null bytes are not allowed in symbol names and will cause the `object`
187    // crate to panic. Let's return a clean error instead.
188    if name.contains("\0") {
189        return Err(ModuleError::Backend(anyhow::anyhow!(
190            "Symbol {:?} has a null byte, which is disallowed",
191            name
192        )));
193    }
194    Ok(())
195}
196
197impl Module for ObjectModule {
198    fn isa(&self) -> &dyn TargetIsa {
199        &*self.isa
200    }
201
202    fn declarations(&self) -> &ModuleDeclarations {
203        &self.declarations
204    }
205
206    fn declare_function(
207        &mut self,
208        name: &str,
209        linkage: Linkage,
210        signature: &ir::Signature,
211    ) -> ModuleResult<FuncId> {
212        validate_symbol(name)?;
213
214        let (id, linkage) = self
215            .declarations
216            .declare_function(name, linkage, signature)?;
217
218        let (scope, weak) = translate_linkage(linkage);
219
220        if let Some((function, _defined)) = self.functions[id] {
221            let symbol = self.object.symbol_mut(function);
222            symbol.scope = scope;
223            symbol.weak = weak;
224        } else {
225            let symbol_id = self.object.add_symbol(Symbol {
226                name: name.as_bytes().to_vec(),
227                value: 0,
228                size: 0,
229                kind: SymbolKind::Text,
230                scope,
231                weak,
232                section: SymbolSection::Undefined,
233                flags: SymbolFlags::None,
234            });
235            self.functions[id] = Some((symbol_id, false));
236        }
237
238        Ok(id)
239    }
240
241    fn declare_anonymous_function(&mut self, signature: &ir::Signature) -> ModuleResult<FuncId> {
242        let id = self.declarations.declare_anonymous_function(signature)?;
243
244        let symbol_id = self.object.add_symbol(Symbol {
245            name: self
246                .declarations
247                .get_function_decl(id)
248                .linkage_name(id)
249                .into_owned()
250                .into_bytes(),
251            value: 0,
252            size: 0,
253            kind: SymbolKind::Text,
254            scope: SymbolScope::Compilation,
255            weak: false,
256            section: SymbolSection::Undefined,
257            flags: SymbolFlags::None,
258        });
259        self.functions[id] = Some((symbol_id, false));
260
261        Ok(id)
262    }
263
264    fn declare_data(
265        &mut self,
266        name: &str,
267        linkage: Linkage,
268        writable: bool,
269        tls: bool,
270    ) -> ModuleResult<DataId> {
271        validate_symbol(name)?;
272
273        let (id, linkage) = self
274            .declarations
275            .declare_data(name, linkage, writable, tls)?;
276
277        // Merging declarations with conflicting values for tls is not allowed, so it is safe to use
278        // the passed in tls value here.
279        let kind = if tls {
280            SymbolKind::Tls
281        } else {
282            SymbolKind::Data
283        };
284        let (scope, weak) = translate_linkage(linkage);
285
286        if let Some((data, _defined)) = self.data_objects[id] {
287            let symbol = self.object.symbol_mut(data);
288            symbol.kind = kind;
289            symbol.scope = scope;
290            symbol.weak = weak;
291        } else {
292            let symbol_id = self.object.add_symbol(Symbol {
293                name: name.as_bytes().to_vec(),
294                value: 0,
295                size: 0,
296                kind,
297                scope,
298                weak,
299                section: SymbolSection::Undefined,
300                flags: SymbolFlags::None,
301            });
302            self.data_objects[id] = Some((symbol_id, false));
303        }
304
305        Ok(id)
306    }
307
308    fn declare_anonymous_data(&mut self, writable: bool, tls: bool) -> ModuleResult<DataId> {
309        let id = self.declarations.declare_anonymous_data(writable, tls)?;
310
311        let kind = if tls {
312            SymbolKind::Tls
313        } else {
314            SymbolKind::Data
315        };
316
317        let symbol_id = self.object.add_symbol(Symbol {
318            name: self
319                .declarations
320                .get_data_decl(id)
321                .linkage_name(id)
322                .into_owned()
323                .into_bytes(),
324            value: 0,
325            size: 0,
326            kind,
327            scope: SymbolScope::Compilation,
328            weak: false,
329            section: SymbolSection::Undefined,
330            flags: SymbolFlags::None,
331        });
332        self.data_objects[id] = Some((symbol_id, false));
333
334        Ok(id)
335    }
336
337    fn define_function_with_control_plane(
338        &mut self,
339        func_id: FuncId,
340        ctx: &mut cranelift_codegen::Context,
341        ctrl_plane: &mut ControlPlane,
342    ) -> ModuleResult<()> {
343        info!("defining function {}: {}", func_id, ctx.func.display());
344
345        let res = ctx.compile(self.isa(), ctrl_plane)?;
346        let alignment = res.buffer.alignment as u64;
347
348        self.define_function_bytes(
349            func_id,
350            &ctx.func,
351            alignment,
352            ctx.compiled_code().unwrap().code_buffer(),
353            ctx.compiled_code().unwrap().buffer.relocs(),
354        )
355    }
356
357    fn define_function_bytes(
358        &mut self,
359        func_id: FuncId,
360        func: &ir::Function,
361        alignment: u64,
362        bytes: &[u8],
363        relocs: &[FinalizedMachReloc],
364    ) -> ModuleResult<()> {
365        info!("defining function {} with bytes", func_id);
366        let decl = self.declarations.get_function_decl(func_id);
367        let decl_name = decl.linkage_name(func_id);
368        if !decl.linkage.is_definable() {
369            return Err(ModuleError::InvalidImportDefinition(decl_name.into_owned()));
370        }
371
372        let &mut (symbol, ref mut defined) = self.functions[func_id].as_mut().unwrap();
373        if *defined {
374            return Err(ModuleError::DuplicateDefinition(decl_name.into_owned()));
375        }
376        *defined = true;
377
378        let align = alignment
379            .max(self.isa.function_alignment().minimum.into())
380            .max(self.isa.symbol_alignment());
381        let section = if self.per_function_section {
382            // FIXME pass empty symbol name once add_subsection produces `.text` as section name
383            // instead of `.text.` when passed an empty symbol name. (object#748) Until then pass
384            // `subsection` to produce `.text.subsection` as section name to reduce confusion.
385            self.object
386                .add_subsection(StandardSection::Text, b"subsection")
387        } else {
388            self.object.section_id(StandardSection::Text)
389        };
390        let offset = self.object.add_symbol_data(symbol, section, bytes, align);
391
392        if !relocs.is_empty() {
393            let relocs = relocs
394                .iter()
395                .map(|record| {
396                    self.process_reloc(&ModuleReloc::from_mach_reloc(&record, func, func_id))
397                })
398                .collect();
399            self.relocs.push(SymbolRelocs {
400                section,
401                offset,
402                relocs,
403            });
404        }
405
406        Ok(())
407    }
408
409    fn define_data(&mut self, data_id: DataId, data: &DataDescription) -> ModuleResult<()> {
410        let decl = self.declarations.get_data_decl(data_id);
411        if !decl.linkage.is_definable() {
412            return Err(ModuleError::InvalidImportDefinition(
413                decl.linkage_name(data_id).into_owned(),
414            ));
415        }
416
417        let &mut (symbol, ref mut defined) = self.data_objects[data_id].as_mut().unwrap();
418        if *defined {
419            return Err(ModuleError::DuplicateDefinition(
420                decl.linkage_name(data_id).into_owned(),
421            ));
422        }
423        *defined = true;
424
425        let &DataDescription {
426            ref init,
427            function_decls: _,
428            data_decls: _,
429            function_relocs: _,
430            data_relocs: _,
431            ref custom_segment_section,
432            align,
433        } = data;
434
435        let pointer_reloc = match self.isa.triple().pointer_width().unwrap() {
436            PointerWidth::U16 => unimplemented!("16bit pointers"),
437            PointerWidth::U32 => Reloc::Abs4,
438            PointerWidth::U64 => Reloc::Abs8,
439        };
440        let relocs = data
441            .all_relocs(pointer_reloc)
442            .map(|record| self.process_reloc(&record))
443            .collect::<Vec<_>>();
444
445        let section = if custom_segment_section.is_none() {
446            let section_kind = if let Init::Zeros { .. } = *init {
447                if decl.tls {
448                    StandardSection::UninitializedTls
449                } else {
450                    StandardSection::UninitializedData
451                }
452            } else if decl.tls {
453                StandardSection::Tls
454            } else if decl.writable {
455                StandardSection::Data
456            } else if relocs.is_empty() {
457                StandardSection::ReadOnlyData
458            } else {
459                StandardSection::ReadOnlyDataWithRel
460            };
461            if self.per_data_object_section {
462                // FIXME pass empty symbol name once add_subsection produces `.text` as section name
463                // instead of `.text.` when passed an empty symbol name. (object#748) Until then
464                // pass `subsection` to produce `.text.subsection` as section name to reduce
465                // confusion.
466                self.object.add_subsection(section_kind, b"subsection")
467            } else {
468                self.object.section_id(section_kind)
469            }
470        } else {
471            if decl.tls {
472                return Err(cranelift_module::ModuleError::Backend(anyhow::anyhow!(
473                    "Custom section not supported for TLS"
474                )));
475            }
476            let (seg, sec) = &custom_segment_section.as_ref().unwrap();
477            self.object.add_section(
478                seg.clone().into_bytes(),
479                sec.clone().into_bytes(),
480                if decl.writable {
481                    SectionKind::Data
482                } else if relocs.is_empty() {
483                    SectionKind::ReadOnlyData
484                } else {
485                    SectionKind::ReadOnlyDataWithRel
486                },
487            )
488        };
489
490        let align = std::cmp::max(align.unwrap_or(1), self.isa.symbol_alignment());
491        let offset = match *init {
492            Init::Uninitialized => {
493                panic!("data is not initialized yet");
494            }
495            Init::Zeros { size } => self
496                .object
497                .add_symbol_bss(symbol, section, size as u64, align),
498            Init::Bytes { ref contents } => self
499                .object
500                .add_symbol_data(symbol, section, &contents, align),
501        };
502        if !relocs.is_empty() {
503            self.relocs.push(SymbolRelocs {
504                section,
505                offset,
506                relocs,
507            });
508        }
509        Ok(())
510    }
511}
512
513impl ObjectModule {
514    /// Finalize all relocations and output an object.
515    pub fn finish(mut self) -> ObjectProduct {
516        let symbol_relocs = mem::take(&mut self.relocs);
517        for symbol in symbol_relocs {
518            for &ObjectRelocRecord {
519                offset,
520                ref name,
521                flags,
522                addend,
523            } in &symbol.relocs
524            {
525                let target_symbol = self.get_symbol(name);
526                self.object
527                    .add_relocation(
528                        symbol.section,
529                        Relocation {
530                            offset: symbol.offset + u64::from(offset),
531                            flags,
532                            symbol: target_symbol,
533                            addend,
534                        },
535                    )
536                    .unwrap();
537            }
538        }
539
540        // Indicate that this object has a non-executable stack.
541        if self.object.format() == object::BinaryFormat::Elf {
542            self.object.add_section(
543                vec![],
544                ".note.GNU-stack".as_bytes().to_vec(),
545                SectionKind::Linker,
546            );
547        }
548
549        ObjectProduct {
550            object: self.object,
551            functions: self.functions,
552            data_objects: self.data_objects,
553        }
554    }
555
556    /// This should only be called during finish because it creates
557    /// symbols for missing libcalls.
558    fn get_symbol(&mut self, name: &ModuleRelocTarget) -> SymbolId {
559        match *name {
560            ModuleRelocTarget::User { .. } => {
561                if ModuleDeclarations::is_function(name) {
562                    let id = FuncId::from_name(name);
563                    self.functions[id].unwrap().0
564                } else {
565                    let id = DataId::from_name(name);
566                    self.data_objects[id].unwrap().0
567                }
568            }
569            ModuleRelocTarget::LibCall(ref libcall) => {
570                let name = (self.libcall_names)(*libcall);
571                if let Some(symbol) = self.object.symbol_id(name.as_bytes()) {
572                    symbol
573                } else if let Some(symbol) = self.libcalls.get(libcall) {
574                    *symbol
575                } else {
576                    let symbol = self.object.add_symbol(Symbol {
577                        name: name.as_bytes().to_vec(),
578                        value: 0,
579                        size: 0,
580                        kind: SymbolKind::Text,
581                        scope: SymbolScope::Unknown,
582                        weak: false,
583                        section: SymbolSection::Undefined,
584                        flags: SymbolFlags::None,
585                    });
586                    self.libcalls.insert(*libcall, symbol);
587                    symbol
588                }
589            }
590            // These are "magic" names well-known to the linker.
591            // They require special treatment.
592            ModuleRelocTarget::KnownSymbol(ref known_symbol) => {
593                if let Some(symbol) = self.known_symbols.get(known_symbol) {
594                    *symbol
595                } else {
596                    let symbol = self.object.add_symbol(match known_symbol {
597                        ir::KnownSymbol::ElfGlobalOffsetTable => Symbol {
598                            name: b"_GLOBAL_OFFSET_TABLE_".to_vec(),
599                            value: 0,
600                            size: 0,
601                            kind: SymbolKind::Data,
602                            scope: SymbolScope::Unknown,
603                            weak: false,
604                            section: SymbolSection::Undefined,
605                            flags: SymbolFlags::None,
606                        },
607                        ir::KnownSymbol::CoffTlsIndex => Symbol {
608                            name: b"_tls_index".to_vec(),
609                            value: 0,
610                            size: 32,
611                            kind: SymbolKind::Tls,
612                            scope: SymbolScope::Unknown,
613                            weak: false,
614                            section: SymbolSection::Undefined,
615                            flags: SymbolFlags::None,
616                        },
617                    });
618                    self.known_symbols.insert(*known_symbol, symbol);
619                    symbol
620                }
621            }
622
623            ModuleRelocTarget::FunctionOffset(func_id, offset) => {
624                match self.known_labels.entry((func_id, offset)) {
625                    Entry::Occupied(o) => *o.get(),
626                    Entry::Vacant(v) => {
627                        let func_symbol_id = self.functions[func_id].unwrap().0;
628                        let func_symbol = self.object.symbol(func_symbol_id);
629
630                        let name = format!(".L{}_{}", func_id.as_u32(), offset);
631                        let symbol_id = self.object.add_symbol(Symbol {
632                            name: name.as_bytes().to_vec(),
633                            value: func_symbol.value + offset as u64,
634                            size: 0,
635                            kind: SymbolKind::Label,
636                            scope: SymbolScope::Compilation,
637                            weak: false,
638                            section: SymbolSection::Section(func_symbol.section.id().unwrap()),
639                            flags: SymbolFlags::None,
640                        });
641
642                        v.insert(symbol_id);
643                        symbol_id
644                    }
645                }
646            }
647        }
648    }
649
650    fn process_reloc(&self, record: &ModuleReloc) -> ObjectRelocRecord {
651        let flags = match record.kind {
652            Reloc::Abs4 => RelocationFlags::Generic {
653                kind: RelocationKind::Absolute,
654                encoding: RelocationEncoding::Generic,
655                size: 32,
656            },
657            Reloc::Abs8 => RelocationFlags::Generic {
658                kind: RelocationKind::Absolute,
659                encoding: RelocationEncoding::Generic,
660                size: 64,
661            },
662            Reloc::X86PCRel4 => RelocationFlags::Generic {
663                kind: RelocationKind::Relative,
664                encoding: RelocationEncoding::Generic,
665                size: 32,
666            },
667            Reloc::X86CallPCRel4 => RelocationFlags::Generic {
668                kind: RelocationKind::Relative,
669                encoding: RelocationEncoding::X86Branch,
670                size: 32,
671            },
672            // TODO: Get Cranelift to tell us when we can use
673            // R_X86_64_GOTPCRELX/R_X86_64_REX_GOTPCRELX.
674            Reloc::X86CallPLTRel4 => RelocationFlags::Generic {
675                kind: RelocationKind::PltRelative,
676                encoding: RelocationEncoding::X86Branch,
677                size: 32,
678            },
679            Reloc::X86SecRel => RelocationFlags::Generic {
680                kind: RelocationKind::SectionOffset,
681                encoding: RelocationEncoding::Generic,
682                size: 32,
683            },
684            Reloc::X86GOTPCRel4 => RelocationFlags::Generic {
685                kind: RelocationKind::GotRelative,
686                encoding: RelocationEncoding::Generic,
687                size: 32,
688            },
689            Reloc::Arm64Call => RelocationFlags::Generic {
690                kind: RelocationKind::Relative,
691                encoding: RelocationEncoding::AArch64Call,
692                size: 26,
693            },
694            Reloc::ElfX86_64TlsGd => {
695                assert_eq!(
696                    self.object.format(),
697                    object::BinaryFormat::Elf,
698                    "ElfX86_64TlsGd is not supported for this file format"
699                );
700                RelocationFlags::Elf {
701                    r_type: object::elf::R_X86_64_TLSGD,
702                }
703            }
704            Reloc::MachOX86_64Tlv => {
705                assert_eq!(
706                    self.object.format(),
707                    object::BinaryFormat::MachO,
708                    "MachOX86_64Tlv is not supported for this file format"
709                );
710                RelocationFlags::MachO {
711                    r_type: object::macho::X86_64_RELOC_TLV,
712                    r_pcrel: true,
713                    r_length: 2,
714                }
715            }
716            Reloc::MachOAarch64TlsAdrPage21 => {
717                assert_eq!(
718                    self.object.format(),
719                    object::BinaryFormat::MachO,
720                    "MachOAarch64TlsAdrPage21 is not supported for this file format"
721                );
722                RelocationFlags::MachO {
723                    r_type: object::macho::ARM64_RELOC_TLVP_LOAD_PAGE21,
724                    r_pcrel: true,
725                    r_length: 2,
726                }
727            }
728            Reloc::MachOAarch64TlsAdrPageOff12 => {
729                assert_eq!(
730                    self.object.format(),
731                    object::BinaryFormat::MachO,
732                    "MachOAarch64TlsAdrPageOff12 is not supported for this file format"
733                );
734                RelocationFlags::MachO {
735                    r_type: object::macho::ARM64_RELOC_TLVP_LOAD_PAGEOFF12,
736                    r_pcrel: false,
737                    r_length: 2,
738                }
739            }
740            Reloc::Aarch64TlsDescAdrPage21 => {
741                assert_eq!(
742                    self.object.format(),
743                    object::BinaryFormat::Elf,
744                    "Aarch64TlsDescAdrPage21 is not supported for this file format"
745                );
746                RelocationFlags::Elf {
747                    r_type: object::elf::R_AARCH64_TLSDESC_ADR_PAGE21,
748                }
749            }
750            Reloc::Aarch64TlsDescLd64Lo12 => {
751                assert_eq!(
752                    self.object.format(),
753                    object::BinaryFormat::Elf,
754                    "Aarch64TlsDescLd64Lo12 is not supported for this file format"
755                );
756                RelocationFlags::Elf {
757                    r_type: object::elf::R_AARCH64_TLSDESC_LD64_LO12,
758                }
759            }
760            Reloc::Aarch64TlsDescAddLo12 => {
761                assert_eq!(
762                    self.object.format(),
763                    object::BinaryFormat::Elf,
764                    "Aarch64TlsDescAddLo12 is not supported for this file format"
765                );
766                RelocationFlags::Elf {
767                    r_type: object::elf::R_AARCH64_TLSDESC_ADD_LO12,
768                }
769            }
770            Reloc::Aarch64TlsDescCall => {
771                assert_eq!(
772                    self.object.format(),
773                    object::BinaryFormat::Elf,
774                    "Aarch64TlsDescCall is not supported for this file format"
775                );
776                RelocationFlags::Elf {
777                    r_type: object::elf::R_AARCH64_TLSDESC_CALL,
778                }
779            }
780
781            Reloc::Aarch64AdrGotPage21 => match self.object.format() {
782                object::BinaryFormat::Elf => RelocationFlags::Elf {
783                    r_type: object::elf::R_AARCH64_ADR_GOT_PAGE,
784                },
785                object::BinaryFormat::MachO => RelocationFlags::MachO {
786                    r_type: object::macho::ARM64_RELOC_GOT_LOAD_PAGE21,
787                    r_pcrel: true,
788                    r_length: 2,
789                },
790                _ => unimplemented!("Aarch64AdrGotPage21 is not supported for this file format"),
791            },
792            Reloc::Aarch64Ld64GotLo12Nc => match self.object.format() {
793                object::BinaryFormat::Elf => RelocationFlags::Elf {
794                    r_type: object::elf::R_AARCH64_LD64_GOT_LO12_NC,
795                },
796                object::BinaryFormat::MachO => RelocationFlags::MachO {
797                    r_type: object::macho::ARM64_RELOC_GOT_LOAD_PAGEOFF12,
798                    r_pcrel: false,
799                    r_length: 2,
800                },
801                _ => unimplemented!("Aarch64Ld64GotLo12Nc is not supported for this file format"),
802            },
803            Reloc::S390xPCRel32Dbl => RelocationFlags::Generic {
804                kind: RelocationKind::Relative,
805                encoding: RelocationEncoding::S390xDbl,
806                size: 32,
807            },
808            Reloc::S390xPLTRel32Dbl => RelocationFlags::Generic {
809                kind: RelocationKind::PltRelative,
810                encoding: RelocationEncoding::S390xDbl,
811                size: 32,
812            },
813            Reloc::S390xTlsGd64 => {
814                assert_eq!(
815                    self.object.format(),
816                    object::BinaryFormat::Elf,
817                    "S390xTlsGd64 is not supported for this file format"
818                );
819                RelocationFlags::Elf {
820                    r_type: object::elf::R_390_TLS_GD64,
821                }
822            }
823            Reloc::S390xTlsGdCall => {
824                assert_eq!(
825                    self.object.format(),
826                    object::BinaryFormat::Elf,
827                    "S390xTlsGdCall is not supported for this file format"
828                );
829                RelocationFlags::Elf {
830                    r_type: object::elf::R_390_TLS_GDCALL,
831                }
832            }
833            Reloc::RiscvCallPlt => {
834                assert_eq!(
835                    self.object.format(),
836                    object::BinaryFormat::Elf,
837                    "RiscvCallPlt is not supported for this file format"
838                );
839                RelocationFlags::Elf {
840                    r_type: object::elf::R_RISCV_CALL_PLT,
841                }
842            }
843            Reloc::RiscvTlsGdHi20 => {
844                assert_eq!(
845                    self.object.format(),
846                    object::BinaryFormat::Elf,
847                    "RiscvTlsGdHi20 is not supported for this file format"
848                );
849                RelocationFlags::Elf {
850                    r_type: object::elf::R_RISCV_TLS_GD_HI20,
851                }
852            }
853            Reloc::RiscvPCRelLo12I => {
854                assert_eq!(
855                    self.object.format(),
856                    object::BinaryFormat::Elf,
857                    "RiscvPCRelLo12I is not supported for this file format"
858                );
859                RelocationFlags::Elf {
860                    r_type: object::elf::R_RISCV_PCREL_LO12_I,
861                }
862            }
863            Reloc::RiscvGotHi20 => {
864                assert_eq!(
865                    self.object.format(),
866                    object::BinaryFormat::Elf,
867                    "RiscvGotHi20 is not supported for this file format"
868                );
869                RelocationFlags::Elf {
870                    r_type: object::elf::R_RISCV_GOT_HI20,
871                }
872            }
873            // FIXME
874            reloc => unimplemented!("{:?}", reloc),
875        };
876
877        ObjectRelocRecord {
878            offset: record.offset,
879            name: record.name.clone(),
880            flags,
881            addend: record.addend,
882        }
883    }
884}
885
886fn translate_linkage(linkage: Linkage) -> (SymbolScope, bool) {
887    let scope = match linkage {
888        Linkage::Import => SymbolScope::Unknown,
889        Linkage::Local => SymbolScope::Compilation,
890        Linkage::Hidden => SymbolScope::Linkage,
891        Linkage::Export | Linkage::Preemptible => SymbolScope::Dynamic,
892    };
893    // TODO: this matches rustc_codegen_cranelift, but may be wrong.
894    let weak = linkage == Linkage::Preemptible;
895    (scope, weak)
896}
897
898/// This is the output of `ObjectModule`'s
899/// [`finish`](../struct.ObjectModule.html#method.finish) function.
900/// It contains the generated `Object` and other information produced during
901/// compilation.
902pub struct ObjectProduct {
903    /// Object artifact with all functions and data from the module defined.
904    pub object: Object<'static>,
905    /// Symbol IDs for functions (both declared and defined).
906    pub functions: SecondaryMap<FuncId, Option<(SymbolId, bool)>>,
907    /// Symbol IDs for data objects (both declared and defined).
908    pub data_objects: SecondaryMap<DataId, Option<(SymbolId, bool)>>,
909}
910
911impl ObjectProduct {
912    /// Return the `SymbolId` for the given function.
913    #[inline]
914    pub fn function_symbol(&self, id: FuncId) -> SymbolId {
915        self.functions[id].unwrap().0
916    }
917
918    /// Return the `SymbolId` for the given data object.
919    #[inline]
920    pub fn data_symbol(&self, id: DataId) -> SymbolId {
921        self.data_objects[id].unwrap().0
922    }
923
924    /// Write the object bytes in memory.
925    #[inline]
926    pub fn emit(self) -> Result<Vec<u8>, object::write::Error> {
927        self.object.write()
928    }
929}
930
931#[derive(Clone)]
932struct SymbolRelocs {
933    section: SectionId,
934    offset: u64,
935    relocs: Vec<ObjectRelocRecord>,
936}
937
938#[derive(Clone)]
939struct ObjectRelocRecord {
940    offset: CodeOffset,
941    name: ModuleRelocTarget,
942    flags: RelocationFlags,
943    addend: Addend,
944}