heap.cc revision bbd695c71e0bf518f582e84524e1cdeb3de3896c
1/*
2 * Copyright (C) 2011 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 "heap.h"
18
19#define ATRACE_TAG ATRACE_TAG_DALVIK
20#include <cutils/trace.h>
21
22#include <limits>
23#include <vector>
24
25#include "base/histogram-inl.h"
26#include "base/stl_util.h"
27#include "common_throws.h"
28#include "cutils/sched_policy.h"
29#include "debugger.h"
30#include "gc/accounting/atomic_stack.h"
31#include "gc/accounting/card_table-inl.h"
32#include "gc/accounting/heap_bitmap-inl.h"
33#include "gc/accounting/mod_union_table.h"
34#include "gc/accounting/mod_union_table-inl.h"
35#include "gc/accounting/remembered_set.h"
36#include "gc/accounting/space_bitmap-inl.h"
37#include "gc/collector/concurrent_copying.h"
38#include "gc/collector/mark_sweep-inl.h"
39#include "gc/collector/partial_mark_sweep.h"
40#include "gc/collector/semi_space.h"
41#include "gc/collector/sticky_mark_sweep.h"
42#include "gc/space/bump_pointer_space.h"
43#include "gc/space/dlmalloc_space-inl.h"
44#include "gc/space/image_space.h"
45#include "gc/space/large_object_space.h"
46#include "gc/space/rosalloc_space-inl.h"
47#include "gc/space/space-inl.h"
48#include "gc/space/zygote_space.h"
49#include "entrypoints/quick/quick_alloc_entrypoints.h"
50#include "heap-inl.h"
51#include "image.h"
52#include "mirror/art_field-inl.h"
53#include "mirror/class-inl.h"
54#include "mirror/object.h"
55#include "mirror/object-inl.h"
56#include "mirror/object_array-inl.h"
57#include "mirror/reference-inl.h"
58#include "object_utils.h"
59#include "os.h"
60#include "reflection.h"
61#include "runtime.h"
62#include "ScopedLocalRef.h"
63#include "scoped_thread_state_change.h"
64#include "sirt_ref.h"
65#include "thread_list.h"
66#include "UniquePtr.h"
67#include "well_known_classes.h"
68
69namespace art {
70
71namespace gc {
72
73static constexpr size_t kCollectorTransitionStressIterations = 0;
74static constexpr size_t kCollectorTransitionStressWait = 10 * 1000;  // Microseconds
75static constexpr bool kGCALotMode = false;
76static constexpr size_t kGcAlotInterval = KB;
77// Minimum amount of remaining bytes before a concurrent GC is triggered.
78static constexpr size_t kMinConcurrentRemainingBytes = 128 * KB;
79static constexpr size_t kMaxConcurrentRemainingBytes = 512 * KB;
80// Sticky GC throughput adjustment, divided by 4. Increasing this causes sticky GC to occur more
81// relative to partial/full GC. This is desirable since sticky GCs interfere less with mutator
82// threads (lower pauses, use less memory bandwidth).
83static constexpr double kStickyGcThroughputAdjustment = 1.25;
84// Whether or not we use the free list large object space.
85static constexpr bool kUseFreeListSpaceForLOS = false;
86// Whtehr or not we compact the zygote in PreZygoteFork.
87static constexpr bool kCompactZygote = kMovingCollector;
88static constexpr size_t kNonMovingSpaceCapacity = 64 * MB;
89
90Heap::Heap(size_t initial_size, size_t growth_limit, size_t min_free, size_t max_free,
91           double target_utilization, double foreground_heap_growth_multiplier, size_t capacity,
92           const std::string& image_file_name,
93           CollectorType foreground_collector_type, CollectorType background_collector_type,
94           size_t parallel_gc_threads, size_t conc_gc_threads, bool low_memory_mode,
95           size_t long_pause_log_threshold, size_t long_gc_log_threshold,
96           bool ignore_max_footprint, bool use_tlab, bool verify_pre_gc_heap,
97           bool verify_post_gc_heap, bool verify_pre_gc_rosalloc,
98           bool verify_post_gc_rosalloc)
99    : non_moving_space_(nullptr),
100      rosalloc_space_(nullptr),
101      dlmalloc_space_(nullptr),
102      main_space_(nullptr),
103      collector_type_(kCollectorTypeNone),
104      foreground_collector_type_(foreground_collector_type),
105      background_collector_type_(background_collector_type),
106      desired_collector_type_(foreground_collector_type_),
107      heap_trim_request_lock_(nullptr),
108      last_trim_time_(0),
109      heap_transition_target_time_(0),
110      heap_trim_request_pending_(false),
111      parallel_gc_threads_(parallel_gc_threads),
112      conc_gc_threads_(conc_gc_threads),
113      low_memory_mode_(low_memory_mode),
114      long_pause_log_threshold_(long_pause_log_threshold),
115      long_gc_log_threshold_(long_gc_log_threshold),
116      ignore_max_footprint_(ignore_max_footprint),
117      have_zygote_space_(false),
118      large_object_threshold_(std::numeric_limits<size_t>::max()),  // Starts out disabled.
119      collector_type_running_(kCollectorTypeNone),
120      last_gc_type_(collector::kGcTypeNone),
121      next_gc_type_(collector::kGcTypePartial),
122      capacity_(capacity),
123      growth_limit_(growth_limit),
124      max_allowed_footprint_(initial_size),
125      native_footprint_gc_watermark_(initial_size),
126      native_footprint_limit_(2 * initial_size),
127      native_need_to_run_finalization_(false),
128      // Initially assume we perceive jank in case the process state is never updated.
129      process_state_(kProcessStateJankPerceptible),
130      concurrent_start_bytes_(std::numeric_limits<size_t>::max()),
131      total_bytes_freed_ever_(0),
132      total_objects_freed_ever_(0),
133      num_bytes_allocated_(0),
134      native_bytes_allocated_(0),
135      gc_memory_overhead_(0),
136      verify_missing_card_marks_(false),
137      verify_system_weaks_(false),
138      verify_pre_gc_heap_(verify_pre_gc_heap),
139      verify_post_gc_heap_(verify_post_gc_heap),
140      verify_mod_union_table_(false),
141      verify_pre_gc_rosalloc_(verify_pre_gc_rosalloc),
142      verify_post_gc_rosalloc_(verify_post_gc_rosalloc),
143      allocation_rate_(0),
144      /* For GC a lot mode, we limit the allocations stacks to be kGcAlotInterval allocations. This
145       * causes a lot of GC since we do a GC for alloc whenever the stack is full. When heap
146       * verification is enabled, we limit the size of allocation stacks to speed up their
147       * searching.
148       */
149      max_allocation_stack_size_(kGCALotMode ? kGcAlotInterval
150          : (kVerifyObjectSupport > kVerifyObjectModeFast) ? KB : MB),
151      current_allocator_(kAllocatorTypeDlMalloc),
152      current_non_moving_allocator_(kAllocatorTypeNonMoving),
153      bump_pointer_space_(nullptr),
154      temp_space_(nullptr),
155      min_free_(min_free),
156      max_free_(max_free),
157      target_utilization_(target_utilization),
158      foreground_heap_growth_multiplier_(foreground_heap_growth_multiplier),
159      total_wait_time_(0),
160      total_allocation_time_(0),
161      verify_object_mode_(kVerifyObjectModeDisabled),
162      disable_moving_gc_count_(0),
163      running_on_valgrind_(Runtime::Current()->RunningOnValgrind()),
164      use_tlab_(use_tlab) {
165  if (VLOG_IS_ON(heap) || VLOG_IS_ON(startup)) {
166    LOG(INFO) << "Heap() entering";
167  }
168  const bool is_zygote = Runtime::Current()->IsZygote();
169  // If we aren't the zygote, switch to the default non zygote allocator. This may update the
170  // entrypoints.
171  if (!is_zygote) {
172    large_object_threshold_ = kDefaultLargeObjectThreshold;
173    // Background compaction is currently not supported for command line runs.
174    if (background_collector_type_ != foreground_collector_type_) {
175      LOG(WARNING) << "Disabling background compaction for non zygote";
176      background_collector_type_ = foreground_collector_type_;
177    }
178  }
179  ChangeCollector(desired_collector_type_);
180
181  live_bitmap_.reset(new accounting::HeapBitmap(this));
182  mark_bitmap_.reset(new accounting::HeapBitmap(this));
183  // Requested begin for the alloc space, to follow the mapped image and oat files
184  byte* requested_alloc_space_begin = nullptr;
185  if (!image_file_name.empty()) {
186    space::ImageSpace* image_space = space::ImageSpace::Create(image_file_name.c_str());
187    CHECK(image_space != nullptr) << "Failed to create space for " << image_file_name;
188    AddSpace(image_space);
189    // Oat files referenced by image files immediately follow them in memory, ensure alloc space
190    // isn't going to get in the middle
191    byte* oat_file_end_addr = image_space->GetImageHeader().GetOatFileEnd();
192    CHECK_GT(oat_file_end_addr, image_space->End());
193    requested_alloc_space_begin = AlignUp(oat_file_end_addr, kPageSize);
194  }
195  if (is_zygote) {
196    // Reserve the address range before we create the non moving space to make sure bitmaps don't
197    // take it.
198    std::string error_str;
199    MemMap* mem_map = MemMap::MapAnonymous(
200        "main space", requested_alloc_space_begin + kNonMovingSpaceCapacity, capacity,
201        PROT_READ | PROT_WRITE, true, &error_str);
202    CHECK(mem_map != nullptr) << error_str;
203    // Non moving space is always dlmalloc since we currently don't have support for multiple
204    // rosalloc spaces.
205    non_moving_space_ = space::DlMallocSpace::Create(
206        "zygote / non moving space", initial_size, kNonMovingSpaceCapacity, kNonMovingSpaceCapacity,
207        requested_alloc_space_begin, false);
208    non_moving_space_->SetFootprintLimit(non_moving_space_->Capacity());
209    CreateMainMallocSpace(mem_map, initial_size, growth_limit, capacity);
210  } else {
211    std::string error_str;
212    MemMap* mem_map = MemMap::MapAnonymous("main/non-moving space", requested_alloc_space_begin,
213                                           capacity, PROT_READ | PROT_WRITE, true, &error_str);
214    CHECK(mem_map != nullptr) << error_str;
215    // Create the main free list space, which doubles as the non moving space. We can do this since
216    // non zygote means that we won't have any background compaction.
217    CreateMainMallocSpace(mem_map, initial_size, growth_limit, capacity);
218    non_moving_space_ = main_space_;
219  }
220  CHECK(non_moving_space_ != nullptr);
221
222  // We need to create the bump pointer if the foreground collector is a compacting GC. We only
223  // create the bump pointer space if we are not a moving foreground collector but have a moving
224  // background collector since the heap transition code will create the temp space by recycling
225  // the bitmap from the main space.
226  if (kMovingCollector) {
227    // TODO: Place bump-pointer spaces somewhere to minimize size of card table.
228    // TODO: Not create all the bump pointer spaces if not necessary (currently only GSS needs all
229    // 2 of bump pointer spaces + main space) b/14059466. Divide by 2 for a temporary fix.
230    const size_t bump_pointer_space_capacity = capacity / 2;
231    bump_pointer_space_ = space::BumpPointerSpace::Create("Bump pointer space",
232                                                          bump_pointer_space_capacity, nullptr);
233    CHECK(bump_pointer_space_ != nullptr) << "Failed to create bump pointer space";
234    AddSpace(bump_pointer_space_);
235    temp_space_ = space::BumpPointerSpace::Create("Bump pointer space 2",
236                                                  bump_pointer_space_capacity, nullptr);
237    CHECK(temp_space_ != nullptr) << "Failed to create bump pointer space";
238    AddSpace(temp_space_);
239  }
240  if (non_moving_space_ != main_space_) {
241    AddSpace(non_moving_space_);
242  }
243  if (main_space_ != nullptr) {
244    AddSpace(main_space_);
245  }
246
247  // Allocate the large object space.
248  if (kUseFreeListSpaceForLOS) {
249    large_object_space_ = space::FreeListSpace::Create("large object space", nullptr, capacity);
250  } else {
251    large_object_space_ = space::LargeObjectMapSpace::Create("large object space");
252  }
253  CHECK(large_object_space_ != nullptr) << "Failed to create large object space";
254  AddSpace(large_object_space_);
255
256  // Compute heap capacity. Continuous spaces are sorted in order of Begin().
257  CHECK(!continuous_spaces_.empty());
258
259  // Relies on the spaces being sorted.
260  byte* heap_begin = continuous_spaces_.front()->Begin();
261  byte* heap_end = continuous_spaces_.back()->Limit();
262  size_t heap_capacity = heap_end - heap_begin;
263
264  // Allocate the card table.
265  card_table_.reset(accounting::CardTable::Create(heap_begin, heap_capacity));
266  CHECK(card_table_.get() != NULL) << "Failed to create card table";
267
268  // Card cache for now since it makes it easier for us to update the references to the copying
269  // spaces.
270  accounting::ModUnionTable* mod_union_table =
271      new accounting::ModUnionTableToZygoteAllocspace("Image mod-union table", this,
272                                                      GetImageSpace());
273  CHECK(mod_union_table != nullptr) << "Failed to create image mod-union table";
274  AddModUnionTable(mod_union_table);
275
276  if (collector::SemiSpace::kUseRememberedSet) {
277    accounting::RememberedSet* non_moving_space_rem_set =
278        new accounting::RememberedSet("Non-moving space remembered set", this, non_moving_space_);
279    CHECK(non_moving_space_rem_set != nullptr) << "Failed to create non-moving space remembered set";
280    AddRememberedSet(non_moving_space_rem_set);
281    if (main_space_ != nullptr && main_space_ != non_moving_space_) {
282      accounting::RememberedSet* main_space_rem_set =
283          new accounting::RememberedSet("Main space remembered set", this, main_space_);
284      CHECK(main_space_rem_set != nullptr) << "Failed to create main space remembered set";
285      AddRememberedSet(main_space_rem_set);
286    }
287  }
288
289  // TODO: Count objects in the image space here.
290  num_bytes_allocated_ = 0;
291
292  // Default mark stack size in bytes.
293  static const size_t default_mark_stack_size = 64 * KB;
294  mark_stack_.reset(accounting::ObjectStack::Create("mark stack", default_mark_stack_size));
295  allocation_stack_.reset(accounting::ObjectStack::Create("allocation stack",
296                                                          max_allocation_stack_size_));
297  live_stack_.reset(accounting::ObjectStack::Create("live stack",
298                                                    max_allocation_stack_size_));
299
300  // It's still too early to take a lock because there are no threads yet, but we can create locks
301  // now. We don't create it earlier to make it clear that you can't use locks during heap
302  // initialization.
303  gc_complete_lock_ = new Mutex("GC complete lock");
304  gc_complete_cond_.reset(new ConditionVariable("GC complete condition variable",
305                                                *gc_complete_lock_));
306  heap_trim_request_lock_ = new Mutex("Heap trim request lock");
307  last_gc_size_ = GetBytesAllocated();
308
309  if (ignore_max_footprint_) {
310    SetIdealFootprint(std::numeric_limits<size_t>::max());
311    concurrent_start_bytes_ = std::numeric_limits<size_t>::max();
312  }
313  CHECK_NE(max_allowed_footprint_, 0U);
314
315  // Create our garbage collectors.
316  for (size_t i = 0; i < 2; ++i) {
317    const bool concurrent = i != 0;
318    garbage_collectors_.push_back(new collector::MarkSweep(this, concurrent));
319    garbage_collectors_.push_back(new collector::PartialMarkSweep(this, concurrent));
320    garbage_collectors_.push_back(new collector::StickyMarkSweep(this, concurrent));
321  }
322  if (kMovingCollector) {
323    // TODO: Clean this up.
324    bool generational = foreground_collector_type_ == kCollectorTypeGSS;
325    semi_space_collector_ = new collector::SemiSpace(this, generational,
326                                                     generational ? "generational" : "");
327    garbage_collectors_.push_back(semi_space_collector_);
328
329    concurrent_copying_collector_ = new collector::ConcurrentCopying(this);
330    garbage_collectors_.push_back(concurrent_copying_collector_);
331  }
332
333  if (running_on_valgrind_) {
334    Runtime::Current()->GetInstrumentation()->InstrumentQuickAllocEntryPoints();
335  }
336
337  if (VLOG_IS_ON(heap) || VLOG_IS_ON(startup)) {
338    LOG(INFO) << "Heap() exiting";
339  }
340}
341
342void Heap::CreateMainMallocSpace(MemMap* mem_map, size_t initial_size, size_t growth_limit,
343                                 size_t capacity) {
344  // Is background compaction is enabled?
345  bool can_move_objects = IsMovingGc(background_collector_type_) !=
346      IsMovingGc(foreground_collector_type_);
347  // If we are the zygote and don't yet have a zygote space, it means that the zygote fork will
348  // happen in the future. If this happens and we have kCompactZygote enabled we wish to compact
349  // from the main space to the zygote space. If background compaction is enabled, always pass in
350  // that we can move objets.
351  if (kCompactZygote && Runtime::Current()->IsZygote() && !can_move_objects) {
352    // After the zygote we want this to be false if we don't have background compaction enabled so
353    // that getting primitive array elements is faster.
354    can_move_objects = !have_zygote_space_;
355  }
356  if (kUseRosAlloc) {
357    main_space_ = space::RosAllocSpace::CreateFromMemMap(mem_map, "main rosalloc space",
358                                                         kDefaultStartingSize, initial_size,
359                                                         growth_limit, capacity, low_memory_mode_,
360                                                         can_move_objects);
361    CHECK(main_space_ != nullptr) << "Failed to create rosalloc space";
362  } else {
363    main_space_ = space::DlMallocSpace::CreateFromMemMap(mem_map, "main dlmalloc space",
364                                                         kDefaultStartingSize, initial_size,
365                                                         growth_limit, capacity,
366                                                         can_move_objects);
367    CHECK(main_space_ != nullptr) << "Failed to create dlmalloc space";
368  }
369  main_space_->SetFootprintLimit(main_space_->Capacity());
370  VLOG(heap) << "Created main space " << main_space_;
371}
372
373void Heap::ChangeAllocator(AllocatorType allocator) {
374  if (current_allocator_ != allocator) {
375    // These two allocators are only used internally and don't have any entrypoints.
376    CHECK_NE(allocator, kAllocatorTypeLOS);
377    CHECK_NE(allocator, kAllocatorTypeNonMoving);
378    current_allocator_ = allocator;
379    MutexLock mu(nullptr, *Locks::runtime_shutdown_lock_);
380    SetQuickAllocEntryPointsAllocator(current_allocator_);
381    Runtime::Current()->GetInstrumentation()->ResetQuickAllocEntryPoints();
382  }
383}
384
385void Heap::DisableCompaction() {
386  if (IsMovingGc(foreground_collector_type_)) {
387    foreground_collector_type_  = kCollectorTypeCMS;
388  }
389  if (IsMovingGc(background_collector_type_)) {
390    background_collector_type_ = foreground_collector_type_;
391  }
392  TransitionCollector(foreground_collector_type_);
393}
394
395std::string Heap::SafeGetClassDescriptor(mirror::Class* klass) {
396  if (!IsValidContinuousSpaceObjectAddress(klass)) {
397    return StringPrintf("<non heap address klass %p>", klass);
398  }
399  mirror::Class* component_type = klass->GetComponentType<kVerifyNone>();
400  if (IsValidContinuousSpaceObjectAddress(component_type) && klass->IsArrayClass<kVerifyNone>()) {
401    std::string result("[");
402    result += SafeGetClassDescriptor(component_type);
403    return result;
404  } else if (UNLIKELY(klass->IsPrimitive<kVerifyNone>())) {
405    return Primitive::Descriptor(klass->GetPrimitiveType<kVerifyNone>());
406  } else if (UNLIKELY(klass->IsProxyClass<kVerifyNone>())) {
407    return Runtime::Current()->GetClassLinker()->GetDescriptorForProxy(klass);
408  } else {
409    mirror::DexCache* dex_cache = klass->GetDexCache<kVerifyNone>();
410    if (!IsValidContinuousSpaceObjectAddress(dex_cache)) {
411      return StringPrintf("<non heap address dex_cache %p>", dex_cache);
412    }
413    const DexFile* dex_file = dex_cache->GetDexFile();
414    uint16_t class_def_idx = klass->GetDexClassDefIndex();
415    if (class_def_idx == DexFile::kDexNoIndex16) {
416      return "<class def not found>";
417    }
418    const DexFile::ClassDef& class_def = dex_file->GetClassDef(class_def_idx);
419    const DexFile::TypeId& type_id = dex_file->GetTypeId(class_def.class_idx_);
420    return dex_file->GetTypeDescriptor(type_id);
421  }
422}
423
424std::string Heap::SafePrettyTypeOf(mirror::Object* obj) {
425  if (obj == nullptr) {
426    return "null";
427  }
428  mirror::Class* klass = obj->GetClass<kVerifyNone>();
429  if (klass == nullptr) {
430    return "(class=null)";
431  }
432  std::string result(SafeGetClassDescriptor(klass));
433  if (obj->IsClass()) {
434    result += "<" + SafeGetClassDescriptor(obj->AsClass<kVerifyNone>()) + ">";
435  }
436  return result;
437}
438
439void Heap::DumpObject(std::ostream& stream, mirror::Object* obj) {
440  if (obj == nullptr) {
441    stream << "(obj=null)";
442    return;
443  }
444  if (IsAligned<kObjectAlignment>(obj)) {
445    space::Space* space = nullptr;
446    // Don't use find space since it only finds spaces which actually contain objects instead of
447    // spaces which may contain objects (e.g. cleared bump pointer spaces).
448    for (const auto& cur_space : continuous_spaces_) {
449      if (cur_space->HasAddress(obj)) {
450        space = cur_space;
451        break;
452      }
453    }
454    // Unprotect all the spaces.
455    for (const auto& space : continuous_spaces_) {
456      mprotect(space->Begin(), space->Capacity(), PROT_READ | PROT_WRITE);
457    }
458    stream << "Object " << obj;
459    if (space != nullptr) {
460      stream << " in space " << *space;
461    }
462    mirror::Class* klass = obj->GetClass<kVerifyNone>();
463    stream << "\nclass=" << klass;
464    if (klass != nullptr) {
465      stream << " type= " << SafePrettyTypeOf(obj);
466    }
467    // Re-protect the address we faulted on.
468    mprotect(AlignDown(obj, kPageSize), kPageSize, PROT_NONE);
469  }
470}
471
472bool Heap::IsCompilingBoot() const {
473  for (const auto& space : continuous_spaces_) {
474    if (space->IsImageSpace() || space->IsZygoteSpace()) {
475      return false;
476    }
477  }
478  return true;
479}
480
481bool Heap::HasImageSpace() const {
482  for (const auto& space : continuous_spaces_) {
483    if (space->IsImageSpace()) {
484      return true;
485    }
486  }
487  return false;
488}
489
490void Heap::IncrementDisableMovingGC(Thread* self) {
491  // Need to do this holding the lock to prevent races where the GC is about to run / running when
492  // we attempt to disable it.
493  ScopedThreadStateChange tsc(self, kWaitingForGcToComplete);
494  MutexLock mu(self, *gc_complete_lock_);
495  ++disable_moving_gc_count_;
496  if (IsMovingGc(collector_type_running_)) {
497    WaitForGcToCompleteLocked(self);
498  }
499}
500
501void Heap::DecrementDisableMovingGC(Thread* self) {
502  MutexLock mu(self, *gc_complete_lock_);
503  CHECK_GE(disable_moving_gc_count_, 0U);
504  --disable_moving_gc_count_;
505}
506
507void Heap::UpdateProcessState(ProcessState process_state) {
508  if (process_state_ != process_state) {
509    process_state_ = process_state;
510    for (size_t i = 1; i <= kCollectorTransitionStressIterations; ++i) {
511      // Start at index 1 to avoid "is always false" warning.
512      // Have iteration 1 always transition the collector.
513      TransitionCollector((((i & 1) == 1) == (process_state_ == kProcessStateJankPerceptible))
514                          ? foreground_collector_type_ : background_collector_type_);
515      usleep(kCollectorTransitionStressWait);
516    }
517    if (process_state_ == kProcessStateJankPerceptible) {
518      // Transition back to foreground right away to prevent jank.
519      RequestCollectorTransition(foreground_collector_type_, 0);
520    } else {
521      // Don't delay for debug builds since we may want to stress test the GC.
522      RequestCollectorTransition(background_collector_type_, kIsDebugBuild ? 0 :
523          kCollectorTransitionWait);
524    }
525  }
526}
527
528void Heap::CreateThreadPool() {
529  const size_t num_threads = std::max(parallel_gc_threads_, conc_gc_threads_);
530  if (num_threads != 0) {
531    thread_pool_.reset(new ThreadPool("Heap thread pool", num_threads));
532  }
533}
534
535void Heap::VisitObjects(ObjectCallback callback, void* arg) {
536  Thread* self = Thread::Current();
537  // GCs can move objects, so don't allow this.
538  const char* old_cause = self->StartAssertNoThreadSuspension("Visiting objects");
539  if (bump_pointer_space_ != nullptr) {
540    // Visit objects in bump pointer space.
541    bump_pointer_space_->Walk(callback, arg);
542  }
543  // TODO: Switch to standard begin and end to use ranged a based loop.
544  for (mirror::Object** it = allocation_stack_->Begin(), **end = allocation_stack_->End();
545      it < end; ++it) {
546    mirror::Object* obj = *it;
547    if (obj != nullptr && obj->GetClass() != nullptr) {
548      // Avoid the race condition caused by the object not yet being written into the allocation
549      // stack or the class not yet being written in the object. Or, if kUseThreadLocalAllocationStack,
550      // there can be nulls on the allocation stack.
551      callback(obj, arg);
552    }
553  }
554  GetLiveBitmap()->Walk(callback, arg);
555  self->EndAssertNoThreadSuspension(old_cause);
556}
557
558void Heap::MarkAllocStackAsLive(accounting::ObjectStack* stack) {
559  space::ContinuousSpace* space1 = rosalloc_space_ != nullptr ? rosalloc_space_ : non_moving_space_;
560  space::ContinuousSpace* space2 = dlmalloc_space_ != nullptr ? dlmalloc_space_ : non_moving_space_;
561  // This is just logic to handle a case of either not having a rosalloc or dlmalloc space.
562  // TODO: Generalize this to n bitmaps?
563  if (space1 == nullptr) {
564    DCHECK(space2 != nullptr);
565    space1 = space2;
566  }
567  if (space2 == nullptr) {
568    DCHECK(space1 != nullptr);
569    space2 = space1;
570  }
571  MarkAllocStack(space1->GetLiveBitmap(), space2->GetLiveBitmap(),
572                 large_object_space_->GetLiveBitmap(), stack);
573}
574
575void Heap::DeleteThreadPool() {
576  thread_pool_.reset(nullptr);
577}
578
579void Heap::AddSpace(space::Space* space, bool set_as_default) {
580  DCHECK(space != nullptr);
581  WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
582  if (space->IsContinuousSpace()) {
583    DCHECK(!space->IsDiscontinuousSpace());
584    space::ContinuousSpace* continuous_space = space->AsContinuousSpace();
585    // Continuous spaces don't necessarily have bitmaps.
586    accounting::ContinuousSpaceBitmap* live_bitmap = continuous_space->GetLiveBitmap();
587    accounting::ContinuousSpaceBitmap* mark_bitmap = continuous_space->GetMarkBitmap();
588    if (live_bitmap != nullptr) {
589      DCHECK(mark_bitmap != nullptr);
590      live_bitmap_->AddContinuousSpaceBitmap(live_bitmap);
591      mark_bitmap_->AddContinuousSpaceBitmap(mark_bitmap);
592    }
593    continuous_spaces_.push_back(continuous_space);
594    if (set_as_default) {
595      if (continuous_space->IsDlMallocSpace()) {
596        dlmalloc_space_ = continuous_space->AsDlMallocSpace();
597      } else if (continuous_space->IsRosAllocSpace()) {
598        rosalloc_space_ = continuous_space->AsRosAllocSpace();
599      }
600    }
601    // Ensure that spaces remain sorted in increasing order of start address.
602    std::sort(continuous_spaces_.begin(), continuous_spaces_.end(),
603              [](const space::ContinuousSpace* a, const space::ContinuousSpace* b) {
604      return a->Begin() < b->Begin();
605    });
606  } else {
607    DCHECK(space->IsDiscontinuousSpace());
608    space::DiscontinuousSpace* discontinuous_space = space->AsDiscontinuousSpace();
609    live_bitmap_->AddLargeObjectBitmap(discontinuous_space->GetLiveBitmap());
610    mark_bitmap_->AddLargeObjectBitmap(discontinuous_space->GetMarkBitmap());
611    discontinuous_spaces_.push_back(discontinuous_space);
612  }
613  if (space->IsAllocSpace()) {
614    alloc_spaces_.push_back(space->AsAllocSpace());
615  }
616}
617
618void Heap::RemoveSpace(space::Space* space) {
619  DCHECK(space != nullptr);
620  WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
621  if (space->IsContinuousSpace()) {
622    DCHECK(!space->IsDiscontinuousSpace());
623    space::ContinuousSpace* continuous_space = space->AsContinuousSpace();
624    // Continuous spaces don't necessarily have bitmaps.
625    accounting::ContinuousSpaceBitmap* live_bitmap = continuous_space->GetLiveBitmap();
626    accounting::ContinuousSpaceBitmap* mark_bitmap = continuous_space->GetMarkBitmap();
627    if (live_bitmap != nullptr) {
628      DCHECK(mark_bitmap != nullptr);
629      live_bitmap_->RemoveContinuousSpaceBitmap(live_bitmap);
630      mark_bitmap_->RemoveContinuousSpaceBitmap(mark_bitmap);
631    }
632    auto it = std::find(continuous_spaces_.begin(), continuous_spaces_.end(), continuous_space);
633    DCHECK(it != continuous_spaces_.end());
634    continuous_spaces_.erase(it);
635    if (continuous_space == dlmalloc_space_) {
636      dlmalloc_space_ = nullptr;
637    } else if (continuous_space == rosalloc_space_) {
638      rosalloc_space_ = nullptr;
639    }
640    if (continuous_space == main_space_) {
641      main_space_ = nullptr;
642    } else if (continuous_space == bump_pointer_space_) {
643      bump_pointer_space_ = nullptr;
644    } else if (continuous_space == temp_space_) {
645      temp_space_ = nullptr;
646    }
647  } else {
648    DCHECK(space->IsDiscontinuousSpace());
649    space::DiscontinuousSpace* discontinuous_space = space->AsDiscontinuousSpace();
650    live_bitmap_->RemoveLargeObjectBitmap(discontinuous_space->GetLiveBitmap());
651    mark_bitmap_->RemoveLargeObjectBitmap(discontinuous_space->GetMarkBitmap());
652    auto it = std::find(discontinuous_spaces_.begin(), discontinuous_spaces_.end(),
653                        discontinuous_space);
654    DCHECK(it != discontinuous_spaces_.end());
655    discontinuous_spaces_.erase(it);
656  }
657  if (space->IsAllocSpace()) {
658    auto it = std::find(alloc_spaces_.begin(), alloc_spaces_.end(), space->AsAllocSpace());
659    DCHECK(it != alloc_spaces_.end());
660    alloc_spaces_.erase(it);
661  }
662}
663
664void Heap::RegisterGCAllocation(size_t bytes) {
665  if (this != nullptr) {
666    gc_memory_overhead_.FetchAndAdd(bytes);
667  }
668}
669
670void Heap::RegisterGCDeAllocation(size_t bytes) {
671  if (this != nullptr) {
672    gc_memory_overhead_.FetchAndSub(bytes);
673  }
674}
675
676void Heap::DumpGcPerformanceInfo(std::ostream& os) {
677  // Dump cumulative timings.
678  os << "Dumping cumulative Gc timings\n";
679  uint64_t total_duration = 0;
680  // Dump cumulative loggers for each GC type.
681  uint64_t total_paused_time = 0;
682  for (auto& collector : garbage_collectors_) {
683    const CumulativeLogger& logger = collector->GetCumulativeTimings();
684    const size_t iterations = logger.GetIterations();
685    const Histogram<uint64_t>& pause_histogram = collector->GetPauseHistogram();
686    if (iterations != 0 && pause_histogram.SampleSize() != 0) {
687      os << ConstDumpable<CumulativeLogger>(logger);
688      const uint64_t total_ns = logger.GetTotalNs();
689      const uint64_t total_pause_ns = collector->GetTotalPausedTimeNs();
690      double seconds = NsToMs(logger.GetTotalNs()) / 1000.0;
691      const uint64_t freed_bytes = collector->GetTotalFreedBytes();
692      const uint64_t freed_objects = collector->GetTotalFreedObjects();
693      Histogram<uint64_t>::CumulativeData cumulative_data;
694      pause_histogram.CreateHistogram(&cumulative_data);
695      pause_histogram.PrintConfidenceIntervals(os, 0.99, cumulative_data);
696      os << collector->GetName() << " total time: " << PrettyDuration(total_ns)
697         << " mean time: " << PrettyDuration(total_ns / iterations) << "\n"
698         << collector->GetName() << " freed: " << freed_objects
699         << " objects with total size " << PrettySize(freed_bytes) << "\n"
700         << collector->GetName() << " throughput: " << freed_objects / seconds << "/s / "
701         << PrettySize(freed_bytes / seconds) << "/s\n";
702      total_duration += total_ns;
703      total_paused_time += total_pause_ns;
704    }
705    collector->ResetMeasurements();
706  }
707  uint64_t allocation_time = static_cast<uint64_t>(total_allocation_time_) * kTimeAdjust;
708  if (total_duration != 0) {
709    const double total_seconds = static_cast<double>(total_duration / 1000) / 1000000.0;
710    os << "Total time spent in GC: " << PrettyDuration(total_duration) << "\n";
711    os << "Mean GC size throughput: "
712       << PrettySize(GetBytesFreedEver() / total_seconds) << "/s\n";
713    os << "Mean GC object throughput: "
714       << (GetObjectsFreedEver() / total_seconds) << " objects/s\n";
715  }
716  size_t total_objects_allocated = GetObjectsAllocatedEver();
717  os << "Total number of allocations: " << total_objects_allocated << "\n";
718  size_t total_bytes_allocated = GetBytesAllocatedEver();
719  os << "Total bytes allocated " << PrettySize(total_bytes_allocated) << "\n";
720  if (kMeasureAllocationTime) {
721    os << "Total time spent allocating: " << PrettyDuration(allocation_time) << "\n";
722    os << "Mean allocation time: " << PrettyDuration(allocation_time / total_objects_allocated)
723       << "\n";
724  }
725  os << "Total mutator paused time: " << PrettyDuration(total_paused_time) << "\n";
726  os << "Total time waiting for GC to complete: " << PrettyDuration(total_wait_time_) << "\n";
727  os << "Approximate GC data structures memory overhead: " << gc_memory_overhead_;
728}
729
730Heap::~Heap() {
731  VLOG(heap) << "Starting ~Heap()";
732  STLDeleteElements(&garbage_collectors_);
733  // If we don't reset then the mark stack complains in its destructor.
734  allocation_stack_->Reset();
735  live_stack_->Reset();
736  STLDeleteValues(&mod_union_tables_);
737  STLDeleteValues(&remembered_sets_);
738  STLDeleteElements(&continuous_spaces_);
739  STLDeleteElements(&discontinuous_spaces_);
740  delete gc_complete_lock_;
741  delete heap_trim_request_lock_;
742  VLOG(heap) << "Finished ~Heap()";
743}
744
745space::ContinuousSpace* Heap::FindContinuousSpaceFromObject(const mirror::Object* obj,
746                                                            bool fail_ok) const {
747  for (const auto& space : continuous_spaces_) {
748    if (space->Contains(obj)) {
749      return space;
750    }
751  }
752  if (!fail_ok) {
753    LOG(FATAL) << "object " << reinterpret_cast<const void*>(obj) << " not inside any spaces!";
754  }
755  return NULL;
756}
757
758space::DiscontinuousSpace* Heap::FindDiscontinuousSpaceFromObject(const mirror::Object* obj,
759                                                                  bool fail_ok) const {
760  for (const auto& space : discontinuous_spaces_) {
761    if (space->Contains(obj)) {
762      return space;
763    }
764  }
765  if (!fail_ok) {
766    LOG(FATAL) << "object " << reinterpret_cast<const void*>(obj) << " not inside any spaces!";
767  }
768  return NULL;
769}
770
771space::Space* Heap::FindSpaceFromObject(const mirror::Object* obj, bool fail_ok) const {
772  space::Space* result = FindContinuousSpaceFromObject(obj, true);
773  if (result != NULL) {
774    return result;
775  }
776  return FindDiscontinuousSpaceFromObject(obj, true);
777}
778
779struct SoftReferenceArgs {
780  IsMarkedCallback* is_marked_callback_;
781  MarkObjectCallback* mark_callback_;
782  void* arg_;
783};
784
785mirror::Object* Heap::PreserveSoftReferenceCallback(mirror::Object* obj, void* arg) {
786  SoftReferenceArgs* args = reinterpret_cast<SoftReferenceArgs*>(arg);
787  // TODO: Not preserve all soft references.
788  return args->mark_callback_(obj, args->arg_);
789}
790
791void Heap::ProcessSoftReferences(TimingLogger& timings, bool clear_soft,
792                                 IsMarkedCallback* is_marked_callback,
793                                 MarkObjectCallback* mark_object_callback,
794                                 ProcessMarkStackCallback* process_mark_stack_callback, void* arg) {
795  // Unless required to clear soft references with white references, preserve some white referents.
796  if (!clear_soft) {
797    // Don't clear for sticky GC.
798    SoftReferenceArgs soft_reference_args;
799    soft_reference_args.is_marked_callback_ = is_marked_callback;
800    soft_reference_args.mark_callback_ = mark_object_callback;
801    soft_reference_args.arg_ = arg;
802    // References with a marked referent are removed from the list.
803    soft_reference_queue_.PreserveSomeSoftReferences(&PreserveSoftReferenceCallback,
804                                                     &soft_reference_args);
805    process_mark_stack_callback(arg);
806  }
807}
808
809// Process reference class instances and schedule finalizations.
810void Heap::ProcessReferences(TimingLogger& timings, bool clear_soft,
811                             IsMarkedCallback* is_marked_callback,
812                             MarkObjectCallback* mark_object_callback,
813                             ProcessMarkStackCallback* process_mark_stack_callback, void* arg) {
814  timings.StartSplit("(Paused)ProcessReferences");
815  ProcessSoftReferences(timings, clear_soft, is_marked_callback, mark_object_callback,
816                        process_mark_stack_callback, arg);
817  // Clear all remaining soft and weak references with white referents.
818  soft_reference_queue_.ClearWhiteReferences(cleared_references_, is_marked_callback, arg);
819  weak_reference_queue_.ClearWhiteReferences(cleared_references_, is_marked_callback, arg);
820  timings.EndSplit();
821  // Preserve all white objects with finalize methods and schedule them for finalization.
822  timings.StartSplit("(Paused)EnqueueFinalizerReferences");
823  finalizer_reference_queue_.EnqueueFinalizerReferences(cleared_references_, is_marked_callback,
824                                                        mark_object_callback, arg);
825  process_mark_stack_callback(arg);
826  timings.EndSplit();
827  timings.StartSplit("(Paused)ProcessReferences");
828  // Clear all f-reachable soft and weak references with white referents.
829  soft_reference_queue_.ClearWhiteReferences(cleared_references_, is_marked_callback, arg);
830  weak_reference_queue_.ClearWhiteReferences(cleared_references_, is_marked_callback, arg);
831  // Clear all phantom references with white referents.
832  phantom_reference_queue_.ClearWhiteReferences(cleared_references_, is_marked_callback, arg);
833  // At this point all reference queues other than the cleared references should be empty.
834  DCHECK(soft_reference_queue_.IsEmpty());
835  DCHECK(weak_reference_queue_.IsEmpty());
836  DCHECK(finalizer_reference_queue_.IsEmpty());
837  DCHECK(phantom_reference_queue_.IsEmpty());
838  timings.EndSplit();
839}
840
841// Process the "referent" field in a java.lang.ref.Reference.  If the referent has not yet been
842// marked, put it on the appropriate list in the heap for later processing.
843void Heap::DelayReferenceReferent(mirror::Class* klass, mirror::Reference* ref,
844                                  IsMarkedCallback is_marked_callback, void* arg) {
845  // klass can be the class of the old object if the visitor already updated the class of ref.
846  DCHECK(klass->IsReferenceClass());
847  mirror::Object* referent = ref->GetReferent();
848  if (referent != nullptr) {
849    mirror::Object* forward_address = is_marked_callback(referent, arg);
850    // Null means that the object is not currently marked.
851    if (forward_address == nullptr) {
852      Thread* self = Thread::Current();
853      // TODO: Remove these locks, and use atomic stacks for storing references?
854      // We need to check that the references haven't already been enqueued since we can end up
855      // scanning the same reference multiple times due to dirty cards.
856      if (klass->IsSoftReferenceClass()) {
857        soft_reference_queue_.AtomicEnqueueIfNotEnqueued(self, ref);
858      } else if (klass->IsWeakReferenceClass()) {
859        weak_reference_queue_.AtomicEnqueueIfNotEnqueued(self, ref);
860      } else if (klass->IsFinalizerReferenceClass()) {
861        finalizer_reference_queue_.AtomicEnqueueIfNotEnqueued(self, ref);
862      } else if (klass->IsPhantomReferenceClass()) {
863        phantom_reference_queue_.AtomicEnqueueIfNotEnqueued(self, ref);
864      } else {
865        LOG(FATAL) << "Invalid reference type " << PrettyClass(klass) << " " << std::hex
866                   << klass->GetAccessFlags();
867      }
868    } else if (referent != forward_address) {
869      // Referent is already marked and we need to update it.
870      ref->SetReferent<false>(forward_address);
871    }
872  }
873}
874
875space::ImageSpace* Heap::GetImageSpace() const {
876  for (const auto& space : continuous_spaces_) {
877    if (space->IsImageSpace()) {
878      return space->AsImageSpace();
879    }
880  }
881  return NULL;
882}
883
884static void MSpaceChunkCallback(void* start, void* end, size_t used_bytes, void* arg) {
885  size_t chunk_size = reinterpret_cast<uint8_t*>(end) - reinterpret_cast<uint8_t*>(start);
886  if (used_bytes < chunk_size) {
887    size_t chunk_free_bytes = chunk_size - used_bytes;
888    size_t& max_contiguous_allocation = *reinterpret_cast<size_t*>(arg);
889    max_contiguous_allocation = std::max(max_contiguous_allocation, chunk_free_bytes);
890  }
891}
892
893void Heap::ThrowOutOfMemoryError(Thread* self, size_t byte_count, bool large_object_allocation) {
894  std::ostringstream oss;
895  size_t total_bytes_free = GetFreeMemory();
896  oss << "Failed to allocate a " << byte_count << " byte allocation with " << total_bytes_free
897      << " free bytes";
898  // If the allocation failed due to fragmentation, print out the largest continuous allocation.
899  if (!large_object_allocation && total_bytes_free >= byte_count) {
900    size_t max_contiguous_allocation = 0;
901    for (const auto& space : continuous_spaces_) {
902      if (space->IsMallocSpace()) {
903        // To allow the Walk/InspectAll() to exclusively-lock the mutator
904        // lock, temporarily release the shared access to the mutator
905        // lock here by transitioning to the suspended state.
906        Locks::mutator_lock_->AssertSharedHeld(self);
907        self->TransitionFromRunnableToSuspended(kSuspended);
908        space->AsMallocSpace()->Walk(MSpaceChunkCallback, &max_contiguous_allocation);
909        self->TransitionFromSuspendedToRunnable();
910        Locks::mutator_lock_->AssertSharedHeld(self);
911      }
912    }
913    oss << "; failed due to fragmentation (largest possible contiguous allocation "
914        <<  max_contiguous_allocation << " bytes)";
915  }
916  self->ThrowOutOfMemoryError(oss.str().c_str());
917}
918
919void Heap::DoPendingTransitionOrTrim() {
920  Thread* self = Thread::Current();
921  CollectorType desired_collector_type;
922  // Wait until we reach the desired transition time.
923  while (true) {
924    uint64_t wait_time;
925    {
926      MutexLock mu(self, *heap_trim_request_lock_);
927      desired_collector_type = desired_collector_type_;
928      uint64_t current_time = NanoTime();
929      if (current_time >= heap_transition_target_time_) {
930        break;
931      }
932      wait_time = heap_transition_target_time_ - current_time;
933    }
934    ScopedThreadStateChange tsc(self, kSleeping);
935    usleep(wait_time / 1000);  // Usleep takes microseconds.
936  }
937  // Transition the collector if the desired collector type is not the same as the current
938  // collector type.
939  TransitionCollector(desired_collector_type);
940  if (!CareAboutPauseTimes()) {
941    // Deflate the monitors, this can cause a pause but shouldn't matter since we don't care
942    // about pauses.
943    Runtime* runtime = Runtime::Current();
944    runtime->GetThreadList()->SuspendAll();
945    runtime->GetMonitorList()->DeflateMonitors();
946    runtime->GetThreadList()->ResumeAll();
947    // Do a heap trim if it is needed.
948    Trim();
949  }
950}
951
952void Heap::Trim() {
953  Thread* self = Thread::Current();
954  {
955    MutexLock mu(self, *heap_trim_request_lock_);
956    if (!heap_trim_request_pending_ || last_trim_time_ + kHeapTrimWait >= NanoTime()) {
957      return;
958    }
959    last_trim_time_ = NanoTime();
960    heap_trim_request_pending_ = false;
961  }
962  {
963    // Need to do this before acquiring the locks since we don't want to get suspended while
964    // holding any locks.
965    ScopedThreadStateChange tsc(self, kWaitingForGcToComplete);
966    // Pretend we are doing a GC to prevent background compaction from deleting the space we are
967    // trimming.
968    MutexLock mu(self, *gc_complete_lock_);
969    // Ensure there is only one GC at a time.
970    WaitForGcToCompleteLocked(self);
971    collector_type_running_ = kCollectorTypeHeapTrim;
972  }
973  uint64_t start_ns = NanoTime();
974  // Trim the managed spaces.
975  uint64_t total_alloc_space_allocated = 0;
976  uint64_t total_alloc_space_size = 0;
977  uint64_t managed_reclaimed = 0;
978  for (const auto& space : continuous_spaces_) {
979    if (space->IsMallocSpace()) {
980      gc::space::MallocSpace* alloc_space = space->AsMallocSpace();
981      total_alloc_space_size += alloc_space->Size();
982      managed_reclaimed += alloc_space->Trim();
983    }
984  }
985  total_alloc_space_allocated = GetBytesAllocated() - large_object_space_->GetBytesAllocated();
986  if (bump_pointer_space_ != nullptr) {
987    total_alloc_space_allocated -= bump_pointer_space_->Size();
988  }
989  const float managed_utilization = static_cast<float>(total_alloc_space_allocated) /
990      static_cast<float>(total_alloc_space_size);
991  uint64_t gc_heap_end_ns = NanoTime();
992  // We never move things in the native heap, so we can finish the GC at this point.
993  FinishGC(self, collector::kGcTypeNone);
994  // Trim the native heap.
995  dlmalloc_trim(0);
996  size_t native_reclaimed = 0;
997  dlmalloc_inspect_all(DlmallocMadviseCallback, &native_reclaimed);
998  uint64_t end_ns = NanoTime();
999  VLOG(heap) << "Heap trim of managed (duration=" << PrettyDuration(gc_heap_end_ns - start_ns)
1000      << ", advised=" << PrettySize(managed_reclaimed) << ") and native (duration="
1001      << PrettyDuration(end_ns - gc_heap_end_ns) << ", advised=" << PrettySize(native_reclaimed)
1002      << ") heaps. Managed heap utilization of " << static_cast<int>(100 * managed_utilization)
1003      << "%.";
1004}
1005
1006bool Heap::IsValidObjectAddress(const mirror::Object* obj) const {
1007  // Note: we deliberately don't take the lock here, and mustn't test anything that would require
1008  // taking the lock.
1009  if (obj == nullptr) {
1010    return true;
1011  }
1012  return IsAligned<kObjectAlignment>(obj) && FindSpaceFromObject(obj, true) != nullptr;
1013}
1014
1015bool Heap::IsNonDiscontinuousSpaceHeapAddress(const mirror::Object* obj) const {
1016  return FindContinuousSpaceFromObject(obj, true) != nullptr;
1017}
1018
1019bool Heap::IsValidContinuousSpaceObjectAddress(const mirror::Object* obj) const {
1020  if (obj == nullptr || !IsAligned<kObjectAlignment>(obj)) {
1021    return false;
1022  }
1023  for (const auto& space : continuous_spaces_) {
1024    if (space->HasAddress(obj)) {
1025      return true;
1026    }
1027  }
1028  return false;
1029}
1030
1031bool Heap::IsLiveObjectLocked(mirror::Object* obj, bool search_allocation_stack,
1032                              bool search_live_stack, bool sorted) {
1033  if (UNLIKELY(!IsAligned<kObjectAlignment>(obj))) {
1034    return false;
1035  }
1036  if (bump_pointer_space_ != nullptr && bump_pointer_space_->HasAddress(obj)) {
1037    mirror::Class* klass = obj->GetClass<kVerifyNone>();
1038    if (obj == klass) {
1039      // This case happens for java.lang.Class.
1040      return true;
1041    }
1042    return VerifyClassClass(klass) && IsLiveObjectLocked(klass);
1043  } else if (temp_space_ != nullptr && temp_space_->HasAddress(obj)) {
1044    // If we are in the allocated region of the temp space, then we are probably live (e.g. during
1045    // a GC). When a GC isn't running End() - Begin() is 0 which means no objects are contained.
1046    return temp_space_->Contains(obj);
1047  }
1048  space::ContinuousSpace* c_space = FindContinuousSpaceFromObject(obj, true);
1049  space::DiscontinuousSpace* d_space = nullptr;
1050  if (c_space != nullptr) {
1051    if (c_space->GetLiveBitmap()->Test(obj)) {
1052      return true;
1053    }
1054  } else {
1055    d_space = FindDiscontinuousSpaceFromObject(obj, true);
1056    if (d_space != nullptr) {
1057      if (d_space->GetLiveBitmap()->Test(obj)) {
1058        return true;
1059      }
1060    }
1061  }
1062  // This is covering the allocation/live stack swapping that is done without mutators suspended.
1063  for (size_t i = 0; i < (sorted ? 1 : 5); ++i) {
1064    if (i > 0) {
1065      NanoSleep(MsToNs(10));
1066    }
1067    if (search_allocation_stack) {
1068      if (sorted) {
1069        if (allocation_stack_->ContainsSorted(obj)) {
1070          return true;
1071        }
1072      } else if (allocation_stack_->Contains(obj)) {
1073        return true;
1074      }
1075    }
1076
1077    if (search_live_stack) {
1078      if (sorted) {
1079        if (live_stack_->ContainsSorted(obj)) {
1080          return true;
1081        }
1082      } else if (live_stack_->Contains(obj)) {
1083        return true;
1084      }
1085    }
1086  }
1087  // We need to check the bitmaps again since there is a race where we mark something as live and
1088  // then clear the stack containing it.
1089  if (c_space != nullptr) {
1090    if (c_space->GetLiveBitmap()->Test(obj)) {
1091      return true;
1092    }
1093  } else {
1094    d_space = FindDiscontinuousSpaceFromObject(obj, true);
1095    if (d_space != nullptr && d_space->GetLiveBitmap()->Test(obj)) {
1096      return true;
1097    }
1098  }
1099  return false;
1100}
1101
1102void Heap::DumpSpaces(std::ostream& stream) {
1103  for (const auto& space : continuous_spaces_) {
1104    accounting::ContinuousSpaceBitmap* live_bitmap = space->GetLiveBitmap();
1105    accounting::ContinuousSpaceBitmap* mark_bitmap = space->GetMarkBitmap();
1106    stream << space << " " << *space << "\n";
1107    if (live_bitmap != nullptr) {
1108      stream << live_bitmap << " " << *live_bitmap << "\n";
1109    }
1110    if (mark_bitmap != nullptr) {
1111      stream << mark_bitmap << " " << *mark_bitmap << "\n";
1112    }
1113  }
1114  for (const auto& space : discontinuous_spaces_) {
1115    stream << space << " " << *space << "\n";
1116  }
1117}
1118
1119void Heap::VerifyObjectBody(mirror::Object* obj) {
1120  if (this == nullptr && verify_object_mode_ == kVerifyObjectModeDisabled) {
1121    return;
1122  }
1123  // Ignore early dawn of the universe verifications.
1124  if (UNLIKELY(static_cast<size_t>(num_bytes_allocated_.Load()) < 10 * KB)) {
1125    return;
1126  }
1127  CHECK(IsAligned<kObjectAlignment>(obj)) << "Object isn't aligned: " << obj;
1128  mirror::Class* c = obj->GetFieldObject<mirror::Class, kVerifyNone>(
1129      mirror::Object::ClassOffset(), false);
1130  CHECK(c != nullptr) << "Null class in object " << obj;
1131  CHECK(IsAligned<kObjectAlignment>(c)) << "Class " << c << " not aligned in object " << obj;
1132  CHECK(VerifyClassClass(c));
1133
1134  if (verify_object_mode_ > kVerifyObjectModeFast) {
1135    // Note: the bitmap tests below are racy since we don't hold the heap bitmap lock.
1136    if (!IsLiveObjectLocked(obj)) {
1137      DumpSpaces();
1138      LOG(FATAL) << "Object is dead: " << obj;
1139    }
1140  }
1141}
1142
1143void Heap::VerificationCallback(mirror::Object* obj, void* arg) {
1144  reinterpret_cast<Heap*>(arg)->VerifyObjectBody(obj);
1145}
1146
1147void Heap::VerifyHeap() {
1148  ReaderMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
1149  GetLiveBitmap()->Walk(Heap::VerificationCallback, this);
1150}
1151
1152void Heap::RecordFree(ssize_t freed_objects, ssize_t freed_bytes) {
1153  // Use signed comparison since freed bytes can be negative when background compaction foreground
1154  // transitions occurs. This is caused by the moving objects from a bump pointer space to a
1155  // free list backed space typically increasing memory footprint due to padding and binning.
1156  DCHECK_LE(freed_bytes, static_cast<ssize_t>(num_bytes_allocated_.Load()));
1157  DCHECK_GE(freed_objects, 0);
1158  num_bytes_allocated_.FetchAndSub(freed_bytes);
1159  if (Runtime::Current()->HasStatsEnabled()) {
1160    RuntimeStats* thread_stats = Thread::Current()->GetStats();
1161    thread_stats->freed_objects += freed_objects;
1162    thread_stats->freed_bytes += freed_bytes;
1163    // TODO: Do this concurrently.
1164    RuntimeStats* global_stats = Runtime::Current()->GetStats();
1165    global_stats->freed_objects += freed_objects;
1166    global_stats->freed_bytes += freed_bytes;
1167  }
1168}
1169
1170mirror::Object* Heap::AllocateInternalWithGc(Thread* self, AllocatorType allocator,
1171                                             size_t alloc_size, size_t* bytes_allocated,
1172                                             size_t* usable_size,
1173                                             mirror::Class** klass) {
1174  mirror::Object* ptr = nullptr;
1175  bool was_default_allocator = allocator == GetCurrentAllocator();
1176  DCHECK(klass != nullptr);
1177  SirtRef<mirror::Class> sirt_klass(self, *klass);
1178  // The allocation failed. If the GC is running, block until it completes, and then retry the
1179  // allocation.
1180  collector::GcType last_gc = WaitForGcToComplete(self);
1181  if (last_gc != collector::kGcTypeNone) {
1182    // If we were the default allocator but the allocator changed while we were suspended,
1183    // abort the allocation.
1184    if (was_default_allocator && allocator != GetCurrentAllocator()) {
1185      *klass = sirt_klass.get();
1186      return nullptr;
1187    }
1188    // A GC was in progress and we blocked, retry allocation now that memory has been freed.
1189    ptr = TryToAllocate<true, false>(self, allocator, alloc_size, bytes_allocated, usable_size);
1190  }
1191
1192  collector::GcType tried_type = next_gc_type_;
1193  if (ptr == nullptr) {
1194    const bool gc_ran =
1195        CollectGarbageInternal(tried_type, kGcCauseForAlloc, false) != collector::kGcTypeNone;
1196    if (was_default_allocator && allocator != GetCurrentAllocator()) {
1197      *klass = sirt_klass.get();
1198      return nullptr;
1199    }
1200    if (gc_ran) {
1201      ptr = TryToAllocate<true, false>(self, allocator, alloc_size, bytes_allocated, usable_size);
1202    }
1203  }
1204
1205  // Loop through our different Gc types and try to Gc until we get enough free memory.
1206  for (collector::GcType gc_type : gc_plan_) {
1207    if (ptr != nullptr) {
1208      break;
1209    }
1210    if (gc_type == tried_type) {
1211      continue;
1212    }
1213    // Attempt to run the collector, if we succeed, re-try the allocation.
1214    const bool gc_ran =
1215        CollectGarbageInternal(gc_type, kGcCauseForAlloc, false) != collector::kGcTypeNone;
1216    if (was_default_allocator && allocator != GetCurrentAllocator()) {
1217      *klass = sirt_klass.get();
1218      return nullptr;
1219    }
1220    if (gc_ran) {
1221      // Did we free sufficient memory for the allocation to succeed?
1222      ptr = TryToAllocate<true, false>(self, allocator, alloc_size, bytes_allocated, usable_size);
1223    }
1224  }
1225  // Allocations have failed after GCs;  this is an exceptional state.
1226  if (ptr == nullptr) {
1227    // Try harder, growing the heap if necessary.
1228    ptr = TryToAllocate<true, true>(self, allocator, alloc_size, bytes_allocated, usable_size);
1229  }
1230  if (ptr == nullptr) {
1231    // Most allocations should have succeeded by now, so the heap is really full, really fragmented,
1232    // or the requested size is really big. Do another GC, collecting SoftReferences this time. The
1233    // VM spec requires that all SoftReferences have been collected and cleared before throwing
1234    // OOME.
1235    VLOG(gc) << "Forcing collection of SoftReferences for " << PrettySize(alloc_size)
1236             << " allocation";
1237    // TODO: Run finalization, but this may cause more allocations to occur.
1238    // We don't need a WaitForGcToComplete here either.
1239    DCHECK(!gc_plan_.empty());
1240    CollectGarbageInternal(gc_plan_.back(), kGcCauseForAlloc, true);
1241    if (was_default_allocator && allocator != GetCurrentAllocator()) {
1242      *klass = sirt_klass.get();
1243      return nullptr;
1244    }
1245    ptr = TryToAllocate<true, true>(self, allocator, alloc_size, bytes_allocated, usable_size);
1246    if (ptr == nullptr) {
1247      ThrowOutOfMemoryError(self, alloc_size, false);
1248    }
1249  }
1250  *klass = sirt_klass.get();
1251  return ptr;
1252}
1253
1254void Heap::SetTargetHeapUtilization(float target) {
1255  DCHECK_GT(target, 0.0f);  // asserted in Java code
1256  DCHECK_LT(target, 1.0f);
1257  target_utilization_ = target;
1258}
1259
1260size_t Heap::GetObjectsAllocated() const {
1261  size_t total = 0;
1262  for (space::AllocSpace* space : alloc_spaces_) {
1263    total += space->GetObjectsAllocated();
1264  }
1265  return total;
1266}
1267
1268size_t Heap::GetObjectsAllocatedEver() const {
1269  return GetObjectsFreedEver() + GetObjectsAllocated();
1270}
1271
1272size_t Heap::GetBytesAllocatedEver() const {
1273  return GetBytesFreedEver() + GetBytesAllocated();
1274}
1275
1276class InstanceCounter {
1277 public:
1278  InstanceCounter(const std::vector<mirror::Class*>& classes, bool use_is_assignable_from, uint64_t* counts)
1279      SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
1280      : classes_(classes), use_is_assignable_from_(use_is_assignable_from), counts_(counts) {
1281  }
1282  static void Callback(mirror::Object* obj, void* arg)
1283      SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
1284    InstanceCounter* instance_counter = reinterpret_cast<InstanceCounter*>(arg);
1285    mirror::Class* instance_class = obj->GetClass();
1286    CHECK(instance_class != nullptr);
1287    for (size_t i = 0; i < instance_counter->classes_.size(); ++i) {
1288      if (instance_counter->use_is_assignable_from_) {
1289        if (instance_counter->classes_[i]->IsAssignableFrom(instance_class)) {
1290          ++instance_counter->counts_[i];
1291        }
1292      } else if (instance_class == instance_counter->classes_[i]) {
1293        ++instance_counter->counts_[i];
1294      }
1295    }
1296  }
1297
1298 private:
1299  const std::vector<mirror::Class*>& classes_;
1300  bool use_is_assignable_from_;
1301  uint64_t* const counts_;
1302  DISALLOW_COPY_AND_ASSIGN(InstanceCounter);
1303};
1304
1305void Heap::CountInstances(const std::vector<mirror::Class*>& classes, bool use_is_assignable_from,
1306                          uint64_t* counts) {
1307  // Can't do any GC in this function since this may move classes.
1308  Thread* self = Thread::Current();
1309  auto* old_cause = self->StartAssertNoThreadSuspension("CountInstances");
1310  InstanceCounter counter(classes, use_is_assignable_from, counts);
1311  WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
1312  VisitObjects(InstanceCounter::Callback, &counter);
1313  self->EndAssertNoThreadSuspension(old_cause);
1314}
1315
1316class InstanceCollector {
1317 public:
1318  InstanceCollector(mirror::Class* c, int32_t max_count, std::vector<mirror::Object*>& instances)
1319      SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
1320      : class_(c), max_count_(max_count), instances_(instances) {
1321  }
1322  static void Callback(mirror::Object* obj, void* arg)
1323      SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
1324    DCHECK(arg != nullptr);
1325    InstanceCollector* instance_collector = reinterpret_cast<InstanceCollector*>(arg);
1326    mirror::Class* instance_class = obj->GetClass();
1327    if (instance_class == instance_collector->class_) {
1328      if (instance_collector->max_count_ == 0 ||
1329          instance_collector->instances_.size() < instance_collector->max_count_) {
1330        instance_collector->instances_.push_back(obj);
1331      }
1332    }
1333  }
1334
1335 private:
1336  mirror::Class* class_;
1337  uint32_t max_count_;
1338  std::vector<mirror::Object*>& instances_;
1339  DISALLOW_COPY_AND_ASSIGN(InstanceCollector);
1340};
1341
1342void Heap::GetInstances(mirror::Class* c, int32_t max_count,
1343                        std::vector<mirror::Object*>& instances) {
1344  // Can't do any GC in this function since this may move classes.
1345  Thread* self = Thread::Current();
1346  auto* old_cause = self->StartAssertNoThreadSuspension("GetInstances");
1347  InstanceCollector collector(c, max_count, instances);
1348  WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
1349  VisitObjects(&InstanceCollector::Callback, &collector);
1350  self->EndAssertNoThreadSuspension(old_cause);
1351}
1352
1353class ReferringObjectsFinder {
1354 public:
1355  ReferringObjectsFinder(mirror::Object* object, int32_t max_count,
1356                         std::vector<mirror::Object*>& referring_objects)
1357      SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
1358      : object_(object), max_count_(max_count), referring_objects_(referring_objects) {
1359  }
1360
1361  static void Callback(mirror::Object* obj, void* arg)
1362      SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
1363    reinterpret_cast<ReferringObjectsFinder*>(arg)->operator()(obj);
1364  }
1365
1366  // For bitmap Visit.
1367  // TODO: Fix lock analysis to not use NO_THREAD_SAFETY_ANALYSIS, requires support for
1368  // annotalysis on visitors.
1369  void operator()(mirror::Object* o) const NO_THREAD_SAFETY_ANALYSIS {
1370    o->VisitReferences<true>(*this);
1371  }
1372
1373  // For Object::VisitReferences.
1374  void operator()(mirror::Object* obj, MemberOffset offset, bool /* is_static */) const
1375      SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1376    mirror::Object* ref = obj->GetFieldObject<mirror::Object>(offset, false);
1377    if (ref == object_ && (max_count_ == 0 || referring_objects_.size() < max_count_)) {
1378      referring_objects_.push_back(obj);
1379    }
1380  }
1381
1382 private:
1383  mirror::Object* object_;
1384  uint32_t max_count_;
1385  std::vector<mirror::Object*>& referring_objects_;
1386  DISALLOW_COPY_AND_ASSIGN(ReferringObjectsFinder);
1387};
1388
1389void Heap::GetReferringObjects(mirror::Object* o, int32_t max_count,
1390                               std::vector<mirror::Object*>& referring_objects) {
1391  // Can't do any GC in this function since this may move the object o.
1392  Thread* self = Thread::Current();
1393  auto* old_cause = self->StartAssertNoThreadSuspension("GetReferringObjects");
1394  ReferringObjectsFinder finder(o, max_count, referring_objects);
1395  WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
1396  VisitObjects(&ReferringObjectsFinder::Callback, &finder);
1397  self->EndAssertNoThreadSuspension(old_cause);
1398}
1399
1400void Heap::CollectGarbage(bool clear_soft_references) {
1401  // Even if we waited for a GC we still need to do another GC since weaks allocated during the
1402  // last GC will not have necessarily been cleared.
1403  CollectGarbageInternal(gc_plan_.back(), kGcCauseExplicit, clear_soft_references);
1404}
1405
1406void Heap::TransitionCollector(CollectorType collector_type) {
1407  if (collector_type == collector_type_) {
1408    return;
1409  }
1410  VLOG(heap) << "TransitionCollector: " << static_cast<int>(collector_type_)
1411             << " -> " << static_cast<int>(collector_type);
1412  uint64_t start_time = NanoTime();
1413  uint32_t before_allocated = num_bytes_allocated_.Load();
1414  ThreadList* tl = Runtime::Current()->GetThreadList();
1415  Thread* self = Thread::Current();
1416  ScopedThreadStateChange tsc(self, kWaitingPerformingGc);
1417  Locks::mutator_lock_->AssertNotHeld(self);
1418  const bool copying_transition =
1419      IsMovingGc(background_collector_type_) || IsMovingGc(foreground_collector_type_);
1420  // Busy wait until we can GC (StartGC can fail if we have a non-zero
1421  // compacting_gc_disable_count_, this should rarely occurs).
1422  for (;;) {
1423    {
1424      ScopedThreadStateChange tsc(self, kWaitingForGcToComplete);
1425      MutexLock mu(self, *gc_complete_lock_);
1426      // Ensure there is only one GC at a time.
1427      WaitForGcToCompleteLocked(self);
1428      // If someone else beat us to it and changed the collector before we could, exit.
1429      // This is safe to do before the suspend all since we set the collector_type_running_ before
1430      // we exit the loop. If another thread attempts to do the heap transition before we exit,
1431      // then it would get blocked on WaitForGcToCompleteLocked.
1432      if (collector_type == collector_type_) {
1433        return;
1434      }
1435      // GC can be disabled if someone has a used GetPrimitiveArrayCritical but not yet released.
1436      if (!copying_transition || disable_moving_gc_count_ == 0) {
1437        // TODO: Not hard code in semi-space collector?
1438        collector_type_running_ = copying_transition ? kCollectorTypeSS : collector_type;
1439        break;
1440      }
1441    }
1442    usleep(1000);
1443  }
1444  tl->SuspendAll();
1445  PreGcRosAllocVerification(&semi_space_collector_->GetTimings());
1446  switch (collector_type) {
1447    case kCollectorTypeSS:
1448      // Fall-through.
1449    case kCollectorTypeGSS: {
1450      if (!IsMovingGc(collector_type_)) {
1451        // We are transitioning from non moving GC -> moving GC, since we copied from the bump
1452        // pointer space last transition it will be protected.
1453        bump_pointer_space_->GetMemMap()->Protect(PROT_READ | PROT_WRITE);
1454        Compact(bump_pointer_space_, main_space_);
1455      }
1456      break;
1457    }
1458    case kCollectorTypeMS:
1459      // Fall through.
1460    case kCollectorTypeCMS: {
1461      if (IsMovingGc(collector_type_)) {
1462        // Compact to the main space from the bump pointer space, don't need to swap semispaces.
1463        main_space_->GetMemMap()->Protect(PROT_READ | PROT_WRITE);
1464        Compact(main_space_, bump_pointer_space_);
1465      }
1466      break;
1467    }
1468    default: {
1469      LOG(FATAL) << "Attempted to transition to invalid collector type "
1470                 << static_cast<size_t>(collector_type);
1471      break;
1472    }
1473  }
1474  ChangeCollector(collector_type);
1475  PostGcRosAllocVerification(&semi_space_collector_->GetTimings());
1476  tl->ResumeAll();
1477  // Can't call into java code with all threads suspended.
1478  EnqueueClearedReferences();
1479  uint64_t duration = NanoTime() - start_time;
1480  GrowForUtilization(semi_space_collector_);
1481  FinishGC(self, collector::kGcTypeFull);
1482  int32_t after_allocated = num_bytes_allocated_.Load();
1483  int32_t delta_allocated = before_allocated - after_allocated;
1484  LOG(INFO) << "Heap transition to " << process_state_ << " took "
1485      << PrettyDuration(duration) << " saved at least " << PrettySize(delta_allocated);
1486}
1487
1488void Heap::ChangeCollector(CollectorType collector_type) {
1489  // TODO: Only do this with all mutators suspended to avoid races.
1490  if (collector_type != collector_type_) {
1491    collector_type_ = collector_type;
1492    gc_plan_.clear();
1493    switch (collector_type_) {
1494      case kCollectorTypeCC:  // Fall-through.
1495      case kCollectorTypeSS:  // Fall-through.
1496      case kCollectorTypeGSS: {
1497        gc_plan_.push_back(collector::kGcTypeFull);
1498        if (use_tlab_) {
1499          ChangeAllocator(kAllocatorTypeTLAB);
1500        } else {
1501          ChangeAllocator(kAllocatorTypeBumpPointer);
1502        }
1503        break;
1504      }
1505      case kCollectorTypeMS: {
1506        gc_plan_.push_back(collector::kGcTypeSticky);
1507        gc_plan_.push_back(collector::kGcTypePartial);
1508        gc_plan_.push_back(collector::kGcTypeFull);
1509        ChangeAllocator(kUseRosAlloc ? kAllocatorTypeRosAlloc : kAllocatorTypeDlMalloc);
1510        break;
1511      }
1512      case kCollectorTypeCMS: {
1513        gc_plan_.push_back(collector::kGcTypeSticky);
1514        gc_plan_.push_back(collector::kGcTypePartial);
1515        gc_plan_.push_back(collector::kGcTypeFull);
1516        ChangeAllocator(kUseRosAlloc ? kAllocatorTypeRosAlloc : kAllocatorTypeDlMalloc);
1517        break;
1518      }
1519      default: {
1520        LOG(FATAL) << "Unimplemented";
1521      }
1522    }
1523    if (IsGcConcurrent()) {
1524      concurrent_start_bytes_ =
1525          std::max(max_allowed_footprint_, kMinConcurrentRemainingBytes) - kMinConcurrentRemainingBytes;
1526    } else {
1527      concurrent_start_bytes_ = std::numeric_limits<size_t>::max();
1528    }
1529  }
1530}
1531
1532// Special compacting collector which uses sub-optimal bin packing to reduce zygote space size.
1533class ZygoteCompactingCollector FINAL : public collector::SemiSpace {
1534 public:
1535  explicit ZygoteCompactingCollector(gc::Heap* heap) : SemiSpace(heap, false, "zygote collector"),
1536      bin_live_bitmap_(nullptr), bin_mark_bitmap_(nullptr) {
1537  }
1538
1539  void BuildBins(space::ContinuousSpace* space) {
1540    bin_live_bitmap_ = space->GetLiveBitmap();
1541    bin_mark_bitmap_ = space->GetMarkBitmap();
1542    BinContext context;
1543    context.prev_ = reinterpret_cast<uintptr_t>(space->Begin());
1544    context.collector_ = this;
1545    WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
1546    // Note: This requires traversing the space in increasing order of object addresses.
1547    bin_live_bitmap_->Walk(Callback, reinterpret_cast<void*>(&context));
1548    // Add the last bin which spans after the last object to the end of the space.
1549    AddBin(reinterpret_cast<uintptr_t>(space->End()) - context.prev_, context.prev_);
1550  }
1551
1552 private:
1553  struct BinContext {
1554    uintptr_t prev_;  // The end of the previous object.
1555    ZygoteCompactingCollector* collector_;
1556  };
1557  // Maps from bin sizes to locations.
1558  std::multimap<size_t, uintptr_t> bins_;
1559  // Live bitmap of the space which contains the bins.
1560  accounting::ContinuousSpaceBitmap* bin_live_bitmap_;
1561  // Mark bitmap of the space which contains the bins.
1562  accounting::ContinuousSpaceBitmap* bin_mark_bitmap_;
1563
1564  static void Callback(mirror::Object* obj, void* arg)
1565      SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1566    DCHECK(arg != nullptr);
1567    BinContext* context = reinterpret_cast<BinContext*>(arg);
1568    ZygoteCompactingCollector* collector = context->collector_;
1569    uintptr_t object_addr = reinterpret_cast<uintptr_t>(obj);
1570    size_t bin_size = object_addr - context->prev_;
1571    // Add the bin consisting of the end of the previous object to the start of the current object.
1572    collector->AddBin(bin_size, context->prev_);
1573    context->prev_ = object_addr + RoundUp(obj->SizeOf(), kObjectAlignment);
1574  }
1575
1576  void AddBin(size_t size, uintptr_t position) {
1577    if (size != 0) {
1578      bins_.insert(std::make_pair(size, position));
1579    }
1580  }
1581
1582  virtual bool ShouldSweepSpace(space::ContinuousSpace* space) const {
1583    // Don't sweep any spaces since we probably blasted the internal accounting of the free list
1584    // allocator.
1585    return false;
1586  }
1587
1588  virtual mirror::Object* MarkNonForwardedObject(mirror::Object* obj)
1589      EXCLUSIVE_LOCKS_REQUIRED(Locks::heap_bitmap_lock_, Locks::mutator_lock_) {
1590    size_t object_size = RoundUp(obj->SizeOf(), kObjectAlignment);
1591    mirror::Object* forward_address;
1592    // Find the smallest bin which we can move obj in.
1593    auto it = bins_.lower_bound(object_size);
1594    if (it == bins_.end()) {
1595      // No available space in the bins, place it in the target space instead (grows the zygote
1596      // space).
1597      size_t bytes_allocated;
1598      forward_address = to_space_->Alloc(self_, object_size, &bytes_allocated, nullptr);
1599      if (to_space_live_bitmap_ != nullptr) {
1600        to_space_live_bitmap_->Set(forward_address);
1601      } else {
1602        GetHeap()->GetNonMovingSpace()->GetLiveBitmap()->Set(forward_address);
1603        GetHeap()->GetNonMovingSpace()->GetMarkBitmap()->Set(forward_address);
1604      }
1605    } else {
1606      size_t size = it->first;
1607      uintptr_t pos = it->second;
1608      bins_.erase(it);  // Erase the old bin which we replace with the new smaller bin.
1609      forward_address = reinterpret_cast<mirror::Object*>(pos);
1610      // Set the live and mark bits so that sweeping system weaks works properly.
1611      bin_live_bitmap_->Set(forward_address);
1612      bin_mark_bitmap_->Set(forward_address);
1613      DCHECK_GE(size, object_size);
1614      AddBin(size - object_size, pos + object_size);  // Add a new bin with the remaining space.
1615    }
1616    // Copy the object over to its new location.
1617    memcpy(reinterpret_cast<void*>(forward_address), obj, object_size);
1618    if (kUseBakerOrBrooksReadBarrier) {
1619      obj->AssertReadBarrierPointer();
1620      if (kUseBrooksReadBarrier) {
1621        DCHECK_EQ(forward_address->GetReadBarrierPointer(), obj);
1622        forward_address->SetReadBarrierPointer(forward_address);
1623      }
1624      forward_address->AssertReadBarrierPointer();
1625    }
1626    return forward_address;
1627  }
1628};
1629
1630void Heap::UnBindBitmaps() {
1631  for (const auto& space : GetContinuousSpaces()) {
1632    if (space->IsContinuousMemMapAllocSpace()) {
1633      space::ContinuousMemMapAllocSpace* alloc_space = space->AsContinuousMemMapAllocSpace();
1634      if (alloc_space->HasBoundBitmaps()) {
1635        alloc_space->UnBindBitmaps();
1636      }
1637    }
1638  }
1639}
1640
1641void Heap::PreZygoteFork() {
1642  CollectGarbageInternal(collector::kGcTypeFull, kGcCauseBackground, false);
1643  static Mutex zygote_creation_lock_("zygote creation lock", kZygoteCreationLock);
1644  Thread* self = Thread::Current();
1645  MutexLock mu(self, zygote_creation_lock_);
1646  // Try to see if we have any Zygote spaces.
1647  if (have_zygote_space_) {
1648    return;
1649  }
1650  VLOG(heap) << "Starting PreZygoteFork";
1651  // Trim the pages at the end of the non moving space.
1652  non_moving_space_->Trim();
1653  // The end of the non-moving space may be protected, unprotect it so that we can copy the zygote
1654  // there.
1655  non_moving_space_->GetMemMap()->Protect(PROT_READ | PROT_WRITE);
1656  // Change the collector to the post zygote one.
1657  if (kCompactZygote) {
1658    DCHECK(semi_space_collector_ != nullptr);
1659    // Temporarily disable rosalloc verification because the zygote
1660    // compaction will mess up the rosalloc internal metadata.
1661    ScopedDisableRosAllocVerification disable_rosalloc_verif(this);
1662    ZygoteCompactingCollector zygote_collector(this);
1663    zygote_collector.BuildBins(non_moving_space_);
1664    // Create a new bump pointer space which we will compact into.
1665    space::BumpPointerSpace target_space("zygote bump space", non_moving_space_->End(),
1666                                         non_moving_space_->Limit());
1667    // Compact the bump pointer space to a new zygote bump pointer space.
1668    bool reset_main_space = false;
1669    if (IsMovingGc(collector_type_)) {
1670      zygote_collector.SetFromSpace(bump_pointer_space_);
1671    } else {
1672      CHECK(main_space_ != nullptr);
1673      // Copy from the main space.
1674      zygote_collector.SetFromSpace(main_space_);
1675      reset_main_space = true;
1676    }
1677    zygote_collector.SetToSpace(&target_space);
1678
1679    Runtime::Current()->GetThreadList()->SuspendAll();
1680    zygote_collector.Run(kGcCauseCollectorTransition, false);
1681    if (IsMovingGc(collector_type_)) {
1682      SwapSemiSpaces();
1683    }
1684    Runtime::Current()->GetThreadList()->ResumeAll();
1685
1686    if (reset_main_space) {
1687      main_space_->GetMemMap()->Protect(PROT_READ | PROT_WRITE);
1688      madvise(main_space_->Begin(), main_space_->Capacity(), MADV_DONTNEED);
1689      MemMap* mem_map = main_space_->ReleaseMemMap();
1690      RemoveSpace(main_space_);
1691      delete main_space_;
1692      main_space_ = nullptr;
1693      CreateMainMallocSpace(mem_map, kDefaultInitialSize, mem_map->Size(), mem_map->Size());
1694      AddSpace(main_space_);
1695    } else {
1696      bump_pointer_space_->GetMemMap()->Protect(PROT_READ | PROT_WRITE);
1697    }
1698    if (temp_space_ != nullptr) {
1699      CHECK(temp_space_->IsEmpty());
1700    }
1701    total_objects_freed_ever_ += semi_space_collector_->GetFreedObjects();
1702    total_bytes_freed_ever_ += semi_space_collector_->GetFreedBytes();
1703    // Update the end and write out image.
1704    non_moving_space_->SetEnd(target_space.End());
1705    non_moving_space_->SetLimit(target_space.Limit());
1706    VLOG(heap) << "Zygote space size " << non_moving_space_->Size() << " bytes";
1707  }
1708  ChangeCollector(foreground_collector_type_);
1709  // Save the old space so that we can remove it after we complete creating the zygote space.
1710  space::MallocSpace* old_alloc_space = non_moving_space_;
1711  // Turn the current alloc space into a zygote space and obtain the new alloc space composed of
1712  // the remaining available space.
1713  // Remove the old space before creating the zygote space since creating the zygote space sets
1714  // the old alloc space's bitmaps to nullptr.
1715  RemoveSpace(old_alloc_space);
1716  if (collector::SemiSpace::kUseRememberedSet) {
1717    // Sanity bound check.
1718    FindRememberedSetFromSpace(old_alloc_space)->AssertAllDirtyCardsAreWithinSpace();
1719    // Remove the remembered set for the now zygote space (the old
1720    // non-moving space). Note now that we have compacted objects into
1721    // the zygote space, the data in the remembered set is no longer
1722    // needed. The zygote space will instead have a mod-union table
1723    // from this point on.
1724    RemoveRememberedSet(old_alloc_space);
1725  }
1726  space::ZygoteSpace* zygote_space = old_alloc_space->CreateZygoteSpace("alloc space",
1727                                                                        low_memory_mode_,
1728                                                                        &non_moving_space_);
1729  delete old_alloc_space;
1730  CHECK(zygote_space != nullptr) << "Failed creating zygote space";
1731  AddSpace(zygote_space, false);
1732  non_moving_space_->SetFootprintLimit(non_moving_space_->Capacity());
1733  AddSpace(non_moving_space_);
1734  have_zygote_space_ = true;
1735  // Enable large object space allocations.
1736  large_object_threshold_ = kDefaultLargeObjectThreshold;
1737  // Create the zygote space mod union table.
1738  accounting::ModUnionTable* mod_union_table =
1739      new accounting::ModUnionTableCardCache("zygote space mod-union table", this, zygote_space);
1740  CHECK(mod_union_table != nullptr) << "Failed to create zygote space mod-union table";
1741  AddModUnionTable(mod_union_table);
1742  if (collector::SemiSpace::kUseRememberedSet) {
1743    // Add a new remembered set for the post-zygote non-moving space.
1744    accounting::RememberedSet* post_zygote_non_moving_space_rem_set =
1745        new accounting::RememberedSet("Post-zygote non-moving space remembered set", this,
1746                                      non_moving_space_);
1747    CHECK(post_zygote_non_moving_space_rem_set != nullptr)
1748        << "Failed to create post-zygote non-moving space remembered set";
1749    AddRememberedSet(post_zygote_non_moving_space_rem_set);
1750  }
1751}
1752
1753void Heap::FlushAllocStack() {
1754  MarkAllocStackAsLive(allocation_stack_.get());
1755  allocation_stack_->Reset();
1756}
1757
1758void Heap::MarkAllocStack(accounting::ContinuousSpaceBitmap* bitmap1,
1759                          accounting::ContinuousSpaceBitmap* bitmap2,
1760                          accounting::LargeObjectBitmap* large_objects,
1761                          accounting::ObjectStack* stack) {
1762  DCHECK(bitmap1 != nullptr);
1763  DCHECK(bitmap2 != nullptr);
1764  mirror::Object** limit = stack->End();
1765  for (mirror::Object** it = stack->Begin(); it != limit; ++it) {
1766    const mirror::Object* obj = *it;
1767    if (!kUseThreadLocalAllocationStack || obj != nullptr) {
1768      if (bitmap1->HasAddress(obj)) {
1769        bitmap1->Set(obj);
1770      } else if (bitmap2->HasAddress(obj)) {
1771        bitmap2->Set(obj);
1772      } else {
1773        large_objects->Set(obj);
1774      }
1775    }
1776  }
1777}
1778
1779void Heap::SwapSemiSpaces() {
1780  CHECK(bump_pointer_space_ != nullptr);
1781  CHECK(temp_space_ != nullptr);
1782  std::swap(bump_pointer_space_, temp_space_);
1783}
1784
1785void Heap::Compact(space::ContinuousMemMapAllocSpace* target_space,
1786                   space::ContinuousMemMapAllocSpace* source_space) {
1787  CHECK(kMovingCollector);
1788  CHECK_NE(target_space, source_space) << "In-place compaction currently unsupported";
1789  if (target_space != source_space) {
1790    semi_space_collector_->SetFromSpace(source_space);
1791    semi_space_collector_->SetToSpace(target_space);
1792    semi_space_collector_->Run(kGcCauseCollectorTransition, false);
1793  }
1794}
1795
1796collector::GcType Heap::CollectGarbageInternal(collector::GcType gc_type, GcCause gc_cause,
1797                                               bool clear_soft_references) {
1798  Thread* self = Thread::Current();
1799  Runtime* runtime = Runtime::Current();
1800  // If the heap can't run the GC, silently fail and return that no GC was run.
1801  switch (gc_type) {
1802    case collector::kGcTypePartial: {
1803      if (!have_zygote_space_) {
1804        return collector::kGcTypeNone;
1805      }
1806      break;
1807    }
1808    default: {
1809      // Other GC types don't have any special cases which makes them not runnable. The main case
1810      // here is full GC.
1811    }
1812  }
1813  ScopedThreadStateChange tsc(self, kWaitingPerformingGc);
1814  Locks::mutator_lock_->AssertNotHeld(self);
1815  if (self->IsHandlingStackOverflow()) {
1816    LOG(WARNING) << "Performing GC on a thread that is handling a stack overflow.";
1817  }
1818  bool compacting_gc;
1819  {
1820    gc_complete_lock_->AssertNotHeld(self);
1821    ScopedThreadStateChange tsc(self, kWaitingForGcToComplete);
1822    MutexLock mu(self, *gc_complete_lock_);
1823    // Ensure there is only one GC at a time.
1824    WaitForGcToCompleteLocked(self);
1825    compacting_gc = IsMovingGc(collector_type_);
1826    // GC can be disabled if someone has a used GetPrimitiveArrayCritical.
1827    if (compacting_gc && disable_moving_gc_count_ != 0) {
1828      LOG(WARNING) << "Skipping GC due to disable moving GC count " << disable_moving_gc_count_;
1829      return collector::kGcTypeNone;
1830    }
1831    collector_type_running_ = collector_type_;
1832  }
1833
1834  if (gc_cause == kGcCauseForAlloc && runtime->HasStatsEnabled()) {
1835    ++runtime->GetStats()->gc_for_alloc_count;
1836    ++self->GetStats()->gc_for_alloc_count;
1837  }
1838  uint64_t gc_start_time_ns = NanoTime();
1839  uint64_t gc_start_size = GetBytesAllocated();
1840  // Approximate allocation rate in bytes / second.
1841  uint64_t ms_delta = NsToMs(gc_start_time_ns - last_gc_time_ns_);
1842  // Back to back GCs can cause 0 ms of wait time in between GC invocations.
1843  if (LIKELY(ms_delta != 0)) {
1844    allocation_rate_ = ((gc_start_size - last_gc_size_) * 1000) / ms_delta;
1845    VLOG(heap) << "Allocation rate: " << PrettySize(allocation_rate_) << "/s";
1846  }
1847
1848  DCHECK_LT(gc_type, collector::kGcTypeMax);
1849  DCHECK_NE(gc_type, collector::kGcTypeNone);
1850
1851  collector::GarbageCollector* collector = nullptr;
1852  // TODO: Clean this up.
1853  if (compacting_gc) {
1854    DCHECK(current_allocator_ == kAllocatorTypeBumpPointer ||
1855           current_allocator_ == kAllocatorTypeTLAB);
1856    if (collector_type_ == kCollectorTypeSS || collector_type_ == kCollectorTypeGSS) {
1857      gc_type = semi_space_collector_->GetGcType();
1858      semi_space_collector_->SetFromSpace(bump_pointer_space_);
1859      semi_space_collector_->SetToSpace(temp_space_);
1860      collector = semi_space_collector_;
1861    } else if (collector_type_ == kCollectorTypeCC) {
1862      gc_type = concurrent_copying_collector_->GetGcType();
1863      collector = concurrent_copying_collector_;
1864    } else {
1865      LOG(FATAL) << "Unreachable - invalid collector type " << static_cast<size_t>(collector_type_);
1866    }
1867    temp_space_->GetMemMap()->Protect(PROT_READ | PROT_WRITE);
1868    CHECK(temp_space_->IsEmpty());
1869    gc_type = collector::kGcTypeFull;
1870  } else if (current_allocator_ == kAllocatorTypeRosAlloc ||
1871      current_allocator_ == kAllocatorTypeDlMalloc) {
1872    collector = FindCollectorByGcType(gc_type);
1873  } else {
1874    LOG(FATAL) << "Invalid current allocator " << current_allocator_;
1875  }
1876  CHECK(collector != nullptr)
1877      << "Could not find garbage collector with collector_type="
1878      << static_cast<size_t>(collector_type_) << " and gc_type=" << gc_type;
1879  ATRACE_BEGIN(StringPrintf("%s %s GC", PrettyCause(gc_cause), collector->GetName()).c_str());
1880  if (compacting_gc) {
1881    runtime->GetThreadList()->SuspendAll();
1882    collector->Run(gc_cause, clear_soft_references || runtime->IsZygote());
1883    SwapSemiSpaces();
1884    runtime->GetThreadList()->ResumeAll();
1885  } else {
1886    collector->Run(gc_cause, clear_soft_references || runtime->IsZygote());
1887  }
1888  total_objects_freed_ever_ += collector->GetFreedObjects();
1889  total_bytes_freed_ever_ += collector->GetFreedBytes();
1890  RequestHeapTrim();
1891  // Enqueue cleared references.
1892  EnqueueClearedReferences();
1893  // Grow the heap so that we know when to perform the next GC.
1894  GrowForUtilization(collector);
1895  if (CareAboutPauseTimes()) {
1896    const size_t duration = collector->GetDurationNs();
1897    std::vector<uint64_t> pauses = collector->GetPauseTimes();
1898    // GC for alloc pauses the allocating thread, so consider it as a pause.
1899    bool was_slow = duration > long_gc_log_threshold_ ||
1900        (gc_cause == kGcCauseForAlloc && duration > long_pause_log_threshold_);
1901    if (!was_slow) {
1902      for (uint64_t pause : pauses) {
1903        was_slow = was_slow || pause > long_pause_log_threshold_;
1904      }
1905    }
1906    if (was_slow) {
1907        const size_t percent_free = GetPercentFree();
1908        const size_t current_heap_size = GetBytesAllocated();
1909        const size_t total_memory = GetTotalMemory();
1910        std::ostringstream pause_string;
1911        for (size_t i = 0; i < pauses.size(); ++i) {
1912            pause_string << PrettyDuration((pauses[i] / 1000) * 1000)
1913                         << ((i != pauses.size() - 1) ? ", " : "");
1914        }
1915        LOG(INFO) << gc_cause << " " << collector->GetName()
1916                  << " GC freed "  <<  collector->GetFreedObjects() << "("
1917                  << PrettySize(collector->GetFreedBytes()) << ") AllocSpace objects, "
1918                  << collector->GetFreedLargeObjects() << "("
1919                  << PrettySize(collector->GetFreedLargeObjectBytes()) << ") LOS objects, "
1920                  << percent_free << "% free, " << PrettySize(current_heap_size) << "/"
1921                  << PrettySize(total_memory) << ", " << "paused " << pause_string.str()
1922                  << " total " << PrettyDuration((duration / 1000) * 1000);
1923        VLOG(heap) << ConstDumpable<TimingLogger>(collector->GetTimings());
1924    }
1925  }
1926  FinishGC(self, gc_type);
1927  ATRACE_END();
1928
1929  // Inform DDMS that a GC completed.
1930  Dbg::GcDidFinish();
1931  return gc_type;
1932}
1933
1934void Heap::FinishGC(Thread* self, collector::GcType gc_type) {
1935  MutexLock mu(self, *gc_complete_lock_);
1936  collector_type_running_ = kCollectorTypeNone;
1937  if (gc_type != collector::kGcTypeNone) {
1938    last_gc_type_ = gc_type;
1939  }
1940  // Wake anyone who may have been waiting for the GC to complete.
1941  gc_complete_cond_->Broadcast(self);
1942}
1943
1944static void RootMatchesObjectVisitor(mirror::Object** root, void* arg, uint32_t /*thread_id*/,
1945                                     RootType /*root_type*/) {
1946  mirror::Object* obj = reinterpret_cast<mirror::Object*>(arg);
1947  if (*root == obj) {
1948    LOG(INFO) << "Object " << obj << " is a root";
1949  }
1950}
1951
1952class ScanVisitor {
1953 public:
1954  void operator()(const mirror::Object* obj) const {
1955    LOG(ERROR) << "Would have rescanned object " << obj;
1956  }
1957};
1958
1959// Verify a reference from an object.
1960class VerifyReferenceVisitor {
1961 public:
1962  explicit VerifyReferenceVisitor(Heap* heap)
1963      SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_)
1964      : heap_(heap), failed_(false) {}
1965
1966  bool Failed() const {
1967    return failed_;
1968  }
1969
1970  void operator()(mirror::Class* klass, mirror::Reference* ref) const
1971      SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1972    this->operator()(ref, mirror::Reference::ReferentOffset(), false);
1973  }
1974
1975  void operator()(mirror::Object* obj, MemberOffset offset, bool /*is_static*/) const
1976      SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1977    this->operator()(obj, obj->GetFieldObject<mirror::Object>(offset, false), offset);
1978  }
1979
1980  // TODO: Fix the no thread safety analysis.
1981  void operator()(mirror::Object* obj, mirror::Object* ref, MemberOffset offset) const
1982      NO_THREAD_SAFETY_ANALYSIS {
1983    if (ref == nullptr || IsLive(ref)) {
1984      // Verify that the reference is live.
1985      return;
1986    }
1987    if (!failed_) {
1988      // Print message on only on first failure to prevent spam.
1989      LOG(ERROR) << "!!!!!!!!!!!!!!Heap corruption detected!!!!!!!!!!!!!!!!!!!";
1990      failed_ = true;
1991    }
1992    if (obj != nullptr) {
1993      accounting::CardTable* card_table = heap_->GetCardTable();
1994      accounting::ObjectStack* alloc_stack = heap_->allocation_stack_.get();
1995      accounting::ObjectStack* live_stack = heap_->live_stack_.get();
1996      byte* card_addr = card_table->CardFromAddr(obj);
1997      LOG(ERROR) << "Object " << obj << " references dead object " << ref << " at offset "
1998                 << offset << "\n card value = " << static_cast<int>(*card_addr);
1999      if (heap_->IsValidObjectAddress(obj->GetClass())) {
2000        LOG(ERROR) << "Obj type " << PrettyTypeOf(obj);
2001      } else {
2002        LOG(ERROR) << "Object " << obj << " class(" << obj->GetClass() << ") not a heap address";
2003      }
2004
2005      // Attmept to find the class inside of the recently freed objects.
2006      space::ContinuousSpace* ref_space = heap_->FindContinuousSpaceFromObject(ref, true);
2007      if (ref_space != nullptr && ref_space->IsMallocSpace()) {
2008        space::MallocSpace* space = ref_space->AsMallocSpace();
2009        mirror::Class* ref_class = space->FindRecentFreedObject(ref);
2010        if (ref_class != nullptr) {
2011          LOG(ERROR) << "Reference " << ref << " found as a recently freed object with class "
2012                     << PrettyClass(ref_class);
2013        } else {
2014          LOG(ERROR) << "Reference " << ref << " not found as a recently freed object";
2015        }
2016      }
2017
2018      if (ref->GetClass() != nullptr && heap_->IsValidObjectAddress(ref->GetClass()) &&
2019          ref->GetClass()->IsClass()) {
2020        LOG(ERROR) << "Ref type " << PrettyTypeOf(ref);
2021      } else {
2022        LOG(ERROR) << "Ref " << ref << " class(" << ref->GetClass()
2023                   << ") is not a valid heap address";
2024      }
2025
2026      card_table->CheckAddrIsInCardTable(reinterpret_cast<const byte*>(obj));
2027      void* cover_begin = card_table->AddrFromCard(card_addr);
2028      void* cover_end = reinterpret_cast<void*>(reinterpret_cast<size_t>(cover_begin) +
2029          accounting::CardTable::kCardSize);
2030      LOG(ERROR) << "Card " << reinterpret_cast<void*>(card_addr) << " covers " << cover_begin
2031          << "-" << cover_end;
2032      accounting::ContinuousSpaceBitmap* bitmap =
2033          heap_->GetLiveBitmap()->GetContinuousSpaceBitmap(obj);
2034
2035      if (bitmap == nullptr) {
2036        LOG(ERROR) << "Object " << obj << " has no bitmap";
2037        if (!VerifyClassClass(obj->GetClass())) {
2038          LOG(ERROR) << "Object " << obj << " failed class verification!";
2039        }
2040      } else {
2041        // Print out how the object is live.
2042        if (bitmap->Test(obj)) {
2043          LOG(ERROR) << "Object " << obj << " found in live bitmap";
2044        }
2045        if (alloc_stack->Contains(const_cast<mirror::Object*>(obj))) {
2046          LOG(ERROR) << "Object " << obj << " found in allocation stack";
2047        }
2048        if (live_stack->Contains(const_cast<mirror::Object*>(obj))) {
2049          LOG(ERROR) << "Object " << obj << " found in live stack";
2050        }
2051        if (alloc_stack->Contains(const_cast<mirror::Object*>(ref))) {
2052          LOG(ERROR) << "Ref " << ref << " found in allocation stack";
2053        }
2054        if (live_stack->Contains(const_cast<mirror::Object*>(ref))) {
2055          LOG(ERROR) << "Ref " << ref << " found in live stack";
2056        }
2057        // Attempt to see if the card table missed the reference.
2058        ScanVisitor scan_visitor;
2059        byte* byte_cover_begin = reinterpret_cast<byte*>(card_table->AddrFromCard(card_addr));
2060        card_table->Scan(bitmap, byte_cover_begin,
2061                         byte_cover_begin + accounting::CardTable::kCardSize, scan_visitor);
2062      }
2063
2064      // Search to see if any of the roots reference our object.
2065      void* arg = const_cast<void*>(reinterpret_cast<const void*>(obj));
2066      Runtime::Current()->VisitRoots(&RootMatchesObjectVisitor, arg);
2067
2068      // Search to see if any of the roots reference our reference.
2069      arg = const_cast<void*>(reinterpret_cast<const void*>(ref));
2070      Runtime::Current()->VisitRoots(&RootMatchesObjectVisitor, arg);
2071    } else {
2072      LOG(ERROR) << "Root " << ref << " is dead with type " << PrettyTypeOf(ref);
2073    }
2074  }
2075
2076  bool IsLive(mirror::Object* obj) const NO_THREAD_SAFETY_ANALYSIS {
2077    return heap_->IsLiveObjectLocked(obj, true, false, true);
2078  }
2079
2080  static void VerifyRoots(mirror::Object** root, void* arg, uint32_t /*thread_id*/,
2081                          RootType /*root_type*/) {
2082    VerifyReferenceVisitor* visitor = reinterpret_cast<VerifyReferenceVisitor*>(arg);
2083    (*visitor)(nullptr, *root, MemberOffset(0));
2084  }
2085
2086 private:
2087  Heap* const heap_;
2088  mutable bool failed_;
2089};
2090
2091// Verify all references within an object, for use with HeapBitmap::Visit.
2092class VerifyObjectVisitor {
2093 public:
2094  explicit VerifyObjectVisitor(Heap* heap) : heap_(heap), failed_(false) {}
2095
2096  void operator()(mirror::Object* obj) const
2097      SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
2098    // Note: we are verifying the references in obj but not obj itself, this is because obj must
2099    // be live or else how did we find it in the live bitmap?
2100    VerifyReferenceVisitor visitor(heap_);
2101    // The class doesn't count as a reference but we should verify it anyways.
2102    obj->VisitReferences<true>(visitor, visitor);
2103    failed_ = failed_ || visitor.Failed();
2104  }
2105
2106  static void VisitCallback(mirror::Object* obj, void* arg)
2107      SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
2108    VerifyObjectVisitor* visitor = reinterpret_cast<VerifyObjectVisitor*>(arg);
2109    visitor->operator()(obj);
2110  }
2111
2112  bool Failed() const {
2113    return failed_;
2114  }
2115
2116 private:
2117  Heap* const heap_;
2118  mutable bool failed_;
2119};
2120
2121// Must do this with mutators suspended since we are directly accessing the allocation stacks.
2122bool Heap::VerifyHeapReferences() {
2123  Thread* self = Thread::Current();
2124  Locks::mutator_lock_->AssertExclusiveHeld(self);
2125  // Lets sort our allocation stacks so that we can efficiently binary search them.
2126  allocation_stack_->Sort();
2127  live_stack_->Sort();
2128  // Since we sorted the allocation stack content, need to revoke all
2129  // thread-local allocation stacks.
2130  RevokeAllThreadLocalAllocationStacks(self);
2131  VerifyObjectVisitor visitor(this);
2132  // Verify objects in the allocation stack since these will be objects which were:
2133  // 1. Allocated prior to the GC (pre GC verification).
2134  // 2. Allocated during the GC (pre sweep GC verification).
2135  // We don't want to verify the objects in the live stack since they themselves may be
2136  // pointing to dead objects if they are not reachable.
2137  VisitObjects(VerifyObjectVisitor::VisitCallback, &visitor);
2138  // Verify the roots:
2139  Runtime::Current()->VisitRoots(VerifyReferenceVisitor::VerifyRoots, &visitor);
2140  if (visitor.Failed()) {
2141    // Dump mod-union tables.
2142    for (const auto& table_pair : mod_union_tables_) {
2143      accounting::ModUnionTable* mod_union_table = table_pair.second;
2144      mod_union_table->Dump(LOG(ERROR) << mod_union_table->GetName() << ": ");
2145    }
2146    // Dump remembered sets.
2147    for (const auto& table_pair : remembered_sets_) {
2148      accounting::RememberedSet* remembered_set = table_pair.second;
2149      remembered_set->Dump(LOG(ERROR) << remembered_set->GetName() << ": ");
2150    }
2151    DumpSpaces();
2152    return false;
2153  }
2154  return true;
2155}
2156
2157class VerifyReferenceCardVisitor {
2158 public:
2159  VerifyReferenceCardVisitor(Heap* heap, bool* failed)
2160      SHARED_LOCKS_REQUIRED(Locks::mutator_lock_,
2161                            Locks::heap_bitmap_lock_)
2162      : heap_(heap), failed_(failed) {
2163  }
2164
2165  // TODO: Fix lock analysis to not use NO_THREAD_SAFETY_ANALYSIS, requires support for
2166  // annotalysis on visitors.
2167  void operator()(mirror::Object* obj, MemberOffset offset, bool is_static) const
2168      NO_THREAD_SAFETY_ANALYSIS {
2169    mirror::Object* ref = obj->GetFieldObject<mirror::Object>(offset, false);
2170    // Filter out class references since changing an object's class does not mark the card as dirty.
2171    // Also handles large objects, since the only reference they hold is a class reference.
2172    if (ref != nullptr && !ref->IsClass()) {
2173      accounting::CardTable* card_table = heap_->GetCardTable();
2174      // If the object is not dirty and it is referencing something in the live stack other than
2175      // class, then it must be on a dirty card.
2176      if (!card_table->AddrIsInCardTable(obj)) {
2177        LOG(ERROR) << "Object " << obj << " is not in the address range of the card table";
2178        *failed_ = true;
2179      } else if (!card_table->IsDirty(obj)) {
2180        // TODO: Check mod-union tables.
2181        // Card should be either kCardDirty if it got re-dirtied after we aged it, or
2182        // kCardDirty - 1 if it didnt get touched since we aged it.
2183        accounting::ObjectStack* live_stack = heap_->live_stack_.get();
2184        if (live_stack->ContainsSorted(ref)) {
2185          if (live_stack->ContainsSorted(obj)) {
2186            LOG(ERROR) << "Object " << obj << " found in live stack";
2187          }
2188          if (heap_->GetLiveBitmap()->Test(obj)) {
2189            LOG(ERROR) << "Object " << obj << " found in live bitmap";
2190          }
2191          LOG(ERROR) << "Object " << obj << " " << PrettyTypeOf(obj)
2192                    << " references " << ref << " " << PrettyTypeOf(ref) << " in live stack";
2193
2194          // Print which field of the object is dead.
2195          if (!obj->IsObjectArray()) {
2196            mirror::Class* klass = is_static ? obj->AsClass() : obj->GetClass();
2197            CHECK(klass != NULL);
2198            mirror::ObjectArray<mirror::ArtField>* fields = is_static ? klass->GetSFields()
2199                                                                      : klass->GetIFields();
2200            CHECK(fields != NULL);
2201            for (int32_t i = 0; i < fields->GetLength(); ++i) {
2202              mirror::ArtField* cur = fields->Get(i);
2203              if (cur->GetOffset().Int32Value() == offset.Int32Value()) {
2204                LOG(ERROR) << (is_static ? "Static " : "") << "field in the live stack is "
2205                          << PrettyField(cur);
2206                break;
2207              }
2208            }
2209          } else {
2210            mirror::ObjectArray<mirror::Object>* object_array =
2211                obj->AsObjectArray<mirror::Object>();
2212            for (int32_t i = 0; i < object_array->GetLength(); ++i) {
2213              if (object_array->Get(i) == ref) {
2214                LOG(ERROR) << (is_static ? "Static " : "") << "obj[" << i << "] = ref";
2215              }
2216            }
2217          }
2218
2219          *failed_ = true;
2220        }
2221      }
2222    }
2223  }
2224
2225 private:
2226  Heap* const heap_;
2227  bool* const failed_;
2228};
2229
2230class VerifyLiveStackReferences {
2231 public:
2232  explicit VerifyLiveStackReferences(Heap* heap)
2233      : heap_(heap),
2234        failed_(false) {}
2235
2236  void operator()(mirror::Object* obj) const
2237      SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
2238    VerifyReferenceCardVisitor visitor(heap_, const_cast<bool*>(&failed_));
2239    obj->VisitReferences<true>(visitor);
2240  }
2241
2242  bool Failed() const {
2243    return failed_;
2244  }
2245
2246 private:
2247  Heap* const heap_;
2248  bool failed_;
2249};
2250
2251bool Heap::VerifyMissingCardMarks() {
2252  Thread* self = Thread::Current();
2253  Locks::mutator_lock_->AssertExclusiveHeld(self);
2254
2255  // We need to sort the live stack since we binary search it.
2256  live_stack_->Sort();
2257  // Since we sorted the allocation stack content, need to revoke all
2258  // thread-local allocation stacks.
2259  RevokeAllThreadLocalAllocationStacks(self);
2260  VerifyLiveStackReferences visitor(this);
2261  GetLiveBitmap()->Visit(visitor);
2262
2263  // We can verify objects in the live stack since none of these should reference dead objects.
2264  for (mirror::Object** it = live_stack_->Begin(); it != live_stack_->End(); ++it) {
2265    if (!kUseThreadLocalAllocationStack || *it != nullptr) {
2266      visitor(*it);
2267    }
2268  }
2269
2270  if (visitor.Failed()) {
2271    DumpSpaces();
2272    return false;
2273  }
2274  return true;
2275}
2276
2277void Heap::SwapStacks(Thread* self) {
2278  if (kUseThreadLocalAllocationStack) {
2279    live_stack_->AssertAllZero();
2280  }
2281  allocation_stack_.swap(live_stack_);
2282}
2283
2284void Heap::RevokeAllThreadLocalAllocationStacks(Thread* self) {
2285  // This must be called only during the pause.
2286  CHECK(Locks::mutator_lock_->IsExclusiveHeld(self));
2287  MutexLock mu(self, *Locks::runtime_shutdown_lock_);
2288  MutexLock mu2(self, *Locks::thread_list_lock_);
2289  std::list<Thread*> thread_list = Runtime::Current()->GetThreadList()->GetList();
2290  for (Thread* t : thread_list) {
2291    t->RevokeThreadLocalAllocationStack();
2292  }
2293}
2294
2295void Heap::AssertAllBumpPointerSpaceThreadLocalBuffersAreRevoked() {
2296  if (kIsDebugBuild) {
2297    if (bump_pointer_space_ != nullptr) {
2298      bump_pointer_space_->AssertAllThreadLocalBuffersAreRevoked();
2299    }
2300  }
2301}
2302
2303accounting::ModUnionTable* Heap::FindModUnionTableFromSpace(space::Space* space) {
2304  auto it = mod_union_tables_.find(space);
2305  if (it == mod_union_tables_.end()) {
2306    return nullptr;
2307  }
2308  return it->second;
2309}
2310
2311accounting::RememberedSet* Heap::FindRememberedSetFromSpace(space::Space* space) {
2312  auto it = remembered_sets_.find(space);
2313  if (it == remembered_sets_.end()) {
2314    return nullptr;
2315  }
2316  return it->second;
2317}
2318
2319void Heap::ProcessCards(TimingLogger& timings, bool use_rem_sets) {
2320  // Clear cards and keep track of cards cleared in the mod-union table.
2321  for (const auto& space : continuous_spaces_) {
2322    accounting::ModUnionTable* table = FindModUnionTableFromSpace(space);
2323    accounting::RememberedSet* rem_set = FindRememberedSetFromSpace(space);
2324    if (table != nullptr) {
2325      const char* name = space->IsZygoteSpace() ? "ZygoteModUnionClearCards" :
2326          "ImageModUnionClearCards";
2327      TimingLogger::ScopedSplit split(name, &timings);
2328      table->ClearCards();
2329    } else if (use_rem_sets && rem_set != nullptr) {
2330      DCHECK(collector::SemiSpace::kUseRememberedSet && collector_type_ == kCollectorTypeGSS)
2331          << static_cast<int>(collector_type_);
2332      TimingLogger::ScopedSplit split("AllocSpaceRemSetClearCards", &timings);
2333      rem_set->ClearCards();
2334    } else if (space->GetType() != space::kSpaceTypeBumpPointerSpace) {
2335      TimingLogger::ScopedSplit split("AllocSpaceClearCards", &timings);
2336      // No mod union table for the AllocSpace. Age the cards so that the GC knows that these cards
2337      // were dirty before the GC started.
2338      // TODO: Need to use atomic for the case where aged(cleaning thread) -> dirty(other thread)
2339      // -> clean(cleaning thread).
2340      // The races are we either end up with: Aged card, unaged card. Since we have the checkpoint
2341      // roots and then we scan / update mod union tables after. We will always scan either card.
2342      // If we end up with the non aged card, we scan it it in the pause.
2343      card_table_->ModifyCardsAtomic(space->Begin(), space->End(), AgeCardVisitor(), VoidFunctor());
2344    }
2345  }
2346}
2347
2348static void IdentityMarkHeapReferenceCallback(mirror::HeapReference<mirror::Object>*, void*) {
2349}
2350
2351void Heap::PreGcVerification(collector::GarbageCollector* gc) {
2352  ThreadList* thread_list = Runtime::Current()->GetThreadList();
2353  Thread* self = Thread::Current();
2354
2355  if (verify_pre_gc_heap_) {
2356    thread_list->SuspendAll();
2357    {
2358      ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
2359      if (!VerifyHeapReferences()) {
2360        LOG(FATAL) << "Pre " << gc->GetName() << " heap verification failed";
2361      }
2362    }
2363    thread_list->ResumeAll();
2364  }
2365
2366  // Check that all objects which reference things in the live stack are on dirty cards.
2367  if (verify_missing_card_marks_) {
2368    thread_list->SuspendAll();
2369    {
2370      ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
2371      SwapStacks(self);
2372      // Sort the live stack so that we can quickly binary search it later.
2373      if (!VerifyMissingCardMarks()) {
2374        LOG(FATAL) << "Pre " << gc->GetName() << " missing card mark verification failed";
2375      }
2376      SwapStacks(self);
2377    }
2378    thread_list->ResumeAll();
2379  }
2380
2381  if (verify_mod_union_table_) {
2382    thread_list->SuspendAll();
2383    ReaderMutexLock reader_lock(self, *Locks::heap_bitmap_lock_);
2384    for (const auto& table_pair : mod_union_tables_) {
2385      accounting::ModUnionTable* mod_union_table = table_pair.second;
2386      mod_union_table->UpdateAndMarkReferences(IdentityMarkHeapReferenceCallback, nullptr);
2387      mod_union_table->Verify();
2388    }
2389    thread_list->ResumeAll();
2390  }
2391}
2392
2393void Heap::PreSweepingGcVerification(collector::GarbageCollector* gc) {
2394  // Called before sweeping occurs since we want to make sure we are not going so reclaim any
2395  // reachable objects.
2396  if (verify_post_gc_heap_) {
2397    Thread* self = Thread::Current();
2398    CHECK_NE(self->GetState(), kRunnable);
2399    {
2400      WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
2401      // Swapping bound bitmaps does nothing.
2402      gc->SwapBitmaps();
2403      SwapSemiSpaces();
2404      if (!VerifyHeapReferences()) {
2405        LOG(FATAL) << "Pre sweeping " << gc->GetName() << " GC verification failed";
2406      }
2407      SwapSemiSpaces();
2408      gc->SwapBitmaps();
2409    }
2410  }
2411}
2412
2413void Heap::PostGcVerification(collector::GarbageCollector* gc) {
2414  if (verify_system_weaks_) {
2415    Thread* self = Thread::Current();
2416    ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
2417    collector::MarkSweep* mark_sweep = down_cast<collector::MarkSweep*>(gc);
2418    mark_sweep->VerifySystemWeaks();
2419  }
2420}
2421
2422void Heap::PreGcRosAllocVerification(TimingLogger* timings) {
2423  if (verify_pre_gc_rosalloc_) {
2424    TimingLogger::ScopedSplit split("PreGcRosAllocVerification", timings);
2425    for (const auto& space : continuous_spaces_) {
2426      if (space->IsRosAllocSpace()) {
2427        VLOG(heap) << "PreGcRosAllocVerification : " << space->GetName();
2428        space::RosAllocSpace* rosalloc_space = space->AsRosAllocSpace();
2429        rosalloc_space->Verify();
2430      }
2431    }
2432  }
2433}
2434
2435void Heap::PostGcRosAllocVerification(TimingLogger* timings) {
2436  if (verify_post_gc_rosalloc_) {
2437    TimingLogger::ScopedSplit split("PostGcRosAllocVerification", timings);
2438    for (const auto& space : continuous_spaces_) {
2439      if (space->IsRosAllocSpace()) {
2440        VLOG(heap) << "PostGcRosAllocVerification : " << space->GetName();
2441        space::RosAllocSpace* rosalloc_space = space->AsRosAllocSpace();
2442        rosalloc_space->Verify();
2443      }
2444    }
2445  }
2446}
2447
2448collector::GcType Heap::WaitForGcToComplete(Thread* self) {
2449  ScopedThreadStateChange tsc(self, kWaitingForGcToComplete);
2450  MutexLock mu(self, *gc_complete_lock_);
2451  return WaitForGcToCompleteLocked(self);
2452}
2453
2454collector::GcType Heap::WaitForGcToCompleteLocked(Thread* self) {
2455  collector::GcType last_gc_type = collector::kGcTypeNone;
2456  uint64_t wait_start = NanoTime();
2457  while (collector_type_running_ != kCollectorTypeNone) {
2458    ATRACE_BEGIN("GC: Wait For Completion");
2459    // We must wait, change thread state then sleep on gc_complete_cond_;
2460    gc_complete_cond_->Wait(self);
2461    last_gc_type = last_gc_type_;
2462    ATRACE_END();
2463  }
2464  uint64_t wait_time = NanoTime() - wait_start;
2465  total_wait_time_ += wait_time;
2466  if (wait_time > long_pause_log_threshold_) {
2467    LOG(INFO) << "WaitForGcToComplete blocked for " << PrettyDuration(wait_time);
2468  }
2469  return last_gc_type;
2470}
2471
2472void Heap::DumpForSigQuit(std::ostream& os) {
2473  os << "Heap: " << GetPercentFree() << "% free, " << PrettySize(GetBytesAllocated()) << "/"
2474     << PrettySize(GetTotalMemory()) << "; " << GetObjectsAllocated() << " objects\n";
2475  DumpGcPerformanceInfo(os);
2476}
2477
2478size_t Heap::GetPercentFree() {
2479  return static_cast<size_t>(100.0f * static_cast<float>(GetFreeMemory()) / GetTotalMemory());
2480}
2481
2482void Heap::SetIdealFootprint(size_t max_allowed_footprint) {
2483  if (max_allowed_footprint > GetMaxMemory()) {
2484    VLOG(gc) << "Clamp target GC heap from " << PrettySize(max_allowed_footprint) << " to "
2485             << PrettySize(GetMaxMemory());
2486    max_allowed_footprint = GetMaxMemory();
2487  }
2488  max_allowed_footprint_ = max_allowed_footprint;
2489}
2490
2491bool Heap::IsMovableObject(const mirror::Object* obj) const {
2492  if (kMovingCollector) {
2493    space::Space* space = FindContinuousSpaceFromObject(obj, true);
2494    if (space != nullptr) {
2495      // TODO: Check large object?
2496      return space->CanMoveObjects();
2497    }
2498  }
2499  return false;
2500}
2501
2502void Heap::UpdateMaxNativeFootprint() {
2503  size_t native_size = native_bytes_allocated_;
2504  // TODO: Tune the native heap utilization to be a value other than the java heap utilization.
2505  size_t target_size = native_size / GetTargetHeapUtilization();
2506  if (target_size > native_size + max_free_) {
2507    target_size = native_size + max_free_;
2508  } else if (target_size < native_size + min_free_) {
2509    target_size = native_size + min_free_;
2510  }
2511  native_footprint_gc_watermark_ = target_size;
2512  native_footprint_limit_ = 2 * target_size - native_size;
2513}
2514
2515collector::GarbageCollector* Heap::FindCollectorByGcType(collector::GcType gc_type) {
2516  for (const auto& collector : garbage_collectors_) {
2517    if (collector->GetCollectorType() == collector_type_ &&
2518        collector->GetGcType() == gc_type) {
2519      return collector;
2520    }
2521  }
2522  return nullptr;
2523}
2524
2525double Heap::HeapGrowthMultiplier() const {
2526  // If we don't care about pause times we are background, so return 1.0.
2527  if (!CareAboutPauseTimes() || IsLowMemoryMode()) {
2528    return 1.0;
2529  }
2530  return foreground_heap_growth_multiplier_;
2531}
2532
2533void Heap::GrowForUtilization(collector::GarbageCollector* collector_ran) {
2534  // We know what our utilization is at this moment.
2535  // This doesn't actually resize any memory. It just lets the heap grow more when necessary.
2536  const uint64_t bytes_allocated = GetBytesAllocated();
2537  last_gc_size_ = bytes_allocated;
2538  last_gc_time_ns_ = NanoTime();
2539  uint64_t target_size;
2540  collector::GcType gc_type = collector_ran->GetGcType();
2541  if (gc_type != collector::kGcTypeSticky) {
2542    // Grow the heap for non sticky GC.
2543    const float multiplier = HeapGrowthMultiplier();  // Use the multiplier to grow more for
2544    // foreground.
2545    intptr_t delta = bytes_allocated / GetTargetHeapUtilization() - bytes_allocated;
2546    CHECK_GE(delta, 0);
2547    target_size = bytes_allocated + delta * multiplier;
2548    target_size = std::min(target_size,
2549                           bytes_allocated + static_cast<uint64_t>(max_free_ * multiplier));
2550    target_size = std::max(target_size,
2551                           bytes_allocated + static_cast<uint64_t>(min_free_ * multiplier));
2552    native_need_to_run_finalization_ = true;
2553    next_gc_type_ = collector::kGcTypeSticky;
2554  } else {
2555    collector::GcType non_sticky_gc_type =
2556        have_zygote_space_ ? collector::kGcTypePartial : collector::kGcTypeFull;
2557    // Find what the next non sticky collector will be.
2558    collector::GarbageCollector* non_sticky_collector = FindCollectorByGcType(non_sticky_gc_type);
2559    // If the throughput of the current sticky GC >= throughput of the non sticky collector, then
2560    // do another sticky collection next.
2561    // We also check that the bytes allocated aren't over the footprint limit in order to prevent a
2562    // pathological case where dead objects which aren't reclaimed by sticky could get accumulated
2563    // if the sticky GC throughput always remained >= the full/partial throughput.
2564    if (collector_ran->GetEstimatedLastIterationThroughput() * kStickyGcThroughputAdjustment >=
2565        non_sticky_collector->GetEstimatedMeanThroughput() &&
2566        non_sticky_collector->GetIterations() > 0 &&
2567        bytes_allocated <= max_allowed_footprint_) {
2568      next_gc_type_ = collector::kGcTypeSticky;
2569    } else {
2570      next_gc_type_ = non_sticky_gc_type;
2571    }
2572    // If we have freed enough memory, shrink the heap back down.
2573    if (bytes_allocated + max_free_ < max_allowed_footprint_) {
2574      target_size = bytes_allocated + max_free_;
2575    } else {
2576      target_size = std::max(bytes_allocated, static_cast<uint64_t>(max_allowed_footprint_));
2577    }
2578  }
2579  if (!ignore_max_footprint_) {
2580    SetIdealFootprint(target_size);
2581    if (IsGcConcurrent()) {
2582      // Calculate when to perform the next ConcurrentGC.
2583      // Calculate the estimated GC duration.
2584      const double gc_duration_seconds = NsToMs(collector_ran->GetDurationNs()) / 1000.0;
2585      // Estimate how many remaining bytes we will have when we need to start the next GC.
2586      size_t remaining_bytes = allocation_rate_ * gc_duration_seconds;
2587      remaining_bytes = std::min(remaining_bytes, kMaxConcurrentRemainingBytes);
2588      remaining_bytes = std::max(remaining_bytes, kMinConcurrentRemainingBytes);
2589      if (UNLIKELY(remaining_bytes > max_allowed_footprint_)) {
2590        // A never going to happen situation that from the estimated allocation rate we will exceed
2591        // the applications entire footprint with the given estimated allocation rate. Schedule
2592        // another GC nearly straight away.
2593        remaining_bytes = kMinConcurrentRemainingBytes;
2594      }
2595      DCHECK_LE(remaining_bytes, max_allowed_footprint_);
2596      DCHECK_LE(max_allowed_footprint_, growth_limit_);
2597      // Start a concurrent GC when we get close to the estimated remaining bytes. When the
2598      // allocation rate is very high, remaining_bytes could tell us that we should start a GC
2599      // right away.
2600      concurrent_start_bytes_ = std::max(max_allowed_footprint_ - remaining_bytes,
2601                                         static_cast<size_t>(bytes_allocated));
2602    }
2603  }
2604}
2605
2606void Heap::ClearGrowthLimit() {
2607  growth_limit_ = capacity_;
2608  non_moving_space_->ClearGrowthLimit();
2609}
2610
2611void Heap::AddFinalizerReference(Thread* self, mirror::Object* object) {
2612  ScopedObjectAccess soa(self);
2613  ScopedLocalRef<jobject> arg(self->GetJniEnv(), soa.AddLocalReference<jobject>(object));
2614  jvalue args[1];
2615  args[0].l = arg.get();
2616  InvokeWithJValues(soa, nullptr, WellKnownClasses::java_lang_ref_FinalizerReference_add, args);
2617}
2618
2619void Heap::EnqueueClearedReferences() {
2620  Thread* self = Thread::Current();
2621  Locks::mutator_lock_->AssertNotHeld(self);
2622  if (!cleared_references_.IsEmpty()) {
2623    // When a runtime isn't started there are no reference queues to care about so ignore.
2624    if (LIKELY(Runtime::Current()->IsStarted())) {
2625      ScopedObjectAccess soa(self);
2626      ScopedLocalRef<jobject> arg(self->GetJniEnv(),
2627                                  soa.AddLocalReference<jobject>(cleared_references_.GetList()));
2628      jvalue args[1];
2629      args[0].l = arg.get();
2630      InvokeWithJValues(soa, nullptr, WellKnownClasses::java_lang_ref_ReferenceQueue_add, args);
2631    }
2632    cleared_references_.Clear();
2633  }
2634}
2635
2636void Heap::RequestConcurrentGC(Thread* self) {
2637  // Make sure that we can do a concurrent GC.
2638  Runtime* runtime = Runtime::Current();
2639  if (runtime == NULL || !runtime->IsFinishedStarting() || runtime->IsShuttingDown(self) ||
2640      self->IsHandlingStackOverflow()) {
2641    return;
2642  }
2643  // We already have a request pending, no reason to start more until we update
2644  // concurrent_start_bytes_.
2645  concurrent_start_bytes_ = std::numeric_limits<size_t>::max();
2646  JNIEnv* env = self->GetJniEnv();
2647  DCHECK(WellKnownClasses::java_lang_Daemons != nullptr);
2648  DCHECK(WellKnownClasses::java_lang_Daemons_requestGC != nullptr);
2649  env->CallStaticVoidMethod(WellKnownClasses::java_lang_Daemons,
2650                            WellKnownClasses::java_lang_Daemons_requestGC);
2651  CHECK(!env->ExceptionCheck());
2652}
2653
2654void Heap::ConcurrentGC(Thread* self) {
2655  if (Runtime::Current()->IsShuttingDown(self)) {
2656    return;
2657  }
2658  // Wait for any GCs currently running to finish.
2659  if (WaitForGcToComplete(self) == collector::kGcTypeNone) {
2660    // If the we can't run the GC type we wanted to run, find the next appropriate one and try that
2661    // instead. E.g. can't do partial, so do full instead.
2662    if (CollectGarbageInternal(next_gc_type_, kGcCauseBackground, false) ==
2663        collector::kGcTypeNone) {
2664      for (collector::GcType gc_type : gc_plan_) {
2665        // Attempt to run the collector, if we succeed, we are done.
2666        if (gc_type > next_gc_type_ &&
2667            CollectGarbageInternal(gc_type, kGcCauseBackground, false) != collector::kGcTypeNone) {
2668          break;
2669        }
2670      }
2671    }
2672  }
2673}
2674
2675void Heap::RequestCollectorTransition(CollectorType desired_collector_type, uint64_t delta_time) {
2676  Thread* self = Thread::Current();
2677  {
2678    MutexLock mu(self, *heap_trim_request_lock_);
2679    if (desired_collector_type_ == desired_collector_type) {
2680      return;
2681    }
2682    heap_transition_target_time_ = std::max(heap_transition_target_time_, NanoTime() + delta_time);
2683    desired_collector_type_ = desired_collector_type;
2684  }
2685  SignalHeapTrimDaemon(self);
2686}
2687
2688void Heap::RequestHeapTrim() {
2689  // Request a heap trim only if we do not currently care about pause times.
2690  if (CareAboutPauseTimes()) {
2691    return;
2692  }
2693  // GC completed and now we must decide whether to request a heap trim (advising pages back to the
2694  // kernel) or not. Issuing a request will also cause trimming of the libc heap. As a trim scans
2695  // a space it will hold its lock and can become a cause of jank.
2696  // Note, the large object space self trims and the Zygote space was trimmed and unchanging since
2697  // forking.
2698
2699  // We don't have a good measure of how worthwhile a trim might be. We can't use the live bitmap
2700  // because that only marks object heads, so a large array looks like lots of empty space. We
2701  // don't just call dlmalloc all the time, because the cost of an _attempted_ trim is proportional
2702  // to utilization (which is probably inversely proportional to how much benefit we can expect).
2703  // We could try mincore(2) but that's only a measure of how many pages we haven't given away,
2704  // not how much use we're making of those pages.
2705
2706  Thread* self = Thread::Current();
2707  Runtime* runtime = Runtime::Current();
2708  if (runtime == nullptr || !runtime->IsFinishedStarting() || runtime->IsShuttingDown(self)) {
2709    // Heap trimming isn't supported without a Java runtime or Daemons (such as at dex2oat time)
2710    // Also: we do not wish to start a heap trim if the runtime is shutting down (a racy check
2711    // as we don't hold the lock while requesting the trim).
2712    return;
2713  }
2714  {
2715    MutexLock mu(self, *heap_trim_request_lock_);
2716    if (last_trim_time_ + kHeapTrimWait >= NanoTime()) {
2717      // We have done a heap trim in the last kHeapTrimWait nanosecs, don't request another one
2718      // just yet.
2719      return;
2720    }
2721    heap_trim_request_pending_ = true;
2722  }
2723  // Notify the daemon thread which will actually do the heap trim.
2724  SignalHeapTrimDaemon(self);
2725}
2726
2727void Heap::SignalHeapTrimDaemon(Thread* self) {
2728  JNIEnv* env = self->GetJniEnv();
2729  DCHECK(WellKnownClasses::java_lang_Daemons != nullptr);
2730  DCHECK(WellKnownClasses::java_lang_Daemons_requestHeapTrim != nullptr);
2731  env->CallStaticVoidMethod(WellKnownClasses::java_lang_Daemons,
2732                            WellKnownClasses::java_lang_Daemons_requestHeapTrim);
2733  CHECK(!env->ExceptionCheck());
2734}
2735
2736void Heap::RevokeThreadLocalBuffers(Thread* thread) {
2737  if (rosalloc_space_ != nullptr) {
2738    rosalloc_space_->RevokeThreadLocalBuffers(thread);
2739  }
2740  if (bump_pointer_space_ != nullptr) {
2741    bump_pointer_space_->RevokeThreadLocalBuffers(thread);
2742  }
2743}
2744
2745void Heap::RevokeRosAllocThreadLocalBuffers(Thread* thread) {
2746  if (rosalloc_space_ != nullptr) {
2747    rosalloc_space_->RevokeThreadLocalBuffers(thread);
2748  }
2749}
2750
2751void Heap::RevokeAllThreadLocalBuffers() {
2752  if (rosalloc_space_ != nullptr) {
2753    rosalloc_space_->RevokeAllThreadLocalBuffers();
2754  }
2755  if (bump_pointer_space_ != nullptr) {
2756    bump_pointer_space_->RevokeAllThreadLocalBuffers();
2757  }
2758}
2759
2760bool Heap::IsGCRequestPending() const {
2761  return concurrent_start_bytes_ != std::numeric_limits<size_t>::max();
2762}
2763
2764void Heap::RunFinalization(JNIEnv* env) {
2765  // Can't do this in WellKnownClasses::Init since System is not properly set up at that point.
2766  if (WellKnownClasses::java_lang_System_runFinalization == nullptr) {
2767    CHECK(WellKnownClasses::java_lang_System != nullptr);
2768    WellKnownClasses::java_lang_System_runFinalization =
2769        CacheMethod(env, WellKnownClasses::java_lang_System, true, "runFinalization", "()V");
2770    CHECK(WellKnownClasses::java_lang_System_runFinalization != nullptr);
2771  }
2772  env->CallStaticVoidMethod(WellKnownClasses::java_lang_System,
2773                            WellKnownClasses::java_lang_System_runFinalization);
2774}
2775
2776void Heap::RegisterNativeAllocation(JNIEnv* env, int bytes) {
2777  Thread* self = ThreadForEnv(env);
2778  if (native_need_to_run_finalization_) {
2779    RunFinalization(env);
2780    UpdateMaxNativeFootprint();
2781    native_need_to_run_finalization_ = false;
2782  }
2783  // Total number of native bytes allocated.
2784  native_bytes_allocated_.FetchAndAdd(bytes);
2785  if (static_cast<size_t>(native_bytes_allocated_) > native_footprint_gc_watermark_) {
2786    collector::GcType gc_type = have_zygote_space_ ? collector::kGcTypePartial :
2787        collector::kGcTypeFull;
2788
2789    // The second watermark is higher than the gc watermark. If you hit this it means you are
2790    // allocating native objects faster than the GC can keep up with.
2791    if (static_cast<size_t>(native_bytes_allocated_) > native_footprint_limit_) {
2792      if (WaitForGcToComplete(self) != collector::kGcTypeNone) {
2793        // Just finished a GC, attempt to run finalizers.
2794        RunFinalization(env);
2795        CHECK(!env->ExceptionCheck());
2796      }
2797      // If we still are over the watermark, attempt a GC for alloc and run finalizers.
2798      if (static_cast<size_t>(native_bytes_allocated_) > native_footprint_limit_) {
2799        CollectGarbageInternal(gc_type, kGcCauseForNativeAlloc, false);
2800        RunFinalization(env);
2801        native_need_to_run_finalization_ = false;
2802        CHECK(!env->ExceptionCheck());
2803      }
2804      // We have just run finalizers, update the native watermark since it is very likely that
2805      // finalizers released native managed allocations.
2806      UpdateMaxNativeFootprint();
2807    } else if (!IsGCRequestPending()) {
2808      if (IsGcConcurrent()) {
2809        RequestConcurrentGC(self);
2810      } else {
2811        CollectGarbageInternal(gc_type, kGcCauseForNativeAlloc, false);
2812      }
2813    }
2814  }
2815}
2816
2817void Heap::RegisterNativeFree(JNIEnv* env, int bytes) {
2818  int expected_size, new_size;
2819  do {
2820    expected_size = native_bytes_allocated_.Load();
2821    new_size = expected_size - bytes;
2822    if (UNLIKELY(new_size < 0)) {
2823      ScopedObjectAccess soa(env);
2824      env->ThrowNew(WellKnownClasses::java_lang_RuntimeException,
2825                    StringPrintf("Attempted to free %d native bytes with only %d native bytes "
2826                                 "registered as allocated", bytes, expected_size).c_str());
2827      break;
2828    }
2829  } while (!native_bytes_allocated_.CompareAndSwap(expected_size, new_size));
2830}
2831
2832size_t Heap::GetTotalMemory() const {
2833  size_t ret = 0;
2834  for (const auto& space : continuous_spaces_) {
2835    // Currently don't include the image space.
2836    if (!space->IsImageSpace()) {
2837      ret += space->Size();
2838    }
2839  }
2840  for (const auto& space : discontinuous_spaces_) {
2841    if (space->IsLargeObjectSpace()) {
2842      ret += space->AsLargeObjectSpace()->GetBytesAllocated();
2843    }
2844  }
2845  return ret;
2846}
2847
2848void Heap::AddModUnionTable(accounting::ModUnionTable* mod_union_table) {
2849  DCHECK(mod_union_table != nullptr);
2850  mod_union_tables_.Put(mod_union_table->GetSpace(), mod_union_table);
2851}
2852
2853void Heap::CheckPreconditionsForAllocObject(mirror::Class* c, size_t byte_count) {
2854  CHECK(c == NULL || (c->IsClassClass() && byte_count >= sizeof(mirror::Class)) ||
2855        (c->IsVariableSize() || c->GetObjectSize() == byte_count) ||
2856        strlen(ClassHelper(c).GetDescriptor()) == 0);
2857  CHECK_GE(byte_count, sizeof(mirror::Object));
2858}
2859
2860void Heap::AddRememberedSet(accounting::RememberedSet* remembered_set) {
2861  CHECK(remembered_set != nullptr);
2862  space::Space* space = remembered_set->GetSpace();
2863  CHECK(space != nullptr);
2864  CHECK(remembered_sets_.find(space) == remembered_sets_.end());
2865  remembered_sets_.Put(space, remembered_set);
2866  CHECK(remembered_sets_.find(space) != remembered_sets_.end());
2867}
2868
2869void Heap::RemoveRememberedSet(space::Space* space) {
2870  CHECK(space != nullptr);
2871  auto it = remembered_sets_.find(space);
2872  CHECK(it != remembered_sets_.end());
2873  remembered_sets_.erase(it);
2874  CHECK(remembered_sets_.find(space) == remembered_sets_.end());
2875}
2876
2877void Heap::ClearMarkedObjects() {
2878  // Clear all of the spaces' mark bitmaps.
2879  for (const auto& space : GetContinuousSpaces()) {
2880    accounting::ContinuousSpaceBitmap* mark_bitmap = space->GetMarkBitmap();
2881    if (space->GetLiveBitmap() != mark_bitmap) {
2882      mark_bitmap->Clear();
2883    }
2884  }
2885  // Clear the marked objects in the discontinous space object sets.
2886  for (const auto& space : GetDiscontinuousSpaces()) {
2887    space->GetMarkBitmap()->Clear();
2888  }
2889}
2890
2891}  // namespace gc
2892}  // namespace art
2893