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
#[macro_use]
extern crate nom;
extern crate byteorder;
#[macro_use]
mod macros;
mod value;
mod header;
mod section;
mod pht;
#[allow(unused_imports)]
pub use section::{
Section,
SectionType,
SegFlag
};
use section::read_section;
#[allow(unused_imports)]
pub use value::{
Elf_Addr,
Elf_Off,
Elf_VarWord,
Elf_Half,
Elf_SHalf,
Elf_Word,
Elf_SWord,
Elf_XWord,
Elf_Sxword
};
#[allow(unused_imports)]
pub use header::{
Endian,
Platform,
ElfHeader,
ABI,
Kind,
Arch
};
use header::read_elf_header;
use pht::{read_pht_64,read_pht_32};
use value::get_platform;
#[allow(unused_imports)]
pub use pht::{
ProgramHeaderTable,
RamFlags
};
pub use nom::IResult;
#[derive(Debug)]
pub struct Elf {
pub header: ElfHeader,
pub sections: Vec<Section>,
pub progheader: Vec<ProgramHeaderTable>
}
impl Elf {
pub fn parse(x: &[u8] ) -> Option<Elf> {
let (_,header) = match read_elf_header(x) {
IResult::Done(x,y) => (x,y),
_ => return None
};
let mut ret_sec = Vec::<Section>::with_capacity(0);
let mut ret_pht = Vec::<ProgramHeaderTable>::with_capacity(0);
let section_offset: usize = header.shoff.into();
let section_size: usize = header.shentsize.into();
let section_num: usize = header.shnum.into();
if section_num > 0 {
let section_table_end: usize = section_size * section_num + section_offset;
let sec = &x[section_offset..section_table_end];
let mut sections = Vec::with_capacity(section_num);
let mut val: &[u8] = sec;
for _ in 0..section_num {
let (rem, sec) = match read_section(val) {
IResult::Done(x,y) => (x,y),
_ => return None
};
val = rem;
sections.push(sec);
}
ret_sec = sections;
}
let pht_offset: usize = header.phoff.into();
let pht_size: usize = header.shentsize.into();
let pht_num: usize = header.shnum.into();
if pht_num > 0 {
let pht_end: usize = pht_size * pht_num + pht_offset;
let sec = &x[pht_offset..pht_end];
let mut pht = Vec::with_capacity(pht_num);
let mut val: &[u8] = sec;
for _ in 0..pht_num {
if get_platform() == Platform::Bit32 {
let (rem, sec) = match read_pht_32(val) {
IResult::Done(x,y) => (x,y),
_ => return None
};
val = rem;
pht.push(sec);
} else {
let (rem, sec) = match read_pht_64(val) {
IResult::Done(x,y) => (x,y),
_ => return None
};
val = rem;
pht.push(sec);
}
}
ret_pht = pht;
}
Some(Elf {
header: header,
sections: ret_sec,
progheader: ret_pht
})
}
}