blob: 2497e6a1cd7396d9e30a8f80bf22c191cc9421a6 [file] [log] [blame]
Elliott Hughes2faa5f12012-01-30 14:42:07 -08001/*
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 */
Carl Shapiro69759ea2011-07-21 18:13:35 -070016
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070017#include "heap.h"
Carl Shapiro58551df2011-07-24 03:09:51 -070018
Mathieu Chartier752a0e62013-06-27 11:03:27 -070019#define ATRACE_TAG ATRACE_TAG_DALVIK
20#include <cutils/trace.h>
Brian Carlstrom5643b782012-02-05 12:32:53 -080021
Brian Carlstrom58ae9412011-10-04 00:56:06 -070022#include <limits>
Carl Shapiro58551df2011-07-24 03:09:51 -070023#include <vector>
Hiroshi Yamauchi50b29282013-07-30 13:58:37 -070024#include <valgrind.h>
Carl Shapiro58551df2011-07-24 03:09:51 -070025
Mathieu Chartierb2f99362013-11-20 17:26:00 -080026#include "base/histogram-inl.h"
Elliott Hughes1aa246d2012-12-13 09:29:36 -080027#include "base/stl_util.h"
Mathieu Chartier987ccff2013-07-08 11:05:21 -070028#include "common_throws.h"
Ian Rogers48931882013-01-22 14:35:16 -080029#include "cutils/sched_policy.h"
Elliott Hughes767a1472011-10-26 18:49:02 -070030#include "debugger.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070031#include "gc/accounting/atomic_stack.h"
32#include "gc/accounting/card_table-inl.h"
33#include "gc/accounting/heap_bitmap-inl.h"
Mathieu Chartier590fee92013-09-13 13:46:47 -070034#include "gc/accounting/mod_union_table.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070035#include "gc/accounting/mod_union_table-inl.h"
36#include "gc/accounting/space_bitmap-inl.h"
37#include "gc/collector/mark_sweep-inl.h"
38#include "gc/collector/partial_mark_sweep.h"
Mathieu Chartier590fee92013-09-13 13:46:47 -070039#include "gc/collector/semi_space.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070040#include "gc/collector/sticky_mark_sweep.h"
Mathieu Chartier590fee92013-09-13 13:46:47 -070041#include "gc/space/bump_pointer_space.h"
Hiroshi Yamauchi50b29282013-07-30 13:58:37 -070042#include "gc/space/dlmalloc_space-inl.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070043#include "gc/space/image_space.h"
44#include "gc/space/large_object_space.h"
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -070045#include "gc/space/rosalloc_space-inl.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070046#include "gc/space/space-inl.h"
Mathieu Chartiera1602f22014-01-13 17:19:19 -080047#include "gc/space/zygote_space.h"
Mathieu Chartierd8891782014-03-02 13:28:37 -080048#include "entrypoints/quick/quick_alloc_entrypoints.h"
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -070049#include "heap-inl.h"
Brian Carlstrom9cff8e12011-08-18 16:47:29 -070050#include "image.h"
Jeff Hao5d917302013-02-27 17:57:33 -080051#include "invoke_arg_array_builder.h"
Brian Carlstromea46f952013-07-30 01:26:50 -070052#include "mirror/art_field-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080053#include "mirror/class-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080054#include "mirror/object.h"
55#include "mirror/object-inl.h"
56#include "mirror/object_array-inl.h"
Ian Rogers6d4d9fc2011-11-30 16:24:48 -080057#include "object_utils.h"
Brian Carlstrom5643b782012-02-05 12:32:53 -080058#include "os.h"
Mathieu Chartier0de9f732013-11-22 17:58:48 -080059#include "runtime.h"
Mathieu Chartier7664f5c2012-06-08 18:15:32 -070060#include "ScopedLocalRef.h"
Ian Rogers00f7d0e2012-07-19 15:28:27 -070061#include "scoped_thread_state_change.h"
Ian Rogers1f539342012-10-03 21:09:42 -070062#include "sirt_ref.h"
Elliott Hughes8d768a92011-09-14 16:35:25 -070063#include "thread_list.h"
Elliott Hughes767a1472011-10-26 18:49:02 -070064#include "UniquePtr.h"
Elliott Hugheseac76672012-05-24 21:56:51 -070065#include "well_known_classes.h"
Carl Shapiro69759ea2011-07-21 18:13:35 -070066
67namespace art {
Mathieu Chartier50482232013-11-21 11:48:14 -080068
Ian Rogers1d54e732013-05-02 21:10:01 -070069namespace gc {
Carl Shapiro69759ea2011-07-21 18:13:35 -070070
Mathieu Chartier720ef762013-08-17 14:46:54 -070071static constexpr bool kGCALotMode = false;
72static constexpr size_t kGcAlotInterval = KB;
Ian Rogers1d54e732013-05-02 21:10:01 -070073// Minimum amount of remaining bytes before a concurrent GC is triggered.
Mathieu Chartier720ef762013-08-17 14:46:54 -070074static constexpr size_t kMinConcurrentRemainingBytes = 128 * KB;
Mathieu Chartier74762802014-01-24 10:21:35 -080075static constexpr size_t kMaxConcurrentRemainingBytes = 512 * KB;
Mathieu Chartier0051be62012-10-12 17:47:11 -070076
Mathieu Chartier0051be62012-10-12 17:47:11 -070077Heap::Heap(size_t initial_size, size_t growth_limit, size_t min_free, size_t max_free,
Ian Rogers8d31bbd2013-10-13 10:44:14 -070078 double target_utilization, size_t capacity, const std::string& image_file_name,
Mathieu Chartiere6da9af2013-12-16 11:54:42 -080079 CollectorType post_zygote_collector_type, CollectorType background_collector_type,
80 size_t parallel_gc_threads, size_t conc_gc_threads, bool low_memory_mode,
81 size_t long_pause_log_threshold, size_t long_gc_log_threshold,
Mathieu Chartier938a03b2014-01-16 15:10:31 -080082 bool ignore_max_footprint, bool use_tlab, bool verify_pre_gc_heap,
Hiroshi Yamauchia4adbfd2014-02-04 18:12:17 -080083 bool verify_post_gc_heap, bool verify_pre_gc_rosalloc,
84 bool verify_post_gc_rosalloc)
Mathieu Chartiercbb2d202013-11-14 17:45:16 -080085 : non_moving_space_(nullptr),
Mathieu Chartiere6da9af2013-12-16 11:54:42 -080086 rosalloc_space_(nullptr),
87 dlmalloc_space_(nullptr),
Mathieu Chartierfc5b5282014-01-09 16:15:36 -080088 main_space_(nullptr),
Mathieu Chartier7bf82af2013-12-06 16:51:45 -080089 concurrent_gc_(false),
90 collector_type_(kCollectorTypeNone),
91 post_zygote_collector_type_(post_zygote_collector_type),
Mathieu Chartiere6da9af2013-12-16 11:54:42 -080092 background_collector_type_(background_collector_type),
Mathieu Chartiera5f9de02014-02-28 16:48:42 -080093 desired_collector_type_(collector_type_),
94 heap_trim_request_lock_(nullptr),
95 heap_trim_target_time_(0),
96 heap_transition_target_time_(0),
97 heap_trim_request_pending_(false),
Mathieu Chartier2775ee42013-08-20 17:43:47 -070098 parallel_gc_threads_(parallel_gc_threads),
99 conc_gc_threads_(conc_gc_threads),
Mathieu Chartiere0a53e92013-08-05 10:17:40 -0700100 low_memory_mode_(low_memory_mode),
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700101 long_pause_log_threshold_(long_pause_log_threshold),
102 long_gc_log_threshold_(long_gc_log_threshold),
103 ignore_max_footprint_(ignore_max_footprint),
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700104 have_zygote_space_(false),
Mathieu Chartierbd0a6532014-02-27 11:14:21 -0800105 large_object_threshold_(std::numeric_limits<size_t>::max()), // Starts out disabled.
Mathieu Chartier39e32612013-11-12 16:28:05 -0800106 soft_reference_queue_(this),
107 weak_reference_queue_(this),
108 finalizer_reference_queue_(this),
109 phantom_reference_queue_(this),
110 cleared_references_(this),
Mathieu Chartierd5a89ee2014-01-31 09:55:13 -0800111 collector_type_running_(kCollectorTypeNone),
Ian Rogers1d54e732013-05-02 21:10:01 -0700112 last_gc_type_(collector::kGcTypeNone),
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -0700113 next_gc_type_(collector::kGcTypePartial),
Mathieu Chartier80de7a62012-11-27 17:21:50 -0800114 capacity_(capacity),
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700115 growth_limit_(growth_limit),
Mathieu Chartier0051be62012-10-12 17:47:11 -0700116 max_allowed_footprint_(initial_size),
Mathieu Chartier987ccff2013-07-08 11:05:21 -0700117 native_footprint_gc_watermark_(initial_size),
118 native_footprint_limit_(2 * initial_size),
Mathieu Chartier590fee92013-09-13 13:46:47 -0700119 native_need_to_run_finalization_(false),
Mathieu Chartierca2a24d2013-11-25 15:12:12 -0800120 // Initially assume we perceive jank in case the process state is never updated.
121 process_state_(kProcessStateJankPerceptible),
Mathieu Chartier7bf82af2013-12-06 16:51:45 -0800122 concurrent_start_bytes_(std::numeric_limits<size_t>::max()),
Ian Rogers1d54e732013-05-02 21:10:01 -0700123 total_bytes_freed_ever_(0),
124 total_objects_freed_ever_(0),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800125 num_bytes_allocated_(0),
Mathieu Chartier987ccff2013-07-08 11:05:21 -0700126 native_bytes_allocated_(0),
Mathieu Chartier0a9dc052013-07-25 11:01:28 -0700127 gc_memory_overhead_(0),
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700128 verify_missing_card_marks_(false),
129 verify_system_weaks_(false),
Mathieu Chartier938a03b2014-01-16 15:10:31 -0800130 verify_pre_gc_heap_(verify_pre_gc_heap),
131 verify_post_gc_heap_(verify_post_gc_heap),
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700132 verify_mod_union_table_(false),
Hiroshi Yamauchia4adbfd2014-02-04 18:12:17 -0800133 verify_pre_gc_rosalloc_(verify_pre_gc_rosalloc),
134 verify_post_gc_rosalloc_(verify_post_gc_rosalloc),
Mathieu Chartier65db8802012-11-20 12:36:46 -0800135 allocation_rate_(0),
Mathieu Chartier0418ae22013-07-31 13:35:46 -0700136 /* For GC a lot mode, we limit the allocations stacks to be kGcAlotInterval allocations. This
137 * causes a lot of GC since we do a GC for alloc whenever the stack is full. When heap
138 * verification is enabled, we limit the size of allocation stacks to speed up their
139 * searching.
140 */
141 max_allocation_stack_size_(kGCALotMode ? kGcAlotInterval
Mathieu Chartier4e305412014-02-19 10:54:44 -0800142 : (kVerifyObjectSupport > kVerifyObjectModeFast) ? KB : MB),
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800143 current_allocator_(kAllocatorTypeDlMalloc),
144 current_non_moving_allocator_(kAllocatorTypeNonMoving),
Mathieu Chartier590fee92013-09-13 13:46:47 -0700145 bump_pointer_space_(nullptr),
146 temp_space_(nullptr),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800147 reference_referent_offset_(0),
148 reference_queue_offset_(0),
149 reference_queueNext_offset_(0),
150 reference_pendingNext_offset_(0),
151 finalizer_reference_zombie_offset_(0),
Mathieu Chartier0051be62012-10-12 17:47:11 -0700152 min_free_(min_free),
153 max_free_(max_free),
154 target_utilization_(target_utilization),
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700155 total_wait_time_(0),
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700156 total_allocation_time_(0),
Mathieu Chartier4e305412014-02-19 10:54:44 -0800157 verify_object_mode_(kVerifyObjectModeDisabled),
Mathieu Chartier1d27b342014-01-28 12:51:09 -0800158 disable_moving_gc_count_(0),
Mathieu Chartier661974a2014-01-09 11:23:53 -0800159 running_on_valgrind_(RUNNING_ON_VALGRIND > 0),
Mathieu Chartier692fafd2013-11-29 17:24:40 -0800160 use_tlab_(use_tlab) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800161 if (VLOG_IS_ON(heap) || VLOG_IS_ON(startup)) {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800162 LOG(INFO) << "Heap() entering";
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700163 }
Mathieu Chartier50482232013-11-21 11:48:14 -0800164 // If we aren't the zygote, switch to the default non zygote allocator. This may update the
165 // entrypoints.
Mathieu Chartierbd0a6532014-02-27 11:14:21 -0800166 if (!Runtime::Current()->IsZygote()) {
Mathieu Chartiera5f9de02014-02-28 16:48:42 -0800167 desired_collector_type_ = post_zygote_collector_type_;
Mathieu Chartierbd0a6532014-02-27 11:14:21 -0800168 large_object_threshold_ = kDefaultLargeObjectThreshold;
Mathieu Chartier7bf82af2013-12-06 16:51:45 -0800169 } else {
Mathieu Chartierbd0a6532014-02-27 11:14:21 -0800170 if (kMovingCollector) {
171 // We are the zygote, use bump pointer allocation + semi space collector.
Mathieu Chartiera5f9de02014-02-28 16:48:42 -0800172 desired_collector_type_ = kCollectorTypeSS;
Mathieu Chartierbd0a6532014-02-27 11:14:21 -0800173 } else {
Mathieu Chartiera5f9de02014-02-28 16:48:42 -0800174 desired_collector_type_ = post_zygote_collector_type_;
Mathieu Chartierbd0a6532014-02-27 11:14:21 -0800175 }
Mathieu Chartier50482232013-11-21 11:48:14 -0800176 }
Mathieu Chartiera5f9de02014-02-28 16:48:42 -0800177 ChangeCollector(desired_collector_type_);
Mathieu Chartier7bf82af2013-12-06 16:51:45 -0800178
Ian Rogers1d54e732013-05-02 21:10:01 -0700179 live_bitmap_.reset(new accounting::HeapBitmap(this));
180 mark_bitmap_.reset(new accounting::HeapBitmap(this));
Ian Rogers30fab402012-01-23 15:43:46 -0800181 // Requested begin for the alloc space, to follow the mapped image and oat files
Mathieu Chartier50482232013-11-21 11:48:14 -0800182 byte* requested_alloc_space_begin = nullptr;
Brian Carlstrom5643b782012-02-05 12:32:53 -0800183 if (!image_file_name.empty()) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700184 space::ImageSpace* image_space = space::ImageSpace::Create(image_file_name.c_str());
Mathieu Chartier50482232013-11-21 11:48:14 -0800185 CHECK(image_space != nullptr) << "Failed to create space for " << image_file_name;
Mathieu Chartier590fee92013-09-13 13:46:47 -0700186 AddSpace(image_space);
Ian Rogers30fab402012-01-23 15:43:46 -0800187 // Oat files referenced by image files immediately follow them in memory, ensure alloc space
188 // isn't going to get in the middle
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800189 byte* oat_file_end_addr = image_space->GetImageHeader().GetOatFileEnd();
190 CHECK_GT(oat_file_end_addr, image_space->End());
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700191 if (oat_file_end_addr > requested_alloc_space_begin) {
Mathieu Chartier50482232013-11-21 11:48:14 -0800192 requested_alloc_space_begin = AlignUp(oat_file_end_addr, kPageSize);
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700193 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700194 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700195 const char* name = Runtime::Current()->IsZygote() ? "zygote space" : "alloc space";
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800196 space::MallocSpace* malloc_space;
197 if (kUseRosAlloc) {
198 malloc_space = space::RosAllocSpace::Create(name, initial_size, growth_limit, capacity,
199 requested_alloc_space_begin, low_memory_mode_);
200 CHECK(malloc_space != nullptr) << "Failed to create rosalloc space";
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -0700201 } else {
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800202 malloc_space = space::DlMallocSpace::Create(name, initial_size, growth_limit, capacity,
203 requested_alloc_space_begin);
204 CHECK(malloc_space != nullptr) << "Failed to create dlmalloc space";
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -0700205 }
Hiroshi Yamauchi05e713a2014-01-09 13:24:51 -0800206 VLOG(heap) << "malloc_space : " << malloc_space;
Mathieu Chartier590fee92013-09-13 13:46:47 -0700207 if (kMovingCollector) {
208 // TODO: Place bump-pointer spaces somewhere to minimize size of card table.
209 // TODO: Having 3+ spaces as big as the large heap size can cause virtual memory fragmentation
210 // issues.
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800211 const size_t bump_pointer_space_size = std::min(malloc_space->Capacity(), 128 * MB);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700212 bump_pointer_space_ = space::BumpPointerSpace::Create("Bump pointer space",
213 bump_pointer_space_size, nullptr);
214 CHECK(bump_pointer_space_ != nullptr) << "Failed to create bump pointer space";
215 AddSpace(bump_pointer_space_);
216 temp_space_ = space::BumpPointerSpace::Create("Bump pointer space 2", bump_pointer_space_size,
217 nullptr);
218 CHECK(temp_space_ != nullptr) << "Failed to create bump pointer space";
219 AddSpace(temp_space_);
Hiroshi Yamauchi05e713a2014-01-09 13:24:51 -0800220 VLOG(heap) << "bump_pointer_space : " << bump_pointer_space_;
221 VLOG(heap) << "temp_space : " << temp_space_;
Mathieu Chartier590fee92013-09-13 13:46:47 -0700222 }
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800223 non_moving_space_ = malloc_space;
224 malloc_space->SetFootprintLimit(malloc_space->Capacity());
225 AddSpace(malloc_space);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700226
Mathieu Chartiereb5710e2013-07-25 15:19:42 -0700227 // Allocate the large object space.
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800228 constexpr bool kUseFreeListSpaceForLOS = false;
Mathieu Chartiereb5710e2013-07-25 15:19:42 -0700229 if (kUseFreeListSpaceForLOS) {
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800230 large_object_space_ = space::FreeListSpace::Create("large object space", nullptr, capacity);
Mathieu Chartiereb5710e2013-07-25 15:19:42 -0700231 } else {
232 large_object_space_ = space::LargeObjectMapSpace::Create("large object space");
233 }
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800234 CHECK(large_object_space_ != nullptr) << "Failed to create large object space";
Mathieu Chartier590fee92013-09-13 13:46:47 -0700235 AddSpace(large_object_space_);
Mathieu Chartiereb5710e2013-07-25 15:19:42 -0700236
Ian Rogers1d54e732013-05-02 21:10:01 -0700237 // Compute heap capacity. Continuous spaces are sorted in order of Begin().
Mathieu Chartier590fee92013-09-13 13:46:47 -0700238 CHECK(!continuous_spaces_.empty());
Mathieu Chartier938a03b2014-01-16 15:10:31 -0800239
Mathieu Chartier590fee92013-09-13 13:46:47 -0700240 // Relies on the spaces being sorted.
Mathieu Chartier9be9a7a2014-01-24 14:07:33 -0800241 byte* heap_begin = continuous_spaces_.front()->Begin();
242 byte* heap_end = continuous_spaces_.back()->Limit();
243 if (Runtime::Current()->IsZygote()) {
244 std::string error_str;
245 post_zygote_non_moving_space_mem_map_.reset(
246 MemMap::MapAnonymous("post zygote non-moving space", nullptr, 64 * MB,
Ian Rogersef7d42f2014-01-06 12:55:46 -0800247 PROT_READ | PROT_WRITE, true, &error_str));
Mathieu Chartier9be9a7a2014-01-24 14:07:33 -0800248 CHECK(post_zygote_non_moving_space_mem_map_.get() != nullptr) << error_str;
249 heap_begin = std::min(post_zygote_non_moving_space_mem_map_->Begin(), heap_begin);
250 heap_end = std::max(post_zygote_non_moving_space_mem_map_->End(), heap_end);
251 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700252 size_t heap_capacity = heap_end - heap_begin;
Carl Shapiro69759ea2011-07-21 18:13:35 -0700253
Elliott Hughes6c9c06d2011-11-07 16:43:47 -0800254 // Allocate the card table.
Ian Rogers1d54e732013-05-02 21:10:01 -0700255 card_table_.reset(accounting::CardTable::Create(heap_begin, heap_capacity));
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700256 CHECK(card_table_.get() != NULL) << "Failed to create card table";
Ian Rogers5d76c432011-10-31 21:42:49 -0700257
Mathieu Chartier590fee92013-09-13 13:46:47 -0700258 // Card cache for now since it makes it easier for us to update the references to the copying
259 // spaces.
Mathieu Chartier11409ae2013-09-23 11:49:36 -0700260 accounting::ModUnionTable* mod_union_table =
Mathieu Chartier590fee92013-09-13 13:46:47 -0700261 new accounting::ModUnionTableCardCache("Image mod-union table", this, GetImageSpace());
Mathieu Chartier11409ae2013-09-23 11:49:36 -0700262 CHECK(mod_union_table != nullptr) << "Failed to create image mod-union table";
263 AddModUnionTable(mod_union_table);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700264
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700265 // TODO: Count objects in the image space here.
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -0700266 num_bytes_allocated_ = 0;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700267
Mathieu Chartierd22d5482012-11-06 17:14:12 -0800268 // Default mark stack size in bytes.
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700269 static const size_t default_mark_stack_size = 64 * KB;
Ian Rogers1d54e732013-05-02 21:10:01 -0700270 mark_stack_.reset(accounting::ObjectStack::Create("mark stack", default_mark_stack_size));
271 allocation_stack_.reset(accounting::ObjectStack::Create("allocation stack",
272 max_allocation_stack_size_));
273 live_stack_.reset(accounting::ObjectStack::Create("live stack",
274 max_allocation_stack_size_));
Mathieu Chartier5301cd22012-05-31 12:11:36 -0700275
Mathieu Chartier65db8802012-11-20 12:36:46 -0800276 // It's still too early to take a lock because there are no threads yet, but we can create locks
277 // now. We don't create it earlier to make it clear that you can't use locks during heap
278 // initialization.
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700279 gc_complete_lock_ = new Mutex("GC complete lock");
Ian Rogersc604d732012-10-14 16:09:54 -0700280 gc_complete_cond_.reset(new ConditionVariable("GC complete condition variable",
281 *gc_complete_lock_));
Mathieu Chartiera5f9de02014-02-28 16:48:42 -0800282 heap_trim_request_lock_ = new Mutex("Heap trim request lock");
Mathieu Chartier65db8802012-11-20 12:36:46 -0800283 last_gc_size_ = GetBytesAllocated();
284
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700285 if (ignore_max_footprint_) {
286 SetIdealFootprint(std::numeric_limits<size_t>::max());
Mathieu Chartier590fee92013-09-13 13:46:47 -0700287 concurrent_start_bytes_ = std::numeric_limits<size_t>::max();
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700288 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700289 CHECK_NE(max_allowed_footprint_, 0U);
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700290
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800291 // Create our garbage collectors.
Mathieu Chartier50482232013-11-21 11:48:14 -0800292 for (size_t i = 0; i < 2; ++i) {
293 const bool concurrent = i != 0;
294 garbage_collectors_.push_back(new collector::MarkSweep(this, concurrent));
295 garbage_collectors_.push_back(new collector::PartialMarkSweep(this, concurrent));
296 garbage_collectors_.push_back(new collector::StickyMarkSweep(this, concurrent));
297 }
Mathieu Chartier50482232013-11-21 11:48:14 -0800298 if (kMovingCollector) {
299 // TODO: Clean this up.
Hiroshi Yamauchi6f4ffe42014-01-13 12:30:44 -0800300 bool generational = post_zygote_collector_type_ == kCollectorTypeGSS;
301 semi_space_collector_ = new collector::SemiSpace(this, generational);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700302 garbage_collectors_.push_back(semi_space_collector_);
Mathieu Chartier0325e622012-09-05 14:22:51 -0700303 }
304
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -0700305 if (running_on_valgrind_) {
Ian Rogersfa824272013-11-05 16:12:57 -0800306 Runtime::Current()->GetInstrumentation()->InstrumentQuickAllocEntryPoints();
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -0700307 }
308
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800309 if (VLOG_IS_ON(heap) || VLOG_IS_ON(startup)) {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800310 LOG(INFO) << "Heap() exiting";
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700311 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700312}
313
Mathieu Chartier50482232013-11-21 11:48:14 -0800314void Heap::ChangeAllocator(AllocatorType allocator) {
Mathieu Chartier50482232013-11-21 11:48:14 -0800315 if (current_allocator_ != allocator) {
Mathieu Chartierd8891782014-03-02 13:28:37 -0800316 // These two allocators are only used internally and don't have any entrypoints.
317 CHECK_NE(allocator, kAllocatorTypeLOS);
318 CHECK_NE(allocator, kAllocatorTypeNonMoving);
Mathieu Chartier50482232013-11-21 11:48:14 -0800319 current_allocator_ = allocator;
Mathieu Chartierd8891782014-03-02 13:28:37 -0800320 MutexLock mu(nullptr, *Locks::runtime_shutdown_lock_);
Mathieu Chartier50482232013-11-21 11:48:14 -0800321 SetQuickAllocEntryPointsAllocator(current_allocator_);
322 Runtime::Current()->GetInstrumentation()->ResetQuickAllocEntryPoints();
323 }
324}
325
Mathieu Chartier6dda8982014-03-06 11:11:48 -0800326void Heap::DisableCompaction() {
327 if (IsCompactingGC(post_zygote_collector_type_)) {
328 post_zygote_collector_type_ = kCollectorTypeCMS;
329 }
330 if (IsCompactingGC(background_collector_type_)) {
331 background_collector_type_ = post_zygote_collector_type_;
332 }
333 TransitionCollector(post_zygote_collector_type_);
334}
335
Mathieu Chartier15d34022014-02-26 17:16:38 -0800336std::string Heap::SafeGetClassDescriptor(mirror::Class* klass) {
337 if (!IsValidContinuousSpaceObjectAddress(klass)) {
338 return StringPrintf("<non heap address klass %p>", klass);
339 }
340 mirror::Class* component_type = klass->GetComponentType<kVerifyNone>();
341 if (IsValidContinuousSpaceObjectAddress(component_type) && klass->IsArrayClass<kVerifyNone>()) {
342 std::string result("[");
343 result += SafeGetClassDescriptor(component_type);
344 return result;
345 } else if (UNLIKELY(klass->IsPrimitive<kVerifyNone>())) {
346 return Primitive::Descriptor(klass->GetPrimitiveType<kVerifyNone>());
Mathieu Chartierc2f4d022014-03-03 16:11:42 -0800347 } else if (UNLIKELY(klass->IsProxyClass<kVerifyNone>())) {
Mathieu Chartier15d34022014-02-26 17:16:38 -0800348 return Runtime::Current()->GetClassLinker()->GetDescriptorForProxy(klass);
349 } else {
Mathieu Chartierc2f4d022014-03-03 16:11:42 -0800350 mirror::DexCache* dex_cache = klass->GetDexCache<kVerifyNone>();
Mathieu Chartier15d34022014-02-26 17:16:38 -0800351 if (!IsValidContinuousSpaceObjectAddress(dex_cache)) {
352 return StringPrintf("<non heap address dex_cache %p>", dex_cache);
353 }
354 const DexFile* dex_file = dex_cache->GetDexFile();
355 uint16_t class_def_idx = klass->GetDexClassDefIndex();
356 if (class_def_idx == DexFile::kDexNoIndex16) {
357 return "<class def not found>";
358 }
359 const DexFile::ClassDef& class_def = dex_file->GetClassDef(class_def_idx);
360 const DexFile::TypeId& type_id = dex_file->GetTypeId(class_def.class_idx_);
361 return dex_file->GetTypeDescriptor(type_id);
362 }
363}
364
365std::string Heap::SafePrettyTypeOf(mirror::Object* obj) {
366 if (obj == nullptr) {
367 return "null";
368 }
369 mirror::Class* klass = obj->GetClass<kVerifyNone>();
370 if (klass == nullptr) {
371 return "(class=null)";
372 }
373 std::string result(SafeGetClassDescriptor(klass));
374 if (obj->IsClass()) {
Mathieu Chartierc2f4d022014-03-03 16:11:42 -0800375 result += "<" + SafeGetClassDescriptor(obj->AsClass<kVerifyNone>()) + ">";
Mathieu Chartier15d34022014-02-26 17:16:38 -0800376 }
377 return result;
378}
379
380void Heap::DumpObject(std::ostream& stream, mirror::Object* obj) {
381 if (obj == nullptr) {
382 stream << "(obj=null)";
383 return;
384 }
385 if (IsAligned<kObjectAlignment>(obj)) {
386 space::Space* space = nullptr;
387 // Don't use find space since it only finds spaces which actually contain objects instead of
388 // spaces which may contain objects (e.g. cleared bump pointer spaces).
389 for (const auto& cur_space : continuous_spaces_) {
390 if (cur_space->HasAddress(obj)) {
391 space = cur_space;
392 break;
393 }
394 }
395 if (space == nullptr) {
396 if (allocator_mem_map_.get() == nullptr || !allocator_mem_map_->HasAddress(obj)) {
397 stream << "obj " << obj << " not a valid heap address";
398 return;
399 } else if (allocator_mem_map_.get() != nullptr) {
400 allocator_mem_map_->Protect(PROT_READ | PROT_WRITE);
401 }
402 }
403 // Unprotect all the spaces.
404 for (const auto& space : continuous_spaces_) {
405 mprotect(space->Begin(), space->Capacity(), PROT_READ | PROT_WRITE);
406 }
407 stream << "Object " << obj;
408 if (space != nullptr) {
409 stream << " in space " << *space;
410 }
Mathieu Chartierc2f4d022014-03-03 16:11:42 -0800411 mirror::Class* klass = obj->GetClass<kVerifyNone>();
Mathieu Chartier15d34022014-02-26 17:16:38 -0800412 stream << "\nclass=" << klass;
413 if (klass != nullptr) {
414 stream << " type= " << SafePrettyTypeOf(obj);
415 }
416 // Re-protect the address we faulted on.
417 mprotect(AlignDown(obj, kPageSize), kPageSize, PROT_NONE);
418 }
419}
420
Mathieu Chartier590fee92013-09-13 13:46:47 -0700421bool Heap::IsCompilingBoot() const {
422 for (const auto& space : continuous_spaces_) {
Mathieu Chartier4e305412014-02-19 10:54:44 -0800423 if (space->IsImageSpace() || space->IsZygoteSpace()) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700424 return false;
425 }
426 }
427 return true;
428}
429
430bool Heap::HasImageSpace() const {
431 for (const auto& space : continuous_spaces_) {
432 if (space->IsImageSpace()) {
433 return true;
434 }
435 }
436 return false;
437}
438
Mathieu Chartier1d27b342014-01-28 12:51:09 -0800439void Heap::IncrementDisableMovingGC(Thread* self) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700440 // Need to do this holding the lock to prevent races where the GC is about to run / running when
441 // we attempt to disable it.
Mathieu Chartiercaa82d62014-02-02 16:51:17 -0800442 ScopedThreadStateChange tsc(self, kWaitingForGcToComplete);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700443 MutexLock mu(self, *gc_complete_lock_);
Mathieu Chartier1d27b342014-01-28 12:51:09 -0800444 ++disable_moving_gc_count_;
Mathieu Chartierd5a89ee2014-01-31 09:55:13 -0800445 if (IsCompactingGC(collector_type_running_)) {
446 WaitForGcToCompleteLocked(self);
447 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700448}
449
Mathieu Chartier1d27b342014-01-28 12:51:09 -0800450void Heap::DecrementDisableMovingGC(Thread* self) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700451 MutexLock mu(self, *gc_complete_lock_);
Mathieu Chartier1d27b342014-01-28 12:51:09 -0800452 CHECK_GE(disable_moving_gc_count_, 0U);
453 --disable_moving_gc_count_;
Mathieu Chartier590fee92013-09-13 13:46:47 -0700454}
455
Mathieu Chartierca2a24d2013-11-25 15:12:12 -0800456void Heap::UpdateProcessState(ProcessState process_state) {
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800457 if (process_state_ != process_state) {
458 process_state_ = process_state;
459 if (process_state_ == kProcessStateJankPerceptible) {
Mathieu Chartiera5f9de02014-02-28 16:48:42 -0800460 // Transition back to foreground right away to prevent jank.
461 RequestHeapTransition(post_zygote_collector_type_, 0);
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800462 } else {
Mathieu Chartiera5f9de02014-02-28 16:48:42 -0800463 // Don't delay for debug builds since we may want to stress test the GC.
464 RequestHeapTransition(background_collector_type_, kIsDebugBuild ? 0 : kHeapTransitionWait);
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800465 }
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800466 }
Mathieu Chartierca2a24d2013-11-25 15:12:12 -0800467}
468
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700469void Heap::CreateThreadPool() {
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700470 const size_t num_threads = std::max(parallel_gc_threads_, conc_gc_threads_);
471 if (num_threads != 0) {
Mathieu Chartierbcd5e9d2013-11-13 14:33:28 -0800472 thread_pool_.reset(new ThreadPool("Heap thread pool", num_threads));
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700473 }
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700474}
475
Mathieu Chartier83c8ee02014-01-28 14:50:23 -0800476void Heap::VisitObjects(ObjectCallback callback, void* arg) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700477 Thread* self = Thread::Current();
Mathieu Chartier692fafd2013-11-29 17:24:40 -0800478 // GCs can move objects, so don't allow this.
479 const char* old_cause = self->StartAssertNoThreadSuspension("Visiting objects");
Mathieu Chartier590fee92013-09-13 13:46:47 -0700480 if (bump_pointer_space_ != nullptr) {
Mathieu Chartier692fafd2013-11-29 17:24:40 -0800481 // Visit objects in bump pointer space.
482 bump_pointer_space_->Walk(callback, arg);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700483 }
484 // TODO: Switch to standard begin and end to use ranged a based loop.
485 for (mirror::Object** it = allocation_stack_->Begin(), **end = allocation_stack_->End();
486 it < end; ++it) {
487 mirror::Object* obj = *it;
Mathieu Chartierebdf3f32014-02-13 10:23:27 -0800488 if (obj != nullptr && obj->GetClass() != nullptr) {
489 // Avoid the race condition caused by the object not yet being written into the allocation
Hiroshi Yamauchif5b0e202014-02-11 17:02:22 -0800490 // stack or the class not yet being written in the object. Or, if kUseThreadLocalAllocationStack,
491 // there can be nulls on the allocation stack.
Mathieu Chartierebdf3f32014-02-13 10:23:27 -0800492 callback(obj, arg);
493 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700494 }
495 GetLiveBitmap()->Walk(callback, arg);
Mathieu Chartier692fafd2013-11-29 17:24:40 -0800496 self->EndAssertNoThreadSuspension(old_cause);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700497}
498
499void Heap::MarkAllocStackAsLive(accounting::ObjectStack* stack) {
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800500 space::ContinuousSpace* space1 = rosalloc_space_ != nullptr ? rosalloc_space_ : non_moving_space_;
501 space::ContinuousSpace* space2 = dlmalloc_space_ != nullptr ? dlmalloc_space_ : non_moving_space_;
502 // This is just logic to handle a case of either not having a rosalloc or dlmalloc space.
503 // TODO: Generalize this to n bitmaps?
504 if (space1 == nullptr) {
505 DCHECK(space2 != nullptr);
506 space1 = space2;
507 }
508 if (space2 == nullptr) {
509 DCHECK(space1 != nullptr);
510 space2 = space1;
511 }
512 MarkAllocStack(space1->GetLiveBitmap(), space2->GetLiveBitmap(),
513 large_object_space_->GetLiveObjects(), stack);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700514}
515
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700516void Heap::DeleteThreadPool() {
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700517 thread_pool_.reset(nullptr);
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700518}
519
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800520void Heap::AddSpace(space::Space* space, bool set_as_default) {
521 DCHECK(space != nullptr);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700522 WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
523 if (space->IsContinuousSpace()) {
524 DCHECK(!space->IsDiscontinuousSpace());
525 space::ContinuousSpace* continuous_space = space->AsContinuousSpace();
526 // Continuous spaces don't necessarily have bitmaps.
527 accounting::SpaceBitmap* live_bitmap = continuous_space->GetLiveBitmap();
528 accounting::SpaceBitmap* mark_bitmap = continuous_space->GetMarkBitmap();
529 if (live_bitmap != nullptr) {
530 DCHECK(mark_bitmap != nullptr);
531 live_bitmap_->AddContinuousSpaceBitmap(live_bitmap);
532 mark_bitmap_->AddContinuousSpaceBitmap(mark_bitmap);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700533 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700534 continuous_spaces_.push_back(continuous_space);
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800535 if (set_as_default) {
536 if (continuous_space->IsDlMallocSpace()) {
537 dlmalloc_space_ = continuous_space->AsDlMallocSpace();
538 } else if (continuous_space->IsRosAllocSpace()) {
539 rosalloc_space_ = continuous_space->AsRosAllocSpace();
540 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700541 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700542 // Ensure that spaces remain sorted in increasing order of start address.
543 std::sort(continuous_spaces_.begin(), continuous_spaces_.end(),
544 [](const space::ContinuousSpace* a, const space::ContinuousSpace* b) {
545 return a->Begin() < b->Begin();
546 });
Mathieu Chartier590fee92013-09-13 13:46:47 -0700547 } else {
548 DCHECK(space->IsDiscontinuousSpace());
549 space::DiscontinuousSpace* discontinuous_space = space->AsDiscontinuousSpace();
550 DCHECK(discontinuous_space->GetLiveObjects() != nullptr);
551 live_bitmap_->AddDiscontinuousObjectSet(discontinuous_space->GetLiveObjects());
552 DCHECK(discontinuous_space->GetMarkObjects() != nullptr);
553 mark_bitmap_->AddDiscontinuousObjectSet(discontinuous_space->GetMarkObjects());
554 discontinuous_spaces_.push_back(discontinuous_space);
555 }
556 if (space->IsAllocSpace()) {
557 alloc_spaces_.push_back(space->AsAllocSpace());
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700558 }
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800559}
560
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800561void Heap::RemoveSpace(space::Space* space) {
562 DCHECK(space != nullptr);
563 WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
564 if (space->IsContinuousSpace()) {
565 DCHECK(!space->IsDiscontinuousSpace());
566 space::ContinuousSpace* continuous_space = space->AsContinuousSpace();
567 // Continuous spaces don't necessarily have bitmaps.
568 accounting::SpaceBitmap* live_bitmap = continuous_space->GetLiveBitmap();
569 accounting::SpaceBitmap* mark_bitmap = continuous_space->GetMarkBitmap();
570 if (live_bitmap != nullptr) {
571 DCHECK(mark_bitmap != nullptr);
572 live_bitmap_->RemoveContinuousSpaceBitmap(live_bitmap);
573 mark_bitmap_->RemoveContinuousSpaceBitmap(mark_bitmap);
574 }
575 auto it = std::find(continuous_spaces_.begin(), continuous_spaces_.end(), continuous_space);
576 DCHECK(it != continuous_spaces_.end());
577 continuous_spaces_.erase(it);
578 if (continuous_space == dlmalloc_space_) {
579 dlmalloc_space_ = nullptr;
580 } else if (continuous_space == rosalloc_space_) {
581 rosalloc_space_ = nullptr;
582 }
Mathieu Chartierfc5b5282014-01-09 16:15:36 -0800583 if (continuous_space == main_space_) {
584 main_space_ = nullptr;
585 }
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800586 } else {
587 DCHECK(space->IsDiscontinuousSpace());
588 space::DiscontinuousSpace* discontinuous_space = space->AsDiscontinuousSpace();
589 DCHECK(discontinuous_space->GetLiveObjects() != nullptr);
590 live_bitmap_->RemoveDiscontinuousObjectSet(discontinuous_space->GetLiveObjects());
591 DCHECK(discontinuous_space->GetMarkObjects() != nullptr);
592 mark_bitmap_->RemoveDiscontinuousObjectSet(discontinuous_space->GetMarkObjects());
593 auto it = std::find(discontinuous_spaces_.begin(), discontinuous_spaces_.end(),
594 discontinuous_space);
595 DCHECK(it != discontinuous_spaces_.end());
596 discontinuous_spaces_.erase(it);
597 }
598 if (space->IsAllocSpace()) {
599 auto it = std::find(alloc_spaces_.begin(), alloc_spaces_.end(), space->AsAllocSpace());
600 DCHECK(it != alloc_spaces_.end());
601 alloc_spaces_.erase(it);
602 }
603}
604
Mathieu Chartier0a9dc052013-07-25 11:01:28 -0700605void Heap::RegisterGCAllocation(size_t bytes) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700606 if (this != nullptr) {
Ian Rogersb122a4b2013-11-19 18:00:50 -0800607 gc_memory_overhead_.FetchAndAdd(bytes);
Mathieu Chartier0a9dc052013-07-25 11:01:28 -0700608 }
609}
610
611void Heap::RegisterGCDeAllocation(size_t bytes) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700612 if (this != nullptr) {
Ian Rogersb122a4b2013-11-19 18:00:50 -0800613 gc_memory_overhead_.FetchAndSub(bytes);
Mathieu Chartier0a9dc052013-07-25 11:01:28 -0700614 }
615}
616
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700617void Heap::DumpGcPerformanceInfo(std::ostream& os) {
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700618 // Dump cumulative timings.
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700619 os << "Dumping cumulative Gc timings\n";
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700620 uint64_t total_duration = 0;
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800621
622 // Dump cumulative loggers for each GC type.
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800623 uint64_t total_paused_time = 0;
Mathieu Chartier590fee92013-09-13 13:46:47 -0700624 for (const auto& collector : garbage_collectors_) {
Sameer Abu Asala8439542013-02-14 16:06:42 -0800625 CumulativeLogger& logger = collector->GetCumulativeTimings();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800626 if (logger.GetTotalNs() != 0) {
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700627 os << Dumpable<CumulativeLogger>(logger);
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800628 const uint64_t total_ns = logger.GetTotalNs();
Mathieu Chartier02e25112013-08-14 16:14:24 -0700629 const uint64_t total_pause_ns = collector->GetTotalPausedTimeNs();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800630 double seconds = NsToMs(logger.GetTotalNs()) / 1000.0;
631 const uint64_t freed_bytes = collector->GetTotalFreedBytes();
632 const uint64_t freed_objects = collector->GetTotalFreedObjects();
Mathieu Chartierb2f99362013-11-20 17:26:00 -0800633 Histogram<uint64_t>::CumulativeData cumulative_data;
634 collector->GetPauseHistogram().CreateHistogram(&cumulative_data);
635 collector->GetPauseHistogram().PrintConfidenceIntervals(os, 0.99, cumulative_data);
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700636 os << collector->GetName() << " total time: " << PrettyDuration(total_ns) << "\n"
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700637 << collector->GetName() << " freed: " << freed_objects
638 << " objects with total size " << PrettySize(freed_bytes) << "\n"
639 << collector->GetName() << " throughput: " << freed_objects / seconds << "/s / "
640 << PrettySize(freed_bytes / seconds) << "/s\n";
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800641 total_duration += total_ns;
642 total_paused_time += total_pause_ns;
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700643 }
644 }
645 uint64_t allocation_time = static_cast<uint64_t>(total_allocation_time_) * kTimeAdjust;
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700646 if (total_duration != 0) {
Brian Carlstrom2d888622013-07-18 17:02:00 -0700647 const double total_seconds = static_cast<double>(total_duration / 1000) / 1000000.0;
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700648 os << "Total time spent in GC: " << PrettyDuration(total_duration) << "\n";
649 os << "Mean GC size throughput: "
Ian Rogers1d54e732013-05-02 21:10:01 -0700650 << PrettySize(GetBytesFreedEver() / total_seconds) << "/s\n";
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700651 os << "Mean GC object throughput: "
Ian Rogers1d54e732013-05-02 21:10:01 -0700652 << (GetObjectsFreedEver() / total_seconds) << " objects/s\n";
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700653 }
Mathieu Chartier692fafd2013-11-29 17:24:40 -0800654 size_t total_objects_allocated = GetObjectsAllocatedEver();
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700655 os << "Total number of allocations: " << total_objects_allocated << "\n";
Mathieu Chartier692fafd2013-11-29 17:24:40 -0800656 size_t total_bytes_allocated = GetBytesAllocatedEver();
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700657 os << "Total bytes allocated " << PrettySize(total_bytes_allocated) << "\n";
Hiroshi Yamauchi50b29282013-07-30 13:58:37 -0700658 if (kMeasureAllocationTime) {
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700659 os << "Total time spent allocating: " << PrettyDuration(allocation_time) << "\n";
660 os << "Mean allocation time: " << PrettyDuration(allocation_time / total_objects_allocated)
661 << "\n";
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700662 }
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700663 os << "Total mutator paused time: " << PrettyDuration(total_paused_time) << "\n";
664 os << "Total time waiting for GC to complete: " << PrettyDuration(total_wait_time_) << "\n";
Mathieu Chartier0a9dc052013-07-25 11:01:28 -0700665 os << "Approximate GC data structures memory overhead: " << gc_memory_overhead_;
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700666}
667
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800668Heap::~Heap() {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700669 VLOG(heap) << "Starting ~Heap()";
Mathieu Chartier590fee92013-09-13 13:46:47 -0700670 STLDeleteElements(&garbage_collectors_);
671 // If we don't reset then the mark stack complains in its destructor.
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700672 allocation_stack_->Reset();
673 live_stack_->Reset();
Mathieu Chartier11409ae2013-09-23 11:49:36 -0700674 STLDeleteValues(&mod_union_tables_);
Ian Rogers1d54e732013-05-02 21:10:01 -0700675 STLDeleteElements(&continuous_spaces_);
676 STLDeleteElements(&discontinuous_spaces_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700677 delete gc_complete_lock_;
Mathieu Chartier590fee92013-09-13 13:46:47 -0700678 VLOG(heap) << "Finished ~Heap()";
Carl Shapiro69759ea2011-07-21 18:13:35 -0700679}
680
Ian Rogers1d54e732013-05-02 21:10:01 -0700681space::ContinuousSpace* Heap::FindContinuousSpaceFromObject(const mirror::Object* obj,
682 bool fail_ok) const {
Mathieu Chartier02e25112013-08-14 16:14:24 -0700683 for (const auto& space : continuous_spaces_) {
684 if (space->Contains(obj)) {
685 return space;
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700686 }
687 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700688 if (!fail_ok) {
689 LOG(FATAL) << "object " << reinterpret_cast<const void*>(obj) << " not inside any spaces!";
690 }
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700691 return NULL;
692}
693
Ian Rogers1d54e732013-05-02 21:10:01 -0700694space::DiscontinuousSpace* Heap::FindDiscontinuousSpaceFromObject(const mirror::Object* obj,
695 bool fail_ok) const {
Mathieu Chartier02e25112013-08-14 16:14:24 -0700696 for (const auto& space : discontinuous_spaces_) {
697 if (space->Contains(obj)) {
698 return space;
Ian Rogers1d54e732013-05-02 21:10:01 -0700699 }
700 }
701 if (!fail_ok) {
702 LOG(FATAL) << "object " << reinterpret_cast<const void*>(obj) << " not inside any spaces!";
703 }
704 return NULL;
705}
706
707space::Space* Heap::FindSpaceFromObject(const mirror::Object* obj, bool fail_ok) const {
708 space::Space* result = FindContinuousSpaceFromObject(obj, true);
709 if (result != NULL) {
710 return result;
711 }
712 return FindDiscontinuousSpaceFromObject(obj, true);
713}
714
Mathieu Chartier39e32612013-11-12 16:28:05 -0800715struct SoftReferenceArgs {
Mathieu Chartier83c8ee02014-01-28 14:50:23 -0800716 IsMarkedCallback* is_marked_callback_;
Mathieu Chartier3bb57c72014-02-18 11:38:45 -0800717 MarkObjectCallback* mark_callback_;
Mathieu Chartier39e32612013-11-12 16:28:05 -0800718 void* arg_;
719};
720
721mirror::Object* Heap::PreserveSoftReferenceCallback(mirror::Object* obj, void* arg) {
Mathieu Chartiera1602f22014-01-13 17:19:19 -0800722 SoftReferenceArgs* args = reinterpret_cast<SoftReferenceArgs*>(arg);
Mathieu Chartier39e32612013-11-12 16:28:05 -0800723 // TODO: Not preserve all soft references.
Mathieu Chartier3bb57c72014-02-18 11:38:45 -0800724 return args->mark_callback_(obj, args->arg_);
Mathieu Chartier39e32612013-11-12 16:28:05 -0800725}
726
727// Process reference class instances and schedule finalizations.
728void Heap::ProcessReferences(TimingLogger& timings, bool clear_soft,
Mathieu Chartier83c8ee02014-01-28 14:50:23 -0800729 IsMarkedCallback* is_marked_callback,
Mathieu Chartier3bb57c72014-02-18 11:38:45 -0800730 MarkObjectCallback* mark_object_callback,
731 ProcessMarkStackCallback* process_mark_stack_callback, void* arg) {
Mathieu Chartier39e32612013-11-12 16:28:05 -0800732 // Unless we are in the zygote or required to clear soft references with white references,
733 // preserve some white referents.
734 if (!clear_soft && !Runtime::Current()->IsZygote()) {
735 SoftReferenceArgs soft_reference_args;
736 soft_reference_args.is_marked_callback_ = is_marked_callback;
Mathieu Chartier3bb57c72014-02-18 11:38:45 -0800737 soft_reference_args.mark_callback_ = mark_object_callback;
Mathieu Chartier39e32612013-11-12 16:28:05 -0800738 soft_reference_args.arg_ = arg;
739 soft_reference_queue_.PreserveSomeSoftReferences(&PreserveSoftReferenceCallback,
740 &soft_reference_args);
Mathieu Chartier3bb57c72014-02-18 11:38:45 -0800741 process_mark_stack_callback(arg);
Mathieu Chartier39e32612013-11-12 16:28:05 -0800742 }
Mathieu Chartier3bb57c72014-02-18 11:38:45 -0800743 timings.StartSplit("(Paused)ProcessReferences");
Mathieu Chartier39e32612013-11-12 16:28:05 -0800744 // Clear all remaining soft and weak references with white referents.
745 soft_reference_queue_.ClearWhiteReferences(cleared_references_, is_marked_callback, arg);
746 weak_reference_queue_.ClearWhiteReferences(cleared_references_, is_marked_callback, arg);
747 timings.EndSplit();
748 // Preserve all white objects with finalize methods and schedule them for finalization.
Mathieu Chartier3bb57c72014-02-18 11:38:45 -0800749 timings.StartSplit("(Paused)EnqueueFinalizerReferences");
Mathieu Chartier39e32612013-11-12 16:28:05 -0800750 finalizer_reference_queue_.EnqueueFinalizerReferences(cleared_references_, is_marked_callback,
Mathieu Chartier3bb57c72014-02-18 11:38:45 -0800751 mark_object_callback, arg);
752 process_mark_stack_callback(arg);
Mathieu Chartier39e32612013-11-12 16:28:05 -0800753 timings.EndSplit();
Mathieu Chartier3bb57c72014-02-18 11:38:45 -0800754 timings.StartSplit("(Paused)ProcessReferences");
Mathieu Chartier39e32612013-11-12 16:28:05 -0800755 // Clear all f-reachable soft and weak references with white referents.
756 soft_reference_queue_.ClearWhiteReferences(cleared_references_, is_marked_callback, arg);
757 weak_reference_queue_.ClearWhiteReferences(cleared_references_, is_marked_callback, arg);
758 // Clear all phantom references with white referents.
759 phantom_reference_queue_.ClearWhiteReferences(cleared_references_, is_marked_callback, arg);
760 // At this point all reference queues other than the cleared references should be empty.
761 DCHECK(soft_reference_queue_.IsEmpty());
762 DCHECK(weak_reference_queue_.IsEmpty());
763 DCHECK(finalizer_reference_queue_.IsEmpty());
764 DCHECK(phantom_reference_queue_.IsEmpty());
765 timings.EndSplit();
766}
767
768bool Heap::IsEnqueued(mirror::Object* ref) const {
769 // Since the references are stored as cyclic lists it means that once enqueued, the pending next
770 // will always be non-null.
Ian Rogersef7d42f2014-01-06 12:55:46 -0800771 return ref->GetFieldObject<mirror::Object>(GetReferencePendingNextOffset(), false) != nullptr;
Mathieu Chartier39e32612013-11-12 16:28:05 -0800772}
773
Ian Rogersef7d42f2014-01-06 12:55:46 -0800774bool Heap::IsEnqueuable(mirror::Object* ref) const {
Mathieu Chartier39e32612013-11-12 16:28:05 -0800775 DCHECK(ref != nullptr);
776 const mirror::Object* queue =
Ian Rogersef7d42f2014-01-06 12:55:46 -0800777 ref->GetFieldObject<mirror::Object>(GetReferenceQueueOffset(), false);
Mathieu Chartier39e32612013-11-12 16:28:05 -0800778 const mirror::Object* queue_next =
Ian Rogersef7d42f2014-01-06 12:55:46 -0800779 ref->GetFieldObject<mirror::Object>(GetReferenceQueueNextOffset(), false);
Mathieu Chartier39e32612013-11-12 16:28:05 -0800780 return queue != nullptr && queue_next == nullptr;
781}
782
783// Process the "referent" field in a java.lang.ref.Reference. If the referent has not yet been
784// marked, put it on the appropriate list in the heap for later processing.
785void Heap::DelayReferenceReferent(mirror::Class* klass, mirror::Object* obj,
Mathieu Chartier83c8ee02014-01-28 14:50:23 -0800786 IsMarkedCallback is_marked_callback, void* arg) {
Mathieu Chartier39e32612013-11-12 16:28:05 -0800787 DCHECK(klass != nullptr);
788 DCHECK(klass->IsReferenceClass());
789 DCHECK(obj != nullptr);
790 mirror::Object* referent = GetReferenceReferent(obj);
791 if (referent != nullptr) {
Mathieu Chartier83c8ee02014-01-28 14:50:23 -0800792 mirror::Object* forward_address = is_marked_callback(referent, arg);
Mathieu Chartier39e32612013-11-12 16:28:05 -0800793 // Null means that the object is not currently marked.
794 if (forward_address == nullptr) {
795 Thread* self = Thread::Current();
796 // TODO: Remove these locks, and use atomic stacks for storing references?
797 // We need to check that the references haven't already been enqueued since we can end up
798 // scanning the same reference multiple times due to dirty cards.
799 if (klass->IsSoftReferenceClass()) {
800 soft_reference_queue_.AtomicEnqueueIfNotEnqueued(self, obj);
801 } else if (klass->IsWeakReferenceClass()) {
802 weak_reference_queue_.AtomicEnqueueIfNotEnqueued(self, obj);
803 } else if (klass->IsFinalizerReferenceClass()) {
804 finalizer_reference_queue_.AtomicEnqueueIfNotEnqueued(self, obj);
805 } else if (klass->IsPhantomReferenceClass()) {
806 phantom_reference_queue_.AtomicEnqueueIfNotEnqueued(self, obj);
807 } else {
808 LOG(FATAL) << "Invalid reference type " << PrettyClass(klass) << " " << std::hex
809 << klass->GetAccessFlags();
810 }
811 } else if (referent != forward_address) {
812 // Referent is already marked and we need to update it.
813 SetReferenceReferent(obj, forward_address);
814 }
815 }
816}
817
Ian Rogers1d54e732013-05-02 21:10:01 -0700818space::ImageSpace* Heap::GetImageSpace() const {
Mathieu Chartier02e25112013-08-14 16:14:24 -0700819 for (const auto& space : continuous_spaces_) {
820 if (space->IsImageSpace()) {
821 return space->AsImageSpace();
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700822 }
823 }
824 return NULL;
825}
826
Elliott Hughes8a8b9cb2012-04-13 18:29:22 -0700827static void MSpaceChunkCallback(void* start, void* end, size_t used_bytes, void* arg) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700828 size_t chunk_size = reinterpret_cast<uint8_t*>(end) - reinterpret_cast<uint8_t*>(start);
Elliott Hughes8a8b9cb2012-04-13 18:29:22 -0700829 if (used_bytes < chunk_size) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700830 size_t chunk_free_bytes = chunk_size - used_bytes;
831 size_t& max_contiguous_allocation = *reinterpret_cast<size_t*>(arg);
832 max_contiguous_allocation = std::max(max_contiguous_allocation, chunk_free_bytes);
Elliott Hughes8a8b9cb2012-04-13 18:29:22 -0700833 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700834}
835
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -0700836void Heap::ThrowOutOfMemoryError(Thread* self, size_t byte_count, bool large_object_allocation) {
837 std::ostringstream oss;
Ian Rogersef7d42f2014-01-06 12:55:46 -0800838 size_t total_bytes_free = GetFreeMemory();
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -0700839 oss << "Failed to allocate a " << byte_count << " byte allocation with " << total_bytes_free
840 << " free bytes";
841 // If the allocation failed due to fragmentation, print out the largest continuous allocation.
842 if (!large_object_allocation && total_bytes_free >= byte_count) {
843 size_t max_contiguous_allocation = 0;
844 for (const auto& space : continuous_spaces_) {
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -0700845 if (space->IsMallocSpace()) {
846 // To allow the Walk/InspectAll() to exclusively-lock the mutator
847 // lock, temporarily release the shared access to the mutator
848 // lock here by transitioning to the suspended state.
849 Locks::mutator_lock_->AssertSharedHeld(self);
850 self->TransitionFromRunnableToSuspended(kSuspended);
851 space->AsMallocSpace()->Walk(MSpaceChunkCallback, &max_contiguous_allocation);
852 self->TransitionFromSuspendedToRunnable();
853 Locks::mutator_lock_->AssertSharedHeld(self);
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -0700854 }
855 }
856 oss << "; failed due to fragmentation (largest possible contiguous allocation "
857 << max_contiguous_allocation << " bytes)";
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700858 }
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -0700859 self->ThrowOutOfMemoryError(oss.str().c_str());
860}
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700861
Mathieu Chartiera5f9de02014-02-28 16:48:42 -0800862void Heap::DoPendingTransitionOrTrim() {
863 Thread* self = Thread::Current();
864 CollectorType desired_collector_type;
865 // Wait until we reach the desired transition time.
866 while (true) {
867 uint64_t wait_time;
868 {
869 MutexLock mu(self, *heap_trim_request_lock_);
870 desired_collector_type = desired_collector_type_;
871 uint64_t current_time = NanoTime();
872 if (current_time >= heap_transition_target_time_) {
873 break;
874 }
875 wait_time = heap_transition_target_time_ - current_time;
876 }
877 ScopedThreadStateChange tsc(self, kSleeping);
878 usleep(wait_time / 1000); // Usleep takes microseconds.
879 }
880 // Transition the heap if the desired collector type is nto the same as the current collector type.
881 TransitionCollector(desired_collector_type);
882 // Do a heap trim if it is needed.
883 Trim();
884}
885
Mathieu Chartier590fee92013-09-13 13:46:47 -0700886void Heap::Trim() {
Mathieu Chartierd5a89ee2014-01-31 09:55:13 -0800887 Thread* self = Thread::Current();
888 {
Mathieu Chartiera5f9de02014-02-28 16:48:42 -0800889 MutexLock mu(self, *heap_trim_request_lock_);
890 if (!heap_trim_request_pending_ || NanoTime() < heap_trim_target_time_) {
891 return;
892 }
893 heap_trim_request_pending_ = false;
894 }
895 {
Mathieu Chartiercaa82d62014-02-02 16:51:17 -0800896 // Need to do this before acquiring the locks since we don't want to get suspended while
897 // holding any locks.
898 ScopedThreadStateChange tsc(self, kWaitingForGcToComplete);
Mathieu Chartierd5a89ee2014-01-31 09:55:13 -0800899 // Pretend we are doing a GC to prevent background compaction from deleting the space we are
900 // trimming.
901 MutexLock mu(self, *gc_complete_lock_);
902 // Ensure there is only one GC at a time.
903 WaitForGcToCompleteLocked(self);
904 collector_type_running_ = kCollectorTypeHeapTrim;
905 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700906 uint64_t start_ns = NanoTime();
907 // Trim the managed spaces.
908 uint64_t total_alloc_space_allocated = 0;
909 uint64_t total_alloc_space_size = 0;
910 uint64_t managed_reclaimed = 0;
911 for (const auto& space : continuous_spaces_) {
Mathieu Chartiera1602f22014-01-13 17:19:19 -0800912 if (space->IsMallocSpace()) {
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -0700913 gc::space::MallocSpace* alloc_space = space->AsMallocSpace();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700914 total_alloc_space_size += alloc_space->Size();
915 managed_reclaimed += alloc_space->Trim();
916 }
917 }
918 total_alloc_space_allocated = GetBytesAllocated() - large_object_space_->GetBytesAllocated() -
Mathieu Chartier692fafd2013-11-29 17:24:40 -0800919 bump_pointer_space_->Size();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700920 const float managed_utilization = static_cast<float>(total_alloc_space_allocated) /
921 static_cast<float>(total_alloc_space_size);
922 uint64_t gc_heap_end_ns = NanoTime();
Mathieu Chartierd5a89ee2014-01-31 09:55:13 -0800923 // We never move things in the native heap, so we can finish the GC at this point.
924 FinishGC(self, collector::kGcTypeNone);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700925 // Trim the native heap.
926 dlmalloc_trim(0);
927 size_t native_reclaimed = 0;
928 dlmalloc_inspect_all(DlmallocMadviseCallback, &native_reclaimed);
929 uint64_t end_ns = NanoTime();
930 VLOG(heap) << "Heap trim of managed (duration=" << PrettyDuration(gc_heap_end_ns - start_ns)
931 << ", advised=" << PrettySize(managed_reclaimed) << ") and native (duration="
932 << PrettyDuration(end_ns - gc_heap_end_ns) << ", advised=" << PrettySize(native_reclaimed)
933 << ") heaps. Managed heap utilization of " << static_cast<int>(100 * managed_utilization)
934 << "%.";
935}
936
937bool Heap::IsValidObjectAddress(const mirror::Object* obj) const {
938 // Note: we deliberately don't take the lock here, and mustn't test anything that would require
939 // taking the lock.
940 if (obj == nullptr) {
Elliott Hughes88c5c352012-03-15 18:49:48 -0700941 return true;
942 }
Mathieu Chartier15d34022014-02-26 17:16:38 -0800943 return IsAligned<kObjectAlignment>(obj) && FindSpaceFromObject(obj, true) != nullptr;
Mathieu Chartier590fee92013-09-13 13:46:47 -0700944}
945
Mathieu Chartierd68ac702014-02-11 14:50:51 -0800946bool Heap::IsNonDiscontinuousSpaceHeapAddress(const mirror::Object* obj) const {
947 return FindContinuousSpaceFromObject(obj, true) != nullptr;
948}
949
Mathieu Chartier15d34022014-02-26 17:16:38 -0800950bool Heap::IsValidContinuousSpaceObjectAddress(const mirror::Object* obj) const {
951 if (obj == nullptr || !IsAligned<kObjectAlignment>(obj)) {
952 return false;
953 }
954 for (const auto& space : continuous_spaces_) {
955 if (space->HasAddress(obj)) {
956 return true;
957 }
958 }
959 return false;
Elliott Hughesa2501992011-08-26 19:39:54 -0700960}
961
Ian Rogersef7d42f2014-01-06 12:55:46 -0800962bool Heap::IsLiveObjectLocked(mirror::Object* obj, bool search_allocation_stack,
Mathieu Chartier0f72e412013-09-06 16:40:01 -0700963 bool search_live_stack, bool sorted) {
Mathieu Chartier938a03b2014-01-16 15:10:31 -0800964 if (UNLIKELY(!IsAligned<kObjectAlignment>(obj))) {
965 return false;
966 }
967 if (bump_pointer_space_ != nullptr && bump_pointer_space_->HasAddress(obj)) {
Mathieu Chartier4e305412014-02-19 10:54:44 -0800968 mirror::Class* klass = obj->GetClass<kVerifyNone>();
Mathieu Chartier938a03b2014-01-16 15:10:31 -0800969 if (obj == klass) {
Mathieu Chartier9be9a7a2014-01-24 14:07:33 -0800970 // This case happens for java.lang.Class.
Mathieu Chartier938a03b2014-01-16 15:10:31 -0800971 return true;
972 }
973 return VerifyClassClass(klass) && IsLiveObjectLocked(klass);
974 } else if (temp_space_ != nullptr && temp_space_->HasAddress(obj)) {
Mathieu Chartier4e305412014-02-19 10:54:44 -0800975 // If we are in the allocated region of the temp space, then we are probably live (e.g. during
976 // a GC). When a GC isn't running End() - Begin() is 0 which means no objects are contained.
977 return temp_space_->Contains(obj);
Ian Rogers1d54e732013-05-02 21:10:01 -0700978 }
Mathieu Chartierf082d3c2013-07-29 17:04:07 -0700979 space::ContinuousSpace* c_space = FindContinuousSpaceFromObject(obj, true);
980 space::DiscontinuousSpace* d_space = NULL;
Mathieu Chartier938a03b2014-01-16 15:10:31 -0800981 if (c_space != nullptr) {
Mathieu Chartierf082d3c2013-07-29 17:04:07 -0700982 if (c_space->GetLiveBitmap()->Test(obj)) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700983 return true;
984 }
985 } else {
Mathieu Chartierf082d3c2013-07-29 17:04:07 -0700986 d_space = FindDiscontinuousSpaceFromObject(obj, true);
Mathieu Chartier938a03b2014-01-16 15:10:31 -0800987 if (d_space != nullptr) {
Mathieu Chartierf082d3c2013-07-29 17:04:07 -0700988 if (d_space->GetLiveObjects()->Test(obj)) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700989 return true;
990 }
991 }
992 }
Mathieu Chartierf082d3c2013-07-29 17:04:07 -0700993 // This is covering the allocation/live stack swapping that is done without mutators suspended.
Mathieu Chartier0f72e412013-09-06 16:40:01 -0700994 for (size_t i = 0; i < (sorted ? 1 : 5); ++i) {
995 if (i > 0) {
996 NanoSleep(MsToNs(10));
Ian Rogers1d54e732013-05-02 21:10:01 -0700997 }
Mathieu Chartier0f72e412013-09-06 16:40:01 -0700998 if (search_allocation_stack) {
999 if (sorted) {
1000 if (allocation_stack_->ContainsSorted(const_cast<mirror::Object*>(obj))) {
1001 return true;
1002 }
1003 } else if (allocation_stack_->Contains(const_cast<mirror::Object*>(obj))) {
1004 return true;
1005 }
1006 }
1007
1008 if (search_live_stack) {
1009 if (sorted) {
1010 if (live_stack_->ContainsSorted(const_cast<mirror::Object*>(obj))) {
1011 return true;
1012 }
1013 } else if (live_stack_->Contains(const_cast<mirror::Object*>(obj))) {
1014 return true;
1015 }
1016 }
Ian Rogers1d54e732013-05-02 21:10:01 -07001017 }
Mathieu Chartierf082d3c2013-07-29 17:04:07 -07001018 // We need to check the bitmaps again since there is a race where we mark something as live and
1019 // then clear the stack containing it.
Mathieu Chartier938a03b2014-01-16 15:10:31 -08001020 if (c_space != nullptr) {
Mathieu Chartierf082d3c2013-07-29 17:04:07 -07001021 if (c_space->GetLiveBitmap()->Test(obj)) {
1022 return true;
1023 }
1024 } else {
1025 d_space = FindDiscontinuousSpaceFromObject(obj, true);
Mathieu Chartier938a03b2014-01-16 15:10:31 -08001026 if (d_space != nullptr && d_space->GetLiveObjects()->Test(obj)) {
Mathieu Chartierf082d3c2013-07-29 17:04:07 -07001027 return true;
1028 }
1029 }
Ian Rogers1d54e732013-05-02 21:10:01 -07001030 return false;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001031}
1032
Mathieu Chartier590fee92013-09-13 13:46:47 -07001033void Heap::DumpSpaces(std::ostream& stream) {
Mathieu Chartier02e25112013-08-14 16:14:24 -07001034 for (const auto& space : continuous_spaces_) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001035 accounting::SpaceBitmap* live_bitmap = space->GetLiveBitmap();
1036 accounting::SpaceBitmap* mark_bitmap = space->GetMarkBitmap();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001037 stream << space << " " << *space << "\n";
1038 if (live_bitmap != nullptr) {
1039 stream << live_bitmap << " " << *live_bitmap << "\n";
1040 }
1041 if (mark_bitmap != nullptr) {
1042 stream << mark_bitmap << " " << *mark_bitmap << "\n";
1043 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001044 }
Mathieu Chartier02e25112013-08-14 16:14:24 -07001045 for (const auto& space : discontinuous_spaces_) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001046 stream << space << " " << *space << "\n";
Mathieu Chartier128c52c2012-10-16 14:12:41 -07001047 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001048}
1049
Ian Rogersef7d42f2014-01-06 12:55:46 -08001050void Heap::VerifyObjectBody(mirror::Object* obj) {
Mathieu Chartier4e305412014-02-19 10:54:44 -08001051 if (this == nullptr && verify_object_mode_ == kVerifyObjectModeDisabled) {
1052 return;
1053 }
Mathieu Chartier0f72e412013-09-06 16:40:01 -07001054 // Ignore early dawn of the universe verifications.
Ian Rogersb122a4b2013-11-19 18:00:50 -08001055 if (UNLIKELY(static_cast<size_t>(num_bytes_allocated_.Load()) < 10 * KB)) {
Ian Rogers62d6c772013-02-27 08:32:07 -08001056 return;
1057 }
Mathieu Chartier4e305412014-02-19 10:54:44 -08001058 CHECK(IsAligned<kObjectAlignment>(obj)) << "Object isn't aligned: " << obj;
1059 mirror::Class* c = obj->GetFieldObject<mirror::Class, kVerifyNone>(
1060 mirror::Object::ClassOffset(), false);
1061 CHECK(c != nullptr) << "Null class in object " << obj;
1062 CHECK(IsAligned<kObjectAlignment>(c)) << "Class " << c << " not aligned in object " << obj;
Mathieu Chartier938a03b2014-01-16 15:10:31 -08001063 CHECK(VerifyClassClass(c));
Mathieu Chartier0325e622012-09-05 14:22:51 -07001064
Mathieu Chartier4e305412014-02-19 10:54:44 -08001065 if (verify_object_mode_ > kVerifyObjectModeFast) {
1066 // Note: the bitmap tests below are racy since we don't hold the heap bitmap lock.
Ian Rogers1d54e732013-05-02 21:10:01 -07001067 if (!IsLiveObjectLocked(obj)) {
1068 DumpSpaces();
1069 LOG(FATAL) << "Object is dead: " << obj;
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001070 }
Mathieu Chartierdcf8d722012-08-02 14:55:54 -07001071 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001072}
1073
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001074void Heap::VerificationCallback(mirror::Object* obj, void* arg) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001075 reinterpret_cast<Heap*>(arg)->VerifyObjectBody(obj);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001076}
1077
1078void Heap::VerifyHeap() {
Ian Rogers50b35e22012-10-04 10:09:15 -07001079 ReaderMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07001080 GetLiveBitmap()->Walk(Heap::VerificationCallback, this);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001081}
1082
Ian Rogersef7d42f2014-01-06 12:55:46 -08001083void Heap::RecordFree(size_t freed_objects, size_t freed_bytes) {
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001084 DCHECK_LE(freed_bytes, num_bytes_allocated_.Load());
Ian Rogersb122a4b2013-11-19 18:00:50 -08001085 num_bytes_allocated_.FetchAndSub(freed_bytes);
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07001086 if (Runtime::Current()->HasStatsEnabled()) {
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07001087 RuntimeStats* thread_stats = Thread::Current()->GetStats();
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001088 thread_stats->freed_objects += freed_objects;
Elliott Hughes307f75d2011-10-12 18:04:40 -07001089 thread_stats->freed_bytes += freed_bytes;
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001090 // TODO: Do this concurrently.
1091 RuntimeStats* global_stats = Runtime::Current()->GetStats();
1092 global_stats->freed_objects += freed_objects;
1093 global_stats->freed_bytes += freed_bytes;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07001094 }
Carl Shapiro58551df2011-07-24 03:09:51 -07001095}
1096
Mathieu Chartiercbb2d202013-11-14 17:45:16 -08001097mirror::Object* Heap::AllocateInternalWithGc(Thread* self, AllocatorType allocator,
Mathieu Chartierc528dba2013-11-26 12:00:11 -08001098 size_t alloc_size, size_t* bytes_allocated,
Ian Rogers6fac4472014-02-25 17:01:10 -08001099 size_t* usable_size,
Mathieu Chartierc528dba2013-11-26 12:00:11 -08001100 mirror::Class** klass) {
Mathieu Chartiercbb2d202013-11-14 17:45:16 -08001101 mirror::Object* ptr = nullptr;
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001102 bool was_default_allocator = allocator == GetCurrentAllocator();
Mathieu Chartierc528dba2013-11-26 12:00:11 -08001103 DCHECK(klass != nullptr);
1104 SirtRef<mirror::Class> sirt_klass(self, *klass);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001105 // The allocation failed. If the GC is running, block until it completes, and then retry the
1106 // allocation.
Mathieu Chartier590fee92013-09-13 13:46:47 -07001107 collector::GcType last_gc = WaitForGcToComplete(self);
Ian Rogers1d54e732013-05-02 21:10:01 -07001108 if (last_gc != collector::kGcTypeNone) {
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001109 // If we were the default allocator but the allocator changed while we were suspended,
1110 // abort the allocation.
1111 if (was_default_allocator && allocator != GetCurrentAllocator()) {
1112 *klass = sirt_klass.get();
1113 return nullptr;
1114 }
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001115 // A GC was in progress and we blocked, retry allocation now that memory has been freed.
Ian Rogers6fac4472014-02-25 17:01:10 -08001116 ptr = TryToAllocate<true, false>(self, allocator, alloc_size, bytes_allocated, usable_size);
Carl Shapiro69759ea2011-07-21 18:13:35 -07001117 }
1118
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001119 // Loop through our different Gc types and try to Gc until we get enough free memory.
Mathieu Chartiercbb2d202013-11-14 17:45:16 -08001120 for (collector::GcType gc_type : gc_plan_) {
1121 if (ptr != nullptr) {
1122 break;
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001123 }
Mathieu Chartiercbb2d202013-11-14 17:45:16 -08001124 // Attempt to run the collector, if we succeed, re-try the allocation.
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001125 bool gc_ran =
1126 CollectGarbageInternal(gc_type, kGcCauseForAlloc, false) != collector::kGcTypeNone;
1127 if (was_default_allocator && allocator != GetCurrentAllocator()) {
1128 *klass = sirt_klass.get();
1129 return nullptr;
1130 }
1131 if (gc_ran) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001132 // Did we free sufficient memory for the allocation to succeed?
Ian Rogers6fac4472014-02-25 17:01:10 -08001133 ptr = TryToAllocate<true, false>(self, allocator, alloc_size, bytes_allocated, usable_size);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001134 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001135 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001136 // Allocations have failed after GCs; this is an exceptional state.
Mathieu Chartiercbb2d202013-11-14 17:45:16 -08001137 if (ptr == nullptr) {
1138 // Try harder, growing the heap if necessary.
Ian Rogers6fac4472014-02-25 17:01:10 -08001139 ptr = TryToAllocate<true, true>(self, allocator, alloc_size, bytes_allocated, usable_size);
Carl Shapiro69759ea2011-07-21 18:13:35 -07001140 }
Mathieu Chartiercbb2d202013-11-14 17:45:16 -08001141 if (ptr == nullptr) {
1142 // Most allocations should have succeeded by now, so the heap is really full, really fragmented,
1143 // or the requested size is really big. Do another GC, collecting SoftReferences this time. The
1144 // VM spec requires that all SoftReferences have been collected and cleared before throwing
1145 // OOME.
1146 VLOG(gc) << "Forcing collection of SoftReferences for " << PrettySize(alloc_size)
1147 << " allocation";
1148 // TODO: Run finalization, but this may cause more allocations to occur.
1149 // We don't need a WaitForGcToComplete here either.
1150 DCHECK(!gc_plan_.empty());
1151 CollectGarbageInternal(gc_plan_.back(), kGcCauseForAlloc, true);
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001152 if (was_default_allocator && allocator != GetCurrentAllocator()) {
1153 *klass = sirt_klass.get();
1154 return nullptr;
1155 }
Ian Rogers6fac4472014-02-25 17:01:10 -08001156 ptr = TryToAllocate<true, true>(self, allocator, alloc_size, bytes_allocated, usable_size);
Mathieu Chartiercbb2d202013-11-14 17:45:16 -08001157 if (ptr == nullptr) {
1158 ThrowOutOfMemoryError(self, alloc_size, false);
1159 }
1160 }
Mathieu Chartierc528dba2013-11-26 12:00:11 -08001161 *klass = sirt_klass.get();
Mathieu Chartiercbb2d202013-11-14 17:45:16 -08001162 return ptr;
Carl Shapiro69759ea2011-07-21 18:13:35 -07001163}
1164
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001165void Heap::SetTargetHeapUtilization(float target) {
1166 DCHECK_GT(target, 0.0f); // asserted in Java code
1167 DCHECK_LT(target, 1.0f);
1168 target_utilization_ = target;
1169}
1170
Ian Rogers1d54e732013-05-02 21:10:01 -07001171size_t Heap::GetObjectsAllocated() const {
1172 size_t total = 0;
Mathieu Chartier590fee92013-09-13 13:46:47 -07001173 for (space::AllocSpace* space : alloc_spaces_) {
1174 total += space->GetObjectsAllocated();
Ian Rogers1d54e732013-05-02 21:10:01 -07001175 }
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001176 return total;
1177}
1178
Ian Rogers1d54e732013-05-02 21:10:01 -07001179size_t Heap::GetObjectsAllocatedEver() const {
Mathieu Chartier692fafd2013-11-29 17:24:40 -08001180 return GetObjectsFreedEver() + GetObjectsAllocated();
Ian Rogers1d54e732013-05-02 21:10:01 -07001181}
1182
1183size_t Heap::GetBytesAllocatedEver() const {
Mathieu Chartier692fafd2013-11-29 17:24:40 -08001184 return GetBytesFreedEver() + GetBytesAllocated();
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001185}
1186
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07001187class InstanceCounter {
1188 public:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001189 InstanceCounter(const std::vector<mirror::Class*>& classes, bool use_is_assignable_from, uint64_t* counts)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001190 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Elliott Hughesec0f83d2013-01-15 16:54:08 -08001191 : classes_(classes), use_is_assignable_from_(use_is_assignable_from), counts_(counts) {
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07001192 }
Mathieu Chartier412c7fc2014-02-07 12:18:39 -08001193 static void Callback(mirror::Object* obj, void* arg)
1194 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
1195 InstanceCounter* instance_counter = reinterpret_cast<InstanceCounter*>(arg);
1196 mirror::Class* instance_class = obj->GetClass();
1197 CHECK(instance_class != nullptr);
1198 for (size_t i = 0; i < instance_counter->classes_.size(); ++i) {
1199 if (instance_counter->use_is_assignable_from_) {
1200 if (instance_counter->classes_[i]->IsAssignableFrom(instance_class)) {
1201 ++instance_counter->counts_[i];
Elliott Hughesec0f83d2013-01-15 16:54:08 -08001202 }
Mathieu Chartier412c7fc2014-02-07 12:18:39 -08001203 } else if (instance_class == instance_counter->classes_[i]) {
1204 ++instance_counter->counts_[i];
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07001205 }
1206 }
1207 }
1208
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001209 private:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001210 const std::vector<mirror::Class*>& classes_;
Elliott Hughesec0f83d2013-01-15 16:54:08 -08001211 bool use_is_assignable_from_;
1212 uint64_t* const counts_;
Elliott Hughesec0f83d2013-01-15 16:54:08 -08001213 DISALLOW_COPY_AND_ASSIGN(InstanceCounter);
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07001214};
1215
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001216void Heap::CountInstances(const std::vector<mirror::Class*>& classes, bool use_is_assignable_from,
Elliott Hughesec0f83d2013-01-15 16:54:08 -08001217 uint64_t* counts) {
Mathieu Chartier412c7fc2014-02-07 12:18:39 -08001218 // Can't do any GC in this function since this may move classes.
Elliott Hughesec0f83d2013-01-15 16:54:08 -08001219 Thread* self = Thread::Current();
Mathieu Chartier412c7fc2014-02-07 12:18:39 -08001220 auto* old_cause = self->StartAssertNoThreadSuspension("CountInstances");
Elliott Hughesec0f83d2013-01-15 16:54:08 -08001221 InstanceCounter counter(classes, use_is_assignable_from, counts);
Mathieu Chartier412c7fc2014-02-07 12:18:39 -08001222 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
1223 VisitObjects(InstanceCounter::Callback, &counter);
1224 self->EndAssertNoThreadSuspension(old_cause);
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07001225}
1226
Elliott Hughes3b78c942013-01-15 17:35:41 -08001227class InstanceCollector {
1228 public:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001229 InstanceCollector(mirror::Class* c, int32_t max_count, std::vector<mirror::Object*>& instances)
Elliott Hughes3b78c942013-01-15 17:35:41 -08001230 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
1231 : class_(c), max_count_(max_count), instances_(instances) {
1232 }
Mathieu Chartier412c7fc2014-02-07 12:18:39 -08001233 static void Callback(mirror::Object* obj, void* arg)
1234 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
1235 DCHECK(arg != nullptr);
1236 InstanceCollector* instance_collector = reinterpret_cast<InstanceCollector*>(arg);
1237 mirror::Class* instance_class = obj->GetClass();
1238 if (instance_class == instance_collector->class_) {
1239 if (instance_collector->max_count_ == 0 ||
1240 instance_collector->instances_.size() < instance_collector->max_count_) {
1241 instance_collector->instances_.push_back(obj);
Elliott Hughes3b78c942013-01-15 17:35:41 -08001242 }
1243 }
1244 }
1245
1246 private:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001247 mirror::Class* class_;
Elliott Hughes3b78c942013-01-15 17:35:41 -08001248 uint32_t max_count_;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001249 std::vector<mirror::Object*>& instances_;
Elliott Hughes3b78c942013-01-15 17:35:41 -08001250 DISALLOW_COPY_AND_ASSIGN(InstanceCollector);
1251};
1252
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001253void Heap::GetInstances(mirror::Class* c, int32_t max_count,
1254 std::vector<mirror::Object*>& instances) {
Mathieu Chartier412c7fc2014-02-07 12:18:39 -08001255 // Can't do any GC in this function since this may move classes.
Elliott Hughes3b78c942013-01-15 17:35:41 -08001256 Thread* self = Thread::Current();
Mathieu Chartier412c7fc2014-02-07 12:18:39 -08001257 auto* old_cause = self->StartAssertNoThreadSuspension("GetInstances");
Elliott Hughes3b78c942013-01-15 17:35:41 -08001258 InstanceCollector collector(c, max_count, instances);
Mathieu Chartier412c7fc2014-02-07 12:18:39 -08001259 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
1260 VisitObjects(&InstanceCollector::Callback, &collector);
1261 self->EndAssertNoThreadSuspension(old_cause);
Elliott Hughes3b78c942013-01-15 17:35:41 -08001262}
1263
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001264class ReferringObjectsFinder {
1265 public:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001266 ReferringObjectsFinder(mirror::Object* object, int32_t max_count,
1267 std::vector<mirror::Object*>& referring_objects)
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001268 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
1269 : object_(object), max_count_(max_count), referring_objects_(referring_objects) {
1270 }
1271
Mathieu Chartier412c7fc2014-02-07 12:18:39 -08001272 static void Callback(mirror::Object* obj, void* arg)
1273 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
1274 reinterpret_cast<ReferringObjectsFinder*>(arg)->operator()(obj);
1275 }
1276
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001277 // For bitmap Visit.
1278 // TODO: Fix lock analysis to not use NO_THREAD_SAFETY_ANALYSIS, requires support for
1279 // annotalysis on visitors.
Mathieu Chartier590fee92013-09-13 13:46:47 -07001280 void operator()(const mirror::Object* o) const NO_THREAD_SAFETY_ANALYSIS {
1281 collector::MarkSweep::VisitObjectReferences(const_cast<mirror::Object*>(o), *this, true);
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001282 }
1283
1284 // For MarkSweep::VisitObjectReferences.
Mathieu Chartier11409ae2013-09-23 11:49:36 -07001285 void operator()(mirror::Object* referrer, mirror::Object* object,
Brian Carlstromdf629502013-07-17 22:39:56 -07001286 const MemberOffset&, bool) const {
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001287 if (object == object_ && (max_count_ == 0 || referring_objects_.size() < max_count_)) {
Mathieu Chartier11409ae2013-09-23 11:49:36 -07001288 referring_objects_.push_back(referrer);
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001289 }
1290 }
1291
1292 private:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001293 mirror::Object* object_;
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001294 uint32_t max_count_;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001295 std::vector<mirror::Object*>& referring_objects_;
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001296 DISALLOW_COPY_AND_ASSIGN(ReferringObjectsFinder);
1297};
1298
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001299void Heap::GetReferringObjects(mirror::Object* o, int32_t max_count,
1300 std::vector<mirror::Object*>& referring_objects) {
Mathieu Chartier83c8ee02014-01-28 14:50:23 -08001301 // Can't do any GC in this function since this may move the object o.
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001302 Thread* self = Thread::Current();
Mathieu Chartier412c7fc2014-02-07 12:18:39 -08001303 auto* old_cause = self->StartAssertNoThreadSuspension("GetReferringObjects");
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001304 ReferringObjectsFinder finder(o, max_count, referring_objects);
Mathieu Chartier412c7fc2014-02-07 12:18:39 -08001305 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
1306 VisitObjects(&ReferringObjectsFinder::Callback, &finder);
1307 self->EndAssertNoThreadSuspension(old_cause);
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001308}
1309
Ian Rogers30fab402012-01-23 15:43:46 -08001310void Heap::CollectGarbage(bool clear_soft_references) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001311 // Even if we waited for a GC we still need to do another GC since weaks allocated during the
1312 // last GC will not have necessarily been cleared.
Mathieu Chartier7bf82af2013-12-06 16:51:45 -08001313 CollectGarbageInternal(gc_plan_.back(), kGcCauseExplicit, clear_soft_references);
Carl Shapiro69759ea2011-07-21 18:13:35 -07001314}
1315
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001316void Heap::TransitionCollector(CollectorType collector_type) {
1317 if (collector_type == collector_type_) {
1318 return;
1319 }
Hiroshi Yamauchia4adbfd2014-02-04 18:12:17 -08001320 VLOG(heap) << "TransitionCollector: " << static_cast<int>(collector_type_)
1321 << " -> " << static_cast<int>(collector_type);
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001322 uint64_t start_time = NanoTime();
Ian Rogersef7d42f2014-01-06 12:55:46 -08001323 uint32_t before_size = GetTotalMemory();
1324 uint32_t before_allocated = num_bytes_allocated_.Load();
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001325 ThreadList* tl = Runtime::Current()->GetThreadList();
1326 Thread* self = Thread::Current();
1327 ScopedThreadStateChange tsc(self, kWaitingPerformingGc);
1328 Locks::mutator_lock_->AssertNotHeld(self);
Mathieu Chartierd5a89ee2014-01-31 09:55:13 -08001329 const bool copying_transition =
1330 IsCompactingGC(background_collector_type_) || IsCompactingGC(post_zygote_collector_type_);
Mathieu Chartier1d27b342014-01-28 12:51:09 -08001331 // Busy wait until we can GC (StartGC can fail if we have a non-zero
1332 // compacting_gc_disable_count_, this should rarely occurs).
Mathieu Chartierd5a89ee2014-01-31 09:55:13 -08001333 for (;;) {
Mathieu Chartiercaa82d62014-02-02 16:51:17 -08001334 {
1335 ScopedThreadStateChange tsc(self, kWaitingForGcToComplete);
1336 MutexLock mu(self, *gc_complete_lock_);
1337 // Ensure there is only one GC at a time.
1338 WaitForGcToCompleteLocked(self);
1339 // GC can be disabled if someone has a used GetPrimitiveArrayCritical but not yet released.
1340 if (!copying_transition || disable_moving_gc_count_ == 0) {
1341 // TODO: Not hard code in semi-space collector?
1342 collector_type_running_ = copying_transition ? kCollectorTypeSS : collector_type;
1343 break;
1344 }
Mathieu Chartierd5a89ee2014-01-31 09:55:13 -08001345 }
Mathieu Chartiercaa82d62014-02-02 16:51:17 -08001346 usleep(1000);
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001347 }
1348 tl->SuspendAll();
Hiroshi Yamauchia4adbfd2014-02-04 18:12:17 -08001349 PreGcRosAllocVerification(&semi_space_collector_->GetTimings());
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001350 switch (collector_type) {
Hiroshi Yamauchi6f4ffe42014-01-13 12:30:44 -08001351 case kCollectorTypeSS:
Mathieu Chartier1d27b342014-01-28 12:51:09 -08001352 // Fall-through.
Hiroshi Yamauchi6f4ffe42014-01-13 12:30:44 -08001353 case kCollectorTypeGSS: {
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001354 mprotect(temp_space_->Begin(), temp_space_->Capacity(), PROT_READ | PROT_WRITE);
Mathieu Chartierfc5b5282014-01-09 16:15:36 -08001355 CHECK(main_space_ != nullptr);
1356 Compact(temp_space_, main_space_);
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001357 DCHECK(allocator_mem_map_.get() == nullptr);
Mathieu Chartierfc5b5282014-01-09 16:15:36 -08001358 allocator_mem_map_.reset(main_space_->ReleaseMemMap());
1359 madvise(main_space_->Begin(), main_space_->Size(), MADV_DONTNEED);
Mathieu Chartiera1602f22014-01-13 17:19:19 -08001360 // RemoveSpace does not delete the removed space.
1361 space::Space* old_space = main_space_;
1362 RemoveSpace(old_space);
1363 delete old_space;
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001364 break;
1365 }
1366 case kCollectorTypeMS:
1367 // Fall through.
1368 case kCollectorTypeCMS: {
Mathieu Chartier1d27b342014-01-28 12:51:09 -08001369 if (IsCompactingGC(collector_type_)) {
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001370 // TODO: Use mem-map from temp space?
1371 MemMap* mem_map = allocator_mem_map_.release();
1372 CHECK(mem_map != nullptr);
1373 size_t initial_size = kDefaultInitialSize;
1374 mprotect(mem_map->Begin(), initial_size, PROT_READ | PROT_WRITE);
Mathieu Chartierfc5b5282014-01-09 16:15:36 -08001375 CHECK(main_space_ == nullptr);
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001376 if (kUseRosAlloc) {
Mathieu Chartierfc5b5282014-01-09 16:15:36 -08001377 main_space_ =
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001378 space::RosAllocSpace::CreateFromMemMap(mem_map, "alloc space", kPageSize,
1379 initial_size, mem_map->Size(),
1380 mem_map->Size(), low_memory_mode_);
1381 } else {
Mathieu Chartierfc5b5282014-01-09 16:15:36 -08001382 main_space_ =
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001383 space::DlMallocSpace::CreateFromMemMap(mem_map, "alloc space", kPageSize,
1384 initial_size, mem_map->Size(),
1385 mem_map->Size());
1386 }
Mathieu Chartierfc5b5282014-01-09 16:15:36 -08001387 main_space_->SetFootprintLimit(main_space_->Capacity());
1388 AddSpace(main_space_);
1389 Compact(main_space_, bump_pointer_space_);
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001390 }
1391 break;
1392 }
1393 default: {
1394 LOG(FATAL) << "Attempted to transition to invalid collector type";
1395 break;
1396 }
1397 }
1398 ChangeCollector(collector_type);
Hiroshi Yamauchia4adbfd2014-02-04 18:12:17 -08001399 PostGcRosAllocVerification(&semi_space_collector_->GetTimings());
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001400 tl->ResumeAll();
1401 // Can't call into java code with all threads suspended.
1402 EnqueueClearedReferences();
1403 uint64_t duration = NanoTime() - start_time;
1404 GrowForUtilization(collector::kGcTypeFull, duration);
1405 FinishGC(self, collector::kGcTypeFull);
1406 int32_t after_size = GetTotalMemory();
1407 int32_t delta_size = before_size - after_size;
1408 int32_t after_allocated = num_bytes_allocated_.Load();
1409 int32_t delta_allocated = before_allocated - after_allocated;
1410 const std::string saved_bytes_str =
1411 delta_size < 0 ? "-" + PrettySize(-delta_size) : PrettySize(delta_size);
1412 LOG(INFO) << "Heap transition to " << process_state_ << " took "
1413 << PrettyDuration(duration) << " " << PrettySize(before_size) << "->"
1414 << PrettySize(after_size) << " from " << PrettySize(delta_allocated) << " to "
1415 << PrettySize(delta_size) << " saved";
1416}
1417
Mathieu Chartier0de9f732013-11-22 17:58:48 -08001418void Heap::ChangeCollector(CollectorType collector_type) {
Mathieu Chartier7bf82af2013-12-06 16:51:45 -08001419 // TODO: Only do this with all mutators suspended to avoid races.
1420 if (collector_type != collector_type_) {
1421 collector_type_ = collector_type;
1422 gc_plan_.clear();
1423 switch (collector_type_) {
Hiroshi Yamauchi6f4ffe42014-01-13 12:30:44 -08001424 case kCollectorTypeSS:
Mathieu Chartier1d27b342014-01-28 12:51:09 -08001425 // Fall-through.
Hiroshi Yamauchi6f4ffe42014-01-13 12:30:44 -08001426 case kCollectorTypeGSS: {
Mathieu Chartier7bf82af2013-12-06 16:51:45 -08001427 concurrent_gc_ = false;
1428 gc_plan_.push_back(collector::kGcTypeFull);
Mathieu Chartier692fafd2013-11-29 17:24:40 -08001429 if (use_tlab_) {
1430 ChangeAllocator(kAllocatorTypeTLAB);
1431 } else {
1432 ChangeAllocator(kAllocatorTypeBumpPointer);
1433 }
Mathieu Chartier7bf82af2013-12-06 16:51:45 -08001434 break;
1435 }
1436 case kCollectorTypeMS: {
1437 concurrent_gc_ = false;
1438 gc_plan_.push_back(collector::kGcTypeSticky);
1439 gc_plan_.push_back(collector::kGcTypePartial);
1440 gc_plan_.push_back(collector::kGcTypeFull);
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001441 ChangeAllocator(kUseRosAlloc ? kAllocatorTypeRosAlloc : kAllocatorTypeDlMalloc);
Mathieu Chartier7bf82af2013-12-06 16:51:45 -08001442 break;
1443 }
1444 case kCollectorTypeCMS: {
1445 concurrent_gc_ = true;
1446 gc_plan_.push_back(collector::kGcTypeSticky);
1447 gc_plan_.push_back(collector::kGcTypePartial);
1448 gc_plan_.push_back(collector::kGcTypeFull);
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001449 ChangeAllocator(kUseRosAlloc ? kAllocatorTypeRosAlloc : kAllocatorTypeDlMalloc);
Mathieu Chartier7bf82af2013-12-06 16:51:45 -08001450 break;
1451 }
1452 default: {
1453 LOG(FATAL) << "Unimplemented";
1454 }
Mathieu Chartier0de9f732013-11-22 17:58:48 -08001455 }
Mathieu Chartier7bf82af2013-12-06 16:51:45 -08001456 if (concurrent_gc_) {
1457 concurrent_start_bytes_ =
1458 std::max(max_allowed_footprint_, kMinConcurrentRemainingBytes) - kMinConcurrentRemainingBytes;
1459 } else {
1460 concurrent_start_bytes_ = std::numeric_limits<size_t>::max();
Mathieu Chartier0de9f732013-11-22 17:58:48 -08001461 }
1462 }
1463}
1464
Mathieu Chartier85a43c02014-01-07 17:59:00 -08001465// Special compacting collector which uses sub-optimal bin packing to reduce zygote space size.
Ian Rogers6fac4472014-02-25 17:01:10 -08001466class ZygoteCompactingCollector FINAL : public collector::SemiSpace {
Mathieu Chartier85a43c02014-01-07 17:59:00 -08001467 public:
Ian Rogers6fac4472014-02-25 17:01:10 -08001468 explicit ZygoteCompactingCollector(gc::Heap* heap) : SemiSpace(heap, "zygote collector"),
1469 bin_live_bitmap_(nullptr), bin_mark_bitmap_(nullptr) {
Mathieu Chartier85a43c02014-01-07 17:59:00 -08001470 }
1471
1472 void BuildBins(space::ContinuousSpace* space) {
1473 bin_live_bitmap_ = space->GetLiveBitmap();
1474 bin_mark_bitmap_ = space->GetMarkBitmap();
1475 BinContext context;
1476 context.prev_ = reinterpret_cast<uintptr_t>(space->Begin());
1477 context.collector_ = this;
1478 WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
1479 // Note: This requires traversing the space in increasing order of object addresses.
1480 bin_live_bitmap_->Walk(Callback, reinterpret_cast<void*>(&context));
1481 // Add the last bin which spans after the last object to the end of the space.
1482 AddBin(reinterpret_cast<uintptr_t>(space->End()) - context.prev_, context.prev_);
1483 }
1484
1485 private:
1486 struct BinContext {
1487 uintptr_t prev_; // The end of the previous object.
1488 ZygoteCompactingCollector* collector_;
1489 };
1490 // Maps from bin sizes to locations.
1491 std::multimap<size_t, uintptr_t> bins_;
1492 // Live bitmap of the space which contains the bins.
1493 accounting::SpaceBitmap* bin_live_bitmap_;
1494 // Mark bitmap of the space which contains the bins.
1495 accounting::SpaceBitmap* bin_mark_bitmap_;
1496
1497 static void Callback(mirror::Object* obj, void* arg)
1498 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1499 DCHECK(arg != nullptr);
1500 BinContext* context = reinterpret_cast<BinContext*>(arg);
1501 ZygoteCompactingCollector* collector = context->collector_;
1502 uintptr_t object_addr = reinterpret_cast<uintptr_t>(obj);
1503 size_t bin_size = object_addr - context->prev_;
1504 // Add the bin consisting of the end of the previous object to the start of the current object.
1505 collector->AddBin(bin_size, context->prev_);
1506 context->prev_ = object_addr + RoundUp(obj->SizeOf(), kObjectAlignment);
1507 }
1508
1509 void AddBin(size_t size, uintptr_t position) {
1510 if (size != 0) {
1511 bins_.insert(std::make_pair(size, position));
1512 }
1513 }
1514
Mathieu Chartiera1602f22014-01-13 17:19:19 -08001515 virtual bool ShouldSweepSpace(space::ContinuousSpace* space) const {
Mathieu Chartier85a43c02014-01-07 17:59:00 -08001516 // Don't sweep any spaces since we probably blasted the internal accounting of the free list
1517 // allocator.
1518 return false;
1519 }
1520
1521 virtual mirror::Object* MarkNonForwardedObject(mirror::Object* obj)
1522 EXCLUSIVE_LOCKS_REQUIRED(Locks::heap_bitmap_lock_, Locks::mutator_lock_) {
1523 size_t object_size = RoundUp(obj->SizeOf(), kObjectAlignment);
Mathieu Chartier5dc08a62014-01-10 10:10:23 -08001524 mirror::Object* forward_address;
Mathieu Chartier85a43c02014-01-07 17:59:00 -08001525 // Find the smallest bin which we can move obj in.
1526 auto it = bins_.lower_bound(object_size);
1527 if (it == bins_.end()) {
1528 // No available space in the bins, place it in the target space instead (grows the zygote
1529 // space).
Mathieu Chartier5dc08a62014-01-10 10:10:23 -08001530 size_t bytes_allocated;
Ian Rogers6fac4472014-02-25 17:01:10 -08001531 forward_address = to_space_->Alloc(self_, object_size, &bytes_allocated, nullptr);
Mathieu Chartier85a43c02014-01-07 17:59:00 -08001532 if (to_space_live_bitmap_ != nullptr) {
1533 to_space_live_bitmap_->Set(forward_address);
Mathieu Chartier938a03b2014-01-16 15:10:31 -08001534 } else {
1535 GetHeap()->GetNonMovingSpace()->GetLiveBitmap()->Set(forward_address);
1536 GetHeap()->GetNonMovingSpace()->GetMarkBitmap()->Set(forward_address);
Mathieu Chartier85a43c02014-01-07 17:59:00 -08001537 }
1538 } else {
1539 size_t size = it->first;
1540 uintptr_t pos = it->second;
1541 bins_.erase(it); // Erase the old bin which we replace with the new smaller bin.
1542 forward_address = reinterpret_cast<mirror::Object*>(pos);
1543 // Set the live and mark bits so that sweeping system weaks works properly.
1544 bin_live_bitmap_->Set(forward_address);
1545 bin_mark_bitmap_->Set(forward_address);
1546 DCHECK_GE(size, object_size);
1547 AddBin(size - object_size, pos + object_size); // Add a new bin with the remaining space.
1548 }
1549 // Copy the object over to its new location.
1550 memcpy(reinterpret_cast<void*>(forward_address), obj, object_size);
Hiroshi Yamauchi9d04a202014-01-31 13:35:49 -08001551 if (kUseBrooksPointer) {
1552 obj->AssertSelfBrooksPointer();
1553 DCHECK_EQ(forward_address->GetBrooksPointer(), obj);
1554 forward_address->SetBrooksPointer(forward_address);
1555 forward_address->AssertSelfBrooksPointer();
1556 }
Mathieu Chartier85a43c02014-01-07 17:59:00 -08001557 return forward_address;
1558 }
1559};
1560
Mathieu Chartiera1602f22014-01-13 17:19:19 -08001561void Heap::UnBindBitmaps() {
1562 for (const auto& space : GetContinuousSpaces()) {
1563 if (space->IsContinuousMemMapAllocSpace()) {
1564 space::ContinuousMemMapAllocSpace* alloc_space = space->AsContinuousMemMapAllocSpace();
1565 if (alloc_space->HasBoundBitmaps()) {
1566 alloc_space->UnBindBitmaps();
1567 }
1568 }
1569 }
1570}
1571
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001572void Heap::PreZygoteFork() {
Mathieu Chartier1f3b5352014-02-03 14:00:42 -08001573 CollectGarbageInternal(collector::kGcTypeFull, kGcCauseBackground, false);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001574 static Mutex zygote_creation_lock_("zygote creation lock", kZygoteCreationLock);
Ian Rogers81d425b2012-09-27 16:03:43 -07001575 Thread* self = Thread::Current();
1576 MutexLock mu(self, zygote_creation_lock_);
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001577 // Try to see if we have any Zygote spaces.
1578 if (have_zygote_space_) {
1579 return;
1580 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07001581 VLOG(heap) << "Starting PreZygoteFork";
Mathieu Chartier590fee92013-09-13 13:46:47 -07001582 // Trim the pages at the end of the non moving space.
1583 non_moving_space_->Trim();
1584 non_moving_space_->GetMemMap()->Protect(PROT_READ | PROT_WRITE);
Mathieu Chartier7bf82af2013-12-06 16:51:45 -08001585 // Change the collector to the post zygote one.
1586 ChangeCollector(post_zygote_collector_type_);
Mathieu Chartier50482232013-11-21 11:48:14 -08001587 // TODO: Delete bump_pointer_space_ and temp_pointer_space_?
Mathieu Chartier590fee92013-09-13 13:46:47 -07001588 if (semi_space_collector_ != nullptr) {
Hiroshi Yamauchia4adbfd2014-02-04 18:12:17 -08001589 // Temporarily disable rosalloc verification because the zygote
1590 // compaction will mess up the rosalloc internal metadata.
1591 ScopedDisableRosAllocVerification disable_rosalloc_verif(this);
Mathieu Chartier85a43c02014-01-07 17:59:00 -08001592 ZygoteCompactingCollector zygote_collector(this);
1593 zygote_collector.BuildBins(non_moving_space_);
Mathieu Chartier50482232013-11-21 11:48:14 -08001594 // Create a new bump pointer space which we will compact into.
Mathieu Chartier590fee92013-09-13 13:46:47 -07001595 space::BumpPointerSpace target_space("zygote bump space", non_moving_space_->End(),
1596 non_moving_space_->Limit());
1597 // Compact the bump pointer space to a new zygote bump pointer space.
1598 temp_space_->GetMemMap()->Protect(PROT_READ | PROT_WRITE);
Mathieu Chartier85a43c02014-01-07 17:59:00 -08001599 zygote_collector.SetFromSpace(bump_pointer_space_);
1600 zygote_collector.SetToSpace(&target_space);
Hiroshi Yamauchi6f4ffe42014-01-13 12:30:44 -08001601 zygote_collector.Run(kGcCauseCollectorTransition, false);
Mathieu Chartier692fafd2013-11-29 17:24:40 -08001602 CHECK(temp_space_->IsEmpty());
Mathieu Chartier590fee92013-09-13 13:46:47 -07001603 total_objects_freed_ever_ += semi_space_collector_->GetFreedObjects();
1604 total_bytes_freed_ever_ += semi_space_collector_->GetFreedBytes();
1605 // Update the end and write out image.
1606 non_moving_space_->SetEnd(target_space.End());
1607 non_moving_space_->SetLimit(target_space.Limit());
Mathieu Chartier85a43c02014-01-07 17:59:00 -08001608 VLOG(heap) << "Zygote size " << non_moving_space_->Size() << " bytes";
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001609 }
Mathieu Chartiera1602f22014-01-13 17:19:19 -08001610 // Save the old space so that we can remove it after we complete creating the zygote space.
1611 space::MallocSpace* old_alloc_space = non_moving_space_;
Mathieu Chartier590fee92013-09-13 13:46:47 -07001612 // Turn the current alloc space into a zygote space and obtain the new alloc space composed of
Mathieu Chartiera1602f22014-01-13 17:19:19 -08001613 // the remaining available space.
1614 // Remove the old space before creating the zygote space since creating the zygote space sets
1615 // the old alloc space's bitmaps to nullptr.
1616 RemoveSpace(old_alloc_space);
1617 space::ZygoteSpace* zygote_space = old_alloc_space->CreateZygoteSpace("alloc space",
1618 low_memory_mode_,
1619 &main_space_);
1620 delete old_alloc_space;
1621 CHECK(zygote_space != nullptr) << "Failed creating zygote space";
1622 AddSpace(zygote_space, false);
1623 CHECK(main_space_ != nullptr);
Mathieu Chartierfc5b5282014-01-09 16:15:36 -08001624 if (main_space_->IsRosAllocSpace()) {
1625 rosalloc_space_ = main_space_->AsRosAllocSpace();
1626 } else if (main_space_->IsDlMallocSpace()) {
1627 dlmalloc_space_ = main_space_->AsDlMallocSpace();
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001628 }
Mathieu Chartierfc5b5282014-01-09 16:15:36 -08001629 main_space_->SetFootprintLimit(main_space_->Capacity());
Mathieu Chartierfc5b5282014-01-09 16:15:36 -08001630 AddSpace(main_space_);
Ian Rogers1d54e732013-05-02 21:10:01 -07001631 have_zygote_space_ = true;
Mathieu Chartierbd0a6532014-02-27 11:14:21 -08001632 // Enable large object space allocations.
1633 large_object_threshold_ = kDefaultLargeObjectThreshold;
Mathieu Chartier11409ae2013-09-23 11:49:36 -07001634 // Create the zygote space mod union table.
1635 accounting::ModUnionTable* mod_union_table =
1636 new accounting::ModUnionTableCardCache("zygote space mod-union table", this, zygote_space);
1637 CHECK(mod_union_table != nullptr) << "Failed to create zygote space mod-union table";
1638 AddModUnionTable(mod_union_table);
Mathieu Chartierfc5b5282014-01-09 16:15:36 -08001639 // Can't use RosAlloc for non moving space due to thread local buffers.
1640 // TODO: Non limited space for non-movable objects?
Mathieu Chartier938a03b2014-01-16 15:10:31 -08001641 MemMap* mem_map = post_zygote_non_moving_space_mem_map_.release();
1642 space::MallocSpace* new_non_moving_space =
1643 space::DlMallocSpace::CreateFromMemMap(mem_map, "Non moving dlmalloc space", kPageSize,
1644 2 * MB, mem_map->Size(), mem_map->Size());
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001645 AddSpace(new_non_moving_space, false);
1646 CHECK(new_non_moving_space != nullptr) << "Failed to create new non-moving space";
1647 new_non_moving_space->SetFootprintLimit(new_non_moving_space->Capacity());
1648 non_moving_space_ = new_non_moving_space;
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001649}
1650
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001651void Heap::FlushAllocStack() {
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001652 MarkAllocStackAsLive(allocation_stack_.get());
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001653 allocation_stack_->Reset();
1654}
1655
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001656void Heap::MarkAllocStack(accounting::SpaceBitmap* bitmap1,
1657 accounting::SpaceBitmap* bitmap2,
Mathieu Chartierdb7f37d2014-01-10 11:09:06 -08001658 accounting::ObjectSet* large_objects,
Ian Rogers1d54e732013-05-02 21:10:01 -07001659 accounting::ObjectStack* stack) {
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001660 DCHECK(bitmap1 != nullptr);
1661 DCHECK(bitmap2 != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001662 mirror::Object** limit = stack->End();
1663 for (mirror::Object** it = stack->Begin(); it != limit; ++it) {
1664 const mirror::Object* obj = *it;
Hiroshi Yamauchif5b0e202014-02-11 17:02:22 -08001665 if (!kUseThreadLocalAllocationStack || obj != nullptr) {
1666 if (bitmap1->HasAddress(obj)) {
1667 bitmap1->Set(obj);
1668 } else if (bitmap2->HasAddress(obj)) {
1669 bitmap2->Set(obj);
1670 } else {
1671 large_objects->Set(obj);
1672 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001673 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001674 }
1675}
1676
Mathieu Chartier590fee92013-09-13 13:46:47 -07001677void Heap::SwapSemiSpaces() {
1678 // Swap the spaces so we allocate into the space which we just evacuated.
1679 std::swap(bump_pointer_space_, temp_space_);
Mathieu Chartier15d34022014-02-26 17:16:38 -08001680 bump_pointer_space_->Clear();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001681}
1682
1683void Heap::Compact(space::ContinuousMemMapAllocSpace* target_space,
1684 space::ContinuousMemMapAllocSpace* source_space) {
1685 CHECK(kMovingCollector);
Mathieu Chartier50482232013-11-21 11:48:14 -08001686 CHECK_NE(target_space, source_space) << "In-place compaction currently unsupported";
Mathieu Chartier590fee92013-09-13 13:46:47 -07001687 if (target_space != source_space) {
1688 semi_space_collector_->SetFromSpace(source_space);
1689 semi_space_collector_->SetToSpace(target_space);
Hiroshi Yamauchi6f4ffe42014-01-13 12:30:44 -08001690 semi_space_collector_->Run(kGcCauseCollectorTransition, false);
Mathieu Chartier590fee92013-09-13 13:46:47 -07001691 }
1692}
Anwar Ghuloum67f99412013-08-12 14:19:48 -07001693
Ian Rogers1d54e732013-05-02 21:10:01 -07001694collector::GcType Heap::CollectGarbageInternal(collector::GcType gc_type, GcCause gc_cause,
1695 bool clear_soft_references) {
Ian Rogers81d425b2012-09-27 16:03:43 -07001696 Thread* self = Thread::Current();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001697 Runtime* runtime = Runtime::Current();
Mathieu Chartiercbb2d202013-11-14 17:45:16 -08001698 // If the heap can't run the GC, silently fail and return that no GC was run.
1699 switch (gc_type) {
Mathieu Chartiercbb2d202013-11-14 17:45:16 -08001700 case collector::kGcTypePartial: {
1701 if (!have_zygote_space_) {
1702 return collector::kGcTypeNone;
1703 }
1704 break;
1705 }
1706 default: {
1707 // Other GC types don't have any special cases which makes them not runnable. The main case
1708 // here is full GC.
1709 }
1710 }
Mathieu Chartier65db8802012-11-20 12:36:46 -08001711 ScopedThreadStateChange tsc(self, kWaitingPerformingGc);
Ian Rogers81d425b2012-09-27 16:03:43 -07001712 Locks::mutator_lock_->AssertNotHeld(self);
Ian Rogers120f1c72012-09-28 17:17:10 -07001713 if (self->IsHandlingStackOverflow()) {
1714 LOG(WARNING) << "Performing GC on a thread that is handling a stack overflow.";
1715 }
Mathieu Chartierd5a89ee2014-01-31 09:55:13 -08001716 bool compacting_gc;
1717 {
1718 gc_complete_lock_->AssertNotHeld(self);
Mathieu Chartiercaa82d62014-02-02 16:51:17 -08001719 ScopedThreadStateChange tsc(self, kWaitingForGcToComplete);
Mathieu Chartierd5a89ee2014-01-31 09:55:13 -08001720 MutexLock mu(self, *gc_complete_lock_);
1721 // Ensure there is only one GC at a time.
1722 WaitForGcToCompleteLocked(self);
1723 compacting_gc = IsCompactingGC(collector_type_);
1724 // GC can be disabled if someone has a used GetPrimitiveArrayCritical.
1725 if (compacting_gc && disable_moving_gc_count_ != 0) {
1726 LOG(WARNING) << "Skipping GC due to disable moving GC count " << disable_moving_gc_count_;
1727 return collector::kGcTypeNone;
1728 }
1729 collector_type_running_ = collector_type_;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001730 }
Mathieu Chartierd5a89ee2014-01-31 09:55:13 -08001731
Mathieu Chartier590fee92013-09-13 13:46:47 -07001732 if (gc_cause == kGcCauseForAlloc && runtime->HasStatsEnabled()) {
1733 ++runtime->GetStats()->gc_for_alloc_count;
1734 ++self->GetStats()->gc_for_alloc_count;
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001735 }
Ian Rogers1d54e732013-05-02 21:10:01 -07001736 uint64_t gc_start_time_ns = NanoTime();
Mathieu Chartier65db8802012-11-20 12:36:46 -08001737 uint64_t gc_start_size = GetBytesAllocated();
1738 // Approximate allocation rate in bytes / second.
Ian Rogers1d54e732013-05-02 21:10:01 -07001739 uint64_t ms_delta = NsToMs(gc_start_time_ns - last_gc_time_ns_);
Mathieu Chartier590fee92013-09-13 13:46:47 -07001740 // Back to back GCs can cause 0 ms of wait time in between GC invocations.
1741 if (LIKELY(ms_delta != 0)) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001742 allocation_rate_ = ((gc_start_size - last_gc_size_) * 1000) / ms_delta;
Mathieu Chartier65db8802012-11-20 12:36:46 -08001743 VLOG(heap) << "Allocation rate: " << PrettySize(allocation_rate_) << "/s";
1744 }
1745
Ian Rogers1d54e732013-05-02 21:10:01 -07001746 DCHECK_LT(gc_type, collector::kGcTypeMax);
1747 DCHECK_NE(gc_type, collector::kGcTypeNone);
Anwar Ghuloum67f99412013-08-12 14:19:48 -07001748
Mathieu Chartier590fee92013-09-13 13:46:47 -07001749 collector::GarbageCollector* collector = nullptr;
Mathieu Chartier50482232013-11-21 11:48:14 -08001750 // TODO: Clean this up.
Mathieu Chartier1d27b342014-01-28 12:51:09 -08001751 if (compacting_gc) {
Mathieu Chartier692fafd2013-11-29 17:24:40 -08001752 DCHECK(current_allocator_ == kAllocatorTypeBumpPointer ||
1753 current_allocator_ == kAllocatorTypeTLAB);
Mathieu Chartier590fee92013-09-13 13:46:47 -07001754 gc_type = semi_space_collector_->GetGcType();
Mathieu Chartier692fafd2013-11-29 17:24:40 -08001755 CHECK(temp_space_->IsEmpty());
Mathieu Chartier590fee92013-09-13 13:46:47 -07001756 semi_space_collector_->SetFromSpace(bump_pointer_space_);
1757 semi_space_collector_->SetToSpace(temp_space_);
Mathieu Chartier15d34022014-02-26 17:16:38 -08001758 temp_space_->GetMemMap()->Protect(PROT_READ | PROT_WRITE);
Mathieu Chartier50482232013-11-21 11:48:14 -08001759 collector = semi_space_collector_;
Mathieu Chartier590fee92013-09-13 13:46:47 -07001760 gc_type = collector::kGcTypeFull;
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001761 } else if (current_allocator_ == kAllocatorTypeRosAlloc ||
1762 current_allocator_ == kAllocatorTypeDlMalloc) {
Mathieu Chartier50482232013-11-21 11:48:14 -08001763 for (const auto& cur_collector : garbage_collectors_) {
1764 if (cur_collector->IsConcurrent() == concurrent_gc_ &&
1765 cur_collector->GetGcType() == gc_type) {
1766 collector = cur_collector;
1767 break;
1768 }
1769 }
1770 } else {
1771 LOG(FATAL) << "Invalid current allocator " << current_allocator_;
Mathieu Chartier590fee92013-09-13 13:46:47 -07001772 }
Mathieu Chartier7bf82af2013-12-06 16:51:45 -08001773 CHECK(collector != nullptr)
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001774 << "Could not find garbage collector with concurrent=" << concurrent_gc_
1775 << " and type=" << gc_type;
Mathieu Chartier590fee92013-09-13 13:46:47 -07001776 ATRACE_BEGIN(StringPrintf("%s %s GC", PrettyCause(gc_cause), collector->GetName()).c_str());
Hiroshi Yamauchi6f4ffe42014-01-13 12:30:44 -08001777 collector->Run(gc_cause, clear_soft_references);
Ian Rogers1d54e732013-05-02 21:10:01 -07001778 total_objects_freed_ever_ += collector->GetFreedObjects();
1779 total_bytes_freed_ever_ += collector->GetFreedBytes();
Mathieu Chartiera5f9de02014-02-28 16:48:42 -08001780 RequestHeapTrim(Heap::kHeapTrimWait);
Mathieu Chartier39e32612013-11-12 16:28:05 -08001781 // Enqueue cleared references.
1782 EnqueueClearedReferences();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001783 // Grow the heap so that we know when to perform the next GC.
1784 GrowForUtilization(gc_type, collector->GetDurationNs());
Mathieu Chartierca2a24d2013-11-25 15:12:12 -08001785 if (CareAboutPauseTimes()) {
Mathieu Chartiere53225c2013-08-19 10:59:11 -07001786 const size_t duration = collector->GetDurationNs();
1787 std::vector<uint64_t> pauses = collector->GetPauseTimes();
1788 // GC for alloc pauses the allocating thread, so consider it as a pause.
Mathieu Chartier2775ee42013-08-20 17:43:47 -07001789 bool was_slow = duration > long_gc_log_threshold_ ||
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001790 (gc_cause == kGcCauseForAlloc && duration > long_pause_log_threshold_);
Mathieu Chartiere53225c2013-08-19 10:59:11 -07001791 if (!was_slow) {
1792 for (uint64_t pause : pauses) {
Mathieu Chartier2775ee42013-08-20 17:43:47 -07001793 was_slow = was_slow || pause > long_pause_log_threshold_;
Mathieu Chartiere53225c2013-08-19 10:59:11 -07001794 }
1795 }
Mathieu Chartiere53225c2013-08-19 10:59:11 -07001796 if (was_slow) {
1797 const size_t percent_free = GetPercentFree();
1798 const size_t current_heap_size = GetBytesAllocated();
1799 const size_t total_memory = GetTotalMemory();
1800 std::ostringstream pause_string;
1801 for (size_t i = 0; i < pauses.size(); ++i) {
1802 pause_string << PrettyDuration((pauses[i] / 1000) * 1000)
1803 << ((i != pauses.size() - 1) ? ", " : "");
1804 }
1805 LOG(INFO) << gc_cause << " " << collector->GetName()
1806 << " GC freed " << collector->GetFreedObjects() << "("
1807 << PrettySize(collector->GetFreedBytes()) << ") AllocSpace objects, "
1808 << collector->GetFreedLargeObjects() << "("
1809 << PrettySize(collector->GetFreedLargeObjectBytes()) << ") LOS objects, "
1810 << percent_free << "% free, " << PrettySize(current_heap_size) << "/"
1811 << PrettySize(total_memory) << ", " << "paused " << pause_string.str()
1812 << " total " << PrettyDuration((duration / 1000) * 1000);
1813 if (VLOG_IS_ON(heap)) {
Ian Rogers5fe9af72013-11-14 00:17:20 -08001814 LOG(INFO) << Dumpable<TimingLogger>(collector->GetTimings());
Mathieu Chartiere53225c2013-08-19 10:59:11 -07001815 }
1816 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001817 }
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001818 FinishGC(self, gc_type);
Mathieu Chartier752a0e62013-06-27 11:03:27 -07001819 ATRACE_END();
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001820
1821 // Inform DDMS that a GC completed.
Ian Rogers15bf2d32012-08-28 17:33:04 -07001822 Dbg::GcDidFinish();
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001823 return gc_type;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001824}
Mathieu Chartiera6399032012-06-11 18:49:50 -07001825
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001826void Heap::FinishGC(Thread* self, collector::GcType gc_type) {
1827 MutexLock mu(self, *gc_complete_lock_);
Mathieu Chartierd5a89ee2014-01-31 09:55:13 -08001828 collector_type_running_ = kCollectorTypeNone;
1829 if (gc_type != collector::kGcTypeNone) {
1830 last_gc_type_ = gc_type;
1831 }
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001832 // Wake anyone who may have been waiting for the GC to complete.
1833 gc_complete_cond_->Broadcast(self);
1834}
1835
Mathieu Chartier815873e2014-02-13 18:02:13 -08001836static void RootMatchesObjectVisitor(mirror::Object** root, void* arg, uint32_t /*thread_id*/,
1837 RootType /*root_type*/) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001838 mirror::Object* obj = reinterpret_cast<mirror::Object*>(arg);
Mathieu Chartier815873e2014-02-13 18:02:13 -08001839 if (*root == obj) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001840 LOG(INFO) << "Object " << obj << " is a root";
1841 }
1842}
1843
1844class ScanVisitor {
1845 public:
Brian Carlstromdf629502013-07-17 22:39:56 -07001846 void operator()(const mirror::Object* obj) const {
Mathieu Chartier0f72e412013-09-06 16:40:01 -07001847 LOG(ERROR) << "Would have rescanned object " << obj;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001848 }
1849};
1850
Ian Rogers1d54e732013-05-02 21:10:01 -07001851// Verify a reference from an object.
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001852class VerifyReferenceVisitor {
1853 public:
Brian Carlstrom93ba8932013-07-17 21:31:49 -07001854 explicit VerifyReferenceVisitor(Heap* heap)
Ian Rogers1d54e732013-05-02 21:10:01 -07001855 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_)
Brian Carlstrom93ba8932013-07-17 21:31:49 -07001856 : heap_(heap), failed_(false) {}
Ian Rogers1d54e732013-05-02 21:10:01 -07001857
1858 bool Failed() const {
1859 return failed_;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001860 }
1861
1862 // TODO: Fix lock analysis to not use NO_THREAD_SAFETY_ANALYSIS, requires support for smarter
Ian Rogers1d54e732013-05-02 21:10:01 -07001863 // analysis on visitors.
Ian Rogersef7d42f2014-01-06 12:55:46 -08001864 void operator()(mirror::Object* obj, mirror::Object* ref,
Brian Carlstromdf629502013-07-17 22:39:56 -07001865 const MemberOffset& offset, bool /* is_static */) const
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001866 NO_THREAD_SAFETY_ANALYSIS {
Mathieu Chartier938a03b2014-01-16 15:10:31 -08001867 if (ref == nullptr || IsLive(ref)) {
1868 // Verify that the reference is live.
1869 return;
1870 }
1871 if (!failed_) {
1872 // Print message on only on first failure to prevent spam.
1873 LOG(ERROR) << "!!!!!!!!!!!!!!Heap corruption detected!!!!!!!!!!!!!!!!!!!";
1874 failed_ = true;
1875 }
1876 if (obj != nullptr) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001877 accounting::CardTable* card_table = heap_->GetCardTable();
1878 accounting::ObjectStack* alloc_stack = heap_->allocation_stack_.get();
1879 accounting::ObjectStack* live_stack = heap_->live_stack_.get();
Mathieu Chartier938a03b2014-01-16 15:10:31 -08001880 byte* card_addr = card_table->CardFromAddr(obj);
1881 LOG(ERROR) << "Object " << obj << " references dead object " << ref << " at offset "
1882 << offset << "\n card value = " << static_cast<int>(*card_addr);
1883 if (heap_->IsValidObjectAddress(obj->GetClass())) {
1884 LOG(ERROR) << "Obj type " << PrettyTypeOf(obj);
1885 } else {
1886 LOG(ERROR) << "Object " << obj << " class(" << obj->GetClass() << ") not a heap address";
Mathieu Chartier0f72e412013-09-06 16:40:01 -07001887 }
Mathieu Chartier938a03b2014-01-16 15:10:31 -08001888
1889 // Attmept to find the class inside of the recently freed objects.
1890 space::ContinuousSpace* ref_space = heap_->FindContinuousSpaceFromObject(ref, true);
1891 if (ref_space != nullptr && ref_space->IsMallocSpace()) {
1892 space::MallocSpace* space = ref_space->AsMallocSpace();
1893 mirror::Class* ref_class = space->FindRecentFreedObject(ref);
1894 if (ref_class != nullptr) {
1895 LOG(ERROR) << "Reference " << ref << " found as a recently freed object with class "
1896 << PrettyClass(ref_class);
Mathieu Chartier0f72e412013-09-06 16:40:01 -07001897 } else {
Mathieu Chartier938a03b2014-01-16 15:10:31 -08001898 LOG(ERROR) << "Reference " << ref << " not found as a recently freed object";
Mathieu Chartier0f72e412013-09-06 16:40:01 -07001899 }
Mathieu Chartier938a03b2014-01-16 15:10:31 -08001900 }
Mathieu Chartier0f72e412013-09-06 16:40:01 -07001901
Mathieu Chartier938a03b2014-01-16 15:10:31 -08001902 if (ref->GetClass() != nullptr && heap_->IsValidObjectAddress(ref->GetClass()) &&
1903 ref->GetClass()->IsClass()) {
1904 LOG(ERROR) << "Ref type " << PrettyTypeOf(ref);
1905 } else {
1906 LOG(ERROR) << "Ref " << ref << " class(" << ref->GetClass()
1907 << ") is not a valid heap address";
1908 }
1909
1910 card_table->CheckAddrIsInCardTable(reinterpret_cast<const byte*>(obj));
1911 void* cover_begin = card_table->AddrFromCard(card_addr);
1912 void* cover_end = reinterpret_cast<void*>(reinterpret_cast<size_t>(cover_begin) +
1913 accounting::CardTable::kCardSize);
1914 LOG(ERROR) << "Card " << reinterpret_cast<void*>(card_addr) << " covers " << cover_begin
1915 << "-" << cover_end;
1916 accounting::SpaceBitmap* bitmap = heap_->GetLiveBitmap()->GetContinuousSpaceBitmap(obj);
1917
1918 if (bitmap == nullptr) {
1919 LOG(ERROR) << "Object " << obj << " has no bitmap";
Mathieu Chartier4e305412014-02-19 10:54:44 -08001920 if (!VerifyClassClass(obj->GetClass())) {
Mathieu Chartier938a03b2014-01-16 15:10:31 -08001921 LOG(ERROR) << "Object " << obj << " failed class verification!";
Mathieu Chartier0f72e412013-09-06 16:40:01 -07001922 }
Mathieu Chartier938a03b2014-01-16 15:10:31 -08001923 } else {
Ian Rogers1d54e732013-05-02 21:10:01 -07001924 // Print out how the object is live.
Mathieu Chartier938a03b2014-01-16 15:10:31 -08001925 if (bitmap->Test(obj)) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001926 LOG(ERROR) << "Object " << obj << " found in live bitmap";
1927 }
Mathieu Chartier0f72e412013-09-06 16:40:01 -07001928 if (alloc_stack->Contains(const_cast<mirror::Object*>(obj))) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001929 LOG(ERROR) << "Object " << obj << " found in allocation stack";
1930 }
Mathieu Chartier0f72e412013-09-06 16:40:01 -07001931 if (live_stack->Contains(const_cast<mirror::Object*>(obj))) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001932 LOG(ERROR) << "Object " << obj << " found in live stack";
1933 }
Mathieu Chartier0f72e412013-09-06 16:40:01 -07001934 if (alloc_stack->Contains(const_cast<mirror::Object*>(ref))) {
1935 LOG(ERROR) << "Ref " << ref << " found in allocation stack";
1936 }
1937 if (live_stack->Contains(const_cast<mirror::Object*>(ref))) {
1938 LOG(ERROR) << "Ref " << ref << " found in live stack";
1939 }
Ian Rogers1d54e732013-05-02 21:10:01 -07001940 // Attempt to see if the card table missed the reference.
1941 ScanVisitor scan_visitor;
1942 byte* byte_cover_begin = reinterpret_cast<byte*>(card_table->AddrFromCard(card_addr));
1943 card_table->Scan(bitmap, byte_cover_begin,
Mathieu Chartier184e3222013-08-03 14:02:57 -07001944 byte_cover_begin + accounting::CardTable::kCardSize, scan_visitor);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001945 }
Mathieu Chartier938a03b2014-01-16 15:10:31 -08001946
1947 // Search to see if any of the roots reference our object.
1948 void* arg = const_cast<void*>(reinterpret_cast<const void*>(obj));
Mathieu Chartier893263b2014-03-04 11:07:42 -08001949 Runtime::Current()->VisitRoots(&RootMatchesObjectVisitor, arg);
Mathieu Chartier938a03b2014-01-16 15:10:31 -08001950
1951 // Search to see if any of the roots reference our reference.
1952 arg = const_cast<void*>(reinterpret_cast<const void*>(ref));
Mathieu Chartier893263b2014-03-04 11:07:42 -08001953 Runtime::Current()->VisitRoots(&RootMatchesObjectVisitor, arg);
Mathieu Chartier938a03b2014-01-16 15:10:31 -08001954 } else {
1955 LOG(ERROR) << "Root " << ref << " is dead with type " << PrettyTypeOf(ref);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001956 }
1957 }
1958
Ian Rogersef7d42f2014-01-06 12:55:46 -08001959 bool IsLive(mirror::Object* obj) const NO_THREAD_SAFETY_ANALYSIS {
Mathieu Chartier0f72e412013-09-06 16:40:01 -07001960 return heap_->IsLiveObjectLocked(obj, true, false, true);
Ian Rogers1d54e732013-05-02 21:10:01 -07001961 }
1962
Mathieu Chartier815873e2014-02-13 18:02:13 -08001963 static void VerifyRoots(mirror::Object** root, void* arg, uint32_t /*thread_id*/,
1964 RootType /*root_type*/) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001965 VerifyReferenceVisitor* visitor = reinterpret_cast<VerifyReferenceVisitor*>(arg);
Mathieu Chartier815873e2014-02-13 18:02:13 -08001966 (*visitor)(nullptr, *root, MemberOffset(0), true);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001967 }
1968
1969 private:
Ian Rogers1d54e732013-05-02 21:10:01 -07001970 Heap* const heap_;
1971 mutable bool failed_;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001972};
1973
Ian Rogers1d54e732013-05-02 21:10:01 -07001974// Verify all references within an object, for use with HeapBitmap::Visit.
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001975class VerifyObjectVisitor {
1976 public:
Brian Carlstrom93ba8932013-07-17 21:31:49 -07001977 explicit VerifyObjectVisitor(Heap* heap) : heap_(heap), failed_(false) {}
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001978
Mathieu Chartier590fee92013-09-13 13:46:47 -07001979 void operator()(mirror::Object* obj) const
Ian Rogersb726dcb2012-09-05 08:57:23 -07001980 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001981 // Note: we are verifying the references in obj but not obj itself, this is because obj must
1982 // be live or else how did we find it in the live bitmap?
1983 VerifyReferenceVisitor visitor(heap_);
Mathieu Chartier0f72e412013-09-06 16:40:01 -07001984 // The class doesn't count as a reference but we should verify it anyways.
Mathieu Chartier590fee92013-09-13 13:46:47 -07001985 collector::MarkSweep::VisitObjectReferences(obj, visitor, true);
1986 if (obj->GetClass()->IsReferenceClass()) {
1987 visitor(obj, heap_->GetReferenceReferent(obj), MemberOffset(0), false);
1988 }
Ian Rogers1d54e732013-05-02 21:10:01 -07001989 failed_ = failed_ || visitor.Failed();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001990 }
1991
Mathieu Chartier590fee92013-09-13 13:46:47 -07001992 static void VisitCallback(mirror::Object* obj, void* arg)
1993 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
1994 VerifyObjectVisitor* visitor = reinterpret_cast<VerifyObjectVisitor*>(arg);
1995 visitor->operator()(obj);
1996 }
1997
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001998 bool Failed() const {
1999 return failed_;
2000 }
2001
2002 private:
Ian Rogers1d54e732013-05-02 21:10:01 -07002003 Heap* const heap_;
2004 mutable bool failed_;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07002005};
2006
2007// Must do this with mutators suspended since we are directly accessing the allocation stacks.
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07002008bool Heap::VerifyHeapReferences() {
Hiroshi Yamauchi1ed90612014-02-14 15:00:51 -08002009 Thread* self = Thread::Current();
2010 Locks::mutator_lock_->AssertExclusiveHeld(self);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07002011 // Lets sort our allocation stacks so that we can efficiently binary search them.
Ian Rogers1d54e732013-05-02 21:10:01 -07002012 allocation_stack_->Sort();
2013 live_stack_->Sort();
Hiroshi Yamauchi1ed90612014-02-14 15:00:51 -08002014 // Since we sorted the allocation stack content, need to revoke all
2015 // thread-local allocation stacks.
2016 RevokeAllThreadLocalAllocationStacks(self);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07002017 VerifyObjectVisitor visitor(this);
Mathieu Chartier0f72e412013-09-06 16:40:01 -07002018 // Verify objects in the allocation stack since these will be objects which were:
2019 // 1. Allocated prior to the GC (pre GC verification).
2020 // 2. Allocated during the GC (pre sweep GC verification).
Mathieu Chartier0f72e412013-09-06 16:40:01 -07002021 // We don't want to verify the objects in the live stack since they themselves may be
Mathieu Chartierfd678be2012-08-30 14:50:54 -07002022 // pointing to dead objects if they are not reachable.
Mathieu Chartier590fee92013-09-13 13:46:47 -07002023 VisitObjects(VerifyObjectVisitor::VisitCallback, &visitor);
2024 // Verify the roots:
Mathieu Chartier893263b2014-03-04 11:07:42 -08002025 Runtime::Current()->VisitRoots(VerifyReferenceVisitor::VerifyRoots, &visitor);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07002026 if (visitor.Failed()) {
Mathieu Chartier0f72e412013-09-06 16:40:01 -07002027 // Dump mod-union tables.
Mathieu Chartier11409ae2013-09-23 11:49:36 -07002028 for (const auto& table_pair : mod_union_tables_) {
2029 accounting::ModUnionTable* mod_union_table = table_pair.second;
2030 mod_union_table->Dump(LOG(ERROR) << mod_union_table->GetName() << ": ");
2031 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -07002032 DumpSpaces();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07002033 return false;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07002034 }
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07002035 return true;
2036}
2037
2038class VerifyReferenceCardVisitor {
2039 public:
2040 VerifyReferenceCardVisitor(Heap* heap, bool* failed)
2041 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_,
2042 Locks::heap_bitmap_lock_)
Ian Rogers1d54e732013-05-02 21:10:01 -07002043 : heap_(heap), failed_(failed) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07002044 }
2045
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08002046 // TODO: Fix lock analysis to not use NO_THREAD_SAFETY_ANALYSIS, requires support for
2047 // annotalysis on visitors.
Ian Rogersef7d42f2014-01-06 12:55:46 -08002048 void operator()(mirror::Object* obj, mirror::Object* ref, const MemberOffset& offset,
Brian Carlstromdf629502013-07-17 22:39:56 -07002049 bool is_static) const NO_THREAD_SAFETY_ANALYSIS {
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08002050 // Filter out class references since changing an object's class does not mark the card as dirty.
2051 // Also handles large objects, since the only reference they hold is a class reference.
2052 if (ref != NULL && !ref->IsClass()) {
Ian Rogers1d54e732013-05-02 21:10:01 -07002053 accounting::CardTable* card_table = heap_->GetCardTable();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07002054 // If the object is not dirty and it is referencing something in the live stack other than
2055 // class, then it must be on a dirty card.
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07002056 if (!card_table->AddrIsInCardTable(obj)) {
2057 LOG(ERROR) << "Object " << obj << " is not in the address range of the card table";
2058 *failed_ = true;
Mathieu Chartier2b82db42012-11-14 17:29:05 -08002059 } else if (!card_table->IsDirty(obj)) {
Mathieu Chartier938a03b2014-01-16 15:10:31 -08002060 // TODO: Check mod-union tables.
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08002061 // Card should be either kCardDirty if it got re-dirtied after we aged it, or
2062 // kCardDirty - 1 if it didnt get touched since we aged it.
Ian Rogers1d54e732013-05-02 21:10:01 -07002063 accounting::ObjectStack* live_stack = heap_->live_stack_.get();
Mathieu Chartierf082d3c2013-07-29 17:04:07 -07002064 if (live_stack->ContainsSorted(const_cast<mirror::Object*>(ref))) {
2065 if (live_stack->ContainsSorted(const_cast<mirror::Object*>(obj))) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07002066 LOG(ERROR) << "Object " << obj << " found in live stack";
2067 }
2068 if (heap_->GetLiveBitmap()->Test(obj)) {
2069 LOG(ERROR) << "Object " << obj << " found in live bitmap";
2070 }
2071 LOG(ERROR) << "Object " << obj << " " << PrettyTypeOf(obj)
2072 << " references " << ref << " " << PrettyTypeOf(ref) << " in live stack";
2073
2074 // Print which field of the object is dead.
2075 if (!obj->IsObjectArray()) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08002076 mirror::Class* klass = is_static ? obj->AsClass() : obj->GetClass();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07002077 CHECK(klass != NULL);
Ian Rogersef7d42f2014-01-06 12:55:46 -08002078 mirror::ObjectArray<mirror::ArtField>* fields = is_static ? klass->GetSFields()
2079 : klass->GetIFields();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07002080 CHECK(fields != NULL);
2081 for (int32_t i = 0; i < fields->GetLength(); ++i) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08002082 mirror::ArtField* cur = fields->Get(i);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07002083 if (cur->GetOffset().Int32Value() == offset.Int32Value()) {
2084 LOG(ERROR) << (is_static ? "Static " : "") << "field in the live stack is "
2085 << PrettyField(cur);
2086 break;
2087 }
2088 }
2089 } else {
Ian Rogersef7d42f2014-01-06 12:55:46 -08002090 mirror::ObjectArray<mirror::Object>* object_array =
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002091 obj->AsObjectArray<mirror::Object>();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07002092 for (int32_t i = 0; i < object_array->GetLength(); ++i) {
2093 if (object_array->Get(i) == ref) {
2094 LOG(ERROR) << (is_static ? "Static " : "") << "obj[" << i << "] = ref";
2095 }
2096 }
2097 }
2098
2099 *failed_ = true;
2100 }
2101 }
2102 }
2103 }
2104
2105 private:
Ian Rogers1d54e732013-05-02 21:10:01 -07002106 Heap* const heap_;
2107 bool* const failed_;
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07002108};
2109
2110class VerifyLiveStackReferences {
2111 public:
Brian Carlstrom93ba8932013-07-17 21:31:49 -07002112 explicit VerifyLiveStackReferences(Heap* heap)
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07002113 : heap_(heap),
Brian Carlstrom93ba8932013-07-17 21:31:49 -07002114 failed_(false) {}
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07002115
Mathieu Chartier11409ae2013-09-23 11:49:36 -07002116 void operator()(mirror::Object* obj) const
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07002117 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
2118 VerifyReferenceCardVisitor visitor(heap_, const_cast<bool*>(&failed_));
Mathieu Chartier590fee92013-09-13 13:46:47 -07002119 collector::MarkSweep::VisitObjectReferences(const_cast<mirror::Object*>(obj), visitor, true);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07002120 }
2121
2122 bool Failed() const {
2123 return failed_;
2124 }
2125
2126 private:
Ian Rogers1d54e732013-05-02 21:10:01 -07002127 Heap* const heap_;
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07002128 bool failed_;
2129};
2130
2131bool Heap::VerifyMissingCardMarks() {
Hiroshi Yamauchi1ed90612014-02-14 15:00:51 -08002132 Thread* self = Thread::Current();
2133 Locks::mutator_lock_->AssertExclusiveHeld(self);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07002134
Mathieu Chartier2b82db42012-11-14 17:29:05 -08002135 // We need to sort the live stack since we binary search it.
Ian Rogers1d54e732013-05-02 21:10:01 -07002136 live_stack_->Sort();
Hiroshi Yamauchi1ed90612014-02-14 15:00:51 -08002137 // Since we sorted the allocation stack content, need to revoke all
2138 // thread-local allocation stacks.
2139 RevokeAllThreadLocalAllocationStacks(self);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07002140 VerifyLiveStackReferences visitor(this);
2141 GetLiveBitmap()->Visit(visitor);
2142
2143 // We can verify objects in the live stack since none of these should reference dead objects.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002144 for (mirror::Object** it = live_stack_->Begin(); it != live_stack_->End(); ++it) {
Hiroshi Yamauchif5b0e202014-02-11 17:02:22 -08002145 if (!kUseThreadLocalAllocationStack || *it != nullptr) {
2146 visitor(*it);
2147 }
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07002148 }
2149
2150 if (visitor.Failed()) {
2151 DumpSpaces();
2152 return false;
2153 }
2154 return true;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07002155}
2156
Hiroshi Yamauchif5b0e202014-02-11 17:02:22 -08002157void Heap::SwapStacks(Thread* self) {
2158 if (kUseThreadLocalAllocationStack) {
2159 live_stack_->AssertAllZero();
2160 }
Mathieu Chartierd22d5482012-11-06 17:14:12 -08002161 allocation_stack_.swap(live_stack_);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07002162}
2163
Hiroshi Yamauchif5b0e202014-02-11 17:02:22 -08002164void Heap::RevokeAllThreadLocalAllocationStacks(Thread* self) {
Hiroshi Yamauchif5b0e202014-02-11 17:02:22 -08002165 // This must be called only during the pause.
2166 CHECK(Locks::mutator_lock_->IsExclusiveHeld(self));
2167 MutexLock mu(self, *Locks::runtime_shutdown_lock_);
2168 MutexLock mu2(self, *Locks::thread_list_lock_);
2169 std::list<Thread*> thread_list = Runtime::Current()->GetThreadList()->GetList();
2170 for (Thread* t : thread_list) {
2171 t->RevokeThreadLocalAllocationStack();
2172 }
2173}
2174
Mathieu Chartier11409ae2013-09-23 11:49:36 -07002175accounting::ModUnionTable* Heap::FindModUnionTableFromSpace(space::Space* space) {
2176 auto it = mod_union_tables_.find(space);
2177 if (it == mod_union_tables_.end()) {
2178 return nullptr;
2179 }
2180 return it->second;
2181}
2182
Ian Rogers5fe9af72013-11-14 00:17:20 -08002183void Heap::ProcessCards(TimingLogger& timings) {
Ian Rogers1d54e732013-05-02 21:10:01 -07002184 // Clear cards and keep track of cards cleared in the mod-union table.
Mathieu Chartier02e25112013-08-14 16:14:24 -07002185 for (const auto& space : continuous_spaces_) {
Mathieu Chartier11409ae2013-09-23 11:49:36 -07002186 accounting::ModUnionTable* table = FindModUnionTableFromSpace(space);
2187 if (table != nullptr) {
2188 const char* name = space->IsZygoteSpace() ? "ZygoteModUnionClearCards" :
2189 "ImageModUnionClearCards";
Ian Rogers5fe9af72013-11-14 00:17:20 -08002190 TimingLogger::ScopedSplit split(name, &timings);
Mathieu Chartier11409ae2013-09-23 11:49:36 -07002191 table->ClearCards();
Mathieu Chartier590fee92013-09-13 13:46:47 -07002192 } else if (space->GetType() != space::kSpaceTypeBumpPointerSpace) {
Ian Rogers5fe9af72013-11-14 00:17:20 -08002193 TimingLogger::ScopedSplit split("AllocSpaceClearCards", &timings);
Mathieu Chartierd22d5482012-11-06 17:14:12 -08002194 // No mod union table for the AllocSpace. Age the cards so that the GC knows that these cards
2195 // were dirty before the GC started.
Mathieu Chartierbd0a6532014-02-27 11:14:21 -08002196 // TODO: Need to use atomic for the case where aged(cleaning thread) -> dirty(other thread)
2197 // -> clean(cleaning thread).
Mathieu Chartier590fee92013-09-13 13:46:47 -07002198 // The races are we either end up with: Aged card, unaged card. Since we have the checkpoint
Mathieu Chartier938a03b2014-01-16 15:10:31 -08002199 // roots and then we scan / update mod union tables after. We will always scan either card.
Mathieu Chartier590fee92013-09-13 13:46:47 -07002200 // If we end up with the non aged card, we scan it it in the pause.
Mathieu Chartierd22d5482012-11-06 17:14:12 -08002201 card_table_->ModifyCardsAtomic(space->Begin(), space->End(), AgeCardVisitor(), VoidFunctor());
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07002202 }
2203 }
2204}
2205
Mathieu Chartier815873e2014-02-13 18:02:13 -08002206static mirror::Object* IdentityMarkObjectCallback(mirror::Object* obj, void*) {
Mathieu Chartier11409ae2013-09-23 11:49:36 -07002207 return obj;
2208}
2209
Ian Rogers1d54e732013-05-02 21:10:01 -07002210void Heap::PreGcVerification(collector::GarbageCollector* gc) {
Mathieu Chartier2b82db42012-11-14 17:29:05 -08002211 ThreadList* thread_list = Runtime::Current()->GetThreadList();
2212 Thread* self = Thread::Current();
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08002213
Mathieu Chartier2b82db42012-11-14 17:29:05 -08002214 if (verify_pre_gc_heap_) {
2215 thread_list->SuspendAll();
2216 {
2217 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
2218 if (!VerifyHeapReferences()) {
2219 LOG(FATAL) << "Pre " << gc->GetName() << " heap verification failed";
2220 }
2221 }
2222 thread_list->ResumeAll();
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08002223 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -08002224
2225 // Check that all objects which reference things in the live stack are on dirty cards.
2226 if (verify_missing_card_marks_) {
2227 thread_list->SuspendAll();
2228 {
2229 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Hiroshi Yamauchif5b0e202014-02-11 17:02:22 -08002230 SwapStacks(self);
Mathieu Chartier2b82db42012-11-14 17:29:05 -08002231 // Sort the live stack so that we can quickly binary search it later.
2232 if (!VerifyMissingCardMarks()) {
2233 LOG(FATAL) << "Pre " << gc->GetName() << " missing card mark verification failed";
2234 }
Hiroshi Yamauchif5b0e202014-02-11 17:02:22 -08002235 SwapStacks(self);
Mathieu Chartier2b82db42012-11-14 17:29:05 -08002236 }
2237 thread_list->ResumeAll();
2238 }
2239
2240 if (verify_mod_union_table_) {
2241 thread_list->SuspendAll();
2242 ReaderMutexLock reader_lock(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier11409ae2013-09-23 11:49:36 -07002243 for (const auto& table_pair : mod_union_tables_) {
2244 accounting::ModUnionTable* mod_union_table = table_pair.second;
Mathieu Chartier815873e2014-02-13 18:02:13 -08002245 mod_union_table->UpdateAndMarkReferences(IdentityMarkObjectCallback, nullptr);
Mathieu Chartier11409ae2013-09-23 11:49:36 -07002246 mod_union_table->Verify();
2247 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -08002248 thread_list->ResumeAll();
2249 }
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08002250}
2251
Ian Rogers1d54e732013-05-02 21:10:01 -07002252void Heap::PreSweepingGcVerification(collector::GarbageCollector* gc) {
Mathieu Chartier2b82db42012-11-14 17:29:05 -08002253 // Called before sweeping occurs since we want to make sure we are not going so reclaim any
2254 // reachable objects.
2255 if (verify_post_gc_heap_) {
Ian Rogers1d54e732013-05-02 21:10:01 -07002256 Thread* self = Thread::Current();
2257 CHECK_NE(self->GetState(), kRunnable);
Ian Rogers1d54e732013-05-02 21:10:01 -07002258 {
2259 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
2260 // Swapping bound bitmaps does nothing.
2261 gc->SwapBitmaps();
2262 if (!VerifyHeapReferences()) {
Mathieu Chartier0f72e412013-09-06 16:40:01 -07002263 LOG(FATAL) << "Pre sweeping " << gc->GetName() << " GC verification failed";
Ian Rogers1d54e732013-05-02 21:10:01 -07002264 }
2265 gc->SwapBitmaps();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002266 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002267 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -08002268}
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002269
Ian Rogers1d54e732013-05-02 21:10:01 -07002270void Heap::PostGcVerification(collector::GarbageCollector* gc) {
Mathieu Chartier2b82db42012-11-14 17:29:05 -08002271 if (verify_system_weaks_) {
Anwar Ghuloum67f99412013-08-12 14:19:48 -07002272 Thread* self = Thread::Current();
Mathieu Chartier2b82db42012-11-14 17:29:05 -08002273 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Ian Rogers1d54e732013-05-02 21:10:01 -07002274 collector::MarkSweep* mark_sweep = down_cast<collector::MarkSweep*>(gc);
Mathieu Chartier2b82db42012-11-14 17:29:05 -08002275 mark_sweep->VerifySystemWeaks();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002276 }
Carl Shapiro69759ea2011-07-21 18:13:35 -07002277}
2278
Hiroshi Yamauchia4adbfd2014-02-04 18:12:17 -08002279void Heap::PreGcRosAllocVerification(TimingLogger* timings) {
2280 if (verify_pre_gc_rosalloc_) {
2281 TimingLogger::ScopedSplit split("PreGcRosAllocVerification", timings);
2282 for (const auto& space : continuous_spaces_) {
2283 if (space->IsRosAllocSpace()) {
2284 VLOG(heap) << "PreGcRosAllocVerification : " << space->GetName();
2285 space::RosAllocSpace* rosalloc_space = space->AsRosAllocSpace();
2286 rosalloc_space->Verify();
2287 }
2288 }
2289 }
2290}
2291
2292void Heap::PostGcRosAllocVerification(TimingLogger* timings) {
2293 if (verify_post_gc_rosalloc_) {
2294 TimingLogger::ScopedSplit split("PostGcRosAllocVerification", timings);
2295 for (const auto& space : continuous_spaces_) {
2296 if (space->IsRosAllocSpace()) {
2297 VLOG(heap) << "PostGcRosAllocVerification : " << space->GetName();
2298 space::RosAllocSpace* rosalloc_space = space->AsRosAllocSpace();
2299 rosalloc_space->Verify();
2300 }
2301 }
2302 }
2303}
2304
Mathieu Chartier590fee92013-09-13 13:46:47 -07002305collector::GcType Heap::WaitForGcToComplete(Thread* self) {
Mathieu Chartiercaa82d62014-02-02 16:51:17 -08002306 ScopedThreadStateChange tsc(self, kWaitingForGcToComplete);
Mathieu Chartier590fee92013-09-13 13:46:47 -07002307 MutexLock mu(self, *gc_complete_lock_);
2308 return WaitForGcToCompleteLocked(self);
2309}
2310
2311collector::GcType Heap::WaitForGcToCompleteLocked(Thread* self) {
Ian Rogers1d54e732013-05-02 21:10:01 -07002312 collector::GcType last_gc_type = collector::kGcTypeNone;
Mathieu Chartier590fee92013-09-13 13:46:47 -07002313 uint64_t wait_start = NanoTime();
Mathieu Chartierd5a89ee2014-01-31 09:55:13 -08002314 while (collector_type_running_ != kCollectorTypeNone) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07002315 ATRACE_BEGIN("GC: Wait For Completion");
2316 // We must wait, change thread state then sleep on gc_complete_cond_;
2317 gc_complete_cond_->Wait(self);
2318 last_gc_type = last_gc_type_;
Mathieu Chartier752a0e62013-06-27 11:03:27 -07002319 ATRACE_END();
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07002320 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07002321 uint64_t wait_time = NanoTime() - wait_start;
2322 total_wait_time_ += wait_time;
2323 if (wait_time > long_pause_log_threshold_) {
2324 LOG(INFO) << "WaitForGcToComplete blocked for " << PrettyDuration(wait_time);
2325 }
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07002326 return last_gc_type;
Carl Shapiro69759ea2011-07-21 18:13:35 -07002327}
2328
Elliott Hughesc967f782012-04-16 10:23:15 -07002329void Heap::DumpForSigQuit(std::ostream& os) {
Ian Rogers1d54e732013-05-02 21:10:01 -07002330 os << "Heap: " << GetPercentFree() << "% free, " << PrettySize(GetBytesAllocated()) << "/"
Mathieu Chartier2fde5332012-09-14 14:51:54 -07002331 << PrettySize(GetTotalMemory()) << "; " << GetObjectsAllocated() << " objects\n";
Elliott Hughes8b788fe2013-04-17 15:57:01 -07002332 DumpGcPerformanceInfo(os);
Elliott Hughesc967f782012-04-16 10:23:15 -07002333}
2334
2335size_t Heap::GetPercentFree() {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07002336 return static_cast<size_t>(100.0f * static_cast<float>(GetFreeMemory()) / GetTotalMemory());
Elliott Hughesc967f782012-04-16 10:23:15 -07002337}
2338
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002339void Heap::SetIdealFootprint(size_t max_allowed_footprint) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07002340 if (max_allowed_footprint > GetMaxMemory()) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07002341 VLOG(gc) << "Clamp target GC heap from " << PrettySize(max_allowed_footprint) << " to "
Mathieu Chartier2fde5332012-09-14 14:51:54 -07002342 << PrettySize(GetMaxMemory());
2343 max_allowed_footprint = GetMaxMemory();
2344 }
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -07002345 max_allowed_footprint_ = max_allowed_footprint;
Shih-wei Liao8c2f6412011-10-03 22:58:14 -07002346}
2347
Mathieu Chartier590fee92013-09-13 13:46:47 -07002348bool Heap::IsMovableObject(const mirror::Object* obj) const {
2349 if (kMovingCollector) {
2350 DCHECK(!IsInTempSpace(obj));
2351 if (bump_pointer_space_->HasAddress(obj)) {
2352 return true;
2353 }
Mathieu Chartier9be9a7a2014-01-24 14:07:33 -08002354 // TODO: Refactor this logic into the space itself?
2355 // Objects in the main space are only copied during background -> foreground transitions or
2356 // visa versa.
2357 if (main_space_ != nullptr && main_space_->HasAddress(obj) &&
Mathieu Chartier1d27b342014-01-28 12:51:09 -08002358 (IsCompactingGC(background_collector_type_) ||
2359 IsCompactingGC(post_zygote_collector_type_))) {
Mathieu Chartierfc5b5282014-01-09 16:15:36 -08002360 return true;
2361 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07002362 }
2363 return false;
2364}
2365
2366bool Heap::IsInTempSpace(const mirror::Object* obj) const {
2367 if (temp_space_->HasAddress(obj) && !temp_space_->Contains(obj)) {
2368 return true;
2369 }
2370 return false;
2371}
2372
Mathieu Chartier987ccff2013-07-08 11:05:21 -07002373void Heap::UpdateMaxNativeFootprint() {
2374 size_t native_size = native_bytes_allocated_;
2375 // TODO: Tune the native heap utilization to be a value other than the java heap utilization.
2376 size_t target_size = native_size / GetTargetHeapUtilization();
2377 if (target_size > native_size + max_free_) {
2378 target_size = native_size + max_free_;
2379 } else if (target_size < native_size + min_free_) {
2380 target_size = native_size + min_free_;
2381 }
2382 native_footprint_gc_watermark_ = target_size;
2383 native_footprint_limit_ = 2 * target_size - native_size;
2384}
2385
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -07002386void Heap::GrowForUtilization(collector::GcType gc_type, uint64_t gc_duration) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07002387 // We know what our utilization is at this moment.
2388 // This doesn't actually resize any memory. It just lets the heap grow more when necessary.
Mathieu Chartier65db8802012-11-20 12:36:46 -08002389 const size_t bytes_allocated = GetBytesAllocated();
2390 last_gc_size_ = bytes_allocated;
Ian Rogers1d54e732013-05-02 21:10:01 -07002391 last_gc_time_ns_ = NanoTime();
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -07002392 size_t target_size;
2393 if (gc_type != collector::kGcTypeSticky) {
2394 // Grow the heap for non sticky GC.
2395 target_size = bytes_allocated / GetTargetHeapUtilization();
2396 if (target_size > bytes_allocated + max_free_) {
2397 target_size = bytes_allocated + max_free_;
2398 } else if (target_size < bytes_allocated + min_free_) {
2399 target_size = bytes_allocated + min_free_;
2400 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07002401 native_need_to_run_finalization_ = true;
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -07002402 next_gc_type_ = collector::kGcTypeSticky;
2403 } else {
2404 // Based on how close the current heap size is to the target size, decide
2405 // whether or not to do a partial or sticky GC next.
2406 if (bytes_allocated + min_free_ <= max_allowed_footprint_) {
2407 next_gc_type_ = collector::kGcTypeSticky;
2408 } else {
Mathieu Chartier74762802014-01-24 10:21:35 -08002409 next_gc_type_ = have_zygote_space_ ? collector::kGcTypePartial : collector::kGcTypeFull;
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -07002410 }
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -07002411 // If we have freed enough memory, shrink the heap back down.
2412 if (bytes_allocated + max_free_ < max_allowed_footprint_) {
2413 target_size = bytes_allocated + max_free_;
2414 } else {
2415 target_size = std::max(bytes_allocated, max_allowed_footprint_);
2416 }
2417 }
Mathieu Chartier2775ee42013-08-20 17:43:47 -07002418 if (!ignore_max_footprint_) {
2419 SetIdealFootprint(target_size);
Mathieu Chartier7bf82af2013-12-06 16:51:45 -08002420 if (concurrent_gc_) {
Mathieu Chartier2775ee42013-08-20 17:43:47 -07002421 // Calculate when to perform the next ConcurrentGC.
Mathieu Chartier2775ee42013-08-20 17:43:47 -07002422 // Calculate the estimated GC duration.
Mathieu Chartier74762802014-01-24 10:21:35 -08002423 const double gc_duration_seconds = NsToMs(gc_duration) / 1000.0;
Mathieu Chartier2775ee42013-08-20 17:43:47 -07002424 // Estimate how many remaining bytes we will have when we need to start the next GC.
2425 size_t remaining_bytes = allocation_rate_ * gc_duration_seconds;
Mathieu Chartier74762802014-01-24 10:21:35 -08002426 remaining_bytes = std::min(remaining_bytes, kMaxConcurrentRemainingBytes);
Mathieu Chartier2775ee42013-08-20 17:43:47 -07002427 remaining_bytes = std::max(remaining_bytes, kMinConcurrentRemainingBytes);
2428 if (UNLIKELY(remaining_bytes > max_allowed_footprint_)) {
2429 // A never going to happen situation that from the estimated allocation rate we will exceed
2430 // the applications entire footprint with the given estimated allocation rate. Schedule
Mathieu Chartier74762802014-01-24 10:21:35 -08002431 // another GC nearly straight away.
2432 remaining_bytes = kMinConcurrentRemainingBytes;
Mathieu Chartier2775ee42013-08-20 17:43:47 -07002433 }
Mathieu Chartier74762802014-01-24 10:21:35 -08002434 DCHECK_LE(remaining_bytes, max_allowed_footprint_);
Mathieu Chartier2775ee42013-08-20 17:43:47 -07002435 DCHECK_LE(max_allowed_footprint_, growth_limit_);
Mathieu Chartier74762802014-01-24 10:21:35 -08002436 // Start a concurrent GC when we get close to the estimated remaining bytes. When the
2437 // allocation rate is very high, remaining_bytes could tell us that we should start a GC
2438 // right away.
2439 concurrent_start_bytes_ = std::max(max_allowed_footprint_ - remaining_bytes, bytes_allocated);
Mathieu Chartier65db8802012-11-20 12:36:46 -08002440 }
Mathieu Chartier65db8802012-11-20 12:36:46 -08002441 }
Carl Shapiro69759ea2011-07-21 18:13:35 -07002442}
2443
jeffhaoc1160702011-10-27 15:48:45 -07002444void Heap::ClearGrowthLimit() {
Mathieu Chartier80de7a62012-11-27 17:21:50 -08002445 growth_limit_ = capacity_;
Mathieu Chartier590fee92013-09-13 13:46:47 -07002446 non_moving_space_->ClearGrowthLimit();
jeffhaoc1160702011-10-27 15:48:45 -07002447}
2448
Elliott Hughesadb460d2011-10-05 17:02:34 -07002449void Heap::SetReferenceOffsets(MemberOffset reference_referent_offset,
Mathieu Chartier50482232013-11-21 11:48:14 -08002450 MemberOffset reference_queue_offset,
2451 MemberOffset reference_queueNext_offset,
2452 MemberOffset reference_pendingNext_offset,
2453 MemberOffset finalizer_reference_zombie_offset) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07002454 reference_referent_offset_ = reference_referent_offset;
2455 reference_queue_offset_ = reference_queue_offset;
2456 reference_queueNext_offset_ = reference_queueNext_offset;
2457 reference_pendingNext_offset_ = reference_pendingNext_offset;
2458 finalizer_reference_zombie_offset_ = finalizer_reference_zombie_offset;
2459 CHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
2460 CHECK_NE(reference_queue_offset_.Uint32Value(), 0U);
2461 CHECK_NE(reference_queueNext_offset_.Uint32Value(), 0U);
2462 CHECK_NE(reference_pendingNext_offset_.Uint32Value(), 0U);
2463 CHECK_NE(finalizer_reference_zombie_offset_.Uint32Value(), 0U);
2464}
2465
Mathieu Chartier590fee92013-09-13 13:46:47 -07002466void Heap::SetReferenceReferent(mirror::Object* reference, mirror::Object* referent) {
2467 DCHECK(reference != NULL);
2468 DCHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01002469 reference->SetFieldObject<false, false>(reference_referent_offset_, referent, true);
Mathieu Chartier590fee92013-09-13 13:46:47 -07002470}
2471
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002472mirror::Object* Heap::GetReferenceReferent(mirror::Object* reference) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07002473 DCHECK(reference != NULL);
2474 DCHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
Ian Rogersef7d42f2014-01-06 12:55:46 -08002475 return reference->GetFieldObject<mirror::Object>(reference_referent_offset_, true);
Elliott Hughesadb460d2011-10-05 17:02:34 -07002476}
2477
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002478void Heap::AddFinalizerReference(Thread* self, mirror::Object* object) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002479 ScopedObjectAccess soa(self);
Jeff Hao5d917302013-02-27 17:57:33 -08002480 JValue result;
Ian Rogers0177e532014-02-11 16:30:46 -08002481 ArgArray arg_array("VL", 2);
Ian Rogersef7d42f2014-01-06 12:55:46 -08002482 arg_array.Append(object);
Jeff Hao5d917302013-02-27 17:57:33 -08002483 soa.DecodeMethod(WellKnownClasses::java_lang_ref_FinalizerReference_add)->Invoke(self,
Ian Rogers0177e532014-02-11 16:30:46 -08002484 arg_array.GetArray(), arg_array.GetNumBytes(), &result, "VL");
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002485}
2486
Mathieu Chartier39e32612013-11-12 16:28:05 -08002487void Heap::EnqueueClearedReferences() {
Mathieu Chartierd5a89ee2014-01-31 09:55:13 -08002488 Thread* self = Thread::Current();
2489 Locks::mutator_lock_->AssertNotHeld(self);
Mathieu Chartier39e32612013-11-12 16:28:05 -08002490 if (!cleared_references_.IsEmpty()) {
Ian Rogers64b6d142012-10-29 16:34:15 -07002491 // When a runtime isn't started there are no reference queues to care about so ignore.
2492 if (LIKELY(Runtime::Current()->IsStarted())) {
Mathieu Chartierd5a89ee2014-01-31 09:55:13 -08002493 ScopedObjectAccess soa(self);
Jeff Hao5d917302013-02-27 17:57:33 -08002494 JValue result;
Ian Rogers0177e532014-02-11 16:30:46 -08002495 ArgArray arg_array("VL", 2);
Ian Rogersef7d42f2014-01-06 12:55:46 -08002496 arg_array.Append(cleared_references_.GetList());
Jeff Hao5d917302013-02-27 17:57:33 -08002497 soa.DecodeMethod(WellKnownClasses::java_lang_ref_ReferenceQueue_add)->Invoke(soa.Self(),
Ian Rogers0177e532014-02-11 16:30:46 -08002498 arg_array.GetArray(), arg_array.GetNumBytes(), &result, "VL");
Ian Rogers64b6d142012-10-29 16:34:15 -07002499 }
Mathieu Chartier39e32612013-11-12 16:28:05 -08002500 cleared_references_.Clear();
Elliott Hughesadb460d2011-10-05 17:02:34 -07002501 }
2502}
2503
Ian Rogers1f539342012-10-03 21:09:42 -07002504void Heap::RequestConcurrentGC(Thread* self) {
Mathieu Chartier069387a2012-06-18 12:01:01 -07002505 // Make sure that we can do a concurrent GC.
Ian Rogers120f1c72012-09-28 17:17:10 -07002506 Runtime* runtime = Runtime::Current();
Mathieu Chartier590fee92013-09-13 13:46:47 -07002507 if (runtime == NULL || !runtime->IsFinishedStarting() || runtime->IsShuttingDown(self) ||
2508 self->IsHandlingStackOverflow()) {
Ian Rogers120f1c72012-09-28 17:17:10 -07002509 return;
2510 }
Mathieu Chartier987ccff2013-07-08 11:05:21 -07002511 // We already have a request pending, no reason to start more until we update
2512 // concurrent_start_bytes_.
2513 concurrent_start_bytes_ = std::numeric_limits<size_t>::max();
Ian Rogers120f1c72012-09-28 17:17:10 -07002514 JNIEnv* env = self->GetJniEnv();
Mathieu Chartier590fee92013-09-13 13:46:47 -07002515 DCHECK(WellKnownClasses::java_lang_Daemons != nullptr);
2516 DCHECK(WellKnownClasses::java_lang_Daemons_requestGC != nullptr);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002517 env->CallStaticVoidMethod(WellKnownClasses::java_lang_Daemons,
2518 WellKnownClasses::java_lang_Daemons_requestGC);
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07002519 CHECK(!env->ExceptionCheck());
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07002520}
2521
Ian Rogers81d425b2012-09-27 16:03:43 -07002522void Heap::ConcurrentGC(Thread* self) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07002523 if (Runtime::Current()->IsShuttingDown(self)) {
2524 return;
Mathieu Chartier2542d662012-06-21 17:14:11 -07002525 }
Mathieu Chartier65db8802012-11-20 12:36:46 -08002526 // Wait for any GCs currently running to finish.
Mathieu Chartier590fee92013-09-13 13:46:47 -07002527 if (WaitForGcToComplete(self) == collector::kGcTypeNone) {
Mathieu Chartierf9ed0d32013-11-21 16:42:47 -08002528 // If the we can't run the GC type we wanted to run, find the next appropriate one and try that
2529 // instead. E.g. can't do partial, so do full instead.
2530 if (CollectGarbageInternal(next_gc_type_, kGcCauseBackground, false) ==
2531 collector::kGcTypeNone) {
2532 for (collector::GcType gc_type : gc_plan_) {
2533 // Attempt to run the collector, if we succeed, we are done.
2534 if (gc_type > next_gc_type_ &&
2535 CollectGarbageInternal(gc_type, kGcCauseBackground, false) != collector::kGcTypeNone) {
2536 break;
2537 }
2538 }
2539 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -07002540 }
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07002541}
2542
Mathieu Chartiera5f9de02014-02-28 16:48:42 -08002543void Heap::RequestHeapTransition(CollectorType desired_collector_type, uint64_t delta_time) {
2544 Thread* self = Thread::Current();
2545 {
2546 MutexLock mu(self, *heap_trim_request_lock_);
2547 if (desired_collector_type_ == desired_collector_type) {
2548 return;
2549 }
2550 heap_transition_target_time_ = std::max(heap_transition_target_time_, NanoTime() + delta_time);
2551 desired_collector_type_ = desired_collector_type;
2552 }
2553 SignalHeapTrimDaemon(self);
2554}
2555
2556void Heap::RequestHeapTrim(uint64_t delta_time) {
Ian Rogers48931882013-01-22 14:35:16 -08002557 // GC completed and now we must decide whether to request a heap trim (advising pages back to the
2558 // kernel) or not. Issuing a request will also cause trimming of the libc heap. As a trim scans
2559 // a space it will hold its lock and can become a cause of jank.
2560 // Note, the large object space self trims and the Zygote space was trimmed and unchanging since
2561 // forking.
2562
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08002563 // We don't have a good measure of how worthwhile a trim might be. We can't use the live bitmap
2564 // because that only marks object heads, so a large array looks like lots of empty space. We
2565 // don't just call dlmalloc all the time, because the cost of an _attempted_ trim is proportional
2566 // to utilization (which is probably inversely proportional to how much benefit we can expect).
2567 // We could try mincore(2) but that's only a measure of how many pages we haven't given away,
2568 // not how much use we're making of those pages.
Ian Rogers120f1c72012-09-28 17:17:10 -07002569
2570 Thread* self = Thread::Current();
Mathieu Chartier590fee92013-09-13 13:46:47 -07002571 Runtime* runtime = Runtime::Current();
2572 if (runtime == nullptr || !runtime->IsFinishedStarting() || runtime->IsShuttingDown(self)) {
2573 // Heap trimming isn't supported without a Java runtime or Daemons (such as at dex2oat time)
2574 // Also: we do not wish to start a heap trim if the runtime is shutting down (a racy check
2575 // as we don't hold the lock while requesting the trim).
2576 return;
Ian Rogerse1d490c2012-02-03 09:09:07 -08002577 }
Ian Rogers48931882013-01-22 14:35:16 -08002578
Mathieu Chartiera5f9de02014-02-28 16:48:42 -08002579 // Request a heap trim only if we do not currently care about pause times.
Mathieu Chartierca2a24d2013-11-25 15:12:12 -08002580 if (!CareAboutPauseTimes()) {
Mathieu Chartiera5f9de02014-02-28 16:48:42 -08002581 {
2582 MutexLock mu(self, *heap_trim_request_lock_);
2583 heap_trim_target_time_ = std::max(heap_trim_target_time_, NanoTime() + delta_time);
2584 heap_trim_request_pending_ = true;
2585 }
2586 // Notify the daemon thread which will actually do the heap trim.
2587 SignalHeapTrimDaemon(self);
Mathieu Chartierc39e3422013-08-07 16:41:36 -07002588 }
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08002589}
2590
Mathieu Chartiera5f9de02014-02-28 16:48:42 -08002591void Heap::SignalHeapTrimDaemon(Thread* self) {
2592 JNIEnv* env = self->GetJniEnv();
2593 DCHECK(WellKnownClasses::java_lang_Daemons != nullptr);
2594 DCHECK(WellKnownClasses::java_lang_Daemons_requestHeapTrim != nullptr);
2595 env->CallStaticVoidMethod(WellKnownClasses::java_lang_Daemons,
2596 WellKnownClasses::java_lang_Daemons_requestHeapTrim);
2597 CHECK(!env->ExceptionCheck());
2598}
2599
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -07002600void Heap::RevokeThreadLocalBuffers(Thread* thread) {
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08002601 if (rosalloc_space_ != nullptr) {
2602 rosalloc_space_->RevokeThreadLocalBuffers(thread);
2603 }
Mathieu Chartier692fafd2013-11-29 17:24:40 -08002604 if (bump_pointer_space_ != nullptr) {
2605 bump_pointer_space_->RevokeThreadLocalBuffers(thread);
2606 }
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -07002607}
2608
2609void Heap::RevokeAllThreadLocalBuffers() {
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08002610 if (rosalloc_space_ != nullptr) {
2611 rosalloc_space_->RevokeAllThreadLocalBuffers();
2612 }
Mathieu Chartier692fafd2013-11-29 17:24:40 -08002613 if (bump_pointer_space_ != nullptr) {
2614 bump_pointer_space_->RevokeAllThreadLocalBuffers();
2615 }
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -07002616}
2617
Mathieu Chartier987ccff2013-07-08 11:05:21 -07002618bool Heap::IsGCRequestPending() const {
2619 return concurrent_start_bytes_ != std::numeric_limits<size_t>::max();
2620}
2621
Mathieu Chartier590fee92013-09-13 13:46:47 -07002622void Heap::RunFinalization(JNIEnv* env) {
2623 // Can't do this in WellKnownClasses::Init since System is not properly set up at that point.
2624 if (WellKnownClasses::java_lang_System_runFinalization == nullptr) {
2625 CHECK(WellKnownClasses::java_lang_System != nullptr);
2626 WellKnownClasses::java_lang_System_runFinalization =
2627 CacheMethod(env, WellKnownClasses::java_lang_System, true, "runFinalization", "()V");
2628 CHECK(WellKnownClasses::java_lang_System_runFinalization != nullptr);
2629 }
2630 env->CallStaticVoidMethod(WellKnownClasses::java_lang_System,
2631 WellKnownClasses::java_lang_System_runFinalization);
2632}
2633
Ian Rogers1eb512d2013-10-18 15:42:20 -07002634void Heap::RegisterNativeAllocation(JNIEnv* env, int bytes) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07002635 Thread* self = ThreadForEnv(env);
2636 if (native_need_to_run_finalization_) {
2637 RunFinalization(env);
2638 UpdateMaxNativeFootprint();
2639 native_need_to_run_finalization_ = false;
2640 }
Mathieu Chartier987ccff2013-07-08 11:05:21 -07002641 // Total number of native bytes allocated.
Ian Rogersb122a4b2013-11-19 18:00:50 -08002642 native_bytes_allocated_.FetchAndAdd(bytes);
Mathieu Chartier987ccff2013-07-08 11:05:21 -07002643 if (static_cast<size_t>(native_bytes_allocated_) > native_footprint_gc_watermark_) {
Mathieu Chartiercbb2d202013-11-14 17:45:16 -08002644 collector::GcType gc_type = have_zygote_space_ ? collector::kGcTypePartial :
2645 collector::kGcTypeFull;
2646
Mathieu Chartier987ccff2013-07-08 11:05:21 -07002647 // The second watermark is higher than the gc watermark. If you hit this it means you are
2648 // allocating native objects faster than the GC can keep up with.
2649 if (static_cast<size_t>(native_bytes_allocated_) > native_footprint_limit_) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07002650 if (WaitForGcToComplete(self) != collector::kGcTypeNone) {
2651 // Just finished a GC, attempt to run finalizers.
2652 RunFinalization(env);
2653 CHECK(!env->ExceptionCheck());
2654 }
2655 // If we still are over the watermark, attempt a GC for alloc and run finalizers.
2656 if (static_cast<size_t>(native_bytes_allocated_) > native_footprint_limit_) {
Hiroshi Yamauchi6f4ffe42014-01-13 12:30:44 -08002657 CollectGarbageInternal(gc_type, kGcCauseForNativeAlloc, false);
Mathieu Chartier590fee92013-09-13 13:46:47 -07002658 RunFinalization(env);
2659 native_need_to_run_finalization_ = false;
2660 CHECK(!env->ExceptionCheck());
2661 }
2662 // We have just run finalizers, update the native watermark since it is very likely that
2663 // finalizers released native managed allocations.
2664 UpdateMaxNativeFootprint();
2665 } else if (!IsGCRequestPending()) {
Mathieu Chartier7bf82af2013-12-06 16:51:45 -08002666 if (concurrent_gc_) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07002667 RequestConcurrentGC(self);
2668 } else {
Mathieu Chartiercbb2d202013-11-14 17:45:16 -08002669 CollectGarbageInternal(gc_type, kGcCauseForAlloc, false);
Mathieu Chartier987ccff2013-07-08 11:05:21 -07002670 }
2671 }
2672 }
2673}
2674
Ian Rogers1eb512d2013-10-18 15:42:20 -07002675void Heap::RegisterNativeFree(JNIEnv* env, int bytes) {
Mathieu Chartier987ccff2013-07-08 11:05:21 -07002676 int expected_size, new_size;
2677 do {
Ian Rogersb122a4b2013-11-19 18:00:50 -08002678 expected_size = native_bytes_allocated_.Load();
Mathieu Chartier590fee92013-09-13 13:46:47 -07002679 new_size = expected_size - bytes;
2680 if (UNLIKELY(new_size < 0)) {
2681 ScopedObjectAccess soa(env);
2682 env->ThrowNew(WellKnownClasses::java_lang_RuntimeException,
2683 StringPrintf("Attempted to free %d native bytes with only %d native bytes "
2684 "registered as allocated", bytes, expected_size).c_str());
2685 break;
2686 }
Ian Rogersb122a4b2013-11-19 18:00:50 -08002687 } while (!native_bytes_allocated_.CompareAndSwap(expected_size, new_size));
Mathieu Chartier987ccff2013-07-08 11:05:21 -07002688}
2689
Ian Rogersef7d42f2014-01-06 12:55:46 -08002690size_t Heap::GetTotalMemory() const {
2691 size_t ret = 0;
Mathieu Chartier02e25112013-08-14 16:14:24 -07002692 for (const auto& space : continuous_spaces_) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07002693 // Currently don't include the image space.
2694 if (!space->IsImageSpace()) {
2695 ret += space->Size();
Hiroshi Yamauchi09b07a92013-07-15 13:17:06 -07002696 }
2697 }
Mathieu Chartier02e25112013-08-14 16:14:24 -07002698 for (const auto& space : discontinuous_spaces_) {
Hiroshi Yamauchi09b07a92013-07-15 13:17:06 -07002699 if (space->IsLargeObjectSpace()) {
2700 ret += space->AsLargeObjectSpace()->GetBytesAllocated();
2701 }
2702 }
2703 return ret;
2704}
2705
Mathieu Chartier11409ae2013-09-23 11:49:36 -07002706void Heap::AddModUnionTable(accounting::ModUnionTable* mod_union_table) {
2707 DCHECK(mod_union_table != nullptr);
2708 mod_union_tables_.Put(mod_union_table->GetSpace(), mod_union_table);
2709}
2710
Ian Rogers1d54e732013-05-02 21:10:01 -07002711} // namespace gc
Carl Shapiro69759ea2011-07-21 18:13:35 -07002712} // namespace art