]> git.lizzy.rs Git - rust.git/blob - src/tools/tidy/src/deps.rs
Rollup merge of #102323 - Stoozy:master, r=cjgillot
[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 ];
26
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)
49 ];
50
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"),
66 ];
67
68 const EXCEPTIONS_BOOTSTRAP: &[(&str, &str)] = &[
69     ("ryu", "Apache-2.0 OR BSL-1.0"), // through serde
70 ];
71
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"];
75
76 /// Crates rustc is allowed to depend on. Avoid adding to the list if possible.
77 ///
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] = &[
81     "addr2line",
82     "adler",
83     "ahash",
84     "aho-corasick",
85     "annotate-snippets",
86     "ansi_term",
87     "arrayvec",
88     "atty",
89     "autocfg",
90     "bitflags",
91     "block-buffer",
92     "cc",
93     "cfg-if",
94     "chalk-derive",
95     "chalk-engine",
96     "chalk-ir",
97     "chalk-solve",
98     "chrono",
99     "compiler_builtins",
100     "cpufeatures",
101     "crc32fast",
102     "crossbeam-channel",
103     "crossbeam-deque",
104     "crossbeam-epoch",
105     "crossbeam-utils",
106     "crypto-common",
107     "cstr",
108     "datafrog",
109     "difference",
110     "digest",
111     "dlmalloc",
112     "either",
113     "ena",
114     "env_logger",
115     "expect-test",
116     "fallible-iterator", // dependency of `thorin`
117     "filetime",
118     "fixedbitset",
119     "flate2",
120     "fluent-bundle",
121     "fluent-langneg",
122     "fluent-syntax",
123     "fortanix-sgx-abi",
124     "generic-array",
125     "getopts",
126     "getrandom",
127     "gimli",
128     "gsgdt",
129     "hashbrown",
130     "hermit-abi",
131     "humantime",
132     "if_chain",
133     "indexmap",
134     "instant",
135     "intl-memoizer",
136     "intl_pluralrules",
137     "itertools",
138     "itoa",
139     "jobserver",
140     "lazy_static",
141     "libc",
142     "libloading",
143     "libz-sys",
144     "lock_api",
145     "log",
146     "matchers",
147     "md-5",
148     "measureme",
149     "memchr",
150     "memmap2",
151     "memoffset",
152     "miniz_oxide",
153     "num-integer",
154     "num-traits",
155     "num_cpus",
156     "object",
157     "odht",
158     "once_cell",
159     "parking_lot",
160     "parking_lot_core",
161     "pathdiff",
162     "perf-event-open-sys",
163     "petgraph",
164     "pin-project-lite",
165     "pkg-config",
166     "polonius-engine",
167     "ppv-lite86",
168     "proc-macro-hack",
169     "proc-macro2",
170     "psm",
171     "punycode",
172     "quick-error",
173     "quote",
174     "rand",
175     "rand_chacha",
176     "rand_core",
177     "rand_hc",
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     "tinyvec_macros",
220     "thin-vec",
221     "tracing",
222     "tracing-attributes",
223     "tracing-core",
224     "tracing-log",
225     "tracing-subscriber",
226     "tracing-tree",
227     "type-map",
228     "typenum",
229     "unic-char-property",
230     "unic-char-range",
231     "unic-common",
232     "unic-emoji-char",
233     "unic-langid",
234     "unic-langid-impl",
235     "unic-langid-macros",
236     "unic-langid-macros-impl",
237     "unic-ucd-version",
238     "unicode-normalization",
239     "unicode-script",
240     "unicode-security",
241     "unicode-width",
242     "unicode-xid",
243     "vcpkg",
244     "valuable",
245     "version_check",
246     "wasi",
247     "winapi",
248     "winapi-i686-pc-windows-gnu",
249     "winapi-util",
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.
253     "yansi-term",
254 ];
255
256 const PERMITTED_CRANELIFT_DEPENDENCIES: &[&str] = &[
257     "ahash",
258     "anyhow",
259     "ar",
260     "autocfg",
261     "bitflags",
262     "byteorder",
263     "cfg-if",
264     "cranelift-bforest",
265     "cranelift-codegen",
266     "cranelift-codegen-meta",
267     "cranelift-codegen-shared",
268     "cranelift-entity",
269     "cranelift-frontend",
270     "cranelift-isle",
271     "cranelift-jit",
272     "cranelift-module",
273     "cranelift-native",
274     "cranelift-object",
275     "crc32fast",
276     "fxhash",
277     "getrandom",
278     "gimli",
279     "hashbrown",
280     "indexmap",
281     "libc",
282     "libloading",
283     "log",
284     "mach",
285     "memchr",
286     "object",
287     "once_cell",
288     "regalloc2",
289     "region",
290     "slice-group-by",
291     "smallvec",
292     "target-lexicon",
293     "version_check",
294     "wasi",
295     "winapi",
296     "winapi-i686-pc-windows-gnu",
297     "winapi-x86_64-pc-windows-gnu",
298     "windows-sys",
299     "windows_aarch64_msvc",
300     "windows_i686_gnu",
301     "windows_i686_msvc",
302     "windows_x86_64_gnu",
303     "windows_x86_64_msvc",
304 ];
305
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
309     // under control.
310     "cargo",
311 ];
312
313 /// Dependency checks.
314 ///
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(
326         &metadata,
327         "rustc",
328         PERMITTED_RUSTC_DEPENDENCIES,
329         &["rustc_driver", "rustc_codegen_llvm"],
330         bad,
331     );
332     check_crate_duplicate(&metadata, FORBIDDEN_TO_HAVE_DUPLICATES, bad);
333     check_rustfix(&metadata, bad);
334
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(
344         &metadata,
345         "cranelift",
346         PERMITTED_CRANELIFT_DEPENDENCIES,
347         &["rustc_codegen_cranelift"],
348         bad,
349     );
350     check_crate_duplicate(&metadata, &[], bad);
351
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);
359 }
360
361 /// Check that all licenses are in the valid list in `LICENSES`.
362 ///
363 /// Packages listed in `exceptions` are allowed for tools.
364 fn check_license_exceptions(
365     metadata: &Metadata,
366     exceptions: &[(&str, &str)],
367     runtime_ids: HashSet<&PackageId>,
368     bad: &mut bool,
369 ) {
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) {
374             tidy_error!(
375                 bad,
376                 "could not find exception package `{}`\n\
377                 Remove from EXCEPTIONS list if it is no longer used.",
378                 name
379             );
380         }
381         // Check that the license hasn't changed.
382         for pkg in metadata.packages.iter().filter(|p| p.name == *name) {
383             match &pkg.license {
384                 None => {
385                     tidy_error!(
386                         bad,
387                         "dependency exception `{}` does not declare a license expression",
388                         pkg.id
389                     );
390                 }
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");
396                         *bad = true;
397                     }
398                 }
399             }
400         }
401     }
402
403     let exception_names: Vec<_> = exceptions.iter().map(|(name, _license)| *name).collect();
404
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.
409             continue;
410         }
411         if !runtime_ids.contains(&pkg.id) && exception_names.contains(&pkg.name.as_str()) {
412             continue;
413         }
414         let license = match &pkg.license {
415             Some(license) => license,
416             None => {
417                 tidy_error!(bad, "dependency `{}` does not define a license expression", pkg.id);
418                 continue;
419             }
420         };
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.
427                 continue;
428             }
429             tidy_error!(bad, "invalid license `{}` in `{}`", license, pkg.id);
430         }
431     }
432 }
433
434 /// Checks the dependency of `restricted_dependency_crates` at the given path. Changes `bad` to
435 /// `true` if a check failed.
436 ///
437 /// Specifically, this checks that the dependencies are on the `permitted_dependencies`.
438 fn check_permitted_dependencies(
439     metadata: &Metadata,
440     descr: &str,
441     permitted_dependencies: &[&'static str],
442     restricted_dependency_crates: &[&'static str],
443     bad: &mut bool,
444 ) {
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) {
448             tidy_error!(
449                 bad,
450                 "could not find allowed package `{}`\n\
451                 Remove from PERMITTED_DEPENDENCIES list if it is no longer used.",
452                 name
453             );
454         }
455     }
456     // Get the list in a convenient form.
457     let permitted_dependencies: HashSet<_> = permitted_dependencies.iter().cloned().collect();
458
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);
464         let mut bad =
465             check_crate_dependencies(&permitted_dependencies, metadata, &mut visited, pkg);
466         unapproved.append(&mut bad);
467     }
468
469     if !unapproved.is_empty() {
470         tidy_error!(bad, "Dependencies for {} not explicitly permitted:", descr);
471         for dep in unapproved {
472             println!("* {dep}");
473         }
474     }
475 }
476
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>,
483     krate: &'a Package,
484 ) -> BTreeSet<&'a PackageId> {
485     // This will contain bad deps.
486     let mut unapproved = BTreeSet::new();
487
488     // Check if we have already visited this crate.
489     if visited.contains(&krate.id) {
490         return unapproved;
491     }
492
493     visited.insert(&krate.id);
494
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);
500         }
501     }
502
503     // Do a DFS in the crate graph.
504     let to_check = deps_of(metadata, &krate.id);
505
506     for dep in to_check {
507         let mut bad = check_crate_dependencies(permitted_dependencies, metadata, visited, dep);
508         unapproved.append(&mut bad);
509     }
510
511     unapproved
512 }
513
514 /// Prevents multiple versions of some expensive crates.
515 fn check_crate_duplicate(
516     metadata: &Metadata,
517     forbidden_to_have_duplicates: &[&str],
518     bad: &mut bool,
519 ) {
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() {
523             0 => {
524                 tidy_error!(
525                     bad,
526                     "crate `{}` is missing, update `check_crate_duplicate` \
527                     if it is no longer used",
528                     name
529                 );
530             }
531             1 => {}
532             _ => {
533                 tidy_error!(
534                     bad,
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",
538                     name
539                 );
540                 for pkg in matches {
541                     println!("  * {}", pkg.id);
542                 }
543             }
544         }
545     }
546 }
547
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();
551     let node = resolve
552         .nodes
553         .iter()
554         .find(|n| &n.id == pkg_id)
555         .unwrap_or_else(|| panic!("could not find `{pkg_id}` in resolve"));
556     node.deps
557         .iter()
558         .map(|dep| {
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)
561             })
562         })
563         .collect()
564 }
565
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);
569     let result =
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}`");
572     result
573 }
574
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);
582     }
583     result
584 }
585
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>,
591 ) {
592     if !result.insert(pkg_id) {
593         return;
594     }
595     let node = resolve
596         .nodes
597         .iter()
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);
602     }
603 }
604
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 {
613         tidy_error!(
614             bad,
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
620         );
621     }
622 }