forked from firefox-devtools/profiler
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprocess-profile.js
2086 lines (1915 loc) · 69.4 KB
/
process-profile.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 { attemptToConvertChromeProfile } from './import/chrome';
import { attemptToConvertDhat } from './import/dhat';
import { AddressLocator } from './address-locator';
import { UniqueStringArray } from '../utils/unique-string-array';
import {
resourceTypes,
getEmptyExtensions,
getEmptyFuncTable,
getEmptyResourceTable,
getEmptyRawMarkerTable,
getEmptyJsAllocationsTable,
getEmptyUnbalancedNativeAllocationsTable,
getEmptyNativeSymbolTable,
} from './data-structures';
import { immutableUpdate, ensureExists, coerce } from '../utils/flow';
import { attemptToUpgradeProcessedProfileThroughMutation } from './processed-profile-versioning';
import { upgradeGeckoProfileToCurrentVersion } from './gecko-profile-versioning';
import {
isPerfScriptFormat,
convertPerfScriptProfile,
} from './import/linux-perf';
import { isArtTraceFormat, convertArtTraceProfile } from './import/art-trace';
import {
PROCESSED_PROFILE_VERSION,
INTERVAL,
INTERVAL_END,
INSTANT,
} from '../app-logic/constants';
import {
getFriendlyThreadName,
getOrCreateURIResource,
nudgeReturnAddresses,
} from '../profile-logic/profile-data';
import { convertJsTracerToThread } from '../profile-logic/js-tracer';
import type {
Profile,
Thread,
Counter,
ExtensionTable,
CategoryList,
FrameTable,
SamplesTable,
StackTable,
RawMarkerTable,
Lib,
LibMapping,
FuncTable,
ResourceTable,
IndexIntoLibs,
IndexIntoStackTable,
IndexIntoFuncTable,
IndexIntoStringTable,
IndexIntoResourceTable,
JsTracerTable,
JsAllocationsTable,
ProfilerOverhead,
NativeAllocationsTable,
Milliseconds,
Microseconds,
Address,
GeckoCounter,
GeckoProfile,
GeckoSubprocessProfile,
GeckoThread,
GeckoMarkers,
GeckoMarkerStruct,
GeckoMarkerTuple,
GeckoFrameStruct,
GeckoSampleStruct,
GeckoStackStruct,
GeckoProfilerOverhead,
GCSliceMarkerPayload,
GCMajorMarkerPayload,
MarkerPayload,
MarkerPayload_Gecko,
GCSliceData_Gecko,
GCMajorCompleted,
GCMajorCompleted_Gecko,
GCMajorAborted,
PhaseTimes,
SerializableProfile,
ExternalMarkersData,
MarkerSchema,
ProfileMeta,
PageList,
ThreadIndex,
BrowsertimeMarkerPayload,
MarkerPhase,
Pid,
} from 'firefox-profiler/types';
type RegExpResult = null | string[];
/**
* Module for converting a Gecko profile into the 'processed' format.
* @module process-profile
*/
/**
* Turn a data table from the form `{ schema, data }` (as used in the Gecko profile
* JSON) into a struct of arrays. This isn't very nice to read, but it
* drastically reduces the number of JS objects the JS engine has to deal with,
* resulting in fewer GC pauses and hopefully better performance.
*
* e.g Take geckoTable A data table of the form
* `{ schema, data }`.
* And turn it into a data table of the form
* `{ length: number, field1: array, field2: array }`
*/
function _toStructOfArrays(geckoTable: any): any {
const result = { length: geckoTable.data.length };
for (const fieldName in geckoTable.schema) {
const fieldIndex = geckoTable.schema[fieldName];
if (typeof fieldIndex !== 'number') {
throw new Error(
'fieldIndex must be a number in the Gecko profile table.'
);
}
result[fieldName] = geckoTable.data.map((entry) =>
fieldIndex in entry ? entry[fieldIndex] : null
);
}
return result;
}
/**
* JS File information sometimes comes with multiple URIs which are chained
* with " -> ". We only want the last URI in this list.
*/
function _getRealScriptURI(url: string): string {
if (url) {
const urls = url.split(' -> ');
return urls[urls.length - 1];
}
return url;
}
function _sortMarkers(markers: GeckoMarkers): GeckoMarkers {
const { startTime, endTime } = markers.schema;
const sortedData = markers.data.slice(0);
// Sort the markers based on their startTime. If there is no startTime, then use
// endtime.
sortedData.sort((a, b) => {
const aTime: null | Milliseconds = a[endTime] || a[startTime];
const bTime: null | Milliseconds = b[endTime] || b[startTime];
if (aTime === null) {
console.error(a);
throw new Error('A marker had null start and end time.');
}
if (bTime === null) {
console.error(b);
throw new Error('A marker had null start and end time.');
}
return aTime - bTime;
});
return Object.assign({}, markers, { data: sortedData });
}
function _cleanFunctionName(functionName: string): string {
const ignoredPrefix = 'non-virtual thunk to ';
if (functionName.startsWith && functionName.startsWith(ignoredPrefix)) {
return functionName.substr(ignoredPrefix.length);
}
return functionName;
}
/**
* GlobalDataCollector collects data which is global in the processed profile
* format but per-process or per-thread in the Gecko profile format. It
* de-duplicates elements and builds one shared list of each type.
* For now it only de-duplicates libraries, but in the future we may move more
* tables to be global.
* You could also call this class an "interner".
*/
export class GlobalDataCollector {
_libs: Lib[] = [];
_libKeyToLibIndex: Map<string, IndexIntoLibs> = new Map();
// Return the global index for this library, adding it to the global list if
// necessary.
indexForLib(libMapping: LibMapping | Lib): IndexIntoLibs {
const { debugName, breakpadId } = libMapping;
const libKey = `${debugName}/${breakpadId}`;
let index = this._libKeyToLibIndex.get(libKey);
if (index === undefined) {
index = this._libs.length;
const { arch, name, path, debugPath, codeId } = libMapping;
this._libs.push({
arch,
name,
path,
debugName,
debugPath,
breakpadId,
codeId: codeId ?? null,
});
this._libKeyToLibIndex.set(libKey, index);
}
return index;
}
// Package up all de-duplicated global tables so that they can be embedded in
// the profile.
finish(): {| libs: Lib[] |} {
return { libs: this._libs };
}
}
type ExtractionInfo = {
funcTable: FuncTable,
resourceTable: ResourceTable,
stringTable: UniqueStringArray,
addressLocator: AddressLocator,
libToResourceIndex: Map<IndexIntoLibs, IndexIntoResourceTable>,
originToResourceIndex: Map<string, IndexIntoResourceTable>,
libNameToResourceIndex: Map<IndexIntoStringTable, IndexIntoResourceTable>,
stringToNewFuncIndexAndFrameAddress: Map<
string,
{ funcIndex: IndexIntoFuncTable, frameAddress: Address | null },
>,
globalDataCollector: GlobalDataCollector,
};
/**
* Resources and funcs are not part of the Gecko Profile format. This information is
* implicitly defined in the frame tables' location strings. This function derives a new
* FuncTable and ResourceTable for easily accesing this information in a structred format.
*
* The returned IndexIntoFuncTable[] value maps the index of each element in the
* frameLocations array to a func from the returned FuncTable.
*/
export function extractFuncsAndResourcesFromFrameLocations(
frameLocations: IndexIntoStringTable[],
relevantForJSPerFrame: boolean[],
stringTable: UniqueStringArray,
libs: LibMapping[],
extensions: ExtensionTable = getEmptyExtensions(),
globalDataCollector: GlobalDataCollector
): {
funcTable: FuncTable,
resourceTable: ResourceTable,
frameFuncs: IndexIntoFuncTable[],
frameAddresses: (Address | null)[],
} {
// Important! If the flow type for the FuncTable was changed, update all the functions
// in this file that start with the word "extract".
const funcTable = getEmptyFuncTable();
// Important! If the flow type for the ResourceTable was changed, update all the functions
// in this file that start with the word "extract".
const resourceTable = getEmptyResourceTable();
// Bundle all of the variables up into an object to pass them around to functions.
const extractionInfo: ExtractionInfo = {
funcTable,
resourceTable,
stringTable,
addressLocator: new AddressLocator(libs),
libToResourceIndex: new Map(),
originToResourceIndex: new Map(),
libNameToResourceIndex: new Map(),
stringToNewFuncIndexAndFrameAddress: new Map(),
globalDataCollector,
};
for (let i = 0; i < extensions.length; i++) {
_addExtensionOrigin(extractionInfo, extensions, i);
}
// Go through every frame location string, and deduce the function and resource
// information by applying various string matching heuristics.
const frameFuncs = [];
const frameAddresses = [];
for (let frameIndex = 0; frameIndex < frameLocations.length; frameIndex++) {
const locationIndex = frameLocations[frameIndex];
const locationString = stringTable.getString(locationIndex);
const relevantForJS = relevantForJSPerFrame[frameIndex];
const info =
extractionInfo.stringToNewFuncIndexAndFrameAddress.get(locationString);
if (info !== undefined) {
// The location string was already processed.
const { funcIndex, frameAddress } = info;
frameFuncs.push(funcIndex);
frameAddresses.push(frameAddress);
continue;
}
// These nested `if` branches check for 3 cases for constructing function and
// resource information.
let funcIndex = null;
let frameAddress = null;
const unsymbolicatedInfo = _extractUnsymbolicatedFunction(
extractionInfo,
locationString,
locationIndex
);
if (unsymbolicatedInfo !== null) {
funcIndex = unsymbolicatedInfo.funcIndex;
frameAddress = unsymbolicatedInfo.frameAddress;
} else {
funcIndex = _extractCppFunction(extractionInfo, locationString);
if (funcIndex === null) {
funcIndex = _extractJsFunction(extractionInfo, locationString);
if (funcIndex === null) {
funcIndex = _extractUnknownFunctionType(
extractionInfo,
locationIndex,
relevantForJS
);
}
}
}
// Cache the above results.
extractionInfo.stringToNewFuncIndexAndFrameAddress.set(locationString, {
funcIndex,
frameAddress,
});
frameFuncs.push(funcIndex);
frameAddresses.push(frameAddress);
}
return {
funcTable: extractionInfo.funcTable,
resourceTable: extractionInfo.resourceTable,
frameFuncs,
frameAddresses,
};
}
/**
* Given a location string that looks like a memory address, e.g. "0xfe9a097e0", treat
* it as an unsymblicated memory address and add a new function for it to the function table.
* This happens before we have any symbol info, so we do not know which addresses fall
* into the same function, so cannot do any function grouping. So we get one "function" per
* address.
* We also associate the address with the library that contains it, and convert the address
* into a library-relative offset. This association is established via the function's
* "resource": The function points to the resource (of type resourceTypes.library), and the
* resource has the index to the library in thread.libs.
* We return the index of the newly-added function, and the address as a library-relative
* offset.
*/
function _extractUnsymbolicatedFunction(
extractionInfo: ExtractionInfo,
locationString: string,
locationIndex: IndexIntoStringTable
): { funcIndex: IndexIntoFuncTable, frameAddress: Address } | null {
if (!locationString.startsWith('0x')) {
return null;
}
const {
addressLocator,
libToResourceIndex,
resourceTable,
funcTable,
stringTable,
} = extractionInfo;
let resourceIndex = -1;
let addressRelativeToLib: Address = -1;
try {
// The frame address, as observed in the profiled process. This address was
// valid in the (virtual memory) address space of the profiled process.
// It can be a very large u64 value, larger than Number.MAX_SAFE_INTEGER.
// To make sure we don't lose precision, we leave it as a hex string.
const addressHex = locationString;
// We want to turn this address into a library-relative offset.
// Look up to see if it falls into one of the libraries that were mapped into
// the profiled process, according to the libs list.
// This call will throw if addressHex is not a valid hex number.
const { lib, relativeAddress } = addressLocator.locateAddress(addressHex);
if (lib !== null) {
// Yes, we found the library whose mapping covers this address!
addressRelativeToLib = relativeAddress;
const libIndex = extractionInfo.globalDataCollector.indexForLib(lib);
resourceIndex = libToResourceIndex.get(libIndex);
if (resourceIndex === undefined) {
// This library doesn't exist in the libs array, insert it. This resou
// A lib resource is a systems-level compiled library, for example "XUL",
// "AppKit", or "CoreFoundation".
resourceIndex = resourceTable.length++;
resourceTable.lib[resourceIndex] = libIndex;
resourceTable.name[resourceIndex] = stringTable.indexForString(
lib.name
);
resourceTable.host[resourceIndex] = null;
resourceTable.type[resourceIndex] = resourceTypes.library;
libToResourceIndex.set(libIndex, resourceIndex);
}
}
} catch (e) {
// Probably a hex parse error. Ignore.
}
// Add the function to the funcTable.
const funcIndex = funcTable.length++;
funcTable.name[funcIndex] = locationIndex;
funcTable.resource[funcIndex] = resourceIndex;
funcTable.relevantForJS[funcIndex] = false;
funcTable.isJS[funcIndex] = false;
funcTable.fileName[funcIndex] = null;
funcTable.lineNumber[funcIndex] = null;
funcTable.columnNumber[funcIndex] = null;
return { funcIndex, frameAddress: addressRelativeToLib };
}
/**
* Given a location string that looks like a C++ function (by matching various regular
* expressions) e.g. "functionName (in library name)", this function will classify it
* as a C++ function, and add the library resource information if it's not already
* present.
*/
function _extractCppFunction(
extractionInfo: ExtractionInfo,
locationString: string
): IndexIntoFuncTable | null {
// Check for a C++ location string.
const cppMatch: RegExpResult =
// Given: "functionName (in library name) + 1234"
// Captures: 1^^^^^^^^^^^ 2^^^^^^^^^^^ 3^^^
/^(.*) \(in ([^)]*)\) (\+ [0-9]+)$/.exec(locationString) ||
// Given: "functionName (in library name) (1234:1234)"
// Captures: 1^^^^^^^^^^^ 2^^^^^^^^^^^ 3^^^^^^^^
/^(.*) \(in ([^)]*)\) (\(.*:.*\))$/.exec(locationString) ||
// Given: "functionName (in library name)"
// Captures: 1^^^^^^^^^^^ 2^^^^^^^^^^^
/^(.*) \(in ([^)]*)\)$/.exec(locationString);
if (!cppMatch) {
return null;
}
const {
funcTable,
stringTable,
stringToNewFuncIndexAndFrameAddress,
libNameToResourceIndex,
resourceTable,
} = extractionInfo;
const [, funcNameRaw, libraryNameString] = cppMatch;
const funcName = _cleanFunctionName(funcNameRaw);
const funcNameIndex = stringTable.indexForString(funcName);
const libraryNameStringIndex = stringTable.indexForString(libraryNameString);
const frameInfo = stringToNewFuncIndexAndFrameAddress.get(funcName);
if (frameInfo !== undefined) {
// Do not insert a new function.
return frameInfo.funcIndex;
}
let resourceIndex = libNameToResourceIndex.get(libraryNameStringIndex);
if (resourceIndex === undefined) {
resourceIndex = resourceTable.length++;
libNameToResourceIndex.set(libraryNameStringIndex, resourceIndex);
resourceTable.lib[resourceIndex] = null;
resourceTable.name[resourceIndex] = libraryNameStringIndex;
resourceTable.host[resourceIndex] = null;
resourceTable.type[resourceIndex] = resourceTypes.library;
}
const newFuncIndex = funcTable.length++;
funcTable.name[newFuncIndex] = funcNameIndex;
funcTable.resource[newFuncIndex] = resourceIndex;
funcTable.relevantForJS[newFuncIndex] = false;
funcTable.isJS[newFuncIndex] = false;
funcTable.fileName[newFuncIndex] = null;
funcTable.lineNumber[newFuncIndex] = null;
funcTable.columnNumber[newFuncIndex] = null;
return newFuncIndex;
}
// Adds a resource table entry for an extension's base URL origin
// string, mapping it to the extension's name and internal ID.
function _addExtensionOrigin(
extractionInfo: ExtractionInfo,
extensions: ExtensionTable,
index: number
): void {
const { originToResourceIndex, resourceTable, stringTable } = extractionInfo;
const origin = new URL(extensions.baseURL[index]).origin;
let resourceIndex = originToResourceIndex.get(origin);
if (resourceIndex === undefined) {
resourceIndex = resourceTable.length++;
originToResourceIndex.set(origin, resourceIndex);
const quotedName = JSON.stringify(extensions.name[index]);
const name = `Extension ${quotedName} (ID: ${extensions.id[index]})`;
const idIndex = stringTable.indexForString(extensions.id[index]);
resourceTable.lib[resourceIndex] = null;
resourceTable.name[resourceIndex] = stringTable.indexForString(name);
resourceTable.host[resourceIndex] = idIndex;
resourceTable.type[resourceIndex] = resourceTypes.addon;
}
}
/**
* Given a location string that looks like a JS function (by matching various regular
* expressions) e.g. "functionName:134", this function will classify it as a JS
* function, and add the resource information if it's not already present.
*/
function _extractJsFunction(
extractionInfo: ExtractionInfo,
locationString: string
): IndexIntoFuncTable | null {
// Check for a JS location string.
const jsMatch: RegExpResult =
// Given: "functionName (http://script.url/:1234:1234)"
// Captures: 1^^^^^^^^^^ 2^^^^^^^^^^^^^^^^^^ 3^^^ 4^^^
/^(.*) \((.+?):([0-9]+)(?::([0-9]+))?\)$/.exec(locationString) ||
// Given: "http://script.url/:1234:1234"
// Captures: 2^^^^^^^^^^^^^^^^^ 3^^^ 4^^^
/^()(.+?):([0-9]+)(?::([0-9]+))?$/.exec(locationString);
if (!jsMatch) {
return null;
}
const { funcTable, stringTable, resourceTable, originToResourceIndex } =
extractionInfo;
// Case 4: JS function - A match was found in the location string in the format
// of a JS function.
const [, funcName, rawScriptURI] = jsMatch;
const scriptURI = _getRealScriptURI(rawScriptURI);
const resourceIndex = getOrCreateURIResource(
scriptURI,
resourceTable,
stringTable,
originToResourceIndex
);
let funcNameIndex;
if (funcName) {
funcNameIndex = stringTable.indexForString(funcName);
} else {
// Some JS frames don't have a function because they are for the
// initial evaluation of the whole JS file. In that case, use the
// file name itself, prepended by '(root scope) ', as the function
// name.
funcNameIndex = stringTable.indexForString(`(root scope) ${scriptURI}`);
}
const fileName = stringTable.indexForString(scriptURI);
const lineNumber = parseInt(jsMatch[3], 10);
const columnNumber = jsMatch[4] ? parseInt(jsMatch[4], 10) : null;
// Add the function to the funcTable.
const funcIndex = funcTable.length++;
funcTable.name[funcIndex] = funcNameIndex;
funcTable.resource[funcIndex] = resourceIndex;
funcTable.relevantForJS[funcIndex] = false;
funcTable.isJS[funcIndex] = true;
funcTable.fileName[funcIndex] = fileName;
funcTable.lineNumber[funcIndex] = lineNumber;
funcTable.columnNumber[funcIndex] = columnNumber;
return funcIndex;
}
/**
* Nothing is known about this function. Add it without any resource information.
*/
function _extractUnknownFunctionType(
{ funcTable }: ExtractionInfo,
locationIndex: IndexIntoStringTable,
relevantForJS: boolean
): IndexIntoFuncTable {
const index = funcTable.length++;
funcTable.name[index] = locationIndex;
funcTable.resource[index] = -1;
funcTable.relevantForJS[index] = relevantForJS;
funcTable.isJS[index] = false;
funcTable.fileName[index] = null;
funcTable.lineNumber[index] = null;
funcTable.columnNumber[index] = null;
return index;
}
/**
* Explicitly recreate the frame table here to help enforce our assumptions about types.
*/
function _processFrameTable(
geckoFrameStruct: GeckoFrameStruct,
frameFuncs: IndexIntoFuncTable[],
frameAddresses: (Address | null)[]
): FrameTable {
return {
address: frameAddresses.map((a) => a ?? -1),
inlineDepth: Array(geckoFrameStruct.length).fill(0),
category: geckoFrameStruct.category,
subcategory: geckoFrameStruct.subcategory,
func: frameFuncs,
nativeSymbol: Array(geckoFrameStruct.length).fill(null),
innerWindowID: geckoFrameStruct.innerWindowID,
implementation: geckoFrameStruct.implementation,
line: geckoFrameStruct.line,
column: geckoFrameStruct.column,
length: geckoFrameStruct.length,
};
}
/**
* Explicitly recreate the stack table here to help enforce our assumptions about types.
* Also add a category column.
*/
function _processStackTable(
geckoStackTable: GeckoStackStruct,
frameTable: FrameTable,
categories: CategoryList
): StackTable {
// Compute a non-null category for every stack
const defaultCategory = categories.findIndex((c) => c.color === 'grey') || 0;
const categoryColumn = new Array(geckoStackTable.length);
const subcategoryColumn = new Array(geckoStackTable.length);
for (let stackIndex = 0; stackIndex < geckoStackTable.length; stackIndex++) {
const frameIndex = geckoStackTable.frame[stackIndex];
const frameCategory = frameTable.category[frameIndex];
const frameSubcategory = frameTable.subcategory[frameIndex];
let stackCategory;
let stackSubcategory;
if (frameCategory !== null) {
stackCategory = frameCategory;
stackSubcategory = frameSubcategory || 0;
} else {
const prefix = geckoStackTable.prefix[stackIndex];
if (prefix !== null) {
// Because of the structure of the stack table, prefix < stackIndex.
// So we've already computed the category for the prefix.
stackCategory = categoryColumn[prefix];
stackSubcategory = subcategoryColumn[prefix];
} else {
stackCategory = defaultCategory;
stackSubcategory = 0;
}
}
categoryColumn[stackIndex] = stackCategory;
subcategoryColumn[stackIndex] = stackSubcategory;
}
return {
frame: geckoStackTable.frame,
category: categoryColumn,
subcategory: subcategoryColumn,
prefix: geckoStackTable.prefix,
length: geckoStackTable.length,
};
}
/**
* Convert stack field to cause field for the given payload. A cause field includes
* the thread ID (tid), an IndexIntoStackTable, and the time the stack was captured.
* If the stack was captured within the start and end time of the marker, this was a
* synchronous stack. Otherwise, if it happened before, it was an async stack, and is
* most likely some event that happened in the past that triggered the marker.
*/
function _convertStackToCause(data: MarkerPayload_Gecko) {
if ('stack' in data && data.stack && data.stack.samples.data.length > 0) {
const { stack, ...newData } = data;
const stackIndex = stack.samples.data[0][stack.samples.schema.stack];
const time = stack.samples.data[0][stack.samples.schema.time];
if (stackIndex !== null) {
return {
...newData,
cause: { tid: stack.tid, time, stack: stackIndex },
};
}
return newData;
}
return data;
}
/**
* Sometimes we don't want to extract a cause, but rather just the stack index
* from a gecko payload.
*/
function _convertPayloadStackToIndex(
data: MarkerPayload_Gecko | null
): IndexIntoStackTable | null {
if (!data) {
return null;
}
if (data.stack && data.stack.samples.data.length > 0) {
const { samples } = data.stack;
return samples.data[0][samples.schema.stack];
}
return null;
}
/**
* Process the markers.
* Convert stacks to causes.
* Process GC markers.
* Extract JS allocations into the JsAllocationsTable.
* Extract Native allocations into the NativeAllocationsTable.
*/
function _processMarkers(geckoMarkers: GeckoMarkerStruct): {|
markers: RawMarkerTable,
jsAllocations: JsAllocationsTable | null,
nativeAllocations: NativeAllocationsTable | null,
|} {
const markers = getEmptyRawMarkerTable();
const jsAllocations = getEmptyJsAllocationsTable();
const inProgressNativeAllocations =
getEmptyUnbalancedNativeAllocationsTable();
const memoryAddress: number[] = [];
const threadId: number[] = [];
// Determine if native allocations have memory addresses.
let hasMemoryAddresses;
for (let markerIndex = 0; markerIndex < geckoMarkers.length; markerIndex++) {
const geckoPayload = geckoMarkers.data[markerIndex];
if (geckoPayload) {
switch (geckoPayload.type) {
case 'JS allocation': {
// Build up a separate table for the JS allocation data, and do not
// include it in the marker information.
jsAllocations.time.push(
ensureExists(
geckoMarkers.startTime[markerIndex],
'JS Allocations are assumed to have a startTime'
)
);
jsAllocations.className.push(geckoPayload.className);
jsAllocations.typeName.push(geckoPayload.typeName);
jsAllocations.coarseType.push(geckoPayload.coarseType);
jsAllocations.weight.push(geckoPayload.size);
jsAllocations.inNursery.push(geckoPayload.inNursery);
jsAllocations.stack.push(_convertPayloadStackToIndex(geckoPayload));
jsAllocations.length++;
// Do not process the marker and add it to the marker list.
continue;
}
case 'Native allocation': {
if (hasMemoryAddresses === undefined) {
// If one payload as the memory address, then all of them should.
hasMemoryAddresses = 'memoryAddress' in geckoPayload;
}
// Build up a separate table for the native allocation data, and do not
// include it in the marker information.
inProgressNativeAllocations.time.push(
ensureExists(
geckoMarkers.startTime[markerIndex],
'Native Allocations are assumed to have a startTime'
)
);
inProgressNativeAllocations.weight.push(geckoPayload.size);
inProgressNativeAllocations.stack.push(
_convertPayloadStackToIndex(geckoPayload)
);
inProgressNativeAllocations.length++;
if (hasMemoryAddresses) {
memoryAddress.push(
ensureExists(
geckoPayload.memoryAddress,
'Could not find the memoryAddress property on a gecko marker payload.'
)
);
threadId.push(
ensureExists(
geckoPayload.threadId,
'Could not find a threadId property on a gecko marker payload.'
)
);
}
// Do not process the marker and add it to the marker list.
continue;
}
default:
// This is not an allocation, continue on to process the marker.
}
}
const payload = _processMarkerPayload(geckoPayload);
const name = geckoMarkers.name[markerIndex];
const startTime = geckoMarkers.startTime[markerIndex];
const endTime = geckoMarkers.endTime[markerIndex];
const phase = geckoMarkers.phase[markerIndex];
const category = geckoMarkers.category[markerIndex];
markers.name.push(name);
markers.startTime.push(startTime);
markers.endTime.push(endTime);
markers.phase.push(phase);
markers.category.push(category);
markers.data.push(payload);
markers.length++;
}
// Properly handle the different cases of native allocations.
let nativeAllocations;
if (inProgressNativeAllocations.length === 0) {
// There are none, don't add it.
nativeAllocations = null;
} else if (hasMemoryAddresses) {
// This is the newer native allocations with memory addresses.
nativeAllocations = {
time: inProgressNativeAllocations.time,
weight: inProgressNativeAllocations.weight,
weightType: inProgressNativeAllocations.weightType,
stack: inProgressNativeAllocations.stack,
memoryAddress,
threadId,
length: inProgressNativeAllocations.length,
};
} else {
// There is the older native allocations, without memory addresses.
nativeAllocations = {
time: inProgressNativeAllocations.time,
weight: inProgressNativeAllocations.weight,
weightType: inProgressNativeAllocations.weightType,
stack: inProgressNativeAllocations.stack,
length: inProgressNativeAllocations.length,
};
}
return {
markers: markers,
jsAllocations: jsAllocations.length === 0 ? null : jsAllocations,
nativeAllocations,
};
}
function convertPhaseTimes(
old_phases: PhaseTimes<Milliseconds>
): PhaseTimes<Microseconds> {
const phases = {};
for (const phase in old_phases) {
phases[phase] = old_phases[phase] * 1000;
}
return phases;
}
/**
* Process just the marker payload. This converts stacks into causes, and augments
* the GC information.
*/
function _processMarkerPayload(
geckoPayload: MarkerPayload_Gecko | null
): MarkerPayload | null {
if (!geckoPayload) {
return null;
}
// If there is a "stack" field, convert it to a "cause" field. This is
// pre-emptively done for every single marker payload.
//
// Warning: This function converts the payload into an any type
const payload = _convertStackToCause(geckoPayload);
switch (payload.type) {
/*
* We want to improve the format of these markers to make them
* easier to understand and work with, but we can't do that by
* upgrading the gecko profile since that would break
* compatibility with telemetry, however we can make some
* improvements while we process a gecko profile.
*/
case 'GCSlice': {
const { times, ...partialTimings }: GCSliceData_Gecko = payload.timings;
return ({
type: 'GCSlice',
timings: {
...partialTimings,
phase_times: times ? convertPhaseTimes(times) : {},
},
}: GCSliceMarkerPayload);
}
case 'GCMajor': {
const geckoTimings: GCMajorAborted | GCMajorCompleted_Gecko =
payload.timings;
switch (geckoTimings.status) {
case 'completed': {
const { totals, ...partialMt } = geckoTimings;
const timings: GCMajorCompleted = {
...partialMt,
phase_times: convertPhaseTimes(totals),
mmu_20ms: geckoTimings.mmu_20ms / 100,
mmu_50ms: geckoTimings.mmu_50ms / 100,
};
return ({
type: 'GCMajor',
timings: timings,
}: GCMajorMarkerPayload);
}
case 'aborted':
return ({
type: 'GCMajor',
timings: { status: 'aborted' },
}: GCMajorMarkerPayload);
default:
// Flow cannot detect that this switch is complete.
console.log('Unknown GCMajor status');
throw new Error('Unknown GCMajor status');
}
}
case 'IPC': {
// Convert otherPid to a string.
const {
startTime,
endTime,
otherPid,
messageType,
messageSeqno,
side,
direction,
phase,
sync,
threadId,
} = payload;
return {
type: 'IPC',
startTime,
endTime,
otherPid: `${otherPid}`,
messageType,
messageSeqno,
side,
direction,
phase,
sync,
threadId,
};
}
default:
// `payload` is currently typed as the result of _convertStackToCause, which
// is MarkerPayload_Gecko where `stack` has been replaced with `cause`. This
// should be reasonably close to `MarkerPayload`, but Flow doesn't work well
// with our MarkerPayload type. So we're coerce this return value to `any`
// here, and then to `MarkerPayload` as the return value for this function.
// This doesn't provide type safety but it shows the intent of going from an
// object without much type safety, to a specific type definition.
return (payload: any);
}
}
/**
* Explicitly recreate the markers here to help enforce our assumptions about types.
*/
function _processSamples(geckoSamples: GeckoSampleStruct): SamplesTable {
const samples: SamplesTable = {
stack: geckoSamples.stack,
time: geckoSamples.time,
weightType: 'samples',
weight: null,
length: geckoSamples.length,
};
if (geckoSamples.threadCPUDelta) {
// Check to see the CPU delta numbers are all null and if they are, remove
// this array completely. For example on JVM threads, all the threadCPUDelta
// values will be null and therefore it will fail to paint the activity graph.
// Instead we should remove the whole array. This call will be quick for most
// of the cases because we usually have values at least in the second sample.
const hasCPUDeltaValues = geckoSamples.threadCPUDelta.some(
(val) => val !== null
);
if (hasCPUDeltaValues) {
samples.threadCPUDelta = geckoSamples.threadCPUDelta;
}
}
if (geckoSamples.eventDelay) {
samples.eventDelay = geckoSamples.eventDelay;
} else if (geckoSamples.responsiveness) {
samples.responsiveness = geckoSamples.responsiveness;
} else {
throw new Error(
'The profile processor expected an eventDelay or responsiveness array in the samples table, but none was found.'
);
}
return samples;
}
/**
* Converts the Gecko list of counters into the processed format.
*/
function _processCounters(
geckoProfile: GeckoProfile | GeckoSubprocessProfile,
// The counters are listed independently from the threads, so we need an index that
// references back into a stable list of threads. The threads list in the processing
// step is built dynamically, so the "stableThreadList" variable is a hint that this