Debian Codegraph @

third_party/rust/goblin/src/mach/imports.rs

raw
1 //! Dynamically linked symbolic imports
2
3 // table of tuples:
4 // <seg-index, seg-offset, type, symbol-library-ordinal, symbol-name, addend>
5 // symbol flags are undocumented
6
7 use alloc::vec::Vec;
8 use core::fmt::{self, Debug};
9 use core::ops::Range;
10 use scroll::{Pread, Sleb128, Uleb128};
11
12 use crate::container;
13 use crate::error;
14 use crate::mach::bind_opcodes;
15 use crate::mach::load_command;
16 use crate::mach::segment;
17
18 #[derive(Debug)]
19 /// Import binding information generated by running the Finite State Automaton programmed via `bind_opcodes`
20 struct BindInformation<'a> {
21 seg_index: u8,
22 seg_offset: u64,
23 bind_type: u8,
24 symbol_library_ordinal: u8,
25 symbol_name: &'a str,
26 symbol_flags: u8,
27 addend: i64,
28 special_dylib: u8, // seeing self = 0 assuming this means the symbol is imported from itself, because its... libSystem.B.dylib?
29 is_lazy: bool,
30 }
31
32 impl<'a> BindInformation<'a> {
33 pub fn new(is_lazy: bool) -> Self {
34 let mut bind_info = BindInformation::default();
35 if is_lazy {
36 bind_info.is_lazy = true;
37 bind_info.bind_type = bind_opcodes::BIND_TYPE_POINTER;
38 }
39 bind_info
40 }
41 pub fn is_weak(&self) -> bool {
42 self.symbol_flags & bind_opcodes::BIND_SYMBOL_FLAGS_WEAK_IMPORT != 0
43 }
44 }
45
46 impl<'a> Default for BindInformation<'a> {
47 fn default() -> Self {
48 BindInformation {
49 seg_index: 0,
50 seg_offset: 0x0,
51 bind_type: 0x0,
52 special_dylib: 1,
53 symbol_library_ordinal: 0,
54 symbol_name: "",
55 symbol_flags: 0,
56 addend: 0,
57 is_lazy: false,
58 }
59 }
60 }
61
62 #[derive(Debug)]
63 /// An dynamically linked symbolic import
64 pub struct Import<'a> {
65 /// The symbol name dyld uses to resolve this import
66 pub name: &'a str,
67 /// The library this symbol belongs to (thanks to two-level namespaces)
68 pub dylib: &'a str,
69 /// Whether the symbol is lazily resolved or not
70 pub is_lazy: bool,
71 /// The offset in the binary this import is found
72 pub offset: u64,
73 /// The size of this import
74 pub size: usize,
75 /// The virtual memory address at which this import is found
76 pub address: u64,
77 /// The addend of this import
78 pub addend: i64,
79 /// Whether this import is weak
80 pub is_weak: bool,
81 /// The offset in the stream of bind opcodes that caused this import
82 pub start_of_sequence_offset: u64,
83 }
84
85 impl<'a> Import<'a> {
86 /// Create a new import from the import binding information in `bi`
87 fn new(
88 bi: &BindInformation<'a>,
89 libs: &[&'a str],
90 segments: &[segment::Segment],
91 start_of_sequence_offset: usize,
92 ) -> Import<'a> {
93 let (offset, address) = {
94 let segment = &segments[bi.seg_index as usize];
95 (
96 segment.fileoff + bi.seg_offset,
97 segment.vmaddr + bi.seg_offset,
98 )
99 };
100 let size = if bi.is_lazy { 8 } else { 0 };
101 Import {
102 name: bi.symbol_name,
103 dylib: libs[bi.symbol_library_ordinal as usize],
104 is_lazy: bi.is_lazy,
105 offset,
106 size,
107 address,
108 addend: bi.addend,
109 is_weak: bi.is_weak(),
110 start_of_sequence_offset: start_of_sequence_offset as u64,
111 }
112 }
113 }
114
115 /// An interpreter for mach BIND opcodes.
116 /// Runs on prebound (non lazy) symbols (usually dylib extern consts and extern variables),
117 /// and lazy symbols (usually dylib functions)
118 pub struct BindInterpreter<'a> {
119 data: &'a [u8],
120 location: Range<usize>,
121 lazy_location: Range<usize>,
122 }
123
124 impl<'a> Debug for BindInterpreter<'a> {
125 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
126 fmt.debug_struct("BindInterpreter")
127 .field("data", &"<... redacted ...>")
128 .field(
129 "location",
130 &format_args!("{:#x}..{:#x}", self.location.start, self.location.end),
131 )
132 .field(
133 "lazy_location",
134 &format_args!(
135 "{:#x}..{:#x}",
136 self.lazy_location.start, self.lazy_location.end
137 ),
138 )
139 .finish()
140 }
141 }
142
143 impl<'a> BindInterpreter<'a> {
144 /// Construct a new import binding interpreter from `bytes` and the load `command`
145 pub fn new(bytes: &'a [u8], command: &load_command::DyldInfoCommand) -> Self {
146 let get_pos = |off: u32, size: u32| -> Range<usize> {
147 let start = off as usize;
148 start..start.saturating_add(size as usize)
149 };
150 let location = get_pos(command.bind_off, command.bind_size);
151 let lazy_location = get_pos(command.lazy_bind_off, command.lazy_bind_size);
152 BindInterpreter {
153 data: bytes,
154 location,
155 lazy_location,
156 }
157 }
158 /// Return the imports in this binary
159 pub fn imports(
160 &self,
161 libs: &[&'a str],
162 segments: &[segment::Segment],
163 ctx: container::Ctx,
164 ) -> error::Result<Vec<Import<'a>>> {
165 let mut imports = Vec::new();
166 self.run(false, libs, segments, ctx, &mut imports)?;
167 self.run(true, libs, segments, ctx, &mut imports)?;
168 Ok(imports)
169 }
170 fn run(
171 &self,
172 is_lazy: bool,
173 libs: &[&'a str],
174 segments: &[segment::Segment],
175 ctx: container::Ctx,
176 imports: &mut Vec<Import<'a>>,
177 ) -> error::Result<()> {
178 use crate::mach::bind_opcodes::*;
179 let location = if is_lazy {
180 &self.lazy_location
181 } else {
182 &self.location
183 };
184 let mut bind_info = BindInformation::new(is_lazy);
185 let mut offset = location.start;
186 let mut start_of_sequence: usize = 0;
187 while offset < location.end {
188 let opcode = self.data.gread::<i8>(&mut offset)? as bind_opcodes::Opcode;
189 // let mut input = String::new();
190 // ::std::io::stdin().read_line(&mut input).unwrap();
191 // println!("opcode: {} ({:#x}) offset: {:#x}\n {:?}", opcode_to_str(opcode & BIND_OPCODE_MASK), opcode, offset - location.start - 1, &bind_info);
192 match opcode & BIND_OPCODE_MASK {
193 // we do nothing, don't update our records, and add a new, fresh record
194 BIND_OPCODE_DONE => {
195 bind_info = BindInformation::new(is_lazy);
196 start_of_sequence = offset - location.start;
197 }
198 BIND_OPCODE_SET_DYLIB_ORDINAL_IMM => {
199 let symbol_library_ordinal = opcode & BIND_IMMEDIATE_MASK;
200 bind_info.symbol_library_ordinal = symbol_library_ordinal;
201 }
202 BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB => {
203 let symbol_library_ordinal = Uleb128::read(&self.data, &mut offset)?;
204 bind_info.symbol_library_ordinal = symbol_library_ordinal as u8;
205 }
206 BIND_OPCODE_SET_DYLIB_SPECIAL_IMM => {
207 // dyld puts the immediate into the symbol_library_ordinal field...
208 let special_dylib = opcode & BIND_IMMEDIATE_MASK;
209 // Printf.printf "special_dylib: 0x%x\n" special_dylib
210 bind_info.special_dylib = special_dylib;
211 }
212 BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM => {
213 let symbol_flags = opcode & BIND_IMMEDIATE_MASK;
214 let symbol_name = self.data.pread::<&str>(offset)?;
215 offset += symbol_name.len() + 1; // second time this \0 caused debug woes
216 bind_info.symbol_name = symbol_name;
217 bind_info.symbol_flags = symbol_flags;
218 }
219 BIND_OPCODE_SET_TYPE_IMM => {
220 let bind_type = opcode & BIND_IMMEDIATE_MASK;
221 bind_info.bind_type = bind_type;
222 }
223 BIND_OPCODE_SET_ADDEND_SLEB => {
224 let addend = Sleb128::read(&self.data, &mut offset)?;
225 bind_info.addend = addend;
226 }
227 BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB => {
228 let seg_index = opcode & BIND_IMMEDIATE_MASK;
229 // dyld sets the address to the segActualLoadAddress(segIndex) + uleb128
230 // address = segActualLoadAddress(segmentIndex) + read_uleb128(p, end);
231 let seg_offset = Uleb128::read(&self.data, &mut offset)?;
232 bind_info.seg_index = seg_index;
233 bind_info.seg_offset = seg_offset;
234 }
235 BIND_OPCODE_ADD_ADDR_ULEB => {
236 let addr = Uleb128::read(&self.data, &mut offset)?;
237 let seg_offset = bind_info.seg_offset.wrapping_add(addr);
238 bind_info.seg_offset = seg_offset;
239 }
240 // record the record by placing its value into our list
241 BIND_OPCODE_DO_BIND => {
242 // from dyld:
243 // if ( address >= segmentEndAddress )
244 // throwBadBindingAddress(address, segmentEndAddress, segmentIndex, start, end, p);
245 // (this->*handler)(context, address, type, symbolName, symboFlags, addend, libraryOrdinal, "", &last);
246 // address += sizeof(intptr_t);
247 imports.push(Import::new(&bind_info, libs, segments, start_of_sequence));
248 let seg_offset = bind_info.seg_offset.wrapping_add(ctx.size() as u64);
249 bind_info.seg_offset = seg_offset;
250 }
251 BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB => {
252 // dyld:
253 // if ( address >= segmentEndAddress )
254 // throwBadBindingAddress(address, segmentEndAddress, segmentIndex, start, end, p);
255 // (this->*handler)(context, address, type, symbolName, symboFlags, addend, libraryOrdinal, "", &last);
256 // address += read_uleb128(p, end) + sizeof(intptr_t);
257 // we bind the old record, then increment bind info address for the next guy, plus the ptr offset *)
258 imports.push(Import::new(&bind_info, libs, segments, start_of_sequence));
259 let addr = Uleb128::read(&self.data, &mut offset)?;
260 let seg_offset = bind_info
261 .seg_offset
262 .wrapping_add(addr)
263 .wrapping_add(ctx.size() as u64);
264 bind_info.seg_offset = seg_offset;
265 }
266 BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED => {
267 // dyld:
268 // if ( address >= segmentEndAddress )
269 // throwBadBindingAddress(address, segmentEndAddress, segmentIndex, start, end, p);
270 // (this->*handler)(context, address, type, symbolName, symboFlags, addend, libraryOrdinal, "", &last);
271 // address += immediate*sizeof(intptr_t) + sizeof(intptr_t);
272 // break;
273 // similarly, we bind the old record, then perform address manipulation for the next record
274 imports.push(Import::new(&bind_info, libs, segments, start_of_sequence));
275 let scale = opcode & BIND_IMMEDIATE_MASK;
276 let size = ctx.size() as u64;
277 let seg_offset = bind_info
278 .seg_offset
279 .wrapping_add(u64::from(scale) * size)
280 .wrapping_add(size);
281 bind_info.seg_offset = seg_offset;
282 }
283 BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB => {
284 // dyld:
285 // count = read_uleb128(p, end);
286 // skip = read_uleb128(p, end);
287 // for (uint32_t i=0; i < count; ++i) {
288 // if ( address >= segmentEndAddress )
289 // throwBadBindingAddress(address, segmentEndAddress, segmentIndex, start, end, p);
290 // (this->*handler)(context, address, type, symbolName, symboFlags, addend, libraryOrdinal, "", &last);
291 // address += skip + sizeof(intptr_t);
292 // }
293 // break;
294 let count = Uleb128::read(&self.data, &mut offset)?;
295 let skip = Uleb128::read(&self.data, &mut offset)?;
296 let skip_plus_size = skip + ctx.size() as u64;
297 for _i in 0..count {
298 imports.push(Import::new(&bind_info, libs, segments, start_of_sequence));
299 let seg_offset = bind_info.seg_offset.wrapping_add(skip_plus_size);
300 bind_info.seg_offset = seg_offset;
301 }
302 }
303 _ => {}
304 }
305 }
306 Ok(())
307 }
308 }