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