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
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
use crate::debugid_util::debug_id_for_object;
use crate::error::{Context, Error};
use crate::path_mapper::{ExtraPathMapper, PathMapper};
use crate::shared::{
AddressInfo, FileAndPathHelper, FileContents, FileContentsWrapper, FrameDebugInfo,
FramesLookupResult, SymbolInfo,
};
use crate::symbol_map::{
GenericSymbolMap, SymbolMap, SymbolMapDataMidTrait, SymbolMapDataOuterTrait,
SymbolMapInnerWrapper, SymbolMapTrait,
};
use crate::symbol_map_object::{FunctionAddressesComputer, ObjectSymbolMapDataMid};
use crate::{demangle, FileLocation, MappedPath, SourceFilePath};
use debugid::DebugId;
use object::{File, FileKind};
use pdb::PDB;
use pdb_addr2line::pdb;
use regex::Regex;
use std::borrow::Cow;
use std::collections::HashMap;
use std::ops::Deref;
use std::sync::Mutex;
pub async fn load_symbol_map_for_pdb_corresponding_to_binary<
'h,
H: FileAndPathHelper<'h, FL = FL>,
FL: FileLocation,
>(
file_kind: FileKind,
file_contents: &FileContentsWrapper<impl FileContents + 'static>,
file_location: FL,
helper: &'h H,
) -> Result<SymbolMap<FL>, Error> {
use object::Object;
let pe =
object::File::parse(file_contents).map_err(|e| Error::ObjectParseError(file_kind, e))?;
let info = match pe.pdb_info() {
Ok(Some(info)) => info,
_ => return Err(Error::NoDebugInfoInPeBinary(file_location.to_string())),
};
let binary_debug_id = debug_id_for_object(&pe).expect("we checked pdb_info above");
let pdb_path_str = std::str::from_utf8(info.path())
.map_err(|_| Error::PdbPathNotUtf8(file_location.to_string()))?;
let pdb_location = file_location
.location_for_pdb_from_binary(pdb_path_str)
.ok_or(Error::FileLocationRefusedPdbLocation)?;
let pdb_file = helper
.load_file(pdb_location)
.await
.map_err(|e| Error::HelperErrorDuringOpenFile(pdb_path_str.to_string(), e))?;
let symbol_map = get_symbol_map_for_pdb(FileContentsWrapper::new(pdb_file), file_location)?;
if symbol_map.debug_id() != binary_debug_id {
return Err(Error::UnmatchedDebugId(
binary_debug_id,
symbol_map.debug_id(),
));
}
Ok(symbol_map)
}
pub fn get_symbol_map_for_pe<F, FL>(
file_contents: FileContentsWrapper<F>,
file_kind: FileKind,
file_location: FL,
) -> Result<SymbolMap<FL>, Error>
where
F: FileContents + 'static,
FL: FileLocation,
{
let owner = PeSymbolMapData::new(file_contents, file_kind);
let symbol_map = GenericSymbolMap::new(owner)?;
Ok(SymbolMap::new(file_location, Box::new(symbol_map)))
}
struct PeSymbolMapData<T>
where
T: FileContents,
{
file_data: FileContentsWrapper<T>,
file_kind: FileKind,
}
impl<T: FileContents> PeSymbolMapData<T> {
pub fn new(file_data: FileContentsWrapper<T>, file_kind: FileKind) -> Self {
Self {
file_data,
file_kind,
}
}
}
impl<T: FileContents + 'static> SymbolMapDataOuterTrait for PeSymbolMapData<T> {
fn make_symbol_map_data_mid(&self) -> Result<Box<dyn SymbolMapDataMidTrait + '_>, Error> {
let object =
File::parse(&self.file_data).map_err(|e| Error::ObjectParseError(self.file_kind, e))?;
let debug_id = debug_id_for_object(&object)
.ok_or(Error::InvalidInputError("debug ID cannot be read"))?;
let object = ObjectSymbolMapDataMid::new(
object,
None,
PeFunctionAddressesComputer,
&self.file_data,
None,
None,
debug_id,
);
Ok(Box::new(object))
}
}
struct PeFunctionAddressesComputer;
impl<'data> FunctionAddressesComputer<'data> for PeFunctionAddressesComputer {
fn compute_function_addresses<'file, O>(
&'file self,
object_file: &'file O,
) -> (Option<Vec<u32>>, Option<Vec<u32>>)
where
'data: 'file,
O: object::Object<'data, 'file>,
{
use object::ObjectSection;
if let Some(pdata) = object_file
.section_by_name_bytes(b".pdata")
.and_then(|s| s.data().ok())
{
let (s, e) = function_start_and_end_addresses(pdata);
(Some(s), Some(e))
} else {
(None, None)
}
}
}
pub fn is_pdb_file<F: FileContents>(file: &FileContentsWrapper<F>) -> bool {
PDB::open(file).is_ok()
}
struct PdbObject<'data, FC: FileContents + 'static> {
context_data: pdb_addr2line::ContextPdbData<'data, 'data, &'data FileContentsWrapper<FC>>,
debug_id: DebugId,
srcsrv_stream: Option<Box<dyn Deref<Target = [u8]> + 'data>>,
}
impl<'data, FC: FileContents + 'static> SymbolMapDataMidTrait for PdbObject<'data, FC> {
fn make_symbol_map_inner(&self) -> Result<SymbolMapInnerWrapper<'_>, Error> {
let context = self.make_context()?;
let path_mapper = match &self.srcsrv_stream {
Some(srcsrv_stream) => Some(SrcSrvPathMapper::new(srcsrv::SrcSrvStream::parse(
srcsrv_stream.deref(),
)?)),
None => None,
};
let path_mapper = PathMapper::new_with_maybe_extra_mapper(path_mapper);
let symbol_map = PdbSymbolMapInner {
context,
debug_id: self.debug_id,
path_mapper: Mutex::new(path_mapper),
};
Ok(SymbolMapInnerWrapper(Box::new(symbol_map)))
}
}
impl<'data, FC: FileContents + 'static> PdbObject<'data, FC> {
fn make_context<'object>(
&'object self,
) -> Result<Box<dyn PdbAddr2lineContextTrait + 'object>, Error> {
let context = self.context_data.make_context().context("make_context()")?;
Ok(Box::new(context))
}
}
trait PdbAddr2lineContextTrait {
fn find_frames(
&self,
probe: u32,
) -> Result<Option<pdb_addr2line::FunctionFrames>, pdb_addr2line::Error>;
fn function_count(&self) -> usize;
fn functions(&self) -> Box<dyn Iterator<Item = pdb_addr2line::Function> + '_>;
}
impl<'a, 's> PdbAddr2lineContextTrait for pdb_addr2line::Context<'a, 's> {
fn find_frames(
&self,
probe: u32,
) -> Result<Option<pdb_addr2line::FunctionFrames>, pdb_addr2line::Error> {
self.find_frames(probe)
}
fn function_count(&self) -> usize {
self.function_count()
}
fn functions(&self) -> Box<dyn Iterator<Item = pdb_addr2line::Function> + '_> {
Box::new(self.functions())
}
}
struct PdbSymbolMapInner<'object> {
context: Box<dyn PdbAddr2lineContextTrait + 'object>,
debug_id: DebugId,
path_mapper: Mutex<PathMapper<SrcSrvPathMapper<'object>>>,
}
impl<'object> SymbolMapTrait for PdbSymbolMapInner<'object> {
fn debug_id(&self) -> DebugId {
self.debug_id
}
fn symbol_count(&self) -> usize {
self.context.function_count()
}
fn iter_symbols(&self) -> Box<dyn Iterator<Item = (u32, Cow<'_, str>)> + '_> {
let iter = self.context.functions().map(|f| {
let start_rva = f.start_rva;
(
start_rva,
Cow::Owned(f.name.unwrap_or_else(|| format!("fun_{:x}", start_rva))),
)
});
Box::new(iter)
}
fn lookup(&self, address: u32) -> Option<AddressInfo> {
let function_frames = self.context.find_frames(address).ok()??;
let symbol_address = function_frames.start_rva;
let symbol_name = match &function_frames.frames.last().unwrap().function {
Some(name) => demangle::demangle_any(name),
None => "unknown".to_string(),
};
let function_size = function_frames
.end_rva
.map(|end_rva| end_rva - function_frames.start_rva);
let symbol = SymbolInfo {
address: symbol_address,
size: function_size,
name: symbol_name,
};
let frames = if has_debug_info(&function_frames) {
let mut path_mapper = self.path_mapper.lock().unwrap();
let mut map_path = |path: Cow<str>| {
let mapped_path = path_mapper.map_path(&path);
SourceFilePath::new(path.into_owned(), mapped_path)
};
let frames: Vec<_> = function_frames
.frames
.into_iter()
.map(|frame| FrameDebugInfo {
function: frame.function,
file_path: frame.file.map(&mut map_path),
line_number: frame.line,
})
.collect();
FramesLookupResult::Available(frames)
} else {
FramesLookupResult::Unavailable
};
Some(AddressInfo { symbol, frames })
}
}
fn box_stream<'data, T>(stream: T) -> Box<dyn Deref<Target = [u8]> + 'data>
where
T: Deref<Target = [u8]> + 'data,
{
Box::new(stream)
}
struct PdbSymbolData<T: FileContents + 'static>(FileContentsWrapper<T>);
impl<T: FileContents + 'static> SymbolMapDataOuterTrait for PdbSymbolData<T> {
fn make_symbol_map_data_mid(&self) -> Result<Box<dyn SymbolMapDataMidTrait + '_>, Error> {
let mut pdb = PDB::open(&self.0)?;
let info = pdb.pdb_information().context("pdb_information")?;
let dbi = pdb.debug_information()?;
let age = dbi.age().unwrap_or(info.age);
let debug_id = DebugId::from_parts(info.guid, age);
let srcsrv_stream = match pdb.named_stream(b"srcsrv") {
Ok(stream) => Some(box_stream(stream)),
Err(pdb::Error::StreamNameNotFound | pdb::Error::StreamNotFound(_)) => None,
Err(e) => return Err(Error::PdbError("pdb.named_stream(srcsrv)", e)),
};
let context_data = pdb_addr2line::ContextPdbData::try_from_pdb(pdb)
.context("ContextConstructionData::try_from_pdb")?;
Ok(Box::new(PdbObject {
context_data,
debug_id,
srcsrv_stream,
}))
}
}
pub fn get_symbol_map_for_pdb<F, FL>(
file_contents: FileContentsWrapper<F>,
debug_file_location: FL,
) -> Result<SymbolMap<FL>, Error>
where
F: FileContents + 'static,
FL: FileLocation,
{
let symbol_map = GenericSymbolMap::new(PdbSymbolData(file_contents))?;
Ok(SymbolMap::new(debug_file_location, Box::new(symbol_map)))
}
struct SrcSrvPathMapper<'a> {
srcsrv_stream: srcsrv::SrcSrvStream<'a>,
cache: HashMap<String, Option<MappedPath>>,
github_regex: Regex,
hg_regex: Regex,
s3_regex: Regex,
gitiles_regex: Regex,
command_is_file_download_with_url_in_var4_and_uncompress_function_in_var5: bool,
}
impl<'a> ExtraPathMapper for SrcSrvPathMapper<'a> {
fn map_path(&mut self, path: &str) -> Option<MappedPath> {
if let Some(value) = self.cache.get(path) {
return value.clone();
}
let value = match self
.srcsrv_stream
.source_and_raw_var_values_for_path(path, "C:\\Dummy")
{
Ok(Some((srcsrv::SourceRetrievalMethod::Download { url }, _map))) => {
self.url_to_mapped_path(&url)
}
Ok(Some((srcsrv::SourceRetrievalMethod::ExecuteCommand { .. }, map))) => {
self.gitiles_to_mapped_path(&map)
}
_ => None,
};
self.cache.insert(path.to_string(), value.clone());
value
}
}
impl<'a> SrcSrvPathMapper<'a> {
pub fn new(srcsrv_stream: srcsrv::SrcSrvStream<'a>) -> Self {
let command_is_file_download_with_url_in_var4_and_uncompress_function_in_var5 =
Self::matches_chrome_gitiles_workaround(&srcsrv_stream);
SrcSrvPathMapper {
srcsrv_stream,
cache: HashMap::new(),
github_regex: Regex::new(r"^https://raw\.githubusercontent\.com/(?P<repo>[^/]+/[^/]+)/(?P<rev>[^/]+)/(?P<path>.*)$").unwrap(),
hg_regex: Regex::new(r"^https://(?P<repo>hg\..+)/raw-file/(?P<rev>[0-9a-f]+)/(?P<path>.*)$").unwrap(),
s3_regex: Regex::new(r"^https://(?P<bucket>[^/]+).s3.amazonaws.com/(?P<digest>[^/]+)/(?P<path>.*)$").unwrap(),
gitiles_regex: Regex::new(r"^https://(?P<repo>.+)\.git/\+/(?P<rev>[^/]+)/(?P<path>.*)\?format=TEXT$").unwrap(),
command_is_file_download_with_url_in_var4_and_uncompress_function_in_var5,
}
}
fn matches_chrome_gitiles_workaround(srcsrv_stream: &srcsrv::SrcSrvStream<'a>) -> bool {
let cmd = srcsrv_stream.get_raw_var("SRC_EXTRACT_CMD");
srcsrv_stream.get_raw_var("SRCSRVCMD") == Some("%SRC_EXTRACT_CMD%")
&& (cmd
== Some(
r#"cmd /c "mkdir "%SRC_EXTRACT_TARGET_DIR%" & python3 -c "import urllib.request, base64;url = \"%var4%\";u = urllib.request.urlopen(url);open(r\"%SRC_EXTRACT_TARGET%\", \"wb\").write(%var5%(u.read()))""#,
)
|| cmd
== Some(
r#"SRC_EXTRACT_CMD=cmd /c "mkdir "%SRC_EXTRACT_TARGET_DIR%" & python3 -c "import urllib.request, base64;url = \"%var4%\";u = urllib.request.urlopen(url);open(r\"%SRC_EXTRACT_TARGET%\", \"wb\").write(%var5%(u.read()))""#,
))
}
fn gitiles_to_mapped_path(&self, map: &HashMap<String, String>) -> Option<MappedPath> {
if !self.command_is_file_download_with_url_in_var4_and_uncompress_function_in_var5 {
return None;
}
if map.get("var5").map(String::as_str) != Some("base64.b64decode") {
return None;
}
let url = map.get("var4")?;
let captures = self.gitiles_regex.captures(url)?;
let repo = captures.name("repo").unwrap().as_str().to_owned();
let path = captures.name("path").unwrap().as_str().to_owned();
let rev = captures.name("rev").unwrap().as_str().to_owned();
Some(MappedPath::Git { repo, path, rev })
}
fn url_to_mapped_path(&self, url: &str) -> Option<MappedPath> {
if let Some(captures) = self.github_regex.captures(url) {
let repo = captures.name("repo").unwrap().as_str().to_owned();
let path = captures.name("path").unwrap().as_str().to_owned();
let rev = captures.name("rev").unwrap().as_str().to_owned();
Some(MappedPath::Git { repo, path, rev })
} else if let Some(captures) = self.hg_regex.captures(url) {
let repo = captures.name("repo").unwrap().as_str().to_owned();
let path = captures.name("path").unwrap().as_str().to_owned();
let rev = captures.name("rev").unwrap().as_str().to_owned();
Some(MappedPath::Hg { repo, path, rev })
} else if let Some(captures) = self.s3_regex.captures(url) {
let bucket = captures.name("bucket").unwrap().as_str().to_owned();
let digest = captures.name("digest").unwrap().as_str().to_owned();
let path = captures.name("path").unwrap().as_str().to_owned();
Some(MappedPath::S3 {
bucket,
digest,
path,
})
} else {
None
}
}
}
fn has_debug_info(func: &pdb_addr2line::FunctionFrames) -> bool {
if func.frames.len() > 1 {
true
} else if func.frames.is_empty() {
false
} else {
func.frames[0].file.is_some() || func.frames[0].line.is_some()
}
}
#[derive(Clone)]
struct ReadView {
bytes: Vec<u8>,
}
impl std::fmt::Debug for ReadView {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::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, F: FileContents> pdb::Source<'s> for &'s FileContentsWrapper<F> {
fn view(
&mut self,
slices: &[pdb::SourceSlice],
) -> std::result::Result<Box<dyn pdb::SourceView<'s>>, 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 {
self.read_bytes_into(&mut bytes, slice.offset, slice.size)
.map_err(|e| std::io::Error::new(std::io::ErrorKind::Other, e))?;
}
Ok(Box::new(ReadView { bytes }))
}
}
fn function_start_and_end_addresses(pdata: &[u8]) -> (Vec<u32>, Vec<u32>) {
let mut start_addresses = Vec::new();
let mut end_addresses = Vec::new();
for entry in pdata.chunks_exact(3 * std::mem::size_of::<u32>()) {
let start_address = u32::from_le_bytes([entry[0], entry[1], entry[2], entry[3]]);
let end_address = u32::from_le_bytes([entry[4], entry[5], entry[6], entry[7]]);
start_addresses.push(start_address);
end_addresses.push(end_address);
}
(start_addresses, end_addresses)
}