Home | History | Annotate | Download | only in gc
      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/stl_util.h"
     27 #include "common_throws.h"
     28 #include "cutils/sched_policy.h"
     29 #include "debugger.h"
     30 #include "gc/accounting/atomic_stack.h"
     31 #include "gc/accounting/card_table-inl.h"
     32 #include "gc/accounting/heap_bitmap-inl.h"
     33 #include "gc/accounting/mod_union_table-inl.h"
     34 #include "gc/accounting/space_bitmap-inl.h"
     35 #include "gc/collector/mark_sweep-inl.h"
     36 #include "gc/collector/partial_mark_sweep.h"
     37 #include "gc/collector/sticky_mark_sweep.h"
     38 #include "gc/space/dlmalloc_space-inl.h"
     39 #include "gc/space/image_space.h"
     40 #include "gc/space/large_object_space.h"
     41 #include "gc/space/space-inl.h"
     42 #include "image.h"
     43 #include "invoke_arg_array_builder.h"
     44 #include "mirror/art_field-inl.h"
     45 #include "mirror/class-inl.h"
     46 #include "mirror/object.h"
     47 #include "mirror/object-inl.h"
     48 #include "mirror/object_array-inl.h"
     49 #include "object_utils.h"
     50 #include "os.h"
     51 #include "ScopedLocalRef.h"
     52 #include "scoped_thread_state_change.h"
     53 #include "sirt_ref.h"
     54 #include "thread_list.h"
     55 #include "UniquePtr.h"
     56 #include "well_known_classes.h"
     57 
     58 namespace art {
     59 namespace gc {
     60 
     61 static constexpr bool kGCALotMode = false;
     62 static constexpr size_t kGcAlotInterval = KB;
     63 static constexpr bool kDumpGcPerformanceOnShutdown = false;
     64 // Minimum amount of remaining bytes before a concurrent GC is triggered.
     65 static constexpr size_t kMinConcurrentRemainingBytes = 128 * KB;
     66 // If true, measure the total allocation time.
     67 static constexpr bool kMeasureAllocationTime = false;
     68 
     69 Heap::Heap(size_t initial_size, size_t growth_limit, size_t min_free, size_t max_free,
     70            double target_utilization, size_t capacity, const std::string& original_image_file_name,
     71            bool concurrent_gc, size_t parallel_gc_threads, size_t conc_gc_threads,
     72            bool low_memory_mode, size_t long_pause_log_threshold, size_t long_gc_log_threshold,
     73            bool ignore_max_footprint)
     74     : alloc_space_(NULL),
     75       card_table_(NULL),
     76       concurrent_gc_(concurrent_gc),
     77       parallel_gc_threads_(parallel_gc_threads),
     78       conc_gc_threads_(conc_gc_threads),
     79       low_memory_mode_(low_memory_mode),
     80       long_pause_log_threshold_(long_pause_log_threshold),
     81       long_gc_log_threshold_(long_gc_log_threshold),
     82       ignore_max_footprint_(ignore_max_footprint),
     83       have_zygote_space_(false),
     84       soft_ref_queue_lock_(NULL),
     85       weak_ref_queue_lock_(NULL),
     86       finalizer_ref_queue_lock_(NULL),
     87       phantom_ref_queue_lock_(NULL),
     88       is_gc_running_(false),
     89       last_gc_type_(collector::kGcTypeNone),
     90       next_gc_type_(collector::kGcTypePartial),
     91       capacity_(capacity),
     92       growth_limit_(growth_limit),
     93       max_allowed_footprint_(initial_size),
     94       native_footprint_gc_watermark_(initial_size),
     95       native_footprint_limit_(2 * initial_size),
     96       activity_thread_class_(NULL),
     97       application_thread_class_(NULL),
     98       activity_thread_(NULL),
     99       application_thread_(NULL),
    100       last_process_state_id_(NULL),
    101       // Initially care about pauses in case we never get notified of process states, or if the JNI
    102       // code becomes broken.
    103       care_about_pause_times_(true),
    104       concurrent_start_bytes_(concurrent_gc_ ? initial_size - kMinConcurrentRemainingBytes
    105           :  std::numeric_limits<size_t>::max()),
    106       total_bytes_freed_ever_(0),
    107       total_objects_freed_ever_(0),
    108       large_object_threshold_(3 * kPageSize),
    109       num_bytes_allocated_(0),
    110       native_bytes_allocated_(0),
    111       gc_memory_overhead_(0),
    112       verify_missing_card_marks_(false),
    113       verify_system_weaks_(false),
    114       verify_pre_gc_heap_(false),
    115       verify_post_gc_heap_(false),
    116       verify_mod_union_table_(false),
    117       min_alloc_space_size_for_sticky_gc_(2 * MB),
    118       min_remaining_space_for_sticky_gc_(1 * MB),
    119       last_trim_time_ms_(0),
    120       allocation_rate_(0),
    121       /* For GC a lot mode, we limit the allocations stacks to be kGcAlotInterval allocations. This
    122        * causes a lot of GC since we do a GC for alloc whenever the stack is full. When heap
    123        * verification is enabled, we limit the size of allocation stacks to speed up their
    124        * searching.
    125        */
    126       max_allocation_stack_size_(kGCALotMode ? kGcAlotInterval
    127           : (kDesiredHeapVerification > kNoHeapVerification) ? KB : MB),
    128       reference_referent_offset_(0),
    129       reference_queue_offset_(0),
    130       reference_queueNext_offset_(0),
    131       reference_pendingNext_offset_(0),
    132       finalizer_reference_zombie_offset_(0),
    133       min_free_(min_free),
    134       max_free_(max_free),
    135       target_utilization_(target_utilization),
    136       total_wait_time_(0),
    137       total_allocation_time_(0),
    138       verify_object_mode_(kHeapVerificationNotPermitted),
    139       running_on_valgrind_(RUNNING_ON_VALGRIND) {
    140   if (VLOG_IS_ON(heap) || VLOG_IS_ON(startup)) {
    141     LOG(INFO) << "Heap() entering";
    142   }
    143 
    144   live_bitmap_.reset(new accounting::HeapBitmap(this));
    145   mark_bitmap_.reset(new accounting::HeapBitmap(this));
    146 
    147   // Requested begin for the alloc space, to follow the mapped image and oat files
    148   byte* requested_alloc_space_begin = NULL;
    149   std::string image_file_name(original_image_file_name);
    150   if (!image_file_name.empty()) {
    151     space::ImageSpace* image_space = space::ImageSpace::Create(image_file_name);
    152     CHECK(image_space != NULL) << "Failed to create space for " << image_file_name;
    153     AddContinuousSpace(image_space);
    154     // Oat files referenced by image files immediately follow them in memory, ensure alloc space
    155     // isn't going to get in the middle
    156     byte* oat_file_end_addr = image_space->GetImageHeader().GetOatFileEnd();
    157     CHECK_GT(oat_file_end_addr, image_space->End());
    158     if (oat_file_end_addr > requested_alloc_space_begin) {
    159       requested_alloc_space_begin =
    160           reinterpret_cast<byte*>(RoundUp(reinterpret_cast<uintptr_t>(oat_file_end_addr),
    161                                           kPageSize));
    162     }
    163   }
    164 
    165   alloc_space_ = space::DlMallocSpace::Create(Runtime::Current()->IsZygote() ? "zygote space" : "alloc space",
    166                                               initial_size,
    167                                               growth_limit, capacity,
    168                                               requested_alloc_space_begin);
    169   CHECK(alloc_space_ != NULL) << "Failed to create alloc space";
    170   alloc_space_->SetFootprintLimit(alloc_space_->Capacity());
    171   AddContinuousSpace(alloc_space_);
    172 
    173   // Allocate the large object space.
    174   const bool kUseFreeListSpaceForLOS = false;
    175   if (kUseFreeListSpaceForLOS) {
    176     large_object_space_ = space::FreeListSpace::Create("large object space", NULL, capacity);
    177   } else {
    178     large_object_space_ = space::LargeObjectMapSpace::Create("large object space");
    179   }
    180   CHECK(large_object_space_ != NULL) << "Failed to create large object space";
    181   AddDiscontinuousSpace(large_object_space_);
    182 
    183   // Compute heap capacity. Continuous spaces are sorted in order of Begin().
    184   byte* heap_begin = continuous_spaces_.front()->Begin();
    185   size_t heap_capacity = continuous_spaces_.back()->End() - continuous_spaces_.front()->Begin();
    186   if (continuous_spaces_.back()->IsDlMallocSpace()) {
    187     heap_capacity += continuous_spaces_.back()->AsDlMallocSpace()->NonGrowthLimitCapacity();
    188   }
    189 
    190   // Allocate the card table.
    191   card_table_.reset(accounting::CardTable::Create(heap_begin, heap_capacity));
    192   CHECK(card_table_.get() != NULL) << "Failed to create card table";
    193 
    194   image_mod_union_table_.reset(new accounting::ModUnionTableToZygoteAllocspace(this));
    195   CHECK(image_mod_union_table_.get() != NULL) << "Failed to create image mod-union table";
    196 
    197   zygote_mod_union_table_.reset(new accounting::ModUnionTableCardCache(this));
    198   CHECK(zygote_mod_union_table_.get() != NULL) << "Failed to create Zygote mod-union table";
    199 
    200   // TODO: Count objects in the image space here.
    201   num_bytes_allocated_ = 0;
    202 
    203   // Default mark stack size in bytes.
    204   static const size_t default_mark_stack_size = 64 * KB;
    205   mark_stack_.reset(accounting::ObjectStack::Create("mark stack", default_mark_stack_size));
    206   allocation_stack_.reset(accounting::ObjectStack::Create("allocation stack",
    207                                                           max_allocation_stack_size_));
    208   live_stack_.reset(accounting::ObjectStack::Create("live stack",
    209                                                     max_allocation_stack_size_));
    210 
    211   // It's still too early to take a lock because there are no threads yet, but we can create locks
    212   // now. We don't create it earlier to make it clear that you can't use locks during heap
    213   // initialization.
    214   gc_complete_lock_ = new Mutex("GC complete lock");
    215   gc_complete_cond_.reset(new ConditionVariable("GC complete condition variable",
    216                                                 *gc_complete_lock_));
    217 
    218   // Create the reference queue locks, this is required so for parallel object scanning in the GC.
    219   soft_ref_queue_lock_ = new Mutex("Soft reference queue lock");
    220   weak_ref_queue_lock_ = new Mutex("Weak reference queue lock");
    221   finalizer_ref_queue_lock_ = new Mutex("Finalizer reference queue lock");
    222   phantom_ref_queue_lock_ = new Mutex("Phantom reference queue lock");
    223 
    224   last_gc_time_ns_ = NanoTime();
    225   last_gc_size_ = GetBytesAllocated();
    226 
    227   if (ignore_max_footprint_) {
    228     SetIdealFootprint(std::numeric_limits<size_t>::max());
    229     concurrent_start_bytes_ = max_allowed_footprint_;
    230   }
    231 
    232   // Create our garbage collectors.
    233   for (size_t i = 0; i < 2; ++i) {
    234     const bool concurrent = i != 0;
    235     mark_sweep_collectors_.push_back(new collector::MarkSweep(this, concurrent));
    236     mark_sweep_collectors_.push_back(new collector::PartialMarkSweep(this, concurrent));
    237     mark_sweep_collectors_.push_back(new collector::StickyMarkSweep(this, concurrent));
    238   }
    239 
    240   CHECK_NE(max_allowed_footprint_, 0U);
    241   if (VLOG_IS_ON(heap) || VLOG_IS_ON(startup)) {
    242     LOG(INFO) << "Heap() exiting";
    243   }
    244 }
    245 
    246 void Heap::CreateThreadPool() {
    247   const size_t num_threads = std::max(parallel_gc_threads_, conc_gc_threads_);
    248   if (num_threads != 0) {
    249     thread_pool_.reset(new ThreadPool(num_threads));
    250   }
    251 }
    252 
    253 void Heap::DeleteThreadPool() {
    254   thread_pool_.reset(nullptr);
    255 }
    256 
    257 static bool ReadStaticInt(JNIEnvExt* env, jclass clz, const char* name, int* out_value) {
    258   CHECK(out_value != NULL);
    259   jfieldID field = env->GetStaticFieldID(clz, name, "I");
    260   if (field == NULL) {
    261     env->ExceptionClear();
    262     return false;
    263   }
    264   *out_value = env->GetStaticIntField(clz, field);
    265   return true;
    266 }
    267 
    268 void Heap::ListenForProcessStateChange() {
    269   VLOG(heap) << "Heap notified of process state change";
    270 
    271   Thread* self = Thread::Current();
    272   JNIEnvExt* env = self->GetJniEnv();
    273 
    274   if (!have_zygote_space_) {
    275     return;
    276   }
    277 
    278   if (activity_thread_class_ == NULL) {
    279     jclass clz = env->FindClass("android/app/ActivityThread");
    280     if (clz == NULL) {
    281       env->ExceptionClear();
    282       LOG(WARNING) << "Could not find activity thread class in process state change";
    283       return;
    284     }
    285     activity_thread_class_ = reinterpret_cast<jclass>(env->NewGlobalRef(clz));
    286   }
    287 
    288   if (activity_thread_class_ != NULL && activity_thread_ == NULL) {
    289     jmethodID current_activity_method = env->GetStaticMethodID(activity_thread_class_,
    290                                                                "currentActivityThread",
    291                                                                "()Landroid/app/ActivityThread;");
    292     if (current_activity_method == NULL) {
    293       env->ExceptionClear();
    294       LOG(WARNING) << "Could not get method for currentActivityThread";
    295       return;
    296     }
    297 
    298     jobject obj = env->CallStaticObjectMethod(activity_thread_class_, current_activity_method);
    299     if (obj == NULL) {
    300       env->ExceptionClear();
    301       LOG(WARNING) << "Could not get current activity";
    302       return;
    303     }
    304     activity_thread_ = env->NewGlobalRef(obj);
    305   }
    306 
    307   if (process_state_cares_about_pause_time_.empty()) {
    308     // Just attempt to do this the first time.
    309     jclass clz = env->FindClass("android/app/ActivityManager");
    310     if (clz == NULL) {
    311       LOG(WARNING) << "Activity manager class is null";
    312       return;
    313     }
    314     ScopedLocalRef<jclass> activity_manager(env, clz);
    315     std::vector<const char*> care_about_pauses;
    316     care_about_pauses.push_back("PROCESS_STATE_TOP");
    317     care_about_pauses.push_back("PROCESS_STATE_IMPORTANT_BACKGROUND");
    318     // Attempt to read the constants and classify them as whether or not we care about pause times.
    319     for (size_t i = 0; i < care_about_pauses.size(); ++i) {
    320       int process_state = 0;
    321       if (ReadStaticInt(env, activity_manager.get(), care_about_pauses[i], &process_state)) {
    322         process_state_cares_about_pause_time_.insert(process_state);
    323         VLOG(heap) << "Adding process state " << process_state
    324                    << " to set of states which care about pause time";
    325       }
    326     }
    327   }
    328 
    329   if (application_thread_class_ == NULL) {
    330     jclass clz = env->FindClass("android/app/ActivityThread$ApplicationThread");
    331     if (clz == NULL) {
    332       env->ExceptionClear();
    333       LOG(WARNING) << "Could not get application thread class";
    334       return;
    335     }
    336     application_thread_class_ = reinterpret_cast<jclass>(env->NewGlobalRef(clz));
    337     last_process_state_id_ = env->GetFieldID(application_thread_class_, "mLastProcessState", "I");
    338     if (last_process_state_id_ == NULL) {
    339       env->ExceptionClear();
    340       LOG(WARNING) << "Could not get last process state member";
    341       return;
    342     }
    343   }
    344 
    345   if (application_thread_class_ != NULL && application_thread_ == NULL) {
    346     jmethodID get_application_thread =
    347         env->GetMethodID(activity_thread_class_, "getApplicationThread",
    348                          "()Landroid/app/ActivityThread$ApplicationThread;");
    349     if (get_application_thread == NULL) {
    350       LOG(WARNING) << "Could not get method ID for get application thread";
    351       return;
    352     }
    353 
    354     jobject obj = env->CallObjectMethod(activity_thread_, get_application_thread);
    355     if (obj == NULL) {
    356       LOG(WARNING) << "Could not get application thread";
    357       return;
    358     }
    359 
    360     application_thread_ = env->NewGlobalRef(obj);
    361   }
    362 
    363   if (application_thread_ != NULL && last_process_state_id_ != NULL) {
    364     int process_state = env->GetIntField(application_thread_, last_process_state_id_);
    365     env->ExceptionClear();
    366 
    367     care_about_pause_times_ = process_state_cares_about_pause_time_.find(process_state) !=
    368         process_state_cares_about_pause_time_.end();
    369 
    370     VLOG(heap) << "New process state " << process_state
    371                << " care about pauses " << care_about_pause_times_;
    372   }
    373 }
    374 
    375 void Heap::AddContinuousSpace(space::ContinuousSpace* space) {
    376   WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
    377   DCHECK(space != NULL);
    378   DCHECK(space->GetLiveBitmap() != NULL);
    379   live_bitmap_->AddContinuousSpaceBitmap(space->GetLiveBitmap());
    380   DCHECK(space->GetMarkBitmap() != NULL);
    381   mark_bitmap_->AddContinuousSpaceBitmap(space->GetMarkBitmap());
    382   continuous_spaces_.push_back(space);
    383   if (space->IsDlMallocSpace() && !space->IsLargeObjectSpace()) {
    384     alloc_space_ = space->AsDlMallocSpace();
    385   }
    386 
    387   // Ensure that spaces remain sorted in increasing order of start address (required for CMS finger)
    388   std::sort(continuous_spaces_.begin(), continuous_spaces_.end(),
    389             [](const space::ContinuousSpace* a, const space::ContinuousSpace* b) {
    390               return a->Begin() < b->Begin();
    391             });
    392 
    393   // Ensure that ImageSpaces < ZygoteSpaces < AllocSpaces so that we can do address based checks to
    394   // avoid redundant marking.
    395   bool seen_zygote = false, seen_alloc = false;
    396   for (const auto& space : continuous_spaces_) {
    397     if (space->IsImageSpace()) {
    398       DCHECK(!seen_zygote);
    399       DCHECK(!seen_alloc);
    400     } else if (space->IsZygoteSpace()) {
    401       DCHECK(!seen_alloc);
    402       seen_zygote = true;
    403     } else if (space->IsDlMallocSpace()) {
    404       seen_alloc = true;
    405     }
    406   }
    407 }
    408 
    409 void Heap::RegisterGCAllocation(size_t bytes) {
    410   if (this != NULL) {
    411     gc_memory_overhead_.fetch_add(bytes);
    412   }
    413 }
    414 
    415 void Heap::RegisterGCDeAllocation(size_t bytes) {
    416   if (this != NULL) {
    417     gc_memory_overhead_.fetch_sub(bytes);
    418   }
    419 }
    420 
    421 void Heap::AddDiscontinuousSpace(space::DiscontinuousSpace* space) {
    422   WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
    423   DCHECK(space != NULL);
    424   DCHECK(space->GetLiveObjects() != NULL);
    425   live_bitmap_->AddDiscontinuousObjectSet(space->GetLiveObjects());
    426   DCHECK(space->GetMarkObjects() != NULL);
    427   mark_bitmap_->AddDiscontinuousObjectSet(space->GetMarkObjects());
    428   discontinuous_spaces_.push_back(space);
    429 }
    430 
    431 void Heap::DumpGcPerformanceInfo(std::ostream& os) {
    432   // Dump cumulative timings.
    433   os << "Dumping cumulative Gc timings\n";
    434   uint64_t total_duration = 0;
    435 
    436   // Dump cumulative loggers for each GC type.
    437   uint64_t total_paused_time = 0;
    438   for (const auto& collector : mark_sweep_collectors_) {
    439     CumulativeLogger& logger = collector->GetCumulativeTimings();
    440     if (logger.GetTotalNs() != 0) {
    441       os << Dumpable<CumulativeLogger>(logger);
    442       const uint64_t total_ns = logger.GetTotalNs();
    443       const uint64_t total_pause_ns = collector->GetTotalPausedTimeNs();
    444       double seconds = NsToMs(logger.GetTotalNs()) / 1000.0;
    445       const uint64_t freed_bytes = collector->GetTotalFreedBytes();
    446       const uint64_t freed_objects = collector->GetTotalFreedObjects();
    447       os << collector->GetName() << " total time: " << PrettyDuration(total_ns) << "\n"
    448          << collector->GetName() << " paused time: " << PrettyDuration(total_pause_ns) << "\n"
    449          << collector->GetName() << " freed: " << freed_objects
    450          << " objects with total size " << PrettySize(freed_bytes) << "\n"
    451          << collector->GetName() << " throughput: " << freed_objects / seconds << "/s / "
    452          << PrettySize(freed_bytes / seconds) << "/s\n";
    453       total_duration += total_ns;
    454       total_paused_time += total_pause_ns;
    455     }
    456   }
    457   uint64_t allocation_time = static_cast<uint64_t>(total_allocation_time_) * kTimeAdjust;
    458   size_t total_objects_allocated = GetObjectsAllocatedEver();
    459   size_t total_bytes_allocated = GetBytesAllocatedEver();
    460   if (total_duration != 0) {
    461     const double total_seconds = static_cast<double>(total_duration / 1000) / 1000000.0;
    462     os << "Total time spent in GC: " << PrettyDuration(total_duration) << "\n";
    463     os << "Mean GC size throughput: "
    464        << PrettySize(GetBytesFreedEver() / total_seconds) << "/s\n";
    465     os << "Mean GC object throughput: "
    466        << (GetObjectsFreedEver() / total_seconds) << " objects/s\n";
    467   }
    468   os << "Total number of allocations: " << total_objects_allocated << "\n";
    469   os << "Total bytes allocated " << PrettySize(total_bytes_allocated) << "\n";
    470   if (kMeasureAllocationTime) {
    471     os << "Total time spent allocating: " << PrettyDuration(allocation_time) << "\n";
    472     os << "Mean allocation time: " << PrettyDuration(allocation_time / total_objects_allocated)
    473        << "\n";
    474   }
    475   os << "Total mutator paused time: " << PrettyDuration(total_paused_time) << "\n";
    476   os << "Total time waiting for GC to complete: " << PrettyDuration(total_wait_time_) << "\n";
    477   os << "Approximate GC data structures memory overhead: " << gc_memory_overhead_;
    478 }
    479 
    480 Heap::~Heap() {
    481   if (kDumpGcPerformanceOnShutdown) {
    482     DumpGcPerformanceInfo(LOG(INFO));
    483   }
    484 
    485   STLDeleteElements(&mark_sweep_collectors_);
    486 
    487   // If we don't reset then the mark stack complains in it's destructor.
    488   allocation_stack_->Reset();
    489   live_stack_->Reset();
    490 
    491   VLOG(heap) << "~Heap()";
    492   // We can't take the heap lock here because there might be a daemon thread suspended with the
    493   // heap lock held. We know though that no non-daemon threads are executing, and we know that
    494   // all daemon threads are suspended, and we also know that the threads list have been deleted, so
    495   // those threads can't resume. We're the only running thread, and we can do whatever we like...
    496   STLDeleteElements(&continuous_spaces_);
    497   STLDeleteElements(&discontinuous_spaces_);
    498   delete gc_complete_lock_;
    499   delete soft_ref_queue_lock_;
    500   delete weak_ref_queue_lock_;
    501   delete finalizer_ref_queue_lock_;
    502   delete phantom_ref_queue_lock_;
    503 }
    504 
    505 space::ContinuousSpace* Heap::FindContinuousSpaceFromObject(const mirror::Object* obj,
    506                                                             bool fail_ok) const {
    507   for (const auto& space : continuous_spaces_) {
    508     if (space->Contains(obj)) {
    509       return space;
    510     }
    511   }
    512   if (!fail_ok) {
    513     LOG(FATAL) << "object " << reinterpret_cast<const void*>(obj) << " not inside any spaces!";
    514   }
    515   return NULL;
    516 }
    517 
    518 space::DiscontinuousSpace* Heap::FindDiscontinuousSpaceFromObject(const mirror::Object* obj,
    519                                                                   bool fail_ok) const {
    520   for (const auto& space : discontinuous_spaces_) {
    521     if (space->Contains(obj)) {
    522       return space;
    523     }
    524   }
    525   if (!fail_ok) {
    526     LOG(FATAL) << "object " << reinterpret_cast<const void*>(obj) << " not inside any spaces!";
    527   }
    528   return NULL;
    529 }
    530 
    531 space::Space* Heap::FindSpaceFromObject(const mirror::Object* obj, bool fail_ok) const {
    532   space::Space* result = FindContinuousSpaceFromObject(obj, true);
    533   if (result != NULL) {
    534     return result;
    535   }
    536   return FindDiscontinuousSpaceFromObject(obj, true);
    537 }
    538 
    539 space::ImageSpace* Heap::GetImageSpace() const {
    540   for (const auto& space : continuous_spaces_) {
    541     if (space->IsImageSpace()) {
    542       return space->AsImageSpace();
    543     }
    544   }
    545   return NULL;
    546 }
    547 
    548 static void MSpaceChunkCallback(void* start, void* end, size_t used_bytes, void* arg) {
    549   size_t chunk_size = reinterpret_cast<uint8_t*>(end) - reinterpret_cast<uint8_t*>(start);
    550   if (used_bytes < chunk_size) {
    551     size_t chunk_free_bytes = chunk_size - used_bytes;
    552     size_t& max_contiguous_allocation = *reinterpret_cast<size_t*>(arg);
    553     max_contiguous_allocation = std::max(max_contiguous_allocation, chunk_free_bytes);
    554   }
    555 }
    556 
    557 mirror::Object* Heap::AllocObject(Thread* self, mirror::Class* c, size_t byte_count) {
    558   DCHECK(c == NULL || (c->IsClassClass() && byte_count >= sizeof(mirror::Class)) ||
    559          (c->IsVariableSize() || c->GetObjectSize() == byte_count) ||
    560          strlen(ClassHelper(c).GetDescriptor()) == 0);
    561   DCHECK_GE(byte_count, sizeof(mirror::Object));
    562 
    563   mirror::Object* obj = NULL;
    564   size_t bytes_allocated = 0;
    565   uint64_t allocation_start = 0;
    566   if (UNLIKELY(kMeasureAllocationTime)) {
    567     allocation_start = NanoTime() / kTimeAdjust;
    568   }
    569 
    570   // We need to have a zygote space or else our newly allocated large object can end up in the
    571   // Zygote resulting in it being prematurely freed.
    572   // We can only do this for primitive objects since large objects will not be within the card table
    573   // range. This also means that we rely on SetClass not dirtying the object's card.
    574   bool large_object_allocation =
    575       byte_count >= large_object_threshold_ && have_zygote_space_ && c->IsPrimitiveArray();
    576   if (UNLIKELY(large_object_allocation)) {
    577     obj = Allocate(self, large_object_space_, byte_count, &bytes_allocated);
    578     // Make sure that our large object didn't get placed anywhere within the space interval or else
    579     // it breaks the immune range.
    580     DCHECK(obj == NULL ||
    581            reinterpret_cast<byte*>(obj) < continuous_spaces_.front()->Begin() ||
    582            reinterpret_cast<byte*>(obj) >= continuous_spaces_.back()->End());
    583   } else {
    584     obj = Allocate(self, alloc_space_, byte_count, &bytes_allocated);
    585     // Ensure that we did not allocate into a zygote space.
    586     DCHECK(obj == NULL || !have_zygote_space_ || !FindSpaceFromObject(obj, false)->IsZygoteSpace());
    587   }
    588 
    589   if (LIKELY(obj != NULL)) {
    590     obj->SetClass(c);
    591 
    592     // Record allocation after since we want to use the atomic add for the atomic fence to guard
    593     // the SetClass since we do not want the class to appear NULL in another thread.
    594     RecordAllocation(bytes_allocated, obj);
    595 
    596     if (Dbg::IsAllocTrackingEnabled()) {
    597       Dbg::RecordAllocation(c, byte_count);
    598     }
    599     if (UNLIKELY(static_cast<size_t>(num_bytes_allocated_) >= concurrent_start_bytes_)) {
    600       // The SirtRef is necessary since the calls in RequestConcurrentGC are a safepoint.
    601       SirtRef<mirror::Object> ref(self, obj);
    602       RequestConcurrentGC(self);
    603     }
    604     if (kDesiredHeapVerification > kNoHeapVerification) {
    605       VerifyObject(obj);
    606     }
    607 
    608     if (UNLIKELY(kMeasureAllocationTime)) {
    609       total_allocation_time_.fetch_add(NanoTime() / kTimeAdjust - allocation_start);
    610     }
    611 
    612     return obj;
    613   } else {
    614     std::ostringstream oss;
    615     int64_t total_bytes_free = GetFreeMemory();
    616     oss << "Failed to allocate a " << byte_count << " byte allocation with " << total_bytes_free
    617         << " free bytes";
    618     // If the allocation failed due to fragmentation, print out the largest continuous allocation.
    619     if (!large_object_allocation && total_bytes_free >= byte_count) {
    620       size_t max_contiguous_allocation = 0;
    621       for (const auto& space : continuous_spaces_) {
    622         if (space->IsDlMallocSpace()) {
    623           space->AsDlMallocSpace()->Walk(MSpaceChunkCallback, &max_contiguous_allocation);
    624         }
    625       }
    626       oss << "; failed due to fragmentation (largest possible contiguous allocation "
    627           <<  max_contiguous_allocation << " bytes)";
    628     }
    629     self->ThrowOutOfMemoryError(oss.str().c_str());
    630     return NULL;
    631   }
    632 }
    633 
    634 bool Heap::IsHeapAddress(const mirror::Object* obj) {
    635   // Note: we deliberately don't take the lock here, and mustn't test anything that would
    636   // require taking the lock.
    637   if (obj == NULL) {
    638     return true;
    639   }
    640   if (UNLIKELY(!IsAligned<kObjectAlignment>(obj))) {
    641     return false;
    642   }
    643   return FindSpaceFromObject(obj, true) != NULL;
    644 }
    645 
    646 bool Heap::IsLiveObjectLocked(const mirror::Object* obj, bool search_allocation_stack,
    647                               bool search_live_stack, bool sorted) {
    648   // Locks::heap_bitmap_lock_->AssertReaderHeld(Thread::Current());
    649   if (obj == NULL || UNLIKELY(!IsAligned<kObjectAlignment>(obj))) {
    650     return false;
    651   }
    652   space::ContinuousSpace* c_space = FindContinuousSpaceFromObject(obj, true);
    653   space::DiscontinuousSpace* d_space = NULL;
    654   if (c_space != NULL) {
    655     if (c_space->GetLiveBitmap()->Test(obj)) {
    656       return true;
    657     }
    658   } else {
    659     d_space = FindDiscontinuousSpaceFromObject(obj, true);
    660     if (d_space != NULL) {
    661       if (d_space->GetLiveObjects()->Test(obj)) {
    662         return true;
    663       }
    664     }
    665   }
    666   // This is covering the allocation/live stack swapping that is done without mutators suspended.
    667   for (size_t i = 0; i < (sorted ? 1 : 5); ++i) {
    668     if (i > 0) {
    669       NanoSleep(MsToNs(10));
    670     }
    671 
    672     if (search_allocation_stack) {
    673       if (sorted) {
    674         if (allocation_stack_->ContainsSorted(const_cast<mirror::Object*>(obj))) {
    675           return true;
    676         }
    677       } else if (allocation_stack_->Contains(const_cast<mirror::Object*>(obj))) {
    678         return true;
    679       }
    680     }
    681 
    682     if (search_live_stack) {
    683       if (sorted) {
    684         if (live_stack_->ContainsSorted(const_cast<mirror::Object*>(obj))) {
    685           return true;
    686         }
    687       } else if (live_stack_->Contains(const_cast<mirror::Object*>(obj))) {
    688         return true;
    689       }
    690     }
    691   }
    692   // We need to check the bitmaps again since there is a race where we mark something as live and
    693   // then clear the stack containing it.
    694   if (c_space != NULL) {
    695     if (c_space->GetLiveBitmap()->Test(obj)) {
    696       return true;
    697     }
    698   } else {
    699     d_space = FindDiscontinuousSpaceFromObject(obj, true);
    700     if (d_space != NULL && d_space->GetLiveObjects()->Test(obj)) {
    701       return true;
    702     }
    703   }
    704   return false;
    705 }
    706 
    707 void Heap::VerifyObjectImpl(const mirror::Object* obj) {
    708   if (Thread::Current() == NULL ||
    709       Runtime::Current()->GetThreadList()->GetLockOwner() == Thread::Current()->GetTid()) {
    710     return;
    711   }
    712   VerifyObjectBody(obj);
    713 }
    714 
    715 void Heap::DumpSpaces() {
    716   for (const auto& space : continuous_spaces_) {
    717     accounting::SpaceBitmap* live_bitmap = space->GetLiveBitmap();
    718     accounting::SpaceBitmap* mark_bitmap = space->GetMarkBitmap();
    719     LOG(INFO) << space << " " << *space << "\n"
    720               << live_bitmap << " " << *live_bitmap << "\n"
    721               << mark_bitmap << " " << *mark_bitmap;
    722   }
    723   for (const auto& space : discontinuous_spaces_) {
    724     LOG(INFO) << space << " " << *space << "\n";
    725   }
    726 }
    727 
    728 void Heap::VerifyObjectBody(const mirror::Object* obj) {
    729   CHECK(IsAligned<kObjectAlignment>(obj)) << "Object isn't aligned: " << obj;
    730   // Ignore early dawn of the universe verifications.
    731   if (UNLIKELY(static_cast<size_t>(num_bytes_allocated_.load()) < 10 * KB)) {
    732     return;
    733   }
    734   const byte* raw_addr = reinterpret_cast<const byte*>(obj) +
    735       mirror::Object::ClassOffset().Int32Value();
    736   const mirror::Class* c = *reinterpret_cast<mirror::Class* const *>(raw_addr);
    737   if (UNLIKELY(c == NULL)) {
    738     LOG(FATAL) << "Null class in object: " << obj;
    739   } else if (UNLIKELY(!IsAligned<kObjectAlignment>(c))) {
    740     LOG(FATAL) << "Class isn't aligned: " << c << " in object: " << obj;
    741   }
    742   // Check obj.getClass().getClass() == obj.getClass().getClass().getClass()
    743   // Note: we don't use the accessors here as they have internal sanity checks
    744   // that we don't want to run
    745   raw_addr = reinterpret_cast<const byte*>(c) + mirror::Object::ClassOffset().Int32Value();
    746   const mirror::Class* c_c = *reinterpret_cast<mirror::Class* const *>(raw_addr);
    747   raw_addr = reinterpret_cast<const byte*>(c_c) + mirror::Object::ClassOffset().Int32Value();
    748   const mirror::Class* c_c_c = *reinterpret_cast<mirror::Class* const *>(raw_addr);
    749   CHECK_EQ(c_c, c_c_c);
    750 
    751   if (verify_object_mode_ != kVerifyAllFast) {
    752     // TODO: the bitmap tests below are racy if VerifyObjectBody is called without the
    753     //       heap_bitmap_lock_.
    754     if (!IsLiveObjectLocked(obj)) {
    755       DumpSpaces();
    756       LOG(FATAL) << "Object is dead: " << obj;
    757     }
    758     if (!IsLiveObjectLocked(c)) {
    759       LOG(FATAL) << "Class of object is dead: " << c << " in object: " << obj;
    760     }
    761   }
    762 }
    763 
    764 void Heap::VerificationCallback(mirror::Object* obj, void* arg) {
    765   DCHECK(obj != NULL);
    766   reinterpret_cast<Heap*>(arg)->VerifyObjectBody(obj);
    767 }
    768 
    769 void Heap::VerifyHeap() {
    770   ReaderMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
    771   GetLiveBitmap()->Walk(Heap::VerificationCallback, this);
    772 }
    773 
    774 inline void Heap::RecordAllocation(size_t size, mirror::Object* obj) {
    775   DCHECK(obj != NULL);
    776   DCHECK_GT(size, 0u);
    777   num_bytes_allocated_.fetch_add(size);
    778 
    779   if (Runtime::Current()->HasStatsEnabled()) {
    780     RuntimeStats* thread_stats = Thread::Current()->GetStats();
    781     ++thread_stats->allocated_objects;
    782     thread_stats->allocated_bytes += size;
    783 
    784     // TODO: Update these atomically.
    785     RuntimeStats* global_stats = Runtime::Current()->GetStats();
    786     ++global_stats->allocated_objects;
    787     global_stats->allocated_bytes += size;
    788   }
    789 
    790   // This is safe to do since the GC will never free objects which are neither in the allocation
    791   // stack or the live bitmap.
    792   while (!allocation_stack_->AtomicPushBack(obj)) {
    793     CollectGarbageInternal(collector::kGcTypeSticky, kGcCauseForAlloc, false);
    794   }
    795 }
    796 
    797 void Heap::RecordFree(size_t freed_objects, size_t freed_bytes) {
    798   DCHECK_LE(freed_bytes, static_cast<size_t>(num_bytes_allocated_));
    799   num_bytes_allocated_.fetch_sub(freed_bytes);
    800 
    801   if (Runtime::Current()->HasStatsEnabled()) {
    802     RuntimeStats* thread_stats = Thread::Current()->GetStats();
    803     thread_stats->freed_objects += freed_objects;
    804     thread_stats->freed_bytes += freed_bytes;
    805 
    806     // TODO: Do this concurrently.
    807     RuntimeStats* global_stats = Runtime::Current()->GetStats();
    808     global_stats->freed_objects += freed_objects;
    809     global_stats->freed_bytes += freed_bytes;
    810   }
    811 }
    812 
    813 inline bool Heap::IsOutOfMemoryOnAllocation(size_t alloc_size, bool grow) {
    814   size_t new_footprint = num_bytes_allocated_ + alloc_size;
    815   if (UNLIKELY(new_footprint > max_allowed_footprint_)) {
    816     if (UNLIKELY(new_footprint > growth_limit_)) {
    817       return true;
    818     }
    819     if (!concurrent_gc_) {
    820       if (!grow) {
    821         return true;
    822       } else {
    823         max_allowed_footprint_ = new_footprint;
    824       }
    825     }
    826   }
    827   return false;
    828 }
    829 
    830 inline mirror::Object* Heap::TryToAllocate(Thread* self, space::AllocSpace* space, size_t alloc_size,
    831                                            bool grow, size_t* bytes_allocated) {
    832   if (UNLIKELY(IsOutOfMemoryOnAllocation(alloc_size, grow))) {
    833     return NULL;
    834   }
    835   return space->Alloc(self, alloc_size, bytes_allocated);
    836 }
    837 
    838 // DlMallocSpace-specific version.
    839 inline mirror::Object* Heap::TryToAllocate(Thread* self, space::DlMallocSpace* space, size_t alloc_size,
    840                                            bool grow, size_t* bytes_allocated) {
    841   if (UNLIKELY(IsOutOfMemoryOnAllocation(alloc_size, grow))) {
    842     return NULL;
    843   }
    844   if (LIKELY(!running_on_valgrind_)) {
    845     return space->AllocNonvirtual(self, alloc_size, bytes_allocated);
    846   } else {
    847     return space->Alloc(self, alloc_size, bytes_allocated);
    848   }
    849 }
    850 
    851 template <class T>
    852 inline mirror::Object* Heap::Allocate(Thread* self, T* space, size_t alloc_size,
    853                                       size_t* bytes_allocated) {
    854   // Since allocation can cause a GC which will need to SuspendAll, make sure all allocations are
    855   // done in the runnable state where suspension is expected.
    856   DCHECK_EQ(self->GetState(), kRunnable);
    857   self->AssertThreadSuspensionIsAllowable();
    858 
    859   mirror::Object* ptr = TryToAllocate(self, space, alloc_size, false, bytes_allocated);
    860   if (ptr != NULL) {
    861     return ptr;
    862   }
    863   return AllocateInternalWithGc(self, space, alloc_size, bytes_allocated);
    864 }
    865 
    866 mirror::Object* Heap::AllocateInternalWithGc(Thread* self, space::AllocSpace* space,
    867                                              size_t alloc_size, size_t* bytes_allocated) {
    868   mirror::Object* ptr;
    869 
    870   // The allocation failed. If the GC is running, block until it completes, and then retry the
    871   // allocation.
    872   collector::GcType last_gc = WaitForConcurrentGcToComplete(self);
    873   if (last_gc != collector::kGcTypeNone) {
    874     // A GC was in progress and we blocked, retry allocation now that memory has been freed.
    875     ptr = TryToAllocate(self, space, alloc_size, false, bytes_allocated);
    876     if (ptr != NULL) {
    877       return ptr;
    878     }
    879   }
    880 
    881   // Loop through our different Gc types and try to Gc until we get enough free memory.
    882   for (size_t i = static_cast<size_t>(last_gc) + 1;
    883       i < static_cast<size_t>(collector::kGcTypeMax); ++i) {
    884     bool run_gc = false;
    885     collector::GcType gc_type = static_cast<collector::GcType>(i);
    886     switch (gc_type) {
    887       case collector::kGcTypeSticky: {
    888           const size_t alloc_space_size = alloc_space_->Size();
    889           run_gc = alloc_space_size > min_alloc_space_size_for_sticky_gc_ &&
    890               alloc_space_->Capacity() - alloc_space_size >= min_remaining_space_for_sticky_gc_;
    891           break;
    892         }
    893       case collector::kGcTypePartial:
    894         run_gc = have_zygote_space_;
    895         break;
    896       case collector::kGcTypeFull:
    897         run_gc = true;
    898         break;
    899       default:
    900         break;
    901     }
    902 
    903     if (run_gc) {
    904       // If we actually ran a different type of Gc than requested, we can skip the index forwards.
    905       collector::GcType gc_type_ran = CollectGarbageInternal(gc_type, kGcCauseForAlloc, false);
    906       DCHECK_GE(static_cast<size_t>(gc_type_ran), i);
    907       i = static_cast<size_t>(gc_type_ran);
    908 
    909       // Did we free sufficient memory for the allocation to succeed?
    910       ptr = TryToAllocate(self, space, alloc_size, false, bytes_allocated);
    911       if (ptr != NULL) {
    912         return ptr;
    913       }
    914     }
    915   }
    916 
    917   // Allocations have failed after GCs;  this is an exceptional state.
    918   // Try harder, growing the heap if necessary.
    919   ptr = TryToAllocate(self, space, alloc_size, true, bytes_allocated);
    920   if (ptr != NULL) {
    921     return ptr;
    922   }
    923 
    924   // Most allocations should have succeeded by now, so the heap is really full, really fragmented,
    925   // or the requested size is really big. Do another GC, collecting SoftReferences this time. The
    926   // VM spec requires that all SoftReferences have been collected and cleared before throwing OOME.
    927 
    928   // OLD-TODO: wait for the finalizers from the previous GC to finish
    929   VLOG(gc) << "Forcing collection of SoftReferences for " << PrettySize(alloc_size)
    930            << " allocation";
    931 
    932   // We don't need a WaitForConcurrentGcToComplete here either.
    933   CollectGarbageInternal(collector::kGcTypeFull, kGcCauseForAlloc, true);
    934   return TryToAllocate(self, space, alloc_size, true, bytes_allocated);
    935 }
    936 
    937 void Heap::SetTargetHeapUtilization(float target) {
    938   DCHECK_GT(target, 0.0f);  // asserted in Java code
    939   DCHECK_LT(target, 1.0f);
    940   target_utilization_ = target;
    941 }
    942 
    943 size_t Heap::GetObjectsAllocated() const {
    944   size_t total = 0;
    945   typedef std::vector<space::ContinuousSpace*>::const_iterator It;
    946   for (It it = continuous_spaces_.begin(), end = continuous_spaces_.end(); it != end; ++it) {
    947     space::ContinuousSpace* space = *it;
    948     if (space->IsDlMallocSpace()) {
    949       total += space->AsDlMallocSpace()->GetObjectsAllocated();
    950     }
    951   }
    952   typedef std::vector<space::DiscontinuousSpace*>::const_iterator It2;
    953   for (It2 it = discontinuous_spaces_.begin(), end = discontinuous_spaces_.end(); it != end; ++it) {
    954     space::DiscontinuousSpace* space = *it;
    955     total += space->AsLargeObjectSpace()->GetObjectsAllocated();
    956   }
    957   return total;
    958 }
    959 
    960 size_t Heap::GetObjectsAllocatedEver() const {
    961   size_t total = 0;
    962   typedef std::vector<space::ContinuousSpace*>::const_iterator It;
    963   for (It it = continuous_spaces_.begin(), end = continuous_spaces_.end(); it != end; ++it) {
    964     space::ContinuousSpace* space = *it;
    965     if (space->IsDlMallocSpace()) {
    966       total += space->AsDlMallocSpace()->GetTotalObjectsAllocated();
    967     }
    968   }
    969   typedef std::vector<space::DiscontinuousSpace*>::const_iterator It2;
    970   for (It2 it = discontinuous_spaces_.begin(), end = discontinuous_spaces_.end(); it != end; ++it) {
    971     space::DiscontinuousSpace* space = *it;
    972     total += space->AsLargeObjectSpace()->GetTotalObjectsAllocated();
    973   }
    974   return total;
    975 }
    976 
    977 size_t Heap::GetBytesAllocatedEver() const {
    978   size_t total = 0;
    979   typedef std::vector<space::ContinuousSpace*>::const_iterator It;
    980   for (It it = continuous_spaces_.begin(), end = continuous_spaces_.end(); it != end; ++it) {
    981     space::ContinuousSpace* space = *it;
    982     if (space->IsDlMallocSpace()) {
    983       total += space->AsDlMallocSpace()->GetTotalBytesAllocated();
    984     }
    985   }
    986   typedef std::vector<space::DiscontinuousSpace*>::const_iterator It2;
    987   for (It2 it = discontinuous_spaces_.begin(), end = discontinuous_spaces_.end(); it != end; ++it) {
    988     space::DiscontinuousSpace* space = *it;
    989     total += space->AsLargeObjectSpace()->GetTotalBytesAllocated();
    990   }
    991   return total;
    992 }
    993 
    994 class InstanceCounter {
    995  public:
    996   InstanceCounter(const std::vector<mirror::Class*>& classes, bool use_is_assignable_from, uint64_t* counts)
    997       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
    998       : classes_(classes), use_is_assignable_from_(use_is_assignable_from), counts_(counts) {
    999   }
   1000 
   1001   void operator()(const mirror::Object* o) const SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
   1002     for (size_t i = 0; i < classes_.size(); ++i) {
   1003       const mirror::Class* instance_class = o->GetClass();
   1004       if (use_is_assignable_from_) {
   1005         if (instance_class != NULL && classes_[i]->IsAssignableFrom(instance_class)) {
   1006           ++counts_[i];
   1007         }
   1008       } else {
   1009         if (instance_class == classes_[i]) {
   1010           ++counts_[i];
   1011         }
   1012       }
   1013     }
   1014   }
   1015 
   1016  private:
   1017   const std::vector<mirror::Class*>& classes_;
   1018   bool use_is_assignable_from_;
   1019   uint64_t* const counts_;
   1020 
   1021   DISALLOW_COPY_AND_ASSIGN(InstanceCounter);
   1022 };
   1023 
   1024 void Heap::CountInstances(const std::vector<mirror::Class*>& classes, bool use_is_assignable_from,
   1025                           uint64_t* counts) {
   1026   // We only want reachable instances, so do a GC. This also ensures that the alloc stack
   1027   // is empty, so the live bitmap is the only place we need to look.
   1028   Thread* self = Thread::Current();
   1029   self->TransitionFromRunnableToSuspended(kNative);
   1030   CollectGarbage(false);
   1031   self->TransitionFromSuspendedToRunnable();
   1032 
   1033   InstanceCounter counter(classes, use_is_assignable_from, counts);
   1034   ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
   1035   GetLiveBitmap()->Visit(counter);
   1036 }
   1037 
   1038 class InstanceCollector {
   1039  public:
   1040   InstanceCollector(mirror::Class* c, int32_t max_count, std::vector<mirror::Object*>& instances)
   1041       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
   1042       : class_(c), max_count_(max_count), instances_(instances) {
   1043   }
   1044 
   1045   void operator()(const mirror::Object* o) const SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
   1046     const mirror::Class* instance_class = o->GetClass();
   1047     if (instance_class == class_) {
   1048       if (max_count_ == 0 || instances_.size() < max_count_) {
   1049         instances_.push_back(const_cast<mirror::Object*>(o));
   1050       }
   1051     }
   1052   }
   1053 
   1054  private:
   1055   mirror::Class* class_;
   1056   uint32_t max_count_;
   1057   std::vector<mirror::Object*>& instances_;
   1058 
   1059   DISALLOW_COPY_AND_ASSIGN(InstanceCollector);
   1060 };
   1061 
   1062 void Heap::GetInstances(mirror::Class* c, int32_t max_count,
   1063                         std::vector<mirror::Object*>& instances) {
   1064   // We only want reachable instances, so do a GC. This also ensures that the alloc stack
   1065   // is empty, so the live bitmap is the only place we need to look.
   1066   Thread* self = Thread::Current();
   1067   self->TransitionFromRunnableToSuspended(kNative);
   1068   CollectGarbage(false);
   1069   self->TransitionFromSuspendedToRunnable();
   1070 
   1071   InstanceCollector collector(c, max_count, instances);
   1072   ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
   1073   GetLiveBitmap()->Visit(collector);
   1074 }
   1075 
   1076 class ReferringObjectsFinder {
   1077  public:
   1078   ReferringObjectsFinder(mirror::Object* object, int32_t max_count,
   1079                          std::vector<mirror::Object*>& referring_objects)
   1080       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
   1081       : object_(object), max_count_(max_count), referring_objects_(referring_objects) {
   1082   }
   1083 
   1084   // For bitmap Visit.
   1085   // TODO: Fix lock analysis to not use NO_THREAD_SAFETY_ANALYSIS, requires support for
   1086   // annotalysis on visitors.
   1087   void operator()(const mirror::Object* o) const NO_THREAD_SAFETY_ANALYSIS {
   1088     collector::MarkSweep::VisitObjectReferences(o, *this);
   1089   }
   1090 
   1091   // For MarkSweep::VisitObjectReferences.
   1092   void operator()(const mirror::Object* referrer, const mirror::Object* object,
   1093                   const MemberOffset&, bool) const {
   1094     if (object == object_ && (max_count_ == 0 || referring_objects_.size() < max_count_)) {
   1095       referring_objects_.push_back(const_cast<mirror::Object*>(referrer));
   1096     }
   1097   }
   1098 
   1099  private:
   1100   mirror::Object* object_;
   1101   uint32_t max_count_;
   1102   std::vector<mirror::Object*>& referring_objects_;
   1103 
   1104   DISALLOW_COPY_AND_ASSIGN(ReferringObjectsFinder);
   1105 };
   1106 
   1107 void Heap::GetReferringObjects(mirror::Object* o, int32_t max_count,
   1108                                std::vector<mirror::Object*>& referring_objects) {
   1109   // We only want reachable instances, so do a GC. This also ensures that the alloc stack
   1110   // is empty, so the live bitmap is the only place we need to look.
   1111   Thread* self = Thread::Current();
   1112   self->TransitionFromRunnableToSuspended(kNative);
   1113   CollectGarbage(false);
   1114   self->TransitionFromSuspendedToRunnable();
   1115 
   1116   ReferringObjectsFinder finder(o, max_count, referring_objects);
   1117   ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
   1118   GetLiveBitmap()->Visit(finder);
   1119 }
   1120 
   1121 void Heap::CollectGarbage(bool clear_soft_references) {
   1122   // Even if we waited for a GC we still need to do another GC since weaks allocated during the
   1123   // last GC will not have necessarily been cleared.
   1124   Thread* self = Thread::Current();
   1125   WaitForConcurrentGcToComplete(self);
   1126   CollectGarbageInternal(collector::kGcTypeFull, kGcCauseExplicit, clear_soft_references);
   1127 }
   1128 
   1129 void Heap::PreZygoteFork() {
   1130   static Mutex zygote_creation_lock_("zygote creation lock", kZygoteCreationLock);
   1131   // Do this before acquiring the zygote creation lock so that we don't get lock order violations.
   1132   CollectGarbage(false);
   1133   Thread* self = Thread::Current();
   1134   MutexLock mu(self, zygote_creation_lock_);
   1135 
   1136   // Try to see if we have any Zygote spaces.
   1137   if (have_zygote_space_) {
   1138     return;
   1139   }
   1140 
   1141   VLOG(heap) << "Starting PreZygoteFork with alloc space size " << PrettySize(alloc_space_->Size());
   1142 
   1143   {
   1144     // Flush the alloc stack.
   1145     WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
   1146     FlushAllocStack();
   1147   }
   1148 
   1149   // Turns the current alloc space into a Zygote space and obtain the new alloc space composed
   1150   // of the remaining available heap memory.
   1151   space::DlMallocSpace* zygote_space = alloc_space_;
   1152   alloc_space_ = zygote_space->CreateZygoteSpace("alloc space");
   1153   alloc_space_->SetFootprintLimit(alloc_space_->Capacity());
   1154 
   1155   // Change the GC retention policy of the zygote space to only collect when full.
   1156   zygote_space->SetGcRetentionPolicy(space::kGcRetentionPolicyFullCollect);
   1157   AddContinuousSpace(alloc_space_);
   1158   have_zygote_space_ = true;
   1159 
   1160   // Reset the cumulative loggers since we now have a few additional timing phases.
   1161   for (const auto& collector : mark_sweep_collectors_) {
   1162     collector->ResetCumulativeStatistics();
   1163   }
   1164 }
   1165 
   1166 void Heap::FlushAllocStack() {
   1167   MarkAllocStack(alloc_space_->GetLiveBitmap(), large_object_space_->GetLiveObjects(),
   1168                  allocation_stack_.get());
   1169   allocation_stack_->Reset();
   1170 }
   1171 
   1172 void Heap::MarkAllocStack(accounting::SpaceBitmap* bitmap, accounting::SpaceSetMap* large_objects,
   1173                           accounting::ObjectStack* stack) {
   1174   mirror::Object** limit = stack->End();
   1175   for (mirror::Object** it = stack->Begin(); it != limit; ++it) {
   1176     const mirror::Object* obj = *it;
   1177     DCHECK(obj != NULL);
   1178     if (LIKELY(bitmap->HasAddress(obj))) {
   1179       bitmap->Set(obj);
   1180     } else {
   1181       large_objects->Set(obj);
   1182     }
   1183   }
   1184 }
   1185 
   1186 
   1187 const char* gc_cause_and_type_strings[3][4] = {
   1188     {"", "GC Alloc Sticky", "GC Alloc Partial", "GC Alloc Full"},
   1189     {"", "GC Background Sticky", "GC Background Partial", "GC Background Full"},
   1190     {"", "GC Explicit Sticky", "GC Explicit Partial", "GC Explicit Full"}};
   1191 
   1192 collector::GcType Heap::CollectGarbageInternal(collector::GcType gc_type, GcCause gc_cause,
   1193                                                bool clear_soft_references) {
   1194   Thread* self = Thread::Current();
   1195 
   1196   ScopedThreadStateChange tsc(self, kWaitingPerformingGc);
   1197   Locks::mutator_lock_->AssertNotHeld(self);
   1198 
   1199   if (self->IsHandlingStackOverflow()) {
   1200     LOG(WARNING) << "Performing GC on a thread that is handling a stack overflow.";
   1201   }
   1202 
   1203   // Ensure there is only one GC at a time.
   1204   bool start_collect = false;
   1205   while (!start_collect) {
   1206     {
   1207       MutexLock mu(self, *gc_complete_lock_);
   1208       if (!is_gc_running_) {
   1209         is_gc_running_ = true;
   1210         start_collect = true;
   1211       }
   1212     }
   1213     if (!start_collect) {
   1214       // TODO: timinglog this.
   1215       WaitForConcurrentGcToComplete(self);
   1216 
   1217       // TODO: if another thread beat this one to do the GC, perhaps we should just return here?
   1218       //       Not doing at the moment to ensure soft references are cleared.
   1219     }
   1220   }
   1221   gc_complete_lock_->AssertNotHeld(self);
   1222 
   1223   if (gc_cause == kGcCauseForAlloc && Runtime::Current()->HasStatsEnabled()) {
   1224     ++Runtime::Current()->GetStats()->gc_for_alloc_count;
   1225     ++Thread::Current()->GetStats()->gc_for_alloc_count;
   1226   }
   1227 
   1228   uint64_t gc_start_time_ns = NanoTime();
   1229   uint64_t gc_start_size = GetBytesAllocated();
   1230   // Approximate allocation rate in bytes / second.
   1231   if (UNLIKELY(gc_start_time_ns == last_gc_time_ns_)) {
   1232     LOG(WARNING) << "Timers are broken (gc_start_time == last_gc_time_).";
   1233   }
   1234   uint64_t ms_delta = NsToMs(gc_start_time_ns - last_gc_time_ns_);
   1235   if (ms_delta != 0) {
   1236     allocation_rate_ = ((gc_start_size - last_gc_size_) * 1000) / ms_delta;
   1237     VLOG(heap) << "Allocation rate: " << PrettySize(allocation_rate_) << "/s";
   1238   }
   1239 
   1240   if (gc_type == collector::kGcTypeSticky &&
   1241       alloc_space_->Size() < min_alloc_space_size_for_sticky_gc_) {
   1242     gc_type = collector::kGcTypePartial;
   1243   }
   1244 
   1245   DCHECK_LT(gc_type, collector::kGcTypeMax);
   1246   DCHECK_NE(gc_type, collector::kGcTypeNone);
   1247   DCHECK_LE(gc_cause, kGcCauseExplicit);
   1248 
   1249   ATRACE_BEGIN(gc_cause_and_type_strings[gc_cause][gc_type]);
   1250 
   1251   collector::MarkSweep* collector = NULL;
   1252   for (const auto& cur_collector : mark_sweep_collectors_) {
   1253     if (cur_collector->IsConcurrent() == concurrent_gc_ && cur_collector->GetGcType() == gc_type) {
   1254       collector = cur_collector;
   1255       break;
   1256     }
   1257   }
   1258   CHECK(collector != NULL)
   1259       << "Could not find garbage collector with concurrent=" << concurrent_gc_
   1260       << " and type=" << gc_type;
   1261 
   1262   collector->clear_soft_references_ = clear_soft_references;
   1263   collector->Run();
   1264   total_objects_freed_ever_ += collector->GetFreedObjects();
   1265   total_bytes_freed_ever_ += collector->GetFreedBytes();
   1266   if (care_about_pause_times_) {
   1267     const size_t duration = collector->GetDurationNs();
   1268     std::vector<uint64_t> pauses = collector->GetPauseTimes();
   1269     // GC for alloc pauses the allocating thread, so consider it as a pause.
   1270     bool was_slow = duration > long_gc_log_threshold_ ||
   1271             (gc_cause == kGcCauseForAlloc && duration > long_pause_log_threshold_);
   1272     if (!was_slow) {
   1273       for (uint64_t pause : pauses) {
   1274         was_slow = was_slow || pause > long_pause_log_threshold_;
   1275       }
   1276     }
   1277 
   1278     if (was_slow) {
   1279         const size_t percent_free = GetPercentFree();
   1280         const size_t current_heap_size = GetBytesAllocated();
   1281         const size_t total_memory = GetTotalMemory();
   1282         std::ostringstream pause_string;
   1283         for (size_t i = 0; i < pauses.size(); ++i) {
   1284             pause_string << PrettyDuration((pauses[i] / 1000) * 1000)
   1285                          << ((i != pauses.size() - 1) ? ", " : "");
   1286         }
   1287         LOG(INFO) << gc_cause << " " << collector->GetName()
   1288                   << " GC freed "  <<  collector->GetFreedObjects() << "("
   1289                   << PrettySize(collector->GetFreedBytes()) << ") AllocSpace objects, "
   1290                   << collector->GetFreedLargeObjects() << "("
   1291                   << PrettySize(collector->GetFreedLargeObjectBytes()) << ") LOS objects, "
   1292                   << percent_free << "% free, " << PrettySize(current_heap_size) << "/"
   1293                   << PrettySize(total_memory) << ", " << "paused " << pause_string.str()
   1294                   << " total " << PrettyDuration((duration / 1000) * 1000);
   1295         if (VLOG_IS_ON(heap)) {
   1296             LOG(INFO) << Dumpable<base::TimingLogger>(collector->GetTimings());
   1297         }
   1298     }
   1299   }
   1300 
   1301   {
   1302       MutexLock mu(self, *gc_complete_lock_);
   1303       is_gc_running_ = false;
   1304       last_gc_type_ = gc_type;
   1305       // Wake anyone who may have been waiting for the GC to complete.
   1306       gc_complete_cond_->Broadcast(self);
   1307   }
   1308 
   1309   ATRACE_END();
   1310 
   1311   // Inform DDMS that a GC completed.
   1312   Dbg::GcDidFinish();
   1313   return gc_type;
   1314 }
   1315 
   1316 void Heap::UpdateAndMarkModUnion(collector::MarkSweep* mark_sweep, base::TimingLogger& timings,
   1317                                  collector::GcType gc_type) {
   1318   if (gc_type == collector::kGcTypeSticky) {
   1319     // Don't need to do anything for mod union table in this case since we are only scanning dirty
   1320     // cards.
   1321     return;
   1322   }
   1323 
   1324   base::TimingLogger::ScopedSplit split("UpdateModUnionTable", &timings);
   1325   // Update zygote mod union table.
   1326   if (gc_type == collector::kGcTypePartial) {
   1327     base::TimingLogger::ScopedSplit split("UpdateZygoteModUnionTable", &timings);
   1328     zygote_mod_union_table_->Update();
   1329 
   1330     timings.NewSplit("ZygoteMarkReferences");
   1331     zygote_mod_union_table_->MarkReferences(mark_sweep);
   1332   }
   1333 
   1334   // Processes the cards we cleared earlier and adds their objects into the mod-union table.
   1335   timings.NewSplit("UpdateModUnionTable");
   1336   image_mod_union_table_->Update();
   1337 
   1338   // Scans all objects in the mod-union table.
   1339   timings.NewSplit("MarkImageToAllocSpaceReferences");
   1340   image_mod_union_table_->MarkReferences(mark_sweep);
   1341 }
   1342 
   1343 static void RootMatchesObjectVisitor(const mirror::Object* root, void* arg) {
   1344   mirror::Object* obj = reinterpret_cast<mirror::Object*>(arg);
   1345   if (root == obj) {
   1346     LOG(INFO) << "Object " << obj << " is a root";
   1347   }
   1348 }
   1349 
   1350 class ScanVisitor {
   1351  public:
   1352   void operator()(const mirror::Object* obj) const {
   1353     LOG(ERROR) << "Would have rescanned object " << obj;
   1354   }
   1355 };
   1356 
   1357 // Verify a reference from an object.
   1358 class VerifyReferenceVisitor {
   1359  public:
   1360   explicit VerifyReferenceVisitor(Heap* heap)
   1361       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_)
   1362       : heap_(heap), failed_(false) {}
   1363 
   1364   bool Failed() const {
   1365     return failed_;
   1366   }
   1367 
   1368   // TODO: Fix lock analysis to not use NO_THREAD_SAFETY_ANALYSIS, requires support for smarter
   1369   // analysis on visitors.
   1370   void operator()(const mirror::Object* obj, const mirror::Object* ref,
   1371                   const MemberOffset& offset, bool /* is_static */) const
   1372       NO_THREAD_SAFETY_ANALYSIS {
   1373     // Verify that the reference is live.
   1374     if (UNLIKELY(ref != NULL && !IsLive(ref))) {
   1375       accounting::CardTable* card_table = heap_->GetCardTable();
   1376       accounting::ObjectStack* alloc_stack = heap_->allocation_stack_.get();
   1377       accounting::ObjectStack* live_stack = heap_->live_stack_.get();
   1378 
   1379       if (!failed_) {
   1380         // Print message on only on first failure to prevent spam.
   1381         LOG(ERROR) << "!!!!!!!!!!!!!!Heap corruption detected!!!!!!!!!!!!!!!!!!!";
   1382         failed_ = true;
   1383       }
   1384       if (obj != nullptr) {
   1385         byte* card_addr = card_table->CardFromAddr(obj);
   1386         LOG(ERROR) << "Object " << obj << " references dead object " << ref << " at offset "
   1387                    << offset << "\n card value = " << static_cast<int>(*card_addr);
   1388         if (heap_->IsHeapAddress(obj->GetClass())) {
   1389           LOG(ERROR) << "Obj type " << PrettyTypeOf(obj);
   1390         } else {
   1391           LOG(ERROR) << "Object " << obj << " class(" << obj->GetClass() << ") not a heap address";
   1392         }
   1393 
   1394         // Attmept to find the class inside of the recently freed objects.
   1395         space::ContinuousSpace* ref_space = heap_->FindContinuousSpaceFromObject(ref, true);
   1396         if (ref_space->IsDlMallocSpace()) {
   1397           space::DlMallocSpace* space = ref_space->AsDlMallocSpace();
   1398           mirror::Class* ref_class = space->FindRecentFreedObject(ref);
   1399           if (ref_class != nullptr) {
   1400             LOG(ERROR) << "Reference " << ref << " found as a recently freed object with class "
   1401                        << PrettyClass(ref_class);
   1402           } else {
   1403             LOG(ERROR) << "Reference " << ref << " not found as a recently freed object";
   1404           }
   1405         }
   1406 
   1407         if (ref->GetClass() != nullptr && heap_->IsHeapAddress(ref->GetClass()) &&
   1408             ref->GetClass()->IsClass()) {
   1409           LOG(ERROR) << "Ref type " << PrettyTypeOf(ref);
   1410         } else {
   1411           LOG(ERROR) << "Ref " << ref << " class(" << ref->GetClass()
   1412                      << ") is not a valid heap address";
   1413         }
   1414 
   1415         card_table->CheckAddrIsInCardTable(reinterpret_cast<const byte*>(obj));
   1416         void* cover_begin = card_table->AddrFromCard(card_addr);
   1417         void* cover_end = reinterpret_cast<void*>(reinterpret_cast<size_t>(cover_begin) +
   1418             accounting::CardTable::kCardSize);
   1419         LOG(ERROR) << "Card " << reinterpret_cast<void*>(card_addr) << " covers " << cover_begin
   1420             << "-" << cover_end;
   1421         accounting::SpaceBitmap* bitmap = heap_->GetLiveBitmap()->GetContinuousSpaceBitmap(obj);
   1422 
   1423         // Print out how the object is live.
   1424         if (bitmap != NULL && bitmap->Test(obj)) {
   1425           LOG(ERROR) << "Object " << obj << " found in live bitmap";
   1426         }
   1427         if (alloc_stack->Contains(const_cast<mirror::Object*>(obj))) {
   1428           LOG(ERROR) << "Object " << obj << " found in allocation stack";
   1429         }
   1430         if (live_stack->Contains(const_cast<mirror::Object*>(obj))) {
   1431           LOG(ERROR) << "Object " << obj << " found in live stack";
   1432         }
   1433         if (alloc_stack->Contains(const_cast<mirror::Object*>(ref))) {
   1434           LOG(ERROR) << "Ref " << ref << " found in allocation stack";
   1435         }
   1436         if (live_stack->Contains(const_cast<mirror::Object*>(ref))) {
   1437           LOG(ERROR) << "Ref " << ref << " found in live stack";
   1438         }
   1439         // Attempt to see if the card table missed the reference.
   1440         ScanVisitor scan_visitor;
   1441         byte* byte_cover_begin = reinterpret_cast<byte*>(card_table->AddrFromCard(card_addr));
   1442         card_table->Scan(bitmap, byte_cover_begin,
   1443                          byte_cover_begin + accounting::CardTable::kCardSize, scan_visitor);
   1444 
   1445         // Search to see if any of the roots reference our object.
   1446         void* arg = const_cast<void*>(reinterpret_cast<const void*>(obj));
   1447         Runtime::Current()->VisitRoots(&RootMatchesObjectVisitor, arg, false, false);
   1448 
   1449         // Search to see if any of the roots reference our reference.
   1450         arg = const_cast<void*>(reinterpret_cast<const void*>(ref));
   1451         Runtime::Current()->VisitRoots(&RootMatchesObjectVisitor, arg, false, false);
   1452       } else {
   1453         LOG(ERROR) << "Root references dead object " << ref << "\nRef type " << PrettyTypeOf(ref);
   1454       }
   1455     }
   1456   }
   1457 
   1458   bool IsLive(const mirror::Object* obj) const NO_THREAD_SAFETY_ANALYSIS {
   1459     return heap_->IsLiveObjectLocked(obj, true, false, true);
   1460   }
   1461 
   1462   static void VerifyRoots(const mirror::Object* root, void* arg) {
   1463     VerifyReferenceVisitor* visitor = reinterpret_cast<VerifyReferenceVisitor*>(arg);
   1464     (*visitor)(NULL, root, MemberOffset(0), true);
   1465   }
   1466 
   1467  private:
   1468   Heap* const heap_;
   1469   mutable bool failed_;
   1470 };
   1471 
   1472 // Verify all references within an object, for use with HeapBitmap::Visit.
   1473 class VerifyObjectVisitor {
   1474  public:
   1475   explicit VerifyObjectVisitor(Heap* heap) : heap_(heap), failed_(false) {}
   1476 
   1477   void operator()(const mirror::Object* obj) const
   1478       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
   1479     // Note: we are verifying the references in obj but not obj itself, this is because obj must
   1480     // be live or else how did we find it in the live bitmap?
   1481     VerifyReferenceVisitor visitor(heap_);
   1482     // The class doesn't count as a reference but we should verify it anyways.
   1483     visitor(obj, obj->GetClass(), MemberOffset(0), false);
   1484     collector::MarkSweep::VisitObjectReferences(obj, visitor);
   1485     failed_ = failed_ || visitor.Failed();
   1486   }
   1487 
   1488   bool Failed() const {
   1489     return failed_;
   1490   }
   1491 
   1492  private:
   1493   Heap* const heap_;
   1494   mutable bool failed_;
   1495 };
   1496 
   1497 // Must do this with mutators suspended since we are directly accessing the allocation stacks.
   1498 bool Heap::VerifyHeapReferences() {
   1499   Locks::mutator_lock_->AssertExclusiveHeld(Thread::Current());
   1500   // Lets sort our allocation stacks so that we can efficiently binary search them.
   1501   allocation_stack_->Sort();
   1502   live_stack_->Sort();
   1503   // Perform the verification.
   1504   VerifyObjectVisitor visitor(this);
   1505   Runtime::Current()->VisitRoots(VerifyReferenceVisitor::VerifyRoots, &visitor, false, false);
   1506   GetLiveBitmap()->Visit(visitor);
   1507   // Verify objects in the allocation stack since these will be objects which were:
   1508   // 1. Allocated prior to the GC (pre GC verification).
   1509   // 2. Allocated during the GC (pre sweep GC verification).
   1510   for (mirror::Object** it = allocation_stack_->Begin(); it != allocation_stack_->End(); ++it) {
   1511     visitor(*it);
   1512   }
   1513   // We don't want to verify the objects in the live stack since they themselves may be
   1514   // pointing to dead objects if they are not reachable.
   1515   if (visitor.Failed()) {
   1516     // Dump mod-union tables.
   1517     image_mod_union_table_->Dump(LOG(ERROR) << "Image mod-union table: ");
   1518     zygote_mod_union_table_->Dump(LOG(ERROR) << "Zygote mod-union table: ");
   1519     DumpSpaces();
   1520     return false;
   1521   }
   1522   return true;
   1523 }
   1524 
   1525 class VerifyReferenceCardVisitor {
   1526  public:
   1527   VerifyReferenceCardVisitor(Heap* heap, bool* failed)
   1528       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_,
   1529                             Locks::heap_bitmap_lock_)
   1530       : heap_(heap), failed_(failed) {
   1531   }
   1532 
   1533   // TODO: Fix lock analysis to not use NO_THREAD_SAFETY_ANALYSIS, requires support for
   1534   // annotalysis on visitors.
   1535   void operator()(const mirror::Object* obj, const mirror::Object* ref, const MemberOffset& offset,
   1536                   bool is_static) const NO_THREAD_SAFETY_ANALYSIS {
   1537     // Filter out class references since changing an object's class does not mark the card as dirty.
   1538     // Also handles large objects, since the only reference they hold is a class reference.
   1539     if (ref != NULL && !ref->IsClass()) {
   1540       accounting::CardTable* card_table = heap_->GetCardTable();
   1541       // If the object is not dirty and it is referencing something in the live stack other than
   1542       // class, then it must be on a dirty card.
   1543       if (!card_table->AddrIsInCardTable(obj)) {
   1544         LOG(ERROR) << "Object " << obj << " is not in the address range of the card table";
   1545         *failed_ = true;
   1546       } else if (!card_table->IsDirty(obj)) {
   1547         // Card should be either kCardDirty if it got re-dirtied after we aged it, or
   1548         // kCardDirty - 1 if it didnt get touched since we aged it.
   1549         accounting::ObjectStack* live_stack = heap_->live_stack_.get();
   1550         if (live_stack->ContainsSorted(const_cast<mirror::Object*>(ref))) {
   1551           if (live_stack->ContainsSorted(const_cast<mirror::Object*>(obj))) {
   1552             LOG(ERROR) << "Object " << obj << " found in live stack";
   1553           }
   1554           if (heap_->GetLiveBitmap()->Test(obj)) {
   1555             LOG(ERROR) << "Object " << obj << " found in live bitmap";
   1556           }
   1557           LOG(ERROR) << "Object " << obj << " " << PrettyTypeOf(obj)
   1558                     << " references " << ref << " " << PrettyTypeOf(ref) << " in live stack";
   1559 
   1560           // Print which field of the object is dead.
   1561           if (!obj->IsObjectArray()) {
   1562             const mirror::Class* klass = is_static ? obj->AsClass() : obj->GetClass();
   1563             CHECK(klass != NULL);
   1564             const mirror::ObjectArray<mirror::ArtField>* fields = is_static ? klass->GetSFields()
   1565                                                                             : klass->GetIFields();
   1566             CHECK(fields != NULL);
   1567             for (int32_t i = 0; i < fields->GetLength(); ++i) {
   1568               const mirror::ArtField* cur = fields->Get(i);
   1569               if (cur->GetOffset().Int32Value() == offset.Int32Value()) {
   1570                 LOG(ERROR) << (is_static ? "Static " : "") << "field in the live stack is "
   1571                           << PrettyField(cur);
   1572                 break;
   1573               }
   1574             }
   1575           } else {
   1576             const mirror::ObjectArray<mirror::Object>* object_array =
   1577                 obj->AsObjectArray<mirror::Object>();
   1578             for (int32_t i = 0; i < object_array->GetLength(); ++i) {
   1579               if (object_array->Get(i) == ref) {
   1580                 LOG(ERROR) << (is_static ? "Static " : "") << "obj[" << i << "] = ref";
   1581               }
   1582             }
   1583           }
   1584 
   1585           *failed_ = true;
   1586         }
   1587       }
   1588     }
   1589   }
   1590 
   1591  private:
   1592   Heap* const heap_;
   1593   bool* const failed_;
   1594 };
   1595 
   1596 class VerifyLiveStackReferences {
   1597  public:
   1598   explicit VerifyLiveStackReferences(Heap* heap)
   1599       : heap_(heap),
   1600         failed_(false) {}
   1601 
   1602   void operator()(const mirror::Object* obj) const
   1603       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
   1604     VerifyReferenceCardVisitor visitor(heap_, const_cast<bool*>(&failed_));
   1605     collector::MarkSweep::VisitObjectReferences(obj, visitor);
   1606   }
   1607 
   1608   bool Failed() const {
   1609     return failed_;
   1610   }
   1611 
   1612  private:
   1613   Heap* const heap_;
   1614   bool failed_;
   1615 };
   1616 
   1617 bool Heap::VerifyMissingCardMarks() {
   1618   Locks::mutator_lock_->AssertExclusiveHeld(Thread::Current());
   1619 
   1620   // We need to sort the live stack since we binary search it.
   1621   live_stack_->Sort();
   1622   VerifyLiveStackReferences visitor(this);
   1623   GetLiveBitmap()->Visit(visitor);
   1624 
   1625   // We can verify objects in the live stack since none of these should reference dead objects.
   1626   for (mirror::Object** it = live_stack_->Begin(); it != live_stack_->End(); ++it) {
   1627     visitor(*it);
   1628   }
   1629 
   1630   if (visitor.Failed()) {
   1631     DumpSpaces();
   1632     return false;
   1633   }
   1634   return true;
   1635 }
   1636 
   1637 void Heap::SwapStacks() {
   1638   allocation_stack_.swap(live_stack_);
   1639 }
   1640 
   1641 void Heap::ProcessCards(base::TimingLogger& timings) {
   1642   // Clear cards and keep track of cards cleared in the mod-union table.
   1643   for (const auto& space : continuous_spaces_) {
   1644     if (space->IsImageSpace()) {
   1645       base::TimingLogger::ScopedSplit split("ImageModUnionClearCards", &timings);
   1646       image_mod_union_table_->ClearCards(space);
   1647     } else if (space->IsZygoteSpace()) {
   1648       base::TimingLogger::ScopedSplit split("ZygoteModUnionClearCards", &timings);
   1649       zygote_mod_union_table_->ClearCards(space);
   1650     } else {
   1651       base::TimingLogger::ScopedSplit split("AllocSpaceClearCards", &timings);
   1652       // No mod union table for the AllocSpace. Age the cards so that the GC knows that these cards
   1653       // were dirty before the GC started.
   1654       card_table_->ModifyCardsAtomic(space->Begin(), space->End(), AgeCardVisitor(), VoidFunctor());
   1655     }
   1656   }
   1657 }
   1658 
   1659 void Heap::PreGcVerification(collector::GarbageCollector* gc) {
   1660   ThreadList* thread_list = Runtime::Current()->GetThreadList();
   1661   Thread* self = Thread::Current();
   1662 
   1663   if (verify_pre_gc_heap_) {
   1664     thread_list->SuspendAll();
   1665     {
   1666       ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
   1667       if (!VerifyHeapReferences()) {
   1668         LOG(FATAL) << "Pre " << gc->GetName() << " heap verification failed";
   1669       }
   1670     }
   1671     thread_list->ResumeAll();
   1672   }
   1673 
   1674   // Check that all objects which reference things in the live stack are on dirty cards.
   1675   if (verify_missing_card_marks_) {
   1676     thread_list->SuspendAll();
   1677     {
   1678       ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
   1679       SwapStacks();
   1680       // Sort the live stack so that we can quickly binary search it later.
   1681       if (!VerifyMissingCardMarks()) {
   1682         LOG(FATAL) << "Pre " << gc->GetName() << " missing card mark verification failed";
   1683       }
   1684       SwapStacks();
   1685     }
   1686     thread_list->ResumeAll();
   1687   }
   1688 
   1689   if (verify_mod_union_table_) {
   1690     thread_list->SuspendAll();
   1691     ReaderMutexLock reader_lock(self, *Locks::heap_bitmap_lock_);
   1692     zygote_mod_union_table_->Update();
   1693     zygote_mod_union_table_->Verify();
   1694     image_mod_union_table_->Update();
   1695     image_mod_union_table_->Verify();
   1696     thread_list->ResumeAll();
   1697   }
   1698 }
   1699 
   1700 void Heap::PreSweepingGcVerification(collector::GarbageCollector* gc) {
   1701   // Called before sweeping occurs since we want to make sure we are not going so reclaim any
   1702   // reachable objects.
   1703   if (verify_post_gc_heap_) {
   1704     Thread* self = Thread::Current();
   1705     CHECK_NE(self->GetState(), kRunnable);
   1706     {
   1707       WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
   1708       // Swapping bound bitmaps does nothing.
   1709       gc->SwapBitmaps();
   1710       if (!VerifyHeapReferences()) {
   1711         LOG(FATAL) << "Pre sweeping " << gc->GetName() << " GC verification failed";
   1712       }
   1713       gc->SwapBitmaps();
   1714     }
   1715   }
   1716 }
   1717 
   1718 void Heap::PostGcVerification(collector::GarbageCollector* gc) {
   1719   if (verify_system_weaks_) {
   1720     Thread* self = Thread::Current();
   1721     ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
   1722     collector::MarkSweep* mark_sweep = down_cast<collector::MarkSweep*>(gc);
   1723     mark_sweep->VerifySystemWeaks();
   1724   }
   1725 }
   1726 
   1727 collector::GcType Heap::WaitForConcurrentGcToComplete(Thread* self) {
   1728   collector::GcType last_gc_type = collector::kGcTypeNone;
   1729   if (concurrent_gc_) {
   1730     ATRACE_BEGIN("GC: Wait For Concurrent");
   1731     bool do_wait;
   1732     uint64_t wait_start = NanoTime();
   1733     {
   1734       // Check if GC is running holding gc_complete_lock_.
   1735       MutexLock mu(self, *gc_complete_lock_);
   1736       do_wait = is_gc_running_;
   1737     }
   1738     if (do_wait) {
   1739       uint64_t wait_time;
   1740       // We must wait, change thread state then sleep on gc_complete_cond_;
   1741       ScopedThreadStateChange tsc(Thread::Current(), kWaitingForGcToComplete);
   1742       {
   1743         MutexLock mu(self, *gc_complete_lock_);
   1744         while (is_gc_running_) {
   1745           gc_complete_cond_->Wait(self);
   1746         }
   1747         last_gc_type = last_gc_type_;
   1748         wait_time = NanoTime() - wait_start;
   1749         total_wait_time_ += wait_time;
   1750       }
   1751       if (wait_time > long_pause_log_threshold_) {
   1752         LOG(INFO) << "WaitForConcurrentGcToComplete blocked for " << PrettyDuration(wait_time);
   1753       }
   1754     }
   1755     ATRACE_END();
   1756   }
   1757   return last_gc_type;
   1758 }
   1759 
   1760 void Heap::DumpForSigQuit(std::ostream& os) {
   1761   os << "Heap: " << GetPercentFree() << "% free, " << PrettySize(GetBytesAllocated()) << "/"
   1762      << PrettySize(GetTotalMemory()) << "; " << GetObjectsAllocated() << " objects\n";
   1763   DumpGcPerformanceInfo(os);
   1764 }
   1765 
   1766 size_t Heap::GetPercentFree() {
   1767   return static_cast<size_t>(100.0f * static_cast<float>(GetFreeMemory()) / GetTotalMemory());
   1768 }
   1769 
   1770 void Heap::SetIdealFootprint(size_t max_allowed_footprint) {
   1771   if (max_allowed_footprint > GetMaxMemory()) {
   1772     VLOG(gc) << "Clamp target GC heap from " << PrettySize(max_allowed_footprint) << " to "
   1773              << PrettySize(GetMaxMemory());
   1774     max_allowed_footprint = GetMaxMemory();
   1775   }
   1776   max_allowed_footprint_ = max_allowed_footprint;
   1777 }
   1778 
   1779 void Heap::UpdateMaxNativeFootprint() {
   1780   size_t native_size = native_bytes_allocated_;
   1781   // TODO: Tune the native heap utilization to be a value other than the java heap utilization.
   1782   size_t target_size = native_size / GetTargetHeapUtilization();
   1783   if (target_size > native_size + max_free_) {
   1784     target_size = native_size + max_free_;
   1785   } else if (target_size < native_size + min_free_) {
   1786     target_size = native_size + min_free_;
   1787   }
   1788   native_footprint_gc_watermark_ = target_size;
   1789   native_footprint_limit_ = 2 * target_size - native_size;
   1790 }
   1791 
   1792 void Heap::GrowForUtilization(collector::GcType gc_type, uint64_t gc_duration) {
   1793   // We know what our utilization is at this moment.
   1794   // This doesn't actually resize any memory. It just lets the heap grow more when necessary.
   1795   const size_t bytes_allocated = GetBytesAllocated();
   1796   last_gc_size_ = bytes_allocated;
   1797   last_gc_time_ns_ = NanoTime();
   1798 
   1799   size_t target_size;
   1800   if (gc_type != collector::kGcTypeSticky) {
   1801     // Grow the heap for non sticky GC.
   1802     target_size = bytes_allocated / GetTargetHeapUtilization();
   1803     if (target_size > bytes_allocated + max_free_) {
   1804       target_size = bytes_allocated + max_free_;
   1805     } else if (target_size < bytes_allocated + min_free_) {
   1806       target_size = bytes_allocated + min_free_;
   1807     }
   1808     next_gc_type_ = collector::kGcTypeSticky;
   1809   } else {
   1810     // Based on how close the current heap size is to the target size, decide
   1811     // whether or not to do a partial or sticky GC next.
   1812     if (bytes_allocated + min_free_ <= max_allowed_footprint_) {
   1813       next_gc_type_ = collector::kGcTypeSticky;
   1814     } else {
   1815       next_gc_type_ = collector::kGcTypePartial;
   1816     }
   1817 
   1818     // If we have freed enough memory, shrink the heap back down.
   1819     if (bytes_allocated + max_free_ < max_allowed_footprint_) {
   1820       target_size = bytes_allocated + max_free_;
   1821     } else {
   1822       target_size = std::max(bytes_allocated, max_allowed_footprint_);
   1823     }
   1824   }
   1825 
   1826   if (!ignore_max_footprint_) {
   1827     SetIdealFootprint(target_size);
   1828 
   1829     if (concurrent_gc_) {
   1830       // Calculate when to perform the next ConcurrentGC.
   1831 
   1832       // Calculate the estimated GC duration.
   1833       double gc_duration_seconds = NsToMs(gc_duration) / 1000.0;
   1834       // Estimate how many remaining bytes we will have when we need to start the next GC.
   1835       size_t remaining_bytes = allocation_rate_ * gc_duration_seconds;
   1836       remaining_bytes = std::max(remaining_bytes, kMinConcurrentRemainingBytes);
   1837       if (UNLIKELY(remaining_bytes > max_allowed_footprint_)) {
   1838         // A never going to happen situation that from the estimated allocation rate we will exceed
   1839         // the applications entire footprint with the given estimated allocation rate. Schedule
   1840         // another GC straight away.
   1841         concurrent_start_bytes_ = bytes_allocated;
   1842       } else {
   1843         // Start a concurrent GC when we get close to the estimated remaining bytes. When the
   1844         // allocation rate is very high, remaining_bytes could tell us that we should start a GC
   1845         // right away.
   1846         concurrent_start_bytes_ = std::max(max_allowed_footprint_ - remaining_bytes, bytes_allocated);
   1847       }
   1848       DCHECK_LE(concurrent_start_bytes_, max_allowed_footprint_);
   1849       DCHECK_LE(max_allowed_footprint_, growth_limit_);
   1850     }
   1851   }
   1852 
   1853   UpdateMaxNativeFootprint();
   1854 }
   1855 
   1856 void Heap::ClearGrowthLimit() {
   1857   growth_limit_ = capacity_;
   1858   alloc_space_->ClearGrowthLimit();
   1859 }
   1860 
   1861 void Heap::SetReferenceOffsets(MemberOffset reference_referent_offset,
   1862                                 MemberOffset reference_queue_offset,
   1863                                 MemberOffset reference_queueNext_offset,
   1864                                 MemberOffset reference_pendingNext_offset,
   1865                                 MemberOffset finalizer_reference_zombie_offset) {
   1866   reference_referent_offset_ = reference_referent_offset;
   1867   reference_queue_offset_ = reference_queue_offset;
   1868   reference_queueNext_offset_ = reference_queueNext_offset;
   1869   reference_pendingNext_offset_ = reference_pendingNext_offset;
   1870   finalizer_reference_zombie_offset_ = finalizer_reference_zombie_offset;
   1871   CHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
   1872   CHECK_NE(reference_queue_offset_.Uint32Value(), 0U);
   1873   CHECK_NE(reference_queueNext_offset_.Uint32Value(), 0U);
   1874   CHECK_NE(reference_pendingNext_offset_.Uint32Value(), 0U);
   1875   CHECK_NE(finalizer_reference_zombie_offset_.Uint32Value(), 0U);
   1876 }
   1877 
   1878 mirror::Object* Heap::GetReferenceReferent(mirror::Object* reference) {
   1879   DCHECK(reference != NULL);
   1880   DCHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
   1881   return reference->GetFieldObject<mirror::Object*>(reference_referent_offset_, true);
   1882 }
   1883 
   1884 void Heap::ClearReferenceReferent(mirror::Object* reference) {
   1885   DCHECK(reference != NULL);
   1886   DCHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
   1887   reference->SetFieldObject(reference_referent_offset_, NULL, true);
   1888 }
   1889 
   1890 // Returns true if the reference object has not yet been enqueued.
   1891 bool Heap::IsEnqueuable(const mirror::Object* ref) {
   1892   DCHECK(ref != NULL);
   1893   const mirror::Object* queue =
   1894       ref->GetFieldObject<mirror::Object*>(reference_queue_offset_, false);
   1895   const mirror::Object* queue_next =
   1896       ref->GetFieldObject<mirror::Object*>(reference_queueNext_offset_, false);
   1897   return (queue != NULL) && (queue_next == NULL);
   1898 }
   1899 
   1900 void Heap::EnqueueReference(mirror::Object* ref, mirror::Object** cleared_reference_list) {
   1901   DCHECK(ref != NULL);
   1902   CHECK(ref->GetFieldObject<mirror::Object*>(reference_queue_offset_, false) != NULL);
   1903   CHECK(ref->GetFieldObject<mirror::Object*>(reference_queueNext_offset_, false) == NULL);
   1904   EnqueuePendingReference(ref, cleared_reference_list);
   1905 }
   1906 
   1907 bool Heap::IsEnqueued(mirror::Object* ref) {
   1908   // Since the references are stored as cyclic lists it means that once enqueued, the pending next
   1909   // will always be non-null.
   1910   return ref->GetFieldObject<mirror::Object*>(GetReferencePendingNextOffset(), false) != nullptr;
   1911 }
   1912 
   1913 void Heap::EnqueuePendingReference(mirror::Object* ref, mirror::Object** list) {
   1914   DCHECK(ref != NULL);
   1915   DCHECK(list != NULL);
   1916   if (*list == NULL) {
   1917     // 1 element cyclic queue, ie: Reference ref = ..; ref.pendingNext = ref;
   1918     ref->SetFieldObject(reference_pendingNext_offset_, ref, false);
   1919     *list = ref;
   1920   } else {
   1921     mirror::Object* head =
   1922         (*list)->GetFieldObject<mirror::Object*>(reference_pendingNext_offset_, false);
   1923     ref->SetFieldObject(reference_pendingNext_offset_, head, false);
   1924     (*list)->SetFieldObject(reference_pendingNext_offset_, ref, false);
   1925   }
   1926 }
   1927 
   1928 mirror::Object* Heap::DequeuePendingReference(mirror::Object** list) {
   1929   DCHECK(list != NULL);
   1930   DCHECK(*list != NULL);
   1931   mirror::Object* head = (*list)->GetFieldObject<mirror::Object*>(reference_pendingNext_offset_,
   1932                                                                   false);
   1933   mirror::Object* ref;
   1934 
   1935   // Note: the following code is thread-safe because it is only called from ProcessReferences which
   1936   // is single threaded.
   1937   if (*list == head) {
   1938     ref = *list;
   1939     *list = NULL;
   1940   } else {
   1941     mirror::Object* next = head->GetFieldObject<mirror::Object*>(reference_pendingNext_offset_,
   1942                                                                  false);
   1943     (*list)->SetFieldObject(reference_pendingNext_offset_, next, false);
   1944     ref = head;
   1945   }
   1946   ref->SetFieldObject(reference_pendingNext_offset_, NULL, false);
   1947   return ref;
   1948 }
   1949 
   1950 void Heap::AddFinalizerReference(Thread* self, mirror::Object* object) {
   1951   ScopedObjectAccess soa(self);
   1952   JValue result;
   1953   ArgArray arg_array(NULL, 0);
   1954   arg_array.Append(reinterpret_cast<uint32_t>(object));
   1955   soa.DecodeMethod(WellKnownClasses::java_lang_ref_FinalizerReference_add)->Invoke(self,
   1956       arg_array.GetArray(), arg_array.GetNumBytes(), &result, 'V');
   1957 }
   1958 
   1959 void Heap::EnqueueClearedReferences(mirror::Object** cleared) {
   1960   DCHECK(cleared != NULL);
   1961   if (*cleared != NULL) {
   1962     // When a runtime isn't started there are no reference queues to care about so ignore.
   1963     if (LIKELY(Runtime::Current()->IsStarted())) {
   1964       ScopedObjectAccess soa(Thread::Current());
   1965       JValue result;
   1966       ArgArray arg_array(NULL, 0);
   1967       arg_array.Append(reinterpret_cast<uint32_t>(*cleared));
   1968       soa.DecodeMethod(WellKnownClasses::java_lang_ref_ReferenceQueue_add)->Invoke(soa.Self(),
   1969           arg_array.GetArray(), arg_array.GetNumBytes(), &result, 'V');
   1970     }
   1971     *cleared = NULL;
   1972   }
   1973 }
   1974 
   1975 void Heap::RequestConcurrentGC(Thread* self) {
   1976   // Make sure that we can do a concurrent GC.
   1977   Runtime* runtime = Runtime::Current();
   1978   DCHECK(concurrent_gc_);
   1979   if (runtime == NULL || !runtime->IsFinishedStarting() ||
   1980       !runtime->IsConcurrentGcEnabled()) {
   1981     return;
   1982   }
   1983   {
   1984     MutexLock mu(self, *Locks::runtime_shutdown_lock_);
   1985     if (runtime->IsShuttingDown()) {
   1986       return;
   1987     }
   1988   }
   1989   if (self->IsHandlingStackOverflow()) {
   1990     return;
   1991   }
   1992 
   1993   // We already have a request pending, no reason to start more until we update
   1994   // concurrent_start_bytes_.
   1995   concurrent_start_bytes_ = std::numeric_limits<size_t>::max();
   1996 
   1997   JNIEnv* env = self->GetJniEnv();
   1998   DCHECK(WellKnownClasses::java_lang_Daemons != NULL);
   1999   DCHECK(WellKnownClasses::java_lang_Daemons_requestGC != NULL);
   2000   env->CallStaticVoidMethod(WellKnownClasses::java_lang_Daemons,
   2001                             WellKnownClasses::java_lang_Daemons_requestGC);
   2002   CHECK(!env->ExceptionCheck());
   2003 }
   2004 
   2005 void Heap::ConcurrentGC(Thread* self) {
   2006   {
   2007     MutexLock mu(self, *Locks::runtime_shutdown_lock_);
   2008     if (Runtime::Current()->IsShuttingDown()) {
   2009       return;
   2010     }
   2011   }
   2012 
   2013   // Wait for any GCs currently running to finish.
   2014   if (WaitForConcurrentGcToComplete(self) == collector::kGcTypeNone) {
   2015     CollectGarbageInternal(next_gc_type_, kGcCauseBackground, false);
   2016   }
   2017 }
   2018 
   2019 void Heap::RequestHeapTrim() {
   2020   // GC completed and now we must decide whether to request a heap trim (advising pages back to the
   2021   // kernel) or not. Issuing a request will also cause trimming of the libc heap. As a trim scans
   2022   // a space it will hold its lock and can become a cause of jank.
   2023   // Note, the large object space self trims and the Zygote space was trimmed and unchanging since
   2024   // forking.
   2025 
   2026   // We don't have a good measure of how worthwhile a trim might be. We can't use the live bitmap
   2027   // because that only marks object heads, so a large array looks like lots of empty space. We
   2028   // don't just call dlmalloc all the time, because the cost of an _attempted_ trim is proportional
   2029   // to utilization (which is probably inversely proportional to how much benefit we can expect).
   2030   // We could try mincore(2) but that's only a measure of how many pages we haven't given away,
   2031   // not how much use we're making of those pages.
   2032   uint64_t ms_time = MilliTime();
   2033   float utilization =
   2034       static_cast<float>(alloc_space_->GetBytesAllocated()) / alloc_space_->Size();
   2035   if ((utilization > 0.75f && !IsLowMemoryMode()) || ((ms_time - last_trim_time_ms_) < 2 * 1000)) {
   2036     // Don't bother trimming the alloc space if it's more than 75% utilized and low memory mode is
   2037     // not enabled, or if a heap trim occurred in the last two seconds.
   2038     return;
   2039   }
   2040 
   2041   Thread* self = Thread::Current();
   2042   {
   2043     MutexLock mu(self, *Locks::runtime_shutdown_lock_);
   2044     Runtime* runtime = Runtime::Current();
   2045     if (runtime == NULL || !runtime->IsFinishedStarting() || runtime->IsShuttingDown()) {
   2046       // Heap trimming isn't supported without a Java runtime or Daemons (such as at dex2oat time)
   2047       // Also: we do not wish to start a heap trim if the runtime is shutting down (a racy check
   2048       // as we don't hold the lock while requesting the trim).
   2049       return;
   2050     }
   2051   }
   2052 
   2053   last_trim_time_ms_ = ms_time;
   2054   ListenForProcessStateChange();
   2055 
   2056   // Trim only if we do not currently care about pause times.
   2057   if (!care_about_pause_times_) {
   2058     JNIEnv* env = self->GetJniEnv();
   2059     DCHECK(WellKnownClasses::java_lang_Daemons != NULL);
   2060     DCHECK(WellKnownClasses::java_lang_Daemons_requestHeapTrim != NULL);
   2061     env->CallStaticVoidMethod(WellKnownClasses::java_lang_Daemons,
   2062                               WellKnownClasses::java_lang_Daemons_requestHeapTrim);
   2063     CHECK(!env->ExceptionCheck());
   2064   }
   2065 }
   2066 
   2067 size_t Heap::Trim() {
   2068   // Handle a requested heap trim on a thread outside of the main GC thread.
   2069   return alloc_space_->Trim();
   2070 }
   2071 
   2072 bool Heap::IsGCRequestPending() const {
   2073   return concurrent_start_bytes_ != std::numeric_limits<size_t>::max();
   2074 }
   2075 
   2076 void Heap::RegisterNativeAllocation(int bytes) {
   2077   // Total number of native bytes allocated.
   2078   native_bytes_allocated_.fetch_add(bytes);
   2079   Thread* self = Thread::Current();
   2080   if (static_cast<size_t>(native_bytes_allocated_) > native_footprint_gc_watermark_) {
   2081     // The second watermark is higher than the gc watermark. If you hit this it means you are
   2082     // allocating native objects faster than the GC can keep up with.
   2083     if (static_cast<size_t>(native_bytes_allocated_) > native_footprint_limit_) {
   2084         JNIEnv* env = self->GetJniEnv();
   2085         // Can't do this in WellKnownClasses::Init since System is not properly set up at that
   2086         // point.
   2087         if (WellKnownClasses::java_lang_System_runFinalization == NULL) {
   2088           DCHECK(WellKnownClasses::java_lang_System != NULL);
   2089           WellKnownClasses::java_lang_System_runFinalization =
   2090               CacheMethod(env, WellKnownClasses::java_lang_System, true, "runFinalization", "()V");
   2091           assert(WellKnownClasses::java_lang_System_runFinalization != NULL);
   2092         }
   2093         if (WaitForConcurrentGcToComplete(self) != collector::kGcTypeNone) {
   2094           // Just finished a GC, attempt to run finalizers.
   2095           env->CallStaticVoidMethod(WellKnownClasses::java_lang_System,
   2096                                     WellKnownClasses::java_lang_System_runFinalization);
   2097           CHECK(!env->ExceptionCheck());
   2098         }
   2099 
   2100         // If we still are over the watermark, attempt a GC for alloc and run finalizers.
   2101         if (static_cast<size_t>(native_bytes_allocated_) > native_footprint_limit_) {
   2102           CollectGarbageInternal(collector::kGcTypePartial, kGcCauseForAlloc, false);
   2103           env->CallStaticVoidMethod(WellKnownClasses::java_lang_System,
   2104                                     WellKnownClasses::java_lang_System_runFinalization);
   2105           CHECK(!env->ExceptionCheck());
   2106         }
   2107         // We have just run finalizers, update the native watermark since it is very likely that
   2108         // finalizers released native managed allocations.
   2109         UpdateMaxNativeFootprint();
   2110     } else {
   2111       if (!IsGCRequestPending()) {
   2112         RequestConcurrentGC(self);
   2113       }
   2114     }
   2115   }
   2116 }
   2117 
   2118 void Heap::RegisterNativeFree(int bytes) {
   2119   int expected_size, new_size;
   2120   do {
   2121       expected_size = native_bytes_allocated_.load();
   2122       new_size = expected_size - bytes;
   2123       if (new_size < 0) {
   2124         ThrowRuntimeException("attempted to free %d native bytes with only %d native bytes registered as allocated",
   2125                               bytes, expected_size);
   2126         break;
   2127       }
   2128   } while (!native_bytes_allocated_.compare_and_swap(expected_size, new_size));
   2129 }
   2130 
   2131 int64_t Heap::GetTotalMemory() const {
   2132   int64_t ret = 0;
   2133   for (const auto& space : continuous_spaces_) {
   2134     if (space->IsImageSpace()) {
   2135       // Currently don't include the image space.
   2136     } else if (space->IsDlMallocSpace()) {
   2137       // Zygote or alloc space
   2138       ret += space->AsDlMallocSpace()->GetFootprint();
   2139     }
   2140   }
   2141   for (const auto& space : discontinuous_spaces_) {
   2142     if (space->IsLargeObjectSpace()) {
   2143       ret += space->AsLargeObjectSpace()->GetBytesAllocated();
   2144     }
   2145   }
   2146   return ret;
   2147 }
   2148 
   2149 }  // namespace gc
   2150 }  // namespace art
   2151