heap.cc revision 4c7fc5950853b0c368e2148db77ced7c4d3c303c
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  DCHECK(klass != nullptr);
1229  StackHandleScope<1> hs(self);
1230  HandleWrapper<mirror::Class> h(hs.NewHandleWrapper(klass));
1231  klass = nullptr;  // Invalidate for safety.
1232  // The allocation failed. If the GC is running, block until it completes, and then retry the
1233  // allocation.
1234  collector::GcType last_gc = WaitForGcToComplete(kGcCauseForAlloc, self);
1235  if (last_gc != collector::kGcTypeNone) {
1236    // If we were the default allocator but the allocator changed while we were suspended,
1237    // abort the allocation.
1238    if (was_default_allocator && allocator != GetCurrentAllocator()) {
1239      return nullptr;
1240    }
1241    // A GC was in progress and we blocked, retry allocation now that memory has been freed.
1242    mirror::Object* ptr = TryToAllocate<true, false>(self, allocator, alloc_size, bytes_allocated,
1243                                                     usable_size);
1244    if (ptr != nullptr) {
1245      return ptr;
1246    }
1247  }
1248
1249  collector::GcType tried_type = next_gc_type_;
1250  const bool gc_ran =
1251      CollectGarbageInternal(tried_type, kGcCauseForAlloc, false) != collector::kGcTypeNone;
1252  if (was_default_allocator && allocator != GetCurrentAllocator()) {
1253    return nullptr;
1254  }
1255  if (gc_ran) {
1256    mirror::Object* ptr = TryToAllocate<true, false>(self, allocator, alloc_size, bytes_allocated,
1257                                                     usable_size);
1258    if (ptr != nullptr) {
1259      return ptr;
1260    }
1261  }
1262
1263  // Loop through our different Gc types and try to Gc until we get enough free memory.
1264  for (collector::GcType gc_type : gc_plan_) {
1265    if (gc_type == tried_type) {
1266      continue;
1267    }
1268    // Attempt to run the collector, if we succeed, re-try the allocation.
1269    const bool gc_ran =
1270        CollectGarbageInternal(gc_type, kGcCauseForAlloc, false) != collector::kGcTypeNone;
1271    if (was_default_allocator && allocator != GetCurrentAllocator()) {
1272      return nullptr;
1273    }
1274    if (gc_ran) {
1275      // Did we free sufficient memory for the allocation to succeed?
1276      mirror::Object* ptr = TryToAllocate<true, false>(self, allocator, alloc_size, bytes_allocated,
1277                                                       usable_size);
1278      if (ptr != nullptr) {
1279        return ptr;
1280      }
1281    }
1282  }
1283  // Allocations have failed after GCs;  this is an exceptional state.
1284  // Try harder, growing the heap if necessary.
1285  mirror::Object* ptr = TryToAllocate<true, true>(self, allocator, alloc_size, bytes_allocated,
1286                                                  usable_size);
1287  if (ptr != nullptr) {
1288    return ptr;
1289  }
1290  // Most allocations should have succeeded by now, so the heap is really full, really fragmented,
1291  // or the requested size is really big. Do another GC, collecting SoftReferences this time. The
1292  // VM spec requires that all SoftReferences have been collected and cleared before throwing
1293  // OOME.
1294  VLOG(gc) << "Forcing collection of SoftReferences for " << PrettySize(alloc_size)
1295           << " allocation";
1296  // TODO: Run finalization, but this may cause more allocations to occur.
1297  // We don't need a WaitForGcToComplete here either.
1298  DCHECK(!gc_plan_.empty());
1299  CollectGarbageInternal(gc_plan_.back(), kGcCauseForAlloc, true);
1300  if (was_default_allocator && allocator != GetCurrentAllocator()) {
1301    return nullptr;
1302  }
1303  ptr = TryToAllocate<true, true>(self, allocator, alloc_size, bytes_allocated, usable_size);
1304  if (ptr == nullptr) {
1305    const uint64_t current_time = NanoTime();
1306    switch (allocator) {
1307      case kAllocatorTypeRosAlloc:
1308        // Fall-through.
1309      case kAllocatorTypeDlMalloc: {
1310        if (use_homogeneous_space_compaction_for_oom_ &&
1311            current_time - last_time_homogeneous_space_compaction_by_oom_ >
1312            min_interval_homogeneous_space_compaction_by_oom_) {
1313          last_time_homogeneous_space_compaction_by_oom_ = current_time;
1314          HomogeneousSpaceCompactResult result = PerformHomogeneousSpaceCompact();
1315          switch (result) {
1316            case HomogeneousSpaceCompactResult::kSuccess:
1317              // If the allocation succeeded, we delayed an oom.
1318              ptr = TryToAllocate<true, true>(self, allocator, alloc_size, bytes_allocated,
1319                                              usable_size);
1320              if (ptr != nullptr) {
1321                count_delayed_oom_++;
1322              }
1323              break;
1324            case HomogeneousSpaceCompactResult::kErrorReject:
1325              // Reject due to disabled moving GC.
1326              break;
1327            case HomogeneousSpaceCompactResult::kErrorVMShuttingDown:
1328              // Throw OOM by default.
1329              break;
1330            default: {
1331              LOG(FATAL) << "Unimplemented homogeneous space compaction result "
1332                         << static_cast<size_t>(result);
1333            }
1334          }
1335          // Always print that we ran homogeneous space compation since this can cause jank.
1336          VLOG(heap) << "Ran heap homogeneous space compaction, "
1337                    << " requested defragmentation "
1338                    << count_requested_homogeneous_space_compaction_.LoadSequentiallyConsistent()
1339                    << " performed defragmentation "
1340                    << count_performed_homogeneous_space_compaction_.LoadSequentiallyConsistent()
1341                    << " ignored homogeneous space compaction "
1342                    << count_ignored_homogeneous_space_compaction_.LoadSequentiallyConsistent()
1343                    << " delayed count = "
1344                    << count_delayed_oom_.LoadSequentiallyConsistent();
1345        }
1346        break;
1347      }
1348      case kAllocatorTypeNonMoving: {
1349        // Try to transition the heap if the allocation failure was due to the space being full.
1350        if (!IsOutOfMemoryOnAllocation<false>(allocator, alloc_size)) {
1351          // If we aren't out of memory then the OOM was probably from the non moving space being
1352          // full. Attempt to disable compaction and turn the main space into a non moving space.
1353          DisableMovingGc();
1354          // If we are still a moving GC then something must have caused the transition to fail.
1355          if (IsMovingGc(collector_type_)) {
1356            MutexLock mu(self, *gc_complete_lock_);
1357            // If we couldn't disable moving GC, just throw OOME and return null.
1358            LOG(WARNING) << "Couldn't disable moving GC with disable GC count "
1359                         << disable_moving_gc_count_;
1360          } else {
1361            LOG(WARNING) << "Disabled moving GC due to the non moving space being full";
1362            ptr = TryToAllocate<true, true>(self, allocator, alloc_size, bytes_allocated,
1363                                            usable_size);
1364          }
1365        }
1366        break;
1367      }
1368      default: {
1369        // Do nothing for others allocators.
1370      }
1371    }
1372  }
1373  // If the allocation hasn't succeeded by this point, throw an OOM error.
1374  if (ptr == nullptr) {
1375    ThrowOutOfMemoryError(self, alloc_size, allocator);
1376  }
1377  return ptr;
1378}
1379
1380void Heap::SetTargetHeapUtilization(float target) {
1381  DCHECK_GT(target, 0.0f);  // asserted in Java code
1382  DCHECK_LT(target, 1.0f);
1383  target_utilization_ = target;
1384}
1385
1386size_t Heap::GetObjectsAllocated() const {
1387  size_t total = 0;
1388  for (space::AllocSpace* space : alloc_spaces_) {
1389    total += space->GetObjectsAllocated();
1390  }
1391  return total;
1392}
1393
1394uint64_t Heap::GetObjectsAllocatedEver() const {
1395  return GetObjectsFreedEver() + GetObjectsAllocated();
1396}
1397
1398uint64_t Heap::GetBytesAllocatedEver() const {
1399  return GetBytesFreedEver() + GetBytesAllocated();
1400}
1401
1402class InstanceCounter {
1403 public:
1404  InstanceCounter(const std::vector<mirror::Class*>& classes, bool use_is_assignable_from, uint64_t* counts)
1405      SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
1406      : classes_(classes), use_is_assignable_from_(use_is_assignable_from), counts_(counts) {
1407  }
1408  static void Callback(mirror::Object* obj, void* arg)
1409      SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
1410    InstanceCounter* instance_counter = reinterpret_cast<InstanceCounter*>(arg);
1411    mirror::Class* instance_class = obj->GetClass();
1412    CHECK(instance_class != nullptr);
1413    for (size_t i = 0; i < instance_counter->classes_.size(); ++i) {
1414      if (instance_counter->use_is_assignable_from_) {
1415        if (instance_counter->classes_[i]->IsAssignableFrom(instance_class)) {
1416          ++instance_counter->counts_[i];
1417        }
1418      } else if (instance_class == instance_counter->classes_[i]) {
1419        ++instance_counter->counts_[i];
1420      }
1421    }
1422  }
1423
1424 private:
1425  const std::vector<mirror::Class*>& classes_;
1426  bool use_is_assignable_from_;
1427  uint64_t* const counts_;
1428  DISALLOW_COPY_AND_ASSIGN(InstanceCounter);
1429};
1430
1431void Heap::CountInstances(const std::vector<mirror::Class*>& classes, bool use_is_assignable_from,
1432                          uint64_t* counts) {
1433  // Can't do any GC in this function since this may move classes.
1434  Thread* self = Thread::Current();
1435  auto* old_cause = self->StartAssertNoThreadSuspension("CountInstances");
1436  InstanceCounter counter(classes, use_is_assignable_from, counts);
1437  WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
1438  VisitObjects(InstanceCounter::Callback, &counter);
1439  self->EndAssertNoThreadSuspension(old_cause);
1440}
1441
1442class InstanceCollector {
1443 public:
1444  InstanceCollector(mirror::Class* c, int32_t max_count, std::vector<mirror::Object*>& instances)
1445      SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
1446      : class_(c), max_count_(max_count), instances_(instances) {
1447  }
1448  static void Callback(mirror::Object* obj, void* arg)
1449      SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
1450    DCHECK(arg != nullptr);
1451    InstanceCollector* instance_collector = reinterpret_cast<InstanceCollector*>(arg);
1452    mirror::Class* instance_class = obj->GetClass();
1453    if (instance_class == instance_collector->class_) {
1454      if (instance_collector->max_count_ == 0 ||
1455          instance_collector->instances_.size() < instance_collector->max_count_) {
1456        instance_collector->instances_.push_back(obj);
1457      }
1458    }
1459  }
1460
1461 private:
1462  mirror::Class* class_;
1463  uint32_t max_count_;
1464  std::vector<mirror::Object*>& instances_;
1465  DISALLOW_COPY_AND_ASSIGN(InstanceCollector);
1466};
1467
1468void Heap::GetInstances(mirror::Class* c, int32_t max_count,
1469                        std::vector<mirror::Object*>& instances) {
1470  // Can't do any GC in this function since this may move classes.
1471  Thread* self = Thread::Current();
1472  auto* old_cause = self->StartAssertNoThreadSuspension("GetInstances");
1473  InstanceCollector collector(c, max_count, instances);
1474  WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
1475  VisitObjects(&InstanceCollector::Callback, &collector);
1476  self->EndAssertNoThreadSuspension(old_cause);
1477}
1478
1479class ReferringObjectsFinder {
1480 public:
1481  ReferringObjectsFinder(mirror::Object* object, int32_t max_count,
1482                         std::vector<mirror::Object*>& referring_objects)
1483      SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
1484      : object_(object), max_count_(max_count), referring_objects_(referring_objects) {
1485  }
1486
1487  static void Callback(mirror::Object* obj, void* arg)
1488      SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
1489    reinterpret_cast<ReferringObjectsFinder*>(arg)->operator()(obj);
1490  }
1491
1492  // For bitmap Visit.
1493  // TODO: Fix lock analysis to not use NO_THREAD_SAFETY_ANALYSIS, requires support for
1494  // annotalysis on visitors.
1495  void operator()(mirror::Object* o) const NO_THREAD_SAFETY_ANALYSIS {
1496    o->VisitReferences<true>(*this, VoidFunctor());
1497  }
1498
1499  // For Object::VisitReferences.
1500  void operator()(mirror::Object* obj, MemberOffset offset, bool /* is_static */) const
1501      SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1502    mirror::Object* ref = obj->GetFieldObject<mirror::Object>(offset);
1503    if (ref == object_ && (max_count_ == 0 || referring_objects_.size() < max_count_)) {
1504      referring_objects_.push_back(obj);
1505    }
1506  }
1507
1508 private:
1509  mirror::Object* object_;
1510  uint32_t max_count_;
1511  std::vector<mirror::Object*>& referring_objects_;
1512  DISALLOW_COPY_AND_ASSIGN(ReferringObjectsFinder);
1513};
1514
1515void Heap::GetReferringObjects(mirror::Object* o, int32_t max_count,
1516                               std::vector<mirror::Object*>& referring_objects) {
1517  // Can't do any GC in this function since this may move the object o.
1518  Thread* self = Thread::Current();
1519  auto* old_cause = self->StartAssertNoThreadSuspension("GetReferringObjects");
1520  ReferringObjectsFinder finder(o, max_count, referring_objects);
1521  WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
1522  VisitObjects(&ReferringObjectsFinder::Callback, &finder);
1523  self->EndAssertNoThreadSuspension(old_cause);
1524}
1525
1526void Heap::CollectGarbage(bool clear_soft_references) {
1527  // Even if we waited for a GC we still need to do another GC since weaks allocated during the
1528  // last GC will not have necessarily been cleared.
1529  CollectGarbageInternal(gc_plan_.back(), kGcCauseExplicit, clear_soft_references);
1530}
1531
1532HomogeneousSpaceCompactResult Heap::PerformHomogeneousSpaceCompact() {
1533  Thread* self = Thread::Current();
1534  // Inc requested homogeneous space compaction.
1535  count_requested_homogeneous_space_compaction_++;
1536  // Store performed homogeneous space compaction at a new request arrival.
1537  ThreadList* tl = Runtime::Current()->GetThreadList();
1538  ScopedThreadStateChange tsc(self, kWaitingPerformingGc);
1539  Locks::mutator_lock_->AssertNotHeld(self);
1540  {
1541    ScopedThreadStateChange tsc(self, kWaitingForGcToComplete);
1542    MutexLock mu(self, *gc_complete_lock_);
1543    // Ensure there is only one GC at a time.
1544    WaitForGcToCompleteLocked(kGcCauseHomogeneousSpaceCompact, self);
1545    // Homogeneous space compaction is a copying transition, can't run it if the moving GC disable count
1546    // is non zero.
1547    // If the collector type changed to something which doesn't benefit from homogeneous space compaction,
1548    // exit.
1549    if (disable_moving_gc_count_ != 0 || IsMovingGc(collector_type_) ||
1550        !main_space_->CanMoveObjects()) {
1551      return HomogeneousSpaceCompactResult::kErrorReject;
1552    }
1553    collector_type_running_ = kCollectorTypeHomogeneousSpaceCompact;
1554  }
1555  if (Runtime::Current()->IsShuttingDown(self)) {
1556    // Don't allow heap transitions to happen if the runtime is shutting down since these can
1557    // cause objects to get finalized.
1558    FinishGC(self, collector::kGcTypeNone);
1559    return HomogeneousSpaceCompactResult::kErrorVMShuttingDown;
1560  }
1561  // Suspend all threads.
1562  tl->SuspendAll();
1563  uint64_t start_time = NanoTime();
1564  // Launch compaction.
1565  space::MallocSpace* to_space = main_space_backup_.release();
1566  space::MallocSpace* from_space = main_space_;
1567  to_space->GetMemMap()->Protect(PROT_READ | PROT_WRITE);
1568  const uint64_t space_size_before_compaction = from_space->Size();
1569  AddSpace(to_space);
1570  Compact(to_space, from_space, kGcCauseHomogeneousSpaceCompact);
1571  // Leave as prot read so that we can still run ROSAlloc verification on this space.
1572  from_space->GetMemMap()->Protect(PROT_READ);
1573  const uint64_t space_size_after_compaction = to_space->Size();
1574  main_space_ = to_space;
1575  main_space_backup_.reset(from_space);
1576  RemoveSpace(from_space);
1577  SetSpaceAsDefault(main_space_);  // Set as default to reset the proper dlmalloc space.
1578  // Update performed homogeneous space compaction count.
1579  count_performed_homogeneous_space_compaction_++;
1580  // Print statics log and resume all threads.
1581  uint64_t duration = NanoTime() - start_time;
1582  VLOG(heap) << "Heap homogeneous space compaction took " << PrettyDuration(duration) << " size: "
1583             << PrettySize(space_size_before_compaction) << " -> "
1584             << PrettySize(space_size_after_compaction) << " compact-ratio: "
1585             << std::fixed << static_cast<double>(space_size_after_compaction) /
1586             static_cast<double>(space_size_before_compaction);
1587  tl->ResumeAll();
1588  // Finish GC.
1589  reference_processor_.EnqueueClearedReferences(self);
1590  GrowForUtilization(semi_space_collector_);
1591  FinishGC(self, collector::kGcTypeFull);
1592  return HomogeneousSpaceCompactResult::kSuccess;
1593}
1594
1595
1596void Heap::TransitionCollector(CollectorType collector_type) {
1597  if (collector_type == collector_type_) {
1598    return;
1599  }
1600  VLOG(heap) << "TransitionCollector: " << static_cast<int>(collector_type_)
1601             << " -> " << static_cast<int>(collector_type);
1602  uint64_t start_time = NanoTime();
1603  uint32_t before_allocated = num_bytes_allocated_.LoadSequentiallyConsistent();
1604  Runtime* const runtime = Runtime::Current();
1605  ThreadList* const tl = runtime->GetThreadList();
1606  Thread* const self = Thread::Current();
1607  ScopedThreadStateChange tsc(self, kWaitingPerformingGc);
1608  Locks::mutator_lock_->AssertNotHeld(self);
1609  // Busy wait until we can GC (StartGC can fail if we have a non-zero
1610  // compacting_gc_disable_count_, this should rarely occurs).
1611  for (;;) {
1612    {
1613      ScopedThreadStateChange tsc(self, kWaitingForGcToComplete);
1614      MutexLock mu(self, *gc_complete_lock_);
1615      // Ensure there is only one GC at a time.
1616      WaitForGcToCompleteLocked(kGcCauseCollectorTransition, self);
1617      // Currently we only need a heap transition if we switch from a moving collector to a
1618      // non-moving one, or visa versa.
1619      const bool copying_transition = IsMovingGc(collector_type_) != IsMovingGc(collector_type);
1620      // If someone else beat us to it and changed the collector before we could, exit.
1621      // This is safe to do before the suspend all since we set the collector_type_running_ before
1622      // we exit the loop. If another thread attempts to do the heap transition before we exit,
1623      // then it would get blocked on WaitForGcToCompleteLocked.
1624      if (collector_type == collector_type_) {
1625        return;
1626      }
1627      // GC can be disabled if someone has a used GetPrimitiveArrayCritical but not yet released.
1628      if (!copying_transition || disable_moving_gc_count_ == 0) {
1629        // TODO: Not hard code in semi-space collector?
1630        collector_type_running_ = copying_transition ? kCollectorTypeSS : collector_type;
1631        break;
1632      }
1633    }
1634    usleep(1000);
1635  }
1636  if (runtime->IsShuttingDown(self)) {
1637    // Don't allow heap transitions to happen if the runtime is shutting down since these can
1638    // cause objects to get finalized.
1639    FinishGC(self, collector::kGcTypeNone);
1640    return;
1641  }
1642  tl->SuspendAll();
1643  switch (collector_type) {
1644    case kCollectorTypeSS: {
1645      if (!IsMovingGc(collector_type_)) {
1646        // Create the bump pointer space from the backup space.
1647        CHECK(main_space_backup_ != nullptr);
1648        std::unique_ptr<MemMap> mem_map(main_space_backup_->ReleaseMemMap());
1649        // We are transitioning from non moving GC -> moving GC, since we copied from the bump
1650        // pointer space last transition it will be protected.
1651        CHECK(mem_map != nullptr);
1652        mem_map->Protect(PROT_READ | PROT_WRITE);
1653        bump_pointer_space_ = space::BumpPointerSpace::CreateFromMemMap("Bump pointer space",
1654                                                                        mem_map.release());
1655        AddSpace(bump_pointer_space_);
1656        Compact(bump_pointer_space_, main_space_, kGcCauseCollectorTransition);
1657        // Use the now empty main space mem map for the bump pointer temp space.
1658        mem_map.reset(main_space_->ReleaseMemMap());
1659        // Unset the pointers just in case.
1660        if (dlmalloc_space_ == main_space_) {
1661          dlmalloc_space_ = nullptr;
1662        } else if (rosalloc_space_ == main_space_) {
1663          rosalloc_space_ = nullptr;
1664        }
1665        // Remove the main space so that we don't try to trim it, this doens't work for debug
1666        // builds since RosAlloc attempts to read the magic number from a protected page.
1667        RemoveSpace(main_space_);
1668        RemoveRememberedSet(main_space_);
1669        delete main_space_;  // Delete the space since it has been removed.
1670        main_space_ = nullptr;
1671        RemoveRememberedSet(main_space_backup_.get());
1672        main_space_backup_.reset(nullptr);  // Deletes the space.
1673        temp_space_ = space::BumpPointerSpace::CreateFromMemMap("Bump pointer space 2",
1674                                                                mem_map.release());
1675        AddSpace(temp_space_);
1676      }
1677      break;
1678    }
1679    case kCollectorTypeMS:
1680      // Fall through.
1681    case kCollectorTypeCMS: {
1682      if (IsMovingGc(collector_type_)) {
1683        CHECK(temp_space_ != nullptr);
1684        std::unique_ptr<MemMap> mem_map(temp_space_->ReleaseMemMap());
1685        RemoveSpace(temp_space_);
1686        temp_space_ = nullptr;
1687        mem_map->Protect(PROT_READ | PROT_WRITE);
1688        CreateMainMallocSpace(mem_map.get(), kDefaultInitialSize, mem_map->Size(),
1689                              mem_map->Size());
1690        mem_map.release();
1691        // Compact to the main space from the bump pointer space, don't need to swap semispaces.
1692        AddSpace(main_space_);
1693        Compact(main_space_, bump_pointer_space_, kGcCauseCollectorTransition);
1694        mem_map.reset(bump_pointer_space_->ReleaseMemMap());
1695        RemoveSpace(bump_pointer_space_);
1696        bump_pointer_space_ = nullptr;
1697        const char* name = kUseRosAlloc ? kRosAllocSpaceName[1] : kDlMallocSpaceName[1];
1698        // Temporarily unprotect the backup mem map so rosalloc can write the debug magic number.
1699        if (kIsDebugBuild && kUseRosAlloc) {
1700          mem_map->Protect(PROT_READ | PROT_WRITE);
1701        }
1702        main_space_backup_.reset(CreateMallocSpaceFromMemMap(mem_map.get(), kDefaultInitialSize,
1703                                                             mem_map->Size(), mem_map->Size(),
1704                                                             name, true));
1705        if (kIsDebugBuild && kUseRosAlloc) {
1706          mem_map->Protect(PROT_NONE);
1707        }
1708        mem_map.release();
1709      }
1710      break;
1711    }
1712    default: {
1713      LOG(FATAL) << "Attempted to transition to invalid collector type "
1714                 << static_cast<size_t>(collector_type);
1715      break;
1716    }
1717  }
1718  ChangeCollector(collector_type);
1719  tl->ResumeAll();
1720  // Can't call into java code with all threads suspended.
1721  reference_processor_.EnqueueClearedReferences(self);
1722  uint64_t duration = NanoTime() - start_time;
1723  GrowForUtilization(semi_space_collector_);
1724  FinishGC(self, collector::kGcTypeFull);
1725  int32_t after_allocated = num_bytes_allocated_.LoadSequentiallyConsistent();
1726  int32_t delta_allocated = before_allocated - after_allocated;
1727  std::string saved_str;
1728  if (delta_allocated >= 0) {
1729    saved_str = " saved at least " + PrettySize(delta_allocated);
1730  } else {
1731    saved_str = " expanded " + PrettySize(-delta_allocated);
1732  }
1733  VLOG(heap) << "Heap transition to " << process_state_ << " took "
1734      << PrettyDuration(duration) << saved_str;
1735}
1736
1737void Heap::ChangeCollector(CollectorType collector_type) {
1738  // TODO: Only do this with all mutators suspended to avoid races.
1739  if (collector_type != collector_type_) {
1740    if (collector_type == kCollectorTypeMC) {
1741      // Don't allow mark compact unless support is compiled in.
1742      CHECK(kMarkCompactSupport);
1743    }
1744    collector_type_ = collector_type;
1745    gc_plan_.clear();
1746    switch (collector_type_) {
1747      case kCollectorTypeCC:  // Fall-through.
1748      case kCollectorTypeMC:  // Fall-through.
1749      case kCollectorTypeSS:  // Fall-through.
1750      case kCollectorTypeGSS: {
1751        gc_plan_.push_back(collector::kGcTypeFull);
1752        if (use_tlab_) {
1753          ChangeAllocator(kAllocatorTypeTLAB);
1754        } else {
1755          ChangeAllocator(kAllocatorTypeBumpPointer);
1756        }
1757        break;
1758      }
1759      case kCollectorTypeMS: {
1760        gc_plan_.push_back(collector::kGcTypeSticky);
1761        gc_plan_.push_back(collector::kGcTypePartial);
1762        gc_plan_.push_back(collector::kGcTypeFull);
1763        ChangeAllocator(kUseRosAlloc ? kAllocatorTypeRosAlloc : kAllocatorTypeDlMalloc);
1764        break;
1765      }
1766      case kCollectorTypeCMS: {
1767        gc_plan_.push_back(collector::kGcTypeSticky);
1768        gc_plan_.push_back(collector::kGcTypePartial);
1769        gc_plan_.push_back(collector::kGcTypeFull);
1770        ChangeAllocator(kUseRosAlloc ? kAllocatorTypeRosAlloc : kAllocatorTypeDlMalloc);
1771        break;
1772      }
1773      default: {
1774        LOG(FATAL) << "Unimplemented";
1775      }
1776    }
1777    if (IsGcConcurrent()) {
1778      concurrent_start_bytes_ =
1779          std::max(max_allowed_footprint_, kMinConcurrentRemainingBytes) - kMinConcurrentRemainingBytes;
1780    } else {
1781      concurrent_start_bytes_ = std::numeric_limits<size_t>::max();
1782    }
1783  }
1784}
1785
1786// Special compacting collector which uses sub-optimal bin packing to reduce zygote space size.
1787class ZygoteCompactingCollector FINAL : public collector::SemiSpace {
1788 public:
1789  explicit ZygoteCompactingCollector(gc::Heap* heap) : SemiSpace(heap, false, "zygote collector"),
1790      bin_live_bitmap_(nullptr), bin_mark_bitmap_(nullptr) {
1791  }
1792
1793  void BuildBins(space::ContinuousSpace* space) {
1794    bin_live_bitmap_ = space->GetLiveBitmap();
1795    bin_mark_bitmap_ = space->GetMarkBitmap();
1796    BinContext context;
1797    context.prev_ = reinterpret_cast<uintptr_t>(space->Begin());
1798    context.collector_ = this;
1799    WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
1800    // Note: This requires traversing the space in increasing order of object addresses.
1801    bin_live_bitmap_->Walk(Callback, reinterpret_cast<void*>(&context));
1802    // Add the last bin which spans after the last object to the end of the space.
1803    AddBin(reinterpret_cast<uintptr_t>(space->End()) - context.prev_, context.prev_);
1804  }
1805
1806 private:
1807  struct BinContext {
1808    uintptr_t prev_;  // The end of the previous object.
1809    ZygoteCompactingCollector* collector_;
1810  };
1811  // Maps from bin sizes to locations.
1812  std::multimap<size_t, uintptr_t> bins_;
1813  // Live bitmap of the space which contains the bins.
1814  accounting::ContinuousSpaceBitmap* bin_live_bitmap_;
1815  // Mark bitmap of the space which contains the bins.
1816  accounting::ContinuousSpaceBitmap* bin_mark_bitmap_;
1817
1818  static void Callback(mirror::Object* obj, void* arg)
1819      SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1820    DCHECK(arg != nullptr);
1821    BinContext* context = reinterpret_cast<BinContext*>(arg);
1822    ZygoteCompactingCollector* collector = context->collector_;
1823    uintptr_t object_addr = reinterpret_cast<uintptr_t>(obj);
1824    size_t bin_size = object_addr - context->prev_;
1825    // Add the bin consisting of the end of the previous object to the start of the current object.
1826    collector->AddBin(bin_size, context->prev_);
1827    context->prev_ = object_addr + RoundUp(obj->SizeOf(), kObjectAlignment);
1828  }
1829
1830  void AddBin(size_t size, uintptr_t position) {
1831    if (size != 0) {
1832      bins_.insert(std::make_pair(size, position));
1833    }
1834  }
1835
1836  virtual bool ShouldSweepSpace(space::ContinuousSpace* space) const {
1837    // Don't sweep any spaces since we probably blasted the internal accounting of the free list
1838    // allocator.
1839    return false;
1840  }
1841
1842  virtual mirror::Object* MarkNonForwardedObject(mirror::Object* obj)
1843      EXCLUSIVE_LOCKS_REQUIRED(Locks::heap_bitmap_lock_, Locks::mutator_lock_) {
1844    size_t object_size = RoundUp(obj->SizeOf(), kObjectAlignment);
1845    mirror::Object* forward_address;
1846    // Find the smallest bin which we can move obj in.
1847    auto it = bins_.lower_bound(object_size);
1848    if (it == bins_.end()) {
1849      // No available space in the bins, place it in the target space instead (grows the zygote
1850      // space).
1851      size_t bytes_allocated;
1852      forward_address = to_space_->Alloc(self_, object_size, &bytes_allocated, nullptr);
1853      if (to_space_live_bitmap_ != nullptr) {
1854        to_space_live_bitmap_->Set(forward_address);
1855      } else {
1856        GetHeap()->GetNonMovingSpace()->GetLiveBitmap()->Set(forward_address);
1857        GetHeap()->GetNonMovingSpace()->GetMarkBitmap()->Set(forward_address);
1858      }
1859    } else {
1860      size_t size = it->first;
1861      uintptr_t pos = it->second;
1862      bins_.erase(it);  // Erase the old bin which we replace with the new smaller bin.
1863      forward_address = reinterpret_cast<mirror::Object*>(pos);
1864      // Set the live and mark bits so that sweeping system weaks works properly.
1865      bin_live_bitmap_->Set(forward_address);
1866      bin_mark_bitmap_->Set(forward_address);
1867      DCHECK_GE(size, object_size);
1868      AddBin(size - object_size, pos + object_size);  // Add a new bin with the remaining space.
1869    }
1870    // Copy the object over to its new location.
1871    memcpy(reinterpret_cast<void*>(forward_address), obj, object_size);
1872    if (kUseBakerOrBrooksReadBarrier) {
1873      obj->AssertReadBarrierPointer();
1874      if (kUseBrooksReadBarrier) {
1875        DCHECK_EQ(forward_address->GetReadBarrierPointer(), obj);
1876        forward_address->SetReadBarrierPointer(forward_address);
1877      }
1878      forward_address->AssertReadBarrierPointer();
1879    }
1880    return forward_address;
1881  }
1882};
1883
1884void Heap::UnBindBitmaps() {
1885  TimingLogger::ScopedTiming t("UnBindBitmaps", GetCurrentGcIteration()->GetTimings());
1886  for (const auto& space : GetContinuousSpaces()) {
1887    if (space->IsContinuousMemMapAllocSpace()) {
1888      space::ContinuousMemMapAllocSpace* alloc_space = space->AsContinuousMemMapAllocSpace();
1889      if (alloc_space->HasBoundBitmaps()) {
1890        alloc_space->UnBindBitmaps();
1891      }
1892    }
1893  }
1894}
1895
1896void Heap::PreZygoteFork() {
1897  CollectGarbageInternal(collector::kGcTypeFull, kGcCauseBackground, false);
1898  Thread* self = Thread::Current();
1899  MutexLock mu(self, zygote_creation_lock_);
1900  // Try to see if we have any Zygote spaces.
1901  if (have_zygote_space_) {
1902    return;
1903  }
1904  VLOG(heap) << "Starting PreZygoteFork";
1905  // Trim the pages at the end of the non moving space.
1906  non_moving_space_->Trim();
1907  // The end of the non-moving space may be protected, unprotect it so that we can copy the zygote
1908  // there.
1909  non_moving_space_->GetMemMap()->Protect(PROT_READ | PROT_WRITE);
1910  const bool same_space = non_moving_space_ == main_space_;
1911  if (kCompactZygote) {
1912    // Can't compact if the non moving space is the same as the main space.
1913    DCHECK(semi_space_collector_ != nullptr);
1914    // Temporarily disable rosalloc verification because the zygote
1915    // compaction will mess up the rosalloc internal metadata.
1916    ScopedDisableRosAllocVerification disable_rosalloc_verif(this);
1917    ZygoteCompactingCollector zygote_collector(this);
1918    zygote_collector.BuildBins(non_moving_space_);
1919    // Create a new bump pointer space which we will compact into.
1920    space::BumpPointerSpace target_space("zygote bump space", non_moving_space_->End(),
1921                                         non_moving_space_->Limit());
1922    // Compact the bump pointer space to a new zygote bump pointer space.
1923    bool reset_main_space = false;
1924    if (IsMovingGc(collector_type_)) {
1925      zygote_collector.SetFromSpace(bump_pointer_space_);
1926    } else {
1927      CHECK(main_space_ != nullptr);
1928      // Copy from the main space.
1929      zygote_collector.SetFromSpace(main_space_);
1930      reset_main_space = true;
1931    }
1932    zygote_collector.SetToSpace(&target_space);
1933    zygote_collector.SetSwapSemiSpaces(false);
1934    zygote_collector.Run(kGcCauseCollectorTransition, false);
1935    if (reset_main_space) {
1936      main_space_->GetMemMap()->Protect(PROT_READ | PROT_WRITE);
1937      madvise(main_space_->Begin(), main_space_->Capacity(), MADV_DONTNEED);
1938      MemMap* mem_map = main_space_->ReleaseMemMap();
1939      RemoveSpace(main_space_);
1940      space::Space* old_main_space = main_space_;
1941      CreateMainMallocSpace(mem_map, kDefaultInitialSize, mem_map->Size(), mem_map->Size());
1942      delete old_main_space;
1943      AddSpace(main_space_);
1944    } else {
1945      bump_pointer_space_->GetMemMap()->Protect(PROT_READ | PROT_WRITE);
1946    }
1947    if (temp_space_ != nullptr) {
1948      CHECK(temp_space_->IsEmpty());
1949    }
1950    total_objects_freed_ever_ += GetCurrentGcIteration()->GetFreedObjects();
1951    total_bytes_freed_ever_ += GetCurrentGcIteration()->GetFreedBytes();
1952    // Update the end and write out image.
1953    non_moving_space_->SetEnd(target_space.End());
1954    non_moving_space_->SetLimit(target_space.Limit());
1955    VLOG(heap) << "Zygote space size " << non_moving_space_->Size() << " bytes";
1956  }
1957  // Change the collector to the post zygote one.
1958  ChangeCollector(foreground_collector_type_);
1959  // Save the old space so that we can remove it after we complete creating the zygote space.
1960  space::MallocSpace* old_alloc_space = non_moving_space_;
1961  // Turn the current alloc space into a zygote space and obtain the new alloc space composed of
1962  // the remaining available space.
1963  // Remove the old space before creating the zygote space since creating the zygote space sets
1964  // the old alloc space's bitmaps to nullptr.
1965  RemoveSpace(old_alloc_space);
1966  if (collector::SemiSpace::kUseRememberedSet) {
1967    // Sanity bound check.
1968    FindRememberedSetFromSpace(old_alloc_space)->AssertAllDirtyCardsAreWithinSpace();
1969    // Remove the remembered set for the now zygote space (the old
1970    // non-moving space). Note now that we have compacted objects into
1971    // the zygote space, the data in the remembered set is no longer
1972    // needed. The zygote space will instead have a mod-union table
1973    // from this point on.
1974    RemoveRememberedSet(old_alloc_space);
1975  }
1976  space::ZygoteSpace* zygote_space = old_alloc_space->CreateZygoteSpace("alloc space",
1977                                                                        low_memory_mode_,
1978                                                                        &non_moving_space_);
1979  CHECK(!non_moving_space_->CanMoveObjects());
1980  if (same_space) {
1981    main_space_ = non_moving_space_;
1982    SetSpaceAsDefault(main_space_);
1983  }
1984  delete old_alloc_space;
1985  CHECK(zygote_space != nullptr) << "Failed creating zygote space";
1986  AddSpace(zygote_space);
1987  non_moving_space_->SetFootprintLimit(non_moving_space_->Capacity());
1988  AddSpace(non_moving_space_);
1989  have_zygote_space_ = true;
1990  // Enable large object space allocations.
1991  large_object_threshold_ = kDefaultLargeObjectThreshold;
1992  // Create the zygote space mod union table.
1993  accounting::ModUnionTable* mod_union_table =
1994      new accounting::ModUnionTableCardCache("zygote space mod-union table", this, zygote_space);
1995  CHECK(mod_union_table != nullptr) << "Failed to create zygote space mod-union table";
1996  AddModUnionTable(mod_union_table);
1997  if (collector::SemiSpace::kUseRememberedSet) {
1998    // Add a new remembered set for the post-zygote non-moving space.
1999    accounting::RememberedSet* post_zygote_non_moving_space_rem_set =
2000        new accounting::RememberedSet("Post-zygote non-moving space remembered set", this,
2001                                      non_moving_space_);
2002    CHECK(post_zygote_non_moving_space_rem_set != nullptr)
2003        << "Failed to create post-zygote non-moving space remembered set";
2004    AddRememberedSet(post_zygote_non_moving_space_rem_set);
2005  }
2006}
2007
2008void Heap::FlushAllocStack() {
2009  MarkAllocStackAsLive(allocation_stack_.get());
2010  allocation_stack_->Reset();
2011}
2012
2013void Heap::MarkAllocStack(accounting::ContinuousSpaceBitmap* bitmap1,
2014                          accounting::ContinuousSpaceBitmap* bitmap2,
2015                          accounting::LargeObjectBitmap* large_objects,
2016                          accounting::ObjectStack* stack) {
2017  DCHECK(bitmap1 != nullptr);
2018  DCHECK(bitmap2 != nullptr);
2019  mirror::Object** limit = stack->End();
2020  for (mirror::Object** it = stack->Begin(); it != limit; ++it) {
2021    const mirror::Object* obj = *it;
2022    if (!kUseThreadLocalAllocationStack || obj != nullptr) {
2023      if (bitmap1->HasAddress(obj)) {
2024        bitmap1->Set(obj);
2025      } else if (bitmap2->HasAddress(obj)) {
2026        bitmap2->Set(obj);
2027      } else {
2028        large_objects->Set(obj);
2029      }
2030    }
2031  }
2032}
2033
2034void Heap::SwapSemiSpaces() {
2035  CHECK(bump_pointer_space_ != nullptr);
2036  CHECK(temp_space_ != nullptr);
2037  std::swap(bump_pointer_space_, temp_space_);
2038}
2039
2040void Heap::Compact(space::ContinuousMemMapAllocSpace* target_space,
2041                   space::ContinuousMemMapAllocSpace* source_space,
2042                   GcCause gc_cause) {
2043  CHECK(kMovingCollector);
2044  if (target_space != source_space) {
2045    // Don't swap spaces since this isn't a typical semi space collection.
2046    semi_space_collector_->SetSwapSemiSpaces(false);
2047    semi_space_collector_->SetFromSpace(source_space);
2048    semi_space_collector_->SetToSpace(target_space);
2049    semi_space_collector_->Run(gc_cause, false);
2050  } else {
2051    CHECK(target_space->IsBumpPointerSpace())
2052        << "In-place compaction is only supported for bump pointer spaces";
2053    mark_compact_collector_->SetSpace(target_space->AsBumpPointerSpace());
2054    mark_compact_collector_->Run(kGcCauseCollectorTransition, false);
2055  }
2056}
2057
2058collector::GcType Heap::CollectGarbageInternal(collector::GcType gc_type, GcCause gc_cause,
2059                                               bool clear_soft_references) {
2060  Thread* self = Thread::Current();
2061  Runtime* runtime = Runtime::Current();
2062  // If the heap can't run the GC, silently fail and return that no GC was run.
2063  switch (gc_type) {
2064    case collector::kGcTypePartial: {
2065      if (!have_zygote_space_) {
2066        return collector::kGcTypeNone;
2067      }
2068      break;
2069    }
2070    default: {
2071      // Other GC types don't have any special cases which makes them not runnable. The main case
2072      // here is full GC.
2073    }
2074  }
2075  ScopedThreadStateChange tsc(self, kWaitingPerformingGc);
2076  Locks::mutator_lock_->AssertNotHeld(self);
2077  if (self->IsHandlingStackOverflow()) {
2078    LOG(WARNING) << "Performing GC on a thread that is handling a stack overflow.";
2079  }
2080  bool compacting_gc;
2081  {
2082    gc_complete_lock_->AssertNotHeld(self);
2083    ScopedThreadStateChange tsc(self, kWaitingForGcToComplete);
2084    MutexLock mu(self, *gc_complete_lock_);
2085    // Ensure there is only one GC at a time.
2086    WaitForGcToCompleteLocked(gc_cause, self);
2087    compacting_gc = IsMovingGc(collector_type_);
2088    // GC can be disabled if someone has a used GetPrimitiveArrayCritical.
2089    if (compacting_gc && disable_moving_gc_count_ != 0) {
2090      LOG(WARNING) << "Skipping GC due to disable moving GC count " << disable_moving_gc_count_;
2091      return collector::kGcTypeNone;
2092    }
2093    collector_type_running_ = collector_type_;
2094  }
2095
2096  if (gc_cause == kGcCauseForAlloc && runtime->HasStatsEnabled()) {
2097    ++runtime->GetStats()->gc_for_alloc_count;
2098    ++self->GetStats()->gc_for_alloc_count;
2099  }
2100  uint64_t gc_start_time_ns = NanoTime();
2101  uint64_t gc_start_size = GetBytesAllocated();
2102  // Approximate allocation rate in bytes / second.
2103  uint64_t ms_delta = NsToMs(gc_start_time_ns - last_gc_time_ns_);
2104  // Back to back GCs can cause 0 ms of wait time in between GC invocations.
2105  if (LIKELY(ms_delta != 0)) {
2106    allocation_rate_ = ((gc_start_size - last_gc_size_) * 1000) / ms_delta;
2107    ATRACE_INT("Allocation rate KB/s", allocation_rate_ / KB);
2108    VLOG(heap) << "Allocation rate: " << PrettySize(allocation_rate_) << "/s";
2109  }
2110
2111  DCHECK_LT(gc_type, collector::kGcTypeMax);
2112  DCHECK_NE(gc_type, collector::kGcTypeNone);
2113
2114  collector::GarbageCollector* collector = nullptr;
2115  // TODO: Clean this up.
2116  if (compacting_gc) {
2117    DCHECK(current_allocator_ == kAllocatorTypeBumpPointer ||
2118           current_allocator_ == kAllocatorTypeTLAB);
2119    switch (collector_type_) {
2120      case kCollectorTypeSS:
2121        // Fall-through.
2122      case kCollectorTypeGSS:
2123        semi_space_collector_->SetFromSpace(bump_pointer_space_);
2124        semi_space_collector_->SetToSpace(temp_space_);
2125        semi_space_collector_->SetSwapSemiSpaces(true);
2126        collector = semi_space_collector_;
2127        break;
2128      case kCollectorTypeCC:
2129        collector = concurrent_copying_collector_;
2130        break;
2131      case kCollectorTypeMC:
2132        mark_compact_collector_->SetSpace(bump_pointer_space_);
2133        collector = mark_compact_collector_;
2134        break;
2135      default:
2136        LOG(FATAL) << "Invalid collector type " << static_cast<size_t>(collector_type_);
2137    }
2138    if (collector != mark_compact_collector_) {
2139      temp_space_->GetMemMap()->Protect(PROT_READ | PROT_WRITE);
2140      CHECK(temp_space_->IsEmpty());
2141    }
2142    gc_type = collector::kGcTypeFull;  // TODO: Not hard code this in.
2143  } else if (current_allocator_ == kAllocatorTypeRosAlloc ||
2144      current_allocator_ == kAllocatorTypeDlMalloc) {
2145    collector = FindCollectorByGcType(gc_type);
2146  } else {
2147    LOG(FATAL) << "Invalid current allocator " << current_allocator_;
2148  }
2149  CHECK(collector != nullptr)
2150      << "Could not find garbage collector with collector_type="
2151      << static_cast<size_t>(collector_type_) << " and gc_type=" << gc_type;
2152  collector->Run(gc_cause, clear_soft_references || runtime->IsZygote());
2153  total_objects_freed_ever_ += GetCurrentGcIteration()->GetFreedObjects();
2154  total_bytes_freed_ever_ += GetCurrentGcIteration()->GetFreedBytes();
2155  RequestHeapTrim();
2156  // Enqueue cleared references.
2157  reference_processor_.EnqueueClearedReferences(self);
2158  // Grow the heap so that we know when to perform the next GC.
2159  GrowForUtilization(collector);
2160  const size_t duration = GetCurrentGcIteration()->GetDurationNs();
2161  const std::vector<uint64_t>& pause_times = GetCurrentGcIteration()->GetPauseTimes();
2162  // Print the GC if it is an explicit GC (e.g. Runtime.gc()) or a slow GC
2163  // (mutator time blocked >= long_pause_log_threshold_).
2164  bool log_gc = gc_cause == kGcCauseExplicit;
2165  if (!log_gc && CareAboutPauseTimes()) {
2166    // GC for alloc pauses the allocating thread, so consider it as a pause.
2167    log_gc = duration > long_gc_log_threshold_ ||
2168        (gc_cause == kGcCauseForAlloc && duration > long_pause_log_threshold_);
2169    for (uint64_t pause : pause_times) {
2170      log_gc = log_gc || pause >= long_pause_log_threshold_;
2171    }
2172  }
2173  if (log_gc) {
2174    const size_t percent_free = GetPercentFree();
2175    const size_t current_heap_size = GetBytesAllocated();
2176    const size_t total_memory = GetTotalMemory();
2177    std::ostringstream pause_string;
2178    for (size_t i = 0; i < pause_times.size(); ++i) {
2179        pause_string << PrettyDuration((pause_times[i] / 1000) * 1000)
2180                     << ((i != pause_times.size() - 1) ? "," : "");
2181    }
2182    LOG(INFO) << gc_cause << " " << collector->GetName()
2183              << " GC freed "  << current_gc_iteration_.GetFreedObjects() << "("
2184              << PrettySize(current_gc_iteration_.GetFreedBytes()) << ") AllocSpace objects, "
2185              << current_gc_iteration_.GetFreedLargeObjects() << "("
2186              << PrettySize(current_gc_iteration_.GetFreedLargeObjectBytes()) << ") LOS objects, "
2187              << percent_free << "% free, " << PrettySize(current_heap_size) << "/"
2188              << PrettySize(total_memory) << ", " << "paused " << pause_string.str()
2189              << " total " << PrettyDuration((duration / 1000) * 1000);
2190    VLOG(heap) << ConstDumpable<TimingLogger>(*current_gc_iteration_.GetTimings());
2191  }
2192  FinishGC(self, gc_type);
2193  // Inform DDMS that a GC completed.
2194  Dbg::GcDidFinish();
2195  return gc_type;
2196}
2197
2198void Heap::FinishGC(Thread* self, collector::GcType gc_type) {
2199  MutexLock mu(self, *gc_complete_lock_);
2200  collector_type_running_ = kCollectorTypeNone;
2201  if (gc_type != collector::kGcTypeNone) {
2202    last_gc_type_ = gc_type;
2203  }
2204  // Wake anyone who may have been waiting for the GC to complete.
2205  gc_complete_cond_->Broadcast(self);
2206}
2207
2208static void RootMatchesObjectVisitor(mirror::Object** root, void* arg, uint32_t /*thread_id*/,
2209                                     RootType /*root_type*/) {
2210  mirror::Object* obj = reinterpret_cast<mirror::Object*>(arg);
2211  if (*root == obj) {
2212    LOG(INFO) << "Object " << obj << " is a root";
2213  }
2214}
2215
2216class ScanVisitor {
2217 public:
2218  void operator()(const mirror::Object* obj) const {
2219    LOG(ERROR) << "Would have rescanned object " << obj;
2220  }
2221};
2222
2223// Verify a reference from an object.
2224class VerifyReferenceVisitor {
2225 public:
2226  explicit VerifyReferenceVisitor(Heap* heap, Atomic<size_t>* fail_count, bool verify_referent)
2227      SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_)
2228      : heap_(heap), fail_count_(fail_count), verify_referent_(verify_referent) {}
2229
2230  size_t GetFailureCount() const {
2231    return fail_count_->LoadSequentiallyConsistent();
2232  }
2233
2234  void operator()(mirror::Class* klass, mirror::Reference* ref) const
2235      SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
2236    if (verify_referent_) {
2237      VerifyReference(ref, ref->GetReferent(), mirror::Reference::ReferentOffset());
2238    }
2239  }
2240
2241  void operator()(mirror::Object* obj, MemberOffset offset, bool /*is_static*/) const
2242      SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
2243    VerifyReference(obj, obj->GetFieldObject<mirror::Object>(offset), offset);
2244  }
2245
2246  bool IsLive(mirror::Object* obj) const NO_THREAD_SAFETY_ANALYSIS {
2247    return heap_->IsLiveObjectLocked(obj, true, false, true);
2248  }
2249
2250  static void VerifyRootCallback(mirror::Object** root, void* arg, uint32_t thread_id,
2251                                 RootType root_type) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
2252    VerifyReferenceVisitor* visitor = reinterpret_cast<VerifyReferenceVisitor*>(arg);
2253    if (!visitor->VerifyReference(nullptr, *root, MemberOffset(0))) {
2254      LOG(ERROR) << "Root " << *root << " is dead with type " << PrettyTypeOf(*root)
2255          << " thread_id= " << thread_id << " root_type= " << root_type;
2256    }
2257  }
2258
2259 private:
2260  // TODO: Fix the no thread safety analysis.
2261  // Returns false on failure.
2262  bool VerifyReference(mirror::Object* obj, mirror::Object* ref, MemberOffset offset) const
2263      NO_THREAD_SAFETY_ANALYSIS {
2264    if (ref == nullptr || IsLive(ref)) {
2265      // Verify that the reference is live.
2266      return true;
2267    }
2268    if (fail_count_->FetchAndAddSequentiallyConsistent(1) == 0) {
2269      // Print message on only on first failure to prevent spam.
2270      LOG(ERROR) << "!!!!!!!!!!!!!!Heap corruption detected!!!!!!!!!!!!!!!!!!!";
2271    }
2272    if (obj != nullptr) {
2273      // Only do this part for non roots.
2274      accounting::CardTable* card_table = heap_->GetCardTable();
2275      accounting::ObjectStack* alloc_stack = heap_->allocation_stack_.get();
2276      accounting::ObjectStack* live_stack = heap_->live_stack_.get();
2277      byte* card_addr = card_table->CardFromAddr(obj);
2278      LOG(ERROR) << "Object " << obj << " references dead object " << ref << " at offset "
2279                 << offset << "\n card value = " << static_cast<int>(*card_addr);
2280      if (heap_->IsValidObjectAddress(obj->GetClass())) {
2281        LOG(ERROR) << "Obj type " << PrettyTypeOf(obj);
2282      } else {
2283        LOG(ERROR) << "Object " << obj << " class(" << obj->GetClass() << ") not a heap address";
2284      }
2285
2286      // Attempt to find the class inside of the recently freed objects.
2287      space::ContinuousSpace* ref_space = heap_->FindContinuousSpaceFromObject(ref, true);
2288      if (ref_space != nullptr && ref_space->IsMallocSpace()) {
2289        space::MallocSpace* space = ref_space->AsMallocSpace();
2290        mirror::Class* ref_class = space->FindRecentFreedObject(ref);
2291        if (ref_class != nullptr) {
2292          LOG(ERROR) << "Reference " << ref << " found as a recently freed object with class "
2293                     << PrettyClass(ref_class);
2294        } else {
2295          LOG(ERROR) << "Reference " << ref << " not found as a recently freed object";
2296        }
2297      }
2298
2299      if (ref->GetClass() != nullptr && heap_->IsValidObjectAddress(ref->GetClass()) &&
2300          ref->GetClass()->IsClass()) {
2301        LOG(ERROR) << "Ref type " << PrettyTypeOf(ref);
2302      } else {
2303        LOG(ERROR) << "Ref " << ref << " class(" << ref->GetClass()
2304                   << ") is not a valid heap address";
2305      }
2306
2307      card_table->CheckAddrIsInCardTable(reinterpret_cast<const byte*>(obj));
2308      void* cover_begin = card_table->AddrFromCard(card_addr);
2309      void* cover_end = reinterpret_cast<void*>(reinterpret_cast<size_t>(cover_begin) +
2310          accounting::CardTable::kCardSize);
2311      LOG(ERROR) << "Card " << reinterpret_cast<void*>(card_addr) << " covers " << cover_begin
2312          << "-" << cover_end;
2313      accounting::ContinuousSpaceBitmap* bitmap =
2314          heap_->GetLiveBitmap()->GetContinuousSpaceBitmap(obj);
2315
2316      if (bitmap == nullptr) {
2317        LOG(ERROR) << "Object " << obj << " has no bitmap";
2318        if (!VerifyClassClass(obj->GetClass())) {
2319          LOG(ERROR) << "Object " << obj << " failed class verification!";
2320        }
2321      } else {
2322        // Print out how the object is live.
2323        if (bitmap->Test(obj)) {
2324          LOG(ERROR) << "Object " << obj << " found in live bitmap";
2325        }
2326        if (alloc_stack->Contains(const_cast<mirror::Object*>(obj))) {
2327          LOG(ERROR) << "Object " << obj << " found in allocation stack";
2328        }
2329        if (live_stack->Contains(const_cast<mirror::Object*>(obj))) {
2330          LOG(ERROR) << "Object " << obj << " found in live stack";
2331        }
2332        if (alloc_stack->Contains(const_cast<mirror::Object*>(ref))) {
2333          LOG(ERROR) << "Ref " << ref << " found in allocation stack";
2334        }
2335        if (live_stack->Contains(const_cast<mirror::Object*>(ref))) {
2336          LOG(ERROR) << "Ref " << ref << " found in live stack";
2337        }
2338        // Attempt to see if the card table missed the reference.
2339        ScanVisitor scan_visitor;
2340        byte* byte_cover_begin = reinterpret_cast<byte*>(card_table->AddrFromCard(card_addr));
2341        card_table->Scan(bitmap, byte_cover_begin,
2342                         byte_cover_begin + accounting::CardTable::kCardSize, scan_visitor);
2343      }
2344
2345      // Search to see if any of the roots reference our object.
2346      void* arg = const_cast<void*>(reinterpret_cast<const void*>(obj));
2347      Runtime::Current()->VisitRoots(&RootMatchesObjectVisitor, arg);
2348
2349      // Search to see if any of the roots reference our reference.
2350      arg = const_cast<void*>(reinterpret_cast<const void*>(ref));
2351      Runtime::Current()->VisitRoots(&RootMatchesObjectVisitor, arg);
2352    }
2353    return false;
2354  }
2355
2356  Heap* const heap_;
2357  Atomic<size_t>* const fail_count_;
2358  const bool verify_referent_;
2359};
2360
2361// Verify all references within an object, for use with HeapBitmap::Visit.
2362class VerifyObjectVisitor {
2363 public:
2364  explicit VerifyObjectVisitor(Heap* heap, Atomic<size_t>* fail_count, bool verify_referent)
2365      : heap_(heap), fail_count_(fail_count), verify_referent_(verify_referent) {
2366  }
2367
2368  void operator()(mirror::Object* obj) const
2369      SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
2370    // Note: we are verifying the references in obj but not obj itself, this is because obj must
2371    // be live or else how did we find it in the live bitmap?
2372    VerifyReferenceVisitor visitor(heap_, fail_count_, verify_referent_);
2373    // The class doesn't count as a reference but we should verify it anyways.
2374    obj->VisitReferences<true>(visitor, visitor);
2375  }
2376
2377  static void VisitCallback(mirror::Object* obj, void* arg)
2378      SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
2379    VerifyObjectVisitor* visitor = reinterpret_cast<VerifyObjectVisitor*>(arg);
2380    visitor->operator()(obj);
2381  }
2382
2383  size_t GetFailureCount() const {
2384    return fail_count_->LoadSequentiallyConsistent();
2385  }
2386
2387 private:
2388  Heap* const heap_;
2389  Atomic<size_t>* const fail_count_;
2390  const bool verify_referent_;
2391};
2392
2393void Heap::PushOnAllocationStackWithInternalGC(Thread* self, mirror::Object** obj) {
2394  // Slow path, the allocation stack push back must have already failed.
2395  DCHECK(!allocation_stack_->AtomicPushBack(*obj));
2396  do {
2397    // TODO: Add handle VerifyObject.
2398    StackHandleScope<1> hs(self);
2399    HandleWrapper<mirror::Object> wrapper(hs.NewHandleWrapper(obj));
2400    // Push our object into the reserve region of the allocaiton stack. This is only required due
2401    // to heap verification requiring that roots are live (either in the live bitmap or in the
2402    // allocation stack).
2403    CHECK(allocation_stack_->AtomicPushBackIgnoreGrowthLimit(*obj));
2404    CollectGarbageInternal(collector::kGcTypeSticky, kGcCauseForAlloc, false);
2405  } while (!allocation_stack_->AtomicPushBack(*obj));
2406}
2407
2408void Heap::PushOnThreadLocalAllocationStackWithInternalGC(Thread* self, mirror::Object** obj) {
2409  // Slow path, the allocation stack push back must have already failed.
2410  DCHECK(!self->PushOnThreadLocalAllocationStack(*obj));
2411  mirror::Object** start_address;
2412  mirror::Object** end_address;
2413  while (!allocation_stack_->AtomicBumpBack(kThreadLocalAllocationStackSize, &start_address,
2414                                            &end_address)) {
2415    // TODO: Add handle VerifyObject.
2416    StackHandleScope<1> hs(self);
2417    HandleWrapper<mirror::Object> wrapper(hs.NewHandleWrapper(obj));
2418    // Push our object into the reserve region of the allocaiton stack. This is only required due
2419    // to heap verification requiring that roots are live (either in the live bitmap or in the
2420    // allocation stack).
2421    CHECK(allocation_stack_->AtomicPushBackIgnoreGrowthLimit(*obj));
2422    // Push into the reserve allocation stack.
2423    CollectGarbageInternal(collector::kGcTypeSticky, kGcCauseForAlloc, false);
2424  }
2425  self->SetThreadLocalAllocationStack(start_address, end_address);
2426  // Retry on the new thread-local allocation stack.
2427  CHECK(self->PushOnThreadLocalAllocationStack(*obj));  // Must succeed.
2428}
2429
2430// Must do this with mutators suspended since we are directly accessing the allocation stacks.
2431size_t Heap::VerifyHeapReferences(bool verify_referents) {
2432  Thread* self = Thread::Current();
2433  Locks::mutator_lock_->AssertExclusiveHeld(self);
2434  // Lets sort our allocation stacks so that we can efficiently binary search them.
2435  allocation_stack_->Sort();
2436  live_stack_->Sort();
2437  // Since we sorted the allocation stack content, need to revoke all
2438  // thread-local allocation stacks.
2439  RevokeAllThreadLocalAllocationStacks(self);
2440  Atomic<size_t> fail_count_(0);
2441  VerifyObjectVisitor visitor(this, &fail_count_, verify_referents);
2442  // Verify objects in the allocation stack since these will be objects which were:
2443  // 1. Allocated prior to the GC (pre GC verification).
2444  // 2. Allocated during the GC (pre sweep GC verification).
2445  // We don't want to verify the objects in the live stack since they themselves may be
2446  // pointing to dead objects if they are not reachable.
2447  VisitObjects(VerifyObjectVisitor::VisitCallback, &visitor);
2448  // Verify the roots:
2449  Runtime::Current()->VisitRoots(VerifyReferenceVisitor::VerifyRootCallback, &visitor);
2450  if (visitor.GetFailureCount() > 0) {
2451    // Dump mod-union tables.
2452    for (const auto& table_pair : mod_union_tables_) {
2453      accounting::ModUnionTable* mod_union_table = table_pair.second;
2454      mod_union_table->Dump(LOG(ERROR) << mod_union_table->GetName() << ": ");
2455    }
2456    // Dump remembered sets.
2457    for (const auto& table_pair : remembered_sets_) {
2458      accounting::RememberedSet* remembered_set = table_pair.second;
2459      remembered_set->Dump(LOG(ERROR) << remembered_set->GetName() << ": ");
2460    }
2461    DumpSpaces(LOG(ERROR));
2462  }
2463  return visitor.GetFailureCount();
2464}
2465
2466class VerifyReferenceCardVisitor {
2467 public:
2468  VerifyReferenceCardVisitor(Heap* heap, bool* failed)
2469      SHARED_LOCKS_REQUIRED(Locks::mutator_lock_,
2470                            Locks::heap_bitmap_lock_)
2471      : heap_(heap), failed_(failed) {
2472  }
2473
2474  // TODO: Fix lock analysis to not use NO_THREAD_SAFETY_ANALYSIS, requires support for
2475  // annotalysis on visitors.
2476  void operator()(mirror::Object* obj, MemberOffset offset, bool is_static) const
2477      NO_THREAD_SAFETY_ANALYSIS {
2478    mirror::Object* ref = obj->GetFieldObject<mirror::Object>(offset);
2479    // Filter out class references since changing an object's class does not mark the card as dirty.
2480    // Also handles large objects, since the only reference they hold is a class reference.
2481    if (ref != nullptr && !ref->IsClass()) {
2482      accounting::CardTable* card_table = heap_->GetCardTable();
2483      // If the object is not dirty and it is referencing something in the live stack other than
2484      // class, then it must be on a dirty card.
2485      if (!card_table->AddrIsInCardTable(obj)) {
2486        LOG(ERROR) << "Object " << obj << " is not in the address range of the card table";
2487        *failed_ = true;
2488      } else if (!card_table->IsDirty(obj)) {
2489        // TODO: Check mod-union tables.
2490        // Card should be either kCardDirty if it got re-dirtied after we aged it, or
2491        // kCardDirty - 1 if it didnt get touched since we aged it.
2492        accounting::ObjectStack* live_stack = heap_->live_stack_.get();
2493        if (live_stack->ContainsSorted(ref)) {
2494          if (live_stack->ContainsSorted(obj)) {
2495            LOG(ERROR) << "Object " << obj << " found in live stack";
2496          }
2497          if (heap_->GetLiveBitmap()->Test(obj)) {
2498            LOG(ERROR) << "Object " << obj << " found in live bitmap";
2499          }
2500          LOG(ERROR) << "Object " << obj << " " << PrettyTypeOf(obj)
2501                    << " references " << ref << " " << PrettyTypeOf(ref) << " in live stack";
2502
2503          // Print which field of the object is dead.
2504          if (!obj->IsObjectArray()) {
2505            mirror::Class* klass = is_static ? obj->AsClass() : obj->GetClass();
2506            CHECK(klass != NULL);
2507            mirror::ObjectArray<mirror::ArtField>* fields = is_static ? klass->GetSFields()
2508                                                                      : klass->GetIFields();
2509            CHECK(fields != NULL);
2510            for (int32_t i = 0; i < fields->GetLength(); ++i) {
2511              mirror::ArtField* cur = fields->Get(i);
2512              if (cur->GetOffset().Int32Value() == offset.Int32Value()) {
2513                LOG(ERROR) << (is_static ? "Static " : "") << "field in the live stack is "
2514                          << PrettyField(cur);
2515                break;
2516              }
2517            }
2518          } else {
2519            mirror::ObjectArray<mirror::Object>* object_array =
2520                obj->AsObjectArray<mirror::Object>();
2521            for (int32_t i = 0; i < object_array->GetLength(); ++i) {
2522              if (object_array->Get(i) == ref) {
2523                LOG(ERROR) << (is_static ? "Static " : "") << "obj[" << i << "] = ref";
2524              }
2525            }
2526          }
2527
2528          *failed_ = true;
2529        }
2530      }
2531    }
2532  }
2533
2534 private:
2535  Heap* const heap_;
2536  bool* const failed_;
2537};
2538
2539class VerifyLiveStackReferences {
2540 public:
2541  explicit VerifyLiveStackReferences(Heap* heap)
2542      : heap_(heap),
2543        failed_(false) {}
2544
2545  void operator()(mirror::Object* obj) const
2546      SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
2547    VerifyReferenceCardVisitor visitor(heap_, const_cast<bool*>(&failed_));
2548    obj->VisitReferences<true>(visitor, VoidFunctor());
2549  }
2550
2551  bool Failed() const {
2552    return failed_;
2553  }
2554
2555 private:
2556  Heap* const heap_;
2557  bool failed_;
2558};
2559
2560bool Heap::VerifyMissingCardMarks() {
2561  Thread* self = Thread::Current();
2562  Locks::mutator_lock_->AssertExclusiveHeld(self);
2563  // We need to sort the live stack since we binary search it.
2564  live_stack_->Sort();
2565  // Since we sorted the allocation stack content, need to revoke all
2566  // thread-local allocation stacks.
2567  RevokeAllThreadLocalAllocationStacks(self);
2568  VerifyLiveStackReferences visitor(this);
2569  GetLiveBitmap()->Visit(visitor);
2570  // We can verify objects in the live stack since none of these should reference dead objects.
2571  for (mirror::Object** it = live_stack_->Begin(); it != live_stack_->End(); ++it) {
2572    if (!kUseThreadLocalAllocationStack || *it != nullptr) {
2573      visitor(*it);
2574    }
2575  }
2576  return !visitor.Failed();
2577}
2578
2579void Heap::SwapStacks(Thread* self) {
2580  if (kUseThreadLocalAllocationStack) {
2581    live_stack_->AssertAllZero();
2582  }
2583  allocation_stack_.swap(live_stack_);
2584}
2585
2586void Heap::RevokeAllThreadLocalAllocationStacks(Thread* self) {
2587  // This must be called only during the pause.
2588  CHECK(Locks::mutator_lock_->IsExclusiveHeld(self));
2589  MutexLock mu(self, *Locks::runtime_shutdown_lock_);
2590  MutexLock mu2(self, *Locks::thread_list_lock_);
2591  std::list<Thread*> thread_list = Runtime::Current()->GetThreadList()->GetList();
2592  for (Thread* t : thread_list) {
2593    t->RevokeThreadLocalAllocationStack();
2594  }
2595}
2596
2597void Heap::AssertAllBumpPointerSpaceThreadLocalBuffersAreRevoked() {
2598  if (kIsDebugBuild) {
2599    if (bump_pointer_space_ != nullptr) {
2600      bump_pointer_space_->AssertAllThreadLocalBuffersAreRevoked();
2601    }
2602  }
2603}
2604
2605accounting::ModUnionTable* Heap::FindModUnionTableFromSpace(space::Space* space) {
2606  auto it = mod_union_tables_.find(space);
2607  if (it == mod_union_tables_.end()) {
2608    return nullptr;
2609  }
2610  return it->second;
2611}
2612
2613accounting::RememberedSet* Heap::FindRememberedSetFromSpace(space::Space* space) {
2614  auto it = remembered_sets_.find(space);
2615  if (it == remembered_sets_.end()) {
2616    return nullptr;
2617  }
2618  return it->second;
2619}
2620
2621void Heap::ProcessCards(TimingLogger* timings, bool use_rem_sets) {
2622  TimingLogger::ScopedTiming t(__FUNCTION__, timings);
2623  // Clear cards and keep track of cards cleared in the mod-union table.
2624  for (const auto& space : continuous_spaces_) {
2625    accounting::ModUnionTable* table = FindModUnionTableFromSpace(space);
2626    accounting::RememberedSet* rem_set = FindRememberedSetFromSpace(space);
2627    if (table != nullptr) {
2628      const char* name = space->IsZygoteSpace() ? "ZygoteModUnionClearCards" :
2629          "ImageModUnionClearCards";
2630      TimingLogger::ScopedTiming t(name, timings);
2631      table->ClearCards();
2632    } else if (use_rem_sets && rem_set != nullptr) {
2633      DCHECK(collector::SemiSpace::kUseRememberedSet && collector_type_ == kCollectorTypeGSS)
2634          << static_cast<int>(collector_type_);
2635      TimingLogger::ScopedTiming t("AllocSpaceRemSetClearCards", timings);
2636      rem_set->ClearCards();
2637    } else if (space->GetType() != space::kSpaceTypeBumpPointerSpace) {
2638      TimingLogger::ScopedTiming t("AllocSpaceClearCards", timings);
2639      // No mod union table for the AllocSpace. Age the cards so that the GC knows that these cards
2640      // were dirty before the GC started.
2641      // TODO: Need to use atomic for the case where aged(cleaning thread) -> dirty(other thread)
2642      // -> clean(cleaning thread).
2643      // The races are we either end up with: Aged card, unaged card. Since we have the checkpoint
2644      // roots and then we scan / update mod union tables after. We will always scan either card.
2645      // If we end up with the non aged card, we scan it it in the pause.
2646      card_table_->ModifyCardsAtomic(space->Begin(), space->End(), AgeCardVisitor(),
2647                                     VoidFunctor());
2648    }
2649  }
2650}
2651
2652static void IdentityMarkHeapReferenceCallback(mirror::HeapReference<mirror::Object>*, void*) {
2653}
2654
2655void Heap::PreGcVerificationPaused(collector::GarbageCollector* gc) {
2656  Thread* const self = Thread::Current();
2657  TimingLogger* const timings = current_gc_iteration_.GetTimings();
2658  TimingLogger::ScopedTiming t(__FUNCTION__, timings);
2659  if (verify_pre_gc_heap_) {
2660    TimingLogger::ScopedTiming t("(Paused)PreGcVerifyHeapReferences", timings);
2661    ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
2662    size_t failures = VerifyHeapReferences();
2663    if (failures > 0) {
2664      LOG(FATAL) << "Pre " << gc->GetName() << " heap verification failed with " << failures
2665          << " failures";
2666    }
2667  }
2668  // Check that all objects which reference things in the live stack are on dirty cards.
2669  if (verify_missing_card_marks_) {
2670    TimingLogger::ScopedTiming t("(Paused)PreGcVerifyMissingCardMarks", timings);
2671    ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
2672    SwapStacks(self);
2673    // Sort the live stack so that we can quickly binary search it later.
2674    CHECK(VerifyMissingCardMarks()) << "Pre " << gc->GetName()
2675                                    << " missing card mark verification failed\n" << DumpSpaces();
2676    SwapStacks(self);
2677  }
2678  if (verify_mod_union_table_) {
2679    TimingLogger::ScopedTiming t("(Paused)PreGcVerifyModUnionTables", timings);
2680    ReaderMutexLock reader_lock(self, *Locks::heap_bitmap_lock_);
2681    for (const auto& table_pair : mod_union_tables_) {
2682      accounting::ModUnionTable* mod_union_table = table_pair.second;
2683      mod_union_table->UpdateAndMarkReferences(IdentityMarkHeapReferenceCallback, nullptr);
2684      mod_union_table->Verify();
2685    }
2686  }
2687}
2688
2689void Heap::PreGcVerification(collector::GarbageCollector* gc) {
2690  if (verify_pre_gc_heap_ || verify_missing_card_marks_ || verify_mod_union_table_) {
2691    collector::GarbageCollector::ScopedPause pause(gc);
2692    PreGcVerificationPaused(gc);
2693  }
2694}
2695
2696void Heap::PrePauseRosAllocVerification(collector::GarbageCollector* gc) {
2697  // TODO: Add a new runtime option for this?
2698  if (verify_pre_gc_rosalloc_) {
2699    RosAllocVerification(current_gc_iteration_.GetTimings(), "PreGcRosAllocVerification");
2700  }
2701}
2702
2703void Heap::PreSweepingGcVerification(collector::GarbageCollector* gc) {
2704  Thread* const self = Thread::Current();
2705  TimingLogger* const timings = current_gc_iteration_.GetTimings();
2706  TimingLogger::ScopedTiming t(__FUNCTION__, timings);
2707  // Called before sweeping occurs since we want to make sure we are not going so reclaim any
2708  // reachable objects.
2709  if (verify_pre_sweeping_heap_) {
2710    TimingLogger::ScopedTiming t("(Paused)PostSweepingVerifyHeapReferences", timings);
2711    CHECK_NE(self->GetState(), kRunnable);
2712    WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
2713    // Swapping bound bitmaps does nothing.
2714    gc->SwapBitmaps();
2715    // Pass in false since concurrent reference processing can mean that the reference referents
2716    // may point to dead objects at the point which PreSweepingGcVerification is called.
2717    size_t failures = VerifyHeapReferences(false);
2718    if (failures > 0) {
2719      LOG(FATAL) << "Pre sweeping " << gc->GetName() << " GC verification failed with " << failures
2720          << " failures";
2721    }
2722    gc->SwapBitmaps();
2723  }
2724  if (verify_pre_sweeping_rosalloc_) {
2725    RosAllocVerification(timings, "PreSweepingRosAllocVerification");
2726  }
2727}
2728
2729void Heap::PostGcVerificationPaused(collector::GarbageCollector* gc) {
2730  // Only pause if we have to do some verification.
2731  Thread* const self = Thread::Current();
2732  TimingLogger* const timings = GetCurrentGcIteration()->GetTimings();
2733  TimingLogger::ScopedTiming t(__FUNCTION__, timings);
2734  if (verify_system_weaks_) {
2735    ReaderMutexLock mu2(self, *Locks::heap_bitmap_lock_);
2736    collector::MarkSweep* mark_sweep = down_cast<collector::MarkSweep*>(gc);
2737    mark_sweep->VerifySystemWeaks();
2738  }
2739  if (verify_post_gc_rosalloc_) {
2740    RosAllocVerification(timings, "(Paused)PostGcRosAllocVerification");
2741  }
2742  if (verify_post_gc_heap_) {
2743    TimingLogger::ScopedTiming t("(Paused)PostGcVerifyHeapReferences", timings);
2744    ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
2745    size_t failures = VerifyHeapReferences();
2746    if (failures > 0) {
2747      LOG(FATAL) << "Pre " << gc->GetName() << " heap verification failed with " << failures
2748          << " failures";
2749    }
2750  }
2751}
2752
2753void Heap::PostGcVerification(collector::GarbageCollector* gc) {
2754  if (verify_system_weaks_ || verify_post_gc_rosalloc_ || verify_post_gc_heap_) {
2755    collector::GarbageCollector::ScopedPause pause(gc);
2756    PostGcVerificationPaused(gc);
2757  }
2758}
2759
2760void Heap::RosAllocVerification(TimingLogger* timings, const char* name) {
2761  TimingLogger::ScopedTiming t(name, timings);
2762  for (const auto& space : continuous_spaces_) {
2763    if (space->IsRosAllocSpace()) {
2764      VLOG(heap) << name << " : " << space->GetName();
2765      space->AsRosAllocSpace()->Verify();
2766    }
2767  }
2768}
2769
2770collector::GcType Heap::WaitForGcToComplete(GcCause cause, Thread* self) {
2771  ScopedThreadStateChange tsc(self, kWaitingForGcToComplete);
2772  MutexLock mu(self, *gc_complete_lock_);
2773  return WaitForGcToCompleteLocked(cause, self);
2774}
2775
2776collector::GcType Heap::WaitForGcToCompleteLocked(GcCause cause, Thread* self) {
2777  collector::GcType last_gc_type = collector::kGcTypeNone;
2778  uint64_t wait_start = NanoTime();
2779  while (collector_type_running_ != kCollectorTypeNone) {
2780    ATRACE_BEGIN("GC: Wait For Completion");
2781    // We must wait, change thread state then sleep on gc_complete_cond_;
2782    gc_complete_cond_->Wait(self);
2783    last_gc_type = last_gc_type_;
2784    ATRACE_END();
2785  }
2786  uint64_t wait_time = NanoTime() - wait_start;
2787  total_wait_time_ += wait_time;
2788  if (wait_time > long_pause_log_threshold_) {
2789    LOG(INFO) << "WaitForGcToComplete blocked for " << PrettyDuration(wait_time)
2790        << " for cause " << cause;
2791  }
2792  return last_gc_type;
2793}
2794
2795void Heap::DumpForSigQuit(std::ostream& os) {
2796  os << "Heap: " << GetPercentFree() << "% free, " << PrettySize(GetBytesAllocated()) << "/"
2797     << PrettySize(GetTotalMemory()) << "; " << GetObjectsAllocated() << " objects\n";
2798  DumpGcPerformanceInfo(os);
2799}
2800
2801size_t Heap::GetPercentFree() {
2802  return static_cast<size_t>(100.0f * static_cast<float>(GetFreeMemory()) / max_allowed_footprint_);
2803}
2804
2805void Heap::SetIdealFootprint(size_t max_allowed_footprint) {
2806  if (max_allowed_footprint > GetMaxMemory()) {
2807    VLOG(gc) << "Clamp target GC heap from " << PrettySize(max_allowed_footprint) << " to "
2808             << PrettySize(GetMaxMemory());
2809    max_allowed_footprint = GetMaxMemory();
2810  }
2811  max_allowed_footprint_ = max_allowed_footprint;
2812}
2813
2814bool Heap::IsMovableObject(const mirror::Object* obj) const {
2815  if (kMovingCollector) {
2816    space::Space* space = FindContinuousSpaceFromObject(obj, true);
2817    if (space != nullptr) {
2818      // TODO: Check large object?
2819      return space->CanMoveObjects();
2820    }
2821  }
2822  return false;
2823}
2824
2825void Heap::UpdateMaxNativeFootprint() {
2826  size_t native_size = native_bytes_allocated_.LoadRelaxed();
2827  // TODO: Tune the native heap utilization to be a value other than the java heap utilization.
2828  size_t target_size = native_size / GetTargetHeapUtilization();
2829  if (target_size > native_size + max_free_) {
2830    target_size = native_size + max_free_;
2831  } else if (target_size < native_size + min_free_) {
2832    target_size = native_size + min_free_;
2833  }
2834  native_footprint_gc_watermark_ = std::min(growth_limit_, target_size);
2835}
2836
2837collector::GarbageCollector* Heap::FindCollectorByGcType(collector::GcType gc_type) {
2838  for (const auto& collector : garbage_collectors_) {
2839    if (collector->GetCollectorType() == collector_type_ &&
2840        collector->GetGcType() == gc_type) {
2841      return collector;
2842    }
2843  }
2844  return nullptr;
2845}
2846
2847double Heap::HeapGrowthMultiplier() const {
2848  // If we don't care about pause times we are background, so return 1.0.
2849  if (!CareAboutPauseTimes() || IsLowMemoryMode()) {
2850    return 1.0;
2851  }
2852  return foreground_heap_growth_multiplier_;
2853}
2854
2855void Heap::GrowForUtilization(collector::GarbageCollector* collector_ran) {
2856  // We know what our utilization is at this moment.
2857  // This doesn't actually resize any memory. It just lets the heap grow more when necessary.
2858  const uint64_t bytes_allocated = GetBytesAllocated();
2859  last_gc_size_ = bytes_allocated;
2860  last_gc_time_ns_ = NanoTime();
2861  uint64_t target_size;
2862  collector::GcType gc_type = collector_ran->GetGcType();
2863  if (gc_type != collector::kGcTypeSticky) {
2864    // Grow the heap for non sticky GC.
2865    const float multiplier = HeapGrowthMultiplier();  // Use the multiplier to grow more for
2866    // foreground.
2867    intptr_t delta = bytes_allocated / GetTargetHeapUtilization() - bytes_allocated;
2868    CHECK_GE(delta, 0);
2869    target_size = bytes_allocated + delta * multiplier;
2870    target_size = std::min(target_size,
2871                           bytes_allocated + static_cast<uint64_t>(max_free_ * multiplier));
2872    target_size = std::max(target_size,
2873                           bytes_allocated + static_cast<uint64_t>(min_free_ * multiplier));
2874    native_need_to_run_finalization_ = true;
2875    next_gc_type_ = collector::kGcTypeSticky;
2876  } else {
2877    collector::GcType non_sticky_gc_type =
2878        have_zygote_space_ ? collector::kGcTypePartial : collector::kGcTypeFull;
2879    // Find what the next non sticky collector will be.
2880    collector::GarbageCollector* non_sticky_collector = FindCollectorByGcType(non_sticky_gc_type);
2881    // If the throughput of the current sticky GC >= throughput of the non sticky collector, then
2882    // do another sticky collection next.
2883    // We also check that the bytes allocated aren't over the footprint limit in order to prevent a
2884    // pathological case where dead objects which aren't reclaimed by sticky could get accumulated
2885    // if the sticky GC throughput always remained >= the full/partial throughput.
2886    if (current_gc_iteration_.GetEstimatedThroughput() * kStickyGcThroughputAdjustment >=
2887        non_sticky_collector->GetEstimatedMeanThroughput() &&
2888        non_sticky_collector->NumberOfIterations() > 0 &&
2889        bytes_allocated <= max_allowed_footprint_) {
2890      next_gc_type_ = collector::kGcTypeSticky;
2891    } else {
2892      next_gc_type_ = non_sticky_gc_type;
2893    }
2894    // If we have freed enough memory, shrink the heap back down.
2895    if (bytes_allocated + max_free_ < max_allowed_footprint_) {
2896      target_size = bytes_allocated + max_free_;
2897    } else {
2898      target_size = std::max(bytes_allocated, static_cast<uint64_t>(max_allowed_footprint_));
2899    }
2900  }
2901  if (!ignore_max_footprint_) {
2902    SetIdealFootprint(target_size);
2903    if (IsGcConcurrent()) {
2904      // Calculate when to perform the next ConcurrentGC.
2905      // Calculate the estimated GC duration.
2906      const double gc_duration_seconds = NsToMs(current_gc_iteration_.GetDurationNs()) / 1000.0;
2907      // Estimate how many remaining bytes we will have when we need to start the next GC.
2908      size_t remaining_bytes = allocation_rate_ * gc_duration_seconds;
2909      remaining_bytes = std::min(remaining_bytes, kMaxConcurrentRemainingBytes);
2910      remaining_bytes = std::max(remaining_bytes, kMinConcurrentRemainingBytes);
2911      if (UNLIKELY(remaining_bytes > max_allowed_footprint_)) {
2912        // A never going to happen situation that from the estimated allocation rate we will exceed
2913        // the applications entire footprint with the given estimated allocation rate. Schedule
2914        // another GC nearly straight away.
2915        remaining_bytes = kMinConcurrentRemainingBytes;
2916      }
2917      DCHECK_LE(remaining_bytes, max_allowed_footprint_);
2918      DCHECK_LE(max_allowed_footprint_, GetMaxMemory());
2919      // Start a concurrent GC when we get close to the estimated remaining bytes. When the
2920      // allocation rate is very high, remaining_bytes could tell us that we should start a GC
2921      // right away.
2922      concurrent_start_bytes_ = std::max(max_allowed_footprint_ - remaining_bytes,
2923                                         static_cast<size_t>(bytes_allocated));
2924    }
2925  }
2926}
2927
2928void Heap::ClearGrowthLimit() {
2929  growth_limit_ = capacity_;
2930  non_moving_space_->ClearGrowthLimit();
2931}
2932
2933void Heap::AddFinalizerReference(Thread* self, mirror::Object** object) {
2934  ScopedObjectAccess soa(self);
2935  ScopedLocalRef<jobject> arg(self->GetJniEnv(), soa.AddLocalReference<jobject>(*object));
2936  jvalue args[1];
2937  args[0].l = arg.get();
2938  InvokeWithJValues(soa, nullptr, WellKnownClasses::java_lang_ref_FinalizerReference_add, args);
2939  // Restore object in case it gets moved.
2940  *object = soa.Decode<mirror::Object*>(arg.get());
2941}
2942
2943void Heap::RequestConcurrentGCAndSaveObject(Thread* self, mirror::Object** obj) {
2944  StackHandleScope<1> hs(self);
2945  HandleWrapper<mirror::Object> wrapper(hs.NewHandleWrapper(obj));
2946  RequestConcurrentGC(self);
2947}
2948
2949void Heap::RequestConcurrentGC(Thread* self) {
2950  // Make sure that we can do a concurrent GC.
2951  Runtime* runtime = Runtime::Current();
2952  if (runtime == nullptr || !runtime->IsFinishedStarting() || runtime->IsShuttingDown(self) ||
2953      self->IsHandlingStackOverflow()) {
2954    return;
2955  }
2956  // We already have a request pending, no reason to start more until we update
2957  // concurrent_start_bytes_.
2958  concurrent_start_bytes_ = std::numeric_limits<size_t>::max();
2959  JNIEnv* env = self->GetJniEnv();
2960  DCHECK(WellKnownClasses::java_lang_Daemons != nullptr);
2961  DCHECK(WellKnownClasses::java_lang_Daemons_requestGC != nullptr);
2962  env->CallStaticVoidMethod(WellKnownClasses::java_lang_Daemons,
2963                            WellKnownClasses::java_lang_Daemons_requestGC);
2964  CHECK(!env->ExceptionCheck());
2965}
2966
2967void Heap::ConcurrentGC(Thread* self) {
2968  if (Runtime::Current()->IsShuttingDown(self)) {
2969    return;
2970  }
2971  // Wait for any GCs currently running to finish.
2972  if (WaitForGcToComplete(kGcCauseBackground, self) == collector::kGcTypeNone) {
2973    // If the we can't run the GC type we wanted to run, find the next appropriate one and try that
2974    // instead. E.g. can't do partial, so do full instead.
2975    if (CollectGarbageInternal(next_gc_type_, kGcCauseBackground, false) ==
2976        collector::kGcTypeNone) {
2977      for (collector::GcType gc_type : gc_plan_) {
2978        // Attempt to run the collector, if we succeed, we are done.
2979        if (gc_type > next_gc_type_ &&
2980            CollectGarbageInternal(gc_type, kGcCauseBackground, false) != collector::kGcTypeNone) {
2981          break;
2982        }
2983      }
2984    }
2985  }
2986}
2987
2988void Heap::RequestCollectorTransition(CollectorType desired_collector_type, uint64_t delta_time) {
2989  Thread* self = Thread::Current();
2990  {
2991    MutexLock mu(self, *heap_trim_request_lock_);
2992    if (desired_collector_type_ == desired_collector_type) {
2993      return;
2994    }
2995    heap_transition_or_trim_target_time_ =
2996        std::max(heap_transition_or_trim_target_time_, NanoTime() + delta_time);
2997    desired_collector_type_ = desired_collector_type;
2998  }
2999  SignalHeapTrimDaemon(self);
3000}
3001
3002void Heap::RequestHeapTrim() {
3003  // GC completed and now we must decide whether to request a heap trim (advising pages back to the
3004  // kernel) or not. Issuing a request will also cause trimming of the libc heap. As a trim scans
3005  // a space it will hold its lock and can become a cause of jank.
3006  // Note, the large object space self trims and the Zygote space was trimmed and unchanging since
3007  // forking.
3008
3009  // We don't have a good measure of how worthwhile a trim might be. We can't use the live bitmap
3010  // because that only marks object heads, so a large array looks like lots of empty space. We
3011  // don't just call dlmalloc all the time, because the cost of an _attempted_ trim is proportional
3012  // to utilization (which is probably inversely proportional to how much benefit we can expect).
3013  // We could try mincore(2) but that's only a measure of how many pages we haven't given away,
3014  // not how much use we're making of those pages.
3015
3016  Thread* self = Thread::Current();
3017  Runtime* runtime = Runtime::Current();
3018  if (runtime == nullptr || !runtime->IsFinishedStarting() || runtime->IsShuttingDown(self)) {
3019    // Heap trimming isn't supported without a Java runtime or Daemons (such as at dex2oat time)
3020    // Also: we do not wish to start a heap trim if the runtime is shutting down (a racy check
3021    // as we don't hold the lock while requesting the trim).
3022    return;
3023  }
3024  {
3025    MutexLock mu(self, *heap_trim_request_lock_);
3026    if (last_trim_time_ + kHeapTrimWait >= NanoTime()) {
3027      // We have done a heap trim in the last kHeapTrimWait nanosecs, don't request another one
3028      // just yet.
3029      return;
3030    }
3031    heap_trim_request_pending_ = true;
3032    uint64_t current_time = NanoTime();
3033    if (heap_transition_or_trim_target_time_ < current_time) {
3034      heap_transition_or_trim_target_time_ = current_time + kHeapTrimWait;
3035    }
3036  }
3037  // Notify the daemon thread which will actually do the heap trim.
3038  SignalHeapTrimDaemon(self);
3039}
3040
3041void Heap::SignalHeapTrimDaemon(Thread* self) {
3042  JNIEnv* env = self->GetJniEnv();
3043  DCHECK(WellKnownClasses::java_lang_Daemons != nullptr);
3044  DCHECK(WellKnownClasses::java_lang_Daemons_requestHeapTrim != nullptr);
3045  env->CallStaticVoidMethod(WellKnownClasses::java_lang_Daemons,
3046                            WellKnownClasses::java_lang_Daemons_requestHeapTrim);
3047  CHECK(!env->ExceptionCheck());
3048}
3049
3050void Heap::RevokeThreadLocalBuffers(Thread* thread) {
3051  if (rosalloc_space_ != nullptr) {
3052    rosalloc_space_->RevokeThreadLocalBuffers(thread);
3053  }
3054  if (bump_pointer_space_ != nullptr) {
3055    bump_pointer_space_->RevokeThreadLocalBuffers(thread);
3056  }
3057}
3058
3059void Heap::RevokeRosAllocThreadLocalBuffers(Thread* thread) {
3060  if (rosalloc_space_ != nullptr) {
3061    rosalloc_space_->RevokeThreadLocalBuffers(thread);
3062  }
3063}
3064
3065void Heap::RevokeAllThreadLocalBuffers() {
3066  if (rosalloc_space_ != nullptr) {
3067    rosalloc_space_->RevokeAllThreadLocalBuffers();
3068  }
3069  if (bump_pointer_space_ != nullptr) {
3070    bump_pointer_space_->RevokeAllThreadLocalBuffers();
3071  }
3072}
3073
3074bool Heap::IsGCRequestPending() const {
3075  return concurrent_start_bytes_ != std::numeric_limits<size_t>::max();
3076}
3077
3078void Heap::RunFinalization(JNIEnv* env) {
3079  // Can't do this in WellKnownClasses::Init since System is not properly set up at that point.
3080  if (WellKnownClasses::java_lang_System_runFinalization == nullptr) {
3081    CHECK(WellKnownClasses::java_lang_System != nullptr);
3082    WellKnownClasses::java_lang_System_runFinalization =
3083        CacheMethod(env, WellKnownClasses::java_lang_System, true, "runFinalization", "()V");
3084    CHECK(WellKnownClasses::java_lang_System_runFinalization != nullptr);
3085  }
3086  env->CallStaticVoidMethod(WellKnownClasses::java_lang_System,
3087                            WellKnownClasses::java_lang_System_runFinalization);
3088  env->CallStaticVoidMethod(WellKnownClasses::java_lang_System,
3089                            WellKnownClasses::java_lang_System_runFinalization);
3090}
3091
3092void Heap::RegisterNativeAllocation(JNIEnv* env, size_t 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, size_t bytes) {
3135  size_t expected_size;
3136  do {
3137    expected_size = native_bytes_allocated_.LoadRelaxed();
3138    if (UNLIKELY(bytes > expected_size)) {
3139      ScopedObjectAccess soa(env);
3140      env->ThrowNew(WellKnownClasses::java_lang_RuntimeException,
3141                    StringPrintf("Attempted to free %zd native bytes with only %zd native bytes "
3142                                 "registered as allocated", bytes, expected_size).c_str());
3143      break;
3144    }
3145  } while (!native_bytes_allocated_.CompareExchangeWeakRelaxed(expected_size,
3146                                                               expected_size - bytes));
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