blob: 4ca6bf7e3f20e593b8054257e380145aa230bcca [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>
Alex Light986914b2019-11-19 01:12:25 +000020#include "android-base/thread_annotations.h"
Hans Boehmb5870722018-12-13 16:25:05 -080021#if defined(__BIONIC__) || defined(__GLIBC__)
Hans Boehmc220f982018-10-12 16:15:45 -070022#include <malloc.h> // For mallinfo()
Hans Boehmb5870722018-12-13 16:25:05 -080023#endif
Ian Rogers700a4022014-05-19 16:49:03 -070024#include <memory>
Carl Shapiro58551df2011-07-24 03:09:51 -070025#include <vector>
26
Andreas Gampe46ee31b2016-12-14 10:11:49 -080027#include "android-base/stringprintf.h"
28
Andreas Gampe27fa96c2016-10-07 15:05:24 -070029#include "allocation_listener.h"
Mathieu Chartierc7853442015-03-27 14:35:38 -070030#include "art_field-inl.h"
Mathieu Chartier34583592017-03-23 23:51:34 -070031#include "backtrace_helper.h"
Mathieu Chartierbad02672014-08-25 13:08:22 -070032#include "base/allocator.h"
Mathieu Chartier8d447252015-10-26 10:21:14 -070033#include "base/arena_allocator.h"
Ian Rogersc7dd2952014-10-21 23:31:19 -070034#include "base/dumpable.h"
David Sehr891a50e2017-10-27 17:01:07 -070035#include "base/file_utils.h"
Mathieu Chartierb2f99362013-11-20 17:26:00 -080036#include "base/histogram-inl.h"
Andreas Gampe170331f2017-12-07 18:41:03 -080037#include "base/logging.h" // For VLOG.
Hiroshi Yamauchi55113ed2017-02-10 15:12:46 -080038#include "base/memory_tool.h"
Alex Light66834462019-04-08 16:28:29 +000039#include "base/mutex.h"
David Sehrc431b9d2018-03-02 12:01:51 -080040#include "base/os.h"
Elliott Hughes1aa246d2012-12-13 09:29:36 -080041#include "base/stl_util.h"
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -080042#include "base/systrace.h"
Vladimir Marko80afd022015-05-19 18:08:00 +010043#include "base/time_utils.h"
Andreas Gampe97b28112018-12-04 09:09:12 -080044#include "base/utils.h"
Vladimir Marko5868ada2020-05-12 11:50:34 +010045#include "class_root-inl.h"
Mathieu Chartier987ccff2013-07-08 11:05:21 -070046#include "common_throws.h"
Elliott Hughes767a1472011-10-26 18:49:02 -070047#include "debugger.h"
David Sehr9e734c72018-01-04 17:56:19 -080048#include "dex/dex_file-inl.h"
Steven Morelande431e272017-07-18 16:53:49 -070049#include "entrypoints/quick/quick_alloc_entrypoints.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070050#include "gc/accounting/card_table-inl.h"
51#include "gc/accounting/heap_bitmap-inl.h"
52#include "gc/accounting/mod_union_table-inl.h"
Andreas Gamped4901292017-05-30 18:41:34 -070053#include "gc/accounting/read_barrier_table.h"
Hiroshi Yamauchi38e68e92014-03-07 13:59:08 -080054#include "gc/accounting/remembered_set.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070055#include "gc/accounting/space_bitmap-inl.h"
Hiroshi Yamauchid5307ec2014-03-27 21:07:51 -070056#include "gc/collector/concurrent_copying.h"
Mathieu Chartier3cf22532015-07-09 15:15:09 -070057#include "gc/collector/mark_sweep.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070058#include "gc/collector/partial_mark_sweep.h"
Mathieu Chartier590fee92013-09-13 13:46:47 -070059#include "gc/collector/semi_space.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070060#include "gc/collector/sticky_mark_sweep.h"
Hans Boehmfb8b4e22018-09-05 16:45:42 -070061#include "gc/racing_check.h"
Mathieu Chartier78f7b4c2014-05-06 10:57:27 -070062#include "gc/reference_processor.h"
Hiroshi Yamauchi3b1d1b72016-10-12 11:53:57 -070063#include "gc/scoped_gc_critical_section.h"
Mathieu Chartier590fee92013-09-13 13:46:47 -070064#include "gc/space/bump_pointer_space.h"
Hiroshi Yamauchi50b29282013-07-30 13:58:37 -070065#include "gc/space/dlmalloc_space-inl.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070066#include "gc/space/image_space.h"
67#include "gc/space/large_object_space.h"
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -080068#include "gc/space/region_space.h"
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -070069#include "gc/space/rosalloc_space-inl.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070070#include "gc/space/space-inl.h"
Mathieu Chartiera1602f22014-01-13 17:19:19 -080071#include "gc/space/zygote_space.h"
Mathieu Chartiera5eae692014-12-17 17:56:03 -080072#include "gc/task_processor.h"
Mathieu Chartier1ca68902017-04-18 11:26:22 -070073#include "gc/verification.h"
Andreas Gampe9b8c5882016-10-21 15:27:46 -070074#include "gc_pause_listener.h"
Andreas Gamped4901292017-05-30 18:41:34 -070075#include "gc_root.h"
Steven Morelande431e272017-07-18 16:53:49 -070076#include "handle_scope-inl.h"
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -070077#include "heap-inl.h"
Andreas Gampe351c4472017-07-12 19:32:55 -070078#include "heap-visit-objects-inl.h"
Brian Carlstrom9cff8e12011-08-18 16:47:29 -070079#include "image.h"
Mathieu Chartiereb175f72014-10-31 11:49:27 -070080#include "intern_table.h"
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +000081#include "jit/jit.h"
82#include "jit/jit_code_cache.h"
Vladimir Markoa3ad0cd2018-05-04 10:06:38 +010083#include "jni/java_vm_ext.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080084#include "mirror/class-inl.h"
Alex Lightc18eba32019-09-24 14:36:27 -070085#include "mirror/executable-inl.h"
86#include "mirror/field.h"
87#include "mirror/method_handle_impl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080088#include "mirror/object-inl.h"
Andreas Gampec6ea7d02017-02-01 16:46:28 -080089#include "mirror/object-refvisitor-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080090#include "mirror/object_array-inl.h"
Mathieu Chartier8fa2dad2014-03-13 12:22:56 -070091#include "mirror/reference-inl.h"
Alex Lightc18eba32019-09-24 14:36:27 -070092#include "mirror/var_handle.h"
Andreas Gampe373a9b52017-10-18 09:01:57 -070093#include "nativehelper/scoped_local_ref.h"
Steven Morelande431e272017-07-18 16:53:49 -070094#include "obj_ptr-inl.h"
Ian Rogers53b8b092014-03-13 23:45:53 -070095#include "reflection.h"
Mathieu Chartier0de9f732013-11-22 17:58:48 -080096#include "runtime.h"
Wessam Hassaneinb5a10be2020-11-11 16:42:52 -080097#include "javaheapprof/javaheapsampler.h"
Mathieu Chartier0795f232016-09-27 18:43:30 -070098#include "scoped_thread_state_change-inl.h"
Elliott Hughes8d768a92011-09-14 16:35:25 -070099#include "thread_list.h"
Andreas Gampe90b936d2017-01-31 08:58:55 -0800100#include "verify_object-inl.h"
Elliott Hugheseac76672012-05-24 21:56:51 -0700101#include "well_known_classes.h"
Carl Shapiro69759ea2011-07-21 18:13:35 -0700102
103namespace art {
Mathieu Chartier50482232013-11-21 11:48:14 -0800104
Ian Rogers1d54e732013-05-02 21:10:01 -0700105namespace gc {
Carl Shapiro69759ea2011-07-21 18:13:35 -0700106
Andreas Gampeed56b5e2017-10-19 12:58:19 -0700107DEFINE_RUNTIME_DEBUG_FLAG(Heap, kStressCollectorTransition);
108
Ian Rogers1d54e732013-05-02 21:10:01 -0700109// Minimum amount of remaining bytes before a concurrent GC is triggered.
Mathieu Chartier720ef762013-08-17 14:46:54 -0700110static constexpr size_t kMinConcurrentRemainingBytes = 128 * KB;
Mathieu Chartier74762802014-01-24 10:21:35 -0800111static constexpr size_t kMaxConcurrentRemainingBytes = 512 * KB;
Mathieu Chartierdf86d1f2014-04-08 13:44:04 -0700112// Sticky GC throughput adjustment, divided by 4. Increasing this causes sticky GC to occur more
Mathieu Chartier73d1e172014-04-11 17:53:48 -0700113// relative to partial/full GC. This may be desirable since sticky GCs interfere less with mutator
Mathieu Chartierdf86d1f2014-04-08 13:44:04 -0700114// threads (lower pauses, use less memory bandwidth).
Albert Mingkun Yang0b4d1462018-11-29 13:25:35 +0000115static double GetStickyGcThroughputAdjustment(bool use_generational_cc) {
116 return use_generational_cc ? 0.5 : 1.0;
117}
Mathieu Chartierc1790162014-05-23 10:54:50 -0700118// Whether or not we compact the zygote in PreZygoteFork.
Mathieu Chartier31f44142014-04-08 14:40:03 -0700119static constexpr bool kCompactZygote = kMovingCollector;
Mathieu Chartierc1790162014-05-23 10:54:50 -0700120// How many reserve entries are at the end of the allocation stack, these are only needed if the
121// allocation stack overflows.
122static constexpr size_t kAllocationStackReserveSize = 1024;
123// Default mark stack size in bytes.
124static const size_t kDefaultMarkStackSize = 64 * KB;
Zuo Wangf37a88b2014-07-10 04:26:41 -0700125// Define space name.
126static const char* kDlMallocSpaceName[2] = {"main dlmalloc space", "main dlmalloc space 1"};
127static const char* kRosAllocSpaceName[2] = {"main rosalloc space", "main rosalloc space 1"};
128static const char* kMemMapSpaceName[2] = {"main space", "main space 1"};
Mathieu Chartier7247af52014-11-19 10:51:42 -0800129static const char* kNonMovingSpaceName = "non moving space";
130static const char* kZygoteSpaceName = "zygote space";
Mathieu Chartier95a505c2014-12-10 18:45:30 -0800131static constexpr bool kGCALotMode = false;
132// GC alot mode uses a small allocation stack to stress test a lot of GC.
133static constexpr size_t kGcAlotAllocationStackSize = 4 * KB /
134 sizeof(mirror::HeapReference<mirror::Object>);
135// Verify objet has a small allocation stack size since searching the allocation stack is slow.
136static constexpr size_t kVerifyObjectAllocationStackSize = 16 * KB /
137 sizeof(mirror::HeapReference<mirror::Object>);
138static constexpr size_t kDefaultAllocationStackSize = 8 * MB /
139 sizeof(mirror::HeapReference<mirror::Object>);
Mathieu Chartier0051be62012-10-12 17:47:11 -0700140
Andreas Gampeace0dc12016-01-20 13:33:13 -0800141// For deterministic compilation, we need the heap to be at a well-known address.
142static constexpr uint32_t kAllocSpaceBeginForDeterministicAoT = 0x40000000;
Hiroshi Yamauchib62f2e62016-03-23 15:51:24 -0700143// Dump the rosalloc stats on SIGQUIT.
144static constexpr bool kDumpRosAllocStatsOnSigQuit = false;
Andreas Gampeace0dc12016-01-20 13:33:13 -0800145
Hiroshi Yamauchi3c3c4a12017-02-21 16:49:59 -0800146static const char* kRegionSpaceName = "main space (region space)";
147
Mathieu Chartier6bc77742017-04-18 17:46:23 -0700148// If true, we log all GCs in the both the foreground and background. Used for debugging.
149static constexpr bool kLogAllGCs = false;
150
Mathieu Chartiera98a2822017-05-24 16:14:10 -0700151// Use Max heap for 2 seconds, this is smaller than the usual 5s window since we don't want to leave
152// allocate with relaxed ergonomics for that long.
153static constexpr size_t kPostForkMaxHeapDurationMS = 2000;
154
Hiroshi Yamauchi3c3c4a12017-02-21 16:49:59 -0800155#if defined(__LP64__) || !defined(ADDRESS_SANITIZER)
156// 300 MB (0x12c00000) - (default non-moving space capacity).
Mathieu Chartierfa4ea822018-03-02 13:48:54 -0800157uint8_t* const Heap::kPreferredAllocSpaceBegin =
158 reinterpret_cast<uint8_t*>(300 * MB - kDefaultNonMovingSpaceCapacity);
Hiroshi Yamauchi3c3c4a12017-02-21 16:49:59 -0800159#else
Andreas Gampee8857fe2017-05-03 08:28:13 -0700160#ifdef __ANDROID__
161// For 32-bit Android, use 0x20000000 because asan reserves 0x04000000 - 0x20000000.
Mathieu Chartierfa4ea822018-03-02 13:48:54 -0800162uint8_t* const Heap::kPreferredAllocSpaceBegin = reinterpret_cast<uint8_t*>(0x20000000);
Andreas Gampee8857fe2017-05-03 08:28:13 -0700163#else
164// For 32-bit host, use 0x40000000 because asan uses most of the space below this.
Mathieu Chartierfa4ea822018-03-02 13:48:54 -0800165uint8_t* const Heap::kPreferredAllocSpaceBegin = reinterpret_cast<uint8_t*>(0x40000000);
Andreas Gampee8857fe2017-05-03 08:28:13 -0700166#endif
Hiroshi Yamauchi3c3c4a12017-02-21 16:49:59 -0800167#endif
168
Mathieu Chartierf8cb1782016-03-18 18:45:41 -0700169static inline bool CareAboutPauseTimes() {
170 return Runtime::Current()->InJankPerceptibleProcessState();
171}
172
Vladimir Marko7cde4582019-07-05 13:26:11 +0100173static void VerifyBootImagesContiguity(const std::vector<gc::space::ImageSpace*>& image_spaces) {
174 uint32_t boot_image_size = 0u;
175 for (size_t i = 0u, num_spaces = image_spaces.size(); i != num_spaces; ) {
176 const ImageHeader& image_header = image_spaces[i]->GetImageHeader();
177 uint32_t reservation_size = image_header.GetImageReservationSize();
Vladimir Markod0036ac2019-11-21 11:47:12 +0000178 uint32_t image_count = image_header.GetImageSpaceCount();
Vladimir Marko7cde4582019-07-05 13:26:11 +0100179
Vladimir Markod0036ac2019-11-21 11:47:12 +0000180 CHECK_NE(image_count, 0u);
181 CHECK_LE(image_count, num_spaces - i);
Vladimir Marko7cde4582019-07-05 13:26:11 +0100182 CHECK_NE(reservation_size, 0u);
Vladimir Markod0036ac2019-11-21 11:47:12 +0000183 for (size_t j = 1u; j != image_count; ++j) {
Vladimir Marko7cde4582019-07-05 13:26:11 +0100184 CHECK_EQ(image_spaces[i + j]->GetImageHeader().GetComponentCount(), 0u);
185 CHECK_EQ(image_spaces[i + j]->GetImageHeader().GetImageReservationSize(), 0u);
186 }
187
188 // Check the start of the heap.
189 CHECK_EQ(image_spaces[0]->Begin() + boot_image_size, image_spaces[i]->Begin());
190 // Check contiguous layout of images and oat files.
191 const uint8_t* current_heap = image_spaces[i]->Begin();
192 const uint8_t* current_oat = image_spaces[i]->GetImageHeader().GetOatFileBegin();
Vladimir Markod0036ac2019-11-21 11:47:12 +0000193 for (size_t j = 0u; j != image_count; ++j) {
Vladimir Marko7cde4582019-07-05 13:26:11 +0100194 const ImageHeader& current_header = image_spaces[i + j]->GetImageHeader();
195 CHECK_EQ(current_heap, image_spaces[i + j]->Begin());
196 CHECK_EQ(current_oat, current_header.GetOatFileBegin());
197 current_heap += RoundUp(current_header.GetImageSize(), kPageSize);
198 CHECK_GT(current_header.GetOatFileEnd(), current_header.GetOatFileBegin());
199 current_oat = current_header.GetOatFileEnd();
200 }
201 // Check that oat files start at the end of images.
202 CHECK_EQ(current_heap, image_spaces[i]->GetImageHeader().GetOatFileBegin());
203 // Check that the reservation size equals the size of images and oat files.
204 CHECK_EQ(reservation_size, static_cast<size_t>(current_oat - image_spaces[i]->Begin()));
205
206 boot_image_size += reservation_size;
Vladimir Markod0036ac2019-11-21 11:47:12 +0000207 i += image_count;
Vladimir Marko7cde4582019-07-05 13:26:11 +0100208 }
209}
210
Mathieu Chartiera4f6af92015-08-11 17:35:25 -0700211Heap::Heap(size_t initial_size,
212 size_t growth_limit,
213 size_t min_free,
214 size_t max_free,
215 double target_utilization,
216 double foreground_heap_growth_multiplier,
Hans Boehmbb2467b2019-03-29 22:55:06 -0700217 size_t stop_for_native_allocs,
Mathieu Chartiera4f6af92015-08-11 17:35:25 -0700218 size_t capacity,
219 size_t non_moving_space_capacity,
Vladimir Markod1908512018-11-22 14:57:28 +0000220 const std::vector<std::string>& boot_class_path,
221 const std::vector<std::string>& boot_class_path_locations,
Mathieu Chartiera4f6af92015-08-11 17:35:25 -0700222 const std::string& image_file_name,
223 const InstructionSet image_instruction_set,
224 CollectorType foreground_collector_type,
Mathieu Chartier2dbe6272014-09-16 10:43:23 -0700225 CollectorType background_collector_type,
Mathieu Chartiera4f6af92015-08-11 17:35:25 -0700226 space::LargeObjectSpaceType large_object_space_type,
227 size_t large_object_threshold,
228 size_t parallel_gc_threads,
229 size_t conc_gc_threads,
230 bool low_memory_mode,
231 size_t long_pause_log_threshold,
232 size_t long_gc_log_threshold,
Hans Boehmc220f982018-10-12 16:15:45 -0700233 bool ignore_target_footprint,
Alex Lightb5a0e912020-07-23 10:54:47 -0700234 bool always_log_explicit_gcs,
Mathieu Chartiera4f6af92015-08-11 17:35:25 -0700235 bool use_tlab,
236 bool verify_pre_gc_heap,
237 bool verify_pre_sweeping_heap,
238 bool verify_post_gc_heap,
239 bool verify_pre_gc_rosalloc,
240 bool verify_pre_sweeping_rosalloc,
241 bool verify_post_gc_rosalloc,
242 bool gc_stress_mode,
Mathieu Chartier56fe2582016-07-14 13:30:03 -0700243 bool measure_gc_performance,
Mathieu Chartier31000802015-06-14 14:14:37 -0700244 bool use_homogeneous_space_compaction_for_oom,
Albert Mingkun Yang0b4d1462018-11-29 13:25:35 +0000245 bool use_generational_cc,
Albert Mingkun Yangde94ea72018-11-16 10:15:49 +0000246 uint64_t min_interval_homogeneous_space_compaction_by_oom,
247 bool dump_region_info_before_gc,
Orion Hodsonae7168e2020-10-09 15:13:29 +0100248 bool dump_region_info_after_gc)
Mathieu Chartiercbb2d202013-11-14 17:45:16 -0800249 : non_moving_space_(nullptr),
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800250 rosalloc_space_(nullptr),
251 dlmalloc_space_(nullptr),
Mathieu Chartierfc5b5282014-01-09 16:15:36 -0800252 main_space_(nullptr),
Mathieu Chartier7bf82af2013-12-06 16:51:45 -0800253 collector_type_(kCollectorTypeNone),
Mathieu Chartier31f44142014-04-08 14:40:03 -0700254 foreground_collector_type_(foreground_collector_type),
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800255 background_collector_type_(background_collector_type),
Mathieu Chartier31f44142014-04-08 14:40:03 -0700256 desired_collector_type_(foreground_collector_type_),
Mathieu Chartiera5eae692014-12-17 17:56:03 -0800257 pending_task_lock_(nullptr),
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700258 parallel_gc_threads_(parallel_gc_threads),
259 conc_gc_threads_(conc_gc_threads),
Mathieu Chartiere0a53e92013-08-05 10:17:40 -0700260 low_memory_mode_(low_memory_mode),
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700261 long_pause_log_threshold_(long_pause_log_threshold),
262 long_gc_log_threshold_(long_gc_log_threshold),
Albert Mingkun Yang2d7329b2018-11-30 19:58:18 +0000263 process_cpu_start_time_ns_(ProcessCpuNanoTime()),
Albert Mingkun Yang6e0d3252018-12-10 15:22:45 +0000264 pre_gc_last_process_cpu_time_ns_(process_cpu_start_time_ns_),
265 post_gc_last_process_cpu_time_ns_(process_cpu_start_time_ns_),
266 pre_gc_weighted_allocated_bytes_(0.0),
267 post_gc_weighted_allocated_bytes_(0.0),
Hans Boehmc220f982018-10-12 16:15:45 -0700268 ignore_target_footprint_(ignore_target_footprint),
Alex Lightb5a0e912020-07-23 10:54:47 -0700269 always_log_explicit_gcs_(always_log_explicit_gcs),
Mathieu Chartier8e4a96d2014-05-21 10:44:32 -0700270 zygote_creation_lock_("zygote creation lock", kZygoteCreationLock),
Mathieu Chartiere4cab172014-08-19 18:24:04 -0700271 zygote_space_(nullptr),
Mathieu Chartier2dbe6272014-09-16 10:43:23 -0700272 large_object_threshold_(large_object_threshold),
Hiroshi Yamauchi76f55b02015-08-21 16:10:39 -0700273 disable_thread_flip_count_(0),
274 thread_flip_running_(false),
Mathieu Chartierd5a89ee2014-01-31 09:55:13 -0800275 collector_type_running_(kCollectorTypeNone),
Mathieu Chartier40112dd2017-06-26 17:49:09 -0700276 last_gc_cause_(kGcCauseNone),
Mathieu Chartier183009a2017-02-16 21:19:28 -0800277 thread_running_gc_(nullptr),
Ian Rogers1d54e732013-05-02 21:10:01 -0700278 last_gc_type_(collector::kGcTypeNone),
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -0700279 next_gc_type_(collector::kGcTypePartial),
Mathieu Chartier80de7a62012-11-27 17:21:50 -0800280 capacity_(capacity),
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700281 growth_limit_(growth_limit),
Hans Boehmc220f982018-10-12 16:15:45 -0700282 target_footprint_(initial_size),
Lokesh Gidraacd70602019-12-05 17:46:25 -0800283 // Using kPostMonitorLock as a lock at kDefaultMutexLevel is acquired after
284 // this one.
285 process_state_update_lock_("process state update lock", kPostMonitorLock),
286 min_foreground_target_footprint_(0),
Mathieu Chartier7bf82af2013-12-06 16:51:45 -0800287 concurrent_start_bytes_(std::numeric_limits<size_t>::max()),
Ian Rogers1d54e732013-05-02 21:10:01 -0700288 total_bytes_freed_ever_(0),
289 total_objects_freed_ever_(0),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800290 num_bytes_allocated_(0),
Hans Boehmc220f982018-10-12 16:15:45 -0700291 native_bytes_registered_(0),
Richard Uhlercaaa2b02017-02-01 09:54:17 +0000292 old_native_bytes_allocated_(0),
Hans Boehmc220f982018-10-12 16:15:45 -0700293 native_objects_notified_(0),
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -0700294 num_bytes_freed_revoke_(0),
Mathieu Chartierc7b83a02012-09-11 18:07:39 -0700295 verify_missing_card_marks_(false),
296 verify_system_weaks_(false),
Mathieu Chartier938a03b2014-01-16 15:10:31 -0800297 verify_pre_gc_heap_(verify_pre_gc_heap),
Mathieu Chartier6f365cc2014-04-23 12:42:27 -0700298 verify_pre_sweeping_heap_(verify_pre_sweeping_heap),
Mathieu Chartier938a03b2014-01-16 15:10:31 -0800299 verify_post_gc_heap_(verify_post_gc_heap),
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700300 verify_mod_union_table_(false),
Hiroshi Yamauchia4adbfd2014-02-04 18:12:17 -0800301 verify_pre_gc_rosalloc_(verify_pre_gc_rosalloc),
Mathieu Chartier6f365cc2014-04-23 12:42:27 -0700302 verify_pre_sweeping_rosalloc_(verify_pre_sweeping_rosalloc),
Hiroshi Yamauchia4adbfd2014-02-04 18:12:17 -0800303 verify_post_gc_rosalloc_(verify_post_gc_rosalloc),
Mathieu Chartier31000802015-06-14 14:14:37 -0700304 gc_stress_mode_(gc_stress_mode),
Hans Boehmd972b422017-09-11 12:57:00 -0700305 /* For GC a lot mode, we limit the allocation stacks to be kGcAlotInterval allocations. This
Mathieu Chartier0418ae22013-07-31 13:35:46 -0700306 * causes a lot of GC since we do a GC for alloc whenever the stack is full. When heap
307 * verification is enabled, we limit the size of allocation stacks to speed up their
308 * searching.
309 */
Mathieu Chartier95a505c2014-12-10 18:45:30 -0800310 max_allocation_stack_size_(kGCALotMode ? kGcAlotAllocationStackSize
311 : (kVerifyObjectSupport > kVerifyObjectModeFast) ? kVerifyObjectAllocationStackSize :
312 kDefaultAllocationStackSize),
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800313 current_allocator_(kAllocatorTypeDlMalloc),
314 current_non_moving_allocator_(kAllocatorTypeNonMoving),
Mathieu Chartier590fee92013-09-13 13:46:47 -0700315 bump_pointer_space_(nullptr),
316 temp_space_(nullptr),
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800317 region_space_(nullptr),
Mathieu Chartier0051be62012-10-12 17:47:11 -0700318 min_free_(min_free),
319 max_free_(max_free),
320 target_utilization_(target_utilization),
Mathieu Chartier11c273d2017-10-15 20:54:45 -0700321 foreground_heap_growth_multiplier_(foreground_heap_growth_multiplier),
Hans Boehmbb2467b2019-03-29 22:55:06 -0700322 stop_for_native_allocs_(stop_for_native_allocs),
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700323 total_wait_time_(0),
Mathieu Chartier4e305412014-02-19 10:54:44 -0800324 verify_object_mode_(kVerifyObjectModeDisabled),
Mathieu Chartier1d27b342014-01-28 12:51:09 -0800325 disable_moving_gc_count_(0),
Vladimir Marko8da690f2016-08-11 18:25:53 +0100326 semi_space_collector_(nullptr),
Mathieu Chartier8d1a9962016-08-17 16:39:45 -0700327 active_concurrent_copying_collector_(nullptr),
328 young_concurrent_copying_collector_(nullptr),
Vladimir Marko8da690f2016-08-11 18:25:53 +0100329 concurrent_copying_collector_(nullptr),
Evgenii Stepanov1e133742015-05-20 12:30:59 -0700330 is_running_on_memory_tool_(Runtime::Current()->IsRunningOnMemoryTool()),
Zuo Wangf37a88b2014-07-10 04:26:41 -0700331 use_tlab_(use_tlab),
332 main_space_backup_(nullptr),
Mathieu Chartierb363f662014-07-16 13:28:58 -0700333 min_interval_homogeneous_space_compaction_by_oom_(
334 min_interval_homogeneous_space_compaction_by_oom),
Zuo Wangf37a88b2014-07-10 04:26:41 -0700335 last_time_homogeneous_space_compaction_by_oom_(NanoTime()),
Mathieu Chartiera5eae692014-12-17 17:56:03 -0800336 pending_collector_transition_(nullptr),
337 pending_heap_trim_(nullptr),
Hiroshi Yamauchia1c9f012015-04-02 10:18:12 -0700338 use_homogeneous_space_compaction_for_oom_(use_homogeneous_space_compaction_for_oom),
Albert Mingkun Yang0b4d1462018-11-29 13:25:35 +0000339 use_generational_cc_(use_generational_cc),
Hiroshi Yamauchia1c9f012015-04-02 10:18:12 -0700340 running_collection_is_blocking_(false),
341 blocking_gc_count_(0U),
342 blocking_gc_time_(0U),
343 last_update_time_gc_count_rate_histograms_( // Round down by the window duration.
344 (NanoTime() / kGcCountRateHistogramWindowDuration) * kGcCountRateHistogramWindowDuration),
345 gc_count_last_window_(0U),
346 blocking_gc_count_last_window_(0U),
347 gc_count_rate_histogram_("gc count rate histogram", 1U, kGcCountRateMaxBucketCount),
348 blocking_gc_count_rate_histogram_("blocking gc count rate histogram", 1U,
Man Cao8c2ff642015-05-27 17:25:30 -0700349 kGcCountRateMaxBucketCount),
Mathieu Chartier31000802015-06-14 14:14:37 -0700350 alloc_tracking_enabled_(false),
Mathieu Chartier0a206072019-03-28 12:29:22 -0700351 alloc_record_depth_(AllocRecordObjectMap::kDefaultAllocStackDepth),
Wessam Hassaneinb5a10be2020-11-11 16:42:52 -0800352 perfetto_javaheapprof_heapid_(0),
Mathieu Chartier31000802015-06-14 14:14:37 -0700353 backtrace_lock_(nullptr),
354 seen_backtrace_count_(0u),
Mathieu Chartier51168372015-08-12 16:40:32 -0700355 unique_backtrace_count_(0u),
Albert Mingkun Yangde94ea72018-11-16 10:15:49 +0000356 gc_disabled_for_shutdown_(false),
357 dump_region_info_before_gc_(dump_region_info_before_gc),
Vladimir Marko7cde4582019-07-05 13:26:11 +0100358 dump_region_info_after_gc_(dump_region_info_after_gc),
359 boot_image_spaces_(),
360 boot_images_start_address_(0u),
361 boot_images_size_(0u) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800362 if (VLOG_IS_ON(heap) || VLOG_IS_ON(startup)) {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800363 LOG(INFO) << "Heap() entering";
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700364 }
Hiroshi Yamauchi1b0adbf2016-11-14 17:35:12 -0800365 if (kUseReadBarrier) {
366 CHECK_EQ(foreground_collector_type_, kCollectorTypeCC);
367 CHECK_EQ(background_collector_type_, kCollectorTypeCCBackground);
Mathieu Chartier40594872019-04-10 16:51:06 -0700368 } else if (background_collector_type_ != gc::kCollectorTypeHomogeneousSpaceCompact) {
Mathieu Chartierb52df532019-04-09 14:10:59 -0700369 CHECK_EQ(IsMovingGc(foreground_collector_type_), IsMovingGc(background_collector_type_))
Mathieu Chartier40594872019-04-10 16:51:06 -0700370 << "Changing from " << foreground_collector_type_ << " to "
371 << background_collector_type_ << " (or visa versa) is not supported.";
Hiroshi Yamauchi1b0adbf2016-11-14 17:35:12 -0800372 }
Mathieu Chartier1ca68902017-04-18 11:26:22 -0700373 verification_.reset(new Verification(this));
Mathieu Chartier8261d022016-08-08 09:41:04 -0700374 CHECK_GE(large_object_threshold, kMinLargeObjectThreshold);
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800375 ScopedTrace trace(__FUNCTION__);
Mathieu Chartier31000802015-06-14 14:14:37 -0700376 Runtime* const runtime = Runtime::Current();
Mathieu Chartier50482232013-11-21 11:48:14 -0800377 // If we aren't the zygote, switch to the default non zygote allocator. This may update the
378 // entrypoints.
Mathieu Chartier31000802015-06-14 14:14:37 -0700379 const bool is_zygote = runtime->IsZygote();
Mathieu Chartier8e219ae2014-08-19 14:29:46 -0700380 if (!is_zygote) {
Mathieu Chartier31f44142014-04-08 14:40:03 -0700381 // Background compaction is currently not supported for command line runs.
382 if (background_collector_type_ != foreground_collector_type_) {
Mathieu Chartier52ba1992014-05-07 14:39:21 -0700383 VLOG(heap) << "Disabling background compaction for non zygote";
Mathieu Chartier31f44142014-04-08 14:40:03 -0700384 background_collector_type_ = foreground_collector_type_;
Mathieu Chartierbd0a6532014-02-27 11:14:21 -0800385 }
Mathieu Chartier50482232013-11-21 11:48:14 -0800386 }
Mathieu Chartiera5f9de02014-02-28 16:48:42 -0800387 ChangeCollector(desired_collector_type_);
Ian Rogers1d54e732013-05-02 21:10:01 -0700388 live_bitmap_.reset(new accounting::HeapBitmap(this));
389 mark_bitmap_.reset(new accounting::HeapBitmap(this));
Jeff Haodcdc85b2015-12-04 14:06:18 -0800390
Mathieu Chartierf75dce42019-04-08 09:36:23 -0700391 // We don't have hspace compaction enabled with CC.
392 if (foreground_collector_type_ == kCollectorTypeCC) {
Hiroshi Yamauchi20ed5af2014-11-17 18:05:44 -0800393 use_homogeneous_space_compaction_for_oom_ = false;
394 }
Mathieu Chartierb363f662014-07-16 13:28:58 -0700395 bool support_homogeneous_space_compaction =
Mathieu Chartier0deeb812014-08-21 18:28:20 -0700396 background_collector_type_ == gc::kCollectorTypeHomogeneousSpaceCompact ||
Hiroshi Yamauchi20ed5af2014-11-17 18:05:44 -0800397 use_homogeneous_space_compaction_for_oom_;
Mathieu Chartierb363f662014-07-16 13:28:58 -0700398 // We may use the same space the main space for the non moving space if we don't need to compact
399 // from the main space.
400 // This is not the case if we support homogeneous compaction or have a moving background
401 // collector type.
Mathieu Chartierb363f662014-07-16 13:28:58 -0700402 bool separate_non_moving_space = is_zygote ||
403 support_homogeneous_space_compaction || IsMovingGc(foreground_collector_type_) ||
404 IsMovingGc(background_collector_type_);
Vladimir Markod44d7032018-08-30 13:02:31 +0100405
406 // Requested begin for the alloc space, to follow the mapped image and oat files
407 uint8_t* request_begin = nullptr;
408 // Calculate the extra space required after the boot image, see allocations below.
Vladimir Marko4df2d802018-09-27 16:42:44 +0000409 size_t heap_reservation_size = 0u;
410 if (separate_non_moving_space) {
411 heap_reservation_size = non_moving_space_capacity;
Mathieu Chartierf75dce42019-04-08 09:36:23 -0700412 } else if (foreground_collector_type_ != kCollectorTypeCC && is_zygote) {
Vladimir Marko4df2d802018-09-27 16:42:44 +0000413 heap_reservation_size = capacity_;
414 }
Vladimir Markod44d7032018-08-30 13:02:31 +0100415 heap_reservation_size = RoundUp(heap_reservation_size, kPageSize);
416 // Load image space(s).
417 std::vector<std::unique_ptr<space::ImageSpace>> boot_image_spaces;
418 MemMap heap_reservation;
Vladimir Markod1908512018-11-22 14:57:28 +0000419 if (space::ImageSpace::LoadBootImage(boot_class_path,
420 boot_class_path_locations,
421 image_file_name,
Vladimir Markod44d7032018-08-30 13:02:31 +0100422 image_instruction_set,
Vladimir Marko3364d182019-03-13 13:55:01 +0000423 runtime->ShouldRelocate(),
424 /*executable=*/ !runtime->IsAotCompiler(),
Vladimir Markod44d7032018-08-30 13:02:31 +0100425 heap_reservation_size,
426 &boot_image_spaces,
427 &heap_reservation)) {
428 DCHECK_EQ(heap_reservation_size, heap_reservation.IsValid() ? heap_reservation.Size() : 0u);
429 DCHECK(!boot_image_spaces.empty());
430 request_begin = boot_image_spaces.back()->GetImageHeader().GetOatFileEnd();
431 DCHECK(!heap_reservation.IsValid() || request_begin == heap_reservation.Begin())
432 << "request_begin=" << static_cast<const void*>(request_begin)
433 << " heap_reservation.Begin()=" << static_cast<const void*>(heap_reservation.Begin());
434 for (std::unique_ptr<space::ImageSpace>& space : boot_image_spaces) {
435 boot_image_spaces_.push_back(space.get());
436 AddSpace(space.release());
437 }
Vladimir Marko7cde4582019-07-05 13:26:11 +0100438 boot_images_start_address_ = PointerToLowMemUInt32(boot_image_spaces_.front()->Begin());
439 uint32_t boot_images_end =
440 PointerToLowMemUInt32(boot_image_spaces_.back()->GetImageHeader().GetOatFileEnd());
441 boot_images_size_ = boot_images_end - boot_images_start_address_;
442 if (kIsDebugBuild) {
443 VerifyBootImagesContiguity(boot_image_spaces_);
444 }
Vladimir Markod44d7032018-08-30 13:02:31 +0100445 } else {
446 if (foreground_collector_type_ == kCollectorTypeCC) {
447 // Need to use a low address so that we can allocate a contiguous 2 * Xmx space
448 // when there's no image (dex2oat for target).
449 request_begin = kPreferredAllocSpaceBegin;
450 }
451 // Gross hack to make dex2oat deterministic.
452 if (foreground_collector_type_ == kCollectorTypeMS && Runtime::Current()->IsAotCompiler()) {
453 // Currently only enabled for MS collector since that is what the deterministic dex2oat uses.
454 // b/26849108
455 request_begin = reinterpret_cast<uint8_t*>(kAllocSpaceBeginForDeterministicAoT);
456 }
457 }
458
459 /*
460 requested_alloc_space_begin -> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
461 +- nonmoving space (non_moving_space_capacity)+-
462 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
463 +-????????????????????????????????????????????+-
464 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
465 +-main alloc space / bump space 1 (capacity_) +-
466 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
467 +-????????????????????????????????????????????+-
468 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
469 +-main alloc space2 / bump space 2 (capacity_)+-
470 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
471 */
472
Vladimir Markoc34bebf2018-08-16 16:12:49 +0100473 MemMap main_mem_map_1;
474 MemMap main_mem_map_2;
Andreas Gampeace0dc12016-01-20 13:33:13 -0800475
Mathieu Chartierb363f662014-07-16 13:28:58 -0700476 std::string error_str;
Vladimir Markoc34bebf2018-08-16 16:12:49 +0100477 MemMap non_moving_space_mem_map;
Mathieu Chartierb363f662014-07-16 13:28:58 -0700478 if (separate_non_moving_space) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800479 ScopedTrace trace2("Create separate non moving space");
Mathieu Chartier7247af52014-11-19 10:51:42 -0800480 // If we are the zygote, the non moving space becomes the zygote space when we run
481 // PreZygoteFork the first time. In this case, call the map "zygote space" since we can't
482 // rename the mem map later.
Roland Levillain5e8d5f02016-10-18 18:03:43 +0100483 const char* space_name = is_zygote ? kZygoteSpaceName : kNonMovingSpaceName;
Mathieu Chartierb363f662014-07-16 13:28:58 -0700484 // Reserve the non moving mem map before the other two since it needs to be at a specific
485 // address.
Vladimir Markod44d7032018-08-30 13:02:31 +0100486 DCHECK_EQ(heap_reservation.IsValid(), !boot_image_spaces_.empty());
487 if (heap_reservation.IsValid()) {
488 non_moving_space_mem_map = heap_reservation.RemapAtEnd(
489 heap_reservation.Begin(), space_name, PROT_READ | PROT_WRITE, &error_str);
490 } else {
491 non_moving_space_mem_map = MapAnonymousPreferredAddress(
492 space_name, request_begin, non_moving_space_capacity, &error_str);
493 }
Vladimir Markoc34bebf2018-08-16 16:12:49 +0100494 CHECK(non_moving_space_mem_map.IsValid()) << error_str;
Vladimir Markod44d7032018-08-30 13:02:31 +0100495 DCHECK(!heap_reservation.IsValid());
Mathieu Chartierc44ce2e2014-08-25 16:32:41 -0700496 // Try to reserve virtual memory at a lower address if we have a separate non moving space.
Hiroshi Yamauchi3c3c4a12017-02-21 16:49:59 -0800497 request_begin = kPreferredAllocSpaceBegin + non_moving_space_capacity;
Mathieu Chartierb363f662014-07-16 13:28:58 -0700498 }
Hiroshi Yamauchi3dbf2342015-03-17 16:01:11 -0700499 // Attempt to create 2 mem maps at or after the requested begin.
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800500 if (foreground_collector_type_ != kCollectorTypeCC) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800501 ScopedTrace trace2("Create main mem map");
Mathieu Chartierf75dce42019-04-08 09:36:23 -0700502 if (separate_non_moving_space || !is_zygote) {
Vladimir Markoc34bebf2018-08-16 16:12:49 +0100503 main_mem_map_1 = MapAnonymousPreferredAddress(
504 kMemMapSpaceName[0], request_begin, capacity_, &error_str);
Hiroshi Yamauchi3dbf2342015-03-17 16:01:11 -0700505 } else {
Mathieu Chartierf75dce42019-04-08 09:36:23 -0700506 // If no separate non-moving space and we are the zygote, the main space must come right after
507 // the image space to avoid a gap. This is required since we want the zygote space to be
508 // adjacent to the image space.
Vladimir Markod44d7032018-08-30 13:02:31 +0100509 DCHECK_EQ(heap_reservation.IsValid(), !boot_image_spaces_.empty());
510 main_mem_map_1 = MemMap::MapAnonymous(
511 kMemMapSpaceName[0],
512 request_begin,
513 capacity_,
514 PROT_READ | PROT_WRITE,
Andreas Gampe98ea9d92018-10-19 14:06:15 -0700515 /* low_4gb= */ true,
516 /* reuse= */ false,
Vladimir Markod44d7032018-08-30 13:02:31 +0100517 heap_reservation.IsValid() ? &heap_reservation : nullptr,
518 &error_str);
Hiroshi Yamauchi3dbf2342015-03-17 16:01:11 -0700519 }
Vladimir Markoc34bebf2018-08-16 16:12:49 +0100520 CHECK(main_mem_map_1.IsValid()) << error_str;
Vladimir Markod44d7032018-08-30 13:02:31 +0100521 DCHECK(!heap_reservation.IsValid());
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800522 }
Mathieu Chartierb363f662014-07-16 13:28:58 -0700523 if (support_homogeneous_space_compaction ||
524 background_collector_type_ == kCollectorTypeSS ||
525 foreground_collector_type_ == kCollectorTypeSS) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800526 ScopedTrace trace2("Create main mem map 2");
Vladimir Markoc34bebf2018-08-16 16:12:49 +0100527 main_mem_map_2 = MapAnonymousPreferredAddress(
528 kMemMapSpaceName[1], main_mem_map_1.End(), capacity_, &error_str);
529 CHECK(main_mem_map_2.IsValid()) << error_str;
Mathieu Chartierb363f662014-07-16 13:28:58 -0700530 }
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800531
Mathieu Chartierb363f662014-07-16 13:28:58 -0700532 // Create the non moving space first so that bitmaps don't take up the address range.
533 if (separate_non_moving_space) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800534 ScopedTrace trace2("Add non moving space");
Mathieu Chartier31f44142014-04-08 14:40:03 -0700535 // Non moving space is always dlmalloc since we currently don't have support for multiple
Zuo Wangf37a88b2014-07-10 04:26:41 -0700536 // active rosalloc spaces.
Vladimir Markoc34bebf2018-08-16 16:12:49 +0100537 const size_t size = non_moving_space_mem_map.Size();
Vladimir Markobd5e5f62018-09-07 11:21:34 +0100538 const void* non_moving_space_mem_map_begin = non_moving_space_mem_map.Begin();
Vladimir Markoc34bebf2018-08-16 16:12:49 +0100539 non_moving_space_ = space::DlMallocSpace::CreateFromMemMap(std::move(non_moving_space_mem_map),
540 "zygote / non moving space",
541 kDefaultStartingSize,
542 initial_size,
543 size,
544 size,
Andreas Gampe98ea9d92018-10-19 14:06:15 -0700545 /* can_move_objects= */ false);
Mathieu Chartierb363f662014-07-16 13:28:58 -0700546 CHECK(non_moving_space_ != nullptr) << "Failed creating non moving space "
Vladimir Markobd5e5f62018-09-07 11:21:34 +0100547 << non_moving_space_mem_map_begin;
548 non_moving_space_->SetFootprintLimit(non_moving_space_->Capacity());
Mathieu Chartierb363f662014-07-16 13:28:58 -0700549 AddSpace(non_moving_space_);
550 }
551 // Create other spaces based on whether or not we have a moving GC.
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800552 if (foreground_collector_type_ == kCollectorTypeCC) {
Hiroshi Yamauchi3c3c4a12017-02-21 16:49:59 -0800553 CHECK(separate_non_moving_space);
Roland Levillain8f7ea9a2018-01-26 17:27:59 +0000554 // Reserve twice the capacity, to allow evacuating every region for explicit GCs.
Vladimir Markoc34bebf2018-08-16 16:12:49 +0100555 MemMap region_space_mem_map =
556 space::RegionSpace::CreateMemMap(kRegionSpaceName, capacity_ * 2, request_begin);
557 CHECK(region_space_mem_map.IsValid()) << "No region space mem map";
Albert Mingkun Yang0b4d1462018-11-29 13:25:35 +0000558 region_space_ = space::RegionSpace::Create(
559 kRegionSpaceName, std::move(region_space_mem_map), use_generational_cc_);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800560 AddSpace(region_space_);
Mathieu Chartierf75dce42019-04-08 09:36:23 -0700561 } else if (IsMovingGc(foreground_collector_type_)) {
Mathieu Chartierb363f662014-07-16 13:28:58 -0700562 // Create bump pointer spaces.
563 // We only to create the bump pointer if the foreground collector is a compacting GC.
564 // TODO: Place bump-pointer spaces somewhere to minimize size of card table.
565 bump_pointer_space_ = space::BumpPointerSpace::CreateFromMemMap("Bump pointer space 1",
Vladimir Markoc34bebf2018-08-16 16:12:49 +0100566 std::move(main_mem_map_1));
Mathieu Chartierb363f662014-07-16 13:28:58 -0700567 CHECK(bump_pointer_space_ != nullptr) << "Failed to create bump pointer space";
568 AddSpace(bump_pointer_space_);
569 temp_space_ = space::BumpPointerSpace::CreateFromMemMap("Bump pointer space 2",
Vladimir Markoc34bebf2018-08-16 16:12:49 +0100570 std::move(main_mem_map_2));
Mathieu Chartierb363f662014-07-16 13:28:58 -0700571 CHECK(temp_space_ != nullptr) << "Failed to create bump pointer space";
572 AddSpace(temp_space_);
573 CHECK(separate_non_moving_space);
Hiroshi Yamauchi5ccd4982014-03-11 12:19:04 -0700574 } else {
Vladimir Markoc34bebf2018-08-16 16:12:49 +0100575 CreateMainMallocSpace(std::move(main_mem_map_1), initial_size, growth_limit_, capacity_);
Mathieu Chartierb363f662014-07-16 13:28:58 -0700576 CHECK(main_space_ != nullptr);
577 AddSpace(main_space_);
578 if (!separate_non_moving_space) {
Zuo Wangf37a88b2014-07-10 04:26:41 -0700579 non_moving_space_ = main_space_;
Mathieu Chartierb363f662014-07-16 13:28:58 -0700580 CHECK(!non_moving_space_->CanMoveObjects());
581 }
Mathieu Chartierf75dce42019-04-08 09:36:23 -0700582 if (main_mem_map_2.IsValid()) {
Mathieu Chartierb363f662014-07-16 13:28:58 -0700583 const char* name = kUseRosAlloc ? kRosAllocSpaceName[1] : kDlMallocSpaceName[1];
Vladimir Markoc34bebf2018-08-16 16:12:49 +0100584 main_space_backup_.reset(CreateMallocSpaceFromMemMap(std::move(main_mem_map_2),
585 initial_size,
586 growth_limit_,
587 capacity_,
588 name,
Andreas Gampe98ea9d92018-10-19 14:06:15 -0700589 /* can_move_objects= */ true));
Mathieu Chartierb363f662014-07-16 13:28:58 -0700590 CHECK(main_space_backup_.get() != nullptr);
591 // Add the space so its accounted for in the heap_begin and heap_end.
592 AddSpace(main_space_backup_.get());
Zuo Wangf37a88b2014-07-10 04:26:41 -0700593 }
Hiroshi Yamauchi5ccd4982014-03-11 12:19:04 -0700594 }
Mathieu Chartier31f44142014-04-08 14:40:03 -0700595 CHECK(non_moving_space_ != nullptr);
Mathieu Chartierb363f662014-07-16 13:28:58 -0700596 CHECK(!non_moving_space_->CanMoveObjects());
Mathieu Chartiereb5710e2013-07-25 15:19:42 -0700597 // Allocate the large object space.
Igor Murashkinaaebaa02015-01-26 10:55:53 -0800598 if (large_object_space_type == space::LargeObjectSpaceType::kFreeList) {
Vladimir Marko11306592018-10-26 14:22:59 +0100599 large_object_space_ = space::FreeListSpace::Create("free list large object space", capacity_);
Mathieu Chartier2dbe6272014-09-16 10:43:23 -0700600 CHECK(large_object_space_ != nullptr) << "Failed to create large object space";
Igor Murashkinaaebaa02015-01-26 10:55:53 -0800601 } else if (large_object_space_type == space::LargeObjectSpaceType::kMap) {
Mathieu Chartier2dbe6272014-09-16 10:43:23 -0700602 large_object_space_ = space::LargeObjectMapSpace::Create("mem map large object space");
603 CHECK(large_object_space_ != nullptr) << "Failed to create large object space";
Mathieu Chartiereb5710e2013-07-25 15:19:42 -0700604 } else {
Mathieu Chartier2dbe6272014-09-16 10:43:23 -0700605 // Disable the large object space by making the cutoff excessively large.
606 large_object_threshold_ = std::numeric_limits<size_t>::max();
607 large_object_space_ = nullptr;
Mathieu Chartiereb5710e2013-07-25 15:19:42 -0700608 }
Mathieu Chartier2dbe6272014-09-16 10:43:23 -0700609 if (large_object_space_ != nullptr) {
610 AddSpace(large_object_space_);
611 }
Ian Rogers1d54e732013-05-02 21:10:01 -0700612 // Compute heap capacity. Continuous spaces are sorted in order of Begin().
Mathieu Chartier590fee92013-09-13 13:46:47 -0700613 CHECK(!continuous_spaces_.empty());
614 // Relies on the spaces being sorted.
Ian Rogers13735952014-10-08 12:43:28 -0700615 uint8_t* heap_begin = continuous_spaces_.front()->Begin();
616 uint8_t* heap_end = continuous_spaces_.back()->Limit();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700617 size_t heap_capacity = heap_end - heap_begin;
Mathieu Chartierb363f662014-07-16 13:28:58 -0700618 // Remove the main backup space since it slows down the GC to have unused extra spaces.
Mathieu Chartier0310da52014-12-01 13:40:48 -0800619 // TODO: Avoid needing to do this.
Mathieu Chartierb363f662014-07-16 13:28:58 -0700620 if (main_space_backup_.get() != nullptr) {
621 RemoveSpace(main_space_backup_.get());
622 }
Elliott Hughes6c9c06d2011-11-07 16:43:47 -0800623 // Allocate the card table.
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800624 // We currently don't support dynamically resizing the card table.
625 // Since we don't know where in the low_4gb the app image will be located, make the card table
626 // cover the whole low_4gb. TODO: Extend the card table in AddSpace.
627 UNUSED(heap_capacity);
Roland Levillain8f7ea9a2018-01-26 17:27:59 +0000628 // Start at 4 KB, we can be sure there are no spaces mapped this low since the address range is
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800629 // reserved by the kernel.
630 static constexpr size_t kMinHeapAddress = 4 * KB;
631 card_table_.reset(accounting::CardTable::Create(reinterpret_cast<uint8_t*>(kMinHeapAddress),
632 4 * GB - kMinHeapAddress));
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700633 CHECK(card_table_.get() != nullptr) << "Failed to create card table";
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800634 if (foreground_collector_type_ == kCollectorTypeCC && kUseTableLookupReadBarrier) {
635 rb_table_.reset(new accounting::ReadBarrierTable());
636 DCHECK(rb_table_->IsAllCleared());
637 }
Jeff Haodcdc85b2015-12-04 14:06:18 -0800638 if (HasBootImageSpace()) {
Mathieu Chartier4858a932015-01-23 13:18:53 -0800639 // Don't add the image mod union table if we are running without an image, this can crash if
640 // we use the CardCache implementation.
Jeff Haodcdc85b2015-12-04 14:06:18 -0800641 for (space::ImageSpace* image_space : GetBootImageSpaces()) {
642 accounting::ModUnionTable* mod_union_table = new accounting::ModUnionTableToZygoteAllocspace(
643 "Image mod-union table", this, image_space);
644 CHECK(mod_union_table != nullptr) << "Failed to create image mod-union table";
645 AddModUnionTable(mod_union_table);
646 }
Mathieu Chartier4858a932015-01-23 13:18:53 -0800647 }
Mathieu Chartier96bcd452014-06-17 09:50:02 -0700648 if (collector::SemiSpace::kUseRememberedSet && non_moving_space_ != main_space_) {
Hiroshi Yamauchi38e68e92014-03-07 13:59:08 -0800649 accounting::RememberedSet* non_moving_space_rem_set =
650 new accounting::RememberedSet("Non-moving space remembered set", this, non_moving_space_);
651 CHECK(non_moving_space_rem_set != nullptr) << "Failed to create non-moving space remembered set";
652 AddRememberedSet(non_moving_space_rem_set);
653 }
Mathieu Chartierb363f662014-07-16 13:28:58 -0700654 // TODO: Count objects in the image space here?
Orion Hodson88591fe2018-03-06 13:35:43 +0000655 num_bytes_allocated_.store(0, std::memory_order_relaxed);
Mathieu Chartierc1790162014-05-23 10:54:50 -0700656 mark_stack_.reset(accounting::ObjectStack::Create("mark stack", kDefaultMarkStackSize,
657 kDefaultMarkStackSize));
658 const size_t alloc_stack_capacity = max_allocation_stack_size_ + kAllocationStackReserveSize;
659 allocation_stack_.reset(accounting::ObjectStack::Create(
660 "allocation stack", max_allocation_stack_size_, alloc_stack_capacity));
661 live_stack_.reset(accounting::ObjectStack::Create(
662 "live stack", max_allocation_stack_size_, alloc_stack_capacity));
Mathieu Chartier65db8802012-11-20 12:36:46 -0800663 // It's still too early to take a lock because there are no threads yet, but we can create locks
664 // now. We don't create it earlier to make it clear that you can't use locks during heap
665 // initialization.
Mathieu Chartierfd678be2012-08-30 14:50:54 -0700666 gc_complete_lock_ = new Mutex("GC complete lock");
Ian Rogersc604d732012-10-14 16:09:54 -0700667 gc_complete_cond_.reset(new ConditionVariable("GC complete condition variable",
668 *gc_complete_lock_));
Richard Uhlercaaa2b02017-02-01 09:54:17 +0000669
Hiroshi Yamauchi76f55b02015-08-21 16:10:39 -0700670 thread_flip_lock_ = new Mutex("GC thread flip lock");
671 thread_flip_cond_.reset(new ConditionVariable("GC thread flip condition variable",
672 *thread_flip_lock_));
Mathieu Chartiera5eae692014-12-17 17:56:03 -0800673 task_processor_.reset(new TaskProcessor());
Mathieu Chartier3cf22532015-07-09 15:15:09 -0700674 reference_processor_.reset(new ReferenceProcessor());
Mathieu Chartiera5eae692014-12-17 17:56:03 -0800675 pending_task_lock_ = new Mutex("Pending task lock");
Hans Boehmc220f982018-10-12 16:15:45 -0700676 if (ignore_target_footprint_) {
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700677 SetIdealFootprint(std::numeric_limits<size_t>::max());
Mathieu Chartier590fee92013-09-13 13:46:47 -0700678 concurrent_start_bytes_ = std::numeric_limits<size_t>::max();
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700679 }
Hans Boehmc220f982018-10-12 16:15:45 -0700680 CHECK_NE(target_footprint_.load(std::memory_order_relaxed), 0U);
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800681 // Create our garbage collectors.
Mathieu Chartier50482232013-11-21 11:48:14 -0800682 for (size_t i = 0; i < 2; ++i) {
683 const bool concurrent = i != 0;
Mathieu Chartierdfe30832015-03-06 15:28:34 -0800684 if ((MayUseCollector(kCollectorTypeCMS) && concurrent) ||
685 (MayUseCollector(kCollectorTypeMS) && !concurrent)) {
686 garbage_collectors_.push_back(new collector::MarkSweep(this, concurrent));
687 garbage_collectors_.push_back(new collector::PartialMarkSweep(this, concurrent));
688 garbage_collectors_.push_back(new collector::StickyMarkSweep(this, concurrent));
689 }
Mathieu Chartier50482232013-11-21 11:48:14 -0800690 }
Mathieu Chartier50482232013-11-21 11:48:14 -0800691 if (kMovingCollector) {
Mathieu Chartierf75dce42019-04-08 09:36:23 -0700692 if (MayUseCollector(kCollectorTypeSS) ||
Mathieu Chartierdfe30832015-03-06 15:28:34 -0800693 MayUseCollector(kCollectorTypeHomogeneousSpaceCompact) ||
694 use_homogeneous_space_compaction_for_oom_) {
Mathieu Chartierf75dce42019-04-08 09:36:23 -0700695 semi_space_collector_ = new collector::SemiSpace(this);
Mathieu Chartierdfe30832015-03-06 15:28:34 -0800696 garbage_collectors_.push_back(semi_space_collector_);
697 }
698 if (MayUseCollector(kCollectorTypeCC)) {
Mathieu Chartier56fe2582016-07-14 13:30:03 -0700699 concurrent_copying_collector_ = new collector::ConcurrentCopying(this,
Andreas Gampe98ea9d92018-10-19 14:06:15 -0700700 /*young_gen=*/false,
Albert Mingkun Yang0b4d1462018-11-29 13:25:35 +0000701 use_generational_cc_,
Mathieu Chartier56fe2582016-07-14 13:30:03 -0700702 "",
703 measure_gc_performance);
Albert Mingkun Yang0b4d1462018-11-29 13:25:35 +0000704 if (use_generational_cc_) {
Mathieu Chartier8d1a9962016-08-17 16:39:45 -0700705 young_concurrent_copying_collector_ = new collector::ConcurrentCopying(
706 this,
Andreas Gampe98ea9d92018-10-19 14:06:15 -0700707 /*young_gen=*/true,
Albert Mingkun Yang0b4d1462018-11-29 13:25:35 +0000708 use_generational_cc_,
Mathieu Chartier8d1a9962016-08-17 16:39:45 -0700709 "young",
710 measure_gc_performance);
711 }
Lokesh Gidra45aa2af2020-12-08 15:06:36 -0800712 active_concurrent_copying_collector_.store(concurrent_copying_collector_,
713 std::memory_order_relaxed);
Hiroshi Yamauchi4af14172016-10-25 11:55:10 -0700714 DCHECK(region_space_ != nullptr);
715 concurrent_copying_collector_->SetRegionSpace(region_space_);
Albert Mingkun Yang0b4d1462018-11-29 13:25:35 +0000716 if (use_generational_cc_) {
Mathieu Chartier8d1a9962016-08-17 16:39:45 -0700717 young_concurrent_copying_collector_->SetRegionSpace(region_space_);
Lokesh Gidra1c34b712018-12-18 13:41:58 -0800718 // At this point, non-moving space should be created.
719 DCHECK(non_moving_space_ != nullptr);
720 concurrent_copying_collector_->CreateInterRegionRefBitmaps();
Mathieu Chartier8d1a9962016-08-17 16:39:45 -0700721 }
Mathieu Chartierdfe30832015-03-06 15:28:34 -0800722 garbage_collectors_.push_back(concurrent_copying_collector_);
Albert Mingkun Yang0b4d1462018-11-29 13:25:35 +0000723 if (use_generational_cc_) {
Mathieu Chartier8d1a9962016-08-17 16:39:45 -0700724 garbage_collectors_.push_back(young_concurrent_copying_collector_);
725 }
Mathieu Chartierdfe30832015-03-06 15:28:34 -0800726 }
Mathieu Chartier0325e622012-09-05 14:22:51 -0700727 }
Jeff Haodcdc85b2015-12-04 14:06:18 -0800728 if (!GetBootImageSpaces().empty() && non_moving_space_ != nullptr &&
Mathieu Chartierf75dce42019-04-08 09:36:23 -0700729 (is_zygote || separate_non_moving_space)) {
Mathieu Chartierb363f662014-07-16 13:28:58 -0700730 // 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 -0700731 // immune region won't break (eg. due to a large object allocated in the gap). This is only
Mathieu Chartierf75dce42019-04-08 09:36:23 -0700732 // required when we're the zygote.
Mathieu Chartiera06ba052016-01-06 13:51:52 -0800733 // Space with smallest Begin().
734 space::ImageSpace* first_space = nullptr;
735 for (space::ImageSpace* space : boot_image_spaces_) {
736 if (first_space == nullptr || space->Begin() < first_space->Begin()) {
737 first_space = space;
738 }
739 }
Vladimir Markoc34bebf2018-08-16 16:12:49 +0100740 bool no_gap = MemMap::CheckNoGaps(*first_space->GetMemMap(), *non_moving_space_->GetMemMap());
Hiroshi Yamauchi3eed93d2014-06-04 11:43:59 -0700741 if (!no_gap) {
David Srbecky5dedb802015-06-17 00:08:02 +0100742 PrintFileToLog("/proc/self/maps", LogSeverity::ERROR);
Andreas Gampe98ea9d92018-10-19 14:06:15 -0700743 MemMap::DumpMaps(LOG_STREAM(ERROR), /* terse= */ true);
Mathieu Chartierc7853442015-03-27 14:35:38 -0700744 LOG(FATAL) << "There's a gap between the image space and the non-moving space";
Hiroshi Yamauchi3eed93d2014-06-04 11:43:59 -0700745 }
746 }
Wessam Hassaneinb5a10be2020-11-11 16:42:52 -0800747 // Perfetto Java Heap Profiler Support.
748 if (runtime->IsPerfettoJavaHeapStackProfEnabled()) {
749 // Perfetto Plugin is loaded and enabled, initialize the Java Heap Profiler.
750 InitPerfettoJavaHeapProf();
751 } else {
752 // Disable the Java Heap Profiler.
753 GetHeapSampler().DisableHeapSampler(/*disable_ptr=*/nullptr, /*disable_info_ptr=*/nullptr);
754 }
755
Mathieu Chartier31000802015-06-14 14:14:37 -0700756 instrumentation::Instrumentation* const instrumentation = runtime->GetInstrumentation();
757 if (gc_stress_mode_) {
758 backtrace_lock_ = new Mutex("GC complete lock");
759 }
Evgenii Stepanov1e133742015-05-20 12:30:59 -0700760 if (is_running_on_memory_tool_ || gc_stress_mode_) {
Mathieu Chartier31000802015-06-14 14:14:37 -0700761 instrumentation->InstrumentQuickAllocEntryPoints();
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -0700762 }
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800763 if (VLOG_IS_ON(heap) || VLOG_IS_ON(startup)) {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800764 LOG(INFO) << "Heap() exiting";
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700765 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700766}
767
Vladimir Markoc34bebf2018-08-16 16:12:49 +0100768MemMap Heap::MapAnonymousPreferredAddress(const char* name,
769 uint8_t* request_begin,
770 size_t capacity,
771 std::string* out_error_str) {
Mathieu Chartierb363f662014-07-16 13:28:58 -0700772 while (true) {
Vladimir Markoc34bebf2018-08-16 16:12:49 +0100773 MemMap map = MemMap::MapAnonymous(name,
774 request_begin,
775 capacity,
776 PROT_READ | PROT_WRITE,
Vladimir Marko11306592018-10-26 14:22:59 +0100777 /*low_4gb=*/ true,
778 /*reuse=*/ false,
779 /*reservation=*/ nullptr,
Vladimir Markoc34bebf2018-08-16 16:12:49 +0100780 out_error_str);
781 if (map.IsValid() || request_begin == nullptr) {
Mathieu Chartierb363f662014-07-16 13:28:58 -0700782 return map;
783 }
784 // Retry a second time with no specified request begin.
785 request_begin = nullptr;
786 }
Mathieu Chartierb363f662014-07-16 13:28:58 -0700787}
788
Mathieu Chartierdfe30832015-03-06 15:28:34 -0800789bool Heap::MayUseCollector(CollectorType type) const {
790 return foreground_collector_type_ == type || background_collector_type_ == type;
791}
792
Vladimir Markoc34bebf2018-08-16 16:12:49 +0100793space::MallocSpace* Heap::CreateMallocSpaceFromMemMap(MemMap&& mem_map,
Mathieu Chartiera4f6af92015-08-11 17:35:25 -0700794 size_t initial_size,
795 size_t growth_limit,
796 size_t capacity,
797 const char* name,
798 bool can_move_objects) {
Zuo Wangf37a88b2014-07-10 04:26:41 -0700799 space::MallocSpace* malloc_space = nullptr;
800 if (kUseRosAlloc) {
801 // Create rosalloc space.
Vladimir Markoc34bebf2018-08-16 16:12:49 +0100802 malloc_space = space::RosAllocSpace::CreateFromMemMap(std::move(mem_map),
803 name,
804 kDefaultStartingSize,
805 initial_size,
806 growth_limit,
807 capacity,
808 low_memory_mode_,
809 can_move_objects);
Zuo Wangf37a88b2014-07-10 04:26:41 -0700810 } else {
Vladimir Markoc34bebf2018-08-16 16:12:49 +0100811 malloc_space = space::DlMallocSpace::CreateFromMemMap(std::move(mem_map),
812 name,
813 kDefaultStartingSize,
814 initial_size,
815 growth_limit,
816 capacity,
Zuo Wangf37a88b2014-07-10 04:26:41 -0700817 can_move_objects);
818 }
819 if (collector::SemiSpace::kUseRememberedSet) {
820 accounting::RememberedSet* rem_set =
821 new accounting::RememberedSet(std::string(name) + " remembered set", this, malloc_space);
822 CHECK(rem_set != nullptr) << "Failed to create main space remembered set";
823 AddRememberedSet(rem_set);
824 }
825 CHECK(malloc_space != nullptr) << "Failed to create " << name;
826 malloc_space->SetFootprintLimit(malloc_space->Capacity());
827 return malloc_space;
828}
829
Vladimir Markoc34bebf2018-08-16 16:12:49 +0100830void Heap::CreateMainMallocSpace(MemMap&& mem_map,
831 size_t initial_size,
832 size_t growth_limit,
Mathieu Chartier31f44142014-04-08 14:40:03 -0700833 size_t capacity) {
834 // Is background compaction is enabled?
835 bool can_move_objects = IsMovingGc(background_collector_type_) !=
Zuo Wangf37a88b2014-07-10 04:26:41 -0700836 IsMovingGc(foreground_collector_type_) || use_homogeneous_space_compaction_for_oom_;
Mathieu Chartier31f44142014-04-08 14:40:03 -0700837 // If we are the zygote and don't yet have a zygote space, it means that the zygote fork will
838 // happen in the future. If this happens and we have kCompactZygote enabled we wish to compact
839 // from the main space to the zygote space. If background compaction is enabled, always pass in
840 // that we can move objets.
841 if (kCompactZygote && Runtime::Current()->IsZygote() && !can_move_objects) {
842 // After the zygote we want this to be false if we don't have background compaction enabled so
843 // that getting primitive array elements is faster.
Mathieu Chartierf75dce42019-04-08 09:36:23 -0700844 can_move_objects = !HasZygoteSpace();
Mathieu Chartier31f44142014-04-08 14:40:03 -0700845 }
Mathieu Chartier96bcd452014-06-17 09:50:02 -0700846 if (collector::SemiSpace::kUseRememberedSet && main_space_ != nullptr) {
847 RemoveRememberedSet(main_space_);
848 }
Zuo Wangf37a88b2014-07-10 04:26:41 -0700849 const char* name = kUseRosAlloc ? kRosAllocSpaceName[0] : kDlMallocSpaceName[0];
Vladimir Markoc34bebf2018-08-16 16:12:49 +0100850 main_space_ = CreateMallocSpaceFromMemMap(std::move(mem_map),
851 initial_size,
852 growth_limit,
853 capacity, name,
Zuo Wangf37a88b2014-07-10 04:26:41 -0700854 can_move_objects);
855 SetSpaceAsDefault(main_space_);
Mathieu Chartier31f44142014-04-08 14:40:03 -0700856 VLOG(heap) << "Created main space " << main_space_;
857}
858
Mathieu Chartier50482232013-11-21 11:48:14 -0800859void Heap::ChangeAllocator(AllocatorType allocator) {
Mathieu Chartier50482232013-11-21 11:48:14 -0800860 if (current_allocator_ != allocator) {
Mathieu Chartierd8891782014-03-02 13:28:37 -0800861 // These two allocators are only used internally and don't have any entrypoints.
862 CHECK_NE(allocator, kAllocatorTypeLOS);
863 CHECK_NE(allocator, kAllocatorTypeNonMoving);
Mathieu Chartier50482232013-11-21 11:48:14 -0800864 current_allocator_ = allocator;
Mathieu Chartierd8891782014-03-02 13:28:37 -0800865 MutexLock mu(nullptr, *Locks::runtime_shutdown_lock_);
Mathieu Chartier50482232013-11-21 11:48:14 -0800866 SetQuickAllocEntryPointsAllocator(current_allocator_);
867 Runtime::Current()->GetInstrumentation()->ResetQuickAllocEntryPoints();
868 }
869}
870
Mathieu Chartier590fee92013-09-13 13:46:47 -0700871bool Heap::IsCompilingBoot() const {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800872 if (!Runtime::Current()->IsAotCompiler()) {
Alex Light64ad14d2014-08-19 14:23:13 -0700873 return false;
874 }
Mathieu Chartiera9d82fe2016-01-25 20:06:11 -0800875 ScopedObjectAccess soa(Thread::Current());
Mathieu Chartier590fee92013-09-13 13:46:47 -0700876 for (const auto& space : continuous_spaces_) {
Mathieu Chartier4e305412014-02-19 10:54:44 -0800877 if (space->IsImageSpace() || space->IsZygoteSpace()) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700878 return false;
879 }
880 }
881 return true;
882}
883
Mathieu Chartier1d27b342014-01-28 12:51:09 -0800884void Heap::IncrementDisableMovingGC(Thread* self) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700885 // Need to do this holding the lock to prevent races where the GC is about to run / running when
886 // we attempt to disable it.
Mathieu Chartiercaa82d62014-02-02 16:51:17 -0800887 ScopedThreadStateChange tsc(self, kWaitingForGcToComplete);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700888 MutexLock mu(self, *gc_complete_lock_);
Mathieu Chartier1d27b342014-01-28 12:51:09 -0800889 ++disable_moving_gc_count_;
Mathieu Chartier31f44142014-04-08 14:40:03 -0700890 if (IsMovingGc(collector_type_running_)) {
Mathieu Chartier89a201e2014-05-02 10:27:26 -0700891 WaitForGcToCompleteLocked(kGcCauseDisableMovingGc, self);
Mathieu Chartierd5a89ee2014-01-31 09:55:13 -0800892 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700893}
894
Mathieu Chartier1d27b342014-01-28 12:51:09 -0800895void Heap::DecrementDisableMovingGC(Thread* self) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700896 MutexLock mu(self, *gc_complete_lock_);
Mathieu Chartierb735bd92015-06-24 17:04:17 -0700897 CHECK_GT(disable_moving_gc_count_, 0U);
Mathieu Chartier1d27b342014-01-28 12:51:09 -0800898 --disable_moving_gc_count_;
Mathieu Chartier590fee92013-09-13 13:46:47 -0700899}
900
Hiroshi Yamauchi76f55b02015-08-21 16:10:39 -0700901void Heap::IncrementDisableThreadFlip(Thread* self) {
902 // Supposed to be called by mutators. If thread_flip_running_ is true, block. Otherwise, go ahead.
903 CHECK(kUseReadBarrier);
Hiroshi Yamauchi20a0be02016-02-19 15:44:06 -0800904 bool is_nested = self->GetDisableThreadFlipCount() > 0;
905 self->IncrementDisableThreadFlipCount();
906 if (is_nested) {
907 // If this is a nested JNI critical section enter, we don't need to wait or increment the global
908 // counter. The global counter is incremented only once for a thread for the outermost enter.
909 return;
910 }
Hiroshi Yamauchi76f55b02015-08-21 16:10:39 -0700911 ScopedThreadStateChange tsc(self, kWaitingForGcThreadFlip);
912 MutexLock mu(self, *thread_flip_lock_);
Alex Light66834462019-04-08 16:28:29 +0000913 thread_flip_cond_->CheckSafeToWait(self);
Hiroshi Yamauchi76f55b02015-08-21 16:10:39 -0700914 bool has_waited = false;
Eric Holk6f5e7292020-02-25 15:10:50 -0800915 uint64_t wait_start = 0;
Hiroshi Yamauchiee235822016-08-19 17:03:27 -0700916 if (thread_flip_running_) {
Eric Holk6f5e7292020-02-25 15:10:50 -0800917 wait_start = NanoTime();
Andreas Gampe9b827ab2017-12-07 19:32:48 -0800918 ScopedTrace trace("IncrementDisableThreadFlip");
Hiroshi Yamauchiee235822016-08-19 17:03:27 -0700919 while (thread_flip_running_) {
920 has_waited = true;
921 thread_flip_cond_->Wait(self);
922 }
Hiroshi Yamauchi76f55b02015-08-21 16:10:39 -0700923 }
924 ++disable_thread_flip_count_;
925 if (has_waited) {
926 uint64_t wait_time = NanoTime() - wait_start;
927 total_wait_time_ += wait_time;
928 if (wait_time > long_pause_log_threshold_) {
929 LOG(INFO) << __FUNCTION__ << " blocked for " << PrettyDuration(wait_time);
930 }
931 }
932}
933
934void Heap::DecrementDisableThreadFlip(Thread* self) {
935 // Supposed to be called by mutators. Decrement disable_thread_flip_count_ and potentially wake up
936 // the GC waiting before doing a thread flip.
937 CHECK(kUseReadBarrier);
Hiroshi Yamauchi20a0be02016-02-19 15:44:06 -0800938 self->DecrementDisableThreadFlipCount();
939 bool is_outermost = self->GetDisableThreadFlipCount() == 0;
940 if (!is_outermost) {
941 // If this is not an outermost JNI critical exit, we don't need to decrement the global counter.
942 // The global counter is decremented only once for a thread for the outermost exit.
943 return;
944 }
Hiroshi Yamauchi76f55b02015-08-21 16:10:39 -0700945 MutexLock mu(self, *thread_flip_lock_);
946 CHECK_GT(disable_thread_flip_count_, 0U);
947 --disable_thread_flip_count_;
Hiroshi Yamauchi20a0be02016-02-19 15:44:06 -0800948 if (disable_thread_flip_count_ == 0) {
949 // Potentially notify the GC thread blocking to begin a thread flip.
950 thread_flip_cond_->Broadcast(self);
951 }
Hiroshi Yamauchi76f55b02015-08-21 16:10:39 -0700952}
953
954void Heap::ThreadFlipBegin(Thread* self) {
955 // Supposed to be called by GC. Set thread_flip_running_ to be true. If disable_thread_flip_count_
956 // > 0, block. Otherwise, go ahead.
957 CHECK(kUseReadBarrier);
958 ScopedThreadStateChange tsc(self, kWaitingForGcThreadFlip);
959 MutexLock mu(self, *thread_flip_lock_);
Alex Light66834462019-04-08 16:28:29 +0000960 thread_flip_cond_->CheckSafeToWait(self);
Hiroshi Yamauchi76f55b02015-08-21 16:10:39 -0700961 bool has_waited = false;
962 uint64_t wait_start = NanoTime();
963 CHECK(!thread_flip_running_);
Hiroshi Yamauchi20a0be02016-02-19 15:44:06 -0800964 // Set this to true before waiting so that frequent JNI critical enter/exits won't starve
965 // GC. This like a writer preference of a reader-writer lock.
Hiroshi Yamauchi76f55b02015-08-21 16:10:39 -0700966 thread_flip_running_ = true;
967 while (disable_thread_flip_count_ > 0) {
968 has_waited = true;
969 thread_flip_cond_->Wait(self);
970 }
971 if (has_waited) {
972 uint64_t wait_time = NanoTime() - wait_start;
973 total_wait_time_ += wait_time;
974 if (wait_time > long_pause_log_threshold_) {
975 LOG(INFO) << __FUNCTION__ << " blocked for " << PrettyDuration(wait_time);
976 }
977 }
978}
979
980void Heap::ThreadFlipEnd(Thread* self) {
981 // Supposed to be called by GC. Set thread_flip_running_ to false and potentially wake up mutators
982 // waiting before doing a JNI critical.
983 CHECK(kUseReadBarrier);
984 MutexLock mu(self, *thread_flip_lock_);
985 CHECK(thread_flip_running_);
986 thread_flip_running_ = false;
Hiroshi Yamauchi20a0be02016-02-19 15:44:06 -0800987 // Potentially notify mutator threads blocking to enter a JNI critical section.
Hiroshi Yamauchi76f55b02015-08-21 16:10:39 -0700988 thread_flip_cond_->Broadcast(self);
989}
990
Lokesh Gidraacd70602019-12-05 17:46:25 -0800991void Heap::GrowHeapOnJankPerceptibleSwitch() {
992 MutexLock mu(Thread::Current(), process_state_update_lock_);
993 size_t orig_target_footprint = target_footprint_.load(std::memory_order_relaxed);
994 if (orig_target_footprint < min_foreground_target_footprint_) {
995 target_footprint_.compare_exchange_strong(orig_target_footprint,
996 min_foreground_target_footprint_,
997 std::memory_order_relaxed);
998 }
999 min_foreground_target_footprint_ = 0;
1000}
1001
Mathieu Chartierf8cb1782016-03-18 18:45:41 -07001002void Heap::UpdateProcessState(ProcessState old_process_state, ProcessState new_process_state) {
1003 if (old_process_state != new_process_state) {
1004 const bool jank_perceptible = new_process_state == kProcessStateJankPerceptible;
Mathieu Chartierf8cb1782016-03-18 18:45:41 -07001005 if (jank_perceptible) {
Mathieu Chartiera5f9de02014-02-28 16:48:42 -08001006 // Transition back to foreground right away to prevent jank.
Mathieu Chartier31f44142014-04-08 14:40:03 -07001007 RequestCollectorTransition(foreground_collector_type_, 0);
Lokesh Gidraacd70602019-12-05 17:46:25 -08001008 GrowHeapOnJankPerceptibleSwitch();
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001009 } else {
Mathieu Chartiera5f9de02014-02-28 16:48:42 -08001010 // Don't delay for debug builds since we may want to stress test the GC.
Zuo Wangf37a88b2014-07-10 04:26:41 -07001011 // If background_collector_type_ is kCollectorTypeHomogeneousSpaceCompact then we have
1012 // special handling which does a homogenous space compaction once but then doesn't transition
Hiroshi Yamauchi60985b72016-08-24 13:53:12 -07001013 // the collector. Similarly, we invoke a full compaction for kCollectorTypeCC but don't
1014 // transition the collector.
Zuo Wangf37a88b2014-07-10 04:26:41 -07001015 RequestCollectorTransition(background_collector_type_,
Andreas Gampeed56b5e2017-10-19 12:58:19 -07001016 kStressCollectorTransition
1017 ? 0
1018 : kCollectorTransitionWait);
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001019 }
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001020 }
Mathieu Chartierca2a24d2013-11-25 15:12:12 -08001021}
1022
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001023void Heap::CreateThreadPool() {
Mathieu Chartier2775ee42013-08-20 17:43:47 -07001024 const size_t num_threads = std::max(parallel_gc_threads_, conc_gc_threads_);
1025 if (num_threads != 0) {
Mathieu Chartierbcd5e9d2013-11-13 14:33:28 -08001026 thread_pool_.reset(new ThreadPool("Heap thread pool", num_threads));
Mathieu Chartier94c32c52013-08-09 11:14:04 -07001027 }
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001028}
1029
Mathieu Chartier590fee92013-09-13 13:46:47 -07001030void Heap::MarkAllocStackAsLive(accounting::ObjectStack* stack) {
Mathieu Chartier00b59152014-07-25 10:13:51 -07001031 space::ContinuousSpace* space1 = main_space_ != nullptr ? main_space_ : non_moving_space_;
1032 space::ContinuousSpace* space2 = non_moving_space_;
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001033 // TODO: Generalize this to n bitmaps?
Mathieu Chartier00b59152014-07-25 10:13:51 -07001034 CHECK(space1 != nullptr);
1035 CHECK(space2 != nullptr);
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001036 MarkAllocStack(space1->GetLiveBitmap(), space2->GetLiveBitmap(),
Mathieu Chartier2dbe6272014-09-16 10:43:23 -07001037 (large_object_space_ != nullptr ? large_object_space_->GetLiveBitmap() : nullptr),
1038 stack);
Mathieu Chartier590fee92013-09-13 13:46:47 -07001039}
1040
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001041void Heap::DeleteThreadPool() {
Mathieu Chartier2775ee42013-08-20 17:43:47 -07001042 thread_pool_.reset(nullptr);
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001043}
1044
Mathieu Chartier1b54f9c2014-04-30 16:45:02 -07001045void Heap::AddSpace(space::Space* space) {
Zuo Wangf37a88b2014-07-10 04:26:41 -07001046 CHECK(space != nullptr);
Mathieu Chartier590fee92013-09-13 13:46:47 -07001047 WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
1048 if (space->IsContinuousSpace()) {
1049 DCHECK(!space->IsDiscontinuousSpace());
1050 space::ContinuousSpace* continuous_space = space->AsContinuousSpace();
1051 // Continuous spaces don't necessarily have bitmaps.
Mathieu Chartiera8e8f9c2014-04-09 14:51:05 -07001052 accounting::ContinuousSpaceBitmap* live_bitmap = continuous_space->GetLiveBitmap();
1053 accounting::ContinuousSpaceBitmap* mark_bitmap = continuous_space->GetMarkBitmap();
Mathieu Chartierecc82302017-02-16 10:20:12 -08001054 // The region space bitmap is not added since VisitObjects visits the region space objects with
1055 // special handling.
1056 if (live_bitmap != nullptr && !space->IsRegionSpace()) {
Mathieu Chartier2796a162014-07-25 11:50:47 -07001057 CHECK(mark_bitmap != nullptr);
Mathieu Chartier590fee92013-09-13 13:46:47 -07001058 live_bitmap_->AddContinuousSpaceBitmap(live_bitmap);
1059 mark_bitmap_->AddContinuousSpaceBitmap(mark_bitmap);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001060 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07001061 continuous_spaces_.push_back(continuous_space);
Mathieu Chartier590fee92013-09-13 13:46:47 -07001062 // Ensure that spaces remain sorted in increasing order of start address.
1063 std::sort(continuous_spaces_.begin(), continuous_spaces_.end(),
1064 [](const space::ContinuousSpace* a, const space::ContinuousSpace* b) {
1065 return a->Begin() < b->Begin();
1066 });
Mathieu Chartier590fee92013-09-13 13:46:47 -07001067 } else {
Mathieu Chartier2796a162014-07-25 11:50:47 -07001068 CHECK(space->IsDiscontinuousSpace());
Mathieu Chartier590fee92013-09-13 13:46:47 -07001069 space::DiscontinuousSpace* discontinuous_space = space->AsDiscontinuousSpace();
Mathieu Chartierbbd695c2014-04-16 09:48:48 -07001070 live_bitmap_->AddLargeObjectBitmap(discontinuous_space->GetLiveBitmap());
1071 mark_bitmap_->AddLargeObjectBitmap(discontinuous_space->GetMarkBitmap());
Mathieu Chartier590fee92013-09-13 13:46:47 -07001072 discontinuous_spaces_.push_back(discontinuous_space);
1073 }
1074 if (space->IsAllocSpace()) {
1075 alloc_spaces_.push_back(space->AsAllocSpace());
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001076 }
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08001077}
1078
Mathieu Chartier1b54f9c2014-04-30 16:45:02 -07001079void Heap::SetSpaceAsDefault(space::ContinuousSpace* continuous_space) {
1080 WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
1081 if (continuous_space->IsDlMallocSpace()) {
1082 dlmalloc_space_ = continuous_space->AsDlMallocSpace();
1083 } else if (continuous_space->IsRosAllocSpace()) {
1084 rosalloc_space_ = continuous_space->AsRosAllocSpace();
1085 }
1086}
1087
1088void Heap::RemoveSpace(space::Space* space) {
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001089 DCHECK(space != nullptr);
1090 WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
1091 if (space->IsContinuousSpace()) {
1092 DCHECK(!space->IsDiscontinuousSpace());
1093 space::ContinuousSpace* continuous_space = space->AsContinuousSpace();
1094 // Continuous spaces don't necessarily have bitmaps.
Mathieu Chartiera8e8f9c2014-04-09 14:51:05 -07001095 accounting::ContinuousSpaceBitmap* live_bitmap = continuous_space->GetLiveBitmap();
1096 accounting::ContinuousSpaceBitmap* mark_bitmap = continuous_space->GetMarkBitmap();
Mathieu Chartierecc82302017-02-16 10:20:12 -08001097 if (live_bitmap != nullptr && !space->IsRegionSpace()) {
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001098 DCHECK(mark_bitmap != nullptr);
1099 live_bitmap_->RemoveContinuousSpaceBitmap(live_bitmap);
1100 mark_bitmap_->RemoveContinuousSpaceBitmap(mark_bitmap);
1101 }
1102 auto it = std::find(continuous_spaces_.begin(), continuous_spaces_.end(), continuous_space);
1103 DCHECK(it != continuous_spaces_.end());
1104 continuous_spaces_.erase(it);
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001105 } else {
1106 DCHECK(space->IsDiscontinuousSpace());
1107 space::DiscontinuousSpace* discontinuous_space = space->AsDiscontinuousSpace();
Mathieu Chartierbbd695c2014-04-16 09:48:48 -07001108 live_bitmap_->RemoveLargeObjectBitmap(discontinuous_space->GetLiveBitmap());
1109 mark_bitmap_->RemoveLargeObjectBitmap(discontinuous_space->GetMarkBitmap());
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001110 auto it = std::find(discontinuous_spaces_.begin(), discontinuous_spaces_.end(),
1111 discontinuous_space);
1112 DCHECK(it != discontinuous_spaces_.end());
1113 discontinuous_spaces_.erase(it);
1114 }
1115 if (space->IsAllocSpace()) {
1116 auto it = std::find(alloc_spaces_.begin(), alloc_spaces_.end(), space->AsAllocSpace());
1117 DCHECK(it != alloc_spaces_.end());
1118 alloc_spaces_.erase(it);
1119 }
1120}
1121
Albert Mingkun Yang6e0d3252018-12-10 15:22:45 +00001122double Heap::CalculateGcWeightedAllocatedBytes(uint64_t gc_last_process_cpu_time_ns,
1123 uint64_t current_process_cpu_time) const {
Albert Mingkun Yang2d7329b2018-11-30 19:58:18 +00001124 uint64_t bytes_allocated = GetBytesAllocated();
Albert Mingkun Yang6e0d3252018-12-10 15:22:45 +00001125 double weight = current_process_cpu_time - gc_last_process_cpu_time_ns;
1126 return weight * bytes_allocated;
1127}
1128
1129void Heap::CalculatePreGcWeightedAllocatedBytes() {
1130 uint64_t current_process_cpu_time = ProcessCpuNanoTime();
1131 pre_gc_weighted_allocated_bytes_ +=
1132 CalculateGcWeightedAllocatedBytes(pre_gc_last_process_cpu_time_ns_, current_process_cpu_time);
1133 pre_gc_last_process_cpu_time_ns_ = current_process_cpu_time;
1134}
1135
1136void Heap::CalculatePostGcWeightedAllocatedBytes() {
1137 uint64_t current_process_cpu_time = ProcessCpuNanoTime();
1138 post_gc_weighted_allocated_bytes_ +=
1139 CalculateGcWeightedAllocatedBytes(post_gc_last_process_cpu_time_ns_, current_process_cpu_time);
1140 post_gc_last_process_cpu_time_ns_ = current_process_cpu_time;
Albert Mingkun Yang2d7329b2018-11-30 19:58:18 +00001141}
1142
Albert Mingkun Yangd6e178e2018-11-19 12:58:30 +00001143uint64_t Heap::GetTotalGcCpuTime() {
1144 uint64_t sum = 0;
Albert Mingkun Yang1c42e752018-11-19 16:10:24 +00001145 for (auto* collector : garbage_collectors_) {
Albert Mingkun Yangd6e178e2018-11-19 12:58:30 +00001146 sum += collector->GetTotalCpuTime();
1147 }
1148 return sum;
1149}
1150
Elliott Hughes8b788fe2013-04-17 15:57:01 -07001151void Heap::DumpGcPerformanceInfo(std::ostream& os) {
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001152 // Dump cumulative timings.
Elliott Hughes8b788fe2013-04-17 15:57:01 -07001153 os << "Dumping cumulative Gc timings\n";
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001154 uint64_t total_duration = 0;
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001155 // Dump cumulative loggers for each GC type.
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001156 uint64_t total_paused_time = 0;
Albert Mingkun Yang1c42e752018-11-19 16:10:24 +00001157 for (auto* collector : garbage_collectors_) {
Mathieu Chartier104fa0c2014-08-07 14:26:27 -07001158 total_duration += collector->GetCumulativeTimings().GetTotalNs();
1159 total_paused_time += collector->GetTotalPausedTimeNs();
1160 collector->DumpPerformanceInfo(os);
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001161 }
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001162 if (total_duration != 0) {
Lokesh Gidraa65859d2019-04-11 12:27:38 -07001163 const double total_seconds = total_duration / 1.0e9;
1164 const double total_cpu_seconds = GetTotalGcCpuTime() / 1.0e9;
Elliott Hughes8b788fe2013-04-17 15:57:01 -07001165 os << "Total time spent in GC: " << PrettyDuration(total_duration) << "\n";
1166 os << "Mean GC size throughput: "
Lokesh Gidraa65859d2019-04-11 12:27:38 -07001167 << PrettySize(GetBytesFreedEver() / total_seconds) << "/s"
1168 << " per cpu-time: "
1169 << PrettySize(GetBytesFreedEver() / total_cpu_seconds) << "/s\n";
Elliott Hughes8b788fe2013-04-17 15:57:01 -07001170 os << "Mean GC object throughput: "
Ian Rogers1d54e732013-05-02 21:10:01 -07001171 << (GetObjectsFreedEver() / total_seconds) << " objects/s\n";
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001172 }
Mathieu Chartierdd162fb2014-08-06 17:06:33 -07001173 uint64_t total_objects_allocated = GetObjectsAllocatedEver();
Mathieu Chartierc30a7252014-08-12 10:13:48 -07001174 os << "Total number of allocations " << total_objects_allocated << "\n";
Hiroshi Yamauchia1c9f012015-04-02 10:18:12 -07001175 os << "Total bytes allocated " << PrettySize(GetBytesAllocatedEver()) << "\n";
1176 os << "Total bytes freed " << PrettySize(GetBytesFreedEver()) << "\n";
Mathieu Chartierc30a7252014-08-12 10:13:48 -07001177 os << "Free memory " << PrettySize(GetFreeMemory()) << "\n";
Mathieu Chartierdd162fb2014-08-06 17:06:33 -07001178 os << "Free memory until GC " << PrettySize(GetFreeMemoryUntilGC()) << "\n";
1179 os << "Free memory until OOME " << PrettySize(GetFreeMemoryUntilOOME()) << "\n";
Mathieu Chartierc30a7252014-08-12 10:13:48 -07001180 os << "Total memory " << PrettySize(GetTotalMemory()) << "\n";
1181 os << "Max memory " << PrettySize(GetMaxMemory()) << "\n";
Mathieu Chartiere4cab172014-08-19 18:24:04 -07001182 if (HasZygoteSpace()) {
1183 os << "Zygote space size " << PrettySize(zygote_space_->Size()) << "\n";
1184 }
Elliott Hughes8b788fe2013-04-17 15:57:01 -07001185 os << "Total mutator paused time: " << PrettyDuration(total_paused_time) << "\n";
Hiroshi Yamauchia1c9f012015-04-02 10:18:12 -07001186 os << "Total time waiting for GC to complete: " << PrettyDuration(total_wait_time_) << "\n";
1187 os << "Total GC count: " << GetGcCount() << "\n";
1188 os << "Total GC time: " << PrettyDuration(GetGcTime()) << "\n";
1189 os << "Total blocking GC count: " << GetBlockingGcCount() << "\n";
1190 os << "Total blocking GC time: " << PrettyDuration(GetBlockingGcTime()) << "\n";
1191
1192 {
1193 MutexLock mu(Thread::Current(), *gc_complete_lock_);
1194 if (gc_count_rate_histogram_.SampleSize() > 0U) {
1195 os << "Histogram of GC count per " << NsToMs(kGcCountRateHistogramWindowDuration) << " ms: ";
1196 gc_count_rate_histogram_.DumpBins(os);
1197 os << "\n";
1198 }
1199 if (blocking_gc_count_rate_histogram_.SampleSize() > 0U) {
1200 os << "Histogram of blocking GC count per "
1201 << NsToMs(kGcCountRateHistogramWindowDuration) << " ms: ";
1202 blocking_gc_count_rate_histogram_.DumpBins(os);
1203 os << "\n";
1204 }
1205 }
1206
Hiroshi Yamauchib62f2e62016-03-23 15:51:24 -07001207 if (kDumpRosAllocStatsOnSigQuit && rosalloc_space_ != nullptr) {
1208 rosalloc_space_->DumpStats(os);
1209 }
1210
Hans Boehmc220f982018-10-12 16:15:45 -07001211 os << "Native bytes total: " << GetNativeBytes()
1212 << " registered: " << native_bytes_registered_.load(std::memory_order_relaxed) << "\n";
1213
1214 os << "Total native bytes at last GC: "
1215 << old_native_bytes_allocated_.load(std::memory_order_relaxed) << "\n";
Mathieu Chartier5d2a3f72016-05-11 11:35:39 -07001216
Mathieu Chartier73d1e172014-04-11 17:53:48 -07001217 BaseMutex::DumpAll(os);
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001218}
1219
Hiroshi Yamauchi37670172015-06-10 17:20:54 -07001220void Heap::ResetGcPerformanceInfo() {
Albert Mingkun Yang1c42e752018-11-19 16:10:24 +00001221 for (auto* collector : garbage_collectors_) {
Hiroshi Yamauchi37670172015-06-10 17:20:54 -07001222 collector->ResetMeasurements();
1223 }
Albert Mingkun Yang2d7329b2018-11-30 19:58:18 +00001224
1225 process_cpu_start_time_ns_ = ProcessCpuNanoTime();
Albert Mingkun Yang6e0d3252018-12-10 15:22:45 +00001226
1227 pre_gc_last_process_cpu_time_ns_ = process_cpu_start_time_ns_;
1228 pre_gc_weighted_allocated_bytes_ = 0u;
1229
1230 post_gc_last_process_cpu_time_ns_ = process_cpu_start_time_ns_;
1231 post_gc_weighted_allocated_bytes_ = 0u;
Albert Mingkun Yang2d7329b2018-11-30 19:58:18 +00001232
Hans Boehm4c6d7652019-11-01 09:23:19 -07001233 total_bytes_freed_ever_.store(0);
1234 total_objects_freed_ever_.store(0);
Hiroshi Yamauchi37670172015-06-10 17:20:54 -07001235 total_wait_time_ = 0;
1236 blocking_gc_count_ = 0;
1237 blocking_gc_time_ = 0;
1238 gc_count_last_window_ = 0;
1239 blocking_gc_count_last_window_ = 0;
1240 last_update_time_gc_count_rate_histograms_ = // Round down by the window duration.
1241 (NanoTime() / kGcCountRateHistogramWindowDuration) * kGcCountRateHistogramWindowDuration;
1242 {
1243 MutexLock mu(Thread::Current(), *gc_complete_lock_);
1244 gc_count_rate_histogram_.Reset();
1245 blocking_gc_count_rate_histogram_.Reset();
1246 }
1247}
1248
Hiroshi Yamauchia1c9f012015-04-02 10:18:12 -07001249uint64_t Heap::GetGcCount() const {
1250 uint64_t gc_count = 0U;
Albert Mingkun Yang1c42e752018-11-19 16:10:24 +00001251 for (auto* collector : garbage_collectors_) {
Hiroshi Yamauchia1c9f012015-04-02 10:18:12 -07001252 gc_count += collector->GetCumulativeTimings().GetIterations();
1253 }
1254 return gc_count;
1255}
1256
1257uint64_t Heap::GetGcTime() const {
1258 uint64_t gc_time = 0U;
Albert Mingkun Yang1c42e752018-11-19 16:10:24 +00001259 for (auto* collector : garbage_collectors_) {
Hiroshi Yamauchia1c9f012015-04-02 10:18:12 -07001260 gc_time += collector->GetCumulativeTimings().GetTotalNs();
1261 }
1262 return gc_time;
1263}
1264
1265uint64_t Heap::GetBlockingGcCount() const {
1266 return blocking_gc_count_;
1267}
1268
1269uint64_t Heap::GetBlockingGcTime() const {
1270 return blocking_gc_time_;
1271}
1272
1273void Heap::DumpGcCountRateHistogram(std::ostream& os) const {
1274 MutexLock mu(Thread::Current(), *gc_complete_lock_);
1275 if (gc_count_rate_histogram_.SampleSize() > 0U) {
1276 gc_count_rate_histogram_.DumpBins(os);
1277 }
1278}
1279
1280void Heap::DumpBlockingGcCountRateHistogram(std::ostream& os) const {
1281 MutexLock mu(Thread::Current(), *gc_complete_lock_);
1282 if (blocking_gc_count_rate_histogram_.SampleSize() > 0U) {
1283 blocking_gc_count_rate_histogram_.DumpBins(os);
1284 }
1285}
1286
Andreas Gampe27fa96c2016-10-07 15:05:24 -07001287ALWAYS_INLINE
1288static inline AllocationListener* GetAndOverwriteAllocationListener(
1289 Atomic<AllocationListener*>* storage, AllocationListener* new_value) {
Orion Hodson88591fe2018-03-06 13:35:43 +00001290 return storage->exchange(new_value);
Andreas Gampe27fa96c2016-10-07 15:05:24 -07001291}
1292
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08001293Heap::~Heap() {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001294 VLOG(heap) << "Starting ~Heap()";
Mathieu Chartier590fee92013-09-13 13:46:47 -07001295 STLDeleteElements(&garbage_collectors_);
1296 // If we don't reset then the mark stack complains in its destructor.
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001297 allocation_stack_->Reset();
Man Cao8c2ff642015-05-27 17:25:30 -07001298 allocation_records_.reset();
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001299 live_stack_->Reset();
Mathieu Chartier11409ae2013-09-23 11:49:36 -07001300 STLDeleteValues(&mod_union_tables_);
Mathieu Chartier0767c9a2014-03-26 12:53:19 -07001301 STLDeleteValues(&remembered_sets_);
Ian Rogers1d54e732013-05-02 21:10:01 -07001302 STLDeleteElements(&continuous_spaces_);
1303 STLDeleteElements(&discontinuous_spaces_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001304 delete gc_complete_lock_;
Andreas Gampe6be4f2a2015-11-10 13:34:17 -08001305 delete thread_flip_lock_;
Mathieu Chartiera5eae692014-12-17 17:56:03 -08001306 delete pending_task_lock_;
Mathieu Chartier31000802015-06-14 14:14:37 -07001307 delete backtrace_lock_;
Hans Boehmfb8b4e22018-09-05 16:45:42 -07001308 uint64_t unique_count = unique_backtrace_count_.load();
1309 uint64_t seen_count = seen_backtrace_count_.load();
Orion Hodson88591fe2018-03-06 13:35:43 +00001310 if (unique_count != 0 || seen_count != 0) {
1311 LOG(INFO) << "gc stress unique=" << unique_count << " total=" << (unique_count + seen_count);
Mathieu Chartier31000802015-06-14 14:14:37 -07001312 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07001313 VLOG(heap) << "Finished ~Heap()";
Carl Shapiro69759ea2011-07-21 18:13:35 -07001314}
1315
Mathieu Chartier9d156d52016-10-06 17:44:26 -07001316
1317space::ContinuousSpace* Heap::FindContinuousSpaceFromAddress(const mirror::Object* addr) const {
Mathieu Chartier02e25112013-08-14 16:14:24 -07001318 for (const auto& space : continuous_spaces_) {
Mathieu Chartier9d156d52016-10-06 17:44:26 -07001319 if (space->Contains(addr)) {
Mathieu Chartier02e25112013-08-14 16:14:24 -07001320 return space;
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07001321 }
1322 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001323 return nullptr;
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07001324}
1325
Mathieu Chartier9d156d52016-10-06 17:44:26 -07001326space::ContinuousSpace* Heap::FindContinuousSpaceFromObject(ObjPtr<mirror::Object> obj,
1327 bool fail_ok) const {
1328 space::ContinuousSpace* space = FindContinuousSpaceFromAddress(obj.Ptr());
1329 if (space != nullptr) {
1330 return space;
1331 }
1332 if (!fail_ok) {
1333 LOG(FATAL) << "object " << obj << " not inside any spaces!";
1334 }
1335 return nullptr;
1336}
1337
1338space::DiscontinuousSpace* Heap::FindDiscontinuousSpaceFromObject(ObjPtr<mirror::Object> obj,
Ian Rogers1d54e732013-05-02 21:10:01 -07001339 bool fail_ok) const {
Mathieu Chartier02e25112013-08-14 16:14:24 -07001340 for (const auto& space : discontinuous_spaces_) {
Mathieu Chartier9d156d52016-10-06 17:44:26 -07001341 if (space->Contains(obj.Ptr())) {
Mathieu Chartier02e25112013-08-14 16:14:24 -07001342 return space;
Ian Rogers1d54e732013-05-02 21:10:01 -07001343 }
1344 }
1345 if (!fail_ok) {
Mathieu Chartier9d156d52016-10-06 17:44:26 -07001346 LOG(FATAL) << "object " << obj << " not inside any spaces!";
Ian Rogers1d54e732013-05-02 21:10:01 -07001347 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001348 return nullptr;
Ian Rogers1d54e732013-05-02 21:10:01 -07001349}
1350
Mathieu Chartier9d156d52016-10-06 17:44:26 -07001351space::Space* Heap::FindSpaceFromObject(ObjPtr<mirror::Object> obj, bool fail_ok) const {
Ian Rogers1d54e732013-05-02 21:10:01 -07001352 space::Space* result = FindContinuousSpaceFromObject(obj, true);
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001353 if (result != nullptr) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001354 return result;
1355 }
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07001356 return FindDiscontinuousSpaceFromObject(obj, fail_ok);
Ian Rogers1d54e732013-05-02 21:10:01 -07001357}
1358
Mathieu Chartier9d156d52016-10-06 17:44:26 -07001359space::Space* Heap::FindSpaceFromAddress(const void* addr) const {
1360 for (const auto& space : continuous_spaces_) {
1361 if (space->Contains(reinterpret_cast<const mirror::Object*>(addr))) {
1362 return space;
1363 }
1364 }
1365 for (const auto& space : discontinuous_spaces_) {
1366 if (space->Contains(reinterpret_cast<const mirror::Object*>(addr))) {
1367 return space;
1368 }
1369 }
1370 return nullptr;
1371}
1372
Roland Levillain5fcf1ea2018-10-30 11:58:08 +00001373std::string Heap::DumpSpaceNameFromAddress(const void* addr) const {
1374 space::Space* space = FindSpaceFromAddress(addr);
1375 return (space != nullptr) ? space->GetName() : "no space";
1376}
Mathieu Chartier9d156d52016-10-06 17:44:26 -07001377
Hiroshi Yamauchi654dd482014-07-09 12:54:32 -07001378void Heap::ThrowOutOfMemoryError(Thread* self, size_t byte_count, AllocatorType allocator_type) {
Mathieu Chartiere8f3f032016-04-04 16:49:44 -07001379 // If we're in a stack overflow, do not create a new exception. It would require running the
1380 // constructor, which will of course still be in a stack overflow.
1381 if (self->IsHandlingStackOverflow()) {
Roland Levillain7b0e8442018-04-11 18:27:47 +01001382 self->SetException(
1383 Runtime::Current()->GetPreAllocatedOutOfMemoryErrorWhenHandlingStackOverflow());
Mathieu Chartiere8f3f032016-04-04 16:49:44 -07001384 return;
1385 }
1386
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -07001387 std::ostringstream oss;
Ian Rogersef7d42f2014-01-06 12:55:46 -08001388 size_t total_bytes_free = GetFreeMemory();
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -07001389 oss << "Failed to allocate a " << byte_count << " byte allocation with " << total_bytes_free
Mathieu Chartiera9033d72016-12-01 17:41:17 -08001390 << " free bytes and " << PrettySize(GetFreeMemoryUntilOOME()) << " until OOM,"
Hans Boehmc220f982018-10-12 16:15:45 -07001391 << " target footprint " << target_footprint_.load(std::memory_order_relaxed)
1392 << ", growth limit "
Mathieu Chartiera9033d72016-12-01 17:41:17 -08001393 << growth_limit_;
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -07001394 // If the allocation failed due to fragmentation, print out the largest continuous allocation.
Zuo Wangf37a88b2014-07-10 04:26:41 -07001395 if (total_bytes_free >= byte_count) {
Mathieu Chartierb363f662014-07-16 13:28:58 -07001396 space::AllocSpace* space = nullptr;
Hiroshi Yamauchi654dd482014-07-09 12:54:32 -07001397 if (allocator_type == kAllocatorTypeNonMoving) {
1398 space = non_moving_space_;
1399 } else if (allocator_type == kAllocatorTypeRosAlloc ||
1400 allocator_type == kAllocatorTypeDlMalloc) {
1401 space = main_space_;
Mathieu Chartierb363f662014-07-16 13:28:58 -07001402 } else if (allocator_type == kAllocatorTypeBumpPointer ||
1403 allocator_type == kAllocatorTypeTLAB) {
1404 space = bump_pointer_space_;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001405 } else if (allocator_type == kAllocatorTypeRegion ||
1406 allocator_type == kAllocatorTypeRegionTLAB) {
1407 space = region_space_;
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -07001408 }
Lokesh Gidra3d189432020-05-16 00:57:59 +00001409
1410 // There is no fragmentation info to log for large-object space.
1411 if (allocator_type != kAllocatorTypeLOS) {
1412 CHECK(space != nullptr) << "allocator_type:" << allocator_type
1413 << " byte_count:" << byte_count
1414 << " total_bytes_free:" << total_bytes_free;
1415 space->LogFragmentationAllocFailure(oss, byte_count);
1416 }
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001417 }
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -07001418 self->ThrowOutOfMemoryError(oss.str().c_str());
1419}
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001420
Mathieu Chartiera5eae692014-12-17 17:56:03 -08001421void Heap::DoPendingCollectorTransition() {
1422 CollectorType desired_collector_type = desired_collector_type_;
Mathieu Chartierb2728552014-09-08 20:08:41 +00001423 // Launch homogeneous space compaction if it is desired.
1424 if (desired_collector_type == kCollectorTypeHomogeneousSpaceCompact) {
1425 if (!CareAboutPauseTimes()) {
1426 PerformHomogeneousSpaceCompact();
Mathieu Chartiera5eae692014-12-17 17:56:03 -08001427 } else {
1428 VLOG(gc) << "Homogeneous compaction ignored due to jank perceptible process state";
Mathieu Chartierb2728552014-09-08 20:08:41 +00001429 }
Hiroshi Yamauchi60985b72016-08-24 13:53:12 -07001430 } else if (desired_collector_type == kCollectorTypeCCBackground) {
1431 DCHECK(kUseReadBarrier);
1432 if (!CareAboutPauseTimes()) {
1433 // Invoke CC full compaction.
1434 CollectGarbageInternal(collector::kGcTypeFull,
1435 kGcCauseCollectorTransition,
Andreas Gampe98ea9d92018-10-19 14:06:15 -07001436 /*clear_soft_references=*/false);
Hiroshi Yamauchi60985b72016-08-24 13:53:12 -07001437 } else {
1438 VLOG(gc) << "CC background compaction ignored due to jank perceptible process state";
1439 }
Mathieu Chartiera5eae692014-12-17 17:56:03 -08001440 } else {
Mathieu Chartierb52df532019-04-09 14:10:59 -07001441 CHECK_EQ(desired_collector_type, collector_type_) << "Unsupported collector transition";
Mathieu Chartierb2728552014-09-08 20:08:41 +00001442 }
Mathieu Chartiera5eae692014-12-17 17:56:03 -08001443}
1444
1445void Heap::Trim(Thread* self) {
Mathieu Chartier8d447252015-10-26 10:21:14 -07001446 Runtime* const runtime = Runtime::Current();
Mathieu Chartier440e4ce2014-03-31 16:36:35 -07001447 if (!CareAboutPauseTimes()) {
1448 // Deflate the monitors, this can cause a pause but shouldn't matter since we don't care
1449 // about pauses.
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001450 ScopedTrace trace("Deflating monitors");
Hiroshi Yamauchi3b1d1b72016-10-12 11:53:57 -07001451 // Avoid race conditions on the lock word for CC.
1452 ScopedGCCriticalSection gcs(self, kGcCauseTrim, kCollectorTypeHeapTrim);
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001453 ScopedSuspendAll ssa(__FUNCTION__);
1454 uint64_t start_time = NanoTime();
1455 size_t count = runtime->GetMonitorList()->DeflateMonitors();
1456 VLOG(heap) << "Deflating " << count << " monitors took "
1457 << PrettyDuration(NanoTime() - start_time);
Mathieu Chartier440e4ce2014-03-31 16:36:35 -07001458 }
Mathieu Chartiera5eae692014-12-17 17:56:03 -08001459 TrimIndirectReferenceTables(self);
1460 TrimSpaces(self);
Mathieu Chartier8d447252015-10-26 10:21:14 -07001461 // Trim arenas that may have been used by JIT or verifier.
Mathieu Chartier8d447252015-10-26 10:21:14 -07001462 runtime->GetArenaPool()->TrimMaps();
Mathieu Chartiera5f9de02014-02-28 16:48:42 -08001463}
1464
Mathieu Chartier91c2f0c2014-11-26 11:21:15 -08001465class TrimIndirectReferenceTableClosure : public Closure {
1466 public:
1467 explicit TrimIndirectReferenceTableClosure(Barrier* barrier) : barrier_(barrier) {
1468 }
Roland Levillainf73caca2018-08-24 17:19:07 +01001469 void Run(Thread* thread) override NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers55256cb2017-12-21 17:07:11 -08001470 thread->GetJniEnv()->TrimLocals();
Lei Lidd9943d2015-02-02 14:24:44 +08001471 // If thread is a running mutator, then act on behalf of the trim thread.
1472 // See the code in ThreadList::RunCheckpoint.
Mathieu Chartier10d25082015-10-28 18:36:09 -07001473 barrier_->Pass(Thread::Current());
Mathieu Chartier91c2f0c2014-11-26 11:21:15 -08001474 }
1475
1476 private:
1477 Barrier* const barrier_;
1478};
1479
Mathieu Chartiera5eae692014-12-17 17:56:03 -08001480void Heap::TrimIndirectReferenceTables(Thread* self) {
1481 ScopedObjectAccess soa(self);
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001482 ScopedTrace trace(__PRETTY_FUNCTION__);
Mathieu Chartiera5eae692014-12-17 17:56:03 -08001483 JavaVMExt* vm = soa.Vm();
1484 // Trim globals indirect reference table.
1485 vm->TrimGlobals();
1486 // Trim locals indirect reference tables.
1487 Barrier barrier(0);
1488 TrimIndirectReferenceTableClosure closure(&barrier);
1489 ScopedThreadStateChange tsc(self, kWaitingForCheckPointsToRun);
1490 size_t barrier_count = Runtime::Current()->GetThreadList()->RunCheckpoint(&closure);
Lei Lidd9943d2015-02-02 14:24:44 +08001491 if (barrier_count != 0) {
1492 barrier.Increment(self, barrier_count);
1493 }
Mathieu Chartiera5eae692014-12-17 17:56:03 -08001494}
Mathieu Chartier91c2f0c2014-11-26 11:21:15 -08001495
Mathieu Chartieraa516822015-10-02 15:53:37 -07001496void Heap::StartGC(Thread* self, GcCause cause, CollectorType collector_type) {
Mathieu Chartierb93d5b12017-05-19 13:05:06 -07001497 // Need to do this before acquiring the locks since we don't want to get suspended while
1498 // holding any locks.
1499 ScopedThreadStateChange tsc(self, kWaitingForGcToComplete);
Mathieu Chartieraa516822015-10-02 15:53:37 -07001500 MutexLock mu(self, *gc_complete_lock_);
1501 // Ensure there is only one GC at a time.
1502 WaitForGcToCompleteLocked(cause, self);
1503 collector_type_running_ = collector_type;
Mathieu Chartier40112dd2017-06-26 17:49:09 -07001504 last_gc_cause_ = cause;
Mathieu Chartier183009a2017-02-16 21:19:28 -08001505 thread_running_gc_ = self;
Mathieu Chartieraa516822015-10-02 15:53:37 -07001506}
1507
Mathieu Chartiera5eae692014-12-17 17:56:03 -08001508void Heap::TrimSpaces(Thread* self) {
Mathieu Chartierb93d5b12017-05-19 13:05:06 -07001509 // Pretend we are doing a GC to prevent background compaction from deleting the space we are
1510 // trimming.
1511 StartGC(self, kGcCauseTrim, kCollectorTypeHeapTrim);
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001512 ScopedTrace trace(__PRETTY_FUNCTION__);
Mathieu Chartiera5eae692014-12-17 17:56:03 -08001513 const uint64_t start_ns = NanoTime();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001514 // Trim the managed spaces.
1515 uint64_t total_alloc_space_allocated = 0;
1516 uint64_t total_alloc_space_size = 0;
1517 uint64_t managed_reclaimed = 0;
Mathieu Chartiera9d82fe2016-01-25 20:06:11 -08001518 {
1519 ScopedObjectAccess soa(self);
1520 for (const auto& space : continuous_spaces_) {
1521 if (space->IsMallocSpace()) {
1522 gc::space::MallocSpace* malloc_space = space->AsMallocSpace();
1523 if (malloc_space->IsRosAllocSpace() || !CareAboutPauseTimes()) {
1524 // Don't trim dlmalloc spaces if we care about pauses since this can hold the space lock
1525 // for a long period of time.
1526 managed_reclaimed += malloc_space->Trim();
1527 }
1528 total_alloc_space_size += malloc_space->Size();
Mathieu Chartiera5b5c552014-06-24 14:48:59 -07001529 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07001530 }
1531 }
Mathieu Chartier2dbe6272014-09-16 10:43:23 -07001532 total_alloc_space_allocated = GetBytesAllocated();
1533 if (large_object_space_ != nullptr) {
1534 total_alloc_space_allocated -= large_object_space_->GetBytesAllocated();
1535 }
Mathieu Chartier31f44142014-04-08 14:40:03 -07001536 if (bump_pointer_space_ != nullptr) {
1537 total_alloc_space_allocated -= bump_pointer_space_->Size();
1538 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001539 if (region_space_ != nullptr) {
1540 total_alloc_space_allocated -= region_space_->GetBytesAllocated();
1541 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07001542 const float managed_utilization = static_cast<float>(total_alloc_space_allocated) /
1543 static_cast<float>(total_alloc_space_size);
1544 uint64_t gc_heap_end_ns = NanoTime();
Mathieu Chartierd5a89ee2014-01-31 09:55:13 -08001545 // We never move things in the native heap, so we can finish the GC at this point.
1546 FinishGC(self, collector::kGcTypeNone);
Ian Rogers872dd822014-10-30 11:19:14 -07001547
Mathieu Chartier590fee92013-09-13 13:46:47 -07001548 VLOG(heap) << "Heap trim of managed (duration=" << PrettyDuration(gc_heap_end_ns - start_ns)
Dimitry Ivanove6465bc2015-12-14 18:55:02 -08001549 << ", advised=" << PrettySize(managed_reclaimed) << ") heap. Managed heap utilization of "
1550 << static_cast<int>(100 * managed_utilization) << "%.";
Mathieu Chartier590fee92013-09-13 13:46:47 -07001551}
1552
Mathieu Chartier9d156d52016-10-06 17:44:26 -07001553bool Heap::IsValidObjectAddress(const void* addr) const {
1554 if (addr == nullptr) {
Elliott Hughes88c5c352012-03-15 18:49:48 -07001555 return true;
1556 }
Mathieu Chartier9d156d52016-10-06 17:44:26 -07001557 return IsAligned<kObjectAlignment>(addr) && FindSpaceFromAddress(addr) != nullptr;
Mathieu Chartier590fee92013-09-13 13:46:47 -07001558}
1559
Mathieu Chartier9d156d52016-10-06 17:44:26 -07001560bool Heap::IsNonDiscontinuousSpaceHeapAddress(const void* addr) const {
1561 return FindContinuousSpaceFromAddress(reinterpret_cast<const mirror::Object*>(addr)) != nullptr;
Mathieu Chartierd68ac702014-02-11 14:50:51 -08001562}
1563
Mathieu Chartier9d156d52016-10-06 17:44:26 -07001564bool Heap::IsLiveObjectLocked(ObjPtr<mirror::Object> obj,
1565 bool search_allocation_stack,
1566 bool search_live_stack,
1567 bool sorted) {
1568 if (UNLIKELY(!IsAligned<kObjectAlignment>(obj.Ptr()))) {
Mathieu Chartier15d34022014-02-26 17:16:38 -08001569 return false;
1570 }
Mathieu Chartier9d156d52016-10-06 17:44:26 -07001571 if (bump_pointer_space_ != nullptr && bump_pointer_space_->HasAddress(obj.Ptr())) {
Mathieu Chartier4e305412014-02-19 10:54:44 -08001572 mirror::Class* klass = obj->GetClass<kVerifyNone>();
Mathieu Chartier938a03b2014-01-16 15:10:31 -08001573 if (obj == klass) {
Mathieu Chartier9be9a7a2014-01-24 14:07:33 -08001574 // This case happens for java.lang.Class.
Mathieu Chartier938a03b2014-01-16 15:10:31 -08001575 return true;
1576 }
1577 return VerifyClassClass(klass) && IsLiveObjectLocked(klass);
Mathieu Chartier9d156d52016-10-06 17:44:26 -07001578 } else if (temp_space_ != nullptr && temp_space_->HasAddress(obj.Ptr())) {
Mathieu Chartier4e305412014-02-19 10:54:44 -08001579 // If we are in the allocated region of the temp space, then we are probably live (e.g. during
1580 // 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 -07001581 return temp_space_->Contains(obj.Ptr());
Ian Rogers1d54e732013-05-02 21:10:01 -07001582 }
Mathieu Chartier9d156d52016-10-06 17:44:26 -07001583 if (region_space_ != nullptr && region_space_->HasAddress(obj.Ptr())) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001584 return true;
1585 }
Mathieu Chartierf082d3c2013-07-29 17:04:07 -07001586 space::ContinuousSpace* c_space = FindContinuousSpaceFromObject(obj, true);
Mathieu Chartierbbd695c2014-04-16 09:48:48 -07001587 space::DiscontinuousSpace* d_space = nullptr;
Mathieu Chartier938a03b2014-01-16 15:10:31 -08001588 if (c_space != nullptr) {
Mathieu Chartier9d156d52016-10-06 17:44:26 -07001589 if (c_space->GetLiveBitmap()->Test(obj.Ptr())) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001590 return true;
1591 }
1592 } else {
Mathieu Chartierf082d3c2013-07-29 17:04:07 -07001593 d_space = FindDiscontinuousSpaceFromObject(obj, true);
Mathieu Chartier938a03b2014-01-16 15:10:31 -08001594 if (d_space != nullptr) {
Mathieu Chartier9d156d52016-10-06 17:44:26 -07001595 if (d_space->GetLiveBitmap()->Test(obj.Ptr())) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001596 return true;
1597 }
1598 }
1599 }
Mathieu Chartierf082d3c2013-07-29 17:04:07 -07001600 // This is covering the allocation/live stack swapping that is done without mutators suspended.
Mathieu Chartier0f72e412013-09-06 16:40:01 -07001601 for (size_t i = 0; i < (sorted ? 1 : 5); ++i) {
1602 if (i > 0) {
1603 NanoSleep(MsToNs(10));
Ian Rogers1d54e732013-05-02 21:10:01 -07001604 }
Mathieu Chartier0f72e412013-09-06 16:40:01 -07001605 if (search_allocation_stack) {
1606 if (sorted) {
Mathieu Chartier9d156d52016-10-06 17:44:26 -07001607 if (allocation_stack_->ContainsSorted(obj.Ptr())) {
Mathieu Chartier0f72e412013-09-06 16:40:01 -07001608 return true;
1609 }
Mathieu Chartier9d156d52016-10-06 17:44:26 -07001610 } else if (allocation_stack_->Contains(obj.Ptr())) {
Mathieu Chartier0f72e412013-09-06 16:40:01 -07001611 return true;
1612 }
1613 }
1614
1615 if (search_live_stack) {
1616 if (sorted) {
Mathieu Chartier9d156d52016-10-06 17:44:26 -07001617 if (live_stack_->ContainsSorted(obj.Ptr())) {
Mathieu Chartier0f72e412013-09-06 16:40:01 -07001618 return true;
1619 }
Mathieu Chartier9d156d52016-10-06 17:44:26 -07001620 } else if (live_stack_->Contains(obj.Ptr())) {
Mathieu Chartier0f72e412013-09-06 16:40:01 -07001621 return true;
1622 }
1623 }
Ian Rogers1d54e732013-05-02 21:10:01 -07001624 }
Mathieu Chartierf082d3c2013-07-29 17:04:07 -07001625 // We need to check the bitmaps again since there is a race where we mark something as live and
1626 // then clear the stack containing it.
Mathieu Chartier938a03b2014-01-16 15:10:31 -08001627 if (c_space != nullptr) {
Mathieu Chartier9d156d52016-10-06 17:44:26 -07001628 if (c_space->GetLiveBitmap()->Test(obj.Ptr())) {
Mathieu Chartierf082d3c2013-07-29 17:04:07 -07001629 return true;
1630 }
1631 } else {
1632 d_space = FindDiscontinuousSpaceFromObject(obj, true);
Mathieu Chartier9d156d52016-10-06 17:44:26 -07001633 if (d_space != nullptr && d_space->GetLiveBitmap()->Test(obj.Ptr())) {
Mathieu Chartierf082d3c2013-07-29 17:04:07 -07001634 return true;
1635 }
1636 }
Ian Rogers1d54e732013-05-02 21:10:01 -07001637 return false;
Elliott Hughes6a5bd492011-10-28 14:33:57 -07001638}
1639
Mathieu Chartier4c13a3f2014-07-14 14:57:16 -07001640std::string Heap::DumpSpaces() const {
1641 std::ostringstream oss;
1642 DumpSpaces(oss);
1643 return oss.str();
1644}
1645
1646void Heap::DumpSpaces(std::ostream& stream) const {
Mathieu Chartier02e25112013-08-14 16:14:24 -07001647 for (const auto& space : continuous_spaces_) {
Mathieu Chartiera8e8f9c2014-04-09 14:51:05 -07001648 accounting::ContinuousSpaceBitmap* live_bitmap = space->GetLiveBitmap();
1649 accounting::ContinuousSpaceBitmap* mark_bitmap = space->GetMarkBitmap();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001650 stream << space << " " << *space << "\n";
1651 if (live_bitmap != nullptr) {
1652 stream << live_bitmap << " " << *live_bitmap << "\n";
1653 }
1654 if (mark_bitmap != nullptr) {
1655 stream << mark_bitmap << " " << *mark_bitmap << "\n";
1656 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001657 }
Mathieu Chartier02e25112013-08-14 16:14:24 -07001658 for (const auto& space : discontinuous_spaces_) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001659 stream << space << " " << *space << "\n";
Mathieu Chartier128c52c2012-10-16 14:12:41 -07001660 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -07001661}
1662
Mathieu Chartier9d156d52016-10-06 17:44:26 -07001663void Heap::VerifyObjectBody(ObjPtr<mirror::Object> obj) {
Stephen Hines22c6a812014-07-16 11:03:43 -07001664 if (verify_object_mode_ == kVerifyObjectModeDisabled) {
1665 return;
1666 }
1667
Mathieu Chartier0f72e412013-09-06 16:40:01 -07001668 // Ignore early dawn of the universe verifications.
Orion Hodson88591fe2018-03-06 13:35:43 +00001669 if (UNLIKELY(num_bytes_allocated_.load(std::memory_order_relaxed) < 10 * KB)) {
Ian Rogers62d6c772013-02-27 08:32:07 -08001670 return;
1671 }
Mathieu Chartier9d156d52016-10-06 17:44:26 -07001672 CHECK_ALIGNED(obj.Ptr(), kObjectAlignment) << "Object isn't aligned";
Ian Rogersb0fa5dc2014-04-28 16:47:08 -07001673 mirror::Class* c = obj->GetFieldObject<mirror::Class, kVerifyNone>(mirror::Object::ClassOffset());
Mathieu Chartier4e305412014-02-19 10:54:44 -08001674 CHECK(c != nullptr) << "Null class in object " << obj;
Roland Levillain14d90572015-07-16 10:52:26 +01001675 CHECK_ALIGNED(c, kObjectAlignment) << "Class " << c << " not aligned in object " << obj;
Mathieu Chartier938a03b2014-01-16 15:10:31 -08001676 CHECK(VerifyClassClass(c));
Mathieu Chartier0325e622012-09-05 14:22:51 -07001677
Mathieu Chartier4e305412014-02-19 10:54:44 -08001678 if (verify_object_mode_ > kVerifyObjectModeFast) {
1679 // Note: the bitmap tests below are racy since we don't hold the heap bitmap lock.
Mathieu Chartier4c13a3f2014-07-14 14:57:16 -07001680 CHECK(IsLiveObjectLocked(obj)) << "Object is dead " << obj << "\n" << DumpSpaces();
Mathieu Chartierdcf8d722012-08-02 14:55:54 -07001681 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001682}
1683
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001684void Heap::VerifyHeap() {
Ian Rogers50b35e22012-10-04 10:09:15 -07001685 ReaderMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
Andreas Gampe0c183382017-07-13 22:26:24 -07001686 auto visitor = [&](mirror::Object* obj) {
1687 VerifyObjectBody(obj);
1688 };
1689 // Technically we need the mutator lock here to call Visit. However, VerifyObjectBody is already
1690 // NO_THREAD_SAFETY_ANALYSIS.
1691 auto no_thread_safety_analysis = [&]() NO_THREAD_SAFETY_ANALYSIS {
1692 GetLiveBitmap()->Visit(visitor);
1693 };
1694 no_thread_safety_analysis();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001695}
1696
Mathieu Chartiere76e70f2014-05-02 16:35:37 -07001697void Heap::RecordFree(uint64_t freed_objects, int64_t freed_bytes) {
Mathieu Chartier601276a2014-03-20 15:12:30 -07001698 // Use signed comparison since freed bytes can be negative when background compaction foreground
Hans Boehma253c2d2019-05-13 12:38:54 -07001699 // transitions occurs. This is typically due to objects moving from a bump pointer space to a
1700 // free list backed space, which may increase memory footprint due to padding and binning.
Hans Boehmfb8b4e22018-09-05 16:45:42 -07001701 RACING_DCHECK_LE(freed_bytes,
1702 static_cast<int64_t>(num_bytes_allocated_.load(std::memory_order_relaxed)));
Mathieu Chartiere76e70f2014-05-02 16:35:37 -07001703 // Note: This relies on 2s complement for handling negative freed_bytes.
Hans Boehmfb8b4e22018-09-05 16:45:42 -07001704 num_bytes_allocated_.fetch_sub(static_cast<ssize_t>(freed_bytes), std::memory_order_relaxed);
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07001705 if (Runtime::Current()->HasStatsEnabled()) {
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07001706 RuntimeStats* thread_stats = Thread::Current()->GetStats();
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001707 thread_stats->freed_objects += freed_objects;
Elliott Hughes307f75d2011-10-12 18:04:40 -07001708 thread_stats->freed_bytes += freed_bytes;
Mathieu Chartier2fde5332012-09-14 14:51:54 -07001709 // TODO: Do this concurrently.
1710 RuntimeStats* global_stats = Runtime::Current()->GetStats();
1711 global_stats->freed_objects += freed_objects;
1712 global_stats->freed_bytes += freed_bytes;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07001713 }
Carl Shapiro58551df2011-07-24 03:09:51 -07001714}
1715
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07001716void Heap::RecordFreeRevoke() {
1717 // Subtract num_bytes_freed_revoke_ from num_bytes_allocated_ to cancel out the
Roland Levillainef012222017-06-21 16:28:06 +01001718 // ahead-of-time, bulk counting of bytes allocated in rosalloc thread-local buffers.
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07001719 // If there's a concurrent revoke, ok to not necessarily reset num_bytes_freed_revoke_
1720 // all the way to zero exactly as the remainder will be subtracted at the next GC.
Hans Boehmfb8b4e22018-09-05 16:45:42 -07001721 size_t bytes_freed = num_bytes_freed_revoke_.load(std::memory_order_relaxed);
1722 CHECK_GE(num_bytes_freed_revoke_.fetch_sub(bytes_freed, std::memory_order_relaxed),
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07001723 bytes_freed) << "num_bytes_freed_revoke_ underflow";
Hans Boehmfb8b4e22018-09-05 16:45:42 -07001724 CHECK_GE(num_bytes_allocated_.fetch_sub(bytes_freed, std::memory_order_relaxed),
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07001725 bytes_freed) << "num_bytes_allocated_ underflow";
1726 GetCurrentGcIteration()->SetFreedRevoke(bytes_freed);
1727}
1728
Zuo Wangf37a88b2014-07-10 04:26:41 -07001729space::RosAllocSpace* Heap::GetRosAllocSpace(gc::allocator::RosAlloc* rosalloc) const {
Mathieu Chartiera9d82fe2016-01-25 20:06:11 -08001730 if (rosalloc_space_ != nullptr && rosalloc_space_->GetRosAlloc() == rosalloc) {
1731 return rosalloc_space_;
1732 }
Zuo Wangf37a88b2014-07-10 04:26:41 -07001733 for (const auto& space : continuous_spaces_) {
1734 if (space->AsContinuousSpace()->IsRosAllocSpace()) {
1735 if (space->AsContinuousSpace()->AsRosAllocSpace()->GetRosAlloc() == rosalloc) {
1736 return space->AsContinuousSpace()->AsRosAllocSpace();
1737 }
1738 }
1739 }
1740 return nullptr;
1741}
1742
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001743static inline bool EntrypointsInstrumented() REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiereebc3af2016-02-29 18:13:38 -08001744 instrumentation::Instrumentation* const instrumentation =
1745 Runtime::Current()->GetInstrumentation();
1746 return instrumentation != nullptr && instrumentation->AllocEntrypointsInstrumented();
1747}
1748
Mathieu Chartiera4f6af92015-08-11 17:35:25 -07001749mirror::Object* Heap::AllocateInternalWithGc(Thread* self,
1750 AllocatorType allocator,
Mathieu Chartiereebc3af2016-02-29 18:13:38 -08001751 bool instrumented,
Mathieu Chartiera4f6af92015-08-11 17:35:25 -07001752 size_t alloc_size,
1753 size_t* bytes_allocated,
Ian Rogers6fac4472014-02-25 17:01:10 -08001754 size_t* usable_size,
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07001755 size_t* bytes_tl_bulk_allocated,
Mathieu Chartierdc540df2019-11-15 17:11:44 -08001756 ObjPtr<mirror::Class>* klass) {
Lokesh Gidra3d189432020-05-16 00:57:59 +00001757 // After a GC (due to allocation failure) we should retrieve at least this
1758 // fraction of the current max heap size. Otherwise throw OOME.
1759 constexpr double kMinFreeHeapAfterGcForAlloc = 0.01;
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001760 bool was_default_allocator = allocator == GetCurrentAllocator();
Mathieu Chartierf4f38432014-09-03 11:21:08 -07001761 // Make sure there is no pending exception since we may need to throw an OOME.
1762 self->AssertNoPendingException();
Mathieu Chartierc528dba2013-11-26 12:00:11 -08001763 DCHECK(klass != nullptr);
Alex Light986914b2019-11-19 01:12:25 +00001764
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001765 StackHandleScope<1> hs(self);
Alex Light986914b2019-11-19 01:12:25 +00001766 HandleWrapperObjPtr<mirror::Class> h_klass(hs.NewHandleWrapper(klass));
1767
Alex Light001e5b32019-12-17 15:30:33 -08001768 auto send_object_pre_alloc =
1769 [&]() REQUIRES_SHARED(Locks::mutator_lock_) REQUIRES(!Roles::uninterruptible_) {
1770 if (UNLIKELY(instrumented)) {
1771 AllocationListener* l = alloc_listener_.load(std::memory_order_seq_cst);
1772 if (UNLIKELY(l != nullptr) && UNLIKELY(l->HasPreAlloc())) {
1773 l->PreObjectAllocated(self, h_klass, &alloc_size);
1774 }
1775 }
1776 };
Alex Light986914b2019-11-19 01:12:25 +00001777#define PERFORM_SUSPENDING_OPERATION(op) \
1778 [&]() REQUIRES(Roles::uninterruptible_) REQUIRES_SHARED(Locks::mutator_lock_) { \
Mathieu Chartierdc540df2019-11-15 17:11:44 -08001779 ScopedAllowThreadSuspension ats; \
Alex Light986914b2019-11-19 01:12:25 +00001780 auto res = (op); \
1781 send_object_pre_alloc(); \
1782 return res; \
1783 }()
1784
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001785 // The allocation failed. If the GC is running, block until it completes, and then retry the
1786 // allocation.
Mathieu Chartierdc540df2019-11-15 17:11:44 -08001787 collector::GcType last_gc =
1788 PERFORM_SUSPENDING_OPERATION(WaitForGcToComplete(kGcCauseForAlloc, self));
Mathieu Chartiereebc3af2016-02-29 18:13:38 -08001789 // If we were the default allocator but the allocator changed while we were suspended,
1790 // abort the allocation.
1791 if ((was_default_allocator && allocator != GetCurrentAllocator()) ||
1792 (!instrumented && EntrypointsInstrumented())) {
1793 return nullptr;
1794 }
Ian Rogers1d54e732013-05-02 21:10:01 -07001795 if (last_gc != collector::kGcTypeNone) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001796 // A GC was in progress and we blocked, retry allocation now that memory has been freed.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001797 mirror::Object* ptr = TryToAllocate<true, false>(self, allocator, alloc_size, bytes_allocated,
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07001798 usable_size, bytes_tl_bulk_allocated);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001799 if (ptr != nullptr) {
1800 return ptr;
1801 }
Carl Shapiro69759ea2011-07-21 18:13:35 -07001802 }
1803
Lokesh Gidra3d189432020-05-16 00:57:59 +00001804 auto have_reclaimed_enough = [&]() {
1805 size_t curr_bytes_allocated = GetBytesAllocated();
1806 double curr_free_heap =
1807 static_cast<double>(growth_limit_ - curr_bytes_allocated) / growth_limit_;
1808 return curr_free_heap >= kMinFreeHeapAfterGcForAlloc;
1809 };
1810 // We perform one GC as per the next_gc_type_ (chosen in GrowForUtilization),
1811 // if it's not already tried. If that doesn't succeed then go for the most
1812 // exhaustive option. Perform a full-heap collection including clearing
1813 // SoftReferences. In case of ConcurrentCopying, it will also ensure that
1814 // all regions are evacuated. If allocation doesn't succeed even after that
1815 // then there is no hope, so we throw OOME.
Mathieu Chartier5ae2c932014-03-28 16:22:20 -07001816 collector::GcType tried_type = next_gc_type_;
Lokesh Gidra3d189432020-05-16 00:57:59 +00001817 if (last_gc < tried_type) {
1818 const bool gc_ran = PERFORM_SUSPENDING_OPERATION(
1819 CollectGarbageInternal(tried_type, kGcCauseForAlloc, false) != collector::kGcTypeNone);
Alex Light986914b2019-11-19 01:12:25 +00001820
Mathieu Chartiereebc3af2016-02-29 18:13:38 -08001821 if ((was_default_allocator && allocator != GetCurrentAllocator()) ||
1822 (!instrumented && EntrypointsInstrumented())) {
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001823 return nullptr;
1824 }
Lokesh Gidra3d189432020-05-16 00:57:59 +00001825 if (gc_ran && have_reclaimed_enough()) {
1826 mirror::Object* ptr = TryToAllocate<true, false>(self, allocator,
1827 alloc_size, bytes_allocated,
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07001828 usable_size, bytes_tl_bulk_allocated);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001829 if (ptr != nullptr) {
1830 return ptr;
1831 }
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001832 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001833 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001834 // Most allocations should have succeeded by now, so the heap is really full, really fragmented,
1835 // or the requested size is really big. Do another GC, collecting SoftReferences this time. The
1836 // VM spec requires that all SoftReferences have been collected and cleared before throwing
1837 // OOME.
1838 VLOG(gc) << "Forcing collection of SoftReferences for " << PrettySize(alloc_size)
1839 << " allocation";
1840 // TODO: Run finalization, but this may cause more allocations to occur.
1841 // We don't need a WaitForGcToComplete here either.
1842 DCHECK(!gc_plan_.empty());
Alex Light986914b2019-11-19 01:12:25 +00001843 PERFORM_SUSPENDING_OPERATION(CollectGarbageInternal(gc_plan_.back(), kGcCauseForAlloc, true));
Mathieu Chartiereebc3af2016-02-29 18:13:38 -08001844 if ((was_default_allocator && allocator != GetCurrentAllocator()) ||
1845 (!instrumented && EntrypointsInstrumented())) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001846 return nullptr;
Mathieu Chartiercbb2d202013-11-14 17:45:16 -08001847 }
Lokesh Gidra3d189432020-05-16 00:57:59 +00001848 mirror::Object* ptr = nullptr;
1849 if (have_reclaimed_enough()) {
1850 ptr = TryToAllocate<true, true>(self, allocator, alloc_size, bytes_allocated,
1851 usable_size, bytes_tl_bulk_allocated);
1852 }
1853
Mathieu Chartier6a7824d2014-08-22 14:53:04 -07001854 if (ptr == nullptr) {
Zuo Wangf37a88b2014-07-10 04:26:41 -07001855 const uint64_t current_time = NanoTime();
Mathieu Chartier6a7824d2014-08-22 14:53:04 -07001856 switch (allocator) {
1857 case kAllocatorTypeRosAlloc:
1858 // Fall-through.
1859 case kAllocatorTypeDlMalloc: {
1860 if (use_homogeneous_space_compaction_for_oom_ &&
1861 current_time - last_time_homogeneous_space_compaction_by_oom_ >
1862 min_interval_homogeneous_space_compaction_by_oom_) {
1863 last_time_homogeneous_space_compaction_by_oom_ = current_time;
Alex Light986914b2019-11-19 01:12:25 +00001864 HomogeneousSpaceCompactResult result =
1865 PERFORM_SUSPENDING_OPERATION(PerformHomogeneousSpaceCompact());
Mathieu Chartiereebc3af2016-02-29 18:13:38 -08001866 // Thread suspension could have occurred.
1867 if ((was_default_allocator && allocator != GetCurrentAllocator()) ||
1868 (!instrumented && EntrypointsInstrumented())) {
1869 return nullptr;
1870 }
Mathieu Chartier6a7824d2014-08-22 14:53:04 -07001871 switch (result) {
1872 case HomogeneousSpaceCompactResult::kSuccess:
1873 // If the allocation succeeded, we delayed an oom.
1874 ptr = TryToAllocate<true, true>(self, allocator, alloc_size, bytes_allocated,
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07001875 usable_size, bytes_tl_bulk_allocated);
Mathieu Chartier6a7824d2014-08-22 14:53:04 -07001876 if (ptr != nullptr) {
1877 count_delayed_oom_++;
1878 }
1879 break;
1880 case HomogeneousSpaceCompactResult::kErrorReject:
1881 // Reject due to disabled moving GC.
1882 break;
1883 case HomogeneousSpaceCompactResult::kErrorVMShuttingDown:
1884 // Throw OOM by default.
1885 break;
1886 default: {
Ian Rogers2c4257b2014-10-24 14:20:06 -07001887 UNIMPLEMENTED(FATAL) << "homogeneous space compaction result: "
1888 << static_cast<size_t>(result);
1889 UNREACHABLE();
Mathieu Chartier6a7824d2014-08-22 14:53:04 -07001890 }
Zuo Wangf37a88b2014-07-10 04:26:41 -07001891 }
Mathieu Chartier6a7824d2014-08-22 14:53:04 -07001892 // Always print that we ran homogeneous space compation since this can cause jank.
1893 VLOG(heap) << "Ran heap homogeneous space compaction, "
1894 << " requested defragmentation "
Orion Hodson88591fe2018-03-06 13:35:43 +00001895 << count_requested_homogeneous_space_compaction_.load()
Mathieu Chartier6a7824d2014-08-22 14:53:04 -07001896 << " performed defragmentation "
Orion Hodson88591fe2018-03-06 13:35:43 +00001897 << count_performed_homogeneous_space_compaction_.load()
Mathieu Chartier6a7824d2014-08-22 14:53:04 -07001898 << " ignored homogeneous space compaction "
Orion Hodson88591fe2018-03-06 13:35:43 +00001899 << count_ignored_homogeneous_space_compaction_.load()
Mathieu Chartier6a7824d2014-08-22 14:53:04 -07001900 << " delayed count = "
Orion Hodson88591fe2018-03-06 13:35:43 +00001901 << count_delayed_oom_.load();
Zuo Wangf37a88b2014-07-10 04:26:41 -07001902 }
Mathieu Chartier6a7824d2014-08-22 14:53:04 -07001903 break;
Zuo Wangf37a88b2014-07-10 04:26:41 -07001904 }
Mathieu Chartier6a7824d2014-08-22 14:53:04 -07001905 default: {
1906 // Do nothing for others allocators.
1907 }
Zuo Wangf37a88b2014-07-10 04:26:41 -07001908 }
1909 }
Alex Light986914b2019-11-19 01:12:25 +00001910#undef PERFORM_SUSPENDING_OPERATION
Zuo Wangf37a88b2014-07-10 04:26:41 -07001911 // If the allocation hasn't succeeded by this point, throw an OOM error.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001912 if (ptr == nullptr) {
Mathieu Chartierdc540df2019-11-15 17:11:44 -08001913 ScopedAllowThreadSuspension ats;
Hiroshi Yamauchi654dd482014-07-09 12:54:32 -07001914 ThrowOutOfMemoryError(self, alloc_size, allocator);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001915 }
Mathieu Chartiercbb2d202013-11-14 17:45:16 -08001916 return ptr;
Carl Shapiro69759ea2011-07-21 18:13:35 -07001917}
1918
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001919void Heap::SetTargetHeapUtilization(float target) {
Hans Boehmc220f982018-10-12 16:15:45 -07001920 DCHECK_GT(target, 0.1f); // asserted in Java code
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001921 DCHECK_LT(target, 1.0f);
1922 target_utilization_ = target;
1923}
1924
Ian Rogers1d54e732013-05-02 21:10:01 -07001925size_t Heap::GetObjectsAllocated() const {
Mathieu Chartier4f55e222015-09-04 13:26:21 -07001926 Thread* const self = Thread::Current();
Mathieu Chartierb43390c2015-05-12 10:47:11 -07001927 ScopedThreadStateChange tsc(self, kWaitingForGetObjectsAllocated);
Roland Levillainef012222017-06-21 16:28:06 +01001928 // Prevent GC running during GetObjectsAllocated since we may get a checkpoint request that tells
Mathieu Chartiere8649c72017-03-03 18:02:18 -08001929 // us to suspend while we are doing SuspendAll. b/35232978
1930 gc::ScopedGCCriticalSection gcs(Thread::Current(),
1931 gc::kGcCauseGetObjectsAllocated,
1932 gc::kCollectorTypeGetObjectsAllocated);
Mathieu Chartierb43390c2015-05-12 10:47:11 -07001933 // Need SuspendAll here to prevent lock violation if RosAlloc does it during InspectAll.
Mathieu Chartier4f55e222015-09-04 13:26:21 -07001934 ScopedSuspendAll ssa(__FUNCTION__);
1935 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Ian Rogers1d54e732013-05-02 21:10:01 -07001936 size_t total = 0;
Mathieu Chartier4f55e222015-09-04 13:26:21 -07001937 for (space::AllocSpace* space : alloc_spaces_) {
1938 total += space->GetObjectsAllocated();
Ian Rogers1d54e732013-05-02 21:10:01 -07001939 }
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001940 return total;
1941}
1942
Mathieu Chartierdd162fb2014-08-06 17:06:33 -07001943uint64_t Heap::GetObjectsAllocatedEver() const {
Mathieu Chartier4edd8472015-06-01 10:47:36 -07001944 uint64_t total = GetObjectsFreedEver();
1945 // If we are detached, we can't use GetObjectsAllocated since we can't change thread states.
1946 if (Thread::Current() != nullptr) {
1947 total += GetObjectsAllocated();
1948 }
1949 return total;
Ian Rogers1d54e732013-05-02 21:10:01 -07001950}
1951
Mathieu Chartierdd162fb2014-08-06 17:06:33 -07001952uint64_t Heap::GetBytesAllocatedEver() const {
Hans Boehm4c6d7652019-11-01 09:23:19 -07001953 // Force the returned value to be monotonically increasing, in the sense that if this is called
1954 // at A and B, such that A happens-before B, then the call at B returns a value no smaller than
1955 // that at A. This is not otherwise guaranteed, since num_bytes_allocated_ is decremented first,
1956 // and total_bytes_freed_ever_ is incremented later.
1957 static std::atomic<uint64_t> max_bytes_so_far(0);
1958 uint64_t so_far = max_bytes_so_far.load(std::memory_order_relaxed);
1959 uint64_t current_bytes = GetBytesFreedEver(std::memory_order_acquire);
1960 current_bytes += GetBytesAllocated();
1961 do {
1962 if (current_bytes <= so_far) {
1963 return so_far;
1964 }
1965 } while (!max_bytes_so_far.compare_exchange_weak(so_far /* updated */,
1966 current_bytes, std::memory_order_relaxed));
1967 return current_bytes;
Mathieu Chartier155dfe92012-10-09 14:24:49 -07001968}
1969
Richard Uhler660be6f2017-11-22 16:12:29 +00001970// Check whether the given object is an instance of the given class.
1971static bool MatchesClass(mirror::Object* obj,
1972 Handle<mirror::Class> h_class,
1973 bool use_is_assignable_from) REQUIRES_SHARED(Locks::mutator_lock_) {
1974 mirror::Class* instance_class = obj->GetClass();
1975 CHECK(instance_class != nullptr);
1976 ObjPtr<mirror::Class> klass = h_class.Get();
1977 if (use_is_assignable_from) {
1978 return klass != nullptr && klass->IsAssignableFrom(instance_class);
1979 }
1980 return instance_class == klass;
1981}
1982
Mathieu Chartier9d156d52016-10-06 17:44:26 -07001983void Heap::CountInstances(const std::vector<Handle<mirror::Class>>& classes,
1984 bool use_is_assignable_from,
Elliott Hughesec0f83d2013-01-15 16:54:08 -08001985 uint64_t* counts) {
Andreas Gampe1c158a02017-07-13 17:26:19 -07001986 auto instance_counter = [&](mirror::Object* obj) REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampe1c158a02017-07-13 17:26:19 -07001987 for (size_t i = 0; i < classes.size(); ++i) {
Richard Uhler660be6f2017-11-22 16:12:29 +00001988 if (MatchesClass(obj, classes[i], use_is_assignable_from)) {
Andreas Gampe1c158a02017-07-13 17:26:19 -07001989 ++counts[i];
Elliott Hughes3b78c942013-01-15 17:35:41 -08001990 }
1991 }
Andreas Gampe1c158a02017-07-13 17:26:19 -07001992 };
1993 VisitObjects(instance_counter);
Elliott Hughes3b78c942013-01-15 17:35:41 -08001994}
1995
Andreas Gampe94c589d2017-12-27 12:43:01 -08001996void Heap::CollectGarbage(bool clear_soft_references, GcCause cause) {
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07001997 // Even if we waited for a GC we still need to do another GC since weaks allocated during the
1998 // last GC will not have necessarily been cleared.
Andreas Gampe94c589d2017-12-27 12:43:01 -08001999 CollectGarbageInternal(gc_plan_.back(), cause, clear_soft_references);
Carl Shapiro69759ea2011-07-21 18:13:35 -07002000}
2001
Mathieu Chartierdb00eaf2015-08-31 17:10:05 -07002002bool Heap::SupportHomogeneousSpaceCompactAndCollectorTransitions() const {
2003 return main_space_backup_.get() != nullptr && main_space_ != nullptr &&
2004 foreground_collector_type_ == kCollectorTypeCMS;
2005}
2006
Zuo Wangf37a88b2014-07-10 04:26:41 -07002007HomogeneousSpaceCompactResult Heap::PerformHomogeneousSpaceCompact() {
2008 Thread* self = Thread::Current();
2009 // Inc requested homogeneous space compaction.
2010 count_requested_homogeneous_space_compaction_++;
2011 // Store performed homogeneous space compaction at a new request arrival.
Zuo Wangf37a88b2014-07-10 04:26:41 -07002012 ScopedThreadStateChange tsc(self, kWaitingPerformingGc);
Ziang Wan92db59b2019-07-22 21:19:24 +00002013 Locks::mutator_lock_->AssertNotHeld(self);
Zuo Wangf37a88b2014-07-10 04:26:41 -07002014 {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002015 ScopedThreadStateChange tsc2(self, kWaitingForGcToComplete);
Zuo Wangf37a88b2014-07-10 04:26:41 -07002016 MutexLock mu(self, *gc_complete_lock_);
2017 // Ensure there is only one GC at a time.
2018 WaitForGcToCompleteLocked(kGcCauseHomogeneousSpaceCompact, self);
Roland Levillain2ae376f2018-01-30 11:35:11 +00002019 // Homogeneous space compaction is a copying transition, can't run it if the moving GC disable
2020 // count is non zero.
2021 // If the collector type changed to something which doesn't benefit from homogeneous space
2022 // compaction, exit.
Mathieu Chartier6a7824d2014-08-22 14:53:04 -07002023 if (disable_moving_gc_count_ != 0 || IsMovingGc(collector_type_) ||
2024 !main_space_->CanMoveObjects()) {
Mathieu Chartierdb00eaf2015-08-31 17:10:05 -07002025 return kErrorReject;
2026 }
2027 if (!SupportHomogeneousSpaceCompactAndCollectorTransitions()) {
2028 return kErrorUnsupported;
Zuo Wangf37a88b2014-07-10 04:26:41 -07002029 }
2030 collector_type_running_ = kCollectorTypeHomogeneousSpaceCompact;
2031 }
2032 if (Runtime::Current()->IsShuttingDown(self)) {
2033 // Don't allow heap transitions to happen if the runtime is shutting down since these can
2034 // cause objects to get finalized.
2035 FinishGC(self, collector::kGcTypeNone);
2036 return HomogeneousSpaceCompactResult::kErrorVMShuttingDown;
2037 }
Mathieu Chartier4f55e222015-09-04 13:26:21 -07002038 collector::GarbageCollector* collector;
2039 {
2040 ScopedSuspendAll ssa(__FUNCTION__);
2041 uint64_t start_time = NanoTime();
2042 // Launch compaction.
2043 space::MallocSpace* to_space = main_space_backup_.release();
2044 space::MallocSpace* from_space = main_space_;
2045 to_space->GetMemMap()->Protect(PROT_READ | PROT_WRITE);
2046 const uint64_t space_size_before_compaction = from_space->Size();
2047 AddSpace(to_space);
2048 // Make sure that we will have enough room to copy.
2049 CHECK_GE(to_space->GetFootprintLimit(), from_space->GetFootprintLimit());
2050 collector = Compact(to_space, from_space, kGcCauseHomogeneousSpaceCompact);
2051 const uint64_t space_size_after_compaction = to_space->Size();
2052 main_space_ = to_space;
2053 main_space_backup_.reset(from_space);
2054 RemoveSpace(from_space);
2055 SetSpaceAsDefault(main_space_); // Set as default to reset the proper dlmalloc space.
2056 // Update performed homogeneous space compaction count.
2057 count_performed_homogeneous_space_compaction_++;
2058 // Print statics log and resume all threads.
2059 uint64_t duration = NanoTime() - start_time;
2060 VLOG(heap) << "Heap homogeneous space compaction took " << PrettyDuration(duration) << " size: "
2061 << PrettySize(space_size_before_compaction) << " -> "
2062 << PrettySize(space_size_after_compaction) << " compact-ratio: "
2063 << std::fixed << static_cast<double>(space_size_after_compaction) /
2064 static_cast<double>(space_size_before_compaction);
2065 }
Zuo Wangf37a88b2014-07-10 04:26:41 -07002066 // Finish GC.
Alex Lighte3020882019-05-13 16:35:02 -07002067 // Get the references we need to enqueue.
2068 SelfDeletingTask* clear = reference_processor_->CollectClearedReferences(self);
Zuo Wangf37a88b2014-07-10 04:26:41 -07002069 GrowForUtilization(semi_space_collector_);
Hiroshi Yamauchie4d99872015-02-26 12:53:45 -08002070 LogGC(kGcCauseHomogeneousSpaceCompact, collector);
Zuo Wangf37a88b2014-07-10 04:26:41 -07002071 FinishGC(self, collector::kGcTypeFull);
Alex Lighte3020882019-05-13 16:35:02 -07002072 // Enqueue any references after losing the GC locks.
2073 clear->Run(self);
2074 clear->Finalize();
Mathieu Chartier598302a2015-09-23 14:52:39 -07002075 {
2076 ScopedObjectAccess soa(self);
2077 soa.Vm()->UnloadNativeLibraries();
2078 }
Zuo Wangf37a88b2014-07-10 04:26:41 -07002079 return HomogeneousSpaceCompactResult::kSuccess;
2080}
2081
Mathieu Chartier0de9f732013-11-22 17:58:48 -08002082void Heap::ChangeCollector(CollectorType collector_type) {
Mathieu Chartier7bf82af2013-12-06 16:51:45 -08002083 // TODO: Only do this with all mutators suspended to avoid races.
2084 if (collector_type != collector_type_) {
2085 collector_type_ = collector_type;
2086 gc_plan_.clear();
2087 switch (collector_type_) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002088 case kCollectorTypeCC: {
Albert Mingkun Yang0b4d1462018-11-29 13:25:35 +00002089 if (use_generational_cc_) {
Mathieu Chartier8d1a9962016-08-17 16:39:45 -07002090 gc_plan_.push_back(collector::kGcTypeSticky);
2091 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002092 gc_plan_.push_back(collector::kGcTypeFull);
2093 if (use_tlab_) {
2094 ChangeAllocator(kAllocatorTypeRegionTLAB);
2095 } else {
2096 ChangeAllocator(kAllocatorTypeRegion);
2097 }
2098 break;
2099 }
Mathieu Chartierf75dce42019-04-08 09:36:23 -07002100 case kCollectorTypeSS: {
Mathieu Chartier7bf82af2013-12-06 16:51:45 -08002101 gc_plan_.push_back(collector::kGcTypeFull);
Mathieu Chartier692fafd2013-11-29 17:24:40 -08002102 if (use_tlab_) {
2103 ChangeAllocator(kAllocatorTypeTLAB);
2104 } else {
2105 ChangeAllocator(kAllocatorTypeBumpPointer);
2106 }
Mathieu Chartier7bf82af2013-12-06 16:51:45 -08002107 break;
2108 }
2109 case kCollectorTypeMS: {
Mathieu Chartier7bf82af2013-12-06 16:51:45 -08002110 gc_plan_.push_back(collector::kGcTypeSticky);
2111 gc_plan_.push_back(collector::kGcTypePartial);
2112 gc_plan_.push_back(collector::kGcTypeFull);
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08002113 ChangeAllocator(kUseRosAlloc ? kAllocatorTypeRosAlloc : kAllocatorTypeDlMalloc);
Mathieu Chartier7bf82af2013-12-06 16:51:45 -08002114 break;
2115 }
2116 case kCollectorTypeCMS: {
Mathieu Chartier7bf82af2013-12-06 16:51:45 -08002117 gc_plan_.push_back(collector::kGcTypeSticky);
2118 gc_plan_.push_back(collector::kGcTypePartial);
2119 gc_plan_.push_back(collector::kGcTypeFull);
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08002120 ChangeAllocator(kUseRosAlloc ? kAllocatorTypeRosAlloc : kAllocatorTypeDlMalloc);
Mathieu Chartier7bf82af2013-12-06 16:51:45 -08002121 break;
2122 }
2123 default: {
Ian Rogers2c4257b2014-10-24 14:20:06 -07002124 UNIMPLEMENTED(FATAL);
2125 UNREACHABLE();
Mathieu Chartier7bf82af2013-12-06 16:51:45 -08002126 }
Mathieu Chartier0de9f732013-11-22 17:58:48 -08002127 }
Hiroshi Yamauchi3e417802014-03-20 12:03:02 -07002128 if (IsGcConcurrent()) {
Mathieu Chartier7bf82af2013-12-06 16:51:45 -08002129 concurrent_start_bytes_ =
Hans Boehmc220f982018-10-12 16:15:45 -07002130 UnsignedDifference(target_footprint_.load(std::memory_order_relaxed),
2131 kMinConcurrentRemainingBytes);
Mathieu Chartier7bf82af2013-12-06 16:51:45 -08002132 } else {
2133 concurrent_start_bytes_ = std::numeric_limits<size_t>::max();
Mathieu Chartier0de9f732013-11-22 17:58:48 -08002134 }
2135 }
2136}
2137
Mathieu Chartier85a43c02014-01-07 17:59:00 -08002138// Special compacting collector which uses sub-optimal bin packing to reduce zygote space size.
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01002139class ZygoteCompactingCollector final : public collector::SemiSpace {
Mathieu Chartier85a43c02014-01-07 17:59:00 -08002140 public:
Roland Levillain3887c462015-08-12 18:15:42 +01002141 ZygoteCompactingCollector(gc::Heap* heap, bool is_running_on_memory_tool)
Mathieu Chartierf75dce42019-04-08 09:36:23 -07002142 : SemiSpace(heap, "zygote collector"),
Evgenii Stepanov1e133742015-05-20 12:30:59 -07002143 bin_live_bitmap_(nullptr),
2144 bin_mark_bitmap_(nullptr),
2145 is_running_on_memory_tool_(is_running_on_memory_tool) {}
Mathieu Chartier85a43c02014-01-07 17:59:00 -08002146
Andreas Gampe0c183382017-07-13 22:26:24 -07002147 void BuildBins(space::ContinuousSpace* space) REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier85a43c02014-01-07 17:59:00 -08002148 bin_live_bitmap_ = space->GetLiveBitmap();
2149 bin_mark_bitmap_ = space->GetMarkBitmap();
Andreas Gampe0c183382017-07-13 22:26:24 -07002150 uintptr_t prev = reinterpret_cast<uintptr_t>(space->Begin());
Mathieu Chartier85a43c02014-01-07 17:59:00 -08002151 WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
2152 // Note: This requires traversing the space in increasing order of object addresses.
Andreas Gampe0c183382017-07-13 22:26:24 -07002153 auto visitor = [&](mirror::Object* obj) REQUIRES_SHARED(Locks::mutator_lock_) {
2154 uintptr_t object_addr = reinterpret_cast<uintptr_t>(obj);
2155 size_t bin_size = object_addr - prev;
2156 // Add the bin consisting of the end of the previous object to the start of the current object.
2157 AddBin(bin_size, prev);
2158 prev = object_addr + RoundUp(obj->SizeOf<kDefaultVerifyFlags>(), kObjectAlignment);
2159 };
2160 bin_live_bitmap_->Walk(visitor);
Mathieu Chartier85a43c02014-01-07 17:59:00 -08002161 // Add the last bin which spans after the last object to the end of the space.
Andreas Gampe0c183382017-07-13 22:26:24 -07002162 AddBin(reinterpret_cast<uintptr_t>(space->End()) - prev, prev);
Mathieu Chartier85a43c02014-01-07 17:59:00 -08002163 }
2164
2165 private:
Mathieu Chartier85a43c02014-01-07 17:59:00 -08002166 // Maps from bin sizes to locations.
2167 std::multimap<size_t, uintptr_t> bins_;
2168 // Live bitmap of the space which contains the bins.
Mathieu Chartiera8e8f9c2014-04-09 14:51:05 -07002169 accounting::ContinuousSpaceBitmap* bin_live_bitmap_;
Mathieu Chartier85a43c02014-01-07 17:59:00 -08002170 // Mark bitmap of the space which contains the bins.
Mathieu Chartiera8e8f9c2014-04-09 14:51:05 -07002171 accounting::ContinuousSpaceBitmap* bin_mark_bitmap_;
Evgenii Stepanov1e133742015-05-20 12:30:59 -07002172 const bool is_running_on_memory_tool_;
Mathieu Chartier85a43c02014-01-07 17:59:00 -08002173
Mathieu Chartier85a43c02014-01-07 17:59:00 -08002174 void AddBin(size_t size, uintptr_t position) {
Evgenii Stepanov1e133742015-05-20 12:30:59 -07002175 if (is_running_on_memory_tool_) {
2176 MEMORY_TOOL_MAKE_DEFINED(reinterpret_cast<void*>(position), size);
2177 }
Mathieu Chartier85a43c02014-01-07 17:59:00 -08002178 if (size != 0) {
2179 bins_.insert(std::make_pair(size, position));
2180 }
2181 }
2182
Andreas Gampefa6a1b02018-09-07 08:11:55 -07002183 bool ShouldSweepSpace(space::ContinuousSpace* space ATTRIBUTE_UNUSED) const override {
Mathieu Chartier85a43c02014-01-07 17:59:00 -08002184 // Don't sweep any spaces since we probably blasted the internal accounting of the free list
2185 // allocator.
2186 return false;
2187 }
2188
Andreas Gampefa6a1b02018-09-07 08:11:55 -07002189 mirror::Object* MarkNonForwardedObject(mirror::Object* obj) override
Mathieu Chartier90443472015-07-16 20:32:27 -07002190 REQUIRES(Locks::heap_bitmap_lock_, Locks::mutator_lock_) {
Mathieu Chartierd08f66f2017-04-13 11:47:53 -07002191 size_t obj_size = obj->SizeOf<kDefaultVerifyFlags>();
Hiroshi Yamauchi8711d1f2015-03-13 16:48:55 -07002192 size_t alloc_size = RoundUp(obj_size, kObjectAlignment);
Mathieu Chartier5dc08a62014-01-10 10:10:23 -08002193 mirror::Object* forward_address;
Mathieu Chartier85a43c02014-01-07 17:59:00 -08002194 // Find the smallest bin which we can move obj in.
Hiroshi Yamauchi8711d1f2015-03-13 16:48:55 -07002195 auto it = bins_.lower_bound(alloc_size);
Mathieu Chartier85a43c02014-01-07 17:59:00 -08002196 if (it == bins_.end()) {
2197 // No available space in the bins, place it in the target space instead (grows the zygote
2198 // space).
Roland Levillain3c98d692020-07-27 16:25:54 +01002199 size_t bytes_allocated, unused_bytes_tl_bulk_allocated;
2200 forward_address = to_space_->Alloc(
2201 self_, alloc_size, &bytes_allocated, nullptr, &unused_bytes_tl_bulk_allocated);
Mathieu Chartier85a43c02014-01-07 17:59:00 -08002202 if (to_space_live_bitmap_ != nullptr) {
2203 to_space_live_bitmap_->Set(forward_address);
Mathieu Chartier938a03b2014-01-16 15:10:31 -08002204 } else {
2205 GetHeap()->GetNonMovingSpace()->GetLiveBitmap()->Set(forward_address);
2206 GetHeap()->GetNonMovingSpace()->GetMarkBitmap()->Set(forward_address);
Mathieu Chartier85a43c02014-01-07 17:59:00 -08002207 }
2208 } else {
2209 size_t size = it->first;
2210 uintptr_t pos = it->second;
2211 bins_.erase(it); // Erase the old bin which we replace with the new smaller bin.
2212 forward_address = reinterpret_cast<mirror::Object*>(pos);
2213 // Set the live and mark bits so that sweeping system weaks works properly.
2214 bin_live_bitmap_->Set(forward_address);
2215 bin_mark_bitmap_->Set(forward_address);
Hiroshi Yamauchi8711d1f2015-03-13 16:48:55 -07002216 DCHECK_GE(size, alloc_size);
2217 // Add a new bin with the remaining space.
2218 AddBin(size - alloc_size, pos + alloc_size);
Mathieu Chartier85a43c02014-01-07 17:59:00 -08002219 }
Roland Levillain05e34f42018-05-24 13:19:05 +00002220 // Copy the object over to its new location.
2221 // Historical note: We did not use `alloc_size` to avoid a Valgrind error.
Hiroshi Yamauchi8711d1f2015-03-13 16:48:55 -07002222 memcpy(reinterpret_cast<void*>(forward_address), obj, obj_size);
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07002223 if (kUseBakerReadBarrier) {
2224 obj->AssertReadBarrierState();
2225 forward_address->AssertReadBarrierState();
Hiroshi Yamauchi9d04a202014-01-31 13:35:49 -08002226 }
Mathieu Chartier85a43c02014-01-07 17:59:00 -08002227 return forward_address;
2228 }
2229};
2230
Mathieu Chartiera1602f22014-01-13 17:19:19 -08002231void Heap::UnBindBitmaps() {
Mathieu Chartierf5997b42014-06-20 10:37:54 -07002232 TimingLogger::ScopedTiming t("UnBindBitmaps", GetCurrentGcIteration()->GetTimings());
Mathieu Chartiera1602f22014-01-13 17:19:19 -08002233 for (const auto& space : GetContinuousSpaces()) {
2234 if (space->IsContinuousMemMapAllocSpace()) {
2235 space::ContinuousMemMapAllocSpace* alloc_space = space->AsContinuousMemMapAllocSpace();
Mathieu Chartier7c502742019-08-01 12:47:18 -07002236 if (alloc_space->GetLiveBitmap() != nullptr && alloc_space->HasBoundBitmaps()) {
Mathieu Chartiera1602f22014-01-13 17:19:19 -08002237 alloc_space->UnBindBitmaps();
2238 }
2239 }
2240 }
2241}
2242
Hans Boehm4c6d7652019-11-01 09:23:19 -07002243void Heap::IncrementFreedEver() {
2244 // Counters are updated only by us, but may be read concurrently.
2245 // The updates should become visible after the corresponding live object info.
2246 total_objects_freed_ever_.store(total_objects_freed_ever_.load(std::memory_order_relaxed)
2247 + GetCurrentGcIteration()->GetFreedObjects()
2248 + GetCurrentGcIteration()->GetFreedLargeObjects(),
2249 std::memory_order_release);
2250 total_bytes_freed_ever_.store(total_bytes_freed_ever_.load(std::memory_order_relaxed)
2251 + GetCurrentGcIteration()->GetFreedBytes()
2252 + GetCurrentGcIteration()->GetFreedLargeObjectBytes(),
2253 std::memory_order_release);
2254}
2255
Hans Boehm65c18a22020-01-03 23:37:13 +00002256#pragma clang diagnostic push
2257#if !ART_USE_FUTEXES
2258// Frame gets too large, perhaps due to Bionic pthread_mutex_lock size. We don't care.
2259# pragma clang diagnostic ignored "-Wframe-larger-than="
2260#endif
2261// This has a large frame, but shouldn't be run anywhere near the stack limit.
Mathieu Chartiercc236d72012-07-20 10:29:05 -07002262void Heap::PreZygoteFork() {
Mathieu Chartierfaed9952015-03-31 16:28:53 -07002263 if (!HasZygoteSpace()) {
2264 // We still want to GC in case there is some unreachable non moving objects that could cause a
2265 // suboptimal bin packing when we compact the zygote space.
2266 CollectGarbageInternal(collector::kGcTypeFull, kGcCauseBackground, false);
Mathieu Chartier76ce9172016-01-27 10:44:20 -08002267 // Trim the pages at the end of the non moving space. Trim while not holding zygote lock since
2268 // the trim process may require locking the mutator lock.
2269 non_moving_space_->Trim();
Mathieu Chartierfaed9952015-03-31 16:28:53 -07002270 }
Ian Rogers81d425b2012-09-27 16:03:43 -07002271 Thread* self = Thread::Current();
2272 MutexLock mu(self, zygote_creation_lock_);
Mathieu Chartiercc236d72012-07-20 10:29:05 -07002273 // Try to see if we have any Zygote spaces.
Mathieu Chartiere4cab172014-08-19 18:24:04 -07002274 if (HasZygoteSpace()) {
Mathieu Chartiercc236d72012-07-20 10:29:05 -07002275 return;
2276 }
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002277 Runtime::Current()->GetInternTable()->AddNewTable();
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002278 Runtime::Current()->GetClassLinker()->MoveClassTableToPreZygote();
Mathieu Chartier590fee92013-09-13 13:46:47 -07002279 VLOG(heap) << "Starting PreZygoteFork";
Mathieu Chartier31f44142014-04-08 14:40:03 -07002280 // The end of the non-moving space may be protected, unprotect it so that we can copy the zygote
2281 // there.
Mathieu Chartier590fee92013-09-13 13:46:47 -07002282 non_moving_space_->GetMemMap()->Protect(PROT_READ | PROT_WRITE);
Mathieu Chartier6a7824d2014-08-22 14:53:04 -07002283 const bool same_space = non_moving_space_ == main_space_;
Mathieu Chartier31f44142014-04-08 14:40:03 -07002284 if (kCompactZygote) {
Hiroshi Yamauchia4adbfd2014-02-04 18:12:17 -08002285 // Temporarily disable rosalloc verification because the zygote
2286 // compaction will mess up the rosalloc internal metadata.
2287 ScopedDisableRosAllocVerification disable_rosalloc_verif(this);
Evgenii Stepanov1e133742015-05-20 12:30:59 -07002288 ZygoteCompactingCollector zygote_collector(this, is_running_on_memory_tool_);
Mathieu Chartier85a43c02014-01-07 17:59:00 -08002289 zygote_collector.BuildBins(non_moving_space_);
Mathieu Chartier50482232013-11-21 11:48:14 -08002290 // Create a new bump pointer space which we will compact into.
Mathieu Chartier590fee92013-09-13 13:46:47 -07002291 space::BumpPointerSpace target_space("zygote bump space", non_moving_space_->End(),
2292 non_moving_space_->Limit());
2293 // Compact the bump pointer space to a new zygote bump pointer space.
Mathieu Chartier31f44142014-04-08 14:40:03 -07002294 bool reset_main_space = false;
2295 if (IsMovingGc(collector_type_)) {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002296 if (collector_type_ == kCollectorTypeCC) {
2297 zygote_collector.SetFromSpace(region_space_);
2298 } else {
2299 zygote_collector.SetFromSpace(bump_pointer_space_);
2300 }
Mathieu Chartier31f44142014-04-08 14:40:03 -07002301 } else {
2302 CHECK(main_space_ != nullptr);
Hiroshi Yamauchid04495e2015-03-11 19:09:07 -07002303 CHECK_NE(main_space_, non_moving_space_)
2304 << "Does not make sense to compact within the same space";
Mathieu Chartier31f44142014-04-08 14:40:03 -07002305 // Copy from the main space.
2306 zygote_collector.SetFromSpace(main_space_);
2307 reset_main_space = true;
2308 }
Mathieu Chartier85a43c02014-01-07 17:59:00 -08002309 zygote_collector.SetToSpace(&target_space);
Mathieu Chartier1b54f9c2014-04-30 16:45:02 -07002310 zygote_collector.SetSwapSemiSpaces(false);
Hiroshi Yamauchi6f4ffe42014-01-13 12:30:44 -08002311 zygote_collector.Run(kGcCauseCollectorTransition, false);
Mathieu Chartier31f44142014-04-08 14:40:03 -07002312 if (reset_main_space) {
2313 main_space_->GetMemMap()->Protect(PROT_READ | PROT_WRITE);
2314 madvise(main_space_->Begin(), main_space_->Capacity(), MADV_DONTNEED);
Vladimir Markoc34bebf2018-08-16 16:12:49 +01002315 MemMap mem_map = main_space_->ReleaseMemMap();
Mathieu Chartier31f44142014-04-08 14:40:03 -07002316 RemoveSpace(main_space_);
Mathieu Chartier96bcd452014-06-17 09:50:02 -07002317 space::Space* old_main_space = main_space_;
Vladimir Markoc34bebf2018-08-16 16:12:49 +01002318 CreateMainMallocSpace(std::move(mem_map),
2319 kDefaultInitialSize,
2320 std::min(mem_map.Size(), growth_limit_),
2321 mem_map.Size());
Mathieu Chartier96bcd452014-06-17 09:50:02 -07002322 delete old_main_space;
Mathieu Chartier31f44142014-04-08 14:40:03 -07002323 AddSpace(main_space_);
2324 } else {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002325 if (collector_type_ == kCollectorTypeCC) {
2326 region_space_->GetMemMap()->Protect(PROT_READ | PROT_WRITE);
Mathieu Chartier7ec38dc2016-10-07 15:24:46 -07002327 // Evacuated everything out of the region space, clear the mark bitmap.
2328 region_space_->GetMarkBitmap()->Clear();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002329 } else {
2330 bump_pointer_space_->GetMemMap()->Protect(PROT_READ | PROT_WRITE);
2331 }
Mathieu Chartier31f44142014-04-08 14:40:03 -07002332 }
2333 if (temp_space_ != nullptr) {
2334 CHECK(temp_space_->IsEmpty());
2335 }
Hans Boehm4c6d7652019-11-01 09:23:19 -07002336 IncrementFreedEver();
Mathieu Chartier590fee92013-09-13 13:46:47 -07002337 // Update the end and write out image.
2338 non_moving_space_->SetEnd(target_space.End());
2339 non_moving_space_->SetLimit(target_space.Limit());
Mathieu Chartierfaed9952015-03-31 16:28:53 -07002340 VLOG(heap) << "Create zygote space with size=" << non_moving_space_->Size() << " bytes";
Mathieu Chartier357e9be2012-08-01 11:00:14 -07002341 }
Mathieu Chartier6a7824d2014-08-22 14:53:04 -07002342 // Change the collector to the post zygote one.
Mathieu Chartier31f44142014-04-08 14:40:03 -07002343 ChangeCollector(foreground_collector_type_);
Mathieu Chartiera1602f22014-01-13 17:19:19 -08002344 // Save the old space so that we can remove it after we complete creating the zygote space.
2345 space::MallocSpace* old_alloc_space = non_moving_space_;
Mathieu Chartier590fee92013-09-13 13:46:47 -07002346 // Turn the current alloc space into a zygote space and obtain the new alloc space composed of
Mathieu Chartiera1602f22014-01-13 17:19:19 -08002347 // the remaining available space.
2348 // Remove the old space before creating the zygote space since creating the zygote space sets
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002349 // the old alloc space's bitmaps to null.
Mathieu Chartiera1602f22014-01-13 17:19:19 -08002350 RemoveSpace(old_alloc_space);
Hiroshi Yamauchi38e68e92014-03-07 13:59:08 -08002351 if (collector::SemiSpace::kUseRememberedSet) {
David Srbecky346fd962020-07-27 16:51:00 +01002352 // Consistency bound check.
Hiroshi Yamauchi38e68e92014-03-07 13:59:08 -08002353 FindRememberedSetFromSpace(old_alloc_space)->AssertAllDirtyCardsAreWithinSpace();
2354 // Remove the remembered set for the now zygote space (the old
2355 // non-moving space). Note now that we have compacted objects into
2356 // the zygote space, the data in the remembered set is no longer
2357 // needed. The zygote space will instead have a mod-union table
2358 // from this point on.
2359 RemoveRememberedSet(old_alloc_space);
2360 }
Mathieu Chartier7247af52014-11-19 10:51:42 -08002361 // Remaining space becomes the new non moving space.
2362 zygote_space_ = old_alloc_space->CreateZygoteSpace(kNonMovingSpaceName, low_memory_mode_,
Mathieu Chartiere4cab172014-08-19 18:24:04 -07002363 &non_moving_space_);
Mathieu Chartierb363f662014-07-16 13:28:58 -07002364 CHECK(!non_moving_space_->CanMoveObjects());
2365 if (same_space) {
2366 main_space_ = non_moving_space_;
2367 SetSpaceAsDefault(main_space_);
2368 }
Mathieu Chartiera1602f22014-01-13 17:19:19 -08002369 delete old_alloc_space;
Mathieu Chartiere4cab172014-08-19 18:24:04 -07002370 CHECK(HasZygoteSpace()) << "Failed creating zygote space";
2371 AddSpace(zygote_space_);
Mathieu Chartier31f44142014-04-08 14:40:03 -07002372 non_moving_space_->SetFootprintLimit(non_moving_space_->Capacity());
2373 AddSpace(non_moving_space_);
Lokesh Gidra8787cf82019-07-11 12:50:31 -07002374 constexpr bool set_mark_bit = kUseBakerReadBarrier
2375 && gc::collector::ConcurrentCopying::kGrayDirtyImmuneObjects;
2376 if (set_mark_bit) {
Mathieu Chartier36a270a2016-07-28 18:08:51 -07002377 // Treat all of the objects in the zygote as marked to avoid unnecessary dirty pages. This is
2378 // safe since we mark all of the objects that may reference non immune objects as gray.
Lokesh Gidra52c468a2019-07-18 18:16:04 -07002379 zygote_space_->SetMarkBitInLiveObjects();
Mathieu Chartier36a270a2016-07-28 18:08:51 -07002380 }
2381
Mathieu Chartier11409ae2013-09-23 11:49:36 -07002382 // Create the zygote space mod union table.
2383 accounting::ModUnionTable* mod_union_table =
Mathieu Chartier962cd7a2016-08-16 12:15:59 -07002384 new accounting::ModUnionTableCardCache("zygote space mod-union table", this, zygote_space_);
Mathieu Chartier11409ae2013-09-23 11:49:36 -07002385 CHECK(mod_union_table != nullptr) << "Failed to create zygote space mod-union table";
Mathieu Chartier962cd7a2016-08-16 12:15:59 -07002386
2387 if (collector_type_ != kCollectorTypeCC) {
2388 // Set all the cards in the mod-union table since we don't know which objects contain references
2389 // to large objects.
2390 mod_union_table->SetCards();
2391 } else {
Mathieu Chartier55c05f52017-04-11 11:12:28 -07002392 // Make sure to clear the zygote space cards so that we don't dirty pages in the next GC. There
2393 // may be dirty cards from the zygote compaction or reference processing. These cards are not
2394 // necessary to have marked since the zygote space may not refer to any objects not in the
2395 // zygote or image spaces at this point.
2396 mod_union_table->ProcessCards();
2397 mod_union_table->ClearTable();
2398
Mathieu Chartier962cd7a2016-08-16 12:15:59 -07002399 // For CC we never collect zygote large objects. This means we do not need to set the cards for
2400 // the zygote mod-union table and we can also clear all of the existing image mod-union tables.
2401 // The existing mod-union tables are only for image spaces and may only reference zygote and
2402 // image objects.
2403 for (auto& pair : mod_union_tables_) {
2404 CHECK(pair.first->IsImageSpace());
2405 CHECK(!pair.first->AsImageSpace()->GetImageHeader().IsAppImage());
2406 accounting::ModUnionTable* table = pair.second;
2407 table->ClearTable();
2408 }
2409 }
Mathieu Chartier11409ae2013-09-23 11:49:36 -07002410 AddModUnionTable(mod_union_table);
Lokesh Gidra8787cf82019-07-11 12:50:31 -07002411 large_object_space_->SetAllLargeObjectsAsZygoteObjects(self, set_mark_bit);
Hiroshi Yamauchi38e68e92014-03-07 13:59:08 -08002412 if (collector::SemiSpace::kUseRememberedSet) {
Hiroshi Yamauchi38e68e92014-03-07 13:59:08 -08002413 // Add a new remembered set for the post-zygote non-moving space.
2414 accounting::RememberedSet* post_zygote_non_moving_space_rem_set =
2415 new accounting::RememberedSet("Post-zygote non-moving space remembered set", this,
2416 non_moving_space_);
2417 CHECK(post_zygote_non_moving_space_rem_set != nullptr)
2418 << "Failed to create post-zygote non-moving space remembered set";
2419 AddRememberedSet(post_zygote_non_moving_space_rem_set);
2420 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -07002421}
Hans Boehm65c18a22020-01-03 23:37:13 +00002422#pragma clang diagnostic pop
Mathieu Chartiercc236d72012-07-20 10:29:05 -07002423
Mathieu Chartier357e9be2012-08-01 11:00:14 -07002424void Heap::FlushAllocStack() {
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08002425 MarkAllocStackAsLive(allocation_stack_.get());
Mathieu Chartier357e9be2012-08-01 11:00:14 -07002426 allocation_stack_->Reset();
2427}
2428
Mathieu Chartiera8e8f9c2014-04-09 14:51:05 -07002429void Heap::MarkAllocStack(accounting::ContinuousSpaceBitmap* bitmap1,
2430 accounting::ContinuousSpaceBitmap* bitmap2,
Mathieu Chartierbbd695c2014-04-16 09:48:48 -07002431 accounting::LargeObjectBitmap* large_objects,
Ian Rogers1d54e732013-05-02 21:10:01 -07002432 accounting::ObjectStack* stack) {
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08002433 DCHECK(bitmap1 != nullptr);
2434 DCHECK(bitmap2 != nullptr);
Mathieu Chartiercb535da2015-01-23 13:50:03 -08002435 const auto* limit = stack->End();
2436 for (auto* it = stack->Begin(); it != limit; ++it) {
2437 const mirror::Object* obj = it->AsMirrorPtr();
Hiroshi Yamauchif5b0e202014-02-11 17:02:22 -08002438 if (!kUseThreadLocalAllocationStack || obj != nullptr) {
2439 if (bitmap1->HasAddress(obj)) {
2440 bitmap1->Set(obj);
2441 } else if (bitmap2->HasAddress(obj)) {
2442 bitmap2->Set(obj);
2443 } else {
Mathieu Chartier2dbe6272014-09-16 10:43:23 -07002444 DCHECK(large_objects != nullptr);
Hiroshi Yamauchif5b0e202014-02-11 17:02:22 -08002445 large_objects->Set(obj);
2446 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07002447 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07002448 }
2449}
2450
Mathieu Chartier590fee92013-09-13 13:46:47 -07002451void Heap::SwapSemiSpaces() {
Mathieu Chartier31f44142014-04-08 14:40:03 -07002452 CHECK(bump_pointer_space_ != nullptr);
2453 CHECK(temp_space_ != nullptr);
Mathieu Chartier590fee92013-09-13 13:46:47 -07002454 std::swap(bump_pointer_space_, temp_space_);
2455}
2456
Hiroshi Yamauchie4d99872015-02-26 12:53:45 -08002457collector::GarbageCollector* Heap::Compact(space::ContinuousMemMapAllocSpace* target_space,
2458 space::ContinuousMemMapAllocSpace* source_space,
2459 GcCause gc_cause) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07002460 CHECK(kMovingCollector);
Mathieu Chartier590fee92013-09-13 13:46:47 -07002461 if (target_space != source_space) {
Mathieu Chartier6f365cc2014-04-23 12:42:27 -07002462 // Don't swap spaces since this isn't a typical semi space collection.
2463 semi_space_collector_->SetSwapSemiSpaces(false);
Mathieu Chartier590fee92013-09-13 13:46:47 -07002464 semi_space_collector_->SetFromSpace(source_space);
2465 semi_space_collector_->SetToSpace(target_space);
Zuo Wangf37a88b2014-07-10 04:26:41 -07002466 semi_space_collector_->Run(gc_cause, false);
Hiroshi Yamauchie4d99872015-02-26 12:53:45 -08002467 return semi_space_collector_;
Mathieu Chartier590fee92013-09-13 13:46:47 -07002468 }
Mathieu Chartierf8e5d8c2018-04-06 13:35:37 -07002469 LOG(FATAL) << "Unsupported";
2470 UNREACHABLE();
Mathieu Chartier590fee92013-09-13 13:46:47 -07002471}
Anwar Ghuloum67f99412013-08-12 14:19:48 -07002472
Mathieu Chartier34afcde2017-06-30 15:31:11 -07002473void Heap::TraceHeapSize(size_t heap_size) {
Orion Hodson119733d2019-01-30 15:14:41 +00002474 ATraceIntegerValue("Heap size (KB)", heap_size / KB);
Mathieu Chartier34afcde2017-06-30 15:31:11 -07002475}
2476
Hans Boehm13e951d2019-11-01 16:48:28 -07002477#if defined(__GLIBC__)
2478# define IF_GLIBC(x) x
2479#else
2480# define IF_GLIBC(x)
2481#endif
2482
Hans Boehmc220f982018-10-12 16:15:45 -07002483size_t Heap::GetNativeBytes() {
2484 size_t malloc_bytes;
Hans Boehmc220f982018-10-12 16:15:45 -07002485#if defined(__BIONIC__) || defined(__GLIBC__)
Hans Boehm13e951d2019-11-01 16:48:28 -07002486 IF_GLIBC(size_t mmapped_bytes;)
Hans Boehmc220f982018-10-12 16:15:45 -07002487 struct mallinfo mi = mallinfo();
2488 // In spite of the documentation, the jemalloc version of this call seems to do what we want,
2489 // and it is thread-safe.
2490 if (sizeof(size_t) > sizeof(mi.uordblks) && sizeof(size_t) > sizeof(mi.hblkhd)) {
2491 // Shouldn't happen, but glibc declares uordblks as int.
2492 // Avoiding sign extension gets us correct behavior for another 2 GB.
2493 malloc_bytes = (unsigned int)mi.uordblks;
Hans Boehm13e951d2019-11-01 16:48:28 -07002494 IF_GLIBC(mmapped_bytes = (unsigned int)mi.hblkhd;)
Hans Boehmc220f982018-10-12 16:15:45 -07002495 } else {
2496 malloc_bytes = mi.uordblks;
Hans Boehm13e951d2019-11-01 16:48:28 -07002497 IF_GLIBC(mmapped_bytes = mi.hblkhd;)
Hans Boehmc220f982018-10-12 16:15:45 -07002498 }
Hans Boehm13e951d2019-11-01 16:48:28 -07002499 // From the spec, it appeared mmapped_bytes <= malloc_bytes. Reality was sometimes
2500 // dramatically different. (b/119580449 was an early bug.) If so, we try to fudge it.
2501 // However, malloc implementations seem to interpret hblkhd differently, namely as
2502 // mapped blocks backing the entire heap (e.g. jemalloc) vs. large objects directly
2503 // allocated via mmap (e.g. glibc). Thus we now only do this for glibc, where it
2504 // previously helped, and which appears to use a reading of the spec compatible
2505 // with our adjustment.
2506#if defined(__GLIBC__)
Hans Boehmc220f982018-10-12 16:15:45 -07002507 if (mmapped_bytes > malloc_bytes) {
2508 malloc_bytes = mmapped_bytes;
2509 }
Hans Boehm13e951d2019-11-01 16:48:28 -07002510#endif // GLIBC
2511#else // Neither Bionic nor Glibc
Hans Boehmc220f982018-10-12 16:15:45 -07002512 // We should hit this case only in contexts in which GC triggering is not critical. Effectively
2513 // disable GC triggering based on malloc().
2514 malloc_bytes = 1000;
2515#endif
2516 return malloc_bytes + native_bytes_registered_.load(std::memory_order_relaxed);
2517 // An alternative would be to get RSS from /proc/self/statm. Empirically, that's no
2518 // more expensive, and it would allow us to count memory allocated by means other than malloc.
2519 // However it would change as pages are unmapped and remapped due to memory pressure, among
2520 // other things. It seems risky to trigger GCs as a result of such changes.
2521}
2522
Mathieu Chartiera4f6af92015-08-11 17:35:25 -07002523collector::GcType Heap::CollectGarbageInternal(collector::GcType gc_type,
2524 GcCause gc_cause,
Ian Rogers1d54e732013-05-02 21:10:01 -07002525 bool clear_soft_references) {
Ian Rogers81d425b2012-09-27 16:03:43 -07002526 Thread* self = Thread::Current();
Mathieu Chartier590fee92013-09-13 13:46:47 -07002527 Runtime* runtime = Runtime::Current();
Mathieu Chartiercbb2d202013-11-14 17:45:16 -08002528 // If the heap can't run the GC, silently fail and return that no GC was run.
2529 switch (gc_type) {
Mathieu Chartiercbb2d202013-11-14 17:45:16 -08002530 case collector::kGcTypePartial: {
Mathieu Chartiere4cab172014-08-19 18:24:04 -07002531 if (!HasZygoteSpace()) {
Mathieu Chartiercbb2d202013-11-14 17:45:16 -08002532 return collector::kGcTypeNone;
2533 }
2534 break;
2535 }
2536 default: {
2537 // Other GC types don't have any special cases which makes them not runnable. The main case
2538 // here is full GC.
2539 }
2540 }
Mathieu Chartier65db8802012-11-20 12:36:46 -08002541 ScopedThreadStateChange tsc(self, kWaitingPerformingGc);
Ziang Wan92db59b2019-07-22 21:19:24 +00002542 Locks::mutator_lock_->AssertNotHeld(self);
Ian Rogers120f1c72012-09-28 17:17:10 -07002543 if (self->IsHandlingStackOverflow()) {
Mathieu Chartier50c138f2015-01-07 16:00:03 -08002544 // If we are throwing a stack overflow error we probably don't have enough remaining stack
2545 // space to run the GC.
2546 return collector::kGcTypeNone;
Ian Rogers120f1c72012-09-28 17:17:10 -07002547 }
Mathieu Chartierd5a89ee2014-01-31 09:55:13 -08002548 bool compacting_gc;
2549 {
2550 gc_complete_lock_->AssertNotHeld(self);
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002551 ScopedThreadStateChange tsc2(self, kWaitingForGcToComplete);
Mathieu Chartierd5a89ee2014-01-31 09:55:13 -08002552 MutexLock mu(self, *gc_complete_lock_);
2553 // Ensure there is only one GC at a time.
Mathieu Chartier89a201e2014-05-02 10:27:26 -07002554 WaitForGcToCompleteLocked(gc_cause, self);
Mathieu Chartier31f44142014-04-08 14:40:03 -07002555 compacting_gc = IsMovingGc(collector_type_);
Mathieu Chartierd5a89ee2014-01-31 09:55:13 -08002556 // GC can be disabled if someone has a used GetPrimitiveArrayCritical.
2557 if (compacting_gc && disable_moving_gc_count_ != 0) {
2558 LOG(WARNING) << "Skipping GC due to disable moving GC count " << disable_moving_gc_count_;
2559 return collector::kGcTypeNone;
2560 }
Mathieu Chartier51168372015-08-12 16:40:32 -07002561 if (gc_disabled_for_shutdown_) {
2562 return collector::kGcTypeNone;
2563 }
Mathieu Chartierd5a89ee2014-01-31 09:55:13 -08002564 collector_type_running_ = collector_type_;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002565 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07002566 if (gc_cause == kGcCauseForAlloc && runtime->HasStatsEnabled()) {
2567 ++runtime->GetStats()->gc_for_alloc_count;
2568 ++self->GetStats()->gc_for_alloc_count;
Mathieu Chartier2fde5332012-09-14 14:51:54 -07002569 }
Hans Boehmc220f982018-10-12 16:15:45 -07002570 const size_t bytes_allocated_before_gc = GetBytesAllocated();
Richard Uhlercaaa2b02017-02-01 09:54:17 +00002571
Ian Rogers1d54e732013-05-02 21:10:01 -07002572 DCHECK_LT(gc_type, collector::kGcTypeMax);
2573 DCHECK_NE(gc_type, collector::kGcTypeNone);
Anwar Ghuloum67f99412013-08-12 14:19:48 -07002574
Mathieu Chartier590fee92013-09-13 13:46:47 -07002575 collector::GarbageCollector* collector = nullptr;
Mathieu Chartier50482232013-11-21 11:48:14 -08002576 // TODO: Clean this up.
Mathieu Chartier1d27b342014-01-28 12:51:09 -08002577 if (compacting_gc) {
Mathieu Chartier692fafd2013-11-29 17:24:40 -08002578 DCHECK(current_allocator_ == kAllocatorTypeBumpPointer ||
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002579 current_allocator_ == kAllocatorTypeTLAB ||
2580 current_allocator_ == kAllocatorTypeRegion ||
2581 current_allocator_ == kAllocatorTypeRegionTLAB);
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002582 switch (collector_type_) {
2583 case kCollectorTypeSS:
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002584 semi_space_collector_->SetFromSpace(bump_pointer_space_);
2585 semi_space_collector_->SetToSpace(temp_space_);
2586 semi_space_collector_->SetSwapSemiSpaces(true);
2587 collector = semi_space_collector_;
2588 break;
2589 case kCollectorTypeCC:
Lokesh Gidra45aa2af2020-12-08 15:06:36 -08002590 collector::ConcurrentCopying* active_cc_collector;
Albert Mingkun Yang0b4d1462018-11-29 13:25:35 +00002591 if (use_generational_cc_) {
Mathieu Chartier8d1a9962016-08-17 16:39:45 -07002592 // TODO: Other threads must do the flip checkpoint before they start poking at
2593 // active_concurrent_copying_collector_. So we should not concurrency here.
Lokesh Gidra45aa2af2020-12-08 15:06:36 -08002594 active_cc_collector = (gc_type == collector::kGcTypeSticky) ?
2595 young_concurrent_copying_collector_ : concurrent_copying_collector_;
2596 active_concurrent_copying_collector_.store(active_cc_collector,
2597 std::memory_order_relaxed);
2598 DCHECK(active_cc_collector->RegionSpace() == region_space_);
2599 collector = active_cc_collector;
2600 } else {
2601 collector = active_concurrent_copying_collector_.load(std::memory_order_relaxed);
Mathieu Chartier8d1a9962016-08-17 16:39:45 -07002602 }
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002603 break;
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002604 default:
2605 LOG(FATAL) << "Invalid collector type " << static_cast<size_t>(collector_type_);
Hiroshi Yamauchid5307ec2014-03-27 21:07:51 -07002606 }
Lokesh Gidra45aa2af2020-12-08 15:06:36 -08002607 if (collector != active_concurrent_copying_collector_.load(std::memory_order_relaxed)) {
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002608 temp_space_->GetMemMap()->Protect(PROT_READ | PROT_WRITE);
Hiroshi Yamauchi6edb9ae2016-02-08 14:18:21 -08002609 if (kIsDebugBuild) {
2610 // Try to read each page of the memory map in case mprotect didn't work properly b/19894268.
2611 temp_space_->GetMemMap()->TryReadable();
2612 }
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002613 CHECK(temp_space_->IsEmpty());
2614 }
2615 gc_type = collector::kGcTypeFull; // TODO: Not hard code this in.
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08002616 } else if (current_allocator_ == kAllocatorTypeRosAlloc ||
2617 current_allocator_ == kAllocatorTypeDlMalloc) {
Mathieu Chartierafe49982014-03-27 10:55:04 -07002618 collector = FindCollectorByGcType(gc_type);
Mathieu Chartier50482232013-11-21 11:48:14 -08002619 } else {
2620 LOG(FATAL) << "Invalid current allocator " << current_allocator_;
Mathieu Chartier590fee92013-09-13 13:46:47 -07002621 }
Nicolas Geoffrayb6e20ae2016-03-07 14:29:04 +00002622
Mathieu Chartier7bf82af2013-12-06 16:51:45 -08002623 CHECK(collector != nullptr)
Hiroshi Yamauchi3e417802014-03-20 12:03:02 -07002624 << "Could not find garbage collector with collector_type="
2625 << static_cast<size_t>(collector_type_) << " and gc_type=" << gc_type;
Mathieu Chartier6f365cc2014-04-23 12:42:27 -07002626 collector->Run(gc_cause, clear_soft_references || runtime->IsZygote());
Hans Boehm4c6d7652019-11-01 09:23:19 -07002627 IncrementFreedEver();
Mathieu Chartiera5eae692014-12-17 17:56:03 -08002628 RequestTrim(self);
Alex Lighte3020882019-05-13 16:35:02 -07002629 // Collect cleared references.
2630 SelfDeletingTask* clear = reference_processor_->CollectClearedReferences(self);
Mathieu Chartier590fee92013-09-13 13:46:47 -07002631 // Grow the heap so that we know when to perform the next GC.
Mathieu Chartiere2c2f6e2014-12-16 18:49:31 -08002632 GrowForUtilization(collector, bytes_allocated_before_gc);
Hiroshi Yamauchie4d99872015-02-26 12:53:45 -08002633 LogGC(gc_cause, collector);
2634 FinishGC(self, gc_type);
Alex Lighte3020882019-05-13 16:35:02 -07002635 // Actually enqueue all cleared references. Do this after the GC has officially finished since
2636 // otherwise we can deadlock.
2637 clear->Run(self);
2638 clear->Finalize();
Hiroshi Yamauchie4d99872015-02-26 12:53:45 -08002639 // Inform DDMS that a GC completed.
2640 Dbg::GcDidFinish();
Hans Boehmc220f982018-10-12 16:15:45 -07002641
2642 old_native_bytes_allocated_.store(GetNativeBytes());
2643
Mathieu Chartier598302a2015-09-23 14:52:39 -07002644 // Unload native libraries for class unloading. We do this after calling FinishGC to prevent
2645 // deadlocks in case the JNI_OnUnload function does allocations.
2646 {
2647 ScopedObjectAccess soa(self);
2648 soa.Vm()->UnloadNativeLibraries();
2649 }
Hiroshi Yamauchie4d99872015-02-26 12:53:45 -08002650 return gc_type;
2651}
2652
2653void Heap::LogGC(GcCause gc_cause, collector::GarbageCollector* collector) {
Mathieu Chartier10fb83a2014-06-15 15:15:43 -07002654 const size_t duration = GetCurrentGcIteration()->GetDurationNs();
2655 const std::vector<uint64_t>& pause_times = GetCurrentGcIteration()->GetPauseTimes();
Mathieu Chartier62ab87b2014-04-28 12:22:07 -07002656 // Print the GC if it is an explicit GC (e.g. Runtime.gc()) or a slow GC
Mathieu Chartierf5997b42014-06-20 10:37:54 -07002657 // (mutator time blocked >= long_pause_log_threshold_).
Alex Lightb5a0e912020-07-23 10:54:47 -07002658 bool log_gc = kLogAllGCs || (gc_cause == kGcCauseExplicit && always_log_explicit_gcs_);
Mathieu Chartier62ab87b2014-04-28 12:22:07 -07002659 if (!log_gc && CareAboutPauseTimes()) {
Mathieu Chartiere53225c2013-08-19 10:59:11 -07002660 // GC for alloc pauses the allocating thread, so consider it as a pause.
Mathieu Chartier62ab87b2014-04-28 12:22:07 -07002661 log_gc = duration > long_gc_log_threshold_ ||
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08002662 (gc_cause == kGcCauseForAlloc && duration > long_pause_log_threshold_);
Mathieu Chartier62ab87b2014-04-28 12:22:07 -07002663 for (uint64_t pause : pause_times) {
2664 log_gc = log_gc || pause >= long_pause_log_threshold_;
Mathieu Chartiere53225c2013-08-19 10:59:11 -07002665 }
Mathieu Chartier62ab87b2014-04-28 12:22:07 -07002666 }
2667 if (log_gc) {
2668 const size_t percent_free = GetPercentFree();
2669 const size_t current_heap_size = GetBytesAllocated();
2670 const size_t total_memory = GetTotalMemory();
2671 std::ostringstream pause_string;
2672 for (size_t i = 0; i < pause_times.size(); ++i) {
Hiroshi Yamauchie4d99872015-02-26 12:53:45 -08002673 pause_string << PrettyDuration((pause_times[i] / 1000) * 1000)
2674 << ((i != pause_times.size() - 1) ? "," : "");
Mathieu Chartiere53225c2013-08-19 10:59:11 -07002675 }
Mathieu Chartier62ab87b2014-04-28 12:22:07 -07002676 LOG(INFO) << gc_cause << " " << collector->GetName()
Mathieu Chartier10fb83a2014-06-15 15:15:43 -07002677 << " GC freed " << current_gc_iteration_.GetFreedObjects() << "("
2678 << PrettySize(current_gc_iteration_.GetFreedBytes()) << ") AllocSpace objects, "
2679 << current_gc_iteration_.GetFreedLargeObjects() << "("
2680 << PrettySize(current_gc_iteration_.GetFreedLargeObjectBytes()) << ") LOS objects, "
Mathieu Chartier62ab87b2014-04-28 12:22:07 -07002681 << percent_free << "% free, " << PrettySize(current_heap_size) << "/"
2682 << PrettySize(total_memory) << ", " << "paused " << pause_string.str()
2683 << " total " << PrettyDuration((duration / 1000) * 1000);
Ian Rogersc7dd2952014-10-21 23:31:19 -07002684 VLOG(heap) << Dumpable<TimingLogger>(*current_gc_iteration_.GetTimings());
Mathieu Chartier2b82db42012-11-14 17:29:05 -08002685 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002686}
Mathieu Chartiera6399032012-06-11 18:49:50 -07002687
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08002688void Heap::FinishGC(Thread* self, collector::GcType gc_type) {
2689 MutexLock mu(self, *gc_complete_lock_);
Mathieu Chartierd5a89ee2014-01-31 09:55:13 -08002690 collector_type_running_ = kCollectorTypeNone;
2691 if (gc_type != collector::kGcTypeNone) {
2692 last_gc_type_ = gc_type;
Hiroshi Yamauchia1c9f012015-04-02 10:18:12 -07002693
2694 // Update stats.
2695 ++gc_count_last_window_;
2696 if (running_collection_is_blocking_) {
2697 // If the currently running collection was a blocking one,
2698 // increment the counters and reset the flag.
2699 ++blocking_gc_count_;
2700 blocking_gc_time_ += GetCurrentGcIteration()->GetDurationNs();
2701 ++blocking_gc_count_last_window_;
2702 }
2703 // Update the gc count rate histograms if due.
2704 UpdateGcCountRateHistograms();
Mathieu Chartierd5a89ee2014-01-31 09:55:13 -08002705 }
Hiroshi Yamauchia1c9f012015-04-02 10:18:12 -07002706 // Reset.
2707 running_collection_is_blocking_ = false;
Mathieu Chartier183009a2017-02-16 21:19:28 -08002708 thread_running_gc_ = nullptr;
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08002709 // Wake anyone who may have been waiting for the GC to complete.
2710 gc_complete_cond_->Broadcast(self);
2711}
2712
Hiroshi Yamauchia1c9f012015-04-02 10:18:12 -07002713void Heap::UpdateGcCountRateHistograms() {
2714 // Invariant: if the time since the last update includes more than
2715 // one windows, all the GC runs (if > 0) must have happened in first
2716 // window because otherwise the update must have already taken place
2717 // at an earlier GC run. So, we report the non-first windows with
2718 // zero counts to the histograms.
2719 DCHECK_EQ(last_update_time_gc_count_rate_histograms_ % kGcCountRateHistogramWindowDuration, 0U);
2720 uint64_t now = NanoTime();
2721 DCHECK_GE(now, last_update_time_gc_count_rate_histograms_);
2722 uint64_t time_since_last_update = now - last_update_time_gc_count_rate_histograms_;
2723 uint64_t num_of_windows = time_since_last_update / kGcCountRateHistogramWindowDuration;
Vincent Palomarescc17d072019-01-28 11:14:01 -08002724
2725 // The computed number of windows can be incoherently high if NanoTime() is not monotonic.
2726 // Setting a limit on its maximum value reduces the impact on CPU time in such cases.
2727 if (num_of_windows > kGcCountRateHistogramMaxNumMissedWindows) {
2728 LOG(WARNING) << "Reducing the number of considered missed Gc histogram windows from "
2729 << num_of_windows << " to " << kGcCountRateHistogramMaxNumMissedWindows;
2730 num_of_windows = kGcCountRateHistogramMaxNumMissedWindows;
2731 }
2732
Hiroshi Yamauchia1c9f012015-04-02 10:18:12 -07002733 if (time_since_last_update >= kGcCountRateHistogramWindowDuration) {
2734 // Record the first window.
2735 gc_count_rate_histogram_.AddValue(gc_count_last_window_ - 1); // Exclude the current run.
2736 blocking_gc_count_rate_histogram_.AddValue(running_collection_is_blocking_ ?
2737 blocking_gc_count_last_window_ - 1 : blocking_gc_count_last_window_);
2738 // Record the other windows (with zero counts).
2739 for (uint64_t i = 0; i < num_of_windows - 1; ++i) {
2740 gc_count_rate_histogram_.AddValue(0);
2741 blocking_gc_count_rate_histogram_.AddValue(0);
2742 }
2743 // Update the last update time and reset the counters.
2744 last_update_time_gc_count_rate_histograms_ =
2745 (now / kGcCountRateHistogramWindowDuration) * kGcCountRateHistogramWindowDuration;
2746 gc_count_last_window_ = 1; // Include the current run.
2747 blocking_gc_count_last_window_ = running_collection_is_blocking_ ? 1 : 0;
2748 }
2749 DCHECK_EQ(last_update_time_gc_count_rate_histograms_ % kGcCountRateHistogramWindowDuration, 0U);
2750}
2751
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002752class RootMatchesObjectVisitor : public SingleRootVisitor {
2753 public:
2754 explicit RootMatchesObjectVisitor(const mirror::Object* obj) : obj_(obj) { }
2755
2756 void VisitRoot(mirror::Object* root, const RootInfo& info)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01002757 override REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002758 if (root == obj_) {
2759 LOG(INFO) << "Object " << obj_ << " is a root " << info.ToString();
2760 }
Mathieu Chartierfd678be2012-08-30 14:50:54 -07002761 }
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002762
2763 private:
2764 const mirror::Object* const obj_;
2765};
2766
Mathieu Chartierfd678be2012-08-30 14:50:54 -07002767
2768class ScanVisitor {
2769 public:
Brian Carlstromdf629502013-07-17 22:39:56 -07002770 void operator()(const mirror::Object* obj) const {
Mathieu Chartier0f72e412013-09-06 16:40:01 -07002771 LOG(ERROR) << "Would have rescanned object " << obj;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07002772 }
2773};
2774
Ian Rogers1d54e732013-05-02 21:10:01 -07002775// Verify a reference from an object.
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002776class VerifyReferenceVisitor : public SingleRootVisitor {
Mathieu Chartierfd678be2012-08-30 14:50:54 -07002777 public:
Orion Hodson4a01cc32018-03-26 15:46:18 +01002778 VerifyReferenceVisitor(Thread* self, Heap* heap, size_t* fail_count, bool verify_referent)
Andreas Gampe351c4472017-07-12 19:32:55 -07002779 REQUIRES_SHARED(Locks::mutator_lock_)
Orion Hodson4a01cc32018-03-26 15:46:18 +01002780 : self_(self), heap_(heap), fail_count_(fail_count), verify_referent_(verify_referent) {
2781 CHECK_EQ(self_, Thread::Current());
Mathieu Chartierfd678be2012-08-30 14:50:54 -07002782 }
2783
Mathieu Chartier31e88222016-10-14 18:43:19 -07002784 void operator()(ObjPtr<mirror::Class> klass ATTRIBUTE_UNUSED, ObjPtr<mirror::Reference> ref) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002785 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier78f7b4c2014-05-06 10:57:27 -07002786 if (verify_referent_) {
Mathieu Chartier31e88222016-10-14 18:43:19 -07002787 VerifyReference(ref.Ptr(), ref->GetReferent(), mirror::Reference::ReferentOffset());
Mathieu Chartier78f7b4c2014-05-06 10:57:27 -07002788 }
Mathieu Chartier407f7022014-02-18 14:37:05 -08002789 }
2790
Mathieu Chartier31e88222016-10-14 18:43:19 -07002791 void operator()(ObjPtr<mirror::Object> obj,
2792 MemberOffset offset,
2793 bool is_static ATTRIBUTE_UNUSED) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002794 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier31e88222016-10-14 18:43:19 -07002795 VerifyReference(obj.Ptr(), obj->GetFieldObject<mirror::Object>(offset), offset);
Mathieu Chartier407f7022014-02-18 14:37:05 -08002796 }
2797
Mathieu Chartier31e88222016-10-14 18:43:19 -07002798 bool IsLive(ObjPtr<mirror::Object> obj) const NO_THREAD_SAFETY_ANALYSIS {
Mathieu Chartier8ab7e782014-05-19 16:55:27 -07002799 return heap_->IsLiveObjectLocked(obj, true, false, true);
2800 }
2801
Mathieu Chartierda7c6502015-07-23 16:01:26 -07002802 void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002803 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierda7c6502015-07-23 16:01:26 -07002804 if (!root->IsNull()) {
2805 VisitRoot(root);
2806 }
2807 }
2808 void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002809 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierda7c6502015-07-23 16:01:26 -07002810 const_cast<VerifyReferenceVisitor*>(this)->VisitRoot(
2811 root->AsMirrorPtr(), RootInfo(kRootVMInternal));
2812 }
2813
Roland Levillainf73caca2018-08-24 17:19:07 +01002814 void VisitRoot(mirror::Object* root, const RootInfo& root_info) override
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002815 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002816 if (root == nullptr) {
2817 LOG(ERROR) << "Root is null with info " << root_info.GetType();
2818 } else if (!VerifyReference(nullptr, root, MemberOffset(0))) {
David Sehr709b0702016-10-13 09:12:37 -07002819 LOG(ERROR) << "Root " << root << " is dead with type " << mirror::Object::PrettyTypeOf(root)
Mathieu Chartiere34fa1d2015-01-14 14:55:47 -08002820 << " thread_id= " << root_info.GetThreadId() << " root_type= " << root_info.GetType();
Mathieu Chartier8ab7e782014-05-19 16:55:27 -07002821 }
2822 }
2823
2824 private:
Mathieu Chartier407f7022014-02-18 14:37:05 -08002825 // TODO: Fix the no thread safety analysis.
Mathieu Chartier8ab7e782014-05-19 16:55:27 -07002826 // Returns false on failure.
2827 bool VerifyReference(mirror::Object* obj, mirror::Object* ref, MemberOffset offset) const
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002828 NO_THREAD_SAFETY_ANALYSIS {
Mathieu Chartier938a03b2014-01-16 15:10:31 -08002829 if (ref == nullptr || IsLive(ref)) {
2830 // Verify that the reference is live.
Mathieu Chartier8ab7e782014-05-19 16:55:27 -07002831 return true;
Mathieu Chartier938a03b2014-01-16 15:10:31 -08002832 }
Orion Hodson4a01cc32018-03-26 15:46:18 +01002833 CHECK_EQ(self_, Thread::Current()); // fail_count_ is private to the calling thread.
2834 *fail_count_ += 1;
2835 if (*fail_count_ == 1) {
2836 // Only print message for the first failure to prevent spam.
Mathieu Chartier938a03b2014-01-16 15:10:31 -08002837 LOG(ERROR) << "!!!!!!!!!!!!!!Heap corruption detected!!!!!!!!!!!!!!!!!!!";
Mathieu Chartier938a03b2014-01-16 15:10:31 -08002838 }
2839 if (obj != nullptr) {
Mathieu Chartier8ab7e782014-05-19 16:55:27 -07002840 // Only do this part for non roots.
Ian Rogers1d54e732013-05-02 21:10:01 -07002841 accounting::CardTable* card_table = heap_->GetCardTable();
2842 accounting::ObjectStack* alloc_stack = heap_->allocation_stack_.get();
2843 accounting::ObjectStack* live_stack = heap_->live_stack_.get();
Ian Rogers13735952014-10-08 12:43:28 -07002844 uint8_t* card_addr = card_table->CardFromAddr(obj);
Mathieu Chartier938a03b2014-01-16 15:10:31 -08002845 LOG(ERROR) << "Object " << obj << " references dead object " << ref << " at offset "
2846 << offset << "\n card value = " << static_cast<int>(*card_addr);
2847 if (heap_->IsValidObjectAddress(obj->GetClass())) {
David Sehr709b0702016-10-13 09:12:37 -07002848 LOG(ERROR) << "Obj type " << obj->PrettyTypeOf();
Mathieu Chartier938a03b2014-01-16 15:10:31 -08002849 } else {
2850 LOG(ERROR) << "Object " << obj << " class(" << obj->GetClass() << ") not a heap address";
Mathieu Chartier0f72e412013-09-06 16:40:01 -07002851 }
Mathieu Chartier938a03b2014-01-16 15:10:31 -08002852
Mathieu Chartierb363f662014-07-16 13:28:58 -07002853 // Attempt to find the class inside of the recently freed objects.
Mathieu Chartier938a03b2014-01-16 15:10:31 -08002854 space::ContinuousSpace* ref_space = heap_->FindContinuousSpaceFromObject(ref, true);
2855 if (ref_space != nullptr && ref_space->IsMallocSpace()) {
2856 space::MallocSpace* space = ref_space->AsMallocSpace();
2857 mirror::Class* ref_class = space->FindRecentFreedObject(ref);
2858 if (ref_class != nullptr) {
2859 LOG(ERROR) << "Reference " << ref << " found as a recently freed object with class "
David Sehr709b0702016-10-13 09:12:37 -07002860 << ref_class->PrettyClass();
Mathieu Chartier0f72e412013-09-06 16:40:01 -07002861 } else {
Mathieu Chartier938a03b2014-01-16 15:10:31 -08002862 LOG(ERROR) << "Reference " << ref << " not found as a recently freed object";
Mathieu Chartier0f72e412013-09-06 16:40:01 -07002863 }
Mathieu Chartier938a03b2014-01-16 15:10:31 -08002864 }
Mathieu Chartier0f72e412013-09-06 16:40:01 -07002865
Mathieu Chartier938a03b2014-01-16 15:10:31 -08002866 if (ref->GetClass() != nullptr && heap_->IsValidObjectAddress(ref->GetClass()) &&
2867 ref->GetClass()->IsClass()) {
David Sehr709b0702016-10-13 09:12:37 -07002868 LOG(ERROR) << "Ref type " << ref->PrettyTypeOf();
Mathieu Chartier938a03b2014-01-16 15:10:31 -08002869 } else {
2870 LOG(ERROR) << "Ref " << ref << " class(" << ref->GetClass()
2871 << ") is not a valid heap address";
2872 }
2873
Ian Rogers13735952014-10-08 12:43:28 -07002874 card_table->CheckAddrIsInCardTable(reinterpret_cast<const uint8_t*>(obj));
Mathieu Chartier938a03b2014-01-16 15:10:31 -08002875 void* cover_begin = card_table->AddrFromCard(card_addr);
2876 void* cover_end = reinterpret_cast<void*>(reinterpret_cast<size_t>(cover_begin) +
2877 accounting::CardTable::kCardSize);
2878 LOG(ERROR) << "Card " << reinterpret_cast<void*>(card_addr) << " covers " << cover_begin
2879 << "-" << cover_end;
Mathieu Chartiera8e8f9c2014-04-09 14:51:05 -07002880 accounting::ContinuousSpaceBitmap* bitmap =
2881 heap_->GetLiveBitmap()->GetContinuousSpaceBitmap(obj);
Mathieu Chartier938a03b2014-01-16 15:10:31 -08002882
2883 if (bitmap == nullptr) {
2884 LOG(ERROR) << "Object " << obj << " has no bitmap";
Mathieu Chartier4e305412014-02-19 10:54:44 -08002885 if (!VerifyClassClass(obj->GetClass())) {
Mathieu Chartier938a03b2014-01-16 15:10:31 -08002886 LOG(ERROR) << "Object " << obj << " failed class verification!";
Mathieu Chartier0f72e412013-09-06 16:40:01 -07002887 }
Mathieu Chartier938a03b2014-01-16 15:10:31 -08002888 } else {
Ian Rogers1d54e732013-05-02 21:10:01 -07002889 // Print out how the object is live.
Mathieu Chartier938a03b2014-01-16 15:10:31 -08002890 if (bitmap->Test(obj)) {
Ian Rogers1d54e732013-05-02 21:10:01 -07002891 LOG(ERROR) << "Object " << obj << " found in live bitmap";
2892 }
Mathieu Chartier0f72e412013-09-06 16:40:01 -07002893 if (alloc_stack->Contains(const_cast<mirror::Object*>(obj))) {
Ian Rogers1d54e732013-05-02 21:10:01 -07002894 LOG(ERROR) << "Object " << obj << " found in allocation stack";
2895 }
Mathieu Chartier0f72e412013-09-06 16:40:01 -07002896 if (live_stack->Contains(const_cast<mirror::Object*>(obj))) {
Ian Rogers1d54e732013-05-02 21:10:01 -07002897 LOG(ERROR) << "Object " << obj << " found in live stack";
2898 }
Mathieu Chartier0f72e412013-09-06 16:40:01 -07002899 if (alloc_stack->Contains(const_cast<mirror::Object*>(ref))) {
2900 LOG(ERROR) << "Ref " << ref << " found in allocation stack";
2901 }
2902 if (live_stack->Contains(const_cast<mirror::Object*>(ref))) {
2903 LOG(ERROR) << "Ref " << ref << " found in live stack";
2904 }
Ian Rogers1d54e732013-05-02 21:10:01 -07002905 // Attempt to see if the card table missed the reference.
2906 ScanVisitor scan_visitor;
Ian Rogers13735952014-10-08 12:43:28 -07002907 uint8_t* byte_cover_begin = reinterpret_cast<uint8_t*>(card_table->AddrFromCard(card_addr));
Lei Li727b2942015-01-15 11:26:34 +08002908 card_table->Scan<false>(bitmap, byte_cover_begin,
2909 byte_cover_begin + accounting::CardTable::kCardSize, scan_visitor);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07002910 }
Mathieu Chartier938a03b2014-01-16 15:10:31 -08002911
2912 // Search to see if any of the roots reference our object.
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002913 RootMatchesObjectVisitor visitor1(obj);
2914 Runtime::Current()->VisitRoots(&visitor1);
Mathieu Chartier938a03b2014-01-16 15:10:31 -08002915 // Search to see if any of the roots reference our reference.
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002916 RootMatchesObjectVisitor visitor2(ref);
2917 Runtime::Current()->VisitRoots(&visitor2);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07002918 }
Mathieu Chartier8ab7e782014-05-19 16:55:27 -07002919 return false;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07002920 }
2921
Orion Hodson4a01cc32018-03-26 15:46:18 +01002922 Thread* const self_;
Ian Rogers1d54e732013-05-02 21:10:01 -07002923 Heap* const heap_;
Orion Hodson4a01cc32018-03-26 15:46:18 +01002924 size_t* const fail_count_;
Mathieu Chartier8ab7e782014-05-19 16:55:27 -07002925 const bool verify_referent_;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07002926};
2927
Ian Rogers1d54e732013-05-02 21:10:01 -07002928// Verify all references within an object, for use with HeapBitmap::Visit.
Mathieu Chartierfd678be2012-08-30 14:50:54 -07002929class VerifyObjectVisitor {
2930 public:
Orion Hodson4a01cc32018-03-26 15:46:18 +01002931 VerifyObjectVisitor(Thread* self, Heap* heap, size_t* fail_count, bool verify_referent)
2932 : self_(self), heap_(heap), fail_count_(fail_count), verify_referent_(verify_referent) {}
Mathieu Chartierfd678be2012-08-30 14:50:54 -07002933
Andreas Gampe351c4472017-07-12 19:32:55 -07002934 void operator()(mirror::Object* obj) REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogers1d54e732013-05-02 21:10:01 -07002935 // Note: we are verifying the references in obj but not obj itself, this is because obj must
2936 // be live or else how did we find it in the live bitmap?
Orion Hodson4a01cc32018-03-26 15:46:18 +01002937 VerifyReferenceVisitor visitor(self_, heap_, fail_count_, verify_referent_);
Mathieu Chartier0f72e412013-09-06 16:40:01 -07002938 // The class doesn't count as a reference but we should verify it anyways.
Mathieu Chartier059ef3d2015-08-18 13:54:21 -07002939 obj->VisitReferences(visitor, visitor);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07002940 }
2941
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002942 void VerifyRoots() REQUIRES_SHARED(Locks::mutator_lock_) REQUIRES(!Locks::heap_bitmap_lock_) {
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002943 ReaderMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
Orion Hodson4a01cc32018-03-26 15:46:18 +01002944 VerifyReferenceVisitor visitor(self_, heap_, fail_count_, verify_referent_);
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002945 Runtime::Current()->VisitRoots(&visitor);
2946 }
2947
Orion Hodson4a01cc32018-03-26 15:46:18 +01002948 uint32_t GetFailureCount() const REQUIRES(Locks::mutator_lock_) {
2949 CHECK_EQ(self_, Thread::Current());
2950 return *fail_count_;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07002951 }
2952
2953 private:
Orion Hodson4a01cc32018-03-26 15:46:18 +01002954 Thread* const self_;
Ian Rogers1d54e732013-05-02 21:10:01 -07002955 Heap* const heap_;
Orion Hodson4a01cc32018-03-26 15:46:18 +01002956 size_t* const fail_count_;
Mathieu Chartier78f7b4c2014-05-06 10:57:27 -07002957 const bool verify_referent_;
Mathieu Chartierfd678be2012-08-30 14:50:54 -07002958};
2959
Mathieu Chartier9d156d52016-10-06 17:44:26 -07002960void Heap::PushOnAllocationStackWithInternalGC(Thread* self, ObjPtr<mirror::Object>* obj) {
Mathieu Chartierc1790162014-05-23 10:54:50 -07002961 // Slow path, the allocation stack push back must have already failed.
Mathieu Chartier9d156d52016-10-06 17:44:26 -07002962 DCHECK(!allocation_stack_->AtomicPushBack(obj->Ptr()));
Mathieu Chartierc1790162014-05-23 10:54:50 -07002963 do {
2964 // TODO: Add handle VerifyObject.
2965 StackHandleScope<1> hs(self);
Mathieu Chartier9d156d52016-10-06 17:44:26 -07002966 HandleWrapperObjPtr<mirror::Object> wrapper(hs.NewHandleWrapper(obj));
Hans Boehmd972b422017-09-11 12:57:00 -07002967 // Push our object into the reserve region of the allocation stack. This is only required due
Mathieu Chartierc1790162014-05-23 10:54:50 -07002968 // to heap verification requiring that roots are live (either in the live bitmap or in the
2969 // allocation stack).
Mathieu Chartier9d156d52016-10-06 17:44:26 -07002970 CHECK(allocation_stack_->AtomicPushBackIgnoreGrowthLimit(obj->Ptr()));
Mathieu Chartierc1790162014-05-23 10:54:50 -07002971 CollectGarbageInternal(collector::kGcTypeSticky, kGcCauseForAlloc, false);
Mathieu Chartier9d156d52016-10-06 17:44:26 -07002972 } while (!allocation_stack_->AtomicPushBack(obj->Ptr()));
Mathieu Chartierc1790162014-05-23 10:54:50 -07002973}
2974
Mathieu Chartier9d156d52016-10-06 17:44:26 -07002975void Heap::PushOnThreadLocalAllocationStackWithInternalGC(Thread* self,
2976 ObjPtr<mirror::Object>* obj) {
Mathieu Chartierc1790162014-05-23 10:54:50 -07002977 // Slow path, the allocation stack push back must have already failed.
Mathieu Chartier9d156d52016-10-06 17:44:26 -07002978 DCHECK(!self->PushOnThreadLocalAllocationStack(obj->Ptr()));
Mathieu Chartiercb535da2015-01-23 13:50:03 -08002979 StackReference<mirror::Object>* start_address;
2980 StackReference<mirror::Object>* end_address;
Mathieu Chartierc1790162014-05-23 10:54:50 -07002981 while (!allocation_stack_->AtomicBumpBack(kThreadLocalAllocationStackSize, &start_address,
2982 &end_address)) {
2983 // TODO: Add handle VerifyObject.
2984 StackHandleScope<1> hs(self);
Mathieu Chartier9d156d52016-10-06 17:44:26 -07002985 HandleWrapperObjPtr<mirror::Object> wrapper(hs.NewHandleWrapper(obj));
Mathieu Chartierc1790162014-05-23 10:54:50 -07002986 // Push our object into the reserve region of the allocaiton stack. This is only required due
2987 // to heap verification requiring that roots are live (either in the live bitmap or in the
2988 // allocation stack).
Mathieu Chartier9d156d52016-10-06 17:44:26 -07002989 CHECK(allocation_stack_->AtomicPushBackIgnoreGrowthLimit(obj->Ptr()));
Mathieu Chartierc1790162014-05-23 10:54:50 -07002990 // Push into the reserve allocation stack.
2991 CollectGarbageInternal(collector::kGcTypeSticky, kGcCauseForAlloc, false);
2992 }
2993 self->SetThreadLocalAllocationStack(start_address, end_address);
2994 // Retry on the new thread-local allocation stack.
Mathieu Chartier9d156d52016-10-06 17:44:26 -07002995 CHECK(self->PushOnThreadLocalAllocationStack(obj->Ptr())); // Must succeed.
Mathieu Chartierc1790162014-05-23 10:54:50 -07002996}
2997
Mathieu Chartierfd678be2012-08-30 14:50:54 -07002998// Must do this with mutators suspended since we are directly accessing the allocation stacks.
Mathieu Chartier8ab7e782014-05-19 16:55:27 -07002999size_t Heap::VerifyHeapReferences(bool verify_referents) {
Hiroshi Yamauchi1ed90612014-02-14 15:00:51 -08003000 Thread* self = Thread::Current();
3001 Locks::mutator_lock_->AssertExclusiveHeld(self);
Mathieu Chartierfd678be2012-08-30 14:50:54 -07003002 // Lets sort our allocation stacks so that we can efficiently binary search them.
Ian Rogers1d54e732013-05-02 21:10:01 -07003003 allocation_stack_->Sort();
3004 live_stack_->Sort();
Hiroshi Yamauchi1ed90612014-02-14 15:00:51 -08003005 // Since we sorted the allocation stack content, need to revoke all
3006 // thread-local allocation stacks.
3007 RevokeAllThreadLocalAllocationStacks(self);
Orion Hodson4a01cc32018-03-26 15:46:18 +01003008 size_t fail_count = 0;
3009 VerifyObjectVisitor visitor(self, this, &fail_count, verify_referents);
Mathieu Chartier0f72e412013-09-06 16:40:01 -07003010 // Verify objects in the allocation stack since these will be objects which were:
3011 // 1. Allocated prior to the GC (pre GC verification).
3012 // 2. Allocated during the GC (pre sweep GC verification).
Mathieu Chartier0f72e412013-09-06 16:40:01 -07003013 // We don't want to verify the objects in the live stack since they themselves may be
Mathieu Chartierfd678be2012-08-30 14:50:54 -07003014 // pointing to dead objects if they are not reachable.
Andreas Gampe351c4472017-07-12 19:32:55 -07003015 VisitObjectsPaused(visitor);
Mathieu Chartier590fee92013-09-13 13:46:47 -07003016 // Verify the roots:
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07003017 visitor.VerifyRoots();
Mathieu Chartier8ab7e782014-05-19 16:55:27 -07003018 if (visitor.GetFailureCount() > 0) {
Mathieu Chartier0f72e412013-09-06 16:40:01 -07003019 // Dump mod-union tables.
Mathieu Chartier11409ae2013-09-23 11:49:36 -07003020 for (const auto& table_pair : mod_union_tables_) {
3021 accounting::ModUnionTable* mod_union_table = table_pair.second;
Andreas Gampe3fec9ac2016-09-13 10:47:28 -07003022 mod_union_table->Dump(LOG_STREAM(ERROR) << mod_union_table->GetName() << ": ");
Mathieu Chartier11409ae2013-09-23 11:49:36 -07003023 }
Hiroshi Yamauchi38e68e92014-03-07 13:59:08 -08003024 // Dump remembered sets.
3025 for (const auto& table_pair : remembered_sets_) {
3026 accounting::RememberedSet* remembered_set = table_pair.second;
Andreas Gampe3fec9ac2016-09-13 10:47:28 -07003027 remembered_set->Dump(LOG_STREAM(ERROR) << remembered_set->GetName() << ": ");
Hiroshi Yamauchi38e68e92014-03-07 13:59:08 -08003028 }
Andreas Gampe3fec9ac2016-09-13 10:47:28 -07003029 DumpSpaces(LOG_STREAM(ERROR));
Mathieu Chartierfd678be2012-08-30 14:50:54 -07003030 }
Mathieu Chartier8ab7e782014-05-19 16:55:27 -07003031 return visitor.GetFailureCount();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07003032}
3033
3034class VerifyReferenceCardVisitor {
3035 public:
3036 VerifyReferenceCardVisitor(Heap* heap, bool* failed)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07003037 REQUIRES_SHARED(Locks::mutator_lock_,
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07003038 Locks::heap_bitmap_lock_)
Ian Rogers1d54e732013-05-02 21:10:01 -07003039 : heap_(heap), failed_(failed) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07003040 }
3041
Mathieu Chartierda7c6502015-07-23 16:01:26 -07003042 // There is no card marks for native roots on a class.
3043 void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root ATTRIBUTE_UNUSED)
3044 const {}
3045 void VisitRoot(mirror::CompressedReference<mirror::Object>* root ATTRIBUTE_UNUSED) const {}
3046
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08003047 // TODO: Fix lock analysis to not use NO_THREAD_SAFETY_ANALYSIS, requires support for
3048 // annotalysis on visitors.
Mathieu Chartier407f7022014-02-18 14:37:05 -08003049 void operator()(mirror::Object* obj, MemberOffset offset, bool is_static) const
3050 NO_THREAD_SAFETY_ANALYSIS {
Ian Rogersb0fa5dc2014-04-28 16:47:08 -07003051 mirror::Object* ref = obj->GetFieldObject<mirror::Object>(offset);
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08003052 // Filter out class references since changing an object's class does not mark the card as dirty.
3053 // Also handles large objects, since the only reference they hold is a class reference.
Mathieu Chartier407f7022014-02-18 14:37:05 -08003054 if (ref != nullptr && !ref->IsClass()) {
Ian Rogers1d54e732013-05-02 21:10:01 -07003055 accounting::CardTable* card_table = heap_->GetCardTable();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07003056 // If the object is not dirty and it is referencing something in the live stack other than
3057 // class, then it must be on a dirty card.
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07003058 if (!card_table->AddrIsInCardTable(obj)) {
3059 LOG(ERROR) << "Object " << obj << " is not in the address range of the card table";
3060 *failed_ = true;
Mathieu Chartier2b82db42012-11-14 17:29:05 -08003061 } else if (!card_table->IsDirty(obj)) {
Mathieu Chartier938a03b2014-01-16 15:10:31 -08003062 // TODO: Check mod-union tables.
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08003063 // Card should be either kCardDirty if it got re-dirtied after we aged it, or
3064 // kCardDirty - 1 if it didnt get touched since we aged it.
Ian Rogers1d54e732013-05-02 21:10:01 -07003065 accounting::ObjectStack* live_stack = heap_->live_stack_.get();
Mathieu Chartier407f7022014-02-18 14:37:05 -08003066 if (live_stack->ContainsSorted(ref)) {
3067 if (live_stack->ContainsSorted(obj)) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07003068 LOG(ERROR) << "Object " << obj << " found in live stack";
3069 }
3070 if (heap_->GetLiveBitmap()->Test(obj)) {
3071 LOG(ERROR) << "Object " << obj << " found in live bitmap";
3072 }
David Sehr709b0702016-10-13 09:12:37 -07003073 LOG(ERROR) << "Object " << obj << " " << mirror::Object::PrettyTypeOf(obj)
3074 << " references " << ref << " " << mirror::Object::PrettyTypeOf(ref)
3075 << " in live stack";
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07003076
3077 // Print which field of the object is dead.
3078 if (!obj->IsObjectArray()) {
Vladimir Marko4617d582019-03-28 13:48:31 +00003079 ObjPtr<mirror::Class> klass = is_static ? obj->AsClass() : obj->GetClass();
Mathieu Chartierc7853442015-03-27 14:35:38 -07003080 CHECK(klass != nullptr);
Mathieu Chartierc0fe56a2015-08-11 13:01:23 -07003081 for (ArtField& field : (is_static ? klass->GetSFields() : klass->GetIFields())) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003082 if (field.GetOffset().Int32Value() == offset.Int32Value()) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07003083 LOG(ERROR) << (is_static ? "Static " : "") << "field in the live stack is "
David Sehr709b0702016-10-13 09:12:37 -07003084 << field.PrettyField();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07003085 break;
3086 }
3087 }
3088 } else {
Vladimir Marko4617d582019-03-28 13:48:31 +00003089 ObjPtr<mirror::ObjectArray<mirror::Object>> object_array =
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003090 obj->AsObjectArray<mirror::Object>();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07003091 for (int32_t i = 0; i < object_array->GetLength(); ++i) {
3092 if (object_array->Get(i) == ref) {
3093 LOG(ERROR) << (is_static ? "Static " : "") << "obj[" << i << "] = ref";
3094 }
3095 }
3096 }
3097
3098 *failed_ = true;
3099 }
3100 }
3101 }
3102 }
3103
3104 private:
Ian Rogers1d54e732013-05-02 21:10:01 -07003105 Heap* const heap_;
3106 bool* const failed_;
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07003107};
3108
3109class VerifyLiveStackReferences {
3110 public:
Brian Carlstrom93ba8932013-07-17 21:31:49 -07003111 explicit VerifyLiveStackReferences(Heap* heap)
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07003112 : heap_(heap),
Brian Carlstrom93ba8932013-07-17 21:31:49 -07003113 failed_(false) {}
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07003114
Mathieu Chartier11409ae2013-09-23 11:49:36 -07003115 void operator()(mirror::Object* obj) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07003116 REQUIRES_SHARED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07003117 VerifyReferenceCardVisitor visitor(heap_, const_cast<bool*>(&failed_));
Mathieu Chartier059ef3d2015-08-18 13:54:21 -07003118 obj->VisitReferences(visitor, VoidFunctor());
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07003119 }
3120
3121 bool Failed() const {
3122 return failed_;
3123 }
3124
3125 private:
Ian Rogers1d54e732013-05-02 21:10:01 -07003126 Heap* const heap_;
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07003127 bool failed_;
3128};
3129
3130bool Heap::VerifyMissingCardMarks() {
Hiroshi Yamauchi1ed90612014-02-14 15:00:51 -08003131 Thread* self = Thread::Current();
3132 Locks::mutator_lock_->AssertExclusiveHeld(self);
Mathieu Chartier2b82db42012-11-14 17:29:05 -08003133 // We need to sort the live stack since we binary search it.
Ian Rogers1d54e732013-05-02 21:10:01 -07003134 live_stack_->Sort();
Hiroshi Yamauchi1ed90612014-02-14 15:00:51 -08003135 // Since we sorted the allocation stack content, need to revoke all
3136 // thread-local allocation stacks.
3137 RevokeAllThreadLocalAllocationStacks(self);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07003138 VerifyLiveStackReferences visitor(this);
3139 GetLiveBitmap()->Visit(visitor);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07003140 // We can verify objects in the live stack since none of these should reference dead objects.
Mathieu Chartiercb535da2015-01-23 13:50:03 -08003141 for (auto* it = live_stack_->Begin(); it != live_stack_->End(); ++it) {
3142 if (!kUseThreadLocalAllocationStack || it->AsMirrorPtr() != nullptr) {
3143 visitor(it->AsMirrorPtr());
Hiroshi Yamauchif5b0e202014-02-11 17:02:22 -08003144 }
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07003145 }
Mathieu Chartier4c13a3f2014-07-14 14:57:16 -07003146 return !visitor.Failed();
Mathieu Chartierfd678be2012-08-30 14:50:54 -07003147}
3148
Mathieu Chartiera4f6af92015-08-11 17:35:25 -07003149void Heap::SwapStacks() {
Hiroshi Yamauchif5b0e202014-02-11 17:02:22 -08003150 if (kUseThreadLocalAllocationStack) {
3151 live_stack_->AssertAllZero();
3152 }
Mathieu Chartierd22d5482012-11-06 17:14:12 -08003153 allocation_stack_.swap(live_stack_);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07003154}
3155
Hiroshi Yamauchif5b0e202014-02-11 17:02:22 -08003156void Heap::RevokeAllThreadLocalAllocationStacks(Thread* self) {
Hiroshi Yamauchif5b0e202014-02-11 17:02:22 -08003157 // This must be called only during the pause.
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003158 DCHECK(Locks::mutator_lock_->IsExclusiveHeld(self));
Hiroshi Yamauchif5b0e202014-02-11 17:02:22 -08003159 MutexLock mu(self, *Locks::runtime_shutdown_lock_);
3160 MutexLock mu2(self, *Locks::thread_list_lock_);
3161 std::list<Thread*> thread_list = Runtime::Current()->GetThreadList()->GetList();
3162 for (Thread* t : thread_list) {
3163 t->RevokeThreadLocalAllocationStack();
3164 }
3165}
3166
Ian Rogers68d8b422014-07-17 11:09:10 -07003167void Heap::AssertThreadLocalBuffersAreRevoked(Thread* thread) {
3168 if (kIsDebugBuild) {
3169 if (rosalloc_space_ != nullptr) {
3170 rosalloc_space_->AssertThreadLocalBuffersAreRevoked(thread);
3171 }
3172 if (bump_pointer_space_ != nullptr) {
3173 bump_pointer_space_->AssertThreadLocalBuffersAreRevoked(thread);
3174 }
3175 }
3176}
3177
Hiroshi Yamauchic93c5302014-03-20 16:15:37 -07003178void Heap::AssertAllBumpPointerSpaceThreadLocalBuffersAreRevoked() {
3179 if (kIsDebugBuild) {
3180 if (bump_pointer_space_ != nullptr) {
3181 bump_pointer_space_->AssertAllThreadLocalBuffersAreRevoked();
3182 }
3183 }
3184}
3185
Mathieu Chartier11409ae2013-09-23 11:49:36 -07003186accounting::ModUnionTable* Heap::FindModUnionTableFromSpace(space::Space* space) {
3187 auto it = mod_union_tables_.find(space);
3188 if (it == mod_union_tables_.end()) {
3189 return nullptr;
3190 }
3191 return it->second;
3192}
3193
Hiroshi Yamauchi38e68e92014-03-07 13:59:08 -08003194accounting::RememberedSet* Heap::FindRememberedSetFromSpace(space::Space* space) {
3195 auto it = remembered_sets_.find(space);
3196 if (it == remembered_sets_.end()) {
3197 return nullptr;
3198 }
3199 return it->second;
3200}
3201
Mathieu Chartiera4f6af92015-08-11 17:35:25 -07003202void Heap::ProcessCards(TimingLogger* timings,
3203 bool use_rem_sets,
3204 bool process_alloc_space_cards,
Lei Li4add3b42015-01-15 11:55:26 +08003205 bool clear_alloc_space_cards) {
Mathieu Chartierf5997b42014-06-20 10:37:54 -07003206 TimingLogger::ScopedTiming t(__FUNCTION__, timings);
Ian Rogers1d54e732013-05-02 21:10:01 -07003207 // Clear cards and keep track of cards cleared in the mod-union table.
Mathieu Chartier02e25112013-08-14 16:14:24 -07003208 for (const auto& space : continuous_spaces_) {
Mathieu Chartier11409ae2013-09-23 11:49:36 -07003209 accounting::ModUnionTable* table = FindModUnionTableFromSpace(space);
Hiroshi Yamauchi38e68e92014-03-07 13:59:08 -08003210 accounting::RememberedSet* rem_set = FindRememberedSetFromSpace(space);
Mathieu Chartier11409ae2013-09-23 11:49:36 -07003211 if (table != nullptr) {
3212 const char* name = space->IsZygoteSpace() ? "ZygoteModUnionClearCards" :
3213 "ImageModUnionClearCards";
Andreas Gampe277ccbd2014-11-03 21:36:10 -08003214 TimingLogger::ScopedTiming t2(name, timings);
Mathieu Chartier6e6078a2016-10-24 15:45:41 -07003215 table->ProcessCards();
Hiroshi Yamauchi38e68e92014-03-07 13:59:08 -08003216 } else if (use_rem_sets && rem_set != nullptr) {
Mathieu Chartierf75dce42019-04-08 09:36:23 -07003217 DCHECK(collector::SemiSpace::kUseRememberedSet) << static_cast<int>(collector_type_);
Andreas Gampe277ccbd2014-11-03 21:36:10 -08003218 TimingLogger::ScopedTiming t2("AllocSpaceRemSetClearCards", timings);
Hiroshi Yamauchi38e68e92014-03-07 13:59:08 -08003219 rem_set->ClearCards();
Lei Li4add3b42015-01-15 11:55:26 +08003220 } else if (process_alloc_space_cards) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08003221 TimingLogger::ScopedTiming t2("AllocSpaceClearCards", timings);
Lei Li4add3b42015-01-15 11:55:26 +08003222 if (clear_alloc_space_cards) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08003223 uint8_t* end = space->End();
3224 if (space->IsImageSpace()) {
3225 // Image space end is the end of the mirror objects, it is not necessarily page or card
3226 // aligned. Align up so that the check in ClearCardRange does not fail.
3227 end = AlignUp(end, accounting::CardTable::kCardSize);
3228 }
3229 card_table_->ClearCardRange(space->Begin(), end);
Lei Li4add3b42015-01-15 11:55:26 +08003230 } else {
3231 // No mod union table for the AllocSpace. Age the cards so that the GC knows that these
3232 // cards were dirty before the GC started.
3233 // TODO: Need to use atomic for the case where aged(cleaning thread) -> dirty(other thread)
3234 // -> clean(cleaning thread).
3235 // The races are we either end up with: Aged card, unaged card. Since we have the
3236 // checkpoint roots and then we scan / update mod union tables after. We will always
3237 // scan either card. If we end up with the non aged card, we scan it it in the pause.
3238 card_table_->ModifyCardsAtomic(space->Begin(), space->End(), AgeCardVisitor(),
3239 VoidFunctor());
3240 }
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07003241 }
3242 }
3243}
3244
Mathieu Chartier97509952015-07-13 14:35:43 -07003245struct IdentityMarkHeapReferenceVisitor : public MarkObjectVisitor {
Roland Levillainf73caca2018-08-24 17:19:07 +01003246 mirror::Object* MarkObject(mirror::Object* obj) override {
Mathieu Chartier97509952015-07-13 14:35:43 -07003247 return obj;
3248 }
Roland Levillainf73caca2018-08-24 17:19:07 +01003249 void MarkHeapReference(mirror::HeapReference<mirror::Object>*, bool) override {
Mathieu Chartier97509952015-07-13 14:35:43 -07003250 }
3251};
Mathieu Chartier11409ae2013-09-23 11:49:36 -07003252
Mathieu Chartier6f365cc2014-04-23 12:42:27 -07003253void Heap::PreGcVerificationPaused(collector::GarbageCollector* gc) {
3254 Thread* const self = Thread::Current();
Mathieu Chartier10fb83a2014-06-15 15:15:43 -07003255 TimingLogger* const timings = current_gc_iteration_.GetTimings();
Mathieu Chartierf5997b42014-06-20 10:37:54 -07003256 TimingLogger::ScopedTiming t(__FUNCTION__, timings);
Mathieu Chartier2b82db42012-11-14 17:29:05 -08003257 if (verify_pre_gc_heap_) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08003258 TimingLogger::ScopedTiming t2("(Paused)PreGcVerifyHeapReferences", timings);
Mathieu Chartier8ab7e782014-05-19 16:55:27 -07003259 size_t failures = VerifyHeapReferences();
3260 if (failures > 0) {
3261 LOG(FATAL) << "Pre " << gc->GetName() << " heap verification failed with " << failures
3262 << " failures";
Mathieu Chartier2b82db42012-11-14 17:29:05 -08003263 }
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08003264 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -08003265 // Check that all objects which reference things in the live stack are on dirty cards.
3266 if (verify_missing_card_marks_) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08003267 TimingLogger::ScopedTiming t2("(Paused)PreGcVerifyMissingCardMarks", timings);
Mathieu Chartier6f365cc2014-04-23 12:42:27 -07003268 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartiera4f6af92015-08-11 17:35:25 -07003269 SwapStacks();
Mathieu Chartier6f365cc2014-04-23 12:42:27 -07003270 // Sort the live stack so that we can quickly binary search it later.
Mathieu Chartier4c13a3f2014-07-14 14:57:16 -07003271 CHECK(VerifyMissingCardMarks()) << "Pre " << gc->GetName()
3272 << " missing card mark verification failed\n" << DumpSpaces();
Mathieu Chartiera4f6af92015-08-11 17:35:25 -07003273 SwapStacks();
Mathieu Chartier2b82db42012-11-14 17:29:05 -08003274 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -08003275 if (verify_mod_union_table_) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08003276 TimingLogger::ScopedTiming t2("(Paused)PreGcVerifyModUnionTables", timings);
Mathieu Chartier2b82db42012-11-14 17:29:05 -08003277 ReaderMutexLock reader_lock(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier11409ae2013-09-23 11:49:36 -07003278 for (const auto& table_pair : mod_union_tables_) {
3279 accounting::ModUnionTable* mod_union_table = table_pair.second;
Mathieu Chartier97509952015-07-13 14:35:43 -07003280 IdentityMarkHeapReferenceVisitor visitor;
3281 mod_union_table->UpdateAndMarkReferences(&visitor);
Mathieu Chartier11409ae2013-09-23 11:49:36 -07003282 mod_union_table->Verify();
3283 }
Mathieu Chartier6f365cc2014-04-23 12:42:27 -07003284 }
3285}
3286
3287void Heap::PreGcVerification(collector::GarbageCollector* gc) {
Mathieu Chartier0651d412014-04-29 14:37:57 -07003288 if (verify_pre_gc_heap_ || verify_missing_card_marks_ || verify_mod_union_table_) {
Andreas Gampe4934eb12017-01-30 13:15:26 -08003289 collector::GarbageCollector::ScopedPause pause(gc, false);
Mathieu Chartier6f365cc2014-04-23 12:42:27 -07003290 PreGcVerificationPaused(gc);
3291 }
3292}
3293
Mathieu Chartiera4f6af92015-08-11 17:35:25 -07003294void Heap::PrePauseRosAllocVerification(collector::GarbageCollector* gc ATTRIBUTE_UNUSED) {
Mathieu Chartier6f365cc2014-04-23 12:42:27 -07003295 // TODO: Add a new runtime option for this?
3296 if (verify_pre_gc_rosalloc_) {
Mathieu Chartier10fb83a2014-06-15 15:15:43 -07003297 RosAllocVerification(current_gc_iteration_.GetTimings(), "PreGcRosAllocVerification");
Mathieu Chartier2b82db42012-11-14 17:29:05 -08003298 }
Mathieu Chartier4da7f2f2012-11-13 12:51:01 -08003299}
3300
Ian Rogers1d54e732013-05-02 21:10:01 -07003301void Heap::PreSweepingGcVerification(collector::GarbageCollector* gc) {
Mathieu Chartier6f365cc2014-04-23 12:42:27 -07003302 Thread* const self = Thread::Current();
Mathieu Chartier10fb83a2014-06-15 15:15:43 -07003303 TimingLogger* const timings = current_gc_iteration_.GetTimings();
Mathieu Chartierf5997b42014-06-20 10:37:54 -07003304 TimingLogger::ScopedTiming t(__FUNCTION__, timings);
Mathieu Chartier2b82db42012-11-14 17:29:05 -08003305 // Called before sweeping occurs since we want to make sure we are not going so reclaim any
3306 // reachable objects.
Mathieu Chartier6f365cc2014-04-23 12:42:27 -07003307 if (verify_pre_sweeping_heap_) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08003308 TimingLogger::ScopedTiming t2("(Paused)PostSweepingVerifyHeapReferences", timings);
Ian Rogers1d54e732013-05-02 21:10:01 -07003309 CHECK_NE(self->GetState(), kRunnable);
Hiroshi Yamauchi0c8c3032015-01-16 16:54:35 -08003310 {
3311 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
3312 // Swapping bound bitmaps does nothing.
3313 gc->SwapBitmaps();
3314 }
Mathieu Chartier78f7b4c2014-05-06 10:57:27 -07003315 // Pass in false since concurrent reference processing can mean that the reference referents
3316 // may point to dead objects at the point which PreSweepingGcVerification is called.
Mathieu Chartier8ab7e782014-05-19 16:55:27 -07003317 size_t failures = VerifyHeapReferences(false);
3318 if (failures > 0) {
3319 LOG(FATAL) << "Pre sweeping " << gc->GetName() << " GC verification failed with " << failures
3320 << " failures";
Mathieu Chartier6f365cc2014-04-23 12:42:27 -07003321 }
Hiroshi Yamauchi0c8c3032015-01-16 16:54:35 -08003322 {
3323 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
3324 gc->SwapBitmaps();
3325 }
Mathieu Chartier6f365cc2014-04-23 12:42:27 -07003326 }
3327 if (verify_pre_sweeping_rosalloc_) {
3328 RosAllocVerification(timings, "PreSweepingRosAllocVerification");
3329 }
3330}
3331
3332void Heap::PostGcVerificationPaused(collector::GarbageCollector* gc) {
3333 // Only pause if we have to do some verification.
3334 Thread* const self = Thread::Current();
Mathieu Chartier10fb83a2014-06-15 15:15:43 -07003335 TimingLogger* const timings = GetCurrentGcIteration()->GetTimings();
Mathieu Chartierf5997b42014-06-20 10:37:54 -07003336 TimingLogger::ScopedTiming t(__FUNCTION__, timings);
Mathieu Chartier6f365cc2014-04-23 12:42:27 -07003337 if (verify_system_weaks_) {
3338 ReaderMutexLock mu2(self, *Locks::heap_bitmap_lock_);
3339 collector::MarkSweep* mark_sweep = down_cast<collector::MarkSweep*>(gc);
3340 mark_sweep->VerifySystemWeaks();
3341 }
3342 if (verify_post_gc_rosalloc_) {
Mathieu Chartierf5997b42014-06-20 10:37:54 -07003343 RosAllocVerification(timings, "(Paused)PostGcRosAllocVerification");
Mathieu Chartier6f365cc2014-04-23 12:42:27 -07003344 }
3345 if (verify_post_gc_heap_) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08003346 TimingLogger::ScopedTiming t2("(Paused)PostGcVerifyHeapReferences", timings);
Mathieu Chartier8ab7e782014-05-19 16:55:27 -07003347 size_t failures = VerifyHeapReferences();
3348 if (failures > 0) {
3349 LOG(FATAL) << "Pre " << gc->GetName() << " heap verification failed with " << failures
3350 << " failures";
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003351 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003352 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -08003353}
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003354
Ian Rogers1d54e732013-05-02 21:10:01 -07003355void Heap::PostGcVerification(collector::GarbageCollector* gc) {
Mathieu Chartier6f365cc2014-04-23 12:42:27 -07003356 if (verify_system_weaks_ || verify_post_gc_rosalloc_ || verify_post_gc_heap_) {
Andreas Gampe4934eb12017-01-30 13:15:26 -08003357 collector::GarbageCollector::ScopedPause pause(gc, false);
Mathieu Chartierd35326f2014-08-18 15:02:59 -07003358 PostGcVerificationPaused(gc);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003359 }
Carl Shapiro69759ea2011-07-21 18:13:35 -07003360}
3361
Mathieu Chartier6f365cc2014-04-23 12:42:27 -07003362void Heap::RosAllocVerification(TimingLogger* timings, const char* name) {
Mathieu Chartierf5997b42014-06-20 10:37:54 -07003363 TimingLogger::ScopedTiming t(name, timings);
Mathieu Chartier6f365cc2014-04-23 12:42:27 -07003364 for (const auto& space : continuous_spaces_) {
3365 if (space->IsRosAllocSpace()) {
3366 VLOG(heap) << name << " : " << space->GetName();
3367 space->AsRosAllocSpace()->Verify();
Hiroshi Yamauchia4adbfd2014-02-04 18:12:17 -08003368 }
3369 }
3370}
3371
Mathieu Chartier89a201e2014-05-02 10:27:26 -07003372collector::GcType Heap::WaitForGcToComplete(GcCause cause, Thread* self) {
Mathieu Chartiercaa82d62014-02-02 16:51:17 -08003373 ScopedThreadStateChange tsc(self, kWaitingForGcToComplete);
Mathieu Chartier590fee92013-09-13 13:46:47 -07003374 MutexLock mu(self, *gc_complete_lock_);
Mathieu Chartier89a201e2014-05-02 10:27:26 -07003375 return WaitForGcToCompleteLocked(cause, self);
Mathieu Chartier590fee92013-09-13 13:46:47 -07003376}
3377
Mathieu Chartier89a201e2014-05-02 10:27:26 -07003378collector::GcType Heap::WaitForGcToCompleteLocked(GcCause cause, Thread* self) {
Alex Light66834462019-04-08 16:28:29 +00003379 gc_complete_cond_->CheckSafeToWait(self);
Ian Rogers1d54e732013-05-02 21:10:01 -07003380 collector::GcType last_gc_type = collector::kGcTypeNone;
Mathieu Chartier40112dd2017-06-26 17:49:09 -07003381 GcCause last_gc_cause = kGcCauseNone;
Mathieu Chartier590fee92013-09-13 13:46:47 -07003382 uint64_t wait_start = NanoTime();
Mathieu Chartierd5a89ee2014-01-31 09:55:13 -08003383 while (collector_type_running_ != kCollectorTypeNone) {
Hiroshi Yamauchia1c9f012015-04-02 10:18:12 -07003384 if (self != task_processor_->GetRunningThread()) {
3385 // The current thread is about to wait for a currently running
3386 // collection to finish. If the waiting thread is not the heap
3387 // task daemon thread, the currently running collection is
3388 // considered as a blocking GC.
3389 running_collection_is_blocking_ = true;
3390 VLOG(gc) << "Waiting for a blocking GC " << cause;
3391 }
Andreas Gampeaac09722019-01-03 08:33:58 -08003392 SCOPED_TRACE << "GC: Wait For Completion " << cause;
Mathieu Chartier590fee92013-09-13 13:46:47 -07003393 // We must wait, change thread state then sleep on gc_complete_cond_;
3394 gc_complete_cond_->Wait(self);
3395 last_gc_type = last_gc_type_;
Mathieu Chartier40112dd2017-06-26 17:49:09 -07003396 last_gc_cause = last_gc_cause_;
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07003397 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07003398 uint64_t wait_time = NanoTime() - wait_start;
3399 total_wait_time_ += wait_time;
3400 if (wait_time > long_pause_log_threshold_) {
Mathieu Chartier40112dd2017-06-26 17:49:09 -07003401 LOG(INFO) << "WaitForGcToComplete blocked " << cause << " on " << last_gc_cause << " for "
3402 << PrettyDuration(wait_time);
Mathieu Chartier590fee92013-09-13 13:46:47 -07003403 }
Hiroshi Yamauchia1c9f012015-04-02 10:18:12 -07003404 if (self != task_processor_->GetRunningThread()) {
3405 // The current thread is about to run a collection. If the thread
3406 // is not the heap task daemon thread, it's considered as a
3407 // blocking GC (i.e., blocking itself).
3408 running_collection_is_blocking_ = true;
Mathieu Chartierb166f412017-04-25 16:31:20 -07003409 // Don't log fake "GC" types that are only used for debugger or hidden APIs. If we log these,
3410 // it results in log spam. kGcCauseExplicit is already logged in LogGC, so avoid it here too.
3411 if (cause == kGcCauseForAlloc ||
3412 cause == kGcCauseForNativeAlloc ||
3413 cause == kGcCauseDisableMovingGc) {
3414 VLOG(gc) << "Starting a blocking GC " << cause;
3415 }
Hiroshi Yamauchia1c9f012015-04-02 10:18:12 -07003416 }
Mathieu Chartier866fb2a2012-09-10 10:47:49 -07003417 return last_gc_type;
Carl Shapiro69759ea2011-07-21 18:13:35 -07003418}
3419
Elliott Hughesc967f782012-04-16 10:23:15 -07003420void Heap::DumpForSigQuit(std::ostream& os) {
Ian Rogers1d54e732013-05-02 21:10:01 -07003421 os << "Heap: " << GetPercentFree() << "% free, " << PrettySize(GetBytesAllocated()) << "/"
Mathieu Chartier2fde5332012-09-14 14:51:54 -07003422 << PrettySize(GetTotalMemory()) << "; " << GetObjectsAllocated() << " objects\n";
Elliott Hughes8b788fe2013-04-17 15:57:01 -07003423 DumpGcPerformanceInfo(os);
Elliott Hughesc967f782012-04-16 10:23:15 -07003424}
3425
3426size_t Heap::GetPercentFree() {
Hans Boehmc220f982018-10-12 16:15:45 -07003427 return static_cast<size_t>(100.0f * static_cast<float>(
3428 GetFreeMemory()) / target_footprint_.load(std::memory_order_relaxed));
Elliott Hughesc967f782012-04-16 10:23:15 -07003429}
3430
Hans Boehmc220f982018-10-12 16:15:45 -07003431void Heap::SetIdealFootprint(size_t target_footprint) {
3432 if (target_footprint > GetMaxMemory()) {
3433 VLOG(gc) << "Clamp target GC heap from " << PrettySize(target_footprint) << " to "
Mathieu Chartier2fde5332012-09-14 14:51:54 -07003434 << PrettySize(GetMaxMemory());
Hans Boehmc220f982018-10-12 16:15:45 -07003435 target_footprint = GetMaxMemory();
Mathieu Chartier2fde5332012-09-14 14:51:54 -07003436 }
Hans Boehmc220f982018-10-12 16:15:45 -07003437 target_footprint_.store(target_footprint, std::memory_order_relaxed);
Shih-wei Liao8c2f6412011-10-03 22:58:14 -07003438}
3439
Mathieu Chartier0795f232016-09-27 18:43:30 -07003440bool Heap::IsMovableObject(ObjPtr<mirror::Object> obj) const {
Mathieu Chartier590fee92013-09-13 13:46:47 -07003441 if (kMovingCollector) {
Mathieu Chartier1cc62e42016-10-03 18:01:28 -07003442 space::Space* space = FindContinuousSpaceFromObject(obj.Ptr(), true);
Mathieu Chartier31f44142014-04-08 14:40:03 -07003443 if (space != nullptr) {
3444 // TODO: Check large object?
3445 return space->CanMoveObjects();
Mathieu Chartier590fee92013-09-13 13:46:47 -07003446 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07003447 }
3448 return false;
3449}
3450
Mathieu Chartierafe49982014-03-27 10:55:04 -07003451collector::GarbageCollector* Heap::FindCollectorByGcType(collector::GcType gc_type) {
Albert Mingkun Yang1c42e752018-11-19 16:10:24 +00003452 for (auto* collector : garbage_collectors_) {
Mathieu Chartierafe49982014-03-27 10:55:04 -07003453 if (collector->GetCollectorType() == collector_type_ &&
3454 collector->GetGcType() == gc_type) {
3455 return collector;
3456 }
3457 }
3458 return nullptr;
3459}
3460
Mathieu Chartier2f8da3e2014-04-15 15:37:02 -07003461double Heap::HeapGrowthMultiplier() const {
3462 // If we don't care about pause times we are background, so return 1.0.
Mathieu Chartier11c273d2017-10-15 20:54:45 -07003463 if (!CareAboutPauseTimes()) {
Mathieu Chartier2f8da3e2014-04-15 15:37:02 -07003464 return 1.0;
3465 }
3466 return foreground_heap_growth_multiplier_;
3467}
3468
Mathieu Chartiere2c2f6e2014-12-16 18:49:31 -08003469void Heap::GrowForUtilization(collector::GarbageCollector* collector_ran,
Hans Boehmc220f982018-10-12 16:15:45 -07003470 size_t bytes_allocated_before_gc) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -07003471 // We know what our utilization is at this moment.
3472 // This doesn't actually resize any memory. It just lets the heap grow more when necessary.
Hans Boehmc220f982018-10-12 16:15:45 -07003473 const size_t bytes_allocated = GetBytesAllocated();
Mathieu Chartier34afcde2017-06-30 15:31:11 -07003474 // Trace the new heap size after the GC is finished.
3475 TraceHeapSize(bytes_allocated);
Lokesh Gidraacd70602019-12-05 17:46:25 -08003476 uint64_t target_size, grow_bytes;
Mathieu Chartierafe49982014-03-27 10:55:04 -07003477 collector::GcType gc_type = collector_ran->GetGcType();
Lokesh Gidraacd70602019-12-05 17:46:25 -08003478 MutexLock mu(Thread::Current(), process_state_update_lock_);
Roland Levillain2ae376f2018-01-30 11:35:11 +00003479 // Use the multiplier to grow more for foreground.
Lokesh Gidraacd70602019-12-05 17:46:25 -08003480 const double multiplier = HeapGrowthMultiplier();
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -07003481 if (gc_type != collector::kGcTypeSticky) {
3482 // Grow the heap for non sticky GC.
Hans Boehmc220f982018-10-12 16:15:45 -07003483 uint64_t delta = bytes_allocated * (1.0 / GetTargetHeapUtilization() - 1.0);
3484 DCHECK_LE(delta, std::numeric_limits<size_t>::max()) << "bytes_allocated=" << bytes_allocated
3485 << " target_utilization_=" << target_utilization_;
Lokesh Gidraacd70602019-12-05 17:46:25 -08003486 grow_bytes = std::min(delta, static_cast<uint64_t>(max_free_));
3487 grow_bytes = std::max(grow_bytes, static_cast<uint64_t>(min_free_));
3488 target_size = bytes_allocated + static_cast<uint64_t>(grow_bytes * multiplier);
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -07003489 next_gc_type_ = collector::kGcTypeSticky;
3490 } else {
Richard Uhlercaaa2b02017-02-01 09:54:17 +00003491 collector::GcType non_sticky_gc_type = NonStickyGcType();
Mathieu Chartierafe49982014-03-27 10:55:04 -07003492 // Find what the next non sticky collector will be.
3493 collector::GarbageCollector* non_sticky_collector = FindCollectorByGcType(non_sticky_gc_type);
Albert Mingkun Yang0b4d1462018-11-29 13:25:35 +00003494 if (use_generational_cc_) {
Mathieu Chartier8d1a9962016-08-17 16:39:45 -07003495 if (non_sticky_collector == nullptr) {
3496 non_sticky_collector = FindCollectorByGcType(collector::kGcTypePartial);
3497 }
3498 CHECK(non_sticky_collector != nullptr);
3499 }
Albert Mingkun Yang0b4d1462018-11-29 13:25:35 +00003500 double sticky_gc_throughput_adjustment = GetStickyGcThroughputAdjustment(use_generational_cc_);
3501
Mathieu Chartierafe49982014-03-27 10:55:04 -07003502 // If the throughput of the current sticky GC >= throughput of the non sticky collector, then
3503 // do another sticky collection next.
Lokesh Gidra1a862c82019-02-01 11:05:04 -08003504 // We also check that the bytes allocated aren't over the target_footprint, or
3505 // concurrent_start_bytes in case of concurrent GCs, in order to prevent a
Mathieu Chartierafe49982014-03-27 10:55:04 -07003506 // pathological case where dead objects which aren't reclaimed by sticky could get accumulated
3507 // if the sticky GC throughput always remained >= the full/partial throughput.
Hans Boehmc220f982018-10-12 16:15:45 -07003508 size_t target_footprint = target_footprint_.load(std::memory_order_relaxed);
Albert Mingkun Yang0b4d1462018-11-29 13:25:35 +00003509 if (current_gc_iteration_.GetEstimatedThroughput() * sticky_gc_throughput_adjustment >=
Mathieu Chartierafe49982014-03-27 10:55:04 -07003510 non_sticky_collector->GetEstimatedMeanThroughput() &&
Mathieu Chartier10fb83a2014-06-15 15:15:43 -07003511 non_sticky_collector->NumberOfIterations() > 0 &&
Lokesh Gidra1a862c82019-02-01 11:05:04 -08003512 bytes_allocated <= (IsGcConcurrent() ? concurrent_start_bytes_ : target_footprint)) {
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -07003513 next_gc_type_ = collector::kGcTypeSticky;
3514 } else {
Mathieu Chartierafe49982014-03-27 10:55:04 -07003515 next_gc_type_ = non_sticky_gc_type;
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -07003516 }
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -07003517 // If we have freed enough memory, shrink the heap back down.
Lokesh Gidraacd70602019-12-05 17:46:25 -08003518 const size_t adjusted_max_free = static_cast<size_t>(max_free_ * multiplier);
Hans Boehmc220f982018-10-12 16:15:45 -07003519 if (bytes_allocated + adjusted_max_free < target_footprint) {
Mathieu Chartiere2c2f6e2014-12-16 18:49:31 -08003520 target_size = bytes_allocated + adjusted_max_free;
Lokesh Gidraacd70602019-12-05 17:46:25 -08003521 grow_bytes = max_free_;
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -07003522 } else {
Hans Boehmc220f982018-10-12 16:15:45 -07003523 target_size = std::max(bytes_allocated, target_footprint);
Lokesh Gidraacd70602019-12-05 17:46:25 -08003524 // The same whether jank perceptible or not; just avoid the adjustment.
3525 grow_bytes = 0;
Mathieu Chartierbdd0fb92013-07-02 10:16:15 -07003526 }
3527 }
Hans Boehmc220f982018-10-12 16:15:45 -07003528 CHECK_LE(target_size, std::numeric_limits<size_t>::max());
3529 if (!ignore_target_footprint_) {
Mathieu Chartier2775ee42013-08-20 17:43:47 -07003530 SetIdealFootprint(target_size);
Lokesh Gidraacd70602019-12-05 17:46:25 -08003531 // Store target size (computed with foreground heap growth multiplier) for updating
3532 // target_footprint_ when process state switches to foreground.
3533 // target_size = 0 ensures that target_footprint_ is not updated on
3534 // process-state switch.
3535 min_foreground_target_footprint_ =
3536 (multiplier <= 1.0 && grow_bytes > 0)
3537 ? bytes_allocated + static_cast<size_t>(grow_bytes * foreground_heap_growth_multiplier_)
3538 : 0;
3539
Hiroshi Yamauchi3e417802014-03-20 12:03:02 -07003540 if (IsGcConcurrent()) {
Mathieu Chartiere2c2f6e2014-12-16 18:49:31 -08003541 const uint64_t freed_bytes = current_gc_iteration_.GetFreedBytes() +
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07003542 current_gc_iteration_.GetFreedLargeObjectBytes() +
3543 current_gc_iteration_.GetFreedRevokeBytes();
Mathieu Chartiere2c2f6e2014-12-16 18:49:31 -08003544 // Bytes allocated will shrink by freed_bytes after the GC runs, so if we want to figure out
3545 // how many bytes were allocated during the GC we need to add freed_bytes back on.
3546 CHECK_GE(bytes_allocated + freed_bytes, bytes_allocated_before_gc);
Hans Boehmc220f982018-10-12 16:15:45 -07003547 const size_t bytes_allocated_during_gc = bytes_allocated + freed_bytes -
Mathieu Chartiere2c2f6e2014-12-16 18:49:31 -08003548 bytes_allocated_before_gc;
Mathieu Chartier2775ee42013-08-20 17:43:47 -07003549 // Calculate when to perform the next ConcurrentGC.
Mathieu Chartier2775ee42013-08-20 17:43:47 -07003550 // Estimate how many remaining bytes we will have when we need to start the next GC.
Lokesh Gidra1144b632018-01-18 10:12:38 -08003551 size_t remaining_bytes = bytes_allocated_during_gc;
Mathieu Chartier74762802014-01-24 10:21:35 -08003552 remaining_bytes = std::min(remaining_bytes, kMaxConcurrentRemainingBytes);
Mathieu Chartier2775ee42013-08-20 17:43:47 -07003553 remaining_bytes = std::max(remaining_bytes, kMinConcurrentRemainingBytes);
Hans Boehmc220f982018-10-12 16:15:45 -07003554 size_t target_footprint = target_footprint_.load(std::memory_order_relaxed);
3555 if (UNLIKELY(remaining_bytes > target_footprint)) {
Mathieu Chartier2775ee42013-08-20 17:43:47 -07003556 // A never going to happen situation that from the estimated allocation rate we will exceed
3557 // the applications entire footprint with the given estimated allocation rate. Schedule
Mathieu Chartier74762802014-01-24 10:21:35 -08003558 // another GC nearly straight away.
Hans Boehmc220f982018-10-12 16:15:45 -07003559 remaining_bytes = std::min(kMinConcurrentRemainingBytes, target_footprint);
Mathieu Chartier2775ee42013-08-20 17:43:47 -07003560 }
Hans Boehmc220f982018-10-12 16:15:45 -07003561 DCHECK_LE(target_footprint_.load(std::memory_order_relaxed), GetMaxMemory());
Mathieu Chartier74762802014-01-24 10:21:35 -08003562 // Start a concurrent GC when we get close to the estimated remaining bytes. When the
3563 // allocation rate is very high, remaining_bytes could tell us that we should start a GC
3564 // right away.
Hans Boehmc220f982018-10-12 16:15:45 -07003565 concurrent_start_bytes_ = std::max(target_footprint - remaining_bytes, bytes_allocated);
Mathieu Chartier65db8802012-11-20 12:36:46 -08003566 }
Mathieu Chartier65db8802012-11-20 12:36:46 -08003567 }
Carl Shapiro69759ea2011-07-21 18:13:35 -07003568}
3569
Mathieu Chartier379d09f2015-01-08 11:28:13 -08003570void Heap::ClampGrowthLimit() {
Mathieu Chartierddac4232015-04-02 10:08:03 -07003571 // Use heap bitmap lock to guard against races with BindLiveToMarkBitmap.
Mathieu Chartiera9d82fe2016-01-25 20:06:11 -08003572 ScopedObjectAccess soa(Thread::Current());
3573 WriterMutexLock mu(soa.Self(), *Locks::heap_bitmap_lock_);
Mathieu Chartier379d09f2015-01-08 11:28:13 -08003574 capacity_ = growth_limit_;
3575 for (const auto& space : continuous_spaces_) {
3576 if (space->IsMallocSpace()) {
3577 gc::space::MallocSpace* malloc_space = space->AsMallocSpace();
3578 malloc_space->ClampGrowthLimit();
3579 }
3580 }
Lokesh Gidra5f0b71a2018-02-06 18:01:35 -08003581 if (collector_type_ == kCollectorTypeCC) {
3582 DCHECK(region_space_ != nullptr);
3583 // Twice the capacity as CC needs extra space for evacuating objects.
3584 region_space_->ClampGrowthLimit(2 * capacity_);
3585 }
Mathieu Chartier379d09f2015-01-08 11:28:13 -08003586 // This space isn't added for performance reasons.
3587 if (main_space_backup_.get() != nullptr) {
3588 main_space_backup_->ClampGrowthLimit();
3589 }
3590}
3591
jeffhaoc1160702011-10-27 15:48:45 -07003592void Heap::ClearGrowthLimit() {
Hans Boehmc220f982018-10-12 16:15:45 -07003593 if (target_footprint_.load(std::memory_order_relaxed) == growth_limit_
3594 && growth_limit_ < capacity_) {
3595 target_footprint_.store(capacity_, std::memory_order_relaxed);
Mathieu Chartiera98a2822017-05-24 16:14:10 -07003596 concurrent_start_bytes_ =
Hans Boehmc220f982018-10-12 16:15:45 -07003597 UnsignedDifference(capacity_, kMinConcurrentRemainingBytes);
Mathieu Chartiera98a2822017-05-24 16:14:10 -07003598 }
Mathieu Chartier80de7a62012-11-27 17:21:50 -08003599 growth_limit_ = capacity_;
Mathieu Chartiera9d82fe2016-01-25 20:06:11 -08003600 ScopedObjectAccess soa(Thread::Current());
Mathieu Chartier0310da52014-12-01 13:40:48 -08003601 for (const auto& space : continuous_spaces_) {
3602 if (space->IsMallocSpace()) {
3603 gc::space::MallocSpace* malloc_space = space->AsMallocSpace();
3604 malloc_space->ClearGrowthLimit();
3605 malloc_space->SetFootprintLimit(malloc_space->Capacity());
3606 }
3607 }
3608 // This space isn't added for performance reasons.
3609 if (main_space_backup_.get() != nullptr) {
3610 main_space_backup_->ClearGrowthLimit();
3611 main_space_backup_->SetFootprintLimit(main_space_backup_->Capacity());
3612 }
jeffhaoc1160702011-10-27 15:48:45 -07003613}
3614
Mathieu Chartier9d156d52016-10-06 17:44:26 -07003615void Heap::AddFinalizerReference(Thread* self, ObjPtr<mirror::Object>* object) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003616 ScopedObjectAccess soa(self);
Mathieu Chartier8668c3c2014-04-24 16:48:11 -07003617 ScopedLocalRef<jobject> arg(self->GetJniEnv(), soa.AddLocalReference<jobject>(*object));
Ian Rogers53b8b092014-03-13 23:45:53 -07003618 jvalue args[1];
3619 args[0].l = arg.get();
3620 InvokeWithJValues(soa, nullptr, WellKnownClasses::java_lang_ref_FinalizerReference_add, args);
Mathieu Chartier8668c3c2014-04-24 16:48:11 -07003621 // Restore object in case it gets moved.
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07003622 *object = soa.Decode<mirror::Object>(arg.get());
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003623}
3624
Mathieu Chartier9d156d52016-10-06 17:44:26 -07003625void Heap::RequestConcurrentGCAndSaveObject(Thread* self,
3626 bool force_full,
3627 ObjPtr<mirror::Object>* obj) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003628 StackHandleScope<1> hs(self);
Mathieu Chartier9d156d52016-10-06 17:44:26 -07003629 HandleWrapperObjPtr<mirror::Object> wrapper(hs.NewHandleWrapper(obj));
Mathieu Chartier35b59a22017-04-17 15:24:43 -07003630 RequestConcurrentGC(self, kGcCauseBackground, force_full);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003631}
3632
Mathieu Chartiera5eae692014-12-17 17:56:03 -08003633class Heap::ConcurrentGCTask : public HeapTask {
3634 public:
Mathieu Chartier35b59a22017-04-17 15:24:43 -07003635 ConcurrentGCTask(uint64_t target_time, GcCause cause, bool force_full)
3636 : HeapTask(target_time), cause_(cause), force_full_(force_full) {}
Roland Levillainf73caca2018-08-24 17:19:07 +01003637 void Run(Thread* self) override {
Mathieu Chartiera5eae692014-12-17 17:56:03 -08003638 gc::Heap* heap = Runtime::Current()->GetHeap();
Mathieu Chartier35b59a22017-04-17 15:24:43 -07003639 heap->ConcurrentGC(self, cause_, force_full_);
Mathieu Chartiera5eae692014-12-17 17:56:03 -08003640 heap->ClearConcurrentGCRequest();
Ian Rogers120f1c72012-09-28 17:17:10 -07003641 }
Hiroshi Yamauchi0ae98992015-05-01 14:33:19 -07003642
3643 private:
Mathieu Chartier35b59a22017-04-17 15:24:43 -07003644 const GcCause cause_;
Hiroshi Yamauchi0ae98992015-05-01 14:33:19 -07003645 const bool force_full_; // If true, force full (or partial) collection.
Mathieu Chartiera5eae692014-12-17 17:56:03 -08003646};
3647
Mathieu Chartier90443472015-07-16 20:32:27 -07003648static bool CanAddHeapTask(Thread* self) REQUIRES(!Locks::runtime_shutdown_lock_) {
Mathieu Chartiera5eae692014-12-17 17:56:03 -08003649 Runtime* runtime = Runtime::Current();
3650 return runtime != nullptr && runtime->IsFinishedStarting() && !runtime->IsShuttingDown(self) &&
3651 !self->IsHandlingStackOverflow();
3652}
3653
3654void Heap::ClearConcurrentGCRequest() {
Orion Hodson88591fe2018-03-06 13:35:43 +00003655 concurrent_gc_pending_.store(false, std::memory_order_relaxed);
Mathieu Chartiera5eae692014-12-17 17:56:03 -08003656}
3657
Mathieu Chartier35b59a22017-04-17 15:24:43 -07003658void Heap::RequestConcurrentGC(Thread* self, GcCause cause, bool force_full) {
Mathieu Chartierac195162015-02-20 18:44:28 +00003659 if (CanAddHeapTask(self) &&
Orion Hodson4557b382018-01-03 11:47:54 +00003660 concurrent_gc_pending_.CompareAndSetStrongSequentiallyConsistent(false, true)) {
Hiroshi Yamauchi0ae98992015-05-01 14:33:19 -07003661 task_processor_->AddTask(self, new ConcurrentGCTask(NanoTime(), // Start straight away.
Mathieu Chartier35b59a22017-04-17 15:24:43 -07003662 cause,
Hiroshi Yamauchi0ae98992015-05-01 14:33:19 -07003663 force_full));
Mathieu Chartiera5eae692014-12-17 17:56:03 -08003664 }
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07003665}
3666
Mathieu Chartier35b59a22017-04-17 15:24:43 -07003667void Heap::ConcurrentGC(Thread* self, GcCause cause, bool force_full) {
Mathieu Chartiera5eae692014-12-17 17:56:03 -08003668 if (!Runtime::Current()->IsShuttingDown(self)) {
3669 // Wait for any GCs currently running to finish.
Mathieu Chartier35b59a22017-04-17 15:24:43 -07003670 if (WaitForGcToComplete(cause, self) == collector::kGcTypeNone) {
Hans Boehm15752672018-12-18 17:01:00 -08003671 // If we can't run the GC type we wanted to run, find the next appropriate one and try
Roland Levillainb81e9e92017-04-20 17:35:32 +01003672 // that instead. E.g. can't do partial, so do full instead.
Hiroshi Yamauchi0ae98992015-05-01 14:33:19 -07003673 collector::GcType next_gc_type = next_gc_type_;
3674 // If forcing full and next gc type is sticky, override with a non-sticky type.
3675 if (force_full && next_gc_type == collector::kGcTypeSticky) {
Richard Uhlercaaa2b02017-02-01 09:54:17 +00003676 next_gc_type = NonStickyGcType();
Hiroshi Yamauchi0ae98992015-05-01 14:33:19 -07003677 }
Mathieu Chartier35b59a22017-04-17 15:24:43 -07003678 if (CollectGarbageInternal(next_gc_type, cause, false) == collector::kGcTypeNone) {
Mathieu Chartiera5eae692014-12-17 17:56:03 -08003679 for (collector::GcType gc_type : gc_plan_) {
3680 // Attempt to run the collector, if we succeed, we are done.
Hiroshi Yamauchi0ae98992015-05-01 14:33:19 -07003681 if (gc_type > next_gc_type &&
Mathieu Chartier35b59a22017-04-17 15:24:43 -07003682 CollectGarbageInternal(gc_type, cause, false) != collector::kGcTypeNone) {
Mathieu Chartiera5eae692014-12-17 17:56:03 -08003683 break;
3684 }
Mathieu Chartierf9ed0d32013-11-21 16:42:47 -08003685 }
3686 }
3687 }
Mathieu Chartiercc236d72012-07-20 10:29:05 -07003688 }
Mathieu Chartier7664f5c2012-06-08 18:15:32 -07003689}
3690
Mathieu Chartiera5eae692014-12-17 17:56:03 -08003691class Heap::CollectorTransitionTask : public HeapTask {
3692 public:
Mathieu Chartiera4f6af92015-08-11 17:35:25 -07003693 explicit CollectorTransitionTask(uint64_t target_time) : HeapTask(target_time) {}
3694
Roland Levillainf73caca2018-08-24 17:19:07 +01003695 void Run(Thread* self) override {
Mathieu Chartiera5eae692014-12-17 17:56:03 -08003696 gc::Heap* heap = Runtime::Current()->GetHeap();
3697 heap->DoPendingCollectorTransition();
3698 heap->ClearPendingCollectorTransition(self);
Mathieu Chartiera5f9de02014-02-28 16:48:42 -08003699 }
Mathieu Chartiera5eae692014-12-17 17:56:03 -08003700};
3701
3702void Heap::ClearPendingCollectorTransition(Thread* self) {
3703 MutexLock mu(self, *pending_task_lock_);
3704 pending_collector_transition_ = nullptr;
Mathieu Chartiera5f9de02014-02-28 16:48:42 -08003705}
3706
Mathieu Chartiera5eae692014-12-17 17:56:03 -08003707void Heap::RequestCollectorTransition(CollectorType desired_collector_type, uint64_t delta_time) {
3708 Thread* self = Thread::Current();
3709 desired_collector_type_ = desired_collector_type;
3710 if (desired_collector_type_ == collector_type_ || !CanAddHeapTask(self)) {
3711 return;
3712 }
Hiroshi Yamauchi60985b72016-08-24 13:53:12 -07003713 if (collector_type_ == kCollectorTypeCC) {
3714 // For CC, we invoke a full compaction when going to the background, but the collector type
3715 // doesn't change.
3716 DCHECK_EQ(desired_collector_type_, kCollectorTypeCCBackground);
3717 }
3718 DCHECK_NE(collector_type_, kCollectorTypeCCBackground);
Mathieu Chartiera5eae692014-12-17 17:56:03 -08003719 CollectorTransitionTask* added_task = nullptr;
3720 const uint64_t target_time = NanoTime() + delta_time;
3721 {
3722 MutexLock mu(self, *pending_task_lock_);
3723 // If we have an existing collector transition, update the targe time to be the new target.
3724 if (pending_collector_transition_ != nullptr) {
3725 task_processor_->UpdateTargetRunTime(self, pending_collector_transition_, target_time);
3726 return;
3727 }
3728 added_task = new CollectorTransitionTask(target_time);
3729 pending_collector_transition_ = added_task;
3730 }
3731 task_processor_->AddTask(self, added_task);
3732}
3733
3734class Heap::HeapTrimTask : public HeapTask {
3735 public:
3736 explicit HeapTrimTask(uint64_t delta_time) : HeapTask(NanoTime() + delta_time) { }
Roland Levillainf73caca2018-08-24 17:19:07 +01003737 void Run(Thread* self) override {
Mathieu Chartiera5eae692014-12-17 17:56:03 -08003738 gc::Heap* heap = Runtime::Current()->GetHeap();
3739 heap->Trim(self);
3740 heap->ClearPendingTrim(self);
3741 }
3742};
3743
3744void Heap::ClearPendingTrim(Thread* self) {
3745 MutexLock mu(self, *pending_task_lock_);
3746 pending_heap_trim_ = nullptr;
3747}
3748
3749void Heap::RequestTrim(Thread* self) {
3750 if (!CanAddHeapTask(self)) {
3751 return;
3752 }
Ian Rogers48931882013-01-22 14:35:16 -08003753 // GC completed and now we must decide whether to request a heap trim (advising pages back to the
3754 // kernel) or not. Issuing a request will also cause trimming of the libc heap. As a trim scans
3755 // a space it will hold its lock and can become a cause of jank.
3756 // Note, the large object space self trims and the Zygote space was trimmed and unchanging since
3757 // forking.
3758
Elliott Hughes8cf5bc02012-02-02 16:32:16 -08003759 // We don't have a good measure of how worthwhile a trim might be. We can't use the live bitmap
3760 // because that only marks object heads, so a large array looks like lots of empty space. We
3761 // don't just call dlmalloc all the time, because the cost of an _attempted_ trim is proportional
3762 // to utilization (which is probably inversely proportional to how much benefit we can expect).
3763 // We could try mincore(2) but that's only a measure of how many pages we haven't given away,
3764 // not how much use we're making of those pages.
Mathieu Chartiera5eae692014-12-17 17:56:03 -08003765 HeapTrimTask* added_task = nullptr;
Mathieu Chartier440e4ce2014-03-31 16:36:35 -07003766 {
Mathieu Chartiera5eae692014-12-17 17:56:03 -08003767 MutexLock mu(self, *pending_task_lock_);
3768 if (pending_heap_trim_ != nullptr) {
3769 // Already have a heap trim request in task processor, ignore this request.
Mathieu Chartier440e4ce2014-03-31 16:36:35 -07003770 return;
Mathieu Chartiera5f9de02014-02-28 16:48:42 -08003771 }
Mathieu Chartiera5eae692014-12-17 17:56:03 -08003772 added_task = new HeapTrimTask(kHeapTrimWait);
3773 pending_heap_trim_ = added_task;
Mathieu Chartierc39e3422013-08-07 16:41:36 -07003774 }
Mathieu Chartiera5eae692014-12-17 17:56:03 -08003775 task_processor_->AddTask(self, added_task);
Mathieu Chartiera5f9de02014-02-28 16:48:42 -08003776}
3777
Orion Hodson82cf9a22018-03-27 16:36:32 +01003778void Heap::IncrementNumberOfBytesFreedRevoke(size_t freed_bytes_revoke) {
3779 size_t previous_num_bytes_freed_revoke =
Hans Boehmfb8b4e22018-09-05 16:45:42 -07003780 num_bytes_freed_revoke_.fetch_add(freed_bytes_revoke, std::memory_order_relaxed);
Orion Hodson82cf9a22018-03-27 16:36:32 +01003781 // Check the updated value is less than the number of bytes allocated. There is a risk of
3782 // execution being suspended between the increment above and the CHECK below, leading to
3783 // the use of previous_num_bytes_freed_revoke in the comparison.
3784 CHECK_GE(num_bytes_allocated_.load(std::memory_order_relaxed),
3785 previous_num_bytes_freed_revoke + freed_bytes_revoke);
3786}
3787
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -07003788void Heap::RevokeThreadLocalBuffers(Thread* thread) {
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08003789 if (rosalloc_space_ != nullptr) {
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07003790 size_t freed_bytes_revoke = rosalloc_space_->RevokeThreadLocalBuffers(thread);
3791 if (freed_bytes_revoke > 0U) {
Orion Hodson82cf9a22018-03-27 16:36:32 +01003792 IncrementNumberOfBytesFreedRevoke(freed_bytes_revoke);
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07003793 }
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08003794 }
Mathieu Chartier692fafd2013-11-29 17:24:40 -08003795 if (bump_pointer_space_ != nullptr) {
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07003796 CHECK_EQ(bump_pointer_space_->RevokeThreadLocalBuffers(thread), 0U);
Mathieu Chartier692fafd2013-11-29 17:24:40 -08003797 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003798 if (region_space_ != nullptr) {
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07003799 CHECK_EQ(region_space_->RevokeThreadLocalBuffers(thread), 0U);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003800 }
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -07003801}
3802
Hiroshi Yamauchic93c5302014-03-20 16:15:37 -07003803void Heap::RevokeRosAllocThreadLocalBuffers(Thread* thread) {
3804 if (rosalloc_space_ != nullptr) {
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07003805 size_t freed_bytes_revoke = rosalloc_space_->RevokeThreadLocalBuffers(thread);
3806 if (freed_bytes_revoke > 0U) {
Orion Hodson82cf9a22018-03-27 16:36:32 +01003807 IncrementNumberOfBytesFreedRevoke(freed_bytes_revoke);
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07003808 }
Hiroshi Yamauchic93c5302014-03-20 16:15:37 -07003809 }
3810}
3811
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -07003812void Heap::RevokeAllThreadLocalBuffers() {
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08003813 if (rosalloc_space_ != nullptr) {
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07003814 size_t freed_bytes_revoke = rosalloc_space_->RevokeAllThreadLocalBuffers();
3815 if (freed_bytes_revoke > 0U) {
Orion Hodson82cf9a22018-03-27 16:36:32 +01003816 IncrementNumberOfBytesFreedRevoke(freed_bytes_revoke);
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07003817 }
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08003818 }
Mathieu Chartier692fafd2013-11-29 17:24:40 -08003819 if (bump_pointer_space_ != nullptr) {
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07003820 CHECK_EQ(bump_pointer_space_->RevokeAllThreadLocalBuffers(), 0U);
Mathieu Chartier692fafd2013-11-29 17:24:40 -08003821 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003822 if (region_space_ != nullptr) {
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -07003823 CHECK_EQ(region_space_->RevokeAllThreadLocalBuffers(), 0U);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08003824 }
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -07003825}
3826
Mathieu Chartier987ccff2013-07-08 11:05:21 -07003827bool Heap::IsGCRequestPending() const {
Orion Hodson88591fe2018-03-06 13:35:43 +00003828 return concurrent_gc_pending_.load(std::memory_order_relaxed);
Mathieu Chartier987ccff2013-07-08 11:05:21 -07003829}
3830
Mathieu Chartierb5de3bb2015-06-05 13:21:05 -07003831void Heap::RunFinalization(JNIEnv* env, uint64_t timeout) {
3832 env->CallStaticVoidMethod(WellKnownClasses::dalvik_system_VMRuntime,
3833 WellKnownClasses::dalvik_system_VMRuntime_runFinalization,
3834 static_cast<jlong>(timeout));
Mathieu Chartier590fee92013-09-13 13:46:47 -07003835}
3836
Hans Boehmc220f982018-10-12 16:15:45 -07003837// For GC triggering purposes, we count old (pre-last-GC) and new native allocations as
3838// different fractions of Java allocations.
3839// For now, we essentially do not count old native allocations at all, so that we can preserve the
3840// existing behavior of not limiting native heap size. If we seriously considered it, we would
3841// have to adjust collection thresholds when we encounter large amounts of old native memory,
3842// and handle native out-of-memory situations.
Richard Uhler36bdbd22017-01-24 14:17:05 +00003843
Hans Boehmc220f982018-10-12 16:15:45 -07003844static constexpr size_t kOldNativeDiscountFactor = 65536; // Approximately infinite for now.
3845static constexpr size_t kNewNativeDiscountFactor = 2;
3846
3847// If weighted java + native memory use exceeds our target by kStopForNativeFactor, and
Hans Boehmbb2467b2019-03-29 22:55:06 -07003848// newly allocated memory exceeds stop_for_native_allocs_, we wait for GC to complete to avoid
Hans Boehmc220f982018-10-12 16:15:45 -07003849// running out of memory.
Hans Boehm15752672018-12-18 17:01:00 -08003850static constexpr float kStopForNativeFactor = 4.0;
Hans Boehmc220f982018-10-12 16:15:45 -07003851
3852// Return the ratio of the weighted native + java allocated bytes to its target value.
3853// A return value > 1.0 means we should collect. Significantly larger values mean we're falling
3854// behind.
Hans Boehm7c73dd12019-02-06 00:20:18 +00003855inline float Heap::NativeMemoryOverTarget(size_t current_native_bytes, bool is_gc_concurrent) {
Hans Boehmc220f982018-10-12 16:15:45 -07003856 // Collection check for native allocation. Does not enforce Java heap bounds.
3857 // With adj_start_bytes defined below, effectively checks
3858 // <java bytes allocd> + c1*<old native allocd> + c2*<new native allocd) >= adj_start_bytes,
3859 // where c3 > 1, and currently c1 and c2 are 1 divided by the values defined above.
3860 size_t old_native_bytes = old_native_bytes_allocated_.load(std::memory_order_relaxed);
3861 if (old_native_bytes > current_native_bytes) {
3862 // Net decrease; skip the check, but update old value.
3863 // It's OK to lose an update if two stores race.
3864 old_native_bytes_allocated_.store(current_native_bytes, std::memory_order_relaxed);
3865 return 0.0;
3866 } else {
3867 size_t new_native_bytes = UnsignedDifference(current_native_bytes, old_native_bytes);
3868 size_t weighted_native_bytes = new_native_bytes / kNewNativeDiscountFactor
3869 + old_native_bytes / kOldNativeDiscountFactor;
Hans Boehm15752672018-12-18 17:01:00 -08003870 size_t add_bytes_allowed = static_cast<size_t>(
3871 NativeAllocationGcWatermark() * HeapGrowthMultiplier());
Hans Boehm7c73dd12019-02-06 00:20:18 +00003872 size_t java_gc_start_bytes = is_gc_concurrent
3873 ? concurrent_start_bytes_
3874 : target_footprint_.load(std::memory_order_relaxed);
3875 size_t adj_start_bytes = UnsignedSum(java_gc_start_bytes,
3876 add_bytes_allowed / kNewNativeDiscountFactor);
Hans Boehmc220f982018-10-12 16:15:45 -07003877 return static_cast<float>(GetBytesAllocated() + weighted_native_bytes)
3878 / static_cast<float>(adj_start_bytes);
3879 }
3880}
3881
Hans Boehm7c73dd12019-02-06 00:20:18 +00003882inline void Heap::CheckGCForNative(Thread* self) {
3883 bool is_gc_concurrent = IsGcConcurrent();
Hans Boehmc220f982018-10-12 16:15:45 -07003884 size_t current_native_bytes = GetNativeBytes();
Hans Boehm7c73dd12019-02-06 00:20:18 +00003885 float gc_urgency = NativeMemoryOverTarget(current_native_bytes, is_gc_concurrent);
Hans Boehmc220f982018-10-12 16:15:45 -07003886 if (UNLIKELY(gc_urgency >= 1.0)) {
Hans Boehm7c73dd12019-02-06 00:20:18 +00003887 if (is_gc_concurrent) {
Hans Boehmc220f982018-10-12 16:15:45 -07003888 RequestConcurrentGC(self, kGcCauseForNativeAlloc, /*force_full=*/true);
3889 if (gc_urgency > kStopForNativeFactor
Hans Boehmbb2467b2019-03-29 22:55:06 -07003890 && current_native_bytes > stop_for_native_allocs_) {
Hans Boehmc220f982018-10-12 16:15:45 -07003891 // We're in danger of running out of memory due to rampant native allocation.
3892 if (VLOG_IS_ON(heap) || VLOG_IS_ON(startup)) {
3893 LOG(INFO) << "Stopping for native allocation, urgency: " << gc_urgency;
3894 }
Hans Boehm15752672018-12-18 17:01:00 -08003895 WaitForGcToComplete(kGcCauseForNativeAlloc, self);
Hans Boehmc220f982018-10-12 16:15:45 -07003896 }
Richard Uhlercaaa2b02017-02-01 09:54:17 +00003897 } else {
3898 CollectGarbageInternal(NonStickyGcType(), kGcCauseForNativeAlloc, false);
3899 }
Mathieu Chartier987ccff2013-07-08 11:05:21 -07003900 }
3901}
3902
Hans Boehmc220f982018-10-12 16:15:45 -07003903// About kNotifyNativeInterval allocations have occurred. Check whether we should garbage collect.
3904void Heap::NotifyNativeAllocations(JNIEnv* env) {
3905 native_objects_notified_.fetch_add(kNotifyNativeInterval, std::memory_order_relaxed);
Hans Boehm7c73dd12019-02-06 00:20:18 +00003906 CheckGCForNative(ThreadForEnv(env));
Hans Boehmc220f982018-10-12 16:15:45 -07003907}
3908
3909// Register a native allocation with an explicit size.
3910// This should only be done for large allocations of non-malloc memory, which we wouldn't
3911// otherwise see.
3912void Heap::RegisterNativeAllocation(JNIEnv* env, size_t bytes) {
Hans Boehm13e951d2019-11-01 16:48:28 -07003913 // Cautiously check for a wrapped negative bytes argument.
3914 DCHECK(sizeof(size_t) < 8 || bytes < (std::numeric_limits<size_t>::max() / 2));
Hans Boehmc220f982018-10-12 16:15:45 -07003915 native_bytes_registered_.fetch_add(bytes, std::memory_order_relaxed);
3916 uint32_t objects_notified =
3917 native_objects_notified_.fetch_add(1, std::memory_order_relaxed);
3918 if (objects_notified % kNotifyNativeInterval == kNotifyNativeInterval - 1
3919 || bytes > kCheckImmediatelyThreshold) {
Hans Boehm7c73dd12019-02-06 00:20:18 +00003920 CheckGCForNative(ThreadForEnv(env));
Richard Uhlercaaa2b02017-02-01 09:54:17 +00003921 }
Mathieu Chartier987ccff2013-07-08 11:05:21 -07003922}
3923
Hans Boehmc220f982018-10-12 16:15:45 -07003924void Heap::RegisterNativeFree(JNIEnv*, size_t bytes) {
3925 size_t allocated;
3926 size_t new_freed_bytes;
3927 do {
3928 allocated = native_bytes_registered_.load(std::memory_order_relaxed);
3929 new_freed_bytes = std::min(allocated, bytes);
3930 // We should not be registering more free than allocated bytes.
3931 // But correctly keep going in non-debug builds.
3932 DCHECK_EQ(new_freed_bytes, bytes);
3933 } while (!native_bytes_registered_.CompareAndSetWeakRelaxed(allocated,
3934 allocated - new_freed_bytes));
3935}
3936
Ian Rogersef7d42f2014-01-06 12:55:46 -08003937size_t Heap::GetTotalMemory() const {
Hans Boehmc220f982018-10-12 16:15:45 -07003938 return std::max(target_footprint_.load(std::memory_order_relaxed), GetBytesAllocated());
Hiroshi Yamauchi09b07a92013-07-15 13:17:06 -07003939}
3940
Mathieu Chartier11409ae2013-09-23 11:49:36 -07003941void Heap::AddModUnionTable(accounting::ModUnionTable* mod_union_table) {
3942 DCHECK(mod_union_table != nullptr);
3943 mod_union_tables_.Put(mod_union_table->GetSpace(), mod_union_table);
3944}
3945
Mathieu Chartier9d156d52016-10-06 17:44:26 -07003946void Heap::CheckPreconditionsForAllocObject(ObjPtr<mirror::Class> c, size_t byte_count) {
Mathieu Chartierdf7f7f02017-10-05 09:47:58 -07003947 // Compare rounded sizes since the allocation may have been retried after rounding the size.
3948 // See b/37885600
Mathieu Chartiera5eae692014-12-17 17:56:03 -08003949 CHECK(c == nullptr || (c->IsClassClass() && byte_count >= sizeof(mirror::Class)) ||
Mathieu Chartieraac90122017-10-04 14:58:34 -07003950 (c->IsVariableSize() ||
3951 RoundUp(c->GetObjectSize(), kObjectAlignment) ==
3952 RoundUp(byte_count, kObjectAlignment)))
Mathieu Chartier8876fb72017-02-24 12:39:53 -08003953 << "ClassFlags=" << c->GetClassFlags()
3954 << " IsClassClass=" << c->IsClassClass()
3955 << " byte_count=" << byte_count
3956 << " IsVariableSize=" << c->IsVariableSize()
3957 << " ObjectSize=" << c->GetObjectSize()
3958 << " sizeof(Class)=" << sizeof(mirror::Class)
Andreas Gampe98ea9d92018-10-19 14:06:15 -07003959 << " " << verification_->DumpObjectInfo(c.Ptr(), /*tag=*/ "klass");
Mathieu Chartierc645f1d2014-03-06 18:11:53 -08003960 CHECK_GE(byte_count, sizeof(mirror::Object));
3961}
3962
Hiroshi Yamauchi38e68e92014-03-07 13:59:08 -08003963void Heap::AddRememberedSet(accounting::RememberedSet* remembered_set) {
3964 CHECK(remembered_set != nullptr);
3965 space::Space* space = remembered_set->GetSpace();
3966 CHECK(space != nullptr);
Mathieu Chartier8e4a96d2014-05-21 10:44:32 -07003967 CHECK(remembered_sets_.find(space) == remembered_sets_.end()) << space;
Hiroshi Yamauchi38e68e92014-03-07 13:59:08 -08003968 remembered_sets_.Put(space, remembered_set);
Mathieu Chartier8e4a96d2014-05-21 10:44:32 -07003969 CHECK(remembered_sets_.find(space) != remembered_sets_.end()) << space;
Hiroshi Yamauchi38e68e92014-03-07 13:59:08 -08003970}
3971
3972void Heap::RemoveRememberedSet(space::Space* space) {
3973 CHECK(space != nullptr);
3974 auto it = remembered_sets_.find(space);
3975 CHECK(it != remembered_sets_.end());
Mathieu Chartier5189e242014-07-24 11:11:05 -07003976 delete it->second;
Hiroshi Yamauchi38e68e92014-03-07 13:59:08 -08003977 remembered_sets_.erase(it);
3978 CHECK(remembered_sets_.find(space) == remembered_sets_.end());
3979}
3980
Mathieu Chartier4aeec172014-03-27 16:09:46 -07003981void Heap::ClearMarkedObjects() {
3982 // Clear all of the spaces' mark bitmaps.
3983 for (const auto& space : GetContinuousSpaces()) {
Mathieu Chartier6f382012019-07-30 09:47:35 -07003984 if (space->GetLiveBitmap() != nullptr && !space->HasBoundBitmaps()) {
3985 space->GetMarkBitmap()->Clear();
Mathieu Chartier4aeec172014-03-27 16:09:46 -07003986 }
3987 }
3988 // Clear the marked objects in the discontinous space object sets.
3989 for (const auto& space : GetDiscontinuousSpaces()) {
Mathieu Chartierbbd695c2014-04-16 09:48:48 -07003990 space->GetMarkBitmap()->Clear();
Mathieu Chartier4aeec172014-03-27 16:09:46 -07003991 }
3992}
3993
Man Cao8c2ff642015-05-27 17:25:30 -07003994void Heap::SetAllocationRecords(AllocRecordObjectMap* records) {
3995 allocation_records_.reset(records);
3996}
3997
Man Cao1ed11b92015-06-11 22:47:35 -07003998void Heap::VisitAllocationRecords(RootVisitor* visitor) const {
3999 if (IsAllocTrackingEnabled()) {
4000 MutexLock mu(Thread::Current(), *Locks::alloc_tracker_lock_);
4001 if (IsAllocTrackingEnabled()) {
4002 GetAllocationRecords()->VisitRoots(visitor);
4003 }
4004 }
4005}
4006
Mathieu Chartier97509952015-07-13 14:35:43 -07004007void Heap::SweepAllocationRecords(IsMarkedVisitor* visitor) const {
Man Cao8c2ff642015-05-27 17:25:30 -07004008 if (IsAllocTrackingEnabled()) {
4009 MutexLock mu(Thread::Current(), *Locks::alloc_tracker_lock_);
4010 if (IsAllocTrackingEnabled()) {
Mathieu Chartier97509952015-07-13 14:35:43 -07004011 GetAllocationRecords()->SweepAllocationRecords(visitor);
Man Cao8c2ff642015-05-27 17:25:30 -07004012 }
4013 }
4014}
4015
Man Cao42c3c332015-06-23 16:38:25 -07004016void Heap::AllowNewAllocationRecords() const {
Hiroshi Yamauchifdbd13c2015-09-02 16:16:58 -07004017 CHECK(!kUseReadBarrier);
Hiroshi Yamauchi6f0c6cd2016-03-18 17:17:52 -07004018 MutexLock mu(Thread::Current(), *Locks::alloc_tracker_lock_);
4019 AllocRecordObjectMap* allocation_records = GetAllocationRecords();
4020 if (allocation_records != nullptr) {
4021 allocation_records->AllowNewAllocationRecords();
Man Cao42c3c332015-06-23 16:38:25 -07004022 }
4023}
4024
4025void Heap::DisallowNewAllocationRecords() const {
Hiroshi Yamauchifdbd13c2015-09-02 16:16:58 -07004026 CHECK(!kUseReadBarrier);
Hiroshi Yamauchi6f0c6cd2016-03-18 17:17:52 -07004027 MutexLock mu(Thread::Current(), *Locks::alloc_tracker_lock_);
4028 AllocRecordObjectMap* allocation_records = GetAllocationRecords();
4029 if (allocation_records != nullptr) {
4030 allocation_records->DisallowNewAllocationRecords();
Man Cao42c3c332015-06-23 16:38:25 -07004031 }
4032}
4033
Hiroshi Yamauchifdbd13c2015-09-02 16:16:58 -07004034void Heap::BroadcastForNewAllocationRecords() const {
Hiroshi Yamauchi6f0c6cd2016-03-18 17:17:52 -07004035 // Always broadcast without checking IsAllocTrackingEnabled() because IsAllocTrackingEnabled() may
4036 // be set to false while some threads are waiting for system weak access in
4037 // AllocRecordObjectMap::RecordAllocation() and we may fail to wake them up. b/27467554.
4038 MutexLock mu(Thread::Current(), *Locks::alloc_tracker_lock_);
4039 AllocRecordObjectMap* allocation_records = GetAllocationRecords();
4040 if (allocation_records != nullptr) {
4041 allocation_records->BroadcastForNewAllocationRecords();
Hiroshi Yamauchifdbd13c2015-09-02 16:16:58 -07004042 }
4043}
4044
Wessam Hassaneinb5a10be2020-11-11 16:42:52 -08004045// Perfetto Java Heap Profiler Support.
4046
4047// Perfetto initialization.
4048void Heap::InitPerfettoJavaHeapProf() {
4049 // Register the heap and create the heapid.
4050 // Use a heap name = "HeapSampler".
4051 // Initialize Perfetto Heap info and Heap id.
4052 static uint32_t heap_id = 1; // Initialize to 1, to be overwritten by Perfetto heap id.
4053 SetPerfettoJavaHeapProfHeapID(heap_id);
4054 // Enable the Java Heap Profiler.
4055 GetHeapSampler().EnableHeapSampler(/*enable_ptr=*/nullptr, /*enable_info_ptr=*/nullptr);
4056 // Set the Enable Callback, there is no callback data ("nullptr").
4057 // Set the Disable Callback.
4058 VLOG(heap) << "Java Heap Profiler Initialized";
4059}
4060
4061// Check if the Java Heap Profiler is enabled and initialized.
4062int Heap::CheckPerfettoJHPEnabled() {
4063 return GetHeapSampler().IsEnabled();
4064}
4065
4066void Heap::JHPCheckNonTlabSampleAllocation(Thread* self, mirror::Object* ret, size_t alloc_size) {
4067 bool take_sample = false;
4068 size_t bytes_until_sample = 0;
4069 HeapSampler& prof_heap_sampler = GetHeapSampler();
4070 if (ret != nullptr && prof_heap_sampler.IsEnabled()) {
4071 // An allocation occurred, sample it, even if non-Tlab.
4072 // In case take_sample is already set from the previous GetSampleOffset
4073 // because we tried the Tlab allocation first, we will not use this value.
4074 // A new value is generated below. Also bytes_until_sample will be updated.
4075 // Note that we are not using the return value from the GetSampleOffset in
4076 // the NonTlab case here.
4077 prof_heap_sampler.GetSampleOffset(alloc_size,
4078 self->GetTlabPosOffset(),
4079 &take_sample,
4080 &bytes_until_sample);
4081 prof_heap_sampler.SetBytesUntilSample(bytes_until_sample);
4082 if (take_sample) {
4083 prof_heap_sampler.ReportSample(ret, alloc_size);
4084 }
4085 VLOG(heap) << "JHP:NonTlab:AllocNonvirtual";
4086 }
4087}
4088
4089size_t Heap::JHPCalculateNextTlabSize(Thread* self,
4090 size_t jhp_def_tlab_size,
4091 size_t alloc_size,
4092 bool* take_sample,
4093 size_t* bytes_until_sample) {
4094 size_t next_tlab_size = jhp_def_tlab_size;
4095 if (CheckPerfettoJHPEnabled()) {
4096 size_t next_sample_point =
4097 GetHeapSampler().GetSampleOffset(alloc_size,
4098 self->GetTlabPosOffset(),
4099 take_sample,
4100 bytes_until_sample);
4101 next_tlab_size = std::min(next_sample_point, jhp_def_tlab_size);
4102 }
4103 return next_tlab_size;
4104}
4105
4106void Heap::AdjustSampleOffset(size_t adjustment) {
4107 GetHeapSampler().AdjustSampleOffset(adjustment);
4108}
4109
Mathieu Chartier9d156d52016-10-06 17:44:26 -07004110void Heap::CheckGcStressMode(Thread* self, ObjPtr<mirror::Object>* obj) {
Vladimir Marko317892b2018-05-31 11:11:32 +01004111 DCHECK(gc_stress_mode_);
Mathieu Chartier31000802015-06-14 14:14:37 -07004112 auto* const runtime = Runtime::Current();
Vladimir Marko317892b2018-05-31 11:11:32 +01004113 if (runtime->GetClassLinker()->IsInitialized() && !runtime->IsActiveTransaction()) {
Mathieu Chartier31000802015-06-14 14:14:37 -07004114 // Check if we should GC.
4115 bool new_backtrace = false;
4116 {
4117 static constexpr size_t kMaxFrames = 16u;
Mathieu Chartier409736f2019-10-22 18:13:29 -07004118 MutexLock mu(self, *backtrace_lock_);
Mathieu Chartier34583592017-03-23 23:51:34 -07004119 FixedSizeBacktrace<kMaxFrames> backtrace;
Andreas Gampe98ea9d92018-10-19 14:06:15 -07004120 backtrace.Collect(/* skip_count= */ 2);
Mathieu Chartier34583592017-03-23 23:51:34 -07004121 uint64_t hash = backtrace.Hash();
Mathieu Chartier31000802015-06-14 14:14:37 -07004122 new_backtrace = seen_backtraces_.find(hash) == seen_backtraces_.end();
4123 if (new_backtrace) {
4124 seen_backtraces_.insert(hash);
4125 }
4126 }
4127 if (new_backtrace) {
4128 StackHandleScope<1> hs(self);
4129 auto h = hs.NewHandleWrapper(obj);
Andreas Gampe98ea9d92018-10-19 14:06:15 -07004130 CollectGarbage(/* clear_soft_references= */ false);
Hans Boehmfb8b4e22018-09-05 16:45:42 -07004131 unique_backtrace_count_.fetch_add(1);
Mathieu Chartier31000802015-06-14 14:14:37 -07004132 } else {
Hans Boehmfb8b4e22018-09-05 16:45:42 -07004133 seen_backtrace_count_.fetch_add(1);
Mathieu Chartier31000802015-06-14 14:14:37 -07004134 }
4135 }
4136}
4137
Mathieu Chartier51168372015-08-12 16:40:32 -07004138void Heap::DisableGCForShutdown() {
4139 Thread* const self = Thread::Current();
4140 CHECK(Runtime::Current()->IsShuttingDown(self));
4141 MutexLock mu(self, *gc_complete_lock_);
4142 gc_disabled_for_shutdown_ = true;
4143}
4144
Mathieu Chartier9d156d52016-10-06 17:44:26 -07004145bool Heap::ObjectIsInBootImageSpace(ObjPtr<mirror::Object> obj) const {
Vladimir Marko7cde4582019-07-05 13:26:11 +01004146 DCHECK_EQ(IsBootImageAddress(obj.Ptr()),
4147 any_of(boot_image_spaces_.begin(),
4148 boot_image_spaces_.end(),
4149 [obj](gc::space::ImageSpace* space) REQUIRES_SHARED(Locks::mutator_lock_) {
4150 return space->HasAddress(obj.Ptr());
4151 }));
4152 return IsBootImageAddress(obj.Ptr());
Mathieu Chartierfbc31082016-01-24 11:59:56 -08004153}
4154
Mingyao Yang6ea1a0e2016-01-29 12:12:49 -08004155bool Heap::IsInBootImageOatFile(const void* p) const {
Vladimir Marko7cde4582019-07-05 13:26:11 +01004156 DCHECK_EQ(IsBootImageAddress(p),
4157 any_of(boot_image_spaces_.begin(),
4158 boot_image_spaces_.end(),
4159 [p](gc::space::ImageSpace* space) REQUIRES_SHARED(Locks::mutator_lock_) {
4160 return space->GetOatFile()->Contains(p);
4161 }));
4162 return IsBootImageAddress(p);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08004163}
4164
Andreas Gampe27fa96c2016-10-07 15:05:24 -07004165void Heap::SetAllocationListener(AllocationListener* l) {
4166 AllocationListener* old = GetAndOverwriteAllocationListener(&alloc_listener_, l);
4167
4168 if (old == nullptr) {
4169 Runtime::Current()->GetInstrumentation()->InstrumentQuickAllocEntryPoints();
4170 }
4171}
4172
4173void Heap::RemoveAllocationListener() {
4174 AllocationListener* old = GetAndOverwriteAllocationListener(&alloc_listener_, nullptr);
4175
4176 if (old != nullptr) {
Andreas Gampe172ec8e2016-10-12 13:50:20 -07004177 Runtime::Current()->GetInstrumentation()->UninstrumentQuickAllocEntryPoints();
Andreas Gampe27fa96c2016-10-07 15:05:24 -07004178 }
4179}
4180
Andreas Gampe9b8c5882016-10-21 15:27:46 -07004181void Heap::SetGcPauseListener(GcPauseListener* l) {
Orion Hodson88591fe2018-03-06 13:35:43 +00004182 gc_pause_listener_.store(l, std::memory_order_relaxed);
Andreas Gampe9b8c5882016-10-21 15:27:46 -07004183}
4184
4185void Heap::RemoveGcPauseListener() {
Orion Hodson88591fe2018-03-06 13:35:43 +00004186 gc_pause_listener_.store(nullptr, std::memory_order_relaxed);
Andreas Gampe9b8c5882016-10-21 15:27:46 -07004187}
Andreas Gampe27fa96c2016-10-07 15:05:24 -07004188
Mathieu Chartier5ace2012016-11-30 10:15:41 -08004189mirror::Object* Heap::AllocWithNewTLAB(Thread* self,
Lokesh Gidra7e678d32020-04-28 16:17:49 -07004190 AllocatorType allocator_type,
Mathieu Chartier5ace2012016-11-30 10:15:41 -08004191 size_t alloc_size,
4192 bool grow,
4193 size_t* bytes_allocated,
4194 size_t* usable_size,
4195 size_t* bytes_tl_bulk_allocated) {
Wessam Hassaneinb5a10be2020-11-11 16:42:52 -08004196 mirror::Object* ret = nullptr;
4197 bool take_sample = false;
4198 size_t bytes_until_sample = 0;
4199
Mathieu Chartier6bc77742017-04-18 17:46:23 -07004200 if (kUsePartialTlabs && alloc_size <= self->TlabRemainingCapacity()) {
4201 DCHECK_GT(alloc_size, self->TlabSize());
4202 // There is enough space if we grow the TLAB. Lets do that. This increases the
4203 // TLAB bytes.
4204 const size_t min_expand_size = alloc_size - self->TlabSize();
Wessam Hassaneinb5a10be2020-11-11 16:42:52 -08004205 size_t next_tlab_size = JHPCalculateNextTlabSize(self,
4206 kPartialTlabSize,
4207 alloc_size,
4208 &take_sample,
4209 &bytes_until_sample);
Mathieu Chartier6bc77742017-04-18 17:46:23 -07004210 const size_t expand_bytes = std::max(
4211 min_expand_size,
Wessam Hassaneinb5a10be2020-11-11 16:42:52 -08004212 std::min(self->TlabRemainingCapacity() - self->TlabSize(), next_tlab_size));
Mathieu Chartier6bc77742017-04-18 17:46:23 -07004213 if (UNLIKELY(IsOutOfMemoryOnAllocation(allocator_type, expand_bytes, grow))) {
4214 return nullptr;
4215 }
4216 *bytes_tl_bulk_allocated = expand_bytes;
4217 self->ExpandTlab(expand_bytes);
4218 DCHECK_LE(alloc_size, self->TlabSize());
4219 } else if (allocator_type == kAllocatorTypeTLAB) {
Mathieu Chartier5ace2012016-11-30 10:15:41 -08004220 DCHECK(bump_pointer_space_ != nullptr);
Wessam Hassaneinb5a10be2020-11-11 16:42:52 -08004221 size_t next_tlab_size = JHPCalculateNextTlabSize(self,
4222 kDefaultTLABSize,
4223 alloc_size,
4224 &take_sample,
4225 &bytes_until_sample);
4226 const size_t new_tlab_size = alloc_size + next_tlab_size;
Mathieu Chartier5ace2012016-11-30 10:15:41 -08004227 if (UNLIKELY(IsOutOfMemoryOnAllocation(allocator_type, new_tlab_size, grow))) {
4228 return nullptr;
4229 }
4230 // Try allocating a new thread local buffer, if the allocation fails the space must be
4231 // full so return null.
4232 if (!bump_pointer_space_->AllocNewTlab(self, new_tlab_size)) {
4233 return nullptr;
4234 }
4235 *bytes_tl_bulk_allocated = new_tlab_size;
Wessam Hassaneinb5a10be2020-11-11 16:42:52 -08004236 if (CheckPerfettoJHPEnabled()) {
4237 VLOG(heap) << "JHP:kAllocatorTypeTLAB, New Tlab bytes allocated= " << new_tlab_size;
4238 }
Mathieu Chartier5ace2012016-11-30 10:15:41 -08004239 } else {
4240 DCHECK(allocator_type == kAllocatorTypeRegionTLAB);
4241 DCHECK(region_space_ != nullptr);
4242 if (space::RegionSpace::kRegionSize >= alloc_size) {
4243 // Non-large. Check OOME for a tlab.
4244 if (LIKELY(!IsOutOfMemoryOnAllocation(allocator_type,
4245 space::RegionSpace::kRegionSize,
4246 grow))) {
Wessam Hassaneinb5a10be2020-11-11 16:42:52 -08004247 size_t def_pr_tlab_size = kUsePartialTlabs
4248 ? kPartialTlabSize
4249 : gc::space::RegionSpace::kRegionSize;
4250 size_t next_pr_tlab_size = JHPCalculateNextTlabSize(self,
4251 def_pr_tlab_size,
4252 alloc_size,
4253 &take_sample,
4254 &bytes_until_sample);
Mathieu Chartier6bc77742017-04-18 17:46:23 -07004255 const size_t new_tlab_size = kUsePartialTlabs
Wessam Hassaneinb5a10be2020-11-11 16:42:52 -08004256 ? std::max(alloc_size, next_pr_tlab_size)
4257 : next_pr_tlab_size;
Mathieu Chartier5ace2012016-11-30 10:15:41 -08004258 // Try to allocate a tlab.
Lokesh Gidra4f9d62b2020-01-06 15:06:04 -08004259 if (!region_space_->AllocNewTlab(self, new_tlab_size, bytes_tl_bulk_allocated)) {
Mathieu Chartier5ace2012016-11-30 10:15:41 -08004260 // Failed to allocate a tlab. Try non-tlab.
Wessam Hassaneinb5a10be2020-11-11 16:42:52 -08004261 ret = region_space_->AllocNonvirtual<false>(alloc_size,
4262 bytes_allocated,
4263 usable_size,
4264 bytes_tl_bulk_allocated);
4265 JHPCheckNonTlabSampleAllocation(self, ret, alloc_size);
4266 return ret;
Mathieu Chartier5ace2012016-11-30 10:15:41 -08004267 }
Mathieu Chartier5ace2012016-11-30 10:15:41 -08004268 // Fall-through to using the TLAB below.
4269 } else {
4270 // Check OOME for a non-tlab allocation.
4271 if (!IsOutOfMemoryOnAllocation(allocator_type, alloc_size, grow)) {
Wessam Hassaneinb5a10be2020-11-11 16:42:52 -08004272 ret = region_space_->AllocNonvirtual<false>(alloc_size,
4273 bytes_allocated,
4274 usable_size,
4275 bytes_tl_bulk_allocated);
4276 JHPCheckNonTlabSampleAllocation(self, ret, alloc_size);
4277 return ret;
Mathieu Chartier5ace2012016-11-30 10:15:41 -08004278 }
4279 // Neither tlab or non-tlab works. Give up.
4280 return nullptr;
4281 }
4282 } else {
4283 // Large. Check OOME.
4284 if (LIKELY(!IsOutOfMemoryOnAllocation(allocator_type, alloc_size, grow))) {
Wessam Hassaneinb5a10be2020-11-11 16:42:52 -08004285 ret = region_space_->AllocNonvirtual<false>(alloc_size,
4286 bytes_allocated,
4287 usable_size,
4288 bytes_tl_bulk_allocated);
4289 JHPCheckNonTlabSampleAllocation(self, ret, alloc_size);
4290 return ret;
Mathieu Chartier5ace2012016-11-30 10:15:41 -08004291 }
4292 return nullptr;
4293 }
4294 }
4295 // Refilled TLAB, return.
Wessam Hassaneinb5a10be2020-11-11 16:42:52 -08004296 ret = self->AllocTlab(alloc_size);
Mathieu Chartier5ace2012016-11-30 10:15:41 -08004297 DCHECK(ret != nullptr);
4298 *bytes_allocated = alloc_size;
4299 *usable_size = alloc_size;
Wessam Hassaneinb5a10be2020-11-11 16:42:52 -08004300
4301 // JavaHeapProfiler: Send the thread information about this allocation in case a sample is
4302 // requested.
4303 // This is the fallthrough from both the if and else if above cases => Cases that use TLAB.
4304 if (CheckPerfettoJHPEnabled()) {
4305 if (take_sample) {
4306 GetHeapSampler().ReportSample(ret, alloc_size);
4307 // Update the bytes_until_sample now that the allocation is already done.
4308 GetHeapSampler().SetBytesUntilSample(bytes_until_sample);
4309 }
4310 VLOG(heap) << "JHP:Fallthrough Tlab allocation";
4311 }
4312
Mathieu Chartier5ace2012016-11-30 10:15:41 -08004313 return ret;
4314}
4315
Mathieu Chartier1ca68902017-04-18 11:26:22 -07004316const Verification* Heap::GetVerification() const {
4317 return verification_.get();
4318}
4319
Hans Boehmc220f982018-10-12 16:15:45 -07004320void Heap::VlogHeapGrowth(size_t old_footprint, size_t new_footprint, size_t alloc_size) {
4321 VLOG(heap) << "Growing heap from " << PrettySize(old_footprint) << " to "
Andreas Gampe170331f2017-12-07 18:41:03 -08004322 << PrettySize(new_footprint) << " for a " << PrettySize(alloc_size) << " allocation";
4323}
4324
Mathieu Chartiera98a2822017-05-24 16:14:10 -07004325class Heap::TriggerPostForkCCGcTask : public HeapTask {
4326 public:
4327 explicit TriggerPostForkCCGcTask(uint64_t target_time) : HeapTask(target_time) {}
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01004328 void Run(Thread* self) override {
Mathieu Chartiera98a2822017-05-24 16:14:10 -07004329 gc::Heap* heap = Runtime::Current()->GetHeap();
Hans Boehmfb8b4e22018-09-05 16:45:42 -07004330 // Trigger a GC, if not already done. The first GC after fork, whenever it
Mathieu Chartiera98a2822017-05-24 16:14:10 -07004331 // takes place, will adjust the thresholds to normal levels.
Hans Boehmc220f982018-10-12 16:15:45 -07004332 if (heap->target_footprint_.load(std::memory_order_relaxed) == heap->growth_limit_) {
Mathieu Chartiera98a2822017-05-24 16:14:10 -07004333 heap->RequestConcurrentGC(self, kGcCauseBackground, false);
4334 }
4335 }
4336};
4337
4338void Heap::PostForkChildAction(Thread* self) {
Hans Boehmc220f982018-10-12 16:15:45 -07004339 // Temporarily increase target_footprint_ and concurrent_start_bytes_ to
Mathieu Chartiera98a2822017-05-24 16:14:10 -07004340 // max values to avoid GC during app launch.
4341 if (collector_type_ == kCollectorTypeCC && !IsLowMemoryMode()) {
Hans Boehmc220f982018-10-12 16:15:45 -07004342 // Set target_footprint_ to the largest allowed value.
Mathieu Chartiera98a2822017-05-24 16:14:10 -07004343 SetIdealFootprint(growth_limit_);
4344 // Set concurrent_start_bytes_ to half of the heap size.
Hans Boehmc220f982018-10-12 16:15:45 -07004345 size_t target_footprint = target_footprint_.load(std::memory_order_relaxed);
4346 concurrent_start_bytes_ = std::max(target_footprint / 2, GetBytesAllocated());
Mathieu Chartiera98a2822017-05-24 16:14:10 -07004347
4348 GetTaskProcessor()->AddTask(
4349 self, new TriggerPostForkCCGcTask(NanoTime() + MsToNs(kPostForkMaxHeapDurationMS)));
4350 }
4351}
4352
Alex Lightc18eba32019-09-24 14:36:27 -07004353void Heap::VisitReflectiveTargets(ReflectiveValueVisitor *visit) {
4354 VisitObjectsPaused([&visit](mirror::Object* ref) NO_THREAD_SAFETY_ANALYSIS {
4355 art::ObjPtr<mirror::Class> klass(ref->GetClass());
4356 // All these classes are in the BootstrapClassLoader.
4357 if (!klass->IsBootStrapClassLoaded()) {
4358 return;
4359 }
4360 if (GetClassRoot<mirror::Method>()->IsAssignableFrom(klass) ||
4361 GetClassRoot<mirror::Constructor>()->IsAssignableFrom(klass)) {
4362 down_cast<mirror::Executable*>(ref)->VisitTarget(visit);
4363 } else if (art::GetClassRoot<art::mirror::Field>() == klass) {
4364 down_cast<mirror::Field*>(ref)->VisitTarget(visit);
4365 } else if (art::GetClassRoot<art::mirror::MethodHandle>()->IsAssignableFrom(klass)) {
4366 down_cast<mirror::MethodHandle*>(ref)->VisitTarget(visit);
4367 } else if (art::GetClassRoot<art::mirror::FieldVarHandle>()->IsAssignableFrom(klass)) {
4368 down_cast<mirror::FieldVarHandle*>(ref)->VisitTarget(visit);
4369 } else if (art::GetClassRoot<art::mirror::DexCache>()->IsAssignableFrom(klass)) {
4370 down_cast<mirror::DexCache*>(ref)->VisitReflectiveTargets(visit);
4371 }
4372 });
4373}
4374
Mathieu Chartierad390fa2019-10-16 20:03:00 -07004375bool Heap::AddHeapTask(gc::HeapTask* task) {
4376 Thread* const self = Thread::Current();
4377 if (!CanAddHeapTask(self)) {
4378 return false;
4379 }
4380 GetTaskProcessor()->AddTask(self, task);
4381 return true;
4382}
4383
Ian Rogers1d54e732013-05-02 21:10:01 -07004384} // namespace gc
Carl Shapiro69759ea2011-07-21 18:13:35 -07004385} // namespace art