]> git.lizzy.rs Git - rust.git/blob - src/librustc_metadata/creader.rs
Auto merge of #68448 - maurer:dyn-cdylib, r=alexcrichton
[rust.git] / src / librustc_metadata / creader.rs
1 //! Validates all used crates and extern libraries and loads their metadata
2
3 use crate::locator::{CrateLocator, CratePaths};
4 use crate::rmeta::{CrateDep, CrateMetadata, CrateNumMap, CrateRoot, MetadataBlob};
5
6 use rustc::hir::map::Definitions;
7 use rustc::middle::cstore::DepKind;
8 use rustc::middle::cstore::{CrateSource, ExternCrate, ExternCrateSource, MetadataLoaderDyn};
9 use rustc::session::config;
10 use rustc::session::search_paths::PathKind;
11 use rustc::session::{CrateDisambiguator, Session};
12 use rustc::ty::TyCtxt;
13 use rustc_data_structures::svh::Svh;
14 use rustc_data_structures::sync::Lrc;
15 use rustc_errors::struct_span_err;
16 use rustc_expand::base::SyntaxExtension;
17 use rustc_hir::def_id::{CrateNum, LOCAL_CRATE};
18 use rustc_index::vec::IndexVec;
19 use rustc_span::edition::Edition;
20 use rustc_span::symbol::{sym, Symbol};
21 use rustc_span::{Span, DUMMY_SP};
22 use rustc_target::spec::{PanicStrategy, TargetTriple};
23 use syntax::ast;
24 use syntax::attr;
25 use syntax::expand::allocator::{global_allocator_spans, AllocatorKind};
26
27 use log::{debug, info, log_enabled};
28 use proc_macro::bridge::client::ProcMacro;
29 use std::path::Path;
30 use std::{cmp, fs};
31
32 #[derive(Clone)]
33 pub struct CStore {
34     metas: IndexVec<CrateNum, Option<Lrc<CrateMetadata>>>,
35     injected_panic_runtime: Option<CrateNum>,
36     /// This crate needs an allocator and either provides it itself, or finds it in a dependency.
37     /// If the above is true, then this field denotes the kind of the found allocator.
38     allocator_kind: Option<AllocatorKind>,
39     /// This crate has a `#[global_allocator]` item.
40     has_global_allocator: bool,
41 }
42
43 pub struct CrateLoader<'a> {
44     // Immutable configuration.
45     sess: &'a Session,
46     metadata_loader: &'a MetadataLoaderDyn,
47     local_crate_name: Symbol,
48     // Mutable output.
49     cstore: CStore,
50 }
51
52 pub enum LoadedMacro {
53     MacroDef(ast::Item, Edition),
54     ProcMacro(SyntaxExtension),
55 }
56
57 crate struct Library {
58     pub source: CrateSource,
59     pub metadata: MetadataBlob,
60 }
61
62 enum LoadResult {
63     Previous(CrateNum),
64     Loaded(Library),
65 }
66
67 enum LoadError<'a> {
68     LocatorError(CrateLocator<'a>),
69 }
70
71 impl<'a> LoadError<'a> {
72     fn report(self) -> ! {
73         match self {
74             LoadError::LocatorError(locator) => locator.report_errs(),
75         }
76     }
77 }
78
79 fn dump_crates(cstore: &CStore) {
80     info!("resolved crates:");
81     cstore.iter_crate_data(|cnum, data| {
82         info!("  name: {}", data.name());
83         info!("  cnum: {}", cnum);
84         info!("  hash: {}", data.hash());
85         info!("  reqd: {:?}", data.dep_kind());
86         let CrateSource { dylib, rlib, rmeta } = data.source();
87         dylib.as_ref().map(|dl| info!("  dylib: {}", dl.0.display()));
88         rlib.as_ref().map(|rl| info!("   rlib: {}", rl.0.display()));
89         rmeta.as_ref().map(|rl| info!("   rmeta: {}", rl.0.display()));
90     });
91 }
92
93 impl CStore {
94     crate fn from_tcx(tcx: TyCtxt<'_>) -> &CStore {
95         tcx.cstore_as_any().downcast_ref::<CStore>().expect("`tcx.cstore` is not a `CStore`")
96     }
97
98     fn alloc_new_crate_num(&mut self) -> CrateNum {
99         self.metas.push(None);
100         CrateNum::new(self.metas.len() - 1)
101     }
102
103     crate fn get_crate_data(&self, cnum: CrateNum) -> &CrateMetadata {
104         self.metas[cnum]
105             .as_ref()
106             .unwrap_or_else(|| panic!("Failed to get crate data for {:?}", cnum))
107     }
108
109     fn set_crate_data(&mut self, cnum: CrateNum, data: CrateMetadata) {
110         assert!(self.metas[cnum].is_none(), "Overwriting crate metadata entry");
111         self.metas[cnum] = Some(Lrc::new(data));
112     }
113
114     crate fn iter_crate_data(&self, mut f: impl FnMut(CrateNum, &CrateMetadata)) {
115         for (cnum, data) in self.metas.iter_enumerated() {
116             if let Some(data) = data {
117                 f(cnum, data);
118             }
119         }
120     }
121
122     fn push_dependencies_in_postorder(&self, deps: &mut Vec<CrateNum>, cnum: CrateNum) {
123         if !deps.contains(&cnum) {
124             let data = self.get_crate_data(cnum);
125             for &dep in data.dependencies().iter() {
126                 if dep != cnum {
127                     self.push_dependencies_in_postorder(deps, dep);
128                 }
129             }
130
131             deps.push(cnum);
132         }
133     }
134
135     crate fn crate_dependencies_in_postorder(&self, cnum: CrateNum) -> Vec<CrateNum> {
136         let mut deps = Vec::new();
137         if cnum == LOCAL_CRATE {
138             self.iter_crate_data(|cnum, _| self.push_dependencies_in_postorder(&mut deps, cnum));
139         } else {
140             self.push_dependencies_in_postorder(&mut deps, cnum);
141         }
142         deps
143     }
144
145     fn crate_dependencies_in_reverse_postorder(&self, cnum: CrateNum) -> Vec<CrateNum> {
146         let mut deps = self.crate_dependencies_in_postorder(cnum);
147         deps.reverse();
148         deps
149     }
150
151     crate fn injected_panic_runtime(&self) -> Option<CrateNum> {
152         self.injected_panic_runtime
153     }
154
155     crate fn allocator_kind(&self) -> Option<AllocatorKind> {
156         self.allocator_kind
157     }
158
159     crate fn has_global_allocator(&self) -> bool {
160         self.has_global_allocator
161     }
162 }
163
164 impl<'a> CrateLoader<'a> {
165     pub fn new(
166         sess: &'a Session,
167         metadata_loader: &'a MetadataLoaderDyn,
168         local_crate_name: &str,
169     ) -> Self {
170         CrateLoader {
171             sess,
172             metadata_loader,
173             local_crate_name: Symbol::intern(local_crate_name),
174             cstore: CStore {
175                 // We add an empty entry for LOCAL_CRATE (which maps to zero) in
176                 // order to make array indices in `metas` match with the
177                 // corresponding `CrateNum`. This first entry will always remain
178                 // `None`.
179                 metas: IndexVec::from_elem_n(None, 1),
180                 injected_panic_runtime: None,
181                 allocator_kind: None,
182                 has_global_allocator: false,
183             },
184         }
185     }
186
187     pub fn cstore(&self) -> &CStore {
188         &self.cstore
189     }
190
191     pub fn into_cstore(self) -> CStore {
192         self.cstore
193     }
194
195     fn existing_match(&self, name: Symbol, hash: Option<Svh>, kind: PathKind) -> Option<CrateNum> {
196         let mut ret = None;
197         self.cstore.iter_crate_data(|cnum, data| {
198             if data.name() != name {
199                 return;
200             }
201
202             match hash {
203                 Some(hash) if hash == data.hash() => {
204                     ret = Some(cnum);
205                     return;
206                 }
207                 Some(..) => return,
208                 None => {}
209             }
210
211             // When the hash is None we're dealing with a top-level dependency
212             // in which case we may have a specification on the command line for
213             // this library. Even though an upstream library may have loaded
214             // something of the same name, we have to make sure it was loaded
215             // from the exact same location as well.
216             //
217             // We're also sure to compare *paths*, not actual byte slices. The
218             // `source` stores paths which are normalized which may be different
219             // from the strings on the command line.
220             let source = self.cstore.get_crate_data(cnum).source();
221             if let Some(entry) = self.sess.opts.externs.get(&name.as_str()) {
222                 // Only use `--extern crate_name=path` here, not `--extern crate_name`.
223                 if let Some(mut files) = entry.files() {
224                     if files.any(|l| {
225                         let l = fs::canonicalize(l).ok();
226                         source.dylib.as_ref().map(|p| &p.0) == l.as_ref()
227                             || source.rlib.as_ref().map(|p| &p.0) == l.as_ref()
228                     }) {
229                         ret = Some(cnum);
230                     }
231                 }
232                 return;
233             }
234
235             // Alright, so we've gotten this far which means that `data` has the
236             // right name, we don't have a hash, and we don't have a --extern
237             // pointing for ourselves. We're still not quite yet done because we
238             // have to make sure that this crate was found in the crate lookup
239             // path (this is a top-level dependency) as we don't want to
240             // implicitly load anything inside the dependency lookup path.
241             let prev_kind = source
242                 .dylib
243                 .as_ref()
244                 .or(source.rlib.as_ref())
245                 .or(source.rmeta.as_ref())
246                 .expect("No sources for crate")
247                 .1;
248             if kind.matches(prev_kind) {
249                 ret = Some(cnum);
250             }
251         });
252         return ret;
253     }
254
255     fn verify_no_symbol_conflicts(&self, span: Span, root: &CrateRoot<'_>) {
256         // Check for (potential) conflicts with the local crate
257         if self.local_crate_name == root.name()
258             && self.sess.local_crate_disambiguator() == root.disambiguator()
259         {
260             struct_span_err!(
261                 self.sess,
262                 span,
263                 E0519,
264                 "the current crate is indistinguishable from one of its \
265                          dependencies: it has the same crate-name `{}` and was \
266                          compiled with the same `-C metadata` arguments. This \
267                          will result in symbol conflicts between the two.",
268                 root.name()
269             )
270             .emit()
271         }
272
273         // Check for conflicts with any crate loaded so far
274         self.cstore.iter_crate_data(|_, other| {
275             if other.name() == root.name() && // same crate-name
276                other.disambiguator() == root.disambiguator() &&  // same crate-disambiguator
277                other.hash() != root.hash()
278             {
279                 // but different SVH
280                 struct_span_err!(
281                     self.sess,
282                     span,
283                     E0523,
284                     "found two different crates with name `{}` that are \
285                          not distinguished by differing `-C metadata`. This \
286                          will result in symbol conflicts between the two.",
287                     root.name()
288                 )
289                 .emit();
290             }
291         });
292     }
293
294     fn register_crate(
295         &mut self,
296         host_lib: Option<Library>,
297         root: Option<&CratePaths>,
298         span: Span,
299         lib: Library,
300         dep_kind: DepKind,
301         name: Symbol,
302     ) -> CrateNum {
303         let _prof_timer = self.sess.prof.generic_activity("metadata_register_crate");
304
305         let Library { source, metadata } = lib;
306         let crate_root = metadata.get_root();
307         let host_hash = host_lib.as_ref().map(|lib| lib.metadata.get_root().hash());
308         self.verify_no_symbol_conflicts(span, &crate_root);
309
310         let private_dep =
311             self.sess.opts.externs.get(&name.as_str()).map(|e| e.is_private_dep).unwrap_or(false);
312
313         info!("register crate `{}` (private_dep = {})", crate_root.name(), private_dep);
314
315         // Claim this crate number and cache it
316         let cnum = self.cstore.alloc_new_crate_num();
317
318         // Maintain a reference to the top most crate.
319         // Stash paths for top-most crate locally if necessary.
320         let crate_paths;
321         let root = if let Some(root) = root {
322             root
323         } else {
324             crate_paths = CratePaths::new(crate_root.name(), source.clone());
325             &crate_paths
326         };
327
328         let cnum_map = self.resolve_crate_deps(root, &crate_root, &metadata, cnum, span, dep_kind);
329
330         let raw_proc_macros = if crate_root.is_proc_macro_crate() {
331             let temp_root;
332             let (dlsym_source, dlsym_root) = match &host_lib {
333                 Some(host_lib) => (&host_lib.source, {
334                     temp_root = host_lib.metadata.get_root();
335                     &temp_root
336                 }),
337                 None => (&source, &crate_root),
338             };
339             let dlsym_dylib = dlsym_source.dylib.as_ref().expect("no dylib for a proc-macro crate");
340             Some(self.dlsym_proc_macros(&dlsym_dylib.0, dlsym_root.disambiguator(), span))
341         } else {
342             None
343         };
344
345         self.cstore.set_crate_data(
346             cnum,
347             CrateMetadata::new(
348                 self.sess,
349                 metadata,
350                 crate_root,
351                 raw_proc_macros,
352                 cnum,
353                 cnum_map,
354                 dep_kind,
355                 source,
356                 private_dep,
357                 host_hash,
358             ),
359         );
360
361         cnum
362     }
363
364     fn load_proc_macro<'b>(
365         &self,
366         locator: &mut CrateLocator<'b>,
367         path_kind: PathKind,
368     ) -> Option<(LoadResult, Option<Library>)>
369     where
370         'a: 'b,
371     {
372         // Use a new crate locator so trying to load a proc macro doesn't affect the error
373         // message we emit
374         let mut proc_macro_locator = locator.clone();
375
376         // Try to load a proc macro
377         proc_macro_locator.is_proc_macro = Some(true);
378
379         // Load the proc macro crate for the target
380         let (locator, target_result) = if self.sess.opts.debugging_opts.dual_proc_macros {
381             proc_macro_locator.reset();
382             let result = match self.load(&mut proc_macro_locator)? {
383                 LoadResult::Previous(cnum) => return Some((LoadResult::Previous(cnum), None)),
384                 LoadResult::Loaded(library) => Some(LoadResult::Loaded(library)),
385             };
386             locator.hash = locator.host_hash;
387             // Use the locator when looking for the host proc macro crate, as that is required
388             // so we want it to affect the error message
389             (locator, result)
390         } else {
391             (&mut proc_macro_locator, None)
392         };
393
394         // Load the proc macro crate for the host
395
396         locator.reset();
397         locator.is_proc_macro = Some(true);
398         locator.target = &self.sess.host;
399         locator.triple = TargetTriple::from_triple(config::host_triple());
400         locator.filesearch = self.sess.host_filesearch(path_kind);
401
402         let host_result = self.load(locator)?;
403
404         Some(if self.sess.opts.debugging_opts.dual_proc_macros {
405             let host_result = match host_result {
406                 LoadResult::Previous(..) => {
407                     panic!("host and target proc macros must be loaded in lock-step")
408                 }
409                 LoadResult::Loaded(library) => library,
410             };
411             (target_result.unwrap(), Some(host_result))
412         } else {
413             (host_result, None)
414         })
415     }
416
417     fn resolve_crate<'b>(
418         &'b mut self,
419         name: Symbol,
420         span: Span,
421         dep_kind: DepKind,
422         dep: Option<(&'b CratePaths, &'b CrateDep)>,
423     ) -> CrateNum {
424         self.maybe_resolve_crate(name, span, dep_kind, dep).unwrap_or_else(|err| err.report())
425     }
426
427     fn maybe_resolve_crate<'b>(
428         &'b mut self,
429         name: Symbol,
430         span: Span,
431         mut dep_kind: DepKind,
432         dep: Option<(&'b CratePaths, &'b CrateDep)>,
433     ) -> Result<CrateNum, LoadError<'b>> {
434         info!("resolving crate `{}`", name);
435         let (root, hash, host_hash, extra_filename, path_kind) = match dep {
436             Some((root, dep)) => (
437                 Some(root),
438                 Some(dep.hash),
439                 dep.host_hash,
440                 Some(&dep.extra_filename[..]),
441                 PathKind::Dependency,
442             ),
443             None => (None, None, None, None, PathKind::Crate),
444         };
445         let result = if let Some(cnum) = self.existing_match(name, hash, path_kind) {
446             (LoadResult::Previous(cnum), None)
447         } else {
448             info!("falling back to a load");
449             let mut locator = CrateLocator::new(
450                 self.sess,
451                 self.metadata_loader,
452                 name,
453                 hash,
454                 host_hash,
455                 extra_filename,
456                 false, // is_host
457                 path_kind,
458                 span,
459                 root,
460                 Some(false), // is_proc_macro
461             );
462
463             self.load(&mut locator)
464                 .map(|r| (r, None))
465                 .or_else(|| {
466                     dep_kind = DepKind::UnexportedMacrosOnly;
467                     self.load_proc_macro(&mut locator, path_kind)
468                 })
469                 .ok_or_else(move || LoadError::LocatorError(locator))?
470         };
471
472         match result {
473             (LoadResult::Previous(cnum), None) => {
474                 let data = self.cstore.get_crate_data(cnum);
475                 if data.is_proc_macro_crate() {
476                     dep_kind = DepKind::UnexportedMacrosOnly;
477                 }
478                 data.update_dep_kind(|data_dep_kind| cmp::max(data_dep_kind, dep_kind));
479                 Ok(cnum)
480             }
481             (LoadResult::Loaded(library), host_library) => {
482                 Ok(self.register_crate(host_library, root, span, library, dep_kind, name))
483             }
484             _ => panic!(),
485         }
486     }
487
488     fn load(&self, locator: &mut CrateLocator<'_>) -> Option<LoadResult> {
489         let library = locator.maybe_load_library_crate()?;
490
491         // In the case that we're loading a crate, but not matching
492         // against a hash, we could load a crate which has the same hash
493         // as an already loaded crate. If this is the case prevent
494         // duplicates by just using the first crate.
495         //
496         // Note that we only do this for target triple crates, though, as we
497         // don't want to match a host crate against an equivalent target one
498         // already loaded.
499         let root = library.metadata.get_root();
500         if locator.triple == self.sess.opts.target_triple {
501             let mut result = LoadResult::Loaded(library);
502             self.cstore.iter_crate_data(|cnum, data| {
503                 if data.name() == root.name() && root.hash() == data.hash() {
504                     assert!(locator.hash.is_none());
505                     info!("load success, going to previous cnum: {}", cnum);
506                     result = LoadResult::Previous(cnum);
507                 }
508             });
509             Some(result)
510         } else {
511             Some(LoadResult::Loaded(library))
512         }
513     }
514
515     fn update_extern_crate(&self, cnum: CrateNum, extern_crate: ExternCrate) {
516         let cmeta = self.cstore.get_crate_data(cnum);
517         if cmeta.update_extern_crate(extern_crate) {
518             // Propagate the extern crate info to dependencies if it was updated.
519             let extern_crate = ExternCrate { dependency_of: cnum, ..extern_crate };
520             for &dep_cnum in cmeta.dependencies().iter() {
521                 self.update_extern_crate(dep_cnum, extern_crate);
522             }
523         }
524     }
525
526     // Go through the crate metadata and load any crates that it references
527     fn resolve_crate_deps(
528         &mut self,
529         root: &CratePaths,
530         crate_root: &CrateRoot<'_>,
531         metadata: &MetadataBlob,
532         krate: CrateNum,
533         span: Span,
534         dep_kind: DepKind,
535     ) -> CrateNumMap {
536         debug!("resolving deps of external crate");
537         if crate_root.is_proc_macro_crate() {
538             return CrateNumMap::new();
539         }
540
541         // The map from crate numbers in the crate we're resolving to local crate numbers.
542         // We map 0 and all other holes in the map to our parent crate. The "additional"
543         // self-dependencies should be harmless.
544         std::iter::once(krate)
545             .chain(crate_root.decode_crate_deps(metadata).map(|dep| {
546                 info!(
547                     "resolving dep crate {} hash: `{}` extra filename: `{}`",
548                     dep.name, dep.hash, dep.extra_filename
549                 );
550                 if dep.kind == DepKind::UnexportedMacrosOnly {
551                     return krate;
552                 }
553                 let dep_kind = match dep_kind {
554                     DepKind::MacrosOnly => DepKind::MacrosOnly,
555                     _ => dep.kind,
556                 };
557                 self.resolve_crate(dep.name, span, dep_kind, Some((root, &dep)))
558             }))
559             .collect()
560     }
561
562     fn dlsym_proc_macros(
563         &self,
564         path: &Path,
565         disambiguator: CrateDisambiguator,
566         span: Span,
567     ) -> &'static [ProcMacro] {
568         use crate::dynamic_lib::DynamicLibrary;
569         use std::env;
570
571         // Make sure the path contains a / or the linker will search for it.
572         let path = env::current_dir().unwrap().join(path);
573         let lib = match DynamicLibrary::open(Some(&path)) {
574             Ok(lib) => lib,
575             Err(err) => self.sess.span_fatal(span, &err),
576         };
577
578         let sym = self.sess.generate_proc_macro_decls_symbol(disambiguator);
579         let decls = unsafe {
580             let sym = match lib.symbol(&sym) {
581                 Ok(f) => f,
582                 Err(err) => self.sess.span_fatal(span, &err),
583             };
584             *(sym as *const &[ProcMacro])
585         };
586
587         // Intentionally leak the dynamic library. We can't ever unload it
588         // since the library can make things that will live arbitrarily long.
589         std::mem::forget(lib);
590
591         decls
592     }
593
594     fn inject_panic_runtime(&mut self, krate: &ast::Crate) {
595         // If we're only compiling an rlib, then there's no need to select a
596         // panic runtime, so we just skip this section entirely.
597         let any_non_rlib =
598             self.sess.crate_types.borrow().iter().any(|ct| *ct != config::CrateType::Rlib);
599         if !any_non_rlib {
600             info!("panic runtime injection skipped, only generating rlib");
601             return;
602         }
603
604         // If we need a panic runtime, we try to find an existing one here. At
605         // the same time we perform some general validation of the DAG we've got
606         // going such as ensuring everything has a compatible panic strategy.
607         //
608         // The logic for finding the panic runtime here is pretty much the same
609         // as the allocator case with the only addition that the panic strategy
610         // compilation mode also comes into play.
611         let desired_strategy = self.sess.panic_strategy();
612         let mut runtime_found = false;
613         let mut needs_panic_runtime = attr::contains_name(&krate.attrs, sym::needs_panic_runtime);
614
615         self.cstore.iter_crate_data(|cnum, data| {
616             needs_panic_runtime = needs_panic_runtime || data.needs_panic_runtime();
617             if data.is_panic_runtime() {
618                 // Inject a dependency from all #![needs_panic_runtime] to this
619                 // #![panic_runtime] crate.
620                 self.inject_dependency_if(cnum, "a panic runtime", &|data| {
621                     data.needs_panic_runtime()
622                 });
623                 runtime_found = runtime_found || data.dep_kind() == DepKind::Explicit;
624             }
625         });
626
627         // If an explicitly linked and matching panic runtime was found, or if
628         // we just don't need one at all, then we're done here and there's
629         // nothing else to do.
630         if !needs_panic_runtime || runtime_found {
631             return;
632         }
633
634         // By this point we know that we (a) need a panic runtime and (b) no
635         // panic runtime was explicitly linked. Here we just load an appropriate
636         // default runtime for our panic strategy and then inject the
637         // dependencies.
638         //
639         // We may resolve to an already loaded crate (as the crate may not have
640         // been explicitly linked prior to this) and we may re-inject
641         // dependencies again, but both of those situations are fine.
642         //
643         // Also note that we have yet to perform validation of the crate graph
644         // in terms of everyone has a compatible panic runtime format, that's
645         // performed later as part of the `dependency_format` module.
646         let name = match desired_strategy {
647             PanicStrategy::Unwind => Symbol::intern("panic_unwind"),
648             PanicStrategy::Abort => Symbol::intern("panic_abort"),
649         };
650         info!("panic runtime not found -- loading {}", name);
651
652         let cnum = self.resolve_crate(name, DUMMY_SP, DepKind::Implicit, None);
653         let data = self.cstore.get_crate_data(cnum);
654
655         // Sanity check the loaded crate to ensure it is indeed a panic runtime
656         // and the panic strategy is indeed what we thought it was.
657         if !data.is_panic_runtime() {
658             self.sess.err(&format!("the crate `{}` is not a panic runtime", name));
659         }
660         if data.panic_strategy() != desired_strategy {
661             self.sess.err(&format!(
662                 "the crate `{}` does not have the panic \
663                                     strategy `{}`",
664                 name,
665                 desired_strategy.desc()
666             ));
667         }
668
669         self.cstore.injected_panic_runtime = Some(cnum);
670         self.inject_dependency_if(cnum, "a panic runtime", &|data| data.needs_panic_runtime());
671     }
672
673     fn inject_profiler_runtime(&mut self) {
674         if self.sess.opts.debugging_opts.profile || self.sess.opts.cg.profile_generate.enabled() {
675             info!("loading profiler");
676
677             let name = Symbol::intern("profiler_builtins");
678             let cnum = self.resolve_crate(name, DUMMY_SP, DepKind::Implicit, None);
679             let data = self.cstore.get_crate_data(cnum);
680
681             // Sanity check the loaded crate to ensure it is indeed a profiler runtime
682             if !data.is_profiler_runtime() {
683                 self.sess.err(&format!(
684                     "the crate `profiler_builtins` is not \
685                                         a profiler runtime"
686                 ));
687             }
688         }
689     }
690
691     fn inject_allocator_crate(&mut self, krate: &ast::Crate) {
692         self.cstore.has_global_allocator = match &*global_allocator_spans(krate) {
693             [span1, span2, ..] => {
694                 self.sess
695                     .struct_span_err(*span2, "cannot define multiple global allocators")
696                     .span_label(*span2, "cannot define a new global allocator")
697                     .span_label(*span1, "previous global allocator is defined here")
698                     .emit();
699                 true
700             }
701             spans => !spans.is_empty(),
702         };
703
704         // Check to see if we actually need an allocator. This desire comes
705         // about through the `#![needs_allocator]` attribute and is typically
706         // written down in liballoc.
707         let mut needs_allocator = attr::contains_name(&krate.attrs, sym::needs_allocator);
708         self.cstore.iter_crate_data(|_, data| {
709             needs_allocator = needs_allocator || data.needs_allocator();
710         });
711         if !needs_allocator {
712             return;
713         }
714
715         // At this point we've determined that we need an allocator. Let's see
716         // if our compilation session actually needs an allocator based on what
717         // we're emitting.
718         let all_rlib = self.sess.crate_types.borrow().iter().all(|ct| match *ct {
719             config::CrateType::Rlib => true,
720             _ => false,
721         });
722         if all_rlib {
723             return;
724         }
725
726         // Ok, we need an allocator. Not only that but we're actually going to
727         // create an artifact that needs one linked in. Let's go find the one
728         // that we're going to link in.
729         //
730         // First up we check for global allocators. Look at the crate graph here
731         // and see what's a global allocator, including if we ourselves are a
732         // global allocator.
733         let mut global_allocator =
734             self.cstore.has_global_allocator.then(|| Symbol::intern("this crate"));
735         self.cstore.iter_crate_data(|_, data| {
736             if !data.has_global_allocator() {
737                 return;
738             }
739             match global_allocator {
740                 Some(other_crate) => {
741                     self.sess.err(&format!(
742                         "the `#[global_allocator]` in {} \
743                                             conflicts with global \
744                                             allocator in: {}",
745                         other_crate,
746                         data.name()
747                     ));
748                 }
749                 None => global_allocator = Some(data.name()),
750             }
751         });
752         if global_allocator.is_some() {
753             self.cstore.allocator_kind = Some(AllocatorKind::Global);
754             return;
755         }
756
757         // Ok we haven't found a global allocator but we still need an
758         // allocator. At this point our allocator request is typically fulfilled
759         // by the standard library, denoted by the `#![default_lib_allocator]`
760         // attribute.
761         let mut has_default = attr::contains_name(&krate.attrs, sym::default_lib_allocator);
762         self.cstore.iter_crate_data(|_, data| {
763             if data.has_default_lib_allocator() {
764                 has_default = true;
765             }
766         });
767
768         if !has_default {
769             self.sess.err(
770                 "no global memory allocator found but one is \
771                            required; link to std or \
772                            add `#[global_allocator]` to a static item \
773                            that implements the GlobalAlloc trait.",
774             );
775         }
776         self.cstore.allocator_kind = Some(AllocatorKind::Default);
777     }
778
779     fn inject_dependency_if(
780         &self,
781         krate: CrateNum,
782         what: &str,
783         needs_dep: &dyn Fn(&CrateMetadata) -> bool,
784     ) {
785         // don't perform this validation if the session has errors, as one of
786         // those errors may indicate a circular dependency which could cause
787         // this to stack overflow.
788         if self.sess.has_errors() {
789             return;
790         }
791
792         // Before we inject any dependencies, make sure we don't inject a
793         // circular dependency by validating that this crate doesn't
794         // transitively depend on any crates satisfying `needs_dep`.
795         for dep in self.cstore.crate_dependencies_in_reverse_postorder(krate) {
796             let data = self.cstore.get_crate_data(dep);
797             if needs_dep(&data) {
798                 self.sess.err(&format!(
799                     "the crate `{}` cannot depend \
800                                         on a crate that needs {}, but \
801                                         it depends on `{}`",
802                     self.cstore.get_crate_data(krate).name(),
803                     what,
804                     data.name()
805                 ));
806             }
807         }
808
809         // All crates satisfying `needs_dep` do not explicitly depend on the
810         // crate provided for this compile, but in order for this compilation to
811         // be successfully linked we need to inject a dependency (to order the
812         // crates on the command line correctly).
813         self.cstore.iter_crate_data(|cnum, data| {
814             if !needs_dep(data) {
815                 return;
816             }
817
818             info!("injecting a dep from {} to {}", cnum, krate);
819             data.add_dependency(krate);
820         });
821     }
822
823     pub fn postprocess(&mut self, krate: &ast::Crate) {
824         self.inject_profiler_runtime();
825         self.inject_allocator_crate(krate);
826         self.inject_panic_runtime(krate);
827
828         if log_enabled!(log::Level::Info) {
829             dump_crates(&self.cstore);
830         }
831     }
832
833     pub fn process_extern_crate(
834         &mut self,
835         item: &ast::Item,
836         definitions: &Definitions,
837     ) -> CrateNum {
838         match item.kind {
839             ast::ItemKind::ExternCrate(orig_name) => {
840                 debug!(
841                     "resolving extern crate stmt. ident: {} orig_name: {:?}",
842                     item.ident, orig_name
843                 );
844                 let name = match orig_name {
845                     Some(orig_name) => {
846                         crate::validate_crate_name(
847                             Some(self.sess),
848                             &orig_name.as_str(),
849                             Some(item.span),
850                         );
851                         orig_name
852                     }
853                     None => item.ident.name,
854                 };
855                 let dep_kind = if attr::contains_name(&item.attrs, sym::no_link) {
856                     DepKind::UnexportedMacrosOnly
857                 } else {
858                     DepKind::Explicit
859                 };
860
861                 let cnum = self.resolve_crate(name, item.span, dep_kind, None);
862
863                 let def_id = definitions.opt_local_def_id(item.id).unwrap();
864                 let path_len = definitions.def_path(def_id.index).data.len();
865                 self.update_extern_crate(
866                     cnum,
867                     ExternCrate {
868                         src: ExternCrateSource::Extern(def_id),
869                         span: item.span,
870                         path_len,
871                         dependency_of: LOCAL_CRATE,
872                     },
873                 );
874                 cnum
875             }
876             _ => bug!(),
877         }
878     }
879
880     pub fn process_path_extern(&mut self, name: Symbol, span: Span) -> CrateNum {
881         let cnum = self.resolve_crate(name, span, DepKind::Explicit, None);
882
883         self.update_extern_crate(
884             cnum,
885             ExternCrate {
886                 src: ExternCrateSource::Path,
887                 span,
888                 // to have the least priority in `update_extern_crate`
889                 path_len: usize::max_value(),
890                 dependency_of: LOCAL_CRATE,
891             },
892         );
893
894         cnum
895     }
896
897     pub fn maybe_process_path_extern(&mut self, name: Symbol, span: Span) -> Option<CrateNum> {
898         self.maybe_resolve_crate(name, span, DepKind::Explicit, None).ok()
899     }
900 }