blob: 081be968eb9f09977399dc41c6700ee1a231f858 [file] [log] [blame]
Mathieu Chartier78f7b4c2014-05-06 10:57:27 -07001/*
2 * Copyright (C) 2014 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include "reference_processor.h"
18
Vladimir Marko80afd022015-05-19 18:08:00 +010019#include "base/time_utils.h"
Mathieu Chartier97509952015-07-13 14:35:43 -070020#include "collector/garbage_collector.h"
Mathieu Chartiere401d142015-04-22 13:56:20 -070021#include "mirror/class-inl.h"
Mathieu Chartier78f7b4c2014-05-06 10:57:27 -070022#include "mirror/object-inl.h"
23#include "mirror/reference-inl.h"
Fred Shih4ee7a662014-07-11 09:59:27 -070024#include "reference_processor-inl.h"
Mathieu Chartier78f7b4c2014-05-06 10:57:27 -070025#include "reflection.h"
26#include "ScopedLocalRef.h"
Mathieu Chartier0795f232016-09-27 18:43:30 -070027#include "scoped_thread_state_change-inl.h"
Mathieu Chartiera5eae692014-12-17 17:56:03 -080028#include "task_processor.h"
Vladimir Marko80afd022015-05-19 18:08:00 +010029#include "utils.h"
Mathieu Chartier78f7b4c2014-05-06 10:57:27 -070030#include "well_known_classes.h"
31
32namespace art {
33namespace gc {
34
Mathieu Chartiera5eae692014-12-17 17:56:03 -080035static constexpr bool kAsyncReferenceQueueAdd = false;
36
Mathieu Chartier78f7b4c2014-05-06 10:57:27 -070037ReferenceProcessor::ReferenceProcessor()
Mathieu Chartier97509952015-07-13 14:35:43 -070038 : collector_(nullptr),
Mathieu Chartiera5a53ef2014-09-12 12:58:05 -070039 preserving_references_(false),
40 condition_("reference processor condition", *Locks::reference_processor_lock_) ,
41 soft_reference_queue_(Locks::reference_queue_soft_references_lock_),
42 weak_reference_queue_(Locks::reference_queue_weak_references_lock_),
43 finalizer_reference_queue_(Locks::reference_queue_finalizer_references_lock_),
44 phantom_reference_queue_(Locks::reference_queue_phantom_references_lock_),
45 cleared_references_(Locks::reference_queue_cleared_references_lock_) {
Mathieu Chartier78f7b4c2014-05-06 10:57:27 -070046}
47
48void ReferenceProcessor::EnableSlowPath() {
Fred Shih4ee7a662014-07-11 09:59:27 -070049 mirror::Reference::GetJavaLangRefReference()->SetSlowPath(true);
Mathieu Chartier78f7b4c2014-05-06 10:57:27 -070050}
51
52void ReferenceProcessor::DisableSlowPath(Thread* self) {
Fred Shih4ee7a662014-07-11 09:59:27 -070053 mirror::Reference::GetJavaLangRefReference()->SetSlowPath(false);
Mathieu Chartier78f7b4c2014-05-06 10:57:27 -070054 condition_.Broadcast(self);
55}
56
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -070057void ReferenceProcessor::BroadcastForSlowPath(Thread* self) {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -070058 MutexLock mu(self, *Locks::reference_processor_lock_);
59 condition_.Broadcast(self);
60}
61
Mathieu Chartier5d3f73a2016-10-14 14:28:47 -070062ObjPtr<mirror::Object> ReferenceProcessor::GetReferent(Thread* self,
63 ObjPtr<mirror::Reference> reference) {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -070064 if (!kUseReadBarrier || self->GetWeakRefAccessEnabled()) {
65 // Under read barrier / concurrent copying collector, it's not safe to call GetReferent() when
66 // weak ref access is disabled as the call includes a read barrier which may push a ref onto the
67 // mark stack and interfere with termination of marking.
Mathieu Chartier5d3f73a2016-10-14 14:28:47 -070068 ObjPtr<mirror::Object> const referent = reference->GetReferent();
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -070069 // If the referent is null then it is already cleared, we can just return null since there is no
70 // scenario where it becomes non-null during the reference processing phase.
71 if (UNLIKELY(!SlowPathEnabled()) || referent == nullptr) {
72 return referent;
73 }
Mathieu Chartier78f7b4c2014-05-06 10:57:27 -070074 }
Mathieu Chartiera5a53ef2014-09-12 12:58:05 -070075 MutexLock mu(self, *Locks::reference_processor_lock_);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -070076 while ((!kUseReadBarrier && SlowPathEnabled()) ||
77 (kUseReadBarrier && !self->GetWeakRefAccessEnabled())) {
Mathieu Chartier36994ba2016-12-13 11:46:28 -080078 ObjPtr<mirror::Object> referent = reference->GetReferent<kWithoutReadBarrier>();
Mathieu Chartier308351a2014-06-15 12:39:02 -070079 // If the referent became cleared, return it. Don't need barrier since thread roots can't get
80 // updated until after we leave the function due to holding the mutator lock.
Mathieu Chartier36994ba2016-12-13 11:46:28 -080081 if (referent == nullptr) {
Mathieu Chartier2175f522014-05-09 11:01:06 -070082 return nullptr;
83 }
Mathieu Chartier78f7b4c2014-05-06 10:57:27 -070084 // Try to see if the referent is already marked by using the is_marked_callback. We can return
Mathieu Chartier308351a2014-06-15 12:39:02 -070085 // it to the mutator as long as the GC is not preserving references.
Mathieu Chartier97509952015-07-13 14:35:43 -070086 if (LIKELY(collector_ != nullptr)) {
Mathieu Chartier78f7b4c2014-05-06 10:57:27 -070087 // If it's null it means not marked, but it could become marked if the referent is reachable
Roland Levillain91d65e02016-01-19 15:59:16 +000088 // by finalizer referents. So we cannot return in this case and must block. Otherwise, we
Fred Shih530e1b52014-06-09 15:19:54 -070089 // can return it to the mutator as long as the GC is not preserving references, in which
90 // case only black nodes can be safely returned. If the GC is preserving references, the
91 // mutator could take a white field from a grey or white node and move it somewhere else
92 // in the heap causing corruption since this field would get swept.
Mathieu Chartier36994ba2016-12-13 11:46:28 -080093 // Use the cached referent instead of calling GetReferent since other threads could call
94 // Reference.clear() after we did the null check resulting in a null pointer being
95 // incorrectly passed to IsMarked. b/33569625
96 ObjPtr<mirror::Object> forwarded_ref = collector_->IsMarked(referent.Ptr());
97 if (forwarded_ref != nullptr) {
98 // Non null means that it is marked.
Fred Shih530e1b52014-06-09 15:19:54 -070099 if (!preserving_references_ ||
Richard Uhlerc4695df2016-01-15 14:08:05 -0800100 (LIKELY(!reference->IsFinalizerReferenceInstance()) && reference->IsUnprocessed())) {
Mathieu Chartier36994ba2016-12-13 11:46:28 -0800101 return forwarded_ref;
Fred Shih530e1b52014-06-09 15:19:54 -0700102 }
Mathieu Chartier78f7b4c2014-05-06 10:57:27 -0700103 }
104 }
Hiroshi Yamauchi30493242016-11-03 13:06:52 -0700105 // Check and run the empty checkpoint before blocking so the empty checkpoint will work in the
106 // presence of threads blocking for weak ref access.
107 self->CheckEmptyCheckpoint();
Mathieu Chartier2d1ab0a2014-05-08 15:27:31 -0700108 condition_.WaitHoldingLocks(self);
Mathieu Chartier78f7b4c2014-05-06 10:57:27 -0700109 }
110 return reference->GetReferent();
111}
112
Mathieu Chartier78f7b4c2014-05-06 10:57:27 -0700113void ReferenceProcessor::StartPreservingReferences(Thread* self) {
Mathieu Chartiera5a53ef2014-09-12 12:58:05 -0700114 MutexLock mu(self, *Locks::reference_processor_lock_);
Mathieu Chartier78f7b4c2014-05-06 10:57:27 -0700115 preserving_references_ = true;
116}
117
118void ReferenceProcessor::StopPreservingReferences(Thread* self) {
Mathieu Chartiera5a53ef2014-09-12 12:58:05 -0700119 MutexLock mu(self, *Locks::reference_processor_lock_);
Mathieu Chartier78f7b4c2014-05-06 10:57:27 -0700120 preserving_references_ = false;
121 // We are done preserving references, some people who are blocked may see a marked referent.
122 condition_.Broadcast(self);
123}
124
125// Process reference class instances and schedule finalizations.
Mathieu Chartier5d3f73a2016-10-14 14:28:47 -0700126void ReferenceProcessor::ProcessReferences(bool concurrent,
127 TimingLogger* timings,
Mathieu Chartier78f7b4c2014-05-06 10:57:27 -0700128 bool clear_soft_references,
Mathieu Chartier97509952015-07-13 14:35:43 -0700129 collector::GarbageCollector* collector) {
Mathieu Chartierf5997b42014-06-20 10:37:54 -0700130 TimingLogger::ScopedTiming t(concurrent ? __FUNCTION__ : "(Paused)ProcessReferences", timings);
Mathieu Chartier78f7b4c2014-05-06 10:57:27 -0700131 Thread* self = Thread::Current();
132 {
Mathieu Chartiera5a53ef2014-09-12 12:58:05 -0700133 MutexLock mu(self, *Locks::reference_processor_lock_);
Mathieu Chartier97509952015-07-13 14:35:43 -0700134 collector_ = collector;
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700135 if (!kUseReadBarrier) {
136 CHECK_EQ(SlowPathEnabled(), concurrent) << "Slow path must be enabled iff concurrent";
137 } else {
138 // Weak ref access is enabled at Zygote compaction by SemiSpace (concurrent == false).
139 CHECK_EQ(!self->GetWeakRefAccessEnabled(), concurrent);
140 }
Mathieu Chartier78f7b4c2014-05-06 10:57:27 -0700141 }
Mathieu Chartier78f7b4c2014-05-06 10:57:27 -0700142 // Unless required to clear soft references with white references, preserve some white referents.
143 if (!clear_soft_references) {
Mathieu Chartierf5997b42014-06-20 10:37:54 -0700144 TimingLogger::ScopedTiming split(concurrent ? "ForwardSoftReferences" :
Fred Shih530e1b52014-06-09 15:19:54 -0700145 "(Paused)ForwardSoftReferences", timings);
Mathieu Chartier78f7b4c2014-05-06 10:57:27 -0700146 if (concurrent) {
147 StartPreservingReferences(self);
148 }
Mathieu Chartier81187812015-07-15 14:24:07 -0700149 // TODO: Add smarter logic for preserving soft references. The behavior should be a conditional
150 // mark if the SoftReference is supposed to be preserved.
Mathieu Chartier97509952015-07-13 14:35:43 -0700151 soft_reference_queue_.ForwardSoftReferences(collector);
152 collector->ProcessMarkStack();
Mathieu Chartier78f7b4c2014-05-06 10:57:27 -0700153 if (concurrent) {
154 StopPreservingReferences(self);
155 }
156 }
157 // Clear all remaining soft and weak references with white referents.
Mathieu Chartier97509952015-07-13 14:35:43 -0700158 soft_reference_queue_.ClearWhiteReferences(&cleared_references_, collector);
159 weak_reference_queue_.ClearWhiteReferences(&cleared_references_, collector);
Mathieu Chartier78f7b4c2014-05-06 10:57:27 -0700160 {
Andreas Gampe277ccbd2014-11-03 21:36:10 -0800161 TimingLogger::ScopedTiming t2(concurrent ? "EnqueueFinalizerReferences" :
Mathieu Chartier78f7b4c2014-05-06 10:57:27 -0700162 "(Paused)EnqueueFinalizerReferences", timings);
163 if (concurrent) {
164 StartPreservingReferences(self);
165 }
166 // Preserve all white objects with finalize methods and schedule them for finalization.
Mathieu Chartier97509952015-07-13 14:35:43 -0700167 finalizer_reference_queue_.EnqueueFinalizerReferences(&cleared_references_, collector);
168 collector->ProcessMarkStack();
Mathieu Chartier78f7b4c2014-05-06 10:57:27 -0700169 if (concurrent) {
170 StopPreservingReferences(self);
171 }
172 }
173 // Clear all finalizer referent reachable soft and weak references with white referents.
Mathieu Chartier97509952015-07-13 14:35:43 -0700174 soft_reference_queue_.ClearWhiteReferences(&cleared_references_, collector);
175 weak_reference_queue_.ClearWhiteReferences(&cleared_references_, collector);
Mathieu Chartier78f7b4c2014-05-06 10:57:27 -0700176 // Clear all phantom references with white referents.
Mathieu Chartier97509952015-07-13 14:35:43 -0700177 phantom_reference_queue_.ClearWhiteReferences(&cleared_references_, collector);
Mathieu Chartier78f7b4c2014-05-06 10:57:27 -0700178 // At this point all reference queues other than the cleared references should be empty.
179 DCHECK(soft_reference_queue_.IsEmpty());
180 DCHECK(weak_reference_queue_.IsEmpty());
181 DCHECK(finalizer_reference_queue_.IsEmpty());
182 DCHECK(phantom_reference_queue_.IsEmpty());
Mathieu Chartier2175f522014-05-09 11:01:06 -0700183 {
Mathieu Chartiera5a53ef2014-09-12 12:58:05 -0700184 MutexLock mu(self, *Locks::reference_processor_lock_);
Mathieu Chartier2175f522014-05-09 11:01:06 -0700185 // Need to always do this since the next GC may be concurrent. Doing this for only concurrent
186 // could result in a stale is_marked_callback_ being called before the reference processing
187 // starts since there is a small window of time where slow_path_enabled_ is enabled but the
188 // callback isn't yet set.
Mathieu Chartier97509952015-07-13 14:35:43 -0700189 collector_ = nullptr;
190 if (!kUseReadBarrier && concurrent) {
191 // Done processing, disable the slow path and broadcast to the waiters.
192 DisableSlowPath(self);
Mathieu Chartier2175f522014-05-09 11:01:06 -0700193 }
Mathieu Chartier78f7b4c2014-05-06 10:57:27 -0700194 }
Mathieu Chartier78f7b4c2014-05-06 10:57:27 -0700195}
196
197// Process the "referent" field in a java.lang.ref.Reference. If the referent has not yet been
198// marked, put it on the appropriate list in the heap for later processing.
Mathieu Chartier5d3f73a2016-10-14 14:28:47 -0700199void ReferenceProcessor::DelayReferenceReferent(ObjPtr<mirror::Class> klass,
200 ObjPtr<mirror::Reference> ref,
Mathieu Chartier97509952015-07-13 14:35:43 -0700201 collector::GarbageCollector* collector) {
Mathieu Chartier78f7b4c2014-05-06 10:57:27 -0700202 // klass can be the class of the old object if the visitor already updated the class of ref.
Mathieu Chartier308351a2014-06-15 12:39:02 -0700203 DCHECK(klass != nullptr);
Fred Shih4ee7a662014-07-11 09:59:27 -0700204 DCHECK(klass->IsTypeOfReferenceClass());
Mathieu Chartier308351a2014-06-15 12:39:02 -0700205 mirror::HeapReference<mirror::Object>* referent = ref->GetReferentReferenceAddr();
Mathieu Chartier97509952015-07-13 14:35:43 -0700206 if (referent->AsMirrorPtr() != nullptr && !collector->IsMarkedHeapReference(referent)) {
Mathieu Chartier308351a2014-06-15 12:39:02 -0700207 Thread* self = Thread::Current();
208 // TODO: Remove these locks, and use atomic stacks for storing references?
209 // We need to check that the references haven't already been enqueued since we can end up
210 // scanning the same reference multiple times due to dirty cards.
211 if (klass->IsSoftReferenceClass()) {
212 soft_reference_queue_.AtomicEnqueueIfNotEnqueued(self, ref);
213 } else if (klass->IsWeakReferenceClass()) {
214 weak_reference_queue_.AtomicEnqueueIfNotEnqueued(self, ref);
215 } else if (klass->IsFinalizerReferenceClass()) {
216 finalizer_reference_queue_.AtomicEnqueueIfNotEnqueued(self, ref);
217 } else if (klass->IsPhantomReferenceClass()) {
218 phantom_reference_queue_.AtomicEnqueueIfNotEnqueued(self, ref);
219 } else {
David Sehr709b0702016-10-13 09:12:37 -0700220 LOG(FATAL) << "Invalid reference type " << klass->PrettyClass() << " " << std::hex
Mathieu Chartier308351a2014-06-15 12:39:02 -0700221 << klass->GetAccessFlags();
Mathieu Chartier78f7b4c2014-05-06 10:57:27 -0700222 }
223 }
224}
225
Mathieu Chartier97509952015-07-13 14:35:43 -0700226void ReferenceProcessor::UpdateRoots(IsMarkedVisitor* visitor) {
227 cleared_references_.UpdateRoots(visitor);
Mathieu Chartier52e4b432014-06-10 11:22:31 -0700228}
229
Mathieu Chartiera5eae692014-12-17 17:56:03 -0800230class ClearedReferenceTask : public HeapTask {
231 public:
232 explicit ClearedReferenceTask(jobject cleared_references)
233 : HeapTask(NanoTime()), cleared_references_(cleared_references) {
234 }
235 virtual void Run(Thread* thread) {
236 ScopedObjectAccess soa(thread);
237 jvalue args[1];
238 args[0].l = cleared_references_;
239 InvokeWithJValues(soa, nullptr, WellKnownClasses::java_lang_ref_ReferenceQueue_add, args);
240 soa.Env()->DeleteGlobalRef(cleared_references_);
241 }
242
243 private:
244 const jobject cleared_references_;
245};
246
Mathieu Chartier308351a2014-06-15 12:39:02 -0700247void ReferenceProcessor::EnqueueClearedReferences(Thread* self) {
Mathieu Chartier78f7b4c2014-05-06 10:57:27 -0700248 Locks::mutator_lock_->AssertNotHeld(self);
Mathieu Chartiera5eae692014-12-17 17:56:03 -0800249 // When a runtime isn't started there are no reference queues to care about so ignore.
Mathieu Chartier78f7b4c2014-05-06 10:57:27 -0700250 if (!cleared_references_.IsEmpty()) {
Mathieu Chartier78f7b4c2014-05-06 10:57:27 -0700251 if (LIKELY(Runtime::Current()->IsStarted())) {
Mathieu Chartiera5eae692014-12-17 17:56:03 -0800252 jobject cleared_references;
253 {
254 ReaderMutexLock mu(self, *Locks::mutator_lock_);
255 cleared_references = self->GetJniEnv()->vm->AddGlobalRef(
256 self, cleared_references_.GetList());
257 }
258 if (kAsyncReferenceQueueAdd) {
259 // TODO: This can cause RunFinalization to terminate before newly freed objects are
260 // finalized since they may not be enqueued by the time RunFinalization starts.
261 Runtime::Current()->GetHeap()->GetTaskProcessor()->AddTask(
262 self, new ClearedReferenceTask(cleared_references));
263 } else {
264 ClearedReferenceTask task(cleared_references);
265 task.Run(self);
266 }
Mathieu Chartier78f7b4c2014-05-06 10:57:27 -0700267 }
268 cleared_references_.Clear();
269 }
270}
271
Mathieu Chartierc9a70282016-12-13 14:44:33 -0800272void ReferenceProcessor::ClearReferent(ObjPtr<mirror::Reference> ref) {
Mathieu Chartiera5a53ef2014-09-12 12:58:05 -0700273 Thread* self = Thread::Current();
274 MutexLock mu(self, *Locks::reference_processor_lock_);
Mathieu Chartierc9a70282016-12-13 14:44:33 -0800275 // Need to wait until reference processing is done since IsMarkedHeapReference does not have a
276 // CAS. If we do not wait, it can result in the GC un-clearing references due to race conditions.
277 // This also handles the race where the referent gets cleared after a null check but before
278 // IsMarkedHeapReference is called.
279 WaitUntilDoneProcessingReferences(self);
280 if (Runtime::Current()->IsActiveTransaction()) {
281 ref->ClearReferent<true>();
282 } else {
283 ref->ClearReferent<false>();
284 }
285}
286
287void ReferenceProcessor::WaitUntilDoneProcessingReferences(Thread* self) {
288 // Wait until we are done processing reference.
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700289 while ((!kUseReadBarrier && SlowPathEnabled()) ||
290 (kUseReadBarrier && !self->GetWeakRefAccessEnabled())) {
Hiroshi Yamauchi30493242016-11-03 13:06:52 -0700291 // Check and run the empty checkpoint before blocking so the empty checkpoint will work in the
292 // presence of threads blocking for weak ref access.
293 self->CheckEmptyCheckpoint();
Pavel Vyssotskid64ba382014-12-15 18:00:17 +0600294 condition_.WaitHoldingLocks(self);
Mathieu Chartiera5a53ef2014-09-12 12:58:05 -0700295 }
Mathieu Chartierc9a70282016-12-13 14:44:33 -0800296}
297
298bool ReferenceProcessor::MakeCircularListIfUnenqueued(
299 ObjPtr<mirror::FinalizerReference> reference) {
300 Thread* self = Thread::Current();
301 MutexLock mu(self, *Locks::reference_processor_lock_);
302 WaitUntilDoneProcessingReferences(self);
Mathieu Chartiera5a53ef2014-09-12 12:58:05 -0700303 // At this point, since the sentinel of the reference is live, it is guaranteed to not be
304 // enqueued if we just finished processing references. Otherwise, we may be doing the main GC
305 // phase. Since we are holding the reference processor lock, it guarantees that reference
306 // processing can't begin. The GC could have just enqueued the reference one one of the internal
307 // GC queues, but since we hold the lock finalizer_reference_queue_ lock it also prevents this
308 // race.
309 MutexLock mu2(self, *Locks::reference_queue_finalizer_references_lock_);
Richard Uhlerc4695df2016-01-15 14:08:05 -0800310 if (reference->IsUnprocessed()) {
Mathieu Chartiera5a53ef2014-09-12 12:58:05 -0700311 CHECK(reference->IsFinalizerReferenceInstance());
Richard Uhler522d51b2016-01-22 14:18:57 -0800312 reference->SetPendingNext(reference);
Mathieu Chartiera5a53ef2014-09-12 12:58:05 -0700313 return true;
314 }
315 return false;
316}
317
Mathieu Chartier78f7b4c2014-05-06 10:57:27 -0700318} // namespace gc
319} // namespace art