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;
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
341 let script_out_dir = if bcx.gctx.cli_unstable().build_dir_new_layout {
342 build_runner.files().out_dir_new_layout(unit)
343 } else {
344 build_runner.files().build_script_out_dir(unit)
345 };
346
347 if let Some(deps) = unit.pkg.manifest().metabuild() {
348 prepare_metabuild(build_runner, build_script_unit, deps)?;
349 }
350
351 let to_exec = script_dir.join(unit.target.name());
353
354 let to_exec = to_exec.into_os_string();
362 let mut cmd = build_runner.compilation.host_process(to_exec, &unit.pkg)?;
363 let debug = unit.profile.debuginfo.is_turned_on();
364 cmd.env("OUT_DIR", &script_out_dir)
365 .env("CARGO_MANIFEST_DIR", unit.pkg.root())
366 .env("CARGO_MANIFEST_PATH", unit.pkg.manifest_path())
367 .env("NUM_JOBS", &bcx.jobs().to_string())
368 .env("TARGET", bcx.target_data.short_name(&unit.kind))
369 .env("DEBUG", debug.to_string())
370 .env("OPT_LEVEL", &unit.profile.opt_level)
371 .env(
372 "PROFILE",
373 match unit.profile.root {
374 ProfileRoot::Release => "release",
375 ProfileRoot::Debug => "debug",
376 },
377 )
378 .env("HOST", &bcx.host_triple())
379 .env("RUSTC", &bcx.rustc().path)
380 .env("RUSTDOC", &*bcx.gctx.rustdoc()?)
381 .inherit_jobserver(&build_runner.jobserver);
382
383 for (var, value) in artifact::get_env(build_runner, unit, dependencies)? {
385 cmd.env(&var, value);
386 }
387
388 if let Some(linker) = &build_runner.compilation.target_linker(unit.kind) {
389 cmd.env("RUSTC_LINKER", linker);
390 }
391
392 if let Some(links) = unit.pkg.manifest().links() {
393 cmd.env("CARGO_MANIFEST_LINKS", links);
394 }
395
396 if let Some(trim_paths) = unit.profile.trim_paths.as_ref() {
397 cmd.env("CARGO_TRIM_PATHS", trim_paths.to_string());
398 }
399
400 for feat in &unit.features {
403 cmd.env(&format!("CARGO_FEATURE_{}", super::envify(feat)), "1");
404 }
405
406 let mut cfg_map = HashMap::new();
407 cfg_map.insert(
408 "feature",
409 unit.features.iter().map(|s| s.as_str()).collect::<Vec<_>>(),
410 );
411 if unit.profile.debug_assertions {
415 cfg_map.insert("debug_assertions", Vec::new());
416 }
417 for cfg in bcx.target_data.cfg(unit.kind) {
418 match *cfg {
419 Cfg::Name(ref n) => {
420 if n.as_str() == "debug_assertions" {
422 continue;
423 }
424 cfg_map.insert(n.as_str(), Vec::new());
425 }
426 Cfg::KeyPair(ref k, ref v) => {
427 let values = cfg_map.entry(k.as_str()).or_default();
428 values.push(v.as_str());
429 }
430 }
431 }
432 for (k, v) in cfg_map {
433 let k = format!("CARGO_CFG_{}", super::envify(k));
436 cmd.env(&k, v.join(","));
437 }
438
439 if let Some(wrapper) = bcx.rustc().wrapper.as_ref() {
441 cmd.env("RUSTC_WRAPPER", wrapper);
442 } else {
443 cmd.env_remove("RUSTC_WRAPPER");
444 }
445 cmd.env_remove("RUSTC_WORKSPACE_WRAPPER");
446 if build_runner.bcx.ws.is_member(&unit.pkg) {
447 if let Some(wrapper) = bcx.rustc().workspace_wrapper.as_ref() {
448 cmd.env("RUSTC_WORKSPACE_WRAPPER", wrapper);
449 }
450 }
451 cmd.env("CARGO_ENCODED_RUSTFLAGS", unit.rustflags.join("\x1f"));
452 cmd.env_remove("RUSTFLAGS");
453
454 if build_runner.bcx.ws.gctx().extra_verbose() {
455 cmd.display_env_vars();
456 }
457
458 let any_build_script_metadata = bcx.gctx.cli_unstable().any_build_script_metadata;
459
460 let lib_deps = dependencies
466 .iter()
467 .filter_map(|dep| {
468 if dep.unit.mode.is_run_custom_build() {
469 let dep_metadata = build_runner.get_run_build_script_metadata(&dep.unit);
470
471 let dep_name = dep.dep_name.unwrap_or(dep.unit.pkg.name());
472
473 Some((
474 dep_name,
475 dep.unit
476 .pkg
477 .manifest()
478 .links()
479 .map(|links| links.to_string()),
480 dep.unit.pkg.package_id(),
481 dep_metadata,
482 ))
483 } else {
484 None
485 }
486 })
487 .collect::<Vec<_>>();
488 let library_name = unit.pkg.library().map(|t| t.crate_name());
489 let pkg_descr = unit.pkg.to_string();
490 let build_script_outputs = Arc::clone(&build_runner.build_script_outputs);
491 let id = unit.pkg.package_id();
492 let run_files = BuildScriptRunFiles::for_unit(build_runner, unit);
493 let host_target_root = build_runner.files().host_dest().map(|v| v.to_path_buf());
494 let all = (
495 id,
496 library_name.clone(),
497 pkg_descr.clone(),
498 Arc::clone(&build_script_outputs),
499 run_files.stdout.clone(),
500 script_out_dir.clone(),
501 );
502 let build_scripts = build_runner.build_scripts.get(unit).cloned();
503 let json_messages = bcx.build_config.emit_json();
504 let extra_verbose = bcx.gctx.extra_verbose();
505 let (prev_output, prev_script_out_dir) = prev_build_output(build_runner, unit);
506 let metadata_hash = build_runner.get_run_build_script_metadata(unit);
507
508 paths::create_dir_all(&script_dir)?;
509 paths::create_dir_all(&script_out_dir)?;
510 paths::create_dir_all(&run_files.root)?;
511
512 let nightly_features_allowed = build_runner.bcx.gctx.nightly_features_allowed;
513 let targets: Vec<Target> = unit.pkg.targets().to_vec();
514 let msrv = unit.pkg.rust_version().cloned();
515 let targets_fresh = targets.clone();
517 let msrv_fresh = msrv.clone();
518
519 let env_profile_name = unit.profile.name.to_uppercase();
520 let built_with_debuginfo = build_runner
521 .bcx
522 .unit_graph
523 .get(unit)
524 .and_then(|deps| deps.iter().find(|dep| dep.unit.target == unit.target))
525 .map(|dep| dep.unit.profile.debuginfo.is_turned_on())
526 .unwrap_or(false);
527
528 let dirty = Work::new(move |state| {
534 paths::create_dir_all(&script_out_dir)
539 .context("failed to create script output directory for build command")?;
540
541 {
546 let build_script_outputs = build_script_outputs.lock().unwrap();
547 for (name, links, dep_id, dep_metadata) in lib_deps {
548 let script_output = build_script_outputs.get(dep_metadata).ok_or_else(|| {
549 internal(format!(
550 "failed to locate build state for env vars: {}/{}",
551 dep_id, dep_metadata
552 ))
553 })?;
554 let data = &script_output.metadata;
555 for (key, value) in data.iter() {
556 if let Some(ref links) = links {
557 cmd.env(
558 &format!("DEP_{}_{}", super::envify(&links), super::envify(key)),
559 value,
560 );
561 }
562 if any_build_script_metadata {
563 cmd.env(
564 &format!("CARGO_DEP_{}_{}", super::envify(&name), super::envify(key)),
565 value,
566 );
567 }
568 }
569 }
570 if let Some(build_scripts) = build_scripts
571 && let Some(ref host_target_root) = host_target_root
572 {
573 super::add_plugin_deps(
574 &mut cmd,
575 &build_script_outputs,
576 &build_scripts,
577 host_target_root,
578 )?;
579 }
580 }
581
582 state.running(&cmd);
584 let timestamp = paths::set_invocation_time(&run_files.root)?;
585 let prefix = format!("[{} {}] ", id.name(), id.version());
586 let mut log_messages_in_case_of_panic = Vec::new();
587 let span = tracing::debug_span!("build_script", process = cmd.to_string());
588 let output = span.in_scope(|| {
589 cmd.exec_with_streaming(
590 &mut |stdout| {
591 if let Some(error) = stdout.strip_prefix(CARGO_ERROR_SYNTAX) {
592 log_messages_in_case_of_panic.push((Severity::Error, error.to_owned()));
593 }
594 if let Some(warning) = stdout
595 .strip_prefix(OLD_CARGO_WARNING_SYNTAX)
596 .or(stdout.strip_prefix(NEW_CARGO_WARNING_SYNTAX))
597 {
598 log_messages_in_case_of_panic.push((Severity::Warning, warning.to_owned()));
599 }
600 if extra_verbose {
601 state.stdout(format!("{}{}", prefix, stdout))?;
602 }
603 Ok(())
604 },
605 &mut |stderr| {
606 if extra_verbose {
607 state.stderr(format!("{}{}", prefix, stderr))?;
608 }
609 Ok(())
610 },
611 true,
612 )
613 .with_context(|| {
614 let mut build_error_context =
615 format!("failed to run custom build command for `{}`", pkg_descr);
616
617 #[expect(clippy::disallowed_methods, reason = "consistency with rustc")]
621 if let Ok(show_backtraces) = std::env::var("RUST_BACKTRACE") {
622 if !built_with_debuginfo && show_backtraces != "0" {
623 build_error_context.push_str(&format!(
624 "\n\
625 note: To improve backtraces for build dependencies, set the \
626 CARGO_PROFILE_{env_profile_name}_BUILD_OVERRIDE_DEBUG=true environment \
627 variable to enable debug information generation.",
628 ));
629 }
630 }
631
632 build_error_context
633 })
634 });
635
636 if let Err(error) = output {
638 insert_log_messages_in_build_outputs(
639 build_script_outputs,
640 id,
641 metadata_hash,
642 log_messages_in_case_of_panic,
643 );
644 return Err(error);
645 }
646 else if log_messages_in_case_of_panic
648 .iter()
649 .any(|(severity, _)| *severity == Severity::Error)
650 {
651 insert_log_messages_in_build_outputs(
652 build_script_outputs,
653 id,
654 metadata_hash,
655 log_messages_in_case_of_panic,
656 );
657 anyhow::bail!("build script logged errors");
658 }
659
660 let output = output.unwrap();
661
662 paths::write(&run_files.stdout, &output.stdout)?;
670 paths::set_file_time_no_err(run_files.stdout, timestamp);
673 paths::write(&run_files.stderr, &output.stderr)?;
674 paths::write(&run_files.root_output, paths::path2bytes(&script_out_dir)?)?;
675 let parsed_output = BuildOutput::parse(
676 &output.stdout,
677 library_name,
678 &pkg_descr,
679 &script_out_dir,
680 &script_out_dir,
681 nightly_features_allowed,
682 &targets,
683 &msrv,
684 )?;
685
686 if json_messages {
687 emit_build_output(state, &parsed_output, script_out_dir.as_path(), id)?;
688 }
689 build_script_outputs
690 .lock()
691 .unwrap()
692 .insert(id, metadata_hash, parsed_output);
693 Ok(())
694 });
695
696 let fresh = Work::new(move |state| {
700 let (id, library_name, pkg_descr, build_script_outputs, output_file, script_out_dir) = all;
701 let output = match prev_output {
702 Some(output) => output,
703 None => BuildOutput::parse_file(
704 &output_file,
705 library_name,
706 &pkg_descr,
707 &prev_script_out_dir,
708 &script_out_dir,
709 nightly_features_allowed,
710 &targets_fresh,
711 &msrv_fresh,
712 )?,
713 };
714
715 if json_messages {
716 emit_build_output(state, &output, script_out_dir.as_path(), id)?;
717 }
718
719 build_script_outputs
720 .lock()
721 .unwrap()
722 .insert(id, metadata_hash, output);
723 Ok(())
724 });
725
726 let mut job = fingerprint::prepare_target(build_runner, unit, false)?;
727 if job.freshness().is_dirty() {
728 job.before(dirty);
729 } else {
730 job.before(fresh);
731 }
732 Ok(job)
733}
734
735fn insert_log_messages_in_build_outputs(
738 build_script_outputs: Arc<Mutex<BuildScriptOutputs>>,
739 id: PackageId,
740 metadata_hash: UnitHash,
741 log_messages: Vec<LogMessage>,
742) {
743 let build_output_with_only_log_messages = BuildOutput {
744 log_messages,
745 ..BuildOutput::default()
746 };
747 build_script_outputs.lock().unwrap().insert(
748 id,
749 metadata_hash,
750 build_output_with_only_log_messages,
751 );
752}
753
754impl BuildOutput {
755 pub fn parse_file(
757 path: &Path,
758 library_name: Option<String>,
759 pkg_descr: &str,
760 script_out_dir_when_generated: &Path,
761 script_out_dir: &Path,
762 nightly_features_allowed: bool,
763 targets: &[Target],
764 msrv: &Option<RustVersion>,
765 ) -> CargoResult<BuildOutput> {
766 let contents = paths::read_bytes(path)?;
767 BuildOutput::parse(
768 &contents,
769 library_name,
770 pkg_descr,
771 script_out_dir_when_generated,
772 script_out_dir,
773 nightly_features_allowed,
774 targets,
775 msrv,
776 )
777 }
778
779 pub fn parse(
784 input: &[u8],
785 library_name: Option<String>,
787 pkg_descr: &str,
788 script_out_dir_when_generated: &Path,
789 script_out_dir: &Path,
790 nightly_features_allowed: bool,
791 targets: &[Target],
792 msrv: &Option<RustVersion>,
793 ) -> CargoResult<BuildOutput> {
794 let mut library_paths = Vec::new();
795 let mut library_links = Vec::new();
796 let mut linker_args = Vec::new();
797 let mut cfgs = Vec::new();
798 let mut check_cfgs = Vec::new();
799 let mut env = Vec::new();
800 let mut metadata = Vec::new();
801 let mut rerun_if_changed = Vec::new();
802 let mut rerun_if_env_changed = Vec::new();
803 let mut log_messages = Vec::new();
804 let whence = format!("build script of `{}`", pkg_descr);
805 const RESERVED_PREFIXES: &[&str] = &[
813 "rustc-flags=",
814 "rustc-link-lib=",
815 "rustc-link-search=",
816 "rustc-link-arg-cdylib=",
817 "rustc-cdylib-link-arg=",
818 "rustc-link-arg-bins=",
819 "rustc-link-arg-bin=",
820 "rustc-link-arg-tests=",
821 "rustc-link-arg-benches=",
822 "rustc-link-arg-examples=",
823 "rustc-link-arg=",
824 "rustc-cfg=",
825 "rustc-check-cfg=",
826 "rustc-env=",
827 "warning=",
828 "rerun-if-changed=",
829 "rerun-if-env-changed=",
830 ];
831 const DOCS_LINK_SUGGESTION: &str = "See https://doc.rust-lang.org/cargo/reference/build-scripts.html#outputs-of-the-build-script \
832 for more information about build script outputs.";
833
834 fn has_reserved_prefix(flag: &str) -> bool {
835 RESERVED_PREFIXES
836 .iter()
837 .any(|reserved_prefix| flag.starts_with(reserved_prefix))
838 }
839
840 fn check_minimum_supported_rust_version_for_new_syntax(
841 pkg_descr: &str,
842 msrv: &Option<RustVersion>,
843 flag: &str,
844 ) -> CargoResult<()> {
845 if let Some(msrv) = msrv {
846 let new_syntax_added_in = RustVersion::new(1, 77, 0);
847 if !new_syntax_added_in.is_compatible_with(&msrv.to_partial()) {
848 let old_syntax_suggestion = if has_reserved_prefix(flag) {
849 format!(
850 "Switch to the old `cargo:{flag}` syntax (note the single colon).\n"
851 )
852 } else if flag.starts_with("metadata=") {
853 let old_format_flag = flag.strip_prefix("metadata=").unwrap();
854 format!(
855 "Switch to the old `cargo:{old_format_flag}` syntax instead of `cargo::{flag}` (note the single colon).\n"
856 )
857 } else {
858 String::new()
859 };
860
861 bail!(
862 "the `cargo::` syntax for build script output instructions was added in \
863 Rust 1.77.0, but the minimum supported Rust version of `{pkg_descr}` is {msrv}.\n\
864 {old_syntax_suggestion}\
865 {DOCS_LINK_SUGGESTION}"
866 );
867 }
868 }
869
870 Ok(())
871 }
872
873 fn parse_directive<'a>(
874 whence: &str,
875 line: &str,
876 data: &'a str,
877 old_syntax: bool,
878 ) -> CargoResult<(&'a str, &'a str)> {
879 let mut iter = data.splitn(2, "=");
880 let key = iter.next();
881 let value = iter.next();
882 match (key, value) {
883 (Some(a), Some(b)) => Ok((a, b.trim_end())),
884 _ => bail!(
885 "invalid output in {whence}: `{line}`\n\
886 Expected a line with `{syntax}KEY=VALUE` with an `=` character, \
887 but none was found.\n\
888 {DOCS_LINK_SUGGESTION}",
889 syntax = if old_syntax { "cargo:" } else { "cargo::" },
890 ),
891 }
892 }
893
894 fn parse_metadata<'a>(
895 whence: &str,
896 line: &str,
897 data: &'a str,
898 old_syntax: bool,
899 ) -> CargoResult<(&'a str, &'a str)> {
900 let mut iter = data.splitn(2, "=");
901 let key = iter.next();
902 let value = iter.next();
903 match (key, value) {
904 (Some(a), Some(b)) => Ok((a, b.trim_end())),
905 _ => bail!(
906 "invalid output in {whence}: `{line}`\n\
907 Expected a line with `{syntax}KEY=VALUE` with an `=` character, \
908 but none was found.\n\
909 {DOCS_LINK_SUGGESTION}",
910 syntax = if old_syntax {
911 "cargo:"
912 } else {
913 "cargo::metadata="
914 },
915 ),
916 }
917 }
918
919 for line in input.split(|b| *b == b'\n') {
920 let line = match str::from_utf8(line) {
921 Ok(line) => line.trim(),
922 Err(..) => continue,
923 };
924 let mut old_syntax = false;
925 let (key, value) = if let Some(data) = line.strip_prefix("cargo::") {
926 check_minimum_supported_rust_version_for_new_syntax(pkg_descr, msrv, data)?;
927 parse_directive(whence.as_str(), line, data, old_syntax)?
929 } else if let Some(data) = line.strip_prefix("cargo:") {
930 old_syntax = true;
931 if has_reserved_prefix(data) {
933 parse_directive(whence.as_str(), line, data, old_syntax)?
934 } else {
935 ("metadata", data)
937 }
938 } else {
939 continue;
941 };
942 let value = value.replace(
944 script_out_dir_when_generated.to_str().unwrap(),
945 script_out_dir.to_str().unwrap(),
946 );
947
948 let syntax_prefix = if old_syntax { "cargo:" } else { "cargo::" };
949 macro_rules! check_and_add_target {
950 ($target_kind: expr, $is_target_kind: expr, $link_type: expr) => {
951 if !targets.iter().any(|target| $is_target_kind(target)) {
952 bail!(
953 "invalid instruction `{}{}` from {}\n\
954 The package {} does not have a {} target.",
955 syntax_prefix,
956 key,
957 whence,
958 pkg_descr,
959 $target_kind
960 );
961 }
962 linker_args.push(($link_type, value));
963 };
964 }
965
966 match key {
968 "rustc-flags" => {
969 let (paths, links) = BuildOutput::parse_rustc_flags(&value, &whence)?;
970 library_links.extend(links.into_iter());
971 library_paths.extend(
972 paths
973 .into_iter()
974 .map(|p| LibraryPath::new(p, script_out_dir)),
975 );
976 }
977 "rustc-link-lib" => library_links.push(value.to_string()),
978 "rustc-link-search" => {
979 library_paths.push(LibraryPath::new(PathBuf::from(value), script_out_dir))
980 }
981 "rustc-link-arg-cdylib" | "rustc-cdylib-link-arg" => {
982 if !targets.iter().any(|target| target.is_cdylib()) {
983 log_messages.push((
984 Severity::Warning,
985 format!(
986 "{}{} was specified in the build script of {}, \
987 but that package does not contain a cdylib target\n\
988 \n\
989 Allowing this was an unintended change in the 1.50 \
990 release, and may become an error in the future. \
991 For more information, see \
992 <https://github.com/rust-lang/cargo/issues/9562>.",
993 syntax_prefix, key, pkg_descr
994 ),
995 ));
996 }
997 linker_args.push((LinkArgTarget::Cdylib, value))
998 }
999 "rustc-link-arg-bins" => {
1000 check_and_add_target!("bin", Target::is_bin, LinkArgTarget::Bin);
1001 }
1002 "rustc-link-arg-bin" => {
1003 let (bin_name, arg) = value.split_once('=').ok_or_else(|| {
1004 anyhow::format_err!(
1005 "invalid instruction `{}{}={}` from {}\n\
1006 The instruction should have the form {}{}=BIN=ARG",
1007 syntax_prefix,
1008 key,
1009 value,
1010 whence,
1011 syntax_prefix,
1012 key
1013 )
1014 })?;
1015 if !targets
1016 .iter()
1017 .any(|target| target.is_bin() && target.name() == bin_name)
1018 {
1019 bail!(
1020 "invalid instruction `{}{}` from {}\n\
1021 The package {} does not have a bin target with the name `{}`.",
1022 syntax_prefix,
1023 key,
1024 whence,
1025 pkg_descr,
1026 bin_name
1027 );
1028 }
1029 linker_args.push((
1030 LinkArgTarget::SingleBin(bin_name.to_owned()),
1031 arg.to_string(),
1032 ));
1033 }
1034 "rustc-link-arg-tests" => {
1035 check_and_add_target!("test", Target::is_test, LinkArgTarget::Test);
1036 }
1037 "rustc-link-arg-benches" => {
1038 check_and_add_target!("benchmark", Target::is_bench, LinkArgTarget::Bench);
1039 }
1040 "rustc-link-arg-examples" => {
1041 check_and_add_target!("example", Target::is_example, LinkArgTarget::Example);
1042 }
1043 "rustc-link-arg" => {
1044 linker_args.push((LinkArgTarget::All, value));
1045 }
1046 "rustc-cfg" => cfgs.push(value.to_string()),
1047 "rustc-check-cfg" => check_cfgs.push(value.to_string()),
1048 "rustc-env" => {
1049 let (key, val) = BuildOutput::parse_rustc_env(&value, &whence)?;
1050 if key == "RUSTC_BOOTSTRAP" {
1053 let rustc_bootstrap_allows = |name: Option<&str>| {
1063 let name = match name {
1064 None => return false,
1068 Some(n) => n,
1069 };
1070 #[expect(
1071 clippy::disallowed_methods,
1072 reason = "consistency with rustc, not specified behavior"
1073 )]
1074 std::env::var("RUSTC_BOOTSTRAP")
1075 .map_or(false, |var| var.split(',').any(|s| s == name))
1076 };
1077 if nightly_features_allowed
1078 || rustc_bootstrap_allows(library_name.as_deref())
1079 {
1080 log_messages.push((Severity::Warning, format!("cannot set `RUSTC_BOOTSTRAP={}` from {}.\n\
1081 note: crates cannot set `RUSTC_BOOTSTRAP` themselves, as doing so would subvert the stability guarantees of Rust for your project.",
1082 val, whence
1083 )));
1084 } else {
1085 bail!(
1088 "cannot set `RUSTC_BOOTSTRAP={}` from {}.\n\
1089 note: crates cannot set `RUSTC_BOOTSTRAP` themselves, as doing so would subvert the stability guarantees of Rust for your project.\n\
1090 help: If you're sure you want to do this in your project, set the environment variable `RUSTC_BOOTSTRAP={}` before running cargo instead.",
1091 val,
1092 whence,
1093 library_name.as_deref().unwrap_or("1"),
1094 );
1095 }
1096 } else {
1097 env.push((key, val));
1098 }
1099 }
1100 "error" => log_messages.push((Severity::Error, value.to_string())),
1101 "warning" => log_messages.push((Severity::Warning, value.to_string())),
1102 "rerun-if-changed" => rerun_if_changed.push(PathBuf::from(value)),
1103 "rerun-if-env-changed" => rerun_if_env_changed.push(value.to_string()),
1104 "metadata" => {
1105 let (key, value) = parse_metadata(whence.as_str(), line, &value, old_syntax)?;
1106 metadata.push((key.to_owned(), value.to_owned()));
1107 }
1108 _ => bail!(
1109 "invalid output in {whence}: `{line}`\n\
1110 Unknown key: `{key}`.\n\
1111 {DOCS_LINK_SUGGESTION}",
1112 ),
1113 }
1114 }
1115
1116 Ok(BuildOutput {
1117 library_paths,
1118 library_links,
1119 linker_args,
1120 cfgs,
1121 check_cfgs,
1122 env,
1123 metadata,
1124 rerun_if_changed,
1125 rerun_if_env_changed,
1126 log_messages,
1127 })
1128 }
1129
1130 pub fn parse_rustc_flags(
1134 value: &str,
1135 whence: &str,
1136 ) -> CargoResult<(Vec<PathBuf>, Vec<String>)> {
1137 let value = value.trim();
1138 let mut flags_iter = value
1139 .split(|c: char| c.is_whitespace())
1140 .filter(|w| w.chars().any(|c| !c.is_whitespace()));
1141 let (mut library_paths, mut library_links) = (Vec::new(), Vec::new());
1142
1143 while let Some(flag) = flags_iter.next() {
1144 if flag.starts_with("-l") || flag.starts_with("-L") {
1145 let (flag, mut value) = flag.split_at(2);
1149 if value.is_empty() {
1150 value = match flags_iter.next() {
1151 Some(v) => v,
1152 None => bail! {
1153 "flag in rustc-flags has no value in {}: {}",
1154 whence,
1155 value
1156 },
1157 }
1158 }
1159
1160 match flag {
1161 "-l" => library_links.push(value.to_string()),
1162 "-L" => library_paths.push(PathBuf::from(value)),
1163
1164 _ => unreachable!(),
1166 };
1167 } else {
1168 bail!(
1169 "only `-l` and `-L` flags are allowed in {}: `{}`",
1170 whence,
1171 value
1172 )
1173 }
1174 }
1175 Ok((library_paths, library_links))
1176 }
1177
1178 pub fn parse_rustc_env(value: &str, whence: &str) -> CargoResult<(String, String)> {
1182 match value.split_once('=') {
1183 Some((n, v)) => Ok((n.to_owned(), v.to_owned())),
1184 _ => bail!("Variable rustc-env has no value in {whence}: {value}"),
1185 }
1186 }
1187}
1188
1189fn prepare_metabuild(
1193 build_runner: &BuildRunner<'_, '_>,
1194 unit: &Unit,
1195 deps: &[String],
1196) -> CargoResult<()> {
1197 let mut output = Vec::new();
1198 let available_deps = build_runner.unit_deps(unit);
1199 let meta_deps: Vec<_> = deps
1201 .iter()
1202 .filter_map(|name| {
1203 available_deps
1204 .iter()
1205 .find(|d| d.unit.pkg.name().as_str() == name.as_str())
1206 .map(|d| d.unit.target.crate_name())
1207 })
1208 .collect();
1209 output.push("fn main() {\n".to_string());
1210 for dep in &meta_deps {
1211 output.push(format!(" {}::metabuild();\n", dep));
1212 }
1213 output.push("}\n".to_string());
1214 let output = output.join("");
1215 let path = unit
1216 .pkg
1217 .manifest()
1218 .metabuild_path(build_runner.bcx.ws.build_dir());
1219 paths::create_dir_all(path.parent().unwrap())?;
1220 paths::write_if_changed(path, &output)?;
1221 Ok(())
1222}
1223
1224impl BuildDeps {
1225 pub fn new(output_file: &Path, output: Option<&BuildOutput>) -> BuildDeps {
1228 BuildDeps {
1229 build_script_output: output_file.to_path_buf(),
1230 rerun_if_changed: output
1231 .map(|p| &p.rerun_if_changed)
1232 .cloned()
1233 .unwrap_or_default(),
1234 rerun_if_env_changed: output
1235 .map(|p| &p.rerun_if_env_changed)
1236 .cloned()
1237 .unwrap_or_default(),
1238 }
1239 }
1240}
1241
1242pub fn build_map(build_runner: &mut BuildRunner<'_, '_>) -> CargoResult<()> {
1264 let mut ret = HashMap::new();
1265 for unit in &build_runner.bcx.roots {
1266 build(&mut ret, build_runner, unit)?;
1267 }
1268 build_runner
1269 .build_scripts
1270 .extend(ret.into_iter().map(|(k, v)| (k, Arc::new(v))));
1271 return Ok(());
1272
1273 fn build<'a>(
1276 out: &'a mut HashMap<Unit, BuildScripts>,
1277 build_runner: &mut BuildRunner<'_, '_>,
1278 unit: &Unit,
1279 ) -> CargoResult<&'a BuildScripts> {
1280 if out.contains_key(unit) {
1283 return Ok(&out[unit]);
1284 }
1285
1286 if unit.mode.is_run_custom_build() {
1288 if let Some(links) = unit.pkg.manifest().links() {
1289 if let Some(output) = unit.links_overrides.get(links) {
1290 let metadata = build_runner.get_run_build_script_metadata(unit);
1291 build_runner.build_script_outputs.lock().unwrap().insert(
1292 unit.pkg.package_id(),
1293 metadata,
1294 output.clone(),
1295 );
1296 }
1297 }
1298 }
1299
1300 let mut ret = BuildScripts::default();
1301
1302 if !unit.target.is_custom_build() && unit.pkg.has_custom_build() {
1304 let script_metas = build_runner
1305 .find_build_script_metadatas(unit)
1306 .expect("has_custom_build should have RunCustomBuild");
1307 for script_meta in script_metas {
1308 add_to_link(&mut ret, unit.pkg.package_id(), script_meta);
1309 }
1310 }
1311
1312 if unit.mode.is_run_custom_build() {
1313 parse_previous_explicit_deps(build_runner, unit);
1314 }
1315
1316 let mut dependencies: Vec<Unit> = build_runner
1321 .unit_deps(unit)
1322 .iter()
1323 .map(|d| d.unit.clone())
1324 .collect();
1325 dependencies.sort_by_key(|u| u.pkg.package_id());
1326
1327 for dep_unit in dependencies.iter() {
1328 let dep_scripts = build(out, build_runner, dep_unit)?;
1329
1330 if dep_unit.target.for_host() {
1331 ret.plugins.extend(dep_scripts.to_link.iter().cloned());
1332 } else if dep_unit.target.is_linkable() {
1333 for &(pkg, metadata) in dep_scripts.to_link.iter() {
1334 add_to_link(&mut ret, pkg, metadata);
1335 }
1336 }
1337 }
1338
1339 match out.entry(unit.clone()) {
1340 Entry::Vacant(entry) => Ok(entry.insert(ret)),
1341 Entry::Occupied(_) => panic!("cyclic dependencies in `build_map`"),
1342 }
1343 }
1344
1345 fn add_to_link(scripts: &mut BuildScripts, pkg: PackageId, metadata: UnitHash) {
1348 if scripts.seen_to_link.insert((pkg, metadata)) {
1349 scripts.to_link.push((pkg, metadata));
1350 }
1351 }
1352
1353 fn parse_previous_explicit_deps(build_runner: &mut BuildRunner<'_, '_>, unit: &Unit) {
1355 let run_files = BuildScriptRunFiles::for_unit(build_runner, unit);
1356 let (prev_output, _) = prev_build_output(build_runner, unit);
1357 let deps = BuildDeps::new(&run_files.stdout, prev_output.as_ref());
1358 build_runner.build_explicit_deps.insert(unit.clone(), deps);
1359 }
1360}
1361
1362fn prev_build_output(
1368 build_runner: &mut BuildRunner<'_, '_>,
1369 unit: &Unit,
1370) -> (Option<BuildOutput>, PathBuf) {
1371 let script_out_dir = if build_runner.bcx.gctx.cli_unstable().build_dir_new_layout {
1372 build_runner.files().out_dir_new_layout(unit)
1373 } else {
1374 build_runner.files().build_script_out_dir(unit)
1375 };
1376 let run_files = BuildScriptRunFiles::for_unit(build_runner, unit);
1377
1378 let prev_script_out_dir = paths::read_bytes(&run_files.root_output)
1379 .and_then(|bytes| paths::bytes2path(&bytes))
1380 .unwrap_or_else(|_| script_out_dir.clone());
1381
1382 (
1383 BuildOutput::parse_file(
1384 &run_files.stdout,
1385 unit.pkg.library().map(|t| t.crate_name()),
1386 &unit.pkg.to_string(),
1387 &prev_script_out_dir,
1388 &script_out_dir,
1389 build_runner.bcx.gctx.nightly_features_allowed,
1390 unit.pkg.targets(),
1391 &unit.pkg.rust_version().cloned(),
1392 )
1393 .ok(),
1394 prev_script_out_dir,
1395 )
1396}
1397
1398impl BuildScriptOutputs {
1399 fn insert(&mut self, pkg_id: PackageId, metadata: UnitHash, parsed_output: BuildOutput) {
1401 match self.outputs.entry(metadata) {
1402 Entry::Vacant(entry) => {
1403 entry.insert(parsed_output);
1404 }
1405 Entry::Occupied(entry) => panic!(
1406 "build script output collision for {}/{}\n\
1407 old={:?}\nnew={:?}",
1408 pkg_id,
1409 metadata,
1410 entry.get(),
1411 parsed_output
1412 ),
1413 }
1414 }
1415
1416 fn contains_key(&self, metadata: UnitHash) -> bool {
1418 self.outputs.contains_key(&metadata)
1419 }
1420
1421 pub fn get(&self, meta: UnitHash) -> Option<&BuildOutput> {
1423 self.outputs.get(&meta)
1424 }
1425
1426 pub fn iter(&self) -> impl Iterator<Item = (&UnitHash, &BuildOutput)> {
1428 self.outputs.iter()
1429 }
1430}
1431
1432struct BuildScriptRunFiles {
1434 root: PathBuf,
1436 stdout: PathBuf,
1438 stderr: PathBuf,
1440 root_output: PathBuf,
1443}
1444
1445impl BuildScriptRunFiles {
1446 pub fn for_unit(build_runner: &BuildRunner<'_, '_>, unit: &Unit) -> Self {
1447 let root = build_runner.files().build_script_run_dir(unit);
1448 let stdout = if build_runner.bcx.gctx.cli_unstable().build_dir_new_layout {
1449 root.join("stdout")
1450 } else {
1451 root.join("output")
1452 };
1453 let stderr = root.join("stderr");
1454 let root_output = root.join("root-output");
1455 Self {
1456 root,
1457 stdout,
1458 stderr,
1459 root_output,
1460 }
1461 }
1462}