1use std::fs::{self, File, OpenOptions};
7use std::io::{Read, Write};
8use std::path::{Path, PathBuf};
9use std::sync::atomic::{AtomicU64, Ordering};
10
11use dive_config::ModelConfig;
12use dive_ir::{Effects, Ir};
13use serde::{Deserialize, Serialize};
14use sha2::{Digest, Sha256};
15
16use crate::{CheckOptions, CheckResult, Verdict};
17
18#[doc(hidden)]
20pub const HEADER: usize = 48;
21pub const MAX_PAYLOAD_BYTES: usize = 64 << 20;
24pub const MAX_STATES: usize = 65_536;
26pub const MAX_STATE_BYTES: usize = 1 << 20;
28pub const MAX_LEVEL: u64 = 65_536;
30pub const MAX_COUNTER: u64 = 9_223_372_036_854_775_807;
32static SERIAL: AtomicU64 = AtomicU64::new(0);
33
34#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
37pub enum Counters {
38 #[default]
40 Tlc,
41 Retain,
43}
44
45#[derive(Clone, Copy, Debug, PartialEq, Eq)]
47pub enum Action {
48 PauseAfterLevels(u64),
51 Recover,
53}
54
55#[derive(Clone, Debug)]
68pub struct Request {
69 pub path: PathBuf,
71 pub action: Action,
73 pub counters: Counters,
75 pub config_source_sha256: Option<String>,
78}
79
80#[derive(Clone, Debug, Serialize)]
82pub struct Receipt {
83 pub status: &'static str,
85 pub payload_sha256: String,
87 pub transient_storage_cleanup_completed: bool,
91 pub archive_bytes: u64,
93 pub next_level: u64,
95 pub discovered: u64,
97 pub queued: u64,
99 pub counters: Counters,
101}
102
103impl Receipt {
104 pub fn finish_storage(
106 &mut self,
107 frontier: &crate::FrontierUsage,
108 predecessor: &crate::result::PredecessorUsage,
109 ) {
110 self.transient_storage_cleanup_completed = frontier.failures.is_empty()
111 && predecessor.failures.is_empty()
112 && predecessor.cleanup_completed;
113 }
114}
115
116#[derive(Clone, Debug)]
118pub struct Result {
119 pub check: CheckResult,
121 pub receipt: Option<Receipt>,
123}
124
125#[doc(hidden)]
127pub type Fallible<T> = std::result::Result<T, String>;
128
129#[doc(hidden)]
131#[allow(
132 missing_docs,
133 reason = "serialized identity fields named by the format"
134)]
135#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
136#[serde(deny_unknown_fields)]
137pub struct Identity {
138 pub schema: u32,
139 pub semantics: String,
140 pub executable_sha256: String,
141 pub ir_sha256: String,
142 pub config_sha256: String,
143 pub config_source_sha256: Option<String>,
144 pub seed: i64,
145 pub fp: usize,
146 pub options: String,
147}
148
149#[doc(hidden)]
151pub fn failure(message: impl Into<String>) -> Verdict {
152 Verdict::ResourceLimit {
153 message: format!("DIVE-S0400: native checkpoint {}", message.into()),
154 }
155}
156#[doc(hidden)]
158pub fn unsupported(feature: impl Into<String>) -> Verdict {
159 Verdict::Unsupported {
160 feature: format!("native checkpoint {}", feature.into()),
161 }
162}
163#[doc(hidden)]
165#[must_use]
166pub fn hex(bytes: &[u8]) -> String {
167 const HEX: &[u8; 16] = b"0123456789abcdef";
168 bytes
169 .iter()
170 .flat_map(|b| {
171 [
172 char::from(HEX[usize::from(b >> 4)]),
173 char::from(HEX[usize::from(b & 15)]),
174 ]
175 })
176 .collect()
177}
178#[doc(hidden)]
180#[must_use]
181pub fn hash(bytes: &[u8]) -> String {
182 hex(&Sha256::digest(bytes))
183}
184#[doc(hidden)]
189pub fn executable_hash() -> Fallible<String> {
190 let mut file = File::open(std::env::current_exe().map_err(|e| e.to_string())?)
191 .map_err(|e| e.to_string())?;
192 let mut digest = Sha256::new();
193 let mut bytes = [0u8; 8192];
194 loop {
195 let n = file.read(&mut bytes).map_err(|e| e.to_string())?;
196 if n == 0 {
197 break;
198 }
199 digest.update(&bytes[..n]);
200 }
201 Ok(hex(&digest.finalize()))
202}
203
204#[doc(hidden)]
210pub fn admit_source_inner(
211 ir: &Ir,
212 cfg: &ModelConfig,
213 allow_temporal: bool,
214) -> std::result::Result<(), Verdict> {
215 let mut targets: std::collections::BTreeSet<&str> = cfg
216 .constants
217 .iter()
218 .filter_map(|entry| {
219 if let dive_config::ConstantEntry::Substitution { target, .. } = entry {
220 Some(target.text.as_str())
221 } else {
222 None
223 }
224 })
225 .collect();
226 for name in [&cfg.init, &cfg.next, &cfg.view, &cfg.symmetry, &cfg.alias]
227 .into_iter()
228 .flatten()
229 {
230 targets.insert(name.text.as_str());
231 }
232 for names in [
233 &cfg.invariants,
234 &cfg.constraints,
235 &cfg.action_constraints,
236 &cfg.postconditions,
237 ] {
238 targets.extend(names.iter().map(|name| name.text.as_str()));
239 }
240 let mut roots: Vec<_> = ir
241 .defs()
242 .iter()
243 .enumerate()
244 .filter_map(|(index, def)| {
245 let startup = !ir.module(def.module).standard
246 || (def.params.is_empty() && matches!(def.scope, dive_ir::DefScope::TopLevel));
247 let user = startup && def.std.is_none();
248 (user || targets.contains(def.name.as_str()))
249 .then(|| dive_ir::DefId(u32::try_from(index).unwrap_or(u32::MAX)))
250 })
251 .collect();
252 roots.extend(ir.modules().iter().flat_map(|module| {
256 module.context.iter().filter_map(|(name, symbol)| {
257 if targets.contains(name.as_str())
258 && let dive_ir::Symbol::Def(def) = symbol
259 {
260 Some(*def)
261 } else {
262 None
263 }
264 })
265 }));
266 let reached = ir.reachable_defs(&roots);
267 let mut seen = std::collections::BTreeSet::new();
268 for (index, def) in ir.defs().iter().enumerate() {
269 if !reached[index] {
270 continue;
271 }
272 if def
273 .effects
274 .intersects(
275 Effects::IMPURE
276 .union(Effects::LIVE_TLCGET)
277 .union(if allow_temporal {
278 Effects::NONE
279 } else {
280 Effects::TEMPORAL
281 }),
282 )
283 {
284 return Err(unsupported(format!(
285 "runtime effects or temporal effects in {}",
286 def.name
287 )));
288 }
289 if let Some(op) = def.std {
290 admit_native(op)?;
291 continue;
292 }
293 let mut pending = vec![def.body];
294 while let Some(id) = pending.pop() {
295 if !seen.insert(id) {
296 continue;
297 }
298 let expression = ir.expr(id);
299 for reference in expression.op_refs() {
300 if let dive_ir::OpRef::Std(op) = reference {
301 admit_native(*op)?;
302 }
303 }
304 pending.extend(expression.children());
305 }
306 }
307 Ok(())
308}
309
310fn admit_native(op: dive_ir::StdOp) -> std::result::Result<(), Verdict> {
311 if op.impure()
312 || matches!(
313 op,
314 dive_ir::StdOp::TlcTLCGet
315 | dive_ir::StdOp::TlcTLCSet
316 | dive_ir::StdOp::TlcExtTLCGetOrDefault
317 )
318 {
319 Err(unsupported(format!(
320 "runtime effects or checker/register reads in {} are not recoverable in this slice",
321 op.name()
322 )))
323 } else {
324 Ok(())
325 }
326}
327
328pub fn read_payload(path: &Path, magic: &[u8; 8]) -> Fallible<(Vec<u8>, String, u64)> {
333 let mut file = File::open(path).map_err(|e| e.to_string())?;
334 let len = file.metadata().map_err(|e| e.to_string())?.len();
335 if len < HEADER as u64 || len > (HEADER + MAX_PAYLOAD_BYTES) as u64 {
336 return Err("archive byte bound".into());
337 }
338 let mut header = [0u8; HEADER];
339 file.read_exact(&mut header).map_err(|e| e.to_string())?;
340 if &header[..8] != magic {
341 return Err("native magic/schema mismatch".into());
342 }
343 let mut n = [0u8; 8];
344 n.copy_from_slice(&header[8..16]);
345 let size = usize::try_from(u64::from_le_bytes(n)).map_err(|e| e.to_string())?;
346 if size > MAX_PAYLOAD_BYTES || size as u64 + HEADER as u64 != len {
347 return Err("payload length/trailing bytes mismatch".into());
348 }
349 let mut payload = Vec::new();
350 payload.try_reserve_exact(size).map_err(|e| e.to_string())?;
351 payload.resize(size, 0);
352 file.read_exact(&mut payload).map_err(|e| e.to_string())?;
353 let mut trailing = [0];
354 if file.read(&mut trailing).map_err(|e| e.to_string())? != 0 {
355 return Err("archive changed or has trailing bytes".into());
356 }
357 let sha = Sha256::digest(&payload);
358 if sha.as_slice() != &header[16..48] {
359 return Err("payload checksum mismatch".into());
360 }
361 Ok((payload, hex(&sha), len))
362}
363
364pub fn write_payload(path: &Path, magic: &[u8; 8], payload: &[u8]) -> Fallible<()> {
369 if payload.len() > MAX_PAYLOAD_BYTES {
370 return Err("archive payload byte bound".into());
371 }
372
373 let parent = path
374 .parent()
375 .filter(|p| !p.as_os_str().is_empty())
376 .unwrap_or_else(|| Path::new("."));
377 let stem = path
378 .file_name()
379 .ok_or_else(|| "checkpoint needs a file name".to_owned())?
380 .to_string_lossy();
381 let staging = parent.join(format!(
382 ".{stem}.{}-{}.tmp",
383 std::process::id(),
384 SERIAL.fetch_add(1, Ordering::Relaxed)
385 ));
386 let result = (|| {
387 let mut options = OpenOptions::new();
388 options.write(true).create_new(true);
389 #[cfg(unix)]
390 {
391 use std::os::unix::fs::OpenOptionsExt;
392 options.mode(0o600);
393 }
394 let mut file = options.open(&staging).map_err(|e| e.to_string())?;
395 file.write_all(magic)
396 .and_then(|()| file.write_all(&(payload.len() as u64).to_le_bytes()))
397 .and_then(|()| file.write_all(&Sha256::digest(payload)))
398 .and_then(|()| file.write_all(payload))
399 .and_then(|()| file.sync_all())
400 .map_err(|e| e.to_string())?;
401 drop(file);
402 fs::hard_link(&staging, path).map_err(|e| e.to_string())?;
405 fs::remove_file(&staging)
406 .map_err(|e| format!("committed but staging cleanup failed: {e}"))?;
407 File::open(parent)
408 .and_then(|f| f.sync_all())
409 .map_err(|e| format!("committed but directory sync failed: {e}"))?;
410 Ok(())
411 })();
412 match result {
413 Ok(()) => Ok(()),
414 Err(original) => {
415 failed_staging_cleanup(original, staging.try_exists(), || fs::remove_file(&staging))
416 }
417 }
418}
419
420#[doc(hidden)]
425pub fn failed_staging_cleanup(
426 original: String,
427 inspection: std::io::Result<bool>,
428 cleanup: impl FnOnce() -> std::io::Result<()>,
429) -> Fallible<()> {
430 match inspection {
431 Ok(false) => Err(original),
432 Ok(true) => match cleanup() {
433 Ok(()) => Err(original),
434 Err(error) => Err(format!(
435 "original failure: {original}; staging cleanup failed: {error}"
436 )),
437 },
438 Err(error) => Err(format!(
439 "original failure: {original}; staging inspection failed: {error}"
440 )),
441 }
442}
443
444#[must_use]
446pub fn config_source_hash(bytes: &[u8]) -> String {
447 hash(bytes)
448}
449
450pub fn owned_identity(
456 ir: &Ir,
457 cfg: &ModelConfig,
458 opts: &CheckOptions,
459 request: &Request,
460 core_options: &str,
461) -> std::result::Result<Vec<u8>, Verdict> {
462 if ir.vars().len() > 1024 {
463 return Err(unsupported("state variable arity above 1024"));
464 }
465 if cfg.periodic.is_some() || cfg.rl_reward.is_some() || !cfg.possible.is_empty() {
466 return Err(unsupported(
467 "periodic/reward/possible hooks in owned Core recovery",
468 ));
469 }
470 admit_source_inner(ir, cfg, true)?;
471 let mut ir_bytes = serde_json::to_vec(ir).map_err(|e| failure(e.to_string()))?;
472 let local_classes = dive_model::local_java_class_digests(ir).map_err(unsupported)?;
473 ir_bytes.extend(serde_json::to_vec(&local_classes).map_err(|e| failure(e.to_string()))?);
474 let identity = Identity {
475 schema: 1,
476 semantics: "owned-core-safety-0141-v1".into(),
477 executable_sha256: executable_hash().map_err(failure)?,
478 ir_sha256: hash(&ir_bytes),
479 config_sha256: hash(format!("{cfg:?}").as_bytes()),
480 config_source_sha256: request.config_source_sha256.clone(),
481 seed: opts.seed,
482 fp: opts.fp_index,
483 options: format!(
484 "{:?}/{:?}/{:?}/{}/{}/{}/{}/{}/{}/{:?}/{:?}/{core_options}",
485 opts.profile,
486 opts.eval.ctx,
487 opts.eval.exploration,
488 opts.eval.max_depth,
489 opts.eval.warnings,
490 opts.fp_index,
491 opts.tlc_fingerprints,
492 opts.seed,
493 opts.no_deadlock,
494 opts.store,
495 opts.eval.comparisons
496 ),
497 };
498 serde_json::to_vec(&identity).map_err(|e| failure(e.to_string()))
499}
500
501pub fn owned_identity_seed_fp(bytes: &[u8]) -> Fallible<(i64, usize)> {
506 let identity: Identity = serde_json::from_slice(bytes).map_err(|e| e.to_string())?;
507 if identity.schema != 1
508 || identity.semantics != "owned-core-safety-0141-v1"
509 || identity.fp >= dive_value::fp64::POLYS.len()
510 {
511 return Err("owned identity schema/semantics/fingerprint mismatch".into());
512 }
513 Ok((identity.seed, identity.fp))
514}