Skip to main content

rucc_object/
section.rs

1//! What an object writer is given, which is a section of bytes and what the linker has to be
2//! told about them.
3//!
4//! Design: `spec/11-asm-objects-debug.md` sections 11.1 and 11.3.
5//!
6//! These types are here rather than beside the assembler that fills them in because they are what
7//! an object file is made of, and because a writer cannot depend on the thing that produces its
8//! input without the graph going the wrong way round. The assembler at layer rank 11 reaches down
9//! to these at rank 9, which is the direction `spec/18-package-layout.md` asks for.
10
11/// What a function is aligned to when nothing asked for more.
12///
13/// Sixteen because that is what every x86-64 toolchain puts a function at, and because it is what
14/// keeps the loop inside one from straddling one more cache line than it has to. Here rather than
15/// beside the assembler because the assembler pads to it and the writer records it, and two
16/// copies of one number is how the padding and the record come apart.
17pub const FUNC_ALIGN: u32 = 16;
18
19/// Whether each function and each variable gets a section to itself.
20///
21/// Design: `spec/11-asm-objects-debug.md` section 11.3, and `spec/04-driver-and-cli.md` section 4.7
22/// for the flags that ask for it.
23///
24/// A linker can drop a section nothing reaches and cannot drop half of one, so a file whose
25/// functions share a section keeps every function that file defines in the output as soon as any
26/// one of them is called. Splitting them is what makes `--gc-sections` do anything, which is how an
27/// embedded image or a kernel gets small, and it is the whole of what these two flags are for. The
28/// cost is a section header per name, which is why it is asked for rather than always done.
29///
30/// Not one flag, because gcc has two and a build that wants one of them and not the other is a
31/// build that measured something. Splitting the code is nearly free at link time; splitting the
32/// data can defeat the linker's ordering of what is next to what.
33#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
34pub struct Sections {
35    /// `-ffunction-sections`. Each function in `.text.<name>` rather than all of them in `.text`.
36    pub functions: bool,
37    /// `-fdata-sections`. Each variable in a section named after it rather than in the one its
38    /// contents would otherwise have chosen.
39    pub data: bool,
40}
41
42impl Sections {
43    /// Whether either of them was asked for.
44    #[must_use]
45    pub const fn any(self) -> bool {
46        self.functions || self.data
47    }
48}
49
50/// What a file says it was built to have checked, which is what `-fcf-protection=` asks for.
51///
52/// Design: `spec/11-asm-objects-debug.md` section 11.3, and `spec/04-driver-and-cli.md` section 4.7
53/// for the flag.
54///
55/// A machine's control flow checks are turned on for a whole process or not at all, never for one
56/// function, so a program made of one object built with them and one built without has to be run
57/// one way or the other. What everybody settled on is that each object records what it was built
58/// for, the linker keeps only what every input agreed on, and the loader turns on what is left. So
59/// an object that records nothing turns the check off for every object it is linked with, which is
60/// why this is written even when the flag changed no instruction in the file.
61///
62/// One number rather than a pair of flags, because that is what the record holds: a word of bits
63/// whose meaning is the machine's, and a linker that has never heard of a bit still knows to drop
64/// it when one input does not have it.
65#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
66pub struct Property {
67    /// The bits of the x86 feature word, which are [`Self::IBT`] and [`Self::SHSTK`].
68    pub features: u32,
69}
70
71impl Property {
72    /// Which property the feature word is, which is the key the record is written under.
73    pub const X86_FEATURES: u32 = 0xc000_0002;
74    /// Indirect branch tracking: every indirect call and jump in the file arrives at a landing
75    /// pad, so the machine may fault on one that does not.
76    pub const IBT: u32 = 1;
77    /// The shadow stack: every return in the file goes where a second copy of the return address
78    /// says it should, so the machine may fault when the two disagree.
79    pub const SHSTK: u32 = 2;
80
81    /// Whether anything is recorded at all, which is whether the record is written.
82    #[must_use]
83    pub const fn any(self) -> bool {
84        self.features != 0
85    }
86}
87
88/// What the command line decided about the file being written, as against what the code in it
89/// decided.
90///
91/// Two answers with nothing to do with each other, together because they arrive together: neither
92/// can be worked out from a function, and the listing and the byte writer have to be handed the
93/// same pair or the two outputs of one command line would not be the same file.
94#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
95pub struct Output {
96    /// Whether each function and each variable gets a section to itself.
97    pub sections: Sections,
98    /// What the file says it was built to have checked.
99    pub property: Property,
100}
101
102/// A text section, and what the linker has to be told about it.
103#[derive(Debug, Clone, PartialEq, Eq)]
104pub struct Text {
105    /// The instructions, in the order they were laid out.
106    pub bytes: Vec<u8>,
107    /// Where each function starts and how long it is, in the order they were written.
108    pub funcs: Vec<Extent>,
109    /// Every place in the bytes that names something the linker has to find.
110    pub relocs: Vec<Reloc>,
111    /// Every place inside a function that has a name of its own, in the order they were written.
112    pub labels: Vec<Marker>,
113    /// What the whole section has to be aligned to, which is the largest alignment any function
114    /// in it asked for.
115    ///
116    /// A function is at a fixed offset inside the section, so a function at a multiple of two
117    /// hundred and fifty six is one only if the section itself is at one. The padding between the
118    /// functions is the assembler's half of the same job and this is the linker's.
119    pub align: u32,
120    /// What an unwinder is told about the functions, which is empty for a format that has no such
121    /// section or a build that asked for none.
122    pub unwind: Unwind,
123    /// The jump tables that are read rather than run, and so go in a read only section of data
124    /// rather than in these bytes. Empty on a format that keeps its tables after the function.
125    pub tables: Vec<Table>,
126}
127
128impl Default for Text {
129    fn default() -> Self {
130        Self {
131            bytes: Vec::new(),
132            funcs: Vec::new(),
133            relocs: Vec::new(),
134            labels: Vec::new(),
135            align: FUNC_ALIGN,
136            unwind: Unwind::default(),
137            tables: Vec::new(),
138        }
139    }
140}
141
142/// The unwind table, as the bytes of the section or two it goes in and what the linker has to be
143/// told about them.
144///
145/// Bytes rather than rows, because what a record is is the platform's answer rather than the object
146/// writer's, and the layer that knows what a frame did is the one that can say it in the fewest of
147/// them. What is left for the writer is where the sections go and what their relocations are.
148///
149/// Two of them, because the two platforms lay the same facts out differently. ELF writes one section
150/// of records, each a little program an unwinder runs to rebuild the frame at an address, and each
151/// carrying its own codes, so [`Self::info`] is empty there. Windows writes a table of fixed rows
152/// sorted by address, one per function, each pointing at the description of that function's prologue
153/// in a second section, which is what [`Self::info`] holds.
154///
155/// Every record says where its function is, and where a function is is a number no compilation
156/// knows: a function is at a fixed offset inside its own section and the section is placed by the
157/// linker. So there are relocations, and which kind they are is the format's answer too.
158#[derive(Debug, Clone, Default, PartialEq, Eq)]
159pub struct Unwind {
160    /// The records: one shared header and one per function on ELF, and one row per function on
161    /// Windows.
162    pub bytes: Vec<u8>,
163    /// Every place in them that names something the linker has to place, which is the functions
164    /// they are about and, where there is a second section, the description each row points at.
165    pub relocs: Vec<Reloc>,
166    /// What those records point at, on the format that keeps the two apart, and nothing at all on
167    /// the one whose records carry their own.
168    pub info: Vec<u8>,
169    /// The names inside [`Self::info`], one per function that has a description there, which are
170    /// what the relocations above ask for.
171    ///
172    /// Names rather than offsets because a relocation names a symbol, and the record and the thing
173    /// it points at are in two different sections, so there is no distance either of them can be
174    /// written with instead.
175    pub labels: Vec<Marker>,
176    /// The table of where each call an unwind lands from goes, which is `.gcc_except_table` and
177    /// is empty in a file with no landing pad in it. One header per function that has any, each
178    /// found by the record of its function through a relocation against this section, which is
179    /// what the name [`EXCEPT_TABLE`] in a relocation of [`Self::relocs`] stands for.
180    pub except: Vec<u8>,
181}
182
183/// The name of the section the call site tables go in, which is also what a relocation against it
184/// names. See [`Unwind::except`].
185pub const EXCEPT_TABLE: &str = ".gcc_except_table";
186
187/// The debug information, as the bytes of the sections it goes in.
188///
189/// Bytes rather than anything shaped like DWARF, for the reason [`Unwind`] is bytes: what a record
190/// is is the format's answer and the layer that knows what the program was doing is the one that
191/// can say it, and what is left for the writer is where the sections go and what their relocations
192/// are. The difference between the two is only that there are more than two sections here and that
193/// their names are not the writer's to choose, so each one carries its own.
194#[derive(Debug, Clone, Default, PartialEq, Eq)]
195pub struct Info {
196    /// One entry per section that has anything in it, in the order they are to be written.
197    ///
198    /// The order matters because a relocation in one of them can name another, and a name is
199    /// resolved against the sections this file already has. Writing them in the order the producer
200    /// hands them over keeps that a property of the list rather than of the writer.
201    pub chunks: Vec<Chunk>,
202}
203
204/// One debug section, with the name it goes in the file under.
205///
206/// A relocation here names either a function this file defines or another section in the same
207/// list, and the two are told apart by looking the name up among the sections first. That is safe
208/// rather than lucky: every section name in DWARF begins with `.debug_`, which is not the spelling
209/// of any name a C program can define.
210#[derive(Debug, Clone, PartialEq, Eq)]
211pub struct Chunk {
212    /// What the section is called, which is the name DWARF gives it.
213    pub name: String,
214    /// Its contents.
215    pub bytes: Vec<u8>,
216    /// Every place in them that names something this file does not place itself.
217    pub relocs: Vec<Reloc>,
218}
219
220/// Where the room a patcher was promised at the top of a function ended up.
221///
222/// What `-fpatchable-function-entry=` asks for, once it is bytes rather than instructions. Two
223/// numbers because the writer has two questions: where the address it records points, and how much
224/// of the function is in front of the symbol.
225///
226/// They are not the same number. The room can be split by the landing pad a function opens with,
227/// since the pad has to be the first instruction after the label and the room does not, so the part
228/// in front of the label and the part after it are not always next to each other. What is recorded
229/// is the front of the whole thing, which is the part in front of the label when there is one.
230#[derive(Debug, Clone, Copy, PartialEq, Eq)]
231pub struct Patch {
232    /// Where the room begins, as an offset into the same bytes [`Extent::start`] is one into.
233    pub at: usize,
234    /// How many bytes of the function are in front of [`Extent::start`], which is where its symbol
235    /// is and where an unwinder is told the function begins.
236    pub before: usize,
237}
238
239/// Where a place inside a function that has a name of its own ended up.
240///
241/// What asks for one is GNU's address of a label in the initializer of an object with static
242/// storage duration. A label is somewhere a jump goes and a jump is a distance the assembler works
243/// out, so no ordinary label is in the symbol table at all. An image is the other case: it is in
244/// another section, so what it holds is a relocation, and a relocation names a symbol.
245///
246/// The name is never one the program wrote, so nothing outside this file looks it up and it is
247/// always local: it is here for a relocation in this same file to resolve against, and a linker
248/// that offered it to another file would be offering the middle of a function.
249#[derive(Debug, Clone, PartialEq, Eq)]
250pub struct Marker {
251    /// The name, which is whatever the compiler minted for it.
252    pub name: String,
253    /// Where it is, as an offset into the same bytes [`Extent::start`] is one into.
254    pub at: usize,
255}
256
257/// One jump table of one function, kept out of the instructions.
258///
259/// A table is data the function reads, and gcc and clang put it in `.rodata` rather than in the
260/// code. Keeping it there keeps data out of the lines the instruction fetcher reads and keeps the
261/// executable sections to what is executed, which is also what a size counted by section is
262/// measuring. The cost is that the two ends of every cell are now in different sections, so each
263/// cell is a relocation the linker fills in rather than a number the assembler writes, which is
264/// what gas does with the same `.long .L3-.L4` when the `.L4` is in `.rodata`.
265///
266/// Each cell is still the distance from the front of the table to a block, so the code that reads
267/// one is the same code wherever the table is.
268#[derive(Debug, Clone, PartialEq, Eq)]
269pub struct Table {
270    /// The name the instruction that reads it gives it, which is local to this file.
271    pub name: String,
272    /// Which of [`Text::funcs`] it belongs to.
273    pub func: usize,
274    /// Where each cell's block is, counted from [`Extent::start`] of that function.
275    pub cells: Vec<usize>,
276}
277
278/// Where one function ended up.
279///
280/// How long a function is is a fact ELF records and Mach-O has no way to, so it is handed over
281/// rather than worked out again: the writer that wants it has it and the one that does not
282/// ignores it.
283#[derive(Debug, Clone, PartialEq, Eq)]
284pub struct Extent {
285    /// The function's name, as the C program spelled it. The underscore an Apple symbol carries
286    /// is the object writer's business, not this one's.
287    pub name: String,
288    /// Where its first instruction is.
289    pub start: usize,
290    /// How many bytes of instructions it is, not counting the padding in front of the next one.
291    pub len: usize,
292    /// What this one function asked to be aligned to, which is not always what the section it is
293    /// in was aligned to.
294    ///
295    /// The two are the same number only when this function is the one that asked for the most.
296    /// Under [`Sections::functions`] each function is a section of its own and this is what that
297    /// section is aligned to, so the number has to survive the trip rather than be recovered from
298    /// the offset, which says nothing once the function is at zero in a section of its own.
299    pub align: u32,
300    /// How the linker sees the name, which is what the C `static` reaches the object file as.
301    pub binding: Binding,
302    /// How far outside a shared library holding this the name reaches.
303    pub visibility: Visibility,
304    /// Where the room a patcher was promised is, or `None` in a function promised none, which is
305    /// every function on a command line that did not ask. See [`Patch`].
306    pub patch: Option<Patch>,
307    /// Each call an unwind lands somewhere from, in the order they are in the function, which is
308    /// empty in every function with no cleanup handler to run on the way out. See [`Site`].
309    pub landings: Vec<Site>,
310}
311
312/// One call an unwind out of lands in a pad, as distances from [`Extent::start`].
313///
314/// What a row of the call site table in `.gcc_except_table` says, which is the bytes of the call
315/// and where the pad is. An unwinder looking up a return address finds the call it is the end of,
316/// so the range is the call's own bytes and nothing around it.
317#[derive(Debug, Clone, Copy, PartialEq, Eq)]
318pub struct Site {
319    /// Where the call begins.
320    pub start: usize,
321    /// How many bytes it is.
322    pub len: usize,
323    /// Where the pad begins.
324    pub pad: usize,
325}
326
327/// The variables a file defines, and what the linker has to be told about them.
328///
329/// One entry per variable rather than one section of everything, because where a variable goes is
330/// worked out from what it is and two of them that land in one section still have their own
331/// alignment, their own size and their own symbol. Putting them together is the writer's job and
332/// is the one part of it the three formats disagree about.
333#[derive(Debug, Clone, Default, PartialEq, Eq)]
334pub struct Data {
335    /// Every variable this file defines, in the order the module held them.
336    pub objects: Vec<Object>,
337    /// Every name this file declares weak and does not define, in the order the module held them.
338    ///
339    /// Each becomes an undefined symbol the linker is allowed to leave undefined, whose references
340    /// then read a zero address. A name here is not an object and carries no bytes, which is why
341    /// it is a list of names beside the objects rather than one of them.
342    pub weak: Vec<String>,
343    /// Every distance between two labels an image holds, which the writer fills in once it knows
344    /// where the labels are. See [`Apart`].
345    pub apart: Vec<Apart>,
346}
347
348/// How far one label is from another, written into a variable's image.
349///
350/// What `static int b[] = { &&l1 - &&l0 };` asks for. Neither label has an address until the
351/// link, and yet both are in the one function's code and the code moves as one piece, so the
352/// distance is known as soon as the code is laid out. That makes it a number the writer puts in
353/// the bytes itself rather than a relocation it asks the linker for, which is what gas does with
354/// `.long .L1-.L0` too, and it is why a label in another function is refused: the two could land
355/// in different sections and then no number is right.
356#[derive(Debug, Clone, PartialEq, Eq)]
357pub struct Apart {
358    /// Which of [`Data::objects`] the distance is written into.
359    pub object: usize,
360    /// How far into that object's image.
361    pub at: usize,
362    /// The label measured to, as the image named it.
363    pub to: String,
364    /// The label measured from.
365    pub from: String,
366    /// What to add to the distance.
367    pub addend: i64,
368    /// How many bytes the distance is written in.
369    pub bytes: u8,
370}
371
372/// A second name for something the same file defines.
373///
374/// Not a section and not a byte of anything, which is the whole point of it: an alias is a symbol
375/// table entry pointing at an address something else already occupies, so a file with one in it is
376/// no larger than the same file without. `.set b, a` is what an assembler is told and a second
377/// entry at the first one's section, value and size is what a writer produces, and the two say the
378/// same thing.
379///
380/// The target is a name rather than an index into anything above, because the two output paths
381/// find it in different places: a listing hands the name to an assembler that resolves it, and a
382/// writer looks it up among the symbols it has already added.
383#[derive(Debug, Clone, PartialEq, Eq)]
384pub struct Alias {
385    /// The name being defined, as the C program spelled it.
386    pub name: String,
387    /// The name it stands for, which has to be something this same file defines.
388    pub target: String,
389    /// How the linker sees the new name, which is not always how it sees the old one: the target
390    /// of `extern int b __attribute__((alias("a")))` may be a `static`.
391    pub binding: Binding,
392    /// How far outside a shared library holding this the new name reaches, which is its own
393    /// answer for the same reason the binding is: the attribute is written on the alias.
394    pub visibility: Visibility,
395}
396
397/// One global variable, laid out.
398#[derive(Debug, Clone, PartialEq, Eq)]
399pub struct Object {
400    /// Its name, as the C program spelled it. The underscore an Apple symbol carries is the
401    /// object writer's business, not this one's.
402    pub name: String,
403    /// Its image, and nothing at all when it is zero filled and the file carries none of it.
404    pub bytes: Vec<u8>,
405    /// How many bytes it occupies, which is the length of the image except when there is none.
406    pub size: u64,
407    /// What it has to be aligned to, always a power of two.
408    pub align: u64,
409    /// Which section it goes in.
410    pub place: Place,
411    /// How the linker sees the name.
412    pub binding: Binding,
413    /// How far outside a shared library holding this the name reaches.
414    pub visibility: Visibility,
415    /// Every place in its image that holds the address of a symbol, counted from the start of
416    /// the image rather than from the start of the section it lands in.
417    pub relocs: Vec<Reloc>,
418}
419
420/// Which section a variable goes in.
421///
422/// Worked out from what the variable is rather than named by it, except in the one case where the
423/// program named it. A reader who wants to know why a variable is in `.rodata` should be able to
424/// find the answer in the variable.
425#[derive(Debug, Clone, PartialEq, Eq)]
426pub enum Place {
427    /// Written to, and its image is not all zeros. `.data`.
428    Written,
429    /// Never written to, so it can go in a page the loader maps read only and every process
430    /// running the program can share. `.rodata`.
431    ReadOnly,
432    /// Never written to by the program, but written once by the dynamic linker, because its image
433    /// holds the address of something and an address is not known until the image is loaded.
434    /// `.data.rel.ro`.
435    ///
436    /// The section has to be writable for that one write and read only afterwards, which is what
437    /// the `PT_GNU_RELRO` segment is: the loader maps it, the relocations are applied, and then it
438    /// is turned read only before the program starts. Putting the variable in `.rodata` instead
439    /// means asking the linker to leave a relocation in a section that is never writable, and what
440    /// it does about that is give the whole image `DT_TEXTREL`, which gives up the protection the
441    /// section was for. Some hardened toolchains refuse the link outright.
442    RelocReadOnly {
443        /// Whether every address in the image is of something this file defines and does not
444        /// export, which means the link can resolve them all and none can be interposed.
445        ///
446        /// Those go in `.data.rel.ro.local`, which the linker puts in the first pages of the
447        /// segment, so the pages holding them are the ones the loader is done with soonest. It is
448        /// a hint about layout rather than a difference in what the section is.
449        local: bool,
450    },
451    /// All zeros, so the file says how big it is and carries none of it. `.bss`.
452    Zero,
453    /// One copy per thread rather than one copy per program. `.tdata` and `.tbss`.
454    ///
455    /// What the loader does with these two sections is what makes them different from every other
456    /// section here. Their contents are the template of a thread's own block of storage rather than
457    /// the storage itself: the image is laid out once, and every thread that starts gets a fresh
458    /// copy of it, so the address of a variable in one of them is a different address in every
459    /// thread and there is no single address for the link to write down. That is why a reference to
460    /// one is not the ordinary distance from the instruction pointer, and why the symbol is marked
461    /// as being of this kind so a linker refuses one that is.
462    ///
463    /// The pair is the same split as `.data` and `.bss` for the same reason, so an image that is
464    /// all zeros costs its size in the file and not its bytes.
465    Thread {
466        /// Whether the image is all zeros, which puts it in `.tbss` rather than `.tdata`.
467        zero: bool,
468    },
469    /// A tentative definition, which is not in a section at all: the linker is asked for that
470    /// much zeroed space and merges every definition of the name into one. `.comm`.
471    Merged,
472    /// The section the program named, from `__attribute__((section(...)))`.
473    Named(String),
474}
475
476impl Place {
477    /// What the section this variable goes in is called under [`Sections::data`], and nothing at
478    /// all for a variable that has no section of its own to be given.
479    ///
480    /// The name is the section it would otherwise have shared with a dot and the variable's name
481    /// after it, which is what gcc writes and is not merely a convention: `--gc-sections`, the
482    /// linker scripts a kernel and an embedded image are linked with, and the default placement
483    /// rules all match on the part in front of the dot, so a section called anything else would be
484    /// placed by whatever the catch all rule is.
485    ///
486    /// Two kinds of variable are left alone. A merged one is a request to the linker for that much
487    /// zeroed space rather than an image, so there is no section to split, and one the program put
488    /// a name on already has the answer the source gave, which this must not overrule.
489    ///
490    /// Here rather than beside either output path, so that the listing `-S` writes and the object
491    /// `-c` writes cannot come to disagree about where a variable went.
492    #[must_use]
493    pub fn split(&self, name: &str) -> Option<String> {
494        Some(format!("{}.{name}", self.base()?))
495    }
496
497    /// The section this variable goes in when nothing is being split up, and nothing at all for
498    /// the two kinds that are not in one.
499    #[must_use]
500    pub fn base(&self) -> Option<&'static str> {
501        Some(match self {
502            Place::Written => ".data",
503            Place::ReadOnly => ".rodata",
504            Place::RelocReadOnly { local: false } => ".data.rel.ro",
505            Place::RelocReadOnly { local: true } => ".data.rel.ro.local",
506            Place::Zero => ".bss",
507            Place::Thread { zero: false } => ".tdata",
508            Place::Thread { zero: true } => ".tbss",
509            Place::Merged | Place::Named(_) => return None,
510        })
511    }
512}
513
514/// A section holding function addresses for a C runtime to call rather than data for the program
515/// to read.
516///
517/// ELF has a type for each of the three, and a section of that type is what the startup code walks:
518/// the linker gathers every input section of the kind into one run and the CRT calls what it finds
519/// between the two ends. A section of the ordinary type with the same name would be gathered the
520/// same way and called by nothing, which is why the type is worth writing down rather than leaving
521/// to the default.
522///
523/// Only ELF says it this way. COFF sorts by what follows the `$` in a section name and Mach-O has
524/// a section attribute for it, so on those two the name carries the whole of the answer and there
525/// is nothing for this to be.
526#[derive(Debug, Clone, Copy, PartialEq, Eq)]
527pub enum Array {
528    /// Run on the way to `main`, in the order the linker sorted the sections into.
529    Init,
530    /// Run after `main` returns, in the reverse of that order.
531    Fini,
532    /// Run ahead of `.init_array` and ahead of the shared libraries a program is linked against,
533    /// which is a thing only the C library itself has a use for.
534    Preinit,
535}
536
537impl Array {
538    /// Which of them a section of this name is, and [`None`] for a name that is not one of them.
539    ///
540    /// The name itself or the name with a dot and a priority after it. A numbered `constructor` is
541    /// written as the second of those and is the same kind of section as the first: the number is
542    /// there so that the linker sorts it, not to make it a different thing.
543    #[must_use]
544    pub fn of(name: &str) -> Option<Array> {
545        let kinds = [
546            (".init_array", Array::Init),
547            (".fini_array", Array::Fini),
548            (".preinit_array", Array::Preinit),
549        ];
550        kinds.into_iter().find_map(|(base, array)| {
551            let rest = name.strip_prefix(base)?;
552            (rest.is_empty() || rest.starts_with('.')).then_some(array)
553        })
554    }
555
556    /// How the type is spelled in a `.section` directive.
557    #[must_use]
558    pub const fn asm(self) -> &'static str {
559        match self {
560            Array::Init => "@init_array",
561            Array::Fini => "@fini_array",
562            Array::Preinit => "@preinit_array",
563        }
564    }
565}
566
567/// How the linker sees a name.
568///
569/// Three of the five linkages the IR has, because that is how many an object file can say. Which
570/// of the two weak ones a symbol had is a fact the optimizer needs and the linker does not.
571#[derive(Debug, Clone, Copy, PartialEq, Eq)]
572pub enum Binding {
573    /// Visible to every other object, and the definition here is the definition.
574    Global,
575    /// Invisible outside this object, which is what `static` at file scope means.
576    Local,
577    /// Visible, and allowed to lose to a definition in another object.
578    Weak,
579}
580
581/// How far outside a shared library a name reaches.
582///
583/// A different question from [`Binding`] and asked of a different linker. The binding is what the
584/// static linker does with a name while it is building the output, and this is what the dynamic
585/// linker may do with it once the output is a shared library and is being loaded. A hidden name is
586/// still global to the static link, so two files in the same library can call each other by it; it
587/// is simply not in the dynamic symbol table afterwards, so nothing outside can name it.
588///
589/// Written down here as its own thing rather than folded into the binding because it is the
590/// mistake tamnd/rucc#733 was: a writer that has one word for both ends up saying something about
591/// visibility while it thinks it is saying something about linkage, and what it said was hidden.
592///
593/// It means nothing for a [`Binding::Local`] name. `static` is already invisible to the whole
594/// world outside the file, and ELF records `STV_DEFAULT` for one, which is what gcc writes.
595#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
596pub enum Visibility {
597    /// In the dynamic symbol table, and a reference from inside the library may be satisfied by a
598    /// definition somewhere else, which is what makes `LD_PRELOAD` work. What a name gets when
599    /// nothing said otherwise.
600    #[default]
601    Default,
602    /// Not in the dynamic symbol table at all, so nothing outside the library can name it and
603    /// every reference to it from inside binds here. `__attribute__((visibility("hidden")))`.
604    Hidden,
605    /// In the dynamic symbol table, so something outside can name it, but a reference from inside
606    /// the library binds to the definition inside it and cannot be interposed.
607    Protected,
608}
609
610/// One reference to something this file does not contain.
611#[derive(Debug, Clone, PartialEq, Eq)]
612pub struct Reloc {
613    /// Where the bytes the linker writes over begin.
614    pub at: usize,
615    /// What is wanted, as the C program spelled it.
616    pub symbol: String,
617    /// What the linker is being asked for.
618    pub kind: Reference,
619    /// What to add to the distance, which is the constant the instruction already meant plus the
620    /// bytes between the hole and the end of the instruction, negated. An instruction counts from
621    /// where it ends and a relocation counts from where it starts, and this is the difference.
622    pub addend: i64,
623    /// How many bytes of the instruction come after the four the linker writes over, which is zero
624    /// for everything except an instruction carrying an immediate behind its displacement.
625    ///
626    /// Already inside [`Self::addend`] and written down again because the two formats disagree about
627    /// which of the two numbers they want. ELF takes the one number and counts from where the hole
628    /// starts, so the difference between that and where the instruction ends is the writer's to fold
629    /// in and nothing after it ever has to be told apart again. COFF counts from where the
630    /// instruction ends and says how far that is in the relocation type itself, which is what
631    /// `IMAGE_REL_AMD64_REL32_1` through `REL32_5` are, so it needs the two apart. A writer cannot
632    /// recover one from the other, since a displacement of minus four and no trailing bytes and a
633    /// displacement of zero and four of them are the same sum.
634    ///
635    /// Zero for a relocation in an image, where there is no instruction and the question does not
636    /// arise.
637    pub after: u8,
638}
639
640/// What kind of thing a relocation is asking the linker for.
641///
642/// The first four are the distance from the end of an instruction to something, which is what every
643/// reference the code makes is, because this compiler generates position independent code and
644/// nothing else. They are told apart by what the linker is allowed to do about each one. The last
645/// two are not distances from an instruction at all and are what a table of data asks for: the
646/// address itself, which is what an initializer holding the address of something holds, and how far
647/// something is from the front of the image, which is what a table the runtime reads holds.
648#[derive(Debug, Clone, Copy, PartialEq, Eq)]
649pub enum Reference {
650    /// A call, which the linker may satisfy with a stub that reaches further than the four bytes
651    /// would. `R_X86_64_PLT32` on ELF, and the same relocation a branch gets on the other two.
652    Call,
653    /// A datum, reached from the instruction pointer. `R_X86_64_PC32` on ELF.
654    Data,
655    /// A slot of the global offset table, reached from the instruction pointer, holding the
656    /// address of something another object may be the one that defines.
657    ///
658    /// The distance to the slot rather than to the thing, which is the whole difference: the
659    /// distance to the thing is a number only a link that puts the thing in this program can
660    /// work out, and a shared library is a link that does not. `R_X86_64_REX_GOTPCRELX` on ELF,
661    /// which says the instruction is a `mov` with a REX prefix and lets the linker turn it back
662    /// into the `lea` it would have been if the symbol had been here all along.
663    Got,
664    /// A slot of the global offset table read by an instruction the linker may rewrite that has
665    /// no REX prefix, `call *f@GOTPCREL(%rip)` or a 32 bit `mov`. `R_X86_64_GOTPCRELX` on ELF.
666    GotBare,
667    /// A slot of the global offset table read by an instruction the linker has to leave as it is,
668    /// because it is not one of the few it knows how to rewrite: a store into the slot, or a load
669    /// into a vector register. `R_X86_64_GOTPCREL` on ELF.
670    GotKept,
671    /// A slot of the global offset table, reached from the instruction pointer, holding how far
672    /// into a thread's own block of storage a thread-local variable sits.
673    ///
674    /// An offset and not an address, which is what makes it a different relocation from the one
675    /// above rather than the same one against a different symbol: a thread-local variable has one
676    /// copy per thread and therefore no address for a link to write down, and what every copy has
677    /// in common is where it sits inside the block. Adding the block's own address, which the
678    /// machine keeps in a segment register, is what turns one into the other, and that addition is
679    /// in the code rather than in the relocation. `R_X86_64_GOTTPOFF` on ELF, which the linker
680    /// turns into a constant in the instruction when it is making an executable and therefore
681    /// knows how the blocks are laid out.
682    Thread,
683    /// The address itself, written into an image. `int *p = &y;` and nothing else in C.
684    Address {
685        /// How many bytes of it are written, which is the pointer width except on a target with
686        /// a narrower relocation for it. `R_X86_64_64` and `R_X86_64_32` on ELF.
687        bytes: u8,
688    },
689    /// How far the thing is from where the four bytes holding the answer are, written into an
690    /// image rather than reached by an instruction. `.long target - .` in an `asm` at file scope,
691    /// which is how a table of places in a program says where each of them is in four bytes rather
692    /// than eight and says it without anything having to be written into the table at startup.
693    ///
694    /// The same relocation a load makes, with nothing after the hole, because what a load asks is
695    /// the same question about the same four bytes. It is a kind of its own here all the same, and
696    /// not [`Reference::Data`] with `after` left at zero, because the two formats count the answer
697    /// from different ends: ELF counts from the front of the hole, which is what this wants, and
698    /// COFF counts from the byte after it, which is what an instruction wants. Saying which is
699    /// meant is what lets each writer answer for itself rather than one of them be quietly four
700    /// out.
701    Away,
702    /// How far the thing is from the front of the loaded image, written into four bytes.
703    ///
704    /// What every field of a Windows unwind table is. The table is read at run time by code that
705    /// already has the image's own address, so four bytes of distance from it reach anything in an
706    /// image a linker will build, which eight bytes of address would have cost twice as much to say
707    /// and a distance from the table itself could not have said at all: a row is looked up by
708    /// address in a sorted table, and a row whose meaning depended on where the row was would not
709    /// sort. `IMAGE_REL_AMD64_ADDR32NB`.
710    ///
711    /// ELF has no relocation of this kind because nothing it writes asks the question. Its unwind
712    /// records are found by walking rather than by binary search, and what they hold is the ordinary
713    /// distance from the record to the function.
714    Image,
715    /// Some bits of an AArch64 instruction, which the fixup says which and how to fill in.
716    ///
717    /// Its own kind rather than one of the above, because on this machine a reference is not four
718    /// bytes of distance: it is a field of a word, and a name takes two instructions to reach,
719    /// `adrp` for its page and an `add` or a load for the low twelve bits of it. Each of those is
720    /// its own relocation, and the fixup is already the name of one.
721    Field(rucc_target::aarch64::Fixup),
722}