blob: d962f3ce55cb3c54ea6c7f0ae09e4223bd6c226a [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 }
Hiroshi Yamauchi5ccd4982014-03-11 12:19:04 -0700164 const bool is_zygote = Runtime::Current()->IsZygote();
Mathieu Chartier50482232013-11-21 11:48:14 -0800165 // If we aren't the zygote, switch to the default non zygote allocator. This may update the
166 // entrypoints.
Hiroshi Yamauchi5ccd4982014-03-11 12:19:04 -0700167 if (!is_zygote) {
Mathieu Chartiera5f9de02014-02-28 16:48:42 -0800168 desired_collector_type_ = post_zygote_collector_type_;
Mathieu Chartierbd0a6532014-02-27 11:14:21 -0800169 large_object_threshold_ = kDefaultLargeObjectThreshold;
Mathieu Chartier7bf82af2013-12-06 16:51:45 -0800170 } else {
Mathieu Chartierbd0a6532014-02-27 11:14:21 -0800171 if (kMovingCollector) {
172 // We are the zygote, use bump pointer allocation + semi space collector.
Mathieu Chartiera5f9de02014-02-28 16:48:42 -0800173 desired_collector_type_ = kCollectorTypeSS;
Mathieu Chartierbd0a6532014-02-27 11:14:21 -0800174 } else {
Mathieu Chartiera5f9de02014-02-28 16:48:42 -0800175 desired_collector_type_ = post_zygote_collector_type_;
Mathieu Chartierbd0a6532014-02-27 11:14:21 -0800176 }
Mathieu Chartier50482232013-11-21 11:48:14 -0800177 }
Mathieu Chartiera5f9de02014-02-28 16:48:42 -0800178 ChangeCollector(desired_collector_type_);
Mathieu Chartier7bf82af2013-12-06 16:51:45 -0800179
Ian Rogers1d54e732013-05-02 21:10:01 -0700180 live_bitmap_.reset(new accounting::HeapBitmap(this));
181 mark_bitmap_.reset(new accounting::HeapBitmap(this));
Ian Rogers30fab402012-01-23 15:43:46 -0800182 // Requested begin for the alloc space, to follow the mapped image and oat files
Mathieu Chartier50482232013-11-21 11:48:14 -0800183 byte* requested_alloc_space_begin = nullptr;
Brian Carlstrom5643b782012-02-05 12:32:53 -0800184 if (!image_file_name.empty()) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700185 space::ImageSpace* image_space = space::ImageSpace::Create(image_file_name.c_str());
Mathieu Chartier50482232013-11-21 11:48:14 -0800186 CHECK(image_space != nullptr) << "Failed to create space for " << image_file_name;
Mathieu Chartier590fee92013-09-13 13:46:47 -0700187 AddSpace(image_space);
Ian Rogers30fab402012-01-23 15:43:46 -0800188 // Oat files referenced by image files immediately follow them in memory, ensure alloc space
189 // isn't going to get in the middle
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800190 byte* oat_file_end_addr = image_space->GetImageHeader().GetOatFileEnd();
191 CHECK_GT(oat_file_end_addr, image_space->End());
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700192 if (oat_file_end_addr > requested_alloc_space_begin) {
Mathieu Chartier50482232013-11-21 11:48:14 -0800193 requested_alloc_space_begin = AlignUp(oat_file_end_addr, kPageSize);
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700194 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700195 }
Hiroshi Yamauchi5ccd4982014-03-11 12:19:04 -0700196 MemMap* malloc_space_mem_map = nullptr;
197 const char* malloc_space_name = is_zygote ? "zygote space" : "alloc space";
198 if (is_zygote) {
199 // Allocate a single mem map that is split into the malloc space
200 // and the post zygote non-moving space to put them adjacent.
201 size_t post_zygote_non_moving_space_size = 64 * MB;
202 size_t non_moving_spaces_size = capacity + post_zygote_non_moving_space_size;
203 std::string error_str;
204 malloc_space_mem_map = MemMap::MapAnonymous(malloc_space_name, requested_alloc_space_begin,
205 non_moving_spaces_size, PROT_READ | PROT_WRITE,
206 true, &error_str);
207 CHECK(malloc_space_mem_map != nullptr) << error_str;
208 post_zygote_non_moving_space_mem_map_.reset(malloc_space_mem_map->RemapAtEnd(
209 malloc_space_mem_map->Begin() + capacity, "post zygote non-moving space",
210 PROT_READ | PROT_WRITE, &error_str));
211 CHECK(post_zygote_non_moving_space_mem_map_.get() != nullptr) << error_str;
212 VLOG(heap) << "malloc space mem map : " << malloc_space_mem_map;
213 VLOG(heap) << "post zygote non-moving space mem map : "
214 << post_zygote_non_moving_space_mem_map_.get();
215 } else {
216 // Allocate a mem map for the malloc space.
217 std::string error_str;
218 malloc_space_mem_map = MemMap::MapAnonymous(malloc_space_name, requested_alloc_space_begin,
219 capacity, PROT_READ | PROT_WRITE, true, &error_str);
220 CHECK(malloc_space_mem_map != nullptr) << error_str;
221 VLOG(heap) << "malloc space mem map : " << malloc_space_mem_map;
222 }
223 CHECK(malloc_space_mem_map != nullptr);
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800224 space::MallocSpace* malloc_space;
225 if (kUseRosAlloc) {
Hiroshi Yamauchi5ccd4982014-03-11 12:19:04 -0700226 malloc_space = space::RosAllocSpace::CreateFromMemMap(malloc_space_mem_map, malloc_space_name,
227 kDefaultStartingSize, initial_size,
228 growth_limit, capacity, low_memory_mode_);
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800229 CHECK(malloc_space != nullptr) << "Failed to create rosalloc space";
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -0700230 } else {
Hiroshi Yamauchi5ccd4982014-03-11 12:19:04 -0700231 malloc_space = space::DlMallocSpace::CreateFromMemMap(malloc_space_mem_map, malloc_space_name,
232 kDefaultStartingSize, initial_size,
233 growth_limit, capacity);
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800234 CHECK(malloc_space != nullptr) << "Failed to create dlmalloc space";
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -0700235 }
Hiroshi Yamauchi05e713a2014-01-09 13:24:51 -0800236 VLOG(heap) << "malloc_space : " << malloc_space;
Mathieu Chartier590fee92013-09-13 13:46:47 -0700237 if (kMovingCollector) {
238 // TODO: Place bump-pointer spaces somewhere to minimize size of card table.
239 // TODO: Having 3+ spaces as big as the large heap size can cause virtual memory fragmentation
240 // issues.
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800241 const size_t bump_pointer_space_size = std::min(malloc_space->Capacity(), 128 * MB);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700242 bump_pointer_space_ = space::BumpPointerSpace::Create("Bump pointer space",
243 bump_pointer_space_size, nullptr);
244 CHECK(bump_pointer_space_ != nullptr) << "Failed to create bump pointer space";
245 AddSpace(bump_pointer_space_);
246 temp_space_ = space::BumpPointerSpace::Create("Bump pointer space 2", bump_pointer_space_size,
247 nullptr);
248 CHECK(temp_space_ != nullptr) << "Failed to create bump pointer space";
249 AddSpace(temp_space_);
Hiroshi Yamauchi05e713a2014-01-09 13:24:51 -0800250 VLOG(heap) << "bump_pointer_space : " << bump_pointer_space_;
251 VLOG(heap) << "temp_space : " << temp_space_;
Mathieu Chartier590fee92013-09-13 13:46:47 -0700252 }
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800253 non_moving_space_ = malloc_space;
254 malloc_space->SetFootprintLimit(malloc_space->Capacity());
255 AddSpace(malloc_space);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700256
Mathieu Chartiereb5710e2013-07-25 15:19:42 -0700257 // Allocate the large object space.
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800258 constexpr bool kUseFreeListSpaceForLOS = false;
Mathieu Chartiereb5710e2013-07-25 15:19:42 -0700259 if (kUseFreeListSpaceForLOS) {
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800260 large_object_space_ = space::FreeListSpace::Create("large object space", nullptr, capacity);
Mathieu Chartiereb5710e2013-07-25 15:19:42 -0700261 } else {
262 large_object_space_ = space::LargeObjectMapSpace::Create("large object space");
263 }
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800264 CHECK(large_object_space_ != nullptr) << "Failed to create large object space";
Mathieu Chartier590fee92013-09-13 13:46:47 -0700265 AddSpace(large_object_space_);
Mathieu Chartiereb5710e2013-07-25 15:19:42 -0700266
Ian Rogers1d54e732013-05-02 21:10:01 -0700267 // Compute heap capacity. Continuous spaces are sorted in order of Begin().
Mathieu Chartier590fee92013-09-13 13:46:47 -0700268 CHECK(!continuous_spaces_.empty());
Mathieu Chartier938a03b2014-01-16 15:10:31 -0800269
Mathieu Chartier590fee92013-09-13 13:46:47 -0700270 // Relies on the spaces being sorted.
Mathieu Chartier9be9a7a2014-01-24 14:07:33 -0800271 byte* heap_begin = continuous_spaces_.front()->Begin();
272 byte* heap_end = continuous_spaces_.back()->Limit();
Hiroshi Yamauchi5ccd4982014-03-11 12:19:04 -0700273 if (is_zygote) {
274 CHECK(post_zygote_non_moving_space_mem_map_.get() != nullptr);
Mathieu Chartier9be9a7a2014-01-24 14:07:33 -0800275 heap_begin = std::min(post_zygote_non_moving_space_mem_map_->Begin(), heap_begin);
276 heap_end = std::max(post_zygote_non_moving_space_mem_map_->End(), heap_end);
277 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700278 size_t heap_capacity = heap_end - heap_begin;
Carl Shapiro69759ea2011-07-21 18:13:35 -0700279
Elliott Hughes6c9c06d2011-11-07 16:43:47 -0800280 // Allocate the card table.
Ian Rogers1d54e732013-05-02 21:10:01 -0700281 card_table_.reset(accounting::CardTable::Create(heap_begin, heap_capacity));
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700282 CHECK(card_table_.get() != NULL) << "Failed to create card table";
Ian Rogers5d76c432011-10-31 21:42:49 -0700283
Mathieu Chartier590fee92013-09-13 13:46:47 -0700284 // Card cache for now since it makes it easier for us to update the references to the copying
285 // spaces.
Mathieu Chartier11409ae2013-09-23 11:49:36 -0700286 accounting::ModUnionTable* mod_union_table =
Mathieu Chartier590fee92013-09-13 13:46:47 -0700287 new accounting::ModUnionTableCardCache("Image mod-union table", this, GetImageSpace());
Mathieu Chartier11409ae2013-09-23 11:49:36 -0700288 CHECK(mod_union_table != nullptr) << "Failed to create image mod-union table";
289 AddModUnionTable(mod_union_table);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700290
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700291 // TODO: Count objects in the image space here.
Mathieu Chartier1cd9c5c2012-08-23 10:52:44 -0700292 num_bytes_allocated_ = 0;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700293
Mathieu Chartierd22d5482012-11-06 17:14:12 -0800294 // Default mark stack size in bytes.
Mathieu Chartierd8195f12012-10-05 12:21:28 -0700295 static const size_t default_mark_stack_size = 64 * KB;
Ian Rogers1d54e732013-05-02 21:10:01 -0700296 mark_stack_.reset(accounting::ObjectStack::Create("mark stack", default_mark_stack_size));
297 allocation_stack_.reset(accounting::ObjectStack::Create("allocation stack",
298 max_allocation_stack_size_));
299 live_stack_.reset(accounting::ObjectStack::Create("live stack",
300 max_allocation_stack_size_));
Mathieu Chartier5301cd22012-05-31 12:11:36 -0700301
Mathieu Chartier65db8802012-11-20 12:36:46 -0800302 // It's still too early to take a lock because there are no threads yet, but we can create locks
303 // now. We don't create it earlier to make it clear that you can't use locks during heap
304 // initialization.
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700305 gc_complete_lock_ = new Mutex("GC complete lock");
Ian Rogersc604d732012-10-14 16:09:54 -0700306 gc_complete_cond_.reset(new ConditionVariable("GC complete condition variable",
307 *gc_complete_lock_));
Mathieu Chartiera5f9de02014-02-28 16:48:42 -0800308 heap_trim_request_lock_ = new Mutex("Heap trim request lock");
Mathieu Chartier65db8802012-11-20 12:36:46 -0800309 last_gc_size_ = GetBytesAllocated();
310
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700311 if (ignore_max_footprint_) {
312 SetIdealFootprint(std::numeric_limits<size_t>::max());
Mathieu Chartier590fee92013-09-13 13:46:47 -0700313 concurrent_start_bytes_ = std::numeric_limits<size_t>::max();
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700314 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700315 CHECK_NE(max_allowed_footprint_, 0U);
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700316
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800317 // Create our garbage collectors.
Mathieu Chartier50482232013-11-21 11:48:14 -0800318 for (size_t i = 0; i < 2; ++i) {
319 const bool concurrent = i != 0;
320 garbage_collectors_.push_back(new collector::MarkSweep(this, concurrent));
321 garbage_collectors_.push_back(new collector::PartialMarkSweep(this, concurrent));
322 garbage_collectors_.push_back(new collector::StickyMarkSweep(this, concurrent));
323 }
Mathieu Chartier50482232013-11-21 11:48:14 -0800324 if (kMovingCollector) {
325 // TODO: Clean this up.
Hiroshi Yamauchi6f4ffe42014-01-13 12:30:44 -0800326 bool generational = post_zygote_collector_type_ == kCollectorTypeGSS;
327 semi_space_collector_ = new collector::SemiSpace(this, generational);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700328 garbage_collectors_.push_back(semi_space_collector_);
Mathieu Chartier0325e622012-09-05 14:22:51 -0700329 }
330
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -0700331 if (running_on_valgrind_) {
Ian Rogersfa824272013-11-05 16:12:57 -0800332 Runtime::Current()->GetInstrumentation()->InstrumentQuickAllocEntryPoints();
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -0700333 }
334
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800335 if (VLOG_IS_ON(heap) || VLOG_IS_ON(startup)) {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800336 LOG(INFO) << "Heap() exiting";
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700337 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700338}
339
Mathieu Chartier50482232013-11-21 11:48:14 -0800340void Heap::ChangeAllocator(AllocatorType allocator) {
Mathieu Chartier50482232013-11-21 11:48:14 -0800341 if (current_allocator_ != allocator) {
Mathieu Chartierd8891782014-03-02 13:28:37 -0800342 // These two allocators are only used internally and don't have any entrypoints.
343 CHECK_NE(allocator, kAllocatorTypeLOS);
344 CHECK_NE(allocator, kAllocatorTypeNonMoving);
Mathieu Chartier50482232013-11-21 11:48:14 -0800345 current_allocator_ = allocator;
Mathieu Chartierd8891782014-03-02 13:28:37 -0800346 MutexLock mu(nullptr, *Locks::runtime_shutdown_lock_);
Mathieu Chartier50482232013-11-21 11:48:14 -0800347 SetQuickAllocEntryPointsAllocator(current_allocator_);
348 Runtime::Current()->GetInstrumentation()->ResetQuickAllocEntryPoints();
349 }
350}
351
Mathieu Chartier6dda8982014-03-06 11:11:48 -0800352void Heap::DisableCompaction() {
353 if (IsCompactingGC(post_zygote_collector_type_)) {
354 post_zygote_collector_type_ = kCollectorTypeCMS;
355 }
356 if (IsCompactingGC(background_collector_type_)) {
357 background_collector_type_ = post_zygote_collector_type_;
358 }
359 TransitionCollector(post_zygote_collector_type_);
360}
361
Mathieu Chartier15d34022014-02-26 17:16:38 -0800362std::string Heap::SafeGetClassDescriptor(mirror::Class* klass) {
363 if (!IsValidContinuousSpaceObjectAddress(klass)) {
364 return StringPrintf("<non heap address klass %p>", klass);
365 }
366 mirror::Class* component_type = klass->GetComponentType<kVerifyNone>();
367 if (IsValidContinuousSpaceObjectAddress(component_type) && klass->IsArrayClass<kVerifyNone>()) {
368 std::string result("[");
369 result += SafeGetClassDescriptor(component_type);
370 return result;
371 } else if (UNLIKELY(klass->IsPrimitive<kVerifyNone>())) {
372 return Primitive::Descriptor(klass->GetPrimitiveType<kVerifyNone>());
Mathieu Chartierc2f4d022014-03-03 16:11:42 -0800373 } else if (UNLIKELY(klass->IsProxyClass<kVerifyNone>())) {
Mathieu Chartier15d34022014-02-26 17:16:38 -0800374 return Runtime::Current()->GetClassLinker()->GetDescriptorForProxy(klass);
375 } else {
Mathieu Chartierc2f4d022014-03-03 16:11:42 -0800376 mirror::DexCache* dex_cache = klass->GetDexCache<kVerifyNone>();
Mathieu Chartier15d34022014-02-26 17:16:38 -0800377 if (!IsValidContinuousSpaceObjectAddress(dex_cache)) {
378 return StringPrintf("<non heap address dex_cache %p>", dex_cache);
379 }
380 const DexFile* dex_file = dex_cache->GetDexFile();
381 uint16_t class_def_idx = klass->GetDexClassDefIndex();
382 if (class_def_idx == DexFile::kDexNoIndex16) {
383 return "<class def not found>";
384 }
385 const DexFile::ClassDef& class_def = dex_file->GetClassDef(class_def_idx);
386 const DexFile::TypeId& type_id = dex_file->GetTypeId(class_def.class_idx_);
387 return dex_file->GetTypeDescriptor(type_id);
388 }
389}
390
391std::string Heap::SafePrettyTypeOf(mirror::Object* obj) {
392 if (obj == nullptr) {
393 return "null";
394 }
395 mirror::Class* klass = obj->GetClass<kVerifyNone>();
396 if (klass == nullptr) {
397 return "(class=null)";
398 }
399 std::string result(SafeGetClassDescriptor(klass));
400 if (obj->IsClass()) {
Mathieu Chartierc2f4d022014-03-03 16:11:42 -0800401 result += "<" + SafeGetClassDescriptor(obj->AsClass<kVerifyNone>()) + ">";
Mathieu Chartier15d34022014-02-26 17:16:38 -0800402 }
403 return result;
404}
405
406void Heap::DumpObject(std::ostream& stream, mirror::Object* obj) {
407 if (obj == nullptr) {
408 stream << "(obj=null)";
409 return;
410 }
411 if (IsAligned<kObjectAlignment>(obj)) {
412 space::Space* space = nullptr;
413 // Don't use find space since it only finds spaces which actually contain objects instead of
414 // spaces which may contain objects (e.g. cleared bump pointer spaces).
415 for (const auto& cur_space : continuous_spaces_) {
416 if (cur_space->HasAddress(obj)) {
417 space = cur_space;
418 break;
419 }
420 }
421 if (space == nullptr) {
422 if (allocator_mem_map_.get() == nullptr || !allocator_mem_map_->HasAddress(obj)) {
423 stream << "obj " << obj << " not a valid heap address";
424 return;
425 } else if (allocator_mem_map_.get() != nullptr) {
426 allocator_mem_map_->Protect(PROT_READ | PROT_WRITE);
427 }
428 }
429 // Unprotect all the spaces.
430 for (const auto& space : continuous_spaces_) {
431 mprotect(space->Begin(), space->Capacity(), PROT_READ | PROT_WRITE);
432 }
433 stream << "Object " << obj;
434 if (space != nullptr) {
435 stream << " in space " << *space;
436 }
Mathieu Chartierc2f4d022014-03-03 16:11:42 -0800437 mirror::Class* klass = obj->GetClass<kVerifyNone>();
Mathieu Chartier15d34022014-02-26 17:16:38 -0800438 stream << "\nclass=" << klass;
439 if (klass != nullptr) {
440 stream << " type= " << SafePrettyTypeOf(obj);
441 }
442 // Re-protect the address we faulted on.
443 mprotect(AlignDown(obj, kPageSize), kPageSize, PROT_NONE);
444 }
445}
446
Mathieu Chartier590fee92013-09-13 13:46:47 -0700447bool Heap::IsCompilingBoot() const {
448 for (const auto& space : continuous_spaces_) {
Mathieu Chartier4e305412014-02-19 10:54:44 -0800449 if (space->IsImageSpace() || space->IsZygoteSpace()) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700450 return false;
451 }
452 }
453 return true;
454}
455
456bool Heap::HasImageSpace() const {
457 for (const auto& space : continuous_spaces_) {
458 if (space->IsImageSpace()) {
459 return true;
460 }
461 }
462 return false;
463}
464
Mathieu Chartier1d27b342014-01-28 12:51:09 -0800465void Heap::IncrementDisableMovingGC(Thread* self) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700466 // Need to do this holding the lock to prevent races where the GC is about to run / running when
467 // we attempt to disable it.
Mathieu Chartiercaa82d62014-02-02 16:51:17 -0800468 ScopedThreadStateChange tsc(self, kWaitingForGcToComplete);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700469 MutexLock mu(self, *gc_complete_lock_);
Mathieu Chartier1d27b342014-01-28 12:51:09 -0800470 ++disable_moving_gc_count_;
Mathieu Chartierd5a89ee2014-01-31 09:55:13 -0800471 if (IsCompactingGC(collector_type_running_)) {
472 WaitForGcToCompleteLocked(self);
473 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700474}
475
Mathieu Chartier1d27b342014-01-28 12:51:09 -0800476void Heap::DecrementDisableMovingGC(Thread* self) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700477 MutexLock mu(self, *gc_complete_lock_);
Mathieu Chartier1d27b342014-01-28 12:51:09 -0800478 CHECK_GE(disable_moving_gc_count_, 0U);
479 --disable_moving_gc_count_;
Mathieu Chartier590fee92013-09-13 13:46:47 -0700480}
481
Mathieu Chartierca2a24d2013-11-25 15:12:12 -0800482void Heap::UpdateProcessState(ProcessState process_state) {
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800483 if (process_state_ != process_state) {
484 process_state_ = process_state;
485 if (process_state_ == kProcessStateJankPerceptible) {
Mathieu Chartiera5f9de02014-02-28 16:48:42 -0800486 // Transition back to foreground right away to prevent jank.
487 RequestHeapTransition(post_zygote_collector_type_, 0);
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800488 } else {
Mathieu Chartiera5f9de02014-02-28 16:48:42 -0800489 // Don't delay for debug builds since we may want to stress test the GC.
490 RequestHeapTransition(background_collector_type_, kIsDebugBuild ? 0 : kHeapTransitionWait);
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800491 }
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800492 }
Mathieu Chartierca2a24d2013-11-25 15:12:12 -0800493}
494
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700495void Heap::CreateThreadPool() {
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700496 const size_t num_threads = std::max(parallel_gc_threads_, conc_gc_threads_);
497 if (num_threads != 0) {
Mathieu Chartierbcd5e9d2013-11-13 14:33:28 -0800498 thread_pool_.reset(new ThreadPool("Heap thread pool", num_threads));
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700499 }
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700500}
501
Mathieu Chartier83c8ee02014-01-28 14:50:23 -0800502void Heap::VisitObjects(ObjectCallback callback, void* arg) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700503 Thread* self = Thread::Current();
Mathieu Chartier692fafd2013-11-29 17:24:40 -0800504 // GCs can move objects, so don't allow this.
505 const char* old_cause = self->StartAssertNoThreadSuspension("Visiting objects");
Mathieu Chartier590fee92013-09-13 13:46:47 -0700506 if (bump_pointer_space_ != nullptr) {
Mathieu Chartier692fafd2013-11-29 17:24:40 -0800507 // Visit objects in bump pointer space.
508 bump_pointer_space_->Walk(callback, arg);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700509 }
510 // TODO: Switch to standard begin and end to use ranged a based loop.
511 for (mirror::Object** it = allocation_stack_->Begin(), **end = allocation_stack_->End();
512 it < end; ++it) {
513 mirror::Object* obj = *it;
Mathieu Chartierebdf3f32014-02-13 10:23:27 -0800514 if (obj != nullptr && obj->GetClass() != nullptr) {
515 // Avoid the race condition caused by the object not yet being written into the allocation
Hiroshi Yamauchif5b0e202014-02-11 17:02:22 -0800516 // stack or the class not yet being written in the object. Or, if kUseThreadLocalAllocationStack,
517 // there can be nulls on the allocation stack.
Mathieu Chartierebdf3f32014-02-13 10:23:27 -0800518 callback(obj, arg);
519 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700520 }
521 GetLiveBitmap()->Walk(callback, arg);
Mathieu Chartier692fafd2013-11-29 17:24:40 -0800522 self->EndAssertNoThreadSuspension(old_cause);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700523}
524
525void Heap::MarkAllocStackAsLive(accounting::ObjectStack* stack) {
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800526 space::ContinuousSpace* space1 = rosalloc_space_ != nullptr ? rosalloc_space_ : non_moving_space_;
527 space::ContinuousSpace* space2 = dlmalloc_space_ != nullptr ? dlmalloc_space_ : non_moving_space_;
528 // This is just logic to handle a case of either not having a rosalloc or dlmalloc space.
529 // TODO: Generalize this to n bitmaps?
530 if (space1 == nullptr) {
531 DCHECK(space2 != nullptr);
532 space1 = space2;
533 }
534 if (space2 == nullptr) {
535 DCHECK(space1 != nullptr);
536 space2 = space1;
537 }
538 MarkAllocStack(space1->GetLiveBitmap(), space2->GetLiveBitmap(),
539 large_object_space_->GetLiveObjects(), stack);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700540}
541
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700542void Heap::DeleteThreadPool() {
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700543 thread_pool_.reset(nullptr);
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700544}
545
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800546void Heap::AddSpace(space::Space* space, bool set_as_default) {
547 DCHECK(space != nullptr);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700548 WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
549 if (space->IsContinuousSpace()) {
550 DCHECK(!space->IsDiscontinuousSpace());
551 space::ContinuousSpace* continuous_space = space->AsContinuousSpace();
552 // Continuous spaces don't necessarily have bitmaps.
553 accounting::SpaceBitmap* live_bitmap = continuous_space->GetLiveBitmap();
554 accounting::SpaceBitmap* mark_bitmap = continuous_space->GetMarkBitmap();
555 if (live_bitmap != nullptr) {
556 DCHECK(mark_bitmap != nullptr);
557 live_bitmap_->AddContinuousSpaceBitmap(live_bitmap);
558 mark_bitmap_->AddContinuousSpaceBitmap(mark_bitmap);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700559 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700560 continuous_spaces_.push_back(continuous_space);
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800561 if (set_as_default) {
562 if (continuous_space->IsDlMallocSpace()) {
563 dlmalloc_space_ = continuous_space->AsDlMallocSpace();
564 } else if (continuous_space->IsRosAllocSpace()) {
565 rosalloc_space_ = continuous_space->AsRosAllocSpace();
566 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700567 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700568 // Ensure that spaces remain sorted in increasing order of start address.
569 std::sort(continuous_spaces_.begin(), continuous_spaces_.end(),
570 [](const space::ContinuousSpace* a, const space::ContinuousSpace* b) {
571 return a->Begin() < b->Begin();
572 });
Mathieu Chartier590fee92013-09-13 13:46:47 -0700573 } else {
574 DCHECK(space->IsDiscontinuousSpace());
575 space::DiscontinuousSpace* discontinuous_space = space->AsDiscontinuousSpace();
576 DCHECK(discontinuous_space->GetLiveObjects() != nullptr);
577 live_bitmap_->AddDiscontinuousObjectSet(discontinuous_space->GetLiveObjects());
578 DCHECK(discontinuous_space->GetMarkObjects() != nullptr);
579 mark_bitmap_->AddDiscontinuousObjectSet(discontinuous_space->GetMarkObjects());
580 discontinuous_spaces_.push_back(discontinuous_space);
581 }
582 if (space->IsAllocSpace()) {
583 alloc_spaces_.push_back(space->AsAllocSpace());
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700584 }
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800585}
586
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800587void Heap::RemoveSpace(space::Space* space) {
588 DCHECK(space != nullptr);
589 WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
590 if (space->IsContinuousSpace()) {
591 DCHECK(!space->IsDiscontinuousSpace());
592 space::ContinuousSpace* continuous_space = space->AsContinuousSpace();
593 // Continuous spaces don't necessarily have bitmaps.
594 accounting::SpaceBitmap* live_bitmap = continuous_space->GetLiveBitmap();
595 accounting::SpaceBitmap* mark_bitmap = continuous_space->GetMarkBitmap();
596 if (live_bitmap != nullptr) {
597 DCHECK(mark_bitmap != nullptr);
598 live_bitmap_->RemoveContinuousSpaceBitmap(live_bitmap);
599 mark_bitmap_->RemoveContinuousSpaceBitmap(mark_bitmap);
600 }
601 auto it = std::find(continuous_spaces_.begin(), continuous_spaces_.end(), continuous_space);
602 DCHECK(it != continuous_spaces_.end());
603 continuous_spaces_.erase(it);
604 if (continuous_space == dlmalloc_space_) {
605 dlmalloc_space_ = nullptr;
606 } else if (continuous_space == rosalloc_space_) {
607 rosalloc_space_ = nullptr;
608 }
Mathieu Chartierfc5b5282014-01-09 16:15:36 -0800609 if (continuous_space == main_space_) {
610 main_space_ = nullptr;
611 }
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800612 } else {
613 DCHECK(space->IsDiscontinuousSpace());
614 space::DiscontinuousSpace* discontinuous_space = space->AsDiscontinuousSpace();
615 DCHECK(discontinuous_space->GetLiveObjects() != nullptr);
616 live_bitmap_->RemoveDiscontinuousObjectSet(discontinuous_space->GetLiveObjects());
617 DCHECK(discontinuous_space->GetMarkObjects() != nullptr);
618 mark_bitmap_->RemoveDiscontinuousObjectSet(discontinuous_space->GetMarkObjects());
619 auto it = std::find(discontinuous_spaces_.begin(), discontinuous_spaces_.end(),
620 discontinuous_space);
621 DCHECK(it != discontinuous_spaces_.end());
622 discontinuous_spaces_.erase(it);
623 }
624 if (space->IsAllocSpace()) {
625 auto it = std::find(alloc_spaces_.begin(), alloc_spaces_.end(), space->AsAllocSpace());
626 DCHECK(it != alloc_spaces_.end());
627 alloc_spaces_.erase(it);
628 }
629}
630
Mathieu Chartier0a9dc052013-07-25 11:01:28 -0700631void Heap::RegisterGCAllocation(size_t bytes) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700632 if (this != nullptr) {
Ian Rogersb122a4b2013-11-19 18:00:50 -0800633 gc_memory_overhead_.FetchAndAdd(bytes);
Mathieu Chartier0a9dc052013-07-25 11:01:28 -0700634 }
635}
636
637void Heap::RegisterGCDeAllocation(size_t bytes) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700638 if (this != nullptr) {
Ian Rogersb122a4b2013-11-19 18:00:50 -0800639 gc_memory_overhead_.FetchAndSub(bytes);
Mathieu Chartier0a9dc052013-07-25 11:01:28 -0700640 }
641}
642
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700643void Heap::DumpGcPerformanceInfo(std::ostream& os) {
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700644 // Dump cumulative timings.
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700645 os << "Dumping cumulative Gc timings\n";
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700646 uint64_t total_duration = 0;
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800647
648 // Dump cumulative loggers for each GC type.
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800649 uint64_t total_paused_time = 0;
Mathieu Chartier590fee92013-09-13 13:46:47 -0700650 for (const auto& collector : garbage_collectors_) {
Sameer Abu Asala8439542013-02-14 16:06:42 -0800651 CumulativeLogger& logger = collector->GetCumulativeTimings();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800652 if (logger.GetTotalNs() != 0) {
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700653 os << Dumpable<CumulativeLogger>(logger);
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800654 const uint64_t total_ns = logger.GetTotalNs();
Mathieu Chartier02e25112013-08-14 16:14:24 -0700655 const uint64_t total_pause_ns = collector->GetTotalPausedTimeNs();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800656 double seconds = NsToMs(logger.GetTotalNs()) / 1000.0;
657 const uint64_t freed_bytes = collector->GetTotalFreedBytes();
658 const uint64_t freed_objects = collector->GetTotalFreedObjects();
Mathieu Chartierb2f99362013-11-20 17:26:00 -0800659 Histogram<uint64_t>::CumulativeData cumulative_data;
660 collector->GetPauseHistogram().CreateHistogram(&cumulative_data);
661 collector->GetPauseHistogram().PrintConfidenceIntervals(os, 0.99, cumulative_data);
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700662 os << collector->GetName() << " total time: " << PrettyDuration(total_ns) << "\n"
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700663 << collector->GetName() << " freed: " << freed_objects
664 << " objects with total size " << PrettySize(freed_bytes) << "\n"
665 << collector->GetName() << " throughput: " << freed_objects / seconds << "/s / "
666 << PrettySize(freed_bytes / seconds) << "/s\n";
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800667 total_duration += total_ns;
668 total_paused_time += total_pause_ns;
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700669 }
670 }
671 uint64_t allocation_time = static_cast<uint64_t>(total_allocation_time_) * kTimeAdjust;
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700672 if (total_duration != 0) {
Brian Carlstrom2d888622013-07-18 17:02:00 -0700673 const double total_seconds = static_cast<double>(total_duration / 1000) / 1000000.0;
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700674 os << "Total time spent in GC: " << PrettyDuration(total_duration) << "\n";
675 os << "Mean GC size throughput: "
Ian Rogers1d54e732013-05-02 21:10:01 -0700676 << PrettySize(GetBytesFreedEver() / total_seconds) << "/s\n";
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700677 os << "Mean GC object throughput: "
Ian Rogers1d54e732013-05-02 21:10:01 -0700678 << (GetObjectsFreedEver() / total_seconds) << " objects/s\n";
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700679 }
Mathieu Chartier692fafd2013-11-29 17:24:40 -0800680 size_t total_objects_allocated = GetObjectsAllocatedEver();
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700681 os << "Total number of allocations: " << total_objects_allocated << "\n";
Mathieu Chartier692fafd2013-11-29 17:24:40 -0800682 size_t total_bytes_allocated = GetBytesAllocatedEver();
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700683 os << "Total bytes allocated " << PrettySize(total_bytes_allocated) << "\n";
Hiroshi Yamauchi50b29282013-07-30 13:58:37 -0700684 if (kMeasureAllocationTime) {
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700685 os << "Total time spent allocating: " << PrettyDuration(allocation_time) << "\n";
686 os << "Mean allocation time: " << PrettyDuration(allocation_time / total_objects_allocated)
687 << "\n";
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700688 }
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700689 os << "Total mutator paused time: " << PrettyDuration(total_paused_time) << "\n";
690 os << "Total time waiting for GC to complete: " << PrettyDuration(total_wait_time_) << "\n";
Mathieu Chartier0a9dc052013-07-25 11:01:28 -0700691 os << "Approximate GC data structures memory overhead: " << gc_memory_overhead_;
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700692}
693
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800694Heap::~Heap() {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700695 VLOG(heap) << "Starting ~Heap()";
Mathieu Chartier590fee92013-09-13 13:46:47 -0700696 STLDeleteElements(&garbage_collectors_);
697 // If we don't reset then the mark stack complains in its destructor.
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700698 allocation_stack_->Reset();
699 live_stack_->Reset();
Mathieu Chartier11409ae2013-09-23 11:49:36 -0700700 STLDeleteValues(&mod_union_tables_);
Ian Rogers1d54e732013-05-02 21:10:01 -0700701 STLDeleteElements(&continuous_spaces_);
702 STLDeleteElements(&discontinuous_spaces_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700703 delete gc_complete_lock_;
Mathieu Chartier590fee92013-09-13 13:46:47 -0700704 VLOG(heap) << "Finished ~Heap()";
Carl Shapiro69759ea2011-07-21 18:13:35 -0700705}
706
Ian Rogers1d54e732013-05-02 21:10:01 -0700707space::ContinuousSpace* Heap::FindContinuousSpaceFromObject(const mirror::Object* obj,
708 bool fail_ok) const {
Mathieu Chartier02e25112013-08-14 16:14:24 -0700709 for (const auto& space : continuous_spaces_) {
710 if (space->Contains(obj)) {
711 return space;
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700712 }
713 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700714 if (!fail_ok) {
715 LOG(FATAL) << "object " << reinterpret_cast<const void*>(obj) << " not inside any spaces!";
716 }
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700717 return NULL;
718}
719
Ian Rogers1d54e732013-05-02 21:10:01 -0700720space::DiscontinuousSpace* Heap::FindDiscontinuousSpaceFromObject(const mirror::Object* obj,
721 bool fail_ok) const {
Mathieu Chartier02e25112013-08-14 16:14:24 -0700722 for (const auto& space : discontinuous_spaces_) {
723 if (space->Contains(obj)) {
724 return space;
Ian Rogers1d54e732013-05-02 21:10:01 -0700725 }
726 }
727 if (!fail_ok) {
728 LOG(FATAL) << "object " << reinterpret_cast<const void*>(obj) << " not inside any spaces!";
729 }
730 return NULL;
731}
732
733space::Space* Heap::FindSpaceFromObject(const mirror::Object* obj, bool fail_ok) const {
734 space::Space* result = FindContinuousSpaceFromObject(obj, true);
735 if (result != NULL) {
736 return result;
737 }
738 return FindDiscontinuousSpaceFromObject(obj, true);
739}
740
Mathieu Chartier39e32612013-11-12 16:28:05 -0800741struct SoftReferenceArgs {
Mathieu Chartier83c8ee02014-01-28 14:50:23 -0800742 IsMarkedCallback* is_marked_callback_;
Mathieu Chartier3bb57c72014-02-18 11:38:45 -0800743 MarkObjectCallback* mark_callback_;
Mathieu Chartier39e32612013-11-12 16:28:05 -0800744 void* arg_;
745};
746
747mirror::Object* Heap::PreserveSoftReferenceCallback(mirror::Object* obj, void* arg) {
Mathieu Chartiera1602f22014-01-13 17:19:19 -0800748 SoftReferenceArgs* args = reinterpret_cast<SoftReferenceArgs*>(arg);
Mathieu Chartier39e32612013-11-12 16:28:05 -0800749 // TODO: Not preserve all soft references.
Mathieu Chartier3bb57c72014-02-18 11:38:45 -0800750 return args->mark_callback_(obj, args->arg_);
Mathieu Chartier39e32612013-11-12 16:28:05 -0800751}
752
753// Process reference class instances and schedule finalizations.
754void Heap::ProcessReferences(TimingLogger& timings, bool clear_soft,
Mathieu Chartier83c8ee02014-01-28 14:50:23 -0800755 IsMarkedCallback* is_marked_callback,
Mathieu Chartier3bb57c72014-02-18 11:38:45 -0800756 MarkObjectCallback* mark_object_callback,
757 ProcessMarkStackCallback* process_mark_stack_callback, void* arg) {
Mathieu Chartier39e32612013-11-12 16:28:05 -0800758 // Unless we are in the zygote or required to clear soft references with white references,
759 // preserve some white referents.
760 if (!clear_soft && !Runtime::Current()->IsZygote()) {
761 SoftReferenceArgs soft_reference_args;
762 soft_reference_args.is_marked_callback_ = is_marked_callback;
Mathieu Chartier3bb57c72014-02-18 11:38:45 -0800763 soft_reference_args.mark_callback_ = mark_object_callback;
Mathieu Chartier39e32612013-11-12 16:28:05 -0800764 soft_reference_args.arg_ = arg;
765 soft_reference_queue_.PreserveSomeSoftReferences(&PreserveSoftReferenceCallback,
766 &soft_reference_args);
Mathieu Chartier3bb57c72014-02-18 11:38:45 -0800767 process_mark_stack_callback(arg);
Mathieu Chartier39e32612013-11-12 16:28:05 -0800768 }
Mathieu Chartier3bb57c72014-02-18 11:38:45 -0800769 timings.StartSplit("(Paused)ProcessReferences");
Mathieu Chartier39e32612013-11-12 16:28:05 -0800770 // Clear all remaining soft and weak references with white referents.
771 soft_reference_queue_.ClearWhiteReferences(cleared_references_, is_marked_callback, arg);
772 weak_reference_queue_.ClearWhiteReferences(cleared_references_, is_marked_callback, arg);
773 timings.EndSplit();
774 // Preserve all white objects with finalize methods and schedule them for finalization.
Mathieu Chartier3bb57c72014-02-18 11:38:45 -0800775 timings.StartSplit("(Paused)EnqueueFinalizerReferences");
Mathieu Chartier39e32612013-11-12 16:28:05 -0800776 finalizer_reference_queue_.EnqueueFinalizerReferences(cleared_references_, is_marked_callback,
Mathieu Chartier3bb57c72014-02-18 11:38:45 -0800777 mark_object_callback, arg);
778 process_mark_stack_callback(arg);
Mathieu Chartier39e32612013-11-12 16:28:05 -0800779 timings.EndSplit();
Mathieu Chartier3bb57c72014-02-18 11:38:45 -0800780 timings.StartSplit("(Paused)ProcessReferences");
Mathieu Chartier39e32612013-11-12 16:28:05 -0800781 // Clear all f-reachable soft and weak references with white referents.
782 soft_reference_queue_.ClearWhiteReferences(cleared_references_, is_marked_callback, arg);
783 weak_reference_queue_.ClearWhiteReferences(cleared_references_, is_marked_callback, arg);
784 // Clear all phantom references with white referents.
785 phantom_reference_queue_.ClearWhiteReferences(cleared_references_, is_marked_callback, arg);
786 // At this point all reference queues other than the cleared references should be empty.
787 DCHECK(soft_reference_queue_.IsEmpty());
788 DCHECK(weak_reference_queue_.IsEmpty());
789 DCHECK(finalizer_reference_queue_.IsEmpty());
790 DCHECK(phantom_reference_queue_.IsEmpty());
791 timings.EndSplit();
792}
793
794bool Heap::IsEnqueued(mirror::Object* ref) const {
795 // Since the references are stored as cyclic lists it means that once enqueued, the pending next
796 // will always be non-null.
Ian Rogersef7d42f2014-01-06 12:55:46 -0800797 return ref->GetFieldObject<mirror::Object>(GetReferencePendingNextOffset(), false) != nullptr;
Mathieu Chartier39e32612013-11-12 16:28:05 -0800798}
799
Ian Rogersef7d42f2014-01-06 12:55:46 -0800800bool Heap::IsEnqueuable(mirror::Object* ref) const {
Mathieu Chartier39e32612013-11-12 16:28:05 -0800801 DCHECK(ref != nullptr);
802 const mirror::Object* queue =
Ian Rogersef7d42f2014-01-06 12:55:46 -0800803 ref->GetFieldObject<mirror::Object>(GetReferenceQueueOffset(), false);
Mathieu Chartier39e32612013-11-12 16:28:05 -0800804 const mirror::Object* queue_next =
Ian Rogersef7d42f2014-01-06 12:55:46 -0800805 ref->GetFieldObject<mirror::Object>(GetReferenceQueueNextOffset(), false);
Mathieu Chartier39e32612013-11-12 16:28:05 -0800806 return queue != nullptr && queue_next == nullptr;
807}
808
809// Process the "referent" field in a java.lang.ref.Reference. If the referent has not yet been
810// marked, put it on the appropriate list in the heap for later processing.
811void Heap::DelayReferenceReferent(mirror::Class* klass, mirror::Object* obj,
Mathieu Chartier83c8ee02014-01-28 14:50:23 -0800812 IsMarkedCallback is_marked_callback, void* arg) {
Mathieu Chartier39e32612013-11-12 16:28:05 -0800813 DCHECK(klass != nullptr);
814 DCHECK(klass->IsReferenceClass());
815 DCHECK(obj != nullptr);
816 mirror::Object* referent = GetReferenceReferent(obj);
817 if (referent != nullptr) {
Mathieu Chartier83c8ee02014-01-28 14:50:23 -0800818 mirror::Object* forward_address = is_marked_callback(referent, arg);
Mathieu Chartier39e32612013-11-12 16:28:05 -0800819 // Null means that the object is not currently marked.
820 if (forward_address == nullptr) {
821 Thread* self = Thread::Current();
822 // TODO: Remove these locks, and use atomic stacks for storing references?
823 // We need to check that the references haven't already been enqueued since we can end up
824 // scanning the same reference multiple times due to dirty cards.
825 if (klass->IsSoftReferenceClass()) {
826 soft_reference_queue_.AtomicEnqueueIfNotEnqueued(self, obj);
827 } else if (klass->IsWeakReferenceClass()) {
828 weak_reference_queue_.AtomicEnqueueIfNotEnqueued(self, obj);
829 } else if (klass->IsFinalizerReferenceClass()) {
830 finalizer_reference_queue_.AtomicEnqueueIfNotEnqueued(self, obj);
831 } else if (klass->IsPhantomReferenceClass()) {
832 phantom_reference_queue_.AtomicEnqueueIfNotEnqueued(self, obj);
833 } else {
834 LOG(FATAL) << "Invalid reference type " << PrettyClass(klass) << " " << std::hex
835 << klass->GetAccessFlags();
836 }
837 } else if (referent != forward_address) {
838 // Referent is already marked and we need to update it.
839 SetReferenceReferent(obj, forward_address);
840 }
841 }
842}
843
Ian Rogers1d54e732013-05-02 21:10:01 -0700844space::ImageSpace* Heap::GetImageSpace() const {
Mathieu Chartier02e25112013-08-14 16:14:24 -0700845 for (const auto& space : continuous_spaces_) {
846 if (space->IsImageSpace()) {
847 return space->AsImageSpace();
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700848 }
849 }
850 return NULL;
851}
852
Elliott Hughes8a8b9cb2012-04-13 18:29:22 -0700853static void MSpaceChunkCallback(void* start, void* end, size_t used_bytes, void* arg) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700854 size_t chunk_size = reinterpret_cast<uint8_t*>(end) - reinterpret_cast<uint8_t*>(start);
Elliott Hughes8a8b9cb2012-04-13 18:29:22 -0700855 if (used_bytes < chunk_size) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700856 size_t chunk_free_bytes = chunk_size - used_bytes;
857 size_t& max_contiguous_allocation = *reinterpret_cast<size_t*>(arg);
858 max_contiguous_allocation = std::max(max_contiguous_allocation, chunk_free_bytes);
Elliott Hughes8a8b9cb2012-04-13 18:29:22 -0700859 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700860}
861
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -0700862void Heap::ThrowOutOfMemoryError(Thread* self, size_t byte_count, bool large_object_allocation) {
863 std::ostringstream oss;
Ian Rogersef7d42f2014-01-06 12:55:46 -0800864 size_t total_bytes_free = GetFreeMemory();
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -0700865 oss << "Failed to allocate a " << byte_count << " byte allocation with " << total_bytes_free
866 << " free bytes";
867 // If the allocation failed due to fragmentation, print out the largest continuous allocation.
868 if (!large_object_allocation && total_bytes_free >= byte_count) {
869 size_t max_contiguous_allocation = 0;
870 for (const auto& space : continuous_spaces_) {
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -0700871 if (space->IsMallocSpace()) {
872 // To allow the Walk/InspectAll() to exclusively-lock the mutator
873 // lock, temporarily release the shared access to the mutator
874 // lock here by transitioning to the suspended state.
875 Locks::mutator_lock_->AssertSharedHeld(self);
876 self->TransitionFromRunnableToSuspended(kSuspended);
877 space->AsMallocSpace()->Walk(MSpaceChunkCallback, &max_contiguous_allocation);
878 self->TransitionFromSuspendedToRunnable();
879 Locks::mutator_lock_->AssertSharedHeld(self);
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -0700880 }
881 }
882 oss << "; failed due to fragmentation (largest possible contiguous allocation "
883 << max_contiguous_allocation << " bytes)";
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700884 }
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -0700885 self->ThrowOutOfMemoryError(oss.str().c_str());
886}
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700887
Mathieu Chartiera5f9de02014-02-28 16:48:42 -0800888void Heap::DoPendingTransitionOrTrim() {
889 Thread* self = Thread::Current();
890 CollectorType desired_collector_type;
891 // Wait until we reach the desired transition time.
892 while (true) {
893 uint64_t wait_time;
894 {
895 MutexLock mu(self, *heap_trim_request_lock_);
896 desired_collector_type = desired_collector_type_;
897 uint64_t current_time = NanoTime();
898 if (current_time >= heap_transition_target_time_) {
899 break;
900 }
901 wait_time = heap_transition_target_time_ - current_time;
902 }
903 ScopedThreadStateChange tsc(self, kSleeping);
904 usleep(wait_time / 1000); // Usleep takes microseconds.
905 }
906 // Transition the heap if the desired collector type is nto the same as the current collector type.
907 TransitionCollector(desired_collector_type);
908 // Do a heap trim if it is needed.
909 Trim();
910}
911
Mathieu Chartier590fee92013-09-13 13:46:47 -0700912void Heap::Trim() {
Mathieu Chartierd5a89ee2014-01-31 09:55:13 -0800913 Thread* self = Thread::Current();
914 {
Mathieu Chartiera5f9de02014-02-28 16:48:42 -0800915 MutexLock mu(self, *heap_trim_request_lock_);
916 if (!heap_trim_request_pending_ || NanoTime() < heap_trim_target_time_) {
917 return;
918 }
919 heap_trim_request_pending_ = false;
920 }
921 {
Mathieu Chartiercaa82d62014-02-02 16:51:17 -0800922 // Need to do this before acquiring the locks since we don't want to get suspended while
923 // holding any locks.
924 ScopedThreadStateChange tsc(self, kWaitingForGcToComplete);
Mathieu Chartierd5a89ee2014-01-31 09:55:13 -0800925 // Pretend we are doing a GC to prevent background compaction from deleting the space we are
926 // trimming.
927 MutexLock mu(self, *gc_complete_lock_);
928 // Ensure there is only one GC at a time.
929 WaitForGcToCompleteLocked(self);
930 collector_type_running_ = kCollectorTypeHeapTrim;
931 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700932 uint64_t start_ns = NanoTime();
933 // Trim the managed spaces.
934 uint64_t total_alloc_space_allocated = 0;
935 uint64_t total_alloc_space_size = 0;
936 uint64_t managed_reclaimed = 0;
937 for (const auto& space : continuous_spaces_) {
Mathieu Chartiera1602f22014-01-13 17:19:19 -0800938 if (space->IsMallocSpace()) {
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -0700939 gc::space::MallocSpace* alloc_space = space->AsMallocSpace();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700940 total_alloc_space_size += alloc_space->Size();
941 managed_reclaimed += alloc_space->Trim();
942 }
943 }
944 total_alloc_space_allocated = GetBytesAllocated() - large_object_space_->GetBytesAllocated() -
Mathieu Chartier692fafd2013-11-29 17:24:40 -0800945 bump_pointer_space_->Size();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700946 const float managed_utilization = static_cast<float>(total_alloc_space_allocated) /
947 static_cast<float>(total_alloc_space_size);
948 uint64_t gc_heap_end_ns = NanoTime();
Mathieu Chartierd5a89ee2014-01-31 09:55:13 -0800949 // We never move things in the native heap, so we can finish the GC at this point.
950 FinishGC(self, collector::kGcTypeNone);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700951 // Trim the native heap.
952 dlmalloc_trim(0);
953 size_t native_reclaimed = 0;
954 dlmalloc_inspect_all(DlmallocMadviseCallback, &native_reclaimed);
955 uint64_t end_ns = NanoTime();
956 VLOG(heap) << "Heap trim of managed (duration=" << PrettyDuration(gc_heap_end_ns - start_ns)
957 << ", advised=" << PrettySize(managed_reclaimed) << ") and native (duration="
958 << PrettyDuration(end_ns - gc_heap_end_ns) << ", advised=" << PrettySize(native_reclaimed)
959 << ") heaps. Managed heap utilization of " << static_cast<int>(100 * managed_utilization)
960 << "%.";
961}
962
963bool Heap::IsValidObjectAddress(const mirror::Object* obj) const {
964 // Note: we deliberately don't take the lock here, and mustn't test anything that would require
965 // taking the lock.
966 if (obj == nullptr) {
Elliott Hughes88c5c352012-03-15 18:49:48 -0700967 return true;
968 }
Mathieu Chartier15d34022014-02-26 17:16:38 -0800969 return IsAligned<kObjectAlignment>(obj) && FindSpaceFromObject(obj, true) != nullptr;
Mathieu Chartier590fee92013-09-13 13:46:47 -0700970}
971
Mathieu Chartierd68ac702014-02-11 14:50:51 -0800972bool Heap::IsNonDiscontinuousSpaceHeapAddress(const mirror::Object* obj) const {
973 return FindContinuousSpaceFromObject(obj, true) != nullptr;
974}
975
Mathieu Chartier15d34022014-02-26 17:16:38 -0800976bool Heap::IsValidContinuousSpaceObjectAddress(const mirror::Object* obj) const {
977 if (obj == nullptr || !IsAligned<kObjectAlignment>(obj)) {
978 return false;
979 }
980 for (const auto& space : continuous_spaces_) {
981 if (space->HasAddress(obj)) {
982 return true;
983 }
984 }
985 return false;
Elliott Hughesa2501992011-08-26 19:39:54 -0700986}
987
Ian Rogersef7d42f2014-01-06 12:55:46 -0800988bool Heap::IsLiveObjectLocked(mirror::Object* obj, bool search_allocation_stack,
Mathieu Chartier0f72e412013-09-06 16:40:01 -0700989 bool search_live_stack, bool sorted) {
Mathieu Chartier938a03b2014-01-16 15:10:31 -0800990 if (UNLIKELY(!IsAligned<kObjectAlignment>(obj))) {
991 return false;
992 }
993 if (bump_pointer_space_ != nullptr && bump_pointer_space_->HasAddress(obj)) {
Mathieu Chartier4e305412014-02-19 10:54:44 -0800994 mirror::Class* klass = obj->GetClass<kVerifyNone>();
Mathieu Chartier938a03b2014-01-16 15:10:31 -0800995 if (obj == klass) {
Mathieu Chartier9be9a7a2014-01-24 14:07:33 -0800996 // This case happens for java.lang.Class.
Mathieu Chartier938a03b2014-01-16 15:10:31 -0800997 return true;
998 }
999 return VerifyClassClass(klass) && IsLiveObjectLocked(klass);
1000 } else if (temp_space_ != nullptr && temp_space_->HasAddress(obj)) {
Mathieu Chartier4e305412014-02-19 10:54:44 -08001001 // If we are in the allocated region of the temp space, then we are probably live (e.g. during
1002 // a GC). When a GC isn't running End() - Begin() is 0 which means no objects are contained.
1003 return temp_space_->Contains(obj);
Ian Rogers1d54e732013-05-02 21:10:01 -07001004 }
Mathieu Chartierf082d3c2013-07-29 17:04:07 -07001005 space::ContinuousSpace* c_space = FindContinuousSpaceFromObject(obj, true);
1006 space::DiscontinuousSpace* d_space = NULL;
Mathieu Chartier938a03b2014-01-16 15:10:31 -08001007 if (c_space != nullptr) {
Mathieu Chartierf082d3c2013-07-29 17:04:07 -07001008 if (c_space->GetLiveBitmap()->Test(obj)) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001009 return true;
1010 }
1011 } else {
Mathieu Chartierf082d3c2013-07-29 17:04:07 -07001012 d_space = FindDiscontinuousSpaceFromObject(obj, true);
Mathieu Chartier938a03b2014-01-16 15:10:31 -08001013 if (d_space != nullptr) {
Mathieu Chartierf082d3c2013-07-29 17:04:07 -07001014 if (d_space->GetLiveObjects()->Test(obj)) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001015 return true;
1016 }
1017 }
1018 }
Mathieu Chartierf082d3c2013-07-29 17:04:07 -07001019 // This is covering the allocation/live stack swapping that is done without mutators suspended.
Mathieu Chartier0f72e412013-09-06 16:40:01 -07001020 for (size_t i = 0; i < (sorted ? 1 : 5); ++i) {
1021 if (i > 0) {
1022 NanoSleep(MsToNs(10));
Ian Rogers1d54e732013-05-02 21:10:01 -07001023 }
Mathieu Chartier0f72e412013-09-06 16:40:01 -07001024 if (search_allocation_stack) {
1025 if (sorted) {
1026 if (allocation_stack_->ContainsSorted(const_cast<mirror::Object*>(obj))) {
1027 return true;
1028 }
1029 } else if (allocation_stack_->Contains(const_cast<mirror::Object*>(obj))) {
1030 return true;
1031 }
1032 }
1033
1034 if (search_live_stack) {
1035 if (sorted) {
1036 if (live_stack_->ContainsSorted(const_cast<mirror::Object*>(obj))) {
1037 return true;
1038 }
1039 } else if (live_stack_->Contains(const_cast<mirror::Object*>(obj))) {
1040 return true;
1041 }
1042 }
Ian Rogers1d54e732013-05-02 21:10:01 -07001043 }
Mathieu Chartierf082d3c2013-07-29 17:04:07 -07001044 // We need to check the bitmaps again since there is a race where we mark something as live and
1045 // then clear the stack containing it.
Mathieu Chartier938a03b2014-01-16 15:10:31 -08001046 if (c_space != nullptr) {
Mathieu Chartierf082d3c2013-07-29 17:04:07 -07001047 if (c_space->GetLiveBitmap()->Test(obj)) {
1048 return true;
1049 }
1050 } else {
1051 d_space = FindDiscontinuousSpaceFromObject(obj, true);
Mathieu Chartier938a03b2014-01-16 15:10:31 -08001052 if (d_space != nullptr && d_space->GetLiveObjects()->Test(obj)) {
Mathieu Chartierf082d3c2013-07-29 17:04:07 -07001053 return true;
1054 }
1055 }
Ian Rogers1d54e732013-05-02 21:10:01 -07001056 return false;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001057}
1058
Mathieu Chartier590fee92013-09-13 13:46:47 -07001059void Heap::DumpSpaces(std::ostream& stream) {
Mathieu Chartier02e25112013-08-14 16:14:24 -07001060 for (const auto& space : continuous_spaces_) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001061 accounting::SpaceBitmap* live_bitmap = space->GetLiveBitmap();
1062 accounting::SpaceBitmap* mark_bitmap = space->GetMarkBitmap();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001063 stream << space << " " << *space << "\n";
1064 if (live_bitmap != nullptr) {
1065 stream << live_bitmap << " " << *live_bitmap << "\n";
1066 }
1067 if (mark_bitmap != nullptr) {
1068 stream << mark_bitmap << " " << *mark_bitmap << "\n";
1069 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001070 }
Mathieu Chartier02e25112013-08-14 16:14:24 -07001071 for (const auto& space : discontinuous_spaces_) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001072 stream << space << " " << *space << "\n";
Mathieu Chartier128c52c2012-10-16 14:12:41 -07001073 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001074}
1075
Ian Rogersef7d42f2014-01-06 12:55:46 -08001076void Heap::VerifyObjectBody(mirror::Object* obj) {
Mathieu Chartier4e305412014-02-19 10:54:44 -08001077 if (this == nullptr && verify_object_mode_ == kVerifyObjectModeDisabled) {
1078 return;
1079 }
Mathieu Chartier0f72e412013-09-06 16:40:01 -07001080 // Ignore early dawn of the universe verifications.
Ian Rogersb122a4b2013-11-19 18:00:50 -08001081 if (UNLIKELY(static_cast<size_t>(num_bytes_allocated_.Load()) < 10 * KB)) {
Ian Rogers62d6c772013-02-27 08:32:07 -08001082 return;
1083 }
Mathieu Chartier4e305412014-02-19 10:54:44 -08001084 CHECK(IsAligned<kObjectAlignment>(obj)) << "Object isn't aligned: " << obj;
1085 mirror::Class* c = obj->GetFieldObject<mirror::Class, kVerifyNone>(
1086 mirror::Object::ClassOffset(), false);
1087 CHECK(c != nullptr) << "Null class in object " << obj;
1088 CHECK(IsAligned<kObjectAlignment>(c)) << "Class " << c << " not aligned in object " << obj;
Mathieu Chartier938a03b2014-01-16 15:10:31 -08001089 CHECK(VerifyClassClass(c));
Mathieu Chartier0325e622012-09-05 14:22:51 -07001090
Mathieu Chartier4e305412014-02-19 10:54:44 -08001091 if (verify_object_mode_ > kVerifyObjectModeFast) {
1092 // Note: the bitmap tests below are racy since we don't hold the heap bitmap lock.
Ian Rogers1d54e732013-05-02 21:10:01 -07001093 if (!IsLiveObjectLocked(obj)) {
1094 DumpSpaces();
1095 LOG(FATAL) << "Object is dead: " << obj;
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001096 }
Mathieu Chartierdcf8d722012-08-02 14:55:54 -07001097 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001098}
1099
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001100void Heap::VerificationCallback(mirror::Object* obj, void* arg) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001101 reinterpret_cast<Heap*>(arg)->VerifyObjectBody(obj);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001102}
1103
1104void Heap::VerifyHeap() {
Ian Rogers50b35e22012-10-04 10:09:15 -07001105 ReaderMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07001106 GetLiveBitmap()->Walk(Heap::VerificationCallback, this);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001107}
1108
Ian Rogersef7d42f2014-01-06 12:55:46 -08001109void Heap::RecordFree(size_t freed_objects, size_t freed_bytes) {
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001110 DCHECK_LE(freed_bytes, num_bytes_allocated_.Load());
Ian Rogersb122a4b2013-11-19 18:00:50 -08001111 num_bytes_allocated_.FetchAndSub(freed_bytes);
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07001112 if (Runtime::Current()->HasStatsEnabled()) {
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07001113 RuntimeStats* thread_stats = Thread::Current()->GetStats();
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001114 thread_stats->freed_objects += freed_objects;
Elliott Hughes307f75d2011-10-12 18:04:40 -07001115 thread_stats->freed_bytes += freed_bytes;
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001116 // TODO: Do this concurrently.
1117 RuntimeStats* global_stats = Runtime::Current()->GetStats();
1118 global_stats->freed_objects += freed_objects;
1119 global_stats->freed_bytes += freed_bytes;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07001120 }
Carl Shapiro58551df2011-07-24 03:09:51 -07001121}
1122
Mathieu Chartiercbb2d202013-11-14 17:45:16 -08001123mirror::Object* Heap::AllocateInternalWithGc(Thread* self, AllocatorType allocator,
Mathieu Chartierc528dba2013-11-26 12:00:11 -08001124 size_t alloc_size, size_t* bytes_allocated,
Ian Rogers6fac4472014-02-25 17:01:10 -08001125 size_t* usable_size,
Mathieu Chartierc528dba2013-11-26 12:00:11 -08001126 mirror::Class** klass) {
Mathieu Chartiercbb2d202013-11-14 17:45:16 -08001127 mirror::Object* ptr = nullptr;
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001128 bool was_default_allocator = allocator == GetCurrentAllocator();
Mathieu Chartierc528dba2013-11-26 12:00:11 -08001129 DCHECK(klass != nullptr);
1130 SirtRef<mirror::Class> sirt_klass(self, *klass);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001131 // The allocation failed. If the GC is running, block until it completes, and then retry the
1132 // allocation.
Mathieu Chartier590fee92013-09-13 13:46:47 -07001133 collector::GcType last_gc = WaitForGcToComplete(self);
Ian Rogers1d54e732013-05-02 21:10:01 -07001134 if (last_gc != collector::kGcTypeNone) {
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001135 // If we were the default allocator but the allocator changed while we were suspended,
1136 // abort the allocation.
1137 if (was_default_allocator && allocator != GetCurrentAllocator()) {
1138 *klass = sirt_klass.get();
1139 return nullptr;
1140 }
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001141 // A GC was in progress and we blocked, retry allocation now that memory has been freed.
Ian Rogers6fac4472014-02-25 17:01:10 -08001142 ptr = TryToAllocate<true, false>(self, allocator, alloc_size, bytes_allocated, usable_size);
Carl Shapiro69759ea2011-07-21 18:13:35 -07001143 }
1144
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001145 // Loop through our different Gc types and try to Gc until we get enough free memory.
Mathieu Chartiercbb2d202013-11-14 17:45:16 -08001146 for (collector::GcType gc_type : gc_plan_) {
1147 if (ptr != nullptr) {
1148 break;
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001149 }
Mathieu Chartiercbb2d202013-11-14 17:45:16 -08001150 // Attempt to run the collector, if we succeed, re-try the allocation.
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001151 bool gc_ran =
1152 CollectGarbageInternal(gc_type, kGcCauseForAlloc, false) != collector::kGcTypeNone;
1153 if (was_default_allocator && allocator != GetCurrentAllocator()) {
1154 *klass = sirt_klass.get();
1155 return nullptr;
1156 }
1157 if (gc_ran) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001158 // Did we free sufficient memory for the allocation to succeed?
Ian Rogers6fac4472014-02-25 17:01:10 -08001159 ptr = TryToAllocate<true, false>(self, allocator, alloc_size, bytes_allocated, usable_size);
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001160 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001161 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001162 // Allocations have failed after GCs; this is an exceptional state.
Mathieu Chartiercbb2d202013-11-14 17:45:16 -08001163 if (ptr == nullptr) {
1164 // Try harder, growing the heap if necessary.
Ian Rogers6fac4472014-02-25 17:01:10 -08001165 ptr = TryToAllocate<true, true>(self, allocator, alloc_size, bytes_allocated, usable_size);
Carl Shapiro69759ea2011-07-21 18:13:35 -07001166 }
Mathieu Chartiercbb2d202013-11-14 17:45:16 -08001167 if (ptr == nullptr) {
1168 // Most allocations should have succeeded by now, so the heap is really full, really fragmented,
1169 // or the requested size is really big. Do another GC, collecting SoftReferences this time. The
1170 // VM spec requires that all SoftReferences have been collected and cleared before throwing
1171 // OOME.
1172 VLOG(gc) << "Forcing collection of SoftReferences for " << PrettySize(alloc_size)
1173 << " allocation";
1174 // TODO: Run finalization, but this may cause more allocations to occur.
1175 // We don't need a WaitForGcToComplete here either.
1176 DCHECK(!gc_plan_.empty());
1177 CollectGarbageInternal(gc_plan_.back(), kGcCauseForAlloc, true);
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001178 if (was_default_allocator && allocator != GetCurrentAllocator()) {
1179 *klass = sirt_klass.get();
1180 return nullptr;
1181 }
Ian Rogers6fac4472014-02-25 17:01:10 -08001182 ptr = TryToAllocate<true, true>(self, allocator, alloc_size, bytes_allocated, usable_size);
Mathieu Chartiercbb2d202013-11-14 17:45:16 -08001183 if (ptr == nullptr) {
1184 ThrowOutOfMemoryError(self, alloc_size, false);
1185 }
1186 }
Mathieu Chartierc528dba2013-11-26 12:00:11 -08001187 *klass = sirt_klass.get();
Mathieu Chartiercbb2d202013-11-14 17:45:16 -08001188 return ptr;
Carl Shapiro69759ea2011-07-21 18:13:35 -07001189}
1190
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001191void Heap::SetTargetHeapUtilization(float target) {
1192 DCHECK_GT(target, 0.0f); // asserted in Java code
1193 DCHECK_LT(target, 1.0f);
1194 target_utilization_ = target;
1195}
1196
Ian Rogers1d54e732013-05-02 21:10:01 -07001197size_t Heap::GetObjectsAllocated() const {
1198 size_t total = 0;
Mathieu Chartier590fee92013-09-13 13:46:47 -07001199 for (space::AllocSpace* space : alloc_spaces_) {
1200 total += space->GetObjectsAllocated();
Ian Rogers1d54e732013-05-02 21:10:01 -07001201 }
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001202 return total;
1203}
1204
Ian Rogers1d54e732013-05-02 21:10:01 -07001205size_t Heap::GetObjectsAllocatedEver() const {
Mathieu Chartier692fafd2013-11-29 17:24:40 -08001206 return GetObjectsFreedEver() + GetObjectsAllocated();
Ian Rogers1d54e732013-05-02 21:10:01 -07001207}
1208
1209size_t Heap::GetBytesAllocatedEver() const {
Mathieu Chartier692fafd2013-11-29 17:24:40 -08001210 return GetBytesFreedEver() + GetBytesAllocated();
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001211}
1212
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07001213class InstanceCounter {
1214 public:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001215 InstanceCounter(const std::vector<mirror::Class*>& classes, bool use_is_assignable_from, uint64_t* counts)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001216 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Elliott Hughesec0f83d2013-01-15 16:54:08 -08001217 : classes_(classes), use_is_assignable_from_(use_is_assignable_from), counts_(counts) {
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07001218 }
Mathieu Chartier412c7fc2014-02-07 12:18:39 -08001219 static void Callback(mirror::Object* obj, void* arg)
1220 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
1221 InstanceCounter* instance_counter = reinterpret_cast<InstanceCounter*>(arg);
1222 mirror::Class* instance_class = obj->GetClass();
1223 CHECK(instance_class != nullptr);
1224 for (size_t i = 0; i < instance_counter->classes_.size(); ++i) {
1225 if (instance_counter->use_is_assignable_from_) {
1226 if (instance_counter->classes_[i]->IsAssignableFrom(instance_class)) {
1227 ++instance_counter->counts_[i];
Elliott Hughesec0f83d2013-01-15 16:54:08 -08001228 }
Mathieu Chartier412c7fc2014-02-07 12:18:39 -08001229 } else if (instance_class == instance_counter->classes_[i]) {
1230 ++instance_counter->counts_[i];
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07001231 }
1232 }
1233 }
1234
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001235 private:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001236 const std::vector<mirror::Class*>& classes_;
Elliott Hughesec0f83d2013-01-15 16:54:08 -08001237 bool use_is_assignable_from_;
1238 uint64_t* const counts_;
Elliott Hughesec0f83d2013-01-15 16:54:08 -08001239 DISALLOW_COPY_AND_ASSIGN(InstanceCounter);
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07001240};
1241
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001242void Heap::CountInstances(const std::vector<mirror::Class*>& classes, bool use_is_assignable_from,
Elliott Hughesec0f83d2013-01-15 16:54:08 -08001243 uint64_t* counts) {
Mathieu Chartier412c7fc2014-02-07 12:18:39 -08001244 // Can't do any GC in this function since this may move classes.
Elliott Hughesec0f83d2013-01-15 16:54:08 -08001245 Thread* self = Thread::Current();
Mathieu Chartier412c7fc2014-02-07 12:18:39 -08001246 auto* old_cause = self->StartAssertNoThreadSuspension("CountInstances");
Elliott Hughesec0f83d2013-01-15 16:54:08 -08001247 InstanceCounter counter(classes, use_is_assignable_from, counts);
Mathieu Chartier412c7fc2014-02-07 12:18:39 -08001248 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
1249 VisitObjects(InstanceCounter::Callback, &counter);
1250 self->EndAssertNoThreadSuspension(old_cause);
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07001251}
1252
Elliott Hughes3b78c942013-01-15 17:35:41 -08001253class InstanceCollector {
1254 public:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001255 InstanceCollector(mirror::Class* c, int32_t max_count, std::vector<mirror::Object*>& instances)
Elliott Hughes3b78c942013-01-15 17:35:41 -08001256 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
1257 : class_(c), max_count_(max_count), instances_(instances) {
1258 }
Mathieu Chartier412c7fc2014-02-07 12:18:39 -08001259 static void Callback(mirror::Object* obj, void* arg)
1260 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
1261 DCHECK(arg != nullptr);
1262 InstanceCollector* instance_collector = reinterpret_cast<InstanceCollector*>(arg);
1263 mirror::Class* instance_class = obj->GetClass();
1264 if (instance_class == instance_collector->class_) {
1265 if (instance_collector->max_count_ == 0 ||
1266 instance_collector->instances_.size() < instance_collector->max_count_) {
1267 instance_collector->instances_.push_back(obj);
Elliott Hughes3b78c942013-01-15 17:35:41 -08001268 }
1269 }
1270 }
1271
1272 private:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001273 mirror::Class* class_;
Elliott Hughes3b78c942013-01-15 17:35:41 -08001274 uint32_t max_count_;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001275 std::vector<mirror::Object*>& instances_;
Elliott Hughes3b78c942013-01-15 17:35:41 -08001276 DISALLOW_COPY_AND_ASSIGN(InstanceCollector);
1277};
1278
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001279void Heap::GetInstances(mirror::Class* c, int32_t max_count,
1280 std::vector<mirror::Object*>& instances) {
Mathieu Chartier412c7fc2014-02-07 12:18:39 -08001281 // Can't do any GC in this function since this may move classes.
Elliott Hughes3b78c942013-01-15 17:35:41 -08001282 Thread* self = Thread::Current();
Mathieu Chartier412c7fc2014-02-07 12:18:39 -08001283 auto* old_cause = self->StartAssertNoThreadSuspension("GetInstances");
Elliott Hughes3b78c942013-01-15 17:35:41 -08001284 InstanceCollector collector(c, max_count, instances);
Mathieu Chartier412c7fc2014-02-07 12:18:39 -08001285 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
1286 VisitObjects(&InstanceCollector::Callback, &collector);
1287 self->EndAssertNoThreadSuspension(old_cause);
Elliott Hughes3b78c942013-01-15 17:35:41 -08001288}
1289
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001290class ReferringObjectsFinder {
1291 public:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001292 ReferringObjectsFinder(mirror::Object* object, int32_t max_count,
1293 std::vector<mirror::Object*>& referring_objects)
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001294 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
1295 : object_(object), max_count_(max_count), referring_objects_(referring_objects) {
1296 }
1297
Mathieu Chartier412c7fc2014-02-07 12:18:39 -08001298 static void Callback(mirror::Object* obj, void* arg)
1299 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
1300 reinterpret_cast<ReferringObjectsFinder*>(arg)->operator()(obj);
1301 }
1302
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001303 // For bitmap Visit.
1304 // TODO: Fix lock analysis to not use NO_THREAD_SAFETY_ANALYSIS, requires support for
1305 // annotalysis on visitors.
Mathieu Chartier590fee92013-09-13 13:46:47 -07001306 void operator()(const mirror::Object* o) const NO_THREAD_SAFETY_ANALYSIS {
1307 collector::MarkSweep::VisitObjectReferences(const_cast<mirror::Object*>(o), *this, true);
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001308 }
1309
1310 // For MarkSweep::VisitObjectReferences.
Mathieu Chartier11409ae2013-09-23 11:49:36 -07001311 void operator()(mirror::Object* referrer, mirror::Object* object,
Brian Carlstromdf629502013-07-17 22:39:56 -07001312 const MemberOffset&, bool) const {
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001313 if (object == object_ && (max_count_ == 0 || referring_objects_.size() < max_count_)) {
Mathieu Chartier11409ae2013-09-23 11:49:36 -07001314 referring_objects_.push_back(referrer);
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001315 }
1316 }
1317
1318 private:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001319 mirror::Object* object_;
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001320 uint32_t max_count_;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001321 std::vector<mirror::Object*>& referring_objects_;
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001322 DISALLOW_COPY_AND_ASSIGN(ReferringObjectsFinder);
1323};
1324
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001325void Heap::GetReferringObjects(mirror::Object* o, int32_t max_count,
1326 std::vector<mirror::Object*>& referring_objects) {
Mathieu Chartier83c8ee02014-01-28 14:50:23 -08001327 // Can't do any GC in this function since this may move the object o.
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001328 Thread* self = Thread::Current();
Mathieu Chartier412c7fc2014-02-07 12:18:39 -08001329 auto* old_cause = self->StartAssertNoThreadSuspension("GetReferringObjects");
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001330 ReferringObjectsFinder finder(o, max_count, referring_objects);
Mathieu Chartier412c7fc2014-02-07 12:18:39 -08001331 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
1332 VisitObjects(&ReferringObjectsFinder::Callback, &finder);
1333 self->EndAssertNoThreadSuspension(old_cause);
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001334}
1335
Ian Rogers30fab402012-01-23 15:43:46 -08001336void Heap::CollectGarbage(bool clear_soft_references) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001337 // Even if we waited for a GC we still need to do another GC since weaks allocated during the
1338 // last GC will not have necessarily been cleared.
Mathieu Chartier7bf82af2013-12-06 16:51:45 -08001339 CollectGarbageInternal(gc_plan_.back(), kGcCauseExplicit, clear_soft_references);
Carl Shapiro69759ea2011-07-21 18:13:35 -07001340}
1341
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001342void Heap::TransitionCollector(CollectorType collector_type) {
1343 if (collector_type == collector_type_) {
1344 return;
1345 }
Hiroshi Yamauchia4adbfd2014-02-04 18:12:17 -08001346 VLOG(heap) << "TransitionCollector: " << static_cast<int>(collector_type_)
1347 << " -> " << static_cast<int>(collector_type);
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001348 uint64_t start_time = NanoTime();
Ian Rogersef7d42f2014-01-06 12:55:46 -08001349 uint32_t before_size = GetTotalMemory();
1350 uint32_t before_allocated = num_bytes_allocated_.Load();
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001351 ThreadList* tl = Runtime::Current()->GetThreadList();
1352 Thread* self = Thread::Current();
1353 ScopedThreadStateChange tsc(self, kWaitingPerformingGc);
1354 Locks::mutator_lock_->AssertNotHeld(self);
Mathieu Chartierd5a89ee2014-01-31 09:55:13 -08001355 const bool copying_transition =
1356 IsCompactingGC(background_collector_type_) || IsCompactingGC(post_zygote_collector_type_);
Mathieu Chartier1d27b342014-01-28 12:51:09 -08001357 // Busy wait until we can GC (StartGC can fail if we have a non-zero
1358 // compacting_gc_disable_count_, this should rarely occurs).
Mathieu Chartierd5a89ee2014-01-31 09:55:13 -08001359 for (;;) {
Mathieu Chartiercaa82d62014-02-02 16:51:17 -08001360 {
1361 ScopedThreadStateChange tsc(self, kWaitingForGcToComplete);
1362 MutexLock mu(self, *gc_complete_lock_);
1363 // Ensure there is only one GC at a time.
1364 WaitForGcToCompleteLocked(self);
1365 // GC can be disabled if someone has a used GetPrimitiveArrayCritical but not yet released.
1366 if (!copying_transition || disable_moving_gc_count_ == 0) {
1367 // TODO: Not hard code in semi-space collector?
1368 collector_type_running_ = copying_transition ? kCollectorTypeSS : collector_type;
1369 break;
1370 }
Mathieu Chartierd5a89ee2014-01-31 09:55:13 -08001371 }
Mathieu Chartiercaa82d62014-02-02 16:51:17 -08001372 usleep(1000);
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001373 }
1374 tl->SuspendAll();
Hiroshi Yamauchia4adbfd2014-02-04 18:12:17 -08001375 PreGcRosAllocVerification(&semi_space_collector_->GetTimings());
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001376 switch (collector_type) {
Hiroshi Yamauchi6f4ffe42014-01-13 12:30:44 -08001377 case kCollectorTypeSS:
Mathieu Chartier1d27b342014-01-28 12:51:09 -08001378 // Fall-through.
Hiroshi Yamauchi6f4ffe42014-01-13 12:30:44 -08001379 case kCollectorTypeGSS: {
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001380 mprotect(temp_space_->Begin(), temp_space_->Capacity(), PROT_READ | PROT_WRITE);
Mathieu Chartierfc5b5282014-01-09 16:15:36 -08001381 CHECK(main_space_ != nullptr);
1382 Compact(temp_space_, main_space_);
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001383 DCHECK(allocator_mem_map_.get() == nullptr);
Mathieu Chartierfc5b5282014-01-09 16:15:36 -08001384 allocator_mem_map_.reset(main_space_->ReleaseMemMap());
1385 madvise(main_space_->Begin(), main_space_->Size(), MADV_DONTNEED);
Mathieu Chartiera1602f22014-01-13 17:19:19 -08001386 // RemoveSpace does not delete the removed space.
1387 space::Space* old_space = main_space_;
1388 RemoveSpace(old_space);
1389 delete old_space;
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001390 break;
1391 }
1392 case kCollectorTypeMS:
1393 // Fall through.
1394 case kCollectorTypeCMS: {
Mathieu Chartier1d27b342014-01-28 12:51:09 -08001395 if (IsCompactingGC(collector_type_)) {
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001396 // TODO: Use mem-map from temp space?
1397 MemMap* mem_map = allocator_mem_map_.release();
1398 CHECK(mem_map != nullptr);
Hiroshi Yamauchi5ccd4982014-03-11 12:19:04 -07001399 size_t starting_size = kDefaultStartingSize;
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001400 size_t initial_size = kDefaultInitialSize;
1401 mprotect(mem_map->Begin(), initial_size, PROT_READ | PROT_WRITE);
Mathieu Chartierfc5b5282014-01-09 16:15:36 -08001402 CHECK(main_space_ == nullptr);
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001403 if (kUseRosAlloc) {
Mathieu Chartierfc5b5282014-01-09 16:15:36 -08001404 main_space_ =
Hiroshi Yamauchi5ccd4982014-03-11 12:19:04 -07001405 space::RosAllocSpace::CreateFromMemMap(mem_map, "alloc space", starting_size,
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001406 initial_size, mem_map->Size(),
1407 mem_map->Size(), low_memory_mode_);
1408 } else {
Mathieu Chartierfc5b5282014-01-09 16:15:36 -08001409 main_space_ =
Hiroshi Yamauchi5ccd4982014-03-11 12:19:04 -07001410 space::DlMallocSpace::CreateFromMemMap(mem_map, "alloc space", starting_size,
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001411 initial_size, mem_map->Size(),
1412 mem_map->Size());
1413 }
Mathieu Chartierfc5b5282014-01-09 16:15:36 -08001414 main_space_->SetFootprintLimit(main_space_->Capacity());
1415 AddSpace(main_space_);
1416 Compact(main_space_, bump_pointer_space_);
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001417 }
1418 break;
1419 }
1420 default: {
1421 LOG(FATAL) << "Attempted to transition to invalid collector type";
1422 break;
1423 }
1424 }
1425 ChangeCollector(collector_type);
Hiroshi Yamauchia4adbfd2014-02-04 18:12:17 -08001426 PostGcRosAllocVerification(&semi_space_collector_->GetTimings());
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001427 tl->ResumeAll();
1428 // Can't call into java code with all threads suspended.
1429 EnqueueClearedReferences();
1430 uint64_t duration = NanoTime() - start_time;
1431 GrowForUtilization(collector::kGcTypeFull, duration);
1432 FinishGC(self, collector::kGcTypeFull);
1433 int32_t after_size = GetTotalMemory();
1434 int32_t delta_size = before_size - after_size;
1435 int32_t after_allocated = num_bytes_allocated_.Load();
1436 int32_t delta_allocated = before_allocated - after_allocated;
1437 const std::string saved_bytes_str =
1438 delta_size < 0 ? "-" + PrettySize(-delta_size) : PrettySize(delta_size);
1439 LOG(INFO) << "Heap transition to " << process_state_ << " took "
1440 << PrettyDuration(duration) << " " << PrettySize(before_size) << "->"
1441 << PrettySize(after_size) << " from " << PrettySize(delta_allocated) << " to "
1442 << PrettySize(delta_size) << " saved";
1443}
1444
Mathieu Chartier0de9f732013-11-22 17:58:48 -08001445void Heap::ChangeCollector(CollectorType collector_type) {
Mathieu Chartier7bf82af2013-12-06 16:51:45 -08001446 // TODO: Only do this with all mutators suspended to avoid races.
1447 if (collector_type != collector_type_) {
1448 collector_type_ = collector_type;
1449 gc_plan_.clear();
1450 switch (collector_type_) {
Hiroshi Yamauchi6f4ffe42014-01-13 12:30:44 -08001451 case kCollectorTypeSS:
Mathieu Chartier1d27b342014-01-28 12:51:09 -08001452 // Fall-through.
Hiroshi Yamauchi6f4ffe42014-01-13 12:30:44 -08001453 case kCollectorTypeGSS: {
Mathieu Chartier7bf82af2013-12-06 16:51:45 -08001454 concurrent_gc_ = false;
1455 gc_plan_.push_back(collector::kGcTypeFull);
Mathieu Chartier692fafd2013-11-29 17:24:40 -08001456 if (use_tlab_) {
1457 ChangeAllocator(kAllocatorTypeTLAB);
1458 } else {
1459 ChangeAllocator(kAllocatorTypeBumpPointer);
1460 }
Mathieu Chartier7bf82af2013-12-06 16:51:45 -08001461 break;
1462 }
1463 case kCollectorTypeMS: {
1464 concurrent_gc_ = false;
1465 gc_plan_.push_back(collector::kGcTypeSticky);
1466 gc_plan_.push_back(collector::kGcTypePartial);
1467 gc_plan_.push_back(collector::kGcTypeFull);
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001468 ChangeAllocator(kUseRosAlloc ? kAllocatorTypeRosAlloc : kAllocatorTypeDlMalloc);
Mathieu Chartier7bf82af2013-12-06 16:51:45 -08001469 break;
1470 }
1471 case kCollectorTypeCMS: {
1472 concurrent_gc_ = true;
1473 gc_plan_.push_back(collector::kGcTypeSticky);
1474 gc_plan_.push_back(collector::kGcTypePartial);
1475 gc_plan_.push_back(collector::kGcTypeFull);
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001476 ChangeAllocator(kUseRosAlloc ? kAllocatorTypeRosAlloc : kAllocatorTypeDlMalloc);
Mathieu Chartier7bf82af2013-12-06 16:51:45 -08001477 break;
1478 }
1479 default: {
1480 LOG(FATAL) << "Unimplemented";
1481 }
Mathieu Chartier0de9f732013-11-22 17:58:48 -08001482 }
Mathieu Chartier7bf82af2013-12-06 16:51:45 -08001483 if (concurrent_gc_) {
1484 concurrent_start_bytes_ =
1485 std::max(max_allowed_footprint_, kMinConcurrentRemainingBytes) - kMinConcurrentRemainingBytes;
1486 } else {
1487 concurrent_start_bytes_ = std::numeric_limits<size_t>::max();
Mathieu Chartier0de9f732013-11-22 17:58:48 -08001488 }
1489 }
1490}
1491
Mathieu Chartier85a43c02014-01-07 17:59:00 -08001492// Special compacting collector which uses sub-optimal bin packing to reduce zygote space size.
Ian Rogers6fac4472014-02-25 17:01:10 -08001493class ZygoteCompactingCollector FINAL : public collector::SemiSpace {
Mathieu Chartier85a43c02014-01-07 17:59:00 -08001494 public:
Ian Rogers6fac4472014-02-25 17:01:10 -08001495 explicit ZygoteCompactingCollector(gc::Heap* heap) : SemiSpace(heap, "zygote collector"),
1496 bin_live_bitmap_(nullptr), bin_mark_bitmap_(nullptr) {
Mathieu Chartier85a43c02014-01-07 17:59:00 -08001497 }
1498
1499 void BuildBins(space::ContinuousSpace* space) {
1500 bin_live_bitmap_ = space->GetLiveBitmap();
1501 bin_mark_bitmap_ = space->GetMarkBitmap();
1502 BinContext context;
1503 context.prev_ = reinterpret_cast<uintptr_t>(space->Begin());
1504 context.collector_ = this;
1505 WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
1506 // Note: This requires traversing the space in increasing order of object addresses.
1507 bin_live_bitmap_->Walk(Callback, reinterpret_cast<void*>(&context));
1508 // Add the last bin which spans after the last object to the end of the space.
1509 AddBin(reinterpret_cast<uintptr_t>(space->End()) - context.prev_, context.prev_);
1510 }
1511
1512 private:
1513 struct BinContext {
1514 uintptr_t prev_; // The end of the previous object.
1515 ZygoteCompactingCollector* collector_;
1516 };
1517 // Maps from bin sizes to locations.
1518 std::multimap<size_t, uintptr_t> bins_;
1519 // Live bitmap of the space which contains the bins.
1520 accounting::SpaceBitmap* bin_live_bitmap_;
1521 // Mark bitmap of the space which contains the bins.
1522 accounting::SpaceBitmap* bin_mark_bitmap_;
1523
1524 static void Callback(mirror::Object* obj, void* arg)
1525 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1526 DCHECK(arg != nullptr);
1527 BinContext* context = reinterpret_cast<BinContext*>(arg);
1528 ZygoteCompactingCollector* collector = context->collector_;
1529 uintptr_t object_addr = reinterpret_cast<uintptr_t>(obj);
1530 size_t bin_size = object_addr - context->prev_;
1531 // Add the bin consisting of the end of the previous object to the start of the current object.
1532 collector->AddBin(bin_size, context->prev_);
1533 context->prev_ = object_addr + RoundUp(obj->SizeOf(), kObjectAlignment);
1534 }
1535
1536 void AddBin(size_t size, uintptr_t position) {
1537 if (size != 0) {
1538 bins_.insert(std::make_pair(size, position));
1539 }
1540 }
1541
Mathieu Chartiera1602f22014-01-13 17:19:19 -08001542 virtual bool ShouldSweepSpace(space::ContinuousSpace* space) const {
Mathieu Chartier85a43c02014-01-07 17:59:00 -08001543 // Don't sweep any spaces since we probably blasted the internal accounting of the free list
1544 // allocator.
1545 return false;
1546 }
1547
1548 virtual mirror::Object* MarkNonForwardedObject(mirror::Object* obj)
1549 EXCLUSIVE_LOCKS_REQUIRED(Locks::heap_bitmap_lock_, Locks::mutator_lock_) {
1550 size_t object_size = RoundUp(obj->SizeOf(), kObjectAlignment);
Mathieu Chartier5dc08a62014-01-10 10:10:23 -08001551 mirror::Object* forward_address;
Mathieu Chartier85a43c02014-01-07 17:59:00 -08001552 // Find the smallest bin which we can move obj in.
1553 auto it = bins_.lower_bound(object_size);
1554 if (it == bins_.end()) {
1555 // No available space in the bins, place it in the target space instead (grows the zygote
1556 // space).
Mathieu Chartier5dc08a62014-01-10 10:10:23 -08001557 size_t bytes_allocated;
Ian Rogers6fac4472014-02-25 17:01:10 -08001558 forward_address = to_space_->Alloc(self_, object_size, &bytes_allocated, nullptr);
Mathieu Chartier85a43c02014-01-07 17:59:00 -08001559 if (to_space_live_bitmap_ != nullptr) {
1560 to_space_live_bitmap_->Set(forward_address);
Mathieu Chartier938a03b2014-01-16 15:10:31 -08001561 } else {
1562 GetHeap()->GetNonMovingSpace()->GetLiveBitmap()->Set(forward_address);
1563 GetHeap()->GetNonMovingSpace()->GetMarkBitmap()->Set(forward_address);
Mathieu Chartier85a43c02014-01-07 17:59:00 -08001564 }
1565 } else {
1566 size_t size = it->first;
1567 uintptr_t pos = it->second;
1568 bins_.erase(it); // Erase the old bin which we replace with the new smaller bin.
1569 forward_address = reinterpret_cast<mirror::Object*>(pos);
1570 // Set the live and mark bits so that sweeping system weaks works properly.
1571 bin_live_bitmap_->Set(forward_address);
1572 bin_mark_bitmap_->Set(forward_address);
1573 DCHECK_GE(size, object_size);
1574 AddBin(size - object_size, pos + object_size); // Add a new bin with the remaining space.
1575 }
1576 // Copy the object over to its new location.
1577 memcpy(reinterpret_cast<void*>(forward_address), obj, object_size);
Hiroshi Yamauchi9d04a202014-01-31 13:35:49 -08001578 if (kUseBrooksPointer) {
1579 obj->AssertSelfBrooksPointer();
1580 DCHECK_EQ(forward_address->GetBrooksPointer(), obj);
1581 forward_address->SetBrooksPointer(forward_address);
1582 forward_address->AssertSelfBrooksPointer();
1583 }
Mathieu Chartier85a43c02014-01-07 17:59:00 -08001584 return forward_address;
1585 }
1586};
1587
Mathieu Chartiera1602f22014-01-13 17:19:19 -08001588void Heap::UnBindBitmaps() {
1589 for (const auto& space : GetContinuousSpaces()) {
1590 if (space->IsContinuousMemMapAllocSpace()) {
1591 space::ContinuousMemMapAllocSpace* alloc_space = space->AsContinuousMemMapAllocSpace();
1592 if (alloc_space->HasBoundBitmaps()) {
1593 alloc_space->UnBindBitmaps();
1594 }
1595 }
1596 }
1597}
1598
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001599void Heap::PreZygoteFork() {
Mathieu Chartier1f3b5352014-02-03 14:00:42 -08001600 CollectGarbageInternal(collector::kGcTypeFull, kGcCauseBackground, false);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001601 static Mutex zygote_creation_lock_("zygote creation lock", kZygoteCreationLock);
Ian Rogers81d425b2012-09-27 16:03:43 -07001602 Thread* self = Thread::Current();
1603 MutexLock mu(self, zygote_creation_lock_);
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001604 // Try to see if we have any Zygote spaces.
1605 if (have_zygote_space_) {
1606 return;
1607 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07001608 VLOG(heap) << "Starting PreZygoteFork";
Mathieu Chartier590fee92013-09-13 13:46:47 -07001609 // Trim the pages at the end of the non moving space.
1610 non_moving_space_->Trim();
1611 non_moving_space_->GetMemMap()->Protect(PROT_READ | PROT_WRITE);
Mathieu Chartier7bf82af2013-12-06 16:51:45 -08001612 // Change the collector to the post zygote one.
1613 ChangeCollector(post_zygote_collector_type_);
Mathieu Chartier50482232013-11-21 11:48:14 -08001614 // TODO: Delete bump_pointer_space_ and temp_pointer_space_?
Mathieu Chartier590fee92013-09-13 13:46:47 -07001615 if (semi_space_collector_ != nullptr) {
Hiroshi Yamauchia4adbfd2014-02-04 18:12:17 -08001616 // Temporarily disable rosalloc verification because the zygote
1617 // compaction will mess up the rosalloc internal metadata.
1618 ScopedDisableRosAllocVerification disable_rosalloc_verif(this);
Mathieu Chartier85a43c02014-01-07 17:59:00 -08001619 ZygoteCompactingCollector zygote_collector(this);
1620 zygote_collector.BuildBins(non_moving_space_);
Mathieu Chartier50482232013-11-21 11:48:14 -08001621 // Create a new bump pointer space which we will compact into.
Mathieu Chartier590fee92013-09-13 13:46:47 -07001622 space::BumpPointerSpace target_space("zygote bump space", non_moving_space_->End(),
1623 non_moving_space_->Limit());
1624 // Compact the bump pointer space to a new zygote bump pointer space.
1625 temp_space_->GetMemMap()->Protect(PROT_READ | PROT_WRITE);
Mathieu Chartier85a43c02014-01-07 17:59:00 -08001626 zygote_collector.SetFromSpace(bump_pointer_space_);
1627 zygote_collector.SetToSpace(&target_space);
Hiroshi Yamauchi6f4ffe42014-01-13 12:30:44 -08001628 zygote_collector.Run(kGcCauseCollectorTransition, false);
Mathieu Chartier692fafd2013-11-29 17:24:40 -08001629 CHECK(temp_space_->IsEmpty());
Mathieu Chartier590fee92013-09-13 13:46:47 -07001630 total_objects_freed_ever_ += semi_space_collector_->GetFreedObjects();
1631 total_bytes_freed_ever_ += semi_space_collector_->GetFreedBytes();
1632 // Update the end and write out image.
1633 non_moving_space_->SetEnd(target_space.End());
1634 non_moving_space_->SetLimit(target_space.Limit());
Mathieu Chartier85a43c02014-01-07 17:59:00 -08001635 VLOG(heap) << "Zygote size " << non_moving_space_->Size() << " bytes";
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001636 }
Mathieu Chartiera1602f22014-01-13 17:19:19 -08001637 // Save the old space so that we can remove it after we complete creating the zygote space.
1638 space::MallocSpace* old_alloc_space = non_moving_space_;
Mathieu Chartier590fee92013-09-13 13:46:47 -07001639 // Turn the current alloc space into a zygote space and obtain the new alloc space composed of
Mathieu Chartiera1602f22014-01-13 17:19:19 -08001640 // the remaining available space.
1641 // Remove the old space before creating the zygote space since creating the zygote space sets
1642 // the old alloc space's bitmaps to nullptr.
1643 RemoveSpace(old_alloc_space);
1644 space::ZygoteSpace* zygote_space = old_alloc_space->CreateZygoteSpace("alloc space",
1645 low_memory_mode_,
1646 &main_space_);
1647 delete old_alloc_space;
1648 CHECK(zygote_space != nullptr) << "Failed creating zygote space";
1649 AddSpace(zygote_space, false);
1650 CHECK(main_space_ != nullptr);
Mathieu Chartierfc5b5282014-01-09 16:15:36 -08001651 if (main_space_->IsRosAllocSpace()) {
1652 rosalloc_space_ = main_space_->AsRosAllocSpace();
1653 } else if (main_space_->IsDlMallocSpace()) {
1654 dlmalloc_space_ = main_space_->AsDlMallocSpace();
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001655 }
Mathieu Chartierfc5b5282014-01-09 16:15:36 -08001656 main_space_->SetFootprintLimit(main_space_->Capacity());
Mathieu Chartierfc5b5282014-01-09 16:15:36 -08001657 AddSpace(main_space_);
Ian Rogers1d54e732013-05-02 21:10:01 -07001658 have_zygote_space_ = true;
Mathieu Chartierbd0a6532014-02-27 11:14:21 -08001659 // Enable large object space allocations.
1660 large_object_threshold_ = kDefaultLargeObjectThreshold;
Mathieu Chartier11409ae2013-09-23 11:49:36 -07001661 // Create the zygote space mod union table.
1662 accounting::ModUnionTable* mod_union_table =
1663 new accounting::ModUnionTableCardCache("zygote space mod-union table", this, zygote_space);
1664 CHECK(mod_union_table != nullptr) << "Failed to create zygote space mod-union table";
1665 AddModUnionTable(mod_union_table);
Mathieu Chartierfc5b5282014-01-09 16:15:36 -08001666 // Can't use RosAlloc for non moving space due to thread local buffers.
1667 // TODO: Non limited space for non-movable objects?
Mathieu Chartier938a03b2014-01-16 15:10:31 -08001668 MemMap* mem_map = post_zygote_non_moving_space_mem_map_.release();
1669 space::MallocSpace* new_non_moving_space =
1670 space::DlMallocSpace::CreateFromMemMap(mem_map, "Non moving dlmalloc space", kPageSize,
1671 2 * MB, mem_map->Size(), mem_map->Size());
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001672 AddSpace(new_non_moving_space, false);
1673 CHECK(new_non_moving_space != nullptr) << "Failed to create new non-moving space";
1674 new_non_moving_space->SetFootprintLimit(new_non_moving_space->Capacity());
1675 non_moving_space_ = new_non_moving_space;
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001676}
1677
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001678void Heap::FlushAllocStack() {
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001679 MarkAllocStackAsLive(allocation_stack_.get());
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001680 allocation_stack_->Reset();
1681}
1682
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001683void Heap::MarkAllocStack(accounting::SpaceBitmap* bitmap1,
1684 accounting::SpaceBitmap* bitmap2,
Mathieu Chartierdb7f37d2014-01-10 11:09:06 -08001685 accounting::ObjectSet* large_objects,
Ian Rogers1d54e732013-05-02 21:10:01 -07001686 accounting::ObjectStack* stack) {
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001687 DCHECK(bitmap1 != nullptr);
1688 DCHECK(bitmap2 != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001689 mirror::Object** limit = stack->End();
1690 for (mirror::Object** it = stack->Begin(); it != limit; ++it) {
1691 const mirror::Object* obj = *it;
Hiroshi Yamauchif5b0e202014-02-11 17:02:22 -08001692 if (!kUseThreadLocalAllocationStack || obj != nullptr) {
1693 if (bitmap1->HasAddress(obj)) {
1694 bitmap1->Set(obj);
1695 } else if (bitmap2->HasAddress(obj)) {
1696 bitmap2->Set(obj);
1697 } else {
1698 large_objects->Set(obj);
1699 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001700 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001701 }
1702}
1703
Mathieu Chartier590fee92013-09-13 13:46:47 -07001704void Heap::SwapSemiSpaces() {
1705 // Swap the spaces so we allocate into the space which we just evacuated.
1706 std::swap(bump_pointer_space_, temp_space_);
Mathieu Chartier15d34022014-02-26 17:16:38 -08001707 bump_pointer_space_->Clear();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001708}
1709
1710void Heap::Compact(space::ContinuousMemMapAllocSpace* target_space,
1711 space::ContinuousMemMapAllocSpace* source_space) {
1712 CHECK(kMovingCollector);
Mathieu Chartier50482232013-11-21 11:48:14 -08001713 CHECK_NE(target_space, source_space) << "In-place compaction currently unsupported";
Mathieu Chartier590fee92013-09-13 13:46:47 -07001714 if (target_space != source_space) {
1715 semi_space_collector_->SetFromSpace(source_space);
1716 semi_space_collector_->SetToSpace(target_space);
Hiroshi Yamauchi6f4ffe42014-01-13 12:30:44 -08001717 semi_space_collector_->Run(kGcCauseCollectorTransition, false);
Mathieu Chartier590fee92013-09-13 13:46:47 -07001718 }
1719}
Anwar Ghuloum67f99412013-08-12 14:19:48 -07001720
Ian Rogers1d54e732013-05-02 21:10:01 -07001721collector::GcType Heap::CollectGarbageInternal(collector::GcType gc_type, GcCause gc_cause,
1722 bool clear_soft_references) {
Ian Rogers81d425b2012-09-27 16:03:43 -07001723 Thread* self = Thread::Current();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001724 Runtime* runtime = Runtime::Current();
Mathieu Chartiercbb2d202013-11-14 17:45:16 -08001725 // If the heap can't run the GC, silently fail and return that no GC was run.
1726 switch (gc_type) {
Mathieu Chartiercbb2d202013-11-14 17:45:16 -08001727 case collector::kGcTypePartial: {
1728 if (!have_zygote_space_) {
1729 return collector::kGcTypeNone;
1730 }
1731 break;
1732 }
1733 default: {
1734 // Other GC types don't have any special cases which makes them not runnable. The main case
1735 // here is full GC.
1736 }
1737 }
Mathieu Chartier65db8802012-11-20 12:36:46 -08001738 ScopedThreadStateChange tsc(self, kWaitingPerformingGc);
Ian Rogers81d425b2012-09-27 16:03:43 -07001739 Locks::mutator_lock_->AssertNotHeld(self);
Ian Rogers120f1c72012-09-28 17:17:10 -07001740 if (self->IsHandlingStackOverflow()) {
1741 LOG(WARNING) << "Performing GC on a thread that is handling a stack overflow.";
1742 }
Mathieu Chartierd5a89ee2014-01-31 09:55:13 -08001743 bool compacting_gc;
1744 {
1745 gc_complete_lock_->AssertNotHeld(self);
Mathieu Chartiercaa82d62014-02-02 16:51:17 -08001746 ScopedThreadStateChange tsc(self, kWaitingForGcToComplete);
Mathieu Chartierd5a89ee2014-01-31 09:55:13 -08001747 MutexLock mu(self, *gc_complete_lock_);
1748 // Ensure there is only one GC at a time.
1749 WaitForGcToCompleteLocked(self);
1750 compacting_gc = IsCompactingGC(collector_type_);
1751 // GC can be disabled if someone has a used GetPrimitiveArrayCritical.
1752 if (compacting_gc && disable_moving_gc_count_ != 0) {
1753 LOG(WARNING) << "Skipping GC due to disable moving GC count " << disable_moving_gc_count_;
1754 return collector::kGcTypeNone;
1755 }
1756 collector_type_running_ = collector_type_;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001757 }
Mathieu Chartierd5a89ee2014-01-31 09:55:13 -08001758
Mathieu Chartier590fee92013-09-13 13:46:47 -07001759 if (gc_cause == kGcCauseForAlloc && runtime->HasStatsEnabled()) {
1760 ++runtime->GetStats()->gc_for_alloc_count;
1761 ++self->GetStats()->gc_for_alloc_count;
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001762 }
Ian Rogers1d54e732013-05-02 21:10:01 -07001763 uint64_t gc_start_time_ns = NanoTime();
Mathieu Chartier65db8802012-11-20 12:36:46 -08001764 uint64_t gc_start_size = GetBytesAllocated();
1765 // Approximate allocation rate in bytes / second.
Ian Rogers1d54e732013-05-02 21:10:01 -07001766 uint64_t ms_delta = NsToMs(gc_start_time_ns - last_gc_time_ns_);
Mathieu Chartier590fee92013-09-13 13:46:47 -07001767 // Back to back GCs can cause 0 ms of wait time in between GC invocations.
1768 if (LIKELY(ms_delta != 0)) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001769 allocation_rate_ = ((gc_start_size - last_gc_size_) * 1000) / ms_delta;
Mathieu Chartier65db8802012-11-20 12:36:46 -08001770 VLOG(heap) << "Allocation rate: " << PrettySize(allocation_rate_) << "/s";
1771 }
1772
Ian Rogers1d54e732013-05-02 21:10:01 -07001773 DCHECK_LT(gc_type, collector::kGcTypeMax);
1774 DCHECK_NE(gc_type, collector::kGcTypeNone);
Anwar Ghuloum67f99412013-08-12 14:19:48 -07001775
Mathieu Chartier590fee92013-09-13 13:46:47 -07001776 collector::GarbageCollector* collector = nullptr;
Mathieu Chartier50482232013-11-21 11:48:14 -08001777 // TODO: Clean this up.
Mathieu Chartier1d27b342014-01-28 12:51:09 -08001778 if (compacting_gc) {
Mathieu Chartier692fafd2013-11-29 17:24:40 -08001779 DCHECK(current_allocator_ == kAllocatorTypeBumpPointer ||
1780 current_allocator_ == kAllocatorTypeTLAB);
Mathieu Chartier590fee92013-09-13 13:46:47 -07001781 gc_type = semi_space_collector_->GetGcType();
Mathieu Chartier692fafd2013-11-29 17:24:40 -08001782 CHECK(temp_space_->IsEmpty());
Mathieu Chartier590fee92013-09-13 13:46:47 -07001783 semi_space_collector_->SetFromSpace(bump_pointer_space_);
1784 semi_space_collector_->SetToSpace(temp_space_);
Mathieu Chartier15d34022014-02-26 17:16:38 -08001785 temp_space_->GetMemMap()->Protect(PROT_READ | PROT_WRITE);
Mathieu Chartier50482232013-11-21 11:48:14 -08001786 collector = semi_space_collector_;
Mathieu Chartier590fee92013-09-13 13:46:47 -07001787 gc_type = collector::kGcTypeFull;
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001788 } else if (current_allocator_ == kAllocatorTypeRosAlloc ||
1789 current_allocator_ == kAllocatorTypeDlMalloc) {
Mathieu Chartier50482232013-11-21 11:48:14 -08001790 for (const auto& cur_collector : garbage_collectors_) {
1791 if (cur_collector->IsConcurrent() == concurrent_gc_ &&
1792 cur_collector->GetGcType() == gc_type) {
1793 collector = cur_collector;
1794 break;
1795 }
1796 }
1797 } else {
1798 LOG(FATAL) << "Invalid current allocator " << current_allocator_;
Mathieu Chartier590fee92013-09-13 13:46:47 -07001799 }
Mathieu Chartier7bf82af2013-12-06 16:51:45 -08001800 CHECK(collector != nullptr)
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001801 << "Could not find garbage collector with concurrent=" << concurrent_gc_
1802 << " and type=" << gc_type;
Mathieu Chartier590fee92013-09-13 13:46:47 -07001803 ATRACE_BEGIN(StringPrintf("%s %s GC", PrettyCause(gc_cause), collector->GetName()).c_str());
Hiroshi Yamauchi6f4ffe42014-01-13 12:30:44 -08001804 collector->Run(gc_cause, clear_soft_references);
Ian Rogers1d54e732013-05-02 21:10:01 -07001805 total_objects_freed_ever_ += collector->GetFreedObjects();
1806 total_bytes_freed_ever_ += collector->GetFreedBytes();
Mathieu Chartiera5f9de02014-02-28 16:48:42 -08001807 RequestHeapTrim(Heap::kHeapTrimWait);
Mathieu Chartier39e32612013-11-12 16:28:05 -08001808 // Enqueue cleared references.
1809 EnqueueClearedReferences();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001810 // Grow the heap so that we know when to perform the next GC.
1811 GrowForUtilization(gc_type, collector->GetDurationNs());
Mathieu Chartierca2a24d2013-11-25 15:12:12 -08001812 if (CareAboutPauseTimes()) {
Mathieu Chartiere53225c2013-08-19 10:59:11 -07001813 const size_t duration = collector->GetDurationNs();
1814 std::vector<uint64_t> pauses = collector->GetPauseTimes();
1815 // GC for alloc pauses the allocating thread, so consider it as a pause.
Mathieu Chartier2775ee42013-08-20 17:43:47 -07001816 bool was_slow = duration > long_gc_log_threshold_ ||
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001817 (gc_cause == kGcCauseForAlloc && duration > long_pause_log_threshold_);
Mathieu Chartiere53225c2013-08-19 10:59:11 -07001818 if (!was_slow) {
1819 for (uint64_t pause : pauses) {
Mathieu Chartier2775ee42013-08-20 17:43:47 -07001820 was_slow = was_slow || pause > long_pause_log_threshold_;
Mathieu Chartiere53225c2013-08-19 10:59:11 -07001821 }
1822 }
Mathieu Chartiere53225c2013-08-19 10:59:11 -07001823 if (was_slow) {
1824 const size_t percent_free = GetPercentFree();
1825 const size_t current_heap_size = GetBytesAllocated();
1826 const size_t total_memory = GetTotalMemory();
1827 std::ostringstream pause_string;
1828 for (size_t i = 0; i < pauses.size(); ++i) {
1829 pause_string << PrettyDuration((pauses[i] / 1000) * 1000)
1830 << ((i != pauses.size() - 1) ? ", " : "");
1831 }
1832 LOG(INFO) << gc_cause << " " << collector->GetName()
1833 << " GC freed " << collector->GetFreedObjects() << "("
1834 << PrettySize(collector->GetFreedBytes()) << ") AllocSpace objects, "
1835 << collector->GetFreedLargeObjects() << "("
1836 << PrettySize(collector->GetFreedLargeObjectBytes()) << ") LOS objects, "
1837 << percent_free << "% free, " << PrettySize(current_heap_size) << "/"
1838 << PrettySize(total_memory) << ", " << "paused " << pause_string.str()
1839 << " total " << PrettyDuration((duration / 1000) * 1000);
1840 if (VLOG_IS_ON(heap)) {
Ian Rogers5fe9af72013-11-14 00:17:20 -08001841 LOG(INFO) << Dumpable<TimingLogger>(collector->GetTimings());
Mathieu Chartiere53225c2013-08-19 10:59:11 -07001842 }
1843 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001844 }
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001845 FinishGC(self, gc_type);
Mathieu Chartier752a0e62013-06-27 11:03:27 -07001846 ATRACE_END();
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07001847
1848 // Inform DDMS that a GC completed.
Ian Rogers15bf2d32012-08-28 17:33:04 -07001849 Dbg::GcDidFinish();
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001850 return gc_type;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001851}
Mathieu Chartiera6399032012-06-11 18:49:50 -07001852
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001853void Heap::FinishGC(Thread* self, collector::GcType gc_type) {
1854 MutexLock mu(self, *gc_complete_lock_);
Mathieu Chartierd5a89ee2014-01-31 09:55:13 -08001855 collector_type_running_ = kCollectorTypeNone;
1856 if (gc_type != collector::kGcTypeNone) {
1857 last_gc_type_ = gc_type;
1858 }
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001859 // Wake anyone who may have been waiting for the GC to complete.
1860 gc_complete_cond_->Broadcast(self);
1861}
1862
Mathieu Chartier815873e2014-02-13 18:02:13 -08001863static void RootMatchesObjectVisitor(mirror::Object** root, void* arg, uint32_t /*thread_id*/,
1864 RootType /*root_type*/) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001865 mirror::Object* obj = reinterpret_cast<mirror::Object*>(arg);
Mathieu Chartier815873e2014-02-13 18:02:13 -08001866 if (*root == obj) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001867 LOG(INFO) << "Object " << obj << " is a root";
1868 }
1869}
1870
1871class ScanVisitor {
1872 public:
Brian Carlstromdf629502013-07-17 22:39:56 -07001873 void operator()(const mirror::Object* obj) const {
Mathieu Chartier0f72e412013-09-06 16:40:01 -07001874 LOG(ERROR) << "Would have rescanned object " << obj;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001875 }
1876};
1877
Ian Rogers1d54e732013-05-02 21:10:01 -07001878// Verify a reference from an object.
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001879class VerifyReferenceVisitor {
1880 public:
Brian Carlstrom93ba8932013-07-17 21:31:49 -07001881 explicit VerifyReferenceVisitor(Heap* heap)
Ian Rogers1d54e732013-05-02 21:10:01 -07001882 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_)
Brian Carlstrom93ba8932013-07-17 21:31:49 -07001883 : heap_(heap), failed_(false) {}
Ian Rogers1d54e732013-05-02 21:10:01 -07001884
1885 bool Failed() const {
1886 return failed_;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001887 }
1888
1889 // TODO: Fix lock analysis to not use NO_THREAD_SAFETY_ANALYSIS, requires support for smarter
Ian Rogers1d54e732013-05-02 21:10:01 -07001890 // analysis on visitors.
Ian Rogersef7d42f2014-01-06 12:55:46 -08001891 void operator()(mirror::Object* obj, mirror::Object* ref,
Brian Carlstromdf629502013-07-17 22:39:56 -07001892 const MemberOffset& offset, bool /* is_static */) const
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001893 NO_THREAD_SAFETY_ANALYSIS {
Mathieu Chartier938a03b2014-01-16 15:10:31 -08001894 if (ref == nullptr || IsLive(ref)) {
1895 // Verify that the reference is live.
1896 return;
1897 }
1898 if (!failed_) {
1899 // Print message on only on first failure to prevent spam.
1900 LOG(ERROR) << "!!!!!!!!!!!!!!Heap corruption detected!!!!!!!!!!!!!!!!!!!";
1901 failed_ = true;
1902 }
1903 if (obj != nullptr) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001904 accounting::CardTable* card_table = heap_->GetCardTable();
1905 accounting::ObjectStack* alloc_stack = heap_->allocation_stack_.get();
1906 accounting::ObjectStack* live_stack = heap_->live_stack_.get();
Mathieu Chartier938a03b2014-01-16 15:10:31 -08001907 byte* card_addr = card_table->CardFromAddr(obj);
1908 LOG(ERROR) << "Object " << obj << " references dead object " << ref << " at offset "
1909 << offset << "\n card value = " << static_cast<int>(*card_addr);
1910 if (heap_->IsValidObjectAddress(obj->GetClass())) {
1911 LOG(ERROR) << "Obj type " << PrettyTypeOf(obj);
1912 } else {
1913 LOG(ERROR) << "Object " << obj << " class(" << obj->GetClass() << ") not a heap address";
Mathieu Chartier0f72e412013-09-06 16:40:01 -07001914 }
Mathieu Chartier938a03b2014-01-16 15:10:31 -08001915
1916 // Attmept to find the class inside of the recently freed objects.
1917 space::ContinuousSpace* ref_space = heap_->FindContinuousSpaceFromObject(ref, true);
1918 if (ref_space != nullptr && ref_space->IsMallocSpace()) {
1919 space::MallocSpace* space = ref_space->AsMallocSpace();
1920 mirror::Class* ref_class = space->FindRecentFreedObject(ref);
1921 if (ref_class != nullptr) {
1922 LOG(ERROR) << "Reference " << ref << " found as a recently freed object with class "
1923 << PrettyClass(ref_class);
Mathieu Chartier0f72e412013-09-06 16:40:01 -07001924 } else {
Mathieu Chartier938a03b2014-01-16 15:10:31 -08001925 LOG(ERROR) << "Reference " << ref << " not found as a recently freed object";
Mathieu Chartier0f72e412013-09-06 16:40:01 -07001926 }
Mathieu Chartier938a03b2014-01-16 15:10:31 -08001927 }
Mathieu Chartier0f72e412013-09-06 16:40:01 -07001928
Mathieu Chartier938a03b2014-01-16 15:10:31 -08001929 if (ref->GetClass() != nullptr && heap_->IsValidObjectAddress(ref->GetClass()) &&
1930 ref->GetClass()->IsClass()) {
1931 LOG(ERROR) << "Ref type " << PrettyTypeOf(ref);
1932 } else {
1933 LOG(ERROR) << "Ref " << ref << " class(" << ref->GetClass()
1934 << ") is not a valid heap address";
1935 }
1936
1937 card_table->CheckAddrIsInCardTable(reinterpret_cast<const byte*>(obj));
1938 void* cover_begin = card_table->AddrFromCard(card_addr);
1939 void* cover_end = reinterpret_cast<void*>(reinterpret_cast<size_t>(cover_begin) +
1940 accounting::CardTable::kCardSize);
1941 LOG(ERROR) << "Card " << reinterpret_cast<void*>(card_addr) << " covers " << cover_begin
1942 << "-" << cover_end;
1943 accounting::SpaceBitmap* bitmap = heap_->GetLiveBitmap()->GetContinuousSpaceBitmap(obj);
1944
1945 if (bitmap == nullptr) {
1946 LOG(ERROR) << "Object " << obj << " has no bitmap";
Mathieu Chartier4e305412014-02-19 10:54:44 -08001947 if (!VerifyClassClass(obj->GetClass())) {
Mathieu Chartier938a03b2014-01-16 15:10:31 -08001948 LOG(ERROR) << "Object " << obj << " failed class verification!";
Mathieu Chartier0f72e412013-09-06 16:40:01 -07001949 }
Mathieu Chartier938a03b2014-01-16 15:10:31 -08001950 } else {
Ian Rogers1d54e732013-05-02 21:10:01 -07001951 // Print out how the object is live.
Mathieu Chartier938a03b2014-01-16 15:10:31 -08001952 if (bitmap->Test(obj)) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001953 LOG(ERROR) << "Object " << obj << " found in live bitmap";
1954 }
Mathieu Chartier0f72e412013-09-06 16:40:01 -07001955 if (alloc_stack->Contains(const_cast<mirror::Object*>(obj))) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001956 LOG(ERROR) << "Object " << obj << " found in allocation stack";
1957 }
Mathieu Chartier0f72e412013-09-06 16:40:01 -07001958 if (live_stack->Contains(const_cast<mirror::Object*>(obj))) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001959 LOG(ERROR) << "Object " << obj << " found in live stack";
1960 }
Mathieu Chartier0f72e412013-09-06 16:40:01 -07001961 if (alloc_stack->Contains(const_cast<mirror::Object*>(ref))) {
1962 LOG(ERROR) << "Ref " << ref << " found in allocation stack";
1963 }
1964 if (live_stack->Contains(const_cast<mirror::Object*>(ref))) {
1965 LOG(ERROR) << "Ref " << ref << " found in live stack";
1966 }
Ian Rogers1d54e732013-05-02 21:10:01 -07001967 // Attempt to see if the card table missed the reference.
1968 ScanVisitor scan_visitor;
1969 byte* byte_cover_begin = reinterpret_cast<byte*>(card_table->AddrFromCard(card_addr));
1970 card_table->Scan(bitmap, byte_cover_begin,
Mathieu Chartier184e3222013-08-03 14:02:57 -07001971 byte_cover_begin + accounting::CardTable::kCardSize, scan_visitor);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001972 }
Mathieu Chartier938a03b2014-01-16 15:10:31 -08001973
1974 // Search to see if any of the roots reference our object.
1975 void* arg = const_cast<void*>(reinterpret_cast<const void*>(obj));
Mathieu Chartier893263b2014-03-04 11:07:42 -08001976 Runtime::Current()->VisitRoots(&RootMatchesObjectVisitor, arg);
Mathieu Chartier938a03b2014-01-16 15:10:31 -08001977
1978 // Search to see if any of the roots reference our reference.
1979 arg = const_cast<void*>(reinterpret_cast<const void*>(ref));
Mathieu Chartier893263b2014-03-04 11:07:42 -08001980 Runtime::Current()->VisitRoots(&RootMatchesObjectVisitor, arg);
Mathieu Chartier938a03b2014-01-16 15:10:31 -08001981 } else {
1982 LOG(ERROR) << "Root " << ref << " is dead with type " << PrettyTypeOf(ref);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001983 }
1984 }
1985
Ian Rogersef7d42f2014-01-06 12:55:46 -08001986 bool IsLive(mirror::Object* obj) const NO_THREAD_SAFETY_ANALYSIS {
Mathieu Chartier0f72e412013-09-06 16:40:01 -07001987 return heap_->IsLiveObjectLocked(obj, true, false, true);
Ian Rogers1d54e732013-05-02 21:10:01 -07001988 }
1989
Mathieu Chartier815873e2014-02-13 18:02:13 -08001990 static void VerifyRoots(mirror::Object** root, void* arg, uint32_t /*thread_id*/,
1991 RootType /*root_type*/) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001992 VerifyReferenceVisitor* visitor = reinterpret_cast<VerifyReferenceVisitor*>(arg);
Mathieu Chartier815873e2014-02-13 18:02:13 -08001993 (*visitor)(nullptr, *root, MemberOffset(0), true);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001994 }
1995
1996 private:
Ian Rogers1d54e732013-05-02 21:10:01 -07001997 Heap* const heap_;
1998 mutable bool failed_;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07001999};
2000
Ian Rogers1d54e732013-05-02 21:10:01 -07002001// Verify all references within an object, for use with HeapBitmap::Visit.
Mathieu Chartierfd678be2012-08-30 14:50:54 -07002002class VerifyObjectVisitor {
2003 public:
Brian Carlstrom93ba8932013-07-17 21:31:49 -07002004 explicit VerifyObjectVisitor(Heap* heap) : heap_(heap), failed_(false) {}
Mathieu Chartierfd678be2012-08-30 14:50:54 -07002005
Mathieu Chartier590fee92013-09-13 13:46:47 -07002006 void operator()(mirror::Object* obj) const
Ian Rogersb726dcb2012-09-05 08:57:23 -07002007 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Ian Rogers1d54e732013-05-02 21:10:01 -07002008 // Note: we are verifying the references in obj but not obj itself, this is because obj must
2009 // be live or else how did we find it in the live bitmap?
2010 VerifyReferenceVisitor visitor(heap_);
Mathieu Chartier0f72e412013-09-06 16:40:01 -07002011 // The class doesn't count as a reference but we should verify it anyways.
Mathieu Chartier590fee92013-09-13 13:46:47 -07002012 collector::MarkSweep::VisitObjectReferences(obj, visitor, true);
2013 if (obj->GetClass()->IsReferenceClass()) {
2014 visitor(obj, heap_->GetReferenceReferent(obj), MemberOffset(0), false);
2015 }
Ian Rogers1d54e732013-05-02 21:10:01 -07002016 failed_ = failed_ || visitor.Failed();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07002017 }
2018
Mathieu Chartier590fee92013-09-13 13:46:47 -07002019 static void VisitCallback(mirror::Object* obj, void* arg)
2020 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
2021 VerifyObjectVisitor* visitor = reinterpret_cast<VerifyObjectVisitor*>(arg);
2022 visitor->operator()(obj);
2023 }
2024
Mathieu Chartierfd678be2012-08-30 14:50:54 -07002025 bool Failed() const {
2026 return failed_;
2027 }
2028
2029 private:
Ian Rogers1d54e732013-05-02 21:10:01 -07002030 Heap* const heap_;
2031 mutable bool failed_;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07002032};
2033
2034// Must do this with mutators suspended since we are directly accessing the allocation stacks.
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07002035bool Heap::VerifyHeapReferences() {
Hiroshi Yamauchi1ed90612014-02-14 15:00:51 -08002036 Thread* self = Thread::Current();
2037 Locks::mutator_lock_->AssertExclusiveHeld(self);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07002038 // Lets sort our allocation stacks so that we can efficiently binary search them.
Ian Rogers1d54e732013-05-02 21:10:01 -07002039 allocation_stack_->Sort();
2040 live_stack_->Sort();
Hiroshi Yamauchi1ed90612014-02-14 15:00:51 -08002041 // Since we sorted the allocation stack content, need to revoke all
2042 // thread-local allocation stacks.
2043 RevokeAllThreadLocalAllocationStacks(self);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07002044 VerifyObjectVisitor visitor(this);
Mathieu Chartier0f72e412013-09-06 16:40:01 -07002045 // Verify objects in the allocation stack since these will be objects which were:
2046 // 1. Allocated prior to the GC (pre GC verification).
2047 // 2. Allocated during the GC (pre sweep GC verification).
Mathieu Chartier0f72e412013-09-06 16:40:01 -07002048 // We don't want to verify the objects in the live stack since they themselves may be
Mathieu Chartierfd678be2012-08-30 14:50:54 -07002049 // pointing to dead objects if they are not reachable.
Mathieu Chartier590fee92013-09-13 13:46:47 -07002050 VisitObjects(VerifyObjectVisitor::VisitCallback, &visitor);
2051 // Verify the roots:
Mathieu Chartier893263b2014-03-04 11:07:42 -08002052 Runtime::Current()->VisitRoots(VerifyReferenceVisitor::VerifyRoots, &visitor);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07002053 if (visitor.Failed()) {
Mathieu Chartier0f72e412013-09-06 16:40:01 -07002054 // Dump mod-union tables.
Mathieu Chartier11409ae2013-09-23 11:49:36 -07002055 for (const auto& table_pair : mod_union_tables_) {
2056 accounting::ModUnionTable* mod_union_table = table_pair.second;
2057 mod_union_table->Dump(LOG(ERROR) << mod_union_table->GetName() << ": ");
2058 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -07002059 DumpSpaces();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07002060 return false;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07002061 }
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07002062 return true;
2063}
2064
2065class VerifyReferenceCardVisitor {
2066 public:
2067 VerifyReferenceCardVisitor(Heap* heap, bool* failed)
2068 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_,
2069 Locks::heap_bitmap_lock_)
Ian Rogers1d54e732013-05-02 21:10:01 -07002070 : heap_(heap), failed_(failed) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07002071 }
2072
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08002073 // TODO: Fix lock analysis to not use NO_THREAD_SAFETY_ANALYSIS, requires support for
2074 // annotalysis on visitors.
Ian Rogersef7d42f2014-01-06 12:55:46 -08002075 void operator()(mirror::Object* obj, mirror::Object* ref, const MemberOffset& offset,
Brian Carlstromdf629502013-07-17 22:39:56 -07002076 bool is_static) const NO_THREAD_SAFETY_ANALYSIS {
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08002077 // Filter out class references since changing an object's class does not mark the card as dirty.
2078 // Also handles large objects, since the only reference they hold is a class reference.
2079 if (ref != NULL && !ref->IsClass()) {
Ian Rogers1d54e732013-05-02 21:10:01 -07002080 accounting::CardTable* card_table = heap_->GetCardTable();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07002081 // If the object is not dirty and it is referencing something in the live stack other than
2082 // class, then it must be on a dirty card.
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07002083 if (!card_table->AddrIsInCardTable(obj)) {
2084 LOG(ERROR) << "Object " << obj << " is not in the address range of the card table";
2085 *failed_ = true;
Mathieu Chartier2b82db42012-11-14 17:29:05 -08002086 } else if (!card_table->IsDirty(obj)) {
Mathieu Chartier938a03b2014-01-16 15:10:31 -08002087 // TODO: Check mod-union tables.
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08002088 // Card should be either kCardDirty if it got re-dirtied after we aged it, or
2089 // kCardDirty - 1 if it didnt get touched since we aged it.
Ian Rogers1d54e732013-05-02 21:10:01 -07002090 accounting::ObjectStack* live_stack = heap_->live_stack_.get();
Mathieu Chartierf082d3c2013-07-29 17:04:07 -07002091 if (live_stack->ContainsSorted(const_cast<mirror::Object*>(ref))) {
2092 if (live_stack->ContainsSorted(const_cast<mirror::Object*>(obj))) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07002093 LOG(ERROR) << "Object " << obj << " found in live stack";
2094 }
2095 if (heap_->GetLiveBitmap()->Test(obj)) {
2096 LOG(ERROR) << "Object " << obj << " found in live bitmap";
2097 }
2098 LOG(ERROR) << "Object " << obj << " " << PrettyTypeOf(obj)
2099 << " references " << ref << " " << PrettyTypeOf(ref) << " in live stack";
2100
2101 // Print which field of the object is dead.
2102 if (!obj->IsObjectArray()) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08002103 mirror::Class* klass = is_static ? obj->AsClass() : obj->GetClass();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07002104 CHECK(klass != NULL);
Ian Rogersef7d42f2014-01-06 12:55:46 -08002105 mirror::ObjectArray<mirror::ArtField>* fields = is_static ? klass->GetSFields()
2106 : klass->GetIFields();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07002107 CHECK(fields != NULL);
2108 for (int32_t i = 0; i < fields->GetLength(); ++i) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08002109 mirror::ArtField* cur = fields->Get(i);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07002110 if (cur->GetOffset().Int32Value() == offset.Int32Value()) {
2111 LOG(ERROR) << (is_static ? "Static " : "") << "field in the live stack is "
2112 << PrettyField(cur);
2113 break;
2114 }
2115 }
2116 } else {
Ian Rogersef7d42f2014-01-06 12:55:46 -08002117 mirror::ObjectArray<mirror::Object>* object_array =
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002118 obj->AsObjectArray<mirror::Object>();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07002119 for (int32_t i = 0; i < object_array->GetLength(); ++i) {
2120 if (object_array->Get(i) == ref) {
2121 LOG(ERROR) << (is_static ? "Static " : "") << "obj[" << i << "] = ref";
2122 }
2123 }
2124 }
2125
2126 *failed_ = true;
2127 }
2128 }
2129 }
2130 }
2131
2132 private:
Ian Rogers1d54e732013-05-02 21:10:01 -07002133 Heap* const heap_;
2134 bool* const failed_;
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07002135};
2136
2137class VerifyLiveStackReferences {
2138 public:
Brian Carlstrom93ba8932013-07-17 21:31:49 -07002139 explicit VerifyLiveStackReferences(Heap* heap)
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07002140 : heap_(heap),
Brian Carlstrom93ba8932013-07-17 21:31:49 -07002141 failed_(false) {}
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07002142
Mathieu Chartier11409ae2013-09-23 11:49:36 -07002143 void operator()(mirror::Object* obj) const
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07002144 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
2145 VerifyReferenceCardVisitor visitor(heap_, const_cast<bool*>(&failed_));
Mathieu Chartier590fee92013-09-13 13:46:47 -07002146 collector::MarkSweep::VisitObjectReferences(const_cast<mirror::Object*>(obj), visitor, true);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07002147 }
2148
2149 bool Failed() const {
2150 return failed_;
2151 }
2152
2153 private:
Ian Rogers1d54e732013-05-02 21:10:01 -07002154 Heap* const heap_;
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07002155 bool failed_;
2156};
2157
2158bool Heap::VerifyMissingCardMarks() {
Hiroshi Yamauchi1ed90612014-02-14 15:00:51 -08002159 Thread* self = Thread::Current();
2160 Locks::mutator_lock_->AssertExclusiveHeld(self);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07002161
Mathieu Chartier2b82db42012-11-14 17:29:05 -08002162 // We need to sort the live stack since we binary search it.
Ian Rogers1d54e732013-05-02 21:10:01 -07002163 live_stack_->Sort();
Hiroshi Yamauchi1ed90612014-02-14 15:00:51 -08002164 // Since we sorted the allocation stack content, need to revoke all
2165 // thread-local allocation stacks.
2166 RevokeAllThreadLocalAllocationStacks(self);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07002167 VerifyLiveStackReferences visitor(this);
2168 GetLiveBitmap()->Visit(visitor);
2169
2170 // We can verify objects in the live stack since none of these should reference dead objects.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002171 for (mirror::Object** it = live_stack_->Begin(); it != live_stack_->End(); ++it) {
Hiroshi Yamauchif5b0e202014-02-11 17:02:22 -08002172 if (!kUseThreadLocalAllocationStack || *it != nullptr) {
2173 visitor(*it);
2174 }
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07002175 }
2176
2177 if (visitor.Failed()) {
2178 DumpSpaces();
2179 return false;
2180 }
2181 return true;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07002182}
2183
Hiroshi Yamauchif5b0e202014-02-11 17:02:22 -08002184void Heap::SwapStacks(Thread* self) {
2185 if (kUseThreadLocalAllocationStack) {
2186 live_stack_->AssertAllZero();
2187 }
Mathieu Chartierd22d5482012-11-06 17:14:12 -08002188 allocation_stack_.swap(live_stack_);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07002189}
2190
Hiroshi Yamauchif5b0e202014-02-11 17:02:22 -08002191void Heap::RevokeAllThreadLocalAllocationStacks(Thread* self) {
Hiroshi Yamauchif5b0e202014-02-11 17:02:22 -08002192 // This must be called only during the pause.
2193 CHECK(Locks::mutator_lock_->IsExclusiveHeld(self));
2194 MutexLock mu(self, *Locks::runtime_shutdown_lock_);
2195 MutexLock mu2(self, *Locks::thread_list_lock_);
2196 std::list<Thread*> thread_list = Runtime::Current()->GetThreadList()->GetList();
2197 for (Thread* t : thread_list) {
2198 t->RevokeThreadLocalAllocationStack();
2199 }
2200}
2201
Mathieu Chartier11409ae2013-09-23 11:49:36 -07002202accounting::ModUnionTable* Heap::FindModUnionTableFromSpace(space::Space* space) {
2203 auto it = mod_union_tables_.find(space);
2204 if (it == mod_union_tables_.end()) {
2205 return nullptr;
2206 }
2207 return it->second;
2208}
2209
Ian Rogers5fe9af72013-11-14 00:17:20 -08002210void Heap::ProcessCards(TimingLogger& timings) {
Ian Rogers1d54e732013-05-02 21:10:01 -07002211 // Clear cards and keep track of cards cleared in the mod-union table.
Mathieu Chartier02e25112013-08-14 16:14:24 -07002212 for (const auto& space : continuous_spaces_) {
Mathieu Chartier11409ae2013-09-23 11:49:36 -07002213 accounting::ModUnionTable* table = FindModUnionTableFromSpace(space);
2214 if (table != nullptr) {
2215 const char* name = space->IsZygoteSpace() ? "ZygoteModUnionClearCards" :
2216 "ImageModUnionClearCards";
Ian Rogers5fe9af72013-11-14 00:17:20 -08002217 TimingLogger::ScopedSplit split(name, &timings);
Mathieu Chartier11409ae2013-09-23 11:49:36 -07002218 table->ClearCards();
Mathieu Chartier590fee92013-09-13 13:46:47 -07002219 } else if (space->GetType() != space::kSpaceTypeBumpPointerSpace) {
Ian Rogers5fe9af72013-11-14 00:17:20 -08002220 TimingLogger::ScopedSplit split("AllocSpaceClearCards", &timings);
Mathieu Chartierd22d5482012-11-06 17:14:12 -08002221 // No mod union table for the AllocSpace. Age the cards so that the GC knows that these cards
2222 // were dirty before the GC started.
Mathieu Chartierbd0a6532014-02-27 11:14:21 -08002223 // TODO: Need to use atomic for the case where aged(cleaning thread) -> dirty(other thread)
2224 // -> clean(cleaning thread).
Mathieu Chartier590fee92013-09-13 13:46:47 -07002225 // The races are we either end up with: Aged card, unaged card. Since we have the checkpoint
Mathieu Chartier938a03b2014-01-16 15:10:31 -08002226 // roots and then we scan / update mod union tables after. We will always scan either card.
Mathieu Chartier590fee92013-09-13 13:46:47 -07002227 // If we end up with the non aged card, we scan it it in the pause.
Mathieu Chartierd22d5482012-11-06 17:14:12 -08002228 card_table_->ModifyCardsAtomic(space->Begin(), space->End(), AgeCardVisitor(), VoidFunctor());
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07002229 }
2230 }
2231}
2232
Mathieu Chartier815873e2014-02-13 18:02:13 -08002233static mirror::Object* IdentityMarkObjectCallback(mirror::Object* obj, void*) {
Mathieu Chartier11409ae2013-09-23 11:49:36 -07002234 return obj;
2235}
2236
Ian Rogers1d54e732013-05-02 21:10:01 -07002237void Heap::PreGcVerification(collector::GarbageCollector* gc) {
Mathieu Chartier2b82db42012-11-14 17:29:05 -08002238 ThreadList* thread_list = Runtime::Current()->GetThreadList();
2239 Thread* self = Thread::Current();
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08002240
Mathieu Chartier2b82db42012-11-14 17:29:05 -08002241 if (verify_pre_gc_heap_) {
2242 thread_list->SuspendAll();
2243 {
2244 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
2245 if (!VerifyHeapReferences()) {
2246 LOG(FATAL) << "Pre " << gc->GetName() << " heap verification failed";
2247 }
2248 }
2249 thread_list->ResumeAll();
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08002250 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -08002251
2252 // Check that all objects which reference things in the live stack are on dirty cards.
2253 if (verify_missing_card_marks_) {
2254 thread_list->SuspendAll();
2255 {
2256 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Hiroshi Yamauchif5b0e202014-02-11 17:02:22 -08002257 SwapStacks(self);
Mathieu Chartier2b82db42012-11-14 17:29:05 -08002258 // Sort the live stack so that we can quickly binary search it later.
2259 if (!VerifyMissingCardMarks()) {
2260 LOG(FATAL) << "Pre " << gc->GetName() << " missing card mark verification failed";
2261 }
Hiroshi Yamauchif5b0e202014-02-11 17:02:22 -08002262 SwapStacks(self);
Mathieu Chartier2b82db42012-11-14 17:29:05 -08002263 }
2264 thread_list->ResumeAll();
2265 }
2266
2267 if (verify_mod_union_table_) {
2268 thread_list->SuspendAll();
2269 ReaderMutexLock reader_lock(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier11409ae2013-09-23 11:49:36 -07002270 for (const auto& table_pair : mod_union_tables_) {
2271 accounting::ModUnionTable* mod_union_table = table_pair.second;
Mathieu Chartier815873e2014-02-13 18:02:13 -08002272 mod_union_table->UpdateAndMarkReferences(IdentityMarkObjectCallback, nullptr);
Mathieu Chartier11409ae2013-09-23 11:49:36 -07002273 mod_union_table->Verify();
2274 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -08002275 thread_list->ResumeAll();
2276 }
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08002277}
2278
Ian Rogers1d54e732013-05-02 21:10:01 -07002279void Heap::PreSweepingGcVerification(collector::GarbageCollector* gc) {
Mathieu Chartier2b82db42012-11-14 17:29:05 -08002280 // Called before sweeping occurs since we want to make sure we are not going so reclaim any
2281 // reachable objects.
2282 if (verify_post_gc_heap_) {
Ian Rogers1d54e732013-05-02 21:10:01 -07002283 Thread* self = Thread::Current();
2284 CHECK_NE(self->GetState(), kRunnable);
Ian Rogers1d54e732013-05-02 21:10:01 -07002285 {
2286 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
2287 // Swapping bound bitmaps does nothing.
2288 gc->SwapBitmaps();
2289 if (!VerifyHeapReferences()) {
Mathieu Chartier0f72e412013-09-06 16:40:01 -07002290 LOG(FATAL) << "Pre sweeping " << gc->GetName() << " GC verification failed";
Ian Rogers1d54e732013-05-02 21:10:01 -07002291 }
2292 gc->SwapBitmaps();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002293 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002294 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -08002295}
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002296
Ian Rogers1d54e732013-05-02 21:10:01 -07002297void Heap::PostGcVerification(collector::GarbageCollector* gc) {
Mathieu Chartier2b82db42012-11-14 17:29:05 -08002298 if (verify_system_weaks_) {
Anwar Ghuloum67f99412013-08-12 14:19:48 -07002299 Thread* self = Thread::Current();
Mathieu Chartier2b82db42012-11-14 17:29:05 -08002300 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Ian Rogers1d54e732013-05-02 21:10:01 -07002301 collector::MarkSweep* mark_sweep = down_cast<collector::MarkSweep*>(gc);
Mathieu Chartier2b82db42012-11-14 17:29:05 -08002302 mark_sweep->VerifySystemWeaks();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002303 }
Carl Shapiro69759ea2011-07-21 18:13:35 -07002304}
2305
Hiroshi Yamauchia4adbfd2014-02-04 18:12:17 -08002306void Heap::PreGcRosAllocVerification(TimingLogger* timings) {
2307 if (verify_pre_gc_rosalloc_) {
2308 TimingLogger::ScopedSplit split("PreGcRosAllocVerification", timings);
2309 for (const auto& space : continuous_spaces_) {
2310 if (space->IsRosAllocSpace()) {
2311 VLOG(heap) << "PreGcRosAllocVerification : " << space->GetName();
2312 space::RosAllocSpace* rosalloc_space = space->AsRosAllocSpace();
2313 rosalloc_space->Verify();
2314 }
2315 }
2316 }
2317}
2318
2319void Heap::PostGcRosAllocVerification(TimingLogger* timings) {
2320 if (verify_post_gc_rosalloc_) {
2321 TimingLogger::ScopedSplit split("PostGcRosAllocVerification", timings);
2322 for (const auto& space : continuous_spaces_) {
2323 if (space->IsRosAllocSpace()) {
2324 VLOG(heap) << "PostGcRosAllocVerification : " << space->GetName();
2325 space::RosAllocSpace* rosalloc_space = space->AsRosAllocSpace();
2326 rosalloc_space->Verify();
2327 }
2328 }
2329 }
2330}
2331
Mathieu Chartier590fee92013-09-13 13:46:47 -07002332collector::GcType Heap::WaitForGcToComplete(Thread* self) {
Mathieu Chartiercaa82d62014-02-02 16:51:17 -08002333 ScopedThreadStateChange tsc(self, kWaitingForGcToComplete);
Mathieu Chartier590fee92013-09-13 13:46:47 -07002334 MutexLock mu(self, *gc_complete_lock_);
2335 return WaitForGcToCompleteLocked(self);
2336}
2337
2338collector::GcType Heap::WaitForGcToCompleteLocked(Thread* self) {
Ian Rogers1d54e732013-05-02 21:10:01 -07002339 collector::GcType last_gc_type = collector::kGcTypeNone;
Mathieu Chartier590fee92013-09-13 13:46:47 -07002340 uint64_t wait_start = NanoTime();
Mathieu Chartierd5a89ee2014-01-31 09:55:13 -08002341 while (collector_type_running_ != kCollectorTypeNone) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07002342 ATRACE_BEGIN("GC: Wait For Completion");
2343 // We must wait, change thread state then sleep on gc_complete_cond_;
2344 gc_complete_cond_->Wait(self);
2345 last_gc_type = last_gc_type_;
Mathieu Chartier752a0e62013-06-27 11:03:27 -07002346 ATRACE_END();
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07002347 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07002348 uint64_t wait_time = NanoTime() - wait_start;
2349 total_wait_time_ += wait_time;
2350 if (wait_time > long_pause_log_threshold_) {
2351 LOG(INFO) << "WaitForGcToComplete blocked for " << PrettyDuration(wait_time);
2352 }
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07002353 return last_gc_type;
Carl Shapiro69759ea2011-07-21 18:13:35 -07002354}
2355
Elliott Hughesc967f782012-04-16 10:23:15 -07002356void Heap::DumpForSigQuit(std::ostream& os) {
Ian Rogers1d54e732013-05-02 21:10:01 -07002357 os << "Heap: " << GetPercentFree() << "% free, " << PrettySize(GetBytesAllocated()) << "/"
Mathieu Chartier2fde5332012-09-14 14:51:54 -07002358 << PrettySize(GetTotalMemory()) << "; " << GetObjectsAllocated() << " objects\n";
Elliott Hughes8b788fe2013-04-17 15:57:01 -07002359 DumpGcPerformanceInfo(os);
Elliott Hughesc967f782012-04-16 10:23:15 -07002360}
2361
2362size_t Heap::GetPercentFree() {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07002363 return static_cast<size_t>(100.0f * static_cast<float>(GetFreeMemory()) / GetTotalMemory());
Elliott Hughesc967f782012-04-16 10:23:15 -07002364}
2365
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002366void Heap::SetIdealFootprint(size_t max_allowed_footprint) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07002367 if (max_allowed_footprint > GetMaxMemory()) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07002368 VLOG(gc) << "Clamp target GC heap from " << PrettySize(max_allowed_footprint) << " to "
Mathieu Chartier2fde5332012-09-14 14:51:54 -07002369 << PrettySize(GetMaxMemory());
2370 max_allowed_footprint = GetMaxMemory();
2371 }
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -07002372 max_allowed_footprint_ = max_allowed_footprint;
Shih-wei Liao8c2f6412011-10-03 22:58:14 -07002373}
2374
Mathieu Chartier590fee92013-09-13 13:46:47 -07002375bool Heap::IsMovableObject(const mirror::Object* obj) const {
2376 if (kMovingCollector) {
2377 DCHECK(!IsInTempSpace(obj));
2378 if (bump_pointer_space_->HasAddress(obj)) {
2379 return true;
2380 }
Mathieu Chartier9be9a7a2014-01-24 14:07:33 -08002381 // TODO: Refactor this logic into the space itself?
2382 // Objects in the main space are only copied during background -> foreground transitions or
2383 // visa versa.
2384 if (main_space_ != nullptr && main_space_->HasAddress(obj) &&
Mathieu Chartier1d27b342014-01-28 12:51:09 -08002385 (IsCompactingGC(background_collector_type_) ||
2386 IsCompactingGC(post_zygote_collector_type_))) {
Mathieu Chartierfc5b5282014-01-09 16:15:36 -08002387 return true;
2388 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07002389 }
2390 return false;
2391}
2392
2393bool Heap::IsInTempSpace(const mirror::Object* obj) const {
2394 if (temp_space_->HasAddress(obj) && !temp_space_->Contains(obj)) {
2395 return true;
2396 }
2397 return false;
2398}
2399
Mathieu Chartier987ccff2013-07-08 11:05:21 -07002400void Heap::UpdateMaxNativeFootprint() {
2401 size_t native_size = native_bytes_allocated_;
2402 // TODO: Tune the native heap utilization to be a value other than the java heap utilization.
2403 size_t target_size = native_size / GetTargetHeapUtilization();
2404 if (target_size > native_size + max_free_) {
2405 target_size = native_size + max_free_;
2406 } else if (target_size < native_size + min_free_) {
2407 target_size = native_size + min_free_;
2408 }
2409 native_footprint_gc_watermark_ = target_size;
2410 native_footprint_limit_ = 2 * target_size - native_size;
2411}
2412
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -07002413void Heap::GrowForUtilization(collector::GcType gc_type, uint64_t gc_duration) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07002414 // We know what our utilization is at this moment.
2415 // This doesn't actually resize any memory. It just lets the heap grow more when necessary.
Mathieu Chartier65db8802012-11-20 12:36:46 -08002416 const size_t bytes_allocated = GetBytesAllocated();
2417 last_gc_size_ = bytes_allocated;
Ian Rogers1d54e732013-05-02 21:10:01 -07002418 last_gc_time_ns_ = NanoTime();
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -07002419 size_t target_size;
2420 if (gc_type != collector::kGcTypeSticky) {
2421 // Grow the heap for non sticky GC.
2422 target_size = bytes_allocated / GetTargetHeapUtilization();
2423 if (target_size > bytes_allocated + max_free_) {
2424 target_size = bytes_allocated + max_free_;
2425 } else if (target_size < bytes_allocated + min_free_) {
2426 target_size = bytes_allocated + min_free_;
2427 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07002428 native_need_to_run_finalization_ = true;
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -07002429 next_gc_type_ = collector::kGcTypeSticky;
2430 } else {
2431 // Based on how close the current heap size is to the target size, decide
2432 // whether or not to do a partial or sticky GC next.
2433 if (bytes_allocated + min_free_ <= max_allowed_footprint_) {
2434 next_gc_type_ = collector::kGcTypeSticky;
2435 } else {
Mathieu Chartier74762802014-01-24 10:21:35 -08002436 next_gc_type_ = have_zygote_space_ ? collector::kGcTypePartial : collector::kGcTypeFull;
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -07002437 }
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -07002438 // If we have freed enough memory, shrink the heap back down.
2439 if (bytes_allocated + max_free_ < max_allowed_footprint_) {
2440 target_size = bytes_allocated + max_free_;
2441 } else {
2442 target_size = std::max(bytes_allocated, max_allowed_footprint_);
2443 }
2444 }
Mathieu Chartier2775ee42013-08-20 17:43:47 -07002445 if (!ignore_max_footprint_) {
2446 SetIdealFootprint(target_size);
Mathieu Chartier7bf82af2013-12-06 16:51:45 -08002447 if (concurrent_gc_) {
Mathieu Chartier2775ee42013-08-20 17:43:47 -07002448 // Calculate when to perform the next ConcurrentGC.
Mathieu Chartier2775ee42013-08-20 17:43:47 -07002449 // Calculate the estimated GC duration.
Mathieu Chartier74762802014-01-24 10:21:35 -08002450 const double gc_duration_seconds = NsToMs(gc_duration) / 1000.0;
Mathieu Chartier2775ee42013-08-20 17:43:47 -07002451 // Estimate how many remaining bytes we will have when we need to start the next GC.
2452 size_t remaining_bytes = allocation_rate_ * gc_duration_seconds;
Mathieu Chartier74762802014-01-24 10:21:35 -08002453 remaining_bytes = std::min(remaining_bytes, kMaxConcurrentRemainingBytes);
Mathieu Chartier2775ee42013-08-20 17:43:47 -07002454 remaining_bytes = std::max(remaining_bytes, kMinConcurrentRemainingBytes);
2455 if (UNLIKELY(remaining_bytes > max_allowed_footprint_)) {
2456 // A never going to happen situation that from the estimated allocation rate we will exceed
2457 // the applications entire footprint with the given estimated allocation rate. Schedule
Mathieu Chartier74762802014-01-24 10:21:35 -08002458 // another GC nearly straight away.
2459 remaining_bytes = kMinConcurrentRemainingBytes;
Mathieu Chartier2775ee42013-08-20 17:43:47 -07002460 }
Mathieu Chartier74762802014-01-24 10:21:35 -08002461 DCHECK_LE(remaining_bytes, max_allowed_footprint_);
Mathieu Chartier2775ee42013-08-20 17:43:47 -07002462 DCHECK_LE(max_allowed_footprint_, growth_limit_);
Mathieu Chartier74762802014-01-24 10:21:35 -08002463 // Start a concurrent GC when we get close to the estimated remaining bytes. When the
2464 // allocation rate is very high, remaining_bytes could tell us that we should start a GC
2465 // right away.
2466 concurrent_start_bytes_ = std::max(max_allowed_footprint_ - remaining_bytes, bytes_allocated);
Mathieu Chartier65db8802012-11-20 12:36:46 -08002467 }
Mathieu Chartier65db8802012-11-20 12:36:46 -08002468 }
Carl Shapiro69759ea2011-07-21 18:13:35 -07002469}
2470
jeffhaoc1160702011-10-27 15:48:45 -07002471void Heap::ClearGrowthLimit() {
Mathieu Chartier80de7a62012-11-27 17:21:50 -08002472 growth_limit_ = capacity_;
Mathieu Chartier590fee92013-09-13 13:46:47 -07002473 non_moving_space_->ClearGrowthLimit();
jeffhaoc1160702011-10-27 15:48:45 -07002474}
2475
Elliott Hughesadb460d2011-10-05 17:02:34 -07002476void Heap::SetReferenceOffsets(MemberOffset reference_referent_offset,
Mathieu Chartier50482232013-11-21 11:48:14 -08002477 MemberOffset reference_queue_offset,
2478 MemberOffset reference_queueNext_offset,
2479 MemberOffset reference_pendingNext_offset,
2480 MemberOffset finalizer_reference_zombie_offset) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07002481 reference_referent_offset_ = reference_referent_offset;
2482 reference_queue_offset_ = reference_queue_offset;
2483 reference_queueNext_offset_ = reference_queueNext_offset;
2484 reference_pendingNext_offset_ = reference_pendingNext_offset;
2485 finalizer_reference_zombie_offset_ = finalizer_reference_zombie_offset;
2486 CHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
2487 CHECK_NE(reference_queue_offset_.Uint32Value(), 0U);
2488 CHECK_NE(reference_queueNext_offset_.Uint32Value(), 0U);
2489 CHECK_NE(reference_pendingNext_offset_.Uint32Value(), 0U);
2490 CHECK_NE(finalizer_reference_zombie_offset_.Uint32Value(), 0U);
2491}
2492
Mathieu Chartier590fee92013-09-13 13:46:47 -07002493void Heap::SetReferenceReferent(mirror::Object* reference, mirror::Object* referent) {
2494 DCHECK(reference != NULL);
2495 DCHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01002496 reference->SetFieldObject<false, false>(reference_referent_offset_, referent, true);
Mathieu Chartier590fee92013-09-13 13:46:47 -07002497}
2498
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002499mirror::Object* Heap::GetReferenceReferent(mirror::Object* reference) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07002500 DCHECK(reference != NULL);
2501 DCHECK_NE(reference_referent_offset_.Uint32Value(), 0U);
Ian Rogersef7d42f2014-01-06 12:55:46 -08002502 return reference->GetFieldObject<mirror::Object>(reference_referent_offset_, true);
Elliott Hughesadb460d2011-10-05 17:02:34 -07002503}
2504
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002505void Heap::AddFinalizerReference(Thread* self, mirror::Object* object) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002506 ScopedObjectAccess soa(self);
Jeff Hao5d917302013-02-27 17:57:33 -08002507 JValue result;
Ian Rogers0177e532014-02-11 16:30:46 -08002508 ArgArray arg_array("VL", 2);
Ian Rogersef7d42f2014-01-06 12:55:46 -08002509 arg_array.Append(object);
Jeff Hao5d917302013-02-27 17:57:33 -08002510 soa.DecodeMethod(WellKnownClasses::java_lang_ref_FinalizerReference_add)->Invoke(self,
Ian Rogers0177e532014-02-11 16:30:46 -08002511 arg_array.GetArray(), arg_array.GetNumBytes(), &result, "VL");
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002512}
2513
Mathieu Chartier39e32612013-11-12 16:28:05 -08002514void Heap::EnqueueClearedReferences() {
Mathieu Chartierd5a89ee2014-01-31 09:55:13 -08002515 Thread* self = Thread::Current();
2516 Locks::mutator_lock_->AssertNotHeld(self);
Mathieu Chartier39e32612013-11-12 16:28:05 -08002517 if (!cleared_references_.IsEmpty()) {
Ian Rogers64b6d142012-10-29 16:34:15 -07002518 // When a runtime isn't started there are no reference queues to care about so ignore.
2519 if (LIKELY(Runtime::Current()->IsStarted())) {
Mathieu Chartierd5a89ee2014-01-31 09:55:13 -08002520 ScopedObjectAccess soa(self);
Jeff Hao5d917302013-02-27 17:57:33 -08002521 JValue result;
Ian Rogers0177e532014-02-11 16:30:46 -08002522 ArgArray arg_array("VL", 2);
Ian Rogersef7d42f2014-01-06 12:55:46 -08002523 arg_array.Append(cleared_references_.GetList());
Jeff Hao5d917302013-02-27 17:57:33 -08002524 soa.DecodeMethod(WellKnownClasses::java_lang_ref_ReferenceQueue_add)->Invoke(soa.Self(),
Ian Rogers0177e532014-02-11 16:30:46 -08002525 arg_array.GetArray(), arg_array.GetNumBytes(), &result, "VL");
Ian Rogers64b6d142012-10-29 16:34:15 -07002526 }
Mathieu Chartier39e32612013-11-12 16:28:05 -08002527 cleared_references_.Clear();
Elliott Hughesadb460d2011-10-05 17:02:34 -07002528 }
2529}
2530
Ian Rogers1f539342012-10-03 21:09:42 -07002531void Heap::RequestConcurrentGC(Thread* self) {
Mathieu Chartier069387a2012-06-18 12:01:01 -07002532 // Make sure that we can do a concurrent GC.
Ian Rogers120f1c72012-09-28 17:17:10 -07002533 Runtime* runtime = Runtime::Current();
Mathieu Chartier590fee92013-09-13 13:46:47 -07002534 if (runtime == NULL || !runtime->IsFinishedStarting() || runtime->IsShuttingDown(self) ||
2535 self->IsHandlingStackOverflow()) {
Ian Rogers120f1c72012-09-28 17:17:10 -07002536 return;
2537 }
Mathieu Chartier987ccff2013-07-08 11:05:21 -07002538 // We already have a request pending, no reason to start more until we update
2539 // concurrent_start_bytes_.
2540 concurrent_start_bytes_ = std::numeric_limits<size_t>::max();
Ian Rogers120f1c72012-09-28 17:17:10 -07002541 JNIEnv* env = self->GetJniEnv();
Mathieu Chartier590fee92013-09-13 13:46:47 -07002542 DCHECK(WellKnownClasses::java_lang_Daemons != nullptr);
2543 DCHECK(WellKnownClasses::java_lang_Daemons_requestGC != nullptr);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002544 env->CallStaticVoidMethod(WellKnownClasses::java_lang_Daemons,
2545 WellKnownClasses::java_lang_Daemons_requestGC);
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07002546 CHECK(!env->ExceptionCheck());
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07002547}
2548
Ian Rogers81d425b2012-09-27 16:03:43 -07002549void Heap::ConcurrentGC(Thread* self) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07002550 if (Runtime::Current()->IsShuttingDown(self)) {
2551 return;
Mathieu Chartier2542d662012-06-21 17:14:11 -07002552 }
Mathieu Chartier65db8802012-11-20 12:36:46 -08002553 // Wait for any GCs currently running to finish.
Mathieu Chartier590fee92013-09-13 13:46:47 -07002554 if (WaitForGcToComplete(self) == collector::kGcTypeNone) {
Mathieu Chartierf9ed0d32013-11-21 16:42:47 -08002555 // If the we can't run the GC type we wanted to run, find the next appropriate one and try that
2556 // instead. E.g. can't do partial, so do full instead.
2557 if (CollectGarbageInternal(next_gc_type_, kGcCauseBackground, false) ==
2558 collector::kGcTypeNone) {
2559 for (collector::GcType gc_type : gc_plan_) {
2560 // Attempt to run the collector, if we succeed, we are done.
2561 if (gc_type > next_gc_type_ &&
2562 CollectGarbageInternal(gc_type, kGcCauseBackground, false) != collector::kGcTypeNone) {
2563 break;
2564 }
2565 }
2566 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -07002567 }
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07002568}
2569
Mathieu Chartiera5f9de02014-02-28 16:48:42 -08002570void Heap::RequestHeapTransition(CollectorType desired_collector_type, uint64_t delta_time) {
2571 Thread* self = Thread::Current();
2572 {
2573 MutexLock mu(self, *heap_trim_request_lock_);
2574 if (desired_collector_type_ == desired_collector_type) {
2575 return;
2576 }
2577 heap_transition_target_time_ = std::max(heap_transition_target_time_, NanoTime() + delta_time);
2578 desired_collector_type_ = desired_collector_type;
2579 }
2580 SignalHeapTrimDaemon(self);
2581}
2582
2583void Heap::RequestHeapTrim(uint64_t delta_time) {
Ian Rogers48931882013-01-22 14:35:16 -08002584 // GC completed and now we must decide whether to request a heap trim (advising pages back to the
2585 // kernel) or not. Issuing a request will also cause trimming of the libc heap. As a trim scans
2586 // a space it will hold its lock and can become a cause of jank.
2587 // Note, the large object space self trims and the Zygote space was trimmed and unchanging since
2588 // forking.
2589
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08002590 // We don't have a good measure of how worthwhile a trim might be. We can't use the live bitmap
2591 // because that only marks object heads, so a large array looks like lots of empty space. We
2592 // don't just call dlmalloc all the time, because the cost of an _attempted_ trim is proportional
2593 // to utilization (which is probably inversely proportional to how much benefit we can expect).
2594 // We could try mincore(2) but that's only a measure of how many pages we haven't given away,
2595 // not how much use we're making of those pages.
Ian Rogers120f1c72012-09-28 17:17:10 -07002596
2597 Thread* self = Thread::Current();
Mathieu Chartier590fee92013-09-13 13:46:47 -07002598 Runtime* runtime = Runtime::Current();
2599 if (runtime == nullptr || !runtime->IsFinishedStarting() || runtime->IsShuttingDown(self)) {
2600 // Heap trimming isn't supported without a Java runtime or Daemons (such as at dex2oat time)
2601 // Also: we do not wish to start a heap trim if the runtime is shutting down (a racy check
2602 // as we don't hold the lock while requesting the trim).
2603 return;
Ian Rogerse1d490c2012-02-03 09:09:07 -08002604 }
Ian Rogers48931882013-01-22 14:35:16 -08002605
Mathieu Chartiera5f9de02014-02-28 16:48:42 -08002606 // Request a heap trim only if we do not currently care about pause times.
Mathieu Chartierca2a24d2013-11-25 15:12:12 -08002607 if (!CareAboutPauseTimes()) {
Mathieu Chartiera5f9de02014-02-28 16:48:42 -08002608 {
2609 MutexLock mu(self, *heap_trim_request_lock_);
2610 heap_trim_target_time_ = std::max(heap_trim_target_time_, NanoTime() + delta_time);
2611 heap_trim_request_pending_ = true;
2612 }
2613 // Notify the daemon thread which will actually do the heap trim.
2614 SignalHeapTrimDaemon(self);
Mathieu Chartierc39e3422013-08-07 16:41:36 -07002615 }
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08002616}
2617
Mathieu Chartiera5f9de02014-02-28 16:48:42 -08002618void Heap::SignalHeapTrimDaemon(Thread* self) {
2619 JNIEnv* env = self->GetJniEnv();
2620 DCHECK(WellKnownClasses::java_lang_Daemons != nullptr);
2621 DCHECK(WellKnownClasses::java_lang_Daemons_requestHeapTrim != nullptr);
2622 env->CallStaticVoidMethod(WellKnownClasses::java_lang_Daemons,
2623 WellKnownClasses::java_lang_Daemons_requestHeapTrim);
2624 CHECK(!env->ExceptionCheck());
2625}
2626
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -07002627void Heap::RevokeThreadLocalBuffers(Thread* thread) {
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08002628 if (rosalloc_space_ != nullptr) {
2629 rosalloc_space_->RevokeThreadLocalBuffers(thread);
2630 }
Mathieu Chartier692fafd2013-11-29 17:24:40 -08002631 if (bump_pointer_space_ != nullptr) {
2632 bump_pointer_space_->RevokeThreadLocalBuffers(thread);
2633 }
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -07002634}
2635
2636void Heap::RevokeAllThreadLocalBuffers() {
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08002637 if (rosalloc_space_ != nullptr) {
2638 rosalloc_space_->RevokeAllThreadLocalBuffers();
2639 }
Mathieu Chartier692fafd2013-11-29 17:24:40 -08002640 if (bump_pointer_space_ != nullptr) {
2641 bump_pointer_space_->RevokeAllThreadLocalBuffers();
2642 }
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -07002643}
2644
Mathieu Chartier987ccff2013-07-08 11:05:21 -07002645bool Heap::IsGCRequestPending() const {
2646 return concurrent_start_bytes_ != std::numeric_limits<size_t>::max();
2647}
2648
Mathieu Chartier590fee92013-09-13 13:46:47 -07002649void Heap::RunFinalization(JNIEnv* env) {
2650 // Can't do this in WellKnownClasses::Init since System is not properly set up at that point.
2651 if (WellKnownClasses::java_lang_System_runFinalization == nullptr) {
2652 CHECK(WellKnownClasses::java_lang_System != nullptr);
2653 WellKnownClasses::java_lang_System_runFinalization =
2654 CacheMethod(env, WellKnownClasses::java_lang_System, true, "runFinalization", "()V");
2655 CHECK(WellKnownClasses::java_lang_System_runFinalization != nullptr);
2656 }
2657 env->CallStaticVoidMethod(WellKnownClasses::java_lang_System,
2658 WellKnownClasses::java_lang_System_runFinalization);
2659}
2660
Ian Rogers1eb512d2013-10-18 15:42:20 -07002661void Heap::RegisterNativeAllocation(JNIEnv* env, int bytes) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07002662 Thread* self = ThreadForEnv(env);
2663 if (native_need_to_run_finalization_) {
2664 RunFinalization(env);
2665 UpdateMaxNativeFootprint();
2666 native_need_to_run_finalization_ = false;
2667 }
Mathieu Chartier987ccff2013-07-08 11:05:21 -07002668 // Total number of native bytes allocated.
Ian Rogersb122a4b2013-11-19 18:00:50 -08002669 native_bytes_allocated_.FetchAndAdd(bytes);
Mathieu Chartier987ccff2013-07-08 11:05:21 -07002670 if (static_cast<size_t>(native_bytes_allocated_) > native_footprint_gc_watermark_) {
Mathieu Chartiercbb2d202013-11-14 17:45:16 -08002671 collector::GcType gc_type = have_zygote_space_ ? collector::kGcTypePartial :
2672 collector::kGcTypeFull;
2673
Mathieu Chartier987ccff2013-07-08 11:05:21 -07002674 // The second watermark is higher than the gc watermark. If you hit this it means you are
2675 // allocating native objects faster than the GC can keep up with.
2676 if (static_cast<size_t>(native_bytes_allocated_) > native_footprint_limit_) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07002677 if (WaitForGcToComplete(self) != collector::kGcTypeNone) {
2678 // Just finished a GC, attempt to run finalizers.
2679 RunFinalization(env);
2680 CHECK(!env->ExceptionCheck());
2681 }
2682 // If we still are over the watermark, attempt a GC for alloc and run finalizers.
2683 if (static_cast<size_t>(native_bytes_allocated_) > native_footprint_limit_) {
Hiroshi Yamauchi6f4ffe42014-01-13 12:30:44 -08002684 CollectGarbageInternal(gc_type, kGcCauseForNativeAlloc, false);
Mathieu Chartier590fee92013-09-13 13:46:47 -07002685 RunFinalization(env);
2686 native_need_to_run_finalization_ = false;
2687 CHECK(!env->ExceptionCheck());
2688 }
2689 // We have just run finalizers, update the native watermark since it is very likely that
2690 // finalizers released native managed allocations.
2691 UpdateMaxNativeFootprint();
2692 } else if (!IsGCRequestPending()) {
Mathieu Chartier7bf82af2013-12-06 16:51:45 -08002693 if (concurrent_gc_) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07002694 RequestConcurrentGC(self);
2695 } else {
Mathieu Chartiercbb2d202013-11-14 17:45:16 -08002696 CollectGarbageInternal(gc_type, kGcCauseForAlloc, false);
Mathieu Chartier987ccff2013-07-08 11:05:21 -07002697 }
2698 }
2699 }
2700}
2701
Ian Rogers1eb512d2013-10-18 15:42:20 -07002702void Heap::RegisterNativeFree(JNIEnv* env, int bytes) {
Mathieu Chartier987ccff2013-07-08 11:05:21 -07002703 int expected_size, new_size;
2704 do {
Ian Rogersb122a4b2013-11-19 18:00:50 -08002705 expected_size = native_bytes_allocated_.Load();
Mathieu Chartier590fee92013-09-13 13:46:47 -07002706 new_size = expected_size - bytes;
2707 if (UNLIKELY(new_size < 0)) {
2708 ScopedObjectAccess soa(env);
2709 env->ThrowNew(WellKnownClasses::java_lang_RuntimeException,
2710 StringPrintf("Attempted to free %d native bytes with only %d native bytes "
2711 "registered as allocated", bytes, expected_size).c_str());
2712 break;
2713 }
Ian Rogersb122a4b2013-11-19 18:00:50 -08002714 } while (!native_bytes_allocated_.CompareAndSwap(expected_size, new_size));
Mathieu Chartier987ccff2013-07-08 11:05:21 -07002715}
2716
Ian Rogersef7d42f2014-01-06 12:55:46 -08002717size_t Heap::GetTotalMemory() const {
2718 size_t ret = 0;
Mathieu Chartier02e25112013-08-14 16:14:24 -07002719 for (const auto& space : continuous_spaces_) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07002720 // Currently don't include the image space.
2721 if (!space->IsImageSpace()) {
2722 ret += space->Size();
Hiroshi Yamauchi09b07a92013-07-15 13:17:06 -07002723 }
2724 }
Mathieu Chartier02e25112013-08-14 16:14:24 -07002725 for (const auto& space : discontinuous_spaces_) {
Hiroshi Yamauchi09b07a92013-07-15 13:17:06 -07002726 if (space->IsLargeObjectSpace()) {
2727 ret += space->AsLargeObjectSpace()->GetBytesAllocated();
2728 }
2729 }
2730 return ret;
2731}
2732
Mathieu Chartier11409ae2013-09-23 11:49:36 -07002733void Heap::AddModUnionTable(accounting::ModUnionTable* mod_union_table) {
2734 DCHECK(mod_union_table != nullptr);
2735 mod_union_tables_.Put(mod_union_table->GetSpace(), mod_union_table);
2736}
2737
Mathieu Chartierc645f1d2014-03-06 18:11:53 -08002738void Heap::CheckPreconditionsForAllocObject(mirror::Class* c, size_t byte_count) {
2739 CHECK(c == NULL || (c->IsClassClass() && byte_count >= sizeof(mirror::Class)) ||
2740 (c->IsVariableSize() || c->GetObjectSize() == byte_count) ||
2741 strlen(ClassHelper(c).GetDescriptor()) == 0);
2742 CHECK_GE(byte_count, sizeof(mirror::Object));
2743}
2744
Ian Rogers1d54e732013-05-02 21:10:01 -07002745} // namespace gc
Carl Shapiro69759ea2011-07-21 18:13:35 -07002746} // namespace art