miden_processor/fast/mod.rs
1use alloc::{
2 boxed::Box,
3 collections::{BTreeMap, BTreeSet},
4 sync::Arc,
5 vec,
6 vec::Vec,
7};
8use core::{cmp::min, ops::ControlFlow};
9
10use miden_air_definitions::vm::trace::RowIndex;
11use miden_core::{
12 EMPTY_WORD, Felt, WORD_SIZE, Word, ZERO,
13 deferred::{DeferredState, Digest, PrecompileWitness},
14 mast::{ExecutableMastForest, MastForest},
15 program::{MIN_STACK_DEPTH, Program, StackInputs, StackOutputs},
16 utils::range,
17};
18use miden_mast_package::{
19 Package,
20 debug_info::{DebugSourceNodeId, PackageDebugInfo},
21};
22
23use crate::{
24 AdviceInputs, AdviceProvider, ContextId, ExecutionError, ExecutionOptions, LoadedMastForest,
25 ProcessorState,
26 advice::AdviceError,
27 continuation_stack::{Continuation, ContinuationStack},
28 errors::MapExecErrNoCtx,
29 operation::OperationError,
30 tracer::{OperationHelperRegisters, Tracer},
31};
32
33mod basic_block;
34mod debug;
35mod execution_api;
36mod external;
37mod memory;
38mod operation;
39mod step;
40
41pub use basic_block::SystemEventError;
42pub use debug::{DebugCallFrame, DebugCallFrameResolver, DebugFrameOrigin};
43pub use memory::Memory;
44pub(crate) use step::BreakReason;
45pub use step::ResumeContext;
46
47#[cfg(test)]
48mod tests;
49
50// CONSTANTS
51// ================================================================================================
52
53/// The initial size of the stack buffer.
54///
55/// Note: This value is much larger than it needs to be for the majority of programs. However, some
56/// existing programs need it, so we're forced to push it up (though this should be double-checked).
57/// At this high a value, we're starting to see some performance degradation on benchmarks. For
58/// example, the blake3 benchmark went from 285 MHz to 250 MHz (~10% degradation). Perhaps a better
59/// solution would be to make this value much smaller (~1000), and then fallback to a `Vec` if the
60/// stack overflows.
61const INITIAL_STACK_BUFFER_SIZE: usize = 6850;
62
63/// The initial position of the top of the stack in the stack buffer.
64///
65/// We place this value close to 0 because if a program hits the limit, it's much more likely to hit
66/// the upper bound than the lower bound, since hitting the lower bound only occurs when you drop
67/// 0's that were generated automatically to keep the stack depth at 16. In practice, if this
68/// occurs, it is most likely a bug.
69const INITIAL_STACK_TOP_IDX: usize = 250;
70
71/// Default maximum operand stack depth preserving the previous fixed-buffer ceiling.
72const DEFAULT_MAX_STACK_DEPTH: usize =
73 INITIAL_STACK_BUFFER_SIZE - INITIAL_STACK_TOP_IDX - 1 + MIN_STACK_DEPTH;
74
75const _: [(); 1] =
76 [(); (ExecutionOptions::DEFAULT_MAX_STACK_DEPTH == DEFAULT_MAX_STACK_DEPTH) as usize];
77
78/// The stack buffer index where the logical operand stack starts after reset/recenter.
79const STACK_BUFFER_BASE_IDX: usize = INITIAL_STACK_TOP_IDX - MIN_STACK_DEPTH;
80
81// FAST PROCESSOR
82// ================================================================================================
83
84/// A fast processor which doesn't generate any trace.
85///
86/// This processor is designed to be as fast as possible. Hence, it only keeps track of the current
87/// state of the processor (i.e. the stack, current clock cycle, current memory context, and free
88/// memory pointer).
89///
90/// # Stack Management
91/// A few key points about how the stack was designed for maximum performance:
92///
93/// - The stack starts with a fixed buffer size defined by `INITIAL_STACK_BUFFER_SIZE`.
94/// - This was observed to increase performance by at least 2x compared to using a `Vec` with
95/// `push()` & `pop()`.
96/// - We track the stack top and bottom using indices `stack_top_idx` and `stack_bot_idx`,
97/// respectively.
98/// - Since we are using a fixed-size buffer, we need to ensure that stack buffer accesses are not
99/// out of bounds. Naively, we could check for this on every access. However, every operation
100/// alters the stack depth by a predetermined amount, allowing us to precisely determine the
101/// minimum number of operations required to reach a stack buffer boundary, whether at the top or
102/// bottom.
103/// - For example, if the stack top is 10 elements away from the top boundary, and the stack
104/// bottom is 15 elements away from the bottom boundary, then we can safely execute 10
105/// operations that modify the stack depth with no bounds check.
106/// - When switching contexts (e.g., during a call or syscall), all elements past the first 16 are
107/// stored in `stack_overflow_save_stack`, and the stack is truncated to 16 elements. They will be
108/// restored when returning from the call or syscall.
109///
110/// # Clock Cycle Management
111/// - The clock cycle (`clk`) is managed in the same way as in `Process`. That is, it is incremented
112/// by 1 for every row that `Process` adds to the main trace.
113/// - It is important to do so because the clock cycle is used to determine the context ID for
114/// new execution contexts when using `call` or `dyncall`.
115#[derive(Debug)]
116pub struct FastProcessor {
117 /// The stack is stored in reverse order, so that the last element is at the top of the stack.
118 stack: Box<[Felt]>,
119 /// The index of the top of the stack.
120 stack_top_idx: usize,
121 /// The index of the bottom of the stack.
122 stack_bot_idx: usize,
123
124 /// The current clock cycle.
125 clk: RowIndex,
126
127 /// The current context ID.
128 ctx: ContextId,
129
130 /// The hash of the function that called into the current context, or `[ZERO, ZERO, ZERO,
131 /// ZERO]` if we are in the first context (i.e. when `system_call_state_stack` is empty).
132 caller_hash: Word,
133
134 /// The advice provider to be used during execution.
135 advice: AdviceProvider,
136
137 /// MAST forests loaded during this execution, indexed by their local procedure digests.
138 loaded_mast_forests: BTreeMap<Word, LoadedMastForest>,
139
140 /// Commitments of MAST forests whose advice maps have been merged into the advice provider.
141 merged_mast_forests: BTreeSet<Word>,
142
143 /// A map from (context_id, word_address) to the word stored starting at that memory location.
144 memory: Memory,
145
146 /// Stack of saved system state, used when starting a new execution context (from a `call`,
147 /// `syscall` or `dyncall`) to keep track of the previous `(ctx, caller_hash)` upon return.
148 /// Pushed in lockstep with `stack_overflow_save_stack`.
149 system_call_state_stack: Vec<SystemCallState>,
150
151 /// Stack of saved operand-stack overflows, used when starting a new execution context to keep
152 /// the elements that lived past the top 16 of the previous context. Pushed in lockstep with
153 /// `system_call_state_stack`.
154 stack_overflow_save_stack: Vec<Vec<Felt>>,
155
156 /// Running total of the number of field elements currently held across all suspended overflow
157 /// segments in `stack_overflow_save_stack`. Maintained in lockstep with that stack so the
158 /// aggregate operand-stack depth (active context plus all suspended overflow) can be bounded
159 /// by `ExecutionOptions::max_stack_depth()` in O(1) without summing every saved segment on
160 /// each push. See [`Self::ensure_stack_capacity_for_push`].
161 saved_overflow_len: usize,
162
163 /// Options for execution, including cycle limits, stack limits, advice map limits, and the
164 /// size of core trace fragments during execution.
165 options: ExecutionOptions,
166
167 /// Eager deferred evaluation state retained only while execution is running.
168 deferred_state: DeferredState,
169
170 /// Package debug information configured through [`ProgramExecutor`](crate::ProgramExecutor).
171 pub(crate) package_debug_info: Option<PackageDebugInfo>,
172
173 /// Entrypoint source node configured through [`ProgramExecutor`](crate::ProgramExecutor).
174 pub(crate) entrypoint_source_node: Option<DebugSourceNodeId>,
175}
176
177impl FastProcessor {
178 /// Packages the processor state after successful execution into a public result type.
179 #[inline(always)]
180 fn into_execution_output(self, stack: StackOutputs) -> Result<ExecutionOutput, ExecutionError> {
181 let precompile_root = self.deferred_state.root();
182 let precompile_witness = self
183 .deferred_state
184 .into_witness(self.options.verification_precompile_limits())
185 .map_err(OperationError::from)
186 .map_exec_err_no_ctx()?;
187 Ok(ExecutionOutput {
188 stack,
189 advice: self.advice,
190 memory: self.memory,
191 precompile_root,
192 precompile_witness,
193 })
194 }
195
196 /// Converts the terminal result of a full execution run into [`ExecutionOutput`].
197 #[inline(always)]
198 fn execution_result_from_flow(
199 flow: ControlFlow<BreakReason<Arc<MastForest>>, StackOutputs>,
200 processor: Self,
201 ) -> Result<ExecutionOutput, ExecutionError> {
202 match flow {
203 ControlFlow::Continue(stack_outputs) => processor.into_execution_output(stack_outputs),
204 ControlFlow::Break(break_reason) => match break_reason {
205 BreakReason::Err(err) => Err(err),
206 BreakReason::Stopped(_) => {
207 unreachable!("Execution never stops prematurely with NeverStopper")
208 },
209 },
210 }
211 }
212
213 /// Converts a testing-only execution result into stack outputs.
214 #[cfg(any(test, feature = "testing"))]
215 #[inline(always)]
216 fn stack_result_from_flow(
217 flow: ControlFlow<BreakReason<Arc<MastForest>>, StackOutputs>,
218 ) -> Result<StackOutputs, ExecutionError> {
219 match flow {
220 ControlFlow::Continue(stack_outputs) => Ok(stack_outputs),
221 ControlFlow::Break(break_reason) => match break_reason {
222 BreakReason::Err(err) => Err(err),
223 BreakReason::Stopped(_) => {
224 unreachable!("Execution never stops prematurely with NeverStopper")
225 },
226 },
227 }
228 }
229
230 // CONSTRUCTORS
231 // ----------------------------------------------------------------------------------------------
232
233 /// Creates a new `FastProcessor` instance with the given stack inputs.
234 ///
235 /// By default, advice inputs are empty and execution options use their defaults.
236 ///
237 /// # Example
238 /// ```ignore
239 /// use miden_processor::FastProcessor;
240 ///
241 /// let processor = FastProcessor::new(stack_inputs)
242 /// .with_advice(advice_inputs)
243 /// .expect("advice inputs should fit advice map limits");
244 /// ```
245 ///
246 /// When using non-default advice map limits, prefer [`Self::new_with_options`] so the advice
247 /// inputs are validated against the intended execution options.
248 pub fn new(stack_inputs: StackInputs) -> Self {
249 Self::new_with_options(stack_inputs, AdviceInputs::default(), ExecutionOptions::default())
250 .expect("default processor initialization should fit default execution limits")
251 }
252
253 /// Sets the advice inputs for the processor.
254 ///
255 /// Advice inputs are loaded into the live advice provider immediately and are validated against
256 /// the processor's current [`ExecutionOptions`]. If the advice map needs non-default limits,
257 /// construct the processor with [`Self::new_with_options`] or call [`Self::with_options`]
258 /// before calling this method.
259 pub fn with_advice(mut self, advice_inputs: AdviceInputs) -> Result<Self, AdviceError> {
260 self.advice = AdviceProvider::new(advice_inputs, &self.options)?;
261 Ok(self)
262 }
263
264 /// Sets the execution options for the processor.
265 ///
266 /// Existing advice inputs are revalidated against the new options before they are applied. To
267 /// load advice inputs that require non-default advice map limits, call this before
268 /// [`Self::with_advice`] or use [`Self::new_with_options`]. The installed precompile registry
269 /// and any accumulated deferred state are preserved. Execution precompile limits cannot be
270 /// lowered below work already consumed by that state.
271 pub fn with_options(mut self, options: ExecutionOptions) -> Result<Self, AdviceError> {
272 self.advice.set_options(&options)?;
273 self.memory.set_max_elements(options.max_memory_elements());
274 self.deferred_state
275 .set_execution_limits(options.execution_precompile_limits().clone())
276 .map_err(AdviceError::DeferredStateConfigurationFailed)?;
277 self.options = options;
278 Ok(self)
279 }
280
281 /// Constructor for creating a `FastProcessor` with all options specified at once.
282 ///
283 /// For a more fluent API, consider using `FastProcessor::new()` with builder methods.
284 pub fn new_with_options(
285 stack_inputs: StackInputs,
286 advice_inputs: AdviceInputs,
287 options: ExecutionOptions,
288 ) -> Result<Self, AdviceError> {
289 let stack_top_idx = INITIAL_STACK_TOP_IDX;
290 let stack = {
291 // Note: we use `Vec::into_boxed_slice()` here, since `Box::new([T; N])` first allocates
292 // the array on the stack, and then moves it to the heap. This might cause a
293 // stack overflow on some systems.
294 let mut stack = vec![ZERO; INITIAL_STACK_BUFFER_SIZE].into_boxed_slice();
295
296 // Copy inputs in reverse order so first element ends up at top of stack
297 for (i, &input) in stack_inputs.iter().enumerate() {
298 stack[stack_top_idx - 1 - i] = input;
299 }
300 stack
301 };
302
303 Ok(Self {
304 advice: AdviceProvider::new(advice_inputs, &options)?,
305 loaded_mast_forests: BTreeMap::new(),
306 merged_mast_forests: BTreeSet::new(),
307 stack,
308 stack_top_idx,
309 stack_bot_idx: stack_top_idx - MIN_STACK_DEPTH,
310 clk: 0_u32.into(),
311 ctx: 0_u32.into(),
312 caller_hash: EMPTY_WORD,
313 memory: Memory::new(options.max_memory_elements()),
314 system_call_state_stack: Vec::new(),
315 stack_overflow_save_stack: Vec::new(),
316 saved_overflow_len: 0,
317 deferred_state: DeferredState::new(
318 Arc::new(miden_precompiles::registry()),
319 options.execution_precompile_limits().clone(),
320 )
321 .map_err(AdviceError::DeferredStateConfigurationFailed)?,
322 package_debug_info: None,
323 entrypoint_source_node: None,
324 options,
325 })
326 }
327
328 /// Returns the resume context to be used with the first call to `step_sync()`.
329 ///
330 /// This function asserts that `package` is of executable type - callers should ensure that it
331 /// is before calling.
332 pub fn get_initial_resume_context_for_package(
333 &mut self,
334 package: Arc<Package>,
335 ) -> Result<ResumeContext, ExecutionError> {
336 let program = package.unwrap_program();
337 let package_debug_info = package.debug_info()?.map(Arc::new);
338 let current_forest = program.mast_forest().clone();
339 self.advice.extend_map(current_forest.advice_map()).map_exec_err_no_ctx()?;
340
341 let entrypoint_source_node_id = package.entrypoint_source_node();
342 let continuation_stack = if let Some(debug_info) = package_debug_info.as_deref() {
343 Self::source_aware_continuation_stack(&program, debug_info, entrypoint_source_node_id)?
344 } else {
345 ContinuationStack::new(&program)
346 };
347
348 Ok(ResumeContext {
349 current_forest,
350 continuation_stack,
351 kernel: program.kernel().clone(),
352 package_debug_info,
353 inline_call_contexts: Vec::new(),
354 })
355 }
356
357 /// Returns the resume context to be used with the first call to `step_sync()`.
358 pub fn get_initial_resume_context(
359 &mut self,
360 program: &Program,
361 ) -> Result<ResumeContext, ExecutionError> {
362 self.advice
363 .extend_map(program.mast_forest().advice_map())
364 .map_exec_err_no_ctx()?;
365
366 Ok(ResumeContext {
367 current_forest: program.mast_forest().clone(),
368 continuation_stack: ContinuationStack::new(program),
369 kernel: program.kernel().clone(),
370 package_debug_info: None,
371 inline_call_contexts: Vec::new(),
372 })
373 }
374
375 // ACCESSORS
376 // -------------------------------------------------------------------------------------------
377
378 /// Returns the deferred witness accumulated during execution.
379 #[inline(always)]
380 pub fn deferred_state(&self) -> &DeferredState {
381 &self.deferred_state
382 }
383
384 #[inline(always)]
385 pub(super) fn deferred_state_mut(&mut self) -> &mut DeferredState {
386 &mut self.deferred_state
387 }
388
389 /// Returns the size of the stack.
390 #[inline(always)]
391 fn stack_size(&self) -> usize {
392 self.stack_top_idx - self.stack_bot_idx
393 }
394
395 /// Returns the stack, such that the top of the stack is at the last index of the returned
396 /// slice.
397 pub fn stack(&self) -> &[Felt] {
398 &self.stack[self.stack_bot_idx..self.stack_top_idx]
399 }
400
401 /// Returns the top 16 elements of the stack.
402 pub fn stack_top(&self) -> &[Felt] {
403 &self.stack[self.stack_top_idx - MIN_STACK_DEPTH..self.stack_top_idx]
404 }
405
406 /// Returns a mutable reference to the top 16 elements of the stack.
407 pub fn stack_top_mut(&mut self) -> &mut [Felt] {
408 &mut self.stack[self.stack_top_idx - MIN_STACK_DEPTH..self.stack_top_idx]
409 }
410
411 /// Returns the element on the stack at index `idx`.
412 ///
413 /// This method is only meant to be used to access the stack top by operation handlers, and
414 /// system event handlers.
415 ///
416 /// # Preconditions
417 /// - `idx` must be less than or equal to 15.
418 #[inline(always)]
419 pub fn stack_get(&self, idx: usize) -> Felt {
420 self.stack[self.stack_top_idx - idx - 1]
421 }
422
423 /// Same as [`Self::stack_get()`], but returns [`ZERO`] if `idx` falls below index 0 in the
424 /// stack buffer.
425 ///
426 /// Use this instead of `stack_get()` when `idx` may exceed 15.
427 #[inline(always)]
428 pub fn stack_get_safe(&self, idx: usize) -> Felt {
429 if idx < self.stack_top_idx {
430 self.stack[self.stack_top_idx - idx - 1]
431 } else {
432 ZERO
433 }
434 }
435
436 /// Mutable variant of `stack_get()`.
437 ///
438 /// This method is only meant to be used to access the stack top by operation handlers, and
439 /// system event handlers.
440 ///
441 /// # Preconditions
442 /// - `idx` must be less than or equal to 15.
443 #[inline(always)]
444 pub fn stack_get_mut(&mut self, idx: usize) -> &mut Felt {
445 &mut self.stack[self.stack_top_idx - idx - 1]
446 }
447
448 /// Returns the word on the stack starting at index `start_idx` in "stack order".
449 ///
450 /// For `start_idx=0` the top element of the stack will be at position 0 in the word.
451 ///
452 /// For example, if the stack looks like this:
453 ///
454 /// top bottom
455 /// v v
456 /// a | b | c | d | e | f | g | h | i | j | k | l | m | n | o | p
457 ///
458 /// Then
459 /// - `stack_get_word(0)` returns `[a, b, c, d]`,
460 /// - `stack_get_word(1)` returns `[b, c, d, e]`,
461 /// - etc.
462 ///
463 /// This method is only meant to be used to access the stack top by operation handlers, and
464 /// system event handlers.
465 ///
466 /// # Preconditions
467 /// - `start_idx` must be less than or equal to 12.
468 #[inline(always)]
469 pub fn stack_get_word(&self, start_idx: usize) -> Word {
470 // Ensure we have enough elements to form a complete word
471 debug_assert!(
472 start_idx + WORD_SIZE <= self.stack_depth() as usize,
473 "Not enough elements on stack to read word starting at index {start_idx}"
474 );
475
476 let word_start_idx = self.stack_top_idx - start_idx - WORD_SIZE;
477 let mut result: [Felt; WORD_SIZE] =
478 self.stack[range(word_start_idx, WORD_SIZE)].try_into().unwrap();
479 // Reverse so top of stack (idx 0) goes to word[0]
480 result.reverse();
481 result.into()
482 }
483
484 /// Same as [`Self::stack_get_word()`], but returns [`ZERO`] for any element that falls below
485 /// index 0 in the stack buffer.
486 ///
487 /// Use this instead of `stack_get_word()` when `start_idx + WORD_SIZE` may exceed
488 /// `stack_top_idx`.
489 #[inline(always)]
490 pub fn stack_get_word_safe(&self, start_idx: usize) -> Word {
491 let buf_end = self.stack_top_idx.saturating_sub(start_idx);
492 let buf_start = self.stack_top_idx.saturating_sub(start_idx.saturating_add(WORD_SIZE));
493 let num_elements_to_read_from_buf = buf_end - buf_start;
494
495 let mut result = [ZERO; WORD_SIZE];
496 if num_elements_to_read_from_buf == WORD_SIZE {
497 result.copy_from_slice(&self.stack[range(buf_start, WORD_SIZE)]);
498 } else if num_elements_to_read_from_buf > 0 {
499 let offset = WORD_SIZE - num_elements_to_read_from_buf;
500 result[offset..]
501 .copy_from_slice(&self.stack[range(buf_start, num_elements_to_read_from_buf)]);
502 }
503 result.reverse();
504
505 result.into()
506 }
507
508 /// Returns the number of elements on the stack in the current context.
509 #[inline(always)]
510 pub fn stack_depth(&self) -> u32 {
511 (self.stack_top_idx - self.stack_bot_idx) as u32
512 }
513
514 /// Returns a reference to the processor's memory.
515 pub fn memory(&self) -> &Memory {
516 &self.memory
517 }
518
519 /// Consumes the processor and returns the advice provider and memory.
520 pub fn into_parts(self) -> (AdviceProvider, Memory) {
521 (self.advice, self.memory)
522 }
523
524 /// Returns a reference to the execution options.
525 pub fn execution_options(&self) -> &ExecutionOptions {
526 &self.options
527 }
528
529 /// Returns a narrowed interface for reading and updating the processor state.
530 #[inline(always)]
531 pub fn state(&self) -> ProcessorState<'_> {
532 ProcessorState { processor: self }
533 }
534
535 // MUTATORS
536 // -------------------------------------------------------------------------------------------
537
538 /// Writes an element to the stack at the given index.
539 #[inline(always)]
540 pub fn stack_write(&mut self, idx: usize, element: Felt) {
541 self.stack[self.stack_top_idx - idx - 1] = element
542 }
543
544 /// Writes a word to the stack starting at the given index.
545 ///
546 /// `word[0]` goes to stack position start_idx (top), `word[1]` to start_idx+1, etc.
547 #[inline(always)]
548 pub fn stack_write_word(&mut self, start_idx: usize, word: &Word) {
549 debug_assert!(start_idx <= MIN_STACK_DEPTH - WORD_SIZE);
550
551 let word_start_idx = self.stack_top_idx - start_idx - 4;
552 let mut source: [Felt; WORD_SIZE] = (*word).into();
553 // Reverse so word[0] ends up at the top of stack (highest internal index)
554 source.reverse();
555 self.stack[range(word_start_idx, WORD_SIZE)].copy_from_slice(&source)
556 }
557
558 /// Swaps the elements at the given indices on the stack.
559 #[inline(always)]
560 pub fn stack_swap(&mut self, idx1: usize, idx2: usize) {
561 let a = self.stack_get(idx1);
562 let b = self.stack_get(idx2);
563 self.stack_write(idx1, b);
564 self.stack_write(idx2, a);
565 }
566
567 /// Increments the stack top pointer by 1.
568 ///
569 /// The bottom of the stack is never affected by this operation.
570 #[inline(always)]
571 fn increment_stack_size(&mut self) {
572 self.stack_top_idx += 1;
573 }
574
575 /// Ensures the internal stack storage can accommodate one additional logical stack element.
576 ///
577 /// The operand stack depth limit is the semantic resource bound; the buffer is only an
578 /// implementation detail. We therefore check the logical depth before allocating so a program
579 /// cannot force memory growth beyond `ExecutionOptions::max_stack_depth()`. When storage does
580 /// need to grow, it grows geometrically and remains heap-allocated as a boxed slice. A
581 /// `SmallVec` would put a useful inline buffer inside `FastProcessor`, and preallocating the
582 /// full limit would penalize ordinary programs. This policy is performance-sensitive and should
583 /// be benchmarked against the fixed-buffer baseline.
584 ///
585 /// The depth that is checked is the *aggregate* operand-stack depth: the active context's depth
586 /// plus every element held in suspended overflow segments (`saved_overflow_len`). A `call`,
587 /// `dyncall`, or `syscall` context switch hides the caller's overflow in
588 /// `stack_overflow_save_stack` rather than freeing it, so checking only the active context
589 /// would let a program nest context switches to accumulate `O(call_depth *
590 /// max_stack_depth)` hidden operand-stack memory while every live frame stayed within the
591 /// limit. Because a context switch merely moves elements between the active stack and the
592 /// saved overflow (it never creates elements), the aggregate is conserved across switches
593 /// and only grows on a push, so enforcing the bound here is sufficient to cap total
594 /// operand-stack memory.
595 #[inline(always)]
596 fn ensure_stack_capacity_for_push(&mut self) -> Result<(), ExecutionError> {
597 let depth = self.stack_size() + self.saved_overflow_len + 1;
598 let max = self.options.max_stack_depth();
599 if depth > max {
600 return Err(ExecutionError::StackDepthLimitExceeded { depth, max });
601 }
602
603 if self.stack_top_idx >= self.stack.len() - 1 {
604 self.grow_stack_buffer(self.stack_top_idx + 2);
605 }
606
607 Ok(())
608 }
609
610 fn ensure_stack_capacity_for_top_idx(&mut self, top_idx: usize) {
611 if top_idx >= self.stack.len() {
612 self.grow_stack_buffer(top_idx + 1);
613 }
614 }
615
616 fn grow_stack_buffer(&mut self, requested_min_len: usize) {
617 // The maximum allocation is tied to the logical operand stack depth, not to the current
618 // buffer position. Using `stack_bot_idx` here would make the allocation ceiling drift when
619 // the live stack has moved away from the initial base.
620 let max_len = STACK_BUFFER_BASE_IDX
621 .saturating_add(self.options.max_stack_depth())
622 .saturating_add(1);
623 let live_len = self.stack_size();
624
625 // Growth also recenters the live stack at the normal base. This keeps future push/drop
626 // behavior close to the fixed-buffer layout and avoids carrying unused prefix cells into
627 // the new allocation. The extra slot is for the next checked push that triggered growth.
628 let recentered_min_len = STACK_BUFFER_BASE_IDX.saturating_add(live_len).saturating_add(2);
629 debug_assert!(recentered_min_len <= max_len);
630
631 // Allocation growth is based on the stack's post-recentered live range, not the previous
632 // buffer length. The `requested_min_len` may be beyond the allocation cap when a shallow
633 // context is still positioned near the end of the old buffer; recentering the live stack is
634 // what makes that valid. The VM-visible requirements are that the live stack is restored at
635 // `STACK_BUFFER_BASE_IDX`, the post-recentered push slot is available, and allocation stays
636 // capped by the configured stack depth. The allocation size can differ from the previous
637 // doubling policy: normal push growth may allocate a couple of extra cells because of the
638 // spare push slot, while restoring a deep caller from a shallow callee may allocate only
639 // the requested restored range instead of doubling the old buffer. That smaller
640 // restore allocation is intentional, but it means future pushes can grow again
641 // sooner and should stay covered by benchmarks.
642 let new_len = recentered_min_len.saturating_mul(2).max(requested_min_len).min(max_len);
643 debug_assert!(new_len <= max_len);
644
645 let mut new_stack = vec![ZERO; new_len].into_boxed_slice();
646 let new_stack_bot_idx = STACK_BUFFER_BASE_IDX;
647 let new_stack_top_idx = new_stack_bot_idx + live_len;
648
649 // Only the active stack range carries VM state. Prefix/suffix cells are scratch storage and
650 // stay zeroed, which keeps growth proportional to the live depth instead of the old buffer
651 // length.
652 new_stack[new_stack_bot_idx..new_stack_top_idx]
653 .copy_from_slice(&self.stack[self.stack_bot_idx..self.stack_top_idx]);
654
655 self.stack = new_stack;
656 self.stack_bot_idx = new_stack_bot_idx;
657 self.stack_top_idx = new_stack_top_idx;
658 }
659
660 /// Decrements the stack top pointer by 1.
661 ///
662 /// The bottom of the stack is only decremented in cases where the stack depth would become less
663 /// than 16.
664 #[inline(always)]
665 fn decrement_stack_size(&mut self) {
666 if self.stack_top_idx == MIN_STACK_DEPTH {
667 // We no longer have any room in the stack buffer to decrement the stack size (which
668 // would cause the `stack_bot_idx` to go below 0). We therefore reset the stack to its
669 // original position.
670 self.reset_stack_in_buffer(INITIAL_STACK_TOP_IDX);
671 }
672
673 self.stack_top_idx -= 1;
674 self.stack_bot_idx = min(self.stack_bot_idx, self.stack_top_idx - MIN_STACK_DEPTH);
675 }
676
677 /// Resets the stack in the buffer to a new position, preserving the top 16 elements of the
678 /// stack.
679 ///
680 /// # Preconditions
681 /// - The stack is expected to have exactly 16 elements.
682 #[inline(always)]
683 fn reset_stack_in_buffer(&mut self, new_stack_top_idx: usize) {
684 debug_assert_eq!(self.stack_depth(), MIN_STACK_DEPTH as u32);
685
686 let new_stack_bot_idx = new_stack_top_idx - MIN_STACK_DEPTH;
687
688 // Copy stack to its new position
689 self.stack
690 .copy_within(self.stack_bot_idx..self.stack_top_idx, new_stack_bot_idx);
691
692 // Zero out stack below the new new_stack_bot_idx, since this is where overflow values
693 // come from, and are guaranteed to be ZERO. We don't need to zero out above
694 // `stack_top_idx`, since values there are never read before being written.
695 self.stack[0..new_stack_bot_idx].fill(ZERO);
696
697 // Update indices.
698 self.stack_bot_idx = new_stack_bot_idx;
699 self.stack_top_idx = new_stack_top_idx;
700 }
701}
702
703// EXECUTION OUTPUT
704// ===============================================================================================
705
706/// The output of a program execution, containing the state of the stack, advice provider, memory,
707/// and optional portable precompile witness at the end of execution.
708#[derive(Debug)]
709pub struct ExecutionOutput {
710 pub stack: StackOutputs,
711 pub advice: AdviceProvider,
712 pub memory: Memory,
713 pub precompile_root: Digest,
714 pub precompile_witness: Option<PrecompileWitness>,
715}
716
717impl ExecutionOutput {
718 /// Returns the deferred root accumulated during execution.
719 ///
720 /// This does not validate the witness's precompile computations.
721 pub fn precompile_root(&self) -> Digest {
722 self.precompile_root
723 }
724}
725
726// SYSTEM CALL STATE
727// ===============================================================================================
728
729/// The system-state half of a saved execution context.
730///
731/// Used to keep track of the `(ctx, caller_hash)` pair that needs to be restored upon return from a
732/// `call`, `syscall` or `dyncall`.
733#[derive(Debug)]
734pub(super) struct SystemCallState {
735 pub ctx: ContextId,
736 pub caller_hash: Word,
737}
738
739// NOOP TRACER
740// ================================================================================================
741
742/// A [Tracer] that does nothing.
743pub struct NoopTracer;
744
745impl Tracer for NoopTracer {
746 type Processor = FastProcessor;
747 type Forest = Arc<MastForest>;
748
749 #[inline(always)]
750 fn start_clock_cycle(
751 &mut self,
752 _processor: &FastProcessor,
753 _continuation: Continuation<Arc<MastForest>>,
754 _continuation_stack: &ContinuationStack<Arc<MastForest>>,
755 _current_forest: &Arc<MastForest>,
756 ) {
757 // do nothing
758 }
759
760 #[inline(always)]
761 fn finalize_clock_cycle(
762 &mut self,
763 _processor: &FastProcessor,
764 _op_helper_registers: OperationHelperRegisters,
765 _current_forest: &Arc<MastForest>,
766 ) -> Result<(), ExecutionError> {
767 // do nothing
768 Ok(())
769 }
770}