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