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
|
use std::borrow::Cow;
use std::fmt;
use std::fs::File;
use std::io::{BufRead, Lines, StdinLock, Write};
use std::path::{Path, PathBuf};
use clap::parser::ValuesRef;
use clap::{value_parser, Arg, ArgAction, Command};
use msvc_demangler::DemangleFlags;
use pdb_addr2line::pdb;
fn parse_uint_from_hex_string(string: &str) -> u32 {
if string.len() > 2 && string.starts_with("0x") {
u32::from_str_radix(&string[2..], 16).expect("Failed to parse address")
} else {
u32::from_str_radix(string, 16).expect("Failed to parse address")
}
}
enum Addrs<'a> {
Args(ValuesRef<'a, String>),
Stdin(Lines<StdinLock<'a>>),
}
impl<'a> Iterator for Addrs<'a> {
type Item = u32;
fn next(&mut self) -> Option<u32> {
let text = match *self {
Addrs::Args(ref mut vals) => vals.next().map(Cow::from),
Addrs::Stdin(ref mut lines) => lines.next().map(Result::unwrap).map(Cow::from),
};
text.as_ref()
.map(Cow::as_ref)
.map(parse_uint_from_hex_string)
}
}
fn print_loc(file: &Option<Cow<str>>, line: Option<u32>, basenames: bool, llvm: bool) {
if let Some(file) = file {
let file: &str = file;
let path = if basenames {
Path::new(Path::new(file).file_name().unwrap())
} else {
Path::new(file)
};
print!("{}:", path.display());
if llvm {
print!("{}:0", line.unwrap_or(0));
} else if let Some(line) = line {
print!("{}", line);
} else {
print!("?");
}
println!();
} else if llvm {
println!("??:0:0");
} else {
println!("??:?");
}
}
fn print_function(name: &str, demangle: bool) {
if demangle && name.starts_with('?') {
let flags = DemangleFlags::NO_ACCESS_SPECIFIERS
| DemangleFlags::NO_FUNCTION_RETURNS
| DemangleFlags::NO_MEMBER_TYPE
| DemangleFlags::NO_MS_KEYWORDS
| DemangleFlags::NO_THISTYPE
| DemangleFlags::NO_CLASS_TYPE
| DemangleFlags::SPACE_AFTER_COMMA
| DemangleFlags::HUG_TYPE;
print!(
"{}",
msvc_demangler::demangle(name, flags)
.as_deref()
.unwrap_or(name)
);
} else {
print!("{}", name);
}
}
fn main() {
let matches = Command::new("pdb-addr2line")
.version("0.1")
.about("A fast addr2line port for PDBs")
.args(&[
Arg::new("exe")
.short('e')
.long("exe")
.value_name("filename")
.value_parser(value_parser!(PathBuf))
.help(
"Specify the name of the executable for which addresses should be translated.",
)
.required(true),
Arg::new("sup")
.long("sup")
.value_name("filename")
.help("Path to supplementary object file."),
Arg::new("functions")
.action(ArgAction::SetTrue)
.short('f')
.long("functions")
.help("Display function names as well as file and line number information."),
Arg::new("pretty")
.action(ArgAction::SetTrue)
.short('p')
.long("pretty-print")
.help(
"Make the output more human friendly: each location are printed on \
one line.",
),
Arg::new("inlines")
.action(ArgAction::SetTrue)
.short('i')
.long("inlines")
.help(
"If the address belongs to a function that was inlined, the source \
information for all enclosing scopes back to the first non-inlined \
function will also be printed.",
),
Arg::new("addresses")
.action(ArgAction::SetTrue)
.short('a')
.long("addresses")
.help(
"Display the address before the function name, file and line \
number information.",
),
Arg::new("basenames")
.action(ArgAction::SetTrue)
.short('s')
.long("basenames")
.help("Display only the base of each file name."),
Arg::new("demangle")
.action(ArgAction::SetTrue)
.short('C')
.long("demangle")
.help(
"Demangle function names. \
Specifying a specific demangling style (like GNU addr2line) \
is not supported. (TODO)",
),
Arg::new("llvm")
.action(ArgAction::SetTrue)
.long("llvm")
.help("Display output in the same format as llvm-symbolizer."),
Arg::new("addrs")
.action(ArgAction::Append)
.help("Addresses to use instead of reading from stdin."),
])
.get_matches();
let do_functions = matches.get_flag("functions");
let do_inlines = matches.get_flag("inlines");
let pretty = matches.get_flag("pretty");
let print_addrs = matches.get_flag("addresses");
let basenames = matches.get_flag("basenames");
let demangle = matches.get_flag("demangle");
let llvm = matches.get_flag("llvm");
let path = matches.get_one::<PathBuf>("exe").unwrap();
let file = File::open(path).unwrap();
let map = unsafe { memmap2::MmapOptions::new().map(&file).unwrap() };
let source = Source(map);
let pdb = pdb::PDB::open(source).unwrap();
let context_data = pdb_addr2line::ContextPdbData::try_from_pdb(pdb).unwrap();
let ctx = context_data.make_context().unwrap();
let stdin = std::io::stdin();
let addrs = matches
.get_many("addrs")
.map(Addrs::Args)
.unwrap_or_else(|| Addrs::Stdin(stdin.lock().lines()));
for probe in addrs {
if print_addrs {
if llvm {
print!("0x{:x}", probe);
} else {
print!("0x{:016x}", probe);
}
if pretty {
print!(": ");
} else {
println!();
}
}
if do_functions || do_inlines {
let mut printed_anything = false;
if let Some(frames) = ctx.find_frames(probe).unwrap() {
for (i, frame) in frames.frames.iter().enumerate() {
if pretty && i != 0 {
print!(" (inlined by) ");
}
if do_functions {
if let Some(func) = &frame.function {
print_function(func, demangle);
} else {
print!("??");
}
if pretty {
print!(" at ");
} else {
println!();
}
}
print_loc(&frame.file, frame.line, basenames, llvm);
printed_anything = true;
if !do_inlines {
break;
}
}
}
if !printed_anything {
if do_functions {
print!("??");
if pretty {
print!(" at ");
} else {
println!();
}
}
if llvm {
println!("??:0:0");
} else {
println!("??:?");
}
}
} else {
let frames = ctx.find_frames(probe).unwrap().unwrap();
let frame = &frames.frames[0];
print_loc(&frame.file, frame.line, basenames, llvm);
}
if llvm {
println!();
}
std::io::stdout().flush().unwrap();
}
}
#[derive(Debug)]
struct Source(memmap2::Mmap);
#[derive(Clone)]
struct ReadView {
bytes: Vec<u8>,
}
impl fmt::Debug for ReadView {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "ReadView({} bytes)", self.bytes.len())
}
}
impl pdb::SourceView<'_> for ReadView {
fn as_slice(&self) -> &[u8] {
self.bytes.as_slice()
}
}
impl<'s> pdb::Source<'s> for Source {
fn view(
&mut self,
slices: &[pdb::SourceSlice],
) -> Result<Box<dyn pdb::SourceView<'s> + Send + Sync>, std::io::Error> {
let len = slices.iter().fold(0, |acc, s| acc + s.size);
let mut bytes = Vec::with_capacity(len);
for slice in slices {
bytes.extend_from_slice(&self.0[slice.offset as usize..][..slice.size]);
}
Ok(Box::new(ReadView { bytes }))
}
}
|