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