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, 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            (Directives::Elf, Place::ReadOnly) => out.push_str("\t.section\t.rodata\n"),
273            (Directives::Elf, Place::RelocReadOnly { local }) => {
274                let name = if *local { ".data.rel.ro.local" } else { ".data.rel.ro" };
275                let _ = writeln!(out, "\t.section\t{name},\"aw\",@progbits");
276            }
277            // COFF has no section of this kind and needs none. A Windows image is relocated as a
278            // whole rather than a symbol at a time, and the loader makes whatever pages it has to
279            // write writable for as long as it is writing them and puts them back afterwards, so
280            // an address in a read only section costs a base relocation and nothing else.
281            (Directives::Coff, Place::ReadOnly | Place::RelocReadOnly { .. }) => {
282                out.push_str("\t.section\t.rdata,\"dr\"\n");
283            }
284            (Directives::Elf, Place::Named(name)) => {
285                let _ = writeln!(out, "\t.section\t{name},\"aw\",@progbits");
286            }
287            (Directives::Coff, Place::Named(name)) => {
288                let _ = writeln!(out, "\t.section\t{name},\"dw\"");
289            }
290            (Directives::MachO, Place::ReadOnly) => out.push_str("\t.section\t__TEXT,__const\n"),
291            // Mach-O has the same problem and the same answer under a different name. A section in
292            // `__TEXT` is never writable, so a constant holding an address goes in `__DATA,__const`
293            // instead, which `dyld` writes and then protects. There is no `.local` half: the layout
294            // hint is an ELF linker's, and this one has nothing to do with it.
295            (Directives::MachO, Place::RelocReadOnly { .. }) => {
296                out.push_str("\t.section\t__DATA,__const\n");
297            }
298            // A Mach-O section name carries the segment it is in, so a program that named one
299            // named both halves and there is nothing to add to it.
300            (Directives::MachO, Place::Named(name)) => {
301                let _ = writeln!(out, "\t.section\t{name}");
302            }
303            (Directives::MachO, _) => out.push_str("\t.section\t__DATA,__data\n"),
304        }
305    }
306
307    /// What is said about a variable before its image, and whether an image follows.
308    ///
309    /// Two kinds of variable are one directive rather than a section, a label and bytes. A
310    /// tentative definition is a request to the linker for that much zeroed space on every format,
311    /// and on Mach-O so is a variable whose image is all zeros, because the section that would
312    /// hold it is one nothing may write bytes into.
313    pub fn variable(self, out: &mut String, var: &Variable, sections: Sections) -> bool {
314        let symbol = self.symbol();
315        let align = var.align.max(1).trailing_zeros();
316        match (self, &var.place) {
317            (_, Place::Merged) => {
318                let comm = if var.binding == Binding::Local { ".lcomm" } else { ".comm" };
319                let name = &var.name;
320                let _ = writeln!(out, "\t{comm}\t{symbol}{name},{},{}", var.size, var.align);
321                return false;
322            }
323            (Directives::MachO, Place::Zero) => {
324                let name = &var.name;
325                let _ =
326                    writeln!(out, "\t.zerofill\t__DATA,__bss,{symbol}{name},{},{align}", var.size);
327                return false;
328            }
329            _ => {}
330        }
331        self.section(out, &var.place, &var.name, sections);
332        match var.binding {
333            Binding::Global => {
334                let _ = writeln!(out, "\t.globl\t{symbol}{}", var.name);
335            }
336            Binding::Weak => {
337                let _ = writeln!(out, "\t.weak\t{symbol}{}", var.name);
338            }
339            // Nothing, which is what makes it invisible outside the file. A name no directive
340            // mentions is still in the symbol table as a local one, which is what `static` is.
341            Binding::Local => {}
342        }
343        self.seen(out, &var.name, var.binding, var.visibility);
344        let _ = writeln!(out, "\t.p2align\t{align}");
345        if self == Directives::Elf {
346            let _ = writeln!(out, "\t.type\t{}, @object", var.name);
347        }
348        let _ = writeln!(out, "{symbol}{}:", var.name);
349        true
350    }
351
352    /// What is said about a function after its last instruction.
353    ///
354    /// The size, on the format that has one. It is written as the distance from the label to here
355    /// rather than as a number, because the assembler is the one that knows how long an
356    /// instruction turned out to be and this file is what it is about to find out from.
357    pub fn close(self, out: &mut String, name: &str) {
358        if self == Directives::Elf {
359            let _ = writeln!(out, "\t.size\t{name}, .-{name}");
360        }
361    }
362
363    /// A second name for something the file already wrote down.
364    ///
365    /// The binding and then `.set`, which is all gcc writes and all an assembler needs: the type
366    /// and the size of the new symbol are taken from the old one, so writing them again would
367    /// only be a second chance to disagree. Nothing opens a section first, because the symbol is
368    /// an entry in a table rather than a byte of anything, and no `.size` closes it for the same
369    /// reason.
370    pub fn alias(self, out: &mut String, alias: &Alias) {
371        let symbol = self.symbol();
372        match alias.binding {
373            Binding::Global => {
374                let _ = writeln!(out, "\t.globl\t{symbol}{}", alias.name);
375            }
376            Binding::Weak => {
377                let _ = writeln!(out, "\t.weak\t{symbol}{}", alias.name);
378            }
379            Binding::Local => {}
380        }
381        self.seen(out, &alias.name, alias.binding, alias.visibility);
382        let _ = writeln!(out, "\t.set\t{symbol}{},{symbol}{}", alias.name, alias.target);
383    }
384
385    /// What is said once, after every function.
386    ///
387    /// `property` is what the file says it was built to have checked, which is written on the one
388    /// format that has somewhere to put it and is nothing on the other two.
389    pub fn end(self, out: &mut String, property: Property) {
390        match self {
391            Directives::Elf => {
392                if property.any() {
393                    self.property(out, property);
394                }
395                // Without this the stack is executable, which is not a default anybody chose.
396                out.push_str("\t.section\t.note.GNU-stack,\"\",@progbits\n");
397            }
398            // What lets the linker throw away a function nothing calls, which it cannot do
399            // without being told that the boundaries between them are real.
400            Directives::MachO => out.push_str("\t.subsections_via_symbols\n"),
401            Directives::Coff => {}
402        }
403    }
404
405    /// The note that says what the file was built to have checked.
406    ///
407    /// A note is how long its name is, how long its description is, which kind it is, the name and
408    /// then the description, and this kind's description is a list of properties. The one written
409    /// here is the feature word, whose bits are what `-fcf-protection=` asked for.
410    ///
411    /// The lengths count the padding that follows what they measure, which is why the description
412    /// is sixteen bytes for a property of twelve. Nothing between the name and the description,
413    /// because twelve bytes of header and four of name is already a multiple of eight, and the four
414    /// zero bytes at the end are what carries it to the next one. Written as numbers rather than as
415    /// distances between labels, which is what gcc writes, because the numbers are fixed by there
416    /// being exactly one property in it and a label in a listing is another name that can collide.
417    fn property(self, out: &mut String, property: Property) {
418        out.push_str("\t.section\t.note.gnu.property,\"a\",@note\n");
419        out.push_str("\t.p2align\t3\n");
420        let _ = writeln!(out, "\t.long\t4");
421        let _ = writeln!(out, "\t.long\t16");
422        let _ = writeln!(out, "\t.long\t5");
423        let _ = writeln!(out, "\t.asciz\t\"GNU\"");
424        let _ = writeln!(out, "\t.long\t{:#x}", Property::X86_FEATURES);
425        let _ = writeln!(out, "\t.long\t4");
426        let _ = writeln!(out, "\t.long\t{:#x}", property.features);
427        let _ = writeln!(out, "\t.long\t0");
428    }
429}
430
431/// What the object file is told about a function's name, from what the machine function carries.
432///
433/// Two names for one set of three, because the machine IR is not allowed to know what an object
434/// file is and the object writer is not allowed to know what a machine function is. This crate is
435/// where they meet, which is where the two spellings are put side by side.
436#[must_use]
437pub(crate) fn binding(binding: mir::Binding) -> Binding {
438    match binding {
439        mir::Binding::Global => Binding::Global,
440        mir::Binding::Local => Binding::Local,
441        mir::Binding::Weak => Binding::Weak,
442    }
443}
444
445/// What the object file is told about how far a name reaches outside a shared library, from what
446/// the machine function carries.
447///
448/// Two spellings of one set of three, for the reason [`binding`] above has two.
449#[must_use]
450pub(crate) fn visibility(visibility: mir::Visibility) -> Visibility {
451    match visibility {
452        mir::Visibility::Default => Visibility::Default,
453        mir::Visibility::Hidden => Visibility::Hidden,
454        mir::Visibility::Protected => Visibility::Protected,
455    }
456}
457
458#[cfg(test)]
459mod tests {
460    use rucc_object::FUNC_ALIGN;
461
462    use super::*;
463
464    #[test]
465    fn a_mach_o_symbol_is_the_c_name_with_an_underscore_in_front_of_it() {
466        let mut out = String::new();
467        Directives::MachO.open(&mut out, "main", 16, Binding::Global, Visibility::Default, "");
468        assert!(out.contains("\t.globl\t_main\n"), "{out}");
469        assert!(out.contains("\n_main:\n"), "{out}");
470        // No type and no size, neither of which Mach-O has.
471        assert!(!out.contains(".type"), "{out}");
472        let mut close = String::new();
473        Directives::MachO.close(&mut close, "main");
474        assert_eq!(close, "");
475    }
476
477    #[test]
478    fn an_elf_function_says_what_it_is_and_how_long_it_is() {
479        let mut out = String::new();
480        Directives::Elf.open(&mut out, "main", 16, Binding::Global, Visibility::Default, "");
481        Directives::Elf.close(&mut out, "main");
482        assert!(out.contains("\t.type\tmain, @function\n"), "{out}");
483        assert!(out.contains("\t.size\tmain, .-main\n"), "{out}");
484    }
485
486    #[test]
487    fn a_function_that_asked_to_be_more_aligned_is_written_at_that_alignment() {
488        let mut out = String::new();
489        Directives::Elf.open(&mut out, "f", 256, Binding::Global, Visibility::Default, "");
490        // The directive counts in powers of two and the attribute counts in bytes, and two
491        // hundred and fifty six bytes is eight of them.
492        assert!(out.contains("\t.p2align\t8, 0x90\n"), "{out}");
493        let mut plain = String::new();
494        Directives::Elf.open(&mut plain, "f", FUNC_ALIGN, Binding::Global, Visibility::Default, "");
495        assert!(plain.contains("\t.p2align\t4, 0x90\n"), "{plain}");
496    }
497
498    /// The two directives that say a name does not leave the shared library, or leaves it and
499    /// cannot be replaced.
500    ///
501    /// The listing half of tamnd/rucc#733. It matters that this is written in the listing and not
502    /// only in the object writer, because the two are the same compiler taking two roads out and a
503    /// program built through `-S` and an assembler has to come out the same as one built straight
504    /// to an object.
505    #[test]
506    fn a_name_that_does_not_leave_the_library_says_so_in_the_listing() {
507        let mut out = String::new();
508        Directives::Elf.open(&mut out, "f", 16, Binding::Global, Visibility::Hidden, "");
509        assert!(out.contains("\t.globl\tf\n"), "still global to the static linker: {out}");
510        assert!(out.contains("\t.hidden\tf\n"), "{out}");
511        let mut protected = String::new();
512        Directives::Elf.open(&mut protected, "f", 16, Binding::Global, Visibility::Protected, "");
513        assert!(protected.contains("\t.protected\tf\n"), "{protected}");
514        // Mach-O's one spelling of the one of these it has, and it carries the underscore every
515        // other Apple symbol does.
516        let mut apple = String::new();
517        Directives::MachO.open(&mut apple, "f", 16, Binding::Global, Visibility::Hidden, "");
518        assert!(apple.contains("\t.private_extern\t_f\n"), "{apple}");
519    }
520
521    /// A `static` name gets no visibility directive whatever it asked for.
522    ///
523    /// gcc writes none for one either, and an assembler that is handed `.hidden` for a name that
524    /// was never `.globl` has been told something about a symbol that is not in anybody's dynamic
525    /// table to begin with.
526    #[test]
527    fn a_static_name_is_told_nothing_about_a_dynamic_linker_it_will_never_meet() {
528        for seen in [Visibility::Default, Visibility::Hidden, Visibility::Protected] {
529            let mut out = String::new();
530            Directives::Elf.open(&mut out, "f", 16, Binding::Local, seen, "");
531            assert!(!out.contains(".hidden"), "{seen:?}: {out}");
532            assert!(!out.contains(".protected"), "{seen:?}: {out}");
533        }
534    }
535
536    /// The names are what gcc 16 writes for the same declarations, checked against it on a Linux
537    /// host, and the leading `.text.` is the part that has to be right rather than decoration:
538    /// `--gc-sections` and the linker scripts a kernel is linked with both match on it.
539    #[test]
540    fn a_function_given_a_section_of_its_own_opens_one_named_after_it() {
541        let split = Sections { functions: true, data: false };
542        let mut out = String::new();
543        Directives::Elf.code(&mut out, "f", split);
544        assert_eq!(out, "\t.section\t.text.f,\"ax\",@progbits\n");
545        // Windows says it as a COMDAT, which is one name for several sections and a symbol saying
546        // which of them is which. That is what clang writes for the same flag on a Windows target.
547        let mut windows = String::new();
548        Directives::Coff.code(&mut windows, "f", split);
549        assert_eq!(windows, "\t.section\t.text,\"xr\",one_only,f\n");
550        // Nothing on Mach-O, whose objects end with `.subsections_via_symbols` and so already let
551        // the linker drop a function nothing reaches.
552        let mut apple = String::new();
553        Directives::MachO.code(&mut apple, "f", split);
554        assert_eq!(apple, "");
555        // And nothing anywhere when nothing asked, which is the default and is what leaves every
556        // function in the one `.text` the file opens with.
557        for directives in [Directives::Elf, Directives::Coff, Directives::MachO] {
558            let mut plain = String::new();
559            directives.code(&mut plain, "f", Sections::default());
560            assert_eq!(plain, "", "{directives:?}");
561        }
562    }
563
564    /// Splitting must change which section header a symbol points at and nothing else, so each of
565    /// these carries the flags of the section it came out of. The spellings are gcc 16's, which is
566    /// shorter than what it writes for the unsplit sections: no `@progbits`, since that is what a
567    /// section is when nothing says otherwise.
568    #[test]
569    fn a_variable_given_a_section_of_its_own_keeps_the_flags_it_would_have_had() {
570        let split = Sections { functions: false, data: true };
571        let cases = [
572            (Place::Written, "\t.section\t.data.x,\"aw\"\n"),
573            (Place::Zero, "\t.section\t.bss.x,\"aw\",@nobits\n"),
574            (Place::ReadOnly, "\t.section\t.rodata.x,\"a\"\n"),
575            (Place::RelocReadOnly { local: false }, "\t.section\t.data.rel.ro.x,\"aw\"\n"),
576            (Place::RelocReadOnly { local: true }, "\t.section\t.data.rel.ro.local.x,\"aw\"\n"),
577        ];
578        for (place, want) in cases {
579            let mut out = String::new();
580            Directives::Elf.section(&mut out, &place, "x", split);
581            assert_eq!(out, want, "{place:?}");
582        }
583    }
584
585    /// The two kinds of variable the flag leaves alone, and the format that ignores it.
586    ///
587    /// A tentative definition is a request to the linker for that much zeroed space rather than an
588    /// image, so there is no section to split off, and a variable the program put a section name on
589    /// has the answer the source gave, which a flag must not overrule.
590    #[test]
591    fn a_variable_that_has_no_section_of_its_own_to_be_given_is_left_where_it_was() {
592        let split = Sections { functions: false, data: true };
593        let mut merged = String::new();
594        Directives::Elf.section(&mut merged, &Place::Merged, "x", split);
595        assert_eq!(merged, "\t.data\n");
596        let named = Place::Named(".init_array".to_owned());
597        let mut asked = String::new();
598        Directives::Elf.section(&mut asked, &named, "x", split);
599        assert_eq!(asked, "\t.section\t.init_array,\"aw\",@progbits\n");
600        let mut apple = String::new();
601        Directives::MachO.section(&mut apple, &Place::Written, "x", split);
602        assert_eq!(apple, "\t.section\t__DATA,__data\n");
603    }
604
605    #[test]
606    fn an_elf_file_says_the_stack_is_not_executable() {
607        // The absence of this is what makes it executable, so the test is that it is there
608        // rather than that it is spelled a particular way.
609        let mut out = String::new();
610        Directives::Elf.end(&mut out, Property::default());
611        assert!(out.contains(".note.GNU-stack"), "{out}");
612        assert!(!out.contains(".note.gnu.property"), "nothing was asked to be checked");
613    }
614
615    /// What the file says it was built to have checked, as the assembler reads it.
616    ///
617    /// The two lengths are the part worth a test. They count the padding after what they measure,
618    /// so a note that gets them right for its own contents and wrong for the alignment is one the
619    /// linker drops without a word, and what comes of that is a program the loader leaves the check
620    /// turned off for.
621    #[test]
622    fn an_elf_file_says_what_it_was_built_to_have_checked() {
623        let mut out = String::new();
624        Directives::Elf.end(&mut out, Property { features: Property::IBT });
625        let lines: Vec<&str> = out.lines().collect();
626        assert_eq!(
627            lines,
628            [
629                "\t.section\t.note.gnu.property,\"a\",@note",
630                "\t.p2align\t3",
631                "\t.long\t4",
632                "\t.long\t16",
633                "\t.long\t5",
634                "\t.asciz\t\"GNU\"",
635                "\t.long\t0xc0000002",
636                "\t.long\t4",
637                "\t.long\t0x1",
638                "\t.long\t0",
639                "\t.section\t.note.GNU-stack,\"\",@progbits",
640            ]
641        );
642    }
643
644    #[test]
645    fn every_object_format_has_directives() {
646        for format in [ObjectFormat::Elf, ObjectFormat::MachO, ObjectFormat::Coff] {
647            let directives = Directives::of(format);
648            assert!(directives.text().starts_with('\t'));
649            let mut out = String::new();
650            directives.open(&mut out, "f", 16, Binding::Global, Visibility::Default, "");
651            directives.close(&mut out, "f");
652            directives.end(&mut out, Property::default());
653            assert!(out.ends_with('\n'), "{format:?} left a line unfinished");
654        }
655    }
656}