]> git.lizzy.rs Git - rust.git/blob - src/tools/tidy/src/deps.rs
Rollup merge of #75064 - petrochenkov:llvmtarg, r=Mark-Simulacrum
[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 ];
22
23 /// These are exceptions to Rust's permissive licensing policy, and
24 /// should be considered bugs. Exceptions are only allowed in Rust
25 /// tooling. It is _crucial_ that no exception crates be dependencies
26 /// of the Rust runtime (std/test).
27 const EXCEPTIONS: &[(&str, &str)] = &[
28     ("mdbook", "MPL-2.0"),                  // mdbook
29     ("openssl", "Apache-2.0"),              // cargo, mdbook
30     ("rdrand", "ISC"),                      // mdbook, rustfmt
31     ("fuchsia-cprng", "BSD-3-Clause"),      // mdbook, rustfmt
32     ("fuchsia-zircon-sys", "BSD-3-Clause"), // rustdoc, rustc, cargo
33     ("fuchsia-zircon", "BSD-3-Clause"),     // rustdoc, rustc, cargo (jobserver & tempdir)
34     ("colored", "MPL-2.0"),                 // rustfmt
35     ("ordslice", "Apache-2.0"),             // rls
36     ("cloudabi", "BSD-2-Clause"),           // (rls -> crossbeam-channel 0.2 -> rand 0.5)
37     ("ryu", "Apache-2.0 OR BSL-1.0"),       // rls/cargo/... (because of serde)
38     ("bytesize", "Apache-2.0"),             // cargo
39     ("im-rc", "MPL-2.0+"),                  // cargo
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     "addr2line",
61     "adler",
62     "aho-corasick",
63     "annotate-snippets",
64     "ansi_term",
65     "arrayvec",
66     "atty",
67     "autocfg",
68     "backtrace",
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     "gimli",
102     "hashbrown",
103     "hermit-abi",
104     "humantime",
105     "indexmap",
106     "itertools",
107     "jobserver",
108     "kernel32-sys",
109     "lazy_static",
110     "libc",
111     "libz-sys",
112     "lock_api",
113     "log",
114     "log_settings",
115     "md-5",
116     "measureme",
117     "memchr",
118     "memmap",
119     "memoffset",
120     "miniz_oxide",
121     "nodrop",
122     "num_cpus",
123     "object",
124     "once_cell",
125     "opaque-debug",
126     "parking_lot",
127     "parking_lot_core",
128     "pathdiff",
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_pcg",
142     "rand_xorshift",
143     "redox_syscall",
144     "regex",
145     "regex-syntax",
146     "remove_dir_all",
147     "rustc-demangle",
148     "rustc-hash",
149     "rustc-rayon",
150     "rustc-rayon-core",
151     "rustc_version",
152     "scoped-tls",
153     "scopeguard",
154     "semver",
155     "semver-parser",
156     "serde",
157     "serde_derive",
158     "sha-1",
159     "smallvec",
160     "stable_deref_trait",
161     "stacker",
162     "syn",
163     "synstructure",
164     "tempfile",
165     "termcolor",
166     "termize",
167     "thread_local",
168     "tracing",
169     "tracing-attributes",
170     "tracing-core",
171     "typenum",
172     "unicode-normalization",
173     "unicode-script",
174     "unicode-security",
175     "unicode-width",
176     "unicode-xid",
177     "vcpkg",
178     "version_check",
179     "wasi",
180     "winapi",
181     "winapi-build",
182     "winapi-i686-pc-windows-gnu",
183     "winapi-util",
184     "winapi-x86_64-pc-windows-gnu",
185 ];
186
187 /// Dependency checks.
188 ///
189 /// `root` is path to the directory with the root `Cargo.toml` (for the workspace). `cargo` is path
190 /// to the cargo executable.
191 pub fn check(root: &Path, cargo: &Path, bad: &mut bool) {
192     let mut cmd = cargo_metadata::MetadataCommand::new();
193     cmd.cargo_path(cargo)
194         .manifest_path(root.join("Cargo.toml"))
195         .features(cargo_metadata::CargoOpt::AllFeatures);
196     let metadata = t!(cmd.exec());
197     check_exceptions(&metadata, bad);
198     check_dependencies(&metadata, bad);
199     check_crate_duplicate(&metadata, bad);
200 }
201
202 /// Check that all licenses are in the valid list in `LICENSES`.
203 ///
204 /// Packages listed in `EXCEPTIONS` are allowed for tools.
205 fn check_exceptions(metadata: &Metadata, bad: &mut bool) {
206     // Validate the EXCEPTIONS list hasn't changed.
207     for (name, license) in EXCEPTIONS {
208         // Check that the package actually exists.
209         if !metadata.packages.iter().any(|p| p.name == *name) {
210             println!(
211                 "could not find exception package `{}`\n\
212                 Remove from EXCEPTIONS list if it is no longer used.",
213                 name
214             );
215             *bad = true;
216         }
217         // Check that the license hasn't changed.
218         for pkg in metadata.packages.iter().filter(|p| p.name == *name) {
219             if pkg.name == "fuchsia-cprng" {
220                 // This package doesn't declare a license expression. Manual
221                 // inspection of the license file is necessary, which appears
222                 // to be BSD-3-Clause.
223                 assert!(pkg.license.is_none());
224                 continue;
225             }
226             match &pkg.license {
227                 None => {
228                     println!(
229                         "dependency exception `{}` does not declare a license expression",
230                         pkg.id
231                     );
232                     *bad = true;
233                 }
234                 Some(pkg_license) => {
235                     if pkg_license.as_str() != *license {
236                         println!("dependency exception `{}` license has changed", name);
237                         println!("    previously `{}` now `{}`", license, pkg_license);
238                         println!("    update EXCEPTIONS for the new license");
239                         *bad = true;
240                     }
241                 }
242             }
243         }
244     }
245
246     let exception_names: Vec<_> = EXCEPTIONS.iter().map(|(name, _license)| *name).collect();
247     let runtime_ids = compute_runtime_crates(metadata);
248
249     // Check if any package does not have a valid license.
250     for pkg in &metadata.packages {
251         if pkg.source.is_none() {
252             // No need to check local packages.
253             continue;
254         }
255         if !runtime_ids.contains(&pkg.id) && exception_names.contains(&pkg.name.as_str()) {
256             continue;
257         }
258         let license = match &pkg.license {
259             Some(license) => license,
260             None => {
261                 println!("dependency `{}` does not define a license expression", pkg.id,);
262                 *bad = true;
263                 continue;
264             }
265         };
266         if !LICENSES.contains(&license.as_str()) {
267             if pkg.name == "fortanix-sgx-abi" {
268                 // This is a specific exception because SGX is considered
269                 // "third party". See
270                 // https://github.com/rust-lang/rust/issues/62620 for more. In
271                 // general, these should never be added.
272                 continue;
273             }
274             println!("invalid license `{}` in `{}`", license, pkg.id);
275             *bad = true;
276         }
277     }
278 }
279
280 /// Checks the dependency of `RESTRICTED_DEPENDENCY_CRATES` at the given path. Changes `bad` to
281 /// `true` if a check failed.
282 ///
283 /// Specifically, this checks that the dependencies are on the `PERMITTED_DEPENDENCIES`.
284 fn check_dependencies(metadata: &Metadata, bad: &mut bool) {
285     // Check that the PERMITTED_DEPENDENCIES does not have unused entries.
286     for name in PERMITTED_DEPENDENCIES {
287         if !metadata.packages.iter().any(|p| p.name == *name) {
288             println!(
289                 "could not find allowed package `{}`\n\
290                 Remove from PERMITTED_DEPENDENCIES list if it is no longer used.",
291                 name
292             );
293             *bad = true;
294         }
295     }
296     // Get the list in a convenient form.
297     let permitted_dependencies: HashSet<_> = PERMITTED_DEPENDENCIES.iter().cloned().collect();
298
299     // Check dependencies.
300     let mut visited = BTreeSet::new();
301     let mut unapproved = BTreeSet::new();
302     for &krate in RESTRICTED_DEPENDENCY_CRATES.iter() {
303         let pkg = pkg_from_name(metadata, krate);
304         let mut bad =
305             check_crate_dependencies(&permitted_dependencies, metadata, &mut visited, pkg);
306         unapproved.append(&mut bad);
307     }
308
309     if !unapproved.is_empty() {
310         println!("Dependencies not explicitly permitted:");
311         for dep in unapproved {
312             println!("* {}", dep);
313         }
314         *bad = true;
315     }
316 }
317
318 /// Checks the dependencies of the given crate from the given cargo metadata to see if they are on
319 /// the list of permitted dependencies. Returns a list of disallowed dependencies.
320 fn check_crate_dependencies<'a>(
321     permitted_dependencies: &'a HashSet<&'static str>,
322     metadata: &'a Metadata,
323     visited: &mut BTreeSet<&'a PackageId>,
324     krate: &'a Package,
325 ) -> BTreeSet<&'a PackageId> {
326     // This will contain bad deps.
327     let mut unapproved = BTreeSet::new();
328
329     // Check if we have already visited this crate.
330     if visited.contains(&krate.id) {
331         return unapproved;
332     }
333
334     visited.insert(&krate.id);
335
336     // If this path is in-tree, we don't require it to be explicitly permitted.
337     if krate.source.is_some() {
338         // If this dependency is not on `PERMITTED_DEPENDENCIES`, add to bad set.
339         if !permitted_dependencies.contains(krate.name.as_str()) {
340             unapproved.insert(&krate.id);
341         }
342     }
343
344     // Do a DFS in the crate graph.
345     let to_check = deps_of(metadata, &krate.id);
346
347     for dep in to_check {
348         let mut bad = check_crate_dependencies(permitted_dependencies, metadata, visited, dep);
349         unapproved.append(&mut bad);
350     }
351
352     unapproved
353 }
354
355 /// Prevents multiple versions of some expensive crates.
356 fn check_crate_duplicate(metadata: &Metadata, bad: &mut bool) {
357     const FORBIDDEN_TO_HAVE_DUPLICATES: &[&str] = &[
358         // These two crates take quite a long time to build, so don't allow two versions of them
359         // to accidentally sneak into our dependency graph, in order to ensure we keep our CI times
360         // under control.
361         "cargo",
362         "rustc-ap-rustc_ast",
363     ];
364
365     for &name in FORBIDDEN_TO_HAVE_DUPLICATES {
366         let matches: Vec<_> = metadata.packages.iter().filter(|pkg| pkg.name == name).collect();
367         match matches.len() {
368             0 => {
369                 println!(
370                     "crate `{}` is missing, update `check_crate_duplicate` \
371                     if it is no longer used",
372                     name
373                 );
374                 *bad = true;
375             }
376             1 => {}
377             _ => {
378                 println!(
379                     "crate `{}` is duplicated in `Cargo.lock`, \
380                     it is too expensive to build multiple times, \
381                     so make sure only one version appears across all dependencies",
382                     name
383                 );
384                 for pkg in matches {
385                     println!("  * {}", pkg.id);
386                 }
387                 *bad = true;
388             }
389         }
390     }
391 }
392
393 /// Returns a list of dependencies for the given package.
394 fn deps_of<'a>(metadata: &'a Metadata, pkg_id: &'a PackageId) -> Vec<&'a Package> {
395     let resolve = metadata.resolve.as_ref().unwrap();
396     let node = resolve
397         .nodes
398         .iter()
399         .find(|n| &n.id == pkg_id)
400         .unwrap_or_else(|| panic!("could not find `{}` in resolve", pkg_id));
401     node.deps
402         .iter()
403         .map(|dep| {
404             metadata.packages.iter().find(|pkg| pkg.id == dep.pkg).unwrap_or_else(|| {
405                 panic!("could not find dep `{}` for pkg `{}` in resolve", dep.pkg, pkg_id)
406             })
407         })
408         .collect()
409 }
410
411 /// Finds a package with the given name.
412 fn pkg_from_name<'a>(metadata: &'a Metadata, name: &'static str) -> &'a Package {
413     let mut i = metadata.packages.iter().filter(|p| p.name == name);
414     let result =
415         i.next().unwrap_or_else(|| panic!("could not find package `{}` in package list", name));
416     assert!(i.next().is_none(), "more than one package found for `{}`", name);
417     result
418 }
419
420 /// Finds all the packages that are in the rust runtime.
421 fn compute_runtime_crates<'a>(metadata: &'a Metadata) -> HashSet<&'a PackageId> {
422     let resolve = metadata.resolve.as_ref().unwrap();
423     let mut result = HashSet::new();
424     for name in RUNTIME_CRATES {
425         let id = &pkg_from_name(metadata, name).id;
426         normal_deps_of_r(resolve, id, &mut result);
427     }
428     result
429 }
430
431 /// Recursively find all normal dependencies.
432 fn normal_deps_of_r<'a>(
433     resolve: &'a Resolve,
434     pkg_id: &'a PackageId,
435     result: &mut HashSet<&'a PackageId>,
436 ) {
437     if !result.insert(pkg_id) {
438         return;
439     }
440     let node = resolve
441         .nodes
442         .iter()
443         .find(|n| &n.id == pkg_id)
444         .unwrap_or_else(|| panic!("could not find `{}` in resolve", pkg_id));
445     // Don't care about dev-dependencies.
446     // Build dependencies *shouldn't* matter unless they do some kind of
447     // codegen. For now we'll assume they don't.
448     let deps = node.deps.iter().filter(|node_dep| {
449         node_dep
450             .dep_kinds
451             .iter()
452             .any(|kind_info| kind_info.kind == cargo_metadata::DependencyKind::Normal)
453     });
454     for dep in deps {
455         normal_deps_of_r(resolve, &dep.pkg, result);
456     }
457 }