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