1use super::{BuildRunner, Job, Unit, Work, fingerprint, get_dynamic_search_path};
35use crate::core::compiler::CompileMode;
36use crate::core::compiler::artifact;
37use crate::core::compiler::build_runner::UnitHash;
38use crate::core::compiler::fingerprint::DirtyReason;
39use crate::core::compiler::job_queue::JobState;
40use crate::core::{PackageId, Target, profiles::ProfileRoot};
41use crate::util::errors::CargoResult;
42use crate::util::internal;
43use crate::util::machine_message::{self, Message};
44use anyhow::{Context as _, bail};
45use cargo_platform::Cfg;
46use cargo_util::paths;
47use cargo_util_schemas::manifest::RustVersion;
48use std::collections::hash_map::{Entry, HashMap};
49use std::collections::{BTreeSet, HashSet};
50use std::path::{Path, PathBuf};
51use std::str::{self, FromStr};
52use std::sync::{Arc, Mutex};
53
54const CARGO_ERROR_SYNTAX: &str = "cargo::error=";
59const OLD_CARGO_WARNING_SYNTAX: &str = "cargo:warning=";
64const NEW_CARGO_WARNING_SYNTAX: &str = "cargo::warning=";
69
70#[derive(Clone, Debug, Hash, PartialEq, Eq, PartialOrd, Ord)]
71pub enum Severity {
72 Error,
73 Warning,
74}
75
76pub type LogMessage = (Severity, String);
77
78#[derive(Clone, Debug, Hash, PartialEq, Eq, PartialOrd, Ord)]
109pub enum LibraryPath {
110 CargoArtifact(PathBuf),
113 External(PathBuf),
116}
117
118impl LibraryPath {
119 fn new(p: PathBuf, script_out_dir: &Path) -> Self {
120 let search_path = get_dynamic_search_path(&p);
121 if search_path.starts_with(script_out_dir) {
122 Self::CargoArtifact(p)
123 } else {
124 Self::External(p)
125 }
126 }
127
128 pub fn into_path_buf(self) -> PathBuf {
129 match self {
130 LibraryPath::CargoArtifact(p) | LibraryPath::External(p) => p,
131 }
132 }
133}
134
135impl AsRef<PathBuf> for LibraryPath {
136 fn as_ref(&self) -> &PathBuf {
137 match self {
138 LibraryPath::CargoArtifact(p) | LibraryPath::External(p) => p,
139 }
140 }
141}
142
143#[derive(Clone, Debug, Hash, Default, PartialEq, Eq, PartialOrd, Ord)]
145pub struct BuildOutput {
146 pub library_paths: Vec<LibraryPath>,
148 pub library_links: Vec<String>,
150 pub linker_args: Vec<(LinkArgTarget, String)>,
152 pub cfgs: Vec<String>,
154 pub check_cfgs: Vec<String>,
156 pub env: Vec<(String, String)>,
158 pub metadata: Vec<(String, String)>,
160 pub rerun_if_changed: Vec<PathBuf>,
163 pub rerun_if_env_changed: Vec<String>,
165 pub log_messages: Vec<LogMessage>,
172}
173
174#[derive(Default)]
185pub struct BuildScriptOutputs {
186 outputs: HashMap<UnitHash, BuildOutput>,
187}
188
189#[derive(Default)]
193pub struct BuildScripts {
194 pub to_link: Vec<(PackageId, UnitHash)>,
211 seen_to_link: HashSet<(PackageId, UnitHash)>,
213 pub plugins: BTreeSet<(PackageId, UnitHash)>,
222}
223
224#[derive(Debug)]
227pub struct BuildDeps {
228 pub build_script_output: PathBuf,
231 pub rerun_if_changed: Vec<PathBuf>,
233 pub rerun_if_env_changed: Vec<String>,
235}
236
237#[derive(Clone, Hash, Debug, PartialEq, Eq, PartialOrd, Ord)]
246pub enum LinkArgTarget {
247 All,
249 Cdylib,
251 Bin,
253 SingleBin(String),
255 Test,
257 Bench,
259 Example,
261}
262
263impl LinkArgTarget {
264 pub fn applies_to(&self, target: &Target, mode: CompileMode) -> bool {
266 let is_test = mode.is_any_test();
267 match self {
268 LinkArgTarget::All => true,
269 LinkArgTarget::Cdylib => !is_test && target.is_cdylib(),
270 LinkArgTarget::Bin => target.is_bin(),
271 LinkArgTarget::SingleBin(name) => target.is_bin() && target.name() == name,
272 LinkArgTarget::Test => target.is_test(),
273 LinkArgTarget::Bench => target.is_bench(),
274 LinkArgTarget::Example => target.is_exe_example(),
275 }
276 }
277}
278
279#[tracing::instrument(skip_all)]
281pub fn prepare(build_runner: &mut BuildRunner<'_, '_>, unit: &Unit) -> CargoResult<Job> {
282 let metadata = build_runner.get_run_build_script_metadata(unit);
283 if build_runner
284 .build_script_outputs
285 .lock()
286 .unwrap()
287 .contains_key(metadata)
288 {
289 fingerprint::prepare_target(build_runner, unit, false)
291 } else {
292 build_work(build_runner, unit)
293 }
294}
295
296fn emit_build_output(
299 state: &JobState<'_, '_>,
300 output: &BuildOutput,
301 out_dir: &Path,
302 package_id: PackageId,
303) -> CargoResult<()> {
304 let library_paths = output
305 .library_paths
306 .iter()
307 .map(|l| l.as_ref().display().to_string())
308 .collect::<Vec<_>>();
309
310 let msg = machine_message::BuildScript {
311 package_id: package_id.to_spec(),
312 linked_libs: &output.library_links,
313 linked_paths: &library_paths,
314 cfgs: &output.cfgs,
315 env: &output.env,
316 out_dir,
317 }
318 .to_json_string();
319 state.stdout(msg)?;
320 Ok(())
321}
322
323fn build_work(build_runner: &mut BuildRunner<'_, '_>, unit: &Unit) -> CargoResult<Job> {
332 assert!(unit.mode.is_run_custom_build());
333 let bcx = &build_runner.bcx;
334 let dependencies = build_runner.unit_deps(unit);
335 let build_script_unit = dependencies
336 .iter()
337 .find(|d| !d.unit.mode.is_run_custom_build() && d.unit.target.is_custom_build())
338 .map(|d| &d.unit)
339 .expect("running a script not depending on an actual script");
340 let script_dir = build_runner.files().build_script_dir(build_script_unit);
341 let script_out_dir = build_runner.files().build_script_out_dir(unit);
342 let script_run_dir = build_runner.files().build_script_run_dir(unit);
343 let build_plan = bcx.build_config.build_plan;
344 let invocation_name = unit.buildkey();
345
346 if let Some(deps) = unit.pkg.manifest().metabuild() {
347 prepare_metabuild(build_runner, build_script_unit, deps)?;
348 }
349
350 let to_exec = script_dir.join(unit.target.name());
352
353 let to_exec = to_exec.into_os_string();
361 let mut cmd = build_runner.compilation.host_process(to_exec, &unit.pkg)?;
362 let debug = unit.profile.debuginfo.is_turned_on();
363 cmd.env("OUT_DIR", &script_out_dir)
364 .env("CARGO_MANIFEST_DIR", unit.pkg.root())
365 .env("CARGO_MANIFEST_PATH", unit.pkg.manifest_path())
366 .env("NUM_JOBS", &bcx.jobs().to_string())
367 .env("TARGET", bcx.target_data.short_name(&unit.kind))
368 .env("DEBUG", debug.to_string())
369 .env("OPT_LEVEL", &unit.profile.opt_level)
370 .env(
371 "PROFILE",
372 match unit.profile.root {
373 ProfileRoot::Release => "release",
374 ProfileRoot::Debug => "debug",
375 },
376 )
377 .env("HOST", &bcx.host_triple())
378 .env("RUSTC", &bcx.rustc().path)
379 .env("RUSTDOC", &*bcx.gctx.rustdoc()?)
380 .inherit_jobserver(&build_runner.jobserver);
381
382 for (var, value) in artifact::get_env(build_runner, dependencies)? {
384 cmd.env(&var, value);
385 }
386
387 if let Some(linker) = &build_runner.compilation.target_linker(unit.kind) {
388 cmd.env("RUSTC_LINKER", linker);
389 }
390
391 if let Some(links) = unit.pkg.manifest().links() {
392 cmd.env("CARGO_MANIFEST_LINKS", links);
393 }
394
395 if let Some(trim_paths) = unit.profile.trim_paths.as_ref() {
396 cmd.env("CARGO_TRIM_PATHS", trim_paths.to_string());
397 }
398
399 for feat in &unit.features {
402 cmd.env(&format!("CARGO_FEATURE_{}", super::envify(feat)), "1");
403 }
404
405 let mut cfg_map = HashMap::new();
406 cfg_map.insert(
407 "feature",
408 unit.features.iter().map(|s| s.as_str()).collect::<Vec<_>>(),
409 );
410 for cfg in bcx.target_data.cfg(unit.kind) {
411 match *cfg {
412 Cfg::Name(ref n) => {
413 cfg_map.insert(n.as_str(), Vec::new());
414 }
415 Cfg::KeyPair(ref k, ref v) => {
416 let values = cfg_map.entry(k.as_str()).or_default();
417 values.push(v.as_str());
418 }
419 }
420 }
421 for (k, v) in cfg_map {
422 if k == "debug_assertions" {
423 continue;
426 }
427 let k = format!("CARGO_CFG_{}", super::envify(k));
430 cmd.env(&k, v.join(","));
431 }
432
433 if let Some(wrapper) = bcx.rustc().wrapper.as_ref() {
435 cmd.env("RUSTC_WRAPPER", wrapper);
436 } else {
437 cmd.env_remove("RUSTC_WRAPPER");
438 }
439 cmd.env_remove("RUSTC_WORKSPACE_WRAPPER");
440 if build_runner.bcx.ws.is_member(&unit.pkg) {
441 if let Some(wrapper) = bcx.rustc().workspace_wrapper.as_ref() {
442 cmd.env("RUSTC_WORKSPACE_WRAPPER", wrapper);
443 }
444 }
445 cmd.env("CARGO_ENCODED_RUSTFLAGS", unit.rustflags.join("\x1f"));
446 cmd.env_remove("RUSTFLAGS");
447
448 if build_runner.bcx.ws.gctx().extra_verbose() {
449 cmd.display_env_vars();
450 }
451
452 let lib_deps = dependencies
458 .iter()
459 .filter_map(|dep| {
460 if dep.unit.mode.is_run_custom_build() {
461 let dep_metadata = build_runner.get_run_build_script_metadata(&dep.unit);
462 Some((
463 dep.unit.pkg.manifest().links().unwrap().to_string(),
464 dep.unit.pkg.package_id(),
465 dep_metadata,
466 ))
467 } else {
468 None
469 }
470 })
471 .collect::<Vec<_>>();
472 let library_name = unit.pkg.library().map(|t| t.crate_name());
473 let pkg_descr = unit.pkg.to_string();
474 let build_script_outputs = Arc::clone(&build_runner.build_script_outputs);
475 let id = unit.pkg.package_id();
476 let output_file = script_run_dir.join("output");
477 let err_file = script_run_dir.join("stderr");
478 let root_output_file = script_run_dir.join("root-output");
479 let host_target_root = build_runner.files().host_dest().to_path_buf();
480 let all = (
481 id,
482 library_name.clone(),
483 pkg_descr.clone(),
484 Arc::clone(&build_script_outputs),
485 output_file.clone(),
486 script_out_dir.clone(),
487 );
488 let build_scripts = build_runner.build_scripts.get(unit).cloned();
489 let json_messages = bcx.build_config.emit_json();
490 let extra_verbose = bcx.gctx.extra_verbose();
491 let (prev_output, prev_script_out_dir) = prev_build_output(build_runner, unit);
492 let metadata_hash = build_runner.get_run_build_script_metadata(unit);
493
494 paths::create_dir_all(&script_dir)?;
495 paths::create_dir_all(&script_out_dir)?;
496
497 let nightly_features_allowed = build_runner.bcx.gctx.nightly_features_allowed;
498 let targets: Vec<Target> = unit.pkg.targets().to_vec();
499 let msrv = unit.pkg.rust_version().cloned();
500 let targets_fresh = targets.clone();
502 let msrv_fresh = msrv.clone();
503
504 let env_profile_name = unit.profile.name.to_uppercase();
505 let built_with_debuginfo = build_runner
506 .bcx
507 .unit_graph
508 .get(unit)
509 .and_then(|deps| deps.iter().find(|dep| dep.unit.target == unit.target))
510 .map(|dep| dep.unit.profile.debuginfo.is_turned_on())
511 .unwrap_or(false);
512
513 let dirty = Work::new(move |state| {
519 paths::create_dir_all(&script_out_dir)
524 .context("failed to create script output directory for build command")?;
525
526 if !build_plan {
531 let build_script_outputs = build_script_outputs.lock().unwrap();
532 for (name, dep_id, dep_metadata) in lib_deps {
533 let script_output = build_script_outputs.get(dep_metadata).ok_or_else(|| {
534 internal(format!(
535 "failed to locate build state for env vars: {}/{}",
536 dep_id, dep_metadata
537 ))
538 })?;
539 let data = &script_output.metadata;
540 for (key, value) in data.iter() {
541 cmd.env(
542 &format!("DEP_{}_{}", super::envify(&name), super::envify(key)),
543 value,
544 );
545 }
546 }
547 if let Some(build_scripts) = build_scripts {
548 super::add_plugin_deps(
549 &mut cmd,
550 &build_script_outputs,
551 &build_scripts,
552 &host_target_root,
553 )?;
554 }
555 }
556
557 if build_plan {
558 state.build_plan(invocation_name, cmd.clone(), Arc::new(Vec::new()));
559 return Ok(());
560 }
561
562 state.running(&cmd);
564 let timestamp = paths::set_invocation_time(&script_run_dir)?;
565 let prefix = format!("[{} {}] ", id.name(), id.version());
566 let mut log_messages_in_case_of_panic = Vec::new();
567 let output = cmd
568 .exec_with_streaming(
569 &mut |stdout| {
570 if let Some(error) = stdout.strip_prefix(CARGO_ERROR_SYNTAX) {
571 log_messages_in_case_of_panic.push((Severity::Error, error.to_owned()));
572 }
573 if let Some(warning) = stdout
574 .strip_prefix(OLD_CARGO_WARNING_SYNTAX)
575 .or(stdout.strip_prefix(NEW_CARGO_WARNING_SYNTAX))
576 {
577 log_messages_in_case_of_panic.push((Severity::Warning, warning.to_owned()));
578 }
579 if extra_verbose {
580 state.stdout(format!("{}{}", prefix, stdout))?;
581 }
582 Ok(())
583 },
584 &mut |stderr| {
585 if extra_verbose {
586 state.stderr(format!("{}{}", prefix, stderr))?;
587 }
588 Ok(())
589 },
590 true,
591 )
592 .with_context(|| {
593 let mut build_error_context =
594 format!("failed to run custom build command for `{}`", pkg_descr);
595
596 #[allow(clippy::disallowed_methods)]
603 if let Ok(show_backtraces) = std::env::var("RUST_BACKTRACE") {
604 if !built_with_debuginfo && show_backtraces != "0" {
605 build_error_context.push_str(&format!(
606 "\n\
607 note: To improve backtraces for build dependencies, set the \
608 CARGO_PROFILE_{env_profile_name}_BUILD_OVERRIDE_DEBUG=true environment \
609 variable to enable debug information generation.",
610 ));
611 }
612 }
613
614 build_error_context
615 });
616
617 if let Err(error) = output {
619 insert_log_messages_in_build_outputs(
620 build_script_outputs,
621 id,
622 metadata_hash,
623 log_messages_in_case_of_panic,
624 );
625 return Err(error);
626 }
627 else if log_messages_in_case_of_panic
629 .iter()
630 .any(|(severity, _)| *severity == Severity::Error)
631 {
632 insert_log_messages_in_build_outputs(
633 build_script_outputs,
634 id,
635 metadata_hash,
636 log_messages_in_case_of_panic,
637 );
638 anyhow::bail!("build script logged errors");
639 }
640
641 let output = output.unwrap();
642
643 paths::write(&output_file, &output.stdout)?;
651 paths::set_file_time_no_err(output_file, timestamp);
654 paths::write(&err_file, &output.stderr)?;
655 paths::write(&root_output_file, paths::path2bytes(&script_out_dir)?)?;
656 let parsed_output = BuildOutput::parse(
657 &output.stdout,
658 library_name,
659 &pkg_descr,
660 &script_out_dir,
661 &script_out_dir,
662 nightly_features_allowed,
663 &targets,
664 &msrv,
665 )?;
666
667 if json_messages {
668 emit_build_output(state, &parsed_output, script_out_dir.as_path(), id)?;
669 }
670 build_script_outputs
671 .lock()
672 .unwrap()
673 .insert(id, metadata_hash, parsed_output);
674 Ok(())
675 });
676
677 let fresh = Work::new(move |state| {
681 let (id, library_name, pkg_descr, build_script_outputs, output_file, script_out_dir) = all;
682 let output = match prev_output {
683 Some(output) => output,
684 None => BuildOutput::parse_file(
685 &output_file,
686 library_name,
687 &pkg_descr,
688 &prev_script_out_dir,
689 &script_out_dir,
690 nightly_features_allowed,
691 &targets_fresh,
692 &msrv_fresh,
693 )?,
694 };
695
696 if json_messages {
697 emit_build_output(state, &output, script_out_dir.as_path(), id)?;
698 }
699
700 build_script_outputs
701 .lock()
702 .unwrap()
703 .insert(id, metadata_hash, output);
704 Ok(())
705 });
706
707 let mut job = if build_runner.bcx.build_config.build_plan {
708 Job::new_dirty(Work::noop(), DirtyReason::FreshBuild)
709 } else {
710 fingerprint::prepare_target(build_runner, unit, false)?
711 };
712 if job.freshness().is_dirty() {
713 job.before(dirty);
714 } else {
715 job.before(fresh);
716 }
717 Ok(job)
718}
719
720fn insert_log_messages_in_build_outputs(
723 build_script_outputs: Arc<Mutex<BuildScriptOutputs>>,
724 id: PackageId,
725 metadata_hash: UnitHash,
726 log_messages: Vec<LogMessage>,
727) {
728 let build_output_with_only_log_messages = BuildOutput {
729 log_messages,
730 ..BuildOutput::default()
731 };
732 build_script_outputs.lock().unwrap().insert(
733 id,
734 metadata_hash,
735 build_output_with_only_log_messages,
736 );
737}
738
739impl BuildOutput {
740 pub fn parse_file(
742 path: &Path,
743 library_name: Option<String>,
744 pkg_descr: &str,
745 script_out_dir_when_generated: &Path,
746 script_out_dir: &Path,
747 nightly_features_allowed: bool,
748 targets: &[Target],
749 msrv: &Option<RustVersion>,
750 ) -> CargoResult<BuildOutput> {
751 let contents = paths::read_bytes(path)?;
752 BuildOutput::parse(
753 &contents,
754 library_name,
755 pkg_descr,
756 script_out_dir_when_generated,
757 script_out_dir,
758 nightly_features_allowed,
759 targets,
760 msrv,
761 )
762 }
763
764 pub fn parse(
769 input: &[u8],
770 library_name: Option<String>,
772 pkg_descr: &str,
773 script_out_dir_when_generated: &Path,
774 script_out_dir: &Path,
775 nightly_features_allowed: bool,
776 targets: &[Target],
777 msrv: &Option<RustVersion>,
778 ) -> CargoResult<BuildOutput> {
779 let mut library_paths = Vec::new();
780 let mut library_links = Vec::new();
781 let mut linker_args = Vec::new();
782 let mut cfgs = Vec::new();
783 let mut check_cfgs = Vec::new();
784 let mut env = Vec::new();
785 let mut metadata = Vec::new();
786 let mut rerun_if_changed = Vec::new();
787 let mut rerun_if_env_changed = Vec::new();
788 let mut log_messages = Vec::new();
789 let whence = format!("build script of `{}`", pkg_descr);
790 const RESERVED_PREFIXES: &[&str] = &[
798 "rustc-flags=",
799 "rustc-link-lib=",
800 "rustc-link-search=",
801 "rustc-link-arg-cdylib=",
802 "rustc-cdylib-link-arg=",
803 "rustc-link-arg-bins=",
804 "rustc-link-arg-bin=",
805 "rustc-link-arg-tests=",
806 "rustc-link-arg-benches=",
807 "rustc-link-arg-examples=",
808 "rustc-link-arg=",
809 "rustc-cfg=",
810 "rustc-check-cfg=",
811 "rustc-env=",
812 "warning=",
813 "rerun-if-changed=",
814 "rerun-if-env-changed=",
815 ];
816 const DOCS_LINK_SUGGESTION: &str = "See https://doc.rust-lang.org/cargo/reference/build-scripts.html#outputs-of-the-build-script \
817 for more information about build script outputs.";
818
819 fn has_reserved_prefix(flag: &str) -> bool {
820 RESERVED_PREFIXES
821 .iter()
822 .any(|reserved_prefix| flag.starts_with(reserved_prefix))
823 }
824
825 fn check_minimum_supported_rust_version_for_new_syntax(
826 pkg_descr: &str,
827 msrv: &Option<RustVersion>,
828 flag: &str,
829 ) -> CargoResult<()> {
830 if let Some(msrv) = msrv {
831 let new_syntax_added_in = RustVersion::from_str("1.77.0")?;
832 if !new_syntax_added_in.is_compatible_with(msrv.as_partial()) {
833 let old_syntax_suggestion = if has_reserved_prefix(flag) {
834 format!(
835 "Switch to the old `cargo:{flag}` syntax (note the single colon).\n"
836 )
837 } else if flag.starts_with("metadata=") {
838 let old_format_flag = flag.strip_prefix("metadata=").unwrap();
839 format!(
840 "Switch to the old `cargo:{old_format_flag}` syntax instead of `cargo::{flag}` (note the single colon).\n"
841 )
842 } else {
843 String::new()
844 };
845
846 bail!(
847 "the `cargo::` syntax for build script output instructions was added in \
848 Rust 1.77.0, but the minimum supported Rust version of `{pkg_descr}` is {msrv}.\n\
849 {old_syntax_suggestion}\
850 {DOCS_LINK_SUGGESTION}"
851 );
852 }
853 }
854
855 Ok(())
856 }
857
858 fn parse_directive<'a>(
859 whence: &str,
860 line: &str,
861 data: &'a str,
862 old_syntax: bool,
863 ) -> CargoResult<(&'a str, &'a str)> {
864 let mut iter = data.splitn(2, "=");
865 let key = iter.next();
866 let value = iter.next();
867 match (key, value) {
868 (Some(a), Some(b)) => Ok((a, b.trim_end())),
869 _ => bail!(
870 "invalid output in {whence}: `{line}`\n\
871 Expected a line with `{syntax}KEY=VALUE` with an `=` character, \
872 but none was found.\n\
873 {DOCS_LINK_SUGGESTION}",
874 syntax = if old_syntax { "cargo:" } else { "cargo::" },
875 ),
876 }
877 }
878
879 fn parse_metadata<'a>(
880 whence: &str,
881 line: &str,
882 data: &'a str,
883 old_syntax: bool,
884 ) -> CargoResult<(&'a str, &'a str)> {
885 let mut iter = data.splitn(2, "=");
886 let key = iter.next();
887 let value = iter.next();
888 match (key, value) {
889 (Some(a), Some(b)) => Ok((a, b.trim_end())),
890 _ => bail!(
891 "invalid output in {whence}: `{line}`\n\
892 Expected a line with `{syntax}KEY=VALUE` with an `=` character, \
893 but none was found.\n\
894 {DOCS_LINK_SUGGESTION}",
895 syntax = if old_syntax {
896 "cargo:"
897 } else {
898 "cargo::metadata="
899 },
900 ),
901 }
902 }
903
904 for line in input.split(|b| *b == b'\n') {
905 let line = match str::from_utf8(line) {
906 Ok(line) => line.trim(),
907 Err(..) => continue,
908 };
909 let mut old_syntax = false;
910 let (key, value) = if let Some(data) = line.strip_prefix("cargo::") {
911 check_minimum_supported_rust_version_for_new_syntax(pkg_descr, msrv, data)?;
912 parse_directive(whence.as_str(), line, data, old_syntax)?
914 } else if let Some(data) = line.strip_prefix("cargo:") {
915 old_syntax = true;
916 if has_reserved_prefix(data) {
918 parse_directive(whence.as_str(), line, data, old_syntax)?
919 } else {
920 ("metadata", data)
922 }
923 } else {
924 continue;
926 };
927 let value = value.replace(
929 script_out_dir_when_generated.to_str().unwrap(),
930 script_out_dir.to_str().unwrap(),
931 );
932
933 let syntax_prefix = if old_syntax { "cargo:" } else { "cargo::" };
934 macro_rules! check_and_add_target {
935 ($target_kind: expr, $is_target_kind: expr, $link_type: expr) => {
936 if !targets.iter().any(|target| $is_target_kind(target)) {
937 bail!(
938 "invalid instruction `{}{}` from {}\n\
939 The package {} does not have a {} target.",
940 syntax_prefix,
941 key,
942 whence,
943 pkg_descr,
944 $target_kind
945 );
946 }
947 linker_args.push(($link_type, value));
948 };
949 }
950
951 match key {
953 "rustc-flags" => {
954 let (paths, links) = BuildOutput::parse_rustc_flags(&value, &whence)?;
955 library_links.extend(links.into_iter());
956 library_paths.extend(
957 paths
958 .into_iter()
959 .map(|p| LibraryPath::new(p, script_out_dir)),
960 );
961 }
962 "rustc-link-lib" => library_links.push(value.to_string()),
963 "rustc-link-search" => {
964 library_paths.push(LibraryPath::new(PathBuf::from(value), script_out_dir))
965 }
966 "rustc-link-arg-cdylib" | "rustc-cdylib-link-arg" => {
967 if !targets.iter().any(|target| target.is_cdylib()) {
968 log_messages.push((
969 Severity::Warning,
970 format!(
971 "{}{} was specified in the build script of {}, \
972 but that package does not contain a cdylib target\n\
973 \n\
974 Allowing this was an unintended change in the 1.50 \
975 release, and may become an error in the future. \
976 For more information, see \
977 <https://github.com/rust-lang/cargo/issues/9562>.",
978 syntax_prefix, key, pkg_descr
979 ),
980 ));
981 }
982 linker_args.push((LinkArgTarget::Cdylib, value))
983 }
984 "rustc-link-arg-bins" => {
985 check_and_add_target!("bin", Target::is_bin, LinkArgTarget::Bin);
986 }
987 "rustc-link-arg-bin" => {
988 let (bin_name, arg) = value.split_once('=').ok_or_else(|| {
989 anyhow::format_err!(
990 "invalid instruction `{}{}={}` from {}\n\
991 The instruction should have the form {}{}=BIN=ARG",
992 syntax_prefix,
993 key,
994 value,
995 whence,
996 syntax_prefix,
997 key
998 )
999 })?;
1000 if !targets
1001 .iter()
1002 .any(|target| target.is_bin() && target.name() == bin_name)
1003 {
1004 bail!(
1005 "invalid instruction `{}{}` from {}\n\
1006 The package {} does not have a bin target with the name `{}`.",
1007 syntax_prefix,
1008 key,
1009 whence,
1010 pkg_descr,
1011 bin_name
1012 );
1013 }
1014 linker_args.push((
1015 LinkArgTarget::SingleBin(bin_name.to_owned()),
1016 arg.to_string(),
1017 ));
1018 }
1019 "rustc-link-arg-tests" => {
1020 check_and_add_target!("test", Target::is_test, LinkArgTarget::Test);
1021 }
1022 "rustc-link-arg-benches" => {
1023 check_and_add_target!("benchmark", Target::is_bench, LinkArgTarget::Bench);
1024 }
1025 "rustc-link-arg-examples" => {
1026 check_and_add_target!("example", Target::is_example, LinkArgTarget::Example);
1027 }
1028 "rustc-link-arg" => {
1029 linker_args.push((LinkArgTarget::All, value));
1030 }
1031 "rustc-cfg" => cfgs.push(value.to_string()),
1032 "rustc-check-cfg" => check_cfgs.push(value.to_string()),
1033 "rustc-env" => {
1034 let (key, val) = BuildOutput::parse_rustc_env(&value, &whence)?;
1035 if key == "RUSTC_BOOTSTRAP" {
1038 let rustc_bootstrap_allows = |name: Option<&str>| {
1048 let name = match name {
1049 None => return false,
1053 Some(n) => n,
1054 };
1055 #[allow(clippy::disallowed_methods)]
1059 std::env::var("RUSTC_BOOTSTRAP")
1060 .map_or(false, |var| var.split(',').any(|s| s == name))
1061 };
1062 if nightly_features_allowed
1063 || rustc_bootstrap_allows(library_name.as_deref())
1064 {
1065 log_messages.push((Severity::Warning, format!("Cannot set `RUSTC_BOOTSTRAP={}` from {}.\n\
1066 note: Crates cannot set `RUSTC_BOOTSTRAP` themselves, as doing so would subvert the stability guarantees of Rust for your project.",
1067 val, whence
1068 )));
1069 } else {
1070 bail!(
1073 "Cannot set `RUSTC_BOOTSTRAP={}` from {}.\n\
1074 note: Crates cannot set `RUSTC_BOOTSTRAP` themselves, as doing so would subvert the stability guarantees of Rust for your project.\n\
1075 help: If you're sure you want to do this in your project, set the environment variable `RUSTC_BOOTSTRAP={}` before running cargo instead.",
1076 val,
1077 whence,
1078 library_name.as_deref().unwrap_or("1"),
1079 );
1080 }
1081 } else {
1082 env.push((key, val));
1083 }
1084 }
1085 "error" => log_messages.push((Severity::Error, value.to_string())),
1086 "warning" => log_messages.push((Severity::Warning, value.to_string())),
1087 "rerun-if-changed" => rerun_if_changed.push(PathBuf::from(value)),
1088 "rerun-if-env-changed" => rerun_if_env_changed.push(value.to_string()),
1089 "metadata" => {
1090 let (key, value) = parse_metadata(whence.as_str(), line, &value, old_syntax)?;
1091 metadata.push((key.to_owned(), value.to_owned()));
1092 }
1093 _ => bail!(
1094 "invalid output in {whence}: `{line}`\n\
1095 Unknown key: `{key}`.\n\
1096 {DOCS_LINK_SUGGESTION}",
1097 ),
1098 }
1099 }
1100
1101 Ok(BuildOutput {
1102 library_paths,
1103 library_links,
1104 linker_args,
1105 cfgs,
1106 check_cfgs,
1107 env,
1108 metadata,
1109 rerun_if_changed,
1110 rerun_if_env_changed,
1111 log_messages,
1112 })
1113 }
1114
1115 pub fn parse_rustc_flags(
1119 value: &str,
1120 whence: &str,
1121 ) -> CargoResult<(Vec<PathBuf>, Vec<String>)> {
1122 let value = value.trim();
1123 let mut flags_iter = value
1124 .split(|c: char| c.is_whitespace())
1125 .filter(|w| w.chars().any(|c| !c.is_whitespace()));
1126 let (mut library_paths, mut library_links) = (Vec::new(), Vec::new());
1127
1128 while let Some(flag) = flags_iter.next() {
1129 if flag.starts_with("-l") || flag.starts_with("-L") {
1130 let (flag, mut value) = flag.split_at(2);
1134 if value.is_empty() {
1135 value = match flags_iter.next() {
1136 Some(v) => v,
1137 None => bail! {
1138 "Flag in rustc-flags has no value in {}: {}",
1139 whence,
1140 value
1141 },
1142 }
1143 }
1144
1145 match flag {
1146 "-l" => library_links.push(value.to_string()),
1147 "-L" => library_paths.push(PathBuf::from(value)),
1148
1149 _ => unreachable!(),
1151 };
1152 } else {
1153 bail!(
1154 "Only `-l` and `-L` flags are allowed in {}: `{}`",
1155 whence,
1156 value
1157 )
1158 }
1159 }
1160 Ok((library_paths, library_links))
1161 }
1162
1163 pub fn parse_rustc_env(value: &str, whence: &str) -> CargoResult<(String, String)> {
1167 match value.split_once('=') {
1168 Some((n, v)) => Ok((n.to_owned(), v.to_owned())),
1169 _ => bail!("Variable rustc-env has no value in {whence}: {value}"),
1170 }
1171 }
1172}
1173
1174fn prepare_metabuild(
1178 build_runner: &BuildRunner<'_, '_>,
1179 unit: &Unit,
1180 deps: &[String],
1181) -> CargoResult<()> {
1182 let mut output = Vec::new();
1183 let available_deps = build_runner.unit_deps(unit);
1184 let meta_deps: Vec<_> = deps
1186 .iter()
1187 .filter_map(|name| {
1188 available_deps
1189 .iter()
1190 .find(|d| d.unit.pkg.name().as_str() == name.as_str())
1191 .map(|d| d.unit.target.crate_name())
1192 })
1193 .collect();
1194 output.push("fn main() {\n".to_string());
1195 for dep in &meta_deps {
1196 output.push(format!(" {}::metabuild();\n", dep));
1197 }
1198 output.push("}\n".to_string());
1199 let output = output.join("");
1200 let path = unit
1201 .pkg
1202 .manifest()
1203 .metabuild_path(build_runner.bcx.ws.build_dir());
1204 paths::create_dir_all(path.parent().unwrap())?;
1205 paths::write_if_changed(path, &output)?;
1206 Ok(())
1207}
1208
1209impl BuildDeps {
1210 pub fn new(output_file: &Path, output: Option<&BuildOutput>) -> BuildDeps {
1213 BuildDeps {
1214 build_script_output: output_file.to_path_buf(),
1215 rerun_if_changed: output
1216 .map(|p| &p.rerun_if_changed)
1217 .cloned()
1218 .unwrap_or_default(),
1219 rerun_if_env_changed: output
1220 .map(|p| &p.rerun_if_env_changed)
1221 .cloned()
1222 .unwrap_or_default(),
1223 }
1224 }
1225}
1226
1227pub fn build_map(build_runner: &mut BuildRunner<'_, '_>) -> CargoResult<()> {
1249 let mut ret = HashMap::new();
1250 for unit in &build_runner.bcx.roots {
1251 build(&mut ret, build_runner, unit)?;
1252 }
1253 build_runner
1254 .build_scripts
1255 .extend(ret.into_iter().map(|(k, v)| (k, Arc::new(v))));
1256 return Ok(());
1257
1258 fn build<'a>(
1261 out: &'a mut HashMap<Unit, BuildScripts>,
1262 build_runner: &mut BuildRunner<'_, '_>,
1263 unit: &Unit,
1264 ) -> CargoResult<&'a BuildScripts> {
1265 if out.contains_key(unit) {
1268 return Ok(&out[unit]);
1269 }
1270
1271 if unit.mode.is_run_custom_build() {
1273 if let Some(links) = unit.pkg.manifest().links() {
1274 if let Some(output) = unit.links_overrides.get(links) {
1275 let metadata = build_runner.get_run_build_script_metadata(unit);
1276 build_runner.build_script_outputs.lock().unwrap().insert(
1277 unit.pkg.package_id(),
1278 metadata,
1279 output.clone(),
1280 );
1281 }
1282 }
1283 }
1284
1285 let mut ret = BuildScripts::default();
1286
1287 if !unit.target.is_custom_build() && unit.pkg.has_custom_build() {
1289 let script_metas = build_runner
1290 .find_build_script_metadatas(unit)
1291 .expect("has_custom_build should have RunCustomBuild");
1292 for script_meta in script_metas {
1293 add_to_link(&mut ret, unit.pkg.package_id(), script_meta);
1294 }
1295 }
1296
1297 if unit.mode.is_run_custom_build() {
1298 parse_previous_explicit_deps(build_runner, unit);
1299 }
1300
1301 let mut dependencies: Vec<Unit> = build_runner
1306 .unit_deps(unit)
1307 .iter()
1308 .map(|d| d.unit.clone())
1309 .collect();
1310 dependencies.sort_by_key(|u| u.pkg.package_id());
1311
1312 for dep_unit in dependencies.iter() {
1313 let dep_scripts = build(out, build_runner, dep_unit)?;
1314
1315 if dep_unit.target.for_host() {
1316 ret.plugins.extend(dep_scripts.to_link.iter().cloned());
1317 } else if dep_unit.target.is_linkable() {
1318 for &(pkg, metadata) in dep_scripts.to_link.iter() {
1319 add_to_link(&mut ret, pkg, metadata);
1320 }
1321 }
1322 }
1323
1324 match out.entry(unit.clone()) {
1325 Entry::Vacant(entry) => Ok(entry.insert(ret)),
1326 Entry::Occupied(_) => panic!("cyclic dependencies in `build_map`"),
1327 }
1328 }
1329
1330 fn add_to_link(scripts: &mut BuildScripts, pkg: PackageId, metadata: UnitHash) {
1333 if scripts.seen_to_link.insert((pkg, metadata)) {
1334 scripts.to_link.push((pkg, metadata));
1335 }
1336 }
1337
1338 fn parse_previous_explicit_deps(build_runner: &mut BuildRunner<'_, '_>, unit: &Unit) {
1340 let script_run_dir = build_runner.files().build_script_run_dir(unit);
1341 let output_file = script_run_dir.join("output");
1342 let (prev_output, _) = prev_build_output(build_runner, unit);
1343 let deps = BuildDeps::new(&output_file, prev_output.as_ref());
1344 build_runner.build_explicit_deps.insert(unit.clone(), deps);
1345 }
1346}
1347
1348fn prev_build_output(
1354 build_runner: &mut BuildRunner<'_, '_>,
1355 unit: &Unit,
1356) -> (Option<BuildOutput>, PathBuf) {
1357 let script_out_dir = build_runner.files().build_script_out_dir(unit);
1358 let script_run_dir = build_runner.files().build_script_run_dir(unit);
1359 let root_output_file = script_run_dir.join("root-output");
1360 let output_file = script_run_dir.join("output");
1361
1362 let prev_script_out_dir = paths::read_bytes(&root_output_file)
1363 .and_then(|bytes| paths::bytes2path(&bytes))
1364 .unwrap_or_else(|_| script_out_dir.clone());
1365
1366 (
1367 BuildOutput::parse_file(
1368 &output_file,
1369 unit.pkg.library().map(|t| t.crate_name()),
1370 &unit.pkg.to_string(),
1371 &prev_script_out_dir,
1372 &script_out_dir,
1373 build_runner.bcx.gctx.nightly_features_allowed,
1374 unit.pkg.targets(),
1375 &unit.pkg.rust_version().cloned(),
1376 )
1377 .ok(),
1378 prev_script_out_dir,
1379 )
1380}
1381
1382impl BuildScriptOutputs {
1383 fn insert(&mut self, pkg_id: PackageId, metadata: UnitHash, parsed_output: BuildOutput) {
1385 match self.outputs.entry(metadata) {
1386 Entry::Vacant(entry) => {
1387 entry.insert(parsed_output);
1388 }
1389 Entry::Occupied(entry) => panic!(
1390 "build script output collision for {}/{}\n\
1391 old={:?}\nnew={:?}",
1392 pkg_id,
1393 metadata,
1394 entry.get(),
1395 parsed_output
1396 ),
1397 }
1398 }
1399
1400 fn contains_key(&self, metadata: UnitHash) -> bool {
1402 self.outputs.contains_key(&metadata)
1403 }
1404
1405 pub fn get(&self, meta: UnitHash) -> Option<&BuildOutput> {
1407 self.outputs.get(&meta)
1408 }
1409
1410 pub fn iter(&self) -> impl Iterator<Item = (&UnitHash, &BuildOutput)> {
1412 self.outputs.iter()
1413 }
1414}