rust-samp 3.4.0

Write SA-MP and open.mp plugins in safe Rust instead of C++. A single binary runs natively on both servers, with proc macros (`#[native]`, `initialize_plugin!`) that hide the FFI boilerplate and ABI-correct marshalling for Linux (Itanium) and Windows (MSVC).
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
//! Pawn callback interception for the `#[event]` macro.
//!
//! SA-MP and open.mp deliver gamemode callbacks (`OnPlayerConnect`,
//! `OnPlayerSpawn`, …) only to the gamemode's own AMX — a plugin does not
//! receive them by default. To observe a callback from Rust the SDK detours the
//! VM's `amx_Exec`: every public invocation is inspected and, when its index
//! matches a registered event on that AMX, the handler runs before the original
//! public executes.
//!
//! The detour is installed lazily — only when the plugin registered at least one
//! `#[event]` handler **and** the AMX function table is available. Plugins with
//! no events never touch `amx_Exec`.
//!
//! Handlers are **observers** by default: a handler returning `AmxResult<T>` /
//! `T` has its value ignored and the gamemode's public always runs. A handler
//! that instead returns [`EventReturn`] can cancel the callback
//! ([`EventReturn::Suppress`]) — the original public is skipped and the supplied
//! value is returned in its place.

use samp_sdk::amx::Amx;
use samp_sdk::args::Args;
use samp_sdk::raw::types::AMX;

use crate::amx::AmxIdent;
use crate::runtime::Runtime;

// Detour machinery is x86/x86_64-only (retour supports no other arch, and
// SA-MP/open.mp run only on 32-bit x86).
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
use std::cell::RefCell;
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
use std::collections::HashSet;
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
use std::sync::OnceLock;

#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
use retour::GenericDetour;

#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
use samp_sdk::consts::AmxExecIdx;
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
use samp_sdk::exports::{Exec, Export};

/// What the SDK does with the gamemode's public after an event handler runs.
///
/// A `#[event]` handler may return this type to influence the callback. Handlers
/// that instead return `AmxResult<T>` / `T` are pure **observers**: their value
/// is ignored and the original public always runs (equivalent to `Continue`).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum EventReturn {
    /// Let the gamemode's own public run as usual. The default for observers.
    Continue,
    /// Skip the gamemode's public entirely; the callback returns this raw cell
    /// to its caller. Use to cancel a callback (e.g. reject a command in
    /// `OnPlayerCommandText` by returning `EventReturn::Suppress(1)`).
    ///
    /// The value is a raw AMX cell. For a typed return (`f32`, `bool`, …) use
    /// [`EventReturn::suppress`], which encodes the value to a cell for you.
    Suppress(i32),
}

impl EventReturn {
    /// Suppresses the callback, returning `value` encoded as an AMX cell.
    ///
    /// Convenience over `Suppress(i32)` for callbacks whose Pawn return type is
    /// not a plain integer — a `Float:` callback wants the bit pattern of the
    /// `f32`, a `bool:` callback wants `0`/`1`. `CellConvert` handles the
    /// encoding, so `EventReturn::suppress(1.5_f32)` and
    /// `EventReturn::suppress(true)` do the right thing.
    ///
    /// ```rust,ignore
    /// #[event(name = "OnPlayerRequestScore")]
    /// fn on_score(&mut self, _amx: &Amx, _id: i32) -> EventReturn {
    ///     EventReturn::suppress(1.5_f32) // Float: callback, returns 1.5
    /// }
    /// ```
    #[must_use]
    pub fn suppress<T: samp_sdk::cell::CellConvert>(value: T) -> Self {
        EventReturn::Suppress(value.into_cell())
    }
}

/// Handler wrapper generated by `#[event]`.
///
/// Receives the `&Amx` and the [`Args`] the dispatcher built from the VM stack,
/// parses the callback arguments into the declared Rust types, invokes the
/// plugin method, and reports whether to run or suppress the original public.
pub type EventHandler = fn(&Amx, &mut Args) -> EventReturn;

/// Pawn callback name paired with its handler wrapper.
///
/// Produced by the `__samp_event_reg_*` function that `#[event]` generates and
/// consumed by `initialize_plugin!(events: [...])`.
#[derive(Clone, Copy)]
pub struct EventInfo {
    /// Pawn callback name, e.g. `"OnPlayerConnect"`.
    pub name: &'static str,
    /// Wrapper that parses arguments and dispatches into the plugin method.
    pub handler: EventHandler,
}

/// Signature of the VM's `amx_Exec` — `(amx, retval, public index)`.
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
type ExecFn = unsafe extern "C" fn(*mut AMX, *mut i32, i32) -> i32;

/// Owns the live detour so it stays enabled for the process lifetime (dropping a
/// [`GenericDetour`] removes the hook). A single detour covers every AMX — the
/// server routes all public execution through the same function pointer.
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
struct ExecDetour(GenericDetour<ExecFn>);

// SAFETY: SA-MP and open.mp are single-threaded; the detour is only ever touched
// on the main thread. This mirrors the `Runtime` Sync/Send rationale.
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
unsafe impl Sync for ExecDetour {}
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
unsafe impl Send for ExecDetour {}

/// Installed lazily on the first AMX that carries events; `Some` thereafter.
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
static EXEC_DETOUR: OnceLock<ExecDetour> = OnceLock::new();

/// Resolves the registered events against a freshly loaded AMX and, on the
/// first AMX that carries events, installs the `amx_Exec` detour.
///
/// No-op when the plugin registered no `#[event]` handlers.
pub(crate) fn on_amx_load(rt: &Runtime, amx: &Amx) {
    if !rt.has_events() {
        return;
    }
    resolve_events_for_amx(rt, amx);
    install_exec_hook(rt.amx_exports());
}

/// Drops the resolved handlers for an AMX being unloaded.
pub(crate) fn on_amx_unload(rt: &Runtime, amx_ptr: *mut AMX) {
    if rt.has_events() {
        rt.remove_resolved_events(AmxIdent::from(amx_ptr));
    }
}

/// For each registered event, resolves its public index in `amx` (via
/// `amx_FindPublic`) and records `(ident, index, handler)` for dispatch. A
/// callback the gamemode does not define is simply skipped.
fn resolve_events_for_amx(rt: &Runtime, amx: &Amx) {
    let Some(ptr) = amx.amx() else {
        return;
    };
    let ident = AmxIdent::from(ptr.as_ptr());

    // Clear any prior resolution for this AMX first, so a second `on_amx_load`
    // for the same script (e.g. an open.mp pre-load path) cannot register
    // duplicate handlers that would fire the callback more than once.
    rt.remove_resolved_events(ident);

    for event in rt.events_snapshot() {
        if let Ok(idx) = amx.find_public(event.name) {
            rt.push_resolved_event(ident, i32::from(idx), event.handler);
        }
    }
}

/// Installs the `amx_Exec` detour from the AMX function table. Idempotent —
/// once the `OnceLock` is set every later call short-circuits.
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
fn install_exec_hook(fn_table: usize) {
    if EXEC_DETOUR.get().is_some() || fn_table == 0 {
        return;
    }

    // `Exec::from_table` panics on a null table; guarded above. The returned
    // safe `fn` coerces to the `unsafe extern "C" fn` the detour expects.
    let target: ExecFn = Exec::from_table(fn_table);

    // SAFETY: `target` is the server's real `amx_Exec`; retour builds a
    // trampoline that preserves the original code. `exec_detour` never unwinds
    // across the boundary (it wraps dispatch in `catch_unwind`).
    let detour = match unsafe { GenericDetour::new(target, exec_detour) } {
        Ok(detour) => detour,
        Err(err) => {
            log::warn!("[rust-samp] failed to build amx_Exec detour: {err}; events will not fire");
            return;
        }
    };

    // Store before enabling so a callback that fires mid-install already finds
    // the detour and can reach the original trampoline.
    let cell = EXEC_DETOUR.get_or_init(|| ExecDetour(detour));

    // SAFETY: enabling rewrites the target prologue; retour keeps the original
    // reachable via the trampoline used by `call`.
    if let Err(err) = unsafe { cell.0.enable() } {
        log::warn!("[rust-samp] failed to enable amx_Exec detour: {err}; events will not fire");
    }
}

/// On non-x86 arches the detour library is unavailable, so events never fire.
/// This keeps the public API (`#[event]`, `events: [...]`) compiling everywhere
/// — the aarch64 check job builds the lib without a hook.
#[cfg(not(any(target_arch = "x86", target_arch = "x86_64")))]
fn install_exec_hook(_fn_table: usize) {}

/// Trampoline installed in place of `amx_Exec`. Dispatches to matching event
/// handlers; a handler may suppress the gamemode's public, otherwise it runs
/// unchanged.
///
/// # Safety
/// Installed by retour as the replacement for the VM's `amx_Exec`; the server
/// calls it with the same arguments the original expects.
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
unsafe extern "C" fn exec_detour(amx: *mut AMX, retval: *mut i32, index: i32) -> i32 {
    // A panic must never cross back into the VM's C code. On panic, fall through
    // to the original public (no suppression).
    let suppressed =
        std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| dispatch(amx, index)))
            .unwrap_or(None);

    if let Some(value) = suppressed {
        // A handler cancelled the callback: skip the original public, hand
        // `value` back as its return value, and report success (AMX_ERR_NONE).
        if !retval.is_null() {
            unsafe { *retval = value };
        }
        return 0;
    }

    // SAFETY: delegates to retour's preserved trampoline with the original args.
    match EXEC_DETOUR.get() {
        Some(cell) => unsafe { cell.0.call(amx, retval, index) },
        None => 0,
    }
}

// Tracks the `(amx, public index)` pairs currently being dispatched on this
// thread, so a handler that re-enters the VM on the *same* public does not
// recurse into dispatch again (which could loop unbounded).
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
thread_local! {
    static ACTIVE: RefCell<HashSet<(usize, i32)>> = RefCell::new(HashSet::new());
}

/// RAII guard for the reentrancy set: [`acquire`] inserts the key (returning
/// `None` if it was already dispatching) and `Drop` removes it — so the key is
/// cleared even if a handler unwinds.
///
/// [`acquire`]: ActiveGuard::acquire
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
struct ActiveGuard(usize, i32);

#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
impl ActiveGuard {
    fn acquire(key: (usize, i32)) -> Option<Self> {
        ACTIVE.with(|active| {
            active
                .borrow_mut()
                .insert(key)
                .then_some(ActiveGuard(key.0, key.1))
        })
    }
}

#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
impl Drop for ActiveGuard {
    fn drop(&mut self) {
        ACTIVE.with(|active| {
            active.borrow_mut().remove(&(self.0, self.1));
        });
    }
}

/// Core dispatch: for the public `index` being executed on `amx_ptr`, run every
/// event handler registered for that `(amx, index)` pair, in registration order.
///
/// Returns `Some(value)` if a handler suppressed the callback (the first one to
/// do so wins and the rest are skipped), `None` to run the gamemode's public.
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
fn dispatch(amx_ptr: *mut AMX, index: i32) -> Option<i32> {
    // Only user-defined publics carry gamemode callbacks; skip main/continue.
    let AmxExecIdx::UserDef(idx) = AmxExecIdx::from(index) else {
        return None;
    };
    if amx_ptr.is_null() {
        return None;
    }

    let rt = Runtime::get();
    let ident = AmxIdent::from(amx_ptr);
    let handlers = rt.resolved_handlers(ident, idx);
    if handlers.is_empty() {
        return None;
    }

    // Reentrancy guard: a handler re-entering the same public runs it directly
    // rather than dispatching again. Dropped (key cleared) on every return path,
    // including a handler unwind.
    let _guard = ActiveGuard::acquire((amx_ptr as usize, idx))?;

    let amx = crate::amx::get(ident)?;
    let params = read_stack_params(amx_ptr, amx)?;

    let mut args = Args::new(amx, params.as_ptr());
    for handler in handlers {
        // Each handler reads the same argument list from the start.
        args.reset();
        if let EventReturn::Suppress(value) = handler(amx, &mut args) {
            return Some(value);
        }
    }
    None
}

/// Rebuilds the native-style parameter table (`[byte_count, arg0, arg1, …]`)
/// from the callback arguments the gamemode pushed onto the VM stack, so the
/// existing [`Args`] machinery can parse them exactly like a native call.
///
/// Returns `None` if the stack layout is inconsistent (negative param count or
/// an out-of-bounds cell) — a corrupt frame is skipped rather than trusted.
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
fn read_stack_params(amx_ptr: *mut AMX, amx: &Amx) -> Option<Vec<i32>> {
    // SAFETY: `amx_ptr` is non-null (checked by the caller). `AMX` is `repr(C)`;
    // `read_unaligned` is defensive and never assumes field alignment.
    let (paramcount, stk) = unsafe {
        (
            std::ptr::addr_of!((*amx_ptr).paramcount).read_unaligned(),
            std::ptr::addr_of!((*amx_ptr).stk).read_unaligned(),
        )
    };

    if paramcount < 0 {
        return None;
    }
    let count = paramcount as usize;

    let mut params = Vec::with_capacity(count + 1);
    // Args reads slot 0 as "bytes used by the arguments" and divides by 4.
    params.push(paramcount.checked_mul(4)?);

    for k in 0..count {
        let offset = i32::try_from(k).ok()?.checked_mul(4)?;
        let addr = stk.checked_add(offset)?;
        params.push(amx.read_cell(addr)?);
    }

    Some(params)
}

#[cfg(test)]
mod tests {
    use super::*;
    use samp_sdk::cell::Ref;

    fn handler_stub(_amx: &Amx, _args: &mut Args) -> EventReturn {
        EventReturn::Continue
    }

    #[test]
    fn event_info_is_copy_and_holds_fields() {
        let info = EventInfo {
            name: "OnPlayerConnect",
            handler: handler_stub,
        };
        let copy = info;
        assert_eq!(copy.name, "OnPlayerConnect");
    }

    #[test]
    fn event_return_suppress_carries_value() {
        assert_eq!(EventReturn::Suppress(1), EventReturn::Suppress(1));
        assert_ne!(EventReturn::Continue, EventReturn::Suppress(0));
    }

    #[test]
    fn event_return_typed_suppress_encodes_cells() {
        // i32 identity, bool -> 0/1, f32 -> IEEE-754 bits.
        assert_eq!(EventReturn::suppress(42_i32), EventReturn::Suppress(42));
        assert_eq!(EventReturn::suppress(true), EventReturn::Suppress(1));
        assert_eq!(EventReturn::suppress(false), EventReturn::Suppress(0));
        assert_eq!(
            EventReturn::suppress(1.5_f32),
            EventReturn::Suppress(1.5_f32.to_bits().cast_signed())
        );
    }

    #[test]
    fn synthetic_params_parse_back_through_args() {
        // A public with two integer args: build the native-style param table the
        // dispatcher would hand to `Args` and verify round-tripping.
        let params: [i32; 3] = [2 * 4, 7, 42];
        let amx = Amx::new(std::ptr::null_mut(), 0);
        let mut args = Args::new(&amx, params.as_ptr());
        assert_eq!(args.count(), 2);
        assert_eq!(args.next_arg::<i32>(), Some(7));
        assert_eq!(args.next_arg::<i32>(), Some(42));
        assert_eq!(args.next_arg::<i32>(), None);
    }

    #[test]
    fn zero_arg_public_yields_empty_arg_list() {
        let params: [i32; 1] = [0];
        let amx = Amx::new(std::ptr::null_mut(), 0);
        let args = Args::new(&amx, params.as_ptr());
        assert_eq!(args.count(), 0);
        assert!(args.get::<Ref<i32>>(0).is_none());
    }
}