forked from chromium/chromium
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathHeapTest.cpp
6723 lines (5647 loc) · 213 KB
/
HeapTest.cpp
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 (C) 2013 Google Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <algorithm>
#include <memory>
#include "build/build_config.h"
#include "platform/CrossThreadFunctional.h"
#include "platform/WebTaskRunner.h"
#include "platform/heap/Handle.h"
#include "platform/heap/Heap.h"
#include "platform/heap/HeapLinkedStack.h"
#include "platform/heap/HeapTerminatedArrayBuilder.h"
#include "platform/heap/SafePoint.h"
#include "platform/heap/SelfKeepAlive.h"
#include "platform/heap/ThreadState.h"
#include "platform/heap/Visitor.h"
#include "platform/testing/UnitTestHelpers.h"
#include "platform/wtf/HashTraits.h"
#include "platform/wtf/LinkedHashSet.h"
#include "platform/wtf/PtrUtil.h"
#include "public/platform/Platform.h"
#include "public/platform/WebTraceLocation.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace blink {
namespace {
void PreciselyCollectGarbage() {
ThreadState::Current()->CollectGarbage(BlinkGC::kNoHeapPointersOnStack,
BlinkGC::kGCWithSweep,
BlinkGC::kForcedGC);
}
void ConservativelyCollectGarbage() {
ThreadState::Current()->CollectGarbage(
BlinkGC::kHeapPointersOnStack, BlinkGC::kGCWithSweep, BlinkGC::kForcedGC);
}
class IntWrapper : public GarbageCollectedFinalized<IntWrapper> {
public:
static IntWrapper* Create(int x) { return new IntWrapper(x); }
virtual ~IntWrapper() { ++destructor_calls_; }
static int destructor_calls_;
DEFINE_INLINE_TRACE() {}
int Value() const { return x_; }
bool operator==(const IntWrapper& other) const {
return other.Value() == Value();
}
unsigned GetHash() { return IntHash<int>::GetHash(x_); }
IntWrapper(int x) : x_(x) {}
private:
IntWrapper();
int x_;
};
static_assert(WTF::IsTraceable<IntWrapper>::value,
"IsTraceable<> template failed to recognize trace method.");
class KeyWithCopyingMoveConstructor final {
public:
struct Hash final {
STATIC_ONLY(Hash);
public:
static unsigned GetHash(const KeyWithCopyingMoveConstructor& key) {
return key.hash_;
}
static bool Equal(const KeyWithCopyingMoveConstructor& x,
const KeyWithCopyingMoveConstructor& y) {
return x.hash_ == y.hash_;
}
static constexpr bool safe_to_compare_to_empty_or_deleted = true;
};
KeyWithCopyingMoveConstructor() = default;
KeyWithCopyingMoveConstructor(WTF::HashTableDeletedValueType) : hash_(-1) {}
~KeyWithCopyingMoveConstructor() = default;
KeyWithCopyingMoveConstructor(unsigned hash, const String& string)
: hash_(hash), string_(string) {
DCHECK_NE(hash_, 0);
DCHECK_NE(hash_, -1);
}
KeyWithCopyingMoveConstructor(const KeyWithCopyingMoveConstructor&) = default;
// The move constructor delegates to the copy constructor intentionally.
KeyWithCopyingMoveConstructor(KeyWithCopyingMoveConstructor&& x)
: KeyWithCopyingMoveConstructor(x) {}
KeyWithCopyingMoveConstructor& operator=(
const KeyWithCopyingMoveConstructor&) = default;
bool operator==(const KeyWithCopyingMoveConstructor& x) const {
return hash_ == x.hash_;
}
bool IsHashTableDeletedValue() const { return hash_ == -1; }
private:
int hash_ = 0;
String string_;
};
struct SameSizeAsPersistent {
void* pointer_[4];
};
static_assert(sizeof(Persistent<IntWrapper>) <= sizeof(SameSizeAsPersistent),
"Persistent handle should stay small");
class ThreadMarker {
public:
ThreadMarker()
: creating_thread_(reinterpret_cast<ThreadState*>(0)), num_(0) {}
ThreadMarker(unsigned i)
: creating_thread_(ThreadState::Current()), num_(i) {}
ThreadMarker(WTF::HashTableDeletedValueType deleted)
: creating_thread_(reinterpret_cast<ThreadState*>(-1)), num_(0) {}
~ThreadMarker() {
EXPECT_TRUE((creating_thread_ == ThreadState::Current()) ||
(creating_thread_ == reinterpret_cast<ThreadState*>(0)) ||
(creating_thread_ == reinterpret_cast<ThreadState*>(-1)));
}
bool IsHashTableDeletedValue() const {
return creating_thread_ == reinterpret_cast<ThreadState*>(-1);
}
bool operator==(const ThreadMarker& other) const {
return other.creating_thread_ == creating_thread_ && other.num_ == num_;
}
ThreadState* creating_thread_;
unsigned num_;
};
struct ThreadMarkerHash {
static unsigned GetHash(const ThreadMarker& key) {
return static_cast<unsigned>(
reinterpret_cast<uintptr_t>(key.creating_thread_) + key.num_);
}
static bool Equal(const ThreadMarker& a, const ThreadMarker& b) {
return a == b;
}
static const bool safe_to_compare_to_empty_or_deleted = false;
};
typedef std::pair<Member<IntWrapper>, WeakMember<IntWrapper>> StrongWeakPair;
struct PairWithWeakHandling : public StrongWeakPair {
DISALLOW_NEW_EXCEPT_PLACEMENT_NEW();
public:
// Regular constructor.
PairWithWeakHandling(IntWrapper* one, IntWrapper* two)
: StrongWeakPair(one, two) {
DCHECK(one); // We use null first field to indicate empty slots in the hash
// table.
}
// The HashTable (via the HashTrait) calls this constructor with a
// placement new to mark slots in the hash table as being deleted. We will
// never call trace or the destructor on these slots. We mark ourselves
// deleted
// with a pointer to -1 in the first field.
PairWithWeakHandling(WTF::HashTableDeletedValueType)
: StrongWeakPair(reinterpret_cast<IntWrapper*>(-1), nullptr) {}
// Used by the HashTable (via the HashTrait) to skip deleted slots in the
// table. Recognizes objects that were 'constructed' using the above
// constructor.
bool IsHashTableDeletedValue() const {
return first == reinterpret_cast<IntWrapper*>(-1);
}
// Since we don't allocate independent objects of this type, we don't need
// a regular trace method. Instead, we use a traceInCollection method. If
// the entry should be deleted from the collection we return true and don't
// trace the strong pointer.
template <typename VisitorDispatcher>
bool TraceInCollection(VisitorDispatcher visitor,
WTF::ShouldWeakPointersBeMarkedStrongly strongify) {
visitor->TraceInCollection(second, strongify);
if (!ThreadHeap::IsHeapObjectAlive(second))
return true;
// FIXME: traceInCollection is also called from WeakProcessing to check if
// the entry is dead.
// The below if avoids calling trace in that case by only calling trace when
// |first| is not yet marked.
if (!ThreadHeap::IsHeapObjectAlive(first))
visitor->Trace(first);
return false;
}
};
template <typename T>
struct WeakHandlingHashTraits : WTF::SimpleClassHashTraits<T> {
// We want to treat the object as a weak object in the sense that it can
// disappear from hash sets and hash maps.
static const WTF::WeakHandlingFlag kWeakHandlingFlag =
WTF::kWeakHandlingInCollections;
// Normally whether or not an object needs tracing is inferred
// automatically from the presence of the trace method, but we don't
// necessarily have a trace method, and we may not need one because T
// can perhaps only be allocated inside collections, never as independent
// objects. Explicitly mark this as needing tracing and it will be traced
// in collections using the traceInCollection method, which it must have.
template <typename U = void>
struct IsTraceableInCollection {
static const bool value = true;
};
// The traceInCollection method traces differently depending on whether we
// are strongifying the trace operation. We strongify the trace operation
// when there are active iterators on the object. In this case all
// WeakMembers are marked like strong members so that elements do not
// suddenly disappear during iteration. Returns true if weak pointers to
// dead objects were found: In this case any strong pointers were not yet
// traced and the entry should be removed from the collection.
template <typename VisitorDispatcher>
static bool TraceInCollection(
VisitorDispatcher visitor,
T& t,
WTF::ShouldWeakPointersBeMarkedStrongly strongify) {
return t.TraceInCollection(visitor, strongify);
}
};
} // namespace
} // namespace blink
namespace WTF {
template <typename T>
struct DefaultHash;
template <>
struct DefaultHash<blink::ThreadMarker> {
typedef blink::ThreadMarkerHash Hash;
};
// ThreadMarkerHash is the default hash for ThreadMarker
template <>
struct HashTraits<blink::ThreadMarker>
: GenericHashTraits<blink::ThreadMarker> {
static const bool kEmptyValueIsZero = true;
static void ConstructDeletedValue(blink::ThreadMarker& slot, bool) {
new (NotNull, &slot) blink::ThreadMarker(kHashTableDeletedValue);
}
static bool IsDeletedValue(const blink::ThreadMarker& slot) {
return slot.IsHashTableDeletedValue();
}
};
// The hash algorithm for our custom pair class is just the standard double
// hash for pairs. Note that this means you can't mutate either of the parts of
// the pair while they are in the hash table, as that would change their hash
// code and thus their preferred placement in the table.
template <>
struct DefaultHash<blink::PairWithWeakHandling> {
typedef PairHash<blink::Member<blink::IntWrapper>,
blink::WeakMember<blink::IntWrapper>>
Hash;
};
// Custom traits for the pair. These are weakness handling traits, which means
// PairWithWeakHandling must implement the traceInCollection method.
// In addition, these traits are concerned with the two magic values for the
// object, that represent empty and deleted slots in the hash table. The
// SimpleClassHashTraits allow empty slots in the table to be initialzed with
// memset to zero, and we use -1 in the first part of the pair to represent
// deleted slots.
template <>
struct HashTraits<blink::PairWithWeakHandling>
: blink::WeakHandlingHashTraits<blink::PairWithWeakHandling> {
static const bool kHasIsEmptyValueFunction = true;
static bool IsEmptyValue(const blink::PairWithWeakHandling& value) {
return !value.first;
}
static void ConstructDeletedValue(blink::PairWithWeakHandling& slot, bool) {
new (NotNull, &slot) blink::PairWithWeakHandling(kHashTableDeletedValue);
}
static bool IsDeletedValue(const blink::PairWithWeakHandling& value) {
return value.IsHashTableDeletedValue();
}
};
template <>
struct IsTraceable<blink::PairWithWeakHandling> {
static const bool value = IsTraceable<blink::StrongWeakPair>::value;
};
template <>
struct DefaultHash<blink::KeyWithCopyingMoveConstructor> {
using Hash = blink::KeyWithCopyingMoveConstructor::Hash;
};
template <>
struct HashTraits<blink::KeyWithCopyingMoveConstructor>
: public SimpleClassHashTraits<blink::KeyWithCopyingMoveConstructor> {};
} // namespace WTF
namespace blink {
class TestGCScope {
public:
explicit TestGCScope(BlinkGC::StackState state)
: state_(ThreadState::Current()), safe_point_scope_(state) {
DCHECK(state_->CheckThread());
state_->PreGC();
}
~TestGCScope() {
state_->PostGC(BlinkGC::kGCWithSweep);
state_->PreSweep(BlinkGC::kGCWithSweep);
}
private:
ThreadState* state_;
SafePointScope safe_point_scope_;
};
class SimpleObject : public GarbageCollected<SimpleObject> {
public:
static SimpleObject* Create() { return new SimpleObject(); }
DEFINE_INLINE_TRACE() {}
char GetPayload(int i) { return payload[i]; }
// This virtual method is unused but it is here to make sure
// that this object has a vtable. This object is used
// as the super class for objects that also have garbage
// collected mixins and having a virtual here makes sure
// that adjustment is needed both for marking and for isAlive
// checks.
virtual void VirtualMethod() {}
protected:
SimpleObject() {}
char payload[64];
};
class HeapTestSuperClass
: public GarbageCollectedFinalized<HeapTestSuperClass> {
public:
static HeapTestSuperClass* Create() { return new HeapTestSuperClass(); }
virtual ~HeapTestSuperClass() { ++destructor_calls_; }
static int destructor_calls_;
DEFINE_INLINE_TRACE() {}
protected:
HeapTestSuperClass() {}
};
int HeapTestSuperClass::destructor_calls_ = 0;
class HeapTestOtherSuperClass {
public:
int payload;
};
static const size_t kClassMagic = 0xABCDDBCA;
class HeapTestSubClass : public HeapTestOtherSuperClass,
public HeapTestSuperClass {
public:
static HeapTestSubClass* Create() { return new HeapTestSubClass(); }
~HeapTestSubClass() override {
EXPECT_EQ(kClassMagic, magic_);
++destructor_calls_;
}
static int destructor_calls_;
private:
HeapTestSubClass() : magic_(kClassMagic) {}
const size_t magic_;
};
int HeapTestSubClass::destructor_calls_ = 0;
class HeapAllocatedArray : public GarbageCollected<HeapAllocatedArray> {
public:
HeapAllocatedArray() {
for (int i = 0; i < kArraySize; ++i) {
array_[i] = i % 128;
}
}
int8_t at(size_t i) { return array_[i]; }
DEFINE_INLINE_TRACE() {}
private:
static const int kArraySize = 1000;
int8_t array_[kArraySize];
};
// Do several GCs to make sure that later GCs don't free up old memory from
// previously run tests in this process.
static void ClearOutOldGarbage() {
ThreadHeap& heap = ThreadState::Current()->Heap();
while (true) {
size_t used = heap.ObjectPayloadSizeForTesting();
PreciselyCollectGarbage();
if (heap.ObjectPayloadSizeForTesting() >= used)
break;
}
}
class OffHeapInt : public RefCounted<OffHeapInt> {
public:
static RefPtr<OffHeapInt> Create(int x) {
return AdoptRef(new OffHeapInt(x));
}
virtual ~OffHeapInt() { ++destructor_calls_; }
static int destructor_calls_;
int Value() const { return x_; }
bool operator==(const OffHeapInt& other) const {
return other.Value() == Value();
}
unsigned GetHash() { return IntHash<int>::GetHash(x_); }
void VoidFunction() {}
protected:
OffHeapInt(int x) : x_(x) {}
private:
OffHeapInt();
int x_;
};
int IntWrapper::destructor_calls_ = 0;
int OffHeapInt::destructor_calls_ = 0;
class ThreadedTesterBase {
protected:
static void Test(ThreadedTesterBase* tester) {
Vector<std::unique_ptr<WebThread>, kNumberOfThreads> threads;
for (int i = 0; i < kNumberOfThreads; i++) {
threads.push_back(
Platform::Current()->CreateThread("blink gc testing thread"));
threads.back()->GetWebTaskRunner()->PostTask(
BLINK_FROM_HERE,
CrossThreadBind(ThreadFunc, CrossThreadUnretained(tester)));
}
while (tester->threads_to_finish_) {
testing::YieldCurrentThread();
}
delete tester;
}
virtual void RunThread() = 0;
protected:
static const int kNumberOfThreads = 10;
static const int kGcPerThread = 5;
static const int kNumberOfAllocations = 50;
ThreadedTesterBase() : gc_count_(0), threads_to_finish_(kNumberOfThreads) {}
virtual ~ThreadedTesterBase() {}
inline bool Done() const {
return gc_count_ >= kNumberOfThreads * kGcPerThread;
}
volatile int gc_count_;
volatile int threads_to_finish_;
private:
static void ThreadFunc(void* data) {
reinterpret_cast<ThreadedTesterBase*>(data)->RunThread();
}
};
// Needed to give this variable a definition (the initializer above is only a
// declaration), so that subclasses can use it.
const int ThreadedTesterBase::kNumberOfThreads;
class ThreadedHeapTester : public ThreadedTesterBase {
public:
static void Test() { ThreadedTesterBase::Test(new ThreadedHeapTester); }
~ThreadedHeapTester() override {
// Verify that the threads cleared their CTPs when
// terminating, preventing access to a finalized heap.
for (auto& global_int_wrapper : cross_persistents_) {
DCHECK(global_int_wrapper.get());
EXPECT_FALSE(global_int_wrapper.get()->Get());
}
}
protected:
using GlobalIntWrapperPersistent = CrossThreadPersistent<IntWrapper>;
Mutex mutex_;
Vector<std::unique_ptr<GlobalIntWrapperPersistent>> cross_persistents_;
std::unique_ptr<GlobalIntWrapperPersistent> CreateGlobalPersistent(
int value) {
return WTF::WrapUnique(
new GlobalIntWrapperPersistent(IntWrapper::Create(value)));
}
void AddGlobalPersistent() {
MutexLocker lock(mutex_);
cross_persistents_.push_back(CreateGlobalPersistent(0x2a2a2a2a));
}
void RunThread() override {
ThreadState::AttachCurrentThread();
// Add a cross-thread persistent from this thread; the test object
// verifies that it will have been cleared out after the threads
// have all detached, running their termination GCs while doing so.
AddGlobalPersistent();
int gc_count = 0;
while (!Done()) {
{
Persistent<IntWrapper> wrapper;
std::unique_ptr<GlobalIntWrapperPersistent> global_persistent =
CreateGlobalPersistent(0x0ed0cabb);
for (int i = 0; i < kNumberOfAllocations; i++) {
wrapper = IntWrapper::Create(0x0bbac0de);
if (!(i % 10)) {
global_persistent = CreateGlobalPersistent(0x0ed0cabb);
}
testing::YieldCurrentThread();
}
if (gc_count < kGcPerThread) {
PreciselyCollectGarbage();
gc_count++;
AtomicIncrement(&gc_count_);
}
// Taking snapshot shouldn't have any bad side effect.
// TODO(haraken): This snapshot GC causes crashes, so disable
// it at the moment. Fix the crash and enable it.
// ThreadHeap::collectGarbage(BlinkGC::NoHeapPointersOnStack,
// BlinkGC::TakeSnapshot, BlinkGC::ForcedGC);
PreciselyCollectGarbage();
EXPECT_EQ(wrapper->Value(), 0x0bbac0de);
EXPECT_EQ((*global_persistent)->Value(), 0x0ed0cabb);
}
testing::YieldCurrentThread();
}
ThreadState::DetachCurrentThread();
AtomicDecrement(&threads_to_finish_);
}
};
class ThreadedWeaknessTester : public ThreadedTesterBase {
public:
static void Test() { ThreadedTesterBase::Test(new ThreadedWeaknessTester); }
private:
void RunThread() override {
ThreadState::AttachCurrentThread();
int gc_count = 0;
while (!Done()) {
{
Persistent<HeapHashMap<ThreadMarker, WeakMember<IntWrapper>>> weak_map =
new HeapHashMap<ThreadMarker, WeakMember<IntWrapper>>;
PersistentHeapHashMap<ThreadMarker, WeakMember<IntWrapper>> weak_map2;
for (int i = 0; i < kNumberOfAllocations; i++) {
weak_map->insert(static_cast<unsigned>(i), IntWrapper::Create(0));
weak_map2.insert(static_cast<unsigned>(i), IntWrapper::Create(0));
testing::YieldCurrentThread();
}
if (gc_count < kGcPerThread) {
PreciselyCollectGarbage();
gc_count++;
AtomicIncrement(&gc_count_);
}
// Taking snapshot shouldn't have any bad side effect.
// TODO(haraken): This snapshot GC causes crashes, so disable
// it at the moment. Fix the crash and enable it.
// ThreadHeap::collectGarbage(BlinkGC::NoHeapPointersOnStack,
// BlinkGC::TakeSnapshot, BlinkGC::ForcedGC);
PreciselyCollectGarbage();
EXPECT_TRUE(weak_map->IsEmpty());
EXPECT_TRUE(weak_map2.IsEmpty());
}
testing::YieldCurrentThread();
}
ThreadState::DetachCurrentThread();
AtomicDecrement(&threads_to_finish_);
}
};
class ThreadPersistentHeapTester : public ThreadedTesterBase {
public:
static void Test() {
ThreadedTesterBase::Test(new ThreadPersistentHeapTester);
}
protected:
class Local final : public GarbageCollected<Local> {
public:
Local() {}
DEFINE_INLINE_TRACE() {}
};
class PersistentChain;
class RefCountedChain : public RefCounted<RefCountedChain> {
public:
static RefCountedChain* Create(int count) {
return new RefCountedChain(count);
}
private:
explicit RefCountedChain(int count) {
if (count > 0) {
--count;
persistent_chain_ = PersistentChain::Create(count);
}
}
Persistent<PersistentChain> persistent_chain_;
};
class PersistentChain : public GarbageCollectedFinalized<PersistentChain> {
public:
static PersistentChain* Create(int count) {
return new PersistentChain(count);
}
DEFINE_INLINE_TRACE() {}
private:
explicit PersistentChain(int count) {
ref_counted_chain_ = AdoptRef(RefCountedChain::Create(count));
}
RefPtr<RefCountedChain> ref_counted_chain_;
};
void RunThread() override {
ThreadState::AttachCurrentThread();
PersistentChain::Create(100);
// Upon thread detach, GCs will run until all persistents have been
// released. We verify that the draining of persistents proceeds
// as expected by dropping one Persistent<> per GC until there
// are none left.
ThreadState::DetachCurrentThread();
AtomicDecrement(&threads_to_finish_);
}
};
// The accounting for memory includes the memory used by rounding up object
// sizes. This is done in a different way on 32 bit and 64 bit, so we have to
// have some slack in the tests.
template <typename T>
void CheckWithSlack(T expected, T actual, int slack) {
EXPECT_LE(expected, actual);
EXPECT_GE((intptr_t)expected + slack, (intptr_t)actual);
}
class TraceCounter : public GarbageCollectedFinalized<TraceCounter> {
public:
static TraceCounter* Create() { return new TraceCounter(); }
DEFINE_INLINE_TRACE() { trace_count_++; }
int TraceCount() { return trace_count_; }
private:
TraceCounter() : trace_count_(0) {}
int trace_count_;
};
class ClassWithMember : public GarbageCollected<ClassWithMember> {
public:
static ClassWithMember* Create() { return new ClassWithMember(); }
DEFINE_INLINE_TRACE() {
EXPECT_TRUE(ThreadHeap::IsHeapObjectAlive(this));
// Const pointer should also be alive. See http://crbug.com/661363.
const ClassWithMember* const_ptr =
static_cast<const ClassWithMember*>(this);
EXPECT_TRUE(ThreadHeap::IsHeapObjectAlive(const_ptr));
if (!TraceCount())
EXPECT_FALSE(ThreadHeap::IsHeapObjectAlive(trace_counter_));
else
EXPECT_TRUE(ThreadHeap::IsHeapObjectAlive(trace_counter_));
visitor->Trace(trace_counter_);
}
int TraceCount() { return trace_counter_->TraceCount(); }
private:
ClassWithMember() : trace_counter_(TraceCounter::Create()) {}
Member<TraceCounter> trace_counter_;
};
class SimpleFinalizedObject
: public GarbageCollectedFinalized<SimpleFinalizedObject> {
public:
static SimpleFinalizedObject* Create() { return new SimpleFinalizedObject(); }
~SimpleFinalizedObject() { ++destructor_calls_; }
static int destructor_calls_;
DEFINE_INLINE_TRACE() {}
private:
SimpleFinalizedObject() {}
};
int SimpleFinalizedObject::destructor_calls_ = 0;
class IntNode : public GarbageCollected<IntNode> {
public:
// IntNode is used to test typed heap allocation. Instead of
// redefining blink::Node to our test version, we keep it separate
// so as to avoid possible warnings about linker duplicates.
// Override operator new to allocate IntNode subtype objects onto
// the dedicated heap for blink::Node.
//
// TODO(haraken): untangling the heap unit tests from Blink would
// simplify and avoid running into this problem - http://crbug.com/425381
GC_PLUGIN_IGNORE("crbug.com/443854")
void* operator new(size_t size) {
ThreadState* state = ThreadState::Current();
const char* type_name = WTF_HEAP_PROFILER_TYPE_NAME(IntNode);
return ThreadHeap::AllocateOnArenaIndex(
state, size, BlinkGC::kNodeArenaIndex, GCInfoTrait<IntNode>::Index(),
type_name);
}
static IntNode* Create(int i) { return new IntNode(i); }
DEFINE_INLINE_TRACE() {}
int Value() { return value_; }
private:
IntNode(int i) : value_(i) {}
int value_;
};
class Bar : public GarbageCollectedFinalized<Bar> {
public:
static Bar* Create() { return new Bar(); }
void FinalizeGarbageCollectedObject() {
EXPECT_TRUE(magic_ == kMagic);
magic_ = 0;
live_--;
}
bool HasBeenFinalized() const { return !magic_; }
DEFINE_INLINE_VIRTUAL_TRACE() {}
static unsigned live_;
protected:
static const int kMagic = 1337;
int magic_;
Bar() : magic_(kMagic) { live_++; }
};
WILL_NOT_BE_EAGERLY_TRACED_CLASS(Bar);
unsigned Bar::live_ = 0;
class Baz : public GarbageCollected<Baz> {
public:
static Baz* Create(Bar* bar) { return new Baz(bar); }
DEFINE_INLINE_TRACE() { visitor->Trace(bar_); }
void Clear() { bar_.Release(); }
// willFinalize is called by FinalizationObserver.
void WillFinalize() { EXPECT_TRUE(!bar_->HasBeenFinalized()); }
private:
explicit Baz(Bar* bar) : bar_(bar) {}
Member<Bar> bar_;
};
class Foo : public Bar {
public:
static Foo* Create(Bar* bar) { return new Foo(bar); }
static Foo* Create(Foo* foo) { return new Foo(foo); }
DEFINE_INLINE_VIRTUAL_TRACE() {
if (points_to_foo_)
visitor->Mark(static_cast<Foo*>(bar_));
else
visitor->Mark(bar_);
}
private:
Foo(Bar* bar) : Bar(), bar_(bar), points_to_foo_(false) {}
Foo(Foo* foo) : Bar(), bar_(foo), points_to_foo_(true) {}
Bar* bar_;
bool points_to_foo_;
};
WILL_NOT_BE_EAGERLY_TRACED_CLASS(Foo);
class Bars : public Bar {
public:
static Bars* Create() { return new Bars(); }
DEFINE_INLINE_VIRTUAL_TRACE() {
for (unsigned i = 0; i < width_; i++)
visitor->Trace(bars_[i]);
}
unsigned GetWidth() const { return width_; }
static const unsigned kWidth = 7500;
private:
Bars() : width_(0) {
for (unsigned i = 0; i < kWidth; i++) {
bars_[i] = Bar::Create();
width_++;
}
}
unsigned width_;
Member<Bar> bars_[kWidth];
};
WILL_NOT_BE_EAGERLY_TRACED_CLASS(Bars);
class ConstructorAllocation : public GarbageCollected<ConstructorAllocation> {
public:
static ConstructorAllocation* Create() { return new ConstructorAllocation(); }
DEFINE_INLINE_TRACE() { visitor->Trace(int_wrapper_); }
private:
ConstructorAllocation() { int_wrapper_ = IntWrapper::Create(42); }
Member<IntWrapper> int_wrapper_;
};
class LargeHeapObject : public GarbageCollectedFinalized<LargeHeapObject> {
public:
~LargeHeapObject() { destructor_calls_++; }
static LargeHeapObject* Create() { return new LargeHeapObject(); }
char Get(size_t i) { return data_[i]; }
void Set(size_t i, char c) { data_[i] = c; }
size_t length() { return kLength; }
DEFINE_INLINE_TRACE() { visitor->Trace(int_wrapper_); }
static int destructor_calls_;
private:
static const size_t kLength = 1024 * 1024;
LargeHeapObject() { int_wrapper_ = IntWrapper::Create(23); }
Member<IntWrapper> int_wrapper_;
char data_[kLength];
};
int LargeHeapObject::destructor_calls_ = 0;
// This test class served a more important role while Blink
// was transitioned over to using Oilpan. That required classes
// that were hybrid, both ref-counted and on the Oilpan heap
// (the RefCountedGarbageCollected<> class providing just that.)
//
// There's no current need for having a ref-counted veneer on
// top of a GCed class, but we preserve it here to exercise the
// implementation technique that it used -- keeping an internal
// "keep alive" persistent reference that is set & cleared across
// ref-counting operations.
//
class RefCountedAndGarbageCollected
: public GarbageCollectedFinalized<RefCountedAndGarbageCollected> {
public:
static RefCountedAndGarbageCollected* Create() {
return new RefCountedAndGarbageCollected;
}
~RefCountedAndGarbageCollected() { ++destructor_calls_; }
void Ref() {
if (UNLIKELY(!ref_count_)) {
#if DCHECK_IS_ON()
DCHECK(ThreadState::Current()->FindPageFromAddress(
reinterpret_cast<Address>(this)));
#endif
keep_alive_ = this;
}
++ref_count_;
}
void Deref() {
DCHECK_GT(ref_count_, 0);
if (!--ref_count_)
keep_alive_.Clear();
}
DEFINE_INLINE_TRACE() {}
static int destructor_calls_;
private:
RefCountedAndGarbageCollected() : ref_count_(0) {}
int ref_count_;
SelfKeepAlive<RefCountedAndGarbageCollected> keep_alive_;
};
int RefCountedAndGarbageCollected::destructor_calls_ = 0;
class RefCountedAndGarbageCollected2
: public HeapTestOtherSuperClass,
public GarbageCollectedFinalized<RefCountedAndGarbageCollected2> {
public:
static RefCountedAndGarbageCollected2* Create() {
return new RefCountedAndGarbageCollected2;
}
~RefCountedAndGarbageCollected2() { ++destructor_calls_; }
void Ref() {
if (UNLIKELY(!ref_count_)) {
#if DCHECK_IS_ON()
DCHECK(ThreadState::Current()->FindPageFromAddress(
reinterpret_cast<Address>(this)));
#endif
keep_alive_ = this;
}
++ref_count_;
}
void Deref() {
DCHECK_GT(ref_count_, 0);
if (!--ref_count_)
keep_alive_.Clear();
}