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
prelude! {}
use std::{
ffi::OsString,
path::{Path, PathBuf},
thread::sleep,
time::{Duration, SystemTime},
};
pub struct Watcher {
dir: String,
tmp_file: String,
init_file: String,
init_last_modified: Option<SystemTime>,
known_files: BTSet<OsString>,
new_diff_paths: Vec<PathBuf>,
new_diffs: Vec<alloc::Diff>,
buf: String,
}
impl Watcher {
pub fn spawn(target: impl AsRef<Path>, forever: bool) {
let path = target.as_ref();
if path.is_file() {
let path = path.display().to_string();
let _ = std::thread::spawn(move || match Self::ctf_run(path) {
Ok(()) => (),
Err(e) => err::register_fatal(e),
});
} else if path.is_dir() {
let mut watcher = Self::new(target);
log::warn!("running on legacy memthol dump format");
log::warn!("this will probably not work with this version of memthol");
log::warn!("unless the diffs must verify the following invariant:");
log::warn!("- allocations appear ordered by allocation UID");
log::warn!("- no allocation UID is skipped");
log::warn!(
"meaning successive UIDs `uid_i` and `uid_j` \
must be such that `uid_j == uid_i + 1`"
);
let _ = std::thread::spawn(move || match watcher.run(forever) {
Ok(()) => (),
Err(e) => err::register_non_fatal(e.to_pretty()),
});
} else {
err::register_fatal(format!(
"expected dump directory or memtrace CTF file\n\
got `{}` which is neither or a file nor a directory",
path.display()
))
}
}
pub fn ctf_run(target: impl AsRef<Path>) -> Res<()> {
base::new_time_stats! {
struct Prof {
total => "total",
load => "loading",
parse => "parsing",
}
}
let mut prof = Prof::new();
prof.total.start();
let target = target.as_ref();
log::info!("loading ctf file `{}`", target.display());
prof.load.start();
let bytes = {
use std::io::Read;
let mut file = std::fs::OpenOptions::new()
.read(true)
.open(target)
.chain_err(|| format!("while opening ctf file `{}`", target.display()))?;
let len = file
.metadata()
.map(|meta| meta.len() as usize)
.unwrap_or(150_000);
let mut buff = Vec::with_capacity(len);
let data_len = file
.read_to_end(&mut buff)
.chain_err(|| format!("while reading ctf file `{}`", target.display()))?;
super::progress::set_total(data_len)?;
buff
};
prof.load.stop();
let mut factory = data::FullFactory::new(false);
prof.parse.start();
ctf::parse(
&bytes,
&mut factory,
|bytes_progress| {
err::unwrap_register_fatal(super::progress::set_loaded(bytes_progress))
},
|factory, init| {
if factory.data.has_init() {
panic!("live profiling restart is not supported yet")
} else {
factory.data.reset(target, init)
}
},
|factory, builder| err::unwrap_register_fatal(factory.build_new(builder)),
|factory, timestamp, uid| err::unwrap_register_fatal(factory.add_dead(timestamp, uid)),
|factory, timestamp| factory.mark_timestamp(timestamp),
)
.chain_err(|| format!("while parsing ctf file `{}`", target.display()))?;
prof.parse.stop();
factory.fill_stats()?;
super::progress::set_done()?;
prof.all_do(
|| log::info!("done loading ctf file `{}`", target.display()),
|desc, sw| log::info!("| {:>9}: {}", desc, sw),
);
if !Prof::TIME_STATS_ACTIVE {
log::info!("done loading ctf file `{}`", target.display());
}
Ok(())
}
pub fn run(&mut self, forever: bool) -> Res<()> {
crate::data::progress::set_unknown()?;
'first_init: loop {
if let Some(init) = self.try_read_init()? {
let mut data =
super::get_mut().chain_err(|| "while registering the initial state")?;
if data.has_init() {
bail!("live profiling restart is not supported yet")
} else {
data.reset(&self.dir, init)
}
break 'first_init;
} else {
sleep(Duration::from_millis(200));
continue 'first_init;
}
}
let mut just_started = true;
let mut diff_error: Option<err::Error> = None;
loop {
if let Some(init) = self
.try_read_init()
.chain_err(|| "while checking whether the init file of the run has changed")?
{
diff_error = None;
just_started = true;
self.reset_run(init)
.chain_err(|| "while resetting the run after init file was changed")?
}
if let Some(e) = std::mem::replace(&mut diff_error, None) {
bail!(e)
}
let diff_res = self.register_new_diffs(just_started);
just_started = false;
match diff_res {
Ok(true) => {
()
}
Ok(false) => {
sleep(Duration::from_millis(100))
}
Err(e) => {
if forever {
diff_error = Some(e)
} else {
bail!(e)
}
}
}
if !forever {
break Ok(());
}
}
}
}
impl Watcher {
pub fn new(dir: impl AsRef<Path>) -> Self {
let dir = dir.as_ref().display().to_string();
let tmp_file = "tmp.memthol".into();
let init_file = "init.memthol".into();
let init_last_modified = None;
let known_files = BTSet::new();
let new_diff_paths = vec![];
let new_diffs = vec![];
let buf = String::new();
let mut slf = Self {
dir,
tmp_file,
init_file,
init_last_modified,
known_files,
new_diff_paths,
new_diffs,
buf,
};
slf.reset();
slf
}
pub fn reset(&mut self) {
self.known_files.clear();
self.new_diffs.clear();
let is_new = self.known_files.insert((&self.tmp_file).into());
debug_assert!(is_new);
let is_new = self.known_files.insert((&self.init_file).into());
debug_assert!(is_new)
}
pub fn reset_run(&mut self, init: alloc::Init) -> Res<()> {
self.reset();
let mut data = super::get_mut().chain_err(|| "while resetting the data")?;
data.reset(&self.dir, init);
Ok(())
}
pub fn read_content<Out>(
&mut self,
path: impl AsRef<Path>,
f: impl FnOnce(&str) -> Res<Out>,
) -> Res<Out> {
use std::{fs::OpenOptions, io::Read};
debug_assert!(self.buf.is_empty());
let path = path.as_ref();
let mut file_reader = OpenOptions::new().read(true).write(false).open(path)?;
file_reader.read_to_string(&mut self.buf)?;
let res = f(&self.buf);
self.buf.clear();
res
}
}
impl Watcher {
pub fn try_read_init(&mut self) -> Res<Option<alloc::Init>> {
let mut init_path = PathBuf::new();
init_path.push(&self.dir);
init_path.push(&self.init_file);
if !(init_path.exists() && init_path.is_file()) {
return Ok(None);
}
let last_modified = init_path
.metadata()
.chain_err(|| {
format!(
"could not retrieve metadata of init file `{}`",
init_path.to_string_lossy()
)
})?
.modified()
.chain_err(|| {
format!(
"could not retrieve time of last modification of init file`{}`",
init_path.to_string_lossy()
)
})?;
if let Some(lm) = self.init_last_modified.as_mut() {
if last_modified != *lm {
debug_assert! { *lm <= last_modified }
*lm = last_modified
} else {
return Ok(None);
}
} else {
self.init_last_modified = Some(last_modified)
}
self.read_content(init_path, |content| {
if content.is_empty() {
return Ok(None);
} else {
use alloc_data::parser::Parseable;
let init = alloc::Init::parse(content)?;
Ok(Some(init))
}
})
.chain_err(|| format!("while reading content of init file `{}`", self.init_file))
}
}
impl Watcher {
pub fn register_new_diffs(&mut self, update_progress: bool) -> Res<bool> {
debug_assert!(self.new_diffs.is_empty());
let upper_bound = self.gather_new_diffs(None)?;
let new_stuff = upper_bound.is_some();
if new_stuff {
self.gather_new_diffs(upper_bound)?;
if !self.new_diff_paths.is_empty() {
if update_progress {
crate::data::progress::set_total(self.new_diff_paths.len())?;
}
{
let data = super::get().chain_err(|| "while accessing init info from data")?;
let init = data.init.as_ref().ok_or_else(|| {
"trying to parse diffs when no init file has been parsed yet"
})?;
while let Some(diff_path) = self.new_diff_paths.pop() {
let diff = self.load(init, diff_path)?;
if update_progress {
crate::data::progress::inc_loaded()?;
}
self.new_diffs.push(diff);
}
}
self.new_diffs
.sort_by(|diff_1, diff_2| diff_1.time.cmp(&diff_2.time));
for diff in self.new_diffs.drain(0..) {
super::add_diff(diff)?;
}
}
}
data::progress::set_done()?;
Ok(new_stuff)
}
pub fn gather_new_diffs(&mut self, upper_bound: Option<SystemTime>) -> Res<Option<SystemTime>> {
use std::fs::read_dir;
let mut highest_last_modified = None;
let init_last_modified = self
.init_last_modified
.clone()
.ok_or("trying to gather diff file, but the init file has not been processed yet")?;
debug_assert!(upper_bound.is_some() || self.new_diffs.is_empty());
let dir = read_dir(&self.dir)
.chain_err(|| format!("while reading dump directory `{}`", self.dir))?;
for file in dir {
let file = file.chain_err(|| format!("while reading dump directory `{}`", self.dir))?;
let file_type = file.file_type().chain_err(|| {
format!(
"failed to retrieve file/dir information for `{}`",
file.file_name().to_string_lossy()
)
})?;
if !file_type.is_file() {
continue;
}
let file_path = file.path();
let is_new = self.known_files.insert(file.file_name());
if !is_new {
continue;
}
let last_modified = file_path
.metadata()
.chain_err(|| {
format!(
"could not retrieve metadata of file `{}`",
file_path.to_string_lossy()
)
})?
.modified()
.chain_err(|| {
format!(
"could not retrieve time of last modification of init file`{}`",
file_path.to_string_lossy()
)
})?;
if last_modified < init_last_modified
|| upper_bound
.as_ref()
.map(|ubound| &last_modified > ubound)
.unwrap_or(false)
{
if last_modified >= init_last_modified {
let was_there = self.known_files.remove(&file.file_name());
debug_assert!(was_there);
}
continue;
}
highest_last_modified = Some(if let Some(highest) = highest_last_modified {
if highest < last_modified {
last_modified
} else {
highest
}
} else {
last_modified
});
self.new_diff_paths.push(file_path.into())
}
Ok(highest_last_modified)
}
fn load(&mut self, init: &alloc::Init, path: PathBuf) -> Res<alloc::Diff> {
self.read_content(&path, |content| {
use alloc_data::parser::Parseable;
let diff = alloc::Diff::parse_with(content, init)?;
Ok(diff)
})
.chain_err(|| format!("while reading content of file `{}`", path.to_string_lossy()))
}
}