Skip to main content

rucc_object/
file.rs

1//! Relocatable objects, in whichever of the formats the target wants.
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, 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//! # One layout and two sets of answers
10//!
11//! Which sections a file has, what goes in each of them, which symbol says where each thing is and
12//! what each relocation is against are the same questions for ELF and for COFF, and they have the
13//! same answers, so they are asked once here. What differs is a short list: the number a relocation
14//! is, the field a visibility goes in, the note saying what the file was built to have checked, and
15//! the marker whose absence makes the stack executable. [`Flavour`] is that list, and the answers
16//! are in [`crate::elf`] and [`crate::coff`] beside each other where they can be read against one
17//! another.
18//!
19//! The alternative was two writers, and the reason against it is what a second copy of a layout
20//! decays into: a fix to one of them is a fix to one platform, and which platform got it is
21//! whichever the person who found the bug was building for.
22//!
23//! # What is not here
24//!
25//! Mach-O. The formats disagree about more than their headers: an Apple symbol carries an
26//! underscore in front of the C name and Mach-O has no way to say how long a function is, wanting
27//! `.subsections_via_symbols` instead. It is written when the target that needs it is.
28//!
29//! Thread-local storage. Reaching a thread-local variable is a different instruction sequence per
30//! model and the back end writes none of them, so a module carrying one is refused before it
31//! reaches here rather than written as an ordinary variable in the wrong section.
32
33use std::collections::{BTreeMap, HashMap, HashSet};
34
35use object::write::{
36    Object as Writer, Relocation, StandardSection, Symbol, SymbolId, SymbolSection,
37};
38use object::{
39    Architecture, BinaryFormat, Endianness, RelocationFlags, SectionFlags, SectionKind,
40    SymbolFlags, SymbolKind, SymbolScope,
41};
42use rucc_target::{ObjectFormat, TargetInfo};
43use rucc_tuple::Arch;
44
45use crate::section::{
46    Alias, Apart, Array, Binding, Data, EXCEPT_TABLE, Info, Object, Output, Place, Property,
47    Reference, Reloc, Sections, Text, Visibility,
48};
49use crate::{coff, elf};
50
51/// Which of the three formats is being written, and therefore which set of answers the questions
52/// this module cannot decide get.
53///
54/// A short list rather than a trait, because the list is short and closed: everything a format has
55/// an opinion about is a call to one of the methods below, so a format is an arm in each of them
56/// and the compiler names every one that was forgotten.
57#[derive(Debug, Clone, Copy, PartialEq, Eq)]
58pub(crate) enum Flavour {
59    /// Linux, the BSDs and the freestanding targets.
60    Elf,
61    /// Windows, under either of its two runtimes.
62    Coff,
63    /// Apple's platforms, which are written only from a file of assembly and only for AArch64 so
64    /// far, so [`Flavour::of`] does not give it and [`crate::assembled`] asks for it by name.
65    MachO,
66}
67
68impl Flavour {
69    /// Which one a target wants, and nothing for the two formats that are not written.
70    pub(crate) fn of(target: &TargetInfo) -> Option<Flavour> {
71        match target.object_format {
72            ObjectFormat::Elf => Some(Flavour::Elf),
73            ObjectFormat::Coff => Some(Flavour::Coff),
74            ObjectFormat::MachO | ObjectFormat::Wasm => None,
75        }
76    }
77
78    /// The format the writer underneath is asked for.
79    pub(crate) fn binary(self) -> BinaryFormat {
80        match self {
81            Flavour::Elf => BinaryFormat::Elf,
82            Flavour::Coff => BinaryFormat::Coff,
83            Flavour::MachO => BinaryFormat::MachO,
84        }
85    }
86
87    /// Which relocation this reference is, or `None` for one this format has none of.
88    ///
89    /// `after` is how many bytes of the instruction come after the four the linker writes over,
90    /// which ELF has already folded into the addend and COFF wants told apart. See [`crate::Reloc`].
91    pub(crate) fn reloc(self, reference: Reference, after: u8) -> Option<RelocationFlags> {
92        match self {
93            Flavour::Elf => elf::r_type(reference).map(|r_type| RelocationFlags::Elf { r_type }),
94            Flavour::Coff => coff::reloc(reference, after),
95            Flavour::MachO => crate::macho::reloc(reference, 0).ok(),
96        }
97    }
98
99    /// Say how far a name reaches beyond what its scope already said.
100    ///
101    /// Nothing on COFF, where a symbol has nowhere to keep it. A file built with
102    /// `-fvisibility=hidden` for Windows is a file where that flag changed nothing, which is what
103    /// gcc does there as well.
104    pub(crate) fn see(
105        self,
106        obj: &mut Writer<'_>,
107        id: SymbolId,
108        binding: Binding,
109        visibility: Visibility,
110    ) {
111        match self {
112            Flavour::Elf => elf::see(obj, id, binding, visibility),
113            Flavour::Coff => {}
114            // Hidden is the one visibility Mach-O has a bit for, which keeps a name out of the
115            // image's exports and lets every object in the link see it. Protected has none.
116            Flavour::MachO => {
117                if binding != Binding::Local && visibility == Visibility::Hidden {
118                    obj.symbol_mut(id).scope = SymbolScope::Linkage;
119                }
120            }
121        }
122    }
123
124    /// The section a variable the loader writes into before anything reads it goes in, when the
125    /// program asked for the half of it the linker keeps apart, or nothing for a format that has no
126    /// such half and puts one in ordinary read only data with the rest.
127    fn rel_ro_local(self) -> Option<&'static str> {
128        match self {
129            Flavour::Elf => elf::REL_RO_LOCAL,
130            Flavour::Coff => coff::REL_RO_LOCAL,
131            Flavour::MachO => None,
132        }
133    }
134
135    /// The type and flags a section of function addresses the startup code calls has, where the
136    /// format has something to say about it.
137    ///
138    /// Nothing on COFF, where such a section is refused by [`beyond`] before it reaches here rather
139    /// than written under a name nothing on that platform gathers.
140    fn gathered(self, array: Array) -> Option<SectionFlags> {
141        match self {
142            Flavour::Elf => Some(elf::gathered(array)),
143            Flavour::Coff | Flavour::MachO => None,
144        }
145    }
146
147    /// The header fields a file of assembly stated about one of its own sections, where the format
148    /// has fields to put them in.
149    ///
150    /// ELF has one for each of the letters, so what the source wrote is written down as it stands
151    /// and the section kind handed to the writer alongside is only a summary of it. COFF has no
152    /// field the letters map onto one for one, and the characteristics the writer works out from
153    /// that kind are the ones every other Windows assembler produces, so there is nothing to add and
154    /// saying so is [`None`] rather than a word built out of guesses.
155    pub(crate) fn stated(self, shape: crate::source::Shape) -> Option<SectionFlags> {
156        match self {
157            Flavour::Elf => {
158                Some(SectionFlags::Elf { sh_type: shape.sh_type(), sh_flags: shape.sh_flags() })
159            }
160            Flavour::Coff => None,
161            Flavour::MachO => Some(SectionFlags::MachO {
162                flags: object::macho::SectionFlags(shape.mach),
163                reserved2: 0,
164            }),
165        }
166    }
167
168    /// What kind of symbol a name out of a file of assembly is, given what `.type` said about it and
169    /// how far it reaches.
170    ///
171    /// The binding is a parameter because on COFF the two are not separable. ELF keeps the type and
172    /// the binding in different halves of a byte, so a name that nothing stated a type for is
173    /// `STT_NOTYPE` whether it is local or global, and that is what gas writes for a plain label.
174    /// COFF has no type field of that sort: what the writer underneath calls a label is storage
175    /// class `LABEL`, which is a name inside this file and nothing a linker will resolve against, so
176    /// a `.globl` with no `.type` under it would quietly stop being offered. The kind with no
177    /// function type on it and an external storage class is the data one, which is what gas for this
178    /// platform writes for the same input, so that is what an untyped global becomes here.
179    ///
180    /// Mach-O keeps no type at all and the writer underneath has no label there, so a function is
181    /// text and everything else is data. A thread-local is data as well, because the kind the
182    /// writer has for one makes a descriptor for it and the listing has already written that.
183    pub(crate) fn sort(self, sort: crate::source::Sort, binding: Binding) -> SymbolKind {
184        if self == Flavour::MachO {
185            return match sort {
186                crate::source::Sort::Func => SymbolKind::Text,
187                crate::source::Sort::File => SymbolKind::File,
188                _ => SymbolKind::Data,
189            };
190        }
191        match sort {
192            crate::source::Sort::Func => SymbolKind::Text,
193            crate::source::Sort::Object => SymbolKind::Data,
194            crate::source::Sort::Thread => SymbolKind::Tls,
195            crate::source::Sort::File => SymbolKind::File,
196            crate::source::Sort::Untyped => match (self, binding) {
197                (Flavour::Coff, Binding::Global | Binding::Weak) => SymbolKind::Data,
198                _ => SymbolKind::Label,
199            },
200        }
201    }
202
203    /// The marker a linker looks for in every input, where there is one.
204    pub(crate) fn marker(self, obj: &mut Writer<'_>) {
205        match self {
206            Flavour::Elf => elf::marker(obj),
207            Flavour::Coff => coff::marker(obj),
208            Flavour::MachO => {}
209        }
210    }
211
212    /// What the file says it was built to have checked, where the format has a way to say it.
213    ///
214    /// ELF writes a note the linker keeps only the agreed part of. A PE image says the same thing in
215    /// the header of the finished image rather than in its inputs, so an object carries nothing and
216    /// the instructions the flag asked for are in the text either way.
217    fn property(self, obj: &mut Writer<'_>, property: Property) {
218        if !property.any() {
219            return;
220        }
221        match self {
222            Flavour::Elf => {
223                let note = obj.section_id(StandardSection::GnuProperty);
224                obj.append_section_data(note, &elf::record(property), 8);
225            }
226            Flavour::Coff | Flavour::MachO => {}
227        }
228    }
229
230    /// Where the unwind table goes: the section the records are in and what it is aligned to, and
231    /// the second section holding what those records point at, on the format that keeps the two
232    /// apart.
233    fn tables(self) -> ((&'static str, u64), Option<(&'static str, u64)>) {
234        match self {
235            Flavour::Elf => (elf::FRAMES, None),
236            Flavour::Coff => (coff::FUNCTIONS, Some(coff::CODES)),
237            Flavour::MachO => (("__TEXT,__eh_frame", 8), None),
238        }
239    }
240
241    /// Anything that has to be written into the finished bytes rather than said to the writer.
242    fn finish(self, bytes: &mut [u8], ordered: &[String]) {
243        match self {
244            Flavour::Elf => elf::link(bytes, ordered),
245            Flavour::Coff | Flavour::MachO => {
246                debug_assert!(ordered.is_empty(), "a record this format cannot write");
247            }
248        }
249    }
250}
251
252/// Why an object file could not be written.
253#[derive(Debug, Clone, PartialEq, Eq)]
254pub enum Error {
255    /// A machine or a platform this does not write objects for.
256    Format {
257        /// The triple that was asked for.
258        triple: String,
259    },
260    /// The writer refused something it was given, which is a bug here rather than in a program.
261    Refused {
262        /// What it said, already formatted.
263        why: String,
264    },
265}
266
267impl std::fmt::Display for Error {
268    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
269        match self {
270            Error::Format { triple } => {
271                write!(f, "there is no object writer for {triple} in this compiler yet")
272            }
273            Error::Refused { why } => {
274                write!(f, "the object writer refused what it was given: {why}")
275            }
276        }
277    }
278}
279
280impl std::error::Error for Error {}
281
282/// One text section and the variables beside it, as a relocatable object in the target's format.
283///
284/// `info` is the debug sections, already encoded, and is empty in a build that asked for none.
285/// What it holds is bytes and relocations for the same reason [`Text::unwind`] is bytes: the
286/// format's answer is the producer's to give and what is left here is where the sections go.
287///
288/// # Errors
289///
290/// [`Error::Format`] for a machine or a platform this does not write, and [`Error::Refused`] for
291/// anything the writer underneath objected to, which would be a bug here. An alias whose target
292/// this file does not define is refused the same way, since the front end is what reports that as
293/// a program's mistake and one reaching here means it did not. So is anything the target's format
294/// has no way to write, which for COFF is a thread-local variable, a reference through a table the
295/// platform does not have, a record of where a patcher's room is and a section the startup code is
296/// expected to gather. See [`Error`].
297pub fn write(
298    text: &Text,
299    data: &Data,
300    aliases: &[Alias],
301    target: &TargetInfo,
302    output: Output,
303    info: &Info,
304) -> Result<Vec<u8>, Error> {
305    let Output { sections, property } = output;
306    let flavour = Flavour::of(target).filter(|_| target.tuple.arch() == Arch::X86_64);
307    let Some(flavour) = flavour else {
308        return Err(Error::Format { triple: target.tuple.to_string() });
309    };
310    if flavour == Flavour::Coff {
311        beyond(text, data, info)?;
312    }
313    let mut obj = Writer::new(flavour.binary(), Architecture::X86_64, Endianness::Little);
314    // The one that holds every function when they are not being split up. Asked for even when it
315    // will stay empty, because it is the section the writer underneath starts a file with anyway
316    // and gcc writes an empty `.text` under `-ffunction-sections` too.
317    let whole = obj.section_id(StandardSection::Text);
318    if !sections.functions {
319        obj.append_section_data(whole, &text.bytes, u64::from(text.align));
320    }
321
322    // Every function defined here, then every variable, then every name either of them wanted that
323    // is not. A name is looked up rather than added twice, because two symbols with one name is
324    // not a file a linker accepts.
325    let mut symbols = BTreeMap::new();
326    // Where each function ended up, in the order they were written, so that a relocation inside
327    // one goes into the section that one is in and one that points at the start of one can be
328    // written against that section. The same list as `text.funcs` and in the same order, so the
329    // two are walked together below.
330    let mut split: Vec<(object::write::SectionId, u64)> = Vec::with_capacity(text.funcs.len());
331    // Which text section each record of where a patcher's room is belongs to, in the order the
332    // records were added, which is the order their headers come out in. See `link`.
333    let mut ordered: Vec<String> = Vec::new();
334    for func in &text.funcs {
335        // A section of its own, holding this function's bytes and nothing else, so the linker can
336        // drop it when nothing reaches it. The name is what gcc writes, and the leading `.text.`
337        // is not decoration: `--gc-sections` and the linker scripts that place code both match on
338        // it, and a section called something else would be placed by the catch all rule.
339        //
340        // The room a patcher was promised in front of the label goes in it too. Those bytes are
341        // the function's, they are just not under its name: the symbol is where the label was and
342        // the room is what came before, so a section holding one without the other would be a
343        // section a linker could place with the room missing.
344        let ahead = func.patch.map_or(0, |patch| patch.before);
345        let (section, at) = if sections.functions {
346            let name = format!(".text.{}", func.name).into_bytes();
347            let id = obj.add_section(Vec::new(), name, SectionKind::Text);
348            let bytes = &text.bytes[func.start - ahead..func.start + func.len];
349            obj.append_section_data(id, bytes, u64::from(func.align.max(1)));
350            (id, ahead as u64)
351        } else {
352            (whole, func.start as u64)
353        };
354        // Where the room is, in a section of its own that says nothing else. What reads it is a
355        // tracer patching every function in an image at once, and what it needs is every address
356        // in one place: a stripped kernel has no symbol table to walk instead, which is the whole
357        // reason the list is written rather than worked out later.
358        //
359        // The address is a relocation rather than a number, because a function is at a fixed
360        // offset in its own section and where that section lands is the linker's answer. It is
361        // written against the section rather than against the function's own name so that it still
362        // points at the room when the room is in front of the name.
363        //
364        // One section per function even when they all point at the same text, which is what gas
365        // produces and what lets a linker throw the record away with the function. `SHF_LINK_ORDER`
366        // is what ties the two together and it needs a section index the writer underneath does not
367        // set, so `link` fills it in afterwards. See `link`.
368        if let Some(patch) = func.patch {
369            let base = if sections.functions { func.start - ahead } else { 0 };
370            let name = elf::PATCHABLE.as_bytes().to_vec();
371            let id = obj.add_section(Vec::new(), name, SectionKind::Data);
372            obj.section_mut(id).flags = elf::ordered();
373            obj.append_section_data(id, &[0; 8], 8);
374            let symbol = obj.section_symbol(section);
375            let flags = flavour.reloc(Reference::Address { bytes: 8 }, 0).ok_or_else(|| {
376                Error::Refused { why: "no relocation holds an address here".to_owned() }
377            })?;
378            obj.add_relocation(
379                id,
380                Relocation { offset: 0, symbol, addend: (patch.at - base) as i64, flags },
381            )
382            .map_err(|why| Error::Refused { why: why.to_string() })?;
383            ordered.push(if sections.functions {
384                format!(".text.{}", func.name)
385            } else {
386                ".text".to_owned()
387            });
388        }
389        let id = obj.add_symbol(Symbol {
390            name: func.name.clone().into_bytes(),
391            value: at,
392            size: func.len as u64,
393            kind: SymbolKind::Text,
394            scope: scope_of(func.binding),
395            weak: func.binding == Binding::Weak,
396            section: SymbolSection::Section(section),
397            flags: SymbolFlags::None,
398        });
399        flavour.see(&mut obj, id, func.binding, func.visibility);
400        symbols.insert(func.name.clone(), id);
401        split.push((section, at));
402    }
403
404    // The places inside a function that have names of their own, which is where a label whose
405    // address an image holds is. After the functions, because the section one goes in is the
406    // section of the function it is inside and that is what the walk above worked out.
407    for label in &text.labels {
408        let after = text.funcs.partition_point(|func| func.start <= label.at);
409        let Some(index) = after.checked_sub(1) else {
410            let why = format!("'{}' is at {} and in front of every function", label.name, label.at);
411            return Err(Error::Refused { why });
412        };
413        let func = &text.funcs[index];
414        let (section, at) = if sections.functions {
415            // From the start of the section rather than from the symbol, which is the same
416            // correction a relocation inside a function gets below.
417            let base = func.start - func.patch.map_or(0, |patch| patch.before);
418            (split[index].0, (label.at - base) as u64)
419        } else {
420            (whole, label.at as u64)
421        };
422        let id = obj.add_symbol(Symbol {
423            name: label.name.clone().into_bytes(),
424            value: at,
425            // A label has no length. What is at it is the rest of the function, and a size here
426            // would be a claim that the bytes after it are a thing of their own.
427            size: 0,
428            kind: SymbolKind::Label,
429            // Never offered to another file. The name is one the compiler minted and what it
430            // points at is the middle of a function, so the only thing that resolves against it
431            // is the image in this same file that asked for it.
432            scope: SymbolScope::Compilation,
433            weak: false,
434            section: SymbolSection::Section(section),
435            flags: SymbolFlags::None,
436        });
437        symbols.insert(label.name.clone(), id);
438    }
439
440    // Where each variable's image landed in the section it went into, kept because a relocation in
441    // an image counts from the start of the image and one in a file counts from the start of the
442    // section. A variable that is not in a section has no entry, since nothing in a merged one can
443    // hold a relocation: the linker is being asked for zeroed space rather than for an image.
444    let mut placed = Vec::with_capacity(data.objects.len());
445    // The sections the writer has no name of its own for, remembered by name so that every variable
446    // that wants one lands in the same one. The rest come back from `section_id`, which already
447    // answers with the section it made the first time it was asked.
448    let mut named = HashMap::new();
449    for object in &data.objects {
450        let (section, offset) = put(&mut obj, object, &mut named, sections, flavour);
451        let id = obj.add_symbol(Symbol {
452            name: object.name.clone().into_bytes(),
453            // A common symbol says what it wants rather than where it is, and what it wants is
454            // recorded where an ordinary symbol records its address.
455            value: if object.place == Place::Merged { object.align } else { offset },
456            size: object.size,
457            // A thread-local variable is a different kind of symbol rather than a symbol in a
458            // different section, and it has to be both: the kind is what a linker checks a
459            // relocation against, so a `R_X86_64_PC32` aimed at one is refused rather than
460            // resolved to an address that would have been one thread's and is nobody's.
461            kind: match object.place {
462                Place::Thread { .. } => SymbolKind::Tls,
463                _ => SymbolKind::Data,
464            },
465            scope: scope_of(object.binding),
466            weak: object.binding == Binding::Weak,
467            section,
468            flags: SymbolFlags::None,
469        });
470        flavour.see(&mut obj, id, object.binding, object.visibility);
471        symbols.insert(object.name.clone(), id);
472        placed.push((section.id(), offset));
473    }
474
475    // The jump tables, which the code reaches by name and which reach the code in turn. Placed
476    // before any relocation of the text is added, since the instruction that reads one names it.
477    let tables = tables(&mut obj, text, &split, &mut named, sections, flavour)?;
478
479    // The distances between two labels, written into the images just placed. Both labels were
480    // added above with the section they are in and where in it, so the distance is the one value
481    // less the other, and it is a number only when the section is the same one.
482    for apart in &data.apart {
483        let (Some(section), offset) = placed[apart.object] else { continue };
484        let value = distance(&obj, &symbols, apart)?;
485        let bytes = usize::from(apart.bytes);
486        let at = usize::try_from(offset).map_err(|why| Error::Refused { why: why.to_string() })?;
487        let at = at + apart.at;
488        let image = obj.section_mut(section).data_mut();
489        image[at..at + bytes].copy_from_slice(&value.to_le_bytes()[..bytes]);
490    }
491
492    // A second name for something already added, which is where the alias's own binding is the
493    // only thing it does not take from what it points at: the target of one may be a `static` and
494    // the alias of it may not be. Before the loop below rather than after it, because a reference
495    // to the new name is a reference to something this file defines and would otherwise be added
496    // as a name this file wants from somewhere else.
497    for alias in aliases {
498        let Some(&id) = symbols.get(&alias.target) else {
499            let why =
500                format!("'{}' is aliased to '{}', which is not here", alias.name, alias.target);
501            return Err(Error::Refused { why });
502        };
503        let (value, size) = (obj.symbol(id).value, obj.symbol(id).size);
504        let (kind, section) = (obj.symbol(id).kind, obj.symbol(id).section);
505        let id = obj.add_symbol(Symbol {
506            name: alias.name.clone().into_bytes(),
507            value,
508            size,
509            kind,
510            scope: scope_of(alias.binding),
511            weak: alias.binding == Binding::Weak,
512            section,
513            flags: SymbolFlags::None,
514        });
515        flavour.see(&mut obj, id, alias.binding, alias.visibility);
516        symbols.insert(alias.name.clone(), id);
517    }
518
519    // Not the unwind table's, which name functions this file defines and are written against the
520    // section rather than against the name. A record for anything else is refused below, so a name
521    // added here for one would be a name nothing goes on to use.
522    // The names a declaration wrote `weak` on, which the link is allowed to leave undefined and
523    // whose references then read a zero address. The listing writes a `.weak` for each of the same
524    // names, so the two paths put the same entries in whether or not anything refers to one.
525    let weak: HashSet<&str> = data.weak.iter().map(String::as_str).collect();
526    let relocs = || text.relocs.iter().chain(data.objects.iter().flat_map(|o| &o.relocs));
527    // The names something here reaches through the thread pointer, which is the one thing about an
528    // undefined name this file does know. A reference to a thread-local variable is a different kind
529    // of reference from a reference to an ordinary one and the code that makes it is already
530    // different, so the file has been told, and ELF wants the symbol to say so as well.
531    let thread: HashSet<&str> = relocs()
532        .filter(|reloc| reloc.kind == Reference::Thread)
533        .map(|reloc| reloc.symbol.as_str())
534        .collect();
535    let wanted: Vec<&String> =
536        relocs().map(|reloc| &reloc.symbol).chain(data.weak.iter()).collect();
537    for name in wanted {
538        if symbols.contains_key(name) || tables.contains_key(name) {
539            continue;
540        }
541        let id = obj.add_symbol(Symbol {
542            name: name.clone().into_bytes(),
543            value: 0,
544            size: 0,
545            // What kind of thing an undefined name is is not known here and does not have to be:
546            // a linker resolves an undefined symbol by its name, and the type of one that is not
547            // defined anywhere in this file is nothing this file can say. A thread-local one is the
548            // exception, and the linker makes it one. A reference to a thread-local variable is
549            // satisfied by an offset into a block rather than by an address, so the linker has to
550            // know which of the two it is being asked for before it has found the definition, and it
551            // refuses a link where one file says `STT_TLS` and another does not rather than picking
552            // one. That is tamnd/rucc#1461: libmpfr writes `__gmpfr_flags` in one file and reads it
553            // in a hundred others, and `ld` stopped at the first reader with a mismatch.
554            kind: if thread.contains(name.as_str()) {
555                SymbolKind::Tls
556            } else {
557                SymbolKind::Unknown
558            },
559            scope: SymbolScope::Dynamic,
560            weak: weak.contains(name.as_str()),
561            section: SymbolSection::Undefined,
562            flags: SymbolFlags::None,
563        });
564        symbols.insert(name.clone(), id);
565    }
566
567    for reloc in &text.relocs {
568        // Which function's bytes this one is in, which is the question only the split path has to
569        // ask: when there is one text section every offset in it is already the offset in it.
570        // Every relocation is inside some function, since the padding between two of them is
571        // instructions that do nothing and holds nothing a linker fills in.
572        let (section, at) = if sections.functions {
573            let after = text.funcs.partition_point(|func| func.start <= reloc.at);
574            let Some(func) = after.checked_sub(1).map(|i| &text.funcs[i]) else {
575                let why = format!("a relocation at {} is in front of every function", reloc.at);
576                return Err(Error::Refused { why });
577            };
578            // From the start of the section rather than from the symbol, and the two are not the
579            // same byte in a function with room in front of its label.
580            let base = func.start - func.patch.map_or(0, |patch| patch.before);
581            (split[after - 1].0, (reloc.at - base) as u64)
582        } else {
583            (whole, reloc.at as u64)
584        };
585        // The address of a jump table, which is against the section the table is in and not a
586        // name of its own, the way gas writes a reference to a `.L` label: such a name is not
587        // kept in the symbol table, so what the linker is told is the section and how far in.
588        if let Some(&(table, offset)) = tables.get(&reloc.symbol) {
589            let flags = flavour.reloc(reloc.kind, reloc.after).ok_or_else(|| Error::Refused {
590                why: format!("no relocation is {:?}", reloc.kind),
591            })?;
592            let symbol = obj.section_symbol(table);
593            let addend = reloc.addend + offset as i64;
594            obj.add_relocation(section, Relocation { offset: at, symbol, addend, flags })
595                .map_err(|why| Error::Refused { why: why.to_string() })?;
596            continue;
597        }
598        add(&mut obj, section, at, reloc, &symbols, flavour)?;
599    }
600
601    // The unwind table, if there is one. Its own section rather than part of the text, because it
602    // is read rather than run: the loader maps it and the linker gathers every input's into one
603    // table and builds the index the unwinder searches.
604    if !text.unwind.bytes.is_empty() {
605        let ((name, align), second) = flavour.tables();
606        let frames = obj.add_section(Vec::new(), name.into(), SectionKind::ReadOnlyData);
607        obj.append_section_data(frames, &text.unwind.bytes, align);
608        // What the rows point at, on the format that keeps the descriptions in a section of their
609        // own, and a name for each of them, because a row reaches one through a relocation and a
610        // relocation names a symbol. The names are never offered to another file: what they point
611        // at is one function's prologue, described for the runtime of this program and nothing else.
612        let mut described = HashMap::new();
613        if !text.unwind.info.is_empty() {
614            let Some((name, align)) = second else {
615                let why = "an unwind table here is one section and it was given two".to_owned();
616                return Err(Error::Refused { why });
617            };
618            let codes = obj.add_section(Vec::new(), name.into(), SectionKind::ReadOnlyData);
619            obj.append_section_data(codes, &text.unwind.info, align);
620            for label in &text.unwind.labels {
621                let id = obj.add_symbol(Symbol {
622                    name: label.name.clone().into_bytes(),
623                    value: label.at as u64,
624                    size: 0,
625                    kind: SymbolKind::Label,
626                    scope: SymbolScope::Compilation,
627                    weak: false,
628                    section: SymbolSection::Section(codes),
629                    flags: SymbolFlags::None,
630                });
631                described.insert(label.name.clone(), id);
632            }
633        }
634        // The call site tables of the functions with a landing pad, which a record reaches through
635        // the section's own symbol and the table's offset in it, the same way gcc's records do.
636        // The personality routine's pointer is an ordinary data symbol of this file and is looked
637        // up with the rest below.
638        if !text.unwind.except.is_empty() {
639            let except =
640                obj.add_section(Vec::new(), EXCEPT_TABLE.into(), SectionKind::ReadOnlyData);
641            obj.append_section_data(except, &text.unwind.except, 4);
642            described.insert(EXCEPT_TABLE.to_owned(), obj.section_symbol(except));
643        }
644        for reloc in &text.unwind.relocs {
645            let found = described.get(&reloc.symbol).or_else(|| {
646                // Only a variable this file defines. A function is reached through its section
647                // below for the reasons given there, and a name defined somewhere else is refused
648                // there as well.
649                let ours = data.objects.iter().any(|object| object.name == reloc.symbol);
650                if ours { symbols.get(&reloc.symbol) } else { None }
651            });
652            let (symbol, addend) = match found {
653                // A description in the section above, reached by its own name and needing no
654                // correction, since the name is at the description rather than at the front of the
655                // section it is in.
656                Some(&id) => (id, reloc.addend),
657                // A function, and against the section it is in rather than against its own name,
658                // which is the same reason the record of a patcher's room is written that way and
659                // one more besides. The section is the only one of the two that is settled here: a
660                // global name is answered at load time by whichever object defines it first, so a
661                // distance measured to one is not a distance the linker can work out, and it says
662                // so and stops. The effect was that nothing this compiler wrote could go into a
663                // shared library at all, because every function has a record and every record
664                // pointed at a name.
665                //
666                // A function defined elsewhere has no record here, so the lookup failing means the
667                // record is for something that is not a function in this file, and that is a bug
668                // rather than a shape to handle: the writer says what it was given rather than
669                // guessing.
670                None => {
671                    let found = text.funcs.iter().position(|func| func.name == reloc.symbol);
672                    let Some((section, at)) = found.map(|i| split[i]) else {
673                        let why = format!(
674                            "'{}' has an unwind record and is not a function here",
675                            reloc.symbol
676                        );
677                        return Err(Error::Refused { why });
678                    };
679                    // Where the function starts inside its section, since the section symbol is
680                    // where the section starts and the two are the same byte only for the first
681                    // function in one.
682                    (obj.section_symbol(section), reloc.addend + at as i64)
683                }
684            };
685            let flags = flavour.reloc(reloc.kind, reloc.after).ok_or_else(|| Error::Refused {
686                why: format!("no relocation is {:?}", reloc.kind),
687            })?;
688            let record = Relocation { offset: reloc.at as u64, symbol, addend, flags };
689            obj.add_relocation(frames, record)
690                .map_err(|why| Error::Refused { why: why.to_string() })?;
691        }
692    }
693    // The debug information, if the build asked for any. One section per chunk under the name
694    // DWARF gives it, and none of them allocated: the loader does not map a debug section and
695    // nothing at run time reads one, which is what tells this apart from the unwind table, whose
696    // whole point is that a program walking its own stack can reach it.
697    //
698    // Every section is added before any relocation is, because a relocation in one of them names
699    // another as often as it names a function, and a name is resolved against the sections the
700    // file already has.
701    let mut named = HashMap::new();
702    for chunk in &info.chunks {
703        let id = obj.add_section(Vec::new(), chunk.name.clone().into_bytes(), SectionKind::Debug);
704        obj.append_section_data(id, &chunk.bytes, 1);
705        named.insert(chunk.name.as_str(), id);
706    }
707    for chunk in &info.chunks {
708        let section = named[chunk.name.as_str()];
709        for reloc in &chunk.relocs {
710            let (symbol, addend) = match named.get(reloc.symbol.as_str()) {
711                // Another debug section, reached by its own name. The distance is from the front
712                // of that section, which is what the section symbol is, so the addend stands.
713                Some(&id) => (obj.section_symbol(id), reloc.addend),
714                // A function, and against the section it is in rather than against its own name,
715                // for the reason the unwind table's records are written that way: a global name is
716                // answered at load time by whichever object defines it first, and a distance to
717                // one is not a distance a linker can work out.
718                None => match text.funcs.iter().position(|func| func.name == reloc.symbol) {
719                    Some(which) => {
720                        let (section, at) = split[which];
721                        (obj.section_symbol(section), reloc.addend + at as i64)
722                    }
723                    // Or a variable this file defines, which a `DW_TAG_variable` asks for the
724                    // address of. Against its section for the reason a function is, where it has
725                    // one. A variable the linker is being asked for zeroed space for has no
726                    // section to count from and nothing but its own name to ask by, which is the
727                    // one case here where the name goes in the relocation.
728                    None => {
729                        let found = data.objects.iter().position(|had| had.name == reloc.symbol);
730                        let Some(which) = found else {
731                            let why = format!(
732                                "'{}' is named by the debug information and is not defined here",
733                                reloc.symbol
734                            );
735                            return Err(Error::Refused { why });
736                        };
737                        match placed[which] {
738                            (Some(section), at) => {
739                                (obj.section_symbol(section), reloc.addend + at as i64)
740                            }
741                            (None, _) => (symbols[&reloc.symbol], reloc.addend),
742                        }
743                    }
744                },
745            };
746            let flags = flavour.reloc(reloc.kind, reloc.after).ok_or_else(|| Error::Refused {
747                why: format!("no relocation is {:?}", reloc.kind),
748            })?;
749            let record = Relocation { offset: reloc.at as u64, symbol, addend, flags };
750            obj.add_relocation(section, record)
751                .map_err(|why| Error::Refused { why: why.to_string() })?;
752        }
753    }
754    for (object, &(section, offset)) in data.objects.iter().zip(&placed) {
755        let Some(section) = section else { continue };
756        for reloc in &object.relocs {
757            add(&mut obj, section, offset + reloc.at as u64, reloc, &symbols, flavour)?;
758        }
759    }
760
761    // What the file was built to have checked, when it was built to have anything checked. Left
762    // out otherwise rather than written as a zero, because a linker treats a missing note and a
763    // note with no bits in it the same way and gcc writes nothing.
764    flavour.property(&mut obj, property);
765
766    // Written rather than left out, because a linker that does not find it in every input marks
767    // the stack executable, on the format that has one.
768    flavour.marker(&mut obj);
769
770    let mut bytes = obj.write().map_err(|why| Error::Refused { why: why.to_string() })?;
771    flavour.finish(&mut bytes, &ordered);
772    Ok(bytes)
773}
774
775/// How far one label is from another, from the symbols [`write()`] added for them.
776///
777/// # Errors
778///
779/// [`Error::Refused`] for a label that is not here, for two that are in different sections, and
780/// for a distance too far for the width it is written in.
781fn distance(
782    obj: &Writer<'_>,
783    symbols: &BTreeMap<String, SymbolId>,
784    apart: &Apart,
785) -> Result<i64, Error> {
786    let find = |name: &str| match symbols.get(name) {
787        Some(&id) => Ok(obj.symbol(id)),
788        None => Err(Error::Refused { why: format!("'{name}' is measured from and is not here") }),
789    };
790    let (to, from) = (find(&apart.to)?, find(&apart.from)?);
791    if to.section != from.section {
792        let why = format!("'{}' and '{}' are in different sections", apart.to, apart.from);
793        return Err(Error::Refused { why });
794    }
795    let value = (to.value as i64).wrapping_sub(from.value as i64).wrapping_add(apart.addend);
796    let bits = u32::from(apart.bytes) * 8;
797    if bits < 64 && (value >> (bits - 1)) != 0 && (value >> (bits - 1)) != -1 {
798        let why = format!("'{}' is too far from '{}' for {} bytes", apart.to, apart.from, bits / 8);
799        return Err(Error::Refused { why });
800    }
801    Ok(value)
802}
803
804/// Everything in this module the target's format has no way to write, refused by name.
805///
806/// Each of these is something ELF has and COFF does not, and each would otherwise be written as the
807/// nearest thing rather than refused, which is worse: a thread-local variable written as an ordinary
808/// one is a program where every thread shares what the source said each would have its own copy of,
809/// and a constructor list under a name the Windows runtime does not gather is a program whose
810/// constructors never run. A message naming the feature is what the caller turns into a diagnostic,
811/// and the front end refusing first is what stops one ever being seen.
812///
813/// # Errors
814///
815/// [`Error::Refused`], naming the one it found first.
816fn beyond(text: &Text, data: &Data, info: &Info) -> Result<(), Error> {
817    let why = |why: String| Err(Error::Refused { why });
818    if !info.chunks.is_empty() {
819        return why("debug information here goes in sections this writer does not name".to_owned());
820    }
821    if text.funcs.iter().any(|func| func.patch.is_some()) {
822        return why("a record of where a patcher's room is has no section flags here".to_owned());
823    }
824    for reloc in text.relocs.iter().chain(data.objects.iter().flat_map(|object| &object.relocs)) {
825        if matches!(
826            reloc.kind,
827            Reference::Got | Reference::GotBare | Reference::GotKept | Reference::Thread
828        ) {
829            return why(format!("nothing reaches '{}' through a table here", reloc.symbol));
830        }
831    }
832    for object in &data.objects {
833        if matches!(object.place, Place::Thread { .. }) {
834            return why(format!("'{}' is thread-local and this format is not", object.name));
835        }
836        let Place::Named(name) = &object.place else { continue };
837        if Array::of(name).is_some() {
838            return why(format!("'{name}' is not a list the startup code here gathers"));
839        }
840    }
841    Ok(())
842}
843
844/// Every name a linker can find in the object [`write()`] would write from the same input.
845///
846/// What asks for this is the archive writer. A static link resolves through the symbol index, so an
847/// index entry has to name a symbol the member really defines: an entry for a name that is not in
848/// the member is an archive the linker searches, pulls the member out of, and then still reports
849/// the name undefined. So the list comes from the writer rather than from the caller, because the
850/// writer is the only thing that knows what it wrote.
851///
852/// The names are as the C program spelled them, with nothing in front of them, which is what both
853/// the formats this writes have on this machine. Mach-O puts an underscore there and so does COFF on
854/// a 32-bit machine, and when either of those is written this is the function that has to say so,
855/// which is why it asks about the target it otherwise would not have to.
856///
857/// Order is the functions, then the variables, then the aliases, each in the order the module held
858/// them, which is the order [`write()`] adds the symbols in. A `static` is left out: it is a name the
859/// link has already finished with by the time an archive is searched, and an index entry for one
860/// would offer the linker a definition it is not allowed to use.
861///
862/// # Errors
863///
864/// [`Error::Format`] for a machine or a platform this does not write, which is the same refusal
865/// [`write()`] gives and is here for the same reason: a list of undecorated names for a format whose
866/// symbols carry an underscore is worse than no list at all.
867pub fn defines(
868    text: &Text,
869    data: &Data,
870    aliases: &[Alias],
871    target: &TargetInfo,
872) -> Result<Vec<String>, Error> {
873    if target.tuple.arch() != Arch::X86_64 || Flavour::of(target).is_none() {
874        return Err(Error::Format { triple: target.tuple.to_string() });
875    }
876    let names = text
877        .funcs
878        .iter()
879        .filter(|func| func.binding != Binding::Local)
880        .map(|func| func.name.clone())
881        .chain(
882            data.objects
883                .iter()
884                .filter(|object| object.binding != Binding::Local)
885                .map(|object| object.name.clone()),
886        )
887        .chain(
888            aliases
889                .iter()
890                .filter(|alias| alias.binding != Binding::Local)
891                .map(|alias| alias.name.clone()),
892        )
893        .collect();
894    Ok(names)
895}
896
897/// One variable's image into the section it belongs in, and where in that section it landed.
898///
899/// A zero filled variable takes as many bytes of the file as it is long on the way in and none on
900/// the way out, which is the whole point of the section it goes in. A merged one goes in no section
901/// at all: the linker is being asked for that much zeroed space under that name, and where it ends
902/// up is the linker's answer rather than this file's.
903fn put(
904    obj: &mut Writer<'_>,
905    object: &Object,
906    named: &mut HashMap<String, object::write::SectionId>,
907    sections: Sections,
908    flavour: Flavour,
909) -> (SymbolSection, u64) {
910    // A section of its own, named after the variable and after the section it would have gone in,
911    // which is what `-fdata-sections` asks for. A merged variable has no section to split and a
912    // named one was named by the program, so both are left where they are: the first is a request
913    // to the linker rather than an image, and the second would otherwise have the flag silently
914    // overrule what the source said.
915    if sections.data {
916        if let Some(name) = object.place.split(&object.name) {
917            let section = obj.add_section(Vec::new(), name.into_bytes(), kind_of(&object.place));
918            let offset = if carries_no_bytes(&object.place) {
919                obj.append_section_bss(section, object.size, object.align)
920            } else {
921                obj.append_section_data(section, &object.bytes, object.align)
922            };
923            return (SymbolSection::Section(section), offset);
924        }
925    }
926    let section = match &object.place {
927        Place::Written => obj.section_id(StandardSection::Data),
928        Place::ReadOnly => obj.section_id(StandardSection::ReadOnlyData),
929        // Read only after the loader has written it, which the writer knows as the relocatable
930        // read only data section and which is `.data.rel.ro` on ELF. The `.local` half is a layout
931        // hint the writer has no name for, so it is added by hand and remembered: asking again
932        // would make a second section with the same name, and a file with one of those per variable
933        // is a file whose section headers outweigh what they describe.
934        Place::RelocReadOnly { local } => match flavour.rel_ro_local().filter(|_| *local) {
935            Some(name) => made(obj, named, name, SectionKind::ReadOnlyDataWithRel),
936            None => obj.section_id(StandardSection::ReadOnlyDataWithRel),
937        },
938        Place::Zero => obj.section_id(StandardSection::UninitializedData),
939        Place::Thread { zero: false } => obj.section_id(StandardSection::Tls),
940        Place::Thread { zero: true } => obj.section_id(StandardSection::UninitializedTls),
941        Place::Merged => return (SymbolSection::Common, 0),
942        // A named section is the program's word for where this goes, and a program that names one
943        // wants what it named rather than what would have been chosen. It is written as ordinary
944        // data because nothing in the IR says otherwise, except for the three names the startup
945        // code calls what it finds in, which have a section type of their own and are gathered by
946        // the linker whether or not they carry it.
947        Place::Named(name) => {
948            let section = made(obj, named, name, SectionKind::Data);
949            if let Some(flags) = Array::of(name).and_then(|array| flavour.gathered(array)) {
950                obj.section_mut(section).flags = flags;
951            }
952            section
953        }
954    };
955    let offset = if carries_no_bytes(&object.place) {
956        obj.append_section_bss(section, object.size, object.align)
957    } else {
958        obj.append_section_data(section, &object.bytes, object.align)
959    };
960    (SymbolSection::Section(section), offset)
961}
962
963/// Every jump table of the text, in `.rodata`, each cell a distance the linker works out, giving
964/// back the section each one went in and where in it, by the name the code gives it.
965///
966/// The section is `.rodata` for all of them, or `.rodata.` and the function's name under
967/// `-fdata-sections`, which is where gcc puts a table in each case. Not split under
968/// `-ffunction-sections` alone, which is gcc's answer too.
969///
970/// A cell is the distance from the front of the table to a block, and the block is in the text
971/// while the table is not, so it is `R_X86_64_PC32` against the function's section with the block's
972/// offset and the cell's own place in the table as the addend. Against the section rather than the
973/// function's name for the reason the unwind records are: a global name may be answered by another
974/// object at load time, and a linker refuses a distance to one.
975fn tables(
976    obj: &mut Writer<'_>,
977    text: &Text,
978    split: &[(object::write::SectionId, u64)],
979    named: &mut HashMap<String, object::write::SectionId>,
980    sections: Sections,
981    flavour: Flavour,
982) -> Result<HashMap<String, (object::write::SectionId, u64)>, Error> {
983    let mut placed = HashMap::new();
984    if text.tables.is_empty() {
985        return Ok(placed);
986    }
987    if flavour != Flavour::Elf {
988        let why = "a jump table outside the code is written on ELF only".to_owned();
989        return Err(Error::Refused { why });
990    }
991    let flags = flavour.reloc(Reference::Away, 0).ok_or_else(|| Error::Refused {
992        why: "no relocation is a distance from where it is written".to_owned(),
993    })?;
994    for table in &text.tables {
995        let func = text.funcs.get(table.func).ok_or_else(|| Error::Refused {
996            why: format!("'{}' belongs to function {}, which is not here", table.name, table.func),
997        })?;
998        let section = if sections.data {
999            let name = format!(".rodata.{}", func.name);
1000            made(obj, named, &name, SectionKind::ReadOnlyData)
1001        } else {
1002            obj.section_id(StandardSection::ReadOnlyData)
1003        };
1004        let offset = obj.append_section_data(section, &vec![0; 4 * table.cells.len()], 4);
1005        placed.insert(table.name.clone(), (section, offset));
1006        let (code, at) = split[table.func];
1007        let symbol = obj.section_symbol(code);
1008        for (index, &cell) in table.cells.iter().enumerate() {
1009            let place = 4 * index as u64;
1010            let addend = at as i64 + cell as i64 + place as i64;
1011            let record = Relocation { offset: offset + place, symbol, addend, flags };
1012            obj.add_relocation(section, record)
1013                .map_err(|why| Error::Refused { why: why.to_string() })?;
1014        }
1015    }
1016    Ok(placed)
1017}
1018
1019/// Whether the section this goes in says how big the variable is and holds none of its bytes.
1020///
1021/// Two of them, and they are the same answer twice: `.bss` is the image that is all zeros, and
1022/// `.tbss` is a thread's own copy of one. A section like this costs its size in the section header
1023/// and nothing in the file, which is what keeps a program with a large zeroed array small.
1024fn carries_no_bytes(place: &Place) -> bool {
1025    matches!(place, Place::Zero | Place::Thread { zero: true })
1026}
1027
1028/// The section of this name, made the first time it is asked for and found afterwards.
1029///
1030/// Two variables the program put the same section name on belong in one section, the way two in
1031/// `.data` do. Asking the writer for a new one each time would make a second header with the same
1032/// name, which a linker takes and which makes a file with ten constructors in it carry ten section
1033/// headers describing eight bytes each. `section_id` does this already for the sections it has
1034/// names of its own for, and this is the same answer for the ones it does not.
1035fn made(
1036    obj: &mut Writer<'_>,
1037    named: &mut HashMap<String, object::write::SectionId>,
1038    name: &str,
1039    kind: SectionKind,
1040) -> object::write::SectionId {
1041    if let Some(section) = named.get(name) {
1042        return *section;
1043    }
1044    let section = obj.add_section(Vec::new(), name.as_bytes().to_vec(), kind);
1045    named.insert(name.to_owned(), section);
1046    section
1047}
1048
1049/// What a section split off for one variable is, which is what the section it was split off from
1050/// was.
1051///
1052/// Splitting changes the name and nothing else. A variable that was going to be in a page the
1053/// loader maps read only is still in one, and a zero filled variable still costs the file nothing,
1054/// so the flags a linker reads off the section header have to come out the same as they would
1055/// have. The two kinds with no section of their own never reach here, and `Data` for them is a
1056/// value that is never used rather than a claim about either.
1057fn kind_of(place: &Place) -> SectionKind {
1058    match place {
1059        Place::ReadOnly => SectionKind::ReadOnlyData,
1060        Place::RelocReadOnly { .. } => SectionKind::ReadOnlyDataWithRel,
1061        Place::Zero => SectionKind::UninitializedData,
1062        Place::Thread { zero: false } => SectionKind::Tls,
1063        Place::Thread { zero: true } => SectionKind::UninitializedTls,
1064        Place::Written | Place::Merged | Place::Named(_) => SectionKind::Data,
1065    }
1066}
1067
1068/// One relocation, `at` bytes into the section it ended up in.
1069///
1070/// The offset is worked out by the caller rather than here, because the two callers count from
1071/// different places: a relocation in an image counts from the start of that image and a relocation
1072/// in a function counts from the start of that function, and neither of those is where the section
1073/// begins once something else is in front of it.
1074fn add(
1075    obj: &mut Writer<'_>,
1076    section: object::write::SectionId,
1077    at: u64,
1078    reloc: &Reloc,
1079    symbols: &BTreeMap<String, SymbolId>,
1080    flavour: Flavour,
1081) -> Result<(), Error> {
1082    let flags = flavour
1083        .reloc(reloc.kind, reloc.after)
1084        .ok_or_else(|| Error::Refused { why: format!("no relocation is {:?}", reloc.kind) })?;
1085    obj.add_relocation(
1086        section,
1087        Relocation { offset: at, symbol: symbols[&reloc.symbol], addend: reloc.addend, flags },
1088    )
1089    .map_err(|why| Error::Refused { why: why.to_string() })
1090}
1091
1092/// How far a name reaches, which is the one thing about a symbol ELF calls its binding.
1093///
1094/// `SymbolScope` is two facts in one word, and the trap is that the middle one is not the neutral
1095/// answer it reads as. The writer turns `Compilation` into a local symbol, and it turns the choice
1096/// between `Linkage` and `Dynamic` into `st_other`: `Linkage` is `STV_HIDDEN` and `Dynamic` is
1097/// `STV_DEFAULT`. So there is no way to say global and decline to say anything about visibility,
1098/// and picking the one whose name sounds like the smaller claim is picking hidden. That is what
1099/// tamnd/rucc#733 was.
1100///
1101/// `Dynamic` is what every global asks for here, and the visibility is said afterwards by
1102/// [`see`] rather than through this, so that nothing about `st_other` depends on reading one of
1103/// these four names the way its author meant it.
1104pub(crate) fn scope_of(binding: Binding) -> SymbolScope {
1105    match binding {
1106        Binding::Local => SymbolScope::Compilation,
1107        Binding::Global | Binding::Weak => SymbolScope::Dynamic,
1108    }
1109}
1110
1111#[cfg(test)]
1112mod tests {
1113    use super::*;
1114
1115    use object::read::elf::Sym as _;
1116    use object::read::{Object as _, ObjectSection as _, ObjectSymbol as _};
1117    use object::{elf, pe};
1118    use rucc_target::{Arch, Env, Os, Triple};
1119
1120    use crate::elf::PATCHABLE;
1121    use crate::section::{Extent, Marker, Patch, Reloc};
1122
1123    /// A linux x86-64 target, which is the only one this writes.
1124    fn target() -> TargetInfo {
1125        TargetInfo::new(Triple::new(Arch::X86_64, Os::Linux, Env::Gnu))
1126    }
1127
1128    /// One function of that name, at that offset, that many bytes long, and visible that far.
1129    ///
1130    /// Visibility is the field these cases mostly have no opinion about, so it is the one the
1131    /// helper fills in and the two that do have an opinion write for themselves.
1132    fn extent(name: String, start: usize, len: usize, binding: Binding) -> Extent {
1133        Extent {
1134            name,
1135            start,
1136            len,
1137            align: crate::FUNC_ALIGN,
1138            binding,
1139            visibility: Visibility::Default,
1140            patch: None,
1141            landings: Vec::new(),
1142        }
1143    }
1144
1145    /// A call to something outside the file, which is the shape every case here starts from.
1146    fn calling(name: &str) -> Text {
1147        Text {
1148            bytes: vec![0xe8, 0, 0, 0, 0, 0xc3],
1149            funcs: vec![extent("f".to_owned(), 0, 6, Binding::Global)],
1150            relocs: vec![Reloc {
1151                at: 1,
1152                symbol: name.to_owned(),
1153                kind: Reference::Call,
1154                addend: -4,
1155                after: 0,
1156            }],
1157            ..Text::default()
1158        }
1159    }
1160
1161    #[test]
1162    fn the_bytes_come_back_out_of_the_section_they_went_into() {
1163        let text = calling("puts");
1164        let bytes =
1165            write(&text, &Data::default(), &[], &target(), Output::default(), &Info::default())
1166                .expect("an object");
1167        let file = object::File::parse(&bytes[..]).expect("a readable object");
1168        let section = file.section_by_name(".text").expect("a text section");
1169        assert_eq!(section.data().expect("the bytes"), &text.bytes[..]);
1170    }
1171
1172    #[test]
1173    fn a_function_is_a_symbol_that_says_where_it_is_and_how_long_it_is() {
1174        let mut text = calling("puts");
1175        text.funcs.push(extent("g".to_owned(), 16, 1, Binding::Global));
1176        text.bytes.resize(17, 0x90);
1177        let bytes =
1178            write(&text, &Data::default(), &[], &target(), Output::default(), &Info::default())
1179                .expect("an object");
1180        let file = object::File::parse(&bytes[..]).expect("a readable object");
1181        let g = file.symbols().find(|s| s.name() == Ok("g")).expect("the second function");
1182        assert_eq!(g.address(), 16);
1183        assert_eq!(g.size(), 1);
1184        assert_eq!(g.kind(), SymbolKind::Text);
1185        assert!(g.is_global(), "nothing said otherwise about this one");
1186    }
1187
1188    #[test]
1189    fn a_function_no_other_file_can_see_is_a_local_symbol() {
1190        let mut text = calling("puts");
1191        text.funcs.push(extent("hidden".to_owned(), 16, 1, Binding::Local));
1192        text.funcs.push(extent("shared".to_owned(), 32, 1, Binding::Weak));
1193        text.bytes.resize(33, 0x90);
1194        let bytes =
1195            write(&text, &Data::default(), &[], &target(), Output::default(), &Info::default())
1196                .expect("an object");
1197        let file = object::File::parse(&bytes[..]).expect("a readable object");
1198        let hidden = file.symbols().find(|s| s.name() == Ok("hidden")).expect("the static one");
1199        // A symbol the linker keeps and does not let another file reach, which is the whole of
1200        // what `static` on a function means and what two files each defining their own need.
1201        assert!(hidden.is_local(), "a static function must not be offered to the linker");
1202        assert!(!hidden.is_weak());
1203        let shared = file.symbols().find(|s| s.name() == Ok("shared")).expect("the weak one");
1204        assert!(shared.is_weak(), "a weak function has to be able to lose");
1205        assert!(shared.is_global());
1206    }
1207
1208    /// A global is `STV_DEFAULT`, so a shared library built from these objects exports something.
1209    ///
1210    /// The bug in tamnd/rucc#733. Every global came out `STV_HIDDEN`, which a static link does not
1211    /// look at, so nothing here noticed and SQLite linked and ran and the whole test suite passed.
1212    /// What it costs is the dynamic symbol table: `gcc -shared` over one of these objects produced
1213    /// a library with an empty one, and `dlsym` could not find a function the file plainly defines.
1214    ///
1215    /// Written against `st_other` itself rather than against the reader's `scope`, because `scope`
1216    /// is the word that was misread in the first place and a test that asks it the same question
1217    /// would agree with whatever the writer did.
1218    /// The record of where a patcher's room is, and what it says about it.
1219    ///
1220    /// Four things have to be right at once for a linker to take it: the flags, the alignment, the
1221    /// relocation and the section it says it is ordered after. The last of those is the one the
1222    /// writer underneath cannot say, so a zero there would be a file `ld` refuses and a test that
1223    /// only looked at the bytes would not see it.
1224    #[test]
1225    fn where_a_patcher_may_write_is_recorded_in_a_section_tied_to_the_code_it_is_about() {
1226        let mut text = calling("puts");
1227        text.bytes.splice(0..0, [0x90, 0x90, 0x90]);
1228        text.funcs[0].start = 3;
1229        text.funcs[0].patch = Some(Patch { at: 0, before: 3 });
1230        text.relocs[0].at = 4;
1231        let bytes =
1232            write(&text, &Data::default(), &[], &target(), Output::default(), &Info::default())
1233                .expect("an object");
1234        let file = object::read::elf::ElfFile64::<Endianness>::parse(&bytes[..]).expect("readable");
1235        let section = file.section_by_name(PATCHABLE).expect("a record of the room");
1236        assert_eq!(section.size(), 8, "one address, and this file defines one function");
1237        assert_eq!(section.align(), 8);
1238        let header = section.elf_section_header();
1239        assert_eq!(
1240            header.sh_flags.get(Endianness::Little),
1241            elf::SHF_ALLOC | elf::SHF_WRITE | elf::SHF_LINK_ORDER
1242        );
1243        // Which is the whole point of the fixup: the index has to be the text section's own, and
1244        // the writer underneath had written a zero there.
1245        let index = file.section_by_name(".text").expect("a text section").index().0;
1246        assert_eq!(header.sh_link.get(Endianness::Little) as usize, index);
1247        assert_ne!(index, 0);
1248
1249        // And the address, which is the front of the room rather than the function's own symbol.
1250        let [(at, reloc)] = &section.relocations().collect::<Vec<_>>()[..] else {
1251            panic!("one address in the record")
1252        };
1253        assert_eq!(*at, 0);
1254        assert_eq!(reloc.addend(), 0);
1255        assert_eq!(reloc.flags(), RelocationFlags::Elf { r_type: elf::R_X86_64_64 });
1256    }
1257
1258    /// And a file that asked for none has no such section, which is nearly every file.
1259    #[test]
1260    fn a_file_that_promised_a_patcher_nothing_records_nothing() {
1261        let text = calling("puts");
1262        let bytes =
1263            write(&text, &Data::default(), &[], &target(), Output::default(), &Info::default())
1264                .expect("an object");
1265        let file = object::File::parse(&bytes[..]).expect("a readable object");
1266        assert!(file.section_by_name(PATCHABLE).is_none());
1267    }
1268
1269    /// The same when each function is a section of its own, which is what a kernel builds with.
1270    ///
1271    /// Each record then points at a different section, which is what makes the pairing worth
1272    /// asserting: getting it backwards would still produce a file every tool reads and every
1273    /// address in it would be about the wrong function.
1274    #[test]
1275    fn each_record_is_tied_to_its_own_function_when_they_are_split_up() {
1276        let mut text = calling("puts");
1277        text.funcs[0].patch = Some(Patch { at: 0, before: 0 });
1278        text.funcs.push(extent("g".to_owned(), 16, 1, Binding::Global));
1279        text.funcs[1].patch = Some(Patch { at: 16, before: 0 });
1280        text.bytes.resize(17, 0x90);
1281        let output =
1282            Output { sections: Sections { functions: true, data: false }, ..Output::default() };
1283        let bytes = write(&text, &Data::default(), &[], &target(), output, &Info::default())
1284            .expect("an object");
1285        let file = object::read::elf::ElfFile64::<Endianness>::parse(&bytes[..]).expect("readable");
1286        let links: Vec<usize> = file
1287            .sections()
1288            .filter(|section| section.name() == Ok(PATCHABLE))
1289            .map(|section| section.elf_section_header().sh_link.get(Endianness::Little) as usize)
1290            .collect();
1291        let index = |name: &str| file.section_by_name(name).expect("a text section").index().0;
1292        assert_eq!(links, [index(".text.f"), index(".text.g")]);
1293    }
1294
1295    #[test]
1296    fn a_global_is_visible_to_the_dynamic_linker_and_a_static_one_is_not_a_symbol_at_all() {
1297        let mut text = calling("puts");
1298        text.funcs.push(extent("g".to_owned(), 16, 1, Binding::Global));
1299        text.funcs.push(extent("w".to_owned(), 32, 1, Binding::Weak));
1300        text.funcs.push(extent("s".to_owned(), 48, 1, Binding::Local));
1301        text.bytes.resize(49, 0x90);
1302        let bytes =
1303            write(&text, &Data::default(), &[], &target(), Output::default(), &Info::default())
1304                .expect("an object");
1305        let file = object::read::elf::ElfFile64::<Endianness>::parse(&bytes[..]).expect("readable");
1306        let visibility = |name: &str| {
1307            file.symbols()
1308                .find(|s| s.name() == Ok(name))
1309                .expect("the function")
1310                .elf_symbol()
1311                .st_visibility()
1312        };
1313        // Nothing said hidden about either of these, so neither is.
1314        assert_eq!(visibility("g"), elf::STV_DEFAULT);
1315        assert_eq!(visibility("w"), elf::STV_DEFAULT, "a weak one is still a name others may use");
1316        // The `static` one is local, and a local symbol's visibility means nothing either way,
1317        // which is why the binding is what this asks about.
1318        assert_eq!(visibility("s"), elf::STV_DEFAULT);
1319    }
1320
1321    /// And the other direction: a name that did ask to be hidden is hidden, and a protected one is
1322    /// protected.
1323    ///
1324    /// The half of tamnd/rucc#733 that the fix above left open. Saying `STV_DEFAULT` for everything
1325    /// is right for everything nobody marked and wrong the moment something is marked, so the two
1326    /// tests together are what says the field carries an answer rather than a constant.
1327    ///
1328    /// Both are asked of a function and of a variable, because they are added by two different
1329    /// loops in `write` and a field one of them fills in is not a field the other one does.
1330    #[test]
1331    fn a_name_that_asked_to_be_hidden_is_hidden_and_a_protected_one_is_protected() {
1332        let mut text = calling("puts");
1333        for (index, (name, seen)) in
1334            [("h", Visibility::Hidden), ("p", Visibility::Protected)].into_iter().enumerate()
1335        {
1336            let mut func = extent(name.to_owned(), 16 + index * 16, 1, Binding::Global);
1337            func.visibility = seen;
1338            text.funcs.push(func);
1339        }
1340        text.bytes.resize(49, 0x90);
1341        let mut data = Data::default();
1342        for (name, seen) in [("vh", Visibility::Hidden), ("vp", Visibility::Protected)] {
1343            let mut object = variable(name, Place::Written);
1344            object.visibility = seen;
1345            data.objects.push(object);
1346        }
1347        let bytes = write(&text, &data, &[], &target(), Output::default(), &Info::default())
1348            .expect("an object");
1349        let file = object::read::elf::ElfFile64::<Endianness>::parse(&bytes[..]).expect("readable");
1350        let visibility = |name: &str| {
1351            file.symbols()
1352                .find(|s| s.name() == Ok(name))
1353                .expect("the symbol")
1354                .elf_symbol()
1355                .st_visibility()
1356        };
1357        assert_eq!(visibility("h"), elf::STV_HIDDEN);
1358        assert_eq!(visibility("p"), elf::STV_PROTECTED);
1359        assert_eq!(visibility("vh"), elf::STV_HIDDEN, "a variable goes through a second loop");
1360        assert_eq!(visibility("vp"), elf::STV_PROTECTED);
1361        // The one thing a visibility must not disturb, since `st_info` and `st_other` are written
1362        // in one go and the second was set after the first.
1363        let h = file.symbols().find(|s| s.name() == Ok("h")).expect("the function");
1364        assert!(h.is_global(), "hidden is about the dynamic linker and not about the binding");
1365        assert_eq!(h.size(), 1, "and it is still a function of the length it was");
1366    }
1367
1368    #[test]
1369    fn a_name_this_file_does_not_define_is_left_for_the_linker_to_find() {
1370        let bytes = write(
1371            &calling("puts"),
1372            &Data::default(),
1373            &[],
1374            &target(),
1375            Output::default(),
1376            &Info::default(),
1377        )
1378        .expect("an object");
1379        let file = object::File::parse(&bytes[..]).expect("a readable object");
1380        let puts = file.symbols().find(|s| s.name() == Ok("puts")).expect("the callee");
1381        assert!(puts.is_undefined(), "the file does not define it and must not claim to");
1382    }
1383
1384    #[test]
1385    fn a_call_asks_for_the_relocation_a_stub_may_answer_and_a_load_asks_for_the_one_that_may_not() {
1386        for (reference, wanted) in [
1387            (Reference::Call, elf::R_X86_64_PLT32),
1388            (Reference::Data, elf::R_X86_64_PC32),
1389            (Reference::Got, elf::R_X86_64_REX_GOTPCRELX),
1390            (Reference::GotBare, elf::R_X86_64_GOTPCRELX),
1391            (Reference::GotKept, elf::R_X86_64_GOTPCREL),
1392            (Reference::Thread, elf::R_X86_64_GOTTPOFF),
1393        ] {
1394            let mut text = calling("puts");
1395            text.relocs[0].kind = reference;
1396            let bytes =
1397                write(&text, &Data::default(), &[], &target(), Output::default(), &Info::default())
1398                    .expect("an object");
1399            let file = object::File::parse(&bytes[..]).expect("a readable object");
1400            let section = file.section_by_name(".text").expect("a text section");
1401            let (offset, reloc) = section.relocations().next().expect("one relocation");
1402            assert_eq!(offset, 1);
1403            assert_eq!(reloc.addend(), -4);
1404            assert_eq!(reloc.flags(), RelocationFlags::Elf { r_type: wanted });
1405        }
1406    }
1407
1408    #[test]
1409    fn a_name_wanted_twice_is_one_symbol_rather_than_two() {
1410        let mut text = calling("puts");
1411        text.relocs.push(Reloc {
1412            at: 1,
1413            symbol: "puts".to_owned(),
1414            kind: Reference::Call,
1415            addend: -4,
1416            after: 0,
1417        });
1418        let bytes =
1419            write(&text, &Data::default(), &[], &target(), Output::default(), &Info::default())
1420                .expect("an object");
1421        let file = object::File::parse(&bytes[..]).expect("a readable object");
1422        assert_eq!(file.symbols().filter(|s| s.name() == Ok("puts")).count(), 1);
1423    }
1424
1425    #[test]
1426    fn a_function_that_is_also_called_is_not_a_second_symbol() {
1427        let text = calling("f");
1428        let bytes =
1429            write(&text, &Data::default(), &[], &target(), Output::default(), &Info::default())
1430                .expect("an object");
1431        let file = object::File::parse(&bytes[..]).expect("a readable object");
1432        let mut found = file.symbols().filter(|s| s.name() == Ok("f"));
1433        let f = found.next().expect("the function");
1434        assert!(!f.is_undefined(), "the file defines it");
1435        assert!(found.next().is_none(), "and defines it once");
1436    }
1437
1438    #[test]
1439    fn the_marker_that_says_the_stack_is_not_executable_is_written() {
1440        let bytes = write(
1441            &calling("puts"),
1442            &Data::default(),
1443            &[],
1444            &target(),
1445            Output::default(),
1446            &Info::default(),
1447        )
1448        .expect("an object");
1449        let file = object::File::parse(&bytes[..]).expect("a readable object");
1450        let note = file.section_by_name(".note.GNU-stack").expect("the marker");
1451        assert!(note.data().expect("no bytes").is_empty());
1452    }
1453
1454    /// What the file says it was built to have checked, byte for byte.
1455    ///
1456    /// Written against the bytes rather than against a reader, because the two lengths in the
1457    /// header count the padding after what they measure and a note whose lengths are one word out
1458    /// is one a linker drops without saying anything. What comes of that is a program the loader
1459    /// leaves the check turned off for, which is a build that looks like it worked.
1460    #[test]
1461    fn the_note_that_says_what_the_file_was_built_to_have_checked_is_written() {
1462        let property = Property { features: Property::IBT | Property::SHSTK };
1463        let output = Output { property, ..Output::default() };
1464        let bytes =
1465            write(&calling("puts"), &Data::default(), &[], &target(), output, &Info::default())
1466                .expect("an object");
1467        let file = object::File::parse(&bytes[..]).expect("a readable object");
1468        let note = file.section_by_name(".note.gnu.property").expect("the note");
1469        assert_eq!(note.align(), 8, "a note in a sixty four bit object is read a word at a time");
1470        let want: Vec<u8> = [
1471            4u32,
1472            16,
1473            5,
1474            u32::from_le_bytes(*b"GNU\0"),
1475            Property::X86_FEATURES,
1476            4,
1477            Property::IBT | Property::SHSTK,
1478            0,
1479        ]
1480        .iter()
1481        .flat_map(|word| word.to_le_bytes())
1482        .collect();
1483        assert_eq!(note.data().expect("the bytes"), &want[..]);
1484    }
1485
1486    /// And nothing at all when the file was built to have nothing checked.
1487    ///
1488    /// A note with an empty feature word and no note are the same thing to a linker, which drops
1489    /// the whole property when any input lacks it. gcc writes nothing, so a section header that
1490    /// describes nothing would be the one difference between the two compilers' objects.
1491    #[test]
1492    fn a_file_built_to_have_nothing_checked_says_nothing() {
1493        let bytes = write(
1494            &calling("puts"),
1495            &Data::default(),
1496            &[],
1497            &target(),
1498            Output::default(),
1499            &Info::default(),
1500        )
1501        .expect("an object");
1502        let file = object::File::parse(&bytes[..]).expect("a readable object");
1503        assert!(file.section_by_name(".note.gnu.property").is_none());
1504    }
1505
1506    /// Every unwind record names the function it is about, and each name goes where it is in the
1507    /// table rather than at the start of it.
1508    ///
1509    /// Written because working the offset out is the caller's job here, which is what the two text
1510    /// paths differ about, and a third caller that let it default to nothing would put every record
1511    /// in the table on the same function. Nothing else would notice: the section is the right
1512    /// length, the symbols are right, the link succeeds, and what comes of it is an unwinder that
1513    /// walks out of the wrong frame the first time something throws or a backtrace is taken.
1514    #[test]
1515    fn an_unwind_record_names_the_function_it_is_about_and_not_the_first_one() {
1516        let mut text = calling("puts");
1517        text.funcs.push(extent("g".to_owned(), 16, 1, Binding::Global));
1518        text.bytes.resize(17, 0x90);
1519        // A shared header and two records, whose contents nothing here reads: what is being asked
1520        // is where in them each name landed.
1521        text.unwind.bytes = vec![0; 64];
1522        for (at, name) in [(32usize, "f"), (48usize, "g")] {
1523            text.unwind.relocs.push(Reloc {
1524                at,
1525                symbol: name.to_owned(),
1526                kind: Reference::Address { bytes: 8 },
1527                addend: 0,
1528                after: 0,
1529            });
1530        }
1531        let bytes =
1532            write(&text, &Data::default(), &[], &target(), Output::default(), &Info::default())
1533                .expect("an object");
1534        let file = object::File::parse(&bytes[..]).expect("a readable object");
1535        let mut found = points_at(&file);
1536        found.sort_unstable();
1537        assert_eq!(found, [(32, ".text".to_owned(), 0), (48, ".text".to_owned(), 16)]);
1538    }
1539
1540    /// What each record in the unwind table points at: where it is, the section it reaches, and
1541    /// how far into that section the function it is about begins.
1542    fn points_at(file: &object::File<'_>) -> Vec<(u64, String, i64)> {
1543        let frames = file.section_by_name(".eh_frame").expect("the table");
1544        frames
1545            .relocations()
1546            .map(|(offset, reloc)| {
1547                let object::RelocationTarget::Symbol(index) = reloc.target() else {
1548                    panic!("a record points at something that is not a symbol");
1549                };
1550                let symbol = file.symbol_by_index(index).expect("a symbol that is in the table");
1551                assert_eq!(symbol.kind(), SymbolKind::Section, "a record names a section");
1552                let section = symbol.section_index().expect("a section symbol is in one");
1553                let name = file.section_by_index(section).expect("a readable section");
1554                (offset, name.name().expect("a named section").to_owned(), reloc.addend())
1555            })
1556            .collect()
1557    }
1558
1559    /// A record points at the section its function is in rather than at the function's name.
1560    ///
1561    /// Written for tamnd/rucc#1004, which was that nothing this compiler wrote could go into a
1562    /// shared library. A global name is answered at load time by whichever object defines it
1563    /// first, so the distance from a record to one of them is not a distance a static linker can
1564    /// work out, and `ld` says so and stops with advice to recompile with the flag that was
1565    /// already on the command line. A section is settled by then, which is why gcc measures to a
1566    /// local label and why this measures to the section.
1567    ///
1568    /// Both ways of splitting the text, because the offset is the part that differs: one section
1569    /// holding everything makes it the function's place in the whole text, and a section per
1570    /// function makes it whatever room a patcher was promised in front of the label.
1571    #[test]
1572    fn a_record_reaches_its_function_through_the_section_it_is_in() {
1573        let mut text = two();
1574        text.unwind.bytes = vec![0; 64];
1575        for (at, name) in [(32usize, "f"), (48usize, "g")] {
1576            text.unwind.relocs.push(Reloc {
1577                at,
1578                symbol: name.to_owned(),
1579                kind: Reference::Data,
1580                addend: 0,
1581                after: 0,
1582            });
1583        }
1584        let bytes =
1585            write(&text, &Data::default(), &[], &target(), Output::default(), &Info::default())
1586                .expect("an object");
1587        let file = object::File::parse(&bytes[..]).expect("a readable object");
1588        let mut whole = points_at(&file);
1589        whole.sort_unstable();
1590        assert_eq!(whole, [(32, ".text".to_owned(), 0), (48, ".text".to_owned(), 16)]);
1591
1592        let sections =
1593            Output { sections: Sections { functions: true, data: false }, ..Output::default() };
1594        let bytes = write(&text, &Data::default(), &[], &target(), sections, &Info::default())
1595            .expect("an object");
1596        let file = object::File::parse(&bytes[..]).expect("a readable object");
1597        let mut split = points_at(&file);
1598        split.sort_unstable();
1599        assert_eq!(split, [(32, ".text.f".to_owned(), 0), (48, ".text.g".to_owned(), 0)]);
1600    }
1601
1602    /// A record about a name this file does not define is refused rather than written.
1603    ///
1604    /// There is no such file today: the table is built beside the text out of the functions that
1605    /// were just compiled. It is refused rather than left to the linker because the alternative is
1606    /// the shape that was just fixed, a record measured to a name, and the writer saying what it
1607    /// was given is how that stays fixed.
1608    #[test]
1609    fn a_record_about_something_this_file_does_not_define_is_refused() {
1610        let mut text = calling("puts");
1611        text.unwind.bytes = vec![0; 64];
1612        text.unwind.relocs.push(Reloc {
1613            at: 32,
1614            symbol: "puts".to_owned(),
1615            kind: Reference::Data,
1616            addend: 0,
1617            after: 0,
1618        });
1619        let why =
1620            write(&text, &Data::default(), &[], &target(), Output::default(), &Info::default())
1621                .expect_err("a record about a name from somewhere else");
1622        assert!(why.to_string().contains("puts"), "{why}");
1623    }
1624
1625    /// The name of the section that symbol is defined in.
1626    fn lives_in<'a>(file: &'a object::File<'a>, name: &str) -> String {
1627        let symbol = file.symbols().find(|s| s.name() == Ok(name)).expect("the symbol");
1628        let index = symbol.section_index().expect("a section to be defined in");
1629        let section = file.section_by_index(index).expect("a readable section");
1630        section.name().expect("a named section").to_owned()
1631    }
1632
1633    /// Two functions, the second of them sixteen bytes in and calling something outside the file.
1634    fn two() -> Text {
1635        let mut text = calling("puts");
1636        // Padded to where the second one is aligned to, with the instruction that does nothing,
1637        // because the space in front of a function is reached by falling off the end of one.
1638        text.bytes.resize(16, 0x90);
1639        text.bytes.extend_from_slice(&[0xe8, 0, 0, 0, 0, 0xc3]);
1640        text.funcs.push(extent("g".to_owned(), 16, 6, Binding::Global));
1641        text.relocs.push(Reloc {
1642            at: 17,
1643            symbol: "puts".to_owned(),
1644            kind: Reference::Call,
1645            addend: -4,
1646            after: 0,
1647        });
1648        text
1649    }
1650
1651    /// What `-ffunction-sections` comes down to in an object file, which is the flag that makes
1652    /// `--gc-sections` able to drop anything: a linker can leave out a section nothing reaches and
1653    /// cannot leave out half of one.
1654    ///
1655    /// The empty `.text` stays, because it is the section the writer underneath opens a file with
1656    /// and gcc 16 leaves an empty one behind under the flag too.
1657    #[test]
1658    fn every_function_gets_a_section_of_its_own_when_that_is_what_was_asked_for() {
1659        let sections =
1660            Output { sections: Sections { functions: true, data: false }, ..Output::default() };
1661        let bytes = write(&two(), &Data::default(), &[], &target(), sections, &Info::default())
1662            .expect("an object");
1663        let file = object::File::parse(&bytes[..]).expect("a readable object");
1664        assert_eq!(lives_in(&file, "f"), ".text.f");
1665        assert_eq!(lives_in(&file, "g"), ".text.g");
1666        assert!(file.section_by_name(".text").expect("the empty one").size() == 0);
1667        // Each one at nothing into its own section, and as long as it was: a function alone in a
1668        // section starts where the section does, whatever it started at when they shared one.
1669        for name in ["f", "g"] {
1670            let symbol = file.symbols().find(|s| s.name() == Ok(name)).expect("the function");
1671            assert_eq!(symbol.address(), 0, "{name}");
1672            assert_eq!(symbol.size(), 6, "{name}");
1673        }
1674        let section = file.section_by_name(".text.g").expect("the second function");
1675        assert_eq!(section.data().expect("the bytes"), &[0xe8, 0, 0, 0, 0, 0xc3]);
1676        // The padding between the two is gone with them, since it was there to align the second
1677        // one inside a section they shared and each section is aligned by the linker now.
1678        assert_eq!(section.align(), u64::from(crate::FUNC_ALIGN));
1679    }
1680
1681    /// A relocation counts from the start of whichever section its function ended up in, which is
1682    /// the arithmetic the split path has to do and the unsplit one never does.
1683    ///
1684    /// Getting it wrong is a call patched over the wrong bytes, which assembles, links, and jumps
1685    /// into the middle of an instruction at run time.
1686    #[test]
1687    fn a_relocation_moves_with_the_function_whose_bytes_it_is_in() {
1688        let sections =
1689            Output { sections: Sections { functions: true, data: false }, ..Output::default() };
1690        let bytes = write(&two(), &Data::default(), &[], &target(), sections, &Info::default())
1691            .expect("an object");
1692        let file = object::File::parse(&bytes[..]).expect("a readable object");
1693        for name in [".text.f", ".text.g"] {
1694            let section = file.section_by_name(name).expect("a function");
1695            let (offset, _) = section.relocations().next().expect("the call in it");
1696            // One byte in either way, because the call is the first instruction of both and the
1697            // opcode is one byte in front of the address the linker fills in.
1698            assert_eq!(offset, 1, "{name}");
1699            assert_eq!(section.relocations().count(), 1, "{name}");
1700        }
1701    }
1702
1703    /// The second of `two` with a table of two cells, to its first byte and to its return.
1704    fn switching() -> Text {
1705        let mut text = two();
1706        let name = ".Lg_j0".to_owned();
1707        text.tables.push(crate::Table { name, func: 1, cells: vec![0, 5] });
1708        text
1709    }
1710
1711    /// Where each relocation of that section is, what it is against and what it adds.
1712    fn cells(file: &object::File<'_>, section: &str) -> Vec<(u64, String, i64)> {
1713        let section = file.section_by_name(section).expect("the table's section");
1714        section
1715            .relocations()
1716            .map(|(offset, reloc)| {
1717                assert_eq!(reloc.flags(), RelocationFlags::Elf { r_type: elf::R_X86_64_PC32 });
1718                let object::RelocationTarget::Symbol(index) = reloc.target() else {
1719                    panic!("a cell against something that is not a symbol");
1720                };
1721                let symbol = file.symbol_by_index(index).expect("a symbol");
1722                assert_eq!(symbol.kind(), SymbolKind::Section);
1723                let at = symbol.section_index().expect("a section symbol is in one");
1724                let name = file.section_by_index(at).expect("a section").name().expect("a name");
1725                (offset, name.to_owned(), reloc.addend())
1726            })
1727            .collect()
1728    }
1729
1730    #[test]
1731    fn a_jump_table_is_read_only_data_whose_cells_the_linker_fills_in() {
1732        // And the code reaches it by the name the table was given, which here is the second of the
1733        // two references in `two`.
1734        let mut text = switching();
1735        text.relocs[1].symbol = ".Lg_j0".to_owned();
1736        text.relocs[1].kind = Reference::Data;
1737        let bytes =
1738            write(&text, &Data::default(), &[], &target(), Output::default(), &Info::default())
1739                .expect("an object");
1740        let file = object::File::parse(&bytes[..]).expect("a readable object");
1741        let rodata = file.section_by_name(".rodata").expect("the table's section");
1742        assert_eq!(rodata.data().expect("the bytes"), &[0; 8]);
1743        assert_eq!(rodata.kind(), SectionKind::ReadOnlyData);
1744        assert!(file.symbols().all(|s| s.name() != Ok(".Lg_j0")), "a table leaves no name behind");
1745        let (at, reloc) = file
1746            .section_by_name(".text")
1747            .expect("the code")
1748            .relocations()
1749            .find(|(at, _)| *at == 17)
1750            .expect("the reference to the table");
1751        assert_eq!((at, reloc.addend()), (17, -4));
1752        let object::RelocationTarget::Symbol(index) = reloc.target() else {
1753            panic!("a reference against something that is not a symbol");
1754        };
1755        let symbol = file.symbol_by_index(index).expect("a symbol");
1756        assert_eq!(symbol.section_index(), Some(rodata.index()));
1757        assert_eq!(symbol.kind(), SymbolKind::Section);
1758        // `g` starts sixteen bytes into `.text`, and each cell is its block's place in the text
1759        // and its own place in the table, so that the linker's answer is block less table.
1760        assert_eq!(
1761            cells(&file, ".rodata"),
1762            [(0, ".text".to_owned(), 16), (4, ".text".to_owned(), 25)]
1763        );
1764    }
1765
1766    #[test]
1767    fn a_jump_table_under_data_sections_is_in_a_section_named_after_its_function() {
1768        let sections =
1769            Output { sections: Sections { functions: true, data: true }, ..Output::default() };
1770        let bytes =
1771            write(&switching(), &Data::default(), &[], &target(), sections, &Info::default())
1772                .expect("an object");
1773        let file = object::File::parse(&bytes[..]).expect("a readable object");
1774        // Against the function's own section now, where it starts at nothing.
1775        assert_eq!(
1776            cells(&file, ".rodata.g"),
1777            [(0, ".text.g".to_owned(), 0), (4, ".text.g".to_owned(), 9)]
1778        );
1779    }
1780
1781    #[test]
1782    fn a_jump_table_outside_the_code_is_refused_on_windows() {
1783        let target = TargetInfo::new(Triple::new(Arch::X86_64, Os::Windows, Env::Gnu));
1784        let written = write(
1785            &switching(),
1786            &Data::default(),
1787            &[],
1788            &target,
1789            Output::default(),
1790            &Info::default(),
1791        );
1792        assert!(matches!(written, Err(Error::Refused { .. })), "{written:?}");
1793    }
1794
1795    /// One variable of four bytes, in whichever section its own answer puts it.
1796    fn variable(name: &str, place: Place) -> Object {
1797        Object {
1798            name: name.to_owned(),
1799            bytes: if carries_no_bytes(&place) { Vec::new() } else { vec![1, 0, 0, 0] },
1800            size: 4,
1801            align: 4,
1802            place,
1803            binding: Binding::Global,
1804            visibility: Visibility::Default,
1805            relocs: Vec::new(),
1806        }
1807    }
1808
1809    /// Two labels in `f` and an image holding the distance between them each way round.
1810    fn measured() -> (Text, Data) {
1811        let mut text = calling("puts");
1812        text.labels.push(Marker { name: ".L0".to_owned(), at: 1 });
1813        text.labels.push(Marker { name: ".L1".to_owned(), at: 5 });
1814        let mut table = variable("table", Place::ReadOnly);
1815        table.bytes = vec![0; 8];
1816        table.size = 8;
1817        let apart = |at, to: &str, from: &str| Apart {
1818            object: 0,
1819            at,
1820            to: to.to_owned(),
1821            from: from.to_owned(),
1822            addend: 0,
1823            bytes: 4,
1824        };
1825        let apart = vec![apart(0, ".L1", ".L0"), apart(4, ".L0", ".L1")];
1826        (text, Data { apart, weak: Vec::new(), objects: vec![table] })
1827    }
1828
1829    #[test]
1830    fn a_distance_between_two_labels_is_a_number_and_not_a_relocation() {
1831        let (text, data) = measured();
1832        let bytes = write(&text, &data, &[], &target(), Output::default(), &Info::default())
1833            .expect("an object");
1834        let file = object::File::parse(&bytes[..]).expect("a readable object");
1835        let section = file.section_by_name(".rodata").expect("a read only section");
1836        assert_eq!(section.relocations().count(), 0);
1837        let image = section.data().expect("the image");
1838        assert_eq!(image[..8], [4, 0, 0, 0, 0xfc, 0xff, 0xff, 0xff]);
1839    }
1840
1841    #[test]
1842    fn a_distance_between_labels_in_two_sections_is_refused() {
1843        // `.L1` moves to a second function, which `-ffunction-sections` puts in a section of its
1844        // own, and then no number is the distance.
1845        let (mut text, data) = measured();
1846        text.bytes.resize(22, 0x90);
1847        text.funcs.push(extent("g".to_owned(), 16, 6, Binding::Global));
1848        text.labels[1].at = 17;
1849        let output =
1850            Output { sections: Sections { functions: true, data: false }, ..Output::default() };
1851        let refused = write(&text, &data, &[], &target(), output, &Info::default());
1852        assert!(matches!(refused, Err(Error::Refused { .. })), "{refused:?}");
1853    }
1854
1855    /// A file of that one variable and nothing else.
1856    fn holding(object: Object) -> Vec<u8> {
1857        let data = Data { apart: Vec::new(), weak: Vec::new(), objects: vec![object] };
1858        write(&Text::default(), &data, &[], &target(), Output::default(), &Info::default())
1859            .expect("an object")
1860    }
1861
1862    #[test]
1863    fn what_a_variable_is_decides_which_section_it_goes_in() {
1864        for (place, wanted) in [
1865            (Place::Written, ".data"),
1866            (Place::ReadOnly, ".rodata"),
1867            (Place::RelocReadOnly { local: false }, ".data.rel.ro"),
1868            (Place::RelocReadOnly { local: true }, ".data.rel.ro.local"),
1869            (Place::Zero, ".bss"),
1870            (Place::Thread { zero: false }, ".tdata"),
1871            (Place::Thread { zero: true }, ".tbss"),
1872            (Place::Named(".init_array".to_owned()), ".init_array"),
1873        ] {
1874            let bytes = holding(variable("x", place.clone()));
1875            let file = object::File::parse(&bytes[..]).expect("a readable object");
1876            let section = file.section_by_name(wanted).unwrap_or_else(|| panic!("{place:?}"));
1877            assert_eq!(section.size(), 4, "{place:?}");
1878            // The zero filled one is as long as it says and carries none of it, which is the
1879            // whole reason the section exists.
1880            let carried = section.data().expect("the bytes").len();
1881            assert_eq!(carried, if carries_no_bytes(&place) { 0 } else { 4 }, "{place:?}");
1882        }
1883    }
1884
1885    /// The section is half of it and the symbol is the other half.
1886    ///
1887    /// A linker checks a relocation against the kind of the symbol it names, so a variable that is
1888    /// in `.tdata` and is an ordinary data symbol is one an ordinary reference resolves to an
1889    /// address that belongs to no thread. `STT_TLS` is what makes that reference an error instead.
1890    #[test]
1891    fn a_thread_local_variable_is_a_thread_local_symbol_and_not_only_a_thread_local_section() {
1892        for place in [Place::Thread { zero: false }, Place::Thread { zero: true }] {
1893            let bytes = holding(variable("counter", place.clone()));
1894            let file = object::File::parse(&bytes[..]).expect("a readable object");
1895            let symbol = file
1896                .symbols()
1897                .find(|symbol| symbol.name() == Ok("counter"))
1898                .unwrap_or_else(|| panic!("{place:?}"));
1899            assert_eq!(symbol.kind(), SymbolKind::Tls, "{place:?}");
1900        }
1901    }
1902
1903    /// The section type a startup list carries, which is what makes the CRT call what is in it.
1904    ///
1905    /// A section of the ordinary type with the right name is gathered by the linker in the same run
1906    /// and called by nobody, so the type is the whole of what this is about. The numbered name is
1907    /// the same kind of section as the plain one: the number is there so that the linker sorts it.
1908    #[test]
1909    fn a_section_of_function_addresses_carries_the_type_the_runtime_looks_for() {
1910        for (name, wanted) in [
1911            (".init_array", elf::SHT_INIT_ARRAY),
1912            (".init_array.00101", elf::SHT_INIT_ARRAY),
1913            (".fini_array", elf::SHT_FINI_ARRAY),
1914            (".preinit_array", elf::SHT_PREINIT_ARRAY),
1915            (".init_arrays", elf::SHT_PROGBITS),
1916        ] {
1917            let bytes = holding(variable("x", Place::Named(name.to_owned())));
1918            let file = object::File::parse(&bytes[..]).expect("a readable object");
1919            let section = file.section_by_name(name).unwrap_or_else(|| panic!("{name}"));
1920            let SectionFlags::Elf { sh_type, sh_flags } = section.flags() else {
1921                panic!("{name} is not an elf section");
1922            };
1923            assert_eq!(sh_type, wanted, "{name}");
1924            assert!(sh_flags.contains(elf::SHF_ALLOC | elf::SHF_WRITE), "{name}");
1925        }
1926    }
1927
1928    /// Two variables the program put one section name on, which belong in one section.
1929    ///
1930    /// A file with ten constructors in it would otherwise carry ten section headers describing eight
1931    /// bytes each, and the order the entries run in would be the order the linker happened to put
1932    /// the headers in rather than the order they were written.
1933    #[test]
1934    fn two_variables_in_one_named_section_share_it() {
1935        let objects = vec![
1936            variable("x", Place::Named(".init_array".to_owned())),
1937            variable("y", Place::Named(".init_array".to_owned())),
1938        ];
1939        let data = Data { apart: Vec::new(), weak: Vec::new(), objects };
1940        let bytes =
1941            write(&Text::default(), &data, &[], &target(), Output::default(), &Info::default())
1942                .expect("an object");
1943        let file = object::File::parse(&bytes[..]).expect("a readable object");
1944        let named: Vec<_> =
1945            file.sections().filter(|section| section.name() == Ok(".init_array")).collect();
1946        assert_eq!(named.len(), 1);
1947        assert_eq!(named[0].size(), 8);
1948    }
1949
1950    /// What `-fdata-sections` comes down to in an object file: the section a variable would have
1951    /// shared, with its own name after it. The names are gcc 16's, checked against it on a Linux
1952    /// host, and the part in front of the dot is what a linker script and `--gc-sections` match on.
1953    #[test]
1954    fn every_variable_gets_a_section_of_its_own_when_that_is_what_was_asked_for() {
1955        let sections =
1956            Output { sections: Sections { functions: false, data: true }, ..Output::default() };
1957        for (place, wanted) in [
1958            (Place::Written, ".data.x"),
1959            (Place::ReadOnly, ".rodata.x"),
1960            (Place::RelocReadOnly { local: false }, ".data.rel.ro.x"),
1961            (Place::RelocReadOnly { local: true }, ".data.rel.ro.local.x"),
1962            (Place::Zero, ".bss.x"),
1963            (Place::Thread { zero: false }, ".tdata.x"),
1964            (Place::Thread { zero: true }, ".tbss.x"),
1965        ] {
1966            let data = Data {
1967                apart: Vec::new(),
1968                weak: Vec::new(),
1969                objects: vec![variable("x", place.clone())],
1970            };
1971            let bytes = write(&Text::default(), &data, &[], &target(), sections, &Info::default())
1972                .expect("object");
1973            let file = object::File::parse(&bytes[..]).expect("a readable object");
1974            assert_eq!(lives_in(&file, "x"), wanted, "{place:?}");
1975            let section = file.section_by_name(wanted).expect("the section it named");
1976            assert_eq!(section.size(), 4, "{place:?}");
1977            // Which page it lands in is what the section it came out of decided, and splitting
1978            // must not quietly change it: the zero filled one still carries none of its bytes.
1979            let carried = section.data().expect("the bytes").len();
1980            assert_eq!(carried, if carries_no_bytes(&place) { 0 } else { 4 }, "{place:?}");
1981        }
1982    }
1983
1984    /// The two kinds of variable the flag leaves alone. A tentative definition is a request to the
1985    /// linker for that much zeroed space rather than an image, so there is no section to split off,
1986    /// and one the program named has the answer the source gave, which a flag must not overrule.
1987    #[test]
1988    fn a_variable_that_has_no_section_of_its_own_to_be_given_is_left_where_it_was() {
1989        let sections =
1990            Output { sections: Sections { functions: false, data: true }, ..Output::default() };
1991        let named = Place::Named(".init_array".to_owned());
1992        let objects = vec![variable("m", Place::Merged), variable("n", named)];
1993        let bytes = write(
1994            &Text::default(),
1995            &Data { apart: Vec::new(), weak: Vec::new(), objects },
1996            &[],
1997            &target(),
1998            sections,
1999            &Info::default(),
2000        )
2001        .expect("object");
2002        let file = object::File::parse(&bytes[..]).expect("a readable object");
2003        let m = file.symbols().find(|s| s.name() == Ok("m")).expect("the tentative one");
2004        assert!(m.is_common(), "still the linker's to merge and not in a section at all");
2005        assert_eq!(lives_in(&file, "n"), ".init_array");
2006        assert!(file.section_by_name(".init_array.n").is_none(), "the source already answered");
2007    }
2008
2009    /// A relocation in a variable's image counts from the start of the section it ended up in, the
2010    /// same question the split text has to answer and a shorter answer: a variable alone in a
2011    /// section starts where the section does.
2012    #[test]
2013    fn a_relocation_in_an_image_moves_with_the_variable_whose_image_it_is_in() {
2014        let sections =
2015            Output { sections: Sections { functions: false, data: true }, ..Output::default() };
2016        let pointer = Object {
2017            bytes: vec![0; 8],
2018            size: 8,
2019            align: 8,
2020            relocs: vec![Reloc {
2021                at: 0,
2022                symbol: "y".to_owned(),
2023                kind: Reference::Address { bytes: 8 },
2024                addend: 0,
2025                after: 0,
2026            }],
2027            ..variable("p", Place::Written)
2028        };
2029        let objects = vec![variable("first", Place::Written), pointer];
2030        let bytes = write(
2031            &Text::default(),
2032            &Data { apart: Vec::new(), weak: Vec::new(), objects },
2033            &[],
2034            &target(),
2035            sections,
2036            &Info::default(),
2037        )
2038        .expect("object");
2039        let file = object::File::parse(&bytes[..]).expect("a readable object");
2040        let section = file.section_by_name(".data.p").expect("the pointer's own section");
2041        let (offset, reloc) = section.relocations().next().expect("one relocation");
2042        // Nothing rather than the eight it would be if the variable in front of it were still
2043        // counted, which is what a section of its own means.
2044        assert_eq!(offset, 0);
2045        assert_eq!(reloc.flags(), RelocationFlags::Elf { r_type: elf::R_X86_64_64 });
2046    }
2047
2048    /// Two variables that want `.data.rel.ro.local` end up in one section, not two of one name.
2049    ///
2050    /// The writer has no name of its own for that section, so it is added by hand, and asking for
2051    /// it again makes a second section rather than handing back the first. SQLite has enough const
2052    /// tables of function pointers in it to turn that into eighty odd sections in one object, each
2053    /// with its own relocation section beside it, which is a pile of section headers describing
2054    /// eight bytes apiece.
2055    #[test]
2056    fn every_variable_that_wants_the_local_relocated_section_shares_one() {
2057        let place = Place::RelocReadOnly { local: true };
2058        let data = Data {
2059            apart: Vec::new(),
2060            weak: Vec::new(),
2061            objects: vec![variable("first", place.clone()), variable("second", place)],
2062        };
2063        let bytes =
2064            write(&Text::default(), &data, &[], &target(), Output::default(), &Info::default())
2065                .expect("an object");
2066        let file = object::File::parse(&bytes[..]).expect("a readable object");
2067        let named = file.sections().filter(|s| s.name() == Ok(".data.rel.ro.local")).count();
2068        assert_eq!(named, 1, "one section holding both, not one each");
2069    }
2070
2071    #[test]
2072    fn a_variable_is_a_symbol_that_says_where_it_is_and_how_long_it_is() {
2073        let mut data = Data {
2074            apart: Vec::new(),
2075            weak: Vec::new(),
2076            objects: vec![variable("first", Place::Written)],
2077        };
2078        data.objects.push(Object { align: 16, ..variable("second", Place::Written) });
2079        let bytes =
2080            write(&Text::default(), &data, &[], &target(), Output::default(), &Info::default())
2081                .expect("an object");
2082        let file = object::File::parse(&bytes[..]).expect("a readable object");
2083        let second = file.symbols().find(|s| s.name() == Ok("second")).expect("the second one");
2084        assert_eq!(second.kind(), SymbolKind::Data);
2085        assert_eq!(second.size(), 4);
2086        // Sixteen rather than four, because the second one asked for sixteen and the first one
2087        // had already used four. Getting this wrong is a variable at an address it said it would
2088        // never be at, which nothing downstream would notice until an aligned load faulted.
2089        assert_eq!(second.address(), 16);
2090    }
2091
2092    #[test]
2093    fn the_linkage_a_variable_had_is_the_binding_the_symbol_gets() {
2094        for (binding, global, weak) in [
2095            (Binding::Global, true, false),
2096            (Binding::Local, false, false),
2097            (Binding::Weak, true, true),
2098        ] {
2099            let bytes = holding(Object { binding, ..variable("x", Place::Written) });
2100            let file = object::File::parse(&bytes[..]).expect("a readable object");
2101            let x = file.symbols().find(|s| s.name() == Ok("x")).expect("the variable");
2102            assert_eq!(x.is_global(), global, "{binding:?}");
2103            assert_eq!(x.is_weak(), weak, "{binding:?}");
2104        }
2105    }
2106
2107    #[test]
2108    fn a_tentative_definition_asks_the_linker_for_space_rather_than_naming_any() {
2109        let bytes = holding(Object { align: 8, ..variable("x", Place::Merged) });
2110        let file = object::read::elf::ElfFile64::<Endianness>::parse(&bytes[..]).expect("readable");
2111        let x = file.symbols().find(|s| s.name() == Ok("x")).expect("the variable");
2112        assert!(x.is_common(), "the linker merges every definition of this name into one");
2113        assert_eq!(x.size(), 4);
2114        // What a common symbol records where an ordinary one records its address is what it wants
2115        // to be aligned to, because it has no address yet. The reader deliberately answers nothing
2116        // when asked for the address of one, so this is the field itself.
2117        assert_eq!(x.address(), 0);
2118        assert_eq!(x.elf_symbol().st_value(Endianness::Little), 8);
2119    }
2120
2121    #[test]
2122    fn an_address_in_an_image_is_the_address_and_not_a_distance_to_it() {
2123        let object = Object {
2124            bytes: vec![0; 8],
2125            size: 8,
2126            align: 8,
2127            relocs: vec![Reloc {
2128                at: 0,
2129                symbol: "y".to_owned(),
2130                kind: Reference::Address { bytes: 8 },
2131                addend: 16,
2132                after: 0,
2133            }],
2134            ..variable("p", Place::Written)
2135        };
2136        let bytes = holding(object);
2137        let file = object::File::parse(&bytes[..]).expect("a readable object");
2138        let section = file.section_by_name(".data").expect("a data section");
2139        let (offset, reloc) = section.relocations().next().expect("one relocation");
2140        assert_eq!(offset, 0);
2141        assert_eq!(reloc.addend(), 16);
2142        assert_eq!(reloc.flags(), RelocationFlags::Elf { r_type: elf::R_X86_64_64 });
2143        let y = file.symbols().find(|s| s.name() == Ok("y")).expect("what it points at");
2144        assert!(y.is_undefined(), "nothing here defines it and the linker is being asked for it");
2145    }
2146
2147    /// A name a declaration wrote `weak` on is undefined and may stay that way.
2148    ///
2149    /// The difference between this and the case above is one bit and the whole of what a link does
2150    /// about it: an ordinary undefined symbol is a name the linker has to find, and a weak one is a
2151    /// name it may fail to find, in which case every reference reads a zero address. That is what
2152    /// lets a library offer a hook a profiler may fill in, which is tamnd/rucc#1414.
2153    #[test]
2154    fn a_weak_undefined_name_is_one_the_link_may_leave_unfound() {
2155        let mut text = Text::default();
2156        text.funcs.push(extent("caller".to_owned(), 0, 8, Binding::Global));
2157        text.bytes.resize(8, 0x90);
2158        text.relocs.push(Reloc {
2159            at: 1,
2160            symbol: "hook".to_owned(),
2161            kind: Reference::Call,
2162            addend: -4,
2163            after: 0,
2164        });
2165        let data = Data {
2166            apart: Vec::new(),
2167            weak: vec!["hook".to_owned(), "never_called".to_owned()],
2168            objects: vec![],
2169        };
2170        let bytes = write(&text, &data, &[], &target(), Output::default(), &Info::default())
2171            .expect("an object");
2172        let file = object::File::parse(&bytes[..]).expect("a readable object");
2173
2174        let hook = file.symbols().find(|s| s.name() == Ok("hook")).expect("the one called");
2175        assert!(hook.is_undefined(), "nothing here defines it");
2176        assert!(hook.is_weak(), "so the link may leave it alone rather than fail");
2177
2178        // And one nothing refers to is still written down, because the listing writes a directive
2179        // for it and the two paths have to put the same entries in. A linker has nothing to do
2180        // about an undefined weak symbol no relocation names.
2181        let quiet = file.symbols().find(|s| s.name() == Ok("never_called")).expect("the other");
2182        assert!(quiet.is_undefined() && quiet.is_weak(), "{:?}", quiet.flags());
2183    }
2184
2185    /// A name this file reads through the thread pointer is undefined and is still known to be
2186    /// thread-local.
2187    ///
2188    /// The other undefined names here are written with no type at all, because a name this file does
2189    /// not define is a name this file has nothing to say about. A thread-local one is different in
2190    /// the one way that counts: a reference to it is satisfied by an offset into a block rather than
2191    /// by an address, so the linker has to know which of the two is wanted before it has found the
2192    /// definition, and rather than guess it refuses a link where one file says `STT_TLS` about a name
2193    /// and another does not. Writing the type is not extra information, it is the same information
2194    /// the relocation already carried, said where the linker looks for it.
2195    ///
2196    /// That is tamnd/rucc#1461. libmpfr defines `__gmpfr_flags` in `exceptions.c` and reads it in a
2197    /// hundred other files, and the link stopped at the first reader with `TLS definition in
2198    /// exceptions.o section .tdata mismatches non-TLS reference in add.o`.
2199    #[test]
2200    fn a_thread_local_name_this_file_only_reads_is_still_written_down_as_thread_local() {
2201        let mut text = Text::default();
2202        text.funcs.push(extent("reader".to_owned(), 0, 16, Binding::Global));
2203        text.bytes.resize(16, 0x90);
2204        text.relocs.push(Reloc {
2205            at: 3,
2206            symbol: "flags".to_owned(),
2207            kind: Reference::Thread,
2208            addend: -4,
2209            after: 0,
2210        });
2211        // One of them reached the ordinary way, so that what the type says is the relocation's doing
2212        // and not something every undefined name here would have got.
2213        text.relocs.push(Reloc {
2214            at: 10,
2215            symbol: "shared".to_owned(),
2216            kind: Reference::Got,
2217            addend: -4,
2218            after: 0,
2219        });
2220        let data = Data { apart: Vec::new(), weak: Vec::new(), objects: vec![] };
2221        let bytes = write(&text, &data, &[], &target(), Output::default(), &Info::default())
2222            .expect("an object");
2223        let file = object::File::parse(&bytes[..]).expect("a readable object");
2224
2225        let flags = file.symbols().find(|s| s.name() == Ok("flags")).expect("the thread-local one");
2226        assert!(flags.is_undefined(), "nothing here defines it");
2227        assert_eq!(flags.kind(), SymbolKind::Tls, "which is what the linker refuses to guess");
2228
2229        let shared = file.symbols().find(|s| s.name() == Ok("shared")).expect("the ordinary one");
2230        assert!(shared.is_undefined(), "nothing here defines this one either");
2231        assert_eq!(shared.kind(), SymbolKind::Unknown, "and there is nothing to say about it");
2232    }
2233
2234    /// Not a rewording of the case above: what is checked is the arithmetic between the two.
2235    #[test]
2236    fn a_relocation_counts_from_the_start_of_the_section_and_not_of_the_image_it_is_in() {
2237        let mut data = Data {
2238            apart: Vec::new(),
2239            weak: Vec::new(),
2240            objects: vec![variable("first", Place::Written)],
2241        };
2242        data.objects.push(Object {
2243            bytes: vec![0; 16],
2244            size: 16,
2245            align: 8,
2246            relocs: vec![Reloc {
2247                at: 8,
2248                symbol: "y".to_owned(),
2249                kind: Reference::Address { bytes: 8 },
2250                addend: 0,
2251                after: 0,
2252            }],
2253            ..variable("second", Place::Written)
2254        });
2255        let bytes =
2256            write(&Text::default(), &data, &[], &target(), Output::default(), &Info::default())
2257                .expect("an object");
2258        let file = object::File::parse(&bytes[..]).expect("a readable object");
2259        let section = file.section_by_name(".data").expect("a data section");
2260        let (offset, _) = section.relocations().next().expect("one relocation");
2261        // Eight into the second image, which starts eight in because the first one is four long
2262        // and the second is eight aligned.
2263        assert_eq!(offset, 16);
2264    }
2265
2266    #[test]
2267    fn a_second_name_is_a_second_symbol_at_the_first_one_s_address_and_no_second_image() {
2268        let data = Data {
2269            apart: Vec::new(),
2270            weak: Vec::new(),
2271            objects: vec![Object { binding: Binding::Local, ..variable("a", Place::Written) }],
2272        };
2273        let aliases = [Alias {
2274            name: "b".to_owned(),
2275            target: "a".to_owned(),
2276            binding: Binding::Global,
2277            visibility: Visibility::Default,
2278        }];
2279        let bytes = write(
2280            &Text::default(),
2281            &data,
2282            &aliases,
2283            &target(),
2284            Output::default(),
2285            &Info::default(),
2286        )
2287        .expect("an object");
2288        let file = object::File::parse(&bytes[..]).expect("a readable object");
2289        let a = file.symbols().find(|s| s.name() == Ok("a")).expect("the variable");
2290        let b = file.symbols().find(|s| s.name() == Ok("b")).expect("the second name");
2291        assert_eq!(b.address(), a.address(), "the same place");
2292        assert_eq!(b.size(), a.size());
2293        assert_eq!(b.section_index(), a.section_index());
2294        // The binding is the one thing the second name does not take from the first, which is
2295        // what `extern int b __attribute__((alias("a")))` on a `static a` asks for.
2296        assert!(a.is_local(), "the target was written `static`");
2297        assert!(b.is_global(), "and the name given to it was not");
2298        // Four bytes of image and not eight, since an alias is a name and not a copy.
2299        assert_eq!(file.section_by_name(".data").expect("a data section").size(), 4);
2300    }
2301
2302    #[test]
2303    fn a_function_can_be_given_a_second_name_the_same_way_a_variable_can() {
2304        let text = calling("puts");
2305        let aliases = [Alias {
2306            name: "g".to_owned(),
2307            target: "f".to_owned(),
2308            binding: Binding::Weak,
2309            visibility: Visibility::Default,
2310        }];
2311        let bytes = write(
2312            &text,
2313            &Data::default(),
2314            &aliases,
2315            &target(),
2316            Output::default(),
2317            &Info::default(),
2318        )
2319        .expect("an object");
2320        let file = object::File::parse(&bytes[..]).expect("a readable object");
2321        let f = file.symbols().find(|s| s.name() == Ok("f")).expect("the function");
2322        let g = file.symbols().find(|s| s.name() == Ok("g")).expect("the second name");
2323        assert_eq!(g.address(), f.address());
2324        assert_eq!(g.size(), f.size());
2325        assert_eq!(g.kind(), f.kind(), "a second name for a function is a function");
2326        assert!(g.is_weak(), "so that a program may define the name itself instead");
2327    }
2328
2329    /// The front end is what reports this as a program's mistake, so one arriving here is a bug
2330    /// in this compiler and is said so rather than written as an undefined symbol.
2331    #[test]
2332    fn a_second_name_for_something_this_file_does_not_define_is_refused() {
2333        let aliases = [Alias {
2334            name: "b".to_owned(),
2335            target: "a".to_owned(),
2336            binding: Binding::Global,
2337            visibility: Visibility::Default,
2338        }];
2339        let error = write(
2340            &Text::default(),
2341            &Data::default(),
2342            &aliases,
2343            &target(),
2344            Output::default(),
2345            &Info::default(),
2346        )
2347        .expect_err("nothing to point at");
2348        assert!(matches!(error, Error::Refused { .. }), "{error:?}");
2349    }
2350
2351    #[test]
2352    fn a_platform_this_does_not_write_is_said_so_rather_than_written_as_elf() {
2353        let text = calling("puts");
2354        for triple in [
2355            Triple::new(Arch::Aarch64, Os::Linux, Env::Gnu),
2356            Triple::new(Arch::X86_64, Os::Darwin, Env::Gnu),
2357        ] {
2358            let error = write(
2359                &text,
2360                &Data::default(),
2361                &[],
2362                &TargetInfo::new(triple),
2363                Output::default(),
2364                &Info::default(),
2365            )
2366            .expect_err("no writer");
2367            assert!(matches!(error, Error::Format { .. }), "{error:?}");
2368        }
2369    }
2370
2371    /// What the archive's symbol index is built from is what the linker can find in the member.
2372    ///
2373    /// Written against the object rather than against the list, because the two agreeing is the
2374    /// whole point: a list that says more than the file does is an archive that promises a
2375    /// definition it does not have, and a list that says less is a member nothing pulls out.
2376    #[test]
2377    fn the_names_a_linker_can_find_are_the_names_the_list_gives() {
2378        let mut text = calling("puts");
2379        text.funcs.push(extent("hidden".to_owned(), 16, 1, Binding::Local));
2380        text.funcs.push(extent("shared".to_owned(), 32, 1, Binding::Weak));
2381        text.bytes.resize(33, 0x90);
2382        let data = Data {
2383            apart: Vec::new(),
2384            weak: Vec::new(),
2385            objects: vec![variable("seen", Place::Written), {
2386                let mut quiet = variable("quiet", Place::Zero);
2387                quiet.binding = Binding::Local;
2388                quiet
2389            }],
2390        };
2391        let aliases = [Alias {
2392            name: "second".to_owned(),
2393            target: "f".to_owned(),
2394            binding: Binding::Global,
2395            visibility: Visibility::Default,
2396        }];
2397
2398        let names = defines(&text, &data, &aliases, &target()).expect("a list");
2399        assert_eq!(names, ["f", "shared", "seen", "second"]);
2400
2401        let bytes = write(&text, &data, &aliases, &target(), Output::default(), &Info::default())
2402            .expect("an object");
2403        let file = object::File::parse(&bytes[..]).expect("a readable object");
2404        let found: Vec<String> = file
2405            .symbols()
2406            .filter(|symbol| symbol.is_global() && symbol.is_definition())
2407            .map(|symbol| symbol.name().unwrap_or_default().to_owned())
2408            .collect();
2409        let mut sorted = names.clone();
2410        sorted.sort();
2411        let mut theirs = found;
2412        theirs.sort();
2413        assert_eq!(sorted, theirs, "the list and the file have to say the same thing");
2414    }
2415
2416    /// A windows x86-64 target, which is the other format this writes.
2417    fn windows() -> TargetInfo {
2418        TargetInfo::new(Triple::new(Arch::X86_64, Os::Windows, Env::Gnu))
2419    }
2420
2421    /// What the four bytes a relocation covers hold, which is where COFF keeps its addend.
2422    fn inline(bytes: &[u8], section: &str, at: usize) -> i32 {
2423        let file = object::File::parse(bytes).expect("a readable object");
2424        let found = file.section_by_name(section).expect("the section").data().expect("the bytes");
2425        i32::from_le_bytes(found[at..at + 4].try_into().expect("four bytes"))
2426    }
2427
2428    #[test]
2429    fn a_windows_target_is_written_rather_than_refused() {
2430        let text = calling("puts");
2431        let bytes =
2432            write(&text, &Data::default(), &[], &windows(), Output::default(), &Info::default())
2433                .expect("an object");
2434        let file = object::File::parse(&bytes[..]).expect("a readable object");
2435        assert_eq!(file.format(), BinaryFormat::Coff);
2436        let section = file.section_by_name(".text").expect("a text section");
2437        assert_eq!(section.data().expect("the bytes"), &text.bytes[..]);
2438        let names: Vec<&str> = file.symbols().filter_map(|symbol| symbol.name().ok()).collect();
2439        assert!(names.contains(&"f"), "{names:?}");
2440        assert!(names.contains(&"puts"), "{names:?}");
2441    }
2442
2443    /// The whole reason a relocation carries where the instruction ended as well as the addend.
2444    ///
2445    /// A call ends at the four bytes the linker writes over, and a store of a constant through an
2446    /// address counted from the instruction pointer has the constant after them, and ELF tells the
2447    /// two apart by the addend alone. COFF cannot: it says how far the end is in the relocation type
2448    /// and works the addend out from that, so the same four bytes come out of two different types
2449    /// and both have to end up meaning the same distance.
2450    #[test]
2451    fn how_far_the_instruction_runs_past_the_hole_is_in_the_relocation_type() {
2452        for (after, typ) in [
2453            (0, pe::IMAGE_REL_AMD64_REL32),
2454            (1, pe::IMAGE_REL_AMD64_REL32_1),
2455            (4, pe::IMAGE_REL_AMD64_REL32_4),
2456            (5, pe::IMAGE_REL_AMD64_REL32_5),
2457        ] {
2458            let mut text = calling("puts");
2459            // The same distance every time, said the way ELF says it: from where the four bytes
2460            // start, with everything else folded in.
2461            text.relocs[0].addend = -4 - i64::from(after);
2462            text.relocs[0].after = after;
2463            text.bytes.resize(6 + after as usize, 0x90);
2464            text.funcs[0].len = text.bytes.len();
2465            let bytes = write(
2466                &text,
2467                &Data::default(),
2468                &[],
2469                &windows(),
2470                Output::default(),
2471                &Info::default(),
2472            )
2473            .expect("an object");
2474            let file = object::File::parse(&bytes[..]).expect("a readable object");
2475            let section = file.section_by_name(".text").expect("a text section");
2476            let (_, reloc) = section.relocations().next().expect("the relocation");
2477            assert_eq!(reloc.flags(), RelocationFlags::Coff { typ }, "{after}");
2478            // And the bytes come out holding nothing, because the distance the instruction wants
2479            // and the distance the type already says are the same one.
2480            assert_eq!(inline(&bytes, ".text", 1), 0, "{after}");
2481        }
2482    }
2483
2484    /// The addend a COFF object keeps is in the bytes rather than in the relocation, so the number
2485    /// the caller handed over has to survive the trip through the type.
2486    #[test]
2487    fn a_distance_the_instruction_did_not_ask_for_stays_in_the_bytes() {
2488        let mut text = calling("puts");
2489        text.relocs[0].addend = 12;
2490        let bytes =
2491            write(&text, &Data::default(), &[], &windows(), Output::default(), &Info::default())
2492                .expect("an object");
2493        assert_eq!(inline(&bytes, ".text", 1), 16, "twelve past the end, which is four past here");
2494    }
2495
2496    #[test]
2497    fn an_address_written_into_an_image_is_the_wide_relocation_here_too() {
2498        let object = Object {
2499            bytes: vec![0; 8],
2500            size: 8,
2501            align: 8,
2502            relocs: vec![Reloc {
2503                at: 0,
2504                symbol: "y".to_owned(),
2505                kind: Reference::Address { bytes: 8 },
2506                addend: 0,
2507                after: 0,
2508            }],
2509            ..variable("p", Place::Written)
2510        };
2511        let data = Data { apart: Vec::new(), weak: Vec::new(), objects: vec![object] };
2512        let bytes =
2513            write(&Text::default(), &data, &[], &windows(), Output::default(), &Info::default())
2514                .expect("an object");
2515        let file = object::File::parse(&bytes[..]).expect("a readable object");
2516        let section = file.section_by_name(".data").expect("a data section");
2517        let (_, reloc) = section.relocations().next().expect("the relocation");
2518        let typ = pe::IMAGE_REL_AMD64_ADDR64;
2519        assert_eq!(reloc.flags(), RelocationFlags::Coff { typ });
2520    }
2521
2522    /// `.data.rel.ro` is an ELF answer to a problem this format solves elsewhere, so both halves of
2523    /// it land in ordinary read only data, which is where the platform's own linker puts them.
2524    #[test]
2525    fn a_variable_the_loader_writes_into_is_read_only_data_here() {
2526        for local in [false, true] {
2527            let data = Data {
2528                apart: Vec::new(),
2529                weak: Vec::new(),
2530                objects: vec![variable("p", Place::RelocReadOnly { local })],
2531            };
2532            let bytes = write(
2533                &Text::default(),
2534                &data,
2535                &[],
2536                &windows(),
2537                Output::default(),
2538                &Info::default(),
2539            )
2540            .expect("an object");
2541            let file = object::File::parse(&bytes[..]).expect("a readable object");
2542            assert!(file.section_by_name(".rdata").is_some(), "{local}");
2543            assert!(file.section_by_name(".data.rel.ro.local").is_none(), "{local}");
2544        }
2545    }
2546
2547    /// No marker and no note, because a PE image says both of those things in the header of the
2548    /// finished image rather than in each of its inputs.
2549    #[test]
2550    fn the_sections_only_elf_reads_are_left_out_rather_than_written_empty() {
2551        let text = calling("puts");
2552        let output = Output { property: Property { features: 3 }, ..Output::default() };
2553        let bytes = write(&text, &Data::default(), &[], &windows(), output, &Info::default())
2554            .expect("an object");
2555        let file = object::File::parse(&bytes[..]).expect("a readable object");
2556        assert!(file.section_by_name(".note.GNU-stack").is_none());
2557        assert!(file.section_by_name(".note.gnu.property").is_none());
2558    }
2559
2560    /// Each of these is something this format has no way to write, and writing the nearest thing
2561    /// would be worse than refusing: a thread-local variable written as an ordinary one is one copy
2562    /// where the program asked for one per thread, and a constructor list under a name nothing
2563    /// gathers is a program whose constructors never run.
2564    #[test]
2565    fn what_this_format_cannot_say_is_refused_by_name() {
2566        let ordinary = Text::default();
2567        let empty = Data::default();
2568
2569        let mut thread = Data::default();
2570        thread.objects.push(variable("t", Place::Thread { zero: false }));
2571
2572        let mut gathered = Data::default();
2573        gathered.objects.push(variable("c", Place::Named(".init_array".to_owned())));
2574
2575        let mut table = calling("puts");
2576        table.relocs[0].kind = Reference::Got;
2577
2578        let mut room = calling("puts");
2579        room.funcs[0].patch = Some(Patch { at: 0, before: 0 });
2580
2581        let cases: [(&str, &Text, &Data); 4] = [
2582            ("thread-local", &ordinary, &thread),
2583            ("startup", &ordinary, &gathered),
2584            ("table", &table, &empty),
2585            ("patcher", &room, &empty),
2586        ];
2587        for (what, text, data) in cases {
2588            let error = write(text, data, &[], &windows(), Output::default(), &Info::default())
2589                .expect_err("something this format cannot write");
2590            assert!(matches!(error, Error::Refused { .. }), "{what}: {error:?}");
2591        }
2592    }
2593
2594    /// A visibility is not refused, because there is nothing to refuse: it is a fact about a dynamic
2595    /// symbol table and a COFF symbol has nowhere to keep one, which is what gcc does on the
2596    /// platform as well.
2597    #[test]
2598    fn a_visibility_this_format_cannot_keep_changes_nothing_rather_than_failing() {
2599        let mut text = calling("puts");
2600        text.funcs[0].visibility = Visibility::Hidden;
2601        let bytes =
2602            write(&text, &Data::default(), &[], &windows(), Output::default(), &Info::default())
2603                .expect("an object");
2604        let file = object::File::parse(&bytes[..]).expect("a readable object");
2605        let symbol = file.symbols().find(|symbol| symbol.name() == Ok("f")).expect("the function");
2606        assert!(symbol.is_global(), "a name others may use either way");
2607    }
2608
2609    #[test]
2610    fn the_names_a_linker_can_find_are_the_same_list_on_either_format() {
2611        let text = calling("puts");
2612        let data = Data {
2613            apart: Vec::new(),
2614            weak: Vec::new(),
2615            objects: vec![variable("shared", Place::Written)],
2616        };
2617        let theirs = defines(&text, &data, &[], &windows()).expect("a list");
2618        assert_eq!(theirs, defines(&text, &data, &[], &target()).expect("a list"));
2619    }
2620
2621    /// The same refusal the writer gives, for the reason the function says: an undecorated name is
2622    /// the wrong answer for a format whose symbols carry an underscore, and a wrong index entry is
2623    /// worse than no archive.
2624    #[test]
2625    fn a_platform_this_does_not_write_has_no_list_of_names_either() {
2626        let text = calling("puts");
2627        for triple in [
2628            Triple::new(Arch::Aarch64, Os::Linux, Env::Gnu),
2629            Triple::new(Arch::X86_64, Os::Darwin, Env::Gnu),
2630        ] {
2631            let error = defines(&text, &Data::default(), &[], &TargetInfo::new(triple))
2632                .expect_err("no writer");
2633            assert!(matches!(error, Error::Format { .. }), "{error:?}");
2634        }
2635    }
2636}