rust-samp 3.6.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
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
//! 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;
// Only the `amx_Exec` hook logs, and it exists only where `retour` can build one.
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
use crate::macros::sdk_warn;
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::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;

/// The handlers of one script, by public index: `None` for a public no
/// handler watches.
pub(crate) type EventTable = Vec<Option<std::rc::Rc<[EventHandler]>>>;

/// 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 mut by_index: Vec<Vec<EventHandler>> = Vec::new();
    for event in rt.events_snapshot() {
        let Ok(index) = amx.find_public(event.name) else {
            continue;
        };
        let Ok(index) = usize::try_from(i32::from(index)) else {
            continue;
        };
        if by_index.len() <= index {
            by_index.resize_with(index + 1, Vec::new);
        }
        by_index[index].push(event.handler);
    }
    let table: EventTable = by_index
        .into_iter()
        .map(|handlers| (!handlers.is_empty()).then(|| handlers.into()))
        .collect();

    // Replaces any prior resolution for this AMX, 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.set_resolved_events(AmxIdent::from(ptr.as_ptr()), table);
}

/// 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;
    }

    // The returned safe `fn` coerces to the `unsafe extern "C" fn` the detour
    // expects. A table without `amx_Exec` leaves nothing to hook.
    let Some(exec) = Exec::try_from_table(fn_table) else {
        sdk_warn!("the AMX function table has no amx_Exec; #[event] handlers will not fire");
        return;
    };
    let target: ExecFn = exec;

    // 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) => {
            sdk_warn!("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() } {
        sdk_warn!("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 = crate::panic_guard::catch(|| 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).
        // The arguments the caller pushed are consumed as the call would have.
        unsafe { consume_arguments(amx) };
        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,
    }
}

/// What `amx_Exec` does with the arguments of a public it runs: the caller
/// pushed them (`amx_Push`, `paramcount` counting them), and the call takes
/// them off the stack (`stk += paramcount * cell`, `paramcount = 0`). A
/// suppressed public skips the call, so it must do the same — otherwise each
/// one leaves its arguments on the script's stack and a stale `paramcount` for
/// the next call, and in a few hundred calls the script's stack runs into its
/// heap and the script stops running.
///
/// # Safety
/// `amx` must be null or point to a live `AMX`.
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
unsafe fn consume_arguments(amx: *mut AMX) {
    if amx.is_null() {
        return;
    }
    // SAFETY: `amx` is a live `AMX` (caller's contract); the fields are read
    // and written unaligned, as everywhere else for this packed struct.
    unsafe {
        let paramcount = std::ptr::addr_of!((*amx).paramcount).read_unaligned();
        let stk = std::ptr::addr_of!((*amx).stk).read_unaligned();
        let consumed = paramcount
            .max(0)
            .checked_mul(4)
            .and_then(|bytes| stk.checked_add(bytes));
        if let Some(stk) = consumed {
            std::ptr::addr_of_mut!((*amx).stk).write_unaligned(stk);
        }
        std::ptr::addr_of_mut!((*amx).paramcount).write_unaligned(0);
    }
}

/// Marks `(amx, public index)` as being dispatched for as long as it lives, so
/// a handler that re-enters the VM on the *same* public does not recurse into
/// dispatch again (which could loop unbounded). Cleared on drop, including when
/// a handler unwinds.
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
struct ActiveGuard<'rt> {
    rt: &'rt Runtime,
    key: (AmxIdent, i32),
}

#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
impl<'rt> ActiveGuard<'rt> {
    fn acquire(rt: &'rt Runtime, ident: AmxIdent, index: i32) -> Option<Self> {
        rt.enter_dispatch(ident, index).then_some(ActiveGuard {
            rt,
            key: (ident, index),
        })
    }
}

#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
impl Drop for ActiveGuard<'_> {
    fn drop(&mut self) {
        self.rt.leave_dispatch(self.key.0, self.key.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)?;

    // 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(rt, ident, idx)?;

    let amx = crate::amx::get(ident)?;
    let mut inline = [0i32; INLINE_PARAMS + 1];
    let mut spilled = Vec::new();
    let params = read_stack_params(amx_ptr, amx, &mut inline, &mut spilled)?;

    let mut args = Args::new(amx, params.as_ptr());
    for handler in handlers.iter() {
        // 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
}

/// Callbacks with up to this many arguments are read into a buffer on the
/// stack; longer ones (rare) into a `Vec`.
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
const INLINE_PARAMS: usize = 16;

/// 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.
/// The table goes into `inline` when it fits, otherwise into `spilled`.
///
/// 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<'b>(
    amx_ptr: *mut AMX,
    amx: &Amx,
    inline: &'b mut [i32; INLINE_PARAMS + 1],
    spilled: &'b mut Vec<i32>,
) -> Option<&'b mut [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(),
        )
    };

    let count = usize::try_from(paramcount).ok()?;
    let params: &mut [i32] = if count <= INLINE_PARAMS {
        &mut inline[..=count]
    } else {
        spilled.resize(count + 1, 0);
        spilled
    };

    // Args reads slot 0 as "bytes used by the arguments" and divides by 4.
    params[0] = paramcount.checked_mul(4)?;
    let mut addr = stk;
    for slot in &mut params[1..] {
        *slot = amx.read_cell(addr)?;
        addr = addr.checked_add(4)?;
    }

    Some(params)
}

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

    #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
    #[test]
    fn a_suppressed_public_consumes_its_arguments_like_amx_exec() {
        extern "C" fn callback(_: *mut AMX, _: i32, _: *mut i32, _: *mut i32) -> i32 {
            0
        }
        extern "C" fn debug(_: *mut AMX) -> i32 {
            0
        }
        // Two arguments pushed: the stack went down 8 bytes from 4096.
        let mut amx = AMX {
            base: std::ptr::null_mut(),
            data: std::ptr::null_mut(),
            callback,
            debug,
            cip: 0,
            frm: 0,
            hea: 0,
            hlw: 0,
            stk: 4096 - 8,
            stp: 4096,
            flags: 0,
            usertags: [0; 4],
            userdata: [std::ptr::null_mut(); 4],
            error: 0,
            paramcount: 2,
            pri: 0,
            alt: 0,
            reset_stk: 0,
            reset_hea: 0,
            sysreq_d: 0,
        };
        unsafe { consume_arguments(&raw mut amx) };
        assert_eq!({ amx.stk }, 4096);
        assert_eq!({ amx.paramcount }, 0);

        // Nothing pushed: nothing to consume.
        unsafe { consume_arguments(&raw mut amx) };
        assert_eq!({ amx.stk }, 4096);
        unsafe { consume_arguments(std::ptr::null_mut()) };
    }

    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());
    }
}