creader.rs 33.1 KB
Newer Older
1
//! Validates all used crates and extern libraries and loads their metadata
2

3
use crate::locator::{CrateLocator, CratePaths};
M
Mark Rousskov 已提交
4
use crate::rmeta::{CrateDep, CrateMetadata, CrateNumMap, CrateRoot, MetadataBlob};
5

M
Mark Rousskov 已提交
6 7 8
use rustc::hir::map::Definitions;
use rustc::middle::cstore::DepKind;
use rustc::middle::cstore::{CrateSource, ExternCrate, ExternCrateSource, MetadataLoaderDyn};
9
use rustc::session::config;
M
Mark Rousskov 已提交
10 11 12
use rustc::session::search_paths::PathKind;
use rustc::session::{CrateDisambiguator, Session};
use rustc::ty::TyCtxt;
13 14 15
use rustc_ast::ast;
use rustc_ast::attr;
use rustc_ast::expand::allocator::{global_allocator_spans, AllocatorKind};
16
use rustc_data_structures::svh::Svh;
17
use rustc_data_structures::sync::Lrc;
18 19
use rustc_errors::struct_span_err;
use rustc_expand::base::SyntaxExtension;
20
use rustc_hir::def_id::{CrateNum, LOCAL_CRATE};
21
use rustc_index::vec::IndexVec;
22
use rustc_span::edition::Edition;
23
use rustc_span::symbol::{sym, Symbol};
24
use rustc_span::{Span, DUMMY_SP};
25
use rustc_target::spec::{PanicStrategy, TargetTriple};
26

27 28 29 30
use log::{debug, info, log_enabled};
use proc_macro::bridge::client::ProcMacro;
use std::path::Path;
use std::{cmp, fs};
31

32 33 34
#[derive(Clone)]
pub struct CStore {
    metas: IndexVec<CrateNum, Option<Lrc<CrateMetadata>>>,
35
    injected_panic_runtime: Option<CrateNum>,
36 37
    /// This crate needs an allocator and either provides it itself, or finds it in a dependency.
    /// If the above is true, then this field denotes the kind of the found allocator.
38
    allocator_kind: Option<AllocatorKind>,
39 40
    /// This crate has a `#[global_allocator]` item.
    has_global_allocator: bool,
41 42
}

43
pub struct CrateLoader<'a> {
44
    // Immutable configuration.
45
    sess: &'a Session,
46
    metadata_loader: &'a MetadataLoaderDyn,
47
    local_crate_name: Symbol,
48 49
    // Mutable output.
    cstore: CStore,
50 51
}

52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
pub enum LoadedMacro {
    MacroDef(ast::Item, Edition),
    ProcMacro(SyntaxExtension),
}

crate struct Library {
    pub source: CrateSource,
    pub metadata: MetadataBlob,
}

enum LoadResult {
    Previous(CrateNum),
    Loaded(Library),
}

enum LoadError<'a> {
    LocatorError(CrateLocator<'a>),
}

impl<'a> LoadError<'a> {
    fn report(self) -> ! {
        match self {
            LoadError::LocatorError(locator) => locator.report_errs(),
        }
    }
}

79 80 81 82 83 84 85 86 87 88 89 90 91 92 93
/// A reference to `CrateMetadata` that can also give access to whole crate store when necessary.
#[derive(Clone, Copy)]
crate struct CrateMetadataRef<'a> {
    pub cdata: &'a CrateMetadata,
    pub cstore: &'a CStore,
}

impl std::ops::Deref for CrateMetadataRef<'_> {
    type Target = CrateMetadata;

    fn deref(&self) -> &Self::Target {
        self.cdata
    }
}

94
fn dump_crates(cstore: &CStore) {
95
    info!("resolved crates:");
96
    cstore.iter_crate_data(|cnum, data| {
97
        info!("  name: {}", data.name());
98
        info!("  cnum: {}", cnum);
99
        info!("  hash: {}", data.hash());
100
        info!("  reqd: {:?}", data.dep_kind());
101 102
        let CrateSource { dylib, rlib, rmeta } = data.source();
        dylib.as_ref().map(|dl| info!("  dylib: {}", dl.0.display()));
M
Mark Rousskov 已提交
103
        rlib.as_ref().map(|rl| info!("   rlib: {}", rl.0.display()));
104
        rmeta.as_ref().map(|rl| info!("   rmeta: {}", rl.0.display()));
N
Nick Cameron 已提交
105
    });
B
Brian Anderson 已提交
106 107
}

108
impl CStore {
109 110 111 112
    crate fn from_tcx(tcx: TyCtxt<'_>) -> &CStore {
        tcx.cstore_as_any().downcast_ref::<CStore>().expect("`tcx.cstore` is not a `CStore`")
    }

113
    fn alloc_new_crate_num(&mut self) -> CrateNum {
114 115 116
        self.metas.push(None);
        CrateNum::new(self.metas.len() - 1)
    }
117

118 119
    crate fn get_crate_data(&self, cnum: CrateNum) -> CrateMetadataRef<'_> {
        let cdata = self.metas[cnum]
M
Mark Rousskov 已提交
120
            .as_ref()
121 122
            .unwrap_or_else(|| panic!("Failed to get crate data for {:?}", cnum));
        CrateMetadataRef { cdata, cstore: self }
123
    }
124

125
    fn set_crate_data(&mut self, cnum: CrateNum, data: CrateMetadata) {
126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147
        assert!(self.metas[cnum].is_none(), "Overwriting crate metadata entry");
        self.metas[cnum] = Some(Lrc::new(data));
    }

    crate fn iter_crate_data(&self, mut f: impl FnMut(CrateNum, &CrateMetadata)) {
        for (cnum, data) in self.metas.iter_enumerated() {
            if let Some(data) = data {
                f(cnum, data);
            }
        }
    }

    fn push_dependencies_in_postorder(&self, deps: &mut Vec<CrateNum>, cnum: CrateNum) {
        if !deps.contains(&cnum) {
            let data = self.get_crate_data(cnum);
            for &dep in data.dependencies().iter() {
                if dep != cnum {
                    self.push_dependencies_in_postorder(deps, dep);
                }
            }

            deps.push(cnum);
148 149
        }
    }
150 151 152 153 154 155 156 157 158 159 160

    crate fn crate_dependencies_in_postorder(&self, cnum: CrateNum) -> Vec<CrateNum> {
        let mut deps = Vec::new();
        if cnum == LOCAL_CRATE {
            self.iter_crate_data(|cnum, _| self.push_dependencies_in_postorder(&mut deps, cnum));
        } else {
            self.push_dependencies_in_postorder(&mut deps, cnum);
        }
        deps
    }

161
    fn crate_dependencies_in_reverse_postorder(&self, cnum: CrateNum) -> Vec<CrateNum> {
162 163 164 165
        let mut deps = self.crate_dependencies_in_postorder(cnum);
        deps.reverse();
        deps
    }
166 167 168 169 170 171 172 173

    crate fn injected_panic_runtime(&self) -> Option<CrateNum> {
        self.injected_panic_runtime
    }

    crate fn allocator_kind(&self) -> Option<AllocatorKind> {
        self.allocator_kind
    }
174 175 176 177

    crate fn has_global_allocator(&self) -> bool {
        self.has_global_allocator
    }
178 179
}

180
impl<'a> CrateLoader<'a> {
181 182 183 184 185
    pub fn new(
        sess: &'a Session,
        metadata_loader: &'a MetadataLoaderDyn,
        local_crate_name: &str,
    ) -> Self {
186
        CrateLoader {
187
            sess,
188
            metadata_loader,
189
            local_crate_name: Symbol::intern(local_crate_name),
190 191 192 193 194 195 196 197
            cstore: CStore {
                // We add an empty entry for LOCAL_CRATE (which maps to zero) in
                // order to make array indices in `metas` match with the
                // corresponding `CrateNum`. This first entry will always remain
                // `None`.
                metas: IndexVec::from_elem_n(None, 1),
                injected_panic_runtime: None,
                allocator_kind: None,
198
                has_global_allocator: false,
M
Mark Rousskov 已提交
199
            },
K
Keegan McAllister 已提交
200 201 202
        }
    }

203 204 205 206 207 208 209 210
    pub fn cstore(&self) -> &CStore {
        &self.cstore
    }

    pub fn into_cstore(self) -> CStore {
        self.cstore
    }

211
    fn existing_match(&self, name: Symbol, hash: Option<Svh>, kind: PathKind) -> Option<CrateNum> {
212
        let mut ret = None;
A
Ariel Ben-Yehuda 已提交
213
        self.cstore.iter_crate_data(|cnum, data| {
M
Mark Rousskov 已提交
214 215 216
            if data.name() != name {
                return;
            }
217 218

            match hash {
M
Mark Rousskov 已提交
219 220 221 222
                Some(hash) if hash == data.hash() => {
                    ret = Some(cnum);
                    return;
                }
223 224 225 226
                Some(..) => return,
                None => {}
            }

227 228 229 230 231
            // When the hash is None we're dealing with a top-level dependency
            // in which case we may have a specification on the command line for
            // this library. Even though an upstream library may have loaded
            // something of the same name, we have to make sure it was loaded
            // from the exact same location as well.
232 233 234 235
            //
            // We're also sure to compare *paths*, not actual byte slices. The
            // `source` stores paths which are normalized which may be different
            // from the strings on the command line.
236
            let source = self.cstore.get_crate_data(cnum).cdata.source();
237
            if let Some(entry) = self.sess.opts.externs.get(&name.as_str()) {
238
                // Only use `--extern crate_name=path` here, not `--extern crate_name`.
E
Eric Huss 已提交
239 240 241
                if let Some(mut files) = entry.files() {
                    if files.any(|l| {
                        let l = fs::canonicalize(l).ok();
M
Mark Rousskov 已提交
242 243
                        source.dylib.as_ref().map(|p| &p.0) == l.as_ref()
                            || source.rlib.as_ref().map(|p| &p.0) == l.as_ref()
E
Eric Huss 已提交
244 245 246
                    }) {
                        ret = Some(cnum);
                    }
247
                }
M
Mark Rousskov 已提交
248
                return;
249 250 251 252 253 254 255 256
            }

            // Alright, so we've gotten this far which means that `data` has the
            // right name, we don't have a hash, and we don't have a --extern
            // pointing for ourselves. We're still not quite yet done because we
            // have to make sure that this crate was found in the crate lookup
            // path (this is a top-level dependency) as we don't want to
            // implicitly load anything inside the dependency lookup path.
M
Mark Rousskov 已提交
257 258 259 260 261 262 263
            let prev_kind = source
                .dylib
                .as_ref()
                .or(source.rlib.as_ref())
                .or(source.rmeta.as_ref())
                .expect("No sources for crate")
                .1;
V
Vadim Petrochenkov 已提交
264
            if kind.matches(prev_kind) {
265
                ret = Some(cnum);
266 267 268 269
            }
        });
        return ret;
    }
270

M
Mark Rousskov 已提交
271
    fn verify_no_symbol_conflicts(&self, span: Span, root: &CrateRoot<'_>) {
272
        // Check for (potential) conflicts with the local crate
M
Mark Rousskov 已提交
273 274 275
        if self.local_crate_name == root.name()
            && self.sess.local_crate_disambiguator() == root.disambiguator()
        {
276
            struct_span_err!(
M
Mark Rousskov 已提交
277 278 279 280
                self.sess,
                span,
                E0519,
                "the current crate is indistinguishable from one of its \
281 282 283
                         dependencies: it has the same crate-name `{}` and was \
                         compiled with the same `-C metadata` arguments. This \
                         will result in symbol conflicts between the two.",
M
Mark Rousskov 已提交
284 285
                root.name()
            )
286
            .emit()
287 288 289 290
        }

        // Check for conflicts with any crate loaded so far
        self.cstore.iter_crate_data(|_, other| {
291 292
            if other.name() == root.name() && // same crate-name
               other.disambiguator() == root.disambiguator() &&  // same crate-disambiguator
M
Mark Rousskov 已提交
293 294 295
               other.hash() != root.hash()
            {
                // but different SVH
296
                struct_span_err!(
M
Mark Rousskov 已提交
297 298 299 300
                    self.sess,
                    span,
                    E0523,
                    "found two different crates with name `{}` that are \
301 302
                         not distinguished by differing `-C metadata`. This \
                         will result in symbol conflicts between the two.",
M
Mark Rousskov 已提交
303 304
                    root.name()
                )
305
                .emit();
306 307 308 309
            }
        });
    }

310
    fn register_crate(
311
        &mut self,
312
        host_lib: Option<Library>,
313
        root: Option<&CratePaths>,
314 315
        span: Span,
        lib: Library,
316
        dep_kind: DepKind,
M
Mark Rousskov 已提交
317
        name: Symbol,
318
    ) -> CrateNum {
319
        let _prof_timer = self.sess.prof.generic_activity("metadata_register_crate");
320

321 322
        let Library { source, metadata } = lib;
        let crate_root = metadata.get_root();
323
        let host_hash = host_lib.as_ref().map(|lib| lib.metadata.get_root().hash());
324
        self.verify_no_symbol_conflicts(span, &crate_root);
325

M
Mark Rousskov 已提交
326 327
        let private_dep =
            self.sess.opts.externs.get(&name.as_str()).map(|e| e.is_private_dep).unwrap_or(false);
328

329
        info!("register crate `{}` (private_dep = {})", crate_root.name(), private_dep);
330

331
        // Claim this crate number and cache it
332
        let cnum = self.cstore.alloc_new_crate_num();
333

334
        // Maintain a reference to the top most crate.
335
        // Stash paths for top-most crate locally if necessary.
336 337 338 339
        let crate_paths;
        let root = if let Some(root) = root {
            root
        } else {
340
            crate_paths = CratePaths::new(crate_root.name(), source.clone());
341
            &crate_paths
342
        };
343

344
        let cnum_map = self.resolve_crate_deps(root, &crate_root, &metadata, cnum, span, dep_kind);
345

346
        let raw_proc_macros = if crate_root.is_proc_macro_crate() {
347
            let temp_root;
348
            let (dlsym_source, dlsym_root) = match &host_lib {
M
Mark Rousskov 已提交
349 350 351 352
                Some(host_lib) => (&host_lib.source, {
                    temp_root = host_lib.metadata.get_root();
                    &temp_root
                }),
353
                None => (&source, &crate_root),
354
            };
355
            let dlsym_dylib = dlsym_source.dylib.as_ref().expect("no dylib for a proc-macro crate");
356
            Some(self.dlsym_proc_macros(&dlsym_dylib.0, dlsym_root.disambiguator(), span))
357 358 359
        } else {
            None
        };
360

M
Mark Rousskov 已提交
361
        self.cstore.set_crate_data(
362
            cnum,
M
Mark Rousskov 已提交
363 364 365 366 367 368 369 370 371 372 373 374 375
            CrateMetadata::new(
                self.sess,
                metadata,
                crate_root,
                raw_proc_macros,
                cnum,
                cnum_map,
                dep_kind,
                source,
                private_dep,
                host_hash,
            ),
        );
376

377
        cnum
378
    }
379

380
    fn load_proc_macro<'b>(
381
        &self,
382
        locator: &mut CrateLocator<'b>,
383
        path_kind: PathKind,
384 385 386 387
    ) -> Option<(LoadResult, Option<Library>)>
    where
        'a: 'b,
    {
388
        // Use a new crate locator so trying to load a proc macro doesn't affect the error
389
        // message we emit
390
        let mut proc_macro_locator = locator.clone();
391 392 393 394 395 396 397 398 399

        // Try to load a proc macro
        proc_macro_locator.is_proc_macro = Some(true);

        // Load the proc macro crate for the target
        let (locator, target_result) = if self.sess.opts.debugging_opts.dual_proc_macros {
            proc_macro_locator.reset();
            let result = match self.load(&mut proc_macro_locator)? {
                LoadResult::Previous(cnum) => return Some((LoadResult::Previous(cnum), None)),
M
Mark Rousskov 已提交
400
                LoadResult::Loaded(library) => Some(LoadResult::Loaded(library)),
401
            };
402 403
            locator.hash = locator.host_hash;
            // Use the locator when looking for the host proc macro crate, as that is required
404
            // so we want it to affect the error message
405
            (locator, result)
406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424
        } else {
            (&mut proc_macro_locator, None)
        };

        // Load the proc macro crate for the host

        locator.reset();
        locator.is_proc_macro = Some(true);
        locator.target = &self.sess.host;
        locator.triple = TargetTriple::from_triple(config::host_triple());
        locator.filesearch = self.sess.host_filesearch(path_kind);

        let host_result = self.load(locator)?;

        Some(if self.sess.opts.debugging_opts.dual_proc_macros {
            let host_result = match host_result {
                LoadResult::Previous(..) => {
                    panic!("host and target proc macros must be loaded in lock-step")
                }
M
Mark Rousskov 已提交
425
                LoadResult::Loaded(library) => library,
426 427 428 429 430 431 432
            };
            (target_result.unwrap(), Some(host_result))
        } else {
            (host_result, None)
        })
    }

433
    fn resolve_crate<'b>(
434
        &'b mut self,
435 436
        name: Symbol,
        span: Span,
437 438
        dep_kind: DepKind,
        dep: Option<(&'b CratePaths, &'b CrateDep)>,
439
    ) -> CrateNum {
440 441 442 443
        self.maybe_resolve_crate(name, span, dep_kind, dep).unwrap_or_else(|err| err.report())
    }

    fn maybe_resolve_crate<'b>(
444
        &'b mut self,
445 446
        name: Symbol,
        span: Span,
447
        mut dep_kind: DepKind,
448
        dep: Option<(&'b CratePaths, &'b CrateDep)>,
449
    ) -> Result<CrateNum, LoadError<'b>> {
450
        info!("resolving crate `{}`", name);
M
msizanoen 已提交
451 452 453
        let (root, hash, host_hash, extra_filename, path_kind) = match dep {
            Some((root, dep)) => (
                Some(root),
454 455
                Some(dep.hash),
                dep.host_hash,
M
msizanoen 已提交
456
                Some(&dep.extra_filename[..]),
457
                PathKind::Dependency,
M
msizanoen 已提交
458 459
            ),
            None => (None, None, None, None, PathKind::Crate),
460
        };
461
        let result = if let Some(cnum) = self.existing_match(name, hash, path_kind) {
462
            (LoadResult::Previous(cnum), None)
463 464
        } else {
            info!("falling back to a load");
465 466 467 468
            let mut locator = CrateLocator::new(
                self.sess,
                self.metadata_loader,
                name,
B
bjorn3 已提交
469
                hash,
M
msizanoen 已提交
470
                host_hash,
B
bjorn3 已提交
471
                extra_filename,
472 473 474
                false, // is_host
                path_kind,
                span,
J
John Kåre Alsaker 已提交
475
                root,
476 477
                Some(false), // is_proc_macro
            );
J
John Kåre Alsaker 已提交
478

M
Mark Rousskov 已提交
479 480 481
            self.load(&mut locator)
                .map(|r| (r, None))
                .or_else(|| {
482
                    dep_kind = DepKind::MacrosOnly;
M
Mark Rousskov 已提交
483 484 485
                    self.load_proc_macro(&mut locator, path_kind)
                })
                .ok_or_else(move || LoadError::LocatorError(locator))?
486 487 488
        };

        match result {
489
            (LoadResult::Previous(cnum), None) => {
A
Ariel Ben-Yehuda 已提交
490
                let data = self.cstore.get_crate_data(cnum);
491
                if data.is_proc_macro_crate() {
492
                    dep_kind = DepKind::MacrosOnly;
493
                }
494
                data.update_dep_kind(|data_dep_kind| cmp::max(data_dep_kind, dep_kind));
495
                Ok(cnum)
496
            }
497
            (LoadResult::Loaded(library), host_library) => {
498
                Ok(self.register_crate(host_library, root, span, library, dep_kind, name))
499
            }
M
Mark Rousskov 已提交
500
            _ => panic!(),
501
        }
502
    }
503

504 505
    fn load(&self, locator: &mut CrateLocator<'_>) -> Option<LoadResult> {
        let library = locator.maybe_load_library_crate()?;
506 507 508 509 510 511 512 513 514

        // In the case that we're loading a crate, but not matching
        // against a hash, we could load a crate which has the same hash
        // as an already loaded crate. If this is the case prevent
        // duplicates by just using the first crate.
        //
        // Note that we only do this for target triple crates, though, as we
        // don't want to match a host crate against an equivalent target one
        // already loaded.
515
        let root = library.metadata.get_root();
516
        if locator.triple == self.sess.opts.target_triple {
517 518
            let mut result = LoadResult::Loaded(library);
            self.cstore.iter_crate_data(|cnum, data| {
519
                if data.name() == root.name() && root.hash() == data.hash() {
520
                    assert!(locator.hash.is_none());
521
                    info!("load success, going to previous cnum: {}", cnum);
522 523 524 525 526 527 528 529 530
                    result = LoadResult::Previous(cnum);
                }
            });
            Some(result)
        } else {
            Some(LoadResult::Loaded(library))
        }
    }

531
    fn update_extern_crate(&self, cnum: CrateNum, extern_crate: ExternCrate) {
532
        let cmeta = self.cstore.get_crate_data(cnum);
533
        if cmeta.update_extern_crate(extern_crate) {
534 535
            // Propagate the extern crate info to dependencies if it was updated.
            let extern_crate = ExternCrate { dependency_of: cnum, ..extern_crate };
536
            for &dep_cnum in cmeta.dependencies().iter() {
537
                self.update_extern_crate(dep_cnum, extern_crate);
538
            }
539 540 541
        }
    }

542
    // Go through the crate metadata and load any crates that it references
M
Mark Rousskov 已提交
543 544 545 546 547 548 549 550 551
    fn resolve_crate_deps(
        &mut self,
        root: &CratePaths,
        crate_root: &CrateRoot<'_>,
        metadata: &MetadataBlob,
        krate: CrateNum,
        span: Span,
        dep_kind: DepKind,
    ) -> CrateNumMap {
552
        debug!("resolving deps of external crate");
553
        if crate_root.is_proc_macro_crate() {
554
            return CrateNumMap::new();
555 556
        }

557 558 559
        // The map from crate numbers in the crate we're resolving to local crate numbers.
        // We map 0 and all other holes in the map to our parent crate. The "additional"
        // self-dependencies should be harmless.
M
Mark Rousskov 已提交
560 561 562 563 564 565 566 567 568 569 570 571 572
        std::iter::once(krate)
            .chain(crate_root.decode_crate_deps(metadata).map(|dep| {
                info!(
                    "resolving dep crate {} hash: `{}` extra filename: `{}`",
                    dep.name, dep.hash, dep.extra_filename
                );
                let dep_kind = match dep_kind {
                    DepKind::MacrosOnly => DepKind::MacrosOnly,
                    _ => dep.kind,
                };
                self.resolve_crate(dep.name, span, dep_kind, Some((root, &dep)))
            }))
            .collect()
573
    }
574

M
Mark Rousskov 已提交
575 576 577 578 579
    fn dlsym_proc_macros(
        &self,
        path: &Path,
        disambiguator: CrateDisambiguator,
        span: Span,
580
    ) -> &'static [ProcMacro] {
T
Taiki Endo 已提交
581
        use crate::dynamic_lib::DynamicLibrary;
M
Mark Rousskov 已提交
582
        use std::env;
583 584 585 586 587

        // Make sure the path contains a / or the linker will search for it.
        let path = env::current_dir().unwrap().join(path);
        let lib = match DynamicLibrary::open(Some(&path)) {
            Ok(lib) => lib,
588
            Err(err) => self.sess.span_fatal(span, &err),
589 590
        };

591
        let sym = self.sess.generate_proc_macro_decls_symbol(disambiguator);
592
        let decls = unsafe {
593 594
            let sym = match lib.symbol(&sym) {
                Ok(f) => f,
595
                Err(err) => self.sess.span_fatal(span, &err),
596
            };
597
            *(sym as *const &[ProcMacro])
598 599 600 601
        };

        // Intentionally leak the dynamic library. We can't ever unload it
        // since the library can make things that will live arbitrarily long.
602
        std::mem::forget(lib);
603

604
        decls
605
    }
606

607
    fn inject_panic_runtime(&mut self, krate: &ast::Crate) {
608 609
        // If we're only compiling an rlib, then there's no need to select a
        // panic runtime, so we just skip this section entirely.
M
Mark Rousskov 已提交
610 611
        let any_non_rlib =
            self.sess.crate_types.borrow().iter().any(|ct| *ct != config::CrateType::Rlib);
612 613
        if !any_non_rlib {
            info!("panic runtime injection skipped, only generating rlib");
M
Mark Rousskov 已提交
614
            return;
615 616 617 618 619 620 621 622 623
        }

        // If we need a panic runtime, we try to find an existing one here. At
        // the same time we perform some general validation of the DAG we've got
        // going such as ensuring everything has a compatible panic strategy.
        //
        // The logic for finding the panic runtime here is pretty much the same
        // as the allocator case with the only addition that the panic strategy
        // compilation mode also comes into play.
624
        let desired_strategy = self.sess.panic_strategy();
625
        let mut runtime_found = false;
M
Mark Rousskov 已提交
626
        let mut needs_panic_runtime = attr::contains_name(&krate.attrs, sym::needs_panic_runtime);
627

628
        self.cstore.iter_crate_data(|cnum, data| {
629 630
            needs_panic_runtime = needs_panic_runtime || data.needs_panic_runtime();
            if data.is_panic_runtime() {
631 632
                // Inject a dependency from all #![needs_panic_runtime] to this
                // #![panic_runtime] crate.
M
Mark Rousskov 已提交
633 634 635
                self.inject_dependency_if(cnum, "a panic runtime", &|data| {
                    data.needs_panic_runtime()
                });
636
                runtime_found = runtime_found || data.dep_kind() == DepKind::Explicit;
637 638 639 640 641 642 643
            }
        });

        // If an explicitly linked and matching panic runtime was found, or if
        // we just don't need one at all, then we're done here and there's
        // nothing else to do.
        if !needs_panic_runtime || runtime_found {
M
Mark Rousskov 已提交
644
            return;
645 646 647 648 649 650 651 652 653 654 655 656 657 658 659
        }

        // By this point we know that we (a) need a panic runtime and (b) no
        // panic runtime was explicitly linked. Here we just load an appropriate
        // default runtime for our panic strategy and then inject the
        // dependencies.
        //
        // We may resolve to an already loaded crate (as the crate may not have
        // been explicitly linked prior to this) and we may re-inject
        // dependencies again, but both of those situations are fine.
        //
        // Also note that we have yet to perform validation of the crate graph
        // in terms of everyone has a compatible panic runtime format, that's
        // performed later as part of the `dependency_format` module.
        let name = match desired_strategy {
660 661
            PanicStrategy::Unwind => Symbol::intern("panic_unwind"),
            PanicStrategy::Abort => Symbol::intern("panic_abort"),
662 663 664
        };
        info!("panic runtime not found -- loading {}", name);

665 666
        let cnum = self.resolve_crate(name, DUMMY_SP, DepKind::Implicit, None);
        let data = self.cstore.get_crate_data(cnum);
667 668 669

        // Sanity check the loaded crate to ensure it is indeed a panic runtime
        // and the panic strategy is indeed what we thought it was.
670
        if !data.is_panic_runtime() {
M
Mark Rousskov 已提交
671
            self.sess.err(&format!("the crate `{}` is not a panic runtime", name));
672
        }
673
        if data.panic_strategy() != desired_strategy {
M
Mark Rousskov 已提交
674 675
            self.sess.err(&format!(
                "the crate `{}` does not have the panic \
676
                                    strategy `{}`",
M
Mark Rousskov 已提交
677 678 679
                name,
                desired_strategy.desc()
            ));
680 681
        }

682
        self.cstore.injected_panic_runtime = Some(cnum);
M
Mark Rousskov 已提交
683
        self.inject_dependency_if(cnum, "a panic runtime", &|data| data.needs_panic_runtime());
684 685
    }

686
    fn inject_profiler_runtime(&mut self) {
M
Mark Rousskov 已提交
687
        if self.sess.opts.debugging_opts.profile || self.sess.opts.cg.profile_generate.enabled() {
M
Marco Castelluccio 已提交
688 689
            info!("loading profiler");

690
            let name = Symbol::intern("profiler_builtins");
691 692
            let cnum = self.resolve_crate(name, DUMMY_SP, DepKind::Implicit, None);
            let data = self.cstore.get_crate_data(cnum);
M
Marco Castelluccio 已提交
693 694

            // Sanity check the loaded crate to ensure it is indeed a profiler runtime
695
            if !data.is_profiler_runtime() {
696
                self.sess.err("the crate `profiler_builtins` is not a profiler runtime");
697 698 699 700
            }
        }
    }

M
Mark Rousskov 已提交
701
    fn inject_allocator_crate(&mut self, krate: &ast::Crate) {
702
        self.cstore.has_global_allocator = match &*global_allocator_spans(krate) {
703
            [span1, span2, ..] => {
M
Mark Rousskov 已提交
704 705
                self.sess
                    .struct_span_err(*span2, "cannot define multiple global allocators")
E
Esteban Küber 已提交
706
                    .span_label(*span2, "cannot define a new global allocator")
707
                    .span_label(*span1, "previous global allocator defined here")
E
Esteban Küber 已提交
708
                    .emit();
709 710
                true
            }
M
Mark Rousskov 已提交
711
            spans => !spans.is_empty(),
712
        };
713 714 715 716

        // Check to see if we actually need an allocator. This desire comes
        // about through the `#![needs_allocator]` attribute and is typically
        // written down in liballoc.
M
Mark Rousskov 已提交
717
        let mut needs_allocator = attr::contains_name(&krate.attrs, sym::needs_allocator);
718
        self.cstore.iter_crate_data(|_, data| {
719
            needs_allocator = needs_allocator || data.needs_allocator();
720
        });
721
        if !needs_allocator {
M
Mark Rousskov 已提交
722
            return;
723
        }
724

725 726 727
        // At this point we've determined that we need an allocator. Let's see
        // if our compilation session actually needs an allocator based on what
        // we're emitting.
M
Mark Rousskov 已提交
728 729 730 731
        let all_rlib = self.sess.crate_types.borrow().iter().all(|ct| match *ct {
            config::CrateType::Rlib => true,
            _ => false,
        });
732
        if all_rlib {
M
Mark Rousskov 已提交
733
            return;
734
        }
735

736 737 738
        // Ok, we need an allocator. Not only that but we're actually going to
        // create an artifact that needs one linked in. Let's go find the one
        // that we're going to link in.
739
        //
740 741 742
        // First up we check for global allocators. Look at the crate graph here
        // and see what's a global allocator, including if we ourselves are a
        // global allocator.
M
Mark Rousskov 已提交
743 744
        let mut global_allocator =
            self.cstore.has_global_allocator.then(|| Symbol::intern("this crate"));
745
        self.cstore.iter_crate_data(|_, data| {
746
            if !data.has_global_allocator() {
M
Mark Rousskov 已提交
747
                return;
748 749
            }
            match global_allocator {
750
                Some(other_crate) => {
M
Mark Rousskov 已提交
751 752
                    self.sess.err(&format!(
                        "the `#[global_allocator]` in {} \
753
                                            conflicts with global \
754
                                            allocator in: {}",
M
Mark Rousskov 已提交
755 756 757
                        other_crate,
                        data.name()
                    ));
758
                }
759
                None => global_allocator = Some(data.name()),
760 761 762
            }
        });
        if global_allocator.is_some() {
M
Mark Rousskov 已提交
763
            self.cstore.allocator_kind = Some(AllocatorKind::Global);
M
Mark Rousskov 已提交
764
            return;
765 766 767
        }

        // Ok we haven't found a global allocator but we still need an
768 769 770
        // allocator. At this point our allocator request is typically fulfilled
        // by the standard library, denoted by the `#![default_lib_allocator]`
        // attribute.
771
        let mut has_default = attr::contains_name(&krate.attrs, sym::default_lib_allocator);
772
        self.cstore.iter_crate_data(|_, data| {
773
            if data.has_default_lib_allocator() {
774
                has_default = true;
775
            }
776 777
        });

778
        if !has_default {
M
Mark Rousskov 已提交
779 780
            self.sess.err(
                "no global memory allocator found but one is \
781
                           required; link to std or \
782
                           add `#[global_allocator]` to a static item \
M
Mark Rousskov 已提交
783 784
                           that implements the GlobalAlloc trait.",
            );
785
        }
786
        self.cstore.allocator_kind = Some(AllocatorKind::Default);
787 788
    }

M
Mark Rousskov 已提交
789 790 791 792 793 794
    fn inject_dependency_if(
        &self,
        krate: CrateNum,
        what: &str,
        needs_dep: &dyn Fn(&CrateMetadata) -> bool,
    ) {
795 796 797 798
        // don't perform this validation if the session has errors, as one of
        // those errors may indicate a circular dependency which could cause
        // this to stack overflow.
        if self.sess.has_errors() {
M
Mark Rousskov 已提交
799
            return;
800 801
        }

802
        // Before we inject any dependencies, make sure we don't inject a
803 804
        // circular dependency by validating that this crate doesn't
        // transitively depend on any crates satisfying `needs_dep`.
805
        for dep in self.cstore.crate_dependencies_in_reverse_postorder(krate) {
806 807
            let data = self.cstore.get_crate_data(dep);
            if needs_dep(&data) {
M
Mark Rousskov 已提交
808 809
                self.sess.err(&format!(
                    "the crate `{}` cannot depend \
810 811
                                        on a crate that needs {}, but \
                                        it depends on `{}`",
M
Mark Rousskov 已提交
812 813 814 815
                    self.cstore.get_crate_data(krate).name(),
                    what,
                    data.name()
                ));
816 817
            }
        }
818 819 820 821 822

        // All crates satisfying `needs_dep` do not explicitly depend on the
        // crate provided for this compile, but in order for this compilation to
        // be successfully linked we need to inject a dependency (to order the
        // crates on the command line correctly).
A
Ariel Ben-Yehuda 已提交
823
        self.cstore.iter_crate_data(|cnum, data| {
824
            if !needs_dep(data) {
M
Mark Rousskov 已提交
825
                return;
826 827
            }

828
            info!("injecting a dep from {} to {}", cnum, krate);
829
            data.add_dependency(krate);
830 831
        });
    }
832

833
    pub fn postprocess(&mut self, krate: &ast::Crate) {
834
        self.inject_profiler_runtime();
835
        self.inject_allocator_crate(krate);
836
        self.inject_panic_runtime(krate);
837

838
        if log_enabled!(log::Level::Info) {
839 840 841 842
            dump_crates(&self.cstore);
        }
    }

843 844 845 846 847
    pub fn process_extern_crate(
        &mut self,
        item: &ast::Item,
        definitions: &Definitions,
    ) -> CrateNum {
V
varkor 已提交
848
        match item.kind {
849
            ast::ItemKind::ExternCrate(orig_name) => {
M
Mark Rousskov 已提交
850 851 852 853
                debug!(
                    "resolving extern crate stmt. ident: {} orig_name: {:?}",
                    item.ident, orig_name
                );
854
                let name = match orig_name {
855
                    Some(orig_name) => {
M
Mark Rousskov 已提交
856 857 858 859 860
                        crate::validate_crate_name(
                            Some(self.sess),
                            &orig_name.as_str(),
                            Some(item.span),
                        );
861
                        orig_name
862 863 864
                    }
                    None => item.ident.name,
                };
865
                let dep_kind = if attr::contains_name(&item.attrs, sym::no_link) {
866
                    DepKind::MacrosOnly
867 868 869 870
                } else {
                    DepKind::Explicit
                };

871
                let cnum = self.resolve_crate(name, item.span, dep_kind, None);
872

873
                let def_id = definitions.opt_local_def_id(item.id).unwrap();
874
                let path_len = definitions.def_path(def_id.index).data.len();
875 876 877
                self.update_extern_crate(
                    cnum,
                    ExternCrate {
S
Shotaro Yamada 已提交
878
                        src: ExternCrateSource::Extern(def_id),
879
                        span: item.span,
S
Shotaro Yamada 已提交
880
                        path_len,
881
                        dependency_of: LOCAL_CRATE,
882 883 884
                    },
                );
                cnum
885
            }
886
            _ => bug!(),
887
        }
888
    }
889

890
    pub fn process_path_extern(&mut self, name: Symbol, span: Span) -> CrateNum {
891
        let cnum = self.resolve_crate(name, span, DepKind::Explicit, None);
892 893 894 895 896 897

        self.update_extern_crate(
            cnum,
            ExternCrate {
                src: ExternCrateSource::Path,
                span,
S
Shotaro Yamada 已提交
898 899
                // to have the least priority in `update_extern_crate`
                path_len: usize::max_value(),
900
                dependency_of: LOCAL_CRATE,
901 902 903 904 905
            },
        );

        cnum
    }
906

907
    pub fn maybe_process_path_extern(&mut self, name: Symbol, span: Span) -> Option<CrateNum> {
908
        self.maybe_resolve_crate(name, span, DepKind::Explicit, None).ok()
909
    }
910
}