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
use std::fmt;
use std::str;
use std::mem;
use std::cmp::min;
use std::path::Path;
use std::borrow::Cow;
use std::io::Result;
use std::iter::Peekable;
use std::collections::HashMap;

use uuid::{Uuid, NAMESPACE_DNS};
use regex::bytes::{Regex, CaptureMatches};
use memmap::{Mmap, Protection};

lazy_static! {
    static ref METHOD_RE: Regex = Regex::new(
        r#"(?m)^    (?:(\d+):(\d+):)?([^ ]+) ([^\(]+?)\(([^\)]*?)\) -> ([\S]+)(?:\r?\n|$)"#).unwrap();
    static ref CLASS_LINE_RE: Regex = Regex::new(
        r#"(?m)^([\S]+) -> ([\S]+?):(?:\r?\n|$)"#).unwrap();
    static ref MEMBER_RE: Regex = Regex::new(
        r#"(?m)^    (?:(\d+):(\d+):)?([^ ]+) ([^\(]+?)(?:\(([^\)]*?)\))? -> ([\S]+)(?:\r?\n|$)"#).unwrap();
}


enum Backing<'a> {
    Buf(Cow<'a, [u8]>),
    Mmap(Mmap),
}

/// Represents class mapping information.
#[derive(Clone)]
pub struct Class<'a> {
    alias: &'a [u8],
    class_name: &'a [u8],
    buf: &'a [u8],
}

/// Represents a member of a class.
pub struct MemberInfo<'a> {
    alias: &'a [u8],
    ty: &'a [u8],
    name: &'a [u8],
    args: Option<Vec<&'a [u8]>>,
    lineno_range: Option<(u32, u32)>,
}

/// Represents arguments of a method.
pub struct Args<'a> {
    args: &'a[&'a [u8]],
    idx: usize,
}

/// Represents a view over a mapping text file.
pub struct MappingView<'a> {
    parser: Parser<'a>,
    classes: HashMap<&'a str, Class<'a>>,
}

/// Parses a proguard file.
pub struct Parser<'a> {
    backing: Backing<'a>,
}

impl<'a> MappingView<'a> {
    fn from_parser(parser: Parser<'a>) -> Result<MappingView<'a>> {
        let mut view = MappingView {
            parser: parser,
            classes: HashMap::new(),
        };
        unsafe {
            let iter: ClassIter<'a> = mem::transmute(view.parser.classes());
            for class in iter {
                view.classes.insert(mem::transmute(class.alias()), class);
            }
        }
        Ok(view)
    }

    /// Creates a mapping view from a Cow buffer.
    pub fn from_cow(cow: Cow<'a, [u8]>) -> Result<MappingView<'a>> {
        MappingView::from_parser(Parser::from_cow(cow)?)
    }

    /// Creates a mapping from a borrowed byte slice.
    pub fn from_slice(buffer: &'a [u8]) -> Result<MappingView<'a>> {
        MappingView::from_cow(Cow::Borrowed(buffer))
    }

    /// Creates a mapping from an owned vector.
    pub fn from_vec(buffer: Vec<u8>) -> Result<MappingView<'a>> {
        MappingView::from_cow(Cow::Owned(buffer))
    }

    /// Opens a mapping view from a file on the file system.
    pub fn from_path<P: AsRef<Path>>(path: P) -> Result<MappingView<'a>> {
        MappingView::from_parser(Parser::from_path(path)?)
    }

    /// Returns the UUID of the mapping file.
    pub fn uuid(&self) -> Uuid {
        self.parser.uuid()
    }

    /// Returns `true` if the mapping file contains line information.
    pub fn has_line_info(&self) -> bool {
        self.parser.has_line_info()
    }

    /// Locates a class by an obfuscated alias.
    pub fn find_class<'this>(&'this self, alias: &str) -> Option<&'this Class<'a>> {
        self.classes.get(alias)
    }
}

impl<'a> Class<'a> {
    /// Returns the name of the class.
    pub fn class_name(&self) -> &str {
        str::from_utf8(self.class_name).unwrap_or("<unknown>")
    }

    /// Returns the obfuscated alias of a class.
    pub fn alias(&self) -> &str {
        str::from_utf8(self.alias).unwrap_or("<unknown>")
    }

    /// Looks up a field by an alias.
    pub fn get_field(&'a self, alias: &str) -> Option<MemberInfo<'a>> {
        self.members()
            .filter(|x| !x.is_method() && x.alias() == alias)
            .next()
    }

    /// Looks up all matching methods for a given alias.
    ///
    /// If the line number is supplied as well the return value will
    /// most likely only return a single item if found.
    pub fn get_methods(&'a self, alias: &str, lineno: Option<u32>)
        -> Vec<MemberInfo<'a>>
    {
        let mut rv: Vec<_> = self.members()
            .filter(|x| x.is_method() && x.alias() == alias && x.matches_line(lineno))
            .collect();
        rv.sort_by_key(|x| x.line_diff(lineno));
        rv
    }

    /// Iterates over all members of the class.
    pub fn members<'this>(&'this self) -> MemberIter<'this> {
        let iter = MEMBER_RE.captures_iter(self.buf).peekable();
        MemberIter {
            iter: iter,
        }
    }
}

impl<'a> fmt::Display for Class<'a> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", self.class_name())
    }
}

impl<'a> fmt::Display for MemberInfo<'a> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{} {}", self.type_name(), self.name())?;
        if let Some(args) = self.args() {
            write!(f, "(")?;
            for (idx, arg) in args.enumerate() {
                if idx > 0 {
                    write!(f, ", ")?;
                }
                write!(f, "{}", arg)?;
            }
            write!(f, ")")?;
        }
        Ok(())
    }
}

impl<'a> Iterator for Args<'a> {
    type Item = &'a str;

    fn next(&mut self) -> Option<&'a str> {
        loop {
            if self.idx >= self.args.len() {
                return None;
            }
            self.idx += 1;
            if let Ok(arg) = str::from_utf8(self.args[self.idx - 1]) {
                return Some(arg);
            }
        }
    }
}

/// Iterates over all classes.
pub struct ClassIter<'a> {
    buf: &'a [u8],
    iter: Peekable<CaptureMatches<'static, 'a>>,
}

/// Iterates over all members of a class.
pub struct MemberIter<'a> {
    iter: Peekable<CaptureMatches<'static, 'a>>,
}

impl<'a> Iterator for ClassIter<'a> {
    type Item = Class<'a>;

    fn next(&mut self) -> Option<Class<'a>> {
        if let Some(caps) = self.iter.next() {
            let class_name = caps.get(1).unwrap();
            let buf_start = caps.get(0).unwrap().end();
            let buf_end = if let Some(caps) = self.iter.peek() {
                caps.get(0).unwrap().start()
            } else {
                self.buf.len()
            };
            let alias_match = caps.get(2).unwrap();
            Some(Class {
                alias: alias_match.as_bytes(),
                class_name: class_name.as_bytes(),
                buf: &self.buf[buf_start..buf_end],
            })
        } else {
            None
        }
    }
}

impl<'a> Iterator for MemberIter<'a> {
    type Item = MemberInfo<'a>;

    fn next(&mut self) -> Option<MemberInfo<'a>> {
        if let Some(caps) = self.iter.next() {
            let from_line: u32 = caps.get(1)
                .and_then(|x| str::from_utf8(x.as_bytes()).ok())
                .and_then(|x| x.parse().ok())
                .unwrap_or(0);
            let to_line: u32 = caps.get(2)
                .and_then(|x| str::from_utf8(x.as_bytes()).ok())
                .and_then(|x| x.parse().ok())
                .unwrap_or(0);

            Some(MemberInfo {
                alias: caps.get(6).unwrap().as_bytes(),
                ty: caps.get(3).unwrap().as_bytes(),
                name: caps.get(4).unwrap().as_bytes(),
                args: caps.get(5).map(|x| x.as_bytes().split(|&x| x == b',').collect()),
                lineno_range: if from_line > 0 && to_line > 0 {
                    Some((from_line, to_line))
                } else {
                    None
                },
            })
        } else {
            None
        }
    }
}

impl<'a> Parser<'a> {
    /// Creates a parser from a Cow buffer.
    pub fn from_cow(cow: Cow<'a, [u8]>) -> Result<Parser<'a>> {
        Ok(Parser {
            backing: Backing::Buf(cow),
        })
    }

    /// Creates a parser from a slice.
    pub fn from_slice(buffer: &'a [u8]) -> Result<Parser<'a>> {
        Parser::from_cow(Cow::Borrowed(buffer))
    }

    /// Creates a parser from a vec.
    pub fn from_vec(buffer: Vec<u8>) -> Result<Parser<'a>> {
        Parser::from_cow(Cow::Owned(buffer))
    }

    /// Creates a parser from a path.
    pub fn from_path<P: AsRef<Path>>(path: P) -> Result<Parser<'a>> {
        let mmap = Mmap::open_path(path, Protection::Read)?;
        Ok(Parser {
            backing: Backing::Mmap(mmap),
        })
    }

    /// Calculates the UUID of the mapping file the parser looks at.
    pub fn uuid(&self) -> Uuid {
        let namespace = Uuid::new_v5(&NAMESPACE_DNS, "guardsquare.com");
        // this internally only operates on bytes, so this is safe to do
        Uuid::new_v5(&namespace, unsafe {
            str::from_utf8_unchecked(self.buffer())
        })
    }

    /// Returns `true` if the mapping file contains line information.
    pub fn has_line_info(&self) -> bool {
        let buf = self.buffer();
        for caps in METHOD_RE.captures_iter(buf) {
            if caps.get(1).is_some() {
                return true;
            }
        }

        false
    }

    /// Locates a class by an obfuscated alias.
    pub fn classes<'this>(&'this self) -> ClassIter<'this> {
        let buf = self.buffer();
        let iter = CLASS_LINE_RE.captures_iter(buf).peekable();
        ClassIter {
            buf: buf,
            iter: iter,
        }
    }

    #[inline(always)]
    fn buffer(&self) -> &[u8] {
        match self.backing {
            Backing::Buf(ref buf) => buf,
            Backing::Mmap(ref mmap) => unsafe { mmap.as_slice() }
        }
    }
}

impl<'a> MemberInfo<'a> {
    /// Returns the alias of this member.
    pub fn alias(&self) -> &str {
        str::from_utf8(self.alias).unwrap_or("<unknown>")
    }

    /// Returns the type of this member or return value of method.
    pub fn type_name(&self) -> &str {
        str::from_utf8(self.ty).unwrap_or("<unknown>")
    }

    /// Returns the name of this member.
    pub fn name(&self) -> &str {
        str::from_utf8(self.name).unwrap_or("<unknown>")
    }

    /// Returns the args of this member if it's a method.
    pub fn args(&'a self) -> Option<Args<'a>> {
        self.args.as_ref().map(|args| Args { args: &args[..], idx: 0 })
    }

    /// Returns `true` if this is a method.
    pub fn is_method(&self) -> bool {
        self.args.is_some()
    }

    /// Returns the first line of this member range.
    pub fn first_line(&self) -> u32 {
        self.lineno_range.map(|x| x.0).unwrap_or(0)
    }

    /// Returns the last line of this member range.
    pub fn last_line(&self) -> u32 {
        self.lineno_range.map(|x| x.1).unwrap_or(0)
    }

    fn line_diff(&self, lineno: Option<u32>) -> u32 {
        (min(self.first_line() as i64, self.last_line() as i64) -
         (lineno.unwrap_or(0) as i64)).abs() as u32
    }

    fn matches_line(&self, lineno: Option<u32>) -> bool {
        let lineno = lineno.unwrap_or(0);
        if let Some((first, last)) = self.lineno_range {
            lineno == 0 || (first <= lineno && lineno <= last) || last == 0
        } else {
            true
        }
    }
}