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
//! Explicit host categories and bounded, source-ordered external input replay.
//!
//! Recorded values are assumptions supplied by the caller. Replay proves their
//! use by source operations; it cannot prove what a past operating system held.
use std::collections::BTreeMap;
use std::sync::{Mutex, PoisonError};
use dive_ir::{StdOp, StdSupport};
use crate::HostError;
/// Maximum total UTF-8 bytes retained by one external-input context.
pub const MAX_INPUT_BYTES: usize = 1 << 20;
/// Maximum source input operations retained by one context.
pub const MAX_INPUT_RECORDS: usize = 256;
/// Maximum entries in one captured environment.
pub const MAX_ENV_ENTRIES: usize = 4096;
/// Explicit host category grants. Every profile defaults to no grants.
/// A grant never supplies an implementation or overrides a driver's refusal.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub struct HostAccess {
/// Read the process environment.
pub env: bool,
/// Read or write files, where the chosen driver implements the operation.
pub files: bool,
/// Execute processes, where implemented. Currently refused by the drivers.
pub exec: bool,
}
impl HostAccess {
/// No host access, including under TLC compatibility.
pub const NONE: Self = Self {
env: false,
files: false,
exec: false,
};
/// Parses the approved comma-separated category spelling.
///
/// ```
/// let access = dive_eval::inputs::HostAccess::parse("env,files")?;
/// assert!(access.env && access.files && !access.exec);
/// # Ok::<(), &'static str>(())
/// ```
///
/// # Errors
/// Empty, duplicate or unknown category names.
pub fn parse(text: &str) -> Result<Self, &'static str> {
let mut access = Self::NONE;
for name in text.split(',') {
let slot = match name {
"env" => &mut access.env,
"files" => &mut access.files,
"exec" => &mut access.exec,
_ => return Err("--allow-io expects comma-separated env,files,exec categories"),
};
if *slot {
return Err("--allow-io repeats a category");
}
*slot = true;
}
Ok(access)
}
/// Granted category names in stable report order.
#[must_use]
pub fn names(self) -> Vec<&'static str> {
[
(self.env, "env"),
(self.files, "files"),
(self.exec, "exec"),
]
.into_iter()
.filter_map(|(yes, name)| yes.then_some(name))
.collect()
}
/// Whether no category was granted.
#[must_use]
pub const fn is_empty(self) -> bool {
!self.env && !self.files && !self.exec
}
/// Whether a native operator's host category is granted. Non-I/O operators
/// require no category; this says nothing about implementation support.
#[must_use]
pub fn allows(self, op: StdOp) -> bool {
self.denied(op).is_none()
}
pub(crate) fn denied(self, op: StdOp) -> Option<&'static str> {
let (allowed, category) = match op {
StdOp::IoUtilsIOEnv => (self.env, "env"),
StdOp::IoUtilsIOExec
| StdOp::IoUtilsIOEnvExec
| StdOp::IoUtilsIOExecTemplate
| StdOp::IoUtilsIOEnvExecTemplate => (self.exec, "exec"),
_ if op.support() == StdSupport::Io => (self.files, "files"),
_ => return None,
};
(!allowed).then_some(category)
}
}
/// A source operation's external request, after its real arguments evaluate.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum InputRequest {
/// `IOUtils!IOEnv`.
Environment,
/// `IOUtils!Deserialize` with admitted TXT/UTF-8 options.
TextFile(String),
}
/// External bytes interpreted by the evaluator, never an arbitrary TLA+ value.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum InputResponse {
/// The complete UTF-8 process environment, fixed for a run.
Environment(BTreeMap<String, String>),
/// Exact UTF-8 contents of one file read.
Text(String),
}
/// One actual source-ordered input operation and its assumed response.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct InputRecord {
/// The source operation and actual path argument.
pub request: InputRequest,
/// The recorded external input, not a producer state or proof flag.
pub response: InputResponse,
}
impl InputRecord {
/// Retained UTF-8 bytes, including names and path arguments.
#[must_use]
pub fn bytes(&self) -> usize {
let path = match &self.request {
InputRequest::Environment => 0,
InputRequest::TextFile(path) => path.len(),
};
path.saturating_add(match &self.response {
InputResponse::Environment(entries) => {
entries.iter().fold(0usize, |n, (key, value)| {
n.saturating_add(key.len()).saturating_add(value.len())
})
}
InputResponse::Text(text) => text.len(),
})
}
}
/// Bounded external assumptions for a fresh source binding.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct RecordedInputs {
/// Explicit categories used by the original request.
pub grants: HostAccess,
/// Operations in their actual source execution order.
pub records: Vec<InputRecord>,
}
/// Raw external input provider owned by one source-binding operation.
pub trait InputSource: Send + Sync + std::fmt::Debug {
/// Executes or replays one exact source request.
///
/// # Errors
/// A named unsupported request, resource bound or replay mismatch.
fn request(&self, request: &InputRequest) -> Result<InputResponse, HostError>;
/// Closes binding and checks all required source demand.
///
/// # Errors
/// A remembered error or undemanded extra input records.
fn finish_binding(&self) -> Result<(), HostError>;
/// Captured assumptions as raw text, never evaluator-owned values.
fn recorded(&self) -> RecordedInputs;
}
impl RecordedInputs {
/// Checks resource bounds and response/request consistency without I/O.
///
/// # Errors
/// Oversized, incorrectly typed, ungranted or inconsistent input records.
pub fn validate(&self) -> Result<(), HostError> {
if self.records.len() > MAX_INPUT_RECORDS
|| self
.records
.iter()
.fold(0usize, |n, r| n.saturating_add(r.bytes()))
> MAX_INPUT_BYTES
{
return Err(input_error("recorded external input bounds"));
}
let mut environment = None;
for record in &self.records {
match (&record.request, &record.response) {
(InputRequest::Environment, InputResponse::Environment(entries))
if self.grants.env =>
{
if entries.len() > MAX_ENV_ENTRIES {
return Err(input_error("environment entry limit"));
}
if environment.is_some_and(|previous| previous != entries) {
return Err(input_error("recorded IOEnv must retain one environment"));
}
environment = Some(entries);
}
(InputRequest::TextFile(_), InputResponse::Text(_)) if self.grants.files => {}
_ => return Err(input_error("recorded input kind or category mismatch")),
}
}
Ok(())
}
}
/// A fresh ordered replay cursor. It has no operating-system access.
#[derive(Debug)]
pub struct InputReplay {
inputs: RecordedInputs,
cursor: Mutex<(usize, bool, Option<HostError>)>,
}
impl InputReplay {
/// Starts an independent cursor over explicit, bounded assumptions.
///
/// ```
/// use dive_eval::inputs::{HostAccess, InputRecord, InputReplay,
/// InputRequest, InputResponse, RecordedInputs};
/// let request = InputRequest::TextFile("input.txt".into());
/// let replay = InputReplay::new(RecordedInputs {
/// grants: HostAccess::parse("files").unwrap(),
/// records: vec![InputRecord { request: request.clone(),
/// response: InputResponse::Text("hello".into()) }],
/// }).unwrap();
/// assert_eq!(replay.request(&request).unwrap(), InputResponse::Text("hello".into()));
/// replay.finish_binding().unwrap();
/// ```
///
/// # Errors
/// Invalid recorded inputs; no source or host callback is executed.
pub fn new(inputs: RecordedInputs) -> Result<Self, HostError> {
inputs.validate()?;
Ok(Self {
inputs,
cursor: Mutex::new((0, false, None)),
})
}
/// Consumes the next exact source operation/argument pair.
///
/// # Errors
/// Missing, mismatched, extra-phase or previously failed input requests.
pub fn request(&self, request: &InputRequest) -> Result<InputResponse, HostError> {
let mut cursor = self.cursor.lock().unwrap_or_else(PoisonError::into_inner);
if let Some(error) = &cursor.2 {
return Err(error.clone());
}
let record = self.inputs.records.get(cursor.0);
let result = if cursor.1 {
Err(input_error("external input outside source binding"))
} else if let Some(record) = record {
if &record.request == request {
Ok(record.response.clone())
} else {
Err(input_error(
"recorded input does not match the next source operation and arguments",
))
}
} else {
Err(input_error("missing recorded source input"))
};
match &result {
Ok(_) => cursor.0 += 1,
Err(error) => cursor.2 = Some(error.clone()),
}
result
}
/// Closes binding, requiring every supplied record to have been demanded.
///
/// # Errors
/// A latched replay failure or extra input records.
pub fn finish_binding(&self) -> Result<(), HostError> {
let mut cursor = self.cursor.lock().unwrap_or_else(PoisonError::into_inner);
cursor.1 = true;
if let Some(error) = &cursor.2 {
return Err(error.clone());
}
if cursor.0 != self.inputs.records.len() {
let error = input_error("extra recorded inputs not demanded by source binding");
cursor.2 = Some(error.clone());
return Err(error);
}
Ok(())
}
/// A latched mismatch or request outside binding, even if source caught it.
#[must_use]
pub fn failure(&self) -> Option<HostError> {
self.cursor
.lock()
.unwrap_or_else(PoisonError::into_inner)
.2
.clone()
}
}
impl InputSource for InputReplay {
fn request(&self, request: &InputRequest) -> Result<InputResponse, HostError> {
Self::request(self, request)
}
fn finish_binding(&self) -> Result<(), HostError> {
Self::finish_binding(self)
}
fn recorded(&self) -> RecordedInputs {
self.inputs.clone()
}
}
impl crate::Host for InputReplay {
fn input(&self, request: &InputRequest) -> Option<Result<InputResponse, HostError>> {
Some(self.request(request))
}
}
/// A named external-input refusal; code zero never certifies a TLC exception.
#[must_use]
pub fn input_error(message: &str) -> HostError {
HostError {
code: 0,
message: format!("external inputs: {message}"),
}
}