rucc_codegen/elsewhere.rs
1//! Which names this file may not work the address of out for itself.
2//!
3//! Design: `spec/11-asm-objects-debug.md` section 11.3.
4//!
5//! Everything this compiler emits is position independent, so the address of a name is the distance
6//! from the instruction asking to the name, and that distance is a number the assembler leaves a
7//! hole for and the linker fills in. The linker can only fill it in when it is putting both ends in
8//! the same program. A name this file only declares may turn out to be in a shared library, and
9//! then there is no such distance and the link fails rather than guessing one.
10//!
11//! The way round it is a table: the linker gives the name one slot in the global offset table, fills
12//! the slot with whatever address the name ends up at, and the code loads the address out of the
13//! slot instead of working it out. The slot is in this program, so the distance to the slot is a
14//! number the linker has. It costs a load, and the linker takes the load back out again when the
15//! name turns out to have been in this program all along.
16//!
17//! Which names need it is a fact about the whole module and the code generator sees one function at
18//! a time, which is why this is worked out first and handed in rather than asked at the point of
19//! use.
20//!
21//! It is also a fact about which link is coming, which is [`rucc_ir::Pic`] and is why this is built
22//! from more than the module. Under `-fPIC` the link may be one that produces a shared library, and
23//! then a name this file exports is one the dynamic linker may find a different definition of, so
24//! reaching it from the instruction pointer would reach the wrong one. The static linker will not
25//! let that happen quietly: `R_X86_64_PC32` against a name it can see is replaceable is refused
26//! when it is making a shared object, which is how tamnd/rucc#756 was found.
27//!
28//! A thread-local variable is the other name this file cannot work the address of out for itself,
29//! and it is here for the same reason: which names are thread-local is a fact about the module and
30//! the code generator sees one function at a time. It is a harder case than the one above rather
31//! than a variation of it, because there is no address to work out at all. Every thread has its own
32//! copy, so what the link can say is only where the variable sits inside the block a thread gets,
33//! and turning that into an address is something the running program does. See [`Elsewhere::thread`].
34
35use std::collections::HashSet;
36
37use rucc_base::Symbol;
38use rucc_ir::{Linkage, Module, Pic, Visibility};
39use rucc_target::ObjectFormat;
40
41/// The names whose address only the linker knows.
42///
43/// Two ways in, and the first one holds whichever link is coming. A function this file only
44/// declares is one, because a function cannot be copied: it has exactly one address that every
45/// object in the program has to agree on, or two pointers to it compare unequal, so the one address
46/// is what the table holds and what everything reads. A variable can be copied, and in an
47/// executable it is, since the linker answers a reference to one another object defines by making
48/// room for it here and copying it there, so the name really does end up somewhere this file can
49/// measure to.
50///
51/// The second way in is `-fPIC`, where the link may be one that produces a shared library and the
52/// copying does not happen. There every replaceable name is in here, defined or not and function or
53/// variable, because the definition the process ends up using may be in another object however
54/// plainly this file defines it. What is not in here is what `-fPIC` costs nothing for: a `static`,
55/// and a name marked hidden or protected, which is the reason `-fPIC -fvisibility=hidden` is the
56/// combination a library that cares about its own speed is built with.
57///
58/// Both ways in are shut on a format with no such table, which is COFF. See `Self::table` for why
59/// the question has a different answer there rather than no answer.
60///
61/// A name this module has never heard of is not in here. Nothing the front end writes produces one,
62/// and treating an unknown name as a function would put the addresses the instrumentation takes of
63/// its own tables through a table of their own for no reason.
64///
65/// A thread-local variable is kept separately and answered by [`Self::thread`], because the two
66/// questions have different answers rather than one being a case of the other: the table slot of an
67/// ordinary name holds its address and the slot of a thread-local holds an offset, and reading
68/// either as though it were the other is a wrong answer rather than a slower one.
69#[derive(Debug, Clone, Default, PartialEq, Eq)]
70pub struct Elsewhere {
71 names: HashSet<Symbol>,
72 threads: HashSet<Symbol>,
73 described: bool,
74}
75
76impl Elsewhere {
77 /// The names that link cannot reach from the instruction pointer.
78 ///
79 /// `copies` is whether the linker answers a reference from the instruction pointer to a
80 /// variable another object defines by copying the variable into the executable. x86-64 does,
81 /// even in a position independent executable. AArch64 and RISC-V do not: GNU ld refuses an
82 /// `adrp` against such a variable when it makes a PIE, which is the default link on every
83 /// distribution, and gcc reads the address out of the table there instead.
84 #[must_use]
85 pub fn of(module: &Module, pic: Pic, format: ObjectFormat, copies: bool) -> Self {
86 let threads = module
87 .globals()
88 .filter(|&id| module[id].tls.is_some())
89 .map(|id| module[id].name)
90 .collect();
91 let described = format == ObjectFormat::MachO;
92 Self { threads, described, ..Self::table(module, pic, format, copies) }
93 }
94
95 /// The half of the above that is about the global offset table, which is the older one.
96 ///
97 /// Empty on a format that has no such table. COFF is the one, and it is not that the question
98 /// goes unanswered there: a name this file only declares is reached from the instruction
99 /// pointer like any other, because whatever supplies it supplies a piece of this image to
100 /// measure to. A name the link resolves out of another object is in the image, and a name that
101 /// comes from a DLL arrives through an import library, which is an archive member holding a
102 /// jump under the plain name, so the name still stands for an address in this image and every
103 /// object that takes it gets the one the linker kept. Measured against gcc 13.2 for
104 /// `x86_64-w64-mingw32`, which writes `leaq other(%rip), %rax` for the address of a function it
105 /// has only seen declared. Asking for a table there instead reached the object writer as a
106 /// relocation it has no way to write, which is what tamnd/rucc#1443 was.
107 fn table(module: &Module, pic: Pic, format: ObjectFormat, copies: bool) -> Self {
108 if format == ObjectFormat::Coff {
109 return Self::default();
110 }
111 let funcs = module.funcs().filter(|&id| {
112 let func = &module[id];
113 func.is_declaration() || pic.replaceable(func.linkage, func.visibility)
114 });
115 // A weak variable nothing here defines is the one variable the copying above does not
116 // cover, since there may be no definition anywhere to copy and then its address is null. The
117 // distance from here to null is not a number the linker has, so lld refuses the
118 // `R_X86_64_PC32` and gcc reads the address out of a slot, which the linker fills with zero.
119 //
120 // Mach-O does no copying at all. `dyld` has no copy relocation, so a variable a library
121 // defines stays in the library and the only way to it is the slot. That is every variable
122 // this file only declares, unless it is hidden and so promised to be in the same image,
123 // and it is what clang writes: `_ext@GOTPAGE` on arm64 and `_ext@GOTPCREL` on x86-64.
124 let uncopied = format == ObjectFormat::MachO || !copies;
125 let globals = module
126 .globals()
127 .filter(|&id| {
128 let global = &module[id];
129 (global.is_declaration()
130 && (global.linkage == Linkage::Weak
131 || (uncopied && global.visibility == Visibility::Default)))
132 || pic.replaceable(global.linkage, global.visibility)
133 })
134 .map(|id| module[id].name);
135 // An alias is a symbol of its own with a linkage and a visibility of its own, so it answers
136 // this for itself the same way it answered the visibility question in #752. What it points
137 // at is a separate name and is decided separately, which is what `weak, alias,
138 // visibility("hidden")` over an exported definition needs.
139 let aliases = module
140 .aliases()
141 .filter(|&id| pic.replaceable(module[id].linkage, module[id].visibility))
142 .map(|id| module[id].name);
143 funcs.map(|id| module[id].name).chain(globals).chain(aliases).collect()
144 }
145
146 /// Whether the address of that name has to be read out of the global offset table.
147 #[must_use]
148 pub fn holds(&self, name: Symbol) -> bool {
149 self.names.contains(&name)
150 }
151
152 /// Whether that name is a variable every thread has its own copy of.
153 ///
154 /// Asked before [`Self::holds`] and not instead of it, because the two answers are about
155 /// different things: a thread-local variable that another object may define is still reached
156 /// the same way, since the table slot holds an offset that is the same for every copy and the
157 /// question of whose copy is answered by the segment register rather than by the link.
158 #[must_use]
159 pub fn thread(&self, name: Symbol) -> bool {
160 self.threads.contains(&name)
161 }
162
163 /// Whether a thread-local variable is reached by calling through its descriptor, which is how
164 /// Mach-O does it on both architectures.
165 ///
166 /// The slot the table holds for such a variable is the address of the descriptor rather than an
167 /// offset from the thread pointer, and the first word of the descriptor is a function that takes
168 /// that address and gives back this thread's copy. So there is no thread pointer to add to,
169 /// and the answer is the value the call returns.
170 #[must_use]
171 pub const fn described(&self) -> bool {
172 self.described
173 }
174}
175
176/// The same set, written out by hand.
177///
178/// [`Elsewhere::of`] is how the driver builds one and is the only way a compilation does. This is
179/// for a test that wants to lower one function and say what is outside the file without building a
180/// module for it to be outside of.
181impl FromIterator<Symbol> for Elsewhere {
182 fn from_iter<T: IntoIterator<Item = Symbol>>(names: T) -> Self {
183 Self { names: names.into_iter().collect(), threads: HashSet::new(), described: false }
184 }
185}
186
187impl Elsewhere {
188 /// The same set with those names said to be thread-local, for a test that lowers one function.
189 #[must_use]
190 pub fn with_threads<T: IntoIterator<Item = Symbol>>(mut self, threads: T) -> Self {
191 self.threads = threads.into_iter().collect();
192 self
193 }
194
195 /// The same set with thread-locals reached through a descriptor, for a test that lowers one
196 /// function the way Mach-O would.
197 #[must_use]
198 pub const fn with_descriptors(mut self) -> Self {
199 self.described = true;
200 self
201 }
202}
203
204#[cfg(test)]
205mod tests {
206 use super::*;
207
208 use rucc_base::Interner;
209 use rucc_ir::{Alias, Func, Global, Linkage, Signature, TlsModel, Visibility};
210 use rucc_target::{Arch, Env, Os, TargetInfo, Triple};
211
212 /// A module with one of everything: a function with a body and one without, a variable with an
213 /// image and one without, a `static`, a hidden export, an alias and a thread-local.
214 fn module(names: &mut Interner) -> Module {
215 let target = TargetInfo::new(Triple::new(Arch::X86_64, Os::Linux, Env::Gnu));
216 let mut module = Module::new(names.intern("test.c"), &target);
217 let mut defined = Func::new(names.intern("here"), Signature::new());
218 defined.create_block();
219 module.add_func(defined);
220 module.add_func(Func::new(names.intern("exit"), Signature::new()));
221
222 let mut kept = Global::new(names.intern("kept"), 4, 4);
223 kept.init = Some(module.push_data(&[]));
224 module.add_global(kept);
225 module.add_global(Global::new(names.intern("away"), 4, 4));
226
227 let mut quiet = Global::new(names.intern("quiet"), 4, 4);
228 quiet.init = Some(module.push_data(&[]));
229 quiet.linkage = Linkage::Internal;
230 module.add_global(quiet);
231
232 let mut shy = Global::new(names.intern("shy"), 4, 4);
233 shy.init = Some(module.push_data(&[]));
234 shy.visibility = Visibility::Hidden;
235 module.add_global(shy);
236
237 let mut own = Global::new(names.intern("own"), 4, 4);
238 own.init = Some(module.push_data(&[]));
239 own.tls = Some(TlsModel::GlobalDynamic);
240 module.add_global(own);
241
242 module.add_alias(Alias::new(names.intern("second"), names.intern("here")));
243 module
244 }
245
246 #[test]
247 fn a_variable_every_thread_has_its_own_copy_of_is_one() {
248 let mut names = Interner::new();
249 let module = module(&mut names);
250 let elsewhere = Elsewhere::of(&module, Pic::Executable, ObjectFormat::Elf, true);
251 assert!(elsewhere.thread(names.intern("own")));
252 }
253
254 /// The question the other five ask is a different question, and a variable that is not
255 /// thread-local answering yes to this one would put an offset where an address belongs.
256 #[test]
257 fn an_ordinary_variable_is_not() {
258 let mut names = Interner::new();
259 let module = module(&mut names);
260 let elsewhere = Elsewhere::of(&module, Pic::Executable, ObjectFormat::Elf, true);
261 for name in ["kept", "away", "quiet", "shy", "here"] {
262 assert!(!elsewhere.thread(names.intern(name)), "{name} was called thread-local");
263 }
264 }
265
266 #[test]
267 fn a_function_this_file_only_declares_is_reached_through_the_table() {
268 let mut names = Interner::new();
269 let module = module(&mut names);
270 let elsewhere = Elsewhere::of(&module, Pic::Executable, ObjectFormat::Elf, true);
271 assert!(elsewhere.holds(names.intern("exit")));
272 }
273
274 #[test]
275 fn a_function_this_file_defines_is_not() {
276 let mut names = Interner::new();
277 let module = module(&mut names);
278 let elsewhere = Elsewhere::of(&module, Pic::Executable, ObjectFormat::Elf, true);
279 assert!(!elsewhere.holds(names.intern("here")));
280 }
281
282 #[test]
283 fn a_name_the_module_does_not_carry_at_all_is_not() {
284 let mut names = Interner::new();
285 let module = module(&mut names);
286 let elsewhere = Elsewhere::of(&module, Pic::Executable, ObjectFormat::Elf, true);
287 assert!(!elsewhere.holds(names.intern("nowhere")));
288 }
289
290 /// The whole of what an executable pays, which is one entry for the one function it calls in a
291 /// library. Every variable is reached from the instruction pointer, the one it does not define
292 /// included, because the linker copies that one in here.
293 #[test]
294 fn an_executable_pays_for_the_functions_and_for_nothing_else() {
295 let mut names = Interner::new();
296 let module = module(&mut names);
297 let elsewhere = Elsewhere::of(&module, Pic::Executable, ObjectFormat::Elf, true);
298 for name in ["kept", "away", "quiet", "shy", "second"] {
299 assert!(!elsewhere.holds(names.intern(name)), "{name} was in the table");
300 }
301 }
302
303 /// A weak variable nothing defines may be at zero, which no distance from the code reaches.
304 #[test]
305 fn a_weak_variable_this_file_only_declares_is_reached_through_the_table() {
306 let mut names = Interner::new();
307 let mut module = module(&mut names);
308 let mut maybe = Global::new(names.intern("maybe"), 4, 4);
309 maybe.linkage = Linkage::Weak;
310 module.add_global(maybe);
311 let elsewhere = Elsewhere::of(&module, Pic::Executable, ObjectFormat::Elf, true);
312 assert!(elsewhere.holds(names.intern("maybe")));
313 }
314
315 /// Mach-O never copies a variable into the executable, so the one this file only declares is
316 /// read through the table even in a program, and the ones it defines are still reached
317 /// directly.
318 #[test]
319 fn a_mach_o_executable_pays_for_the_variables_it_does_not_define_as_well() {
320 let mut names = Interner::new();
321 let mut module = module(&mut names);
322 let mut near = Global::new(names.intern("near"), 4, 4);
323 near.visibility = Visibility::Hidden;
324 module.add_global(near);
325 let elsewhere = Elsewhere::of(&module, Pic::Executable, ObjectFormat::MachO, true);
326 assert!(elsewhere.holds(names.intern("away")));
327 for name in ["kept", "quiet", "shy", "near"] {
328 assert!(!elsewhere.holds(names.intern(name)), "{name} was in the table");
329 }
330 }
331
332 /// An AArch64 executable pays for a variable it only declares, because the linker there makes
333 /// no copy for an `adrp` and refuses one in a PIE. bzip2 reading `stderr` is what found it.
334 #[test]
335 fn an_executable_that_gets_no_copies_pays_for_the_variables_it_does_not_define() {
336 let mut names = Interner::new();
337 let module = module(&mut names);
338 let elsewhere = Elsewhere::of(&module, Pic::Executable, ObjectFormat::Elf, false);
339 assert!(elsewhere.holds(names.intern("away")));
340 for name in ["kept", "quiet", "shy"] {
341 assert!(!elsewhere.holds(names.intern(name)), "{name} was in the table");
342 }
343 let copied = Elsewhere::of(&module, Pic::Executable, ObjectFormat::Elf, true);
344 assert!(!copied.holds(names.intern("away")));
345 }
346
347 /// A library pays for every name it exports, defined here or not, because the definition the
348 /// process uses may be in another object however plainly this file defines it.
349 #[test]
350 fn a_library_pays_for_every_name_something_else_may_define() {
351 let mut names = Interner::new();
352 let module = module(&mut names);
353 let elsewhere = Elsewhere::of(&module, Pic::Library, ObjectFormat::Elf, true);
354 for name in ["here", "exit", "kept", "away", "second"] {
355 assert!(elsewhere.holds(names.intern(name)), "{name} was not in the table");
356 }
357 }
358
359 /// A format with no table asks nothing of anybody, which is not the same as asking and being
360 /// told no. The name of a function this file only declares stands for an address in the image
361 /// on this format whether the link finds it in another object or in an import library, so the
362 /// instruction pointer reaches it and there is nothing left over to put in a table. gcc writes
363 /// the same `leaq other(%rip)` for the same declaration.
364 #[test]
365 fn a_format_with_no_table_puts_nothing_in_one() {
366 let mut names = Interner::new();
367 let module = module(&mut names);
368 let elsewhere = Elsewhere::of(&module, Pic::Executable, ObjectFormat::Coff, true);
369 for name in ["here", "exit", "kept", "away", "quiet", "shy", "second"] {
370 assert!(!elsewhere.holds(names.intern(name)), "{name} was in the table");
371 }
372 }
373
374 /// And the flag that fills the table on the other format does not fill it here either, since
375 /// there is no interposition on this one for it to be about.
376 #[test]
377 fn a_format_with_no_table_does_not_grow_one_under_the_library_flag() {
378 let mut names = Interner::new();
379 let module = module(&mut names);
380 let elsewhere = Elsewhere::of(&module, Pic::Library, ObjectFormat::Coff, true);
381 for name in ["here", "exit", "kept", "away", "second"] {
382 assert!(!elsewhere.holds(names.intern(name)), "{name} was in the table");
383 }
384 }
385
386 /// The other question this type answers is not the table's, so it keeps its answer whatever the
387 /// format. What a target with no thread-local storage does about it is the writer's refusal
388 /// rather than a name quietly left out here.
389 #[test]
390 fn a_format_with_no_table_still_says_which_variable_every_thread_has_a_copy_of() {
391 let mut names = Interner::new();
392 let module = module(&mut names);
393 let elsewhere = Elsewhere::of(&module, Pic::Executable, ObjectFormat::Coff, true);
394 assert!(elsewhere.thread(names.intern("own")));
395 }
396
397 /// And not for the names nothing outside can reach, which is what makes `-fvisibility=hidden`
398 /// worth writing next to it.
399 #[test]
400 fn a_library_pays_nothing_for_a_name_nothing_outside_it_can_see() {
401 let mut names = Interner::new();
402 let module = module(&mut names);
403 let elsewhere = Elsewhere::of(&module, Pic::Library, ObjectFormat::Elf, true);
404 assert!(!elsewhere.holds(names.intern("quiet")));
405 assert!(!elsewhere.holds(names.intern("shy")));
406 }
407}