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
use foreign_types::{ForeignType, ForeignTypeRef, Opaque};
use libc::{c_int, c_void, pid_t};
use std::any::Any;
use std::ffi::CStr;
use std::marker::PhantomData;
use std::ops::{Deref, DerefMut};
use std::panic::{self, AssertUnwindSafe};
use std::ptr;

use crate::dwfl::{cvt, Callbacks, Error, FrameRef, ModuleRef, ThreadRef};

/// The base type used when interacting with libdwfl.
pub struct Dwfl<'a>(*mut dw_sys::Dwfl, PhantomData<&'a ()>);

impl<'a> Drop for Dwfl<'a> {
    fn drop(&mut self) {
        unsafe {
            dw_sys::dwfl_end(self.as_ptr());
        }
    }
}

impl<'a> ForeignType for Dwfl<'a> {
    type CType = dw_sys::Dwfl;
    type Ref = DwflRef<'a>;

    #[inline]
    unsafe fn from_ptr(ptr: *mut dw_sys::Dwfl) -> Dwfl<'a> {
        Dwfl(ptr, PhantomData)
    }

    #[inline]
    fn as_ptr(&self) -> *mut dw_sys::Dwfl {
        self.0
    }
}

impl<'a> Deref for Dwfl<'a> {
    type Target = DwflRef<'a>;

    #[inline]
    fn deref(&self) -> &DwflRef<'a> {
        unsafe { &*(self.as_ptr() as *mut DwflRef<'a>) }
    }
}

impl<'a> DerefMut for Dwfl<'a> {
    #[inline]
    fn deref_mut(&mut self) -> &mut DwflRef<'a> {
        unsafe { &mut *(self.as_ptr() as *mut DwflRef<'a>) }
    }
}

impl<'a> Dwfl<'a> {
    /// Creates a new `Dwfl` which will use the specified callbacks.
    pub fn begin(callbacks: &'a Callbacks) -> Result<Dwfl<'a>, Error> {
        unsafe {
            let ptr = dw_sys::dwfl_begin(callbacks.as_ptr());
            if ptr.is_null() {
                Err(Error::new())
            } else {
                Ok(Dwfl::from_ptr(ptr))
            }
        }
    }
}

/// A borrowed reference to a `Dwfl`.
pub struct DwflRef<'a>(Opaque, PhantomData<&'a ()>);

impl<'a> ForeignTypeRef for DwflRef<'a> {
    type CType = dw_sys::Dwfl;
}

impl<'a> DwflRef<'a> {
    /// Returns a string describing the version of libdw used.
    pub fn version(&self) -> &str {
        unsafe {
            let p = dw_sys::dwfl_version(self.as_ptr());
            CStr::from_ptr(p).to_str().unwrap()
        }
    }

    /// Starts a "reporting" session used to register new segments and modules.
    ///
    /// Existing segments and modules will be removed.
    pub fn report(&mut self) -> Report<'_, 'a> {
        unsafe {
            dw_sys::dwfl_report_begin(self.as_ptr());
            Report(self)
        }
    }

    /// Starts a "reporting" session used to register new segments and modules.
    ///
    /// Unlike the `report` method, this will not remove existing segments and modules.
    pub fn report_add(&mut self) -> Report<'_, 'a> {
        unsafe {
            dw_sys::dwfl_report_begin_add(self.as_ptr());
            Report(self)
        }
    }

    /// Configures the session to unwind the threads of a remote process via ptrace and the `/proc` pseudo-filesystem.
    ///
    /// Normally, the session will ptrace attach to threads being unwound, but if `assume_ptrace_stopped` is set to
    /// `true`, this will not happen. It's then the responsibility of the caller to ensure that the thread is already
    /// attached and stopped.
    pub fn linux_proc_attach(
        &mut self,
        pid: u32,
        assume_ptrace_stopped: bool,
    ) -> Result<(), Error> {
        unsafe {
            cvt(dw_sys::dwfl_linux_proc_attach(
                self.as_ptr(),
                pid as pid_t,
                assume_ptrace_stopped,
            ))
        }
    }

    /// Iterates through the threads of the attached process.
    ///
    /// The callback will be invoked for each thread in turn.
    pub fn threads<F>(&mut self, callback: F) -> Result<(), Error>
    where
        F: FnMut(&mut ThreadRef) -> Result<(), Error>,
    {
        unsafe {
            let mut state = ThreadsCallbackState {
                callback,
                panic: None,
                error: None,
            };
            let r = dw_sys::dwfl_getthreads(
                self.as_ptr(),
                Some(threads_cb::<F>),
                &mut state as *mut _ as *mut c_void,
            );

            if let Some(payload) = state.panic {
                panic::resume_unwind(payload);
            }
            if let Some(error) = state.error {
                return Err(error);
            }

            cvt(r)
        }
    }

    /// Iterates through the frames of a specific thread of the attached process.
    ///
    /// The callback will be invoked for each stack frame of the thread in turn.
    pub fn thread_frames<F>(&mut self, tid: u32, callback: F) -> Result<(), Error>
    where
        F: FnMut(&mut FrameRef) -> Result<(), Error>,
    {
        unsafe {
            let mut state = FramesCallbackState {
                callback,
                panic: None,
                error: None,
            };
            let r = dw_sys::dwfl_getthread_frames(
                self.as_ptr(),
                tid as pid_t,
                Some(frames_cb::<F>),
                &mut state as *mut _ as *mut c_void,
            );

            if let Some(payload) = state.panic {
                panic::resume_unwind(payload);
            }
            if let Some(e) = state.error {
                return Err(e);
            }

            cvt(r)
        }
    }

    /// Looks up the module containing the address.
    pub fn addr_module(&self, address: u64) -> Result<&ModuleRef, Error> {
        unsafe {
            let ptr = dw_sys::dwfl_addrmodule(self.as_ptr(), address);
            if ptr.is_null() {
                Err(Error::new())
            } else {
                Ok(ModuleRef::from_ptr(ptr))
            }
        }
    }
}

/// A type used to register segments and modules with a DWFL session.
pub struct Report<'a, 'b>(&'a mut DwflRef<'b>);

impl<'a, 'b> Drop for Report<'a, 'b> {
    fn drop(&mut self) {
        unsafe {
            dw_sys::dwfl_report_end(self.0.as_ptr(), None, ptr::null_mut());
        }
    }
}

impl<'a, 'b> Report<'a, 'b> {
    /// Uses the `/proc` pseudo-filesystem to register the information for a specific running process.
    ///
    /// The `FindElf::LINUX_PROC` callback should be used with this method.
    pub fn linux_proc(&mut self, pid: u32) -> Result<(), Error> {
        unsafe {
            cvt(dw_sys::dwfl_linux_proc_report(
                self.0.as_ptr(),
                pid as pid_t,
            ))
        }
    }
}

struct ThreadsCallbackState<F> {
    callback: F,
    panic: Option<Box<Any + Send>>,
    error: Option<Error>,
}

unsafe extern "C" fn threads_cb<F>(thread: *mut dw_sys::Dwfl_Thread, arg: *mut c_void) -> c_int
where
    F: FnMut(&mut ThreadRef) -> Result<(), Error>,
{
    let state = &mut *(arg as *mut ThreadsCallbackState<F>);
    let thread = ThreadRef::from_ptr_mut(thread);

    match panic::catch_unwind(AssertUnwindSafe(|| (state.callback)(thread))) {
        Ok(Ok(())) => dw_sys::DWARF_CB_OK,
        Ok(Err(e)) => {
            state.error = Some(e);
            dw_sys::DWARF_CB_ABORT
        }
        Err(e) => {
            state.panic = Some(e);
            dw_sys::DWARF_CB_ABORT
        }
    }
}

struct FramesCallbackState<F> {
    callback: F,
    panic: Option<Box<Any + Send>>,
    error: Option<Error>,
}

unsafe extern "C" fn frames_cb<F>(frame: *mut dw_sys::Dwfl_Frame, arg: *mut c_void) -> c_int
where
    F: FnMut(&mut FrameRef) -> Result<(), Error>,
{
    let state = &mut *(arg as *mut FramesCallbackState<F>);
    let frame = FrameRef::from_ptr_mut(frame);

    match panic::catch_unwind(AssertUnwindSafe(|| (state.callback)(frame))) {
        Ok(Ok(())) => dw_sys::DWARF_CB_OK,
        Ok(Err(e)) => {
            state.error = Some(e);
            dw_sys::DWARF_CB_ABORT
        }
        Err(e) => {
            state.panic = Some(e);
            dw_sys::DWARF_CB_ABORT
        }
    }
}