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