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
//! A Rust API for working with OSX's Mach-O object files.

#![deny(missing_docs)]

extern crate mach_o_sys;

use mach_o_sys::{loader, getsect};
use std::ffi::CStr;
use std::mem;

/// An error that occurred while parsing the mach-o file contents.
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub enum Error {
    /// The input is not long enough to contain valid contents.
    InputNotLongEnough,
    /// Found an unknown magic header value.
    UnknownMagicHeaderValue,
}

#[derive(Copy, Clone, Debug)]
enum RawHeader {
    MachHeader32(*const loader::mach_header),
    MachHeader64(*const loader::mach_header_64),
}

/// A mach-o file header.
#[derive(Copy, Clone, Debug)]
pub struct Header<'a> {
    raw_header: RawHeader,
    input: &'a [u8],
}

impl<'a> Header<'a> {
    /// Parse the mach-o file header from the given input slice.
    pub fn new(input: &'a [u8]) -> Result<Header<'a>, Error> {
        if input.len() < mem::size_of::<loader::mach_header>() {
            return Err(Error::InputNotLongEnough);
        }

        let mut magic: [u8; 4] = [0, 0, 0, 0];
        magic.copy_from_slice(&input[..4]);
        let magic = unsafe { mem::transmute(magic) };

        match magic {
            // 32 bit.
            loader::MH_MAGIC | loader::MH_CIGAM => {
                Ok(Header {
                    raw_header: RawHeader::MachHeader32(unsafe { mem::transmute(input.as_ptr()) }),
                    input: input,
                })
            }

            // 64 bit.
            loader::MH_MAGIC_64 |
            loader::MH_CIGAM_64 => {
                if input.len() < mem::size_of::<loader::mach_header_64>() {
                    return Err(Error::InputNotLongEnough);
                }

                Ok(Header {
                    raw_header: RawHeader::MachHeader64(unsafe { mem::transmute(input.as_ptr()) }),
                    input: input,
                })
            }

            // Unknown magic header value.
            _ => Err(Error::UnknownMagicHeaderValue),
        }
    }

    /// Get the magic value for this header.
    pub fn magic(&self) -> u32 {
        unsafe {
            match self.raw_header {
                RawHeader::MachHeader32(h) => h.as_ref().unwrap().magic,
                RawHeader::MachHeader64(h) => h.as_ref().unwrap().magic,
            }
        }
    }

    /// Returns true if the object file is encoded with the same byteorder that
    /// the current platform uses natively.
    pub fn is_native_byteorder(&self) -> bool {
        match self.magic() {
            loader::MH_MAGIC |
            loader::MH_MAGIC_64 => true,
            _ => false,
        }
    }

    /// Returns true if the object file is 64-bit, false if it is 32-bit.
    pub fn is_64_bit(&self) -> bool {
        match self.magic() {
            loader::MH_MAGIC_64 |
            loader::MH_CIGAM_64 => true,
            _ => false,
        }
    }

    /// Get the data for a given section, if it exists.
    pub fn get_section(&self, segment_name: &CStr, section_name: &CStr) -> Option<Section<'a>> {
        unsafe {
            match self.raw_header {
                RawHeader::MachHeader32(h) => {
                    let h: *mut getsect::mach_header = mem::transmute(h);
                    let section = getsect::getsectbynamefromheader(h,
                                                                   segment_name.as_ptr(),
                                                                   section_name.as_ptr());

                    section.as_ref().map(|section| {
                        Section {
                            raw_section: RawSection::Section32(section),
                            input: self.input,
                        }
                    })
                }
                RawHeader::MachHeader64(h) => {
                    let h: *mut getsect::mach_header_64 = mem::transmute(h);
                    let section = getsect::getsectbynamefromheader_64(h,
                                                                      segment_name.as_ptr(),
                                                                      section_name.as_ptr());

                    section.as_ref().map(|section| {
                        Section {
                            raw_section: RawSection::Section64(section),
                            input: self.input,
                        }
                    })
                }
            }
        }
    }
}

#[derive(Copy, Clone, Debug)]
enum RawSection {
    Section32(*const getsect::section),
    Section64(*const getsect::section_64),
}

/// A section in the mach-o file.
#[derive(Copy, Clone, Debug)]
pub struct Section<'a> {
    raw_section: RawSection,
    input: &'a [u8],
}

impl<'a> Section<'a> {
    /// Get this section's name.
    pub fn name(&self) -> &CStr {
        unsafe {
            match self.raw_section {
                RawSection::Section32(s) => {
                    CStr::from_ptr(mem::transmute(&s.as_ref().unwrap().sectname))
                }
                RawSection::Section64(s) => {
                    CStr::from_ptr(mem::transmute(&s.as_ref().unwrap().sectname))
                }
            }
        }
    }

    /// Get this section's segment's name.
    pub fn segment_name(&self) -> &CStr {
        unsafe {
            match self.raw_section {
                RawSection::Section32(s) => {
                    CStr::from_ptr(mem::transmute(&s.as_ref().unwrap().segname))
                }
                RawSection::Section64(s) => {
                    CStr::from_ptr(mem::transmute(&s.as_ref().unwrap().segname))
                }
            }
        }
    }

    /// Get this section's vm address.
    pub fn addr(&self) -> u64 {
        unsafe {
            match self.raw_section {
                RawSection::Section32(s) => s.as_ref().unwrap().addr as u64,
                RawSection::Section64(s) => s.as_ref().unwrap().addr,
            }
        }
    }

    /// Get this section's data.
    pub fn data(&self) -> &'a [u8] {
        unsafe {
            match self.raw_section {
                RawSection::Section32(s) => {
                    let s = s.as_ref().unwrap();
                    let start = s.offset as usize;
                    let end = start + s.size as usize;
                    &self.input[start..end]
                }
                RawSection::Section64(s) => {
                    let s = s.as_ref().unwrap();
                    let start = s.offset as usize;
                    let end = start + s.size as usize;
                    &self.input[start..end]
                }
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use mach_o_sys::loader;

    const LITTLE_ENDIAN_HEADER_64: [u8; 32] = [0xcf, 0xfa, 0xed, 0xfe, 0x07, 0x00, 0x00, 0x01,
                                               0x03, 0x00, 0x00, 0x80, 0x02, 0x00, 0x00, 0x00,
                                               0x12, 0x00, 0x00, 0x00, 0xd8, 0x08, 0x00, 0x00,
                                               0x85, 0x80, 0xa1, 0x00, 0x00, 0x00, 0x00, 0x00];

    #[test]
    fn test_read_header() {
        let buf = &LITTLE_ENDIAN_HEADER_64;
        let header = Header::new(buf).expect("Should parse the header OK");
        assert_eq!(header.magic(), loader::MH_MAGIC_64);
    }
}