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
/*!
    Core of SDK to interact with AMX.
*/

use std::ptr::{read};
use std::mem::{transmute, transmute_copy, size_of};
use std::ffi::CString;
use types;
use types::Cell;
use consts::*;
use data::amx_functions;

pub type AmxResult<T> = Result<T, AmxError>;

/// Converts a raw AMX error to `AmxError`.
macro_rules! ret {
    ($res:ident, $ret:expr) => {
        {
            if $res == 0 {
                Ok($ret)
            } else {
                Err(AmxError::from($res))
            }
        }
    }
}

/// Makes an call to any AMX functions and uses `ret!`.
macro_rules! call {
    (
        $ex:expr
        =>
        $ret:expr
    ) => {
        {
            let result = $ex;
            ret!(result, $ret)
        }
    }
}

/// Gets a function from a raw pointer in `data::amx_functions`.
macro_rules! import {
    ($type:ident) => {
        unsafe {
            read(amx_functions.offset(Exports::$type as isize) as *const $crate::types::$type)
        }
    };
}

/// AMX struct that holds raw `types::AMX` pointer.
pub struct AMX {
    amx: *mut types::AMX,
}

impl AMX {
    /// Converts a raw `types::AMX` pointer.
    ///
    /// Shouldn't used directly in your code. `AMX::new()` is calling from raw natives functions.
    pub fn new(amx: *mut types::AMX) -> AMX {
        AMX {
            amx,
        }
    }

    /// Registers natives functions
    ///
    /// # Examples
    /// 
    /// ```
    /// fn amx_load(amx: AMX) -> Cell {
    ///     let natives = natives!{
    ///         "SomeFunction" => some_function,
    ///         "AnotherFunction" => another_function   
    ///     };
    /// 
    ///     amx.register(&natives).unwrap();
    ///     
    ///     AMX_ERR_NONE
    /// }
    /// ```
    pub fn register(&self, natives: &Vec<types::AMX_NATIVE_INFO>) -> AmxResult<()> {
        let len = natives.len();
        let ptr = natives.as_slice().as_ptr();

        let register = import!(Register);
        call!(register(self.amx, ptr, len as i32) => ())
    }

    /// Allocates memory cells inside AMX.
    /// 
    /// # Return
    /// Return typle of two addresses:
    /// * The address of the variable relatived to AMX data section.
    /// * The physical address.
    ///
    /// # Examples
    /// Allot one cell to a reference to a value and push it.
    /// ```
    /// let (amx_addr, phys_addr) = amx.allot(1)?;
    /// let value: &mut i32 = phys_addr as &mut i32;
    /// *value = 655;
    /// amx.push(amx_addr)?;
    /// ```
    pub fn allot(&self, cells: usize) -> AmxResult<(Cell, usize)> {
        let amx_addr = 0;
        let phys_addr = 0;

        let allot = import!(Allot);

        unsafe {
            call!(allot(self.amx, cells as i32, transmute(&amx_addr), transmute(&phys_addr)) => (amx_addr, phys_addr))
        }
    }

    /// Frees all memory **above** input address.
    pub fn release(&self, address: Cell) -> AmxResult<()> {
        let release = import!(Release);
        call!(release(self.amx, address) => ())
    }

    /// Get an address of a reference value given to native.
    ///
    /// # Examples
    ///
    /// ```
    /// // native: SomeNative(&int_value);
    /// fn some_native(amx: &AMX, args: *mut Cell) -> Cell {
    ///     let ptr = std::ptr::read(args.offset(1));
    ///     let int_value: &mut i32 = amx.get_address(ptr).unwrap();
    ///     *int_value = 10;
    /// }
    /// ```
    pub fn get_address<'a, T: Sized>(&self, address: Cell) -> AmxResult<&'a mut T> {
        unsafe {
            let header = (*self.amx).base as *const types::AMX_HEADER;
            
            let data = if (*self.amx).data.is_null() {
                (*self.amx).base as usize + (*header).dat as usize
            } else {
                (*self.amx).data as usize
            };

            if address >= (*self.amx).hea && address < (*self.amx).stk || address < 0 || address >= (*self.amx).stp {
                Err(AmxError::MemoryAccess)
            } else {
                Ok(transmute(data + address as usize))
            }
        }
    }

    /// Pushes a primitive value or an address to AMX stack.
    ///
    /// # Examples
    ///
    /// ```
    /// let index = amx.find_public("OnPlayerHPChanged").unwrap();
    /// let player_id: u32 = 12;
    /// let health: f32 = 100.0;
    ///
    /// amx.push(health);
    /// amx.push(player_id);
    /// amx.exec(index);
    /// ```
    pub fn push<T: Sized>(&self, value: T) -> AmxResult<()> {
        let push = import!(Push);
        
        unsafe {
            call!(push(self.amx, transmute_copy(&value)) => ())
        }
    }

    /// Pushes a slice to the AMX stack.
    ///
    /// # Examples
    ///
    /// ```
    /// let func = amx.find_public("GiveMeArray")?;
    /// let player_data = vec![1, 2, 3, 4, 5];
    /// let player_ids = vec![1, 2, 3, 4, 5];
    /// 
    /// let amx_addr = amx.push_array(&player_data)?; // push an array and save address relatived to first item on the heap.
    /// amx.push_array(&player_ids)?; // push the next array
    /// amx.exec(func)?; // exec the public
    /// amx.release(amx_addr)?; // release all allocated memory inside AMX
    /// ```
    pub fn push_array<T: Sized>(&self, array: &[T]) -> AmxResult<Cell> {
        let (amx_addr, phys_addr) = self.allot(array.len())?;
        let dest = phys_addr as *mut Cell;

        for i in 0..array.len() {
            unsafe {
                *(dest.offset(i as isize)) = transmute_copy(&array[i]);
            }
        }

        self.push(amx_addr)?;
        Ok(amx_addr)
    }

    /// Allots memory for a string and pushes it to the AMX stack.
    ///
    /// Please, don't use it directly! Better use macros `exec!`, `exec_public!` and `exec_native!`.
    pub fn push_string(&self, string: &str, packed: bool) -> AmxResult<Cell> {
        if packed {
            unimplemented!()
        } else {
            let bytes = string.as_bytes();
            let (amx_addr, phys_addr) = self.allot(bytes.len() + 1)?;
            let dest = phys_addr as *mut Cell;

            for i in 0..string.len() {
                unsafe {
                    *(dest.offset(i as isize)) = transmute_copy(&bytes[i]);
                }
            }

            unsafe {
                *(dest.offset(string.len() as isize)) = 0;
            }

            self.push(amx_addr)?;
            Ok(amx_addr)
        }
    }

    /// Execs an AMX function.
    ///
    /// # Examples
    ///
    /// ```
    /// let index = amx.find_native("GetPlayerMoney").unwrap();
    /// amx.push(1); // a player with ID 1
    /// 
    /// match amx.exec(index) {
    ///     Ok(money) => log!("Player has {} money.", money),
    ///     Err(err) => log!("Error: {:?}", err),
    /// }
    /// ```
    pub fn exec(&self, index: i32) -> AmxResult<i64> {
        let exec = import!(Exec);

        let retval = -1;
        unsafe {
            call!(exec(self.amx, transmute(&retval), index) => retval)
        }
    }

    /// Returns an index of a public by its name.
    ///
    /// # Examples
    ///
    /// ```
    /// let public_index = amx.find_public("OnPlayerConnect").unwrap();
    /// ```
    pub fn find_public(&self, name: &str) -> AmxResult<i32> {
        let find_public = import!(FindPublic);

        let index = -1;
        let c_name = CString::new(name).unwrap();
        
        unsafe {
            call!(find_public(self.amx, c_name.as_ptr(), transmute(&index)) => index)
        }
    }

    /// Returns an index of a native by its name.
    ///
    /// # Examples
    /// See `find_public` and `exec` examples.
    pub fn find_native(&self, name: &str) -> AmxResult<i32> {
        let find_native = import!(FindNative);

        let index = -1;
        let c_name = CString::new(name).unwrap();
        
        unsafe {
            call!(find_native(self.amx, c_name.as_ptr(), transmute(&index)) => index)
        }
    }

    /// Returns a pointer to a public variable.
    pub fn find_pubvar<T: Sized>(&self, name: &str) -> AmxResult<&mut T> {
        let find_pubvar = import!(FindPubVar);

        let value: Cell = 0;
        let c_name = CString::new(name).unwrap();

        unsafe {
            let retval = find_pubvar(self.amx, c_name.as_ptr(), transmute(&value));
            
            if retval == 0 {
                self.get_address(value)
            } else {
                Err(AmxError::from(retval))
            }
        }
    }

    /// Gets length of a string.
    pub fn string_len(&self, address: *const Cell) -> AmxResult<usize> {
        let string_len = import!(StrLen);
        let mut length = 0;
        
        call!(string_len(address, &mut length) => length as usize)
    }

    /// Gets a string from AMX.
    /// 
    /// # Examples
    /// 
    /// ```
    /// fn raw_function(&self, amx: &AMX, params: *mut types::Cell) -> AmxResult<Cell> {
    ///     unsafe {
    ///         let ptr = std::ptr::read(params.offset(1));
    ///         let mut addr = amx.get_address::<i32>(ptr)?; // get a pointer from amx
    ///         let len = amx.string_len(addr.as_mut())?; // get string length in amx
    ///         let string = amx.get_string(addr.as_mut(), len + 1)?; // convert amx string to rust String
    ///        
    ///         log!("got string: {}", string);
    ///
    ///         std::mem::forget(addr);
    ///     }
    ///
    ///     Ok(0)
    /// }
    /// ```
    pub fn get_string(&self, address: *const Cell, size: usize) -> AmxResult<String> {
        const UNPACKEDMAX: u32 = ((1u32 << (size_of::<u32>() - 1) * 8) - 1u32);
        const CHARBITS: usize = 8 * size_of::<u8>();

        let mut string = Vec::with_capacity(size);
        
        unsafe {
            if read(address) as u32 > UNPACKEDMAX {
                // packed string
                let mut i = size_of::<Cell>() - 1;
                let mut cell = 0;
                let mut ch;
                let mut length = 0;
                let mut offset = 0;

                while length < size {
                    if i == size_of::<Cell>() - 1 {
                        cell = read(address.offset(offset));
                        offset += 1;
                    }

                    ch = (cell >> i * CHARBITS) as u8;

                    if ch == 0 {
                        break;
                    }

                    string.push(ch);
                    length += 1;
                    i = (i + size_of::<Cell>() - 1) % size_of::<Cell>();
                }
            } else {
                let mut length = 0;
                let mut byte = read(address.offset(length));

                while byte != 0 && length < size as isize {
                    string.push(byte as u8);
                    length += 1;
                    byte = read(address.offset(length));
                }
            }
            Ok(String::from_utf8_unchecked(string))
        }
    }

    /// Raises an AMX error.
    pub fn raise_error(&self, error: AmxError) -> AmxResult<()> {
        let raise_error = import!(RaiseError);
        call!(raise_error(self.amx, error as i32) => ())
    }
}

/// Custom error type for AMX errors.
/// Can be casted from i32
///
/// # Examples
/// 
/// ```
/// let find_public: samp_sdk::types::FindPublic_t = ...;
/// let result = find_public(...);
/// return AmxError::from(result);
/// ```
#[derive(Debug)]
pub enum AmxError {
    Exit = 1,
    Assert = 2,
    StackError = 3,
    Bounds = 4,
    MemoryAccess = 5,
    InvalidInstruction = 6,
    StackLow = 7,
    HeapLow = 8,
    Callback = 9,
    Native = 10,
    Divide = 11,
    Sleep = 12,
    InvalidState = 13,
    Memory = 16,
    Format = 17,
    Version = 18,
    NotFound = 19,
    Index = 20,
    Debug = 21,
    Init = 22,
    UserData = 23,
    InitJit = 24,
    Params = 25,
    Domain = 26,
    General = 27,
    Unknown,
}

impl From<i32> for AmxError {
    fn from(val: i32) -> Self {
        match val {
            1 => AmxError::Exit,
            2 => AmxError::Assert,
            3 => AmxError::StackError,
            4 => AmxError::Bounds,
            5 => AmxError::MemoryAccess,
            6 => AmxError::InvalidInstruction,
            7 => AmxError::StackLow,
            8 => AmxError::HeapLow,
            9 => AmxError::Callback,
            10 => AmxError::Native,
            11 => AmxError::Divide,
            12 => AmxError::Sleep,
            13 => AmxError::InvalidState,
            16 => AmxError::Memory,
            17 => AmxError::Format,
            18 => AmxError::Version,
            19 => AmxError::NotFound,
            20 => AmxError::Index,
            21 => AmxError::Debug,
            22 => AmxError::Init,
            23 => AmxError::UserData,
            24 => AmxError::InitJit,
            25 => AmxError::Params,
            26 => AmxError::Domain,
            27 => AmxError::General,
            _ => AmxError::Unknown,
        }
    }
}