]> git.lizzy.rs Git - rust.git/blob - src/librustc_trans/back/symbol_export.rs
rustc: Implement the #[global_allocator] attribute
[rust.git] / src / librustc_trans / back / symbol_export.rs
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 use context::SharedCrateContext;
12 use monomorphize::Instance;
13 use rustc::util::nodemap::FxHashMap;
14 use rustc::hir::def_id::{DefId, CrateNum, LOCAL_CRATE};
15 use rustc::session::config;
16 use rustc::ty::TyCtxt;
17 use syntax::attr;
18
19 /// The SymbolExportLevel of a symbols specifies from which kinds of crates
20 /// the symbol will be exported. `C` symbols will be exported from any
21 /// kind of crate, including cdylibs which export very few things.
22 /// `Rust` will only be exported if the crate produced is a Rust
23 /// dylib.
24 #[derive(Eq, PartialEq, Debug, Copy, Clone)]
25 pub enum SymbolExportLevel {
26     C,
27     Rust,
28 }
29
30 /// The set of symbols exported from each crate in the crate graph.
31 pub struct ExportedSymbols {
32     exports: FxHashMap<CrateNum, Vec<(String, SymbolExportLevel)>>,
33 }
34
35 impl ExportedSymbols {
36     pub fn empty() -> ExportedSymbols {
37         ExportedSymbols {
38             exports: FxHashMap(),
39         }
40     }
41
42     pub fn compute<'a, 'tcx>(scx: &SharedCrateContext<'a, 'tcx>) -> ExportedSymbols {
43         let mut local_crate: Vec<_> = scx
44             .exported_symbols()
45             .iter()
46             .map(|&node_id| {
47                 scx.tcx().hir.local_def_id(node_id)
48             })
49             .map(|def_id| {
50                 let name = scx.tcx().symbol_name(Instance::mono(scx.tcx(), def_id));
51                 let export_level = export_level(scx, def_id);
52                 debug!("EXPORTED SYMBOL (local): {} ({:?})", name, export_level);
53                 (str::to_owned(&name), export_level)
54             })
55             .collect();
56
57         if scx.sess().entry_fn.borrow().is_some() {
58             local_crate.push(("main".to_string(), SymbolExportLevel::C));
59         }
60
61         if let Some(id) = scx.sess().derive_registrar_fn.get() {
62             let def_id = scx.tcx().hir.local_def_id(id);
63             let idx = def_id.index;
64             let disambiguator = scx.sess().local_crate_disambiguator();
65             let registrar = scx.sess().generate_derive_registrar_symbol(disambiguator, idx);
66             local_crate.push((registrar, SymbolExportLevel::C));
67         }
68
69         if scx.sess().crate_types.borrow().contains(&config::CrateTypeDylib) {
70             local_crate.push((metadata_symbol_name(scx.tcx()),
71                               SymbolExportLevel::Rust));
72         }
73
74         let mut exports = FxHashMap();
75         exports.insert(LOCAL_CRATE, local_crate);
76
77         for cnum in scx.sess().cstore.crates() {
78             debug_assert!(cnum != LOCAL_CRATE);
79
80             // If this crate is a plugin and/or a custom derive crate, then
81             // we're not even going to link those in so we skip those crates.
82             if scx.sess().cstore.plugin_registrar_fn(cnum).is_some() ||
83                scx.sess().cstore.derive_registrar_fn(cnum).is_some() {
84                 continue;
85             }
86
87             // Check to see if this crate is a "special runtime crate". These
88             // crates, implementation details of the standard library, typically
89             // have a bunch of `pub extern` and `#[no_mangle]` functions as the
90             // ABI between them. We don't want their symbols to have a `C`
91             // export level, however, as they're just implementation details.
92             // Down below we'll hardwire all of the symbols to the `Rust` export
93             // level instead.
94             let special_runtime_crate =
95                 scx.tcx().is_panic_runtime(cnum.as_def_id()) ||
96                 scx.sess().cstore.is_compiler_builtins(cnum);
97
98             let crate_exports = scx
99                 .sess()
100                 .cstore
101                 .exported_symbols(cnum)
102                 .iter()
103                 .map(|&def_id| {
104                     let name = scx.tcx().symbol_name(Instance::mono(scx.tcx(), def_id));
105                     let export_level = if special_runtime_crate {
106                         // We can probably do better here by just ensuring that
107                         // it has hidden visibility rather than public
108                         // visibility, as this is primarily here to ensure it's
109                         // not stripped during LTO.
110                         //
111                         // In general though we won't link right if these
112                         // symbols are stripped, and LTO currently strips them.
113                         if &*name == "rust_eh_personality" ||
114                            &*name == "rust_eh_register_frames" ||
115                            &*name == "rust_eh_unregister_frames" {
116                             SymbolExportLevel::C
117                         } else {
118                             SymbolExportLevel::Rust
119                         }
120                     } else {
121                         export_level(scx, def_id)
122                     };
123                     debug!("EXPORTED SYMBOL (re-export): {} ({:?})", name, export_level);
124                     (str::to_owned(&name), export_level)
125                 })
126                 .collect();
127
128             exports.insert(cnum, crate_exports);
129         }
130
131         return ExportedSymbols {
132             exports: exports
133         };
134
135         fn export_level(scx: &SharedCrateContext,
136                         sym_def_id: DefId)
137                         -> SymbolExportLevel {
138             let attrs = scx.tcx().get_attrs(sym_def_id);
139             if attr::contains_extern_indicator(scx.sess().diagnostic(), &attrs) {
140                 SymbolExportLevel::C
141             } else {
142                 SymbolExportLevel::Rust
143             }
144         }
145     }
146
147     pub fn exported_symbols(&self,
148                             cnum: CrateNum)
149                             -> &[(String, SymbolExportLevel)] {
150         match self.exports.get(&cnum) {
151             Some(exports) => exports,
152             None => &[]
153         }
154     }
155
156     pub fn for_each_exported_symbol<F>(&self,
157                                        cnum: CrateNum,
158                                        export_threshold: SymbolExportLevel,
159                                        mut f: F)
160         where F: FnMut(&str, SymbolExportLevel)
161     {
162         for &(ref name, export_level) in self.exported_symbols(cnum) {
163             if is_below_threshold(export_level, export_threshold) {
164                 f(&name, export_level)
165             }
166         }
167     }
168 }
169
170 pub fn metadata_symbol_name(tcx: TyCtxt) -> String {
171     format!("rust_metadata_{}_{}",
172             tcx.crate_name(LOCAL_CRATE),
173             tcx.crate_disambiguator(LOCAL_CRATE))
174 }
175
176 pub fn crate_export_threshold(crate_type: config::CrateType)
177                                      -> SymbolExportLevel {
178     match crate_type {
179         config::CrateTypeExecutable |
180         config::CrateTypeStaticlib  |
181         config::CrateTypeProcMacro  |
182         config::CrateTypeCdylib     => SymbolExportLevel::C,
183         config::CrateTypeRlib       |
184         config::CrateTypeDylib      => SymbolExportLevel::Rust,
185     }
186 }
187
188 pub fn crates_export_threshold(crate_types: &[config::CrateType])
189                                       -> SymbolExportLevel {
190     if crate_types.iter().any(|&crate_type| {
191         crate_export_threshold(crate_type) == SymbolExportLevel::Rust
192     }) {
193         SymbolExportLevel::Rust
194     } else {
195         SymbolExportLevel::C
196     }
197 }
198
199 pub fn is_below_threshold(level: SymbolExportLevel,
200                           threshold: SymbolExportLevel)
201                           -> bool {
202     if threshold == SymbolExportLevel::Rust {
203         // We export everything from Rust dylibs
204         true
205     } else {
206         level == SymbolExportLevel::C
207     }
208 }