forked from firefox-devtools/profiler
-
Notifications
You must be signed in to change notification settings - Fork 0
/
profile-data.js
1647 lines (1500 loc) · 54.1 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 type {
Profile,
Thread,
SamplesTable,
StackTable,
ExtensionTable,
CategoryList,
FrameTable,
FuncTable,
ResourceTable,
IndexIntoCategoryList,
IndexIntoFuncTable,
IndexIntoSamplesTable,
IndexIntoStackTable,
ThreadIndex,
} from '../types/profile';
import type {
CallNodeInfo,
CallNodeTable,
CallNodePath,
IndexIntoCallNodeTable,
} from '../types/profile-derived';
import { CURRENT_VERSION as GECKO_PROFILE_VERSION } from './gecko-profile-versioning';
import { CURRENT_VERSION as PROCESSED_PROFILE_VERSION } from './processed-profile-versioning';
import type { Milliseconds, StartEndRange } from '../types/units';
import { timeCode } from '../utils/time-code';
import { hashPath } from '../utils/path';
import type { ImplementationFilter } from '../types/actions';
import bisection from 'bisection';
import type { UniqueStringArray } from '../utils/unique-string-array';
/**
* Various helpers for dealing with the profile as a data structure.
* @module profile-data
*/
export const resourceTypes = {
unknown: 0,
library: 1,
addon: 2,
webhost: 3,
otherhost: 4,
url: 5,
};
export const emptyExtensions: ExtensionTable = Object.freeze({
id: Object.freeze([]),
name: Object.freeze([]),
baseURL: Object.freeze([]),
length: 0,
});
export const defaultCategories: CategoryList = Object.freeze([
{ name: 'Idle', color: 'transparent' },
{ name: 'Other', color: 'grey' },
{ name: 'Layout', color: 'purple' },
{ name: 'JavaScript', color: 'yellow' },
{ name: 'GC / CC', color: 'orange' },
{ name: 'Network', color: 'lightblue' },
{ name: 'Graphics', color: 'green' },
{ name: 'DOM', color: 'blue' },
]);
/**
* Generate the CallNodeInfo which contains 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 getCallNodeInfo(
stackTable: StackTable,
frameTable: FrameTable,
funcTable: FuncTable,
defaultCategory: IndexIntoCategoryList
): CallNodeInfo {
return timeCode('getCallNodeInfo', () => {
const stackIndexToCallNodeIndex = new Uint32Array(stackTable.length);
const funcCount = funcTable.length;
// Maps can't key off of two items, so combine the prefixCallNode and the funcIndex
// using the following formula: prefixCallNode * funcCount + funcIndex => callNode
const prefixCallNodeAndFuncToCallNodeMap = new Map();
// The callNodeTable components.
const prefix: Array<IndexIntoCallNodeTable> = [];
const func: Array<IndexIntoFuncTable> = [];
const category: Array<IndexIntoCategoryList> = [];
const depth: Array<number> = [];
let length = 0;
function addCallNode(
prefixIndex: IndexIntoCallNodeTable,
funcIndex: IndexIntoFuncTable,
categoryIndex: IndexIntoCategoryList
) {
const index = length++;
prefix[index] = prefixIndex;
func[index] = funcIndex;
category[index] = categoryIndex;
if (prefixIndex === -1) {
depth[index] = 0;
} else {
depth[index] = depth[prefixIndex] + 1;
}
}
// 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 funcIndex = frameTable.func[frameIndex];
const prefixCallNodeAndFuncIndex = prefixCallNode * funcCount + funcIndex;
let callNodeIndex = prefixCallNodeAndFuncToCallNodeMap.get(
prefixCallNodeAndFuncIndex
);
if (callNodeIndex === undefined) {
callNodeIndex = length;
addCallNode(prefixCallNode, funcIndex, categoryIndex);
prefixCallNodeAndFuncToCallNodeMap.set(
prefixCallNodeAndFuncIndex,
callNodeIndex
);
} else if (category[callNodeIndex] !== categoryIndex) {
// Conflicting origin stack categories -> default category.
category[callNodeIndex] = defaultCategory;
}
stackIndexToCallNodeIndex[stackIndex] = callNodeIndex;
}
const callNodeTable: CallNodeTable = {
prefix: new Int32Array(prefix),
func: new Int32Array(func),
category: new Int32Array(category),
depth,
length,
};
return { callNodeTable, stackIndexToCallNodeIndex };
});
}
/**
* Take a samples table, and return an array that contain indexes that point to the
* leaf most call node, or null.
*/
export function getSampleCallNodes(
samples: SamplesTable,
stackIndexToCallNodeIndex: {
[key: IndexIntoStackTable]: IndexIntoCallNodeTable,
}
): Array<IndexIntoCallNodeTable | null> {
return samples.stack.map(stack => {
return stack === null ? null : stackIndexToCallNodeIndex[stack];
});
}
export type SelectedState =
// Samples can be filtered through various operations, like searching, or
// call tree transforms.
| 'FILTERED_OUT'
// This sample is selected because either the tip or an ancestor call node matches
// the currently selected call node.
| 'SELECTED'
// This call node is not selected, and the stacks are ordered before the selected
// call node as sorted by the getTreeOrderComparator.
| 'UNSELECTED_ORDERED_BEFORE_SELECTED'
// This call node is not selected, and the stacks are ordered after the selected
// call node as sorted by the getTreeOrderComparator.
| 'UNSELECTED_ORDERED_AFTER_SELECTED';
/**
* Go through the samples, and determine their current state.
*
* For samples that are neither 'FILTERED_OUT' nor 'SELECTED', this function compares
* the sample's call node to the selected call node, in tree order. It uses the same
* ordering as the function compareCallNodes in getTreeOrderComparator. But it does not
* call compareCallNodes with the selected node for each sample's call node, because doing
* so would recompute information about the selected call node on every call. Instead, it
* has an equivalent implementation that is faster because it only computes information
* about the selected call node's ancestors once.
*/
export function getSamplesSelectedStates(
callNodeTable: CallNodeTable,
sampleCallNodes: Array<IndexIntoCallNodeTable | null>,
selectedCallNodeIndex: IndexIntoCallNodeTable | null
): SelectedState[] {
const result = new Array(sampleCallNodes.length);
const selectedCallNodeDepth =
selectedCallNodeIndex === -1 || selectedCallNodeIndex === null
? 0
: callNodeTable.depth[selectedCallNodeIndex];
// Find all of the call nodes from the current depth to the root.
const selectedCallNodeAtDepth: IndexIntoCallNodeTable[] = new Array(
selectedCallNodeDepth
);
for (
let callNodeIndex = selectedCallNodeIndex, depth = selectedCallNodeDepth;
depth >= 0 && callNodeIndex !== null;
depth--, callNodeIndex = callNodeTable.prefix[callNodeIndex]
) {
selectedCallNodeAtDepth[depth] = callNodeIndex;
}
/**
* Take a call node, and compute its selected state.
*/
function getSelectedStateFromCallNode(
callNode: IndexIntoCallNodeTable | null
): SelectedState {
let callNodeIndex = callNode;
if (callNodeIndex === null) {
return 'FILTERED_OUT';
}
// Walk the call nodes toward the root, and get the call node at the the depth
// of the selected call node.
let depth = callNodeTable.depth[callNodeIndex];
while (depth > selectedCallNodeDepth) {
callNodeIndex = callNodeTable.prefix[callNodeIndex];
depth--;
}
if (callNodeIndex === selectedCallNodeIndex) {
// This sample's call node at the depth matches the selected call node.
return 'SELECTED';
}
// If we're here, it means that callNode is not selected, because it's not
// an ancestor of selectedCallNodeIndex.
// Determine if it's ordered "before" or "after" the selected call node,
// in order to provide a stable ordering when rendering visualizations.
// Walk the call nodes towards the root, until we find the common ancestor.
// Once we've found the common ancestor, compare the order of the two
// child nodes that we passed through, which are siblings.
while (true) {
const prevCallNodeIndex = callNodeIndex;
callNodeIndex = callNodeTable.prefix[callNodeIndex];
depth--;
if (
callNodeIndex === -1 ||
callNodeIndex === selectedCallNodeAtDepth[depth]
) {
// callNodeIndex is the lowest common ancestor of selectedCallNodeIndex
// and callNode. Compare the order of the two children that we passed
// through on the way up to the ancestor. These nodes are siblings, so
// their order is defined by the numerical order of call node indexes.
return prevCallNodeIndex <= selectedCallNodeAtDepth[depth + 1]
? 'UNSELECTED_ORDERED_BEFORE_SELECTED'
: 'UNSELECTED_ORDERED_AFTER_SELECTED';
}
}
// This code is unreachable, but Flow doesn't know that and thinks this
// function could return undefined. So throw an error.
/* eslint-disable no-unreachable */
throw new Error('unreachable');
/* eslint-enable no-unreachable */
}
// Go through each sample, and label its state.
for (
let sampleIndex = 0;
sampleIndex < sampleCallNodes.length;
sampleIndex++
) {
result[sampleIndex] = getSelectedStateFromCallNode(
sampleCallNodes[sampleIndex]
);
}
return result;
}
/**
* 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' | 'ion' | 'baseline' | 'unknown';
export type StackImplementation = 'native' | JsImplementation;
export type BreakdownByImplementation = { [StackImplementation]: Milliseconds };
type ItemTimings = {|
selfTime: {|
// time spent excluding children
value: Milliseconds,
breakdownByImplementation: BreakdownByImplementation | null,
|},
totalTime: {|
// time spent including children
value: Milliseconds,
breakdownByImplementation: BreakdownByImplementation | null,
|},
|};
export type TimingsForPath = {|
// timings for this path
forPath: ItemTimings,
// timings for this func across the tree
forFunc: ItemTimings,
rootTime: Milliseconds, // time for all the samples in the current tree
|};
/**
* This function Returns the JS implementation information for a specific stack.
*/
export function getJsImplementationForStack(
stackIndex: IndexIntoStackTable,
{ stackTable, frameTable, stringTable }: Thread
): JsImplementation {
const frameIndex = stackTable.frame[stackIndex];
const jsImplementationStrIndex = frameTable.implementation[frameIndex];
if (jsImplementationStrIndex === null) {
return 'interpreter';
}
const jsImplementation = stringTable.getString(jsImplementationStrIndex);
switch (jsImplementation) {
case 'baseline':
case 'ion':
return jsImplementation;
default:
return 'unknown';
}
}
/**
* This function returns the timings for a specific path. The algorithm is
* adjusted when the call tree is inverted.
*/
export function getTimingsForPath(
needlePath: CallNodePath,
{ callNodeTable, stackIndexToCallNodeIndex }: CallNodeInfo,
interval: number,
isInvertedTree: boolean,
thread: Thread
): TimingsForPath {
if (!needlePath.length) {
// If the path is empty, which shouldn't usually happen, we return an empty
// structure right away.
// The rest of this function's code assumes a non-empty path.
return {
forPath: {
selfTime: { value: 0, breakdownByImplementation: null },
totalTime: { value: 0, breakdownByImplementation: null },
},
forFunc: {
selfTime: { value: 0, breakdownByImplementation: null },
totalTime: { value: 0, breakdownByImplementation: null },
},
rootTime: 0,
};
}
const { samples, stackTable, funcTable } = thread;
const needleNodeIndex = getCallNodeIndexFromPath(needlePath, callNodeTable);
const needleFuncIndex = getLeafFuncIndex(needlePath);
const pathTimings: ItemTimings = {
selfTime: { value: 0, breakdownByImplementation: null },
totalTime: { value: 0, breakdownByImplementation: null },
};
const funcTimings: ItemTimings = {
selfTime: { value: 0, breakdownByImplementation: null },
totalTime: { value: 0, breakdownByImplementation: null },
};
let rootTime = 0;
/**
* This is a small utility function to more easily add data to breakdowns.
* The funcIndex could be computed from the stackIndex but is provided as an
* argument because it's been already computed when this function is called.
*/
function accumulateDataToTimings(
timings: {
breakdownByImplementation: BreakdownByImplementation | null,
value: number,
},
stackIndex: IndexIntoStackTable,
funcIndex: IndexIntoFuncTable
): void {
// Step 1: increment the total value
timings.value += interval;
// Step 2: find the implementation value for this stack
const implementation = funcTable.isJS[funcIndex]
? getJsImplementationForStack(stackIndex, thread)
: 'native';
// 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] += interval;
}
// Loop over each sample and accumulate the self time, running time, and
// the implementation breakdown.
for (const thisStackIndex of samples.stack) {
if (thisStackIndex === null) {
continue;
}
rootTime += interval;
const thisNodeIndex = stackIndexToCallNodeIndex[thisStackIndex];
const thisFunc = callNodeTable.func[thisNodeIndex];
if (!isInvertedTree) {
// For non-inverted trees, we compute the self time from the stacks' leaf nodes.
if (thisNodeIndex === needleNodeIndex) {
accumulateDataToTimings(pathTimings.selfTime, thisStackIndex, thisFunc);
}
if (thisFunc === needleFuncIndex) {
accumulateDataToTimings(funcTimings.selfTime, thisStackIndex, thisFunc);
}
}
// Use the stackTable to traverse the call node path and get various
// measurements.
// We don't use getCallNodePathFromIndex because we don't need the result
// itself, and it's costly to get. Moreover we can break out of the loop
// early if necessary.
let funcFound = false;
let pathFound = false;
let nextStackIndex;
for (
let currentStackIndex = thisStackIndex;
currentStackIndex !== null;
currentStackIndex = nextStackIndex
) {
const currentNodeIndex = stackIndexToCallNodeIndex[currentStackIndex];
const currentFuncIndex = callNodeTable.func[currentNodeIndex];
nextStackIndex = stackTable.prefix[currentStackIndex];
if (currentNodeIndex === needleNodeIndex) {
// One of the parents is the exact passed path.
// For non-inverted trees, we can contribute the data to the
// implementation breakdown now.
// Note that for inverted trees, we need to traverse up to the root node
// first, see below for this.
if (!isInvertedTree) {
accumulateDataToTimings(
pathTimings.totalTime,
thisStackIndex,
thisFunc
);
}
pathFound = true;
}
if (!funcFound && currentFuncIndex === needleFuncIndex) {
// One of the parents' func is the same function as the passed path.
// Note we could have the same function several times in the stack, so
// we need a boolean variable to prevent adding it more than once.
// The boolean variable will also be used to accumulate timings for
// inverted trees below.
if (!isInvertedTree) {
accumulateDataToTimings(
funcTimings.totalTime,
thisStackIndex,
thisFunc
);
}
funcFound = true;
}
// When the tree isn't inverted, we don't need to move further up the call
// node if we already found all the data.
// But for inverted trees, the selfTime is counted on the root node so we
// need to go on looping the stack until we find it.
if (!isInvertedTree && funcFound && pathFound) {
// As explained above, for non-inverted trees, we can break here if we
// found everything already.
break;
}
if (isInvertedTree && nextStackIndex === null) {
// This is an inverted tree, and we're at the root node because its
// prefix is `null`.
if (currentNodeIndex === needleNodeIndex) {
// This root node matches the passed call node path.
// This is the only place where we don't accumulate timings, mainly
// because this would be the same as for the total time.
pathTimings.selfTime.value += interval;
}
if (currentFuncIndex === needleFuncIndex) {
// This root node is the same function as the passed call node path.
accumulateDataToTimings(
funcTimings.selfTime,
currentStackIndex,
currentFuncIndex
);
}
if (pathFound) {
// We contribute the implementation information if the passed path was
// found in this stack earlier.
accumulateDataToTimings(
pathTimings.totalTime,
currentStackIndex,
currentFuncIndex
);
}
if (funcFound) {
// We contribute the implementation information if the leaf function
// of the passed path was found in this stack earlier.
accumulateDataToTimings(
funcTimings.totalTime,
currentStackIndex,
currentFuncIndex
);
}
}
}
}
return { forPath: pathTimings, forFunc: funcTimings, rootTime };
}
function _getTimeRangeForThread(
thread: Thread,
interval: number
): StartEndRange {
if (thread.samples.length === 0) {
return { start: Infinity, end: -Infinity };
}
return {
start: thread.samples.time[0],
end: thread.samples.time[thread.samples.length - 1] + interval,
};
}
export function getTimeRangeIncludingAllThreads(
profile: Profile
): StartEndRange {
const completeRange = { start: Infinity, end: -Infinity };
profile.threads.forEach(thread => {
const threadRange = _getTimeRangeForThread(thread, profile.meta.interval);
completeRange.start = Math.min(completeRange.start, threadRange.start);
completeRange.end = Math.max(completeRange.end, threadRange.end);
});
return completeRange;
}
export function defaultThreadOrder(threads: Thread[]): ThreadIndex[] {
// Put the compositor/renderer thread last.
const threadOrder = threads.map((thread, i) => i);
threadOrder.sort((a, b) => {
const nameA = threads[a].name;
const nameB = threads[b].name;
if (nameA === nameB) {
return a - b;
}
return nameA === 'Compositor' || nameA === 'Renderer' ? 1 : -1;
});
return threadOrder;
}
export function toValidImplementationFilter(
implementation: string
): ImplementationFilter {
switch (implementation) {
case 'cpp':
case 'js':
return implementation;
default:
return 'combined';
}
}
export function filterThreadByImplementation(
thread: Thread,
implementation: string,
defaultCategory: IndexIntoCategoryList
): Thread {
const { funcTable, stringTable } = thread;
switch (implementation) {
case 'cpp':
return _filterThreadByFunc(
thread,
funcIndex => {
// Return quickly if this is a JS frame.
if (funcTable.isJS[funcIndex]) {
return false;
}
// Regular C++ functions are associated with a resource that describes the
// shared library that these C++ functions were loaded from. Jitcode is not
// loaded from shared libraries but instead generated at runtime, so Jitcode
// frames are not associated with a shared library and thus have no resource
const locationString = stringTable.getString(
funcTable.name[funcIndex]
);
const isProbablyJitCode =
funcTable.resource[funcIndex] === -1 &&
locationString.startsWith('0x');
return !isProbablyJitCode;
},
defaultCategory
);
case 'js':
return _filterThreadByFunc(
thread,
funcIndex => funcTable.isJS[funcIndex],
defaultCategory
);
default:
return thread;
}
}
function _filterThreadByFunc(
thread: Thread,
filter: IndexIntoFuncTable => boolean,
defaultCategory: IndexIntoCallNodeTable
): Thread {
return timeCode('filterThread', () => {
const { stackTable, frameTable, samples } = thread;
const newStackTable = {
length: 0,
frame: [],
prefix: [],
category: [],
};
const oldStackToNewStack = new Map();
const frameCount = frameTable.length;
const prefixStackAndFrameToStack = new Map(); // prefixNewStack * frameCount + frame => newStackIndex
function convertStack(stackIndex) {
if (stackIndex === null) {
return null;
}
let newStack = oldStackToNewStack.get(stackIndex);
if (newStack === undefined) {
const prefixNewStack = convertStack(stackTable.prefix[stackIndex]);
const frameIndex = stackTable.frame[stackIndex];
const funcIndex = frameTable.func[frameIndex];
if (filter(funcIndex)) {
const prefixStackAndFrameIndex =
(prefixNewStack === null ? -1 : prefixNewStack) * frameCount +
frameIndex;
newStack = prefixStackAndFrameToStack.get(prefixStackAndFrameIndex);
if (newStack === undefined) {
newStack = newStackTable.length++;
newStackTable.prefix[newStack] = prefixNewStack;
newStackTable.frame[newStack] = frameIndex;
newStackTable.category[newStack] = stackTable.category[stackIndex];
} else if (
newStackTable.category[newStack] !== stackTable.category[stackIndex]
) {
// Conflicting origin stack categories -> default category.
newStackTable.category[newStack] = defaultCategory;
}
oldStackToNewStack.set(stackIndex, newStack);
prefixStackAndFrameToStack.set(prefixStackAndFrameIndex, newStack);
} else {
newStack = prefixNewStack;
}
}
return newStack;
}
const newSamples = Object.assign({}, samples, {
stack: samples.stack.map(oldStack => convertStack(oldStack)),
});
return Object.assign({}, thread, {
samples: newSamples,
stackTable: newStackTable,
});
});
}
/**
* Given a thread with stacks like below, collapse together the platform stack frames into
* a single pseudo platform stack frame. In the diagram "J" represents JavaScript stack
* frame timing, and "P" Platform stack frame timing. New psuedo-stack frames are created
* for the platform stacks.
*
* JJJJJJJJJJJJJJJJ ---> JJJJJJJJJJJJJJJJ
* PPPPPPPPPPPPPPPP PPPPPPPPPPPPPPPP
* PPPPPPPPPPPP JJJJJJJJ
* PPPPPPPP JJJ PPP
* JJJJJJJJ JJJ
* JJJ PPP
* JJJ
*
* @param {Object} thread - A thread.
* @returns {Object} The thread with collapsed samples.
*/
export function collapsePlatformStackFrames(thread: Thread): Thread {
return timeCode('collapsePlatformStackFrames', () => {
const { stackTable, funcTable, frameTable, samples, stringTable } = thread;
// Create new tables for the data.
const newStackTable: StackTable = {
length: 0,
frame: [],
category: [],
prefix: [],
};
const newFrameTable: FrameTable = {
length: frameTable.length,
implementation: frameTable.implementation.slice(),
optimizations: frameTable.optimizations.slice(),
line: frameTable.line.slice(),
column: frameTable.column.slice(),
category: frameTable.category.slice(),
func: frameTable.func.slice(),
address: frameTable.address.slice(),
};
const newFuncTable: FuncTable = {
length: funcTable.length,
name: funcTable.name.slice(),
resource: funcTable.resource.slice(),
relevantForJS: funcTable.relevantForJS.slice(),
address: funcTable.address.slice(),
isJS: funcTable.isJS.slice(),
fileName: funcTable.fileName.slice(),
lineNumber: funcTable.lineNumber.slice(),
columnNumber: funcTable.columnNumber.slice(),
};
// Create a Map that takes a prefix and frame as input, and maps it to the new stack
// index. Since Maps can't be keyed off of two values, do a little math to key off
// of both values: newStackPrefix * potentialFrameCount + frame => newStackIndex
const prefixStackAndFrameToStack = new Map();
const potentialFrameCount = newFrameTable.length * 2;
const oldStackToNewStack = new Map();
function convertStack(oldStack) {
if (oldStack === null) {
return null;
}
let newStack = oldStackToNewStack.get(oldStack);
if (newStack === undefined) {
// No stack was found, generate a new one.
const oldStackPrefix = stackTable.prefix[oldStack];
const newStackPrefix = convertStack(oldStackPrefix);
const frameIndex = stackTable.frame[oldStack];
const funcIndex = newFrameTable.func[frameIndex];
const oldStackIsPlatform = !newFuncTable.isJS[funcIndex];
let keepStackFrame = true;
if (oldStackIsPlatform) {
if (oldStackPrefix !== null) {
// Only keep the platform stack frame if the prefix is JS.
const prefixFrameIndex = stackTable.frame[oldStackPrefix];
const prefixFuncIndex = newFrameTable.func[prefixFrameIndex];
keepStackFrame = newFuncTable.isJS[prefixFuncIndex];
}
}
if (keepStackFrame) {
// Convert the old JS stack to a new JS stack.
const prefixStackAndFrameIndex =
(newStackPrefix === null ? -1 : newStackPrefix) *
potentialFrameCount +
frameIndex;
newStack = prefixStackAndFrameToStack.get(prefixStackAndFrameIndex);
if (newStack === undefined) {
newStack = newStackTable.length++;
newStackTable.prefix[newStack] = newStackPrefix;
newStackTable.category[newStack] = stackTable.category[oldStack];
if (oldStackIsPlatform) {
// Create a new platform frame
const newFuncIndex = newFuncTable.length++;
newFuncTable.name.push(stringTable.indexForString('Platform'));
newFuncTable.resource.push(-1);
newFuncTable.address.push(-1);
newFuncTable.isJS.push(false);
newFuncTable.fileName.push(null);
newFuncTable.lineNumber.push(null);
newFuncTable.columnNumber.push(null);
if (newFuncTable.name.length !== newFuncTable.length) {
console.error(
'length is not correct',
newFuncTable.name.length,
newFuncTable.length
);
}
newFrameTable.implementation.push(null);
newFrameTable.optimizations.push(null);
newFrameTable.line.push(null);
newFrameTable.column.push(null);
newFrameTable.category.push(null);
newFrameTable.func.push(newFuncIndex);
newFrameTable.address.push(-1);
newStackTable.frame[newStack] = newFrameTable.length++;
} else {
newStackTable.frame[newStack] = frameIndex;
}
}
oldStackToNewStack.set(oldStack, newStack);
prefixStackAndFrameToStack.set(prefixStackAndFrameIndex, newStack);
}
// If the the stack frame was not kept, use the prefix.
if (newStack === undefined) {
newStack = newStackPrefix;
}
}
return newStack;
}
const newSamples = Object.assign({}, samples, {
stack: samples.stack.map(oldStack => convertStack(oldStack)),
});
return Object.assign({}, thread, {
samples: newSamples,
stackTable: newStackTable,
frameTable: newFrameTable,
funcTable: newFuncTable,
});
});
}
export function filterThreadToSearchStrings(
thread: Thread,
searchStrings: string[] | null
): Thread {
return timeCode('filterThreadToSearchStrings', () => {
if (!searchStrings || !searchStrings.length) {
return thread;
}
return searchStrings.reduce(filterThreadToSearchString, thread);
});
}
export function filterThreadToSearchString(
thread: Thread,
searchString: string
): Thread {
if (!searchString) {
return thread;
}
const lowercaseSearchString = searchString.toLowerCase();
const {
samples,
funcTable,
frameTable,
stackTable,
stringTable,
resourceTable,
} = thread;
function computeFuncMatchesFilter(func) {
const nameIndex = funcTable.name[func];
const nameString = stringTable.getString(nameIndex);
if (nameString.toLowerCase().includes(lowercaseSearchString)) {
return true;
}
const fileNameIndex = funcTable.fileName[func];
if (fileNameIndex !== null) {
const fileNameString = stringTable.getString(fileNameIndex);
if (fileNameString.toLowerCase().includes(lowercaseSearchString)) {
return true;
}
}
const resourceIndex = funcTable.resource[func];
const resourceNameIndex = resourceTable.name[resourceIndex];
if (resourceNameIndex !== undefined) {
const resourceNameString = stringTable.getString(resourceNameIndex);
if (resourceNameString.toLowerCase().includes(lowercaseSearchString)) {
return true;
}
}
return false;
}
const funcMatchesFilterCache = new Map();
function funcMatchesFilter(func) {
let result = funcMatchesFilterCache.get(func);
if (result === undefined) {
result = computeFuncMatchesFilter(func);
funcMatchesFilterCache.set(func, result);
}
return result;
}
const stackMatchesFilterCache = new Map();
function stackMatchesFilter(stackIndex) {
if (stackIndex === null) {
return false;
}
let result = stackMatchesFilterCache.get(stackIndex);
if (result === undefined) {
const prefix = stackTable.prefix[stackIndex];
if (stackMatchesFilter(prefix)) {
result = true;
} else {
const frame = stackTable.frame[stackIndex];
const func = frameTable.func[frame];
result = funcMatchesFilter(func);
}
stackMatchesFilterCache.set(stackIndex, result);
}
return result;
}
return Object.assign({}, thread, {
samples: Object.assign({}, samples, {
stack: samples.stack.map(s => (stackMatchesFilter(s) ? s : null)),
}),
});
}
function _getSampleIndexRangeForSelection(
samples: SamplesTable,
rangeStart: number,
rangeEnd: number
): [IndexIntoSamplesTable, IndexIntoSamplesTable] {
// TODO: This should really use bisect. samples.time is sorted.
const firstSample = samples.time.findIndex(t => t >= rangeStart);
if (firstSample === -1) {
return [samples.length, samples.length];
}
const afterLastSample = samples.time
.slice(firstSample)
.findIndex(t => t >= rangeEnd);
if (afterLastSample === -1) {
return [firstSample, samples.length];
}
return [firstSample, firstSample + afterLastSample];
}
export function filterThreadSamplesToRange(
thread: Thread,
rangeStart: number,
rangeEnd: number
): Thread {
const { samples } = thread;
const [sBegin, sEnd] = _getSampleIndexRangeForSelection(
samples,
rangeStart,
rangeEnd
);
const newSamples = {
length: sEnd - sBegin,
time: samples.time.slice(sBegin, sEnd),
stack: samples.stack.slice(sBegin, sEnd),
responsiveness: samples.responsiveness.slice(sBegin, sEnd),
rss: samples.rss.slice(sBegin, sEnd),
uss: samples.uss.slice(sBegin, sEnd),
};
return Object.assign({}, thread, {
samples: newSamples,
});
}
// --------------- CallNodePath and CallNodeIndex manipulations ---------------
// Returns a list of CallNodeIndex from CallNodePaths. This function uses a map
// to speed up the look-up process.
export function getCallNodeIndicesFromPaths(
callNodePaths: CallNodePath[],
callNodeTable: CallNodeTable
): Array<IndexIntoCallNodeTable | null> {
// This is a Map<CallNodePathHash, IndexIntoCallNodeTable>. This map speeds up