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