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