forked from flier/rust-macho
-
Notifications
You must be signed in to change notification settings - Fork 1
/
otool.rs
388 lines (324 loc) · 13.5 KB
/
otool.rs
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
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
#[macro_use]
extern crate log;
extern crate env_logger;
extern crate getopts;
extern crate byteorder;
extern crate memmap;
extern crate mach_object;
use std::env;
use std::mem::size_of;
use std::io::{Write, Cursor, Seek, SeekFrom, stdout, stderr};
use std::path::Path;
use std::process::exit;
use getopts::Options;
use byteorder::ReadBytesExt;
use memmap::{Mmap, Protection};
use mach_object::*;
const APP_VERSION: &'static str = "0.1.1";
fn print_usage(program: &str, opts: Options) {
let brief = format!("Usage: {} [-arch arch_type] [options] [--version] <object file> ...",
program);
print!("{}", opts.usage(&brief));
}
fn main() {
env_logger::init().unwrap();
let args: Vec<String> = env::args().collect();
let program = Path::new(args[0].as_str()).file_name().unwrap().to_str().unwrap();
let mut opts = Options::new();
opts.optopt("", "arch", "Specifies the architecture", "arch_type");
opts.optflag("f", "", "print the fat headers");
opts.optflag("a", "", "print the archive headers");
opts.optflag("h", "", "print the mach header");
opts.optflag("l", "", "print the load commands");
opts.optflag("L", "", "print shared libraries used");
opts.optflag("D", "", "print shared library id name");
opts.optflag("t", "", "print the text section");
opts.optflag("d", "", "print the data section");
opts.optflag("n", "", "print the symbol table");
opts.optopt("s", "", "print contents of section", "<segname>:<sectname>");
opts.optflag("S", "", "print the table of contents of a library");
opts.optflag("X", "", "print no leading addresses or headers");
opts.optflag("",
"version",
format!("print the version of {}", program).as_str());
let matches = match opts.parse(&args[1..]) {
Ok(m) => m,
Err(_) => {
print_usage(&program, opts);
exit(-1);
}
};
if matches.opt_present("version") {
println!("{} version {}", program, APP_VERSION);
exit(0);
}
if matches.free.is_empty() {
write!(stderr(), "at least one file must be specified\n\n").unwrap();
print_usage(&program, opts);
exit(-1);
}
let mut processor = FileProcessor {
w: stdout(),
cpu_type: 0,
print_headers: !matches.opt_present("X"),
print_fat_header: matches.opt_present("f"),
print_archive_header: matches.opt_present("a"),
print_mach_header: matches.opt_present("h"),
print_load_commands: matches.opt_present("l"),
print_shared_lib: matches.opt_present("L") || matches.opt_present("D"),
print_shared_lib_just_id: matches.opt_present("D") && !matches.opt_present("L"),
print_text_section: matches.opt_present("t"),
print_data_section: matches.opt_present("d"),
print_symbol_table: matches.opt_present("n"),
print_section: matches.opt_str("s").map(|s| {
let names: Vec<&str> = s.splitn(2, ':').collect();
if names.len() == 2 {
(String::from(names[0]), Some(String::from(names[1])))
} else {
(String::from(names[0]), None)
}
}),
print_lib_toc: matches.opt_present("S"),
};
if let Some(flags) = matches.opt_str("arch") {
if let Some(&(cpu_type, _)) = get_arch_from_flag(flags.as_str()) {
processor.cpu_type = cpu_type;
} else {
write!(stderr(),
"unknown architecture specification flag: arch {}\n",
flags)
.unwrap();
exit(-1);
}
}
for filename in matches.free {
if let Err(err) = processor.process(filename.as_str()) {
write!(stderr(), "fail to process file {}, {}", filename, err).unwrap();
exit(-1);
}
}
}
struct FileProcessor<T: Write> {
w: T,
cpu_type: cpu_type_t,
print_headers: bool,
print_fat_header: bool,
print_archive_header: bool,
print_mach_header: bool,
print_load_commands: bool,
print_shared_lib: bool,
print_shared_lib_just_id: bool,
print_text_section: bool,
print_data_section: bool,
print_symbol_table: bool,
print_section: Option<(String, Option<String>)>,
print_lib_toc: bool,
}
struct FileProcessContext<'a> {
filename: String,
cur: &'a mut Cursor<&'a [u8]>,
}
impl<'a> FileProcessContext<'a> {
fn hexdump(&mut self, addr: usize, size: usize) -> Result<Vec<u8>, Error> {
let mut w = Vec::new();
for off in 0..size {
if (off % 16) == 0 {
if off > 0 {
try!(write!(&mut w, "\n"));
}
try!(write!(&mut w, "{:016x}\t", addr + off));
}
try!(write!(&mut w, "{:02x} ", try!(self.cur.read_u8())));
}
try!(write!(&mut w, "\n"));
Ok(w)
}
}
impl<T: Write> FileProcessor<T> {
fn process(&mut self, filename: &str) -> Result<(), Error> {
let file_mmap = try!(Mmap::open_path(filename, Protection::Read));
let mut cur = Cursor::new(unsafe { file_mmap.as_slice() });
let file = try!(OFile::parse(&mut cur));
let mut ctxt = FileProcessContext {
filename: String::from(filename),
cur: &mut cur,
};
debug!("process file {} with {} bytes", filename, file_mmap.len());
try!(self.process_ofile(&file, &mut ctxt));
if self.print_symbol_table {
debug!("dumping symbol table");
if let Some(symbols) = file.symbols(ctxt.cur) {
for symbol in symbols {
try!(write!(self.w, "{}\n", symbol));
}
}
}
Ok(())
}
fn process_ofile(&mut self, ofile: &OFile, ctxt: &mut FileProcessContext) -> Result<(), Error> {
match ofile {
&OFile::MachFile { ref header, ref commands } => {
self.process_mach_file(&header, &commands, ctxt)
}
&OFile::FatFile { magic, ref files } => self.process_fat_file(magic, files, ctxt),
&OFile::ArFile { ref files } => self.process_ar_file(files, ctxt),
&OFile::SymDef { ref ranlibs } => self.process_symdef(ranlibs, ctxt),
}
}
fn print_mach_file(&self) -> bool {
self.print_mach_header | self.print_load_commands | self.print_text_section |
self.print_data_section | self.print_shared_lib
}
fn process_mach_file(&mut self,
header: &MachHeader,
commands: &Vec<MachCommand>,
ctxt: &mut FileProcessContext)
-> Result<(), Error> {
if self.cpu_type != 0 && self.cpu_type != CPU_TYPE_ANY && self.cpu_type != header.cputype {
return Ok(());
}
if self.print_headers && self.print_mach_file() {
if self.cpu_type != 0 {
try!(write!(self.w,
"{} (architecture {}):\n",
ctxt.filename,
get_arch_name_from_types(header.cputype, header.cpusubtype)
.unwrap_or(format!("cputype {} cpusubtype {}",
header.cputype,
header.cpusubtype)
.as_str())));
} else {
try!(write!(self.w, "{}:\n", ctxt.filename));
}
}
if self.print_mach_header {
try!(write!(self.w, "{}", header));
}
if self.print_load_commands {
for (i, ref cmd) in commands.iter().enumerate() {
try!(write!(self.w, "Load command {}\n", i));
try!(write!(self.w, "{}", cmd));
}
}
for cmd in commands {
let &MachCommand(ref cmd, _) = cmd;
match cmd {
&LoadCommand::Segment { ref sections, .. } |
&LoadCommand::Segment64 { ref sections, .. } => {
for ref sect in sections {
let name = Some((sect.segname.clone(), Some(sect.sectname.clone())));
if name == self.print_section ||
Some((sect.segname.clone(), None)) == self.print_section ||
(self.print_text_section &&
name ==
Some((String::from(SEG_TEXT), Some(String::from(SECT_TEXT))))) ||
(self.print_data_section &&
name == Some((String::from(SEG_DATA), Some(String::from(SECT_DATA))))) {
if self.print_headers {
try!(write!(self.w,
"Contents of ({},{}) section\n",
sect.segname,
sect.sectname));
}
try!(ctxt.cur.seek(SeekFrom::Start(sect.offset as u64)));
let dump = try!(ctxt.hexdump(sect.addr, sect.size));
try!(self.w.write(&dump[..]));
}
}
}
&LoadCommand::IdFvmLib(ref fvmlib) |
&LoadCommand::LoadFvmLib(ref fvmlib) if self.print_shared_lib &&
!self.print_shared_lib_just_id => {
try!(write!(self.w,
"\t{} (minor version {})\n",
fvmlib.name,
fvmlib.minor_version));
}
&LoadCommand::IdDyLib(ref dylib) |
&LoadCommand::LoadDyLib(ref dylib) |
&LoadCommand::LoadWeakDyLib(ref dylib) |
&LoadCommand::ReexportDyLib(ref dylib) |
&LoadCommand::LoadUpwardDylib(ref dylib) |
&LoadCommand::LazyLoadDylib(ref dylib) if self.print_shared_lib &&
(cmd.cmd() == LC_ID_DYLIB ||
!self.print_shared_lib_just_id) => {
if self.print_shared_lib_just_id {
try!(write!(self.w, "{}", dylib.name));
} else {
try!(write!(self.w,
"\t{} (compatibility version {}.{}.{}, current version \
{}.{}.{})\n",
dylib.name,
dylib.compatibility_version.major(),
dylib.compatibility_version.minor(),
dylib.compatibility_version.release(),
dylib.current_version.major(),
dylib.current_version.minor(),
dylib.current_version.release()));
}
}
_ => {}
}
}
Ok(())
}
fn process_fat_file(&mut self,
magic: u32,
files: &Vec<(FatArch, OFile)>,
ctxt: &mut FileProcessContext)
-> Result<(), Error> {
if self.print_fat_header {
let header = FatHeader {
magic: magic,
archs: files.iter().map(|&(ref arch, _)| arch.clone()).collect(),
};
try!(write!(self.w, "{}", header));
}
for &(_, ref file) in files {
try!(self.process_ofile(file, ctxt));
}
Ok(())
}
fn process_ar_file(&mut self,
files: &Vec<(ArHeader, OFile)>,
ctxt: &mut FileProcessContext)
-> Result<(), Error> {
if self.print_headers && (self.print_lib_toc || self.print_mach_file()) {
try!(write!(self.w, "Archive :{}\n", ctxt.filename));
}
if self.print_archive_header {
for &(ref header, _) in files {
try!(write!(self.w, "{}", header));
}
}
for &(ref header, ref file) in files {
try!(self.process_ofile(file,
&mut FileProcessContext {
filename: if let Some(ref name) = header.ar_member_name {
format!("{}({})", ctxt.filename, name)
} else {
ctxt.filename.clone()
},
cur: &mut ctxt.cur.clone(),
}));
}
Ok(())
}
fn process_symdef(&mut self,
ranlibs: &Vec<RanLib>,
ctxt: &mut FileProcessContext)
-> Result<(), Error> {
if self.print_lib_toc {
try!(write!(self.w, "Table of contents from: {}\n", ctxt.filename));
try!(write!(self.w,
"size of ranlib structures: {} (number {})\n",
ranlibs.len() * size_of::<RanLib>(),
ranlibs.len()));
try!(write!(self.w, "object offset string index\n"));
for ref ranlib in ranlibs {
try!(write!(self.w, "{:<14} {}\n", ranlib.ran_off, ranlib.ran_strx));
}
}
Ok(())
}
}