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