1use crate::{CheckReport, CheckRequest, check_file};
3use dive_core::debug::{Instruction, Observer, Returned, SourceMap};
4use dive_core::plan::Code;
5use dive_core::{Error, Handle, Machine};
6use serde_json::{Value, json};
7use std::collections::{HashMap, VecDeque};
8use std::fmt::Write as _;
9use std::sync::{Arc, Condvar, Mutex, MutexGuard, PoisonError};
10use std::thread::JoinHandle;
11use std::time::{Duration, Instant};
12
13#[derive(Clone, Debug, PartialEq, Eq)]
15pub struct DebugError(pub String);
16impl std::fmt::Display for DebugError {
17 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
18 write!(f, "DIVE-D0001: {}", self.0)
19 }
20}
21impl std::error::Error for DebugError {}
22fn source_matches(path: &str, loaded: &str) -> bool {
23 let (path, loaded) = (std::path::Path::new(path), std::path::Path::new(loaded));
24 path == loaded
25 || std::env::current_dir()
26 .is_ok_and(|directory| directory.join(path) == directory.join(loaded))
27}
28fn rejected(message: &str) -> DebugError {
29 DebugError(message.into())
30}
31
32#[derive(Clone, Debug)]
34#[non_exhaustive]
35pub enum Event {
36 Prepared,
38 Stopped {
40 id: u64,
42 reason: String,
44 breakpoints: Vec<u64>,
46 description: Option<String>,
48 },
49 Completed(Value),
51 Failed(String),
53}
54
55#[derive(Clone, Debug)]
57pub struct Breakpoint {
58 pub id: u64,
60 pub line: u32,
62 pub verified: bool,
64}
65
66#[derive(Clone, Copy, Debug, PartialEq, Eq)]
67struct Key {
68 file: usize,
69 line: u32,
70 environment: usize,
71 definition: usize,
72 instance: Option<u32>,
73 base: usize,
74}
75#[derive(Clone, Debug)]
76struct Activation {
77 instruction: Instruction,
78 base: usize,
79}
80#[derive(Clone, Copy, Debug)]
81enum Motion {
82 Continue,
83 Into,
84 Over(usize),
85 Out(usize),
86}
87#[derive(Clone, Debug)]
88struct Installed {
89 file: usize,
90 breakpoint: Breakpoint,
91}
92#[derive(Clone, Debug)]
93struct Frame {
94 id: u64,
95 document: Value,
96 state: Vec<Value>,
97 next: Vec<Value>,
98 locals: Vec<Value>,
99}
100#[derive(Clone, Debug)]
101struct Snapshot {
102 frames: Vec<Frame>,
103 key: Key,
104 depth: usize,
105}
106#[derive(Debug)]
107#[allow(
108 clippy::struct_excessive_bools,
109 reason = "independent protocol controls, motion, error-unwind and producer lifecycle flags"
110)]
111struct State {
112 map: Option<SourceMap>,
113 configured: bool,
114 terminated: bool,
115 stop_entry: bool,
116 pause: bool,
117 exceptions: bool,
118 motion: Motion,
119 compat_tlc: bool,
120 stack: Vec<Activation>,
121 breakpoints: Vec<Installed>,
122 next_breakpoint: u64,
123 ignore: Option<(Key, usize)>,
124 snapshot: Option<Snapshot>,
125 epoch: u64,
126 events: VecDeque<Event>,
127 completion: Option<Value>,
128 error_in_flight: bool,
129}
130impl Default for State {
131 fn default() -> Self {
132 Self {
133 map: None,
134 configured: false,
135 terminated: false,
136 stop_entry: false,
137 pause: false,
138 exceptions: false,
139 motion: Motion::Continue,
140 compat_tlc: false,
141 stack: Vec::new(),
142 breakpoints: Vec::new(),
143 next_breakpoint: 1,
144 ignore: None,
145 snapshot: None,
146 epoch: 0,
147 events: VecDeque::new(),
148 completion: None,
149 error_in_flight: false,
150 }
151 }
152}
153#[derive(Debug, Default)]
154struct Control {
155 state: Mutex<State>,
156 changed: Condvar,
157}
158impl Control {
159 fn lock(&self) -> MutexGuard<'_, State> {
160 self.state.lock().unwrap_or_else(PoisonError::into_inner)
161 }
162 fn key(map: &SourceMap, instruction: Instruction, base: usize) -> Option<Key> {
163 let location = map.location(instruction)?;
164 Some(Key {
165 file: location.origin.file?.index(),
166 line: location.origin.begin.0,
167 environment: location.environment_id,
168 definition: location.definition_id,
169 instance: location.substitutions.last().map(|entry| entry.identity),
170 base,
171 })
172 }
173 #[allow(
174 clippy::too_many_arguments,
175 reason = "atomic producer stop retains lock, actual instruction/machine and event details"
176 )]
177 fn stop<'a>(
178 &self,
179 mut state: MutexGuard<'a, State>,
180 instruction: Instruction,
181 code: &Code,
182 machine: &Machine,
183 reason: &str,
184 breakpoints: Vec<u64>,
185 description: Option<String>,
186 ) -> Result<MutexGuard<'a, State>, Error> {
187 state.epoch = state
188 .epoch
189 .checked_add(1)
190 .filter(|epoch| *epoch < 524_287)
191 .ok_or_else(|| Error::unsupported("debugger stop handle capacity"))?;
192 let snapshot = snapshot(&state, instruction, code, machine)?;
193 let id = state.epoch;
194 state.snapshot = Some(snapshot);
195 if state.events.len() >= 256 {
196 return Err(Error::unsupported("debugger unconsumed event capacity"));
197 }
198 state.events.push_back(Event::Stopped {
199 id,
200 reason: reason.into(),
201 breakpoints,
202 description,
203 });
204 self.changed.notify_all();
205 while state.snapshot.is_some() && !state.terminated {
206 state = self
207 .changed
208 .wait(state)
209 .unwrap_or_else(PoisonError::into_inner);
210 }
211 if state.terminated {
212 return Err(Error::unsupported(
213 "debugger terminated the check before completion",
214 ));
215 }
216 Ok(state)
217 }
218 fn complete(&self, report: Result<&CheckReport, String>) {
219 let mut state = self.lock();
220 state.snapshot = None;
221 match report {
222 Ok(report) => {
223 let document = report.to_json_with_exit_convention(crate::ExitConvention::Native);
224 state.completion = Some(document.clone());
225 state.events.push_back(Event::Completed(document));
226 }
227 Err(error) => state.events.push_back(Event::Failed(error)),
228 }
229 self.changed.notify_all();
230 }
231}
232impl Observer for Control {
233 fn prepared(&self, map: &SourceMap) -> Result<(), Error> {
234 let mut state = self.lock();
235 state.map = Some(map.clone());
236 state.events.push_back(Event::Prepared);
237 self.changed.notify_all();
238 while !state.configured && !state.terminated {
239 state = self
240 .changed
241 .wait(state)
242 .unwrap_or_else(PoisonError::into_inner);
243 }
244 if state.terminated {
245 Err(Error::unsupported("debugger terminated before search"))
246 } else {
247 Ok(())
248 }
249 }
250 fn enter(&self, instruction: Instruction, code: &Code, machine: &Machine) -> Result<(), Error> {
251 let mut state = self.lock();
252 if state.terminated {
253 return Err(Error::unsupported(
254 "debugger terminated the check before completion",
255 ));
256 }
257 if state.stack.len() >= 4096 {
258 return Err(Error::unsupported("debugger activation capacity"));
259 }
260 state.stack.push(Activation {
261 instruction,
262 base: machine.base,
263 });
264 let Some(map) = &state.map else {
265 return Ok(());
266 };
267 let Some(key) = Self::key(map, instruction, machine.base) else {
268 return Ok(());
269 };
270 let depth = state.stack.len();
271 let hits = state
272 .breakpoints
273 .iter()
274 .filter(|bp| {
275 bp.breakpoint.verified && bp.file == key.file && bp.breakpoint.line == key.line
276 })
277 .map(|bp| bp.breakpoint.id)
278 .collect::<Vec<_>>();
279 let ignored = state.ignore.is_some_and(|(old, _)| old == key);
280 let reason = if state.pause {
281 Some("pause")
282 } else if state.stop_entry {
283 Some("entry")
284 } else if !hits.is_empty() && !ignored {
285 Some("breakpoint")
286 } else if match state.motion {
287 Motion::Continue => false,
288 Motion::Into => true,
289 Motion::Over(old) => depth <= old,
290 Motion::Out(old) => depth < old,
291 } {
292 Some("step")
293 } else {
294 None
295 };
296 if let Some(reason) = reason {
297 state.pause = false;
298 state.stop_entry = false;
299 state.motion = Motion::Continue;
300 if let Err(error) = self.stop(state, instruction, code, machine, reason, hits, None) {
301 self.lock().stack.pop();
302 return Err(error);
303 }
304 }
305 Ok(())
306 }
307 fn returned(
308 &self,
309 instruction: Instruction,
310 code: &Code,
311 machine: &Machine,
312 result: Returned<'_>,
313 ) -> Result<(), Error> {
314 let mut state = self.lock();
315 if state.terminated {
316 return Err(Error::unsupported(
317 "debugger terminated the check before completion",
318 ));
319 }
320 if !state.exceptions || state.error_in_flight {
321 return Ok(());
322 }
323 let description = match result {
324 Returned::Failed(error) if error.kind() == dive_core::ErrorKind::Eval => {
325 Some(error.message().to_owned())
326 }
327 Returned::Value(value) if value.as_bool() == Some(false) => {
328 if let Instruction::Value(index) = instruction {
329 state
330 .map
331 .as_ref()
332 .and_then(|map| map.obligations.iter().find(|(node, _)| *node == index))
333 .map(|(_, name)| format!("Property {name} is false"))
334 } else {
335 None
336 }
337 }
338 _ => None,
339 };
340 if let Some(description) = description
341 && state
342 .map
343 .as_ref()
344 .and_then(|map| Self::key(map, instruction, machine.base))
345 .is_some()
346 {
347 state.error_in_flight = true;
348 drop(self.stop(
349 state,
350 instruction,
351 code,
352 machine,
353 "exception",
354 Vec::new(),
355 Some(description),
356 )?);
357 }
358 Ok(())
359 }
360 fn leave(&self) {
361 let mut state = self.lock();
362 state.stack.pop();
363 if state
364 .ignore
365 .is_some_and(|(_, depth)| state.stack.len() < depth)
366 {
367 state.ignore = None;
368 }
369 if state.stack.is_empty() {
370 state.error_in_flight = false;
371 }
372 }
373}
374fn scalar(value: Handle, machine: &Machine) -> (String, &'static str, Option<Value>) {
375 if let Some(value) = value.as_int() {
376 return (value.to_string(), "integer", Some(json!(value)));
377 }
378 if let Some(value) = value.as_bool() {
379 return (
380 if value { "TRUE" } else { "FALSE" }.into(),
381 "boolean",
382 Some(json!(value)),
383 );
384 }
385 if let Some(id) = value.as_str_id()
386 && let Some(text) = machine.heap.store().strings().text(id)
387 && text.len() <= 4096
388 {
389 return (json!(&*text).to_string(), "string", Some(json!(&*text)));
390 }
391 if value.is_empty() {
392 ("<unassigned or unforced>".into(), "unavailable", None)
393 } else {
394 ("<opaque; not inspected>".into(), "unavailable", None)
395 }
396}
397fn variable(name: &str, value: Option<Handle>, machine: &Machine) -> Value {
398 let (text, kind, scalar) = value.map_or_else(
399 || ("<not evaluated>".into(), "unavailable", None),
400 |value| scalar(value, machine),
401 );
402 json!({"name":name,"value":text,"type":kind,"variablesReference":0,"scalar":scalar})
403}
404fn dap_position(source: &str, offset: u32) -> Option<(u32, u32)> {
405 let prefix = source.get(..usize::try_from(offset).ok()?)?;
406 let mut characters = prefix.chars().peekable();
407 let (mut line, mut column) = (1_u32, 1_u32);
408 while let Some(character) = characters.next() {
409 match character {
410 '\r' => {
411 if characters.peek() == Some(&'\n') {
412 characters.next();
413 }
414 line += 1;
415 column = 1;
416 }
417 '\n' => {
418 line += 1;
419 column = 1;
420 }
421 _ => column += u32::try_from(character.len_utf16()).ok()?,
422 }
423 }
424 Some((line, column))
425}
426
427fn snapshot(
428 state: &State,
429 instruction: Instruction,
430 code: &Code,
431 machine: &Machine,
432) -> Result<Snapshot, Error> {
433 let map = state
434 .map
435 .as_ref()
436 .ok_or_else(|| Error::internal("debugger map unavailable"))?;
437 let key = Control::key(map, instruction, machine.base)
438 .ok_or_else(|| Error::internal("debugger stop without source"))?;
439 let mut frames = Vec::new();
440 let mut previous = None;
441 for activation in state.stack.iter().rev() {
442 let Some(location) = map.location(activation.instruction) else {
443 continue;
444 };
445 let Some(file) = location
446 .origin
447 .file
448 .and_then(|file| map.files.get(file.index()))
449 else {
450 continue;
451 };
452 let identity = (
453 location.definition_id,
454 location.environment_id,
455 activation.base,
456 location.substitutions.last().map(|entry| entry.identity),
457 );
458 if previous == Some(identity) {
459 continue;
460 }
461 previous = Some(identity);
462 if frames.len() >= 128 {
463 return Err(Error::unsupported("debugger visible frame capacity"));
464 }
465 let ordinal =
466 u64::try_from(frames.len()).map_err(|_| Error::internal("debugger frame index"))?;
467 let id = state.epoch * 1024 + ordinal + 1;
468 let begin = dap_position(&file.source, location.origin.range.0)
469 .ok_or_else(|| Error::internal("compiled debugger source start range"))?;
470 let end = dap_position(&file.source, location.origin.range.1)
471 .ok_or_else(|| Error::internal("compiled debugger source end range"))?;
472 let document = json!({"id":id,"name":location.definition,"line":begin.0,"column":begin.1,
473 "endLine":end.0,"endColumn":end.1,
474 "source":{"name":file.module,"path":file.display,"sourceReference":location.origin.file.map(|file|file.index()+1)},
475 "instruction":format!("{:?}",activation.instruction),"instance":location.origin.instance.map(dive_ir::DefId::index),"environment":location.environment_id,"compilationCaller":location.caller,
476 "substitutions":location.substitutions.iter().map(|entry|json!({"declaration":entry.declaration,"identity":entry.identity,
477 "actual":entry.actual.map(|origin|json!({"path":origin.file.and_then(|file|map.files.get(file.index())).map(|file|&file.display),"begin":origin.begin,"end":origin.end,"range":origin.range}))})).collect::<Vec<_>>()});
478 let locals = location
479 .locals
480 .iter()
481 .map(|local| {
482 variable(
483 &local.name,
484 dive_core::debug::read_binding(&local.binding, code, machine, activation.base),
485 machine,
486 )
487 })
488 .collect();
489 let values = |values: &[Handle]| {
490 map.variables
491 .iter()
492 .enumerate()
493 .map(|(index, name)| variable(name, values.get(index).copied(), machine))
494 .collect()
495 };
496 frames.push(Frame {
497 id,
498 document,
499 state: values(&machine.s0),
500 next: values(&machine.s1),
501 locals,
502 });
503 }
504 Ok(Snapshot {
505 frames,
506 key,
507 depth: state.stack.len(),
508 })
509}
510
511#[derive(Debug)]
526pub struct Session {
527 control: Arc<Control>,
528 worker: Option<JoinHandle<Result<CheckReport, crate::ApiError>>>,
529}
530impl Session {
531 pub fn launch(mut request: CheckRequest, stop_on_entry: bool) -> Result<Self, DebugError> {
538 if request.store_compact_bytes.is_some() {
539 return Err(rejected(
540 "compiled debugger with Store reclamation is not implemented",
541 ));
542 }
543 if request.tlc_coverage {
544 return Err(rejected(
545 "compiled debugger with TLC logical coverage is not implemented",
546 ));
547 }
548 if request.source_coverage {
549 return Err(rejected(
550 "compiled debugger with native source coverage is not implemented",
551 ));
552 }
553 if request.distributed.is_some() {
554 return Err(rejected(
555 "compiled debugger with distributed safety checking is not implemented",
556 ));
557 }
558 if request.debugger.is_some()
559 || request.temporal_refusal.is_some()
560 || request.core_sample.is_some()
561 || !request.host_access.is_empty()
562 {
563 return Err(rejected(
564 "debugger supports local Core ordinary safety without host grants, coverage or sampling",
565 ));
566 }
567 let control = Arc::new(Control::default());
568 {
569 let mut state = control.lock();
570 state.stop_entry = stop_on_entry;
571 state.compat_tlc = request.compat_tlc;
572 }
573 request.debugger = Some(Arc::clone(&control) as Arc<dyn Observer>);
574 let observed = Arc::clone(&control);
575 let worker = std::thread::Builder::new()
576 .name("dive-debug-check".into())
577 .stack_size(32 << 20)
578 .spawn(move || {
579 let result = check_file(&request);
580 observed.complete(result.as_ref().map_err(ToString::to_string));
581 result
582 })
583 .map_err(|error| DebugError(error.to_string()))?;
584 Ok(Self {
585 control,
586 worker: Some(worker),
587 })
588 }
589 pub fn wait_event(&self, timeout: Duration) -> Result<Option<Event>, DebugError> {
594 if timeout > Duration::from_secs(60) {
595 return Err(rejected("debugger event wait exceeds one minute"));
596 }
597 let deadline = Instant::now() + timeout;
598 let mut state = self.control.lock();
599 loop {
600 if let Some(event) = state.events.pop_front() {
601 return Ok(Some(event));
602 }
603 let remaining = deadline.saturating_duration_since(Instant::now());
604 if remaining.is_zero() {
605 return Ok(None);
606 }
607 let (next, wait) = self
608 .control
609 .changed
610 .wait_timeout(state, remaining)
611 .unwrap_or_else(PoisonError::into_inner);
612 state = next;
613 if wait.timed_out() {
614 return Ok(state.events.pop_front());
615 }
616 }
617 }
618 pub fn set_breakpoints(
623 &self,
624 path: &str,
625 lines: &[u32],
626 ) -> Result<Vec<Breakpoint>, DebugError> {
627 if lines.len() > 1024 || lines.contains(&0) {
628 return Err(rejected("invalid or excessive source breakpoints"));
629 }
630 let mut state = self.control.lock();
631 let map = state
632 .map
633 .as_ref()
634 .ok_or_else(|| rejected("compiled map is not ready"))?;
635 let file = map
636 .files
637 .iter()
638 .position(|file| source_matches(path, &file.display))
639 .ok_or_else(|| rejected("source is not loaded by this check"))?;
640 let verified = lines
641 .iter()
642 .map(|line| {
643 map.executable.iter().any(|site| {
644 map.location(*site).is_some_and(|location| {
645 location.origin.file.is_some_and(|id| id.index() == file)
646 && location.origin.begin.0 == *line
647 })
648 })
649 })
650 .collect::<Vec<_>>();
651 state.breakpoints.retain(|bp| bp.file != file);
652 let mut result = Vec::new();
653 for (line, verified) in lines.iter().zip(verified) {
654 let id = state.next_breakpoint;
655 state.next_breakpoint = state
656 .next_breakpoint
657 .checked_add(1)
658 .filter(|id| *id < 1_000_000_000)
659 .ok_or_else(|| rejected("breakpoint identity capacity"))?;
660 let breakpoint = Breakpoint {
661 id,
662 line: *line,
663 verified,
664 };
665 state.breakpoints.push(Installed {
666 file,
667 breakpoint: breakpoint.clone(),
668 });
669 result.push(breakpoint);
670 }
671 Ok(result)
672 }
673 pub fn break_on_entry(&self, enabled: bool) -> Result<(), DebugError> {
678 let mut state = self.control.lock();
679 if state.configured || state.terminated || state.completion.is_some() {
680 return Err(rejected("entry policy requires a pending check"));
681 }
682 state.stop_entry = enabled;
683 Ok(())
684 }
685
686 pub fn configuration_done(&self) -> Result<(), DebugError> {
691 let mut state = self.control.lock();
692 if state.map.is_none() || state.terminated || state.configured {
693 return Err(rejected("debugger configuration is unavailable"));
694 }
695 state.configured = true;
696 self.control.changed.notify_all();
697 Ok(())
698 }
699 pub fn exception_breakpoints(&self, enabled: bool) -> Result<(), DebugError> {
704 let mut state = self.control.lock();
705 if state.map.is_none() || state.terminated || state.completion.is_some() {
706 return Err(rejected("no active compiled session"));
707 }
708 state.exceptions = enabled;
709 Ok(())
710 }
711 pub fn pause(&self) -> Result<(), DebugError> {
716 let mut state = self.control.lock();
717 if !state.configured
718 || state.completion.is_some()
719 || state.terminated
720 || state.snapshot.is_some()
721 {
722 return Err(rejected("no active producer to pause"));
723 }
724 state.pause = true;
725 Ok(())
726 }
727 fn resume(&self, motion: Motion) -> Result<(), DebugError> {
728 let mut state = self.control.lock();
729 let snapshot = state
730 .snapshot
731 .take()
732 .ok_or_else(|| rejected("producer is not stopped"))?;
733 state.ignore = Some((snapshot.key, snapshot.depth));
734 state.motion = match motion {
735 Motion::Over(_) => Motion::Over(snapshot.depth),
736 Motion::Out(_) => Motion::Out(snapshot.depth),
737 other => other,
738 };
739 self.control.changed.notify_all();
740 Ok(())
741 }
742 pub fn continue_check(&self) -> Result<(), DebugError> {
747 self.resume(Motion::Continue)
748 }
749 pub fn step_in(&self) -> Result<(), DebugError> {
754 self.resume(Motion::Into)
755 }
756 pub fn next(&self) -> Result<(), DebugError> {
761 self.resume(Motion::Over(0))
762 }
763 pub fn step_out(&self) -> Result<(), DebugError> {
768 self.resume(Motion::Out(0))
769 }
770 pub fn stack(&self) -> Result<Vec<Value>, DebugError> {
775 let state = self.control.lock();
776 Ok(state
777 .snapshot
778 .as_ref()
779 .ok_or_else(|| rejected("producer is not stopped"))?
780 .frames
781 .iter()
782 .map(|frame| frame.document.clone())
783 .collect())
784 }
785 pub fn scopes(&self, frame: u64) -> Result<Vec<Value>, DebugError> {
790 let state = self.control.lock();
791 let snapshot = state
792 .snapshot
793 .as_ref()
794 .ok_or_else(|| rejected("producer is not stopped"))?;
795 let frame = snapshot
796 .frames
797 .iter()
798 .find(|candidate| candidate.id == frame)
799 .ok_or_else(|| rejected("stale or unknown frame handle"))?;
800 Ok([("State",1),("Successor",2),("Locals",3)].map(|(name,kind)|json!({"name":name,"variablesReference":frame.id*4+kind,"expensive":false})).to_vec())
801 }
802 pub fn variables(&self, reference: u64) -> Result<Vec<Value>, DebugError> {
807 let state = self.control.lock();
808 let snapshot = state
809 .snapshot
810 .as_ref()
811 .ok_or_else(|| rejected("producer is not stopped"))?;
812 for frame in &snapshot.frames {
813 let values = match reference.checked_sub(frame.id * 4) {
814 Some(1) => Some(&frame.state),
815 Some(2) => Some(&frame.next),
816 Some(3) => Some(&frame.locals),
817 _ => None,
818 };
819 if let Some(values) = values {
820 return Ok(values.clone());
821 }
822 }
823 Err(rejected("stale or unknown variables handle"))
824 }
825 pub fn evaluate(&self, frame: u64, expression: &str) -> Result<Value, DebugError> {
831 let (values, compat_tlc) = {
832 let state = self.control.lock();
833 let snapshot = state
834 .snapshot
835 .as_ref()
836 .ok_or_else(|| rejected("producer is not stopped"))?;
837 let frame = snapshot
838 .frames
839 .iter()
840 .find(|candidate| candidate.id == frame)
841 .ok_or_else(|| rejected("stale or unknown frame handle"))?;
842 let mut values = HashMap::new();
843 for value in frame.state.iter().chain(&frame.locals) {
844 if let Some(name) = value["name"].as_str() {
845 values.insert(name.to_owned(), value["scalar"].clone());
846 }
847 }
848 (values, state.compat_tlc)
849 };
850 evaluate_scalar(expression, &values, compat_tlc)
851 }
852
853 pub fn source(&self, reference: usize) -> Result<String, DebugError> {
858 let state = self.control.lock();
859 let map = state
860 .map
861 .as_ref()
862 .ok_or_else(|| rejected("compiled map is not ready"))?;
863 Ok(map
864 .files
865 .get(
866 reference
867 .checked_sub(1)
868 .ok_or_else(|| rejected("invalid source reference"))?,
869 )
870 .ok_or_else(|| rejected("unknown source reference"))?
871 .source
872 .to_string())
873 }
874 pub fn terminate(&self) {
876 let mut state = self.control.lock();
877 state.terminated = true;
878 state.snapshot = None;
879 self.control.changed.notify_all();
880 }
881 pub fn finish(&mut self) -> Result<CheckReport, DebugError> {
886 if !self
887 .worker
888 .as_ref()
889 .is_some_and(std::thread::JoinHandle::is_finished)
890 && self.control.lock().completion.is_none()
891 {
892 return Err(rejected(
893 "checker has not returned; continue or terminate before joining",
894 ));
895 }
896 let worker = self
897 .worker
898 .take()
899 .ok_or_else(|| rejected("checker already joined"))?;
900 worker
901 .join()
902 .map_err(|_| rejected("debugger checking thread failed"))?
903 .map_err(|error| DebugError(error.to_string()))
904 }
905}
906impl Drop for Session {
907 fn drop(&mut self) {
908 if self.worker.is_some() {
909 self.terminate();
910 }
911 }
912}
913
914#[allow(
915 clippy::too_many_lines,
916 reason = "admit bounded captured scalar grammar before isolated native compile/evaluation"
917)]
918fn evaluate_scalar(
919 expression: &str,
920 values: &HashMap<String, Value>,
921 compat_tlc: bool,
922) -> Result<Value, DebugError> {
923 use dive_core::compile::{Handoff, Role};
924 if expression.is_empty() || expression.len() > 1024 {
925 return Err(rejected("debugger expression byte bound"));
926 }
927 let operators = [
928 "+", "-", "*", "\\div", "%", "=", "#", "/=", "<", ">", "<=", ">=", "/\\", "\\/", "~", "=>",
929 "<=>", "(", ")", "TRUE", "FALSE",
930 ];
931 let tokens = dive_syntax::tokens::tokenize_spec(expression);
932 if tokens.len() > 256 {
933 return Err(rejected("debugger expression token bound"));
934 }
935 for token in &tokens {
936 if token.error.is_some() {
937 return Err(rejected("invalid debugger expression token"));
938 }
939 if token.kind.is_trivia() {
940 continue;
941 }
942 let word = &expression[token.range];
943 let integer = word.len() <= 10 && word.bytes().all(|byte| byte.is_ascii_digit());
944 let known = values
945 .get(word)
946 .is_some_and(|value| value.is_i64() || value.is_boolean());
947 if !integer && !known && !operators.contains(&word) {
948 return Err(rejected(
949 "debugger evaluation admits only captured integer/boolean names and bounded pure operators",
950 ));
951 }
952 }
953 let mut source = String::from("---- MODULE DebuggerExpression ----\nEXTENDS Integers\n");
954 let mut names = values
955 .keys()
956 .filter(|name| {
957 tokens
958 .iter()
959 .any(|token| &expression[token.range] == name.as_str())
960 })
961 .collect::<Vec<_>>();
962 names.sort();
963 for name in names {
964 let value = &values[name];
965 let literal = if let Some(value) = value.as_i64() {
966 value.to_string()
967 } else if let Some(value) = value.as_bool() {
968 if value { "TRUE" } else { "FALSE" }.into()
969 } else {
970 continue;
971 };
972 let _ = writeln!(source, "{name} == {literal}");
973 }
974 let mut result_name = String::from("DIVE_debug_result");
975 while values.contains_key(&result_name) {
976 result_name.push('_');
977 }
978 let _ = write!(source, "{result_name} == ({expression})\n====\n");
979 let analysis = dive_sema::analyze_source(
980 "DebuggerExpression.tla",
981 &source,
982 &dive_sema::Options::default(),
983 );
984 let ir = dive_ir::lower(&analysis).map_err(|error| DebugError(error.to_string()))?;
985 let definition = ir
986 .root_def(&result_name)
987 .ok_or_else(|| rejected("debugger expression definition"))?;
988 let eval = if compat_tlc {
989 dive_eval::Options::tlc()
990 } else {
991 dive_eval::Options::dive()
992 };
993 let store = Arc::new(dive_core::Store::with_semantics(
994 true,
995 crate::core_engine::semantics(&eval),
996 ));
997 let h = Handoff {
998 ir: &ir,
999 ctx: eval.ctx,
1000 action_composition: eval.action_composition == dive_eval::ActionComposition::Tla,
1001 constants: Vec::new(),
1002 redirects: HashMap::new(),
1003 std_redirects: HashMap::new(),
1004 precomputed: HashMap::new(),
1005 overrides: std::collections::HashSet::new(),
1006 deferred: std::collections::BTreeSet::new(),
1007 startup_evaluator: None,
1008 assumptions: Vec::new(),
1009 init: Vec::new(),
1010 next: Vec::new(),
1011 invariants: vec![Role {
1012 name: result_name,
1013 expr: ir.def(definition).body,
1014 def: definition,
1015 slots: Vec::new(),
1016 substs: Vec::new(),
1017 }],
1018 constraints: Vec::new(),
1019 action_constraints: Vec::new(),
1020 implied_inits: Vec::new(),
1021 implied_actions: Vec::new(),
1022 check_deadlock: false,
1023 symmetry: Vec::new(),
1024 view: None,
1025 };
1026 let opts = dive_core::Opts {
1027 fold: false,
1028 memo: false,
1029 step_memo: false,
1030 primed_memo: false,
1031 ..dive_core::Opts::default()
1032 };
1033 let plan = dive_core::compile(&h, Arc::clone(&store), opts)
1034 .map_err(|error| DebugError(error.to_string()))?;
1035 let check = plan
1036 .invariants
1037 .first()
1038 .ok_or_else(|| rejected("debugger expression plan"))?;
1039 let part = check
1040 .conjuncts
1041 .first()
1042 .ok_or_else(|| rejected("debugger expression root"))?;
1043 let mut machine = Machine::new(store, 0, opts, dive_core::memo::Memo::default());
1044 machine.set_fuel(4096);
1045 let old = machine.enter(check.frame);
1046 let result = machine
1047 .eval(&plan.code, part.p)
1048 .map_err(|error| DebugError(error.to_string()));
1049 machine.leave(old);
1050 let value = result?;
1051 let (text, kind, scalar) = scalar(value, &machine);
1052 if scalar.is_none() {
1053 return Err(rejected(
1054 "debugger expression produced an unproved scalar representation",
1055 ));
1056 }
1057 Ok(json!({"result":text,"type":kind,"variablesReference":0,"scalar":scalar}))
1058}