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