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