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