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