Skip to main content

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