forked from firefox-devtools/profiler
-
Notifications
You must be signed in to change notification settings - Fork 0
/
profile-data.js
3791 lines (3493 loc) · 129 KB
/
profile-data.js
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
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
// @flow
import memoize from 'memoize-immutable';
import MixedTupleMap from 'mixedtuplemap';
import { oneLine } from 'common-tags';
import {
resourceTypes,
getEmptyUnbalancedNativeAllocationsTable,
getEmptyBalancedNativeAllocationsTable,
getEmptyStackTable,
getEmptyCallNodeTable,
shallowCloneFrameTable,
shallowCloneFuncTable,
} from './data-structures';
import { CallNodeInfoImpl } from './call-node-info';
import {
INSTANT,
INTERVAL,
INTERVAL_START,
INTERVAL_END,
} from 'firefox-profiler/app-logic/constants';
import { timeCode } from 'firefox-profiler/utils/time-code';
import { bisectionRight, bisectionLeft } from 'firefox-profiler/utils/bisect';
import { parseFileNameFromSymbolication } from 'firefox-profiler/utils/special-paths';
import {
assertExhaustiveCheck,
ensureExists,
getFirstItemFromSet,
} from 'firefox-profiler/utils/flow';
import ExtensionFavicon from '../../res/img/svg/extension-outline.svg';
import DefaultLinkFavicon from '../../res/img/svg/globe.svg';
import type {
Profile,
Thread,
SamplesTable,
StackTable,
FrameTable,
FuncTable,
NativeSymbolTable,
ResourceTable,
CategoryList,
IndexIntoCategoryList,
IndexIntoSubcategoryListForCategory,
IndexIntoFuncTable,
IndexIntoSamplesTable,
IndexIntoStackTable,
IndexIntoResourceTable,
IndexIntoNativeSymbolTable,
ThreadIndex,
Category,
Counter,
CounterSamplesTable,
NativeAllocationsTable,
InnerWindowID,
BalancedNativeAllocationsTable,
IndexIntoFrameTable,
PageList,
CallNodeInfo,
CallNodeTable,
CallNodePath,
CallNodeAndCategoryPath,
IndexIntoCallNodeTable,
AccumulatedCounterSamples,
SamplesLikeTable,
SelectedState,
ProfileFilterPageData,
Milliseconds,
StartEndRange,
ImplementationFilter,
CallTreeSummaryStrategy,
EventDelayInfo,
ThreadsKey,
resourceTypeEnum,
MarkerPayload,
Address,
AddressProof,
TimelineType,
NativeSymbolInfo,
BottomBoxInfo,
Bytes,
ThreadWithReservedFunctions,
TabID,
} from 'firefox-profiler/types';
import type { UniqueStringArray } from 'firefox-profiler/utils/unique-string-array';
/**
* Various helpers for dealing with the profile as a data structure.
* @module profile-data
*/
/**
* Generate the non-inverted CallNodeInfo for a thread.
*/
export function getCallNodeInfo(
stackTable: StackTable,
frameTable: FrameTable,
funcTable: FuncTable,
defaultCategory: IndexIntoCategoryList
): CallNodeInfo {
const { callNodeTable, stackIndexToCallNodeIndex } = computeCallNodeTable(
stackTable,
frameTable,
funcTable,
defaultCategory
);
return new CallNodeInfoImpl(
callNodeTable,
callNodeTable,
stackIndexToCallNodeIndex,
stackIndexToCallNodeIndex,
false
);
}
type CallNodeTableAndStackMap = {
callNodeTable: CallNodeTable,
// IndexIntoStackTable -> IndexIntoCallNodeTable
stackIndexToCallNodeIndex: Int32Array,
};
/**
* Generate the CallNodeTable, and a map to convert an IndexIntoStackTable to a
* IndexIntoCallNodeTable. This function runs through a stackTable, and
* de-duplicates stacks that have frames that point to the same function.
*
* See `src/types/profile-derived.js` for the type definitions.
* See `docs-developer/call-trees.md` for a detailed explanation of CallNodes.
*/
export function computeCallNodeTable(
stackTable: StackTable,
frameTable: FrameTable,
funcTable: FuncTable,
defaultCategory: IndexIntoCategoryList
): CallNodeTableAndStackMap {
return timeCode('getCallNodeInfo', () => {
const stackIndexToCallNodeIndex = new Int32Array(stackTable.length);
// The callNodeTable components.
const prefix: Array<IndexIntoCallNodeTable> = [];
const firstChild: Array<IndexIntoCallNodeTable> = [];
const nextSibling: Array<IndexIntoCallNodeTable> = [];
const func: Array<IndexIntoFuncTable> = [];
const category: Array<IndexIntoCategoryList> = [];
const subcategory: Array<IndexIntoSubcategoryListForCategory> = [];
const innerWindowID: Array<InnerWindowID> = [];
const sourceFramesInlinedIntoSymbol: Array<
IndexIntoNativeSymbolTable | -1 | null,
> = [];
let length = 0;
// An extra column that only gets used while the table is built up: For each
// node A, currentLastChild[A] tracks the last currently-known child node of A.
// It is updated whenever a new node is created; e.g. creating node B updates
// currentLastChild[prefix[B]].
// currentLastChild[A] is -1 while A has no children.
const currentLastChild: Array<IndexIntoCallNodeTable> = [];
// The last currently-known root node, i.e. the last known "child of -1".
let currentLastRoot = -1;
function addCallNode(
prefixIndex: IndexIntoCallNodeTable,
funcIndex: IndexIntoFuncTable,
categoryIndex: IndexIntoCategoryList,
subcategoryIndex: IndexIntoSubcategoryListForCategory,
windowID: InnerWindowID,
inlinedIntoSymbol: IndexIntoNativeSymbolTable | null
) {
const index = length++;
prefix[index] = prefixIndex;
func[index] = funcIndex;
category[index] = categoryIndex;
subcategory[index] = subcategoryIndex;
innerWindowID[index] = windowID;
sourceFramesInlinedIntoSymbol[index] = inlinedIntoSymbol;
// Initialize these firstChild and nextSibling to -1. They will be updated
// once this node's first child or next sibling gets created.
firstChild[index] = -1;
nextSibling[index] = -1;
currentLastChild[index] = -1;
// Update the next sibling of our previous sibling, and the first child of
// our prefix (if we're the first child).
// Also set this node's depth.
if (prefixIndex === -1) {
// This node is a root. Just update the previous root's nextSibling. Because
// this node has no parent, there's also no firstChild information to update.
if (currentLastRoot !== -1) {
nextSibling[currentLastRoot] = index;
}
currentLastRoot = index;
} else {
// This node is not a root: update both firstChild and nextSibling information
// when appropriate.
const prevSiblingIndex = currentLastChild[prefixIndex];
if (prevSiblingIndex === -1) {
// This is the first child for this prefix.
firstChild[prefixIndex] = index;
} else {
nextSibling[prevSiblingIndex] = index;
}
currentLastChild[prefixIndex] = index;
}
}
// Go through each stack, and create a new callNode table, which is based off of
// functions rather than frames.
for (let stackIndex = 0; stackIndex < stackTable.length; stackIndex++) {
const prefixStack = stackTable.prefix[stackIndex];
// We know that at this point the following condition holds:
// assert(prefixStack === null || prefixStack < stackIndex);
const prefixCallNode =
prefixStack === null ? -1 : stackIndexToCallNodeIndex[prefixStack];
const frameIndex = stackTable.frame[stackIndex];
const categoryIndex = stackTable.category[stackIndex];
const subcategoryIndex = stackTable.subcategory[stackIndex];
const inlinedIntoSymbol =
frameTable.inlineDepth[frameIndex] > 0
? frameTable.nativeSymbol[frameIndex]
: null;
const funcIndex = frameTable.func[frameIndex];
// Check if the call node for this stack already exists.
let callNodeIndex = -1;
if (stackIndex !== 0) {
const currentFirstSibling =
prefixCallNode === -1 ? 0 : firstChild[prefixCallNode];
for (
let currentSibling = currentFirstSibling;
currentSibling !== -1;
currentSibling = nextSibling[currentSibling]
) {
if (func[currentSibling] === funcIndex) {
callNodeIndex = currentSibling;
break;
}
}
}
if (callNodeIndex === -1) {
const windowID = frameTable.innerWindowID[frameIndex] || 0;
// New call node.
callNodeIndex = length;
addCallNode(
prefixCallNode,
funcIndex,
categoryIndex,
subcategoryIndex,
windowID,
inlinedIntoSymbol
);
} else {
// There is already a call node for this function. Use it, and check if
// there are any conflicts between the various stack nodes that have been
// merged into it.
// Resolve category conflicts, by resetting a conflicting subcategory or
// category to the default category.
if (category[callNodeIndex] !== categoryIndex) {
// Conflicting origin stack categories -> default category + subcategory.
category[callNodeIndex] = defaultCategory;
subcategory[callNodeIndex] = 0;
} else if (subcategory[callNodeIndex] !== subcategoryIndex) {
// Conflicting origin stack subcategories -> "Other" subcategory.
subcategory[callNodeIndex] = 0;
}
// Resolve "inlined into" conflicts. This can happen if you have two
// function calls A -> B where only one of the B calls is inlined, or
// if you use call tree transforms in such a way that a function B which
// was inlined into two different callers (A -> B, C -> B) gets collapsed
// into one call node.
if (
sourceFramesInlinedIntoSymbol[callNodeIndex] !== inlinedIntoSymbol
) {
// Conflicting inlining: -1.
sourceFramesInlinedIntoSymbol[callNodeIndex] = -1;
}
}
stackIndexToCallNodeIndex[stackIndex] = callNodeIndex;
}
return _createCallNodeTableFromUnorderedComponents(
prefix,
firstChild,
nextSibling,
func,
category,
subcategory,
innerWindowID,
sourceFramesInlinedIntoSymbol,
length,
stackIndexToCallNodeIndex
);
});
}
/**
* Create a CallNodeTableAndStackMap with an ordered call node table based on
* the pieces of an unordered call node table.
*
* The order of siblings is maintained.
* If a node A has children, its first child B directly follows A.
* Otherwise, the node following A is A's next sibling (if it has one), or the
* next sibling of the closest ancestor which has a next sibling.
* This means that any node and all its descendants are laid out contiguously.
*/
function _createCallNodeTableFromUnorderedComponents(
prefix: Array<IndexIntoCallNodeTable>,
firstChild: Array<IndexIntoFuncTable>,
nextSibling: Array<IndexIntoFuncTable>,
func: Array<IndexIntoFuncTable>,
category: Array<IndexIntoCategoryList>,
subcategory: Array<IndexIntoSubcategoryListForCategory>,
innerWindowID: Array<InnerWindowID>,
sourceFramesInlinedIntoSymbol: Array<IndexIntoNativeSymbolTable | -1 | null>,
length: number,
stackIndexToCallNodeIndex: Int32Array
): CallNodeTableAndStackMap {
return timeCode('createCallNodeInfoFromUnorderedComponents', () => {
if (length === 0) {
return {
callNodeTable: getEmptyCallNodeTable(),
stackIndexToCallNodeIndex: new Int32Array(0),
};
}
const prefixSorted = new Int32Array(length);
const nextSiblingSorted = new Int32Array(length);
const subtreeRangeEndSorted = new Uint32Array(length);
const funcSorted = new Int32Array(length);
const categorySorted = new Int32Array(length);
const subcategorySorted = new Int32Array(length);
const innerWindowIDSorted = new Float64Array(length);
const sourceFramesInlinedIntoSymbolSorted = new Array(length);
const depthSorted = new Array(length);
let maxDepth = 0;
// Traverse the entire tree, as follows:
// 1. nextOldIndex is the next node in DFS order. Copy over all values from
// the unsorted columns into the sorted columns.
// 2. Find the next node in DFS order, set nextOldIndex to it, and continue
// to the next loop iteration.
const oldIndexToNewIndex = new Uint32Array(length);
let nextOldIndex = 0;
let nextNewIndex = 0;
let currentDepth = 0;
let currentOldPrefix = -1;
let currentNewPrefix = -1;
while (nextOldIndex !== -1) {
const oldIndex = nextOldIndex;
const newIndex = nextNewIndex;
oldIndexToNewIndex[oldIndex] = newIndex;
nextNewIndex++;
prefixSorted[newIndex] = currentNewPrefix;
funcSorted[newIndex] = func[oldIndex];
categorySorted[newIndex] = category[oldIndex];
subcategorySorted[newIndex] = subcategory[oldIndex];
innerWindowIDSorted[newIndex] = innerWindowID[oldIndex];
sourceFramesInlinedIntoSymbolSorted[newIndex] =
sourceFramesInlinedIntoSymbol[oldIndex];
depthSorted[newIndex] = currentDepth;
// The remaining two columns, nextSiblingSorted and subtreeRangeEndSorted,
// will be filled in when we get to the end of the current subtree.
// Find the next index in DFS order: If we have children, then our first child
// is next. Otherwise, we need to advance to our next sibling, if we have one,
// otherwise to the next sibling of the first ancestor which has one.
const oldFirstChild = firstChild[oldIndex];
if (oldFirstChild !== -1) {
// We have children. Our first child is the next node in DFS order.
currentOldPrefix = oldIndex;
currentNewPrefix = newIndex;
nextOldIndex = oldFirstChild;
currentDepth++;
if (currentDepth > maxDepth) {
maxDepth = currentDepth;
}
continue;
}
// We have no children. The next node is the next sibling of this node or
// of an ancestor node. Now is also a good time to fill in the values for
// subtreeRangeEnd and nextSibling.
subtreeRangeEndSorted[newIndex] = nextNewIndex;
nextOldIndex = nextSibling[oldIndex];
nextSiblingSorted[newIndex] = nextOldIndex === -1 ? -1 : nextNewIndex;
while (nextOldIndex === -1 && currentOldPrefix !== -1) {
subtreeRangeEndSorted[currentNewPrefix] = nextNewIndex;
const oldPrefixNextSibling = nextSibling[currentOldPrefix];
nextSiblingSorted[currentNewPrefix] =
oldPrefixNextSibling === -1 ? -1 : nextNewIndex;
nextOldIndex = oldPrefixNextSibling;
currentOldPrefix = prefix[currentOldPrefix];
currentNewPrefix = prefixSorted[currentNewPrefix];
currentDepth--;
}
}
const callNodeTable: CallNodeTable = {
prefix: prefixSorted,
subtreeRangeEnd: subtreeRangeEndSorted,
nextSibling: nextSiblingSorted,
func: funcSorted,
category: categorySorted,
subcategory: subcategorySorted,
innerWindowID: innerWindowIDSorted,
sourceFramesInlinedIntoSymbol: sourceFramesInlinedIntoSymbolSorted,
depth: depthSorted,
maxDepth,
length,
};
return {
callNodeTable,
stackIndexToCallNodeIndex: stackIndexToCallNodeIndex.map(
(oldIndex) => oldIndexToNewIndex[oldIndex]
),
};
});
}
/**
* Generate the inverted CallNodeInfo for a thread.
*/
export function getInvertedCallNodeInfo(
thread: Thread,
nonInvertedCallNodeTable: CallNodeTable,
stackIndexToNonInvertedCallNodeIndex: Int32Array,
defaultCategory: IndexIntoCategoryList
): CallNodeInfo {
// We compute an inverted stack table, but we don't let it escape this function.
const {
invertedThread,
oldStackToNewStack: nonInvertedStackToInvertedStack,
} = _computeThreadWithInvertedStackTable(thread, defaultCategory);
// Create an inverted call node table based on the inverted stack table.
const {
callNodeTable,
stackIndexToCallNodeIndex: invertedStackIndexToCallNodeIndex,
} = computeCallNodeTable(
invertedThread.stackTable,
invertedThread.frameTable,
invertedThread.funcTable,
defaultCategory
);
// Create a mapping that maps a stack index from the non-inverted thread to
// its corresponding call node in the inverted tree.
const nonInvertedStackIndexToCallNodeIndex = new Int32Array(
thread.stackTable.length
);
for (
let nonInvertedStackIndex = 0;
nonInvertedStackIndex < nonInvertedStackIndexToCallNodeIndex.length;
nonInvertedStackIndex++
) {
const invertedStackIndex = nonInvertedStackToInvertedStack.get(
nonInvertedStackIndex
);
if (invertedStackIndex === undefined) {
// This stack is not used as a self stack, only as a prefix stack.
// There may or may not be an inverted call node that corresponds to it,
// but we haven't checked that and we don't need to know it.
// nonInvertedStackIndexToCallNodeIndex only needs useful values for self stacks.
nonInvertedStackIndexToCallNodeIndex[nonInvertedStackIndex] = -1;
} else {
nonInvertedStackIndexToCallNodeIndex[nonInvertedStackIndex] =
invertedStackIndexToCallNodeIndex[invertedStackIndex];
}
}
return new CallNodeInfoImpl(
callNodeTable,
nonInvertedCallNodeTable,
nonInvertedStackIndexToCallNodeIndex,
stackIndexToNonInvertedCallNodeIndex,
true
);
}
// Given a stack index `needleStack` and a call node in the inverted tree
// `invertedCallTreeNode`, find an ancestor stack of `needleStack` which
// corresponds to the given call node in the inverted call tree. Returns null if
// there is no such ancestor stack.
//
// Also returns null for any stacks which aren't used as self stacks.
//
// Example:
//
// Stack table (`<func>:<line>`): Inverted call tree:
//
// - A:10 - A
// - B:20 - B
// - C:30 - A
// - C:31 - C
// - B:21 - B
// - A
//
// In this example, given the inverted tree call node C <- B and the needle
// stack A:10 -> B:20 -> C:30, the function will return the stack A:10 -> B:20.
//
// For example, if you double click the call node C <- B in the inverted tree,
// and if all samples spend their time in the stack A:10 -> B:20 -> C:30, then
// the source view should be scrolled to line 20.
//
// Background: needleStack has some self time. This self time shows up in a
// root node of the inverted tree. If you go to needleStack's prefix stack, i.e.
// if you go "up" a level in the non-inverted stack table, you go "down" a level
// in the inverted call tree. We want to go up/down enough so that we hit our
// call node. This gives us a stack node whose frame's func is the same as the
// func of `invertedCallTreeNode`. Then our caller can get some information from
// that frame, for example the frame's address or line.
export function getMatchingAncestorStackForInvertedCallNode(
needleStack: IndexIntoStackTable,
invertedTreeCallNode: IndexIntoCallNodeTable,
invertedTreeCallNodeSubtreeEnd: IndexIntoCallNodeTable,
invertedTreeCallNodeDepth: number,
stackIndexToInvertedCallNodeIndex: Int32Array,
stackTablePrefixCol: Array<IndexIntoStackTable | null>
): IndexIntoStackTable | null {
// Get the inverted call tree node for the (non-inverted) stack.
// For example, if the stack has the call path A -> B -> C,
// this will give us the node C <- B <- A in the inverted tree.
const needleCallNode = stackIndexToInvertedCallNodeIndex[needleStack];
// Check if needleCallNode is a descendant of invertedTreeCallNode in the
// inverted tree.
if (
needleCallNode >= invertedTreeCallNode &&
needleCallNode < invertedTreeCallNodeSubtreeEnd
) {
// needleCallNode is a descendant of invertedTreeCallNode in the inverted tree.
// That means that needleStack's self time contributes to the total time of
// invertedTreeCallNode. It also means that the non-inverted call path of
// needleStack "ends with" the suffix described by invertedTreeCallNode.
// For example, if invertedTreeCallNode is C <- B, and needleStack has the
// non-inverted call path A -> B -> C, then we now know that A -> B -> C ends
// with B -> C.
// Now we strip off this suffix. In the example, we strip off "-> C" at the
// end so that we end up with a stack for A -> B.
// Stripping off the suffix is equivalent to "walking down" in the inverted tree.
return getNthPrefixStack(
needleStack,
invertedTreeCallNodeDepth,
stackTablePrefixCol
);
}
// Not a descendant; return null.
return null;
}
/**
* Returns the n'th prefix of a stack, or null if it doesn't exist.
* (n = 0: the node itself, n = 1: the immediate parent node,
* n = 2: the grandparent, etc)
*/
export function getNthPrefixStack(
stackIndex: IndexIntoStackTable | null,
n: number,
stackTablePrefixCol: Array<IndexIntoStackTable | null>
): IndexIntoStackTable | null {
let s = stackIndex;
for (let i = 0; i < n && s !== null; i++) {
s = stackTablePrefixCol[s];
}
return s;
}
/**
* Take a samples table, and return an array that contain indexes that point to the
* leaf most call node, or null.
*/
export function getSampleIndexToCallNodeIndex(
stacks: Array<IndexIntoStackTable | null>,
stackIndexToCallNodeIndex: {
[key: IndexIntoStackTable]: IndexIntoCallNodeTable,
}
): Array<IndexIntoCallNodeTable | null> {
return stacks.map((stack) => {
return stack === null ? null : stackIndexToCallNodeIndex[stack];
});
}
/**
* This is an implementation of getSamplesSelectedStates for just the case where
* no call node is selected.
*/
function getSamplesSelectedStatesForNoSelection(
sampleCallNodes: Array<IndexIntoCallNodeTable | null>,
activeTabFilteredCallNodes: Array<IndexIntoCallNodeTable | null>
): SelectedState[] {
const result = new Array(sampleCallNodes.length);
for (
let sampleIndex = 0;
sampleIndex < sampleCallNodes.length;
sampleIndex++
) {
// When there's no selected call node, we don't want to shadow everything
// because everything is unselected. So let's pretend that
// everything is selected so that anything not filtered out will be nicely
// visible.
let sampleSelectedState = 'SELECTED';
// But we still want to display filtered-out samples differently.
const callNodeIndex = sampleCallNodes[sampleIndex];
if (callNodeIndex === null) {
sampleSelectedState =
activeTabFilteredCallNodes[sampleIndex] === null
? // This sample was not part of the active tab.
'FILTERED_OUT_BY_ACTIVE_TAB'
: // This sample was filtered out in the transform pipeline.
'FILTERED_OUT_BY_TRANSFORM';
}
result[sampleIndex] = sampleSelectedState;
}
return result;
}
/**
* Given the call node for each sample and the call node selected states,
* compute each sample's selected state.
*
* For samples that are not filtered out, the sample's selected state is based
* on the relation of the sample's call node to the selected call node: Any call
* nodes in the selected node's subtree are "selected"; all other nodes are
* either "before" or "after" the selected subtree.
*
* Call node tables are ordered in depth-first traversal order, so we can
* determine whether a node is before, inside or after a subtree simply by
* comparing the call node index to the "selected index range". Example:
*
* ```
* before, 0
* before, 1
* before, 2
* before, 3
* before, 4
* before, 5
* before, 6
* before, 7
* before, 8
* before, 9
* before, 10
* before, 11
* before, 12
* selected, 13 <-- selected node
* selected, 14
* selected, 15
* selected, 16
* selected, 17
* selected, 18
* selected, 19
* selected, 20
* after, 21
* after, 22
* after, 23
* after, 24
* after, 25
* after, 26
* after, 27
* ```
*
* In this example, the selected node has index 13 and the "selected index range"
* is the range from 13 to 21 (not including 21).
*/
function mapCallNodeSelectedStatesToSamples(
sampleCallNodes: Array<IndexIntoCallNodeTable | null>,
activeTabFilteredCallNodes: Array<IndexIntoCallNodeTable | null>,
selectedCallNodeIndex: IndexIntoCallNodeTable,
selectedCallNodeDescendantsEndIndex: IndexIntoCallNodeTable
): SelectedState[] {
const sampleCount = sampleCallNodes.length;
const samplesSelectedStates = new Array(sampleCount);
for (let sampleIndex = 0; sampleIndex < sampleCount; sampleIndex++) {
let sampleSelectedState: SelectedState = 'SELECTED';
const callNodeIndex = sampleCallNodes[sampleIndex];
if (callNodeIndex !== null) {
if (callNodeIndex < selectedCallNodeIndex) {
sampleSelectedState = 'UNSELECTED_ORDERED_BEFORE_SELECTED';
} else if (callNodeIndex < selectedCallNodeDescendantsEndIndex) {
sampleSelectedState = 'SELECTED';
} else {
sampleSelectedState = 'UNSELECTED_ORDERED_AFTER_SELECTED';
}
} else {
// This sample was filtered out.
sampleSelectedState =
activeTabFilteredCallNodes[sampleIndex] === null
? // This sample was not part of the active tab.
'FILTERED_OUT_BY_ACTIVE_TAB'
: // This sample was filtered out in the transform pipeline.
'FILTERED_OUT_BY_TRANSFORM';
}
samplesSelectedStates[sampleIndex] = sampleSelectedState;
}
return samplesSelectedStates;
}
/**
* Go through the samples, and determine their current state with respect to
* the selection.
*
* This is used in the activity graph. The "ordering" is used so that samples
* from the same subtree (in the call tree) "clump together" in the graph.
*/
export function getSamplesSelectedStates(
callNodeInfo: CallNodeInfo,
sampleCallNodes: Array<IndexIntoCallNodeTable | null>,
activeTabFilteredCallNodes: Array<IndexIntoCallNodeTable | null>,
selectedCallNodeIndex: IndexIntoCallNodeTable | null
): SelectedState[] {
if (selectedCallNodeIndex === null || selectedCallNodeIndex === -1) {
return getSamplesSelectedStatesForNoSelection(
sampleCallNodes,
activeTabFilteredCallNodes
);
}
const callNodeTable = callNodeInfo.getCallNodeTable();
return mapCallNodeSelectedStatesToSamples(
sampleCallNodes,
activeTabFilteredCallNodes,
selectedCallNodeIndex,
callNodeTable.subtreeRangeEnd[selectedCallNodeIndex]
);
}
/**
* This function returns the function index for a specific call node path. This
* is the last element of this path, or the leaf element of the path.
*/
export function getLeafFuncIndex(path: CallNodePath): IndexIntoFuncTable {
if (path.length === 0) {
throw new Error("getLeafFuncIndex assumes that the path isn't empty.");
}
return path[path.length - 1];
}
export type JsImplementation =
| 'interpreter'
| 'blinterp'
| 'baseline'
| 'ion'
| 'unknown';
export type StackImplementation = 'native' | JsImplementation;
export type BreakdownByImplementation = { [StackImplementation]: Milliseconds };
export type OneCategoryBreakdown = {|
entireCategoryValue: Milliseconds,
subcategoryBreakdown: Milliseconds[], // { [IndexIntoSubcategoryList]: Milliseconds }
|};
export type BreakdownByCategory = OneCategoryBreakdown[]; // { [IndexIntoCategoryList]: OneCategoryBreakdown }
export type ItemTimings = {|
selfTime: {|
// time spent excluding children
value: Milliseconds,
breakdownByImplementation: BreakdownByImplementation | null,
breakdownByCategory: BreakdownByCategory | null,
|},
totalTime: {|
// time spent including children
value: Milliseconds,
breakdownByImplementation: BreakdownByImplementation | null,
breakdownByCategory: BreakdownByCategory | null,
|},
|};
export type TimingsForPath = {|
// timings for this path
forPath: ItemTimings,
rootTime: Milliseconds, // time for all the samples in the current tree
|};
/**
* This function is the same as getTimingsForCallNodeIndex, but accepts a CallNodePath
* instead of an IndexIntoCallNodeTable.
*/
export function getTimingsForPath(
needlePath: CallNodePath,
callNodeInfo: CallNodeInfo,
interval: Milliseconds,
thread: Thread,
unfilteredThread: Thread,
sampleIndexOffset: number,
categories: CategoryList,
samples: SamplesLikeTable,
unfilteredSamples: SamplesLikeTable,
displayImplementation: boolean
) {
return getTimingsForCallNodeIndex(
callNodeInfo.getCallNodeIndexFromPath(needlePath),
callNodeInfo,
interval,
thread,
unfilteredThread,
sampleIndexOffset,
categories,
samples,
unfilteredSamples,
displayImplementation
);
}
/**
* This function returns the timings for a specific call node. The algorithm is
* adjusted when the call tree is inverted.
* Note that the unfilteredThread should be the original thread before any filtering
* (by range or other) happens. Also sampleIndexOffset needs to be properly
* specified and is the offset to be applied on thread's indexes to access
* the same samples in unfilteredThread.
*/
export function getTimingsForCallNodeIndex(
needleNodeIndex: IndexIntoCallNodeTable | null,
callNodeInfo: CallNodeInfo,
interval: Milliseconds,
thread: Thread,
unfilteredThread: Thread,
sampleIndexOffset: number,
categories: CategoryList,
samples: SamplesLikeTable,
unfilteredSamples: SamplesLikeTable,
displayImplementation: boolean
): TimingsForPath {
/* ------------ Variables definitions ------------*/
// This is the data from the filtered thread that we'll loop over.
const { stringTable } = thread;
// This is the data from the unfiltered thread that we'll use to gather
// category and JS implementation information. Note that samples are offset by
// `sampleIndexOffset` because of range filtering.
const {
stackTable: unfilteredStackTable,
funcTable: unfilteredFuncTable,
frameTable: unfilteredFrameTable,
} = unfilteredThread;
// This holds the category index for the JavaScript category, so that we can
// use it to quickly check the category later on.
const javascriptCategoryIndex = categories.findIndex(
({ name }) => name === 'JavaScript'
);
// This object holds the timings for the current call node path, specified by
// needleNodeIndex.
const pathTimings: ItemTimings = {
selfTime: {
value: 0,
breakdownByImplementation: null,
breakdownByCategory: null,
},
totalTime: {
value: 0,
breakdownByImplementation: null,
breakdownByCategory: null,
},
};
// This holds the root time, it's incremented for all samples and is useful to
// have an absolute value to compare the other values with.
let rootTime = 0;
/* -------- End of variable definitions ------- */
/* ------------ Functions definitions --------- *
* We define functions here so that they have easy access to the variables and
* the algorithm's parameters. */
/**
* This function is called for native stacks. If the native stack has the
* 'JavaScript' category, then we move up the call tree to find the nearest
* ancestor that's JS and returns its JS implementation.
*/
function getImplementationForNativeStack(
unfilteredStackIndex: IndexIntoStackTable
): StackImplementation {
const category = unfilteredStackTable.category[unfilteredStackIndex];
if (category !== javascriptCategoryIndex) {
return 'native';
}
for (
let currentStackIndex = unfilteredStackIndex;
currentStackIndex !== null;
currentStackIndex = unfilteredStackTable.prefix[currentStackIndex]
) {
const frameIndex = unfilteredStackTable.frame[currentStackIndex];
const funcIndex = unfilteredFrameTable.func[frameIndex];
const isJS = unfilteredFuncTable.isJS[funcIndex];
if (isJS) {
return getImplementationForJsStack(frameIndex);
}
}
// No JS frame was found in the ancestors, this is weird but why not?
return 'native';
}
/**
* This function Returns the JS implementation information for a specific JS stack.
*/
function getImplementationForJsStack(
unfilteredFrameIndex: IndexIntoFrameTable
): JsImplementation {
const jsImplementationStrIndex =
unfilteredFrameTable.implementation[unfilteredFrameIndex];
if (jsImplementationStrIndex === null) {
return 'interpreter';
}
const jsImplementation = stringTable.getString(jsImplementationStrIndex);
switch (jsImplementation) {
case 'baseline':
case 'blinterp':
case 'ion':
return jsImplementation;
default:
return 'unknown';
}
}
function getImplementationForStack(
thisSampleIndex: IndexIntoSamplesTable
): StackImplementation {
const stackIndex =
unfilteredSamples.stack[thisSampleIndex + sampleIndexOffset];
if (stackIndex === null) {
// This should not happen in the unfiltered thread.
console.error('We got a null stack, this should not happen.');
return 'native';
}
const frameIndex = unfilteredStackTable.frame[stackIndex];
const funcIndex = unfilteredFrameTable.func[frameIndex];
const implementation = unfilteredFuncTable.isJS[funcIndex]
? getImplementationForJsStack(frameIndex)
: getImplementationForNativeStack(stackIndex);
return implementation;
}
/**
* This is a small utility function to more easily add data to breakdowns.
*/
function accumulateDataToTimings(
timings: {
breakdownByImplementation: BreakdownByImplementation | null,
breakdownByCategory: BreakdownByCategory | null,
value: number,
},
sampleIndex: IndexIntoSamplesTable,
duration: Milliseconds
): void {
// Step 1: increment the total value
timings.value += duration;
if (displayImplementation) {
// Step 2: find the implementation value for this sample
const implementation = getImplementationForStack(sampleIndex);
// Step 3: increment the right value in the implementation breakdown
if (timings.breakdownByImplementation === null) {
timings.breakdownByImplementation = {};
}
if (timings.breakdownByImplementation[implementation] === undefined) {
timings.breakdownByImplementation[implementation] = 0;
}
timings.breakdownByImplementation[implementation] += duration;
} else {
timings.breakdownByImplementation = null;
}
// step 4: find the category value for this stack. We want to use the
// category of the unfilteredThread.
const unfilteredStackIndex =
unfilteredSamples.stack[sampleIndex + sampleIndexOffset];
if (unfilteredStackIndex !== null) {
const categoryIndex = unfilteredStackTable.category[unfilteredStackIndex];
const subcategoryIndex =
unfilteredStackTable.subcategory[unfilteredStackIndex];
// step 5: increment the right value in the category breakdown
if (timings.breakdownByCategory === null) {
timings.breakdownByCategory = categories.map((category) => ({
entireCategoryValue: 0,
subcategoryBreakdown: Array(category.subcategories.length).fill(0),
}));
}