Skip to main content

rucc_object/
elf.rs

1//! Relocatable ELF objects.
2//!
3//! Design: `spec/11-asm-objects-debug.md` section 11.3, which says the three formats are written
4//! through the [`object`] crate's writer with our own layer above it for the parts it does not
5//! model. This is that layer for ELF, and what it holds is the part `object` cannot decide: which
6//! relocation an instruction wants, what a symbol's binding and type are, and the sections a
7//! linker expects to find whether or not anything was put in them.
8//!
9//! # The marker that has to be there
10//!
11//! `.note.GNU-stack`. A linker that does not find it in every input marks the stack executable,
12//! which section 11.3 calls out as a real and recurring security bug rather than a missing
13//! nicety. It is an empty section and nothing reads its contents, and leaving it out is the kind
14//! of mistake that produces a working program with a weakness in it, so it is written here and a
15//! test says so.
16//!
17//! # What is not here
18//!
19//! Mach-O and COFF. The formats disagree about more than their headers: an Apple symbol carries
20//! an underscore in front of the C name, Mach-O has no way to say how long a function is and
21//! wants `.subsections_via_symbols` instead, and COFF wants storage classes and `.pdata`. Each is
22//! its own piece of work and each is written when the target that needs it is.
23//!
24//! Thread-local storage. Reaching a thread-local variable is a different instruction sequence per
25//! model and the back end writes none of them, so a module carrying one is refused before it
26//! reaches here rather than written as an ordinary variable in the wrong section.
27
28use object::write::{
29    Object as Writer, Relocation, StandardSection, Symbol, SymbolId, SymbolSection,
30};
31use object::{
32    Architecture, BinaryFormat, Endianness, RelocationFlags, SectionKind, SymbolFlags, SymbolKind,
33    SymbolScope, elf,
34};
35use rucc_target::{ObjectFormat, TargetInfo};
36use rucc_tuple::Arch;
37
38use crate::section::{
39    Alias, Binding, Data, Object, Output, Place, Property, Reference, Reloc, Sections, Text,
40    Visibility,
41};
42
43/// Why an object file could not be written.
44#[derive(Debug, Clone, PartialEq, Eq)]
45pub enum Error {
46    /// A machine or a platform this does not write objects for.
47    Format {
48        /// The triple that was asked for.
49        triple: String,
50    },
51    /// The writer refused something it was given, which is a bug here rather than in a program.
52    Refused {
53        /// What it said, already formatted.
54        why: String,
55    },
56}
57
58impl std::fmt::Display for Error {
59    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
60        match self {
61            Error::Format { triple } => {
62                write!(f, "there is no object writer for {triple} in this compiler yet")
63            }
64            Error::Refused { why } => {
65                write!(f, "the object writer refused what it was given: {why}")
66            }
67        }
68    }
69}
70
71impl std::error::Error for Error {}
72
73/// One text section and the variables beside it, as a relocatable ELF object.
74///
75/// # Errors
76///
77/// [`Error::Format`] for a machine or a platform this does not write, and [`Error::Refused`] for
78/// anything the writer underneath objected to, which would be a bug here. An alias whose target
79/// this file does not define is refused the same way, since the front end is what reports that as
80/// a program's mistake and one reaching here means it did not. See [`Error`].
81pub fn write(
82    text: &Text,
83    data: &Data,
84    aliases: &[Alias],
85    target: &TargetInfo,
86    output: Output,
87) -> Result<Vec<u8>, Error> {
88    let Output { sections, property } = output;
89    if target.tuple.arch() != Arch::X86_64 || target.object_format != ObjectFormat::Elf {
90        return Err(Error::Format { triple: target.tuple.to_string() });
91    }
92    let mut obj = Writer::new(BinaryFormat::Elf, Architecture::X86_64, Endianness::Little);
93    // The one that holds every function when they are not being split up. Asked for even when it
94    // will stay empty, because it is the section the writer underneath starts a file with anyway
95    // and gcc writes an empty `.text` under `-ffunction-sections` too.
96    let whole = obj.section_id(StandardSection::Text);
97    if !sections.functions {
98        obj.append_section_data(whole, &text.bytes, u64::from(text.align));
99    }
100
101    // Every function defined here, then every variable, then every name either of them wanted that
102    // is not. A name is looked up rather than added twice, because two symbols with one name is
103    // not a file a linker accepts.
104    let mut symbols = std::collections::BTreeMap::new();
105    // Where each function ended up, in the order they were written, so that a relocation inside
106    // one goes into the section that one is in. The same list as `text.funcs` and in the same
107    // order, so the two are walked together below.
108    let mut split = Vec::with_capacity(text.funcs.len());
109    for func in &text.funcs {
110        // A section of its own, holding this function's bytes and nothing else, so the linker can
111        // drop it when nothing reaches it. The name is what gcc writes, and the leading `.text.`
112        // is not decoration: `--gc-sections` and the linker scripts that place code both match on
113        // it, and a section called something else would be placed by the catch all rule.
114        let (section, at) = if sections.functions {
115            let name = format!(".text.{}", func.name).into_bytes();
116            let id = obj.add_section(Vec::new(), name, SectionKind::Text);
117            let bytes = &text.bytes[func.start..func.start + func.len];
118            obj.append_section_data(id, bytes, u64::from(func.align.max(1)));
119            (id, 0)
120        } else {
121            (whole, func.start as u64)
122        };
123        let id = obj.add_symbol(Symbol {
124            name: func.name.clone().into_bytes(),
125            value: at,
126            size: func.len as u64,
127            kind: SymbolKind::Text,
128            scope: scope_of(func.binding),
129            weak: func.binding == Binding::Weak,
130            section: SymbolSection::Section(section),
131            flags: SymbolFlags::None,
132        });
133        see(&mut obj, id, func.binding, func.visibility);
134        symbols.insert(func.name.clone(), id);
135        split.push(section);
136    }
137
138    // Where each variable's image landed in the section it went into, kept because a relocation in
139    // an image counts from the start of the image and one in a file counts from the start of the
140    // section. A variable that is not in a section has no entry, since nothing in a merged one can
141    // hold a relocation: the linker is being asked for zeroed space rather than for an image.
142    let mut placed = Vec::with_capacity(data.objects.len());
143    // The one section the writer has no name of its own for, remembered so that every variable that
144    // wants it lands in the same one. The rest come back from `section_id`, which already answers
145    // with the section it made the first time it was asked.
146    let mut local = None;
147    for object in &data.objects {
148        let (section, offset) = put(&mut obj, object, &mut local, sections);
149        let id = obj.add_symbol(Symbol {
150            name: object.name.clone().into_bytes(),
151            // A common symbol says what it wants rather than where it is, and what it wants is
152            // recorded where an ordinary symbol records its address.
153            value: if object.place == Place::Merged { object.align } else { offset },
154            size: object.size,
155            kind: SymbolKind::Data,
156            scope: scope_of(object.binding),
157            weak: object.binding == Binding::Weak,
158            section,
159            flags: SymbolFlags::None,
160        });
161        see(&mut obj, id, object.binding, object.visibility);
162        symbols.insert(object.name.clone(), id);
163        placed.push((section.id(), offset));
164    }
165
166    // A second name for something already added, which is where the alias's own binding is the
167    // only thing it does not take from what it points at: the target of one may be a `static` and
168    // the alias of it may not be. Before the loop below rather than after it, because a reference
169    // to the new name is a reference to something this file defines and would otherwise be added
170    // as a name this file wants from somewhere else.
171    for alias in aliases {
172        let Some(&id) = symbols.get(&alias.target) else {
173            let why =
174                format!("'{}' is aliased to '{}', which is not here", alias.name, alias.target);
175            return Err(Error::Refused { why });
176        };
177        let (value, size) = (obj.symbol(id).value, obj.symbol(id).size);
178        let (kind, section) = (obj.symbol(id).kind, obj.symbol(id).section);
179        let id = obj.add_symbol(Symbol {
180            name: alias.name.clone().into_bytes(),
181            value,
182            size,
183            kind,
184            scope: scope_of(alias.binding),
185            weak: alias.binding == Binding::Weak,
186            section,
187            flags: SymbolFlags::None,
188        });
189        see(&mut obj, id, alias.binding, alias.visibility);
190        symbols.insert(alias.name.clone(), id);
191    }
192
193    let wanted = text
194        .relocs
195        .iter()
196        .chain(text.unwind.relocs.iter())
197        .chain(data.objects.iter().flat_map(|object| &object.relocs));
198    for reloc in wanted {
199        if symbols.contains_key(&reloc.symbol) {
200            continue;
201        }
202        let id = obj.add_symbol(Symbol {
203            name: reloc.symbol.clone().into_bytes(),
204            value: 0,
205            size: 0,
206            // What kind of thing an undefined name is is not known here and does not have to be:
207            // a linker resolves an undefined symbol by its name, and the type of one that is not
208            // defined anywhere in this file is nothing this file can say.
209            kind: SymbolKind::Unknown,
210            scope: SymbolScope::Dynamic,
211            weak: false,
212            section: SymbolSection::Undefined,
213            flags: SymbolFlags::None,
214        });
215        symbols.insert(reloc.symbol.clone(), id);
216    }
217
218    for reloc in &text.relocs {
219        // Which function's bytes this one is in, which is the question only the split path has to
220        // ask: when there is one text section every offset in it is already the offset in it.
221        // Every relocation is inside some function, since the padding between two of them is
222        // instructions that do nothing and holds nothing a linker fills in.
223        let (section, at) = if sections.functions {
224            let after = text.funcs.partition_point(|func| func.start <= reloc.at);
225            let Some(func) = after.checked_sub(1).map(|i| &text.funcs[i]) else {
226                let why = format!("a relocation at {} is in front of every function", reloc.at);
227                return Err(Error::Refused { why });
228            };
229            (split[after - 1], (reloc.at - func.start) as u64)
230        } else {
231            (whole, reloc.at as u64)
232        };
233        add(&mut obj, section, at, reloc, &symbols)?;
234    }
235
236    // The unwind table, if there is one. Its own section rather than part of the text, because it
237    // is read rather than run: the loader maps it and the linker gathers every input's into one
238    // table and builds the index the unwinder binary searches. Eight, because a record is looked
239    // up by address at a point where the program is usually already crashing and an unaligned read
240    // there is a second fault on top of the first.
241    if !text.unwind.bytes.is_empty() {
242        let frames = obj.add_section(Vec::new(), b".eh_frame".to_vec(), SectionKind::ReadOnlyData);
243        obj.append_section_data(frames, &text.unwind.bytes, 8);
244        for reloc in &text.unwind.relocs {
245            add(&mut obj, frames, reloc.at as u64, reloc, &symbols)?;
246        }
247    }
248    for (object, &(section, offset)) in data.objects.iter().zip(&placed) {
249        let Some(section) = section else { continue };
250        for reloc in &object.relocs {
251            add(&mut obj, section, offset + reloc.at as u64, reloc, &symbols)?;
252        }
253    }
254
255    // What the file was built to have checked, when it was built to have anything checked. Left
256    // out otherwise rather than written as a zero, because a linker treats a missing note and a
257    // note with no bits in it the same way and gcc writes nothing.
258    if property.any() {
259        let note = obj.section_id(StandardSection::GnuProperty);
260        obj.append_section_data(note, &record(property), 8);
261    }
262
263    // Written as an empty note rather than left out, because a linker that does not find it in
264    // every input marks the stack executable.
265    obj.add_section(Vec::new(), b".note.GNU-stack".to_vec(), SectionKind::Metadata);
266
267    obj.write().map_err(|why| Error::Refused { why: why.to_string() })
268}
269
270/// The note that says what the file was built to have checked.
271///
272/// A note is a name, a description and a number saying what kind it is, and this kind is the one
273/// whose description is a list of properties. Each property is a key, a length and that many bytes,
274/// and the one written here is the feature word.
275///
276/// Everything is padded to eight rather than to four, which is what a note in a sixty four bit
277/// object is aligned to and what makes the reader's walk over the list a walk over aligned words.
278/// The two lengths in the header count the padding after what they measure, which is why the
279/// description is sixteen bytes for a property of twelve.
280fn record(property: Property) -> Vec<u8> {
281    // How long the name is, how long the description is, and which kind of note this is. Then the
282    // name, and then the description, which is the one property and the four bytes that pad it.
283    let head = [4, 16, elf::NT_GNU_PROPERTY_TYPE_0.0];
284    let desc = [Property::X86_FEATURES, 4, property.features, 0];
285    let mut out = Vec::with_capacity(32);
286    for word in head {
287        out.extend_from_slice(&word.to_le_bytes());
288    }
289    // Twelve bytes in and already a multiple of eight, so the description begins straight after the
290    // name with no padding between them.
291    out.extend_from_slice(b"GNU\0");
292    for word in desc {
293        out.extend_from_slice(&word.to_le_bytes());
294    }
295    out
296}
297
298/// One variable's image into the section it belongs in, and where in that section it landed.
299///
300/// A zero filled variable takes as many bytes of the file as it is long on the way in and none on
301/// the way out, which is the whole point of the section it goes in. A merged one goes in no section
302/// at all: the linker is being asked for that much zeroed space under that name, and where it ends
303/// up is the linker's answer rather than this file's.
304fn put(
305    obj: &mut Writer<'_>,
306    object: &Object,
307    local: &mut Option<object::write::SectionId>,
308    sections: Sections,
309) -> (SymbolSection, u64) {
310    // A section of its own, named after the variable and after the section it would have gone in,
311    // which is what `-fdata-sections` asks for. A merged variable has no section to split and a
312    // named one was named by the program, so both are left where they are: the first is a request
313    // to the linker rather than an image, and the second would otherwise have the flag silently
314    // overrule what the source said.
315    if sections.data {
316        if let Some(name) = object.place.split(&object.name) {
317            let section = obj.add_section(Vec::new(), name.into_bytes(), kind_of(&object.place));
318            let offset = if object.place == Place::Zero {
319                obj.append_section_bss(section, object.size, object.align)
320            } else {
321                obj.append_section_data(section, &object.bytes, object.align)
322            };
323            return (SymbolSection::Section(section), offset);
324        }
325    }
326    let section = match &object.place {
327        Place::Written => obj.section_id(StandardSection::Data),
328        Place::ReadOnly => obj.section_id(StandardSection::ReadOnlyData),
329        // Read only after the loader has written it, which the writer knows as the relocatable
330        // read only data section and which is `.data.rel.ro` on ELF. The `.local` half is a layout
331        // hint the writer has no name for, so it is added by hand and remembered: asking again
332        // would make a second section with the same name, and a file with one of those per variable
333        // is a file whose section headers outweigh what they describe.
334        Place::RelocReadOnly { local: false } => {
335            obj.section_id(StandardSection::ReadOnlyDataWithRel)
336        }
337        Place::RelocReadOnly { local: true } => *local.get_or_insert_with(|| {
338            obj.add_section(
339                Vec::new(),
340                b".data.rel.ro.local".to_vec(),
341                SectionKind::ReadOnlyDataWithRel,
342            )
343        }),
344        Place::Zero => obj.section_id(StandardSection::UninitializedData),
345        Place::Merged => return (SymbolSection::Common, 0),
346        // A named section is the program's word for where this goes, and a program that names one
347        // wants what it named rather than what would have been chosen. It is written as ordinary
348        // data because nothing in the IR says otherwise.
349        Place::Named(name) => {
350            obj.add_section(Vec::new(), name.clone().into_bytes(), SectionKind::Data)
351        }
352    };
353    let offset = if object.place == Place::Zero {
354        obj.append_section_bss(section, object.size, object.align)
355    } else {
356        obj.append_section_data(section, &object.bytes, object.align)
357    };
358    (SymbolSection::Section(section), offset)
359}
360
361/// What a section split off for one variable is, which is what the section it was split off from
362/// was.
363///
364/// Splitting changes the name and nothing else. A variable that was going to be in a page the
365/// loader maps read only is still in one, and a zero filled variable still costs the file nothing,
366/// so the flags a linker reads off the section header have to come out the same as they would
367/// have. The two kinds with no section of their own never reach here, and `Data` for them is a
368/// value that is never used rather than a claim about either.
369fn kind_of(place: &Place) -> SectionKind {
370    match place {
371        Place::ReadOnly => SectionKind::ReadOnlyData,
372        Place::RelocReadOnly { .. } => SectionKind::ReadOnlyDataWithRel,
373        Place::Zero => SectionKind::UninitializedData,
374        Place::Written | Place::Merged | Place::Named(_) => SectionKind::Data,
375    }
376}
377
378/// One relocation, `at` bytes into the section it ended up in.
379///
380/// The offset is worked out by the caller rather than here, because the two callers count from
381/// different places: a relocation in an image counts from the start of that image and a relocation
382/// in a function counts from the start of that function, and neither of those is where the section
383/// begins once something else is in front of it.
384fn add(
385    obj: &mut Writer<'_>,
386    section: object::write::SectionId,
387    at: u64,
388    reloc: &Reloc,
389    symbols: &std::collections::BTreeMap<String, SymbolId>,
390) -> Result<(), Error> {
391    let r_type = r_type(reloc.kind)
392        .ok_or_else(|| Error::Refused { why: format!("no relocation is {:?}", reloc.kind) })?;
393    obj.add_relocation(
394        section,
395        Relocation {
396            offset: at,
397            symbol: symbols[&reloc.symbol],
398            addend: reloc.addend,
399            flags: RelocationFlags::Elf { r_type },
400        },
401    )
402    .map_err(|why| Error::Refused { why: why.to_string() })
403}
404
405/// How far a name reaches, which is the one thing about a symbol ELF calls its binding.
406///
407/// `SymbolScope` is two facts in one word, and the trap is that the middle one is not the neutral
408/// answer it reads as. The writer turns `Compilation` into a local symbol, and it turns the choice
409/// between `Linkage` and `Dynamic` into `st_other`: `Linkage` is `STV_HIDDEN` and `Dynamic` is
410/// `STV_DEFAULT`. So there is no way to say global and decline to say anything about visibility,
411/// and picking the one whose name sounds like the smaller claim is picking hidden. That is what
412/// tamnd/rucc#733 was.
413///
414/// `Dynamic` is what every global asks for here, and the visibility is said afterwards by
415/// [`see`] rather than through this, so that nothing about `st_other` depends on reading one of
416/// these four names the way its author meant it.
417fn scope_of(binding: Binding) -> SymbolScope {
418    match binding {
419        Binding::Local => SymbolScope::Compilation,
420        Binding::Global | Binding::Weak => SymbolScope::Dynamic,
421    }
422}
423
424/// Say what `st_other` is for a symbol that has just been added, rather than leave it to be
425/// inferred from the scope.
426///
427/// The writer underneath fills `st_info` in from the kind, the binding and whether the symbol is
428/// defined, and there is nothing to add to that. `st_other` is the field this compiler has an
429/// opinion about and the field the `SymbolScope` mapping got wrong, so it is written here in the
430/// two bits ELF puts the visibility in and the rest of the byte is left as it was found.
431///
432/// A local symbol is left alone. Its visibility means nothing, since a name the static link has
433/// already finished with cannot be in a dynamic symbol table whatever `st_other` says, and gcc
434/// writes `STV_DEFAULT` for one, which is what the writer underneath produces on its own.
435fn see(obj: &mut Writer<'_>, id: SymbolId, binding: Binding, visibility: Visibility) {
436    if binding == Binding::Local {
437        return;
438    }
439    let wanted = match visibility {
440        Visibility::Default => elf::STV_DEFAULT,
441        Visibility::Hidden => elf::STV_HIDDEN,
442        Visibility::Protected => elf::STV_PROTECTED,
443    };
444    if let SymbolFlags::Elf { st_other, .. } = obj.symbol_flags_mut(id) {
445        *st_other = st_other.with_visibility(wanted);
446    }
447}
448
449/// Which relocation of this machine one reference is, and nothing for one this machine has none of.
450///
451/// The first three are the distance from the end of an instruction to something, and they differ in
452/// what the linker is allowed to do about it. A call may go through a stub, which is what lets a
453/// call reach a symbol further away than four bytes can say and what makes a call to a shared
454/// library work at all. A load may not, because there is nowhere to put a stub that a load would
455/// read, so a load of something another object may define reads a table slot the linker fills in
456/// instead, and the relaxing form of the relocation lets the linker undo that when it turns out
457/// nobody else defines it. The fourth is the address itself, at the two widths this machine writes
458/// one at.
459fn r_type(reference: Reference) -> Option<elf::RelocationType> {
460    Some(match reference {
461        Reference::Call => elf::R_X86_64_PLT32,
462        Reference::Data => elf::R_X86_64_PC32,
463        Reference::Got => elf::R_X86_64_REX_GOTPCRELX,
464        Reference::Address { bytes: 8 } => elf::R_X86_64_64,
465        Reference::Address { bytes: 4 } => elf::R_X86_64_32,
466        Reference::Address { .. } => return None,
467    })
468}
469
470#[cfg(test)]
471mod tests {
472    use super::*;
473
474    use object::read::elf::Sym as _;
475    use object::read::{Object as _, ObjectSection as _, ObjectSymbol as _};
476    use rucc_target::{Arch, Env, Os, Triple};
477
478    use crate::section::{Extent, Reloc};
479
480    /// A linux x86-64 target, which is the only one this writes.
481    fn target() -> TargetInfo {
482        TargetInfo::new(Triple::new(Arch::X86_64, Os::Linux, Env::Gnu))
483    }
484
485    /// One function of that name, at that offset, that many bytes long, and visible that far.
486    ///
487    /// Visibility is the field these cases mostly have no opinion about, so it is the one the
488    /// helper fills in and the two that do have an opinion write for themselves.
489    fn extent(name: String, start: usize, len: usize, binding: Binding) -> Extent {
490        Extent {
491            name,
492            start,
493            len,
494            align: crate::FUNC_ALIGN,
495            binding,
496            visibility: Visibility::Default,
497        }
498    }
499
500    /// A call to something outside the file, which is the shape every case here starts from.
501    fn calling(name: &str) -> Text {
502        Text {
503            bytes: vec![0xe8, 0, 0, 0, 0, 0xc3],
504            funcs: vec![extent("f".to_owned(), 0, 6, Binding::Global)],
505            relocs: vec![Reloc {
506                at: 1,
507                symbol: name.to_owned(),
508                kind: Reference::Call,
509                addend: -4,
510            }],
511            ..Text::default()
512        }
513    }
514
515    #[test]
516    fn the_bytes_come_back_out_of_the_section_they_went_into() {
517        let text = calling("puts");
518        let bytes =
519            write(&text, &Data::default(), &[], &target(), Output::default()).expect("an object");
520        let file = object::File::parse(&bytes[..]).expect("a readable object");
521        let section = file.section_by_name(".text").expect("a text section");
522        assert_eq!(section.data().expect("the bytes"), &text.bytes[..]);
523    }
524
525    #[test]
526    fn a_function_is_a_symbol_that_says_where_it_is_and_how_long_it_is() {
527        let mut text = calling("puts");
528        text.funcs.push(extent("g".to_owned(), 16, 1, Binding::Global));
529        text.bytes.resize(17, 0x90);
530        let bytes =
531            write(&text, &Data::default(), &[], &target(), Output::default()).expect("an object");
532        let file = object::File::parse(&bytes[..]).expect("a readable object");
533        let g = file.symbols().find(|s| s.name() == Ok("g")).expect("the second function");
534        assert_eq!(g.address(), 16);
535        assert_eq!(g.size(), 1);
536        assert_eq!(g.kind(), SymbolKind::Text);
537        assert!(g.is_global(), "nothing said otherwise about this one");
538    }
539
540    #[test]
541    fn a_function_no_other_file_can_see_is_a_local_symbol() {
542        let mut text = calling("puts");
543        text.funcs.push(extent("hidden".to_owned(), 16, 1, Binding::Local));
544        text.funcs.push(extent("shared".to_owned(), 32, 1, Binding::Weak));
545        text.bytes.resize(33, 0x90);
546        let bytes =
547            write(&text, &Data::default(), &[], &target(), Output::default()).expect("an object");
548        let file = object::File::parse(&bytes[..]).expect("a readable object");
549        let hidden = file.symbols().find(|s| s.name() == Ok("hidden")).expect("the static one");
550        // A symbol the linker keeps and does not let another file reach, which is the whole of
551        // what `static` on a function means and what two files each defining their own need.
552        assert!(hidden.is_local(), "a static function must not be offered to the linker");
553        assert!(!hidden.is_weak());
554        let shared = file.symbols().find(|s| s.name() == Ok("shared")).expect("the weak one");
555        assert!(shared.is_weak(), "a weak function has to be able to lose");
556        assert!(shared.is_global());
557    }
558
559    /// A global is `STV_DEFAULT`, so a shared library built from these objects exports something.
560    ///
561    /// The bug in tamnd/rucc#733. Every global came out `STV_HIDDEN`, which a static link does not
562    /// look at, so nothing here noticed and SQLite linked and ran and the whole test suite passed.
563    /// What it costs is the dynamic symbol table: `gcc -shared` over one of these objects produced
564    /// a library with an empty one, and `dlsym` could not find a function the file plainly defines.
565    ///
566    /// Written against `st_other` itself rather than against the reader's `scope`, because `scope`
567    /// is the word that was misread in the first place and a test that asks it the same question
568    /// would agree with whatever the writer did.
569    #[test]
570    fn a_global_is_visible_to_the_dynamic_linker_and_a_static_one_is_not_a_symbol_at_all() {
571        let mut text = calling("puts");
572        text.funcs.push(extent("g".to_owned(), 16, 1, Binding::Global));
573        text.funcs.push(extent("w".to_owned(), 32, 1, Binding::Weak));
574        text.funcs.push(extent("s".to_owned(), 48, 1, Binding::Local));
575        text.bytes.resize(49, 0x90);
576        let bytes =
577            write(&text, &Data::default(), &[], &target(), Output::default()).expect("an object");
578        let file = object::read::elf::ElfFile64::<Endianness>::parse(&bytes[..]).expect("readable");
579        let visibility = |name: &str| {
580            file.symbols()
581                .find(|s| s.name() == Ok(name))
582                .expect("the function")
583                .elf_symbol()
584                .st_visibility()
585        };
586        // Nothing said hidden about either of these, so neither is.
587        assert_eq!(visibility("g"), elf::STV_DEFAULT);
588        assert_eq!(visibility("w"), elf::STV_DEFAULT, "a weak one is still a name others may use");
589        // The `static` one is local, and a local symbol's visibility means nothing either way,
590        // which is why the binding is what this asks about.
591        assert_eq!(visibility("s"), elf::STV_DEFAULT);
592    }
593
594    /// And the other direction: a name that did ask to be hidden is hidden, and a protected one is
595    /// protected.
596    ///
597    /// The half of tamnd/rucc#733 that the fix above left open. Saying `STV_DEFAULT` for everything
598    /// is right for everything nobody marked and wrong the moment something is marked, so the two
599    /// tests together are what says the field carries an answer rather than a constant.
600    ///
601    /// Both are asked of a function and of a variable, because they are added by two different
602    /// loops in `write` and a field one of them fills in is not a field the other one does.
603    #[test]
604    fn a_name_that_asked_to_be_hidden_is_hidden_and_a_protected_one_is_protected() {
605        let mut text = calling("puts");
606        for (index, (name, seen)) in
607            [("h", Visibility::Hidden), ("p", Visibility::Protected)].into_iter().enumerate()
608        {
609            let mut func = extent(name.to_owned(), 16 + index * 16, 1, Binding::Global);
610            func.visibility = seen;
611            text.funcs.push(func);
612        }
613        text.bytes.resize(49, 0x90);
614        let mut data = Data::default();
615        for (name, seen) in [("vh", Visibility::Hidden), ("vp", Visibility::Protected)] {
616            let mut object = variable(name, Place::Written);
617            object.visibility = seen;
618            data.objects.push(object);
619        }
620        let bytes = write(&text, &data, &[], &target(), Output::default()).expect("an object");
621        let file = object::read::elf::ElfFile64::<Endianness>::parse(&bytes[..]).expect("readable");
622        let visibility = |name: &str| {
623            file.symbols()
624                .find(|s| s.name() == Ok(name))
625                .expect("the symbol")
626                .elf_symbol()
627                .st_visibility()
628        };
629        assert_eq!(visibility("h"), elf::STV_HIDDEN);
630        assert_eq!(visibility("p"), elf::STV_PROTECTED);
631        assert_eq!(visibility("vh"), elf::STV_HIDDEN, "a variable goes through a second loop");
632        assert_eq!(visibility("vp"), elf::STV_PROTECTED);
633        // The one thing a visibility must not disturb, since `st_info` and `st_other` are written
634        // in one go and the second was set after the first.
635        let h = file.symbols().find(|s| s.name() == Ok("h")).expect("the function");
636        assert!(h.is_global(), "hidden is about the dynamic linker and not about the binding");
637        assert_eq!(h.size(), 1, "and it is still a function of the length it was");
638    }
639
640    #[test]
641    fn a_name_this_file_does_not_define_is_left_for_the_linker_to_find() {
642        let bytes = write(&calling("puts"), &Data::default(), &[], &target(), Output::default())
643            .expect("an object");
644        let file = object::File::parse(&bytes[..]).expect("a readable object");
645        let puts = file.symbols().find(|s| s.name() == Ok("puts")).expect("the callee");
646        assert!(puts.is_undefined(), "the file does not define it and must not claim to");
647    }
648
649    #[test]
650    fn a_call_asks_for_the_relocation_a_stub_may_answer_and_a_load_asks_for_the_one_that_may_not() {
651        for (reference, wanted) in [
652            (Reference::Call, elf::R_X86_64_PLT32),
653            (Reference::Data, elf::R_X86_64_PC32),
654            (Reference::Got, elf::R_X86_64_REX_GOTPCRELX),
655        ] {
656            let mut text = calling("puts");
657            text.relocs[0].kind = reference;
658            let bytes = write(&text, &Data::default(), &[], &target(), Output::default())
659                .expect("an object");
660            let file = object::File::parse(&bytes[..]).expect("a readable object");
661            let section = file.section_by_name(".text").expect("a text section");
662            let (offset, reloc) = section.relocations().next().expect("one relocation");
663            assert_eq!(offset, 1);
664            assert_eq!(reloc.addend(), -4);
665            assert_eq!(reloc.flags(), RelocationFlags::Elf { r_type: wanted });
666        }
667    }
668
669    #[test]
670    fn a_name_wanted_twice_is_one_symbol_rather_than_two() {
671        let mut text = calling("puts");
672        text.relocs.push(Reloc {
673            at: 1,
674            symbol: "puts".to_owned(),
675            kind: Reference::Call,
676            addend: -4,
677        });
678        let bytes =
679            write(&text, &Data::default(), &[], &target(), Output::default()).expect("an object");
680        let file = object::File::parse(&bytes[..]).expect("a readable object");
681        assert_eq!(file.symbols().filter(|s| s.name() == Ok("puts")).count(), 1);
682    }
683
684    #[test]
685    fn a_function_that_is_also_called_is_not_a_second_symbol() {
686        let text = calling("f");
687        let bytes =
688            write(&text, &Data::default(), &[], &target(), Output::default()).expect("an object");
689        let file = object::File::parse(&bytes[..]).expect("a readable object");
690        let mut found = file.symbols().filter(|s| s.name() == Ok("f"));
691        let f = found.next().expect("the function");
692        assert!(!f.is_undefined(), "the file defines it");
693        assert!(found.next().is_none(), "and defines it once");
694    }
695
696    #[test]
697    fn the_marker_that_says_the_stack_is_not_executable_is_written() {
698        let bytes = write(&calling("puts"), &Data::default(), &[], &target(), Output::default())
699            .expect("an object");
700        let file = object::File::parse(&bytes[..]).expect("a readable object");
701        let note = file.section_by_name(".note.GNU-stack").expect("the marker");
702        assert!(note.data().expect("no bytes").is_empty());
703    }
704
705    /// What the file says it was built to have checked, byte for byte.
706    ///
707    /// Written against the bytes rather than against a reader, because the two lengths in the
708    /// header count the padding after what they measure and a note whose lengths are one word out
709    /// is one a linker drops without saying anything. What comes of that is a program the loader
710    /// leaves the check turned off for, which is a build that looks like it worked.
711    #[test]
712    fn the_note_that_says_what_the_file_was_built_to_have_checked_is_written() {
713        let property = Property { features: Property::IBT | Property::SHSTK };
714        let output = Output { property, ..Output::default() };
715        let bytes =
716            write(&calling("puts"), &Data::default(), &[], &target(), output).expect("an object");
717        let file = object::File::parse(&bytes[..]).expect("a readable object");
718        let note = file.section_by_name(".note.gnu.property").expect("the note");
719        assert_eq!(note.align(), 8, "a note in a sixty four bit object is read a word at a time");
720        let want: Vec<u8> = [
721            4u32,
722            16,
723            5,
724            u32::from_le_bytes(*b"GNU\0"),
725            Property::X86_FEATURES,
726            4,
727            Property::IBT | Property::SHSTK,
728            0,
729        ]
730        .iter()
731        .flat_map(|word| word.to_le_bytes())
732        .collect();
733        assert_eq!(note.data().expect("the bytes"), &want[..]);
734    }
735
736    /// And nothing at all when the file was built to have nothing checked.
737    ///
738    /// A note with an empty feature word and no note are the same thing to a linker, which drops
739    /// the whole property when any input lacks it. gcc writes nothing, so a section header that
740    /// describes nothing would be the one difference between the two compilers' objects.
741    #[test]
742    fn a_file_built_to_have_nothing_checked_says_nothing() {
743        let bytes = write(&calling("puts"), &Data::default(), &[], &target(), Output::default())
744            .expect("an object");
745        let file = object::File::parse(&bytes[..]).expect("a readable object");
746        assert!(file.section_by_name(".note.gnu.property").is_none());
747    }
748
749    /// Every unwind record names the function it is about, and each name goes where it is in the
750    /// table rather than at the start of it.
751    ///
752    /// Written because working the offset out is the caller's job here, which is what the two text
753    /// paths differ about, and a third caller that let it default to nothing would put every record
754    /// in the table on the same function. Nothing else would notice: the section is the right
755    /// length, the symbols are right, the link succeeds, and what comes of it is an unwinder that
756    /// walks out of the wrong frame the first time something throws or a backtrace is taken.
757    #[test]
758    fn an_unwind_record_names_the_function_it_is_about_and_not_the_first_one() {
759        let mut text = calling("puts");
760        text.funcs.push(extent("g".to_owned(), 16, 1, Binding::Global));
761        text.bytes.resize(17, 0x90);
762        // A shared header and two records, whose contents nothing here reads: what is being asked
763        // is where in them each name landed.
764        text.unwind.bytes = vec![0; 64];
765        for (at, name) in [(32usize, "f"), (48usize, "g")] {
766            text.unwind.relocs.push(Reloc {
767                at,
768                symbol: name.to_owned(),
769                kind: Reference::Address { bytes: 8 },
770                addend: 0,
771            });
772        }
773        let bytes =
774            write(&text, &Data::default(), &[], &target(), Output::default()).expect("an object");
775        let file = object::File::parse(&bytes[..]).expect("a readable object");
776        let frames = file.section_by_name(".eh_frame").expect("the table");
777        let mut at = frames.relocations().map(|(offset, _)| offset).collect::<Vec<_>>();
778        at.sort_unstable();
779        assert_eq!(at, [32, 48]);
780    }
781
782    /// The name of the section that symbol is defined in.
783    fn lives_in<'a>(file: &'a object::File<'a>, name: &str) -> String {
784        let symbol = file.symbols().find(|s| s.name() == Ok(name)).expect("the symbol");
785        let index = symbol.section_index().expect("a section to be defined in");
786        let section = file.section_by_index(index).expect("a readable section");
787        section.name().expect("a named section").to_owned()
788    }
789
790    /// Two functions, the second of them sixteen bytes in and calling something outside the file.
791    fn two() -> Text {
792        let mut text = calling("puts");
793        // Padded to where the second one is aligned to, with the instruction that does nothing,
794        // because the space in front of a function is reached by falling off the end of one.
795        text.bytes.resize(16, 0x90);
796        text.bytes.extend_from_slice(&[0xe8, 0, 0, 0, 0, 0xc3]);
797        text.funcs.push(extent("g".to_owned(), 16, 6, Binding::Global));
798        text.relocs.push(Reloc {
799            at: 17,
800            symbol: "puts".to_owned(),
801            kind: Reference::Call,
802            addend: -4,
803        });
804        text
805    }
806
807    /// What `-ffunction-sections` comes down to in an object file, which is the flag that makes
808    /// `--gc-sections` able to drop anything: a linker can leave out a section nothing reaches and
809    /// cannot leave out half of one.
810    ///
811    /// The empty `.text` stays, because it is the section the writer underneath opens a file with
812    /// and gcc 16 leaves an empty one behind under the flag too.
813    #[test]
814    fn every_function_gets_a_section_of_its_own_when_that_is_what_was_asked_for() {
815        let sections =
816            Output { sections: Sections { functions: true, data: false }, ..Output::default() };
817        let bytes = write(&two(), &Data::default(), &[], &target(), sections).expect("an object");
818        let file = object::File::parse(&bytes[..]).expect("a readable object");
819        assert_eq!(lives_in(&file, "f"), ".text.f");
820        assert_eq!(lives_in(&file, "g"), ".text.g");
821        assert!(file.section_by_name(".text").expect("the empty one").size() == 0);
822        // Each one at nothing into its own section, and as long as it was: a function alone in a
823        // section starts where the section does, whatever it started at when they shared one.
824        for name in ["f", "g"] {
825            let symbol = file.symbols().find(|s| s.name() == Ok(name)).expect("the function");
826            assert_eq!(symbol.address(), 0, "{name}");
827            assert_eq!(symbol.size(), 6, "{name}");
828        }
829        let section = file.section_by_name(".text.g").expect("the second function");
830        assert_eq!(section.data().expect("the bytes"), &[0xe8, 0, 0, 0, 0, 0xc3]);
831        // The padding between the two is gone with them, since it was there to align the second
832        // one inside a section they shared and each section is aligned by the linker now.
833        assert_eq!(section.align(), u64::from(crate::FUNC_ALIGN));
834    }
835
836    /// A relocation counts from the start of whichever section its function ended up in, which is
837    /// the arithmetic the split path has to do and the unsplit one never does.
838    ///
839    /// Getting it wrong is a call patched over the wrong bytes, which assembles, links, and jumps
840    /// into the middle of an instruction at run time.
841    #[test]
842    fn a_relocation_moves_with_the_function_whose_bytes_it_is_in() {
843        let sections =
844            Output { sections: Sections { functions: true, data: false }, ..Output::default() };
845        let bytes = write(&two(), &Data::default(), &[], &target(), sections).expect("an object");
846        let file = object::File::parse(&bytes[..]).expect("a readable object");
847        for name in [".text.f", ".text.g"] {
848            let section = file.section_by_name(name).expect("a function");
849            let (offset, _) = section.relocations().next().expect("the call in it");
850            // One byte in either way, because the call is the first instruction of both and the
851            // opcode is one byte in front of the address the linker fills in.
852            assert_eq!(offset, 1, "{name}");
853            assert_eq!(section.relocations().count(), 1, "{name}");
854        }
855    }
856
857    /// One variable of four bytes, in whichever section its own answer puts it.
858    fn variable(name: &str, place: Place) -> Object {
859        Object {
860            name: name.to_owned(),
861            bytes: if place == Place::Zero { Vec::new() } else { vec![1, 0, 0, 0] },
862            size: 4,
863            align: 4,
864            place,
865            binding: Binding::Global,
866            visibility: Visibility::Default,
867            relocs: Vec::new(),
868        }
869    }
870
871    /// A file of that one variable and nothing else.
872    fn holding(object: Object) -> Vec<u8> {
873        let data = Data { objects: vec![object] };
874        write(&Text::default(), &data, &[], &target(), Output::default()).expect("an object")
875    }
876
877    #[test]
878    fn what_a_variable_is_decides_which_section_it_goes_in() {
879        for (place, wanted) in [
880            (Place::Written, ".data"),
881            (Place::ReadOnly, ".rodata"),
882            (Place::RelocReadOnly { local: false }, ".data.rel.ro"),
883            (Place::RelocReadOnly { local: true }, ".data.rel.ro.local"),
884            (Place::Zero, ".bss"),
885            (Place::Named(".init_array".to_owned()), ".init_array"),
886        ] {
887            let bytes = holding(variable("x", place.clone()));
888            let file = object::File::parse(&bytes[..]).expect("a readable object");
889            let section = file.section_by_name(wanted).unwrap_or_else(|| panic!("{place:?}"));
890            assert_eq!(section.size(), 4, "{place:?}");
891            // The zero filled one is as long as it says and carries none of it, which is the
892            // whole reason the section exists.
893            let carried = section.data().expect("the bytes").len();
894            assert_eq!(carried, if place == Place::Zero { 0 } else { 4 }, "{place:?}");
895        }
896    }
897
898    /// What `-fdata-sections` comes down to in an object file: the section a variable would have
899    /// shared, with its own name after it. The names are gcc 16's, checked against it on a Linux
900    /// host, and the part in front of the dot is what a linker script and `--gc-sections` match on.
901    #[test]
902    fn every_variable_gets_a_section_of_its_own_when_that_is_what_was_asked_for() {
903        let sections =
904            Output { sections: Sections { functions: false, data: true }, ..Output::default() };
905        for (place, wanted) in [
906            (Place::Written, ".data.x"),
907            (Place::ReadOnly, ".rodata.x"),
908            (Place::RelocReadOnly { local: false }, ".data.rel.ro.x"),
909            (Place::RelocReadOnly { local: true }, ".data.rel.ro.local.x"),
910            (Place::Zero, ".bss.x"),
911        ] {
912            let data = Data { objects: vec![variable("x", place.clone())] };
913            let bytes = write(&Text::default(), &data, &[], &target(), sections).expect("object");
914            let file = object::File::parse(&bytes[..]).expect("a readable object");
915            assert_eq!(lives_in(&file, "x"), wanted, "{place:?}");
916            let section = file.section_by_name(wanted).expect("the section it named");
917            assert_eq!(section.size(), 4, "{place:?}");
918            // Which page it lands in is what the section it came out of decided, and splitting
919            // must not quietly change it: the zero filled one still carries none of its bytes.
920            let carried = section.data().expect("the bytes").len();
921            assert_eq!(carried, if place == Place::Zero { 0 } else { 4 }, "{place:?}");
922        }
923    }
924
925    /// The two kinds of variable the flag leaves alone. A tentative definition is a request to the
926    /// linker for that much zeroed space rather than an image, so there is no section to split off,
927    /// and one the program named has the answer the source gave, which a flag must not overrule.
928    #[test]
929    fn a_variable_that_has_no_section_of_its_own_to_be_given_is_left_where_it_was() {
930        let sections =
931            Output { sections: Sections { functions: false, data: true }, ..Output::default() };
932        let named = Place::Named(".init_array".to_owned());
933        let objects = vec![variable("m", Place::Merged), variable("n", named)];
934        let bytes =
935            write(&Text::default(), &Data { objects }, &[], &target(), sections).expect("object");
936        let file = object::File::parse(&bytes[..]).expect("a readable object");
937        let m = file.symbols().find(|s| s.name() == Ok("m")).expect("the tentative one");
938        assert!(m.is_common(), "still the linker's to merge and not in a section at all");
939        assert_eq!(lives_in(&file, "n"), ".init_array");
940        assert!(file.section_by_name(".init_array.n").is_none(), "the source already answered");
941    }
942
943    /// A relocation in a variable's image counts from the start of the section it ended up in, the
944    /// same question the split text has to answer and a shorter answer: a variable alone in a
945    /// section starts where the section does.
946    #[test]
947    fn a_relocation_in_an_image_moves_with_the_variable_whose_image_it_is_in() {
948        let sections =
949            Output { sections: Sections { functions: false, data: true }, ..Output::default() };
950        let pointer = Object {
951            bytes: vec![0; 8],
952            size: 8,
953            align: 8,
954            relocs: vec![Reloc {
955                at: 0,
956                symbol: "y".to_owned(),
957                kind: Reference::Address { bytes: 8 },
958                addend: 0,
959            }],
960            ..variable("p", Place::Written)
961        };
962        let objects = vec![variable("first", Place::Written), pointer];
963        let bytes =
964            write(&Text::default(), &Data { objects }, &[], &target(), sections).expect("object");
965        let file = object::File::parse(&bytes[..]).expect("a readable object");
966        let section = file.section_by_name(".data.p").expect("the pointer's own section");
967        let (offset, reloc) = section.relocations().next().expect("one relocation");
968        // Nothing rather than the eight it would be if the variable in front of it were still
969        // counted, which is what a section of its own means.
970        assert_eq!(offset, 0);
971        assert_eq!(reloc.flags(), RelocationFlags::Elf { r_type: elf::R_X86_64_64 });
972    }
973
974    /// Two variables that want `.data.rel.ro.local` end up in one section, not two of one name.
975    ///
976    /// The writer has no name of its own for that section, so it is added by hand, and asking for
977    /// it again makes a second section rather than handing back the first. SQLite has enough const
978    /// tables of function pointers in it to turn that into eighty odd sections in one object, each
979    /// with its own relocation section beside it, which is a pile of section headers describing
980    /// eight bytes apiece.
981    #[test]
982    fn every_variable_that_wants_the_local_relocated_section_shares_one() {
983        let place = Place::RelocReadOnly { local: true };
984        let data =
985            Data { objects: vec![variable("first", place.clone()), variable("second", place)] };
986        let bytes =
987            write(&Text::default(), &data, &[], &target(), Output::default()).expect("an object");
988        let file = object::File::parse(&bytes[..]).expect("a readable object");
989        let named = file.sections().filter(|s| s.name() == Ok(".data.rel.ro.local")).count();
990        assert_eq!(named, 1, "one section holding both, not one each");
991    }
992
993    #[test]
994    fn a_variable_is_a_symbol_that_says_where_it_is_and_how_long_it_is() {
995        let mut data = Data { objects: vec![variable("first", Place::Written)] };
996        data.objects.push(Object { align: 16, ..variable("second", Place::Written) });
997        let bytes =
998            write(&Text::default(), &data, &[], &target(), Output::default()).expect("an object");
999        let file = object::File::parse(&bytes[..]).expect("a readable object");
1000        let second = file.symbols().find(|s| s.name() == Ok("second")).expect("the second one");
1001        assert_eq!(second.kind(), SymbolKind::Data);
1002        assert_eq!(second.size(), 4);
1003        // Sixteen rather than four, because the second one asked for sixteen and the first one
1004        // had already used four. Getting this wrong is a variable at an address it said it would
1005        // never be at, which nothing downstream would notice until an aligned load faulted.
1006        assert_eq!(second.address(), 16);
1007    }
1008
1009    #[test]
1010    fn the_linkage_a_variable_had_is_the_binding_the_symbol_gets() {
1011        for (binding, global, weak) in [
1012            (Binding::Global, true, false),
1013            (Binding::Local, false, false),
1014            (Binding::Weak, true, true),
1015        ] {
1016            let bytes = holding(Object { binding, ..variable("x", Place::Written) });
1017            let file = object::File::parse(&bytes[..]).expect("a readable object");
1018            let x = file.symbols().find(|s| s.name() == Ok("x")).expect("the variable");
1019            assert_eq!(x.is_global(), global, "{binding:?}");
1020            assert_eq!(x.is_weak(), weak, "{binding:?}");
1021        }
1022    }
1023
1024    #[test]
1025    fn a_tentative_definition_asks_the_linker_for_space_rather_than_naming_any() {
1026        let bytes = holding(Object { align: 8, ..variable("x", Place::Merged) });
1027        let file = object::read::elf::ElfFile64::<Endianness>::parse(&bytes[..]).expect("readable");
1028        let x = file.symbols().find(|s| s.name() == Ok("x")).expect("the variable");
1029        assert!(x.is_common(), "the linker merges every definition of this name into one");
1030        assert_eq!(x.size(), 4);
1031        // What a common symbol records where an ordinary one records its address is what it wants
1032        // to be aligned to, because it has no address yet. The reader deliberately answers nothing
1033        // when asked for the address of one, so this is the field itself.
1034        assert_eq!(x.address(), 0);
1035        assert_eq!(x.elf_symbol().st_value(Endianness::Little), 8);
1036    }
1037
1038    #[test]
1039    fn an_address_in_an_image_is_the_address_and_not_a_distance_to_it() {
1040        let object = Object {
1041            bytes: vec![0; 8],
1042            size: 8,
1043            align: 8,
1044            relocs: vec![Reloc {
1045                at: 0,
1046                symbol: "y".to_owned(),
1047                kind: Reference::Address { bytes: 8 },
1048                addend: 16,
1049            }],
1050            ..variable("p", Place::Written)
1051        };
1052        let bytes = holding(object);
1053        let file = object::File::parse(&bytes[..]).expect("a readable object");
1054        let section = file.section_by_name(".data").expect("a data section");
1055        let (offset, reloc) = section.relocations().next().expect("one relocation");
1056        assert_eq!(offset, 0);
1057        assert_eq!(reloc.addend(), 16);
1058        assert_eq!(reloc.flags(), RelocationFlags::Elf { r_type: elf::R_X86_64_64 });
1059        let y = file.symbols().find(|s| s.name() == Ok("y")).expect("what it points at");
1060        assert!(y.is_undefined(), "nothing here defines it and the linker is being asked for it");
1061    }
1062
1063    /// Not a rewording of the case above: what is checked is the arithmetic between the two.
1064    #[test]
1065    fn a_relocation_counts_from_the_start_of_the_section_and_not_of_the_image_it_is_in() {
1066        let mut data = Data { objects: vec![variable("first", Place::Written)] };
1067        data.objects.push(Object {
1068            bytes: vec![0; 16],
1069            size: 16,
1070            align: 8,
1071            relocs: vec![Reloc {
1072                at: 8,
1073                symbol: "y".to_owned(),
1074                kind: Reference::Address { bytes: 8 },
1075                addend: 0,
1076            }],
1077            ..variable("second", Place::Written)
1078        });
1079        let bytes =
1080            write(&Text::default(), &data, &[], &target(), Output::default()).expect("an object");
1081        let file = object::File::parse(&bytes[..]).expect("a readable object");
1082        let section = file.section_by_name(".data").expect("a data section");
1083        let (offset, _) = section.relocations().next().expect("one relocation");
1084        // Eight into the second image, which starts eight in because the first one is four long
1085        // and the second is eight aligned.
1086        assert_eq!(offset, 16);
1087    }
1088
1089    #[test]
1090    fn a_second_name_is_a_second_symbol_at_the_first_one_s_address_and_no_second_image() {
1091        let data = Data {
1092            objects: vec![Object { binding: Binding::Local, ..variable("a", Place::Written) }],
1093        };
1094        let aliases = [Alias {
1095            name: "b".to_owned(),
1096            target: "a".to_owned(),
1097            binding: Binding::Global,
1098            visibility: Visibility::Default,
1099        }];
1100        let bytes = write(&Text::default(), &data, &aliases, &target(), Output::default())
1101            .expect("an object");
1102        let file = object::File::parse(&bytes[..]).expect("a readable object");
1103        let a = file.symbols().find(|s| s.name() == Ok("a")).expect("the variable");
1104        let b = file.symbols().find(|s| s.name() == Ok("b")).expect("the second name");
1105        assert_eq!(b.address(), a.address(), "the same place");
1106        assert_eq!(b.size(), a.size());
1107        assert_eq!(b.section_index(), a.section_index());
1108        // The binding is the one thing the second name does not take from the first, which is
1109        // what `extern int b __attribute__((alias("a")))` on a `static a` asks for.
1110        assert!(a.is_local(), "the target was written `static`");
1111        assert!(b.is_global(), "and the name given to it was not");
1112        // Four bytes of image and not eight, since an alias is a name and not a copy.
1113        assert_eq!(file.section_by_name(".data").expect("a data section").size(), 4);
1114    }
1115
1116    #[test]
1117    fn a_function_can_be_given_a_second_name_the_same_way_a_variable_can() {
1118        let text = calling("puts");
1119        let aliases = [Alias {
1120            name: "g".to_owned(),
1121            target: "f".to_owned(),
1122            binding: Binding::Weak,
1123            visibility: Visibility::Default,
1124        }];
1125        let bytes = write(&text, &Data::default(), &aliases, &target(), Output::default())
1126            .expect("an object");
1127        let file = object::File::parse(&bytes[..]).expect("a readable object");
1128        let f = file.symbols().find(|s| s.name() == Ok("f")).expect("the function");
1129        let g = file.symbols().find(|s| s.name() == Ok("g")).expect("the second name");
1130        assert_eq!(g.address(), f.address());
1131        assert_eq!(g.size(), f.size());
1132        assert_eq!(g.kind(), f.kind(), "a second name for a function is a function");
1133        assert!(g.is_weak(), "so that a program may define the name itself instead");
1134    }
1135
1136    /// The front end is what reports this as a program's mistake, so one arriving here is a bug
1137    /// in this compiler and is said so rather than written as an undefined symbol.
1138    #[test]
1139    fn a_second_name_for_something_this_file_does_not_define_is_refused() {
1140        let aliases = [Alias {
1141            name: "b".to_owned(),
1142            target: "a".to_owned(),
1143            binding: Binding::Global,
1144            visibility: Visibility::Default,
1145        }];
1146        let error =
1147            write(&Text::default(), &Data::default(), &aliases, &target(), Output::default())
1148                .expect_err("nothing to point at");
1149        assert!(matches!(error, Error::Refused { .. }), "{error:?}");
1150    }
1151
1152    #[test]
1153    fn a_platform_this_does_not_write_is_said_so_rather_than_written_as_elf() {
1154        let text = calling("puts");
1155        for triple in [
1156            Triple::new(Arch::Aarch64, Os::Linux, Env::Gnu),
1157            Triple::new(Arch::X86_64, Os::Darwin, Env::Gnu),
1158        ] {
1159            let error =
1160                write(&text, &Data::default(), &[], &TargetInfo::new(triple), Output::default())
1161                    .expect_err("no writer");
1162            assert!(matches!(error, Error::Format { .. }), "{error:?}");
1163        }
1164    }
1165}