blob: 8cd8d73ba5d796b5eeac65b17de882f636cc47ba [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>
Mathieu Chartier31000802015-06-14 14:14:37 -070024#include <unwind.h> // For GC verification.
Carl Shapiro58551df2011-07-24 03:09:51 -070025#include <vector>
26
Mathieu Chartierc7853442015-03-27 14:35:38 -070027#include "art_field-inl.h"
Mathieu Chartierbad02672014-08-25 13:08:22 -070028#include "base/allocator.h"
Mathieu Chartier8d447252015-10-26 10:21:14 -070029#include "base/arena_allocator.h"
Ian Rogersc7dd2952014-10-21 23:31:19 -070030#include "base/dumpable.h"
Mathieu Chartierb2f99362013-11-20 17:26:00 -080031#include "base/histogram-inl.h"
Elliott Hughes1aa246d2012-12-13 09:29:36 -080032#include "base/stl_util.h"
Vladimir Marko80afd022015-05-19 18:08:00 +010033#include "base/time_utils.h"
Mathieu Chartier987ccff2013-07-08 11:05:21 -070034#include "common_throws.h"
Ian Rogers48931882013-01-22 14:35:16 -080035#include "cutils/sched_policy.h"
Elliott Hughes767a1472011-10-26 18:49:02 -070036#include "debugger.h"
Elliott Hughes956af0f2014-12-11 14:34:28 -080037#include "dex_file-inl.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070038#include "gc/accounting/atomic_stack.h"
39#include "gc/accounting/card_table-inl.h"
40#include "gc/accounting/heap_bitmap-inl.h"
41#include "gc/accounting/mod_union_table-inl.h"
Hiroshi Yamauchi38e68e92014-03-07 13:59:08 -080042#include "gc/accounting/remembered_set.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070043#include "gc/accounting/space_bitmap-inl.h"
Hiroshi Yamauchid5307ec2014-03-27 21:07:51 -070044#include "gc/collector/concurrent_copying.h"
Mathieu Chartier52e4b432014-06-10 11:22:31 -070045#include "gc/collector/mark_compact.h"
Mathieu Chartier3cf22532015-07-09 15:15:09 -070046#include "gc/collector/mark_sweep.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070047#include "gc/collector/partial_mark_sweep.h"
Mathieu Chartier590fee92013-09-13 13:46:47 -070048#include "gc/collector/semi_space.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070049#include "gc/collector/sticky_mark_sweep.h"
Mathieu Chartier78f7b4c2014-05-06 10:57:27 -070050#include "gc/reference_processor.h"
Mathieu Chartier590fee92013-09-13 13:46:47 -070051#include "gc/space/bump_pointer_space.h"
Hiroshi Yamauchi50b29282013-07-30 13:58:37 -070052#include "gc/space/dlmalloc_space-inl.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070053#include "gc/space/image_space.h"
54#include "gc/space/large_object_space.h"
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -080055#include "gc/space/region_space.h"
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -070056#include "gc/space/rosalloc_space-inl.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070057#include "gc/space/space-inl.h"
Mathieu Chartiera1602f22014-01-13 17:19:19 -080058#include "gc/space/zygote_space.h"
Mathieu Chartiera5eae692014-12-17 17:56:03 -080059#include "gc/task_processor.h"
Mathieu Chartierd8891782014-03-02 13:28:37 -080060#include "entrypoints/quick/quick_alloc_entrypoints.h"
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -070061#include "heap-inl.h"
Brian Carlstrom9cff8e12011-08-18 16:47:29 -070062#include "image.h"
Mathieu Chartiereb175f72014-10-31 11:49:27 -070063#include "intern_table.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080064#include "mirror/class-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080065#include "mirror/object-inl.h"
66#include "mirror/object_array-inl.h"
Mathieu Chartier8fa2dad2014-03-13 12:22:56 -070067#include "mirror/reference-inl.h"
Brian Carlstrom5643b782012-02-05 12:32:53 -080068#include "os.h"
Ian Rogers53b8b092014-03-13 23:45:53 -070069#include "reflection.h"
Mathieu Chartier0de9f732013-11-22 17:58:48 -080070#include "runtime.h"
Mathieu Chartier7664f5c2012-06-08 18:15:32 -070071#include "ScopedLocalRef.h"
Ian Rogers00f7d0e2012-07-19 15:28:27 -070072#include "scoped_thread_state_change.h"
Mathieu Chartiereb8167a2014-05-07 15:43:14 -070073#include "handle_scope-inl.h"
Elliott Hughes8d768a92011-09-14 16:35:25 -070074#include "thread_list.h"
Elliott Hugheseac76672012-05-24 21:56:51 -070075#include "well_known_classes.h"
Carl Shapiro69759ea2011-07-21 18:13:35 -070076
77namespace art {
Mathieu Chartier50482232013-11-21 11:48:14 -080078
Ian Rogers1d54e732013-05-02 21:10:01 -070079namespace gc {
Carl Shapiro69759ea2011-07-21 18:13:35 -070080
Mathieu Chartier91e30632014-03-25 15:58:50 -070081static constexpr size_t kCollectorTransitionStressIterations = 0;
82static constexpr size_t kCollectorTransitionStressWait = 10 * 1000; // Microseconds
Ian Rogers1d54e732013-05-02 21:10:01 -070083// Minimum amount of remaining bytes before a concurrent GC is triggered.
Mathieu Chartier720ef762013-08-17 14:46:54 -070084static constexpr size_t kMinConcurrentRemainingBytes = 128 * KB;
Mathieu Chartier74762802014-01-24 10:21:35 -080085static constexpr size_t kMaxConcurrentRemainingBytes = 512 * KB;
Mathieu Chartierdf86d1f2014-04-08 13:44:04 -070086// Sticky GC throughput adjustment, divided by 4. Increasing this causes sticky GC to occur more
Mathieu Chartier73d1e172014-04-11 17:53:48 -070087// relative to partial/full GC. This may be desirable since sticky GCs interfere less with mutator
Mathieu Chartierdf86d1f2014-04-08 13:44:04 -070088// threads (lower pauses, use less memory bandwidth).
Mathieu Chartier73d1e172014-04-11 17:53:48 -070089static constexpr double kStickyGcThroughputAdjustment = 1.0;
Mathieu Chartierc1790162014-05-23 10:54:50 -070090// Whether or not we compact the zygote in PreZygoteFork.
Mathieu Chartier31f44142014-04-08 14:40:03 -070091static constexpr bool kCompactZygote = kMovingCollector;
Mathieu Chartierc1790162014-05-23 10:54:50 -070092// How many reserve entries are at the end of the allocation stack, these are only needed if the
93// allocation stack overflows.
94static constexpr size_t kAllocationStackReserveSize = 1024;
95// Default mark stack size in bytes.
96static const size_t kDefaultMarkStackSize = 64 * KB;
Zuo Wangf37a88b2014-07-10 04:26:41 -070097// Define space name.
98static const char* kDlMallocSpaceName[2] = {"main dlmalloc space", "main dlmalloc space 1"};
99static const char* kRosAllocSpaceName[2] = {"main rosalloc space", "main rosalloc space 1"};
100static const char* kMemMapSpaceName[2] = {"main space", "main space 1"};
Mathieu Chartier7247af52014-11-19 10:51:42 -0800101static const char* kNonMovingSpaceName = "non moving space";
102static const char* kZygoteSpaceName = "zygote space";
Mathieu Chartierb363f662014-07-16 13:28:58 -0700103static constexpr size_t kGSSBumpPointerSpaceCapacity = 32 * MB;
Mathieu Chartier95a505c2014-12-10 18:45:30 -0800104static constexpr bool kGCALotMode = false;
105// GC alot mode uses a small allocation stack to stress test a lot of GC.
106static constexpr size_t kGcAlotAllocationStackSize = 4 * KB /
107 sizeof(mirror::HeapReference<mirror::Object>);
108// Verify objet has a small allocation stack size since searching the allocation stack is slow.
109static constexpr size_t kVerifyObjectAllocationStackSize = 16 * KB /
110 sizeof(mirror::HeapReference<mirror::Object>);
111static constexpr size_t kDefaultAllocationStackSize = 8 * MB /
112 sizeof(mirror::HeapReference<mirror::Object>);
Mathieu Chartierb5de3bb2015-06-05 13:21:05 -0700113// System.runFinalization can deadlock with native allocations, to deal with this, we have a
114// timeout on how long we wait for finalizers to run. b/21544853
115static constexpr uint64_t kNativeAllocationFinalizeTimeout = MsToNs(250u);
Mathieu Chartier0051be62012-10-12 17:47:11 -0700116
Mathieu Chartiera4f6af92015-08-11 17:35:25 -0700117Heap::Heap(size_t initial_size,
118 size_t growth_limit,
119 size_t min_free,
120 size_t max_free,
121 double target_utilization,
122 double foreground_heap_growth_multiplier,
123 size_t capacity,
124 size_t non_moving_space_capacity,
125 const std::string& image_file_name,
126 const InstructionSet image_instruction_set,
127 CollectorType foreground_collector_type,
Mathieu Chartier2dbe6272014-09-16 10:43:23 -0700128 CollectorType background_collector_type,
Mathieu Chartiera4f6af92015-08-11 17:35:25 -0700129 space::LargeObjectSpaceType large_object_space_type,
130 size_t large_object_threshold,
131 size_t parallel_gc_threads,
132 size_t conc_gc_threads,
133 bool low_memory_mode,
134 size_t long_pause_log_threshold,
135 size_t long_gc_log_threshold,
136 bool ignore_max_footprint,
137 bool use_tlab,
138 bool verify_pre_gc_heap,
139 bool verify_pre_sweeping_heap,
140 bool verify_post_gc_heap,
141 bool verify_pre_gc_rosalloc,
142 bool verify_pre_sweeping_rosalloc,
143 bool verify_post_gc_rosalloc,
144 bool gc_stress_mode,
Mathieu Chartier31000802015-06-14 14:14:37 -0700145 bool use_homogeneous_space_compaction_for_oom,
Zuo Wangf37a88b2014-07-10 04:26:41 -0700146 uint64_t min_interval_homogeneous_space_compaction_by_oom)
Mathieu Chartiercbb2d202013-11-14 17:45:16 -0800147 : non_moving_space_(nullptr),
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800148 rosalloc_space_(nullptr),
149 dlmalloc_space_(nullptr),
Mathieu Chartierfc5b5282014-01-09 16:15:36 -0800150 main_space_(nullptr),
Mathieu Chartier7bf82af2013-12-06 16:51:45 -0800151 collector_type_(kCollectorTypeNone),
Mathieu Chartier31f44142014-04-08 14:40:03 -0700152 foreground_collector_type_(foreground_collector_type),
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800153 background_collector_type_(background_collector_type),
Mathieu Chartier31f44142014-04-08 14:40:03 -0700154 desired_collector_type_(foreground_collector_type_),
Mathieu Chartiera5eae692014-12-17 17:56:03 -0800155 pending_task_lock_(nullptr),
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700156 parallel_gc_threads_(parallel_gc_threads),
157 conc_gc_threads_(conc_gc_threads),
Mathieu Chartiere0a53e92013-08-05 10:17:40 -0700158 low_memory_mode_(low_memory_mode),
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700159 long_pause_log_threshold_(long_pause_log_threshold),
160 long_gc_log_threshold_(long_gc_log_threshold),
161 ignore_max_footprint_(ignore_max_footprint),
Mathieu Chartier8e4a96d2014-05-21 10:44:32 -0700162 zygote_creation_lock_("zygote creation lock", kZygoteCreationLock),
Mathieu Chartiere4cab172014-08-19 18:24:04 -0700163 zygote_space_(nullptr),
Mathieu Chartier2dbe6272014-09-16 10:43:23 -0700164 large_object_threshold_(large_object_threshold),
Hiroshi Yamauchi76f55b02015-08-21 16:10:39 -0700165 disable_thread_flip_count_(0),
166 thread_flip_running_(false),
Mathieu Chartierd5a89ee2014-01-31 09:55:13 -0800167 collector_type_running_(kCollectorTypeNone),
Ian Rogers1d54e732013-05-02 21:10:01 -0700168 last_gc_type_(collector::kGcTypeNone),
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -0700169 next_gc_type_(collector::kGcTypePartial),
Mathieu Chartier80de7a62012-11-27 17:21:50 -0800170 capacity_(capacity),
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700171 growth_limit_(growth_limit),
Mathieu Chartier0051be62012-10-12 17:47:11 -0700172 max_allowed_footprint_(initial_size),
Mathieu Chartier987ccff2013-07-08 11:05:21 -0700173 native_footprint_gc_watermark_(initial_size),
Mathieu Chartier590fee92013-09-13 13:46:47 -0700174 native_need_to_run_finalization_(false),
Mathieu Chartierca2a24d2013-11-25 15:12:12 -0800175 // Initially assume we perceive jank in case the process state is never updated.
176 process_state_(kProcessStateJankPerceptible),
Mathieu Chartier7bf82af2013-12-06 16:51:45 -0800177 concurrent_start_bytes_(std::numeric_limits<size_t>::max()),
Ian Rogers1d54e732013-05-02 21:10:01 -0700178 total_bytes_freed_ever_(0),
179 total_objects_freed_ever_(0),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800180 num_bytes_allocated_(0),
Mathieu Chartier987ccff2013-07-08 11:05:21 -0700181 native_bytes_allocated_(0),
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -0700182 num_bytes_freed_revoke_(0),
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700183 verify_missing_card_marks_(false),
184 verify_system_weaks_(false),
Mathieu Chartier938a03b2014-01-16 15:10:31 -0800185 verify_pre_gc_heap_(verify_pre_gc_heap),
Mathieu Chartier6f365cc2014-04-23 12:42:27 -0700186 verify_pre_sweeping_heap_(verify_pre_sweeping_heap),
Mathieu Chartier938a03b2014-01-16 15:10:31 -0800187 verify_post_gc_heap_(verify_post_gc_heap),
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700188 verify_mod_union_table_(false),
Hiroshi Yamauchia4adbfd2014-02-04 18:12:17 -0800189 verify_pre_gc_rosalloc_(verify_pre_gc_rosalloc),
Mathieu Chartier6f365cc2014-04-23 12:42:27 -0700190 verify_pre_sweeping_rosalloc_(verify_pre_sweeping_rosalloc),
Hiroshi Yamauchia4adbfd2014-02-04 18:12:17 -0800191 verify_post_gc_rosalloc_(verify_post_gc_rosalloc),
Mathieu Chartier31000802015-06-14 14:14:37 -0700192 gc_stress_mode_(gc_stress_mode),
Mathieu Chartier0418ae22013-07-31 13:35:46 -0700193 /* For GC a lot mode, we limit the allocations stacks to be kGcAlotInterval allocations. This
194 * causes a lot of GC since we do a GC for alloc whenever the stack is full. When heap
195 * verification is enabled, we limit the size of allocation stacks to speed up their
196 * searching.
197 */
Mathieu Chartier95a505c2014-12-10 18:45:30 -0800198 max_allocation_stack_size_(kGCALotMode ? kGcAlotAllocationStackSize
199 : (kVerifyObjectSupport > kVerifyObjectModeFast) ? kVerifyObjectAllocationStackSize :
200 kDefaultAllocationStackSize),
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800201 current_allocator_(kAllocatorTypeDlMalloc),
202 current_non_moving_allocator_(kAllocatorTypeNonMoving),
Mathieu Chartier590fee92013-09-13 13:46:47 -0700203 bump_pointer_space_(nullptr),
204 temp_space_(nullptr),
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800205 region_space_(nullptr),
Mathieu Chartier0051be62012-10-12 17:47:11 -0700206 min_free_(min_free),
207 max_free_(max_free),
208 target_utilization_(target_utilization),
Mathieu Chartier2f8da3e2014-04-15 15:37:02 -0700209 foreground_heap_growth_multiplier_(foreground_heap_growth_multiplier),
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700210 total_wait_time_(0),
Mathieu Chartier4e305412014-02-19 10:54:44 -0800211 verify_object_mode_(kVerifyObjectModeDisabled),
Mathieu Chartier1d27b342014-01-28 12:51:09 -0800212 disable_moving_gc_count_(0),
Evgenii Stepanov1e133742015-05-20 12:30:59 -0700213 is_running_on_memory_tool_(Runtime::Current()->IsRunningOnMemoryTool()),
Zuo Wangf37a88b2014-07-10 04:26:41 -0700214 use_tlab_(use_tlab),
215 main_space_backup_(nullptr),
Mathieu Chartierb363f662014-07-16 13:28:58 -0700216 min_interval_homogeneous_space_compaction_by_oom_(
217 min_interval_homogeneous_space_compaction_by_oom),
Zuo Wangf37a88b2014-07-10 04:26:41 -0700218 last_time_homogeneous_space_compaction_by_oom_(NanoTime()),
Mathieu Chartiera5eae692014-12-17 17:56:03 -0800219 pending_collector_transition_(nullptr),
220 pending_heap_trim_(nullptr),
Hiroshi Yamauchia1c9f012015-04-02 10:18:12 -0700221 use_homogeneous_space_compaction_for_oom_(use_homogeneous_space_compaction_for_oom),
222 running_collection_is_blocking_(false),
223 blocking_gc_count_(0U),
224 blocking_gc_time_(0U),
225 last_update_time_gc_count_rate_histograms_( // Round down by the window duration.
226 (NanoTime() / kGcCountRateHistogramWindowDuration) * kGcCountRateHistogramWindowDuration),
227 gc_count_last_window_(0U),
228 blocking_gc_count_last_window_(0U),
229 gc_count_rate_histogram_("gc count rate histogram", 1U, kGcCountRateMaxBucketCount),
230 blocking_gc_count_rate_histogram_("blocking gc count rate histogram", 1U,
Man Cao8c2ff642015-05-27 17:25:30 -0700231 kGcCountRateMaxBucketCount),
Mathieu Chartier31000802015-06-14 14:14:37 -0700232 alloc_tracking_enabled_(false),
233 backtrace_lock_(nullptr),
234 seen_backtrace_count_(0u),
Mathieu Chartier51168372015-08-12 16:40:32 -0700235 unique_backtrace_count_(0u),
Jeff Haodcdc85b2015-12-04 14:06:18 -0800236 gc_disabled_for_shutdown_(false) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800237 if (VLOG_IS_ON(heap) || VLOG_IS_ON(startup)) {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800238 LOG(INFO) << "Heap() entering";
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700239 }
Mathieu Chartier31000802015-06-14 14:14:37 -0700240 Runtime* const runtime = Runtime::Current();
Mathieu Chartier50482232013-11-21 11:48:14 -0800241 // If we aren't the zygote, switch to the default non zygote allocator. This may update the
242 // entrypoints.
Mathieu Chartier31000802015-06-14 14:14:37 -0700243 const bool is_zygote = runtime->IsZygote();
Mathieu Chartier8e219ae2014-08-19 14:29:46 -0700244 if (!is_zygote) {
Mathieu Chartier31f44142014-04-08 14:40:03 -0700245 // Background compaction is currently not supported for command line runs.
246 if (background_collector_type_ != foreground_collector_type_) {
Mathieu Chartier52ba1992014-05-07 14:39:21 -0700247 VLOG(heap) << "Disabling background compaction for non zygote";
Mathieu Chartier31f44142014-04-08 14:40:03 -0700248 background_collector_type_ = foreground_collector_type_;
Mathieu Chartierbd0a6532014-02-27 11:14:21 -0800249 }
Mathieu Chartier50482232013-11-21 11:48:14 -0800250 }
Mathieu Chartiera5f9de02014-02-28 16:48:42 -0800251 ChangeCollector(desired_collector_type_);
Ian Rogers1d54e732013-05-02 21:10:01 -0700252 live_bitmap_.reset(new accounting::HeapBitmap(this));
253 mark_bitmap_.reset(new accounting::HeapBitmap(this));
Ian Rogers30fab402012-01-23 15:43:46 -0800254 // Requested begin for the alloc space, to follow the mapped image and oat files
Ian Rogers13735952014-10-08 12:43:28 -0700255 uint8_t* requested_alloc_space_begin = nullptr;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800256 if (foreground_collector_type_ == kCollectorTypeCC) {
257 // Need to use a low address so that we can allocate a contiguous
258 // 2 * Xmx space when there's no image (dex2oat for target).
259 CHECK_GE(300 * MB, non_moving_space_capacity);
260 requested_alloc_space_begin = reinterpret_cast<uint8_t*>(300 * MB) - non_moving_space_capacity;
261 }
Jeff Haodcdc85b2015-12-04 14:06:18 -0800262
263 // Load image space(s).
Brian Carlstrom5643b782012-02-05 12:32:53 -0800264 if (!image_file_name.empty()) {
Jeff Haodcdc85b2015-12-04 14:06:18 -0800265 // For code reuse, handle this like a work queue.
266 std::vector<std::string> image_file_names;
267 image_file_names.push_back(image_file_name);
Andreas Gampe8994a042015-12-30 19:03:17 +0000268 // The loaded spaces. Secondary images may fail to load, in which case we need to remove
269 // already added spaces.
270 std::vector<space::Space*> added_image_spaces;
Jeff Haodcdc85b2015-12-04 14:06:18 -0800271
272 for (size_t index = 0; index < image_file_names.size(); ++index) {
273 std::string& image_name = image_file_names[index];
274 ATRACE_BEGIN("ImageSpace::Create");
275 std::string error_msg;
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800276 space::ImageSpace* boot_image_space = space::ImageSpace::CreateBootImage(
277 image_name.c_str(),
278 image_instruction_set,
279 index > 0,
280 &error_msg);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800281 ATRACE_END();
282 if (boot_image_space != nullptr) {
283 AddSpace(boot_image_space);
Andreas Gampe8994a042015-12-30 19:03:17 +0000284 added_image_spaces.push_back(boot_image_space);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800285 // Oat files referenced by image files immediately follow them in memory, ensure alloc space
286 // isn't going to get in the middle
287 uint8_t* oat_file_end_addr = boot_image_space->GetImageHeader().GetOatFileEnd();
288 CHECK_GT(oat_file_end_addr, boot_image_space->End());
289 requested_alloc_space_begin = AlignUp(oat_file_end_addr, kPageSize);
290 boot_image_spaces_.push_back(boot_image_space);
291
292 if (index == 0) {
293 // If this was the first space, check whether there are more images to load.
294 const OatFile* boot_oat_file = boot_image_space->GetOatFile();
295 if (boot_oat_file == nullptr) {
296 continue;
297 }
298
299 const OatHeader& boot_oat_header = boot_oat_file->GetOatHeader();
300 const char* boot_classpath =
301 boot_oat_header.GetStoreValueByKey(OatHeader::kBootClassPath);
302 if (boot_classpath == nullptr) {
303 continue;
304 }
305
Andreas Gampe8994a042015-12-30 19:03:17 +0000306 space::ImageSpace::CreateMultiImageLocations(image_file_name,
307 boot_classpath,
308 &image_file_names);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800309 }
310 } else {
311 LOG(ERROR) << "Could not create image space with image file '" << image_file_name << "'. "
312 << "Attempting to fall back to imageless running. Error was: " << error_msg
313 << "\nAttempted image: " << image_name;
Andreas Gampe8994a042015-12-30 19:03:17 +0000314 // Remove already loaded spaces.
315 for (space::Space* loaded_space : added_image_spaces) {
316 RemoveSpace(loaded_space);
317 }
Jeff Haodcdc85b2015-12-04 14:06:18 -0800318 break;
319 }
Alex Light64ad14d2014-08-19 14:23:13 -0700320 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700321 }
Zuo Wangf37a88b2014-07-10 04:26:41 -0700322 /*
323 requested_alloc_space_begin -> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
Mathieu Chartier6a7824d2014-08-22 14:53:04 -0700324 +- nonmoving space (non_moving_space_capacity)+-
Zuo Wangf37a88b2014-07-10 04:26:41 -0700325 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
Mathieu Chartier8e219ae2014-08-19 14:29:46 -0700326 +-????????????????????????????????????????????+-
327 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
Mathieu Chartierb363f662014-07-16 13:28:58 -0700328 +-main alloc space / bump space 1 (capacity_) +-
Zuo Wangf37a88b2014-07-10 04:26:41 -0700329 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
Mathieu Chartierb363f662014-07-16 13:28:58 -0700330 +-????????????????????????????????????????????+-
331 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
332 +-main alloc space2 / bump space 2 (capacity_)+-
Zuo Wangf37a88b2014-07-10 04:26:41 -0700333 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
334 */
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800335 // We don't have hspace compaction enabled with GSS or CC.
336 if (foreground_collector_type_ == kCollectorTypeGSS ||
337 foreground_collector_type_ == kCollectorTypeCC) {
Hiroshi Yamauchi20ed5af2014-11-17 18:05:44 -0800338 use_homogeneous_space_compaction_for_oom_ = false;
339 }
Mathieu Chartierb363f662014-07-16 13:28:58 -0700340 bool support_homogeneous_space_compaction =
Mathieu Chartier0deeb812014-08-21 18:28:20 -0700341 background_collector_type_ == gc::kCollectorTypeHomogeneousSpaceCompact ||
Hiroshi Yamauchi20ed5af2014-11-17 18:05:44 -0800342 use_homogeneous_space_compaction_for_oom_;
Mathieu Chartierb363f662014-07-16 13:28:58 -0700343 // We may use the same space the main space for the non moving space if we don't need to compact
344 // from the main space.
345 // This is not the case if we support homogeneous compaction or have a moving background
346 // collector type.
Mathieu Chartierb363f662014-07-16 13:28:58 -0700347 bool separate_non_moving_space = is_zygote ||
348 support_homogeneous_space_compaction || IsMovingGc(foreground_collector_type_) ||
349 IsMovingGc(background_collector_type_);
350 if (foreground_collector_type == kCollectorTypeGSS) {
351 separate_non_moving_space = false;
352 }
353 std::unique_ptr<MemMap> main_mem_map_1;
354 std::unique_ptr<MemMap> main_mem_map_2;
Ian Rogers13735952014-10-08 12:43:28 -0700355 uint8_t* request_begin = requested_alloc_space_begin;
Mathieu Chartierb363f662014-07-16 13:28:58 -0700356 if (request_begin != nullptr && separate_non_moving_space) {
Mathieu Chartier6a7824d2014-08-22 14:53:04 -0700357 request_begin += non_moving_space_capacity;
Mathieu Chartierb363f662014-07-16 13:28:58 -0700358 }
359 std::string error_str;
360 std::unique_ptr<MemMap> non_moving_space_mem_map;
Richard Uhler054a0782015-04-07 10:56:50 -0700361 ATRACE_BEGIN("Create heap maps");
Mathieu Chartierb363f662014-07-16 13:28:58 -0700362 if (separate_non_moving_space) {
Mathieu Chartier7247af52014-11-19 10:51:42 -0800363 // If we are the zygote, the non moving space becomes the zygote space when we run
364 // PreZygoteFork the first time. In this case, call the map "zygote space" since we can't
365 // rename the mem map later.
366 const char* space_name = is_zygote ? kZygoteSpaceName: kNonMovingSpaceName;
Mathieu Chartierb363f662014-07-16 13:28:58 -0700367 // Reserve the non moving mem map before the other two since it needs to be at a specific
368 // address.
369 non_moving_space_mem_map.reset(
Mathieu Chartier7247af52014-11-19 10:51:42 -0800370 MemMap::MapAnonymous(space_name, requested_alloc_space_begin,
Vladimir Marko5c42c292015-02-25 12:02:49 +0000371 non_moving_space_capacity, PROT_READ | PROT_WRITE, true, false,
372 &error_str));
Mathieu Chartierb363f662014-07-16 13:28:58 -0700373 CHECK(non_moving_space_mem_map != nullptr) << error_str;
Mathieu Chartierc44ce2e2014-08-25 16:32:41 -0700374 // Try to reserve virtual memory at a lower address if we have a separate non moving space.
Ian Rogers13735952014-10-08 12:43:28 -0700375 request_begin = reinterpret_cast<uint8_t*>(300 * MB);
Mathieu Chartierb363f662014-07-16 13:28:58 -0700376 }
Hiroshi Yamauchi3dbf2342015-03-17 16:01:11 -0700377 // Attempt to create 2 mem maps at or after the requested begin.
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800378 if (foreground_collector_type_ != kCollectorTypeCC) {
Mathieu Chartier966f5332016-01-25 12:53:03 -0800379 if (separate_non_moving_space || !is_zygote) {
380 main_mem_map_1.reset(MapAnonymousPreferredAddress(kMemMapSpaceName[0],
381 request_begin,
382 capacity_,
383 &error_str));
Hiroshi Yamauchi3dbf2342015-03-17 16:01:11 -0700384 } else {
Mathieu Chartier966f5332016-01-25 12:53:03 -0800385 // If no separate non-moving space and we are the zygote, the main space must come right
386 // after the image space to avoid a gap. This is required since we want the zygote space to
387 // be adjacent to the image space.
Hiroshi Yamauchi3dbf2342015-03-17 16:01:11 -0700388 main_mem_map_1.reset(MemMap::MapAnonymous(kMemMapSpaceName[0], request_begin, capacity_,
389 PROT_READ | PROT_WRITE, true, false,
390 &error_str));
391 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800392 CHECK(main_mem_map_1.get() != nullptr) << error_str;
393 }
Mathieu Chartierb363f662014-07-16 13:28:58 -0700394 if (support_homogeneous_space_compaction ||
395 background_collector_type_ == kCollectorTypeSS ||
396 foreground_collector_type_ == kCollectorTypeSS) {
397 main_mem_map_2.reset(MapAnonymousPreferredAddress(kMemMapSpaceName[1], main_mem_map_1->End(),
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700398 capacity_, &error_str));
Mathieu Chartierb363f662014-07-16 13:28:58 -0700399 CHECK(main_mem_map_2.get() != nullptr) << error_str;
400 }
Richard Uhler054a0782015-04-07 10:56:50 -0700401 ATRACE_END();
402 ATRACE_BEGIN("Create spaces");
Mathieu Chartierb363f662014-07-16 13:28:58 -0700403 // Create the non moving space first so that bitmaps don't take up the address range.
404 if (separate_non_moving_space) {
Mathieu Chartier31f44142014-04-08 14:40:03 -0700405 // Non moving space is always dlmalloc since we currently don't have support for multiple
Zuo Wangf37a88b2014-07-10 04:26:41 -0700406 // active rosalloc spaces.
Mathieu Chartierb363f662014-07-16 13:28:58 -0700407 const size_t size = non_moving_space_mem_map->Size();
408 non_moving_space_ = space::DlMallocSpace::CreateFromMemMap(
Mathieu Chartier6a7824d2014-08-22 14:53:04 -0700409 non_moving_space_mem_map.release(), "zygote / non moving space", kDefaultStartingSize,
Mathieu Chartierb363f662014-07-16 13:28:58 -0700410 initial_size, size, size, false);
Mathieu Chartier78408882014-04-11 18:06:01 -0700411 non_moving_space_->SetFootprintLimit(non_moving_space_->Capacity());
Mathieu Chartierb363f662014-07-16 13:28:58 -0700412 CHECK(non_moving_space_ != nullptr) << "Failed creating non moving space "
413 << requested_alloc_space_begin;
414 AddSpace(non_moving_space_);
415 }
416 // Create other spaces based on whether or not we have a moving GC.
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800417 if (foreground_collector_type_ == kCollectorTypeCC) {
418 region_space_ = space::RegionSpace::Create("Region space", capacity_ * 2, request_begin);
419 AddSpace(region_space_);
Richard Uhler054a0782015-04-07 10:56:50 -0700420 } else if (IsMovingGc(foreground_collector_type_) &&
421 foreground_collector_type_ != kCollectorTypeGSS) {
Mathieu Chartierb363f662014-07-16 13:28:58 -0700422 // Create bump pointer spaces.
423 // We only to create the bump pointer if the foreground collector is a compacting GC.
424 // TODO: Place bump-pointer spaces somewhere to minimize size of card table.
425 bump_pointer_space_ = space::BumpPointerSpace::CreateFromMemMap("Bump pointer space 1",
426 main_mem_map_1.release());
427 CHECK(bump_pointer_space_ != nullptr) << "Failed to create bump pointer space";
428 AddSpace(bump_pointer_space_);
429 temp_space_ = space::BumpPointerSpace::CreateFromMemMap("Bump pointer space 2",
430 main_mem_map_2.release());
431 CHECK(temp_space_ != nullptr) << "Failed to create bump pointer space";
432 AddSpace(temp_space_);
433 CHECK(separate_non_moving_space);
Hiroshi Yamauchi5ccd4982014-03-11 12:19:04 -0700434 } else {
Mathieu Chartierb363f662014-07-16 13:28:58 -0700435 CreateMainMallocSpace(main_mem_map_1.release(), initial_size, growth_limit_, capacity_);
436 CHECK(main_space_ != nullptr);
437 AddSpace(main_space_);
438 if (!separate_non_moving_space) {
Zuo Wangf37a88b2014-07-10 04:26:41 -0700439 non_moving_space_ = main_space_;
Mathieu Chartierb363f662014-07-16 13:28:58 -0700440 CHECK(!non_moving_space_->CanMoveObjects());
441 }
442 if (foreground_collector_type_ == kCollectorTypeGSS) {
443 CHECK_EQ(foreground_collector_type_, background_collector_type_);
444 // Create bump pointer spaces instead of a backup space.
445 main_mem_map_2.release();
446 bump_pointer_space_ = space::BumpPointerSpace::Create("Bump pointer space 1",
447 kGSSBumpPointerSpaceCapacity, nullptr);
448 CHECK(bump_pointer_space_ != nullptr);
449 AddSpace(bump_pointer_space_);
450 temp_space_ = space::BumpPointerSpace::Create("Bump pointer space 2",
451 kGSSBumpPointerSpaceCapacity, nullptr);
452 CHECK(temp_space_ != nullptr);
453 AddSpace(temp_space_);
454 } else if (main_mem_map_2.get() != nullptr) {
455 const char* name = kUseRosAlloc ? kRosAllocSpaceName[1] : kDlMallocSpaceName[1];
456 main_space_backup_.reset(CreateMallocSpaceFromMemMap(main_mem_map_2.release(), initial_size,
457 growth_limit_, capacity_, name, true));
458 CHECK(main_space_backup_.get() != nullptr);
459 // Add the space so its accounted for in the heap_begin and heap_end.
460 AddSpace(main_space_backup_.get());
Zuo Wangf37a88b2014-07-10 04:26:41 -0700461 }
Hiroshi Yamauchi5ccd4982014-03-11 12:19:04 -0700462 }
Mathieu Chartier31f44142014-04-08 14:40:03 -0700463 CHECK(non_moving_space_ != nullptr);
Mathieu Chartierb363f662014-07-16 13:28:58 -0700464 CHECK(!non_moving_space_->CanMoveObjects());
Mathieu Chartiereb5710e2013-07-25 15:19:42 -0700465 // Allocate the large object space.
Igor Murashkinaaebaa02015-01-26 10:55:53 -0800466 if (large_object_space_type == space::LargeObjectSpaceType::kFreeList) {
Mathieu Chartier2dbe6272014-09-16 10:43:23 -0700467 large_object_space_ = space::FreeListSpace::Create("free list large object space", nullptr,
468 capacity_);
469 CHECK(large_object_space_ != nullptr) << "Failed to create large object space";
Igor Murashkinaaebaa02015-01-26 10:55:53 -0800470 } else if (large_object_space_type == space::LargeObjectSpaceType::kMap) {
Mathieu Chartier2dbe6272014-09-16 10:43:23 -0700471 large_object_space_ = space::LargeObjectMapSpace::Create("mem map large object space");
472 CHECK(large_object_space_ != nullptr) << "Failed to create large object space";
Mathieu Chartiereb5710e2013-07-25 15:19:42 -0700473 } else {
Mathieu Chartier2dbe6272014-09-16 10:43:23 -0700474 // Disable the large object space by making the cutoff excessively large.
475 large_object_threshold_ = std::numeric_limits<size_t>::max();
476 large_object_space_ = nullptr;
Mathieu Chartiereb5710e2013-07-25 15:19:42 -0700477 }
Mathieu Chartier2dbe6272014-09-16 10:43:23 -0700478 if (large_object_space_ != nullptr) {
479 AddSpace(large_object_space_);
480 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700481 // Compute heap capacity. Continuous spaces are sorted in order of Begin().
Mathieu Chartier590fee92013-09-13 13:46:47 -0700482 CHECK(!continuous_spaces_.empty());
483 // Relies on the spaces being sorted.
Ian Rogers13735952014-10-08 12:43:28 -0700484 uint8_t* heap_begin = continuous_spaces_.front()->Begin();
485 uint8_t* heap_end = continuous_spaces_.back()->Limit();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700486 size_t heap_capacity = heap_end - heap_begin;
Mathieu Chartierb363f662014-07-16 13:28:58 -0700487 // Remove the main backup space since it slows down the GC to have unused extra spaces.
Mathieu Chartier0310da52014-12-01 13:40:48 -0800488 // TODO: Avoid needing to do this.
Mathieu Chartierb363f662014-07-16 13:28:58 -0700489 if (main_space_backup_.get() != nullptr) {
490 RemoveSpace(main_space_backup_.get());
491 }
Richard Uhler054a0782015-04-07 10:56:50 -0700492 ATRACE_END();
Elliott Hughes6c9c06d2011-11-07 16:43:47 -0800493 // Allocate the card table.
Richard Uhler054a0782015-04-07 10:56:50 -0700494 ATRACE_BEGIN("Create card table");
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800495 // We currently don't support dynamically resizing the card table.
496 // Since we don't know where in the low_4gb the app image will be located, make the card table
497 // cover the whole low_4gb. TODO: Extend the card table in AddSpace.
498 UNUSED(heap_capacity);
499 // Start at 64 KB, we can be sure there are no spaces mapped this low since the address range is
500 // reserved by the kernel.
501 static constexpr size_t kMinHeapAddress = 4 * KB;
502 card_table_.reset(accounting::CardTable::Create(reinterpret_cast<uint8_t*>(kMinHeapAddress),
503 4 * GB - kMinHeapAddress));
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700504 CHECK(card_table_.get() != nullptr) << "Failed to create card table";
Richard Uhler054a0782015-04-07 10:56:50 -0700505 ATRACE_END();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800506 if (foreground_collector_type_ == kCollectorTypeCC && kUseTableLookupReadBarrier) {
507 rb_table_.reset(new accounting::ReadBarrierTable());
508 DCHECK(rb_table_->IsAllCleared());
509 }
Jeff Haodcdc85b2015-12-04 14:06:18 -0800510 if (HasBootImageSpace()) {
Mathieu Chartier4858a932015-01-23 13:18:53 -0800511 // Don't add the image mod union table if we are running without an image, this can crash if
512 // we use the CardCache implementation.
Jeff Haodcdc85b2015-12-04 14:06:18 -0800513 for (space::ImageSpace* image_space : GetBootImageSpaces()) {
514 accounting::ModUnionTable* mod_union_table = new accounting::ModUnionTableToZygoteAllocspace(
515 "Image mod-union table", this, image_space);
516 CHECK(mod_union_table != nullptr) << "Failed to create image mod-union table";
517 AddModUnionTable(mod_union_table);
518 }
Mathieu Chartier4858a932015-01-23 13:18:53 -0800519 }
Mathieu Chartier96bcd452014-06-17 09:50:02 -0700520 if (collector::SemiSpace::kUseRememberedSet && non_moving_space_ != main_space_) {
Hiroshi Yamauchi38e68e92014-03-07 13:59:08 -0800521 accounting::RememberedSet* non_moving_space_rem_set =
522 new accounting::RememberedSet("Non-moving space remembered set", this, non_moving_space_);
523 CHECK(non_moving_space_rem_set != nullptr) << "Failed to create non-moving space remembered set";
524 AddRememberedSet(non_moving_space_rem_set);
525 }
Mathieu Chartierb363f662014-07-16 13:28:58 -0700526 // TODO: Count objects in the image space here?
Ian Rogers3e5cf302014-05-20 16:40:37 -0700527 num_bytes_allocated_.StoreRelaxed(0);
Mathieu Chartierc1790162014-05-23 10:54:50 -0700528 mark_stack_.reset(accounting::ObjectStack::Create("mark stack", kDefaultMarkStackSize,
529 kDefaultMarkStackSize));
530 const size_t alloc_stack_capacity = max_allocation_stack_size_ + kAllocationStackReserveSize;
531 allocation_stack_.reset(accounting::ObjectStack::Create(
532 "allocation stack", max_allocation_stack_size_, alloc_stack_capacity));
533 live_stack_.reset(accounting::ObjectStack::Create(
534 "live stack", max_allocation_stack_size_, alloc_stack_capacity));
Mathieu Chartier65db8802012-11-20 12:36:46 -0800535 // It's still too early to take a lock because there are no threads yet, but we can create locks
536 // now. We don't create it earlier to make it clear that you can't use locks during heap
537 // initialization.
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700538 gc_complete_lock_ = new Mutex("GC complete lock");
Ian Rogersc604d732012-10-14 16:09:54 -0700539 gc_complete_cond_.reset(new ConditionVariable("GC complete condition variable",
540 *gc_complete_lock_));
Hiroshi Yamauchi76f55b02015-08-21 16:10:39 -0700541 thread_flip_lock_ = new Mutex("GC thread flip lock");
542 thread_flip_cond_.reset(new ConditionVariable("GC thread flip condition variable",
543 *thread_flip_lock_));
Mathieu Chartiera5eae692014-12-17 17:56:03 -0800544 task_processor_.reset(new TaskProcessor());
Mathieu Chartier3cf22532015-07-09 15:15:09 -0700545 reference_processor_.reset(new ReferenceProcessor());
Mathieu Chartiera5eae692014-12-17 17:56:03 -0800546 pending_task_lock_ = new Mutex("Pending task lock");
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700547 if (ignore_max_footprint_) {
548 SetIdealFootprint(std::numeric_limits<size_t>::max());
Mathieu Chartier590fee92013-09-13 13:46:47 -0700549 concurrent_start_bytes_ = std::numeric_limits<size_t>::max();
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700550 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700551 CHECK_NE(max_allowed_footprint_, 0U);
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800552 // Create our garbage collectors.
Mathieu Chartier50482232013-11-21 11:48:14 -0800553 for (size_t i = 0; i < 2; ++i) {
554 const bool concurrent = i != 0;
Mathieu Chartierdfe30832015-03-06 15:28:34 -0800555 if ((MayUseCollector(kCollectorTypeCMS) && concurrent) ||
556 (MayUseCollector(kCollectorTypeMS) && !concurrent)) {
557 garbage_collectors_.push_back(new collector::MarkSweep(this, concurrent));
558 garbage_collectors_.push_back(new collector::PartialMarkSweep(this, concurrent));
559 garbage_collectors_.push_back(new collector::StickyMarkSweep(this, concurrent));
560 }
Mathieu Chartier50482232013-11-21 11:48:14 -0800561 }
Mathieu Chartier50482232013-11-21 11:48:14 -0800562 if (kMovingCollector) {
Mathieu Chartierdfe30832015-03-06 15:28:34 -0800563 if (MayUseCollector(kCollectorTypeSS) || MayUseCollector(kCollectorTypeGSS) ||
564 MayUseCollector(kCollectorTypeHomogeneousSpaceCompact) ||
565 use_homogeneous_space_compaction_for_oom_) {
566 // TODO: Clean this up.
567 const bool generational = foreground_collector_type_ == kCollectorTypeGSS;
568 semi_space_collector_ = new collector::SemiSpace(this, generational,
569 generational ? "generational" : "");
570 garbage_collectors_.push_back(semi_space_collector_);
571 }
572 if (MayUseCollector(kCollectorTypeCC)) {
573 concurrent_copying_collector_ = new collector::ConcurrentCopying(this);
574 garbage_collectors_.push_back(concurrent_copying_collector_);
575 }
576 if (MayUseCollector(kCollectorTypeMC)) {
577 mark_compact_collector_ = new collector::MarkCompact(this);
578 garbage_collectors_.push_back(mark_compact_collector_);
579 }
Mathieu Chartier0325e622012-09-05 14:22:51 -0700580 }
Jeff Haodcdc85b2015-12-04 14:06:18 -0800581 if (!GetBootImageSpaces().empty() && non_moving_space_ != nullptr &&
Andreas Gampee1cb2982014-08-27 11:01:09 -0700582 (is_zygote || separate_non_moving_space || foreground_collector_type_ == kCollectorTypeGSS)) {
Mathieu Chartierb363f662014-07-16 13:28:58 -0700583 // 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 -0700584 // immune region won't break (eg. due to a large object allocated in the gap). This is only
585 // required when we're the zygote or using GSS.
Mathieu Chartiera06ba052016-01-06 13:51:52 -0800586 // Space with smallest Begin().
587 space::ImageSpace* first_space = nullptr;
588 for (space::ImageSpace* space : boot_image_spaces_) {
589 if (first_space == nullptr || space->Begin() < first_space->Begin()) {
590 first_space = space;
591 }
592 }
593 bool no_gap = MemMap::CheckNoGaps(first_space->GetMemMap(), non_moving_space_->GetMemMap());
Hiroshi Yamauchi3eed93d2014-06-04 11:43:59 -0700594 if (!no_gap) {
David Srbecky5dedb802015-06-17 00:08:02 +0100595 PrintFileToLog("/proc/self/maps", LogSeverity::ERROR);
Vladimir Marko17a924a2015-05-08 15:17:32 +0100596 MemMap::DumpMaps(LOG(ERROR), true);
Mathieu Chartierc7853442015-03-27 14:35:38 -0700597 LOG(FATAL) << "There's a gap between the image space and the non-moving space";
Hiroshi Yamauchi3eed93d2014-06-04 11:43:59 -0700598 }
599 }
Mathieu Chartier31000802015-06-14 14:14:37 -0700600 instrumentation::Instrumentation* const instrumentation = runtime->GetInstrumentation();
601 if (gc_stress_mode_) {
602 backtrace_lock_ = new Mutex("GC complete lock");
603 }
Evgenii Stepanov1e133742015-05-20 12:30:59 -0700604 if (is_running_on_memory_tool_ || gc_stress_mode_) {
Mathieu Chartier31000802015-06-14 14:14:37 -0700605 instrumentation->InstrumentQuickAllocEntryPoints();
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -0700606 }
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800607 if (VLOG_IS_ON(heap) || VLOG_IS_ON(startup)) {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800608 LOG(INFO) << "Heap() exiting";
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700609 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700610}
611
Mathieu Chartiera4f6af92015-08-11 17:35:25 -0700612MemMap* Heap::MapAnonymousPreferredAddress(const char* name,
613 uint8_t* request_begin,
614 size_t capacity,
615 std::string* out_error_str) {
Mathieu Chartierb363f662014-07-16 13:28:58 -0700616 while (true) {
Kyungmin Leeef32b8f2014-10-23 09:32:05 +0900617 MemMap* map = MemMap::MapAnonymous(name, request_begin, capacity,
Vladimir Marko5c42c292015-02-25 12:02:49 +0000618 PROT_READ | PROT_WRITE, true, false, out_error_str);
Mathieu Chartierb363f662014-07-16 13:28:58 -0700619 if (map != nullptr || request_begin == nullptr) {
620 return map;
621 }
622 // Retry a second time with no specified request begin.
623 request_begin = nullptr;
624 }
Mathieu Chartierb363f662014-07-16 13:28:58 -0700625}
626
Mathieu Chartierdfe30832015-03-06 15:28:34 -0800627bool Heap::MayUseCollector(CollectorType type) const {
628 return foreground_collector_type_ == type || background_collector_type_ == type;
629}
630
Mathieu Chartiera4f6af92015-08-11 17:35:25 -0700631space::MallocSpace* Heap::CreateMallocSpaceFromMemMap(MemMap* mem_map,
632 size_t initial_size,
633 size_t growth_limit,
634 size_t capacity,
635 const char* name,
636 bool can_move_objects) {
Zuo Wangf37a88b2014-07-10 04:26:41 -0700637 space::MallocSpace* malloc_space = nullptr;
638 if (kUseRosAlloc) {
639 // Create rosalloc space.
640 malloc_space = space::RosAllocSpace::CreateFromMemMap(mem_map, name, kDefaultStartingSize,
641 initial_size, growth_limit, capacity,
642 low_memory_mode_, can_move_objects);
643 } else {
644 malloc_space = space::DlMallocSpace::CreateFromMemMap(mem_map, name, kDefaultStartingSize,
645 initial_size, growth_limit, capacity,
646 can_move_objects);
647 }
648 if (collector::SemiSpace::kUseRememberedSet) {
649 accounting::RememberedSet* rem_set =
650 new accounting::RememberedSet(std::string(name) + " remembered set", this, malloc_space);
651 CHECK(rem_set != nullptr) << "Failed to create main space remembered set";
652 AddRememberedSet(rem_set);
653 }
654 CHECK(malloc_space != nullptr) << "Failed to create " << name;
655 malloc_space->SetFootprintLimit(malloc_space->Capacity());
656 return malloc_space;
657}
658
Mathieu Chartier31f44142014-04-08 14:40:03 -0700659void Heap::CreateMainMallocSpace(MemMap* mem_map, size_t initial_size, size_t growth_limit,
660 size_t capacity) {
661 // Is background compaction is enabled?
662 bool can_move_objects = IsMovingGc(background_collector_type_) !=
Zuo Wangf37a88b2014-07-10 04:26:41 -0700663 IsMovingGc(foreground_collector_type_) || use_homogeneous_space_compaction_for_oom_;
Mathieu Chartier31f44142014-04-08 14:40:03 -0700664 // If we are the zygote and don't yet have a zygote space, it means that the zygote fork will
665 // happen in the future. If this happens and we have kCompactZygote enabled we wish to compact
666 // from the main space to the zygote space. If background compaction is enabled, always pass in
667 // that we can move objets.
668 if (kCompactZygote && Runtime::Current()->IsZygote() && !can_move_objects) {
669 // After the zygote we want this to be false if we don't have background compaction enabled so
670 // that getting primitive array elements is faster.
Mathieu Chartierb363f662014-07-16 13:28:58 -0700671 // We never have homogeneous compaction with GSS and don't need a space with movable objects.
Mathieu Chartiere4cab172014-08-19 18:24:04 -0700672 can_move_objects = !HasZygoteSpace() && foreground_collector_type_ != kCollectorTypeGSS;
Mathieu Chartier31f44142014-04-08 14:40:03 -0700673 }
Mathieu Chartier96bcd452014-06-17 09:50:02 -0700674 if (collector::SemiSpace::kUseRememberedSet && main_space_ != nullptr) {
675 RemoveRememberedSet(main_space_);
676 }
Zuo Wangf37a88b2014-07-10 04:26:41 -0700677 const char* name = kUseRosAlloc ? kRosAllocSpaceName[0] : kDlMallocSpaceName[0];
678 main_space_ = CreateMallocSpaceFromMemMap(mem_map, initial_size, growth_limit, capacity, name,
679 can_move_objects);
680 SetSpaceAsDefault(main_space_);
Mathieu Chartier31f44142014-04-08 14:40:03 -0700681 VLOG(heap) << "Created main space " << main_space_;
682}
683
Mathieu Chartier50482232013-11-21 11:48:14 -0800684void Heap::ChangeAllocator(AllocatorType allocator) {
Mathieu Chartier50482232013-11-21 11:48:14 -0800685 if (current_allocator_ != allocator) {
Mathieu Chartierd8891782014-03-02 13:28:37 -0800686 // These two allocators are only used internally and don't have any entrypoints.
687 CHECK_NE(allocator, kAllocatorTypeLOS);
688 CHECK_NE(allocator, kAllocatorTypeNonMoving);
Mathieu Chartier50482232013-11-21 11:48:14 -0800689 current_allocator_ = allocator;
Mathieu Chartierd8891782014-03-02 13:28:37 -0800690 MutexLock mu(nullptr, *Locks::runtime_shutdown_lock_);
Mathieu Chartier50482232013-11-21 11:48:14 -0800691 SetQuickAllocEntryPointsAllocator(current_allocator_);
692 Runtime::Current()->GetInstrumentation()->ResetQuickAllocEntryPoints();
693 }
694}
695
Mathieu Chartier6a7824d2014-08-22 14:53:04 -0700696void Heap::DisableMovingGc() {
Mathieu Chartier31f44142014-04-08 14:40:03 -0700697 if (IsMovingGc(foreground_collector_type_)) {
Mathieu Chartier6a7824d2014-08-22 14:53:04 -0700698 foreground_collector_type_ = kCollectorTypeCMS;
Mathieu Chartier6dda8982014-03-06 11:11:48 -0800699 }
Mathieu Chartier31f44142014-04-08 14:40:03 -0700700 if (IsMovingGc(background_collector_type_)) {
701 background_collector_type_ = foreground_collector_type_;
Mathieu Chartier6dda8982014-03-06 11:11:48 -0800702 }
Mathieu Chartier31f44142014-04-08 14:40:03 -0700703 TransitionCollector(foreground_collector_type_);
Mathieu Chartier4f55e222015-09-04 13:26:21 -0700704 Thread* const self = Thread::Current();
Mathieu Chartier6a7824d2014-08-22 14:53:04 -0700705 ScopedThreadStateChange tsc(self, kSuspended);
Mathieu Chartier4f55e222015-09-04 13:26:21 -0700706 ScopedSuspendAll ssa(__FUNCTION__);
Mathieu Chartier6a7824d2014-08-22 14:53:04 -0700707 // Something may have caused the transition to fail.
Mathieu Chartiere4927f62014-08-23 13:56:03 -0700708 if (!IsMovingGc(collector_type_) && non_moving_space_ != main_space_) {
Mathieu Chartier6a7824d2014-08-22 14:53:04 -0700709 CHECK(main_space_ != nullptr);
710 // The allocation stack may have non movable objects in it. We need to flush it since the GC
711 // can't only handle marking allocation stack objects of one non moving space and one main
712 // space.
713 {
714 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
715 FlushAllocStack();
716 }
717 main_space_->DisableMovingObjects();
718 non_moving_space_ = main_space_;
719 CHECK(!non_moving_space_->CanMoveObjects());
720 }
Mathieu Chartier6dda8982014-03-06 11:11:48 -0800721}
722
Mathieu Chartier15d34022014-02-26 17:16:38 -0800723std::string Heap::SafeGetClassDescriptor(mirror::Class* klass) {
724 if (!IsValidContinuousSpaceObjectAddress(klass)) {
725 return StringPrintf("<non heap address klass %p>", klass);
726 }
727 mirror::Class* component_type = klass->GetComponentType<kVerifyNone>();
728 if (IsValidContinuousSpaceObjectAddress(component_type) && klass->IsArrayClass<kVerifyNone>()) {
729 std::string result("[");
730 result += SafeGetClassDescriptor(component_type);
731 return result;
732 } else if (UNLIKELY(klass->IsPrimitive<kVerifyNone>())) {
733 return Primitive::Descriptor(klass->GetPrimitiveType<kVerifyNone>());
Nicolas Geoffray3a090922015-11-24 09:17:30 +0000734 } else if (UNLIKELY(klass->IsProxyClass<kVerifyNone>())) {
735 return Runtime::Current()->GetClassLinker()->GetDescriptorForProxy(klass);
Mathieu Chartier15d34022014-02-26 17:16:38 -0800736 } else {
Mathieu Chartierc2f4d022014-03-03 16:11:42 -0800737 mirror::DexCache* dex_cache = klass->GetDexCache<kVerifyNone>();
Mathieu Chartier15d34022014-02-26 17:16:38 -0800738 if (!IsValidContinuousSpaceObjectAddress(dex_cache)) {
739 return StringPrintf("<non heap address dex_cache %p>", dex_cache);
740 }
741 const DexFile* dex_file = dex_cache->GetDexFile();
742 uint16_t class_def_idx = klass->GetDexClassDefIndex();
743 if (class_def_idx == DexFile::kDexNoIndex16) {
744 return "<class def not found>";
745 }
746 const DexFile::ClassDef& class_def = dex_file->GetClassDef(class_def_idx);
747 const DexFile::TypeId& type_id = dex_file->GetTypeId(class_def.class_idx_);
748 return dex_file->GetTypeDescriptor(type_id);
749 }
750}
751
752std::string Heap::SafePrettyTypeOf(mirror::Object* obj) {
753 if (obj == nullptr) {
754 return "null";
755 }
756 mirror::Class* klass = obj->GetClass<kVerifyNone>();
757 if (klass == nullptr) {
758 return "(class=null)";
759 }
760 std::string result(SafeGetClassDescriptor(klass));
761 if (obj->IsClass()) {
Mathieu Chartierc2f4d022014-03-03 16:11:42 -0800762 result += "<" + SafeGetClassDescriptor(obj->AsClass<kVerifyNone>()) + ">";
Mathieu Chartier15d34022014-02-26 17:16:38 -0800763 }
764 return result;
765}
766
767void Heap::DumpObject(std::ostream& stream, mirror::Object* obj) {
768 if (obj == nullptr) {
769 stream << "(obj=null)";
770 return;
771 }
772 if (IsAligned<kObjectAlignment>(obj)) {
773 space::Space* space = nullptr;
774 // Don't use find space since it only finds spaces which actually contain objects instead of
775 // spaces which may contain objects (e.g. cleared bump pointer spaces).
776 for (const auto& cur_space : continuous_spaces_) {
777 if (cur_space->HasAddress(obj)) {
778 space = cur_space;
779 break;
780 }
781 }
Mathieu Chartier15d34022014-02-26 17:16:38 -0800782 // Unprotect all the spaces.
Andreas Gampe277ccbd2014-11-03 21:36:10 -0800783 for (const auto& con_space : continuous_spaces_) {
784 mprotect(con_space->Begin(), con_space->Capacity(), PROT_READ | PROT_WRITE);
Mathieu Chartier15d34022014-02-26 17:16:38 -0800785 }
786 stream << "Object " << obj;
787 if (space != nullptr) {
788 stream << " in space " << *space;
789 }
Mathieu Chartierc2f4d022014-03-03 16:11:42 -0800790 mirror::Class* klass = obj->GetClass<kVerifyNone>();
Mathieu Chartier15d34022014-02-26 17:16:38 -0800791 stream << "\nclass=" << klass;
792 if (klass != nullptr) {
793 stream << " type= " << SafePrettyTypeOf(obj);
794 }
795 // Re-protect the address we faulted on.
796 mprotect(AlignDown(obj, kPageSize), kPageSize, PROT_NONE);
797 }
798}
799
Mathieu Chartier590fee92013-09-13 13:46:47 -0700800bool Heap::IsCompilingBoot() const {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800801 if (!Runtime::Current()->IsAotCompiler()) {
Alex Light64ad14d2014-08-19 14:23:13 -0700802 return false;
803 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700804 for (const auto& space : continuous_spaces_) {
Mathieu Chartier4e305412014-02-19 10:54:44 -0800805 if (space->IsImageSpace() || space->IsZygoteSpace()) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700806 return false;
807 }
808 }
809 return true;
810}
811
Mathieu Chartier1d27b342014-01-28 12:51:09 -0800812void Heap::IncrementDisableMovingGC(Thread* self) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700813 // Need to do this holding the lock to prevent races where the GC is about to run / running when
814 // we attempt to disable it.
Mathieu Chartiercaa82d62014-02-02 16:51:17 -0800815 ScopedThreadStateChange tsc(self, kWaitingForGcToComplete);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700816 MutexLock mu(self, *gc_complete_lock_);
Mathieu Chartier1d27b342014-01-28 12:51:09 -0800817 ++disable_moving_gc_count_;
Mathieu Chartier31f44142014-04-08 14:40:03 -0700818 if (IsMovingGc(collector_type_running_)) {
Mathieu Chartier89a201e2014-05-02 10:27:26 -0700819 WaitForGcToCompleteLocked(kGcCauseDisableMovingGc, self);
Mathieu Chartierd5a89ee2014-01-31 09:55:13 -0800820 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700821}
822
Mathieu Chartier1d27b342014-01-28 12:51:09 -0800823void Heap::DecrementDisableMovingGC(Thread* self) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700824 MutexLock mu(self, *gc_complete_lock_);
Mathieu Chartierb735bd92015-06-24 17:04:17 -0700825 CHECK_GT(disable_moving_gc_count_, 0U);
Mathieu Chartier1d27b342014-01-28 12:51:09 -0800826 --disable_moving_gc_count_;
Mathieu Chartier590fee92013-09-13 13:46:47 -0700827}
828
Hiroshi Yamauchi76f55b02015-08-21 16:10:39 -0700829void Heap::IncrementDisableThreadFlip(Thread* self) {
830 // Supposed to be called by mutators. If thread_flip_running_ is true, block. Otherwise, go ahead.
831 CHECK(kUseReadBarrier);
832 ScopedThreadStateChange tsc(self, kWaitingForGcThreadFlip);
833 MutexLock mu(self, *thread_flip_lock_);
834 bool has_waited = false;
835 uint64_t wait_start = NanoTime();
836 while (thread_flip_running_) {
837 has_waited = true;
838 thread_flip_cond_->Wait(self);
839 }
840 ++disable_thread_flip_count_;
841 if (has_waited) {
842 uint64_t wait_time = NanoTime() - wait_start;
843 total_wait_time_ += wait_time;
844 if (wait_time > long_pause_log_threshold_) {
845 LOG(INFO) << __FUNCTION__ << " blocked for " << PrettyDuration(wait_time);
846 }
847 }
848}
849
850void Heap::DecrementDisableThreadFlip(Thread* self) {
851 // Supposed to be called by mutators. Decrement disable_thread_flip_count_ and potentially wake up
852 // the GC waiting before doing a thread flip.
853 CHECK(kUseReadBarrier);
854 MutexLock mu(self, *thread_flip_lock_);
855 CHECK_GT(disable_thread_flip_count_, 0U);
856 --disable_thread_flip_count_;
857 thread_flip_cond_->Broadcast(self);
858}
859
860void Heap::ThreadFlipBegin(Thread* self) {
861 // Supposed to be called by GC. Set thread_flip_running_ to be true. If disable_thread_flip_count_
862 // > 0, block. Otherwise, go ahead.
863 CHECK(kUseReadBarrier);
864 ScopedThreadStateChange tsc(self, kWaitingForGcThreadFlip);
865 MutexLock mu(self, *thread_flip_lock_);
866 bool has_waited = false;
867 uint64_t wait_start = NanoTime();
868 CHECK(!thread_flip_running_);
869 // Set this to true before waiting so that a new mutator entering a JNI critical won't starve GC.
870 thread_flip_running_ = true;
871 while (disable_thread_flip_count_ > 0) {
872 has_waited = true;
873 thread_flip_cond_->Wait(self);
874 }
875 if (has_waited) {
876 uint64_t wait_time = NanoTime() - wait_start;
877 total_wait_time_ += wait_time;
878 if (wait_time > long_pause_log_threshold_) {
879 LOG(INFO) << __FUNCTION__ << " blocked for " << PrettyDuration(wait_time);
880 }
881 }
882}
883
884void Heap::ThreadFlipEnd(Thread* self) {
885 // Supposed to be called by GC. Set thread_flip_running_ to false and potentially wake up mutators
886 // waiting before doing a JNI critical.
887 CHECK(kUseReadBarrier);
888 MutexLock mu(self, *thread_flip_lock_);
889 CHECK(thread_flip_running_);
890 thread_flip_running_ = false;
891 thread_flip_cond_->Broadcast(self);
892}
893
Mathieu Chartierca2a24d2013-11-25 15:12:12 -0800894void Heap::UpdateProcessState(ProcessState process_state) {
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800895 if (process_state_ != process_state) {
896 process_state_ = process_state;
Mathieu Chartier91e30632014-03-25 15:58:50 -0700897 for (size_t i = 1; i <= kCollectorTransitionStressIterations; ++i) {
898 // Start at index 1 to avoid "is always false" warning.
899 // Have iteration 1 always transition the collector.
900 TransitionCollector((((i & 1) == 1) == (process_state_ == kProcessStateJankPerceptible))
Mathieu Chartier31f44142014-04-08 14:40:03 -0700901 ? foreground_collector_type_ : background_collector_type_);
Mathieu Chartier91e30632014-03-25 15:58:50 -0700902 usleep(kCollectorTransitionStressWait);
903 }
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800904 if (process_state_ == kProcessStateJankPerceptible) {
Mathieu Chartiera5f9de02014-02-28 16:48:42 -0800905 // Transition back to foreground right away to prevent jank.
Mathieu Chartier31f44142014-04-08 14:40:03 -0700906 RequestCollectorTransition(foreground_collector_type_, 0);
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800907 } else {
Mathieu Chartiera5f9de02014-02-28 16:48:42 -0800908 // Don't delay for debug builds since we may want to stress test the GC.
Zuo Wangf37a88b2014-07-10 04:26:41 -0700909 // If background_collector_type_ is kCollectorTypeHomogeneousSpaceCompact then we have
910 // special handling which does a homogenous space compaction once but then doesn't transition
911 // the collector.
912 RequestCollectorTransition(background_collector_type_,
913 kIsDebugBuild ? 0 : kCollectorTransitionWait);
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800914 }
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800915 }
Mathieu Chartierca2a24d2013-11-25 15:12:12 -0800916}
917
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700918void Heap::CreateThreadPool() {
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700919 const size_t num_threads = std::max(parallel_gc_threads_, conc_gc_threads_);
920 if (num_threads != 0) {
Mathieu Chartierbcd5e9d2013-11-13 14:33:28 -0800921 thread_pool_.reset(new ThreadPool("Heap thread pool", num_threads));
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700922 }
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700923}
924
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800925// Visit objects when threads aren't suspended. If concurrent moving
926// GC, disable moving GC and suspend threads and then visit objects.
Mathieu Chartier83c8ee02014-01-28 14:50:23 -0800927void Heap::VisitObjects(ObjectCallback callback, void* arg) {
Hiroshi Yamauchi0c8c3032015-01-16 16:54:35 -0800928 Thread* self = Thread::Current();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800929 Locks::mutator_lock_->AssertSharedHeld(self);
930 DCHECK(!Locks::mutator_lock_->IsExclusiveHeld(self)) << "Call VisitObjectsPaused() instead";
931 if (IsGcConcurrentAndMoving()) {
932 // Concurrent moving GC. Just suspending threads isn't sufficient
933 // because a collection isn't one big pause and we could suspend
934 // threads in the middle (between phases) of a concurrent moving
935 // collection where it's not easily known which objects are alive
936 // (both the region space and the non-moving space) or which
937 // copies of objects to visit, and the to-space invariant could be
938 // easily broken. Visit objects while GC isn't running by using
939 // IncrementDisableMovingGC() and threads are suspended.
940 IncrementDisableMovingGC(self);
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700941 {
942 ScopedThreadSuspension sts(self, kWaitingForVisitObjects);
Mathieu Chartier4f55e222015-09-04 13:26:21 -0700943 ScopedSuspendAll ssa(__FUNCTION__);
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700944 VisitObjectsInternalRegionSpace(callback, arg);
945 VisitObjectsInternal(callback, arg);
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700946 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800947 DecrementDisableMovingGC(self);
Hiroshi Yamauchi0c8c3032015-01-16 16:54:35 -0800948 } else {
949 // GCs can move objects, so don't allow this.
950 ScopedAssertNoThreadSuspension ants(self, "Visiting objects");
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800951 DCHECK(region_space_ == nullptr);
Hiroshi Yamauchi0c8c3032015-01-16 16:54:35 -0800952 VisitObjectsInternal(callback, arg);
953 }
954}
955
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800956// Visit objects when threads are already suspended.
957void Heap::VisitObjectsPaused(ObjectCallback callback, void* arg) {
958 Thread* self = Thread::Current();
959 Locks::mutator_lock_->AssertExclusiveHeld(self);
960 VisitObjectsInternalRegionSpace(callback, arg);
961 VisitObjectsInternal(callback, arg);
962}
963
964// Visit objects in the region spaces.
965void Heap::VisitObjectsInternalRegionSpace(ObjectCallback callback, void* arg) {
966 Thread* self = Thread::Current();
967 Locks::mutator_lock_->AssertExclusiveHeld(self);
968 if (region_space_ != nullptr) {
969 DCHECK(IsGcConcurrentAndMoving());
970 if (!zygote_creation_lock_.IsExclusiveHeld(self)) {
971 // Exclude the pre-zygote fork time where the semi-space collector
972 // calls VerifyHeapReferences() as part of the zygote compaction
973 // which then would call here without the moving GC disabled,
974 // which is fine.
975 DCHECK(IsMovingGCDisabled(self));
976 }
977 region_space_->Walk(callback, arg);
978 }
979}
980
981// Visit objects in the other spaces.
Hiroshi Yamauchi0c8c3032015-01-16 16:54:35 -0800982void Heap::VisitObjectsInternal(ObjectCallback callback, void* arg) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700983 if (bump_pointer_space_ != nullptr) {
Mathieu Chartier692fafd2013-11-29 17:24:40 -0800984 // Visit objects in bump pointer space.
985 bump_pointer_space_->Walk(callback, arg);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700986 }
987 // TODO: Switch to standard begin and end to use ranged a based loop.
Mathieu Chartiercb535da2015-01-23 13:50:03 -0800988 for (auto* it = allocation_stack_->Begin(), *end = allocation_stack_->End(); it < end; ++it) {
989 mirror::Object* const obj = it->AsMirrorPtr();
Mathieu Chartierebdf3f32014-02-13 10:23:27 -0800990 if (obj != nullptr && obj->GetClass() != nullptr) {
991 // Avoid the race condition caused by the object not yet being written into the allocation
Mathieu Chartiera5eae692014-12-17 17:56:03 -0800992 // stack or the class not yet being written in the object. Or, if
993 // kUseThreadLocalAllocationStack, there can be nulls on the allocation stack.
Mathieu Chartierebdf3f32014-02-13 10:23:27 -0800994 callback(obj, arg);
995 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700996 }
Hiroshi Yamauchi0c8c3032015-01-16 16:54:35 -0800997 {
998 ReaderMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
999 GetLiveBitmap()->Walk(callback, arg);
1000 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07001001}
1002
1003void Heap::MarkAllocStackAsLive(accounting::ObjectStack* stack) {
Mathieu Chartier00b59152014-07-25 10:13:51 -07001004 space::ContinuousSpace* space1 = main_space_ != nullptr ? main_space_ : non_moving_space_;
1005 space::ContinuousSpace* space2 = non_moving_space_;
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001006 // TODO: Generalize this to n bitmaps?
Mathieu Chartier00b59152014-07-25 10:13:51 -07001007 CHECK(space1 != nullptr);
1008 CHECK(space2 != nullptr);
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001009 MarkAllocStack(space1->GetLiveBitmap(), space2->GetLiveBitmap(),
Mathieu Chartier2dbe6272014-09-16 10:43:23 -07001010 (large_object_space_ != nullptr ? large_object_space_->GetLiveBitmap() : nullptr),
1011 stack);
Mathieu Chartier590fee92013-09-13 13:46:47 -07001012}
1013
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001014void Heap::DeleteThreadPool() {
Mathieu Chartier2775ee42013-08-20 17:43:47 -07001015 thread_pool_.reset(nullptr);
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001016}
1017
Mathieu Chartier1b54f9c2014-04-30 16:45:02 -07001018void Heap::AddSpace(space::Space* space) {
Zuo Wangf37a88b2014-07-10 04:26:41 -07001019 CHECK(space != nullptr);
Mathieu Chartier590fee92013-09-13 13:46:47 -07001020 WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
1021 if (space->IsContinuousSpace()) {
1022 DCHECK(!space->IsDiscontinuousSpace());
1023 space::ContinuousSpace* continuous_space = space->AsContinuousSpace();
1024 // Continuous spaces don't necessarily have bitmaps.
Mathieu Chartiera8e8f9c2014-04-09 14:51:05 -07001025 accounting::ContinuousSpaceBitmap* live_bitmap = continuous_space->GetLiveBitmap();
1026 accounting::ContinuousSpaceBitmap* mark_bitmap = continuous_space->GetMarkBitmap();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001027 if (live_bitmap != nullptr) {
Mathieu Chartier2796a162014-07-25 11:50:47 -07001028 CHECK(mark_bitmap != nullptr);
Mathieu Chartier590fee92013-09-13 13:46:47 -07001029 live_bitmap_->AddContinuousSpaceBitmap(live_bitmap);
1030 mark_bitmap_->AddContinuousSpaceBitmap(mark_bitmap);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001031 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07001032 continuous_spaces_.push_back(continuous_space);
Mathieu Chartier590fee92013-09-13 13:46:47 -07001033 // Ensure that spaces remain sorted in increasing order of start address.
1034 std::sort(continuous_spaces_.begin(), continuous_spaces_.end(),
1035 [](const space::ContinuousSpace* a, const space::ContinuousSpace* b) {
1036 return a->Begin() < b->Begin();
1037 });
Mathieu Chartier590fee92013-09-13 13:46:47 -07001038 } else {
Mathieu Chartier2796a162014-07-25 11:50:47 -07001039 CHECK(space->IsDiscontinuousSpace());
Mathieu Chartier590fee92013-09-13 13:46:47 -07001040 space::DiscontinuousSpace* discontinuous_space = space->AsDiscontinuousSpace();
Mathieu Chartierbbd695c2014-04-16 09:48:48 -07001041 live_bitmap_->AddLargeObjectBitmap(discontinuous_space->GetLiveBitmap());
1042 mark_bitmap_->AddLargeObjectBitmap(discontinuous_space->GetMarkBitmap());
Mathieu Chartier590fee92013-09-13 13:46:47 -07001043 discontinuous_spaces_.push_back(discontinuous_space);
1044 }
1045 if (space->IsAllocSpace()) {
1046 alloc_spaces_.push_back(space->AsAllocSpace());
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001047 }
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08001048}
1049
Mathieu Chartier1b54f9c2014-04-30 16:45:02 -07001050void Heap::SetSpaceAsDefault(space::ContinuousSpace* continuous_space) {
1051 WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
1052 if (continuous_space->IsDlMallocSpace()) {
1053 dlmalloc_space_ = continuous_space->AsDlMallocSpace();
1054 } else if (continuous_space->IsRosAllocSpace()) {
1055 rosalloc_space_ = continuous_space->AsRosAllocSpace();
1056 }
1057}
1058
1059void Heap::RemoveSpace(space::Space* space) {
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001060 DCHECK(space != nullptr);
1061 WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
1062 if (space->IsContinuousSpace()) {
1063 DCHECK(!space->IsDiscontinuousSpace());
1064 space::ContinuousSpace* continuous_space = space->AsContinuousSpace();
1065 // Continuous spaces don't necessarily have bitmaps.
Mathieu Chartiera8e8f9c2014-04-09 14:51:05 -07001066 accounting::ContinuousSpaceBitmap* live_bitmap = continuous_space->GetLiveBitmap();
1067 accounting::ContinuousSpaceBitmap* mark_bitmap = continuous_space->GetMarkBitmap();
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001068 if (live_bitmap != nullptr) {
1069 DCHECK(mark_bitmap != nullptr);
1070 live_bitmap_->RemoveContinuousSpaceBitmap(live_bitmap);
1071 mark_bitmap_->RemoveContinuousSpaceBitmap(mark_bitmap);
1072 }
1073 auto it = std::find(continuous_spaces_.begin(), continuous_spaces_.end(), continuous_space);
1074 DCHECK(it != continuous_spaces_.end());
1075 continuous_spaces_.erase(it);
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001076 } else {
1077 DCHECK(space->IsDiscontinuousSpace());
1078 space::DiscontinuousSpace* discontinuous_space = space->AsDiscontinuousSpace();
Mathieu Chartierbbd695c2014-04-16 09:48:48 -07001079 live_bitmap_->RemoveLargeObjectBitmap(discontinuous_space->GetLiveBitmap());
1080 mark_bitmap_->RemoveLargeObjectBitmap(discontinuous_space->GetMarkBitmap());
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001081 auto it = std::find(discontinuous_spaces_.begin(), discontinuous_spaces_.end(),
1082 discontinuous_space);
1083 DCHECK(it != discontinuous_spaces_.end());
1084 discontinuous_spaces_.erase(it);
1085 }
1086 if (space->IsAllocSpace()) {
1087 auto it = std::find(alloc_spaces_.begin(), alloc_spaces_.end(), space->AsAllocSpace());
1088 DCHECK(it != alloc_spaces_.end());
1089 alloc_spaces_.erase(it);
1090 }
1091}
1092
Elliott Hughes8b788fe2013-04-17 15:57:01 -07001093void Heap::DumpGcPerformanceInfo(std::ostream& os) {
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001094 // Dump cumulative timings.
Elliott Hughes8b788fe2013-04-17 15:57:01 -07001095 os << "Dumping cumulative Gc timings\n";
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001096 uint64_t total_duration = 0;
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001097 // Dump cumulative loggers for each GC type.
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001098 uint64_t total_paused_time = 0;
Mathieu Chartier5a487192014-04-08 11:14:54 -07001099 for (auto& collector : garbage_collectors_) {
Mathieu Chartier104fa0c2014-08-07 14:26:27 -07001100 total_duration += collector->GetCumulativeTimings().GetTotalNs();
1101 total_paused_time += collector->GetTotalPausedTimeNs();
1102 collector->DumpPerformanceInfo(os);
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001103 }
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001104 if (total_duration != 0) {
Brian Carlstrom2d888622013-07-18 17:02:00 -07001105 const double total_seconds = static_cast<double>(total_duration / 1000) / 1000000.0;
Elliott Hughes8b788fe2013-04-17 15:57:01 -07001106 os << "Total time spent in GC: " << PrettyDuration(total_duration) << "\n";
1107 os << "Mean GC size throughput: "
Ian Rogers1d54e732013-05-02 21:10:01 -07001108 << PrettySize(GetBytesFreedEver() / total_seconds) << "/s\n";
Elliott Hughes8b788fe2013-04-17 15:57:01 -07001109 os << "Mean GC object throughput: "
Ian Rogers1d54e732013-05-02 21:10:01 -07001110 << (GetObjectsFreedEver() / total_seconds) << " objects/s\n";
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001111 }
Mathieu Chartierdd162fb2014-08-06 17:06:33 -07001112 uint64_t total_objects_allocated = GetObjectsAllocatedEver();
Mathieu Chartierc30a7252014-08-12 10:13:48 -07001113 os << "Total number of allocations " << total_objects_allocated << "\n";
Hiroshi Yamauchia1c9f012015-04-02 10:18:12 -07001114 os << "Total bytes allocated " << PrettySize(GetBytesAllocatedEver()) << "\n";
1115 os << "Total bytes freed " << PrettySize(GetBytesFreedEver()) << "\n";
Mathieu Chartierc30a7252014-08-12 10:13:48 -07001116 os << "Free memory " << PrettySize(GetFreeMemory()) << "\n";
Mathieu Chartierdd162fb2014-08-06 17:06:33 -07001117 os << "Free memory until GC " << PrettySize(GetFreeMemoryUntilGC()) << "\n";
1118 os << "Free memory until OOME " << PrettySize(GetFreeMemoryUntilOOME()) << "\n";
Mathieu Chartierc30a7252014-08-12 10:13:48 -07001119 os << "Total memory " << PrettySize(GetTotalMemory()) << "\n";
1120 os << "Max memory " << PrettySize(GetMaxMemory()) << "\n";
Mathieu Chartiere4cab172014-08-19 18:24:04 -07001121 if (HasZygoteSpace()) {
1122 os << "Zygote space size " << PrettySize(zygote_space_->Size()) << "\n";
1123 }
Elliott Hughes8b788fe2013-04-17 15:57:01 -07001124 os << "Total mutator paused time: " << PrettyDuration(total_paused_time) << "\n";
Hiroshi Yamauchia1c9f012015-04-02 10:18:12 -07001125 os << "Total time waiting for GC to complete: " << PrettyDuration(total_wait_time_) << "\n";
1126 os << "Total GC count: " << GetGcCount() << "\n";
1127 os << "Total GC time: " << PrettyDuration(GetGcTime()) << "\n";
1128 os << "Total blocking GC count: " << GetBlockingGcCount() << "\n";
1129 os << "Total blocking GC time: " << PrettyDuration(GetBlockingGcTime()) << "\n";
1130
1131 {
1132 MutexLock mu(Thread::Current(), *gc_complete_lock_);
1133 if (gc_count_rate_histogram_.SampleSize() > 0U) {
1134 os << "Histogram of GC count per " << NsToMs(kGcCountRateHistogramWindowDuration) << " ms: ";
1135 gc_count_rate_histogram_.DumpBins(os);
1136 os << "\n";
1137 }
1138 if (blocking_gc_count_rate_histogram_.SampleSize() > 0U) {
1139 os << "Histogram of blocking GC count per "
1140 << NsToMs(kGcCountRateHistogramWindowDuration) << " ms: ";
1141 blocking_gc_count_rate_histogram_.DumpBins(os);
1142 os << "\n";
1143 }
1144 }
1145
Mathieu Chartier73d1e172014-04-11 17:53:48 -07001146 BaseMutex::DumpAll(os);
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001147}
1148
Hiroshi Yamauchi37670172015-06-10 17:20:54 -07001149void Heap::ResetGcPerformanceInfo() {
1150 for (auto& collector : garbage_collectors_) {
1151 collector->ResetMeasurements();
1152 }
Hiroshi Yamauchi37670172015-06-10 17:20:54 -07001153 total_bytes_freed_ever_ = 0;
1154 total_objects_freed_ever_ = 0;
1155 total_wait_time_ = 0;
1156 blocking_gc_count_ = 0;
1157 blocking_gc_time_ = 0;
1158 gc_count_last_window_ = 0;
1159 blocking_gc_count_last_window_ = 0;
1160 last_update_time_gc_count_rate_histograms_ = // Round down by the window duration.
1161 (NanoTime() / kGcCountRateHistogramWindowDuration) * kGcCountRateHistogramWindowDuration;
1162 {
1163 MutexLock mu(Thread::Current(), *gc_complete_lock_);
1164 gc_count_rate_histogram_.Reset();
1165 blocking_gc_count_rate_histogram_.Reset();
1166 }
1167}
1168
Hiroshi Yamauchia1c9f012015-04-02 10:18:12 -07001169uint64_t Heap::GetGcCount() const {
1170 uint64_t gc_count = 0U;
1171 for (auto& collector : garbage_collectors_) {
1172 gc_count += collector->GetCumulativeTimings().GetIterations();
1173 }
1174 return gc_count;
1175}
1176
1177uint64_t Heap::GetGcTime() const {
1178 uint64_t gc_time = 0U;
1179 for (auto& collector : garbage_collectors_) {
1180 gc_time += collector->GetCumulativeTimings().GetTotalNs();
1181 }
1182 return gc_time;
1183}
1184
1185uint64_t Heap::GetBlockingGcCount() const {
1186 return blocking_gc_count_;
1187}
1188
1189uint64_t Heap::GetBlockingGcTime() const {
1190 return blocking_gc_time_;
1191}
1192
1193void Heap::DumpGcCountRateHistogram(std::ostream& os) const {
1194 MutexLock mu(Thread::Current(), *gc_complete_lock_);
1195 if (gc_count_rate_histogram_.SampleSize() > 0U) {
1196 gc_count_rate_histogram_.DumpBins(os);
1197 }
1198}
1199
1200void Heap::DumpBlockingGcCountRateHistogram(std::ostream& os) const {
1201 MutexLock mu(Thread::Current(), *gc_complete_lock_);
1202 if (blocking_gc_count_rate_histogram_.SampleSize() > 0U) {
1203 blocking_gc_count_rate_histogram_.DumpBins(os);
1204 }
1205}
1206
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08001207Heap::~Heap() {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001208 VLOG(heap) << "Starting ~Heap()";
Mathieu Chartier590fee92013-09-13 13:46:47 -07001209 STLDeleteElements(&garbage_collectors_);
1210 // If we don't reset then the mark stack complains in its destructor.
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001211 allocation_stack_->Reset();
Man Cao8c2ff642015-05-27 17:25:30 -07001212 allocation_records_.reset();
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001213 live_stack_->Reset();
Mathieu Chartier11409ae2013-09-23 11:49:36 -07001214 STLDeleteValues(&mod_union_tables_);
Mathieu Chartier0767c9a2014-03-26 12:53:19 -07001215 STLDeleteValues(&remembered_sets_);
Ian Rogers1d54e732013-05-02 21:10:01 -07001216 STLDeleteElements(&continuous_spaces_);
1217 STLDeleteElements(&discontinuous_spaces_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001218 delete gc_complete_lock_;
Andreas Gampe6be4f2a2015-11-10 13:34:17 -08001219 delete thread_flip_lock_;
Mathieu Chartiera5eae692014-12-17 17:56:03 -08001220 delete pending_task_lock_;
Mathieu Chartier31000802015-06-14 14:14:37 -07001221 delete backtrace_lock_;
1222 if (unique_backtrace_count_.LoadRelaxed() != 0 || seen_backtrace_count_.LoadRelaxed() != 0) {
1223 LOG(INFO) << "gc stress unique=" << unique_backtrace_count_.LoadRelaxed()
1224 << " total=" << seen_backtrace_count_.LoadRelaxed() +
1225 unique_backtrace_count_.LoadRelaxed();
1226 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07001227 VLOG(heap) << "Finished ~Heap()";
Carl Shapiro69759ea2011-07-21 18:13:35 -07001228}
1229
Ian Rogers1d54e732013-05-02 21:10:01 -07001230space::ContinuousSpace* Heap::FindContinuousSpaceFromObject(const mirror::Object* obj,
1231 bool fail_ok) const {
Mathieu Chartier02e25112013-08-14 16:14:24 -07001232 for (const auto& space : continuous_spaces_) {
1233 if (space->Contains(obj)) {
1234 return space;
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07001235 }
1236 }
Ian Rogers1d54e732013-05-02 21:10:01 -07001237 if (!fail_ok) {
1238 LOG(FATAL) << "object " << reinterpret_cast<const void*>(obj) << " not inside any spaces!";
1239 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001240 return nullptr;
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07001241}
1242
Ian Rogers1d54e732013-05-02 21:10:01 -07001243space::DiscontinuousSpace* Heap::FindDiscontinuousSpaceFromObject(const mirror::Object* obj,
1244 bool fail_ok) const {
Mathieu Chartier02e25112013-08-14 16:14:24 -07001245 for (const auto& space : discontinuous_spaces_) {
1246 if (space->Contains(obj)) {
1247 return space;
Ian Rogers1d54e732013-05-02 21:10:01 -07001248 }
1249 }
1250 if (!fail_ok) {
1251 LOG(FATAL) << "object " << reinterpret_cast<const void*>(obj) << " not inside any spaces!";
1252 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001253 return nullptr;
Ian Rogers1d54e732013-05-02 21:10:01 -07001254}
1255
1256space::Space* Heap::FindSpaceFromObject(const mirror::Object* obj, bool fail_ok) const {
1257 space::Space* result = FindContinuousSpaceFromObject(obj, true);
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001258 if (result != nullptr) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001259 return result;
1260 }
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07001261 return FindDiscontinuousSpaceFromObject(obj, fail_ok);
Ian Rogers1d54e732013-05-02 21:10:01 -07001262}
1263
Hiroshi Yamauchi654dd482014-07-09 12:54:32 -07001264void Heap::ThrowOutOfMemoryError(Thread* self, size_t byte_count, AllocatorType allocator_type) {
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -07001265 std::ostringstream oss;
Ian Rogersef7d42f2014-01-06 12:55:46 -08001266 size_t total_bytes_free = GetFreeMemory();
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -07001267 oss << "Failed to allocate a " << byte_count << " byte allocation with " << total_bytes_free
Mathieu Chartierdd162fb2014-08-06 17:06:33 -07001268 << " free bytes and " << PrettySize(GetFreeMemoryUntilOOME()) << " until OOM";
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -07001269 // If the allocation failed due to fragmentation, print out the largest continuous allocation.
Zuo Wangf37a88b2014-07-10 04:26:41 -07001270 if (total_bytes_free >= byte_count) {
Mathieu Chartierb363f662014-07-16 13:28:58 -07001271 space::AllocSpace* space = nullptr;
Hiroshi Yamauchi654dd482014-07-09 12:54:32 -07001272 if (allocator_type == kAllocatorTypeNonMoving) {
1273 space = non_moving_space_;
1274 } else if (allocator_type == kAllocatorTypeRosAlloc ||
1275 allocator_type == kAllocatorTypeDlMalloc) {
1276 space = main_space_;
Mathieu Chartierb363f662014-07-16 13:28:58 -07001277 } else if (allocator_type == kAllocatorTypeBumpPointer ||
1278 allocator_type == kAllocatorTypeTLAB) {
1279 space = bump_pointer_space_;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001280 } else if (allocator_type == kAllocatorTypeRegion ||
1281 allocator_type == kAllocatorTypeRegionTLAB) {
1282 space = region_space_;
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -07001283 }
Hiroshi Yamauchi654dd482014-07-09 12:54:32 -07001284 if (space != nullptr) {
1285 space->LogFragmentationAllocFailure(oss, byte_count);
1286 }
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001287 }
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -07001288 self->ThrowOutOfMemoryError(oss.str().c_str());
1289}
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001290
Mathieu Chartiera5eae692014-12-17 17:56:03 -08001291void Heap::DoPendingCollectorTransition() {
1292 CollectorType desired_collector_type = desired_collector_type_;
Mathieu Chartierb2728552014-09-08 20:08:41 +00001293 // Launch homogeneous space compaction if it is desired.
1294 if (desired_collector_type == kCollectorTypeHomogeneousSpaceCompact) {
1295 if (!CareAboutPauseTimes()) {
1296 PerformHomogeneousSpaceCompact();
Mathieu Chartiera5eae692014-12-17 17:56:03 -08001297 } else {
1298 VLOG(gc) << "Homogeneous compaction ignored due to jank perceptible process state";
Mathieu Chartierb2728552014-09-08 20:08:41 +00001299 }
Mathieu Chartiera5eae692014-12-17 17:56:03 -08001300 } else {
1301 TransitionCollector(desired_collector_type);
Mathieu Chartierb2728552014-09-08 20:08:41 +00001302 }
Mathieu Chartiera5eae692014-12-17 17:56:03 -08001303}
1304
1305void Heap::Trim(Thread* self) {
Mathieu Chartier8d447252015-10-26 10:21:14 -07001306 Runtime* const runtime = Runtime::Current();
Mathieu Chartier440e4ce2014-03-31 16:36:35 -07001307 if (!CareAboutPauseTimes()) {
Mathieu Chartiera5eae692014-12-17 17:56:03 -08001308 ATRACE_BEGIN("Deflating monitors");
Mathieu Chartier440e4ce2014-03-31 16:36:35 -07001309 // Deflate the monitors, this can cause a pause but shouldn't matter since we don't care
1310 // about pauses.
Mathieu Chartier4f55e222015-09-04 13:26:21 -07001311 {
1312 ScopedSuspendAll ssa(__FUNCTION__);
1313 uint64_t start_time = NanoTime();
1314 size_t count = runtime->GetMonitorList()->DeflateMonitors();
1315 VLOG(heap) << "Deflating " << count << " monitors took "
1316 << PrettyDuration(NanoTime() - start_time);
1317 }
Mathieu Chartiera5eae692014-12-17 17:56:03 -08001318 ATRACE_END();
Mathieu Chartier440e4ce2014-03-31 16:36:35 -07001319 }
Mathieu Chartiera5eae692014-12-17 17:56:03 -08001320 TrimIndirectReferenceTables(self);
1321 TrimSpaces(self);
Mathieu Chartier8d447252015-10-26 10:21:14 -07001322 // Trim arenas that may have been used by JIT or verifier.
1323 ATRACE_BEGIN("Trimming arena maps");
1324 runtime->GetArenaPool()->TrimMaps();
1325 ATRACE_END();
Mathieu Chartiera5f9de02014-02-28 16:48:42 -08001326}
1327
Mathieu Chartier91c2f0c2014-11-26 11:21:15 -08001328class TrimIndirectReferenceTableClosure : public Closure {
1329 public:
1330 explicit TrimIndirectReferenceTableClosure(Barrier* barrier) : barrier_(barrier) {
1331 }
1332 virtual void Run(Thread* thread) OVERRIDE NO_THREAD_SAFETY_ANALYSIS {
1333 ATRACE_BEGIN("Trimming reference table");
1334 thread->GetJniEnv()->locals.Trim();
1335 ATRACE_END();
Lei Lidd9943d2015-02-02 14:24:44 +08001336 // If thread is a running mutator, then act on behalf of the trim thread.
1337 // See the code in ThreadList::RunCheckpoint.
Mathieu Chartier10d25082015-10-28 18:36:09 -07001338 barrier_->Pass(Thread::Current());
Mathieu Chartier91c2f0c2014-11-26 11:21:15 -08001339 }
1340
1341 private:
1342 Barrier* const barrier_;
1343};
1344
Mathieu Chartiera5eae692014-12-17 17:56:03 -08001345void Heap::TrimIndirectReferenceTables(Thread* self) {
1346 ScopedObjectAccess soa(self);
1347 ATRACE_BEGIN(__FUNCTION__);
1348 JavaVMExt* vm = soa.Vm();
1349 // Trim globals indirect reference table.
1350 vm->TrimGlobals();
1351 // Trim locals indirect reference tables.
1352 Barrier barrier(0);
1353 TrimIndirectReferenceTableClosure closure(&barrier);
1354 ScopedThreadStateChange tsc(self, kWaitingForCheckPointsToRun);
1355 size_t barrier_count = Runtime::Current()->GetThreadList()->RunCheckpoint(&closure);
Lei Lidd9943d2015-02-02 14:24:44 +08001356 if (barrier_count != 0) {
1357 barrier.Increment(self, barrier_count);
1358 }
Mathieu Chartiera5eae692014-12-17 17:56:03 -08001359 ATRACE_END();
1360}
Mathieu Chartier91c2f0c2014-11-26 11:21:15 -08001361
Mathieu Chartieraa516822015-10-02 15:53:37 -07001362void Heap::StartGC(Thread* self, GcCause cause, CollectorType collector_type) {
1363 MutexLock mu(self, *gc_complete_lock_);
1364 // Ensure there is only one GC at a time.
1365 WaitForGcToCompleteLocked(cause, self);
1366 collector_type_running_ = collector_type;
1367}
1368
Mathieu Chartiera5eae692014-12-17 17:56:03 -08001369void Heap::TrimSpaces(Thread* self) {
Mathieu Chartiera5f9de02014-02-28 16:48:42 -08001370 {
Mathieu Chartiercaa82d62014-02-02 16:51:17 -08001371 // Need to do this before acquiring the locks since we don't want to get suspended while
1372 // holding any locks.
1373 ScopedThreadStateChange tsc(self, kWaitingForGcToComplete);
Mathieu Chartierd5a89ee2014-01-31 09:55:13 -08001374 // Pretend we are doing a GC to prevent background compaction from deleting the space we are
1375 // trimming.
Mathieu Chartieraa516822015-10-02 15:53:37 -07001376 StartGC(self, kGcCauseTrim, kCollectorTypeHeapTrim);
Mathieu Chartierd5a89ee2014-01-31 09:55:13 -08001377 }
Mathieu Chartiera5eae692014-12-17 17:56:03 -08001378 ATRACE_BEGIN(__FUNCTION__);
1379 const uint64_t start_ns = NanoTime();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001380 // Trim the managed spaces.
1381 uint64_t total_alloc_space_allocated = 0;
1382 uint64_t total_alloc_space_size = 0;
1383 uint64_t managed_reclaimed = 0;
1384 for (const auto& space : continuous_spaces_) {
Mathieu Chartiera1602f22014-01-13 17:19:19 -08001385 if (space->IsMallocSpace()) {
Mathieu Chartiera5b5c552014-06-24 14:48:59 -07001386 gc::space::MallocSpace* malloc_space = space->AsMallocSpace();
1387 if (malloc_space->IsRosAllocSpace() || !CareAboutPauseTimes()) {
1388 // Don't trim dlmalloc spaces if we care about pauses since this can hold the space lock
1389 // for a long period of time.
1390 managed_reclaimed += malloc_space->Trim();
1391 }
1392 total_alloc_space_size += malloc_space->Size();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001393 }
1394 }
Mathieu Chartier2dbe6272014-09-16 10:43:23 -07001395 total_alloc_space_allocated = GetBytesAllocated();
1396 if (large_object_space_ != nullptr) {
1397 total_alloc_space_allocated -= large_object_space_->GetBytesAllocated();
1398 }
Mathieu Chartier31f44142014-04-08 14:40:03 -07001399 if (bump_pointer_space_ != nullptr) {
1400 total_alloc_space_allocated -= bump_pointer_space_->Size();
1401 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001402 if (region_space_ != nullptr) {
1403 total_alloc_space_allocated -= region_space_->GetBytesAllocated();
1404 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07001405 const float managed_utilization = static_cast<float>(total_alloc_space_allocated) /
1406 static_cast<float>(total_alloc_space_size);
1407 uint64_t gc_heap_end_ns = NanoTime();
Mathieu Chartierd5a89ee2014-01-31 09:55:13 -08001408 // We never move things in the native heap, so we can finish the GC at this point.
1409 FinishGC(self, collector::kGcTypeNone);
Ian Rogers872dd822014-10-30 11:19:14 -07001410
Mathieu Chartier590fee92013-09-13 13:46:47 -07001411 VLOG(heap) << "Heap trim of managed (duration=" << PrettyDuration(gc_heap_end_ns - start_ns)
Dimitry Ivanove6465bc2015-12-14 18:55:02 -08001412 << ", advised=" << PrettySize(managed_reclaimed) << ") heap. Managed heap utilization of "
1413 << static_cast<int>(100 * managed_utilization) << "%.";
Mathieu Chartiera5eae692014-12-17 17:56:03 -08001414 ATRACE_END();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001415}
1416
1417bool Heap::IsValidObjectAddress(const mirror::Object* obj) const {
1418 // Note: we deliberately don't take the lock here, and mustn't test anything that would require
1419 // taking the lock.
1420 if (obj == nullptr) {
Elliott Hughes88c5c352012-03-15 18:49:48 -07001421 return true;
1422 }
Mathieu Chartier15d34022014-02-26 17:16:38 -08001423 return IsAligned<kObjectAlignment>(obj) && FindSpaceFromObject(obj, true) != nullptr;
Mathieu Chartier590fee92013-09-13 13:46:47 -07001424}
1425
Mathieu Chartierd68ac702014-02-11 14:50:51 -08001426bool Heap::IsNonDiscontinuousSpaceHeapAddress(const mirror::Object* obj) const {
1427 return FindContinuousSpaceFromObject(obj, true) != nullptr;
1428}
1429
Mathieu Chartier15d34022014-02-26 17:16:38 -08001430bool Heap::IsValidContinuousSpaceObjectAddress(const mirror::Object* obj) const {
1431 if (obj == nullptr || !IsAligned<kObjectAlignment>(obj)) {
1432 return false;
1433 }
1434 for (const auto& space : continuous_spaces_) {
1435 if (space->HasAddress(obj)) {
1436 return true;
1437 }
1438 }
1439 return false;
Elliott Hughesa2501992011-08-26 19:39:54 -07001440}
1441
Ian Rogersef7d42f2014-01-06 12:55:46 -08001442bool Heap::IsLiveObjectLocked(mirror::Object* obj, bool search_allocation_stack,
Mathieu Chartier0f72e412013-09-06 16:40:01 -07001443 bool search_live_stack, bool sorted) {
Mathieu Chartier938a03b2014-01-16 15:10:31 -08001444 if (UNLIKELY(!IsAligned<kObjectAlignment>(obj))) {
1445 return false;
1446 }
1447 if (bump_pointer_space_ != nullptr && bump_pointer_space_->HasAddress(obj)) {
Mathieu Chartier4e305412014-02-19 10:54:44 -08001448 mirror::Class* klass = obj->GetClass<kVerifyNone>();
Mathieu Chartier938a03b2014-01-16 15:10:31 -08001449 if (obj == klass) {
Mathieu Chartier9be9a7a2014-01-24 14:07:33 -08001450 // This case happens for java.lang.Class.
Mathieu Chartier938a03b2014-01-16 15:10:31 -08001451 return true;
1452 }
1453 return VerifyClassClass(klass) && IsLiveObjectLocked(klass);
1454 } else if (temp_space_ != nullptr && temp_space_->HasAddress(obj)) {
Mathieu Chartier4e305412014-02-19 10:54:44 -08001455 // If we are in the allocated region of the temp space, then we are probably live (e.g. during
1456 // a GC). When a GC isn't running End() - Begin() is 0 which means no objects are contained.
1457 return temp_space_->Contains(obj);
Ian Rogers1d54e732013-05-02 21:10:01 -07001458 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001459 if (region_space_ != nullptr && region_space_->HasAddress(obj)) {
1460 return true;
1461 }
Mathieu Chartierf082d3c2013-07-29 17:04:07 -07001462 space::ContinuousSpace* c_space = FindContinuousSpaceFromObject(obj, true);
Mathieu Chartierbbd695c2014-04-16 09:48:48 -07001463 space::DiscontinuousSpace* d_space = nullptr;
Mathieu Chartier938a03b2014-01-16 15:10:31 -08001464 if (c_space != nullptr) {
Mathieu Chartierf082d3c2013-07-29 17:04:07 -07001465 if (c_space->GetLiveBitmap()->Test(obj)) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001466 return true;
1467 }
1468 } else {
Mathieu Chartierf082d3c2013-07-29 17:04:07 -07001469 d_space = FindDiscontinuousSpaceFromObject(obj, true);
Mathieu Chartier938a03b2014-01-16 15:10:31 -08001470 if (d_space != nullptr) {
Mathieu Chartierbbd695c2014-04-16 09:48:48 -07001471 if (d_space->GetLiveBitmap()->Test(obj)) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001472 return true;
1473 }
1474 }
1475 }
Mathieu Chartierf082d3c2013-07-29 17:04:07 -07001476 // This is covering the allocation/live stack swapping that is done without mutators suspended.
Mathieu Chartier0f72e412013-09-06 16:40:01 -07001477 for (size_t i = 0; i < (sorted ? 1 : 5); ++i) {
1478 if (i > 0) {
1479 NanoSleep(MsToNs(10));
Ian Rogers1d54e732013-05-02 21:10:01 -07001480 }
Mathieu Chartier0f72e412013-09-06 16:40:01 -07001481 if (search_allocation_stack) {
1482 if (sorted) {
Mathieu Chartier407f7022014-02-18 14:37:05 -08001483 if (allocation_stack_->ContainsSorted(obj)) {
Mathieu Chartier0f72e412013-09-06 16:40:01 -07001484 return true;
1485 }
Mathieu Chartier407f7022014-02-18 14:37:05 -08001486 } else if (allocation_stack_->Contains(obj)) {
Mathieu Chartier0f72e412013-09-06 16:40:01 -07001487 return true;
1488 }
1489 }
1490
1491 if (search_live_stack) {
1492 if (sorted) {
Mathieu Chartier407f7022014-02-18 14:37:05 -08001493 if (live_stack_->ContainsSorted(obj)) {
Mathieu Chartier0f72e412013-09-06 16:40:01 -07001494 return true;
1495 }
Mathieu Chartier407f7022014-02-18 14:37:05 -08001496 } else if (live_stack_->Contains(obj)) {
Mathieu Chartier0f72e412013-09-06 16:40:01 -07001497 return true;
1498 }
1499 }
Ian Rogers1d54e732013-05-02 21:10:01 -07001500 }
Mathieu Chartierf082d3c2013-07-29 17:04:07 -07001501 // We need to check the bitmaps again since there is a race where we mark something as live and
1502 // then clear the stack containing it.
Mathieu Chartier938a03b2014-01-16 15:10:31 -08001503 if (c_space != nullptr) {
Mathieu Chartierf082d3c2013-07-29 17:04:07 -07001504 if (c_space->GetLiveBitmap()->Test(obj)) {
1505 return true;
1506 }
1507 } else {
1508 d_space = FindDiscontinuousSpaceFromObject(obj, true);
Mathieu Chartierbbd695c2014-04-16 09:48:48 -07001509 if (d_space != nullptr && d_space->GetLiveBitmap()->Test(obj)) {
Mathieu Chartierf082d3c2013-07-29 17:04:07 -07001510 return true;
1511 }
1512 }
Ian Rogers1d54e732013-05-02 21:10:01 -07001513 return false;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001514}
1515
Mathieu Chartier4c13a3f2014-07-14 14:57:16 -07001516std::string Heap::DumpSpaces() const {
1517 std::ostringstream oss;
1518 DumpSpaces(oss);
1519 return oss.str();
1520}
1521
1522void Heap::DumpSpaces(std::ostream& stream) const {
Mathieu Chartier02e25112013-08-14 16:14:24 -07001523 for (const auto& space : continuous_spaces_) {
Mathieu Chartiera8e8f9c2014-04-09 14:51:05 -07001524 accounting::ContinuousSpaceBitmap* live_bitmap = space->GetLiveBitmap();
1525 accounting::ContinuousSpaceBitmap* mark_bitmap = space->GetMarkBitmap();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001526 stream << space << " " << *space << "\n";
1527 if (live_bitmap != nullptr) {
1528 stream << live_bitmap << " " << *live_bitmap << "\n";
1529 }
1530 if (mark_bitmap != nullptr) {
1531 stream << mark_bitmap << " " << *mark_bitmap << "\n";
1532 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001533 }
Mathieu Chartier02e25112013-08-14 16:14:24 -07001534 for (const auto& space : discontinuous_spaces_) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001535 stream << space << " " << *space << "\n";
Mathieu Chartier128c52c2012-10-16 14:12:41 -07001536 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001537}
1538
Ian Rogersef7d42f2014-01-06 12:55:46 -08001539void Heap::VerifyObjectBody(mirror::Object* obj) {
Stephen Hines22c6a812014-07-16 11:03:43 -07001540 if (verify_object_mode_ == kVerifyObjectModeDisabled) {
1541 return;
1542 }
1543
Mathieu Chartier0f72e412013-09-06 16:40:01 -07001544 // Ignore early dawn of the universe verifications.
Ian Rogers3e5cf302014-05-20 16:40:37 -07001545 if (UNLIKELY(static_cast<size_t>(num_bytes_allocated_.LoadRelaxed()) < 10 * KB)) {
Ian Rogers62d6c772013-02-27 08:32:07 -08001546 return;
1547 }
Roland Levillain14d90572015-07-16 10:52:26 +01001548 CHECK_ALIGNED(obj, kObjectAlignment) << "Object isn't aligned";
Ian Rogersb0fa5dc2014-04-28 16:47:08 -07001549 mirror::Class* c = obj->GetFieldObject<mirror::Class, kVerifyNone>(mirror::Object::ClassOffset());
Mathieu Chartier4e305412014-02-19 10:54:44 -08001550 CHECK(c != nullptr) << "Null class in object " << obj;
Roland Levillain14d90572015-07-16 10:52:26 +01001551 CHECK_ALIGNED(c, kObjectAlignment) << "Class " << c << " not aligned in object " << obj;
Mathieu Chartier938a03b2014-01-16 15:10:31 -08001552 CHECK(VerifyClassClass(c));
Mathieu Chartier0325e622012-09-05 14:22:51 -07001553
Mathieu Chartier4e305412014-02-19 10:54:44 -08001554 if (verify_object_mode_ > kVerifyObjectModeFast) {
1555 // Note: the bitmap tests below are racy since we don't hold the heap bitmap lock.
Mathieu Chartier4c13a3f2014-07-14 14:57:16 -07001556 CHECK(IsLiveObjectLocked(obj)) << "Object is dead " << obj << "\n" << DumpSpaces();
Mathieu Chartierdcf8d722012-08-02 14:55:54 -07001557 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001558}
1559
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001560void Heap::VerificationCallback(mirror::Object* obj, void* arg) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001561 reinterpret_cast<Heap*>(arg)->VerifyObjectBody(obj);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001562}
1563
1564void Heap::VerifyHeap() {
Ian Rogers50b35e22012-10-04 10:09:15 -07001565 ReaderMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07001566 GetLiveBitmap()->Walk(Heap::VerificationCallback, this);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001567}
1568
Mathieu Chartiere76e70f2014-05-02 16:35:37 -07001569void Heap::RecordFree(uint64_t freed_objects, int64_t freed_bytes) {
Mathieu Chartier601276a2014-03-20 15:12:30 -07001570 // Use signed comparison since freed bytes can be negative when background compaction foreground
1571 // transitions occurs. This is caused by the moving objects from a bump pointer space to a
1572 // free list backed space typically increasing memory footprint due to padding and binning.
Ian Rogers3e5cf302014-05-20 16:40:37 -07001573 DCHECK_LE(freed_bytes, static_cast<int64_t>(num_bytes_allocated_.LoadRelaxed()));
Mathieu Chartiere76e70f2014-05-02 16:35:37 -07001574 // Note: This relies on 2s complement for handling negative freed_bytes.
Ian Rogers3e5cf302014-05-20 16:40:37 -07001575 num_bytes_allocated_.FetchAndSubSequentiallyConsistent(static_cast<ssize_t>(freed_bytes));
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07001576 if (Runtime::Current()->HasStatsEnabled()) {
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07001577 RuntimeStats* thread_stats = Thread::Current()->GetStats();
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001578 thread_stats->freed_objects += freed_objects;
Elliott Hughes307f75d2011-10-12 18:04:40 -07001579 thread_stats->freed_bytes += freed_bytes;
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001580 // TODO: Do this concurrently.
1581 RuntimeStats* global_stats = Runtime::Current()->GetStats();
1582 global_stats->freed_objects += freed_objects;
1583 global_stats->freed_bytes += freed_bytes;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07001584 }
Carl Shapiro58551df2011-07-24 03:09:51 -07001585}
1586
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07001587void Heap::RecordFreeRevoke() {
1588 // Subtract num_bytes_freed_revoke_ from num_bytes_allocated_ to cancel out the
1589 // the ahead-of-time, bulk counting of bytes allocated in rosalloc thread-local buffers.
1590 // If there's a concurrent revoke, ok to not necessarily reset num_bytes_freed_revoke_
1591 // all the way to zero exactly as the remainder will be subtracted at the next GC.
1592 size_t bytes_freed = num_bytes_freed_revoke_.LoadSequentiallyConsistent();
1593 CHECK_GE(num_bytes_freed_revoke_.FetchAndSubSequentiallyConsistent(bytes_freed),
1594 bytes_freed) << "num_bytes_freed_revoke_ underflow";
1595 CHECK_GE(num_bytes_allocated_.FetchAndSubSequentiallyConsistent(bytes_freed),
1596 bytes_freed) << "num_bytes_allocated_ underflow";
1597 GetCurrentGcIteration()->SetFreedRevoke(bytes_freed);
1598}
1599
Zuo Wangf37a88b2014-07-10 04:26:41 -07001600space::RosAllocSpace* Heap::GetRosAllocSpace(gc::allocator::RosAlloc* rosalloc) const {
1601 for (const auto& space : continuous_spaces_) {
1602 if (space->AsContinuousSpace()->IsRosAllocSpace()) {
1603 if (space->AsContinuousSpace()->AsRosAllocSpace()->GetRosAlloc() == rosalloc) {
1604 return space->AsContinuousSpace()->AsRosAllocSpace();
1605 }
1606 }
1607 }
1608 return nullptr;
1609}
1610
Mathieu Chartiera4f6af92015-08-11 17:35:25 -07001611mirror::Object* Heap::AllocateInternalWithGc(Thread* self,
1612 AllocatorType allocator,
1613 size_t alloc_size,
1614 size_t* bytes_allocated,
Ian Rogers6fac4472014-02-25 17:01:10 -08001615 size_t* usable_size,
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07001616 size_t* bytes_tl_bulk_allocated,
Mathieu Chartierc528dba2013-11-26 12:00:11 -08001617 mirror::Class** klass) {
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001618 bool was_default_allocator = allocator == GetCurrentAllocator();
Mathieu Chartierf4f38432014-09-03 11:21:08 -07001619 // Make sure there is no pending exception since we may need to throw an OOME.
1620 self->AssertNoPendingException();
Mathieu Chartierc528dba2013-11-26 12:00:11 -08001621 DCHECK(klass != nullptr);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001622 StackHandleScope<1> hs(self);
1623 HandleWrapper<mirror::Class> h(hs.NewHandleWrapper(klass));
1624 klass = nullptr; // Invalidate for safety.
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001625 // The allocation failed. If the GC is running, block until it completes, and then retry the
1626 // allocation.
Mathieu Chartier89a201e2014-05-02 10:27:26 -07001627 collector::GcType last_gc = WaitForGcToComplete(kGcCauseForAlloc, self);
Ian Rogers1d54e732013-05-02 21:10:01 -07001628 if (last_gc != collector::kGcTypeNone) {
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001629 // If we were the default allocator but the allocator changed while we were suspended,
1630 // abort the allocation.
1631 if (was_default_allocator && allocator != GetCurrentAllocator()) {
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001632 return nullptr;
1633 }
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001634 // A GC was in progress and we blocked, retry allocation now that memory has been freed.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001635 mirror::Object* ptr = TryToAllocate<true, false>(self, allocator, alloc_size, bytes_allocated,
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07001636 usable_size, bytes_tl_bulk_allocated);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001637 if (ptr != nullptr) {
1638 return ptr;
1639 }
Carl Shapiro69759ea2011-07-21 18:13:35 -07001640 }
1641
Mathieu Chartier5ae2c932014-03-28 16:22:20 -07001642 collector::GcType tried_type = next_gc_type_;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001643 const bool gc_ran =
1644 CollectGarbageInternal(tried_type, kGcCauseForAlloc, false) != collector::kGcTypeNone;
1645 if (was_default_allocator && allocator != GetCurrentAllocator()) {
1646 return nullptr;
1647 }
1648 if (gc_ran) {
1649 mirror::Object* ptr = TryToAllocate<true, false>(self, allocator, alloc_size, bytes_allocated,
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07001650 usable_size, bytes_tl_bulk_allocated);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001651 if (ptr != nullptr) {
1652 return ptr;
Mathieu Chartier5ae2c932014-03-28 16:22:20 -07001653 }
1654 }
1655
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001656 // Loop through our different Gc types and try to Gc until we get enough free memory.
Mathieu Chartiercbb2d202013-11-14 17:45:16 -08001657 for (collector::GcType gc_type : gc_plan_) {
Mathieu Chartier5ae2c932014-03-28 16:22:20 -07001658 if (gc_type == tried_type) {
1659 continue;
1660 }
Mathieu Chartiercbb2d202013-11-14 17:45:16 -08001661 // Attempt to run the collector, if we succeed, re-try the allocation.
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001662 const bool plan_gc_ran =
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001663 CollectGarbageInternal(gc_type, kGcCauseForAlloc, false) != collector::kGcTypeNone;
1664 if (was_default_allocator && allocator != GetCurrentAllocator()) {
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001665 return nullptr;
1666 }
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001667 if (plan_gc_ran) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001668 // Did we free sufficient memory for the allocation to succeed?
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001669 mirror::Object* ptr = TryToAllocate<true, false>(self, allocator, alloc_size, bytes_allocated,
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07001670 usable_size, bytes_tl_bulk_allocated);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001671 if (ptr != nullptr) {
1672 return ptr;
1673 }
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001674 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001675 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001676 // Allocations have failed after GCs; this is an exceptional state.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001677 // Try harder, growing the heap if necessary.
1678 mirror::Object* ptr = TryToAllocate<true, true>(self, allocator, alloc_size, bytes_allocated,
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07001679 usable_size, bytes_tl_bulk_allocated);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001680 if (ptr != nullptr) {
1681 return ptr;
Carl Shapiro69759ea2011-07-21 18:13:35 -07001682 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001683 // Most allocations should have succeeded by now, so the heap is really full, really fragmented,
1684 // or the requested size is really big. Do another GC, collecting SoftReferences this time. The
1685 // VM spec requires that all SoftReferences have been collected and cleared before throwing
1686 // OOME.
1687 VLOG(gc) << "Forcing collection of SoftReferences for " << PrettySize(alloc_size)
1688 << " allocation";
1689 // TODO: Run finalization, but this may cause more allocations to occur.
1690 // We don't need a WaitForGcToComplete here either.
1691 DCHECK(!gc_plan_.empty());
1692 CollectGarbageInternal(gc_plan_.back(), kGcCauseForAlloc, true);
1693 if (was_default_allocator && allocator != GetCurrentAllocator()) {
1694 return nullptr;
Mathieu Chartiercbb2d202013-11-14 17:45:16 -08001695 }
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07001696 ptr = TryToAllocate<true, true>(self, allocator, alloc_size, bytes_allocated, usable_size,
1697 bytes_tl_bulk_allocated);
Mathieu Chartier6a7824d2014-08-22 14:53:04 -07001698 if (ptr == nullptr) {
Zuo Wangf37a88b2014-07-10 04:26:41 -07001699 const uint64_t current_time = NanoTime();
Mathieu Chartier6a7824d2014-08-22 14:53:04 -07001700 switch (allocator) {
1701 case kAllocatorTypeRosAlloc:
1702 // Fall-through.
1703 case kAllocatorTypeDlMalloc: {
1704 if (use_homogeneous_space_compaction_for_oom_ &&
1705 current_time - last_time_homogeneous_space_compaction_by_oom_ >
1706 min_interval_homogeneous_space_compaction_by_oom_) {
1707 last_time_homogeneous_space_compaction_by_oom_ = current_time;
1708 HomogeneousSpaceCompactResult result = PerformHomogeneousSpaceCompact();
1709 switch (result) {
1710 case HomogeneousSpaceCompactResult::kSuccess:
1711 // If the allocation succeeded, we delayed an oom.
1712 ptr = TryToAllocate<true, true>(self, allocator, alloc_size, bytes_allocated,
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07001713 usable_size, bytes_tl_bulk_allocated);
Mathieu Chartier6a7824d2014-08-22 14:53:04 -07001714 if (ptr != nullptr) {
1715 count_delayed_oom_++;
1716 }
1717 break;
1718 case HomogeneousSpaceCompactResult::kErrorReject:
1719 // Reject due to disabled moving GC.
1720 break;
1721 case HomogeneousSpaceCompactResult::kErrorVMShuttingDown:
1722 // Throw OOM by default.
1723 break;
1724 default: {
Ian Rogers2c4257b2014-10-24 14:20:06 -07001725 UNIMPLEMENTED(FATAL) << "homogeneous space compaction result: "
1726 << static_cast<size_t>(result);
1727 UNREACHABLE();
Mathieu Chartier6a7824d2014-08-22 14:53:04 -07001728 }
Zuo Wangf37a88b2014-07-10 04:26:41 -07001729 }
Mathieu Chartier6a7824d2014-08-22 14:53:04 -07001730 // Always print that we ran homogeneous space compation since this can cause jank.
1731 VLOG(heap) << "Ran heap homogeneous space compaction, "
1732 << " requested defragmentation "
1733 << count_requested_homogeneous_space_compaction_.LoadSequentiallyConsistent()
1734 << " performed defragmentation "
1735 << count_performed_homogeneous_space_compaction_.LoadSequentiallyConsistent()
1736 << " ignored homogeneous space compaction "
1737 << count_ignored_homogeneous_space_compaction_.LoadSequentiallyConsistent()
1738 << " delayed count = "
1739 << count_delayed_oom_.LoadSequentiallyConsistent();
Zuo Wangf37a88b2014-07-10 04:26:41 -07001740 }
Mathieu Chartier6a7824d2014-08-22 14:53:04 -07001741 break;
Zuo Wangf37a88b2014-07-10 04:26:41 -07001742 }
Mathieu Chartier6a7824d2014-08-22 14:53:04 -07001743 case kAllocatorTypeNonMoving: {
1744 // Try to transition the heap if the allocation failure was due to the space being full.
1745 if (!IsOutOfMemoryOnAllocation<false>(allocator, alloc_size)) {
1746 // If we aren't out of memory then the OOM was probably from the non moving space being
1747 // full. Attempt to disable compaction and turn the main space into a non moving space.
1748 DisableMovingGc();
1749 // If we are still a moving GC then something must have caused the transition to fail.
1750 if (IsMovingGc(collector_type_)) {
1751 MutexLock mu(self, *gc_complete_lock_);
1752 // If we couldn't disable moving GC, just throw OOME and return null.
1753 LOG(WARNING) << "Couldn't disable moving GC with disable GC count "
1754 << disable_moving_gc_count_;
1755 } else {
1756 LOG(WARNING) << "Disabled moving GC due to the non moving space being full";
1757 ptr = TryToAllocate<true, true>(self, allocator, alloc_size, bytes_allocated,
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07001758 usable_size, bytes_tl_bulk_allocated);
Mathieu Chartier6a7824d2014-08-22 14:53:04 -07001759 }
1760 }
1761 break;
1762 }
1763 default: {
1764 // Do nothing for others allocators.
1765 }
Zuo Wangf37a88b2014-07-10 04:26:41 -07001766 }
1767 }
1768 // If the allocation hasn't succeeded by this point, throw an OOM error.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001769 if (ptr == nullptr) {
Hiroshi Yamauchi654dd482014-07-09 12:54:32 -07001770 ThrowOutOfMemoryError(self, alloc_size, allocator);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001771 }
Mathieu Chartiercbb2d202013-11-14 17:45:16 -08001772 return ptr;
Carl Shapiro69759ea2011-07-21 18:13:35 -07001773}
1774
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001775void Heap::SetTargetHeapUtilization(float target) {
1776 DCHECK_GT(target, 0.0f); // asserted in Java code
1777 DCHECK_LT(target, 1.0f);
1778 target_utilization_ = target;
1779}
1780
Ian Rogers1d54e732013-05-02 21:10:01 -07001781size_t Heap::GetObjectsAllocated() const {
Mathieu Chartier4f55e222015-09-04 13:26:21 -07001782 Thread* const self = Thread::Current();
Mathieu Chartierb43390c2015-05-12 10:47:11 -07001783 ScopedThreadStateChange tsc(self, kWaitingForGetObjectsAllocated);
Mathieu Chartierb43390c2015-05-12 10:47:11 -07001784 // Need SuspendAll here to prevent lock violation if RosAlloc does it during InspectAll.
Mathieu Chartier4f55e222015-09-04 13:26:21 -07001785 ScopedSuspendAll ssa(__FUNCTION__);
1786 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Ian Rogers1d54e732013-05-02 21:10:01 -07001787 size_t total = 0;
Mathieu Chartier4f55e222015-09-04 13:26:21 -07001788 for (space::AllocSpace* space : alloc_spaces_) {
1789 total += space->GetObjectsAllocated();
Ian Rogers1d54e732013-05-02 21:10:01 -07001790 }
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001791 return total;
1792}
1793
Mathieu Chartierdd162fb2014-08-06 17:06:33 -07001794uint64_t Heap::GetObjectsAllocatedEver() const {
Mathieu Chartier4edd8472015-06-01 10:47:36 -07001795 uint64_t total = GetObjectsFreedEver();
1796 // If we are detached, we can't use GetObjectsAllocated since we can't change thread states.
1797 if (Thread::Current() != nullptr) {
1798 total += GetObjectsAllocated();
1799 }
1800 return total;
Ian Rogers1d54e732013-05-02 21:10:01 -07001801}
1802
Mathieu Chartierdd162fb2014-08-06 17:06:33 -07001803uint64_t Heap::GetBytesAllocatedEver() const {
Mathieu Chartier692fafd2013-11-29 17:24:40 -08001804 return GetBytesFreedEver() + GetBytesAllocated();
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001805}
1806
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07001807class InstanceCounter {
1808 public:
Mathieu Chartiera4f6af92015-08-11 17:35:25 -07001809 InstanceCounter(const std::vector<mirror::Class*>& classes,
1810 bool use_is_assignable_from,
1811 uint64_t* counts)
Mathieu Chartier90443472015-07-16 20:32:27 -07001812 SHARED_REQUIRES(Locks::mutator_lock_)
Mathieu Chartiera4f6af92015-08-11 17:35:25 -07001813 : classes_(classes), use_is_assignable_from_(use_is_assignable_from), counts_(counts) {}
1814
Mathieu Chartier412c7fc2014-02-07 12:18:39 -08001815 static void Callback(mirror::Object* obj, void* arg)
Mathieu Chartier90443472015-07-16 20:32:27 -07001816 SHARED_REQUIRES(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Mathieu Chartier412c7fc2014-02-07 12:18:39 -08001817 InstanceCounter* instance_counter = reinterpret_cast<InstanceCounter*>(arg);
1818 mirror::Class* instance_class = obj->GetClass();
1819 CHECK(instance_class != nullptr);
1820 for (size_t i = 0; i < instance_counter->classes_.size(); ++i) {
Mathieu Chartierf1820852015-07-10 13:19:51 -07001821 mirror::Class* klass = instance_counter->classes_[i];
Mathieu Chartier412c7fc2014-02-07 12:18:39 -08001822 if (instance_counter->use_is_assignable_from_) {
Mathieu Chartierf1820852015-07-10 13:19:51 -07001823 if (klass != nullptr && klass->IsAssignableFrom(instance_class)) {
Mathieu Chartier412c7fc2014-02-07 12:18:39 -08001824 ++instance_counter->counts_[i];
Elliott Hughesec0f83d2013-01-15 16:54:08 -08001825 }
Mathieu Chartierf1820852015-07-10 13:19:51 -07001826 } else if (instance_class == klass) {
Mathieu Chartier412c7fc2014-02-07 12:18:39 -08001827 ++instance_counter->counts_[i];
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07001828 }
1829 }
1830 }
1831
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001832 private:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001833 const std::vector<mirror::Class*>& classes_;
Elliott Hughesec0f83d2013-01-15 16:54:08 -08001834 bool use_is_assignable_from_;
1835 uint64_t* const counts_;
Elliott Hughesec0f83d2013-01-15 16:54:08 -08001836 DISALLOW_COPY_AND_ASSIGN(InstanceCounter);
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07001837};
1838
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001839void Heap::CountInstances(const std::vector<mirror::Class*>& classes, bool use_is_assignable_from,
Elliott Hughesec0f83d2013-01-15 16:54:08 -08001840 uint64_t* counts) {
Elliott Hughesec0f83d2013-01-15 16:54:08 -08001841 InstanceCounter counter(classes, use_is_assignable_from, counts);
Mathieu Chartier412c7fc2014-02-07 12:18:39 -08001842 VisitObjects(InstanceCounter::Callback, &counter);
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07001843}
1844
Elliott Hughes3b78c942013-01-15 17:35:41 -08001845class InstanceCollector {
1846 public:
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001847 InstanceCollector(mirror::Class* c, int32_t max_count, std::vector<mirror::Object*>& instances)
Mathieu Chartier90443472015-07-16 20:32:27 -07001848 SHARED_REQUIRES(Locks::mutator_lock_)
Elliott Hughes3b78c942013-01-15 17:35:41 -08001849 : class_(c), max_count_(max_count), instances_(instances) {
1850 }
Mathieu Chartier412c7fc2014-02-07 12:18:39 -08001851 static void Callback(mirror::Object* obj, void* arg)
Mathieu Chartier90443472015-07-16 20:32:27 -07001852 SHARED_REQUIRES(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Mathieu Chartier412c7fc2014-02-07 12:18:39 -08001853 DCHECK(arg != nullptr);
1854 InstanceCollector* instance_collector = reinterpret_cast<InstanceCollector*>(arg);
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07001855 if (obj->GetClass() == instance_collector->class_) {
Mathieu Chartier412c7fc2014-02-07 12:18:39 -08001856 if (instance_collector->max_count_ == 0 ||
1857 instance_collector->instances_.size() < instance_collector->max_count_) {
1858 instance_collector->instances_.push_back(obj);
Elliott Hughes3b78c942013-01-15 17:35:41 -08001859 }
1860 }
1861 }
1862
1863 private:
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07001864 const mirror::Class* const class_;
1865 const uint32_t max_count_;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001866 std::vector<mirror::Object*>& instances_;
Elliott Hughes3b78c942013-01-15 17:35:41 -08001867 DISALLOW_COPY_AND_ASSIGN(InstanceCollector);
1868};
1869
Mathieu Chartiera4f6af92015-08-11 17:35:25 -07001870void Heap::GetInstances(mirror::Class* c,
1871 int32_t max_count,
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001872 std::vector<mirror::Object*>& instances) {
Elliott Hughes3b78c942013-01-15 17:35:41 -08001873 InstanceCollector collector(c, max_count, instances);
Mathieu Chartier412c7fc2014-02-07 12:18:39 -08001874 VisitObjects(&InstanceCollector::Callback, &collector);
Elliott Hughes3b78c942013-01-15 17:35:41 -08001875}
1876
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001877class ReferringObjectsFinder {
1878 public:
Mathieu Chartiera4f6af92015-08-11 17:35:25 -07001879 ReferringObjectsFinder(mirror::Object* object,
1880 int32_t max_count,
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001881 std::vector<mirror::Object*>& referring_objects)
Mathieu Chartier90443472015-07-16 20:32:27 -07001882 SHARED_REQUIRES(Locks::mutator_lock_)
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001883 : object_(object), max_count_(max_count), referring_objects_(referring_objects) {
1884 }
1885
Mathieu Chartier412c7fc2014-02-07 12:18:39 -08001886 static void Callback(mirror::Object* obj, void* arg)
Mathieu Chartier90443472015-07-16 20:32:27 -07001887 SHARED_REQUIRES(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Mathieu Chartier412c7fc2014-02-07 12:18:39 -08001888 reinterpret_cast<ReferringObjectsFinder*>(arg)->operator()(obj);
1889 }
1890
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001891 // For bitmap Visit.
1892 // TODO: Fix lock analysis to not use NO_THREAD_SAFETY_ANALYSIS, requires support for
1893 // annotalysis on visitors.
Mathieu Chartier0e54cd02014-03-20 12:41:23 -07001894 void operator()(mirror::Object* o) const NO_THREAD_SAFETY_ANALYSIS {
Mathieu Chartier059ef3d2015-08-18 13:54:21 -07001895 o->VisitReferences(*this, VoidFunctor());
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001896 }
1897
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -07001898 // For Object::VisitReferences.
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001899 void operator()(mirror::Object* obj, MemberOffset offset, bool is_static ATTRIBUTE_UNUSED) const
Mathieu Chartier90443472015-07-16 20:32:27 -07001900 SHARED_REQUIRES(Locks::mutator_lock_) {
Ian Rogersb0fa5dc2014-04-28 16:47:08 -07001901 mirror::Object* ref = obj->GetFieldObject<mirror::Object>(offset);
Mathieu Chartier407f7022014-02-18 14:37:05 -08001902 if (ref == object_ && (max_count_ == 0 || referring_objects_.size() < max_count_)) {
1903 referring_objects_.push_back(obj);
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001904 }
1905 }
1906
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001907 void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root ATTRIBUTE_UNUSED)
1908 const {}
1909 void VisitRoot(mirror::CompressedReference<mirror::Object>* root ATTRIBUTE_UNUSED) const {}
1910
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001911 private:
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07001912 const mirror::Object* const object_;
1913 const uint32_t max_count_;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001914 std::vector<mirror::Object*>& referring_objects_;
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001915 DISALLOW_COPY_AND_ASSIGN(ReferringObjectsFinder);
1916};
1917
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001918void Heap::GetReferringObjects(mirror::Object* o, int32_t max_count,
1919 std::vector<mirror::Object*>& referring_objects) {
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001920 ReferringObjectsFinder finder(o, max_count, referring_objects);
Mathieu Chartier412c7fc2014-02-07 12:18:39 -08001921 VisitObjects(&ReferringObjectsFinder::Callback, &finder);
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001922}
1923
Ian Rogers30fab402012-01-23 15:43:46 -08001924void Heap::CollectGarbage(bool clear_soft_references) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001925 // Even if we waited for a GC we still need to do another GC since weaks allocated during the
1926 // last GC will not have necessarily been cleared.
Mathieu Chartier7bf82af2013-12-06 16:51:45 -08001927 CollectGarbageInternal(gc_plan_.back(), kGcCauseExplicit, clear_soft_references);
Carl Shapiro69759ea2011-07-21 18:13:35 -07001928}
1929
Mathieu Chartierdb00eaf2015-08-31 17:10:05 -07001930bool Heap::SupportHomogeneousSpaceCompactAndCollectorTransitions() const {
1931 return main_space_backup_.get() != nullptr && main_space_ != nullptr &&
1932 foreground_collector_type_ == kCollectorTypeCMS;
1933}
1934
Zuo Wangf37a88b2014-07-10 04:26:41 -07001935HomogeneousSpaceCompactResult Heap::PerformHomogeneousSpaceCompact() {
1936 Thread* self = Thread::Current();
1937 // Inc requested homogeneous space compaction.
1938 count_requested_homogeneous_space_compaction_++;
1939 // Store performed homogeneous space compaction at a new request arrival.
Zuo Wangf37a88b2014-07-10 04:26:41 -07001940 ScopedThreadStateChange tsc(self, kWaitingPerformingGc);
1941 Locks::mutator_lock_->AssertNotHeld(self);
1942 {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001943 ScopedThreadStateChange tsc2(self, kWaitingForGcToComplete);
Zuo Wangf37a88b2014-07-10 04:26:41 -07001944 MutexLock mu(self, *gc_complete_lock_);
1945 // Ensure there is only one GC at a time.
1946 WaitForGcToCompleteLocked(kGcCauseHomogeneousSpaceCompact, self);
1947 // Homogeneous space compaction is a copying transition, can't run it if the moving GC disable count
1948 // is non zero.
Mathieu Chartier6a7824d2014-08-22 14:53:04 -07001949 // If the collector type changed to something which doesn't benefit from homogeneous space compaction,
Zuo Wangf37a88b2014-07-10 04:26:41 -07001950 // exit.
Mathieu Chartier6a7824d2014-08-22 14:53:04 -07001951 if (disable_moving_gc_count_ != 0 || IsMovingGc(collector_type_) ||
1952 !main_space_->CanMoveObjects()) {
Mathieu Chartierdb00eaf2015-08-31 17:10:05 -07001953 return kErrorReject;
1954 }
1955 if (!SupportHomogeneousSpaceCompactAndCollectorTransitions()) {
1956 return kErrorUnsupported;
Zuo Wangf37a88b2014-07-10 04:26:41 -07001957 }
1958 collector_type_running_ = kCollectorTypeHomogeneousSpaceCompact;
1959 }
1960 if (Runtime::Current()->IsShuttingDown(self)) {
1961 // Don't allow heap transitions to happen if the runtime is shutting down since these can
1962 // cause objects to get finalized.
1963 FinishGC(self, collector::kGcTypeNone);
1964 return HomogeneousSpaceCompactResult::kErrorVMShuttingDown;
1965 }
Mathieu Chartier4f55e222015-09-04 13:26:21 -07001966 collector::GarbageCollector* collector;
1967 {
1968 ScopedSuspendAll ssa(__FUNCTION__);
1969 uint64_t start_time = NanoTime();
1970 // Launch compaction.
1971 space::MallocSpace* to_space = main_space_backup_.release();
1972 space::MallocSpace* from_space = main_space_;
1973 to_space->GetMemMap()->Protect(PROT_READ | PROT_WRITE);
1974 const uint64_t space_size_before_compaction = from_space->Size();
1975 AddSpace(to_space);
1976 // Make sure that we will have enough room to copy.
1977 CHECK_GE(to_space->GetFootprintLimit(), from_space->GetFootprintLimit());
1978 collector = Compact(to_space, from_space, kGcCauseHomogeneousSpaceCompact);
1979 const uint64_t space_size_after_compaction = to_space->Size();
1980 main_space_ = to_space;
1981 main_space_backup_.reset(from_space);
1982 RemoveSpace(from_space);
1983 SetSpaceAsDefault(main_space_); // Set as default to reset the proper dlmalloc space.
1984 // Update performed homogeneous space compaction count.
1985 count_performed_homogeneous_space_compaction_++;
1986 // Print statics log and resume all threads.
1987 uint64_t duration = NanoTime() - start_time;
1988 VLOG(heap) << "Heap homogeneous space compaction took " << PrettyDuration(duration) << " size: "
1989 << PrettySize(space_size_before_compaction) << " -> "
1990 << PrettySize(space_size_after_compaction) << " compact-ratio: "
1991 << std::fixed << static_cast<double>(space_size_after_compaction) /
1992 static_cast<double>(space_size_before_compaction);
1993 }
Zuo Wangf37a88b2014-07-10 04:26:41 -07001994 // Finish GC.
Mathieu Chartier3cf22532015-07-09 15:15:09 -07001995 reference_processor_->EnqueueClearedReferences(self);
Zuo Wangf37a88b2014-07-10 04:26:41 -07001996 GrowForUtilization(semi_space_collector_);
Hiroshi Yamauchie4d99872015-02-26 12:53:45 -08001997 LogGC(kGcCauseHomogeneousSpaceCompact, collector);
Zuo Wangf37a88b2014-07-10 04:26:41 -07001998 FinishGC(self, collector::kGcTypeFull);
Mathieu Chartier598302a2015-09-23 14:52:39 -07001999 {
2000 ScopedObjectAccess soa(self);
2001 soa.Vm()->UnloadNativeLibraries();
2002 }
Zuo Wangf37a88b2014-07-10 04:26:41 -07002003 return HomogeneousSpaceCompactResult::kSuccess;
2004}
2005
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08002006void Heap::TransitionCollector(CollectorType collector_type) {
2007 if (collector_type == collector_type_) {
2008 return;
2009 }
Hiroshi Yamauchia4adbfd2014-02-04 18:12:17 -08002010 VLOG(heap) << "TransitionCollector: " << static_cast<int>(collector_type_)
2011 << " -> " << static_cast<int>(collector_type);
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08002012 uint64_t start_time = NanoTime();
Ian Rogers3e5cf302014-05-20 16:40:37 -07002013 uint32_t before_allocated = num_bytes_allocated_.LoadSequentiallyConsistent();
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002014 Runtime* const runtime = Runtime::Current();
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002015 Thread* const self = Thread::Current();
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08002016 ScopedThreadStateChange tsc(self, kWaitingPerformingGc);
2017 Locks::mutator_lock_->AssertNotHeld(self);
Mathieu Chartier1d27b342014-01-28 12:51:09 -08002018 // Busy wait until we can GC (StartGC can fail if we have a non-zero
2019 // compacting_gc_disable_count_, this should rarely occurs).
Mathieu Chartierd5a89ee2014-01-31 09:55:13 -08002020 for (;;) {
Mathieu Chartiercaa82d62014-02-02 16:51:17 -08002021 {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002022 ScopedThreadStateChange tsc2(self, kWaitingForGcToComplete);
Mathieu Chartiercaa82d62014-02-02 16:51:17 -08002023 MutexLock mu(self, *gc_complete_lock_);
2024 // Ensure there is only one GC at a time.
Mathieu Chartier89a201e2014-05-02 10:27:26 -07002025 WaitForGcToCompleteLocked(kGcCauseCollectorTransition, self);
Mathieu Chartiere4927f62014-08-23 13:56:03 -07002026 // Currently we only need a heap transition if we switch from a moving collector to a
2027 // non-moving one, or visa versa.
2028 const bool copying_transition = IsMovingGc(collector_type_) != IsMovingGc(collector_type);
Mathieu Chartierb38d4832014-04-10 10:56:55 -07002029 // If someone else beat us to it and changed the collector before we could, exit.
2030 // This is safe to do before the suspend all since we set the collector_type_running_ before
2031 // we exit the loop. If another thread attempts to do the heap transition before we exit,
2032 // then it would get blocked on WaitForGcToCompleteLocked.
2033 if (collector_type == collector_type_) {
2034 return;
2035 }
Mathieu Chartiercaa82d62014-02-02 16:51:17 -08002036 // GC can be disabled if someone has a used GetPrimitiveArrayCritical but not yet released.
2037 if (!copying_transition || disable_moving_gc_count_ == 0) {
2038 // TODO: Not hard code in semi-space collector?
2039 collector_type_running_ = copying_transition ? kCollectorTypeSS : collector_type;
2040 break;
2041 }
Mathieu Chartierd5a89ee2014-01-31 09:55:13 -08002042 }
Mathieu Chartiercaa82d62014-02-02 16:51:17 -08002043 usleep(1000);
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08002044 }
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002045 if (runtime->IsShuttingDown(self)) {
Hiroshi Yamauchia6a8d142014-05-12 16:57:33 -07002046 // Don't allow heap transitions to happen if the runtime is shutting down since these can
2047 // cause objects to get finalized.
2048 FinishGC(self, collector::kGcTypeNone);
2049 return;
2050 }
Hiroshi Yamauchie4d99872015-02-26 12:53:45 -08002051 collector::GarbageCollector* collector = nullptr;
Mathieu Chartier4f55e222015-09-04 13:26:21 -07002052 {
2053 ScopedSuspendAll ssa(__FUNCTION__);
2054 switch (collector_type) {
2055 case kCollectorTypeSS: {
2056 if (!IsMovingGc(collector_type_)) {
2057 // Create the bump pointer space from the backup space.
2058 CHECK(main_space_backup_ != nullptr);
2059 std::unique_ptr<MemMap> mem_map(main_space_backup_->ReleaseMemMap());
2060 // We are transitioning from non moving GC -> moving GC, since we copied from the bump
2061 // pointer space last transition it will be protected.
2062 CHECK(mem_map != nullptr);
Hiroshi Yamauchic1276c82014-08-07 10:27:17 -07002063 mem_map->Protect(PROT_READ | PROT_WRITE);
Mathieu Chartier4f55e222015-09-04 13:26:21 -07002064 bump_pointer_space_ = space::BumpPointerSpace::CreateFromMemMap("Bump pointer space",
2065 mem_map.release());
2066 AddSpace(bump_pointer_space_);
2067 collector = Compact(bump_pointer_space_, main_space_, kGcCauseCollectorTransition);
2068 // Use the now empty main space mem map for the bump pointer temp space.
2069 mem_map.reset(main_space_->ReleaseMemMap());
2070 // Unset the pointers just in case.
2071 if (dlmalloc_space_ == main_space_) {
2072 dlmalloc_space_ = nullptr;
2073 } else if (rosalloc_space_ == main_space_) {
2074 rosalloc_space_ = nullptr;
2075 }
2076 // Remove the main space so that we don't try to trim it, this doens't work for debug
2077 // builds since RosAlloc attempts to read the magic number from a protected page.
2078 RemoveSpace(main_space_);
2079 RemoveRememberedSet(main_space_);
2080 delete main_space_; // Delete the space since it has been removed.
2081 main_space_ = nullptr;
2082 RemoveRememberedSet(main_space_backup_.get());
2083 main_space_backup_.reset(nullptr); // Deletes the space.
2084 temp_space_ = space::BumpPointerSpace::CreateFromMemMap("Bump pointer space 2",
2085 mem_map.release());
2086 AddSpace(temp_space_);
Hiroshi Yamauchic1276c82014-08-07 10:27:17 -07002087 }
Mathieu Chartier4f55e222015-09-04 13:26:21 -07002088 break;
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08002089 }
Mathieu Chartier4f55e222015-09-04 13:26:21 -07002090 case kCollectorTypeMS:
2091 // Fall through.
2092 case kCollectorTypeCMS: {
2093 if (IsMovingGc(collector_type_)) {
2094 CHECK(temp_space_ != nullptr);
2095 std::unique_ptr<MemMap> mem_map(temp_space_->ReleaseMemMap());
2096 RemoveSpace(temp_space_);
2097 temp_space_ = nullptr;
2098 mem_map->Protect(PROT_READ | PROT_WRITE);
2099 CreateMainMallocSpace(mem_map.get(),
2100 kDefaultInitialSize,
2101 std::min(mem_map->Size(), growth_limit_),
2102 mem_map->Size());
2103 mem_map.release();
2104 // Compact to the main space from the bump pointer space, don't need to swap semispaces.
2105 AddSpace(main_space_);
2106 collector = Compact(main_space_, bump_pointer_space_, kGcCauseCollectorTransition);
2107 mem_map.reset(bump_pointer_space_->ReleaseMemMap());
2108 RemoveSpace(bump_pointer_space_);
2109 bump_pointer_space_ = nullptr;
2110 const char* name = kUseRosAlloc ? kRosAllocSpaceName[1] : kDlMallocSpaceName[1];
2111 // Temporarily unprotect the backup mem map so rosalloc can write the debug magic number.
2112 if (kIsDebugBuild && kUseRosAlloc) {
2113 mem_map->Protect(PROT_READ | PROT_WRITE);
2114 }
2115 main_space_backup_.reset(CreateMallocSpaceFromMemMap(
2116 mem_map.get(),
2117 kDefaultInitialSize,
2118 std::min(mem_map->Size(), growth_limit_),
2119 mem_map->Size(),
2120 name,
2121 true));
2122 if (kIsDebugBuild && kUseRosAlloc) {
2123 mem_map->Protect(PROT_NONE);
2124 }
2125 mem_map.release();
2126 }
2127 break;
2128 }
2129 default: {
2130 LOG(FATAL) << "Attempted to transition to invalid collector type "
2131 << static_cast<size_t>(collector_type);
2132 break;
2133 }
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08002134 }
Mathieu Chartier4f55e222015-09-04 13:26:21 -07002135 ChangeCollector(collector_type);
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08002136 }
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08002137 // Can't call into java code with all threads suspended.
Mathieu Chartier3cf22532015-07-09 15:15:09 -07002138 reference_processor_->EnqueueClearedReferences(self);
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08002139 uint64_t duration = NanoTime() - start_time;
Mathieu Chartierafe49982014-03-27 10:55:04 -07002140 GrowForUtilization(semi_space_collector_);
Hiroshi Yamauchie4d99872015-02-26 12:53:45 -08002141 DCHECK(collector != nullptr);
2142 LogGC(kGcCauseCollectorTransition, collector);
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08002143 FinishGC(self, collector::kGcTypeFull);
Mathieu Chartier598302a2015-09-23 14:52:39 -07002144 {
2145 ScopedObjectAccess soa(self);
2146 soa.Vm()->UnloadNativeLibraries();
2147 }
Ian Rogers3e5cf302014-05-20 16:40:37 -07002148 int32_t after_allocated = num_bytes_allocated_.LoadSequentiallyConsistent();
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08002149 int32_t delta_allocated = before_allocated - after_allocated;
Mathieu Chartier19d46b42014-06-17 15:04:40 -07002150 std::string saved_str;
2151 if (delta_allocated >= 0) {
2152 saved_str = " saved at least " + PrettySize(delta_allocated);
2153 } else {
2154 saved_str = " expanded " + PrettySize(-delta_allocated);
2155 }
Mathieu Chartier98172a62014-09-02 12:33:25 -07002156 VLOG(heap) << "Heap transition to " << process_state_ << " took "
Mathieu Chartier19d46b42014-06-17 15:04:40 -07002157 << PrettyDuration(duration) << saved_str;
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08002158}
2159
Mathieu Chartier0de9f732013-11-22 17:58:48 -08002160void Heap::ChangeCollector(CollectorType collector_type) {
Mathieu Chartier7bf82af2013-12-06 16:51:45 -08002161 // TODO: Only do this with all mutators suspended to avoid races.
2162 if (collector_type != collector_type_) {
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002163 if (collector_type == kCollectorTypeMC) {
2164 // Don't allow mark compact unless support is compiled in.
2165 CHECK(kMarkCompactSupport);
2166 }
Mathieu Chartier7bf82af2013-12-06 16:51:45 -08002167 collector_type_ = collector_type;
2168 gc_plan_.clear();
2169 switch (collector_type_) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002170 case kCollectorTypeCC: {
2171 gc_plan_.push_back(collector::kGcTypeFull);
2172 if (use_tlab_) {
2173 ChangeAllocator(kAllocatorTypeRegionTLAB);
2174 } else {
2175 ChangeAllocator(kAllocatorTypeRegion);
2176 }
2177 break;
2178 }
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002179 case kCollectorTypeMC: // Fall-through.
Hiroshi Yamauchi3e417802014-03-20 12:03:02 -07002180 case kCollectorTypeSS: // Fall-through.
Hiroshi Yamauchi6f4ffe42014-01-13 12:30:44 -08002181 case kCollectorTypeGSS: {
Mathieu Chartier7bf82af2013-12-06 16:51:45 -08002182 gc_plan_.push_back(collector::kGcTypeFull);
Mathieu Chartier692fafd2013-11-29 17:24:40 -08002183 if (use_tlab_) {
2184 ChangeAllocator(kAllocatorTypeTLAB);
2185 } else {
2186 ChangeAllocator(kAllocatorTypeBumpPointer);
2187 }
Mathieu Chartier7bf82af2013-12-06 16:51:45 -08002188 break;
2189 }
2190 case kCollectorTypeMS: {
Mathieu Chartier7bf82af2013-12-06 16:51:45 -08002191 gc_plan_.push_back(collector::kGcTypeSticky);
2192 gc_plan_.push_back(collector::kGcTypePartial);
2193 gc_plan_.push_back(collector::kGcTypeFull);
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08002194 ChangeAllocator(kUseRosAlloc ? kAllocatorTypeRosAlloc : kAllocatorTypeDlMalloc);
Mathieu Chartier7bf82af2013-12-06 16:51:45 -08002195 break;
2196 }
2197 case kCollectorTypeCMS: {
Mathieu Chartier7bf82af2013-12-06 16:51:45 -08002198 gc_plan_.push_back(collector::kGcTypeSticky);
2199 gc_plan_.push_back(collector::kGcTypePartial);
2200 gc_plan_.push_back(collector::kGcTypeFull);
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08002201 ChangeAllocator(kUseRosAlloc ? kAllocatorTypeRosAlloc : kAllocatorTypeDlMalloc);
Mathieu Chartier7bf82af2013-12-06 16:51:45 -08002202 break;
2203 }
2204 default: {
Ian Rogers2c4257b2014-10-24 14:20:06 -07002205 UNIMPLEMENTED(FATAL);
2206 UNREACHABLE();
Mathieu Chartier7bf82af2013-12-06 16:51:45 -08002207 }
Mathieu Chartier0de9f732013-11-22 17:58:48 -08002208 }
Hiroshi Yamauchi3e417802014-03-20 12:03:02 -07002209 if (IsGcConcurrent()) {
Mathieu Chartier7bf82af2013-12-06 16:51:45 -08002210 concurrent_start_bytes_ =
2211 std::max(max_allowed_footprint_, kMinConcurrentRemainingBytes) - kMinConcurrentRemainingBytes;
2212 } else {
2213 concurrent_start_bytes_ = std::numeric_limits<size_t>::max();
Mathieu Chartier0de9f732013-11-22 17:58:48 -08002214 }
2215 }
2216}
2217
Mathieu Chartier85a43c02014-01-07 17:59:00 -08002218// Special compacting collector which uses sub-optimal bin packing to reduce zygote space size.
Ian Rogers6fac4472014-02-25 17:01:10 -08002219class ZygoteCompactingCollector FINAL : public collector::SemiSpace {
Mathieu Chartier85a43c02014-01-07 17:59:00 -08002220 public:
Roland Levillain3887c462015-08-12 18:15:42 +01002221 ZygoteCompactingCollector(gc::Heap* heap, bool is_running_on_memory_tool)
Evgenii Stepanov1e133742015-05-20 12:30:59 -07002222 : SemiSpace(heap, false, "zygote collector"),
2223 bin_live_bitmap_(nullptr),
2224 bin_mark_bitmap_(nullptr),
2225 is_running_on_memory_tool_(is_running_on_memory_tool) {}
Mathieu Chartier85a43c02014-01-07 17:59:00 -08002226
2227 void BuildBins(space::ContinuousSpace* space) {
2228 bin_live_bitmap_ = space->GetLiveBitmap();
2229 bin_mark_bitmap_ = space->GetMarkBitmap();
2230 BinContext context;
2231 context.prev_ = reinterpret_cast<uintptr_t>(space->Begin());
2232 context.collector_ = this;
2233 WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
2234 // Note: This requires traversing the space in increasing order of object addresses.
2235 bin_live_bitmap_->Walk(Callback, reinterpret_cast<void*>(&context));
2236 // Add the last bin which spans after the last object to the end of the space.
2237 AddBin(reinterpret_cast<uintptr_t>(space->End()) - context.prev_, context.prev_);
2238 }
2239
2240 private:
2241 struct BinContext {
2242 uintptr_t prev_; // The end of the previous object.
2243 ZygoteCompactingCollector* collector_;
2244 };
2245 // Maps from bin sizes to locations.
2246 std::multimap<size_t, uintptr_t> bins_;
2247 // Live bitmap of the space which contains the bins.
Mathieu Chartiera8e8f9c2014-04-09 14:51:05 -07002248 accounting::ContinuousSpaceBitmap* bin_live_bitmap_;
Mathieu Chartier85a43c02014-01-07 17:59:00 -08002249 // Mark bitmap of the space which contains the bins.
Mathieu Chartiera8e8f9c2014-04-09 14:51:05 -07002250 accounting::ContinuousSpaceBitmap* bin_mark_bitmap_;
Evgenii Stepanov1e133742015-05-20 12:30:59 -07002251 const bool is_running_on_memory_tool_;
Mathieu Chartier85a43c02014-01-07 17:59:00 -08002252
2253 static void Callback(mirror::Object* obj, void* arg)
Mathieu Chartier90443472015-07-16 20:32:27 -07002254 SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartier85a43c02014-01-07 17:59:00 -08002255 DCHECK(arg != nullptr);
2256 BinContext* context = reinterpret_cast<BinContext*>(arg);
2257 ZygoteCompactingCollector* collector = context->collector_;
2258 uintptr_t object_addr = reinterpret_cast<uintptr_t>(obj);
2259 size_t bin_size = object_addr - context->prev_;
2260 // Add the bin consisting of the end of the previous object to the start of the current object.
2261 collector->AddBin(bin_size, context->prev_);
2262 context->prev_ = object_addr + RoundUp(obj->SizeOf(), kObjectAlignment);
2263 }
2264
2265 void AddBin(size_t size, uintptr_t position) {
Evgenii Stepanov1e133742015-05-20 12:30:59 -07002266 if (is_running_on_memory_tool_) {
2267 MEMORY_TOOL_MAKE_DEFINED(reinterpret_cast<void*>(position), size);
2268 }
Mathieu Chartier85a43c02014-01-07 17:59:00 -08002269 if (size != 0) {
2270 bins_.insert(std::make_pair(size, position));
2271 }
2272 }
2273
Mathieu Chartiera4f6af92015-08-11 17:35:25 -07002274 virtual bool ShouldSweepSpace(space::ContinuousSpace* space ATTRIBUTE_UNUSED) const {
Mathieu Chartier85a43c02014-01-07 17:59:00 -08002275 // Don't sweep any spaces since we probably blasted the internal accounting of the free list
2276 // allocator.
2277 return false;
2278 }
2279
2280 virtual mirror::Object* MarkNonForwardedObject(mirror::Object* obj)
Mathieu Chartier90443472015-07-16 20:32:27 -07002281 REQUIRES(Locks::heap_bitmap_lock_, Locks::mutator_lock_) {
Hiroshi Yamauchi8711d1f2015-03-13 16:48:55 -07002282 size_t obj_size = obj->SizeOf();
2283 size_t alloc_size = RoundUp(obj_size, kObjectAlignment);
Mathieu Chartier5dc08a62014-01-10 10:10:23 -08002284 mirror::Object* forward_address;
Mathieu Chartier85a43c02014-01-07 17:59:00 -08002285 // Find the smallest bin which we can move obj in.
Hiroshi Yamauchi8711d1f2015-03-13 16:48:55 -07002286 auto it = bins_.lower_bound(alloc_size);
Mathieu Chartier85a43c02014-01-07 17:59:00 -08002287 if (it == bins_.end()) {
2288 // No available space in the bins, place it in the target space instead (grows the zygote
2289 // space).
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07002290 size_t bytes_allocated, dummy;
Hiroshi Yamauchi8711d1f2015-03-13 16:48:55 -07002291 forward_address = to_space_->Alloc(self_, alloc_size, &bytes_allocated, nullptr, &dummy);
Mathieu Chartier85a43c02014-01-07 17:59:00 -08002292 if (to_space_live_bitmap_ != nullptr) {
2293 to_space_live_bitmap_->Set(forward_address);
Mathieu Chartier938a03b2014-01-16 15:10:31 -08002294 } else {
2295 GetHeap()->GetNonMovingSpace()->GetLiveBitmap()->Set(forward_address);
2296 GetHeap()->GetNonMovingSpace()->GetMarkBitmap()->Set(forward_address);
Mathieu Chartier85a43c02014-01-07 17:59:00 -08002297 }
2298 } else {
2299 size_t size = it->first;
2300 uintptr_t pos = it->second;
2301 bins_.erase(it); // Erase the old bin which we replace with the new smaller bin.
2302 forward_address = reinterpret_cast<mirror::Object*>(pos);
2303 // Set the live and mark bits so that sweeping system weaks works properly.
2304 bin_live_bitmap_->Set(forward_address);
2305 bin_mark_bitmap_->Set(forward_address);
Hiroshi Yamauchi8711d1f2015-03-13 16:48:55 -07002306 DCHECK_GE(size, alloc_size);
2307 // Add a new bin with the remaining space.
2308 AddBin(size - alloc_size, pos + alloc_size);
Mathieu Chartier85a43c02014-01-07 17:59:00 -08002309 }
Hiroshi Yamauchi8711d1f2015-03-13 16:48:55 -07002310 // Copy the object over to its new location. Don't use alloc_size to avoid valgrind error.
2311 memcpy(reinterpret_cast<void*>(forward_address), obj, obj_size);
Hiroshi Yamauchi624468c2014-03-31 15:14:47 -07002312 if (kUseBakerOrBrooksReadBarrier) {
2313 obj->AssertReadBarrierPointer();
2314 if (kUseBrooksReadBarrier) {
2315 DCHECK_EQ(forward_address->GetReadBarrierPointer(), obj);
2316 forward_address->SetReadBarrierPointer(forward_address);
2317 }
2318 forward_address->AssertReadBarrierPointer();
Hiroshi Yamauchi9d04a202014-01-31 13:35:49 -08002319 }
Mathieu Chartier85a43c02014-01-07 17:59:00 -08002320 return forward_address;
2321 }
2322};
2323
Mathieu Chartiera1602f22014-01-13 17:19:19 -08002324void Heap::UnBindBitmaps() {
Mathieu Chartierf5997b42014-06-20 10:37:54 -07002325 TimingLogger::ScopedTiming t("UnBindBitmaps", GetCurrentGcIteration()->GetTimings());
Mathieu Chartiera1602f22014-01-13 17:19:19 -08002326 for (const auto& space : GetContinuousSpaces()) {
2327 if (space->IsContinuousMemMapAllocSpace()) {
2328 space::ContinuousMemMapAllocSpace* alloc_space = space->AsContinuousMemMapAllocSpace();
2329 if (alloc_space->HasBoundBitmaps()) {
2330 alloc_space->UnBindBitmaps();
2331 }
2332 }
2333 }
2334}
2335
Mathieu Chartiercc236d72012-07-20 10:29:05 -07002336void Heap::PreZygoteFork() {
Mathieu Chartierfaed9952015-03-31 16:28:53 -07002337 if (!HasZygoteSpace()) {
2338 // We still want to GC in case there is some unreachable non moving objects that could cause a
2339 // suboptimal bin packing when we compact the zygote space.
2340 CollectGarbageInternal(collector::kGcTypeFull, kGcCauseBackground, false);
2341 }
Ian Rogers81d425b2012-09-27 16:03:43 -07002342 Thread* self = Thread::Current();
2343 MutexLock mu(self, zygote_creation_lock_);
Mathieu Chartiercc236d72012-07-20 10:29:05 -07002344 // Try to see if we have any Zygote spaces.
Mathieu Chartiere4cab172014-08-19 18:24:04 -07002345 if (HasZygoteSpace()) {
Mathieu Chartiercc236d72012-07-20 10:29:05 -07002346 return;
2347 }
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002348 Runtime::Current()->GetInternTable()->AddNewTable();
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002349 Runtime::Current()->GetClassLinker()->MoveClassTableToPreZygote();
Mathieu Chartier590fee92013-09-13 13:46:47 -07002350 VLOG(heap) << "Starting PreZygoteFork";
Mathieu Chartier590fee92013-09-13 13:46:47 -07002351 // Trim the pages at the end of the non moving space.
2352 non_moving_space_->Trim();
Mathieu Chartier31f44142014-04-08 14:40:03 -07002353 // The end of the non-moving space may be protected, unprotect it so that we can copy the zygote
2354 // there.
Mathieu Chartier590fee92013-09-13 13:46:47 -07002355 non_moving_space_->GetMemMap()->Protect(PROT_READ | PROT_WRITE);
Mathieu Chartier6a7824d2014-08-22 14:53:04 -07002356 const bool same_space = non_moving_space_ == main_space_;
Mathieu Chartier31f44142014-04-08 14:40:03 -07002357 if (kCompactZygote) {
Hiroshi Yamauchia4adbfd2014-02-04 18:12:17 -08002358 // Temporarily disable rosalloc verification because the zygote
2359 // compaction will mess up the rosalloc internal metadata.
2360 ScopedDisableRosAllocVerification disable_rosalloc_verif(this);
Evgenii Stepanov1e133742015-05-20 12:30:59 -07002361 ZygoteCompactingCollector zygote_collector(this, is_running_on_memory_tool_);
Mathieu Chartier85a43c02014-01-07 17:59:00 -08002362 zygote_collector.BuildBins(non_moving_space_);
Mathieu Chartier50482232013-11-21 11:48:14 -08002363 // Create a new bump pointer space which we will compact into.
Mathieu Chartier590fee92013-09-13 13:46:47 -07002364 space::BumpPointerSpace target_space("zygote bump space", non_moving_space_->End(),
2365 non_moving_space_->Limit());
2366 // Compact the bump pointer space to a new zygote bump pointer space.
Mathieu Chartier31f44142014-04-08 14:40:03 -07002367 bool reset_main_space = false;
2368 if (IsMovingGc(collector_type_)) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002369 if (collector_type_ == kCollectorTypeCC) {
2370 zygote_collector.SetFromSpace(region_space_);
2371 } else {
2372 zygote_collector.SetFromSpace(bump_pointer_space_);
2373 }
Mathieu Chartier31f44142014-04-08 14:40:03 -07002374 } else {
2375 CHECK(main_space_ != nullptr);
Hiroshi Yamauchid04495e2015-03-11 19:09:07 -07002376 CHECK_NE(main_space_, non_moving_space_)
2377 << "Does not make sense to compact within the same space";
Mathieu Chartier31f44142014-04-08 14:40:03 -07002378 // Copy from the main space.
2379 zygote_collector.SetFromSpace(main_space_);
2380 reset_main_space = true;
2381 }
Mathieu Chartier85a43c02014-01-07 17:59:00 -08002382 zygote_collector.SetToSpace(&target_space);
Mathieu Chartier1b54f9c2014-04-30 16:45:02 -07002383 zygote_collector.SetSwapSemiSpaces(false);
Hiroshi Yamauchi6f4ffe42014-01-13 12:30:44 -08002384 zygote_collector.Run(kGcCauseCollectorTransition, false);
Mathieu Chartier31f44142014-04-08 14:40:03 -07002385 if (reset_main_space) {
2386 main_space_->GetMemMap()->Protect(PROT_READ | PROT_WRITE);
2387 madvise(main_space_->Begin(), main_space_->Capacity(), MADV_DONTNEED);
2388 MemMap* mem_map = main_space_->ReleaseMemMap();
2389 RemoveSpace(main_space_);
Mathieu Chartier96bcd452014-06-17 09:50:02 -07002390 space::Space* old_main_space = main_space_;
Mathieu Chartier0310da52014-12-01 13:40:48 -08002391 CreateMainMallocSpace(mem_map, kDefaultInitialSize, std::min(mem_map->Size(), growth_limit_),
2392 mem_map->Size());
Mathieu Chartier96bcd452014-06-17 09:50:02 -07002393 delete old_main_space;
Mathieu Chartier31f44142014-04-08 14:40:03 -07002394 AddSpace(main_space_);
2395 } else {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002396 if (collector_type_ == kCollectorTypeCC) {
2397 region_space_->GetMemMap()->Protect(PROT_READ | PROT_WRITE);
2398 } else {
2399 bump_pointer_space_->GetMemMap()->Protect(PROT_READ | PROT_WRITE);
2400 }
Mathieu Chartier31f44142014-04-08 14:40:03 -07002401 }
2402 if (temp_space_ != nullptr) {
2403 CHECK(temp_space_->IsEmpty());
2404 }
Mathieu Chartier10fb83a2014-06-15 15:15:43 -07002405 total_objects_freed_ever_ += GetCurrentGcIteration()->GetFreedObjects();
2406 total_bytes_freed_ever_ += GetCurrentGcIteration()->GetFreedBytes();
Mathieu Chartier590fee92013-09-13 13:46:47 -07002407 // Update the end and write out image.
2408 non_moving_space_->SetEnd(target_space.End());
2409 non_moving_space_->SetLimit(target_space.Limit());
Mathieu Chartierfaed9952015-03-31 16:28:53 -07002410 VLOG(heap) << "Create zygote space with size=" << non_moving_space_->Size() << " bytes";
Mathieu Chartier357e9be2012-08-01 11:00:14 -07002411 }
Mathieu Chartier6a7824d2014-08-22 14:53:04 -07002412 // Change the collector to the post zygote one.
Mathieu Chartier31f44142014-04-08 14:40:03 -07002413 ChangeCollector(foreground_collector_type_);
Mathieu Chartiera1602f22014-01-13 17:19:19 -08002414 // Save the old space so that we can remove it after we complete creating the zygote space.
2415 space::MallocSpace* old_alloc_space = non_moving_space_;
Mathieu Chartier590fee92013-09-13 13:46:47 -07002416 // Turn the current alloc space into a zygote space and obtain the new alloc space composed of
Mathieu Chartiera1602f22014-01-13 17:19:19 -08002417 // the remaining available space.
2418 // Remove the old space before creating the zygote space since creating the zygote space sets
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002419 // the old alloc space's bitmaps to null.
Mathieu Chartiera1602f22014-01-13 17:19:19 -08002420 RemoveSpace(old_alloc_space);
Hiroshi Yamauchi38e68e92014-03-07 13:59:08 -08002421 if (collector::SemiSpace::kUseRememberedSet) {
2422 // Sanity bound check.
2423 FindRememberedSetFromSpace(old_alloc_space)->AssertAllDirtyCardsAreWithinSpace();
2424 // Remove the remembered set for the now zygote space (the old
2425 // non-moving space). Note now that we have compacted objects into
2426 // the zygote space, the data in the remembered set is no longer
2427 // needed. The zygote space will instead have a mod-union table
2428 // from this point on.
2429 RemoveRememberedSet(old_alloc_space);
2430 }
Mathieu Chartier7247af52014-11-19 10:51:42 -08002431 // Remaining space becomes the new non moving space.
2432 zygote_space_ = old_alloc_space->CreateZygoteSpace(kNonMovingSpaceName, low_memory_mode_,
Mathieu Chartiere4cab172014-08-19 18:24:04 -07002433 &non_moving_space_);
Mathieu Chartierb363f662014-07-16 13:28:58 -07002434 CHECK(!non_moving_space_->CanMoveObjects());
2435 if (same_space) {
2436 main_space_ = non_moving_space_;
2437 SetSpaceAsDefault(main_space_);
2438 }
Mathieu Chartiera1602f22014-01-13 17:19:19 -08002439 delete old_alloc_space;
Mathieu Chartiere4cab172014-08-19 18:24:04 -07002440 CHECK(HasZygoteSpace()) << "Failed creating zygote space";
2441 AddSpace(zygote_space_);
Mathieu Chartier31f44142014-04-08 14:40:03 -07002442 non_moving_space_->SetFootprintLimit(non_moving_space_->Capacity());
2443 AddSpace(non_moving_space_);
Mathieu Chartier11409ae2013-09-23 11:49:36 -07002444 // Create the zygote space mod union table.
2445 accounting::ModUnionTable* mod_union_table =
Mathieu Chartiere4cab172014-08-19 18:24:04 -07002446 new accounting::ModUnionTableCardCache("zygote space mod-union table", this,
2447 zygote_space_);
Mathieu Chartier11409ae2013-09-23 11:49:36 -07002448 CHECK(mod_union_table != nullptr) << "Failed to create zygote space mod-union table";
Mathieu Chartiere4cab172014-08-19 18:24:04 -07002449 // Set all the cards in the mod-union table since we don't know which objects contain references
2450 // to large objects.
2451 mod_union_table->SetCards();
Mathieu Chartier11409ae2013-09-23 11:49:36 -07002452 AddModUnionTable(mod_union_table);
Mathieu Chartierf6c2a272015-06-03 17:32:42 -07002453 large_object_space_->SetAllLargeObjectsAsZygoteObjects(self);
Hiroshi Yamauchi38e68e92014-03-07 13:59:08 -08002454 if (collector::SemiSpace::kUseRememberedSet) {
Hiroshi Yamauchi38e68e92014-03-07 13:59:08 -08002455 // Add a new remembered set for the post-zygote non-moving space.
2456 accounting::RememberedSet* post_zygote_non_moving_space_rem_set =
2457 new accounting::RememberedSet("Post-zygote non-moving space remembered set", this,
2458 non_moving_space_);
2459 CHECK(post_zygote_non_moving_space_rem_set != nullptr)
2460 << "Failed to create post-zygote non-moving space remembered set";
2461 AddRememberedSet(post_zygote_non_moving_space_rem_set);
2462 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -07002463}
2464
Mathieu Chartier357e9be2012-08-01 11:00:14 -07002465void Heap::FlushAllocStack() {
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08002466 MarkAllocStackAsLive(allocation_stack_.get());
Mathieu Chartier357e9be2012-08-01 11:00:14 -07002467 allocation_stack_->Reset();
2468}
2469
Mathieu Chartiera8e8f9c2014-04-09 14:51:05 -07002470void Heap::MarkAllocStack(accounting::ContinuousSpaceBitmap* bitmap1,
2471 accounting::ContinuousSpaceBitmap* bitmap2,
Mathieu Chartierbbd695c2014-04-16 09:48:48 -07002472 accounting::LargeObjectBitmap* large_objects,
Ian Rogers1d54e732013-05-02 21:10:01 -07002473 accounting::ObjectStack* stack) {
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08002474 DCHECK(bitmap1 != nullptr);
2475 DCHECK(bitmap2 != nullptr);
Mathieu Chartiercb535da2015-01-23 13:50:03 -08002476 const auto* limit = stack->End();
2477 for (auto* it = stack->Begin(); it != limit; ++it) {
2478 const mirror::Object* obj = it->AsMirrorPtr();
Hiroshi Yamauchif5b0e202014-02-11 17:02:22 -08002479 if (!kUseThreadLocalAllocationStack || obj != nullptr) {
2480 if (bitmap1->HasAddress(obj)) {
2481 bitmap1->Set(obj);
2482 } else if (bitmap2->HasAddress(obj)) {
2483 bitmap2->Set(obj);
2484 } else {
Mathieu Chartier2dbe6272014-09-16 10:43:23 -07002485 DCHECK(large_objects != nullptr);
Hiroshi Yamauchif5b0e202014-02-11 17:02:22 -08002486 large_objects->Set(obj);
2487 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07002488 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07002489 }
2490}
2491
Mathieu Chartier590fee92013-09-13 13:46:47 -07002492void Heap::SwapSemiSpaces() {
Mathieu Chartier31f44142014-04-08 14:40:03 -07002493 CHECK(bump_pointer_space_ != nullptr);
2494 CHECK(temp_space_ != nullptr);
Mathieu Chartier590fee92013-09-13 13:46:47 -07002495 std::swap(bump_pointer_space_, temp_space_);
2496}
2497
Hiroshi Yamauchie4d99872015-02-26 12:53:45 -08002498collector::GarbageCollector* Heap::Compact(space::ContinuousMemMapAllocSpace* target_space,
2499 space::ContinuousMemMapAllocSpace* source_space,
2500 GcCause gc_cause) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07002501 CHECK(kMovingCollector);
Mathieu Chartier590fee92013-09-13 13:46:47 -07002502 if (target_space != source_space) {
Mathieu Chartier6f365cc2014-04-23 12:42:27 -07002503 // Don't swap spaces since this isn't a typical semi space collection.
2504 semi_space_collector_->SetSwapSemiSpaces(false);
Mathieu Chartier590fee92013-09-13 13:46:47 -07002505 semi_space_collector_->SetFromSpace(source_space);
2506 semi_space_collector_->SetToSpace(target_space);
Zuo Wangf37a88b2014-07-10 04:26:41 -07002507 semi_space_collector_->Run(gc_cause, false);
Hiroshi Yamauchie4d99872015-02-26 12:53:45 -08002508 return semi_space_collector_;
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002509 } else {
2510 CHECK(target_space->IsBumpPointerSpace())
2511 << "In-place compaction is only supported for bump pointer spaces";
2512 mark_compact_collector_->SetSpace(target_space->AsBumpPointerSpace());
2513 mark_compact_collector_->Run(kGcCauseCollectorTransition, false);
Hiroshi Yamauchie4d99872015-02-26 12:53:45 -08002514 return mark_compact_collector_;
Mathieu Chartier590fee92013-09-13 13:46:47 -07002515 }
2516}
Anwar Ghuloum67f99412013-08-12 14:19:48 -07002517
Mathieu Chartiera4f6af92015-08-11 17:35:25 -07002518collector::GcType Heap::CollectGarbageInternal(collector::GcType gc_type,
2519 GcCause gc_cause,
Ian Rogers1d54e732013-05-02 21:10:01 -07002520 bool clear_soft_references) {
Ian Rogers81d425b2012-09-27 16:03:43 -07002521 Thread* self = Thread::Current();
Mathieu Chartier590fee92013-09-13 13:46:47 -07002522 Runtime* runtime = Runtime::Current();
Mathieu Chartiercbb2d202013-11-14 17:45:16 -08002523 // If the heap can't run the GC, silently fail and return that no GC was run.
2524 switch (gc_type) {
Mathieu Chartiercbb2d202013-11-14 17:45:16 -08002525 case collector::kGcTypePartial: {
Mathieu Chartiere4cab172014-08-19 18:24:04 -07002526 if (!HasZygoteSpace()) {
Mathieu Chartiercbb2d202013-11-14 17:45:16 -08002527 return collector::kGcTypeNone;
2528 }
2529 break;
2530 }
2531 default: {
2532 // Other GC types don't have any special cases which makes them not runnable. The main case
2533 // here is full GC.
2534 }
2535 }
Mathieu Chartier65db8802012-11-20 12:36:46 -08002536 ScopedThreadStateChange tsc(self, kWaitingPerformingGc);
Ian Rogers81d425b2012-09-27 16:03:43 -07002537 Locks::mutator_lock_->AssertNotHeld(self);
Ian Rogers120f1c72012-09-28 17:17:10 -07002538 if (self->IsHandlingStackOverflow()) {
Mathieu Chartier50c138f2015-01-07 16:00:03 -08002539 // If we are throwing a stack overflow error we probably don't have enough remaining stack
2540 // space to run the GC.
2541 return collector::kGcTypeNone;
Ian Rogers120f1c72012-09-28 17:17:10 -07002542 }
Mathieu Chartierd5a89ee2014-01-31 09:55:13 -08002543 bool compacting_gc;
2544 {
2545 gc_complete_lock_->AssertNotHeld(self);
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002546 ScopedThreadStateChange tsc2(self, kWaitingForGcToComplete);
Mathieu Chartierd5a89ee2014-01-31 09:55:13 -08002547 MutexLock mu(self, *gc_complete_lock_);
2548 // Ensure there is only one GC at a time.
Mathieu Chartier89a201e2014-05-02 10:27:26 -07002549 WaitForGcToCompleteLocked(gc_cause, self);
Mathieu Chartier31f44142014-04-08 14:40:03 -07002550 compacting_gc = IsMovingGc(collector_type_);
Mathieu Chartierd5a89ee2014-01-31 09:55:13 -08002551 // GC can be disabled if someone has a used GetPrimitiveArrayCritical.
2552 if (compacting_gc && disable_moving_gc_count_ != 0) {
2553 LOG(WARNING) << "Skipping GC due to disable moving GC count " << disable_moving_gc_count_;
2554 return collector::kGcTypeNone;
2555 }
Mathieu Chartier51168372015-08-12 16:40:32 -07002556 if (gc_disabled_for_shutdown_) {
2557 return collector::kGcTypeNone;
2558 }
Mathieu Chartierd5a89ee2014-01-31 09:55:13 -08002559 collector_type_running_ = collector_type_;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002560 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07002561 if (gc_cause == kGcCauseForAlloc && runtime->HasStatsEnabled()) {
2562 ++runtime->GetStats()->gc_for_alloc_count;
2563 ++self->GetStats()->gc_for_alloc_count;
Mathieu Chartier2fde5332012-09-14 14:51:54 -07002564 }
Mathieu Chartiere2c2f6e2014-12-16 18:49:31 -08002565 const uint64_t bytes_allocated_before_gc = GetBytesAllocated();
2566 // Approximate heap size.
2567 ATRACE_INT("Heap size (KB)", bytes_allocated_before_gc / KB);
Mathieu Chartier65db8802012-11-20 12:36:46 -08002568
Ian Rogers1d54e732013-05-02 21:10:01 -07002569 DCHECK_LT(gc_type, collector::kGcTypeMax);
2570 DCHECK_NE(gc_type, collector::kGcTypeNone);
Anwar Ghuloum67f99412013-08-12 14:19:48 -07002571
Mathieu Chartier590fee92013-09-13 13:46:47 -07002572 collector::GarbageCollector* collector = nullptr;
Mathieu Chartier50482232013-11-21 11:48:14 -08002573 // TODO: Clean this up.
Mathieu Chartier1d27b342014-01-28 12:51:09 -08002574 if (compacting_gc) {
Mathieu Chartier692fafd2013-11-29 17:24:40 -08002575 DCHECK(current_allocator_ == kAllocatorTypeBumpPointer ||
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002576 current_allocator_ == kAllocatorTypeTLAB ||
2577 current_allocator_ == kAllocatorTypeRegion ||
2578 current_allocator_ == kAllocatorTypeRegionTLAB);
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002579 switch (collector_type_) {
2580 case kCollectorTypeSS:
2581 // Fall-through.
2582 case kCollectorTypeGSS:
2583 semi_space_collector_->SetFromSpace(bump_pointer_space_);
2584 semi_space_collector_->SetToSpace(temp_space_);
2585 semi_space_collector_->SetSwapSemiSpaces(true);
2586 collector = semi_space_collector_;
2587 break;
2588 case kCollectorTypeCC:
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002589 concurrent_copying_collector_->SetRegionSpace(region_space_);
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002590 collector = concurrent_copying_collector_;
2591 break;
2592 case kCollectorTypeMC:
2593 mark_compact_collector_->SetSpace(bump_pointer_space_);
2594 collector = mark_compact_collector_;
2595 break;
2596 default:
2597 LOG(FATAL) << "Invalid collector type " << static_cast<size_t>(collector_type_);
Hiroshi Yamauchid5307ec2014-03-27 21:07:51 -07002598 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002599 if (collector != mark_compact_collector_ && collector != concurrent_copying_collector_) {
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002600 temp_space_->GetMemMap()->Protect(PROT_READ | PROT_WRITE);
2601 CHECK(temp_space_->IsEmpty());
2602 }
2603 gc_type = collector::kGcTypeFull; // TODO: Not hard code this in.
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08002604 } else if (current_allocator_ == kAllocatorTypeRosAlloc ||
2605 current_allocator_ == kAllocatorTypeDlMalloc) {
Mathieu Chartierafe49982014-03-27 10:55:04 -07002606 collector = FindCollectorByGcType(gc_type);
Mathieu Chartier50482232013-11-21 11:48:14 -08002607 } else {
2608 LOG(FATAL) << "Invalid current allocator " << current_allocator_;
Mathieu Chartier590fee92013-09-13 13:46:47 -07002609 }
Mathieu Chartier08cef222014-10-22 17:18:34 -07002610 if (IsGcConcurrent()) {
2611 // Disable concurrent GC check so that we don't have spammy JNI requests.
2612 // This gets recalculated in GrowForUtilization. It is important that it is disabled /
2613 // calculated in the same thread so that there aren't any races that can cause it to become
2614 // permanantly disabled. b/17942071
2615 concurrent_start_bytes_ = std::numeric_limits<size_t>::max();
2616 }
Mathieu Chartier7bf82af2013-12-06 16:51:45 -08002617 CHECK(collector != nullptr)
Hiroshi Yamauchi3e417802014-03-20 12:03:02 -07002618 << "Could not find garbage collector with collector_type="
2619 << static_cast<size_t>(collector_type_) << " and gc_type=" << gc_type;
Mathieu Chartier6f365cc2014-04-23 12:42:27 -07002620 collector->Run(gc_cause, clear_soft_references || runtime->IsZygote());
Mathieu Chartier10fb83a2014-06-15 15:15:43 -07002621 total_objects_freed_ever_ += GetCurrentGcIteration()->GetFreedObjects();
2622 total_bytes_freed_ever_ += GetCurrentGcIteration()->GetFreedBytes();
Mathieu Chartiera5eae692014-12-17 17:56:03 -08002623 RequestTrim(self);
Mathieu Chartier39e32612013-11-12 16:28:05 -08002624 // Enqueue cleared references.
Mathieu Chartier3cf22532015-07-09 15:15:09 -07002625 reference_processor_->EnqueueClearedReferences(self);
Mathieu Chartier590fee92013-09-13 13:46:47 -07002626 // Grow the heap so that we know when to perform the next GC.
Mathieu Chartiere2c2f6e2014-12-16 18:49:31 -08002627 GrowForUtilization(collector, bytes_allocated_before_gc);
Hiroshi Yamauchie4d99872015-02-26 12:53:45 -08002628 LogGC(gc_cause, collector);
2629 FinishGC(self, gc_type);
2630 // Inform DDMS that a GC completed.
2631 Dbg::GcDidFinish();
Mathieu Chartier598302a2015-09-23 14:52:39 -07002632 // Unload native libraries for class unloading. We do this after calling FinishGC to prevent
2633 // deadlocks in case the JNI_OnUnload function does allocations.
2634 {
2635 ScopedObjectAccess soa(self);
2636 soa.Vm()->UnloadNativeLibraries();
2637 }
Hiroshi Yamauchie4d99872015-02-26 12:53:45 -08002638 return gc_type;
2639}
2640
2641void Heap::LogGC(GcCause gc_cause, collector::GarbageCollector* collector) {
Mathieu Chartier10fb83a2014-06-15 15:15:43 -07002642 const size_t duration = GetCurrentGcIteration()->GetDurationNs();
2643 const std::vector<uint64_t>& pause_times = GetCurrentGcIteration()->GetPauseTimes();
Mathieu Chartier62ab87b2014-04-28 12:22:07 -07002644 // Print the GC if it is an explicit GC (e.g. Runtime.gc()) or a slow GC
Mathieu Chartierf5997b42014-06-20 10:37:54 -07002645 // (mutator time blocked >= long_pause_log_threshold_).
Mathieu Chartier62ab87b2014-04-28 12:22:07 -07002646 bool log_gc = gc_cause == kGcCauseExplicit;
2647 if (!log_gc && CareAboutPauseTimes()) {
Mathieu Chartiere53225c2013-08-19 10:59:11 -07002648 // GC for alloc pauses the allocating thread, so consider it as a pause.
Mathieu Chartier62ab87b2014-04-28 12:22:07 -07002649 log_gc = duration > long_gc_log_threshold_ ||
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08002650 (gc_cause == kGcCauseForAlloc && duration > long_pause_log_threshold_);
Mathieu Chartier62ab87b2014-04-28 12:22:07 -07002651 for (uint64_t pause : pause_times) {
2652 log_gc = log_gc || pause >= long_pause_log_threshold_;
Mathieu Chartiere53225c2013-08-19 10:59:11 -07002653 }
Mathieu Chartier62ab87b2014-04-28 12:22:07 -07002654 }
2655 if (log_gc) {
2656 const size_t percent_free = GetPercentFree();
2657 const size_t current_heap_size = GetBytesAllocated();
2658 const size_t total_memory = GetTotalMemory();
2659 std::ostringstream pause_string;
2660 for (size_t i = 0; i < pause_times.size(); ++i) {
Hiroshi Yamauchie4d99872015-02-26 12:53:45 -08002661 pause_string << PrettyDuration((pause_times[i] / 1000) * 1000)
2662 << ((i != pause_times.size() - 1) ? "," : "");
Mathieu Chartiere53225c2013-08-19 10:59:11 -07002663 }
Mathieu Chartier62ab87b2014-04-28 12:22:07 -07002664 LOG(INFO) << gc_cause << " " << collector->GetName()
Mathieu Chartier10fb83a2014-06-15 15:15:43 -07002665 << " GC freed " << current_gc_iteration_.GetFreedObjects() << "("
2666 << PrettySize(current_gc_iteration_.GetFreedBytes()) << ") AllocSpace objects, "
2667 << current_gc_iteration_.GetFreedLargeObjects() << "("
2668 << PrettySize(current_gc_iteration_.GetFreedLargeObjectBytes()) << ") LOS objects, "
Mathieu Chartier62ab87b2014-04-28 12:22:07 -07002669 << percent_free << "% free, " << PrettySize(current_heap_size) << "/"
2670 << PrettySize(total_memory) << ", " << "paused " << pause_string.str()
2671 << " total " << PrettyDuration((duration / 1000) * 1000);
Ian Rogersc7dd2952014-10-21 23:31:19 -07002672 VLOG(heap) << Dumpable<TimingLogger>(*current_gc_iteration_.GetTimings());
Mathieu Chartier2b82db42012-11-14 17:29:05 -08002673 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002674}
Mathieu Chartiera6399032012-06-11 18:49:50 -07002675
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08002676void Heap::FinishGC(Thread* self, collector::GcType gc_type) {
2677 MutexLock mu(self, *gc_complete_lock_);
Mathieu Chartierd5a89ee2014-01-31 09:55:13 -08002678 collector_type_running_ = kCollectorTypeNone;
2679 if (gc_type != collector::kGcTypeNone) {
2680 last_gc_type_ = gc_type;
Hiroshi Yamauchia1c9f012015-04-02 10:18:12 -07002681
2682 // Update stats.
2683 ++gc_count_last_window_;
2684 if (running_collection_is_blocking_) {
2685 // If the currently running collection was a blocking one,
2686 // increment the counters and reset the flag.
2687 ++blocking_gc_count_;
2688 blocking_gc_time_ += GetCurrentGcIteration()->GetDurationNs();
2689 ++blocking_gc_count_last_window_;
2690 }
2691 // Update the gc count rate histograms if due.
2692 UpdateGcCountRateHistograms();
Mathieu Chartierd5a89ee2014-01-31 09:55:13 -08002693 }
Hiroshi Yamauchia1c9f012015-04-02 10:18:12 -07002694 // Reset.
2695 running_collection_is_blocking_ = false;
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08002696 // Wake anyone who may have been waiting for the GC to complete.
2697 gc_complete_cond_->Broadcast(self);
2698}
2699
Hiroshi Yamauchia1c9f012015-04-02 10:18:12 -07002700void Heap::UpdateGcCountRateHistograms() {
2701 // Invariant: if the time since the last update includes more than
2702 // one windows, all the GC runs (if > 0) must have happened in first
2703 // window because otherwise the update must have already taken place
2704 // at an earlier GC run. So, we report the non-first windows with
2705 // zero counts to the histograms.
2706 DCHECK_EQ(last_update_time_gc_count_rate_histograms_ % kGcCountRateHistogramWindowDuration, 0U);
2707 uint64_t now = NanoTime();
2708 DCHECK_GE(now, last_update_time_gc_count_rate_histograms_);
2709 uint64_t time_since_last_update = now - last_update_time_gc_count_rate_histograms_;
2710 uint64_t num_of_windows = time_since_last_update / kGcCountRateHistogramWindowDuration;
2711 if (time_since_last_update >= kGcCountRateHistogramWindowDuration) {
2712 // Record the first window.
2713 gc_count_rate_histogram_.AddValue(gc_count_last_window_ - 1); // Exclude the current run.
2714 blocking_gc_count_rate_histogram_.AddValue(running_collection_is_blocking_ ?
2715 blocking_gc_count_last_window_ - 1 : blocking_gc_count_last_window_);
2716 // Record the other windows (with zero counts).
2717 for (uint64_t i = 0; i < num_of_windows - 1; ++i) {
2718 gc_count_rate_histogram_.AddValue(0);
2719 blocking_gc_count_rate_histogram_.AddValue(0);
2720 }
2721 // Update the last update time and reset the counters.
2722 last_update_time_gc_count_rate_histograms_ =
2723 (now / kGcCountRateHistogramWindowDuration) * kGcCountRateHistogramWindowDuration;
2724 gc_count_last_window_ = 1; // Include the current run.
2725 blocking_gc_count_last_window_ = running_collection_is_blocking_ ? 1 : 0;
2726 }
2727 DCHECK_EQ(last_update_time_gc_count_rate_histograms_ % kGcCountRateHistogramWindowDuration, 0U);
2728}
2729
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002730class RootMatchesObjectVisitor : public SingleRootVisitor {
2731 public:
2732 explicit RootMatchesObjectVisitor(const mirror::Object* obj) : obj_(obj) { }
2733
2734 void VisitRoot(mirror::Object* root, const RootInfo& info)
Mathieu Chartier90443472015-07-16 20:32:27 -07002735 OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002736 if (root == obj_) {
2737 LOG(INFO) << "Object " << obj_ << " is a root " << info.ToString();
2738 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -07002739 }
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002740
2741 private:
2742 const mirror::Object* const obj_;
2743};
2744
Mathieu Chartierfd678be2012-08-30 14:50:54 -07002745
2746class ScanVisitor {
2747 public:
Brian Carlstromdf629502013-07-17 22:39:56 -07002748 void operator()(const mirror::Object* obj) const {
Mathieu Chartier0f72e412013-09-06 16:40:01 -07002749 LOG(ERROR) << "Would have rescanned object " << obj;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07002750 }
2751};
2752
Ian Rogers1d54e732013-05-02 21:10:01 -07002753// Verify a reference from an object.
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002754class VerifyReferenceVisitor : public SingleRootVisitor {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07002755 public:
Roland Levillain3887c462015-08-12 18:15:42 +01002756 VerifyReferenceVisitor(Heap* heap, Atomic<size_t>* fail_count, bool verify_referent)
Mathieu Chartier90443472015-07-16 20:32:27 -07002757 SHARED_REQUIRES(Locks::mutator_lock_, Locks::heap_bitmap_lock_)
Mathieu Chartier8ab7e782014-05-19 16:55:27 -07002758 : heap_(heap), fail_count_(fail_count), verify_referent_(verify_referent) {}
Ian Rogers1d54e732013-05-02 21:10:01 -07002759
Mathieu Chartier8ab7e782014-05-19 16:55:27 -07002760 size_t GetFailureCount() const {
Mathieu Chartiere9e55ac2014-05-21 17:48:25 -07002761 return fail_count_->LoadSequentiallyConsistent();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07002762 }
2763
Mathieu Chartierda7c6502015-07-23 16:01:26 -07002764 void operator()(mirror::Class* klass ATTRIBUTE_UNUSED, mirror::Reference* ref) const
Mathieu Chartier90443472015-07-16 20:32:27 -07002765 SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartier78f7b4c2014-05-06 10:57:27 -07002766 if (verify_referent_) {
Mathieu Chartier8ab7e782014-05-19 16:55:27 -07002767 VerifyReference(ref, ref->GetReferent(), mirror::Reference::ReferentOffset());
Mathieu Chartier78f7b4c2014-05-06 10:57:27 -07002768 }
Mathieu Chartier407f7022014-02-18 14:37:05 -08002769 }
2770
Mathieu Chartierda7c6502015-07-23 16:01:26 -07002771 void operator()(mirror::Object* obj, MemberOffset offset, bool is_static ATTRIBUTE_UNUSED) const
Mathieu Chartier90443472015-07-16 20:32:27 -07002772 SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartier8ab7e782014-05-19 16:55:27 -07002773 VerifyReference(obj, obj->GetFieldObject<mirror::Object>(offset), offset);
Mathieu Chartier407f7022014-02-18 14:37:05 -08002774 }
2775
Mathieu Chartier8ab7e782014-05-19 16:55:27 -07002776 bool IsLive(mirror::Object* obj) const NO_THREAD_SAFETY_ANALYSIS {
2777 return heap_->IsLiveObjectLocked(obj, true, false, true);
2778 }
2779
Mathieu Chartierda7c6502015-07-23 16:01:26 -07002780 void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root) const
2781 SHARED_REQUIRES(Locks::mutator_lock_) {
2782 if (!root->IsNull()) {
2783 VisitRoot(root);
2784 }
2785 }
2786 void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
2787 SHARED_REQUIRES(Locks::mutator_lock_) {
2788 const_cast<VerifyReferenceVisitor*>(this)->VisitRoot(
2789 root->AsMirrorPtr(), RootInfo(kRootVMInternal));
2790 }
2791
2792 virtual void VisitRoot(mirror::Object* root, const RootInfo& root_info) OVERRIDE
Mathieu Chartier90443472015-07-16 20:32:27 -07002793 SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002794 if (root == nullptr) {
2795 LOG(ERROR) << "Root is null with info " << root_info.GetType();
2796 } else if (!VerifyReference(nullptr, root, MemberOffset(0))) {
2797 LOG(ERROR) << "Root " << root << " is dead with type " << PrettyTypeOf(root)
Mathieu Chartiere34fa1d2015-01-14 14:55:47 -08002798 << " thread_id= " << root_info.GetThreadId() << " root_type= " << root_info.GetType();
Mathieu Chartier8ab7e782014-05-19 16:55:27 -07002799 }
2800 }
2801
2802 private:
Mathieu Chartier407f7022014-02-18 14:37:05 -08002803 // TODO: Fix the no thread safety analysis.
Mathieu Chartier8ab7e782014-05-19 16:55:27 -07002804 // Returns false on failure.
2805 bool VerifyReference(mirror::Object* obj, mirror::Object* ref, MemberOffset offset) const
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002806 NO_THREAD_SAFETY_ANALYSIS {
Mathieu Chartier938a03b2014-01-16 15:10:31 -08002807 if (ref == nullptr || IsLive(ref)) {
2808 // Verify that the reference is live.
Mathieu Chartier8ab7e782014-05-19 16:55:27 -07002809 return true;
Mathieu Chartier938a03b2014-01-16 15:10:31 -08002810 }
Mathieu Chartiere9e55ac2014-05-21 17:48:25 -07002811 if (fail_count_->FetchAndAddSequentiallyConsistent(1) == 0) {
Mathieu Chartier938a03b2014-01-16 15:10:31 -08002812 // Print message on only on first failure to prevent spam.
2813 LOG(ERROR) << "!!!!!!!!!!!!!!Heap corruption detected!!!!!!!!!!!!!!!!!!!";
Mathieu Chartier938a03b2014-01-16 15:10:31 -08002814 }
2815 if (obj != nullptr) {
Mathieu Chartier8ab7e782014-05-19 16:55:27 -07002816 // Only do this part for non roots.
Ian Rogers1d54e732013-05-02 21:10:01 -07002817 accounting::CardTable* card_table = heap_->GetCardTable();
2818 accounting::ObjectStack* alloc_stack = heap_->allocation_stack_.get();
2819 accounting::ObjectStack* live_stack = heap_->live_stack_.get();
Ian Rogers13735952014-10-08 12:43:28 -07002820 uint8_t* card_addr = card_table->CardFromAddr(obj);
Mathieu Chartier938a03b2014-01-16 15:10:31 -08002821 LOG(ERROR) << "Object " << obj << " references dead object " << ref << " at offset "
2822 << offset << "\n card value = " << static_cast<int>(*card_addr);
2823 if (heap_->IsValidObjectAddress(obj->GetClass())) {
2824 LOG(ERROR) << "Obj type " << PrettyTypeOf(obj);
2825 } else {
2826 LOG(ERROR) << "Object " << obj << " class(" << obj->GetClass() << ") not a heap address";
Mathieu Chartier0f72e412013-09-06 16:40:01 -07002827 }
Mathieu Chartier938a03b2014-01-16 15:10:31 -08002828
Mathieu Chartierb363f662014-07-16 13:28:58 -07002829 // Attempt to find the class inside of the recently freed objects.
Mathieu Chartier938a03b2014-01-16 15:10:31 -08002830 space::ContinuousSpace* ref_space = heap_->FindContinuousSpaceFromObject(ref, true);
2831 if (ref_space != nullptr && ref_space->IsMallocSpace()) {
2832 space::MallocSpace* space = ref_space->AsMallocSpace();
2833 mirror::Class* ref_class = space->FindRecentFreedObject(ref);
2834 if (ref_class != nullptr) {
2835 LOG(ERROR) << "Reference " << ref << " found as a recently freed object with class "
2836 << PrettyClass(ref_class);
Mathieu Chartier0f72e412013-09-06 16:40:01 -07002837 } else {
Mathieu Chartier938a03b2014-01-16 15:10:31 -08002838 LOG(ERROR) << "Reference " << ref << " not found as a recently freed object";
Mathieu Chartier0f72e412013-09-06 16:40:01 -07002839 }
Mathieu Chartier938a03b2014-01-16 15:10:31 -08002840 }
Mathieu Chartier0f72e412013-09-06 16:40:01 -07002841
Mathieu Chartier938a03b2014-01-16 15:10:31 -08002842 if (ref->GetClass() != nullptr && heap_->IsValidObjectAddress(ref->GetClass()) &&
2843 ref->GetClass()->IsClass()) {
2844 LOG(ERROR) << "Ref type " << PrettyTypeOf(ref);
2845 } else {
2846 LOG(ERROR) << "Ref " << ref << " class(" << ref->GetClass()
2847 << ") is not a valid heap address";
2848 }
2849
Ian Rogers13735952014-10-08 12:43:28 -07002850 card_table->CheckAddrIsInCardTable(reinterpret_cast<const uint8_t*>(obj));
Mathieu Chartier938a03b2014-01-16 15:10:31 -08002851 void* cover_begin = card_table->AddrFromCard(card_addr);
2852 void* cover_end = reinterpret_cast<void*>(reinterpret_cast<size_t>(cover_begin) +
2853 accounting::CardTable::kCardSize);
2854 LOG(ERROR) << "Card " << reinterpret_cast<void*>(card_addr) << " covers " << cover_begin
2855 << "-" << cover_end;
Mathieu Chartiera8e8f9c2014-04-09 14:51:05 -07002856 accounting::ContinuousSpaceBitmap* bitmap =
2857 heap_->GetLiveBitmap()->GetContinuousSpaceBitmap(obj);
Mathieu Chartier938a03b2014-01-16 15:10:31 -08002858
2859 if (bitmap == nullptr) {
2860 LOG(ERROR) << "Object " << obj << " has no bitmap";
Mathieu Chartier4e305412014-02-19 10:54:44 -08002861 if (!VerifyClassClass(obj->GetClass())) {
Mathieu Chartier938a03b2014-01-16 15:10:31 -08002862 LOG(ERROR) << "Object " << obj << " failed class verification!";
Mathieu Chartier0f72e412013-09-06 16:40:01 -07002863 }
Mathieu Chartier938a03b2014-01-16 15:10:31 -08002864 } else {
Ian Rogers1d54e732013-05-02 21:10:01 -07002865 // Print out how the object is live.
Mathieu Chartier938a03b2014-01-16 15:10:31 -08002866 if (bitmap->Test(obj)) {
Ian Rogers1d54e732013-05-02 21:10:01 -07002867 LOG(ERROR) << "Object " << obj << " found in live bitmap";
2868 }
Mathieu Chartier0f72e412013-09-06 16:40:01 -07002869 if (alloc_stack->Contains(const_cast<mirror::Object*>(obj))) {
Ian Rogers1d54e732013-05-02 21:10:01 -07002870 LOG(ERROR) << "Object " << obj << " found in allocation stack";
2871 }
Mathieu Chartier0f72e412013-09-06 16:40:01 -07002872 if (live_stack->Contains(const_cast<mirror::Object*>(obj))) {
Ian Rogers1d54e732013-05-02 21:10:01 -07002873 LOG(ERROR) << "Object " << obj << " found in live stack";
2874 }
Mathieu Chartier0f72e412013-09-06 16:40:01 -07002875 if (alloc_stack->Contains(const_cast<mirror::Object*>(ref))) {
2876 LOG(ERROR) << "Ref " << ref << " found in allocation stack";
2877 }
2878 if (live_stack->Contains(const_cast<mirror::Object*>(ref))) {
2879 LOG(ERROR) << "Ref " << ref << " found in live stack";
2880 }
Ian Rogers1d54e732013-05-02 21:10:01 -07002881 // Attempt to see if the card table missed the reference.
2882 ScanVisitor scan_visitor;
Ian Rogers13735952014-10-08 12:43:28 -07002883 uint8_t* byte_cover_begin = reinterpret_cast<uint8_t*>(card_table->AddrFromCard(card_addr));
Lei Li727b2942015-01-15 11:26:34 +08002884 card_table->Scan<false>(bitmap, byte_cover_begin,
2885 byte_cover_begin + accounting::CardTable::kCardSize, scan_visitor);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07002886 }
Mathieu Chartier938a03b2014-01-16 15:10:31 -08002887
2888 // Search to see if any of the roots reference our object.
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002889 RootMatchesObjectVisitor visitor1(obj);
2890 Runtime::Current()->VisitRoots(&visitor1);
Mathieu Chartier938a03b2014-01-16 15:10:31 -08002891 // Search to see if any of the roots reference our reference.
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002892 RootMatchesObjectVisitor visitor2(ref);
2893 Runtime::Current()->VisitRoots(&visitor2);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07002894 }
Mathieu Chartier8ab7e782014-05-19 16:55:27 -07002895 return false;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07002896 }
2897
Ian Rogers1d54e732013-05-02 21:10:01 -07002898 Heap* const heap_;
Mathieu Chartier8ab7e782014-05-19 16:55:27 -07002899 Atomic<size_t>* const fail_count_;
2900 const bool verify_referent_;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07002901};
2902
Ian Rogers1d54e732013-05-02 21:10:01 -07002903// Verify all references within an object, for use with HeapBitmap::Visit.
Mathieu Chartierfd678be2012-08-30 14:50:54 -07002904class VerifyObjectVisitor {
2905 public:
Roland Levillain3887c462015-08-12 18:15:42 +01002906 VerifyObjectVisitor(Heap* heap, Atomic<size_t>* fail_count, bool verify_referent)
Mathieu Chartiera4f6af92015-08-11 17:35:25 -07002907 : heap_(heap), fail_count_(fail_count), verify_referent_(verify_referent) {}
Mathieu Chartierfd678be2012-08-30 14:50:54 -07002908
Mathieu Chartierda7c6502015-07-23 16:01:26 -07002909 void operator()(mirror::Object* obj)
Mathieu Chartier90443472015-07-16 20:32:27 -07002910 SHARED_REQUIRES(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Ian Rogers1d54e732013-05-02 21:10:01 -07002911 // Note: we are verifying the references in obj but not obj itself, this is because obj must
2912 // be live or else how did we find it in the live bitmap?
Mathieu Chartier8ab7e782014-05-19 16:55:27 -07002913 VerifyReferenceVisitor visitor(heap_, fail_count_, verify_referent_);
Mathieu Chartier0f72e412013-09-06 16:40:01 -07002914 // The class doesn't count as a reference but we should verify it anyways.
Mathieu Chartier059ef3d2015-08-18 13:54:21 -07002915 obj->VisitReferences(visitor, visitor);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07002916 }
2917
Mathieu Chartier590fee92013-09-13 13:46:47 -07002918 static void VisitCallback(mirror::Object* obj, void* arg)
Mathieu Chartier90443472015-07-16 20:32:27 -07002919 SHARED_REQUIRES(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07002920 VerifyObjectVisitor* visitor = reinterpret_cast<VerifyObjectVisitor*>(arg);
2921 visitor->operator()(obj);
2922 }
2923
Mathieu Chartierda7c6502015-07-23 16:01:26 -07002924 void VerifyRoots() SHARED_REQUIRES(Locks::mutator_lock_) REQUIRES(!Locks::heap_bitmap_lock_) {
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002925 ReaderMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
2926 VerifyReferenceVisitor visitor(heap_, fail_count_, verify_referent_);
2927 Runtime::Current()->VisitRoots(&visitor);
2928 }
2929
Mathieu Chartier8ab7e782014-05-19 16:55:27 -07002930 size_t GetFailureCount() const {
Mathieu Chartiere9e55ac2014-05-21 17:48:25 -07002931 return fail_count_->LoadSequentiallyConsistent();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07002932 }
2933
2934 private:
Ian Rogers1d54e732013-05-02 21:10:01 -07002935 Heap* const heap_;
Mathieu Chartier8ab7e782014-05-19 16:55:27 -07002936 Atomic<size_t>* const fail_count_;
Mathieu Chartier78f7b4c2014-05-06 10:57:27 -07002937 const bool verify_referent_;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07002938};
2939
Mathieu Chartierc1790162014-05-23 10:54:50 -07002940void Heap::PushOnAllocationStackWithInternalGC(Thread* self, mirror::Object** obj) {
2941 // Slow path, the allocation stack push back must have already failed.
2942 DCHECK(!allocation_stack_->AtomicPushBack(*obj));
2943 do {
2944 // TODO: Add handle VerifyObject.
2945 StackHandleScope<1> hs(self);
2946 HandleWrapper<mirror::Object> wrapper(hs.NewHandleWrapper(obj));
2947 // Push our object into the reserve region of the allocaiton stack. This is only required due
2948 // to heap verification requiring that roots are live (either in the live bitmap or in the
2949 // allocation stack).
2950 CHECK(allocation_stack_->AtomicPushBackIgnoreGrowthLimit(*obj));
2951 CollectGarbageInternal(collector::kGcTypeSticky, kGcCauseForAlloc, false);
2952 } while (!allocation_stack_->AtomicPushBack(*obj));
2953}
2954
2955void Heap::PushOnThreadLocalAllocationStackWithInternalGC(Thread* self, mirror::Object** obj) {
2956 // Slow path, the allocation stack push back must have already failed.
2957 DCHECK(!self->PushOnThreadLocalAllocationStack(*obj));
Mathieu Chartiercb535da2015-01-23 13:50:03 -08002958 StackReference<mirror::Object>* start_address;
2959 StackReference<mirror::Object>* end_address;
Mathieu Chartierc1790162014-05-23 10:54:50 -07002960 while (!allocation_stack_->AtomicBumpBack(kThreadLocalAllocationStackSize, &start_address,
2961 &end_address)) {
2962 // TODO: Add handle VerifyObject.
2963 StackHandleScope<1> hs(self);
2964 HandleWrapper<mirror::Object> wrapper(hs.NewHandleWrapper(obj));
2965 // Push our object into the reserve region of the allocaiton stack. This is only required due
2966 // to heap verification requiring that roots are live (either in the live bitmap or in the
2967 // allocation stack).
2968 CHECK(allocation_stack_->AtomicPushBackIgnoreGrowthLimit(*obj));
2969 // Push into the reserve allocation stack.
2970 CollectGarbageInternal(collector::kGcTypeSticky, kGcCauseForAlloc, false);
2971 }
2972 self->SetThreadLocalAllocationStack(start_address, end_address);
2973 // Retry on the new thread-local allocation stack.
2974 CHECK(self->PushOnThreadLocalAllocationStack(*obj)); // Must succeed.
2975}
2976
Mathieu Chartierfd678be2012-08-30 14:50:54 -07002977// Must do this with mutators suspended since we are directly accessing the allocation stacks.
Mathieu Chartier8ab7e782014-05-19 16:55:27 -07002978size_t Heap::VerifyHeapReferences(bool verify_referents) {
Hiroshi Yamauchi1ed90612014-02-14 15:00:51 -08002979 Thread* self = Thread::Current();
2980 Locks::mutator_lock_->AssertExclusiveHeld(self);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07002981 // Lets sort our allocation stacks so that we can efficiently binary search them.
Ian Rogers1d54e732013-05-02 21:10:01 -07002982 allocation_stack_->Sort();
2983 live_stack_->Sort();
Hiroshi Yamauchi1ed90612014-02-14 15:00:51 -08002984 // Since we sorted the allocation stack content, need to revoke all
2985 // thread-local allocation stacks.
2986 RevokeAllThreadLocalAllocationStacks(self);
Mathieu Chartier8ab7e782014-05-19 16:55:27 -07002987 Atomic<size_t> fail_count_(0);
2988 VerifyObjectVisitor visitor(this, &fail_count_, verify_referents);
Mathieu Chartier0f72e412013-09-06 16:40:01 -07002989 // Verify objects in the allocation stack since these will be objects which were:
2990 // 1. Allocated prior to the GC (pre GC verification).
2991 // 2. Allocated during the GC (pre sweep GC verification).
Mathieu Chartier0f72e412013-09-06 16:40:01 -07002992 // We don't want to verify the objects in the live stack since they themselves may be
Mathieu Chartierfd678be2012-08-30 14:50:54 -07002993 // pointing to dead objects if they are not reachable.
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002994 VisitObjectsPaused(VerifyObjectVisitor::VisitCallback, &visitor);
Mathieu Chartier590fee92013-09-13 13:46:47 -07002995 // Verify the roots:
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002996 visitor.VerifyRoots();
Mathieu Chartier8ab7e782014-05-19 16:55:27 -07002997 if (visitor.GetFailureCount() > 0) {
Mathieu Chartier0f72e412013-09-06 16:40:01 -07002998 // Dump mod-union tables.
Mathieu Chartier11409ae2013-09-23 11:49:36 -07002999 for (const auto& table_pair : mod_union_tables_) {
3000 accounting::ModUnionTable* mod_union_table = table_pair.second;
3001 mod_union_table->Dump(LOG(ERROR) << mod_union_table->GetName() << ": ");
3002 }
Hiroshi Yamauchi38e68e92014-03-07 13:59:08 -08003003 // Dump remembered sets.
3004 for (const auto& table_pair : remembered_sets_) {
3005 accounting::RememberedSet* remembered_set = table_pair.second;
3006 remembered_set->Dump(LOG(ERROR) << remembered_set->GetName() << ": ");
3007 }
Mathieu Chartier4c13a3f2014-07-14 14:57:16 -07003008 DumpSpaces(LOG(ERROR));
Mathieu Chartierfd678be2012-08-30 14:50:54 -07003009 }
Mathieu Chartier8ab7e782014-05-19 16:55:27 -07003010 return visitor.GetFailureCount();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07003011}
3012
3013class VerifyReferenceCardVisitor {
3014 public:
3015 VerifyReferenceCardVisitor(Heap* heap, bool* failed)
Mathieu Chartier90443472015-07-16 20:32:27 -07003016 SHARED_REQUIRES(Locks::mutator_lock_,
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07003017 Locks::heap_bitmap_lock_)
Ian Rogers1d54e732013-05-02 21:10:01 -07003018 : heap_(heap), failed_(failed) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07003019 }
3020
Mathieu Chartierda7c6502015-07-23 16:01:26 -07003021 // There is no card marks for native roots on a class.
3022 void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root ATTRIBUTE_UNUSED)
3023 const {}
3024 void VisitRoot(mirror::CompressedReference<mirror::Object>* root ATTRIBUTE_UNUSED) const {}
3025
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08003026 // TODO: Fix lock analysis to not use NO_THREAD_SAFETY_ANALYSIS, requires support for
3027 // annotalysis on visitors.
Mathieu Chartier407f7022014-02-18 14:37:05 -08003028 void operator()(mirror::Object* obj, MemberOffset offset, bool is_static) const
3029 NO_THREAD_SAFETY_ANALYSIS {
Ian Rogersb0fa5dc2014-04-28 16:47:08 -07003030 mirror::Object* ref = obj->GetFieldObject<mirror::Object>(offset);
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08003031 // Filter out class references since changing an object's class does not mark the card as dirty.
3032 // Also handles large objects, since the only reference they hold is a class reference.
Mathieu Chartier407f7022014-02-18 14:37:05 -08003033 if (ref != nullptr && !ref->IsClass()) {
Ian Rogers1d54e732013-05-02 21:10:01 -07003034 accounting::CardTable* card_table = heap_->GetCardTable();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07003035 // If the object is not dirty and it is referencing something in the live stack other than
3036 // class, then it must be on a dirty card.
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07003037 if (!card_table->AddrIsInCardTable(obj)) {
3038 LOG(ERROR) << "Object " << obj << " is not in the address range of the card table";
3039 *failed_ = true;
Mathieu Chartier2b82db42012-11-14 17:29:05 -08003040 } else if (!card_table->IsDirty(obj)) {
Mathieu Chartier938a03b2014-01-16 15:10:31 -08003041 // TODO: Check mod-union tables.
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08003042 // Card should be either kCardDirty if it got re-dirtied after we aged it, or
3043 // kCardDirty - 1 if it didnt get touched since we aged it.
Ian Rogers1d54e732013-05-02 21:10:01 -07003044 accounting::ObjectStack* live_stack = heap_->live_stack_.get();
Mathieu Chartier407f7022014-02-18 14:37:05 -08003045 if (live_stack->ContainsSorted(ref)) {
3046 if (live_stack->ContainsSorted(obj)) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07003047 LOG(ERROR) << "Object " << obj << " found in live stack";
3048 }
3049 if (heap_->GetLiveBitmap()->Test(obj)) {
3050 LOG(ERROR) << "Object " << obj << " found in live bitmap";
3051 }
3052 LOG(ERROR) << "Object " << obj << " " << PrettyTypeOf(obj)
3053 << " references " << ref << " " << PrettyTypeOf(ref) << " in live stack";
3054
3055 // Print which field of the object is dead.
3056 if (!obj->IsObjectArray()) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08003057 mirror::Class* klass = is_static ? obj->AsClass() : obj->GetClass();
Mathieu Chartierc7853442015-03-27 14:35:38 -07003058 CHECK(klass != nullptr);
Mathieu Chartierc0fe56a2015-08-11 13:01:23 -07003059 for (ArtField& field : (is_static ? klass->GetSFields() : klass->GetIFields())) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003060 if (field.GetOffset().Int32Value() == offset.Int32Value()) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07003061 LOG(ERROR) << (is_static ? "Static " : "") << "field in the live stack is "
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003062 << PrettyField(&field);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07003063 break;
3064 }
3065 }
3066 } else {
Ian Rogersef7d42f2014-01-06 12:55:46 -08003067 mirror::ObjectArray<mirror::Object>* object_array =
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003068 obj->AsObjectArray<mirror::Object>();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07003069 for (int32_t i = 0; i < object_array->GetLength(); ++i) {
3070 if (object_array->Get(i) == ref) {
3071 LOG(ERROR) << (is_static ? "Static " : "") << "obj[" << i << "] = ref";
3072 }
3073 }
3074 }
3075
3076 *failed_ = true;
3077 }
3078 }
3079 }
3080 }
3081
3082 private:
Ian Rogers1d54e732013-05-02 21:10:01 -07003083 Heap* const heap_;
3084 bool* const failed_;
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07003085};
3086
3087class VerifyLiveStackReferences {
3088 public:
Brian Carlstrom93ba8932013-07-17 21:31:49 -07003089 explicit VerifyLiveStackReferences(Heap* heap)
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07003090 : heap_(heap),
Brian Carlstrom93ba8932013-07-17 21:31:49 -07003091 failed_(false) {}
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07003092
Mathieu Chartier11409ae2013-09-23 11:49:36 -07003093 void operator()(mirror::Object* obj) const
Mathieu Chartier90443472015-07-16 20:32:27 -07003094 SHARED_REQUIRES(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07003095 VerifyReferenceCardVisitor visitor(heap_, const_cast<bool*>(&failed_));
Mathieu Chartier059ef3d2015-08-18 13:54:21 -07003096 obj->VisitReferences(visitor, VoidFunctor());
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07003097 }
3098
3099 bool Failed() const {
3100 return failed_;
3101 }
3102
3103 private:
Ian Rogers1d54e732013-05-02 21:10:01 -07003104 Heap* const heap_;
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07003105 bool failed_;
3106};
3107
3108bool Heap::VerifyMissingCardMarks() {
Hiroshi Yamauchi1ed90612014-02-14 15:00:51 -08003109 Thread* self = Thread::Current();
3110 Locks::mutator_lock_->AssertExclusiveHeld(self);
Mathieu Chartier2b82db42012-11-14 17:29:05 -08003111 // We need to sort the live stack since we binary search it.
Ian Rogers1d54e732013-05-02 21:10:01 -07003112 live_stack_->Sort();
Hiroshi Yamauchi1ed90612014-02-14 15:00:51 -08003113 // Since we sorted the allocation stack content, need to revoke all
3114 // thread-local allocation stacks.
3115 RevokeAllThreadLocalAllocationStacks(self);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07003116 VerifyLiveStackReferences visitor(this);
3117 GetLiveBitmap()->Visit(visitor);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07003118 // We can verify objects in the live stack since none of these should reference dead objects.
Mathieu Chartiercb535da2015-01-23 13:50:03 -08003119 for (auto* it = live_stack_->Begin(); it != live_stack_->End(); ++it) {
3120 if (!kUseThreadLocalAllocationStack || it->AsMirrorPtr() != nullptr) {
3121 visitor(it->AsMirrorPtr());
Hiroshi Yamauchif5b0e202014-02-11 17:02:22 -08003122 }
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07003123 }
Mathieu Chartier4c13a3f2014-07-14 14:57:16 -07003124 return !visitor.Failed();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07003125}
3126
Mathieu Chartiera4f6af92015-08-11 17:35:25 -07003127void Heap::SwapStacks() {
Hiroshi Yamauchif5b0e202014-02-11 17:02:22 -08003128 if (kUseThreadLocalAllocationStack) {
3129 live_stack_->AssertAllZero();
3130 }
Mathieu Chartierd22d5482012-11-06 17:14:12 -08003131 allocation_stack_.swap(live_stack_);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07003132}
3133
Hiroshi Yamauchif5b0e202014-02-11 17:02:22 -08003134void Heap::RevokeAllThreadLocalAllocationStacks(Thread* self) {
Hiroshi Yamauchif5b0e202014-02-11 17:02:22 -08003135 // This must be called only during the pause.
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003136 DCHECK(Locks::mutator_lock_->IsExclusiveHeld(self));
Hiroshi Yamauchif5b0e202014-02-11 17:02:22 -08003137 MutexLock mu(self, *Locks::runtime_shutdown_lock_);
3138 MutexLock mu2(self, *Locks::thread_list_lock_);
3139 std::list<Thread*> thread_list = Runtime::Current()->GetThreadList()->GetList();
3140 for (Thread* t : thread_list) {
3141 t->RevokeThreadLocalAllocationStack();
3142 }
3143}
3144
Ian Rogers68d8b422014-07-17 11:09:10 -07003145void Heap::AssertThreadLocalBuffersAreRevoked(Thread* thread) {
3146 if (kIsDebugBuild) {
3147 if (rosalloc_space_ != nullptr) {
3148 rosalloc_space_->AssertThreadLocalBuffersAreRevoked(thread);
3149 }
3150 if (bump_pointer_space_ != nullptr) {
3151 bump_pointer_space_->AssertThreadLocalBuffersAreRevoked(thread);
3152 }
3153 }
3154}
3155
Hiroshi Yamauchic93c5302014-03-20 16:15:37 -07003156void Heap::AssertAllBumpPointerSpaceThreadLocalBuffersAreRevoked() {
3157 if (kIsDebugBuild) {
3158 if (bump_pointer_space_ != nullptr) {
3159 bump_pointer_space_->AssertAllThreadLocalBuffersAreRevoked();
3160 }
3161 }
3162}
3163
Mathieu Chartier11409ae2013-09-23 11:49:36 -07003164accounting::ModUnionTable* Heap::FindModUnionTableFromSpace(space::Space* space) {
3165 auto it = mod_union_tables_.find(space);
3166 if (it == mod_union_tables_.end()) {
3167 return nullptr;
3168 }
3169 return it->second;
3170}
3171
Hiroshi Yamauchi38e68e92014-03-07 13:59:08 -08003172accounting::RememberedSet* Heap::FindRememberedSetFromSpace(space::Space* space) {
3173 auto it = remembered_sets_.find(space);
3174 if (it == remembered_sets_.end()) {
3175 return nullptr;
3176 }
3177 return it->second;
3178}
3179
Mathieu Chartiera4f6af92015-08-11 17:35:25 -07003180void Heap::ProcessCards(TimingLogger* timings,
3181 bool use_rem_sets,
3182 bool process_alloc_space_cards,
Lei Li4add3b42015-01-15 11:55:26 +08003183 bool clear_alloc_space_cards) {
Mathieu Chartierf5997b42014-06-20 10:37:54 -07003184 TimingLogger::ScopedTiming t(__FUNCTION__, timings);
Ian Rogers1d54e732013-05-02 21:10:01 -07003185 // Clear cards and keep track of cards cleared in the mod-union table.
Mathieu Chartier02e25112013-08-14 16:14:24 -07003186 for (const auto& space : continuous_spaces_) {
Mathieu Chartier11409ae2013-09-23 11:49:36 -07003187 accounting::ModUnionTable* table = FindModUnionTableFromSpace(space);
Hiroshi Yamauchi38e68e92014-03-07 13:59:08 -08003188 accounting::RememberedSet* rem_set = FindRememberedSetFromSpace(space);
Mathieu Chartier11409ae2013-09-23 11:49:36 -07003189 if (table != nullptr) {
3190 const char* name = space->IsZygoteSpace() ? "ZygoteModUnionClearCards" :
3191 "ImageModUnionClearCards";
Andreas Gampe277ccbd2014-11-03 21:36:10 -08003192 TimingLogger::ScopedTiming t2(name, timings);
Mathieu Chartier11409ae2013-09-23 11:49:36 -07003193 table->ClearCards();
Hiroshi Yamauchi38e68e92014-03-07 13:59:08 -08003194 } else if (use_rem_sets && rem_set != nullptr) {
3195 DCHECK(collector::SemiSpace::kUseRememberedSet && collector_type_ == kCollectorTypeGSS)
3196 << static_cast<int>(collector_type_);
Andreas Gampe277ccbd2014-11-03 21:36:10 -08003197 TimingLogger::ScopedTiming t2("AllocSpaceRemSetClearCards", timings);
Hiroshi Yamauchi38e68e92014-03-07 13:59:08 -08003198 rem_set->ClearCards();
Lei Li4add3b42015-01-15 11:55:26 +08003199 } else if (process_alloc_space_cards) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08003200 TimingLogger::ScopedTiming t2("AllocSpaceClearCards", timings);
Lei Li4add3b42015-01-15 11:55:26 +08003201 if (clear_alloc_space_cards) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08003202 uint8_t* end = space->End();
3203 if (space->IsImageSpace()) {
3204 // Image space end is the end of the mirror objects, it is not necessarily page or card
3205 // aligned. Align up so that the check in ClearCardRange does not fail.
3206 end = AlignUp(end, accounting::CardTable::kCardSize);
3207 }
3208 card_table_->ClearCardRange(space->Begin(), end);
Lei Li4add3b42015-01-15 11:55:26 +08003209 } else {
3210 // No mod union table for the AllocSpace. Age the cards so that the GC knows that these
3211 // cards were dirty before the GC started.
3212 // TODO: Need to use atomic for the case where aged(cleaning thread) -> dirty(other thread)
3213 // -> clean(cleaning thread).
3214 // The races are we either end up with: Aged card, unaged card. Since we have the
3215 // checkpoint roots and then we scan / update mod union tables after. We will always
3216 // scan either card. If we end up with the non aged card, we scan it it in the pause.
3217 card_table_->ModifyCardsAtomic(space->Begin(), space->End(), AgeCardVisitor(),
3218 VoidFunctor());
3219 }
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07003220 }
3221 }
3222}
3223
Mathieu Chartier97509952015-07-13 14:35:43 -07003224struct IdentityMarkHeapReferenceVisitor : public MarkObjectVisitor {
3225 virtual mirror::Object* MarkObject(mirror::Object* obj) OVERRIDE {
3226 return obj;
3227 }
3228 virtual void MarkHeapReference(mirror::HeapReference<mirror::Object>*) OVERRIDE {
3229 }
3230};
Mathieu Chartier11409ae2013-09-23 11:49:36 -07003231
Mathieu Chartier6f365cc2014-04-23 12:42:27 -07003232void Heap::PreGcVerificationPaused(collector::GarbageCollector* gc) {
3233 Thread* const self = Thread::Current();
Mathieu Chartier10fb83a2014-06-15 15:15:43 -07003234 TimingLogger* const timings = current_gc_iteration_.GetTimings();
Mathieu Chartierf5997b42014-06-20 10:37:54 -07003235 TimingLogger::ScopedTiming t(__FUNCTION__, timings);
Mathieu Chartier2b82db42012-11-14 17:29:05 -08003236 if (verify_pre_gc_heap_) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08003237 TimingLogger::ScopedTiming t2("(Paused)PreGcVerifyHeapReferences", timings);
Mathieu Chartier8ab7e782014-05-19 16:55:27 -07003238 size_t failures = VerifyHeapReferences();
3239 if (failures > 0) {
3240 LOG(FATAL) << "Pre " << gc->GetName() << " heap verification failed with " << failures
3241 << " failures";
Mathieu Chartier2b82db42012-11-14 17:29:05 -08003242 }
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08003243 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -08003244 // Check that all objects which reference things in the live stack are on dirty cards.
3245 if (verify_missing_card_marks_) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08003246 TimingLogger::ScopedTiming t2("(Paused)PreGcVerifyMissingCardMarks", timings);
Mathieu Chartier6f365cc2014-04-23 12:42:27 -07003247 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartiera4f6af92015-08-11 17:35:25 -07003248 SwapStacks();
Mathieu Chartier6f365cc2014-04-23 12:42:27 -07003249 // Sort the live stack so that we can quickly binary search it later.
Mathieu Chartier4c13a3f2014-07-14 14:57:16 -07003250 CHECK(VerifyMissingCardMarks()) << "Pre " << gc->GetName()
3251 << " missing card mark verification failed\n" << DumpSpaces();
Mathieu Chartiera4f6af92015-08-11 17:35:25 -07003252 SwapStacks();
Mathieu Chartier2b82db42012-11-14 17:29:05 -08003253 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -08003254 if (verify_mod_union_table_) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08003255 TimingLogger::ScopedTiming t2("(Paused)PreGcVerifyModUnionTables", timings);
Mathieu Chartier2b82db42012-11-14 17:29:05 -08003256 ReaderMutexLock reader_lock(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier11409ae2013-09-23 11:49:36 -07003257 for (const auto& table_pair : mod_union_tables_) {
3258 accounting::ModUnionTable* mod_union_table = table_pair.second;
Mathieu Chartier97509952015-07-13 14:35:43 -07003259 IdentityMarkHeapReferenceVisitor visitor;
3260 mod_union_table->UpdateAndMarkReferences(&visitor);
Mathieu Chartier11409ae2013-09-23 11:49:36 -07003261 mod_union_table->Verify();
3262 }
Mathieu Chartier6f365cc2014-04-23 12:42:27 -07003263 }
3264}
3265
3266void Heap::PreGcVerification(collector::GarbageCollector* gc) {
Mathieu Chartier0651d412014-04-29 14:37:57 -07003267 if (verify_pre_gc_heap_ || verify_missing_card_marks_ || verify_mod_union_table_) {
Mathieu Chartier6f365cc2014-04-23 12:42:27 -07003268 collector::GarbageCollector::ScopedPause pause(gc);
3269 PreGcVerificationPaused(gc);
3270 }
3271}
3272
Mathieu Chartiera4f6af92015-08-11 17:35:25 -07003273void Heap::PrePauseRosAllocVerification(collector::GarbageCollector* gc ATTRIBUTE_UNUSED) {
Mathieu Chartier6f365cc2014-04-23 12:42:27 -07003274 // TODO: Add a new runtime option for this?
3275 if (verify_pre_gc_rosalloc_) {
Mathieu Chartier10fb83a2014-06-15 15:15:43 -07003276 RosAllocVerification(current_gc_iteration_.GetTimings(), "PreGcRosAllocVerification");
Mathieu Chartier2b82db42012-11-14 17:29:05 -08003277 }
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08003278}
3279
Ian Rogers1d54e732013-05-02 21:10:01 -07003280void Heap::PreSweepingGcVerification(collector::GarbageCollector* gc) {
Mathieu Chartier6f365cc2014-04-23 12:42:27 -07003281 Thread* const self = Thread::Current();
Mathieu Chartier10fb83a2014-06-15 15:15:43 -07003282 TimingLogger* const timings = current_gc_iteration_.GetTimings();
Mathieu Chartierf5997b42014-06-20 10:37:54 -07003283 TimingLogger::ScopedTiming t(__FUNCTION__, timings);
Mathieu Chartier2b82db42012-11-14 17:29:05 -08003284 // Called before sweeping occurs since we want to make sure we are not going so reclaim any
3285 // reachable objects.
Mathieu Chartier6f365cc2014-04-23 12:42:27 -07003286 if (verify_pre_sweeping_heap_) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08003287 TimingLogger::ScopedTiming t2("(Paused)PostSweepingVerifyHeapReferences", timings);
Ian Rogers1d54e732013-05-02 21:10:01 -07003288 CHECK_NE(self->GetState(), kRunnable);
Hiroshi Yamauchi0c8c3032015-01-16 16:54:35 -08003289 {
3290 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
3291 // Swapping bound bitmaps does nothing.
3292 gc->SwapBitmaps();
3293 }
Mathieu Chartier78f7b4c2014-05-06 10:57:27 -07003294 // Pass in false since concurrent reference processing can mean that the reference referents
3295 // may point to dead objects at the point which PreSweepingGcVerification is called.
Mathieu Chartier8ab7e782014-05-19 16:55:27 -07003296 size_t failures = VerifyHeapReferences(false);
3297 if (failures > 0) {
3298 LOG(FATAL) << "Pre sweeping " << gc->GetName() << " GC verification failed with " << failures
3299 << " failures";
Mathieu Chartier6f365cc2014-04-23 12:42:27 -07003300 }
Hiroshi Yamauchi0c8c3032015-01-16 16:54:35 -08003301 {
3302 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
3303 gc->SwapBitmaps();
3304 }
Mathieu Chartier6f365cc2014-04-23 12:42:27 -07003305 }
3306 if (verify_pre_sweeping_rosalloc_) {
3307 RosAllocVerification(timings, "PreSweepingRosAllocVerification");
3308 }
3309}
3310
3311void Heap::PostGcVerificationPaused(collector::GarbageCollector* gc) {
3312 // Only pause if we have to do some verification.
3313 Thread* const self = Thread::Current();
Mathieu Chartier10fb83a2014-06-15 15:15:43 -07003314 TimingLogger* const timings = GetCurrentGcIteration()->GetTimings();
Mathieu Chartierf5997b42014-06-20 10:37:54 -07003315 TimingLogger::ScopedTiming t(__FUNCTION__, timings);
Mathieu Chartier6f365cc2014-04-23 12:42:27 -07003316 if (verify_system_weaks_) {
3317 ReaderMutexLock mu2(self, *Locks::heap_bitmap_lock_);
3318 collector::MarkSweep* mark_sweep = down_cast<collector::MarkSweep*>(gc);
3319 mark_sweep->VerifySystemWeaks();
3320 }
3321 if (verify_post_gc_rosalloc_) {
Mathieu Chartierf5997b42014-06-20 10:37:54 -07003322 RosAllocVerification(timings, "(Paused)PostGcRosAllocVerification");
Mathieu Chartier6f365cc2014-04-23 12:42:27 -07003323 }
3324 if (verify_post_gc_heap_) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08003325 TimingLogger::ScopedTiming t2("(Paused)PostGcVerifyHeapReferences", timings);
Mathieu Chartier8ab7e782014-05-19 16:55:27 -07003326 size_t failures = VerifyHeapReferences();
3327 if (failures > 0) {
3328 LOG(FATAL) << "Pre " << gc->GetName() << " heap verification failed with " << failures
3329 << " failures";
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003330 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003331 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -08003332}
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003333
Ian Rogers1d54e732013-05-02 21:10:01 -07003334void Heap::PostGcVerification(collector::GarbageCollector* gc) {
Mathieu Chartier6f365cc2014-04-23 12:42:27 -07003335 if (verify_system_weaks_ || verify_post_gc_rosalloc_ || verify_post_gc_heap_) {
3336 collector::GarbageCollector::ScopedPause pause(gc);
Mathieu Chartierd35326f2014-08-18 15:02:59 -07003337 PostGcVerificationPaused(gc);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003338 }
Carl Shapiro69759ea2011-07-21 18:13:35 -07003339}
3340
Mathieu Chartier6f365cc2014-04-23 12:42:27 -07003341void Heap::RosAllocVerification(TimingLogger* timings, const char* name) {
Mathieu Chartierf5997b42014-06-20 10:37:54 -07003342 TimingLogger::ScopedTiming t(name, timings);
Mathieu Chartier6f365cc2014-04-23 12:42:27 -07003343 for (const auto& space : continuous_spaces_) {
3344 if (space->IsRosAllocSpace()) {
3345 VLOG(heap) << name << " : " << space->GetName();
3346 space->AsRosAllocSpace()->Verify();
Hiroshi Yamauchia4adbfd2014-02-04 18:12:17 -08003347 }
3348 }
3349}
3350
Mathieu Chartier89a201e2014-05-02 10:27:26 -07003351collector::GcType Heap::WaitForGcToComplete(GcCause cause, Thread* self) {
Mathieu Chartiercaa82d62014-02-02 16:51:17 -08003352 ScopedThreadStateChange tsc(self, kWaitingForGcToComplete);
Mathieu Chartier590fee92013-09-13 13:46:47 -07003353 MutexLock mu(self, *gc_complete_lock_);
Mathieu Chartier89a201e2014-05-02 10:27:26 -07003354 return WaitForGcToCompleteLocked(cause, self);
Mathieu Chartier590fee92013-09-13 13:46:47 -07003355}
3356
Mathieu Chartier89a201e2014-05-02 10:27:26 -07003357collector::GcType Heap::WaitForGcToCompleteLocked(GcCause cause, Thread* self) {
Ian Rogers1d54e732013-05-02 21:10:01 -07003358 collector::GcType last_gc_type = collector::kGcTypeNone;
Mathieu Chartier590fee92013-09-13 13:46:47 -07003359 uint64_t wait_start = NanoTime();
Mathieu Chartierd5a89ee2014-01-31 09:55:13 -08003360 while (collector_type_running_ != kCollectorTypeNone) {
Hiroshi Yamauchia1c9f012015-04-02 10:18:12 -07003361 if (self != task_processor_->GetRunningThread()) {
3362 // The current thread is about to wait for a currently running
3363 // collection to finish. If the waiting thread is not the heap
3364 // task daemon thread, the currently running collection is
3365 // considered as a blocking GC.
3366 running_collection_is_blocking_ = true;
3367 VLOG(gc) << "Waiting for a blocking GC " << cause;
3368 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07003369 ATRACE_BEGIN("GC: Wait For Completion");
3370 // We must wait, change thread state then sleep on gc_complete_cond_;
3371 gc_complete_cond_->Wait(self);
3372 last_gc_type = last_gc_type_;
Mathieu Chartier752a0e62013-06-27 11:03:27 -07003373 ATRACE_END();
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07003374 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07003375 uint64_t wait_time = NanoTime() - wait_start;
3376 total_wait_time_ += wait_time;
3377 if (wait_time > long_pause_log_threshold_) {
Mathieu Chartier89a201e2014-05-02 10:27:26 -07003378 LOG(INFO) << "WaitForGcToComplete blocked for " << PrettyDuration(wait_time)
3379 << " for cause " << cause;
Mathieu Chartier590fee92013-09-13 13:46:47 -07003380 }
Hiroshi Yamauchia1c9f012015-04-02 10:18:12 -07003381 if (self != task_processor_->GetRunningThread()) {
3382 // The current thread is about to run a collection. If the thread
3383 // is not the heap task daemon thread, it's considered as a
3384 // blocking GC (i.e., blocking itself).
3385 running_collection_is_blocking_ = true;
3386 VLOG(gc) << "Starting a blocking GC " << cause;
3387 }
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07003388 return last_gc_type;
Carl Shapiro69759ea2011-07-21 18:13:35 -07003389}
3390
Elliott Hughesc967f782012-04-16 10:23:15 -07003391void Heap::DumpForSigQuit(std::ostream& os) {
Ian Rogers1d54e732013-05-02 21:10:01 -07003392 os << "Heap: " << GetPercentFree() << "% free, " << PrettySize(GetBytesAllocated()) << "/"
Mathieu Chartier2fde5332012-09-14 14:51:54 -07003393 << PrettySize(GetTotalMemory()) << "; " << GetObjectsAllocated() << " objects\n";
Elliott Hughes8b788fe2013-04-17 15:57:01 -07003394 DumpGcPerformanceInfo(os);
Elliott Hughesc967f782012-04-16 10:23:15 -07003395}
3396
3397size_t Heap::GetPercentFree() {
Mathieu Chartierd30e1d62014-06-09 13:25:22 -07003398 return static_cast<size_t>(100.0f * static_cast<float>(GetFreeMemory()) / max_allowed_footprint_);
Elliott Hughesc967f782012-04-16 10:23:15 -07003399}
3400
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003401void Heap::SetIdealFootprint(size_t max_allowed_footprint) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07003402 if (max_allowed_footprint > GetMaxMemory()) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07003403 VLOG(gc) << "Clamp target GC heap from " << PrettySize(max_allowed_footprint) << " to "
Mathieu Chartier2fde5332012-09-14 14:51:54 -07003404 << PrettySize(GetMaxMemory());
3405 max_allowed_footprint = GetMaxMemory();
3406 }
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -07003407 max_allowed_footprint_ = max_allowed_footprint;
Shih-wei Liao8c2f6412011-10-03 22:58:14 -07003408}
3409
Mathieu Chartier590fee92013-09-13 13:46:47 -07003410bool Heap::IsMovableObject(const mirror::Object* obj) const {
3411 if (kMovingCollector) {
Mathieu Chartier31f44142014-04-08 14:40:03 -07003412 space::Space* space = FindContinuousSpaceFromObject(obj, true);
3413 if (space != nullptr) {
3414 // TODO: Check large object?
3415 return space->CanMoveObjects();
Mathieu Chartier590fee92013-09-13 13:46:47 -07003416 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07003417 }
3418 return false;
3419}
3420
Mathieu Chartier987ccff2013-07-08 11:05:21 -07003421void Heap::UpdateMaxNativeFootprint() {
Ian Rogers3e5cf302014-05-20 16:40:37 -07003422 size_t native_size = native_bytes_allocated_.LoadRelaxed();
Mathieu Chartier987ccff2013-07-08 11:05:21 -07003423 // TODO: Tune the native heap utilization to be a value other than the java heap utilization.
3424 size_t target_size = native_size / GetTargetHeapUtilization();
3425 if (target_size > native_size + max_free_) {
3426 target_size = native_size + max_free_;
3427 } else if (target_size < native_size + min_free_) {
3428 target_size = native_size + min_free_;
3429 }
Mathieu Chartier8ec31f92014-09-03 10:30:11 -07003430 native_footprint_gc_watermark_ = std::min(growth_limit_, target_size);
Mathieu Chartier987ccff2013-07-08 11:05:21 -07003431}
3432
Mathieu Chartierafe49982014-03-27 10:55:04 -07003433collector::GarbageCollector* Heap::FindCollectorByGcType(collector::GcType gc_type) {
3434 for (const auto& collector : garbage_collectors_) {
3435 if (collector->GetCollectorType() == collector_type_ &&
3436 collector->GetGcType() == gc_type) {
3437 return collector;
3438 }
3439 }
3440 return nullptr;
3441}
3442
Mathieu Chartier2f8da3e2014-04-15 15:37:02 -07003443double Heap::HeapGrowthMultiplier() const {
3444 // If we don't care about pause times we are background, so return 1.0.
3445 if (!CareAboutPauseTimes() || IsLowMemoryMode()) {
3446 return 1.0;
3447 }
3448 return foreground_heap_growth_multiplier_;
3449}
3450
Mathieu Chartiere2c2f6e2014-12-16 18:49:31 -08003451void Heap::GrowForUtilization(collector::GarbageCollector* collector_ran,
3452 uint64_t bytes_allocated_before_gc) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07003453 // We know what our utilization is at this moment.
3454 // This doesn't actually resize any memory. It just lets the heap grow more when necessary.
Mathieu Chartier2f8da3e2014-04-15 15:37:02 -07003455 const uint64_t bytes_allocated = GetBytesAllocated();
Mathieu Chartier2f8da3e2014-04-15 15:37:02 -07003456 uint64_t target_size;
Mathieu Chartierafe49982014-03-27 10:55:04 -07003457 collector::GcType gc_type = collector_ran->GetGcType();
Mathieu Chartiere2c2f6e2014-12-16 18:49:31 -08003458 const double multiplier = HeapGrowthMultiplier(); // Use the multiplier to grow more for
3459 // foreground.
3460 const uint64_t adjusted_min_free = static_cast<uint64_t>(min_free_ * multiplier);
3461 const uint64_t adjusted_max_free = static_cast<uint64_t>(max_free_ * multiplier);
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -07003462 if (gc_type != collector::kGcTypeSticky) {
3463 // Grow the heap for non sticky GC.
Mathieu Chartiere2c2f6e2014-12-16 18:49:31 -08003464 ssize_t delta = bytes_allocated / GetTargetHeapUtilization() - bytes_allocated;
Mathieu Chartier2f8da3e2014-04-15 15:37:02 -07003465 CHECK_GE(delta, 0);
3466 target_size = bytes_allocated + delta * multiplier;
Mathieu Chartiere2c2f6e2014-12-16 18:49:31 -08003467 target_size = std::min(target_size, bytes_allocated + adjusted_max_free);
3468 target_size = std::max(target_size, bytes_allocated + adjusted_min_free);
Mathieu Chartier590fee92013-09-13 13:46:47 -07003469 native_need_to_run_finalization_ = true;
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -07003470 next_gc_type_ = collector::kGcTypeSticky;
3471 } else {
Mathieu Chartierafe49982014-03-27 10:55:04 -07003472 collector::GcType non_sticky_gc_type =
Mathieu Chartiere4cab172014-08-19 18:24:04 -07003473 HasZygoteSpace() ? collector::kGcTypePartial : collector::kGcTypeFull;
Mathieu Chartierafe49982014-03-27 10:55:04 -07003474 // Find what the next non sticky collector will be.
3475 collector::GarbageCollector* non_sticky_collector = FindCollectorByGcType(non_sticky_gc_type);
3476 // If the throughput of the current sticky GC >= throughput of the non sticky collector, then
3477 // do another sticky collection next.
3478 // We also check that the bytes allocated aren't over the footprint limit in order to prevent a
3479 // pathological case where dead objects which aren't reclaimed by sticky could get accumulated
3480 // if the sticky GC throughput always remained >= the full/partial throughput.
Mathieu Chartier10fb83a2014-06-15 15:15:43 -07003481 if (current_gc_iteration_.GetEstimatedThroughput() * kStickyGcThroughputAdjustment >=
Mathieu Chartierafe49982014-03-27 10:55:04 -07003482 non_sticky_collector->GetEstimatedMeanThroughput() &&
Mathieu Chartier10fb83a2014-06-15 15:15:43 -07003483 non_sticky_collector->NumberOfIterations() > 0 &&
Mathieu Chartierafe49982014-03-27 10:55:04 -07003484 bytes_allocated <= max_allowed_footprint_) {
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -07003485 next_gc_type_ = collector::kGcTypeSticky;
3486 } else {
Mathieu Chartierafe49982014-03-27 10:55:04 -07003487 next_gc_type_ = non_sticky_gc_type;
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -07003488 }
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -07003489 // If we have freed enough memory, shrink the heap back down.
Mathieu Chartiere2c2f6e2014-12-16 18:49:31 -08003490 if (bytes_allocated + adjusted_max_free < max_allowed_footprint_) {
3491 target_size = bytes_allocated + adjusted_max_free;
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -07003492 } else {
Mathieu Chartier2f8da3e2014-04-15 15:37:02 -07003493 target_size = std::max(bytes_allocated, static_cast<uint64_t>(max_allowed_footprint_));
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -07003494 }
3495 }
Mathieu Chartier2775ee42013-08-20 17:43:47 -07003496 if (!ignore_max_footprint_) {
3497 SetIdealFootprint(target_size);
Hiroshi Yamauchi3e417802014-03-20 12:03:02 -07003498 if (IsGcConcurrent()) {
Mathieu Chartiere2c2f6e2014-12-16 18:49:31 -08003499 const uint64_t freed_bytes = current_gc_iteration_.GetFreedBytes() +
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07003500 current_gc_iteration_.GetFreedLargeObjectBytes() +
3501 current_gc_iteration_.GetFreedRevokeBytes();
Mathieu Chartiere2c2f6e2014-12-16 18:49:31 -08003502 // Bytes allocated will shrink by freed_bytes after the GC runs, so if we want to figure out
3503 // how many bytes were allocated during the GC we need to add freed_bytes back on.
3504 CHECK_GE(bytes_allocated + freed_bytes, bytes_allocated_before_gc);
3505 const uint64_t bytes_allocated_during_gc = bytes_allocated + freed_bytes -
3506 bytes_allocated_before_gc;
Mathieu Chartier2775ee42013-08-20 17:43:47 -07003507 // Calculate when to perform the next ConcurrentGC.
Mathieu Chartier2775ee42013-08-20 17:43:47 -07003508 // Calculate the estimated GC duration.
Mathieu Chartier10fb83a2014-06-15 15:15:43 -07003509 const double gc_duration_seconds = NsToMs(current_gc_iteration_.GetDurationNs()) / 1000.0;
Mathieu Chartier2775ee42013-08-20 17:43:47 -07003510 // Estimate how many remaining bytes we will have when we need to start the next GC.
Mathieu Chartiere2c2f6e2014-12-16 18:49:31 -08003511 size_t remaining_bytes = bytes_allocated_during_gc * gc_duration_seconds;
Mathieu Chartier74762802014-01-24 10:21:35 -08003512 remaining_bytes = std::min(remaining_bytes, kMaxConcurrentRemainingBytes);
Mathieu Chartier2775ee42013-08-20 17:43:47 -07003513 remaining_bytes = std::max(remaining_bytes, kMinConcurrentRemainingBytes);
3514 if (UNLIKELY(remaining_bytes > max_allowed_footprint_)) {
3515 // A never going to happen situation that from the estimated allocation rate we will exceed
3516 // the applications entire footprint with the given estimated allocation rate. Schedule
Mathieu Chartier74762802014-01-24 10:21:35 -08003517 // another GC nearly straight away.
3518 remaining_bytes = kMinConcurrentRemainingBytes;
Mathieu Chartier2775ee42013-08-20 17:43:47 -07003519 }
Mathieu Chartier74762802014-01-24 10:21:35 -08003520 DCHECK_LE(remaining_bytes, max_allowed_footprint_);
Mathieu Chartierdd162fb2014-08-06 17:06:33 -07003521 DCHECK_LE(max_allowed_footprint_, GetMaxMemory());
Mathieu Chartier74762802014-01-24 10:21:35 -08003522 // Start a concurrent GC when we get close to the estimated remaining bytes. When the
3523 // allocation rate is very high, remaining_bytes could tell us that we should start a GC
3524 // right away.
Mathieu Chartier2f8da3e2014-04-15 15:37:02 -07003525 concurrent_start_bytes_ = std::max(max_allowed_footprint_ - remaining_bytes,
3526 static_cast<size_t>(bytes_allocated));
Mathieu Chartier65db8802012-11-20 12:36:46 -08003527 }
Mathieu Chartier65db8802012-11-20 12:36:46 -08003528 }
Carl Shapiro69759ea2011-07-21 18:13:35 -07003529}
3530
Mathieu Chartier379d09f2015-01-08 11:28:13 -08003531void Heap::ClampGrowthLimit() {
Mathieu Chartierddac4232015-04-02 10:08:03 -07003532 // Use heap bitmap lock to guard against races with BindLiveToMarkBitmap.
3533 WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
Mathieu Chartier379d09f2015-01-08 11:28:13 -08003534 capacity_ = growth_limit_;
3535 for (const auto& space : continuous_spaces_) {
3536 if (space->IsMallocSpace()) {
3537 gc::space::MallocSpace* malloc_space = space->AsMallocSpace();
3538 malloc_space->ClampGrowthLimit();
3539 }
3540 }
3541 // This space isn't added for performance reasons.
3542 if (main_space_backup_.get() != nullptr) {
3543 main_space_backup_->ClampGrowthLimit();
3544 }
3545}
3546
jeffhaoc1160702011-10-27 15:48:45 -07003547void Heap::ClearGrowthLimit() {
Mathieu Chartier80de7a62012-11-27 17:21:50 -08003548 growth_limit_ = capacity_;
Mathieu Chartier0310da52014-12-01 13:40:48 -08003549 for (const auto& space : continuous_spaces_) {
3550 if (space->IsMallocSpace()) {
3551 gc::space::MallocSpace* malloc_space = space->AsMallocSpace();
3552 malloc_space->ClearGrowthLimit();
3553 malloc_space->SetFootprintLimit(malloc_space->Capacity());
3554 }
3555 }
3556 // This space isn't added for performance reasons.
3557 if (main_space_backup_.get() != nullptr) {
3558 main_space_backup_->ClearGrowthLimit();
3559 main_space_backup_->SetFootprintLimit(main_space_backup_->Capacity());
3560 }
jeffhaoc1160702011-10-27 15:48:45 -07003561}
3562
Mathieu Chartier8668c3c2014-04-24 16:48:11 -07003563void Heap::AddFinalizerReference(Thread* self, mirror::Object** object) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003564 ScopedObjectAccess soa(self);
Mathieu Chartier8668c3c2014-04-24 16:48:11 -07003565 ScopedLocalRef<jobject> arg(self->GetJniEnv(), soa.AddLocalReference<jobject>(*object));
Ian Rogers53b8b092014-03-13 23:45:53 -07003566 jvalue args[1];
3567 args[0].l = arg.get();
3568 InvokeWithJValues(soa, nullptr, WellKnownClasses::java_lang_ref_FinalizerReference_add, args);
Mathieu Chartier8668c3c2014-04-24 16:48:11 -07003569 // Restore object in case it gets moved.
3570 *object = soa.Decode<mirror::Object*>(arg.get());
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003571}
3572
Hiroshi Yamauchi0ae98992015-05-01 14:33:19 -07003573void Heap::RequestConcurrentGCAndSaveObject(Thread* self, bool force_full, mirror::Object** obj) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003574 StackHandleScope<1> hs(self);
3575 HandleWrapper<mirror::Object> wrapper(hs.NewHandleWrapper(obj));
Hiroshi Yamauchi0ae98992015-05-01 14:33:19 -07003576 RequestConcurrentGC(self, force_full);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003577}
3578
Mathieu Chartiera5eae692014-12-17 17:56:03 -08003579class Heap::ConcurrentGCTask : public HeapTask {
3580 public:
Roland Levillain3887c462015-08-12 18:15:42 +01003581 ConcurrentGCTask(uint64_t target_time, bool force_full)
3582 : HeapTask(target_time), force_full_(force_full) { }
Mathieu Chartiera5eae692014-12-17 17:56:03 -08003583 virtual void Run(Thread* self) OVERRIDE {
3584 gc::Heap* heap = Runtime::Current()->GetHeap();
Hiroshi Yamauchi0ae98992015-05-01 14:33:19 -07003585 heap->ConcurrentGC(self, force_full_);
Mathieu Chartiera5eae692014-12-17 17:56:03 -08003586 heap->ClearConcurrentGCRequest();
Ian Rogers120f1c72012-09-28 17:17:10 -07003587 }
Hiroshi Yamauchi0ae98992015-05-01 14:33:19 -07003588
3589 private:
3590 const bool force_full_; // If true, force full (or partial) collection.
Mathieu Chartiera5eae692014-12-17 17:56:03 -08003591};
3592
Mathieu Chartier90443472015-07-16 20:32:27 -07003593static bool CanAddHeapTask(Thread* self) REQUIRES(!Locks::runtime_shutdown_lock_) {
Mathieu Chartiera5eae692014-12-17 17:56:03 -08003594 Runtime* runtime = Runtime::Current();
3595 return runtime != nullptr && runtime->IsFinishedStarting() && !runtime->IsShuttingDown(self) &&
3596 !self->IsHandlingStackOverflow();
3597}
3598
3599void Heap::ClearConcurrentGCRequest() {
3600 concurrent_gc_pending_.StoreRelaxed(false);
3601}
3602
Hiroshi Yamauchi0ae98992015-05-01 14:33:19 -07003603void Heap::RequestConcurrentGC(Thread* self, bool force_full) {
Mathieu Chartierac195162015-02-20 18:44:28 +00003604 if (CanAddHeapTask(self) &&
3605 concurrent_gc_pending_.CompareExchangeStrongSequentiallyConsistent(false, true)) {
Hiroshi Yamauchi0ae98992015-05-01 14:33:19 -07003606 task_processor_->AddTask(self, new ConcurrentGCTask(NanoTime(), // Start straight away.
3607 force_full));
Mathieu Chartiera5eae692014-12-17 17:56:03 -08003608 }
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07003609}
3610
Hiroshi Yamauchi0ae98992015-05-01 14:33:19 -07003611void Heap::ConcurrentGC(Thread* self, bool force_full) {
Mathieu Chartiera5eae692014-12-17 17:56:03 -08003612 if (!Runtime::Current()->IsShuttingDown(self)) {
3613 // Wait for any GCs currently running to finish.
3614 if (WaitForGcToComplete(kGcCauseBackground, self) == collector::kGcTypeNone) {
3615 // If the we can't run the GC type we wanted to run, find the next appropriate one and try that
3616 // instead. E.g. can't do partial, so do full instead.
Hiroshi Yamauchi0ae98992015-05-01 14:33:19 -07003617 collector::GcType next_gc_type = next_gc_type_;
3618 // If forcing full and next gc type is sticky, override with a non-sticky type.
3619 if (force_full && next_gc_type == collector::kGcTypeSticky) {
3620 next_gc_type = HasZygoteSpace() ? collector::kGcTypePartial : collector::kGcTypeFull;
3621 }
3622 if (CollectGarbageInternal(next_gc_type, kGcCauseBackground, false) ==
Mathieu Chartiera5eae692014-12-17 17:56:03 -08003623 collector::kGcTypeNone) {
3624 for (collector::GcType gc_type : gc_plan_) {
3625 // Attempt to run the collector, if we succeed, we are done.
Hiroshi Yamauchi0ae98992015-05-01 14:33:19 -07003626 if (gc_type > next_gc_type &&
Mathieu Chartiera5eae692014-12-17 17:56:03 -08003627 CollectGarbageInternal(gc_type, kGcCauseBackground, false) !=
3628 collector::kGcTypeNone) {
3629 break;
3630 }
Mathieu Chartierf9ed0d32013-11-21 16:42:47 -08003631 }
3632 }
3633 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -07003634 }
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07003635}
3636
Mathieu Chartiera5eae692014-12-17 17:56:03 -08003637class Heap::CollectorTransitionTask : public HeapTask {
3638 public:
Mathieu Chartiera4f6af92015-08-11 17:35:25 -07003639 explicit CollectorTransitionTask(uint64_t target_time) : HeapTask(target_time) {}
3640
Mathieu Chartiera5eae692014-12-17 17:56:03 -08003641 virtual void Run(Thread* self) OVERRIDE {
3642 gc::Heap* heap = Runtime::Current()->GetHeap();
3643 heap->DoPendingCollectorTransition();
3644 heap->ClearPendingCollectorTransition(self);
Mathieu Chartiera5f9de02014-02-28 16:48:42 -08003645 }
Mathieu Chartiera5eae692014-12-17 17:56:03 -08003646};
3647
3648void Heap::ClearPendingCollectorTransition(Thread* self) {
3649 MutexLock mu(self, *pending_task_lock_);
3650 pending_collector_transition_ = nullptr;
Mathieu Chartiera5f9de02014-02-28 16:48:42 -08003651}
3652
Mathieu Chartiera5eae692014-12-17 17:56:03 -08003653void Heap::RequestCollectorTransition(CollectorType desired_collector_type, uint64_t delta_time) {
3654 Thread* self = Thread::Current();
3655 desired_collector_type_ = desired_collector_type;
3656 if (desired_collector_type_ == collector_type_ || !CanAddHeapTask(self)) {
3657 return;
3658 }
3659 CollectorTransitionTask* added_task = nullptr;
3660 const uint64_t target_time = NanoTime() + delta_time;
3661 {
3662 MutexLock mu(self, *pending_task_lock_);
3663 // If we have an existing collector transition, update the targe time to be the new target.
3664 if (pending_collector_transition_ != nullptr) {
3665 task_processor_->UpdateTargetRunTime(self, pending_collector_transition_, target_time);
3666 return;
3667 }
3668 added_task = new CollectorTransitionTask(target_time);
3669 pending_collector_transition_ = added_task;
3670 }
3671 task_processor_->AddTask(self, added_task);
3672}
3673
3674class Heap::HeapTrimTask : public HeapTask {
3675 public:
3676 explicit HeapTrimTask(uint64_t delta_time) : HeapTask(NanoTime() + delta_time) { }
3677 virtual void Run(Thread* self) OVERRIDE {
3678 gc::Heap* heap = Runtime::Current()->GetHeap();
3679 heap->Trim(self);
3680 heap->ClearPendingTrim(self);
3681 }
3682};
3683
3684void Heap::ClearPendingTrim(Thread* self) {
3685 MutexLock mu(self, *pending_task_lock_);
3686 pending_heap_trim_ = nullptr;
3687}
3688
3689void Heap::RequestTrim(Thread* self) {
3690 if (!CanAddHeapTask(self)) {
3691 return;
3692 }
Ian Rogers48931882013-01-22 14:35:16 -08003693 // GC completed and now we must decide whether to request a heap trim (advising pages back to the
3694 // kernel) or not. Issuing a request will also cause trimming of the libc heap. As a trim scans
3695 // a space it will hold its lock and can become a cause of jank.
3696 // Note, the large object space self trims and the Zygote space was trimmed and unchanging since
3697 // forking.
3698
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08003699 // We don't have a good measure of how worthwhile a trim might be. We can't use the live bitmap
3700 // because that only marks object heads, so a large array looks like lots of empty space. We
3701 // don't just call dlmalloc all the time, because the cost of an _attempted_ trim is proportional
3702 // to utilization (which is probably inversely proportional to how much benefit we can expect).
3703 // We could try mincore(2) but that's only a measure of how many pages we haven't given away,
3704 // not how much use we're making of those pages.
Mathieu Chartiera5eae692014-12-17 17:56:03 -08003705 HeapTrimTask* added_task = nullptr;
Mathieu Chartier440e4ce2014-03-31 16:36:35 -07003706 {
Mathieu Chartiera5eae692014-12-17 17:56:03 -08003707 MutexLock mu(self, *pending_task_lock_);
3708 if (pending_heap_trim_ != nullptr) {
3709 // Already have a heap trim request in task processor, ignore this request.
Mathieu Chartier440e4ce2014-03-31 16:36:35 -07003710 return;
Mathieu Chartiera5f9de02014-02-28 16:48:42 -08003711 }
Mathieu Chartiera5eae692014-12-17 17:56:03 -08003712 added_task = new HeapTrimTask(kHeapTrimWait);
3713 pending_heap_trim_ = added_task;
Mathieu Chartierc39e3422013-08-07 16:41:36 -07003714 }
Mathieu Chartiera5eae692014-12-17 17:56:03 -08003715 task_processor_->AddTask(self, added_task);
Mathieu Chartiera5f9de02014-02-28 16:48:42 -08003716}
3717
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -07003718void Heap::RevokeThreadLocalBuffers(Thread* thread) {
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08003719 if (rosalloc_space_ != nullptr) {
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07003720 size_t freed_bytes_revoke = rosalloc_space_->RevokeThreadLocalBuffers(thread);
3721 if (freed_bytes_revoke > 0U) {
3722 num_bytes_freed_revoke_.FetchAndAddSequentiallyConsistent(freed_bytes_revoke);
3723 CHECK_GE(num_bytes_allocated_.LoadRelaxed(), num_bytes_freed_revoke_.LoadRelaxed());
3724 }
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08003725 }
Mathieu Chartier692fafd2013-11-29 17:24:40 -08003726 if (bump_pointer_space_ != nullptr) {
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07003727 CHECK_EQ(bump_pointer_space_->RevokeThreadLocalBuffers(thread), 0U);
Mathieu Chartier692fafd2013-11-29 17:24:40 -08003728 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003729 if (region_space_ != nullptr) {
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07003730 CHECK_EQ(region_space_->RevokeThreadLocalBuffers(thread), 0U);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003731 }
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -07003732}
3733
Hiroshi Yamauchic93c5302014-03-20 16:15:37 -07003734void Heap::RevokeRosAllocThreadLocalBuffers(Thread* thread) {
3735 if (rosalloc_space_ != nullptr) {
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07003736 size_t freed_bytes_revoke = rosalloc_space_->RevokeThreadLocalBuffers(thread);
3737 if (freed_bytes_revoke > 0U) {
3738 num_bytes_freed_revoke_.FetchAndAddSequentiallyConsistent(freed_bytes_revoke);
3739 CHECK_GE(num_bytes_allocated_.LoadRelaxed(), num_bytes_freed_revoke_.LoadRelaxed());
3740 }
Hiroshi Yamauchic93c5302014-03-20 16:15:37 -07003741 }
3742}
3743
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -07003744void Heap::RevokeAllThreadLocalBuffers() {
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08003745 if (rosalloc_space_ != nullptr) {
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07003746 size_t freed_bytes_revoke = rosalloc_space_->RevokeAllThreadLocalBuffers();
3747 if (freed_bytes_revoke > 0U) {
3748 num_bytes_freed_revoke_.FetchAndAddSequentiallyConsistent(freed_bytes_revoke);
3749 CHECK_GE(num_bytes_allocated_.LoadRelaxed(), num_bytes_freed_revoke_.LoadRelaxed());
3750 }
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08003751 }
Mathieu Chartier692fafd2013-11-29 17:24:40 -08003752 if (bump_pointer_space_ != nullptr) {
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07003753 CHECK_EQ(bump_pointer_space_->RevokeAllThreadLocalBuffers(), 0U);
Mathieu Chartier692fafd2013-11-29 17:24:40 -08003754 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003755 if (region_space_ != nullptr) {
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07003756 CHECK_EQ(region_space_->RevokeAllThreadLocalBuffers(), 0U);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003757 }
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -07003758}
3759
Mathieu Chartier987ccff2013-07-08 11:05:21 -07003760bool Heap::IsGCRequestPending() const {
Mathieu Chartiera5eae692014-12-17 17:56:03 -08003761 return concurrent_gc_pending_.LoadRelaxed();
Mathieu Chartier987ccff2013-07-08 11:05:21 -07003762}
3763
Mathieu Chartierb5de3bb2015-06-05 13:21:05 -07003764void Heap::RunFinalization(JNIEnv* env, uint64_t timeout) {
3765 env->CallStaticVoidMethod(WellKnownClasses::dalvik_system_VMRuntime,
3766 WellKnownClasses::dalvik_system_VMRuntime_runFinalization,
3767 static_cast<jlong>(timeout));
Mathieu Chartier590fee92013-09-13 13:46:47 -07003768}
3769
Mathieu Chartier8ec31f92014-09-03 10:30:11 -07003770void Heap::RegisterNativeAllocation(JNIEnv* env, size_t bytes) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07003771 Thread* self = ThreadForEnv(env);
3772 if (native_need_to_run_finalization_) {
Mathieu Chartierb5de3bb2015-06-05 13:21:05 -07003773 RunFinalization(env, kNativeAllocationFinalizeTimeout);
Mathieu Chartier590fee92013-09-13 13:46:47 -07003774 UpdateMaxNativeFootprint();
3775 native_need_to_run_finalization_ = false;
3776 }
Mathieu Chartier987ccff2013-07-08 11:05:21 -07003777 // Total number of native bytes allocated.
Ian Rogers3e5cf302014-05-20 16:40:37 -07003778 size_t new_native_bytes_allocated = native_bytes_allocated_.FetchAndAddSequentiallyConsistent(bytes);
3779 new_native_bytes_allocated += bytes;
3780 if (new_native_bytes_allocated > native_footprint_gc_watermark_) {
Mathieu Chartiere4cab172014-08-19 18:24:04 -07003781 collector::GcType gc_type = HasZygoteSpace() ? collector::kGcTypePartial :
Mathieu Chartiercbb2d202013-11-14 17:45:16 -08003782 collector::kGcTypeFull;
3783
Mathieu Chartier987ccff2013-07-08 11:05:21 -07003784 // The second watermark is higher than the gc watermark. If you hit this it means you are
3785 // allocating native objects faster than the GC can keep up with.
Mathieu Chartier08487452014-09-02 16:21:01 -07003786 if (new_native_bytes_allocated > growth_limit_) {
Mathieu Chartier89a201e2014-05-02 10:27:26 -07003787 if (WaitForGcToComplete(kGcCauseForNativeAlloc, self) != collector::kGcTypeNone) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07003788 // Just finished a GC, attempt to run finalizers.
Mathieu Chartierb5de3bb2015-06-05 13:21:05 -07003789 RunFinalization(env, kNativeAllocationFinalizeTimeout);
Mathieu Chartier590fee92013-09-13 13:46:47 -07003790 CHECK(!env->ExceptionCheck());
Lin Zang60e27162015-03-10 18:53:21 +08003791 // Native bytes allocated may be updated by finalization, refresh it.
3792 new_native_bytes_allocated = native_bytes_allocated_.LoadRelaxed();
Mathieu Chartier590fee92013-09-13 13:46:47 -07003793 }
3794 // If we still are over the watermark, attempt a GC for alloc and run finalizers.
Mathieu Chartier08487452014-09-02 16:21:01 -07003795 if (new_native_bytes_allocated > growth_limit_) {
Hiroshi Yamauchi6f4ffe42014-01-13 12:30:44 -08003796 CollectGarbageInternal(gc_type, kGcCauseForNativeAlloc, false);
Mathieu Chartierb5de3bb2015-06-05 13:21:05 -07003797 RunFinalization(env, kNativeAllocationFinalizeTimeout);
Mathieu Chartier590fee92013-09-13 13:46:47 -07003798 native_need_to_run_finalization_ = false;
3799 CHECK(!env->ExceptionCheck());
3800 }
3801 // We have just run finalizers, update the native watermark since it is very likely that
3802 // finalizers released native managed allocations.
3803 UpdateMaxNativeFootprint();
3804 } else if (!IsGCRequestPending()) {
Hiroshi Yamauchi3e417802014-03-20 12:03:02 -07003805 if (IsGcConcurrent()) {
Hiroshi Yamauchi0ae98992015-05-01 14:33:19 -07003806 RequestConcurrentGC(self, true); // Request non-sticky type.
Mathieu Chartier590fee92013-09-13 13:46:47 -07003807 } else {
Hiroshi Yamauchid20aba12014-04-11 15:31:09 -07003808 CollectGarbageInternal(gc_type, kGcCauseForNativeAlloc, false);
Mathieu Chartier987ccff2013-07-08 11:05:21 -07003809 }
3810 }
3811 }
3812}
3813
Mathieu Chartier8ec31f92014-09-03 10:30:11 -07003814void Heap::RegisterNativeFree(JNIEnv* env, size_t bytes) {
3815 size_t expected_size;
Mathieu Chartier987ccff2013-07-08 11:05:21 -07003816 do {
Ian Rogers3e5cf302014-05-20 16:40:37 -07003817 expected_size = native_bytes_allocated_.LoadRelaxed();
Mathieu Chartier8ec31f92014-09-03 10:30:11 -07003818 if (UNLIKELY(bytes > expected_size)) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07003819 ScopedObjectAccess soa(env);
3820 env->ThrowNew(WellKnownClasses::java_lang_RuntimeException,
Mathieu Chartier8ec31f92014-09-03 10:30:11 -07003821 StringPrintf("Attempted to free %zd native bytes with only %zd native bytes "
Mathieu Chartier590fee92013-09-13 13:46:47 -07003822 "registered as allocated", bytes, expected_size).c_str());
3823 break;
3824 }
Mathieu Chartier8ec31f92014-09-03 10:30:11 -07003825 } while (!native_bytes_allocated_.CompareExchangeWeakRelaxed(expected_size,
3826 expected_size - bytes));
Mathieu Chartier987ccff2013-07-08 11:05:21 -07003827}
3828
Ian Rogersef7d42f2014-01-06 12:55:46 -08003829size_t Heap::GetTotalMemory() const {
Mathieu Chartierdd162fb2014-08-06 17:06:33 -07003830 return std::max(max_allowed_footprint_, GetBytesAllocated());
Hiroshi Yamauchi09b07a92013-07-15 13:17:06 -07003831}
3832
Mathieu Chartier11409ae2013-09-23 11:49:36 -07003833void Heap::AddModUnionTable(accounting::ModUnionTable* mod_union_table) {
3834 DCHECK(mod_union_table != nullptr);
3835 mod_union_tables_.Put(mod_union_table->GetSpace(), mod_union_table);
3836}
3837
Mathieu Chartierc645f1d2014-03-06 18:11:53 -08003838void Heap::CheckPreconditionsForAllocObject(mirror::Class* c, size_t byte_count) {
Mathieu Chartiera5eae692014-12-17 17:56:03 -08003839 CHECK(c == nullptr || (c->IsClassClass() && byte_count >= sizeof(mirror::Class)) ||
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07003840 (c->IsVariableSize() || c->GetObjectSize() == byte_count)) << c->GetClassFlags();
Mathieu Chartierc645f1d2014-03-06 18:11:53 -08003841 CHECK_GE(byte_count, sizeof(mirror::Object));
3842}
3843
Hiroshi Yamauchi38e68e92014-03-07 13:59:08 -08003844void Heap::AddRememberedSet(accounting::RememberedSet* remembered_set) {
3845 CHECK(remembered_set != nullptr);
3846 space::Space* space = remembered_set->GetSpace();
3847 CHECK(space != nullptr);
Mathieu Chartier8e4a96d2014-05-21 10:44:32 -07003848 CHECK(remembered_sets_.find(space) == remembered_sets_.end()) << space;
Hiroshi Yamauchi38e68e92014-03-07 13:59:08 -08003849 remembered_sets_.Put(space, remembered_set);
Mathieu Chartier8e4a96d2014-05-21 10:44:32 -07003850 CHECK(remembered_sets_.find(space) != remembered_sets_.end()) << space;
Hiroshi Yamauchi38e68e92014-03-07 13:59:08 -08003851}
3852
3853void Heap::RemoveRememberedSet(space::Space* space) {
3854 CHECK(space != nullptr);
3855 auto it = remembered_sets_.find(space);
3856 CHECK(it != remembered_sets_.end());
Mathieu Chartier5189e242014-07-24 11:11:05 -07003857 delete it->second;
Hiroshi Yamauchi38e68e92014-03-07 13:59:08 -08003858 remembered_sets_.erase(it);
3859 CHECK(remembered_sets_.find(space) == remembered_sets_.end());
3860}
3861
Mathieu Chartier4aeec172014-03-27 16:09:46 -07003862void Heap::ClearMarkedObjects() {
3863 // Clear all of the spaces' mark bitmaps.
3864 for (const auto& space : GetContinuousSpaces()) {
Mathieu Chartiera8e8f9c2014-04-09 14:51:05 -07003865 accounting::ContinuousSpaceBitmap* mark_bitmap = space->GetMarkBitmap();
Mathieu Chartier4aeec172014-03-27 16:09:46 -07003866 if (space->GetLiveBitmap() != mark_bitmap) {
3867 mark_bitmap->Clear();
3868 }
3869 }
3870 // Clear the marked objects in the discontinous space object sets.
3871 for (const auto& space : GetDiscontinuousSpaces()) {
Mathieu Chartierbbd695c2014-04-16 09:48:48 -07003872 space->GetMarkBitmap()->Clear();
Mathieu Chartier4aeec172014-03-27 16:09:46 -07003873 }
3874}
3875
Man Cao8c2ff642015-05-27 17:25:30 -07003876void Heap::SetAllocationRecords(AllocRecordObjectMap* records) {
3877 allocation_records_.reset(records);
3878}
3879
Man Cao1ed11b92015-06-11 22:47:35 -07003880void Heap::VisitAllocationRecords(RootVisitor* visitor) const {
3881 if (IsAllocTrackingEnabled()) {
3882 MutexLock mu(Thread::Current(), *Locks::alloc_tracker_lock_);
3883 if (IsAllocTrackingEnabled()) {
3884 GetAllocationRecords()->VisitRoots(visitor);
3885 }
3886 }
3887}
3888
Mathieu Chartier97509952015-07-13 14:35:43 -07003889void Heap::SweepAllocationRecords(IsMarkedVisitor* visitor) const {
Man Cao8c2ff642015-05-27 17:25:30 -07003890 if (IsAllocTrackingEnabled()) {
3891 MutexLock mu(Thread::Current(), *Locks::alloc_tracker_lock_);
3892 if (IsAllocTrackingEnabled()) {
Mathieu Chartier97509952015-07-13 14:35:43 -07003893 GetAllocationRecords()->SweepAllocationRecords(visitor);
Man Cao8c2ff642015-05-27 17:25:30 -07003894 }
3895 }
3896}
3897
Man Cao42c3c332015-06-23 16:38:25 -07003898void Heap::AllowNewAllocationRecords() const {
Hiroshi Yamauchifdbd13c2015-09-02 16:16:58 -07003899 CHECK(!kUseReadBarrier);
Man Cao42c3c332015-06-23 16:38:25 -07003900 if (IsAllocTrackingEnabled()) {
3901 MutexLock mu(Thread::Current(), *Locks::alloc_tracker_lock_);
3902 if (IsAllocTrackingEnabled()) {
3903 GetAllocationRecords()->AllowNewAllocationRecords();
3904 }
3905 }
3906}
3907
3908void Heap::DisallowNewAllocationRecords() const {
Hiroshi Yamauchifdbd13c2015-09-02 16:16:58 -07003909 CHECK(!kUseReadBarrier);
Man Cao42c3c332015-06-23 16:38:25 -07003910 if (IsAllocTrackingEnabled()) {
3911 MutexLock mu(Thread::Current(), *Locks::alloc_tracker_lock_);
3912 if (IsAllocTrackingEnabled()) {
3913 GetAllocationRecords()->DisallowNewAllocationRecords();
3914 }
3915 }
3916}
3917
Hiroshi Yamauchifdbd13c2015-09-02 16:16:58 -07003918void Heap::BroadcastForNewAllocationRecords() const {
3919 CHECK(kUseReadBarrier);
3920 if (IsAllocTrackingEnabled()) {
3921 MutexLock mu(Thread::Current(), *Locks::alloc_tracker_lock_);
3922 if (IsAllocTrackingEnabled()) {
3923 GetAllocationRecords()->BroadcastForNewAllocationRecords();
3924 }
3925 }
3926}
3927
Mathieu Chartier31000802015-06-14 14:14:37 -07003928// Based on debug malloc logic from libc/bionic/debug_stacktrace.cpp.
3929class StackCrawlState {
3930 public:
3931 StackCrawlState(uintptr_t* frames, size_t max_depth, size_t skip_count)
3932 : frames_(frames), frame_count_(0), max_depth_(max_depth), skip_count_(skip_count) {
3933 }
3934 size_t GetFrameCount() const {
3935 return frame_count_;
3936 }
3937 static _Unwind_Reason_Code Callback(_Unwind_Context* context, void* arg) {
3938 auto* const state = reinterpret_cast<StackCrawlState*>(arg);
3939 const uintptr_t ip = _Unwind_GetIP(context);
3940 // The first stack frame is get_backtrace itself. Skip it.
3941 if (ip != 0 && state->skip_count_ > 0) {
3942 --state->skip_count_;
3943 return _URC_NO_REASON;
3944 }
3945 // ip may be off for ARM but it shouldn't matter since we only use it for hashing.
3946 state->frames_[state->frame_count_] = ip;
3947 state->frame_count_++;
3948 return state->frame_count_ >= state->max_depth_ ? _URC_END_OF_STACK : _URC_NO_REASON;
3949 }
3950
3951 private:
3952 uintptr_t* const frames_;
3953 size_t frame_count_;
3954 const size_t max_depth_;
3955 size_t skip_count_;
3956};
3957
3958static size_t get_backtrace(uintptr_t* frames, size_t max_depth) {
3959 StackCrawlState state(frames, max_depth, 0u);
3960 _Unwind_Backtrace(&StackCrawlState::Callback, &state);
3961 return state.GetFrameCount();
3962}
3963
3964void Heap::CheckGcStressMode(Thread* self, mirror::Object** obj) {
3965 auto* const runtime = Runtime::Current();
3966 if (gc_stress_mode_ && runtime->GetClassLinker()->IsInitialized() &&
3967 !runtime->IsActiveTransaction() && mirror::Class::HasJavaLangClass()) {
3968 // Check if we should GC.
3969 bool new_backtrace = false;
3970 {
3971 static constexpr size_t kMaxFrames = 16u;
3972 uintptr_t backtrace[kMaxFrames];
3973 const size_t frames = get_backtrace(backtrace, kMaxFrames);
3974 uint64_t hash = 0;
3975 for (size_t i = 0; i < frames; ++i) {
3976 hash = hash * 2654435761 + backtrace[i];
3977 hash += (hash >> 13) ^ (hash << 6);
3978 }
3979 MutexLock mu(self, *backtrace_lock_);
3980 new_backtrace = seen_backtraces_.find(hash) == seen_backtraces_.end();
3981 if (new_backtrace) {
3982 seen_backtraces_.insert(hash);
3983 }
3984 }
3985 if (new_backtrace) {
3986 StackHandleScope<1> hs(self);
3987 auto h = hs.NewHandleWrapper(obj);
3988 CollectGarbage(false);
3989 unique_backtrace_count_.FetchAndAddSequentiallyConsistent(1);
3990 } else {
3991 seen_backtrace_count_.FetchAndAddSequentiallyConsistent(1);
3992 }
3993 }
3994}
3995
Mathieu Chartier51168372015-08-12 16:40:32 -07003996void Heap::DisableGCForShutdown() {
3997 Thread* const self = Thread::Current();
3998 CHECK(Runtime::Current()->IsShuttingDown(self));
3999 MutexLock mu(self, *gc_complete_lock_);
4000 gc_disabled_for_shutdown_ = true;
4001}
4002
Mathieu Chartierfbc31082016-01-24 11:59:56 -08004003bool Heap::ObjectIsInBootImageSpace(mirror::Object* obj) const {
4004 for (gc::space::ImageSpace* space : boot_image_spaces_) {
4005 if (space->HasAddress(obj)) {
4006 return true;
4007 }
4008 }
4009 return false;
4010}
4011
4012void Heap::GetBootImagesSize(uint32_t* boot_image_begin,
4013 uint32_t* boot_image_end,
4014 uint32_t* boot_oat_begin,
4015 uint32_t* boot_oat_end) {
4016 DCHECK(boot_image_begin != nullptr);
4017 DCHECK(boot_image_end != nullptr);
4018 DCHECK(boot_oat_begin != nullptr);
4019 DCHECK(boot_oat_end != nullptr);
4020 *boot_image_begin = 0u;
4021 *boot_image_end = 0u;
4022 *boot_oat_begin = 0u;
4023 *boot_oat_end = 0u;
4024 for (gc::space::ImageSpace* space_ : GetBootImageSpaces()) {
4025 const uint32_t image_begin = PointerToLowMemUInt32(space_->Begin());
4026 const uint32_t image_size = space_->GetImageHeader().GetImageSize();
4027 if (*boot_image_begin == 0 || image_begin < *boot_image_begin) {
4028 *boot_image_begin = image_begin;
4029 }
4030 *boot_image_end = std::max(*boot_image_end, image_begin + image_size);
4031 const OatFile* boot_oat_file = space_->GetOatFile();
4032 const uint32_t oat_begin = PointerToLowMemUInt32(boot_oat_file->Begin());
4033 const uint32_t oat_size = boot_oat_file->Size();
4034 if (*boot_oat_begin == 0 || oat_begin < *boot_oat_begin) {
4035 *boot_oat_begin = oat_begin;
4036 }
4037 *boot_oat_end = std::max(*boot_oat_end, oat_begin + oat_size);
4038 }
4039}
4040
Ian Rogers1d54e732013-05-02 21:10:01 -07004041} // namespace gc
Carl Shapiro69759ea2011-07-21 18:13:35 -07004042} // namespace art