]> git.lizzy.rs Git - rust.git/blob - src/tools/tidy/src/deps.rs
Remove mdbook-linkcheck.
[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 ];
21
22 /// These are exceptions to Rust's permissive licensing policy, and
23 /// should be considered bugs. Exceptions are only allowed in Rust
24 /// tooling. It is _crucial_ that no exception crates be dependencies
25 /// of the Rust runtime (std/test).
26 const EXCEPTIONS: &[(&str, &str)] = &[
27     ("mdbook", "MPL-2.0"),                  // mdbook
28     ("openssl", "Apache-2.0"),              // cargo, mdbook
29     ("toml-query", "MPL-2.0"),              // mdbook
30     ("toml-query_derive", "MPL-2.0"),       // mdbook
31     ("is-match", "MPL-2.0"),                // mdbook
32     ("rdrand", "ISC"),                      // mdbook, rustfmt
33     ("fuchsia-cprng", "BSD-3-Clause"),      // mdbook, rustfmt
34     ("fuchsia-zircon-sys", "BSD-3-Clause"), // rustdoc, rustc, cargo
35     ("fuchsia-zircon", "BSD-3-Clause"),     // rustdoc, rustc, cargo (jobserver & tempdir)
36     ("colored", "MPL-2.0"),                 // rustfmt
37     ("ordslice", "Apache-2.0"),             // rls
38     ("cloudabi", "BSD-2-Clause"),           // (rls -> crossbeam-channel 0.2 -> rand 0.5)
39     ("ryu", "Apache-2.0 OR BSL-1.0"),       // rls/cargo/... (because of serde)
40     ("bytesize", "Apache-2.0"),             // cargo
41     ("im-rc", "MPL-2.0+"),                  // cargo
42     ("adler32", "BSD-3-Clause AND Zlib"),   // cargo dep that isn't used
43     ("constant_time_eq", "CC0-1.0"),        // rustfmt
44     ("sized-chunks", "MPL-2.0+"),           // cargo via im-rc
45     ("bitmaps", "MPL-2.0+"),                // cargo via im-rc
46     // FIXME: this dependency violates the documentation comment above:
47     ("fortanix-sgx-abi", "MPL-2.0"), // libstd but only for `sgx` target
48     ("crossbeam-channel", "MIT/Apache-2.0 AND BSD-2-Clause"), // cargo
49 ];
50
51 /// These are the root crates that are part of the runtime. The licenses for
52 /// these and all their dependencies *must not* be in the exception list.
53 const RUNTIME_CRATES: &[&str] = &["std", "core", "alloc", "test", "panic_abort", "panic_unwind"];
54
55 /// Which crates to check against the whitelist?
56 const WHITELIST_CRATES: &[&str] = &["rustc_middle", "rustc_codegen_llvm"];
57
58 /// Whitelist of crates rustc is allowed to depend on. Avoid adding to the list if possible.
59 ///
60 /// This list is here to provide a speed-bump to adding a new dependency to
61 /// rustc. Please check with the compiler team before adding an entry.
62 const WHITELIST: &[&str] = &[
63     "adler32",
64     "aho-corasick",
65     "annotate-snippets",
66     "ansi_term",
67     "arrayvec",
68     "atty",
69     "autocfg",
70     "backtrace",
71     "backtrace-sys",
72     "bitflags",
73     "block-buffer",
74     "block-padding",
75     "byte-tools",
76     "byteorder",
77     "cc",
78     "cfg-if",
79     "chalk-derive",
80     "chalk-ir",
81     "cloudabi",
82     "cmake",
83     "compiler_builtins",
84     "crc32fast",
85     "crossbeam-deque",
86     "crossbeam-epoch",
87     "crossbeam-queue",
88     "crossbeam-utils",
89     "datafrog",
90     "digest",
91     "dlmalloc",
92     "either",
93     "ena",
94     "env_logger",
95     "fake-simd",
96     "filetime",
97     "flate2",
98     "fortanix-sgx-abi",
99     "fuchsia-zircon",
100     "fuchsia-zircon-sys",
101     "generic-array",
102     "getopts",
103     "getrandom",
104     "hashbrown",
105     "hermit-abi",
106     "humantime",
107     "indexmap",
108     "itertools",
109     "jobserver",
110     "kernel32-sys",
111     "lazy_static",
112     "libc",
113     "libz-sys",
114     "lock_api",
115     "log",
116     "log_settings",
117     "md-5",
118     "measureme",
119     "memchr",
120     "memmap",
121     "memoffset",
122     "miniz_oxide",
123     "nodrop",
124     "num_cpus",
125     "once_cell",
126     "opaque-debug",
127     "parking_lot",
128     "parking_lot_core",
129     "pkg-config",
130     "polonius-engine",
131     "ppv-lite86",
132     "proc-macro2",
133     "psm",
134     "punycode",
135     "quick-error",
136     "quote",
137     "rand",
138     "rand_chacha",
139     "rand_core",
140     "rand_hc",
141     "rand_isaac",
142     "rand_pcg",
143     "rand_xorshift",
144     "redox_syscall",
145     "regex",
146     "regex-syntax",
147     "remove_dir_all",
148     "rustc-demangle",
149     "rustc-hash",
150     "rustc-rayon",
151     "rustc-rayon-core",
152     "rustc_version",
153     "scoped-tls",
154     "scopeguard",
155     "semver",
156     "semver-parser",
157     "serde",
158     "serde_derive",
159     "sha-1",
160     "smallvec",
161     "stable_deref_trait",
162     "stacker",
163     "syn",
164     "synstructure",
165     "tempfile",
166     "termcolor",
167     "termize",
168     "thread_local",
169     "typenum",
170     "unicode-normalization",
171     "unicode-script",
172     "unicode-security",
173     "unicode-width",
174     "unicode-xid",
175     "vcpkg",
176     "version_check",
177     "wasi",
178     "winapi",
179     "winapi-build",
180     "winapi-i686-pc-windows-gnu",
181     "winapi-util",
182     "winapi-x86_64-pc-windows-gnu",
183     "wincolor",
184 ];
185
186 /// Dependency checks.
187 ///
188 /// `path` is path to the `src` directory, `cargo` is path to the cargo executable.
189 pub fn check(path: &Path, cargo: &Path, bad: &mut bool) {
190     let mut cmd = cargo_metadata::MetadataCommand::new();
191     cmd.cargo_path(cargo)
192         .manifest_path(path.parent().unwrap().join("Cargo.toml"))
193         .features(cargo_metadata::CargoOpt::AllFeatures);
194     let metadata = t!(cmd.exec());
195     check_exceptions(&metadata, bad);
196     check_whitelist(&metadata, bad);
197     check_crate_duplicate(&metadata, bad);
198 }
199
200 /// Check that all licenses are in the valid list in `LICENSES`.
201 ///
202 /// Packages listed in `EXCEPTIONS` are allowed for tools.
203 fn check_exceptions(metadata: &Metadata, bad: &mut bool) {
204     // Validate the EXCEPTIONS list hasn't changed.
205     for (name, license) in EXCEPTIONS {
206         // Check that the package actually exists.
207         if !metadata.packages.iter().any(|p| p.name == *name) {
208             println!(
209                 "could not find exception package `{}`\n\
210                 Remove from EXCEPTIONS list if it is no longer used.",
211                 name
212             );
213             *bad = true;
214         }
215         // Check that the license hasn't changed.
216         for pkg in metadata.packages.iter().filter(|p| p.name == *name) {
217             if pkg.name == "fuchsia-cprng" {
218                 // This package doesn't declare a license expression. Manual
219                 // inspection of the license file is necessary, which appears
220                 // to be BSD-3-Clause.
221                 assert!(pkg.license.is_none());
222                 continue;
223             }
224             match &pkg.license {
225                 None => {
226                     println!(
227                         "dependency exception `{}` does not declare a license expression",
228                         pkg.id
229                     );
230                     *bad = true;
231                 }
232                 Some(pkg_license) => {
233                     if pkg_license.as_str() != *license {
234                         println!("dependency exception `{}` license has changed", name);
235                         println!("    previously `{}` now `{}`", license, pkg_license);
236                         println!("    update EXCEPTIONS for the new license");
237                         *bad = true;
238                     }
239                 }
240             }
241         }
242     }
243
244     let exception_names: Vec<_> = EXCEPTIONS.iter().map(|(name, _license)| *name).collect();
245     let runtime_ids = compute_runtime_crates(metadata);
246
247     // Check if any package does not have a valid license.
248     for pkg in &metadata.packages {
249         if pkg.source.is_none() {
250             // No need to check local packages.
251             continue;
252         }
253         if !runtime_ids.contains(&pkg.id) && exception_names.contains(&pkg.name.as_str()) {
254             continue;
255         }
256         let license = match &pkg.license {
257             Some(license) => license,
258             None => {
259                 println!("dependency `{}` does not define a license expression", pkg.id,);
260                 *bad = true;
261                 continue;
262             }
263         };
264         if !LICENSES.contains(&license.as_str()) {
265             if pkg.name == "fortanix-sgx-abi" {
266                 // This is a specific exception because SGX is considered
267                 // "third party". See
268                 // https://github.com/rust-lang/rust/issues/62620 for more. In
269                 // general, these should never be added.
270                 continue;
271             }
272             println!("invalid license `{}` in `{}`", license, pkg.id);
273             *bad = true;
274         }
275     }
276 }
277
278 /// Checks the dependency of `WHITELIST_CRATES` at the given path. Changes `bad` to `true` if a
279 /// check failed.
280 ///
281 /// Specifically, this checks that the dependencies are on the `WHITELIST`.
282 fn check_whitelist(metadata: &Metadata, bad: &mut bool) {
283     // Check that the WHITELIST does not have unused entries.
284     for name in WHITELIST {
285         if !metadata.packages.iter().any(|p| p.name == *name) {
286             println!(
287                 "could not find whitelisted package `{}`\n\
288                 Remove from WHITELIST list if it is no longer used.",
289                 name
290             );
291             *bad = true;
292         }
293     }
294     // Get the whitelist in a convenient form.
295     let whitelist: HashSet<_> = WHITELIST.iter().cloned().collect();
296
297     // Check dependencies.
298     let mut visited = BTreeSet::new();
299     let mut unapproved = BTreeSet::new();
300     for &krate in WHITELIST_CRATES.iter() {
301         let pkg = pkg_from_name(metadata, krate);
302         let mut bad = check_crate_whitelist(&whitelist, metadata, &mut visited, pkg);
303         unapproved.append(&mut bad);
304     }
305
306     if !unapproved.is_empty() {
307         println!("Dependencies not on the whitelist:");
308         for dep in unapproved {
309             println!("* {}", dep);
310         }
311         *bad = true;
312     }
313 }
314
315 /// Checks the dependencies of the given crate from the given cargo metadata to see if they are on
316 /// the whitelist. Returns a list of illegal dependencies.
317 fn check_crate_whitelist<'a>(
318     whitelist: &'a HashSet<&'static str>,
319     metadata: &'a Metadata,
320     visited: &mut BTreeSet<&'a PackageId>,
321     krate: &'a Package,
322 ) -> BTreeSet<&'a PackageId> {
323     // This will contain bad deps.
324     let mut unapproved = BTreeSet::new();
325
326     // Check if we have already visited this crate.
327     if visited.contains(&krate.id) {
328         return unapproved;
329     }
330
331     visited.insert(&krate.id);
332
333     // If this path is in-tree, we don't require it to be on the whitelist.
334     if krate.source.is_some() {
335         // If this dependency is not on `WHITELIST`, add to bad set.
336         if !whitelist.contains(krate.name.as_str()) {
337             unapproved.insert(&krate.id);
338         }
339     }
340
341     // Do a DFS in the crate graph.
342     let to_check = deps_of(metadata, &krate.id);
343
344     for dep in to_check {
345         let mut bad = check_crate_whitelist(whitelist, metadata, visited, dep);
346         unapproved.append(&mut bad);
347     }
348
349     unapproved
350 }
351
352 /// Prevents multiple versions of some expensive crates.
353 fn check_crate_duplicate(metadata: &Metadata, bad: &mut bool) {
354     const FORBIDDEN_TO_HAVE_DUPLICATES: &[&str] = &[
355         // These two crates take quite a long time to build, so don't allow two versions of them
356         // to accidentally sneak into our dependency graph, in order to ensure we keep our CI times
357         // under control.
358         "cargo",
359         "rustc-ap-rustc_ast",
360     ];
361
362     for &name in FORBIDDEN_TO_HAVE_DUPLICATES {
363         let matches: Vec<_> = metadata.packages.iter().filter(|pkg| pkg.name == name).collect();
364         match matches.len() {
365             0 => {
366                 println!(
367                     "crate `{}` is missing, update `check_crate_duplicate` \
368                     if it is no longer used",
369                     name
370                 );
371                 *bad = true;
372             }
373             1 => {}
374             _ => {
375                 println!(
376                     "crate `{}` is duplicated in `Cargo.lock`, \
377                     it is too expensive to build multiple times, \
378                     so make sure only one version appears across all dependencies",
379                     name
380                 );
381                 for pkg in matches {
382                     println!("  * {}", pkg.id);
383                 }
384                 *bad = true;
385             }
386         }
387     }
388 }
389
390 /// Returns a list of dependencies for the given package.
391 fn deps_of<'a>(metadata: &'a Metadata, pkg_id: &'a PackageId) -> Vec<&'a Package> {
392     let resolve = metadata.resolve.as_ref().unwrap();
393     let node = resolve
394         .nodes
395         .iter()
396         .find(|n| &n.id == pkg_id)
397         .unwrap_or_else(|| panic!("could not find `{}` in resolve", pkg_id));
398     node.deps
399         .iter()
400         .map(|dep| {
401             metadata.packages.iter().find(|pkg| pkg.id == dep.pkg).unwrap_or_else(|| {
402                 panic!("could not find dep `{}` for pkg `{}` in resolve", dep.pkg, pkg_id)
403             })
404         })
405         .collect()
406 }
407
408 /// Finds a package with the given name.
409 fn pkg_from_name<'a>(metadata: &'a Metadata, name: &'static str) -> &'a Package {
410     let mut i = metadata.packages.iter().filter(|p| p.name == name);
411     let result =
412         i.next().unwrap_or_else(|| panic!("could not find package `{}` in package list", name));
413     assert!(i.next().is_none(), "more than one package found for `{}`", name);
414     result
415 }
416
417 /// Finds all the packages that are in the rust runtime.
418 fn compute_runtime_crates<'a>(metadata: &'a Metadata) -> HashSet<&'a PackageId> {
419     let resolve = metadata.resolve.as_ref().unwrap();
420     let mut result = HashSet::new();
421     for name in RUNTIME_CRATES {
422         let id = &pkg_from_name(metadata, name).id;
423         normal_deps_of_r(resolve, id, &mut result);
424     }
425     result
426 }
427
428 /// Recursively find all normal dependencies.
429 fn normal_deps_of_r<'a>(
430     resolve: &'a Resolve,
431     pkg_id: &'a PackageId,
432     result: &mut HashSet<&'a PackageId>,
433 ) {
434     if !result.insert(pkg_id) {
435         return;
436     }
437     let node = resolve
438         .nodes
439         .iter()
440         .find(|n| &n.id == pkg_id)
441         .unwrap_or_else(|| panic!("could not find `{}` in resolve", pkg_id));
442     // Don't care about dev-dependencies.
443     // Build dependencies *shouldn't* matter unless they do some kind of
444     // codegen. For now we'll assume they don't.
445     let deps = node.deps.iter().filter(|node_dep| {
446         node_dep
447             .dep_kinds
448             .iter()
449             .any(|kind_info| kind_info.kind == cargo_metadata::DependencyKind::Normal)
450     });
451     for dep in deps {
452         normal_deps_of_r(resolve, &dep.pkg, result);
453     }
454 }