forked from firefox-devtools/profiler
-
Notifications
You must be signed in to change notification settings - Fork 0
/
transforms.js
1481 lines (1407 loc) · 50.5 KB
/
transforms.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 {
uintArrayToString,
stringToUintArray,
} from '../utils/uintarray-encoding';
import {
toValidImplementationFilter,
getCallNodeIndexFromPath,
} from './profile-data';
import { timeCode } from '../utils/time-code';
import { assertExhaustiveCheck, convertToTransformType } from '../utils/flow';
import { CallTree } from '../profile-logic/call-tree';
import {
shallowCloneFrameTable,
shallowCloneFuncTable,
getEmptyStackTable,
} from './data-structures';
import { getFunctionName } from './function-info';
import type {
Thread,
FuncTable,
IndexIntoCategoryList,
IndexIntoFuncTable,
IndexIntoStackTable,
IndexIntoResourceTable,
} from '../types/profile';
import type {
CallNodePath,
CallNodeTable,
StackType,
} from '../types/profile-derived';
import type { ImplementationFilter } from '../types/actions';
import type {
Transform,
TransformType,
TransformStack,
} from '../types/transforms';
/**
* This file contains the functions and logic for working with and applying transforms
* to profile data.
*/
// Create mappings from a transform name, to a url-friendly short name.
const TRANSFORM_TO_SHORT_KEY: { [TransformType]: string } = {};
const SHORT_KEY_TO_TRANSFORM: { [string]: TransformType } = {};
[
'focus-subtree',
'focus-function',
'merge-call-node',
'merge-function',
'drop-function',
'collapse-resource',
'collapse-direct-recursion',
'collapse-function-subtree',
].forEach((transform: TransformType) => {
// This is kind of an awkward switch, but it ensures we've exhaustively checked that
// we have a mapping for every transform.
let shortKey;
switch (transform) {
case 'focus-subtree':
shortKey = 'f';
break;
case 'focus-function':
shortKey = 'ff';
break;
case 'merge-call-node':
shortKey = 'mcn';
break;
case 'merge-function':
shortKey = 'mf';
break;
case 'drop-function':
shortKey = 'df';
break;
case 'collapse-resource':
shortKey = 'cr';
break;
case 'collapse-direct-recursion':
shortKey = 'rec';
break;
case 'collapse-function-subtree':
shortKey = 'cfs';
break;
default: {
throw assertExhaustiveCheck(transform);
}
}
TRANSFORM_TO_SHORT_KEY[transform] = shortKey;
SHORT_KEY_TO_TRANSFORM[shortKey] = transform;
});
/**
* Map each transform key into a short representation.
*/
/**
* Every transform is separated by the "~" character.
* Each transform is made up of a tuple separated by "-"
* The first value in the tuple is a short key of the transform type.
*
* e.g "f-js-xFFpUMl-i" or "f-cpp-0KV4KV5KV61KV7KV8K"
*/
export function parseTransforms(stringValue: string = ''): TransformStack {
// Flow had some trouble with the `Transform | null` type, so use a forEach
// rather than a map.
const transforms = [];
stringValue.split('~').forEach(s => {
const tuple = s.split('-');
const shortKey = tuple[0];
const type = convertToTransformType(SHORT_KEY_TO_TRANSFORM[shortKey]);
if (type === null) {
console.error('Unrecognized transform was passed to the URL.', shortKey);
return;
}
// This switch breaks down each transform into the minimum amount of data needed
// to represent it in the URL. Each transform has slightly different requirements
// as defined in src/types/transforms.js.
switch (type) {
case 'collapse-resource': {
// e.g. "cr-js-325-8"
const [
,
implementation,
resourceIndexRaw,
collapsedFuncIndexRaw,
] = tuple;
const resourceIndex = parseInt(resourceIndexRaw, 10);
const collapsedFuncIndex = parseInt(collapsedFuncIndexRaw, 10);
if (isNaN(resourceIndex) || isNaN(collapsedFuncIndex)) {
break;
}
if (resourceIndex >= 0) {
transforms.push({
type,
resourceIndex,
collapsedFuncIndex,
implementation: toValidImplementationFilter(implementation),
});
}
break;
}
case 'collapse-direct-recursion': {
// e.g. "rec-js-325"
const [, implementation, funcIndexRaw] = tuple;
const funcIndex = parseInt(funcIndexRaw, 10);
if (isNaN(funcIndex) || funcIndex < 0) {
break;
}
transforms.push({
type,
funcIndex,
implementation: toValidImplementationFilter(implementation),
});
break;
}
case 'merge-function':
case 'focus-function':
case 'drop-function':
case 'collapse-function-subtree': {
// e.g. "mf-325"
const [, funcIndexRaw] = tuple;
const funcIndex = parseInt(funcIndexRaw, 10);
// Validate that the funcIndex makes sense.
if (!isNaN(funcIndex) && funcIndex >= 0) {
switch (type) {
case 'merge-function':
transforms.push({
type: 'merge-function',
funcIndex,
});
break;
case 'focus-function':
transforms.push({
type: 'focus-function',
funcIndex,
});
break;
case 'drop-function':
transforms.push({
type: 'drop-function',
funcIndex,
});
break;
case 'collapse-function-subtree':
transforms.push({
type: 'collapse-function-subtree',
funcIndex,
});
break;
default:
throw new Error('Unmatched transform.');
}
}
break;
}
case 'focus-subtree':
case 'merge-call-node': {
// e.g. "f-js-xFFpUMl-i" or "f-cpp-0KV4KV5KV61KV7KV8K"
const [
,
implementationRaw,
serializedCallNodePath,
invertedRaw,
] = tuple;
const implementation = toValidImplementationFilter(implementationRaw);
const callNodePath = stringToUintArray(serializedCallNodePath);
const inverted = Boolean(invertedRaw);
// Flow requires a switch because it can't deduce the type string correctly.
switch (type) {
case 'focus-subtree':
transforms.push({
type: 'focus-subtree',
implementation,
callNodePath,
inverted,
});
break;
case 'merge-call-node':
transforms.push({
type: 'merge-call-node',
implementation,
callNodePath,
});
break;
default:
throw new Error('Unmatched transform.');
}
break;
}
default:
throw assertExhaustiveCheck(type);
}
});
return transforms;
}
export function stringifyTransforms(transforms: TransformStack = []): string {
return transforms
.map(transform => {
const shortKey = TRANSFORM_TO_SHORT_KEY[transform.type];
if (!shortKey) {
throw new Error(
'Expected to be able to convert a transform into its short key.'
);
}
// This switch breaks down each transform into shared groups of what data
// they need, as defined in src/types/transforms.js. For instance some transforms
// need only a funcIndex, while some care about the current implemention, or
// other pieces of data.
switch (transform.type) {
case 'merge-function':
case 'drop-function':
case 'collapse-function-subtree':
case 'focus-function':
return `${shortKey}-${transform.funcIndex}`;
case 'collapse-resource':
return `${shortKey}-${transform.implementation}-${
transform.resourceIndex
}-${transform.collapsedFuncIndex}`;
case 'collapse-direct-recursion':
return `${shortKey}-${transform.implementation}-${
transform.funcIndex
}`;
case 'focus-subtree':
case 'merge-call-node': {
let string = [
shortKey,
transform.implementation,
uintArrayToString(transform.callNodePath),
].join('-');
if (transform.inverted) {
string += '-i';
}
return string;
}
default:
throw assertExhaustiveCheck(transform);
}
})
.join('~');
}
export function getTransformLabels(
thread: Thread,
threadName: string,
transforms: Transform[]
) {
const { funcTable, libs, stringTable, resourceTable } = thread;
const labels: string[] = transforms.map(transform => {
// Lookup library information.
if (transform.type === 'collapse-resource') {
const libIndex = resourceTable.lib[transform.resourceIndex];
let resourceName;
if (libIndex === undefined || libIndex === null || libIndex === -1) {
const nameIndex = resourceTable.name[transform.resourceIndex];
if (nameIndex === -1) {
throw new Error('Attempting to collapse a resource without a name');
}
resourceName = stringTable.getString(nameIndex);
} else {
resourceName = libs[libIndex].name;
}
return `Collapse: ${resourceName}`;
}
// Lookup function name.
let funcIndex;
switch (transform.type) {
case 'focus-subtree':
case 'merge-call-node':
funcIndex = transform.callNodePath[transform.callNodePath.length - 1];
break;
case 'focus-function':
case 'merge-function':
case 'drop-function':
case 'collapse-direct-recursion':
case 'collapse-function-subtree':
funcIndex = transform.funcIndex;
break;
default:
throw assertExhaustiveCheck(transform);
}
const nameIndex = funcTable.name[funcIndex];
const funcName = getFunctionName(stringTable.getString(nameIndex));
switch (transform.type) {
case 'focus-subtree':
return `Focus Node: ${funcName}`;
case 'focus-function':
return `Focus: ${funcName}`;
case 'merge-call-node':
return `Merge Node: ${funcName}`;
case 'merge-function':
return `Merge: ${funcName}`;
case 'drop-function':
return `Drop: ${funcName}`;
case 'collapse-direct-recursion':
return `Collapse recursion: ${funcName}`;
case 'collapse-function-subtree':
return `Collapse subtree: ${funcName}`;
default:
throw assertExhaustiveCheck(transform);
}
});
labels.unshift(`Complete "${threadName}"`);
return labels;
}
export function applyTransformToCallNodePath(
callNodePath: CallNodePath,
transform: Transform,
transformedThread: Thread
): CallNodePath {
switch (transform.type) {
case 'focus-subtree':
return _removePrefixPathFromCallNodePath(
transform.callNodePath,
callNodePath
);
case 'focus-function':
return _startCallNodePathWithFunction(transform.funcIndex, callNodePath);
case 'merge-call-node':
return _mergeNodeInCallNodePath(transform.callNodePath, callNodePath);
case 'merge-function':
return _mergeFunctionInCallNodePath(transform.funcIndex, callNodePath);
case 'drop-function':
return _dropFunctionInCallNodePath(transform.funcIndex, callNodePath);
case 'collapse-resource':
return _collapseResourceInCallNodePath(
transform.resourceIndex,
transform.collapsedFuncIndex,
transformedThread.funcTable,
callNodePath
);
case 'collapse-direct-recursion':
return _collapseDirectRecursionInCallNodePath(
transform.funcIndex,
callNodePath
);
case 'collapse-function-subtree':
return _collapseFunctionSubtreeInCallNodePath(
transform.funcIndex,
callNodePath
);
default:
throw assertExhaustiveCheck(transform);
}
}
function _removePrefixPathFromCallNodePath(
prefixPath: CallNodePath,
callNodePath: CallNodePath
): CallNodePath {
return _callNodePathHasPrefixPath(prefixPath, callNodePath)
? callNodePath.slice(prefixPath.length - 1)
: [];
}
function _startCallNodePathWithFunction(
funcIndex: IndexIntoFuncTable,
callNodePath: CallNodePath
): CallNodePath {
const startIndex = callNodePath.indexOf(funcIndex);
return startIndex === -1 ? [] : callNodePath.slice(startIndex);
}
function _mergeNodeInCallNodePath(
prefixPath: CallNodePath,
callNodePath: CallNodePath
): CallNodePath {
return _callNodePathHasPrefixPath(prefixPath, callNodePath)
? callNodePath.filter((_, i) => i !== prefixPath.length - 1)
: callNodePath;
}
function _mergeFunctionInCallNodePath(
funcIndex: IndexIntoFuncTable,
callNodePath: CallNodePath
): CallNodePath {
return callNodePath.filter(nodeFunc => nodeFunc !== funcIndex);
}
function _dropFunctionInCallNodePath(
funcIndex: IndexIntoFuncTable,
callNodePath: CallNodePath
): CallNodePath {
// If the CallNodePath contains the function, return an empty path.
return callNodePath.includes(funcIndex) ? [] : callNodePath;
}
function _collapseResourceInCallNodePath(
resourceIndex: IndexIntoResourceTable,
collapsedFuncIndex: IndexIntoFuncTable,
funcTable: FuncTable,
callNodePath: CallNodePath
) {
return (
callNodePath
// Map any collapsed functions into the collapsedFuncIndex
.map(pathFuncIndex => {
return funcTable.resource[pathFuncIndex] === resourceIndex
? collapsedFuncIndex
: pathFuncIndex;
})
// De-duplicate contiguous collapsed funcs
.filter(
(pathFuncIndex, pathIndex, path) =>
// This function doesn't match the previous one, so keep it.
pathFuncIndex !== path[pathIndex - 1] ||
// This function matched the previous, only keep it if doesn't match the
// collapsed func.
pathFuncIndex !== collapsedFuncIndex
)
);
}
function _collapseDirectRecursionInCallNodePath(
funcIndex: IndexIntoFuncTable,
callNodePath: CallNodePath
) {
const newPath = [];
let previousFunc;
for (let i = 0; i < callNodePath.length; i++) {
const pathFunc = callNodePath[i];
if (pathFunc !== funcIndex || pathFunc !== previousFunc) {
newPath.push(pathFunc);
}
previousFunc = pathFunc;
}
return newPath;
}
function _collapseFunctionSubtreeInCallNodePath(
funcIndex: IndexIntoFuncTable,
callNodePath: CallNodePath
) {
const index = callNodePath.indexOf(funcIndex);
return index === -1 ? callNodePath : callNodePath.slice(0, index + 1);
}
function _callNodePathHasPrefixPath(
prefixPath: CallNodePath,
callNodePath: CallNodePath
): boolean {
return (
prefixPath.length <= callNodePath.length &&
prefixPath.every((prefixFunc, i) => prefixFunc === callNodePath[i])
);
}
/**
* Take a CallNodePath, and invert it given a CallTree. Note that if the CallTree
* is itself inverted, you will get back the uninverted CallNodePath to the regular
* CallTree.
*
* e.g:
* (invertedPath, invertedCallTree) => path
* (path, callTree) => invertedPath
*
* Call trees are sorted with the CallNodes with the heaviest total time as the first
* entry. This function walks to the tip of the heaviest branches to find the leaf node,
* then construct an inverted CallNodePath with the result. This gives a pretty decent
* result, but it doesn't guarantee that it will select the heaviest CallNodePath for the
* INVERTED call tree. This would require doing a round trip through the reducers or
* some other mechanism in order to first calculate the next inverted call tree. This is
* probably not worth it, so go ahead and use the uninverted call tree, as it's probably
* good enough.
*/
export function invertCallNodePath(
path: CallNodePath,
callTree: CallTree,
callNodeTable: CallNodeTable
): CallNodePath {
let callNodeIndex = getCallNodeIndexFromPath(path, callNodeTable);
if (callNodeIndex === null) {
// No path was found, return an empty CallNodePath.
return [];
}
let children = [callNodeIndex];
const pathToLeaf = [];
do {
// Walk down the tree's depth to construct a path to the leaf node, this should
// be the heaviest branch of the tree.
callNodeIndex = children[0];
pathToLeaf.push(callNodeIndex);
children = callTree.getChildren(callNodeIndex);
} while (children && children.length > 0);
return (
pathToLeaf
// Map the CallNodeIndex to FuncIndex.
.map(index => callNodeTable.func[index])
// Reverse it so that it's in the proper inverted order.
.reverse()
);
}
/**
* Transform a thread's stacks to merge stacks that match the CallNodePath into
* the calling stack. See `src/types/transforms.js` for more information about the
* "merge-call-node" transform.
*/
export function mergeCallNode(
thread: Thread,
callNodePath: CallNodePath,
implementation: ImplementationFilter
): Thread {
return timeCode('mergeCallNode', () => {
const { stackTable, frameTable, samples } = thread;
// Depth here is 0 indexed.
const depthAtCallNodePathLeaf = callNodePath.length - 1;
const oldStackToNewStack: Map<
IndexIntoStackTable | null,
IndexIntoStackTable | null
> = new Map();
// A root stack's prefix will be null. Maintain that relationship from old to new
// stacks by mapping from null to null.
oldStackToNewStack.set(null, null);
const newStackTable = getEmptyStackTable();
// Provide two arrays to efficiently cache values for the algorithm. This probably
// could be refactored to use only one array here.
const stackDepths = [];
const stackMatches = [];
const funcMatchesImplementation = FUNC_MATCHES[implementation];
for (let stackIndex = 0; stackIndex < stackTable.length; stackIndex++) {
const prefix = stackTable.prefix[stackIndex];
const frameIndex = stackTable.frame[stackIndex];
const category = stackTable.category[stackIndex];
const subcategory = stackTable.subcategory[stackIndex];
const funcIndex = frameTable.func[frameIndex];
const doesPrefixMatch = prefix === null ? true : stackMatches[prefix];
const prefixDepth = prefix === null ? -1 : stackDepths[prefix];
const currentFuncOnPath = callNodePath[prefixDepth + 1];
let doMerge = false;
let stackDepth = prefixDepth;
let doesMatchCallNodePath;
if (doesPrefixMatch && stackDepth < depthAtCallNodePathLeaf) {
// This stack's prefixes were in our CallNodePath.
if (currentFuncOnPath === funcIndex) {
// This stack's function matches too!
doesMatchCallNodePath = true;
if (stackDepth + 1 === depthAtCallNodePathLeaf) {
// Holy cow, we found a match for our merge operation and can merge this stack.
doMerge = true;
} else {
// Since we found a match, increase the stack depth. This should match
// the depth of the implementation filtered stacks.
stackDepth++;
}
} else if (!funcMatchesImplementation(thread, funcIndex)) {
// This stack's function does not match the CallNodePath, however it's not part
// of the CallNodePath's implementation filter. Go ahead and keep it.
doesMatchCallNodePath = true;
} else {
// While all of the predecessors matched, this stack's function does not :(
doesMatchCallNodePath = false;
}
} else {
// This stack is not part of a matching branch of the tree.
doesMatchCallNodePath = false;
}
stackMatches[stackIndex] = doesMatchCallNodePath;
stackDepths[stackIndex] = stackDepth;
// Map the oldStackToNewStack, and only push on the stacks that aren't merged.
if (doMerge) {
const newStackPrefix = oldStackToNewStack.get(prefix);
oldStackToNewStack.set(
stackIndex,
newStackPrefix === undefined ? null : newStackPrefix
);
} else {
const newStackIndex = newStackTable.length++;
const newStackPrefix = oldStackToNewStack.get(prefix);
newStackTable.prefix[newStackIndex] =
newStackPrefix === undefined ? null : newStackPrefix;
newStackTable.frame[newStackIndex] = frameIndex;
newStackTable.category[newStackIndex] = category;
newStackTable.subcategory[newStackIndex] = subcategory;
oldStackToNewStack.set(stackIndex, newStackIndex);
}
}
const newSamples = {
...samples,
stack: samples.stack.map(oldStack => {
const newStack = oldStackToNewStack.get(oldStack);
if (newStack === undefined) {
throw new Error(
'Converting from the old stack to a new stack cannot be undefined'
);
}
return newStack;
}),
};
return {
...thread,
stackTable: newStackTable,
samples: newSamples,
};
});
}
/**
* Go through the StackTable and remove any stacks that are part of the given function.
* This operation effectively merges the timing of the stacks into their callers.
*/
export function mergeFunction(
thread: Thread,
funcIndexToMerge: IndexIntoFuncTable
): Thread {
const { stackTable, frameTable, samples } = thread;
const oldStackToNewStack: Map<
IndexIntoStackTable | null,
IndexIntoStackTable | null
> = new Map();
// A root stack's prefix will be null. Maintain that relationship from old to new
// stacks by mapping from null to null.
oldStackToNewStack.set(null, null);
const newStackTable = getEmptyStackTable();
for (let stackIndex = 0; stackIndex < stackTable.length; stackIndex++) {
const prefix = stackTable.prefix[stackIndex];
const frameIndex = stackTable.frame[stackIndex];
const category = stackTable.category[stackIndex];
const subcategory = stackTable.subcategory[stackIndex];
const funcIndex = frameTable.func[frameIndex];
if (funcIndex === funcIndexToMerge) {
const newStackPrefix = oldStackToNewStack.get(prefix);
oldStackToNewStack.set(
stackIndex,
newStackPrefix === undefined ? null : newStackPrefix
);
} else {
const newStackIndex = newStackTable.length++;
const newStackPrefix = oldStackToNewStack.get(prefix);
newStackTable.prefix[newStackIndex] =
newStackPrefix === undefined ? null : newStackPrefix;
newStackTable.frame[newStackIndex] = frameIndex;
newStackTable.category[newStackIndex] = category;
newStackTable.subcategory[newStackIndex] = subcategory;
oldStackToNewStack.set(stackIndex, newStackIndex);
}
}
const newSamples = {
...samples,
stack: samples.stack.map(oldStack => {
const newStack = oldStackToNewStack.get(oldStack);
if (newStack === undefined) {
throw new Error(
'Converting from the old stack to a new stack cannot be undefined'
);
}
return newStack;
}),
};
return {
...thread,
stackTable: newStackTable,
samples: newSamples,
};
}
/**
* Drop any samples that contain the given function.
*/
export function dropFunction(
thread: Thread,
funcIndexToDrop: IndexIntoFuncTable
) {
const { stackTable, frameTable, samples } = thread;
// Go through each stack, and label it as containing the function or not.
const stackContainsFunc: Array<void | true> = [];
for (let stackIndex = 0; stackIndex < stackTable.length; stackIndex++) {
const prefix = stackTable.prefix[stackIndex];
const frameIndex = stackTable.frame[stackIndex];
const funcIndex = frameTable.func[frameIndex];
if (
// This is the function we want to remove.
funcIndex === funcIndexToDrop ||
// The parent of this stack contained the function.
(prefix !== null && stackContainsFunc[prefix])
) {
stackContainsFunc[stackIndex] = true;
}
}
// Regenerate the stacks for the samples table.
const stack: Array<null | IndexIntoStackTable> = samples.stack.map(stack =>
stack !== null && stackContainsFunc[stack] ? null : stack
);
// Return the thread with the replaced samples.
return {
...thread,
samples: { ...samples, stack },
};
}
export function collapseResource(
thread: Thread,
resourceIndexToCollapse: IndexIntoResourceTable,
implementation: ImplementationFilter,
defaultCategory: IndexIntoCategoryList
): Thread {
const { stackTable, funcTable, frameTable, resourceTable, samples } = thread;
const resourceNameIndex = resourceTable.name[resourceIndexToCollapse];
const newFrameTable = shallowCloneFrameTable(frameTable);
const newFuncTable = shallowCloneFuncTable(funcTable);
const newStackTable = getEmptyStackTable();
const oldStackToNewStack: Map<
IndexIntoStackTable | null,
IndexIntoStackTable | null
> = new Map();
const prefixStackToCollapsedStack: Map<
IndexIntoStackTable | null, // prefix stack index
IndexIntoStackTable | null // collapsed stack index
> = new Map();
const collapsedStacks: Set<IndexIntoStackTable | null> = new Set();
const funcMatchesImplementation = FUNC_MATCHES[implementation];
// A root stack's prefix will be null. Maintain that relationship from old to new
// stacks by mapping from null to null.
oldStackToNewStack.set(null, null);
// A new func and frame will be created on the first stack that is found that includes
// the given resource.
let collapsedFrameIndex;
let collapsedFuncIndex;
for (let stackIndex = 0; stackIndex < stackTable.length; stackIndex++) {
const prefix = stackTable.prefix[stackIndex];
const frameIndex = stackTable.frame[stackIndex];
const category = stackTable.category[stackIndex];
const subcategory = stackTable.subcategory[stackIndex];
const funcIndex = frameTable.func[frameIndex];
const resourceIndex = funcTable.resource[funcIndex];
const newStackPrefix = oldStackToNewStack.get(prefix);
if (newStackPrefix === undefined) {
throw new Error('newStackPrefix must not be undefined');
}
if (resourceIndex === resourceIndexToCollapse) {
// The stack matches this resource.
if (!collapsedStacks.has(newStackPrefix)) {
// The prefix is not a collapsed stack. So this stack will not collapse into its
// prefix stack. But it might collapse into a sibling stack, if there exists a
// sibling with the same resource. Check if a collapsed stack with the same
// prefix (i.e. a collapsed sibling) exists.
const existingCollapsedStack = prefixStackToCollapsedStack.get(prefix);
if (existingCollapsedStack === undefined) {
// Create a new collapsed frame.
// Compute the next indexes
const newStackIndex = newStackTable.length++;
collapsedStacks.add(newStackIndex);
oldStackToNewStack.set(stackIndex, newStackIndex);
prefixStackToCollapsedStack.set(prefix, newStackIndex);
if (collapsedFrameIndex === undefined) {
collapsedFrameIndex = newFrameTable.length++;
collapsedFuncIndex = newFuncTable.length++;
// Add the collapsed frame
newFrameTable.address.push(frameTable.address[frameIndex]);
newFrameTable.category.push(frameTable.category[frameIndex]);
newFrameTable.subcategory.push(frameTable.subcategory[frameIndex]);
newFrameTable.func.push(collapsedFuncIndex);
newFrameTable.line.push(frameTable.line[frameIndex]);
newFrameTable.column.push(frameTable.column[frameIndex]);
newFrameTable.implementation.push(
frameTable.implementation[frameIndex]
);
newFrameTable.optimizations.push(
frameTable.optimizations[frameIndex]
);
// Add the psuedo-func
newFuncTable.address.push(funcTable.address[funcIndex]);
newFuncTable.isJS.push(funcTable.isJS[funcIndex]);
newFuncTable.name.push(resourceNameIndex);
newFuncTable.resource.push(funcTable.resource[funcIndex]);
newFuncTable.fileName.push(funcTable.fileName[funcIndex]);
newFuncTable.lineNumber.push(null);
newFuncTable.columnNumber.push(null);
}
// Add the new stack.
newStackTable.prefix.push(newStackPrefix);
newStackTable.frame.push(collapsedFrameIndex);
newStackTable.category.push(category);
newStackTable.subcategory.push(subcategory);
} else {
// A collapsed stack at this level already exists, use that one.
if (existingCollapsedStack === null) {
throw new Error('existingCollapsedStack cannot be null');
}
oldStackToNewStack.set(stackIndex, existingCollapsedStack);
if (newStackTable.category[existingCollapsedStack] !== category) {
// Conflicting origin stack categories -> default category + subcategory.
newStackTable.category[existingCollapsedStack] = defaultCategory;
newStackTable.subcategory[existingCollapsedStack] = 0;
} else if (
newStackTable.subcategory[existingCollapsedStack] !== subcategory
) {
// Conflicting origin stack subcategories -> "Other" subcategory.
newStackTable.subcategory[existingCollapsedStack] = 0;
}
}
} else {
// The prefix was already collapsed, use that one.
oldStackToNewStack.set(stackIndex, newStackPrefix);
}
} else {
if (
!funcMatchesImplementation(thread, funcIndex) &&
newStackPrefix !== null
) {
// This function doesn't match the implementation filter.
const prefixFrame = newStackTable.frame[newStackPrefix];
const prefixFunc = newFrameTable.func[prefixFrame];
const prefixResource = newFuncTable.resource[prefixFunc];
if (prefixResource === resourceIndexToCollapse) {
// This stack's prefix did match the collapsed resource, map the stack
// to the already collapsed stack and move on.
oldStackToNewStack.set(stackIndex, newStackPrefix);
continue;
}
}
// This stack isn't part of the collapsed resource. Copy over the previous stack.
const newStackIndex = newStackTable.length++;
newStackTable.prefix.push(newStackPrefix);
newStackTable.frame.push(frameIndex);
newStackTable.category.push(category);
newStackTable.subcategory.push(subcategory);
oldStackToNewStack.set(stackIndex, newStackIndex);
}
}
const newSamples = {
...samples,
stack: samples.stack.map(oldStack => {
const newStack = oldStackToNewStack.get(oldStack);
if (newStack === undefined) {
throw new Error(
'Converting from the old stack to a new stack cannot be undefined'
);
}
return newStack;
}),
};
return {
...thread,
stackTable: newStackTable,
frameTable: newFrameTable,
funcTable: newFuncTable,
samples: newSamples,
};
}
export function collapseDirectRecursion(
thread: Thread,
funcToCollapse: IndexIntoFuncTable,
implementation: ImplementationFilter
): Thread {
const { stackTable, frameTable, samples } = thread;
const oldStackToNewStack: Map<
IndexIntoStackTable | null,
IndexIntoStackTable | null
> = new Map();
// A root stack's prefix will be null. Maintain that relationship from old to new
// stacks by mapping from null to null.
oldStackToNewStack.set(null, null);
const recursiveStacks = new Set();
const newStackTable = getEmptyStackTable();
const funcMatchesImplementation = FUNC_MATCHES[implementation];
for (let stackIndex = 0; stackIndex < stackTable.length; stackIndex++) {
const prefix = stackTable.prefix[stackIndex];
const frameIndex = stackTable.frame[stackIndex];
const category = stackTable.category[stackIndex];
const subcategory = stackTable.subcategory[stackIndex];
const funcIndex = frameTable.func[frameIndex];
if (
// The previous stacks were collapsed or matched the funcToCollapse, check to see
// if this is a candidate for collapsing as well.
recursiveStacks.has(prefix) &&
// Either the function must match, or the implementation must be different.
(funcToCollapse === funcIndex ||
!funcMatchesImplementation(thread, funcIndex))
) {
// Out of N consecutive stacks that match the function to collapse, only remove
// stacks that are N > 1.
const newPrefixStackIndex = oldStackToNewStack.get(prefix);
if (newPrefixStackIndex === undefined) {
throw new Error('newPrefixStackIndex cannot be undefined');
}
oldStackToNewStack.set(stackIndex, newPrefixStackIndex);
recursiveStacks.add(stackIndex);
} else {
// Add a stack in two cases:
// 1. It doesn't match the collapse requirements.
// 2. It is the first instance of a stack to collapse, re-use the stack and frame
// information for the collapsed stack.
const newStackIndex = newStackTable.length++;
const newStackPrefix = oldStackToNewStack.get(prefix);
if (newStackPrefix === undefined) {
throw new Error(
'The newStackPrefix must exist because prefix < stackIndex as the StackTable is ordered.'
);
}
newStackTable.prefix[newStackIndex] = newStackPrefix;
newStackTable.frame[newStackIndex] = frameIndex;
newStackTable.category[newStackIndex] = category;
newStackTable.subcategory[newStackIndex] = subcategory;
oldStackToNewStack.set(stackIndex, newStackIndex);
if (funcToCollapse === funcIndex) {
recursiveStacks.add(stackIndex);
}
}
}
const newSamples = {
...samples,
stack: samples.stack.map(oldStack => {
const newStack = oldStackToNewStack.get(oldStack);
if (newStack === undefined) {
throw new Error(
'Converting from the old stack to a new stack cannot be undefined'
);
}
return newStack;
}),
};
return {
...thread,
stackTable: newStackTable,
samples: newSamples,
};
}
const FUNC_MATCHES = {
combined: (_thread: Thread, _funcIndex: IndexIntoFuncTable) => true,
cpp: (thread: Thread, funcIndex: IndexIntoFuncTable): boolean => {
const { funcTable, stringTable } = thread;
// Return quickly if this is a JS frame.