-
Notifications
You must be signed in to change notification settings - Fork 460
Expand file tree
/
Copy pathreceive-profile.ts
More file actions
1740 lines (1587 loc) · 55.4 KB
/
receive-profile.ts
File metadata and controls
1740 lines (1587 loc) · 55.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* 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/. */
import { oneLine } from 'common-tags';
import queryString from 'query-string';
import type JSZip from 'jszip';
import {
insertExternalMarkersIntoProfile,
insertExternalPowerCountersIntoProfile,
processGeckoProfile,
unserializeProfileOfArbitraryFormat,
} from 'firefox-profiler/profile-logic/process-profile';
import {
readSymbolsFromSymbolTable,
SymbolStore,
} from 'firefox-profiler/profile-logic/symbol-store';
import {
symbolicateProfile,
applySymbolicationSteps,
} from 'firefox-profiler/profile-logic/symbolication';
import * as MozillaSymbolicationAPI from 'firefox-profiler/profile-logic/mozilla-symbolication-api';
import { mergeProfilesForDiffing } from 'firefox-profiler/profile-logic/merge-compare';
import { decompress, isGzip } from 'firefox-profiler/utils/gz';
import { expandUrl } from 'firefox-profiler/utils/shorten-url';
import { TemporaryError } from 'firefox-profiler/utils/errors';
import { isLocalURL } from 'firefox-profiler/utils/url';
import {
getSelectedThreadIndexesOrNull,
getGlobalTrackOrder,
getHiddenGlobalTracks,
getHiddenLocalTracksByPid,
getLocalTrackOrderByPid,
getLegacyThreadOrder,
getLegacyHiddenThreads,
getProfileOrNull,
getProfile,
getView,
getSymbolServerUrl,
getBrowserConnection,
} from 'firefox-profiler/selectors';
import {
getSelectedTab,
getTabFilter,
} from 'firefox-profiler/selectors/url-state';
import {
getTabToThreadIndexesMap,
getThreadActivityScores,
} from 'firefox-profiler/selectors/profile';
import {
withHistoryReplaceStateAsync,
withHistoryReplaceStateSync,
stateFromLocation,
ensureIsValidDataSource,
} from 'firefox-profiler/app-logic/url-handling';
import { tabsShowingSampleData } from 'firefox-profiler/app-logic/tabs-handling';
import {
initializeLocalTrackOrderByPid,
computeLocalTracksByPid,
computeGlobalTracks,
initializeGlobalTrackOrder,
initializeSelectedThreadIndex,
tryInitializeHiddenTracksLegacy,
tryInitializeHiddenTracksFromUrl,
computeDefaultHiddenTracks,
getVisibleThreads,
} from 'firefox-profiler/profile-logic/tracks';
import { setDataSource } from './profile-view';
import { fatalError } from './errors';
import { batchLoadDataUrlIcons } from './icons';
import { GOOGLE_STORAGE_BUCKET } from 'firefox-profiler/app-logic/constants';
import {
determineTimelineType,
hasUsefulSamples,
} from 'firefox-profiler/profile-logic/profile-data';
import type {
RequestedLib,
ImplementationFilter,
TransformStacksPerThread,
Action,
ThunkAction,
Dispatch,
Profile,
ThreadIndex,
TabID,
PageList,
MixedObject,
} from 'firefox-profiler/types';
import type { SymbolicationStepInfo } from '../profile-logic/symbolication';
import { assertExhaustiveCheck } from '../utils/types';
import { bytesToBase64DataUrl } from 'firefox-profiler/utils/base64';
import type {
BrowserConnection,
BrowserConnectionStatus,
} from '../app-logic/browser-connection';
import type {
AddressResult,
LibSymbolicationRequest,
LibSymbolicationResponse,
SymbolProvider,
} from '../profile-logic/symbol-store';
import type { SymbolTableAsTuple } from 'firefox-profiler/profile-logic/symbol-store-db';
import SymbolStoreDB from 'firefox-profiler/profile-logic/symbol-store-db';
import type { ProfileUpgradeInfo } from 'firefox-profiler/profile-logic/processed-profile-versioning';
/**
* This file collects all the actions that are used for receiving the profile in the
* client and getting it into the processed format.
*/
export function triggerLoadingFromUrl(profileUrl: string): Action {
return {
type: 'TRIGGER_LOADING_FROM_URL',
profileUrl,
};
}
export function waitingForProfileFromBrowser(): Action {
return {
type: 'WAITING_FOR_PROFILE_FROM_BROWSER',
};
}
/**
* Call this function once the profile has been fetched and pre-processed from whatever
* source (url, browser, file, etc).
*/
export function loadProfile(
profile: Profile,
config: Partial<{
pathInZipFile: string;
implementationFilter: ImplementationFilter;
transformStacks: TransformStacksPerThread;
browserConnection: BrowserConnection | null;
skipSymbolication: boolean; // Please use this in tests only.
}> = {},
initialLoad: boolean = false
): ThunkAction<Promise<void>> {
return async (dispatch) => {
if (profile.threads.length === 0) {
console.error('This profile has no threads.', profile);
dispatch(
fatalError(
new Error(
'No threads were captured in this profile, there is nothing to display.'
)
)
);
return;
}
// We have a 'PROFILE_LOADED' dispatch here and a second dispatch for
// `finalizeProfileView`. Normally this is an anti-pattern but that was
// necessary for initial load url handling. We are not dispatching
// `finalizeProfileView` here if it's initial load, instead are getting the
// url, upgrading the url and then creating a UrlState that we can use
// first. That is necessary because we need a UrlState inside `finalizeProfileView`.
// If this is not the initial load, we are dispatching both of them.
dispatch({
type: 'PROFILE_LOADED',
profile,
pathInZipFile: config.pathInZipFile ?? null,
implementationFilter: config.implementationFilter ?? null,
transformStacks: config.transformStacks ?? null,
});
// During initial load, we are upgrading the URL and generating the UrlState
// before finalizing profile view. That's why we are dispatching this action
// after completing those steps inside `setupInitialUrlState`.
if (initialLoad === false) {
await dispatch(
finalizeProfileView(
config.browserConnection ?? null,
config.skipSymbolication
)
);
}
};
}
/**
* This function will take the view information from the URL, such as hiding and sorting
* information, and it will validate it against the profile. If there is no pre-existing
* view information, this function will compute the defaults. There is a decent amount of
* complexity to making all of these decisions, which has been collected in a bunch of
* functions in the src/profile-logic/tracks.js file.
*
* Note: skipSymbolication is used in tests only, this is enforced.
*/
export function finalizeProfileView(
browserConnection: BrowserConnection | null = null,
skipSymbolication?: boolean
): ThunkAction<Promise<void>> {
return async (dispatch, getState) => {
if (skipSymbolication && process.env.NODE_ENV !== 'test') {
throw new Error('Please do not use skipSymbolication outside of tests');
}
const profile = getProfileOrNull(getState());
if (profile === null || getView(getState()).phase !== 'PROFILE_LOADED') {
// Profile load was not successful. Do not continue.
return;
}
// The selectedThreadIndex is only null for new profiles that haven't
// been seen before. If it's non-null, then there is profile view information
// encoded into the URL.
const selectedThreadIndexes = getSelectedThreadIndexesOrNull(getState());
const pages = profile.pages;
dispatch(finalizeFullProfileView(profile, selectedThreadIndexes));
let faviconsPromise = null;
if (browserConnection && pages && pages.length > 0) {
faviconsPromise = retrievePageFaviconsFromBrowser(
dispatch,
pages,
browserConnection
);
}
// Note we kick off symbolication only for the profiles we know for sure
// that they weren't symbolicated.
// We can skip the symbolication in tests if needed.
let symbolicationPromise = null;
if (!skipSymbolication && profile.meta.symbolicated === false) {
const symbolStore = getSymbolStore(
dispatch,
getSymbolServerUrl(getState()),
browserConnection
);
if (symbolStore) {
// Only symbolicate if a symbol store is available. In tests we may not
// have access to IndexedDB.
symbolicationPromise = doSymbolicateProfile(
dispatch,
profile,
symbolStore
);
}
}
await Promise.all([faviconsPromise, symbolicationPromise]);
};
}
/**
* Finalize the profile state for full view.
* This function will take the view information from the URL, such as hiding and sorting
* information, and it will validate it against the profile. If there is no pre-existing
* view information, this function will compute the defaults.
*/
export function finalizeFullProfileView(
profile: Profile,
maybeSelectedThreadIndexes: Set<ThreadIndex> | null
): ThunkAction<void> {
return (dispatch, getState) => {
const hasUrlInfo = maybeSelectedThreadIndexes !== null;
const tabToThreadIndexesMap = getTabToThreadIndexesMap(getState());
const tabFilter = hasUrlInfo ? getTabFilter(getState()) : null;
const globalTracks = computeGlobalTracks(
profile,
tabFilter,
tabToThreadIndexesMap
);
const localTracksByPid = computeLocalTracksByPid(profile, globalTracks);
const threadActivityScores = getThreadActivityScores(getState());
const legacyThreadOrder = getLegacyThreadOrder(getState());
const globalTrackOrder = initializeGlobalTrackOrder(
globalTracks,
hasUrlInfo ? getGlobalTrackOrder(getState()) : null,
legacyThreadOrder,
threadActivityScores
);
const localTrackOrderByPid = initializeLocalTrackOrderByPid(
hasUrlInfo ? getLocalTrackOrderByPid(getState()) : null,
localTracksByPid,
legacyThreadOrder,
profile
);
const tracksWithOrder = {
globalTracks,
globalTrackOrder,
localTracksByPid,
localTrackOrderByPid,
};
let hiddenTracks = null;
// For non-initial profile loads, initialize the set of hidden tracks from
// information in the URL.
const legacyHiddenThreads = getLegacyHiddenThreads(getState());
if (legacyHiddenThreads !== null) {
hiddenTracks = tryInitializeHiddenTracksLegacy(
tracksWithOrder,
legacyHiddenThreads,
profile
);
} else if (hasUrlInfo) {
hiddenTracks = tryInitializeHiddenTracksFromUrl(
tracksWithOrder,
getHiddenGlobalTracks(getState()),
getHiddenLocalTracksByPid(getState())
);
}
if (hiddenTracks === null) {
// Compute a default set of hidden tracks.
// This is the case for the initial profile load.
// We also get here if the URL info was ignored, for example if
// respecting it would have caused all threads to become hidden.
const includeParentProcessThreads = tabFilter === null;
hiddenTracks = computeDefaultHiddenTracks(
tracksWithOrder,
profile,
threadActivityScores,
// Only include the parent process if there is no tab filter applied.
includeParentProcessThreads
);
}
const selectedThreadIndexes = initializeSelectedThreadIndex(
maybeSelectedThreadIndexes,
getVisibleThreads(tracksWithOrder, hiddenTracks),
profile,
threadActivityScores
);
let timelineType = null;
if (!hasUrlInfo) {
timelineType = determineTimelineType(profile);
}
// If the currently selected tab is only visible when the selected track
// has samples, verify that the selected track has samples, and if not
// select the marker chart.
let selectedTab = getSelectedTab(getState());
if (tabsShowingSampleData.includes(selectedTab)) {
let hasSamples = false;
for (const threadIndex of selectedThreadIndexes) {
const thread = profile.threads[threadIndex];
const { samples, jsAllocations, nativeAllocations } = thread;
hasSamples = [samples, jsAllocations, nativeAllocations].some((table) =>
hasUsefulSamples(table?.stack, profile.shared)
);
if (hasSamples) {
break;
}
}
if (!hasSamples) {
selectedTab = 'marker-chart';
}
}
withHistoryReplaceStateSync(() => {
dispatch({
type: 'VIEW_FULL_PROFILE',
selectedThreadIndexes,
selectedTab,
globalTracks,
globalTrackOrder,
localTracksByPid,
localTrackOrderByPid,
timelineType,
...hiddenTracks,
});
});
};
}
/**
* Symbolication normally happens when a profile is first loaded. This function
* provides the ability to kick off symbolication again after it has already been
* attempted once.
*/
export function resymbolicateProfile(): ThunkAction<Promise<void>> {
return async (dispatch, getState) => {
const symbolStore = getSymbolStore(
dispatch,
getSymbolServerUrl(getState()),
getBrowserConnection(getState())
);
const profile = getProfile(getState());
if (!symbolStore) {
throw new Error(
'There was no symbol store when attempting to re-symbolicate.'
);
}
await doSymbolicateProfile(
dispatch,
profile,
symbolStore,
/* ignoreCache */ true
);
};
}
// Previously `loadProfile` and `finalizeProfileView` functions were a single
// function called `viewProfile`. Then we had to split it because of the changes
// of url/profile loading mechanism. We kept the `viewProfile` function with the
// same functionality as previous `viewProfile` because many of the tests use this.
// This function will simply call `loadProfile` (and `finalizeProfileView` inside
// `loadProfile`) and wait until symbolication finishes.
export function viewProfile(
profile: Profile,
config: Partial<{
pathInZipFile: string;
implementationFilter: ImplementationFilter;
transformStacks: TransformStacksPerThread;
skipSymbolication: boolean;
browserConnection: BrowserConnection | null;
}> = {}
): ThunkAction<Promise<void>> {
return async (dispatch) => {
await dispatch(loadProfile(profile, config, false));
};
}
export function requestingSymbolTable(requestedLib: RequestedLib): Action {
return {
type: 'REQUESTING_SYMBOL_TABLE',
requestedLib,
};
}
export function receivedSymbolTableReply(requestedLib: RequestedLib): Action {
return {
type: 'RECEIVED_SYMBOL_TABLE_REPLY',
requestedLib,
};
}
export function startSymbolicating(): Action {
return {
type: 'START_SYMBOLICATING',
};
}
export function doneSymbolicating(): Action {
return { type: 'DONE_SYMBOLICATING' };
}
// Apply all the individual "symbolication steps" from symbolicationStepsPerThread
// to the current profile, as one redux action.
// We combine steps into one redux action in order to avoid unnecessary renders.
// When symbolication results arrive, we often get a very high number of individual
// symbolication updates. If we dispatched all of them as individual redux actions,
// we would cause React to re-render synchronously for each action, and the profile
// selectors called from rendering would do expensive work, most of which would never
// reach the screen because it would be invalidated by the next symbolication update.
// So we queue up symbolication steps and run the update from requestIdleCallback.
export function bulkProcessSymbolicationSteps(
symbolicationSteps: SymbolicationStepInfo[]
): ThunkAction<void> {
return (dispatch, getState) => {
const { threads, shared } = getProfile(getState());
const {
threads: symbolicatedThreads,
shared: symbolicatedShared,
oldFuncToNewFuncsMap,
} = applySymbolicationSteps(threads, shared, symbolicationSteps);
dispatch({
type: 'BULK_SYMBOLICATION',
oldFuncToNewFuncsMap,
symbolicatedThreads,
symbolicatedShared,
});
};
}
let requestIdleCallbackPolyfill: (
callback: () => void,
_opts?: { timeout: number }
) => void;
if (typeof window === 'object' && window.requestIdleCallback) {
requestIdleCallbackPolyfill = window.requestIdleCallback;
} else if (typeof process === 'object' && process.nextTick) {
// Node environment
requestIdleCallbackPolyfill = process.nextTick;
} else {
requestIdleCallbackPolyfill = (callback) => setTimeout(callback, 0);
}
// Queues up symbolication steps and bulk-processes them from requestIdleCallback,
// in order to improve UI responsiveness during symbolication.
class SymbolicationStepQueue {
_updates: SymbolicationStepInfo[];
_updateObservers: Array<() => void>;
_requestedUpdate: boolean;
constructor() {
this._updates = [];
this._updateObservers = [];
this._requestedUpdate = false;
}
_scheduleUpdate(dispatch: Dispatch) {
// Only request an update if one hasn't already been scheduled.
if (!this._requestedUpdate) {
requestIdleCallbackPolyfill(() => this._dispatchUpdate(dispatch), {
timeout: 2000,
});
this._requestedUpdate = true;
}
}
_dispatchUpdate(dispatch: Dispatch) {
const updates = this._updates;
const observers = this._updateObservers;
this._updates = [];
this._updateObservers = [];
this._requestedUpdate = false;
dispatch(bulkProcessSymbolicationSteps(updates));
for (const observer of observers) {
observer();
}
}
enqueueSingleSymbolicationStep(
dispatch: Dispatch,
symbolicationStepInfo: SymbolicationStepInfo,
completionHandler: () => void
) {
this._scheduleUpdate(dispatch);
this._updates.push(symbolicationStepInfo);
this._updateObservers.push(completionHandler);
}
}
const _symbolicationStepQueueSingleton = new SymbolicationStepQueue();
/**
* If the profile object we got from the browser is an ArrayBuffer, convert it
* to a gecko profile object by parsing the JSON.
*/
async function _unpackGeckoProfileFromBrowser(
profile: ArrayBuffer | MixedObject
): Promise<unknown> {
// Note: the following check will work for array buffers coming from another
// global. This happens especially with tests but could happen in the future
// in Firefox too.
if (Object.prototype.toString.call(profile) === '[object ArrayBuffer]') {
return _extractJsonFromArrayBuffer(profile as ArrayBuffer);
}
return profile;
}
function getSymbolStore(
dispatch: Dispatch,
symbolServerUrl: string,
browserConnection: BrowserConnection | null
): SymbolStore | null {
if (!window.indexedDB) {
// We could be running in a test environment with no indexedDB support. Do not
// return a symbol store in this case.
return null;
}
// Note, the database name still references the old project name, "perf.html". It was
// left the same as to not invalidate user's information.
const symbolProvider = new RegularSymbolProvider(
'perf-html-async-storage',
dispatch,
symbolServerUrl,
browserConnection
);
return new SymbolStore(symbolProvider);
}
type DemangleFunction = (name: string) => string;
/**
* The regular implementation of the SymbolProvider interface: Symbols are requested
* from a server via fetch, and from the browser via a BrowserConnection (if present).
* State changes are notified via redux actions to the provided `dispatch` function.
*/
class RegularSymbolProvider implements SymbolProvider {
_dispatch: Dispatch;
_symbolServerUrl: string;
_browserConnection: BrowserConnection | null;
_symbolDb: SymbolStoreDB;
_demangleCallback: DemangleFunction | null = null;
constructor(
dbNamePrefix: string,
dispatch: Dispatch,
symbolServerUrl: string,
browserConnection: BrowserConnection | null
) {
this._dispatch = dispatch;
this._symbolServerUrl = symbolServerUrl;
this._browserConnection = browserConnection;
this._symbolDb = new SymbolStoreDB(`${dbNamePrefix}-symbol-tables`);
}
async _makeSymbolicationAPIRequestWithCallback(
symbolSupplierName: string,
requests: LibSymbolicationRequest[],
callback: (path: string, requestJson: string) => Promise<unknown>
) {
for (const { lib } of requests) {
this._dispatch(requestingSymbolTable(lib));
}
try {
return await MozillaSymbolicationAPI.requestSymbols(
symbolSupplierName,
requests,
callback
);
} catch (e) {
throw new Error(
`There was a problem with the symbolication API request to the ${symbolSupplierName}: ${e.message}`
);
} finally {
for (const { lib } of requests) {
this._dispatch(receivedSymbolTableReply(lib));
}
}
}
requestSymbolsFromServer(
requests: LibSymbolicationRequest[]
): Promise<LibSymbolicationResponse[]> {
return this._makeSymbolicationAPIRequestWithCallback(
'symbol server',
requests,
async (path, json) => {
const response = await fetch(this._symbolServerUrl + path, {
body: json,
method: 'POST',
mode: 'cors',
// Use a profiler-specific user agent, so that the symbolication server knows
// what's making this request.
headers: new Headers({
'User-Agent': `FirefoxProfiler/1.0 (+${location.origin})`,
}),
});
return response.json();
}
);
}
async requestSymbolsFromBrowser(
requests: LibSymbolicationRequest[]
): Promise<LibSymbolicationResponse[]> {
if (this._browserConnection === null) {
throw new Error(
'No connection to the browser, cannot run querySymbolicationApi'
);
}
const bc = this._browserConnection;
return this._makeSymbolicationAPIRequestWithCallback(
'browser',
requests,
async (path, json) =>
JSON.parse(await bc.querySymbolicationApi(path, json))
);
}
/**
* This function returns a function that can demangle function name using a
* WebAssembly module, but falls back on the identity function if the
* WebAssembly module isn't available for some reason.
*/
async _createDemangleCallback(): Promise<DemangleFunction> {
try {
// When this module imports some WebAssembly module, the bundler's mechanism
// invokes the WebAssembly object which might be absent in some browsers,
// therefore `import` can throw. Also some browsers might refuse to load a
// wasm module because of our CSP.
const { demangle_any } = await import('gecko-profiler-demangle');
return demangle_any;
} catch (error) {
// Module loading can fail (for example in browsers without WebAssembly
// support, or due to bad server configuration), so we will fall back
// to a pass-through function if that happens.
console.error('Demangling module could not be imported.', error);
return (mangledString) => mangledString;
}
}
async _getDemangleCallback(): Promise<DemangleFunction> {
return (this._demangleCallback ??= await this._createDemangleCallback());
}
// Try to get individual symbol tables from the browser, for any libraries
// which couldn't be symbolicated with the symbolication API.
// This is needed for two cases:
// 1. Firefox 95 and earlier, which didn't have a querySymbolicationApi
// WebChannel access point, and only supports symbol tables.
// 2. Android system libraries, even in modern versions of Firefox. We don't
// support querySymbolicationApi for them yet, see
// https://bugzilla.mozilla.org/show_bug.cgi?id=1735897
async requestSymbolsViaSymbolTableFromBrowser(
request: LibSymbolicationRequest,
ignoreCache: boolean
): Promise<Map<number, AddressResult>> {
// Check this._symbolDb first, and then call this._getSymbolTablesFromBrowser
// if we couldn't find the table in the cache.
// We also need a demangling function for this, which is in an async module.
const demangleCallback = await this._getDemangleCallback();
const { lib, addresses } = request;
const { debugName, breakpadId } = lib;
let symbolTable = null;
if (!ignoreCache) {
// Try to get the symbol table from the database.
// This call will return null if the symbol table is not present.
symbolTable = await this._symbolDb.getSymbolTable(debugName, breakpadId);
}
if (symbolTable === null) {
symbolTable = await this._requestSymbolTableFromBrowser(lib);
this._storeSymbolTableInDB(lib, symbolTable);
}
return readSymbolsFromSymbolTable(addresses, symbolTable, demangleCallback);
}
async _requestSymbolTableFromBrowser(
lib: RequestedLib
): Promise<SymbolTableAsTuple> {
if (this._browserConnection === null) {
throw new Error(
'No connection to the browser, cannot obtain symbol tables'
);
}
const { debugName, breakpadId } = lib;
this._dispatch(requestingSymbolTable(lib));
try {
const symbolTable = await this._browserConnection.getSymbolTable(
debugName,
breakpadId
);
this._dispatch(receivedSymbolTableReply(lib));
return symbolTable;
} catch (error) {
this._dispatch(receivedSymbolTableReply(lib));
throw error;
}
}
// Store a symbol table in the database. This is only used for symbol tables
// and not for partial symbol results. Symbol tables are obtained from the
// browser via the geckoProfiler object which is defined in a frame script:
// https://searchfox.org/mozilla-central/rev/a9db89754fb507254cb8422e5a00af7c10d98264/devtools/client/performance-new/frame-script.js#67-81
//
// We do not store results from the Mozilla symbolication API, because those
// only contain the symbols we requested and not all the symbols of a given
// library.
async _storeSymbolTableInDB(
lib: RequestedLib,
symbolTable: SymbolTableAsTuple
): Promise<void> {
const { debugName, breakpadId } = lib;
try {
await this._symbolDb.storeSymbolTable(debugName, breakpadId, symbolTable);
} catch (error) {
console.log(
`Failed to store the symbol table for ${debugName} in the database:`,
error
);
}
}
}
export async function doSymbolicateProfile(
dispatch: Dispatch,
profile: Profile,
symbolStore: SymbolStore,
ignoreCache?: boolean
) {
dispatch(startSymbolicating());
const completionPromises: Promise<unknown>[] = [];
await symbolicateProfile(
profile,
symbolStore,
(symbolicationStepInfo: SymbolicationStepInfo) => {
completionPromises.push(
new Promise((resolve) => {
_symbolicationStepQueueSingleton.enqueueSingleSymbolicationStep(
dispatch,
symbolicationStepInfo,
() => resolve(undefined)
);
})
);
},
ignoreCache
);
await Promise.all(completionPromises);
dispatch(doneSymbolicating());
}
export async function retrievePageFaviconsFromBrowser(
dispatch: Dispatch,
pages: PageList,
browserConnection: BrowserConnection
) {
const newPages = [...pages];
const favicons = await browserConnection.getPageFavicons(
newPages.map((p) => p.url)
);
if (newPages.length !== favicons.length) {
// It appears that an error occurred since the pages and favicons arrays
// have different lengths. Return early without doing anything. The favicons
// array will be empty if Firefox doesn't support this webchannel request.
return;
}
// Convert binary favicon data into data urls.
const faviconDataStringPromises: Array<Promise<string | null>> = favicons.map(
(faviconData) => {
if (!faviconData) {
return Promise.resolve(null);
}
return bytesToBase64DataUrl(faviconData.data, faviconData.mimeType);
}
);
const faviconDataUrls = await Promise.all(faviconDataStringPromises);
for (let index = 0; index < favicons.length; index++) {
if (faviconDataUrls[index]) {
newPages[index] = {
...newPages[index],
favicon: faviconDataUrls[index],
};
}
}
// Once we update the pages, we can also start loading the data urls.
dispatch(batchLoadDataUrlIcons(faviconDataUrls));
dispatch({
type: 'UPDATE_PAGES',
newPages,
});
}
// From a BrowserConnectionStatus, this unwraps the included browserConnection
// when possible.
export function unwrapBrowserConnection(
browserConnectionStatus: BrowserConnectionStatus
): BrowserConnection {
switch (browserConnectionStatus.status) {
case 'ESTABLISHED':
// Good. This is the normal case.
break;
// The other cases are error cases.
case 'NOT_FIREFOX':
throw new Error('/from-browser only works in Firefox browsers');
case 'NO_ATTEMPT':
throw new Error(
'retrieveProfileFromBrowser should never be called while browserConnectionStatus is NO_ATTEMPT'
);
case 'WAITING':
throw new Error(
'retrieveProfileFromBrowser should never be called while browserConnectionStatus is WAITING'
);
case 'DENIED':
throw browserConnectionStatus.error;
case 'TIMED_OUT':
throw new Error('Timed out when waiting for reply to WebChannel message');
default:
throw assertExhaustiveCheck(browserConnectionStatus as never);
}
// Now we know that browserConnectionStatus.status === 'ESTABLISHED'.
return browserConnectionStatus.browserConnection;
}
export function retrieveProfileFromBrowser(
browserConnectionStatus: BrowserConnectionStatus,
initialLoad: boolean = false
): ThunkAction<Promise<void>> {
return async (dispatch) => {
try {
const browserConnection = unwrapBrowserConnection(
browserConnectionStatus
);
// XXX update state to show that we're connected to the browser
dispatch(waitingForProfileFromBrowser());
const rawGeckoProfile = await browserConnection.getProfile({
onThirtySecondTimeout: () => {
dispatch(
temporaryError(
new TemporaryError(oneLine`
We were unable to connect to the browser within thirty seconds.
This might be because the profile is big or your machine is slower than usual.
Still waiting...
`)
)
);
},
});
const unpackedProfile =
await _unpackGeckoProfileFromBrowser(rawGeckoProfile);
const meta = (unpackedProfile as any).meta;
if (meta.configuration && meta.configuration.features.includes('power')) {
try {
await Promise.all([
browserConnection
.getExternalPowerTracks(
meta.startTime + meta.profilingStartTime,
meta.startTime + meta.profilingEndTime
)
.then((tracks) =>
insertExternalPowerCountersIntoProfile(
tracks as any,
unpackedProfile as any
)
),
browserConnection
.getExternalMarkers(
meta.startTime + meta.profilingStartTime,
meta.startTime + meta.profilingEndTime
)
.then((markers) =>
insertExternalMarkersIntoProfile(
markers,
unpackedProfile as any
)
),
]);
} catch (error) {
// Make failures in adding external data non-fatal.
console.error(error);
}
}
const profile = processGeckoProfile(unpackedProfile as any);
await dispatch(loadProfile(profile, { browserConnection }, initialLoad));
} catch (error) {
dispatch(fatalError(error));
console.error(error);
}
};
}
export function waitingForProfileFromStore(): Action {
return {
type: 'WAITING_FOR_PROFILE_FROM_STORE',
};
}
export function waitingForProfileFromUrl(profileUrl?: string): Action {
return {
type: 'WAITING_FOR_PROFILE_FROM_URL',
profileUrl: profileUrl ?? null,
};
}
export function receiveZipFile(zip: JSZip): Action {
return {
type: 'RECEIVE_ZIP_FILE',
zip,
};
}
export function temporaryError(error: TemporaryError): Action {
return {
type: 'TEMPORARY_ERROR',
error,
};
}
function _wait(delayMs: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, delayMs));
}
function _loadProbablyFailedDueToSafariLocalhostHTTPRestriction(
url: string,
error: Error
): boolean {
if (!navigator.userAgent.match(/Safari\/\d+\.\d+/)) {
return false;
}
// Check if Safari considers this mixed content.
const parsedUrl = new URL(url);
return (
error.name === 'TypeError' &&