blob: c2baa29f6161ea0d8aa15f934c56ff4722911c77 [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>
Ian Rogers700a4022014-05-19 16:49:03 -070023#include <memory>
Carl Shapiro58551df2011-07-24 03:09:51 -070024#include <vector>
25
Mathieu Chartierbad02672014-08-25 13:08:22 -070026#include "base/allocator.h"
Ian Rogersc7dd2952014-10-21 23:31:19 -070027#include "base/dumpable.h"
Mathieu Chartierb2f99362013-11-20 17:26:00 -080028#include "base/histogram-inl.h"
Elliott Hughes1aa246d2012-12-13 09:29:36 -080029#include "base/stl_util.h"
Mathieu Chartier987ccff2013-07-08 11:05:21 -070030#include "common_throws.h"
Ian Rogers48931882013-01-22 14:35:16 -080031#include "cutils/sched_policy.h"
Elliott Hughes767a1472011-10-26 18:49:02 -070032#include "debugger.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070033#include "gc/accounting/atomic_stack.h"
34#include "gc/accounting/card_table-inl.h"
35#include "gc/accounting/heap_bitmap-inl.h"
Mathieu Chartier590fee92013-09-13 13:46:47 -070036#include "gc/accounting/mod_union_table.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070037#include "gc/accounting/mod_union_table-inl.h"
Hiroshi Yamauchi38e68e92014-03-07 13:59:08 -080038#include "gc/accounting/remembered_set.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070039#include "gc/accounting/space_bitmap-inl.h"
Hiroshi Yamauchid5307ec2014-03-27 21:07:51 -070040#include "gc/collector/concurrent_copying.h"
Mathieu Chartier52e4b432014-06-10 11:22:31 -070041#include "gc/collector/mark_compact.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070042#include "gc/collector/mark_sweep-inl.h"
43#include "gc/collector/partial_mark_sweep.h"
Mathieu Chartier590fee92013-09-13 13:46:47 -070044#include "gc/collector/semi_space.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070045#include "gc/collector/sticky_mark_sweep.h"
Mathieu Chartier78f7b4c2014-05-06 10:57:27 -070046#include "gc/reference_processor.h"
Mathieu Chartier590fee92013-09-13 13:46:47 -070047#include "gc/space/bump_pointer_space.h"
Hiroshi Yamauchi50b29282013-07-30 13:58:37 -070048#include "gc/space/dlmalloc_space-inl.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070049#include "gc/space/image_space.h"
50#include "gc/space/large_object_space.h"
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -070051#include "gc/space/rosalloc_space-inl.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070052#include "gc/space/space-inl.h"
Mathieu Chartiera1602f22014-01-13 17:19:19 -080053#include "gc/space/zygote_space.h"
Mathieu Chartierd8891782014-03-02 13:28:37 -080054#include "entrypoints/quick/quick_alloc_entrypoints.h"
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -070055#include "heap-inl.h"
Brian Carlstrom9cff8e12011-08-18 16:47:29 -070056#include "image.h"
Brian Carlstromea46f952013-07-30 01:26:50 -070057#include "mirror/art_field-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080058#include "mirror/class-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080059#include "mirror/object.h"
60#include "mirror/object-inl.h"
61#include "mirror/object_array-inl.h"
Mathieu Chartier8fa2dad2014-03-13 12:22:56 -070062#include "mirror/reference-inl.h"
Brian Carlstrom5643b782012-02-05 12:32:53 -080063#include "os.h"
Ian Rogers53b8b092014-03-13 23:45:53 -070064#include "reflection.h"
Mathieu Chartier0de9f732013-11-22 17:58:48 -080065#include "runtime.h"
Mathieu Chartier7664f5c2012-06-08 18:15:32 -070066#include "ScopedLocalRef.h"
Ian Rogers00f7d0e2012-07-19 15:28:27 -070067#include "scoped_thread_state_change.h"
Mathieu Chartiereb8167a2014-05-07 15:43:14 -070068#include "handle_scope-inl.h"
Elliott Hughes8d768a92011-09-14 16:35:25 -070069#include "thread_list.h"
Elliott Hugheseac76672012-05-24 21:56:51 -070070#include "well_known_classes.h"
Carl Shapiro69759ea2011-07-21 18:13:35 -070071
72namespace art {
Mathieu Chartier50482232013-11-21 11:48:14 -080073
Ian Rogers1d54e732013-05-02 21:10:01 -070074namespace gc {
Carl Shapiro69759ea2011-07-21 18:13:35 -070075
Mathieu Chartier91e30632014-03-25 15:58:50 -070076static constexpr size_t kCollectorTransitionStressIterations = 0;
77static constexpr size_t kCollectorTransitionStressWait = 10 * 1000; // Microseconds
Mathieu Chartier720ef762013-08-17 14:46:54 -070078static constexpr bool kGCALotMode = false;
79static constexpr size_t kGcAlotInterval = KB;
Ian Rogers1d54e732013-05-02 21:10:01 -070080// Minimum amount of remaining bytes before a concurrent GC is triggered.
Mathieu Chartier720ef762013-08-17 14:46:54 -070081static constexpr size_t kMinConcurrentRemainingBytes = 128 * KB;
Mathieu Chartier74762802014-01-24 10:21:35 -080082static constexpr size_t kMaxConcurrentRemainingBytes = 512 * KB;
Mathieu Chartierdf86d1f2014-04-08 13:44:04 -070083// Sticky GC throughput adjustment, divided by 4. Increasing this causes sticky GC to occur more
Mathieu Chartier73d1e172014-04-11 17:53:48 -070084// relative to partial/full GC. This may be desirable since sticky GCs interfere less with mutator
Mathieu Chartierdf86d1f2014-04-08 13:44:04 -070085// threads (lower pauses, use less memory bandwidth).
Mathieu Chartier73d1e172014-04-11 17:53:48 -070086static constexpr double kStickyGcThroughputAdjustment = 1.0;
Mathieu Chartierc1790162014-05-23 10:54:50 -070087// Whether or not we compact the zygote in PreZygoteFork.
Mathieu Chartier31f44142014-04-08 14:40:03 -070088static constexpr bool kCompactZygote = kMovingCollector;
Mathieu Chartierc1790162014-05-23 10:54:50 -070089// How many reserve entries are at the end of the allocation stack, these are only needed if the
90// allocation stack overflows.
91static constexpr size_t kAllocationStackReserveSize = 1024;
92// Default mark stack size in bytes.
93static const size_t kDefaultMarkStackSize = 64 * KB;
Zuo Wangf37a88b2014-07-10 04:26:41 -070094// Define space name.
95static const char* kDlMallocSpaceName[2] = {"main dlmalloc space", "main dlmalloc space 1"};
96static const char* kRosAllocSpaceName[2] = {"main rosalloc space", "main rosalloc space 1"};
97static const char* kMemMapSpaceName[2] = {"main space", "main space 1"};
Mathieu Chartierb363f662014-07-16 13:28:58 -070098static constexpr size_t kGSSBumpPointerSpaceCapacity = 32 * MB;
Mathieu Chartier0051be62012-10-12 17:47:11 -070099
Mathieu Chartier0051be62012-10-12 17:47:11 -0700100Heap::Heap(size_t initial_size, size_t growth_limit, size_t min_free, size_t max_free,
Mathieu Chartier6a7824d2014-08-22 14:53:04 -0700101 double target_utilization, double foreground_heap_growth_multiplier,
102 size_t capacity, size_t non_moving_space_capacity, const std::string& image_file_name,
103 const InstructionSet image_instruction_set, CollectorType foreground_collector_type,
Mathieu Chartier2dbe6272014-09-16 10:43:23 -0700104 CollectorType background_collector_type,
105 space::LargeObjectSpaceType large_object_space_type, size_t large_object_threshold,
106 size_t parallel_gc_threads, size_t conc_gc_threads, bool low_memory_mode,
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800107 size_t long_pause_log_threshold, size_t long_gc_log_threshold,
Mathieu Chartier6f365cc2014-04-23 12:42:27 -0700108 bool ignore_max_footprint, bool use_tlab,
109 bool verify_pre_gc_heap, bool verify_pre_sweeping_heap, bool verify_post_gc_heap,
110 bool verify_pre_gc_rosalloc, bool verify_pre_sweeping_rosalloc,
Zuo Wangf37a88b2014-07-10 04:26:41 -0700111 bool verify_post_gc_rosalloc, bool use_homogeneous_space_compaction_for_oom,
112 uint64_t min_interval_homogeneous_space_compaction_by_oom)
Mathieu Chartiercbb2d202013-11-14 17:45:16 -0800113 : non_moving_space_(nullptr),
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800114 rosalloc_space_(nullptr),
115 dlmalloc_space_(nullptr),
Mathieu Chartierfc5b5282014-01-09 16:15:36 -0800116 main_space_(nullptr),
Mathieu Chartier7bf82af2013-12-06 16:51:45 -0800117 collector_type_(kCollectorTypeNone),
Mathieu Chartier31f44142014-04-08 14:40:03 -0700118 foreground_collector_type_(foreground_collector_type),
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800119 background_collector_type_(background_collector_type),
Mathieu Chartier31f44142014-04-08 14:40:03 -0700120 desired_collector_type_(foreground_collector_type_),
Mathieu Chartiera5f9de02014-02-28 16:48:42 -0800121 heap_trim_request_lock_(nullptr),
Mathieu Chartier7bf52d22014-03-13 14:46:09 -0700122 last_trim_time_(0),
Mathieu Chartierb2728552014-09-08 20:08:41 +0000123 heap_transition_or_trim_target_time_(0),
Mathieu Chartiera5f9de02014-02-28 16:48:42 -0800124 heap_trim_request_pending_(false),
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700125 parallel_gc_threads_(parallel_gc_threads),
126 conc_gc_threads_(conc_gc_threads),
Mathieu Chartiere0a53e92013-08-05 10:17:40 -0700127 low_memory_mode_(low_memory_mode),
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700128 long_pause_log_threshold_(long_pause_log_threshold),
129 long_gc_log_threshold_(long_gc_log_threshold),
130 ignore_max_footprint_(ignore_max_footprint),
Mathieu Chartier8e4a96d2014-05-21 10:44:32 -0700131 zygote_creation_lock_("zygote creation lock", kZygoteCreationLock),
Mathieu Chartiere4cab172014-08-19 18:24:04 -0700132 zygote_space_(nullptr),
Mathieu Chartier2dbe6272014-09-16 10:43:23 -0700133 large_object_threshold_(large_object_threshold),
Mathieu Chartierd5a89ee2014-01-31 09:55:13 -0800134 collector_type_running_(kCollectorTypeNone),
Ian Rogers1d54e732013-05-02 21:10:01 -0700135 last_gc_type_(collector::kGcTypeNone),
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -0700136 next_gc_type_(collector::kGcTypePartial),
Mathieu Chartier80de7a62012-11-27 17:21:50 -0800137 capacity_(capacity),
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700138 growth_limit_(growth_limit),
Mathieu Chartier0051be62012-10-12 17:47:11 -0700139 max_allowed_footprint_(initial_size),
Mathieu Chartier987ccff2013-07-08 11:05:21 -0700140 native_footprint_gc_watermark_(initial_size),
Mathieu Chartier590fee92013-09-13 13:46:47 -0700141 native_need_to_run_finalization_(false),
Mathieu Chartierca2a24d2013-11-25 15:12:12 -0800142 // Initially assume we perceive jank in case the process state is never updated.
143 process_state_(kProcessStateJankPerceptible),
Mathieu Chartier7bf82af2013-12-06 16:51:45 -0800144 concurrent_start_bytes_(std::numeric_limits<size_t>::max()),
Ian Rogers1d54e732013-05-02 21:10:01 -0700145 total_bytes_freed_ever_(0),
146 total_objects_freed_ever_(0),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800147 num_bytes_allocated_(0),
Mathieu Chartier987ccff2013-07-08 11:05:21 -0700148 native_bytes_allocated_(0),
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700149 verify_missing_card_marks_(false),
150 verify_system_weaks_(false),
Mathieu Chartier938a03b2014-01-16 15:10:31 -0800151 verify_pre_gc_heap_(verify_pre_gc_heap),
Mathieu Chartier6f365cc2014-04-23 12:42:27 -0700152 verify_pre_sweeping_heap_(verify_pre_sweeping_heap),
Mathieu Chartier938a03b2014-01-16 15:10:31 -0800153 verify_post_gc_heap_(verify_post_gc_heap),
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700154 verify_mod_union_table_(false),
Hiroshi Yamauchia4adbfd2014-02-04 18:12:17 -0800155 verify_pre_gc_rosalloc_(verify_pre_gc_rosalloc),
Mathieu Chartier6f365cc2014-04-23 12:42:27 -0700156 verify_pre_sweeping_rosalloc_(verify_pre_sweeping_rosalloc),
Hiroshi Yamauchia4adbfd2014-02-04 18:12:17 -0800157 verify_post_gc_rosalloc_(verify_post_gc_rosalloc),
Mathieu Chartieraff59a82014-06-06 17:51:16 -0700158 last_gc_time_ns_(NanoTime()),
Mathieu Chartier65db8802012-11-20 12:36:46 -0800159 allocation_rate_(0),
Mathieu Chartier0418ae22013-07-31 13:35:46 -0700160 /* For GC a lot mode, we limit the allocations stacks to be kGcAlotInterval allocations. This
161 * causes a lot of GC since we do a GC for alloc whenever the stack is full. When heap
162 * verification is enabled, we limit the size of allocation stacks to speed up their
163 * searching.
164 */
165 max_allocation_stack_size_(kGCALotMode ? kGcAlotInterval
Mathieu Chartier4e305412014-02-19 10:54:44 -0800166 : (kVerifyObjectSupport > kVerifyObjectModeFast) ? KB : MB),
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800167 current_allocator_(kAllocatorTypeDlMalloc),
168 current_non_moving_allocator_(kAllocatorTypeNonMoving),
Mathieu Chartier590fee92013-09-13 13:46:47 -0700169 bump_pointer_space_(nullptr),
170 temp_space_(nullptr),
Mathieu Chartier0051be62012-10-12 17:47:11 -0700171 min_free_(min_free),
172 max_free_(max_free),
173 target_utilization_(target_utilization),
Mathieu Chartier2f8da3e2014-04-15 15:37:02 -0700174 foreground_heap_growth_multiplier_(foreground_heap_growth_multiplier),
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700175 total_wait_time_(0),
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700176 total_allocation_time_(0),
Mathieu Chartier4e305412014-02-19 10:54:44 -0800177 verify_object_mode_(kVerifyObjectModeDisabled),
Mathieu Chartier1d27b342014-01-28 12:51:09 -0800178 disable_moving_gc_count_(0),
Mathieu Chartierda44d772014-04-01 15:01:46 -0700179 running_on_valgrind_(Runtime::Current()->RunningOnValgrind()),
Zuo Wangf37a88b2014-07-10 04:26:41 -0700180 use_tlab_(use_tlab),
181 main_space_backup_(nullptr),
Mathieu Chartierb363f662014-07-16 13:28:58 -0700182 min_interval_homogeneous_space_compaction_by_oom_(
183 min_interval_homogeneous_space_compaction_by_oom),
Zuo Wangf37a88b2014-07-10 04:26:41 -0700184 last_time_homogeneous_space_compaction_by_oom_(NanoTime()),
185 use_homogeneous_space_compaction_for_oom_(use_homogeneous_space_compaction_for_oom) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800186 if (VLOG_IS_ON(heap) || VLOG_IS_ON(startup)) {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800187 LOG(INFO) << "Heap() entering";
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700188 }
Mathieu Chartier50482232013-11-21 11:48:14 -0800189 // If we aren't the zygote, switch to the default non zygote allocator. This may update the
190 // entrypoints.
Mathieu Chartier8e219ae2014-08-19 14:29:46 -0700191 const bool is_zygote = Runtime::Current()->IsZygote();
192 if (!is_zygote) {
Mathieu Chartier31f44142014-04-08 14:40:03 -0700193 // Background compaction is currently not supported for command line runs.
194 if (background_collector_type_ != foreground_collector_type_) {
Mathieu Chartier52ba1992014-05-07 14:39:21 -0700195 VLOG(heap) << "Disabling background compaction for non zygote";
Mathieu Chartier31f44142014-04-08 14:40:03 -0700196 background_collector_type_ = foreground_collector_type_;
Mathieu Chartierbd0a6532014-02-27 11:14:21 -0800197 }
Mathieu Chartier50482232013-11-21 11:48:14 -0800198 }
Mathieu Chartiera5f9de02014-02-28 16:48:42 -0800199 ChangeCollector(desired_collector_type_);
Ian Rogers1d54e732013-05-02 21:10:01 -0700200 live_bitmap_.reset(new accounting::HeapBitmap(this));
201 mark_bitmap_.reset(new accounting::HeapBitmap(this));
Ian Rogers30fab402012-01-23 15:43:46 -0800202 // Requested begin for the alloc space, to follow the mapped image and oat files
Ian Rogers13735952014-10-08 12:43:28 -0700203 uint8_t* requested_alloc_space_begin = nullptr;
Brian Carlstrom5643b782012-02-05 12:32:53 -0800204 if (!image_file_name.empty()) {
Alex Light64ad14d2014-08-19 14:23:13 -0700205 std::string error_msg;
Narayan Kamath11d9f062014-04-23 20:24:57 +0100206 space::ImageSpace* image_space = space::ImageSpace::Create(image_file_name.c_str(),
Alex Light64ad14d2014-08-19 14:23:13 -0700207 image_instruction_set,
208 &error_msg);
209 if (image_space != nullptr) {
210 AddSpace(image_space);
211 // Oat files referenced by image files immediately follow them in memory, ensure alloc space
212 // isn't going to get in the middle
Ian Rogers13735952014-10-08 12:43:28 -0700213 uint8_t* oat_file_end_addr = image_space->GetImageHeader().GetOatFileEnd();
Alex Light64ad14d2014-08-19 14:23:13 -0700214 CHECK_GT(oat_file_end_addr, image_space->End());
215 requested_alloc_space_begin = AlignUp(oat_file_end_addr, kPageSize);
216 } else {
217 LOG(WARNING) << "Could not create image space with image file '" << image_file_name << "'. "
218 << "Attempting to fall back to imageless running. Error was: " << error_msg;
219 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700220 }
Zuo Wangf37a88b2014-07-10 04:26:41 -0700221 /*
222 requested_alloc_space_begin -> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
Mathieu Chartier6a7824d2014-08-22 14:53:04 -0700223 +- nonmoving space (non_moving_space_capacity)+-
Zuo Wangf37a88b2014-07-10 04:26:41 -0700224 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
Mathieu Chartier8e219ae2014-08-19 14:29:46 -0700225 +-????????????????????????????????????????????+-
226 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
Mathieu Chartierb363f662014-07-16 13:28:58 -0700227 +-main alloc space / bump space 1 (capacity_) +-
Zuo Wangf37a88b2014-07-10 04:26:41 -0700228 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
Mathieu Chartierb363f662014-07-16 13:28:58 -0700229 +-????????????????????????????????????????????+-
230 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
231 +-main alloc space2 / bump space 2 (capacity_)+-
Zuo Wangf37a88b2014-07-10 04:26:41 -0700232 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
233 */
Mathieu Chartierb363f662014-07-16 13:28:58 -0700234 bool support_homogeneous_space_compaction =
Mathieu Chartier0deeb812014-08-21 18:28:20 -0700235 background_collector_type_ == gc::kCollectorTypeHomogeneousSpaceCompact ||
Zuo Wangf37a88b2014-07-10 04:26:41 -0700236 use_homogeneous_space_compaction_for_oom;
Mathieu Chartierb363f662014-07-16 13:28:58 -0700237 // We may use the same space the main space for the non moving space if we don't need to compact
238 // from the main space.
239 // This is not the case if we support homogeneous compaction or have a moving background
240 // collector type.
Mathieu Chartierb363f662014-07-16 13:28:58 -0700241 bool separate_non_moving_space = is_zygote ||
242 support_homogeneous_space_compaction || IsMovingGc(foreground_collector_type_) ||
243 IsMovingGc(background_collector_type_);
244 if (foreground_collector_type == kCollectorTypeGSS) {
245 separate_non_moving_space = false;
246 }
247 std::unique_ptr<MemMap> main_mem_map_1;
248 std::unique_ptr<MemMap> main_mem_map_2;
Ian Rogers13735952014-10-08 12:43:28 -0700249 uint8_t* request_begin = requested_alloc_space_begin;
Mathieu Chartierb363f662014-07-16 13:28:58 -0700250 if (request_begin != nullptr && separate_non_moving_space) {
Mathieu Chartier6a7824d2014-08-22 14:53:04 -0700251 request_begin += non_moving_space_capacity;
Mathieu Chartierb363f662014-07-16 13:28:58 -0700252 }
253 std::string error_str;
254 std::unique_ptr<MemMap> non_moving_space_mem_map;
255 if (separate_non_moving_space) {
256 // Reserve the non moving mem map before the other two since it needs to be at a specific
257 // address.
258 non_moving_space_mem_map.reset(
259 MemMap::MapAnonymous("non moving space", requested_alloc_space_begin,
Mathieu Chartier6a7824d2014-08-22 14:53:04 -0700260 non_moving_space_capacity, PROT_READ | PROT_WRITE, true, &error_str));
Mathieu Chartierb363f662014-07-16 13:28:58 -0700261 CHECK(non_moving_space_mem_map != nullptr) << error_str;
Mathieu Chartierc44ce2e2014-08-25 16:32:41 -0700262 // Try to reserve virtual memory at a lower address if we have a separate non moving space.
Ian Rogers13735952014-10-08 12:43:28 -0700263 request_begin = reinterpret_cast<uint8_t*>(300 * MB);
Mathieu Chartierb363f662014-07-16 13:28:58 -0700264 }
265 // Attempt to create 2 mem maps at or after the requested begin.
266 main_mem_map_1.reset(MapAnonymousPreferredAddress(kMemMapSpaceName[0], request_begin, capacity_,
267 PROT_READ | PROT_WRITE, &error_str));
268 CHECK(main_mem_map_1.get() != nullptr) << error_str;
269 if (support_homogeneous_space_compaction ||
270 background_collector_type_ == kCollectorTypeSS ||
271 foreground_collector_type_ == kCollectorTypeSS) {
272 main_mem_map_2.reset(MapAnonymousPreferredAddress(kMemMapSpaceName[1], main_mem_map_1->End(),
273 capacity_, PROT_READ | PROT_WRITE,
274 &error_str));
275 CHECK(main_mem_map_2.get() != nullptr) << error_str;
276 }
277 // Create the non moving space first so that bitmaps don't take up the address range.
278 if (separate_non_moving_space) {
Mathieu Chartier31f44142014-04-08 14:40:03 -0700279 // Non moving space is always dlmalloc since we currently don't have support for multiple
Zuo Wangf37a88b2014-07-10 04:26:41 -0700280 // active rosalloc spaces.
Mathieu Chartierb363f662014-07-16 13:28:58 -0700281 const size_t size = non_moving_space_mem_map->Size();
282 non_moving_space_ = space::DlMallocSpace::CreateFromMemMap(
Mathieu Chartier6a7824d2014-08-22 14:53:04 -0700283 non_moving_space_mem_map.release(), "zygote / non moving space", kDefaultStartingSize,
Mathieu Chartierb363f662014-07-16 13:28:58 -0700284 initial_size, size, size, false);
Mathieu Chartier78408882014-04-11 18:06:01 -0700285 non_moving_space_->SetFootprintLimit(non_moving_space_->Capacity());
Mathieu Chartierb363f662014-07-16 13:28:58 -0700286 CHECK(non_moving_space_ != nullptr) << "Failed creating non moving space "
287 << requested_alloc_space_begin;
288 AddSpace(non_moving_space_);
289 }
290 // Create other spaces based on whether or not we have a moving GC.
291 if (IsMovingGc(foreground_collector_type_) && foreground_collector_type_ != kCollectorTypeGSS) {
292 // Create bump pointer spaces.
293 // We only to create the bump pointer if the foreground collector is a compacting GC.
294 // TODO: Place bump-pointer spaces somewhere to minimize size of card table.
295 bump_pointer_space_ = space::BumpPointerSpace::CreateFromMemMap("Bump pointer space 1",
296 main_mem_map_1.release());
297 CHECK(bump_pointer_space_ != nullptr) << "Failed to create bump pointer space";
298 AddSpace(bump_pointer_space_);
299 temp_space_ = space::BumpPointerSpace::CreateFromMemMap("Bump pointer space 2",
300 main_mem_map_2.release());
301 CHECK(temp_space_ != nullptr) << "Failed to create bump pointer space";
302 AddSpace(temp_space_);
303 CHECK(separate_non_moving_space);
Hiroshi Yamauchi5ccd4982014-03-11 12:19:04 -0700304 } else {
Mathieu Chartierb363f662014-07-16 13:28:58 -0700305 CreateMainMallocSpace(main_mem_map_1.release(), initial_size, growth_limit_, capacity_);
306 CHECK(main_space_ != nullptr);
307 AddSpace(main_space_);
308 if (!separate_non_moving_space) {
Zuo Wangf37a88b2014-07-10 04:26:41 -0700309 non_moving_space_ = main_space_;
Mathieu Chartierb363f662014-07-16 13:28:58 -0700310 CHECK(!non_moving_space_->CanMoveObjects());
311 }
312 if (foreground_collector_type_ == kCollectorTypeGSS) {
313 CHECK_EQ(foreground_collector_type_, background_collector_type_);
314 // Create bump pointer spaces instead of a backup space.
315 main_mem_map_2.release();
316 bump_pointer_space_ = space::BumpPointerSpace::Create("Bump pointer space 1",
317 kGSSBumpPointerSpaceCapacity, nullptr);
318 CHECK(bump_pointer_space_ != nullptr);
319 AddSpace(bump_pointer_space_);
320 temp_space_ = space::BumpPointerSpace::Create("Bump pointer space 2",
321 kGSSBumpPointerSpaceCapacity, nullptr);
322 CHECK(temp_space_ != nullptr);
323 AddSpace(temp_space_);
324 } else if (main_mem_map_2.get() != nullptr) {
325 const char* name = kUseRosAlloc ? kRosAllocSpaceName[1] : kDlMallocSpaceName[1];
326 main_space_backup_.reset(CreateMallocSpaceFromMemMap(main_mem_map_2.release(), initial_size,
327 growth_limit_, capacity_, name, true));
328 CHECK(main_space_backup_.get() != nullptr);
329 // Add the space so its accounted for in the heap_begin and heap_end.
330 AddSpace(main_space_backup_.get());
Zuo Wangf37a88b2014-07-10 04:26:41 -0700331 }
Hiroshi Yamauchi5ccd4982014-03-11 12:19:04 -0700332 }
Mathieu Chartier31f44142014-04-08 14:40:03 -0700333 CHECK(non_moving_space_ != nullptr);
Mathieu Chartierb363f662014-07-16 13:28:58 -0700334 CHECK(!non_moving_space_->CanMoveObjects());
Mathieu Chartiereb5710e2013-07-25 15:19:42 -0700335 // Allocate the large object space.
Mathieu Chartier2dbe6272014-09-16 10:43:23 -0700336 if (large_object_space_type == space::kLargeObjectSpaceTypeFreeList) {
337 large_object_space_ = space::FreeListSpace::Create("free list large object space", nullptr,
338 capacity_);
339 CHECK(large_object_space_ != nullptr) << "Failed to create large object space";
340 } else if (large_object_space_type == space::kLargeObjectSpaceTypeMap) {
341 large_object_space_ = space::LargeObjectMapSpace::Create("mem map large object space");
342 CHECK(large_object_space_ != nullptr) << "Failed to create large object space";
Mathieu Chartiereb5710e2013-07-25 15:19:42 -0700343 } else {
Mathieu Chartier2dbe6272014-09-16 10:43:23 -0700344 // Disable the large object space by making the cutoff excessively large.
345 large_object_threshold_ = std::numeric_limits<size_t>::max();
346 large_object_space_ = nullptr;
Mathieu Chartiereb5710e2013-07-25 15:19:42 -0700347 }
Mathieu Chartier2dbe6272014-09-16 10:43:23 -0700348 if (large_object_space_ != nullptr) {
349 AddSpace(large_object_space_);
350 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700351 // Compute heap capacity. Continuous spaces are sorted in order of Begin().
Mathieu Chartier590fee92013-09-13 13:46:47 -0700352 CHECK(!continuous_spaces_.empty());
353 // Relies on the spaces being sorted.
Ian Rogers13735952014-10-08 12:43:28 -0700354 uint8_t* heap_begin = continuous_spaces_.front()->Begin();
355 uint8_t* heap_end = continuous_spaces_.back()->Limit();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700356 size_t heap_capacity = heap_end - heap_begin;
Mathieu Chartierb363f662014-07-16 13:28:58 -0700357 // Remove the main backup space since it slows down the GC to have unused extra spaces.
358 if (main_space_backup_.get() != nullptr) {
359 RemoveSpace(main_space_backup_.get());
360 }
Elliott Hughes6c9c06d2011-11-07 16:43:47 -0800361 // Allocate the card table.
Ian Rogers1d54e732013-05-02 21:10:01 -0700362 card_table_.reset(accounting::CardTable::Create(heap_begin, heap_capacity));
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700363 CHECK(card_table_.get() != NULL) << "Failed to create card table";
Mathieu Chartier590fee92013-09-13 13:46:47 -0700364 // Card cache for now since it makes it easier for us to update the references to the copying
365 // spaces.
Mathieu Chartier11409ae2013-09-23 11:49:36 -0700366 accounting::ModUnionTable* mod_union_table =
Mathieu Chartier0e54cd02014-03-20 12:41:23 -0700367 new accounting::ModUnionTableToZygoteAllocspace("Image mod-union table", this,
368 GetImageSpace());
Mathieu Chartier11409ae2013-09-23 11:49:36 -0700369 CHECK(mod_union_table != nullptr) << "Failed to create image mod-union table";
370 AddModUnionTable(mod_union_table);
Mathieu Chartier96bcd452014-06-17 09:50:02 -0700371 if (collector::SemiSpace::kUseRememberedSet && non_moving_space_ != main_space_) {
Hiroshi Yamauchi38e68e92014-03-07 13:59:08 -0800372 accounting::RememberedSet* non_moving_space_rem_set =
373 new accounting::RememberedSet("Non-moving space remembered set", this, non_moving_space_);
374 CHECK(non_moving_space_rem_set != nullptr) << "Failed to create non-moving space remembered set";
375 AddRememberedSet(non_moving_space_rem_set);
376 }
Mathieu Chartierb363f662014-07-16 13:28:58 -0700377 // TODO: Count objects in the image space here?
Ian Rogers3e5cf302014-05-20 16:40:37 -0700378 num_bytes_allocated_.StoreRelaxed(0);
Mathieu Chartierc1790162014-05-23 10:54:50 -0700379 mark_stack_.reset(accounting::ObjectStack::Create("mark stack", kDefaultMarkStackSize,
380 kDefaultMarkStackSize));
381 const size_t alloc_stack_capacity = max_allocation_stack_size_ + kAllocationStackReserveSize;
382 allocation_stack_.reset(accounting::ObjectStack::Create(
383 "allocation stack", max_allocation_stack_size_, alloc_stack_capacity));
384 live_stack_.reset(accounting::ObjectStack::Create(
385 "live stack", max_allocation_stack_size_, alloc_stack_capacity));
Mathieu Chartier65db8802012-11-20 12:36:46 -0800386 // It's still too early to take a lock because there are no threads yet, but we can create locks
387 // now. We don't create it earlier to make it clear that you can't use locks during heap
388 // initialization.
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700389 gc_complete_lock_ = new Mutex("GC complete lock");
Ian Rogersc604d732012-10-14 16:09:54 -0700390 gc_complete_cond_.reset(new ConditionVariable("GC complete condition variable",
391 *gc_complete_lock_));
Mathieu Chartiera5f9de02014-02-28 16:48:42 -0800392 heap_trim_request_lock_ = new Mutex("Heap trim request lock");
Mathieu Chartier65db8802012-11-20 12:36:46 -0800393 last_gc_size_ = GetBytesAllocated();
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700394 if (ignore_max_footprint_) {
395 SetIdealFootprint(std::numeric_limits<size_t>::max());
Mathieu Chartier590fee92013-09-13 13:46:47 -0700396 concurrent_start_bytes_ = std::numeric_limits<size_t>::max();
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700397 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700398 CHECK_NE(max_allowed_footprint_, 0U);
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800399 // Create our garbage collectors.
Mathieu Chartier50482232013-11-21 11:48:14 -0800400 for (size_t i = 0; i < 2; ++i) {
401 const bool concurrent = i != 0;
402 garbage_collectors_.push_back(new collector::MarkSweep(this, concurrent));
403 garbage_collectors_.push_back(new collector::PartialMarkSweep(this, concurrent));
404 garbage_collectors_.push_back(new collector::StickyMarkSweep(this, concurrent));
405 }
Mathieu Chartier50482232013-11-21 11:48:14 -0800406 if (kMovingCollector) {
407 // TODO: Clean this up.
Zuo Wangf37a88b2014-07-10 04:26:41 -0700408 const bool generational = foreground_collector_type_ == kCollectorTypeGSS;
Hiroshi Yamauchidf386c52014-04-08 16:21:52 -0700409 semi_space_collector_ = new collector::SemiSpace(this, generational,
410 generational ? "generational" : "");
Mathieu Chartier590fee92013-09-13 13:46:47 -0700411 garbage_collectors_.push_back(semi_space_collector_);
Hiroshi Yamauchid5307ec2014-03-27 21:07:51 -0700412 concurrent_copying_collector_ = new collector::ConcurrentCopying(this);
413 garbage_collectors_.push_back(concurrent_copying_collector_);
Mathieu Chartier52e4b432014-06-10 11:22:31 -0700414 mark_compact_collector_ = new collector::MarkCompact(this);
415 garbage_collectors_.push_back(mark_compact_collector_);
Mathieu Chartier0325e622012-09-05 14:22:51 -0700416 }
Andreas Gampee1cb2982014-08-27 11:01:09 -0700417 if (GetImageSpace() != nullptr && non_moving_space_ != nullptr &&
418 (is_zygote || separate_non_moving_space || foreground_collector_type_ == kCollectorTypeGSS)) {
Mathieu Chartierb363f662014-07-16 13:28:58 -0700419 // Check that there's no gap between the image space and the non moving space so that the
Andreas Gampee1cb2982014-08-27 11:01:09 -0700420 // immune region won't break (eg. due to a large object allocated in the gap). This is only
421 // required when we're the zygote or using GSS.
Mathieu Chartierb363f662014-07-16 13:28:58 -0700422 bool no_gap = MemMap::CheckNoGaps(GetImageSpace()->GetMemMap(),
423 non_moving_space_->GetMemMap());
Hiroshi Yamauchi3eed93d2014-06-04 11:43:59 -0700424 if (!no_gap) {
425 MemMap::DumpMaps(LOG(ERROR));
426 LOG(FATAL) << "There's a gap between the image space and the main space";
427 }
428 }
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -0700429 if (running_on_valgrind_) {
Mathieu Chartier9ef78b52014-09-25 17:03:12 -0700430 Runtime::Current()->GetInstrumentation()->InstrumentQuickAllocEntryPoints();
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -0700431 }
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800432 if (VLOG_IS_ON(heap) || VLOG_IS_ON(startup)) {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800433 LOG(INFO) << "Heap() exiting";
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700434 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700435}
436
Ian Rogers13735952014-10-08 12:43:28 -0700437MemMap* Heap::MapAnonymousPreferredAddress(const char* name, uint8_t* request_begin, size_t capacity,
Mathieu Chartierb363f662014-07-16 13:28:58 -0700438 int prot_flags, std::string* out_error_str) {
439 while (true) {
440 MemMap* map = MemMap::MapAnonymous(kMemMapSpaceName[0], request_begin, capacity,
441 PROT_READ | PROT_WRITE, true, out_error_str);
442 if (map != nullptr || request_begin == nullptr) {
443 return map;
444 }
445 // Retry a second time with no specified request begin.
446 request_begin = nullptr;
447 }
448 return nullptr;
449}
450
Zuo Wangf37a88b2014-07-10 04:26:41 -0700451space::MallocSpace* Heap::CreateMallocSpaceFromMemMap(MemMap* mem_map, size_t initial_size,
452 size_t growth_limit, size_t capacity,
453 const char* name, bool can_move_objects) {
454 space::MallocSpace* malloc_space = nullptr;
455 if (kUseRosAlloc) {
456 // Create rosalloc space.
457 malloc_space = space::RosAllocSpace::CreateFromMemMap(mem_map, name, kDefaultStartingSize,
458 initial_size, growth_limit, capacity,
459 low_memory_mode_, can_move_objects);
460 } else {
461 malloc_space = space::DlMallocSpace::CreateFromMemMap(mem_map, name, kDefaultStartingSize,
462 initial_size, growth_limit, capacity,
463 can_move_objects);
464 }
465 if (collector::SemiSpace::kUseRememberedSet) {
466 accounting::RememberedSet* rem_set =
467 new accounting::RememberedSet(std::string(name) + " remembered set", this, malloc_space);
468 CHECK(rem_set != nullptr) << "Failed to create main space remembered set";
469 AddRememberedSet(rem_set);
470 }
471 CHECK(malloc_space != nullptr) << "Failed to create " << name;
472 malloc_space->SetFootprintLimit(malloc_space->Capacity());
473 return malloc_space;
474}
475
Mathieu Chartier31f44142014-04-08 14:40:03 -0700476void Heap::CreateMainMallocSpace(MemMap* mem_map, size_t initial_size, size_t growth_limit,
477 size_t capacity) {
478 // Is background compaction is enabled?
479 bool can_move_objects = IsMovingGc(background_collector_type_) !=
Zuo Wangf37a88b2014-07-10 04:26:41 -0700480 IsMovingGc(foreground_collector_type_) || use_homogeneous_space_compaction_for_oom_;
Mathieu Chartier31f44142014-04-08 14:40:03 -0700481 // If we are the zygote and don't yet have a zygote space, it means that the zygote fork will
482 // happen in the future. If this happens and we have kCompactZygote enabled we wish to compact
483 // from the main space to the zygote space. If background compaction is enabled, always pass in
484 // that we can move objets.
485 if (kCompactZygote && Runtime::Current()->IsZygote() && !can_move_objects) {
486 // After the zygote we want this to be false if we don't have background compaction enabled so
487 // that getting primitive array elements is faster.
Mathieu Chartierb363f662014-07-16 13:28:58 -0700488 // We never have homogeneous compaction with GSS and don't need a space with movable objects.
Mathieu Chartiere4cab172014-08-19 18:24:04 -0700489 can_move_objects = !HasZygoteSpace() && foreground_collector_type_ != kCollectorTypeGSS;
Mathieu Chartier31f44142014-04-08 14:40:03 -0700490 }
Mathieu Chartier96bcd452014-06-17 09:50:02 -0700491 if (collector::SemiSpace::kUseRememberedSet && main_space_ != nullptr) {
492 RemoveRememberedSet(main_space_);
493 }
Zuo Wangf37a88b2014-07-10 04:26:41 -0700494 const char* name = kUseRosAlloc ? kRosAllocSpaceName[0] : kDlMallocSpaceName[0];
495 main_space_ = CreateMallocSpaceFromMemMap(mem_map, initial_size, growth_limit, capacity, name,
496 can_move_objects);
497 SetSpaceAsDefault(main_space_);
Mathieu Chartier31f44142014-04-08 14:40:03 -0700498 VLOG(heap) << "Created main space " << main_space_;
499}
500
Mathieu Chartier50482232013-11-21 11:48:14 -0800501void Heap::ChangeAllocator(AllocatorType allocator) {
Mathieu Chartier50482232013-11-21 11:48:14 -0800502 if (current_allocator_ != allocator) {
Mathieu Chartierd8891782014-03-02 13:28:37 -0800503 // These two allocators are only used internally and don't have any entrypoints.
504 CHECK_NE(allocator, kAllocatorTypeLOS);
505 CHECK_NE(allocator, kAllocatorTypeNonMoving);
Mathieu Chartier50482232013-11-21 11:48:14 -0800506 current_allocator_ = allocator;
Mathieu Chartierd8891782014-03-02 13:28:37 -0800507 MutexLock mu(nullptr, *Locks::runtime_shutdown_lock_);
Mathieu Chartier50482232013-11-21 11:48:14 -0800508 SetQuickAllocEntryPointsAllocator(current_allocator_);
509 Runtime::Current()->GetInstrumentation()->ResetQuickAllocEntryPoints();
510 }
511}
512
Mathieu Chartier6a7824d2014-08-22 14:53:04 -0700513void Heap::DisableMovingGc() {
Mathieu Chartier31f44142014-04-08 14:40:03 -0700514 if (IsMovingGc(foreground_collector_type_)) {
Mathieu Chartier6a7824d2014-08-22 14:53:04 -0700515 foreground_collector_type_ = kCollectorTypeCMS;
Mathieu Chartier6dda8982014-03-06 11:11:48 -0800516 }
Mathieu Chartier31f44142014-04-08 14:40:03 -0700517 if (IsMovingGc(background_collector_type_)) {
518 background_collector_type_ = foreground_collector_type_;
Mathieu Chartier6dda8982014-03-06 11:11:48 -0800519 }
Mathieu Chartier31f44142014-04-08 14:40:03 -0700520 TransitionCollector(foreground_collector_type_);
Mathieu Chartier6a7824d2014-08-22 14:53:04 -0700521 ThreadList* tl = Runtime::Current()->GetThreadList();
522 Thread* self = Thread::Current();
523 ScopedThreadStateChange tsc(self, kSuspended);
524 tl->SuspendAll();
525 // Something may have caused the transition to fail.
Mathieu Chartiere4927f62014-08-23 13:56:03 -0700526 if (!IsMovingGc(collector_type_) && non_moving_space_ != main_space_) {
Mathieu Chartier6a7824d2014-08-22 14:53:04 -0700527 CHECK(main_space_ != nullptr);
528 // The allocation stack may have non movable objects in it. We need to flush it since the GC
529 // can't only handle marking allocation stack objects of one non moving space and one main
530 // space.
531 {
532 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
533 FlushAllocStack();
534 }
535 main_space_->DisableMovingObjects();
536 non_moving_space_ = main_space_;
537 CHECK(!non_moving_space_->CanMoveObjects());
538 }
539 tl->ResumeAll();
Mathieu Chartier6dda8982014-03-06 11:11:48 -0800540}
541
Mathieu Chartier15d34022014-02-26 17:16:38 -0800542std::string Heap::SafeGetClassDescriptor(mirror::Class* klass) {
543 if (!IsValidContinuousSpaceObjectAddress(klass)) {
544 return StringPrintf("<non heap address klass %p>", klass);
545 }
546 mirror::Class* component_type = klass->GetComponentType<kVerifyNone>();
547 if (IsValidContinuousSpaceObjectAddress(component_type) && klass->IsArrayClass<kVerifyNone>()) {
548 std::string result("[");
549 result += SafeGetClassDescriptor(component_type);
550 return result;
551 } else if (UNLIKELY(klass->IsPrimitive<kVerifyNone>())) {
552 return Primitive::Descriptor(klass->GetPrimitiveType<kVerifyNone>());
Mathieu Chartierc2f4d022014-03-03 16:11:42 -0800553 } else if (UNLIKELY(klass->IsProxyClass<kVerifyNone>())) {
Mathieu Chartier15d34022014-02-26 17:16:38 -0800554 return Runtime::Current()->GetClassLinker()->GetDescriptorForProxy(klass);
555 } else {
Mathieu Chartierc2f4d022014-03-03 16:11:42 -0800556 mirror::DexCache* dex_cache = klass->GetDexCache<kVerifyNone>();
Mathieu Chartier15d34022014-02-26 17:16:38 -0800557 if (!IsValidContinuousSpaceObjectAddress(dex_cache)) {
558 return StringPrintf("<non heap address dex_cache %p>", dex_cache);
559 }
560 const DexFile* dex_file = dex_cache->GetDexFile();
561 uint16_t class_def_idx = klass->GetDexClassDefIndex();
562 if (class_def_idx == DexFile::kDexNoIndex16) {
563 return "<class def not found>";
564 }
565 const DexFile::ClassDef& class_def = dex_file->GetClassDef(class_def_idx);
566 const DexFile::TypeId& type_id = dex_file->GetTypeId(class_def.class_idx_);
567 return dex_file->GetTypeDescriptor(type_id);
568 }
569}
570
571std::string Heap::SafePrettyTypeOf(mirror::Object* obj) {
572 if (obj == nullptr) {
573 return "null";
574 }
575 mirror::Class* klass = obj->GetClass<kVerifyNone>();
576 if (klass == nullptr) {
577 return "(class=null)";
578 }
579 std::string result(SafeGetClassDescriptor(klass));
580 if (obj->IsClass()) {
Mathieu Chartierc2f4d022014-03-03 16:11:42 -0800581 result += "<" + SafeGetClassDescriptor(obj->AsClass<kVerifyNone>()) + ">";
Mathieu Chartier15d34022014-02-26 17:16:38 -0800582 }
583 return result;
584}
585
586void Heap::DumpObject(std::ostream& stream, mirror::Object* obj) {
587 if (obj == nullptr) {
588 stream << "(obj=null)";
589 return;
590 }
591 if (IsAligned<kObjectAlignment>(obj)) {
592 space::Space* space = nullptr;
593 // Don't use find space since it only finds spaces which actually contain objects instead of
594 // spaces which may contain objects (e.g. cleared bump pointer spaces).
595 for (const auto& cur_space : continuous_spaces_) {
596 if (cur_space->HasAddress(obj)) {
597 space = cur_space;
598 break;
599 }
600 }
Mathieu Chartier15d34022014-02-26 17:16:38 -0800601 // Unprotect all the spaces.
602 for (const auto& space : continuous_spaces_) {
603 mprotect(space->Begin(), space->Capacity(), PROT_READ | PROT_WRITE);
604 }
605 stream << "Object " << obj;
606 if (space != nullptr) {
607 stream << " in space " << *space;
608 }
Mathieu Chartierc2f4d022014-03-03 16:11:42 -0800609 mirror::Class* klass = obj->GetClass<kVerifyNone>();
Mathieu Chartier15d34022014-02-26 17:16:38 -0800610 stream << "\nclass=" << klass;
611 if (klass != nullptr) {
612 stream << " type= " << SafePrettyTypeOf(obj);
613 }
614 // Re-protect the address we faulted on.
615 mprotect(AlignDown(obj, kPageSize), kPageSize, PROT_NONE);
616 }
617}
618
Mathieu Chartier590fee92013-09-13 13:46:47 -0700619bool Heap::IsCompilingBoot() const {
Alex Light64ad14d2014-08-19 14:23:13 -0700620 if (!Runtime::Current()->IsCompiler()) {
621 return false;
622 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700623 for (const auto& space : continuous_spaces_) {
Mathieu Chartier4e305412014-02-19 10:54:44 -0800624 if (space->IsImageSpace() || space->IsZygoteSpace()) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700625 return false;
626 }
627 }
628 return true;
629}
630
631bool Heap::HasImageSpace() const {
632 for (const auto& space : continuous_spaces_) {
633 if (space->IsImageSpace()) {
634 return true;
635 }
636 }
637 return false;
638}
639
Mathieu Chartier1d27b342014-01-28 12:51:09 -0800640void Heap::IncrementDisableMovingGC(Thread* self) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700641 // Need to do this holding the lock to prevent races where the GC is about to run / running when
642 // we attempt to disable it.
Mathieu Chartiercaa82d62014-02-02 16:51:17 -0800643 ScopedThreadStateChange tsc(self, kWaitingForGcToComplete);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700644 MutexLock mu(self, *gc_complete_lock_);
Mathieu Chartier1d27b342014-01-28 12:51:09 -0800645 ++disable_moving_gc_count_;
Mathieu Chartier31f44142014-04-08 14:40:03 -0700646 if (IsMovingGc(collector_type_running_)) {
Mathieu Chartier89a201e2014-05-02 10:27:26 -0700647 WaitForGcToCompleteLocked(kGcCauseDisableMovingGc, self);
Mathieu Chartierd5a89ee2014-01-31 09:55:13 -0800648 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700649}
650
Mathieu Chartier1d27b342014-01-28 12:51:09 -0800651void Heap::DecrementDisableMovingGC(Thread* self) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700652 MutexLock mu(self, *gc_complete_lock_);
Mathieu Chartier1d27b342014-01-28 12:51:09 -0800653 CHECK_GE(disable_moving_gc_count_, 0U);
654 --disable_moving_gc_count_;
Mathieu Chartier590fee92013-09-13 13:46:47 -0700655}
656
Mathieu Chartierca2a24d2013-11-25 15:12:12 -0800657void Heap::UpdateProcessState(ProcessState process_state) {
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800658 if (process_state_ != process_state) {
659 process_state_ = process_state;
Mathieu Chartier91e30632014-03-25 15:58:50 -0700660 for (size_t i = 1; i <= kCollectorTransitionStressIterations; ++i) {
661 // Start at index 1 to avoid "is always false" warning.
662 // Have iteration 1 always transition the collector.
663 TransitionCollector((((i & 1) == 1) == (process_state_ == kProcessStateJankPerceptible))
Mathieu Chartier31f44142014-04-08 14:40:03 -0700664 ? foreground_collector_type_ : background_collector_type_);
Mathieu Chartier91e30632014-03-25 15:58:50 -0700665 usleep(kCollectorTransitionStressWait);
666 }
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800667 if (process_state_ == kProcessStateJankPerceptible) {
Mathieu Chartiera5f9de02014-02-28 16:48:42 -0800668 // Transition back to foreground right away to prevent jank.
Mathieu Chartier31f44142014-04-08 14:40:03 -0700669 RequestCollectorTransition(foreground_collector_type_, 0);
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800670 } else {
Mathieu Chartiera5f9de02014-02-28 16:48:42 -0800671 // Don't delay for debug builds since we may want to stress test the GC.
Zuo Wangf37a88b2014-07-10 04:26:41 -0700672 // If background_collector_type_ is kCollectorTypeHomogeneousSpaceCompact then we have
673 // special handling which does a homogenous space compaction once but then doesn't transition
674 // the collector.
675 RequestCollectorTransition(background_collector_type_,
676 kIsDebugBuild ? 0 : kCollectorTransitionWait);
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800677 }
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800678 }
Mathieu Chartierca2a24d2013-11-25 15:12:12 -0800679}
680
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700681void Heap::CreateThreadPool() {
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700682 const size_t num_threads = std::max(parallel_gc_threads_, conc_gc_threads_);
683 if (num_threads != 0) {
Mathieu Chartierbcd5e9d2013-11-13 14:33:28 -0800684 thread_pool_.reset(new ThreadPool("Heap thread pool", num_threads));
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700685 }
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700686}
687
Mathieu Chartier83c8ee02014-01-28 14:50:23 -0800688void Heap::VisitObjects(ObjectCallback callback, void* arg) {
Mathieu Chartier692fafd2013-11-29 17:24:40 -0800689 // GCs can move objects, so don't allow this.
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -0700690 ScopedAssertNoThreadSuspension ants(Thread::Current(), "Visiting objects");
Mathieu Chartier590fee92013-09-13 13:46:47 -0700691 if (bump_pointer_space_ != nullptr) {
Mathieu Chartier692fafd2013-11-29 17:24:40 -0800692 // Visit objects in bump pointer space.
693 bump_pointer_space_->Walk(callback, arg);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700694 }
695 // TODO: Switch to standard begin and end to use ranged a based loop.
696 for (mirror::Object** it = allocation_stack_->Begin(), **end = allocation_stack_->End();
697 it < end; ++it) {
698 mirror::Object* obj = *it;
Mathieu Chartierebdf3f32014-02-13 10:23:27 -0800699 if (obj != nullptr && obj->GetClass() != nullptr) {
700 // Avoid the race condition caused by the object not yet being written into the allocation
Hiroshi Yamauchif5b0e202014-02-11 17:02:22 -0800701 // stack or the class not yet being written in the object. Or, if kUseThreadLocalAllocationStack,
702 // there can be nulls on the allocation stack.
Mathieu Chartierebdf3f32014-02-13 10:23:27 -0800703 callback(obj, arg);
704 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700705 }
706 GetLiveBitmap()->Walk(callback, arg);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700707}
708
709void Heap::MarkAllocStackAsLive(accounting::ObjectStack* stack) {
Mathieu Chartier00b59152014-07-25 10:13:51 -0700710 space::ContinuousSpace* space1 = main_space_ != nullptr ? main_space_ : non_moving_space_;
711 space::ContinuousSpace* space2 = non_moving_space_;
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800712 // TODO: Generalize this to n bitmaps?
Mathieu Chartier00b59152014-07-25 10:13:51 -0700713 CHECK(space1 != nullptr);
714 CHECK(space2 != nullptr);
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800715 MarkAllocStack(space1->GetLiveBitmap(), space2->GetLiveBitmap(),
Mathieu Chartier2dbe6272014-09-16 10:43:23 -0700716 (large_object_space_ != nullptr ? large_object_space_->GetLiveBitmap() : nullptr),
717 stack);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700718}
719
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700720void Heap::DeleteThreadPool() {
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700721 thread_pool_.reset(nullptr);
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700722}
723
Mathieu Chartier1b54f9c2014-04-30 16:45:02 -0700724void Heap::AddSpace(space::Space* space) {
Zuo Wangf37a88b2014-07-10 04:26:41 -0700725 CHECK(space != nullptr);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700726 WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
727 if (space->IsContinuousSpace()) {
728 DCHECK(!space->IsDiscontinuousSpace());
729 space::ContinuousSpace* continuous_space = space->AsContinuousSpace();
730 // Continuous spaces don't necessarily have bitmaps.
Mathieu Chartiera8e8f9c2014-04-09 14:51:05 -0700731 accounting::ContinuousSpaceBitmap* live_bitmap = continuous_space->GetLiveBitmap();
732 accounting::ContinuousSpaceBitmap* mark_bitmap = continuous_space->GetMarkBitmap();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700733 if (live_bitmap != nullptr) {
Mathieu Chartier2796a162014-07-25 11:50:47 -0700734 CHECK(mark_bitmap != nullptr);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700735 live_bitmap_->AddContinuousSpaceBitmap(live_bitmap);
736 mark_bitmap_->AddContinuousSpaceBitmap(mark_bitmap);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700737 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700738 continuous_spaces_.push_back(continuous_space);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700739 // Ensure that spaces remain sorted in increasing order of start address.
740 std::sort(continuous_spaces_.begin(), continuous_spaces_.end(),
741 [](const space::ContinuousSpace* a, const space::ContinuousSpace* b) {
742 return a->Begin() < b->Begin();
743 });
Mathieu Chartier590fee92013-09-13 13:46:47 -0700744 } else {
Mathieu Chartier2796a162014-07-25 11:50:47 -0700745 CHECK(space->IsDiscontinuousSpace());
Mathieu Chartier590fee92013-09-13 13:46:47 -0700746 space::DiscontinuousSpace* discontinuous_space = space->AsDiscontinuousSpace();
Mathieu Chartierbbd695c2014-04-16 09:48:48 -0700747 live_bitmap_->AddLargeObjectBitmap(discontinuous_space->GetLiveBitmap());
748 mark_bitmap_->AddLargeObjectBitmap(discontinuous_space->GetMarkBitmap());
Mathieu Chartier590fee92013-09-13 13:46:47 -0700749 discontinuous_spaces_.push_back(discontinuous_space);
750 }
751 if (space->IsAllocSpace()) {
752 alloc_spaces_.push_back(space->AsAllocSpace());
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700753 }
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800754}
755
Mathieu Chartier1b54f9c2014-04-30 16:45:02 -0700756void Heap::SetSpaceAsDefault(space::ContinuousSpace* continuous_space) {
757 WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
758 if (continuous_space->IsDlMallocSpace()) {
759 dlmalloc_space_ = continuous_space->AsDlMallocSpace();
760 } else if (continuous_space->IsRosAllocSpace()) {
761 rosalloc_space_ = continuous_space->AsRosAllocSpace();
762 }
763}
764
765void Heap::RemoveSpace(space::Space* space) {
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800766 DCHECK(space != nullptr);
767 WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
768 if (space->IsContinuousSpace()) {
769 DCHECK(!space->IsDiscontinuousSpace());
770 space::ContinuousSpace* continuous_space = space->AsContinuousSpace();
771 // Continuous spaces don't necessarily have bitmaps.
Mathieu Chartiera8e8f9c2014-04-09 14:51:05 -0700772 accounting::ContinuousSpaceBitmap* live_bitmap = continuous_space->GetLiveBitmap();
773 accounting::ContinuousSpaceBitmap* mark_bitmap = continuous_space->GetMarkBitmap();
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800774 if (live_bitmap != nullptr) {
775 DCHECK(mark_bitmap != nullptr);
776 live_bitmap_->RemoveContinuousSpaceBitmap(live_bitmap);
777 mark_bitmap_->RemoveContinuousSpaceBitmap(mark_bitmap);
778 }
779 auto it = std::find(continuous_spaces_.begin(), continuous_spaces_.end(), continuous_space);
780 DCHECK(it != continuous_spaces_.end());
781 continuous_spaces_.erase(it);
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800782 } else {
783 DCHECK(space->IsDiscontinuousSpace());
784 space::DiscontinuousSpace* discontinuous_space = space->AsDiscontinuousSpace();
Mathieu Chartierbbd695c2014-04-16 09:48:48 -0700785 live_bitmap_->RemoveLargeObjectBitmap(discontinuous_space->GetLiveBitmap());
786 mark_bitmap_->RemoveLargeObjectBitmap(discontinuous_space->GetMarkBitmap());
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800787 auto it = std::find(discontinuous_spaces_.begin(), discontinuous_spaces_.end(),
788 discontinuous_space);
789 DCHECK(it != discontinuous_spaces_.end());
790 discontinuous_spaces_.erase(it);
791 }
792 if (space->IsAllocSpace()) {
793 auto it = std::find(alloc_spaces_.begin(), alloc_spaces_.end(), space->AsAllocSpace());
794 DCHECK(it != alloc_spaces_.end());
795 alloc_spaces_.erase(it);
796 }
797}
798
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700799void Heap::DumpGcPerformanceInfo(std::ostream& os) {
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700800 // Dump cumulative timings.
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700801 os << "Dumping cumulative Gc timings\n";
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700802 uint64_t total_duration = 0;
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800803 // Dump cumulative loggers for each GC type.
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800804 uint64_t total_paused_time = 0;
Mathieu Chartier5a487192014-04-08 11:14:54 -0700805 for (auto& collector : garbage_collectors_) {
Mathieu Chartier104fa0c2014-08-07 14:26:27 -0700806 total_duration += collector->GetCumulativeTimings().GetTotalNs();
807 total_paused_time += collector->GetTotalPausedTimeNs();
808 collector->DumpPerformanceInfo(os);
Mathieu Chartier5a487192014-04-08 11:14:54 -0700809 collector->ResetMeasurements();
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700810 }
Ian Rogers3e5cf302014-05-20 16:40:37 -0700811 uint64_t allocation_time =
812 static_cast<uint64_t>(total_allocation_time_.LoadRelaxed()) * kTimeAdjust;
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700813 if (total_duration != 0) {
Brian Carlstrom2d888622013-07-18 17:02:00 -0700814 const double total_seconds = static_cast<double>(total_duration / 1000) / 1000000.0;
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700815 os << "Total time spent in GC: " << PrettyDuration(total_duration) << "\n";
816 os << "Mean GC size throughput: "
Ian Rogers1d54e732013-05-02 21:10:01 -0700817 << PrettySize(GetBytesFreedEver() / total_seconds) << "/s\n";
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700818 os << "Mean GC object throughput: "
Ian Rogers1d54e732013-05-02 21:10:01 -0700819 << (GetObjectsFreedEver() / total_seconds) << " objects/s\n";
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700820 }
Mathieu Chartierdd162fb2014-08-06 17:06:33 -0700821 uint64_t total_objects_allocated = GetObjectsAllocatedEver();
Mathieu Chartierc30a7252014-08-12 10:13:48 -0700822 os << "Total number of allocations " << total_objects_allocated << "\n";
Mathieu Chartierdd162fb2014-08-06 17:06:33 -0700823 uint64_t total_bytes_allocated = GetBytesAllocatedEver();
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700824 os << "Total bytes allocated " << PrettySize(total_bytes_allocated) << "\n";
Mathieu Chartierc30a7252014-08-12 10:13:48 -0700825 os << "Free memory " << PrettySize(GetFreeMemory()) << "\n";
Mathieu Chartierdd162fb2014-08-06 17:06:33 -0700826 os << "Free memory until GC " << PrettySize(GetFreeMemoryUntilGC()) << "\n";
827 os << "Free memory until OOME " << PrettySize(GetFreeMemoryUntilOOME()) << "\n";
Mathieu Chartierc30a7252014-08-12 10:13:48 -0700828 os << "Total memory " << PrettySize(GetTotalMemory()) << "\n";
829 os << "Max memory " << PrettySize(GetMaxMemory()) << "\n";
Hiroshi Yamauchi50b29282013-07-30 13:58:37 -0700830 if (kMeasureAllocationTime) {
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700831 os << "Total time spent allocating: " << PrettyDuration(allocation_time) << "\n";
832 os << "Mean allocation time: " << PrettyDuration(allocation_time / total_objects_allocated)
833 << "\n";
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700834 }
Mathieu Chartiere4cab172014-08-19 18:24:04 -0700835 if (HasZygoteSpace()) {
836 os << "Zygote space size " << PrettySize(zygote_space_->Size()) << "\n";
837 }
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700838 os << "Total mutator paused time: " << PrettyDuration(total_paused_time) << "\n";
839 os << "Total time waiting for GC to complete: " << PrettyDuration(total_wait_time_) << "\n";
Mathieu Chartier73d1e172014-04-11 17:53:48 -0700840 BaseMutex::DumpAll(os);
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700841}
842
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800843Heap::~Heap() {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700844 VLOG(heap) << "Starting ~Heap()";
Mathieu Chartier590fee92013-09-13 13:46:47 -0700845 STLDeleteElements(&garbage_collectors_);
846 // If we don't reset then the mark stack complains in its destructor.
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700847 allocation_stack_->Reset();
848 live_stack_->Reset();
Mathieu Chartier11409ae2013-09-23 11:49:36 -0700849 STLDeleteValues(&mod_union_tables_);
Mathieu Chartier0767c9a2014-03-26 12:53:19 -0700850 STLDeleteValues(&remembered_sets_);
Ian Rogers1d54e732013-05-02 21:10:01 -0700851 STLDeleteElements(&continuous_spaces_);
852 STLDeleteElements(&discontinuous_spaces_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700853 delete gc_complete_lock_;
Mathieu Chartier0767c9a2014-03-26 12:53:19 -0700854 delete heap_trim_request_lock_;
Mathieu Chartier590fee92013-09-13 13:46:47 -0700855 VLOG(heap) << "Finished ~Heap()";
Carl Shapiro69759ea2011-07-21 18:13:35 -0700856}
857
Ian Rogers1d54e732013-05-02 21:10:01 -0700858space::ContinuousSpace* Heap::FindContinuousSpaceFromObject(const mirror::Object* obj,
859 bool fail_ok) const {
Mathieu Chartier02e25112013-08-14 16:14:24 -0700860 for (const auto& space : continuous_spaces_) {
861 if (space->Contains(obj)) {
862 return space;
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700863 }
864 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700865 if (!fail_ok) {
866 LOG(FATAL) << "object " << reinterpret_cast<const void*>(obj) << " not inside any spaces!";
867 }
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700868 return NULL;
869}
870
Ian Rogers1d54e732013-05-02 21:10:01 -0700871space::DiscontinuousSpace* Heap::FindDiscontinuousSpaceFromObject(const mirror::Object* obj,
872 bool fail_ok) const {
Mathieu Chartier02e25112013-08-14 16:14:24 -0700873 for (const auto& space : discontinuous_spaces_) {
874 if (space->Contains(obj)) {
875 return space;
Ian Rogers1d54e732013-05-02 21:10:01 -0700876 }
877 }
878 if (!fail_ok) {
879 LOG(FATAL) << "object " << reinterpret_cast<const void*>(obj) << " not inside any spaces!";
880 }
881 return NULL;
882}
883
884space::Space* Heap::FindSpaceFromObject(const mirror::Object* obj, bool fail_ok) const {
885 space::Space* result = FindContinuousSpaceFromObject(obj, true);
886 if (result != NULL) {
887 return result;
888 }
889 return FindDiscontinuousSpaceFromObject(obj, true);
890}
891
892space::ImageSpace* Heap::GetImageSpace() const {
Mathieu Chartier02e25112013-08-14 16:14:24 -0700893 for (const auto& space : continuous_spaces_) {
894 if (space->IsImageSpace()) {
895 return space->AsImageSpace();
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700896 }
897 }
898 return NULL;
899}
900
Hiroshi Yamauchi654dd482014-07-09 12:54:32 -0700901void Heap::ThrowOutOfMemoryError(Thread* self, size_t byte_count, AllocatorType allocator_type) {
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -0700902 std::ostringstream oss;
Ian Rogersef7d42f2014-01-06 12:55:46 -0800903 size_t total_bytes_free = GetFreeMemory();
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -0700904 oss << "Failed to allocate a " << byte_count << " byte allocation with " << total_bytes_free
Mathieu Chartierdd162fb2014-08-06 17:06:33 -0700905 << " free bytes and " << PrettySize(GetFreeMemoryUntilOOME()) << " until OOM";
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -0700906 // If the allocation failed due to fragmentation, print out the largest continuous allocation.
Zuo Wangf37a88b2014-07-10 04:26:41 -0700907 if (total_bytes_free >= byte_count) {
Mathieu Chartierb363f662014-07-16 13:28:58 -0700908 space::AllocSpace* space = nullptr;
Hiroshi Yamauchi654dd482014-07-09 12:54:32 -0700909 if (allocator_type == kAllocatorTypeNonMoving) {
910 space = non_moving_space_;
911 } else if (allocator_type == kAllocatorTypeRosAlloc ||
912 allocator_type == kAllocatorTypeDlMalloc) {
913 space = main_space_;
Mathieu Chartierb363f662014-07-16 13:28:58 -0700914 } else if (allocator_type == kAllocatorTypeBumpPointer ||
915 allocator_type == kAllocatorTypeTLAB) {
916 space = bump_pointer_space_;
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -0700917 }
Hiroshi Yamauchi654dd482014-07-09 12:54:32 -0700918 if (space != nullptr) {
919 space->LogFragmentationAllocFailure(oss, byte_count);
920 }
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700921 }
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -0700922 self->ThrowOutOfMemoryError(oss.str().c_str());
923}
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700924
Mathieu Chartiera5f9de02014-02-28 16:48:42 -0800925void Heap::DoPendingTransitionOrTrim() {
Mathieu Chartierb2728552014-09-08 20:08:41 +0000926 Thread* self = Thread::Current();
927 CollectorType desired_collector_type;
928 // Wait until we reach the desired transition time.
929 while (true) {
930 uint64_t wait_time;
931 {
932 MutexLock mu(self, *heap_trim_request_lock_);
933 desired_collector_type = desired_collector_type_;
934 uint64_t current_time = NanoTime();
935 if (current_time >= heap_transition_or_trim_target_time_) {
936 break;
937 }
938 wait_time = heap_transition_or_trim_target_time_ - current_time;
939 }
940 ScopedThreadStateChange tsc(self, kSleeping);
941 usleep(wait_time / 1000); // Usleep takes microseconds.
942 }
943 // Launch homogeneous space compaction if it is desired.
944 if (desired_collector_type == kCollectorTypeHomogeneousSpaceCompact) {
945 if (!CareAboutPauseTimes()) {
946 PerformHomogeneousSpaceCompact();
947 }
948 // No need to Trim(). Homogeneous space compaction may free more virtual and physical memory.
949 desired_collector_type = collector_type_;
950 return;
951 }
952 // Transition the collector if the desired collector type is not the same as the current
953 // collector type.
954 TransitionCollector(desired_collector_type);
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700955 if (!CareAboutPauseTimes()) {
956 // Deflate the monitors, this can cause a pause but shouldn't matter since we don't care
957 // about pauses.
958 Runtime* runtime = Runtime::Current();
959 runtime->GetThreadList()->SuspendAll();
Mathieu Chartier48ab6872014-06-24 11:21:59 -0700960 uint64_t start_time = NanoTime();
961 size_t count = runtime->GetMonitorList()->DeflateMonitors();
962 VLOG(heap) << "Deflating " << count << " monitors took "
963 << PrettyDuration(NanoTime() - start_time);
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700964 runtime->GetThreadList()->ResumeAll();
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700965 }
Mathieu Chartierb2728552014-09-08 20:08:41 +0000966 // Do a heap trim if it is needed.
Mathieu Chartiera5b5c552014-06-24 14:48:59 -0700967 Trim();
Mathieu Chartiera5f9de02014-02-28 16:48:42 -0800968}
969
Mathieu Chartier590fee92013-09-13 13:46:47 -0700970void Heap::Trim() {
Mathieu Chartierd5a89ee2014-01-31 09:55:13 -0800971 Thread* self = Thread::Current();
972 {
Mathieu Chartiera5f9de02014-02-28 16:48:42 -0800973 MutexLock mu(self, *heap_trim_request_lock_);
Mathieu Chartier7bf52d22014-03-13 14:46:09 -0700974 if (!heap_trim_request_pending_ || last_trim_time_ + kHeapTrimWait >= NanoTime()) {
Mathieu Chartiera5f9de02014-02-28 16:48:42 -0800975 return;
976 }
Mathieu Chartier7bf52d22014-03-13 14:46:09 -0700977 last_trim_time_ = NanoTime();
Mathieu Chartiera5f9de02014-02-28 16:48:42 -0800978 heap_trim_request_pending_ = false;
979 }
980 {
Mathieu Chartiercaa82d62014-02-02 16:51:17 -0800981 // Need to do this before acquiring the locks since we don't want to get suspended while
982 // holding any locks.
983 ScopedThreadStateChange tsc(self, kWaitingForGcToComplete);
Mathieu Chartierd5a89ee2014-01-31 09:55:13 -0800984 // Pretend we are doing a GC to prevent background compaction from deleting the space we are
985 // trimming.
986 MutexLock mu(self, *gc_complete_lock_);
987 // Ensure there is only one GC at a time.
Mathieu Chartier89a201e2014-05-02 10:27:26 -0700988 WaitForGcToCompleteLocked(kGcCauseTrim, self);
Mathieu Chartierd5a89ee2014-01-31 09:55:13 -0800989 collector_type_running_ = kCollectorTypeHeapTrim;
990 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700991 uint64_t start_ns = NanoTime();
992 // Trim the managed spaces.
993 uint64_t total_alloc_space_allocated = 0;
994 uint64_t total_alloc_space_size = 0;
995 uint64_t managed_reclaimed = 0;
996 for (const auto& space : continuous_spaces_) {
Mathieu Chartiera1602f22014-01-13 17:19:19 -0800997 if (space->IsMallocSpace()) {
Mathieu Chartiera5b5c552014-06-24 14:48:59 -0700998 gc::space::MallocSpace* malloc_space = space->AsMallocSpace();
999 if (malloc_space->IsRosAllocSpace() || !CareAboutPauseTimes()) {
1000 // Don't trim dlmalloc spaces if we care about pauses since this can hold the space lock
1001 // for a long period of time.
1002 managed_reclaimed += malloc_space->Trim();
1003 }
1004 total_alloc_space_size += malloc_space->Size();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001005 }
1006 }
Mathieu Chartier2dbe6272014-09-16 10:43:23 -07001007 total_alloc_space_allocated = GetBytesAllocated();
1008 if (large_object_space_ != nullptr) {
1009 total_alloc_space_allocated -= large_object_space_->GetBytesAllocated();
1010 }
Mathieu Chartier31f44142014-04-08 14:40:03 -07001011 if (bump_pointer_space_ != nullptr) {
1012 total_alloc_space_allocated -= bump_pointer_space_->Size();
1013 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07001014 const float managed_utilization = static_cast<float>(total_alloc_space_allocated) /
1015 static_cast<float>(total_alloc_space_size);
1016 uint64_t gc_heap_end_ns = NanoTime();
Mathieu Chartierd5a89ee2014-01-31 09:55:13 -08001017 // We never move things in the native heap, so we can finish the GC at this point.
1018 FinishGC(self, collector::kGcTypeNone);
Christopher Ferrisc4ddc042014-05-13 14:47:50 -07001019 size_t native_reclaimed = 0;
Mathieu Chartiera5b5c552014-06-24 14:48:59 -07001020 // Only trim the native heap if we don't care about pauses.
1021 if (!CareAboutPauseTimes()) {
Christopher Ferrisc4ddc042014-05-13 14:47:50 -07001022#if defined(USE_DLMALLOC)
Mathieu Chartiera5b5c552014-06-24 14:48:59 -07001023 // Trim the native heap.
1024 dlmalloc_trim(0);
1025 dlmalloc_inspect_all(DlmallocMadviseCallback, &native_reclaimed);
Christopher Ferrisc4ddc042014-05-13 14:47:50 -07001026#elif defined(USE_JEMALLOC)
Mathieu Chartiera5b5c552014-06-24 14:48:59 -07001027 // Jemalloc does it's own internal trimming.
Christopher Ferrisc4ddc042014-05-13 14:47:50 -07001028#else
Mathieu Chartiera5b5c552014-06-24 14:48:59 -07001029 UNIMPLEMENTED(WARNING) << "Add trimming support";
Christopher Ferrisc4ddc042014-05-13 14:47:50 -07001030#endif
Mathieu Chartiera5b5c552014-06-24 14:48:59 -07001031 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07001032 uint64_t end_ns = NanoTime();
1033 VLOG(heap) << "Heap trim of managed (duration=" << PrettyDuration(gc_heap_end_ns - start_ns)
1034 << ", advised=" << PrettySize(managed_reclaimed) << ") and native (duration="
1035 << PrettyDuration(end_ns - gc_heap_end_ns) << ", advised=" << PrettySize(native_reclaimed)
1036 << ") heaps. Managed heap utilization of " << static_cast<int>(100 * managed_utilization)
1037 << "%.";
1038}
1039
1040bool Heap::IsValidObjectAddress(const mirror::Object* obj) const {
1041 // Note: we deliberately don't take the lock here, and mustn't test anything that would require
1042 // taking the lock.
1043 if (obj == nullptr) {
Elliott Hughes88c5c352012-03-15 18:49:48 -07001044 return true;
1045 }
Mathieu Chartier15d34022014-02-26 17:16:38 -08001046 return IsAligned<kObjectAlignment>(obj) && FindSpaceFromObject(obj, true) != nullptr;
Mathieu Chartier590fee92013-09-13 13:46:47 -07001047}
1048
Mathieu Chartierd68ac702014-02-11 14:50:51 -08001049bool Heap::IsNonDiscontinuousSpaceHeapAddress(const mirror::Object* obj) const {
1050 return FindContinuousSpaceFromObject(obj, true) != nullptr;
1051}
1052
Mathieu Chartier15d34022014-02-26 17:16:38 -08001053bool Heap::IsValidContinuousSpaceObjectAddress(const mirror::Object* obj) const {
1054 if (obj == nullptr || !IsAligned<kObjectAlignment>(obj)) {
1055 return false;
1056 }
1057 for (const auto& space : continuous_spaces_) {
1058 if (space->HasAddress(obj)) {
1059 return true;
1060 }
1061 }
1062 return false;
Elliott Hughesa2501992011-08-26 19:39:54 -07001063}
1064
Ian Rogersef7d42f2014-01-06 12:55:46 -08001065bool Heap::IsLiveObjectLocked(mirror::Object* obj, bool search_allocation_stack,
Mathieu Chartier0f72e412013-09-06 16:40:01 -07001066 bool search_live_stack, bool sorted) {
Mathieu Chartier938a03b2014-01-16 15:10:31 -08001067 if (UNLIKELY(!IsAligned<kObjectAlignment>(obj))) {
1068 return false;
1069 }
1070 if (bump_pointer_space_ != nullptr && bump_pointer_space_->HasAddress(obj)) {
Mathieu Chartier4e305412014-02-19 10:54:44 -08001071 mirror::Class* klass = obj->GetClass<kVerifyNone>();
Mathieu Chartier938a03b2014-01-16 15:10:31 -08001072 if (obj == klass) {
Mathieu Chartier9be9a7a2014-01-24 14:07:33 -08001073 // This case happens for java.lang.Class.
Mathieu Chartier938a03b2014-01-16 15:10:31 -08001074 return true;
1075 }
1076 return VerifyClassClass(klass) && IsLiveObjectLocked(klass);
1077 } else if (temp_space_ != nullptr && temp_space_->HasAddress(obj)) {
Mathieu Chartier4e305412014-02-19 10:54:44 -08001078 // If we are in the allocated region of the temp space, then we are probably live (e.g. during
1079 // a GC). When a GC isn't running End() - Begin() is 0 which means no objects are contained.
1080 return temp_space_->Contains(obj);
Ian Rogers1d54e732013-05-02 21:10:01 -07001081 }
Mathieu Chartierf082d3c2013-07-29 17:04:07 -07001082 space::ContinuousSpace* c_space = FindContinuousSpaceFromObject(obj, true);
Mathieu Chartierbbd695c2014-04-16 09:48:48 -07001083 space::DiscontinuousSpace* d_space = nullptr;
Mathieu Chartier938a03b2014-01-16 15:10:31 -08001084 if (c_space != nullptr) {
Mathieu Chartierf082d3c2013-07-29 17:04:07 -07001085 if (c_space->GetLiveBitmap()->Test(obj)) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001086 return true;
1087 }
1088 } else {
Mathieu Chartierf082d3c2013-07-29 17:04:07 -07001089 d_space = FindDiscontinuousSpaceFromObject(obj, true);
Mathieu Chartier938a03b2014-01-16 15:10:31 -08001090 if (d_space != nullptr) {
Mathieu Chartierbbd695c2014-04-16 09:48:48 -07001091 if (d_space->GetLiveBitmap()->Test(obj)) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001092 return true;
1093 }
1094 }
1095 }
Mathieu Chartierf082d3c2013-07-29 17:04:07 -07001096 // This is covering the allocation/live stack swapping that is done without mutators suspended.
Mathieu Chartier0f72e412013-09-06 16:40:01 -07001097 for (size_t i = 0; i < (sorted ? 1 : 5); ++i) {
1098 if (i > 0) {
1099 NanoSleep(MsToNs(10));
Ian Rogers1d54e732013-05-02 21:10:01 -07001100 }
Mathieu Chartier0f72e412013-09-06 16:40:01 -07001101 if (search_allocation_stack) {
1102 if (sorted) {
Mathieu Chartier407f7022014-02-18 14:37:05 -08001103 if (allocation_stack_->ContainsSorted(obj)) {
Mathieu Chartier0f72e412013-09-06 16:40:01 -07001104 return true;
1105 }
Mathieu Chartier407f7022014-02-18 14:37:05 -08001106 } else if (allocation_stack_->Contains(obj)) {
Mathieu Chartier0f72e412013-09-06 16:40:01 -07001107 return true;
1108 }
1109 }
1110
1111 if (search_live_stack) {
1112 if (sorted) {
Mathieu Chartier407f7022014-02-18 14:37:05 -08001113 if (live_stack_->ContainsSorted(obj)) {
Mathieu Chartier0f72e412013-09-06 16:40:01 -07001114 return true;
1115 }
Mathieu Chartier407f7022014-02-18 14:37:05 -08001116 } else if (live_stack_->Contains(obj)) {
Mathieu Chartier0f72e412013-09-06 16:40:01 -07001117 return true;
1118 }
1119 }
Ian Rogers1d54e732013-05-02 21:10:01 -07001120 }
Mathieu Chartierf082d3c2013-07-29 17:04:07 -07001121 // We need to check the bitmaps again since there is a race where we mark something as live and
1122 // then clear the stack containing it.
Mathieu Chartier938a03b2014-01-16 15:10:31 -08001123 if (c_space != nullptr) {
Mathieu Chartierf082d3c2013-07-29 17:04:07 -07001124 if (c_space->GetLiveBitmap()->Test(obj)) {
1125 return true;
1126 }
1127 } else {
1128 d_space = FindDiscontinuousSpaceFromObject(obj, true);
Mathieu Chartierbbd695c2014-04-16 09:48:48 -07001129 if (d_space != nullptr && d_space->GetLiveBitmap()->Test(obj)) {
Mathieu Chartierf082d3c2013-07-29 17:04:07 -07001130 return true;
1131 }
1132 }
Ian Rogers1d54e732013-05-02 21:10:01 -07001133 return false;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001134}
1135
Mathieu Chartier4c13a3f2014-07-14 14:57:16 -07001136std::string Heap::DumpSpaces() const {
1137 std::ostringstream oss;
1138 DumpSpaces(oss);
1139 return oss.str();
1140}
1141
1142void Heap::DumpSpaces(std::ostream& stream) const {
Mathieu Chartier02e25112013-08-14 16:14:24 -07001143 for (const auto& space : continuous_spaces_) {
Mathieu Chartiera8e8f9c2014-04-09 14:51:05 -07001144 accounting::ContinuousSpaceBitmap* live_bitmap = space->GetLiveBitmap();
1145 accounting::ContinuousSpaceBitmap* mark_bitmap = space->GetMarkBitmap();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001146 stream << space << " " << *space << "\n";
1147 if (live_bitmap != nullptr) {
1148 stream << live_bitmap << " " << *live_bitmap << "\n";
1149 }
1150 if (mark_bitmap != nullptr) {
1151 stream << mark_bitmap << " " << *mark_bitmap << "\n";
1152 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001153 }
Mathieu Chartier02e25112013-08-14 16:14:24 -07001154 for (const auto& space : discontinuous_spaces_) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001155 stream << space << " " << *space << "\n";
Mathieu Chartier128c52c2012-10-16 14:12:41 -07001156 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001157}
1158
Ian Rogersef7d42f2014-01-06 12:55:46 -08001159void Heap::VerifyObjectBody(mirror::Object* obj) {
Stephen Hines22c6a812014-07-16 11:03:43 -07001160 if (verify_object_mode_ == kVerifyObjectModeDisabled) {
1161 return;
1162 }
1163
Mathieu Chartier0f72e412013-09-06 16:40:01 -07001164 // Ignore early dawn of the universe verifications.
Ian Rogers3e5cf302014-05-20 16:40:37 -07001165 if (UNLIKELY(static_cast<size_t>(num_bytes_allocated_.LoadRelaxed()) < 10 * KB)) {
Ian Rogers62d6c772013-02-27 08:32:07 -08001166 return;
1167 }
Mathieu Chartier4e305412014-02-19 10:54:44 -08001168 CHECK(IsAligned<kObjectAlignment>(obj)) << "Object isn't aligned: " << obj;
Ian Rogersb0fa5dc2014-04-28 16:47:08 -07001169 mirror::Class* c = obj->GetFieldObject<mirror::Class, kVerifyNone>(mirror::Object::ClassOffset());
Mathieu Chartier4e305412014-02-19 10:54:44 -08001170 CHECK(c != nullptr) << "Null class in object " << obj;
1171 CHECK(IsAligned<kObjectAlignment>(c)) << "Class " << c << " not aligned in object " << obj;
Mathieu Chartier938a03b2014-01-16 15:10:31 -08001172 CHECK(VerifyClassClass(c));
Mathieu Chartier0325e622012-09-05 14:22:51 -07001173
Mathieu Chartier4e305412014-02-19 10:54:44 -08001174 if (verify_object_mode_ > kVerifyObjectModeFast) {
1175 // Note: the bitmap tests below are racy since we don't hold the heap bitmap lock.
Mathieu Chartier4c13a3f2014-07-14 14:57:16 -07001176 CHECK(IsLiveObjectLocked(obj)) << "Object is dead " << obj << "\n" << DumpSpaces();
Mathieu Chartierdcf8d722012-08-02 14:55:54 -07001177 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001178}
1179
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001180void Heap::VerificationCallback(mirror::Object* obj, void* arg) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001181 reinterpret_cast<Heap*>(arg)->VerifyObjectBody(obj);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001182}
1183
1184void Heap::VerifyHeap() {
Ian Rogers50b35e22012-10-04 10:09:15 -07001185 ReaderMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07001186 GetLiveBitmap()->Walk(Heap::VerificationCallback, this);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001187}
1188
Mathieu Chartiere76e70f2014-05-02 16:35:37 -07001189void Heap::RecordFree(uint64_t freed_objects, int64_t freed_bytes) {
Mathieu Chartier601276a2014-03-20 15:12:30 -07001190 // Use signed comparison since freed bytes can be negative when background compaction foreground
1191 // transitions occurs. This is caused by the moving objects from a bump pointer space to a
1192 // free list backed space typically increasing memory footprint due to padding and binning.
Ian Rogers3e5cf302014-05-20 16:40:37 -07001193 DCHECK_LE(freed_bytes, static_cast<int64_t>(num_bytes_allocated_.LoadRelaxed()));
Mathieu Chartiere76e70f2014-05-02 16:35:37 -07001194 // Note: This relies on 2s complement for handling negative freed_bytes.
Ian Rogers3e5cf302014-05-20 16:40:37 -07001195 num_bytes_allocated_.FetchAndSubSequentiallyConsistent(static_cast<ssize_t>(freed_bytes));
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07001196 if (Runtime::Current()->HasStatsEnabled()) {
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07001197 RuntimeStats* thread_stats = Thread::Current()->GetStats();
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001198 thread_stats->freed_objects += freed_objects;
Elliott Hughes307f75d2011-10-12 18:04:40 -07001199 thread_stats->freed_bytes += freed_bytes;
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001200 // TODO: Do this concurrently.
1201 RuntimeStats* global_stats = Runtime::Current()->GetStats();
1202 global_stats->freed_objects += freed_objects;
1203 global_stats->freed_bytes += freed_bytes;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07001204 }
Carl Shapiro58551df2011-07-24 03:09:51 -07001205}
1206
Zuo Wangf37a88b2014-07-10 04:26:41 -07001207space::RosAllocSpace* Heap::GetRosAllocSpace(gc::allocator::RosAlloc* rosalloc) const {
1208 for (const auto& space : continuous_spaces_) {
1209 if (space->AsContinuousSpace()->IsRosAllocSpace()) {
1210 if (space->AsContinuousSpace()->AsRosAllocSpace()->GetRosAlloc() == rosalloc) {
1211 return space->AsContinuousSpace()->AsRosAllocSpace();
1212 }
1213 }
1214 }
1215 return nullptr;
1216}
1217
Mathieu Chartiercbb2d202013-11-14 17:45:16 -08001218mirror::Object* Heap::AllocateInternalWithGc(Thread* self, AllocatorType allocator,
Mathieu Chartierc528dba2013-11-26 12:00:11 -08001219 size_t alloc_size, size_t* bytes_allocated,
Ian Rogers6fac4472014-02-25 17:01:10 -08001220 size_t* usable_size,
Mathieu Chartierc528dba2013-11-26 12:00:11 -08001221 mirror::Class** klass) {
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001222 bool was_default_allocator = allocator == GetCurrentAllocator();
Mathieu Chartierf4f38432014-09-03 11:21:08 -07001223 // Make sure there is no pending exception since we may need to throw an OOME.
1224 self->AssertNoPendingException();
Mathieu Chartierc528dba2013-11-26 12:00:11 -08001225 DCHECK(klass != nullptr);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001226 StackHandleScope<1> hs(self);
1227 HandleWrapper<mirror::Class> h(hs.NewHandleWrapper(klass));
1228 klass = nullptr; // Invalidate for safety.
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001229 // The allocation failed. If the GC is running, block until it completes, and then retry the
1230 // allocation.
Mathieu Chartier89a201e2014-05-02 10:27:26 -07001231 collector::GcType last_gc = WaitForGcToComplete(kGcCauseForAlloc, self);
Ian Rogers1d54e732013-05-02 21:10:01 -07001232 if (last_gc != collector::kGcTypeNone) {
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001233 // If we were the default allocator but the allocator changed while we were suspended,
1234 // abort the allocation.
1235 if (was_default_allocator && allocator != GetCurrentAllocator()) {
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001236 return nullptr;
1237 }
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001238 // A GC was in progress and we blocked, retry allocation now that memory has been freed.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001239 mirror::Object* ptr = TryToAllocate<true, false>(self, allocator, alloc_size, bytes_allocated,
1240 usable_size);
1241 if (ptr != nullptr) {
1242 return ptr;
1243 }
Carl Shapiro69759ea2011-07-21 18:13:35 -07001244 }
1245
Mathieu Chartier5ae2c932014-03-28 16:22:20 -07001246 collector::GcType tried_type = next_gc_type_;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001247 const bool gc_ran =
1248 CollectGarbageInternal(tried_type, kGcCauseForAlloc, false) != collector::kGcTypeNone;
1249 if (was_default_allocator && allocator != GetCurrentAllocator()) {
1250 return nullptr;
1251 }
1252 if (gc_ran) {
1253 mirror::Object* ptr = TryToAllocate<true, false>(self, allocator, alloc_size, bytes_allocated,
1254 usable_size);
1255 if (ptr != nullptr) {
1256 return ptr;
Mathieu Chartier5ae2c932014-03-28 16:22:20 -07001257 }
1258 }
1259
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001260 // Loop through our different Gc types and try to Gc until we get enough free memory.
Mathieu Chartiercbb2d202013-11-14 17:45:16 -08001261 for (collector::GcType gc_type : gc_plan_) {
Mathieu Chartier5ae2c932014-03-28 16:22:20 -07001262 if (gc_type == tried_type) {
1263 continue;
1264 }
Mathieu Chartiercbb2d202013-11-14 17:45:16 -08001265 // Attempt to run the collector, if we succeed, re-try the allocation.
Mathieu Chartier5ae2c932014-03-28 16:22:20 -07001266 const bool gc_ran =
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001267 CollectGarbageInternal(gc_type, kGcCauseForAlloc, false) != collector::kGcTypeNone;
1268 if (was_default_allocator && allocator != GetCurrentAllocator()) {
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001269 return nullptr;
1270 }
1271 if (gc_ran) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001272 // Did we free sufficient memory for the allocation to succeed?
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001273 mirror::Object* ptr = TryToAllocate<true, false>(self, allocator, alloc_size, bytes_allocated,
1274 usable_size);
1275 if (ptr != nullptr) {
1276 return ptr;
1277 }
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001278 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001279 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001280 // Allocations have failed after GCs; this is an exceptional state.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001281 // Try harder, growing the heap if necessary.
1282 mirror::Object* ptr = TryToAllocate<true, true>(self, allocator, alloc_size, bytes_allocated,
1283 usable_size);
1284 if (ptr != nullptr) {
1285 return ptr;
Carl Shapiro69759ea2011-07-21 18:13:35 -07001286 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001287 // Most allocations should have succeeded by now, so the heap is really full, really fragmented,
1288 // or the requested size is really big. Do another GC, collecting SoftReferences this time. The
1289 // VM spec requires that all SoftReferences have been collected and cleared before throwing
1290 // OOME.
1291 VLOG(gc) << "Forcing collection of SoftReferences for " << PrettySize(alloc_size)
1292 << " allocation";
1293 // TODO: Run finalization, but this may cause more allocations to occur.
1294 // We don't need a WaitForGcToComplete here either.
1295 DCHECK(!gc_plan_.empty());
1296 CollectGarbageInternal(gc_plan_.back(), kGcCauseForAlloc, true);
1297 if (was_default_allocator && allocator != GetCurrentAllocator()) {
1298 return nullptr;
Mathieu Chartiercbb2d202013-11-14 17:45:16 -08001299 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001300 ptr = TryToAllocate<true, true>(self, allocator, alloc_size, bytes_allocated, usable_size);
Mathieu Chartier6a7824d2014-08-22 14:53:04 -07001301 if (ptr == nullptr) {
Zuo Wangf37a88b2014-07-10 04:26:41 -07001302 const uint64_t current_time = NanoTime();
Mathieu Chartier6a7824d2014-08-22 14:53:04 -07001303 switch (allocator) {
1304 case kAllocatorTypeRosAlloc:
1305 // Fall-through.
1306 case kAllocatorTypeDlMalloc: {
1307 if (use_homogeneous_space_compaction_for_oom_ &&
1308 current_time - last_time_homogeneous_space_compaction_by_oom_ >
1309 min_interval_homogeneous_space_compaction_by_oom_) {
1310 last_time_homogeneous_space_compaction_by_oom_ = current_time;
1311 HomogeneousSpaceCompactResult result = PerformHomogeneousSpaceCompact();
1312 switch (result) {
1313 case HomogeneousSpaceCompactResult::kSuccess:
1314 // If the allocation succeeded, we delayed an oom.
1315 ptr = TryToAllocate<true, true>(self, allocator, alloc_size, bytes_allocated,
1316 usable_size);
1317 if (ptr != nullptr) {
1318 count_delayed_oom_++;
1319 }
1320 break;
1321 case HomogeneousSpaceCompactResult::kErrorReject:
1322 // Reject due to disabled moving GC.
1323 break;
1324 case HomogeneousSpaceCompactResult::kErrorVMShuttingDown:
1325 // Throw OOM by default.
1326 break;
1327 default: {
1328 LOG(FATAL) << "Unimplemented homogeneous space compaction result "
1329 << static_cast<size_t>(result);
1330 }
Zuo Wangf37a88b2014-07-10 04:26:41 -07001331 }
Mathieu Chartier6a7824d2014-08-22 14:53:04 -07001332 // Always print that we ran homogeneous space compation since this can cause jank.
1333 VLOG(heap) << "Ran heap homogeneous space compaction, "
1334 << " requested defragmentation "
1335 << count_requested_homogeneous_space_compaction_.LoadSequentiallyConsistent()
1336 << " performed defragmentation "
1337 << count_performed_homogeneous_space_compaction_.LoadSequentiallyConsistent()
1338 << " ignored homogeneous space compaction "
1339 << count_ignored_homogeneous_space_compaction_.LoadSequentiallyConsistent()
1340 << " delayed count = "
1341 << count_delayed_oom_.LoadSequentiallyConsistent();
Zuo Wangf37a88b2014-07-10 04:26:41 -07001342 }
Mathieu Chartier6a7824d2014-08-22 14:53:04 -07001343 break;
Zuo Wangf37a88b2014-07-10 04:26:41 -07001344 }
Mathieu Chartier6a7824d2014-08-22 14:53:04 -07001345 case kAllocatorTypeNonMoving: {
1346 // Try to transition the heap if the allocation failure was due to the space being full.
1347 if (!IsOutOfMemoryOnAllocation<false>(allocator, alloc_size)) {
1348 // If we aren't out of memory then the OOM was probably from the non moving space being
1349 // full. Attempt to disable compaction and turn the main space into a non moving space.
1350 DisableMovingGc();
1351 // If we are still a moving GC then something must have caused the transition to fail.
1352 if (IsMovingGc(collector_type_)) {
1353 MutexLock mu(self, *gc_complete_lock_);
1354 // If we couldn't disable moving GC, just throw OOME and return null.
1355 LOG(WARNING) << "Couldn't disable moving GC with disable GC count "
1356 << disable_moving_gc_count_;
1357 } else {
1358 LOG(WARNING) << "Disabled moving GC due to the non moving space being full";
1359 ptr = TryToAllocate<true, true>(self, allocator, alloc_size, bytes_allocated,
1360 usable_size);
1361 }
1362 }
1363 break;
1364 }
1365 default: {
1366 // Do nothing for others allocators.
1367 }
Zuo Wangf37a88b2014-07-10 04:26:41 -07001368 }
1369 }
1370 // If the allocation hasn't succeeded by this point, throw an OOM error.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001371 if (ptr == nullptr) {
Hiroshi Yamauchi654dd482014-07-09 12:54:32 -07001372 ThrowOutOfMemoryError(self, alloc_size, allocator);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001373 }
Mathieu Chartiercbb2d202013-11-14 17:45:16 -08001374 return ptr;
Carl Shapiro69759ea2011-07-21 18:13:35 -07001375}
1376
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001377void Heap::SetTargetHeapUtilization(float target) {
1378 DCHECK_GT(target, 0.0f); // asserted in Java code
1379 DCHECK_LT(target, 1.0f);
1380 target_utilization_ = target;
1381}
1382
Ian Rogers1d54e732013-05-02 21:10:01 -07001383size_t Heap::GetObjectsAllocated() const {
1384 size_t total = 0;
Mathieu Chartier590fee92013-09-13 13:46:47 -07001385 for (space::AllocSpace* space : alloc_spaces_) {
1386 total += space->GetObjectsAllocated();
Ian Rogers1d54e732013-05-02 21:10:01 -07001387 }
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001388 return total;
1389}
1390
Mathieu Chartierdd162fb2014-08-06 17:06:33 -07001391uint64_t Heap::GetObjectsAllocatedEver() const {
Mathieu Chartier692fafd2013-11-29 17:24:40 -08001392 return GetObjectsFreedEver() + GetObjectsAllocated();
Ian Rogers1d54e732013-05-02 21:10:01 -07001393}
1394
Mathieu Chartierdd162fb2014-08-06 17:06:33 -07001395uint64_t Heap::GetBytesAllocatedEver() const {
Mathieu Chartier692fafd2013-11-29 17:24:40 -08001396 return GetBytesFreedEver() + GetBytesAllocated();
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001397}
1398
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07001399class InstanceCounter {
1400 public:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001401 InstanceCounter(const std::vector<mirror::Class*>& classes, bool use_is_assignable_from, uint64_t* counts)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001402 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Elliott Hughesec0f83d2013-01-15 16:54:08 -08001403 : classes_(classes), use_is_assignable_from_(use_is_assignable_from), counts_(counts) {
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07001404 }
Mathieu Chartier412c7fc2014-02-07 12:18:39 -08001405 static void Callback(mirror::Object* obj, void* arg)
1406 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
1407 InstanceCounter* instance_counter = reinterpret_cast<InstanceCounter*>(arg);
1408 mirror::Class* instance_class = obj->GetClass();
1409 CHECK(instance_class != nullptr);
1410 for (size_t i = 0; i < instance_counter->classes_.size(); ++i) {
1411 if (instance_counter->use_is_assignable_from_) {
1412 if (instance_counter->classes_[i]->IsAssignableFrom(instance_class)) {
1413 ++instance_counter->counts_[i];
Elliott Hughesec0f83d2013-01-15 16:54:08 -08001414 }
Mathieu Chartier412c7fc2014-02-07 12:18:39 -08001415 } else if (instance_class == instance_counter->classes_[i]) {
1416 ++instance_counter->counts_[i];
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07001417 }
1418 }
1419 }
1420
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001421 private:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001422 const std::vector<mirror::Class*>& classes_;
Elliott Hughesec0f83d2013-01-15 16:54:08 -08001423 bool use_is_assignable_from_;
1424 uint64_t* const counts_;
Elliott Hughesec0f83d2013-01-15 16:54:08 -08001425 DISALLOW_COPY_AND_ASSIGN(InstanceCounter);
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07001426};
1427
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001428void Heap::CountInstances(const std::vector<mirror::Class*>& classes, bool use_is_assignable_from,
Elliott Hughesec0f83d2013-01-15 16:54:08 -08001429 uint64_t* counts) {
Mathieu Chartier412c7fc2014-02-07 12:18:39 -08001430 // Can't do any GC in this function since this may move classes.
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07001431 ScopedAssertNoThreadSuspension ants(Thread::Current(), "CountInstances");
Elliott Hughesec0f83d2013-01-15 16:54:08 -08001432 InstanceCounter counter(classes, use_is_assignable_from, counts);
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07001433 ReaderMutexLock mu(ants.Self(), *Locks::heap_bitmap_lock_);
Mathieu Chartier412c7fc2014-02-07 12:18:39 -08001434 VisitObjects(InstanceCounter::Callback, &counter);
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07001435}
1436
Elliott Hughes3b78c942013-01-15 17:35:41 -08001437class InstanceCollector {
1438 public:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001439 InstanceCollector(mirror::Class* c, int32_t max_count, std::vector<mirror::Object*>& instances)
Elliott Hughes3b78c942013-01-15 17:35:41 -08001440 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
1441 : class_(c), max_count_(max_count), instances_(instances) {
1442 }
Mathieu Chartier412c7fc2014-02-07 12:18:39 -08001443 static void Callback(mirror::Object* obj, void* arg)
1444 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
1445 DCHECK(arg != nullptr);
1446 InstanceCollector* instance_collector = reinterpret_cast<InstanceCollector*>(arg);
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07001447 if (obj->GetClass() == instance_collector->class_) {
Mathieu Chartier412c7fc2014-02-07 12:18:39 -08001448 if (instance_collector->max_count_ == 0 ||
1449 instance_collector->instances_.size() < instance_collector->max_count_) {
1450 instance_collector->instances_.push_back(obj);
Elliott Hughes3b78c942013-01-15 17:35:41 -08001451 }
1452 }
1453 }
1454
1455 private:
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07001456 const mirror::Class* const class_;
1457 const uint32_t max_count_;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001458 std::vector<mirror::Object*>& instances_;
Elliott Hughes3b78c942013-01-15 17:35:41 -08001459 DISALLOW_COPY_AND_ASSIGN(InstanceCollector);
1460};
1461
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001462void Heap::GetInstances(mirror::Class* c, int32_t max_count,
1463 std::vector<mirror::Object*>& instances) {
Mathieu Chartier412c7fc2014-02-07 12:18:39 -08001464 // Can't do any GC in this function since this may move classes.
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07001465 ScopedAssertNoThreadSuspension ants(Thread::Current(), "GetInstances");
Elliott Hughes3b78c942013-01-15 17:35:41 -08001466 InstanceCollector collector(c, max_count, instances);
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07001467 ReaderMutexLock mu(ants.Self(), *Locks::heap_bitmap_lock_);
Mathieu Chartier412c7fc2014-02-07 12:18:39 -08001468 VisitObjects(&InstanceCollector::Callback, &collector);
Elliott Hughes3b78c942013-01-15 17:35:41 -08001469}
1470
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001471class ReferringObjectsFinder {
1472 public:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001473 ReferringObjectsFinder(mirror::Object* object, int32_t max_count,
1474 std::vector<mirror::Object*>& referring_objects)
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001475 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
1476 : object_(object), max_count_(max_count), referring_objects_(referring_objects) {
1477 }
1478
Mathieu Chartier412c7fc2014-02-07 12:18:39 -08001479 static void Callback(mirror::Object* obj, void* arg)
1480 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
1481 reinterpret_cast<ReferringObjectsFinder*>(arg)->operator()(obj);
1482 }
1483
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001484 // For bitmap Visit.
1485 // TODO: Fix lock analysis to not use NO_THREAD_SAFETY_ANALYSIS, requires support for
1486 // annotalysis on visitors.
Mathieu Chartier0e54cd02014-03-20 12:41:23 -07001487 void operator()(mirror::Object* o) const NO_THREAD_SAFETY_ANALYSIS {
Ian Rogersb0fa5dc2014-04-28 16:47:08 -07001488 o->VisitReferences<true>(*this, VoidFunctor());
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001489 }
1490
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -07001491 // For Object::VisitReferences.
Mathieu Chartier407f7022014-02-18 14:37:05 -08001492 void operator()(mirror::Object* obj, MemberOffset offset, bool /* is_static */) const
1493 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogersb0fa5dc2014-04-28 16:47:08 -07001494 mirror::Object* ref = obj->GetFieldObject<mirror::Object>(offset);
Mathieu Chartier407f7022014-02-18 14:37:05 -08001495 if (ref == object_ && (max_count_ == 0 || referring_objects_.size() < max_count_)) {
1496 referring_objects_.push_back(obj);
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001497 }
1498 }
1499
1500 private:
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07001501 const mirror::Object* const object_;
1502 const uint32_t max_count_;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001503 std::vector<mirror::Object*>& referring_objects_;
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001504 DISALLOW_COPY_AND_ASSIGN(ReferringObjectsFinder);
1505};
1506
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001507void Heap::GetReferringObjects(mirror::Object* o, int32_t max_count,
1508 std::vector<mirror::Object*>& referring_objects) {
Mathieu Chartier83c8ee02014-01-28 14:50:23 -08001509 // Can't do any GC in this function since this may move the object o.
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07001510 ScopedAssertNoThreadSuspension ants(Thread::Current(), "GetReferringObjects");
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001511 ReferringObjectsFinder finder(o, max_count, referring_objects);
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07001512 ReaderMutexLock mu(ants.Self(), *Locks::heap_bitmap_lock_);
Mathieu Chartier412c7fc2014-02-07 12:18:39 -08001513 VisitObjects(&ReferringObjectsFinder::Callback, &finder);
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001514}
1515
Ian Rogers30fab402012-01-23 15:43:46 -08001516void Heap::CollectGarbage(bool clear_soft_references) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001517 // Even if we waited for a GC we still need to do another GC since weaks allocated during the
1518 // last GC will not have necessarily been cleared.
Mathieu Chartier7bf82af2013-12-06 16:51:45 -08001519 CollectGarbageInternal(gc_plan_.back(), kGcCauseExplicit, clear_soft_references);
Carl Shapiro69759ea2011-07-21 18:13:35 -07001520}
1521
Zuo Wangf37a88b2014-07-10 04:26:41 -07001522HomogeneousSpaceCompactResult Heap::PerformHomogeneousSpaceCompact() {
1523 Thread* self = Thread::Current();
1524 // Inc requested homogeneous space compaction.
1525 count_requested_homogeneous_space_compaction_++;
1526 // Store performed homogeneous space compaction at a new request arrival.
1527 ThreadList* tl = Runtime::Current()->GetThreadList();
1528 ScopedThreadStateChange tsc(self, kWaitingPerformingGc);
1529 Locks::mutator_lock_->AssertNotHeld(self);
1530 {
1531 ScopedThreadStateChange tsc(self, kWaitingForGcToComplete);
1532 MutexLock mu(self, *gc_complete_lock_);
1533 // Ensure there is only one GC at a time.
1534 WaitForGcToCompleteLocked(kGcCauseHomogeneousSpaceCompact, self);
1535 // Homogeneous space compaction is a copying transition, can't run it if the moving GC disable count
1536 // is non zero.
Mathieu Chartier6a7824d2014-08-22 14:53:04 -07001537 // If the collector type changed to something which doesn't benefit from homogeneous space compaction,
Zuo Wangf37a88b2014-07-10 04:26:41 -07001538 // exit.
Mathieu Chartier6a7824d2014-08-22 14:53:04 -07001539 if (disable_moving_gc_count_ != 0 || IsMovingGc(collector_type_) ||
1540 !main_space_->CanMoveObjects()) {
Zuo Wangf37a88b2014-07-10 04:26:41 -07001541 return HomogeneousSpaceCompactResult::kErrorReject;
1542 }
1543 collector_type_running_ = kCollectorTypeHomogeneousSpaceCompact;
1544 }
1545 if (Runtime::Current()->IsShuttingDown(self)) {
1546 // Don't allow heap transitions to happen if the runtime is shutting down since these can
1547 // cause objects to get finalized.
1548 FinishGC(self, collector::kGcTypeNone);
1549 return HomogeneousSpaceCompactResult::kErrorVMShuttingDown;
1550 }
1551 // Suspend all threads.
1552 tl->SuspendAll();
1553 uint64_t start_time = NanoTime();
1554 // Launch compaction.
Mathieu Chartierb363f662014-07-16 13:28:58 -07001555 space::MallocSpace* to_space = main_space_backup_.release();
Zuo Wangf37a88b2014-07-10 04:26:41 -07001556 space::MallocSpace* from_space = main_space_;
1557 to_space->GetMemMap()->Protect(PROT_READ | PROT_WRITE);
1558 const uint64_t space_size_before_compaction = from_space->Size();
Mathieu Chartierb363f662014-07-16 13:28:58 -07001559 AddSpace(to_space);
Zuo Wangf37a88b2014-07-10 04:26:41 -07001560 Compact(to_space, from_space, kGcCauseHomogeneousSpaceCompact);
1561 // Leave as prot read so that we can still run ROSAlloc verification on this space.
1562 from_space->GetMemMap()->Protect(PROT_READ);
1563 const uint64_t space_size_after_compaction = to_space->Size();
Mathieu Chartierb363f662014-07-16 13:28:58 -07001564 main_space_ = to_space;
1565 main_space_backup_.reset(from_space);
1566 RemoveSpace(from_space);
Zuo Wangf37a88b2014-07-10 04:26:41 -07001567 SetSpaceAsDefault(main_space_); // Set as default to reset the proper dlmalloc space.
1568 // Update performed homogeneous space compaction count.
1569 count_performed_homogeneous_space_compaction_++;
1570 // Print statics log and resume all threads.
1571 uint64_t duration = NanoTime() - start_time;
Mathieu Chartier98172a62014-09-02 12:33:25 -07001572 VLOG(heap) << "Heap homogeneous space compaction took " << PrettyDuration(duration) << " size: "
1573 << PrettySize(space_size_before_compaction) << " -> "
1574 << PrettySize(space_size_after_compaction) << " compact-ratio: "
1575 << std::fixed << static_cast<double>(space_size_after_compaction) /
1576 static_cast<double>(space_size_before_compaction);
Zuo Wangf37a88b2014-07-10 04:26:41 -07001577 tl->ResumeAll();
1578 // Finish GC.
1579 reference_processor_.EnqueueClearedReferences(self);
1580 GrowForUtilization(semi_space_collector_);
1581 FinishGC(self, collector::kGcTypeFull);
1582 return HomogeneousSpaceCompactResult::kSuccess;
1583}
1584
1585
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001586void Heap::TransitionCollector(CollectorType collector_type) {
1587 if (collector_type == collector_type_) {
1588 return;
1589 }
Hiroshi Yamauchia4adbfd2014-02-04 18:12:17 -08001590 VLOG(heap) << "TransitionCollector: " << static_cast<int>(collector_type_)
1591 << " -> " << static_cast<int>(collector_type);
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001592 uint64_t start_time = NanoTime();
Ian Rogers3e5cf302014-05-20 16:40:37 -07001593 uint32_t before_allocated = num_bytes_allocated_.LoadSequentiallyConsistent();
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001594 Runtime* const runtime = Runtime::Current();
1595 ThreadList* const tl = runtime->GetThreadList();
1596 Thread* const self = Thread::Current();
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001597 ScopedThreadStateChange tsc(self, kWaitingPerformingGc);
1598 Locks::mutator_lock_->AssertNotHeld(self);
Mathieu Chartier1d27b342014-01-28 12:51:09 -08001599 // Busy wait until we can GC (StartGC can fail if we have a non-zero
1600 // compacting_gc_disable_count_, this should rarely occurs).
Mathieu Chartierd5a89ee2014-01-31 09:55:13 -08001601 for (;;) {
Mathieu Chartiercaa82d62014-02-02 16:51:17 -08001602 {
1603 ScopedThreadStateChange tsc(self, kWaitingForGcToComplete);
1604 MutexLock mu(self, *gc_complete_lock_);
1605 // Ensure there is only one GC at a time.
Mathieu Chartier89a201e2014-05-02 10:27:26 -07001606 WaitForGcToCompleteLocked(kGcCauseCollectorTransition, self);
Mathieu Chartiere4927f62014-08-23 13:56:03 -07001607 // Currently we only need a heap transition if we switch from a moving collector to a
1608 // non-moving one, or visa versa.
1609 const bool copying_transition = IsMovingGc(collector_type_) != IsMovingGc(collector_type);
Mathieu Chartierb38d4832014-04-10 10:56:55 -07001610 // If someone else beat us to it and changed the collector before we could, exit.
1611 // This is safe to do before the suspend all since we set the collector_type_running_ before
1612 // we exit the loop. If another thread attempts to do the heap transition before we exit,
1613 // then it would get blocked on WaitForGcToCompleteLocked.
1614 if (collector_type == collector_type_) {
1615 return;
1616 }
Mathieu Chartiercaa82d62014-02-02 16:51:17 -08001617 // GC can be disabled if someone has a used GetPrimitiveArrayCritical but not yet released.
1618 if (!copying_transition || disable_moving_gc_count_ == 0) {
1619 // TODO: Not hard code in semi-space collector?
1620 collector_type_running_ = copying_transition ? kCollectorTypeSS : collector_type;
1621 break;
1622 }
Mathieu Chartierd5a89ee2014-01-31 09:55:13 -08001623 }
Mathieu Chartiercaa82d62014-02-02 16:51:17 -08001624 usleep(1000);
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001625 }
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001626 if (runtime->IsShuttingDown(self)) {
Hiroshi Yamauchia6a8d142014-05-12 16:57:33 -07001627 // Don't allow heap transitions to happen if the runtime is shutting down since these can
1628 // cause objects to get finalized.
1629 FinishGC(self, collector::kGcTypeNone);
1630 return;
1631 }
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001632 tl->SuspendAll();
1633 switch (collector_type) {
Mathieu Chartierb363f662014-07-16 13:28:58 -07001634 case kCollectorTypeSS: {
Mathieu Chartier31f44142014-04-08 14:40:03 -07001635 if (!IsMovingGc(collector_type_)) {
Mathieu Chartierb363f662014-07-16 13:28:58 -07001636 // Create the bump pointer space from the backup space.
1637 CHECK(main_space_backup_ != nullptr);
1638 std::unique_ptr<MemMap> mem_map(main_space_backup_->ReleaseMemMap());
Mathieu Chartier31f44142014-04-08 14:40:03 -07001639 // We are transitioning from non moving GC -> moving GC, since we copied from the bump
1640 // pointer space last transition it will be protected.
Mathieu Chartierb363f662014-07-16 13:28:58 -07001641 CHECK(mem_map != nullptr);
1642 mem_map->Protect(PROT_READ | PROT_WRITE);
1643 bump_pointer_space_ = space::BumpPointerSpace::CreateFromMemMap("Bump pointer space",
1644 mem_map.release());
1645 AddSpace(bump_pointer_space_);
Zuo Wangf37a88b2014-07-10 04:26:41 -07001646 Compact(bump_pointer_space_, main_space_, kGcCauseCollectorTransition);
Mathieu Chartierb363f662014-07-16 13:28:58 -07001647 // Use the now empty main space mem map for the bump pointer temp space.
1648 mem_map.reset(main_space_->ReleaseMemMap());
Mathieu Chartier00b59152014-07-25 10:13:51 -07001649 // Unset the pointers just in case.
1650 if (dlmalloc_space_ == main_space_) {
1651 dlmalloc_space_ = nullptr;
1652 } else if (rosalloc_space_ == main_space_) {
1653 rosalloc_space_ = nullptr;
1654 }
Mathieu Chartier2796a162014-07-25 11:50:47 -07001655 // Remove the main space so that we don't try to trim it, this doens't work for debug
1656 // builds since RosAlloc attempts to read the magic number from a protected page.
1657 RemoveSpace(main_space_);
Mathieu Chartierc5a83472014-07-23 18:45:17 -07001658 RemoveRememberedSet(main_space_);
Mathieu Chartier2796a162014-07-25 11:50:47 -07001659 delete main_space_; // Delete the space since it has been removed.
Mathieu Chartierc5a83472014-07-23 18:45:17 -07001660 main_space_ = nullptr;
Mathieu Chartier2796a162014-07-25 11:50:47 -07001661 RemoveRememberedSet(main_space_backup_.get());
1662 main_space_backup_.reset(nullptr); // Deletes the space.
Mathieu Chartierb363f662014-07-16 13:28:58 -07001663 temp_space_ = space::BumpPointerSpace::CreateFromMemMap("Bump pointer space 2",
1664 mem_map.release());
1665 AddSpace(temp_space_);
Mathieu Chartier31f44142014-04-08 14:40:03 -07001666 }
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001667 break;
1668 }
1669 case kCollectorTypeMS:
1670 // Fall through.
1671 case kCollectorTypeCMS: {
Mathieu Chartier31f44142014-04-08 14:40:03 -07001672 if (IsMovingGc(collector_type_)) {
Mathieu Chartierb363f662014-07-16 13:28:58 -07001673 CHECK(temp_space_ != nullptr);
1674 std::unique_ptr<MemMap> mem_map(temp_space_->ReleaseMemMap());
1675 RemoveSpace(temp_space_);
1676 temp_space_ = nullptr;
Mathieu Chartier36dab362014-07-30 14:59:56 -07001677 mem_map->Protect(PROT_READ | PROT_WRITE);
Mathieu Chartierb363f662014-07-16 13:28:58 -07001678 CreateMainMallocSpace(mem_map.get(), kDefaultInitialSize, mem_map->Size(),
1679 mem_map->Size());
1680 mem_map.release();
Mathieu Chartier31f44142014-04-08 14:40:03 -07001681 // Compact to the main space from the bump pointer space, don't need to swap semispaces.
Mathieu Chartier1b54f9c2014-04-30 16:45:02 -07001682 AddSpace(main_space_);
Zuo Wangf37a88b2014-07-10 04:26:41 -07001683 Compact(main_space_, bump_pointer_space_, kGcCauseCollectorTransition);
Mathieu Chartierb363f662014-07-16 13:28:58 -07001684 mem_map.reset(bump_pointer_space_->ReleaseMemMap());
1685 RemoveSpace(bump_pointer_space_);
1686 bump_pointer_space_ = nullptr;
1687 const char* name = kUseRosAlloc ? kRosAllocSpaceName[1] : kDlMallocSpaceName[1];
Hiroshi Yamauchic1276c82014-08-07 10:27:17 -07001688 // Temporarily unprotect the backup mem map so rosalloc can write the debug magic number.
1689 if (kIsDebugBuild && kUseRosAlloc) {
1690 mem_map->Protect(PROT_READ | PROT_WRITE);
1691 }
Mathieu Chartierb363f662014-07-16 13:28:58 -07001692 main_space_backup_.reset(CreateMallocSpaceFromMemMap(mem_map.get(), kDefaultInitialSize,
1693 mem_map->Size(), mem_map->Size(),
1694 name, true));
Hiroshi Yamauchic1276c82014-08-07 10:27:17 -07001695 if (kIsDebugBuild && kUseRosAlloc) {
1696 mem_map->Protect(PROT_NONE);
1697 }
Mathieu Chartierb363f662014-07-16 13:28:58 -07001698 mem_map.release();
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001699 }
1700 break;
1701 }
1702 default: {
Hiroshi Yamauchid5307ec2014-03-27 21:07:51 -07001703 LOG(FATAL) << "Attempted to transition to invalid collector type "
1704 << static_cast<size_t>(collector_type);
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001705 break;
1706 }
1707 }
1708 ChangeCollector(collector_type);
1709 tl->ResumeAll();
1710 // Can't call into java code with all threads suspended.
Mathieu Chartier308351a2014-06-15 12:39:02 -07001711 reference_processor_.EnqueueClearedReferences(self);
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001712 uint64_t duration = NanoTime() - start_time;
Mathieu Chartierafe49982014-03-27 10:55:04 -07001713 GrowForUtilization(semi_space_collector_);
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001714 FinishGC(self, collector::kGcTypeFull);
Ian Rogers3e5cf302014-05-20 16:40:37 -07001715 int32_t after_allocated = num_bytes_allocated_.LoadSequentiallyConsistent();
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001716 int32_t delta_allocated = before_allocated - after_allocated;
Mathieu Chartier19d46b42014-06-17 15:04:40 -07001717 std::string saved_str;
1718 if (delta_allocated >= 0) {
1719 saved_str = " saved at least " + PrettySize(delta_allocated);
1720 } else {
1721 saved_str = " expanded " + PrettySize(-delta_allocated);
1722 }
Mathieu Chartier98172a62014-09-02 12:33:25 -07001723 VLOG(heap) << "Heap transition to " << process_state_ << " took "
Mathieu Chartier19d46b42014-06-17 15:04:40 -07001724 << PrettyDuration(duration) << saved_str;
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001725}
1726
Mathieu Chartier0de9f732013-11-22 17:58:48 -08001727void Heap::ChangeCollector(CollectorType collector_type) {
Mathieu Chartier7bf82af2013-12-06 16:51:45 -08001728 // TODO: Only do this with all mutators suspended to avoid races.
1729 if (collector_type != collector_type_) {
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001730 if (collector_type == kCollectorTypeMC) {
1731 // Don't allow mark compact unless support is compiled in.
1732 CHECK(kMarkCompactSupport);
1733 }
Mathieu Chartier7bf82af2013-12-06 16:51:45 -08001734 collector_type_ = collector_type;
1735 gc_plan_.clear();
1736 switch (collector_type_) {
Hiroshi Yamauchid5307ec2014-03-27 21:07:51 -07001737 case kCollectorTypeCC: // Fall-through.
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001738 case kCollectorTypeMC: // Fall-through.
Hiroshi Yamauchi3e417802014-03-20 12:03:02 -07001739 case kCollectorTypeSS: // Fall-through.
Hiroshi Yamauchi6f4ffe42014-01-13 12:30:44 -08001740 case kCollectorTypeGSS: {
Mathieu Chartier7bf82af2013-12-06 16:51:45 -08001741 gc_plan_.push_back(collector::kGcTypeFull);
Mathieu Chartier692fafd2013-11-29 17:24:40 -08001742 if (use_tlab_) {
1743 ChangeAllocator(kAllocatorTypeTLAB);
1744 } else {
1745 ChangeAllocator(kAllocatorTypeBumpPointer);
1746 }
Mathieu Chartier7bf82af2013-12-06 16:51:45 -08001747 break;
1748 }
1749 case kCollectorTypeMS: {
Mathieu Chartier7bf82af2013-12-06 16:51:45 -08001750 gc_plan_.push_back(collector::kGcTypeSticky);
1751 gc_plan_.push_back(collector::kGcTypePartial);
1752 gc_plan_.push_back(collector::kGcTypeFull);
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001753 ChangeAllocator(kUseRosAlloc ? kAllocatorTypeRosAlloc : kAllocatorTypeDlMalloc);
Mathieu Chartier7bf82af2013-12-06 16:51:45 -08001754 break;
1755 }
1756 case kCollectorTypeCMS: {
Mathieu Chartier7bf82af2013-12-06 16:51:45 -08001757 gc_plan_.push_back(collector::kGcTypeSticky);
1758 gc_plan_.push_back(collector::kGcTypePartial);
1759 gc_plan_.push_back(collector::kGcTypeFull);
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001760 ChangeAllocator(kUseRosAlloc ? kAllocatorTypeRosAlloc : kAllocatorTypeDlMalloc);
Mathieu Chartier7bf82af2013-12-06 16:51:45 -08001761 break;
1762 }
1763 default: {
1764 LOG(FATAL) << "Unimplemented";
1765 }
Mathieu Chartier0de9f732013-11-22 17:58:48 -08001766 }
Hiroshi Yamauchi3e417802014-03-20 12:03:02 -07001767 if (IsGcConcurrent()) {
Mathieu Chartier7bf82af2013-12-06 16:51:45 -08001768 concurrent_start_bytes_ =
1769 std::max(max_allowed_footprint_, kMinConcurrentRemainingBytes) - kMinConcurrentRemainingBytes;
1770 } else {
1771 concurrent_start_bytes_ = std::numeric_limits<size_t>::max();
Mathieu Chartier0de9f732013-11-22 17:58:48 -08001772 }
1773 }
1774}
1775
Mathieu Chartier85a43c02014-01-07 17:59:00 -08001776// Special compacting collector which uses sub-optimal bin packing to reduce zygote space size.
Ian Rogers6fac4472014-02-25 17:01:10 -08001777class ZygoteCompactingCollector FINAL : public collector::SemiSpace {
Mathieu Chartier85a43c02014-01-07 17:59:00 -08001778 public:
Hiroshi Yamauchi38e68e92014-03-07 13:59:08 -08001779 explicit ZygoteCompactingCollector(gc::Heap* heap) : SemiSpace(heap, false, "zygote collector"),
Ian Rogers6fac4472014-02-25 17:01:10 -08001780 bin_live_bitmap_(nullptr), bin_mark_bitmap_(nullptr) {
Mathieu Chartier85a43c02014-01-07 17:59:00 -08001781 }
1782
1783 void BuildBins(space::ContinuousSpace* space) {
1784 bin_live_bitmap_ = space->GetLiveBitmap();
1785 bin_mark_bitmap_ = space->GetMarkBitmap();
1786 BinContext context;
1787 context.prev_ = reinterpret_cast<uintptr_t>(space->Begin());
1788 context.collector_ = this;
1789 WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
1790 // Note: This requires traversing the space in increasing order of object addresses.
1791 bin_live_bitmap_->Walk(Callback, reinterpret_cast<void*>(&context));
1792 // Add the last bin which spans after the last object to the end of the space.
1793 AddBin(reinterpret_cast<uintptr_t>(space->End()) - context.prev_, context.prev_);
1794 }
1795
1796 private:
1797 struct BinContext {
1798 uintptr_t prev_; // The end of the previous object.
1799 ZygoteCompactingCollector* collector_;
1800 };
1801 // Maps from bin sizes to locations.
1802 std::multimap<size_t, uintptr_t> bins_;
1803 // Live bitmap of the space which contains the bins.
Mathieu Chartiera8e8f9c2014-04-09 14:51:05 -07001804 accounting::ContinuousSpaceBitmap* bin_live_bitmap_;
Mathieu Chartier85a43c02014-01-07 17:59:00 -08001805 // Mark bitmap of the space which contains the bins.
Mathieu Chartiera8e8f9c2014-04-09 14:51:05 -07001806 accounting::ContinuousSpaceBitmap* bin_mark_bitmap_;
Mathieu Chartier85a43c02014-01-07 17:59:00 -08001807
1808 static void Callback(mirror::Object* obj, void* arg)
1809 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1810 DCHECK(arg != nullptr);
1811 BinContext* context = reinterpret_cast<BinContext*>(arg);
1812 ZygoteCompactingCollector* collector = context->collector_;
1813 uintptr_t object_addr = reinterpret_cast<uintptr_t>(obj);
1814 size_t bin_size = object_addr - context->prev_;
1815 // Add the bin consisting of the end of the previous object to the start of the current object.
1816 collector->AddBin(bin_size, context->prev_);
1817 context->prev_ = object_addr + RoundUp(obj->SizeOf(), kObjectAlignment);
1818 }
1819
1820 void AddBin(size_t size, uintptr_t position) {
1821 if (size != 0) {
1822 bins_.insert(std::make_pair(size, position));
1823 }
1824 }
1825
Mathieu Chartiera1602f22014-01-13 17:19:19 -08001826 virtual bool ShouldSweepSpace(space::ContinuousSpace* space) const {
Mathieu Chartier85a43c02014-01-07 17:59:00 -08001827 // Don't sweep any spaces since we probably blasted the internal accounting of the free list
1828 // allocator.
1829 return false;
1830 }
1831
1832 virtual mirror::Object* MarkNonForwardedObject(mirror::Object* obj)
1833 EXCLUSIVE_LOCKS_REQUIRED(Locks::heap_bitmap_lock_, Locks::mutator_lock_) {
1834 size_t object_size = RoundUp(obj->SizeOf(), kObjectAlignment);
Mathieu Chartier5dc08a62014-01-10 10:10:23 -08001835 mirror::Object* forward_address;
Mathieu Chartier85a43c02014-01-07 17:59:00 -08001836 // Find the smallest bin which we can move obj in.
1837 auto it = bins_.lower_bound(object_size);
1838 if (it == bins_.end()) {
1839 // No available space in the bins, place it in the target space instead (grows the zygote
1840 // space).
Mathieu Chartier5dc08a62014-01-10 10:10:23 -08001841 size_t bytes_allocated;
Ian Rogers6fac4472014-02-25 17:01:10 -08001842 forward_address = to_space_->Alloc(self_, object_size, &bytes_allocated, nullptr);
Mathieu Chartier85a43c02014-01-07 17:59:00 -08001843 if (to_space_live_bitmap_ != nullptr) {
1844 to_space_live_bitmap_->Set(forward_address);
Mathieu Chartier938a03b2014-01-16 15:10:31 -08001845 } else {
1846 GetHeap()->GetNonMovingSpace()->GetLiveBitmap()->Set(forward_address);
1847 GetHeap()->GetNonMovingSpace()->GetMarkBitmap()->Set(forward_address);
Mathieu Chartier85a43c02014-01-07 17:59:00 -08001848 }
1849 } else {
1850 size_t size = it->first;
1851 uintptr_t pos = it->second;
1852 bins_.erase(it); // Erase the old bin which we replace with the new smaller bin.
1853 forward_address = reinterpret_cast<mirror::Object*>(pos);
1854 // Set the live and mark bits so that sweeping system weaks works properly.
1855 bin_live_bitmap_->Set(forward_address);
1856 bin_mark_bitmap_->Set(forward_address);
1857 DCHECK_GE(size, object_size);
1858 AddBin(size - object_size, pos + object_size); // Add a new bin with the remaining space.
1859 }
1860 // Copy the object over to its new location.
1861 memcpy(reinterpret_cast<void*>(forward_address), obj, object_size);
Hiroshi Yamauchi624468c2014-03-31 15:14:47 -07001862 if (kUseBakerOrBrooksReadBarrier) {
1863 obj->AssertReadBarrierPointer();
1864 if (kUseBrooksReadBarrier) {
1865 DCHECK_EQ(forward_address->GetReadBarrierPointer(), obj);
1866 forward_address->SetReadBarrierPointer(forward_address);
1867 }
1868 forward_address->AssertReadBarrierPointer();
Hiroshi Yamauchi9d04a202014-01-31 13:35:49 -08001869 }
Mathieu Chartier85a43c02014-01-07 17:59:00 -08001870 return forward_address;
1871 }
1872};
1873
Mathieu Chartiera1602f22014-01-13 17:19:19 -08001874void Heap::UnBindBitmaps() {
Mathieu Chartierf5997b42014-06-20 10:37:54 -07001875 TimingLogger::ScopedTiming t("UnBindBitmaps", GetCurrentGcIteration()->GetTimings());
Mathieu Chartiera1602f22014-01-13 17:19:19 -08001876 for (const auto& space : GetContinuousSpaces()) {
1877 if (space->IsContinuousMemMapAllocSpace()) {
1878 space::ContinuousMemMapAllocSpace* alloc_space = space->AsContinuousMemMapAllocSpace();
1879 if (alloc_space->HasBoundBitmaps()) {
1880 alloc_space->UnBindBitmaps();
1881 }
1882 }
1883 }
1884}
1885
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001886void Heap::PreZygoteFork() {
Mathieu Chartier1f3b5352014-02-03 14:00:42 -08001887 CollectGarbageInternal(collector::kGcTypeFull, kGcCauseBackground, false);
Ian Rogers81d425b2012-09-27 16:03:43 -07001888 Thread* self = Thread::Current();
1889 MutexLock mu(self, zygote_creation_lock_);
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001890 // Try to see if we have any Zygote spaces.
Mathieu Chartiere4cab172014-08-19 18:24:04 -07001891 if (HasZygoteSpace()) {
1892 LOG(WARNING) << __FUNCTION__ << " called when we already have a zygote space.";
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001893 return;
1894 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07001895 VLOG(heap) << "Starting PreZygoteFork";
Mathieu Chartier590fee92013-09-13 13:46:47 -07001896 // Trim the pages at the end of the non moving space.
1897 non_moving_space_->Trim();
Mathieu Chartier31f44142014-04-08 14:40:03 -07001898 // The end of the non-moving space may be protected, unprotect it so that we can copy the zygote
1899 // there.
Mathieu Chartier590fee92013-09-13 13:46:47 -07001900 non_moving_space_->GetMemMap()->Protect(PROT_READ | PROT_WRITE);
Mathieu Chartier6a7824d2014-08-22 14:53:04 -07001901 const bool same_space = non_moving_space_ == main_space_;
Mathieu Chartier31f44142014-04-08 14:40:03 -07001902 if (kCompactZygote) {
Mathieu Chartier6a7824d2014-08-22 14:53:04 -07001903 // Can't compact if the non moving space is the same as the main space.
Mathieu Chartier31f44142014-04-08 14:40:03 -07001904 DCHECK(semi_space_collector_ != nullptr);
Hiroshi Yamauchia4adbfd2014-02-04 18:12:17 -08001905 // Temporarily disable rosalloc verification because the zygote
1906 // compaction will mess up the rosalloc internal metadata.
1907 ScopedDisableRosAllocVerification disable_rosalloc_verif(this);
Mathieu Chartier85a43c02014-01-07 17:59:00 -08001908 ZygoteCompactingCollector zygote_collector(this);
1909 zygote_collector.BuildBins(non_moving_space_);
Mathieu Chartier50482232013-11-21 11:48:14 -08001910 // Create a new bump pointer space which we will compact into.
Mathieu Chartier590fee92013-09-13 13:46:47 -07001911 space::BumpPointerSpace target_space("zygote bump space", non_moving_space_->End(),
1912 non_moving_space_->Limit());
1913 // Compact the bump pointer space to a new zygote bump pointer space.
Mathieu Chartier31f44142014-04-08 14:40:03 -07001914 bool reset_main_space = false;
1915 if (IsMovingGc(collector_type_)) {
1916 zygote_collector.SetFromSpace(bump_pointer_space_);
1917 } else {
1918 CHECK(main_space_ != nullptr);
1919 // Copy from the main space.
1920 zygote_collector.SetFromSpace(main_space_);
1921 reset_main_space = true;
1922 }
Mathieu Chartier85a43c02014-01-07 17:59:00 -08001923 zygote_collector.SetToSpace(&target_space);
Mathieu Chartier1b54f9c2014-04-30 16:45:02 -07001924 zygote_collector.SetSwapSemiSpaces(false);
Hiroshi Yamauchi6f4ffe42014-01-13 12:30:44 -08001925 zygote_collector.Run(kGcCauseCollectorTransition, false);
Mathieu Chartier31f44142014-04-08 14:40:03 -07001926 if (reset_main_space) {
1927 main_space_->GetMemMap()->Protect(PROT_READ | PROT_WRITE);
1928 madvise(main_space_->Begin(), main_space_->Capacity(), MADV_DONTNEED);
1929 MemMap* mem_map = main_space_->ReleaseMemMap();
1930 RemoveSpace(main_space_);
Mathieu Chartier96bcd452014-06-17 09:50:02 -07001931 space::Space* old_main_space = main_space_;
Mathieu Chartier31f44142014-04-08 14:40:03 -07001932 CreateMainMallocSpace(mem_map, kDefaultInitialSize, mem_map->Size(), mem_map->Size());
Mathieu Chartier96bcd452014-06-17 09:50:02 -07001933 delete old_main_space;
Mathieu Chartier31f44142014-04-08 14:40:03 -07001934 AddSpace(main_space_);
1935 } else {
1936 bump_pointer_space_->GetMemMap()->Protect(PROT_READ | PROT_WRITE);
1937 }
1938 if (temp_space_ != nullptr) {
1939 CHECK(temp_space_->IsEmpty());
1940 }
Mathieu Chartier10fb83a2014-06-15 15:15:43 -07001941 total_objects_freed_ever_ += GetCurrentGcIteration()->GetFreedObjects();
1942 total_bytes_freed_ever_ += GetCurrentGcIteration()->GetFreedBytes();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001943 // Update the end and write out image.
1944 non_moving_space_->SetEnd(target_space.End());
1945 non_moving_space_->SetLimit(target_space.Limit());
Mathieu Chartier31f44142014-04-08 14:40:03 -07001946 VLOG(heap) << "Zygote space size " << non_moving_space_->Size() << " bytes";
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001947 }
Mathieu Chartier6a7824d2014-08-22 14:53:04 -07001948 // Change the collector to the post zygote one.
Mathieu Chartier31f44142014-04-08 14:40:03 -07001949 ChangeCollector(foreground_collector_type_);
Mathieu Chartiera1602f22014-01-13 17:19:19 -08001950 // Save the old space so that we can remove it after we complete creating the zygote space.
1951 space::MallocSpace* old_alloc_space = non_moving_space_;
Mathieu Chartier590fee92013-09-13 13:46:47 -07001952 // Turn the current alloc space into a zygote space and obtain the new alloc space composed of
Mathieu Chartiera1602f22014-01-13 17:19:19 -08001953 // the remaining available space.
1954 // Remove the old space before creating the zygote space since creating the zygote space sets
1955 // the old alloc space's bitmaps to nullptr.
1956 RemoveSpace(old_alloc_space);
Hiroshi Yamauchi38e68e92014-03-07 13:59:08 -08001957 if (collector::SemiSpace::kUseRememberedSet) {
1958 // Sanity bound check.
1959 FindRememberedSetFromSpace(old_alloc_space)->AssertAllDirtyCardsAreWithinSpace();
1960 // Remove the remembered set for the now zygote space (the old
1961 // non-moving space). Note now that we have compacted objects into
1962 // the zygote space, the data in the remembered set is no longer
1963 // needed. The zygote space will instead have a mod-union table
1964 // from this point on.
1965 RemoveRememberedSet(old_alloc_space);
1966 }
Mathieu Chartiere4cab172014-08-19 18:24:04 -07001967 zygote_space_ = old_alloc_space->CreateZygoteSpace("alloc space", low_memory_mode_,
1968 &non_moving_space_);
Mathieu Chartierb363f662014-07-16 13:28:58 -07001969 CHECK(!non_moving_space_->CanMoveObjects());
1970 if (same_space) {
1971 main_space_ = non_moving_space_;
1972 SetSpaceAsDefault(main_space_);
1973 }
Mathieu Chartiera1602f22014-01-13 17:19:19 -08001974 delete old_alloc_space;
Mathieu Chartiere4cab172014-08-19 18:24:04 -07001975 CHECK(HasZygoteSpace()) << "Failed creating zygote space";
1976 AddSpace(zygote_space_);
Mathieu Chartier31f44142014-04-08 14:40:03 -07001977 non_moving_space_->SetFootprintLimit(non_moving_space_->Capacity());
1978 AddSpace(non_moving_space_);
Mathieu Chartier11409ae2013-09-23 11:49:36 -07001979 // Create the zygote space mod union table.
1980 accounting::ModUnionTable* mod_union_table =
Mathieu Chartiere4cab172014-08-19 18:24:04 -07001981 new accounting::ModUnionTableCardCache("zygote space mod-union table", this,
1982 zygote_space_);
Mathieu Chartier11409ae2013-09-23 11:49:36 -07001983 CHECK(mod_union_table != nullptr) << "Failed to create zygote space mod-union table";
Mathieu Chartiere4cab172014-08-19 18:24:04 -07001984 // Set all the cards in the mod-union table since we don't know which objects contain references
1985 // to large objects.
1986 mod_union_table->SetCards();
Mathieu Chartier11409ae2013-09-23 11:49:36 -07001987 AddModUnionTable(mod_union_table);
Hiroshi Yamauchi38e68e92014-03-07 13:59:08 -08001988 if (collector::SemiSpace::kUseRememberedSet) {
Hiroshi Yamauchi38e68e92014-03-07 13:59:08 -08001989 // Add a new remembered set for the post-zygote non-moving space.
1990 accounting::RememberedSet* post_zygote_non_moving_space_rem_set =
1991 new accounting::RememberedSet("Post-zygote non-moving space remembered set", this,
1992 non_moving_space_);
1993 CHECK(post_zygote_non_moving_space_rem_set != nullptr)
1994 << "Failed to create post-zygote non-moving space remembered set";
1995 AddRememberedSet(post_zygote_non_moving_space_rem_set);
1996 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001997}
1998
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001999void Heap::FlushAllocStack() {
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08002000 MarkAllocStackAsLive(allocation_stack_.get());
Mathieu Chartier357e9be2012-08-01 11:00:14 -07002001 allocation_stack_->Reset();
2002}
2003
Mathieu Chartiera8e8f9c2014-04-09 14:51:05 -07002004void Heap::MarkAllocStack(accounting::ContinuousSpaceBitmap* bitmap1,
2005 accounting::ContinuousSpaceBitmap* bitmap2,
Mathieu Chartierbbd695c2014-04-16 09:48:48 -07002006 accounting::LargeObjectBitmap* large_objects,
Ian Rogers1d54e732013-05-02 21:10:01 -07002007 accounting::ObjectStack* stack) {
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08002008 DCHECK(bitmap1 != nullptr);
2009 DCHECK(bitmap2 != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002010 mirror::Object** limit = stack->End();
2011 for (mirror::Object** it = stack->Begin(); it != limit; ++it) {
2012 const mirror::Object* obj = *it;
Hiroshi Yamauchif5b0e202014-02-11 17:02:22 -08002013 if (!kUseThreadLocalAllocationStack || obj != nullptr) {
2014 if (bitmap1->HasAddress(obj)) {
2015 bitmap1->Set(obj);
2016 } else if (bitmap2->HasAddress(obj)) {
2017 bitmap2->Set(obj);
2018 } else {
Mathieu Chartier2dbe6272014-09-16 10:43:23 -07002019 DCHECK(large_objects != nullptr);
Hiroshi Yamauchif5b0e202014-02-11 17:02:22 -08002020 large_objects->Set(obj);
2021 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07002022 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07002023 }
2024}
2025
Mathieu Chartier590fee92013-09-13 13:46:47 -07002026void Heap::SwapSemiSpaces() {
Mathieu Chartier31f44142014-04-08 14:40:03 -07002027 CHECK(bump_pointer_space_ != nullptr);
2028 CHECK(temp_space_ != nullptr);
Mathieu Chartier590fee92013-09-13 13:46:47 -07002029 std::swap(bump_pointer_space_, temp_space_);
2030}
2031
2032void Heap::Compact(space::ContinuousMemMapAllocSpace* target_space,
Zuo Wangf37a88b2014-07-10 04:26:41 -07002033 space::ContinuousMemMapAllocSpace* source_space,
2034 GcCause gc_cause) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07002035 CHECK(kMovingCollector);
Mathieu Chartier590fee92013-09-13 13:46:47 -07002036 if (target_space != source_space) {
Mathieu Chartier6f365cc2014-04-23 12:42:27 -07002037 // Don't swap spaces since this isn't a typical semi space collection.
2038 semi_space_collector_->SetSwapSemiSpaces(false);
Mathieu Chartier590fee92013-09-13 13:46:47 -07002039 semi_space_collector_->SetFromSpace(source_space);
2040 semi_space_collector_->SetToSpace(target_space);
Zuo Wangf37a88b2014-07-10 04:26:41 -07002041 semi_space_collector_->Run(gc_cause, false);
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002042 } else {
2043 CHECK(target_space->IsBumpPointerSpace())
2044 << "In-place compaction is only supported for bump pointer spaces";
2045 mark_compact_collector_->SetSpace(target_space->AsBumpPointerSpace());
2046 mark_compact_collector_->Run(kGcCauseCollectorTransition, false);
Mathieu Chartier590fee92013-09-13 13:46:47 -07002047 }
2048}
Anwar Ghuloum67f99412013-08-12 14:19:48 -07002049
Ian Rogers1d54e732013-05-02 21:10:01 -07002050collector::GcType Heap::CollectGarbageInternal(collector::GcType gc_type, GcCause gc_cause,
2051 bool clear_soft_references) {
Ian Rogers81d425b2012-09-27 16:03:43 -07002052 Thread* self = Thread::Current();
Mathieu Chartier590fee92013-09-13 13:46:47 -07002053 Runtime* runtime = Runtime::Current();
Mathieu Chartiercbb2d202013-11-14 17:45:16 -08002054 // If the heap can't run the GC, silently fail and return that no GC was run.
2055 switch (gc_type) {
Mathieu Chartiercbb2d202013-11-14 17:45:16 -08002056 case collector::kGcTypePartial: {
Mathieu Chartiere4cab172014-08-19 18:24:04 -07002057 if (!HasZygoteSpace()) {
Mathieu Chartiercbb2d202013-11-14 17:45:16 -08002058 return collector::kGcTypeNone;
2059 }
2060 break;
2061 }
2062 default: {
2063 // Other GC types don't have any special cases which makes them not runnable. The main case
2064 // here is full GC.
2065 }
2066 }
Mathieu Chartier65db8802012-11-20 12:36:46 -08002067 ScopedThreadStateChange tsc(self, kWaitingPerformingGc);
Ian Rogers81d425b2012-09-27 16:03:43 -07002068 Locks::mutator_lock_->AssertNotHeld(self);
Ian Rogers120f1c72012-09-28 17:17:10 -07002069 if (self->IsHandlingStackOverflow()) {
2070 LOG(WARNING) << "Performing GC on a thread that is handling a stack overflow.";
2071 }
Mathieu Chartierd5a89ee2014-01-31 09:55:13 -08002072 bool compacting_gc;
2073 {
2074 gc_complete_lock_->AssertNotHeld(self);
Mathieu Chartiercaa82d62014-02-02 16:51:17 -08002075 ScopedThreadStateChange tsc(self, kWaitingForGcToComplete);
Mathieu Chartierd5a89ee2014-01-31 09:55:13 -08002076 MutexLock mu(self, *gc_complete_lock_);
2077 // Ensure there is only one GC at a time.
Mathieu Chartier89a201e2014-05-02 10:27:26 -07002078 WaitForGcToCompleteLocked(gc_cause, self);
Mathieu Chartier31f44142014-04-08 14:40:03 -07002079 compacting_gc = IsMovingGc(collector_type_);
Mathieu Chartierd5a89ee2014-01-31 09:55:13 -08002080 // GC can be disabled if someone has a used GetPrimitiveArrayCritical.
2081 if (compacting_gc && disable_moving_gc_count_ != 0) {
2082 LOG(WARNING) << "Skipping GC due to disable moving GC count " << disable_moving_gc_count_;
2083 return collector::kGcTypeNone;
2084 }
2085 collector_type_running_ = collector_type_;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002086 }
Mathieu Chartierd5a89ee2014-01-31 09:55:13 -08002087
Mathieu Chartier590fee92013-09-13 13:46:47 -07002088 if (gc_cause == kGcCauseForAlloc && runtime->HasStatsEnabled()) {
2089 ++runtime->GetStats()->gc_for_alloc_count;
2090 ++self->GetStats()->gc_for_alloc_count;
Mathieu Chartier2fde5332012-09-14 14:51:54 -07002091 }
Ian Rogers1d54e732013-05-02 21:10:01 -07002092 uint64_t gc_start_time_ns = NanoTime();
Mathieu Chartier65db8802012-11-20 12:36:46 -08002093 uint64_t gc_start_size = GetBytesAllocated();
2094 // Approximate allocation rate in bytes / second.
Ian Rogers1d54e732013-05-02 21:10:01 -07002095 uint64_t ms_delta = NsToMs(gc_start_time_ns - last_gc_time_ns_);
Mathieu Chartier590fee92013-09-13 13:46:47 -07002096 // Back to back GCs can cause 0 ms of wait time in between GC invocations.
2097 if (LIKELY(ms_delta != 0)) {
Ian Rogers1d54e732013-05-02 21:10:01 -07002098 allocation_rate_ = ((gc_start_size - last_gc_size_) * 1000) / ms_delta;
Mathieu Chartier1b636c62014-08-13 10:08:05 -07002099 ATRACE_INT("Allocation rate KB/s", allocation_rate_ / KB);
Mathieu Chartier65db8802012-11-20 12:36:46 -08002100 VLOG(heap) << "Allocation rate: " << PrettySize(allocation_rate_) << "/s";
2101 }
2102
Ian Rogers1d54e732013-05-02 21:10:01 -07002103 DCHECK_LT(gc_type, collector::kGcTypeMax);
2104 DCHECK_NE(gc_type, collector::kGcTypeNone);
Anwar Ghuloum67f99412013-08-12 14:19:48 -07002105
Mathieu Chartier590fee92013-09-13 13:46:47 -07002106 collector::GarbageCollector* collector = nullptr;
Mathieu Chartier50482232013-11-21 11:48:14 -08002107 // TODO: Clean this up.
Mathieu Chartier1d27b342014-01-28 12:51:09 -08002108 if (compacting_gc) {
Mathieu Chartier692fafd2013-11-29 17:24:40 -08002109 DCHECK(current_allocator_ == kAllocatorTypeBumpPointer ||
2110 current_allocator_ == kAllocatorTypeTLAB);
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002111 switch (collector_type_) {
2112 case kCollectorTypeSS:
2113 // Fall-through.
2114 case kCollectorTypeGSS:
2115 semi_space_collector_->SetFromSpace(bump_pointer_space_);
2116 semi_space_collector_->SetToSpace(temp_space_);
2117 semi_space_collector_->SetSwapSemiSpaces(true);
2118 collector = semi_space_collector_;
2119 break;
2120 case kCollectorTypeCC:
2121 collector = concurrent_copying_collector_;
2122 break;
2123 case kCollectorTypeMC:
2124 mark_compact_collector_->SetSpace(bump_pointer_space_);
2125 collector = mark_compact_collector_;
2126 break;
2127 default:
2128 LOG(FATAL) << "Invalid collector type " << static_cast<size_t>(collector_type_);
Hiroshi Yamauchid5307ec2014-03-27 21:07:51 -07002129 }
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002130 if (collector != mark_compact_collector_) {
2131 temp_space_->GetMemMap()->Protect(PROT_READ | PROT_WRITE);
2132 CHECK(temp_space_->IsEmpty());
2133 }
2134 gc_type = collector::kGcTypeFull; // TODO: Not hard code this in.
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08002135 } else if (current_allocator_ == kAllocatorTypeRosAlloc ||
2136 current_allocator_ == kAllocatorTypeDlMalloc) {
Mathieu Chartierafe49982014-03-27 10:55:04 -07002137 collector = FindCollectorByGcType(gc_type);
Mathieu Chartier50482232013-11-21 11:48:14 -08002138 } else {
2139 LOG(FATAL) << "Invalid current allocator " << current_allocator_;
Mathieu Chartier590fee92013-09-13 13:46:47 -07002140 }
Mathieu Chartier7bf82af2013-12-06 16:51:45 -08002141 CHECK(collector != nullptr)
Hiroshi Yamauchi3e417802014-03-20 12:03:02 -07002142 << "Could not find garbage collector with collector_type="
2143 << static_cast<size_t>(collector_type_) << " and gc_type=" << gc_type;
Mathieu Chartier6f365cc2014-04-23 12:42:27 -07002144 collector->Run(gc_cause, clear_soft_references || runtime->IsZygote());
Mathieu Chartier10fb83a2014-06-15 15:15:43 -07002145 total_objects_freed_ever_ += GetCurrentGcIteration()->GetFreedObjects();
2146 total_bytes_freed_ever_ += GetCurrentGcIteration()->GetFreedBytes();
Mathieu Chartier7bf52d22014-03-13 14:46:09 -07002147 RequestHeapTrim();
Mathieu Chartier39e32612013-11-12 16:28:05 -08002148 // Enqueue cleared references.
Mathieu Chartier308351a2014-06-15 12:39:02 -07002149 reference_processor_.EnqueueClearedReferences(self);
Mathieu Chartier590fee92013-09-13 13:46:47 -07002150 // Grow the heap so that we know when to perform the next GC.
Mathieu Chartierafe49982014-03-27 10:55:04 -07002151 GrowForUtilization(collector);
Mathieu Chartier10fb83a2014-06-15 15:15:43 -07002152 const size_t duration = GetCurrentGcIteration()->GetDurationNs();
2153 const std::vector<uint64_t>& pause_times = GetCurrentGcIteration()->GetPauseTimes();
Mathieu Chartier62ab87b2014-04-28 12:22:07 -07002154 // Print the GC if it is an explicit GC (e.g. Runtime.gc()) or a slow GC
Mathieu Chartierf5997b42014-06-20 10:37:54 -07002155 // (mutator time blocked >= long_pause_log_threshold_).
Mathieu Chartier62ab87b2014-04-28 12:22:07 -07002156 bool log_gc = gc_cause == kGcCauseExplicit;
2157 if (!log_gc && CareAboutPauseTimes()) {
Mathieu Chartiere53225c2013-08-19 10:59:11 -07002158 // GC for alloc pauses the allocating thread, so consider it as a pause.
Mathieu Chartier62ab87b2014-04-28 12:22:07 -07002159 log_gc = duration > long_gc_log_threshold_ ||
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08002160 (gc_cause == kGcCauseForAlloc && duration > long_pause_log_threshold_);
Mathieu Chartier62ab87b2014-04-28 12:22:07 -07002161 for (uint64_t pause : pause_times) {
2162 log_gc = log_gc || pause >= long_pause_log_threshold_;
Mathieu Chartiere53225c2013-08-19 10:59:11 -07002163 }
Mathieu Chartier62ab87b2014-04-28 12:22:07 -07002164 }
2165 if (log_gc) {
2166 const size_t percent_free = GetPercentFree();
2167 const size_t current_heap_size = GetBytesAllocated();
2168 const size_t total_memory = GetTotalMemory();
2169 std::ostringstream pause_string;
2170 for (size_t i = 0; i < pause_times.size(); ++i) {
2171 pause_string << PrettyDuration((pause_times[i] / 1000) * 1000)
Mathieu Chartier6f365cc2014-04-23 12:42:27 -07002172 << ((i != pause_times.size() - 1) ? "," : "");
Mathieu Chartiere53225c2013-08-19 10:59:11 -07002173 }
Mathieu Chartier62ab87b2014-04-28 12:22:07 -07002174 LOG(INFO) << gc_cause << " " << collector->GetName()
Mathieu Chartier10fb83a2014-06-15 15:15:43 -07002175 << " GC freed " << current_gc_iteration_.GetFreedObjects() << "("
2176 << PrettySize(current_gc_iteration_.GetFreedBytes()) << ") AllocSpace objects, "
2177 << current_gc_iteration_.GetFreedLargeObjects() << "("
2178 << PrettySize(current_gc_iteration_.GetFreedLargeObjectBytes()) << ") LOS objects, "
Mathieu Chartier62ab87b2014-04-28 12:22:07 -07002179 << percent_free << "% free, " << PrettySize(current_heap_size) << "/"
2180 << PrettySize(total_memory) << ", " << "paused " << pause_string.str()
2181 << " total " << PrettyDuration((duration / 1000) * 1000);
Ian Rogersc7dd2952014-10-21 23:31:19 -07002182 VLOG(heap) << Dumpable<TimingLogger>(*current_gc_iteration_.GetTimings());
Mathieu Chartier2b82db42012-11-14 17:29:05 -08002183 }
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08002184 FinishGC(self, gc_type);
Anwar Ghuloum4446ab92013-08-09 21:17:25 -07002185 // Inform DDMS that a GC completed.
Ian Rogers15bf2d32012-08-28 17:33:04 -07002186 Dbg::GcDidFinish();
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07002187 return gc_type;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002188}
Mathieu Chartiera6399032012-06-11 18:49:50 -07002189
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08002190void Heap::FinishGC(Thread* self, collector::GcType gc_type) {
2191 MutexLock mu(self, *gc_complete_lock_);
Mathieu Chartierd5a89ee2014-01-31 09:55:13 -08002192 collector_type_running_ = kCollectorTypeNone;
2193 if (gc_type != collector::kGcTypeNone) {
2194 last_gc_type_ = gc_type;
2195 }
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08002196 // Wake anyone who may have been waiting for the GC to complete.
2197 gc_complete_cond_->Broadcast(self);
2198}
2199
Mathieu Chartier815873e2014-02-13 18:02:13 -08002200static void RootMatchesObjectVisitor(mirror::Object** root, void* arg, uint32_t /*thread_id*/,
2201 RootType /*root_type*/) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002202 mirror::Object* obj = reinterpret_cast<mirror::Object*>(arg);
Mathieu Chartier815873e2014-02-13 18:02:13 -08002203 if (*root == obj) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07002204 LOG(INFO) << "Object " << obj << " is a root";
2205 }
2206}
2207
2208class ScanVisitor {
2209 public:
Brian Carlstromdf629502013-07-17 22:39:56 -07002210 void operator()(const mirror::Object* obj) const {
Mathieu Chartier0f72e412013-09-06 16:40:01 -07002211 LOG(ERROR) << "Would have rescanned object " << obj;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07002212 }
2213};
2214
Ian Rogers1d54e732013-05-02 21:10:01 -07002215// Verify a reference from an object.
Mathieu Chartierfd678be2012-08-30 14:50:54 -07002216class VerifyReferenceVisitor {
2217 public:
Mathieu Chartier8ab7e782014-05-19 16:55:27 -07002218 explicit VerifyReferenceVisitor(Heap* heap, Atomic<size_t>* fail_count, bool verify_referent)
Ian Rogers1d54e732013-05-02 21:10:01 -07002219 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_)
Mathieu Chartier8ab7e782014-05-19 16:55:27 -07002220 : heap_(heap), fail_count_(fail_count), verify_referent_(verify_referent) {}
Ian Rogers1d54e732013-05-02 21:10:01 -07002221
Mathieu Chartier8ab7e782014-05-19 16:55:27 -07002222 size_t GetFailureCount() const {
Mathieu Chartiere9e55ac2014-05-21 17:48:25 -07002223 return fail_count_->LoadSequentiallyConsistent();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07002224 }
2225
Mathieu Chartier407f7022014-02-18 14:37:05 -08002226 void operator()(mirror::Class* klass, mirror::Reference* ref) const
2227 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier78f7b4c2014-05-06 10:57:27 -07002228 if (verify_referent_) {
Mathieu Chartier8ab7e782014-05-19 16:55:27 -07002229 VerifyReference(ref, ref->GetReferent(), mirror::Reference::ReferentOffset());
Mathieu Chartier78f7b4c2014-05-06 10:57:27 -07002230 }
Mathieu Chartier407f7022014-02-18 14:37:05 -08002231 }
2232
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -07002233 void operator()(mirror::Object* obj, MemberOffset offset, bool /*is_static*/) const
Mathieu Chartier407f7022014-02-18 14:37:05 -08002234 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier8ab7e782014-05-19 16:55:27 -07002235 VerifyReference(obj, obj->GetFieldObject<mirror::Object>(offset), offset);
Mathieu Chartier407f7022014-02-18 14:37:05 -08002236 }
2237
Mathieu Chartier8ab7e782014-05-19 16:55:27 -07002238 bool IsLive(mirror::Object* obj) const NO_THREAD_SAFETY_ANALYSIS {
2239 return heap_->IsLiveObjectLocked(obj, true, false, true);
2240 }
2241
2242 static void VerifyRootCallback(mirror::Object** root, void* arg, uint32_t thread_id,
2243 RootType root_type) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
2244 VerifyReferenceVisitor* visitor = reinterpret_cast<VerifyReferenceVisitor*>(arg);
2245 if (!visitor->VerifyReference(nullptr, *root, MemberOffset(0))) {
2246 LOG(ERROR) << "Root " << *root << " is dead with type " << PrettyTypeOf(*root)
2247 << " thread_id= " << thread_id << " root_type= " << root_type;
2248 }
2249 }
2250
2251 private:
Mathieu Chartier407f7022014-02-18 14:37:05 -08002252 // TODO: Fix the no thread safety analysis.
Mathieu Chartier8ab7e782014-05-19 16:55:27 -07002253 // Returns false on failure.
2254 bool VerifyReference(mirror::Object* obj, mirror::Object* ref, MemberOffset offset) const
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002255 NO_THREAD_SAFETY_ANALYSIS {
Mathieu Chartier938a03b2014-01-16 15:10:31 -08002256 if (ref == nullptr || IsLive(ref)) {
2257 // Verify that the reference is live.
Mathieu Chartier8ab7e782014-05-19 16:55:27 -07002258 return true;
Mathieu Chartier938a03b2014-01-16 15:10:31 -08002259 }
Mathieu Chartiere9e55ac2014-05-21 17:48:25 -07002260 if (fail_count_->FetchAndAddSequentiallyConsistent(1) == 0) {
Mathieu Chartier938a03b2014-01-16 15:10:31 -08002261 // Print message on only on first failure to prevent spam.
2262 LOG(ERROR) << "!!!!!!!!!!!!!!Heap corruption detected!!!!!!!!!!!!!!!!!!!";
Mathieu Chartier938a03b2014-01-16 15:10:31 -08002263 }
2264 if (obj != nullptr) {
Mathieu Chartier8ab7e782014-05-19 16:55:27 -07002265 // Only do this part for non roots.
Ian Rogers1d54e732013-05-02 21:10:01 -07002266 accounting::CardTable* card_table = heap_->GetCardTable();
2267 accounting::ObjectStack* alloc_stack = heap_->allocation_stack_.get();
2268 accounting::ObjectStack* live_stack = heap_->live_stack_.get();
Ian Rogers13735952014-10-08 12:43:28 -07002269 uint8_t* card_addr = card_table->CardFromAddr(obj);
Mathieu Chartier938a03b2014-01-16 15:10:31 -08002270 LOG(ERROR) << "Object " << obj << " references dead object " << ref << " at offset "
2271 << offset << "\n card value = " << static_cast<int>(*card_addr);
2272 if (heap_->IsValidObjectAddress(obj->GetClass())) {
2273 LOG(ERROR) << "Obj type " << PrettyTypeOf(obj);
2274 } else {
2275 LOG(ERROR) << "Object " << obj << " class(" << obj->GetClass() << ") not a heap address";
Mathieu Chartier0f72e412013-09-06 16:40:01 -07002276 }
Mathieu Chartier938a03b2014-01-16 15:10:31 -08002277
Mathieu Chartierb363f662014-07-16 13:28:58 -07002278 // Attempt to find the class inside of the recently freed objects.
Mathieu Chartier938a03b2014-01-16 15:10:31 -08002279 space::ContinuousSpace* ref_space = heap_->FindContinuousSpaceFromObject(ref, true);
2280 if (ref_space != nullptr && ref_space->IsMallocSpace()) {
2281 space::MallocSpace* space = ref_space->AsMallocSpace();
2282 mirror::Class* ref_class = space->FindRecentFreedObject(ref);
2283 if (ref_class != nullptr) {
2284 LOG(ERROR) << "Reference " << ref << " found as a recently freed object with class "
2285 << PrettyClass(ref_class);
Mathieu Chartier0f72e412013-09-06 16:40:01 -07002286 } else {
Mathieu Chartier938a03b2014-01-16 15:10:31 -08002287 LOG(ERROR) << "Reference " << ref << " not found as a recently freed object";
Mathieu Chartier0f72e412013-09-06 16:40:01 -07002288 }
Mathieu Chartier938a03b2014-01-16 15:10:31 -08002289 }
Mathieu Chartier0f72e412013-09-06 16:40:01 -07002290
Mathieu Chartier938a03b2014-01-16 15:10:31 -08002291 if (ref->GetClass() != nullptr && heap_->IsValidObjectAddress(ref->GetClass()) &&
2292 ref->GetClass()->IsClass()) {
2293 LOG(ERROR) << "Ref type " << PrettyTypeOf(ref);
2294 } else {
2295 LOG(ERROR) << "Ref " << ref << " class(" << ref->GetClass()
2296 << ") is not a valid heap address";
2297 }
2298
Ian Rogers13735952014-10-08 12:43:28 -07002299 card_table->CheckAddrIsInCardTable(reinterpret_cast<const uint8_t*>(obj));
Mathieu Chartier938a03b2014-01-16 15:10:31 -08002300 void* cover_begin = card_table->AddrFromCard(card_addr);
2301 void* cover_end = reinterpret_cast<void*>(reinterpret_cast<size_t>(cover_begin) +
2302 accounting::CardTable::kCardSize);
2303 LOG(ERROR) << "Card " << reinterpret_cast<void*>(card_addr) << " covers " << cover_begin
2304 << "-" << cover_end;
Mathieu Chartiera8e8f9c2014-04-09 14:51:05 -07002305 accounting::ContinuousSpaceBitmap* bitmap =
2306 heap_->GetLiveBitmap()->GetContinuousSpaceBitmap(obj);
Mathieu Chartier938a03b2014-01-16 15:10:31 -08002307
2308 if (bitmap == nullptr) {
2309 LOG(ERROR) << "Object " << obj << " has no bitmap";
Mathieu Chartier4e305412014-02-19 10:54:44 -08002310 if (!VerifyClassClass(obj->GetClass())) {
Mathieu Chartier938a03b2014-01-16 15:10:31 -08002311 LOG(ERROR) << "Object " << obj << " failed class verification!";
Mathieu Chartier0f72e412013-09-06 16:40:01 -07002312 }
Mathieu Chartier938a03b2014-01-16 15:10:31 -08002313 } else {
Ian Rogers1d54e732013-05-02 21:10:01 -07002314 // Print out how the object is live.
Mathieu Chartier938a03b2014-01-16 15:10:31 -08002315 if (bitmap->Test(obj)) {
Ian Rogers1d54e732013-05-02 21:10:01 -07002316 LOG(ERROR) << "Object " << obj << " found in live bitmap";
2317 }
Mathieu Chartier0f72e412013-09-06 16:40:01 -07002318 if (alloc_stack->Contains(const_cast<mirror::Object*>(obj))) {
Ian Rogers1d54e732013-05-02 21:10:01 -07002319 LOG(ERROR) << "Object " << obj << " found in allocation stack";
2320 }
Mathieu Chartier0f72e412013-09-06 16:40:01 -07002321 if (live_stack->Contains(const_cast<mirror::Object*>(obj))) {
Ian Rogers1d54e732013-05-02 21:10:01 -07002322 LOG(ERROR) << "Object " << obj << " found in live stack";
2323 }
Mathieu Chartier0f72e412013-09-06 16:40:01 -07002324 if (alloc_stack->Contains(const_cast<mirror::Object*>(ref))) {
2325 LOG(ERROR) << "Ref " << ref << " found in allocation stack";
2326 }
2327 if (live_stack->Contains(const_cast<mirror::Object*>(ref))) {
2328 LOG(ERROR) << "Ref " << ref << " found in live stack";
2329 }
Ian Rogers1d54e732013-05-02 21:10:01 -07002330 // Attempt to see if the card table missed the reference.
2331 ScanVisitor scan_visitor;
Ian Rogers13735952014-10-08 12:43:28 -07002332 uint8_t* byte_cover_begin = reinterpret_cast<uint8_t*>(card_table->AddrFromCard(card_addr));
Ian Rogers1d54e732013-05-02 21:10:01 -07002333 card_table->Scan(bitmap, byte_cover_begin,
Mathieu Chartier184e3222013-08-03 14:02:57 -07002334 byte_cover_begin + accounting::CardTable::kCardSize, scan_visitor);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07002335 }
Mathieu Chartier938a03b2014-01-16 15:10:31 -08002336
2337 // Search to see if any of the roots reference our object.
2338 void* arg = const_cast<void*>(reinterpret_cast<const void*>(obj));
Mathieu Chartier893263b2014-03-04 11:07:42 -08002339 Runtime::Current()->VisitRoots(&RootMatchesObjectVisitor, arg);
Mathieu Chartier938a03b2014-01-16 15:10:31 -08002340
2341 // Search to see if any of the roots reference our reference.
2342 arg = const_cast<void*>(reinterpret_cast<const void*>(ref));
Mathieu Chartier893263b2014-03-04 11:07:42 -08002343 Runtime::Current()->VisitRoots(&RootMatchesObjectVisitor, arg);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07002344 }
Mathieu Chartier8ab7e782014-05-19 16:55:27 -07002345 return false;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07002346 }
2347
Ian Rogers1d54e732013-05-02 21:10:01 -07002348 Heap* const heap_;
Mathieu Chartier8ab7e782014-05-19 16:55:27 -07002349 Atomic<size_t>* const fail_count_;
2350 const bool verify_referent_;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07002351};
2352
Ian Rogers1d54e732013-05-02 21:10:01 -07002353// Verify all references within an object, for use with HeapBitmap::Visit.
Mathieu Chartierfd678be2012-08-30 14:50:54 -07002354class VerifyObjectVisitor {
2355 public:
Mathieu Chartier8ab7e782014-05-19 16:55:27 -07002356 explicit VerifyObjectVisitor(Heap* heap, Atomic<size_t>* fail_count, bool verify_referent)
2357 : heap_(heap), fail_count_(fail_count), verify_referent_(verify_referent) {
Mathieu Chartier78f7b4c2014-05-06 10:57:27 -07002358 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -07002359
Mathieu Chartier590fee92013-09-13 13:46:47 -07002360 void operator()(mirror::Object* obj) const
Ian Rogersb726dcb2012-09-05 08:57:23 -07002361 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Ian Rogers1d54e732013-05-02 21:10:01 -07002362 // Note: we are verifying the references in obj but not obj itself, this is because obj must
2363 // be live or else how did we find it in the live bitmap?
Mathieu Chartier8ab7e782014-05-19 16:55:27 -07002364 VerifyReferenceVisitor visitor(heap_, fail_count_, verify_referent_);
Mathieu Chartier0f72e412013-09-06 16:40:01 -07002365 // The class doesn't count as a reference but we should verify it anyways.
Mathieu Chartier407f7022014-02-18 14:37:05 -08002366 obj->VisitReferences<true>(visitor, visitor);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07002367 }
2368
Mathieu Chartier590fee92013-09-13 13:46:47 -07002369 static void VisitCallback(mirror::Object* obj, void* arg)
2370 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
2371 VerifyObjectVisitor* visitor = reinterpret_cast<VerifyObjectVisitor*>(arg);
2372 visitor->operator()(obj);
2373 }
2374
Mathieu Chartier8ab7e782014-05-19 16:55:27 -07002375 size_t GetFailureCount() const {
Mathieu Chartiere9e55ac2014-05-21 17:48:25 -07002376 return fail_count_->LoadSequentiallyConsistent();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07002377 }
2378
2379 private:
Ian Rogers1d54e732013-05-02 21:10:01 -07002380 Heap* const heap_;
Mathieu Chartier8ab7e782014-05-19 16:55:27 -07002381 Atomic<size_t>* const fail_count_;
Mathieu Chartier78f7b4c2014-05-06 10:57:27 -07002382 const bool verify_referent_;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07002383};
2384
Mathieu Chartierc1790162014-05-23 10:54:50 -07002385void Heap::PushOnAllocationStackWithInternalGC(Thread* self, mirror::Object** obj) {
2386 // Slow path, the allocation stack push back must have already failed.
2387 DCHECK(!allocation_stack_->AtomicPushBack(*obj));
2388 do {
2389 // TODO: Add handle VerifyObject.
2390 StackHandleScope<1> hs(self);
2391 HandleWrapper<mirror::Object> wrapper(hs.NewHandleWrapper(obj));
2392 // Push our object into the reserve region of the allocaiton stack. This is only required due
2393 // to heap verification requiring that roots are live (either in the live bitmap or in the
2394 // allocation stack).
2395 CHECK(allocation_stack_->AtomicPushBackIgnoreGrowthLimit(*obj));
2396 CollectGarbageInternal(collector::kGcTypeSticky, kGcCauseForAlloc, false);
2397 } while (!allocation_stack_->AtomicPushBack(*obj));
2398}
2399
2400void Heap::PushOnThreadLocalAllocationStackWithInternalGC(Thread* self, mirror::Object** obj) {
2401 // Slow path, the allocation stack push back must have already failed.
2402 DCHECK(!self->PushOnThreadLocalAllocationStack(*obj));
2403 mirror::Object** start_address;
2404 mirror::Object** end_address;
2405 while (!allocation_stack_->AtomicBumpBack(kThreadLocalAllocationStackSize, &start_address,
2406 &end_address)) {
2407 // TODO: Add handle VerifyObject.
2408 StackHandleScope<1> hs(self);
2409 HandleWrapper<mirror::Object> wrapper(hs.NewHandleWrapper(obj));
2410 // Push our object into the reserve region of the allocaiton stack. This is only required due
2411 // to heap verification requiring that roots are live (either in the live bitmap or in the
2412 // allocation stack).
2413 CHECK(allocation_stack_->AtomicPushBackIgnoreGrowthLimit(*obj));
2414 // Push into the reserve allocation stack.
2415 CollectGarbageInternal(collector::kGcTypeSticky, kGcCauseForAlloc, false);
2416 }
2417 self->SetThreadLocalAllocationStack(start_address, end_address);
2418 // Retry on the new thread-local allocation stack.
2419 CHECK(self->PushOnThreadLocalAllocationStack(*obj)); // Must succeed.
2420}
2421
Mathieu Chartierfd678be2012-08-30 14:50:54 -07002422// Must do this with mutators suspended since we are directly accessing the allocation stacks.
Mathieu Chartier8ab7e782014-05-19 16:55:27 -07002423size_t Heap::VerifyHeapReferences(bool verify_referents) {
Hiroshi Yamauchi1ed90612014-02-14 15:00:51 -08002424 Thread* self = Thread::Current();
2425 Locks::mutator_lock_->AssertExclusiveHeld(self);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07002426 // Lets sort our allocation stacks so that we can efficiently binary search them.
Ian Rogers1d54e732013-05-02 21:10:01 -07002427 allocation_stack_->Sort();
2428 live_stack_->Sort();
Hiroshi Yamauchi1ed90612014-02-14 15:00:51 -08002429 // Since we sorted the allocation stack content, need to revoke all
2430 // thread-local allocation stacks.
2431 RevokeAllThreadLocalAllocationStacks(self);
Mathieu Chartier8ab7e782014-05-19 16:55:27 -07002432 Atomic<size_t> fail_count_(0);
2433 VerifyObjectVisitor visitor(this, &fail_count_, verify_referents);
Mathieu Chartier0f72e412013-09-06 16:40:01 -07002434 // Verify objects in the allocation stack since these will be objects which were:
2435 // 1. Allocated prior to the GC (pre GC verification).
2436 // 2. Allocated during the GC (pre sweep GC verification).
Mathieu Chartier0f72e412013-09-06 16:40:01 -07002437 // We don't want to verify the objects in the live stack since they themselves may be
Mathieu Chartierfd678be2012-08-30 14:50:54 -07002438 // pointing to dead objects if they are not reachable.
Mathieu Chartier590fee92013-09-13 13:46:47 -07002439 VisitObjects(VerifyObjectVisitor::VisitCallback, &visitor);
2440 // Verify the roots:
Mathieu Chartier8ab7e782014-05-19 16:55:27 -07002441 Runtime::Current()->VisitRoots(VerifyReferenceVisitor::VerifyRootCallback, &visitor);
2442 if (visitor.GetFailureCount() > 0) {
Mathieu Chartier0f72e412013-09-06 16:40:01 -07002443 // Dump mod-union tables.
Mathieu Chartier11409ae2013-09-23 11:49:36 -07002444 for (const auto& table_pair : mod_union_tables_) {
2445 accounting::ModUnionTable* mod_union_table = table_pair.second;
2446 mod_union_table->Dump(LOG(ERROR) << mod_union_table->GetName() << ": ");
2447 }
Hiroshi Yamauchi38e68e92014-03-07 13:59:08 -08002448 // Dump remembered sets.
2449 for (const auto& table_pair : remembered_sets_) {
2450 accounting::RememberedSet* remembered_set = table_pair.second;
2451 remembered_set->Dump(LOG(ERROR) << remembered_set->GetName() << ": ");
2452 }
Mathieu Chartier4c13a3f2014-07-14 14:57:16 -07002453 DumpSpaces(LOG(ERROR));
Mathieu Chartierfd678be2012-08-30 14:50:54 -07002454 }
Mathieu Chartier8ab7e782014-05-19 16:55:27 -07002455 return visitor.GetFailureCount();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07002456}
2457
2458class VerifyReferenceCardVisitor {
2459 public:
2460 VerifyReferenceCardVisitor(Heap* heap, bool* failed)
2461 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_,
2462 Locks::heap_bitmap_lock_)
Ian Rogers1d54e732013-05-02 21:10:01 -07002463 : heap_(heap), failed_(failed) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07002464 }
2465
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08002466 // TODO: Fix lock analysis to not use NO_THREAD_SAFETY_ANALYSIS, requires support for
2467 // annotalysis on visitors.
Mathieu Chartier407f7022014-02-18 14:37:05 -08002468 void operator()(mirror::Object* obj, MemberOffset offset, bool is_static) const
2469 NO_THREAD_SAFETY_ANALYSIS {
Ian Rogersb0fa5dc2014-04-28 16:47:08 -07002470 mirror::Object* ref = obj->GetFieldObject<mirror::Object>(offset);
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08002471 // Filter out class references since changing an object's class does not mark the card as dirty.
2472 // Also handles large objects, since the only reference they hold is a class reference.
Mathieu Chartier407f7022014-02-18 14:37:05 -08002473 if (ref != nullptr && !ref->IsClass()) {
Ian Rogers1d54e732013-05-02 21:10:01 -07002474 accounting::CardTable* card_table = heap_->GetCardTable();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07002475 // If the object is not dirty and it is referencing something in the live stack other than
2476 // class, then it must be on a dirty card.
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07002477 if (!card_table->AddrIsInCardTable(obj)) {
2478 LOG(ERROR) << "Object " << obj << " is not in the address range of the card table";
2479 *failed_ = true;
Mathieu Chartier2b82db42012-11-14 17:29:05 -08002480 } else if (!card_table->IsDirty(obj)) {
Mathieu Chartier938a03b2014-01-16 15:10:31 -08002481 // TODO: Check mod-union tables.
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08002482 // Card should be either kCardDirty if it got re-dirtied after we aged it, or
2483 // kCardDirty - 1 if it didnt get touched since we aged it.
Ian Rogers1d54e732013-05-02 21:10:01 -07002484 accounting::ObjectStack* live_stack = heap_->live_stack_.get();
Mathieu Chartier407f7022014-02-18 14:37:05 -08002485 if (live_stack->ContainsSorted(ref)) {
2486 if (live_stack->ContainsSorted(obj)) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07002487 LOG(ERROR) << "Object " << obj << " found in live stack";
2488 }
2489 if (heap_->GetLiveBitmap()->Test(obj)) {
2490 LOG(ERROR) << "Object " << obj << " found in live bitmap";
2491 }
2492 LOG(ERROR) << "Object " << obj << " " << PrettyTypeOf(obj)
2493 << " references " << ref << " " << PrettyTypeOf(ref) << " in live stack";
2494
2495 // Print which field of the object is dead.
2496 if (!obj->IsObjectArray()) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08002497 mirror::Class* klass = is_static ? obj->AsClass() : obj->GetClass();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07002498 CHECK(klass != NULL);
Ian Rogersef7d42f2014-01-06 12:55:46 -08002499 mirror::ObjectArray<mirror::ArtField>* fields = is_static ? klass->GetSFields()
2500 : klass->GetIFields();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07002501 CHECK(fields != NULL);
2502 for (int32_t i = 0; i < fields->GetLength(); ++i) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08002503 mirror::ArtField* cur = fields->Get(i);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07002504 if (cur->GetOffset().Int32Value() == offset.Int32Value()) {
2505 LOG(ERROR) << (is_static ? "Static " : "") << "field in the live stack is "
2506 << PrettyField(cur);
2507 break;
2508 }
2509 }
2510 } else {
Ian Rogersef7d42f2014-01-06 12:55:46 -08002511 mirror::ObjectArray<mirror::Object>* object_array =
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002512 obj->AsObjectArray<mirror::Object>();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07002513 for (int32_t i = 0; i < object_array->GetLength(); ++i) {
2514 if (object_array->Get(i) == ref) {
2515 LOG(ERROR) << (is_static ? "Static " : "") << "obj[" << i << "] = ref";
2516 }
2517 }
2518 }
2519
2520 *failed_ = true;
2521 }
2522 }
2523 }
2524 }
2525
2526 private:
Ian Rogers1d54e732013-05-02 21:10:01 -07002527 Heap* const heap_;
2528 bool* const failed_;
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07002529};
2530
2531class VerifyLiveStackReferences {
2532 public:
Brian Carlstrom93ba8932013-07-17 21:31:49 -07002533 explicit VerifyLiveStackReferences(Heap* heap)
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07002534 : heap_(heap),
Brian Carlstrom93ba8932013-07-17 21:31:49 -07002535 failed_(false) {}
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07002536
Mathieu Chartier11409ae2013-09-23 11:49:36 -07002537 void operator()(mirror::Object* obj) const
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07002538 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
2539 VerifyReferenceCardVisitor visitor(heap_, const_cast<bool*>(&failed_));
Ian Rogersb0fa5dc2014-04-28 16:47:08 -07002540 obj->VisitReferences<true>(visitor, VoidFunctor());
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07002541 }
2542
2543 bool Failed() const {
2544 return failed_;
2545 }
2546
2547 private:
Ian Rogers1d54e732013-05-02 21:10:01 -07002548 Heap* const heap_;
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07002549 bool failed_;
2550};
2551
2552bool Heap::VerifyMissingCardMarks() {
Hiroshi Yamauchi1ed90612014-02-14 15:00:51 -08002553 Thread* self = Thread::Current();
2554 Locks::mutator_lock_->AssertExclusiveHeld(self);
Mathieu Chartier2b82db42012-11-14 17:29:05 -08002555 // We need to sort the live stack since we binary search it.
Ian Rogers1d54e732013-05-02 21:10:01 -07002556 live_stack_->Sort();
Hiroshi Yamauchi1ed90612014-02-14 15:00:51 -08002557 // Since we sorted the allocation stack content, need to revoke all
2558 // thread-local allocation stacks.
2559 RevokeAllThreadLocalAllocationStacks(self);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07002560 VerifyLiveStackReferences visitor(this);
2561 GetLiveBitmap()->Visit(visitor);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07002562 // We can verify objects in the live stack since none of these should reference dead objects.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002563 for (mirror::Object** it = live_stack_->Begin(); it != live_stack_->End(); ++it) {
Hiroshi Yamauchif5b0e202014-02-11 17:02:22 -08002564 if (!kUseThreadLocalAllocationStack || *it != nullptr) {
2565 visitor(*it);
2566 }
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07002567 }
Mathieu Chartier4c13a3f2014-07-14 14:57:16 -07002568 return !visitor.Failed();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07002569}
2570
Hiroshi Yamauchif5b0e202014-02-11 17:02:22 -08002571void Heap::SwapStacks(Thread* self) {
2572 if (kUseThreadLocalAllocationStack) {
2573 live_stack_->AssertAllZero();
2574 }
Mathieu Chartierd22d5482012-11-06 17:14:12 -08002575 allocation_stack_.swap(live_stack_);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07002576}
2577
Hiroshi Yamauchif5b0e202014-02-11 17:02:22 -08002578void Heap::RevokeAllThreadLocalAllocationStacks(Thread* self) {
Hiroshi Yamauchif5b0e202014-02-11 17:02:22 -08002579 // This must be called only during the pause.
2580 CHECK(Locks::mutator_lock_->IsExclusiveHeld(self));
2581 MutexLock mu(self, *Locks::runtime_shutdown_lock_);
2582 MutexLock mu2(self, *Locks::thread_list_lock_);
2583 std::list<Thread*> thread_list = Runtime::Current()->GetThreadList()->GetList();
2584 for (Thread* t : thread_list) {
2585 t->RevokeThreadLocalAllocationStack();
2586 }
2587}
2588
Ian Rogers68d8b422014-07-17 11:09:10 -07002589void Heap::AssertThreadLocalBuffersAreRevoked(Thread* thread) {
2590 if (kIsDebugBuild) {
2591 if (rosalloc_space_ != nullptr) {
2592 rosalloc_space_->AssertThreadLocalBuffersAreRevoked(thread);
2593 }
2594 if (bump_pointer_space_ != nullptr) {
2595 bump_pointer_space_->AssertThreadLocalBuffersAreRevoked(thread);
2596 }
2597 }
2598}
2599
Hiroshi Yamauchic93c5302014-03-20 16:15:37 -07002600void Heap::AssertAllBumpPointerSpaceThreadLocalBuffersAreRevoked() {
2601 if (kIsDebugBuild) {
2602 if (bump_pointer_space_ != nullptr) {
2603 bump_pointer_space_->AssertAllThreadLocalBuffersAreRevoked();
2604 }
2605 }
2606}
2607
Mathieu Chartier11409ae2013-09-23 11:49:36 -07002608accounting::ModUnionTable* Heap::FindModUnionTableFromSpace(space::Space* space) {
2609 auto it = mod_union_tables_.find(space);
2610 if (it == mod_union_tables_.end()) {
2611 return nullptr;
2612 }
2613 return it->second;
2614}
2615
Hiroshi Yamauchi38e68e92014-03-07 13:59:08 -08002616accounting::RememberedSet* Heap::FindRememberedSetFromSpace(space::Space* space) {
2617 auto it = remembered_sets_.find(space);
2618 if (it == remembered_sets_.end()) {
2619 return nullptr;
2620 }
2621 return it->second;
2622}
2623
Mathieu Chartier10fb83a2014-06-15 15:15:43 -07002624void Heap::ProcessCards(TimingLogger* timings, bool use_rem_sets) {
Mathieu Chartierf5997b42014-06-20 10:37:54 -07002625 TimingLogger::ScopedTiming t(__FUNCTION__, timings);
Ian Rogers1d54e732013-05-02 21:10:01 -07002626 // Clear cards and keep track of cards cleared in the mod-union table.
Mathieu Chartier02e25112013-08-14 16:14:24 -07002627 for (const auto& space : continuous_spaces_) {
Mathieu Chartier11409ae2013-09-23 11:49:36 -07002628 accounting::ModUnionTable* table = FindModUnionTableFromSpace(space);
Hiroshi Yamauchi38e68e92014-03-07 13:59:08 -08002629 accounting::RememberedSet* rem_set = FindRememberedSetFromSpace(space);
Mathieu Chartier11409ae2013-09-23 11:49:36 -07002630 if (table != nullptr) {
2631 const char* name = space->IsZygoteSpace() ? "ZygoteModUnionClearCards" :
2632 "ImageModUnionClearCards";
Mathieu Chartierf5997b42014-06-20 10:37:54 -07002633 TimingLogger::ScopedTiming t(name, timings);
Mathieu Chartier11409ae2013-09-23 11:49:36 -07002634 table->ClearCards();
Hiroshi Yamauchi38e68e92014-03-07 13:59:08 -08002635 } else if (use_rem_sets && rem_set != nullptr) {
2636 DCHECK(collector::SemiSpace::kUseRememberedSet && collector_type_ == kCollectorTypeGSS)
2637 << static_cast<int>(collector_type_);
Mathieu Chartierf5997b42014-06-20 10:37:54 -07002638 TimingLogger::ScopedTiming t("AllocSpaceRemSetClearCards", timings);
Hiroshi Yamauchi38e68e92014-03-07 13:59:08 -08002639 rem_set->ClearCards();
Mathieu Chartier590fee92013-09-13 13:46:47 -07002640 } else if (space->GetType() != space::kSpaceTypeBumpPointerSpace) {
Mathieu Chartierf5997b42014-06-20 10:37:54 -07002641 TimingLogger::ScopedTiming t("AllocSpaceClearCards", timings);
Mathieu Chartierd22d5482012-11-06 17:14:12 -08002642 // No mod union table for the AllocSpace. Age the cards so that the GC knows that these cards
2643 // were dirty before the GC started.
Mathieu Chartierbd0a6532014-02-27 11:14:21 -08002644 // TODO: Need to use atomic for the case where aged(cleaning thread) -> dirty(other thread)
2645 // -> clean(cleaning thread).
Mathieu Chartier590fee92013-09-13 13:46:47 -07002646 // The races are we either end up with: Aged card, unaged card. Since we have the checkpoint
Mathieu Chartier938a03b2014-01-16 15:10:31 -08002647 // roots and then we scan / update mod union tables after. We will always scan either card.
Mathieu Chartier590fee92013-09-13 13:46:47 -07002648 // If we end up with the non aged card, we scan it it in the pause.
Mathieu Chartier10fb83a2014-06-15 15:15:43 -07002649 card_table_->ModifyCardsAtomic(space->Begin(), space->End(), AgeCardVisitor(),
2650 VoidFunctor());
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07002651 }
2652 }
2653}
2654
Mathieu Chartier407f7022014-02-18 14:37:05 -08002655static void IdentityMarkHeapReferenceCallback(mirror::HeapReference<mirror::Object>*, void*) {
Mathieu Chartier11409ae2013-09-23 11:49:36 -07002656}
2657
Mathieu Chartier6f365cc2014-04-23 12:42:27 -07002658void Heap::PreGcVerificationPaused(collector::GarbageCollector* gc) {
2659 Thread* const self = Thread::Current();
Mathieu Chartier10fb83a2014-06-15 15:15:43 -07002660 TimingLogger* const timings = current_gc_iteration_.GetTimings();
Mathieu Chartierf5997b42014-06-20 10:37:54 -07002661 TimingLogger::ScopedTiming t(__FUNCTION__, timings);
Mathieu Chartier2b82db42012-11-14 17:29:05 -08002662 if (verify_pre_gc_heap_) {
Mathieu Chartierf5997b42014-06-20 10:37:54 -07002663 TimingLogger::ScopedTiming t("(Paused)PreGcVerifyHeapReferences", timings);
Mathieu Chartier6f365cc2014-04-23 12:42:27 -07002664 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier8ab7e782014-05-19 16:55:27 -07002665 size_t failures = VerifyHeapReferences();
2666 if (failures > 0) {
2667 LOG(FATAL) << "Pre " << gc->GetName() << " heap verification failed with " << failures
2668 << " failures";
Mathieu Chartier2b82db42012-11-14 17:29:05 -08002669 }
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08002670 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -08002671 // Check that all objects which reference things in the live stack are on dirty cards.
2672 if (verify_missing_card_marks_) {
Mathieu Chartierf5997b42014-06-20 10:37:54 -07002673 TimingLogger::ScopedTiming t("(Paused)PreGcVerifyMissingCardMarks", timings);
Mathieu Chartier6f365cc2014-04-23 12:42:27 -07002674 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
2675 SwapStacks(self);
2676 // Sort the live stack so that we can quickly binary search it later.
Mathieu Chartier4c13a3f2014-07-14 14:57:16 -07002677 CHECK(VerifyMissingCardMarks()) << "Pre " << gc->GetName()
2678 << " missing card mark verification failed\n" << DumpSpaces();
Mathieu Chartier6f365cc2014-04-23 12:42:27 -07002679 SwapStacks(self);
Mathieu Chartier2b82db42012-11-14 17:29:05 -08002680 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -08002681 if (verify_mod_union_table_) {
Mathieu Chartierf5997b42014-06-20 10:37:54 -07002682 TimingLogger::ScopedTiming t("(Paused)PreGcVerifyModUnionTables", timings);
Mathieu Chartier2b82db42012-11-14 17:29:05 -08002683 ReaderMutexLock reader_lock(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier11409ae2013-09-23 11:49:36 -07002684 for (const auto& table_pair : mod_union_tables_) {
2685 accounting::ModUnionTable* mod_union_table = table_pair.second;
Mathieu Chartier407f7022014-02-18 14:37:05 -08002686 mod_union_table->UpdateAndMarkReferences(IdentityMarkHeapReferenceCallback, nullptr);
Mathieu Chartier11409ae2013-09-23 11:49:36 -07002687 mod_union_table->Verify();
2688 }
Mathieu Chartier6f365cc2014-04-23 12:42:27 -07002689 }
2690}
2691
2692void Heap::PreGcVerification(collector::GarbageCollector* gc) {
Mathieu Chartier0651d412014-04-29 14:37:57 -07002693 if (verify_pre_gc_heap_ || verify_missing_card_marks_ || verify_mod_union_table_) {
Mathieu Chartier6f365cc2014-04-23 12:42:27 -07002694 collector::GarbageCollector::ScopedPause pause(gc);
2695 PreGcVerificationPaused(gc);
2696 }
2697}
2698
2699void Heap::PrePauseRosAllocVerification(collector::GarbageCollector* gc) {
2700 // TODO: Add a new runtime option for this?
2701 if (verify_pre_gc_rosalloc_) {
Mathieu Chartier10fb83a2014-06-15 15:15:43 -07002702 RosAllocVerification(current_gc_iteration_.GetTimings(), "PreGcRosAllocVerification");
Mathieu Chartier2b82db42012-11-14 17:29:05 -08002703 }
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08002704}
2705
Ian Rogers1d54e732013-05-02 21:10:01 -07002706void Heap::PreSweepingGcVerification(collector::GarbageCollector* gc) {
Mathieu Chartier6f365cc2014-04-23 12:42:27 -07002707 Thread* const self = Thread::Current();
Mathieu Chartier10fb83a2014-06-15 15:15:43 -07002708 TimingLogger* const timings = current_gc_iteration_.GetTimings();
Mathieu Chartierf5997b42014-06-20 10:37:54 -07002709 TimingLogger::ScopedTiming t(__FUNCTION__, timings);
Mathieu Chartier2b82db42012-11-14 17:29:05 -08002710 // Called before sweeping occurs since we want to make sure we are not going so reclaim any
2711 // reachable objects.
Mathieu Chartier6f365cc2014-04-23 12:42:27 -07002712 if (verify_pre_sweeping_heap_) {
Mathieu Chartierf5997b42014-06-20 10:37:54 -07002713 TimingLogger::ScopedTiming t("(Paused)PostSweepingVerifyHeapReferences", timings);
Ian Rogers1d54e732013-05-02 21:10:01 -07002714 CHECK_NE(self->GetState(), kRunnable);
Mathieu Chartier6f365cc2014-04-23 12:42:27 -07002715 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
2716 // Swapping bound bitmaps does nothing.
2717 gc->SwapBitmaps();
Mathieu Chartier78f7b4c2014-05-06 10:57:27 -07002718 // Pass in false since concurrent reference processing can mean that the reference referents
2719 // may point to dead objects at the point which PreSweepingGcVerification is called.
Mathieu Chartier8ab7e782014-05-19 16:55:27 -07002720 size_t failures = VerifyHeapReferences(false);
2721 if (failures > 0) {
2722 LOG(FATAL) << "Pre sweeping " << gc->GetName() << " GC verification failed with " << failures
2723 << " failures";
Mathieu Chartier6f365cc2014-04-23 12:42:27 -07002724 }
Mathieu Chartier6f365cc2014-04-23 12:42:27 -07002725 gc->SwapBitmaps();
2726 }
2727 if (verify_pre_sweeping_rosalloc_) {
2728 RosAllocVerification(timings, "PreSweepingRosAllocVerification");
2729 }
2730}
2731
2732void Heap::PostGcVerificationPaused(collector::GarbageCollector* gc) {
2733 // Only pause if we have to do some verification.
2734 Thread* const self = Thread::Current();
Mathieu Chartier10fb83a2014-06-15 15:15:43 -07002735 TimingLogger* const timings = GetCurrentGcIteration()->GetTimings();
Mathieu Chartierf5997b42014-06-20 10:37:54 -07002736 TimingLogger::ScopedTiming t(__FUNCTION__, timings);
Mathieu Chartier6f365cc2014-04-23 12:42:27 -07002737 if (verify_system_weaks_) {
2738 ReaderMutexLock mu2(self, *Locks::heap_bitmap_lock_);
2739 collector::MarkSweep* mark_sweep = down_cast<collector::MarkSweep*>(gc);
2740 mark_sweep->VerifySystemWeaks();
2741 }
2742 if (verify_post_gc_rosalloc_) {
Mathieu Chartierf5997b42014-06-20 10:37:54 -07002743 RosAllocVerification(timings, "(Paused)PostGcRosAllocVerification");
Mathieu Chartier6f365cc2014-04-23 12:42:27 -07002744 }
2745 if (verify_post_gc_heap_) {
Mathieu Chartierf5997b42014-06-20 10:37:54 -07002746 TimingLogger::ScopedTiming t("(Paused)PostGcVerifyHeapReferences", timings);
Mathieu Chartier6f365cc2014-04-23 12:42:27 -07002747 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier8ab7e782014-05-19 16:55:27 -07002748 size_t failures = VerifyHeapReferences();
2749 if (failures > 0) {
2750 LOG(FATAL) << "Pre " << gc->GetName() << " heap verification failed with " << failures
2751 << " failures";
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002752 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002753 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -08002754}
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002755
Ian Rogers1d54e732013-05-02 21:10:01 -07002756void Heap::PostGcVerification(collector::GarbageCollector* gc) {
Mathieu Chartier6f365cc2014-04-23 12:42:27 -07002757 if (verify_system_weaks_ || verify_post_gc_rosalloc_ || verify_post_gc_heap_) {
2758 collector::GarbageCollector::ScopedPause pause(gc);
Mathieu Chartierd35326f2014-08-18 15:02:59 -07002759 PostGcVerificationPaused(gc);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002760 }
Carl Shapiro69759ea2011-07-21 18:13:35 -07002761}
2762
Mathieu Chartier6f365cc2014-04-23 12:42:27 -07002763void Heap::RosAllocVerification(TimingLogger* timings, const char* name) {
Mathieu Chartierf5997b42014-06-20 10:37:54 -07002764 TimingLogger::ScopedTiming t(name, timings);
Mathieu Chartier6f365cc2014-04-23 12:42:27 -07002765 for (const auto& space : continuous_spaces_) {
2766 if (space->IsRosAllocSpace()) {
2767 VLOG(heap) << name << " : " << space->GetName();
2768 space->AsRosAllocSpace()->Verify();
Hiroshi Yamauchia4adbfd2014-02-04 18:12:17 -08002769 }
2770 }
2771}
2772
Mathieu Chartier89a201e2014-05-02 10:27:26 -07002773collector::GcType Heap::WaitForGcToComplete(GcCause cause, Thread* self) {
Mathieu Chartiercaa82d62014-02-02 16:51:17 -08002774 ScopedThreadStateChange tsc(self, kWaitingForGcToComplete);
Mathieu Chartier590fee92013-09-13 13:46:47 -07002775 MutexLock mu(self, *gc_complete_lock_);
Mathieu Chartier89a201e2014-05-02 10:27:26 -07002776 return WaitForGcToCompleteLocked(cause, self);
Mathieu Chartier590fee92013-09-13 13:46:47 -07002777}
2778
Mathieu Chartier89a201e2014-05-02 10:27:26 -07002779collector::GcType Heap::WaitForGcToCompleteLocked(GcCause cause, Thread* self) {
Ian Rogers1d54e732013-05-02 21:10:01 -07002780 collector::GcType last_gc_type = collector::kGcTypeNone;
Mathieu Chartier590fee92013-09-13 13:46:47 -07002781 uint64_t wait_start = NanoTime();
Mathieu Chartierd5a89ee2014-01-31 09:55:13 -08002782 while (collector_type_running_ != kCollectorTypeNone) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07002783 ATRACE_BEGIN("GC: Wait For Completion");
2784 // We must wait, change thread state then sleep on gc_complete_cond_;
2785 gc_complete_cond_->Wait(self);
2786 last_gc_type = last_gc_type_;
Mathieu Chartier752a0e62013-06-27 11:03:27 -07002787 ATRACE_END();
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07002788 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07002789 uint64_t wait_time = NanoTime() - wait_start;
2790 total_wait_time_ += wait_time;
2791 if (wait_time > long_pause_log_threshold_) {
Mathieu Chartier89a201e2014-05-02 10:27:26 -07002792 LOG(INFO) << "WaitForGcToComplete blocked for " << PrettyDuration(wait_time)
2793 << " for cause " << cause;
Mathieu Chartier590fee92013-09-13 13:46:47 -07002794 }
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07002795 return last_gc_type;
Carl Shapiro69759ea2011-07-21 18:13:35 -07002796}
2797
Elliott Hughesc967f782012-04-16 10:23:15 -07002798void Heap::DumpForSigQuit(std::ostream& os) {
Ian Rogers1d54e732013-05-02 21:10:01 -07002799 os << "Heap: " << GetPercentFree() << "% free, " << PrettySize(GetBytesAllocated()) << "/"
Mathieu Chartier2fde5332012-09-14 14:51:54 -07002800 << PrettySize(GetTotalMemory()) << "; " << GetObjectsAllocated() << " objects\n";
Elliott Hughes8b788fe2013-04-17 15:57:01 -07002801 DumpGcPerformanceInfo(os);
Elliott Hughesc967f782012-04-16 10:23:15 -07002802}
2803
2804size_t Heap::GetPercentFree() {
Mathieu Chartierd30e1d62014-06-09 13:25:22 -07002805 return static_cast<size_t>(100.0f * static_cast<float>(GetFreeMemory()) / max_allowed_footprint_);
Elliott Hughesc967f782012-04-16 10:23:15 -07002806}
2807
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002808void Heap::SetIdealFootprint(size_t max_allowed_footprint) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07002809 if (max_allowed_footprint > GetMaxMemory()) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07002810 VLOG(gc) << "Clamp target GC heap from " << PrettySize(max_allowed_footprint) << " to "
Mathieu Chartier2fde5332012-09-14 14:51:54 -07002811 << PrettySize(GetMaxMemory());
2812 max_allowed_footprint = GetMaxMemory();
2813 }
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -07002814 max_allowed_footprint_ = max_allowed_footprint;
Shih-wei Liao8c2f6412011-10-03 22:58:14 -07002815}
2816
Mathieu Chartier590fee92013-09-13 13:46:47 -07002817bool Heap::IsMovableObject(const mirror::Object* obj) const {
2818 if (kMovingCollector) {
Mathieu Chartier31f44142014-04-08 14:40:03 -07002819 space::Space* space = FindContinuousSpaceFromObject(obj, true);
2820 if (space != nullptr) {
2821 // TODO: Check large object?
2822 return space->CanMoveObjects();
Mathieu Chartier590fee92013-09-13 13:46:47 -07002823 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07002824 }
2825 return false;
2826}
2827
Mathieu Chartier987ccff2013-07-08 11:05:21 -07002828void Heap::UpdateMaxNativeFootprint() {
Ian Rogers3e5cf302014-05-20 16:40:37 -07002829 size_t native_size = native_bytes_allocated_.LoadRelaxed();
Mathieu Chartier987ccff2013-07-08 11:05:21 -07002830 // TODO: Tune the native heap utilization to be a value other than the java heap utilization.
2831 size_t target_size = native_size / GetTargetHeapUtilization();
2832 if (target_size > native_size + max_free_) {
2833 target_size = native_size + max_free_;
2834 } else if (target_size < native_size + min_free_) {
2835 target_size = native_size + min_free_;
2836 }
Mathieu Chartier8ec31f92014-09-03 10:30:11 -07002837 native_footprint_gc_watermark_ = std::min(growth_limit_, target_size);
Mathieu Chartier987ccff2013-07-08 11:05:21 -07002838}
2839
Mathieu Chartierafe49982014-03-27 10:55:04 -07002840collector::GarbageCollector* Heap::FindCollectorByGcType(collector::GcType gc_type) {
2841 for (const auto& collector : garbage_collectors_) {
2842 if (collector->GetCollectorType() == collector_type_ &&
2843 collector->GetGcType() == gc_type) {
2844 return collector;
2845 }
2846 }
2847 return nullptr;
2848}
2849
Mathieu Chartier2f8da3e2014-04-15 15:37:02 -07002850double Heap::HeapGrowthMultiplier() const {
2851 // If we don't care about pause times we are background, so return 1.0.
2852 if (!CareAboutPauseTimes() || IsLowMemoryMode()) {
2853 return 1.0;
2854 }
2855 return foreground_heap_growth_multiplier_;
2856}
2857
Mathieu Chartierafe49982014-03-27 10:55:04 -07002858void Heap::GrowForUtilization(collector::GarbageCollector* collector_ran) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07002859 // We know what our utilization is at this moment.
2860 // This doesn't actually resize any memory. It just lets the heap grow more when necessary.
Mathieu Chartier2f8da3e2014-04-15 15:37:02 -07002861 const uint64_t bytes_allocated = GetBytesAllocated();
Mathieu Chartier65db8802012-11-20 12:36:46 -08002862 last_gc_size_ = bytes_allocated;
Ian Rogers1d54e732013-05-02 21:10:01 -07002863 last_gc_time_ns_ = NanoTime();
Mathieu Chartier2f8da3e2014-04-15 15:37:02 -07002864 uint64_t target_size;
Mathieu Chartierafe49982014-03-27 10:55:04 -07002865 collector::GcType gc_type = collector_ran->GetGcType();
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -07002866 if (gc_type != collector::kGcTypeSticky) {
2867 // Grow the heap for non sticky GC.
Mathieu Chartier2f8da3e2014-04-15 15:37:02 -07002868 const float multiplier = HeapGrowthMultiplier(); // Use the multiplier to grow more for
2869 // foreground.
2870 intptr_t delta = bytes_allocated / GetTargetHeapUtilization() - bytes_allocated;
2871 CHECK_GE(delta, 0);
2872 target_size = bytes_allocated + delta * multiplier;
2873 target_size = std::min(target_size,
2874 bytes_allocated + static_cast<uint64_t>(max_free_ * multiplier));
2875 target_size = std::max(target_size,
2876 bytes_allocated + static_cast<uint64_t>(min_free_ * multiplier));
Mathieu Chartier590fee92013-09-13 13:46:47 -07002877 native_need_to_run_finalization_ = true;
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -07002878 next_gc_type_ = collector::kGcTypeSticky;
2879 } else {
Mathieu Chartierafe49982014-03-27 10:55:04 -07002880 collector::GcType non_sticky_gc_type =
Mathieu Chartiere4cab172014-08-19 18:24:04 -07002881 HasZygoteSpace() ? collector::kGcTypePartial : collector::kGcTypeFull;
Mathieu Chartierafe49982014-03-27 10:55:04 -07002882 // Find what the next non sticky collector will be.
2883 collector::GarbageCollector* non_sticky_collector = FindCollectorByGcType(non_sticky_gc_type);
2884 // If the throughput of the current sticky GC >= throughput of the non sticky collector, then
2885 // do another sticky collection next.
2886 // We also check that the bytes allocated aren't over the footprint limit in order to prevent a
2887 // pathological case where dead objects which aren't reclaimed by sticky could get accumulated
2888 // if the sticky GC throughput always remained >= the full/partial throughput.
Mathieu Chartier10fb83a2014-06-15 15:15:43 -07002889 if (current_gc_iteration_.GetEstimatedThroughput() * kStickyGcThroughputAdjustment >=
Mathieu Chartierafe49982014-03-27 10:55:04 -07002890 non_sticky_collector->GetEstimatedMeanThroughput() &&
Mathieu Chartier10fb83a2014-06-15 15:15:43 -07002891 non_sticky_collector->NumberOfIterations() > 0 &&
Mathieu Chartierafe49982014-03-27 10:55:04 -07002892 bytes_allocated <= max_allowed_footprint_) {
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -07002893 next_gc_type_ = collector::kGcTypeSticky;
2894 } else {
Mathieu Chartierafe49982014-03-27 10:55:04 -07002895 next_gc_type_ = non_sticky_gc_type;
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -07002896 }
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -07002897 // If we have freed enough memory, shrink the heap back down.
2898 if (bytes_allocated + max_free_ < max_allowed_footprint_) {
2899 target_size = bytes_allocated + max_free_;
2900 } else {
Mathieu Chartier2f8da3e2014-04-15 15:37:02 -07002901 target_size = std::max(bytes_allocated, static_cast<uint64_t>(max_allowed_footprint_));
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -07002902 }
2903 }
Mathieu Chartier2775ee42013-08-20 17:43:47 -07002904 if (!ignore_max_footprint_) {
2905 SetIdealFootprint(target_size);
Hiroshi Yamauchi3e417802014-03-20 12:03:02 -07002906 if (IsGcConcurrent()) {
Mathieu Chartier2775ee42013-08-20 17:43:47 -07002907 // Calculate when to perform the next ConcurrentGC.
Mathieu Chartier2775ee42013-08-20 17:43:47 -07002908 // Calculate the estimated GC duration.
Mathieu Chartier10fb83a2014-06-15 15:15:43 -07002909 const double gc_duration_seconds = NsToMs(current_gc_iteration_.GetDurationNs()) / 1000.0;
Mathieu Chartier2775ee42013-08-20 17:43:47 -07002910 // Estimate how many remaining bytes we will have when we need to start the next GC.
2911 size_t remaining_bytes = allocation_rate_ * gc_duration_seconds;
Mathieu Chartier74762802014-01-24 10:21:35 -08002912 remaining_bytes = std::min(remaining_bytes, kMaxConcurrentRemainingBytes);
Mathieu Chartier2775ee42013-08-20 17:43:47 -07002913 remaining_bytes = std::max(remaining_bytes, kMinConcurrentRemainingBytes);
2914 if (UNLIKELY(remaining_bytes > max_allowed_footprint_)) {
2915 // A never going to happen situation that from the estimated allocation rate we will exceed
2916 // the applications entire footprint with the given estimated allocation rate. Schedule
Mathieu Chartier74762802014-01-24 10:21:35 -08002917 // another GC nearly straight away.
2918 remaining_bytes = kMinConcurrentRemainingBytes;
Mathieu Chartier2775ee42013-08-20 17:43:47 -07002919 }
Mathieu Chartier74762802014-01-24 10:21:35 -08002920 DCHECK_LE(remaining_bytes, max_allowed_footprint_);
Mathieu Chartierdd162fb2014-08-06 17:06:33 -07002921 DCHECK_LE(max_allowed_footprint_, GetMaxMemory());
Mathieu Chartier74762802014-01-24 10:21:35 -08002922 // Start a concurrent GC when we get close to the estimated remaining bytes. When the
2923 // allocation rate is very high, remaining_bytes could tell us that we should start a GC
2924 // right away.
Mathieu Chartier2f8da3e2014-04-15 15:37:02 -07002925 concurrent_start_bytes_ = std::max(max_allowed_footprint_ - remaining_bytes,
2926 static_cast<size_t>(bytes_allocated));
Mathieu Chartier65db8802012-11-20 12:36:46 -08002927 }
Mathieu Chartier65db8802012-11-20 12:36:46 -08002928 }
Carl Shapiro69759ea2011-07-21 18:13:35 -07002929}
2930
jeffhaoc1160702011-10-27 15:48:45 -07002931void Heap::ClearGrowthLimit() {
Mathieu Chartier80de7a62012-11-27 17:21:50 -08002932 growth_limit_ = capacity_;
Mathieu Chartier590fee92013-09-13 13:46:47 -07002933 non_moving_space_->ClearGrowthLimit();
jeffhaoc1160702011-10-27 15:48:45 -07002934}
2935
Mathieu Chartier8668c3c2014-04-24 16:48:11 -07002936void Heap::AddFinalizerReference(Thread* self, mirror::Object** object) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002937 ScopedObjectAccess soa(self);
Mathieu Chartier8668c3c2014-04-24 16:48:11 -07002938 ScopedLocalRef<jobject> arg(self->GetJniEnv(), soa.AddLocalReference<jobject>(*object));
Ian Rogers53b8b092014-03-13 23:45:53 -07002939 jvalue args[1];
2940 args[0].l = arg.get();
2941 InvokeWithJValues(soa, nullptr, WellKnownClasses::java_lang_ref_FinalizerReference_add, args);
Mathieu Chartier8668c3c2014-04-24 16:48:11 -07002942 // Restore object in case it gets moved.
2943 *object = soa.Decode<mirror::Object*>(arg.get());
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002944}
2945
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002946void Heap::RequestConcurrentGCAndSaveObject(Thread* self, mirror::Object** obj) {
2947 StackHandleScope<1> hs(self);
2948 HandleWrapper<mirror::Object> wrapper(hs.NewHandleWrapper(obj));
2949 RequestConcurrentGC(self);
2950}
2951
Ian Rogers1f539342012-10-03 21:09:42 -07002952void Heap::RequestConcurrentGC(Thread* self) {
Mathieu Chartier069387a2012-06-18 12:01:01 -07002953 // Make sure that we can do a concurrent GC.
Ian Rogers120f1c72012-09-28 17:17:10 -07002954 Runtime* runtime = Runtime::Current();
Mathieu Chartier78f7b4c2014-05-06 10:57:27 -07002955 if (runtime == nullptr || !runtime->IsFinishedStarting() || runtime->IsShuttingDown(self) ||
Mathieu Chartier590fee92013-09-13 13:46:47 -07002956 self->IsHandlingStackOverflow()) {
Ian Rogers120f1c72012-09-28 17:17:10 -07002957 return;
2958 }
Mathieu Chartier987ccff2013-07-08 11:05:21 -07002959 // We already have a request pending, no reason to start more until we update
2960 // concurrent_start_bytes_.
2961 concurrent_start_bytes_ = std::numeric_limits<size_t>::max();
Ian Rogers120f1c72012-09-28 17:17:10 -07002962 JNIEnv* env = self->GetJniEnv();
Mathieu Chartier590fee92013-09-13 13:46:47 -07002963 DCHECK(WellKnownClasses::java_lang_Daemons != nullptr);
2964 DCHECK(WellKnownClasses::java_lang_Daemons_requestGC != nullptr);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002965 env->CallStaticVoidMethod(WellKnownClasses::java_lang_Daemons,
2966 WellKnownClasses::java_lang_Daemons_requestGC);
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07002967 CHECK(!env->ExceptionCheck());
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07002968}
2969
Ian Rogers81d425b2012-09-27 16:03:43 -07002970void Heap::ConcurrentGC(Thread* self) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07002971 if (Runtime::Current()->IsShuttingDown(self)) {
2972 return;
Mathieu Chartier2542d662012-06-21 17:14:11 -07002973 }
Mathieu Chartier65db8802012-11-20 12:36:46 -08002974 // Wait for any GCs currently running to finish.
Mathieu Chartier89a201e2014-05-02 10:27:26 -07002975 if (WaitForGcToComplete(kGcCauseBackground, self) == collector::kGcTypeNone) {
Mathieu Chartierf9ed0d32013-11-21 16:42:47 -08002976 // If the we can't run the GC type we wanted to run, find the next appropriate one and try that
2977 // instead. E.g. can't do partial, so do full instead.
2978 if (CollectGarbageInternal(next_gc_type_, kGcCauseBackground, false) ==
2979 collector::kGcTypeNone) {
2980 for (collector::GcType gc_type : gc_plan_) {
2981 // Attempt to run the collector, if we succeed, we are done.
2982 if (gc_type > next_gc_type_ &&
2983 CollectGarbageInternal(gc_type, kGcCauseBackground, false) != collector::kGcTypeNone) {
2984 break;
2985 }
2986 }
2987 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -07002988 }
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07002989}
2990
Mathieu Chartier7bf52d22014-03-13 14:46:09 -07002991void Heap::RequestCollectorTransition(CollectorType desired_collector_type, uint64_t delta_time) {
Mathieu Chartiera5f9de02014-02-28 16:48:42 -08002992 Thread* self = Thread::Current();
2993 {
2994 MutexLock mu(self, *heap_trim_request_lock_);
2995 if (desired_collector_type_ == desired_collector_type) {
2996 return;
2997 }
Mathieu Chartierb2728552014-09-08 20:08:41 +00002998 heap_transition_or_trim_target_time_ =
2999 std::max(heap_transition_or_trim_target_time_, NanoTime() + delta_time);
Mathieu Chartiera5f9de02014-02-28 16:48:42 -08003000 desired_collector_type_ = desired_collector_type;
3001 }
3002 SignalHeapTrimDaemon(self);
3003}
3004
Mathieu Chartier7bf52d22014-03-13 14:46:09 -07003005void Heap::RequestHeapTrim() {
Ian Rogers48931882013-01-22 14:35:16 -08003006 // GC completed and now we must decide whether to request a heap trim (advising pages back to the
3007 // kernel) or not. Issuing a request will also cause trimming of the libc heap. As a trim scans
3008 // a space it will hold its lock and can become a cause of jank.
3009 // Note, the large object space self trims and the Zygote space was trimmed and unchanging since
3010 // forking.
3011
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08003012 // We don't have a good measure of how worthwhile a trim might be. We can't use the live bitmap
3013 // because that only marks object heads, so a large array looks like lots of empty space. We
3014 // don't just call dlmalloc all the time, because the cost of an _attempted_ trim is proportional
3015 // to utilization (which is probably inversely proportional to how much benefit we can expect).
3016 // We could try mincore(2) but that's only a measure of how many pages we haven't given away,
3017 // not how much use we're making of those pages.
Ian Rogers120f1c72012-09-28 17:17:10 -07003018
3019 Thread* self = Thread::Current();
Mathieu Chartier590fee92013-09-13 13:46:47 -07003020 Runtime* runtime = Runtime::Current();
Mathieu Chartier30cbbee2014-09-08 13:35:11 -07003021 if (runtime == nullptr || !runtime->IsFinishedStarting() || runtime->IsShuttingDown(self) ||
3022 runtime->IsZygote()) {
3023 // Ignore the request if we are the zygote to prevent app launching lag due to sleep in heap
3024 // trimmer daemon. b/17310019
Mathieu Chartier590fee92013-09-13 13:46:47 -07003025 // Heap trimming isn't supported without a Java runtime or Daemons (such as at dex2oat time)
3026 // Also: we do not wish to start a heap trim if the runtime is shutting down (a racy check
3027 // as we don't hold the lock while requesting the trim).
3028 return;
Ian Rogerse1d490c2012-02-03 09:09:07 -08003029 }
Mathieu Chartier440e4ce2014-03-31 16:36:35 -07003030 {
3031 MutexLock mu(self, *heap_trim_request_lock_);
3032 if (last_trim_time_ + kHeapTrimWait >= NanoTime()) {
3033 // We have done a heap trim in the last kHeapTrimWait nanosecs, don't request another one
3034 // just yet.
3035 return;
Mathieu Chartiera5f9de02014-02-28 16:48:42 -08003036 }
Mathieu Chartier440e4ce2014-03-31 16:36:35 -07003037 heap_trim_request_pending_ = true;
Mathieu Chartierb2728552014-09-08 20:08:41 +00003038 uint64_t current_time = NanoTime();
3039 if (heap_transition_or_trim_target_time_ < current_time) {
3040 heap_transition_or_trim_target_time_ = current_time + kHeapTrimWait;
3041 }
Mathieu Chartierc39e3422013-08-07 16:41:36 -07003042 }
Mathieu Chartier440e4ce2014-03-31 16:36:35 -07003043 // Notify the daemon thread which will actually do the heap trim.
3044 SignalHeapTrimDaemon(self);
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08003045}
3046
Mathieu Chartiera5f9de02014-02-28 16:48:42 -08003047void Heap::SignalHeapTrimDaemon(Thread* self) {
3048 JNIEnv* env = self->GetJniEnv();
3049 DCHECK(WellKnownClasses::java_lang_Daemons != nullptr);
3050 DCHECK(WellKnownClasses::java_lang_Daemons_requestHeapTrim != nullptr);
3051 env->CallStaticVoidMethod(WellKnownClasses::java_lang_Daemons,
3052 WellKnownClasses::java_lang_Daemons_requestHeapTrim);
3053 CHECK(!env->ExceptionCheck());
3054}
3055
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -07003056void Heap::RevokeThreadLocalBuffers(Thread* thread) {
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08003057 if (rosalloc_space_ != nullptr) {
3058 rosalloc_space_->RevokeThreadLocalBuffers(thread);
3059 }
Mathieu Chartier692fafd2013-11-29 17:24:40 -08003060 if (bump_pointer_space_ != nullptr) {
3061 bump_pointer_space_->RevokeThreadLocalBuffers(thread);
3062 }
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -07003063}
3064
Hiroshi Yamauchic93c5302014-03-20 16:15:37 -07003065void Heap::RevokeRosAllocThreadLocalBuffers(Thread* thread) {
3066 if (rosalloc_space_ != nullptr) {
3067 rosalloc_space_->RevokeThreadLocalBuffers(thread);
3068 }
3069}
3070
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -07003071void Heap::RevokeAllThreadLocalBuffers() {
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08003072 if (rosalloc_space_ != nullptr) {
3073 rosalloc_space_->RevokeAllThreadLocalBuffers();
3074 }
Mathieu Chartier692fafd2013-11-29 17:24:40 -08003075 if (bump_pointer_space_ != nullptr) {
3076 bump_pointer_space_->RevokeAllThreadLocalBuffers();
3077 }
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -07003078}
3079
Mathieu Chartier987ccff2013-07-08 11:05:21 -07003080bool Heap::IsGCRequestPending() const {
3081 return concurrent_start_bytes_ != std::numeric_limits<size_t>::max();
3082}
3083
Mathieu Chartier590fee92013-09-13 13:46:47 -07003084void Heap::RunFinalization(JNIEnv* env) {
3085 // Can't do this in WellKnownClasses::Init since System is not properly set up at that point.
3086 if (WellKnownClasses::java_lang_System_runFinalization == nullptr) {
3087 CHECK(WellKnownClasses::java_lang_System != nullptr);
3088 WellKnownClasses::java_lang_System_runFinalization =
3089 CacheMethod(env, WellKnownClasses::java_lang_System, true, "runFinalization", "()V");
3090 CHECK(WellKnownClasses::java_lang_System_runFinalization != nullptr);
3091 }
3092 env->CallStaticVoidMethod(WellKnownClasses::java_lang_System,
3093 WellKnownClasses::java_lang_System_runFinalization);
3094}
3095
Mathieu Chartier8ec31f92014-09-03 10:30:11 -07003096void Heap::RegisterNativeAllocation(JNIEnv* env, size_t bytes) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07003097 Thread* self = ThreadForEnv(env);
3098 if (native_need_to_run_finalization_) {
3099 RunFinalization(env);
3100 UpdateMaxNativeFootprint();
3101 native_need_to_run_finalization_ = false;
3102 }
Mathieu Chartier987ccff2013-07-08 11:05:21 -07003103 // Total number of native bytes allocated.
Ian Rogers3e5cf302014-05-20 16:40:37 -07003104 size_t new_native_bytes_allocated = native_bytes_allocated_.FetchAndAddSequentiallyConsistent(bytes);
3105 new_native_bytes_allocated += bytes;
3106 if (new_native_bytes_allocated > native_footprint_gc_watermark_) {
Mathieu Chartiere4cab172014-08-19 18:24:04 -07003107 collector::GcType gc_type = HasZygoteSpace() ? collector::kGcTypePartial :
Mathieu Chartiercbb2d202013-11-14 17:45:16 -08003108 collector::kGcTypeFull;
3109
Mathieu Chartier987ccff2013-07-08 11:05:21 -07003110 // The second watermark is higher than the gc watermark. If you hit this it means you are
3111 // allocating native objects faster than the GC can keep up with.
Mathieu Chartier08487452014-09-02 16:21:01 -07003112 if (new_native_bytes_allocated > growth_limit_) {
Mathieu Chartier89a201e2014-05-02 10:27:26 -07003113 if (WaitForGcToComplete(kGcCauseForNativeAlloc, self) != collector::kGcTypeNone) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07003114 // Just finished a GC, attempt to run finalizers.
3115 RunFinalization(env);
3116 CHECK(!env->ExceptionCheck());
3117 }
3118 // If we still are over the watermark, attempt a GC for alloc and run finalizers.
Mathieu Chartier08487452014-09-02 16:21:01 -07003119 if (new_native_bytes_allocated > growth_limit_) {
Hiroshi Yamauchi6f4ffe42014-01-13 12:30:44 -08003120 CollectGarbageInternal(gc_type, kGcCauseForNativeAlloc, false);
Mathieu Chartier590fee92013-09-13 13:46:47 -07003121 RunFinalization(env);
3122 native_need_to_run_finalization_ = false;
3123 CHECK(!env->ExceptionCheck());
3124 }
3125 // We have just run finalizers, update the native watermark since it is very likely that
3126 // finalizers released native managed allocations.
3127 UpdateMaxNativeFootprint();
3128 } else if (!IsGCRequestPending()) {
Hiroshi Yamauchi3e417802014-03-20 12:03:02 -07003129 if (IsGcConcurrent()) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07003130 RequestConcurrentGC(self);
3131 } else {
Hiroshi Yamauchid20aba12014-04-11 15:31:09 -07003132 CollectGarbageInternal(gc_type, kGcCauseForNativeAlloc, false);
Mathieu Chartier987ccff2013-07-08 11:05:21 -07003133 }
3134 }
3135 }
3136}
3137
Mathieu Chartier8ec31f92014-09-03 10:30:11 -07003138void Heap::RegisterNativeFree(JNIEnv* env, size_t bytes) {
3139 size_t expected_size;
Mathieu Chartier987ccff2013-07-08 11:05:21 -07003140 do {
Ian Rogers3e5cf302014-05-20 16:40:37 -07003141 expected_size = native_bytes_allocated_.LoadRelaxed();
Mathieu Chartier8ec31f92014-09-03 10:30:11 -07003142 if (UNLIKELY(bytes > expected_size)) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07003143 ScopedObjectAccess soa(env);
3144 env->ThrowNew(WellKnownClasses::java_lang_RuntimeException,
Mathieu Chartier8ec31f92014-09-03 10:30:11 -07003145 StringPrintf("Attempted to free %zd native bytes with only %zd native bytes "
Mathieu Chartier590fee92013-09-13 13:46:47 -07003146 "registered as allocated", bytes, expected_size).c_str());
3147 break;
3148 }
Mathieu Chartier8ec31f92014-09-03 10:30:11 -07003149 } while (!native_bytes_allocated_.CompareExchangeWeakRelaxed(expected_size,
3150 expected_size - bytes));
Mathieu Chartier987ccff2013-07-08 11:05:21 -07003151}
3152
Ian Rogersef7d42f2014-01-06 12:55:46 -08003153size_t Heap::GetTotalMemory() const {
Mathieu Chartierdd162fb2014-08-06 17:06:33 -07003154 return std::max(max_allowed_footprint_, GetBytesAllocated());
Hiroshi Yamauchi09b07a92013-07-15 13:17:06 -07003155}
3156
Mathieu Chartier11409ae2013-09-23 11:49:36 -07003157void Heap::AddModUnionTable(accounting::ModUnionTable* mod_union_table) {
3158 DCHECK(mod_union_table != nullptr);
3159 mod_union_tables_.Put(mod_union_table->GetSpace(), mod_union_table);
3160}
3161
Mathieu Chartierc645f1d2014-03-06 18:11:53 -08003162void Heap::CheckPreconditionsForAllocObject(mirror::Class* c, size_t byte_count) {
3163 CHECK(c == NULL || (c->IsClassClass() && byte_count >= sizeof(mirror::Class)) ||
Ian Rogers1ff3c982014-08-12 02:30:58 -07003164 (c->IsVariableSize() || c->GetObjectSize() == byte_count));
Mathieu Chartierc645f1d2014-03-06 18:11:53 -08003165 CHECK_GE(byte_count, sizeof(mirror::Object));
3166}
3167
Hiroshi Yamauchi38e68e92014-03-07 13:59:08 -08003168void Heap::AddRememberedSet(accounting::RememberedSet* remembered_set) {
3169 CHECK(remembered_set != nullptr);
3170 space::Space* space = remembered_set->GetSpace();
3171 CHECK(space != nullptr);
Mathieu Chartier8e4a96d2014-05-21 10:44:32 -07003172 CHECK(remembered_sets_.find(space) == remembered_sets_.end()) << space;
Hiroshi Yamauchi38e68e92014-03-07 13:59:08 -08003173 remembered_sets_.Put(space, remembered_set);
Mathieu Chartier8e4a96d2014-05-21 10:44:32 -07003174 CHECK(remembered_sets_.find(space) != remembered_sets_.end()) << space;
Hiroshi Yamauchi38e68e92014-03-07 13:59:08 -08003175}
3176
3177void Heap::RemoveRememberedSet(space::Space* space) {
3178 CHECK(space != nullptr);
3179 auto it = remembered_sets_.find(space);
3180 CHECK(it != remembered_sets_.end());
Mathieu Chartier5189e242014-07-24 11:11:05 -07003181 delete it->second;
Hiroshi Yamauchi38e68e92014-03-07 13:59:08 -08003182 remembered_sets_.erase(it);
3183 CHECK(remembered_sets_.find(space) == remembered_sets_.end());
3184}
3185
Mathieu Chartier4aeec172014-03-27 16:09:46 -07003186void Heap::ClearMarkedObjects() {
3187 // Clear all of the spaces' mark bitmaps.
3188 for (const auto& space : GetContinuousSpaces()) {
Mathieu Chartiera8e8f9c2014-04-09 14:51:05 -07003189 accounting::ContinuousSpaceBitmap* mark_bitmap = space->GetMarkBitmap();
Mathieu Chartier4aeec172014-03-27 16:09:46 -07003190 if (space->GetLiveBitmap() != mark_bitmap) {
3191 mark_bitmap->Clear();
3192 }
3193 }
3194 // Clear the marked objects in the discontinous space object sets.
3195 for (const auto& space : GetDiscontinuousSpaces()) {
Mathieu Chartierbbd695c2014-04-16 09:48:48 -07003196 space->GetMarkBitmap()->Clear();
Mathieu Chartier4aeec172014-03-27 16:09:46 -07003197 }
3198}
3199
Ian Rogers1d54e732013-05-02 21:10:01 -07003200} // namespace gc
Carl Shapiro69759ea2011-07-21 18:13:35 -07003201} // namespace art