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