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
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
use scroll::{self, Pread, Gread};
use super::strtab;
pub use super::error;
use error::{Result, Error};
use std::io::Read;
use std::fs::File;
use std::usize;
use std::collections::HashMap;
pub const SIZEOF_MAGIC: usize = 8;
pub const MAGIC: &'static [u8; SIZEOF_MAGIC] = b"!<arch>\x0A";
const SIZEOF_FILE_IDENTIFER: usize = 16;
#[derive(Debug, Clone, PartialEq)]
pub struct Header {
pub identifier: String,
pub timestamp: [u8; 12],
pub owner_id: [u8; 6],
pub group_id: [u8; 6],
pub mode: [u8; 8],
pub size: usize,
pub terminator: [u8; 2],
}
const SIZEOF_FILE_SIZE: usize = 10;
pub const SIZEOF_HEADER: usize = SIZEOF_FILE_IDENTIFER + 12 + 6 + 6 + 8 + SIZEOF_FILE_SIZE + 2;
impl Header {
pub fn parse<R: AsRef<[u8]>>(buffer: &R, offset: &mut usize) -> Result<Header> {
let file_identifier = buffer.gread_slice::<str>(offset, SIZEOF_FILE_IDENTIFER)?.to_string();
let mut file_modification_timestamp = [0u8; 12];
buffer.gread_inout(offset, &mut file_modification_timestamp)?;
let mut owner_id = [0u8; 6];
buffer.gread_inout(offset, &mut owner_id)?;
let mut group_id = [0u8; 6];
buffer.gread_inout(offset, &mut group_id)?;
let mut file_mode = [0u8; 8];
buffer.gread_inout(offset, &mut file_mode)?;
let file_size_pos = *offset;
let file_size_str = buffer.gread_slice::<str>(offset, SIZEOF_FILE_SIZE)?;
let mut terminator = [0u8; 2];
buffer.gread_inout(offset, &mut terminator)?;
let file_size = match usize::from_str_radix(file_size_str.trim_right(), 10) {
Ok(file_size) => file_size,
Err(err) => return Err(Error::Malformed(format!("{:?} Bad file_size {:?} at offset 0x{:X}: {:?} {:?} {:?} {:?} {:?} {:?}",
err, &file_size_str, file_size_pos, file_identifier, file_modification_timestamp, owner_id, group_id,
file_mode, &file_size_str)).into()),
};
Ok(Header {
identifier: file_identifier,
timestamp: file_modification_timestamp.clone(),
owner_id: owner_id.clone(),
group_id: group_id.clone(),
mode: file_mode.clone(),
size: file_size,
terminator: terminator,
})
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct Member {
header: Header,
pub offset: u64,
}
impl Member {
pub fn parse<R: AsRef<[u8]>>(buffer: &R, offset: &mut usize) -> Result<Self> {
let header = Header::parse(buffer, offset)?;
if *offset & 1 == 1 {
*offset += 1;
}
Ok(Member {
header: header,
offset: *offset as u64,
})
}
pub fn size(&self) -> usize {
self.header.size
}
fn trim(name: &str) -> &str {
name.trim_right_matches(' ').trim_right_matches('/')
}
pub fn name(&self) -> &str {
&self.header.identifier
}
}
#[derive(Debug, Default)]
pub struct Index {
pub size: usize,
pub symbol_indexes: Vec<u32>,
pub strtab: Vec<String>,
}
const INDEX_NAME: &'static str = "/ ";
const NAME_INDEX_NAME: &'static str = "// ";
impl Index {
pub fn parse<R: AsRef<[u8]>>(buffer: &R, size: usize) -> Result<Index> {
let mut offset = &mut 0;
let sizeof_table = buffer.gread_with::<u32>(offset, scroll::BE)? as usize;
let mut indexes = Vec::with_capacity(sizeof_table);
for _ in 0..sizeof_table {
indexes.push(buffer.gread_with::<u32>(offset, scroll::BE)?);
}
let sizeof_strtab = size - ((sizeof_table * 4) + 4);
let strtab = strtab::Strtab::parse(buffer, *offset, sizeof_strtab, 0x0)?;
Ok (Index {
size: sizeof_table,
symbol_indexes: indexes,
strtab: strtab.to_vec(),
})
}
}
#[derive(Debug, Default)]
struct NameIndex {
strtab: strtab::Strtab<'static>
}
impl NameIndex {
pub fn parse<R: AsRef<[u8]>> (buffer: &R, offset: &mut usize, size: usize) -> Result<Self> {
let hacked_size = size + 1;
let strtab = strtab::Strtab::parse(buffer, *offset-1, hacked_size, '\n' as u8)?;
*offset += hacked_size - 2;
Ok (NameIndex {
strtab: strtab
})
}
pub fn get(&self, name: &str) -> Result<&str> {
let idx = name.trim_left_matches('/').trim_right();
match usize::from_str_radix(idx, 10) {
Ok(idx) => {
let name = &self.strtab[idx+1];
if name != "" {
Ok(name.trim_right_matches('/'))
} else {
return Err(Error::Malformed(format!("Could not find {:?} in index", name).into()));
}
},
Err (_) => {
return Err(Error::Malformed(format!("Bad name index {:?} in index", name).into()));
}
}
}
}
#[derive(Debug)]
pub struct Archive {
index: Index,
extended_names: NameIndex,
member_array: Vec<Member>,
members: HashMap<String, usize>,
symbol_index: HashMap<String, usize>
}
impl Archive {
pub fn try_from(fd: &mut File) -> Result<Archive> {
let buffer = scroll::Buffer::try_from(fd)?;
Archive::parse(&buffer, buffer.len())
}
pub fn parse<R: Read + AsRef<[u8]>>(buffer: &R, size: usize) -> Result<Archive> {
let mut magic = [0u8; SIZEOF_MAGIC];
let mut offset = &mut 0usize;
buffer.gread_inout(offset, &mut magic)?;
if &magic != MAGIC {
use scroll::Pread;
return Err(Error::BadMagic(magic.pread(0)?).into());
}
let mut member_array = Vec::new();
let size = size as u64;
let mut pos = 0u64;
let mut index = Index::default();
let mut extended_names = NameIndex::default();
loop {
if pos >= size { break }
if pos & 1 == 1 {
*offset += 1;
}
let member = Member::parse(buffer, offset)?;
if member.name() == INDEX_NAME {
*offset = member.offset as usize;
let data: &[u8] = buffer.gread_slice(offset, member.size())?;
index = Index::parse(&data, member.size())?;
pos = *offset as u64;
} else if member.name() == NAME_INDEX_NAME {
*offset = member.offset as usize;
extended_names = NameIndex::parse(buffer, offset, member.size())?;
pos = *offset as u64;
} else {
*offset += member.size();
pos = *offset as u64;
member_array.push(member);
}
}
let mut members = HashMap::new();
for (i, member) in member_array.iter().enumerate() {
let key = {
let name = member.name();
if name.starts_with("/") {
try!(extended_names.get(name))
} else {
Member::trim(name)
}}.to_owned();
members.insert(key, i);
}
let mut symbol_index = HashMap::new();
let mut last_symidx = 0u32;
let mut last_member = 0usize;
for (i, symidx) in index.symbol_indexes.iter().enumerate() {
let name = index.strtab[i].to_owned();
if *symidx == last_symidx {
symbol_index.insert(name, last_member);
} else {
for (memidx, member) in member_array.iter().enumerate() {
if *symidx == (member.offset - SIZEOF_HEADER as u64) as u32 {
symbol_index.insert(name, memidx);
last_symidx = *symidx;
last_member = memidx;
break
}
}
}
}
let archive = Archive {
index: index,
member_array: member_array,
extended_names: extended_names,
members: members,
symbol_index: symbol_index,
};
Ok(archive)
}
fn get (&self, member: &str) -> Option<&Member> {
if let Some(idx) = self.members.get(member) {
Some(&self.member_array[*idx])
} else {
None
}
}
pub fn extract<'a, R: AsRef<[u8]>> (&self, member: &str, buffer: &'a R) -> Result<&'a [u8]> {
if let Some(member) = self.get(member) {
let bytes = buffer.pread_slice(member.offset as usize, member.size())?;
Ok(bytes)
} else {
Err(Error::Malformed(format!("Cannot extract member {:?}", member).into()))
}
}
pub fn members(&self) -> Vec<&String> {
self.members.keys().collect()
}
pub fn member_of_symbol (&self, symbol: &str) -> Option<&str> {
if let Some(idx) = self.symbol_index.get(symbol) {
let name = self.member_array[*idx].name();
if name.starts_with("/") {
Some(self.extended_names.get(name).unwrap())
} else {
Some(Member::trim(name))
}
} else {
None
}
}
}
#[no_mangle]
pub extern fn wow_so_meta_doge_symbol() { println!("wow_so_meta_doge_symbol")}
#[cfg(test)]
mod tests {
extern crate scroll;
use super::*;
use std::path::Path;
use std::fs::File;
use super::super::elf;
#[test]
fn parse_file_header() {
let file_header: [u8; SIZEOF_HEADER] = [0x2f, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x30, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x30, 0x20, 0x20, 0x20, 0x20, 0x20, 0x30,
0x20, 0x20, 0x20, 0x20, 0x20, 0x30, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x38,
0x32, 0x34, 0x34, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x60, 0x0a];
let buffer = scroll::Buffer::new(&file_header[..]);
match Header::parse(&buffer, &mut 0) {
Err(_) => assert!(false),
Ok(file_header2) => {
let file_header = Header { identifier: "/ ".to_owned(),
timestamp: [48, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32],
owner_id: [48, 32, 32, 32, 32, 32],
group_id: [48, 32, 32, 32, 32, 32],
mode: [48, 32, 32, 32, 32, 32, 32, 32],
size: 8244, terminator:
[96, 10] };
assert_eq!(file_header, file_header2)
}
}
}
#[test]
fn parse_archive() {
let crt1a: Vec<u8> = include!("../../etc/crt1a.rs");
const START: &'static str = "_start";
let len = crt1a.len();
let buffer = scroll::Buffer::new(crt1a);
match Archive::parse(&buffer, len) {
Ok(archive) => {
assert_eq!(archive.member_of_symbol(START), Some("crt1.o"));
if let Some(member) = archive.get("crt1.o") {
assert_eq!(member.offset, 194);
assert_eq!(member.size(), 1928)
} else {
println!("could not get crt1.o");
assert!(false)
}
},
Err(err) => {println!("could not parse archive: {:?}", err); assert!(false)}
};
}
#[test]
fn parse_self_wow_so_meta_doge() {
let path = Path::new("target").join("debug").join("libgoblin.rlib");
match File::open(path) {
Ok(fd) => {
let buffer = scroll::Buffer::try_from(fd).unwrap();
let size = buffer.len();
match Archive::parse(&buffer, size) {
Ok(archive) => {
let mut found = false;
for member in archive.members() {
if member.starts_with("goblin") && member.ends_with("0.o") {
assert_eq!(archive.member_of_symbol("wow_so_meta_doge_symbol"), Some(member.as_str()));
match archive.extract(member.as_str(), &buffer) {
Ok(bytes) => {
match elf::Elf::parse::<scroll::Buffer>(&scroll::Buffer::new(bytes)) {
Ok(elf) => {
assert!(elf.entry == 0);
assert!(elf.bias == 0);
found = true;
break;
},
Err(_) => assert!(false)
}
},
Err(_) => assert!(false)
}
}
}
if !found {
println!("goblin-<hash>.0.o not found");
assert!(false)
}
},
Err(err) => {println!("{:?}", err); assert!(false)}
}
},
Err(err) => {println!("{:?}", err); assert!(false)}
}
}
}