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
prelude! {}
pub mod label;
pub mod loc;
pub mod ord;
mod spec;
pub mod stats;
pub mod string_like;
pub mod sub;
#[cfg(any(test, feature = "server"))]
pub mod gen;
#[cfg(any(test, feature = "server"))]
pub use gen::FilterGen;
pub use label::LabelFilter;
pub use loc::LocFilter;
use ord::OrdFilter;
pub use spec::FilterSpec;
pub use sub::SubFilter;
pub type SizeFilter = OrdFilter<u32>;
pub type LifetimeFilter = OrdFilter<time::Lifetime>;
impl LifetimeFilter {
pub fn apply_at(&self, timestamp: &time::SinceStart, alloc_toc: &time::SinceStart) -> bool {
debug_assert!(alloc_toc <= timestamp);
let lt = (timestamp - alloc_toc).to_lifetime();
self.apply(<)
}
}
pub trait FilterExt<Data>: Sized
where
Data: ?Sized,
{
fn apply(&self, alloc_data: &Data) -> bool;
}
#[derive(Clone, Copy, Debug, Serialize, Deserialize)]
pub enum CmpKind {
Ord(ord::Pred),
Label(label::LabelPred),
Loc(loc::LocPred),
}
impl CmpKind {
pub fn new_ord(kind: ord::Pred) -> Self {
Self::Ord(kind)
}
pub fn new_label(kind: label::LabelPred) -> Self {
Self::Label(kind)
}
pub fn new_loc(kind: loc::LocPred) -> Self {
Self::Loc(kind)
}
}
impl fmt::Display for CmpKind {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
match self {
Self::Ord(kind) => write!(fmt, "{}", kind),
Self::Label(kind) => write!(fmt, "{}", kind),
Self::Loc(kind) => write!(fmt, "{}", kind),
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
pub enum FilterKind {
Size,
Lifetime,
Label,
Loc,
}
impl fmt::Display for FilterKind {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
match self {
Self::Size => write!(fmt, "size"),
Self::Lifetime => write!(fmt, "lifetime"),
Self::Label => write!(fmt, "labels"),
Self::Loc => write!(fmt, "callstack"),
}
}
}
impl FilterKind {
pub fn all() -> Vec<FilterKind> {
base::debug_do! {
match Self::Size {
Self::Size => (),
Self::Lifetime => (),
Self::Label => (),
Self::Loc => (),
}
}
vec![
FilterKind::Size,
FilterKind::Lifetime,
FilterKind::Loc,
]
}
}
#[derive(Debug, Clone)]
pub struct Filters {
catch_all: FilterSpec,
everything: FilterSpec,
filters: Vec<Filter>,
memory: BTMap<uid::Alloc, uid::Filter>,
}
impl Filters {
pub fn new() -> Self {
Filters {
filters: vec![],
catch_all: FilterSpec::new_catch_all(),
everything: FilterSpec::new_everything(),
memory: BTMap::new(),
}
}
pub fn new_with(filters: Vec<Filter>) -> Self {
Filters {
filters,
catch_all: FilterSpec::new_catch_all(),
everything: FilterSpec::new_everything(),
memory: BTMap::new(),
}
}
pub fn catch_all(&self) -> &FilterSpec {
&self.catch_all
}
pub fn everything(&self) -> &FilterSpec {
&self.everything
}
pub fn filters(&self) -> &Vec<Filter> {
&self.filters
}
#[cfg(any(test, feature = "server"))]
pub fn auto_gen(
data: &data::Data,
generator: impl Into<filter::gen::FilterGen>,
) -> Res<(Self, Vec<chart::Chart>)> {
let generator = generator.into();
generator.run(data)
}
pub fn len(&self) -> usize {
self.filters.len()
}
pub fn get_spec_mut(&mut self, uid: Option<uid::Filter>) -> Res<&mut FilterSpec> {
if let Some(uid) = uid {
self.get_mut(uid).map(|(_, filter)| filter.spec_mut())
} else {
Ok(&mut self.catch_all)
}
}
pub fn get_mut(&mut self, uid: uid::Filter) -> Res<(usize, &mut Filter)> {
for (index, filter) in self.filters.iter_mut().enumerate() {
if filter.uid() == uid {
return Ok((index, filter));
}
}
bail!("cannot access filter with unknown UID #{}", uid)
}
pub fn iter(&self) -> impl Iterator<Item = &Filter> {
self.filters.iter()
}
pub fn iter_mut(&mut self) -> impl Iterator<Item = &mut Filter> {
self.filters.iter_mut()
}
fn remember(
memory: &mut BTMap<uid::Alloc, uid::Filter>,
alloc: uid::Alloc,
filter: uid::Filter,
) {
let prev = memory.insert(alloc, filter);
let collision = prev.map(|uid| uid != filter).unwrap_or(false);
if collision {
panic!("filter memory collision")
}
}
pub fn find_match(
&mut self,
timestamp: &time::SinceStart,
alloc: &Alloc,
) -> Option<uid::Filter> {
for filter in &self.filters {
if filter.apply(timestamp, alloc) {
Self::remember(&mut self.memory, alloc.uid().clone(), filter.uid());
return Some(filter.uid());
}
}
None
}
pub fn find_dead_match(&mut self, alloc: &uid::Alloc) -> Option<uid::Filter> {
self.memory.get(alloc).map(|uid| *uid)
}
pub fn reset(&mut self) {
self.memory.clear()
}
pub fn fold<T>(&self, mut init: T, mut fold: impl FnMut(T, uid::Line) -> T) -> T {
init = fold(init, self.everything.uid());
for filter in &self.filters {
init = fold(init, filter.spec().uid());
}
fold(init, self.catch_all.uid())
}
pub fn uid_map<T>(&self, default: T) -> BTMap<uid::Line, T>
where
T: Clone + fmt::Debug + std::cmp::PartialEq,
{
self.fold(BTMap::new(), |mut map, uid| {
let prev = map.insert(uid, default.clone());
debug_assert_eq!(prev, None);
map
})
}
}
impl Filters {
pub fn update(&mut self, msg: msg::to_server::FiltersMsg) -> Res<(msg::to_client::Msgs, bool)> {
use msg::to_server::FiltersMsg::*;
let (res, should_reload) = match msg {
RequestNew => (self.add_new(), false),
RequestNewSub(uid) => (self.add_new_sub(uid), false),
Revert => (self.revert(), false),
UpdateAll {
everything,
filters,
catch_all,
} => (self.update_all(everything, filters, catch_all), true),
};
res.map(|msgs| (msgs, should_reload))
}
pub fn revert(&self) -> Res<msg::to_client::Msgs> {
let catch_all = self.catch_all.clone();
let everything = self.everything.clone();
let filters = self.filters.clone();
Ok(vec![msg::to_client::FiltersMsg::revert(
everything, filters, catch_all,
)])
}
pub fn update_all(
&mut self,
everything: FilterSpec,
filters: Vec<Filter>,
catch_all: FilterSpec,
) -> Res<msg::to_client::Msgs> {
self.catch_all = catch_all;
self.everything = everything;
self.filters = filters;
Ok(vec![])
}
pub fn add_new(&mut self) -> Res<msg::to_client::Msgs> {
let spec = FilterSpec::new(Color::random());
let filter = Filter::new(spec).chain_err(|| "while creating new filter")?;
let msg = msg::to_client::FiltersMsg::add(filter);
Ok(vec![msg])
}
pub fn add_new_sub(&mut self, uid: uid::Filter) -> Res<msg::to_client::Msgs> {
let msg = msg::to_client::FiltersMsg::add_sub(uid, SubFilter::default());
Ok(vec![msg])
}
#[cfg(any(test, feature = "server"))]
pub fn filter_stats(&self) -> Res<stats::AllFilterStats> {
let mut stats = stats::AllFilterStats::new();
let mut registered = 0;
for (_, filter) in &self.memory {
registered += 1;
stats.stats_do((*filter).into(), |stats| stats.inc())
}
let total = data::alloc_count()?;
if registered > total {
bail!(
"inconsistent state, extracted filter stats for {} allocation, \
but allocation count is {}",
registered,
total,
)
}
stats.stats_do(uid::Line::CatchAll, |stats| {
stats.alloc_count = total - registered
});
Ok(stats)
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Filter {
subs: BTMap<uid::SubFilter, SubFilter>,
spec: FilterSpec,
}
impl Filter {
pub fn new(spec: FilterSpec) -> Res<Filter> {
if spec.uid().filter_uid().is_none() {
bail!("trying to construct a filter with no UID")
}
let slf = Self {
subs: BTMap::new(),
spec,
};
Ok(slf)
}
pub fn spec(&self) -> &FilterSpec {
&self.spec
}
pub fn spec_mut(&mut self) -> &mut FilterSpec {
&mut self.spec
}
pub fn name(&self) -> &str {
self.spec().name()
}
pub fn uid(&self) -> uid::Filter {
self.spec()
.uid()
.filter_uid()
.expect("invariant violation, found a filter with no UID")
}
pub fn apply(&self, timestamp: &time::SinceStart, alloc: &Alloc) -> bool {
for filter in self.subs.values() {
if !filter.apply(timestamp, alloc) {
return false;
}
}
true
}
pub fn remove(&mut self, sub_uid: uid::SubFilter) -> Res<()> {
let prev = self.subs.remove(&sub_uid);
if prev.is_none() {
bail!("failed to remove unknown subfilter UID #{}", sub_uid)
}
Ok(())
}
pub fn iter(&self) -> impl Iterator<Item = &SubFilter> {
self.subs.values()
}
pub fn iter_mut(&mut self) -> impl Iterator<Item = &mut SubFilter> {
self.subs.values_mut()
}
pub fn insert(&mut self, sub: impl Into<SubFilter>) -> Res<()> {
let sub = sub.into();
let prev = self.subs.insert(sub.uid(), sub);
if let Some(prev) = prev {
bail!("subfilter UID collision on #{}", prev.uid())
}
Ok(())
}
pub fn replace(&mut self, sub: SubFilter) -> Res<()> {
let uid = sub.uid();
let prev = self.subs.insert(sub.uid(), sub);
if prev.is_none() {
bail!("failed to replace subfilter with unknown UID #{}", uid)
}
Ok(())
}
}