]> git.lizzy.rs Git - rust.git/blob - src/tools/tidy/src/deps.rs
56d2717c30477913881d71d70770f4f7f0a72a56
[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     ("rdrand", "ISC"),                      // mdbook, rustfmt
30     ("fuchsia-cprng", "BSD-3-Clause"),      // mdbook, rustfmt
31     ("fuchsia-zircon-sys", "BSD-3-Clause"), // rustdoc, rustc, cargo
32     ("fuchsia-zircon", "BSD-3-Clause"),     // rustdoc, rustc, cargo (jobserver & tempdir)
33     ("colored", "MPL-2.0"),                 // rustfmt
34     ("ordslice", "Apache-2.0"),             // rls
35     ("cloudabi", "BSD-2-Clause"),           // (rls -> crossbeam-channel 0.2 -> rand 0.5)
36     ("ryu", "Apache-2.0 OR BSL-1.0"),       // rls/cargo/... (because of serde)
37     ("bytesize", "Apache-2.0"),             // cargo
38     ("im-rc", "MPL-2.0+"),                  // cargo
39     ("adler32", "BSD-3-Clause AND Zlib"),   // cargo dep that isn't used
40     ("constant_time_eq", "CC0-1.0"),        // rustfmt
41     ("sized-chunks", "MPL-2.0+"),           // cargo via im-rc
42     ("bitmaps", "MPL-2.0+"),                // cargo via im-rc
43     // FIXME: this dependency violates the documentation comment above:
44     ("fortanix-sgx-abi", "MPL-2.0"), // libstd but only for `sgx` target
45     ("crossbeam-channel", "MIT/Apache-2.0 AND BSD-2-Clause"), // cargo
46 ];
47
48 /// These are the root crates that are part of the runtime. The licenses for
49 /// these and all their dependencies *must not* be in the exception list.
50 const RUNTIME_CRATES: &[&str] = &["std", "core", "alloc", "test", "panic_abort", "panic_unwind"];
51
52 /// Crates whose dependencies must be explicitly permitted.
53 const RESTRICTED_DEPENDENCY_CRATES: &[&str] = &["rustc_middle", "rustc_codegen_llvm"];
54
55 /// Crates rustc is allowed to depend on. Avoid adding to the list if possible.
56 ///
57 /// This list is here to provide a speed-bump to adding a new dependency to
58 /// rustc. Please check with the compiler team before adding an entry.
59 const PERMITTED_DEPENDENCIES: &[&str] = &[
60     "adler32",
61     "aho-corasick",
62     "annotate-snippets",
63     "ansi_term",
64     "arrayvec",
65     "atty",
66     "autocfg",
67     "backtrace",
68     "backtrace-sys",
69     "bitflags",
70     "block-buffer",
71     "block-padding",
72     "byte-tools",
73     "byteorder",
74     "cc",
75     "cfg-if",
76     "chalk-derive",
77     "chalk-ir",
78     "cloudabi",
79     "cmake",
80     "compiler_builtins",
81     "crc32fast",
82     "crossbeam-deque",
83     "crossbeam-epoch",
84     "crossbeam-queue",
85     "crossbeam-utils",
86     "datafrog",
87     "digest",
88     "dlmalloc",
89     "either",
90     "ena",
91     "env_logger",
92     "fake-simd",
93     "filetime",
94     "flate2",
95     "fortanix-sgx-abi",
96     "fuchsia-zircon",
97     "fuchsia-zircon-sys",
98     "generic-array",
99     "getopts",
100     "getrandom",
101     "hashbrown",
102     "hermit-abi",
103     "humantime",
104     "indexmap",
105     "itertools",
106     "jobserver",
107     "kernel32-sys",
108     "lazy_static",
109     "libc",
110     "libz-sys",
111     "lock_api",
112     "log",
113     "log_settings",
114     "md-5",
115     "measureme",
116     "memchr",
117     "memmap",
118     "memoffset",
119     "miniz_oxide",
120     "nodrop",
121     "num_cpus",
122     "once_cell",
123     "opaque-debug",
124     "parking_lot",
125     "parking_lot_core",
126     "pathdiff",
127     "pkg-config",
128     "polonius-engine",
129     "ppv-lite86",
130     "proc-macro2",
131     "psm",
132     "punycode",
133     "quick-error",
134     "quote",
135     "rand",
136     "rand_chacha",
137     "rand_core",
138     "rand_hc",
139     "rand_isaac",
140     "rand_pcg",
141     "rand_xorshift",
142     "redox_syscall",
143     "regex",
144     "regex-syntax",
145     "remove_dir_all",
146     "rustc-demangle",
147     "rustc-hash",
148     "rustc-rayon",
149     "rustc-rayon-core",
150     "rustc_version",
151     "scoped-tls",
152     "scopeguard",
153     "semver",
154     "semver-parser",
155     "serde",
156     "serde_derive",
157     "sha-1",
158     "smallvec",
159     "stable_deref_trait",
160     "stacker",
161     "syn",
162     "synstructure",
163     "tempfile",
164     "termcolor",
165     "termize",
166     "thread_local",
167     "typenum",
168     "unicode-normalization",
169     "unicode-script",
170     "unicode-security",
171     "unicode-width",
172     "unicode-xid",
173     "vcpkg",
174     "version_check",
175     "wasi",
176     "winapi",
177     "winapi-build",
178     "winapi-i686-pc-windows-gnu",
179     "winapi-util",
180     "winapi-x86_64-pc-windows-gnu",
181     "wincolor",
182 ];
183
184 /// Dependency checks.
185 ///
186 /// `root` is path to the directory with the root `Cargo.toml` (for the workspace). `cargo` is path
187 /// to the cargo executable.
188 pub fn check(root: &Path, cargo: &Path, bad: &mut bool) {
189     let mut cmd = cargo_metadata::MetadataCommand::new();
190     cmd.cargo_path(cargo)
191         .manifest_path(root.join("Cargo.toml"))
192         .features(cargo_metadata::CargoOpt::AllFeatures);
193     let metadata = t!(cmd.exec());
194     check_exceptions(&metadata, bad);
195     check_dependencies(&metadata, bad);
196     check_crate_duplicate(&metadata, bad);
197 }
198
199 /// Check that all licenses are in the valid list in `LICENSES`.
200 ///
201 /// Packages listed in `EXCEPTIONS` are allowed for tools.
202 fn check_exceptions(metadata: &Metadata, bad: &mut bool) {
203     // Validate the EXCEPTIONS list hasn't changed.
204     for (name, license) in EXCEPTIONS {
205         // Check that the package actually exists.
206         if !metadata.packages.iter().any(|p| p.name == *name) {
207             println!(
208                 "could not find exception package `{}`\n\
209                 Remove from EXCEPTIONS list if it is no longer used.",
210                 name
211             );
212             *bad = true;
213         }
214         // Check that the license hasn't changed.
215         for pkg in metadata.packages.iter().filter(|p| p.name == *name) {
216             if pkg.name == "fuchsia-cprng" {
217                 // This package doesn't declare a license expression. Manual
218                 // inspection of the license file is necessary, which appears
219                 // to be BSD-3-Clause.
220                 assert!(pkg.license.is_none());
221                 continue;
222             }
223             match &pkg.license {
224                 None => {
225                     println!(
226                         "dependency exception `{}` does not declare a license expression",
227                         pkg.id
228                     );
229                     *bad = true;
230                 }
231                 Some(pkg_license) => {
232                     if pkg_license.as_str() != *license {
233                         println!("dependency exception `{}` license has changed", name);
234                         println!("    previously `{}` now `{}`", license, pkg_license);
235                         println!("    update EXCEPTIONS for the new license");
236                         *bad = true;
237                     }
238                 }
239             }
240         }
241     }
242
243     let exception_names: Vec<_> = EXCEPTIONS.iter().map(|(name, _license)| *name).collect();
244     let runtime_ids = compute_runtime_crates(metadata);
245
246     // Check if any package does not have a valid license.
247     for pkg in &metadata.packages {
248         if pkg.source.is_none() {
249             // No need to check local packages.
250             continue;
251         }
252         if !runtime_ids.contains(&pkg.id) && exception_names.contains(&pkg.name.as_str()) {
253             continue;
254         }
255         let license = match &pkg.license {
256             Some(license) => license,
257             None => {
258                 println!("dependency `{}` does not define a license expression", pkg.id,);
259                 *bad = true;
260                 continue;
261             }
262         };
263         if !LICENSES.contains(&license.as_str()) {
264             if pkg.name == "fortanix-sgx-abi" {
265                 // This is a specific exception because SGX is considered
266                 // "third party". See
267                 // https://github.com/rust-lang/rust/issues/62620 for more. In
268                 // general, these should never be added.
269                 continue;
270             }
271             println!("invalid license `{}` in `{}`", license, pkg.id);
272             *bad = true;
273         }
274     }
275 }
276
277 /// Checks the dependency of `RESTRICTED_DEPENDENCY_CRATES` at the given path. Changes `bad` to
278 /// `true` if a check failed.
279 ///
280 /// Specifically, this checks that the dependencies are on the `PERMITTED_DEPENDENCIES`.
281 fn check_dependencies(metadata: &Metadata, bad: &mut bool) {
282     // Check that the PERMITTED_DEPENDENCIES does not have unused entries.
283     for name in PERMITTED_DEPENDENCIES {
284         if !metadata.packages.iter().any(|p| p.name == *name) {
285             println!(
286                 "could not find allowed package `{}`\n\
287                 Remove from PERMITTED_DEPENDENCIES list if it is no longer used.",
288                 name
289             );
290             *bad = true;
291         }
292     }
293     // Get the list in a convenient form.
294     let permitted_dependencies: HashSet<_> = PERMITTED_DEPENDENCIES.iter().cloned().collect();
295
296     // Check dependencies.
297     let mut visited = BTreeSet::new();
298     let mut unapproved = BTreeSet::new();
299     for &krate in RESTRICTED_DEPENDENCY_CRATES.iter() {
300         let pkg = pkg_from_name(metadata, krate);
301         let mut bad =
302             check_crate_dependencies(&permitted_dependencies, metadata, &mut visited, pkg);
303         unapproved.append(&mut bad);
304     }
305
306     if !unapproved.is_empty() {
307         println!("Dependencies not explicitly permitted:");
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 list of permitted dependencies. Returns a list of disallowed dependencies.
317 fn check_crate_dependencies<'a>(
318     permitted_dependencies: &'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 explicitly permitted.
334     if krate.source.is_some() {
335         // If this dependency is not on `PERMITTED_DEPENDENCIES`, add to bad set.
336         if !permitted_dependencies.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_dependencies(permitted_dependencies, 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 }