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