]> git.lizzy.rs Git - rust.git/blob - src/librustc_trans/back/symbol_export.rs
move Instance to rustc and use it in the collector
[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 symbol_map::SymbolMap;
14 use back::symbol_names::symbol_name;
15 use util::nodemap::FxHashMap;
16 use rustc::hir::def_id::{DefId, CrateNum, LOCAL_CRATE};
17 use rustc::session::config;
18 use syntax::attr;
19 use trans_item::TransItem;
20
21 /// The SymbolExportLevel of a symbols specifies from which kinds of crates
22 /// the symbol will be exported. `C` symbols will be exported from any
23 /// kind of crate, including cdylibs which export very few things.
24 /// `Rust` will only be exported if the crate produced is a Rust
25 /// dylib.
26 #[derive(Eq, PartialEq, Debug, Copy, Clone)]
27 pub enum SymbolExportLevel {
28     C,
29     Rust,
30 }
31
32 /// The set of symbols exported from each crate in the crate graph.
33 pub struct ExportedSymbols {
34     exports: FxHashMap<CrateNum, Vec<(String, SymbolExportLevel)>>,
35 }
36
37 impl ExportedSymbols {
38
39     pub fn empty() -> ExportedSymbols {
40         ExportedSymbols {
41             exports: FxHashMap(),
42         }
43     }
44
45     pub fn compute_from<'a, 'tcx>(scx: &SharedCrateContext<'a, 'tcx>,
46                                   symbol_map: &SymbolMap<'tcx>)
47                                   -> ExportedSymbols {
48         let mut local_crate: Vec<_> = scx
49             .exported_symbols()
50             .iter()
51             .map(|&node_id| {
52                 scx.tcx().hir.local_def_id(node_id)
53             })
54             .map(|def_id| {
55                 let name = symbol_for_def_id(scx, def_id, symbol_map);
56                 let export_level = export_level(scx, def_id);
57                 debug!("EXPORTED SYMBOL (local): {} ({:?})", name, export_level);
58                 (name, export_level)
59             })
60             .collect();
61
62         if scx.sess().entry_fn.borrow().is_some() {
63             local_crate.push(("main".to_string(), SymbolExportLevel::C));
64         }
65
66         if let Some(id) = scx.sess().derive_registrar_fn.get() {
67             let svh = &scx.link_meta().crate_hash;
68             let def_id = scx.tcx().hir.local_def_id(id);
69             let idx = def_id.index;
70             let registrar = scx.sess().generate_derive_registrar_symbol(svh, idx);
71             local_crate.push((registrar, SymbolExportLevel::C));
72         }
73
74         if scx.sess().crate_types.borrow().contains(&config::CrateTypeDylib) {
75             local_crate.push((scx.metadata_symbol_name(),
76                               SymbolExportLevel::Rust));
77         }
78
79         let mut exports = FxHashMap();
80         exports.insert(LOCAL_CRATE, local_crate);
81
82         for cnum in scx.sess().cstore.crates() {
83             debug_assert!(cnum != LOCAL_CRATE);
84
85             // If this crate is a plugin and/or a custom derive crate, then
86             // we're not even going to link those in so we skip those crates.
87             if scx.sess().cstore.plugin_registrar_fn(cnum).is_some() ||
88                scx.sess().cstore.derive_registrar_fn(cnum).is_some() {
89                 continue;
90             }
91
92             // Check to see if this crate is a "special runtime crate". These
93             // crates, implementation details of the standard library, typically
94             // have a bunch of `pub extern` and `#[no_mangle]` functions as the
95             // ABI between them. We don't want their symbols to have a `C`
96             // export level, however, as they're just implementation details.
97             // Down below we'll hardwire all of the symbols to the `Rust` export
98             // level instead.
99             let special_runtime_crate =
100                 scx.sess().cstore.is_allocator(cnum) ||
101                 scx.sess().cstore.is_panic_runtime(cnum) ||
102                 scx.sess().cstore.is_compiler_builtins(cnum);
103
104             let crate_exports = scx
105                 .sess()
106                 .cstore
107                 .exported_symbols(cnum)
108                 .iter()
109                 .map(|&def_id| {
110                     let name = symbol_name(Instance::mono(scx.tcx(), def_id), scx);
111                     let export_level = if special_runtime_crate {
112                         // We can probably do better here by just ensuring that
113                         // it has hidden visibility rather than public
114                         // visibility, as this is primarily here to ensure it's
115                         // not stripped during LTO.
116                         //
117                         // In general though we won't link right if these
118                         // symbols are stripped, and LTO currently strips them.
119                         if name == "rust_eh_personality" ||
120                            name == "rust_eh_register_frames" ||
121                            name == "rust_eh_unregister_frames" {
122                             SymbolExportLevel::C
123                         } else {
124                             SymbolExportLevel::Rust
125                         }
126                     } else {
127                         export_level(scx, def_id)
128                     };
129                     debug!("EXPORTED SYMBOL (re-export): {} ({:?})", name, export_level);
130                     (name, export_level)
131                 })
132                 .collect();
133
134             exports.insert(cnum, crate_exports);
135         }
136
137         return ExportedSymbols {
138             exports: exports
139         };
140
141         fn export_level(scx: &SharedCrateContext,
142                         sym_def_id: DefId)
143                         -> SymbolExportLevel {
144             let attrs = scx.tcx().get_attrs(sym_def_id);
145             if attr::contains_extern_indicator(scx.sess().diagnostic(), &attrs) {
146                 SymbolExportLevel::C
147             } else {
148                 SymbolExportLevel::Rust
149             }
150         }
151     }
152
153     pub fn exported_symbols(&self,
154                             cnum: CrateNum)
155                             -> &[(String, SymbolExportLevel)] {
156         match self.exports.get(&cnum) {
157             Some(exports) => &exports[..],
158             None => &[]
159         }
160     }
161
162     pub fn for_each_exported_symbol<F>(&self,
163                                        cnum: CrateNum,
164                                        export_threshold: SymbolExportLevel,
165                                        mut f: F)
166         where F: FnMut(&str, SymbolExportLevel)
167     {
168         for &(ref name, export_level) in self.exported_symbols(cnum) {
169             if is_below_threshold(export_level, export_threshold) {
170                 f(&name[..], export_level)
171             }
172         }
173     }
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 }
209
210 fn symbol_for_def_id<'a, 'tcx>(scx: &SharedCrateContext<'a, 'tcx>,
211                                def_id: DefId,
212                                symbol_map: &SymbolMap<'tcx>)
213                                -> String {
214     // Just try to look things up in the symbol map. If nothing's there, we
215     // recompute.
216     if let Some(node_id) = scx.tcx().hir.as_local_node_id(def_id) {
217         if let Some(sym) = symbol_map.get(TransItem::Static(node_id)) {
218             return sym.to_owned();
219         }
220     }
221
222     let instance = Instance::mono(scx.tcx(), def_id);
223
224     symbol_map.get(TransItem::Fn(instance))
225               .map(str::to_owned)
226               .unwrap_or_else(|| symbol_name(instance, scx))
227 }