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 #[must_use]
79 pub fn of(module: &Module, pic: Pic, format: ObjectFormat) -> Self {
80 let threads = module
81 .globals()
82 .filter(|&id| module[id].tls.is_some())
83 .map(|id| module[id].name)
84 .collect();
85 let described = format == ObjectFormat::MachO;
86 Self { threads, described, ..Self::table(module, pic, format) }
87 }
88
89 /// The half of the above that is about the global offset table, which is the older one.
90 ///
91 /// Empty on a format that has no such table. COFF is the one, and it is not that the question
92 /// goes unanswered there: a name this file only declares is reached from the instruction
93 /// pointer like any other, because whatever supplies it supplies a piece of this image to
94 /// measure to. A name the link resolves out of another object is in the image, and a name that
95 /// comes from a DLL arrives through an import library, which is an archive member holding a
96 /// jump under the plain name, so the name still stands for an address in this image and every
97 /// object that takes it gets the one the linker kept. Measured against gcc 13.2 for
98 /// `x86_64-w64-mingw32`, which writes `leaq other(%rip), %rax` for the address of a function it
99 /// has only seen declared. Asking for a table there instead reached the object writer as a
100 /// relocation it has no way to write, which is what tamnd/rucc#1443 was.
101 fn table(module: &Module, pic: Pic, format: ObjectFormat) -> Self {
102 if format == ObjectFormat::Coff {
103 return Self::default();
104 }
105 let funcs = module.funcs().filter(|&id| {
106 let func = &module[id];
107 func.is_declaration() || pic.replaceable(func.linkage, func.visibility)
108 });
109 // A weak variable nothing here defines is the one variable the copying above does not
110 // cover, since there may be no definition anywhere to copy and then its address is null. The
111 // distance from here to null is not a number the linker has, so lld refuses the
112 // `R_X86_64_PC32` and gcc reads the address out of a slot, which the linker fills with zero.
113 //
114 // Mach-O does no copying at all. `dyld` has no copy relocation, so a variable a library
115 // defines stays in the library and the only way to it is the slot. That is every variable
116 // this file only declares, unless it is hidden and so promised to be in the same image,
117 // and it is what clang writes: `_ext@GOTPAGE` on arm64 and `_ext@GOTPCREL` on x86-64.
118 let uncopied = format == ObjectFormat::MachO;
119 let globals = module
120 .globals()
121 .filter(|&id| {
122 let global = &module[id];
123 (global.is_declaration()
124 && (global.linkage == Linkage::Weak
125 || (uncopied && global.visibility == Visibility::Default)))
126 || pic.replaceable(global.linkage, global.visibility)
127 })
128 .map(|id| module[id].name);
129 // An alias is a symbol of its own with a linkage and a visibility of its own, so it answers
130 // this for itself the same way it answered the visibility question in #752. What it points
131 // at is a separate name and is decided separately, which is what `weak, alias,
132 // visibility("hidden")` over an exported definition needs.
133 let aliases = module
134 .aliases()
135 .filter(|&id| pic.replaceable(module[id].linkage, module[id].visibility))
136 .map(|id| module[id].name);
137 funcs.map(|id| module[id].name).chain(globals).chain(aliases).collect()
138 }
139
140 /// Whether the address of that name has to be read out of the global offset table.
141 #[must_use]
142 pub fn holds(&self, name: Symbol) -> bool {
143 self.names.contains(&name)
144 }
145
146 /// Whether that name is a variable every thread has its own copy of.
147 ///
148 /// Asked before [`Self::holds`] and not instead of it, because the two answers are about
149 /// different things: a thread-local variable that another object may define is still reached
150 /// the same way, since the table slot holds an offset that is the same for every copy and the
151 /// question of whose copy is answered by the segment register rather than by the link.
152 #[must_use]
153 pub fn thread(&self, name: Symbol) -> bool {
154 self.threads.contains(&name)
155 }
156
157 /// Whether a thread-local variable is reached by calling through its descriptor, which is how
158 /// Mach-O does it on both architectures.
159 ///
160 /// The slot the table holds for such a variable is the address of the descriptor rather than an
161 /// offset from the thread pointer, and the first word of the descriptor is a function that takes
162 /// that address and gives back this thread's copy. So there is no thread pointer to add to,
163 /// and the answer is the value the call returns.
164 #[must_use]
165 pub const fn described(&self) -> bool {
166 self.described
167 }
168}
169
170/// The same set, written out by hand.
171///
172/// [`Elsewhere::of`] is how the driver builds one and is the only way a compilation does. This is
173/// for a test that wants to lower one function and say what is outside the file without building a
174/// module for it to be outside of.
175impl FromIterator<Symbol> for Elsewhere {
176 fn from_iter<T: IntoIterator<Item = Symbol>>(names: T) -> Self {
177 Self { names: names.into_iter().collect(), threads: HashSet::new(), described: false }
178 }
179}
180
181impl Elsewhere {
182 /// The same set with those names said to be thread-local, for a test that lowers one function.
183 #[must_use]
184 pub fn with_threads<T: IntoIterator<Item = Symbol>>(mut self, threads: T) -> Self {
185 self.threads = threads.into_iter().collect();
186 self
187 }
188
189 /// The same set with thread-locals reached through a descriptor, for a test that lowers one
190 /// function the way Mach-O would.
191 #[must_use]
192 pub const fn with_descriptors(mut self) -> Self {
193 self.described = true;
194 self
195 }
196}
197
198#[cfg(test)]
199mod tests {
200 use super::*;
201
202 use rucc_base::Interner;
203 use rucc_ir::{Alias, Func, Global, Linkage, Signature, TlsModel, Visibility};
204 use rucc_target::{Arch, Env, Os, TargetInfo, Triple};
205
206 /// A module with one of everything: a function with a body and one without, a variable with an
207 /// image and one without, a `static`, a hidden export, an alias and a thread-local.
208 fn module(names: &mut Interner) -> Module {
209 let target = TargetInfo::new(Triple::new(Arch::X86_64, Os::Linux, Env::Gnu));
210 let mut module = Module::new(names.intern("test.c"), &target);
211 let mut defined = Func::new(names.intern("here"), Signature::new());
212 defined.create_block();
213 module.add_func(defined);
214 module.add_func(Func::new(names.intern("exit"), Signature::new()));
215
216 let mut kept = Global::new(names.intern("kept"), 4, 4);
217 kept.init = Some(module.push_data(&[]));
218 module.add_global(kept);
219 module.add_global(Global::new(names.intern("away"), 4, 4));
220
221 let mut quiet = Global::new(names.intern("quiet"), 4, 4);
222 quiet.init = Some(module.push_data(&[]));
223 quiet.linkage = Linkage::Internal;
224 module.add_global(quiet);
225
226 let mut shy = Global::new(names.intern("shy"), 4, 4);
227 shy.init = Some(module.push_data(&[]));
228 shy.visibility = Visibility::Hidden;
229 module.add_global(shy);
230
231 let mut own = Global::new(names.intern("own"), 4, 4);
232 own.init = Some(module.push_data(&[]));
233 own.tls = Some(TlsModel::GlobalDynamic);
234 module.add_global(own);
235
236 module.add_alias(Alias::new(names.intern("second"), names.intern("here")));
237 module
238 }
239
240 #[test]
241 fn a_variable_every_thread_has_its_own_copy_of_is_one() {
242 let mut names = Interner::new();
243 let module = module(&mut names);
244 let elsewhere = Elsewhere::of(&module, Pic::Executable, ObjectFormat::Elf);
245 assert!(elsewhere.thread(names.intern("own")));
246 }
247
248 /// The question the other five ask is a different question, and a variable that is not
249 /// thread-local answering yes to this one would put an offset where an address belongs.
250 #[test]
251 fn an_ordinary_variable_is_not() {
252 let mut names = Interner::new();
253 let module = module(&mut names);
254 let elsewhere = Elsewhere::of(&module, Pic::Executable, ObjectFormat::Elf);
255 for name in ["kept", "away", "quiet", "shy", "here"] {
256 assert!(!elsewhere.thread(names.intern(name)), "{name} was called thread-local");
257 }
258 }
259
260 #[test]
261 fn a_function_this_file_only_declares_is_reached_through_the_table() {
262 let mut names = Interner::new();
263 let module = module(&mut names);
264 let elsewhere = Elsewhere::of(&module, Pic::Executable, ObjectFormat::Elf);
265 assert!(elsewhere.holds(names.intern("exit")));
266 }
267
268 #[test]
269 fn a_function_this_file_defines_is_not() {
270 let mut names = Interner::new();
271 let module = module(&mut names);
272 let elsewhere = Elsewhere::of(&module, Pic::Executable, ObjectFormat::Elf);
273 assert!(!elsewhere.holds(names.intern("here")));
274 }
275
276 #[test]
277 fn a_name_the_module_does_not_carry_at_all_is_not() {
278 let mut names = Interner::new();
279 let module = module(&mut names);
280 let elsewhere = Elsewhere::of(&module, Pic::Executable, ObjectFormat::Elf);
281 assert!(!elsewhere.holds(names.intern("nowhere")));
282 }
283
284 /// The whole of what an executable pays, which is one entry for the one function it calls in a
285 /// library. Every variable is reached from the instruction pointer, the one it does not define
286 /// included, because the linker copies that one in here.
287 #[test]
288 fn an_executable_pays_for_the_functions_and_for_nothing_else() {
289 let mut names = Interner::new();
290 let module = module(&mut names);
291 let elsewhere = Elsewhere::of(&module, Pic::Executable, ObjectFormat::Elf);
292 for name in ["kept", "away", "quiet", "shy", "second"] {
293 assert!(!elsewhere.holds(names.intern(name)), "{name} was in the table");
294 }
295 }
296
297 /// A weak variable nothing defines may be at zero, which no distance from the code reaches.
298 #[test]
299 fn a_weak_variable_this_file_only_declares_is_reached_through_the_table() {
300 let mut names = Interner::new();
301 let mut module = module(&mut names);
302 let mut maybe = Global::new(names.intern("maybe"), 4, 4);
303 maybe.linkage = Linkage::Weak;
304 module.add_global(maybe);
305 let elsewhere = Elsewhere::of(&module, Pic::Executable, ObjectFormat::Elf);
306 assert!(elsewhere.holds(names.intern("maybe")));
307 }
308
309 /// Mach-O never copies a variable into the executable, so the one this file only declares is
310 /// read through the table even in a program, and the ones it defines are still reached
311 /// directly.
312 #[test]
313 fn a_mach_o_executable_pays_for_the_variables_it_does_not_define_as_well() {
314 let mut names = Interner::new();
315 let mut module = module(&mut names);
316 let mut near = Global::new(names.intern("near"), 4, 4);
317 near.visibility = Visibility::Hidden;
318 module.add_global(near);
319 let elsewhere = Elsewhere::of(&module, Pic::Executable, ObjectFormat::MachO);
320 assert!(elsewhere.holds(names.intern("away")));
321 for name in ["kept", "quiet", "shy", "near"] {
322 assert!(!elsewhere.holds(names.intern(name)), "{name} was in the table");
323 }
324 }
325
326 /// A library pays for every name it exports, defined here or not, because the definition the
327 /// process uses may be in another object however plainly this file defines it.
328 #[test]
329 fn a_library_pays_for_every_name_something_else_may_define() {
330 let mut names = Interner::new();
331 let module = module(&mut names);
332 let elsewhere = Elsewhere::of(&module, Pic::Library, ObjectFormat::Elf);
333 for name in ["here", "exit", "kept", "away", "second"] {
334 assert!(elsewhere.holds(names.intern(name)), "{name} was not in the table");
335 }
336 }
337
338 /// A format with no table asks nothing of anybody, which is not the same as asking and being
339 /// told no. The name of a function this file only declares stands for an address in the image
340 /// on this format whether the link finds it in another object or in an import library, so the
341 /// instruction pointer reaches it and there is nothing left over to put in a table. gcc writes
342 /// the same `leaq other(%rip)` for the same declaration.
343 #[test]
344 fn a_format_with_no_table_puts_nothing_in_one() {
345 let mut names = Interner::new();
346 let module = module(&mut names);
347 let elsewhere = Elsewhere::of(&module, Pic::Executable, ObjectFormat::Coff);
348 for name in ["here", "exit", "kept", "away", "quiet", "shy", "second"] {
349 assert!(!elsewhere.holds(names.intern(name)), "{name} was in the table");
350 }
351 }
352
353 /// And the flag that fills the table on the other format does not fill it here either, since
354 /// there is no interposition on this one for it to be about.
355 #[test]
356 fn a_format_with_no_table_does_not_grow_one_under_the_library_flag() {
357 let mut names = Interner::new();
358 let module = module(&mut names);
359 let elsewhere = Elsewhere::of(&module, Pic::Library, ObjectFormat::Coff);
360 for name in ["here", "exit", "kept", "away", "second"] {
361 assert!(!elsewhere.holds(names.intern(name)), "{name} was in the table");
362 }
363 }
364
365 /// The other question this type answers is not the table's, so it keeps its answer whatever the
366 /// format. What a target with no thread-local storage does about it is the writer's refusal
367 /// rather than a name quietly left out here.
368 #[test]
369 fn a_format_with_no_table_still_says_which_variable_every_thread_has_a_copy_of() {
370 let mut names = Interner::new();
371 let module = module(&mut names);
372 let elsewhere = Elsewhere::of(&module, Pic::Executable, ObjectFormat::Coff);
373 assert!(elsewhere.thread(names.intern("own")));
374 }
375
376 /// And not for the names nothing outside can reach, which is what makes `-fvisibility=hidden`
377 /// worth writing next to it.
378 #[test]
379 fn a_library_pays_nothing_for_a_name_nothing_outside_it_can_see() {
380 let mut names = Interner::new();
381 let module = module(&mut names);
382 let elsewhere = Elsewhere::of(&module, Pic::Library, ObjectFormat::Elf);
383 assert!(!elsewhere.holds(names.intern("quiet")));
384 assert!(!elsewhere.holds(names.intern("shy")));
385 }
386}