This repository was archived by the owner on Feb 16, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathheader.rs
More file actions
702 lines (653 loc) · 23 KB
/
Copy pathheader.rs
File metadata and controls
702 lines (653 loc) · 23 KB
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
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
//! Module containing the Dex file header.
use crate::{
error,
sizes::{
CLASS_DEF_ITEM_SIZE, FIELD_ID_ITEM_SIZE, HEADER_SIZE, METHOD_ID_ITEM_SIZE,
PROTO_ID_ITEM_SIZE, STRING_ID_ITEM_SIZE, TYPE_ID_ITEM_SIZE,
},
};
use anyhow::{Context, Result};
use byteorder::{BigEndian, ByteOrder, LittleEndian, ReadBytesExt};
use std::{
fmt, fs,
io::{BufReader, Read},
path::Path,
u32,
};
/// Endianness constant representing little endian file.
pub const ENDIAN_CONSTANT: u32 = 0x12_34_56_78;
/// Endianness constant representing big endian file.
pub const REVERSE_ENDIAN_CONSTANT: u32 = 0x78_56_34_12;
/// Dex header representation structure.
#[derive(Clone, Copy)]
pub struct Header {
magic: [u8; 8],
checksum: u32,
signature: [u8; 20],
file_size: u32,
header_size: u32,
endian_tag: u32,
link_size: u32,
link_offset: Option<u32>,
map_offset: u32,
string_ids_size: u32,
string_ids_offset: Option<u32>,
type_ids_size: u32,
type_ids_offset: Option<u32>,
prototype_ids_size: u32,
prototype_ids_offset: Option<u32>,
field_ids_size: u32,
field_ids_offset: Option<u32>,
method_ids_size: u32,
method_ids_offset: Option<u32>,
class_defs_size: u32,
class_defs_offset: Option<u32>,
data_size: u32,
data_offset: u32,
}
impl Header {
/// Obtains the header from a Dex file.
pub fn from_file<P: AsRef<Path>>(path: P) -> Result<Self> {
let f = fs::File::open(path).context("could not open file")?;
let file_size = f.metadata().context("could not read file metadata")?.len();
if file_size < u64::from(HEADER_SIZE) || file_size > (u64::from(u32::max_value())) {
return Err(error::InvalidFileSize { file_size }.into());
}
let header = Self::from_reader(BufReader::new(f)).context(error::Header::Generic {
error: "there was an error reading the header of the dex file".to_owned(),
})?;
if file_size == u64::from(header.get_file_size()) {
Ok(header)
} else {
Err(error::Header::FileSizeMismatch {
file_size,
size_in_header: header.get_file_size(),
}
.into())
}
}
/// Obtains the header from a Dex file reader.
pub fn from_reader<R: Read>(mut reader: R) -> Result<Self> {
// Magic number
let mut magic = [0_u8; 8];
reader
.read_exact(&mut magic)
.context("could not read dex magic number")?;
if !Self::is_magic_valid(magic) {
return Err(error::Header::IncorrectMagic { dex_magic: magic }.into());
}
// Checksum
let mut checksum = reader
.read_u32::<LittleEndian>()
.context("could not read file checksum")?;
// Signature
let mut signature = [0_u8; 20];
reader
.read_exact(&mut signature)
.context("could not read file signature")?;
// File size
let mut file_size = reader
.read_u32::<LittleEndian>()
.context("could not read file size")?;
// Header size
let mut header_size = reader
.read_u32::<LittleEndian>()
.context("could not read header size")?;
// Endian tag
let endian_tag = reader
.read_u32::<LittleEndian>()
.context("could not read endian tag")?;
// Check endianness
if endian_tag == REVERSE_ENDIAN_CONSTANT {
// The file is in big endian instead of little endian.
checksum = checksum.swap_bytes();
file_size = file_size.swap_bytes();
header_size = header_size.swap_bytes();
} else if endian_tag != ENDIAN_CONSTANT {
return Err(error::Header::InvalidEndianTag { endian_tag }.into());
}
// Check header size
if header_size != HEADER_SIZE {
return Err(error::Header::IncorrectHeaderSize { header_size }.into());
}
if endian_tag == ENDIAN_CONSTANT {
Self::read_data::<_, LittleEndian>(
reader,
magic,
checksum,
signature,
file_size,
header_size,
ENDIAN_CONSTANT,
)
} else {
Self::read_data::<_, BigEndian>(
reader,
magic,
checksum,
signature,
file_size,
header_size,
REVERSE_ENDIAN_CONSTANT,
)
}
}
fn read_data<R: Read, E: ByteOrder>(
mut reader: R,
magic: [u8; 8],
checksum: u32,
signature: [u8; 20],
file_size: u32,
header_size: u32,
endian_tag: u32,
) -> Result<Self> {
/// Returns `Some(x)` if the boolean is `true`, `None` otherwise.
#[inline]
fn some_if(x: u32, b: bool) -> Option<u32> {
if b {
Some(x)
} else {
None
}
}
let mut current_offset = HEADER_SIZE;
// Link size
let link_size = reader
.read_u32::<E>()
.context("could not read the link section size")?;
// Link offset
let link_offset = reader
.read_u32::<E>()
.context("could not read the link section offset")?;
if link_size == 0 && link_offset != 0 {
return Err(error::Parse::OffsetMismatch {
offset_name: "link_offset",
current_offset: link_offset,
expected_offset: 0,
}
.into());
}
// Map offset
let map_offset = reader
.read_u32::<E>()
.context("could not read the map section offset")?;
if map_offset == 0x0000_0000 {
return Err(error::Parse::InvalidOffset {
desc: "`map_offset` was 0x00000000, and it can never be zero".to_owned(),
}
.into());
}
// String IDs size
let string_ids_size = reader
.read_u32::<E>()
.context("could not read the string IDs list size")?;
// String IDs offset
let string_ids_offset = reader
.read_u32::<E>()
.context("could not read the string IDs list offset")?;
if string_ids_size > 0 && string_ids_offset != current_offset {
return Err(error::Parse::OffsetMismatch {
offset_name: "string_ids_offset",
current_offset: string_ids_offset,
expected_offset: HEADER_SIZE,
}
.into());
}
if string_ids_size == 0 && string_ids_offset != 0 {
return Err(error::Parse::OffsetMismatch {
offset_name: "string_ids_offset",
current_offset: string_ids_offset,
expected_offset: 0,
}
.into());
}
current_offset += string_ids_size * STRING_ID_ITEM_SIZE;
// Types IDs size
let type_ids_size = reader
.read_u32::<E>()
.context("could not read the type IDs list size")?;
// Types IDs offset
let type_ids_offset = reader
.read_u32::<E>()
.context("could not read the type IDs list offset")?;
if type_ids_size > 0 && type_ids_offset != current_offset {
return Err(error::Parse::OffsetMismatch {
offset_name: "type_ids_offset",
current_offset: type_ids_offset,
expected_offset: current_offset,
}
.into());
}
if type_ids_size == 0 && type_ids_offset != 0 {
return Err(error::Parse::OffsetMismatch {
offset_name: "type_ids_offset",
current_offset: type_ids_offset,
expected_offset: 0,
}
.into());
}
current_offset += type_ids_size * TYPE_ID_ITEM_SIZE;
// Prototype IDs size
let prototype_ids_size = reader
.read_u32::<E>()
.context("could not read the prototype IDs list size")?;
// Prototype IDs offset
let prototype_ids_offset = reader
.read_u32::<E>()
.context("could not read the prototype IDs list offset")?;
if prototype_ids_size > 0 && prototype_ids_offset != current_offset {
return Err(error::Parse::OffsetMismatch {
offset_name: "prototype_ids_offset",
current_offset: prototype_ids_offset,
expected_offset: current_offset,
}
.into());
}
if prototype_ids_size == 0 && prototype_ids_offset != 0 {
return Err(error::Parse::OffsetMismatch {
offset_name: "prototype_ids_offset",
current_offset: prototype_ids_offset,
expected_offset: 0,
}
.into());
}
current_offset += prototype_ids_size * PROTO_ID_ITEM_SIZE;
// Field IDs size
let field_ids_size = reader
.read_u32::<E>()
.context("could not read the field IDs list size")?;
// Field IDs offset
let field_ids_offset = reader
.read_u32::<E>()
.context("could not read the field IDs list offset")?;
if field_ids_size > 0 && field_ids_offset != current_offset {
return Err(error::Parse::OffsetMismatch {
offset_name: "field_ids_offset",
current_offset: field_ids_offset,
expected_offset: current_offset,
}
.into());
}
if field_ids_size == 0 && field_ids_offset != 0 {
return Err(error::Parse::OffsetMismatch {
offset_name: "field_ids_offset",
current_offset: field_ids_offset,
expected_offset: 0,
}
.into());
}
current_offset += field_ids_size * FIELD_ID_ITEM_SIZE;
// Method IDs size
let method_ids_size = reader
.read_u32::<E>()
.context("could not read the method IDs list size")?;
// Method IDs offset
let method_ids_offset = reader
.read_u32::<E>()
.context("could not read the method IDs list offset")?;
if method_ids_size > 0 && method_ids_offset != current_offset {
return Err(error::Parse::OffsetMismatch {
offset_name: "method_ids_offset",
current_offset: method_ids_offset,
expected_offset: current_offset,
}
.into());
}
if method_ids_size == 0 && method_ids_offset != 0 {
return Err(error::Parse::OffsetMismatch {
offset_name: "method_ids_offset",
current_offset: method_ids_offset,
expected_offset: 0,
}
.into());
}
current_offset += method_ids_size * METHOD_ID_ITEM_SIZE;
// Class defs size
let class_defs_size = reader
.read_u32::<E>()
.context("could not read the class definitions list size")?;
// Class defs offset
let class_defs_offset = reader
.read_u32::<E>()
.context("could not read the class definitions list offset")?;
if class_defs_size > 0 && class_defs_offset != current_offset {
return Err(error::Parse::OffsetMismatch {
offset_name: "class_defs_offset",
current_offset: class_defs_offset,
expected_offset: current_offset,
}
.into());
}
if class_defs_size == 0 && class_defs_offset != 0 {
return Err(error::Parse::OffsetMismatch {
offset_name: "class_defs_offset",
current_offset: class_defs_offset,
expected_offset: 0,
}
.into());
}
current_offset += class_defs_size * CLASS_DEF_ITEM_SIZE;
// Data size
let data_size = reader
.read_u32::<E>()
.context("could not read the data section size")?;
if data_size & 0b11 != 0 {
return Err(error::Header::Generic {
error: format!(
"`data_size` must be a 4-byte multiple, but it was {:#010x}",
data_size
),
}
.into());
}
// Data offset
let data_offset = reader
.read_u32::<E>()
.context("could not read the data section offset")?;
if data_offset != current_offset {
// return Err(Error::mismatched_offsets("data_offset", data_offset, current_offset));
// TODO seems that there is more information after the class definitions.
if cfg!(feature = "debug") {
println!(
"{} bytes of unknown data were found.",
data_offset - current_offset
);
}
current_offset = data_offset;
}
current_offset += data_size;
if map_offset < data_offset || map_offset > data_offset + data_size {
return Err(error::Parse::InvalidOffset {
desc: format!(
"`map_offset` section must be in the `data` section (between {:#010x} and \
{:#010x}) but it was at {:#010x}",
data_offset, current_offset, map_offset
),
}
.into());
}
if link_size == 0 && current_offset != file_size {
return Err(error::Header::Generic {
error: format!(
"`data` section must end at the EOF if there are no links in the file. Data \
end: {:#010x}, `file_size`: {:#010x}",
current_offset, file_size
),
}
.into());
}
if link_size != 0 && link_offset == 0 {
return Err(error::Parse::OffsetMismatch {
offset_name: "link_offset",
current_offset: 0,
expected_offset: current_offset,
}
.into());
}
if link_size != 0 && link_offset != 0 {
if link_offset != current_offset {
return Err(error::Parse::OffsetMismatch {
offset_name: "link_offset",
current_offset: link_offset,
expected_offset: current_offset,
}
.into());
}
if link_offset + link_size != file_size {
return Err(error::Header::Generic {
error: "`link_data` section must end at the end of file".to_owned(),
}
.into());
}
}
Ok(Self {
magic,
checksum,
signature,
file_size,
header_size,
endian_tag,
link_size,
link_offset: some_if(link_offset, link_offset != 0),
map_offset,
string_ids_size,
string_ids_offset: some_if(string_ids_offset, string_ids_offset > 0),
type_ids_size,
type_ids_offset: some_if(type_ids_offset, type_ids_offset > 0),
prototype_ids_size,
prototype_ids_offset: some_if(prototype_ids_offset, prototype_ids_size > 0),
field_ids_size,
field_ids_offset: some_if(field_ids_offset, field_ids_size > 0),
method_ids_size,
method_ids_offset: some_if(method_ids_offset, method_ids_size > 0),
class_defs_size,
class_defs_offset: some_if(class_defs_offset, class_defs_size > 0),
data_size,
data_offset,
})
}
/// Checks if the dex magic number given is valid.
fn is_magic_valid(magic: [u8; 8]) -> bool {
magic[0..4] == [0x64, 0x65, 0x78, 0x0a]
&& magic[7] == 0x00
&& magic[4] >= 0x30
&& magic[5] >= 0x30
&& magic[6] >= 0x30
&& magic[4] <= 0x39
&& magic[5] <= 0x39
&& magic[6] <= 0x39
}
/// Gets the magic value.
pub fn get_magic(&self) -> &[u8; 8] {
&self.magic
}
/// Gets Dex version.
pub fn get_dex_version(&self) -> u8 {
(self.magic[4] - 0x30) * 100 + (self.magic[5] - 0x30) * 10 + (self.magic[6] - 0x30)
}
/// Gets file checksum.
pub fn get_checksum(&self) -> u32 {
self.checksum
}
/// Gets file SHA-1 signature.
pub fn get_signature(&self) -> &[u8; 20] {
&self.signature
}
/// Gets file size.
pub fn get_file_size(&self) -> u32 {
self.file_size
}
/// Gets header size, in bytes.
///
/// This must be 0x70.
pub fn get_header_size(&self) -> u32 {
self.header_size
}
/// Gets the endian tag.
///
/// This must be `ENDIAN_CONSTANT` or `REVERSE_ENDIAN_CONSTANT`.
pub fn get_endian_tag(&self) -> u32 {
self.endian_tag
}
/// Gets wether the file is in little endian or not.
pub fn is_little_endian(&self) -> bool {
self.endian_tag == ENDIAN_CONSTANT
}
/// Gets wether the file is in big endian or not.
pub fn is_big_endian(&self) -> bool {
self.endian_tag == REVERSE_ENDIAN_CONSTANT
}
/// Gets the link section size
pub fn get_link_size(&self) -> u32 {
self.link_size
}
/// Gets the link section offset.
pub fn get_link_offset(&self) -> Option<u32> {
self.link_offset
}
/// Gets the map section offset.
pub fn get_map_offset(&self) -> u32 {
self.map_offset
}
/// Gets the string IDs list size.
pub fn get_string_ids_size(&self) -> u32 {
self.string_ids_size
}
/// Gets the string IDs list offset.
pub fn get_string_ids_offset(&self) -> Option<u32> {
self.string_ids_offset
}
/// Gets the type IDs list size.
pub fn get_type_ids_size(&self) -> u32 {
self.type_ids_size
}
/// Gets the type IDs list offset.
pub fn get_type_ids_offset(&self) -> Option<u32> {
self.type_ids_offset
}
/// Gets the prototype IDs list size.
pub fn get_prototype_ids_size(&self) -> u32 {
self.prototype_ids_size
}
/// Gets the prototype IDs list offset.
pub fn get_prototype_ids_offset(&self) -> Option<u32> {
self.prototype_ids_offset
}
/// Gets the field IDs list size.
pub fn get_field_ids_size(&self) -> u32 {
self.field_ids_size
}
/// Gets the field IDs list offset.
pub fn get_field_ids_offset(&self) -> Option<u32> {
self.field_ids_offset
}
/// Gets the method IDs list size.
pub fn get_method_ids_size(&self) -> u32 {
self.method_ids_size
}
/// Gets the method IDs list offset.
pub fn get_method_ids_offset(&self) -> Option<u32> {
self.method_ids_offset
}
/// Gets the class definition list size.
pub fn get_class_defs_size(&self) -> u32 {
self.class_defs_size
}
/// Gets the class definition list offset.
pub fn get_class_defs_offset(&self) -> Option<u32> {
self.class_defs_offset
}
/// Gets the data section size.
pub fn get_data_size(&self) -> u32 {
self.data_size
}
/// Gets the data section offset.
pub fn get_data_offset(&self) -> u32 {
self.data_offset
}
// /// Verifies the file at the given path.
// pub fn verify_file<P: AsRef<Path>>(&self, path: P) -> bool {
// unimplemented!() // TODO
// }
//
// /// Verifies the file in the given reader.
// ///
// /// The reader should be positioned at the start of the file.
// pub fn verify_reader<R: Read>(&self, mut reader: R) -> bool {
// unimplemented!() // TODO
// }
}
impl fmt::Debug for Header {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"Header {{ magic: [ {} ] (version: {}), checksum: {:#x}, SHA-1 signature: {}, \
file_size: {} bytes, header_size: {} bytes, endian_tag: {:#x} ({} endian), {}, \
map_offset: {:#x}, {}, {}, {}, {}, {}, {}, data_size: {} bytes, data_offset: \
{:#x} }}",
{
let mut magic_vec = Vec::with_capacity(8);
for b in &self.magic {
magic_vec.push(format!("{:#02x}", b))
}
magic_vec.join(", ")
},
self.get_dex_version(),
self.checksum,
{
let mut signature = String::with_capacity(40);
for b in &self.signature {
signature.push_str(&format!("{:02x}", b))
}
signature
},
self.file_size,
self.header_size,
self.endian_tag,
if self.is_little_endian() {
"little"
} else {
"big"
},
if let Some(off) = self.link_offset {
format!(
"link_size: {} bytes, link_offset: {:#x}",
self.link_size, off
)
} else {
String::from("no link section")
},
self.map_offset,
if let Some(off) = self.string_ids_offset {
format!(
"string_ids_size: {} strings, string_ids_offset: {:#x}",
self.string_ids_size, off
)
} else {
String::from("no strings")
},
if let Some(off) = self.type_ids_offset {
format!(
"type_ids_size: {} types, type_ids_offset: {:#x}",
self.type_ids_size, off
)
} else {
String::from("no types")
},
if let Some(off) = self.prototype_ids_offset {
format!(
"prototype_ids_size: {} types, prototype_ids_offset: {:#x}",
self.prototype_ids_size, off
)
} else {
String::from("no prototypes")
},
if let Some(off) = self.field_ids_offset {
format!(
"field_ids_size: {} types, field_ids_offset: {:#x}",
self.field_ids_size, off
)
} else {
String::from("no fields")
},
if let Some(off) = self.method_ids_offset {
format!(
"method_ids_size: {} types, method_ids_offset: {:#x}",
self.method_ids_size, off
)
} else {
String::from("no methods")
},
if let Some(off) = self.class_defs_offset {
format!(
"class_defs_size: {} classes, class_defs_offset: {:#x}",
self.class_defs_size, off
)
} else {
String::from("no classes")
},
self.data_size,
self.data_offset
)
}
}