1 //! Checks the licenses of third-party dependencies.
3 use cargo_metadata::{Metadata, Package, PackageId, Resolve};
4 use std::collections::{BTreeSet, HashSet};
7 /// These are licenses that are allowed for all crates, including the runtime,
9 const LICENSES: &[&str] = &[
16 "Apache-2.0 WITH LLVM-exception OR Apache-2.0 OR MIT", // wasi license
21 "0BSD OR MIT OR Apache-2.0", // adler license
22 "Zlib OR Apache-2.0 OR MIT", // tinyvec
23 "MIT OR Apache-2.0 OR Zlib", // tinyvec_macros
24 "MIT OR Zlib OR Apache-2.0", // miniz_oxide
25 "(MIT OR Apache-2.0) AND Unicode-DFS-2016", // unicode_ident
28 /// These are exceptions to Rust's permissive licensing policy, and
29 /// should be considered bugs. Exceptions are only allowed in Rust
30 /// tooling. It is _crucial_ that no exception crates be dependencies
31 /// of the Rust runtime (std/test).
32 const EXCEPTIONS: &[(&str, &str)] = &[
33 ("mdbook", "MPL-2.0"), // mdbook
34 ("openssl", "Apache-2.0"), // cargo, mdbook
35 ("colored", "MPL-2.0"), // rustfmt
36 ("ryu", "Apache-2.0 OR BSL-1.0"), // cargo/... (because of serde)
37 ("bytesize", "Apache-2.0"), // cargo
38 ("im-rc", "MPL-2.0+"), // cargo
39 ("sized-chunks", "MPL-2.0+"), // cargo via im-rc
40 ("bitmaps", "MPL-2.0+"), // cargo via im-rc
41 ("instant", "BSD-3-Clause"), // rustc_driver/tracing-subscriber/parking_lot
42 ("snap", "BSD-3-Clause"), // rustc
43 ("fluent-langneg", "Apache-2.0"), // rustc (fluent translations)
44 ("self_cell", "Apache-2.0"), // rustc (fluent translations)
45 // FIXME: this dependency violates the documentation comment above:
46 ("fortanix-sgx-abi", "MPL-2.0"), // libstd but only for `sgx` target
47 ("dunce", "CC0-1.0"), // cargo (dev dependency)
48 ("similar", "Apache-2.0"), // cargo (dev dependency)
49 ("normalize-line-endings", "Apache-2.0"), // cargo (dev dependency)
52 const EXCEPTIONS_CRANELIFT: &[(&str, &str)] = &[
53 ("cranelift-bforest", "Apache-2.0 WITH LLVM-exception"),
54 ("cranelift-codegen", "Apache-2.0 WITH LLVM-exception"),
55 ("cranelift-codegen-meta", "Apache-2.0 WITH LLVM-exception"),
56 ("cranelift-codegen-shared", "Apache-2.0 WITH LLVM-exception"),
57 ("cranelift-entity", "Apache-2.0 WITH LLVM-exception"),
58 ("cranelift-frontend", "Apache-2.0 WITH LLVM-exception"),
59 ("cranelift-isle", "Apache-2.0 WITH LLVM-exception"),
60 ("cranelift-jit", "Apache-2.0 WITH LLVM-exception"),
61 ("cranelift-module", "Apache-2.0 WITH LLVM-exception"),
62 ("cranelift-native", "Apache-2.0 WITH LLVM-exception"),
63 ("cranelift-object", "Apache-2.0 WITH LLVM-exception"),
64 ("mach", "BSD-2-Clause"),
65 ("regalloc2", "Apache-2.0 WITH LLVM-exception"),
66 ("target-lexicon", "Apache-2.0 WITH LLVM-exception"),
69 const EXCEPTIONS_BOOTSTRAP: &[(&str, &str)] = &[
70 ("ryu", "Apache-2.0 OR BSL-1.0"), // through serde
73 /// These are the root crates that are part of the runtime. The licenses for
74 /// these and all their dependencies *must not* be in the exception list.
75 const RUNTIME_CRATES: &[&str] = &["std", "core", "alloc", "test", "panic_abort", "panic_unwind"];
77 /// Crates rustc is allowed to depend on. Avoid adding to the list if possible.
79 /// This list is here to provide a speed-bump to adding a new dependency to
80 /// rustc. Please check with the compiler team before adding an entry.
81 const PERMITTED_RUSTC_DEPENDENCIES: &[&str] = &[
117 "fallible-iterator", // dependency of `thorin`
163 "perf-event-open-sys",
206 "stable_deref_trait",
223 "tracing-attributes",
226 "tracing-subscriber",
230 "unic-char-property",
236 "unic-langid-macros",
237 "unic-langid-macros-impl",
240 "unicode-normalization",
250 "winapi-i686-pc-windows-gnu",
252 "winapi-x86_64-pc-windows-gnu",
253 // this is a false-positive: it's only used by rustfmt, but because it's enabled through a
254 // feature, tidy thinks it's used by rustc as well.
258 const PERMITTED_CRANELIFT_DEPENDENCIES: &[&str] = &[
268 "cranelift-codegen-meta",
269 "cranelift-codegen-shared",
271 "cranelift-frontend",
298 "winapi-i686-pc-windows-gnu",
299 "winapi-x86_64-pc-windows-gnu",
301 "windows_aarch64_msvc",
304 "windows_x86_64_gnu",
305 "windows_x86_64_msvc",
308 const FORBIDDEN_TO_HAVE_DUPLICATES: &[&str] = &[
309 // This crate takes quite a long time to build, so don't allow two versions of them
310 // to accidentally sneak into our dependency graph, in order to ensure we keep our CI times
315 /// Dependency checks.
317 /// `root` is path to the directory with the root `Cargo.toml` (for the workspace). `cargo` is path
318 /// to the cargo executable.
319 pub fn check(root: &Path, cargo: &Path, bad: &mut bool) {
320 let mut cmd = cargo_metadata::MetadataCommand::new();
321 cmd.cargo_path(cargo)
322 .manifest_path(root.join("Cargo.toml"))
323 .features(cargo_metadata::CargoOpt::AllFeatures);
324 let metadata = t!(cmd.exec());
325 let runtime_ids = compute_runtime_crates(&metadata);
326 check_license_exceptions(&metadata, EXCEPTIONS, runtime_ids, bad);
327 check_permitted_dependencies(
330 PERMITTED_RUSTC_DEPENDENCIES,
331 &["rustc_driver", "rustc_codegen_llvm"],
334 check_crate_duplicate(&metadata, FORBIDDEN_TO_HAVE_DUPLICATES, bad);
335 check_rustfix(&metadata, bad);
337 // Check rustc_codegen_cranelift independently as it has it's own workspace.
338 let mut cmd = cargo_metadata::MetadataCommand::new();
339 cmd.cargo_path(cargo)
340 .manifest_path(root.join("compiler/rustc_codegen_cranelift/Cargo.toml"))
341 .features(cargo_metadata::CargoOpt::AllFeatures);
342 let metadata = t!(cmd.exec());
343 let runtime_ids = HashSet::new();
344 check_license_exceptions(&metadata, EXCEPTIONS_CRANELIFT, runtime_ids, bad);
345 check_permitted_dependencies(
348 PERMITTED_CRANELIFT_DEPENDENCIES,
349 &["rustc_codegen_cranelift"],
352 check_crate_duplicate(&metadata, &[], bad);
354 let mut cmd = cargo_metadata::MetadataCommand::new();
355 cmd.cargo_path(cargo)
356 .manifest_path(root.join("src/bootstrap/Cargo.toml"))
357 .features(cargo_metadata::CargoOpt::AllFeatures);
358 let metadata = t!(cmd.exec());
359 let runtime_ids = HashSet::new();
360 check_license_exceptions(&metadata, EXCEPTIONS_BOOTSTRAP, runtime_ids, bad);
363 /// Check that all licenses are in the valid list in `LICENSES`.
365 /// Packages listed in `exceptions` are allowed for tools.
366 fn check_license_exceptions(
368 exceptions: &[(&str, &str)],
369 runtime_ids: HashSet<&PackageId>,
372 // Validate the EXCEPTIONS list hasn't changed.
373 for (name, license) in exceptions {
374 // Check that the package actually exists.
375 if !metadata.packages.iter().any(|p| p.name == *name) {
378 "could not find exception package `{}`\n\
379 Remove from EXCEPTIONS list if it is no longer used.",
383 // Check that the license hasn't changed.
384 for pkg in metadata.packages.iter().filter(|p| p.name == *name) {
389 "dependency exception `{}` does not declare a license expression",
393 Some(pkg_license) => {
394 if pkg_license.as_str() != *license {
395 println!("dependency exception `{name}` license has changed");
396 println!(" previously `{license}` now `{pkg_license}`");
397 println!(" update EXCEPTIONS for the new license");
405 let exception_names: Vec<_> = exceptions.iter().map(|(name, _license)| *name).collect();
407 // Check if any package does not have a valid license.
408 for pkg in &metadata.packages {
409 if pkg.source.is_none() {
410 // No need to check local packages.
413 if !runtime_ids.contains(&pkg.id) && exception_names.contains(&pkg.name.as_str()) {
416 let license = match &pkg.license {
417 Some(license) => license,
419 tidy_error!(bad, "dependency `{}` does not define a license expression", pkg.id);
423 if !LICENSES.contains(&license.as_str()) {
424 if pkg.name == "fortanix-sgx-abi" {
425 // This is a specific exception because SGX is considered
426 // "third party". See
427 // https://github.com/rust-lang/rust/issues/62620 for more. In
428 // general, these should never be added.
431 tidy_error!(bad, "invalid license `{}` in `{}`", license, pkg.id);
436 /// Checks the dependency of `restricted_dependency_crates` at the given path. Changes `bad` to
437 /// `true` if a check failed.
439 /// Specifically, this checks that the dependencies are on the `permitted_dependencies`.
440 fn check_permitted_dependencies(
443 permitted_dependencies: &[&'static str],
444 restricted_dependency_crates: &[&'static str],
447 // Check that the PERMITTED_DEPENDENCIES does not have unused entries.
448 for name in permitted_dependencies {
449 if !metadata.packages.iter().any(|p| p.name == *name) {
452 "could not find allowed package `{}`\n\
453 Remove from PERMITTED_DEPENDENCIES list if it is no longer used.",
458 // Get the list in a convenient form.
459 let permitted_dependencies: HashSet<_> = permitted_dependencies.iter().cloned().collect();
461 // Check dependencies.
462 let mut visited = BTreeSet::new();
463 let mut unapproved = BTreeSet::new();
464 for &krate in restricted_dependency_crates.iter() {
465 let pkg = pkg_from_name(metadata, krate);
467 check_crate_dependencies(&permitted_dependencies, metadata, &mut visited, pkg);
468 unapproved.append(&mut bad);
471 if !unapproved.is_empty() {
472 tidy_error!(bad, "Dependencies for {} not explicitly permitted:", descr);
473 for dep in unapproved {
479 /// Checks the dependencies of the given crate from the given cargo metadata to see if they are on
480 /// the list of permitted dependencies. Returns a list of disallowed dependencies.
481 fn check_crate_dependencies<'a>(
482 permitted_dependencies: &'a HashSet<&'static str>,
483 metadata: &'a Metadata,
484 visited: &mut BTreeSet<&'a PackageId>,
486 ) -> BTreeSet<&'a PackageId> {
487 // This will contain bad deps.
488 let mut unapproved = BTreeSet::new();
490 // Check if we have already visited this crate.
491 if visited.contains(&krate.id) {
495 visited.insert(&krate.id);
497 // If this path is in-tree, we don't require it to be explicitly permitted.
498 if krate.source.is_some() {
499 // If this dependency is not on `PERMITTED_DEPENDENCIES`, add to bad set.
500 if !permitted_dependencies.contains(krate.name.as_str()) {
501 unapproved.insert(&krate.id);
505 // Do a DFS in the crate graph.
506 let to_check = deps_of(metadata, &krate.id);
508 for dep in to_check {
509 let mut bad = check_crate_dependencies(permitted_dependencies, metadata, visited, dep);
510 unapproved.append(&mut bad);
516 /// Prevents multiple versions of some expensive crates.
517 fn check_crate_duplicate(
519 forbidden_to_have_duplicates: &[&str],
522 for &name in forbidden_to_have_duplicates {
523 let matches: Vec<_> = metadata.packages.iter().filter(|pkg| pkg.name == name).collect();
524 match matches.len() {
528 "crate `{}` is missing, update `check_crate_duplicate` \
529 if it is no longer used",
537 "crate `{}` is duplicated in `Cargo.lock`, \
538 it is too expensive to build multiple times, \
539 so make sure only one version appears across all dependencies",
543 println!(" * {}", pkg.id);
550 /// Returns a list of dependencies for the given package.
551 fn deps_of<'a>(metadata: &'a Metadata, pkg_id: &'a PackageId) -> Vec<&'a Package> {
552 let resolve = metadata.resolve.as_ref().unwrap();
556 .find(|n| &n.id == pkg_id)
557 .unwrap_or_else(|| panic!("could not find `{pkg_id}` in resolve"));
561 metadata.packages.iter().find(|pkg| pkg.id == dep.pkg).unwrap_or_else(|| {
562 panic!("could not find dep `{}` for pkg `{}` in resolve", dep.pkg, pkg_id)
568 /// Finds a package with the given name.
569 fn pkg_from_name<'a>(metadata: &'a Metadata, name: &'static str) -> &'a Package {
570 let mut i = metadata.packages.iter().filter(|p| p.name == name);
572 i.next().unwrap_or_else(|| panic!("could not find package `{name}` in package list"));
573 assert!(i.next().is_none(), "more than one package found for `{name}`");
577 /// Finds all the packages that are in the rust runtime.
578 fn compute_runtime_crates<'a>(metadata: &'a Metadata) -> HashSet<&'a PackageId> {
579 let resolve = metadata.resolve.as_ref().unwrap();
580 let mut result = HashSet::new();
581 for name in RUNTIME_CRATES {
582 let id = &pkg_from_name(metadata, name).id;
583 normal_deps_of_r(resolve, id, &mut result);
588 /// Recursively find all normal dependencies.
589 fn normal_deps_of_r<'a>(
590 resolve: &'a Resolve,
591 pkg_id: &'a PackageId,
592 result: &mut HashSet<&'a PackageId>,
594 if !result.insert(pkg_id) {
600 .find(|n| &n.id == pkg_id)
601 .unwrap_or_else(|| panic!("could not find `{pkg_id}` in resolve"));
602 for dep in &node.deps {
603 normal_deps_of_r(resolve, &dep.pkg, result);
607 fn check_rustfix(metadata: &Metadata, bad: &mut bool) {
608 let cargo = pkg_from_name(metadata, "cargo");
609 let compiletest = pkg_from_name(metadata, "compiletest");
610 let cargo_deps = deps_of(metadata, &cargo.id);
611 let compiletest_deps = deps_of(metadata, &compiletest.id);
612 let cargo_rustfix = cargo_deps.iter().find(|p| p.name == "rustfix").unwrap();
613 let compiletest_rustfix = compiletest_deps.iter().find(|p| p.name == "rustfix").unwrap();
614 if cargo_rustfix.version != compiletest_rustfix.version {
617 "cargo's rustfix version {} does not match compiletest's rustfix version {}\n\
618 rustfix should be kept in sync, update the cargo side first, and then update \
619 compiletest along with cargo.",
620 cargo_rustfix.version,
621 compiletest_rustfix.version