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