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