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
use std::fmt;
use std::io::Cursor;

use failure::{Backtrace, Context, Fail, ResultExt};
use goblin::{self, elf, mach, Hint};

use symbolic_common::byteview::{ByteView, ByteViewHandle};
use symbolic_common::types::{Arch, DebugId, DebugKind, Endianness, ObjectClass, ObjectKind};

use breakpad::BreakpadSym;
use dwarf::DwarfData;
use elf::{get_elf_id, get_elf_vmaddr};
use mach::{get_mach_id, get_mach_vmaddr};

/// Contains type specific data of `Object`s.
pub(crate) enum ObjectTarget<'bytes> {
    Breakpad(&'bytes BreakpadSym),
    Elf(&'bytes elf::Elf<'bytes>),
    MachOSingle(&'bytes mach::MachO<'bytes>),
    MachOFat(mach::fat::FatArch, mach::MachO<'bytes>),
}

/// The kind of an `ObjectError`.
#[derive(Debug, Fail, Copy, Clone, Eq, PartialEq)]
pub enum ObjectErrorKind {
    /// The `Object` file format is not supported.
    #[fail(display = "unsupported object file")]
    UnsupportedObject,

    /// The `Object` file contains invalid data.
    #[fail(display = "failed to read object file")]
    BadObject,

    /// Reading symbol tables is not supported for this `Object` file format.
    #[fail(display = "symbol table not supported for this object format")]
    UnsupportedSymbolTable,
}

/// An error returned when working with `Object` and `FatObject`.
///
/// This error contains a context with a stack trace and error causes.
#[derive(Debug)]
pub struct ObjectError {
    inner: Context<ObjectErrorKind>,
}

impl Fail for ObjectError {
    fn cause(&self) -> Option<&Fail> {
        self.inner.cause()
    }

    fn backtrace(&self) -> Option<&Backtrace> {
        self.inner.backtrace()
    }
}

impl fmt::Display for ObjectError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        fmt::Display::fmt(&self.inner, f)
    }
}

impl ObjectError {
    pub fn kind(&self) -> ObjectErrorKind {
        *self.inner.get_context()
    }
}

impl From<ObjectErrorKind> for ObjectError {
    fn from(kind: ObjectErrorKind) -> ObjectError {
        ObjectError {
            inner: Context::new(kind),
        }
    }
}

impl From<Context<ObjectErrorKind>> for ObjectError {
    fn from(inner: Context<ObjectErrorKind>) -> ObjectError {
        ObjectError { inner }
    }
}

/// Represents a single object in a fat object.
pub struct Object<'bytes> {
    fat_bytes: &'bytes [u8],
    pub(crate) target: ObjectTarget<'bytes>,
}

impl<'bytes> Object<'bytes> {
    /// Returns the identifier of the object.
    pub fn id(&self) -> Option<DebugId> {
        match self.target {
            ObjectTarget::Breakpad(ref breakpad) => Some(breakpad.id()),
            ObjectTarget::Elf(ref elf) => get_elf_id(elf, self.fat_bytes),
            ObjectTarget::MachOSingle(macho) => get_mach_id(macho),
            ObjectTarget::MachOFat(_, ref macho) => get_mach_id(macho),
        }
    }

    /// Returns the kind of the object.
    pub fn kind(&self) -> ObjectKind {
        match self.target {
            ObjectTarget::Breakpad(..) => ObjectKind::Breakpad,
            ObjectTarget::Elf(..) => ObjectKind::Elf,
            ObjectTarget::MachOSingle(..) => ObjectKind::MachO,
            ObjectTarget::MachOFat(..) => ObjectKind::MachO,
        }
    }

    /// Returns the architecture of the object.
    pub fn arch(&self) -> Result<Arch, ObjectError> {
        Ok(match self.target {
            ObjectTarget::Breakpad(ref breakpad) => breakpad.arch(),
            ObjectTarget::Elf(ref elf) => {
                Arch::from_elf(elf.header.e_machine).context(ObjectErrorKind::UnsupportedObject)?
            }
            ObjectTarget::MachOSingle(mach) => {
                Arch::from_mach(mach.header.cputype(), mach.header.cpusubtype())
                    .context(ObjectErrorKind::UnsupportedObject)?
            }
            ObjectTarget::MachOFat(_, ref mach) => {
                Arch::from_mach(mach.header.cputype(), mach.header.cpusubtype())
                    .context(ObjectErrorKind::UnsupportedObject)?
            }
        })
    }

    /// Return the vmaddr of the code portion of the image.
    pub fn vmaddr(&self) -> u64 {
        match self.target {
            // Breakpad accounts for the vmaddr when dumping symbols
            ObjectTarget::Breakpad(..) => 0,
            ObjectTarget::Elf(elf) => get_elf_vmaddr(elf),
            ObjectTarget::MachOSingle(macho) => get_mach_vmaddr(macho),
            ObjectTarget::MachOFat(_, ref macho) => get_mach_vmaddr(macho),
        }
    }

    /// True if little endian, false if not.
    pub fn endianness(&self) -> Endianness {
        let little = match self.target {
            ObjectTarget::Breakpad(..) => return Endianness::default(),
            ObjectTarget::Elf(ref elf) => elf.little_endian,
            ObjectTarget::MachOSingle(macho) => macho.little_endian,
            ObjectTarget::MachOFat(_, ref macho) => macho.little_endian,
        };

        if little {
            Endianness::Little
        } else {
            Endianness::Big
        }
    }

    /// Returns the content of the object as bytes.
    pub fn as_bytes(&self) -> &'bytes [u8] {
        match self.target {
            ObjectTarget::Breakpad(..) => self.fat_bytes,
            ObjectTarget::Elf(..) => self.fat_bytes,
            ObjectTarget::MachOSingle(_) => self.fat_bytes,
            ObjectTarget::MachOFat(ref arch, _) => {
                let bytes = self.fat_bytes;
                &bytes[arch.offset as usize..(arch.offset + arch.size) as usize]
            }
        }
    }

    /// Returns the desiganted use of the object file and hints at its contents.
    pub fn class(&self) -> ObjectClass {
        match self.target {
            ObjectTarget::Breakpad(..) => ObjectClass::Debug,
            ObjectTarget::Elf(ref elf) => {
                ObjectClass::from_elf_full(elf.header.e_type, elf.interpreter.is_some())
            }
            ObjectTarget::MachOSingle(macho) => ObjectClass::from_mach(macho.header.filetype),
            ObjectTarget::MachOFat(_, ref macho) => ObjectClass::from_mach(macho.header.filetype),
        }
    }

    /// Returns the type of debug data contained in this object file.
    pub fn debug_kind(&self) -> Option<DebugKind> {
        match self.target {
            ObjectTarget::Breakpad(..) => Some(DebugKind::Breakpad),
            ObjectTarget::Elf(..) | ObjectTarget::MachOSingle(..) | ObjectTarget::MachOFat(..)
                if self.has_dwarf_data() =>
            {
                Some(DebugKind::Dwarf)
            }
            _ => None,
        }
    }
}

impl<'bytes> fmt::Debug for Object<'bytes> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.debug_struct("Object")
            .field("id", &self.id())
            .field("arch", &self.arch())
            .field("vmaddr", &self.vmaddr())
            .field("endianness", &self.endianness())
            .field("kind", &self.kind())
            .finish()
    }
}

/// Iterator over `Object`s in a `FatObject`.
pub struct Objects<'fat> {
    fat: &'fat FatObject<'fat>,
    index: usize,
}

impl<'fat> Objects<'fat> {
    fn new(fat: &'fat FatObject<'fat>) -> Objects<'fat> {
        Objects { fat: fat, index: 0 }
    }
}

impl<'fat> Iterator for Objects<'fat> {
    type Item = Result<Object<'fat>, ObjectError>;

    fn next(&mut self) -> Option<Self::Item> {
        let result = match self.fat.get_object(self.index) {
            Ok(Some(object)) => Some(Ok(object)),
            Ok(None) => None,
            Err(err) => Some(Err(err)),
        };

        if result.is_some() {
            self.index += 1;
        }

        result
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        let remaining = self.fat.object_count() - self.index;
        (remaining, Some(remaining))
    }

    fn count(mut self) -> usize {
        let (remaining, _) = self.size_hint();
        self.index += remaining;
        remaining
    }
}

/// Internal data used to access platform-specific data of a `FatObject`.
pub(crate) enum FatObjectKind<'bytes> {
    Breakpad(BreakpadSym),
    Elf(elf::Elf<'bytes>),
    MachO(mach::Mach<'bytes>),
}

/// Represents a potentially fat object containing one or more objects.
pub struct FatObject<'bytes> {
    handle: ByteViewHandle<'bytes, FatObjectKind<'bytes>>,
}

impl<'bytes> FatObject<'bytes> {
    /// Returns the type of the FatObject.
    pub fn peek<B>(bytes: B) -> Result<Option<ObjectKind>, ObjectError>
    where
        B: AsRef<[u8]>,
    {
        let bytes = bytes.as_ref();
        let mut cur = Cursor::new(bytes);

        match goblin::peek(&mut cur).context(ObjectErrorKind::BadObject)? {
            Hint::Elf(_) => return Ok(Some(ObjectKind::Elf)),
            Hint::Mach(_) => return Ok(Some(ObjectKind::MachO)),
            Hint::MachFat(_) => return Ok(Some(ObjectKind::MachO)),
            _ => (),
        };

        if bytes.starts_with(b"MODULE ") {
            return Ok(Some(ObjectKind::Breakpad));
        }

        Ok(None)
    }

    /// Provides a view to an object file from a `ByteView`.
    pub fn parse(byteview: ByteView<'bytes>) -> Result<FatObject<'bytes>, ObjectError> {
        let handle = ByteViewHandle::from_byteview(byteview, |bytes| -> Result<_, ObjectError> {
            Ok(match FatObject::peek(bytes)? {
                Some(ObjectKind::Elf) => {
                    let inner = elf::Elf::parse(bytes).context(ObjectErrorKind::BadObject)?;
                    FatObjectKind::Elf(inner)
                }
                Some(ObjectKind::MachO) => {
                    let inner = mach::Mach::parse(bytes).context(ObjectErrorKind::BadObject)?;
                    FatObjectKind::MachO(inner)
                }
                Some(ObjectKind::Breakpad) => {
                    let inner = BreakpadSym::parse(bytes).context(ObjectErrorKind::BadObject)?;
                    FatObjectKind::Breakpad(inner)
                }
                None => return Err(ObjectErrorKind::UnsupportedObject.into()),
            })
        })?;

        Ok(FatObject { handle: handle })
    }

    /// Returns the kind of this `FatObject`.
    pub fn kind(&self) -> ObjectKind {
        match *self.handle {
            FatObjectKind::Breakpad(_) => ObjectKind::Breakpad,
            FatObjectKind::Elf(..) => ObjectKind::Elf,
            FatObjectKind::MachO(..) => ObjectKind::MachO,
        }
    }

    /// Returns the contents as bytes.
    pub fn as_bytes(&self) -> &[u8] {
        ByteViewHandle::get_bytes(&self.handle)
    }

    /// Returns the number of contained objects.
    pub fn object_count(&self) -> usize {
        match *self.handle {
            FatObjectKind::Breakpad(_) => 1,
            FatObjectKind::Elf(..) => 1,
            FatObjectKind::MachO(ref mach) => match *mach {
                mach::Mach::Fat(ref fat) => fat.narches,
                mach::Mach::Binary(..) => 1,
            },
        }
    }

    /// Returns the n-th object.
    pub fn get_object(&'bytes self, index: usize) -> Result<Option<Object<'bytes>>, ObjectError> {
        if index >= self.object_count() {
            return Ok(None);
        }

        let target = match *self.handle {
            FatObjectKind::Breakpad(ref breakpad) => ObjectTarget::Breakpad(breakpad),
            FatObjectKind::Elf(ref elf) => ObjectTarget::Elf(elf),
            FatObjectKind::MachO(ref mach) => match *mach {
                mach::Mach::Binary(ref bin) => ObjectTarget::MachOSingle(bin),
                mach::Mach::Fat(ref fat) => {
                    let mach = fat.get(index).context(ObjectErrorKind::BadObject)?;
                    let arch = fat.iter_arches()
                        .nth(index)
                        .unwrap()
                        .context(ObjectErrorKind::BadObject)?;

                    ObjectTarget::MachOFat(arch, mach)
                }
            },
        };

        Ok(Some(Object {
            fat_bytes: self.as_bytes(),
            target: target,
        }))
    }

    /// Returns a iterator over object variants in this fat object.
    pub fn objects(&'bytes self) -> Objects<'bytes> {
        Objects::new(self)
    }
}

impl<'bytes> fmt::Debug for FatObject<'bytes> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.debug_struct("Object")
            .field("kind", &self.kind())
            .field("object_count", &self.object_count())
            .finish()
    }
}