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