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 /// A name this file uses and does not define, which the link may leave undefined.
414 ///
415 /// The same directive a weak definition gets and nothing else, because the difference between
416 /// the two is whether a label follows it: `.weak f` with a body under it is a definition
417 /// another object may beat, and `.weak f` with nothing under it is a reference that may come
418 /// to nothing and whose address is then zero. That is how gas reads it and it is what gcc
419 /// writes, which was measured rather than read off the manual.
420 ///
421 /// After everything else, which is also where gcc writes it. Nothing turns on the position,
422 /// since a directive about a name is not a byte of any section, but a listing somebody
423 /// compares against gcc's is easier to compare when the two put things in the same order.
424 pub fn absent(self, out: &mut String, name: &str) {
425 let _ = writeln!(out, "\t.weak\t{}{name}", self.symbol());
426 }
427
428 /// What is said once, after every function.
429 ///
430 /// `property` is what the file says it was built to have checked, which is written on the one
431 /// format that has somewhere to put it and is nothing on the other two.
432 pub fn end(self, out: &mut String, property: Property) {
433 match self {
434 Directives::Elf => {
435 if property.any() {
436 self.property(out, property);
437 }
438 // Without this the stack is executable, which is not a default anybody chose.
439 out.push_str("\t.section\t.note.GNU-stack,\"\",@progbits\n");
440 }
441 // What lets the linker throw away a function nothing calls, which it cannot do
442 // without being told that the boundaries between them are real.
443 Directives::MachO => out.push_str("\t.subsections_via_symbols\n"),
444 Directives::Coff => {}
445 }
446 }
447
448 /// The note that says what the file was built to have checked.
449 ///
450 /// A note is how long its name is, how long its description is, which kind it is, the name and
451 /// then the description, and this kind's description is a list of properties. The one written
452 /// here is the feature word, whose bits are what `-fcf-protection=` asked for.
453 ///
454 /// The lengths count the padding that follows what they measure, which is why the description
455 /// is sixteen bytes for a property of twelve. Nothing between the name and the description,
456 /// because twelve bytes of header and four of name is already a multiple of eight, and the four
457 /// zero bytes at the end are what carries it to the next one. Written as numbers rather than as
458 /// distances between labels, which is what gcc writes, because the numbers are fixed by there
459 /// being exactly one property in it and a label in a listing is another name that can collide.
460 fn property(self, out: &mut String, property: Property) {
461 out.push_str("\t.section\t.note.gnu.property,\"a\",@note\n");
462 out.push_str("\t.p2align\t3\n");
463 let _ = writeln!(out, "\t.long\t4");
464 let _ = writeln!(out, "\t.long\t16");
465 let _ = writeln!(out, "\t.long\t5");
466 let _ = writeln!(out, "\t.asciz\t\"GNU\"");
467 let _ = writeln!(out, "\t.long\t{:#x}", Property::X86_FEATURES);
468 let _ = writeln!(out, "\t.long\t4");
469 let _ = writeln!(out, "\t.long\t{:#x}", property.features);
470 let _ = writeln!(out, "\t.long\t0");
471 }
472}
473
474/// What the object file is told about a function's name, from what the machine function carries.
475///
476/// Two names for one set of three, because the machine IR is not allowed to know what an object
477/// file is and the object writer is not allowed to know what a machine function is. This crate is
478/// where they meet, which is where the two spellings are put side by side.
479#[must_use]
480pub(crate) fn binding(binding: mir::Binding) -> Binding {
481 match binding {
482 mir::Binding::Global => Binding::Global,
483 mir::Binding::Local => Binding::Local,
484 mir::Binding::Weak => Binding::Weak,
485 }
486}
487
488/// What the object file is told about how far a name reaches outside a shared library, from what
489/// the machine function carries.
490///
491/// Two spellings of one set of three, for the reason [`binding`] above has two.
492#[must_use]
493pub(crate) fn visibility(visibility: mir::Visibility) -> Visibility {
494 match visibility {
495 mir::Visibility::Default => Visibility::Default,
496 mir::Visibility::Hidden => Visibility::Hidden,
497 mir::Visibility::Protected => Visibility::Protected,
498 }
499}
500
501#[cfg(test)]
502mod tests {
503 use rucc_object::FUNC_ALIGN;
504
505 use super::*;
506
507 #[test]
508 fn a_mach_o_symbol_is_the_c_name_with_an_underscore_in_front_of_it() {
509 let mut out = String::new();
510 Directives::MachO.open(&mut out, "main", 16, Binding::Global, Visibility::Default, "");
511 assert!(out.contains("\t.globl\t_main\n"), "{out}");
512 assert!(out.contains("\n_main:\n"), "{out}");
513 // No type and no size, neither of which Mach-O has.
514 assert!(!out.contains(".type"), "{out}");
515 let mut close = String::new();
516 Directives::MachO.close(&mut close, "main");
517 assert_eq!(close, "");
518 }
519
520 #[test]
521 fn an_elf_function_says_what_it_is_and_how_long_it_is() {
522 let mut out = String::new();
523 Directives::Elf.open(&mut out, "main", 16, Binding::Global, Visibility::Default, "");
524 Directives::Elf.close(&mut out, "main");
525 assert!(out.contains("\t.type\tmain, @function\n"), "{out}");
526 assert!(out.contains("\t.size\tmain, .-main\n"), "{out}");
527 }
528
529 #[test]
530 fn a_function_that_asked_to_be_more_aligned_is_written_at_that_alignment() {
531 let mut out = String::new();
532 Directives::Elf.open(&mut out, "f", 256, Binding::Global, Visibility::Default, "");
533 // The directive counts in powers of two and the attribute counts in bytes, and two
534 // hundred and fifty six bytes is eight of them.
535 assert!(out.contains("\t.p2align\t8, 0x90\n"), "{out}");
536 let mut plain = String::new();
537 Directives::Elf.open(&mut plain, "f", FUNC_ALIGN, Binding::Global, Visibility::Default, "");
538 assert!(plain.contains("\t.p2align\t4, 0x90\n"), "{plain}");
539 }
540
541 /// The two directives that say a name does not leave the shared library, or leaves it and
542 /// cannot be replaced.
543 ///
544 /// The listing half of tamnd/rucc#733. It matters that this is written in the listing and not
545 /// only in the object writer, because the two are the same compiler taking two roads out and a
546 /// program built through `-S` and an assembler has to come out the same as one built straight
547 /// to an object.
548 #[test]
549 fn a_name_that_does_not_leave_the_library_says_so_in_the_listing() {
550 let mut out = String::new();
551 Directives::Elf.open(&mut out, "f", 16, Binding::Global, Visibility::Hidden, "");
552 assert!(out.contains("\t.globl\tf\n"), "still global to the static linker: {out}");
553 assert!(out.contains("\t.hidden\tf\n"), "{out}");
554 let mut protected = String::new();
555 Directives::Elf.open(&mut protected, "f", 16, Binding::Global, Visibility::Protected, "");
556 assert!(protected.contains("\t.protected\tf\n"), "{protected}");
557 // Mach-O's one spelling of the one of these it has, and it carries the underscore every
558 // other Apple symbol does.
559 let mut apple = String::new();
560 Directives::MachO.open(&mut apple, "f", 16, Binding::Global, Visibility::Hidden, "");
561 assert!(apple.contains("\t.private_extern\t_f\n"), "{apple}");
562 }
563
564 /// A `static` name gets no visibility directive whatever it asked for.
565 ///
566 /// gcc writes none for one either, and an assembler that is handed `.hidden` for a name that
567 /// was never `.globl` has been told something about a symbol that is not in anybody's dynamic
568 /// table to begin with.
569 #[test]
570 fn a_static_name_is_told_nothing_about_a_dynamic_linker_it_will_never_meet() {
571 for seen in [Visibility::Default, Visibility::Hidden, Visibility::Protected] {
572 let mut out = String::new();
573 Directives::Elf.open(&mut out, "f", 16, Binding::Local, seen, "");
574 assert!(!out.contains(".hidden"), "{seen:?}: {out}");
575 assert!(!out.contains(".protected"), "{seen:?}: {out}");
576 }
577 }
578
579 /// The names are what gcc 16 writes for the same declarations, checked against it on a Linux
580 /// host, and the leading `.text.` is the part that has to be right rather than decoration:
581 /// `--gc-sections` and the linker scripts a kernel is linked with both match on it.
582 #[test]
583 fn a_function_given_a_section_of_its_own_opens_one_named_after_it() {
584 let split = Sections { functions: true, data: false };
585 let mut out = String::new();
586 Directives::Elf.code(&mut out, "f", split);
587 assert_eq!(out, "\t.section\t.text.f,\"ax\",@progbits\n");
588 // Windows says it as a COMDAT, which is one name for several sections and a symbol saying
589 // which of them is which. That is what clang writes for the same flag on a Windows target.
590 let mut windows = String::new();
591 Directives::Coff.code(&mut windows, "f", split);
592 assert_eq!(windows, "\t.section\t.text,\"xr\",one_only,f\n");
593 // Nothing on Mach-O, whose objects end with `.subsections_via_symbols` and so already let
594 // the linker drop a function nothing reaches.
595 let mut apple = String::new();
596 Directives::MachO.code(&mut apple, "f", split);
597 assert_eq!(apple, "");
598 // And nothing anywhere when nothing asked, which is the default and is what leaves every
599 // function in the one `.text` the file opens with.
600 for directives in [Directives::Elf, Directives::Coff, Directives::MachO] {
601 let mut plain = String::new();
602 directives.code(&mut plain, "f", Sections::default());
603 assert_eq!(plain, "", "{directives:?}");
604 }
605 }
606
607 /// Splitting must change which section header a symbol points at and nothing else, so each of
608 /// these carries the flags of the section it came out of. The spellings are gcc 16's, which is
609 /// shorter than what it writes for the unsplit sections: no `@progbits`, since that is what a
610 /// section is when nothing says otherwise.
611 #[test]
612 fn a_variable_given_a_section_of_its_own_keeps_the_flags_it_would_have_had() {
613 let split = Sections { functions: false, data: true };
614 let cases = [
615 (Place::Written, "\t.section\t.data.x,\"aw\"\n"),
616 (Place::Zero, "\t.section\t.bss.x,\"aw\",@nobits\n"),
617 (Place::ReadOnly, "\t.section\t.rodata.x,\"a\"\n"),
618 (Place::RelocReadOnly { local: false }, "\t.section\t.data.rel.ro.x,\"aw\"\n"),
619 (Place::RelocReadOnly { local: true }, "\t.section\t.data.rel.ro.local.x,\"aw\"\n"),
620 ];
621 for (place, want) in cases {
622 let mut out = String::new();
623 Directives::Elf.section(&mut out, &place, "x", split);
624 assert_eq!(out, want, "{place:?}");
625 }
626 }
627
628 /// The two kinds of variable the flag leaves alone, and the format that ignores it.
629 ///
630 /// A tentative definition is a request to the linker for that much zeroed space rather than an
631 /// image, so there is no section to split off, and a variable the program put a section name on
632 /// has the answer the source gave, which a flag must not overrule.
633 #[test]
634 fn a_variable_that_has_no_section_of_its_own_to_be_given_is_left_where_it_was() {
635 let split = Sections { functions: false, data: true };
636 let mut merged = String::new();
637 Directives::Elf.section(&mut merged, &Place::Merged, "x", split);
638 assert_eq!(merged, "\t.data\n");
639 let named = Place::Named(".init_array".to_owned());
640 let mut asked = String::new();
641 Directives::Elf.section(&mut asked, &named, "x", split);
642 assert_eq!(asked, "\t.section\t.init_array,\"aw\",@init_array\n");
643 let mut apple = String::new();
644 Directives::MachO.section(&mut apple, &Place::Written, "x", split);
645 assert_eq!(apple, "\t.section\t__DATA,__data\n");
646 }
647
648 /// The three names the startup code calls what it finds in, and one that merely begins like
649 /// one.
650 ///
651 /// A numbered priority is written as a suffix on the name and is the same kind of section, so
652 /// the type has to survive the number. `.init_arrays` is an ordinary section whose name happens
653 /// to start with one of theirs, and writing the type on it would tell the linker to gather it
654 /// with them.
655 #[test]
656 fn a_section_of_function_addresses_says_which_kind_it_is() {
657 let cases = [
658 (".init_array", "\t.section\t.init_array,\"aw\",@init_array\n"),
659 (".init_array.00101", "\t.section\t.init_array.00101,\"aw\",@init_array\n"),
660 (".fini_array", "\t.section\t.fini_array,\"aw\",@fini_array\n"),
661 (".preinit_array", "\t.section\t.preinit_array,\"aw\",@preinit_array\n"),
662 (".init_arrays", "\t.section\t.init_arrays,\"aw\",@progbits\n"),
663 ];
664 for (name, want) in cases {
665 let mut out = String::new();
666 let place = Place::Named(name.to_owned());
667 Directives::Elf.section(&mut out, &place, "x", Sections::default());
668 assert_eq!(out, want, "{name}");
669 }
670 }
671
672 #[test]
673 fn an_elf_file_says_the_stack_is_not_executable() {
674 // The absence of this is what makes it executable, so the test is that it is there
675 // rather than that it is spelled a particular way.
676 let mut out = String::new();
677 Directives::Elf.end(&mut out, Property::default());
678 assert!(out.contains(".note.GNU-stack"), "{out}");
679 assert!(!out.contains(".note.gnu.property"), "nothing was asked to be checked");
680 }
681
682 /// What the file says it was built to have checked, as the assembler reads it.
683 ///
684 /// The two lengths are the part worth a test. They count the padding after what they measure,
685 /// so a note that gets them right for its own contents and wrong for the alignment is one the
686 /// linker drops without a word, and what comes of that is a program the loader leaves the check
687 /// turned off for.
688 #[test]
689 fn an_elf_file_says_what_it_was_built_to_have_checked() {
690 let mut out = String::new();
691 Directives::Elf.end(&mut out, Property { features: Property::IBT });
692 let lines: Vec<&str> = out.lines().collect();
693 assert_eq!(
694 lines,
695 [
696 "\t.section\t.note.gnu.property,\"a\",@note",
697 "\t.p2align\t3",
698 "\t.long\t4",
699 "\t.long\t16",
700 "\t.long\t5",
701 "\t.asciz\t\"GNU\"",
702 "\t.long\t0xc0000002",
703 "\t.long\t4",
704 "\t.long\t0x1",
705 "\t.long\t0",
706 "\t.section\t.note.GNU-stack,\"\",@progbits",
707 ]
708 );
709 }
710
711 #[test]
712 fn every_object_format_has_directives() {
713 for format in [ObjectFormat::Elf, ObjectFormat::MachO, ObjectFormat::Coff] {
714 let directives = Directives::of(format);
715 assert!(directives.text().starts_with('\t'));
716 let mut out = String::new();
717 directives.open(&mut out, "f", 16, Binding::Global, Visibility::Default, "");
718 directives.close(&mut out, "f");
719 directives.end(&mut out, Property::default());
720 assert!(out.ends_with('\n'), "{format:?} left a line unfinished");
721 }
722 }
723}