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