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