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