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
27 /// These are exceptions to Rust's permissive licensing policy, and
28 /// should be considered bugs. Exceptions are only allowed in Rust
29 /// tooling. It is _crucial_ that no exception crates be dependencies
30 /// of the Rust runtime (std/test).
31 const EXCEPTIONS: &[(&str, &str)] = &[
32 ("mdbook", "MPL-2.0"), // mdbook
33 ("openssl", "Apache-2.0"), // cargo, mdbook
34 ("colored", "MPL-2.0"), // rustfmt
35 ("ryu", "Apache-2.0 OR BSL-1.0"), // cargo/... (because of serde)
36 ("bytesize", "Apache-2.0"), // cargo
37 ("im-rc", "MPL-2.0+"), // cargo
38 ("sized-chunks", "MPL-2.0+"), // cargo via im-rc
39 ("bitmaps", "MPL-2.0+"), // cargo via im-rc
40 ("instant", "BSD-3-Clause"), // rustc_driver/tracing-subscriber/parking_lot
41 ("snap", "BSD-3-Clause"), // rustc
42 ("fluent-langneg", "Apache-2.0"), // rustc (fluent translations)
43 ("self_cell", "Apache-2.0"), // rustc (fluent translations)
44 // FIXME: this dependency violates the documentation comment above:
45 ("fortanix-sgx-abi", "MPL-2.0"), // libstd but only for `sgx` target
46 ("dunce", "CC0-1.0"), // cargo (dev dependency)
47 ("similar", "Apache-2.0"), // cargo (dev dependency)
48 ("normalize-line-endings", "Apache-2.0"), // cargo (dev dependency)
51 const EXCEPTIONS_CRANELIFT: &[(&str, &str)] = &[
52 ("cranelift-bforest", "Apache-2.0 WITH LLVM-exception"),
53 ("cranelift-codegen", "Apache-2.0 WITH LLVM-exception"),
54 ("cranelift-codegen-meta", "Apache-2.0 WITH LLVM-exception"),
55 ("cranelift-codegen-shared", "Apache-2.0 WITH LLVM-exception"),
56 ("cranelift-entity", "Apache-2.0 WITH LLVM-exception"),
57 ("cranelift-frontend", "Apache-2.0 WITH LLVM-exception"),
58 ("cranelift-isle", "Apache-2.0 WITH LLVM-exception"),
59 ("cranelift-jit", "Apache-2.0 WITH LLVM-exception"),
60 ("cranelift-module", "Apache-2.0 WITH LLVM-exception"),
61 ("cranelift-native", "Apache-2.0 WITH LLVM-exception"),
62 ("cranelift-object", "Apache-2.0 WITH LLVM-exception"),
63 ("mach", "BSD-2-Clause"),
64 ("regalloc2", "Apache-2.0 WITH LLVM-exception"),
65 ("target-lexicon", "Apache-2.0 WITH LLVM-exception"),
68 const EXCEPTIONS_BOOTSTRAP: &[(&str, &str)] = &[
69 ("ryu", "Apache-2.0 OR BSL-1.0"), // through serde
72 /// These are the root crates that are part of the runtime. The licenses for
73 /// these and all their dependencies *must not* be in the exception list.
74 const RUNTIME_CRATES: &[&str] = &["std", "core", "alloc", "test", "panic_abort", "panic_unwind"];
76 /// Crates rustc is allowed to depend on. Avoid adding to the list if possible.
78 /// This list is here to provide a speed-bump to adding a new dependency to
79 /// rustc. Please check with the compiler team before adding an entry.
80 const PERMITTED_RUSTC_DEPENDENCIES: &[&str] = &[
116 "fallible-iterator", // dependency of `thorin`
162 "perf-event-open-sys",
205 "stable_deref_trait",
222 "tracing-attributes",
225 "tracing-subscriber",
229 "unic-char-property",
235 "unic-langid-macros",
236 "unic-langid-macros-impl",
238 "unicode-normalization",
248 "winapi-i686-pc-windows-gnu",
250 "winapi-x86_64-pc-windows-gnu",
251 // this is a false-positive: it's only used by rustfmt, but because it's enabled through a
252 // feature, tidy thinks it's used by rustc as well.
256 const PERMITTED_CRANELIFT_DEPENDENCIES: &[&str] = &[
266 "cranelift-codegen-meta",
267 "cranelift-codegen-shared",
269 "cranelift-frontend",
296 "winapi-i686-pc-windows-gnu",
297 "winapi-x86_64-pc-windows-gnu",
299 "windows_aarch64_msvc",
302 "windows_x86_64_gnu",
303 "windows_x86_64_msvc",
306 const FORBIDDEN_TO_HAVE_DUPLICATES: &[&str] = &[
307 // This crate takes quite a long time to build, so don't allow two versions of them
308 // to accidentally sneak into our dependency graph, in order to ensure we keep our CI times
313 /// Dependency checks.
315 /// `root` is path to the directory with the root `Cargo.toml` (for the workspace). `cargo` is path
316 /// to the cargo executable.
317 pub fn check(root: &Path, cargo: &Path, bad: &mut bool) {
318 let mut cmd = cargo_metadata::MetadataCommand::new();
319 cmd.cargo_path(cargo)
320 .manifest_path(root.join("Cargo.toml"))
321 .features(cargo_metadata::CargoOpt::AllFeatures);
322 let metadata = t!(cmd.exec());
323 let runtime_ids = compute_runtime_crates(&metadata);
324 check_license_exceptions(&metadata, EXCEPTIONS, runtime_ids, bad);
325 check_permitted_dependencies(
328 PERMITTED_RUSTC_DEPENDENCIES,
329 &["rustc_driver", "rustc_codegen_llvm"],
332 check_crate_duplicate(&metadata, FORBIDDEN_TO_HAVE_DUPLICATES, bad);
333 check_rustfix(&metadata, bad);
335 // Check rustc_codegen_cranelift independently as it has it's own workspace.
336 let mut cmd = cargo_metadata::MetadataCommand::new();
337 cmd.cargo_path(cargo)
338 .manifest_path(root.join("compiler/rustc_codegen_cranelift/Cargo.toml"))
339 .features(cargo_metadata::CargoOpt::AllFeatures);
340 let metadata = t!(cmd.exec());
341 let runtime_ids = HashSet::new();
342 check_license_exceptions(&metadata, EXCEPTIONS_CRANELIFT, runtime_ids, bad);
343 check_permitted_dependencies(
346 PERMITTED_CRANELIFT_DEPENDENCIES,
347 &["rustc_codegen_cranelift"],
350 check_crate_duplicate(&metadata, &[], bad);
352 let mut cmd = cargo_metadata::MetadataCommand::new();
353 cmd.cargo_path(cargo)
354 .manifest_path(root.join("src/bootstrap/Cargo.toml"))
355 .features(cargo_metadata::CargoOpt::AllFeatures);
356 let metadata = t!(cmd.exec());
357 let runtime_ids = HashSet::new();
358 check_license_exceptions(&metadata, EXCEPTIONS_BOOTSTRAP, runtime_ids, bad);
361 /// Check that all licenses are in the valid list in `LICENSES`.
363 /// Packages listed in `exceptions` are allowed for tools.
364 fn check_license_exceptions(
366 exceptions: &[(&str, &str)],
367 runtime_ids: HashSet<&PackageId>,
370 // Validate the EXCEPTIONS list hasn't changed.
371 for (name, license) in exceptions {
372 // Check that the package actually exists.
373 if !metadata.packages.iter().any(|p| p.name == *name) {
376 "could not find exception package `{}`\n\
377 Remove from EXCEPTIONS list if it is no longer used.",
381 // Check that the license hasn't changed.
382 for pkg in metadata.packages.iter().filter(|p| p.name == *name) {
387 "dependency exception `{}` does not declare a license expression",
391 Some(pkg_license) => {
392 if pkg_license.as_str() != *license {
393 println!("dependency exception `{name}` license has changed");
394 println!(" previously `{license}` now `{pkg_license}`");
395 println!(" update EXCEPTIONS for the new license");
403 let exception_names: Vec<_> = exceptions.iter().map(|(name, _license)| *name).collect();
405 // Check if any package does not have a valid license.
406 for pkg in &metadata.packages {
407 if pkg.source.is_none() {
408 // No need to check local packages.
411 if !runtime_ids.contains(&pkg.id) && exception_names.contains(&pkg.name.as_str()) {
414 let license = match &pkg.license {
415 Some(license) => license,
417 tidy_error!(bad, "dependency `{}` does not define a license expression", pkg.id);
421 if !LICENSES.contains(&license.as_str()) {
422 if pkg.name == "fortanix-sgx-abi" {
423 // This is a specific exception because SGX is considered
424 // "third party". See
425 // https://github.com/rust-lang/rust/issues/62620 for more. In
426 // general, these should never be added.
429 tidy_error!(bad, "invalid license `{}` in `{}`", license, pkg.id);
434 /// Checks the dependency of `restricted_dependency_crates` at the given path. Changes `bad` to
435 /// `true` if a check failed.
437 /// Specifically, this checks that the dependencies are on the `permitted_dependencies`.
438 fn check_permitted_dependencies(
441 permitted_dependencies: &[&'static str],
442 restricted_dependency_crates: &[&'static str],
445 // Check that the PERMITTED_DEPENDENCIES does not have unused entries.
446 for name in permitted_dependencies {
447 if !metadata.packages.iter().any(|p| p.name == *name) {
450 "could not find allowed package `{}`\n\
451 Remove from PERMITTED_DEPENDENCIES list if it is no longer used.",
456 // Get the list in a convenient form.
457 let permitted_dependencies: HashSet<_> = permitted_dependencies.iter().cloned().collect();
459 // Check dependencies.
460 let mut visited = BTreeSet::new();
461 let mut unapproved = BTreeSet::new();
462 for &krate in restricted_dependency_crates.iter() {
463 let pkg = pkg_from_name(metadata, krate);
465 check_crate_dependencies(&permitted_dependencies, metadata, &mut visited, pkg);
466 unapproved.append(&mut bad);
469 if !unapproved.is_empty() {
470 tidy_error!(bad, "Dependencies for {} not explicitly permitted:", descr);
471 for dep in unapproved {
477 /// Checks the dependencies of the given crate from the given cargo metadata to see if they are on
478 /// the list of permitted dependencies. Returns a list of disallowed dependencies.
479 fn check_crate_dependencies<'a>(
480 permitted_dependencies: &'a HashSet<&'static str>,
481 metadata: &'a Metadata,
482 visited: &mut BTreeSet<&'a PackageId>,
484 ) -> BTreeSet<&'a PackageId> {
485 // This will contain bad deps.
486 let mut unapproved = BTreeSet::new();
488 // Check if we have already visited this crate.
489 if visited.contains(&krate.id) {
493 visited.insert(&krate.id);
495 // If this path is in-tree, we don't require it to be explicitly permitted.
496 if krate.source.is_some() {
497 // If this dependency is not on `PERMITTED_DEPENDENCIES`, add to bad set.
498 if !permitted_dependencies.contains(krate.name.as_str()) {
499 unapproved.insert(&krate.id);
503 // Do a DFS in the crate graph.
504 let to_check = deps_of(metadata, &krate.id);
506 for dep in to_check {
507 let mut bad = check_crate_dependencies(permitted_dependencies, metadata, visited, dep);
508 unapproved.append(&mut bad);
514 /// Prevents multiple versions of some expensive crates.
515 fn check_crate_duplicate(
517 forbidden_to_have_duplicates: &[&str],
520 for &name in forbidden_to_have_duplicates {
521 let matches: Vec<_> = metadata.packages.iter().filter(|pkg| pkg.name == name).collect();
522 match matches.len() {
526 "crate `{}` is missing, update `check_crate_duplicate` \
527 if it is no longer used",
535 "crate `{}` is duplicated in `Cargo.lock`, \
536 it is too expensive to build multiple times, \
537 so make sure only one version appears across all dependencies",
541 println!(" * {}", pkg.id);
548 /// Returns a list of dependencies for the given package.
549 fn deps_of<'a>(metadata: &'a Metadata, pkg_id: &'a PackageId) -> Vec<&'a Package> {
550 let resolve = metadata.resolve.as_ref().unwrap();
554 .find(|n| &n.id == pkg_id)
555 .unwrap_or_else(|| panic!("could not find `{pkg_id}` in resolve"));
559 metadata.packages.iter().find(|pkg| pkg.id == dep.pkg).unwrap_or_else(|| {
560 panic!("could not find dep `{}` for pkg `{}` in resolve", dep.pkg, pkg_id)
566 /// Finds a package with the given name.
567 fn pkg_from_name<'a>(metadata: &'a Metadata, name: &'static str) -> &'a Package {
568 let mut i = metadata.packages.iter().filter(|p| p.name == name);
570 i.next().unwrap_or_else(|| panic!("could not find package `{name}` in package list"));
571 assert!(i.next().is_none(), "more than one package found for `{name}`");
575 /// Finds all the packages that are in the rust runtime.
576 fn compute_runtime_crates<'a>(metadata: &'a Metadata) -> HashSet<&'a PackageId> {
577 let resolve = metadata.resolve.as_ref().unwrap();
578 let mut result = HashSet::new();
579 for name in RUNTIME_CRATES {
580 let id = &pkg_from_name(metadata, name).id;
581 normal_deps_of_r(resolve, id, &mut result);
586 /// Recursively find all normal dependencies.
587 fn normal_deps_of_r<'a>(
588 resolve: &'a Resolve,
589 pkg_id: &'a PackageId,
590 result: &mut HashSet<&'a PackageId>,
592 if !result.insert(pkg_id) {
598 .find(|n| &n.id == pkg_id)
599 .unwrap_or_else(|| panic!("could not find `{pkg_id}` in resolve"));
600 for dep in &node.deps {
601 normal_deps_of_r(resolve, &dep.pkg, result);
605 fn check_rustfix(metadata: &Metadata, bad: &mut bool) {
606 let cargo = pkg_from_name(metadata, "cargo");
607 let compiletest = pkg_from_name(metadata, "compiletest");
608 let cargo_deps = deps_of(metadata, &cargo.id);
609 let compiletest_deps = deps_of(metadata, &compiletest.id);
610 let cargo_rustfix = cargo_deps.iter().find(|p| p.name == "rustfix").unwrap();
611 let compiletest_rustfix = compiletest_deps.iter().find(|p| p.name == "rustfix").unwrap();
612 if cargo_rustfix.version != compiletest_rustfix.version {
615 "cargo's rustfix version {} does not match compiletest's rustfix version {}\n\
616 rustfix should be kept in sync, update the cargo side first, and then update \
617 compiletest along with cargo.",
618 cargo_rustfix.version,
619 compiletest_rustfix.version