-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathid1.rs
296 lines (277 loc) · 11 KB
/
id1.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
use anyhow::{anyhow, ensure, Result};
use std::ops::Range;
use crate::ida_reader::IdaGenericUnpack;
use crate::{IDBHeader, IDBSectionCompression, VaVersion};
#[derive(Clone, Debug)]
pub struct ID1Section {
pub seglist: Vec<SegInfo>,
}
#[derive(Clone, Debug)]
pub struct SegInfo {
pub offset: u64,
pub data: Vec<u8>,
// TODO find a way to decode this data
_flags: Vec<u32>,
}
impl ID1Section {
pub(crate) fn read(
input: &mut impl IdaGenericUnpack,
header: &IDBHeader,
compress: IDBSectionCompression,
) -> Result<Self> {
match compress {
IDBSectionCompression::None => Self::read_inner(input, header),
IDBSectionCompression::Zlib => {
let mut input = flate2::read::ZlibDecoder::new(input);
Self::read_inner(&mut input, header)
}
}
}
fn read_inner(
input: &mut impl IdaGenericUnpack,
header: &IDBHeader,
) -> Result<Self> {
// TODO pages are always 0x2000?
const PAGE_SIZE: usize = 0x2000;
let mut buf = vec![0; PAGE_SIZE];
input.read_exact(&mut buf[..])?;
let mut header_page = &buf[..];
let version = VaVersion::read(&mut header_page)?;
let (npages, seglist_raw) = match version {
VaVersion::Va0
| VaVersion::Va1
| VaVersion::Va2
| VaVersion::Va3
| VaVersion::Va4 => {
let nsegments: u16 =
bincode::deserialize_from(&mut header_page)?;
let npages: u16 = bincode::deserialize_from(&mut header_page)?;
ensure!(
npages > 0,
"Invalid number of pages, net at least one for the header"
);
// TODO section_size / npages == 0x2000
// TODO the reference code uses the magic version, should it use
// the version itself instead?
let seglist: Vec<SegInfoVaNRaw> = if header
.magic_version
.is_64()
{
(0..nsegments)
.map(|_| {
let start: u64 =
bincode::deserialize_from(&mut header_page)?;
let end: u64 =
bincode::deserialize_from(&mut header_page)?;
ensure!(start <= end);
let offset: u64 =
bincode::deserialize_from(&mut header_page)?;
Ok(SegInfoVaNRaw {
address: start..end,
offset,
})
})
.collect::<Result<_>>()?
} else {
(0..nsegments)
.map(|_| {
let start: u32 =
bincode::deserialize_from(&mut header_page)?;
let end: u32 =
bincode::deserialize_from(&mut header_page)?;
ensure!(start <= end);
let offset: u32 =
bincode::deserialize_from(&mut header_page)?;
Ok(SegInfoVaNRaw {
address: start.into()..end.into(),
offset: offset.into(),
})
})
.collect::<Result<_>>()?
};
(u32::from(npages), SegInfoRaw::VaN(seglist))
}
VaVersion::VaX => {
let unknown_always3: u32 =
bincode::deserialize_from(&mut header_page)?;
ensure!(unknown_always3 == 3);
let nsegments: u32 =
bincode::deserialize_from(&mut header_page)?;
let unknown_always2048: u32 =
bincode::deserialize_from(&mut header_page)?;
ensure!(unknown_always2048 == 2048);
let npages: u32 = bincode::deserialize_from(&mut header_page)?;
let seglist: Vec<Range<u64>> = (0..nsegments)
// TODO the reference code uses the magic version, should it use
// the version itself instead?
.map(|_| {
let (start, end) = match header.magic_version {
crate::IDBMagic::IDA0 | crate::IDBMagic::IDA1 => {
let startea: u32 = bincode::deserialize_from(
&mut header_page,
)?;
let endea: u32 = bincode::deserialize_from(
&mut header_page,
)?;
(startea.into(), endea.into())
}
crate::IDBMagic::IDA2 => (
bincode::deserialize_from(&mut header_page)?,
bincode::deserialize_from(&mut header_page)?,
),
};
ensure!(start <= end);
Ok(start..end)
})
.collect::<Result<_>>()?;
(npages, SegInfoRaw::VaX(seglist))
}
};
// make sure the unused values a all zero
ensure!(header_page.iter().all(|b| *b == 0));
// sort segments by address
let mut overlay_check = match &seglist_raw {
SegInfoRaw::VaN(segs) => {
segs.iter().map(|s| s.address.clone()).collect()
}
SegInfoRaw::VaX(segs) => segs.clone(),
};
overlay_check.sort_unstable_by_key(|s| s.start);
// make sure segments don't overlap
let overlap = overlay_check.windows(2).any(|segs| {
let [seg1, seg2] = segs else { unreachable!() };
seg1.end >= seg2.start
});
ensure!(!overlap);
// make sure the data fits the available pages
let required_size: u64 =
overlay_check.iter().map(|s| (s.end - s.start) * 4).sum();
let required_pages =
required_size.div_ceil(u64::try_from(PAGE_SIZE).unwrap());
// TODO if the extra data at the end of the section is identified, review replacing <= with ==
// -1 because the first page is always the header
ensure!(required_pages <= u64::from(npages - 1));
// populated the seglist data using the pages
let seglist = match seglist_raw {
SegInfoRaw::VaN(mut segs) => {
// sort it by disk offset, so we can read one after the other
segs.sort_unstable_by_key(|s| s.offset);
let mut current_offset = u64::try_from(PAGE_SIZE).unwrap();
segs.into_iter()
.map(|seg| {
// skip any gaps
match seg.offset.cmp(¤t_offset) {
std::cmp::Ordering::Less => {
return Err(anyhow!("invalid offset"))
}
std::cmp::Ordering::Greater => {
// TODO can be any deleted sector contains randon data?
// skip intermidiate bytes, also ensuring they are all zeros
ensure_all_bytes_are_zero(
std::io::Read::take(
&mut *input,
seg.offset - current_offset,
),
&mut buf,
)?;
current_offset = seg.offset;
}
std::cmp::Ordering::Equal => {}
}
let len = seg.address.end - seg.address.start;
let (data, _flags) =
split_flags_data(&mut *input, len)?;
current_offset += len * 4;
Ok(SegInfo {
offset: seg.address.start,
data,
_flags,
})
})
.collect::<Result<_>>()?
}
SegInfoRaw::VaX(segs) => {
// the data for the segments are stored sequentialy in disk
segs.into_iter()
.map(|address| {
let (data, _flags) = split_flags_data(
&mut *input,
address.end - address.start,
)?;
Ok(SegInfo {
offset: address.start,
data,
_flags,
})
})
.collect::<Result<_>>()?
}
};
//// ensure the rest of the data (page alignment) is just zeros
//ensure_all_bytes_are_zero(input, &mut buf)?;
// TODO sometimes there some extra data with unknown meaning, maybe it's just a
// deleted segment
ignore_bytes(input, &mut buf)?;
Ok(Self { seglist })
}
}
#[derive(Clone, Debug)]
enum SegInfoRaw {
VaN(Vec<SegInfoVaNRaw>),
VaX(Vec<Range<u64>>),
}
#[derive(Clone, Debug)]
struct SegInfoVaNRaw {
address: Range<u64>,
offset: u64,
}
fn ensure_all_bytes_are_zero(
mut input: impl IdaGenericUnpack,
buf: &mut [u8],
) -> Result<()> {
loop {
match input.read(buf) {
// found EoF
Ok(0) => break,
// read something
Ok(n) => ensure!(&buf[..n].iter().all(|b| *b == 0)),
// ignore interrupts
Err(ref e)
if matches!(e.kind(), std::io::ErrorKind::Interrupted) => {}
Err(e) => return Err(e.into()),
};
}
Ok(())
}
fn ignore_bytes(
mut input: impl IdaGenericUnpack,
buf: &mut [u8],
) -> Result<()> {
loop {
match input.read(buf) {
// found EoF
Ok(0) => break,
// read something
Ok(_n) => {}
// ignore interrupts
Err(ref e)
if matches!(e.kind(), std::io::ErrorKind::Interrupted) => {}
Err(e) => return Err(e.into()),
};
}
Ok(())
}
fn split_flags_data(
mut input: impl IdaGenericUnpack,
len: u64,
) -> Result<(Vec<u8>, Vec<u32>)> {
let len = usize::try_from(len).unwrap();
let mut flags = Vec::with_capacity(len);
let mut data = Vec::with_capacity(len);
for _i in 0..len {
let bytes = input.read_u32()?;
data.push((bytes & 0xFF) as u8);
flags.push(bytes >> 8);
}
Ok((data, flags))
}