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. `fill` is the byte the padding is made of, which
117    /// on x86-64 is `0x90` because the space in front of a function is reached by falling off the
118    /// end of the one before it and that byte is a `nop`. A machine with no one byte `nop` gives
119    /// `None` and the assembler pads with whatever `nop` the machine has.
120    #[allow(
121        clippy::too_many_arguments,
122        reason = "each is a separate thing a function is opened with"
123    )]
124    pub fn open(
125        self,
126        out: &mut String,
127        name: &str,
128        align: u32,
129        fill: Option<u8>,
130        binding: Binding,
131        visibility: Visibility,
132        ahead: &str,
133    ) {
134        let symbol = self.symbol();
135        let power = align.max(1).trailing_zeros();
136        let _ = match fill {
137            Some(byte) => writeln!(out, "\t.p2align\t{power}, {byte:#x}"),
138            None => writeln!(out, "\t.p2align\t{power}"),
139        };
140        self.bind(out, name, binding);
141        self.seen(out, name, binding, visibility);
142        match self {
143            Directives::Elf => {
144                let _ = writeln!(out, "\t.type\t{name}, @function");
145            }
146            // Windows says the storage class and the type code, and thirty two is a function.
147            Directives::Coff => {
148                let scl = if binding == Binding::Local { 3 } else { 2 };
149                let _ = writeln!(out, "\t.def\t{name}\n\t.scl\t{scl}\n\t.type\t32\n\t.endef");
150            }
151            Directives::MachO => {}
152        }
153        out.push_str(ahead);
154        let _ = writeln!(out, "{symbol}{name}:");
155    }
156
157    /// Where the room a patcher was promised at the top of this function is, as the record a
158    /// tracer reads to find every one of them.
159    ///
160    /// Eight bytes in a section of its own holding the address of the room, and the section is the
161    /// point of it: a tracer that wants to patch every function in a kernel has to be able to find
162    /// them without reading the symbol table, which a stripped image does not have. `o` is the flag
163    /// that ties this section to the text the label is in, so that a linker throwing that text away
164    /// throws the record away with it and never leaves an address pointing at nothing.
165    ///
166    /// `back` is what returns to the text section, which is passed in because which one that is
167    /// depends on whether every function got a section of its own and this does not otherwise care.
168    ///
169    /// Nothing on the other two formats. Neither has a section that works this way and neither has
170    /// a tracer looking for one, and the driver refuses the flag on a target that is not ELF rather
171    /// than letting a build come out looking patchable and not being.
172    pub fn patchable(self, out: &mut String, label: &str, back: &str) {
173        if self != Directives::Elf {
174            return;
175        }
176        let _ = writeln!(out, "\t.section\t__patchable_function_entries,\"awo\",@progbits,{label}");
177        let _ = writeln!(out, "\t.align\t8");
178        let _ = writeln!(out, "\t.quad\t{label}");
179        let _ = writeln!(out, "{back}");
180    }
181
182    /// What is said about how far a name reaches outside a shared library, which is nothing at
183    /// all in the ordinary case.
184    ///
185    /// A local name gets no directive whatever was asked for. `static` is already invisible to
186    /// everything outside the file, so there is no dynamic symbol table for it to be in or out of,
187    /// and gcc writes no visibility directive for one either.
188    ///
189    /// ELF says both of the other two and says them the same way an assembler expects. Mach-O has
190    /// one of them: `.private_extern` is a symbol that leaves this object and does not leave the
191    /// library, which is what hidden means, and there is no Mach-O spelling of protected because
192    /// the format has no way to say a symbol is exported and cannot be interposed. COFF has
193    /// neither, since what leaves a Windows DLL is decided by an export table the linker is given
194    /// rather than by a bit on each symbol.
195    pub fn seen(self, out: &mut String, name: &str, binding: Binding, visibility: Visibility) {
196        if binding == Binding::Local || visibility == Visibility::Default {
197            return;
198        }
199        let symbol = self.symbol();
200        match (self, visibility) {
201            (Directives::Elf, Visibility::Hidden) => {
202                let _ = writeln!(out, "\t.hidden\t{name}");
203            }
204            (Directives::Elf, Visibility::Protected) => {
205                let _ = writeln!(out, "\t.protected\t{name}");
206            }
207            (Directives::MachO, Visibility::Hidden) => {
208                let _ = writeln!(out, "\t.private_extern\t{symbol}{name}");
209            }
210            (Directives::MachO, Visibility::Protected) | (Directives::Coff, _) => {}
211            (_, Visibility::Default) => unreachable!("returned above"),
212        }
213    }
214
215    /// The directive that opens the section a variable goes in when it is being given one of its
216    /// own, and nothing at all when it is not.
217    ///
218    /// The name is worked out once, in [`Place::split`], so that the listing and the object file
219    /// cannot come to disagree about it. What is left here is the flags, which are the flags the
220    /// section it was split off from carries: splitting changes which section header a symbol
221    /// points at and must not quietly change whether the page it lands in is writable.
222    ///
223    /// Nothing on Mach-O, for the reason [`Directives::code`] gives.
224    fn split(self, out: &mut String, place: &Place, name: &str) -> bool {
225        let Some(named) = place.split(name) else { return false };
226        match self {
227            Directives::Elf => {
228                // `@nobits` for the zero filled one, because a section that says nothing about it
229                // is one the assembler writes the bytes of into the file, and the point of that
230                // section is that the file carries none of them. The rest of the flags are what
231                // gcc 16 writes, which is a shorter spelling than the one it uses elsewhere: no
232                // `@progbits`, since that is what a section is when nothing says otherwise.
233                let flags = match place {
234                    Place::Zero => "\"aw\",@nobits",
235                    Place::ReadOnly => "\"a\"",
236                    _ => "\"aw\"",
237                };
238                let _ = writeln!(out, "\t.section\t{named},{flags}");
239            }
240            // COFF gives every one of them the name of the section it came out of and tells the
241            // linker which symbol the group is about, which is the same COMDAT the code above is.
242            Directives::Coff => {
243                let (named, flags) = match place {
244                    Place::Zero => (".bss", "\"bw\""),
245                    Place::ReadOnly | Place::RelocReadOnly { .. } => (".rdata", "\"dr\""),
246                    _ => (".data", "\"dw\""),
247                };
248                let _ = writeln!(out, "\t.section\t{named},{flags},one_only,{name}");
249            }
250            Directives::MachO => return false,
251        }
252        true
253    }
254
255    /// The directive that opens the section a variable goes in.
256    ///
257    /// The three formats disagree about the names and about how much has to be said. ELF and COFF
258    /// have a directive per section that every assembler knows, and both want the flags spelled
259    /// out for a section the program named, since nothing else says whether it may be written to.
260    /// Mach-O has one directive and a segment in front of every section name.
261    ///
262    /// `name` is the variable's, which matters only when it is being given a section of its own.
263    pub fn section(self, out: &mut String, place: &Place, name: &str, sections: Sections) {
264        if sections.data && self.split(out, place, name) {
265            return;
266        }
267        match (self, place) {
268            // A tentative definition is not in a section at all, and the caller is what decides
269            // that. It is answered here as the section it would otherwise have gone in, so that
270            // the match stays about sections and nothing has to be said twice.
271            (Directives::Elf | Directives::Coff, Place::Written | Place::Merged) => {
272                out.push_str("\t.data\n");
273            }
274            (Directives::Elf | Directives::Coff, Place::Zero) => out.push_str("\t.bss\n"),
275            // The flags are spelled out because no assembler has a one word directive for either
276            // of these, and `T` is the one that matters: it is `SHF_TLS`, and it is what tells the
277            // linker the section is the template every thread gets a copy of rather than storage
278            // the program has one of. The other two are the `a` and `w` that `.data` has already.
279            (Directives::Elf, Place::Thread { zero: false }) => {
280                out.push_str("\t.section\t.tdata,\"awT\",@progbits\n");
281            }
282            (Directives::Elf, Place::Thread { zero: true }) => {
283                out.push_str("\t.section\t.tbss,\"awT\",@nobits\n");
284            }
285            // The section every thread gets a copy of, which the linker sorts in after the `.tls`
286            // the C runtime starts it with. There is no zeroed half, so [`crate::globals`] never
287            // gives this format a zeroed one.
288            (Directives::Coff, Place::Thread { .. }) => out.push_str("\t.section\t.tls$,\"dw\"\n"),
289            (Directives::Elf, Place::ReadOnly) => out.push_str("\t.section\t.rodata\n"),
290            (Directives::Elf, Place::RelocReadOnly { local }) => {
291                let name = if *local { ".data.rel.ro.local" } else { ".data.rel.ro" };
292                let _ = writeln!(out, "\t.section\t{name},\"aw\",@progbits");
293            }
294            // COFF has no section of this kind and needs none. A Windows image is relocated as a
295            // whole rather than a symbol at a time, and the loader makes whatever pages it has to
296            // write writable for as long as it is writing them and puts them back afterwards, so
297            // an address in a read only section costs a base relocation and nothing else.
298            (Directives::Coff, Place::ReadOnly | Place::RelocReadOnly { .. }) => {
299                out.push_str("\t.section\t.rdata,\"dr\"\n");
300            }
301            // The type is `@progbits` for almost every name a program writes, and the three it is
302            // not for are the ones the startup code calls what it finds in. A section of the wrong
303            // type under the right name is gathered by the linker all the same and then called by
304            // nobody, which is a program whose constructors silently do not run.
305            (Directives::Elf, Place::Named(name)) => {
306                let kind = Array::of(name).map_or("@progbits", Array::asm);
307                let _ = writeln!(out, "\t.section\t{name},\"aw\",{kind}");
308            }
309            (Directives::Coff, Place::Named(name)) => {
310                let _ = writeln!(out, "\t.section\t{name},\"dw\"");
311            }
312            (Directives::MachO, Place::ReadOnly) => out.push_str("\t.section\t__TEXT,__const\n"),
313            // Mach-O has the same problem and the same answer under a different name. A section in
314            // `__TEXT` is never writable, so a constant holding an address goes in `__DATA,__const`
315            // instead, which `dyld` writes and then protects. There is no `.local` half: the layout
316            // hint is an ELF linker's, and this one has nothing to do with it.
317            (Directives::MachO, Place::RelocReadOnly { .. }) => {
318                out.push_str("\t.section\t__DATA,__const\n");
319            }
320            // A Mach-O section name carries the segment it is in, so a program that named one
321            // named both halves and there is nothing to add to it.
322            (Directives::MachO, Place::Named(name)) => {
323                let _ = writeln!(out, "\t.section\t{name}");
324            }
325            (Directives::MachO, Place::Thread { .. }) => {
326                out.push_str("\t.section\t__DATA,__thread_data,thread_local_regular\n");
327            }
328            (Directives::MachO, _) => out.push_str("\t.section\t__DATA,__data\n"),
329        }
330    }
331
332    /// What is said about a variable before its image, and whether an image follows.
333    ///
334    /// Two kinds of variable are one directive rather than a section, a label and bytes. A
335    /// tentative definition is a request to the linker for that much zeroed space on every format,
336    /// and on Mach-O so is a variable whose image is all zeros, because the section that would
337    /// hold it is one nothing may write bytes into.
338    pub fn variable(self, out: &mut String, var: &Variable, sections: Sections) -> bool {
339        let symbol = self.symbol();
340        let align = var.align.max(1).trailing_zeros();
341        match (self, &var.place) {
342            (_, Place::Merged) => {
343                let comm = if var.binding == Binding::Local { ".lcomm" } else { ".comm" };
344                let name = &var.name;
345                // Apple's assembler takes the alignment as a power of two and gas as a count of
346                // bytes, which are the same number only for one byte.
347                let boundary = if self == Directives::MachO { u64::from(align) } else { var.align };
348                let _ = writeln!(out, "\t{comm}\t{symbol}{name},{},{boundary}", var.size);
349                return false;
350            }
351            // Apple's `.tbss` is `.zerofill` for the per thread image, and the name a program uses is
352            // the descriptor written after it, so that is the one that gets the binding.
353            (Directives::MachO, Place::Thread { zero: true }) => {
354                let name = &var.name;
355                let _ = writeln!(out, "\t.tbss\t{symbol}{name}$tlv$init,{},{align}", var.size);
356                self.descriptor(out, var);
357                return false;
358            }
359            (Directives::MachO, Place::Thread { zero: false }) => {
360                self.section(out, &var.place, &var.name, sections);
361                let _ = writeln!(out, "\t.p2align\t{align}");
362                let _ = writeln!(out, "{symbol}{}$tlv$init:", var.name);
363                return true;
364            }
365            // The directive defines the symbol and says nothing about who may see it, so the
366            // binding is written first, the same as it is above a label.
367            (Directives::MachO, Place::Zero) => {
368                let name = &var.name;
369                self.bind(out, name, var.binding);
370                self.seen(out, name, var.binding, var.visibility);
371                let _ =
372                    writeln!(out, "\t.zerofill\t__DATA,__bss,{symbol}{name},{},{align}", var.size);
373                return false;
374            }
375            _ => {}
376        }
377        self.section(out, &var.place, &var.name, sections);
378        self.bind(out, &var.name, var.binding);
379        self.seen(out, &var.name, var.binding, var.visibility);
380        let _ = writeln!(out, "\t.p2align\t{align}");
381        if self == Directives::Elf {
382            // The type a linker checks a relocation against. A reference to a thread-local is not
383            // the distance to an address, because it has a different address in every thread, so
384            // saying which kind of object this is is what lets the linker refuse a reference that
385            // asked for the wrong thing rather than resolve it to a number that means nothing.
386            let kind = match var.place {
387                Place::Thread { .. } => "@tls_object",
388                _ => "@object",
389            };
390            let _ = writeln!(out, "\t.type\t{}, {kind}", var.name);
391        }
392        let _ = writeln!(out, "{symbol}{}:", var.name);
393        true
394    }
395
396    /// What a thread-local variable on Mach-O is known by, which is not its image.
397    ///
398    /// The image above is only what each thread's copy starts out as. The name the program uses is
399    /// a descriptor of three words: the function that finds this thread's copy, a key it fills in,
400    /// and where the image is. Code reaches the variable by loading the descriptor's address and
401    /// calling the first word with it. `dyld` points the first word at its own function the first
402    /// time the image is loaded, and `__tlv_bootstrap` is only what it starts as. Nothing on any
403    /// other format or for any other variable.
404    pub fn descriptor(self, out: &mut String, var: &Variable) {
405        if self != Directives::MachO || !matches!(var.place, Place::Thread { .. }) {
406            return;
407        }
408        let symbol = self.symbol();
409        let name = &var.name;
410        out.push_str("\t.section\t__DATA,__thread_vars,thread_local_variables\n");
411        self.bind(out, name, var.binding);
412        self.seen(out, name, var.binding, var.visibility);
413        out.push_str("\t.p2align\t3\n");
414        let _ = writeln!(out, "{symbol}{name}:");
415        let _ = writeln!(out, "\t.quad\t{symbol}_tlv_bootstrap");
416        out.push_str("\t.quad\t0\n");
417        let _ = writeln!(out, "\t.quad\t{symbol}{name}$tlv$init");
418    }
419
420    /// The directive that makes a variable visible outside the file, if it is.
421    fn bind(self, out: &mut String, name: &str, binding: Binding) {
422        let symbol = self.symbol();
423        match binding {
424            Binding::Global => {
425                let _ = writeln!(out, "\t.globl\t{symbol}{name}");
426            }
427            // Apple's assembler reads `.weak` as nothing it knows. A weak definition there is an
428            // external name with a second directive saying another object may beat it.
429            Binding::Weak if self == Directives::MachO => {
430                let _ = writeln!(out, "\t.globl\t{symbol}{name}");
431                let _ = writeln!(out, "\t.weak_definition\t{symbol}{name}");
432            }
433            Binding::Weak => {
434                let _ = writeln!(out, "\t.weak\t{symbol}{name}");
435            }
436            // Nothing, which is what makes it invisible outside the file. A name no directive
437            // mentions is still in the symbol table as a local one, which is what `static` is.
438            Binding::Local => {}
439        }
440    }
441
442    /// What is said about a function after its last instruction.
443    ///
444    /// The size, on the format that has one. It is written as the distance from the label to here
445    /// rather than as a number, because the assembler is the one that knows how long an
446    /// instruction turned out to be and this file is what it is about to find out from.
447    pub fn close(self, out: &mut String, name: &str) {
448        if self == Directives::Elf {
449            let _ = writeln!(out, "\t.size\t{name}, .-{name}");
450        }
451    }
452
453    /// A second name for something the file already wrote down.
454    ///
455    /// The binding and then `.set`, which is all gcc writes and all an assembler needs: the type
456    /// and the size of the new symbol are taken from the old one, so writing them again would
457    /// only be a second chance to disagree. Nothing opens a section first, because the symbol is
458    /// an entry in a table rather than a byte of anything, and no `.size` closes it for the same
459    /// reason.
460    ///
461    /// A name with an `@` in it is a symbol version, which gas will not take in `.set` or
462    /// `.globl`. It is written back as the `.symver` it came from, which binds it the way the
463    /// name it stands for is bound.
464    pub fn alias(self, out: &mut String, alias: &Alias) {
465        let symbol = self.symbol();
466        if alias.name.contains('@') {
467            let _ = writeln!(out, "\t.symver\t{symbol}{},{symbol}{}", alias.target, alias.name);
468            return;
469        }
470        self.bind(out, &alias.name, alias.binding);
471        self.seen(out, &alias.name, alias.binding, alias.visibility);
472        let _ = writeln!(out, "\t.set\t{symbol}{},{symbol}{}", alias.name, alias.target);
473    }
474
475    /// A name this file uses and does not define, which the link may leave undefined.
476    ///
477    /// The same directive a weak definition gets and nothing else, because the difference between
478    /// the two is whether a label follows it: `.weak f` with a body under it is a definition
479    /// another object may beat, and `.weak f` with nothing under it is a reference that may come
480    /// to nothing and whose address is then zero. That is how gas reads it and it is what gcc
481    /// writes, which was measured rather than read off the manual.
482    ///
483    /// After everything else, which is also where gcc writes it. Nothing turns on the position,
484    /// since a directive about a name is not a byte of any section, but a listing somebody
485    /// compares against gcc's is easier to compare when the two put things in the same order.
486    ///
487    /// Apple's assembler has a directive of its own for the reference, `.weak_reference`.
488    pub fn absent(self, out: &mut String, name: &str) {
489        let weak = if self == Directives::MachO { ".weak_reference" } else { ".weak" };
490        let _ = writeln!(out, "\t{weak}\t{}{name}", self.symbol());
491    }
492
493    /// What is said once, after every function.
494    ///
495    /// `property` is what the file says it was built to have checked, which is written on the one
496    /// format that has somewhere to put it and is nothing on the other two.
497    pub fn end(self, out: &mut String, property: Property) {
498        match self {
499            Directives::Elf => {
500                if property.any() {
501                    self.property(out, property);
502                }
503                // Without this the stack is executable, which is not a default anybody chose.
504                out.push_str("\t.section\t.note.GNU-stack,\"\",@progbits\n");
505            }
506            // What lets the linker throw away a function nothing calls, which it cannot do
507            // without being told that the boundaries between them are real.
508            Directives::MachO => out.push_str("\t.subsections_via_symbols\n"),
509            Directives::Coff => {}
510        }
511    }
512
513    /// The note that says what the file was built to have checked.
514    ///
515    /// A note is how long its name is, how long its description is, which kind it is, the name and
516    /// then the description, and this kind's description is a list of properties. The one written
517    /// here is the feature word, whose bits are what `-fcf-protection=` asked for.
518    ///
519    /// The lengths count the padding that follows what they measure, which is why the description
520    /// is sixteen bytes for a property of twelve. Nothing between the name and the description,
521    /// because twelve bytes of header and four of name is already a multiple of eight, and the four
522    /// zero bytes at the end are what carries it to the next one. Written as numbers rather than as
523    /// distances between labels, which is what gcc writes, because the numbers are fixed by there
524    /// being exactly one property in it and a label in a listing is another name that can collide.
525    fn property(self, out: &mut String, property: Property) {
526        out.push_str("\t.section\t.note.gnu.property,\"a\",@note\n");
527        out.push_str("\t.p2align\t3\n");
528        let _ = writeln!(out, "\t.long\t4");
529        let _ = writeln!(out, "\t.long\t16");
530        let _ = writeln!(out, "\t.long\t5");
531        let _ = writeln!(out, "\t.asciz\t\"GNU\"");
532        let _ = writeln!(out, "\t.long\t{:#x}", Property::X86_FEATURES);
533        let _ = writeln!(out, "\t.long\t4");
534        let _ = writeln!(out, "\t.long\t{:#x}", property.features);
535        let _ = writeln!(out, "\t.long\t0");
536    }
537}
538
539/// What the object file is told about a function's name, from what the machine function carries.
540///
541/// Two names for one set of three, because the machine IR is not allowed to know what an object
542/// file is and the object writer is not allowed to know what a machine function is. This crate is
543/// where they meet, which is where the two spellings are put side by side.
544#[must_use]
545pub(crate) fn binding(binding: mir::Binding) -> Binding {
546    match binding {
547        mir::Binding::Global => Binding::Global,
548        mir::Binding::Local => Binding::Local,
549        mir::Binding::Weak => Binding::Weak,
550    }
551}
552
553/// What the object file is told about how far a name reaches outside a shared library, from what
554/// the machine function carries.
555///
556/// Two spellings of one set of three, for the reason [`binding`] above has two.
557#[must_use]
558pub(crate) fn visibility(visibility: mir::Visibility) -> Visibility {
559    match visibility {
560        mir::Visibility::Default => Visibility::Default,
561        mir::Visibility::Hidden => Visibility::Hidden,
562        mir::Visibility::Protected => Visibility::Protected,
563    }
564}
565
566#[cfg(test)]
567mod tests {
568    use rucc_object::FUNC_ALIGN;
569
570    use super::*;
571
572    #[test]
573    fn a_mach_o_symbol_is_the_c_name_with_an_underscore_in_front_of_it() {
574        let mut out = String::new();
575        Directives::MachO.open(
576            &mut out,
577            "main",
578            16,
579            Some(0x90),
580            Binding::Global,
581            Visibility::Default,
582            "",
583        );
584        assert!(out.contains("\t.globl\t_main\n"), "{out}");
585        assert!(out.contains("\n_main:\n"), "{out}");
586        // No type and no size, neither of which Mach-O has.
587        assert!(!out.contains(".type"), "{out}");
588        let mut close = String::new();
589        Directives::MachO.close(&mut close, "main");
590        assert_eq!(close, "");
591    }
592
593    /// What clang writes for the same declarations with `-target arm64-apple-macos`, and what
594    /// Apple's assembler takes: it has no `.weak`, and a byte count in `.comm` would be read as
595    /// a power of two and ask for a boundary of 2^8.
596    #[test]
597    fn a_mach_o_listing_says_weak_and_common_the_way_apple_does() {
598        let mut out = String::new();
599        Directives::MachO.open(&mut out, "f", 4, None, Binding::Weak, Visibility::Default, "");
600        assert!(out.contains("\t.globl\t_f\n\t.weak_definition\t_f\n"), "{out}");
601        let mut absent = String::new();
602        Directives::MachO.absent(&mut absent, "g");
603        assert_eq!(absent, "\t.weak_reference\t_g\n");
604        let var = Variable {
605            name: "shared".to_owned(),
606            size: 16,
607            align: 8,
608            place: Place::Merged,
609            binding: Binding::Global,
610            visibility: Visibility::Default,
611            pieces: Vec::new(),
612        };
613        let mut apple = String::new();
614        Directives::MachO.variable(&mut apple, &var, Sections::default());
615        assert_eq!(apple, "\t.comm\t_shared,16,3\n");
616        let mut elf = String::new();
617        Directives::Elf.variable(&mut elf, &var, Sections::default());
618        assert_eq!(elf, "\t.comm\tshared,16,8\n");
619    }
620
621    #[test]
622    fn an_elf_function_says_what_it_is_and_how_long_it_is() {
623        let mut out = String::new();
624        Directives::Elf.open(
625            &mut out,
626            "main",
627            16,
628            Some(0x90),
629            Binding::Global,
630            Visibility::Default,
631            "",
632        );
633        Directives::Elf.close(&mut out, "main");
634        assert!(out.contains("\t.type\tmain, @function\n"), "{out}");
635        assert!(out.contains("\t.size\tmain, .-main\n"), "{out}");
636    }
637
638    #[test]
639    fn a_function_that_asked_to_be_more_aligned_is_written_at_that_alignment() {
640        let mut out = String::new();
641        Directives::Elf.open(
642            &mut out,
643            "f",
644            256,
645            Some(0x90),
646            Binding::Global,
647            Visibility::Default,
648            "",
649        );
650        // The directive counts in powers of two and the attribute counts in bytes, and two
651        // hundred and fifty six bytes is eight of them.
652        assert!(out.contains("\t.p2align\t8, 0x90\n"), "{out}");
653        let mut plain = String::new();
654        Directives::Elf.open(
655            &mut plain,
656            "f",
657            FUNC_ALIGN,
658            Some(0x90),
659            Binding::Global,
660            Visibility::Default,
661            "",
662        );
663        assert!(plain.contains("\t.p2align\t4, 0x90\n"), "{plain}");
664    }
665
666    /// The two directives that say a name does not leave the shared library, or leaves it and
667    /// cannot be replaced.
668    ///
669    /// The listing half of tamnd/rucc#733. It matters that this is written in the listing and not
670    /// only in the object writer, because the two are the same compiler taking two roads out and a
671    /// program built through `-S` and an assembler has to come out the same as one built straight
672    /// to an object.
673    #[test]
674    fn a_name_that_does_not_leave_the_library_says_so_in_the_listing() {
675        let mut out = String::new();
676        Directives::Elf.open(
677            &mut out,
678            "f",
679            16,
680            Some(0x90),
681            Binding::Global,
682            Visibility::Hidden,
683            "",
684        );
685        assert!(out.contains("\t.globl\tf\n"), "still global to the static linker: {out}");
686        assert!(out.contains("\t.hidden\tf\n"), "{out}");
687        let mut protected = String::new();
688        Directives::Elf.open(
689            &mut protected,
690            "f",
691            16,
692            Some(0x90),
693            Binding::Global,
694            Visibility::Protected,
695            "",
696        );
697        assert!(protected.contains("\t.protected\tf\n"), "{protected}");
698        // Mach-O's one spelling of the one of these it has, and it carries the underscore every
699        // other Apple symbol does.
700        let mut apple = String::new();
701        Directives::MachO.open(
702            &mut apple,
703            "f",
704            16,
705            Some(0x90),
706            Binding::Global,
707            Visibility::Hidden,
708            "",
709        );
710        assert!(apple.contains("\t.private_extern\t_f\n"), "{apple}");
711    }
712
713    /// A `static` name gets no visibility directive whatever it asked for.
714    ///
715    /// gcc writes none for one either, and an assembler that is handed `.hidden` for a name that
716    /// was never `.globl` has been told something about a symbol that is not in anybody's dynamic
717    /// table to begin with.
718    #[test]
719    fn a_static_name_is_told_nothing_about_a_dynamic_linker_it_will_never_meet() {
720        for seen in [Visibility::Default, Visibility::Hidden, Visibility::Protected] {
721            let mut out = String::new();
722            Directives::Elf.open(&mut out, "f", 16, Some(0x90), Binding::Local, seen, "");
723            assert!(!out.contains(".hidden"), "{seen:?}: {out}");
724            assert!(!out.contains(".protected"), "{seen:?}: {out}");
725        }
726    }
727
728    /// The names are what gcc 16 writes for the same declarations, checked against it on a Linux
729    /// host, and the leading `.text.` is the part that has to be right rather than decoration:
730    /// `--gc-sections` and the linker scripts a kernel is linked with both match on it.
731    #[test]
732    fn a_function_given_a_section_of_its_own_opens_one_named_after_it() {
733        let split = Sections { functions: true, data: false };
734        let mut out = String::new();
735        Directives::Elf.code(&mut out, "f", split);
736        assert_eq!(out, "\t.section\t.text.f,\"ax\",@progbits\n");
737        // Windows says it as a COMDAT, which is one name for several sections and a symbol saying
738        // which of them is which. That is what clang writes for the same flag on a Windows target.
739        let mut windows = String::new();
740        Directives::Coff.code(&mut windows, "f", split);
741        assert_eq!(windows, "\t.section\t.text,\"xr\",one_only,f\n");
742        // Nothing on Mach-O, whose objects end with `.subsections_via_symbols` and so already let
743        // the linker drop a function nothing reaches.
744        let mut apple = String::new();
745        Directives::MachO.code(&mut apple, "f", split);
746        assert_eq!(apple, "");
747        // And nothing anywhere when nothing asked, which is the default and is what leaves every
748        // function in the one `.text` the file opens with.
749        for directives in [Directives::Elf, Directives::Coff, Directives::MachO] {
750            let mut plain = String::new();
751            directives.code(&mut plain, "f", Sections::default());
752            assert_eq!(plain, "", "{directives:?}");
753        }
754    }
755
756    /// Splitting must change which section header a symbol points at and nothing else, so each of
757    /// these carries the flags of the section it came out of. The spellings are gcc 16's, which is
758    /// shorter than what it writes for the unsplit sections: no `@progbits`, since that is what a
759    /// section is when nothing says otherwise.
760    #[test]
761    fn a_variable_given_a_section_of_its_own_keeps_the_flags_it_would_have_had() {
762        let split = Sections { functions: false, data: true };
763        let cases = [
764            (Place::Written, "\t.section\t.data.x,\"aw\"\n"),
765            (Place::Zero, "\t.section\t.bss.x,\"aw\",@nobits\n"),
766            (Place::ReadOnly, "\t.section\t.rodata.x,\"a\"\n"),
767            (Place::RelocReadOnly { local: false }, "\t.section\t.data.rel.ro.x,\"aw\"\n"),
768            (Place::RelocReadOnly { local: true }, "\t.section\t.data.rel.ro.local.x,\"aw\"\n"),
769        ];
770        for (place, want) in cases {
771            let mut out = String::new();
772            Directives::Elf.section(&mut out, &place, "x", split);
773            assert_eq!(out, want, "{place:?}");
774        }
775    }
776
777    /// The two kinds of variable the flag leaves alone, and the format that ignores it.
778    ///
779    /// A tentative definition is a request to the linker for that much zeroed space rather than an
780    /// image, so there is no section to split off, and a variable the program put a section name on
781    /// has the answer the source gave, which a flag must not overrule.
782    #[test]
783    fn a_variable_that_has_no_section_of_its_own_to_be_given_is_left_where_it_was() {
784        let split = Sections { functions: false, data: true };
785        let mut merged = String::new();
786        Directives::Elf.section(&mut merged, &Place::Merged, "x", split);
787        assert_eq!(merged, "\t.data\n");
788        let named = Place::Named(".init_array".to_owned());
789        let mut asked = String::new();
790        Directives::Elf.section(&mut asked, &named, "x", split);
791        assert_eq!(asked, "\t.section\t.init_array,\"aw\",@init_array\n");
792        let mut apple = String::new();
793        Directives::MachO.section(&mut apple, &Place::Written, "x", split);
794        assert_eq!(apple, "\t.section\t__DATA,__data\n");
795    }
796
797    /// The three names the startup code calls what it finds in, and one that merely begins like
798    /// one.
799    ///
800    /// A numbered priority is written as a suffix on the name and is the same kind of section, so
801    /// the type has to survive the number. `.init_arrays` is an ordinary section whose name happens
802    /// to start with one of theirs, and writing the type on it would tell the linker to gather it
803    /// with them.
804    #[test]
805    fn a_section_of_function_addresses_says_which_kind_it_is() {
806        let cases = [
807            (".init_array", "\t.section\t.init_array,\"aw\",@init_array\n"),
808            (".init_array.00101", "\t.section\t.init_array.00101,\"aw\",@init_array\n"),
809            (".fini_array", "\t.section\t.fini_array,\"aw\",@fini_array\n"),
810            (".preinit_array", "\t.section\t.preinit_array,\"aw\",@preinit_array\n"),
811            (".init_arrays", "\t.section\t.init_arrays,\"aw\",@progbits\n"),
812        ];
813        for (name, want) in cases {
814            let mut out = String::new();
815            let place = Place::Named(name.to_owned());
816            Directives::Elf.section(&mut out, &place, "x", Sections::default());
817            assert_eq!(out, want, "{name}");
818        }
819    }
820
821    #[test]
822    fn an_elf_file_says_the_stack_is_not_executable() {
823        // The absence of this is what makes it executable, so the test is that it is there
824        // rather than that it is spelled a particular way.
825        let mut out = String::new();
826        Directives::Elf.end(&mut out, Property::default());
827        assert!(out.contains(".note.GNU-stack"), "{out}");
828        assert!(!out.contains(".note.gnu.property"), "nothing was asked to be checked");
829    }
830
831    /// What the file says it was built to have checked, as the assembler reads it.
832    ///
833    /// The two lengths are the part worth a test. They count the padding after what they measure,
834    /// so a note that gets them right for its own contents and wrong for the alignment is one the
835    /// linker drops without a word, and what comes of that is a program the loader leaves the check
836    /// turned off for.
837    #[test]
838    fn an_elf_file_says_what_it_was_built_to_have_checked() {
839        let mut out = String::new();
840        Directives::Elf.end(&mut out, Property { features: Property::IBT });
841        let lines: Vec<&str> = out.lines().collect();
842        assert_eq!(
843            lines,
844            [
845                "\t.section\t.note.gnu.property,\"a\",@note",
846                "\t.p2align\t3",
847                "\t.long\t4",
848                "\t.long\t16",
849                "\t.long\t5",
850                "\t.asciz\t\"GNU\"",
851                "\t.long\t0xc0000002",
852                "\t.long\t4",
853                "\t.long\t0x1",
854                "\t.long\t0",
855                "\t.section\t.note.GNU-stack,\"\",@progbits",
856            ]
857        );
858    }
859
860    #[test]
861    fn every_object_format_has_directives() {
862        for format in [ObjectFormat::Elf, ObjectFormat::MachO, ObjectFormat::Coff] {
863            let directives = Directives::of(format);
864            assert!(directives.text().starts_with('\t'));
865            let mut out = String::new();
866            directives.open(
867                &mut out,
868                "f",
869                16,
870                Some(0x90),
871                Binding::Global,
872                Visibility::Default,
873                "",
874            );
875            directives.close(&mut out, "f");
876            directives.end(&mut out, Property::default());
877            assert!(out.ends_with('\n'), "{format:?} left a line unfinished");
878        }
879    }
880}