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