cairo_lang_executable/
executable.rs

1use cairo_lang_casm::assembler::AssembledCairoProgram;
2use cairo_lang_casm::casm;
3use cairo_vm::types::builtin_name::BuiltinName;
4use itertools::chain;
5use serde::{Deserialize, Serialize};
6
7use crate::compile::CompiledFunction;
8
9/// Structure to hold the executable representation of a program.
10#[derive(Debug, Clone, Serialize, Deserialize)]
11pub struct Executable {
12    /// The bytecode of the program.
13    pub program: AssembledCairoProgram,
14    /// The available entrypoints for the program.
15    pub entrypoints: Vec<ExecutableEntryPoint>,
16}
17
18impl Executable {
19    /// Create a new executable program from a compiled function.
20    pub fn new(compiled: CompiledFunction) -> Self {
21        let non_returning_header = casm! {
22            ap += (compiled.wrapper.builtins.len());
23            call rel 4;
24            jmp rel 0;
25        };
26        Self {
27            program: compiled.program.assemble_ex(
28                chain!(&non_returning_header.instructions, &compiled.wrapper.header),
29                &compiled.wrapper.footer,
30            ),
31            entrypoints: vec![
32                ExecutableEntryPoint {
33                    builtins: compiled.wrapper.builtins.clone(),
34                    offset: 0,
35                    kind: EntryPointKind::Standalone,
36                },
37                ExecutableEntryPoint {
38                    builtins: compiled.wrapper.builtins,
39                    offset: non_returning_header.current_code_offset,
40                    kind: EntryPointKind::Bootloader,
41                },
42            ],
43        }
44    }
45}
46
47/// Information about an executable entrypoint.
48#[derive(Debug, Clone, Serialize, Deserialize)]
49pub struct ExecutableEntryPoint {
50    /// The used builtins of the function.
51    pub builtins: Vec<BuiltinName>,
52    /// The offset of the entrypoint in the bytecode.
53    pub offset: usize,
54    /// The kind of the entrypoint.
55    pub kind: EntryPointKind,
56}
57
58/// The kind of an entrypoint.
59#[derive(Debug, Clone, Serialize, Deserialize)]
60pub enum EntryPointKind {
61    /// Entrypoint is for running it using a bootloader.
62    ///
63    /// The entrypoint is a function, ending with a `ret`, expecting the builtins as its parameters.
64    Bootloader,
65    /// Entrypoint is for running this executable as a standalone program.
66    ///
67    /// The entrypoint starts with `ap += <builtins.len()>` and expected the builtins to be injected
68    /// there, and ends with an infinite loop.
69    Standalone,
70}