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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
base / profiler / stack_sampling_profiler_unittest.cc [blame]
// Copyright 2015 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/profiler/stack_sampling_profiler.h"
#include <stddef.h>
#include <stdint.h>
#include <array>
#include <cstdlib>
#include <memory>
#include <set>
#include <utility>
#include <vector>
#include "base/compiler_specific.h"
#include "base/files/file_util.h"
#include "base/functional/bind.h"
#include "base/functional/callback.h"
#include "base/location.h"
#include "base/memory/ptr_util.h"
#include "base/memory/raw_ptr.h"
#include "base/metrics/metrics_hashes.h"
#include "base/notimplemented.h"
#include "base/profiler/profiler_buildflags.h"
#include "base/profiler/sample_metadata.h"
#include "base/profiler/stack_sampler.h"
#include "base/profiler/stack_sampling_profiler_test_util.h"
#include "base/profiler/unwinder.h"
#include "base/ranges/algorithm.h"
#include "base/run_loop.h"
#include "base/scoped_native_library.h"
#include "base/strings/utf_string_conversions.h"
#include "base/synchronization/lock.h"
#include "base/synchronization/waitable_event.h"
#include "base/test/bind.h"
#include "base/test/task_environment.h"
#include "base/threading/simple_thread.h"
#include "base/time/time.h"
#include "build/build_config.h"
#include "testing/gtest/include/gtest/gtest.h"
#if BUILDFLAG(IS_WIN)
#include <windows.h>
#include <intrin.h>
#include <malloc.h>
#else
#include <alloca.h>
#endif
// STACK_SAMPLING_PROFILER_SUPPORTED is used to conditionally enable the tests
// below for supported platforms (currently Win x64, Mac, iOS 64, some
// Android, and ChromeOS x64).
// ChromeOS: These don't run under MSan because parts of the stack aren't
// initialized.
#if (BUILDFLAG(IS_WIN) && defined(ARCH_CPU_X86_64)) || (BUILDFLAG(IS_MAC)) || \
(BUILDFLAG(IS_IOS) && defined(ARCH_CPU_64_BITS)) || \
(BUILDFLAG(IS_ANDROID) && BUILDFLAG(ENABLE_ARM_CFI_TABLE)) || \
(BUILDFLAG(IS_CHROMEOS) && \
(defined(ARCH_CPU_X86_64) || defined(ARCH_CPU_ARM64)) && \
!defined(MEMORY_SANITIZER))
#define STACK_SAMPLING_PROFILER_SUPPORTED 1
#endif
namespace base {
#if defined(STACK_SAMPLING_PROFILER_SUPPORTED)
#define PROFILER_TEST_F(TestClass, TestName) TEST_F(TestClass, TestName)
#else
#define PROFILER_TEST_F(TestClass, TestName) \
TEST_F(TestClass, DISABLED_##TestName)
#endif
using SamplingParams = StackSamplingProfiler::SamplingParams;
namespace {
// State provided to the ProfileBuilder's ApplyMetadataRetrospectively function.
struct RetrospectiveMetadata {
TimeTicks period_start;
TimeTicks period_end;
MetadataRecorder::Item item;
};
// Profile consists of a set of samples and other sampling information.
struct Profile {
// The collected samples.
std::vector<std::vector<Frame>> samples;
// The number of invocations of RecordMetadata().
int record_metadata_count;
// The retrospective metadata requests.
std::vector<RetrospectiveMetadata> retrospective_metadata;
// The profile metadata requests.
std::vector<MetadataRecorder::Item> profile_metadata;
// Duration of this profile.
TimeDelta profile_duration;
// Time between samples.
TimeDelta sampling_period;
};
// The callback type used to collect a profile. The passed Profile is move-only.
// Other threads, including the UI thread, may block on callback completion so
// this should run as quickly as possible.
using ProfileCompletedCallback = OnceCallback<void(Profile)>;
// TestProfileBuilder collects samples produced by the profiler.
class TestProfileBuilder : public ProfileBuilder {
public:
TestProfileBuilder(ModuleCache* module_cache,
ProfileCompletedCallback callback);
TestProfileBuilder(const TestProfileBuilder&) = delete;
TestProfileBuilder& operator=(const TestProfileBuilder&) = delete;
~TestProfileBuilder() override;
// ProfileBuilder:
ModuleCache* GetModuleCache() override;
void RecordMetadata(
const MetadataRecorder::MetadataProvider& metadata_provider) override;
void ApplyMetadataRetrospectively(
TimeTicks period_start,
TimeTicks period_end,
const MetadataRecorder::Item& item) override;
void AddProfileMetadata(const MetadataRecorder::Item& item) override;
void OnSampleCompleted(std::vector<Frame> sample,
TimeTicks sample_timestamp) override;
void OnProfileCompleted(TimeDelta profile_duration,
TimeDelta sampling_period) override;
private:
raw_ptr<ModuleCache> module_cache_;
// The set of recorded samples.
std::vector<std::vector<Frame>> samples_;
// The number of invocations of RecordMetadata().
int record_metadata_count_ = 0;
// The retrospective metadata requests.
std::vector<RetrospectiveMetadata> retrospective_metadata_;
// The profile metadata requests.
std::vector<MetadataRecorder::Item> profile_metadata_;
// Callback made when sampling a profile completes.
ProfileCompletedCallback callback_;
};
TestProfileBuilder::TestProfileBuilder(ModuleCache* module_cache,
ProfileCompletedCallback callback)
: module_cache_(module_cache), callback_(std::move(callback)) {}
TestProfileBuilder::~TestProfileBuilder() = default;
ModuleCache* TestProfileBuilder::GetModuleCache() {
return module_cache_;
}
void TestProfileBuilder::RecordMetadata(
const MetadataRecorder::MetadataProvider& metadata_provider) {
++record_metadata_count_;
}
void TestProfileBuilder::ApplyMetadataRetrospectively(
TimeTicks period_start,
TimeTicks period_end,
const MetadataRecorder::Item& item) {
retrospective_metadata_.push_back(
RetrospectiveMetadata{period_start, period_end, item});
}
void TestProfileBuilder::AddProfileMetadata(
const MetadataRecorder::Item& item) {
profile_metadata_.push_back(item);
}
void TestProfileBuilder::OnSampleCompleted(std::vector<Frame> sample,
TimeTicks sample_timestamp) {
samples_.push_back(std::move(sample));
}
void TestProfileBuilder::OnProfileCompleted(TimeDelta profile_duration,
TimeDelta sampling_period) {
std::move(callback_).Run(Profile{samples_, record_metadata_count_,
retrospective_metadata_, profile_metadata_,
profile_duration, sampling_period});
}
// Unloads |library| and returns when it has completed unloading. Unloading a
// library is asynchronous on Windows, so simply calling UnloadNativeLibrary()
// is insufficient to ensure it's been unloaded.
void SynchronousUnloadNativeLibrary(NativeLibrary library) {
UnloadNativeLibrary(library);
#if BUILDFLAG(IS_WIN)
// NativeLibrary is a typedef for HMODULE, which is actually the base address
// of the module.
uintptr_t module_base_address = reinterpret_cast<uintptr_t>(library);
HMODULE module_handle;
// Keep trying to get the module handle until the call fails.
while (::GetModuleHandleEx(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS |
GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
reinterpret_cast<LPCTSTR>(module_base_address),
&module_handle) ||
::GetLastError() != ERROR_MOD_NOT_FOUND) {
PlatformThread::Sleep(Milliseconds(1));
}
#elif BUILDFLAG(IS_APPLE) || BUILDFLAG(IS_ANDROID) || BUILDFLAG(IS_CHROMEOS)
// Unloading a library on Mac and Android is synchronous.
#else
NOTIMPLEMENTED();
#endif
}
void WithTargetThread(ProfileCallback profile_callback) {
UnwindScenario scenario(BindRepeating(&CallWithPlainFunction));
WithTargetThread(&scenario, std::move(profile_callback));
}
struct TestProfilerInfo {
TestProfilerInfo(SamplingProfilerThreadToken thread_token,
const SamplingParams& params,
ModuleCache* module_cache,
StackSamplerTestDelegate* delegate = nullptr)
: completed(WaitableEvent::ResetPolicy::MANUAL,
WaitableEvent::InitialState::NOT_SIGNALED),
profiler(thread_token,
params,
std::make_unique<TestProfileBuilder>(
module_cache,
BindLambdaForTesting([this](Profile result_profile) {
profile = std::move(result_profile);
completed.Signal();
})),
CreateCoreUnwindersFactoryForTesting(module_cache),
RepeatingClosure(),
delegate) {}
TestProfilerInfo(const TestProfilerInfo&) = delete;
TestProfilerInfo& operator=(const TestProfilerInfo&) = delete;
// The order here is important to ensure objects being referenced don't get
// destructed until after the objects referencing them.
Profile profile;
WaitableEvent completed;
StackSamplingProfiler profiler;
};
// Captures samples as specified by |params| on the TargetThread, and returns
// them. Waits up to |profiler_wait_time| for the profiler to complete.
std::vector<std::vector<Frame>> CaptureSamples(const SamplingParams& params,
TimeDelta profiler_wait_time,
ModuleCache* module_cache) {
std::vector<std::vector<Frame>> samples;
WithTargetThread(BindLambdaForTesting(
[&](SamplingProfilerThreadToken target_thread_token) {
TestProfilerInfo info(target_thread_token, params, module_cache);
info.profiler.Start();
info.completed.TimedWait(profiler_wait_time);
info.profiler.Stop();
info.completed.Wait();
samples = std::move(info.profile.samples);
}));
return samples;
}
// Waits for one of multiple samplings to complete.
size_t WaitForSamplingComplete(
const std::vector<std::unique_ptr<TestProfilerInfo>>& infos) {
// Map unique_ptrs to something that WaitMany can accept.
std::vector<WaitableEvent*> sampling_completed_rawptrs(infos.size());
ranges::transform(infos, sampling_completed_rawptrs.begin(),
[](const std::unique_ptr<TestProfilerInfo>& info) {
return &info.get()->completed;
});
// Wait for one profiler to finish.
return WaitableEvent::WaitMany(sampling_completed_rawptrs.data(),
sampling_completed_rawptrs.size());
}
// Returns a duration that is longer than the test timeout. We would use
// TimeDelta::Max() but https://crbug.com/465948.
TimeDelta AVeryLongTimeDelta() {
return Days(1);
}
// Tests the scenario where the library is unloaded after copying the stack, but
// before walking it. If |wait_until_unloaded| is true, ensures that the
// asynchronous library loading has completed before walking the stack. If
// false, the unloading may still be occurring during the stack walk.
void TestLibraryUnload(bool wait_until_unloaded, ModuleCache* module_cache) {
// Test delegate that supports intervening between the copying of the stack
// and the walking of the stack.
class StackCopiedSignaler : public StackSamplerTestDelegate {
public:
StackCopiedSignaler(WaitableEvent* stack_copied,
WaitableEvent* start_stack_walk,
bool wait_to_walk_stack)
: stack_copied_(stack_copied),
start_stack_walk_(start_stack_walk),
wait_to_walk_stack_(wait_to_walk_stack) {}
void OnPreStackWalk() override {
stack_copied_->Signal();
if (wait_to_walk_stack_)
start_stack_walk_->Wait();
}
private:
const raw_ptr<WaitableEvent> stack_copied_;
const raw_ptr<WaitableEvent> start_stack_walk_;
const bool wait_to_walk_stack_;
};
SamplingParams params;
params.sampling_interval = Milliseconds(0);
params.samples_per_profile = 1;
NativeLibrary other_library = LoadOtherLibrary();
// TODO(crbug.com/40061562): Remove `UnsafeDanglingUntriaged`
UnwindScenario scenario(BindRepeating(
&CallThroughOtherLibrary, UnsafeDanglingUntriaged(other_library)));
UnwindScenario::SampleEvents events;
TargetThread target_thread(
BindLambdaForTesting([&] { scenario.Execute(&events); }));
target_thread.Start();
events.ready_for_sample.Wait();
WaitableEvent sampling_thread_completed(
WaitableEvent::ResetPolicy::MANUAL,
WaitableEvent::InitialState::NOT_SIGNALED);
Profile profile;
WaitableEvent stack_copied(WaitableEvent::ResetPolicy::MANUAL,
WaitableEvent::InitialState::NOT_SIGNALED);
WaitableEvent start_stack_walk(WaitableEvent::ResetPolicy::MANUAL,
WaitableEvent::InitialState::NOT_SIGNALED);
StackCopiedSignaler test_delegate(&stack_copied, &start_stack_walk,
wait_until_unloaded);
StackSamplingProfiler profiler(
target_thread.thread_token(), params,
std::make_unique<TestProfileBuilder>(
module_cache,
BindLambdaForTesting(
[&profile, &sampling_thread_completed](Profile result_profile) {
profile = std::move(result_profile);
sampling_thread_completed.Signal();
})),
CreateCoreUnwindersFactoryForTesting(module_cache), RepeatingClosure(),
&test_delegate);
profiler.Start();
// Wait for the stack to be copied and the target thread to be resumed.
stack_copied.Wait();
// Cause the target thread to finish, so that it's no longer executing code in
// the library we're about to unload.
events.sample_finished.Signal();
target_thread.Join();
// Unload the library now that it's not being used.
if (wait_until_unloaded)
SynchronousUnloadNativeLibrary(other_library);
else
UnloadNativeLibrary(other_library);
// Let the stack walk commence after unloading the library, if we're waiting
// on that event.
start_stack_walk.Signal();
// Wait for the sampling thread to complete and fill out |profile|.
sampling_thread_completed.Wait();
// Look up the sample.
ASSERT_EQ(1u, profile.samples.size());
const std::vector<Frame>& sample = profile.samples[0];
if (wait_until_unloaded) {
// We expect the stack to look something like this, with the frame in the
// now-unloaded library having a null module.
//
// ... WaitableEvent and system frames ...
// WaitForSample()
// TargetThread::OtherLibraryCallback
// <frame in unloaded library>
EXPECT_EQ(nullptr, sample.back().module)
<< "Stack:\n"
<< FormatSampleForDiagnosticOutput(sample);
ExpectStackContains(sample, {scenario.GetWaitForSampleAddressRange()});
ExpectStackDoesNotContain(sample,
{scenario.GetSetupFunctionAddressRange(),
scenario.GetOuterFunctionAddressRange()});
} else {
// We didn't wait for the asynchronous unloading to complete, so the results
// are non-deterministic: if the library finished unloading we should have
// the same stack as |wait_until_unloaded|, if not we should have the full
// stack. The important thing is that we should not crash.
if (!sample.back().module) {
// This is the same case as |wait_until_unloaded|.
ExpectStackContains(sample, {scenario.GetWaitForSampleAddressRange()});
ExpectStackDoesNotContain(sample,
{scenario.GetSetupFunctionAddressRange(),
scenario.GetOuterFunctionAddressRange()});
return;
}
ExpectStackContains(sample, {scenario.GetWaitForSampleAddressRange(),
scenario.GetSetupFunctionAddressRange(),
scenario.GetOuterFunctionAddressRange()});
}
}
// Provide a suitable (and clean) environment for the tests below. All tests
// must use this class to ensure that proper clean-up is done and thus be
// usable in a later test.
class StackSamplingProfilerTest : public testing::Test {
public:
StackSamplingProfilerTest() = default;
void SetUp() override {
// The idle-shutdown time is too long for convenient (and accurate) testing.
// That behavior is checked instead by artificially triggering it through
// the TestPeer.
StackSamplingProfiler::TestPeer::DisableIdleShutdown();
}
void TearDown() override {
// Be a good citizen and clean up after ourselves. This also re-enables the
// idle-shutdown behavior.
StackSamplingProfiler::TestPeer::Reset();
}
protected:
ModuleCache* module_cache() { return &module_cache_; }
private:
ModuleCache module_cache_;
base::test::TaskEnvironment task_environment_;
};
} // namespace
// Checks that the basic expected information is present in sampled frames.
//
// macOS ASAN is not yet supported - crbug.com/718628.
//
// TODO(crbug.com/40702833): Enable this test again for Android with
// ASAN. This is now disabled because the android-asan bot fails.
//
// If we're running the ChromeOS unit tests on Linux, this test will never pass
// because Ubuntu's libc isn't compiled with frame pointers. Skip if not a real
// ChromeOS device.
#if (defined(ADDRESS_SANITIZER) && BUILDFLAG(IS_APPLE)) || \
(defined(ADDRESS_SANITIZER) && BUILDFLAG(IS_ANDROID)) || \
(BUILDFLAG(IS_CHROMEOS) && !BUILDFLAG(IS_CHROMEOS_DEVICE))
#define MAYBE_Basic DISABLED_Basic
#else
#define MAYBE_Basic Basic
#endif
PROFILER_TEST_F(StackSamplingProfilerTest, MAYBE_Basic) {
UnwindScenario scenario(BindRepeating(&CallWithPlainFunction));
const std::vector<Frame>& sample = SampleScenario(&scenario, module_cache());
// Check that all the modules are valid.
for (const auto& frame : sample)
EXPECT_NE(nullptr, frame.module);
// The stack should contain a full unwind.
ExpectStackContains(sample, {scenario.GetWaitForSampleAddressRange(),
scenario.GetSetupFunctionAddressRange(),
scenario.GetOuterFunctionAddressRange()});
}
// A simple unwinder that always generates one frame then aborts the stack walk.
class TestAuxUnwinder : public Unwinder {
public:
TestAuxUnwinder(const Frame& frame_to_report,
base::RepeatingClosure add_initial_modules_callback)
: frame_to_report_(frame_to_report),
add_initial_modules_callback_(std::move(add_initial_modules_callback)) {
}
TestAuxUnwinder(const TestAuxUnwinder&) = delete;
TestAuxUnwinder& operator=(const TestAuxUnwinder&) = delete;
void InitializeModules() override {
if (add_initial_modules_callback_)
add_initial_modules_callback_.Run();
}
bool CanUnwindFrom(const Frame& current_frame) const override { return true; }
UnwindResult TryUnwind(UnwinderStateCapture* capture_state,
RegisterContext* thread_context,
uintptr_t stack_top,
std::vector<Frame>* stack) override {
stack->push_back(frame_to_report_);
return UnwindResult::kAborted;
}
private:
const Frame frame_to_report_;
base::RepeatingClosure add_initial_modules_callback_;
};
// Checks that the profiler handles stacks containing dynamically-allocated
// stack memory.
// macOS ASAN is not yet supported - crbug.com/718628.
// Android is not supported since Chrome unwind tables don't support dynamic
// frames.
// If we're running the ChromeOS unit tests on Linux, this test will never pass
// because Ubuntu's libc isn't compiled with frame pointers. Skip if not a real
// ChromeOS device.
#if (defined(ADDRESS_SANITIZER) && BUILDFLAG(IS_APPLE)) || \
BUILDFLAG(IS_ANDROID) || \
(BUILDFLAG(IS_CHROMEOS) && !BUILDFLAG(IS_CHROMEOS_DEVICE))
#define MAYBE_Alloca DISABLED_Alloca
#else
#define MAYBE_Alloca Alloca
#endif
PROFILER_TEST_F(StackSamplingProfilerTest, MAYBE_Alloca) {
UnwindScenario scenario(BindRepeating(&CallWithAlloca));
const std::vector<Frame>& sample = SampleScenario(&scenario, module_cache());
// The stack should contain a full unwind.
ExpectStackContains(sample, {scenario.GetWaitForSampleAddressRange(),
scenario.GetSetupFunctionAddressRange(),
scenario.GetOuterFunctionAddressRange()});
}
// Checks that a stack that runs through another library produces a stack with
// the expected functions.
// macOS ASAN is not yet supported - crbug.com/718628.
// iOS chrome doesn't support loading native libraries.
// Android is not supported when EXCLUDE_UNWIND_TABLES |other_library| doesn't
// have unwind tables.
// TODO(crbug.com/40702833): Enable this test again for Android with
// ASAN. This is now disabled because the android-asan bot fails.
// If we're running the ChromeOS unit tests on Linux, this test will never pass
// because Ubuntu's libc isn't compiled with frame pointers. Skip if not a real
// ChromeOS device.
#if (defined(ADDRESS_SANITIZER) && BUILDFLAG(IS_APPLE)) || \
BUILDFLAG(IS_IOS) || \
(BUILDFLAG(IS_ANDROID) && BUILDFLAG(EXCLUDE_UNWIND_TABLES)) || \
(BUILDFLAG(IS_ANDROID) && defined(ADDRESS_SANITIZER)) || \
(BUILDFLAG(IS_CHROMEOS) && !BUILDFLAG(IS_CHROMEOS_DEVICE))
#define MAYBE_OtherLibrary DISABLED_OtherLibrary
#else
#define MAYBE_OtherLibrary OtherLibrary
#endif
PROFILER_TEST_F(StackSamplingProfilerTest, MAYBE_OtherLibrary) {
ScopedNativeLibrary other_library(LoadOtherLibrary());
UnwindScenario scenario(
BindRepeating(&CallThroughOtherLibrary, Unretained(other_library.get())));
const std::vector<Frame>& sample = SampleScenario(&scenario, module_cache());
// The stack should contain a full unwind.
ExpectStackContains(sample, {scenario.GetWaitForSampleAddressRange(),
scenario.GetSetupFunctionAddressRange(),
scenario.GetOuterFunctionAddressRange()});
}
// Checks that a stack that runs through a library that is unloading produces a
// stack, and doesn't crash.
// Unloading is synchronous on the Mac, so this test is inapplicable.
// Android is not supported when EXCLUDE_UNWIND_TABLES |other_library| doesn't
// have unwind tables.
// TODO(crbug.com/40702833): Enable this test again for Android with
// ASAN. This is now disabled because the android-asan bot fails.
// If we're running the ChromeOS unit tests on Linux, this test will never pass
// because Ubuntu's libc isn't compiled with frame pointers. Skip if not a real
// ChromeOS device.
#if BUILDFLAG(IS_APPLE) || \
(BUILDFLAG(IS_ANDROID) && BUILDFLAG(EXCLUDE_UNWIND_TABLES)) || \
(BUILDFLAG(IS_ANDROID) && defined(ADDRESS_SANITIZER)) || \
(BUILDFLAG(IS_CHROMEOS) && !BUILDFLAG(IS_CHROMEOS_DEVICE))
#define MAYBE_UnloadingLibrary DISABLED_UnloadingLibrary
#else
#define MAYBE_UnloadingLibrary UnloadingLibrary
#endif
PROFILER_TEST_F(StackSamplingProfilerTest, MAYBE_UnloadingLibrary) {
TestLibraryUnload(false, module_cache());
}
// Checks that a stack that runs through a library that has been unloaded
// produces a stack, and doesn't crash.
// macOS ASAN is not yet supported - crbug.com/718628.
// Android is not supported since modules are found before unwinding.
// If we're running the ChromeOS unit tests on Linux, this test will never pass
// because Ubuntu's libc isn't compiled with frame pointers. Skip if not a real
// ChromeOS device.
#if (defined(ADDRESS_SANITIZER) && BUILDFLAG(IS_APPLE)) || \
BUILDFLAG(IS_ANDROID) || BUILDFLAG(IS_IOS) || \
(BUILDFLAG(IS_CHROMEOS) && !BUILDFLAG(IS_CHROMEOS_DEVICE))
#define MAYBE_UnloadedLibrary DISABLED_UnloadedLibrary
#else
#define MAYBE_UnloadedLibrary UnloadedLibrary
#endif
PROFILER_TEST_F(StackSamplingProfilerTest, MAYBE_UnloadedLibrary) {
TestLibraryUnload(true, module_cache());
}
// Checks that a profiler can stop/destruct without ever having started.
PROFILER_TEST_F(StackSamplingProfilerTest, StopWithoutStarting) {
WithTargetThread(BindLambdaForTesting(
[this](SamplingProfilerThreadToken target_thread_token) {
SamplingParams params;
params.sampling_interval = Milliseconds(0);
params.samples_per_profile = 1;
Profile profile;
WaitableEvent sampling_completed(
WaitableEvent::ResetPolicy::MANUAL,
WaitableEvent::InitialState::NOT_SIGNALED);
StackSamplingProfiler profiler(
target_thread_token, params,
std::make_unique<TestProfileBuilder>(
module_cache(),
BindLambdaForTesting(
[&profile, &sampling_completed](Profile result_profile) {
profile = std::move(result_profile);
sampling_completed.Signal();
})),
CreateCoreUnwindersFactoryForTesting(module_cache()));
profiler.Stop(); // Constructed but never started.
EXPECT_FALSE(sampling_completed.IsSignaled());
}));
}
// Checks that its okay to stop a profiler before it finishes even when the
// sampling thread continues to run.
PROFILER_TEST_F(StackSamplingProfilerTest, StopSafely) {
// Test delegate that counts samples.
class SampleRecordedCounter : public StackSamplerTestDelegate {
public:
SampleRecordedCounter() = default;
void OnPreStackWalk() override {
AutoLock lock(lock_);
++count_;
}
size_t Get() {
AutoLock lock(lock_);
return count_;
}
private:
Lock lock_;
size_t count_ = 0;
};
WithTargetThread(
BindLambdaForTesting([](SamplingProfilerThreadToken target_thread_token) {
std::array<SamplingParams, 2> params;
// Providing an initial delay makes it more likely that both will be
// scheduled before either starts to run. Once started, samples will
// run ordered by their scheduled, interleaved times regardless of
// whatever interval the thread wakes up.
params[0].initial_delay = Milliseconds(10);
params[0].sampling_interval = Milliseconds(1);
params[0].samples_per_profile = 100000;
params[1].initial_delay = Milliseconds(10);
params[1].sampling_interval = Milliseconds(1);
params[1].samples_per_profile = 100000;
std::array<SampleRecordedCounter, std::size(params)> samples_recorded;
ModuleCache module_cache1, module_cache2;
TestProfilerInfo profiler_info0(target_thread_token, params[0],
&module_cache1, &samples_recorded[0]);
TestProfilerInfo profiler_info1(target_thread_token, params[1],
&module_cache2, &samples_recorded[1]);
profiler_info0.profiler.Start();
profiler_info1.profiler.Start();
// Wait for both to start accumulating samples. Using a WaitableEvent is
// possible but gets complicated later on because there's no way of
// knowing if 0 or 1 additional sample will be taken after Stop() and
// thus no way of knowing how many Wait() calls to make on it.
while (samples_recorded[0].Get() == 0 || samples_recorded[1].Get() == 0)
PlatformThread::Sleep(Milliseconds(1));
// Ensure that the first sampler can be safely stopped while the second
// continues to run. The stopped first profiler will still have a
// RecordSampleTask pending that will do nothing when executed because
// the collection will have been removed by Stop().
profiler_info0.profiler.Stop();
profiler_info0.completed.Wait();
size_t count0 = samples_recorded[0].Get();
size_t count1 = samples_recorded[1].Get();
// Waiting for the second sampler to collect a couple samples ensures
// that the pending RecordSampleTask for the first has executed because
// tasks are always ordered by their next scheduled time.
while (samples_recorded[1].Get() < count1 + 2)
PlatformThread::Sleep(Milliseconds(1));
// Ensure that the first profiler didn't do anything since it was
// stopped.
EXPECT_EQ(count0, samples_recorded[0].Get());
}));
}
// Checks that no sample are captured if the profiling is stopped during the
// initial delay.
PROFILER_TEST_F(StackSamplingProfilerTest, StopDuringInitialDelay) {
SamplingParams params;
params.initial_delay = Seconds(60);
std::vector<std::vector<Frame>> samples =
CaptureSamples(params, Milliseconds(0), module_cache());
EXPECT_TRUE(samples.empty());
}
// Checks that tasks can be stopped before completion and incomplete samples are
// captured.
PROFILER_TEST_F(StackSamplingProfilerTest, StopDuringInterSampleInterval) {
// Test delegate that counts samples.
class SampleRecordedEvent : public StackSamplerTestDelegate {
public:
SampleRecordedEvent()
: sample_recorded_(WaitableEvent::ResetPolicy::MANUAL,
WaitableEvent::InitialState::NOT_SIGNALED) {}
void OnPreStackWalk() override { sample_recorded_.Signal(); }
void WaitForSample() { sample_recorded_.Wait(); }
private:
WaitableEvent sample_recorded_;
};
WithTargetThread(BindLambdaForTesting(
[this](SamplingProfilerThreadToken target_thread_token) {
SamplingParams params;
params.sampling_interval = AVeryLongTimeDelta();
params.samples_per_profile = 2;
SampleRecordedEvent samples_recorded;
TestProfilerInfo profiler_info(target_thread_token, params,
module_cache(), &samples_recorded);
profiler_info.profiler.Start();
// Wait for profiler to start accumulating samples.
samples_recorded.WaitForSample();
// Ensure that it can stop safely.
profiler_info.profiler.Stop();
profiler_info.completed.Wait();
EXPECT_EQ(1u, profiler_info.profile.samples.size());
}));
}
PROFILER_TEST_F(StackSamplingProfilerTest, GetNextSampleTime_NormalExecution) {
const auto& GetNextSampleTime =
StackSamplingProfiler::TestPeer::GetNextSampleTime;
const TimeTicks scheduled_current_sample_time = TimeTicks::UnixEpoch();
const TimeDelta sampling_interval = Milliseconds(10);
// When executing the sample at exactly the scheduled time the next sample
// should be one interval later.
EXPECT_EQ(scheduled_current_sample_time + sampling_interval,
GetNextSampleTime(scheduled_current_sample_time, sampling_interval,
scheduled_current_sample_time));
// When executing the sample less than half an interval after the scheduled
// time the next sample also should be one interval later.
EXPECT_EQ(scheduled_current_sample_time + sampling_interval,
GetNextSampleTime(
scheduled_current_sample_time, sampling_interval,
scheduled_current_sample_time + 0.4 * sampling_interval));
// When executing the sample less than half an interval before the scheduled
// time the next sample also should be one interval later. This is not
// expected to occur in practice since delayed tasks never run early.
EXPECT_EQ(scheduled_current_sample_time + sampling_interval,
GetNextSampleTime(
scheduled_current_sample_time, sampling_interval,
scheduled_current_sample_time - 0.4 * sampling_interval));
}
PROFILER_TEST_F(StackSamplingProfilerTest, GetNextSampleTime_DelayedExecution) {
const auto& GetNextSampleTime =
StackSamplingProfiler::TestPeer::GetNextSampleTime;
const TimeTicks scheduled_current_sample_time = TimeTicks::UnixEpoch();
const TimeDelta sampling_interval = Milliseconds(10);
// When executing the sample between 0.5 and 1.5 intervals after the scheduled
// time the next sample should be two intervals later.
EXPECT_EQ(scheduled_current_sample_time + 2 * sampling_interval,
GetNextSampleTime(
scheduled_current_sample_time, sampling_interval,
scheduled_current_sample_time + 0.6 * sampling_interval));
EXPECT_EQ(scheduled_current_sample_time + 2 * sampling_interval,
GetNextSampleTime(
scheduled_current_sample_time, sampling_interval,
scheduled_current_sample_time + 1.0 * sampling_interval));
EXPECT_EQ(scheduled_current_sample_time + 2 * sampling_interval,
GetNextSampleTime(
scheduled_current_sample_time, sampling_interval,
scheduled_current_sample_time + 1.4 * sampling_interval));
// Similarly when executing the sample between 9.5 and 10.5 intervals after
// the scheduled time the next sample should be 11 intervals later.
EXPECT_EQ(scheduled_current_sample_time + 11 * sampling_interval,
GetNextSampleTime(
scheduled_current_sample_time, sampling_interval,
scheduled_current_sample_time + 9.6 * sampling_interval));
EXPECT_EQ(scheduled_current_sample_time + 11 * sampling_interval,
GetNextSampleTime(
scheduled_current_sample_time, sampling_interval,
scheduled_current_sample_time + 10.0 * sampling_interval));
EXPECT_EQ(scheduled_current_sample_time + 11 * sampling_interval,
GetNextSampleTime(
scheduled_current_sample_time, sampling_interval,
scheduled_current_sample_time + 10.4 * sampling_interval));
}
// Checks that we can destroy the profiler while profiling.
PROFILER_TEST_F(StackSamplingProfilerTest, DestroyProfilerWhileProfiling) {
SamplingParams params;
params.sampling_interval = Milliseconds(10);
Profile profile;
WithTargetThread(BindLambdaForTesting([&, this](SamplingProfilerThreadToken
target_thread_token) {
std::unique_ptr<StackSamplingProfiler> profiler;
auto profile_builder = std::make_unique<TestProfileBuilder>(
module_cache(),
BindLambdaForTesting([&profile](Profile result_profile) {
profile = std::move(result_profile);
}));
profiler = std::make_unique<StackSamplingProfiler>(
target_thread_token, params, std::move(profile_builder),
CreateCoreUnwindersFactoryForTesting(module_cache()));
profiler->Start();
profiler.reset();
// Wait longer than a sample interval to catch any use-after-free actions by
// the profiler thread.
PlatformThread::Sleep(Milliseconds(50));
}));
}
// Checks that the different profilers may be run.
PROFILER_TEST_F(StackSamplingProfilerTest, CanRunMultipleProfilers) {
SamplingParams params;
params.sampling_interval = Milliseconds(0);
params.samples_per_profile = 1;
std::vector<std::vector<Frame>> samples =
CaptureSamples(params, AVeryLongTimeDelta(), module_cache());
ASSERT_EQ(1u, samples.size());
samples = CaptureSamples(params, AVeryLongTimeDelta(), module_cache());
ASSERT_EQ(1u, samples.size());
}
// Checks that a sampler can be started while another is running.
PROFILER_TEST_F(StackSamplingProfilerTest, MultipleStart) {
WithTargetThread(
BindLambdaForTesting([](SamplingProfilerThreadToken target_thread_token) {
SamplingParams params1;
params1.initial_delay = AVeryLongTimeDelta();
params1.samples_per_profile = 1;
ModuleCache module_cache1;
TestProfilerInfo profiler_info1(target_thread_token, params1,
&module_cache1);
SamplingParams params2;
params2.sampling_interval = Milliseconds(1);
params2.samples_per_profile = 1;
ModuleCache module_cache2;
TestProfilerInfo profiler_info2(target_thread_token, params2,
&module_cache2);
profiler_info1.profiler.Start();
profiler_info2.profiler.Start();
profiler_info2.completed.Wait();
EXPECT_EQ(1u, profiler_info2.profile.samples.size());
}));
}
// Checks that the profile duration and the sampling interval are calculated
// correctly. Also checks that RecordMetadata() is invoked each time a sample
// is recorded.
PROFILER_TEST_F(StackSamplingProfilerTest, ProfileGeneralInfo) {
WithTargetThread(BindLambdaForTesting(
[this](SamplingProfilerThreadToken target_thread_token) {
SamplingParams params;
params.sampling_interval = Milliseconds(1);
params.samples_per_profile = 3;
TestProfilerInfo profiler_info(target_thread_token, params,
module_cache());
profiler_info.profiler.Start();
profiler_info.completed.Wait();
EXPECT_EQ(3u, profiler_info.profile.samples.size());
// The profile duration should be greater than the total sampling
// intervals.
EXPECT_GT(profiler_info.profile.profile_duration,
profiler_info.profile.sampling_period * 3);
EXPECT_EQ(Milliseconds(1), profiler_info.profile.sampling_period);
// The number of invocations of RecordMetadata() should be equal to the
// number of samples recorded.
EXPECT_EQ(3, profiler_info.profile.record_metadata_count);
}));
}
// Checks that the sampling thread can shut down.
PROFILER_TEST_F(StackSamplingProfilerTest, SamplerIdleShutdown) {
SamplingParams params;
params.sampling_interval = Milliseconds(0);
params.samples_per_profile = 1;
std::vector<std::vector<Frame>> samples =
CaptureSamples(params, AVeryLongTimeDelta(), module_cache());
ASSERT_EQ(1u, samples.size());
// Capture thread should still be running at this point.
ASSERT_TRUE(StackSamplingProfiler::TestPeer::IsSamplingThreadRunning());
// Initiate an "idle" shutdown and ensure it happens. Idle-shutdown was
// disabled by the test fixture so the test will fail due to a timeout if
// it does not exit.
StackSamplingProfiler::TestPeer::PerformSamplingThreadIdleShutdown(false);
// While the shutdown has been initiated, the actual exit of the thread still
// happens asynchronously. Watch until the thread actually exits. This test
// will time-out in the case of failure.
while (StackSamplingProfiler::TestPeer::IsSamplingThreadRunning())
PlatformThread::Sleep(Milliseconds(1));
}
// Checks that additional requests will restart a stopped profiler.
PROFILER_TEST_F(StackSamplingProfilerTest,
WillRestartSamplerAfterIdleShutdown) {
SamplingParams params;
params.sampling_interval = Milliseconds(0);
params.samples_per_profile = 1;
std::vector<std::vector<Frame>> samples =
CaptureSamples(params, AVeryLongTimeDelta(), module_cache());
ASSERT_EQ(1u, samples.size());
// Capture thread should still be running at this point.
ASSERT_TRUE(StackSamplingProfiler::TestPeer::IsSamplingThreadRunning());
// Post a ShutdownTask on the sampling thread which, when executed, will
// mark the thread as EXITING and begin shut down of the thread.
StackSamplingProfiler::TestPeer::PerformSamplingThreadIdleShutdown(false);
// Ensure another capture will start the sampling thread and run.
samples = CaptureSamples(params, AVeryLongTimeDelta(), module_cache());
ASSERT_EQ(1u, samples.size());
EXPECT_TRUE(StackSamplingProfiler::TestPeer::IsSamplingThreadRunning());
}
// Checks that it's safe to stop a task after it's completed and the sampling
// thread has shut-down for being idle.
PROFILER_TEST_F(StackSamplingProfilerTest, StopAfterIdleShutdown) {
WithTargetThread(BindLambdaForTesting(
[this](SamplingProfilerThreadToken target_thread_token) {
SamplingParams params;
params.sampling_interval = Milliseconds(1);
params.samples_per_profile = 1;
TestProfilerInfo profiler_info(target_thread_token, params,
module_cache());
profiler_info.profiler.Start();
profiler_info.completed.Wait();
// Capture thread should still be running at this point.
ASSERT_TRUE(StackSamplingProfiler::TestPeer::IsSamplingThreadRunning());
// Perform an idle shutdown.
StackSamplingProfiler::TestPeer::PerformSamplingThreadIdleShutdown(
false);
// Stop should be safe though its impossible to know at this moment if
// the sampling thread has completely exited or will just "stop soon".
profiler_info.profiler.Stop();
}));
}
// Checks that profilers can run both before and after the sampling thread has
// started.
PROFILER_TEST_F(StackSamplingProfilerTest,
ProfileBeforeAndAfterSamplingThreadRunning) {
WithTargetThread(
BindLambdaForTesting([](SamplingProfilerThreadToken target_thread_token) {
ModuleCache module_cache1;
ModuleCache module_cache2;
std::vector<std::unique_ptr<TestProfilerInfo>> profiler_infos;
profiler_infos.push_back(std::make_unique<TestProfilerInfo>(
target_thread_token,
SamplingParams{/*initial_delay=*/AVeryLongTimeDelta(),
/*samples_per_profile=*/1,
/*sampling_interval=*/Milliseconds(1)},
&module_cache1));
profiler_infos.push_back(std::make_unique<TestProfilerInfo>(
target_thread_token,
SamplingParams{/*initial_delay=*/Milliseconds(0),
/*samples_per_profile=*/1,
/*sampling_interval=*/Milliseconds(1)},
&module_cache2));
// First profiler is started when there has never been a sampling
// thread.
EXPECT_FALSE(
StackSamplingProfiler::TestPeer::IsSamplingThreadRunning());
profiler_infos[0]->profiler.Start();
// Second profiler is started when sampling thread is already running.
EXPECT_TRUE(StackSamplingProfiler::TestPeer::IsSamplingThreadRunning());
profiler_infos[1]->profiler.Start();
// Only the second profiler should finish before test times out.
size_t completed_profiler = WaitForSamplingComplete(profiler_infos);
EXPECT_EQ(1U, completed_profiler);
}));
}
// Checks that an idle-shutdown task will abort if a new profiler starts
// between when it was posted and when it runs.
PROFILER_TEST_F(StackSamplingProfilerTest, IdleShutdownAbort) {
WithTargetThread(BindLambdaForTesting(
[this](SamplingProfilerThreadToken target_thread_token) {
SamplingParams params;
params.sampling_interval = Milliseconds(1);
params.samples_per_profile = 1;
TestProfilerInfo profiler_info(target_thread_token, params,
module_cache());
profiler_info.profiler.Start();
profiler_info.completed.Wait();
EXPECT_EQ(1u, profiler_info.profile.samples.size());
// Perform an idle shutdown but simulate that a new capture is started
// before it can actually run.
StackSamplingProfiler::TestPeer::PerformSamplingThreadIdleShutdown(
true);
// Though the shutdown-task has been executed, any actual exit of the
// thread is asynchronous so there is no way to detect that *didn't*
// exit except to wait a reasonable amount of time and then check. Since
// the thread was just running ("perform" blocked until it was), it
// should finish almost immediately and without any waiting for tasks or
// events.
PlatformThread::Sleep(Milliseconds(200));
EXPECT_TRUE(StackSamplingProfiler::TestPeer::IsSamplingThreadRunning());
// Ensure that it's still possible to run another sampler.
TestProfilerInfo another_info(target_thread_token, params,
module_cache());
another_info.profiler.Start();
another_info.completed.Wait();
EXPECT_EQ(1u, another_info.profile.samples.size());
}));
}
// Checks that synchronized multiple sampling requests execute in parallel.
PROFILER_TEST_F(StackSamplingProfilerTest, ConcurrentProfiling_InSync) {
WithTargetThread(
BindLambdaForTesting([](SamplingProfilerThreadToken target_thread_token) {
ModuleCache module_cache1;
ModuleCache module_cache2;
// Providing an initial delay makes it more likely that both will be
// scheduled before either starts to run. Once started, samples will
// run ordered by their scheduled, interleaved times regardless of
// whatever interval the thread wakes up. Thus, total execution time
// will be 10ms (delay) + 10x1ms (sampling) + 1/2 timer minimum
// interval.
std::vector<std::unique_ptr<TestProfilerInfo>> profiler_infos;
profiler_infos.push_back(std::make_unique<TestProfilerInfo>(
target_thread_token,
SamplingParams{/*initial_delay=*/Milliseconds(10),
/*samples_per_profile=*/9,
/*sampling_interval=*/Milliseconds(1)},
&module_cache1));
profiler_infos.push_back(std::make_unique<TestProfilerInfo>(
target_thread_token,
SamplingParams{/*initial_delay=*/Milliseconds(11),
/*samples_per_profile=*/8,
/*sampling_interval=*/Milliseconds(1)},
&module_cache2));
profiler_infos[0]->profiler.Start();
profiler_infos[1]->profiler.Start();
// Wait for one profiler to finish.
size_t completed_profiler = WaitForSamplingComplete(profiler_infos);
size_t other_profiler = 1 - completed_profiler;
// Wait for the other profiler to finish.
profiler_infos[other_profiler]->completed.Wait();
// Ensure each got the correct number of samples.
EXPECT_EQ(9u, profiler_infos[0]->profile.samples.size());
EXPECT_EQ(8u, profiler_infos[1]->profile.samples.size());
}));
}
// Checks that several mixed sampling requests execute in parallel.
PROFILER_TEST_F(StackSamplingProfilerTest, ConcurrentProfiling_Mixed) {
WithTargetThread(
BindLambdaForTesting([](SamplingProfilerThreadToken target_thread_token) {
std::vector<ModuleCache> module_caches(3);
std::vector<std::unique_ptr<TestProfilerInfo>> profiler_infos;
profiler_infos.push_back(std::make_unique<TestProfilerInfo>(
target_thread_token,
SamplingParams{/*initial_delay=*/Milliseconds(8),
/*samples_per_profile=*/10,
/*sampling_interval=*/Milliseconds(4)},
&module_caches[0]));
profiler_infos.push_back(std::make_unique<TestProfilerInfo>(
target_thread_token,
SamplingParams{/*initial_delay=*/Milliseconds(9),
/*samples_per_profile=*/10,
/*sampling_interval=*/Milliseconds(3)},
&module_caches[1]));
profiler_infos.push_back(std::make_unique<TestProfilerInfo>(
target_thread_token,
SamplingParams{/*initial_delay=*/Milliseconds(10),
/*samples_per_profile=*/10,
/*sampling_interval=*/Milliseconds(2)},
&module_caches[2]));
for (auto& i : profiler_infos) {
i->profiler.Start();
}
// Wait for one profiler to finish.
size_t completed_profiler = WaitForSamplingComplete(profiler_infos);
EXPECT_EQ(10u,
profiler_infos[completed_profiler]->profile.samples.size());
// Stop and destroy all profilers, always in the same order. Don't
// crash.
for (auto& i : profiler_infos) {
i->profiler.Stop();
}
for (auto& i : profiler_infos) {
i.reset();
}
}));
}
// Checks that different threads can be sampled in parallel.
PROFILER_TEST_F(StackSamplingProfilerTest, MultipleSampledThreads) {
UnwindScenario scenario1(BindRepeating(&CallWithPlainFunction));
UnwindScenario::SampleEvents events1;
TargetThread target_thread1(
BindLambdaForTesting([&] { scenario1.Execute(&events1); }));
target_thread1.Start();
events1.ready_for_sample.Wait();
UnwindScenario scenario2(BindRepeating(&CallWithPlainFunction));
UnwindScenario::SampleEvents events2;
TargetThread target_thread2(
BindLambdaForTesting([&] { scenario2.Execute(&events2); }));
target_thread2.Start();
events2.ready_for_sample.Wait();
// Providing an initial delay makes it more likely that both will be
// scheduled before either starts to run. Once started, samples will
// run ordered by their scheduled, interleaved times regardless of
// whatever interval the thread wakes up.
SamplingParams params1, params2;
params1.initial_delay = Milliseconds(10);
params1.sampling_interval = Milliseconds(1);
params1.samples_per_profile = 9;
params2.initial_delay = Milliseconds(10);
params2.sampling_interval = Milliseconds(1);
params2.samples_per_profile = 8;
Profile profile1, profile2;
ModuleCache module_cache1, module_cache2;
WaitableEvent sampling_thread_completed1(
WaitableEvent::ResetPolicy::MANUAL,
WaitableEvent::InitialState::NOT_SIGNALED);
StackSamplingProfiler profiler1(
target_thread1.thread_token(), params1,
std::make_unique<TestProfileBuilder>(
&module_cache1,
BindLambdaForTesting(
[&profile1, &sampling_thread_completed1](Profile result_profile) {
profile1 = std::move(result_profile);
sampling_thread_completed1.Signal();
})),
CreateCoreUnwindersFactoryForTesting(&module_cache1));
WaitableEvent sampling_thread_completed2(
WaitableEvent::ResetPolicy::MANUAL,
WaitableEvent::InitialState::NOT_SIGNALED);
StackSamplingProfiler profiler2(
target_thread2.thread_token(), params2,
std::make_unique<TestProfileBuilder>(
&module_cache2,
BindLambdaForTesting(
[&profile2, &sampling_thread_completed2](Profile result_profile) {
profile2 = std::move(result_profile);
sampling_thread_completed2.Signal();
})),
CreateCoreUnwindersFactoryForTesting(&module_cache2));
// Finally the real work.
profiler1.Start();
profiler2.Start();
sampling_thread_completed1.Wait();
sampling_thread_completed2.Wait();
EXPECT_EQ(9u, profile1.samples.size());
EXPECT_EQ(8u, profile2.samples.size());
events1.sample_finished.Signal();
events2.sample_finished.Signal();
target_thread1.Join();
target_thread2.Join();
}
// A simple thread that runs a profiler on another thread.
class ProfilerThread : public SimpleThread {
public:
ProfilerThread(const std::string& name,
SamplingProfilerThreadToken thread_token,
const SamplingParams& params,
ModuleCache* module_cache)
: SimpleThread(name, Options()),
run_(WaitableEvent::ResetPolicy::MANUAL,
WaitableEvent::InitialState::NOT_SIGNALED),
completed_(WaitableEvent::ResetPolicy::MANUAL,
WaitableEvent::InitialState::NOT_SIGNALED),
profiler_(thread_token,
params,
std::make_unique<TestProfileBuilder>(
module_cache,
BindLambdaForTesting([this](Profile result_profile) {
profile_ = std::move(result_profile);
completed_.Signal();
})),
CreateCoreUnwindersFactoryForTesting(module_cache)) {}
void Run() override {
run_.Wait();
profiler_.Start();
}
void Go() { run_.Signal(); }
void Wait() { completed_.Wait(); }
Profile& profile() { return profile_; }
private:
WaitableEvent run_;
Profile profile_;
WaitableEvent completed_;
StackSamplingProfiler profiler_;
};
// Checks that different threads can run samplers in parallel.
PROFILER_TEST_F(StackSamplingProfilerTest, MultipleProfilerThreads) {
WithTargetThread(
BindLambdaForTesting([](SamplingProfilerThreadToken target_thread_token) {
// Providing an initial delay makes it more likely that both will be
// scheduled before either starts to run. Once started, samples will
// run ordered by their scheduled, interleaved times regardless of
// whatever interval the thread wakes up.
SamplingParams params1, params2;
params1.initial_delay = Milliseconds(10);
params1.sampling_interval = Milliseconds(1);
params1.samples_per_profile = 9;
params2.initial_delay = Milliseconds(10);
params2.sampling_interval = Milliseconds(1);
params2.samples_per_profile = 8;
// Start the profiler threads and give them a moment to get going.
ModuleCache module_cache1;
ProfilerThread profiler_thread1("profiler1", target_thread_token,
params1, &module_cache1);
ModuleCache module_cache2;
ProfilerThread profiler_thread2("profiler2", target_thread_token,
params2, &module_cache2);
profiler_thread1.Start();
profiler_thread2.Start();
PlatformThread::Sleep(Milliseconds(10));
// This will (approximately) synchronize the two threads.
profiler_thread1.Go();
profiler_thread2.Go();
// Wait for them both to finish and validate collection.
profiler_thread1.Wait();
profiler_thread2.Wait();
EXPECT_EQ(9u, profiler_thread1.profile().samples.size());
EXPECT_EQ(8u, profiler_thread2.profile().samples.size());
profiler_thread1.Join();
profiler_thread2.Join();
}));
}
PROFILER_TEST_F(StackSamplingProfilerTest, AddAuxUnwinder_BeforeStart) {
SamplingParams params;
params.sampling_interval = Milliseconds(0);
params.samples_per_profile = 1;
UnwindScenario scenario(BindRepeating(&CallWithPlainFunction));
int add_initial_modules_invocation_count = 0;
const auto add_initial_modules_callback =
[&add_initial_modules_invocation_count] {
++add_initial_modules_invocation_count;
};
Profile profile;
WithTargetThread(
&scenario,
BindLambdaForTesting(
[&](SamplingProfilerThreadToken target_thread_token) {
WaitableEvent sampling_thread_completed(
WaitableEvent::ResetPolicy::MANUAL,
WaitableEvent::InitialState::NOT_SIGNALED);
StackSamplingProfiler profiler(
target_thread_token, params,
std::make_unique<TestProfileBuilder>(
module_cache(),
BindLambdaForTesting([&profile, &sampling_thread_completed](
Profile result_profile) {
profile = std::move(result_profile);
sampling_thread_completed.Signal();
})),
CreateCoreUnwindersFactoryForTesting(module_cache()));
profiler.AddAuxUnwinder(std::make_unique<TestAuxUnwinder>(
Frame(23, nullptr),
BindLambdaForTesting(add_initial_modules_callback)));
profiler.Start();
sampling_thread_completed.Wait();
}));
ASSERT_EQ(1, add_initial_modules_invocation_count);
// The sample should have one frame from the context values aFFnd one from the
// TestAuxUnwinder.
ASSERT_EQ(1u, profile.samples.size());
const std::vector<Frame>& frames = profile.samples[0];
ASSERT_EQ(2u, frames.size());
EXPECT_EQ(23u, frames[1].instruction_pointer);
EXPECT_EQ(nullptr, frames[1].module);
}
PROFILER_TEST_F(StackSamplingProfilerTest, AddAuxUnwinder_AfterStart) {
SamplingParams params;
params.sampling_interval = Milliseconds(10);
params.samples_per_profile = 2;
UnwindScenario scenario(BindRepeating(&CallWithPlainFunction));
int add_initial_modules_invocation_count = 0;
const auto add_initial_modules_callback =
[&add_initial_modules_invocation_count] {
++add_initial_modules_invocation_count;
};
Profile profile;
WithTargetThread(
&scenario,
BindLambdaForTesting(
[&](SamplingProfilerThreadToken target_thread_token) {
WaitableEvent sampling_thread_completed(
WaitableEvent::ResetPolicy::MANUAL,
WaitableEvent::InitialState::NOT_SIGNALED);
StackSamplingProfiler profiler(
target_thread_token, params,
std::make_unique<TestProfileBuilder>(
module_cache(),
BindLambdaForTesting([&profile, &sampling_thread_completed](
Profile result_profile) {
profile = std::move(result_profile);
sampling_thread_completed.Signal();
})),
CreateCoreUnwindersFactoryForTesting(module_cache()));
profiler.Start();
profiler.AddAuxUnwinder(std::make_unique<TestAuxUnwinder>(
Frame(23, nullptr),
BindLambdaForTesting(add_initial_modules_callback)));
sampling_thread_completed.Wait();
}));
ASSERT_EQ(1, add_initial_modules_invocation_count);
// The sample should have one frame from the context values and one from the
// TestAuxUnwinder.
ASSERT_EQ(2u, profile.samples.size());
// Whether the aux unwinder is available for the first sample is racy, so rely
// on the second sample.
const std::vector<Frame>& frames = profile.samples[1];
ASSERT_EQ(2u, frames.size());
EXPECT_EQ(23u, frames[1].instruction_pointer);
EXPECT_EQ(nullptr, frames[1].module);
}
PROFILER_TEST_F(StackSamplingProfilerTest, AddAuxUnwinder_AfterStop) {
SamplingParams params;
params.sampling_interval = Milliseconds(0);
params.samples_per_profile = 1;
UnwindScenario scenario(BindRepeating(&CallWithPlainFunction));
Profile profile;
WithTargetThread(
&scenario,
BindLambdaForTesting(
[&](SamplingProfilerThreadToken target_thread_token) {
WaitableEvent sampling_thread_completed(
WaitableEvent::ResetPolicy::MANUAL,
WaitableEvent::InitialState::NOT_SIGNALED);
StackSamplingProfiler profiler(
target_thread_token, params,
std::make_unique<TestProfileBuilder>(
module_cache(),
BindLambdaForTesting([&profile, &sampling_thread_completed](
Profile result_profile) {
profile = std::move(result_profile);
sampling_thread_completed.Signal();
})),
CreateCoreUnwindersFactoryForTesting(module_cache()));
profiler.Start();
profiler.Stop();
profiler.AddAuxUnwinder(std::make_unique<TestAuxUnwinder>(
Frame(23, nullptr), base::RepeatingClosure()));
sampling_thread_completed.Wait();
}));
// The AuxUnwinder should be accepted without error. It will have no effect
// since the collection has stopped.
}
// Checks that requests to apply metadata to past samples are passed on to the
// profile builder.
PROFILER_TEST_F(StackSamplingProfilerTest,
ApplyMetadataToPastSamples_PassedToProfileBuilder) {
// Runs the passed closure on the profiler thread after a sample is taken.
class PostSampleInvoker : public StackSamplerTestDelegate {
public:
explicit PostSampleInvoker(RepeatingClosure post_sample_closure)
: post_sample_closure_(std::move(post_sample_closure)) {}
void OnPreStackWalk() override { post_sample_closure_.Run(); }
private:
RepeatingClosure post_sample_closure_;
};
// Thread-safe representation of the times that samples were taken.
class SynchronizedSampleTimes {
public:
void AddNow() {
AutoLock lock(lock_);
times_.push_back(TimeTicks::Now());
}
std::vector<TimeTicks> GetTimes() {
AutoLock lock(lock_);
return times_;
}
private:
Lock lock_;
std::vector<TimeTicks> times_;
};
SamplingParams params;
params.sampling_interval = Milliseconds(10);
// 10,000 samples ensures the profiler continues running until manually
// stopped, after applying metadata.
params.samples_per_profile = 10000;
UnwindScenario scenario(BindRepeating(&CallWithPlainFunction));
std::vector<TimeTicks> sample_times;
Profile profile;
WithTargetThread(
&scenario,
BindLambdaForTesting(
[&](SamplingProfilerThreadToken target_thread_token) {
SynchronizedSampleTimes synchronized_sample_times;
WaitableEvent sample_seen(WaitableEvent::ResetPolicy::AUTOMATIC);
PostSampleInvoker post_sample_invoker(BindLambdaForTesting([&] {
synchronized_sample_times.AddNow();
sample_seen.Signal();
}));
StackSamplingProfiler profiler(
target_thread_token, params,
std::make_unique<TestProfileBuilder>(
module_cache(),
BindLambdaForTesting([&profile](Profile result_profile) {
profile = std::move(result_profile);
})),
CreateCoreUnwindersFactoryForTesting(module_cache()),
RepeatingClosure(), &post_sample_invoker);
profiler.Start();
// Wait for 5 samples to be collected.
for (int i = 0; i < 5; ++i)
sample_seen.Wait();
sample_times = synchronized_sample_times.GetTimes();
// Record metadata on past samples, with and without a key value.
// The range [times[1], times[3]] is guaranteed to include only
// samples 2 and 3, and likewise [times[2], times[4]] is guaranteed
// to include only samples 3 and 4.
ApplyMetadataToPastSamples(sample_times[1], sample_times[3],
"TestMetadata1", 10,
base::SampleMetadataScope::kProcess);
ApplyMetadataToPastSamples(sample_times[2], sample_times[4],
"TestMetadata2", 100, 11,
base::SampleMetadataScope::kProcess);
profiler.Stop();
}));
ASSERT_EQ(2u, profile.retrospective_metadata.size());
const RetrospectiveMetadata& metadata1 = profile.retrospective_metadata[0];
EXPECT_EQ(sample_times[1], metadata1.period_start);
EXPECT_EQ(sample_times[3], metadata1.period_end);
EXPECT_EQ(HashMetricName("TestMetadata1"), metadata1.item.name_hash);
EXPECT_FALSE(metadata1.item.key.has_value());
EXPECT_EQ(10, metadata1.item.value);
const RetrospectiveMetadata& metadata2 = profile.retrospective_metadata[1];
EXPECT_EQ(sample_times[2], metadata2.period_start);
EXPECT_EQ(sample_times[4], metadata2.period_end);
EXPECT_EQ(HashMetricName("TestMetadata2"), metadata2.item.name_hash);
ASSERT_TRUE(metadata2.item.key.has_value());
EXPECT_EQ(100, *metadata2.item.key);
EXPECT_EQ(11, metadata2.item.value);
}
PROFILER_TEST_F(
StackSamplingProfilerTest,
ApplyMetadataToPastSamples_PassedToProfileBuilder_MultipleCollections) {
SamplingParams params;
params.sampling_interval = Milliseconds(10);
// 10,000 samples ensures the profiler continues running until manually
// stopped, after applying metadata.
params.samples_per_profile = 10000;
ModuleCache module_cache1, module_cache2;
WaitableEvent profiler1_started;
WaitableEvent profiler2_started;
WaitableEvent profiler1_metadata_applied;
WaitableEvent profiler2_metadata_applied;
Profile profile1;
WaitableEvent sampling_completed1;
TargetThread target_thread1(BindLambdaForTesting([&] {
StackSamplingProfiler profiler1(
target_thread1.thread_token(), params,
std::make_unique<TestProfileBuilder>(
&module_cache1, BindLambdaForTesting([&](Profile result_profile) {
profile1 = std::move(result_profile);
sampling_completed1.Signal();
})),
CreateCoreUnwindersFactoryForTesting(&module_cache1),
RepeatingClosure());
profiler1.Start();
profiler1_started.Signal();
profiler2_started.Wait();
// Record metadata on past samples only for this thread. The time range
// shouldn't affect the outcome, it should always be passed to the
// ProfileBuilder.
ApplyMetadataToPastSamples(TimeTicks(), TimeTicks::Now(), "TestMetadata1",
10, 10, SampleMetadataScope::kThread);
profiler1_metadata_applied.Signal();
profiler2_metadata_applied.Wait();
profiler1.Stop();
}));
target_thread1.Start();
Profile profile2;
WaitableEvent sampling_completed2;
TargetThread target_thread2(BindLambdaForTesting([&] {
StackSamplingProfiler profiler2(
target_thread2.thread_token(), params,
std::make_unique<TestProfileBuilder>(
&module_cache2, BindLambdaForTesting([&](Profile result_profile) {
profile2 = std::move(result_profile);
sampling_completed2.Signal();
})),
CreateCoreUnwindersFactoryForTesting(&module_cache2),
RepeatingClosure());
profiler2.Start();
profiler2_started.Signal();
profiler1_started.Wait();
// Record metadata on past samples only for this thread.
ApplyMetadataToPastSamples(TimeTicks(), TimeTicks::Now(), "TestMetadata2",
20, 20, SampleMetadataScope::kThread);
profiler2_metadata_applied.Signal();
profiler1_metadata_applied.Wait();
profiler2.Stop();
}));
target_thread2.Start();
target_thread1.Join();
target_thread2.Join();
// Wait for the profile to be captured before checking expectations.
sampling_completed1.Wait();
sampling_completed2.Wait();
ASSERT_EQ(1u, profile1.retrospective_metadata.size());
ASSERT_EQ(1u, profile2.retrospective_metadata.size());
{
const RetrospectiveMetadata& metadata1 = profile1.retrospective_metadata[0];
EXPECT_EQ(HashMetricName("TestMetadata1"), metadata1.item.name_hash);
ASSERT_TRUE(metadata1.item.key.has_value());
EXPECT_EQ(10, *metadata1.item.key);
EXPECT_EQ(10, metadata1.item.value);
}
{
const RetrospectiveMetadata& metadata2 = profile2.retrospective_metadata[0];
EXPECT_EQ(HashMetricName("TestMetadata2"), metadata2.item.name_hash);
ASSERT_TRUE(metadata2.item.key.has_value());
EXPECT_EQ(20, *metadata2.item.key);
EXPECT_EQ(20, metadata2.item.value);
}
}
// Checks that requests to add profile metadata are passed on to the profile
// builder.
PROFILER_TEST_F(StackSamplingProfilerTest,
AddProfileMetadata_PassedToProfileBuilder) {
// Runs the passed closure on the profiler thread after a sample is taken.
class PostSampleInvoker : public StackSamplerTestDelegate {
public:
explicit PostSampleInvoker(RepeatingClosure post_sample_closure)
: post_sample_closure_(std::move(post_sample_closure)) {}
void OnPreStackWalk() override { post_sample_closure_.Run(); }
private:
RepeatingClosure post_sample_closure_;
};
SamplingParams params;
params.sampling_interval = Milliseconds(10);
// 10,000 samples ensures the profiler continues running until manually
// stopped.
params.samples_per_profile = 10000;
UnwindScenario scenario(BindRepeating(&CallWithPlainFunction));
Profile profile;
WithTargetThread(
&scenario,
BindLambdaForTesting(
[&](SamplingProfilerThreadToken target_thread_token) {
WaitableEvent sample_seen(WaitableEvent::ResetPolicy::AUTOMATIC);
PostSampleInvoker post_sample_invoker(
BindLambdaForTesting([&] { sample_seen.Signal(); }));
StackSamplingProfiler profiler(
target_thread_token, params,
std::make_unique<TestProfileBuilder>(
module_cache(),
BindLambdaForTesting([&profile](Profile result_profile) {
profile = std::move(result_profile);
})),
CreateCoreUnwindersFactoryForTesting(module_cache()),
RepeatingClosure(), &post_sample_invoker);
profiler.Start();
sample_seen.Wait();
AddProfileMetadata("TestMetadata", 1, 2,
SampleMetadataScope::kProcess);
profiler.Stop();
}));
ASSERT_EQ(1u, profile.profile_metadata.size());
const MetadataRecorder::Item& item = profile.profile_metadata[0];
EXPECT_EQ(HashMetricName("TestMetadata"), item.name_hash);
EXPECT_EQ(1, *item.key);
EXPECT_EQ(2, item.value);
}
PROFILER_TEST_F(StackSamplingProfilerTest,
AddProfileMetadata_PassedToProfileBuilder_MultipleCollections) {
SamplingParams params;
params.sampling_interval = Milliseconds(10);
// 10,000 samples ensures the profiler continues running until manually
// stopped.
params.samples_per_profile = 10000;
ModuleCache module_cache1, module_cache2;
WaitableEvent profiler1_started;
WaitableEvent profiler2_started;
WaitableEvent profiler1_metadata_applied;
WaitableEvent profiler2_metadata_applied;
Profile profile1;
WaitableEvent sampling_completed1;
TargetThread target_thread1(BindLambdaForTesting([&] {
StackSamplingProfiler profiler1(
target_thread1.thread_token(), params,
std::make_unique<TestProfileBuilder>(
&module_cache1, BindLambdaForTesting([&](Profile result_profile) {
profile1 = std::move(result_profile);
sampling_completed1.Signal();
})),
CreateCoreUnwindersFactoryForTesting(&module_cache1),
RepeatingClosure());
profiler1.Start();
profiler1_started.Signal();
profiler2_started.Wait();
AddProfileMetadata("TestMetadata1", 1, 2, SampleMetadataScope::kThread);
profiler1_metadata_applied.Signal();
profiler2_metadata_applied.Wait();
profiler1.Stop();
}));
target_thread1.Start();
Profile profile2;
WaitableEvent sampling_completed2;
TargetThread target_thread2(BindLambdaForTesting([&] {
StackSamplingProfiler profiler2(
target_thread2.thread_token(), params,
std::make_unique<TestProfileBuilder>(
&module_cache2, BindLambdaForTesting([&](Profile result_profile) {
profile2 = std::move(result_profile);
sampling_completed2.Signal();
})),
CreateCoreUnwindersFactoryForTesting(&module_cache2),
RepeatingClosure());
profiler2.Start();
profiler2_started.Signal();
profiler1_started.Wait();
AddProfileMetadata("TestMetadata2", 11, 12, SampleMetadataScope::kThread);
profiler2_metadata_applied.Signal();
profiler1_metadata_applied.Wait();
profiler2.Stop();
}));
target_thread2.Start();
target_thread1.Join();
target_thread2.Join();
// Wait for the profile to be captured before checking expectations.
sampling_completed1.Wait();
sampling_completed2.Wait();
ASSERT_EQ(1u, profile1.profile_metadata.size());
ASSERT_EQ(1u, profile2.profile_metadata.size());
{
const MetadataRecorder::Item& item = profile1.profile_metadata[0];
EXPECT_EQ(HashMetricName("TestMetadata1"), item.name_hash);
ASSERT_TRUE(item.key.has_value());
EXPECT_EQ(1, *item.key);
EXPECT_EQ(2, item.value);
}
{
const MetadataRecorder::Item& item = profile2.profile_metadata[0];
EXPECT_EQ(HashMetricName("TestMetadata2"), item.name_hash);
ASSERT_TRUE(item.key.has_value());
EXPECT_EQ(11, *item.key);
EXPECT_EQ(12, item.value);
}
}
} // namespace base