-
Notifications
You must be signed in to change notification settings - Fork 2.4k
/
mod.rs
1761 lines (1590 loc) · 63.9 KB
/
mod.rs
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
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! # Interact with the compiler
//!
//! If you consider [`ops::cargo_compile::compile`] as a `rustc` driver but on
//! Cargo side, this module is kinda the `rustc_interface` for that merits.
//! It contains all the interaction between Cargo and the rustc compiler,
//! from preparing the context for the entire build process, to scheduling
//! and executing each unit of work (e.g. running `rustc`), to managing and
//! caching the output artifact of a build.
//!
//! However, it hasn't yet exposed a clear definition of each phase or session,
//! like what rustc has done[^1]. Also, no one knows if Cargo really needs that.
//! To be pragmatic, here we list a handful of items you may want to learn:
//!
//! * [`BuildContext`] is a static context containing all information you need
//! before a build gets started.
//! * [`Context`] is the center of the world, coordinating a running build and
//! collecting information from it.
//! * [`custom_build`] is the home of build script executions and output parsing.
//! * [`fingerprint`] not only defines but also executes a set of rules to
//! determine if a re-compile is needed.
//! * [`job_queue`] is where the parallelism, job scheduling, and communication
//! machinery happen between Cargo and the compiler.
//! * [`layout`] defines and manages output artifacts of a build in the filesystem.
//! * [`unit_dependencies`] is for building a dependency graph for compilation
//! from a result of dependency resolution.
//! * [`Unit`] contains sufficient information to build something, usually
//! turning into a compiler invocation in a later phase.
//!
//! [^1]: Maybe [`-Zbuild-plan`](https://doc.rust-lang.org/nightly/cargo/reference/unstable.html#build-plan)
//! was designed to serve that purpose but still [in flux](https://github.com/rust-lang/cargo/issues/7614).
//!
//! [`ops::cargo_compile::compile`]: crate::ops::compile
pub mod artifact;
mod build_config;
pub(crate) mod build_context;
mod build_plan;
mod compilation;
mod compile_kind;
pub(crate) mod context;
mod crate_type;
mod custom_build;
pub(crate) mod fingerprint;
pub mod future_incompat;
pub(crate) mod job_queue;
pub(crate) mod layout;
mod links;
mod lto;
mod output_depinfo;
pub mod rustdoc;
pub mod standard_lib;
mod timings;
mod unit;
pub mod unit_dependencies;
pub mod unit_graph;
use std::collections::{HashMap, HashSet};
use std::env;
use std::ffi::{OsStr, OsString};
use std::fmt::Display;
use std::fs::{self, File};
use std::io::{BufRead, Write};
use std::path::{Path, PathBuf};
use std::sync::Arc;
use anyhow::{Context as _, Error};
use lazycell::LazyCell;
use tracing::{debug, trace};
pub use self::build_config::{BuildConfig, CompileMode, MessageFormat, TimingOutput};
pub use self::build_context::{
BuildContext, FileFlavor, FileType, RustDocFingerprint, RustcTargetData, TargetInfo,
};
use self::build_plan::BuildPlan;
pub use self::compilation::{Compilation, Doctest, UnitOutput};
pub use self::compile_kind::{CompileKind, CompileTarget};
pub use self::context::{Context, Metadata};
pub use self::crate_type::CrateType;
pub use self::custom_build::LinkArgTarget;
pub use self::custom_build::{BuildOutput, BuildScriptOutputs, BuildScripts};
pub(crate) use self::fingerprint::DirtyReason;
pub use self::job_queue::Freshness;
use self::job_queue::{Job, JobQueue, JobState, Work};
pub(crate) use self::layout::Layout;
pub use self::lto::Lto;
use self::output_depinfo::output_depinfo;
use self::unit_graph::UnitDep;
use crate::core::compiler::future_incompat::FutureIncompatReport;
pub use crate::core::compiler::unit::{Unit, UnitInterner};
use crate::core::manifest::TargetSourcePath;
use crate::core::profiles::{PanicStrategy, Profile, Strip};
use crate::core::{Feature, PackageId, Target, Verbosity};
use crate::util::errors::{CargoResult, VerboseError};
use crate::util::interning::InternedString;
use crate::util::machine_message::{self, Message};
use crate::util::toml::TomlDebugInfo;
use crate::util::{add_path_args, internal, iter_join_onto, profile};
use cargo_util::{paths, ProcessBuilder, ProcessError};
use rustfix::diagnostics::Applicability;
const RUSTDOC_CRATE_VERSION_FLAG: &str = "--crate-version";
/// A glorified callback for executing calls to rustc. Rather than calling rustc
/// directly, we'll use an `Executor`, giving clients an opportunity to intercept
/// the build calls.
pub trait Executor: Send + Sync + 'static {
/// Called after a rustc process invocation is prepared up-front for a given
/// unit of work (may still be modified for runtime-known dependencies, when
/// the work is actually executed).
fn init(&self, _cx: &Context<'_, '_>, _unit: &Unit) {}
/// In case of an `Err`, Cargo will not continue with the build process for
/// this package.
fn exec(
&self,
cmd: &ProcessBuilder,
id: PackageId,
target: &Target,
mode: CompileMode,
on_stdout_line: &mut dyn FnMut(&str) -> CargoResult<()>,
on_stderr_line: &mut dyn FnMut(&str) -> CargoResult<()>,
) -> CargoResult<()>;
/// Queried when queuing each unit of work. If it returns true, then the
/// unit will always be rebuilt, independent of whether it needs to be.
fn force_rebuild(&self, _unit: &Unit) -> bool {
false
}
}
/// A `DefaultExecutor` calls rustc without doing anything else. It is Cargo's
/// default behaviour.
#[derive(Copy, Clone)]
pub struct DefaultExecutor;
impl Executor for DefaultExecutor {
fn exec(
&self,
cmd: &ProcessBuilder,
_id: PackageId,
_target: &Target,
_mode: CompileMode,
on_stdout_line: &mut dyn FnMut(&str) -> CargoResult<()>,
on_stderr_line: &mut dyn FnMut(&str) -> CargoResult<()>,
) -> CargoResult<()> {
cmd.exec_with_streaming(on_stdout_line, on_stderr_line, false)
.map(drop)
}
}
/// Builds up and enqueue a list of pending jobs onto the `job` queue.
///
/// Starting from the `unit`, this function recursively calls itself to build
/// all jobs for dependencies of the `unit`. Each of these jobs represents
/// compiling a particular package.
///
/// Note that **no actual work is executed as part of this**, that's all done
/// next as part of [`JobQueue::execute`] function which will run everything
/// in order with proper parallelism.
fn compile<'cfg>(
cx: &mut Context<'_, 'cfg>,
jobs: &mut JobQueue<'cfg>,
plan: &mut BuildPlan,
unit: &Unit,
exec: &Arc<dyn Executor>,
force_rebuild: bool,
) -> CargoResult<()> {
let bcx = cx.bcx;
let build_plan = bcx.build_config.build_plan;
if !cx.compiled.insert(unit.clone()) {
return Ok(());
}
// Build up the work to be done to compile this unit, enqueuing it once
// we've got everything constructed.
let p = profile::start(format!("preparing: {}/{}", unit.pkg, unit.target.name()));
fingerprint::prepare_init(cx, unit)?;
let job = if unit.mode.is_run_custom_build() {
custom_build::prepare(cx, unit)?
} else if unit.mode.is_doc_test() {
// We run these targets later, so this is just a no-op for now.
Job::new_fresh()
} else if build_plan {
Job::new_dirty(rustc(cx, unit, &exec.clone())?, None)
} else {
let force = exec.force_rebuild(unit) || force_rebuild;
let mut job = fingerprint::prepare_target(cx, unit, force)?;
job.before(if job.freshness().is_dirty() {
let work = if unit.mode.is_doc() || unit.mode.is_doc_scrape() {
rustdoc(cx, unit)?
} else {
rustc(cx, unit, exec)?
};
work.then(link_targets(cx, unit, false)?)
} else {
// We always replay the output cache,
// since it might contain future-incompat-report messages
let work = replay_output_cache(
unit.pkg.package_id(),
PathBuf::from(unit.pkg.manifest_path()),
&unit.target,
cx.files().message_cache_path(unit),
cx.bcx.build_config.message_format,
unit.show_warnings(bcx.config),
);
// Need to link targets on both the dirty and fresh.
work.then(link_targets(cx, unit, true)?)
});
job
};
jobs.enqueue(cx, unit, job)?;
drop(p);
// Be sure to compile all dependencies of this target as well.
let deps = Vec::from(cx.unit_deps(unit)); // Create vec due to mutable borrow.
for dep in deps {
compile(cx, jobs, plan, &dep.unit, exec, false)?;
}
if build_plan {
plan.add(cx, unit)?;
}
Ok(())
}
/// Generates the warning message used when fallible doc-scrape units fail,
/// either for rustdoc or rustc.
fn make_failed_scrape_diagnostic(
cx: &Context<'_, '_>,
unit: &Unit,
top_line: impl Display,
) -> String {
let manifest_path = unit.pkg.manifest_path();
let relative_manifest_path = manifest_path
.strip_prefix(cx.bcx.ws.root())
.unwrap_or(&manifest_path);
format!(
"\
{top_line}
Try running with `--verbose` to see the error message.
If an example should not be scanned, then consider adding `doc-scrape-examples = false` to its `[[example]]` definition in {}",
relative_manifest_path.display()
)
}
/// Creates a unit of work invoking `rustc` for building the `unit`.
fn rustc(cx: &mut Context<'_, '_>, unit: &Unit, exec: &Arc<dyn Executor>) -> CargoResult<Work> {
let mut rustc = prepare_rustc(cx, unit)?;
let build_plan = cx.bcx.build_config.build_plan;
let name = unit.pkg.name();
let buildkey = unit.buildkey();
let outputs = cx.outputs(unit)?;
let root = cx.files().out_dir(unit);
// Prepare the native lib state (extra `-L` and `-l` flags).
let build_script_outputs = Arc::clone(&cx.build_script_outputs);
let current_id = unit.pkg.package_id();
let manifest_path = PathBuf::from(unit.pkg.manifest_path());
let build_scripts = cx.build_scripts.get(unit).cloned();
// If we are a binary and the package also contains a library, then we
// don't pass the `-l` flags.
let pass_l_flag = unit.target.is_lib() || !unit.pkg.targets().iter().any(|t| t.is_lib());
let dep_info_name = if cx.files().use_extra_filename(unit) {
format!(
"{}-{}.d",
unit.target.crate_name(),
cx.files().metadata(unit)
)
} else {
format!("{}.d", unit.target.crate_name())
};
let rustc_dep_info_loc = root.join(dep_info_name);
let dep_info_loc = fingerprint::dep_info_loc(cx, unit);
let mut output_options = OutputOptions::new(cx, unit);
let package_id = unit.pkg.package_id();
let target = Target::clone(&unit.target);
let mode = unit.mode;
exec.init(cx, unit);
let exec = exec.clone();
let root_output = cx.files().host_dest().to_path_buf();
let target_dir = cx.bcx.ws.target_dir().into_path_unlocked();
let pkg_root = unit.pkg.root().to_path_buf();
let cwd = rustc
.get_cwd()
.unwrap_or_else(|| cx.bcx.config.cwd())
.to_path_buf();
let fingerprint_dir = cx.files().fingerprint_dir(unit);
let script_metadata = cx.find_build_script_metadata(unit);
let is_local = unit.is_local();
let artifact = unit.artifact;
let hide_diagnostics_for_scrape_unit = cx.bcx.unit_can_fail_for_docscraping(unit)
&& !matches!(cx.bcx.config.shell().verbosity(), Verbosity::Verbose);
let failed_scrape_diagnostic = hide_diagnostics_for_scrape_unit.then(|| {
// If this unit is needed for doc-scraping, then we generate a diagnostic that
// describes the set of reverse-dependencies that cause the unit to be needed.
let target_desc = unit.target.description_named();
let mut for_scrape_units = cx
.bcx
.scrape_units_have_dep_on(unit)
.into_iter()
.map(|unit| unit.target.description_named())
.collect::<Vec<_>>();
for_scrape_units.sort();
let for_scrape_units = for_scrape_units.join(", ");
make_failed_scrape_diagnostic(cx, unit, format_args!("failed to check {target_desc} in package `{name}` as a prerequisite for scraping examples from: {for_scrape_units}"))
});
if hide_diagnostics_for_scrape_unit {
output_options.show_diagnostics = false;
}
return Ok(Work::new(move |state| {
// Artifacts are in a different location than typical units,
// hence we must assure the crate- and target-dependent
// directory is present.
if artifact.is_true() {
paths::create_dir_all(&root)?;
}
// Only at runtime have we discovered what the extra -L and -l
// arguments are for native libraries, so we process those here. We
// also need to be sure to add any -L paths for our plugins to the
// dynamic library load path as a plugin's dynamic library may be
// located somewhere in there.
// Finally, if custom environment variables have been produced by
// previous build scripts, we include them in the rustc invocation.
if let Some(build_scripts) = build_scripts {
let script_outputs = build_script_outputs.lock().unwrap();
if !build_plan {
add_native_deps(
&mut rustc,
&script_outputs,
&build_scripts,
pass_l_flag,
&target,
current_id,
)?;
add_plugin_deps(&mut rustc, &script_outputs, &build_scripts, &root_output)?;
}
add_custom_flags(&mut rustc, &script_outputs, script_metadata)?;
}
for output in outputs.iter() {
// If there is both an rmeta and rlib, rustc will prefer to use the
// rlib, even if it is older. Therefore, we must delete the rlib to
// force using the new rmeta.
if output.path.extension() == Some(OsStr::new("rmeta")) {
let dst = root.join(&output.path).with_extension("rlib");
if dst.exists() {
paths::remove_file(&dst)?;
}
}
// Some linkers do not remove the executable, but truncate and modify it.
// That results in the old hard-link being modified even after renamed.
// We delete the old artifact here to prevent this behavior from confusing users.
// See rust-lang/cargo#8348.
if output.hardlink.is_some() && output.path.exists() {
_ = paths::remove_file(&output.path).map_err(|e| {
tracing::debug!(
"failed to delete previous output file `{:?}`: {e:?}",
output.path
);
});
}
}
fn verbose_if_simple_exit_code(err: Error) -> Error {
// If a signal on unix (`code == None`) or an abnormal termination
// on Windows (codes like `0xC0000409`), don't hide the error details.
match err
.downcast_ref::<ProcessError>()
.as_ref()
.and_then(|perr| perr.code)
{
Some(n) if cargo_util::is_simple_exit_code(n) => VerboseError::new(err).into(),
_ => err,
}
}
state.running(&rustc);
let timestamp = paths::set_invocation_time(&fingerprint_dir)?;
if build_plan {
state.build_plan(buildkey, rustc.clone(), outputs.clone());
} else {
let result = exec
.exec(
&rustc,
package_id,
&target,
mode,
&mut |line| on_stdout_line(state, line, package_id, &target),
&mut |line| {
on_stderr_line(
state,
line,
package_id,
&manifest_path,
&target,
&mut output_options,
)
},
)
.map_err(verbose_if_simple_exit_code)
.with_context(|| {
// adapted from rustc_errors/src/lib.rs
let warnings = match output_options.warnings_seen {
0 => String::new(),
1 => "; 1 warning emitted".to_string(),
count => format!("; {} warnings emitted", count),
};
let errors = match output_options.errors_seen {
0 => String::new(),
1 => " due to previous error".to_string(),
count => format!(" due to {} previous errors", count),
};
let name = descriptive_pkg_name(&name, &target, &mode);
format!("could not compile {name}{errors}{warnings}")
});
if let Err(e) = result {
if let Some(diagnostic) = failed_scrape_diagnostic {
state.warning(diagnostic)?;
}
return Err(e);
}
// Exec should never return with success *and* generate an error.
debug_assert_eq!(output_options.errors_seen, 0);
}
if rustc_dep_info_loc.exists() {
fingerprint::translate_dep_info(
&rustc_dep_info_loc,
&dep_info_loc,
&cwd,
&pkg_root,
&target_dir,
&rustc,
// Do not track source files in the fingerprint for registry dependencies.
is_local,
)
.with_context(|| {
internal(format!(
"could not parse/generate dep info at: {}",
rustc_dep_info_loc.display()
))
})?;
// This mtime shift allows Cargo to detect if a source file was
// modified in the middle of the build.
paths::set_file_time_no_err(dep_info_loc, timestamp);
}
Ok(())
}));
// Add all relevant `-L` and `-l` flags from dependencies (now calculated and
// present in `state`) to the command provided.
fn add_native_deps(
rustc: &mut ProcessBuilder,
build_script_outputs: &BuildScriptOutputs,
build_scripts: &BuildScripts,
pass_l_flag: bool,
target: &Target,
current_id: PackageId,
) -> CargoResult<()> {
for key in build_scripts.to_link.iter() {
let output = build_script_outputs.get(key.1).ok_or_else(|| {
internal(format!(
"couldn't find build script output for {}/{}",
key.0, key.1
))
})?;
for path in output.library_paths.iter() {
rustc.arg("-L").arg(path);
}
if key.0 == current_id {
if pass_l_flag {
for name in output.library_links.iter() {
rustc.arg("-l").arg(name);
}
}
}
for (lt, arg) in &output.linker_args {
// There was an unintentional change where cdylibs were
// allowed to be passed via transitive dependencies. This
// clause should have been kept in the `if` block above. For
// now, continue allowing it for cdylib only.
// See https://github.com/rust-lang/cargo/issues/9562
if lt.applies_to(target) && (key.0 == current_id || *lt == LinkArgTarget::Cdylib) {
rustc.arg("-C").arg(format!("link-arg={}", arg));
}
}
}
Ok(())
}
}
/// Link the compiled target (often of form `foo-{metadata_hash}`) to the
/// final target. This must happen during both "Fresh" and "Compile".
fn link_targets(cx: &mut Context<'_, '_>, unit: &Unit, fresh: bool) -> CargoResult<Work> {
let bcx = cx.bcx;
let outputs = cx.outputs(unit)?;
let export_dir = cx.files().export_dir();
let package_id = unit.pkg.package_id();
let manifest_path = PathBuf::from(unit.pkg.manifest_path());
let profile = unit.profile.clone();
let unit_mode = unit.mode;
let features = unit.features.iter().map(|s| s.to_string()).collect();
let json_messages = bcx.build_config.emit_json();
let executable = cx.get_executable(unit)?;
let mut target = Target::clone(&unit.target);
if let TargetSourcePath::Metabuild = target.src_path() {
// Give it something to serialize.
let path = unit.pkg.manifest().metabuild_path(cx.bcx.ws.target_dir());
target.set_src_path(TargetSourcePath::Path(path));
}
Ok(Work::new(move |state| {
// If we're a "root crate", e.g., the target of this compilation, then we
// hard link our outputs out of the `deps` directory into the directory
// above. This means that `cargo build` will produce binaries in
// `target/debug` which one probably expects.
let mut destinations = vec![];
for output in outputs.iter() {
let src = &output.path;
// This may have been a `cargo rustc` command which changes the
// output, so the source may not actually exist.
if !src.exists() {
continue;
}
let Some(dst) = output.hardlink.as_ref() else {
destinations.push(src.clone());
continue;
};
destinations.push(dst.clone());
paths::link_or_copy(src, dst)?;
if let Some(ref path) = output.export_path {
let export_dir = export_dir.as_ref().unwrap();
paths::create_dir_all(export_dir)?;
paths::link_or_copy(src, path)?;
}
}
if json_messages {
let debuginfo = match profile.debuginfo.into_inner() {
TomlDebugInfo::None => machine_message::ArtifactDebuginfo::Int(0),
TomlDebugInfo::Limited => machine_message::ArtifactDebuginfo::Int(1),
TomlDebugInfo::Full => machine_message::ArtifactDebuginfo::Int(2),
TomlDebugInfo::LineDirectivesOnly => {
machine_message::ArtifactDebuginfo::Named("line-directives-only")
}
TomlDebugInfo::LineTablesOnly => {
machine_message::ArtifactDebuginfo::Named("line-tables-only")
}
};
let art_profile = machine_message::ArtifactProfile {
opt_level: profile.opt_level.as_str(),
debuginfo: Some(debuginfo),
debug_assertions: profile.debug_assertions,
overflow_checks: profile.overflow_checks,
test: unit_mode.is_any_test(),
};
let msg = machine_message::Artifact {
package_id,
manifest_path,
target: &target,
profile: art_profile,
features,
filenames: destinations,
executable,
fresh,
}
.to_json_string();
state.stdout(msg)?;
}
Ok(())
}))
}
// For all plugin dependencies, add their -L paths (now calculated and present
// in `build_script_outputs`) to the dynamic library load path for the command
// to execute.
fn add_plugin_deps(
rustc: &mut ProcessBuilder,
build_script_outputs: &BuildScriptOutputs,
build_scripts: &BuildScripts,
root_output: &Path,
) -> CargoResult<()> {
let var = paths::dylib_path_envvar();
let search_path = rustc.get_env(var).unwrap_or_default();
let mut search_path = env::split_paths(&search_path).collect::<Vec<_>>();
for (pkg_id, metadata) in &build_scripts.plugins {
let output = build_script_outputs
.get(*metadata)
.ok_or_else(|| internal(format!("couldn't find libs for plugin dep {}", pkg_id)))?;
search_path.append(&mut filter_dynamic_search_path(
output.library_paths.iter(),
root_output,
));
}
let search_path = paths::join_paths(&search_path, var)?;
rustc.env(var, &search_path);
Ok(())
}
// Determine paths to add to the dynamic search path from -L entries
//
// Strip off prefixes like "native=" or "framework=" and filter out directories
// **not** inside our output directory since they are likely spurious and can cause
// clashes with system shared libraries (issue #3366).
fn filter_dynamic_search_path<'a, I>(paths: I, root_output: &Path) -> Vec<PathBuf>
where
I: Iterator<Item = &'a PathBuf>,
{
let mut search_path = vec![];
for dir in paths {
let dir = match dir.to_str().and_then(|s| s.split_once("=")) {
Some(("native" | "crate" | "dependency" | "framework" | "all", path)) => path.into(),
_ => dir.clone(),
};
if dir.starts_with(&root_output) {
search_path.push(dir);
} else {
debug!(
"Not including path {} in runtime library search path because it is \
outside target root {}",
dir.display(),
root_output.display()
);
}
}
search_path
}
/// Prepares flags and environments we can compute for a `rustc` invocation
/// before the job queue starts compiling any unit.
///
/// This builds a static view of the invocation. Flags depending on the
/// completion of other units will be added later in runtime, such as flags
/// from build scripts.
fn prepare_rustc(cx: &Context<'_, '_>, unit: &Unit) -> CargoResult<ProcessBuilder> {
let is_primary = cx.is_primary_package(unit);
let is_workspace = cx.bcx.ws.is_member(&unit.pkg);
let mut base = cx
.compilation
.rustc_process(unit, is_primary, is_workspace)?;
if is_primary {
base.env("CARGO_PRIMARY_PACKAGE", "1");
}
if unit.target.is_test() || unit.target.is_bench() {
let tmp = cx.files().layout(unit.kind).prepare_tmp()?;
base.env("CARGO_TARGET_TMPDIR", tmp.display().to_string());
}
base.inherit_jobserver(&cx.jobserver);
build_base_args(cx, &mut base, unit)?;
build_deps_args(&mut base, cx, unit)?;
add_cap_lints(cx.bcx, unit, &mut base);
base.args(cx.bcx.rustflags_args(unit));
if cx.bcx.config.cli_unstable().binary_dep_depinfo {
base.arg("-Z").arg("binary-dep-depinfo");
}
Ok(base)
}
/// Prepares flags and environments we can compute for a `rustdoc` invocation
/// before the job queue starts compiling any unit.
///
/// This builds a static view of the invocation. Flags depending on the
/// completion of other units will be added later in runtime, such as flags
/// from build scripts.
fn prepare_rustdoc(cx: &Context<'_, '_>, unit: &Unit) -> CargoResult<ProcessBuilder> {
let bcx = cx.bcx;
// script_metadata is not needed here, it is only for tests.
let mut rustdoc = cx.compilation.rustdoc_process(unit, None)?;
rustdoc.inherit_jobserver(&cx.jobserver);
let crate_name = unit.target.crate_name();
rustdoc.arg("--crate-name").arg(&crate_name);
add_path_args(bcx.ws, unit, &mut rustdoc);
add_cap_lints(bcx, unit, &mut rustdoc);
if let CompileKind::Target(target) = unit.kind {
rustdoc.arg("--target").arg(target.rustc_target());
}
let doc_dir = cx.files().out_dir(unit);
rustdoc.arg("-o").arg(&doc_dir);
rustdoc.args(&features_args(unit));
rustdoc.args(&check_cfg_args(cx, unit));
add_error_format_and_color(cx, &mut rustdoc);
add_allow_features(cx, &mut rustdoc);
rustdoc.args(unit.pkg.manifest().lint_rustflags());
if let Some(args) = cx.bcx.extra_args_for(unit) {
rustdoc.args(args);
}
let metadata = cx.metadata_for_doc_units[unit];
rustdoc.arg("-C").arg(format!("metadata={}", metadata));
if unit.mode.is_doc_scrape() {
debug_assert!(cx.bcx.scrape_units.contains(unit));
if unit.target.is_test() {
rustdoc.arg("--scrape-tests");
}
rustdoc.arg("-Zunstable-options");
rustdoc
.arg("--scrape-examples-output-path")
.arg(scrape_output_path(cx, unit)?);
// Only scrape example for items from crates in the workspace, to reduce generated file size
for pkg in cx.bcx.ws.members() {
let names = pkg
.targets()
.iter()
.map(|target| target.crate_name())
.collect::<HashSet<_>>();
for name in names {
rustdoc.arg("--scrape-examples-target-crate").arg(name);
}
}
}
if should_include_scrape_units(cx.bcx, unit) {
rustdoc.arg("-Zunstable-options");
}
build_deps_args(&mut rustdoc, cx, unit)?;
rustdoc::add_root_urls(cx, unit, &mut rustdoc)?;
rustdoc.args(bcx.rustdocflags_args(unit));
if !crate_version_flag_already_present(&rustdoc) {
append_crate_version_flag(unit, &mut rustdoc);
}
Ok(rustdoc)
}
/// Creates a unit of work invoking `rustdoc` for documenting the `unit`.
fn rustdoc(cx: &mut Context<'_, '_>, unit: &Unit) -> CargoResult<Work> {
let mut rustdoc = prepare_rustdoc(cx, unit)?;
let crate_name = unit.target.crate_name();
let doc_dir = cx.files().out_dir(unit);
// Create the documentation directory ahead of time as rustdoc currently has
// a bug where concurrent invocations will race to create this directory if
// it doesn't already exist.
paths::create_dir_all(&doc_dir)?;
let target_desc = unit.target.description_named();
let name = unit.pkg.name();
let build_script_outputs = Arc::clone(&cx.build_script_outputs);
let package_id = unit.pkg.package_id();
let manifest_path = PathBuf::from(unit.pkg.manifest_path());
let target = Target::clone(&unit.target);
let mut output_options = OutputOptions::new(cx, unit);
let script_metadata = cx.find_build_script_metadata(unit);
let scrape_outputs = if should_include_scrape_units(cx.bcx, unit) {
Some(
cx.bcx
.scrape_units
.iter()
.map(|unit| Ok((cx.files().metadata(unit), scrape_output_path(cx, unit)?)))
.collect::<CargoResult<HashMap<_, _>>>()?,
)
} else {
None
};
let failed_scrape_units = Arc::clone(&cx.failed_scrape_units);
let hide_diagnostics_for_scrape_unit = cx.bcx.unit_can_fail_for_docscraping(unit)
&& !matches!(cx.bcx.config.shell().verbosity(), Verbosity::Verbose);
let failed_scrape_diagnostic = hide_diagnostics_for_scrape_unit.then(|| {
make_failed_scrape_diagnostic(
cx,
unit,
format_args!("failed to scan {target_desc} in package `{name}` for example code usage"),
)
});
if hide_diagnostics_for_scrape_unit {
output_options.show_diagnostics = false;
}
Ok(Work::new(move |state| {
add_custom_flags(
&mut rustdoc,
&build_script_outputs.lock().unwrap(),
script_metadata,
)?;
// Add the output of scraped examples to the rustdoc command.
// This action must happen after the unit's dependencies have finished,
// because some of those deps may be Docscrape units which have failed.
// So we dynamically determine which `--with-examples` flags to pass here.
if let Some(scrape_outputs) = scrape_outputs {
let failed_scrape_units = failed_scrape_units.lock().unwrap();
for (metadata, output_path) in &scrape_outputs {
if !failed_scrape_units.contains(metadata) {
rustdoc.arg("--with-examples").arg(output_path);
}
}
}
let crate_dir = doc_dir.join(&crate_name);
if crate_dir.exists() {
// Remove output from a previous build. This ensures that stale
// files for removed items are removed.
debug!("removing pre-existing doc directory {:?}", crate_dir);
paths::remove_dir_all(crate_dir)?;
}
state.running(&rustdoc);
let result = rustdoc
.exec_with_streaming(
&mut |line| on_stdout_line(state, line, package_id, &target),
&mut |line| {
on_stderr_line(
state,
line,
package_id,
&manifest_path,
&target,
&mut output_options,
)
},
false,
)
.with_context(|| format!("could not document `{}`", name));
if let Err(e) = result {
if let Some(diagnostic) = failed_scrape_diagnostic {
state.warning(diagnostic)?;
}
return Err(e);
}
Ok(())
}))
}
// The --crate-version flag could have already been passed in RUSTDOCFLAGS
// or as an extra compiler argument for rustdoc
fn crate_version_flag_already_present(rustdoc: &ProcessBuilder) -> bool {
rustdoc.get_args().any(|flag| {
flag.to_str()
.map_or(false, |flag| flag.starts_with(RUSTDOC_CRATE_VERSION_FLAG))
})
}
fn append_crate_version_flag(unit: &Unit, rustdoc: &mut ProcessBuilder) {
rustdoc
.arg(RUSTDOC_CRATE_VERSION_FLAG)
.arg(unit.pkg.version().to_string());
}
/// Adds [`--cap-lints`] to the command to execute.
///
/// [`--cap-lints`]: https://doc.rust-lang.org/nightly/rustc/lints/levels.html#capping-lints
fn add_cap_lints(bcx: &BuildContext<'_, '_>, unit: &Unit, cmd: &mut ProcessBuilder) {
// If this is an upstream dep we don't want warnings from, turn off all
// lints.
if !unit.show_warnings(bcx.config) {
cmd.arg("--cap-lints").arg("allow");
// If this is an upstream dep but we *do* want warnings, make sure that they
// don't fail compilation.
} else if !unit.is_local() {
cmd.arg("--cap-lints").arg("warn");
}
}
/// Forwards [`-Zallow-features`] if it is set for cargo.
///
/// [`-Zallow-features`]: https://doc.rust-lang.org/nightly/cargo/reference/unstable.html#allow-features
fn add_allow_features(cx: &Context<'_, '_>, cmd: &mut ProcessBuilder) {
if let Some(allow) = &cx.bcx.config.cli_unstable().allow_features {
let mut arg = String::from("-Zallow-features=");
let _ = iter_join_onto(&mut arg, allow, ",");
cmd.arg(&arg);
}
}
/// Adds [`--error-format`] to the command to execute.
///
/// Cargo always uses JSON output. This has several benefits, such as being
/// easier to parse, handles changing formats (for replaying cached messages),
/// ensures atomic output (so messages aren't interleaved), allows for
/// intercepting messages like rmeta artifacts, etc. rustc includes a
/// "rendered" field in the JSON message with the message properly formatted,
/// which Cargo will extract and display to the user.
///
/// [`--error-format`]: https://doc.rust-lang.org/nightly/rustc/command-line-arguments.html#--error-format-control-how-errors-are-produced
fn add_error_format_and_color(cx: &Context<'_, '_>, cmd: &mut ProcessBuilder) {
cmd.arg("--error-format=json");
let mut json = String::from("--json=diagnostic-rendered-ansi,artifacts,future-incompat");
match cx.bcx.build_config.message_format {
MessageFormat::Short | MessageFormat::Json { short: true, .. } => {
json.push_str(",diagnostic-short");
}
_ => {}
}
cmd.arg(json);
let config = cx.bcx.config;
if let Some(width) = config.shell().err_width().diagnostic_terminal_width() {
cmd.arg(format!("--diagnostic-width={width}"));
}
}
/// Adds essential rustc flags and environment variables to the command to execute.
fn build_base_args(cx: &Context<'_, '_>, cmd: &mut ProcessBuilder, unit: &Unit) -> CargoResult<()> {
assert!(!unit.mode.is_run_custom_build());
let bcx = cx.bcx;
let Profile {
ref opt_level,
codegen_backend,
codegen_units,
debuginfo,
debug_assertions,
split_debuginfo,
overflow_checks,
rpath,
ref panic,
incremental,
strip,
rustflags: profile_rustflags,
..
} = unit.profile.clone();
let test = unit.mode.is_any_test();
cmd.arg("--crate-name").arg(&unit.target.crate_name());
let edition = unit.target.edition();
edition.cmd_edition_arg(cmd);
add_path_args(bcx.ws, unit, cmd);
add_error_format_and_color(cx, cmd);
add_allow_features(cx, cmd);
let mut contains_dy_lib = false;
if !test {
for crate_type in &unit.target.rustc_crate_types() {
cmd.arg("--crate-type").arg(crate_type.as_str());
contains_dy_lib |= crate_type == &CrateType::Dylib;
}
}
if unit.mode.is_check() {
cmd.arg("--emit=dep-info,metadata");
} else if !unit.requires_upstream_objects() {
// Always produce metadata files for rlib outputs. Metadata may be used
// in this session for a pipelined compilation, or it may be used in a
// future Cargo session as part of a pipelined compile.
cmd.arg("--emit=dep-info,metadata,link");
} else {
cmd.arg("--emit=dep-info,link");
}
let prefer_dynamic = (unit.target.for_host() && !unit.target.is_custom_build())
|| (contains_dy_lib && !cx.is_primary_package(unit));
if prefer_dynamic {
cmd.arg("-C").arg("prefer-dynamic");
}
if opt_level.as_str() != "0" {
cmd.arg("-C").arg(&format!("opt-level={}", opt_level));
}
if *panic != PanicStrategy::Unwind {
cmd.arg("-C").arg(format!("panic={}", panic));
}
cmd.args(<o_args(cx, unit));