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