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