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