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
//! Library to parse stack usage information ([`.stack_sizes`]) produced by LLVM
//!
//! [`.stack_sizes`]: https://llvm.org/docs/CodeGenerator.html#emitting-function-stack-size-information

#![deny(missing_docs)]
#![deny(warnings)]

extern crate byteorder;
extern crate either;
#[macro_use]
extern crate failure;
extern crate leb128;
#[cfg(feature = "tools")]
extern crate rustc_demangle;
extern crate xmas_elf;

use std::{collections::HashMap, io::Cursor, u32};
#[cfg(feature = "tools")]
use std::{fs::File, io::Read, path::Path};

use byteorder::{ReadBytesExt, LE};
use either::Either;
use xmas_elf::{
    sections::{SectionData, SectionHeader},
    symbol_table::{Entry, Type},
    ElfFile,
};

/// Information about a function
#[derive(Debug)]
pub struct Function<'a, A> {
    address: Option<A>,
    names: Vec<&'a str>,
    size: u64,
    stack: Option<u64>,
}

impl<'a, A> Function<'a, A> {
    /// Returns the address of the function
    ///
    /// A value of `None` indicates that this symbol is undefined (dynamically loaded)
    pub fn address(&self) -> Option<A>
    where
        A: Copy,
    {
        self.address
    }

    /// Returns the (mangled) name of the function and its aliases
    pub fn names(&self) -> &[&'a str] {
        &self.names
    }

    /// Returns the size of this subroutine in bytes
    pub fn size(&self) -> u64 {
        self.size
    }

    /// Returns the stack usage of the function in bytes
    pub fn stack(&self) -> Option<u64> {
        self.stack
    }
}

/// Parses an ELF file and returns a list of functions and their stack usage
pub fn analyze(
    elf: &[u8],
) -> Result<Either<Vec<Function<u32>>, Vec<Function<u64>>>, failure::Error> {
    let elf = ElfFile::new(elf).map_err(failure::err_msg)?;

    // address -> ([name], size)
    let mut all_names = HashMap::new();
    let mut undefs = vec![];

    let mut maybe_aliases = HashMap::new();
    let mut is_64_bit = false;
    if let Some(section) = elf.find_section_by_name(".symtab") {
        match section.get_data(&elf).map_err(failure::err_msg)? {
            SectionData::SymbolTable32(entries) => {
                for entry in entries {
                    let ty = entry.get_type();
                    let value = entry.value();
                    let size = entry.size();
                    let name = entry.get_name(&elf).map_err(failure::err_msg)?;
                    if ty == Ok(Type::Func) {
                        if value == 0 && size == 0 {
                            undefs.push(name);
                        } else {
                            all_names
                                .entry(value)
                                .or_insert((vec![], size))
                                .0
                                .push(name);
                        }
                    } else if ty == Ok(Type::NoType) {
                        maybe_aliases.entry(value).or_insert(vec![]).push(name);
                    }
                }
            }

            SectionData::SymbolTable64(entries) => {
                is_64_bit = true;

                for entry in entries {
                    let ty = entry.get_type();
                    let value = entry.value();
                    let size = entry.size();
                    let name = entry.get_name(&elf).map_err(failure::err_msg)?;
                    if ty == Ok(Type::Func) {
                        if value == 0 && size == 0 {
                            undefs.push(name);
                        } else {
                            all_names
                                .entry(value)
                                .or_insert((vec![], size))
                                .0
                                .push(name);
                        }
                    } else if ty == Ok(Type::NoType) {
                        maybe_aliases.entry(value).or_insert(vec![]).push(name);
                    }
                }
            }
            _ => bail!("malformed .symtab section"),
        }
    }

    for (value, alias) in maybe_aliases {
        if let Some((names, _)) = all_names.get_mut(&value) {
            names.extend(alias);
        }
    }

    if let Some(stack_sizes) = elf.find_section_by_name(".stack_sizes") {
        let data = stack_sizes.raw_data(&elf);
        let end = data.len() as u64;
        let mut cursor = Cursor::new(data);

        match stack_sizes {
            SectionHeader::Sh32(..) => {
                let mut funs = vec![];

                while cursor.position() < end {
                    let address = cursor.read_u32::<LE>()?;
                    // NOTE we also try the address plus one because this could be a function in Thumb
                    // mode
                    let (mut names, size) = all_names
                        .remove(&(u64::from(address)))
                        .or_else(|| all_names.remove(&(u64::from(address) + 1)))
                        .expect("UNREACHABLE");
                    let stack = Some(leb128::read::unsigned(&mut cursor)?);

                    names.sort();
                    funs.push(Function {
                        address: Some(address),
                        stack,
                        names,
                        size,
                    });
                }

                funs.sort_by(|a, b| b.stack().cmp(&a.stack()));

                // add functions for which we don't have stack size information
                for (address, (mut names, size)) in all_names {
                    names.sort();

                    funs.push(Function {
                        address: Some(address as u32),
                        stack: None,
                        names,
                        size,
                    });
                }

                if !undefs.is_empty() {
                    funs.push(Function {
                        address: None,
                        stack: None,
                        names: undefs,
                        size: 0,
                    });
                }

                Ok(Either::Left(funs))
            }
            SectionHeader::Sh64(..) => {
                let mut funs = vec![];

                while cursor.position() < end {
                    let address = cursor.read_u64::<LE>()?;
                    // NOTE we also try the address plus one because this could be a function in Thumb
                    // mode
                    let (mut names, size) = all_names
                        .remove(&address)
                        .or_else(|| all_names.remove(&(address + 1)))
                        .expect("UNREACHABLE");
                    let stack = Some(leb128::read::unsigned(&mut cursor)?);

                    names.sort();
                    funs.push(Function {
                        address: Some(address),
                        stack,
                        names,
                        size,
                    });
                }

                funs.sort_by(|a, b| b.stack().cmp(&a.stack()));

                // add functions for which we don't have stack size information
                for (address, (mut names, size)) in all_names {
                    names.sort();

                    funs.push(Function {
                        address: Some(address),
                        stack: None,
                        names,
                        size,
                    });
                }

                if !undefs.is_empty() {
                    funs.push(Function {
                        address: None,
                        stack: None,
                        names: undefs,
                        size: 0,
                    });
                }

                Ok(Either::Right(funs))
            }
        }
    } else if is_64_bit {
        let mut funs = all_names
            .into_iter()
            .map(|(address, (mut names, size))| {
                names.sort();

                Function {
                    address: Some(address),
                    stack: None,
                    names,
                    size,
                }
            })
            .collect::<Vec<_>>();

        if !undefs.is_empty() {
            funs.push(Function {
                address: None,
                stack: None,
                names: undefs,
                size: 0,
            });
        }

        Ok(Either::Right(funs))
    } else {
        let mut funs = all_names
            .into_iter()
            .map(|(address, (mut names, size))| {
                names.sort();
                Function {
                    address: Some(address as u32),
                    stack: None,
                    names,
                    size,
                }
            })
            .collect::<Vec<_>>();

        if !undefs.is_empty() {
            funs.push(Function {
                address: None,
                stack: None,
                names: undefs,
                size: 0,
            });
        }

        Ok(Either::Left(funs))
    }
}

#[cfg(feature = "tools")]
#[doc(hidden)]
pub fn run<P>(path: P) -> Result<(), failure::Error>
where
    P: AsRef<Path>,
{
    let mut bytes = vec![];
    File::open(path)?.read_to_end(&mut bytes)?;

    let funs = analyze(&bytes)?;

    match funs {
        Either::Left(funs) => {
            // 32-bit address space
            println!("address\t\tstack\tname");

            for fun in funs {
                if let (Some(name), Some(stack), Some(addr)) =
                    (fun.names().first(), fun.stack(), fun.address())
                {
                    println!(
                        "{:#010x}\t{}\t{}",
                        addr,
                        stack,
                        rustc_demangle::demangle(name)
                    );
                }
            }
        }
        Either::Right(funs) => {
            // 64-bit address space
            println!("address\t\t\tstack\tname");

            for fun in funs {
                if let (Some(name), Some(stack), Some(addr)) =
                    (fun.names().first(), fun.stack(), fun.address())
                {
                    println!(
                        "{:#018x}\t{}\t{}",
                        addr,
                        stack,
                        rustc_demangle::demangle(name)
                    );
                }
            }
        }
    }

    Ok(())
}