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