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