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    /// What the whole section has to be aligned to, which is the largest alignment any function
112    /// in it asked for.
113    ///
114    /// A function is at a fixed offset inside the section, so a function at a multiple of two
115    /// hundred and fifty six is one only if the section itself is at one. The padding between the
116    /// functions is the assembler's half of the same job and this is the linker's.
117    pub align: u32,
118    /// What an unwinder is told about the functions, which is empty for a format that has no such
119    /// section or a build that asked for none.
120    pub unwind: Unwind,
121}
122
123impl Default for Text {
124    fn default() -> Self {
125        Self {
126            bytes: Vec::new(),
127            funcs: Vec::new(),
128            relocs: Vec::new(),
129            align: FUNC_ALIGN,
130            unwind: Unwind::default(),
131        }
132    }
133}
134
135/// The unwind table, as the bytes of its own section and what the linker has to be told about them.
136///
137/// Bytes rather than rows, because what a record is is DWARF's answer and not the object format's,
138/// and the layer that knows what a frame did is the one that can say it in the fewest of them. What
139/// is left for the writer is where the section goes and what its relocations are, which is the part
140/// the three formats disagree about.
141///
142/// Each record says where its function is as a distance from the record to the function, which is
143/// a number no compilation knows: a function is at a fixed offset inside its own section and the
144/// section is placed by the linker. So there is one relocation per record and it is the ordinary
145/// instruction pointer relative one, since the distance is between two things in the same file.
146#[derive(Debug, Clone, Default, PartialEq, Eq)]
147pub struct Unwind {
148    /// The records, one shared header and one per function.
149    pub bytes: Vec<u8>,
150    /// Every place in them that names a function the linker has to place.
151    pub relocs: Vec<Reloc>,
152}
153
154/// Where one function ended up.
155///
156/// How long a function is is a fact ELF records and Mach-O has no way to, so it is handed over
157/// rather than worked out again: the writer that wants it has it and the one that does not
158/// ignores it.
159#[derive(Debug, Clone, PartialEq, Eq)]
160pub struct Extent {
161    /// The function's name, as the C program spelled it. The underscore an Apple symbol carries
162    /// is the object writer's business, not this one's.
163    pub name: String,
164    /// Where its first instruction is.
165    pub start: usize,
166    /// How many bytes of instructions it is, not counting the padding in front of the next one.
167    pub len: usize,
168    /// What this one function asked to be aligned to, which is not always what the section it is
169    /// in was aligned to.
170    ///
171    /// The two are the same number only when this function is the one that asked for the most.
172    /// Under [`Sections::functions`] each function is a section of its own and this is what that
173    /// section is aligned to, so the number has to survive the trip rather than be recovered from
174    /// the offset, which says nothing once the function is at zero in a section of its own.
175    pub align: u32,
176    /// How the linker sees the name, which is what the C `static` reaches the object file as.
177    pub binding: Binding,
178    /// How far outside a shared library holding this the name reaches.
179    pub visibility: Visibility,
180}
181
182/// The variables a file defines, and what the linker has to be told about them.
183///
184/// One entry per variable rather than one section of everything, because where a variable goes is
185/// worked out from what it is and two of them that land in one section still have their own
186/// alignment, their own size and their own symbol. Putting them together is the writer's job and
187/// is the one part of it the three formats disagree about.
188#[derive(Debug, Clone, Default, PartialEq, Eq)]
189pub struct Data {
190    /// Every variable this file defines, in the order the module held them.
191    pub objects: Vec<Object>,
192}
193
194/// A second name for something the same file defines.
195///
196/// Not a section and not a byte of anything, which is the whole point of it: an alias is a symbol
197/// table entry pointing at an address something else already occupies, so a file with one in it is
198/// no larger than the same file without. `.set b, a` is what an assembler is told and a second
199/// entry at the first one's section, value and size is what a writer produces, and the two say the
200/// same thing.
201///
202/// The target is a name rather than an index into anything above, because the two output paths
203/// find it in different places: a listing hands the name to an assembler that resolves it, and a
204/// writer looks it up among the symbols it has already added.
205#[derive(Debug, Clone, PartialEq, Eq)]
206pub struct Alias {
207    /// The name being defined, as the C program spelled it.
208    pub name: String,
209    /// The name it stands for, which has to be something this same file defines.
210    pub target: String,
211    /// How the linker sees the new name, which is not always how it sees the old one: the target
212    /// of `extern int b __attribute__((alias("a")))` may be a `static`.
213    pub binding: Binding,
214    /// How far outside a shared library holding this the new name reaches, which is its own
215    /// answer for the same reason the binding is: the attribute is written on the alias.
216    pub visibility: Visibility,
217}
218
219/// One global variable, laid out.
220#[derive(Debug, Clone, PartialEq, Eq)]
221pub struct Object {
222    /// Its name, as the C program spelled it. The underscore an Apple symbol carries is the
223    /// object writer's business, not this one's.
224    pub name: String,
225    /// Its image, and nothing at all when it is zero filled and the file carries none of it.
226    pub bytes: Vec<u8>,
227    /// How many bytes it occupies, which is the length of the image except when there is none.
228    pub size: u64,
229    /// What it has to be aligned to, always a power of two.
230    pub align: u64,
231    /// Which section it goes in.
232    pub place: Place,
233    /// How the linker sees the name.
234    pub binding: Binding,
235    /// How far outside a shared library holding this the name reaches.
236    pub visibility: Visibility,
237    /// Every place in its image that holds the address of a symbol, counted from the start of
238    /// the image rather than from the start of the section it lands in.
239    pub relocs: Vec<Reloc>,
240}
241
242/// Which section a variable goes in.
243///
244/// Worked out from what the variable is rather than named by it, except in the one case where the
245/// program named it. A reader who wants to know why a variable is in `.rodata` should be able to
246/// find the answer in the variable.
247#[derive(Debug, Clone, PartialEq, Eq)]
248pub enum Place {
249    /// Written to, and its image is not all zeros. `.data`.
250    Written,
251    /// Never written to, so it can go in a page the loader maps read only and every process
252    /// running the program can share. `.rodata`.
253    ReadOnly,
254    /// Never written to by the program, but written once by the dynamic linker, because its image
255    /// holds the address of something and an address is not known until the image is loaded.
256    /// `.data.rel.ro`.
257    ///
258    /// The section has to be writable for that one write and read only afterwards, which is what
259    /// the `PT_GNU_RELRO` segment is: the loader maps it, the relocations are applied, and then it
260    /// is turned read only before the program starts. Putting the variable in `.rodata` instead
261    /// means asking the linker to leave a relocation in a section that is never writable, and what
262    /// it does about that is give the whole image `DT_TEXTREL`, which gives up the protection the
263    /// section was for. Some hardened toolchains refuse the link outright.
264    RelocReadOnly {
265        /// Whether every address in the image is of something this file defines and does not
266        /// export, which means the link can resolve them all and none can be interposed.
267        ///
268        /// Those go in `.data.rel.ro.local`, which the linker puts in the first pages of the
269        /// segment, so the pages holding them are the ones the loader is done with soonest. It is
270        /// a hint about layout rather than a difference in what the section is.
271        local: bool,
272    },
273    /// All zeros, so the file says how big it is and carries none of it. `.bss`.
274    Zero,
275    /// A tentative definition, which is not in a section at all: the linker is asked for that
276    /// much zeroed space and merges every definition of the name into one. `.comm`.
277    Merged,
278    /// The section the program named, from `__attribute__((section(...)))`.
279    Named(String),
280}
281
282impl Place {
283    /// What the section this variable goes in is called under [`Sections::data`], and nothing at
284    /// all for a variable that has no section of its own to be given.
285    ///
286    /// The name is the section it would otherwise have shared with a dot and the variable's name
287    /// after it, which is what gcc writes and is not merely a convention: `--gc-sections`, the
288    /// linker scripts a kernel and an embedded image are linked with, and the default placement
289    /// rules all match on the part in front of the dot, so a section called anything else would be
290    /// placed by whatever the catch all rule is.
291    ///
292    /// Two kinds of variable are left alone. A merged one is a request to the linker for that much
293    /// zeroed space rather than an image, so there is no section to split, and one the program put
294    /// a name on already has the answer the source gave, which this must not overrule.
295    ///
296    /// Here rather than beside either output path, so that the listing `-S` writes and the object
297    /// `-c` writes cannot come to disagree about where a variable went.
298    #[must_use]
299    pub fn split(&self, name: &str) -> Option<String> {
300        Some(format!("{}.{name}", self.base()?))
301    }
302
303    /// The section this variable goes in when nothing is being split up, and nothing at all for
304    /// the two kinds that are not in one.
305    #[must_use]
306    pub fn base(&self) -> Option<&'static str> {
307        Some(match self {
308            Place::Written => ".data",
309            Place::ReadOnly => ".rodata",
310            Place::RelocReadOnly { local: false } => ".data.rel.ro",
311            Place::RelocReadOnly { local: true } => ".data.rel.ro.local",
312            Place::Zero => ".bss",
313            Place::Merged | Place::Named(_) => return None,
314        })
315    }
316}
317
318/// How the linker sees a name.
319///
320/// Three of the five linkages the IR has, because that is how many an object file can say. Which
321/// of the two weak ones a symbol had is a fact the optimizer needs and the linker does not.
322#[derive(Debug, Clone, Copy, PartialEq, Eq)]
323pub enum Binding {
324    /// Visible to every other object, and the definition here is the definition.
325    Global,
326    /// Invisible outside this object, which is what `static` at file scope means.
327    Local,
328    /// Visible, and allowed to lose to a definition in another object.
329    Weak,
330}
331
332/// How far outside a shared library a name reaches.
333///
334/// A different question from [`Binding`] and asked of a different linker. The binding is what the
335/// static linker does with a name while it is building the output, and this is what the dynamic
336/// linker may do with it once the output is a shared library and is being loaded. A hidden name is
337/// still global to the static link, so two files in the same library can call each other by it; it
338/// is simply not in the dynamic symbol table afterwards, so nothing outside can name it.
339///
340/// Written down here as its own thing rather than folded into the binding because it is the
341/// mistake tamnd/rucc#733 was: a writer that has one word for both ends up saying something about
342/// visibility while it thinks it is saying something about linkage, and what it said was hidden.
343///
344/// It means nothing for a [`Binding::Local`] name. `static` is already invisible to the whole
345/// world outside the file, and ELF records `STV_DEFAULT` for one, which is what gcc writes.
346#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
347pub enum Visibility {
348    /// In the dynamic symbol table, and a reference from inside the library may be satisfied by a
349    /// definition somewhere else, which is what makes `LD_PRELOAD` work. What a name gets when
350    /// nothing said otherwise.
351    #[default]
352    Default,
353    /// Not in the dynamic symbol table at all, so nothing outside the library can name it and
354    /// every reference to it from inside binds here. `__attribute__((visibility("hidden")))`.
355    Hidden,
356    /// In the dynamic symbol table, so something outside can name it, but a reference from inside
357    /// the library binds to the definition inside it and cannot be interposed.
358    Protected,
359}
360
361/// One reference to something this file does not contain.
362#[derive(Debug, Clone, PartialEq, Eq)]
363pub struct Reloc {
364    /// Where the bytes the linker writes over begin.
365    pub at: usize,
366    /// What is wanted, as the C program spelled it.
367    pub symbol: String,
368    /// What the linker is being asked for.
369    pub kind: Reference,
370    /// What to add to the distance, which is the constant the instruction already meant plus the
371    /// bytes between the hole and the end of the instruction, negated. An instruction counts from
372    /// where it ends and a relocation counts from where it starts, and this is the difference.
373    pub addend: i64,
374}
375
376/// What kind of thing a relocation is asking the linker for.
377///
378/// The first three are the distance from the end of an instruction to something, which is what
379/// every reference the code makes is, because this compiler generates position independent code and
380/// nothing else. They are told apart by what the linker is allowed to do about each one. The fourth
381/// is not a distance at all and is the only kind an image asks for, since an initializer holding the
382/// address of something holds the address itself.
383#[derive(Debug, Clone, Copy, PartialEq, Eq)]
384pub enum Reference {
385    /// A call, which the linker may satisfy with a stub that reaches further than the four bytes
386    /// would. `R_X86_64_PLT32` on ELF, and the same relocation a branch gets on the other two.
387    Call,
388    /// A datum, reached from the instruction pointer. `R_X86_64_PC32` on ELF.
389    Data,
390    /// A slot of the global offset table, reached from the instruction pointer, holding the
391    /// address of something another object may be the one that defines.
392    ///
393    /// The distance to the slot rather than to the thing, which is the whole difference: the
394    /// distance to the thing is a number only a link that puts the thing in this program can
395    /// work out, and a shared library is a link that does not. `R_X86_64_REX_GOTPCRELX` on ELF,
396    /// which says the instruction is a `mov` with a REX prefix and lets the linker turn it back
397    /// into the `lea` it would have been if the symbol had been here all along.
398    Got,
399    /// The address itself, written into an image. `int *p = &y;` and nothing else in C.
400    Address {
401        /// How many bytes of it are written, which is the pointer width except on a target with
402        /// a narrower relocation for it. `R_X86_64_64` and `R_X86_64_32` on ELF.
403        bytes: u8,
404    },
405}