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_object::{Binding, Place};
19use rucc_target::ObjectFormat;
20
21use crate::data::Variable;
22
23/// The directives one object format wraps a function in.
24#[derive(Debug, Clone, Copy, PartialEq, Eq)]
25pub enum Directives {
26 /// ELF, which is Linux and the freestanding targets.
27 Elf,
28 /// Mach-O, which is Apple's.
29 MachO,
30 /// COFF, which is Windows.
31 Coff,
32}
33
34impl Directives {
35 /// The directives that go with that object format.
36 #[must_use]
37 pub const fn of(format: ObjectFormat) -> Directives {
38 match format {
39 ObjectFormat::Elf => Directives::Elf,
40 ObjectFormat::MachO => Directives::MachO,
41 ObjectFormat::Coff => Directives::Coff,
42 }
43 }
44
45 /// What goes in front of a C name to make the name the linker sees.
46 ///
47 /// Mach-O keeps the underscore that every Unix linker once had, so `main` in C is `_main` in
48 /// the object, and a listing that leaves it off refers to a symbol nothing defines.
49 #[must_use]
50 pub const fn symbol(self) -> &'static str {
51 match self {
52 Directives::Elf | Directives::Coff => "",
53 Directives::MachO => "_",
54 }
55 }
56
57 /// What goes in front of a label that belongs to one function and leaves no symbol behind.
58 #[must_use]
59 pub const fn local(self) -> &'static str {
60 match self {
61 Directives::Elf | Directives::Coff => ".L",
62 Directives::MachO => "L",
63 }
64 }
65
66 /// The directive that opens the section code goes in.
67 #[must_use]
68 pub const fn text(self) -> &'static str {
69 match self {
70 Directives::Elf | Directives::Coff => "\t.text",
71 Directives::MachO => "\t.section\t__TEXT,__text,regular,pure_instructions",
72 }
73 }
74
75 /// What is said about a function before its first instruction.
76 ///
77 /// Every function is global, because a machine function does not carry the linkage the C did
78 /// and nothing below the driver could ask. That is wrong for a `static` function and is the
79 /// reason `-S` output is a thing to read rather than a thing to link, until the object writer
80 /// gives the machine IR somewhere to keep it.
81 ///
82 /// `align` is in bytes and is a power of two, and the padding is `0x90` because the space in
83 /// front of a function is reached by falling off the end of the one before it.
84 pub fn open(self, out: &mut String, name: &str, align: u32) {
85 let symbol = self.symbol();
86 let _ = writeln!(out, "\t.p2align\t{}, 0x90", align.max(1).trailing_zeros());
87 let _ = writeln!(out, "\t.globl\t{symbol}{name}");
88 match self {
89 Directives::Elf => {
90 let _ = writeln!(out, "\t.type\t{name}, @function");
91 }
92 // Windows says the same thing as a storage class and a type code: two is external and
93 // thirty two is a function, and the two numbers together are what ELF's one word says.
94 Directives::Coff => {
95 let _ = writeln!(out, "\t.def\t{name}\n\t.scl\t2\n\t.type\t32\n\t.endef");
96 }
97 Directives::MachO => {}
98 }
99 let _ = writeln!(out, "{symbol}{name}:");
100 }
101
102 /// The directive that opens the section a variable goes in.
103 ///
104 /// The three formats disagree about the names and about how much has to be said. ELF and COFF
105 /// have a directive per section that every assembler knows, and both want the flags spelled
106 /// out for a section the program named, since nothing else says whether it may be written to.
107 /// Mach-O has one directive and a segment in front of every section name.
108 pub fn section(self, out: &mut String, place: &Place) {
109 match (self, place) {
110 // A tentative definition is not in a section at all, and the caller is what decides
111 // that. It is answered here as the section it would otherwise have gone in, so that
112 // the match stays about sections and nothing has to be said twice.
113 (Directives::Elf | Directives::Coff, Place::Written | Place::Merged) => {
114 out.push_str("\t.data\n");
115 }
116 (Directives::Elf | Directives::Coff, Place::Zero) => out.push_str("\t.bss\n"),
117 (Directives::Elf, Place::ReadOnly) => out.push_str("\t.section\t.rodata\n"),
118 (Directives::Coff, Place::ReadOnly) => out.push_str("\t.section\t.rdata,\"dr\"\n"),
119 (Directives::Elf, Place::Named(name)) => {
120 let _ = writeln!(out, "\t.section\t{name},\"aw\",@progbits");
121 }
122 (Directives::Coff, Place::Named(name)) => {
123 let _ = writeln!(out, "\t.section\t{name},\"dw\"");
124 }
125 (Directives::MachO, Place::ReadOnly) => out.push_str("\t.section\t__TEXT,__const\n"),
126 // A Mach-O section name carries the segment it is in, so a program that named one
127 // named both halves and there is nothing to add to it.
128 (Directives::MachO, Place::Named(name)) => {
129 let _ = writeln!(out, "\t.section\t{name}");
130 }
131 (Directives::MachO, _) => out.push_str("\t.section\t__DATA,__data\n"),
132 }
133 }
134
135 /// What is said about a variable before its image, and whether an image follows.
136 ///
137 /// Two kinds of variable are one directive rather than a section, a label and bytes. A
138 /// tentative definition is a request to the linker for that much zeroed space on every format,
139 /// and on Mach-O so is a variable whose image is all zeros, because the section that would
140 /// hold it is one nothing may write bytes into.
141 pub fn variable(self, out: &mut String, var: &Variable) -> bool {
142 let symbol = self.symbol();
143 let align = var.align.max(1).trailing_zeros();
144 match (self, &var.place) {
145 (_, Place::Merged) => {
146 let comm = if var.binding == Binding::Local { ".lcomm" } else { ".comm" };
147 let name = &var.name;
148 let _ = writeln!(out, "\t{comm}\t{symbol}{name},{},{}", var.size, var.align);
149 return false;
150 }
151 (Directives::MachO, Place::Zero) => {
152 let name = &var.name;
153 let _ =
154 writeln!(out, "\t.zerofill\t__DATA,__bss,{symbol}{name},{},{align}", var.size);
155 return false;
156 }
157 _ => {}
158 }
159 self.section(out, &var.place);
160 match var.binding {
161 Binding::Global => {
162 let _ = writeln!(out, "\t.globl\t{symbol}{}", var.name);
163 }
164 Binding::Weak => {
165 let _ = writeln!(out, "\t.weak\t{symbol}{}", var.name);
166 }
167 // Nothing, which is what makes it invisible outside the file. A name no directive
168 // mentions is still in the symbol table as a local one, which is what `static` is.
169 Binding::Local => {}
170 }
171 let _ = writeln!(out, "\t.p2align\t{align}");
172 if self == Directives::Elf {
173 let _ = writeln!(out, "\t.type\t{}, @object", var.name);
174 }
175 let _ = writeln!(out, "{symbol}{}:", var.name);
176 true
177 }
178
179 /// What is said about a function after its last instruction.
180 ///
181 /// The size, on the format that has one. It is written as the distance from the label to here
182 /// rather than as a number, because the assembler is the one that knows how long an
183 /// instruction turned out to be and this file is what it is about to find out from.
184 pub fn close(self, out: &mut String, name: &str) {
185 if self == Directives::Elf {
186 let _ = writeln!(out, "\t.size\t{name}, .-{name}");
187 }
188 }
189
190 /// What is said once, after every function.
191 pub fn end(self, out: &mut String) {
192 match self {
193 // Without this the stack is executable, which is not a default anybody chose.
194 Directives::Elf => out.push_str("\t.section\t.note.GNU-stack,\"\",@progbits\n"),
195 // What lets the linker throw away a function nothing calls, which it cannot do
196 // without being told that the boundaries between them are real.
197 Directives::MachO => out.push_str("\t.subsections_via_symbols\n"),
198 Directives::Coff => {}
199 }
200 }
201}
202
203#[cfg(test)]
204mod tests {
205 use rucc_object::FUNC_ALIGN;
206
207 use super::*;
208
209 #[test]
210 fn a_mach_o_symbol_is_the_c_name_with_an_underscore_in_front_of_it() {
211 let mut out = String::new();
212 Directives::MachO.open(&mut out, "main", 16);
213 assert!(out.contains("\t.globl\t_main\n"), "{out}");
214 assert!(out.contains("\n_main:\n"), "{out}");
215 // No type and no size, neither of which Mach-O has.
216 assert!(!out.contains(".type"), "{out}");
217 let mut close = String::new();
218 Directives::MachO.close(&mut close, "main");
219 assert_eq!(close, "");
220 }
221
222 #[test]
223 fn an_elf_function_says_what_it_is_and_how_long_it_is() {
224 let mut out = String::new();
225 Directives::Elf.open(&mut out, "main", 16);
226 Directives::Elf.close(&mut out, "main");
227 assert!(out.contains("\t.type\tmain, @function\n"), "{out}");
228 assert!(out.contains("\t.size\tmain, .-main\n"), "{out}");
229 }
230
231 #[test]
232 fn a_function_that_asked_to_be_more_aligned_is_written_at_that_alignment() {
233 let mut out = String::new();
234 Directives::Elf.open(&mut out, "f", 256);
235 // The directive counts in powers of two and the attribute counts in bytes, and two
236 // hundred and fifty six bytes is eight of them.
237 assert!(out.contains("\t.p2align\t8, 0x90\n"), "{out}");
238 let mut plain = String::new();
239 Directives::Elf.open(&mut plain, "f", FUNC_ALIGN);
240 assert!(plain.contains("\t.p2align\t4, 0x90\n"), "{plain}");
241 }
242
243 #[test]
244 fn an_elf_file_says_the_stack_is_not_executable() {
245 // The absence of this is what makes it executable, so the test is that it is there
246 // rather than that it is spelled a particular way.
247 let mut out = String::new();
248 Directives::Elf.end(&mut out);
249 assert!(out.contains(".note.GNU-stack"), "{out}");
250 }
251
252 #[test]
253 fn every_object_format_has_directives() {
254 for format in [ObjectFormat::Elf, ObjectFormat::MachO, ObjectFormat::Coff] {
255 let directives = Directives::of(format);
256 assert!(directives.text().starts_with('\t'));
257 let mut out = String::new();
258 directives.open(&mut out, "f", 16);
259 directives.close(&mut out, "f");
260 directives.end(&mut out);
261 assert!(out.ends_with('\n'), "{format:?} left a line unfinished");
262 }
263 }
264}