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
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
use crate::ProfilingAgent;
use anyhow::Result;
use object::{Object, ObjectSection};
use scroll::{IOwrite, SizeWith, NATIVE};
use serde::{Deserialize, Serialize};
use std::fmt::Debug;
use std::fs::{File, OpenOptions};
use std::io;
use std::io::Write;
use std::os::unix::prelude::*;
use std::ptr;
use std::sync::Mutex;
use std::{borrow, mem, process};
use target_lexicon::Architecture;
use wasmtime_environ::entity::PrimaryMap;
use wasmtime_environ::wasm::DefinedFuncIndex;
use wasmtime_environ::Module;
use wasmtime_runtime::VMFunctionBody;
use object::elf;
#[repr(u32)]
pub enum RecordId {
JitCodeLoad = 0,
_JitCodeMove = 1,
JitCodeDebugInfo = 2,
_JitCodeClose = 3,
_JitCodeUnwindingInfo = 4,
}
#[derive(Serialize, Deserialize, Debug, Default, Clone, Copy, IOwrite, SizeWith)]
#[repr(C)]
pub struct RecordHeader {
id: u32,
record_size: u32,
timestamp: u64,
}
#[derive(Serialize, Deserialize, Debug, Default, Clone, Copy, IOwrite, SizeWith)]
#[repr(C)]
pub struct CodeLoadRecord {
header: RecordHeader,
pid: u32,
tid: u32,
virtual_address: u64,
address: u64,
size: u64,
index: u64,
}
#[derive(Serialize, Deserialize, Debug, Default)]
#[repr(C)]
pub struct DebugEntry {
address: u64,
line: u32,
discriminator: u32,
filename: String,
}
#[derive(Serialize, Deserialize, Debug, Default, Clone, Copy, IOwrite, SizeWith)]
#[repr(C)]
pub struct DebugInfoRecord {
header: RecordHeader,
address: u64,
count: u64,
}
#[derive(Serialize, Deserialize, Debug, Default, IOwrite, SizeWith)]
#[repr(C)]
pub struct FileHeader {
magic: u32,
version: u32,
size: u32,
e_machine: u32,
pad1: u32,
pid: u32,
timestamp: u64,
flags: u64,
}
pub struct JitDumpAgent {
state: Mutex<State>,
}
struct State {
jitdump_file: File,
map_addr: usize,
code_index: u64,
dump_funcs: bool,
}
impl JitDumpAgent {
pub fn new() -> Result<Self> {
let filename = format!("./jit-{}.dump", process::id());
let jitdump_file = OpenOptions::new()
.read(true)
.write(true)
.create(true)
.truncate(true)
.open(&filename)?;
let map_addr = unsafe {
let ptr = libc::mmap(
ptr::null_mut(),
libc::sysconf(libc::_SC_PAGESIZE) as usize,
libc::PROT_EXEC | libc::PROT_READ,
libc::MAP_PRIVATE,
jitdump_file.as_raw_fd(),
0,
);
if ptr == libc::MAP_FAILED {
return Err(io::Error::last_os_error().into());
}
ptr as usize
};
let mut state = State {
jitdump_file,
map_addr,
code_index: 0,
dump_funcs: true,
};
state.write_file_header()?;
Ok(JitDumpAgent {
state: Mutex::new(state),
})
}
}
impl ProfilingAgent for JitDumpAgent {
fn module_load(
&self,
module: &Module,
functions: &PrimaryMap<DefinedFuncIndex, *mut [VMFunctionBody]>,
dbg_image: Option<&[u8]>,
) {
self.state
.lock()
.unwrap()
.module_load(module, functions, dbg_image);
}
}
impl State {
fn get_time_stamp(&self) -> u64 {
unsafe {
let mut ts = mem::MaybeUninit::zeroed();
assert_eq!(
libc::clock_gettime(libc::CLOCK_MONOTONIC, ts.as_mut_ptr()),
0
);
let ts = ts.assume_init();
(ts.tv_sec * 1_000_000_000 + ts.tv_nsec) as u64
}
}
fn get_e_machine(&self) -> u32 {
match target_lexicon::HOST.architecture {
Architecture::X86_64 => elf::EM_X86_64 as u32,
Architecture::X86_32(_) => elf::EM_386 as u32,
Architecture::Arm(_) => elf::EM_ARM as u32,
Architecture::Aarch64(_) => elf::EM_AARCH64 as u32,
_ => unimplemented!("unrecognized architecture"),
}
}
fn write_file_header(&mut self) -> Result<()> {
let header = FileHeader {
timestamp: self.get_time_stamp(),
e_machine: self.get_e_machine(),
magic: 0x4A695444,
version: 1,
size: mem::size_of::<FileHeader>() as u32,
pad1: 0,
pid: process::id(),
flags: 0,
};
self.jitdump_file.iowrite_with(header, NATIVE)?;
Ok(())
}
fn write_code_load_record(
&mut self,
record_name: &str,
cl_record: CodeLoadRecord,
code_buffer: &[u8],
) -> Result<()> {
self.jitdump_file.iowrite_with(cl_record, NATIVE)?;
self.jitdump_file.write_all(record_name.as_bytes())?;
self.jitdump_file.write_all(b"\0")?;
self.jitdump_file.write_all(code_buffer)?;
Ok(())
}
fn write_debug_info_record(&mut self, dir_record: DebugInfoRecord) -> Result<()> {
self.jitdump_file.iowrite_with(dir_record, NATIVE)?;
Ok(())
}
fn write_debug_info_entries(&mut self, die_entries: Vec<DebugEntry>) -> Result<()> {
for entry in die_entries.iter() {
self.jitdump_file.iowrite_with(entry.address, NATIVE)?;
self.jitdump_file.iowrite_with(entry.line, NATIVE)?;
self.jitdump_file
.iowrite_with(entry.discriminator, NATIVE)?;
self.jitdump_file.write_all(entry.filename.as_bytes())?;
self.jitdump_file.write_all(b"\0")?;
}
Ok(())
}
pub fn module_load(
&mut self,
module: &Module,
functions: &PrimaryMap<DefinedFuncIndex, *mut [VMFunctionBody]>,
dbg_image: Option<&[u8]>,
) -> () {
let pid = process::id();
let tid = pid;
for (idx, func) in functions.iter() {
let (addr, len) = unsafe { ((**func).as_ptr() as *const u8, (**func).len()) };
if let Some(img) = &dbg_image {
if let Err(err) = self.dump_from_debug_image(img, "wasm", addr, len, pid, tid) {
println!(
"Jitdump: module_load failed dumping from debug image: {:?}\n",
err
);
}
} else {
let timestamp = self.get_time_stamp();
let name = super::debug_name(module, idx);
self.dump_code_load_record(&name, addr, len, timestamp, pid, tid);
}
}
}
fn dump_code_load_record(
&mut self,
method_name: &str,
addr: *const u8,
len: usize,
timestamp: u64,
pid: u32,
tid: u32,
) -> () {
let name_len = method_name.len() + 1;
let size_limit = mem::size_of::<CodeLoadRecord>();
let rh = RecordHeader {
id: RecordId::JitCodeLoad as u32,
record_size: size_limit as u32 + name_len as u32 + len as u32,
timestamp: timestamp,
};
let clr = CodeLoadRecord {
header: rh,
pid: pid,
tid: tid,
virtual_address: addr as u64,
address: addr as u64,
size: len as u64,
index: self.code_index,
};
self.code_index += 1;
unsafe {
let code_buffer: &[u8] = std::slice::from_raw_parts(addr, len);
if let Err(err) = self.write_code_load_record(method_name, clr, code_buffer) {
println!("Jitdump: write_code_load_failed_record failed: {:?}\n", err);
}
}
}
pub fn dump_from_debug_image(
&mut self,
dbg_image: &[u8],
module_name: &str,
addr: *const u8,
len: usize,
pid: u32,
tid: u32,
) -> Result<()> {
let file = object::File::parse(&dbg_image).unwrap();
let endian = if file.is_little_endian() {
gimli::RunTimeEndian::Little
} else {
gimli::RunTimeEndian::Big
};
let load_section = |id: gimli::SectionId| -> Result<borrow::Cow<[u8]>> {
if let Some(section) = file.section_by_name(id.name()) {
Ok(section.data()?.into())
} else {
Ok((&[] as &[u8]).into())
}
};
let load_section_sup = |_| Ok(borrow::Cow::Borrowed(&[][..]));
let dwarf_cow = gimli::Dwarf::load(&load_section, &load_section_sup)?;
let borrow_section: &dyn for<'a> Fn(
&'a borrow::Cow<[u8]>,
)
-> gimli::EndianSlice<'a, gimli::RunTimeEndian> =
&|section| gimli::EndianSlice::new(&*section, endian);
let dwarf = dwarf_cow.borrow(&borrow_section);
let mut iter = dwarf.units();
while let Some(header) = iter.next()? {
let unit = match dwarf.unit(header) {
Ok(unit) => unit,
Err(_err) => {
return Ok(());
}
};
self.dump_entries(unit, &dwarf, module_name, addr, len, pid, tid)?;
break;
}
if !self.dump_funcs {
let timestamp = self.get_time_stamp();
self.dump_code_load_record(module_name, addr, len, timestamp, pid, tid);
}
Ok(())
}
fn dump_entries<R: Reader>(
&mut self,
unit: gimli::Unit<R>,
dwarf: &gimli::Dwarf<R>,
module_name: &str,
addr: *const u8,
len: usize,
pid: u32,
tid: u32,
) -> Result<()> {
let mut depth = 0;
let mut entries = unit.entries();
while let Some((delta_depth, entry)) = entries.next_dfs()? {
if self.dump_funcs {
let record_header = RecordHeader {
id: RecordId::JitCodeLoad as u32,
record_size: 0,
timestamp: 0,
};
let mut clr = CodeLoadRecord {
header: record_header,
pid: pid,
tid: tid,
virtual_address: 0,
address: 0,
size: 0,
index: 0,
};
let mut clr_name: String = String::from(module_name);
let mut get_debug_entry = false;
depth += delta_depth;
assert!(depth >= 0);
if entry.tag() == gimli::constants::DW_TAG_subprogram {
get_debug_entry = true;
let mut attrs = entry.attrs();
while let Some(attr) = attrs.next()? {
if let Some(n) = attr.name().static_string() {
if n == "DW_AT_low_pc" {
clr.address = match attr.value() {
gimli::AttributeValue::Addr(address) => address,
_ => 0,
};
clr.virtual_address = clr.address;
} else if n == "DW_AT_high_pc" {
clr.size = match attr.value() {
gimli::AttributeValue::Udata(data) => data,
_ => 0,
};
} else if n == "DW_AT_name" {
clr_name = match attr.value() {
gimli::AttributeValue::DebugStrRef(offset) => {
if let Ok(s) = dwarf.debug_str.get_str(offset) {
clr_name.push_str("::");
clr_name.push_str(&s.to_string_lossy()?);
clr_name
} else {
clr_name.push_str("::");
clr_name.push_str("?");
clr_name
}
}
_ => {
clr_name.push_str("??");
clr_name
}
};
}
}
}
}
if get_debug_entry {
if clr.address == 0 {
continue;
}
if clr_name == "?" {
continue;
}
if clr.address == 0 || clr.size == 0 {
clr.address = addr as u64;
clr.virtual_address = addr as u64;
clr.size = len as u64;
}
clr.header.record_size = mem::size_of::<CodeLoadRecord>() as u32
+ (clr_name.len() + 1) as u32
+ clr.size as u32;
clr.index = self.code_index;
self.code_index += 1;
self.dump_debug_info(&unit, &dwarf, clr.address, clr.size, None)?;
clr.header.timestamp = self.get_time_stamp();
unsafe {
let code_buffer: &[u8] =
std::slice::from_raw_parts(clr.address as *const u8, clr.size as usize);
let _ = self.write_code_load_record(&clr_name, clr, code_buffer);
}
}
} else {
let mut func_name: String = String::from("?");
let mut func_addr = 0;
let mut func_size = 0;
let mut get_debug_entry = false;
depth += delta_depth;
assert!(depth >= 0);
if entry.tag() == gimli::constants::DW_TAG_subprogram {
get_debug_entry = true;
let mut attrs = entry.attrs();
while let Some(attr) = attrs.next()? {
if let Some(n) = attr.name().static_string() {
if n == "DW_AT_low_pc" {
func_addr = match attr.value() {
gimli::AttributeValue::Addr(address) => address,
_ => 0,
};
} else if n == "DW_AT_high_pc" {
func_size = match attr.value() {
gimli::AttributeValue::Udata(data) => data,
_ => 0,
};
} else if n == "DW_AT_name" {
func_name = match attr.value() {
gimli::AttributeValue::DebugStrRef(offset) => {
if let Ok(s) = dwarf.debug_str.get_str(offset) {
func_name.clear();
func_name.push_str(&s.to_string_lossy()?);
func_name
} else {
func_name.push_str("?");
func_name
}
}
_ => {
func_name.push_str("??");
func_name
}
};
}
}
}
}
if get_debug_entry {
if func_addr == 0 {
continue;
}
if func_name == "?" {
continue;
}
self.dump_debug_info(
&unit,
&dwarf,
func_addr,
func_size,
Some(func_name.as_str()),
)?;
}
}
}
Ok(())
}
fn dump_debug_info<R: Reader>(
&mut self,
unit: &gimli::Unit<R>,
dwarf: &gimli::Dwarf<R>,
address: u64,
size: u64,
file_suffix: Option<&str>,
) -> Result<()> {
let timestamp = self.get_time_stamp();
if let Some(program) = unit.line_program.clone() {
let mut debug_info_record = DebugInfoRecord {
header: RecordHeader {
id: RecordId::JitCodeDebugInfo as u32,
record_size: 0,
timestamp: timestamp,
},
address: address,
count: 0,
};
let mut debug_entries = Vec::new();
let mut debug_entries_total_filenames_len = 0;
let mut rows = program.rows();
while let Some((header, row)) = rows.next_row()? {
let row_file_index = row.file_index() - 1;
let myfile = dwarf
.attr_string(
&unit,
header.file_names()[row_file_index as usize].path_name(),
)
.unwrap();
let filename = myfile.to_string_lossy()?;
let line = row.line().unwrap_or(0);
let column = match row.column() {
gimli::ColumnType::Column(column) => column,
gimli::ColumnType::LeftEdge => 0,
};
if (row.address() < address) || (row.address() > (address + size)) {
continue;
}
let mut debug_entry = DebugEntry {
address: row.address(),
line: line as u32,
discriminator: column as u32,
filename: filename.to_string(),
};
if let Some(suffix) = file_suffix {
debug_entry.filename.push_str("::");
debug_entry.filename.push_str(suffix);
}
debug_entries_total_filenames_len += debug_entry.filename.len() + 1;
debug_entries.push(debug_entry);
}
debug_info_record.count = debug_entries.len() as u64;
let debug_entries_size = (debug_info_record.count
* (mem::size_of::<DebugEntry>() as u64 - mem::size_of::<String>() as u64))
+ debug_entries_total_filenames_len as u64;
debug_info_record.header.record_size =
mem::size_of::<DebugInfoRecord>() as u32 + debug_entries_size as u32;
let _ = self.write_debug_info_record(debug_info_record);
let _ = self.write_debug_info_entries(debug_entries);
}
Ok(())
}
}
impl Drop for State {
fn drop(&mut self) {
unsafe {
libc::munmap(
self.map_addr as *mut _,
libc::sysconf(libc::_SC_PAGESIZE) as usize,
);
}
}
}
trait Reader: gimli::Reader<Offset = usize> + Send + Sync {}
impl<'input, Endian> Reader for gimli::EndianSlice<'input, Endian> where
Endian: gimli::Endianity + Send + Sync
{
}