1use crate::{BuildStrategy, CompatibilityFloor, ReleasePlan};
4use command_group::CommandGroup;
5use eggpack_contract::{DistributionContract, ExpandedAssets};
6use serde::{Deserialize, Serialize};
7use std::{
8 collections::{BTreeMap, BTreeSet},
9 ffi::OsString,
10 fs,
11 io::{Read, Write},
12 path::{Path, PathBuf},
13 process::{Command, Stdio},
14 sync::{Arc, Mutex},
15 thread,
16 time::{Duration, Instant},
17};
18
19const MAX_OUTPUT: usize = 256 * 1024;
21const MAX_PROCESS_OUTPUT: usize = 8 * 1024 * 1024;
28const GIT_TIMEOUT: Duration = Duration::from_secs(30);
30const GIT_OUTPUT_LIMIT: usize = 4 * 1024;
32const MIN_DRAIN_GRACE: Duration = Duration::from_secs(1);
38const MAX_DRAIN_GRACE: Duration = Duration::from_secs(2);
46
47fn ensure_candidate_executable(path: &Path) -> Result<(), BuildError> {
52 #[cfg(unix)]
53 {
54 use std::os::unix::fs::PermissionsExt;
55 let meta =
56 fs::symlink_metadata(path).map_err(|_| build_err("candidate is not executable"))?;
57 if meta.file_type().is_symlink() || !meta.is_file() {
58 return Err(build_err("candidate is not executable"));
59 }
60 let mut permissions = meta.permissions();
61 permissions.set_mode(permissions.mode() | 0o111);
62 fs::set_permissions(path, permissions)
63 .map_err(|_| build_err("candidate is not executable"))?;
64 Ok(())
65 }
66 #[cfg(not(unix))]
67 {
68 let _ = path;
69 Ok(())
70 }
71}
72
73#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
75#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
76pub enum LogicalOutputSelector {
77 Direct,
79 BundleEntry {
81 index: usize,
83 },
84 ArchiveMember {
86 source: String,
88 },
89}
90
91#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
93#[serde(deny_unknown_fields)]
94pub struct BuildBinding {
95 pub selector: LogicalOutputSelector,
97 pub package: String,
99 pub binary: String,
101}
102
103#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
105#[serde(deny_unknown_fields)]
106pub struct BuildBindingsV1 {
107 pub schema_version: u32,
109 pub targets: BTreeMap<String, Vec<BuildBinding>>,
111}
112
113#[derive(Debug, Clone, PartialEq, Eq)]
115pub struct BuildError(pub(crate) String);
116impl std::fmt::Display for BuildError {
117 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
118 f.write_str(&self.0)
119 }
120}
121impl std::error::Error for BuildError {}
122fn build_err(s: &str) -> BuildError {
123 BuildError(s.to_owned())
124}
125
126#[derive(Clone, Copy)]
127enum ExecutableAllowance {
128 Builder,
129 Candidate,
130 Qemu,
131 Git,
132 Interpreter,
133}
134
135enum Cancellation<'a> {
140 None,
142 Build(&'a BuildCancellation),
144 Flag(&'a std::sync::atomic::AtomicBool),
146}
147
148impl Cancellation<'_> {
149 fn is_cancelled(&self) -> bool {
150 match self {
151 Cancellation::None => false,
152 Cancellation::Build(cancellation) => cancellation.is_cancelled(),
153 Cancellation::Flag(flag) => flag.load(std::sync::atomic::Ordering::SeqCst),
154 }
155 }
156}
157
158#[derive(Debug, Clone, PartialEq, Eq)]
160pub struct CommandSpec {
161 pub executable: String,
163 pub args: Vec<String>,
165 pub cwd: PathBuf,
167 pub env: BTreeMap<String, String>,
169 pub timeout: Duration,
171 pub stdout_limit: usize,
173 pub stderr_limit: usize,
175 pub expected_stdout: Option<String>,
177 pub expected_stdout_exact: Option<String>,
182}
183
184#[derive(Debug, Clone, PartialEq, Eq)]
186pub struct BoundCommand {
187 pub selector: LogicalOutputSelector,
189 pub package: String,
191 pub binary: String,
193 pub command: CommandSpec,
195}
196
197#[derive(Debug, Clone, PartialEq, Eq)]
203pub struct InterpreterCommandSpec {
204 pub executable: String,
206 pub args: Vec<OsString>,
208 pub cwd: PathBuf,
210 pub env: BTreeMap<String, String>,
212 pub timeout: Duration,
214 pub stdout_limit: usize,
216 pub stderr_limit: usize,
218 pub expected_stdout: Option<String>,
220}
221
222#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
224pub enum CommandOutcome {
225 Success,
227 Failed(i32),
229 TimedOut,
231 Cancelled,
233 OutputLimitExceeded,
235}
236
237#[derive(Debug, Clone, Default)]
239pub struct BuildCancellation(std::sync::Arc<std::sync::atomic::AtomicBool>);
240impl BuildCancellation {
241 pub fn new() -> Self {
243 Self::default()
244 }
245 pub fn cancel(&self) {
247 self.0.store(true, std::sync::atomic::Ordering::SeqCst);
248 }
249 pub(crate) fn is_cancelled(&self) -> bool {
250 self.0.load(std::sync::atomic::Ordering::SeqCst)
251 }
252}
253
254#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
256pub struct ProcessEvidence {
257 pub outcome: CommandOutcome,
259 pub stdout_bytes: usize,
261 pub stderr_bytes: usize,
263}
264
265#[derive(Debug, Clone, PartialEq, Eq)]
267pub struct CandidateArtifact {
268 pub target: String,
270 pub selector: LogicalOutputSelector,
272 pub package: String,
274 pub binary: String,
276 pub path: PathBuf,
278 pub size: u64,
280}
281
282#[derive(Debug, Clone, PartialEq, Eq)]
284pub struct BuildAttempt {
285 pub release_id: String,
287 pub source_revision: String,
289 pub target: String,
291 pub strategy: BuildStrategy,
293 pub tool_summary: String,
295 pub process: ProcessEvidence,
297 pub candidates: Vec<CandidateArtifact>,
299}
300
301impl BuildBindingsV1 {
302 pub fn from_toml(text: &str) -> Result<Self, BuildError> {
304 let value: Self =
305 toml::from_str(text).map_err(|_| build_err("invalid BuildBindings TOML"))?;
306 value.validate_shape()?;
307 Ok(value)
308 }
309 fn validate_shape(&self) -> Result<(), BuildError> {
310 if self.schema_version != 1 || self.targets.is_empty() || self.targets.len() > 256 {
311 return Err(build_err("invalid BuildBindings version or target count"));
312 }
313 for (target, bindings) in &self.targets {
314 if target.is_empty() || bindings.is_empty() || bindings.len() > 256 {
315 return Err(build_err("invalid BuildBindings target or binding count"));
316 }
317 let mut slots = BTreeSet::new();
318 for b in bindings {
319 if !slots.insert(&b.selector)
320 || !valid_identifier(&b.package)
321 || !valid_identifier(&b.binary)
322 {
323 return Err(build_err("duplicate slot or invalid Cargo identifier"));
324 }
325 if let LogicalOutputSelector::ArchiveMember { source } = &b.selector {
326 if source.is_empty()
327 || source.len() > 255
328 || source.starts_with('/')
329 || source
330 .split('/')
331 .any(|p| p.is_empty() || p == "." || p == "..")
332 {
333 return Err(build_err("invalid archive member source"));
334 }
335 }
336 }
337 }
338 Ok(())
339 }
340 pub fn validate_for(
342 &self,
343 contract: &DistributionContract,
344 plan: &ReleasePlan,
345 ) -> Result<(), BuildError> {
346 self.validate_shape()?;
347 for target in &plan.targets {
348 let bindings = self
349 .targets
350 .get(&target.target)
351 .ok_or_else(|| build_err("missing target bindings"))?;
352 let expanded = contract
353 .expand(&target.target, &plan.release_id)
354 .map_err(|_| build_err("contract target expansion failed"))?;
355 let expected: BTreeSet<LogicalOutputSelector> = match expanded.assets {
356 ExpandedAssets::Direct(_) => [LogicalOutputSelector::Direct].into_iter().collect(),
357 ExpandedAssets::Bundle(b) => (0..b.entries.len())
358 .map(|index| LogicalOutputSelector::BundleEntry { index })
359 .collect(),
360 ExpandedAssets::Archive(a) => a
361 .members
362 .into_iter()
363 .map(|m| LogicalOutputSelector::ArchiveMember { source: m.source })
364 .collect(),
365 };
366 let actual: BTreeSet<_> = bindings.iter().map(|b| b.selector.clone()).collect();
367 if actual != expected {
368 return Err(build_err(
369 "bindings do not exactly cover contract Cargo slots",
370 ));
371 }
372 }
373 if self
374 .targets
375 .keys()
376 .any(|k| !plan.targets.iter().any(|t| &t.target == k))
377 {
378 return Err(build_err("bindings include target outside ReleasePlan"));
379 }
380 Ok(())
381 }
382}
383fn valid_identifier(s: &str) -> bool {
384 !s.is_empty()
385 && s.len() <= 128
386 && s.bytes()
387 .all(|c| c.is_ascii_alphanumeric() || matches!(c, b'_' | b'-' | b'.'))
388}
389
390pub fn cargo_command(
392 target: &crate::PlannedTarget,
393 binding: &BuildBinding,
394 cwd: &Path,
395 target_dir: &Path,
396 timeout: Duration,
397) -> Result<CommandSpec, BuildError> {
398 if !valid_identifier(&binding.package) || !valid_identifier(&binding.binary) {
399 return Err(build_err("invalid Cargo identifier"));
400 }
401 let rustup = target.policy.toolchain.rust.as_str();
402 let mut args = vec!["+".to_owned() + rustup];
406 args.push(
407 match target.policy.strategy {
408 BuildStrategy::NativeCargo => "build",
409 BuildStrategy::CargoZigbuild => "zigbuild",
410 }
411 .into(),
412 );
413 args.extend(["--release".to_owned(), "--locked".to_owned()]);
414 if target.policy.strategy == BuildStrategy::CargoZigbuild {
415 let triple = match target.policy.floor {
416 CompatibilityFloor::Glibc { major, minor } => {
417 format!("{}.{major}.{minor}", target.target)
418 }
419 CompatibilityFloor::Macos { .. } => {
420 crate::validate_floor_applicability(
423 &target.policy.floor,
424 target.policy.strategy,
425 &target.target,
426 )
427 .map_err(|_| build_err("macOS floor cannot use cargo-zigbuild"))?;
428 target.target.clone()
429 }
430 CompatibilityFloor::None => target.target.clone(),
431 };
432 args.extend(["--target".to_owned(), triple]);
433 } else {
434 args.extend(["--target".to_owned(), target.target.clone()]);
435 }
436 args.extend([
437 "--package".into(),
438 binding.package.clone(),
439 "--bin".into(),
440 binding.binary.clone(),
441 ]);
442 let mut env = BTreeMap::new();
443 env.insert(
444 "CARGO_TARGET_DIR".into(),
445 target_dir.to_string_lossy().into_owned(),
446 );
447 Ok(CommandSpec {
448 executable: "cargo".into(),
449 args,
450 cwd: cwd.to_path_buf(),
451 env,
452 timeout,
453 stdout_limit: MAX_OUTPUT,
454 stderr_limit: MAX_OUTPUT,
455 expected_stdout: None,
456 expected_stdout_exact: None,
457 })
458}
459
460pub fn run_bounded_cancellable(
462 spec: &CommandSpec,
463 cancellation: &BuildCancellation,
464) -> Result<ProcessEvidence, BuildError> {
465 run_bounded_inner(
466 spec,
467 Cancellation::Build(cancellation),
468 ExecutableAllowance::Builder,
469 )
470}
471
472pub fn run_interpreter_bounded(
486 spec: &InterpreterCommandSpec,
487 cancelled: Option<&std::sync::atomic::AtomicBool>,
488) -> Result<ProcessEvidence, BuildError> {
489 let cancellation = match cancelled {
490 Some(flag) => Cancellation::Flag(flag),
491 None => Cancellation::None,
492 };
493 let run = BoundedRun {
494 executable: spec.executable.as_str(),
495 args: &spec.args,
496 cwd: spec.cwd.as_path(),
497 env: &spec.env,
498 timeout: spec.timeout,
499 stdout_limit: spec.stdout_limit,
500 stderr_limit: spec.stderr_limit,
501 expected_stdout: spec.expected_stdout.as_deref(),
502 expected_stdout_exact: None,
503 };
504 run_bounded(&run, cancellation, ExecutableAllowance::Interpreter)
505}
506
507pub fn run_git_bounded(expected: &str, cwd: Option<&Path>) -> Result<ProcessEvidence, BuildError> {
513 run_git_resolve_bounded(
514 vec![
515 "rev-parse".into(),
516 "--verify".into(),
517 "HEAD^{commit}".into(),
518 ],
519 expected,
520 cwd,
521 )
522}
523
524pub fn run_git_tag_bounded(
526 tag: &str,
527 expected: &str,
528 cwd: Option<&Path>,
529) -> Result<ProcessEvidence, BuildError> {
530 if crate::validate_exact_tag_safety(tag).is_err() {
533 return Err(build_err("invalid exact git tag"));
534 }
535 run_git_resolve_bounded(
536 vec![
537 "rev-parse".into(),
538 "--verify".into(),
539 format!("refs/tags/{tag}^{{commit}}"),
540 ],
541 expected,
542 cwd,
543 )
544}
545
546fn run_git_resolve_bounded(
547 args: Vec<String>,
548 expected: &str,
549 cwd: Option<&Path>,
550) -> Result<ProcessEvidence, BuildError> {
551 let cwd = match cwd {
552 Some(cwd) => cwd.to_path_buf(),
553 None => std::env::current_dir().map_err(|_| build_err("working directory unavailable"))?,
554 };
555 let spec = CommandSpec {
556 executable: "git".into(),
557 args,
558 cwd,
559 env: BTreeMap::new(),
560 timeout: GIT_TIMEOUT,
561 stdout_limit: GIT_OUTPUT_LIMIT,
562 stderr_limit: GIT_OUTPUT_LIMIT,
563 expected_stdout: None,
564 expected_stdout_exact: Some(expected.to_owned()),
565 };
566 run_bounded_inner(&spec, Cancellation::None, ExecutableAllowance::Git)
567}
568
569pub(crate) fn run_qualification_process(
570 spec: &CommandSpec,
571 cancellation: &BuildCancellation,
572) -> Result<ProcessEvidence, BuildError> {
573 run_bounded_inner(
574 spec,
575 Cancellation::Build(cancellation),
576 ExecutableAllowance::Candidate,
577 )
578}
579
580pub(crate) fn run_qemu_process(
581 spec: &CommandSpec,
582 cancellation: &BuildCancellation,
583) -> Result<ProcessEvidence, BuildError> {
584 run_bounded_inner(
585 spec,
586 Cancellation::Build(cancellation),
587 ExecutableAllowance::Qemu,
588 )
589}
590
591struct BoundedRun<'a> {
597 executable: &'a str,
598 args: &'a [OsString],
599 cwd: &'a Path,
600 env: &'a BTreeMap<String, String>,
601 timeout: Duration,
602 stdout_limit: usize,
603 stderr_limit: usize,
604 expected_stdout: Option<&'a str>,
605 expected_stdout_exact: Option<&'a str>,
606}
607
608fn run_bounded_inner(
609 spec: &CommandSpec,
610 cancellation: Cancellation<'_>,
611 allowance: ExecutableAllowance,
612) -> Result<ProcessEvidence, BuildError> {
613 let args: Vec<OsString> = spec.args.iter().map(OsString::from).collect();
614 let run = BoundedRun {
615 executable: spec.executable.as_str(),
616 args: &args,
617 cwd: spec.cwd.as_path(),
618 env: &spec.env,
619 timeout: spec.timeout,
620 stdout_limit: spec.stdout_limit,
621 stderr_limit: spec.stderr_limit,
622 expected_stdout: spec.expected_stdout.as_deref(),
623 expected_stdout_exact: spec.expected_stdout_exact.as_deref(),
624 };
625 run_bounded(&run, cancellation, allowance)
626}
627
628#[cfg(unix)]
645fn group_signal_failure_is_benign(
646 error: &std::io::Error,
647 child_exited: bool,
648 retry_group_signal: impl FnOnce() -> std::io::Result<()>,
649) -> bool {
650 if error.raw_os_error() == Some(libc::ESRCH) {
651 return true;
652 }
653 if !child_exited {
654 return false;
655 }
656 match retry_group_signal() {
657 Ok(()) => true,
658 Err(retry_error) => retry_error.raw_os_error() == Some(libc::ESRCH),
659 }
660}
661
662fn terminate_process_group(
676 child: &mut command_group::GroupChild,
677 message: &str,
678) -> Result<(), BuildError> {
679 match child.kill() {
680 Ok(()) => Ok(()),
681 Err(error) => {
682 let child_wait = child.try_wait();
685 #[cfg(unix)]
686 let child_exited = child_wait.as_ref().is_ok_and(Option::is_some);
687 #[cfg(unix)]
688 if group_signal_failure_is_benign(&error, child_exited, || child.kill()) {
689 return Ok(());
690 }
691 #[cfg(not(unix))]
692 let _ = child_wait;
693 Err(build_err(message))
694 }
695 }
696}
697
698fn run_bounded(
699 run: &BoundedRun<'_>,
700 cancellation: Cancellation<'_>,
701 allowance: ExecutableAllowance,
702) -> Result<ProcessEvidence, BuildError> {
703 let executable_allowed = match allowance {
704 ExecutableAllowance::Builder => {
705 matches!(run.executable, "cargo" | "rustc" | "zig")
706 }
707 ExecutableAllowance::Candidate => Path::new(run.executable).is_absolute(),
708 ExecutableAllowance::Qemu => {
709 matches!(run.executable, "qemu-x86_64" | "qemu-aarch64" | "qemu-arm")
710 }
711 ExecutableAllowance::Git => run.executable == "git",
712 ExecutableAllowance::Interpreter => matches!(run.executable, "python3" | "python"),
713 };
714 if !executable_allowed
715 || run.timeout.is_zero()
716 || run.timeout > Duration::from_secs(86_400)
717 || run.stdout_limit == 0
718 || run.stderr_limit == 0
719 || run.stdout_limit > MAX_PROCESS_OUTPUT
720 || run.stderr_limit > MAX_PROCESS_OUTPUT
721 {
722 return Err(build_err("invalid process bounds or executable"));
723 }
724 if matches!(allowance, ExecutableAllowance::Candidate)
729 && ensure_candidate_executable(Path::new(run.executable)).is_err()
730 {
731 return Err(build_err("candidate is not executable"));
732 }
733 let mut command = Command::new(run.executable);
734 command
735 .args(run.args)
736 .current_dir(run.cwd)
737 .env_clear()
738 .stdin(Stdio::null())
739 .stdout(Stdio::piped())
740 .stderr(Stdio::piped());
741 let environment = if matches!(allowance, ExecutableAllowance::Git) {
742 [
746 "PATH",
747 "HOME",
748 "USERPROFILE",
749 "SystemRoot",
750 "WINDIR",
751 "TEMP",
752 "TMP",
753 ]
754 .as_slice()
755 } else if !matches!(allowance, ExecutableAllowance::Builder) {
756 ["PATH", "SystemRoot", "WINDIR", "TEMP", "TMP"].as_slice()
757 } else {
758 [
759 "PATH",
760 "HOME",
761 "USERPROFILE",
762 "SystemRoot",
763 "WINDIR",
764 "TEMP",
765 "TMP",
766 "CARGO_HOME",
767 "RUSTUP_HOME",
768 "LIB",
769 "LIBPATH",
770 "INCLUDE",
771 "VCToolsInstallDir",
772 "VisualStudioVersion",
773 "VCINSTALLDIR",
774 "WindowsSdkDir",
775 "WindowsSDKVersion",
776 "UniversalCRTSdkDir",
777 "UCRTVersion",
778 ]
779 .as_slice()
780 };
781 for key in environment {
782 if let Some(value) = std::env::var_os(key) {
783 command.env(key, value);
784 }
785 }
786 #[cfg(windows)]
787 if let Some(vc_tools) = std::env::var_os("VCToolsInstallDir") {
788 let preferred_linker = PathBuf::from(vc_tools)
789 .join("bin")
790 .join("Hostx64")
791 .join("x64");
792 if let Some(path) = std::env::var_os("PATH") {
793 let path = std::iter::once(preferred_linker).chain(std::env::split_paths(&path));
794 if let Ok(path) = std::env::join_paths(path) {
795 command.env("PATH", path);
796 }
797 }
798 }
799 command.envs(run.env);
800 let mut child = command
801 .group_spawn()
802 .map_err(|_| build_err("process spawn failed"))?;
803 let stdout = child
804 .inner()
805 .stdout
806 .take()
807 .ok_or_else(|| build_err("stdout pipe unavailable"))?;
808 let stderr = child
809 .inner()
810 .stderr
811 .take()
812 .ok_or_else(|| build_err("stderr pipe unavailable"))?;
813 let out = Arc::new(Mutex::new((Vec::new(), false)));
814 let err = Arc::new(Mutex::new((Vec::new(), false)));
815 let out2 = out.clone();
816 let out_limit = run.stdout_limit;
817 let t1 = thread::spawn(move || drain(stdout, out2, out_limit));
818 let err2 = err.clone();
819 let err_limit = run.stderr_limit;
820 let t2 = thread::spawn(move || drain(stderr, err2, err_limit));
821 let until = Instant::now() + run.timeout;
822 let (timed_out, cancelled, over_limit) = loop {
823 if cancellation.is_cancelled() {
824 terminate_process_group(&mut child, "cancelled process-group termination failed")?;
825 child
826 .wait()
827 .map_err(|_| build_err("cancelled process-group wait failed"))?;
828 break (false, true, false);
829 }
830 if Instant::now() >= until {
831 terminate_process_group(&mut child, "process-group termination failed")?;
832 child
833 .wait()
834 .map_err(|_| build_err("process-group wait failed"))?;
835 break (true, false, false);
836 }
837 if stream_over_limit(&out) || stream_over_limit(&err) {
841 terminate_process_group(&mut child, "output-limit process-group termination failed")?;
842 child
843 .wait()
844 .map_err(|_| build_err("output-limit process-group wait failed"))?;
845 break (false, false, true);
846 }
847 if child
848 .try_wait()
849 .map_err(|_| build_err("process wait failed"))?
850 .is_some()
851 {
852 break (false, false, false);
853 }
854 thread::sleep(Duration::from_millis(20));
855 };
856 let drain_budget = until
864 .saturating_duration_since(Instant::now())
865 .clamp(MIN_DRAIN_GRACE, MAX_DRAIN_GRACE);
866 let drain_until = Instant::now() + drain_budget;
867 let drained = join_drained(t1, drain_until, "stdout reader failed")?
868 & join_drained(t2, drain_until, "stderr reader failed")?;
869 if !drained {
870 let _ = child.kill();
875 }
876 let status = child
877 .try_wait()
878 .map_err(|_| build_err("process wait failed"))?
879 .ok_or_else(|| build_err("process cleanup incomplete"))?;
880 let (stdout, out_over) = out
881 .lock()
882 .map_err(|_| build_err("stdout state unavailable"))?
883 .clone();
884 let (stderr, err_over) = err
885 .lock()
886 .map_err(|_| build_err("stderr state unavailable"))?
887 .clone();
888 let expected_missing = run
889 .expected_stdout
890 .is_some_and(|expected| !String::from_utf8_lossy(&stdout).contains(expected))
891 || run
892 .expected_stdout_exact
893 .is_some_and(|expected| String::from_utf8_lossy(&stdout).trim() != expected);
894 let outcome = if timed_out {
895 CommandOutcome::TimedOut
896 } else if cancelled {
897 CommandOutcome::Cancelled
898 } else if over_limit || !drained || out_over || err_over {
899 CommandOutcome::OutputLimitExceeded
900 } else if expected_missing {
901 CommandOutcome::Failed(-1)
902 } else if status.success() {
903 CommandOutcome::Success
904 } else {
905 CommandOutcome::Failed(status.code().unwrap_or(-1))
906 };
907 Ok(ProcessEvidence {
908 outcome,
909 stdout_bytes: stdout.len(),
910 stderr_bytes: stderr.len(),
911 })
912}
913fn join_drained(
921 handle: thread::JoinHandle<()>,
922 drain_until: Instant,
923 reader_error: &'static str,
924) -> Result<bool, BuildError> {
925 while !handle.is_finished() {
926 if Instant::now() >= drain_until {
927 return Ok(false);
928 }
929 thread::sleep(Duration::from_millis(10));
930 }
931 handle.join().map_err(|_| build_err(reader_error))?;
932 Ok(true)
933}
934
935fn stream_over_limit(capture: &Arc<Mutex<(Vec<u8>, bool)>>) -> bool {
941 capture.lock().map(|state| state.1).unwrap_or(false)
942}
943
944fn drain<R: Read>(mut reader: R, capture: Arc<Mutex<(Vec<u8>, bool)>>, limit: usize) {
945 let mut buffer = [0; 8192];
946 loop {
947 match reader.read(&mut buffer) {
948 Ok(0) | Err(_) => break,
949 Ok(n) => {
950 if let Ok(mut state) = capture.lock() {
951 let keep = n.min(limit.saturating_sub(state.0.len()));
952 state.0.extend_from_slice(&buffer[..keep]);
953 if keep < n {
954 state.1 = true;
955 }
956 }
957 }
958 }
959 }
960}
961
962fn preflight(
964 target: &crate::PlannedTarget,
965 cwd: &Path,
966 cancellation: &BuildCancellation,
967) -> Result<(), BuildError> {
968 let rust = run_bounded_cancellable(
969 &CommandSpec {
970 executable: "rustc".into(),
971 args: vec![
972 "+".to_owned() + &target.policy.toolchain.rust,
973 "--version".into(),
974 ],
975 cwd: cwd.into(),
976 env: BTreeMap::new(),
977 timeout: Duration::from_secs(10),
978 stdout_limit: 1024,
979 stderr_limit: 1024,
980 expected_stdout: None,
981 expected_stdout_exact: None,
982 },
983 cancellation,
984 )?;
985 if rust.outcome != CommandOutcome::Success {
986 return Err(build_err("configured Rust toolchain preflight failed"));
987 }
988 let cargo = run_bounded_cancellable(
989 &CommandSpec {
990 executable: "cargo".into(),
991 args: vec![
992 "+".to_owned() + &target.policy.toolchain.rust,
993 "--version".into(),
994 ],
995 cwd: cwd.into(),
996 env: BTreeMap::new(),
997 timeout: Duration::from_secs(10),
998 stdout_limit: 1024,
999 stderr_limit: 1024,
1000 expected_stdout: None,
1001 expected_stdout_exact: None,
1002 },
1003 cancellation,
1004 )?;
1005 if cargo.outcome != CommandOutcome::Success {
1006 return Err(build_err("configured Cargo toolchain preflight failed"));
1007 }
1008 if target.policy.strategy == BuildStrategy::CargoZigbuild {
1009 let expected = target
1010 .policy
1011 .toolchain
1012 .cargo_zigbuild
1013 .as_deref()
1014 .ok_or_else(|| build_err("cargo-zigbuild version missing"))?;
1015 let expected_zig = target
1016 .policy
1017 .toolchain
1018 .zig
1019 .as_deref()
1020 .ok_or_else(|| build_err("Zig version missing"))?;
1021 let actual = run_bounded_cancellable(
1022 &CommandSpec {
1023 executable: "cargo".into(),
1024 args: vec!["zigbuild".into(), "--version".into()],
1025 cwd: cwd.into(),
1026 env: BTreeMap::new(),
1027 timeout: Duration::from_secs(10),
1028 stdout_limit: 1024,
1029 stderr_limit: 1024,
1030 expected_stdout: None,
1033 expected_stdout_exact: Some(format!("cargo-zigbuild {expected}")),
1034 },
1035 cancellation,
1036 )?;
1037 if actual.outcome != CommandOutcome::Success {
1038 return Err(build_err("cargo-zigbuild version mismatch"));
1039 }
1040 let zig = run_bounded_cancellable(
1041 &CommandSpec {
1042 executable: "zig".into(),
1043 args: vec!["version".into()],
1044 cwd: cwd.into(),
1045 env: BTreeMap::new(),
1046 timeout: Duration::from_secs(10),
1047 stdout_limit: 1024,
1048 stderr_limit: 1024,
1049 expected_stdout: None,
1051 expected_stdout_exact: Some(expected_zig.to_owned()),
1052 },
1053 cancellation,
1054 )?;
1055 if zig.outcome != CommandOutcome::Success {
1056 return Err(build_err("Zig version mismatch"));
1057 }
1058 }
1059 Ok(())
1060}
1061
1062pub fn execute_target(
1064 plan: &ReleasePlan,
1065 target: &crate::PlannedTarget,
1066 bindings: &[BuildBinding],
1067 repository_root: &Path,
1068 work_root: &Path,
1069 invocation: &str,
1070) -> Result<BuildAttempt, BuildError> {
1071 execute_target_cancellable(
1072 plan,
1073 target,
1074 bindings,
1075 repository_root,
1076 work_root,
1077 invocation,
1078 &BuildCancellation::new(),
1079 )
1080}
1081
1082pub fn execute_target_cancellable(
1084 plan: &ReleasePlan,
1085 target: &crate::PlannedTarget,
1086 bindings: &[BuildBinding],
1087 repository_root: &Path,
1088 work_root: &Path,
1089 invocation: &str,
1090 cancellation: &BuildCancellation,
1091) -> Result<BuildAttempt, BuildError> {
1092 if !plan.targets.iter().any(|planned| planned == target)
1093 || plan.schema_version != 1
1094 || plan.release_id.is_empty()
1095 || plan.source_revision.is_empty()
1096 {
1097 return Err(build_err(
1098 "target is not part of the supplied ReleasePlan identity",
1099 ));
1100 }
1101 if !repository_root.is_absolute() {
1102 return Err(build_err("repository root must be absolute"));
1103 }
1104 let repository =
1105 fs::canonicalize(repository_root).map_err(|_| build_err("repository root unavailable"))?;
1106 preflight(target, &repository, cancellation)?;
1107 let target_dir = private_target_dir(work_root, invocation, &target.target)?;
1108 fs::create_dir(&target_dir)
1109 .map_err(|_| build_err("private Cargo target directory creation failed"))?;
1110 let mut candidates = Vec::new();
1111 let mut last = ProcessEvidence {
1112 outcome: CommandOutcome::Success,
1113 stdout_bytes: 0,
1114 stderr_bytes: 0,
1115 };
1116 for binding in bindings {
1117 let spec = cargo_command(
1118 target,
1119 binding,
1120 &repository,
1121 &target_dir,
1122 Duration::from_secs(1800),
1123 )?;
1124 let evidence = run_bounded_cancellable(&spec, cancellation)?;
1125 if evidence.outcome != CommandOutcome::Success {
1126 return Ok(BuildAttempt {
1127 release_id: plan.release_id.clone(),
1128 source_revision: plan.source_revision.clone(),
1129 target: target.target.clone(),
1130 strategy: target.policy.strategy,
1131 tool_summary: format!("rust {}", target.policy.toolchain.rust),
1132 process: evidence,
1133 candidates: Vec::new(),
1134 });
1135 }
1136 let (path, size) = discover_candidate(&target_dir, &target.target, &binding.binary)?;
1137 candidates.push(CandidateArtifact {
1138 target: target.target.clone(),
1139 selector: binding.selector.clone(),
1140 package: binding.package.clone(),
1141 binary: binding.binary.clone(),
1142 path,
1143 size,
1144 });
1145 last = evidence;
1146 }
1147 if candidates.is_empty() {
1148 return Err(build_err("build produced no candidates"));
1152 }
1153 Ok(BuildAttempt {
1154 release_id: plan.release_id.clone(),
1155 source_revision: plan.source_revision.clone(),
1156 target: target.target.clone(),
1157 strategy: target.policy.strategy,
1158 tool_summary: format!(
1159 "rust {}{}{}",
1160 target.policy.toolchain.rust,
1161 target
1162 .policy
1163 .toolchain
1164 .cargo_zigbuild
1165 .as_ref()
1166 .map(|v| format!(" cargo-zigbuild {v}"))
1167 .unwrap_or_default(),
1168 target
1169 .policy
1170 .toolchain
1171 .zig
1172 .as_ref()
1173 .map(|v| format!(" zig {v}"))
1174 .unwrap_or_default()
1175 ),
1176 process: last,
1177 candidates,
1178 })
1179}
1180
1181pub fn private_target_dir(
1183 work_root: &Path,
1184 invocation: &str,
1185 target: &str,
1186) -> Result<PathBuf, BuildError> {
1187 if !work_root.is_absolute()
1188 || invocation.is_empty()
1189 || invocation.len() > 128
1190 || target.is_empty()
1191 {
1192 return Err(build_err("invalid private work root identity"));
1193 }
1194 if fs::symlink_metadata(work_root)
1195 .map_err(|_| build_err("work root must pre-exist"))?
1196 .file_type()
1197 .is_symlink()
1198 {
1199 return Err(build_err("symlink work root rejected"));
1200 }
1201 let canonical =
1202 fs::canonicalize(work_root).map_err(|_| build_err("work root canonicalization failed"))?;
1203 let name = format!("{}-{}", safe_component(invocation), safe_component(target));
1204 let path = canonical.join(name);
1205 match fs::create_dir(&path) {
1206 Ok(()) => (),
1207 Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
1208 return Err(build_err("private build directory already exists"))
1209 }
1210 Err(_) => return Err(build_err("private build directory creation failed")),
1211 }
1212 let check = fs::canonicalize(&path)
1213 .map_err(|_| build_err("private build path canonicalization failed"))?;
1214 if !check.starts_with(&canonical) {
1215 return Err(build_err("private build path escapes work root"));
1216 }
1217 let mut metadata = fs::File::create(path.join(".eggpack-owner"))
1218 .map_err(|_| build_err("ownership marker creation failed"))?;
1219 metadata
1220 .write_all(format!("1\n{}\n{}\n", invocation, target).as_bytes())
1221 .map_err(|_| build_err("ownership marker write failed"))?;
1222 Ok(path.join("target"))
1223}
1224fn safe_component(s: &str) -> String {
1225 s.chars()
1226 .map(|c| {
1227 if c.is_ascii_alphanumeric() || c == '-' || c == '_' {
1228 c
1229 } else {
1230 '_'
1231 }
1232 })
1233 .collect()
1234}
1235
1236pub fn discover_candidate(
1238 target_dir: &Path,
1239 target: &str,
1240 binary: &str,
1241) -> Result<(PathBuf, u64), BuildError> {
1242 if !valid_identifier(binary) {
1243 return Err(build_err("invalid binary name"));
1244 }
1245 let mut path = target_dir.join(target).join("release").join(binary);
1246 if target.contains("-windows-") {
1247 path.set_file_name(format!("{binary}.exe"));
1250 }
1251 let metadata =
1252 fs::symlink_metadata(&path).map_err(|_| build_err("expected candidate missing"))?;
1253 if metadata.file_type().is_symlink() || !metadata.file_type().is_file() || metadata.len() == 0 {
1254 return Err(build_err("candidate is not a non-empty regular file"));
1255 }
1256 let canonical_root =
1257 fs::canonicalize(target_dir).map_err(|_| build_err("target directory unavailable"))?;
1258 let canonical_file =
1259 fs::canonicalize(&path).map_err(|_| build_err("candidate canonicalization failed"))?;
1260 if !canonical_file.starts_with(&canonical_root) {
1261 return Err(build_err("candidate escapes private target directory"));
1262 }
1263 let release_dir = target_dir.join(target).join("release");
1264 let target_meta = fs::symlink_metadata(target_dir.join(target))
1265 .map_err(|_| build_err("target output directory missing"))?;
1266 let release_meta = fs::symlink_metadata(&release_dir)
1267 .map_err(|_| build_err("release output directory missing"))?;
1268 if target_meta.file_type().is_symlink()
1269 || !target_meta.is_dir()
1270 || release_meta.file_type().is_symlink()
1271 || !release_meta.is_dir()
1272 {
1273 return Err(build_err(
1274 "candidate parent directory is not private regular directory",
1275 ));
1276 }
1277 Ok((path, metadata.len()))
1278}
1279
1280#[cfg(test)]
1281mod tests {
1282 use super::*;
1283 use crate::{HostArch, HostOs, Qualification, SupportTier, TargetPolicy, ToolchainRequirement};
1284 use std::sync::Mutex;
1285
1286 static CARGO_FIXTURE_LOCK: Mutex<()> = Mutex::new(());
1287
1288 fn target() -> crate::PlannedTarget {
1289 crate::PlannedTarget {
1290 target: "x86_64-unknown-linux-gnu".into(),
1291 policy: TargetPolicy {
1292 target: "x86_64-unknown-linux-gnu".into(),
1293 strategy: BuildStrategy::NativeCargo,
1294 host_os: HostOs::Linux,
1295 host_arch: HostArch::X86_64,
1296 qualification_host: None,
1297 toolchain: ToolchainRequirement {
1298 rust: "1.89.0".into(),
1299 cargo_zigbuild: None,
1300 zig: None,
1301 },
1302 floor: CompatibilityFloor::None,
1303 qualification: Qualification::Native,
1304 support: SupportTier::Required,
1305 },
1306 artifact_form: crate::PlannedAssetForm::Direct,
1307 floor_status: crate::FloorVerificationStatus::NotDeclared,
1308 }
1309 }
1310 #[test]
1311 fn command_is_explicit_and_never_shell_based() {
1312 let b = BuildBinding {
1313 selector: LogicalOutputSelector::Direct,
1314 package: "demo".into(),
1315 binary: "demo-bin".into(),
1316 };
1317 let c = cargo_command(
1318 &target(),
1319 &b,
1320 Path::new("/repo"),
1321 Path::new("/private/target"),
1322 Duration::from_secs(10),
1323 )
1324 .unwrap();
1325 assert_eq!(c.executable, "cargo");
1326 assert_eq!(
1327 c.args,
1328 [
1329 "+1.89.0",
1330 "build",
1331 "--release",
1332 "--locked",
1333 "--target",
1334 "x86_64-unknown-linux-gnu",
1335 "--package",
1336 "demo",
1337 "--bin",
1338 "demo-bin"
1339 ]
1340 );
1341 assert_eq!(c.env["CARGO_TARGET_DIR"], "/private/target");
1342 let mut arbitrary = c;
1343 arbitrary.executable = "sh".into();
1344 assert!(
1345 run_bounded_inner(&arbitrary, Cancellation::None, ExecutableAllowance::Builder)
1346 .is_err()
1347 );
1348 }
1349 #[test]
1350 fn zigbuild_floor_uses_only_gnu_target_syntax() {
1351 let mut t = target();
1352 t.policy.strategy = BuildStrategy::CargoZigbuild;
1353 t.policy.toolchain.cargo_zigbuild = Some("0.19.8".into());
1354 t.policy.toolchain.zig = Some("0.14.1".into());
1355 t.policy.floor = CompatibilityFloor::Glibc {
1356 major: 2,
1357 minor: 17,
1358 };
1359 let binding = BuildBinding {
1360 selector: LogicalOutputSelector::Direct,
1361 package: "demo".into(),
1362 binary: "demo".into(),
1363 };
1364 let command = cargo_command(
1365 &t,
1366 &binding,
1367 Path::new("/repo"),
1368 Path::new("/target"),
1369 Duration::from_secs(10),
1370 )
1371 .unwrap();
1372 assert_eq!(command.args[1], "zigbuild");
1373 assert_eq!(command.args[5], "x86_64-unknown-linux-gnu.2.17");
1374 t.policy.floor = CompatibilityFloor::Macos {
1375 major: 13,
1376 minor: 0,
1377 };
1378 assert!(cargo_command(
1379 &t,
1380 &binding,
1381 Path::new("/repo"),
1382 Path::new("/target"),
1383 Duration::from_secs(10)
1384 )
1385 .is_err());
1386 }
1387 #[test]
1393 fn the_cargo_zigbuild_floor_rewrite_and_macos_refusal_are_unchanged() {
1394 let mut t = target();
1395 t.policy.strategy = BuildStrategy::CargoZigbuild;
1396 t.policy.toolchain.cargo_zigbuild = Some("0.23.3".into());
1397 t.policy.toolchain.zig = Some("0.14.1".into());
1398 t.policy.floor = CompatibilityFloor::Glibc {
1399 major: 2,
1400 minor: 17,
1401 };
1402 let binding = BuildBinding {
1403 selector: LogicalOutputSelector::Direct,
1404 package: "demo".into(),
1405 binary: "demo".into(),
1406 };
1407 let command = cargo_command(
1408 &t,
1409 &binding,
1410 Path::new("/repo"),
1411 Path::new("/target"),
1412 Duration::from_secs(10),
1413 )
1414 .unwrap();
1415 assert_eq!(
1416 command.args,
1417 vec![
1418 "+1.89.0",
1419 "zigbuild",
1420 "--release",
1421 "--locked",
1422 "--target",
1423 "x86_64-unknown-linux-gnu.2.17",
1424 "--package",
1425 "demo",
1426 "--bin",
1427 "demo",
1428 ]
1429 );
1430 t.policy.floor = CompatibilityFloor::Macos {
1433 major: 13,
1434 minor: 0,
1435 };
1436 let refusal = cargo_command(
1437 &t,
1438 &binding,
1439 Path::new("/repo"),
1440 Path::new("/target"),
1441 Duration::from_secs(10),
1442 )
1443 .unwrap_err();
1444 assert_eq!(refusal.to_string(), "macOS floor cannot use cargo-zigbuild");
1445 assert_eq!(
1448 t.policy.floor,
1449 CompatibilityFloor::Macos {
1450 major: 13,
1451 minor: 0
1452 }
1453 );
1454 }
1455 #[test]
1456 fn binding_document_rejects_duplicate_and_unknown_fields() {
1457 let good = r#"schema_version = 1
1458[targets]
1459"x86_64-unknown-linux-gnu" = [{ selector = { kind = "direct" }, package = "demo", binary = "demo" }]
1460"#;
1461 assert!(BuildBindingsV1::from_toml(good).is_ok());
1462 assert!(BuildBindingsV1::from_toml(
1463 &good.replace("schema_version = 1", "schema_version = 2")
1464 )
1465 .is_err());
1466 assert!(
1467 BuildBindingsV1::from_toml(&good.replace("package =", "extra = 1, package =")).is_err()
1468 );
1469 }
1470 #[test]
1471 fn bindings_must_match_direct_contract_slots_exactly() {
1472 let contract = DistributionContract::parse_toml_str(include_str!(
1473 "../../eggpack-contract/tests/fixtures/simple-direct.toml"
1474 ))
1475 .unwrap();
1476 let plan = crate::PackConfig {
1477 schema_version: 1,
1478 targets: vec![target().policy],
1479 }
1480 .resolve(&contract, "1.0", "abc", &["linux-x64".into()])
1481 .unwrap();
1482 let bindings = BuildBindingsV1 {
1483 schema_version: 1,
1484 targets: [(
1485 "x86_64-unknown-linux-gnu".into(),
1486 vec![BuildBinding {
1487 selector: LogicalOutputSelector::Direct,
1488 package: "demo".into(),
1489 binary: "demo".into(),
1490 }],
1491 )]
1492 .into_iter()
1493 .collect(),
1494 };
1495 assert!(bindings.validate_for(&contract, &plan).is_ok());
1496 let mut invalid = bindings;
1497 invalid.targets.get_mut("x86_64-unknown-linux-gnu").unwrap()[0].selector =
1498 LogicalOutputSelector::BundleEntry { index: 0 };
1499 assert!(invalid.validate_for(&contract, &plan).is_err());
1500 }
1501 #[test]
1502 fn candidate_lookup_is_exact_regular_and_nonempty() {
1503 let root = crate::test_temp_dir("builder-test");
1504 let out = root.join("x86_64-unknown-linux-gnu/release");
1505 fs::create_dir_all(&out).unwrap();
1506 fs::write(out.join("demo"), b"binary").unwrap();
1507 assert_eq!(
1508 discover_candidate(&root, "x86_64-unknown-linux-gnu", "demo")
1509 .unwrap()
1510 .1,
1511 6
1512 );
1513 fs::write(out.join("empty"), b"").unwrap();
1514 assert!(discover_candidate(&root, "x86_64-unknown-linux-gnu", "empty").is_err());
1515 assert!(discover_candidate(&root, "x86_64-unknown-linux-gnu", "other").is_err());
1516 fs::remove_dir_all(root).unwrap();
1517 }
1518 #[test]
1519 fn windows_candidate_appends_exe_and_preserves_dotted_names() {
1520 let root = crate::test_temp_dir("builder-exe-test");
1521 let target = "x86_64-pc-windows-msvc";
1522 let out = root.join(target).join("release");
1523 fs::create_dir_all(&out).unwrap();
1524 fs::write(out.join("demo.exe"), b"binary").unwrap();
1525 assert_eq!(discover_candidate(&root, target, "demo").unwrap().1, 6);
1526 fs::write(out.join("tool.cli.exe"), b"dotted").unwrap();
1527 let (path, size) = discover_candidate(&root, target, "tool.cli").unwrap();
1530 assert!(path.ends_with("tool.cli.exe"), "{path:?}");
1531 assert_eq!(size, 6);
1532 fs::remove_dir_all(root).unwrap();
1533
1534 let root = crate::test_temp_dir("builder-exe-test-2");
1537 let out = root.join(target).join("release");
1538 fs::create_dir_all(&out).unwrap();
1539 fs::write(out.join("tool.exe"), b"truncated").unwrap();
1540 assert!(discover_candidate(&root, target, "tool.cli").is_err());
1541 fs::remove_dir_all(root).unwrap();
1542 }
1543 #[test]
1544 fn windows_candidate_matching_is_not_a_substring_heuristic() {
1545 let root = crate::test_temp_dir("builder-triple-test");
1546 let target = "x86_64-unknown-notwindowsish";
1547 let out = root.join(target).join("release");
1548 fs::create_dir_all(&out).unwrap();
1549 fs::write(out.join("demo"), b"binary").unwrap();
1550 assert!(discover_candidate(&root, target, "demo").is_ok());
1551 fs::remove_dir_all(root).unwrap();
1552 }
1553 #[test]
1554 fn git_verification_is_bounded_and_exact() {
1555 let root = crate::test_temp_dir("builder-git-test");
1556 let git = |args: &[&str]| {
1557 Command::new("git")
1558 .args(args)
1559 .current_dir(&root)
1560 .env("GIT_AUTHOR_NAME", "t")
1561 .env("GIT_AUTHOR_EMAIL", "t@example.invalid")
1562 .env("GIT_COMMITTER_NAME", "t")
1563 .env("GIT_COMMITTER_EMAIL", "t@example.invalid")
1564 .output()
1565 };
1566 if !git(&["init", "--quiet"]).is_ok_and(|o| o.status.success()) {
1567 fs::remove_dir_all(root).unwrap();
1568 return; }
1570 fs::write(root.join("f"), b"x").unwrap();
1571 if !git(&["add", "f"]).is_ok_and(|o| o.status.success())
1572 || !git(&["commit", "--quiet", "-m", "c"]).is_ok_and(|o| o.status.success())
1573 {
1574 fs::remove_dir_all(root).unwrap();
1575 return;
1576 }
1577 let head = String::from_utf8(git(&["rev-parse", "HEAD"]).unwrap().stdout)
1578 .unwrap()
1579 .trim()
1580 .to_owned();
1581 assert_eq!(head.len(), 40);
1582 assert!(git(&["tag", "v1.2.3"]).is_ok_and(|o| o.status.success()));
1583 assert_eq!(
1584 run_git_tag_bounded("v1.2.3", &head, Some(&root))
1585 .unwrap()
1586 .outcome,
1587 CommandOutcome::Success
1588 );
1589 assert_ne!(
1590 run_git_tag_bounded("v1.2.4", &head, Some(&root))
1591 .unwrap()
1592 .outcome,
1593 CommandOutcome::Success
1594 );
1595 assert!(run_git_tag_bounded("v../evil", &head, Some(&root)).is_err());
1596 assert!(run_git_tag_bounded("v1.2.3^{}", &head, Some(&root)).is_err());
1597 fs::write(root.join("f"), b"second commit").unwrap();
1598 assert!(git(&["add", "f"]).is_ok_and(|o| o.status.success()));
1599 assert!(git(&["commit", "--quiet", "-m", "second"]).is_ok_and(|o| o.status.success()));
1600 assert!(git(&["tag", "v1.2.9"]).is_ok_and(|o| o.status.success()));
1601 let second_head = String::from_utf8(git(&["rev-parse", "HEAD"]).unwrap().stdout)
1602 .unwrap()
1603 .trim()
1604 .to_owned();
1605 assert_ne!(
1606 run_git_tag_bounded("v1.2.9", &head, Some(&root))
1607 .unwrap()
1608 .outcome,
1609 CommandOutcome::Success,
1610 "another tag pointing at a different commit must fail"
1611 );
1612 assert_eq!(
1613 run_git_bounded(&second_head, Some(&root)).unwrap().outcome,
1614 CommandOutcome::Success
1615 );
1616 let noisy = format!(" {second_head} ");
1618 assert_ne!(
1619 run_git_bounded(&noisy, Some(&root)).unwrap().outcome,
1620 CommandOutcome::Success
1621 );
1622 assert_ne!(
1623 run_git_bounded(&second_head[..39], Some(&root))
1624 .unwrap()
1625 .outcome,
1626 CommandOutcome::Success
1627 );
1628 assert_ne!(
1629 run_git_bounded(&"0".repeat(40), Some(&root))
1630 .unwrap()
1631 .outcome,
1632 CommandOutcome::Success
1633 );
1634 let outside = crate::test_temp_dir("builder-git-outside");
1636 assert_ne!(
1637 run_git_bounded(&second_head, Some(&outside))
1638 .unwrap()
1639 .outcome,
1640 CommandOutcome::Success
1641 );
1642 fs::remove_dir_all(outside).unwrap();
1643 fs::remove_dir_all(root).unwrap();
1644 }
1645 #[test]
1646 fn private_workspace_rejects_relative_and_reused_invocations() {
1647 let root = crate::test_temp_dir("private-test");
1648 assert!(private_target_dir(Path::new("relative"), "run", "target").is_err());
1649 assert!(private_target_dir(&root, "run", "target").is_ok());
1650 assert!(private_target_dir(&root, "run", "target").is_err());
1651 fs::remove_dir_all(root).unwrap();
1652 }
1653 #[test]
1654 fn process_output_is_bounded_and_exit_status_explicit() {
1655 let spec = CommandSpec {
1656 executable: "rustc".into(),
1657 args: vec!["--version".into()],
1658 cwd: std::env::current_dir().unwrap(),
1659 env: BTreeMap::new(),
1660 timeout: Duration::from_secs(5),
1661 stdout_limit: 1024,
1662 stderr_limit: 1024,
1663 expected_stdout: None,
1664 expected_stdout_exact: None,
1665 };
1666 let result =
1667 run_bounded_inner(&spec, Cancellation::None, ExecutableAllowance::Builder).unwrap();
1668 assert_eq!(result.outcome, CommandOutcome::Success);
1669 assert!(result.stdout_bytes <= 1024);
1670 }
1671 #[cfg(unix)]
1683 #[test]
1684 fn terminating_an_already_exited_process_group_is_not_a_failure() {
1685 let mut command = Command::new("sh");
1686 command.args(["-c", "exit 0"]);
1687 let mut child = command.group_spawn().unwrap();
1688 child.wait().unwrap();
1690 assert!(child.kill().is_err());
1692 assert!(terminate_process_group(&mut child, "test termination").is_ok());
1694 }
1695 #[cfg(unix)]
1696 #[test]
1697 fn a_failed_group_signal_is_benign_only_after_recheck_proves_termination() {
1698 let no_such_group = std::io::Error::from_raw_os_error(libc::ESRCH);
1699 let not_permitted = std::io::Error::from_raw_os_error(libc::EPERM);
1700
1701 assert!(group_signal_failure_is_benign(
1702 &no_such_group,
1703 false,
1704 || { panic!("ESRCH must not trigger a retry") }
1705 ));
1706 assert!(!group_signal_failure_is_benign(
1707 ¬_permitted,
1708 false,
1709 || { panic!("a live or unverified child must not trigger a retry") }
1710 ));
1711 assert!(group_signal_failure_is_benign(¬_permitted, true, || Ok(
1712 ()
1713 )));
1714 assert!(group_signal_failure_is_benign(¬_permitted, true, || {
1715 Err(std::io::Error::from_raw_os_error(libc::ESRCH))
1716 }));
1717 assert!(!group_signal_failure_is_benign(
1718 ¬_permitted,
1719 true,
1720 || { Err(std::io::Error::from_raw_os_error(libc::EPERM)) }
1721 ));
1722 }
1723 #[cfg(unix)]
1724 #[test]
1725 fn terminating_an_exited_leader_still_signals_a_live_group_descendant() {
1726 let root = crate::test_temp_dir("group-descendant-termination");
1727 let started = root.join("descendant-started");
1728 let release = root.join("descendant-release");
1729 let survived = root.join("descendant-survived");
1730 let started_arg = started.to_string_lossy().into_owned();
1731 let release_arg = release.to_string_lossy().into_owned();
1732 let survived_arg = survived.to_string_lossy().into_owned();
1733 let mut command = Command::new("sh");
1734 command.args([
1735 "-c",
1736 "sh -c 'printf started > \"$1\"; while [ ! -e \"$2\" ]; do sleep 0.01; done; printf survived > \"$3\"' sh \"$1\" \"$2\" \"$3\" >/dev/null 2>&1 & while [ ! -e \"$1\" ]; do sleep 0.01; done; exit 0",
1737 "group-fixture",
1738 started_arg.as_str(),
1739 release_arg.as_str(),
1740 survived_arg.as_str(),
1741 ]);
1742 let mut child = command.group_spawn().unwrap();
1743
1744 let leader_deadline = Instant::now() + Duration::from_secs(3);
1745 let leader_status = loop {
1746 match child.try_wait() {
1747 Ok(Some(status)) => break Some(status),
1748 Ok(None) if Instant::now() < leader_deadline => {
1749 thread::sleep(Duration::from_millis(10));
1750 }
1751 _ => break None,
1752 }
1753 };
1754 let descendant_deadline = Instant::now() + Duration::from_secs(1);
1755 while !started.is_file() && Instant::now() < descendant_deadline {
1756 thread::sleep(Duration::from_millis(10));
1757 }
1758
1759 let terminated = terminate_process_group(&mut child, "test termination").is_ok();
1760 if !terminated {
1761 let _ = child.kill();
1762 }
1763 fs::write(&release, "release").unwrap();
1766 let survivor_deadline = Instant::now() + Duration::from_secs(1);
1767 while !survived.is_file() && Instant::now() < survivor_deadline {
1768 thread::sleep(Duration::from_millis(10));
1769 }
1770 let descendant_started = started.is_file();
1771 let descendant_survived = survived.exists();
1772 let leader_succeeded = leader_status.is_some_and(|status| status.success());
1773 fs::remove_dir_all(root).unwrap();
1774
1775 assert!(leader_succeeded, "the group leader must exit normally");
1776 assert!(descendant_started, "the live descendant fixture must start");
1777 assert!(terminated, "the process group must be terminated");
1778 assert!(
1779 !descendant_survived,
1780 "the descendant must not outlive group termination"
1781 );
1782 }
1783 #[test]
1784 fn nonzero_tool_exit_is_not_success() {
1785 let spec = CommandSpec {
1786 executable: "rustc".into(),
1787 args: vec!["--eggpack-invalid-option".into()],
1788 cwd: std::env::current_dir().unwrap(),
1789 env: BTreeMap::new(),
1790 timeout: Duration::from_secs(5),
1791 stdout_limit: 1024,
1792 stderr_limit: 1024,
1793 expected_stdout: None,
1794 expected_stdout_exact: None,
1795 };
1796 assert!(matches!(
1797 run_bounded_inner(&spec, Cancellation::None, ExecutableAllowance::Builder)
1798 .unwrap()
1799 .outcome,
1800 CommandOutcome::Failed(_)
1801 ));
1802 }
1803 #[test]
1804 fn stdout_overflow_is_bounded_and_not_success() {
1805 let root = crate::test_temp_dir("output-bound");
1806 let source = root.join("many-errors.rs");
1807 let body = (0..200)
1808 .map(|i| format!("fn f{i}() {{ absent_symbol_{i}(); }}\n"))
1809 .collect::<String>();
1810 fs::write(&source, body).unwrap();
1811 let spec = CommandSpec {
1812 executable: "rustc".into(),
1813 args: vec![
1814 "--crate-type".into(),
1815 "lib".into(),
1816 source.to_string_lossy().into_owned(),
1817 ],
1818 cwd: root.clone(),
1819 env: BTreeMap::new(),
1820 timeout: Duration::from_secs(10),
1821 stdout_limit: 128,
1822 stderr_limit: 128,
1823 expected_stdout: None,
1824 expected_stdout_exact: None,
1825 };
1826 assert_eq!(
1827 run_bounded_inner(&spec, Cancellation::None, ExecutableAllowance::Builder)
1828 .unwrap()
1829 .outcome,
1830 CommandOutcome::OutputLimitExceeded
1831 );
1832 fs::remove_dir_all(root).unwrap();
1833 }
1834 #[test]
1835 fn timeout_kills_and_waits_for_the_process_group() {
1836 let _cargo_guard = CARGO_FIXTURE_LOCK.lock().unwrap();
1837 let root = crate::test_temp_dir("timeout");
1838 fs::create_dir_all(root.join("src")).unwrap();
1839 fs::write(root.join("Cargo.toml"), "[package]\nname='timeout-fixture'\nversion='0.1.0'\nedition='2021'\nbuild='build.rs'\n").unwrap();
1840 fs::write(
1841 root.join("Cargo.lock"),
1842 "version = 3\n\n[[package]]\nname = \"timeout-fixture\"\nversion = \"0.1.0\"\n",
1843 )
1844 .unwrap();
1845 fs::write(
1846 root.join("build.rs"),
1847 "fn main() { println!(\"cargo:rerun-if-env-changed=EGGPACK_BUILD_STARTED\"); println!(\"cargo:rerun-if-env-changed=EGGPACK_BUILD_SLEEP\"); if let Some(path) = std::env::var_os(\"EGGPACK_BUILD_STARTED\") { std::fs::write(path, b\"started\").unwrap(); } if std::env::var_os(\"EGGPACK_BUILD_SLEEP\").is_some() { std::thread::sleep(std::time::Duration::from_secs(30)); } }\n",
1848 )
1849 .unwrap();
1850 fs::write(root.join("src/lib.rs"), "pub fn fixture() {}\n").unwrap();
1851 let mut spec = CommandSpec {
1852 executable: "cargo".into(),
1853 args: vec![
1854 "build".into(),
1855 "--locked".into(),
1856 "--offline".into(),
1857 "--manifest-path".into(),
1858 root.join("Cargo.toml").to_string_lossy().into_owned(),
1859 ],
1860 cwd: root.clone(),
1861 env: BTreeMap::new(),
1862 timeout: Duration::from_secs(60),
1863 stdout_limit: 4096,
1864 stderr_limit: 4096,
1865 expected_stdout: None,
1866 expected_stdout_exact: None,
1867 };
1868 for iteration in 0..3 {
1869 spec.timeout = Duration::from_secs(60);
1870 spec.env.remove("EGGPACK_BUILD_SLEEP");
1871 let timeout_target = root.join(format!("cargo-target-timeout-{iteration}"));
1872 spec.env.insert(
1873 "CARGO_TARGET_DIR".into(),
1874 timeout_target.to_string_lossy().into_owned(),
1875 );
1876 let warm_timeout = root.join(format!("warm-timeout-{iteration}"));
1877 spec.env.insert(
1878 "EGGPACK_BUILD_STARTED".into(),
1879 warm_timeout.to_string_lossy().into_owned(),
1880 );
1881 assert_eq!(
1882 run_bounded_inner(&spec, Cancellation::None, ExecutableAllowance::Builder)
1883 .unwrap()
1884 .outcome,
1885 CommandOutcome::Success
1886 );
1887 assert!(warm_timeout.is_file(), "timeout fixture warm-up failed");
1888 spec.timeout = Duration::from_secs(5);
1889 spec.env.insert("EGGPACK_BUILD_SLEEP".into(), "1".into());
1890 let timeout_started = root.join(format!("timeout-started-{iteration}"));
1891 spec.env.insert(
1892 "EGGPACK_BUILD_STARTED".into(),
1893 timeout_started.to_string_lossy().into_owned(),
1894 );
1895 assert_eq!(
1896 run_bounded_inner(&spec, Cancellation::None, ExecutableAllowance::Builder)
1897 .unwrap()
1898 .outcome,
1899 CommandOutcome::TimedOut
1900 );
1901 assert!(timeout_started.is_file(), "build script never started");
1902
1903 spec.timeout = Duration::from_secs(60);
1904 spec.env.remove("EGGPACK_BUILD_SLEEP");
1905 let cancel_target = root.join(format!("cargo-target-cancel-{iteration}"));
1906 spec.env.insert(
1907 "CARGO_TARGET_DIR".into(),
1908 cancel_target.to_string_lossy().into_owned(),
1909 );
1910 let warm_cancel = root.join(format!("warm-cancel-{iteration}"));
1911 spec.env.insert(
1912 "EGGPACK_BUILD_STARTED".into(),
1913 warm_cancel.to_string_lossy().into_owned(),
1914 );
1915 assert_eq!(
1916 run_bounded_inner(&spec, Cancellation::None, ExecutableAllowance::Builder)
1917 .unwrap()
1918 .outcome,
1919 CommandOutcome::Success
1920 );
1921 assert!(warm_cancel.is_file(), "cancellation fixture warm-up failed");
1922
1923 spec.timeout = Duration::from_secs(180);
1924 spec.env.insert("EGGPACK_BUILD_SLEEP".into(), "1".into());
1925 let cancellation = BuildCancellation::new();
1926 let request = cancellation.clone();
1927 let cancellation_started = root.join(format!("cancellation-started-{iteration}"));
1928 spec.env.insert(
1929 "EGGPACK_BUILD_STARTED".into(),
1930 cancellation_started.to_string_lossy().into_owned(),
1931 );
1932 let cancellation_started_by_thread = cancellation_started.clone();
1933 let canceller = thread::spawn(move || {
1934 let deadline = Instant::now() + Duration::from_secs(15);
1935 while !cancellation_started_by_thread.is_file() && Instant::now() < deadline {
1936 thread::sleep(Duration::from_millis(10));
1937 }
1938 assert!(
1939 cancellation_started_by_thread.is_file(),
1940 "build script did not start before cancellation deadline"
1941 );
1942 request.cancel();
1943 });
1944 assert_eq!(
1945 run_bounded_cancellable(&spec, &cancellation)
1946 .unwrap()
1947 .outcome,
1948 CommandOutcome::Cancelled
1949 );
1950 canceller.join().unwrap();
1951 assert!(cancellation_started.is_file());
1952 }
1953 fs::remove_dir_all(root).unwrap();
1954 }
1955 #[test]
1960 #[ignore]
1961 #[allow(clippy::zombie_processes)]
1965 fn builder_child_leaves_parked_descendant() {
1966 std::process::Command::new(std::env::current_exe().unwrap())
1967 .args([
1968 "--exact",
1969 "builder::tests::builder_child_holds_stdout",
1970 "--ignored",
1971 "--nocapture",
1972 ])
1973 .spawn()
1974 .unwrap();
1975 }
1976
1977 #[test]
1979 #[ignore]
1980 fn builder_child_holds_stdout() {
1981 std::thread::sleep(Duration::from_secs(20));
1982 }
1983
1984 #[test]
1988 fn parked_drain_reader_cannot_outlive_the_deadline() {
1989 let spec = CommandSpec {
1990 executable: std::env::current_exe()
1991 .unwrap()
1992 .to_string_lossy()
1993 .into_owned(),
1994 args: vec![
1995 "--exact".into(),
1996 "builder::tests::builder_child_leaves_parked_descendant".into(),
1997 "--ignored".into(),
1998 "--nocapture".into(),
1999 ],
2000 cwd: std::env::current_dir().unwrap(),
2001 env: BTreeMap::new(),
2002 timeout: Duration::from_secs(10),
2003 stdout_limit: 4096,
2004 stderr_limit: 4096,
2005 expected_stdout: None,
2006 expected_stdout_exact: None,
2007 };
2008 let started = Instant::now();
2009 let evidence =
2010 run_bounded_inner(&spec, Cancellation::None, ExecutableAllowance::Candidate).unwrap();
2011 assert_eq!(
2012 evidence.outcome,
2013 CommandOutcome::OutputLimitExceeded,
2014 "a parked drain reader must fail the run closed, not report success"
2015 );
2016 assert!(
2017 started.elapsed() < Duration::from_secs(15),
2018 "bounded run took {:?}; the parked reader defeated the deadline",
2019 started.elapsed()
2020 );
2021 }
2022 #[test]
2023 fn real_local_cargo_fixture_builds_a_direct_candidate() {
2024 let _cargo_guard = CARGO_FIXTURE_LOCK.lock().unwrap();
2025 let base = crate::test_temp_dir("cargo-smoke");
2026 let repo = base.join("repo");
2027 let work = base.join("work");
2028 fs::create_dir_all(repo.join("src")).unwrap();
2029 fs::create_dir_all(&work).unwrap();
2030 fs::write(
2031 repo.join("Cargo.toml"),
2032 "[package]\nname='smoke-fixture'\nversion='0.1.0'\nedition='2021'\n",
2033 )
2034 .unwrap();
2035 fs::write(
2036 repo.join("Cargo.lock"),
2037 "version = 3\n\n[[package]]\nname = \"smoke-fixture\"\nversion = \"0.1.0\"\n",
2038 )
2039 .unwrap();
2040 fs::write(repo.join("src/main.rs"), "fn main() {}\n").unwrap();
2041 let mut t = target();
2042 t.policy.toolchain.rust = "stable".into();
2043 let (triple, os, arch) = match (std::env::consts::OS, std::env::consts::ARCH) {
2044 ("windows", "x86_64") => ("x86_64-pc-windows-msvc", HostOs::Windows, HostArch::X86_64),
2045 ("macos", "x86_64") => ("x86_64-apple-darwin", HostOs::Macos, HostArch::X86_64),
2046 ("macos", "aarch64") => ("aarch64-apple-darwin", HostOs::Macos, HostArch::Aarch64),
2047 ("linux", "x86_64") => ("x86_64-unknown-linux-gnu", HostOs::Linux, HostArch::X86_64),
2048 ("linux", "aarch64") => (
2049 "aarch64-unknown-linux-gnu",
2050 HostOs::Linux,
2051 HostArch::Aarch64,
2052 ),
2053 other => panic!("unsupported hosted Cargo smoke platform: {other:?}"),
2054 };
2055 t.target = triple.into();
2056 t.policy.target = triple.into();
2057 t.policy.host_os = os;
2058 t.policy.host_arch = arch;
2059 let binding = BuildBinding {
2060 selector: LogicalOutputSelector::Direct,
2061 package: "smoke-fixture".into(),
2062 binary: "smoke-fixture".into(),
2063 };
2064 let plan = ReleasePlan {
2065 schema_version: 1,
2066 release_id: "test".into(),
2067 source_revision: "abc".into(),
2068 targets: vec![t.clone()],
2069 };
2070 let attempt = execute_target(&plan, &t, &[binding], &repo, &work, "smoke").unwrap();
2071 assert_eq!(attempt.process.outcome, CommandOutcome::Success);
2072 assert_eq!(attempt.release_id, plan.release_id);
2073 assert_eq!(attempt.source_revision, plan.source_revision);
2074 assert_eq!(attempt.candidates.len(), 1);
2075 assert!(attempt.candidates[0].size > 0);
2076 fs::remove_dir_all(base).unwrap();
2077 }
2078}