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
20 "0BSD OR MIT OR Apache-2.0", // adler license
21 "Zlib OR Apache-2.0 OR MIT", // tinyvec
24 /// These are exceptions to Rust's permissive licensing policy, and
25 /// should be considered bugs. Exceptions are only allowed in Rust
26 /// tooling. It is _crucial_ that no exception crates be dependencies
27 /// of the Rust runtime (std/test).
28 const EXCEPTIONS: &[(&str, &str)] = &[
29 ("mdbook", "MPL-2.0"), // mdbook
30 ("openssl", "Apache-2.0"), // cargo, mdbook
31 ("fuchsia-zircon-sys", "BSD-3-Clause"), // rustdoc, rustc, cargo
32 ("fuchsia-zircon", "BSD-3-Clause"), // rustdoc, rustc, cargo (jobserver & tempdir)
33 ("colored", "MPL-2.0"), // rustfmt
34 ("ordslice", "Apache-2.0"), // rls
35 ("ryu", "Apache-2.0 OR BSL-1.0"), // rls/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 ("crossbeam-queue", "MIT/Apache-2.0 AND BSD-2-Clause"), // rls via rayon
41 ("instant", "BSD-3-Clause"), // rustc_driver/tracing-subscriber/parking_lot
42 ("snap", "BSD-3-Clause"), // rustc
43 // FIXME: this dependency violates the documentation comment above:
44 ("fortanix-sgx-abi", "MPL-2.0"), // libstd but only for `sgx` target
47 /// These are the root crates that are part of the runtime. The licenses for
48 /// these and all their dependencies *must not* be in the exception list.
49 const RUNTIME_CRATES: &[&str] = &["std", "core", "alloc", "test", "panic_abort", "panic_unwind"];
51 /// Crates whose dependencies must be explicitly permitted.
52 const RESTRICTED_DEPENDENCY_CRATES: &[&str] = &["rustc_driver", "rustc_codegen_llvm"];
54 /// Crates rustc is allowed to depend on. Avoid adding to the list if possible.
56 /// This list is here to provide a speed-bump to adding a new dependency to
57 /// rustc. Please check with the compiler team before adding an entry.
58 const PERMITTED_DEPENDENCIES: &[&str] = &[
102 "fuchsia-zircon-sys",
140 "perf-event-open-sys",
182 "stable_deref_trait",
193 "tracing-attributes",
197 "tracing-subscriber",
200 "unicode-normalization",
210 "winapi-i686-pc-windows-gnu",
212 "winapi-x86_64-pc-windows-gnu",
215 /// Dependency checks.
217 /// `root` is path to the directory with the root `Cargo.toml` (for the workspace). `cargo` is path
218 /// to the cargo executable.
219 pub fn check(root: &Path, cargo: &Path, bad: &mut bool) {
220 let mut cmd = cargo_metadata::MetadataCommand::new();
221 cmd.cargo_path(cargo)
222 .manifest_path(root.join("Cargo.toml"))
223 .features(cargo_metadata::CargoOpt::AllFeatures);
224 let metadata = t!(cmd.exec());
225 check_exceptions(&metadata, bad);
226 check_dependencies(&metadata, bad);
227 check_crate_duplicate(&metadata, bad);
230 /// Check that all licenses are in the valid list in `LICENSES`.
232 /// Packages listed in `EXCEPTIONS` are allowed for tools.
233 fn check_exceptions(metadata: &Metadata, bad: &mut bool) {
234 // Validate the EXCEPTIONS list hasn't changed.
235 for (name, license) in EXCEPTIONS {
236 // Check that the package actually exists.
237 if !metadata.packages.iter().any(|p| p.name == *name) {
240 "could not find exception package `{}`\n\
241 Remove from EXCEPTIONS list if it is no longer used.",
245 // Check that the license hasn't changed.
246 for pkg in metadata.packages.iter().filter(|p| p.name == *name) {
247 if pkg.name == "fuchsia-cprng" {
248 // This package doesn't declare a license expression. Manual
249 // inspection of the license file is necessary, which appears
250 // to be BSD-3-Clause.
251 assert!(pkg.license.is_none());
258 "dependency exception `{}` does not declare a license expression",
262 Some(pkg_license) => {
263 if pkg_license.as_str() != *license {
264 if *name == "crossbeam-queue"
265 && *license == "MIT/Apache-2.0 AND BSD-2-Clause"
267 // We have two versions of crossbeam-queue and both
272 println!("dependency exception `{}` license has changed", name);
273 println!(" previously `{}` now `{}`", license, pkg_license);
274 println!(" update EXCEPTIONS for the new license");
282 let exception_names: Vec<_> = EXCEPTIONS.iter().map(|(name, _license)| *name).collect();
283 let runtime_ids = compute_runtime_crates(metadata);
285 // Check if any package does not have a valid license.
286 for pkg in &metadata.packages {
287 if pkg.source.is_none() {
288 // No need to check local packages.
291 if !runtime_ids.contains(&pkg.id) && exception_names.contains(&pkg.name.as_str()) {
294 let license = match &pkg.license {
295 Some(license) => license,
297 tidy_error!(bad, "dependency `{}` does not define a license expression", pkg.id);
301 if !LICENSES.contains(&license.as_str()) {
302 if pkg.name == "fortanix-sgx-abi" {
303 // This is a specific exception because SGX is considered
304 // "third party". See
305 // https://github.com/rust-lang/rust/issues/62620 for more. In
306 // general, these should never be added.
309 tidy_error!(bad, "invalid license `{}` in `{}`", license, pkg.id);
314 /// Checks the dependency of `RESTRICTED_DEPENDENCY_CRATES` at the given path. Changes `bad` to
315 /// `true` if a check failed.
317 /// Specifically, this checks that the dependencies are on the `PERMITTED_DEPENDENCIES`.
318 fn check_dependencies(metadata: &Metadata, bad: &mut bool) {
319 // Check that the PERMITTED_DEPENDENCIES does not have unused entries.
320 for name in PERMITTED_DEPENDENCIES {
321 if !metadata.packages.iter().any(|p| p.name == *name) {
324 "could not find allowed package `{}`\n\
325 Remove from PERMITTED_DEPENDENCIES list if it is no longer used.",
330 // Get the list in a convenient form.
331 let permitted_dependencies: HashSet<_> = PERMITTED_DEPENDENCIES.iter().cloned().collect();
333 // Check dependencies.
334 let mut visited = BTreeSet::new();
335 let mut unapproved = BTreeSet::new();
336 for &krate in RESTRICTED_DEPENDENCY_CRATES.iter() {
337 let pkg = pkg_from_name(metadata, krate);
339 check_crate_dependencies(&permitted_dependencies, metadata, &mut visited, pkg);
340 unapproved.append(&mut bad);
343 if !unapproved.is_empty() {
344 tidy_error!(bad, "Dependencies not explicitly permitted:");
345 for dep in unapproved {
346 println!("* {}", dep);
351 /// Checks the dependencies of the given crate from the given cargo metadata to see if they are on
352 /// the list of permitted dependencies. Returns a list of disallowed dependencies.
353 fn check_crate_dependencies<'a>(
354 permitted_dependencies: &'a HashSet<&'static str>,
355 metadata: &'a Metadata,
356 visited: &mut BTreeSet<&'a PackageId>,
358 ) -> BTreeSet<&'a PackageId> {
359 // This will contain bad deps.
360 let mut unapproved = BTreeSet::new();
362 // Check if we have already visited this crate.
363 if visited.contains(&krate.id) {
367 visited.insert(&krate.id);
369 // If this path is in-tree, we don't require it to be explicitly permitted.
370 if krate.source.is_some() {
371 // If this dependency is not on `PERMITTED_DEPENDENCIES`, add to bad set.
372 if !permitted_dependencies.contains(krate.name.as_str()) {
373 unapproved.insert(&krate.id);
377 // Do a DFS in the crate graph.
378 let to_check = deps_of(metadata, &krate.id);
380 for dep in to_check {
381 let mut bad = check_crate_dependencies(permitted_dependencies, metadata, visited, dep);
382 unapproved.append(&mut bad);
388 /// Prevents multiple versions of some expensive crates.
389 fn check_crate_duplicate(metadata: &Metadata, bad: &mut bool) {
390 const FORBIDDEN_TO_HAVE_DUPLICATES: &[&str] = &[
391 // These two crates take quite a long time to build, so don't allow two versions of them
392 // to accidentally sneak into our dependency graph, in order to ensure we keep our CI times
395 "rustc-ap-rustc_ast",
398 for &name in FORBIDDEN_TO_HAVE_DUPLICATES {
399 let matches: Vec<_> = metadata.packages.iter().filter(|pkg| pkg.name == name).collect();
400 match matches.len() {
404 "crate `{}` is missing, update `check_crate_duplicate` \
405 if it is no longer used",
413 "crate `{}` is duplicated in `Cargo.lock`, \
414 it is too expensive to build multiple times, \
415 so make sure only one version appears across all dependencies",
419 println!(" * {}", pkg.id);
426 /// Returns a list of dependencies for the given package.
427 fn deps_of<'a>(metadata: &'a Metadata, pkg_id: &'a PackageId) -> Vec<&'a Package> {
428 let resolve = metadata.resolve.as_ref().unwrap();
432 .find(|n| &n.id == pkg_id)
433 .unwrap_or_else(|| panic!("could not find `{}` in resolve", pkg_id));
437 metadata.packages.iter().find(|pkg| pkg.id == dep.pkg).unwrap_or_else(|| {
438 panic!("could not find dep `{}` for pkg `{}` in resolve", dep.pkg, pkg_id)
444 /// Finds a package with the given name.
445 fn pkg_from_name<'a>(metadata: &'a Metadata, name: &'static str) -> &'a Package {
446 let mut i = metadata.packages.iter().filter(|p| p.name == name);
448 i.next().unwrap_or_else(|| panic!("could not find package `{}` in package list", name));
449 assert!(i.next().is_none(), "more than one package found for `{}`", name);
453 /// Finds all the packages that are in the rust runtime.
454 fn compute_runtime_crates<'a>(metadata: &'a Metadata) -> HashSet<&'a PackageId> {
455 let resolve = metadata.resolve.as_ref().unwrap();
456 let mut result = HashSet::new();
457 for name in RUNTIME_CRATES {
458 let id = &pkg_from_name(metadata, name).id;
459 normal_deps_of_r(resolve, id, &mut result);
464 /// Recursively find all normal dependencies.
465 fn normal_deps_of_r<'a>(
466 resolve: &'a Resolve,
467 pkg_id: &'a PackageId,
468 result: &mut HashSet<&'a PackageId>,
470 if !result.insert(pkg_id) {
476 .find(|n| &n.id == pkg_id)
477 .unwrap_or_else(|| panic!("could not find `{}` in resolve", pkg_id));
478 // Don't care about dev-dependencies.
479 // Build dependencies *shouldn't* matter unless they do some kind of
480 // codegen. For now we'll assume they don't.
481 let deps = node.deps.iter().filter(|node_dep| {
485 .any(|kind_info| kind_info.kind == cargo_metadata::DependencyKind::Normal)
488 normal_deps_of_r(resolve, &dep.pkg, result);