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