]> git.lizzy.rs Git - rust.git/blob - src/tools/tidy/src/deps.rs
ea6e01e577c6bfd3fa56740ce8d72c1a9a1a42ef
[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 ];
24
25 /// These are exceptions to Rust's permissive licensing policy, and
26 /// should be considered bugs. Exceptions are only allowed in Rust
27 /// tooling. It is _crucial_ that no exception crates be dependencies
28 /// of the Rust runtime (std/test).
29 const EXCEPTIONS: &[(&str, &str)] = &[
30     ("mdbook", "MPL-2.0"),            // mdbook
31     ("openssl", "Apache-2.0"),        // cargo, mdbook
32     ("colored", "MPL-2.0"),           // rustfmt
33     ("ordslice", "Apache-2.0"),       // rls
34     ("ryu", "Apache-2.0 OR BSL-1.0"), // rls/cargo/... (because of serde)
35     ("bytesize", "Apache-2.0"),       // cargo
36     ("im-rc", "MPL-2.0+"),            // cargo
37     ("sized-chunks", "MPL-2.0+"),     // cargo via im-rc
38     ("bitmaps", "MPL-2.0+"),          // cargo via im-rc
39     ("instant", "BSD-3-Clause"),      // rustc_driver/tracing-subscriber/parking_lot
40     ("snap", "BSD-3-Clause"),         // rustc
41     ("fluent-langneg", "Apache-2.0"), // rustc (fluent translations)
42     ("self_cell", "Apache-2.0"),      // rustc (fluent translations)
43     // FIXME: this dependency violates the documentation comment above:
44     ("fortanix-sgx-abi", "MPL-2.0"), // libstd but only for `sgx` target
45 ];
46
47 const EXCEPTIONS_CRANELIFT: &[(&str, &str)] = &[
48     ("cranelift-bforest", "Apache-2.0 WITH LLVM-exception"),
49     ("cranelift-codegen", "Apache-2.0 WITH LLVM-exception"),
50     ("cranelift-codegen-meta", "Apache-2.0 WITH LLVM-exception"),
51     ("cranelift-codegen-shared", "Apache-2.0 WITH LLVM-exception"),
52     ("cranelift-entity", "Apache-2.0 WITH LLVM-exception"),
53     ("cranelift-frontend", "Apache-2.0 WITH LLVM-exception"),
54     ("cranelift-jit", "Apache-2.0 WITH LLVM-exception"),
55     ("cranelift-module", "Apache-2.0 WITH LLVM-exception"),
56     ("cranelift-native", "Apache-2.0 WITH LLVM-exception"),
57     ("cranelift-object", "Apache-2.0 WITH LLVM-exception"),
58     ("mach", "BSD-2-Clause"),
59     ("regalloc", "Apache-2.0 WITH LLVM-exception"),
60     ("target-lexicon", "Apache-2.0 WITH LLVM-exception"),
61 ];
62
63 /// These are the root crates that are part of the runtime. The licenses for
64 /// these and all their dependencies *must not* be in the exception list.
65 const RUNTIME_CRATES: &[&str] = &["std", "core", "alloc", "test", "panic_abort", "panic_unwind"];
66
67 /// Crates whose dependencies must be explicitly permitted.
68 const RESTRICTED_DEPENDENCY_CRATES: &[&str] = &["rustc_driver", "rustc_codegen_llvm"];
69
70 /// Crates rustc is allowed to depend on. Avoid adding to the list if possible.
71 ///
72 /// This list is here to provide a speed-bump to adding a new dependency to
73 /// rustc. Please check with the compiler team before adding an entry.
74 const PERMITTED_DEPENDENCIES: &[&str] = &[
75     "addr2line",
76     "adler",
77     "ahash",
78     "aho-corasick",
79     "annotate-snippets",
80     "ansi_term",
81     "arrayvec",
82     "atty",
83     "autocfg",
84     "bitflags",
85     "block-buffer",
86     "block-padding",
87     "byte-tools",
88     "byteorder",
89     "cc",
90     "cfg-if",
91     "chalk-derive",
92     "chalk-engine",
93     "chalk-ir",
94     "chalk-solve",
95     "chrono",
96     "cmake",
97     "compiler_builtins",
98     "cpufeatures",
99     "crc32fast",
100     "crossbeam-deque",
101     "crossbeam-epoch",
102     "crossbeam-utils",
103     "crypto-common",
104     "cstr",
105     "datafrog",
106     "difference",
107     "digest",
108     "dlmalloc",
109     "either",
110     "ena",
111     "env_logger",
112     "expect-test",
113     "fake-simd",
114     "fallible-iterator", // dependency of `thorin`
115     "filetime",
116     "fixedbitset",
117     "flate2",
118     "fluent-bundle",
119     "fluent-langneg",
120     "fluent-syntax",
121     "fortanix-sgx-abi",
122     "generic-array",
123     "getopts",
124     "getrandom",
125     "gimli",
126     "gsgdt",
127     "hashbrown",
128     "hermit-abi",
129     "humantime",
130     "if_chain",
131     "indexmap",
132     "instant",
133     "intl-memoizer",
134     "intl_pluralrules",
135     "itertools",
136     "itoa",
137     "jobserver",
138     "lazy_static",
139     "libc",
140     "libloading",
141     "libz-sys",
142     "lock_api",
143     "log",
144     "matchers",
145     "md-5",
146     "measureme",
147     "memchr",
148     "memmap2",
149     "memoffset",
150     "miniz_oxide",
151     "num-integer",
152     "num-traits",
153     "num_cpus",
154     "object",
155     "odht",
156     "once_cell",
157     "opaque-debug",
158     "parking_lot",
159     "parking_lot_core",
160     "pathdiff",
161     "perf-event-open-sys",
162     "petgraph",
163     "pin-project-lite",
164     "pkg-config",
165     "polonius-engine",
166     "ppv-lite86",
167     "proc-macro-hack",
168     "proc-macro2",
169     "psm",
170     "punycode",
171     "quick-error",
172     "quote",
173     "rand",
174     "rand_chacha",
175     "rand_core",
176     "rand_hc",
177     "rand_pcg",
178     "rand_xorshift",
179     "rand_xoshiro",
180     "redox_syscall",
181     "regex",
182     "regex-automata",
183     "regex-syntax",
184     "remove_dir_all",
185     "rls-data",
186     "rls-span",
187     "rustc-demangle",
188     "rustc-hash",
189     "rustc-rayon",
190     "rustc-rayon-core",
191     "rustc_version",
192     "ryu",
193     "scoped-tls",
194     "scopeguard",
195     "self_cell",
196     "semver",
197     "serde",
198     "serde_derive",
199     "serde_json",
200     "sha-1",
201     "sha2",
202     "sharded-slab",
203     "smallvec",
204     "snap",
205     "stable_deref_trait",
206     "stacker",
207     "syn",
208     "synstructure",
209     "tempfile",
210     "termcolor",
211     "termize",
212     "thiserror",
213     "thiserror-impl",
214     "thorin-dwp",
215     "thread_local",
216     "time",
217     "tinystr",
218     "tinyvec",
219     "tracing",
220     "tracing-attributes",
221     "tracing-core",
222     "tracing-log",
223     "tracing-subscriber",
224     "tracing-tree",
225     "type-map",
226     "typenum",
227     "unic-char-property",
228     "unic-char-range",
229     "unic-common",
230     "unic-emoji-char",
231     "unic-langid",
232     "unic-langid-impl",
233     "unic-langid-macros",
234     "unic-langid-macros-impl",
235     "unic-ucd-version",
236     "unicode-normalization",
237     "unicode-script",
238     "unicode-security",
239     "unicode-width",
240     "unicode-xid",
241     "vcpkg",
242     "version_check",
243     "wasi",
244     "winapi",
245     "winapi-i686-pc-windows-gnu",
246     "winapi-util",
247     "winapi-x86_64-pc-windows-gnu",
248     // this is a false-positive: it's only used by rustfmt, but because it's enabled through a
249     // feature, tidy thinks it's used by rustc as well.
250     "yansi-term",
251 ];
252
253 const PERMITTED_CRANELIFT_DEPENDENCIES: &[&str] = &[
254     "anyhow",
255     "ar",
256     "autocfg",
257     "bitflags",
258     "cfg-if",
259     "cranelift-bforest",
260     "cranelift-codegen",
261     "cranelift-codegen-meta",
262     "cranelift-codegen-shared",
263     "cranelift-entity",
264     "cranelift-frontend",
265     "cranelift-jit",
266     "cranelift-module",
267     "cranelift-native",
268     "cranelift-object",
269     "crc32fast",
270     "gimli",
271     "hashbrown",
272     "indexmap",
273     "libc",
274     "libloading",
275     "log",
276     "mach",
277     "memchr",
278     "object",
279     "once_cell",
280     "regalloc",
281     "region",
282     "rustc-hash",
283     "smallvec",
284     "target-lexicon",
285     "winapi",
286     "winapi-i686-pc-windows-gnu",
287     "winapi-x86_64-pc-windows-gnu",
288 ];
289
290 const FORBIDDEN_TO_HAVE_DUPLICATES: &[&str] = &[
291     // These two crates take quite a long time to build, so don't allow two versions of them
292     // to accidentally sneak into our dependency graph, in order to ensure we keep our CI times
293     // under control.
294     "cargo",
295 ];
296
297 /// Dependency checks.
298 ///
299 /// `root` is path to the directory with the root `Cargo.toml` (for the workspace). `cargo` is path
300 /// to the cargo executable.
301 pub fn check(root: &Path, cargo: &Path, bad: &mut bool) {
302     let mut cmd = cargo_metadata::MetadataCommand::new();
303     cmd.cargo_path(cargo)
304         .manifest_path(root.join("Cargo.toml"))
305         .features(cargo_metadata::CargoOpt::AllFeatures);
306     let metadata = t!(cmd.exec());
307     let runtime_ids = compute_runtime_crates(&metadata);
308     check_exceptions(&metadata, EXCEPTIONS, runtime_ids, bad);
309     check_dependencies(&metadata, PERMITTED_DEPENDENCIES, RESTRICTED_DEPENDENCY_CRATES, bad);
310     check_crate_duplicate(&metadata, FORBIDDEN_TO_HAVE_DUPLICATES, bad);
311     check_rustfix(&metadata, bad);
312
313     // Check rustc_codegen_cranelift independently as it has it's own workspace.
314     let mut cmd = cargo_metadata::MetadataCommand::new();
315     cmd.cargo_path(cargo)
316         .manifest_path(root.join("compiler/rustc_codegen_cranelift/Cargo.toml"))
317         .features(cargo_metadata::CargoOpt::AllFeatures);
318     let metadata = t!(cmd.exec());
319     let runtime_ids = HashSet::new();
320     check_exceptions(&metadata, EXCEPTIONS_CRANELIFT, runtime_ids, bad);
321     check_dependencies(
322         &metadata,
323         PERMITTED_CRANELIFT_DEPENDENCIES,
324         &["rustc_codegen_cranelift"],
325         bad,
326     );
327     check_crate_duplicate(&metadata, &[], bad);
328 }
329
330 /// Check that all licenses are in the valid list in `LICENSES`.
331 ///
332 /// Packages listed in `EXCEPTIONS` are allowed for tools.
333 fn check_exceptions(
334     metadata: &Metadata,
335     exceptions: &[(&str, &str)],
336     runtime_ids: HashSet<&PackageId>,
337     bad: &mut bool,
338 ) {
339     // Validate the EXCEPTIONS list hasn't changed.
340     for (name, license) in exceptions {
341         // Check that the package actually exists.
342         if !metadata.packages.iter().any(|p| p.name == *name) {
343             tidy_error!(
344                 bad,
345                 "could not find exception package `{}`\n\
346                 Remove from EXCEPTIONS list if it is no longer used.",
347                 name
348             );
349         }
350         // Check that the license hasn't changed.
351         for pkg in metadata.packages.iter().filter(|p| p.name == *name) {
352             match &pkg.license {
353                 None => {
354                     tidy_error!(
355                         bad,
356                         "dependency exception `{}` does not declare a license expression",
357                         pkg.id
358                     );
359                 }
360                 Some(pkg_license) => {
361                     if pkg_license.as_str() != *license {
362                         println!("dependency exception `{name}` license has changed");
363                         println!("    previously `{license}` now `{pkg_license}`");
364                         println!("    update EXCEPTIONS for the new license");
365                         *bad = true;
366                     }
367                 }
368             }
369         }
370     }
371
372     let exception_names: Vec<_> = exceptions.iter().map(|(name, _license)| *name).collect();
373
374     // Check if any package does not have a valid license.
375     for pkg in &metadata.packages {
376         if pkg.source.is_none() {
377             // No need to check local packages.
378             continue;
379         }
380         if !runtime_ids.contains(&pkg.id) && exception_names.contains(&pkg.name.as_str()) {
381             continue;
382         }
383         let license = match &pkg.license {
384             Some(license) => license,
385             None => {
386                 tidy_error!(bad, "dependency `{}` does not define a license expression", pkg.id);
387                 continue;
388             }
389         };
390         if !LICENSES.contains(&license.as_str()) {
391             if pkg.name == "fortanix-sgx-abi" {
392                 // This is a specific exception because SGX is considered
393                 // "third party". See
394                 // https://github.com/rust-lang/rust/issues/62620 for more. In
395                 // general, these should never be added.
396                 continue;
397             }
398             tidy_error!(bad, "invalid license `{}` in `{}`", license, pkg.id);
399         }
400     }
401 }
402
403 /// Checks the dependency of `RESTRICTED_DEPENDENCY_CRATES` at the given path. Changes `bad` to
404 /// `true` if a check failed.
405 ///
406 /// Specifically, this checks that the dependencies are on the `PERMITTED_DEPENDENCIES`.
407 fn check_dependencies(
408     metadata: &Metadata,
409     permitted_dependencies: &[&'static str],
410     restricted_dependency_crates: &[&'static str],
411     bad: &mut bool,
412 ) {
413     // Check that the PERMITTED_DEPENDENCIES does not have unused entries.
414     for name in permitted_dependencies {
415         if !metadata.packages.iter().any(|p| p.name == *name) {
416             tidy_error!(
417                 bad,
418                 "could not find allowed package `{}`\n\
419                 Remove from PERMITTED_DEPENDENCIES list if it is no longer used.",
420                 name
421             );
422         }
423     }
424     // Get the list in a convenient form.
425     let permitted_dependencies: HashSet<_> = permitted_dependencies.iter().cloned().collect();
426
427     // Check dependencies.
428     let mut visited = BTreeSet::new();
429     let mut unapproved = BTreeSet::new();
430     for &krate in restricted_dependency_crates.iter() {
431         let pkg = pkg_from_name(metadata, krate);
432         let mut bad =
433             check_crate_dependencies(&permitted_dependencies, metadata, &mut visited, pkg);
434         unapproved.append(&mut bad);
435     }
436
437     if !unapproved.is_empty() {
438         tidy_error!(bad, "Dependencies not explicitly permitted:");
439         for dep in unapproved {
440             println!("* {dep}");
441         }
442     }
443 }
444
445 /// Checks the dependencies of the given crate from the given cargo metadata to see if they are on
446 /// the list of permitted dependencies. Returns a list of disallowed dependencies.
447 fn check_crate_dependencies<'a>(
448     permitted_dependencies: &'a HashSet<&'static str>,
449     metadata: &'a Metadata,
450     visited: &mut BTreeSet<&'a PackageId>,
451     krate: &'a Package,
452 ) -> BTreeSet<&'a PackageId> {
453     // This will contain bad deps.
454     let mut unapproved = BTreeSet::new();
455
456     // Check if we have already visited this crate.
457     if visited.contains(&krate.id) {
458         return unapproved;
459     }
460
461     visited.insert(&krate.id);
462
463     // If this path is in-tree, we don't require it to be explicitly permitted.
464     if krate.source.is_some() {
465         // If this dependency is not on `PERMITTED_DEPENDENCIES`, add to bad set.
466         if !permitted_dependencies.contains(krate.name.as_str()) {
467             unapproved.insert(&krate.id);
468         }
469     }
470
471     // Do a DFS in the crate graph.
472     let to_check = deps_of(metadata, &krate.id);
473
474     for dep in to_check {
475         let mut bad = check_crate_dependencies(permitted_dependencies, metadata, visited, dep);
476         unapproved.append(&mut bad);
477     }
478
479     unapproved
480 }
481
482 /// Prevents multiple versions of some expensive crates.
483 fn check_crate_duplicate(
484     metadata: &Metadata,
485     forbidden_to_have_duplicates: &[&str],
486     bad: &mut bool,
487 ) {
488     for &name in forbidden_to_have_duplicates {
489         let matches: Vec<_> = metadata.packages.iter().filter(|pkg| pkg.name == name).collect();
490         match matches.len() {
491             0 => {
492                 tidy_error!(
493                     bad,
494                     "crate `{}` is missing, update `check_crate_duplicate` \
495                     if it is no longer used",
496                     name
497                 );
498             }
499             1 => {}
500             _ => {
501                 tidy_error!(
502                     bad,
503                     "crate `{}` is duplicated in `Cargo.lock`, \
504                     it is too expensive to build multiple times, \
505                     so make sure only one version appears across all dependencies",
506                     name
507                 );
508                 for pkg in matches {
509                     println!("  * {}", pkg.id);
510                 }
511             }
512         }
513     }
514 }
515
516 /// Returns a list of dependencies for the given package.
517 fn deps_of<'a>(metadata: &'a Metadata, pkg_id: &'a PackageId) -> Vec<&'a Package> {
518     let resolve = metadata.resolve.as_ref().unwrap();
519     let node = resolve
520         .nodes
521         .iter()
522         .find(|n| &n.id == pkg_id)
523         .unwrap_or_else(|| panic!("could not find `{pkg_id}` in resolve"));
524     node.deps
525         .iter()
526         .map(|dep| {
527             metadata.packages.iter().find(|pkg| pkg.id == dep.pkg).unwrap_or_else(|| {
528                 panic!("could not find dep `{}` for pkg `{}` in resolve", dep.pkg, pkg_id)
529             })
530         })
531         .collect()
532 }
533
534 /// Finds a package with the given name.
535 fn pkg_from_name<'a>(metadata: &'a Metadata, name: &'static str) -> &'a Package {
536     let mut i = metadata.packages.iter().filter(|p| p.name == name);
537     let result =
538         i.next().unwrap_or_else(|| panic!("could not find package `{name}` in package list"));
539     assert!(i.next().is_none(), "more than one package found for `{name}`");
540     result
541 }
542
543 /// Finds all the packages that are in the rust runtime.
544 fn compute_runtime_crates<'a>(metadata: &'a Metadata) -> HashSet<&'a PackageId> {
545     let resolve = metadata.resolve.as_ref().unwrap();
546     let mut result = HashSet::new();
547     for name in RUNTIME_CRATES {
548         let id = &pkg_from_name(metadata, name).id;
549         normal_deps_of_r(resolve, id, &mut result);
550     }
551     result
552 }
553
554 /// Recursively find all normal dependencies.
555 fn normal_deps_of_r<'a>(
556     resolve: &'a Resolve,
557     pkg_id: &'a PackageId,
558     result: &mut HashSet<&'a PackageId>,
559 ) {
560     if !result.insert(pkg_id) {
561         return;
562     }
563     let node = resolve
564         .nodes
565         .iter()
566         .find(|n| &n.id == pkg_id)
567         .unwrap_or_else(|| panic!("could not find `{pkg_id}` in resolve"));
568     for dep in &node.deps {
569         normal_deps_of_r(resolve, &dep.pkg, result);
570     }
571 }
572
573 fn check_rustfix(metadata: &Metadata, bad: &mut bool) {
574     let cargo = pkg_from_name(metadata, "cargo");
575     let compiletest = pkg_from_name(metadata, "compiletest");
576     let cargo_deps = deps_of(metadata, &cargo.id);
577     let compiletest_deps = deps_of(metadata, &compiletest.id);
578     let cargo_rustfix = cargo_deps.iter().find(|p| p.name == "rustfix").unwrap();
579     let compiletest_rustfix = compiletest_deps.iter().find(|p| p.name == "rustfix").unwrap();
580     if cargo_rustfix.version != compiletest_rustfix.version {
581         tidy_error!(
582             bad,
583             "cargo's rustfix version {} does not match compiletest's rustfix version {}\n\
584              rustfix should be kept in sync, update the cargo side first, and then update \
585              compiletest along with cargo.",
586             cargo_rustfix.version,
587             compiletest_rustfix.version
588         );
589     }
590 }