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