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
use crate::internal_prelude::*;

#[derive(Debug, Eq, Ord, PartialEq, PartialOrd, Hash)]
pub struct Handle(syz_Handle);

impl Handle {
    pub fn new(h: syz_Handle) -> Handle {
        Handle(h)
    }

    pub fn handle(&self) -> &Handle {
        &self
    }

    pub fn into_handle(self) -> Handle {
        self
    }

    /// Get the object's type if possible.  THis function will fail if Synthizer
    /// is not initialized.
    pub fn get_type(&self) -> Result<ObjectType> {
        let mut out = 0;
        check_error(unsafe {
            syz_handleGetObjectType(&mut out as *mut i32, self.to_syz_handle())
        })?;
        Ok(unsafe { std::mem::transmute(out) })
    }

    /// Try to cast this object to another object type.  Will return
    /// `Ok(None)` if this is because of a type mismatch, otherwise `Err`.
    /// Clones `self` on success in order to prevent throwing the object
    /// away on error.
    pub fn cast_to<T: CastTarget>(&self) -> Result<Option<T>> {
        T::cast_from(self.handle_ref())
    }

    /// Get this handle's userdata.
    pub fn get_userdata(&self) -> Result<Option<Arc<dyn Any + Send + Sync>>> {
        with_witness(|| {
            let b = self.get_userdata_box()?;
            Ok(unsafe { b.as_mut().expect("Is always non-NULL").get_userdata() }.clone())
        })
    }

    /// Set the userdata for this handle.
    pub fn set_userdata(&self, userdata: Option<impl Any + Send + Sync>) -> Result<()> {
        with_witness(move || {
            let b = self.get_userdata_box()?;
            unsafe {
                b.as_mut()
                    .expect("Pointer is always valid")
                    .set_userdata(userdata)
            };
            Ok(())
        })
    }

    /// Needs to be called inside of [with_witness].
    fn get_userdata_box(&self) -> Result<*mut UserdataBox> {
        let mut ud: *mut std::ffi::c_void = std::ptr::null_mut();
        check_error(unsafe {
            syz_handleGetUserdata(&mut ud as *mut *mut std::ffi::c_void, self.0)
        })?;
        let ud_box = ud as *mut UserdataBox;
        Ok(ud_box)
    }

    pub fn config_delete_behavior(&self, config: &DeleteBehaviorConfig) -> Result<()> {
        check_error(unsafe {
            syz_configDeleteBehavior(self.0, &config.cfg as *const syz_DeleteBehaviorConfig)
        })
    }

    #[allow(clippy::wrong_self_convention)]
    pub(crate) fn from_handle_internal(h: Handle) -> Handle {
        h
    }
}

impl Drop for Handle {
    fn drop(&mut self) {
        check_error(unsafe { syz_handleDecRef(self.0) })
            .expect("Dropping handles should not error");
    }
}

impl Clone for Handle {
    fn clone(&self) -> Handle {
        check_error(unsafe { syz_handleIncRef(self.0) })
            .expect("Incrementing reference counts should never error");
        Handle(self.0)
    }
}

// A weird workaround to keep the `ToHandle` trait private.  I actually don't
// understand why this works, but it does.
mod priv_traits {
    use super::*;

    /// Internal helper trait to convert things to handles.  We don't use `From`
    /// because that's public: people should be using the bindings, not
    /// converting handles directly.
    pub trait ToSyzHandle {
        fn to_syz_handle(&self) -> syz_Handle;
    }

    /// Trait to get a reference to the handle.
    pub trait HandleRef {
        fn handle_ref(&self) -> &Handle;
    }
}

pub(crate) use priv_traits::*;

impl ToSyzHandle for Handle {
    fn to_syz_handle(&self) -> syz_Handle {
        self.0
    }
}

impl HandleRef for Handle {
    fn handle_ref(&self) -> &Handle {
        &self
    }
}

macro_rules! handle_traits {
    ($t: ty) => {
        impl ToSyzHandle for $t {
            fn to_syz_handle(&self) -> syz_Handle {
                self.0.to_syz_handle()
            }
        }

        impl HandleRef for $t {
            fn handle_ref(&self) -> &Handle {
                &self.0
            }
        }
    };
}