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(|dep| dep.unit.is_std == unit.is_std)
468 .filter_map(|dep| {
469 if dep.unit.mode.is_run_custom_build() {
470 let dep_metadata = build_runner.get_run_build_script_metadata(&dep.unit);
471
472 let dep_name = dep.dep_name.unwrap_or(dep.unit.pkg.name());
473
474 Some((
475 dep_name,
476 dep.unit
477 .pkg
478 .manifest()
479 .links()
480 .map(|links| links.to_string()),
481 dep.unit.pkg.package_id(),
482 dep_metadata,
483 ))
484 } else {
485 None
486 }
487 })
488 .collect::<Vec<_>>();
489 let library_name = unit.pkg.library().map(|t| t.crate_name());
490 let pkg_descr = unit.pkg.to_string();
491 let build_script_outputs = Arc::clone(&build_runner.build_script_outputs);
492 let id = unit.pkg.package_id();
493 let output_file = script_run_dir.join("output");
494 let err_file = script_run_dir.join("stderr");
495 let root_output_file = script_run_dir.join("root-output");
496 let host_target_root = build_runner.files().host_dest().map(|v| v.to_path_buf());
497 let all = (
498 id,
499 library_name.clone(),
500 pkg_descr.clone(),
501 Arc::clone(&build_script_outputs),
502 output_file.clone(),
503 script_out_dir.clone(),
504 );
505 let build_scripts = build_runner.build_scripts.get(unit).cloned();
506 let json_messages = bcx.build_config.emit_json();
507 let extra_verbose = bcx.gctx.extra_verbose();
508 let (prev_output, prev_script_out_dir) = prev_build_output(build_runner, unit);
509 let metadata_hash = build_runner.get_run_build_script_metadata(unit);
510
511 paths::create_dir_all(&script_dir)?;
512 paths::create_dir_all(&script_out_dir)?;
513
514 let nightly_features_allowed = build_runner.bcx.gctx.nightly_features_allowed;
515 let targets: Vec<Target> = unit.pkg.targets().to_vec();
516 let msrv = unit.pkg.rust_version().cloned();
517 let targets_fresh = targets.clone();
519 let msrv_fresh = msrv.clone();
520
521 let env_profile_name = unit.profile.name.to_uppercase();
522 let built_with_debuginfo = build_runner
523 .bcx
524 .unit_graph
525 .get(unit)
526 .and_then(|deps| deps.iter().find(|dep| dep.unit.target == unit.target))
527 .map(|dep| dep.unit.profile.debuginfo.is_turned_on())
528 .unwrap_or(false);
529
530 let dirty = Work::new(move |state| {
536 paths::create_dir_all(&script_out_dir)
541 .context("failed to create script output directory for build command")?;
542
543 {
548 let build_script_outputs = build_script_outputs.lock().unwrap();
549 for (name, links, dep_id, dep_metadata) in lib_deps {
550 let script_output = build_script_outputs.get(dep_metadata).ok_or_else(|| {
551 internal(format!(
552 "failed to locate build state for env vars: {}/{}",
553 dep_id, dep_metadata
554 ))
555 })?;
556 let data = &script_output.metadata;
557 for (key, value) in data.iter() {
558 if let Some(ref links) = links {
559 cmd.env(
560 &format!("DEP_{}_{}", super::envify(&links), super::envify(key)),
561 value,
562 );
563 }
564 if any_build_script_metadata {
565 cmd.env(
566 &format!("CARGO_DEP_{}_{}", super::envify(&name), super::envify(key)),
567 value,
568 );
569 }
570 }
571 }
572 if let Some(build_scripts) = build_scripts
573 && let Some(ref host_target_root) = host_target_root
574 {
575 super::add_plugin_deps(
576 &mut cmd,
577 &build_script_outputs,
578 &build_scripts,
579 host_target_root,
580 )?;
581 }
582 }
583
584 state.running(&cmd);
586 let timestamp = paths::set_invocation_time(&script_run_dir)?;
587 let prefix = format!("[{} {}] ", id.name(), id.version());
588 let mut log_messages_in_case_of_panic = Vec::new();
589 let span = tracing::debug_span!("build_script", process = cmd.to_string());
590 let output = span.in_scope(|| {
591 cmd.exec_with_streaming(
592 &mut |stdout| {
593 if let Some(error) = stdout.strip_prefix(CARGO_ERROR_SYNTAX) {
594 log_messages_in_case_of_panic.push((Severity::Error, error.to_owned()));
595 }
596 if let Some(warning) = stdout
597 .strip_prefix(OLD_CARGO_WARNING_SYNTAX)
598 .or(stdout.strip_prefix(NEW_CARGO_WARNING_SYNTAX))
599 {
600 log_messages_in_case_of_panic.push((Severity::Warning, warning.to_owned()));
601 }
602 if extra_verbose {
603 state.stdout(format!("{}{}", prefix, stdout))?;
604 }
605 Ok(())
606 },
607 &mut |stderr| {
608 if extra_verbose {
609 state.stderr(format!("{}{}", prefix, stderr))?;
610 }
611 Ok(())
612 },
613 true,
614 )
615 .with_context(|| {
616 let mut build_error_context =
617 format!("failed to run custom build command for `{}`", pkg_descr);
618
619 #[expect(clippy::disallowed_methods, reason = "consistency with rustc")]
623 if let Ok(show_backtraces) = std::env::var("RUST_BACKTRACE") {
624 if !built_with_debuginfo && show_backtraces != "0" {
625 build_error_context.push_str(&format!(
626 "\n\
627 note: To improve backtraces for build dependencies, set the \
628 CARGO_PROFILE_{env_profile_name}_BUILD_OVERRIDE_DEBUG=true environment \
629 variable to enable debug information generation.",
630 ));
631 }
632 }
633
634 build_error_context
635 })
636 });
637
638 if let Err(error) = output {
640 insert_log_messages_in_build_outputs(
641 build_script_outputs,
642 id,
643 metadata_hash,
644 log_messages_in_case_of_panic,
645 );
646 return Err(error);
647 }
648 else if log_messages_in_case_of_panic
650 .iter()
651 .any(|(severity, _)| *severity == Severity::Error)
652 {
653 insert_log_messages_in_build_outputs(
654 build_script_outputs,
655 id,
656 metadata_hash,
657 log_messages_in_case_of_panic,
658 );
659 anyhow::bail!("build script logged errors");
660 }
661
662 let output = output.unwrap();
663
664 paths::write(&output_file, &output.stdout)?;
672 paths::set_file_time_no_err(output_file, timestamp);
675 paths::write(&err_file, &output.stderr)?;
676 paths::write(&root_output_file, paths::path2bytes(&script_out_dir)?)?;
677 let parsed_output = BuildOutput::parse(
678 &output.stdout,
679 library_name,
680 &pkg_descr,
681 &script_out_dir,
682 &script_out_dir,
683 nightly_features_allowed,
684 &targets,
685 &msrv,
686 )?;
687
688 if json_messages {
689 emit_build_output(state, &parsed_output, script_out_dir.as_path(), id)?;
690 }
691 build_script_outputs
692 .lock()
693 .unwrap()
694 .insert(id, metadata_hash, parsed_output);
695 Ok(())
696 });
697
698 let fresh = Work::new(move |state| {
702 let (id, library_name, pkg_descr, build_script_outputs, output_file, script_out_dir) = all;
703 let output = match prev_output {
704 Some(output) => output,
705 None => BuildOutput::parse_file(
706 &output_file,
707 library_name,
708 &pkg_descr,
709 &prev_script_out_dir,
710 &script_out_dir,
711 nightly_features_allowed,
712 &targets_fresh,
713 &msrv_fresh,
714 )?,
715 };
716
717 if json_messages {
718 emit_build_output(state, &output, script_out_dir.as_path(), id)?;
719 }
720
721 build_script_outputs
722 .lock()
723 .unwrap()
724 .insert(id, metadata_hash, output);
725 Ok(())
726 });
727
728 let mut job = fingerprint::prepare_target(build_runner, unit, false)?;
729 if job.freshness().is_dirty() {
730 job.before(dirty);
731 } else {
732 job.before(fresh);
733 }
734 Ok(job)
735}
736
737fn insert_log_messages_in_build_outputs(
740 build_script_outputs: Arc<Mutex<BuildScriptOutputs>>,
741 id: PackageId,
742 metadata_hash: UnitHash,
743 log_messages: Vec<LogMessage>,
744) {
745 let build_output_with_only_log_messages = BuildOutput {
746 log_messages,
747 ..BuildOutput::default()
748 };
749 build_script_outputs.lock().unwrap().insert(
750 id,
751 metadata_hash,
752 build_output_with_only_log_messages,
753 );
754}
755
756impl BuildOutput {
757 pub fn parse_file(
759 path: &Path,
760 library_name: Option<String>,
761 pkg_descr: &str,
762 script_out_dir_when_generated: &Path,
763 script_out_dir: &Path,
764 nightly_features_allowed: bool,
765 targets: &[Target],
766 msrv: &Option<RustVersion>,
767 ) -> CargoResult<BuildOutput> {
768 let contents = paths::read_bytes(path)?;
769 BuildOutput::parse(
770 &contents,
771 library_name,
772 pkg_descr,
773 script_out_dir_when_generated,
774 script_out_dir,
775 nightly_features_allowed,
776 targets,
777 msrv,
778 )
779 }
780
781 pub fn parse(
786 input: &[u8],
787 library_name: Option<String>,
789 pkg_descr: &str,
790 script_out_dir_when_generated: &Path,
791 script_out_dir: &Path,
792 nightly_features_allowed: bool,
793 targets: &[Target],
794 msrv: &Option<RustVersion>,
795 ) -> CargoResult<BuildOutput> {
796 let mut library_paths = Vec::new();
797 let mut library_links = Vec::new();
798 let mut linker_args = Vec::new();
799 let mut cfgs = Vec::new();
800 let mut check_cfgs = Vec::new();
801 let mut env = Vec::new();
802 let mut metadata = Vec::new();
803 let mut rerun_if_changed = Vec::new();
804 let mut rerun_if_env_changed = Vec::new();
805 let mut log_messages = Vec::new();
806 let whence = format!("build script of `{}`", pkg_descr);
807 const RESERVED_PREFIXES: &[&str] = &[
815 "rustc-flags=",
816 "rustc-link-lib=",
817 "rustc-link-search=",
818 "rustc-link-arg-cdylib=",
819 "rustc-cdylib-link-arg=",
820 "rustc-link-arg-bins=",
821 "rustc-link-arg-bin=",
822 "rustc-link-arg-tests=",
823 "rustc-link-arg-benches=",
824 "rustc-link-arg-examples=",
825 "rustc-link-arg=",
826 "rustc-cfg=",
827 "rustc-check-cfg=",
828 "rustc-env=",
829 "warning=",
830 "rerun-if-changed=",
831 "rerun-if-env-changed=",
832 ];
833 const DOCS_LINK_SUGGESTION: &str = "See https://doc.rust-lang.org/cargo/reference/build-scripts.html#outputs-of-the-build-script \
834 for more information about build script outputs.";
835
836 fn has_reserved_prefix(flag: &str) -> bool {
837 RESERVED_PREFIXES
838 .iter()
839 .any(|reserved_prefix| flag.starts_with(reserved_prefix))
840 }
841
842 fn check_minimum_supported_rust_version_for_new_syntax(
843 pkg_descr: &str,
844 msrv: &Option<RustVersion>,
845 flag: &str,
846 ) -> CargoResult<()> {
847 if let Some(msrv) = msrv {
848 let new_syntax_added_in = RustVersion::from_str("1.77.0")?;
849 if !new_syntax_added_in.is_compatible_with(msrv.as_partial()) {
850 let old_syntax_suggestion = if has_reserved_prefix(flag) {
851 format!(
852 "Switch to the old `cargo:{flag}` syntax (note the single colon).\n"
853 )
854 } else if flag.starts_with("metadata=") {
855 let old_format_flag = flag.strip_prefix("metadata=").unwrap();
856 format!(
857 "Switch to the old `cargo:{old_format_flag}` syntax instead of `cargo::{flag}` (note the single colon).\n"
858 )
859 } else {
860 String::new()
861 };
862
863 bail!(
864 "the `cargo::` syntax for build script output instructions was added in \
865 Rust 1.77.0, but the minimum supported Rust version of `{pkg_descr}` is {msrv}.\n\
866 {old_syntax_suggestion}\
867 {DOCS_LINK_SUGGESTION}"
868 );
869 }
870 }
871
872 Ok(())
873 }
874
875 fn parse_directive<'a>(
876 whence: &str,
877 line: &str,
878 data: &'a str,
879 old_syntax: bool,
880 ) -> CargoResult<(&'a str, &'a str)> {
881 let mut iter = data.splitn(2, "=");
882 let key = iter.next();
883 let value = iter.next();
884 match (key, value) {
885 (Some(a), Some(b)) => Ok((a, b.trim_end())),
886 _ => bail!(
887 "invalid output in {whence}: `{line}`\n\
888 Expected a line with `{syntax}KEY=VALUE` with an `=` character, \
889 but none was found.\n\
890 {DOCS_LINK_SUGGESTION}",
891 syntax = if old_syntax { "cargo:" } else { "cargo::" },
892 ),
893 }
894 }
895
896 fn parse_metadata<'a>(
897 whence: &str,
898 line: &str,
899 data: &'a str,
900 old_syntax: bool,
901 ) -> CargoResult<(&'a str, &'a str)> {
902 let mut iter = data.splitn(2, "=");
903 let key = iter.next();
904 let value = iter.next();
905 match (key, value) {
906 (Some(a), Some(b)) => Ok((a, b.trim_end())),
907 _ => bail!(
908 "invalid output in {whence}: `{line}`\n\
909 Expected a line with `{syntax}KEY=VALUE` with an `=` character, \
910 but none was found.\n\
911 {DOCS_LINK_SUGGESTION}",
912 syntax = if old_syntax {
913 "cargo:"
914 } else {
915 "cargo::metadata="
916 },
917 ),
918 }
919 }
920
921 for line in input.split(|b| *b == b'\n') {
922 let line = match str::from_utf8(line) {
923 Ok(line) => line.trim(),
924 Err(..) => continue,
925 };
926 let mut old_syntax = false;
927 let (key, value) = if let Some(data) = line.strip_prefix("cargo::") {
928 check_minimum_supported_rust_version_for_new_syntax(pkg_descr, msrv, data)?;
929 parse_directive(whence.as_str(), line, data, old_syntax)?
931 } else if let Some(data) = line.strip_prefix("cargo:") {
932 old_syntax = true;
933 if has_reserved_prefix(data) {
935 parse_directive(whence.as_str(), line, data, old_syntax)?
936 } else {
937 ("metadata", data)
939 }
940 } else {
941 continue;
943 };
944 let value = value.replace(
946 script_out_dir_when_generated.to_str().unwrap(),
947 script_out_dir.to_str().unwrap(),
948 );
949
950 let syntax_prefix = if old_syntax { "cargo:" } else { "cargo::" };
951 macro_rules! check_and_add_target {
952 ($target_kind: expr, $is_target_kind: expr, $link_type: expr) => {
953 if !targets.iter().any(|target| $is_target_kind(target)) {
954 bail!(
955 "invalid instruction `{}{}` from {}\n\
956 The package {} does not have a {} target.",
957 syntax_prefix,
958 key,
959 whence,
960 pkg_descr,
961 $target_kind
962 );
963 }
964 linker_args.push(($link_type, value));
965 };
966 }
967
968 match key {
970 "rustc-flags" => {
971 let (paths, links) = BuildOutput::parse_rustc_flags(&value, &whence)?;
972 library_links.extend(links.into_iter());
973 library_paths.extend(
974 paths
975 .into_iter()
976 .map(|p| LibraryPath::new(p, script_out_dir)),
977 );
978 }
979 "rustc-link-lib" => library_links.push(value.to_string()),
980 "rustc-link-search" => {
981 library_paths.push(LibraryPath::new(PathBuf::from(value), script_out_dir))
982 }
983 "rustc-link-arg-cdylib" | "rustc-cdylib-link-arg" => {
984 if !targets.iter().any(|target| target.is_cdylib()) {
985 log_messages.push((
986 Severity::Warning,
987 format!(
988 "{}{} was specified in the build script of {}, \
989 but that package does not contain a cdylib target\n\
990 \n\
991 Allowing this was an unintended change in the 1.50 \
992 release, and may become an error in the future. \
993 For more information, see \
994 <https://github.com/rust-lang/cargo/issues/9562>.",
995 syntax_prefix, key, pkg_descr
996 ),
997 ));
998 }
999 linker_args.push((LinkArgTarget::Cdylib, value))
1000 }
1001 "rustc-link-arg-bins" => {
1002 check_and_add_target!("bin", Target::is_bin, LinkArgTarget::Bin);
1003 }
1004 "rustc-link-arg-bin" => {
1005 let (bin_name, arg) = value.split_once('=').ok_or_else(|| {
1006 anyhow::format_err!(
1007 "invalid instruction `{}{}={}` from {}\n\
1008 The instruction should have the form {}{}=BIN=ARG",
1009 syntax_prefix,
1010 key,
1011 value,
1012 whence,
1013 syntax_prefix,
1014 key
1015 )
1016 })?;
1017 if !targets
1018 .iter()
1019 .any(|target| target.is_bin() && target.name() == bin_name)
1020 {
1021 bail!(
1022 "invalid instruction `{}{}` from {}\n\
1023 The package {} does not have a bin target with the name `{}`.",
1024 syntax_prefix,
1025 key,
1026 whence,
1027 pkg_descr,
1028 bin_name
1029 );
1030 }
1031 linker_args.push((
1032 LinkArgTarget::SingleBin(bin_name.to_owned()),
1033 arg.to_string(),
1034 ));
1035 }
1036 "rustc-link-arg-tests" => {
1037 check_and_add_target!("test", Target::is_test, LinkArgTarget::Test);
1038 }
1039 "rustc-link-arg-benches" => {
1040 check_and_add_target!("benchmark", Target::is_bench, LinkArgTarget::Bench);
1041 }
1042 "rustc-link-arg-examples" => {
1043 check_and_add_target!("example", Target::is_example, LinkArgTarget::Example);
1044 }
1045 "rustc-link-arg" => {
1046 linker_args.push((LinkArgTarget::All, value));
1047 }
1048 "rustc-cfg" => cfgs.push(value.to_string()),
1049 "rustc-check-cfg" => check_cfgs.push(value.to_string()),
1050 "rustc-env" => {
1051 let (key, val) = BuildOutput::parse_rustc_env(&value, &whence)?;
1052 if key == "RUSTC_BOOTSTRAP" {
1055 let rustc_bootstrap_allows = |name: Option<&str>| {
1065 let name = match name {
1066 None => return false,
1070 Some(n) => n,
1071 };
1072 #[expect(
1073 clippy::disallowed_methods,
1074 reason = "consistency with rustc, not specified behavior"
1075 )]
1076 std::env::var("RUSTC_BOOTSTRAP")
1077 .map_or(false, |var| var.split(',').any(|s| s == name))
1078 };
1079 if nightly_features_allowed
1080 || rustc_bootstrap_allows(library_name.as_deref())
1081 {
1082 log_messages.push((Severity::Warning, format!("Cannot set `RUSTC_BOOTSTRAP={}` from {}.\n\
1083 note: Crates cannot set `RUSTC_BOOTSTRAP` themselves, as doing so would subvert the stability guarantees of Rust for your project.",
1084 val, whence
1085 )));
1086 } else {
1087 bail!(
1090 "Cannot set `RUSTC_BOOTSTRAP={}` from {}.\n\
1091 note: Crates cannot set `RUSTC_BOOTSTRAP` themselves, as doing so would subvert the stability guarantees of Rust for your project.\n\
1092 help: If you're sure you want to do this in your project, set the environment variable `RUSTC_BOOTSTRAP={}` before running cargo instead.",
1093 val,
1094 whence,
1095 library_name.as_deref().unwrap_or("1"),
1096 );
1097 }
1098 } else {
1099 env.push((key, val));
1100 }
1101 }
1102 "error" => log_messages.push((Severity::Error, value.to_string())),
1103 "warning" => log_messages.push((Severity::Warning, value.to_string())),
1104 "rerun-if-changed" => rerun_if_changed.push(PathBuf::from(value)),
1105 "rerun-if-env-changed" => rerun_if_env_changed.push(value.to_string()),
1106 "metadata" => {
1107 let (key, value) = parse_metadata(whence.as_str(), line, &value, old_syntax)?;
1108 metadata.push((key.to_owned(), value.to_owned()));
1109 }
1110 _ => bail!(
1111 "invalid output in {whence}: `{line}`\n\
1112 Unknown key: `{key}`.\n\
1113 {DOCS_LINK_SUGGESTION}",
1114 ),
1115 }
1116 }
1117
1118 Ok(BuildOutput {
1119 library_paths,
1120 library_links,
1121 linker_args,
1122 cfgs,
1123 check_cfgs,
1124 env,
1125 metadata,
1126 rerun_if_changed,
1127 rerun_if_env_changed,
1128 log_messages,
1129 })
1130 }
1131
1132 pub fn parse_rustc_flags(
1136 value: &str,
1137 whence: &str,
1138 ) -> CargoResult<(Vec<PathBuf>, Vec<String>)> {
1139 let value = value.trim();
1140 let mut flags_iter = value
1141 .split(|c: char| c.is_whitespace())
1142 .filter(|w| w.chars().any(|c| !c.is_whitespace()));
1143 let (mut library_paths, mut library_links) = (Vec::new(), Vec::new());
1144
1145 while let Some(flag) = flags_iter.next() {
1146 if flag.starts_with("-l") || flag.starts_with("-L") {
1147 let (flag, mut value) = flag.split_at(2);
1151 if value.is_empty() {
1152 value = match flags_iter.next() {
1153 Some(v) => v,
1154 None => bail! {
1155 "Flag in rustc-flags has no value in {}: {}",
1156 whence,
1157 value
1158 },
1159 }
1160 }
1161
1162 match flag {
1163 "-l" => library_links.push(value.to_string()),
1164 "-L" => library_paths.push(PathBuf::from(value)),
1165
1166 _ => unreachable!(),
1168 };
1169 } else {
1170 bail!(
1171 "Only `-l` and `-L` flags are allowed in {}: `{}`",
1172 whence,
1173 value
1174 )
1175 }
1176 }
1177 Ok((library_paths, library_links))
1178 }
1179
1180 pub fn parse_rustc_env(value: &str, whence: &str) -> CargoResult<(String, String)> {
1184 match value.split_once('=') {
1185 Some((n, v)) => Ok((n.to_owned(), v.to_owned())),
1186 _ => bail!("Variable rustc-env has no value in {whence}: {value}"),
1187 }
1188 }
1189}
1190
1191fn prepare_metabuild(
1195 build_runner: &BuildRunner<'_, '_>,
1196 unit: &Unit,
1197 deps: &[String],
1198) -> CargoResult<()> {
1199 let mut output = Vec::new();
1200 let available_deps = build_runner.unit_deps(unit);
1201 let meta_deps: Vec<_> = deps
1203 .iter()
1204 .filter_map(|name| {
1205 available_deps
1206 .iter()
1207 .find(|d| d.unit.pkg.name().as_str() == name.as_str())
1208 .map(|d| d.unit.target.crate_name())
1209 })
1210 .collect();
1211 output.push("fn main() {\n".to_string());
1212 for dep in &meta_deps {
1213 output.push(format!(" {}::metabuild();\n", dep));
1214 }
1215 output.push("}\n".to_string());
1216 let output = output.join("");
1217 let path = unit
1218 .pkg
1219 .manifest()
1220 .metabuild_path(build_runner.bcx.ws.build_dir());
1221 paths::create_dir_all(path.parent().unwrap())?;
1222 paths::write_if_changed(path, &output)?;
1223 Ok(())
1224}
1225
1226impl BuildDeps {
1227 pub fn new(output_file: &Path, output: Option<&BuildOutput>) -> BuildDeps {
1230 BuildDeps {
1231 build_script_output: output_file.to_path_buf(),
1232 rerun_if_changed: output
1233 .map(|p| &p.rerun_if_changed)
1234 .cloned()
1235 .unwrap_or_default(),
1236 rerun_if_env_changed: output
1237 .map(|p| &p.rerun_if_env_changed)
1238 .cloned()
1239 .unwrap_or_default(),
1240 }
1241 }
1242}
1243
1244pub fn build_map(build_runner: &mut BuildRunner<'_, '_>) -> CargoResult<()> {
1266 let mut ret = HashMap::new();
1267 for unit in &build_runner.bcx.roots {
1268 build(&mut ret, build_runner, unit)?;
1269 }
1270 build_runner
1271 .build_scripts
1272 .extend(ret.into_iter().map(|(k, v)| (k, Arc::new(v))));
1273 return Ok(());
1274
1275 fn build<'a>(
1278 out: &'a mut HashMap<Unit, BuildScripts>,
1279 build_runner: &mut BuildRunner<'_, '_>,
1280 unit: &Unit,
1281 ) -> CargoResult<&'a BuildScripts> {
1282 if out.contains_key(unit) {
1285 return Ok(&out[unit]);
1286 }
1287
1288 if unit.mode.is_run_custom_build() {
1290 if let Some(links) = unit.pkg.manifest().links() {
1291 if let Some(output) = unit.links_overrides.get(links) {
1292 let metadata = build_runner.get_run_build_script_metadata(unit);
1293 build_runner.build_script_outputs.lock().unwrap().insert(
1294 unit.pkg.package_id(),
1295 metadata,
1296 output.clone(),
1297 );
1298 }
1299 }
1300 }
1301
1302 let mut ret = BuildScripts::default();
1303
1304 if !unit.target.is_custom_build() && unit.pkg.has_custom_build() {
1306 let script_metas = build_runner
1307 .find_build_script_metadatas(unit)
1308 .expect("has_custom_build should have RunCustomBuild");
1309 for script_meta in script_metas {
1310 add_to_link(&mut ret, unit.pkg.package_id(), script_meta);
1311 }
1312 }
1313
1314 if unit.mode.is_run_custom_build() {
1315 parse_previous_explicit_deps(build_runner, unit);
1316 }
1317
1318 let mut dependencies: Vec<Unit> = build_runner
1323 .unit_deps(unit)
1324 .iter()
1325 .map(|d| d.unit.clone())
1326 .collect();
1327 dependencies.sort_by_key(|u| u.pkg.package_id());
1328
1329 for dep_unit in dependencies.iter() {
1330 let dep_scripts = build(out, build_runner, dep_unit)?;
1331
1332 if dep_unit.target.for_host() {
1333 ret.plugins.extend(dep_scripts.to_link.iter().cloned());
1334 } else if dep_unit.target.is_linkable() {
1335 for &(pkg, metadata) in dep_scripts.to_link.iter() {
1336 add_to_link(&mut ret, pkg, metadata);
1337 }
1338 }
1339 }
1340
1341 match out.entry(unit.clone()) {
1342 Entry::Vacant(entry) => Ok(entry.insert(ret)),
1343 Entry::Occupied(_) => panic!("cyclic dependencies in `build_map`"),
1344 }
1345 }
1346
1347 fn add_to_link(scripts: &mut BuildScripts, pkg: PackageId, metadata: UnitHash) {
1350 if scripts.seen_to_link.insert((pkg, metadata)) {
1351 scripts.to_link.push((pkg, metadata));
1352 }
1353 }
1354
1355 fn parse_previous_explicit_deps(build_runner: &mut BuildRunner<'_, '_>, unit: &Unit) {
1357 let script_run_dir = build_runner.files().build_script_run_dir(unit);
1358 let output_file = script_run_dir.join("output");
1359 let (prev_output, _) = prev_build_output(build_runner, unit);
1360 let deps = BuildDeps::new(&output_file, prev_output.as_ref());
1361 build_runner.build_explicit_deps.insert(unit.clone(), deps);
1362 }
1363}
1364
1365fn prev_build_output(
1371 build_runner: &mut BuildRunner<'_, '_>,
1372 unit: &Unit,
1373) -> (Option<BuildOutput>, PathBuf) {
1374 let script_out_dir = build_runner.files().build_script_out_dir(unit);
1375 let script_run_dir = build_runner.files().build_script_run_dir(unit);
1376 let root_output_file = script_run_dir.join("root-output");
1377 let output_file = script_run_dir.join("output");
1378
1379 let prev_script_out_dir = paths::read_bytes(&root_output_file)
1380 .and_then(|bytes| paths::bytes2path(&bytes))
1381 .unwrap_or_else(|_| script_out_dir.clone());
1382
1383 (
1384 BuildOutput::parse_file(
1385 &output_file,
1386 unit.pkg.library().map(|t| t.crate_name()),
1387 &unit.pkg.to_string(),
1388 &prev_script_out_dir,
1389 &script_out_dir,
1390 build_runner.bcx.gctx.nightly_features_allowed,
1391 unit.pkg.targets(),
1392 &unit.pkg.rust_version().cloned(),
1393 )
1394 .ok(),
1395 prev_script_out_dir,
1396 )
1397}
1398
1399impl BuildScriptOutputs {
1400 fn insert(&mut self, pkg_id: PackageId, metadata: UnitHash, parsed_output: BuildOutput) {
1402 match self.outputs.entry(metadata) {
1403 Entry::Vacant(entry) => {
1404 entry.insert(parsed_output);
1405 }
1406 Entry::Occupied(entry) => panic!(
1407 "build script output collision for {}/{}\n\
1408 old={:?}\nnew={:?}",
1409 pkg_id,
1410 metadata,
1411 entry.get(),
1412 parsed_output
1413 ),
1414 }
1415 }
1416
1417 fn contains_key(&self, metadata: UnitHash) -> bool {
1419 self.outputs.contains_key(&metadata)
1420 }
1421
1422 pub fn get(&self, meta: UnitHash) -> Option<&BuildOutput> {
1424 self.outputs.get(&meta)
1425 }
1426
1427 pub fn iter(&self) -> impl Iterator<Item = (&UnitHash, &BuildOutput)> {
1429 self.outputs.iter()
1430 }
1431}