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::{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, Array, Binding, Data, Info, Object, Output, Place, Property, Reference, Reloc, Sections,
47    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 = std::collections::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    // A second name for something already added, which is where the alias's own binding is the
444    // only thing it does not take from what it points at: the target of one may be a `static` and
445    // the alias of it may not be. Before the loop below rather than after it, because a reference
446    // to the new name is a reference to something this file defines and would otherwise be added
447    // as a name this file wants from somewhere else.
448    for alias in aliases {
449        let Some(&id) = symbols.get(&alias.target) else {
450            let why =
451                format!("'{}' is aliased to '{}', which is not here", alias.name, alias.target);
452            return Err(Error::Refused { why });
453        };
454        let (value, size) = (obj.symbol(id).value, obj.symbol(id).size);
455        let (kind, section) = (obj.symbol(id).kind, obj.symbol(id).section);
456        let id = obj.add_symbol(Symbol {
457            name: alias.name.clone().into_bytes(),
458            value,
459            size,
460            kind,
461            scope: scope_of(alias.binding),
462            weak: alias.binding == Binding::Weak,
463            section,
464            flags: SymbolFlags::None,
465        });
466        flavour.see(&mut obj, id, alias.binding, alias.visibility);
467        symbols.insert(alias.name.clone(), id);
468    }
469
470    // Not the unwind table's, which name functions this file defines and are written against the
471    // section rather than against the name. A record for anything else is refused below, so a name
472    // added here for one would be a name nothing goes on to use.
473    // The names a declaration wrote `weak` on, which the link is allowed to leave undefined and
474    // whose references then read a zero address. The listing writes a `.weak` for each of the same
475    // names, so the two paths put the same entries in whether or not anything refers to one.
476    let weak: HashSet<&str> = data.weak.iter().map(String::as_str).collect();
477    let relocs = || text.relocs.iter().chain(data.objects.iter().flat_map(|o| &o.relocs));
478    // The names something here reaches through the thread pointer, which is the one thing about an
479    // undefined name this file does know. A reference to a thread-local variable is a different kind
480    // of reference from a reference to an ordinary one and the code that makes it is already
481    // different, so the file has been told, and ELF wants the symbol to say so as well.
482    let thread: HashSet<&str> = relocs()
483        .filter(|reloc| reloc.kind == Reference::Thread)
484        .map(|reloc| reloc.symbol.as_str())
485        .collect();
486    let wanted: Vec<&String> =
487        relocs().map(|reloc| &reloc.symbol).chain(data.weak.iter()).collect();
488    for name in wanted {
489        if symbols.contains_key(name) {
490            continue;
491        }
492        let id = obj.add_symbol(Symbol {
493            name: name.clone().into_bytes(),
494            value: 0,
495            size: 0,
496            // What kind of thing an undefined name is is not known here and does not have to be:
497            // a linker resolves an undefined symbol by its name, and the type of one that is not
498            // defined anywhere in this file is nothing this file can say. A thread-local one is the
499            // exception, and the linker makes it one. A reference to a thread-local variable is
500            // satisfied by an offset into a block rather than by an address, so the linker has to
501            // know which of the two it is being asked for before it has found the definition, and it
502            // refuses a link where one file says `STT_TLS` and another does not rather than picking
503            // one. That is tamnd/rucc#1461: libmpfr writes `__gmpfr_flags` in one file and reads it
504            // in a hundred others, and `ld` stopped at the first reader with a mismatch.
505            kind: if thread.contains(name.as_str()) {
506                SymbolKind::Tls
507            } else {
508                SymbolKind::Unknown
509            },
510            scope: SymbolScope::Dynamic,
511            weak: weak.contains(name.as_str()),
512            section: SymbolSection::Undefined,
513            flags: SymbolFlags::None,
514        });
515        symbols.insert(name.clone(), id);
516    }
517
518    for reloc in &text.relocs {
519        // Which function's bytes this one is in, which is the question only the split path has to
520        // ask: when there is one text section every offset in it is already the offset in it.
521        // Every relocation is inside some function, since the padding between two of them is
522        // instructions that do nothing and holds nothing a linker fills in.
523        let (section, at) = if sections.functions {
524            let after = text.funcs.partition_point(|func| func.start <= reloc.at);
525            let Some(func) = after.checked_sub(1).map(|i| &text.funcs[i]) else {
526                let why = format!("a relocation at {} is in front of every function", reloc.at);
527                return Err(Error::Refused { why });
528            };
529            // From the start of the section rather than from the symbol, and the two are not the
530            // same byte in a function with room in front of its label.
531            let base = func.start - func.patch.map_or(0, |patch| patch.before);
532            (split[after - 1].0, (reloc.at - base) as u64)
533        } else {
534            (whole, reloc.at as u64)
535        };
536        add(&mut obj, section, at, reloc, &symbols, flavour)?;
537    }
538
539    // The unwind table, if there is one. Its own section rather than part of the text, because it
540    // is read rather than run: the loader maps it and the linker gathers every input's into one
541    // table and builds the index the unwinder searches.
542    if !text.unwind.bytes.is_empty() {
543        let ((name, align), second) = flavour.tables();
544        let frames = obj.add_section(Vec::new(), name.into(), SectionKind::ReadOnlyData);
545        obj.append_section_data(frames, &text.unwind.bytes, align);
546        // What the rows point at, on the format that keeps the descriptions in a section of their
547        // own, and a name for each of them, because a row reaches one through a relocation and a
548        // relocation names a symbol. The names are never offered to another file: what they point
549        // at is one function's prologue, described for the runtime of this program and nothing else.
550        let mut described = HashMap::new();
551        if !text.unwind.info.is_empty() {
552            let Some((name, align)) = second else {
553                let why = "an unwind table here is one section and it was given two".to_owned();
554                return Err(Error::Refused { why });
555            };
556            let codes = obj.add_section(Vec::new(), name.into(), SectionKind::ReadOnlyData);
557            obj.append_section_data(codes, &text.unwind.info, align);
558            for label in &text.unwind.labels {
559                let id = obj.add_symbol(Symbol {
560                    name: label.name.clone().into_bytes(),
561                    value: label.at as u64,
562                    size: 0,
563                    kind: SymbolKind::Label,
564                    scope: SymbolScope::Compilation,
565                    weak: false,
566                    section: SymbolSection::Section(codes),
567                    flags: SymbolFlags::None,
568                });
569                described.insert(label.name.clone(), id);
570            }
571        }
572        for reloc in &text.unwind.relocs {
573            let (symbol, addend) = match described.get(&reloc.symbol) {
574                // A description in the section above, reached by its own name and needing no
575                // correction, since the name is at the description rather than at the front of the
576                // section it is in.
577                Some(&id) => (id, reloc.addend),
578                // A function, and against the section it is in rather than against its own name,
579                // which is the same reason the record of a patcher's room is written that way and
580                // one more besides. The section is the only one of the two that is settled here: a
581                // global name is answered at load time by whichever object defines it first, so a
582                // distance measured to one is not a distance the linker can work out, and it says
583                // so and stops. The effect was that nothing this compiler wrote could go into a
584                // shared library at all, because every function has a record and every record
585                // pointed at a name.
586                //
587                // A function defined elsewhere has no record here, so the lookup failing means the
588                // record is for something that is not a function in this file, and that is a bug
589                // rather than a shape to handle: the writer says what it was given rather than
590                // guessing.
591                None => {
592                    let found = text.funcs.iter().position(|func| func.name == reloc.symbol);
593                    let Some((section, at)) = found.map(|i| split[i]) else {
594                        let why = format!(
595                            "'{}' has an unwind record and is not a function here",
596                            reloc.symbol
597                        );
598                        return Err(Error::Refused { why });
599                    };
600                    // Where the function starts inside its section, since the section symbol is
601                    // where the section starts and the two are the same byte only for the first
602                    // function in one.
603                    (obj.section_symbol(section), reloc.addend + at as i64)
604                }
605            };
606            let flags = flavour.reloc(reloc.kind, reloc.after).ok_or_else(|| Error::Refused {
607                why: format!("no relocation is {:?}", reloc.kind),
608            })?;
609            let record = Relocation { offset: reloc.at as u64, symbol, addend, flags };
610            obj.add_relocation(frames, record)
611                .map_err(|why| Error::Refused { why: why.to_string() })?;
612        }
613    }
614    // The debug information, if the build asked for any. One section per chunk under the name
615    // DWARF gives it, and none of them allocated: the loader does not map a debug section and
616    // nothing at run time reads one, which is what tells this apart from the unwind table, whose
617    // whole point is that a program walking its own stack can reach it.
618    //
619    // Every section is added before any relocation is, because a relocation in one of them names
620    // another as often as it names a function, and a name is resolved against the sections the
621    // file already has.
622    let mut named = HashMap::new();
623    for chunk in &info.chunks {
624        let id = obj.add_section(Vec::new(), chunk.name.clone().into_bytes(), SectionKind::Debug);
625        obj.append_section_data(id, &chunk.bytes, 1);
626        named.insert(chunk.name.as_str(), id);
627    }
628    for chunk in &info.chunks {
629        let section = named[chunk.name.as_str()];
630        for reloc in &chunk.relocs {
631            let (symbol, addend) = match named.get(reloc.symbol.as_str()) {
632                // Another debug section, reached by its own name. The distance is from the front
633                // of that section, which is what the section symbol is, so the addend stands.
634                Some(&id) => (obj.section_symbol(id), reloc.addend),
635                // A function, and against the section it is in rather than against its own name,
636                // for the reason the unwind table's records are written that way: a global name is
637                // answered at load time by whichever object defines it first, and a distance to
638                // one is not a distance a linker can work out.
639                None => {
640                    let found = text.funcs.iter().position(|func| func.name == reloc.symbol);
641                    let Some((section, at)) = found.map(|i| split[i]) else {
642                        let why = format!(
643                            "'{}' is named by the debug information and is not a function here",
644                            reloc.symbol
645                        );
646                        return Err(Error::Refused { why });
647                    };
648                    (obj.section_symbol(section), reloc.addend + at as i64)
649                }
650            };
651            let flags = flavour.reloc(reloc.kind, reloc.after).ok_or_else(|| Error::Refused {
652                why: format!("no relocation is {:?}", reloc.kind),
653            })?;
654            let record = Relocation { offset: reloc.at as u64, symbol, addend, flags };
655            obj.add_relocation(section, record)
656                .map_err(|why| Error::Refused { why: why.to_string() })?;
657        }
658    }
659    for (object, &(section, offset)) in data.objects.iter().zip(&placed) {
660        let Some(section) = section else { continue };
661        for reloc in &object.relocs {
662            add(&mut obj, section, offset + reloc.at as u64, reloc, &symbols, flavour)?;
663        }
664    }
665
666    // What the file was built to have checked, when it was built to have anything checked. Left
667    // out otherwise rather than written as a zero, because a linker treats a missing note and a
668    // note with no bits in it the same way and gcc writes nothing.
669    flavour.property(&mut obj, property);
670
671    // Written rather than left out, because a linker that does not find it in every input marks
672    // the stack executable, on the format that has one.
673    flavour.marker(&mut obj);
674
675    let mut bytes = obj.write().map_err(|why| Error::Refused { why: why.to_string() })?;
676    flavour.finish(&mut bytes, &ordered);
677    Ok(bytes)
678}
679
680/// Everything in this module the target's format has no way to write, refused by name.
681///
682/// Each of these is something ELF has and COFF does not, and each would otherwise be written as the
683/// nearest thing rather than refused, which is worse: a thread-local variable written as an ordinary
684/// one is a program where every thread shares what the source said each would have its own copy of,
685/// and a constructor list under a name the Windows runtime does not gather is a program whose
686/// constructors never run. A message naming the feature is what the caller turns into a diagnostic,
687/// and the front end refusing first is what stops one ever being seen.
688///
689/// # Errors
690///
691/// [`Error::Refused`], naming the one it found first.
692fn beyond(text: &Text, data: &Data, info: &Info) -> Result<(), Error> {
693    let why = |why: String| Err(Error::Refused { why });
694    if !info.chunks.is_empty() {
695        return why("debug information here goes in sections this writer does not name".to_owned());
696    }
697    if text.funcs.iter().any(|func| func.patch.is_some()) {
698        return why("a record of where a patcher's room is has no section flags here".to_owned());
699    }
700    for reloc in text.relocs.iter().chain(data.objects.iter().flat_map(|object| &object.relocs)) {
701        if matches!(reloc.kind, Reference::Got | Reference::Thread) {
702            return why(format!("nothing reaches '{}' through a table here", reloc.symbol));
703        }
704    }
705    for object in &data.objects {
706        if matches!(object.place, Place::Thread { .. }) {
707            return why(format!("'{}' is thread-local and this format is not", object.name));
708        }
709        let Place::Named(name) = &object.place else { continue };
710        if Array::of(name).is_some() {
711            return why(format!("'{name}' is not a list the startup code here gathers"));
712        }
713    }
714    Ok(())
715}
716
717/// Every name a linker can find in the object [`write()`] would write from the same input.
718///
719/// What asks for this is the archive writer. A static link resolves through the symbol index, so an
720/// index entry has to name a symbol the member really defines: an entry for a name that is not in
721/// the member is an archive the linker searches, pulls the member out of, and then still reports
722/// the name undefined. So the list comes from the writer rather than from the caller, because the
723/// writer is the only thing that knows what it wrote.
724///
725/// The names are as the C program spelled them, with nothing in front of them, which is what both
726/// the formats this writes have on this machine. Mach-O puts an underscore there and so does COFF on
727/// a 32-bit machine, and when either of those is written this is the function that has to say so,
728/// which is why it asks about the target it otherwise would not have to.
729///
730/// Order is the functions, then the variables, then the aliases, each in the order the module held
731/// them, which is the order [`write()`] adds the symbols in. A `static` is left out: it is a name the
732/// link has already finished with by the time an archive is searched, and an index entry for one
733/// would offer the linker a definition it is not allowed to use.
734///
735/// # Errors
736///
737/// [`Error::Format`] for a machine or a platform this does not write, which is the same refusal
738/// [`write()`] gives and is here for the same reason: a list of undecorated names for a format whose
739/// symbols carry an underscore is worse than no list at all.
740pub fn defines(
741    text: &Text,
742    data: &Data,
743    aliases: &[Alias],
744    target: &TargetInfo,
745) -> Result<Vec<String>, Error> {
746    if target.tuple.arch() != Arch::X86_64 || Flavour::of(target).is_none() {
747        return Err(Error::Format { triple: target.tuple.to_string() });
748    }
749    let names = text
750        .funcs
751        .iter()
752        .filter(|func| func.binding != Binding::Local)
753        .map(|func| func.name.clone())
754        .chain(
755            data.objects
756                .iter()
757                .filter(|object| object.binding != Binding::Local)
758                .map(|object| object.name.clone()),
759        )
760        .chain(
761            aliases
762                .iter()
763                .filter(|alias| alias.binding != Binding::Local)
764                .map(|alias| alias.name.clone()),
765        )
766        .collect();
767    Ok(names)
768}
769
770/// One variable's image into the section it belongs in, and where in that section it landed.
771///
772/// A zero filled variable takes as many bytes of the file as it is long on the way in and none on
773/// the way out, which is the whole point of the section it goes in. A merged one goes in no section
774/// at all: the linker is being asked for that much zeroed space under that name, and where it ends
775/// up is the linker's answer rather than this file's.
776fn put(
777    obj: &mut Writer<'_>,
778    object: &Object,
779    named: &mut HashMap<String, object::write::SectionId>,
780    sections: Sections,
781    flavour: Flavour,
782) -> (SymbolSection, u64) {
783    // A section of its own, named after the variable and after the section it would have gone in,
784    // which is what `-fdata-sections` asks for. A merged variable has no section to split and a
785    // named one was named by the program, so both are left where they are: the first is a request
786    // to the linker rather than an image, and the second would otherwise have the flag silently
787    // overrule what the source said.
788    if sections.data {
789        if let Some(name) = object.place.split(&object.name) {
790            let section = obj.add_section(Vec::new(), name.into_bytes(), kind_of(&object.place));
791            let offset = if carries_no_bytes(&object.place) {
792                obj.append_section_bss(section, object.size, object.align)
793            } else {
794                obj.append_section_data(section, &object.bytes, object.align)
795            };
796            return (SymbolSection::Section(section), offset);
797        }
798    }
799    let section = match &object.place {
800        Place::Written => obj.section_id(StandardSection::Data),
801        Place::ReadOnly => obj.section_id(StandardSection::ReadOnlyData),
802        // Read only after the loader has written it, which the writer knows as the relocatable
803        // read only data section and which is `.data.rel.ro` on ELF. The `.local` half is a layout
804        // hint the writer has no name for, so it is added by hand and remembered: asking again
805        // would make a second section with the same name, and a file with one of those per variable
806        // is a file whose section headers outweigh what they describe.
807        Place::RelocReadOnly { local } => match flavour.rel_ro_local().filter(|_| *local) {
808            Some(name) => made(obj, named, name, SectionKind::ReadOnlyDataWithRel),
809            None => obj.section_id(StandardSection::ReadOnlyDataWithRel),
810        },
811        Place::Zero => obj.section_id(StandardSection::UninitializedData),
812        Place::Thread { zero: false } => obj.section_id(StandardSection::Tls),
813        Place::Thread { zero: true } => obj.section_id(StandardSection::UninitializedTls),
814        Place::Merged => return (SymbolSection::Common, 0),
815        // A named section is the program's word for where this goes, and a program that names one
816        // wants what it named rather than what would have been chosen. It is written as ordinary
817        // data because nothing in the IR says otherwise, except for the three names the startup
818        // code calls what it finds in, which have a section type of their own and are gathered by
819        // the linker whether or not they carry it.
820        Place::Named(name) => {
821            let section = made(obj, named, name, SectionKind::Data);
822            if let Some(flags) = Array::of(name).and_then(|array| flavour.gathered(array)) {
823                obj.section_mut(section).flags = flags;
824            }
825            section
826        }
827    };
828    let offset = if carries_no_bytes(&object.place) {
829        obj.append_section_bss(section, object.size, object.align)
830    } else {
831        obj.append_section_data(section, &object.bytes, object.align)
832    };
833    (SymbolSection::Section(section), offset)
834}
835
836/// Whether the section this goes in says how big the variable is and holds none of its bytes.
837///
838/// Two of them, and they are the same answer twice: `.bss` is the image that is all zeros, and
839/// `.tbss` is a thread's own copy of one. A section like this costs its size in the section header
840/// and nothing in the file, which is what keeps a program with a large zeroed array small.
841fn carries_no_bytes(place: &Place) -> bool {
842    matches!(place, Place::Zero | Place::Thread { zero: true })
843}
844
845/// The section of this name, made the first time it is asked for and found afterwards.
846///
847/// Two variables the program put the same section name on belong in one section, the way two in
848/// `.data` do. Asking the writer for a new one each time would make a second header with the same
849/// name, which a linker takes and which makes a file with ten constructors in it carry ten section
850/// headers describing eight bytes each. `section_id` does this already for the sections it has
851/// names of its own for, and this is the same answer for the ones it does not.
852fn made(
853    obj: &mut Writer<'_>,
854    named: &mut HashMap<String, object::write::SectionId>,
855    name: &str,
856    kind: SectionKind,
857) -> object::write::SectionId {
858    if let Some(section) = named.get(name) {
859        return *section;
860    }
861    let section = obj.add_section(Vec::new(), name.as_bytes().to_vec(), kind);
862    named.insert(name.to_owned(), section);
863    section
864}
865
866/// What a section split off for one variable is, which is what the section it was split off from
867/// was.
868///
869/// Splitting changes the name and nothing else. A variable that was going to be in a page the
870/// loader maps read only is still in one, and a zero filled variable still costs the file nothing,
871/// so the flags a linker reads off the section header have to come out the same as they would
872/// have. The two kinds with no section of their own never reach here, and `Data` for them is a
873/// value that is never used rather than a claim about either.
874fn kind_of(place: &Place) -> SectionKind {
875    match place {
876        Place::ReadOnly => SectionKind::ReadOnlyData,
877        Place::RelocReadOnly { .. } => SectionKind::ReadOnlyDataWithRel,
878        Place::Zero => SectionKind::UninitializedData,
879        Place::Thread { zero: false } => SectionKind::Tls,
880        Place::Thread { zero: true } => SectionKind::UninitializedTls,
881        Place::Written | Place::Merged | Place::Named(_) => SectionKind::Data,
882    }
883}
884
885/// One relocation, `at` bytes into the section it ended up in.
886///
887/// The offset is worked out by the caller rather than here, because the two callers count from
888/// different places: a relocation in an image counts from the start of that image and a relocation
889/// in a function counts from the start of that function, and neither of those is where the section
890/// begins once something else is in front of it.
891fn add(
892    obj: &mut Writer<'_>,
893    section: object::write::SectionId,
894    at: u64,
895    reloc: &Reloc,
896    symbols: &std::collections::BTreeMap<String, SymbolId>,
897    flavour: Flavour,
898) -> Result<(), Error> {
899    let flags = flavour
900        .reloc(reloc.kind, reloc.after)
901        .ok_or_else(|| Error::Refused { why: format!("no relocation is {:?}", reloc.kind) })?;
902    obj.add_relocation(
903        section,
904        Relocation { offset: at, symbol: symbols[&reloc.symbol], addend: reloc.addend, flags },
905    )
906    .map_err(|why| Error::Refused { why: why.to_string() })
907}
908
909/// How far a name reaches, which is the one thing about a symbol ELF calls its binding.
910///
911/// `SymbolScope` is two facts in one word, and the trap is that the middle one is not the neutral
912/// answer it reads as. The writer turns `Compilation` into a local symbol, and it turns the choice
913/// between `Linkage` and `Dynamic` into `st_other`: `Linkage` is `STV_HIDDEN` and `Dynamic` is
914/// `STV_DEFAULT`. So there is no way to say global and decline to say anything about visibility,
915/// and picking the one whose name sounds like the smaller claim is picking hidden. That is what
916/// tamnd/rucc#733 was.
917///
918/// `Dynamic` is what every global asks for here, and the visibility is said afterwards by
919/// [`see`] rather than through this, so that nothing about `st_other` depends on reading one of
920/// these four names the way its author meant it.
921pub(crate) fn scope_of(binding: Binding) -> SymbolScope {
922    match binding {
923        Binding::Local => SymbolScope::Compilation,
924        Binding::Global | Binding::Weak => SymbolScope::Dynamic,
925    }
926}
927
928#[cfg(test)]
929mod tests {
930    use super::*;
931
932    use object::read::elf::Sym as _;
933    use object::read::{Object as _, ObjectSection as _, ObjectSymbol as _};
934    use object::{elf, pe};
935    use rucc_target::{Arch, Env, Os, Triple};
936
937    use crate::elf::PATCHABLE;
938    use crate::section::{Extent, Patch, Reloc};
939
940    /// A linux x86-64 target, which is the only one this writes.
941    fn target() -> TargetInfo {
942        TargetInfo::new(Triple::new(Arch::X86_64, Os::Linux, Env::Gnu))
943    }
944
945    /// One function of that name, at that offset, that many bytes long, and visible that far.
946    ///
947    /// Visibility is the field these cases mostly have no opinion about, so it is the one the
948    /// helper fills in and the two that do have an opinion write for themselves.
949    fn extent(name: String, start: usize, len: usize, binding: Binding) -> Extent {
950        Extent {
951            name,
952            start,
953            len,
954            align: crate::FUNC_ALIGN,
955            binding,
956            visibility: Visibility::Default,
957            patch: None,
958        }
959    }
960
961    /// A call to something outside the file, which is the shape every case here starts from.
962    fn calling(name: &str) -> Text {
963        Text {
964            bytes: vec![0xe8, 0, 0, 0, 0, 0xc3],
965            funcs: vec![extent("f".to_owned(), 0, 6, Binding::Global)],
966            relocs: vec![Reloc {
967                at: 1,
968                symbol: name.to_owned(),
969                kind: Reference::Call,
970                addend: -4,
971                after: 0,
972            }],
973            ..Text::default()
974        }
975    }
976
977    #[test]
978    fn the_bytes_come_back_out_of_the_section_they_went_into() {
979        let text = calling("puts");
980        let bytes =
981            write(&text, &Data::default(), &[], &target(), Output::default(), &Info::default())
982                .expect("an object");
983        let file = object::File::parse(&bytes[..]).expect("a readable object");
984        let section = file.section_by_name(".text").expect("a text section");
985        assert_eq!(section.data().expect("the bytes"), &text.bytes[..]);
986    }
987
988    #[test]
989    fn a_function_is_a_symbol_that_says_where_it_is_and_how_long_it_is() {
990        let mut text = calling("puts");
991        text.funcs.push(extent("g".to_owned(), 16, 1, Binding::Global));
992        text.bytes.resize(17, 0x90);
993        let bytes =
994            write(&text, &Data::default(), &[], &target(), Output::default(), &Info::default())
995                .expect("an object");
996        let file = object::File::parse(&bytes[..]).expect("a readable object");
997        let g = file.symbols().find(|s| s.name() == Ok("g")).expect("the second function");
998        assert_eq!(g.address(), 16);
999        assert_eq!(g.size(), 1);
1000        assert_eq!(g.kind(), SymbolKind::Text);
1001        assert!(g.is_global(), "nothing said otherwise about this one");
1002    }
1003
1004    #[test]
1005    fn a_function_no_other_file_can_see_is_a_local_symbol() {
1006        let mut text = calling("puts");
1007        text.funcs.push(extent("hidden".to_owned(), 16, 1, Binding::Local));
1008        text.funcs.push(extent("shared".to_owned(), 32, 1, Binding::Weak));
1009        text.bytes.resize(33, 0x90);
1010        let bytes =
1011            write(&text, &Data::default(), &[], &target(), Output::default(), &Info::default())
1012                .expect("an object");
1013        let file = object::File::parse(&bytes[..]).expect("a readable object");
1014        let hidden = file.symbols().find(|s| s.name() == Ok("hidden")).expect("the static one");
1015        // A symbol the linker keeps and does not let another file reach, which is the whole of
1016        // what `static` on a function means and what two files each defining their own need.
1017        assert!(hidden.is_local(), "a static function must not be offered to the linker");
1018        assert!(!hidden.is_weak());
1019        let shared = file.symbols().find(|s| s.name() == Ok("shared")).expect("the weak one");
1020        assert!(shared.is_weak(), "a weak function has to be able to lose");
1021        assert!(shared.is_global());
1022    }
1023
1024    /// A global is `STV_DEFAULT`, so a shared library built from these objects exports something.
1025    ///
1026    /// The bug in tamnd/rucc#733. Every global came out `STV_HIDDEN`, which a static link does not
1027    /// look at, so nothing here noticed and SQLite linked and ran and the whole test suite passed.
1028    /// What it costs is the dynamic symbol table: `gcc -shared` over one of these objects produced
1029    /// a library with an empty one, and `dlsym` could not find a function the file plainly defines.
1030    ///
1031    /// Written against `st_other` itself rather than against the reader's `scope`, because `scope`
1032    /// is the word that was misread in the first place and a test that asks it the same question
1033    /// would agree with whatever the writer did.
1034    /// The record of where a patcher's room is, and what it says about it.
1035    ///
1036    /// Four things have to be right at once for a linker to take it: the flags, the alignment, the
1037    /// relocation and the section it says it is ordered after. The last of those is the one the
1038    /// writer underneath cannot say, so a zero there would be a file `ld` refuses and a test that
1039    /// only looked at the bytes would not see it.
1040    #[test]
1041    fn where_a_patcher_may_write_is_recorded_in_a_section_tied_to_the_code_it_is_about() {
1042        let mut text = calling("puts");
1043        text.bytes.splice(0..0, [0x90, 0x90, 0x90]);
1044        text.funcs[0].start = 3;
1045        text.funcs[0].patch = Some(Patch { at: 0, before: 3 });
1046        text.relocs[0].at = 4;
1047        let bytes =
1048            write(&text, &Data::default(), &[], &target(), Output::default(), &Info::default())
1049                .expect("an object");
1050        let file = object::read::elf::ElfFile64::<Endianness>::parse(&bytes[..]).expect("readable");
1051        let section = file.section_by_name(PATCHABLE).expect("a record of the room");
1052        assert_eq!(section.size(), 8, "one address, and this file defines one function");
1053        assert_eq!(section.align(), 8);
1054        let header = section.elf_section_header();
1055        assert_eq!(
1056            header.sh_flags.get(Endianness::Little),
1057            elf::SHF_ALLOC | elf::SHF_WRITE | elf::SHF_LINK_ORDER
1058        );
1059        // Which is the whole point of the fixup: the index has to be the text section's own, and
1060        // the writer underneath had written a zero there.
1061        let index = file.section_by_name(".text").expect("a text section").index().0;
1062        assert_eq!(header.sh_link.get(Endianness::Little) as usize, index);
1063        assert_ne!(index, 0);
1064
1065        // And the address, which is the front of the room rather than the function's own symbol.
1066        let [(at, reloc)] = &section.relocations().collect::<Vec<_>>()[..] else {
1067            panic!("one address in the record")
1068        };
1069        assert_eq!(*at, 0);
1070        assert_eq!(reloc.addend(), 0);
1071        assert_eq!(reloc.flags(), RelocationFlags::Elf { r_type: elf::R_X86_64_64 });
1072    }
1073
1074    /// And a file that asked for none has no such section, which is nearly every file.
1075    #[test]
1076    fn a_file_that_promised_a_patcher_nothing_records_nothing() {
1077        let text = calling("puts");
1078        let bytes =
1079            write(&text, &Data::default(), &[], &target(), Output::default(), &Info::default())
1080                .expect("an object");
1081        let file = object::File::parse(&bytes[..]).expect("a readable object");
1082        assert!(file.section_by_name(PATCHABLE).is_none());
1083    }
1084
1085    /// The same when each function is a section of its own, which is what a kernel builds with.
1086    ///
1087    /// Each record then points at a different section, which is what makes the pairing worth
1088    /// asserting: getting it backwards would still produce a file every tool reads and every
1089    /// address in it would be about the wrong function.
1090    #[test]
1091    fn each_record_is_tied_to_its_own_function_when_they_are_split_up() {
1092        let mut text = calling("puts");
1093        text.funcs[0].patch = Some(Patch { at: 0, before: 0 });
1094        text.funcs.push(extent("g".to_owned(), 16, 1, Binding::Global));
1095        text.funcs[1].patch = Some(Patch { at: 16, before: 0 });
1096        text.bytes.resize(17, 0x90);
1097        let output =
1098            Output { sections: Sections { functions: true, data: false }, ..Output::default() };
1099        let bytes = write(&text, &Data::default(), &[], &target(), output, &Info::default())
1100            .expect("an object");
1101        let file = object::read::elf::ElfFile64::<Endianness>::parse(&bytes[..]).expect("readable");
1102        let links: Vec<usize> = file
1103            .sections()
1104            .filter(|section| section.name() == Ok(PATCHABLE))
1105            .map(|section| section.elf_section_header().sh_link.get(Endianness::Little) as usize)
1106            .collect();
1107        let index = |name: &str| file.section_by_name(name).expect("a text section").index().0;
1108        assert_eq!(links, [index(".text.f"), index(".text.g")]);
1109    }
1110
1111    #[test]
1112    fn a_global_is_visible_to_the_dynamic_linker_and_a_static_one_is_not_a_symbol_at_all() {
1113        let mut text = calling("puts");
1114        text.funcs.push(extent("g".to_owned(), 16, 1, Binding::Global));
1115        text.funcs.push(extent("w".to_owned(), 32, 1, Binding::Weak));
1116        text.funcs.push(extent("s".to_owned(), 48, 1, Binding::Local));
1117        text.bytes.resize(49, 0x90);
1118        let bytes =
1119            write(&text, &Data::default(), &[], &target(), Output::default(), &Info::default())
1120                .expect("an object");
1121        let file = object::read::elf::ElfFile64::<Endianness>::parse(&bytes[..]).expect("readable");
1122        let visibility = |name: &str| {
1123            file.symbols()
1124                .find(|s| s.name() == Ok(name))
1125                .expect("the function")
1126                .elf_symbol()
1127                .st_visibility()
1128        };
1129        // Nothing said hidden about either of these, so neither is.
1130        assert_eq!(visibility("g"), elf::STV_DEFAULT);
1131        assert_eq!(visibility("w"), elf::STV_DEFAULT, "a weak one is still a name others may use");
1132        // The `static` one is local, and a local symbol's visibility means nothing either way,
1133        // which is why the binding is what this asks about.
1134        assert_eq!(visibility("s"), elf::STV_DEFAULT);
1135    }
1136
1137    /// And the other direction: a name that did ask to be hidden is hidden, and a protected one is
1138    /// protected.
1139    ///
1140    /// The half of tamnd/rucc#733 that the fix above left open. Saying `STV_DEFAULT` for everything
1141    /// is right for everything nobody marked and wrong the moment something is marked, so the two
1142    /// tests together are what says the field carries an answer rather than a constant.
1143    ///
1144    /// Both are asked of a function and of a variable, because they are added by two different
1145    /// loops in `write` and a field one of them fills in is not a field the other one does.
1146    #[test]
1147    fn a_name_that_asked_to_be_hidden_is_hidden_and_a_protected_one_is_protected() {
1148        let mut text = calling("puts");
1149        for (index, (name, seen)) in
1150            [("h", Visibility::Hidden), ("p", Visibility::Protected)].into_iter().enumerate()
1151        {
1152            let mut func = extent(name.to_owned(), 16 + index * 16, 1, Binding::Global);
1153            func.visibility = seen;
1154            text.funcs.push(func);
1155        }
1156        text.bytes.resize(49, 0x90);
1157        let mut data = Data::default();
1158        for (name, seen) in [("vh", Visibility::Hidden), ("vp", Visibility::Protected)] {
1159            let mut object = variable(name, Place::Written);
1160            object.visibility = seen;
1161            data.objects.push(object);
1162        }
1163        let bytes = write(&text, &data, &[], &target(), Output::default(), &Info::default())
1164            .expect("an object");
1165        let file = object::read::elf::ElfFile64::<Endianness>::parse(&bytes[..]).expect("readable");
1166        let visibility = |name: &str| {
1167            file.symbols()
1168                .find(|s| s.name() == Ok(name))
1169                .expect("the symbol")
1170                .elf_symbol()
1171                .st_visibility()
1172        };
1173        assert_eq!(visibility("h"), elf::STV_HIDDEN);
1174        assert_eq!(visibility("p"), elf::STV_PROTECTED);
1175        assert_eq!(visibility("vh"), elf::STV_HIDDEN, "a variable goes through a second loop");
1176        assert_eq!(visibility("vp"), elf::STV_PROTECTED);
1177        // The one thing a visibility must not disturb, since `st_info` and `st_other` are written
1178        // in one go and the second was set after the first.
1179        let h = file.symbols().find(|s| s.name() == Ok("h")).expect("the function");
1180        assert!(h.is_global(), "hidden is about the dynamic linker and not about the binding");
1181        assert_eq!(h.size(), 1, "and it is still a function of the length it was");
1182    }
1183
1184    #[test]
1185    fn a_name_this_file_does_not_define_is_left_for_the_linker_to_find() {
1186        let bytes = write(
1187            &calling("puts"),
1188            &Data::default(),
1189            &[],
1190            &target(),
1191            Output::default(),
1192            &Info::default(),
1193        )
1194        .expect("an object");
1195        let file = object::File::parse(&bytes[..]).expect("a readable object");
1196        let puts = file.symbols().find(|s| s.name() == Ok("puts")).expect("the callee");
1197        assert!(puts.is_undefined(), "the file does not define it and must not claim to");
1198    }
1199
1200    #[test]
1201    fn a_call_asks_for_the_relocation_a_stub_may_answer_and_a_load_asks_for_the_one_that_may_not() {
1202        for (reference, wanted) in [
1203            (Reference::Call, elf::R_X86_64_PLT32),
1204            (Reference::Data, elf::R_X86_64_PC32),
1205            (Reference::Got, elf::R_X86_64_REX_GOTPCRELX),
1206            (Reference::Thread, elf::R_X86_64_GOTTPOFF),
1207        ] {
1208            let mut text = calling("puts");
1209            text.relocs[0].kind = reference;
1210            let bytes =
1211                write(&text, &Data::default(), &[], &target(), Output::default(), &Info::default())
1212                    .expect("an object");
1213            let file = object::File::parse(&bytes[..]).expect("a readable object");
1214            let section = file.section_by_name(".text").expect("a text section");
1215            let (offset, reloc) = section.relocations().next().expect("one relocation");
1216            assert_eq!(offset, 1);
1217            assert_eq!(reloc.addend(), -4);
1218            assert_eq!(reloc.flags(), RelocationFlags::Elf { r_type: wanted });
1219        }
1220    }
1221
1222    #[test]
1223    fn a_name_wanted_twice_is_one_symbol_rather_than_two() {
1224        let mut text = calling("puts");
1225        text.relocs.push(Reloc {
1226            at: 1,
1227            symbol: "puts".to_owned(),
1228            kind: Reference::Call,
1229            addend: -4,
1230            after: 0,
1231        });
1232        let bytes =
1233            write(&text, &Data::default(), &[], &target(), Output::default(), &Info::default())
1234                .expect("an object");
1235        let file = object::File::parse(&bytes[..]).expect("a readable object");
1236        assert_eq!(file.symbols().filter(|s| s.name() == Ok("puts")).count(), 1);
1237    }
1238
1239    #[test]
1240    fn a_function_that_is_also_called_is_not_a_second_symbol() {
1241        let text = calling("f");
1242        let bytes =
1243            write(&text, &Data::default(), &[], &target(), Output::default(), &Info::default())
1244                .expect("an object");
1245        let file = object::File::parse(&bytes[..]).expect("a readable object");
1246        let mut found = file.symbols().filter(|s| s.name() == Ok("f"));
1247        let f = found.next().expect("the function");
1248        assert!(!f.is_undefined(), "the file defines it");
1249        assert!(found.next().is_none(), "and defines it once");
1250    }
1251
1252    #[test]
1253    fn the_marker_that_says_the_stack_is_not_executable_is_written() {
1254        let bytes = write(
1255            &calling("puts"),
1256            &Data::default(),
1257            &[],
1258            &target(),
1259            Output::default(),
1260            &Info::default(),
1261        )
1262        .expect("an object");
1263        let file = object::File::parse(&bytes[..]).expect("a readable object");
1264        let note = file.section_by_name(".note.GNU-stack").expect("the marker");
1265        assert!(note.data().expect("no bytes").is_empty());
1266    }
1267
1268    /// What the file says it was built to have checked, byte for byte.
1269    ///
1270    /// Written against the bytes rather than against a reader, because the two lengths in the
1271    /// header count the padding after what they measure and a note whose lengths are one word out
1272    /// is one a linker drops without saying anything. What comes of that is a program the loader
1273    /// leaves the check turned off for, which is a build that looks like it worked.
1274    #[test]
1275    fn the_note_that_says_what_the_file_was_built_to_have_checked_is_written() {
1276        let property = Property { features: Property::IBT | Property::SHSTK };
1277        let output = Output { property, ..Output::default() };
1278        let bytes =
1279            write(&calling("puts"), &Data::default(), &[], &target(), output, &Info::default())
1280                .expect("an object");
1281        let file = object::File::parse(&bytes[..]).expect("a readable object");
1282        let note = file.section_by_name(".note.gnu.property").expect("the note");
1283        assert_eq!(note.align(), 8, "a note in a sixty four bit object is read a word at a time");
1284        let want: Vec<u8> = [
1285            4u32,
1286            16,
1287            5,
1288            u32::from_le_bytes(*b"GNU\0"),
1289            Property::X86_FEATURES,
1290            4,
1291            Property::IBT | Property::SHSTK,
1292            0,
1293        ]
1294        .iter()
1295        .flat_map(|word| word.to_le_bytes())
1296        .collect();
1297        assert_eq!(note.data().expect("the bytes"), &want[..]);
1298    }
1299
1300    /// And nothing at all when the file was built to have nothing checked.
1301    ///
1302    /// A note with an empty feature word and no note are the same thing to a linker, which drops
1303    /// the whole property when any input lacks it. gcc writes nothing, so a section header that
1304    /// describes nothing would be the one difference between the two compilers' objects.
1305    #[test]
1306    fn a_file_built_to_have_nothing_checked_says_nothing() {
1307        let bytes = write(
1308            &calling("puts"),
1309            &Data::default(),
1310            &[],
1311            &target(),
1312            Output::default(),
1313            &Info::default(),
1314        )
1315        .expect("an object");
1316        let file = object::File::parse(&bytes[..]).expect("a readable object");
1317        assert!(file.section_by_name(".note.gnu.property").is_none());
1318    }
1319
1320    /// Every unwind record names the function it is about, and each name goes where it is in the
1321    /// table rather than at the start of it.
1322    ///
1323    /// Written because working the offset out is the caller's job here, which is what the two text
1324    /// paths differ about, and a third caller that let it default to nothing would put every record
1325    /// in the table on the same function. Nothing else would notice: the section is the right
1326    /// length, the symbols are right, the link succeeds, and what comes of it is an unwinder that
1327    /// walks out of the wrong frame the first time something throws or a backtrace is taken.
1328    #[test]
1329    fn an_unwind_record_names_the_function_it_is_about_and_not_the_first_one() {
1330        let mut text = calling("puts");
1331        text.funcs.push(extent("g".to_owned(), 16, 1, Binding::Global));
1332        text.bytes.resize(17, 0x90);
1333        // A shared header and two records, whose contents nothing here reads: what is being asked
1334        // is where in them each name landed.
1335        text.unwind.bytes = vec![0; 64];
1336        for (at, name) in [(32usize, "f"), (48usize, "g")] {
1337            text.unwind.relocs.push(Reloc {
1338                at,
1339                symbol: name.to_owned(),
1340                kind: Reference::Address { bytes: 8 },
1341                addend: 0,
1342                after: 0,
1343            });
1344        }
1345        let bytes =
1346            write(&text, &Data::default(), &[], &target(), Output::default(), &Info::default())
1347                .expect("an object");
1348        let file = object::File::parse(&bytes[..]).expect("a readable object");
1349        let mut found = points_at(&file);
1350        found.sort_unstable();
1351        assert_eq!(found, [(32, ".text".to_owned(), 0), (48, ".text".to_owned(), 16)]);
1352    }
1353
1354    /// What each record in the unwind table points at: where it is, the section it reaches, and
1355    /// how far into that section the function it is about begins.
1356    fn points_at(file: &object::File<'_>) -> Vec<(u64, String, i64)> {
1357        let frames = file.section_by_name(".eh_frame").expect("the table");
1358        frames
1359            .relocations()
1360            .map(|(offset, reloc)| {
1361                let object::RelocationTarget::Symbol(index) = reloc.target() else {
1362                    panic!("a record points at something that is not a symbol");
1363                };
1364                let symbol = file.symbol_by_index(index).expect("a symbol that is in the table");
1365                assert_eq!(symbol.kind(), SymbolKind::Section, "a record names a section");
1366                let section = symbol.section_index().expect("a section symbol is in one");
1367                let name = file.section_by_index(section).expect("a readable section");
1368                (offset, name.name().expect("a named section").to_owned(), reloc.addend())
1369            })
1370            .collect()
1371    }
1372
1373    /// A record points at the section its function is in rather than at the function's name.
1374    ///
1375    /// Written for tamnd/rucc#1004, which was that nothing this compiler wrote could go into a
1376    /// shared library. A global name is answered at load time by whichever object defines it
1377    /// first, so the distance from a record to one of them is not a distance a static linker can
1378    /// work out, and `ld` says so and stops with advice to recompile with the flag that was
1379    /// already on the command line. A section is settled by then, which is why gcc measures to a
1380    /// local label and why this measures to the section.
1381    ///
1382    /// Both ways of splitting the text, because the offset is the part that differs: one section
1383    /// holding everything makes it the function's place in the whole text, and a section per
1384    /// function makes it whatever room a patcher was promised in front of the label.
1385    #[test]
1386    fn a_record_reaches_its_function_through_the_section_it_is_in() {
1387        let mut text = two();
1388        text.unwind.bytes = vec![0; 64];
1389        for (at, name) in [(32usize, "f"), (48usize, "g")] {
1390            text.unwind.relocs.push(Reloc {
1391                at,
1392                symbol: name.to_owned(),
1393                kind: Reference::Data,
1394                addend: 0,
1395                after: 0,
1396            });
1397        }
1398        let bytes =
1399            write(&text, &Data::default(), &[], &target(), Output::default(), &Info::default())
1400                .expect("an object");
1401        let file = object::File::parse(&bytes[..]).expect("a readable object");
1402        let mut whole = points_at(&file);
1403        whole.sort_unstable();
1404        assert_eq!(whole, [(32, ".text".to_owned(), 0), (48, ".text".to_owned(), 16)]);
1405
1406        let sections =
1407            Output { sections: Sections { functions: true, data: false }, ..Output::default() };
1408        let bytes = write(&text, &Data::default(), &[], &target(), sections, &Info::default())
1409            .expect("an object");
1410        let file = object::File::parse(&bytes[..]).expect("a readable object");
1411        let mut split = points_at(&file);
1412        split.sort_unstable();
1413        assert_eq!(split, [(32, ".text.f".to_owned(), 0), (48, ".text.g".to_owned(), 0)]);
1414    }
1415
1416    /// A record about a name this file does not define is refused rather than written.
1417    ///
1418    /// There is no such file today: the table is built beside the text out of the functions that
1419    /// were just compiled. It is refused rather than left to the linker because the alternative is
1420    /// the shape that was just fixed, a record measured to a name, and the writer saying what it
1421    /// was given is how that stays fixed.
1422    #[test]
1423    fn a_record_about_something_this_file_does_not_define_is_refused() {
1424        let mut text = calling("puts");
1425        text.unwind.bytes = vec![0; 64];
1426        text.unwind.relocs.push(Reloc {
1427            at: 32,
1428            symbol: "puts".to_owned(),
1429            kind: Reference::Data,
1430            addend: 0,
1431            after: 0,
1432        });
1433        let why =
1434            write(&text, &Data::default(), &[], &target(), Output::default(), &Info::default())
1435                .expect_err("a record about a name from somewhere else");
1436        assert!(why.to_string().contains("puts"), "{why}");
1437    }
1438
1439    /// The name of the section that symbol is defined in.
1440    fn lives_in<'a>(file: &'a object::File<'a>, name: &str) -> String {
1441        let symbol = file.symbols().find(|s| s.name() == Ok(name)).expect("the symbol");
1442        let index = symbol.section_index().expect("a section to be defined in");
1443        let section = file.section_by_index(index).expect("a readable section");
1444        section.name().expect("a named section").to_owned()
1445    }
1446
1447    /// Two functions, the second of them sixteen bytes in and calling something outside the file.
1448    fn two() -> Text {
1449        let mut text = calling("puts");
1450        // Padded to where the second one is aligned to, with the instruction that does nothing,
1451        // because the space in front of a function is reached by falling off the end of one.
1452        text.bytes.resize(16, 0x90);
1453        text.bytes.extend_from_slice(&[0xe8, 0, 0, 0, 0, 0xc3]);
1454        text.funcs.push(extent("g".to_owned(), 16, 6, Binding::Global));
1455        text.relocs.push(Reloc {
1456            at: 17,
1457            symbol: "puts".to_owned(),
1458            kind: Reference::Call,
1459            addend: -4,
1460            after: 0,
1461        });
1462        text
1463    }
1464
1465    /// What `-ffunction-sections` comes down to in an object file, which is the flag that makes
1466    /// `--gc-sections` able to drop anything: a linker can leave out a section nothing reaches and
1467    /// cannot leave out half of one.
1468    ///
1469    /// The empty `.text` stays, because it is the section the writer underneath opens a file with
1470    /// and gcc 16 leaves an empty one behind under the flag too.
1471    #[test]
1472    fn every_function_gets_a_section_of_its_own_when_that_is_what_was_asked_for() {
1473        let sections =
1474            Output { sections: Sections { functions: true, data: false }, ..Output::default() };
1475        let bytes = write(&two(), &Data::default(), &[], &target(), sections, &Info::default())
1476            .expect("an object");
1477        let file = object::File::parse(&bytes[..]).expect("a readable object");
1478        assert_eq!(lives_in(&file, "f"), ".text.f");
1479        assert_eq!(lives_in(&file, "g"), ".text.g");
1480        assert!(file.section_by_name(".text").expect("the empty one").size() == 0);
1481        // Each one at nothing into its own section, and as long as it was: a function alone in a
1482        // section starts where the section does, whatever it started at when they shared one.
1483        for name in ["f", "g"] {
1484            let symbol = file.symbols().find(|s| s.name() == Ok(name)).expect("the function");
1485            assert_eq!(symbol.address(), 0, "{name}");
1486            assert_eq!(symbol.size(), 6, "{name}");
1487        }
1488        let section = file.section_by_name(".text.g").expect("the second function");
1489        assert_eq!(section.data().expect("the bytes"), &[0xe8, 0, 0, 0, 0, 0xc3]);
1490        // The padding between the two is gone with them, since it was there to align the second
1491        // one inside a section they shared and each section is aligned by the linker now.
1492        assert_eq!(section.align(), u64::from(crate::FUNC_ALIGN));
1493    }
1494
1495    /// A relocation counts from the start of whichever section its function ended up in, which is
1496    /// the arithmetic the split path has to do and the unsplit one never does.
1497    ///
1498    /// Getting it wrong is a call patched over the wrong bytes, which assembles, links, and jumps
1499    /// into the middle of an instruction at run time.
1500    #[test]
1501    fn a_relocation_moves_with_the_function_whose_bytes_it_is_in() {
1502        let sections =
1503            Output { sections: Sections { functions: true, data: false }, ..Output::default() };
1504        let bytes = write(&two(), &Data::default(), &[], &target(), sections, &Info::default())
1505            .expect("an object");
1506        let file = object::File::parse(&bytes[..]).expect("a readable object");
1507        for name in [".text.f", ".text.g"] {
1508            let section = file.section_by_name(name).expect("a function");
1509            let (offset, _) = section.relocations().next().expect("the call in it");
1510            // One byte in either way, because the call is the first instruction of both and the
1511            // opcode is one byte in front of the address the linker fills in.
1512            assert_eq!(offset, 1, "{name}");
1513            assert_eq!(section.relocations().count(), 1, "{name}");
1514        }
1515    }
1516
1517    /// One variable of four bytes, in whichever section its own answer puts it.
1518    fn variable(name: &str, place: Place) -> Object {
1519        Object {
1520            name: name.to_owned(),
1521            bytes: if carries_no_bytes(&place) { Vec::new() } else { vec![1, 0, 0, 0] },
1522            size: 4,
1523            align: 4,
1524            place,
1525            binding: Binding::Global,
1526            visibility: Visibility::Default,
1527            relocs: Vec::new(),
1528        }
1529    }
1530
1531    /// A file of that one variable and nothing else.
1532    fn holding(object: Object) -> Vec<u8> {
1533        let data = Data { weak: Vec::new(), objects: vec![object] };
1534        write(&Text::default(), &data, &[], &target(), Output::default(), &Info::default())
1535            .expect("an object")
1536    }
1537
1538    #[test]
1539    fn what_a_variable_is_decides_which_section_it_goes_in() {
1540        for (place, wanted) in [
1541            (Place::Written, ".data"),
1542            (Place::ReadOnly, ".rodata"),
1543            (Place::RelocReadOnly { local: false }, ".data.rel.ro"),
1544            (Place::RelocReadOnly { local: true }, ".data.rel.ro.local"),
1545            (Place::Zero, ".bss"),
1546            (Place::Thread { zero: false }, ".tdata"),
1547            (Place::Thread { zero: true }, ".tbss"),
1548            (Place::Named(".init_array".to_owned()), ".init_array"),
1549        ] {
1550            let bytes = holding(variable("x", place.clone()));
1551            let file = object::File::parse(&bytes[..]).expect("a readable object");
1552            let section = file.section_by_name(wanted).unwrap_or_else(|| panic!("{place:?}"));
1553            assert_eq!(section.size(), 4, "{place:?}");
1554            // The zero filled one is as long as it says and carries none of it, which is the
1555            // whole reason the section exists.
1556            let carried = section.data().expect("the bytes").len();
1557            assert_eq!(carried, if carries_no_bytes(&place) { 0 } else { 4 }, "{place:?}");
1558        }
1559    }
1560
1561    /// The section is half of it and the symbol is the other half.
1562    ///
1563    /// A linker checks a relocation against the kind of the symbol it names, so a variable that is
1564    /// in `.tdata` and is an ordinary data symbol is one an ordinary reference resolves to an
1565    /// address that belongs to no thread. `STT_TLS` is what makes that reference an error instead.
1566    #[test]
1567    fn a_thread_local_variable_is_a_thread_local_symbol_and_not_only_a_thread_local_section() {
1568        for place in [Place::Thread { zero: false }, Place::Thread { zero: true }] {
1569            let bytes = holding(variable("counter", place.clone()));
1570            let file = object::File::parse(&bytes[..]).expect("a readable object");
1571            let symbol = file
1572                .symbols()
1573                .find(|symbol| symbol.name() == Ok("counter"))
1574                .unwrap_or_else(|| panic!("{place:?}"));
1575            assert_eq!(symbol.kind(), SymbolKind::Tls, "{place:?}");
1576        }
1577    }
1578
1579    /// The section type a startup list carries, which is what makes the CRT call what is in it.
1580    ///
1581    /// A section of the ordinary type with the right name is gathered by the linker in the same run
1582    /// and called by nobody, so the type is the whole of what this is about. The numbered name is
1583    /// the same kind of section as the plain one: the number is there so that the linker sorts it.
1584    #[test]
1585    fn a_section_of_function_addresses_carries_the_type_the_runtime_looks_for() {
1586        for (name, wanted) in [
1587            (".init_array", elf::SHT_INIT_ARRAY),
1588            (".init_array.00101", elf::SHT_INIT_ARRAY),
1589            (".fini_array", elf::SHT_FINI_ARRAY),
1590            (".preinit_array", elf::SHT_PREINIT_ARRAY),
1591            (".init_arrays", elf::SHT_PROGBITS),
1592        ] {
1593            let bytes = holding(variable("x", Place::Named(name.to_owned())));
1594            let file = object::File::parse(&bytes[..]).expect("a readable object");
1595            let section = file.section_by_name(name).unwrap_or_else(|| panic!("{name}"));
1596            let SectionFlags::Elf { sh_type, sh_flags } = section.flags() else {
1597                panic!("{name} is not an elf section");
1598            };
1599            assert_eq!(sh_type, wanted, "{name}");
1600            assert!(sh_flags.contains(elf::SHF_ALLOC | elf::SHF_WRITE), "{name}");
1601        }
1602    }
1603
1604    /// Two variables the program put one section name on, which belong in one section.
1605    ///
1606    /// A file with ten constructors in it would otherwise carry ten section headers describing eight
1607    /// bytes each, and the order the entries run in would be the order the linker happened to put
1608    /// the headers in rather than the order they were written.
1609    #[test]
1610    fn two_variables_in_one_named_section_share_it() {
1611        let objects = vec![
1612            variable("x", Place::Named(".init_array".to_owned())),
1613            variable("y", Place::Named(".init_array".to_owned())),
1614        ];
1615        let data = Data { weak: Vec::new(), objects };
1616        let bytes =
1617            write(&Text::default(), &data, &[], &target(), Output::default(), &Info::default())
1618                .expect("an object");
1619        let file = object::File::parse(&bytes[..]).expect("a readable object");
1620        let named: Vec<_> =
1621            file.sections().filter(|section| section.name() == Ok(".init_array")).collect();
1622        assert_eq!(named.len(), 1);
1623        assert_eq!(named[0].size(), 8);
1624    }
1625
1626    /// What `-fdata-sections` comes down to in an object file: the section a variable would have
1627    /// shared, with its own name after it. The names are gcc 16's, checked against it on a Linux
1628    /// host, and the part in front of the dot is what a linker script and `--gc-sections` match on.
1629    #[test]
1630    fn every_variable_gets_a_section_of_its_own_when_that_is_what_was_asked_for() {
1631        let sections =
1632            Output { sections: Sections { functions: false, data: true }, ..Output::default() };
1633        for (place, wanted) in [
1634            (Place::Written, ".data.x"),
1635            (Place::ReadOnly, ".rodata.x"),
1636            (Place::RelocReadOnly { local: false }, ".data.rel.ro.x"),
1637            (Place::RelocReadOnly { local: true }, ".data.rel.ro.local.x"),
1638            (Place::Zero, ".bss.x"),
1639            (Place::Thread { zero: false }, ".tdata.x"),
1640            (Place::Thread { zero: true }, ".tbss.x"),
1641        ] {
1642            let data = Data { weak: Vec::new(), objects: vec![variable("x", place.clone())] };
1643            let bytes = write(&Text::default(), &data, &[], &target(), sections, &Info::default())
1644                .expect("object");
1645            let file = object::File::parse(&bytes[..]).expect("a readable object");
1646            assert_eq!(lives_in(&file, "x"), wanted, "{place:?}");
1647            let section = file.section_by_name(wanted).expect("the section it named");
1648            assert_eq!(section.size(), 4, "{place:?}");
1649            // Which page it lands in is what the section it came out of decided, and splitting
1650            // must not quietly change it: the zero filled one still carries none of its bytes.
1651            let carried = section.data().expect("the bytes").len();
1652            assert_eq!(carried, if carries_no_bytes(&place) { 0 } else { 4 }, "{place:?}");
1653        }
1654    }
1655
1656    /// The two kinds of variable the flag leaves alone. A tentative definition is a request to the
1657    /// linker for that much zeroed space rather than an image, so there is no section to split off,
1658    /// and one the program named has the answer the source gave, which a flag must not overrule.
1659    #[test]
1660    fn a_variable_that_has_no_section_of_its_own_to_be_given_is_left_where_it_was() {
1661        let sections =
1662            Output { sections: Sections { functions: false, data: true }, ..Output::default() };
1663        let named = Place::Named(".init_array".to_owned());
1664        let objects = vec![variable("m", Place::Merged), variable("n", named)];
1665        let bytes = write(
1666            &Text::default(),
1667            &Data { weak: Vec::new(), objects },
1668            &[],
1669            &target(),
1670            sections,
1671            &Info::default(),
1672        )
1673        .expect("object");
1674        let file = object::File::parse(&bytes[..]).expect("a readable object");
1675        let m = file.symbols().find(|s| s.name() == Ok("m")).expect("the tentative one");
1676        assert!(m.is_common(), "still the linker's to merge and not in a section at all");
1677        assert_eq!(lives_in(&file, "n"), ".init_array");
1678        assert!(file.section_by_name(".init_array.n").is_none(), "the source already answered");
1679    }
1680
1681    /// A relocation in a variable's image counts from the start of the section it ended up in, the
1682    /// same question the split text has to answer and a shorter answer: a variable alone in a
1683    /// section starts where the section does.
1684    #[test]
1685    fn a_relocation_in_an_image_moves_with_the_variable_whose_image_it_is_in() {
1686        let sections =
1687            Output { sections: Sections { functions: false, data: true }, ..Output::default() };
1688        let pointer = Object {
1689            bytes: vec![0; 8],
1690            size: 8,
1691            align: 8,
1692            relocs: vec![Reloc {
1693                at: 0,
1694                symbol: "y".to_owned(),
1695                kind: Reference::Address { bytes: 8 },
1696                addend: 0,
1697                after: 0,
1698            }],
1699            ..variable("p", Place::Written)
1700        };
1701        let objects = vec![variable("first", Place::Written), pointer];
1702        let bytes = write(
1703            &Text::default(),
1704            &Data { weak: Vec::new(), objects },
1705            &[],
1706            &target(),
1707            sections,
1708            &Info::default(),
1709        )
1710        .expect("object");
1711        let file = object::File::parse(&bytes[..]).expect("a readable object");
1712        let section = file.section_by_name(".data.p").expect("the pointer's own section");
1713        let (offset, reloc) = section.relocations().next().expect("one relocation");
1714        // Nothing rather than the eight it would be if the variable in front of it were still
1715        // counted, which is what a section of its own means.
1716        assert_eq!(offset, 0);
1717        assert_eq!(reloc.flags(), RelocationFlags::Elf { r_type: elf::R_X86_64_64 });
1718    }
1719
1720    /// Two variables that want `.data.rel.ro.local` end up in one section, not two of one name.
1721    ///
1722    /// The writer has no name of its own for that section, so it is added by hand, and asking for
1723    /// it again makes a second section rather than handing back the first. SQLite has enough const
1724    /// tables of function pointers in it to turn that into eighty odd sections in one object, each
1725    /// with its own relocation section beside it, which is a pile of section headers describing
1726    /// eight bytes apiece.
1727    #[test]
1728    fn every_variable_that_wants_the_local_relocated_section_shares_one() {
1729        let place = Place::RelocReadOnly { local: true };
1730        let data = Data {
1731            weak: Vec::new(),
1732            objects: vec![variable("first", place.clone()), variable("second", place)],
1733        };
1734        let bytes =
1735            write(&Text::default(), &data, &[], &target(), Output::default(), &Info::default())
1736                .expect("an object");
1737        let file = object::File::parse(&bytes[..]).expect("a readable object");
1738        let named = file.sections().filter(|s| s.name() == Ok(".data.rel.ro.local")).count();
1739        assert_eq!(named, 1, "one section holding both, not one each");
1740    }
1741
1742    #[test]
1743    fn a_variable_is_a_symbol_that_says_where_it_is_and_how_long_it_is() {
1744        let mut data = Data { weak: Vec::new(), objects: vec![variable("first", Place::Written)] };
1745        data.objects.push(Object { align: 16, ..variable("second", Place::Written) });
1746        let bytes =
1747            write(&Text::default(), &data, &[], &target(), Output::default(), &Info::default())
1748                .expect("an object");
1749        let file = object::File::parse(&bytes[..]).expect("a readable object");
1750        let second = file.symbols().find(|s| s.name() == Ok("second")).expect("the second one");
1751        assert_eq!(second.kind(), SymbolKind::Data);
1752        assert_eq!(second.size(), 4);
1753        // Sixteen rather than four, because the second one asked for sixteen and the first one
1754        // had already used four. Getting this wrong is a variable at an address it said it would
1755        // never be at, which nothing downstream would notice until an aligned load faulted.
1756        assert_eq!(second.address(), 16);
1757    }
1758
1759    #[test]
1760    fn the_linkage_a_variable_had_is_the_binding_the_symbol_gets() {
1761        for (binding, global, weak) in [
1762            (Binding::Global, true, false),
1763            (Binding::Local, false, false),
1764            (Binding::Weak, true, true),
1765        ] {
1766            let bytes = holding(Object { binding, ..variable("x", Place::Written) });
1767            let file = object::File::parse(&bytes[..]).expect("a readable object");
1768            let x = file.symbols().find(|s| s.name() == Ok("x")).expect("the variable");
1769            assert_eq!(x.is_global(), global, "{binding:?}");
1770            assert_eq!(x.is_weak(), weak, "{binding:?}");
1771        }
1772    }
1773
1774    #[test]
1775    fn a_tentative_definition_asks_the_linker_for_space_rather_than_naming_any() {
1776        let bytes = holding(Object { align: 8, ..variable("x", Place::Merged) });
1777        let file = object::read::elf::ElfFile64::<Endianness>::parse(&bytes[..]).expect("readable");
1778        let x = file.symbols().find(|s| s.name() == Ok("x")).expect("the variable");
1779        assert!(x.is_common(), "the linker merges every definition of this name into one");
1780        assert_eq!(x.size(), 4);
1781        // What a common symbol records where an ordinary one records its address is what it wants
1782        // to be aligned to, because it has no address yet. The reader deliberately answers nothing
1783        // when asked for the address of one, so this is the field itself.
1784        assert_eq!(x.address(), 0);
1785        assert_eq!(x.elf_symbol().st_value(Endianness::Little), 8);
1786    }
1787
1788    #[test]
1789    fn an_address_in_an_image_is_the_address_and_not_a_distance_to_it() {
1790        let object = Object {
1791            bytes: vec![0; 8],
1792            size: 8,
1793            align: 8,
1794            relocs: vec![Reloc {
1795                at: 0,
1796                symbol: "y".to_owned(),
1797                kind: Reference::Address { bytes: 8 },
1798                addend: 16,
1799                after: 0,
1800            }],
1801            ..variable("p", Place::Written)
1802        };
1803        let bytes = holding(object);
1804        let file = object::File::parse(&bytes[..]).expect("a readable object");
1805        let section = file.section_by_name(".data").expect("a data section");
1806        let (offset, reloc) = section.relocations().next().expect("one relocation");
1807        assert_eq!(offset, 0);
1808        assert_eq!(reloc.addend(), 16);
1809        assert_eq!(reloc.flags(), RelocationFlags::Elf { r_type: elf::R_X86_64_64 });
1810        let y = file.symbols().find(|s| s.name() == Ok("y")).expect("what it points at");
1811        assert!(y.is_undefined(), "nothing here defines it and the linker is being asked for it");
1812    }
1813
1814    /// A name a declaration wrote `weak` on is undefined and may stay that way.
1815    ///
1816    /// The difference between this and the case above is one bit and the whole of what a link does
1817    /// about it: an ordinary undefined symbol is a name the linker has to find, and a weak one is a
1818    /// name it may fail to find, in which case every reference reads a zero address. That is what
1819    /// lets a library offer a hook a profiler may fill in, which is tamnd/rucc#1414.
1820    #[test]
1821    fn a_weak_undefined_name_is_one_the_link_may_leave_unfound() {
1822        let mut text = Text::default();
1823        text.funcs.push(extent("caller".to_owned(), 0, 8, Binding::Global));
1824        text.bytes.resize(8, 0x90);
1825        text.relocs.push(Reloc {
1826            at: 1,
1827            symbol: "hook".to_owned(),
1828            kind: Reference::Call,
1829            addend: -4,
1830            after: 0,
1831        });
1832        let data =
1833            Data { weak: vec!["hook".to_owned(), "never_called".to_owned()], objects: vec![] };
1834        let bytes = write(&text, &data, &[], &target(), Output::default(), &Info::default())
1835            .expect("an object");
1836        let file = object::File::parse(&bytes[..]).expect("a readable object");
1837
1838        let hook = file.symbols().find(|s| s.name() == Ok("hook")).expect("the one called");
1839        assert!(hook.is_undefined(), "nothing here defines it");
1840        assert!(hook.is_weak(), "so the link may leave it alone rather than fail");
1841
1842        // And one nothing refers to is still written down, because the listing writes a directive
1843        // for it and the two paths have to put the same entries in. A linker has nothing to do
1844        // about an undefined weak symbol no relocation names.
1845        let quiet = file.symbols().find(|s| s.name() == Ok("never_called")).expect("the other");
1846        assert!(quiet.is_undefined() && quiet.is_weak(), "{:?}", quiet.flags());
1847    }
1848
1849    /// A name this file reads through the thread pointer is undefined and is still known to be
1850    /// thread-local.
1851    ///
1852    /// The other undefined names here are written with no type at all, because a name this file does
1853    /// not define is a name this file has nothing to say about. A thread-local one is different in
1854    /// the one way that counts: a reference to it is satisfied by an offset into a block rather than
1855    /// by an address, so the linker has to know which of the two is wanted before it has found the
1856    /// definition, and rather than guess it refuses a link where one file says `STT_TLS` about a name
1857    /// and another does not. Writing the type is not extra information, it is the same information
1858    /// the relocation already carried, said where the linker looks for it.
1859    ///
1860    /// That is tamnd/rucc#1461. libmpfr defines `__gmpfr_flags` in `exceptions.c` and reads it in a
1861    /// hundred other files, and the link stopped at the first reader with `TLS definition in
1862    /// exceptions.o section .tdata mismatches non-TLS reference in add.o`.
1863    #[test]
1864    fn a_thread_local_name_this_file_only_reads_is_still_written_down_as_thread_local() {
1865        let mut text = Text::default();
1866        text.funcs.push(extent("reader".to_owned(), 0, 16, Binding::Global));
1867        text.bytes.resize(16, 0x90);
1868        text.relocs.push(Reloc {
1869            at: 3,
1870            symbol: "flags".to_owned(),
1871            kind: Reference::Thread,
1872            addend: -4,
1873            after: 0,
1874        });
1875        // One of them reached the ordinary way, so that what the type says is the relocation's doing
1876        // and not something every undefined name here would have got.
1877        text.relocs.push(Reloc {
1878            at: 10,
1879            symbol: "shared".to_owned(),
1880            kind: Reference::Got,
1881            addend: -4,
1882            after: 0,
1883        });
1884        let data = Data { weak: Vec::new(), objects: vec![] };
1885        let bytes = write(&text, &data, &[], &target(), Output::default(), &Info::default())
1886            .expect("an object");
1887        let file = object::File::parse(&bytes[..]).expect("a readable object");
1888
1889        let flags = file.symbols().find(|s| s.name() == Ok("flags")).expect("the thread-local one");
1890        assert!(flags.is_undefined(), "nothing here defines it");
1891        assert_eq!(flags.kind(), SymbolKind::Tls, "which is what the linker refuses to guess");
1892
1893        let shared = file.symbols().find(|s| s.name() == Ok("shared")).expect("the ordinary one");
1894        assert!(shared.is_undefined(), "nothing here defines this one either");
1895        assert_eq!(shared.kind(), SymbolKind::Unknown, "and there is nothing to say about it");
1896    }
1897
1898    /// Not a rewording of the case above: what is checked is the arithmetic between the two.
1899    #[test]
1900    fn a_relocation_counts_from_the_start_of_the_section_and_not_of_the_image_it_is_in() {
1901        let mut data = Data { weak: Vec::new(), objects: vec![variable("first", Place::Written)] };
1902        data.objects.push(Object {
1903            bytes: vec![0; 16],
1904            size: 16,
1905            align: 8,
1906            relocs: vec![Reloc {
1907                at: 8,
1908                symbol: "y".to_owned(),
1909                kind: Reference::Address { bytes: 8 },
1910                addend: 0,
1911                after: 0,
1912            }],
1913            ..variable("second", Place::Written)
1914        });
1915        let bytes =
1916            write(&Text::default(), &data, &[], &target(), Output::default(), &Info::default())
1917                .expect("an object");
1918        let file = object::File::parse(&bytes[..]).expect("a readable object");
1919        let section = file.section_by_name(".data").expect("a data section");
1920        let (offset, _) = section.relocations().next().expect("one relocation");
1921        // Eight into the second image, which starts eight in because the first one is four long
1922        // and the second is eight aligned.
1923        assert_eq!(offset, 16);
1924    }
1925
1926    #[test]
1927    fn a_second_name_is_a_second_symbol_at_the_first_one_s_address_and_no_second_image() {
1928        let data = Data {
1929            weak: Vec::new(),
1930            objects: vec![Object { binding: Binding::Local, ..variable("a", Place::Written) }],
1931        };
1932        let aliases = [Alias {
1933            name: "b".to_owned(),
1934            target: "a".to_owned(),
1935            binding: Binding::Global,
1936            visibility: Visibility::Default,
1937        }];
1938        let bytes = write(
1939            &Text::default(),
1940            &data,
1941            &aliases,
1942            &target(),
1943            Output::default(),
1944            &Info::default(),
1945        )
1946        .expect("an object");
1947        let file = object::File::parse(&bytes[..]).expect("a readable object");
1948        let a = file.symbols().find(|s| s.name() == Ok("a")).expect("the variable");
1949        let b = file.symbols().find(|s| s.name() == Ok("b")).expect("the second name");
1950        assert_eq!(b.address(), a.address(), "the same place");
1951        assert_eq!(b.size(), a.size());
1952        assert_eq!(b.section_index(), a.section_index());
1953        // The binding is the one thing the second name does not take from the first, which is
1954        // what `extern int b __attribute__((alias("a")))` on a `static a` asks for.
1955        assert!(a.is_local(), "the target was written `static`");
1956        assert!(b.is_global(), "and the name given to it was not");
1957        // Four bytes of image and not eight, since an alias is a name and not a copy.
1958        assert_eq!(file.section_by_name(".data").expect("a data section").size(), 4);
1959    }
1960
1961    #[test]
1962    fn a_function_can_be_given_a_second_name_the_same_way_a_variable_can() {
1963        let text = calling("puts");
1964        let aliases = [Alias {
1965            name: "g".to_owned(),
1966            target: "f".to_owned(),
1967            binding: Binding::Weak,
1968            visibility: Visibility::Default,
1969        }];
1970        let bytes = write(
1971            &text,
1972            &Data::default(),
1973            &aliases,
1974            &target(),
1975            Output::default(),
1976            &Info::default(),
1977        )
1978        .expect("an object");
1979        let file = object::File::parse(&bytes[..]).expect("a readable object");
1980        let f = file.symbols().find(|s| s.name() == Ok("f")).expect("the function");
1981        let g = file.symbols().find(|s| s.name() == Ok("g")).expect("the second name");
1982        assert_eq!(g.address(), f.address());
1983        assert_eq!(g.size(), f.size());
1984        assert_eq!(g.kind(), f.kind(), "a second name for a function is a function");
1985        assert!(g.is_weak(), "so that a program may define the name itself instead");
1986    }
1987
1988    /// The front end is what reports this as a program's mistake, so one arriving here is a bug
1989    /// in this compiler and is said so rather than written as an undefined symbol.
1990    #[test]
1991    fn a_second_name_for_something_this_file_does_not_define_is_refused() {
1992        let aliases = [Alias {
1993            name: "b".to_owned(),
1994            target: "a".to_owned(),
1995            binding: Binding::Global,
1996            visibility: Visibility::Default,
1997        }];
1998        let error = write(
1999            &Text::default(),
2000            &Data::default(),
2001            &aliases,
2002            &target(),
2003            Output::default(),
2004            &Info::default(),
2005        )
2006        .expect_err("nothing to point at");
2007        assert!(matches!(error, Error::Refused { .. }), "{error:?}");
2008    }
2009
2010    #[test]
2011    fn a_platform_this_does_not_write_is_said_so_rather_than_written_as_elf() {
2012        let text = calling("puts");
2013        for triple in [
2014            Triple::new(Arch::Aarch64, Os::Linux, Env::Gnu),
2015            Triple::new(Arch::X86_64, Os::Darwin, Env::Gnu),
2016        ] {
2017            let error = write(
2018                &text,
2019                &Data::default(),
2020                &[],
2021                &TargetInfo::new(triple),
2022                Output::default(),
2023                &Info::default(),
2024            )
2025            .expect_err("no writer");
2026            assert!(matches!(error, Error::Format { .. }), "{error:?}");
2027        }
2028    }
2029
2030    /// What the archive's symbol index is built from is what the linker can find in the member.
2031    ///
2032    /// Written against the object rather than against the list, because the two agreeing is the
2033    /// whole point: a list that says more than the file does is an archive that promises a
2034    /// definition it does not have, and a list that says less is a member nothing pulls out.
2035    #[test]
2036    fn the_names_a_linker_can_find_are_the_names_the_list_gives() {
2037        let mut text = calling("puts");
2038        text.funcs.push(extent("hidden".to_owned(), 16, 1, Binding::Local));
2039        text.funcs.push(extent("shared".to_owned(), 32, 1, Binding::Weak));
2040        text.bytes.resize(33, 0x90);
2041        let data = Data {
2042            weak: Vec::new(),
2043            objects: vec![variable("seen", Place::Written), {
2044                let mut quiet = variable("quiet", Place::Zero);
2045                quiet.binding = Binding::Local;
2046                quiet
2047            }],
2048        };
2049        let aliases = [Alias {
2050            name: "second".to_owned(),
2051            target: "f".to_owned(),
2052            binding: Binding::Global,
2053            visibility: Visibility::Default,
2054        }];
2055
2056        let names = defines(&text, &data, &aliases, &target()).expect("a list");
2057        assert_eq!(names, ["f", "shared", "seen", "second"]);
2058
2059        let bytes = write(&text, &data, &aliases, &target(), Output::default(), &Info::default())
2060            .expect("an object");
2061        let file = object::File::parse(&bytes[..]).expect("a readable object");
2062        let found: Vec<String> = file
2063            .symbols()
2064            .filter(|symbol| symbol.is_global() && symbol.is_definition())
2065            .map(|symbol| symbol.name().unwrap_or_default().to_owned())
2066            .collect();
2067        let mut sorted = names.clone();
2068        sorted.sort();
2069        let mut theirs = found;
2070        theirs.sort();
2071        assert_eq!(sorted, theirs, "the list and the file have to say the same thing");
2072    }
2073
2074    /// A windows x86-64 target, which is the other format this writes.
2075    fn windows() -> TargetInfo {
2076        TargetInfo::new(Triple::new(Arch::X86_64, Os::Windows, Env::Gnu))
2077    }
2078
2079    /// What the four bytes a relocation covers hold, which is where COFF keeps its addend.
2080    fn inline(bytes: &[u8], section: &str, at: usize) -> i32 {
2081        let file = object::File::parse(bytes).expect("a readable object");
2082        let found = file.section_by_name(section).expect("the section").data().expect("the bytes");
2083        i32::from_le_bytes(found[at..at + 4].try_into().expect("four bytes"))
2084    }
2085
2086    #[test]
2087    fn a_windows_target_is_written_rather_than_refused() {
2088        let text = calling("puts");
2089        let bytes =
2090            write(&text, &Data::default(), &[], &windows(), Output::default(), &Info::default())
2091                .expect("an object");
2092        let file = object::File::parse(&bytes[..]).expect("a readable object");
2093        assert_eq!(file.format(), BinaryFormat::Coff);
2094        let section = file.section_by_name(".text").expect("a text section");
2095        assert_eq!(section.data().expect("the bytes"), &text.bytes[..]);
2096        let names: Vec<&str> = file.symbols().filter_map(|symbol| symbol.name().ok()).collect();
2097        assert!(names.contains(&"f"), "{names:?}");
2098        assert!(names.contains(&"puts"), "{names:?}");
2099    }
2100
2101    /// The whole reason a relocation carries where the instruction ended as well as the addend.
2102    ///
2103    /// A call ends at the four bytes the linker writes over, and a store of a constant through an
2104    /// address counted from the instruction pointer has the constant after them, and ELF tells the
2105    /// two apart by the addend alone. COFF cannot: it says how far the end is in the relocation type
2106    /// and works the addend out from that, so the same four bytes come out of two different types
2107    /// and both have to end up meaning the same distance.
2108    #[test]
2109    fn how_far_the_instruction_runs_past_the_hole_is_in_the_relocation_type() {
2110        for (after, typ) in [
2111            (0, pe::IMAGE_REL_AMD64_REL32),
2112            (1, pe::IMAGE_REL_AMD64_REL32_1),
2113            (4, pe::IMAGE_REL_AMD64_REL32_4),
2114            (5, pe::IMAGE_REL_AMD64_REL32_5),
2115        ] {
2116            let mut text = calling("puts");
2117            // The same distance every time, said the way ELF says it: from where the four bytes
2118            // start, with everything else folded in.
2119            text.relocs[0].addend = -4 - i64::from(after);
2120            text.relocs[0].after = after;
2121            text.bytes.resize(6 + after as usize, 0x90);
2122            text.funcs[0].len = text.bytes.len();
2123            let bytes = write(
2124                &text,
2125                &Data::default(),
2126                &[],
2127                &windows(),
2128                Output::default(),
2129                &Info::default(),
2130            )
2131            .expect("an object");
2132            let file = object::File::parse(&bytes[..]).expect("a readable object");
2133            let section = file.section_by_name(".text").expect("a text section");
2134            let (_, reloc) = section.relocations().next().expect("the relocation");
2135            assert_eq!(reloc.flags(), RelocationFlags::Coff { typ }, "{after}");
2136            // And the bytes come out holding nothing, because the distance the instruction wants
2137            // and the distance the type already says are the same one.
2138            assert_eq!(inline(&bytes, ".text", 1), 0, "{after}");
2139        }
2140    }
2141
2142    /// The addend a COFF object keeps is in the bytes rather than in the relocation, so the number
2143    /// the caller handed over has to survive the trip through the type.
2144    #[test]
2145    fn a_distance_the_instruction_did_not_ask_for_stays_in_the_bytes() {
2146        let mut text = calling("puts");
2147        text.relocs[0].addend = 12;
2148        let bytes =
2149            write(&text, &Data::default(), &[], &windows(), Output::default(), &Info::default())
2150                .expect("an object");
2151        assert_eq!(inline(&bytes, ".text", 1), 16, "twelve past the end, which is four past here");
2152    }
2153
2154    #[test]
2155    fn an_address_written_into_an_image_is_the_wide_relocation_here_too() {
2156        let object = Object {
2157            bytes: vec![0; 8],
2158            size: 8,
2159            align: 8,
2160            relocs: vec![Reloc {
2161                at: 0,
2162                symbol: "y".to_owned(),
2163                kind: Reference::Address { bytes: 8 },
2164                addend: 0,
2165                after: 0,
2166            }],
2167            ..variable("p", Place::Written)
2168        };
2169        let data = Data { weak: Vec::new(), objects: vec![object] };
2170        let bytes =
2171            write(&Text::default(), &data, &[], &windows(), Output::default(), &Info::default())
2172                .expect("an object");
2173        let file = object::File::parse(&bytes[..]).expect("a readable object");
2174        let section = file.section_by_name(".data").expect("a data section");
2175        let (_, reloc) = section.relocations().next().expect("the relocation");
2176        let typ = pe::IMAGE_REL_AMD64_ADDR64;
2177        assert_eq!(reloc.flags(), RelocationFlags::Coff { typ });
2178    }
2179
2180    /// `.data.rel.ro` is an ELF answer to a problem this format solves elsewhere, so both halves of
2181    /// it land in ordinary read only data, which is where the platform's own linker puts them.
2182    #[test]
2183    fn a_variable_the_loader_writes_into_is_read_only_data_here() {
2184        for local in [false, true] {
2185            let data = Data {
2186                weak: Vec::new(),
2187                objects: vec![variable("p", Place::RelocReadOnly { local })],
2188            };
2189            let bytes = write(
2190                &Text::default(),
2191                &data,
2192                &[],
2193                &windows(),
2194                Output::default(),
2195                &Info::default(),
2196            )
2197            .expect("an object");
2198            let file = object::File::parse(&bytes[..]).expect("a readable object");
2199            assert!(file.section_by_name(".rdata").is_some(), "{local}");
2200            assert!(file.section_by_name(".data.rel.ro.local").is_none(), "{local}");
2201        }
2202    }
2203
2204    /// No marker and no note, because a PE image says both of those things in the header of the
2205    /// finished image rather than in each of its inputs.
2206    #[test]
2207    fn the_sections_only_elf_reads_are_left_out_rather_than_written_empty() {
2208        let text = calling("puts");
2209        let output = Output { property: Property { features: 3 }, ..Output::default() };
2210        let bytes = write(&text, &Data::default(), &[], &windows(), output, &Info::default())
2211            .expect("an object");
2212        let file = object::File::parse(&bytes[..]).expect("a readable object");
2213        assert!(file.section_by_name(".note.GNU-stack").is_none());
2214        assert!(file.section_by_name(".note.gnu.property").is_none());
2215    }
2216
2217    /// Each of these is something this format has no way to write, and writing the nearest thing
2218    /// would be worse than refusing: a thread-local variable written as an ordinary one is one copy
2219    /// where the program asked for one per thread, and a constructor list under a name nothing
2220    /// gathers is a program whose constructors never run.
2221    #[test]
2222    fn what_this_format_cannot_say_is_refused_by_name() {
2223        let ordinary = Text::default();
2224        let empty = Data::default();
2225
2226        let mut thread = Data::default();
2227        thread.objects.push(variable("t", Place::Thread { zero: false }));
2228
2229        let mut gathered = Data::default();
2230        gathered.objects.push(variable("c", Place::Named(".init_array".to_owned())));
2231
2232        let mut table = calling("puts");
2233        table.relocs[0].kind = Reference::Got;
2234
2235        let mut room = calling("puts");
2236        room.funcs[0].patch = Some(Patch { at: 0, before: 0 });
2237
2238        let cases: [(&str, &Text, &Data); 4] = [
2239            ("thread-local", &ordinary, &thread),
2240            ("startup", &ordinary, &gathered),
2241            ("table", &table, &empty),
2242            ("patcher", &room, &empty),
2243        ];
2244        for (what, text, data) in cases {
2245            let error = write(text, data, &[], &windows(), Output::default(), &Info::default())
2246                .expect_err("something this format cannot write");
2247            assert!(matches!(error, Error::Refused { .. }), "{what}: {error:?}");
2248        }
2249    }
2250
2251    /// A visibility is not refused, because there is nothing to refuse: it is a fact about a dynamic
2252    /// symbol table and a COFF symbol has nowhere to keep one, which is what gcc does on the
2253    /// platform as well.
2254    #[test]
2255    fn a_visibility_this_format_cannot_keep_changes_nothing_rather_than_failing() {
2256        let mut text = calling("puts");
2257        text.funcs[0].visibility = Visibility::Hidden;
2258        let bytes =
2259            write(&text, &Data::default(), &[], &windows(), Output::default(), &Info::default())
2260                .expect("an object");
2261        let file = object::File::parse(&bytes[..]).expect("a readable object");
2262        let symbol = file.symbols().find(|symbol| symbol.name() == Ok("f")).expect("the function");
2263        assert!(symbol.is_global(), "a name others may use either way");
2264    }
2265
2266    #[test]
2267    fn the_names_a_linker_can_find_are_the_same_list_on_either_format() {
2268        let text = calling("puts");
2269        let data = Data { weak: Vec::new(), objects: vec![variable("shared", Place::Written)] };
2270        let theirs = defines(&text, &data, &[], &windows()).expect("a list");
2271        assert_eq!(theirs, defines(&text, &data, &[], &target()).expect("a list"));
2272    }
2273
2274    /// The same refusal the writer gives, for the reason the function says: an undecorated name is
2275    /// the wrong answer for a format whose symbols carry an underscore, and a wrong index entry is
2276    /// worse than no archive.
2277    #[test]
2278    fn a_platform_this_does_not_write_has_no_list_of_names_either() {
2279        let text = calling("puts");
2280        for triple in [
2281            Triple::new(Arch::Aarch64, Os::Linux, Env::Gnu),
2282            Triple::new(Arch::X86_64, Os::Darwin, Env::Gnu),
2283        ] {
2284            let error = defines(&text, &Data::default(), &[], &TargetInfo::new(triple))
2285                .expect_err("no writer");
2286            assert!(matches!(error, Error::Format { .. }), "{error:?}");
2287        }
2288    }
2289}