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
use std::iter;
use proc_macro::TokenStream;
use quote::quote;
use darling::FromField;

/// (**Required** Callback) Called when the plugin is being uninitialized
///
///### Example
///
/// ```rust
///use panda::PluginHandle;
///
/// #[panda::init]
/// fn start(_: &mut PluginHandle) {
///     println!("Plugin started up!");
/// }
/// ```
#[proc_macro_attribute]
pub fn init(_: TokenStream, function: TokenStream) -> TokenStream {
    let func = syn::parse_macro_input!(function as syn::ItemFn);

    let args = if func.sig.inputs.is_empty() {
        None
    } else {
        Some(quote!( unsafe { &mut *plugin } ))
    };

    let func_name = &func.sig.ident;

    quote!(
        mod __panda_internal {
            use super::*;

            #[no_mangle]
            unsafe extern "C" fn init_plugin(plugin: *mut ::panda::PluginHandle) {
                for cb in ::panda::inventory::iter::<::panda::Callback> {
                    ::panda::sys::panda_register_callback(plugin as _, cb.cb_type, ::core::mem::transmute(cb.fn_pointer));
                }

                for cb in ::panda::inventory::iter::<::panda::PPPCallbackSetup> {
                    cb.0();
                }

                #func_name(#args);
            }

            #[no_mangle]
            unsafe extern "C" fn uninit_plugin(plugin: *mut ::panda::PluginHandle) {
                for cb in ::panda::inventory::iter::<::panda::UninitCallback> {
                    cb.0(unsafe { &mut *plugin });
                }
            }
        }

        #func
    ).into()
}

/// (Callback) Called when the plugin is being uninitialized
#[proc_macro_attribute]
pub fn uninit(_: TokenStream, function: TokenStream) -> TokenStream {
    let func = syn::parse_macro_input!(function as syn::ItemFn);
    let func_name = &func.sig.ident;

    quote!(
        ::panda::inventory::submit! {
            #![crate = ::panda]
            ::panda::UninitCallback(#func_name)
        }

        #func
    ).into()
}

#[derive(FromField)]
#[darling(attributes(arg))]
struct DeriveArgs {
    #[darling(default)]
    about: Option<String>,
    #[darling(default)]
    default: Option<syn::Lit>,
    #[darling(default)]
    required: bool,
    ident: Option<syn::Ident>,
    ty: syn::Type,
}

fn derive_args_to_mappings(
    DeriveArgs { about, default, ident, ty, required }: DeriveArgs
) -> (syn::Stmt, syn::Ident) {
    let name = &ident;
    let default = if let Some(default) = default {
        match default {
            syn::Lit::Str(string) => quote!(::std::string::String::from(#string)),
            default => quote!(#default)
        }
    } else {
        quote!(Default::default())
    };
    let about = about.unwrap_or_default();
    (
        syn::parse_quote!(
            let #name = <#ty as ::panda::panda_arg::GetPandaArg>::get_panda_arg(
                __args_ptr,
                stringify!(#name),
                #default,
                #about,
                #required
            );
        ),
        ident.unwrap()
    )
}

fn get_field_statements(fields: &syn::Fields) -> Result<(Vec<syn::Stmt>, Vec<syn::Ident>), darling::Error> {
    Ok(fields
        .iter()
        .map(DeriveArgs::from_field)
        .collect::<Result<Vec<_>, _>>()?
        .into_iter()
        .map(derive_args_to_mappings)
        .unzip())
}

fn get_name(attrs: &[syn::Attribute]) -> Option<String> {
    attrs.iter()
        .find(|attr| attr.path.get_ident().map(|x| x.to_string() == "name").unwrap_or(false))
        .map(|attr| attr.parse_meta().ok())
        .flatten()
        .map(|meta| if let syn::Meta::NameValue(syn::MetaNameValue { lit: syn::Lit::Str(s), .. }) = meta {
            Some(s.value())
        } else {
            None
        })
        .flatten()
}

#[proc_macro_derive(PandaArgs, attributes(name, arg))]
pub fn derive_panda_args(input: TokenStream) -> TokenStream {
    let input = syn::parse_macro_input!(input as syn::ItemStruct);

    let name = match get_name(&input.attrs) {
        Some(name) => name,
        None => return quote!(compile_error!("Missing plugin name, add `#[name = ...]` above struct")).into(),
    };

    let ident = &input.ident;

    match get_field_statements(&input.fields) {
        Ok((statements, fields)) => {
            let format_args =
                iter::repeat("{}={}")
                    .take(statements.len())
                    .collect::<Vec<_>>()
                    .join(",");
            quote!(
                impl ::panda::PandaArgs for #ident {
                    fn from_panda_args() -> Self {
                        let name = ::std::ffi::CString::new(#name).unwrap();

                        unsafe {
                            let __args_ptr = ::panda::sys::panda_get_args(name.as_ptr());

                            #(
                                #statements
                            )*

                            ::panda::sys::panda_free_args(__args_ptr);

                            Self {
                                #(#fields),*
                            }
                        }
                    }

                    fn to_panda_args_str(&self) -> ::std::string::String {
                        format!(
                            concat!(#name, ":", #format_args),
                            #(
                                stringify!(#fields), self.#fields
                            ),*
                       )
                    }
                }
            )
        },
        Err(err) => err.write_errors()
    }.into()
}

struct Idents(syn::Ident, syn::Ident);

impl syn::parse::Parse for Idents {
    fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> {
        Ok(Idents(
            input.parse()?,
            input.parse()?
        ))
    }
}

fn get_cfg_attrs(func: &syn::ItemFn) -> Vec<syn::Attribute> {
    func.attrs.iter()
        .filter(|attr| attr.path.get_ident().map(|x| x.to_string() == "cfg").unwrap_or(false))
        .map(|attr| attr.clone())
        .collect()
}

macro_rules! define_callback_attributes {
    ($(
        $($doc:literal)*
        ($attr_name:ident, $const_name:ident, ($($arg:ty),*) $(-> $ret:ty)?)
    ),*) => {
        $(
            doc_comment::doc_comment!{
                concat!(
                    "(Callback) ",
                    $($doc, "\n",)*
                    "\n\nCallback arguments: (",
                    $("`", stringify!($arg), "`, ",)*
                    ")\n### Example\n```rust\nuse panda::prelude::*;\n\n#[panda::",
                    stringify!($attr_name),
                    "]\nfn callback(",
                    $("_: ", stringify!($arg), ", ", )* ")",
                    $(" -> ", stringify!($ret),)?
                    " {\n    // do stuff\n}\n```"),
                #[proc_macro_attribute]
                pub fn $attr_name(_: TokenStream, function: TokenStream) -> TokenStream {
                    let mut function = syn::parse_macro_input!(function as syn::ItemFn);
                    function.sig.abi = Some(syn::parse_quote!(extern "C"));
                    let func = &function.sig.ident;
                    let cfgs = crate::get_cfg_attrs(&function);

                    quote!(
                        #(
                            #cfgs
                         )*
                        const _: fn() = || {
                            use ::panda::sys::*;
                            fn assert_callback_arg_types(_ : extern "C" fn($($arg),*) $(-> $ret)?) {}

                            assert_callback_arg_types(#func);
                        };

                        ::panda::inventory::submit! {
                            #![crate = ::panda]
                            ::panda::Callback::new(
                                ::panda::sys::$const_name,
                                #func as *const ()
                            )
                        }

                        #function
                    ).into()
                }
            }
        )*
    }
}

macro_rules! define_syscalls_callbacks {
    ($(
        $($doc:literal)*
        (
            $attr_name:ident,
            $cb_name:ident,
            $syscall_name:ident,
            $before_or_after:literal,
            ($($arg_name:ident : $arg:ty),* $(,)?)
        )
    ),* $(,)?) => {
        $(
            doc_comment::doc_comment!{
                concat!(
                    "(Callback) A callback that runs ",
                    $before_or_after,
                    " the ",
                    stringify!($syscall_name),
                    " syscall runs.\n\nCallback arguments: (",
                    $("`", stringify!($arg), "`,",)*
                    ")\n### Example\n```rust\nuse panda::prelude::*;\n\n#[panda::",
                    stringify!($attr_name),
                    "]\nfn callback(",
                    $("_: ", stringify!($arg), ", ",)*
                    ") {\n    // do stuff\n}\n```"
                ),
                #[proc_macro_attribute]
                pub fn $attr_name(_: TokenStream, function: TokenStream) -> TokenStream {
                    let mut function = syn::parse_macro_input!(function as syn::ItemFn);
                    function.sig.abi = Some(syn::parse_quote!(extern "C"));
                    let func = &function.sig.ident;
                    let cfgs = crate::get_cfg_attrs(&function);

                    quote!(
                        #(
                            #cfgs
                         )*
                        ::panda::inventory::submit! {
                            #![crate = ::panda]
                            ::panda::PPPCallbackSetup(
                                || {
                                    ::panda::plugins::syscalls2::SYSCALLS.$cb_name(#func);
                                }
                            )
                        }

                        #function
                    ).into()
                }
            }
        )*

        /// For internal use only
        #[proc_macro]
        #[doc(hidden)]
        pub fn generate_syscalls_callbacks(_: TokenStream) -> TokenStream {
            quote!(
                plugin_import!{
                    static SYSCALLS: Syscalls2 = extern "syscalls2" {
                        callbacks {
                            $(
                                fn $attr_name(
                                    //cpu: &mut crate::sys::CPUState,
                                    //pc: crate::sys::target_ulong,
                                    $($arg_name : $arg),*
                                );
                            )*
                            //fn on_sys_read_enter(fd: target_ulong, buf: target_ptr_t, count: target_ulong);
                            //fn on_sys_write_enter(fd: target_ulong, buf: target_ptr_t, count: target_ulong);
                        }
                    };
                }
            ).into()
        }
    };
}

macro_rules! define_hooks2_callbacks {
    ($(
        $($doc:literal)*
        fn($cb_name:ident) $attr_name:ident ($($arg_name:ident : $arg:ty),* $(,)?);
    )*) => {
        $(
            doc_comment::doc_comment!{
                concat!("(Callback) ", $($doc, "\n",)* "\n\nCallback arguments: ("$(, "`", stringify!($arg), "`")*, ")\n### Example\n```rust\nuse panda::prelude::*;\n\n#[panda::", stringify!($attr_name),"]\nfn callback(", $(", _: ", stringify!($arg), )* ") {\n    // do stuff\n}\n```"),
                #[proc_macro_attribute]
                pub fn $attr_name(_: TokenStream, function: TokenStream) -> TokenStream {
                    let mut function = syn::parse_macro_input!(function as syn::ItemFn);
                    function.sig.abi = Some(syn::parse_quote!(extern "C"));
                    let func = &function.sig.ident;
                    let cfgs = crate::get_cfg_attrs(&function);

                    quote!(
                        #(
                            #cfgs
                         )*
                        ::panda::inventory::submit! {
                            #![crate = ::panda]
                            ::panda::PPPCallbackSetup(
                                || {
                                    ::panda::plugins::hooks2::HOOKS.$cb_name(#func);
                                }
                            )
                        }

                        #function
                    ).into()
                }
            }
        )*

        /// For internal use only
        #[doc(hidden)]
        #[proc_macro]
        pub fn generate_hooks2_callbacks(_: TokenStream) -> TokenStream {
            quote!(

                plugin_import!{
                    static HOOKS: Hooks2 = extern "hooks2" {
                        callbacks {
                            $(
                                fn $attr_name(
                                    $($arg_name : $arg),*
                                );
                            )*
                        }
                    };
                }
            ).into()
        }
    };
}

include!("base_callbacks.rs");
include!("hooks2.rs");

#[cfg(feature = "x86_64")]
include!("syscalls/x86_64.rs");

#[cfg(feature = "i386")]
include!("syscalls/i386.rs");

#[cfg(feature = "arm")]
include!("syscalls/arm.rs");

#[cfg(feature = "aarch64")]
include!("syscalls/aarch64.rs");

// PANDA doesn't have PPC support!
//#[cfg(feature = "ppc")]
//include!("syscalls/ppc.rs");

#[cfg(feature = "mips")]
include!("syscalls/mips.rs");

#[cfg(feature = "mipsel")]
include!("syscalls/mipsel.rs");