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
#![warn(missing_docs)]
use std::fmt;
use std::io::Read;
use std::iter::FusedIterator;
use std::ops::Deref;
use bytes::Bytes;
use flate2::bufread::ZlibDecoder;
use scroll::{ctx::TryFromCtx, Endian, Pread};
use crate::context::Unreal4Context;
use crate::error::{Unreal4Error, Unreal4ErrorKind};
use crate::logs::Unreal4LogEntry;
#[derive(Clone, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
struct AnsiString(String);
impl AnsiString {
pub fn as_str(&self) -> &str {
&self.0
}
}
impl AsRef<str> for AnsiString {
fn as_ref(&self) -> &str {
&self.0
}
}
impl Deref for AnsiString {
type Target = str;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl fmt::Display for AnsiString {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.0.fmt(f)
}
}
impl TryFromCtx<'_, Endian> for AnsiString {
type Error = scroll::Error;
fn try_from_ctx(data: &[u8], context: Endian) -> Result<(Self, usize), Self::Error> {
let mut offset = 0;
let len = data.gread_with::<u32>(&mut offset, context)?;
let bytes = data.gread_with::<&[u8]>(&mut offset, len as usize)?;
let mut string = String::from_utf8_lossy(bytes).into_owned();
let actual_len = string.trim_end_matches('\0').len();
string.truncate(actual_len);
Ok((Self(string), offset))
}
}
#[allow(dead_code)]
#[derive(Clone, Debug, Pread)]
struct Unreal4Header {
pub directory_name: AnsiString,
pub file_name: AnsiString,
pub uncompressed_size: i32,
pub file_count: i32,
}
#[derive(Clone, Debug)]
struct Unreal4FileMeta {
index: usize,
file_name: AnsiString,
offset: usize,
len: usize,
}
impl TryFromCtx<'_, usize> for Unreal4FileMeta {
type Error = scroll::Error;
fn try_from_ctx(data: &[u8], file_offset: usize) -> Result<(Self, usize), Self::Error> {
let mut offset = 0;
let index = data.gread_with::<i32>(&mut offset, scroll::LE)? as usize;
let file_name = data.gread_with(&mut offset, scroll::LE)?;
let len = data.gread_with::<i32>(&mut offset, scroll::LE)? as usize;
let file_meta = Unreal4FileMeta {
index,
file_name,
offset: file_offset + offset,
len,
};
if len > 0 {
data.gread_with::<&[u8]>(&mut offset, len)?;
}
Ok((file_meta, offset))
}
}
fn gread_files(
bytes: &[u8],
count: usize,
offset: &mut usize,
) -> Result<Vec<Unreal4FileMeta>, Unreal4Error> {
if count > bytes.len() / 12 {
return Err(Unreal4ErrorKind::BadData.into());
}
let mut files = Vec::with_capacity(count);
for _ in 0..count {
let file_offset = *offset;
files.push(bytes.gread_with(offset, file_offset)?);
}
Ok(files)
}
#[derive(Debug)]
pub struct Unreal4Crash {
bytes: Bytes,
header: Unreal4Header,
files: Vec<Unreal4FileMeta>,
}
impl Unreal4Crash {
fn from_bytes(bytes: Bytes) -> Result<Self, Unreal4Error> {
let mut offset = 0;
let (header, files) = if bytes.starts_with(b"CR1") {
offset = 3;
let header = bytes.gread_with::<Unreal4Header>(&mut offset, scroll::LE)?;
let files = gread_files(&bytes, header.file_count as usize, &mut offset)?;
(header, files)
} else {
let file_count = bytes.pread_with::<i32>(bytes.len() - 4, scroll::LE)? as usize;
bytes.gread_with::<Unreal4Header>(&mut offset, scroll::LE)?;
let files = gread_files(&bytes, file_count, &mut offset)?;
let header = bytes.gread_with(&mut offset, scroll::LE)?;
(header, files)
};
if offset != bytes.len() {
return Err(Unreal4ErrorKind::TrailingData.into());
}
Ok(Unreal4Crash {
bytes,
header,
files,
})
}
pub fn parse(slice: &[u8]) -> Result<Self, Unreal4Error> {
Self::parse_with_limit(slice, usize::MAX)
}
pub fn parse_with_limit(slice: &[u8], limit: usize) -> Result<Self, Unreal4Error> {
if slice.is_empty() {
return Err(Unreal4ErrorKind::Empty.into());
}
let mut decompressed = Vec::new();
let decoder = &mut ZlibDecoder::new(slice);
decoder
.take(limit as u64)
.read_to_end(&mut decompressed)
.map_err(|e| Unreal4Error::new(Unreal4ErrorKind::BadCompression, e))?;
if !matches!(decoder.read(&mut [0; 1]), Ok(0)) {
return Err(Unreal4ErrorKind::TooLarge.into());
}
Self::from_bytes(decompressed.into())
}
pub fn name(&self) -> &str {
&self.header.file_name
}
pub fn directory_name(&self) -> &str {
&self.header.directory_name
}
pub fn files(&self) -> Unreal4FileIterator<'_> {
Unreal4FileIterator {
inner: self.files.iter(),
bytes: &self.bytes,
}
}
pub fn file_count(&self) -> usize {
self.files.len()
}
pub fn file_by_index(&self, index: usize) -> Option<Unreal4File> {
self.files().nth(index)
}
pub fn file_by_type(&self, ty: Unreal4FileType) -> Option<Unreal4File> {
self.files().find(|f| f.ty() == ty)
}
pub fn native_crash(&self) -> Option<Unreal4File> {
self.files().find(|f| {
f.ty() == Unreal4FileType::Minidump || f.ty() == Unreal4FileType::AppleCrashReport
})
}
pub fn context(&self) -> Result<Option<Unreal4Context>, Unreal4Error> {
match self.file_by_type(Unreal4FileType::Context) {
Some(file) => Unreal4Context::parse(file.data()).map(Some),
None => Ok(None),
}
}
pub fn logs(&self, limit: usize) -> Result<Vec<Unreal4LogEntry>, Unreal4Error> {
match self.file_by_type(Unreal4FileType::Log) {
Some(file) => Unreal4LogEntry::parse(file.data(), limit),
None => Ok(Vec::new()),
}
}
}
#[non_exhaustive]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Unreal4FileType {
Minidump,
AppleCrashReport,
Log,
Config,
Context,
Unknown,
}
impl Unreal4FileType {
pub fn name(self) -> &'static str {
match self {
Unreal4FileType::Minidump => "minidump",
Unreal4FileType::AppleCrashReport => "applecrashreport",
Unreal4FileType::Log => "log",
Unreal4FileType::Config => "config",
Unreal4FileType::Context => "context",
Unreal4FileType::Unknown => "unknown",
}
}
}
impl fmt::Display for Unreal4FileType {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.name())
}
}
#[derive(Debug)]
pub struct Unreal4File {
index: usize,
file_name: String,
bytes: Bytes,
}
impl Unreal4File {
fn from_meta(meta: &Unreal4FileMeta, bytes: &Bytes) -> Self {
Unreal4File {
index: meta.index,
file_name: meta.file_name.as_str().to_owned(),
bytes: bytes.slice(meta.offset..meta.offset + meta.len),
}
}
pub fn index(&self) -> usize {
self.index
}
pub fn name(&self) -> &str {
&self.file_name
}
pub fn data(&self) -> &[u8] {
&self.bytes
}
pub fn ty(&self) -> Unreal4FileType {
if self.name() == "CrashReportClient.ini" {
Unreal4FileType::Config
} else if self.name() == "CrashContext.runtime-xml" {
Unreal4FileType::Context
} else if self.name().ends_with(".log") {
Unreal4FileType::Log
} else if self.data().starts_with(b"MDMP") {
Unreal4FileType::Minidump
} else if self.data().starts_with(b"Incident Identifier:") {
Unreal4FileType::AppleCrashReport
} else {
Unreal4FileType::Unknown
}
}
}
pub struct Unreal4FileIterator<'a> {
inner: std::slice::Iter<'a, Unreal4FileMeta>,
bytes: &'a Bytes,
}
impl Iterator for Unreal4FileIterator<'_> {
type Item = Unreal4File;
fn next(&mut self) -> Option<Self::Item> {
let meta = self.inner.next()?;
Some(Unreal4File::from_meta(meta, self.bytes))
}
fn size_hint(&self) -> (usize, Option<usize>) {
self.inner.size_hint()
}
fn count(self) -> usize {
self.inner.count()
}
fn nth(&mut self, n: usize) -> Option<Self::Item> {
let meta = self.inner.nth(n)?;
Some(Unreal4File::from_meta(meta, self.bytes))
}
}
impl DoubleEndedIterator for Unreal4FileIterator<'_> {
fn next_back(&mut self) -> Option<Self::Item> {
let meta = self.inner.next_back()?;
Some(Unreal4File::from_meta(meta, self.bytes))
}
}
impl FusedIterator for Unreal4FileIterator<'_> {}
impl ExactSizeIterator for Unreal4FileIterator<'_> {}
#[cfg(test)]
mod tests {
use std::{error::Error, fs::File};
use symbolic_testutils::fixture;
use super::*;
#[test]
fn test_parse_empty_buffer() {
let crash = &[];
let result = Unreal4Crash::parse(crash);
assert!(matches!(
result.expect_err("empty crash").kind(),
Unreal4ErrorKind::Empty
));
}
#[test]
fn test_parse_invalid_input() {
let crash = &[0u8; 1];
let result = Unreal4Crash::parse(crash);
let error = result.expect_err("empty crash");
assert_eq!(error.kind(), Unreal4ErrorKind::BadCompression);
let source = error.source().expect("error source");
assert_eq!(source.to_string(), "corrupt deflate stream");
}
const DECOMPRESSED_SIZE: usize = 440752;
#[test]
fn test_parse_too_large() {
let mut file = File::open(fixture("unreal/unreal_crash")).expect("example file opens");
let mut file_content = Vec::new();
file.read_to_end(&mut file_content).expect("fixture file");
let result = Unreal4Crash::parse_with_limit(&file_content, DECOMPRESSED_SIZE - 1);
let error = result.expect_err("too large");
assert_eq!(error.kind(), Unreal4ErrorKind::TooLarge);
}
#[test]
fn test_parse_fits_exact() {
let mut file = File::open(fixture("unreal/unreal_crash")).expect("example file opens");
let mut file_content = Vec::new();
file.read_to_end(&mut file_content).expect("fixture file");
Unreal4Crash::parse_with_limit(&file_content, DECOMPRESSED_SIZE)
.expect("file fits decompression buffer");
}
}