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