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