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