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
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
use std::collections::{BTreeSet, HashMap, HashSet};
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex};
use crate::core::compiler::compilation::{self, UnitOutput};
use crate::core::compiler::{self, artifact, Unit};
use crate::core::PackageId;
use crate::util::errors::CargoResult;
use crate::util::profile;
use anyhow::{bail, Context as _};
use filetime::FileTime;
use jobserver::Client;
use super::build_plan::BuildPlan;
use super::custom_build::{self, BuildDeps, BuildScriptOutputs, BuildScripts};
use super::fingerprint::Fingerprint;
use super::job_queue::JobQueue;
use super::layout::Layout;
use super::lto::Lto;
use super::unit_graph::UnitDep;
use super::{
BuildContext, Compilation, CompileKind, CompileMode, Executor, FileFlavor, RustDocFingerprint,
};
mod compilation_files;
use self::compilation_files::CompilationFiles;
pub use self::compilation_files::{Metadata, OutputFile};
pub struct Context<'a, 'cfg> {
pub bcx: &'a BuildContext<'a, 'cfg>,
pub compilation: Compilation<'cfg>,
pub build_script_outputs: Arc<Mutex<BuildScriptOutputs>>,
pub build_explicit_deps: HashMap<Unit, BuildDeps>,
pub fingerprints: HashMap<Unit, Arc<Fingerprint>>,
pub mtime_cache: HashMap<PathBuf, FileTime>,
pub compiled: HashSet<Unit>,
pub build_scripts: HashMap<Unit, Arc<BuildScripts>>,
pub jobserver: Client,
primary_packages: HashSet<PackageId>,
files: Option<CompilationFiles<'a, 'cfg>>,
rmeta_required: HashSet<Unit>,
pub rustc_clients: HashMap<Unit, Client>,
pub lto: HashMap<Unit, Lto>,
pub metadata_for_doc_units: HashMap<Unit, Metadata>,
}
impl<'a, 'cfg> Context<'a, 'cfg> {
pub fn new(bcx: &'a BuildContext<'a, 'cfg>) -> CargoResult<Self> {
let jobserver = match bcx.config.jobserver_from_env() {
Some(c) => c.clone(),
None => {
let client = Client::new(bcx.build_config.jobs as usize)
.with_context(|| "failed to create jobserver")?;
client.acquire_raw()?;
client
}
};
Ok(Self {
bcx,
compilation: Compilation::new(bcx)?,
build_script_outputs: Arc::new(Mutex::new(BuildScriptOutputs::default())),
fingerprints: HashMap::new(),
mtime_cache: HashMap::new(),
compiled: HashSet::new(),
build_scripts: HashMap::new(),
build_explicit_deps: HashMap::new(),
jobserver,
primary_packages: HashSet::new(),
files: None,
rmeta_required: HashSet::new(),
rustc_clients: HashMap::new(),
lto: HashMap::new(),
metadata_for_doc_units: HashMap::new(),
})
}
pub fn compile(mut self, exec: &Arc<dyn Executor>) -> CargoResult<Compilation<'cfg>> {
let mut queue = JobQueue::new(self.bcx);
let mut plan = BuildPlan::new();
let build_plan = self.bcx.build_config.build_plan;
self.lto = super::lto::generate(self.bcx)?;
self.prepare_units()?;
self.prepare()?;
custom_build::build_map(&mut self)?;
self.check_collisions()?;
self.compute_metadata_for_doc_units();
if self.bcx.build_config.mode.is_doc() {
RustDocFingerprint::check_rustdoc_fingerprint(&self)?
}
for unit in &self.bcx.roots {
let force_rebuild = self.bcx.build_config.force_rebuild;
super::compile(&mut self, &mut queue, &mut plan, unit, exec, force_rebuild)?;
}
for fingerprint in self.fingerprints.values() {
fingerprint.clear_memoized();
}
queue.execute(&mut self, &mut plan)?;
if build_plan {
plan.set_inputs(self.build_plan_inputs()?);
plan.output_plan(self.bcx.config);
}
for unit in &self.bcx.roots {
for output in self.outputs(unit)?.iter() {
if output.flavor == FileFlavor::DebugInfo || output.flavor == FileFlavor::Auxiliary
{
continue;
}
let bindst = output.bin_dst();
if unit.mode == CompileMode::Test {
self.compilation
.tests
.push(self.unit_output(unit, &output.path));
} else if unit.target.is_executable() {
self.compilation
.binaries
.push(self.unit_output(unit, bindst));
} else if unit.target.is_cdylib()
&& !self.compilation.cdylibs.iter().any(|uo| uo.unit == *unit)
{
self.compilation
.cdylibs
.push(self.unit_output(unit, bindst));
}
}
if unit.target.is_lib() {
for dep in &self.bcx.unit_graph[unit] {
if dep.unit.mode.is_run_custom_build() {
let out_dir = self
.files()
.build_script_out_dir(&dep.unit)
.display()
.to_string();
let script_meta = self.get_run_build_script_metadata(&dep.unit);
self.compilation
.extra_env
.entry(script_meta)
.or_insert_with(Vec::new)
.push(("OUT_DIR".to_string(), out_dir));
}
}
}
if unit.mode.is_doc_test() {
let mut unstable_opts = false;
let mut args = compiler::extern_args(&self, unit, &mut unstable_opts)?;
args.extend(compiler::lto_args(&self, unit));
args.extend(compiler::features_args(unit));
args.extend(compiler::check_cfg_args(&self, unit));
let script_meta = self.find_build_script_metadata(unit);
if let Some(meta) = script_meta {
if let Some(output) = self.build_script_outputs.lock().unwrap().get(meta) {
for cfg in &output.cfgs {
args.push("--cfg".into());
args.push(cfg.into());
}
if !output.check_cfgs.is_empty() {
args.push("-Zunstable-options".into());
for check_cfg in &output.check_cfgs {
args.push("--check-cfg".into());
args.push(check_cfg.into());
}
}
for (lt, arg) in &output.linker_args {
if lt.applies_to(&unit.target) {
args.push("-C".into());
args.push(format!("link-arg={}", arg).into());
}
}
}
}
args.extend(self.bcx.rustdocflags_args(unit).iter().map(Into::into));
use super::MessageFormat;
let format = match self.bcx.build_config.message_format {
MessageFormat::Short => "short",
MessageFormat::Human => "human",
MessageFormat::Json { .. } => "json",
};
args.push("--error-format".into());
args.push(format.into());
self.compilation.to_doc_test.push(compilation::Doctest {
unit: unit.clone(),
args,
unstable_opts,
linker: self.bcx.linker(unit.kind),
script_meta,
env: artifact::get_env(&self, self.unit_deps(unit))?,
});
}
super::output_depinfo(&mut self, unit)?;
}
for (script_meta, output) in self.build_script_outputs.lock().unwrap().iter() {
self.compilation
.extra_env
.entry(*script_meta)
.or_insert_with(Vec::new)
.extend(output.env.iter().cloned());
for dir in output.library_paths.iter() {
self.compilation.native_dirs.insert(dir.clone());
}
}
Ok(self.compilation)
}
pub fn get_executable(&mut self, unit: &Unit) -> CargoResult<Option<PathBuf>> {
let is_binary = unit.target.is_executable();
let is_test = unit.mode.is_any_test();
if !unit.mode.generates_executable() || !(is_binary || is_test) {
return Ok(None);
}
Ok(self
.outputs(unit)?
.iter()
.find(|o| o.flavor == FileFlavor::Normal)
.map(|output| output.bin_dst().clone()))
}
pub fn prepare_units(&mut self) -> CargoResult<()> {
let dest = self.bcx.profiles.get_dir_name();
let host_layout = Layout::new(self.bcx.ws, None, &dest)?;
let mut targets = HashMap::new();
for kind in self.bcx.all_kinds.iter() {
if let CompileKind::Target(target) = *kind {
let layout = Layout::new(self.bcx.ws, Some(target), &dest)?;
targets.insert(target, layout);
}
}
self.primary_packages
.extend(self.bcx.roots.iter().map(|u| u.pkg.package_id()));
self.compilation
.root_crate_names
.extend(self.bcx.roots.iter().map(|u| u.target.crate_name()));
self.record_units_requiring_metadata();
let files = CompilationFiles::new(self, host_layout, targets);
self.files = Some(files);
Ok(())
}
pub fn prepare(&mut self) -> CargoResult<()> {
let _p = profile::start("preparing layout");
self.files_mut()
.host
.prepare()
.with_context(|| "couldn't prepare build directories")?;
for target in self.files.as_mut().unwrap().target.values_mut() {
target
.prepare()
.with_context(|| "couldn't prepare build directories")?;
}
let files = self.files.as_ref().unwrap();
for &kind in self.bcx.all_kinds.iter() {
let layout = files.layout(kind);
self.compilation
.root_output
.insert(kind, layout.dest().to_path_buf());
self.compilation
.deps_output
.insert(kind, layout.deps().to_path_buf());
}
Ok(())
}
pub fn files(&self) -> &CompilationFiles<'a, 'cfg> {
self.files.as_ref().unwrap()
}
fn files_mut(&mut self) -> &mut CompilationFiles<'a, 'cfg> {
self.files.as_mut().unwrap()
}
pub fn outputs(&self, unit: &Unit) -> CargoResult<Arc<Vec<OutputFile>>> {
self.files.as_ref().unwrap().outputs(unit, self.bcx)
}
pub fn unit_deps(&self, unit: &Unit) -> &[UnitDep] {
&self.bcx.unit_graph[unit]
}
pub fn find_build_script_unit(&self, unit: &Unit) -> Option<Unit> {
if unit.mode.is_run_custom_build() {
return Some(unit.clone());
}
self.bcx.unit_graph[unit]
.iter()
.find(|unit_dep| {
unit_dep.unit.mode.is_run_custom_build()
&& unit_dep.unit.pkg.package_id() == unit.pkg.package_id()
})
.map(|unit_dep| unit_dep.unit.clone())
}
pub fn find_build_script_metadata(&self, unit: &Unit) -> Option<Metadata> {
let script_unit = self.find_build_script_unit(unit)?;
Some(self.get_run_build_script_metadata(&script_unit))
}
pub fn get_run_build_script_metadata(&self, unit: &Unit) -> Metadata {
assert!(unit.mode.is_run_custom_build());
self.files().metadata(unit)
}
pub fn is_primary_package(&self, unit: &Unit) -> bool {
self.primary_packages.contains(&unit.pkg.package_id())
}
pub fn build_plan_inputs(&self) -> CargoResult<Vec<PathBuf>> {
let mut inputs = BTreeSet::new();
for unit in self.bcx.unit_graph.keys() {
inputs.insert(unit.pkg.manifest_path().to_path_buf());
}
Ok(inputs.into_iter().collect())
}
pub fn unit_output(&self, unit: &Unit, path: &Path) -> UnitOutput {
let script_meta = self.find_build_script_metadata(unit);
UnitOutput {
unit: unit.clone(),
path: path.to_path_buf(),
script_meta,
}
}
fn check_collisions(&self) -> CargoResult<()> {
let mut output_collisions = HashMap::new();
let describe_collision = |unit: &Unit, other_unit: &Unit, path: &PathBuf| -> String {
format!(
"The {} target `{}` in package `{}` has the same output \
filename as the {} target `{}` in package `{}`.\n\
Colliding filename is: {}\n",
unit.target.kind().description(),
unit.target.name(),
unit.pkg.package_id(),
other_unit.target.kind().description(),
other_unit.target.name(),
other_unit.pkg.package_id(),
path.display()
)
};
let suggestion =
"Consider changing their names to be unique or compiling them separately.\n\
This may become a hard error in the future; see \
<https://github.com/rust-lang/cargo/issues/6313>.";
let rustdoc_suggestion =
"This is a known bug where multiple crates with the same name use\n\
the same path; see <https://github.com/rust-lang/cargo/issues/6313>.";
let report_collision = |unit: &Unit,
other_unit: &Unit,
path: &PathBuf,
suggestion: &str|
-> CargoResult<()> {
if unit.target.name() == other_unit.target.name() {
self.bcx.config.shell().warn(format!(
"output filename collision.\n\
{}\
The targets should have unique names.\n\
{}",
describe_collision(unit, other_unit, path),
suggestion
))
} else {
self.bcx.config.shell().warn(format!(
"output filename collision.\n\
{}\
The output filenames should be unique.\n\
{}\n\
If this looks unexpected, it may be a bug in Cargo. Please file a bug report at\n\
https://github.com/rust-lang/cargo/issues/ with as much information as you\n\
can provide.\n\
cargo {} running on `{}` target `{}`\n\
First unit: {:?}\n\
Second unit: {:?}",
describe_collision(unit, other_unit, path),
suggestion,
crate::version(),
self.bcx.host_triple(),
self.bcx.target_data.short_name(&unit.kind),
unit,
other_unit))
}
};
fn doc_collision_error(unit: &Unit, other_unit: &Unit) -> CargoResult<()> {
bail!(
"document output filename collision\n\
The {} `{}` in package `{}` has the same name as the {} `{}` in package `{}`.\n\
Only one may be documented at once since they output to the same path.\n\
Consider documenting only one, renaming one, \
or marking one with `doc = false` in Cargo.toml.",
unit.target.kind().description(),
unit.target.name(),
unit.pkg,
other_unit.target.kind().description(),
other_unit.target.name(),
other_unit.pkg,
);
}
let mut keys = self
.bcx
.unit_graph
.keys()
.filter(|unit| !unit.mode.is_run_custom_build())
.collect::<Vec<_>>();
keys.sort_unstable();
let mut doc_libs = HashMap::new();
let mut doc_bins = HashMap::new();
for unit in keys {
if unit.mode.is_doc() && self.is_primary_package(unit) {
if unit.target.is_lib() {
if let Some(prev) = doc_libs.insert((unit.target.crate_name(), unit.kind), unit)
{
doc_collision_error(unit, prev)?;
}
} else if let Some(prev) =
doc_bins.insert((unit.target.crate_name(), unit.kind), unit)
{
doc_collision_error(unit, prev)?;
}
}
for output in self.outputs(unit)?.iter() {
if let Some(other_unit) = output_collisions.insert(output.path.clone(), unit) {
if unit.mode.is_doc() {
report_collision(unit, other_unit, &output.path, rustdoc_suggestion)?;
} else {
report_collision(unit, other_unit, &output.path, suggestion)?;
}
}
if let Some(hardlink) = output.hardlink.as_ref() {
if let Some(other_unit) = output_collisions.insert(hardlink.clone(), unit) {
report_collision(unit, other_unit, hardlink, suggestion)?;
}
}
if let Some(ref export_path) = output.export_path {
if let Some(other_unit) = output_collisions.insert(export_path.clone(), unit) {
self.bcx.config.shell().warn(format!(
"`--out-dir` filename collision.\n\
{}\
The exported filenames should be unique.\n\
{}",
describe_collision(unit, other_unit, export_path),
suggestion
))?;
}
}
}
}
Ok(())
}
fn record_units_requiring_metadata(&mut self) {
for (key, deps) in self.bcx.unit_graph.iter() {
for dep in deps {
if self.only_requires_rmeta(key, &dep.unit) {
self.rmeta_required.insert(dep.unit.clone());
}
}
}
}
pub fn only_requires_rmeta(&self, parent: &Unit, dep: &Unit) -> bool {
!parent.requires_upstream_objects()
&& parent.mode == CompileMode::Build
&& !dep.requires_upstream_objects()
&& dep.mode == CompileMode::Build
}
pub fn rmeta_required(&self, unit: &Unit) -> bool {
self.rmeta_required.contains(unit)
}
pub fn new_jobserver(&mut self) -> CargoResult<Client> {
let tokens = self.bcx.build_config.jobs as usize;
let client = Client::new(tokens).with_context(|| "failed to create jobserver")?;
for i in 0..tokens {
client.acquire_raw().with_context(|| {
format!(
"failed to fully drain {}/{} token from jobserver at startup",
i, tokens,
)
})?;
}
Ok(client)
}
pub fn compute_metadata_for_doc_units(&mut self) {
for unit in self.bcx.unit_graph.keys() {
if !unit.mode.is_doc() && !unit.mode.is_doc_scrape() {
continue;
}
let matching_units = self
.bcx
.unit_graph
.keys()
.filter(|other| {
unit.pkg == other.pkg
&& unit.target == other.target
&& !other.mode.is_doc_scrape()
})
.collect::<Vec<_>>();
let metadata_unit = matching_units
.iter()
.find(|other| other.mode.is_check())
.or_else(|| matching_units.iter().find(|other| other.mode.is_doc()))
.unwrap_or(&unit);
self.metadata_for_doc_units
.insert(unit.clone(), self.files().metadata(metadata_unit));
}
}
}