forked from Pissandshittium/pissandshittium
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpartition_alloc_support.cc
1498 lines (1343 loc) · 56.9 KB
/
partition_alloc_support.cc
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
// Copyright 2021 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/allocator/partition_alloc_support.h"
#include <array>
#include <cinttypes>
#include <cstdint>
#include <map>
#include <string>
#include "base/allocator/partition_alloc_features.h"
#include "base/allocator/partition_allocator/allocation_guard.h"
#include "base/allocator/partition_allocator/dangling_raw_ptr_checks.h"
#include "base/allocator/partition_allocator/memory_reclaimer.h"
#include "base/allocator/partition_allocator/page_allocator.h"
#include "base/allocator/partition_allocator/partition_alloc_base/debug/alias.h"
#include "base/allocator/partition_allocator/partition_alloc_base/threading/platform_thread.h"
#include "base/allocator/partition_allocator/partition_alloc_buildflags.h"
#include "base/allocator/partition_allocator/partition_alloc_check.h"
#include "base/allocator/partition_allocator/partition_alloc_config.h"
#include "base/allocator/partition_allocator/partition_lock.h"
#include "base/allocator/partition_allocator/pointers/raw_ptr.h"
#include "base/allocator/partition_allocator/shim/allocator_shim.h"
#include "base/allocator/partition_allocator/shim/allocator_shim_default_dispatch_to_partition_alloc.h"
#include "base/allocator/partition_allocator/thread_cache.h"
#include "base/at_exit.h"
#include "base/check.h"
#include "base/cpu.h"
#include "base/debug/dump_without_crashing.h"
#include "base/debug/stack_trace.h"
#include "base/debug/task_trace.h"
#include "base/feature_list.h"
#include "base/functional/bind.h"
#include "base/functional/callback.h"
#include "base/immediate_crash.h"
#include "base/location.h"
#include "base/memory/raw_ptr_asan_service.h"
#include "base/metrics/histogram_functions.h"
#include "base/metrics/histogram_macros.h"
#include "base/no_destructor.h"
#include "base/pending_task.h"
#include "base/strings/string_piece.h"
#include "base/strings/string_split.h"
#include "base/strings/stringprintf.h"
#include "base/system/sys_info.h"
#include "base/task/single_thread_task_runner.h"
#include "base/thread_annotations.h"
#include "base/threading/platform_thread.h"
#include "base/time/time.h"
#include "base/timer/timer.h"
#include "base/trace_event/base_tracing.h"
#include "build/build_config.h"
#include "third_party/abseil-cpp/absl/types/optional.h"
#if BUILDFLAG(USE_STARSCAN)
#include "base/allocator/partition_allocator/shim/nonscannable_allocator.h"
#include "base/allocator/partition_allocator/starscan/pcscan.h"
#include "base/allocator/partition_allocator/starscan/pcscan_scheduling.h"
#include "base/allocator/partition_allocator/starscan/stack/stack.h"
#include "base/allocator/partition_allocator/starscan/stats_collector.h"
#include "base/allocator/partition_allocator/starscan/stats_reporter.h"
#endif // BUILDFLAG(USE_STARSCAN)
#if BUILDFLAG(IS_ANDROID)
#include "base/system/sys_info.h"
#endif
#if BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC)
#include "base/allocator/partition_allocator/memory_reclaimer.h"
#endif
namespace base::allocator {
namespace {
// This is defined in content/public/common/content_switches.h, which is not
// accessible in ::base. They must be kept in sync.
namespace switches {
[[maybe_unused]] constexpr char kRendererProcess[] = "renderer";
constexpr char kZygoteProcess[] = "zygote";
#if BUILDFLAG(USE_STARSCAN)
constexpr char kGpuProcess[] = "gpu-process";
constexpr char kUtilityProcess[] = "utility";
#endif
} // namespace switches
#if BUILDFLAG(USE_STARSCAN)
#if BUILDFLAG(ENABLE_BASE_TRACING)
constexpr const char* ScannerIdToTracingString(
partition_alloc::internal::StatsCollector::ScannerId id) {
switch (id) {
case partition_alloc::internal::StatsCollector::ScannerId::kClear:
return "PCScan.Scanner.Clear";
case partition_alloc::internal::StatsCollector::ScannerId::kScan:
return "PCScan.Scanner.Scan";
case partition_alloc::internal::StatsCollector::ScannerId::kSweep:
return "PCScan.Scanner.Sweep";
case partition_alloc::internal::StatsCollector::ScannerId::kOverall:
return "PCScan.Scanner";
case partition_alloc::internal::StatsCollector::ScannerId::kNumIds:
__builtin_unreachable();
}
}
constexpr const char* MutatorIdToTracingString(
partition_alloc::internal::StatsCollector::MutatorId id) {
switch (id) {
case partition_alloc::internal::StatsCollector::MutatorId::kClear:
return "PCScan.Mutator.Clear";
case partition_alloc::internal::StatsCollector::MutatorId::kScanStack:
return "PCScan.Mutator.ScanStack";
case partition_alloc::internal::StatsCollector::MutatorId::kScan:
return "PCScan.Mutator.Scan";
case partition_alloc::internal::StatsCollector::MutatorId::kOverall:
return "PCScan.Mutator";
case partition_alloc::internal::StatsCollector::MutatorId::kNumIds:
__builtin_unreachable();
}
}
#endif // BUILDFLAG(ENABLE_BASE_TRACING)
// Inject TRACE_EVENT_BEGIN/END, TRACE_COUNTER1, and UmaHistogramTimes.
class StatsReporterImpl final : public partition_alloc::StatsReporter {
public:
void ReportTraceEvent(
partition_alloc::internal::StatsCollector::ScannerId id,
[[maybe_unused]] partition_alloc::internal::base::PlatformThreadId tid,
int64_t start_time_ticks_internal_value,
int64_t end_time_ticks_internal_value) override {
#if BUILDFLAG(ENABLE_BASE_TRACING)
// TRACE_EVENT_* macros below drop most parameters when tracing is
// disabled at compile time.
const char* tracing_id = ScannerIdToTracingString(id);
const TimeTicks start_time =
TimeTicks::FromInternalValue(start_time_ticks_internal_value);
const TimeTicks end_time =
TimeTicks::FromInternalValue(end_time_ticks_internal_value);
TRACE_EVENT_BEGIN(kTraceCategory, perfetto::StaticString(tracing_id),
perfetto::ThreadTrack::ForThread(tid), start_time);
TRACE_EVENT_END(kTraceCategory, perfetto::ThreadTrack::ForThread(tid),
end_time);
#endif // BUILDFLAG(ENABLE_BASE_TRACING)
}
void ReportTraceEvent(
partition_alloc::internal::StatsCollector::MutatorId id,
[[maybe_unused]] partition_alloc::internal::base::PlatformThreadId tid,
int64_t start_time_ticks_internal_value,
int64_t end_time_ticks_internal_value) override {
#if BUILDFLAG(ENABLE_BASE_TRACING)
// TRACE_EVENT_* macros below drop most parameters when tracing is
// disabled at compile time.
const char* tracing_id = MutatorIdToTracingString(id);
const TimeTicks start_time =
TimeTicks::FromInternalValue(start_time_ticks_internal_value);
const TimeTicks end_time =
TimeTicks::FromInternalValue(end_time_ticks_internal_value);
TRACE_EVENT_BEGIN(kTraceCategory, perfetto::StaticString(tracing_id),
perfetto::ThreadTrack::ForThread(tid), start_time);
TRACE_EVENT_END(kTraceCategory, perfetto::ThreadTrack::ForThread(tid),
end_time);
#endif // BUILDFLAG(ENABLE_BASE_TRACING)
}
void ReportSurvivedQuarantineSize(size_t survived_size) override {
TRACE_COUNTER1(kTraceCategory, "PCScan.SurvivedQuarantineSize",
survived_size);
}
void ReportSurvivedQuarantinePercent(double survived_rate) override {
// Multiply by 1000 since TRACE_COUNTER1 expects integer. In catapult,
// divide back.
// TODO(bikineev): Remove after switching to perfetto.
TRACE_COUNTER1(kTraceCategory, "PCScan.SurvivedQuarantinePercent",
1000 * survived_rate);
}
void ReportStats(const char* stats_name, int64_t sample_in_usec) override {
TimeDelta sample = Microseconds(sample_in_usec);
UmaHistogramTimes(stats_name, sample);
}
private:
static constexpr char kTraceCategory[] = "partition_alloc";
};
#endif // BUILDFLAG(USE_STARSCAN)
} // namespace
#if BUILDFLAG(USE_STARSCAN)
void RegisterPCScanStatsReporter() {
static StatsReporterImpl s_reporter;
static bool registered = false;
DCHECK(!registered);
partition_alloc::internal::PCScan::RegisterStatsReporter(&s_reporter);
registered = true;
}
#endif // BUILDFLAG(USE_STARSCAN)
namespace {
void RunThreadCachePeriodicPurge() {
// Micros, since periodic purge should typically take at most a few ms.
SCOPED_UMA_HISTOGRAM_TIMER_MICROS("Memory.PartitionAlloc.PeriodicPurge");
TRACE_EVENT0("memory", "PeriodicPurge");
auto& instance = ::partition_alloc::ThreadCacheRegistry::Instance();
instance.RunPeriodicPurge();
TimeDelta delay =
Microseconds(instance.GetPeriodicPurgeNextIntervalInMicroseconds());
SingleThreadTaskRunner::GetCurrentDefault()->PostDelayedTask(
FROM_HERE, BindOnce(RunThreadCachePeriodicPurge), delay);
}
void RunMemoryReclaimer(scoped_refptr<SequencedTaskRunner> task_runner) {
TRACE_EVENT0("base", "partition_alloc::MemoryReclaimer::Reclaim()");
auto* instance = ::partition_alloc::MemoryReclaimer::Instance();
{
// Micros, since memory reclaiming should typically take at most a few ms.
SCOPED_UMA_HISTOGRAM_TIMER_MICROS("Memory.PartitionAlloc.MemoryReclaim");
instance->ReclaimNormal();
}
TimeDelta delay =
Microseconds(instance->GetRecommendedReclaimIntervalInMicroseconds());
task_runner->PostDelayedTask(
FROM_HERE, BindOnce(RunMemoryReclaimer, task_runner), delay);
}
} // namespace
void StartThreadCachePeriodicPurge() {
auto& instance = ::partition_alloc::ThreadCacheRegistry::Instance();
TimeDelta delay =
Microseconds(instance.GetPeriodicPurgeNextIntervalInMicroseconds());
SingleThreadTaskRunner::GetCurrentDefault()->PostDelayedTask(
FROM_HERE, BindOnce(RunThreadCachePeriodicPurge), delay);
}
void StartMemoryReclaimer(scoped_refptr<SequencedTaskRunner> task_runner) {
// Can be called several times.
static bool is_memory_reclaimer_running = false;
if (is_memory_reclaimer_running) {
return;
}
is_memory_reclaimer_running = true;
// The caller of the API fully controls where running the reclaim.
// However there are a few reasons to recommend that the caller runs
// it on the main thread:
// - Most of PartitionAlloc's usage is on the main thread, hence PA's metadata
// is more likely in cache when executing on the main thread.
// - Memory reclaim takes the partition lock for each partition. As a
// consequence, while reclaim is running, the main thread is unlikely to be
// able to make progress, as it would be waiting on the lock.
// - Finally, this runs in idle time only, so there should be no visible
// impact.
//
// From local testing, time to reclaim is 100us-1ms, and reclaiming every few
// seconds is useful. Since this is meant to run during idle time only, it is
// a reasonable starting point balancing effectivenes vs cost. See
// crbug.com/942512 for details and experimental results.
auto* instance = ::partition_alloc::MemoryReclaimer::Instance();
TimeDelta delay =
Microseconds(instance->GetRecommendedReclaimIntervalInMicroseconds());
task_runner->PostDelayedTask(
FROM_HERE, BindOnce(RunMemoryReclaimer, task_runner), delay);
}
std::map<std::string, std::string> ProposeSyntheticFinchTrials() {
std::map<std::string, std::string> trials;
#if BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC)
// BackupRefPtr_Effective and PCScan_Effective record whether or not
// BackupRefPtr and/or PCScan are enabled. The experiments aren't independent,
// so having a synthetic Finch will help look only at cases where one isn't
// affected by the other.
// Whether PartitionAllocBackupRefPtr is enabled (as determined by
// FeatureList::IsEnabled).
[[maybe_unused]] bool brp_finch_enabled = false;
// Whether PartitionAllocBackupRefPtr is set up for the default behavior. The
// default behavior is when either the Finch flag is disabled, or is enabled
// in brp-mode=disabled (these two options are equivalent).
[[maybe_unused]] bool brp_nondefault_behavior = false;
// Whether PartitionAllocBackupRefPtr is set up to enable BRP protection. It
// requires the Finch flag to be enabled and brp-mode!=disabled*. Some modes,
// e.g. disabled-but-3-way-split, do something (hence can't be considered the
// default behavior), but don't enable BRP protection.
[[maybe_unused]] bool brp_truly_enabled = false;
#if BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT)
if (FeatureList::IsEnabled(features::kPartitionAllocBackupRefPtr)) {
brp_finch_enabled = true;
}
if (brp_finch_enabled && features::kBackupRefPtrModeParam.Get() !=
features::BackupRefPtrMode::kDisabled) {
brp_nondefault_behavior = true;
}
if (brp_finch_enabled &&
(features::kBackupRefPtrModeParam.Get() ==
features::BackupRefPtrMode::kEnabled ||
features::kBackupRefPtrModeParam.Get() ==
features::BackupRefPtrMode::kEnabledWithMemoryReclaimer)) {
brp_truly_enabled = true;
}
#endif // BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT)
[[maybe_unused]] bool pcscan_enabled =
#if BUILDFLAG(USE_STARSCAN)
FeatureList::IsEnabled(features::kPartitionAllocPCScanBrowserOnly);
#else
false;
#endif
std::string brp_group_name = "Unavailable";
#if BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT)
if (pcscan_enabled) {
// If PCScan is enabled, just ignore the population.
brp_group_name = "Ignore_PCScanIsOn";
} else if (!brp_finch_enabled) {
// The control group is actually disguised as "enabled", but in fact it's
// disabled using a param. This is to differentiate the population that
// participates in the control group, from the population that isn't in any
// group.
brp_group_name = "Ignore_NoGroup";
} else {
switch (features::kBackupRefPtrModeParam.Get()) {
case features::BackupRefPtrMode::kDisabled:
brp_group_name = "Disabled";
break;
case features::BackupRefPtrMode::kEnabled:
#if BUILDFLAG(PUT_REF_COUNT_IN_PREVIOUS_SLOT)
brp_group_name = "EnabledPrevSlot";
#else
brp_group_name = "EnabledBeforeAlloc";
#endif
break;
case features::BackupRefPtrMode::kEnabledWithMemoryReclaimer:
#if BUILDFLAG(PUT_REF_COUNT_IN_PREVIOUS_SLOT)
brp_group_name = "EnabledPrevSlotWithMemoryReclaimer";
#else
brp_group_name = "EnabledBeforeAllocWithMemoryReclaimer";
#endif
break;
case features::BackupRefPtrMode::kDisabledButSplitPartitions2Way:
brp_group_name = "DisabledBut2WaySplit";
break;
case features::BackupRefPtrMode::
kDisabledButSplitPartitions2WayWithMemoryReclaimer:
brp_group_name = "DisabledBut2WaySplitWithMemoryReclaimer";
break;
case features::BackupRefPtrMode::kDisabledButSplitPartitions3Way:
brp_group_name = "DisabledBut3WaySplit";
break;
}
if (features::kBackupRefPtrModeParam.Get() !=
features::BackupRefPtrMode::kDisabled) {
std::string process_selector;
#if BUILDFLAG(FORCIBLY_ENABLE_BACKUP_REF_PTR_IN_ALL_PROCESSES)
process_selector = "AllProcesses";
#else
switch (features::kBackupRefPtrEnabledProcessesParam.Get()) {
case features::BackupRefPtrEnabledProcesses::kBrowserOnly:
process_selector = "BrowserOnly";
break;
case features::BackupRefPtrEnabledProcesses::kBrowserAndRenderer:
process_selector = "BrowserAndRenderer";
break;
case features::BackupRefPtrEnabledProcesses::kNonRenderer:
process_selector = "NonRenderer";
break;
case features::BackupRefPtrEnabledProcesses::kAllProcesses:
process_selector = "AllProcesses";
break;
}
#endif // BUILDFLAG(FORCIBLY_ENABLE_BACKUP_REF_PTR_IN_ALL_PROCESSES)
brp_group_name += ("_" + process_selector);
}
}
#endif // BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT)
trials.emplace("BackupRefPtr_Effective", brp_group_name);
// On 32-bit architectures, PCScan is not supported and permanently disabled.
// Don't lump it into "Disabled", so that belonging to "Enabled"/"Disabled" is
// fully controlled by Finch and thus have identical population sizes.
std::string pcscan_group_name = "Unavailable";
std::string pcscan_group_name_fallback = "Unavailable";
#if BUILDFLAG(USE_STARSCAN)
if (brp_truly_enabled) {
// If BRP protection is enabled, just ignore the population. Check
// brp_truly_enabled, not brp_finch_enabled, because there are certain modes
// where BRP protection is actually disabled.
pcscan_group_name = "Ignore_BRPIsOn";
} else {
pcscan_group_name = (pcscan_enabled ? "Enabled" : "Disabled");
}
// In case we are incorrect that PCScan is independent of partition-split
// modes, create a fallback trial that only takes into account the BRP Finch
// settings that preserve the default behavior.
if (brp_nondefault_behavior) {
pcscan_group_name_fallback = "Ignore_BRPIsOn";
} else {
pcscan_group_name_fallback = (pcscan_enabled ? "Enabled" : "Disabled");
}
#endif // BUILDFLAG(USE_STARSCAN)
trials.emplace("PCScan_Effective", pcscan_group_name);
trials.emplace("PCScan_Effective_Fallback", pcscan_group_name_fallback);
#endif // BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC)
#if BUILDFLAG(ENABLE_DANGLING_RAW_PTR_CHECKS)
trials.emplace("DanglingPointerDetector", "Enabled");
#else
trials.emplace("DanglingPointerDetector", "Disabled");
#endif
// This value is not surrounded by build flags as it is meant to be updated
// manually in binary experiment patches.
trials.emplace("VectorRawPtrExperiment", "Disabled");
#if BUILDFLAG(FORCIBLY_ENABLE_BACKUP_REF_PTR_IN_ALL_PROCESSES)
trials.emplace(base::features::kRendererLiveBRPSyntheticTrialName, "Enabled");
#else
trials.emplace(base::features::kRendererLiveBRPSyntheticTrialName, "Control");
#endif
#if PA_CONFIG(HAS_MEMORY_TAGGING)
if (base::FeatureList::IsEnabled(
base::features::kPartitionAllocMemoryTagging)) {
if (base::CPU::GetInstanceNoAllocation().has_mte()) {
trials.emplace("MemoryTaggingDogfood", "Enabled");
} else {
trials.emplace("MemoryTaggingDogfood", "Disabled");
}
}
#endif
return trials;
}
#if BUILDFLAG(ENABLE_DANGLING_RAW_PTR_CHECKS)
namespace {
internal::PartitionLock g_stack_trace_buffer_lock;
struct DanglingPointerFreeInfo {
debug::StackTrace stack_trace;
debug::TaskTrace task_trace;
uintptr_t id = 0;
};
using DanglingRawPtrBuffer =
std::array<absl::optional<DanglingPointerFreeInfo>, 32>;
DanglingRawPtrBuffer g_stack_trace_buffer GUARDED_BY(g_stack_trace_buffer_lock);
void DanglingRawPtrDetected(uintptr_t id) {
// This is called from inside the allocator. No allocation is allowed.
internal::PartitionAutoLock guard(g_stack_trace_buffer_lock);
#if DCHECK_IS_ON()
for (absl::optional<DanglingPointerFreeInfo>& entry : g_stack_trace_buffer) {
PA_DCHECK(!entry || entry->id != id);
}
#endif // DCHECK_IS_ON()
for (absl::optional<DanglingPointerFreeInfo>& entry : g_stack_trace_buffer) {
if (!entry) {
entry = {debug::StackTrace(), debug::TaskTrace(), id};
return;
}
}
// The StackTrace hasn't been recorded, because the buffer isn't large
// enough.
}
// From the traces recorded in |DanglingRawPtrDetected|, extract the one
// whose id match |id|. Return nullopt if not found.
absl::optional<DanglingPointerFreeInfo> TakeDanglingPointerFreeInfo(
uintptr_t id) {
internal::PartitionAutoLock guard(g_stack_trace_buffer_lock);
for (absl::optional<DanglingPointerFreeInfo>& entry : g_stack_trace_buffer) {
if (entry && entry->id == id) {
absl::optional<DanglingPointerFreeInfo> result(entry);
entry = absl::nullopt;
return result;
}
}
return absl::nullopt;
}
// Extract from the StackTrace output, the signature of the pertinent caller.
// This function is meant to be used only by Chromium developers, to list what
// are all the dangling raw_ptr occurrences in a table.
std::string ExtractDanglingPtrSignature(std::string stacktrace) {
std::vector<StringPiece> lines = SplitStringPiece(
stacktrace, "\r\n", KEEP_WHITESPACE, SPLIT_WANT_NONEMPTY);
// We are looking for the callers of the function releasing the raw_ptr and
// freeing memory:
const StringPiece callees[] = {
// Common signatures
"internal::PartitionFree",
"base::(anonymous namespace)::FreeFn",
// Linux signatures
"internal::RawPtrBackupRefImpl<>::ReleaseInternal()",
"base::RefCountedThreadSafe<>::Release()",
// Windows signatures
"internal::RawPtrBackupRefImpl<0,0>::ReleaseInternal",
"internal::RawPtrBackupRefImpl<0,1>::ReleaseInternal",
"_free_base",
// Mac signatures
"internal::RawPtrBackupRefImpl<false, false>::ReleaseInternal",
"internal::RawPtrBackupRefImpl<false, true>::ReleaseInternal",
// Task traces are prefixed with "Task trace:" in
// |TaskTrace::OutputToStream|
"Task trace:",
};
size_t caller_index = 0;
for (size_t i = 0; i < lines.size(); ++i) {
for (const auto& callee : callees) {
if (lines[i].find(callee) != StringPiece::npos) {
caller_index = i + 1;
}
}
}
if (caller_index >= lines.size()) {
return "no_callee_match";
}
StringPiece caller = lines[caller_index];
if (caller.empty()) {
return "invalid_format";
}
// On Posix platforms |callers| follows the following format:
//
// #<index> <address> <symbol>
//
// See https://crsrc.org/c/base/debug/stack_trace_posix.cc
if (caller[0] == '#') {
const size_t address_start = caller.find(' ');
const size_t function_start = caller.find(' ', address_start + 1);
if (address_start == caller.npos || function_start == caller.npos) {
return "invalid_format";
}
return std::string(caller.substr(function_start + 1));
}
// On Windows platforms |callers| follows the following format:
//
// \t<symbol> [0x<address>]+<displacement>(<filename>:<line>)
//
// See https://crsrc.org/c/base/debug/stack_trace_win.cc
if (caller[0] == '\t') {
const size_t symbol_start = 1;
const size_t symbol_end = caller.find(' ');
if (symbol_end == caller.npos) {
return "invalid_format";
}
return std::string(caller.substr(symbol_start, symbol_end - symbol_start));
}
// On Mac platforms |callers| follows the following format:
//
// <index> <library> 0x<address> <symbol> + <line>
//
// See https://crsrc.org/c/base/debug/stack_trace_posix.cc
if (caller[0] >= '0' && caller[0] <= '9') {
const size_t address_start = caller.find("0x");
const size_t symbol_start = caller.find(' ', address_start + 1) + 1;
const size_t symbol_end = caller.find(' ', symbol_start);
if (symbol_start == caller.npos || symbol_end == caller.npos) {
return "invalid_format";
}
return std::string(caller.substr(symbol_start, symbol_end - symbol_start));
}
return "invalid_format";
}
std::string ExtractDanglingPtrSignature(debug::TaskTrace task_trace) {
if (task_trace.empty()) {
return "No active task";
}
return ExtractDanglingPtrSignature(task_trace.ToString());
}
std::string ExtractDanglingPtrSignature(
absl::optional<DanglingPointerFreeInfo> free_info,
debug::StackTrace release_stack_trace,
debug::TaskTrace release_task_trace) {
if (free_info) {
return StringPrintf(
"[DanglingSignature]\t%s\t%s\t%s\t%s",
ExtractDanglingPtrSignature(free_info->stack_trace.ToString()).c_str(),
ExtractDanglingPtrSignature(free_info->task_trace).c_str(),
ExtractDanglingPtrSignature(release_stack_trace.ToString()).c_str(),
ExtractDanglingPtrSignature(release_task_trace).c_str());
}
return StringPrintf(
"[DanglingSignature]\t%s\t%s\t%s\t%s", "missing", "missing",
ExtractDanglingPtrSignature(release_stack_trace.ToString()).c_str(),
ExtractDanglingPtrSignature(release_task_trace).c_str());
}
bool operator==(const debug::TaskTrace& lhs, const debug::TaskTrace& rhs) {
// Compare the addresses contained in the task traces.
// The task traces are at most |PendingTask::kTaskBacktraceLength| long.
std::array<const void*, PendingTask::kTaskBacktraceLength> addresses_lhs = {};
std::array<const void*, PendingTask::kTaskBacktraceLength> addresses_rhs = {};
lhs.GetAddresses(addresses_lhs);
rhs.GetAddresses(addresses_rhs);
return addresses_lhs == addresses_rhs;
}
template <features::DanglingPtrMode dangling_pointer_mode,
features::DanglingPtrType dangling_pointer_type>
void DanglingRawPtrReleased(uintptr_t id) {
// This is called from raw_ptr<>'s release operation. Making allocations is
// allowed. In particular, symbolizing and printing the StackTraces may
// allocate memory.
debug::StackTrace stack_trace_release;
debug::TaskTrace task_trace_release;
absl::optional<DanglingPointerFreeInfo> free_info =
TakeDanglingPointerFreeInfo(id);
if constexpr (dangling_pointer_type ==
features::DanglingPtrType::kCrossTask) {
if (!free_info) {
return;
}
if (task_trace_release == free_info->task_trace) {
return;
}
}
std::string dangling_signature = ExtractDanglingPtrSignature(
free_info, stack_trace_release, task_trace_release);
static const char dangling_ptr_footer[] =
"\n"
"\n"
"Please check for more information on:\n"
"https://chromium.googlesource.com/chromium/src/+/main/docs/"
"dangling_ptr_guide.md\n"
"\n"
"Googlers: Please give us your feedback about the dangling pointer\n"
" detector at:\n"
" http://go/dangling-ptr-cq-survey\n";
if (free_info) {
LOG(ERROR) << "Detected dangling raw_ptr with id="
<< StringPrintf("0x%016" PRIxPTR, id) << ":\n"
<< dangling_signature << "\n\n"
<< "The memory was freed at:\n"
<< free_info->stack_trace << "\n"
<< free_info->task_trace << "\n"
<< "The dangling raw_ptr was released at:\n"
<< stack_trace_release << "\n"
<< task_trace_release << dangling_ptr_footer;
} else {
LOG(ERROR) << "Detected dangling raw_ptr with id="
<< StringPrintf("0x%016" PRIxPTR, id) << ":\n\n"
<< dangling_signature << "\n\n"
<< "It was not recorded where the memory was freed.\n\n"
<< "The dangling raw_ptr was released at:\n"
<< stack_trace_release << "\n"
<< task_trace_release << dangling_ptr_footer;
}
if constexpr (dangling_pointer_mode == features::DanglingPtrMode::kCrash) {
ImmediateCrash();
}
}
void CheckDanglingRawPtrBufferEmpty() {
internal::PartitionAutoLock guard(g_stack_trace_buffer_lock);
// TODO(https://crbug.com/1425095): Check for leaked refcount on Android.
#if BUILDFLAG(IS_ANDROID)
g_stack_trace_buffer = DanglingRawPtrBuffer();
#else
bool errors = false;
for (auto entry : g_stack_trace_buffer) {
if (!entry) {
continue;
}
errors = true;
LOG(ERROR) << "A freed allocation is still referenced by a dangling "
"pointer at exit, or at test end. Leaked raw_ptr/raw_ref "
"could cause PartitionAlloc's quarantine memory bloat."
"\n\n"
"Memory was released on:\n"
<< entry->task_trace << "\n"
<< entry->stack_trace << "\n";
}
CHECK(!errors);
#endif
}
} // namespace
void InstallDanglingRawPtrChecks() {
// Multiple tests can run within the same executable's execution. This line
// ensures problems detected from the previous test are causing error before
// entering the next one...
CheckDanglingRawPtrBufferEmpty();
// ... similarly, some allocation may stay forever in the quarantine and we
// might ignore them if the executable exists. This line makes sure dangling
// pointers errors are never ignored, by crashing at exit, as a last resort.
// This makes quarantine memory bloat more likely to be detected.
static bool first_run_in_process = true;
if (first_run_in_process) {
first_run_in_process = false;
AtExitManager::RegisterTask(base::BindOnce(CheckDanglingRawPtrBufferEmpty));
}
if (!FeatureList::IsEnabled(features::kPartitionAllocDanglingPtr)) {
partition_alloc::SetDanglingRawPtrDetectedFn([](uintptr_t) {});
partition_alloc::SetDanglingRawPtrReleasedFn([](uintptr_t) {});
return;
}
partition_alloc::SetDanglingRawPtrDetectedFn(&DanglingRawPtrDetected);
switch (features::kDanglingPtrModeParam.Get()) {
case features::DanglingPtrMode::kCrash:
switch (features::kDanglingPtrTypeParam.Get()) {
case features::DanglingPtrType::kAll:
partition_alloc::SetDanglingRawPtrReleasedFn(
&DanglingRawPtrReleased<features::DanglingPtrMode::kCrash,
features::DanglingPtrType::kAll>);
break;
case features::DanglingPtrType::kCrossTask:
partition_alloc::SetDanglingRawPtrReleasedFn(
&DanglingRawPtrReleased<features::DanglingPtrMode::kCrash,
features::DanglingPtrType::kCrossTask>);
break;
}
break;
case features::DanglingPtrMode::kLogOnly:
switch (features::kDanglingPtrTypeParam.Get()) {
case features::DanglingPtrType::kAll:
partition_alloc::SetDanglingRawPtrReleasedFn(
&DanglingRawPtrReleased<features::DanglingPtrMode::kLogOnly,
features::DanglingPtrType::kAll>);
break;
case features::DanglingPtrType::kCrossTask:
partition_alloc::SetDanglingRawPtrReleasedFn(
&DanglingRawPtrReleased<features::DanglingPtrMode::kLogOnly,
features::DanglingPtrType::kCrossTask>);
break;
}
break;
}
}
// TODO(arthursonzogni): There might exist long lived dangling raw_ptr. If there
// is a dangling pointer, we should crash at some point. Consider providing an
// API to periodically check the buffer.
#else // BUILDFLAG(ENABLE_DANGLING_RAW_PTR_CHECKS)
void InstallDanglingRawPtrChecks() {}
#endif // BUILDFLAG(ENABLE_DANGLING_RAW_PTR_CHECKS)
void UnretainedDanglingRawPtrDetectedDumpWithoutCrashing(uintptr_t id) {
PA_NO_CODE_FOLDING();
debug::DumpWithoutCrashing();
}
void UnretainedDanglingRawPtrDetectedCrash(uintptr_t id) {
debug::TaskTrace task_trace;
debug::StackTrace stack_trace;
LOG(ERROR) << "Detected dangling raw_ptr in unretained with id="
<< StringPrintf("0x%016" PRIxPTR, id) << ":\n\n"
<< task_trace << stack_trace;
ImmediateCrash();
}
void InstallUnretainedDanglingRawPtrChecks() {
if (!FeatureList::IsEnabled(features::kPartitionAllocUnretainedDanglingPtr)) {
partition_alloc::SetUnretainedDanglingRawPtrDetectedFn([](uintptr_t) {});
partition_alloc::SetUnretainedDanglingRawPtrCheckEnabled(/*enabled=*/false);
return;
}
partition_alloc::SetUnretainedDanglingRawPtrCheckEnabled(/*enabled=*/true);
switch (features::kUnretainedDanglingPtrModeParam.Get()) {
case features::UnretainedDanglingPtrMode::kCrash:
partition_alloc::SetUnretainedDanglingRawPtrDetectedFn(
&UnretainedDanglingRawPtrDetectedCrash);
break;
case features::UnretainedDanglingPtrMode::kDumpWithoutCrashing:
partition_alloc::SetUnretainedDanglingRawPtrDetectedFn(
&UnretainedDanglingRawPtrDetectedDumpWithoutCrashing);
break;
}
}
namespace {
#if BUILDFLAG(USE_STARSCAN)
void SetProcessNameForPCScan(const std::string& process_type) {
const char* name = [&process_type] {
if (process_type.empty()) {
// Empty means browser process.
return "Browser";
}
if (process_type == switches::kRendererProcess) {
return "Renderer";
}
if (process_type == switches::kGpuProcess) {
return "Gpu";
}
if (process_type == switches::kUtilityProcess) {
return "Utility";
}
return static_cast<const char*>(nullptr);
}();
if (name) {
partition_alloc::internal::PCScan::SetProcessName(name);
}
}
bool EnablePCScanForMallocPartitionsIfNeeded() {
#if BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC)
partition_alloc::internal::base::PlatformThread::SetThreadNameHook(
&base::PlatformThread::SetName);
using Config = partition_alloc::internal::PCScan::InitConfig;
DCHECK(base::FeatureList::GetInstance());
if (base::FeatureList::IsEnabled(base::features::kPartitionAllocPCScan)) {
allocator_shim::EnablePCScan({Config::WantedWriteProtectionMode::kEnabled,
Config::SafepointMode::kEnabled});
base::allocator::RegisterPCScanStatsReporter();
return true;
}
#endif // BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC)
return false;
}
bool EnablePCScanForMallocPartitionsInBrowserProcessIfNeeded() {
#if BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC)
using Config = partition_alloc::internal::PCScan::InitConfig;
DCHECK(base::FeatureList::GetInstance());
if (base::FeatureList::IsEnabled(
base::features::kPartitionAllocPCScanBrowserOnly)) {
const Config::WantedWriteProtectionMode wp_mode =
base::FeatureList::IsEnabled(base::features::kPartitionAllocDCScan)
? Config::WantedWriteProtectionMode::kEnabled
: Config::WantedWriteProtectionMode::kDisabled;
#if !PA_CONFIG(STARSCAN_UFFD_WRITE_PROTECTOR_SUPPORTED)
CHECK_EQ(Config::WantedWriteProtectionMode::kDisabled, wp_mode)
<< "DCScan is currently only supported on Linux based systems";
#endif
allocator_shim::EnablePCScan({wp_mode, Config::SafepointMode::kEnabled});
base::allocator::RegisterPCScanStatsReporter();
return true;
}
#endif // BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC)
return false;
}
bool EnablePCScanForMallocPartitionsInRendererProcessIfNeeded() {
#if BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC)
using Config = partition_alloc::internal::PCScan::InitConfig;
DCHECK(base::FeatureList::GetInstance());
if (base::FeatureList::IsEnabled(
base::features::kPartitionAllocPCScanRendererOnly)) {
const Config::WantedWriteProtectionMode wp_mode =
base::FeatureList::IsEnabled(base::features::kPartitionAllocDCScan)
? Config::WantedWriteProtectionMode::kEnabled
: Config::WantedWriteProtectionMode::kDisabled;
#if !PA_CONFIG(STARSCAN_UFFD_WRITE_PROTECTOR_SUPPORTED)
CHECK_EQ(Config::WantedWriteProtectionMode::kDisabled, wp_mode)
<< "DCScan is currently only supported on Linux based systems";
#endif
allocator_shim::EnablePCScan({wp_mode, Config::SafepointMode::kDisabled});
base::allocator::RegisterPCScanStatsReporter();
return true;
}
#endif // BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC)
return false;
}
#endif // BUILDFLAG(USE_STARSCAN)
} // namespace
void ReconfigurePartitionForKnownProcess(const std::string& process_type) {
DCHECK_NE(process_type, switches::kZygoteProcess);
// TODO(keishi): Move the code to enable BRP back here after Finch
// experiments.
}
PartitionAllocSupport* PartitionAllocSupport::Get() {
static auto* singleton = new PartitionAllocSupport();
return singleton;
}
PartitionAllocSupport::PartitionAllocSupport() = default;
void PartitionAllocSupport::ReconfigureForTests() {
ReconfigureEarlyish("");
base::AutoLock scoped_lock(lock_);
called_for_tests_ = true;
}
// static
bool PartitionAllocSupport::ShouldEnableMemoryTagging(
const std::string& process_type) {
// Check kPartitionAllocMemoryTagging first so the Feature is activated even
// when mte bootloader flag is disabled.
if (!base::FeatureList::IsEnabled(
base::features::kPartitionAllocMemoryTagging)) {
return false;
}
if (!base::CPU::GetInstanceNoAllocation().has_mte()) {
return false;
}
DCHECK(base::FeatureList::GetInstance());
if (base::FeatureList::IsEnabled(
base::features::kKillPartitionAllocMemoryTagging)) {
return false;
}
switch (base::features::kMemoryTaggingEnabledProcessesParam.Get()) {
case base::features::MemoryTaggingEnabledProcesses::kBrowserOnly:
return process_type.empty();
case base::features::MemoryTaggingEnabledProcesses::kNonRenderer:
return process_type != switches::kRendererProcess;
case base::features::MemoryTaggingEnabledProcesses::kAllProcesses:
return true;
}
}
// static
bool PartitionAllocSupport::ShouldEnableMemoryTaggingInRendererProcess() {
return ShouldEnableMemoryTagging(switches::kRendererProcess);
}
// static
PartitionAllocSupport::BrpConfiguration
PartitionAllocSupport::GetBrpConfiguration(const std::string& process_type) {
// TODO(bartekn): Switch to DCHECK once confirmed there are no issues.
CHECK(base::FeatureList::GetInstance());
bool enable_brp = false;
bool enable_brp_for_ash = false;
bool split_main_partition = false;
bool use_dedicated_aligned_partition = false;
bool process_affected_by_brp_flag = false;
bool enable_memory_reclaimer = false;
size_t ref_count_size = 0;
#if (BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) && \
BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT)) || \
BUILDFLAG(USE_ASAN_BACKUP_REF_PTR)
#if BUILDFLAG(FORCIBLY_ENABLE_BACKUP_REF_PTR_IN_ALL_PROCESSES)
process_affected_by_brp_flag = true;
#else
if (base::FeatureList::IsEnabled(
base::features::kPartitionAllocBackupRefPtr)) {
// No specified process type means this is the Browser process.
switch (base::features::kBackupRefPtrEnabledProcessesParam.Get()) {
case base::features::BackupRefPtrEnabledProcesses::kBrowserOnly:
process_affected_by_brp_flag = process_type.empty();
break;
case base::features::BackupRefPtrEnabledProcesses::kBrowserAndRenderer:
process_affected_by_brp_flag =
process_type.empty() ||
(process_type == switches::kRendererProcess);
break;
case base::features::BackupRefPtrEnabledProcesses::kNonRenderer:
process_affected_by_brp_flag =
(process_type != switches::kRendererProcess);
break;
case base::features::BackupRefPtrEnabledProcesses::kAllProcesses:
process_affected_by_brp_flag = true;
break;
}
}
#endif // BUILDFLAG(FORCIBLY_ENABLE_BACKUP_REF_PTR_IN_ALL_PROCESSES)
#endif // (BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) &&
// BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT)) ||
// BUILDFLAG(USE_ASAN_BACKUP_REF_PTR)
#if BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) && \
BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT)