-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdh_view.js
More file actions
1557 lines (1350 loc) · 50.6 KB
/
dh_view.js
File metadata and controls
1557 lines (1350 loc) · 50.6 KB
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
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//--------------------------------------------------------------------*/
//--- DHAT: a Dynamic Heap Analysis Tool dh_view.js ---*/
//--------------------------------------------------------------------*/
/*
This file is part of DHAT, a Valgrind tool for profiling the
heap usage of programs.
Copyright (C) 2018 Mozilla Foundation
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, see <http://www.gnu.org/licenses/>.
The GNU General Public License is contained in the file COPYING.
*/
/*
Parts of this file are derived from Firefox, copyright Mozilla Foundation,
and may be redistributed under the terms of the Mozilla Public License
Version 2.0, as well as under the license of this project. A copy of the
Mozilla Public License Version 2.0 is available at at
https://www.mozilla.org/en-US/MPL/2.0/.
*/
// Test this file by loading dh_view.html?test=1. That runs the tests in
// dh_test.js and gives pass/fail indicators.
"use strict";
//------------------------------------------------------------//
//--- Globals ---//
//------------------------------------------------------------//
// Important HTML elements.
let gInput;
let gSelect;
let gHeaderDiv, gTestingDiv, gMainDiv, gLegendDiv, gTimingsDiv;
// The name of the loaded file.
let gFilename;
// The object extracted from the JSON input.
let gData = {};
// The root of the radix tree build from gData. A radix tree is a
// space-optimized prefix tree in which each node that is the only child is
// merged with its parent.
let gRoot;
// Data relating to the sort metrics.
//
// - isDefault: True for the default sort metric.
// - label: Used in the drop-down menu.
// - bolds: Which fields to highlight in the output.
// - cmpField: Field used to sort the radix tree.
// - enable: Function saying whether this option is enabled.
// - sig: Significance function used to determine aggregate nodes.
// - sigLabel: Significance threshold description function.
//
const gSelectData = [
{
label: () => `Total (${bytesUnit()})`,
bolds: { "totalTitle": 1, "totalBytes": 1 },
cmpField: "_totalBytes",
enable: (aBkLt, aBkAcc) => true,
sig: (aT) => aT._totalBytes >= 0.01 * gRoot._totalBytes,
sigLabel: () => `\
total >= ${bytesAndPerc(0.01 * gRoot._totalBytes, gRoot._totalBytes)}`
},
{
isDefault: true,
label: () => `Total (${blocksUnit()})`,
bolds: { "totalTitle": 1, "totalBlocks": 1 },
cmpField: "_totalBlocks",
enable: (aBkLt, aBkAcc) => true,
sig: (aT) => aT._totalBlocks >= 0.01 * gRoot._totalBlocks,
sigLabel: () => `\
total >= ${blocksAndPerc(0.01 * gRoot._totalBlocks, gRoot._totalBlocks)}`
},
// No "Total (bytes), tiny" because it's extremely unlikely that a PP with a
// tiny average size will take up a significant number of bytes.
{
label: () => `Total (${blocksUnit()}), tiny`,
bolds: { "totalTitle": 1, "totalBlocks": 1, "totalAvgSizeBytes": 1 },
cmpField: "_totalBlocks",
enable: (aBkLt, aBkAcc) => true,
sig: (aT) => aT._totalBlocks >= 0.005 * gRoot._totalBlocks &&
aT._totalAvgSizeBytes() <= 16,
sigLabel: () => `\
(total >= ${blocksAndPerc(0.005 * gRoot._totalBlocks, gRoot._totalBlocks)}) && \
(avg size <= ${bytes(16)})`
},
// No "Total (bytes), short-lived", because a PP with few large, short-lived
// blocks is unlikely. (In contrast, "Total (blocks), short-lived" is useful,
// because a PP with many small, short-lived blocks *is* likely.) And if
// such a PP existed, it'll probably show up in "Total (bytes), zero reads
// or zero writes" or "Total (bytes), low-access" anyway, because there's
// little time for accesses in a small number of instructions.
{
label: () => "Total (blocks), short-lived",
bolds: { "totalTitle": 1, "totalBlocks": 1, "totalAvgLifetime": 1 },
cmpField: "_totalBlocks",
enable: (aBkLt, aBkAcc) => aBkLt,
sig: (aT) => aT._totalBlocks >= 0.005 * gRoot._totalBlocks &&
aT._totalAvgLifetimes() <= gData.tuth,
sigLabel: () => `\
(total >= ${blocksAndPerc(0.005 * gRoot._totalBlocks, gRoot._totalBlocks)}) && \
(avg lifetime <= ${time(gData.tuth)})`
},
{
label: () => "Total (bytes), zero reads or zero writes",
bolds: { "totalTitle": 1, "totalBytes": 1,
"readsTitle": 1, "readsBytes": 1,
"writesTitle": 1, "writesBytes": 1,
},
cmpField: "_totalBytes",
enable: (aBkLt, aBkAcc) => aBkAcc,
sig: (aT) => aT._totalBytes >= 0.005 * gRoot._totalBytes &&
(aT._readsBytes === 0 || aT._writesBytes === 0),
sigLabel: () => `\
(total >= ${bytesAndPerc(0.005 * gRoot._totalBytes, gRoot._totalBytes)}) && \
((reads == ${bytes(0)}) || (writes == ${bytes(0)}))`
},
{
label: () => "Total (blocks), zero reads or zero writes",
bolds: { "totalTitle": 1, "totalBlocks": 1,
"readsTitle": 1, "readsBytes": 1,
"writesTitle": 1, "writesBytes": 1,
},
cmpField: "_totalBlocks",
enable: (aBkLt, aBkAcc) => aBkAcc,
sig: (aT) => aT._totalBlocks >= 0.005 * gRoot._totalBlocks &&
(aT._readsBytes === 0 || aT._writesBytes === 0),
sigLabel: () => `\
(total >= ${blocksAndPerc(0.005 * gRoot._totalBlocks, gRoot._totalBlocks)}) && \
((reads == ${bytes(0)}) || (writes == ${bytes(0)}))`
},
{
label: () => "Total (bytes), low-access",
bolds: { "totalTitle": 1, "totalBytes": 1,
"readsTitle": 1, "readsAvgPerByte": 1,
"writesTitle": 1, "writesAvgPerByte": 1,
},
cmpField: "_totalBytes",
enable: (aBkLt, aBkAcc) => aBkAcc,
sig: (aT) => aT._totalBytes >= 0.005 * gRoot._totalBytes &&
aT._readsBytes !== 0 &&
aT._writesBytes !== 0 &&
(aT._readsAvgPerByte() <= 0.4 ||
aT._writesAvgPerByte() <= 0.4),
sigLabel: () => `\
(total >= ${bytesAndPerc(0.005 * gRoot._totalBytes, gRoot._totalBytes)}) && \
(reads != ${bytes(0)}) && \
(writes != ${bytes(0)}) && \
((reads <= ${perByte(0.4)}) || (writes <= ${perByte(0.4)}))`
},
{
label: () => "Total (blocks), low-access",
bolds: { "totalTitle": 1, "totalBlocks": 1,
"readsTitle": 1, "readsAvgPerByte": 1,
"writesTitle": 1, "writesAvgPerByte": 1,
},
cmpField: "_totalBlocks",
enable: (aBkLt, aBkAcc) => aBkAcc,
sig: (aT) => aT._totalBlocks >= 0.005 * gRoot._totalBlocks &&
aT._readsBytes !== 0 &&
aT._writesBytes !== 0 &&
(aT._readsAvgPerByte() <= 0.4 ||
aT._writesAvgPerByte() <= 0.4),
sigLabel: () => `\
(total >= ${blocksAndPerc(0.005 * gRoot._totalBlocks, gRoot._totalBlocks)}) && \
(reads != ${bytes(0)}) && \
(writes != ${bytes(0)}) && \
((reads <= ${perByte(0.4)}) || (writes <= ${perByte(0.4)}))`
},
// No "Total (avg size bytes)": not interesting.
// No "Total (avg lifetime)": covered by "Total (blocks), short-lived".
// No "Max (bytes)": not interesting, and unclear how to sort.
// No "Max (blocks)": not interesting, and unclear how to sort.
// No "Max (avg size bytes)": not interesting, and unclear how to sort.
{
label: () => "At t-gmax (bytes)",
bolds: { "atTGmaxTitle": 1, "atTGmaxBytes": 1 },
cmpField: "_atTGmaxBytes",
enable: (aBkLt, aBkAcc) => aBkLt,
sig: (aT) => aT._atTGmaxBytes >= 0.01 * gRoot._atTGmaxBytes,
sigLabel: () => `\
at-t-gmax >= ${bytesAndPerc(0.01 * gRoot._atTGmaxBytes, gRoot._atTGmaxBytes)}`
},
// No "At t-gmax (blocks)": not interesting.
// No "At t-gmax (avg size bytes)": not interesting.
{
label: () => "At t-end (bytes)",
bolds: { "atTEndTitle": 1, "atTEndBytes": 1 },
cmpField: "_atTEndBytes",
enable: (aBkLt, aBkAcc) => aBkLt,
sig: (aT) => aT._atTEndBytes >= 0.01 * gRoot._atTEndBytes,
sigLabel: () => `\
at-t-end >= ${bytesAndPerc(0.01 * gRoot._atTEndBytes, gRoot._atTEndBytes)}`
},
// No "At t-end (blocks)": not interesting.
// No "At t-end (avg size bytes)": not interesting.
{
label: () => "Reads (bytes)",
bolds: { "readsTitle": 1, "readsBytes": 1 },
cmpField: "_readsBytes",
enable: (aBkLt, aBkAcc) => aBkAcc,
sig: (aT) => aT._readsBytes >= 0.01 * gRoot._readsBytes,
sigLabel: () => `\
reads >= ${bytesAndPerc(0.01 * gRoot._readsBytes, gRoot._readsBytes)}`
},
{
label: () => "Reads (bytes), high-access",
bolds: { "readsTitle": 1, "readsBytes": 1, "readsAvgPerByte": 1 },
cmpField: "_readsBytes",
enable: (aBkLt, aBkAcc) => aBkAcc,
sig: (aT) => aT._readsBytes >= 0.005 * gRoot._readsBytes &&
(aT._readsAvgPerByte() >= 1000 ||
aT._writesAvgPerByte() >= 1000),
sigLabel: () => `\
(reads >= ${bytesAndPerc(0.005 * gRoot._readsBytes, gRoot._readsBytes)}) && \
((reads >= ${perByte(1000)}) || (writes >= ${perByte(1000)}))`
},
// No "Reads (avg per byte)": covered by other access-related ones.
{
label: () => "Writes (bytes)",
bolds: { "writesTitle": 1, "writesBytes": 1 },
cmpField: "_writesBytes",
enable: (aBkLt, aBkAcc) => aBkAcc,
sig: (aT) => aT._writesBytes >= 0.01 * gRoot._writesBytes,
sigLabel: () => `\
writes >= ${bytesAndPerc(0.01 * gRoot._writesBytes, gRoot._writesBytes)}`
},
{
label: () => "Writes (bytes), high-access",
bolds: { "writesTitle": 1, "writesBytes": 1, "writesAvgPerByte": 1 },
cmpField: "_writesBytes",
enable: (aBkLt, aBkAcc) => aBkAcc,
sig: (aT) => aT._writesBytes >= 0.005 * gRoot._writesBytes &&
(aT._readsAvgPerByte() >= 1000 ||
aT._writesAvgPerByte() >= 1000),
sigLabel: () => `\
(writes >= ${bytesAndPerc(0.005 * gRoot._writesBytes, gRoot._writesBytes)}) && \
((reads >= ${perByte(1000)}) || (writes >= ${perByte(1000)}))`
}
// No "Writes (avg per byte)": covered by other access-related ones.
];
//------------------------------------------------------------//
//--- Utilities ---//
//------------------------------------------------------------//
// Assertion. Fails if aMsg is missing.
function assert(aCond, aMsg) {
if (!aCond || !aMsg) {
throw new Error(`assertion failed: ${aMsg}`);
}
}
// Division function that returns 0 instead of NaN for 0/0, which is what we
// always want.
function div(aNum, aDenom) {
return aNum === 0 && aDenom === 0 ? 0 : aNum / aDenom;
}
// Execute a function, printing any exception to the page.
function tryFunc(aFunc) {
try {
aFunc();
} catch (ex) {
// Clear gRoot, so that any old or partially-built new value doesn't hang
// around if after this exception is thrown.
gRoot = undefined;
clearMainDivWithText(ex.toString(), "error");
throw ex;
}
}
// Put some text in a div at the bottom of the page. Useful for debugging.
function debug(x) {
let section = appendElement(document.body, "div", "section");
appendElementWithText(section, "div", JSON.stringify(x), "debug noselect");
}
//------------------------------------------------------------//
//--- Radix tree building ---//
//------------------------------------------------------------//
// Notes about the TreeNode kinds:
//
// --------------------------------------------------------------------
// Leaf Internal Aggregate
// --------------------------------------------------------------------
// Has this._kids? No Yes No
// Has this._max*? Yes No No
// Has this._accesses? Maybe Maybe No
// Allowed this._sig values? Self,None Self,Desc,None None
// How many this._add() calls? 1 1+ 1+
// --------------------------------------------------------------------
//
const kLeaf = 1;
const kInternal = 2;
const kAgg = 3;
function TreeNode(aKind, aFrames) {
this._kind = aKind;
this._totalBytes = 0;
this._totalBlocks = 0;
this._totalLifetimes = 0;
// These numbers only make sense for leaf nodes. Unlike total stats, which
// can be summed, _maxBytes/_maxBlocks for two PPs can't be easily combined
// because the maxes may have occurred at different times.
if (this._kind === kLeaf) {
this._maxBytes = 0;
this._maxBlocks = 0;
}
this._atTGmaxBytes = 0;
this._atTGmaxBlocks = 0;
this._atTEndBytes = 0;
this._atTEndBlocks = 0;
this._readsBytes = 0;
this._writesBytes = 0;
// this._accesses is left undefined. It will be added if necessary.
// The possible values have the following meanings:
// - undefined means "unset accesses" (i.e. new node, never been set)
// - length==0 means "no accesses" (i.e. some kids have accesses and some
// don't, or all kids have accesses but in different sizes)
// - length>0 means "accesses" (i.e. all kids have accesses and all the same
// size)
// If a node would only have a single child, we instead effectively inline it
// in the parent. Therefore a node can have multiple frames.
this._frames = aFrames;
// this._kids is left undefined. It will be added if necessary.
// this._sig is added later, by sigTree().
}
TreeNode.prototype = {
_add(aTotalBytes, aTotalBlocks, aTotalLifetimes, aMaxBytes,
aMaxBlocks, aAtTGmaxBytes, aAtTGmaxBlocks, aAtTEndBytes,
aAtTEndBlocks, aReadsBytes, aWritesBytes, aAccesses) {
// We ignore this._kind, this._frames, and this._kids.
// Note: if !gData.bklt and/or !gData.bkacc, some of these fields these
// values come from will be missing in the input file, so the values will
// be `undefined`, and the fields will end up as `NaN`. But this is ok
// because we don't show them.
this._totalBytes += aTotalBytes;
this._totalBlocks += aTotalBlocks;
this._totalLifetimes += aTotalLifetimes;
if (this._kind === kLeaf) {
// Leaf nodes should only be added to once, because DHAT currently
// produces records with unique locations. If we remove addresses from
// frames in the future then something must be done here to sum non-zero
// _maxBytes and _maxBlocks values, but it's unclear exactly what. Range
// arithmetic is a (complicated) possibility.
assert(this._maxBytes === 0, "bad _maxBytes: " + this._maxBytes);
assert(this._maxBlocks === 0, "bad _maxBlocks: " + this._maxBlocks);
this._maxBytes += aMaxBytes;
this._maxBlocks += aMaxBlocks;
}
this._atTGmaxBytes += aAtTGmaxBytes;
this._atTGmaxBlocks += aAtTGmaxBlocks;
this._atTEndBytes += aAtTEndBytes;
this._atTEndBlocks += aAtTEndBlocks;
this._readsBytes += aReadsBytes;
this._writesBytes += aWritesBytes;
if (this._kind !== kAgg) {
if (!this._accesses && aAccesses) {
// unset accesses += accesses --> has accesses (must clone the array)
this._accesses = aAccesses.slice();
} else if (this._accesses && aAccesses &&
this._accesses.length === aAccesses.length) {
// accesses += accesses (with matching lengths) --> accesses
for (let i = 0; i < this._accesses.length; i++) {
this._accesses[i] += aAccesses[i];
}
} else {
// any other combination --> no accesses
this._accesses = [];
}
} else {
assert(!this._accesses, "agg nodes cannot have accesses");
}
},
_addPP(aPP) {
this._add(aPP.tb, aPP.tbk, aPP.tl, aPP.mb, aPP.mbk, aPP.gb, aPP.gbk,
aPP.eb, aPP.ebk, aPP.rb, aPP.wb, aPP.acc);
},
// This is called in two cases.
// - Splitting a node, where we are adding to a fresh node (i.e. effectively
// cloning a node).
// - Aggregating multiple nodes.
_addNode(aT) {
this._add(aT._totalBytes, aT._totalBlocks, aT._totalLifetimes,
aT._maxBytes, aT._maxBlocks, aT._atTGmaxBytes, aT._atTGmaxBlocks,
aT._atTEndBytes, aT._atTEndBlocks,
aT._readsBytes, aT._writesBytes, aT._accesses);
},
// Split the node after the aTi'th internal frame. The inheriting kid will
// get the post-aTi frames; the new kid will get aNewFrames.
_split(aTi, aPP, aNewFrames) {
// kid1 inherits t's kind and values.
let inheritedFrames = this._frames.splice(aTi + 1);
let kid1 = new TreeNode(this._kind, inheritedFrames);
if (this._kids) {
kid1._kids = this._kids;
}
kid1._addNode(this);
// Put all remaining frames into kid2.
let kid2 = new TreeNode(kLeaf, aNewFrames);
kid2._addPP(aPP);
// Update this.
if (this._kind === kLeaf) {
// Convert to an internal node.
this._kind = kInternal;
assert(this.hasOwnProperty("_maxBytes"), "missing _maxBytes");
assert(this.hasOwnProperty("_maxBlocks"), "missing _maxBlocks");
delete this._maxBytes;
delete this._maxBlocks;
}
this._kids = [kid1, kid2];
this._addPP(aPP);
},
_totalAvgSizeBytes() {
return div(this._totalBytes, this._totalBlocks);
},
_totalAvgLifetimes() {
return div(this._totalLifetimes, this._totalBlocks);
},
_maxAvgSizeBytes() {
assert(this._kind === kLeaf, "non-leaf node");
return div(this._maxBytes, this._maxBlocks);
},
_atTGmaxAvgSizeBytes() {
return div(this._atTGmaxBytes, this._atTGmaxBlocks);
},
_atTEndAvgSizeBytes() {
return div(this._atTEndBytes, this._atTEndBlocks);
},
_readsAvgPerByte() {
return div(this._readsBytes, this._totalBytes);
},
_writesAvgPerByte() {
return div(this._writesBytes, this._totalBytes);
}
}
// Check if the fields in `aFields` are present in `aObj`.
function checkFields(aObj, aFields) {
for (let f of aFields) {
if (!aObj.hasOwnProperty(f)) {
throw new Error(`data file is missing a field: ${f}`);
}
}
}
// Do basic checking of a PP read from file.
function checkPP(aPP) {
checkFields(aPP, ["tb", "tbk", "fs"]);
if (gData.bklt) {
checkFields(aPP, ["mb", "mbk", "gb", "gbk", "eb", "ebk"]);
}
if (gData.bkacc) {
checkFields(aPP, ["rb", "wb"]);
}
}
// Access counts latch as 0xffff. Treating 0xffff as Infinity gives us exactly
// the behaviour we want, e.g. Infinity + 1 = Infinity.
function normalizeAccess(aAcc) {
if (aAcc < 0xffff) {
return aAcc;
}
if (aAcc === 0xffff) {
return Infinity;
}
assert(false, "too-large access value");
}
const kExpectedFileVersion = 2;
// Build gRoot from gData.
function buildTree() {
// Check global values.
let fields = ["dhatFileVersion", "mode", "verb",
"bklt", "bkacc",
"tu", "Mtu",
"cmd", "pid",
"te", "pps", "ftbl"];
checkFields(gData, fields);
if (gData.dhatFileVersion != kExpectedFileVersion) {
throw new Error(
`data file has version number ${gData.dhatFileVersion}, ` +
`expected version number ${kExpectedFileVersion}`);
}
if (gData.bklt) {
checkFields(gData, ["tg", "tuth"]);
}
// Update sort metric labels, and disable sort metrics that aren't allowed
// for this data.
for (let [i, option] of gSelect.childNodes.entries()) {
let data = gSelectData[i];
option.label = data.label();
option.disabled = !data.enable(gData.bklt, gData.bkacc);
}
// If the selected sort metric was just disabled, switch the sort metric
// back to the default (which is never disabled).
let option = gSelect.childNodes[gSelect.selectedIndex];
if (option.disabled) {
for (let [i, data] of gSelectData.entries()) {
let option = gSelect.childNodes[i];
if (data.isDefault) {
option.selected = true;
break;
}
}
}
// Build the radix tree. Nodes are in no particular order to start with. The
// algorithm is tricky because we need to use internal frames when possible.
gRoot = new TreeNode(kLeaf, [0]); // Frame 0 is always "[root]".
for (let [i, pp] of gData.pps.entries()) {
checkPP(pp);
// Decompress the run-length encoding in `acc`, if present.
if (pp.acc) {
let acc = [];
for (let i = 0; i < pp.acc.length; i++) {
if (pp.acc[i] < 0) {
// A negative number encodes a repeat count. The following entry has
// the value to be repeated.
let reps = -pp.acc[i++];
let val = pp.acc[i];
for (let j = 0; j < reps; j++) {
acc.push(normalizeAccess(val));
}
} else {
acc.push(normalizeAccess(pp.acc[i]));
}
}
pp.acc = acc;
}
// The first PP is a special case, because we have to build gRoot.
if (i === 0) {
gRoot._frames.push(...pp.fs);
gRoot._addPP(pp);
continue;
}
let t = gRoot; // current node
let ti = 0; // current frame index within t
let done = false;
// In the examples below, tree nodes have the form `abcd:N-Xs`, where
// `abcd` is a frame sequence (and `-` is an empty sequence), `N` is a node
// value, and `Xs` are the node's children.
for (let [j, kidFrame] of pp.fs.entries()) {
// Search for kidFrame among internal frames.
if (ti + 1 < t._frames.length) {
// t has an internal frame at the right index.
if (t._frames[ti + 1] === kidFrame) {
// The internal frame matches. Move to t's next internal frame.
ti++;
} else {
// The internal frame doesn't match. Split the node.
//
// E.g. abcd:20-[] + abef:10 => ab:30-[cd:20-[], ef:10-[]]
t._split(ti, pp, pp.fs.slice(j));
done = true;
break;
}
} else {
// We've run out of internal frames in t. Consider t's kids.
if (!t._kids) {
// No kids; this must be a supersequence of an existing sequence.
// Split t; the inheriting kid will get no frames, the new kid will
// get the leftover frames.
//
// E.g. ab:20-[] + abcd:10 => ab:30-[-:20-[], cd:10-[]]
t._split(ti, pp, pp.fs.slice(j));
done = true;
break;
}
t._addPP(pp);
// Search for the frame among the kids.
let kid;
for (let k of t._kids) {
if (k._frames[0] === kidFrame) {
kid = k;
break;
}
}
if (kid) {
// Found it. Move to it.
t = kid;
ti = 0;
} else {
// Didn't find it. Put all remaining frames into a new leaf node.
//
// E.g. ab:20-[c:10-Xs, d:10-Ys] + abef:10 =>
// ab:30-[c:10-Xs, d:10-Ys, ef:10-[]]
kid = new TreeNode(kLeaf, pp.fs.slice(j));
kid._addPP(pp);
t._kids.push(kid);
done = true;
break;
}
}
}
if (!done) {
// If we reach here, either:
// - pp's frames match an existing frame sequence, in which case we
// just need to _addPP(); or
// - pp's frames are a subsequence of an existing sequence, in which
// case we must split.
if (ti + 1 < t._frames.length) {
// A subsequence of an existing sequence that ends within t's internal
// frames. Split, creating an empty node.
//
// E.g. abcd:20-Xs + ab:10 => ab:30-[cd:20-Xs, -:10-[]]
t._split(ti, pp, []);
} else if (!t._kids) {
// This is impossible because DHAT currently produces records with
// unique locations. If we remove addresses from frames in the future
// then duplicate locations will occur, and the following code is how
// it must be handled.
throw new Error(`data file contains a repeated location (1)`);
// Matches an existing sequence that doesn't end in node with empty
// frames. Add the PP.
//
// E.g. ab:20-[] + ab:10 => ab:30-[]
t._addPP(pp);
} else {
// Look for a kid with empty frames.
let emptyKid;
for (let k of t._kids) {
if (k._frames.length === 0) {
emptyKid = k;
break;
}
}
if (emptyKid) {
// This is impossible because DHAT currently produces records with
// unique locations. If we remove addresses from frames in the future
// then duplicate locations will occur, and the following code is how
// it must be handled.
throw new Error(`data file contains a repeated location (2)`);
// Matches an existing sequence that ends in a node with empty
// frames. Add the PP.
//
// E.g. ab:20-[c:10-Xs, -:10-[]] + ab:10 => ab:30-[c:10-Xs, -:20-[]]
t._addPP(pp);
emptyKid._addPP(pp);
} else {
// A subsequence of an existing sequence that ends at the end of t's
// internal frames. Append an empty node.
//
// E.g. ab:20-[c:10-Xs, d:10-Ys] + ab:10 =>
// ab:30-[c:10-Xs, d:10-Ys, -:10-[]]
let newKid = new TreeNode(kLeaf, []);
newKid._addPP(pp);
t._kids.push(newKid);
t._addPP(pp);
}
}
}
}
}
//------------------------------------------------------------//
//--- Pretty printers ---//
//------------------------------------------------------------//
// Using Intl.NumberFormat makes things faster than using toLocaleString()
// repeatedly.
const kPFormat = new Intl.NumberFormat(undefined, { maximumFractionDigits: 2, style: "percent" });
const kDFormat = new Intl.NumberFormat(undefined, { maximumFractionDigits: 2 }); // decimal
const kTFormat = new Intl.NumberFormat(); // time
function perc(aNum, aDenom) {
return kPFormat.format(div(aNum, aDenom));
}
function perMinstr(aN) {
return `${kDFormat.format(div(1000000 * aN, gData.te))}/${gData.Mtu}`;
}
function byteUnit() {
return gData.hasOwnProperty("bu") ? gData.bsu : "byte";
}
function bytesUnit() {
return gData.hasOwnProperty("bsu") ? gData.bsu : "bytes";
}
function blocksUnit() {
return gData.hasOwnProperty("bksu") ? gData.bksu : "blocks";
}
function bytes(aN) {
return `${kDFormat.format(aN)} ${bytesUnit()}`;
}
function bytesAndPerc(aN, aTotalN) {
return `${bytes(aN)} (${perc(aN, aTotalN)})`;
}
function bytesAndPercAndRate(aN, aTotalN) {
return `${bytes(aN)} (${perc(aN, aTotalN)}, ${perMinstr(aN)})`;
}
function blocks(aN) {
return `${kDFormat.format(aN)} ${blocksUnit()}`;
}
function blocksAndPerc(aN, aTotalN) {
return `${blocks(aN)} (${perc(aN, aTotalN)})`;
}
function blocksAndPercAndRate(aN, aTotalN) {
return `${blocks(aN)} (${perc(aN, aTotalN)}, ${perMinstr(aN)})`;
}
function avgSizeBytes(aN) {
return `avg size ${bytes(aN)}`;
}
function perByte(aN) {
return `${kDFormat.format(aN)}/${byteUnit()}`;
}
function time(aN) {
return `${kDFormat.format(aN)} ${gData.tu}`;
}
function avgLifetime(aN) {
return `avg lifetime ${time(aN)}`;
}
function accesses(aAccesses) {
// Make zero stand out.
if (aAccesses === 0) {
return "-";
}
if (aAccesses === Infinity) {
return "∞";
}
// Don't use toLocaleString() -- in this case the values rarely reach
// 100,000, and the grid formatting means the separators tend to make the
// numbers harder to read. (And locales such as fr-FR use ' ' as the
// separator, which conflicts with our use of ' ' between values!)
return aAccesses.toString();
}
function ms(aNum) {
// This function is called only a handful of times, so there is no need to
// use Intl.NumberFormat.
return aNum !== undefined ? `${kTFormat.format(aNum)}ms` : "n/a";
}
//------------------------------------------------------------//
//--- DOM manipulation ---//
//------------------------------------------------------------//
const kDocumentTitle = "DHAT Viewer";
document.title = kDocumentTitle;
function appendElement(aP, aTagName, aClassName) {
let e = document.createElement(aTagName);
if (aClassName) {
e.className = aClassName;
}
aP.appendChild(e);
return e;
}
function appendElementWithText(aP, aTagName, aText, aClassName) {
let e = appendElement(aP, aTagName, aClassName);
e.textContent = aText;
return e;
}
function appendText(aP, aText) {
let e = document.createTextNode(aText);
aP.appendChild(e);
return e;
}
function clearDiv(aDiv) {
// Replace aDiv with an empty node.
assert(aDiv, "no div given");
let tmp = aDiv.cloneNode(/* deep = */ false);
aDiv.parentNode.replaceChild(tmp, aDiv);
return tmp;
}
function clearMainDiv() {
gMainDiv = clearDiv(gMainDiv);
}
function clearTimingsDiv() {
gTimingsDiv = clearDiv(gTimingsDiv);
}
function clearMainDivWithText(aText, aClassName) {
clearMainDiv();
appendElementWithText(gMainDiv, "span", aText, aClassName);
}
function appendInvocationAndTimes(aP) {
let v, v1, v2;
v = "Invocation {\n";
v += ` Mode: ${gData.mode}\n`;
v += ` Command: ${gData.cmd}\n`;
v += ` PID: ${gData.pid}\n`;
v += "}\n\n";
appendElementWithText(aP, "span", v, "invocation");
v = "Times {\n";
v1 = perc(gData.tg, gData.te);
if (gData.bklt) {
v += ` t-gmax: ${time(gData.tg)} (${v1} of program duration)\n`;
}
v += ` t-end: ${time(gData.te)}\n`;
v += "}\n\n";
appendElementWithText(aP, "span", v, "times");
}
// Arrows indicating what state a node is in.
const kNoKidsArrow = "─ "; // cannot change
const kHidingKidsArrow = "▶ "; // expandible
const kShowingKidsArrow = "▼ "; // collapsible
// HTML doesn't have a tree element, so we fake one with text. One nice
// consequence is that you can copy and paste the output. The non-ASCII chars
// used (for arrows and tree lines) usually reproduce well when pasted into
// textboxes.
//
// - aT: The sub-tree to append.
// - aP: Parent HTML element to append to.
// - aBolds: Which fields to highlight in the output.
// - aPc: The percentage function.
// - aCmp: The comparison function.
// - aSig: The significance function.
// - aNodeIdNums: The node ID numbers, e.g. [1,2,3], which is printed "1.2.3".
// - aNumSibs: The number of siblings that aT has.
// - aOldFrames: Frames preceding this node's frames.
// - aTlFirst: Treeline for the first line of the node.
// - aTlRest: Treeline for the other lines of the node, and its kids.
//
function appendTreeInner(aT, aP, aBolds, aCmp, aPc, aSig, aNodeIdNums,
aNumSibs, aOldFrames, aTlFirst, aTlRest) {
// The primary element we'll be appending to.
let p;
// We build up text fragments in up to seven groups:
// - pre-Bold1 (multiple)
// - Bold1 (single)
// - post-Bold1 (multiple)
// - Bold2 (single)
// - post-Bold2 (multiple)
// - Bold3 (single)
// - post-Bold3 (multiple)
//
// This is so that up to 3 bold sequences can be highlighted per line.
let frags, fi;
// Clear the text fragments.
function clear() {
frags = [[], undefined, [], undefined, [], undefined, []];
fi = 0;
}
// Add a fragment.
// - aShowIfInsig: should we show this even in an insignificant node?
// - aIsBold: if this is shown, should it be bold? If undefined (as is
// common) it takes the same value as aShowIfInsig.
function fr(aStr, aShowIfInsig, aIsBold) {
if (!aShowIfInsig && aT._sig !== kSigSelf) {
return;
}
if (aIsBold === undefined) {
aIsBold = aShowIfInsig;
}
if (aIsBold) {
assert(fi === 0 || fi === 2 || fi === 4, "bad fragIndex (1)");
assert(frags[fi + 1] === undefined, "bold already here");
frags[fi + 1] = aStr;
fi += 2;
} else {
assert(fi === 0 || fi === 2 || fi === 4 || fi === 6, "bad fragIndex (2)");
frags[fi].push(aStr);
}
}
// Add a newline fragment (with a following treeline, unless aIsLast==true).
// - aShowIfInsig: should we show this even in an insignificant node?
// - aIsLast: is this the last newline for the node?
function nl(aShowIfInsig, aIsLast) {
assert(fi === 0 || fi === 2 || fi === 4 || fi === 6, "bad fragIndex (3)");
if (!aShowIfInsig && aT._sig !== kSigSelf) {
return;
}
frags[fi].push("\n");
// Alternate the non-bold fragments (each in a text node) and bold
// fragments (each in a span).
if (frags[0].length > 0) {
appendText(p, frags[0].join(""));
}
if (frags[1] !== undefined) {
appendElementWithText(p, "span", frags[1], "bold");
}
if (frags[2].length > 0) {
appendText(p, frags[2].join(""));
}
if (frags[3] !== undefined) {
appendElementWithText(p, "span", frags[3], "bold");
}
if (frags[4].length > 0) {
appendText(p, frags[4].join(""));
}
if (frags[5] !== undefined) {
appendElementWithText(p, "span", frags[5], "bold");
}
if (frags[6].length > 0) {
appendText(p, frags[6].join(""));
}