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