Skip to main content

rucc_asm/
format.rs

1//! What an assembler is told about a function or a variable, which is the object format's answer
2//! rather than the machine's.
3//!
4//! Design: `spec/11-asm-objects-debug.md` section 11.3, which is about the object files
5//! themselves. The directives here are the same facts said in text: which section code and data go
6//! in, how a symbol is spelled, which symbols leave the file, and where each one ends.
7//!
8//! They are not the same on the three formats and the differences are not cosmetic. A Mach-O
9//! symbol carries an underscore in front of the C name and an ELF one does not, so a listing that
10//! got that wrong would fail to link against every library on the machine. A local label is
11//! spelled `.L` on ELF and COFF and `L` on Mach-O, and a label that is not spelled the local way
12//! ends up in the symbol table, where it is a name a debugger and a backtrace will show. And ELF
13//! wants a marker saying the stack is not executable, whose absence makes it executable, which
14//! section 11.3 calls out as a real and recurring security bug.
15
16use std::fmt::Write as _;
17
18use rucc_mir as mir;
19use rucc_object::{Alias, Array, Binding, Place, Property, Sections, Visibility};
20use rucc_target::ObjectFormat;
21
22use crate::data::Variable;
23
24/// The directives one object format wraps a function in.
25#[derive(Debug, Clone, Copy, PartialEq, Eq)]
26pub enum Directives {
27    /// ELF, which is Linux and the freestanding targets.
28    Elf,
29    /// Mach-O, which is Apple's.
30    MachO,
31    /// COFF, which is Windows.
32    Coff,
33}
34
35impl Directives {
36    /// The directives that go with that object format.
37    #[must_use]
38    pub const fn of(format: ObjectFormat) -> Directives {
39        match format {
40            ObjectFormat::Elf => Directives::Elf,
41            ObjectFormat::MachO => Directives::MachO,
42            ObjectFormat::Coff => Directives::Coff,
43            // No assembler in this crate writes wasm, and the caller that asked has a target it
44            // cannot emit for. ELF's directives are the ones nothing here depends on being right
45            // for a target it will not reach.
46            ObjectFormat::Wasm => Directives::Elf,
47        }
48    }
49
50    /// What goes in front of a C name to make the name the linker sees.
51    ///
52    /// Mach-O keeps the underscore that every Unix linker once had, so `main` in C is `_main` in
53    /// the object, and a listing that leaves it off refers to a symbol nothing defines.
54    #[must_use]
55    pub const fn symbol(self) -> &'static str {
56        match self {
57            Directives::Elf | Directives::Coff => "",
58            Directives::MachO => "_",
59        }
60    }
61
62    /// What goes in front of a label that belongs to one function and leaves no symbol behind.
63    #[must_use]
64    pub const fn local(self) -> &'static str {
65        match self {
66            Directives::Elf | Directives::Coff => ".L",
67            Directives::MachO => "L",
68        }
69    }
70
71    /// The directive that opens the section code goes in.
72    #[must_use]
73    pub const fn text(self) -> &'static str {
74        match self {
75            Directives::Elf | Directives::Coff => "\t.text",
76            Directives::MachO => "\t.section\t__TEXT,__text,regular,pure_instructions",
77        }
78    }
79
80    /// The directive that opens the section one function goes in, and nothing at all when they
81    /// are all going in the same one.
82    ///
83    /// Nothing on Mach-O either, whatever was asked for. Every Mach-O object ends with
84    /// `.subsections_via_symbols`, which tells the linker it may split a section at each symbol in
85    /// it and drop the parts nothing reaches, so the format does by default what the flag asks a
86    /// linker to be able to do and there is nothing left for it to change. Clang takes both flags
87    /// on an Apple target and writes one text section, which is the same answer.
88    ///
89    /// ELF names the section after the function and COFF gives one name to several sections and
90    /// tells the linker which symbol each belongs to. The COFF form is a COMDAT, which is more
91    /// than the ELF one says: a linker keeps one section out of every group that names the same
92    /// symbol. That is what a Windows toolchain does with `/Gy`, and it is what clang writes for
93    /// `-ffunction-sections` on a Windows target, so it is what a Windows linker is expecting.
94    pub fn code(self, out: &mut String, name: &str, sections: Sections) {
95        if !sections.functions {
96            return;
97        }
98        match self {
99            Directives::Elf => {
100                let _ = writeln!(out, "\t.section\t.text.{name},\"ax\",@progbits");
101            }
102            Directives::Coff => {
103                let _ = writeln!(out, "\t.section\t.text,\"xr\",one_only,{name}");
104            }
105            Directives::MachO => {}
106        }
107    }
108
109    /// What is said about a function before its first instruction.
110    ///
111    /// The binding is written the way it is written for a variable, and a local one gets no
112    /// directive at all: a name no directive mentions is still in the symbol table, as a local,
113    /// which is what `static` is. Windows says the same thing as a storage class, where three is
114    /// the local one and two the rest.
115    ///
116    /// `align` is in bytes and is a power of two, and the padding is `0x90` because the space in
117    /// front of a function is reached by falling off the end of the one before it.
118    pub fn open(
119        self,
120        out: &mut String,
121        name: &str,
122        align: u32,
123        binding: Binding,
124        visibility: Visibility,
125        ahead: &str,
126    ) {
127        let symbol = self.symbol();
128        let _ = writeln!(out, "\t.p2align\t{}, 0x90", align.max(1).trailing_zeros());
129        match binding {
130            Binding::Global => {
131                let _ = writeln!(out, "\t.globl\t{symbol}{name}");
132            }
133            Binding::Weak => {
134                let _ = writeln!(out, "\t.weak\t{symbol}{name}");
135            }
136            Binding::Local => {}
137        }
138        self.seen(out, name, binding, visibility);
139        match self {
140            Directives::Elf => {
141                let _ = writeln!(out, "\t.type\t{name}, @function");
142            }
143            // Windows says the storage class and the type code, and thirty two is a function.
144            Directives::Coff => {
145                let scl = if binding == Binding::Local { 3 } else { 2 };
146                let _ = writeln!(out, "\t.def\t{name}\n\t.scl\t{scl}\n\t.type\t32\n\t.endef");
147            }
148            Directives::MachO => {}
149        }
150        out.push_str(ahead);
151        let _ = writeln!(out, "{symbol}{name}:");
152    }
153
154    /// Where the room a patcher was promised at the top of this function is, as the record a
155    /// tracer reads to find every one of them.
156    ///
157    /// Eight bytes in a section of its own holding the address of the room, and the section is the
158    /// point of it: a tracer that wants to patch every function in a kernel has to be able to find
159    /// them without reading the symbol table, which a stripped image does not have. `o` is the flag
160    /// that ties this section to the text the label is in, so that a linker throwing that text away
161    /// throws the record away with it and never leaves an address pointing at nothing.
162    ///
163    /// `back` is what returns to the text section, which is passed in because which one that is
164    /// depends on whether every function got a section of its own and this does not otherwise care.
165    ///
166    /// Nothing on the other two formats. Neither has a section that works this way and neither has
167    /// a tracer looking for one, and the driver refuses the flag on a target that is not ELF rather
168    /// than letting a build come out looking patchable and not being.
169    pub fn patchable(self, out: &mut String, label: &str, back: &str) {
170        if self != Directives::Elf {
171            return;
172        }
173        let _ = writeln!(out, "\t.section\t__patchable_function_entries,\"awo\",@progbits,{label}");
174        let _ = writeln!(out, "\t.align\t8");
175        let _ = writeln!(out, "\t.quad\t{label}");
176        let _ = writeln!(out, "{back}");
177    }
178
179    /// What is said about how far a name reaches outside a shared library, which is nothing at
180    /// all in the ordinary case.
181    ///
182    /// A local name gets no directive whatever was asked for. `static` is already invisible to
183    /// everything outside the file, so there is no dynamic symbol table for it to be in or out of,
184    /// and gcc writes no visibility directive for one either.
185    ///
186    /// ELF says both of the other two and says them the same way an assembler expects. Mach-O has
187    /// one of them: `.private_extern` is a symbol that leaves this object and does not leave the
188    /// library, which is what hidden means, and there is no Mach-O spelling of protected because
189    /// the format has no way to say a symbol is exported and cannot be interposed. COFF has
190    /// neither, since what leaves a Windows DLL is decided by an export table the linker is given
191    /// rather than by a bit on each symbol.
192    pub fn seen(self, out: &mut String, name: &str, binding: Binding, visibility: Visibility) {
193        if binding == Binding::Local || visibility == Visibility::Default {
194            return;
195        }
196        let symbol = self.symbol();
197        match (self, visibility) {
198            (Directives::Elf, Visibility::Hidden) => {
199                let _ = writeln!(out, "\t.hidden\t{name}");
200            }
201            (Directives::Elf, Visibility::Protected) => {
202                let _ = writeln!(out, "\t.protected\t{name}");
203            }
204            (Directives::MachO, Visibility::Hidden) => {
205                let _ = writeln!(out, "\t.private_extern\t{symbol}{name}");
206            }
207            (Directives::MachO, Visibility::Protected) | (Directives::Coff, _) => {}
208            (_, Visibility::Default) => unreachable!("returned above"),
209        }
210    }
211
212    /// The directive that opens the section a variable goes in when it is being given one of its
213    /// own, and nothing at all when it is not.
214    ///
215    /// The name is worked out once, in [`Place::split`], so that the listing and the object file
216    /// cannot come to disagree about it. What is left here is the flags, which are the flags the
217    /// section it was split off from carries: splitting changes which section header a symbol
218    /// points at and must not quietly change whether the page it lands in is writable.
219    ///
220    /// Nothing on Mach-O, for the reason [`Directives::code`] gives.
221    fn split(self, out: &mut String, place: &Place, name: &str) -> bool {
222        let Some(named) = place.split(name) else { return false };
223        match self {
224            Directives::Elf => {
225                // `@nobits` for the zero filled one, because a section that says nothing about it
226                // is one the assembler writes the bytes of into the file, and the point of that
227                // section is that the file carries none of them. The rest of the flags are what
228                // gcc 16 writes, which is a shorter spelling than the one it uses elsewhere: no
229                // `@progbits`, since that is what a section is when nothing says otherwise.
230                let flags = match place {
231                    Place::Zero => "\"aw\",@nobits",
232                    Place::ReadOnly => "\"a\"",
233                    _ => "\"aw\"",
234                };
235                let _ = writeln!(out, "\t.section\t{named},{flags}");
236            }
237            // COFF gives every one of them the name of the section it came out of and tells the
238            // linker which symbol the group is about, which is the same COMDAT the code above is.
239            Directives::Coff => {
240                let (named, flags) = match place {
241                    Place::Zero => (".bss", "\"bw\""),
242                    Place::ReadOnly | Place::RelocReadOnly { .. } => (".rdata", "\"dr\""),
243                    _ => (".data", "\"dw\""),
244                };
245                let _ = writeln!(out, "\t.section\t{named},{flags},one_only,{name}");
246            }
247            Directives::MachO => return false,
248        }
249        true
250    }
251
252    /// The directive that opens the section a variable goes in.
253    ///
254    /// The three formats disagree about the names and about how much has to be said. ELF and COFF
255    /// have a directive per section that every assembler knows, and both want the flags spelled
256    /// out for a section the program named, since nothing else says whether it may be written to.
257    /// Mach-O has one directive and a segment in front of every section name.
258    ///
259    /// `name` is the variable's, which matters only when it is being given a section of its own.
260    pub fn section(self, out: &mut String, place: &Place, name: &str, sections: Sections) {
261        if sections.data && self.split(out, place, name) {
262            return;
263        }
264        match (self, place) {
265            // A tentative definition is not in a section at all, and the caller is what decides
266            // that. It is answered here as the section it would otherwise have gone in, so that
267            // the match stays about sections and nothing has to be said twice.
268            (Directives::Elf | Directives::Coff, Place::Written | Place::Merged) => {
269                out.push_str("\t.data\n");
270            }
271            (Directives::Elf | Directives::Coff, Place::Zero) => out.push_str("\t.bss\n"),
272            // The flags are spelled out because no assembler has a one word directive for either
273            // of these, and `T` is the one that matters: it is `SHF_TLS`, and it is what tells the
274            // linker the section is the template every thread gets a copy of rather than storage
275            // the program has one of. The other two are the `a` and `w` that `.data` has already.
276            (Directives::Elf, Place::Thread { zero: false }) => {
277                out.push_str("\t.section\t.tdata,\"awT\",@progbits\n");
278            }
279            (Directives::Elf, Place::Thread { zero: true }) => {
280                out.push_str("\t.section\t.tbss,\"awT\",@nobits\n");
281            }
282            // COFF and Mach-O spell thread-local storage in ways that are not a section with a
283            // flag on it, and [`crate::globals`] refuses a thread-local variable on both of them
284            // before anything reaches here. This arm is here because the match is over every pair
285            // of a format and a place, not because it is one that can be taken.
286            (Directives::Coff, Place::Thread { .. }) => out.push_str("\t.data\n"),
287            (Directives::Elf, Place::ReadOnly) => out.push_str("\t.section\t.rodata\n"),
288            (Directives::Elf, Place::RelocReadOnly { local }) => {
289                let name = if *local { ".data.rel.ro.local" } else { ".data.rel.ro" };
290                let _ = writeln!(out, "\t.section\t{name},\"aw\",@progbits");
291            }
292            // COFF has no section of this kind and needs none. A Windows image is relocated as a
293            // whole rather than a symbol at a time, and the loader makes whatever pages it has to
294            // write writable for as long as it is writing them and puts them back afterwards, so
295            // an address in a read only section costs a base relocation and nothing else.
296            (Directives::Coff, Place::ReadOnly | Place::RelocReadOnly { .. }) => {
297                out.push_str("\t.section\t.rdata,\"dr\"\n");
298            }
299            // The type is `@progbits` for almost every name a program writes, and the three it is
300            // not for are the ones the startup code calls what it finds in. A section of the wrong
301            // type under the right name is gathered by the linker all the same and then called by
302            // nobody, which is a program whose constructors silently do not run.
303            (Directives::Elf, Place::Named(name)) => {
304                let kind = Array::of(name).map_or("@progbits", Array::asm);
305                let _ = writeln!(out, "\t.section\t{name},\"aw\",{kind}");
306            }
307            (Directives::Coff, Place::Named(name)) => {
308                let _ = writeln!(out, "\t.section\t{name},\"dw\"");
309            }
310            (Directives::MachO, Place::ReadOnly) => out.push_str("\t.section\t__TEXT,__const\n"),
311            // Mach-O has the same problem and the same answer under a different name. A section in
312            // `__TEXT` is never writable, so a constant holding an address goes in `__DATA,__const`
313            // instead, which `dyld` writes and then protects. There is no `.local` half: the layout
314            // hint is an ELF linker's, and this one has nothing to do with it.
315            (Directives::MachO, Place::RelocReadOnly { .. }) => {
316                out.push_str("\t.section\t__DATA,__const\n");
317            }
318            // A Mach-O section name carries the segment it is in, so a program that named one
319            // named both halves and there is nothing to add to it.
320            (Directives::MachO, Place::Named(name)) => {
321                let _ = writeln!(out, "\t.section\t{name}");
322            }
323            (Directives::MachO, _) => out.push_str("\t.section\t__DATA,__data\n"),
324        }
325    }
326
327    /// What is said about a variable before its image, and whether an image follows.
328    ///
329    /// Two kinds of variable are one directive rather than a section, a label and bytes. A
330    /// tentative definition is a request to the linker for that much zeroed space on every format,
331    /// and on Mach-O so is a variable whose image is all zeros, because the section that would
332    /// hold it is one nothing may write bytes into.
333    pub fn variable(self, out: &mut String, var: &Variable, sections: Sections) -> bool {
334        let symbol = self.symbol();
335        let align = var.align.max(1).trailing_zeros();
336        match (self, &var.place) {
337            (_, Place::Merged) => {
338                let comm = if var.binding == Binding::Local { ".lcomm" } else { ".comm" };
339                let name = &var.name;
340                let _ = writeln!(out, "\t{comm}\t{symbol}{name},{},{}", var.size, var.align);
341                return false;
342            }
343            (Directives::MachO, Place::Zero) => {
344                let name = &var.name;
345                let _ =
346                    writeln!(out, "\t.zerofill\t__DATA,__bss,{symbol}{name},{},{align}", var.size);
347                return false;
348            }
349            _ => {}
350        }
351        self.section(out, &var.place, &var.name, sections);
352        match var.binding {
353            Binding::Global => {
354                let _ = writeln!(out, "\t.globl\t{symbol}{}", var.name);
355            }
356            Binding::Weak => {
357                let _ = writeln!(out, "\t.weak\t{symbol}{}", var.name);
358            }
359            // Nothing, which is what makes it invisible outside the file. A name no directive
360            // mentions is still in the symbol table as a local one, which is what `static` is.
361            Binding::Local => {}
362        }
363        self.seen(out, &var.name, var.binding, var.visibility);
364        let _ = writeln!(out, "\t.p2align\t{align}");
365        if self == Directives::Elf {
366            // The type a linker checks a relocation against. A reference to a thread-local is not
367            // the distance to an address, because it has a different address in every thread, so
368            // saying which kind of object this is is what lets the linker refuse a reference that
369            // asked for the wrong thing rather than resolve it to a number that means nothing.
370            let kind = match var.place {
371                Place::Thread { .. } => "@tls_object",
372                _ => "@object",
373            };
374            let _ = writeln!(out, "\t.type\t{}, {kind}", var.name);
375        }
376        let _ = writeln!(out, "{symbol}{}:", var.name);
377        true
378    }
379
380    /// What is said about a function after its last instruction.
381    ///
382    /// The size, on the format that has one. It is written as the distance from the label to here
383    /// rather than as a number, because the assembler is the one that knows how long an
384    /// instruction turned out to be and this file is what it is about to find out from.
385    pub fn close(self, out: &mut String, name: &str) {
386        if self == Directives::Elf {
387            let _ = writeln!(out, "\t.size\t{name}, .-{name}");
388        }
389    }
390
391    /// A second name for something the file already wrote down.
392    ///
393    /// The binding and then `.set`, which is all gcc writes and all an assembler needs: the type
394    /// and the size of the new symbol are taken from the old one, so writing them again would
395    /// only be a second chance to disagree. Nothing opens a section first, because the symbol is
396    /// an entry in a table rather than a byte of anything, and no `.size` closes it for the same
397    /// reason.
398    pub fn alias(self, out: &mut String, alias: &Alias) {
399        let symbol = self.symbol();
400        match alias.binding {
401            Binding::Global => {
402                let _ = writeln!(out, "\t.globl\t{symbol}{}", alias.name);
403            }
404            Binding::Weak => {
405                let _ = writeln!(out, "\t.weak\t{symbol}{}", alias.name);
406            }
407            Binding::Local => {}
408        }
409        self.seen(out, &alias.name, alias.binding, alias.visibility);
410        let _ = writeln!(out, "\t.set\t{symbol}{},{symbol}{}", alias.name, alias.target);
411    }
412
413    /// What is said once, after every function.
414    ///
415    /// `property` is what the file says it was built to have checked, which is written on the one
416    /// format that has somewhere to put it and is nothing on the other two.
417    pub fn end(self, out: &mut String, property: Property) {
418        match self {
419            Directives::Elf => {
420                if property.any() {
421                    self.property(out, property);
422                }
423                // Without this the stack is executable, which is not a default anybody chose.
424                out.push_str("\t.section\t.note.GNU-stack,\"\",@progbits\n");
425            }
426            // What lets the linker throw away a function nothing calls, which it cannot do
427            // without being told that the boundaries between them are real.
428            Directives::MachO => out.push_str("\t.subsections_via_symbols\n"),
429            Directives::Coff => {}
430        }
431    }
432
433    /// The note that says what the file was built to have checked.
434    ///
435    /// A note is how long its name is, how long its description is, which kind it is, the name and
436    /// then the description, and this kind's description is a list of properties. The one written
437    /// here is the feature word, whose bits are what `-fcf-protection=` asked for.
438    ///
439    /// The lengths count the padding that follows what they measure, which is why the description
440    /// is sixteen bytes for a property of twelve. Nothing between the name and the description,
441    /// because twelve bytes of header and four of name is already a multiple of eight, and the four
442    /// zero bytes at the end are what carries it to the next one. Written as numbers rather than as
443    /// distances between labels, which is what gcc writes, because the numbers are fixed by there
444    /// being exactly one property in it and a label in a listing is another name that can collide.
445    fn property(self, out: &mut String, property: Property) {
446        out.push_str("\t.section\t.note.gnu.property,\"a\",@note\n");
447        out.push_str("\t.p2align\t3\n");
448        let _ = writeln!(out, "\t.long\t4");
449        let _ = writeln!(out, "\t.long\t16");
450        let _ = writeln!(out, "\t.long\t5");
451        let _ = writeln!(out, "\t.asciz\t\"GNU\"");
452        let _ = writeln!(out, "\t.long\t{:#x}", Property::X86_FEATURES);
453        let _ = writeln!(out, "\t.long\t4");
454        let _ = writeln!(out, "\t.long\t{:#x}", property.features);
455        let _ = writeln!(out, "\t.long\t0");
456    }
457}
458
459/// What the object file is told about a function's name, from what the machine function carries.
460///
461/// Two names for one set of three, because the machine IR is not allowed to know what an object
462/// file is and the object writer is not allowed to know what a machine function is. This crate is
463/// where they meet, which is where the two spellings are put side by side.
464#[must_use]
465pub(crate) fn binding(binding: mir::Binding) -> Binding {
466    match binding {
467        mir::Binding::Global => Binding::Global,
468        mir::Binding::Local => Binding::Local,
469        mir::Binding::Weak => Binding::Weak,
470    }
471}
472
473/// What the object file is told about how far a name reaches outside a shared library, from what
474/// the machine function carries.
475///
476/// Two spellings of one set of three, for the reason [`binding`] above has two.
477#[must_use]
478pub(crate) fn visibility(visibility: mir::Visibility) -> Visibility {
479    match visibility {
480        mir::Visibility::Default => Visibility::Default,
481        mir::Visibility::Hidden => Visibility::Hidden,
482        mir::Visibility::Protected => Visibility::Protected,
483    }
484}
485
486#[cfg(test)]
487mod tests {
488    use rucc_object::FUNC_ALIGN;
489
490    use super::*;
491
492    #[test]
493    fn a_mach_o_symbol_is_the_c_name_with_an_underscore_in_front_of_it() {
494        let mut out = String::new();
495        Directives::MachO.open(&mut out, "main", 16, Binding::Global, Visibility::Default, "");
496        assert!(out.contains("\t.globl\t_main\n"), "{out}");
497        assert!(out.contains("\n_main:\n"), "{out}");
498        // No type and no size, neither of which Mach-O has.
499        assert!(!out.contains(".type"), "{out}");
500        let mut close = String::new();
501        Directives::MachO.close(&mut close, "main");
502        assert_eq!(close, "");
503    }
504
505    #[test]
506    fn an_elf_function_says_what_it_is_and_how_long_it_is() {
507        let mut out = String::new();
508        Directives::Elf.open(&mut out, "main", 16, Binding::Global, Visibility::Default, "");
509        Directives::Elf.close(&mut out, "main");
510        assert!(out.contains("\t.type\tmain, @function\n"), "{out}");
511        assert!(out.contains("\t.size\tmain, .-main\n"), "{out}");
512    }
513
514    #[test]
515    fn a_function_that_asked_to_be_more_aligned_is_written_at_that_alignment() {
516        let mut out = String::new();
517        Directives::Elf.open(&mut out, "f", 256, Binding::Global, Visibility::Default, "");
518        // The directive counts in powers of two and the attribute counts in bytes, and two
519        // hundred and fifty six bytes is eight of them.
520        assert!(out.contains("\t.p2align\t8, 0x90\n"), "{out}");
521        let mut plain = String::new();
522        Directives::Elf.open(&mut plain, "f", FUNC_ALIGN, Binding::Global, Visibility::Default, "");
523        assert!(plain.contains("\t.p2align\t4, 0x90\n"), "{plain}");
524    }
525
526    /// The two directives that say a name does not leave the shared library, or leaves it and
527    /// cannot be replaced.
528    ///
529    /// The listing half of tamnd/rucc#733. It matters that this is written in the listing and not
530    /// only in the object writer, because the two are the same compiler taking two roads out and a
531    /// program built through `-S` and an assembler has to come out the same as one built straight
532    /// to an object.
533    #[test]
534    fn a_name_that_does_not_leave_the_library_says_so_in_the_listing() {
535        let mut out = String::new();
536        Directives::Elf.open(&mut out, "f", 16, Binding::Global, Visibility::Hidden, "");
537        assert!(out.contains("\t.globl\tf\n"), "still global to the static linker: {out}");
538        assert!(out.contains("\t.hidden\tf\n"), "{out}");
539        let mut protected = String::new();
540        Directives::Elf.open(&mut protected, "f", 16, Binding::Global, Visibility::Protected, "");
541        assert!(protected.contains("\t.protected\tf\n"), "{protected}");
542        // Mach-O's one spelling of the one of these it has, and it carries the underscore every
543        // other Apple symbol does.
544        let mut apple = String::new();
545        Directives::MachO.open(&mut apple, "f", 16, Binding::Global, Visibility::Hidden, "");
546        assert!(apple.contains("\t.private_extern\t_f\n"), "{apple}");
547    }
548
549    /// A `static` name gets no visibility directive whatever it asked for.
550    ///
551    /// gcc writes none for one either, and an assembler that is handed `.hidden` for a name that
552    /// was never `.globl` has been told something about a symbol that is not in anybody's dynamic
553    /// table to begin with.
554    #[test]
555    fn a_static_name_is_told_nothing_about_a_dynamic_linker_it_will_never_meet() {
556        for seen in [Visibility::Default, Visibility::Hidden, Visibility::Protected] {
557            let mut out = String::new();
558            Directives::Elf.open(&mut out, "f", 16, Binding::Local, seen, "");
559            assert!(!out.contains(".hidden"), "{seen:?}: {out}");
560            assert!(!out.contains(".protected"), "{seen:?}: {out}");
561        }
562    }
563
564    /// The names are what gcc 16 writes for the same declarations, checked against it on a Linux
565    /// host, and the leading `.text.` is the part that has to be right rather than decoration:
566    /// `--gc-sections` and the linker scripts a kernel is linked with both match on it.
567    #[test]
568    fn a_function_given_a_section_of_its_own_opens_one_named_after_it() {
569        let split = Sections { functions: true, data: false };
570        let mut out = String::new();
571        Directives::Elf.code(&mut out, "f", split);
572        assert_eq!(out, "\t.section\t.text.f,\"ax\",@progbits\n");
573        // Windows says it as a COMDAT, which is one name for several sections and a symbol saying
574        // which of them is which. That is what clang writes for the same flag on a Windows target.
575        let mut windows = String::new();
576        Directives::Coff.code(&mut windows, "f", split);
577        assert_eq!(windows, "\t.section\t.text,\"xr\",one_only,f\n");
578        // Nothing on Mach-O, whose objects end with `.subsections_via_symbols` and so already let
579        // the linker drop a function nothing reaches.
580        let mut apple = String::new();
581        Directives::MachO.code(&mut apple, "f", split);
582        assert_eq!(apple, "");
583        // And nothing anywhere when nothing asked, which is the default and is what leaves every
584        // function in the one `.text` the file opens with.
585        for directives in [Directives::Elf, Directives::Coff, Directives::MachO] {
586            let mut plain = String::new();
587            directives.code(&mut plain, "f", Sections::default());
588            assert_eq!(plain, "", "{directives:?}");
589        }
590    }
591
592    /// Splitting must change which section header a symbol points at and nothing else, so each of
593    /// these carries the flags of the section it came out of. The spellings are gcc 16's, which is
594    /// shorter than what it writes for the unsplit sections: no `@progbits`, since that is what a
595    /// section is when nothing says otherwise.
596    #[test]
597    fn a_variable_given_a_section_of_its_own_keeps_the_flags_it_would_have_had() {
598        let split = Sections { functions: false, data: true };
599        let cases = [
600            (Place::Written, "\t.section\t.data.x,\"aw\"\n"),
601            (Place::Zero, "\t.section\t.bss.x,\"aw\",@nobits\n"),
602            (Place::ReadOnly, "\t.section\t.rodata.x,\"a\"\n"),
603            (Place::RelocReadOnly { local: false }, "\t.section\t.data.rel.ro.x,\"aw\"\n"),
604            (Place::RelocReadOnly { local: true }, "\t.section\t.data.rel.ro.local.x,\"aw\"\n"),
605        ];
606        for (place, want) in cases {
607            let mut out = String::new();
608            Directives::Elf.section(&mut out, &place, "x", split);
609            assert_eq!(out, want, "{place:?}");
610        }
611    }
612
613    /// The two kinds of variable the flag leaves alone, and the format that ignores it.
614    ///
615    /// A tentative definition is a request to the linker for that much zeroed space rather than an
616    /// image, so there is no section to split off, and a variable the program put a section name on
617    /// has the answer the source gave, which a flag must not overrule.
618    #[test]
619    fn a_variable_that_has_no_section_of_its_own_to_be_given_is_left_where_it_was() {
620        let split = Sections { functions: false, data: true };
621        let mut merged = String::new();
622        Directives::Elf.section(&mut merged, &Place::Merged, "x", split);
623        assert_eq!(merged, "\t.data\n");
624        let named = Place::Named(".init_array".to_owned());
625        let mut asked = String::new();
626        Directives::Elf.section(&mut asked, &named, "x", split);
627        assert_eq!(asked, "\t.section\t.init_array,\"aw\",@init_array\n");
628        let mut apple = String::new();
629        Directives::MachO.section(&mut apple, &Place::Written, "x", split);
630        assert_eq!(apple, "\t.section\t__DATA,__data\n");
631    }
632
633    /// The three names the startup code calls what it finds in, and one that merely begins like
634    /// one.
635    ///
636    /// A numbered priority is written as a suffix on the name and is the same kind of section, so
637    /// the type has to survive the number. `.init_arrays` is an ordinary section whose name happens
638    /// to start with one of theirs, and writing the type on it would tell the linker to gather it
639    /// with them.
640    #[test]
641    fn a_section_of_function_addresses_says_which_kind_it_is() {
642        let cases = [
643            (".init_array", "\t.section\t.init_array,\"aw\",@init_array\n"),
644            (".init_array.00101", "\t.section\t.init_array.00101,\"aw\",@init_array\n"),
645            (".fini_array", "\t.section\t.fini_array,\"aw\",@fini_array\n"),
646            (".preinit_array", "\t.section\t.preinit_array,\"aw\",@preinit_array\n"),
647            (".init_arrays", "\t.section\t.init_arrays,\"aw\",@progbits\n"),
648        ];
649        for (name, want) in cases {
650            let mut out = String::new();
651            let place = Place::Named(name.to_owned());
652            Directives::Elf.section(&mut out, &place, "x", Sections::default());
653            assert_eq!(out, want, "{name}");
654        }
655    }
656
657    #[test]
658    fn an_elf_file_says_the_stack_is_not_executable() {
659        // The absence of this is what makes it executable, so the test is that it is there
660        // rather than that it is spelled a particular way.
661        let mut out = String::new();
662        Directives::Elf.end(&mut out, Property::default());
663        assert!(out.contains(".note.GNU-stack"), "{out}");
664        assert!(!out.contains(".note.gnu.property"), "nothing was asked to be checked");
665    }
666
667    /// What the file says it was built to have checked, as the assembler reads it.
668    ///
669    /// The two lengths are the part worth a test. They count the padding after what they measure,
670    /// so a note that gets them right for its own contents and wrong for the alignment is one the
671    /// linker drops without a word, and what comes of that is a program the loader leaves the check
672    /// turned off for.
673    #[test]
674    fn an_elf_file_says_what_it_was_built_to_have_checked() {
675        let mut out = String::new();
676        Directives::Elf.end(&mut out, Property { features: Property::IBT });
677        let lines: Vec<&str> = out.lines().collect();
678        assert_eq!(
679            lines,
680            [
681                "\t.section\t.note.gnu.property,\"a\",@note",
682                "\t.p2align\t3",
683                "\t.long\t4",
684                "\t.long\t16",
685                "\t.long\t5",
686                "\t.asciz\t\"GNU\"",
687                "\t.long\t0xc0000002",
688                "\t.long\t4",
689                "\t.long\t0x1",
690                "\t.long\t0",
691                "\t.section\t.note.GNU-stack,\"\",@progbits",
692            ]
693        );
694    }
695
696    #[test]
697    fn every_object_format_has_directives() {
698        for format in [ObjectFormat::Elf, ObjectFormat::MachO, ObjectFormat::Coff] {
699            let directives = Directives::of(format);
700            assert!(directives.text().starts_with('\t'));
701            let mut out = String::new();
702            directives.open(&mut out, "f", 16, Binding::Global, Visibility::Default, "");
703            directives.close(&mut out, "f");
704            directives.end(&mut out, Property::default());
705            assert!(out.ends_with('\n'), "{format:?} left a line unfinished");
706        }
707    }
708}