reference_processor.cc revision d85614222fa062ec809af9d65f04ab6b7dc1c248
1/*
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
19#include "mirror/object-inl.h"
20#include "mirror/reference.h"
21#include "mirror/reference-inl.h"
22#include "reference_processor-inl.h"
23#include "reflection.h"
24#include "ScopedLocalRef.h"
25#include "scoped_thread_state_change.h"
26#include "well_known_classes.h"
27
28namespace art {
29namespace gc {
30
31ReferenceProcessor::ReferenceProcessor()
32    : process_references_args_(nullptr, nullptr, nullptr),
33      preserving_references_(false), lock_("reference processor lock", kReferenceProcessorLock),
34      condition_("reference processor condition", lock_) {
35}
36
37void ReferenceProcessor::EnableSlowPath() {
38  mirror::Reference::GetJavaLangRefReference()->SetSlowPath(true);
39}
40
41void ReferenceProcessor::DisableSlowPath(Thread* self) {
42  mirror::Reference::GetJavaLangRefReference()->SetSlowPath(false);
43  condition_.Broadcast(self);
44}
45
46mirror::Object* ReferenceProcessor::GetReferent(Thread* self, mirror::Reference* reference) {
47  mirror::Object* const referent = reference->GetReferent();
48  // If the referent is null then it is already cleared, we can just return null since there is no
49  // scenario where it becomes non-null during the reference processing phase.
50  if (UNLIKELY(!SlowPathEnabled()) || referent == nullptr) {
51    return referent;
52  }
53  MutexLock mu(self, lock_);
54  while (SlowPathEnabled()) {
55    mirror::HeapReference<mirror::Object>* const referent_addr =
56        reference->GetReferentReferenceAddr();
57    // If the referent became cleared, return it. Don't need barrier since thread roots can't get
58    // updated until after we leave the function due to holding the mutator lock.
59    if (referent_addr->AsMirrorPtr() == nullptr) {
60      return nullptr;
61    }
62    // Try to see if the referent is already marked by using the is_marked_callback. We can return
63    // it to the mutator as long as the GC is not preserving references.
64    IsHeapReferenceMarkedCallback* const is_marked_callback =
65        process_references_args_.is_marked_callback_;
66    if (LIKELY(is_marked_callback != nullptr)) {
67      // If it's null it means not marked, but it could become marked if the referent is reachable
68      // by finalizer referents. So we can not return in this case and must block. Otherwise, we
69      // can return it to the mutator as long as the GC is not preserving references, in which
70      // case only black nodes can be safely returned. If the GC is preserving references, the
71      // mutator could take a white field from a grey or white node and move it somewhere else
72      // in the heap causing corruption since this field would get swept.
73      if (is_marked_callback(referent_addr, process_references_args_.arg_)) {
74        if (!preserving_references_ ||
75           (LIKELY(!reference->IsFinalizerReferenceInstance()) && !reference->IsEnqueued())) {
76          return referent_addr->AsMirrorPtr();
77        }
78      }
79    }
80    condition_.WaitHoldingLocks(self);
81  }
82  return reference->GetReferent();
83}
84
85bool ReferenceProcessor::PreserveSoftReferenceCallback(mirror::HeapReference<mirror::Object>* obj,
86                                                       void* arg) {
87  auto* const args = reinterpret_cast<ProcessReferencesArgs*>(arg);
88  // TODO: Add smarter logic for preserving soft references.
89  mirror::Object* new_obj = args->mark_callback_(obj->AsMirrorPtr(), args->arg_);
90  DCHECK(new_obj != nullptr);
91  obj->Assign(new_obj);
92  return true;
93}
94
95void ReferenceProcessor::StartPreservingReferences(Thread* self) {
96  MutexLock mu(self, lock_);
97  preserving_references_ = true;
98}
99
100void ReferenceProcessor::StopPreservingReferences(Thread* self) {
101  MutexLock mu(self, lock_);
102  preserving_references_ = false;
103  // We are done preserving references, some people who are blocked may see a marked referent.
104  condition_.Broadcast(self);
105}
106
107// Process reference class instances and schedule finalizations.
108void ReferenceProcessor::ProcessReferences(bool concurrent, TimingLogger* timings,
109                                           bool clear_soft_references,
110                                           IsHeapReferenceMarkedCallback* is_marked_callback,
111                                           MarkObjectCallback* mark_object_callback,
112                                           ProcessMarkStackCallback* process_mark_stack_callback,
113                                           void* arg) {
114  TimingLogger::ScopedTiming t(concurrent ? __FUNCTION__ : "(Paused)ProcessReferences", timings);
115  Thread* self = Thread::Current();
116  {
117    MutexLock mu(self, lock_);
118    process_references_args_.is_marked_callback_ = is_marked_callback;
119    process_references_args_.mark_callback_ = mark_object_callback;
120    process_references_args_.arg_ = arg;
121    CHECK_EQ(SlowPathEnabled(), concurrent) << "Slow path must be enabled iff concurrent";
122  }
123  // Unless required to clear soft references with white references, preserve some white referents.
124  if (!clear_soft_references) {
125    TimingLogger::ScopedTiming split(concurrent ? "ForwardSoftReferences" :
126        "(Paused)ForwardSoftReferences", timings);
127    if (concurrent) {
128      StartPreservingReferences(self);
129    }
130
131    soft_reference_queue_.ForwardSoftReferences(&PreserveSoftReferenceCallback,
132                                                &process_references_args_);
133    process_mark_stack_callback(arg);
134    if (concurrent) {
135      StopPreservingReferences(self);
136    }
137  }
138  // Clear all remaining soft and weak references with white referents.
139  soft_reference_queue_.ClearWhiteReferences(&cleared_references_, is_marked_callback, arg);
140  weak_reference_queue_.ClearWhiteReferences(&cleared_references_, is_marked_callback, arg);
141  {
142    TimingLogger::ScopedTiming t(concurrent ? "EnqueueFinalizerReferences" :
143        "(Paused)EnqueueFinalizerReferences", timings);
144    if (concurrent) {
145      StartPreservingReferences(self);
146    }
147    // Preserve all white objects with finalize methods and schedule them for finalization.
148    finalizer_reference_queue_.EnqueueFinalizerReferences(&cleared_references_, is_marked_callback,
149                                                          mark_object_callback, arg);
150    process_mark_stack_callback(arg);
151    if (concurrent) {
152      StopPreservingReferences(self);
153    }
154  }
155  // Clear all finalizer referent reachable soft and weak references with white referents.
156  soft_reference_queue_.ClearWhiteReferences(&cleared_references_, is_marked_callback, arg);
157  weak_reference_queue_.ClearWhiteReferences(&cleared_references_, is_marked_callback, arg);
158  // Clear all phantom references with white referents.
159  phantom_reference_queue_.ClearWhiteReferences(&cleared_references_, is_marked_callback, arg);
160  // At this point all reference queues other than the cleared references should be empty.
161  DCHECK(soft_reference_queue_.IsEmpty());
162  DCHECK(weak_reference_queue_.IsEmpty());
163  DCHECK(finalizer_reference_queue_.IsEmpty());
164  DCHECK(phantom_reference_queue_.IsEmpty());
165  {
166    MutexLock mu(self, lock_);
167    // Need to always do this since the next GC may be concurrent. Doing this for only concurrent
168    // could result in a stale is_marked_callback_ being called before the reference processing
169    // starts since there is a small window of time where slow_path_enabled_ is enabled but the
170    // callback isn't yet set.
171    process_references_args_.is_marked_callback_ = nullptr;
172    if (concurrent) {
173      // Done processing, disable the slow path and broadcast to the waiters.
174      DisableSlowPath(self);
175    }
176  }
177}
178
179// Process the "referent" field in a java.lang.ref.Reference.  If the referent has not yet been
180// marked, put it on the appropriate list in the heap for later processing.
181void ReferenceProcessor::DelayReferenceReferent(mirror::Class* klass, mirror::Reference* ref,
182                                                IsHeapReferenceMarkedCallback* is_marked_callback,
183                                                void* arg) {
184  // klass can be the class of the old object if the visitor already updated the class of ref.
185  DCHECK(klass != nullptr);
186  DCHECK(klass->IsTypeOfReferenceClass());
187  mirror::HeapReference<mirror::Object>* referent = ref->GetReferentReferenceAddr();
188  if (referent->AsMirrorPtr() != nullptr && !is_marked_callback(referent, arg)) {
189    Thread* self = Thread::Current();
190    // TODO: Remove these locks, and use atomic stacks for storing references?
191    // We need to check that the references haven't already been enqueued since we can end up
192    // scanning the same reference multiple times due to dirty cards.
193    if (klass->IsSoftReferenceClass()) {
194      soft_reference_queue_.AtomicEnqueueIfNotEnqueued(self, ref);
195    } else if (klass->IsWeakReferenceClass()) {
196      weak_reference_queue_.AtomicEnqueueIfNotEnqueued(self, ref);
197    } else if (klass->IsFinalizerReferenceClass()) {
198      finalizer_reference_queue_.AtomicEnqueueIfNotEnqueued(self, ref);
199    } else if (klass->IsPhantomReferenceClass()) {
200      phantom_reference_queue_.AtomicEnqueueIfNotEnqueued(self, ref);
201    } else {
202      LOG(FATAL) << "Invalid reference type " << PrettyClass(klass) << " " << std::hex
203                 << klass->GetAccessFlags();
204    }
205  }
206}
207
208void ReferenceProcessor::UpdateRoots(IsMarkedCallback* callback, void* arg) {
209  cleared_references_.UpdateRoots(callback, arg);
210}
211
212void ReferenceProcessor::EnqueueClearedReferences(Thread* self) {
213  Locks::mutator_lock_->AssertNotHeld(self);
214  if (!cleared_references_.IsEmpty()) {
215    // When a runtime isn't started there are no reference queues to care about so ignore.
216    if (LIKELY(Runtime::Current()->IsStarted())) {
217      ScopedObjectAccess soa(self);
218      ScopedLocalRef<jobject> arg(self->GetJniEnv(),
219                                  soa.AddLocalReference<jobject>(cleared_references_.GetList()));
220      jvalue args[1];
221      args[0].l = arg.get();
222      InvokeWithJValues(soa, nullptr, WellKnownClasses::java_lang_ref_ReferenceQueue_add, args);
223    }
224    cleared_references_.Clear();
225  }
226}
227
228}  // namespace gc
229}  // namespace art
230