]>
Commit | Line | Data |
---|---|---|
54a0048b SL |
1 | // Copyright 2016 The Rust Project Developers. See the COPYRIGHT |
2 | // file at the top-level directory of this distribution and at | |
3 | // http://rust-lang.org/COPYRIGHT. | |
4 | // | |
5 | // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or | |
6 | // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license | |
7 | // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your | |
8 | // option. This file may not be copied, modified, or distributed | |
9 | // except according to those terms. | |
10 | ||
11 | //! The Rust Linkage Model and Symbol Names | |
12 | //! ======================================= | |
13 | //! | |
14 | //! The semantic model of Rust linkage is, broadly, that "there's no global | |
15 | //! namespace" between crates. Our aim is to preserve the illusion of this | |
16 | //! model despite the fact that it's not *quite* possible to implement on | |
17 | //! modern linkers. We initially didn't use system linkers at all, but have | |
18 | //! been convinced of their utility. | |
19 | //! | |
20 | //! There are a few issues to handle: | |
21 | //! | |
22 | //! - Linkers operate on a flat namespace, so we have to flatten names. | |
23 | //! We do this using the C++ namespace-mangling technique. Foo::bar | |
24 | //! symbols and such. | |
25 | //! | |
26 | //! - Symbols for distinct items with the same *name* need to get different | |
27 | //! linkage-names. Examples of this are monomorphizations of functions or | |
28 | //! items within anonymous scopes that end up having the same path. | |
29 | //! | |
30 | //! - Symbols in different crates but with same names "within" the crate need | |
31 | //! to get different linkage-names. | |
32 | //! | |
33 | //! - Symbol names should be deterministic: Two consecutive runs of the | |
34 | //! compiler over the same code base should produce the same symbol names for | |
35 | //! the same items. | |
36 | //! | |
37 | //! - Symbol names should not depend on any global properties of the code base, | |
38 | //! so that small modifications to the code base do not result in all symbols | |
39 | //! changing. In previous versions of the compiler, symbol names incorporated | |
40 | //! the SVH (Stable Version Hash) of the crate. This scheme turned out to be | |
41 | //! infeasible when used in conjunction with incremental compilation because | |
42 | //! small code changes would invalidate all symbols generated previously. | |
43 | //! | |
44 | //! - Even symbols from different versions of the same crate should be able to | |
45 | //! live next to each other without conflict. | |
46 | //! | |
47 | //! In order to fulfill the above requirements the following scheme is used by | |
48 | //! the compiler: | |
49 | //! | |
50 | //! The main tool for avoiding naming conflicts is the incorporation of a 64-bit | |
51 | //! hash value into every exported symbol name. Anything that makes a difference | |
52 | //! to the symbol being named, but does not show up in the regular path needs to | |
53 | //! be fed into this hash: | |
54 | //! | |
55 | //! - Different monomorphizations of the same item have the same path but differ | |
56 | //! in their concrete type parameters, so these parameters are part of the | |
57 | //! data being digested for the symbol hash. | |
58 | //! | |
59 | //! - Rust allows items to be defined in anonymous scopes, such as in | |
60 | //! `fn foo() { { fn bar() {} } { fn bar() {} } }`. Both `bar` functions have | |
61 | //! the path `foo::bar`, since the anonymous scopes do not contribute to the | |
62 | //! path of an item. The compiler already handles this case via so-called | |
63 | //! disambiguating `DefPaths` which use indices to distinguish items with the | |
64 | //! same name. The DefPaths of the functions above are thus `foo[0]::bar[0]` | |
65 | //! and `foo[0]::bar[1]`. In order to incorporate this disambiguation | |
66 | //! information into the symbol name too, these indices are fed into the | |
67 | //! symbol hash, so that the above two symbols would end up with different | |
68 | //! hash values. | |
69 | //! | |
70 | //! The two measures described above suffice to avoid intra-crate conflicts. In | |
71 | //! order to also avoid inter-crate conflicts two more measures are taken: | |
72 | //! | |
73 | //! - The name of the crate containing the symbol is prepended to the symbol | |
74 | //! name, i.e. symbols are "crate qualified". For example, a function `foo` in | |
75 | //! module `bar` in crate `baz` would get a symbol name like | |
76 | //! `baz::bar::foo::{hash}` instead of just `bar::foo::{hash}`. This avoids | |
77 | //! simple conflicts between functions from different crates. | |
78 | //! | |
79 | //! - In order to be able to also use symbols from two versions of the same | |
80 | //! crate (which naturally also have the same name), a stronger measure is | |
81 | //! required: The compiler accepts an arbitrary "disambiguator" value via the | |
82 | //! `-C metadata` commandline argument. This disambiguator is then fed into | |
83 | //! the symbol hash of every exported item. Consequently, the symbols in two | |
84 | //! identical crates but with different disambiguators are not in conflict | |
85 | //! with each other. This facility is mainly intended to be used by build | |
86 | //! tools like Cargo. | |
87 | //! | |
88 | //! A note on symbol name stability | |
89 | //! ------------------------------- | |
90 | //! Previous versions of the compiler resorted to feeding NodeIds into the | |
91 | //! symbol hash in order to disambiguate between items with the same path. The | |
92 | //! current version of the name generation algorithm takes great care not to do | |
93 | //! that, since NodeIds are notoriously unstable: A small change to the | |
94 | //! code base will offset all NodeIds after the change and thus, much as using | |
95 | //! the SVH in the hash, invalidate an unbounded number of symbol names. This | |
96 | //! makes re-using previously compiled code for incremental compilation | |
97 | //! virtually impossible. Thus, symbol hash generation exclusively relies on | |
98 | //! DefPaths which are much more robust in the face of changes to the code base. | |
99 | ||
54a0048b | 100 | use monomorphize::Instance; |
54a0048b | 101 | |
9e0c209e | 102 | use rustc::middle::weak_lang_items; |
cc61c64b | 103 | use rustc::hir::def_id::DefId; |
3157f602 | 104 | use rustc::hir::map as hir_map; |
cc61c64b | 105 | use rustc::ty::{self, Ty, TyCtxt, TypeFoldable}; |
9e0c209e | 106 | use rustc::ty::fold::TypeVisitor; |
3157f602 | 107 | use rustc::ty::item_path::{self, ItemPathBuffer, RootMode}; |
7cac9316 | 108 | use rustc::ty::maps::Providers; |
9e0c209e | 109 | use rustc::ty::subst::Substs; |
cc61c64b | 110 | use rustc::hir::map::definitions::DefPathData; |
9e0c209e | 111 | use rustc::util::common::record_time; |
54a0048b | 112 | |
3157f602 | 113 | use syntax::attr; |
7cac9316 | 114 | use syntax_pos::symbol::Symbol; |
54a0048b | 115 | |
cc61c64b | 116 | use std::fmt::Write; |
54a0048b | 117 | |
7cac9316 XL |
118 | pub fn provide(providers: &mut Providers) { |
119 | *providers = Providers { | |
120 | def_symbol_name, | |
121 | symbol_name, | |
122 | ..*providers | |
123 | }; | |
124 | } | |
125 | ||
cc61c64b XL |
126 | fn get_symbol_hash<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, |
127 | ||
128 | // the DefId of the item this name is for | |
129 | def_id: Option<DefId>, | |
54a0048b SL |
130 | |
131 | // type of the item, without any generic | |
132 | // parameters substituted; this is | |
133 | // included in the hash as a kind of | |
134 | // safeguard. | |
9e0c209e | 135 | item_type: Ty<'tcx>, |
54a0048b SL |
136 | |
137 | // values for generic type parameters, | |
138 | // if any. | |
9e0c209e | 139 | substs: Option<&'tcx Substs<'tcx>>) |
7cac9316 | 140 | -> u64 { |
cc61c64b | 141 | debug!("get_symbol_hash(def_id={:?}, parameters={:?})", def_id, substs); |
54a0048b | 142 | |
476ff2be | 143 | let mut hasher = ty::util::TypeIdHasher::<u64>::new(tcx); |
9e0c209e | 144 | |
c30ab7b3 | 145 | record_time(&tcx.sess.perf_stats.symbol_hash_time, || { |
9e0c209e SL |
146 | // the main symbol name is not necessarily unique; hash in the |
147 | // compiler's internal def-path, guaranteeing each symbol has a | |
148 | // truly unique path | |
cc61c64b | 149 | hasher.hash(def_id.map(|def_id| tcx.def_path_hash(def_id))); |
9e0c209e SL |
150 | |
151 | // Include the main item-type. Note that, in this case, the | |
152 | // assertions about `needs_subst` may not hold, but this item-type | |
153 | // ought to be the same for every reference anyway. | |
154 | assert!(!item_type.has_erasable_regions()); | |
155 | hasher.visit_ty(item_type); | |
156 | ||
157 | // also include any type parameters (for generic items) | |
158 | if let Some(substs) = substs { | |
159 | assert!(!substs.has_erasable_regions()); | |
160 | assert!(!substs.needs_subst()); | |
161 | substs.visit_with(&mut hasher); | |
32a655c1 SL |
162 | |
163 | // If this is an instance of a generic function, we also hash in | |
164 | // the ID of the instantiating crate. This avoids symbol conflicts | |
165 | // in case the same instances is emitted in two crates of the same | |
166 | // project. | |
167 | if substs.types().next().is_some() { | |
cc61c64b XL |
168 | hasher.hash(tcx.crate_name.as_str()); |
169 | hasher.hash(tcx.sess.local_crate_disambiguator().as_str()); | |
32a655c1 | 170 | } |
9e0c209e SL |
171 | } |
172 | }); | |
54a0048b | 173 | |
9e0c209e | 174 | // 64 bits should be enough to avoid collisions. |
7cac9316 XL |
175 | hasher.finish() |
176 | } | |
177 | ||
178 | fn def_symbol_name<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) | |
179 | -> ty::SymbolName | |
180 | { | |
181 | let mut buffer = SymbolPathBuffer::new(); | |
182 | item_path::with_forced_absolute_paths(|| { | |
183 | tcx.push_item_path(&mut buffer, def_id); | |
184 | }); | |
185 | buffer.into_interned() | |
186 | } | |
187 | ||
188 | fn symbol_name<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, instance: Instance<'tcx>) | |
189 | -> ty::SymbolName | |
190 | { | |
191 | ty::SymbolName { name: Symbol::intern(&compute_symbol_name(tcx, instance)).as_str() } | |
54a0048b SL |
192 | } |
193 | ||
7cac9316 XL |
194 | fn compute_symbol_name<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, instance: Instance<'tcx>) |
195 | -> String | |
196 | { | |
cc61c64b XL |
197 | let def_id = instance.def_id(); |
198 | let substs = instance.substs; | |
3157f602 | 199 | |
cc61c64b XL |
200 | debug!("symbol_name(def_id={:?}, substs={:?})", |
201 | def_id, substs); | |
54a0048b | 202 | |
cc61c64b | 203 | let node_id = tcx.hir.as_local_node_id(def_id); |
54a0048b | 204 | |
cc61c64b XL |
205 | if let Some(id) = node_id { |
206 | if tcx.sess.plugin_registrar_fn.get() == Some(id) { | |
207 | let idx = def_id.index; | |
208 | let disambiguator = tcx.sess.local_crate_disambiguator(); | |
209 | return tcx.sess.generate_plugin_registrar_symbol(disambiguator, idx); | |
54a0048b | 210 | } |
cc61c64b XL |
211 | if tcx.sess.derive_registrar_fn.get() == Some(id) { |
212 | let idx = def_id.index; | |
213 | let disambiguator = tcx.sess.local_crate_disambiguator(); | |
214 | return tcx.sess.generate_derive_registrar_symbol(disambiguator, idx); | |
3157f602 | 215 | } |
cc61c64b | 216 | } |
3157f602 | 217 | |
cc61c64b XL |
218 | // FIXME(eddyb) Precompute a custom symbol name based on attributes. |
219 | let attrs = tcx.get_attrs(def_id); | |
220 | let is_foreign = if let Some(id) = node_id { | |
221 | match tcx.hir.get(id) { | |
222 | hir_map::NodeForeignItem(_) => true, | |
223 | _ => false | |
54a0048b | 224 | } |
cc61c64b | 225 | } else { |
7cac9316 | 226 | tcx.is_foreign_item(def_id) |
cc61c64b | 227 | }; |
54a0048b | 228 | |
cc61c64b XL |
229 | if let Some(name) = weak_lang_items::link_name(&attrs) { |
230 | return name.to_string(); | |
231 | } | |
232 | ||
233 | if is_foreign { | |
234 | if let Some(name) = attr::first_attr_value_str_by_name(&attrs, "link_name") { | |
3157f602 XL |
235 | return name.to_string(); |
236 | } | |
cc61c64b XL |
237 | // Don't mangle foreign items. |
238 | return tcx.item_name(def_id).as_str().to_string(); | |
239 | } | |
54a0048b | 240 | |
cc61c64b XL |
241 | if let Some(name) = attr::find_export_name_attr(tcx.sess.diagnostic(), &attrs) { |
242 | // Use provided name | |
243 | return name.to_string(); | |
244 | } | |
54a0048b | 245 | |
cc61c64b XL |
246 | if attr::contains_name(&attrs, "no_mangle") { |
247 | // Don't mangle | |
248 | return tcx.item_name(def_id).as_str().to_string(); | |
249 | } | |
250 | ||
251 | // We want to compute the "type" of this item. Unfortunately, some | |
252 | // kinds of items (e.g., closures) don't have an entry in the | |
253 | // item-type array. So walk back up the find the closest parent | |
254 | // that DOES have an entry. | |
255 | let mut ty_def_id = def_id; | |
256 | let instance_ty; | |
257 | loop { | |
258 | let key = tcx.def_key(ty_def_id); | |
259 | match key.disambiguated_data.data { | |
260 | DefPathData::TypeNs(_) | | |
261 | DefPathData::ValueNs(_) => { | |
7cac9316 | 262 | instance_ty = tcx.type_of(ty_def_id); |
cc61c64b XL |
263 | break; |
264 | } | |
265 | _ => { | |
266 | // if we're making a symbol for something, there ought | |
267 | // to be a value or type-def or something in there | |
268 | // *somewhere* | |
269 | ty_def_id.index = key.parent.unwrap_or_else(|| { | |
270 | bug!("finding type for {:?}, encountered def-id {:?} with no \ | |
271 | parent", def_id, ty_def_id); | |
272 | }); | |
3157f602 XL |
273 | } |
274 | } | |
cc61c64b | 275 | } |
54a0048b | 276 | |
cc61c64b XL |
277 | // Erase regions because they may not be deterministic when hashed |
278 | // and should not matter anyhow. | |
279 | let instance_ty = tcx.erase_regions(&instance_ty); | |
3157f602 | 280 | |
cc61c64b | 281 | let hash = get_symbol_hash(tcx, Some(def_id), instance_ty, Some(substs)); |
3157f602 | 282 | |
7cac9316 | 283 | SymbolPathBuffer::from_interned(tcx.def_symbol_name(def_id)).finish(hash) |
cc61c64b | 284 | } |
3157f602 | 285 | |
cc61c64b XL |
286 | // Follow C++ namespace-mangling style, see |
287 | // http://en.wikipedia.org/wiki/Name_mangling for more info. | |
288 | // | |
289 | // It turns out that on macOS you can actually have arbitrary symbols in | |
290 | // function names (at least when given to LLVM), but this is not possible | |
291 | // when using unix's linker. Perhaps one day when we just use a linker from LLVM | |
292 | // we won't need to do this name mangling. The problem with name mangling is | |
293 | // that it seriously limits the available characters. For example we can't | |
294 | // have things like &T in symbol names when one would theoretically | |
295 | // want them for things like impls of traits on that type. | |
296 | // | |
297 | // To be able to work on all platforms and get *some* reasonable output, we | |
298 | // use C++ name-mangling. | |
299 | struct SymbolPathBuffer { | |
300 | result: String, | |
301 | temp_buf: String | |
302 | } | |
54a0048b | 303 | |
cc61c64b XL |
304 | impl SymbolPathBuffer { |
305 | fn new() -> Self { | |
306 | let mut result = SymbolPathBuffer { | |
307 | result: String::with_capacity(64), | |
308 | temp_buf: String::with_capacity(16) | |
309 | }; | |
310 | result.result.push_str("_ZN"); // _Z == Begin name-sequence, N == nested | |
311 | result | |
3157f602 | 312 | } |
54a0048b | 313 | |
7cac9316 XL |
314 | fn from_interned(symbol: ty::SymbolName) -> Self { |
315 | let mut result = SymbolPathBuffer { | |
316 | result: String::with_capacity(64), | |
317 | temp_buf: String::with_capacity(16) | |
318 | }; | |
319 | result.result.push_str(&symbol.name); | |
320 | result | |
321 | } | |
322 | ||
323 | fn into_interned(self) -> ty::SymbolName { | |
324 | ty::SymbolName { name: Symbol::intern(&self.result).as_str() } | |
325 | } | |
326 | ||
327 | fn finish(mut self, hash: u64) -> String { | |
328 | // E = end name-sequence | |
329 | let _ = write!(self.result, "17h{:016x}E", hash); | |
cc61c64b XL |
330 | self.result |
331 | } | |
54a0048b SL |
332 | } |
333 | ||
334 | impl ItemPathBuffer for SymbolPathBuffer { | |
335 | fn root_mode(&self) -> &RootMode { | |
336 | const ABSOLUTE: &'static RootMode = &RootMode::Absolute; | |
337 | ABSOLUTE | |
338 | } | |
339 | ||
340 | fn push(&mut self, text: &str) { | |
cc61c64b XL |
341 | self.temp_buf.clear(); |
342 | let need_underscore = sanitize(&mut self.temp_buf, text); | |
343 | let _ = write!(self.result, "{}", self.temp_buf.len() + (need_underscore as usize)); | |
344 | if need_underscore { | |
345 | self.result.push('_'); | |
346 | } | |
347 | self.result.push_str(&self.temp_buf); | |
54a0048b SL |
348 | } |
349 | } | |
350 | ||
54a0048b SL |
351 | // Name sanitation. LLVM will happily accept identifiers with weird names, but |
352 | // gas doesn't! | |
353 | // gas accepts the following characters in symbols: a-z, A-Z, 0-9, ., _, $ | |
cc61c64b XL |
354 | // |
355 | // returns true if an underscore must be added at the start | |
356 | pub fn sanitize(result: &mut String, s: &str) -> bool { | |
54a0048b SL |
357 | for c in s.chars() { |
358 | match c { | |
359 | // Escape these with $ sequences | |
360 | '@' => result.push_str("$SP$"), | |
361 | '*' => result.push_str("$BP$"), | |
362 | '&' => result.push_str("$RF$"), | |
363 | '<' => result.push_str("$LT$"), | |
364 | '>' => result.push_str("$GT$"), | |
365 | '(' => result.push_str("$LP$"), | |
366 | ')' => result.push_str("$RP$"), | |
367 | ',' => result.push_str("$C$"), | |
368 | ||
369 | // '.' doesn't occur in types and functions, so reuse it | |
370 | // for ':' and '-' | |
371 | '-' | ':' => result.push('.'), | |
372 | ||
373 | // These are legal symbols | |
374 | 'a' ... 'z' | |
375 | | 'A' ... 'Z' | |
376 | | '0' ... '9' | |
377 | | '_' | '.' | '$' => result.push(c), | |
378 | ||
379 | _ => { | |
380 | result.push('$'); | |
381 | for c in c.escape_unicode().skip(1) { | |
382 | match c { | |
383 | '{' => {}, | |
384 | '}' => result.push('$'), | |
385 | c => result.push(c), | |
386 | } | |
387 | } | |
388 | } | |
389 | } | |
390 | } | |
391 | ||
392 | // Underscore-qualify anything that didn't start as an ident. | |
cc61c64b | 393 | !result.is_empty() && |
54a0048b | 394 | result.as_bytes()[0] != '_' as u8 && |
cc61c64b | 395 | ! (result.as_bytes()[0] as char).is_xid_start() |
54a0048b | 396 | } |