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