|
| 1 | +//! Profiling-instrumented run wrapper around [`AotContractExecutor::run`]. |
| 2 | +//! |
| 3 | +//! Available under the `with-libfunc-profiling` feature (gated at the `mod` |
| 4 | +//! declaration in `src/executor.rs`). |
| 5 | +
|
| 6 | +use std::sync::atomic::{AtomicU64, Ordering}; |
| 7 | +use std::sync::{Arc, Mutex}; |
| 8 | + |
| 9 | +use cairo_lang_sierra::program::Program; |
| 10 | +use starknet_types_core::felt::Felt; |
| 11 | + |
| 12 | +use crate::error::{Error, Result}; |
| 13 | +use crate::execution_result::ContractExecutionResult; |
| 14 | +use crate::executor::AotContractExecutor; |
| 15 | +use crate::metadata::profiler::{Profile, ProfilerBinding, ProfilerImpl, LIBFUNC_PROFILE}; |
| 16 | +use crate::starknet::StarknetSyscallHandler; |
| 17 | +use crate::utils::BuiltinCosts; |
| 18 | + |
| 19 | +/// Process-wide lock that serializes calls into [`AotContractExecutor::run_with_libfunc_profile`]. |
| 20 | +/// The profiler hot-swaps a process-global symbol (`cairo_native__profiler__profile_id`); |
| 21 | +/// concurrent callers would race on that write and on the [`LIBFUNC_PROFILE`] slot bookkeeping. |
| 22 | +static PROFILE_LOCK: Mutex<()> = Mutex::new(()); |
| 23 | + |
| 24 | +impl AotContractExecutor { |
| 25 | + /// Run the entrypoint with libfunc-level profiling instrumentation. |
| 26 | + /// |
| 27 | + /// Wraps [`AotContractExecutor::run`] with the bookkeeping the |
| 28 | + /// `with-libfunc-profiling` runtime needs: |
| 29 | + /// |
| 30 | + /// 1. Acquires [`PROFILE_LOCK`] so concurrent profile calls serialize on the |
| 31 | + /// global trace-id symbol. The lock is recovered if poisoned. |
| 32 | + /// 2. Looks up the executor's `cairo_native__profiler__profile_id` symbol. If |
| 33 | + /// absent (the .so was compiled without profiling instrumentation) the call |
| 34 | + /// returns an error before touching any global state. |
| 35 | + /// 3. Allocates a unique trace ID and inserts an empty `ProfilerImpl` slot in |
| 36 | + /// [`LIBFUNC_PROFILE`]; points the profile-id symbol at the new ID, saving |
| 37 | + /// the previous value. |
| 38 | + /// 4. Calls `run`. Per-statement samples accumulate in the slot via the runtime |
| 39 | + /// `push_stmt` callback. |
| 40 | + /// 5. Drains the slot. On success (and only on success) hands the resulting |
| 41 | + /// [`Profile`] to `on_profile`; on failure the callback is not invoked |
| 42 | + /// (partial profiles aren't meaningful). |
| 43 | + /// 6. A [`ProfilerGuard`] restores the previous trace ID and clears the slot on |
| 44 | + /// both the success and unwind paths. |
| 45 | + /// |
| 46 | + /// `program` must be the Sierra program this executor was compiled from; it's used |
| 47 | + /// by `get_profile` to map runtime libfunc IDs back to declarations. |
| 48 | + #[allow(clippy::too_many_arguments)] |
| 49 | + pub fn run_with_libfunc_profile<H, F>( |
| 50 | + &self, |
| 51 | + program: &Arc<Program>, |
| 52 | + selector: Felt, |
| 53 | + args: &[Felt], |
| 54 | + gas: u64, |
| 55 | + builtin_costs: Option<BuiltinCosts>, |
| 56 | + syscall_handler: H, |
| 57 | + on_profile: F, |
| 58 | + ) -> Result<ContractExecutionResult> |
| 59 | + where |
| 60 | + H: StarknetSyscallHandler, |
| 61 | + F: FnOnce(Profile), |
| 62 | + { |
| 63 | + // Serialize against concurrent profile calls. Recover from a poisoned lock -- |
| 64 | + // we don't have invariants on the protected state itself; the lock only gates |
| 65 | + // access to the global trace-id symbol. |
| 66 | + let _profile_lock = PROFILE_LOCK.lock().unwrap_or_else(|e| e.into_inner()); |
| 67 | + |
| 68 | + // Look up the profile-id symbol before touching any global state. If the |
| 69 | + // executor wasn't compiled with libfunc-profiling instrumentation, the |
| 70 | + // symbol is absent -- return a typed error rather than panicking. |
| 71 | + let trace_id_ptr = self |
| 72 | + .find_symbol_ptr(ProfilerBinding::ProfileId.symbol()) |
| 73 | + .ok_or_else(|| { |
| 74 | + Error::UnexpectedValue(format!( |
| 75 | + "AOT executor missing libfunc-profiling symbol `{}`; \ |
| 76 | + was the program compiled with libfunc-profiling enabled?", |
| 77 | + ProfilerBinding::ProfileId.symbol() |
| 78 | + )) |
| 79 | + })? |
| 80 | + .cast::<u64>(); |
| 81 | + |
| 82 | + static COUNTER: AtomicU64 = AtomicU64::new(0); |
| 83 | + let counter = COUNTER.fetch_add(1, Ordering::Relaxed); |
| 84 | + |
| 85 | + LIBFUNC_PROFILE |
| 86 | + .lock() |
| 87 | + .unwrap_or_else(|e| e.into_inner()) |
| 88 | + .insert(counter, ProfilerImpl::new()); |
| 89 | + |
| 90 | + // SAFETY: the pointer targets a memref-global emitted into the executor's |
| 91 | + // shared library; the executor outlives the call. `PROFILE_LOCK` serializes |
| 92 | + // us against any other writer, and the JIT/AOT code reads through the same |
| 93 | + // address. Reads/writes are aligned `u64`s. |
| 94 | + let old_trace_id = unsafe { *trace_id_ptr }; |
| 95 | + unsafe { |
| 96 | + *trace_id_ptr = counter; |
| 97 | + } |
| 98 | + |
| 99 | + let _guard = ProfilerGuard { |
| 100 | + trace_id_ptr, |
| 101 | + old_trace_id, |
| 102 | + counter, |
| 103 | + }; |
| 104 | + |
| 105 | + let result = self.run(selector, args, gas, builtin_costs, syscall_handler); |
| 106 | + |
| 107 | + // Drain the slot. `ProfilerGuard::drop` would also remove it; doing it here |
| 108 | + // means we hold the lock for the shortest time and can hand the profile to |
| 109 | + // the callback. Tolerate a poisoned mutex (we'd lose the profile, not state). |
| 110 | + let drained = LIBFUNC_PROFILE |
| 111 | + .lock() |
| 112 | + .unwrap_or_else(|e| e.into_inner()) |
| 113 | + .remove(&counter); |
| 114 | + |
| 115 | + // Only call the user's callback when `run` succeeded -- a partial profile |
| 116 | + // captured against an aborted execution wouldn't be meaningful. |
| 117 | + if let (Some(profiler), Ok(_)) = (drained, &result) { |
| 118 | + on_profile(profiler.get_profile(program)); |
| 119 | + } |
| 120 | + |
| 121 | + result |
| 122 | + } |
| 123 | +} |
| 124 | + |
| 125 | +/// RAII cleanup for the profiler globals. Restores `*trace_id_ptr` on success or |
| 126 | +/// unwind. The [`LIBFUNC_PROFILE`] slot at `counter` is normally drained on the |
| 127 | +/// success path; this guard removes it if it's still occupied (panic case). |
| 128 | +struct ProfilerGuard { |
| 129 | + trace_id_ptr: *mut u64, |
| 130 | + old_trace_id: u64, |
| 131 | + counter: u64, |
| 132 | +} |
| 133 | + |
| 134 | +impl Drop for ProfilerGuard { |
| 135 | + fn drop(&mut self) { |
| 136 | + // SAFETY: same provenance as the construction site. `PROFILE_LOCK` is held |
| 137 | + // by the enclosing scope (still in flight while we drop) so no other thread |
| 138 | + // races us. |
| 139 | + unsafe { |
| 140 | + *self.trace_id_ptr = self.old_trace_id; |
| 141 | + } |
| 142 | + // Tolerate a poisoned mutex silently -- Drop must not panic. Slot leak on |
| 143 | + // poison is intentional and matches the behavior of other Drop impls in |
| 144 | + // this crate; the alternative (panic in Drop) is worse. |
| 145 | + if let Ok(mut profile) = LIBFUNC_PROFILE.lock() { |
| 146 | + profile.remove(&self.counter); |
| 147 | + } |
| 148 | + } |
| 149 | +} |
0 commit comments