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