1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
|
// Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use gnrt_lib::*;
use crates::{ChromiumVendoredCrate, StdVendoredCrate};
use manifest::*;
use std::collections::{HashMap, HashSet};
use std::fs;
use std::io::{self, Write};
use std::path::{Path, PathBuf};
use std::process::{self, ExitCode};
use clap::arg;
fn main() -> ExitCode {
let args = clap::Command::new("gnrt")
.subcommand(clap::Command::new("gen")
.about("Generate GN build rules from third_party/rust crates")
.arg(arg!(--"output-cargo-toml" "Output third_party/rust/Cargo.toml then exit \
immediately"))
.arg(arg!(--"skip-patch" "Don't apply gnrt_build_patch after generating build files. \
Useful when updating the patch."))
.arg(arg!(--"for-std" "(WIP) Generate build files for Rust std library instead of \
third_party/rust"))
)
.subcommand(clap::Command::new("download")
.about("Download the crate with the given name and version to third_party/rust.")
.arg(arg!([NAME] "Name of the crate to download").required(true))
.arg(arg!([VERSION] "Version of the crate to download").required(true))
.arg(
arg!(--"security-critical" <YESNO> "Whether the crate is considered to be \
security critical."
).possible_values(["yes", "no"]).required(true)
)
)
.get_matches();
let paths = paths::ChromiumPaths::new().unwrap();
match args.subcommand() {
Some(("gen", args)) => {
if args.is_present("for-std") {
// This is not fully implemented. Currently, it will print data helpful
// for development then quit.
generate_for_std(&args, &paths)
} else {
generate_for_third_party(&args, &paths)
}
}
Some(("download", args)) => {
let security = args.value_of("security-critical").unwrap() == "yes";
let name = args.value_of("NAME").unwrap();
use std::str::FromStr;
let version = semver::Version::from_str(args.value_of("VERSION").unwrap())
.expect("Invalid version specified");
download::download(name, version, security, &paths)
}
_ => unreachable!("Invalid subcommand"),
}
}
fn generate_for_third_party(args: &clap::ArgMatches, paths: &paths::ChromiumPaths) -> ExitCode {
let manifest_contents =
String::from_utf8(fs::read(paths.third_party.join("third_party.toml")).unwrap()).unwrap();
let third_party_manifest: ThirdPartyManifest = match toml::de::from_str(&manifest_contents) {
Ok(m) => m,
Err(e) => {
eprintln!("Failed to parse 'third_party.toml': {e}");
return ExitCode::FAILURE;
}
};
// Collect special fields from third_party.toml.
//
// TODO(crbug.com/1291994): handle visibility separately for each kind.
let mut pub_deps = HashSet::<ChromiumVendoredCrate>::new();
let mut build_script_outputs = HashMap::<ChromiumVendoredCrate, Vec<String>>::new();
for (dep_name, dep_spec) in [
&third_party_manifest.dependency_spec.dependencies,
&third_party_manifest.dependency_spec.dev_dependencies,
&third_party_manifest.dependency_spec.build_dependencies,
]
.into_iter()
.flatten()
{
let (version_req, is_public, dep_outputs): (&_, bool, &[_]) = match dep_spec {
Dependency::Short(version_req) => (version_req, true, &[]),
Dependency::Full(dep) => (
dep.version.as_ref().unwrap(),
dep.allow_first_party_usage,
&dep.build_script_outputs,
),
};
let epoch = crates::Epoch::from_version_req_str(&version_req.0);
let crate_id = crates::ChromiumVendoredCrate { name: dep_name.clone(), epoch };
if is_public {
pub_deps.insert(crate_id.clone());
}
if !dep_outputs.is_empty() {
build_script_outputs.insert(crate_id, dep_outputs.to_vec());
}
}
// Rebind as immutable.
let (pub_deps, build_script_outputs) = (pub_deps, build_script_outputs);
// Traverse our third-party directory to collect the set of vendored crates.
// Used to generate Cargo.toml [patch] sections, and later to check against
// `cargo metadata`'s dependency resolution to ensure we have all the crates
// we need. We sort `crates` for a stable ordering of [patch] sections.
let mut crates = crates::collect_third_party_crates(paths.third_party.clone()).unwrap();
crates.sort_unstable_by(|a, b| a.0.cmp(&b.0));
// Generate a fake root Cargo.toml for dependency resolution.
let cargo_manifest = generate_fake_cargo_toml(
third_party_manifest,
crates.iter().map(|(c, _)| manifest::PatchSpecification {
package_name: c.name.clone(),
patch_name: c.patch_name(),
path: c.crate_path(),
}),
);
if args.is_present("output-cargo-toml") {
println!("{}", toml::ser::to_string(&cargo_manifest).unwrap());
return ExitCode::SUCCESS;
}
// Create a fake package: Cargo.toml and an empty main.rs. This allows cargo
// to construct a full dependency graph as if Chrome were a cargo package.
write!(
io::BufWriter::new(fs::File::create(paths.third_party.join("Cargo.toml")).unwrap()),
"# {}\n\n{}",
AUTOGENERATED_FILE_HEADER,
toml::to_string(&cargo_manifest).unwrap()
)
.unwrap();
create_dirs_if_needed(&paths.third_party.join("src")).unwrap();
write!(
io::BufWriter::new(fs::File::create(paths.third_party.join("src/main.rs")).unwrap()),
"// {}",
AUTOGENERATED_FILE_HEADER
)
.unwrap();
// Run `cargo metadata` and process the output to get a list of crates we
// depend on.
let mut command = cargo_metadata::MetadataCommand::new();
command.current_dir(&paths.third_party);
let dependencies = deps::collect_dependencies(&command.exec().unwrap(), None);
// Compare cargo's dependency resolution with the crates we have on disk. We
// want to ensure:
// * Each resolved dependency matches with a crate we discovered (no missing
// deps).
// * Each discovered crate matches with a resolved dependency (no unused
// crates).
let mut has_error = false;
let present_crates: HashSet<&ChromiumVendoredCrate> = crates.iter().map(|(c, _)| c).collect();
// Construct the set of requested third-party crates, ensuring we don't have
// duplicate epochs. For example, if we resolved two versions of a
// dependency with the same major version, we cannot continue.
let mut req_crates = HashSet::<ChromiumVendoredCrate>::new();
for package in &dependencies {
if !req_crates.insert(package.third_party_crate_id()) {
panic!("found another requested package with the same name and epoch: {:?}", package);
}
}
let req_crates = req_crates;
for dep in dependencies.iter() {
if !present_crates.contains(&dep.third_party_crate_id()) {
has_error = true;
println!("Missing dependency: {} {}", dep.package_name, dep.version);
for edge in dep.dependency_path.iter() {
println!(" {edge}");
}
} else if !dep.is_local {
// Transitive deps may be requested with version requirements stricter than
// ours: e.g. 1.57 instead of just major version 1. If the version we have
// checked in, e.g. 1.56, has the same epoch but doesn't meet the version
// requirement, the symptom is Cargo will resolve the dependency to an
// upstream source instead of our local path. We must detect this case to
// ensure correctness.
has_error = true;
println!(
"Resolved {} {} to an upstream source. The requested version \
likely has the same epoch as the discovered crate but \
something has a more stringent version requirement.",
dep.package_name, dep.version
);
println!(" Resolved version: {}", dep.version);
}
}
for present_crate in present_crates.iter() {
if !req_crates.contains(present_crate) {
has_error = true;
println!("Unused crate: {present_crate}");
}
}
if has_error {
return ExitCode::FAILURE;
}
let build_files: HashMap<ChromiumVendoredCrate, gn::BuildFile> = gn::build_files_from_deps(
&dependencies,
&paths,
&crates.iter().cloned().collect(),
&build_script_outputs,
&pub_deps,
);
// Before modifying anything make sure we have a one-to-one mapping of
// discovered crates and build file data.
for (crate_id, _) in build_files.iter() {
// This shouldn't happen, but check anyway in case we have a strange
// logic error above.
assert!(present_crates.contains(&crate_id));
}
for crate_id in present_crates.iter() {
if !build_files.contains_key(*crate_id) {
println!("Error: discovered crate {crate_id}, but no build file was generated.");
has_error = true;
}
}
if has_error {
return ExitCode::FAILURE;
}
// Wipe all previous BUILD.gn files. If we fail, we don't want to leave a
// mix of old and new build files.
for build_file in crates.iter().map(|(crate_id, _)| build_file_path(crate_id, &paths)) {
if build_file.exists() {
fs::remove_file(&build_file).unwrap();
}
}
// Generate build files, wiping the previous ones so we don't have any stale
// build rules.
for (crate_id, _) in crates.iter() {
let build_file_path = build_file_path(crate_id, &paths);
let build_file_data = match build_files.get(&crate_id) {
Some(build_file) => build_file,
None => panic!("missing build data for {crate_id}"),
};
write_build_file(&build_file_path, build_file_data).unwrap();
}
// Apply patch for BUILD.gn files.
let build_patch = paths.root.join(paths.third_party.join("gnrt_build_patch"));
if !args.is_present("skip-patch") && build_patch.exists() {
let status = process::Command::new("git")
.arg("apply")
.arg(build_patch)
.current_dir(&paths.root)
.status()
.unwrap();
check_exit_status(status, "applying build patch").unwrap();
}
ExitCode::SUCCESS
}
fn generate_for_std(_args: &clap::ArgMatches, paths: &paths::ChromiumPaths) -> ExitCode {
// Run `cargo metadata` from the std package in the Rust source tree (which
// is a workspace).
let mut command = cargo_metadata::MetadataCommand::new();
command.current_dir(paths.rust_std);
// Ensure we use exactly the dependency versions specified in the Rust
// source's Cargo.lock. This is the only officially tested libstd.
command.other_options(["--locked".to_string(), "--offline".to_string()]);
// Compute the set of crates we need to build to build libstd.
let dependencies =
deps::collect_dependencies(&command.exec().unwrap(), Some(vec!["std".to_string()]));
// Collect the set of third-party dependencies vendored in the Rust source
// package.
let vendored_crates: HashMap<StdVendoredCrate, manifest::CargoPackage> =
crates::collect_std_vendored_crates(paths.rust_src_vendor).unwrap().into_iter().collect();
// Collect vendored dependencies, and also check that all resolved
// dependencies point to our Rust source package. Build rules will be
// generated for these crates separately from std, alloc, and core which
// need special treatment.
let src_prefix = paths.root.join(paths.rust_src);
for dep in &dependencies {
// Skip workspace members. They are not third-party deps in this
// context.
if dep.is_workspace_member {
continue;
}
// Skip "rust-std-workspace-*" deps, which are shims to allow std to
// depend on third-party crates. See
// https://github.com/rust-lang/rust/tree/master/library/rustc-std-workspace-core
if dep.package_name.starts_with("rustc-std-workspace-") {
continue;
}
// Skip crates in stdarch, which is a separate workspace in the same
// source tree.
if dep.package_name.starts_with("std_detect") {
continue;
}
// Skip "rustc-workspace-hack", which is irrelevant to the standard
// library build.
if dep.package_name.starts_with("rustc-workspace-hack") {
continue;
}
// Only process deps with a library target: we are producing build rules
// for the standard library, so transitive binary dependencies don't
// make sense.
let lib = match &dep.lib_target {
Some(lib) => lib,
None => continue,
};
if !lib.root.starts_with(&src_prefix) {
println!(
"Found dependency that was not locally available: {} {}",
dep.package_name, dep.version
);
return ExitCode::FAILURE;
}
let (crate_id, _): (&StdVendoredCrate, _) =
match vendored_crates.get_key_value(&StdVendoredCrate {
name: dep.package_name.clone(),
version: dep.version.clone(),
// Placeholder value for lookup.
is_latest: false,
}) {
Some(id) => id,
None => {
println!(
"Resolved dependency does not match any vendored crate: {} {}",
dep.package_name, dep.version
);
return ExitCode::FAILURE;
}
};
// To test, print the list of needed vendored crates and the path of
// dependency edges leading to them.
println!("{crate_id}");
for next in &dep.dependency_path {
println!(" {next}");
}
}
ExitCode::SUCCESS
}
fn build_file_path(crate_id: &ChromiumVendoredCrate, paths: &paths::ChromiumPaths) -> PathBuf {
let mut path = paths.root.clone();
path.push(&paths.third_party);
path.push(crate_id.build_path());
path.push("BUILD.gn");
path
}
fn write_build_file(path: &Path, build_file: &gn::BuildFile) -> io::Result<()> {
let output_handle = fs::File::create(path).unwrap();
// Run our GN output through the official formatter. The gn invocation will
// write directly to the output file.
let mut formatter = process::Command::new("gn")
.arg("format")
.arg("--stdin")
.stdin(process::Stdio::piped())
.stdout(output_handle)
.spawn()
.unwrap();
write!(io::BufWriter::new(formatter.stdin.take().unwrap()), "{}", build_file.display())?;
let status = formatter.wait()?;
check_exit_status(status, "formatting GN output")
}
fn check_exit_status(status: process::ExitStatus, cmd_msg: &str) -> io::Result<()> {
use std::fmt::Write;
if status.success() {
Ok(())
} else {
let mut msg: String = format!("{cmd_msg} failed with ");
match status.code() {
Some(code) => write!(msg, "{code}").unwrap(),
None => write!(msg, "no code").unwrap(),
};
Err(io::Error::new(io::ErrorKind::Other, msg))
}
}
fn create_dirs_if_needed(path: &Path) -> io::Result<()> {
if path.is_dir() {
return Ok(());
}
if let Some(parent) = path.parent() {
create_dirs_if_needed(parent)?;
}
fs::create_dir(path)
}
/// A message prepended to autogenerated files. Notes this tool generated it and
/// not to edit directly.
static AUTOGENERATED_FILE_HEADER: &'static str = "!!! DO NOT EDIT -- Autogenerated by gnrt from third_party.toml. Edit that file instead. See tools/crates/gnrt.";
|