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