Skip to main content

async_ebpf/
program.rs

1//! This module contains the core logic for eBPF program execution. A lot of
2//! `unsafe` code is used - be careful when making changes here.
3
4use std::{
5  any::{Any, TypeId},
6  cell::{Cell, RefCell},
7  collections::HashMap,
8  ffi::CStr,
9  marker::PhantomData,
10  mem::ManuallyDrop,
11  ops::{Deref, DerefMut},
12  pin::Pin,
13  ptr::NonNull,
14  rc::Rc,
15  sync::{
16    atomic::{compiler_fence, AtomicBool, AtomicU64, Ordering},
17    Arc, Once,
18  },
19  thread::ThreadId,
20  time::{Duration, Instant},
21};
22
23use corosensei::{
24  stack::{DefaultStack, Stack},
25  Coroutine, CoroutineResult, ScopedCoroutine, Yielder,
26};
27use futures::{Future, FutureExt};
28use memmap2::{MmapOptions, MmapRaw};
29use parking_lot::{Condvar, Mutex};
30use rand::prelude::SliceRandom;
31
32use crate::{
33  error::{Error, RuntimeError},
34  helpers::Helper,
35  linker::link_elf,
36  pointer_cage::PointerCage,
37  util::nonnull_bytes_overlap,
38};
39
40const NATIVE_STACK_SIZE: usize = 16384;
41const SHADOW_STACK_SIZE: usize = 4096;
42const MAX_CALLDATA_SIZE: usize = 512;
43const MAX_MUTABLE_DEREF_REGIONS: usize = 4;
44const MAX_IMMUTABLE_DEREF_REGIONS: usize = 16;
45
46/// Per-invocation storage for helper state during a program run.
47pub struct InvokeScope {
48  data: HashMap<TypeId, Box<dyn Any + Send>>,
49}
50
51impl InvokeScope {
52  /// Gets or creates typed data scoped to this invocation.
53  pub fn data_mut<T: Default + Send + 'static>(&mut self) -> &mut T {
54    let ty = TypeId::of::<T>();
55    self
56      .data
57      .entry(ty)
58      .or_insert_with(|| Box::new(T::default()))
59      .downcast_mut()
60      .expect("InvokeScope::data_mut: downcast failed")
61  }
62}
63
64/// Context passed to helpers while a program is executing.
65pub struct HelperScope<'a, 'b> {
66  /// The program being executed.
67  pub program: &'a Program,
68  /// Mutable per-invocation data for helpers.
69  pub invoke: RefCell<&'a mut InvokeScope>,
70  resources: RefCell<&'a mut [&'b mut dyn Any]>,
71  mutable_dereferenced_regions: [Cell<Option<NonNull<[u8]>>>; MAX_MUTABLE_DEREF_REGIONS],
72  immutable_dereferenced_regions: [Cell<Option<NonNull<[u8]>>>; MAX_IMMUTABLE_DEREF_REGIONS],
73  can_post_task: bool,
74}
75
76/// A validated mutable view into user memory.
77pub struct MutableUserMemory<'a, 'b, 'c> {
78  _scope: &'c HelperScope<'a, 'b>,
79  region: NonNull<[u8]>,
80}
81
82impl<'a, 'b, 'c> Deref for MutableUserMemory<'a, 'b, 'c> {
83  type Target = [u8];
84
85  fn deref(&self) -> &Self::Target {
86    unsafe { self.region.as_ref() }
87  }
88}
89
90impl<'a, 'b, 'c> DerefMut for MutableUserMemory<'a, 'b, 'c> {
91  fn deref_mut(&mut self) -> &mut Self::Target {
92    unsafe { self.region.as_mut() }
93  }
94}
95
96impl<'a, 'b> HelperScope<'a, 'b> {
97  /// Posts an async task to be run between timeslices.
98  pub fn post_task(
99    &self,
100    task: impl Future<Output = impl FnOnce(&HelperScope) -> Result<u64, ()> + 'static> + 'static,
101  ) {
102    if !self.can_post_task {
103      panic!("HelperScope::post_task() called in a context where posting task is not allowed");
104    }
105
106    PENDING_ASYNC_TASK.with(|x| {
107      let mut x = x.borrow_mut();
108      if x.is_some() {
109        panic!("post_task called while another task is pending");
110      }
111      *x = Some(async move { Box::new(task.await) as AsyncTaskOutput }.boxed_local());
112    });
113  }
114
115  /// Calls `callback` with a mutable resource of type `T`, if present.
116  pub fn with_resource_mut<'c, T: 'static, R>(
117    &'c self,
118    callback: impl FnOnce(Result<&mut T, ()>) -> R,
119  ) -> R {
120    let mut resources = self.resources.borrow_mut();
121    let Some(res) = resources
122      .iter_mut()
123      .filter_map(|x| x.downcast_mut::<T>())
124      .next()
125    else {
126      tracing::warn!(resource_type = ?TypeId::of::<T>(), "resource not found");
127      return callback(Err(()));
128    };
129
130    callback(Ok(res))
131  }
132
133  /// Validates and returns an immutable view into user memory.
134  pub fn user_memory(&self, ptr: u64, size: u64) -> Result<&[u8], ()> {
135    let Some(region) = self
136      .program
137      .unbound
138      .cage
139      .safe_deref_for_read(ptr as usize, size as usize)
140    else {
141      tracing::warn!(ptr, size, "invalid read");
142      return Err(());
143    };
144
145    if size != 0 {
146      // The region must not overlap with any previously dereferenced mutable regions
147      if self
148        .mutable_dereferenced_regions
149        .iter()
150        .filter_map(|x| x.get())
151        .any(|x| nonnull_bytes_overlap(x, region))
152      {
153        tracing::warn!(ptr, size, "read overlapped with previous write");
154        return Err(());
155      }
156
157      // Find a slot to record this dereference
158      let Some(slot) = self
159        .immutable_dereferenced_regions
160        .iter()
161        .find(|x| x.get().is_none())
162      else {
163        tracing::warn!(ptr, size, "too many reads");
164        return Err(());
165      };
166      slot.set(Some(region));
167    }
168
169    Ok(unsafe { region.as_ref() })
170  }
171
172  /// Validates and returns a mutable view into user memory.
173  pub fn user_memory_mut<'c>(
174    &'c self,
175    ptr: u64,
176    size: u64,
177  ) -> Result<MutableUserMemory<'a, 'b, 'c>, ()> {
178    let Some(region) = self
179      .program
180      .unbound
181      .cage
182      .safe_deref_for_write(ptr as usize, size as usize)
183    else {
184      tracing::warn!(ptr, size, "invalid write");
185      return Err(());
186    };
187
188    if size != 0 {
189      // The region must not overlap with any other previously dereferenced mutable or immutable regions
190      if self
191        .mutable_dereferenced_regions
192        .iter()
193        .chain(self.immutable_dereferenced_regions.iter())
194        .filter_map(|x| x.get())
195        .any(|x| nonnull_bytes_overlap(x, region))
196      {
197        tracing::warn!(ptr, size, "write overlapped with previous read/write");
198        return Err(());
199      }
200
201      // Find a slot to record this dereference
202      let Some(slot) = self
203        .mutable_dereferenced_regions
204        .iter()
205        .find(|x| x.get().is_none())
206      else {
207        tracing::warn!(ptr, size, "too many writes");
208        return Err(());
209      };
210      slot.set(Some(region));
211    }
212
213    Ok(MutableUserMemory {
214      _scope: self,
215      region,
216    })
217  }
218}
219
220#[derive(Copy, Clone)]
221struct AssumeSend<T>(T);
222unsafe impl<T> Send for AssumeSend<T> {}
223
224struct ExecContext {
225  native_stack: DefaultStack,
226  copy_stack: Box<[u8; SHADOW_STACK_SIZE]>,
227}
228
229impl ExecContext {
230  fn new() -> Self {
231    Self {
232      native_stack: DefaultStack::new(NATIVE_STACK_SIZE)
233        .expect("failed to initialize native stack"),
234      copy_stack: Box::new([0u8; SHADOW_STACK_SIZE]),
235    }
236  }
237}
238
239/// A pending async task spawned by a helper.
240pub type PendingAsyncTask = Pin<Box<dyn Future<Output = AsyncTaskOutput>>>;
241/// The callback produced by a helper async task when it resumes.
242pub type AsyncTaskOutput = Box<dyn FnOnce(&HelperScope) -> Result<u64, ()>>;
243
244static NEXT_PROGRAM_ID: AtomicU64 = AtomicU64::new(1);
245
246#[derive(Copy, Clone, Debug)]
247enum PreemptionState {
248  Inactive,
249  Active(usize),
250  Shutdown,
251}
252
253type PreemptionStateSignal = (Mutex<PreemptionState>, Condvar);
254
255thread_local! {
256  static RUST_TID: ThreadId = std::thread::current().id();
257  static SIGUSR1_COUNTER: Cell< u64> = Cell::new(0);
258  static ACTIVE_JIT_CODE_ZONE: ActiveJitCodeZone = ActiveJitCodeZone::default();
259  static EXEC_CONTEXT_POOL: RefCell<Vec<ExecContext>> = Default::default();
260  static PENDING_ASYNC_TASK: RefCell<Option<PendingAsyncTask>> = RefCell::new(None);
261  static PREEMPTION_STATE: Arc<PreemptionStateSignal> = Arc::new((Mutex::new(PreemptionState::Inactive), Condvar::new()));
262  static LOADING_PROGRAM_LOADER: Cell<*const ProgramLoader> = const { Cell::new(std::ptr::null()) };
263}
264
265struct BorrowedExecContext {
266  ctx: ManuallyDrop<ExecContext>,
267}
268
269impl BorrowedExecContext {
270  fn new() -> Self {
271    let mut me = Self {
272      ctx: ManuallyDrop::new(
273        EXEC_CONTEXT_POOL.with(|x| x.borrow_mut().pop().unwrap_or_else(ExecContext::new)),
274      ),
275    };
276    me.ctx.copy_stack.fill(0x8e);
277    me
278  }
279}
280
281impl Drop for BorrowedExecContext {
282  fn drop(&mut self) {
283    let ctx = unsafe { ManuallyDrop::take(&mut self.ctx) };
284    EXEC_CONTEXT_POOL.with(|x| x.borrow_mut().push(ctx));
285  }
286}
287
288#[derive(Default)]
289struct ActiveJitCodeZone {
290  valid: AtomicBool,
291  code_range: Cell<(usize, usize)>,
292  pointer_cage_protected_range: Cell<(usize, usize)>,
293  yielder: Cell<Option<NonNull<Yielder<u64, Dispatch>>>>,
294}
295
296/// Hooks for observing program execution events.
297pub trait ProgramEventListener: Send + Sync + 'static {
298  /// Called after an async preemption is triggered.
299  fn did_async_preempt(&self, _scope: &HelperScope) {}
300  /// Called after yielding back to the async runtime.
301  fn did_yield(&self) {}
302  /// Called after throttling a program's execution.
303  fn did_throttle(&self, _scope: &HelperScope) -> Option<Pin<Box<dyn Future<Output = ()>>>> {
304    None
305  }
306  /// Called after saving the shadow stack before yielding.
307  fn did_save_shadow_stack(&self) {}
308  /// Called after restoring the shadow stack on resume.
309  fn did_restore_shadow_stack(&self) {}
310}
311
312/// No-op event listener implementation.
313pub struct DummyProgramEventListener;
314impl ProgramEventListener for DummyProgramEventListener {}
315
316/// Prepares helper tables and loads eBPF programs.
317pub struct ProgramLoader {
318  helpers_inverse: HashMap<&'static str, i32>,
319  event_listener: Arc<dyn ProgramEventListener>,
320  helper_id_xor: u16,
321  helpers: Arc<Vec<(u16, &'static str, Helper)>>,
322}
323
324/// A loaded program that is not yet pinned to a thread.
325pub struct UnboundProgram {
326  id: u64,
327  _code_mem: MmapRaw,
328  cage: PointerCage,
329  helper_id_xor: u16,
330  helpers: Arc<Vec<(u16, &'static str, Helper)>>,
331  event_listener: Arc<dyn ProgramEventListener>,
332  entrypoints: HashMap<String, Entrypoint>,
333}
334
335/// A program pinned to a specific thread and ready to execute.
336pub struct Program {
337  unbound: UnboundProgram,
338  data: RefCell<HashMap<TypeId, Rc<dyn Any>>>,
339  t: ThreadEnv,
340}
341
342#[derive(Copy, Clone)]
343struct Entrypoint {
344  code_ptr: usize,
345  code_len: usize,
346}
347
348/// Time limits used to yield or throttle execution.
349#[derive(Clone, Debug)]
350pub struct TimesliceConfig {
351  /// Maximum runtime before yielding to the async scheduler.
352  pub max_run_time_before_yield: Duration,
353  /// Maximum runtime before a throttle sleep is forced.
354  pub max_run_time_before_throttle: Duration,
355  /// Duration of the throttle sleep once triggered.
356  pub throttle_duration: Duration,
357}
358
359/// Async runtime integration for yielding and sleeping.
360pub trait Timeslicer {
361  /// Sleep for the provided duration.
362  fn sleep(&self, duration: Duration) -> impl Future<Output = ()>;
363  /// Yield to the async scheduler.
364  fn yield_now(&self) -> impl Future<Output = ()>;
365}
366
367/// Global runtime environment for signal handlers.
368#[derive(Copy, Clone)]
369pub struct GlobalEnv(());
370
371/// Per-thread runtime environment for preemption handling.
372#[derive(Copy, Clone)]
373pub struct ThreadEnv {
374  _not_send_sync: std::marker::PhantomData<*const ()>,
375}
376
377impl GlobalEnv {
378  /// Initializes global state and installs signal handlers.
379  ///
380  /// # Safety
381  /// Must be called in a process that can install SIGUSR1/SIGSEGV handlers.
382  pub unsafe fn new() -> Self {
383    static INIT: Once = Once::new();
384
385    // SIGUSR1 must be blocked during exception handling
386    // Otherwise it seems that Linux gives up and throws an uncatchable SI_KERNEL SIGSEGV:
387    //
388    // [pid 517110] tgkill(517109, 517112, SIGUSR1 <unfinished ...>
389    // [pid 517112] --- SIGSEGV {si_signo=SIGSEGV, si_code=SEGV_ACCERR, si_addr=0x793789be227e} ---
390    // [pid 517109] write(15, "\1\0\0\0\0\0\0\0", 8 <unfinished ...>
391    // [pid 517110] <... tgkill resumed>)      = 0
392    // [pid 517109] <... write resumed>)       = 8
393    // [pid 517112] --- SIGUSR1 {si_signo=SIGUSR1, si_code=SI_TKILL, si_pid=517109, si_uid=1000} ---
394    // [pid 517109] recvfrom(57,  <unfinished ...>
395    // [pid 517110] futex(0x79378abff5a8, FUTEX_WAIT_PRIVATE, 1, {tv_sec=0, tv_nsec=5999909} <unfinished ...>
396    // [pid 517109] <... recvfrom resumed>"GET /write_rodata HTTP/1.1\r\nHost"..., 8192, 0, NULL, NULL) = 61
397    // [pid 517112] --- SIGSEGV {si_signo=SIGSEGV, si_code=SI_KERNEL, si_addr=NULL} ---
398
399    INIT.call_once(|| {
400      let sa_mask = get_blocked_sigset();
401
402      for (sig, handler) in [
403        (libc::SIGUSR1, sigusr1_handler as *const () as usize),
404        (libc::SIGSEGV, sigsegv_handler as *const () as usize),
405      ] {
406        let act = libc::sigaction {
407          sa_sigaction: handler,
408          sa_flags: libc::SA_SIGINFO,
409          sa_mask,
410          sa_restorer: None,
411        };
412        if libc::sigaction(sig, &act, std::ptr::null_mut()) != 0 {
413          panic!("failed to setup handler for signal {}", sig);
414        }
415      }
416    });
417
418    Self(())
419  }
420
421  /// Initializes per-thread state and starts the async preemption watcher.
422  pub fn init_thread(self, async_preemption_interval: Duration) -> ThreadEnv {
423    struct DeferDrop(Arc<PreemptionStateSignal>);
424    impl Drop for DeferDrop {
425      fn drop(&mut self) {
426        let x = &self.0;
427        *x.0.lock() = PreemptionState::Shutdown;
428        x.1.notify_one();
429      }
430    }
431
432    thread_local! {
433      static WATCHER: RefCell<Option<DeferDrop>> = RefCell::new(None);
434    }
435
436    if WATCHER.with(|x| x.borrow().is_some()) {
437      return ThreadEnv {
438        _not_send_sync: PhantomData,
439      };
440    }
441
442    let preemption_state = PREEMPTION_STATE.with(|x| x.clone());
443
444    unsafe {
445      let tgid = libc::getpid();
446      let tid = libc::gettid();
447
448      std::thread::Builder::new()
449        .name("preempt-watcher".to_string())
450        .spawn(move || {
451          let mut state = preemption_state.0.lock();
452          loop {
453            match *state {
454              PreemptionState::Shutdown => break,
455              PreemptionState::Inactive => {
456                preemption_state.1.wait(&mut state);
457              }
458              PreemptionState::Active(_) => {
459                let timeout = preemption_state.1.wait_while_for(
460                  &mut state,
461                  |x| matches!(x, PreemptionState::Active(_)),
462                  async_preemption_interval,
463                );
464                if timeout.timed_out() {
465                  let ret = libc::syscall(libc::SYS_tgkill, tgid, tid, libc::SIGUSR1);
466                  if ret != 0 {
467                    break;
468                  }
469                }
470              }
471            }
472          }
473        })
474        .expect("failed to spawn preemption watcher");
475
476      WATCHER.with(|x| {
477        x.borrow_mut()
478          .replace(DeferDrop(PREEMPTION_STATE.with(|x| x.clone())));
479      });
480
481      ThreadEnv {
482        _not_send_sync: PhantomData,
483      }
484    }
485  }
486}
487
488impl UnboundProgram {
489  /// Pins the program to the current thread using a prepared `ThreadEnv`.
490  pub fn pin_to_current_thread(self, t: ThreadEnv) -> Program {
491    Program {
492      unbound: self,
493      data: RefCell::new(HashMap::new()),
494      t,
495    }
496  }
497}
498
499pub struct PreemptionEnabled(());
500
501impl PreemptionEnabled {
502  pub fn new(_: ThreadEnv) -> Self {
503    PREEMPTION_STATE.with(|x| {
504      let mut notify = false;
505      {
506        let mut st = x.0.lock();
507        let next = match *st {
508          PreemptionState::Inactive => {
509            notify = true;
510            PreemptionState::Active(1)
511          }
512          PreemptionState::Active(n) => PreemptionState::Active(n + 1),
513          PreemptionState::Shutdown => unreachable!(),
514        };
515        *st = next;
516      }
517
518      if notify {
519        x.1.notify_one();
520      }
521    });
522    Self(())
523  }
524}
525
526impl Drop for PreemptionEnabled {
527  fn drop(&mut self) {
528    PREEMPTION_STATE.with(|x| {
529      let mut st = x.0.lock();
530      let next = match *st {
531        PreemptionState::Active(1) => PreemptionState::Inactive,
532        PreemptionState::Active(n) => {
533          assert!(n > 1);
534          PreemptionState::Active(n - 1)
535        }
536        PreemptionState::Inactive | PreemptionState::Shutdown => unreachable!(),
537      };
538      *st = next;
539    });
540  }
541}
542
543impl Program {
544  /// Returns the unique program identifier.
545  pub fn id(&self) -> u64 {
546    self.unbound.id
547  }
548
549  pub fn thread_env(&self) -> ThreadEnv {
550    self.t
551  }
552
553  /// Gets or creates shared typed data for this program instance.
554  pub fn data<T: Default + 'static>(&self) -> Rc<T> {
555    let mut data = self.data.borrow_mut();
556    let entry = data.entry(TypeId::of::<T>());
557    let entry = entry.or_insert_with(|| Rc::new(T::default()));
558    entry.clone().downcast().unwrap()
559  }
560
561  pub fn has_section(&self, name: &str) -> bool {
562    self.unbound.entrypoints.contains_key(name)
563  }
564
565  /// Runs the program entrypoint with the provided resources and calldata.
566  pub async fn run(
567    &self,
568    timeslice: &TimesliceConfig,
569    timeslicer: &impl Timeslicer,
570    entrypoint: &str,
571    resources: &mut [&mut dyn Any],
572    calldata: &[u8],
573    preemption: &PreemptionEnabled,
574  ) -> Result<i64, Error> {
575    self
576      ._run(
577        timeslice, timeslicer, entrypoint, resources, calldata, preemption,
578      )
579      .await
580      .map_err(Error)
581  }
582
583  async fn _run(
584    &self,
585    timeslice: &TimesliceConfig,
586    timeslicer: &impl Timeslicer,
587    entrypoint: &str,
588    resources: &mut [&mut dyn Any],
589    calldata: &[u8],
590    _: &PreemptionEnabled,
591  ) -> Result<i64, RuntimeError> {
592    let Some(entrypoint) = self.unbound.entrypoints.get(entrypoint).copied() else {
593      return Err(RuntimeError::InvalidArgument("entrypoint not found"));
594    };
595
596    let entry = unsafe {
597      std::mem::transmute::<
598        _,
599        unsafe extern "C" fn(ctx: usize, mem_len: usize, stack: usize, stack_len: usize) -> u64,
600      >(entrypoint.code_ptr)
601    };
602    struct CoDropper<'a, Input, Yield, Return, DefaultStack: Stack>(
603      ScopedCoroutine<'a, Input, Yield, Return, DefaultStack>,
604    );
605    impl<'a, Input, Yield, Return, DefaultStack: Stack> Drop
606      for CoDropper<'a, Input, Yield, Return, DefaultStack>
607    {
608      fn drop(&mut self) {
609        // Prevent the coroutine library from attempting to unwind the stack of the coroutine
610        // and run destructors, because this stack might be running a signal handler and
611        // it's not allowed to unwind from there.
612        //
613        // SAFETY: The coroutine stack only contains stack frames for JIT-compiled code and
614        // carefully chosen Rust code that do not hold Droppable values, so it's safe to
615        // skip destructors.
616        unsafe {
617          self.0.force_reset();
618        }
619      }
620    }
621
622    let mut ectx = BorrowedExecContext::new();
623
624    if calldata.len() > MAX_CALLDATA_SIZE {
625      return Err(RuntimeError::InvalidArgument("calldata too large"));
626    }
627    ectx.ctx.copy_stack[SHADOW_STACK_SIZE - calldata.len()..].copy_from_slice(calldata);
628    let calldata_len = calldata.len();
629
630    let program_ret: u64 = {
631      let shadow_stack_top = self.unbound.cage.stack_top();
632      let shadow_stack_bottom = self.unbound.cage.stack_bottom();
633      let shadow_stack_ptr = AssumeSend(
634        self
635          .unbound
636          .cage
637          .safe_deref_for_write(self.unbound.cage.stack_bottom(), SHADOW_STACK_SIZE)
638          .unwrap(),
639      );
640      let ctx = &mut *ectx.ctx;
641
642      let mut co = AssumeSend(CoDropper(Coroutine::with_stack(
643        &mut ctx.native_stack,
644        move |yielder, _input| unsafe {
645          ACTIVE_JIT_CODE_ZONE.with(|x| {
646            x.yielder.set(NonNull::new(yielder as *const _ as *mut _));
647          });
648          let calldata_start = shadow_stack_top - calldata_len;
649          let stack_top = calldata_start & !0x7;
650          let stack_len = stack_top - shadow_stack_bottom;
651          entry(
652            calldata_start,
653            calldata_start,
654            shadow_stack_bottom,
655            stack_len,
656          )
657        },
658      )));
659
660      let mut last_yield_time = Instant::now();
661      let mut last_throttle_time = Instant::now();
662      let mut yielder: Option<AssumeSend<NonNull<Yielder<u64, Dispatch>>>> = None;
663      let mut resume_input: u64 = 0;
664      let mut did_throttle = false;
665      let mut shadow_stack_saved = true;
666      let mut rust_tid_sigusr1_counter = (RUST_TID.with(|x| *x), SIGUSR1_COUNTER.with(|x| x.get()));
667      let mut prev_async_task_output: Option<(&'static str, AsyncTaskOutput)> = None;
668      let mut invoke_scope = InvokeScope {
669        data: HashMap::new(),
670      };
671
672      loop {
673        ACTIVE_JIT_CODE_ZONE.with(|x| {
674          x.code_range.set((
675            entrypoint.code_ptr,
676            entrypoint.code_ptr + entrypoint.code_len,
677          ));
678          x.yielder.set(yielder.map(|x| x.0));
679          x.pointer_cage_protected_range
680            .set(self.unbound.cage.protected_range_without_margins());
681          compiler_fence(Ordering::Release);
682          x.valid.store(true, Ordering::Relaxed);
683        });
684
685        if shadow_stack_saved {
686          shadow_stack_saved = false;
687
688          // restore shadow stack
689          unsafe {
690            std::ptr::copy_nonoverlapping(
691              ctx.copy_stack.as_ptr() as *const u8,
692              shadow_stack_ptr.0.as_ptr() as *mut u8,
693              SHADOW_STACK_SIZE,
694            );
695          }
696
697          self.unbound.event_listener.did_restore_shadow_stack();
698        }
699
700        // If the previous iteration wants to write back to machine state
701        if let Some((helper_name, prev_async_task_output)) = prev_async_task_output.take() {
702          resume_input = prev_async_task_output(&HelperScope {
703            program: self,
704            invoke: RefCell::new(&mut invoke_scope),
705            resources: RefCell::new(resources),
706            mutable_dereferenced_regions: unsafe { std::mem::zeroed() },
707            immutable_dereferenced_regions: unsafe { std::mem::zeroed() },
708            can_post_task: false,
709          })
710          .map_err(|_| RuntimeError::AsyncHelperError(helper_name))?;
711        }
712
713        let ret = co.0 .0.resume(resume_input);
714        ACTIVE_JIT_CODE_ZONE.with(|x| {
715          x.valid.store(false, Ordering::Relaxed);
716          compiler_fence(Ordering::Release);
717          yielder = x.yielder.get().map(AssumeSend);
718        });
719
720        let dispatch: Dispatch = match ret {
721          CoroutineResult::Return(x) => break x,
722          CoroutineResult::Yield(x) => x,
723        };
724
725        // restore signal mask of current thread
726        if dispatch.memory_access_error.is_some() || dispatch.async_preemption {
727          unsafe {
728            let unblock = get_blocked_sigset();
729            libc::sigprocmask(libc::SIG_UNBLOCK, &unblock, std::ptr::null_mut());
730          }
731        }
732
733        if let Some(si_addr) = dispatch.memory_access_error {
734          let vaddr = si_addr - self.unbound.cage.offset();
735          return Err(RuntimeError::MemoryFault(vaddr));
736        }
737
738        // Clear pending task if something else has set it
739        PENDING_ASYNC_TASK.with(|x| x.borrow_mut().take());
740        let mut helper_name: &'static str = "";
741
742        let mut helper_scope = HelperScope {
743          program: self,
744          invoke: RefCell::new(&mut invoke_scope),
745          resources: RefCell::new(resources),
746          mutable_dereferenced_regions: unsafe { std::mem::zeroed() },
747          immutable_dereferenced_regions: unsafe { std::mem::zeroed() },
748          can_post_task: false,
749        };
750
751        if dispatch.async_preemption {
752          self
753            .unbound
754            .event_listener
755            .did_async_preempt(&mut helper_scope);
756        } else {
757          // validator should ensure all helper indexes are present in the table
758          let Some((_, got_helper_name, helper)) = self
759            .unbound
760            .helpers
761            .get(
762              ((dispatch.index & 0xffff) as u16 ^ self.unbound.helper_id_xor).wrapping_sub(1)
763                as usize,
764            )
765            .copied()
766          else {
767            panic!("unknown helper index: {}", dispatch.index);
768          };
769          helper_name = got_helper_name;
770
771          helper_scope.can_post_task = true;
772          resume_input = helper(
773            &mut helper_scope,
774            dispatch.arg1,
775            dispatch.arg2,
776            dispatch.arg3,
777            dispatch.arg4,
778            dispatch.arg5,
779          )
780          .map_err(|()| RuntimeError::HelperError(helper_name))?;
781          helper_scope.can_post_task = false;
782        }
783
784        let pending_async_task = PENDING_ASYNC_TASK.with(|x| x.borrow_mut().take());
785
786        // Fast path: do not read timestamp if no thread migration or async preemption happened
787        let new_rust_tid_sigusr1_counter =
788          (RUST_TID.with(|x| *x), SIGUSR1_COUNTER.with(|x| x.get()));
789        if new_rust_tid_sigusr1_counter == rust_tid_sigusr1_counter && pending_async_task.is_none()
790        {
791          continue;
792        }
793
794        rust_tid_sigusr1_counter = new_rust_tid_sigusr1_counter;
795
796        let now = Instant::now();
797        let should_throttle = now > last_throttle_time
798          && now.duration_since(last_throttle_time) >= timeslice.max_run_time_before_throttle;
799        let should_yield = now > last_yield_time
800          && now.duration_since(last_yield_time) >= timeslice.max_run_time_before_yield;
801        if should_throttle || should_yield || pending_async_task.is_some() {
802          // We are about to yield control to tokio. Save the shadow stack, and release the guard.
803          shadow_stack_saved = true;
804          unsafe {
805            std::ptr::copy_nonoverlapping(
806              shadow_stack_ptr.0.as_ptr() as *const u8,
807              ctx.copy_stack.as_mut_ptr() as *mut u8,
808              SHADOW_STACK_SIZE,
809            );
810          }
811          self.unbound.event_listener.did_save_shadow_stack();
812
813          // we are now free to give up control of current thread to other async tasks
814
815          if should_throttle {
816            if !did_throttle {
817              did_throttle = true;
818              tracing::warn!("throttling program");
819            }
820            timeslicer.sleep(timeslice.throttle_duration).await;
821            let now = Instant::now();
822            last_throttle_time = now;
823            last_yield_time = now;
824            let task = self.unbound.event_listener.did_throttle(&mut helper_scope);
825            if let Some(task) = task {
826              task.await;
827            }
828          } else if should_yield {
829            timeslicer.yield_now().await;
830            let now = Instant::now();
831            last_yield_time = now;
832            self.unbound.event_listener.did_yield();
833          }
834
835          // Now we have released all exclusive resources and can safely execute the async task
836          if let Some(pending_async_task) = pending_async_task {
837            let async_start = Instant::now();
838            prev_async_task_output = Some((helper_name, pending_async_task.await));
839            let async_dur = async_start.elapsed();
840            last_throttle_time += async_dur;
841            last_yield_time += async_dur;
842          }
843        }
844      }
845    };
846
847    Ok(program_ret as i64)
848  }
849}
850
851struct Vm(NonNull<crate::ubpf::ubpf_vm>);
852
853impl Vm {
854  fn new(cage: &PointerCage) -> Self {
855    let vm = NonNull::new(unsafe { crate::ubpf::ubpf_create() }).expect("failed to create ubpf_vm");
856    unsafe {
857      crate::ubpf::ubpf_toggle_bounds_check(vm.as_ptr(), false);
858      crate::ubpf::ubpf_set_jit_pointer_mask_and_offset(vm.as_ptr(), cage.mask(), cage.offset());
859    }
860    Self(vm)
861  }
862}
863
864impl Drop for Vm {
865  fn drop(&mut self) {
866    unsafe {
867      crate::ubpf::ubpf_destroy(self.0.as_ptr());
868    }
869  }
870}
871
872struct LoaderValidationScope {
873  previous: *const ProgramLoader,
874}
875
876impl LoaderValidationScope {
877  fn new(loader: &ProgramLoader) -> Self {
878    let previous = LOADING_PROGRAM_LOADER.with(|x| {
879      let previous = x.get();
880      x.set(loader as *const _);
881      previous
882    });
883    Self { previous }
884  }
885}
886
887impl Drop for LoaderValidationScope {
888  fn drop(&mut self) {
889    LOADING_PROGRAM_LOADER.with(|x| x.set(self.previous));
890  }
891}
892
893impl ProgramLoader {
894  /// Creates a new `ProgramLoader` to load eBPF code.
895  pub fn new(
896    rng: &mut impl rand::Rng,
897    event_listener: Arc<dyn ProgramEventListener>,
898    raw_helpers: &[&[(&'static str, Helper)]],
899  ) -> Self {
900    let helper_id_xor = rng.gen::<u16>();
901    let mut helpers_inverse: HashMap<&'static str, i32> = HashMap::new();
902    // Collect first to a HashMap then to a Vec to deduplicate
903    let mut shuffled_helpers = raw_helpers
904      .iter()
905      .flat_map(|x| x.iter().copied())
906      .collect::<HashMap<_, _>>()
907      .into_iter()
908      .collect::<Vec<_>>();
909    shuffled_helpers.shuffle(rng);
910    let mut helpers: Vec<(u16, &'static str, Helper)> = Vec::with_capacity(shuffled_helpers.len());
911
912    assert!(shuffled_helpers.len() <= 65535);
913
914    for (i, (name, helper)) in shuffled_helpers.into_iter().enumerate() {
915      let entropy = rng.gen::<u16>() & 0x7fff;
916      helpers.push((entropy, name, helper));
917      helpers_inverse.insert(
918        name,
919        (((entropy as usize) << 16) | ((i + 1) ^ (helper_id_xor as usize))) as i32,
920      );
921    }
922
923    tracing::info!(?helpers_inverse, "generated helper table");
924    Self {
925      helper_id_xor,
926      helpers: Arc::new(helpers),
927      helpers_inverse,
928      event_listener,
929    }
930  }
931
932  /// Loads an ELF image into a new `UnboundProgram`.
933  pub fn load(&self, rng: &mut impl rand::Rng, elf: &[u8]) -> Result<UnboundProgram, Error> {
934    self._load(rng, elf).map_err(Error)
935  }
936
937  fn _load(&self, rng: &mut impl rand::Rng, elf: &[u8]) -> Result<UnboundProgram, RuntimeError> {
938    let start_time = Instant::now();
939    let cage = PointerCage::new(rng, SHADOW_STACK_SIZE, elf.len())?;
940    let vm = Vm::new(&cage);
941
942    // Relocate ELF
943    let code_sections = {
944      // XXX: Although we are writing to the data region, we need to use `safe_deref_for_read`
945      // here because the `_write` variant checks that the requested region is within the
946      // stack. It's safe here because `freeze_data` is not yet called.
947      let mut data = cage
948        .safe_deref_for_read(cage.data_bottom(), elf.len())
949        .unwrap();
950      let data = unsafe { data.as_mut() };
951      data.copy_from_slice(elf);
952
953      link_elf(data, cage.data_bottom(), &self.helpers_inverse).map_err(RuntimeError::Linker)?
954    };
955    cage.freeze_data();
956
957    let page_size = unsafe { libc::sysconf(libc::_SC_PAGESIZE) };
958    if page_size < 0 {
959      return Err(RuntimeError::PlatformError("failed to get page size"));
960    }
961    let page_size = page_size as usize;
962
963    // Allocate code memory
964    let guard_size_before = rng.gen_range(16..128) * page_size;
965    let mut guard_size_after = rng.gen_range(16..128) * page_size;
966
967    let code_len_allocated: usize = 65536;
968    let code_mem = MmapRaw::from(
969      MmapOptions::new()
970        .len(code_len_allocated + guard_size_before + guard_size_after)
971        .map_anon()
972        .map_err(|_| RuntimeError::PlatformError("failed to allocate code memory"))?,
973    );
974
975    unsafe {
976      if crate::ubpf::ubpf_register_external_dispatcher(
977        vm.0.as_ptr(),
978        Some(tls_dispatcher),
979        Some(std_validator),
980      ) != 0
981      {
982        return Err(RuntimeError::PlatformError(
983          "ubpf: failed to register external dispatcher",
984        ));
985      }
986      if libc::mprotect(
987        code_mem.as_mut_ptr() as *mut _,
988        guard_size_before,
989        libc::PROT_NONE,
990      ) != 0
991        || libc::mprotect(
992          code_mem
993            .as_mut_ptr()
994            .offset((guard_size_before + code_len_allocated) as isize) as *mut _,
995          guard_size_after,
996          libc::PROT_NONE,
997        ) != 0
998      {
999        return Err(RuntimeError::PlatformError("failed to protect guard pages"));
1000      }
1001    }
1002
1003    let mut entrypoints: HashMap<String, Entrypoint> = HashMap::new();
1004
1005    unsafe {
1006      // Translate eBPF to native code
1007      let mut code_slice = std::slice::from_raw_parts_mut(
1008        code_mem.as_mut_ptr().offset(guard_size_before as isize),
1009        code_len_allocated,
1010      );
1011      for (section_name, code_vaddr_size) in code_sections {
1012        if code_slice.is_empty() {
1013          return Err(RuntimeError::InvalidArgument(
1014            "no space left for jit compilation",
1015          ));
1016        }
1017
1018        crate::ubpf::ubpf_unload_code(vm.0.as_ptr());
1019
1020        let mut errmsg_ptr = std::ptr::null_mut();
1021        let code = cage
1022          .safe_deref_for_read(code_vaddr_size.0, code_vaddr_size.1)
1023          .unwrap();
1024        let ret = {
1025          let validation_scope = LoaderValidationScope::new(self);
1026          let ret = crate::ubpf::ubpf_load(
1027            vm.0.as_ptr(),
1028            code.as_ptr() as *const _,
1029            code.len() as u32,
1030            &mut errmsg_ptr,
1031          );
1032          drop(validation_scope);
1033          ret
1034        };
1035        if ret != 0 {
1036          let errmsg = if errmsg_ptr.is_null() {
1037            "".to_string()
1038          } else {
1039            CStr::from_ptr(errmsg_ptr).to_string_lossy().into_owned()
1040          };
1041          if !errmsg_ptr.is_null() {
1042            libc::free(errmsg_ptr as _);
1043          }
1044          tracing::error!(section_name, error = errmsg, "failed to load code");
1045          return Err(RuntimeError::PlatformError("ubpf: code load failed"));
1046        }
1047
1048        let mut written_len = code_slice.len();
1049        let ret = crate::ubpf::ubpf_translate_ex(
1050          vm.0.as_ptr(),
1051          code_slice.as_mut_ptr(),
1052          &mut written_len,
1053          &mut errmsg_ptr,
1054          crate::ubpf::JitMode_ExtendedJitMode,
1055        );
1056        if ret != 0 {
1057          let errmsg = if errmsg_ptr.is_null() {
1058            "".to_string()
1059          } else {
1060            CStr::from_ptr(errmsg_ptr).to_string_lossy().into_owned()
1061          };
1062          if !errmsg_ptr.is_null() {
1063            libc::free(errmsg_ptr as _);
1064          }
1065          tracing::error!(section_name, error = errmsg, "failed to translate code");
1066          return Err(RuntimeError::PlatformError("ubpf: code translation failed"));
1067        }
1068
1069        assert!(written_len <= code_slice.len());
1070        entrypoints.insert(
1071          section_name,
1072          Entrypoint {
1073            code_ptr: code_mem.as_ptr() as usize + guard_size_before + code_len_allocated
1074              - code_slice.len(),
1075            code_len: written_len,
1076          },
1077        );
1078        code_slice = &mut code_slice[written_len..];
1079      }
1080
1081      // Align up code_len to page size
1082      let unpadded_code_len = code_len_allocated - code_slice.len();
1083      if std::env::var("JIT_DUMP").is_ok() {
1084        eprintln!(
1085          "[JITSIZE] elf={} native_unpadded={} buffer={}",
1086          elf.len(),
1087          unpadded_code_len,
1088          code_len_allocated
1089        );
1090        let native = std::slice::from_raw_parts(
1091          code_mem.as_ptr().offset(guard_size_before as isize),
1092          unpadded_code_len,
1093        );
1094        let mut hex = String::with_capacity(native.len() * 2);
1095        for b in native {
1096          hex.push_str(&format!("{b:02x}"));
1097        }
1098        eprintln!("[JITHEX] {hex}");
1099      }
1100      let code_len = (unpadded_code_len + page_size - 1) & !(page_size - 1);
1101      assert!(code_len <= code_len_allocated);
1102
1103      // RW- -> R-X
1104      // Also make the unused part of the pre-allocated code region PROT_NONE
1105      if libc::mprotect(
1106        code_mem.as_mut_ptr().offset(guard_size_before as isize) as *mut _,
1107        code_len,
1108        libc::PROT_READ | libc::PROT_EXEC,
1109      ) != 0
1110        || (code_len < code_len_allocated
1111          && libc::mprotect(
1112            code_mem
1113              .as_mut_ptr()
1114              .offset((guard_size_before + code_len) as isize) as *mut _,
1115            code_len_allocated - code_len,
1116            libc::PROT_NONE,
1117          ) != 0)
1118      {
1119        return Err(RuntimeError::PlatformError("failed to protect code memory"));
1120      }
1121
1122      guard_size_after += code_len_allocated - code_len;
1123
1124      tracing::info!(
1125        elf_size = elf.len(),
1126        native_code_addr = ?code_mem.as_ptr(),
1127        native_code_size = code_len,
1128        native_code_size_unpadded = unpadded_code_len,
1129        guard_size_before,
1130        guard_size_after,
1131        duration = ?start_time.elapsed(),
1132        cage_ptr = ?cage.region().as_ptr(),
1133        cage_mapped_size = cage.region().len(),
1134        "jit compiled program"
1135      );
1136
1137      Ok(UnboundProgram {
1138        id: NEXT_PROGRAM_ID.fetch_add(1, Ordering::Relaxed),
1139        _code_mem: code_mem,
1140        cage,
1141        helper_id_xor: self.helper_id_xor,
1142        helpers: self.helpers.clone(),
1143        event_listener: self.event_listener.clone(),
1144        entrypoints,
1145      })
1146    }
1147  }
1148}
1149
1150#[derive(Default)]
1151struct Dispatch {
1152  async_preemption: bool,
1153  memory_access_error: Option<usize>,
1154
1155  index: u32,
1156  arg1: u64,
1157  arg2: u64,
1158  arg3: u64,
1159  arg4: u64,
1160  arg5: u64,
1161}
1162
1163unsafe extern "C" fn tls_dispatcher(
1164  arg1: u64,
1165  arg2: u64,
1166  arg3: u64,
1167  arg4: u64,
1168  arg5: u64,
1169  index: std::os::raw::c_uint,
1170  _cookie: *mut std::os::raw::c_void,
1171) -> u64 {
1172  let yielder = ACTIVE_JIT_CODE_ZONE
1173    .with(|x| x.yielder.get())
1174    .expect("no yielder");
1175  let yielder = yielder.as_ref();
1176  let ret = yielder.suspend(Dispatch {
1177    async_preemption: false,
1178    memory_access_error: None,
1179    index,
1180    arg1,
1181    arg2,
1182    arg3,
1183    arg4,
1184    arg5,
1185  });
1186  ret
1187}
1188
1189unsafe extern "C" fn std_validator(
1190  index: std::os::raw::c_uint,
1191  _vm: *const crate::ubpf::ubpf_vm,
1192) -> bool {
1193  let loader = LOADING_PROGRAM_LOADER.with(|x| x.get());
1194  if loader.is_null() {
1195    return false;
1196  }
1197  let loader = &*loader;
1198  let entropy = (index >> 16) & 0xffff;
1199  let index = (((index & 0xffff) as u16) ^ loader.helper_id_xor).wrapping_sub(1);
1200  loader.helpers.get(index as usize).map(|x| x.0) == Some(entropy as u16)
1201}
1202
1203#[cfg(all(target_arch = "x86_64", target_os = "linux"))]
1204unsafe fn program_counter(uctx: *mut libc::ucontext_t) -> usize {
1205  (*uctx).uc_mcontext.gregs[libc::REG_RIP as usize] as usize
1206}
1207
1208#[cfg(all(target_arch = "aarch64", target_os = "linux"))]
1209unsafe fn program_counter(uctx: *mut libc::ucontext_t) -> usize {
1210  (*uctx).uc_mcontext.pc as usize
1211}
1212
1213unsafe extern "C" fn sigsegv_handler(
1214  _sig: i32,
1215  siginfo: *mut libc::siginfo_t,
1216  uctx: *mut libc::ucontext_t,
1217) {
1218  let fail = || restore_default_signal_handler(libc::SIGSEGV);
1219
1220  let Some((jit_code_zone, pointer_cage, yielder)) = ACTIVE_JIT_CODE_ZONE.with(|x| {
1221    if x.valid.load(Ordering::Relaxed) {
1222      compiler_fence(Ordering::Acquire);
1223      Some((
1224        x.code_range.get(),
1225        x.pointer_cage_protected_range.get(),
1226        x.yielder.get(),
1227      ))
1228    } else {
1229      None
1230    }
1231  }) else {
1232    return fail();
1233  };
1234
1235  let pc = program_counter(uctx);
1236
1237  if pc < jit_code_zone.0 || pc >= jit_code_zone.1 {
1238    return fail();
1239  }
1240
1241  // SEGV_ACCERR
1242  if (*siginfo).si_code != 2 {
1243    return fail();
1244  }
1245
1246  let si_addr = (*siginfo).si_addr() as usize;
1247  if si_addr < pointer_cage.0 || si_addr >= pointer_cage.1 {
1248    return fail();
1249  }
1250
1251  let yielder = yielder.expect("no yielder").as_ref();
1252  yielder.suspend(Dispatch {
1253    memory_access_error: Some(si_addr),
1254    ..Default::default()
1255  });
1256}
1257
1258unsafe extern "C" fn sigusr1_handler(
1259  _sig: i32,
1260  _siginfo: *mut libc::siginfo_t,
1261  uctx: *mut libc::ucontext_t,
1262) {
1263  SIGUSR1_COUNTER.with(|x| x.set(x.get() + 1));
1264
1265  let Some((jit_code_zone, yielder)) = ACTIVE_JIT_CODE_ZONE.with(|x| {
1266    if x.valid.load(Ordering::Relaxed) {
1267      compiler_fence(Ordering::Acquire);
1268      Some((x.code_range.get(), x.yielder.get()))
1269    } else {
1270      None
1271    }
1272  }) else {
1273    return;
1274  };
1275  let pc = program_counter(uctx);
1276  if pc < jit_code_zone.0 || pc >= jit_code_zone.1 {
1277    return;
1278  }
1279
1280  let yielder = yielder.expect("no yielder").as_ref();
1281  yielder.suspend(Dispatch {
1282    async_preemption: true,
1283    ..Default::default()
1284  });
1285}
1286
1287unsafe fn restore_default_signal_handler(signum: i32) {
1288  let act = libc::sigaction {
1289    sa_sigaction: libc::SIG_DFL,
1290    sa_flags: libc::SA_SIGINFO,
1291    sa_mask: std::mem::zeroed(),
1292    sa_restorer: None,
1293  };
1294  if libc::sigaction(signum, &act, std::ptr::null_mut()) != 0 {
1295    libc::abort();
1296  }
1297}
1298
1299fn get_blocked_sigset() -> libc::sigset_t {
1300  unsafe {
1301    let mut s: libc::sigset_t = std::mem::zeroed();
1302    libc::sigaddset(&mut s, libc::SIGUSR1);
1303    libc::sigaddset(&mut s, libc::SIGSEGV);
1304    s
1305  }
1306}