1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
use std::cell::RefCell;
#[cfg(test)]
use std::ffi::OsStr;
use std::fs;
use std::num::NonZeroU64;
use std::path::Path;
use std::path::PathBuf;
use std::ptr;
use std::rc::Rc;
use std::sync::atomic::AtomicPtr;
use std::sync::atomic::AtomicUsize;
use std::sync::atomic::Ordering;
use std::time::Duration;
use clap::Args;
use colored::Colorize;
use hermit::Backend;
use hermit::Context;
use hermit::Error;
use hermit::HermitData;
use hermit::Shebang;
use nix::sys::signal::SaFlags;
use nix::sys::signal::SigAction;
use nix::sys::signal::SigHandler;
use nix::sys::signal::SigSet;
use nix::sys::signal::Signal;
use nix::sys::signal::sigaction;
use reverie::process::Command;
use reverie::process::Container;
use reverie::process::ExitStatus;
use reverie::process::Mount;
use reverie::process::MountFlags;
use super::container::IdentityGuard;
use super::container::default_container;
use super::container::identity_hardening_mounts;
use super::gdb_client::CLIENT_EXITED_BEFORE_CONNECTING;
use super::gdb_client::GdbClientWatch;
use super::global_opts::GlobalOpts;
use super::record_envelope::RecordEnvelope;
use super::run::BaseEnv;
use super::run::NetworkingMode;
use super::run::apply_base_environment;
use super::run::is_elf_file;
use super::run::parse_assignment;
use super::run::path_resolution_visits_prefix;
use super::verify::ComparedRun;
use super::verify::ComparisonOptions;
use super::verify::LogCompareStrictness;
use super::verify::SecondRun;
use super::verify::announce_verification_outcome;
use super::verify::compare_two_runs;
use super::verify::emit_compared_guest_output;
use super::verify::setup_double_run;
use super::verify::validate_log_level;
use super::verify::write_pending_verification_json;
use super::verify::write_verification_json;
#[derive(Debug)]
struct E9patchRecordOverlay {
source: PathBuf,
target: PathBuf,
}
static TIMEOUT_MESSAGE: AtomicPtr<u8> = AtomicPtr::new(ptr::null_mut());
static TIMEOUT_MESSAGE_LEN: AtomicUsize = AtomicUsize::new(0);
extern "C" fn recording_timeout_handler(_signal: libc::c_int) {
let len = TIMEOUT_MESSAGE_LEN.load(Ordering::Acquire);
let message = TIMEOUT_MESSAGE.load(Ordering::Acquire);
if !message.is_null() && len != 0 {
// SAFETY: `message` is leaked before the timer is armed, and fcntl(2),
// write(2), and _exit(2) are all async-signal-safe.
unsafe {
// Make stderr non-blocking before writing. If stderr is a pipe or
// socket whose buffer is full, a blocking write(2) would wedge the
// handler and never reach _exit, defeating the deadline. A dropped
// diagnostic is acceptable; a hung timeout is not.
let flags = libc::fcntl(libc::STDERR_FILENO, libc::F_GETFL);
if flags != -1 {
libc::fcntl(libc::STDERR_FILENO, libc::F_SETFL, flags | libc::O_NONBLOCK);
}
libc::write(libc::STDERR_FILENO, message.cast(), len);
}
}
// Exiting PID 1 tears down the isolated recording namespace and its tracees.
// SAFETY: _exit(2) is async-signal-safe and does not run Rust destructors.
unsafe { libc::_exit(124) }
}
struct RecordingDeadline {
previous_handler: SigAction,
// Whether SIGALRM was blocked in the inherited mask and must be re-blocked
// when the deadline is disarmed.
reblock_sigalrm: bool,
}
fn sigalrm_set() -> SigSet {
let mut set = SigSet::empty();
set.add(Signal::SIGALRM);
set
}
impl RecordingDeadline {
fn arm(timeout: Duration) -> Result<Self, Error> {
let seconds: libc::c_uint = timeout
.as_secs()
.try_into()
.map_err(|_| Error::msg("record timeout exceeds the platform alarm limit"))?;
let message = Box::leak(
format!(
"Error: Recording timed out after {} seconds; the recording container was terminated\n",
timeout.as_secs()
)
.into_boxed_str(),
);
TIMEOUT_MESSAGE.store(message.as_mut_ptr(), Ordering::Release);
TIMEOUT_MESSAGE_LEN.store(message.len(), Ordering::Release);
let action = SigAction::new(
SigHandler::Handler(recording_timeout_handler),
SaFlags::SA_RESETHAND,
SigSet::empty(),
);
// SAFETY: the handler uses only async-signal-safe operations and remains
// installed until this guard disarms the alarm.
let previous_handler = unsafe { sigaction(Signal::SIGALRM, &action) }?;
// A signal mask inherited from our parent may have SIGALRM blocked. If
// it is, the alarm signal stays perpetually pending and the handler
// never runs, silently disabling the deadline. Unblock SIGALRM so the
// alarm is deliverable, and remember to restore the original state.
let reblock_sigalrm = SigSet::thread_get_mask()
.map(|mask| mask.contains(Signal::SIGALRM))
.unwrap_or(false);
if reblock_sigalrm {
let _ = sigalrm_set().thread_unblock();
}
// SAFETY: the timeout is nonzero and fits c_uint.
unsafe { libc::alarm(seconds) };
Ok(Self {
previous_handler,
reblock_sigalrm,
})
}
}
impl Drop for RecordingDeadline {
fn drop(&mut self) {
// SAFETY: disarm the process-local alarm before restoring its handler.
unsafe {
libc::alarm(0);
let _ = sigaction(Signal::SIGALRM, &self.previous_handler);
}
// Restore SIGALRM to its inherited blocked state without disturbing the
// rest of the mask.
if self.reblock_sigalrm {
let _ = sigalrm_set().thread_block();
}
TIMEOUT_MESSAGE_LEN.store(0, Ordering::Release);
TIMEOUT_MESSAGE.store(ptr::null_mut(), Ordering::Release);
}
}
fn with_recording_deadline<T>(
timeout: Duration,
record: impl FnOnce() -> Result<T, Error>,
) -> Result<T, Error> {
let _deadline = RecordingDeadline::arm(timeout)?;
record()
}
#[derive(Debug, Args, Clone)]
pub struct StartOpts {
/// Program to run.
#[clap(value_name = "PROGRAM", required = true)]
program: Option<PathBuf>,
/// Accepted and ignored, for command-line compatibility with `hermit run --strict`.
/// Recording does NOT run under `run --strict`'s configuration: see
/// `hermit_cli::metadata::record_or_replay_config`, which deliberately sets
/// `virtualize_time: false`, `deterministic_io: false`, `passthru_opt: true` and
/// `panic_on_unsupported_syscalls: true`. A recorded guest therefore reads the REAL
/// host clock, and two independent recordings of the same program observe different
/// times. What `--verify` establishes is that a recording REPLAYS faithfully, not that
/// two independent recordings agree.
#[clap(long = "strict")]
_strict: bool,
/// Arguments for the program.
#[clap(value_name = "ARGS")]
args: Vec<String>,
/// Additionally append one or more environment variables to the recorded
/// guest environment. If a name is provided without a value, pass that
/// variable through from the host.
#[clap(short = 'e', long, value_parser = parse_assignment, value_name = "name[=val]")]
env: Vec<(String, Option<String>)>,
/// The base environment presented to the recorded guest. This uses the
/// same contract as `hermit run`; record and replay must not diverge merely
/// because the manifest selected a different front door.
#[clap(long, default_value = "host", value_name = "str")]
base_env: BaseEnv,
/// Mount a file, directory, or fresh filesystem for recording and an immediate verify replay.
#[clap(long)]
mount: Vec<Mount>,
/// Select guest networking, with the same contract as `hermit run --network`. `local`
/// (the default) gives the recording and its verify replay an isolated loopback
/// interface; `host` exposes the host network to the recording. The choice is
/// stored in the recording, and `hermit replay --autopilot` replays in the same
/// network. `--verify-with-gdbex` defaults to, and requires, `host`: its replay's
/// gdbserver must be reachable from the gdb client outside the container.
#[clap(long, alias = "net", value_name = "local|host")]
network: Option<NetworkingMode>,
/// Set the working directory for both recording and replay after mounts apply.
#[clap(long, value_name = "path")]
workdir: Option<String>,
/// Directory where recorded syscall data is stored.
#[clap(long, value_name = "DIR", env = "HERMIT_DATA_DIR")]
data_dir: Option<PathBuf>,
/// Kill the recording if the guest does not finish within this many seconds.
#[clap(long, value_name = "SECONDS")]
record_timeout: Option<NonZeroU64>,
/// After recording, immediately replays the command to verify that it works.
/// This is useful for testing purposes where we often want to verify that
/// recording was successful.
///
/// The recording is deleted if the replay was successful.
#[clap(long)]
verify: bool,
/// With --verify, write the verification verdict as a single JSON line to
/// this path: `{"verified":bool,"bitwise_parity":bool,
/// "verdict":"matched"|"diverged","comparison":{"strictness":
/// "stripped"|"canonical","display_name":str,"compare_logs":bool,
/// "compare_io_buffers":bool,
/// "log_scope":
/// "deterministic"|"info"|"full_trace","record_envelope":
/// "all_records_v1","strip_lines":bool,
/// "canonicalize_addresses":bool,"full_trace":bool,"exact_remainder":bool,
/// "stripped_prefixes":[str],"canonicalizations":[str],"ignore_lines":bool,
/// "skip_commit":bool,"skip_detlog":bool},"dbt_counted_branches":
/// {"left":int,"right":int},"guest_exit_code":int|null,
/// "guest_signal":int|null,"first_divergent_scheduler_turn":int|null,
/// "first_divergent_virtual_nanoseconds":int|null,
/// "first_divergent_record":int|null,"first_divergent_syscall":int|null}`.
/// `dbt_counted_branches` is present only when DBT completed a typed
/// whole-process comparison; it is omitted for other backends and no-result.
/// ALL FOUR divergence coordinates are emitted, and they are four
/// DIFFERENT KEYSPACES that must never be compared across axes: one real
/// divergence was record 7495, syscall 1074, scheduler turn 196 -- three
/// numbers for one event. A consumer that reads a subset silently drops
/// located evidence. This is the
/// exit-code-independent verdict
/// channel: `verified` reflects whether the record and replay runs matched,
/// regardless of what the guest exited with, so a caller need not (and must
/// not) infer the verdict from the process exit code. A record/replay parity
/// ratchet must key on `bitwise_parity`, NOT `verified`: `bitwise_parity` is
/// true only under the `canonical` (`BitwiseInfoV1`) policy — a full-INFO
/// comparison inside a named canonical record envelope that strips only the
/// real wall-clock prefix, canonicalizes host addresses to first-appearance
/// ordinals, includes syscall output-buffer hashes, and compares everything
/// else exactly (see --verify-strict) — rather than a stripped, content-blind,
/// or opaque filtered match.
#[clap(long, requires = "verify", value_name = "PATH")]
verify_json: Option<PathBuf>,
/// With --verify, compare the record and replay logs under the CANONICAL
/// parity policy: strip only the real wall-clock timestamp prefix, canonicalize
/// host memory addresses to first-appearance ordinals (tolerating an ASLR
/// shift while still diverging on allocation-order or aliasing changes), and
/// compare every INFO message's remaining bytes — virtual-time timestamps,
/// raw syscall argument/result values, counts, sizes, flags — exactly. An
/// explicit DEBUG/TRACE level remains captured for diagnostics but does not
/// change the INFO verdict. Without this the
/// default `--verify` normalizes away numbers, addresses, tmp paths, and
/// timestamps before comparing, so a "verified" result asserts only stripped
/// parity, not bitwise identity. A record/replay determinism ratchet keying on
/// the verdict should set this so it cannot be silently weakened to a stripped
/// comparison.
#[clap(long, requires = "verify")]
verify_strict: bool,
/// After recording, immediately replays the command to verify that it works
/// With provided gdb command (passed by `-ex`).
/// This is useful for testing purposes where we often want to verify that
/// recording was successful with gdbserver enabled.
///
/// The recording is deleted if the replay was successful.
#[clap(long = "verify-with-gdbex", value_delimiter = ';')]
gdbex: Vec<String>,
}
impl StartOpts {
fn program(&self) -> &PathBuf {
self.program
.as_ref()
.expect("Clap requires PROGRAM unless a record management subcommand is selected")
}
fn record_timeout(&self) -> Option<Duration> {
self.record_timeout
.map(|seconds| Duration::from_secs(seconds.get()))
}
fn guest_command(&self) -> Result<Command, Error> {
let mut command = Command::new(self.program());
command.args(&self.args);
if let Some(workdir) = &self.workdir {
command.current_dir(workdir);
}
apply_base_environment(&mut command, &self.base_env, &self.env)?;
Ok(command)
}
// AUTONOMOUS-BOT-IMPLEMENTED
// TODO-HUMAN-REVIEW(PR-696): Review /proc magic-link rejection for record overlays.
fn resolve_e9patch_record_target(&self) -> Result<PathBuf, Error> {
let command = Command::new(self.program());
let resolved = command.find_program().with_context(|| {
format!(
"Could not resolve program {:?} in PATH for e9patch preprocessing",
self.program()
)
})?;
if path_resolution_visits_prefix(&resolved, Path::new("/proc"))? {
anyhow::bail!(
"e9patch cannot safely overlay executable {} because its path resolves through \
/proc; use the executable's stable filesystem path",
self.program().display()
);
}
fs::canonicalize(&resolved).with_context(|| {
format!(
"failed to resolve e9patch executable {}",
resolved.display()
)
})
}
// AUTONOMOUS-BOT-IMPLEMENTED
// TODO-HUMAN-REVIEW(PR-696): Review e9patch record preparation and executable overlaying.
fn prepare_e9patch_overlay(
&self,
global: &GlobalOpts,
) -> Result<Option<E9patchRecordOverlay>, Error> {
if global.backend != Some(Backend::E9patch) {
return Ok(None);
}
Backend::Ptrace.ensure_available()?;
let target = self.resolve_e9patch_record_target()?;
if !is_elf_file(&target)? {
eprintln!(
":: Backend: e9patch preprocessing + ptrace record runtime; mapped_sites=0; \
main_executable=non-ELF; preprocessing=not-applicable"
);
return Ok(None);
}
if let Some(reason) = hermit::e9patch::unavailable_reason() {
anyhow::bail!("backend `e9patch` is unavailable: {reason}");
}
let prepared = hermit::e9patch::prepare(&target)?;
let rewrite_cache = if prepared.patched_sites == 0 {
"not-applicable"
} else if prepared.rewrite_cache_hit {
"hit"
} else {
"miss"
};
eprintln!(
":: Backend: e9patch preprocessing + ptrace record runtime; candidate_sites={}; \
mapped_sites={}; b0_sites={}; instruction_map_cache={:?}; rewrite_cache={}; \
artifact_sha256={}",
prepared.candidate_sites,
prepared.patched_sites,
prepared.b0_sites,
prepared.instruction_map_cache_status,
rewrite_cache,
prepared.artifact_sha256.as_deref().unwrap_or("none"),
);
Ok(
(prepared.patched_sites != 0).then_some(E9patchRecordOverlay {
source: prepared.binary,
target,
}),
)
}
/// Whether this invocation replays its recording under a gdbserver.
fn replays_under_gdb(&self) -> bool {
!self.verify && !self.gdbex.is_empty()
}
/// The network the recording (and an immediate replay of it) runs in.
fn network(&self) -> NetworkingMode {
self.network.unwrap_or(if self.replays_under_gdb() {
NetworkingMode::Host
} else {
NetworkingMode::Local
})
}
/// A replay served to gdb runs on the host network, where the gdb client
/// can reach its gdbserver port, so the recording it checks must too.
fn check_gdb_replay_network(&self) -> Result<(), Error> {
if self.replays_under_gdb() && self.network() == NetworkingMode::Local {
anyhow::bail!(
"--verify-with-gdbex replays under a gdbserver that the gdb client reaches \
on the host network, so the recording must use the same network; \
--network local is not supported with it"
);
}
Ok(())
}
fn configured_container(
&self,
network: NetworkingMode,
) -> Result<(Container, IdentityGuard), Error> {
let mut container = default_container(true);
network.configure(&mut container, false);
let (mut identity_mounts, mut identity_guard) = identity_hardening_mounts()?;
for mount in &self.mount {
let user_target = mount.get_target();
identity_guard.discard_mounts_shadowed_by(&mut identity_mounts, user_target);
}
container.mounts(identity_mounts);
container.mounts(self.mount.clone());
if let Some(workdir) = &self.workdir {
container.current_dir(workdir);
}
Ok((container, identity_guard))
}
fn recording_container(
&self,
global: &GlobalOpts,
) -> Result<(Container, IdentityGuard), Error> {
let overlay = self.prepare_e9patch_overlay(global)?;
let (mut container, identity_guard) = self.configured_container(self.network())?;
if let Some(overlay) = overlay {
container.mount(Mount::bind(&overlay.source, &overlay.target).readonly());
container.mount(
Mount::new(overlay.target)
.flags(MountFlags::MS_BIND | MountFlags::MS_REMOUNT | MountFlags::MS_RDONLY),
);
}
Ok((container, identity_guard))
}
/// The `--verify-json` path this invocation will publish a verdict to, if
/// any. See `RunOpts::verify_json_path`: the stamp must precede the
/// top-level preflight, not merely `record_verify`'s first statement.
pub(crate) fn verify_json_path(&self) -> Option<&Path> {
self.verify.then_some(self.verify_json.as_deref()).flatten()
}
pub fn main(&self, global: &GlobalOpts) -> Result<ExitStatus, Error> {
if self.verify {
validate_log_level(global)?;
self.record_verify(global)
} else if !self.gdbex.is_empty() {
self.record_verify_debug(global)
} else {
let hermit = HermitData::from(self.data_dir.as_ref());
let record_timeout = self.record_timeout();
let local_networking = self.network() == NetworkingMode::Local;
let (mut container, identity_guard) = self.recording_container(global)?;
// Parent-owned for BOTH deadline and unbounded spellings. No
// metadata/last-id commit occurs before real successful completion.
let data = hermit.create_recording_dir()?;
let resources = format!("recording {} and identity mounts", data.path().display());
let options = self.clone();
let global = global.clone();
let (exit_status, (data, _identity)) = super::owned_container::run(
&mut container,
(data, identity_guard),
resources,
true,
if record_timeout.is_some() {
"record.main.deadline"
} else {
"record.main"
},
None,
move |(data, identity)| {
let _guard = global.init_tracing();
let command = options.guest_command()?;
let mountinfo = identity.mountinfo_root_rewrites()?;
match record_timeout {
Some(timeout) => with_recording_deadline(timeout, || {
hermit::record_to_with_mountinfo(
command,
data.path(),
mountinfo,
local_networking,
)
}),
None => hermit::record_to_with_mountinfo(
command,
data.path(),
mountinfo,
local_networking,
),
}
},
)?;
let recording = hermit.commit_recording(data, exit_status)?;
eprintln!("\n{}\n", "RECORDING COMPLETE!".yellow().bold());
for (label, command) in
replay_hint_commands(&recording.id.to_string(), self.data_dir.as_deref())
{
eprintln!(
"{}:\n\n {}\n",
label.yellow().bold(),
command.blue().bold()
);
}
Ok(recording.exit_status)
}
}
/// This is called when `--verify` is passed to the command line.
fn record_verify(&self, global: &GlobalOpts) -> Result<ExitStatus, Error> {
// Stamp an explicit no-result BEFORE any fallible work: the record and
// replay steps below can fail long before a verdict exists, and a reused
// --verify-json path must never keep showing a previous invocation's
// green as though it described this one.
if let Some(path) = &self.verify_json {
write_pending_verification_json(path)?;
}
let strictness = if self.verify_strict {
LogCompareStrictness::Canonical
} else {
LogCompareStrictness::Stripped
};
let ((global1, log1), (global2, log2)) =
setup_double_run(global, "record", "replay", strictness);
let (mut recording_container, record_identity_guard) = self.recording_container(global)?;
eprintln!(":: {}", "Recording...".yellow().bold());
let temp_data_dir = tempfile::tempdir()?;
let resources = format!(
"verification recording {}, identity mounts and both logs",
temp_data_dir.path().display()
);
let record_timeout = self.record_timeout();
let local_networking = self.network() == NetworkingMode::Local;
let options = self.clone();
let record_global = global1.clone();
let (recording, (temp_data_dir, _record_identity, log1, log2)) =
super::owned_container::run(
&mut recording_container,
(temp_data_dir, record_identity_guard, log1, log2),
resources.clone(),
true,
"record_verify.record",
None,
move |(data, identity, _, _)| {
let _guard = record_global.init_tracing();
let command = options.guest_command()?;
let mountinfo = identity.mountinfo_root_rewrites()?;
match record_timeout {
Some(timeout) => with_recording_deadline(timeout, || {
hermit::record_with_output_with_mountinfo(
command,
data.path(),
mountinfo,
local_networking,
)
}),
None => hermit::record_with_output_with_mountinfo(
command,
data.path(),
mountinfo,
local_networking,
),
}
},
)?;
eprintln!(":: {}", "Replaying...".yellow().bold());
let (mut replay_container, replay_identity) = self.configured_container(self.network())?;
let mounts = self.mount.clone();
let replay_global = global2.clone();
let (replay, (_data, _identity, log1, log2)) = super::owned_container::run(
&mut replay_container,
(temp_data_dir, replay_identity, log1, log2),
resources,
true,
"record_verify.replay",
None,
move |(data, _, _, _)| {
let _guard = replay_global.init_tracing();
hermit::replay_with_output_and_mounts(data.path(), &mounts)
},
)?;
let outcome = compare_two_runs(
ComparedRun {
output: &recording,
log: log1.into_temp_path(),
label: "the recording",
},
ComparedRun {
output: &replay,
log: log2.into_temp_path(),
label: "the replay",
},
ComparisonOptions {
verbose: false,
strictness,
compare_logs: true,
diagnostic_full_trace: false,
// Recording DOES enable the syscall output-buffer hash, so a
// replay verdict here is a content-parity claim. It was not
// before: this line and the recorder's own setting were two
// independent hard-coded `false`s, and they are now one
// constant precisely so they cannot drift apart again. See its
// doc on `RECORD_REPLAY_HASHES_IO_BUFFERS`.
compare_io_buffers: hermit::RECORD_REPLAY_HASHES_IO_BUFFERS,
// Disclose the time policy this path actually runs under. It is
// the SAME constant `record_or_replay_config` uses, so the report
// cannot describe a policy the run did not use.
virtualize_time: hermit::RECORD_REPLAY_VIRTUALIZES_TIME,
keep_logs: false,
match_overridden: false,
failed_log_retention: Some(super::verify::default_failed_verify_log_retention()),
record_envelope: RecordEnvelope::all_records_v1(),
},
)?;
// Emit the machine-readable verdict (if requested) before collapsing the
// outcome to the historical exit-code convention, so the verdict is
// recorded whether or not the runs matched and independent of the guest's
// own exit status.
if let Some(path) = &self.verify_json {
write_verification_json(path, &outcome)?;
}
announce_verification_outcome(
&outcome,
SecondRun::Replay,
"Success: replay matched recording.",
"Recording output did not match replay output!",
);
emit_compared_guest_output(outcome.verified(), &recording, &replay)?;
outcome.into_exit_status()
}
/// This is called when `--verify-with-gdbex` is passed to the command line.
fn record_verify_debug(&self, global: &GlobalOpts) -> Result<ExitStatus, Error> {
self.check_gdb_replay_network()?;
let (mut container, identity_guard) = self.recording_container(global)?;
eprintln!(":: {}", "Recording...".yellow().bold());
let temp_data_dir = tempfile::tempdir()?;
let record_timeout = self.record_timeout();
let local_networking = self.network() == NetworkingMode::Local;
let options = self.clone();
let record_global = global.clone();
let resources = format!(
"debug recording {}, identity mounts and GDB watcher",
temp_data_dir.path().display()
);
let (_, (temp_data_dir, _identity)) = super::owned_container::run(
&mut container,
(temp_data_dir, identity_guard),
resources.clone(),
true,
"record_verify_debug.record",
None,
move |(data, identity)| {
let _guard = record_global.init_tracing();
let command = options.guest_command()?;
let mountinfo = identity.mountinfo_root_rewrites()?;
match record_timeout {
Some(timeout) => with_recording_deadline(timeout, || {
hermit::record_to_with_mountinfo(
command,
data.path(),
mountinfo,
local_networking,
)
}),
None => hermit::record_to_with_mountinfo(
command,
data.path(),
mountinfo,
local_networking,
),
}
},
)?;
let data_dir = temp_data_dir.path();
eprintln!(":: {}", "Replaying...".yellow().bold());
// Find the path to the executable so that GDB can use it to resolve
// symbols.
let exe = data_dir.join("exe");
let real_exe = Shebang::new(&exe).map_or(exe, |s| s.interpreter().into());
// Not using fixed port (such as 1234) here because this is mainly
// intended for tests, which could be running in parallel. This could
// be flakey when port is already in use.
let gdbserver_port = 16384 + nix::unistd::gettid().as_raw() as u16 % 1024;
// Run the gdb client outside of the PID namespace. This cannot be done
// inside of the PID namespace because it would perturb the
// deterministic PID allocation that is needed for the replay.
let mut gdb_command = std::process::Command::new("gdb");
gdb_command
.arg(real_exe)
.arg("-quiet")
.arg("-iex")
// don't prompt (dialog) when breakpoint symbol doesn't exist.
.arg("set breakpoint pending on")
.arg("-ex")
.arg(format!("target remote :{}", gdbserver_port));
for ex in &self.gdbex {
gdb_command.arg("-ex").arg(ex);
}
// Make sure gdb always exit.
gdb_command.arg("-batch");
gdb_command.arg("--return-child-result");
// TODO: For replay, we ought to construct the container from
// `metadata.json`. That logic belongs in `hermit::replay`, but we have
// to initialize logging inside the container because it may spawn a
// thread. If we can guarantee that tracing won't spawn a thread, then
// that restriction be lifted.
// ⚠️ HAND THE CLIENT OVER BEFORE THE CONTAINER STARTS. The gdbserver
// inside the container waits for this process with an UNBOUNDED accept,
// so if it has already died the container blocks forever -- and the
// `gdb_client.wait()` that would have noticed used to sit BELOW the `?`
// on that container result, unreachable in exactly the case that needed
// it. The watch owns the reap and releases the accept.
let gdb_watch = GdbClientWatch::spawn(gdb_command, gdbserver_port)?;
// The gdb client runs outside the container, so the replay's gdbserver
// port must live in the host network namespace, which `network()`
// guarantees the recording also used.
let (mut container, identity) = self.configured_container(self.network())?;
let guards = Rc::new(RefCell::new((temp_data_dir, identity, gdb_watch)));
let replay_global = global.clone();
let mounts = self.mount.clone();
let result = super::owned_container::run(
&mut container,
Rc::clone(&guards),
resources,
true,
"record_verify_debug.replay",
None,
move |guards| {
let _guard = replay_global.init_tracing();
hermit::replay_with_gdbserver_and_mounts(
guards.borrow().0.path(),
gdbserver_port,
&mounts,
)
},
);
if result.as_ref().is_err_and(|e| {
e.downcast_ref::<super::owned_container::ParentCleanupUnconfirmed>()
.is_some()
}) {
return result.map(|(status, _)| status);
}
let finished = guards.borrow_mut().2.finish();
match (result, finished) {
(Ok((status, _)), Ok(_)) => Ok(status),
(Ok(_), Err(watcher)) => Err(watcher),
(Err(primary), Err(watcher)) => {
Err(primary.context(format!("GDB watcher also failed: {watcher:#}")))
}
(Err(primary), Ok(true)) => Err(primary.context(CLIENT_EXITED_BEFORE_CONNECTING)),
(Err(primary), Ok(false)) => Err(primary),
}
}
}
/// The replay commands offered after a successful `hermit record start`, as
/// `(label, command)` pairs in the order they are printed.
///
/// Plain playback comes first because a bare `hermit replay` starts an
/// interactive GDB session (see `ReplayOpts::main`), which is a debugging
/// tool, not the way to watch a recording run again. `--autopilot` replays to
/// the end without a debugger. A recording made with `--data-dir` (or
/// `HERMIT_DATA_DIR`) is only found by a replay given the same directory, so
/// the directory is repeated in both commands.
fn replay_hint_commands(id: &str, data_dir: Option<&Path>) -> [(&'static str, String); 2] {
let data_dir = data_dir.map_or_else(String::new, |dir| {
format!(" --data-dir={}", shell_words::quote(&dir.to_string_lossy()))
});
[
(
"To replay it to the end",
format!("hermit replay --autopilot{data_dir} {id}"),
),
(
"To replay it under GDB for debugging",
format!("hermit replay{data_dir} {id}"),
),
]
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn completion_hint_offers_plain_playback_before_the_gdb_session() {
let id = "0123456789abcdef0123456789abcdef";
let [(plain_label, plain), (gdb_label, gdb)] = replay_hint_commands(id, None);
assert_eq!(plain, format!("hermit replay --autopilot {id}"));
assert_eq!(plain_label, "To replay it to the end");
assert_eq!(gdb, format!("hermit replay {id}"));
assert!(gdb_label.contains("GDB"), "{gdb_label}");
let [(_, plain), (_, gdb)] =
replay_hint_commands(id, Some(Path::new("/data/my recordings")));
assert_eq!(
plain,
format!("hermit replay --autopilot --data-dir='/data/my recordings' {id}")
);
assert_eq!(
gdb,
format!("hermit replay --data-dir='/data/my recordings' {id}")
);
// Both offered commands must parse as real `hermit replay` invocations,
// and only the plain one may select autopilot (no GDB).
use clap::CommandFactory;
for (command, autopilot) in [(&plain, true), (&gdb, false)] {
let matches = crate::Args::command()
.try_get_matches_from(shell_words::split(command).unwrap())
.unwrap_or_else(|e| panic!("{command}: {e}"));
let replay = matches.subcommand_matches("replay").expect(command);
assert_eq!(replay.get_flag("autopilot"), autopilot, "{command}");
assert_eq!(
replay.get_one::<PathBuf>("data_dir"),
Some(&PathBuf::from("/data/my recordings")),
"{command}"
);
}
}
#[test]
fn replay_report_is_published_before_success_is_announced() {
let source = include_str!("record_start.rs");
let verification = source
.split_once("let outcome = compare_two_runs(")
.expect("record/replay comparison")
.1;
let publish = verification
.find("write_verification_json(path, &outcome)")
.expect("verification report publication");
let announce = verification
.find("announce_verification_outcome(")
.expect("verification announcement");
assert!(publish < announce);
// The second half of record-mode verification is a replay, so its match
// line must use the replay wording for the time note.
let call = &verification[announce..];
let call = &call[..call.find(");").expect("end of announcement call")];
assert!(call.contains("SecondRun::Replay"), "{call}");
}
fn start_options(env: Vec<(String, Option<String>)>) -> StartOpts {
StartOpts {
program: Some(PathBuf::from("/bin/true")),
_strict: false,
args: Vec::new(),
env,
base_env: BaseEnv::Host,
mount: Vec::new(),
network: None,
workdir: None,
data_dir: None,
record_timeout: None,
verify: false,
verify_json: None,
verify_strict: false,
gdbex: Vec::new(),
}
}
/// `record start` takes `run`'s networking contract, local by default,
/// except that a gdb-served replay needs the host network.
#[test]
fn record_networking_defaults_to_local_like_run() {
#[derive(clap::Parser)]
struct Cli {
#[clap(flatten)]
start: StartOpts,
}
let parse = |args: &[&str]| {
<Cli as clap::Parser>::try_parse_from(args)
.unwrap()
.start
.network()
};
assert_eq!(parse(&["start", "/bin/true"]), NetworkingMode::Local);
assert_eq!(
parse(&["start", "--network", "host", "/bin/true"]),
NetworkingMode::Host
);
assert_eq!(
parse(&["start", "--verify-with-gdbex", "continue", "/bin/true"]),
NetworkingMode::Host
);
assert_eq!(
parse(&[
"start",
"--verify",
"--verify-with-gdbex",
"continue",
"/bin/true"
]),
NetworkingMode::Local
);
assert_eq!(
parse(&[
"start",
"--network",
"local",
"--verify-with-gdbex",
"continue",
"/bin/true"
]),
NetworkingMode::Local
);
}
#[test]
fn a_gdb_checked_recording_refuses_local_networking() {
#[derive(clap::Parser)]
struct Cli {
#[clap(flatten)]
start: StartOpts,
}
let check = |args: &[&str]| {
<Cli as clap::Parser>::try_parse_from(args)
.unwrap()
.start
.check_gdb_replay_network()
};
let refused = check(&[
"start",
"--network",
"local",
"--verify-with-gdbex",
"continue",
"/bin/true",
])
.unwrap_err();
assert!(
refused
.to_string()
.contains("--network local is not supported"),
"{refused:#}"
);
check(&["start", "--verify-with-gdbex", "continue", "/bin/true"]).unwrap();
check(&[
"start",
"--network",
"host",
"--verify-with-gdbex",
"continue",
"/bin/true",
])
.unwrap();
check(&["start", "--network", "local", "/bin/true"]).unwrap();
}
#[test]
fn record_guest_command_applies_explicit_environment() {
let options = start_options(vec![("RECORD_ENV_FIXTURE".into(), Some("value".into()))]);
let command = options.guest_command().unwrap();
assert!(
command
.get_captured_envs()
.iter()
.any(|(name, value)| name == "RECORD_ENV_FIXTURE" && value == "value")
);
}
#[test]
fn record_guest_command_can_use_the_run_minimal_environment_and_workdir() {
let mut options = start_options(Vec::new());
options.base_env = BaseEnv::Minimal;
options.workdir = Some("/test".into());
let command = options.guest_command().unwrap();
let env = command.get_captured_envs();
assert_eq!(command.get_current_dir(), Some(Path::new("/test")));
assert_eq!(
env.get(OsStr::new("HOME")).and_then(|value| value.to_str()),
Some("/root")
);
assert_eq!(
env.get(OsStr::new("HOSTNAME"))
.and_then(|value| value.to_str()),
Some("hermetic-container.local")
);
assert_eq!(
env.get(OsStr::new("ASAN_OPTIONS"))
.and_then(|value| value.to_str()),
Some("detect_leaks=0")
);
assert!(!env.contains_key(OsStr::new("PWD")));
assert!(!env.contains_key(OsStr::new("OLDPWD")));
}
#[test]
fn record_guest_command_refuses_missing_passthrough_environment() {
let name = "HERMIT_RECORD_MISSING_ENV_FIXTURE_5E7D2C";
assert!(std::env::var_os(name).is_none());
let error = match start_options(vec![(name.into(), None)]).guest_command() {
Ok(_) => panic!("missing pass-through environment was accepted"),
Err(error) => error,
};
assert!(
error
.to_string()
.contains("not set in the host environment")
);
}
// A blocked SIGALRM (e.g. inherited from the parent) would leave the alarm
// perpetually pending and silently disable the deadline. Arming must unblock
// SIGALRM, and dropping must restore the prior blocked state without
// spuriously blocking a signal that started unblocked. A long timeout keeps
// the process-wide alarm from firing during the test; the guard's Drop
// cancels it.
#[test]
fn recording_deadline_manages_sigalrm_mask() {
let sigalrm = sigalrm_set();
// Case 1: SIGALRM starts blocked. Arm unblocks it; drop re-blocks it.
sigalrm.thread_block().unwrap();
assert!(SigSet::thread_get_mask().unwrap().contains(Signal::SIGALRM));
{
let _deadline = RecordingDeadline::arm(Duration::from_secs(3600)).unwrap();
assert!(
!SigSet::thread_get_mask().unwrap().contains(Signal::SIGALRM),
"arming the deadline must unblock SIGALRM so the alarm is deliverable"
);
}
assert!(
SigSet::thread_get_mask().unwrap().contains(Signal::SIGALRM),
"dropping the deadline must restore the inherited blocked state"
);
// Case 2: SIGALRM starts unblocked. Arm leaves it unblocked; drop must
// not spuriously block it.
sigalrm.thread_unblock().unwrap();
assert!(!SigSet::thread_get_mask().unwrap().contains(Signal::SIGALRM));
{
let _deadline = RecordingDeadline::arm(Duration::from_secs(3600)).unwrap();
assert!(!SigSet::thread_get_mask().unwrap().contains(Signal::SIGALRM));
}
assert!(
!SigSet::thread_get_mask().unwrap().contains(Signal::SIGALRM),
"dropping must not block SIGALRM when it started unblocked"
);
}
#[test]
fn e9patch_record_target_rejects_proc_magic_links() {
let options = StartOpts {
program: Some(PathBuf::from("/proc/self/exe")),
_strict: false,
args: Vec::new(),
env: Vec::new(),
base_env: BaseEnv::Host,
mount: Vec::new(),
network: None,
workdir: None,
data_dir: None,
record_timeout: None,
verify: false,
verify_json: None,
verify_strict: false,
gdbex: Vec::new(),
};
let error = options.resolve_e9patch_record_target().unwrap_err();
assert!(
error.to_string().contains("resolves through /proc"),
"unexpected error: {error}"
);
}
}