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
use core::marker::PhantomData;

use crate::endian::Endian;
use crate::macho;
use crate::pod::Bytes;
use crate::read::macho::{MachHeader, SymbolTable};
use crate::read::{ReadError, Result, StringTable};

/// An iterator over the load commands of a `MachHeader`.
#[derive(Debug, Default, Clone, Copy)]
pub struct MachOLoadCommandIterator<'data, E: Endian> {
    endian: E,
    data: Bytes<'data>,
    ncmds: u32,
}

impl<'data, E: Endian> MachOLoadCommandIterator<'data, E> {
    pub(super) fn new(endian: E, data: Bytes<'data>, ncmds: u32) -> Self {
        MachOLoadCommandIterator {
            endian,
            data,
            ncmds,
        }
    }

    /// Return the next load command.
    pub fn next(&mut self) -> Result<Option<MachOLoadCommand<'data, E>>> {
        if self.ncmds == 0 {
            return Ok(None);
        }
        let header = self
            .data
            .read_at::<macho::LoadCommand<E>>(0)
            .read_error("Invalid Mach-O load command header")?;
        let cmd = header.cmd.get(self.endian);
        let cmdsize = header.cmdsize.get(self.endian) as usize;
        let data = self
            .data
            .read_bytes(cmdsize)
            .read_error("Invalid Mach-O load command size")?;
        self.ncmds -= 1;
        Ok(Some(MachOLoadCommand {
            cmd,
            data,
            marker: Default::default(),
        }))
    }
}

/// A parsed `LoadCommand`.
#[derive(Debug, Clone, Copy)]
pub struct MachOLoadCommand<'data, E: Endian> {
    cmd: u32,
    // Includes the header.
    data: Bytes<'data>,
    marker: PhantomData<E>,
}

impl<'data, E: Endian> MachOLoadCommand<'data, E> {
    /// Try to parse this command as a `SegmentCommand32`.
    pub fn segment_32(self) -> Result<Option<(&'data macho::SegmentCommand32<E>, Bytes<'data>)>> {
        if self.cmd == macho::LC_SEGMENT {
            let mut data = self.data;
            let command = data
                .read()
                .read_error("Invalid Mach-O LC_SEGMENT command size")?;
            Ok(Some((command, data)))
        } else {
            Ok(None)
        }
    }

    /// Try to parse this command as a `SymtabCommand`.
    pub fn symtab(self) -> Result<Option<&'data macho::SymtabCommand<E>>> {
        if self.cmd == macho::LC_SYMTAB {
            Some(
                self.data
                    .clone()
                    .read()
                    .read_error("Invalid Mach-O LC_SYMTAB command size"),
            )
            .transpose()
        } else {
            Ok(None)
        }
    }

    /// Try to parse this command as a `DysymtabCommand`.
    pub fn dysymtab(self) -> Result<Option<&'data macho::DysymtabCommand<E>>> {
        if self.cmd == macho::LC_DYSYMTAB {
            Some(
                self.data
                    .clone()
                    .read()
                    .read_error("Invalid Mach-O LC_DYSYMTAB command size"),
            )
            .transpose()
        } else {
            Ok(None)
        }
    }

    /// Try to parse this command as a `DylibCommand`.
    pub fn dylib(self) -> Result<Option<&'data macho::Dylib<E>>> {
        if self.cmd == macho::LC_LOAD_DYLIB
            || self.cmd == macho::LC_LOAD_WEAK_DYLIB
            || self.cmd == macho::LC_REEXPORT_DYLIB
            || self.cmd == macho::LC_LAZY_LOAD_DYLIB
            || self.cmd == macho::LC_LOAD_UPWARD_DYLIB
        {
            let command = self
                .data
                .clone()
                .read::<macho::DylibCommand<_>>()
                .read_error("Invalid Mach-O LC_*_DYLIB command size")?;
            Ok(Some(&command.dylib))
        } else {
            Ok(None)
        }
    }

    /// Try to parse this command as a `UuidCommand`.
    pub fn uuid(self) -> Result<Option<&'data macho::UuidCommand<E>>> {
        if self.cmd == macho::LC_UUID {
            Some(
                self.data
                    .clone()
                    .read()
                    .read_error("Invalid Mach-O LC_UUID command size"),
            )
            .transpose()
        } else {
            Ok(None)
        }
    }

    /// Try to parse this command as a `SegmentCommand64`.
    pub fn segment_64(self) -> Result<Option<(&'data macho::SegmentCommand64<E>, Bytes<'data>)>> {
        if self.cmd == macho::LC_SEGMENT_64 {
            let mut data = self.data;
            let command = data
                .read()
                .read_error("Invalid Mach-O LC_SEGMENT_64 command size")?;
            Ok(Some((command, data)))
        } else {
            Ok(None)
        }
    }

    /// Try to parse this command as a `DyldInfoCommand`.
    pub fn dyld_info(self) -> Result<Option<&'data macho::DyldInfoCommand<E>>> {
        if self.cmd == macho::LC_DYLD_INFO || self.cmd == macho::LC_DYLD_INFO_ONLY {
            Some(
                self.data
                    .clone()
                    .read()
                    .read_error("Invalid Mach-O LC_DYLD_INFO command size"),
            )
            .transpose()
        } else {
            Ok(None)
        }
    }

    /// Try to parse this command as an `EntryPointCommand`.
    pub fn entry_point(self) -> Result<Option<&'data macho::EntryPointCommand<E>>> {
        if self.cmd == macho::LC_MAIN {
            Some(
                self.data
                    .clone()
                    .read()
                    .read_error("Invalid Mach-O LC_MAIN command size"),
            )
            .transpose()
        } else {
            Ok(None)
        }
    }

    pub fn string(&self, endian: E, s: macho::LcStr<E>) -> Result<&'data [u8]> {
        self.data
            .read_string_at(s.offset.get(endian) as usize)
            .read_error("Invalid load command string offset")
    }
}

impl<E: Endian> macho::SymtabCommand<E> {
    /// Return the symbol table that this command references.
    pub fn symbols<'data, Mach: MachHeader<Endian = E>>(
        &self,
        endian: E,
        data: Bytes<'data>,
    ) -> Result<SymbolTable<'data, Mach>> {
        let symbols = data
            .read_slice_at(
                self.symoff.get(endian) as usize,
                self.nsyms.get(endian) as usize,
            )
            .read_error("Invalid Mach-O symbol table offset or size")?;
        let strings = data
            .read_bytes_at(
                self.stroff.get(endian) as usize,
                self.strsize.get(endian) as usize,
            )
            .read_error("Invalid Mach-O string table offset or size")?;
        let strings = StringTable::new(strings);
        Ok(SymbolTable::new(symbols, strings))
    }
}