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