]> git.lizzy.rs Git - rust.git/blob - src/tools/tidy/src/deps.rs
Rollup merge of #102239 - joshtriplett:style-guide, r=calebcartwright
[rust.git] / src / tools / tidy / src / deps.rs
1 //! Checks the licenses of third-party dependencies.
2
3 use cargo_metadata::{Metadata, Package, PackageId, Resolve};
4 use std::collections::{BTreeSet, HashSet};
5 use std::path::Path;
6
7 /// These are licenses that are allowed for all crates, including the runtime,
8 /// rustc, tools, etc.
9 const LICENSES: &[&str] = &[
10     "MIT/Apache-2.0",
11     "MIT / Apache-2.0",
12     "Apache-2.0/MIT",
13     "Apache-2.0 / MIT",
14     "MIT OR Apache-2.0",
15     "Apache-2.0 OR MIT",
16     "Apache-2.0 WITH LLVM-exception OR Apache-2.0 OR MIT", // wasi license
17     "MIT",
18     "ISC",
19     "Unlicense/MIT",
20     "Unlicense OR MIT",
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
26 ];
27
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)
50 ];
51
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"),
67 ];
68
69 const EXCEPTIONS_BOOTSTRAP: &[(&str, &str)] = &[
70     ("ryu", "Apache-2.0 OR BSL-1.0"), // through serde
71 ];
72
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"];
76
77 /// Crates rustc is allowed to depend on. Avoid adding to the list if possible.
78 ///
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] = &[
82     "addr2line",
83     "adler",
84     "ahash",
85     "aho-corasick",
86     "annotate-snippets",
87     "ansi_term",
88     "arrayvec",
89     "atty",
90     "autocfg",
91     "bitflags",
92     "block-buffer",
93     "cc",
94     "cfg-if",
95     "chalk-derive",
96     "chalk-engine",
97     "chalk-ir",
98     "chalk-solve",
99     "chrono",
100     "compiler_builtins",
101     "cpufeatures",
102     "crc32fast",
103     "crossbeam-channel",
104     "crossbeam-deque",
105     "crossbeam-epoch",
106     "crossbeam-utils",
107     "crypto-common",
108     "cstr",
109     "datafrog",
110     "difference",
111     "digest",
112     "dlmalloc",
113     "either",
114     "ena",
115     "env_logger",
116     "expect-test",
117     "fallible-iterator", // dependency of `thorin`
118     "filetime",
119     "fixedbitset",
120     "flate2",
121     "fluent-bundle",
122     "fluent-langneg",
123     "fluent-syntax",
124     "fortanix-sgx-abi",
125     "generic-array",
126     "getopts",
127     "getrandom",
128     "gimli",
129     "gsgdt",
130     "hashbrown",
131     "hermit-abi",
132     "humantime",
133     "if_chain",
134     "indexmap",
135     "instant",
136     "intl-memoizer",
137     "intl_pluralrules",
138     "itertools",
139     "itoa",
140     "jobserver",
141     "lazy_static",
142     "libc",
143     "libloading",
144     "libz-sys",
145     "lock_api",
146     "log",
147     "matchers",
148     "md-5",
149     "measureme",
150     "memchr",
151     "memmap2",
152     "memoffset",
153     "miniz_oxide",
154     "num-integer",
155     "num-traits",
156     "num_cpus",
157     "object",
158     "odht",
159     "once_cell",
160     "parking_lot",
161     "parking_lot_core",
162     "pathdiff",
163     "perf-event-open-sys",
164     "petgraph",
165     "pin-project-lite",
166     "pkg-config",
167     "polonius-engine",
168     "ppv-lite86",
169     "proc-macro-hack",
170     "proc-macro2",
171     "psm",
172     "punycode",
173     "quick-error",
174     "quote",
175     "rand",
176     "rand_chacha",
177     "rand_core",
178     "rand_hc",
179     "rand_xorshift",
180     "rand_xoshiro",
181     "redox_syscall",
182     "regex",
183     "regex-automata",
184     "regex-syntax",
185     "remove_dir_all",
186     "rls-data",
187     "rls-span",
188     "rustc-demangle",
189     "rustc-hash",
190     "rustc-rayon",
191     "rustc-rayon-core",
192     "rustc_version",
193     "ryu",
194     "scoped-tls",
195     "scopeguard",
196     "self_cell",
197     "semver",
198     "serde",
199     "serde_derive",
200     "serde_json",
201     "sha-1",
202     "sha2",
203     "sharded-slab",
204     "smallvec",
205     "snap",
206     "stable_deref_trait",
207     "stacker",
208     "syn",
209     "synstructure",
210     "tempfile",
211     "termcolor",
212     "termize",
213     "thiserror",
214     "thiserror-impl",
215     "thorin-dwp",
216     "thread_local",
217     "time",
218     "tinystr",
219     "tinyvec",
220     "tinyvec_macros",
221     "thin-vec",
222     "tracing",
223     "tracing-attributes",
224     "tracing-core",
225     "tracing-log",
226     "tracing-subscriber",
227     "tracing-tree",
228     "type-map",
229     "typenum",
230     "unic-char-property",
231     "unic-char-range",
232     "unic-common",
233     "unic-emoji-char",
234     "unic-langid",
235     "unic-langid-impl",
236     "unic-langid-macros",
237     "unic-langid-macros-impl",
238     "unic-ucd-version",
239     "unicode-ident",
240     "unicode-normalization",
241     "unicode-script",
242     "unicode-security",
243     "unicode-width",
244     "unicode-xid",
245     "vcpkg",
246     "valuable",
247     "version_check",
248     "wasi",
249     "winapi",
250     "winapi-i686-pc-windows-gnu",
251     "winapi-util",
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.
255     "yansi-term",
256 ];
257
258 const PERMITTED_CRANELIFT_DEPENDENCIES: &[&str] = &[
259     "ahash",
260     "anyhow",
261     "ar",
262     "autocfg",
263     "bitflags",
264     "byteorder",
265     "cfg-if",
266     "cranelift-bforest",
267     "cranelift-codegen",
268     "cranelift-codegen-meta",
269     "cranelift-codegen-shared",
270     "cranelift-entity",
271     "cranelift-frontend",
272     "cranelift-isle",
273     "cranelift-jit",
274     "cranelift-module",
275     "cranelift-native",
276     "cranelift-object",
277     "crc32fast",
278     "fxhash",
279     "getrandom",
280     "gimli",
281     "hashbrown",
282     "indexmap",
283     "libc",
284     "libloading",
285     "log",
286     "mach",
287     "memchr",
288     "object",
289     "once_cell",
290     "regalloc2",
291     "region",
292     "slice-group-by",
293     "smallvec",
294     "target-lexicon",
295     "version_check",
296     "wasi",
297     "winapi",
298     "winapi-i686-pc-windows-gnu",
299     "winapi-x86_64-pc-windows-gnu",
300     "windows-sys",
301     "windows_aarch64_msvc",
302     "windows_i686_gnu",
303     "windows_i686_msvc",
304     "windows_x86_64_gnu",
305     "windows_x86_64_msvc",
306 ];
307
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
311     // under control.
312     "cargo",
313 ];
314
315 /// Dependency checks.
316 ///
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(
328         &metadata,
329         "rustc",
330         PERMITTED_RUSTC_DEPENDENCIES,
331         &["rustc_driver", "rustc_codegen_llvm"],
332         bad,
333     );
334     check_crate_duplicate(&metadata, FORBIDDEN_TO_HAVE_DUPLICATES, bad);
335     check_rustfix(&metadata, bad);
336
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(
346         &metadata,
347         "cranelift",
348         PERMITTED_CRANELIFT_DEPENDENCIES,
349         &["rustc_codegen_cranelift"],
350         bad,
351     );
352     check_crate_duplicate(&metadata, &[], bad);
353
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);
361 }
362
363 /// Check that all licenses are in the valid list in `LICENSES`.
364 ///
365 /// Packages listed in `exceptions` are allowed for tools.
366 fn check_license_exceptions(
367     metadata: &Metadata,
368     exceptions: &[(&str, &str)],
369     runtime_ids: HashSet<&PackageId>,
370     bad: &mut bool,
371 ) {
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) {
376             tidy_error!(
377                 bad,
378                 "could not find exception package `{}`\n\
379                 Remove from EXCEPTIONS list if it is no longer used.",
380                 name
381             );
382         }
383         // Check that the license hasn't changed.
384         for pkg in metadata.packages.iter().filter(|p| p.name == *name) {
385             match &pkg.license {
386                 None => {
387                     tidy_error!(
388                         bad,
389                         "dependency exception `{}` does not declare a license expression",
390                         pkg.id
391                     );
392                 }
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");
398                         *bad = true;
399                     }
400                 }
401             }
402         }
403     }
404
405     let exception_names: Vec<_> = exceptions.iter().map(|(name, _license)| *name).collect();
406
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.
411             continue;
412         }
413         if !runtime_ids.contains(&pkg.id) && exception_names.contains(&pkg.name.as_str()) {
414             continue;
415         }
416         let license = match &pkg.license {
417             Some(license) => license,
418             None => {
419                 tidy_error!(bad, "dependency `{}` does not define a license expression", pkg.id);
420                 continue;
421             }
422         };
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.
429                 continue;
430             }
431             tidy_error!(bad, "invalid license `{}` in `{}`", license, pkg.id);
432         }
433     }
434 }
435
436 /// Checks the dependency of `restricted_dependency_crates` at the given path. Changes `bad` to
437 /// `true` if a check failed.
438 ///
439 /// Specifically, this checks that the dependencies are on the `permitted_dependencies`.
440 fn check_permitted_dependencies(
441     metadata: &Metadata,
442     descr: &str,
443     permitted_dependencies: &[&'static str],
444     restricted_dependency_crates: &[&'static str],
445     bad: &mut bool,
446 ) {
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) {
450             tidy_error!(
451                 bad,
452                 "could not find allowed package `{}`\n\
453                 Remove from PERMITTED_DEPENDENCIES list if it is no longer used.",
454                 name
455             );
456         }
457     }
458     // Get the list in a convenient form.
459     let permitted_dependencies: HashSet<_> = permitted_dependencies.iter().cloned().collect();
460
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);
466         let mut bad =
467             check_crate_dependencies(&permitted_dependencies, metadata, &mut visited, pkg);
468         unapproved.append(&mut bad);
469     }
470
471     if !unapproved.is_empty() {
472         tidy_error!(bad, "Dependencies for {} not explicitly permitted:", descr);
473         for dep in unapproved {
474             println!("* {dep}");
475         }
476     }
477 }
478
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>,
485     krate: &'a Package,
486 ) -> BTreeSet<&'a PackageId> {
487     // This will contain bad deps.
488     let mut unapproved = BTreeSet::new();
489
490     // Check if we have already visited this crate.
491     if visited.contains(&krate.id) {
492         return unapproved;
493     }
494
495     visited.insert(&krate.id);
496
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);
502         }
503     }
504
505     // Do a DFS in the crate graph.
506     let to_check = deps_of(metadata, &krate.id);
507
508     for dep in to_check {
509         let mut bad = check_crate_dependencies(permitted_dependencies, metadata, visited, dep);
510         unapproved.append(&mut bad);
511     }
512
513     unapproved
514 }
515
516 /// Prevents multiple versions of some expensive crates.
517 fn check_crate_duplicate(
518     metadata: &Metadata,
519     forbidden_to_have_duplicates: &[&str],
520     bad: &mut bool,
521 ) {
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() {
525             0 => {
526                 tidy_error!(
527                     bad,
528                     "crate `{}` is missing, update `check_crate_duplicate` \
529                     if it is no longer used",
530                     name
531                 );
532             }
533             1 => {}
534             _ => {
535                 tidy_error!(
536                     bad,
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",
540                     name
541                 );
542                 for pkg in matches {
543                     println!("  * {}", pkg.id);
544                 }
545             }
546         }
547     }
548 }
549
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();
553     let node = resolve
554         .nodes
555         .iter()
556         .find(|n| &n.id == pkg_id)
557         .unwrap_or_else(|| panic!("could not find `{pkg_id}` in resolve"));
558     node.deps
559         .iter()
560         .map(|dep| {
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)
563             })
564         })
565         .collect()
566 }
567
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);
571     let result =
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}`");
574     result
575 }
576
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);
584     }
585     result
586 }
587
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>,
593 ) {
594     if !result.insert(pkg_id) {
595         return;
596     }
597     let node = resolve
598         .nodes
599         .iter()
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);
604     }
605 }
606
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 {
615         tidy_error!(
616             bad,
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
622         );
623     }
624 }