-
Notifications
You must be signed in to change notification settings - Fork 460
Expand file tree
/
Copy pathprofile-data.test.ts
More file actions
1846 lines (1682 loc) · 66.5 KB
/
profile-data.test.ts
File metadata and controls
1846 lines (1682 loc) · 66.5 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 {
symbolicateProfile,
applySymbolicationSteps,
} from '../../profile-logic/symbolication';
import { AddressLocator } from '../../profile-logic/address-locator';
import {
processGeckoProfile,
processGeckoOrDevToolsProfile,
} from '../../profile-logic/process-profile';
import {
getCallNodeInfo,
getInvertedCallNodeInfo,
filterThreadByImplementation,
getSampleIndexClosestToStartTime,
getSampleIndexToCallNodeIndex,
getTreeOrderComparator,
getSampleSelectedStates,
extractProfileFilterPageData,
findAddressProofForFile,
calculateFunctionSizeLowerBound,
getNativeSymbolsForCallNode,
getNativeSymbolInfo,
computeTimeColumnForRawSamplesTable,
getCallNodeFramePerStack,
getTotalNativeSymbolTimingsForCallNode,
} from '../../profile-logic/profile-data';
import {
createGeckoProfile,
createGeckoProfileWithJsTimings,
createGeckoSubprocessProfile,
} from '.././fixtures/profiles/gecko-profile';
import { StringTable } from '../../utils/string-table';
import { FakeSymbolStore } from '../fixtures/fake-symbol-store';
import { sortDataTable } from '../../utils/data-table-utils';
import { ensureExists } from '../../utils/types';
import getCallNodeProfile from '../fixtures/profiles/call-nodes';
import {
getProfileFromTextSamples,
getJsTracerTable,
getProfileWithDicts,
} from '../fixtures/profiles/processed-profile';
import {
funcHasDirectRecursiveCall,
funcHasRecursiveCall,
getBacktraceItemsForStack,
} from '../../profile-logic/transforms';
import type {
Thread,
IndexIntoStackTable,
IndexIntoSamplesTable,
CallNodePath,
LibMapping,
Profile,
RawThread,
RawProfileSharedData,
IndexIntoFrameTable,
IndexIntoSourceTable,
IndexIntoCategoryList,
IndexIntoNativeSymbolTable,
} from 'firefox-profiler/types';
import { SelectedState, ResourceType } from 'firefox-profiler/types';
describe('string-table', function () {
const u = StringTable.withBackingArray(['foo', 'bar', 'baz']);
it('should return the right strings', function () {
expect(u.getString(0)).toEqual('foo');
expect(u.getString(1)).toEqual('bar');
expect(u.getString(2)).toEqual('baz');
});
it('should return the correct index for existing strings', function () {
expect(u.indexForString('foo')).toEqual(0);
expect(u.indexForString('bar')).toEqual(1);
expect(u.indexForString('baz')).toEqual(2);
});
it('should return a new index for a new string', function () {
expect(u.indexForString('qux')).toEqual(3);
expect(u.indexForString('qux')).toEqual(3);
expect(u.indexForString('hello')).toEqual(4);
expect(u.indexForString('bar')).toEqual(1);
expect(u.indexForString('qux')).toEqual(3);
expect(u.getString(3)).toEqual('qux');
expect(u.getString(4)).toEqual('hello');
});
});
describe('data-table-utils', function () {
describe('sortDataTable', function () {
const originalDataTable = {
length: 6,
word: ['a', 'is', 'now', 'This', 'array', 'sorted'],
order: [13, 0.7, 2, -0.2, 100, 20.1],
wordLength: [1, 2, 3, 4, 5, 6],
};
const dt: typeof originalDataTable = JSON.parse(
JSON.stringify(originalDataTable)
);
it('test preparation', function () {
// verify copy
expect(dt).not.toBe(originalDataTable);
expect(dt).toEqual(originalDataTable);
expect(dt.word.map((w) => w.length)).toEqual(dt.wordLength);
});
it('should sort this data table by order', function () {
// sort by order
sortDataTable(dt, dt.order, (a, b) => a - b);
expect(dt.length).toEqual(originalDataTable.length);
expect(dt.word.length).toEqual(originalDataTable.length);
expect(dt.order.length).toEqual(originalDataTable.length);
expect(dt.wordLength.length).toEqual(originalDataTable.length);
expect(dt.word.map((w) => w.length)).toEqual(dt.wordLength);
expect(dt.order).toEqual([...dt.order].sort((a, b) => a - b));
expect(dt.word.join(' ')).toEqual('This is now a sorted array');
});
it('should sort this data table by wordLength', function () {
// sort by wordLength
sortDataTable(dt, dt.wordLength, (a, b) => a - b);
expect(dt).toEqual(originalDataTable);
});
const differentDataTable = {
length: 7,
keyColumn: [1, 2, 3, 5, 6, 4, 7],
};
it('should sort this other data table', function () {
sortDataTable(
differentDataTable,
differentDataTable.keyColumn,
(a, b) => a - b
);
expect(differentDataTable.keyColumn).toEqual([1, 2, 3, 4, 5, 6, 7]);
});
});
});
// TODO: Move this test section to process-profile.test.js?
describe('process-profile', function () {
describe('processGeckoProfile', function () {
const profile = processGeckoProfile(createGeckoProfile());
it('should have three threads', function () {
expect(profile.threads.length).toEqual(3);
});
it('should have a profile-wide libs property', function () {
expect('libs' in profile).toBeTruthy();
expect('stackTable' in profile.shared).toBeTruthy();
expect('frameTable' in profile.shared).toBeTruthy();
expect('funcTable' in profile.shared).toBeTruthy();
expect('resourceTable' in profile.shared).toBeTruthy();
});
it('should have threads that are objects of the right shape', function () {
for (const thread of profile.threads) {
expect(typeof thread).toEqual('object');
expect('samples' in thread).toBeTruthy();
expect('markers' in thread).toBeTruthy();
// Shared data which is not part of a thread:
expect('libs' in thread).toBeFalsy();
expect('stackTable' in thread).toBeFalsy();
expect('frameTable' in thread).toBeFalsy();
expect('funcTable' in thread).toBeFalsy();
expect('resourceTable' in thread).toBeFalsy();
}
});
it('should have reasonable debugName fields on each library', function () {
expect(profile.libs.length).toBe(2);
expect(profile.libs[0].debugName).toEqual('firefox');
expect(profile.libs[1].debugName).toEqual('firefox-webcontent');
// The other libraries aren't used, so they should be culled from the
// processed profile.
});
it('should have reasonable breakpadId fields on each library', function () {
for (const lib of profile.libs) {
expect('breakpadId' in lib).toBeTruthy();
expect(lib.breakpadId.length).toEqual(33);
expect(lib.breakpadId).toEqual(lib.breakpadId.toUpperCase());
}
});
it('should shift the content process by 1 second', function () {
const thread0 = profile.threads[0];
const thread2 = profile.threads[2];
// Should be Content, but modified by workaround for bug 1322471.
expect(thread2.name).toEqual('GeckoMain');
const sampleTimes0 = computeTimeColumnForRawSamplesTable(thread0.samples);
const sampleTimes2 = computeTimeColumnForRawSamplesTable(thread2.samples);
expect(sampleTimes0[0]).toEqual(0);
expect(sampleTimes0[1]).toEqual(1);
// 1 second later than the same samples in the main process because the
// content process' start time is 1s later.
expect(sampleTimes2[0]).toEqual(1000);
expect(sampleTimes2[1]).toEqual(1001);
// Now about markers
expect(thread0.markers.endTime[0]).toEqual(1);
expect(thread0.markers.startTime[1]).toEqual(2);
expect(thread0.markers.startTime[2]).toEqual(3);
expect(thread0.markers.startTime[3]).toEqual(4);
expect(thread0.markers.endTime[4]).toEqual(5);
// If this assertion fails with the value 11, then marker sorting is broken.
expect(thread0.markers.startTime[6]).toEqual(9);
expect(thread0.markers.endTime[7]).toEqual(10);
// 1 second later than the same markers in the main process.
expect(thread2.markers.endTime[0]).toEqual(1001);
expect(thread2.markers.startTime[1]).toEqual(1002);
expect(thread2.markers.startTime[2]).toEqual(1003);
expect(thread2.markers.startTime[3]).toEqual(1004);
expect(thread2.markers.endTime[4]).toEqual(1005);
expect(thread2.markers.startTime[6]).toEqual(1009);
expect(thread2.markers.endTime[7]).toEqual(1010);
// TODO: also shift the samples inside marker callstacks
});
it('should create one function per frame, except for extra frames from return address nudging', function () {
const { shared } = profile;
// The Gecko profile has three threads, default:GeckoMain, default:Compositor, tab:GeckoMain.
// The function table contains 11 items; 3 items are shared between the threads
// ("(root)", "Startup::XRE_Main", "frobnicate"), and 4 items per process which
// are "unique" to that process; they are functions for unsymbolicated addresses.
// The same addresses are used in both processes, but we give the processes different
// library mappings.
// The parent process has a library resource for a 'firefox' binary and the content
// process has a library resource for a 'firefox-webcontent' binary. This makes
// those 4 native functions distinct, and we end up with 4 + 3 + 4 = 11 functions
// in the shared funcTable.
expect(shared.funcTable.length).toEqual(11);
// The Gecko profile frameTable has 7 frames per thread.
// The shared frameTable has 27 items: 7 * 3 + 2 * 3
// - 7 per thread from the gecko thread's frameTable - these all get concatenated
// together to form the shared frameTable
// - 2 per thread from splitting two of these frames (per thread) into "nudged"
// and "non-nudged" instances
expect(shared.frameTable.length).toEqual((7 + 2) * 3);
expect('location' in shared.frameTable).toBeFalsy();
expect('func' in shared.frameTable).toBeTruthy();
expect('resource' in shared.funcTable).toBeTruthy();
expect(shared.frameTable.func[0]).toEqual(0);
expect(shared.frameTable.func[1]).toEqual(1);
expect(shared.frameTable.func[2]).toEqual(2);
expect(shared.frameTable.func[3]).toEqual(3);
expect(shared.frameTable.func[4]).toEqual(4);
expect(shared.frameTable.func[5]).toEqual(5);
expect(shared.frameTable.func[6]).toEqual(6);
expect(shared.frameTable.func[21]).toEqual(2);
expect(shared.frameTable.func[22]).toEqual(2);
expect(shared.frameTable.func[24]).toEqual(1);
expect(shared.frameTable.func[25]).toEqual(1);
expect(shared.frameTable.address[0]).toEqual(-1);
// The next two addresses were return addresses which were "nudged"
// by one byte to point into the calling instruction.
expect(shared.frameTable.address[1]).toEqual(0xf83);
expect(shared.frameTable.address[2]).toEqual(0x1a44);
expect(shared.frameTable.address[3]).toEqual(-1);
expect(shared.frameTable.address[4]).toEqual(-1);
expect(shared.frameTable.address[5]).toEqual(0x1bcd);
expect(shared.frameTable.address[6]).toEqual(0x1bce);
// Here are the non-nudged addresses for when they were sampled directly.
expect(shared.frameTable.address[21]).toEqual(0x1a45);
expect(shared.frameTable.address[22]).toEqual(0x1a45);
expect(shared.frameTable.address[24]).toEqual(0xf84);
expect(shared.frameTable.address[25]).toEqual(0xf84);
const funcTableNames = shared.funcTable.name.map(
(nameIndex) => shared.stringArray[nameIndex]
);
expect(funcTableNames[0]).toEqual('(root)');
expect(funcTableNames[1]).toEqual('0x100000f84');
expect(funcTableNames[2]).toEqual('0x100001a45');
expect(funcTableNames[3]).toEqual('Startup::XRE_Main');
expect(funcTableNames[4]).toEqual('frobnicate');
const chromeSourceIndex = shared.funcTable.source[4];
if (typeof chromeSourceIndex !== 'number') {
throw new Error('chromeSourceIndex must be a number');
}
const chromeStringIndex =
profile.shared.sources.filename[chromeSourceIndex];
expect(shared.stringArray[chromeStringIndex]).toEqual('chrome://blargh');
expect(shared.funcTable.lineNumber[4]).toEqual(34);
expect(shared.funcTable.columnNumber[4]).toEqual(35);
});
it('nudges return addresses but not sampled instruction pointer values', function () {
const profile = processGeckoProfile(createGeckoProfile());
const thread = profile.threads[0];
const shared = profile.shared;
function getFrameAddressesForSampleIndex(sample: IndexIntoSamplesTable) {
const addresses = [];
let stack = thread.samples.stack[sample];
while (stack !== null) {
addresses.push(
shared.frameTable.address[shared.stackTable.frame[stack]]
);
stack = shared.stackTable.prefix[stack];
}
addresses.reverse();
return addresses;
}
expect(getFrameAddressesForSampleIndex(0)).toEqual([-1, 0xf84]);
// 0xf84 from the caller has been nudged to 0xf83
expect(getFrameAddressesForSampleIndex(1)).toEqual([-1, 0xf83, 0x1a45]);
});
it('should create no entries in nativeSymbols before symbolication', function () {
const shared = profile.shared;
expect(shared.frameTable.length).toEqual(27);
expect('nativeSymbol' in shared.frameTable).toBeTruthy();
expect(shared.nativeSymbols.length).toEqual(0);
expect(
shared.frameTable.nativeSymbol.every((s) => s === null)
).toBeTrue();
});
it('should create one resource per used library', function () {
const shared = profile.shared;
expect(shared.resourceTable.length).toEqual(4);
expect(shared.resourceTable.type[0]).toEqual(ResourceType.Addon);
expect(shared.resourceTable.type[1]).toEqual(ResourceType.Library);
expect(shared.resourceTable.type[2]).toEqual(ResourceType.Url);
expect(shared.resourceTable.type[3]).toEqual(ResourceType.Library);
const [name0, name1, name2, name3] = shared.resourceTable.name;
expect(shared.stringArray[name0]).toEqual(
'Extension "Form Autofill" (ID: formautofill@mozilla.org)'
);
expect(shared.stringArray[name1]).toEqual('firefox');
expect(shared.stringArray[name2]).toEqual('chrome://blargh');
expect(shared.stringArray[name3]).toEqual('firefox-webcontent');
});
});
describe('JS tracer', function () {
it('does not have JS tracer information by default', function () {
const profile = processGeckoProfile(createGeckoProfile());
expect(profile.threads[0].jsTracer).toBe(undefined);
});
it('processes JS tracer and offsets the timestamps', function () {
const geckoProfile = createGeckoProfile();
let timestampOffsetMs = 33;
{
// Build the custom thread with JS tracer information. The startTime is offset
// from the parent process.
const geckoSubprocess = createGeckoSubprocessProfile(geckoProfile);
const childProcessThread = geckoSubprocess.threads[0];
const jsTracerDictionary: string[] = [];
const stringTable = StringTable.withBackingArray(jsTracerDictionary);
const jsTracer = getJsTracerTable(stringTable, [
['jsTracerA', 0, 10],
['jsTracerB', 1, 9],
['jsTracerC', 2, 8],
]);
childProcessThread.jsTracerEvents = jsTracer;
geckoSubprocess.jsTracerDictionary = jsTracerDictionary;
geckoSubprocess.meta.startTime += timestampOffsetMs;
// Update the timestampOffset taking into account the subprocess offset
timestampOffsetMs =
geckoSubprocess.meta.startTime - geckoProfile.meta.startTime;
geckoProfile.processes.push(geckoSubprocess);
}
const timestampOffsetMicro = timestampOffsetMs * 1000;
// Process the profile, and grab the threads we are interested in.
const processedProfile = processGeckoProfile(geckoProfile);
const childProcessThread = ensureExists(
processedProfile.threads.find((thread) => thread.jsTracer),
'Could not find the thread with the JS tracer information'
);
const processedJsTracer = ensureExists(
childProcessThread.jsTracer,
'The JS tracer table was not found on the subprocess'
);
// Check that the values are correct from the test defined data.
expect(
processedJsTracer.events.map(
(index) => processedProfile.shared.stringArray[index]
)
).toEqual(['jsTracerA', 'jsTracerB', 'jsTracerC']);
expect(processedJsTracer.durations).toEqual([10000, 8000, 6000]);
expect(processedJsTracer.timestamps).toEqual([
0 + timestampOffsetMicro,
1000 + timestampOffsetMicro,
2000 + timestampOffsetMicro,
]);
});
});
describe('DevTools profiles', function () {
it('should process correctly', function () {
// Mock out a DevTools profile.
const profile = processGeckoOrDevToolsProfile({
label: null,
duration: null,
markers: null,
frames: null,
memory: null,
ticks: null,
allocations: null,
profile: createGeckoProfile(),
configuration: null,
systemHost: null,
systemClient: null,
fileType: null,
version: null,
});
expect(profile.threads.length).toEqual(3);
});
});
describe('extensions metadata', function () {
it('should be processed correctly', function () {
const geckoProfile = createGeckoProfile();
geckoProfile.meta.extensions = {
schema: {
id: 0,
name: 1,
baseURL: 2,
},
data: [
[
'geckoprofiler@mozilla.com',
'Gecko Profiler',
'moz-extension://bf3bb73c-919c-4fef-95c4-070a19fdaf85/',
],
[
'screenshots@mozilla.org',
'Firefox Screenshots',
'moz-extension://fa2edf9c-c45f-4445-b819-c09e3f2d58d5/',
],
],
};
const profile = processGeckoProfile(geckoProfile);
expect(profile.meta.extensions).toEqual({
baseURL: [
'moz-extension://bf3bb73c-919c-4fef-95c4-070a19fdaf85/',
'moz-extension://fa2edf9c-c45f-4445-b819-c09e3f2d58d5/',
],
id: ['geckoprofiler@mozilla.com', 'screenshots@mozilla.org'],
name: ['Gecko Profiler', 'Firefox Screenshots'],
length: 2,
});
});
it('should be handled correctly if missing', function () {
const geckoProfile = createGeckoProfile();
delete geckoProfile.meta.extensions;
const profile = processGeckoProfile(geckoProfile);
expect(profile.meta.extensions).toEqual({
baseURL: [],
id: [],
name: [],
length: 0,
});
});
});
});
describe('profile-data', function () {
describe('createCallNodeTableAndFixupSamples', function () {
const profile = processGeckoProfile(createGeckoProfile());
const { derivedThreads, defaultCategory } = getProfileWithDicts(profile);
const [thread] = derivedThreads;
const callNodeInfo = getCallNodeInfo(
thread.stackTable,
thread.frameTable,
defaultCategory
);
const callNodeTable = callNodeInfo.getCallNodeTable();
it('should create one callNode per original stack', function () {
// After nudgeReturnAddresses, the stack table now has 24 entries, 8 per original thread.
expect(thread.stackTable.length).toEqual(24);
// But the call node table only has 9.
// This is because we de-duplicate nodes with the same function, and all threads share
// the same funcs except for the native functions which have a different library in the
// content process.
// Furthermore, whenever nudgeReturnAddresses duplicates frames (one nudged
// and one non-nudged), the two frames still share the same func, so the call
// node table respects that func sharing.
expect(callNodeTable.length).toEqual(9);
expect('prefix' in callNodeTable).toBeTruthy();
expect('func' in callNodeTable).toBeTruthy();
});
});
function _getStackList(
thread: Thread,
stackIndex: IndexIntoStackTable | null
) {
if (typeof stackIndex !== 'number') {
throw new Error('stackIndex must be a number');
}
const { prefix } = thread.stackTable;
const stackList = [];
let nextStack: IndexIntoStackTable | null = stackIndex;
while (nextStack !== null) {
if (typeof nextStack !== 'number') {
throw new Error('nextStack must be a number');
}
stackList.unshift(nextStack);
nextStack = prefix[nextStack];
}
return stackList;
}
describe('getCallNodeInfo', function () {
const profile = getCallNodeProfile();
const { derivedThreads, defaultCategory } = getProfileWithDicts(profile);
const [thread] = derivedThreads;
const callNodeInfo = getCallNodeInfo(
thread.stackTable,
thread.frameTable,
defaultCategory
);
const callNodeTable = callNodeInfo.getCallNodeTable();
const stackIndexToCallNodeIndex =
callNodeInfo.getStackIndexToNonInvertedCallNodeIndex();
const stack0 = thread.samples.stack[0];
const stack1 = thread.samples.stack[1];
if (stack0 === null || stack1 === null) {
throw new Error('Stacks must not be null.');
}
const originalStackListA = _getStackList(thread, stack0);
const originalStackListB = _getStackList(thread, stack1);
const mergedFuncListA = callNodeInfo.getCallNodePathFromIndex(
stackIndexToCallNodeIndex[stack0]
);
const mergedFuncListB = callNodeInfo.getCallNodePathFromIndex(
stackIndexToCallNodeIndex[stack1]
);
it('starts with a fully unduplicated set stack frames', function () {
/**
* Assert this original structure:
*
* stack0 (funcA)
* |
* v
* stack1 (funcB)
* |
* v
* stack2 (funcC)
* / \
* V V
* stack3 (funcD) stack5 (funcD)
* | |
* v V
* stack4 (funcE) stack6 (funcF)
*
* ^sample 0 ^sample 1
*/
expect(thread.stackTable.length).toEqual(7);
expect(originalStackListA).toEqual([0, 1, 2, 3, 4]);
expect(originalStackListB).toEqual([0, 1, 2, 5, 6]);
});
it('creates a callNodeTable with merged stacks that share functions', function () {
/**
* This structure represents the desired de-duplication.
*
* callNode0 (funcA)
* |
* v
* callNode1 (funcB)
* |
* v
* callNode2 (funcC)
* |
* v
* callNode3 (funcD)
* / \
* V V
* callNode4 (funcE) callNode5 (funcF)
*
* ^sample 0 ^sample 1
*/
expect(mergedFuncListA).toEqual([0, 1, 2, 3, 4]);
expect(mergedFuncListB).toEqual([0, 1, 2, 3, 5]);
expect(callNodeTable.length).toEqual(6);
});
});
});
describe('getInvertedCallNodeInfo', function () {
function setup(plaintextSamples: string) {
const { derivedThreads, funcNamesDictPerThread, defaultCategory } =
getProfileFromTextSamples(plaintextSamples);
const [thread] = derivedThreads;
const [funcNamesDict] = funcNamesDictPerThread;
const nonInvertedCallNodeInfo = getCallNodeInfo(
thread.stackTable,
thread.frameTable,
defaultCategory
);
const invertedCallNodeInfo = getInvertedCallNodeInfo(
nonInvertedCallNodeInfo,
defaultCategory,
thread.funcTable.length
);
// This function is used to test `getSuffixOrderIndexRangeForCallNode` and
// `getSuffixOrderedCallNodes`. To find the non-inverted call nodes with
// a call path suffix, `nodesWithSuffix` gets the inverted node X for the
// given call path suffix, and lists non-inverted nodes in X's "suffix
// order index range".
// These are the nodes whose call paths, if inverted, would correspond to
// inverted call nodes that are descendants of X.
function nodesWithSuffix(callPathSuffix: CallNodePath) {
const invertedNodeForSuffix = ensureExists(
invertedCallNodeInfo.getCallNodeIndexFromPath(
[...callPathSuffix].reverse()
)
);
const [rangeStart, rangeEnd] =
invertedCallNodeInfo.getSuffixOrderIndexRangeForCallNode(
invertedNodeForSuffix
);
const suffixOrderedCallNodes =
invertedCallNodeInfo.getSuffixOrderedCallNodes();
const nonInvertedCallNodes = new Set<unknown>();
for (let i = rangeStart; i < rangeEnd; i++) {
nonInvertedCallNodes.add(suffixOrderedCallNodes[i]);
}
return nonInvertedCallNodes;
}
return {
funcNamesDict,
nonInvertedCallNodeInfo,
invertedCallNodeInfo,
nodesWithSuffix,
};
}
it('creates a correct suffix order for this example profile', function () {
const {
funcNamesDict: { A, B, C },
nonInvertedCallNodeInfo,
nodesWithSuffix,
} = setup(`
A A A A A A A
B B B A A C
A C B
`);
const cnA = nonInvertedCallNodeInfo.getCallNodeIndexFromPath([A]);
const cnAB = nonInvertedCallNodeInfo.getCallNodeIndexFromPath([A, B]);
const cnABA = nonInvertedCallNodeInfo.getCallNodeIndexFromPath([A, B, A]);
const cnABC = nonInvertedCallNodeInfo.getCallNodeIndexFromPath([A, B, C]);
const cnAA = nonInvertedCallNodeInfo.getCallNodeIndexFromPath([A, A]);
const cnAAB = nonInvertedCallNodeInfo.getCallNodeIndexFromPath([A, A, B]);
const cnAC = nonInvertedCallNodeInfo.getCallNodeIndexFromPath([A, C]);
expect(nodesWithSuffix([A])).toEqual(new Set([cnA, cnABA, cnAA]));
expect(nodesWithSuffix([B])).toEqual(new Set([cnAB, cnAAB]));
expect(nodesWithSuffix([A, B])).toEqual(new Set([cnAB, cnAAB]));
expect(nodesWithSuffix([A, A, B])).toEqual(new Set([cnAAB]));
expect(nodesWithSuffix([C])).toEqual(new Set([cnABC, cnAC]));
});
it('creates a correct suffix order for a different example profile', function () {
const {
funcNamesDict: { A, B, C },
nonInvertedCallNodeInfo,
nodesWithSuffix,
} = setup(`
A A A C
B B
C
`);
const cnABC = nonInvertedCallNodeInfo.getCallNodeIndexFromPath([A, B, C]);
const cnC = nonInvertedCallNodeInfo.getCallNodeIndexFromPath([C]);
expect(nodesWithSuffix([B, C])).toEqual(new Set([cnABC]));
expect(nodesWithSuffix([C])).toEqual(new Set([cnABC, cnC]));
});
});
describe('symbolication', function () {
describe('AddressLocator', function () {
const libs: LibMapping[] = [
{ start: 0, end: 0x20, name: 'first' },
{ start: 0x20, end: 0x40, name: 'second' },
{ start: 0x40, end: 0x50, name: 'third' },
{ start: 0x60, end: 0x80, name: 'fourth' },
{ start: 0x80, end: 0xa0, name: 'fifth' },
{ start: 0xfffff80130000000, end: 0xfffff80131046000, name: 'kernel' },
].map((lib) => {
// Make sure our fixtures are correctly typed.
return Object.assign({}, lib, {
offset: 0,
arch: '',
path: '',
debugName: '',
debugPath: '',
breakpadId: '',
});
});
// Help flow out here.
function getLibName(lib: LibMapping | null) {
if (lib) {
return lib.name;
}
return null;
}
const locator = new AddressLocator(libs);
it('should return the first library for addresses inside the first library', function () {
expect(getLibName(locator.locateAddress('0x0').lib)).toEqual('first');
expect(getLibName(locator.locateAddress('0x10').lib)).toEqual('first');
expect(getLibName(locator.locateAddress('0x1f').lib)).toEqual('first');
});
it('should return the second library for addresses inside the second library', function () {
expect(getLibName(locator.locateAddress('0x20').lib)).toEqual('second');
expect(getLibName(locator.locateAddress('0x21').lib)).toEqual('second');
expect(getLibName(locator.locateAddress('0x2b').lib)).toEqual('second');
expect(getLibName(locator.locateAddress('0x3f').lib)).toEqual('second');
});
it('should return the third library for addresses inside the third library', function () {
expect(getLibName(locator.locateAddress('0x40').lib)).toEqual('third');
expect(getLibName(locator.locateAddress('0x41').lib)).toEqual('third');
expect(getLibName(locator.locateAddress('0x4c').lib)).toEqual('third');
expect(getLibName(locator.locateAddress('0x4f').lib)).toEqual('third');
});
it('should return correct relative addresses for large absolute addresses', function () {
expect(
getLibName(locator.locateAddress('0xfffff80130004123').lib)
).toEqual('kernel');
// Regular JS number subtraction would give the wrong value:
// (0xfffff80130004123 - 0xfffff80130000000).toString(16) === "4000"
expect(
locator.locateAddress('0xfffff80130004123').relativeAddress
).toEqual(0x4123);
});
it('should return no library when outside or in holes', function () {
expect(locator.locateAddress('0xa0').lib).toEqual(null);
expect(locator.locateAddress('0x100').lib).toEqual(null);
expect(locator.locateAddress('0x50').lib).toEqual(null);
expect(locator.locateAddress('0x5a').lib).toEqual(null);
expect(locator.locateAddress('0x5f').lib).toEqual(null);
});
});
describe('symbolicateProfile', function () {
let unsymbolicatedProfile: Profile | null = null;
let symbolicatedProfile: Profile | null = null;
beforeAll(function () {
unsymbolicatedProfile = processGeckoProfile(createGeckoProfile());
const symbolTable = new Map<number, string>();
symbolTable.set(0, 'first symbol');
symbolTable.set(0xf00, 'second symbol');
symbolTable.set(0x1a00, 'third symbol');
symbolTable.set(0x2000, 'last symbol');
const symbolStore = new FakeSymbolStore(
new Map<string, Map<number, string>>([
['firefox', symbolTable],
['firefox-webcontent', symbolTable],
])
);
symbolicatedProfile = Object.assign({}, unsymbolicatedProfile, {
threads: unsymbolicatedProfile.threads.slice(),
});
const symbolicationPromise = symbolicateProfile(
unsymbolicatedProfile,
symbolStore,
(symbolicationStepInfo) => {
if (!symbolicatedProfile) {
throw new Error('symbolicatedProfile cannot be null');
}
const { threads, shared } = applySymbolicationSteps(
symbolicatedProfile.threads,
symbolicatedProfile.shared,
[symbolicationStepInfo]
);
symbolicatedProfile.threads = threads;
symbolicatedProfile.shared = shared;
}
);
return symbolicationPromise;
});
it('should assign correct symbols to frames', function () {
function functionNameForFrameInThread(
_thread: RawThread,
shared: RawProfileSharedData,
frameIndex: IndexIntoFrameTable
) {
const funcIndex = shared.frameTable.func[frameIndex];
const funcNameStringIndex = shared.funcTable.name[funcIndex];
return shared.stringArray[funcNameStringIndex];
}
if (!unsymbolicatedProfile || !symbolicatedProfile) {
throw new Error('Profiles cannot be null');
}
const symbolicatedThread = symbolicatedProfile.threads[0];
const unsymbolicatedThread = unsymbolicatedProfile.threads[0];
expect(
functionNameForFrameInThread(
unsymbolicatedThread,
unsymbolicatedProfile.shared,
1
)
).toEqual('0x100000f84');
expect(
functionNameForFrameInThread(
symbolicatedThread,
symbolicatedProfile.shared,
1
)
).toEqual('second symbol');
expect(
functionNameForFrameInThread(
unsymbolicatedThread,
unsymbolicatedProfile.shared,
2
)
).toEqual('0x100001a45');
expect(
functionNameForFrameInThread(
symbolicatedThread,
symbolicatedProfile.shared,
2
)
).toEqual('third symbol');
});
});
// TODO: check that functions are collapsed correctly
});
describe('filter-by-implementation', function () {
const profile = processGeckoProfile(createGeckoProfileWithJsTimings());
const { derivedThreads } = getProfileWithDicts(profile);
const [thread] = derivedThreads;
function stackIsJS(
filteredThread: Thread,
stackIndex: IndexIntoStackTable | null
) {
if (stackIndex === null) {
throw new Error('stackIndex cannot be null');
}
const frameIndex = filteredThread.stackTable.frame[stackIndex];
const funcIndex = filteredThread.frameTable.func[frameIndex];
return filteredThread.funcTable.isJS[funcIndex];
}
it('will return the same thread if filtering to "all"', function () {
expect(filterThreadByImplementation(thread, 'combined')).toEqual(thread);
});
it('will return only JS samples if filtering to "js"', function () {
const jsOnlyThread = filterThreadByImplementation(thread, 'js');
const nonNullSampleStacks = jsOnlyThread.samples.stack.filter(
(stack) => stack !== null
);
const samplesAreAllJS = nonNullSampleStacks
.map((stack) => stackIsJS(jsOnlyThread, stack))
.reduce((a, b) => a && b);
expect(samplesAreAllJS).toBe(true);
expect(nonNullSampleStacks.length).toBe(4);
});
it('will return only C++ samples if filtering to "cpp"', function () {
const cppOnlyThread = filterThreadByImplementation(thread, 'cpp');
const nonNullSampleStacks = cppOnlyThread.samples.stack.filter(
(stack) => stack !== null
);
const samplesAreAllJS = nonNullSampleStacks
.map((stack) => !stackIsJS(cppOnlyThread, stack))
.reduce((a, b) => a && b);
expect(samplesAreAllJS).toBe(true);
expect(nonNullSampleStacks.length).toBe(10);
});
});
describe('get-sample-index-closest-to-time', function () {
it('returns the correct sample index for a provided time', function () {
const { profile, derivedThreads } = getProfileFromTextSamples(
Array(10).fill('A').join(' ')
);
const [thread] = derivedThreads;
const { samples } = filterThreadByImplementation(thread, 'js');
const interval = profile.meta.interval;
expect(getSampleIndexClosestToStartTime(samples, 0, interval)).toBe(0);
expect(getSampleIndexClosestToStartTime(samples, 0.9, interval)).toBe(0);
expect(getSampleIndexClosestToStartTime(samples, 1.1, interval)).toBe(1);
expect(getSampleIndexClosestToStartTime(samples, 1.5, interval)).toBe(1);
expect(getSampleIndexClosestToStartTime(samples, 9.9, interval)).toBe(9);
expect(getSampleIndexClosestToStartTime(samples, 100, interval)).toBe(9);
});
});
describe('funcHasDirectRecursiveCall and funcHasRecursiveCall', function () {
function setup(textSamples: string) {
const {
derivedThreads,
funcNamesPerThread: [funcNames],
defaultCategory,
} = getProfileFromTextSamples(textSamples);
const [thread] = derivedThreads;
const callNodeTable = getCallNodeInfo(
thread.stackTable,
thread.frameTable,
defaultCategory
).getCallNodeTable();
const jsOnlyThread = filterThreadByImplementation(thread, 'js');
const jsOnlyCallNodeTable = getCallNodeInfo(
jsOnlyThread.stackTable,
jsOnlyThread.frameTable,
defaultCategory
).getCallNodeTable();
return { callNodeTable, jsOnlyCallNodeTable, funcNames };
}
it('correctly identifies directly recursive functions based on the filtered call node table, which takes into account implementation', function () {
const { callNodeTable, jsOnlyCallNodeTable, funcNames } = setup(`
A.js
B.js
C.cpp
B.js
D.js
`);
expect(
funcHasDirectRecursiveCall(callNodeTable, funcNames.indexOf('A.js'))
).toBeFalse();
expect(
funcHasDirectRecursiveCall(callNodeTable, funcNames.indexOf('B.js'))
).toBeFalse();
expect(
funcHasDirectRecursiveCall(jsOnlyCallNodeTable, funcNames.indexOf('B.js'))
).toBeTrue();
});
it('funcHasRecursiveCall correctly identifies directly recursive functions', function () {
const { callNodeTable, funcNames } = setup(`
A.js
B.js
C.cpp
B.js
D.js
`);
expect(
funcHasRecursiveCall(callNodeTable, funcNames.indexOf('A.js'))
).toBeFalse();
expect(
funcHasRecursiveCall(callNodeTable, funcNames.indexOf('B.js'))
).toBeTrue();
expect(
funcHasRecursiveCall(callNodeTable, funcNames.indexOf('C.cpp'))
).toBeFalse();
});
});