blob: 67e8a0d02fe9132ee744d19be6278fd2104a38c6 [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
Brian Carlstrom58ae9412011-10-04 00:56:06 -070019#include <limits>
Ian Rogers700a4022014-05-19 16:49:03 -070020#include <memory>
Carl Shapiro58551df2011-07-24 03:09:51 -070021#include <vector>
22
Andreas Gampe46ee31b2016-12-14 10:11:49 -080023#include "android-base/stringprintf.h"
24
Andreas Gampe27fa96c2016-10-07 15:05:24 -070025#include "allocation_listener.h"
Mathieu Chartierc7853442015-03-27 14:35:38 -070026#include "art_field-inl.h"
Mathieu Chartier34583592017-03-23 23:51:34 -070027#include "backtrace_helper.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"
Hiroshi Yamauchi55113ed2017-02-10 15:12:46 -080032#include "base/memory_tool.h"
Elliott Hughes1aa246d2012-12-13 09:29:36 -080033#include "base/stl_util.h"
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -080034#include "base/systrace.h"
Vladimir Marko80afd022015-05-19 18:08:00 +010035#include "base/time_utils.h"
Mathieu Chartier987ccff2013-07-08 11:05:21 -070036#include "common_throws.h"
Ian Rogers48931882013-01-22 14:35:16 -080037#include "cutils/sched_policy.h"
Elliott Hughes767a1472011-10-26 18:49:02 -070038#include "debugger.h"
Elliott Hughes956af0f2014-12-11 14:34:28 -080039#include "dex_file-inl.h"
Steven Morelande431e272017-07-18 16:53:49 -070040#include "entrypoints/quick/quick_alloc_entrypoints.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070041#include "gc/accounting/card_table-inl.h"
42#include "gc/accounting/heap_bitmap-inl.h"
43#include "gc/accounting/mod_union_table-inl.h"
Andreas Gamped4901292017-05-30 18:41:34 -070044#include "gc/accounting/read_barrier_table.h"
Hiroshi Yamauchi38e68e92014-03-07 13:59:08 -080045#include "gc/accounting/remembered_set.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070046#include "gc/accounting/space_bitmap-inl.h"
Hiroshi Yamauchid5307ec2014-03-27 21:07:51 -070047#include "gc/collector/concurrent_copying.h"
Mathieu Chartier52e4b432014-06-10 11:22:31 -070048#include "gc/collector/mark_compact.h"
Mathieu Chartier3cf22532015-07-09 15:15:09 -070049#include "gc/collector/mark_sweep.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070050#include "gc/collector/partial_mark_sweep.h"
Mathieu Chartier590fee92013-09-13 13:46:47 -070051#include "gc/collector/semi_space.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070052#include "gc/collector/sticky_mark_sweep.h"
Mathieu Chartier78f7b4c2014-05-06 10:57:27 -070053#include "gc/reference_processor.h"
Hiroshi Yamauchi3b1d1b72016-10-12 11:53:57 -070054#include "gc/scoped_gc_critical_section.h"
Mathieu Chartier590fee92013-09-13 13:46:47 -070055#include "gc/space/bump_pointer_space.h"
Hiroshi Yamauchi50b29282013-07-30 13:58:37 -070056#include "gc/space/dlmalloc_space-inl.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070057#include "gc/space/image_space.h"
58#include "gc/space/large_object_space.h"
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -080059#include "gc/space/region_space.h"
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -070060#include "gc/space/rosalloc_space-inl.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070061#include "gc/space/space-inl.h"
Mathieu Chartiera1602f22014-01-13 17:19:19 -080062#include "gc/space/zygote_space.h"
Mathieu Chartiera5eae692014-12-17 17:56:03 -080063#include "gc/task_processor.h"
Mathieu Chartier1ca68902017-04-18 11:26:22 -070064#include "gc/verification.h"
Andreas Gampe9b8c5882016-10-21 15:27:46 -070065#include "gc_pause_listener.h"
Andreas Gamped4901292017-05-30 18:41:34 -070066#include "gc_root.h"
Steven Morelande431e272017-07-18 16:53:49 -070067#include "handle_scope-inl.h"
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -070068#include "heap-inl.h"
Andreas Gampe351c4472017-07-12 19:32:55 -070069#include "heap-visit-objects-inl.h"
Brian Carlstrom9cff8e12011-08-18 16:47:29 -070070#include "image.h"
Mathieu Chartiereb175f72014-10-31 11:49:27 -070071#include "intern_table.h"
Andreas Gampec15a2f42017-04-21 12:09:39 -070072#include "java_vm_ext.h"
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +000073#include "jit/jit.h"
74#include "jit/jit_code_cache.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080075#include "mirror/class-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080076#include "mirror/object-inl.h"
Andreas Gampec6ea7d02017-02-01 16:46:28 -080077#include "mirror/object-refvisitor-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080078#include "mirror/object_array-inl.h"
Mathieu Chartier8fa2dad2014-03-13 12:22:56 -070079#include "mirror/reference-inl.h"
Steven Morelande431e272017-07-18 16:53:49 -070080#include "nativehelper/ScopedLocalRef.h"
81#include "obj_ptr-inl.h"
Brian Carlstrom5643b782012-02-05 12:32:53 -080082#include "os.h"
Ian Rogers53b8b092014-03-13 23:45:53 -070083#include "reflection.h"
Mathieu Chartier0de9f732013-11-22 17:58:48 -080084#include "runtime.h"
Mathieu Chartier0795f232016-09-27 18:43:30 -070085#include "scoped_thread_state_change-inl.h"
Elliott Hughes8d768a92011-09-14 16:35:25 -070086#include "thread_list.h"
Andreas Gampe90b936d2017-01-31 08:58:55 -080087#include "verify_object-inl.h"
Elliott Hugheseac76672012-05-24 21:56:51 -070088#include "well_known_classes.h"
Carl Shapiro69759ea2011-07-21 18:13:35 -070089
90namespace art {
Mathieu Chartier50482232013-11-21 11:48:14 -080091
Ian Rogers1d54e732013-05-02 21:10:01 -070092namespace gc {
Carl Shapiro69759ea2011-07-21 18:13:35 -070093
Mathieu Chartier91e30632014-03-25 15:58:50 -070094static constexpr size_t kCollectorTransitionStressIterations = 0;
95static constexpr size_t kCollectorTransitionStressWait = 10 * 1000; // Microseconds
Ian Rogers1d54e732013-05-02 21:10:01 -070096// Minimum amount of remaining bytes before a concurrent GC is triggered.
Mathieu Chartier720ef762013-08-17 14:46:54 -070097static constexpr size_t kMinConcurrentRemainingBytes = 128 * KB;
Mathieu Chartier74762802014-01-24 10:21:35 -080098static constexpr size_t kMaxConcurrentRemainingBytes = 512 * KB;
Mathieu Chartierdf86d1f2014-04-08 13:44:04 -070099// Sticky GC throughput adjustment, divided by 4. Increasing this causes sticky GC to occur more
Mathieu Chartier73d1e172014-04-11 17:53:48 -0700100// relative to partial/full GC. This may be desirable since sticky GCs interfere less with mutator
Mathieu Chartierdf86d1f2014-04-08 13:44:04 -0700101// threads (lower pauses, use less memory bandwidth).
Mathieu Chartier73d1e172014-04-11 17:53:48 -0700102static constexpr double kStickyGcThroughputAdjustment = 1.0;
Mathieu Chartierc1790162014-05-23 10:54:50 -0700103// Whether or not we compact the zygote in PreZygoteFork.
Mathieu Chartier31f44142014-04-08 14:40:03 -0700104static constexpr bool kCompactZygote = kMovingCollector;
Mathieu Chartierc1790162014-05-23 10:54:50 -0700105// How many reserve entries are at the end of the allocation stack, these are only needed if the
106// allocation stack overflows.
107static constexpr size_t kAllocationStackReserveSize = 1024;
108// Default mark stack size in bytes.
109static const size_t kDefaultMarkStackSize = 64 * KB;
Zuo Wangf37a88b2014-07-10 04:26:41 -0700110// Define space name.
111static const char* kDlMallocSpaceName[2] = {"main dlmalloc space", "main dlmalloc space 1"};
112static const char* kRosAllocSpaceName[2] = {"main rosalloc space", "main rosalloc space 1"};
113static const char* kMemMapSpaceName[2] = {"main space", "main space 1"};
Mathieu Chartier7247af52014-11-19 10:51:42 -0800114static const char* kNonMovingSpaceName = "non moving space";
115static const char* kZygoteSpaceName = "zygote space";
Mathieu Chartierb363f662014-07-16 13:28:58 -0700116static constexpr size_t kGSSBumpPointerSpaceCapacity = 32 * MB;
Mathieu Chartier95a505c2014-12-10 18:45:30 -0800117static constexpr bool kGCALotMode = false;
118// GC alot mode uses a small allocation stack to stress test a lot of GC.
119static constexpr size_t kGcAlotAllocationStackSize = 4 * KB /
120 sizeof(mirror::HeapReference<mirror::Object>);
121// Verify objet has a small allocation stack size since searching the allocation stack is slow.
122static constexpr size_t kVerifyObjectAllocationStackSize = 16 * KB /
123 sizeof(mirror::HeapReference<mirror::Object>);
124static constexpr size_t kDefaultAllocationStackSize = 8 * MB /
125 sizeof(mirror::HeapReference<mirror::Object>);
Mathieu Chartierb5de3bb2015-06-05 13:21:05 -0700126// System.runFinalization can deadlock with native allocations, to deal with this, we have a
127// timeout on how long we wait for finalizers to run. b/21544853
128static constexpr uint64_t kNativeAllocationFinalizeTimeout = MsToNs(250u);
Mathieu Chartier0051be62012-10-12 17:47:11 -0700129
Andreas Gampeace0dc12016-01-20 13:33:13 -0800130// For deterministic compilation, we need the heap to be at a well-known address.
131static constexpr uint32_t kAllocSpaceBeginForDeterministicAoT = 0x40000000;
Hiroshi Yamauchib62f2e62016-03-23 15:51:24 -0700132// Dump the rosalloc stats on SIGQUIT.
133static constexpr bool kDumpRosAllocStatsOnSigQuit = false;
Andreas Gampeace0dc12016-01-20 13:33:13 -0800134
Hiroshi Yamauchi3c3c4a12017-02-21 16:49:59 -0800135static const char* kRegionSpaceName = "main space (region space)";
136
Mathieu Chartier6bc77742017-04-18 17:46:23 -0700137// If true, we log all GCs in the both the foreground and background. Used for debugging.
138static constexpr bool kLogAllGCs = false;
139
140// How much we grow the TLAB if we can do it.
141static constexpr size_t kPartialTlabSize = 16 * KB;
142static constexpr bool kUsePartialTlabs = true;
143
Hiroshi Yamauchi3c3c4a12017-02-21 16:49:59 -0800144#if defined(__LP64__) || !defined(ADDRESS_SANITIZER)
145// 300 MB (0x12c00000) - (default non-moving space capacity).
146static uint8_t* const kPreferredAllocSpaceBegin =
147 reinterpret_cast<uint8_t*>(300 * MB - Heap::kDefaultNonMovingSpaceCapacity);
148#else
Andreas Gampee8857fe2017-05-03 08:28:13 -0700149#ifdef __ANDROID__
150// For 32-bit Android, use 0x20000000 because asan reserves 0x04000000 - 0x20000000.
Hiroshi Yamauchi3c3c4a12017-02-21 16:49:59 -0800151static uint8_t* const kPreferredAllocSpaceBegin = reinterpret_cast<uint8_t*>(0x20000000);
Andreas Gampee8857fe2017-05-03 08:28:13 -0700152#else
153// For 32-bit host, use 0x40000000 because asan uses most of the space below this.
154static uint8_t* const kPreferredAllocSpaceBegin = reinterpret_cast<uint8_t*>(0x40000000);
155#endif
Hiroshi Yamauchi3c3c4a12017-02-21 16:49:59 -0800156#endif
157
Mathieu Chartierf8cb1782016-03-18 18:45:41 -0700158static inline bool CareAboutPauseTimes() {
159 return Runtime::Current()->InJankPerceptibleProcessState();
160}
161
Mathieu Chartiera4f6af92015-08-11 17:35:25 -0700162Heap::Heap(size_t initial_size,
163 size_t growth_limit,
164 size_t min_free,
165 size_t max_free,
166 double target_utilization,
167 double foreground_heap_growth_multiplier,
168 size_t capacity,
169 size_t non_moving_space_capacity,
170 const std::string& image_file_name,
171 const InstructionSet image_instruction_set,
172 CollectorType foreground_collector_type,
Mathieu Chartier2dbe6272014-09-16 10:43:23 -0700173 CollectorType background_collector_type,
Mathieu Chartiera4f6af92015-08-11 17:35:25 -0700174 space::LargeObjectSpaceType large_object_space_type,
175 size_t large_object_threshold,
176 size_t parallel_gc_threads,
177 size_t conc_gc_threads,
178 bool low_memory_mode,
179 size_t long_pause_log_threshold,
180 size_t long_gc_log_threshold,
181 bool ignore_max_footprint,
182 bool use_tlab,
183 bool verify_pre_gc_heap,
184 bool verify_pre_sweeping_heap,
185 bool verify_post_gc_heap,
186 bool verify_pre_gc_rosalloc,
187 bool verify_pre_sweeping_rosalloc,
188 bool verify_post_gc_rosalloc,
189 bool gc_stress_mode,
Mathieu Chartier56fe2582016-07-14 13:30:03 -0700190 bool measure_gc_performance,
Mathieu Chartier31000802015-06-14 14:14:37 -0700191 bool use_homogeneous_space_compaction_for_oom,
Zuo Wangf37a88b2014-07-10 04:26:41 -0700192 uint64_t min_interval_homogeneous_space_compaction_by_oom)
Mathieu Chartiercbb2d202013-11-14 17:45:16 -0800193 : non_moving_space_(nullptr),
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800194 rosalloc_space_(nullptr),
195 dlmalloc_space_(nullptr),
Mathieu Chartierfc5b5282014-01-09 16:15:36 -0800196 main_space_(nullptr),
Mathieu Chartier7bf82af2013-12-06 16:51:45 -0800197 collector_type_(kCollectorTypeNone),
Mathieu Chartier31f44142014-04-08 14:40:03 -0700198 foreground_collector_type_(foreground_collector_type),
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800199 background_collector_type_(background_collector_type),
Mathieu Chartier31f44142014-04-08 14:40:03 -0700200 desired_collector_type_(foreground_collector_type_),
Mathieu Chartiera5eae692014-12-17 17:56:03 -0800201 pending_task_lock_(nullptr),
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700202 parallel_gc_threads_(parallel_gc_threads),
203 conc_gc_threads_(conc_gc_threads),
Mathieu Chartiere0a53e92013-08-05 10:17:40 -0700204 low_memory_mode_(low_memory_mode),
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700205 long_pause_log_threshold_(long_pause_log_threshold),
206 long_gc_log_threshold_(long_gc_log_threshold),
207 ignore_max_footprint_(ignore_max_footprint),
Mathieu Chartier8e4a96d2014-05-21 10:44:32 -0700208 zygote_creation_lock_("zygote creation lock", kZygoteCreationLock),
Mathieu Chartiere4cab172014-08-19 18:24:04 -0700209 zygote_space_(nullptr),
Mathieu Chartier2dbe6272014-09-16 10:43:23 -0700210 large_object_threshold_(large_object_threshold),
Hiroshi Yamauchi76f55b02015-08-21 16:10:39 -0700211 disable_thread_flip_count_(0),
212 thread_flip_running_(false),
Mathieu Chartierd5a89ee2014-01-31 09:55:13 -0800213 collector_type_running_(kCollectorTypeNone),
Mathieu Chartier40112dd2017-06-26 17:49:09 -0700214 last_gc_cause_(kGcCauseNone),
Mathieu Chartier183009a2017-02-16 21:19:28 -0800215 thread_running_gc_(nullptr),
Ian Rogers1d54e732013-05-02 21:10:01 -0700216 last_gc_type_(collector::kGcTypeNone),
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -0700217 next_gc_type_(collector::kGcTypePartial),
Mathieu Chartier80de7a62012-11-27 17:21:50 -0800218 capacity_(capacity),
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700219 growth_limit_(growth_limit),
Mathieu Chartier0051be62012-10-12 17:47:11 -0700220 max_allowed_footprint_(initial_size),
Mathieu Chartier7bf82af2013-12-06 16:51:45 -0800221 concurrent_start_bytes_(std::numeric_limits<size_t>::max()),
Ian Rogers1d54e732013-05-02 21:10:01 -0700222 total_bytes_freed_ever_(0),
223 total_objects_freed_ever_(0),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800224 num_bytes_allocated_(0),
Richard Uhlercaaa2b02017-02-01 09:54:17 +0000225 new_native_bytes_allocated_(0),
226 old_native_bytes_allocated_(0),
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -0700227 num_bytes_freed_revoke_(0),
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700228 verify_missing_card_marks_(false),
229 verify_system_weaks_(false),
Mathieu Chartier938a03b2014-01-16 15:10:31 -0800230 verify_pre_gc_heap_(verify_pre_gc_heap),
Mathieu Chartier6f365cc2014-04-23 12:42:27 -0700231 verify_pre_sweeping_heap_(verify_pre_sweeping_heap),
Mathieu Chartier938a03b2014-01-16 15:10:31 -0800232 verify_post_gc_heap_(verify_post_gc_heap),
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700233 verify_mod_union_table_(false),
Hiroshi Yamauchia4adbfd2014-02-04 18:12:17 -0800234 verify_pre_gc_rosalloc_(verify_pre_gc_rosalloc),
Mathieu Chartier6f365cc2014-04-23 12:42:27 -0700235 verify_pre_sweeping_rosalloc_(verify_pre_sweeping_rosalloc),
Hiroshi Yamauchia4adbfd2014-02-04 18:12:17 -0800236 verify_post_gc_rosalloc_(verify_post_gc_rosalloc),
Mathieu Chartier31000802015-06-14 14:14:37 -0700237 gc_stress_mode_(gc_stress_mode),
Hans Boehmd972b422017-09-11 12:57:00 -0700238 /* For GC a lot mode, we limit the allocation stacks to be kGcAlotInterval allocations. This
Mathieu Chartier0418ae22013-07-31 13:35:46 -0700239 * causes a lot of GC since we do a GC for alloc whenever the stack is full. When heap
240 * verification is enabled, we limit the size of allocation stacks to speed up their
241 * searching.
242 */
Mathieu Chartier95a505c2014-12-10 18:45:30 -0800243 max_allocation_stack_size_(kGCALotMode ? kGcAlotAllocationStackSize
244 : (kVerifyObjectSupport > kVerifyObjectModeFast) ? kVerifyObjectAllocationStackSize :
245 kDefaultAllocationStackSize),
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800246 current_allocator_(kAllocatorTypeDlMalloc),
247 current_non_moving_allocator_(kAllocatorTypeNonMoving),
Mathieu Chartier590fee92013-09-13 13:46:47 -0700248 bump_pointer_space_(nullptr),
249 temp_space_(nullptr),
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800250 region_space_(nullptr),
Mathieu Chartier0051be62012-10-12 17:47:11 -0700251 min_free_(min_free),
252 max_free_(max_free),
253 target_utilization_(target_utilization),
Mathieu Chartier11c273d2017-10-15 20:54:45 -0700254 foreground_heap_growth_multiplier_(foreground_heap_growth_multiplier),
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700255 total_wait_time_(0),
Mathieu Chartier4e305412014-02-19 10:54:44 -0800256 verify_object_mode_(kVerifyObjectModeDisabled),
Mathieu Chartier1d27b342014-01-28 12:51:09 -0800257 disable_moving_gc_count_(0),
Vladimir Marko8da690f2016-08-11 18:25:53 +0100258 semi_space_collector_(nullptr),
259 mark_compact_collector_(nullptr),
260 concurrent_copying_collector_(nullptr),
Evgenii Stepanov1e133742015-05-20 12:30:59 -0700261 is_running_on_memory_tool_(Runtime::Current()->IsRunningOnMemoryTool()),
Zuo Wangf37a88b2014-07-10 04:26:41 -0700262 use_tlab_(use_tlab),
263 main_space_backup_(nullptr),
Mathieu Chartierb363f662014-07-16 13:28:58 -0700264 min_interval_homogeneous_space_compaction_by_oom_(
265 min_interval_homogeneous_space_compaction_by_oom),
Zuo Wangf37a88b2014-07-10 04:26:41 -0700266 last_time_homogeneous_space_compaction_by_oom_(NanoTime()),
Mathieu Chartiera5eae692014-12-17 17:56:03 -0800267 pending_collector_transition_(nullptr),
268 pending_heap_trim_(nullptr),
Hiroshi Yamauchia1c9f012015-04-02 10:18:12 -0700269 use_homogeneous_space_compaction_for_oom_(use_homogeneous_space_compaction_for_oom),
270 running_collection_is_blocking_(false),
271 blocking_gc_count_(0U),
272 blocking_gc_time_(0U),
273 last_update_time_gc_count_rate_histograms_( // Round down by the window duration.
274 (NanoTime() / kGcCountRateHistogramWindowDuration) * kGcCountRateHistogramWindowDuration),
275 gc_count_last_window_(0U),
276 blocking_gc_count_last_window_(0U),
277 gc_count_rate_histogram_("gc count rate histogram", 1U, kGcCountRateMaxBucketCount),
278 blocking_gc_count_rate_histogram_("blocking gc count rate histogram", 1U,
Man Cao8c2ff642015-05-27 17:25:30 -0700279 kGcCountRateMaxBucketCount),
Mathieu Chartier31000802015-06-14 14:14:37 -0700280 alloc_tracking_enabled_(false),
281 backtrace_lock_(nullptr),
282 seen_backtrace_count_(0u),
Mathieu Chartier51168372015-08-12 16:40:32 -0700283 unique_backtrace_count_(0u),
Jeff Haodcdc85b2015-12-04 14:06:18 -0800284 gc_disabled_for_shutdown_(false) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800285 if (VLOG_IS_ON(heap) || VLOG_IS_ON(startup)) {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800286 LOG(INFO) << "Heap() entering";
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700287 }
Hiroshi Yamauchi1b0adbf2016-11-14 17:35:12 -0800288 if (kUseReadBarrier) {
289 CHECK_EQ(foreground_collector_type_, kCollectorTypeCC);
290 CHECK_EQ(background_collector_type_, kCollectorTypeCCBackground);
291 }
Mathieu Chartier1ca68902017-04-18 11:26:22 -0700292 verification_.reset(new Verification(this));
Mathieu Chartier8261d022016-08-08 09:41:04 -0700293 CHECK_GE(large_object_threshold, kMinLargeObjectThreshold);
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800294 ScopedTrace trace(__FUNCTION__);
Mathieu Chartier31000802015-06-14 14:14:37 -0700295 Runtime* const runtime = Runtime::Current();
Mathieu Chartier50482232013-11-21 11:48:14 -0800296 // If we aren't the zygote, switch to the default non zygote allocator. This may update the
297 // entrypoints.
Mathieu Chartier31000802015-06-14 14:14:37 -0700298 const bool is_zygote = runtime->IsZygote();
Mathieu Chartier8e219ae2014-08-19 14:29:46 -0700299 if (!is_zygote) {
Mathieu Chartier31f44142014-04-08 14:40:03 -0700300 // Background compaction is currently not supported for command line runs.
301 if (background_collector_type_ != foreground_collector_type_) {
Mathieu Chartier52ba1992014-05-07 14:39:21 -0700302 VLOG(heap) << "Disabling background compaction for non zygote";
Mathieu Chartier31f44142014-04-08 14:40:03 -0700303 background_collector_type_ = foreground_collector_type_;
Mathieu Chartierbd0a6532014-02-27 11:14:21 -0800304 }
Mathieu Chartier50482232013-11-21 11:48:14 -0800305 }
Mathieu Chartiera5f9de02014-02-28 16:48:42 -0800306 ChangeCollector(desired_collector_type_);
Ian Rogers1d54e732013-05-02 21:10:01 -0700307 live_bitmap_.reset(new accounting::HeapBitmap(this));
308 mark_bitmap_.reset(new accounting::HeapBitmap(this));
Ian Rogers30fab402012-01-23 15:43:46 -0800309 // Requested begin for the alloc space, to follow the mapped image and oat files
Ian Rogers13735952014-10-08 12:43:28 -0700310 uint8_t* requested_alloc_space_begin = nullptr;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800311 if (foreground_collector_type_ == kCollectorTypeCC) {
Hiroshi Yamauchi3c3c4a12017-02-21 16:49:59 -0800312 // Need to use a low address so that we can allocate a contiguous 2 * Xmx space when there's no
313 // image (dex2oat for target).
314 requested_alloc_space_begin = kPreferredAllocSpaceBegin;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800315 }
Jeff Haodcdc85b2015-12-04 14:06:18 -0800316
317 // Load image space(s).
Andreas Gampe2bd84282016-12-05 12:37:36 -0800318 if (space::ImageSpace::LoadBootImage(image_file_name,
319 image_instruction_set,
320 &boot_image_spaces_,
321 &requested_alloc_space_begin)) {
322 for (auto space : boot_image_spaces_) {
323 AddSpace(space);
Alex Light64ad14d2014-08-19 14:23:13 -0700324 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700325 }
Andreas Gampe2bd84282016-12-05 12:37:36 -0800326
Zuo Wangf37a88b2014-07-10 04:26:41 -0700327 /*
328 requested_alloc_space_begin -> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
Mathieu Chartier6a7824d2014-08-22 14:53:04 -0700329 +- nonmoving space (non_moving_space_capacity)+-
Zuo Wangf37a88b2014-07-10 04:26:41 -0700330 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
Mathieu Chartier8e219ae2014-08-19 14:29:46 -0700331 +-????????????????????????????????????????????+-
332 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
Mathieu Chartierb363f662014-07-16 13:28:58 -0700333 +-main alloc space / bump space 1 (capacity_) +-
Zuo Wangf37a88b2014-07-10 04:26:41 -0700334 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
Mathieu Chartierb363f662014-07-16 13:28:58 -0700335 +-????????????????????????????????????????????+-
336 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
337 +-main alloc space2 / bump space 2 (capacity_)+-
Zuo Wangf37a88b2014-07-10 04:26:41 -0700338 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
339 */
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800340 // We don't have hspace compaction enabled with GSS or CC.
341 if (foreground_collector_type_ == kCollectorTypeGSS ||
342 foreground_collector_type_ == kCollectorTypeCC) {
Hiroshi Yamauchi20ed5af2014-11-17 18:05:44 -0800343 use_homogeneous_space_compaction_for_oom_ = false;
344 }
Mathieu Chartierb363f662014-07-16 13:28:58 -0700345 bool support_homogeneous_space_compaction =
Mathieu Chartier0deeb812014-08-21 18:28:20 -0700346 background_collector_type_ == gc::kCollectorTypeHomogeneousSpaceCompact ||
Hiroshi Yamauchi20ed5af2014-11-17 18:05:44 -0800347 use_homogeneous_space_compaction_for_oom_;
Mathieu Chartierb363f662014-07-16 13:28:58 -0700348 // We may use the same space the main space for the non moving space if we don't need to compact
349 // from the main space.
350 // This is not the case if we support homogeneous compaction or have a moving background
351 // collector type.
Mathieu Chartierb363f662014-07-16 13:28:58 -0700352 bool separate_non_moving_space = is_zygote ||
353 support_homogeneous_space_compaction || IsMovingGc(foreground_collector_type_) ||
354 IsMovingGc(background_collector_type_);
Mathieu Chartier76ce9172016-01-27 10:44:20 -0800355 if (foreground_collector_type_ == kCollectorTypeGSS) {
Mathieu Chartierb363f662014-07-16 13:28:58 -0700356 separate_non_moving_space = false;
357 }
358 std::unique_ptr<MemMap> main_mem_map_1;
359 std::unique_ptr<MemMap> main_mem_map_2;
Andreas Gampeace0dc12016-01-20 13:33:13 -0800360
361 // Gross hack to make dex2oat deterministic.
Mathieu Chartierc68e77b2016-01-28 09:49:55 -0800362 if (foreground_collector_type_ == kCollectorTypeMS &&
363 requested_alloc_space_begin == nullptr &&
364 Runtime::Current()->IsAotCompiler()) {
365 // Currently only enabled for MS collector since that is what the deterministic dex2oat uses.
366 // b/26849108
Andreas Gampeace0dc12016-01-20 13:33:13 -0800367 requested_alloc_space_begin = reinterpret_cast<uint8_t*>(kAllocSpaceBeginForDeterministicAoT);
368 }
Ian Rogers13735952014-10-08 12:43:28 -0700369 uint8_t* request_begin = requested_alloc_space_begin;
Mathieu Chartierb363f662014-07-16 13:28:58 -0700370 if (request_begin != nullptr && separate_non_moving_space) {
Mathieu Chartier6a7824d2014-08-22 14:53:04 -0700371 request_begin += non_moving_space_capacity;
Mathieu Chartierb363f662014-07-16 13:28:58 -0700372 }
373 std::string error_str;
374 std::unique_ptr<MemMap> non_moving_space_mem_map;
375 if (separate_non_moving_space) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800376 ScopedTrace trace2("Create separate non moving space");
Mathieu Chartier7247af52014-11-19 10:51:42 -0800377 // If we are the zygote, the non moving space becomes the zygote space when we run
378 // PreZygoteFork the first time. In this case, call the map "zygote space" since we can't
379 // rename the mem map later.
Roland Levillain5e8d5f02016-10-18 18:03:43 +0100380 const char* space_name = is_zygote ? kZygoteSpaceName : kNonMovingSpaceName;
Mathieu Chartierb363f662014-07-16 13:28:58 -0700381 // Reserve the non moving mem map before the other two since it needs to be at a specific
382 // address.
383 non_moving_space_mem_map.reset(
Mathieu Chartier7247af52014-11-19 10:51:42 -0800384 MemMap::MapAnonymous(space_name, requested_alloc_space_begin,
Vladimir Marko5c42c292015-02-25 12:02:49 +0000385 non_moving_space_capacity, PROT_READ | PROT_WRITE, true, false,
386 &error_str));
Mathieu Chartierb363f662014-07-16 13:28:58 -0700387 CHECK(non_moving_space_mem_map != nullptr) << error_str;
Mathieu Chartierc44ce2e2014-08-25 16:32:41 -0700388 // Try to reserve virtual memory at a lower address if we have a separate non moving space.
Hiroshi Yamauchi3c3c4a12017-02-21 16:49:59 -0800389 request_begin = kPreferredAllocSpaceBegin + non_moving_space_capacity;
Mathieu Chartierb363f662014-07-16 13:28:58 -0700390 }
Hiroshi Yamauchi3dbf2342015-03-17 16:01:11 -0700391 // Attempt to create 2 mem maps at or after the requested begin.
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800392 if (foreground_collector_type_ != kCollectorTypeCC) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800393 ScopedTrace trace2("Create main mem map");
Mathieu Chartier966f5332016-01-25 12:53:03 -0800394 if (separate_non_moving_space || !is_zygote) {
395 main_mem_map_1.reset(MapAnonymousPreferredAddress(kMemMapSpaceName[0],
396 request_begin,
397 capacity_,
398 &error_str));
Hiroshi Yamauchi3dbf2342015-03-17 16:01:11 -0700399 } else {
Mathieu Chartier966f5332016-01-25 12:53:03 -0800400 // If no separate non-moving space and we are the zygote, the main space must come right
401 // after the image space to avoid a gap. This is required since we want the zygote space to
402 // be adjacent to the image space.
Hiroshi Yamauchi3dbf2342015-03-17 16:01:11 -0700403 main_mem_map_1.reset(MemMap::MapAnonymous(kMemMapSpaceName[0], request_begin, capacity_,
404 PROT_READ | PROT_WRITE, true, false,
405 &error_str));
406 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800407 CHECK(main_mem_map_1.get() != nullptr) << error_str;
408 }
Mathieu Chartierb363f662014-07-16 13:28:58 -0700409 if (support_homogeneous_space_compaction ||
410 background_collector_type_ == kCollectorTypeSS ||
411 foreground_collector_type_ == kCollectorTypeSS) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800412 ScopedTrace trace2("Create main mem map 2");
Mathieu Chartierb363f662014-07-16 13:28:58 -0700413 main_mem_map_2.reset(MapAnonymousPreferredAddress(kMemMapSpaceName[1], main_mem_map_1->End(),
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700414 capacity_, &error_str));
Mathieu Chartierb363f662014-07-16 13:28:58 -0700415 CHECK(main_mem_map_2.get() != nullptr) << error_str;
416 }
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800417
Mathieu Chartierb363f662014-07-16 13:28:58 -0700418 // Create the non moving space first so that bitmaps don't take up the address range.
419 if (separate_non_moving_space) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800420 ScopedTrace trace2("Add non moving space");
Mathieu Chartier31f44142014-04-08 14:40:03 -0700421 // Non moving space is always dlmalloc since we currently don't have support for multiple
Zuo Wangf37a88b2014-07-10 04:26:41 -0700422 // active rosalloc spaces.
Mathieu Chartierb363f662014-07-16 13:28:58 -0700423 const size_t size = non_moving_space_mem_map->Size();
424 non_moving_space_ = space::DlMallocSpace::CreateFromMemMap(
Mathieu Chartier6a7824d2014-08-22 14:53:04 -0700425 non_moving_space_mem_map.release(), "zygote / non moving space", kDefaultStartingSize,
Mathieu Chartierb363f662014-07-16 13:28:58 -0700426 initial_size, size, size, false);
Mathieu Chartier78408882014-04-11 18:06:01 -0700427 non_moving_space_->SetFootprintLimit(non_moving_space_->Capacity());
Mathieu Chartierb363f662014-07-16 13:28:58 -0700428 CHECK(non_moving_space_ != nullptr) << "Failed creating non moving space "
429 << requested_alloc_space_begin;
430 AddSpace(non_moving_space_);
431 }
432 // Create other spaces based on whether or not we have a moving GC.
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800433 if (foreground_collector_type_ == kCollectorTypeCC) {
Hiroshi Yamauchi3c3c4a12017-02-21 16:49:59 -0800434 CHECK(separate_non_moving_space);
435 MemMap* region_space_mem_map = space::RegionSpace::CreateMemMap(kRegionSpaceName,
436 capacity_ * 2,
437 request_begin);
438 CHECK(region_space_mem_map != nullptr) << "No region space mem map";
439 region_space_ = space::RegionSpace::Create(kRegionSpaceName, region_space_mem_map);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800440 AddSpace(region_space_);
Richard Uhler054a0782015-04-07 10:56:50 -0700441 } else if (IsMovingGc(foreground_collector_type_) &&
442 foreground_collector_type_ != kCollectorTypeGSS) {
Mathieu Chartierb363f662014-07-16 13:28:58 -0700443 // Create bump pointer spaces.
444 // We only to create the bump pointer if the foreground collector is a compacting GC.
445 // TODO: Place bump-pointer spaces somewhere to minimize size of card table.
446 bump_pointer_space_ = space::BumpPointerSpace::CreateFromMemMap("Bump pointer space 1",
447 main_mem_map_1.release());
448 CHECK(bump_pointer_space_ != nullptr) << "Failed to create bump pointer space";
449 AddSpace(bump_pointer_space_);
450 temp_space_ = space::BumpPointerSpace::CreateFromMemMap("Bump pointer space 2",
451 main_mem_map_2.release());
452 CHECK(temp_space_ != nullptr) << "Failed to create bump pointer space";
453 AddSpace(temp_space_);
454 CHECK(separate_non_moving_space);
Hiroshi Yamauchi5ccd4982014-03-11 12:19:04 -0700455 } else {
Mathieu Chartierb363f662014-07-16 13:28:58 -0700456 CreateMainMallocSpace(main_mem_map_1.release(), initial_size, growth_limit_, capacity_);
457 CHECK(main_space_ != nullptr);
458 AddSpace(main_space_);
459 if (!separate_non_moving_space) {
Zuo Wangf37a88b2014-07-10 04:26:41 -0700460 non_moving_space_ = main_space_;
Mathieu Chartierb363f662014-07-16 13:28:58 -0700461 CHECK(!non_moving_space_->CanMoveObjects());
462 }
463 if (foreground_collector_type_ == kCollectorTypeGSS) {
464 CHECK_EQ(foreground_collector_type_, background_collector_type_);
465 // Create bump pointer spaces instead of a backup space.
466 main_mem_map_2.release();
467 bump_pointer_space_ = space::BumpPointerSpace::Create("Bump pointer space 1",
468 kGSSBumpPointerSpaceCapacity, nullptr);
469 CHECK(bump_pointer_space_ != nullptr);
470 AddSpace(bump_pointer_space_);
471 temp_space_ = space::BumpPointerSpace::Create("Bump pointer space 2",
472 kGSSBumpPointerSpaceCapacity, nullptr);
473 CHECK(temp_space_ != nullptr);
474 AddSpace(temp_space_);
475 } else if (main_mem_map_2.get() != nullptr) {
476 const char* name = kUseRosAlloc ? kRosAllocSpaceName[1] : kDlMallocSpaceName[1];
477 main_space_backup_.reset(CreateMallocSpaceFromMemMap(main_mem_map_2.release(), initial_size,
478 growth_limit_, capacity_, name, true));
479 CHECK(main_space_backup_.get() != nullptr);
480 // Add the space so its accounted for in the heap_begin and heap_end.
481 AddSpace(main_space_backup_.get());
Zuo Wangf37a88b2014-07-10 04:26:41 -0700482 }
Hiroshi Yamauchi5ccd4982014-03-11 12:19:04 -0700483 }
Mathieu Chartier31f44142014-04-08 14:40:03 -0700484 CHECK(non_moving_space_ != nullptr);
Mathieu Chartierb363f662014-07-16 13:28:58 -0700485 CHECK(!non_moving_space_->CanMoveObjects());
Mathieu Chartiereb5710e2013-07-25 15:19:42 -0700486 // Allocate the large object space.
Igor Murashkinaaebaa02015-01-26 10:55:53 -0800487 if (large_object_space_type == space::LargeObjectSpaceType::kFreeList) {
Mathieu Chartier2dbe6272014-09-16 10:43:23 -0700488 large_object_space_ = space::FreeListSpace::Create("free list large object space", nullptr,
489 capacity_);
490 CHECK(large_object_space_ != nullptr) << "Failed to create large object space";
Igor Murashkinaaebaa02015-01-26 10:55:53 -0800491 } else if (large_object_space_type == space::LargeObjectSpaceType::kMap) {
Mathieu Chartier2dbe6272014-09-16 10:43:23 -0700492 large_object_space_ = space::LargeObjectMapSpace::Create("mem map large object space");
493 CHECK(large_object_space_ != nullptr) << "Failed to create large object space";
Mathieu Chartiereb5710e2013-07-25 15:19:42 -0700494 } else {
Mathieu Chartier2dbe6272014-09-16 10:43:23 -0700495 // Disable the large object space by making the cutoff excessively large.
496 large_object_threshold_ = std::numeric_limits<size_t>::max();
497 large_object_space_ = nullptr;
Mathieu Chartiereb5710e2013-07-25 15:19:42 -0700498 }
Mathieu Chartier2dbe6272014-09-16 10:43:23 -0700499 if (large_object_space_ != nullptr) {
500 AddSpace(large_object_space_);
501 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700502 // Compute heap capacity. Continuous spaces are sorted in order of Begin().
Mathieu Chartier590fee92013-09-13 13:46:47 -0700503 CHECK(!continuous_spaces_.empty());
504 // Relies on the spaces being sorted.
Ian Rogers13735952014-10-08 12:43:28 -0700505 uint8_t* heap_begin = continuous_spaces_.front()->Begin();
506 uint8_t* heap_end = continuous_spaces_.back()->Limit();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700507 size_t heap_capacity = heap_end - heap_begin;
Mathieu Chartierb363f662014-07-16 13:28:58 -0700508 // Remove the main backup space since it slows down the GC to have unused extra spaces.
Mathieu Chartier0310da52014-12-01 13:40:48 -0800509 // TODO: Avoid needing to do this.
Mathieu Chartierb363f662014-07-16 13:28:58 -0700510 if (main_space_backup_.get() != nullptr) {
511 RemoveSpace(main_space_backup_.get());
512 }
Elliott Hughes6c9c06d2011-11-07 16:43:47 -0800513 // Allocate the card table.
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800514 // We currently don't support dynamically resizing the card table.
515 // Since we don't know where in the low_4gb the app image will be located, make the card table
516 // cover the whole low_4gb. TODO: Extend the card table in AddSpace.
517 UNUSED(heap_capacity);
518 // Start at 64 KB, we can be sure there are no spaces mapped this low since the address range is
519 // reserved by the kernel.
520 static constexpr size_t kMinHeapAddress = 4 * KB;
521 card_table_.reset(accounting::CardTable::Create(reinterpret_cast<uint8_t*>(kMinHeapAddress),
522 4 * GB - kMinHeapAddress));
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700523 CHECK(card_table_.get() != nullptr) << "Failed to create card table";
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800524 if (foreground_collector_type_ == kCollectorTypeCC && kUseTableLookupReadBarrier) {
525 rb_table_.reset(new accounting::ReadBarrierTable());
526 DCHECK(rb_table_->IsAllCleared());
527 }
Jeff Haodcdc85b2015-12-04 14:06:18 -0800528 if (HasBootImageSpace()) {
Mathieu Chartier4858a932015-01-23 13:18:53 -0800529 // Don't add the image mod union table if we are running without an image, this can crash if
530 // we use the CardCache implementation.
Jeff Haodcdc85b2015-12-04 14:06:18 -0800531 for (space::ImageSpace* image_space : GetBootImageSpaces()) {
532 accounting::ModUnionTable* mod_union_table = new accounting::ModUnionTableToZygoteAllocspace(
533 "Image mod-union table", this, image_space);
534 CHECK(mod_union_table != nullptr) << "Failed to create image mod-union table";
535 AddModUnionTable(mod_union_table);
536 }
Mathieu Chartier4858a932015-01-23 13:18:53 -0800537 }
Mathieu Chartier96bcd452014-06-17 09:50:02 -0700538 if (collector::SemiSpace::kUseRememberedSet && non_moving_space_ != main_space_) {
Hiroshi Yamauchi38e68e92014-03-07 13:59:08 -0800539 accounting::RememberedSet* non_moving_space_rem_set =
540 new accounting::RememberedSet("Non-moving space remembered set", this, non_moving_space_);
541 CHECK(non_moving_space_rem_set != nullptr) << "Failed to create non-moving space remembered set";
542 AddRememberedSet(non_moving_space_rem_set);
543 }
Mathieu Chartierb363f662014-07-16 13:28:58 -0700544 // TODO: Count objects in the image space here?
Ian Rogers3e5cf302014-05-20 16:40:37 -0700545 num_bytes_allocated_.StoreRelaxed(0);
Mathieu Chartierc1790162014-05-23 10:54:50 -0700546 mark_stack_.reset(accounting::ObjectStack::Create("mark stack", kDefaultMarkStackSize,
547 kDefaultMarkStackSize));
548 const size_t alloc_stack_capacity = max_allocation_stack_size_ + kAllocationStackReserveSize;
549 allocation_stack_.reset(accounting::ObjectStack::Create(
550 "allocation stack", max_allocation_stack_size_, alloc_stack_capacity));
551 live_stack_.reset(accounting::ObjectStack::Create(
552 "live stack", max_allocation_stack_size_, alloc_stack_capacity));
Mathieu Chartier65db8802012-11-20 12:36:46 -0800553 // It's still too early to take a lock because there are no threads yet, but we can create locks
554 // now. We don't create it earlier to make it clear that you can't use locks during heap
555 // initialization.
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700556 gc_complete_lock_ = new Mutex("GC complete lock");
Ian Rogersc604d732012-10-14 16:09:54 -0700557 gc_complete_cond_.reset(new ConditionVariable("GC complete condition variable",
558 *gc_complete_lock_));
Richard Uhlercaaa2b02017-02-01 09:54:17 +0000559 native_blocking_gc_lock_ = new Mutex("Native blocking GC lock");
560 native_blocking_gc_cond_.reset(new ConditionVariable("Native blocking GC condition variable",
561 *native_blocking_gc_lock_));
Richard Uhlerda1da8a2017-05-16 13:37:32 +0000562 native_blocking_gc_is_assigned_ = false;
Richard Uhlercaaa2b02017-02-01 09:54:17 +0000563 native_blocking_gc_in_progress_ = false;
564 native_blocking_gcs_finished_ = 0;
565
Hiroshi Yamauchi76f55b02015-08-21 16:10:39 -0700566 thread_flip_lock_ = new Mutex("GC thread flip lock");
567 thread_flip_cond_.reset(new ConditionVariable("GC thread flip condition variable",
568 *thread_flip_lock_));
Mathieu Chartiera5eae692014-12-17 17:56:03 -0800569 task_processor_.reset(new TaskProcessor());
Mathieu Chartier3cf22532015-07-09 15:15:09 -0700570 reference_processor_.reset(new ReferenceProcessor());
Mathieu Chartiera5eae692014-12-17 17:56:03 -0800571 pending_task_lock_ = new Mutex("Pending task lock");
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700572 if (ignore_max_footprint_) {
573 SetIdealFootprint(std::numeric_limits<size_t>::max());
Mathieu Chartier590fee92013-09-13 13:46:47 -0700574 concurrent_start_bytes_ = std::numeric_limits<size_t>::max();
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700575 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700576 CHECK_NE(max_allowed_footprint_, 0U);
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800577 // Create our garbage collectors.
Mathieu Chartier50482232013-11-21 11:48:14 -0800578 for (size_t i = 0; i < 2; ++i) {
579 const bool concurrent = i != 0;
Mathieu Chartierdfe30832015-03-06 15:28:34 -0800580 if ((MayUseCollector(kCollectorTypeCMS) && concurrent) ||
581 (MayUseCollector(kCollectorTypeMS) && !concurrent)) {
582 garbage_collectors_.push_back(new collector::MarkSweep(this, concurrent));
583 garbage_collectors_.push_back(new collector::PartialMarkSweep(this, concurrent));
584 garbage_collectors_.push_back(new collector::StickyMarkSweep(this, concurrent));
585 }
Mathieu Chartier50482232013-11-21 11:48:14 -0800586 }
Mathieu Chartier50482232013-11-21 11:48:14 -0800587 if (kMovingCollector) {
Mathieu Chartierdfe30832015-03-06 15:28:34 -0800588 if (MayUseCollector(kCollectorTypeSS) || MayUseCollector(kCollectorTypeGSS) ||
589 MayUseCollector(kCollectorTypeHomogeneousSpaceCompact) ||
590 use_homogeneous_space_compaction_for_oom_) {
591 // TODO: Clean this up.
592 const bool generational = foreground_collector_type_ == kCollectorTypeGSS;
593 semi_space_collector_ = new collector::SemiSpace(this, generational,
594 generational ? "generational" : "");
595 garbage_collectors_.push_back(semi_space_collector_);
596 }
597 if (MayUseCollector(kCollectorTypeCC)) {
Mathieu Chartier56fe2582016-07-14 13:30:03 -0700598 concurrent_copying_collector_ = new collector::ConcurrentCopying(this,
599 "",
600 measure_gc_performance);
Hiroshi Yamauchi4af14172016-10-25 11:55:10 -0700601 DCHECK(region_space_ != nullptr);
602 concurrent_copying_collector_->SetRegionSpace(region_space_);
Mathieu Chartierdfe30832015-03-06 15:28:34 -0800603 garbage_collectors_.push_back(concurrent_copying_collector_);
604 }
605 if (MayUseCollector(kCollectorTypeMC)) {
606 mark_compact_collector_ = new collector::MarkCompact(this);
607 garbage_collectors_.push_back(mark_compact_collector_);
608 }
Mathieu Chartier0325e622012-09-05 14:22:51 -0700609 }
Jeff Haodcdc85b2015-12-04 14:06:18 -0800610 if (!GetBootImageSpaces().empty() && non_moving_space_ != nullptr &&
Andreas Gampee1cb2982014-08-27 11:01:09 -0700611 (is_zygote || separate_non_moving_space || foreground_collector_type_ == kCollectorTypeGSS)) {
Mathieu Chartierb363f662014-07-16 13:28:58 -0700612 // 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 -0700613 // immune region won't break (eg. due to a large object allocated in the gap). This is only
614 // required when we're the zygote or using GSS.
Mathieu Chartiera06ba052016-01-06 13:51:52 -0800615 // Space with smallest Begin().
616 space::ImageSpace* first_space = nullptr;
617 for (space::ImageSpace* space : boot_image_spaces_) {
618 if (first_space == nullptr || space->Begin() < first_space->Begin()) {
619 first_space = space;
620 }
621 }
622 bool no_gap = MemMap::CheckNoGaps(first_space->GetMemMap(), non_moving_space_->GetMemMap());
Hiroshi Yamauchi3eed93d2014-06-04 11:43:59 -0700623 if (!no_gap) {
David Srbecky5dedb802015-06-17 00:08:02 +0100624 PrintFileToLog("/proc/self/maps", LogSeverity::ERROR);
Andreas Gampe3fec9ac2016-09-13 10:47:28 -0700625 MemMap::DumpMaps(LOG_STREAM(ERROR), true);
Mathieu Chartierc7853442015-03-27 14:35:38 -0700626 LOG(FATAL) << "There's a gap between the image space and the non-moving space";
Hiroshi Yamauchi3eed93d2014-06-04 11:43:59 -0700627 }
628 }
Mathieu Chartier31000802015-06-14 14:14:37 -0700629 instrumentation::Instrumentation* const instrumentation = runtime->GetInstrumentation();
630 if (gc_stress_mode_) {
631 backtrace_lock_ = new Mutex("GC complete lock");
632 }
Evgenii Stepanov1e133742015-05-20 12:30:59 -0700633 if (is_running_on_memory_tool_ || gc_stress_mode_) {
Mathieu Chartier31000802015-06-14 14:14:37 -0700634 instrumentation->InstrumentQuickAllocEntryPoints();
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -0700635 }
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800636 if (VLOG_IS_ON(heap) || VLOG_IS_ON(startup)) {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800637 LOG(INFO) << "Heap() exiting";
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700638 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700639}
640
Mathieu Chartiera4f6af92015-08-11 17:35:25 -0700641MemMap* Heap::MapAnonymousPreferredAddress(const char* name,
642 uint8_t* request_begin,
643 size_t capacity,
644 std::string* out_error_str) {
Mathieu Chartierb363f662014-07-16 13:28:58 -0700645 while (true) {
Kyungmin Leeef32b8f2014-10-23 09:32:05 +0900646 MemMap* map = MemMap::MapAnonymous(name, request_begin, capacity,
Vladimir Marko5c42c292015-02-25 12:02:49 +0000647 PROT_READ | PROT_WRITE, true, false, out_error_str);
Mathieu Chartierb363f662014-07-16 13:28:58 -0700648 if (map != nullptr || request_begin == nullptr) {
649 return map;
650 }
651 // Retry a second time with no specified request begin.
652 request_begin = nullptr;
653 }
Mathieu Chartierb363f662014-07-16 13:28:58 -0700654}
655
Mathieu Chartierdfe30832015-03-06 15:28:34 -0800656bool Heap::MayUseCollector(CollectorType type) const {
657 return foreground_collector_type_ == type || background_collector_type_ == type;
658}
659
Mathieu Chartiera4f6af92015-08-11 17:35:25 -0700660space::MallocSpace* Heap::CreateMallocSpaceFromMemMap(MemMap* mem_map,
661 size_t initial_size,
662 size_t growth_limit,
663 size_t capacity,
664 const char* name,
665 bool can_move_objects) {
Zuo Wangf37a88b2014-07-10 04:26:41 -0700666 space::MallocSpace* malloc_space = nullptr;
667 if (kUseRosAlloc) {
668 // Create rosalloc space.
669 malloc_space = space::RosAllocSpace::CreateFromMemMap(mem_map, name, kDefaultStartingSize,
670 initial_size, growth_limit, capacity,
671 low_memory_mode_, can_move_objects);
672 } else {
673 malloc_space = space::DlMallocSpace::CreateFromMemMap(mem_map, name, kDefaultStartingSize,
674 initial_size, growth_limit, capacity,
675 can_move_objects);
676 }
677 if (collector::SemiSpace::kUseRememberedSet) {
678 accounting::RememberedSet* rem_set =
679 new accounting::RememberedSet(std::string(name) + " remembered set", this, malloc_space);
680 CHECK(rem_set != nullptr) << "Failed to create main space remembered set";
681 AddRememberedSet(rem_set);
682 }
683 CHECK(malloc_space != nullptr) << "Failed to create " << name;
684 malloc_space->SetFootprintLimit(malloc_space->Capacity());
685 return malloc_space;
686}
687
Mathieu Chartier31f44142014-04-08 14:40:03 -0700688void Heap::CreateMainMallocSpace(MemMap* mem_map, size_t initial_size, size_t growth_limit,
689 size_t capacity) {
690 // Is background compaction is enabled?
691 bool can_move_objects = IsMovingGc(background_collector_type_) !=
Zuo Wangf37a88b2014-07-10 04:26:41 -0700692 IsMovingGc(foreground_collector_type_) || use_homogeneous_space_compaction_for_oom_;
Mathieu Chartier31f44142014-04-08 14:40:03 -0700693 // If we are the zygote and don't yet have a zygote space, it means that the zygote fork will
694 // happen in the future. If this happens and we have kCompactZygote enabled we wish to compact
695 // from the main space to the zygote space. If background compaction is enabled, always pass in
696 // that we can move objets.
697 if (kCompactZygote && Runtime::Current()->IsZygote() && !can_move_objects) {
698 // After the zygote we want this to be false if we don't have background compaction enabled so
699 // that getting primitive array elements is faster.
Mathieu Chartierb363f662014-07-16 13:28:58 -0700700 // We never have homogeneous compaction with GSS and don't need a space with movable objects.
Mathieu Chartiere4cab172014-08-19 18:24:04 -0700701 can_move_objects = !HasZygoteSpace() && foreground_collector_type_ != kCollectorTypeGSS;
Mathieu Chartier31f44142014-04-08 14:40:03 -0700702 }
Mathieu Chartier96bcd452014-06-17 09:50:02 -0700703 if (collector::SemiSpace::kUseRememberedSet && main_space_ != nullptr) {
704 RemoveRememberedSet(main_space_);
705 }
Zuo Wangf37a88b2014-07-10 04:26:41 -0700706 const char* name = kUseRosAlloc ? kRosAllocSpaceName[0] : kDlMallocSpaceName[0];
707 main_space_ = CreateMallocSpaceFromMemMap(mem_map, initial_size, growth_limit, capacity, name,
708 can_move_objects);
709 SetSpaceAsDefault(main_space_);
Mathieu Chartier31f44142014-04-08 14:40:03 -0700710 VLOG(heap) << "Created main space " << main_space_;
711}
712
Mathieu Chartier50482232013-11-21 11:48:14 -0800713void Heap::ChangeAllocator(AllocatorType allocator) {
Mathieu Chartier50482232013-11-21 11:48:14 -0800714 if (current_allocator_ != allocator) {
Mathieu Chartierd8891782014-03-02 13:28:37 -0800715 // These two allocators are only used internally and don't have any entrypoints.
716 CHECK_NE(allocator, kAllocatorTypeLOS);
717 CHECK_NE(allocator, kAllocatorTypeNonMoving);
Mathieu Chartier50482232013-11-21 11:48:14 -0800718 current_allocator_ = allocator;
Mathieu Chartierd8891782014-03-02 13:28:37 -0800719 MutexLock mu(nullptr, *Locks::runtime_shutdown_lock_);
Mathieu Chartier50482232013-11-21 11:48:14 -0800720 SetQuickAllocEntryPointsAllocator(current_allocator_);
721 Runtime::Current()->GetInstrumentation()->ResetQuickAllocEntryPoints();
722 }
723}
724
Mathieu Chartier6a7824d2014-08-22 14:53:04 -0700725void Heap::DisableMovingGc() {
Hiroshi Yamauchi60985b72016-08-24 13:53:12 -0700726 CHECK(!kUseReadBarrier);
Mathieu Chartier31f44142014-04-08 14:40:03 -0700727 if (IsMovingGc(foreground_collector_type_)) {
Mathieu Chartier6a7824d2014-08-22 14:53:04 -0700728 foreground_collector_type_ = kCollectorTypeCMS;
Mathieu Chartier6dda8982014-03-06 11:11:48 -0800729 }
Mathieu Chartier31f44142014-04-08 14:40:03 -0700730 if (IsMovingGc(background_collector_type_)) {
731 background_collector_type_ = foreground_collector_type_;
Mathieu Chartier6dda8982014-03-06 11:11:48 -0800732 }
Mathieu Chartier31f44142014-04-08 14:40:03 -0700733 TransitionCollector(foreground_collector_type_);
Mathieu Chartier4f55e222015-09-04 13:26:21 -0700734 Thread* const self = Thread::Current();
Mathieu Chartier6a7824d2014-08-22 14:53:04 -0700735 ScopedThreadStateChange tsc(self, kSuspended);
Mathieu Chartier4f55e222015-09-04 13:26:21 -0700736 ScopedSuspendAll ssa(__FUNCTION__);
Mathieu Chartier6a7824d2014-08-22 14:53:04 -0700737 // Something may have caused the transition to fail.
Mathieu Chartiere4927f62014-08-23 13:56:03 -0700738 if (!IsMovingGc(collector_type_) && non_moving_space_ != main_space_) {
Mathieu Chartier6a7824d2014-08-22 14:53:04 -0700739 CHECK(main_space_ != nullptr);
740 // The allocation stack may have non movable objects in it. We need to flush it since the GC
741 // can't only handle marking allocation stack objects of one non moving space and one main
742 // space.
743 {
744 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
745 FlushAllocStack();
746 }
747 main_space_->DisableMovingObjects();
748 non_moving_space_ = main_space_;
749 CHECK(!non_moving_space_->CanMoveObjects());
750 }
Mathieu Chartier6dda8982014-03-06 11:11:48 -0800751}
752
Mathieu Chartier590fee92013-09-13 13:46:47 -0700753bool Heap::IsCompilingBoot() const {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800754 if (!Runtime::Current()->IsAotCompiler()) {
Alex Light64ad14d2014-08-19 14:23:13 -0700755 return false;
756 }
Mathieu Chartiera9d82fe2016-01-25 20:06:11 -0800757 ScopedObjectAccess soa(Thread::Current());
Mathieu Chartier590fee92013-09-13 13:46:47 -0700758 for (const auto& space : continuous_spaces_) {
Mathieu Chartier4e305412014-02-19 10:54:44 -0800759 if (space->IsImageSpace() || space->IsZygoteSpace()) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700760 return false;
761 }
762 }
763 return true;
764}
765
Mathieu Chartier1d27b342014-01-28 12:51:09 -0800766void Heap::IncrementDisableMovingGC(Thread* self) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700767 // Need to do this holding the lock to prevent races where the GC is about to run / running when
768 // we attempt to disable it.
Mathieu Chartiercaa82d62014-02-02 16:51:17 -0800769 ScopedThreadStateChange tsc(self, kWaitingForGcToComplete);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700770 MutexLock mu(self, *gc_complete_lock_);
Mathieu Chartier1d27b342014-01-28 12:51:09 -0800771 ++disable_moving_gc_count_;
Mathieu Chartier31f44142014-04-08 14:40:03 -0700772 if (IsMovingGc(collector_type_running_)) {
Mathieu Chartier89a201e2014-05-02 10:27:26 -0700773 WaitForGcToCompleteLocked(kGcCauseDisableMovingGc, self);
Mathieu Chartierd5a89ee2014-01-31 09:55:13 -0800774 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700775}
776
Mathieu Chartier1d27b342014-01-28 12:51:09 -0800777void Heap::DecrementDisableMovingGC(Thread* self) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700778 MutexLock mu(self, *gc_complete_lock_);
Mathieu Chartierb735bd92015-06-24 17:04:17 -0700779 CHECK_GT(disable_moving_gc_count_, 0U);
Mathieu Chartier1d27b342014-01-28 12:51:09 -0800780 --disable_moving_gc_count_;
Mathieu Chartier590fee92013-09-13 13:46:47 -0700781}
782
Hiroshi Yamauchi76f55b02015-08-21 16:10:39 -0700783void Heap::IncrementDisableThreadFlip(Thread* self) {
784 // Supposed to be called by mutators. If thread_flip_running_ is true, block. Otherwise, go ahead.
785 CHECK(kUseReadBarrier);
Hiroshi Yamauchi20a0be02016-02-19 15:44:06 -0800786 bool is_nested = self->GetDisableThreadFlipCount() > 0;
787 self->IncrementDisableThreadFlipCount();
788 if (is_nested) {
789 // If this is a nested JNI critical section enter, we don't need to wait or increment the global
790 // counter. The global counter is incremented only once for a thread for the outermost enter.
791 return;
792 }
Hiroshi Yamauchi76f55b02015-08-21 16:10:39 -0700793 ScopedThreadStateChange tsc(self, kWaitingForGcThreadFlip);
794 MutexLock mu(self, *thread_flip_lock_);
795 bool has_waited = false;
796 uint64_t wait_start = NanoTime();
Hiroshi Yamauchiee235822016-08-19 17:03:27 -0700797 if (thread_flip_running_) {
Hiroshi Yamauchi6fb276b2016-08-26 10:39:29 -0700798 ATRACE_BEGIN("IncrementDisableThreadFlip");
Hiroshi Yamauchiee235822016-08-19 17:03:27 -0700799 while (thread_flip_running_) {
800 has_waited = true;
801 thread_flip_cond_->Wait(self);
802 }
Hiroshi Yamauchi6fb276b2016-08-26 10:39:29 -0700803 ATRACE_END();
Hiroshi Yamauchi76f55b02015-08-21 16:10:39 -0700804 }
805 ++disable_thread_flip_count_;
806 if (has_waited) {
807 uint64_t wait_time = NanoTime() - wait_start;
808 total_wait_time_ += wait_time;
809 if (wait_time > long_pause_log_threshold_) {
810 LOG(INFO) << __FUNCTION__ << " blocked for " << PrettyDuration(wait_time);
811 }
812 }
813}
814
815void Heap::DecrementDisableThreadFlip(Thread* self) {
816 // Supposed to be called by mutators. Decrement disable_thread_flip_count_ and potentially wake up
817 // the GC waiting before doing a thread flip.
818 CHECK(kUseReadBarrier);
Hiroshi Yamauchi20a0be02016-02-19 15:44:06 -0800819 self->DecrementDisableThreadFlipCount();
820 bool is_outermost = self->GetDisableThreadFlipCount() == 0;
821 if (!is_outermost) {
822 // If this is not an outermost JNI critical exit, we don't need to decrement the global counter.
823 // The global counter is decremented only once for a thread for the outermost exit.
824 return;
825 }
Hiroshi Yamauchi76f55b02015-08-21 16:10:39 -0700826 MutexLock mu(self, *thread_flip_lock_);
827 CHECK_GT(disable_thread_flip_count_, 0U);
828 --disable_thread_flip_count_;
Hiroshi Yamauchi20a0be02016-02-19 15:44:06 -0800829 if (disable_thread_flip_count_ == 0) {
830 // Potentially notify the GC thread blocking to begin a thread flip.
831 thread_flip_cond_->Broadcast(self);
832 }
Hiroshi Yamauchi76f55b02015-08-21 16:10:39 -0700833}
834
835void Heap::ThreadFlipBegin(Thread* self) {
836 // Supposed to be called by GC. Set thread_flip_running_ to be true. If disable_thread_flip_count_
837 // > 0, block. Otherwise, go ahead.
838 CHECK(kUseReadBarrier);
839 ScopedThreadStateChange tsc(self, kWaitingForGcThreadFlip);
840 MutexLock mu(self, *thread_flip_lock_);
841 bool has_waited = false;
842 uint64_t wait_start = NanoTime();
843 CHECK(!thread_flip_running_);
Hiroshi Yamauchi20a0be02016-02-19 15:44:06 -0800844 // Set this to true before waiting so that frequent JNI critical enter/exits won't starve
845 // GC. This like a writer preference of a reader-writer lock.
Hiroshi Yamauchi76f55b02015-08-21 16:10:39 -0700846 thread_flip_running_ = true;
847 while (disable_thread_flip_count_ > 0) {
848 has_waited = true;
849 thread_flip_cond_->Wait(self);
850 }
851 if (has_waited) {
852 uint64_t wait_time = NanoTime() - wait_start;
853 total_wait_time_ += wait_time;
854 if (wait_time > long_pause_log_threshold_) {
855 LOG(INFO) << __FUNCTION__ << " blocked for " << PrettyDuration(wait_time);
856 }
857 }
858}
859
860void Heap::ThreadFlipEnd(Thread* self) {
861 // Supposed to be called by GC. Set thread_flip_running_ to false and potentially wake up mutators
862 // waiting before doing a JNI critical.
863 CHECK(kUseReadBarrier);
864 MutexLock mu(self, *thread_flip_lock_);
865 CHECK(thread_flip_running_);
866 thread_flip_running_ = false;
Hiroshi Yamauchi20a0be02016-02-19 15:44:06 -0800867 // Potentially notify mutator threads blocking to enter a JNI critical section.
Hiroshi Yamauchi76f55b02015-08-21 16:10:39 -0700868 thread_flip_cond_->Broadcast(self);
869}
870
Mathieu Chartierf8cb1782016-03-18 18:45:41 -0700871void Heap::UpdateProcessState(ProcessState old_process_state, ProcessState new_process_state) {
872 if (old_process_state != new_process_state) {
873 const bool jank_perceptible = new_process_state == kProcessStateJankPerceptible;
Mathieu Chartier91e30632014-03-25 15:58:50 -0700874 for (size_t i = 1; i <= kCollectorTransitionStressIterations; ++i) {
875 // Start at index 1 to avoid "is always false" warning.
876 // Have iteration 1 always transition the collector.
Mathieu Chartierf8cb1782016-03-18 18:45:41 -0700877 TransitionCollector((((i & 1) == 1) == jank_perceptible)
878 ? foreground_collector_type_
879 : background_collector_type_);
Mathieu Chartier91e30632014-03-25 15:58:50 -0700880 usleep(kCollectorTransitionStressWait);
881 }
Mathieu Chartierf8cb1782016-03-18 18:45:41 -0700882 if (jank_perceptible) {
Mathieu Chartiera5f9de02014-02-28 16:48:42 -0800883 // Transition back to foreground right away to prevent jank.
Mathieu Chartier31f44142014-04-08 14:40:03 -0700884 RequestCollectorTransition(foreground_collector_type_, 0);
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800885 } else {
Mathieu Chartiera5f9de02014-02-28 16:48:42 -0800886 // Don't delay for debug builds since we may want to stress test the GC.
Zuo Wangf37a88b2014-07-10 04:26:41 -0700887 // If background_collector_type_ is kCollectorTypeHomogeneousSpaceCompact then we have
888 // special handling which does a homogenous space compaction once but then doesn't transition
Hiroshi Yamauchi60985b72016-08-24 13:53:12 -0700889 // the collector. Similarly, we invoke a full compaction for kCollectorTypeCC but don't
890 // transition the collector.
Zuo Wangf37a88b2014-07-10 04:26:41 -0700891 RequestCollectorTransition(background_collector_type_,
892 kIsDebugBuild ? 0 : kCollectorTransitionWait);
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800893 }
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800894 }
Mathieu Chartierca2a24d2013-11-25 15:12:12 -0800895}
896
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700897void Heap::CreateThreadPool() {
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700898 const size_t num_threads = std::max(parallel_gc_threads_, conc_gc_threads_);
899 if (num_threads != 0) {
Mathieu Chartierbcd5e9d2013-11-13 14:33:28 -0800900 thread_pool_.reset(new ThreadPool("Heap thread pool", num_threads));
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700901 }
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700902}
903
Mathieu Chartier590fee92013-09-13 13:46:47 -0700904void Heap::MarkAllocStackAsLive(accounting::ObjectStack* stack) {
Mathieu Chartier00b59152014-07-25 10:13:51 -0700905 space::ContinuousSpace* space1 = main_space_ != nullptr ? main_space_ : non_moving_space_;
906 space::ContinuousSpace* space2 = non_moving_space_;
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800907 // TODO: Generalize this to n bitmaps?
Mathieu Chartier00b59152014-07-25 10:13:51 -0700908 CHECK(space1 != nullptr);
909 CHECK(space2 != nullptr);
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800910 MarkAllocStack(space1->GetLiveBitmap(), space2->GetLiveBitmap(),
Mathieu Chartier2dbe6272014-09-16 10:43:23 -0700911 (large_object_space_ != nullptr ? large_object_space_->GetLiveBitmap() : nullptr),
912 stack);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700913}
914
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700915void Heap::DeleteThreadPool() {
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700916 thread_pool_.reset(nullptr);
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700917}
918
Mathieu Chartier1b54f9c2014-04-30 16:45:02 -0700919void Heap::AddSpace(space::Space* space) {
Zuo Wangf37a88b2014-07-10 04:26:41 -0700920 CHECK(space != nullptr);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700921 WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
922 if (space->IsContinuousSpace()) {
923 DCHECK(!space->IsDiscontinuousSpace());
924 space::ContinuousSpace* continuous_space = space->AsContinuousSpace();
925 // Continuous spaces don't necessarily have bitmaps.
Mathieu Chartiera8e8f9c2014-04-09 14:51:05 -0700926 accounting::ContinuousSpaceBitmap* live_bitmap = continuous_space->GetLiveBitmap();
927 accounting::ContinuousSpaceBitmap* mark_bitmap = continuous_space->GetMarkBitmap();
Mathieu Chartierecc82302017-02-16 10:20:12 -0800928 // The region space bitmap is not added since VisitObjects visits the region space objects with
929 // special handling.
930 if (live_bitmap != nullptr && !space->IsRegionSpace()) {
Mathieu Chartier2796a162014-07-25 11:50:47 -0700931 CHECK(mark_bitmap != nullptr);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700932 live_bitmap_->AddContinuousSpaceBitmap(live_bitmap);
933 mark_bitmap_->AddContinuousSpaceBitmap(mark_bitmap);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700934 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700935 continuous_spaces_.push_back(continuous_space);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700936 // Ensure that spaces remain sorted in increasing order of start address.
937 std::sort(continuous_spaces_.begin(), continuous_spaces_.end(),
938 [](const space::ContinuousSpace* a, const space::ContinuousSpace* b) {
939 return a->Begin() < b->Begin();
940 });
Mathieu Chartier590fee92013-09-13 13:46:47 -0700941 } else {
Mathieu Chartier2796a162014-07-25 11:50:47 -0700942 CHECK(space->IsDiscontinuousSpace());
Mathieu Chartier590fee92013-09-13 13:46:47 -0700943 space::DiscontinuousSpace* discontinuous_space = space->AsDiscontinuousSpace();
Mathieu Chartierbbd695c2014-04-16 09:48:48 -0700944 live_bitmap_->AddLargeObjectBitmap(discontinuous_space->GetLiveBitmap());
945 mark_bitmap_->AddLargeObjectBitmap(discontinuous_space->GetMarkBitmap());
Mathieu Chartier590fee92013-09-13 13:46:47 -0700946 discontinuous_spaces_.push_back(discontinuous_space);
947 }
948 if (space->IsAllocSpace()) {
949 alloc_spaces_.push_back(space->AsAllocSpace());
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700950 }
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800951}
952
Mathieu Chartier1b54f9c2014-04-30 16:45:02 -0700953void Heap::SetSpaceAsDefault(space::ContinuousSpace* continuous_space) {
954 WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
955 if (continuous_space->IsDlMallocSpace()) {
956 dlmalloc_space_ = continuous_space->AsDlMallocSpace();
957 } else if (continuous_space->IsRosAllocSpace()) {
958 rosalloc_space_ = continuous_space->AsRosAllocSpace();
959 }
960}
961
962void Heap::RemoveSpace(space::Space* space) {
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800963 DCHECK(space != nullptr);
964 WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
965 if (space->IsContinuousSpace()) {
966 DCHECK(!space->IsDiscontinuousSpace());
967 space::ContinuousSpace* continuous_space = space->AsContinuousSpace();
968 // Continuous spaces don't necessarily have bitmaps.
Mathieu Chartiera8e8f9c2014-04-09 14:51:05 -0700969 accounting::ContinuousSpaceBitmap* live_bitmap = continuous_space->GetLiveBitmap();
970 accounting::ContinuousSpaceBitmap* mark_bitmap = continuous_space->GetMarkBitmap();
Mathieu Chartierecc82302017-02-16 10:20:12 -0800971 if (live_bitmap != nullptr && !space->IsRegionSpace()) {
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800972 DCHECK(mark_bitmap != nullptr);
973 live_bitmap_->RemoveContinuousSpaceBitmap(live_bitmap);
974 mark_bitmap_->RemoveContinuousSpaceBitmap(mark_bitmap);
975 }
976 auto it = std::find(continuous_spaces_.begin(), continuous_spaces_.end(), continuous_space);
977 DCHECK(it != continuous_spaces_.end());
978 continuous_spaces_.erase(it);
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800979 } else {
980 DCHECK(space->IsDiscontinuousSpace());
981 space::DiscontinuousSpace* discontinuous_space = space->AsDiscontinuousSpace();
Mathieu Chartierbbd695c2014-04-16 09:48:48 -0700982 live_bitmap_->RemoveLargeObjectBitmap(discontinuous_space->GetLiveBitmap());
983 mark_bitmap_->RemoveLargeObjectBitmap(discontinuous_space->GetMarkBitmap());
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800984 auto it = std::find(discontinuous_spaces_.begin(), discontinuous_spaces_.end(),
985 discontinuous_space);
986 DCHECK(it != discontinuous_spaces_.end());
987 discontinuous_spaces_.erase(it);
988 }
989 if (space->IsAllocSpace()) {
990 auto it = std::find(alloc_spaces_.begin(), alloc_spaces_.end(), space->AsAllocSpace());
991 DCHECK(it != alloc_spaces_.end());
992 alloc_spaces_.erase(it);
993 }
994}
995
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700996void Heap::DumpGcPerformanceInfo(std::ostream& os) {
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700997 // Dump cumulative timings.
Elliott Hughes8b788fe2013-04-17 15:57:01 -0700998 os << "Dumping cumulative Gc timings\n";
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700999 uint64_t total_duration = 0;
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001000 // Dump cumulative loggers for each GC type.
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001001 uint64_t total_paused_time = 0;
Mathieu Chartier5a487192014-04-08 11:14:54 -07001002 for (auto& collector : garbage_collectors_) {
Mathieu Chartier104fa0c2014-08-07 14:26:27 -07001003 total_duration += collector->GetCumulativeTimings().GetTotalNs();
1004 total_paused_time += collector->GetTotalPausedTimeNs();
1005 collector->DumpPerformanceInfo(os);
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001006 }
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001007 if (total_duration != 0) {
Brian Carlstrom2d888622013-07-18 17:02:00 -07001008 const double total_seconds = static_cast<double>(total_duration / 1000) / 1000000.0;
Elliott Hughes8b788fe2013-04-17 15:57:01 -07001009 os << "Total time spent in GC: " << PrettyDuration(total_duration) << "\n";
1010 os << "Mean GC size throughput: "
Ian Rogers1d54e732013-05-02 21:10:01 -07001011 << PrettySize(GetBytesFreedEver() / total_seconds) << "/s\n";
Elliott Hughes8b788fe2013-04-17 15:57:01 -07001012 os << "Mean GC object throughput: "
Ian Rogers1d54e732013-05-02 21:10:01 -07001013 << (GetObjectsFreedEver() / total_seconds) << " objects/s\n";
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001014 }
Mathieu Chartierdd162fb2014-08-06 17:06:33 -07001015 uint64_t total_objects_allocated = GetObjectsAllocatedEver();
Mathieu Chartierc30a7252014-08-12 10:13:48 -07001016 os << "Total number of allocations " << total_objects_allocated << "\n";
Hiroshi Yamauchia1c9f012015-04-02 10:18:12 -07001017 os << "Total bytes allocated " << PrettySize(GetBytesAllocatedEver()) << "\n";
1018 os << "Total bytes freed " << PrettySize(GetBytesFreedEver()) << "\n";
Mathieu Chartierc30a7252014-08-12 10:13:48 -07001019 os << "Free memory " << PrettySize(GetFreeMemory()) << "\n";
Mathieu Chartierdd162fb2014-08-06 17:06:33 -07001020 os << "Free memory until GC " << PrettySize(GetFreeMemoryUntilGC()) << "\n";
1021 os << "Free memory until OOME " << PrettySize(GetFreeMemoryUntilOOME()) << "\n";
Mathieu Chartierc30a7252014-08-12 10:13:48 -07001022 os << "Total memory " << PrettySize(GetTotalMemory()) << "\n";
1023 os << "Max memory " << PrettySize(GetMaxMemory()) << "\n";
Mathieu Chartiere4cab172014-08-19 18:24:04 -07001024 if (HasZygoteSpace()) {
1025 os << "Zygote space size " << PrettySize(zygote_space_->Size()) << "\n";
1026 }
Elliott Hughes8b788fe2013-04-17 15:57:01 -07001027 os << "Total mutator paused time: " << PrettyDuration(total_paused_time) << "\n";
Hiroshi Yamauchia1c9f012015-04-02 10:18:12 -07001028 os << "Total time waiting for GC to complete: " << PrettyDuration(total_wait_time_) << "\n";
1029 os << "Total GC count: " << GetGcCount() << "\n";
1030 os << "Total GC time: " << PrettyDuration(GetGcTime()) << "\n";
1031 os << "Total blocking GC count: " << GetBlockingGcCount() << "\n";
1032 os << "Total blocking GC time: " << PrettyDuration(GetBlockingGcTime()) << "\n";
1033
1034 {
1035 MutexLock mu(Thread::Current(), *gc_complete_lock_);
1036 if (gc_count_rate_histogram_.SampleSize() > 0U) {
1037 os << "Histogram of GC count per " << NsToMs(kGcCountRateHistogramWindowDuration) << " ms: ";
1038 gc_count_rate_histogram_.DumpBins(os);
1039 os << "\n";
1040 }
1041 if (blocking_gc_count_rate_histogram_.SampleSize() > 0U) {
1042 os << "Histogram of blocking GC count per "
1043 << NsToMs(kGcCountRateHistogramWindowDuration) << " ms: ";
1044 blocking_gc_count_rate_histogram_.DumpBins(os);
1045 os << "\n";
1046 }
1047 }
1048
Hiroshi Yamauchib62f2e62016-03-23 15:51:24 -07001049 if (kDumpRosAllocStatsOnSigQuit && rosalloc_space_ != nullptr) {
1050 rosalloc_space_->DumpStats(os);
1051 }
1052
Richard Uhlercaaa2b02017-02-01 09:54:17 +00001053 os << "Registered native bytes allocated: "
1054 << old_native_bytes_allocated_.LoadRelaxed() + new_native_bytes_allocated_.LoadRelaxed()
1055 << "\n";
Mathieu Chartier5d2a3f72016-05-11 11:35:39 -07001056
Mathieu Chartier73d1e172014-04-11 17:53:48 -07001057 BaseMutex::DumpAll(os);
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001058}
1059
Hiroshi Yamauchi37670172015-06-10 17:20:54 -07001060void Heap::ResetGcPerformanceInfo() {
1061 for (auto& collector : garbage_collectors_) {
1062 collector->ResetMeasurements();
1063 }
Hiroshi Yamauchi37670172015-06-10 17:20:54 -07001064 total_bytes_freed_ever_ = 0;
1065 total_objects_freed_ever_ = 0;
1066 total_wait_time_ = 0;
1067 blocking_gc_count_ = 0;
1068 blocking_gc_time_ = 0;
1069 gc_count_last_window_ = 0;
1070 blocking_gc_count_last_window_ = 0;
1071 last_update_time_gc_count_rate_histograms_ = // Round down by the window duration.
1072 (NanoTime() / kGcCountRateHistogramWindowDuration) * kGcCountRateHistogramWindowDuration;
1073 {
1074 MutexLock mu(Thread::Current(), *gc_complete_lock_);
1075 gc_count_rate_histogram_.Reset();
1076 blocking_gc_count_rate_histogram_.Reset();
1077 }
1078}
1079
Hiroshi Yamauchia1c9f012015-04-02 10:18:12 -07001080uint64_t Heap::GetGcCount() const {
1081 uint64_t gc_count = 0U;
1082 for (auto& collector : garbage_collectors_) {
1083 gc_count += collector->GetCumulativeTimings().GetIterations();
1084 }
1085 return gc_count;
1086}
1087
1088uint64_t Heap::GetGcTime() const {
1089 uint64_t gc_time = 0U;
1090 for (auto& collector : garbage_collectors_) {
1091 gc_time += collector->GetCumulativeTimings().GetTotalNs();
1092 }
1093 return gc_time;
1094}
1095
1096uint64_t Heap::GetBlockingGcCount() const {
1097 return blocking_gc_count_;
1098}
1099
1100uint64_t Heap::GetBlockingGcTime() const {
1101 return blocking_gc_time_;
1102}
1103
1104void Heap::DumpGcCountRateHistogram(std::ostream& os) const {
1105 MutexLock mu(Thread::Current(), *gc_complete_lock_);
1106 if (gc_count_rate_histogram_.SampleSize() > 0U) {
1107 gc_count_rate_histogram_.DumpBins(os);
1108 }
1109}
1110
1111void Heap::DumpBlockingGcCountRateHistogram(std::ostream& os) const {
1112 MutexLock mu(Thread::Current(), *gc_complete_lock_);
1113 if (blocking_gc_count_rate_histogram_.SampleSize() > 0U) {
1114 blocking_gc_count_rate_histogram_.DumpBins(os);
1115 }
1116}
1117
Andreas Gampe27fa96c2016-10-07 15:05:24 -07001118ALWAYS_INLINE
1119static inline AllocationListener* GetAndOverwriteAllocationListener(
1120 Atomic<AllocationListener*>* storage, AllocationListener* new_value) {
1121 AllocationListener* old;
1122 do {
1123 old = storage->LoadSequentiallyConsistent();
1124 } while (!storage->CompareExchangeStrongSequentiallyConsistent(old, new_value));
1125 return old;
1126}
1127
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08001128Heap::~Heap() {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001129 VLOG(heap) << "Starting ~Heap()";
Mathieu Chartier590fee92013-09-13 13:46:47 -07001130 STLDeleteElements(&garbage_collectors_);
1131 // If we don't reset then the mark stack complains in its destructor.
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001132 allocation_stack_->Reset();
Man Cao8c2ff642015-05-27 17:25:30 -07001133 allocation_records_.reset();
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001134 live_stack_->Reset();
Mathieu Chartier11409ae2013-09-23 11:49:36 -07001135 STLDeleteValues(&mod_union_tables_);
Mathieu Chartier0767c9a2014-03-26 12:53:19 -07001136 STLDeleteValues(&remembered_sets_);
Ian Rogers1d54e732013-05-02 21:10:01 -07001137 STLDeleteElements(&continuous_spaces_);
1138 STLDeleteElements(&discontinuous_spaces_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001139 delete gc_complete_lock_;
Richard Uhlercaaa2b02017-02-01 09:54:17 +00001140 delete native_blocking_gc_lock_;
Andreas Gampe6be4f2a2015-11-10 13:34:17 -08001141 delete thread_flip_lock_;
Mathieu Chartiera5eae692014-12-17 17:56:03 -08001142 delete pending_task_lock_;
Mathieu Chartier31000802015-06-14 14:14:37 -07001143 delete backtrace_lock_;
1144 if (unique_backtrace_count_.LoadRelaxed() != 0 || seen_backtrace_count_.LoadRelaxed() != 0) {
1145 LOG(INFO) << "gc stress unique=" << unique_backtrace_count_.LoadRelaxed()
1146 << " total=" << seen_backtrace_count_.LoadRelaxed() +
1147 unique_backtrace_count_.LoadRelaxed();
1148 }
Andreas Gampe27fa96c2016-10-07 15:05:24 -07001149
Mathieu Chartier590fee92013-09-13 13:46:47 -07001150 VLOG(heap) << "Finished ~Heap()";
Carl Shapiro69759ea2011-07-21 18:13:35 -07001151}
1152
Mathieu Chartier9d156d52016-10-06 17:44:26 -07001153
1154space::ContinuousSpace* Heap::FindContinuousSpaceFromAddress(const mirror::Object* addr) const {
Mathieu Chartier02e25112013-08-14 16:14:24 -07001155 for (const auto& space : continuous_spaces_) {
Mathieu Chartier9d156d52016-10-06 17:44:26 -07001156 if (space->Contains(addr)) {
Mathieu Chartier02e25112013-08-14 16:14:24 -07001157 return space;
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07001158 }
1159 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001160 return nullptr;
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07001161}
1162
Mathieu Chartier9d156d52016-10-06 17:44:26 -07001163space::ContinuousSpace* Heap::FindContinuousSpaceFromObject(ObjPtr<mirror::Object> obj,
1164 bool fail_ok) const {
1165 space::ContinuousSpace* space = FindContinuousSpaceFromAddress(obj.Ptr());
1166 if (space != nullptr) {
1167 return space;
1168 }
1169 if (!fail_ok) {
1170 LOG(FATAL) << "object " << obj << " not inside any spaces!";
1171 }
1172 return nullptr;
1173}
1174
1175space::DiscontinuousSpace* Heap::FindDiscontinuousSpaceFromObject(ObjPtr<mirror::Object> obj,
Ian Rogers1d54e732013-05-02 21:10:01 -07001176 bool fail_ok) const {
Mathieu Chartier02e25112013-08-14 16:14:24 -07001177 for (const auto& space : discontinuous_spaces_) {
Mathieu Chartier9d156d52016-10-06 17:44:26 -07001178 if (space->Contains(obj.Ptr())) {
Mathieu Chartier02e25112013-08-14 16:14:24 -07001179 return space;
Ian Rogers1d54e732013-05-02 21:10:01 -07001180 }
1181 }
1182 if (!fail_ok) {
Mathieu Chartier9d156d52016-10-06 17:44:26 -07001183 LOG(FATAL) << "object " << obj << " not inside any spaces!";
Ian Rogers1d54e732013-05-02 21:10:01 -07001184 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001185 return nullptr;
Ian Rogers1d54e732013-05-02 21:10:01 -07001186}
1187
Mathieu Chartier9d156d52016-10-06 17:44:26 -07001188space::Space* Heap::FindSpaceFromObject(ObjPtr<mirror::Object> obj, bool fail_ok) const {
Ian Rogers1d54e732013-05-02 21:10:01 -07001189 space::Space* result = FindContinuousSpaceFromObject(obj, true);
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001190 if (result != nullptr) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001191 return result;
1192 }
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07001193 return FindDiscontinuousSpaceFromObject(obj, fail_ok);
Ian Rogers1d54e732013-05-02 21:10:01 -07001194}
1195
Mathieu Chartier9d156d52016-10-06 17:44:26 -07001196space::Space* Heap::FindSpaceFromAddress(const void* addr) const {
1197 for (const auto& space : continuous_spaces_) {
1198 if (space->Contains(reinterpret_cast<const mirror::Object*>(addr))) {
1199 return space;
1200 }
1201 }
1202 for (const auto& space : discontinuous_spaces_) {
1203 if (space->Contains(reinterpret_cast<const mirror::Object*>(addr))) {
1204 return space;
1205 }
1206 }
1207 return nullptr;
1208}
1209
1210
Hiroshi Yamauchi654dd482014-07-09 12:54:32 -07001211void Heap::ThrowOutOfMemoryError(Thread* self, size_t byte_count, AllocatorType allocator_type) {
Mathieu Chartiere8f3f032016-04-04 16:49:44 -07001212 // If we're in a stack overflow, do not create a new exception. It would require running the
1213 // constructor, which will of course still be in a stack overflow.
1214 if (self->IsHandlingStackOverflow()) {
1215 self->SetException(Runtime::Current()->GetPreAllocatedOutOfMemoryError());
1216 return;
1217 }
1218
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -07001219 std::ostringstream oss;
Ian Rogersef7d42f2014-01-06 12:55:46 -08001220 size_t total_bytes_free = GetFreeMemory();
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -07001221 oss << "Failed to allocate a " << byte_count << " byte allocation with " << total_bytes_free
Mathieu Chartiera9033d72016-12-01 17:41:17 -08001222 << " free bytes and " << PrettySize(GetFreeMemoryUntilOOME()) << " until OOM,"
1223 << " max allowed footprint " << max_allowed_footprint_ << ", growth limit "
1224 << growth_limit_;
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -07001225 // If the allocation failed due to fragmentation, print out the largest continuous allocation.
Zuo Wangf37a88b2014-07-10 04:26:41 -07001226 if (total_bytes_free >= byte_count) {
Mathieu Chartierb363f662014-07-16 13:28:58 -07001227 space::AllocSpace* space = nullptr;
Hiroshi Yamauchi654dd482014-07-09 12:54:32 -07001228 if (allocator_type == kAllocatorTypeNonMoving) {
1229 space = non_moving_space_;
1230 } else if (allocator_type == kAllocatorTypeRosAlloc ||
1231 allocator_type == kAllocatorTypeDlMalloc) {
1232 space = main_space_;
Mathieu Chartierb363f662014-07-16 13:28:58 -07001233 } else if (allocator_type == kAllocatorTypeBumpPointer ||
1234 allocator_type == kAllocatorTypeTLAB) {
1235 space = bump_pointer_space_;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001236 } else if (allocator_type == kAllocatorTypeRegion ||
1237 allocator_type == kAllocatorTypeRegionTLAB) {
1238 space = region_space_;
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -07001239 }
Hiroshi Yamauchi654dd482014-07-09 12:54:32 -07001240 if (space != nullptr) {
1241 space->LogFragmentationAllocFailure(oss, byte_count);
1242 }
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001243 }
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -07001244 self->ThrowOutOfMemoryError(oss.str().c_str());
1245}
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001246
Mathieu Chartiera5eae692014-12-17 17:56:03 -08001247void Heap::DoPendingCollectorTransition() {
1248 CollectorType desired_collector_type = desired_collector_type_;
Mathieu Chartierb2728552014-09-08 20:08:41 +00001249 // Launch homogeneous space compaction if it is desired.
1250 if (desired_collector_type == kCollectorTypeHomogeneousSpaceCompact) {
1251 if (!CareAboutPauseTimes()) {
1252 PerformHomogeneousSpaceCompact();
Mathieu Chartiera5eae692014-12-17 17:56:03 -08001253 } else {
1254 VLOG(gc) << "Homogeneous compaction ignored due to jank perceptible process state";
Mathieu Chartierb2728552014-09-08 20:08:41 +00001255 }
Hiroshi Yamauchi60985b72016-08-24 13:53:12 -07001256 } else if (desired_collector_type == kCollectorTypeCCBackground) {
1257 DCHECK(kUseReadBarrier);
1258 if (!CareAboutPauseTimes()) {
1259 // Invoke CC full compaction.
1260 CollectGarbageInternal(collector::kGcTypeFull,
1261 kGcCauseCollectorTransition,
1262 /*clear_soft_references*/false);
1263 } else {
1264 VLOG(gc) << "CC background compaction ignored due to jank perceptible process state";
1265 }
Mathieu Chartiera5eae692014-12-17 17:56:03 -08001266 } else {
1267 TransitionCollector(desired_collector_type);
Mathieu Chartierb2728552014-09-08 20:08:41 +00001268 }
Mathieu Chartiera5eae692014-12-17 17:56:03 -08001269}
1270
1271void Heap::Trim(Thread* self) {
Mathieu Chartier8d447252015-10-26 10:21:14 -07001272 Runtime* const runtime = Runtime::Current();
Mathieu Chartier440e4ce2014-03-31 16:36:35 -07001273 if (!CareAboutPauseTimes()) {
1274 // Deflate the monitors, this can cause a pause but shouldn't matter since we don't care
1275 // about pauses.
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001276 ScopedTrace trace("Deflating monitors");
Hiroshi Yamauchi3b1d1b72016-10-12 11:53:57 -07001277 // Avoid race conditions on the lock word for CC.
1278 ScopedGCCriticalSection gcs(self, kGcCauseTrim, kCollectorTypeHeapTrim);
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001279 ScopedSuspendAll ssa(__FUNCTION__);
1280 uint64_t start_time = NanoTime();
1281 size_t count = runtime->GetMonitorList()->DeflateMonitors();
1282 VLOG(heap) << "Deflating " << count << " monitors took "
1283 << PrettyDuration(NanoTime() - start_time);
Mathieu Chartier440e4ce2014-03-31 16:36:35 -07001284 }
Mathieu Chartiera5eae692014-12-17 17:56:03 -08001285 TrimIndirectReferenceTables(self);
1286 TrimSpaces(self);
Mathieu Chartier8d447252015-10-26 10:21:14 -07001287 // Trim arenas that may have been used by JIT or verifier.
Mathieu Chartier8d447252015-10-26 10:21:14 -07001288 runtime->GetArenaPool()->TrimMaps();
Mathieu Chartiera5f9de02014-02-28 16:48:42 -08001289}
1290
Mathieu Chartier91c2f0c2014-11-26 11:21:15 -08001291class TrimIndirectReferenceTableClosure : public Closure {
1292 public:
1293 explicit TrimIndirectReferenceTableClosure(Barrier* barrier) : barrier_(barrier) {
1294 }
1295 virtual void Run(Thread* thread) OVERRIDE NO_THREAD_SAFETY_ANALYSIS {
Mathieu Chartier91c2f0c2014-11-26 11:21:15 -08001296 thread->GetJniEnv()->locals.Trim();
Lei Lidd9943d2015-02-02 14:24:44 +08001297 // If thread is a running mutator, then act on behalf of the trim thread.
1298 // See the code in ThreadList::RunCheckpoint.
Mathieu Chartier10d25082015-10-28 18:36:09 -07001299 barrier_->Pass(Thread::Current());
Mathieu Chartier91c2f0c2014-11-26 11:21:15 -08001300 }
1301
1302 private:
1303 Barrier* const barrier_;
1304};
1305
Mathieu Chartiera5eae692014-12-17 17:56:03 -08001306void Heap::TrimIndirectReferenceTables(Thread* self) {
1307 ScopedObjectAccess soa(self);
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001308 ScopedTrace trace(__PRETTY_FUNCTION__);
Mathieu Chartiera5eae692014-12-17 17:56:03 -08001309 JavaVMExt* vm = soa.Vm();
1310 // Trim globals indirect reference table.
1311 vm->TrimGlobals();
1312 // Trim locals indirect reference tables.
1313 Barrier barrier(0);
1314 TrimIndirectReferenceTableClosure closure(&barrier);
1315 ScopedThreadStateChange tsc(self, kWaitingForCheckPointsToRun);
1316 size_t barrier_count = Runtime::Current()->GetThreadList()->RunCheckpoint(&closure);
Lei Lidd9943d2015-02-02 14:24:44 +08001317 if (barrier_count != 0) {
1318 barrier.Increment(self, barrier_count);
1319 }
Mathieu Chartiera5eae692014-12-17 17:56:03 -08001320}
Mathieu Chartier91c2f0c2014-11-26 11:21:15 -08001321
Mathieu Chartieraa516822015-10-02 15:53:37 -07001322void Heap::StartGC(Thread* self, GcCause cause, CollectorType collector_type) {
Mathieu Chartierb93d5b12017-05-19 13:05:06 -07001323 // Need to do this before acquiring the locks since we don't want to get suspended while
1324 // holding any locks.
1325 ScopedThreadStateChange tsc(self, kWaitingForGcToComplete);
Mathieu Chartieraa516822015-10-02 15:53:37 -07001326 MutexLock mu(self, *gc_complete_lock_);
1327 // Ensure there is only one GC at a time.
1328 WaitForGcToCompleteLocked(cause, self);
1329 collector_type_running_ = collector_type;
Mathieu Chartier40112dd2017-06-26 17:49:09 -07001330 last_gc_cause_ = cause;
Mathieu Chartier183009a2017-02-16 21:19:28 -08001331 thread_running_gc_ = self;
Mathieu Chartieraa516822015-10-02 15:53:37 -07001332}
1333
Mathieu Chartiera5eae692014-12-17 17:56:03 -08001334void Heap::TrimSpaces(Thread* self) {
Mathieu Chartierb93d5b12017-05-19 13:05:06 -07001335 // Pretend we are doing a GC to prevent background compaction from deleting the space we are
1336 // trimming.
1337 StartGC(self, kGcCauseTrim, kCollectorTypeHeapTrim);
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001338 ScopedTrace trace(__PRETTY_FUNCTION__);
Mathieu Chartiera5eae692014-12-17 17:56:03 -08001339 const uint64_t start_ns = NanoTime();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001340 // Trim the managed spaces.
1341 uint64_t total_alloc_space_allocated = 0;
1342 uint64_t total_alloc_space_size = 0;
1343 uint64_t managed_reclaimed = 0;
Mathieu Chartiera9d82fe2016-01-25 20:06:11 -08001344 {
1345 ScopedObjectAccess soa(self);
1346 for (const auto& space : continuous_spaces_) {
1347 if (space->IsMallocSpace()) {
1348 gc::space::MallocSpace* malloc_space = space->AsMallocSpace();
1349 if (malloc_space->IsRosAllocSpace() || !CareAboutPauseTimes()) {
1350 // Don't trim dlmalloc spaces if we care about pauses since this can hold the space lock
1351 // for a long period of time.
1352 managed_reclaimed += malloc_space->Trim();
1353 }
1354 total_alloc_space_size += malloc_space->Size();
Mathieu Chartiera5b5c552014-06-24 14:48:59 -07001355 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07001356 }
1357 }
Mathieu Chartier2dbe6272014-09-16 10:43:23 -07001358 total_alloc_space_allocated = GetBytesAllocated();
1359 if (large_object_space_ != nullptr) {
1360 total_alloc_space_allocated -= large_object_space_->GetBytesAllocated();
1361 }
Mathieu Chartier31f44142014-04-08 14:40:03 -07001362 if (bump_pointer_space_ != nullptr) {
1363 total_alloc_space_allocated -= bump_pointer_space_->Size();
1364 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001365 if (region_space_ != nullptr) {
1366 total_alloc_space_allocated -= region_space_->GetBytesAllocated();
1367 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07001368 const float managed_utilization = static_cast<float>(total_alloc_space_allocated) /
1369 static_cast<float>(total_alloc_space_size);
1370 uint64_t gc_heap_end_ns = NanoTime();
Mathieu Chartierd5a89ee2014-01-31 09:55:13 -08001371 // We never move things in the native heap, so we can finish the GC at this point.
1372 FinishGC(self, collector::kGcTypeNone);
Ian Rogers872dd822014-10-30 11:19:14 -07001373
Mathieu Chartier590fee92013-09-13 13:46:47 -07001374 VLOG(heap) << "Heap trim of managed (duration=" << PrettyDuration(gc_heap_end_ns - start_ns)
Dimitry Ivanove6465bc2015-12-14 18:55:02 -08001375 << ", advised=" << PrettySize(managed_reclaimed) << ") heap. Managed heap utilization of "
1376 << static_cast<int>(100 * managed_utilization) << "%.";
Mathieu Chartier590fee92013-09-13 13:46:47 -07001377}
1378
Mathieu Chartier9d156d52016-10-06 17:44:26 -07001379bool Heap::IsValidObjectAddress(const void* addr) const {
1380 if (addr == nullptr) {
Elliott Hughes88c5c352012-03-15 18:49:48 -07001381 return true;
1382 }
Mathieu Chartier9d156d52016-10-06 17:44:26 -07001383 return IsAligned<kObjectAlignment>(addr) && FindSpaceFromAddress(addr) != nullptr;
Mathieu Chartier590fee92013-09-13 13:46:47 -07001384}
1385
Mathieu Chartier9d156d52016-10-06 17:44:26 -07001386bool Heap::IsNonDiscontinuousSpaceHeapAddress(const void* addr) const {
1387 return FindContinuousSpaceFromAddress(reinterpret_cast<const mirror::Object*>(addr)) != nullptr;
Mathieu Chartierd68ac702014-02-11 14:50:51 -08001388}
1389
Mathieu Chartier9d156d52016-10-06 17:44:26 -07001390bool Heap::IsLiveObjectLocked(ObjPtr<mirror::Object> obj,
1391 bool search_allocation_stack,
1392 bool search_live_stack,
1393 bool sorted) {
1394 if (UNLIKELY(!IsAligned<kObjectAlignment>(obj.Ptr()))) {
Mathieu Chartier15d34022014-02-26 17:16:38 -08001395 return false;
1396 }
Mathieu Chartier9d156d52016-10-06 17:44:26 -07001397 if (bump_pointer_space_ != nullptr && bump_pointer_space_->HasAddress(obj.Ptr())) {
Mathieu Chartier4e305412014-02-19 10:54:44 -08001398 mirror::Class* klass = obj->GetClass<kVerifyNone>();
Mathieu Chartier938a03b2014-01-16 15:10:31 -08001399 if (obj == klass) {
Mathieu Chartier9be9a7a2014-01-24 14:07:33 -08001400 // This case happens for java.lang.Class.
Mathieu Chartier938a03b2014-01-16 15:10:31 -08001401 return true;
1402 }
1403 return VerifyClassClass(klass) && IsLiveObjectLocked(klass);
Mathieu Chartier9d156d52016-10-06 17:44:26 -07001404 } else if (temp_space_ != nullptr && temp_space_->HasAddress(obj.Ptr())) {
Mathieu Chartier4e305412014-02-19 10:54:44 -08001405 // If we are in the allocated region of the temp space, then we are probably live (e.g. during
1406 // a GC). When a GC isn't running End() - Begin() is 0 which means no objects are contained.
Mathieu Chartier9d156d52016-10-06 17:44:26 -07001407 return temp_space_->Contains(obj.Ptr());
Ian Rogers1d54e732013-05-02 21:10:01 -07001408 }
Mathieu Chartier9d156d52016-10-06 17:44:26 -07001409 if (region_space_ != nullptr && region_space_->HasAddress(obj.Ptr())) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001410 return true;
1411 }
Mathieu Chartierf082d3c2013-07-29 17:04:07 -07001412 space::ContinuousSpace* c_space = FindContinuousSpaceFromObject(obj, true);
Mathieu Chartierbbd695c2014-04-16 09:48:48 -07001413 space::DiscontinuousSpace* d_space = nullptr;
Mathieu Chartier938a03b2014-01-16 15:10:31 -08001414 if (c_space != nullptr) {
Mathieu Chartier9d156d52016-10-06 17:44:26 -07001415 if (c_space->GetLiveBitmap()->Test(obj.Ptr())) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001416 return true;
1417 }
1418 } else {
Mathieu Chartierf082d3c2013-07-29 17:04:07 -07001419 d_space = FindDiscontinuousSpaceFromObject(obj, true);
Mathieu Chartier938a03b2014-01-16 15:10:31 -08001420 if (d_space != nullptr) {
Mathieu Chartier9d156d52016-10-06 17:44:26 -07001421 if (d_space->GetLiveBitmap()->Test(obj.Ptr())) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001422 return true;
1423 }
1424 }
1425 }
Mathieu Chartierf082d3c2013-07-29 17:04:07 -07001426 // This is covering the allocation/live stack swapping that is done without mutators suspended.
Mathieu Chartier0f72e412013-09-06 16:40:01 -07001427 for (size_t i = 0; i < (sorted ? 1 : 5); ++i) {
1428 if (i > 0) {
1429 NanoSleep(MsToNs(10));
Ian Rogers1d54e732013-05-02 21:10:01 -07001430 }
Mathieu Chartier0f72e412013-09-06 16:40:01 -07001431 if (search_allocation_stack) {
1432 if (sorted) {
Mathieu Chartier9d156d52016-10-06 17:44:26 -07001433 if (allocation_stack_->ContainsSorted(obj.Ptr())) {
Mathieu Chartier0f72e412013-09-06 16:40:01 -07001434 return true;
1435 }
Mathieu Chartier9d156d52016-10-06 17:44:26 -07001436 } else if (allocation_stack_->Contains(obj.Ptr())) {
Mathieu Chartier0f72e412013-09-06 16:40:01 -07001437 return true;
1438 }
1439 }
1440
1441 if (search_live_stack) {
1442 if (sorted) {
Mathieu Chartier9d156d52016-10-06 17:44:26 -07001443 if (live_stack_->ContainsSorted(obj.Ptr())) {
Mathieu Chartier0f72e412013-09-06 16:40:01 -07001444 return true;
1445 }
Mathieu Chartier9d156d52016-10-06 17:44:26 -07001446 } else if (live_stack_->Contains(obj.Ptr())) {
Mathieu Chartier0f72e412013-09-06 16:40:01 -07001447 return true;
1448 }
1449 }
Ian Rogers1d54e732013-05-02 21:10:01 -07001450 }
Mathieu Chartierf082d3c2013-07-29 17:04:07 -07001451 // We need to check the bitmaps again since there is a race where we mark something as live and
1452 // then clear the stack containing it.
Mathieu Chartier938a03b2014-01-16 15:10:31 -08001453 if (c_space != nullptr) {
Mathieu Chartier9d156d52016-10-06 17:44:26 -07001454 if (c_space->GetLiveBitmap()->Test(obj.Ptr())) {
Mathieu Chartierf082d3c2013-07-29 17:04:07 -07001455 return true;
1456 }
1457 } else {
1458 d_space = FindDiscontinuousSpaceFromObject(obj, true);
Mathieu Chartier9d156d52016-10-06 17:44:26 -07001459 if (d_space != nullptr && d_space->GetLiveBitmap()->Test(obj.Ptr())) {
Mathieu Chartierf082d3c2013-07-29 17:04:07 -07001460 return true;
1461 }
1462 }
Ian Rogers1d54e732013-05-02 21:10:01 -07001463 return false;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001464}
1465
Mathieu Chartier4c13a3f2014-07-14 14:57:16 -07001466std::string Heap::DumpSpaces() const {
1467 std::ostringstream oss;
1468 DumpSpaces(oss);
1469 return oss.str();
1470}
1471
1472void Heap::DumpSpaces(std::ostream& stream) const {
Mathieu Chartier02e25112013-08-14 16:14:24 -07001473 for (const auto& space : continuous_spaces_) {
Mathieu Chartiera8e8f9c2014-04-09 14:51:05 -07001474 accounting::ContinuousSpaceBitmap* live_bitmap = space->GetLiveBitmap();
1475 accounting::ContinuousSpaceBitmap* mark_bitmap = space->GetMarkBitmap();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001476 stream << space << " " << *space << "\n";
1477 if (live_bitmap != nullptr) {
1478 stream << live_bitmap << " " << *live_bitmap << "\n";
1479 }
1480 if (mark_bitmap != nullptr) {
1481 stream << mark_bitmap << " " << *mark_bitmap << "\n";
1482 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001483 }
Mathieu Chartier02e25112013-08-14 16:14:24 -07001484 for (const auto& space : discontinuous_spaces_) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001485 stream << space << " " << *space << "\n";
Mathieu Chartier128c52c2012-10-16 14:12:41 -07001486 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001487}
1488
Mathieu Chartier9d156d52016-10-06 17:44:26 -07001489void Heap::VerifyObjectBody(ObjPtr<mirror::Object> obj) {
Stephen Hines22c6a812014-07-16 11:03:43 -07001490 if (verify_object_mode_ == kVerifyObjectModeDisabled) {
1491 return;
1492 }
1493
Mathieu Chartier0f72e412013-09-06 16:40:01 -07001494 // Ignore early dawn of the universe verifications.
Ian Rogers3e5cf302014-05-20 16:40:37 -07001495 if (UNLIKELY(static_cast<size_t>(num_bytes_allocated_.LoadRelaxed()) < 10 * KB)) {
Ian Rogers62d6c772013-02-27 08:32:07 -08001496 return;
1497 }
Mathieu Chartier9d156d52016-10-06 17:44:26 -07001498 CHECK_ALIGNED(obj.Ptr(), kObjectAlignment) << "Object isn't aligned";
Ian Rogersb0fa5dc2014-04-28 16:47:08 -07001499 mirror::Class* c = obj->GetFieldObject<mirror::Class, kVerifyNone>(mirror::Object::ClassOffset());
Mathieu Chartier4e305412014-02-19 10:54:44 -08001500 CHECK(c != nullptr) << "Null class in object " << obj;
Roland Levillain14d90572015-07-16 10:52:26 +01001501 CHECK_ALIGNED(c, kObjectAlignment) << "Class " << c << " not aligned in object " << obj;
Mathieu Chartier938a03b2014-01-16 15:10:31 -08001502 CHECK(VerifyClassClass(c));
Mathieu Chartier0325e622012-09-05 14:22:51 -07001503
Mathieu Chartier4e305412014-02-19 10:54:44 -08001504 if (verify_object_mode_ > kVerifyObjectModeFast) {
1505 // Note: the bitmap tests below are racy since we don't hold the heap bitmap lock.
Mathieu Chartier4c13a3f2014-07-14 14:57:16 -07001506 CHECK(IsLiveObjectLocked(obj)) << "Object is dead " << obj << "\n" << DumpSpaces();
Mathieu Chartierdcf8d722012-08-02 14:55:54 -07001507 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001508}
1509
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001510void Heap::VerifyHeap() {
Ian Rogers50b35e22012-10-04 10:09:15 -07001511 ReaderMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
Andreas Gampe0c183382017-07-13 22:26:24 -07001512 auto visitor = [&](mirror::Object* obj) {
1513 VerifyObjectBody(obj);
1514 };
1515 // Technically we need the mutator lock here to call Visit. However, VerifyObjectBody is already
1516 // NO_THREAD_SAFETY_ANALYSIS.
1517 auto no_thread_safety_analysis = [&]() NO_THREAD_SAFETY_ANALYSIS {
1518 GetLiveBitmap()->Visit(visitor);
1519 };
1520 no_thread_safety_analysis();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001521}
1522
Mathieu Chartiere76e70f2014-05-02 16:35:37 -07001523void Heap::RecordFree(uint64_t freed_objects, int64_t freed_bytes) {
Mathieu Chartier601276a2014-03-20 15:12:30 -07001524 // Use signed comparison since freed bytes can be negative when background compaction foreground
1525 // transitions occurs. This is caused by the moving objects from a bump pointer space to a
1526 // free list backed space typically increasing memory footprint due to padding and binning.
Ian Rogers3e5cf302014-05-20 16:40:37 -07001527 DCHECK_LE(freed_bytes, static_cast<int64_t>(num_bytes_allocated_.LoadRelaxed()));
Mathieu Chartiere76e70f2014-05-02 16:35:37 -07001528 // Note: This relies on 2s complement for handling negative freed_bytes.
Ian Rogers3e5cf302014-05-20 16:40:37 -07001529 num_bytes_allocated_.FetchAndSubSequentiallyConsistent(static_cast<ssize_t>(freed_bytes));
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07001530 if (Runtime::Current()->HasStatsEnabled()) {
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07001531 RuntimeStats* thread_stats = Thread::Current()->GetStats();
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001532 thread_stats->freed_objects += freed_objects;
Elliott Hughes307f75d2011-10-12 18:04:40 -07001533 thread_stats->freed_bytes += freed_bytes;
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001534 // TODO: Do this concurrently.
1535 RuntimeStats* global_stats = Runtime::Current()->GetStats();
1536 global_stats->freed_objects += freed_objects;
1537 global_stats->freed_bytes += freed_bytes;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07001538 }
Carl Shapiro58551df2011-07-24 03:09:51 -07001539}
1540
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07001541void Heap::RecordFreeRevoke() {
1542 // Subtract num_bytes_freed_revoke_ from num_bytes_allocated_ to cancel out the
1543 // the ahead-of-time, bulk counting of bytes allocated in rosalloc thread-local buffers.
1544 // If there's a concurrent revoke, ok to not necessarily reset num_bytes_freed_revoke_
1545 // all the way to zero exactly as the remainder will be subtracted at the next GC.
1546 size_t bytes_freed = num_bytes_freed_revoke_.LoadSequentiallyConsistent();
1547 CHECK_GE(num_bytes_freed_revoke_.FetchAndSubSequentiallyConsistent(bytes_freed),
1548 bytes_freed) << "num_bytes_freed_revoke_ underflow";
1549 CHECK_GE(num_bytes_allocated_.FetchAndSubSequentiallyConsistent(bytes_freed),
1550 bytes_freed) << "num_bytes_allocated_ underflow";
1551 GetCurrentGcIteration()->SetFreedRevoke(bytes_freed);
1552}
1553
Zuo Wangf37a88b2014-07-10 04:26:41 -07001554space::RosAllocSpace* Heap::GetRosAllocSpace(gc::allocator::RosAlloc* rosalloc) const {
Mathieu Chartiera9d82fe2016-01-25 20:06:11 -08001555 if (rosalloc_space_ != nullptr && rosalloc_space_->GetRosAlloc() == rosalloc) {
1556 return rosalloc_space_;
1557 }
Zuo Wangf37a88b2014-07-10 04:26:41 -07001558 for (const auto& space : continuous_spaces_) {
1559 if (space->AsContinuousSpace()->IsRosAllocSpace()) {
1560 if (space->AsContinuousSpace()->AsRosAllocSpace()->GetRosAlloc() == rosalloc) {
1561 return space->AsContinuousSpace()->AsRosAllocSpace();
1562 }
1563 }
1564 }
1565 return nullptr;
1566}
1567
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001568static inline bool EntrypointsInstrumented() REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiereebc3af2016-02-29 18:13:38 -08001569 instrumentation::Instrumentation* const instrumentation =
1570 Runtime::Current()->GetInstrumentation();
1571 return instrumentation != nullptr && instrumentation->AllocEntrypointsInstrumented();
1572}
1573
Mathieu Chartiera4f6af92015-08-11 17:35:25 -07001574mirror::Object* Heap::AllocateInternalWithGc(Thread* self,
1575 AllocatorType allocator,
Mathieu Chartiereebc3af2016-02-29 18:13:38 -08001576 bool instrumented,
Mathieu Chartiera4f6af92015-08-11 17:35:25 -07001577 size_t alloc_size,
1578 size_t* bytes_allocated,
Ian Rogers6fac4472014-02-25 17:01:10 -08001579 size_t* usable_size,
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07001580 size_t* bytes_tl_bulk_allocated,
Mathieu Chartier9d156d52016-10-06 17:44:26 -07001581 ObjPtr<mirror::Class>* klass) {
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001582 bool was_default_allocator = allocator == GetCurrentAllocator();
Mathieu Chartierf4f38432014-09-03 11:21:08 -07001583 // Make sure there is no pending exception since we may need to throw an OOME.
1584 self->AssertNoPendingException();
Mathieu Chartierc528dba2013-11-26 12:00:11 -08001585 DCHECK(klass != nullptr);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001586 StackHandleScope<1> hs(self);
Mathieu Chartier9d156d52016-10-06 17:44:26 -07001587 HandleWrapperObjPtr<mirror::Class> h(hs.NewHandleWrapper(klass));
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001588 // The allocation failed. If the GC is running, block until it completes, and then retry the
1589 // allocation.
Mathieu Chartier89a201e2014-05-02 10:27:26 -07001590 collector::GcType last_gc = WaitForGcToComplete(kGcCauseForAlloc, self);
Mathieu Chartiereebc3af2016-02-29 18:13:38 -08001591 // If we were the default allocator but the allocator changed while we were suspended,
1592 // abort the allocation.
1593 if ((was_default_allocator && allocator != GetCurrentAllocator()) ||
1594 (!instrumented && EntrypointsInstrumented())) {
1595 return nullptr;
1596 }
Ian Rogers1d54e732013-05-02 21:10:01 -07001597 if (last_gc != collector::kGcTypeNone) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001598 // A GC was in progress and we blocked, retry allocation now that memory has been freed.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001599 mirror::Object* ptr = TryToAllocate<true, false>(self, allocator, alloc_size, bytes_allocated,
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07001600 usable_size, bytes_tl_bulk_allocated);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001601 if (ptr != nullptr) {
1602 return ptr;
1603 }
Carl Shapiro69759ea2011-07-21 18:13:35 -07001604 }
1605
Mathieu Chartier5ae2c932014-03-28 16:22:20 -07001606 collector::GcType tried_type = next_gc_type_;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001607 const bool gc_ran =
1608 CollectGarbageInternal(tried_type, kGcCauseForAlloc, false) != collector::kGcTypeNone;
Mathieu Chartiereebc3af2016-02-29 18:13:38 -08001609 if ((was_default_allocator && allocator != GetCurrentAllocator()) ||
1610 (!instrumented && EntrypointsInstrumented())) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001611 return nullptr;
1612 }
1613 if (gc_ran) {
1614 mirror::Object* ptr = TryToAllocate<true, false>(self, allocator, alloc_size, bytes_allocated,
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07001615 usable_size, bytes_tl_bulk_allocated);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001616 if (ptr != nullptr) {
1617 return ptr;
Mathieu Chartier5ae2c932014-03-28 16:22:20 -07001618 }
1619 }
1620
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001621 // Loop through our different Gc types and try to Gc until we get enough free memory.
Mathieu Chartiercbb2d202013-11-14 17:45:16 -08001622 for (collector::GcType gc_type : gc_plan_) {
Mathieu Chartier5ae2c932014-03-28 16:22:20 -07001623 if (gc_type == tried_type) {
1624 continue;
1625 }
Mathieu Chartiercbb2d202013-11-14 17:45:16 -08001626 // Attempt to run the collector, if we succeed, re-try the allocation.
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001627 const bool plan_gc_ran =
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001628 CollectGarbageInternal(gc_type, kGcCauseForAlloc, false) != collector::kGcTypeNone;
Mathieu Chartiereebc3af2016-02-29 18:13:38 -08001629 if ((was_default_allocator && allocator != GetCurrentAllocator()) ||
1630 (!instrumented && EntrypointsInstrumented())) {
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001631 return nullptr;
1632 }
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001633 if (plan_gc_ran) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001634 // Did we free sufficient memory for the allocation to succeed?
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 }
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001640 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001641 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001642 // Allocations have failed after GCs; this is an exceptional state.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001643 // Try harder, growing the heap if necessary.
1644 mirror::Object* ptr = TryToAllocate<true, true>(self, allocator, alloc_size, bytes_allocated,
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07001645 usable_size, bytes_tl_bulk_allocated);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001646 if (ptr != nullptr) {
1647 return ptr;
Carl Shapiro69759ea2011-07-21 18:13:35 -07001648 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001649 // Most allocations should have succeeded by now, so the heap is really full, really fragmented,
1650 // or the requested size is really big. Do another GC, collecting SoftReferences this time. The
1651 // VM spec requires that all SoftReferences have been collected and cleared before throwing
1652 // OOME.
1653 VLOG(gc) << "Forcing collection of SoftReferences for " << PrettySize(alloc_size)
1654 << " allocation";
1655 // TODO: Run finalization, but this may cause more allocations to occur.
1656 // We don't need a WaitForGcToComplete here either.
1657 DCHECK(!gc_plan_.empty());
1658 CollectGarbageInternal(gc_plan_.back(), kGcCauseForAlloc, true);
Mathieu Chartiereebc3af2016-02-29 18:13:38 -08001659 if ((was_default_allocator && allocator != GetCurrentAllocator()) ||
1660 (!instrumented && EntrypointsInstrumented())) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001661 return nullptr;
Mathieu Chartiercbb2d202013-11-14 17:45:16 -08001662 }
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07001663 ptr = TryToAllocate<true, true>(self, allocator, alloc_size, bytes_allocated, usable_size,
1664 bytes_tl_bulk_allocated);
Mathieu Chartier6a7824d2014-08-22 14:53:04 -07001665 if (ptr == nullptr) {
Zuo Wangf37a88b2014-07-10 04:26:41 -07001666 const uint64_t current_time = NanoTime();
Mathieu Chartier6a7824d2014-08-22 14:53:04 -07001667 switch (allocator) {
1668 case kAllocatorTypeRosAlloc:
1669 // Fall-through.
1670 case kAllocatorTypeDlMalloc: {
1671 if (use_homogeneous_space_compaction_for_oom_ &&
1672 current_time - last_time_homogeneous_space_compaction_by_oom_ >
1673 min_interval_homogeneous_space_compaction_by_oom_) {
1674 last_time_homogeneous_space_compaction_by_oom_ = current_time;
1675 HomogeneousSpaceCompactResult result = PerformHomogeneousSpaceCompact();
Mathieu Chartiereebc3af2016-02-29 18:13:38 -08001676 // Thread suspension could have occurred.
1677 if ((was_default_allocator && allocator != GetCurrentAllocator()) ||
1678 (!instrumented && EntrypointsInstrumented())) {
1679 return nullptr;
1680 }
Mathieu Chartier6a7824d2014-08-22 14:53:04 -07001681 switch (result) {
1682 case HomogeneousSpaceCompactResult::kSuccess:
1683 // If the allocation succeeded, we delayed an oom.
1684 ptr = TryToAllocate<true, true>(self, allocator, alloc_size, bytes_allocated,
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07001685 usable_size, bytes_tl_bulk_allocated);
Mathieu Chartier6a7824d2014-08-22 14:53:04 -07001686 if (ptr != nullptr) {
1687 count_delayed_oom_++;
1688 }
1689 break;
1690 case HomogeneousSpaceCompactResult::kErrorReject:
1691 // Reject due to disabled moving GC.
1692 break;
1693 case HomogeneousSpaceCompactResult::kErrorVMShuttingDown:
1694 // Throw OOM by default.
1695 break;
1696 default: {
Ian Rogers2c4257b2014-10-24 14:20:06 -07001697 UNIMPLEMENTED(FATAL) << "homogeneous space compaction result: "
1698 << static_cast<size_t>(result);
1699 UNREACHABLE();
Mathieu Chartier6a7824d2014-08-22 14:53:04 -07001700 }
Zuo Wangf37a88b2014-07-10 04:26:41 -07001701 }
Mathieu Chartier6a7824d2014-08-22 14:53:04 -07001702 // Always print that we ran homogeneous space compation since this can cause jank.
1703 VLOG(heap) << "Ran heap homogeneous space compaction, "
1704 << " requested defragmentation "
1705 << count_requested_homogeneous_space_compaction_.LoadSequentiallyConsistent()
1706 << " performed defragmentation "
1707 << count_performed_homogeneous_space_compaction_.LoadSequentiallyConsistent()
1708 << " ignored homogeneous space compaction "
1709 << count_ignored_homogeneous_space_compaction_.LoadSequentiallyConsistent()
1710 << " delayed count = "
1711 << count_delayed_oom_.LoadSequentiallyConsistent();
Zuo Wangf37a88b2014-07-10 04:26:41 -07001712 }
Mathieu Chartier6a7824d2014-08-22 14:53:04 -07001713 break;
Zuo Wangf37a88b2014-07-10 04:26:41 -07001714 }
Mathieu Chartier6a7824d2014-08-22 14:53:04 -07001715 case kAllocatorTypeNonMoving: {
Hiroshi Yamauchi60985b72016-08-24 13:53:12 -07001716 if (kUseReadBarrier) {
1717 // DisableMovingGc() isn't compatible with CC.
1718 break;
1719 }
Mathieu Chartier6a7824d2014-08-22 14:53:04 -07001720 // Try to transition the heap if the allocation failure was due to the space being full.
Mathieu Chartier5ace2012016-11-30 10:15:41 -08001721 if (!IsOutOfMemoryOnAllocation(allocator, alloc_size, /*grow*/ false)) {
Mathieu Chartier6a7824d2014-08-22 14:53:04 -07001722 // If we aren't out of memory then the OOM was probably from the non moving space being
1723 // full. Attempt to disable compaction and turn the main space into a non moving space.
1724 DisableMovingGc();
Mathieu Chartiereebc3af2016-02-29 18:13:38 -08001725 // Thread suspension could have occurred.
1726 if ((was_default_allocator && allocator != GetCurrentAllocator()) ||
1727 (!instrumented && EntrypointsInstrumented())) {
1728 return nullptr;
1729 }
Mathieu Chartier6a7824d2014-08-22 14:53:04 -07001730 // If we are still a moving GC then something must have caused the transition to fail.
1731 if (IsMovingGc(collector_type_)) {
1732 MutexLock mu(self, *gc_complete_lock_);
1733 // If we couldn't disable moving GC, just throw OOME and return null.
1734 LOG(WARNING) << "Couldn't disable moving GC with disable GC count "
1735 << disable_moving_gc_count_;
1736 } else {
1737 LOG(WARNING) << "Disabled moving GC due to the non moving space being full";
1738 ptr = TryToAllocate<true, true>(self, allocator, alloc_size, bytes_allocated,
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07001739 usable_size, bytes_tl_bulk_allocated);
Mathieu Chartier6a7824d2014-08-22 14:53:04 -07001740 }
1741 }
1742 break;
1743 }
1744 default: {
1745 // Do nothing for others allocators.
1746 }
Zuo Wangf37a88b2014-07-10 04:26:41 -07001747 }
1748 }
1749 // If the allocation hasn't succeeded by this point, throw an OOM error.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001750 if (ptr == nullptr) {
Hiroshi Yamauchi654dd482014-07-09 12:54:32 -07001751 ThrowOutOfMemoryError(self, alloc_size, allocator);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001752 }
Mathieu Chartiercbb2d202013-11-14 17:45:16 -08001753 return ptr;
Carl Shapiro69759ea2011-07-21 18:13:35 -07001754}
1755
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001756void Heap::SetTargetHeapUtilization(float target) {
1757 DCHECK_GT(target, 0.0f); // asserted in Java code
1758 DCHECK_LT(target, 1.0f);
1759 target_utilization_ = target;
1760}
1761
Ian Rogers1d54e732013-05-02 21:10:01 -07001762size_t Heap::GetObjectsAllocated() const {
Mathieu Chartier4f55e222015-09-04 13:26:21 -07001763 Thread* const self = Thread::Current();
Mathieu Chartierb43390c2015-05-12 10:47:11 -07001764 ScopedThreadStateChange tsc(self, kWaitingForGetObjectsAllocated);
Mathieu Chartiere8649c72017-03-03 18:02:18 -08001765 // Prevent GC running during GetObjectsALlocated since we may get a checkpoint request that tells
1766 // us to suspend while we are doing SuspendAll. b/35232978
1767 gc::ScopedGCCriticalSection gcs(Thread::Current(),
1768 gc::kGcCauseGetObjectsAllocated,
1769 gc::kCollectorTypeGetObjectsAllocated);
Mathieu Chartierb43390c2015-05-12 10:47:11 -07001770 // Need SuspendAll here to prevent lock violation if RosAlloc does it during InspectAll.
Mathieu Chartier4f55e222015-09-04 13:26:21 -07001771 ScopedSuspendAll ssa(__FUNCTION__);
1772 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Ian Rogers1d54e732013-05-02 21:10:01 -07001773 size_t total = 0;
Mathieu Chartier4f55e222015-09-04 13:26:21 -07001774 for (space::AllocSpace* space : alloc_spaces_) {
1775 total += space->GetObjectsAllocated();
Ian Rogers1d54e732013-05-02 21:10:01 -07001776 }
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001777 return total;
1778}
1779
Mathieu Chartierdd162fb2014-08-06 17:06:33 -07001780uint64_t Heap::GetObjectsAllocatedEver() const {
Mathieu Chartier4edd8472015-06-01 10:47:36 -07001781 uint64_t total = GetObjectsFreedEver();
1782 // If we are detached, we can't use GetObjectsAllocated since we can't change thread states.
1783 if (Thread::Current() != nullptr) {
1784 total += GetObjectsAllocated();
1785 }
1786 return total;
Ian Rogers1d54e732013-05-02 21:10:01 -07001787}
1788
Mathieu Chartierdd162fb2014-08-06 17:06:33 -07001789uint64_t Heap::GetBytesAllocatedEver() const {
Mathieu Chartier692fafd2013-11-29 17:24:40 -08001790 return GetBytesFreedEver() + GetBytesAllocated();
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001791}
1792
Mathieu Chartier9d156d52016-10-06 17:44:26 -07001793void Heap::CountInstances(const std::vector<Handle<mirror::Class>>& classes,
1794 bool use_is_assignable_from,
Elliott Hughesec0f83d2013-01-15 16:54:08 -08001795 uint64_t* counts) {
Andreas Gampe1c158a02017-07-13 17:26:19 -07001796 auto instance_counter = [&](mirror::Object* obj) REQUIRES_SHARED(Locks::mutator_lock_) {
1797 mirror::Class* instance_class = obj->GetClass();
1798 CHECK(instance_class != nullptr);
1799 for (size_t i = 0; i < classes.size(); ++i) {
1800 ObjPtr<mirror::Class> klass = classes[i].Get();
1801 if (use_is_assignable_from) {
1802 if (klass != nullptr && klass->IsAssignableFrom(instance_class)) {
1803 ++counts[i];
1804 }
1805 } else if (instance_class == klass) {
1806 ++counts[i];
Elliott Hughes3b78c942013-01-15 17:35:41 -08001807 }
1808 }
Andreas Gampe1c158a02017-07-13 17:26:19 -07001809 };
1810 VisitObjects(instance_counter);
Elliott Hughes3b78c942013-01-15 17:35:41 -08001811}
1812
Andreas Gampe1c158a02017-07-13 17:26:19 -07001813void Heap::GetInstances(VariableSizedHandleScope& scope,
1814 Handle<mirror::Class> h_class,
1815 int32_t max_count,
1816 std::vector<Handle<mirror::Object>>& instances) {
1817 DCHECK_GE(max_count, 0);
1818 auto instance_collector = [&](mirror::Object* obj) REQUIRES_SHARED(Locks::mutator_lock_) {
1819 if (obj->GetClass() == h_class.Get()) {
1820 if (max_count == 0 || instances.size() < static_cast<size_t>(max_count)) {
1821 instances.push_back(scope.NewHandle(obj));
1822 }
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001823 }
Andreas Gampe1c158a02017-07-13 17:26:19 -07001824 };
1825 VisitObjects(instance_collector);
1826}
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001827
Mathieu Chartieraea9bfb2016-10-12 19:19:56 -07001828void Heap::GetReferringObjects(VariableSizedHandleScope& scope,
1829 Handle<mirror::Object> o,
Mathieu Chartier9d156d52016-10-06 17:44:26 -07001830 int32_t max_count,
Mathieu Chartieraea9bfb2016-10-12 19:19:56 -07001831 std::vector<Handle<mirror::Object>>& referring_objects) {
Andreas Gampe1c158a02017-07-13 17:26:19 -07001832 class ReferringObjectsFinder {
1833 public:
1834 ReferringObjectsFinder(VariableSizedHandleScope& scope_in,
1835 Handle<mirror::Object> object_in,
1836 int32_t max_count_in,
1837 std::vector<Handle<mirror::Object>>& referring_objects_in)
1838 REQUIRES_SHARED(Locks::mutator_lock_)
1839 : scope_(scope_in),
1840 object_(object_in),
1841 max_count_(max_count_in),
1842 referring_objects_(referring_objects_in) {}
1843
1844 // For Object::VisitReferences.
1845 void operator()(ObjPtr<mirror::Object> obj,
1846 MemberOffset offset,
1847 bool is_static ATTRIBUTE_UNUSED) const
1848 REQUIRES_SHARED(Locks::mutator_lock_) {
1849 mirror::Object* ref = obj->GetFieldObject<mirror::Object>(offset);
1850 if (ref == object_.Get() && (max_count_ == 0 || referring_objects_.size() < max_count_)) {
1851 referring_objects_.push_back(scope_.NewHandle(obj));
1852 }
1853 }
1854
1855 void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root ATTRIBUTE_UNUSED)
1856 const {}
1857 void VisitRoot(mirror::CompressedReference<mirror::Object>* root ATTRIBUTE_UNUSED) const {}
1858
1859 private:
1860 VariableSizedHandleScope& scope_;
1861 Handle<mirror::Object> const object_;
1862 const uint32_t max_count_;
1863 std::vector<Handle<mirror::Object>>& referring_objects_;
1864 DISALLOW_COPY_AND_ASSIGN(ReferringObjectsFinder);
1865 };
Mathieu Chartieraea9bfb2016-10-12 19:19:56 -07001866 ReferringObjectsFinder finder(scope, o, max_count, referring_objects);
Andreas Gampe1c158a02017-07-13 17:26:19 -07001867 auto referring_objects_finder = [&](mirror::Object* obj) REQUIRES_SHARED(Locks::mutator_lock_) {
1868 obj->VisitReferences(finder, VoidFunctor());
1869 };
1870 VisitObjects(referring_objects_finder);
Elliott Hughes0cbaff52013-01-16 15:28:01 -08001871}
1872
Ian Rogers30fab402012-01-23 15:43:46 -08001873void Heap::CollectGarbage(bool clear_soft_references) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001874 // Even if we waited for a GC we still need to do another GC since weaks allocated during the
1875 // last GC will not have necessarily been cleared.
Mathieu Chartier7bf82af2013-12-06 16:51:45 -08001876 CollectGarbageInternal(gc_plan_.back(), kGcCauseExplicit, clear_soft_references);
Carl Shapiro69759ea2011-07-21 18:13:35 -07001877}
1878
Mathieu Chartierdb00eaf2015-08-31 17:10:05 -07001879bool Heap::SupportHomogeneousSpaceCompactAndCollectorTransitions() const {
1880 return main_space_backup_.get() != nullptr && main_space_ != nullptr &&
1881 foreground_collector_type_ == kCollectorTypeCMS;
1882}
1883
Zuo Wangf37a88b2014-07-10 04:26:41 -07001884HomogeneousSpaceCompactResult Heap::PerformHomogeneousSpaceCompact() {
1885 Thread* self = Thread::Current();
1886 // Inc requested homogeneous space compaction.
1887 count_requested_homogeneous_space_compaction_++;
1888 // Store performed homogeneous space compaction at a new request arrival.
Zuo Wangf37a88b2014-07-10 04:26:41 -07001889 ScopedThreadStateChange tsc(self, kWaitingPerformingGc);
1890 Locks::mutator_lock_->AssertNotHeld(self);
1891 {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001892 ScopedThreadStateChange tsc2(self, kWaitingForGcToComplete);
Zuo Wangf37a88b2014-07-10 04:26:41 -07001893 MutexLock mu(self, *gc_complete_lock_);
1894 // Ensure there is only one GC at a time.
1895 WaitForGcToCompleteLocked(kGcCauseHomogeneousSpaceCompact, self);
1896 // Homogeneous space compaction is a copying transition, can't run it if the moving GC disable count
1897 // is non zero.
Mathieu Chartier6a7824d2014-08-22 14:53:04 -07001898 // If the collector type changed to something which doesn't benefit from homogeneous space compaction,
Zuo Wangf37a88b2014-07-10 04:26:41 -07001899 // exit.
Mathieu Chartier6a7824d2014-08-22 14:53:04 -07001900 if (disable_moving_gc_count_ != 0 || IsMovingGc(collector_type_) ||
1901 !main_space_->CanMoveObjects()) {
Mathieu Chartierdb00eaf2015-08-31 17:10:05 -07001902 return kErrorReject;
1903 }
1904 if (!SupportHomogeneousSpaceCompactAndCollectorTransitions()) {
1905 return kErrorUnsupported;
Zuo Wangf37a88b2014-07-10 04:26:41 -07001906 }
1907 collector_type_running_ = kCollectorTypeHomogeneousSpaceCompact;
1908 }
1909 if (Runtime::Current()->IsShuttingDown(self)) {
1910 // Don't allow heap transitions to happen if the runtime is shutting down since these can
1911 // cause objects to get finalized.
1912 FinishGC(self, collector::kGcTypeNone);
1913 return HomogeneousSpaceCompactResult::kErrorVMShuttingDown;
1914 }
Mathieu Chartier4f55e222015-09-04 13:26:21 -07001915 collector::GarbageCollector* collector;
1916 {
1917 ScopedSuspendAll ssa(__FUNCTION__);
1918 uint64_t start_time = NanoTime();
1919 // Launch compaction.
1920 space::MallocSpace* to_space = main_space_backup_.release();
1921 space::MallocSpace* from_space = main_space_;
1922 to_space->GetMemMap()->Protect(PROT_READ | PROT_WRITE);
1923 const uint64_t space_size_before_compaction = from_space->Size();
1924 AddSpace(to_space);
1925 // Make sure that we will have enough room to copy.
1926 CHECK_GE(to_space->GetFootprintLimit(), from_space->GetFootprintLimit());
1927 collector = Compact(to_space, from_space, kGcCauseHomogeneousSpaceCompact);
1928 const uint64_t space_size_after_compaction = to_space->Size();
1929 main_space_ = to_space;
1930 main_space_backup_.reset(from_space);
1931 RemoveSpace(from_space);
1932 SetSpaceAsDefault(main_space_); // Set as default to reset the proper dlmalloc space.
1933 // Update performed homogeneous space compaction count.
1934 count_performed_homogeneous_space_compaction_++;
1935 // Print statics log and resume all threads.
1936 uint64_t duration = NanoTime() - start_time;
1937 VLOG(heap) << "Heap homogeneous space compaction took " << PrettyDuration(duration) << " size: "
1938 << PrettySize(space_size_before_compaction) << " -> "
1939 << PrettySize(space_size_after_compaction) << " compact-ratio: "
1940 << std::fixed << static_cast<double>(space_size_after_compaction) /
1941 static_cast<double>(space_size_before_compaction);
1942 }
Zuo Wangf37a88b2014-07-10 04:26:41 -07001943 // Finish GC.
Mathieu Chartier3cf22532015-07-09 15:15:09 -07001944 reference_processor_->EnqueueClearedReferences(self);
Zuo Wangf37a88b2014-07-10 04:26:41 -07001945 GrowForUtilization(semi_space_collector_);
Hiroshi Yamauchie4d99872015-02-26 12:53:45 -08001946 LogGC(kGcCauseHomogeneousSpaceCompact, collector);
Zuo Wangf37a88b2014-07-10 04:26:41 -07001947 FinishGC(self, collector::kGcTypeFull);
Mathieu Chartier598302a2015-09-23 14:52:39 -07001948 {
1949 ScopedObjectAccess soa(self);
1950 soa.Vm()->UnloadNativeLibraries();
1951 }
Zuo Wangf37a88b2014-07-10 04:26:41 -07001952 return HomogeneousSpaceCompactResult::kSuccess;
1953}
1954
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001955void Heap::TransitionCollector(CollectorType collector_type) {
1956 if (collector_type == collector_type_) {
1957 return;
1958 }
Hiroshi Yamauchia01d0662016-08-30 17:44:41 -07001959 // Collector transition must not happen with CC
1960 CHECK(!kUseReadBarrier);
Hiroshi Yamauchia4adbfd2014-02-04 18:12:17 -08001961 VLOG(heap) << "TransitionCollector: " << static_cast<int>(collector_type_)
1962 << " -> " << static_cast<int>(collector_type);
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001963 uint64_t start_time = NanoTime();
Ian Rogers3e5cf302014-05-20 16:40:37 -07001964 uint32_t before_allocated = num_bytes_allocated_.LoadSequentiallyConsistent();
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001965 Runtime* const runtime = Runtime::Current();
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001966 Thread* const self = Thread::Current();
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001967 ScopedThreadStateChange tsc(self, kWaitingPerformingGc);
1968 Locks::mutator_lock_->AssertNotHeld(self);
Mathieu Chartier1d27b342014-01-28 12:51:09 -08001969 // Busy wait until we can GC (StartGC can fail if we have a non-zero
1970 // compacting_gc_disable_count_, this should rarely occurs).
Mathieu Chartierd5a89ee2014-01-31 09:55:13 -08001971 for (;;) {
Mathieu Chartiercaa82d62014-02-02 16:51:17 -08001972 {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001973 ScopedThreadStateChange tsc2(self, kWaitingForGcToComplete);
Mathieu Chartiercaa82d62014-02-02 16:51:17 -08001974 MutexLock mu(self, *gc_complete_lock_);
1975 // Ensure there is only one GC at a time.
Mathieu Chartier89a201e2014-05-02 10:27:26 -07001976 WaitForGcToCompleteLocked(kGcCauseCollectorTransition, self);
Mathieu Chartiere4927f62014-08-23 13:56:03 -07001977 // Currently we only need a heap transition if we switch from a moving collector to a
1978 // non-moving one, or visa versa.
1979 const bool copying_transition = IsMovingGc(collector_type_) != IsMovingGc(collector_type);
Mathieu Chartierb38d4832014-04-10 10:56:55 -07001980 // If someone else beat us to it and changed the collector before we could, exit.
1981 // This is safe to do before the suspend all since we set the collector_type_running_ before
1982 // we exit the loop. If another thread attempts to do the heap transition before we exit,
1983 // then it would get blocked on WaitForGcToCompleteLocked.
1984 if (collector_type == collector_type_) {
1985 return;
1986 }
Mathieu Chartiercaa82d62014-02-02 16:51:17 -08001987 // GC can be disabled if someone has a used GetPrimitiveArrayCritical but not yet released.
1988 if (!copying_transition || disable_moving_gc_count_ == 0) {
1989 // TODO: Not hard code in semi-space collector?
1990 collector_type_running_ = copying_transition ? kCollectorTypeSS : collector_type;
1991 break;
1992 }
Mathieu Chartierd5a89ee2014-01-31 09:55:13 -08001993 }
Mathieu Chartiercaa82d62014-02-02 16:51:17 -08001994 usleep(1000);
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001995 }
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001996 if (runtime->IsShuttingDown(self)) {
Hiroshi Yamauchia6a8d142014-05-12 16:57:33 -07001997 // Don't allow heap transitions to happen if the runtime is shutting down since these can
1998 // cause objects to get finalized.
1999 FinishGC(self, collector::kGcTypeNone);
2000 return;
2001 }
Hiroshi Yamauchie4d99872015-02-26 12:53:45 -08002002 collector::GarbageCollector* collector = nullptr;
Mathieu Chartier4f55e222015-09-04 13:26:21 -07002003 {
2004 ScopedSuspendAll ssa(__FUNCTION__);
2005 switch (collector_type) {
2006 case kCollectorTypeSS: {
2007 if (!IsMovingGc(collector_type_)) {
2008 // Create the bump pointer space from the backup space.
2009 CHECK(main_space_backup_ != nullptr);
2010 std::unique_ptr<MemMap> mem_map(main_space_backup_->ReleaseMemMap());
2011 // We are transitioning from non moving GC -> moving GC, since we copied from the bump
2012 // pointer space last transition it will be protected.
2013 CHECK(mem_map != nullptr);
Hiroshi Yamauchic1276c82014-08-07 10:27:17 -07002014 mem_map->Protect(PROT_READ | PROT_WRITE);
Mathieu Chartier4f55e222015-09-04 13:26:21 -07002015 bump_pointer_space_ = space::BumpPointerSpace::CreateFromMemMap("Bump pointer space",
2016 mem_map.release());
2017 AddSpace(bump_pointer_space_);
2018 collector = Compact(bump_pointer_space_, main_space_, kGcCauseCollectorTransition);
2019 // Use the now empty main space mem map for the bump pointer temp space.
2020 mem_map.reset(main_space_->ReleaseMemMap());
2021 // Unset the pointers just in case.
2022 if (dlmalloc_space_ == main_space_) {
2023 dlmalloc_space_ = nullptr;
2024 } else if (rosalloc_space_ == main_space_) {
2025 rosalloc_space_ = nullptr;
2026 }
2027 // Remove the main space so that we don't try to trim it, this doens't work for debug
2028 // builds since RosAlloc attempts to read the magic number from a protected page.
2029 RemoveSpace(main_space_);
2030 RemoveRememberedSet(main_space_);
2031 delete main_space_; // Delete the space since it has been removed.
2032 main_space_ = nullptr;
2033 RemoveRememberedSet(main_space_backup_.get());
2034 main_space_backup_.reset(nullptr); // Deletes the space.
2035 temp_space_ = space::BumpPointerSpace::CreateFromMemMap("Bump pointer space 2",
2036 mem_map.release());
2037 AddSpace(temp_space_);
Hiroshi Yamauchic1276c82014-08-07 10:27:17 -07002038 }
Mathieu Chartier4f55e222015-09-04 13:26:21 -07002039 break;
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08002040 }
Mathieu Chartier4f55e222015-09-04 13:26:21 -07002041 case kCollectorTypeMS:
2042 // Fall through.
2043 case kCollectorTypeCMS: {
2044 if (IsMovingGc(collector_type_)) {
2045 CHECK(temp_space_ != nullptr);
2046 std::unique_ptr<MemMap> mem_map(temp_space_->ReleaseMemMap());
2047 RemoveSpace(temp_space_);
2048 temp_space_ = nullptr;
2049 mem_map->Protect(PROT_READ | PROT_WRITE);
2050 CreateMainMallocSpace(mem_map.get(),
2051 kDefaultInitialSize,
2052 std::min(mem_map->Size(), growth_limit_),
2053 mem_map->Size());
2054 mem_map.release();
2055 // Compact to the main space from the bump pointer space, don't need to swap semispaces.
2056 AddSpace(main_space_);
2057 collector = Compact(main_space_, bump_pointer_space_, kGcCauseCollectorTransition);
2058 mem_map.reset(bump_pointer_space_->ReleaseMemMap());
2059 RemoveSpace(bump_pointer_space_);
2060 bump_pointer_space_ = nullptr;
2061 const char* name = kUseRosAlloc ? kRosAllocSpaceName[1] : kDlMallocSpaceName[1];
2062 // Temporarily unprotect the backup mem map so rosalloc can write the debug magic number.
2063 if (kIsDebugBuild && kUseRosAlloc) {
2064 mem_map->Protect(PROT_READ | PROT_WRITE);
2065 }
2066 main_space_backup_.reset(CreateMallocSpaceFromMemMap(
2067 mem_map.get(),
2068 kDefaultInitialSize,
2069 std::min(mem_map->Size(), growth_limit_),
2070 mem_map->Size(),
2071 name,
2072 true));
2073 if (kIsDebugBuild && kUseRosAlloc) {
2074 mem_map->Protect(PROT_NONE);
2075 }
2076 mem_map.release();
2077 }
2078 break;
2079 }
2080 default: {
2081 LOG(FATAL) << "Attempted to transition to invalid collector type "
2082 << static_cast<size_t>(collector_type);
2083 break;
2084 }
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08002085 }
Mathieu Chartier4f55e222015-09-04 13:26:21 -07002086 ChangeCollector(collector_type);
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08002087 }
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08002088 // Can't call into java code with all threads suspended.
Mathieu Chartier3cf22532015-07-09 15:15:09 -07002089 reference_processor_->EnqueueClearedReferences(self);
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08002090 uint64_t duration = NanoTime() - start_time;
Mathieu Chartierafe49982014-03-27 10:55:04 -07002091 GrowForUtilization(semi_space_collector_);
Hiroshi Yamauchie4d99872015-02-26 12:53:45 -08002092 DCHECK(collector != nullptr);
2093 LogGC(kGcCauseCollectorTransition, collector);
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08002094 FinishGC(self, collector::kGcTypeFull);
Mathieu Chartier598302a2015-09-23 14:52:39 -07002095 {
2096 ScopedObjectAccess soa(self);
2097 soa.Vm()->UnloadNativeLibraries();
2098 }
Ian Rogers3e5cf302014-05-20 16:40:37 -07002099 int32_t after_allocated = num_bytes_allocated_.LoadSequentiallyConsistent();
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08002100 int32_t delta_allocated = before_allocated - after_allocated;
Mathieu Chartier19d46b42014-06-17 15:04:40 -07002101 std::string saved_str;
2102 if (delta_allocated >= 0) {
2103 saved_str = " saved at least " + PrettySize(delta_allocated);
2104 } else {
2105 saved_str = " expanded " + PrettySize(-delta_allocated);
2106 }
Mathieu Chartierf8cb1782016-03-18 18:45:41 -07002107 VLOG(heap) << "Collector transition to " << collector_type << " took "
2108 << PrettyDuration(duration) << saved_str;
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08002109}
2110
Mathieu Chartier0de9f732013-11-22 17:58:48 -08002111void Heap::ChangeCollector(CollectorType collector_type) {
Mathieu Chartier7bf82af2013-12-06 16:51:45 -08002112 // TODO: Only do this with all mutators suspended to avoid races.
2113 if (collector_type != collector_type_) {
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002114 if (collector_type == kCollectorTypeMC) {
2115 // Don't allow mark compact unless support is compiled in.
2116 CHECK(kMarkCompactSupport);
2117 }
Mathieu Chartier7bf82af2013-12-06 16:51:45 -08002118 collector_type_ = collector_type;
2119 gc_plan_.clear();
2120 switch (collector_type_) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002121 case kCollectorTypeCC: {
2122 gc_plan_.push_back(collector::kGcTypeFull);
2123 if (use_tlab_) {
2124 ChangeAllocator(kAllocatorTypeRegionTLAB);
2125 } else {
2126 ChangeAllocator(kAllocatorTypeRegion);
2127 }
2128 break;
2129 }
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002130 case kCollectorTypeMC: // Fall-through.
Hiroshi Yamauchi3e417802014-03-20 12:03:02 -07002131 case kCollectorTypeSS: // Fall-through.
Hiroshi Yamauchi6f4ffe42014-01-13 12:30:44 -08002132 case kCollectorTypeGSS: {
Mathieu Chartier7bf82af2013-12-06 16:51:45 -08002133 gc_plan_.push_back(collector::kGcTypeFull);
Mathieu Chartier692fafd2013-11-29 17:24:40 -08002134 if (use_tlab_) {
2135 ChangeAllocator(kAllocatorTypeTLAB);
2136 } else {
2137 ChangeAllocator(kAllocatorTypeBumpPointer);
2138 }
Mathieu Chartier7bf82af2013-12-06 16:51:45 -08002139 break;
2140 }
2141 case kCollectorTypeMS: {
Mathieu Chartier7bf82af2013-12-06 16:51:45 -08002142 gc_plan_.push_back(collector::kGcTypeSticky);
2143 gc_plan_.push_back(collector::kGcTypePartial);
2144 gc_plan_.push_back(collector::kGcTypeFull);
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08002145 ChangeAllocator(kUseRosAlloc ? kAllocatorTypeRosAlloc : kAllocatorTypeDlMalloc);
Mathieu Chartier7bf82af2013-12-06 16:51:45 -08002146 break;
2147 }
2148 case kCollectorTypeCMS: {
Mathieu Chartier7bf82af2013-12-06 16:51:45 -08002149 gc_plan_.push_back(collector::kGcTypeSticky);
2150 gc_plan_.push_back(collector::kGcTypePartial);
2151 gc_plan_.push_back(collector::kGcTypeFull);
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08002152 ChangeAllocator(kUseRosAlloc ? kAllocatorTypeRosAlloc : kAllocatorTypeDlMalloc);
Mathieu Chartier7bf82af2013-12-06 16:51:45 -08002153 break;
2154 }
2155 default: {
Ian Rogers2c4257b2014-10-24 14:20:06 -07002156 UNIMPLEMENTED(FATAL);
2157 UNREACHABLE();
Mathieu Chartier7bf82af2013-12-06 16:51:45 -08002158 }
Mathieu Chartier0de9f732013-11-22 17:58:48 -08002159 }
Hiroshi Yamauchi3e417802014-03-20 12:03:02 -07002160 if (IsGcConcurrent()) {
Mathieu Chartier7bf82af2013-12-06 16:51:45 -08002161 concurrent_start_bytes_ =
2162 std::max(max_allowed_footprint_, kMinConcurrentRemainingBytes) - kMinConcurrentRemainingBytes;
2163 } else {
2164 concurrent_start_bytes_ = std::numeric_limits<size_t>::max();
Mathieu Chartier0de9f732013-11-22 17:58:48 -08002165 }
2166 }
2167}
2168
Mathieu Chartier85a43c02014-01-07 17:59:00 -08002169// Special compacting collector which uses sub-optimal bin packing to reduce zygote space size.
Ian Rogers6fac4472014-02-25 17:01:10 -08002170class ZygoteCompactingCollector FINAL : public collector::SemiSpace {
Mathieu Chartier85a43c02014-01-07 17:59:00 -08002171 public:
Roland Levillain3887c462015-08-12 18:15:42 +01002172 ZygoteCompactingCollector(gc::Heap* heap, bool is_running_on_memory_tool)
Evgenii Stepanov1e133742015-05-20 12:30:59 -07002173 : SemiSpace(heap, false, "zygote collector"),
2174 bin_live_bitmap_(nullptr),
2175 bin_mark_bitmap_(nullptr),
2176 is_running_on_memory_tool_(is_running_on_memory_tool) {}
Mathieu Chartier85a43c02014-01-07 17:59:00 -08002177
Andreas Gampe0c183382017-07-13 22:26:24 -07002178 void BuildBins(space::ContinuousSpace* space) REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier85a43c02014-01-07 17:59:00 -08002179 bin_live_bitmap_ = space->GetLiveBitmap();
2180 bin_mark_bitmap_ = space->GetMarkBitmap();
Andreas Gampe0c183382017-07-13 22:26:24 -07002181 uintptr_t prev = reinterpret_cast<uintptr_t>(space->Begin());
Mathieu Chartier85a43c02014-01-07 17:59:00 -08002182 WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
2183 // Note: This requires traversing the space in increasing order of object addresses.
Andreas Gampe0c183382017-07-13 22:26:24 -07002184 auto visitor = [&](mirror::Object* obj) REQUIRES_SHARED(Locks::mutator_lock_) {
2185 uintptr_t object_addr = reinterpret_cast<uintptr_t>(obj);
2186 size_t bin_size = object_addr - prev;
2187 // Add the bin consisting of the end of the previous object to the start of the current object.
2188 AddBin(bin_size, prev);
2189 prev = object_addr + RoundUp(obj->SizeOf<kDefaultVerifyFlags>(), kObjectAlignment);
2190 };
2191 bin_live_bitmap_->Walk(visitor);
Mathieu Chartier85a43c02014-01-07 17:59:00 -08002192 // Add the last bin which spans after the last object to the end of the space.
Andreas Gampe0c183382017-07-13 22:26:24 -07002193 AddBin(reinterpret_cast<uintptr_t>(space->End()) - prev, prev);
Mathieu Chartier85a43c02014-01-07 17:59:00 -08002194 }
2195
2196 private:
Mathieu Chartier85a43c02014-01-07 17:59:00 -08002197 // Maps from bin sizes to locations.
2198 std::multimap<size_t, uintptr_t> bins_;
2199 // Live bitmap of the space which contains the bins.
Mathieu Chartiera8e8f9c2014-04-09 14:51:05 -07002200 accounting::ContinuousSpaceBitmap* bin_live_bitmap_;
Mathieu Chartier85a43c02014-01-07 17:59:00 -08002201 // Mark bitmap of the space which contains the bins.
Mathieu Chartiera8e8f9c2014-04-09 14:51:05 -07002202 accounting::ContinuousSpaceBitmap* bin_mark_bitmap_;
Evgenii Stepanov1e133742015-05-20 12:30:59 -07002203 const bool is_running_on_memory_tool_;
Mathieu Chartier85a43c02014-01-07 17:59:00 -08002204
Mathieu Chartier85a43c02014-01-07 17:59:00 -08002205 void AddBin(size_t size, uintptr_t position) {
Evgenii Stepanov1e133742015-05-20 12:30:59 -07002206 if (is_running_on_memory_tool_) {
2207 MEMORY_TOOL_MAKE_DEFINED(reinterpret_cast<void*>(position), size);
2208 }
Mathieu Chartier85a43c02014-01-07 17:59:00 -08002209 if (size != 0) {
2210 bins_.insert(std::make_pair(size, position));
2211 }
2212 }
2213
Mathieu Chartiera4f6af92015-08-11 17:35:25 -07002214 virtual bool ShouldSweepSpace(space::ContinuousSpace* space ATTRIBUTE_UNUSED) const {
Mathieu Chartier85a43c02014-01-07 17:59:00 -08002215 // Don't sweep any spaces since we probably blasted the internal accounting of the free list
2216 // allocator.
2217 return false;
2218 }
2219
2220 virtual mirror::Object* MarkNonForwardedObject(mirror::Object* obj)
Mathieu Chartier90443472015-07-16 20:32:27 -07002221 REQUIRES(Locks::heap_bitmap_lock_, Locks::mutator_lock_) {
Mathieu Chartierd08f66f2017-04-13 11:47:53 -07002222 size_t obj_size = obj->SizeOf<kDefaultVerifyFlags>();
Hiroshi Yamauchi8711d1f2015-03-13 16:48:55 -07002223 size_t alloc_size = RoundUp(obj_size, kObjectAlignment);
Mathieu Chartier5dc08a62014-01-10 10:10:23 -08002224 mirror::Object* forward_address;
Mathieu Chartier85a43c02014-01-07 17:59:00 -08002225 // Find the smallest bin which we can move obj in.
Hiroshi Yamauchi8711d1f2015-03-13 16:48:55 -07002226 auto it = bins_.lower_bound(alloc_size);
Mathieu Chartier85a43c02014-01-07 17:59:00 -08002227 if (it == bins_.end()) {
2228 // No available space in the bins, place it in the target space instead (grows the zygote
2229 // space).
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07002230 size_t bytes_allocated, dummy;
Hiroshi Yamauchi8711d1f2015-03-13 16:48:55 -07002231 forward_address = to_space_->Alloc(self_, alloc_size, &bytes_allocated, nullptr, &dummy);
Mathieu Chartier85a43c02014-01-07 17:59:00 -08002232 if (to_space_live_bitmap_ != nullptr) {
2233 to_space_live_bitmap_->Set(forward_address);
Mathieu Chartier938a03b2014-01-16 15:10:31 -08002234 } else {
2235 GetHeap()->GetNonMovingSpace()->GetLiveBitmap()->Set(forward_address);
2236 GetHeap()->GetNonMovingSpace()->GetMarkBitmap()->Set(forward_address);
Mathieu Chartier85a43c02014-01-07 17:59:00 -08002237 }
2238 } else {
2239 size_t size = it->first;
2240 uintptr_t pos = it->second;
2241 bins_.erase(it); // Erase the old bin which we replace with the new smaller bin.
2242 forward_address = reinterpret_cast<mirror::Object*>(pos);
2243 // Set the live and mark bits so that sweeping system weaks works properly.
2244 bin_live_bitmap_->Set(forward_address);
2245 bin_mark_bitmap_->Set(forward_address);
Hiroshi Yamauchi8711d1f2015-03-13 16:48:55 -07002246 DCHECK_GE(size, alloc_size);
2247 // Add a new bin with the remaining space.
2248 AddBin(size - alloc_size, pos + alloc_size);
Mathieu Chartier85a43c02014-01-07 17:59:00 -08002249 }
Hiroshi Yamauchi8711d1f2015-03-13 16:48:55 -07002250 // Copy the object over to its new location. Don't use alloc_size to avoid valgrind error.
2251 memcpy(reinterpret_cast<void*>(forward_address), obj, obj_size);
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07002252 if (kUseBakerReadBarrier) {
2253 obj->AssertReadBarrierState();
2254 forward_address->AssertReadBarrierState();
Hiroshi Yamauchi9d04a202014-01-31 13:35:49 -08002255 }
Mathieu Chartier85a43c02014-01-07 17:59:00 -08002256 return forward_address;
2257 }
2258};
2259
Mathieu Chartiera1602f22014-01-13 17:19:19 -08002260void Heap::UnBindBitmaps() {
Mathieu Chartierf5997b42014-06-20 10:37:54 -07002261 TimingLogger::ScopedTiming t("UnBindBitmaps", GetCurrentGcIteration()->GetTimings());
Mathieu Chartiera1602f22014-01-13 17:19:19 -08002262 for (const auto& space : GetContinuousSpaces()) {
2263 if (space->IsContinuousMemMapAllocSpace()) {
2264 space::ContinuousMemMapAllocSpace* alloc_space = space->AsContinuousMemMapAllocSpace();
2265 if (alloc_space->HasBoundBitmaps()) {
2266 alloc_space->UnBindBitmaps();
2267 }
2268 }
2269 }
2270}
2271
Mathieu Chartiercc236d72012-07-20 10:29:05 -07002272void Heap::PreZygoteFork() {
Mathieu Chartierfaed9952015-03-31 16:28:53 -07002273 if (!HasZygoteSpace()) {
2274 // We still want to GC in case there is some unreachable non moving objects that could cause a
2275 // suboptimal bin packing when we compact the zygote space.
2276 CollectGarbageInternal(collector::kGcTypeFull, kGcCauseBackground, false);
Mathieu Chartier76ce9172016-01-27 10:44:20 -08002277 // Trim the pages at the end of the non moving space. Trim while not holding zygote lock since
2278 // the trim process may require locking the mutator lock.
2279 non_moving_space_->Trim();
Mathieu Chartierfaed9952015-03-31 16:28:53 -07002280 }
Ian Rogers81d425b2012-09-27 16:03:43 -07002281 Thread* self = Thread::Current();
2282 MutexLock mu(self, zygote_creation_lock_);
Mathieu Chartiercc236d72012-07-20 10:29:05 -07002283 // Try to see if we have any Zygote spaces.
Mathieu Chartiere4cab172014-08-19 18:24:04 -07002284 if (HasZygoteSpace()) {
Mathieu Chartiercc236d72012-07-20 10:29:05 -07002285 return;
2286 }
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002287 Runtime::Current()->GetInternTable()->AddNewTable();
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002288 Runtime::Current()->GetClassLinker()->MoveClassTableToPreZygote();
Mathieu Chartier590fee92013-09-13 13:46:47 -07002289 VLOG(heap) << "Starting PreZygoteFork";
Mathieu Chartier31f44142014-04-08 14:40:03 -07002290 // The end of the non-moving space may be protected, unprotect it so that we can copy the zygote
2291 // there.
Mathieu Chartier590fee92013-09-13 13:46:47 -07002292 non_moving_space_->GetMemMap()->Protect(PROT_READ | PROT_WRITE);
Mathieu Chartier6a7824d2014-08-22 14:53:04 -07002293 const bool same_space = non_moving_space_ == main_space_;
Mathieu Chartier31f44142014-04-08 14:40:03 -07002294 if (kCompactZygote) {
Hiroshi Yamauchia4adbfd2014-02-04 18:12:17 -08002295 // Temporarily disable rosalloc verification because the zygote
2296 // compaction will mess up the rosalloc internal metadata.
2297 ScopedDisableRosAllocVerification disable_rosalloc_verif(this);
Evgenii Stepanov1e133742015-05-20 12:30:59 -07002298 ZygoteCompactingCollector zygote_collector(this, is_running_on_memory_tool_);
Mathieu Chartier85a43c02014-01-07 17:59:00 -08002299 zygote_collector.BuildBins(non_moving_space_);
Mathieu Chartier50482232013-11-21 11:48:14 -08002300 // Create a new bump pointer space which we will compact into.
Mathieu Chartier590fee92013-09-13 13:46:47 -07002301 space::BumpPointerSpace target_space("zygote bump space", non_moving_space_->End(),
2302 non_moving_space_->Limit());
2303 // Compact the bump pointer space to a new zygote bump pointer space.
Mathieu Chartier31f44142014-04-08 14:40:03 -07002304 bool reset_main_space = false;
2305 if (IsMovingGc(collector_type_)) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002306 if (collector_type_ == kCollectorTypeCC) {
2307 zygote_collector.SetFromSpace(region_space_);
2308 } else {
2309 zygote_collector.SetFromSpace(bump_pointer_space_);
2310 }
Mathieu Chartier31f44142014-04-08 14:40:03 -07002311 } else {
2312 CHECK(main_space_ != nullptr);
Hiroshi Yamauchid04495e2015-03-11 19:09:07 -07002313 CHECK_NE(main_space_, non_moving_space_)
2314 << "Does not make sense to compact within the same space";
Mathieu Chartier31f44142014-04-08 14:40:03 -07002315 // Copy from the main space.
2316 zygote_collector.SetFromSpace(main_space_);
2317 reset_main_space = true;
2318 }
Mathieu Chartier85a43c02014-01-07 17:59:00 -08002319 zygote_collector.SetToSpace(&target_space);
Mathieu Chartier1b54f9c2014-04-30 16:45:02 -07002320 zygote_collector.SetSwapSemiSpaces(false);
Hiroshi Yamauchi6f4ffe42014-01-13 12:30:44 -08002321 zygote_collector.Run(kGcCauseCollectorTransition, false);
Mathieu Chartier31f44142014-04-08 14:40:03 -07002322 if (reset_main_space) {
2323 main_space_->GetMemMap()->Protect(PROT_READ | PROT_WRITE);
2324 madvise(main_space_->Begin(), main_space_->Capacity(), MADV_DONTNEED);
2325 MemMap* mem_map = main_space_->ReleaseMemMap();
2326 RemoveSpace(main_space_);
Mathieu Chartier96bcd452014-06-17 09:50:02 -07002327 space::Space* old_main_space = main_space_;
Mathieu Chartier0310da52014-12-01 13:40:48 -08002328 CreateMainMallocSpace(mem_map, kDefaultInitialSize, std::min(mem_map->Size(), growth_limit_),
2329 mem_map->Size());
Mathieu Chartier96bcd452014-06-17 09:50:02 -07002330 delete old_main_space;
Mathieu Chartier31f44142014-04-08 14:40:03 -07002331 AddSpace(main_space_);
2332 } else {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002333 if (collector_type_ == kCollectorTypeCC) {
2334 region_space_->GetMemMap()->Protect(PROT_READ | PROT_WRITE);
Mathieu Chartier7ec38dc2016-10-07 15:24:46 -07002335 // Evacuated everything out of the region space, clear the mark bitmap.
2336 region_space_->GetMarkBitmap()->Clear();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002337 } else {
2338 bump_pointer_space_->GetMemMap()->Protect(PROT_READ | PROT_WRITE);
2339 }
Mathieu Chartier31f44142014-04-08 14:40:03 -07002340 }
2341 if (temp_space_ != nullptr) {
2342 CHECK(temp_space_->IsEmpty());
2343 }
Mathieu Chartier10fb83a2014-06-15 15:15:43 -07002344 total_objects_freed_ever_ += GetCurrentGcIteration()->GetFreedObjects();
2345 total_bytes_freed_ever_ += GetCurrentGcIteration()->GetFreedBytes();
Mathieu Chartier590fee92013-09-13 13:46:47 -07002346 // Update the end and write out image.
2347 non_moving_space_->SetEnd(target_space.End());
2348 non_moving_space_->SetLimit(target_space.Limit());
Mathieu Chartierfaed9952015-03-31 16:28:53 -07002349 VLOG(heap) << "Create zygote space with size=" << non_moving_space_->Size() << " bytes";
Mathieu Chartier357e9be2012-08-01 11:00:14 -07002350 }
Mathieu Chartier6a7824d2014-08-22 14:53:04 -07002351 // Change the collector to the post zygote one.
Mathieu Chartier31f44142014-04-08 14:40:03 -07002352 ChangeCollector(foreground_collector_type_);
Mathieu Chartiera1602f22014-01-13 17:19:19 -08002353 // Save the old space so that we can remove it after we complete creating the zygote space.
2354 space::MallocSpace* old_alloc_space = non_moving_space_;
Mathieu Chartier590fee92013-09-13 13:46:47 -07002355 // Turn the current alloc space into a zygote space and obtain the new alloc space composed of
Mathieu Chartiera1602f22014-01-13 17:19:19 -08002356 // the remaining available space.
2357 // Remove the old space before creating the zygote space since creating the zygote space sets
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002358 // the old alloc space's bitmaps to null.
Mathieu Chartiera1602f22014-01-13 17:19:19 -08002359 RemoveSpace(old_alloc_space);
Hiroshi Yamauchi38e68e92014-03-07 13:59:08 -08002360 if (collector::SemiSpace::kUseRememberedSet) {
2361 // Sanity bound check.
2362 FindRememberedSetFromSpace(old_alloc_space)->AssertAllDirtyCardsAreWithinSpace();
2363 // Remove the remembered set for the now zygote space (the old
2364 // non-moving space). Note now that we have compacted objects into
2365 // the zygote space, the data in the remembered set is no longer
2366 // needed. The zygote space will instead have a mod-union table
2367 // from this point on.
2368 RemoveRememberedSet(old_alloc_space);
2369 }
Mathieu Chartier7247af52014-11-19 10:51:42 -08002370 // Remaining space becomes the new non moving space.
2371 zygote_space_ = old_alloc_space->CreateZygoteSpace(kNonMovingSpaceName, low_memory_mode_,
Mathieu Chartiere4cab172014-08-19 18:24:04 -07002372 &non_moving_space_);
Mathieu Chartierb363f662014-07-16 13:28:58 -07002373 CHECK(!non_moving_space_->CanMoveObjects());
2374 if (same_space) {
2375 main_space_ = non_moving_space_;
2376 SetSpaceAsDefault(main_space_);
2377 }
Mathieu Chartiera1602f22014-01-13 17:19:19 -08002378 delete old_alloc_space;
Mathieu Chartiere4cab172014-08-19 18:24:04 -07002379 CHECK(HasZygoteSpace()) << "Failed creating zygote space";
2380 AddSpace(zygote_space_);
Mathieu Chartier31f44142014-04-08 14:40:03 -07002381 non_moving_space_->SetFootprintLimit(non_moving_space_->Capacity());
2382 AddSpace(non_moving_space_);
Mathieu Chartier36a270a2016-07-28 18:08:51 -07002383 if (kUseBakerReadBarrier && gc::collector::ConcurrentCopying::kGrayDirtyImmuneObjects) {
2384 // Treat all of the objects in the zygote as marked to avoid unnecessary dirty pages. This is
2385 // safe since we mark all of the objects that may reference non immune objects as gray.
2386 zygote_space_->GetLiveBitmap()->VisitMarkedRange(
2387 reinterpret_cast<uintptr_t>(zygote_space_->Begin()),
2388 reinterpret_cast<uintptr_t>(zygote_space_->Limit()),
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002389 [](mirror::Object* obj) REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier36a270a2016-07-28 18:08:51 -07002390 CHECK(obj->AtomicSetMarkBit(0, 1));
2391 });
2392 }
2393
Mathieu Chartier11409ae2013-09-23 11:49:36 -07002394 // Create the zygote space mod union table.
2395 accounting::ModUnionTable* mod_union_table =
Mathieu Chartier962cd7a2016-08-16 12:15:59 -07002396 new accounting::ModUnionTableCardCache("zygote space mod-union table", this, zygote_space_);
Mathieu Chartier11409ae2013-09-23 11:49:36 -07002397 CHECK(mod_union_table != nullptr) << "Failed to create zygote space mod-union table";
Mathieu Chartier962cd7a2016-08-16 12:15:59 -07002398
2399 if (collector_type_ != kCollectorTypeCC) {
2400 // Set all the cards in the mod-union table since we don't know which objects contain references
2401 // to large objects.
2402 mod_union_table->SetCards();
2403 } else {
Mathieu Chartier55c05f52017-04-11 11:12:28 -07002404 // Make sure to clear the zygote space cards so that we don't dirty pages in the next GC. There
2405 // may be dirty cards from the zygote compaction or reference processing. These cards are not
2406 // necessary to have marked since the zygote space may not refer to any objects not in the
2407 // zygote or image spaces at this point.
2408 mod_union_table->ProcessCards();
2409 mod_union_table->ClearTable();
2410
Mathieu Chartier962cd7a2016-08-16 12:15:59 -07002411 // For CC we never collect zygote large objects. This means we do not need to set the cards for
2412 // the zygote mod-union table and we can also clear all of the existing image mod-union tables.
2413 // The existing mod-union tables are only for image spaces and may only reference zygote and
2414 // image objects.
2415 for (auto& pair : mod_union_tables_) {
2416 CHECK(pair.first->IsImageSpace());
2417 CHECK(!pair.first->AsImageSpace()->GetImageHeader().IsAppImage());
2418 accounting::ModUnionTable* table = pair.second;
2419 table->ClearTable();
2420 }
2421 }
Mathieu Chartier11409ae2013-09-23 11:49:36 -07002422 AddModUnionTable(mod_union_table);
Mathieu Chartierf6c2a272015-06-03 17:32:42 -07002423 large_object_space_->SetAllLargeObjectsAsZygoteObjects(self);
Hiroshi Yamauchi38e68e92014-03-07 13:59:08 -08002424 if (collector::SemiSpace::kUseRememberedSet) {
Hiroshi Yamauchi38e68e92014-03-07 13:59:08 -08002425 // Add a new remembered set for the post-zygote non-moving space.
2426 accounting::RememberedSet* post_zygote_non_moving_space_rem_set =
2427 new accounting::RememberedSet("Post-zygote non-moving space remembered set", this,
2428 non_moving_space_);
2429 CHECK(post_zygote_non_moving_space_rem_set != nullptr)
2430 << "Failed to create post-zygote non-moving space remembered set";
2431 AddRememberedSet(post_zygote_non_moving_space_rem_set);
2432 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -07002433}
2434
Mathieu Chartier357e9be2012-08-01 11:00:14 -07002435void Heap::FlushAllocStack() {
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08002436 MarkAllocStackAsLive(allocation_stack_.get());
Mathieu Chartier357e9be2012-08-01 11:00:14 -07002437 allocation_stack_->Reset();
2438}
2439
Mathieu Chartiera8e8f9c2014-04-09 14:51:05 -07002440void Heap::MarkAllocStack(accounting::ContinuousSpaceBitmap* bitmap1,
2441 accounting::ContinuousSpaceBitmap* bitmap2,
Mathieu Chartierbbd695c2014-04-16 09:48:48 -07002442 accounting::LargeObjectBitmap* large_objects,
Ian Rogers1d54e732013-05-02 21:10:01 -07002443 accounting::ObjectStack* stack) {
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08002444 DCHECK(bitmap1 != nullptr);
2445 DCHECK(bitmap2 != nullptr);
Mathieu Chartiercb535da2015-01-23 13:50:03 -08002446 const auto* limit = stack->End();
2447 for (auto* it = stack->Begin(); it != limit; ++it) {
2448 const mirror::Object* obj = it->AsMirrorPtr();
Hiroshi Yamauchif5b0e202014-02-11 17:02:22 -08002449 if (!kUseThreadLocalAllocationStack || obj != nullptr) {
2450 if (bitmap1->HasAddress(obj)) {
2451 bitmap1->Set(obj);
2452 } else if (bitmap2->HasAddress(obj)) {
2453 bitmap2->Set(obj);
2454 } else {
Mathieu Chartier2dbe6272014-09-16 10:43:23 -07002455 DCHECK(large_objects != nullptr);
Hiroshi Yamauchif5b0e202014-02-11 17:02:22 -08002456 large_objects->Set(obj);
2457 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07002458 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07002459 }
2460}
2461
Mathieu Chartier590fee92013-09-13 13:46:47 -07002462void Heap::SwapSemiSpaces() {
Mathieu Chartier31f44142014-04-08 14:40:03 -07002463 CHECK(bump_pointer_space_ != nullptr);
2464 CHECK(temp_space_ != nullptr);
Mathieu Chartier590fee92013-09-13 13:46:47 -07002465 std::swap(bump_pointer_space_, temp_space_);
2466}
2467
Hiroshi Yamauchie4d99872015-02-26 12:53:45 -08002468collector::GarbageCollector* Heap::Compact(space::ContinuousMemMapAllocSpace* target_space,
2469 space::ContinuousMemMapAllocSpace* source_space,
2470 GcCause gc_cause) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07002471 CHECK(kMovingCollector);
Mathieu Chartier590fee92013-09-13 13:46:47 -07002472 if (target_space != source_space) {
Mathieu Chartier6f365cc2014-04-23 12:42:27 -07002473 // Don't swap spaces since this isn't a typical semi space collection.
2474 semi_space_collector_->SetSwapSemiSpaces(false);
Mathieu Chartier590fee92013-09-13 13:46:47 -07002475 semi_space_collector_->SetFromSpace(source_space);
2476 semi_space_collector_->SetToSpace(target_space);
Zuo Wangf37a88b2014-07-10 04:26:41 -07002477 semi_space_collector_->Run(gc_cause, false);
Hiroshi Yamauchie4d99872015-02-26 12:53:45 -08002478 return semi_space_collector_;
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002479 } else {
2480 CHECK(target_space->IsBumpPointerSpace())
2481 << "In-place compaction is only supported for bump pointer spaces";
2482 mark_compact_collector_->SetSpace(target_space->AsBumpPointerSpace());
2483 mark_compact_collector_->Run(kGcCauseCollectorTransition, false);
Hiroshi Yamauchie4d99872015-02-26 12:53:45 -08002484 return mark_compact_collector_;
Mathieu Chartier590fee92013-09-13 13:46:47 -07002485 }
2486}
Anwar Ghuloum67f99412013-08-12 14:19:48 -07002487
Mathieu Chartier34afcde2017-06-30 15:31:11 -07002488void Heap::TraceHeapSize(size_t heap_size) {
2489 ATRACE_INT("Heap size (KB)", heap_size / KB);
2490}
2491
Mathieu Chartiera4f6af92015-08-11 17:35:25 -07002492collector::GcType Heap::CollectGarbageInternal(collector::GcType gc_type,
2493 GcCause gc_cause,
Ian Rogers1d54e732013-05-02 21:10:01 -07002494 bool clear_soft_references) {
Ian Rogers81d425b2012-09-27 16:03:43 -07002495 Thread* self = Thread::Current();
Mathieu Chartier590fee92013-09-13 13:46:47 -07002496 Runtime* runtime = Runtime::Current();
Mathieu Chartiercbb2d202013-11-14 17:45:16 -08002497 // If the heap can't run the GC, silently fail and return that no GC was run.
2498 switch (gc_type) {
Mathieu Chartiercbb2d202013-11-14 17:45:16 -08002499 case collector::kGcTypePartial: {
Mathieu Chartiere4cab172014-08-19 18:24:04 -07002500 if (!HasZygoteSpace()) {
Mathieu Chartiercbb2d202013-11-14 17:45:16 -08002501 return collector::kGcTypeNone;
2502 }
2503 break;
2504 }
2505 default: {
2506 // Other GC types don't have any special cases which makes them not runnable. The main case
2507 // here is full GC.
2508 }
2509 }
Mathieu Chartier65db8802012-11-20 12:36:46 -08002510 ScopedThreadStateChange tsc(self, kWaitingPerformingGc);
Ian Rogers81d425b2012-09-27 16:03:43 -07002511 Locks::mutator_lock_->AssertNotHeld(self);
Ian Rogers120f1c72012-09-28 17:17:10 -07002512 if (self->IsHandlingStackOverflow()) {
Mathieu Chartier50c138f2015-01-07 16:00:03 -08002513 // If we are throwing a stack overflow error we probably don't have enough remaining stack
2514 // space to run the GC.
2515 return collector::kGcTypeNone;
Ian Rogers120f1c72012-09-28 17:17:10 -07002516 }
Mathieu Chartierd5a89ee2014-01-31 09:55:13 -08002517 bool compacting_gc;
2518 {
2519 gc_complete_lock_->AssertNotHeld(self);
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002520 ScopedThreadStateChange tsc2(self, kWaitingForGcToComplete);
Mathieu Chartierd5a89ee2014-01-31 09:55:13 -08002521 MutexLock mu(self, *gc_complete_lock_);
2522 // Ensure there is only one GC at a time.
Mathieu Chartier89a201e2014-05-02 10:27:26 -07002523 WaitForGcToCompleteLocked(gc_cause, self);
Mathieu Chartier31f44142014-04-08 14:40:03 -07002524 compacting_gc = IsMovingGc(collector_type_);
Mathieu Chartierd5a89ee2014-01-31 09:55:13 -08002525 // GC can be disabled if someone has a used GetPrimitiveArrayCritical.
2526 if (compacting_gc && disable_moving_gc_count_ != 0) {
2527 LOG(WARNING) << "Skipping GC due to disable moving GC count " << disable_moving_gc_count_;
2528 return collector::kGcTypeNone;
2529 }
Mathieu Chartier51168372015-08-12 16:40:32 -07002530 if (gc_disabled_for_shutdown_) {
2531 return collector::kGcTypeNone;
2532 }
Mathieu Chartierd5a89ee2014-01-31 09:55:13 -08002533 collector_type_running_ = collector_type_;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002534 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07002535 if (gc_cause == kGcCauseForAlloc && runtime->HasStatsEnabled()) {
2536 ++runtime->GetStats()->gc_for_alloc_count;
2537 ++self->GetStats()->gc_for_alloc_count;
Mathieu Chartier2fde5332012-09-14 14:51:54 -07002538 }
Mathieu Chartiere2c2f6e2014-12-16 18:49:31 -08002539 const uint64_t bytes_allocated_before_gc = GetBytesAllocated();
Mathieu Chartier65db8802012-11-20 12:36:46 -08002540
Richard Uhlercaaa2b02017-02-01 09:54:17 +00002541 if (gc_type == NonStickyGcType()) {
2542 // Move all bytes from new_native_bytes_allocated_ to
2543 // old_native_bytes_allocated_ now that GC has been triggered, resetting
2544 // new_native_bytes_allocated_ to zero in the process.
2545 old_native_bytes_allocated_.FetchAndAddRelaxed(new_native_bytes_allocated_.ExchangeRelaxed(0));
Richard Uhlerda1da8a2017-05-16 13:37:32 +00002546 if (gc_cause == kGcCauseForNativeAllocBlocking) {
2547 MutexLock mu(self, *native_blocking_gc_lock_);
2548 native_blocking_gc_in_progress_ = true;
2549 }
Richard Uhlercaaa2b02017-02-01 09:54:17 +00002550 }
2551
Ian Rogers1d54e732013-05-02 21:10:01 -07002552 DCHECK_LT(gc_type, collector::kGcTypeMax);
2553 DCHECK_NE(gc_type, collector::kGcTypeNone);
Anwar Ghuloum67f99412013-08-12 14:19:48 -07002554
Mathieu Chartier590fee92013-09-13 13:46:47 -07002555 collector::GarbageCollector* collector = nullptr;
Mathieu Chartier50482232013-11-21 11:48:14 -08002556 // TODO: Clean this up.
Mathieu Chartier1d27b342014-01-28 12:51:09 -08002557 if (compacting_gc) {
Mathieu Chartier692fafd2013-11-29 17:24:40 -08002558 DCHECK(current_allocator_ == kAllocatorTypeBumpPointer ||
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002559 current_allocator_ == kAllocatorTypeTLAB ||
2560 current_allocator_ == kAllocatorTypeRegion ||
2561 current_allocator_ == kAllocatorTypeRegionTLAB);
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002562 switch (collector_type_) {
2563 case kCollectorTypeSS:
2564 // Fall-through.
2565 case kCollectorTypeGSS:
2566 semi_space_collector_->SetFromSpace(bump_pointer_space_);
2567 semi_space_collector_->SetToSpace(temp_space_);
2568 semi_space_collector_->SetSwapSemiSpaces(true);
2569 collector = semi_space_collector_;
2570 break;
2571 case kCollectorTypeCC:
2572 collector = concurrent_copying_collector_;
2573 break;
2574 case kCollectorTypeMC:
2575 mark_compact_collector_->SetSpace(bump_pointer_space_);
2576 collector = mark_compact_collector_;
2577 break;
2578 default:
2579 LOG(FATAL) << "Invalid collector type " << static_cast<size_t>(collector_type_);
Hiroshi Yamauchid5307ec2014-03-27 21:07:51 -07002580 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002581 if (collector != mark_compact_collector_ && collector != concurrent_copying_collector_) {
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002582 temp_space_->GetMemMap()->Protect(PROT_READ | PROT_WRITE);
Hiroshi Yamauchi6edb9ae2016-02-08 14:18:21 -08002583 if (kIsDebugBuild) {
2584 // Try to read each page of the memory map in case mprotect didn't work properly b/19894268.
2585 temp_space_->GetMemMap()->TryReadable();
2586 }
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002587 CHECK(temp_space_->IsEmpty());
2588 }
2589 gc_type = collector::kGcTypeFull; // TODO: Not hard code this in.
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08002590 } else if (current_allocator_ == kAllocatorTypeRosAlloc ||
2591 current_allocator_ == kAllocatorTypeDlMalloc) {
Mathieu Chartierafe49982014-03-27 10:55:04 -07002592 collector = FindCollectorByGcType(gc_type);
Mathieu Chartier50482232013-11-21 11:48:14 -08002593 } else {
2594 LOG(FATAL) << "Invalid current allocator " << current_allocator_;
Mathieu Chartier590fee92013-09-13 13:46:47 -07002595 }
Mathieu Chartier08cef222014-10-22 17:18:34 -07002596 if (IsGcConcurrent()) {
2597 // Disable concurrent GC check so that we don't have spammy JNI requests.
2598 // This gets recalculated in GrowForUtilization. It is important that it is disabled /
2599 // calculated in the same thread so that there aren't any races that can cause it to become
2600 // permanantly disabled. b/17942071
2601 concurrent_start_bytes_ = std::numeric_limits<size_t>::max();
2602 }
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +00002603
Mathieu Chartier7bf82af2013-12-06 16:51:45 -08002604 CHECK(collector != nullptr)
Hiroshi Yamauchi3e417802014-03-20 12:03:02 -07002605 << "Could not find garbage collector with collector_type="
2606 << static_cast<size_t>(collector_type_) << " and gc_type=" << gc_type;
Mathieu Chartier6f365cc2014-04-23 12:42:27 -07002607 collector->Run(gc_cause, clear_soft_references || runtime->IsZygote());
Mathieu Chartier10fb83a2014-06-15 15:15:43 -07002608 total_objects_freed_ever_ += GetCurrentGcIteration()->GetFreedObjects();
2609 total_bytes_freed_ever_ += GetCurrentGcIteration()->GetFreedBytes();
Mathieu Chartiera5eae692014-12-17 17:56:03 -08002610 RequestTrim(self);
Mathieu Chartier39e32612013-11-12 16:28:05 -08002611 // Enqueue cleared references.
Mathieu Chartier3cf22532015-07-09 15:15:09 -07002612 reference_processor_->EnqueueClearedReferences(self);
Mathieu Chartier590fee92013-09-13 13:46:47 -07002613 // Grow the heap so that we know when to perform the next GC.
Mathieu Chartiere2c2f6e2014-12-16 18:49:31 -08002614 GrowForUtilization(collector, bytes_allocated_before_gc);
Hiroshi Yamauchie4d99872015-02-26 12:53:45 -08002615 LogGC(gc_cause, collector);
2616 FinishGC(self, gc_type);
2617 // Inform DDMS that a GC completed.
2618 Dbg::GcDidFinish();
Mathieu Chartier598302a2015-09-23 14:52:39 -07002619 // Unload native libraries for class unloading. We do this after calling FinishGC to prevent
2620 // deadlocks in case the JNI_OnUnload function does allocations.
2621 {
2622 ScopedObjectAccess soa(self);
2623 soa.Vm()->UnloadNativeLibraries();
2624 }
Hiroshi Yamauchie4d99872015-02-26 12:53:45 -08002625 return gc_type;
2626}
2627
2628void Heap::LogGC(GcCause gc_cause, collector::GarbageCollector* collector) {
Mathieu Chartier10fb83a2014-06-15 15:15:43 -07002629 const size_t duration = GetCurrentGcIteration()->GetDurationNs();
2630 const std::vector<uint64_t>& pause_times = GetCurrentGcIteration()->GetPauseTimes();
Mathieu Chartier62ab87b2014-04-28 12:22:07 -07002631 // Print the GC if it is an explicit GC (e.g. Runtime.gc()) or a slow GC
Mathieu Chartierf5997b42014-06-20 10:37:54 -07002632 // (mutator time blocked >= long_pause_log_threshold_).
Mathieu Chartier6bc77742017-04-18 17:46:23 -07002633 bool log_gc = kLogAllGCs || gc_cause == kGcCauseExplicit;
Mathieu Chartier62ab87b2014-04-28 12:22:07 -07002634 if (!log_gc && CareAboutPauseTimes()) {
Mathieu Chartiere53225c2013-08-19 10:59:11 -07002635 // GC for alloc pauses the allocating thread, so consider it as a pause.
Mathieu Chartier62ab87b2014-04-28 12:22:07 -07002636 log_gc = duration > long_gc_log_threshold_ ||
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08002637 (gc_cause == kGcCauseForAlloc && duration > long_pause_log_threshold_);
Mathieu Chartier62ab87b2014-04-28 12:22:07 -07002638 for (uint64_t pause : pause_times) {
2639 log_gc = log_gc || pause >= long_pause_log_threshold_;
Mathieu Chartiere53225c2013-08-19 10:59:11 -07002640 }
Mathieu Chartier62ab87b2014-04-28 12:22:07 -07002641 }
2642 if (log_gc) {
2643 const size_t percent_free = GetPercentFree();
2644 const size_t current_heap_size = GetBytesAllocated();
2645 const size_t total_memory = GetTotalMemory();
2646 std::ostringstream pause_string;
2647 for (size_t i = 0; i < pause_times.size(); ++i) {
Hiroshi Yamauchie4d99872015-02-26 12:53:45 -08002648 pause_string << PrettyDuration((pause_times[i] / 1000) * 1000)
2649 << ((i != pause_times.size() - 1) ? "," : "");
Mathieu Chartiere53225c2013-08-19 10:59:11 -07002650 }
Mathieu Chartier62ab87b2014-04-28 12:22:07 -07002651 LOG(INFO) << gc_cause << " " << collector->GetName()
Mathieu Chartier10fb83a2014-06-15 15:15:43 -07002652 << " GC freed " << current_gc_iteration_.GetFreedObjects() << "("
2653 << PrettySize(current_gc_iteration_.GetFreedBytes()) << ") AllocSpace objects, "
2654 << current_gc_iteration_.GetFreedLargeObjects() << "("
2655 << PrettySize(current_gc_iteration_.GetFreedLargeObjectBytes()) << ") LOS objects, "
Mathieu Chartier62ab87b2014-04-28 12:22:07 -07002656 << percent_free << "% free, " << PrettySize(current_heap_size) << "/"
2657 << PrettySize(total_memory) << ", " << "paused " << pause_string.str()
2658 << " total " << PrettyDuration((duration / 1000) * 1000);
Ian Rogersc7dd2952014-10-21 23:31:19 -07002659 VLOG(heap) << Dumpable<TimingLogger>(*current_gc_iteration_.GetTimings());
Mathieu Chartier2b82db42012-11-14 17:29:05 -08002660 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002661}
Mathieu Chartiera6399032012-06-11 18:49:50 -07002662
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08002663void Heap::FinishGC(Thread* self, collector::GcType gc_type) {
2664 MutexLock mu(self, *gc_complete_lock_);
Mathieu Chartierd5a89ee2014-01-31 09:55:13 -08002665 collector_type_running_ = kCollectorTypeNone;
2666 if (gc_type != collector::kGcTypeNone) {
2667 last_gc_type_ = gc_type;
Hiroshi Yamauchia1c9f012015-04-02 10:18:12 -07002668
2669 // Update stats.
2670 ++gc_count_last_window_;
2671 if (running_collection_is_blocking_) {
2672 // If the currently running collection was a blocking one,
2673 // increment the counters and reset the flag.
2674 ++blocking_gc_count_;
2675 blocking_gc_time_ += GetCurrentGcIteration()->GetDurationNs();
2676 ++blocking_gc_count_last_window_;
2677 }
2678 // Update the gc count rate histograms if due.
2679 UpdateGcCountRateHistograms();
Mathieu Chartierd5a89ee2014-01-31 09:55:13 -08002680 }
Hiroshi Yamauchia1c9f012015-04-02 10:18:12 -07002681 // Reset.
2682 running_collection_is_blocking_ = false;
Mathieu Chartier183009a2017-02-16 21:19:28 -08002683 thread_running_gc_ = nullptr;
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08002684 // Wake anyone who may have been waiting for the GC to complete.
2685 gc_complete_cond_->Broadcast(self);
2686}
2687
Hiroshi Yamauchia1c9f012015-04-02 10:18:12 -07002688void Heap::UpdateGcCountRateHistograms() {
2689 // Invariant: if the time since the last update includes more than
2690 // one windows, all the GC runs (if > 0) must have happened in first
2691 // window because otherwise the update must have already taken place
2692 // at an earlier GC run. So, we report the non-first windows with
2693 // zero counts to the histograms.
2694 DCHECK_EQ(last_update_time_gc_count_rate_histograms_ % kGcCountRateHistogramWindowDuration, 0U);
2695 uint64_t now = NanoTime();
2696 DCHECK_GE(now, last_update_time_gc_count_rate_histograms_);
2697 uint64_t time_since_last_update = now - last_update_time_gc_count_rate_histograms_;
2698 uint64_t num_of_windows = time_since_last_update / kGcCountRateHistogramWindowDuration;
2699 if (time_since_last_update >= kGcCountRateHistogramWindowDuration) {
2700 // Record the first window.
2701 gc_count_rate_histogram_.AddValue(gc_count_last_window_ - 1); // Exclude the current run.
2702 blocking_gc_count_rate_histogram_.AddValue(running_collection_is_blocking_ ?
2703 blocking_gc_count_last_window_ - 1 : blocking_gc_count_last_window_);
2704 // Record the other windows (with zero counts).
2705 for (uint64_t i = 0; i < num_of_windows - 1; ++i) {
2706 gc_count_rate_histogram_.AddValue(0);
2707 blocking_gc_count_rate_histogram_.AddValue(0);
2708 }
2709 // Update the last update time and reset the counters.
2710 last_update_time_gc_count_rate_histograms_ =
2711 (now / kGcCountRateHistogramWindowDuration) * kGcCountRateHistogramWindowDuration;
2712 gc_count_last_window_ = 1; // Include the current run.
2713 blocking_gc_count_last_window_ = running_collection_is_blocking_ ? 1 : 0;
2714 }
2715 DCHECK_EQ(last_update_time_gc_count_rate_histograms_ % kGcCountRateHistogramWindowDuration, 0U);
2716}
2717
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002718class RootMatchesObjectVisitor : public SingleRootVisitor {
2719 public:
2720 explicit RootMatchesObjectVisitor(const mirror::Object* obj) : obj_(obj) { }
2721
2722 void VisitRoot(mirror::Object* root, const RootInfo& info)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002723 OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002724 if (root == obj_) {
2725 LOG(INFO) << "Object " << obj_ << " is a root " << info.ToString();
2726 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -07002727 }
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002728
2729 private:
2730 const mirror::Object* const obj_;
2731};
2732
Mathieu Chartierfd678be2012-08-30 14:50:54 -07002733
2734class ScanVisitor {
2735 public:
Brian Carlstromdf629502013-07-17 22:39:56 -07002736 void operator()(const mirror::Object* obj) const {
Mathieu Chartier0f72e412013-09-06 16:40:01 -07002737 LOG(ERROR) << "Would have rescanned object " << obj;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07002738 }
2739};
2740
Ian Rogers1d54e732013-05-02 21:10:01 -07002741// Verify a reference from an object.
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002742class VerifyReferenceVisitor : public SingleRootVisitor {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07002743 public:
Roland Levillain3887c462015-08-12 18:15:42 +01002744 VerifyReferenceVisitor(Heap* heap, Atomic<size_t>* fail_count, bool verify_referent)
Andreas Gampe351c4472017-07-12 19:32:55 -07002745 REQUIRES_SHARED(Locks::mutator_lock_)
Mathieu Chartier8ab7e782014-05-19 16:55:27 -07002746 : heap_(heap), fail_count_(fail_count), verify_referent_(verify_referent) {}
Ian Rogers1d54e732013-05-02 21:10:01 -07002747
Mathieu Chartier8ab7e782014-05-19 16:55:27 -07002748 size_t GetFailureCount() const {
Mathieu Chartiere9e55ac2014-05-21 17:48:25 -07002749 return fail_count_->LoadSequentiallyConsistent();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07002750 }
2751
Mathieu Chartier31e88222016-10-14 18:43:19 -07002752 void operator()(ObjPtr<mirror::Class> klass ATTRIBUTE_UNUSED, ObjPtr<mirror::Reference> ref) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002753 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier78f7b4c2014-05-06 10:57:27 -07002754 if (verify_referent_) {
Mathieu Chartier31e88222016-10-14 18:43:19 -07002755 VerifyReference(ref.Ptr(), ref->GetReferent(), mirror::Reference::ReferentOffset());
Mathieu Chartier78f7b4c2014-05-06 10:57:27 -07002756 }
Mathieu Chartier407f7022014-02-18 14:37:05 -08002757 }
2758
Mathieu Chartier31e88222016-10-14 18:43:19 -07002759 void operator()(ObjPtr<mirror::Object> obj,
2760 MemberOffset offset,
2761 bool is_static ATTRIBUTE_UNUSED) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002762 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier31e88222016-10-14 18:43:19 -07002763 VerifyReference(obj.Ptr(), obj->GetFieldObject<mirror::Object>(offset), offset);
Mathieu Chartier407f7022014-02-18 14:37:05 -08002764 }
2765
Mathieu Chartier31e88222016-10-14 18:43:19 -07002766 bool IsLive(ObjPtr<mirror::Object> obj) const NO_THREAD_SAFETY_ANALYSIS {
Mathieu Chartier8ab7e782014-05-19 16:55:27 -07002767 return heap_->IsLiveObjectLocked(obj, true, false, true);
2768 }
2769
Mathieu Chartierda7c6502015-07-23 16:01:26 -07002770 void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002771 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierda7c6502015-07-23 16:01:26 -07002772 if (!root->IsNull()) {
2773 VisitRoot(root);
2774 }
2775 }
2776 void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002777 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierda7c6502015-07-23 16:01:26 -07002778 const_cast<VerifyReferenceVisitor*>(this)->VisitRoot(
2779 root->AsMirrorPtr(), RootInfo(kRootVMInternal));
2780 }
2781
2782 virtual void VisitRoot(mirror::Object* root, const RootInfo& root_info) OVERRIDE
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002783 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002784 if (root == nullptr) {
2785 LOG(ERROR) << "Root is null with info " << root_info.GetType();
2786 } else if (!VerifyReference(nullptr, root, MemberOffset(0))) {
David Sehr709b0702016-10-13 09:12:37 -07002787 LOG(ERROR) << "Root " << root << " is dead with type " << mirror::Object::PrettyTypeOf(root)
Mathieu Chartiere34fa1d2015-01-14 14:55:47 -08002788 << " thread_id= " << root_info.GetThreadId() << " root_type= " << root_info.GetType();
Mathieu Chartier8ab7e782014-05-19 16:55:27 -07002789 }
2790 }
2791
2792 private:
Mathieu Chartier407f7022014-02-18 14:37:05 -08002793 // TODO: Fix the no thread safety analysis.
Mathieu Chartier8ab7e782014-05-19 16:55:27 -07002794 // Returns false on failure.
2795 bool VerifyReference(mirror::Object* obj, mirror::Object* ref, MemberOffset offset) const
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002796 NO_THREAD_SAFETY_ANALYSIS {
Mathieu Chartier938a03b2014-01-16 15:10:31 -08002797 if (ref == nullptr || IsLive(ref)) {
2798 // Verify that the reference is live.
Mathieu Chartier8ab7e782014-05-19 16:55:27 -07002799 return true;
Mathieu Chartier938a03b2014-01-16 15:10:31 -08002800 }
Mathieu Chartiere9e55ac2014-05-21 17:48:25 -07002801 if (fail_count_->FetchAndAddSequentiallyConsistent(1) == 0) {
Mathieu Chartier938a03b2014-01-16 15:10:31 -08002802 // Print message on only on first failure to prevent spam.
2803 LOG(ERROR) << "!!!!!!!!!!!!!!Heap corruption detected!!!!!!!!!!!!!!!!!!!";
Mathieu Chartier938a03b2014-01-16 15:10:31 -08002804 }
2805 if (obj != nullptr) {
Mathieu Chartier8ab7e782014-05-19 16:55:27 -07002806 // Only do this part for non roots.
Ian Rogers1d54e732013-05-02 21:10:01 -07002807 accounting::CardTable* card_table = heap_->GetCardTable();
2808 accounting::ObjectStack* alloc_stack = heap_->allocation_stack_.get();
2809 accounting::ObjectStack* live_stack = heap_->live_stack_.get();
Ian Rogers13735952014-10-08 12:43:28 -07002810 uint8_t* card_addr = card_table->CardFromAddr(obj);
Mathieu Chartier938a03b2014-01-16 15:10:31 -08002811 LOG(ERROR) << "Object " << obj << " references dead object " << ref << " at offset "
2812 << offset << "\n card value = " << static_cast<int>(*card_addr);
2813 if (heap_->IsValidObjectAddress(obj->GetClass())) {
David Sehr709b0702016-10-13 09:12:37 -07002814 LOG(ERROR) << "Obj type " << obj->PrettyTypeOf();
Mathieu Chartier938a03b2014-01-16 15:10:31 -08002815 } else {
2816 LOG(ERROR) << "Object " << obj << " class(" << obj->GetClass() << ") not a heap address";
Mathieu Chartier0f72e412013-09-06 16:40:01 -07002817 }
Mathieu Chartier938a03b2014-01-16 15:10:31 -08002818
Mathieu Chartierb363f662014-07-16 13:28:58 -07002819 // Attempt to find the class inside of the recently freed objects.
Mathieu Chartier938a03b2014-01-16 15:10:31 -08002820 space::ContinuousSpace* ref_space = heap_->FindContinuousSpaceFromObject(ref, true);
2821 if (ref_space != nullptr && ref_space->IsMallocSpace()) {
2822 space::MallocSpace* space = ref_space->AsMallocSpace();
2823 mirror::Class* ref_class = space->FindRecentFreedObject(ref);
2824 if (ref_class != nullptr) {
2825 LOG(ERROR) << "Reference " << ref << " found as a recently freed object with class "
David Sehr709b0702016-10-13 09:12:37 -07002826 << ref_class->PrettyClass();
Mathieu Chartier0f72e412013-09-06 16:40:01 -07002827 } else {
Mathieu Chartier938a03b2014-01-16 15:10:31 -08002828 LOG(ERROR) << "Reference " << ref << " not found as a recently freed object";
Mathieu Chartier0f72e412013-09-06 16:40:01 -07002829 }
Mathieu Chartier938a03b2014-01-16 15:10:31 -08002830 }
Mathieu Chartier0f72e412013-09-06 16:40:01 -07002831
Mathieu Chartier938a03b2014-01-16 15:10:31 -08002832 if (ref->GetClass() != nullptr && heap_->IsValidObjectAddress(ref->GetClass()) &&
2833 ref->GetClass()->IsClass()) {
David Sehr709b0702016-10-13 09:12:37 -07002834 LOG(ERROR) << "Ref type " << ref->PrettyTypeOf();
Mathieu Chartier938a03b2014-01-16 15:10:31 -08002835 } else {
2836 LOG(ERROR) << "Ref " << ref << " class(" << ref->GetClass()
2837 << ") is not a valid heap address";
2838 }
2839
Ian Rogers13735952014-10-08 12:43:28 -07002840 card_table->CheckAddrIsInCardTable(reinterpret_cast<const uint8_t*>(obj));
Mathieu Chartier938a03b2014-01-16 15:10:31 -08002841 void* cover_begin = card_table->AddrFromCard(card_addr);
2842 void* cover_end = reinterpret_cast<void*>(reinterpret_cast<size_t>(cover_begin) +
2843 accounting::CardTable::kCardSize);
2844 LOG(ERROR) << "Card " << reinterpret_cast<void*>(card_addr) << " covers " << cover_begin
2845 << "-" << cover_end;
Mathieu Chartiera8e8f9c2014-04-09 14:51:05 -07002846 accounting::ContinuousSpaceBitmap* bitmap =
2847 heap_->GetLiveBitmap()->GetContinuousSpaceBitmap(obj);
Mathieu Chartier938a03b2014-01-16 15:10:31 -08002848
2849 if (bitmap == nullptr) {
2850 LOG(ERROR) << "Object " << obj << " has no bitmap";
Mathieu Chartier4e305412014-02-19 10:54:44 -08002851 if (!VerifyClassClass(obj->GetClass())) {
Mathieu Chartier938a03b2014-01-16 15:10:31 -08002852 LOG(ERROR) << "Object " << obj << " failed class verification!";
Mathieu Chartier0f72e412013-09-06 16:40:01 -07002853 }
Mathieu Chartier938a03b2014-01-16 15:10:31 -08002854 } else {
Ian Rogers1d54e732013-05-02 21:10:01 -07002855 // Print out how the object is live.
Mathieu Chartier938a03b2014-01-16 15:10:31 -08002856 if (bitmap->Test(obj)) {
Ian Rogers1d54e732013-05-02 21:10:01 -07002857 LOG(ERROR) << "Object " << obj << " found in live bitmap";
2858 }
Mathieu Chartier0f72e412013-09-06 16:40:01 -07002859 if (alloc_stack->Contains(const_cast<mirror::Object*>(obj))) {
Ian Rogers1d54e732013-05-02 21:10:01 -07002860 LOG(ERROR) << "Object " << obj << " found in allocation stack";
2861 }
Mathieu Chartier0f72e412013-09-06 16:40:01 -07002862 if (live_stack->Contains(const_cast<mirror::Object*>(obj))) {
Ian Rogers1d54e732013-05-02 21:10:01 -07002863 LOG(ERROR) << "Object " << obj << " found in live stack";
2864 }
Mathieu Chartier0f72e412013-09-06 16:40:01 -07002865 if (alloc_stack->Contains(const_cast<mirror::Object*>(ref))) {
2866 LOG(ERROR) << "Ref " << ref << " found in allocation stack";
2867 }
2868 if (live_stack->Contains(const_cast<mirror::Object*>(ref))) {
2869 LOG(ERROR) << "Ref " << ref << " found in live stack";
2870 }
Ian Rogers1d54e732013-05-02 21:10:01 -07002871 // Attempt to see if the card table missed the reference.
2872 ScanVisitor scan_visitor;
Ian Rogers13735952014-10-08 12:43:28 -07002873 uint8_t* byte_cover_begin = reinterpret_cast<uint8_t*>(card_table->AddrFromCard(card_addr));
Lei Li727b2942015-01-15 11:26:34 +08002874 card_table->Scan<false>(bitmap, byte_cover_begin,
2875 byte_cover_begin + accounting::CardTable::kCardSize, scan_visitor);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07002876 }
Mathieu Chartier938a03b2014-01-16 15:10:31 -08002877
2878 // Search to see if any of the roots reference our object.
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002879 RootMatchesObjectVisitor visitor1(obj);
2880 Runtime::Current()->VisitRoots(&visitor1);
Mathieu Chartier938a03b2014-01-16 15:10:31 -08002881 // Search to see if any of the roots reference our reference.
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002882 RootMatchesObjectVisitor visitor2(ref);
2883 Runtime::Current()->VisitRoots(&visitor2);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07002884 }
Mathieu Chartier8ab7e782014-05-19 16:55:27 -07002885 return false;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07002886 }
2887
Ian Rogers1d54e732013-05-02 21:10:01 -07002888 Heap* const heap_;
Mathieu Chartier8ab7e782014-05-19 16:55:27 -07002889 Atomic<size_t>* const fail_count_;
2890 const bool verify_referent_;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07002891};
2892
Ian Rogers1d54e732013-05-02 21:10:01 -07002893// Verify all references within an object, for use with HeapBitmap::Visit.
Mathieu Chartierfd678be2012-08-30 14:50:54 -07002894class VerifyObjectVisitor {
2895 public:
Roland Levillain3887c462015-08-12 18:15:42 +01002896 VerifyObjectVisitor(Heap* heap, Atomic<size_t>* fail_count, bool verify_referent)
Mathieu Chartiera4f6af92015-08-11 17:35:25 -07002897 : heap_(heap), fail_count_(fail_count), verify_referent_(verify_referent) {}
Mathieu Chartierfd678be2012-08-30 14:50:54 -07002898
Andreas Gampe351c4472017-07-12 19:32:55 -07002899 void operator()(mirror::Object* obj) REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogers1d54e732013-05-02 21:10:01 -07002900 // Note: we are verifying the references in obj but not obj itself, this is because obj must
2901 // be live or else how did we find it in the live bitmap?
Mathieu Chartier8ab7e782014-05-19 16:55:27 -07002902 VerifyReferenceVisitor visitor(heap_, fail_count_, verify_referent_);
Mathieu Chartier0f72e412013-09-06 16:40:01 -07002903 // The class doesn't count as a reference but we should verify it anyways.
Mathieu Chartier059ef3d2015-08-18 13:54:21 -07002904 obj->VisitReferences(visitor, visitor);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07002905 }
2906
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002907 void VerifyRoots() REQUIRES_SHARED(Locks::mutator_lock_) REQUIRES(!Locks::heap_bitmap_lock_) {
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002908 ReaderMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
2909 VerifyReferenceVisitor visitor(heap_, fail_count_, verify_referent_);
2910 Runtime::Current()->VisitRoots(&visitor);
2911 }
2912
Mathieu Chartier8ab7e782014-05-19 16:55:27 -07002913 size_t GetFailureCount() const {
Mathieu Chartiere9e55ac2014-05-21 17:48:25 -07002914 return fail_count_->LoadSequentiallyConsistent();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07002915 }
2916
2917 private:
Ian Rogers1d54e732013-05-02 21:10:01 -07002918 Heap* const heap_;
Mathieu Chartier8ab7e782014-05-19 16:55:27 -07002919 Atomic<size_t>* const fail_count_;
Mathieu Chartier78f7b4c2014-05-06 10:57:27 -07002920 const bool verify_referent_;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07002921};
2922
Mathieu Chartier9d156d52016-10-06 17:44:26 -07002923void Heap::PushOnAllocationStackWithInternalGC(Thread* self, ObjPtr<mirror::Object>* obj) {
Mathieu Chartierc1790162014-05-23 10:54:50 -07002924 // Slow path, the allocation stack push back must have already failed.
Mathieu Chartier9d156d52016-10-06 17:44:26 -07002925 DCHECK(!allocation_stack_->AtomicPushBack(obj->Ptr()));
Mathieu Chartierc1790162014-05-23 10:54:50 -07002926 do {
2927 // TODO: Add handle VerifyObject.
2928 StackHandleScope<1> hs(self);
Mathieu Chartier9d156d52016-10-06 17:44:26 -07002929 HandleWrapperObjPtr<mirror::Object> wrapper(hs.NewHandleWrapper(obj));
Hans Boehmd972b422017-09-11 12:57:00 -07002930 // Push our object into the reserve region of the allocation stack. This is only required due
Mathieu Chartierc1790162014-05-23 10:54:50 -07002931 // to heap verification requiring that roots are live (either in the live bitmap or in the
2932 // allocation stack).
Mathieu Chartier9d156d52016-10-06 17:44:26 -07002933 CHECK(allocation_stack_->AtomicPushBackIgnoreGrowthLimit(obj->Ptr()));
Mathieu Chartierc1790162014-05-23 10:54:50 -07002934 CollectGarbageInternal(collector::kGcTypeSticky, kGcCauseForAlloc, false);
Mathieu Chartier9d156d52016-10-06 17:44:26 -07002935 } while (!allocation_stack_->AtomicPushBack(obj->Ptr()));
Mathieu Chartierc1790162014-05-23 10:54:50 -07002936}
2937
Mathieu Chartier9d156d52016-10-06 17:44:26 -07002938void Heap::PushOnThreadLocalAllocationStackWithInternalGC(Thread* self,
2939 ObjPtr<mirror::Object>* obj) {
Mathieu Chartierc1790162014-05-23 10:54:50 -07002940 // Slow path, the allocation stack push back must have already failed.
Mathieu Chartier9d156d52016-10-06 17:44:26 -07002941 DCHECK(!self->PushOnThreadLocalAllocationStack(obj->Ptr()));
Mathieu Chartiercb535da2015-01-23 13:50:03 -08002942 StackReference<mirror::Object>* start_address;
2943 StackReference<mirror::Object>* end_address;
Mathieu Chartierc1790162014-05-23 10:54:50 -07002944 while (!allocation_stack_->AtomicBumpBack(kThreadLocalAllocationStackSize, &start_address,
2945 &end_address)) {
2946 // TODO: Add handle VerifyObject.
2947 StackHandleScope<1> hs(self);
Mathieu Chartier9d156d52016-10-06 17:44:26 -07002948 HandleWrapperObjPtr<mirror::Object> wrapper(hs.NewHandleWrapper(obj));
Mathieu Chartierc1790162014-05-23 10:54:50 -07002949 // Push our object into the reserve region of the allocaiton stack. This is only required due
2950 // to heap verification requiring that roots are live (either in the live bitmap or in the
2951 // allocation stack).
Mathieu Chartier9d156d52016-10-06 17:44:26 -07002952 CHECK(allocation_stack_->AtomicPushBackIgnoreGrowthLimit(obj->Ptr()));
Mathieu Chartierc1790162014-05-23 10:54:50 -07002953 // Push into the reserve allocation stack.
2954 CollectGarbageInternal(collector::kGcTypeSticky, kGcCauseForAlloc, false);
2955 }
2956 self->SetThreadLocalAllocationStack(start_address, end_address);
2957 // Retry on the new thread-local allocation stack.
Mathieu Chartier9d156d52016-10-06 17:44:26 -07002958 CHECK(self->PushOnThreadLocalAllocationStack(obj->Ptr())); // Must succeed.
Mathieu Chartierc1790162014-05-23 10:54:50 -07002959}
2960
Mathieu Chartierfd678be2012-08-30 14:50:54 -07002961// Must do this with mutators suspended since we are directly accessing the allocation stacks.
Mathieu Chartier8ab7e782014-05-19 16:55:27 -07002962size_t Heap::VerifyHeapReferences(bool verify_referents) {
Hiroshi Yamauchi1ed90612014-02-14 15:00:51 -08002963 Thread* self = Thread::Current();
2964 Locks::mutator_lock_->AssertExclusiveHeld(self);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07002965 // Lets sort our allocation stacks so that we can efficiently binary search them.
Ian Rogers1d54e732013-05-02 21:10:01 -07002966 allocation_stack_->Sort();
2967 live_stack_->Sort();
Hiroshi Yamauchi1ed90612014-02-14 15:00:51 -08002968 // Since we sorted the allocation stack content, need to revoke all
2969 // thread-local allocation stacks.
2970 RevokeAllThreadLocalAllocationStacks(self);
Mathieu Chartier8ab7e782014-05-19 16:55:27 -07002971 Atomic<size_t> fail_count_(0);
2972 VerifyObjectVisitor visitor(this, &fail_count_, verify_referents);
Mathieu Chartier0f72e412013-09-06 16:40:01 -07002973 // Verify objects in the allocation stack since these will be objects which were:
2974 // 1. Allocated prior to the GC (pre GC verification).
2975 // 2. Allocated during the GC (pre sweep GC verification).
Mathieu Chartier0f72e412013-09-06 16:40:01 -07002976 // We don't want to verify the objects in the live stack since they themselves may be
Mathieu Chartierfd678be2012-08-30 14:50:54 -07002977 // pointing to dead objects if they are not reachable.
Andreas Gampe351c4472017-07-12 19:32:55 -07002978 VisitObjectsPaused(visitor);
Mathieu Chartier590fee92013-09-13 13:46:47 -07002979 // Verify the roots:
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002980 visitor.VerifyRoots();
Mathieu Chartier8ab7e782014-05-19 16:55:27 -07002981 if (visitor.GetFailureCount() > 0) {
Mathieu Chartier0f72e412013-09-06 16:40:01 -07002982 // Dump mod-union tables.
Mathieu Chartier11409ae2013-09-23 11:49:36 -07002983 for (const auto& table_pair : mod_union_tables_) {
2984 accounting::ModUnionTable* mod_union_table = table_pair.second;
Andreas Gampe3fec9ac2016-09-13 10:47:28 -07002985 mod_union_table->Dump(LOG_STREAM(ERROR) << mod_union_table->GetName() << ": ");
Mathieu Chartier11409ae2013-09-23 11:49:36 -07002986 }
Hiroshi Yamauchi38e68e92014-03-07 13:59:08 -08002987 // Dump remembered sets.
2988 for (const auto& table_pair : remembered_sets_) {
2989 accounting::RememberedSet* remembered_set = table_pair.second;
Andreas Gampe3fec9ac2016-09-13 10:47:28 -07002990 remembered_set->Dump(LOG_STREAM(ERROR) << remembered_set->GetName() << ": ");
Hiroshi Yamauchi38e68e92014-03-07 13:59:08 -08002991 }
Andreas Gampe3fec9ac2016-09-13 10:47:28 -07002992 DumpSpaces(LOG_STREAM(ERROR));
Mathieu Chartierfd678be2012-08-30 14:50:54 -07002993 }
Mathieu Chartier8ab7e782014-05-19 16:55:27 -07002994 return visitor.GetFailureCount();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07002995}
2996
2997class VerifyReferenceCardVisitor {
2998 public:
2999 VerifyReferenceCardVisitor(Heap* heap, bool* failed)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07003000 REQUIRES_SHARED(Locks::mutator_lock_,
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07003001 Locks::heap_bitmap_lock_)
Ian Rogers1d54e732013-05-02 21:10:01 -07003002 : heap_(heap), failed_(failed) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07003003 }
3004
Mathieu Chartierda7c6502015-07-23 16:01:26 -07003005 // There is no card marks for native roots on a class.
3006 void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root ATTRIBUTE_UNUSED)
3007 const {}
3008 void VisitRoot(mirror::CompressedReference<mirror::Object>* root ATTRIBUTE_UNUSED) const {}
3009
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08003010 // TODO: Fix lock analysis to not use NO_THREAD_SAFETY_ANALYSIS, requires support for
3011 // annotalysis on visitors.
Mathieu Chartier407f7022014-02-18 14:37:05 -08003012 void operator()(mirror::Object* obj, MemberOffset offset, bool is_static) const
3013 NO_THREAD_SAFETY_ANALYSIS {
Ian Rogersb0fa5dc2014-04-28 16:47:08 -07003014 mirror::Object* ref = obj->GetFieldObject<mirror::Object>(offset);
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08003015 // Filter out class references since changing an object's class does not mark the card as dirty.
3016 // Also handles large objects, since the only reference they hold is a class reference.
Mathieu Chartier407f7022014-02-18 14:37:05 -08003017 if (ref != nullptr && !ref->IsClass()) {
Ian Rogers1d54e732013-05-02 21:10:01 -07003018 accounting::CardTable* card_table = heap_->GetCardTable();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07003019 // If the object is not dirty and it is referencing something in the live stack other than
3020 // class, then it must be on a dirty card.
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07003021 if (!card_table->AddrIsInCardTable(obj)) {
3022 LOG(ERROR) << "Object " << obj << " is not in the address range of the card table";
3023 *failed_ = true;
Mathieu Chartier2b82db42012-11-14 17:29:05 -08003024 } else if (!card_table->IsDirty(obj)) {
Mathieu Chartier938a03b2014-01-16 15:10:31 -08003025 // TODO: Check mod-union tables.
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08003026 // Card should be either kCardDirty if it got re-dirtied after we aged it, or
3027 // kCardDirty - 1 if it didnt get touched since we aged it.
Ian Rogers1d54e732013-05-02 21:10:01 -07003028 accounting::ObjectStack* live_stack = heap_->live_stack_.get();
Mathieu Chartier407f7022014-02-18 14:37:05 -08003029 if (live_stack->ContainsSorted(ref)) {
3030 if (live_stack->ContainsSorted(obj)) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07003031 LOG(ERROR) << "Object " << obj << " found in live stack";
3032 }
3033 if (heap_->GetLiveBitmap()->Test(obj)) {
3034 LOG(ERROR) << "Object " << obj << " found in live bitmap";
3035 }
David Sehr709b0702016-10-13 09:12:37 -07003036 LOG(ERROR) << "Object " << obj << " " << mirror::Object::PrettyTypeOf(obj)
3037 << " references " << ref << " " << mirror::Object::PrettyTypeOf(ref)
3038 << " in live stack";
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07003039
3040 // Print which field of the object is dead.
3041 if (!obj->IsObjectArray()) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08003042 mirror::Class* klass = is_static ? obj->AsClass() : obj->GetClass();
Mathieu Chartierc7853442015-03-27 14:35:38 -07003043 CHECK(klass != nullptr);
Mathieu Chartierc0fe56a2015-08-11 13:01:23 -07003044 for (ArtField& field : (is_static ? klass->GetSFields() : klass->GetIFields())) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003045 if (field.GetOffset().Int32Value() == offset.Int32Value()) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07003046 LOG(ERROR) << (is_static ? "Static " : "") << "field in the live stack is "
David Sehr709b0702016-10-13 09:12:37 -07003047 << field.PrettyField();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07003048 break;
3049 }
3050 }
3051 } else {
Ian Rogersef7d42f2014-01-06 12:55:46 -08003052 mirror::ObjectArray<mirror::Object>* object_array =
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003053 obj->AsObjectArray<mirror::Object>();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07003054 for (int32_t i = 0; i < object_array->GetLength(); ++i) {
3055 if (object_array->Get(i) == ref) {
3056 LOG(ERROR) << (is_static ? "Static " : "") << "obj[" << i << "] = ref";
3057 }
3058 }
3059 }
3060
3061 *failed_ = true;
3062 }
3063 }
3064 }
3065 }
3066
3067 private:
Ian Rogers1d54e732013-05-02 21:10:01 -07003068 Heap* const heap_;
3069 bool* const failed_;
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07003070};
3071
3072class VerifyLiveStackReferences {
3073 public:
Brian Carlstrom93ba8932013-07-17 21:31:49 -07003074 explicit VerifyLiveStackReferences(Heap* heap)
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07003075 : heap_(heap),
Brian Carlstrom93ba8932013-07-17 21:31:49 -07003076 failed_(false) {}
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07003077
Mathieu Chartier11409ae2013-09-23 11:49:36 -07003078 void operator()(mirror::Object* obj) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07003079 REQUIRES_SHARED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07003080 VerifyReferenceCardVisitor visitor(heap_, const_cast<bool*>(&failed_));
Mathieu Chartier059ef3d2015-08-18 13:54:21 -07003081 obj->VisitReferences(visitor, VoidFunctor());
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07003082 }
3083
3084 bool Failed() const {
3085 return failed_;
3086 }
3087
3088 private:
Ian Rogers1d54e732013-05-02 21:10:01 -07003089 Heap* const heap_;
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07003090 bool failed_;
3091};
3092
3093bool Heap::VerifyMissingCardMarks() {
Hiroshi Yamauchi1ed90612014-02-14 15:00:51 -08003094 Thread* self = Thread::Current();
3095 Locks::mutator_lock_->AssertExclusiveHeld(self);
Mathieu Chartier2b82db42012-11-14 17:29:05 -08003096 // We need to sort the live stack since we binary search it.
Ian Rogers1d54e732013-05-02 21:10:01 -07003097 live_stack_->Sort();
Hiroshi Yamauchi1ed90612014-02-14 15:00:51 -08003098 // Since we sorted the allocation stack content, need to revoke all
3099 // thread-local allocation stacks.
3100 RevokeAllThreadLocalAllocationStacks(self);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07003101 VerifyLiveStackReferences visitor(this);
3102 GetLiveBitmap()->Visit(visitor);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07003103 // We can verify objects in the live stack since none of these should reference dead objects.
Mathieu Chartiercb535da2015-01-23 13:50:03 -08003104 for (auto* it = live_stack_->Begin(); it != live_stack_->End(); ++it) {
3105 if (!kUseThreadLocalAllocationStack || it->AsMirrorPtr() != nullptr) {
3106 visitor(it->AsMirrorPtr());
Hiroshi Yamauchif5b0e202014-02-11 17:02:22 -08003107 }
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07003108 }
Mathieu Chartier4c13a3f2014-07-14 14:57:16 -07003109 return !visitor.Failed();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07003110}
3111
Mathieu Chartiera4f6af92015-08-11 17:35:25 -07003112void Heap::SwapStacks() {
Hiroshi Yamauchif5b0e202014-02-11 17:02:22 -08003113 if (kUseThreadLocalAllocationStack) {
3114 live_stack_->AssertAllZero();
3115 }
Mathieu Chartierd22d5482012-11-06 17:14:12 -08003116 allocation_stack_.swap(live_stack_);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07003117}
3118
Hiroshi Yamauchif5b0e202014-02-11 17:02:22 -08003119void Heap::RevokeAllThreadLocalAllocationStacks(Thread* self) {
Hiroshi Yamauchif5b0e202014-02-11 17:02:22 -08003120 // This must be called only during the pause.
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003121 DCHECK(Locks::mutator_lock_->IsExclusiveHeld(self));
Hiroshi Yamauchif5b0e202014-02-11 17:02:22 -08003122 MutexLock mu(self, *Locks::runtime_shutdown_lock_);
3123 MutexLock mu2(self, *Locks::thread_list_lock_);
3124 std::list<Thread*> thread_list = Runtime::Current()->GetThreadList()->GetList();
3125 for (Thread* t : thread_list) {
3126 t->RevokeThreadLocalAllocationStack();
3127 }
3128}
3129
Ian Rogers68d8b422014-07-17 11:09:10 -07003130void Heap::AssertThreadLocalBuffersAreRevoked(Thread* thread) {
3131 if (kIsDebugBuild) {
3132 if (rosalloc_space_ != nullptr) {
3133 rosalloc_space_->AssertThreadLocalBuffersAreRevoked(thread);
3134 }
3135 if (bump_pointer_space_ != nullptr) {
3136 bump_pointer_space_->AssertThreadLocalBuffersAreRevoked(thread);
3137 }
3138 }
3139}
3140
Hiroshi Yamauchic93c5302014-03-20 16:15:37 -07003141void Heap::AssertAllBumpPointerSpaceThreadLocalBuffersAreRevoked() {
3142 if (kIsDebugBuild) {
3143 if (bump_pointer_space_ != nullptr) {
3144 bump_pointer_space_->AssertAllThreadLocalBuffersAreRevoked();
3145 }
3146 }
3147}
3148
Mathieu Chartier11409ae2013-09-23 11:49:36 -07003149accounting::ModUnionTable* Heap::FindModUnionTableFromSpace(space::Space* space) {
3150 auto it = mod_union_tables_.find(space);
3151 if (it == mod_union_tables_.end()) {
3152 return nullptr;
3153 }
3154 return it->second;
3155}
3156
Hiroshi Yamauchi38e68e92014-03-07 13:59:08 -08003157accounting::RememberedSet* Heap::FindRememberedSetFromSpace(space::Space* space) {
3158 auto it = remembered_sets_.find(space);
3159 if (it == remembered_sets_.end()) {
3160 return nullptr;
3161 }
3162 return it->second;
3163}
3164
Mathieu Chartiera4f6af92015-08-11 17:35:25 -07003165void Heap::ProcessCards(TimingLogger* timings,
3166 bool use_rem_sets,
3167 bool process_alloc_space_cards,
Lei Li4add3b42015-01-15 11:55:26 +08003168 bool clear_alloc_space_cards) {
Mathieu Chartierf5997b42014-06-20 10:37:54 -07003169 TimingLogger::ScopedTiming t(__FUNCTION__, timings);
Ian Rogers1d54e732013-05-02 21:10:01 -07003170 // Clear cards and keep track of cards cleared in the mod-union table.
Mathieu Chartier02e25112013-08-14 16:14:24 -07003171 for (const auto& space : continuous_spaces_) {
Mathieu Chartier11409ae2013-09-23 11:49:36 -07003172 accounting::ModUnionTable* table = FindModUnionTableFromSpace(space);
Hiroshi Yamauchi38e68e92014-03-07 13:59:08 -08003173 accounting::RememberedSet* rem_set = FindRememberedSetFromSpace(space);
Mathieu Chartier11409ae2013-09-23 11:49:36 -07003174 if (table != nullptr) {
3175 const char* name = space->IsZygoteSpace() ? "ZygoteModUnionClearCards" :
3176 "ImageModUnionClearCards";
Andreas Gampe277ccbd2014-11-03 21:36:10 -08003177 TimingLogger::ScopedTiming t2(name, timings);
Mathieu Chartier6e6078a2016-10-24 15:45:41 -07003178 table->ProcessCards();
Hiroshi Yamauchi38e68e92014-03-07 13:59:08 -08003179 } else if (use_rem_sets && rem_set != nullptr) {
3180 DCHECK(collector::SemiSpace::kUseRememberedSet && collector_type_ == kCollectorTypeGSS)
3181 << static_cast<int>(collector_type_);
Andreas Gampe277ccbd2014-11-03 21:36:10 -08003182 TimingLogger::ScopedTiming t2("AllocSpaceRemSetClearCards", timings);
Hiroshi Yamauchi38e68e92014-03-07 13:59:08 -08003183 rem_set->ClearCards();
Lei Li4add3b42015-01-15 11:55:26 +08003184 } else if (process_alloc_space_cards) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08003185 TimingLogger::ScopedTiming t2("AllocSpaceClearCards", timings);
Lei Li4add3b42015-01-15 11:55:26 +08003186 if (clear_alloc_space_cards) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08003187 uint8_t* end = space->End();
3188 if (space->IsImageSpace()) {
3189 // Image space end is the end of the mirror objects, it is not necessarily page or card
3190 // aligned. Align up so that the check in ClearCardRange does not fail.
3191 end = AlignUp(end, accounting::CardTable::kCardSize);
3192 }
3193 card_table_->ClearCardRange(space->Begin(), end);
Lei Li4add3b42015-01-15 11:55:26 +08003194 } else {
3195 // No mod union table for the AllocSpace. Age the cards so that the GC knows that these
3196 // cards were dirty before the GC started.
3197 // TODO: Need to use atomic for the case where aged(cleaning thread) -> dirty(other thread)
3198 // -> clean(cleaning thread).
3199 // The races are we either end up with: Aged card, unaged card. Since we have the
3200 // checkpoint roots and then we scan / update mod union tables after. We will always
3201 // scan either card. If we end up with the non aged card, we scan it it in the pause.
3202 card_table_->ModifyCardsAtomic(space->Begin(), space->End(), AgeCardVisitor(),
3203 VoidFunctor());
3204 }
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07003205 }
3206 }
3207}
3208
Mathieu Chartier97509952015-07-13 14:35:43 -07003209struct IdentityMarkHeapReferenceVisitor : public MarkObjectVisitor {
3210 virtual mirror::Object* MarkObject(mirror::Object* obj) OVERRIDE {
3211 return obj;
3212 }
Hiroshi Yamauchi057d9772017-02-17 15:33:23 -08003213 virtual void MarkHeapReference(mirror::HeapReference<mirror::Object>*, bool) OVERRIDE {
Mathieu Chartier97509952015-07-13 14:35:43 -07003214 }
3215};
Mathieu Chartier11409ae2013-09-23 11:49:36 -07003216
Mathieu Chartier6f365cc2014-04-23 12:42:27 -07003217void Heap::PreGcVerificationPaused(collector::GarbageCollector* gc) {
3218 Thread* const self = Thread::Current();
Mathieu Chartier10fb83a2014-06-15 15:15:43 -07003219 TimingLogger* const timings = current_gc_iteration_.GetTimings();
Mathieu Chartierf5997b42014-06-20 10:37:54 -07003220 TimingLogger::ScopedTiming t(__FUNCTION__, timings);
Mathieu Chartier2b82db42012-11-14 17:29:05 -08003221 if (verify_pre_gc_heap_) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08003222 TimingLogger::ScopedTiming t2("(Paused)PreGcVerifyHeapReferences", timings);
Mathieu Chartier8ab7e782014-05-19 16:55:27 -07003223 size_t failures = VerifyHeapReferences();
3224 if (failures > 0) {
3225 LOG(FATAL) << "Pre " << gc->GetName() << " heap verification failed with " << failures
3226 << " failures";
Mathieu Chartier2b82db42012-11-14 17:29:05 -08003227 }
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08003228 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -08003229 // Check that all objects which reference things in the live stack are on dirty cards.
3230 if (verify_missing_card_marks_) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08003231 TimingLogger::ScopedTiming t2("(Paused)PreGcVerifyMissingCardMarks", timings);
Mathieu Chartier6f365cc2014-04-23 12:42:27 -07003232 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartiera4f6af92015-08-11 17:35:25 -07003233 SwapStacks();
Mathieu Chartier6f365cc2014-04-23 12:42:27 -07003234 // Sort the live stack so that we can quickly binary search it later.
Mathieu Chartier4c13a3f2014-07-14 14:57:16 -07003235 CHECK(VerifyMissingCardMarks()) << "Pre " << gc->GetName()
3236 << " missing card mark verification failed\n" << DumpSpaces();
Mathieu Chartiera4f6af92015-08-11 17:35:25 -07003237 SwapStacks();
Mathieu Chartier2b82db42012-11-14 17:29:05 -08003238 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -08003239 if (verify_mod_union_table_) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08003240 TimingLogger::ScopedTiming t2("(Paused)PreGcVerifyModUnionTables", timings);
Mathieu Chartier2b82db42012-11-14 17:29:05 -08003241 ReaderMutexLock reader_lock(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier11409ae2013-09-23 11:49:36 -07003242 for (const auto& table_pair : mod_union_tables_) {
3243 accounting::ModUnionTable* mod_union_table = table_pair.second;
Mathieu Chartier97509952015-07-13 14:35:43 -07003244 IdentityMarkHeapReferenceVisitor visitor;
3245 mod_union_table->UpdateAndMarkReferences(&visitor);
Mathieu Chartier11409ae2013-09-23 11:49:36 -07003246 mod_union_table->Verify();
3247 }
Mathieu Chartier6f365cc2014-04-23 12:42:27 -07003248 }
3249}
3250
3251void Heap::PreGcVerification(collector::GarbageCollector* gc) {
Mathieu Chartier0651d412014-04-29 14:37:57 -07003252 if (verify_pre_gc_heap_ || verify_missing_card_marks_ || verify_mod_union_table_) {
Andreas Gampe4934eb12017-01-30 13:15:26 -08003253 collector::GarbageCollector::ScopedPause pause(gc, false);
Mathieu Chartier6f365cc2014-04-23 12:42:27 -07003254 PreGcVerificationPaused(gc);
3255 }
3256}
3257
Mathieu Chartiera4f6af92015-08-11 17:35:25 -07003258void Heap::PrePauseRosAllocVerification(collector::GarbageCollector* gc ATTRIBUTE_UNUSED) {
Mathieu Chartier6f365cc2014-04-23 12:42:27 -07003259 // TODO: Add a new runtime option for this?
3260 if (verify_pre_gc_rosalloc_) {
Mathieu Chartier10fb83a2014-06-15 15:15:43 -07003261 RosAllocVerification(current_gc_iteration_.GetTimings(), "PreGcRosAllocVerification");
Mathieu Chartier2b82db42012-11-14 17:29:05 -08003262 }
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08003263}
3264
Ian Rogers1d54e732013-05-02 21:10:01 -07003265void Heap::PreSweepingGcVerification(collector::GarbageCollector* gc) {
Mathieu Chartier6f365cc2014-04-23 12:42:27 -07003266 Thread* const self = Thread::Current();
Mathieu Chartier10fb83a2014-06-15 15:15:43 -07003267 TimingLogger* const timings = current_gc_iteration_.GetTimings();
Mathieu Chartierf5997b42014-06-20 10:37:54 -07003268 TimingLogger::ScopedTiming t(__FUNCTION__, timings);
Mathieu Chartier2b82db42012-11-14 17:29:05 -08003269 // Called before sweeping occurs since we want to make sure we are not going so reclaim any
3270 // reachable objects.
Mathieu Chartier6f365cc2014-04-23 12:42:27 -07003271 if (verify_pre_sweeping_heap_) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08003272 TimingLogger::ScopedTiming t2("(Paused)PostSweepingVerifyHeapReferences", timings);
Ian Rogers1d54e732013-05-02 21:10:01 -07003273 CHECK_NE(self->GetState(), kRunnable);
Hiroshi Yamauchi0c8c3032015-01-16 16:54:35 -08003274 {
3275 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
3276 // Swapping bound bitmaps does nothing.
3277 gc->SwapBitmaps();
3278 }
Mathieu Chartier78f7b4c2014-05-06 10:57:27 -07003279 // Pass in false since concurrent reference processing can mean that the reference referents
3280 // may point to dead objects at the point which PreSweepingGcVerification is called.
Mathieu Chartier8ab7e782014-05-19 16:55:27 -07003281 size_t failures = VerifyHeapReferences(false);
3282 if (failures > 0) {
3283 LOG(FATAL) << "Pre sweeping " << gc->GetName() << " GC verification failed with " << failures
3284 << " failures";
Mathieu Chartier6f365cc2014-04-23 12:42:27 -07003285 }
Hiroshi Yamauchi0c8c3032015-01-16 16:54:35 -08003286 {
3287 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
3288 gc->SwapBitmaps();
3289 }
Mathieu Chartier6f365cc2014-04-23 12:42:27 -07003290 }
3291 if (verify_pre_sweeping_rosalloc_) {
3292 RosAllocVerification(timings, "PreSweepingRosAllocVerification");
3293 }
3294}
3295
3296void Heap::PostGcVerificationPaused(collector::GarbageCollector* gc) {
3297 // Only pause if we have to do some verification.
3298 Thread* const self = Thread::Current();
Mathieu Chartier10fb83a2014-06-15 15:15:43 -07003299 TimingLogger* const timings = GetCurrentGcIteration()->GetTimings();
Mathieu Chartierf5997b42014-06-20 10:37:54 -07003300 TimingLogger::ScopedTiming t(__FUNCTION__, timings);
Mathieu Chartier6f365cc2014-04-23 12:42:27 -07003301 if (verify_system_weaks_) {
3302 ReaderMutexLock mu2(self, *Locks::heap_bitmap_lock_);
3303 collector::MarkSweep* mark_sweep = down_cast<collector::MarkSweep*>(gc);
3304 mark_sweep->VerifySystemWeaks();
3305 }
3306 if (verify_post_gc_rosalloc_) {
Mathieu Chartierf5997b42014-06-20 10:37:54 -07003307 RosAllocVerification(timings, "(Paused)PostGcRosAllocVerification");
Mathieu Chartier6f365cc2014-04-23 12:42:27 -07003308 }
3309 if (verify_post_gc_heap_) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08003310 TimingLogger::ScopedTiming t2("(Paused)PostGcVerifyHeapReferences", timings);
Mathieu Chartier8ab7e782014-05-19 16:55:27 -07003311 size_t failures = VerifyHeapReferences();
3312 if (failures > 0) {
3313 LOG(FATAL) << "Pre " << gc->GetName() << " heap verification failed with " << failures
3314 << " failures";
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003315 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003316 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -08003317}
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003318
Ian Rogers1d54e732013-05-02 21:10:01 -07003319void Heap::PostGcVerification(collector::GarbageCollector* gc) {
Mathieu Chartier6f365cc2014-04-23 12:42:27 -07003320 if (verify_system_weaks_ || verify_post_gc_rosalloc_ || verify_post_gc_heap_) {
Andreas Gampe4934eb12017-01-30 13:15:26 -08003321 collector::GarbageCollector::ScopedPause pause(gc, false);
Mathieu Chartierd35326f2014-08-18 15:02:59 -07003322 PostGcVerificationPaused(gc);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003323 }
Carl Shapiro69759ea2011-07-21 18:13:35 -07003324}
3325
Mathieu Chartier6f365cc2014-04-23 12:42:27 -07003326void Heap::RosAllocVerification(TimingLogger* timings, const char* name) {
Mathieu Chartierf5997b42014-06-20 10:37:54 -07003327 TimingLogger::ScopedTiming t(name, timings);
Mathieu Chartier6f365cc2014-04-23 12:42:27 -07003328 for (const auto& space : continuous_spaces_) {
3329 if (space->IsRosAllocSpace()) {
3330 VLOG(heap) << name << " : " << space->GetName();
3331 space->AsRosAllocSpace()->Verify();
Hiroshi Yamauchia4adbfd2014-02-04 18:12:17 -08003332 }
3333 }
3334}
3335
Mathieu Chartier89a201e2014-05-02 10:27:26 -07003336collector::GcType Heap::WaitForGcToComplete(GcCause cause, Thread* self) {
Mathieu Chartiercaa82d62014-02-02 16:51:17 -08003337 ScopedThreadStateChange tsc(self, kWaitingForGcToComplete);
Mathieu Chartier590fee92013-09-13 13:46:47 -07003338 MutexLock mu(self, *gc_complete_lock_);
Mathieu Chartier89a201e2014-05-02 10:27:26 -07003339 return WaitForGcToCompleteLocked(cause, self);
Mathieu Chartier590fee92013-09-13 13:46:47 -07003340}
3341
Mathieu Chartier89a201e2014-05-02 10:27:26 -07003342collector::GcType Heap::WaitForGcToCompleteLocked(GcCause cause, Thread* self) {
Ian Rogers1d54e732013-05-02 21:10:01 -07003343 collector::GcType last_gc_type = collector::kGcTypeNone;
Mathieu Chartier40112dd2017-06-26 17:49:09 -07003344 GcCause last_gc_cause = kGcCauseNone;
Mathieu Chartier590fee92013-09-13 13:46:47 -07003345 uint64_t wait_start = NanoTime();
Mathieu Chartierd5a89ee2014-01-31 09:55:13 -08003346 while (collector_type_running_ != kCollectorTypeNone) {
Hiroshi Yamauchia1c9f012015-04-02 10:18:12 -07003347 if (self != task_processor_->GetRunningThread()) {
3348 // The current thread is about to wait for a currently running
3349 // collection to finish. If the waiting thread is not the heap
3350 // task daemon thread, the currently running collection is
3351 // considered as a blocking GC.
3352 running_collection_is_blocking_ = true;
3353 VLOG(gc) << "Waiting for a blocking GC " << cause;
3354 }
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08003355 ScopedTrace trace("GC: Wait For Completion");
Mathieu Chartier590fee92013-09-13 13:46:47 -07003356 // We must wait, change thread state then sleep on gc_complete_cond_;
3357 gc_complete_cond_->Wait(self);
3358 last_gc_type = last_gc_type_;
Mathieu Chartier40112dd2017-06-26 17:49:09 -07003359 last_gc_cause = last_gc_cause_;
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07003360 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07003361 uint64_t wait_time = NanoTime() - wait_start;
3362 total_wait_time_ += wait_time;
3363 if (wait_time > long_pause_log_threshold_) {
Mathieu Chartier40112dd2017-06-26 17:49:09 -07003364 LOG(INFO) << "WaitForGcToComplete blocked " << cause << " on " << last_gc_cause << " for "
3365 << PrettyDuration(wait_time);
Mathieu Chartier590fee92013-09-13 13:46:47 -07003366 }
Hiroshi Yamauchia1c9f012015-04-02 10:18:12 -07003367 if (self != task_processor_->GetRunningThread()) {
3368 // The current thread is about to run a collection. If the thread
3369 // is not the heap task daemon thread, it's considered as a
3370 // blocking GC (i.e., blocking itself).
3371 running_collection_is_blocking_ = true;
Mathieu Chartierb166f412017-04-25 16:31:20 -07003372 // Don't log fake "GC" types that are only used for debugger or hidden APIs. If we log these,
3373 // it results in log spam. kGcCauseExplicit is already logged in LogGC, so avoid it here too.
3374 if (cause == kGcCauseForAlloc ||
3375 cause == kGcCauseForNativeAlloc ||
Richard Uhlerda1da8a2017-05-16 13:37:32 +00003376 cause == kGcCauseForNativeAllocBlocking ||
Mathieu Chartierb166f412017-04-25 16:31:20 -07003377 cause == kGcCauseDisableMovingGc) {
3378 VLOG(gc) << "Starting a blocking GC " << cause;
3379 }
Hiroshi Yamauchia1c9f012015-04-02 10:18:12 -07003380 }
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07003381 return last_gc_type;
Carl Shapiro69759ea2011-07-21 18:13:35 -07003382}
3383
Elliott Hughesc967f782012-04-16 10:23:15 -07003384void Heap::DumpForSigQuit(std::ostream& os) {
Ian Rogers1d54e732013-05-02 21:10:01 -07003385 os << "Heap: " << GetPercentFree() << "% free, " << PrettySize(GetBytesAllocated()) << "/"
Mathieu Chartier2fde5332012-09-14 14:51:54 -07003386 << PrettySize(GetTotalMemory()) << "; " << GetObjectsAllocated() << " objects\n";
Elliott Hughes8b788fe2013-04-17 15:57:01 -07003387 DumpGcPerformanceInfo(os);
Elliott Hughesc967f782012-04-16 10:23:15 -07003388}
3389
3390size_t Heap::GetPercentFree() {
Mathieu Chartierd30e1d62014-06-09 13:25:22 -07003391 return static_cast<size_t>(100.0f * static_cast<float>(GetFreeMemory()) / max_allowed_footprint_);
Elliott Hughesc967f782012-04-16 10:23:15 -07003392}
3393
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003394void Heap::SetIdealFootprint(size_t max_allowed_footprint) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07003395 if (max_allowed_footprint > GetMaxMemory()) {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07003396 VLOG(gc) << "Clamp target GC heap from " << PrettySize(max_allowed_footprint) << " to "
Mathieu Chartier2fde5332012-09-14 14:51:54 -07003397 << PrettySize(GetMaxMemory());
3398 max_allowed_footprint = GetMaxMemory();
3399 }
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -07003400 max_allowed_footprint_ = max_allowed_footprint;
Shih-wei Liao8c2f6412011-10-03 22:58:14 -07003401}
3402
Mathieu Chartier0795f232016-09-27 18:43:30 -07003403bool Heap::IsMovableObject(ObjPtr<mirror::Object> obj) const {
Mathieu Chartier590fee92013-09-13 13:46:47 -07003404 if (kMovingCollector) {
Mathieu Chartier1cc62e42016-10-03 18:01:28 -07003405 space::Space* space = FindContinuousSpaceFromObject(obj.Ptr(), true);
Mathieu Chartier31f44142014-04-08 14:40:03 -07003406 if (space != nullptr) {
3407 // TODO: Check large object?
3408 return space->CanMoveObjects();
Mathieu Chartier590fee92013-09-13 13:46:47 -07003409 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07003410 }
3411 return false;
3412}
3413
Mathieu Chartierafe49982014-03-27 10:55:04 -07003414collector::GarbageCollector* Heap::FindCollectorByGcType(collector::GcType gc_type) {
3415 for (const auto& collector : garbage_collectors_) {
3416 if (collector->GetCollectorType() == collector_type_ &&
3417 collector->GetGcType() == gc_type) {
3418 return collector;
3419 }
3420 }
3421 return nullptr;
3422}
3423
Mathieu Chartier2f8da3e2014-04-15 15:37:02 -07003424double Heap::HeapGrowthMultiplier() const {
3425 // If we don't care about pause times we are background, so return 1.0.
Mathieu Chartier11c273d2017-10-15 20:54:45 -07003426 if (!CareAboutPauseTimes()) {
Mathieu Chartier2f8da3e2014-04-15 15:37:02 -07003427 return 1.0;
3428 }
3429 return foreground_heap_growth_multiplier_;
3430}
3431
Mathieu Chartiere2c2f6e2014-12-16 18:49:31 -08003432void Heap::GrowForUtilization(collector::GarbageCollector* collector_ran,
3433 uint64_t bytes_allocated_before_gc) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07003434 // We know what our utilization is at this moment.
3435 // This doesn't actually resize any memory. It just lets the heap grow more when necessary.
Mathieu Chartier2f8da3e2014-04-15 15:37:02 -07003436 const uint64_t bytes_allocated = GetBytesAllocated();
Mathieu Chartier34afcde2017-06-30 15:31:11 -07003437 // Trace the new heap size after the GC is finished.
3438 TraceHeapSize(bytes_allocated);
Mathieu Chartier2f8da3e2014-04-15 15:37:02 -07003439 uint64_t target_size;
Mathieu Chartierafe49982014-03-27 10:55:04 -07003440 collector::GcType gc_type = collector_ran->GetGcType();
Mathieu Chartiere2c2f6e2014-12-16 18:49:31 -08003441 const double multiplier = HeapGrowthMultiplier(); // Use the multiplier to grow more for
3442 // foreground.
Hiroshi Yamauchi6711cd82017-02-23 15:11:56 -08003443 const uint64_t adjusted_min_free = static_cast<uint64_t>(min_free_ * multiplier);
3444 const uint64_t adjusted_max_free = static_cast<uint64_t>(max_free_ * multiplier);
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -07003445 if (gc_type != collector::kGcTypeSticky) {
3446 // Grow the heap for non sticky GC.
Mathieu Chartiere2c2f6e2014-12-16 18:49:31 -08003447 ssize_t delta = bytes_allocated / GetTargetHeapUtilization() - bytes_allocated;
Mathieu Chartier2f8da3e2014-04-15 15:37:02 -07003448 CHECK_GE(delta, 0);
3449 target_size = bytes_allocated + delta * multiplier;
Mathieu Chartiere2c2f6e2014-12-16 18:49:31 -08003450 target_size = std::min(target_size, bytes_allocated + adjusted_max_free);
3451 target_size = std::max(target_size, bytes_allocated + adjusted_min_free);
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -07003452 next_gc_type_ = collector::kGcTypeSticky;
3453 } else {
Richard Uhlercaaa2b02017-02-01 09:54:17 +00003454 collector::GcType non_sticky_gc_type = NonStickyGcType();
Mathieu Chartierafe49982014-03-27 10:55:04 -07003455 // Find what the next non sticky collector will be.
3456 collector::GarbageCollector* non_sticky_collector = FindCollectorByGcType(non_sticky_gc_type);
3457 // If the throughput of the current sticky GC >= throughput of the non sticky collector, then
3458 // do another sticky collection next.
3459 // We also check that the bytes allocated aren't over the footprint limit in order to prevent a
3460 // pathological case where dead objects which aren't reclaimed by sticky could get accumulated
3461 // if the sticky GC throughput always remained >= the full/partial throughput.
Mathieu Chartier10fb83a2014-06-15 15:15:43 -07003462 if (current_gc_iteration_.GetEstimatedThroughput() * kStickyGcThroughputAdjustment >=
Mathieu Chartierafe49982014-03-27 10:55:04 -07003463 non_sticky_collector->GetEstimatedMeanThroughput() &&
Mathieu Chartier10fb83a2014-06-15 15:15:43 -07003464 non_sticky_collector->NumberOfIterations() > 0 &&
Mathieu Chartierafe49982014-03-27 10:55:04 -07003465 bytes_allocated <= max_allowed_footprint_) {
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -07003466 next_gc_type_ = collector::kGcTypeSticky;
3467 } else {
Mathieu Chartierafe49982014-03-27 10:55:04 -07003468 next_gc_type_ = non_sticky_gc_type;
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -07003469 }
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -07003470 // If we have freed enough memory, shrink the heap back down.
Mathieu Chartiere2c2f6e2014-12-16 18:49:31 -08003471 if (bytes_allocated + adjusted_max_free < max_allowed_footprint_) {
3472 target_size = bytes_allocated + adjusted_max_free;
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -07003473 } else {
Mathieu Chartier2f8da3e2014-04-15 15:37:02 -07003474 target_size = std::max(bytes_allocated, static_cast<uint64_t>(max_allowed_footprint_));
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -07003475 }
3476 }
Mathieu Chartier2775ee42013-08-20 17:43:47 -07003477 if (!ignore_max_footprint_) {
3478 SetIdealFootprint(target_size);
Hiroshi Yamauchi3e417802014-03-20 12:03:02 -07003479 if (IsGcConcurrent()) {
Mathieu Chartiere2c2f6e2014-12-16 18:49:31 -08003480 const uint64_t freed_bytes = current_gc_iteration_.GetFreedBytes() +
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07003481 current_gc_iteration_.GetFreedLargeObjectBytes() +
3482 current_gc_iteration_.GetFreedRevokeBytes();
Mathieu Chartiere2c2f6e2014-12-16 18:49:31 -08003483 // Bytes allocated will shrink by freed_bytes after the GC runs, so if we want to figure out
3484 // how many bytes were allocated during the GC we need to add freed_bytes back on.
3485 CHECK_GE(bytes_allocated + freed_bytes, bytes_allocated_before_gc);
3486 const uint64_t bytes_allocated_during_gc = bytes_allocated + freed_bytes -
3487 bytes_allocated_before_gc;
Mathieu Chartier2775ee42013-08-20 17:43:47 -07003488 // Calculate when to perform the next ConcurrentGC.
Mathieu Chartier2775ee42013-08-20 17:43:47 -07003489 // Calculate the estimated GC duration.
Mathieu Chartier10fb83a2014-06-15 15:15:43 -07003490 const double gc_duration_seconds = NsToMs(current_gc_iteration_.GetDurationNs()) / 1000.0;
Mathieu Chartier2775ee42013-08-20 17:43:47 -07003491 // Estimate how many remaining bytes we will have when we need to start the next GC.
Mathieu Chartiere2c2f6e2014-12-16 18:49:31 -08003492 size_t remaining_bytes = bytes_allocated_during_gc * gc_duration_seconds;
Mathieu Chartier74762802014-01-24 10:21:35 -08003493 remaining_bytes = std::min(remaining_bytes, kMaxConcurrentRemainingBytes);
Mathieu Chartier2775ee42013-08-20 17:43:47 -07003494 remaining_bytes = std::max(remaining_bytes, kMinConcurrentRemainingBytes);
3495 if (UNLIKELY(remaining_bytes > max_allowed_footprint_)) {
3496 // A never going to happen situation that from the estimated allocation rate we will exceed
3497 // the applications entire footprint with the given estimated allocation rate. Schedule
Mathieu Chartier74762802014-01-24 10:21:35 -08003498 // another GC nearly straight away.
3499 remaining_bytes = kMinConcurrentRemainingBytes;
Mathieu Chartier2775ee42013-08-20 17:43:47 -07003500 }
Mathieu Chartier74762802014-01-24 10:21:35 -08003501 DCHECK_LE(remaining_bytes, max_allowed_footprint_);
Mathieu Chartierdd162fb2014-08-06 17:06:33 -07003502 DCHECK_LE(max_allowed_footprint_, GetMaxMemory());
Mathieu Chartier74762802014-01-24 10:21:35 -08003503 // Start a concurrent GC when we get close to the estimated remaining bytes. When the
3504 // allocation rate is very high, remaining_bytes could tell us that we should start a GC
3505 // right away.
Mathieu Chartier2f8da3e2014-04-15 15:37:02 -07003506 concurrent_start_bytes_ = std::max(max_allowed_footprint_ - remaining_bytes,
3507 static_cast<size_t>(bytes_allocated));
Mathieu Chartier65db8802012-11-20 12:36:46 -08003508 }
Mathieu Chartier65db8802012-11-20 12:36:46 -08003509 }
Carl Shapiro69759ea2011-07-21 18:13:35 -07003510}
3511
Mathieu Chartier379d09f2015-01-08 11:28:13 -08003512void Heap::ClampGrowthLimit() {
Mathieu Chartierddac4232015-04-02 10:08:03 -07003513 // Use heap bitmap lock to guard against races with BindLiveToMarkBitmap.
Mathieu Chartiera9d82fe2016-01-25 20:06:11 -08003514 ScopedObjectAccess soa(Thread::Current());
3515 WriterMutexLock mu(soa.Self(), *Locks::heap_bitmap_lock_);
Mathieu Chartier379d09f2015-01-08 11:28:13 -08003516 capacity_ = growth_limit_;
3517 for (const auto& space : continuous_spaces_) {
3518 if (space->IsMallocSpace()) {
3519 gc::space::MallocSpace* malloc_space = space->AsMallocSpace();
3520 malloc_space->ClampGrowthLimit();
3521 }
3522 }
3523 // This space isn't added for performance reasons.
3524 if (main_space_backup_.get() != nullptr) {
3525 main_space_backup_->ClampGrowthLimit();
3526 }
3527}
3528
jeffhaoc1160702011-10-27 15:48:45 -07003529void Heap::ClearGrowthLimit() {
Mathieu Chartier80de7a62012-11-27 17:21:50 -08003530 growth_limit_ = capacity_;
Mathieu Chartiera9d82fe2016-01-25 20:06:11 -08003531 ScopedObjectAccess soa(Thread::Current());
Mathieu Chartier0310da52014-12-01 13:40:48 -08003532 for (const auto& space : continuous_spaces_) {
3533 if (space->IsMallocSpace()) {
3534 gc::space::MallocSpace* malloc_space = space->AsMallocSpace();
3535 malloc_space->ClearGrowthLimit();
3536 malloc_space->SetFootprintLimit(malloc_space->Capacity());
3537 }
3538 }
3539 // This space isn't added for performance reasons.
3540 if (main_space_backup_.get() != nullptr) {
3541 main_space_backup_->ClearGrowthLimit();
3542 main_space_backup_->SetFootprintLimit(main_space_backup_->Capacity());
3543 }
jeffhaoc1160702011-10-27 15:48:45 -07003544}
3545
Mathieu Chartier9d156d52016-10-06 17:44:26 -07003546void Heap::AddFinalizerReference(Thread* self, ObjPtr<mirror::Object>* object) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003547 ScopedObjectAccess soa(self);
Mathieu Chartier8668c3c2014-04-24 16:48:11 -07003548 ScopedLocalRef<jobject> arg(self->GetJniEnv(), soa.AddLocalReference<jobject>(*object));
Ian Rogers53b8b092014-03-13 23:45:53 -07003549 jvalue args[1];
3550 args[0].l = arg.get();
3551 InvokeWithJValues(soa, nullptr, WellKnownClasses::java_lang_ref_FinalizerReference_add, args);
Mathieu Chartier8668c3c2014-04-24 16:48:11 -07003552 // Restore object in case it gets moved.
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07003553 *object = soa.Decode<mirror::Object>(arg.get());
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003554}
3555
Mathieu Chartier9d156d52016-10-06 17:44:26 -07003556void Heap::RequestConcurrentGCAndSaveObject(Thread* self,
3557 bool force_full,
3558 ObjPtr<mirror::Object>* obj) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003559 StackHandleScope<1> hs(self);
Mathieu Chartier9d156d52016-10-06 17:44:26 -07003560 HandleWrapperObjPtr<mirror::Object> wrapper(hs.NewHandleWrapper(obj));
Mathieu Chartier35b59a22017-04-17 15:24:43 -07003561 RequestConcurrentGC(self, kGcCauseBackground, force_full);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003562}
3563
Mathieu Chartiera5eae692014-12-17 17:56:03 -08003564class Heap::ConcurrentGCTask : public HeapTask {
3565 public:
Mathieu Chartier35b59a22017-04-17 15:24:43 -07003566 ConcurrentGCTask(uint64_t target_time, GcCause cause, bool force_full)
3567 : HeapTask(target_time), cause_(cause), force_full_(force_full) {}
Mathieu Chartiera5eae692014-12-17 17:56:03 -08003568 virtual void Run(Thread* self) OVERRIDE {
3569 gc::Heap* heap = Runtime::Current()->GetHeap();
Mathieu Chartier35b59a22017-04-17 15:24:43 -07003570 heap->ConcurrentGC(self, cause_, force_full_);
Mathieu Chartiera5eae692014-12-17 17:56:03 -08003571 heap->ClearConcurrentGCRequest();
Ian Rogers120f1c72012-09-28 17:17:10 -07003572 }
Hiroshi Yamauchi0ae98992015-05-01 14:33:19 -07003573
3574 private:
Mathieu Chartier35b59a22017-04-17 15:24:43 -07003575 const GcCause cause_;
Hiroshi Yamauchi0ae98992015-05-01 14:33:19 -07003576 const bool force_full_; // If true, force full (or partial) collection.
Mathieu Chartiera5eae692014-12-17 17:56:03 -08003577};
3578
Mathieu Chartier90443472015-07-16 20:32:27 -07003579static bool CanAddHeapTask(Thread* self) REQUIRES(!Locks::runtime_shutdown_lock_) {
Mathieu Chartiera5eae692014-12-17 17:56:03 -08003580 Runtime* runtime = Runtime::Current();
3581 return runtime != nullptr && runtime->IsFinishedStarting() && !runtime->IsShuttingDown(self) &&
3582 !self->IsHandlingStackOverflow();
3583}
3584
3585void Heap::ClearConcurrentGCRequest() {
3586 concurrent_gc_pending_.StoreRelaxed(false);
3587}
3588
Mathieu Chartier35b59a22017-04-17 15:24:43 -07003589void Heap::RequestConcurrentGC(Thread* self, GcCause cause, bool force_full) {
Mathieu Chartierac195162015-02-20 18:44:28 +00003590 if (CanAddHeapTask(self) &&
3591 concurrent_gc_pending_.CompareExchangeStrongSequentiallyConsistent(false, true)) {
Hiroshi Yamauchi0ae98992015-05-01 14:33:19 -07003592 task_processor_->AddTask(self, new ConcurrentGCTask(NanoTime(), // Start straight away.
Mathieu Chartier35b59a22017-04-17 15:24:43 -07003593 cause,
Hiroshi Yamauchi0ae98992015-05-01 14:33:19 -07003594 force_full));
Mathieu Chartiera5eae692014-12-17 17:56:03 -08003595 }
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07003596}
3597
Mathieu Chartier35b59a22017-04-17 15:24:43 -07003598void Heap::ConcurrentGC(Thread* self, GcCause cause, bool force_full) {
Mathieu Chartiera5eae692014-12-17 17:56:03 -08003599 if (!Runtime::Current()->IsShuttingDown(self)) {
3600 // Wait for any GCs currently running to finish.
Mathieu Chartier35b59a22017-04-17 15:24:43 -07003601 if (WaitForGcToComplete(cause, self) == collector::kGcTypeNone) {
Roland Levillainb81e9e92017-04-20 17:35:32 +01003602 // If the we can't run the GC type we wanted to run, find the next appropriate one and try
3603 // that instead. E.g. can't do partial, so do full instead.
Hiroshi Yamauchi0ae98992015-05-01 14:33:19 -07003604 collector::GcType next_gc_type = next_gc_type_;
3605 // If forcing full and next gc type is sticky, override with a non-sticky type.
3606 if (force_full && next_gc_type == collector::kGcTypeSticky) {
Richard Uhlercaaa2b02017-02-01 09:54:17 +00003607 next_gc_type = NonStickyGcType();
Hiroshi Yamauchi0ae98992015-05-01 14:33:19 -07003608 }
Mathieu Chartier35b59a22017-04-17 15:24:43 -07003609 if (CollectGarbageInternal(next_gc_type, cause, false) == collector::kGcTypeNone) {
Mathieu Chartiera5eae692014-12-17 17:56:03 -08003610 for (collector::GcType gc_type : gc_plan_) {
3611 // Attempt to run the collector, if we succeed, we are done.
Hiroshi Yamauchi0ae98992015-05-01 14:33:19 -07003612 if (gc_type > next_gc_type &&
Mathieu Chartier35b59a22017-04-17 15:24:43 -07003613 CollectGarbageInternal(gc_type, cause, false) != collector::kGcTypeNone) {
Mathieu Chartiera5eae692014-12-17 17:56:03 -08003614 break;
3615 }
Mathieu Chartierf9ed0d32013-11-21 16:42:47 -08003616 }
3617 }
3618 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -07003619 }
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07003620}
3621
Mathieu Chartiera5eae692014-12-17 17:56:03 -08003622class Heap::CollectorTransitionTask : public HeapTask {
3623 public:
Mathieu Chartiera4f6af92015-08-11 17:35:25 -07003624 explicit CollectorTransitionTask(uint64_t target_time) : HeapTask(target_time) {}
3625
Mathieu Chartiera5eae692014-12-17 17:56:03 -08003626 virtual void Run(Thread* self) OVERRIDE {
3627 gc::Heap* heap = Runtime::Current()->GetHeap();
3628 heap->DoPendingCollectorTransition();
3629 heap->ClearPendingCollectorTransition(self);
Mathieu Chartiera5f9de02014-02-28 16:48:42 -08003630 }
Mathieu Chartiera5eae692014-12-17 17:56:03 -08003631};
3632
3633void Heap::ClearPendingCollectorTransition(Thread* self) {
3634 MutexLock mu(self, *pending_task_lock_);
3635 pending_collector_transition_ = nullptr;
Mathieu Chartiera5f9de02014-02-28 16:48:42 -08003636}
3637
Mathieu Chartiera5eae692014-12-17 17:56:03 -08003638void Heap::RequestCollectorTransition(CollectorType desired_collector_type, uint64_t delta_time) {
3639 Thread* self = Thread::Current();
3640 desired_collector_type_ = desired_collector_type;
3641 if (desired_collector_type_ == collector_type_ || !CanAddHeapTask(self)) {
3642 return;
3643 }
Hiroshi Yamauchi60985b72016-08-24 13:53:12 -07003644 if (collector_type_ == kCollectorTypeCC) {
3645 // For CC, we invoke a full compaction when going to the background, but the collector type
3646 // doesn't change.
3647 DCHECK_EQ(desired_collector_type_, kCollectorTypeCCBackground);
3648 }
3649 DCHECK_NE(collector_type_, kCollectorTypeCCBackground);
Mathieu Chartiera5eae692014-12-17 17:56:03 -08003650 CollectorTransitionTask* added_task = nullptr;
3651 const uint64_t target_time = NanoTime() + delta_time;
3652 {
3653 MutexLock mu(self, *pending_task_lock_);
3654 // If we have an existing collector transition, update the targe time to be the new target.
3655 if (pending_collector_transition_ != nullptr) {
3656 task_processor_->UpdateTargetRunTime(self, pending_collector_transition_, target_time);
3657 return;
3658 }
3659 added_task = new CollectorTransitionTask(target_time);
3660 pending_collector_transition_ = added_task;
3661 }
3662 task_processor_->AddTask(self, added_task);
3663}
3664
3665class Heap::HeapTrimTask : public HeapTask {
3666 public:
3667 explicit HeapTrimTask(uint64_t delta_time) : HeapTask(NanoTime() + delta_time) { }
3668 virtual void Run(Thread* self) OVERRIDE {
3669 gc::Heap* heap = Runtime::Current()->GetHeap();
3670 heap->Trim(self);
3671 heap->ClearPendingTrim(self);
3672 }
3673};
3674
3675void Heap::ClearPendingTrim(Thread* self) {
3676 MutexLock mu(self, *pending_task_lock_);
3677 pending_heap_trim_ = nullptr;
3678}
3679
3680void Heap::RequestTrim(Thread* self) {
3681 if (!CanAddHeapTask(self)) {
3682 return;
3683 }
Ian Rogers48931882013-01-22 14:35:16 -08003684 // GC completed and now we must decide whether to request a heap trim (advising pages back to the
3685 // kernel) or not. Issuing a request will also cause trimming of the libc heap. As a trim scans
3686 // a space it will hold its lock and can become a cause of jank.
3687 // Note, the large object space self trims and the Zygote space was trimmed and unchanging since
3688 // forking.
3689
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08003690 // We don't have a good measure of how worthwhile a trim might be. We can't use the live bitmap
3691 // because that only marks object heads, so a large array looks like lots of empty space. We
3692 // don't just call dlmalloc all the time, because the cost of an _attempted_ trim is proportional
3693 // to utilization (which is probably inversely proportional to how much benefit we can expect).
3694 // We could try mincore(2) but that's only a measure of how many pages we haven't given away,
3695 // not how much use we're making of those pages.
Mathieu Chartiera5eae692014-12-17 17:56:03 -08003696 HeapTrimTask* added_task = nullptr;
Mathieu Chartier440e4ce2014-03-31 16:36:35 -07003697 {
Mathieu Chartiera5eae692014-12-17 17:56:03 -08003698 MutexLock mu(self, *pending_task_lock_);
3699 if (pending_heap_trim_ != nullptr) {
3700 // Already have a heap trim request in task processor, ignore this request.
Mathieu Chartier440e4ce2014-03-31 16:36:35 -07003701 return;
Mathieu Chartiera5f9de02014-02-28 16:48:42 -08003702 }
Mathieu Chartiera5eae692014-12-17 17:56:03 -08003703 added_task = new HeapTrimTask(kHeapTrimWait);
3704 pending_heap_trim_ = added_task;
Mathieu Chartierc39e3422013-08-07 16:41:36 -07003705 }
Mathieu Chartiera5eae692014-12-17 17:56:03 -08003706 task_processor_->AddTask(self, added_task);
Mathieu Chartiera5f9de02014-02-28 16:48:42 -08003707}
3708
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -07003709void Heap::RevokeThreadLocalBuffers(Thread* thread) {
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08003710 if (rosalloc_space_ != nullptr) {
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07003711 size_t freed_bytes_revoke = rosalloc_space_->RevokeThreadLocalBuffers(thread);
3712 if (freed_bytes_revoke > 0U) {
3713 num_bytes_freed_revoke_.FetchAndAddSequentiallyConsistent(freed_bytes_revoke);
3714 CHECK_GE(num_bytes_allocated_.LoadRelaxed(), num_bytes_freed_revoke_.LoadRelaxed());
3715 }
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08003716 }
Mathieu Chartier692fafd2013-11-29 17:24:40 -08003717 if (bump_pointer_space_ != nullptr) {
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07003718 CHECK_EQ(bump_pointer_space_->RevokeThreadLocalBuffers(thread), 0U);
Mathieu Chartier692fafd2013-11-29 17:24:40 -08003719 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003720 if (region_space_ != nullptr) {
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07003721 CHECK_EQ(region_space_->RevokeThreadLocalBuffers(thread), 0U);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003722 }
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -07003723}
3724
Hiroshi Yamauchic93c5302014-03-20 16:15:37 -07003725void Heap::RevokeRosAllocThreadLocalBuffers(Thread* thread) {
3726 if (rosalloc_space_ != nullptr) {
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07003727 size_t freed_bytes_revoke = rosalloc_space_->RevokeThreadLocalBuffers(thread);
3728 if (freed_bytes_revoke > 0U) {
3729 num_bytes_freed_revoke_.FetchAndAddSequentiallyConsistent(freed_bytes_revoke);
3730 CHECK_GE(num_bytes_allocated_.LoadRelaxed(), num_bytes_freed_revoke_.LoadRelaxed());
3731 }
Hiroshi Yamauchic93c5302014-03-20 16:15:37 -07003732 }
3733}
3734
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -07003735void Heap::RevokeAllThreadLocalBuffers() {
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08003736 if (rosalloc_space_ != nullptr) {
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07003737 size_t freed_bytes_revoke = rosalloc_space_->RevokeAllThreadLocalBuffers();
3738 if (freed_bytes_revoke > 0U) {
3739 num_bytes_freed_revoke_.FetchAndAddSequentiallyConsistent(freed_bytes_revoke);
3740 CHECK_GE(num_bytes_allocated_.LoadRelaxed(), num_bytes_freed_revoke_.LoadRelaxed());
3741 }
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08003742 }
Mathieu Chartier692fafd2013-11-29 17:24:40 -08003743 if (bump_pointer_space_ != nullptr) {
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07003744 CHECK_EQ(bump_pointer_space_->RevokeAllThreadLocalBuffers(), 0U);
Mathieu Chartier692fafd2013-11-29 17:24:40 -08003745 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003746 if (region_space_ != nullptr) {
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07003747 CHECK_EQ(region_space_->RevokeAllThreadLocalBuffers(), 0U);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003748 }
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -07003749}
3750
Mathieu Chartier987ccff2013-07-08 11:05:21 -07003751bool Heap::IsGCRequestPending() const {
Mathieu Chartiera5eae692014-12-17 17:56:03 -08003752 return concurrent_gc_pending_.LoadRelaxed();
Mathieu Chartier987ccff2013-07-08 11:05:21 -07003753}
3754
Mathieu Chartierb5de3bb2015-06-05 13:21:05 -07003755void Heap::RunFinalization(JNIEnv* env, uint64_t timeout) {
3756 env->CallStaticVoidMethod(WellKnownClasses::dalvik_system_VMRuntime,
3757 WellKnownClasses::dalvik_system_VMRuntime_runFinalization,
3758 static_cast<jlong>(timeout));
Mathieu Chartier590fee92013-09-13 13:46:47 -07003759}
3760
Richard Uhler36bdbd22017-01-24 14:17:05 +00003761void Heap::RegisterNativeAllocation(JNIEnv* env, size_t bytes) {
Richard Uhlercaaa2b02017-02-01 09:54:17 +00003762 // See the REDESIGN section of go/understanding-register-native-allocation
3763 // for an explanation of how RegisterNativeAllocation works.
3764 size_t new_value = bytes + new_native_bytes_allocated_.FetchAndAddRelaxed(bytes);
3765 if (new_value > NativeAllocationBlockingGcWatermark()) {
3766 // Wait for a new GC to finish and finalizers to run, because the
3767 // allocation rate is too high.
3768 Thread* self = ThreadForEnv(env);
Richard Uhler36bdbd22017-01-24 14:17:05 +00003769
Richard Uhlercaaa2b02017-02-01 09:54:17 +00003770 bool run_gc = false;
3771 {
3772 MutexLock mu(self, *native_blocking_gc_lock_);
3773 uint32_t initial_gcs_finished = native_blocking_gcs_finished_;
3774 if (native_blocking_gc_in_progress_) {
3775 // A native blocking GC is in progress from the last time the native
3776 // allocation blocking GC watermark was exceeded. Wait for that GC to
3777 // finish before addressing the fact that we exceeded the blocking
3778 // watermark again.
3779 do {
Richard Uhlerda1da8a2017-05-16 13:37:32 +00003780 ScopedTrace trace("RegisterNativeAllocation: Wait For Prior Blocking GC Completion");
Richard Uhlercaaa2b02017-02-01 09:54:17 +00003781 native_blocking_gc_cond_->Wait(self);
3782 } while (native_blocking_gcs_finished_ == initial_gcs_finished);
3783 initial_gcs_finished++;
Richard Uhler36bdbd22017-01-24 14:17:05 +00003784 }
Richard Uhlercaaa2b02017-02-01 09:54:17 +00003785
3786 // It's possible multiple threads have seen that we exceeded the
Richard Uhlerda1da8a2017-05-16 13:37:32 +00003787 // blocking watermark. Ensure that only one of those threads is assigned
3788 // to run the blocking GC. The rest of the threads should instead wait
3789 // for the blocking GC to complete.
Richard Uhler4f4a28d2017-02-09 14:03:09 +00003790 if (native_blocking_gcs_finished_ == initial_gcs_finished) {
Richard Uhlerda1da8a2017-05-16 13:37:32 +00003791 if (native_blocking_gc_is_assigned_) {
Richard Uhler4f4a28d2017-02-09 14:03:09 +00003792 do {
Richard Uhlerda1da8a2017-05-16 13:37:32 +00003793 ScopedTrace trace("RegisterNativeAllocation: Wait For Blocking GC Completion");
Richard Uhler4f4a28d2017-02-09 14:03:09 +00003794 native_blocking_gc_cond_->Wait(self);
3795 } while (native_blocking_gcs_finished_ == initial_gcs_finished);
3796 } else {
Richard Uhlerda1da8a2017-05-16 13:37:32 +00003797 native_blocking_gc_is_assigned_ = true;
Richard Uhler4f4a28d2017-02-09 14:03:09 +00003798 run_gc = true;
3799 }
Richard Uhler36bdbd22017-01-24 14:17:05 +00003800 }
Mathieu Chartier987ccff2013-07-08 11:05:21 -07003801 }
Richard Uhlercaaa2b02017-02-01 09:54:17 +00003802
3803 if (run_gc) {
Richard Uhlerda1da8a2017-05-16 13:37:32 +00003804 CollectGarbageInternal(NonStickyGcType(), kGcCauseForNativeAllocBlocking, false);
Richard Uhlercaaa2b02017-02-01 09:54:17 +00003805 RunFinalization(env, kNativeAllocationFinalizeTimeout);
3806 CHECK(!env->ExceptionCheck());
3807
3808 MutexLock mu(self, *native_blocking_gc_lock_);
Richard Uhlerda1da8a2017-05-16 13:37:32 +00003809 native_blocking_gc_is_assigned_ = false;
Richard Uhlercaaa2b02017-02-01 09:54:17 +00003810 native_blocking_gc_in_progress_ = false;
3811 native_blocking_gcs_finished_++;
3812 native_blocking_gc_cond_->Broadcast(self);
3813 }
Mathieu Chartier75e4b2a2017-05-24 12:01:04 -07003814 } else if (new_value > NativeAllocationGcWatermark() * HeapGrowthMultiplier() &&
3815 !IsGCRequestPending()) {
Richard Uhlercaaa2b02017-02-01 09:54:17 +00003816 // Trigger another GC because there have been enough native bytes
3817 // allocated since the last GC.
3818 if (IsGcConcurrent()) {
Richard Uhlerda1da8a2017-05-16 13:37:32 +00003819 RequestConcurrentGC(ThreadForEnv(env), kGcCauseForNativeAlloc, /*force_full*/true);
Richard Uhlercaaa2b02017-02-01 09:54:17 +00003820 } else {
3821 CollectGarbageInternal(NonStickyGcType(), kGcCauseForNativeAlloc, false);
3822 }
Mathieu Chartier987ccff2013-07-08 11:05:21 -07003823 }
3824}
3825
Richard Uhlercaaa2b02017-02-01 09:54:17 +00003826void Heap::RegisterNativeFree(JNIEnv*, size_t bytes) {
3827 // Take the bytes freed out of new_native_bytes_allocated_ first. If
3828 // new_native_bytes_allocated_ reaches zero, take the remaining bytes freed
3829 // out of old_native_bytes_allocated_ to ensure all freed bytes are
3830 // accounted for.
3831 size_t allocated;
3832 size_t new_freed_bytes;
Mathieu Chartier987ccff2013-07-08 11:05:21 -07003833 do {
Richard Uhlercaaa2b02017-02-01 09:54:17 +00003834 allocated = new_native_bytes_allocated_.LoadRelaxed();
3835 new_freed_bytes = std::min(allocated, bytes);
3836 } while (!new_native_bytes_allocated_.CompareExchangeWeakRelaxed(allocated,
3837 allocated - new_freed_bytes));
3838 if (new_freed_bytes < bytes) {
3839 old_native_bytes_allocated_.FetchAndSubRelaxed(bytes - new_freed_bytes);
3840 }
Mathieu Chartier987ccff2013-07-08 11:05:21 -07003841}
3842
Ian Rogersef7d42f2014-01-06 12:55:46 -08003843size_t Heap::GetTotalMemory() const {
Mathieu Chartierdd162fb2014-08-06 17:06:33 -07003844 return std::max(max_allowed_footprint_, GetBytesAllocated());
Hiroshi Yamauchi09b07a92013-07-15 13:17:06 -07003845}
3846
Mathieu Chartier11409ae2013-09-23 11:49:36 -07003847void Heap::AddModUnionTable(accounting::ModUnionTable* mod_union_table) {
3848 DCHECK(mod_union_table != nullptr);
3849 mod_union_tables_.Put(mod_union_table->GetSpace(), mod_union_table);
3850}
3851
Mathieu Chartier9d156d52016-10-06 17:44:26 -07003852void Heap::CheckPreconditionsForAllocObject(ObjPtr<mirror::Class> c, size_t byte_count) {
Mathieu Chartierdf7f7f02017-10-05 09:47:58 -07003853 // Compare rounded sizes since the allocation may have been retried after rounding the size.
3854 // See b/37885600
Mathieu Chartiera5eae692014-12-17 17:56:03 -08003855 CHECK(c == nullptr || (c->IsClassClass() && byte_count >= sizeof(mirror::Class)) ||
Mathieu Chartieraac90122017-10-04 14:58:34 -07003856 (c->IsVariableSize() ||
3857 RoundUp(c->GetObjectSize(), kObjectAlignment) ==
3858 RoundUp(byte_count, kObjectAlignment)))
Mathieu Chartier8876fb72017-02-24 12:39:53 -08003859 << "ClassFlags=" << c->GetClassFlags()
3860 << " IsClassClass=" << c->IsClassClass()
3861 << " byte_count=" << byte_count
3862 << " IsVariableSize=" << c->IsVariableSize()
3863 << " ObjectSize=" << c->GetObjectSize()
3864 << " sizeof(Class)=" << sizeof(mirror::Class)
Mathieu Chartieraac90122017-10-04 14:58:34 -07003865 << " " << verification_->DumpObjectInfo(c.Ptr(), /*tag*/ "klass");
Mathieu Chartierc645f1d2014-03-06 18:11:53 -08003866 CHECK_GE(byte_count, sizeof(mirror::Object));
3867}
3868
Hiroshi Yamauchi38e68e92014-03-07 13:59:08 -08003869void Heap::AddRememberedSet(accounting::RememberedSet* remembered_set) {
3870 CHECK(remembered_set != nullptr);
3871 space::Space* space = remembered_set->GetSpace();
3872 CHECK(space != nullptr);
Mathieu Chartier8e4a96d2014-05-21 10:44:32 -07003873 CHECK(remembered_sets_.find(space) == remembered_sets_.end()) << space;
Hiroshi Yamauchi38e68e92014-03-07 13:59:08 -08003874 remembered_sets_.Put(space, remembered_set);
Mathieu Chartier8e4a96d2014-05-21 10:44:32 -07003875 CHECK(remembered_sets_.find(space) != remembered_sets_.end()) << space;
Hiroshi Yamauchi38e68e92014-03-07 13:59:08 -08003876}
3877
3878void Heap::RemoveRememberedSet(space::Space* space) {
3879 CHECK(space != nullptr);
3880 auto it = remembered_sets_.find(space);
3881 CHECK(it != remembered_sets_.end());
Mathieu Chartier5189e242014-07-24 11:11:05 -07003882 delete it->second;
Hiroshi Yamauchi38e68e92014-03-07 13:59:08 -08003883 remembered_sets_.erase(it);
3884 CHECK(remembered_sets_.find(space) == remembered_sets_.end());
3885}
3886
Mathieu Chartier4aeec172014-03-27 16:09:46 -07003887void Heap::ClearMarkedObjects() {
3888 // Clear all of the spaces' mark bitmaps.
3889 for (const auto& space : GetContinuousSpaces()) {
Mathieu Chartiera8e8f9c2014-04-09 14:51:05 -07003890 accounting::ContinuousSpaceBitmap* mark_bitmap = space->GetMarkBitmap();
Mathieu Chartier4aeec172014-03-27 16:09:46 -07003891 if (space->GetLiveBitmap() != mark_bitmap) {
3892 mark_bitmap->Clear();
3893 }
3894 }
3895 // Clear the marked objects in the discontinous space object sets.
3896 for (const auto& space : GetDiscontinuousSpaces()) {
Mathieu Chartierbbd695c2014-04-16 09:48:48 -07003897 space->GetMarkBitmap()->Clear();
Mathieu Chartier4aeec172014-03-27 16:09:46 -07003898 }
3899}
3900
Man Cao8c2ff642015-05-27 17:25:30 -07003901void Heap::SetAllocationRecords(AllocRecordObjectMap* records) {
3902 allocation_records_.reset(records);
3903}
3904
Man Cao1ed11b92015-06-11 22:47:35 -07003905void Heap::VisitAllocationRecords(RootVisitor* visitor) const {
3906 if (IsAllocTrackingEnabled()) {
3907 MutexLock mu(Thread::Current(), *Locks::alloc_tracker_lock_);
3908 if (IsAllocTrackingEnabled()) {
3909 GetAllocationRecords()->VisitRoots(visitor);
3910 }
3911 }
3912}
3913
Mathieu Chartier97509952015-07-13 14:35:43 -07003914void Heap::SweepAllocationRecords(IsMarkedVisitor* visitor) const {
Man Cao8c2ff642015-05-27 17:25:30 -07003915 if (IsAllocTrackingEnabled()) {
3916 MutexLock mu(Thread::Current(), *Locks::alloc_tracker_lock_);
3917 if (IsAllocTrackingEnabled()) {
Mathieu Chartier97509952015-07-13 14:35:43 -07003918 GetAllocationRecords()->SweepAllocationRecords(visitor);
Man Cao8c2ff642015-05-27 17:25:30 -07003919 }
3920 }
3921}
3922
Man Cao42c3c332015-06-23 16:38:25 -07003923void Heap::AllowNewAllocationRecords() const {
Hiroshi Yamauchifdbd13c2015-09-02 16:16:58 -07003924 CHECK(!kUseReadBarrier);
Hiroshi Yamauchi6f0c6cd2016-03-18 17:17:52 -07003925 MutexLock mu(Thread::Current(), *Locks::alloc_tracker_lock_);
3926 AllocRecordObjectMap* allocation_records = GetAllocationRecords();
3927 if (allocation_records != nullptr) {
3928 allocation_records->AllowNewAllocationRecords();
Man Cao42c3c332015-06-23 16:38:25 -07003929 }
3930}
3931
3932void Heap::DisallowNewAllocationRecords() const {
Hiroshi Yamauchifdbd13c2015-09-02 16:16:58 -07003933 CHECK(!kUseReadBarrier);
Hiroshi Yamauchi6f0c6cd2016-03-18 17:17:52 -07003934 MutexLock mu(Thread::Current(), *Locks::alloc_tracker_lock_);
3935 AllocRecordObjectMap* allocation_records = GetAllocationRecords();
3936 if (allocation_records != nullptr) {
3937 allocation_records->DisallowNewAllocationRecords();
Man Cao42c3c332015-06-23 16:38:25 -07003938 }
3939}
3940
Hiroshi Yamauchifdbd13c2015-09-02 16:16:58 -07003941void Heap::BroadcastForNewAllocationRecords() const {
Hiroshi Yamauchi6f0c6cd2016-03-18 17:17:52 -07003942 // Always broadcast without checking IsAllocTrackingEnabled() because IsAllocTrackingEnabled() may
3943 // be set to false while some threads are waiting for system weak access in
3944 // AllocRecordObjectMap::RecordAllocation() and we may fail to wake them up. b/27467554.
3945 MutexLock mu(Thread::Current(), *Locks::alloc_tracker_lock_);
3946 AllocRecordObjectMap* allocation_records = GetAllocationRecords();
3947 if (allocation_records != nullptr) {
3948 allocation_records->BroadcastForNewAllocationRecords();
Hiroshi Yamauchifdbd13c2015-09-02 16:16:58 -07003949 }
3950}
3951
Mathieu Chartier9d156d52016-10-06 17:44:26 -07003952void Heap::CheckGcStressMode(Thread* self, ObjPtr<mirror::Object>* obj) {
Mathieu Chartier31000802015-06-14 14:14:37 -07003953 auto* const runtime = Runtime::Current();
3954 if (gc_stress_mode_ && runtime->GetClassLinker()->IsInitialized() &&
3955 !runtime->IsActiveTransaction() && mirror::Class::HasJavaLangClass()) {
3956 // Check if we should GC.
3957 bool new_backtrace = false;
3958 {
3959 static constexpr size_t kMaxFrames = 16u;
Mathieu Chartier34583592017-03-23 23:51:34 -07003960 FixedSizeBacktrace<kMaxFrames> backtrace;
3961 backtrace.Collect(/* skip_frames */ 2);
3962 uint64_t hash = backtrace.Hash();
Mathieu Chartier31000802015-06-14 14:14:37 -07003963 MutexLock mu(self, *backtrace_lock_);
3964 new_backtrace = seen_backtraces_.find(hash) == seen_backtraces_.end();
3965 if (new_backtrace) {
3966 seen_backtraces_.insert(hash);
3967 }
3968 }
3969 if (new_backtrace) {
3970 StackHandleScope<1> hs(self);
3971 auto h = hs.NewHandleWrapper(obj);
3972 CollectGarbage(false);
3973 unique_backtrace_count_.FetchAndAddSequentiallyConsistent(1);
3974 } else {
3975 seen_backtrace_count_.FetchAndAddSequentiallyConsistent(1);
3976 }
3977 }
3978}
3979
Mathieu Chartier51168372015-08-12 16:40:32 -07003980void Heap::DisableGCForShutdown() {
3981 Thread* const self = Thread::Current();
3982 CHECK(Runtime::Current()->IsShuttingDown(self));
3983 MutexLock mu(self, *gc_complete_lock_);
3984 gc_disabled_for_shutdown_ = true;
3985}
3986
Mathieu Chartier9d156d52016-10-06 17:44:26 -07003987bool Heap::ObjectIsInBootImageSpace(ObjPtr<mirror::Object> obj) const {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08003988 for (gc::space::ImageSpace* space : boot_image_spaces_) {
Mathieu Chartier9d156d52016-10-06 17:44:26 -07003989 if (space->HasAddress(obj.Ptr())) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08003990 return true;
3991 }
3992 }
3993 return false;
3994}
3995
Mingyao Yang6ea1a0e2016-01-29 12:12:49 -08003996bool Heap::IsInBootImageOatFile(const void* p) const {
3997 for (gc::space::ImageSpace* space : boot_image_spaces_) {
3998 if (space->GetOatFile()->Contains(p)) {
3999 return true;
4000 }
4001 }
4002 return false;
4003}
4004
Mathieu Chartierfbc31082016-01-24 11:59:56 -08004005void Heap::GetBootImagesSize(uint32_t* boot_image_begin,
4006 uint32_t* boot_image_end,
4007 uint32_t* boot_oat_begin,
4008 uint32_t* boot_oat_end) {
4009 DCHECK(boot_image_begin != nullptr);
4010 DCHECK(boot_image_end != nullptr);
4011 DCHECK(boot_oat_begin != nullptr);
4012 DCHECK(boot_oat_end != nullptr);
4013 *boot_image_begin = 0u;
4014 *boot_image_end = 0u;
4015 *boot_oat_begin = 0u;
4016 *boot_oat_end = 0u;
4017 for (gc::space::ImageSpace* space_ : GetBootImageSpaces()) {
4018 const uint32_t image_begin = PointerToLowMemUInt32(space_->Begin());
4019 const uint32_t image_size = space_->GetImageHeader().GetImageSize();
4020 if (*boot_image_begin == 0 || image_begin < *boot_image_begin) {
4021 *boot_image_begin = image_begin;
4022 }
4023 *boot_image_end = std::max(*boot_image_end, image_begin + image_size);
4024 const OatFile* boot_oat_file = space_->GetOatFile();
4025 const uint32_t oat_begin = PointerToLowMemUInt32(boot_oat_file->Begin());
4026 const uint32_t oat_size = boot_oat_file->Size();
4027 if (*boot_oat_begin == 0 || oat_begin < *boot_oat_begin) {
4028 *boot_oat_begin = oat_begin;
4029 }
4030 *boot_oat_end = std::max(*boot_oat_end, oat_begin + oat_size);
4031 }
4032}
4033
Andreas Gampe27fa96c2016-10-07 15:05:24 -07004034void Heap::SetAllocationListener(AllocationListener* l) {
4035 AllocationListener* old = GetAndOverwriteAllocationListener(&alloc_listener_, l);
4036
4037 if (old == nullptr) {
4038 Runtime::Current()->GetInstrumentation()->InstrumentQuickAllocEntryPoints();
4039 }
4040}
4041
4042void Heap::RemoveAllocationListener() {
4043 AllocationListener* old = GetAndOverwriteAllocationListener(&alloc_listener_, nullptr);
4044
4045 if (old != nullptr) {
Andreas Gampe172ec8e2016-10-12 13:50:20 -07004046 Runtime::Current()->GetInstrumentation()->UninstrumentQuickAllocEntryPoints();
Andreas Gampe27fa96c2016-10-07 15:05:24 -07004047 }
4048}
4049
Andreas Gampe9b8c5882016-10-21 15:27:46 -07004050void Heap::SetGcPauseListener(GcPauseListener* l) {
4051 gc_pause_listener_.StoreRelaxed(l);
4052}
4053
4054void Heap::RemoveGcPauseListener() {
4055 gc_pause_listener_.StoreRelaxed(nullptr);
4056}
Andreas Gampe27fa96c2016-10-07 15:05:24 -07004057
Mathieu Chartier5ace2012016-11-30 10:15:41 -08004058mirror::Object* Heap::AllocWithNewTLAB(Thread* self,
4059 size_t alloc_size,
4060 bool grow,
4061 size_t* bytes_allocated,
4062 size_t* usable_size,
4063 size_t* bytes_tl_bulk_allocated) {
4064 const AllocatorType allocator_type = GetCurrentAllocator();
Mathieu Chartier6bc77742017-04-18 17:46:23 -07004065 if (kUsePartialTlabs && alloc_size <= self->TlabRemainingCapacity()) {
4066 DCHECK_GT(alloc_size, self->TlabSize());
4067 // There is enough space if we grow the TLAB. Lets do that. This increases the
4068 // TLAB bytes.
4069 const size_t min_expand_size = alloc_size - self->TlabSize();
4070 const size_t expand_bytes = std::max(
4071 min_expand_size,
4072 std::min(self->TlabRemainingCapacity() - self->TlabSize(), kPartialTlabSize));
4073 if (UNLIKELY(IsOutOfMemoryOnAllocation(allocator_type, expand_bytes, grow))) {
4074 return nullptr;
4075 }
4076 *bytes_tl_bulk_allocated = expand_bytes;
4077 self->ExpandTlab(expand_bytes);
4078 DCHECK_LE(alloc_size, self->TlabSize());
4079 } else if (allocator_type == kAllocatorTypeTLAB) {
Mathieu Chartier5ace2012016-11-30 10:15:41 -08004080 DCHECK(bump_pointer_space_ != nullptr);
4081 const size_t new_tlab_size = alloc_size + kDefaultTLABSize;
4082 if (UNLIKELY(IsOutOfMemoryOnAllocation(allocator_type, new_tlab_size, grow))) {
4083 return nullptr;
4084 }
4085 // Try allocating a new thread local buffer, if the allocation fails the space must be
4086 // full so return null.
4087 if (!bump_pointer_space_->AllocNewTlab(self, new_tlab_size)) {
4088 return nullptr;
4089 }
4090 *bytes_tl_bulk_allocated = new_tlab_size;
4091 } else {
4092 DCHECK(allocator_type == kAllocatorTypeRegionTLAB);
4093 DCHECK(region_space_ != nullptr);
4094 if (space::RegionSpace::kRegionSize >= alloc_size) {
4095 // Non-large. Check OOME for a tlab.
4096 if (LIKELY(!IsOutOfMemoryOnAllocation(allocator_type,
4097 space::RegionSpace::kRegionSize,
4098 grow))) {
Mathieu Chartier6bc77742017-04-18 17:46:23 -07004099 const size_t new_tlab_size = kUsePartialTlabs
4100 ? std::max(alloc_size, kPartialTlabSize)
4101 : gc::space::RegionSpace::kRegionSize;
Mathieu Chartier5ace2012016-11-30 10:15:41 -08004102 // Try to allocate a tlab.
Mathieu Chartier6bc77742017-04-18 17:46:23 -07004103 if (!region_space_->AllocNewTlab(self, new_tlab_size)) {
Mathieu Chartier5ace2012016-11-30 10:15:41 -08004104 // Failed to allocate a tlab. Try non-tlab.
4105 return region_space_->AllocNonvirtual<false>(alloc_size,
4106 bytes_allocated,
4107 usable_size,
4108 bytes_tl_bulk_allocated);
4109 }
Mathieu Chartier6bc77742017-04-18 17:46:23 -07004110 *bytes_tl_bulk_allocated = new_tlab_size;
Mathieu Chartier5ace2012016-11-30 10:15:41 -08004111 // Fall-through to using the TLAB below.
4112 } else {
4113 // Check OOME for a non-tlab allocation.
4114 if (!IsOutOfMemoryOnAllocation(allocator_type, alloc_size, grow)) {
4115 return region_space_->AllocNonvirtual<false>(alloc_size,
4116 bytes_allocated,
4117 usable_size,
4118 bytes_tl_bulk_allocated);
4119 }
4120 // Neither tlab or non-tlab works. Give up.
4121 return nullptr;
4122 }
4123 } else {
4124 // Large. Check OOME.
4125 if (LIKELY(!IsOutOfMemoryOnAllocation(allocator_type, alloc_size, grow))) {
4126 return region_space_->AllocNonvirtual<false>(alloc_size,
4127 bytes_allocated,
4128 usable_size,
4129 bytes_tl_bulk_allocated);
4130 }
4131 return nullptr;
4132 }
4133 }
4134 // Refilled TLAB, return.
4135 mirror::Object* ret = self->AllocTlab(alloc_size);
4136 DCHECK(ret != nullptr);
4137 *bytes_allocated = alloc_size;
4138 *usable_size = alloc_size;
4139 return ret;
4140}
4141
Mathieu Chartier1ca68902017-04-18 11:26:22 -07004142const Verification* Heap::GetVerification() const {
4143 return verification_.get();
4144}
4145
Ian Rogers1d54e732013-05-02 21:10:01 -07004146} // namespace gc
Carl Shapiro69759ea2011-07-21 18:13:35 -07004147} // namespace art