blob: 4d5ce933aed422ff0a5d4c13b9df86716f9eb547 [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 "space.h"
Carl Shapiro69759ea2011-07-21 18:13:35 -070018
Elliott Hughes90a33692011-08-30 13:27:07 -070019#include "UniquePtr.h"
Ian Rogers30fab402012-01-23 15:43:46 -080020#include "dlmalloc.h"
Brian Carlstrom4a289ed2011-08-16 17:17:49 -070021#include "file.h"
22#include "image.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070023#include "logging.h"
Brian Carlstrom4a289ed2011-08-16 17:17:49 -070024#include "os.h"
Mathieu Chartiercc236d72012-07-20 10:29:05 -070025#include "space_bitmap.h"
Mathieu Chartierb062fdd2012-07-03 09:51:48 -070026#include "stl_util.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070027#include "utils.h"
Carl Shapiro69759ea2011-07-21 18:13:35 -070028
29namespace art {
30
Mathieu Chartier8e9a1492012-10-04 12:25:40 -070031// Magic padding value that we use to check for buffer overruns.
32static const word kPaddingValue = 0xBAC0BAC0;
Ian Rogers30fab402012-01-23 15:43:46 -080033
Mathieu Chartier2fde5332012-09-14 14:51:54 -070034// TODO: Remove define macro
Ian Rogers30fab402012-01-23 15:43:46 -080035#define CHECK_MEMORY_CALL(call, args, what) \
36 do { \
37 int rc = call args; \
38 if (UNLIKELY(rc != 0)) { \
39 errno = rc; \
40 PLOG(FATAL) << # call << " failed for " << what; \
41 } \
42 } while (false)
43
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -070044ImageSpace* Space::AsImageSpace() {
45 DCHECK_EQ(GetType(), kSpaceTypeImageSpace);
46 return down_cast<ImageSpace*>(down_cast<MemMapSpace*>(this));
47}
Mathieu Chartier2fde5332012-09-14 14:51:54 -070048
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -070049DlMallocSpace* Space::AsAllocSpace() {
50 DCHECK_EQ(GetType(), kSpaceTypeAllocSpace);
51 return down_cast<DlMallocSpace*>(down_cast<MemMapSpace*>(this));
52}
53
54DlMallocSpace* Space::AsZygoteSpace() {
55 DCHECK_EQ(GetType(), kSpaceTypeZygoteSpace);
56 return down_cast<DlMallocSpace*>(down_cast<MemMapSpace*>(this));
57}
58
59LargeObjectSpace* Space::AsLargeObjectSpace() {
60 DCHECK_EQ(GetType(), kSpaceTypeLargeObjectSpace);
61 return reinterpret_cast<LargeObjectSpace*>(this);
Mathieu Chartier2fde5332012-09-14 14:51:54 -070062}
63
64ContinuousSpace::ContinuousSpace(const std::string& name, byte* begin, byte* end,
65 GcRetentionPolicy gc_retention_policy)
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -070066 : name_(name), gc_retention_policy_(gc_retention_policy), begin_(begin), end_(end) {
67
68}
69
70DiscontinuousSpace::DiscontinuousSpace(const std::string& name,
71 GcRetentionPolicy gc_retention_policy)
72 : name_(name), gc_retention_policy_(gc_retention_policy) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -070073
74}
75
76MemMapSpace::MemMapSpace(const std::string& name, MemMap* mem_map, size_t initial_size,
77 GcRetentionPolicy gc_retention_policy)
78 : ContinuousSpace(name, mem_map->Begin(), mem_map->Begin() + initial_size, gc_retention_policy),
79 mem_map_(mem_map)
80{
81
82}
83
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -070084size_t DlMallocSpace::bitmap_index_ = 0;
Mathieu Chartierb062fdd2012-07-03 09:51:48 -070085
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -070086DlMallocSpace::DlMallocSpace(const std::string& name, MemMap* mem_map, void* mspace, byte* begin,
Mathieu Chartier2fde5332012-09-14 14:51:54 -070087 byte* end, size_t growth_limit)
Mathieu Chartier7469ebf2012-09-24 16:28:36 -070088 : MemMapSpace(name, mem_map, end - begin, kGcRetentionPolicyAlwaysCollect),
Mathieu Chartier155dfe92012-10-09 14:24:49 -070089 num_bytes_allocated_(0), num_objects_allocated_(0), total_bytes_allocated_(0),
90 total_objects_allocated_(0), lock_("allocation space lock", kAllocSpaceLock), mspace_(mspace),
Ian Rogers15bf2d32012-08-28 17:33:04 -070091 growth_limit_(growth_limit) {
Mathieu Chartierb062fdd2012-07-03 09:51:48 -070092 CHECK(mspace != NULL);
93
94 size_t bitmap_index = bitmap_index_++;
95
Mathieu Chartier7469ebf2012-09-24 16:28:36 -070096 static const uintptr_t kGcCardSize = static_cast<uintptr_t>(CardTable::kCardSize);
Mathieu Chartier2fde5332012-09-14 14:51:54 -070097 CHECK(reinterpret_cast<uintptr_t>(mem_map->Begin()) % kGcCardSize == 0);
98 CHECK(reinterpret_cast<uintptr_t>(mem_map->End()) % kGcCardSize == 0);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -070099 live_bitmap_.reset(SpaceBitmap::Create(
100 StringPrintf("allocspace-%s-live-bitmap-%d", name.c_str(), static_cast<int>(bitmap_index)),
101 Begin(), Capacity()));
102 DCHECK(live_bitmap_.get() != NULL) << "could not create allocspace live bitmap #" << bitmap_index;
103
104 mark_bitmap_.reset(SpaceBitmap::Create(
105 StringPrintf("allocspace-%s-mark-bitmap-%d", name.c_str(), static_cast<int>(bitmap_index)),
106 Begin(), Capacity()));
107 DCHECK(live_bitmap_.get() != NULL) << "could not create allocspace mark bitmap #" << bitmap_index;
108}
109
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700110DlMallocSpace* DlMallocSpace::Create(const std::string& name, size_t initial_size, size_t
111 growth_limit, size_t capacity, byte* requested_begin) {
Ian Rogers3bb17a62012-01-27 23:56:44 -0800112 // Memory we promise to dlmalloc before it asks for morecore.
113 // Note: making this value large means that large allocations are unlikely to succeed as dlmalloc
114 // will ask for this memory from sys_alloc which will fail as the footprint (this value plus the
115 // size of the large allocation) will be greater than the footprint limit.
116 size_t starting_size = kPageSize;
Ian Rogers30fab402012-01-23 15:43:46 -0800117 uint64_t start_time = 0;
118 if (VLOG_IS_ON(heap) || VLOG_IS_ON(startup)) {
119 start_time = NanoTime();
120 VLOG(startup) << "Space::CreateAllocSpace entering " << name
Ian Rogers3bb17a62012-01-27 23:56:44 -0800121 << " initial_size=" << PrettySize(initial_size)
122 << " growth_limit=" << PrettySize(growth_limit)
123 << " capacity=" << PrettySize(capacity)
Ian Rogers30fab402012-01-23 15:43:46 -0800124 << " requested_begin=" << reinterpret_cast<void*>(requested_begin);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700125 }
Ian Rogers30fab402012-01-23 15:43:46 -0800126
127 // Sanity check arguments
Ian Rogers3bb17a62012-01-27 23:56:44 -0800128 if (starting_size > initial_size) {
129 initial_size = starting_size;
130 }
Ian Rogers30fab402012-01-23 15:43:46 -0800131 if (initial_size > growth_limit) {
132 LOG(ERROR) << "Failed to create alloc space (" << name << ") where the initial size ("
Ian Rogers3bb17a62012-01-27 23:56:44 -0800133 << PrettySize(initial_size) << ") is larger than its capacity ("
134 << PrettySize(growth_limit) << ")";
Ian Rogers30fab402012-01-23 15:43:46 -0800135 return NULL;
136 }
137 if (growth_limit > capacity) {
Ian Rogers3bb17a62012-01-27 23:56:44 -0800138 LOG(ERROR) << "Failed to create alloc space (" << name << ") where the growth limit capacity ("
139 << PrettySize(growth_limit) << ") is larger than the capacity ("
140 << PrettySize(capacity) << ")";
Ian Rogers30fab402012-01-23 15:43:46 -0800141 return NULL;
142 }
143
144 // Page align growth limit and capacity which will be used to manage mmapped storage
145 growth_limit = RoundUp(growth_limit, kPageSize);
146 capacity = RoundUp(capacity, kPageSize);
147
148 UniquePtr<MemMap> mem_map(MemMap::MapAnonymous(name.c_str(), requested_begin,
149 capacity, PROT_READ | PROT_WRITE));
150 if (mem_map.get() == NULL) {
151 LOG(ERROR) << "Failed to allocate pages for alloc space (" << name << ") of size "
Ian Rogers3bb17a62012-01-27 23:56:44 -0800152 << PrettySize(capacity);
Ian Rogers30fab402012-01-23 15:43:46 -0800153 return NULL;
154 }
155
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700156 void* mspace = CreateMallocSpace(mem_map->Begin(), starting_size, initial_size);
Ian Rogers30fab402012-01-23 15:43:46 -0800157 if (mspace == NULL) {
158 LOG(ERROR) << "Failed to initialize mspace for alloc space (" << name << ")";
159 return NULL;
160 }
161
Ian Rogers3bb17a62012-01-27 23:56:44 -0800162 // Protect memory beyond the initial size.
163 byte* end = mem_map->Begin() + starting_size;
Ian Rogers30fab402012-01-23 15:43:46 -0800164 if (capacity - initial_size > 0) {
165 CHECK_MEMORY_CALL(mprotect, (end, capacity - initial_size, PROT_NONE), name);
166 }
167
168 // Everything is set so record in immutable structure and leave
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700169 MemMap* mem_map_ptr = mem_map.release();
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700170 DlMallocSpace* space = new DlMallocSpace(name, mem_map_ptr, mspace, mem_map_ptr->Begin(), end,
171 growth_limit);
Ian Rogers30fab402012-01-23 15:43:46 -0800172 if (VLOG_IS_ON(heap) || VLOG_IS_ON(startup)) {
Ian Rogers3bb17a62012-01-27 23:56:44 -0800173 LOG(INFO) << "Space::CreateAllocSpace exiting (" << PrettyDuration(NanoTime() - start_time)
174 << " ) " << *space;
Ian Rogers30fab402012-01-23 15:43:46 -0800175 }
176 return space;
Carl Shapiro69759ea2011-07-21 18:13:35 -0700177}
178
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700179void* DlMallocSpace::CreateMallocSpace(void* begin, size_t morecore_start, size_t initial_size) {
Ian Rogers30fab402012-01-23 15:43:46 -0800180 // clear errno to allow PLOG on error
Carl Shapiro69759ea2011-07-21 18:13:35 -0700181 errno = 0;
Ian Rogers3bb17a62012-01-27 23:56:44 -0800182 // create mspace using our backing storage starting at begin and with a footprint of
183 // morecore_start. Don't use an internal dlmalloc lock (as we already hold heap lock). When
184 // morecore_start bytes of memory is exhaused morecore will be called.
185 void* msp = create_mspace_with_base(begin, morecore_start, false /*locked*/);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700186 if (msp != NULL) {
Ian Rogers30fab402012-01-23 15:43:46 -0800187 // Do not allow morecore requests to succeed beyond the initial size of the heap
Ian Rogers3bb17a62012-01-27 23:56:44 -0800188 mspace_set_footprint_limit(msp, initial_size);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700189 } else {
Ian Rogers30fab402012-01-23 15:43:46 -0800190 PLOG(ERROR) << "create_mspace_with_base failed";
Carl Shapiro69759ea2011-07-21 18:13:35 -0700191 }
192 return msp;
193}
194
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700195void DlMallocSpace::SwapBitmaps() {
Mathieu Chartier654d3a22012-07-11 17:54:18 -0700196 SpaceBitmap* temp_live_bitmap = live_bitmap_.release();
197 live_bitmap_.reset(mark_bitmap_.release());
198 mark_bitmap_.reset(temp_live_bitmap);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700199 // Swap names to get more descriptive diagnostics.
200 std::string temp_name = live_bitmap_->GetName();
201 live_bitmap_->SetName(mark_bitmap_->GetName());
202 mark_bitmap_->SetName(temp_name);
Mathieu Chartier654d3a22012-07-11 17:54:18 -0700203}
204
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700205Object* DlMallocSpace::AllocWithoutGrowthLocked(size_t num_bytes) {
Mathieu Chartier8e9a1492012-10-04 12:25:40 -0700206 if (kDebugSpaces) {
207 num_bytes += sizeof(word);
208 }
209
Ian Rogers30fab402012-01-23 15:43:46 -0800210 Object* result = reinterpret_cast<Object*>(mspace_calloc(mspace_, 1, num_bytes));
Mathieu Chartier8e9a1492012-10-04 12:25:40 -0700211 if (kDebugSpaces && result != NULL) {
Ian Rogers30fab402012-01-23 15:43:46 -0800212 CHECK(Contains(result)) << "Allocation (" << reinterpret_cast<void*>(result)
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700213 << ") not in bounds of allocation space " << *this;
Mathieu Chartier8e9a1492012-10-04 12:25:40 -0700214 // Put a magic pattern before and after the allocation.
215 *reinterpret_cast<word*>(reinterpret_cast<byte*>(result) + AllocationSize(result)
216 - sizeof(word) - kChunkOverhead) = kPaddingValue;
jeffhaoc1160702011-10-27 15:48:45 -0700217 }
Mathieu Chartier155dfe92012-10-09 14:24:49 -0700218 size_t allocation_size = AllocationSize(result);
219 num_bytes_allocated_ += allocation_size;
220 total_bytes_allocated_ += allocation_size;
221 ++total_objects_allocated_;
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700222 ++num_objects_allocated_;
Ian Rogers30fab402012-01-23 15:43:46 -0800223 return result;
Brian Carlstrom4a289ed2011-08-16 17:17:49 -0700224}
225
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700226Object* DlMallocSpace::Alloc(Thread* self, size_t num_bytes) {
Ian Rogers50b35e22012-10-04 10:09:15 -0700227 MutexLock mu(self, lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700228 return AllocWithoutGrowthLocked(num_bytes);
229}
230
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700231Object* DlMallocSpace::AllocWithGrowth(Thread* self, size_t num_bytes) {
Ian Rogers50b35e22012-10-04 10:09:15 -0700232 MutexLock mu(self, lock_);
Ian Rogers30fab402012-01-23 15:43:46 -0800233 // Grow as much as possible within the mspace.
234 size_t max_allowed = Capacity();
235 mspace_set_footprint_limit(mspace_, max_allowed);
236 // Try the allocation.
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700237 Object* result = AllocWithoutGrowthLocked(num_bytes);
Ian Rogers30fab402012-01-23 15:43:46 -0800238 // Shrink back down as small as possible.
239 size_t footprint = mspace_footprint(mspace_);
240 mspace_set_footprint_limit(mspace_, footprint);
241 // Return the new allocation or NULL.
Mathieu Chartier8e9a1492012-10-04 12:25:40 -0700242 CHECK(!kDebugSpaces || result == NULL || Contains(result));
Ian Rogers30fab402012-01-23 15:43:46 -0800243 return result;
Brian Carlstrom4a289ed2011-08-16 17:17:49 -0700244}
245
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700246void DlMallocSpace::SetGrowthLimit(size_t growth_limit) {
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700247 growth_limit = RoundUp(growth_limit, kPageSize);
248 growth_limit_ = growth_limit;
249 if (Size() > growth_limit_) {
250 end_ = begin_ + growth_limit;
251 }
252}
253
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700254DlMallocSpace* DlMallocSpace::CreateZygoteSpace() {
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700255 end_ = reinterpret_cast<byte*>(RoundUp(reinterpret_cast<uintptr_t>(end_), kPageSize));
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700256 DCHECK(IsAligned<CardTable::kCardSize>(begin_));
257 DCHECK(IsAligned<CardTable::kCardSize>(end_));
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700258 DCHECK(IsAligned<kPageSize>(begin_));
259 DCHECK(IsAligned<kPageSize>(end_));
260 size_t size = RoundUp(Size(), kPageSize);
261 // Trim the heap so that we minimize the size of the Zygote space.
262 Trim();
263 // Trim our mem-map to free unused pages.
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700264 GetMemMap()->UnMapAtEnd(end_);
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700265 // TODO: Not hardcode these in?
266 const size_t starting_size = kPageSize;
267 const size_t initial_size = 2 * MB;
268 // Remaining size is for the new alloc space.
269 const size_t growth_limit = growth_limit_ - size;
270 const size_t capacity = Capacity() - size;
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700271 VLOG(heap) << "Begin " << reinterpret_cast<const void*>(begin_) << "\n"
272 << "End " << reinterpret_cast<const void*>(end_) << "\n"
273 << "Size " << size << "\n"
274 << "GrowthLimit " << growth_limit_ << "\n"
275 << "Capacity " << Capacity();
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700276 SetGrowthLimit(RoundUp(size, kPageSize));
277 SetFootprintLimit(RoundUp(size, kPageSize));
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700278 // FIXME: Do we need reference counted pointers here?
279 // Make the two spaces share the same mark bitmaps since the bitmaps span both of the spaces.
Mathieu Chartierdcf8d722012-08-02 14:55:54 -0700280 VLOG(heap) << "Creating new AllocSpace: ";
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700281 VLOG(heap) << "Size " << GetMemMap()->Size();
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700282 VLOG(heap) << "GrowthLimit " << PrettySize(growth_limit);
283 VLOG(heap) << "Capacity " << PrettySize(capacity);
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700284 UniquePtr<MemMap> mem_map(MemMap::MapAnonymous(GetName().c_str(), End(), capacity, PROT_READ | PROT_WRITE));
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700285 void* mspace = CreateMallocSpace(end_, starting_size, initial_size);
286 // Protect memory beyond the initial size.
287 byte* end = mem_map->Begin() + starting_size;
288 if (capacity - initial_size > 0) {
289 CHECK_MEMORY_CALL(mprotect, (end, capacity - initial_size, PROT_NONE), name_.c_str());
290 }
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700291 DlMallocSpace* alloc_space =
292 new DlMallocSpace(name_, mem_map.release(), mspace, end_, end, growth_limit);
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700293 live_bitmap_->SetHeapLimit(reinterpret_cast<uintptr_t>(End()));
294 CHECK_EQ(live_bitmap_->HeapLimit(), reinterpret_cast<uintptr_t>(End()));
295 mark_bitmap_->SetHeapLimit(reinterpret_cast<uintptr_t>(End()));
296 CHECK_EQ(mark_bitmap_->HeapLimit(), reinterpret_cast<uintptr_t>(End()));
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700297 name_ += "-zygote-transformed";
298 VLOG(heap) << "zygote space creation done";
299 return alloc_space;
300}
301
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700302size_t DlMallocSpace::Free(Thread* self, Object* ptr) {
Ian Rogers50b35e22012-10-04 10:09:15 -0700303 MutexLock mu(self, lock_);
Mathieu Chartier8e9a1492012-10-04 12:25:40 -0700304 if (kDebugSpaces) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700305 CHECK(ptr != NULL);
306 CHECK(Contains(ptr)) << "Free (" << ptr << ") not in bounds of heap " << *this;
Mathieu Chartier8e9a1492012-10-04 12:25:40 -0700307 CHECK_EQ(
308 *reinterpret_cast<word*>(reinterpret_cast<byte*>(ptr) + AllocationSize(ptr) -
309 sizeof(word) - kChunkOverhead), kPaddingValue);
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700310 }
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700311 const size_t bytes_freed = AllocationSize(ptr);
312 num_bytes_allocated_ -= bytes_freed;
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700313 --num_objects_allocated_;
Ian Rogers30fab402012-01-23 15:43:46 -0800314 mspace_free(mspace_, ptr);
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700315 return bytes_freed;
Ian Rogers30fab402012-01-23 15:43:46 -0800316}
317
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700318size_t DlMallocSpace::FreeList(Thread* self, size_t num_ptrs, Object** ptrs) {
319 // Don't need the lock to calculate the size of the freed pointers.
320 size_t bytes_freed = 0;
321 for (size_t i = 0; i < num_ptrs; i++) {
322 bytes_freed += AllocationSize(ptrs[i]);
323 }
324
Ian Rogers50b35e22012-10-04 10:09:15 -0700325 MutexLock mu(self, lock_);
Mathieu Chartier8e9a1492012-10-04 12:25:40 -0700326 if (kDebugSpaces) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700327 CHECK(ptrs != NULL);
328 size_t num_broken_ptrs = 0;
329 for (size_t i = 0; i < num_ptrs; i++) {
330 if (!Contains(ptrs[i])) {
331 num_broken_ptrs++;
332 LOG(ERROR) << "FreeList[" << i << "] (" << ptrs[i] << ") not in bounds of heap " << *this;
333 } else {
334 size_t size = mspace_usable_size(ptrs[i]);
335 memset(ptrs[i], 0xEF, size);
336 }
Ian Rogers30fab402012-01-23 15:43:46 -0800337 }
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700338 CHECK_EQ(num_broken_ptrs, 0u);
Ian Rogers30fab402012-01-23 15:43:46 -0800339 }
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700340 num_bytes_allocated_ -= bytes_freed;
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700341 num_objects_allocated_ -= num_ptrs;
Ian Rogers30fab402012-01-23 15:43:46 -0800342 mspace_bulk_free(mspace_, reinterpret_cast<void**>(ptrs), num_ptrs);
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700343 return bytes_freed;
Ian Rogers30fab402012-01-23 15:43:46 -0800344}
345
346// Callback from dlmalloc when it needs to increase the footprint
347extern "C" void* art_heap_morecore(void* mspace, intptr_t increment) {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800348 Heap* heap = Runtime::Current()->GetHeap();
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700349 DCHECK_EQ(heap->GetAllocSpace()->GetMspace(), mspace);
350 return heap->GetAllocSpace()->MoreCore(increment);
Ian Rogers30fab402012-01-23 15:43:46 -0800351}
352
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700353void* DlMallocSpace::MoreCore(intptr_t increment) {
Ian Rogers50b35e22012-10-04 10:09:15 -0700354 lock_.AssertHeld(Thread::Current());
Ian Rogers30fab402012-01-23 15:43:46 -0800355 byte* original_end = end_;
356 if (increment != 0) {
Ian Rogers3bb17a62012-01-27 23:56:44 -0800357 VLOG(heap) << "AllocSpace::MoreCore " << PrettySize(increment);
Ian Rogers30fab402012-01-23 15:43:46 -0800358 byte* new_end = original_end + increment;
359 if (increment > 0) {
360#if DEBUG_SPACES
361 // Should never be asked to increase the allocation beyond the capacity of the space. Enforced
362 // by mspace_set_footprint_limit.
363 CHECK_LE(new_end, Begin() + Capacity());
364#endif
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700365 CHECK_MEMORY_CALL(mprotect, (original_end, increment, PROT_READ | PROT_WRITE), GetName());
Ian Rogers30fab402012-01-23 15:43:46 -0800366 } else {
367#if DEBUG_SPACES
368 // Should never be asked for negative footprint (ie before begin)
369 CHECK_GT(original_end + increment, Begin());
370#endif
371 // Advise we don't need the pages and protect them
Ian Rogers3bb17a62012-01-27 23:56:44 -0800372 // TODO: by removing permissions to the pages we may be causing TLB shoot-down which can be
373 // expensive (note the same isn't true for giving permissions to a page as the protected
374 // page shouldn't be in a TLB). We should investigate performance impact of just
375 // removing ignoring the memory protection change here and in Space::CreateAllocSpace. It's
376 // likely just a useful debug feature.
Ian Rogers30fab402012-01-23 15:43:46 -0800377 size_t size = -increment;
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700378 CHECK_MEMORY_CALL(madvise, (new_end, size, MADV_DONTNEED), GetName());
379 CHECK_MEMORY_CALL(mprotect, (new_end, size, PROT_NONE), GetName());
Ian Rogers30fab402012-01-23 15:43:46 -0800380 }
381 // Update end_
382 end_ = new_end;
383 }
384 return original_end;
385}
386
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700387size_t DlMallocSpace::AllocationSize(const Object* obj) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700388 return mspace_usable_size(const_cast<void*>(reinterpret_cast<const void*>(obj))) +
389 kChunkOverhead;
Ian Rogers30fab402012-01-23 15:43:46 -0800390}
391
Brian Carlstromb18e77a2012-08-21 14:20:03 -0700392void MspaceMadviseCallback(void* start, void* end, size_t used_bytes, void* /* arg */) {
393 // Is this chunk in use?
394 if (used_bytes != 0) {
395 return;
396 }
Elliott Hughes9eebd3b2012-06-08 13:56:31 -0700397 // Do we have any whole pages to give back?
398 start = reinterpret_cast<void*>(RoundUp(reinterpret_cast<uintptr_t>(start), kPageSize));
399 end = reinterpret_cast<void*>(RoundDown(reinterpret_cast<uintptr_t>(end), kPageSize));
400 if (end > start) {
401 size_t length = reinterpret_cast<byte*>(end) - reinterpret_cast<byte*>(start);
402 CHECK_MEMORY_CALL(madvise, (start, length, MADV_DONTNEED), "trim");
Ian Rogers30fab402012-01-23 15:43:46 -0800403 }
404}
405
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700406void DlMallocSpace::Trim() {
Ian Rogers50b35e22012-10-04 10:09:15 -0700407 MutexLock mu(Thread::Current(), lock_);
Elliott Hughes9eebd3b2012-06-08 13:56:31 -0700408 // Trim to release memory at the end of the space.
409 mspace_trim(mspace_, 0);
410 // Visit space looking for page-sized holes to advise the kernel we don't need.
411 mspace_inspect_all(mspace_, MspaceMadviseCallback, NULL);
412}
Ian Rogers30fab402012-01-23 15:43:46 -0800413
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700414void DlMallocSpace::Walk(void(*callback)(void *start, void *end, size_t num_bytes, void* callback_arg),
Ian Rogers30fab402012-01-23 15:43:46 -0800415 void* arg) {
Ian Rogers50b35e22012-10-04 10:09:15 -0700416 MutexLock mu(Thread::Current(), lock_);
Ian Rogers30fab402012-01-23 15:43:46 -0800417 mspace_inspect_all(mspace_, callback, arg);
Ian Rogers15bf2d32012-08-28 17:33:04 -0700418 callback(NULL, NULL, 0, arg); // Indicate end of a space.
Ian Rogers30fab402012-01-23 15:43:46 -0800419}
420
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700421size_t DlMallocSpace::GetFootprintLimit() {
Ian Rogers50b35e22012-10-04 10:09:15 -0700422 MutexLock mu(Thread::Current(), lock_);
Ian Rogers30fab402012-01-23 15:43:46 -0800423 return mspace_footprint_limit(mspace_);
424}
425
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700426void DlMallocSpace::SetFootprintLimit(size_t new_size) {
Ian Rogers50b35e22012-10-04 10:09:15 -0700427 MutexLock mu(Thread::Current(), lock_);
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700428 VLOG(heap) << "DLMallocSpace::SetFootprintLimit " << PrettySize(new_size);
Ian Rogers30fab402012-01-23 15:43:46 -0800429 // Compare against the actual footprint, rather than the Size(), because the heap may not have
430 // grown all the way to the allowed size yet.
Ian Rogers30fab402012-01-23 15:43:46 -0800431 size_t current_space_size = mspace_footprint(mspace_);
432 if (new_size < current_space_size) {
433 // Don't let the space grow any more.
434 new_size = current_space_size;
435 }
436 mspace_set_footprint_limit(mspace_, new_size);
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700437 LOG(INFO) << "Setting footprint limit to " << new_size;
Ian Rogers30fab402012-01-23 15:43:46 -0800438}
439
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700440size_t ImageSpace::bitmap_index_ = 0;
441
442ImageSpace::ImageSpace(const std::string& name, MemMap* mem_map)
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700443 : MemMapSpace(name, mem_map, mem_map->Size(), kGcRetentionPolicyNeverCollect) {
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700444 const size_t bitmap_index = bitmap_index_++;
445 live_bitmap_.reset(SpaceBitmap::Create(
446 StringPrintf("imagespace-%s-live-bitmap-%d", name.c_str(), static_cast<int>(bitmap_index)),
447 Begin(), Capacity()));
448 DCHECK(live_bitmap_.get() != NULL) << "could not create imagespace live bitmap #" << bitmap_index;
449}
450
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700451ImageSpace* ImageSpace::Create(const std::string& image_file_name) {
Brian Carlstrom5643b782012-02-05 12:32:53 -0800452 CHECK(!image_file_name.empty());
Ian Rogers30fab402012-01-23 15:43:46 -0800453
454 uint64_t start_time = 0;
455 if (VLOG_IS_ON(heap) || VLOG_IS_ON(startup)) {
456 start_time = NanoTime();
457 LOG(INFO) << "Space::CreateImageSpace entering" << " image_file_name=" << image_file_name;
458 }
459
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700460 UniquePtr<File> file(OS::OpenFile(image_file_name.c_str(), false));
Elliott Hughes90a33692011-08-30 13:27:07 -0700461 if (file.get() == NULL) {
Ian Rogers30fab402012-01-23 15:43:46 -0800462 LOG(ERROR) << "Failed to open " << image_file_name;
463 return NULL;
Carl Shapiro69759ea2011-07-21 18:13:35 -0700464 }
Brian Carlstrom4a289ed2011-08-16 17:17:49 -0700465 ImageHeader image_header;
466 bool success = file->ReadFully(&image_header, sizeof(image_header));
467 if (!success || !image_header.IsValid()) {
Ian Rogers30fab402012-01-23 15:43:46 -0800468 LOG(ERROR) << "Invalid image header " << image_file_name;
469 return NULL;
Brian Carlstrom4a289ed2011-08-16 17:17:49 -0700470 }
Ian Rogers30fab402012-01-23 15:43:46 -0800471 UniquePtr<MemMap> map(MemMap::MapFileAtAddress(image_header.GetImageBegin(),
Brian Carlstrom89521892011-12-07 22:05:07 -0800472 file->Length(),
473 // TODO: selectively PROT_EXEC stubs
474 PROT_READ | PROT_WRITE | PROT_EXEC,
475 MAP_PRIVATE | MAP_FIXED,
476 file->Fd(),
477 0));
Elliott Hughes90a33692011-08-30 13:27:07 -0700478 if (map.get() == NULL) {
Ian Rogers30fab402012-01-23 15:43:46 -0800479 LOG(ERROR) << "Failed to map " << image_file_name;
480 return NULL;
Brian Carlstrom4a289ed2011-08-16 17:17:49 -0700481 }
Ian Rogers30fab402012-01-23 15:43:46 -0800482 CHECK_EQ(image_header.GetImageBegin(), map->Begin());
483 DCHECK_EQ(0, memcmp(&image_header, map->Begin(), sizeof(ImageHeader)));
Brian Carlstroma663ea52011-08-19 23:33:41 -0700484
Ian Rogers30fab402012-01-23 15:43:46 -0800485 Runtime* runtime = Runtime::Current();
Brian Carlstrom16192862011-09-12 17:50:06 -0700486 Object* jni_stub_array = image_header.GetImageRoot(ImageHeader::kJniStubArray);
Ian Rogers169c9a72011-11-13 20:13:17 -0800487 runtime->SetJniDlsymLookupStub(down_cast<ByteArray*>(jni_stub_array));
Brian Carlstrom16192862011-09-12 17:50:06 -0700488
Brian Carlstrome24fa612011-09-29 00:53:55 -0700489 Object* ame_stub_array = image_header.GetImageRoot(ImageHeader::kAbstractMethodErrorStubArray);
Ian Rogers4f0d07c2011-10-06 23:38:47 -0700490 runtime->SetAbstractMethodErrorStubArray(down_cast<ByteArray*>(ame_stub_array));
Brian Carlstrome24fa612011-09-29 00:53:55 -0700491
Ian Rogersfb6adba2012-03-04 21:51:51 -0800492 Object* resolution_stub_array =
493 image_header.GetImageRoot(ImageHeader::kStaticResolutionStubArray);
Ian Rogers4f0d07c2011-10-06 23:38:47 -0700494 runtime->SetResolutionStubArray(
Ian Rogers1cb0a1d2011-10-06 15:24:35 -0700495 down_cast<ByteArray*>(resolution_stub_array), Runtime::kStaticMethod);
496 resolution_stub_array = image_header.GetImageRoot(ImageHeader::kUnknownMethodResolutionStubArray);
Ian Rogers4f0d07c2011-10-06 23:38:47 -0700497 runtime->SetResolutionStubArray(
Ian Rogers1cb0a1d2011-10-06 15:24:35 -0700498 down_cast<ByteArray*>(resolution_stub_array), Runtime::kUnknownMethod);
Ian Rogersad25ac52011-10-04 19:13:33 -0700499
Ian Rogers19846512012-02-24 11:42:47 -0800500 Object* resolution_method = image_header.GetImageRoot(ImageHeader::kResolutionMethod);
Mathieu Chartier66f19252012-09-18 08:57:04 -0700501 runtime->SetResolutionMethod(down_cast<AbstractMethod*>(resolution_method));
Ian Rogers19846512012-02-24 11:42:47 -0800502
Ian Rogersff1ed472011-09-20 13:46:24 -0700503 Object* callee_save_method = image_header.GetImageRoot(ImageHeader::kCalleeSaveMethod);
Mathieu Chartier66f19252012-09-18 08:57:04 -0700504 runtime->SetCalleeSaveMethod(down_cast<AbstractMethod*>(callee_save_method), Runtime::kSaveAll);
Ian Rogers4f0d07c2011-10-06 23:38:47 -0700505 callee_save_method = image_header.GetImageRoot(ImageHeader::kRefsOnlySaveMethod);
Mathieu Chartier66f19252012-09-18 08:57:04 -0700506 runtime->SetCalleeSaveMethod(down_cast<AbstractMethod*>(callee_save_method), Runtime::kRefsOnly);
Ian Rogers4f0d07c2011-10-06 23:38:47 -0700507 callee_save_method = image_header.GetImageRoot(ImageHeader::kRefsAndArgsSaveMethod);
Mathieu Chartier66f19252012-09-18 08:57:04 -0700508 runtime->SetCalleeSaveMethod(down_cast<AbstractMethod*>(callee_save_method), Runtime::kRefsAndArgs);
Ian Rogersff1ed472011-09-20 13:46:24 -0700509
Ian Rogers30fab402012-01-23 15:43:46 -0800510 ImageSpace* space = new ImageSpace(image_file_name, map.release());
511 if (VLOG_IS_ON(heap) || VLOG_IS_ON(startup)) {
Ian Rogers3bb17a62012-01-27 23:56:44 -0800512 LOG(INFO) << "Space::CreateImageSpace exiting (" << PrettyDuration(NanoTime() - start_time)
513 << ") " << *space;
Ian Rogers5d76c432011-10-31 21:42:49 -0700514 }
Ian Rogers30fab402012-01-23 15:43:46 -0800515 return space;
Ian Rogers5d76c432011-10-31 21:42:49 -0700516}
517
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700518void ImageSpace::RecordImageAllocations(SpaceBitmap* live_bitmap) const {
Ian Rogers30fab402012-01-23 15:43:46 -0800519 uint64_t start_time = 0;
520 if (VLOG_IS_ON(heap) || VLOG_IS_ON(startup)) {
521 LOG(INFO) << "ImageSpace::RecordImageAllocations entering";
522 start_time = NanoTime();
Carl Shapiro69759ea2011-07-21 18:13:35 -0700523 }
Ian Rogers30fab402012-01-23 15:43:46 -0800524 DCHECK(!Runtime::Current()->IsStarted());
525 CHECK(live_bitmap != NULL);
526 byte* current = Begin() + RoundUp(sizeof(ImageHeader), kObjectAlignment);
527 byte* end = End();
528 while (current < end) {
529 DCHECK_ALIGNED(current, kObjectAlignment);
530 const Object* obj = reinterpret_cast<const Object*>(current);
531 live_bitmap->Set(obj);
532 current += RoundUp(obj->SizeOf(), kObjectAlignment);
533 }
534 if (VLOG_IS_ON(heap) || VLOG_IS_ON(startup)) {
Ian Rogers3bb17a62012-01-27 23:56:44 -0800535 LOG(INFO) << "ImageSpace::RecordImageAllocations exiting ("
536 << PrettyDuration(NanoTime() - start_time) << ")";
Carl Shapiro69759ea2011-07-21 18:13:35 -0700537 }
538}
539
Ian Rogers30fab402012-01-23 15:43:46 -0800540std::ostream& operator<<(std::ostream& os, const Space& space) {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700541 space.Dump(os);
Ian Rogers30fab402012-01-23 15:43:46 -0800542 return os;
Carl Shapiro69759ea2011-07-21 18:13:35 -0700543}
544
Mathieu Chartier1c23e1e2012-10-12 14:14:11 -0700545void DlMallocSpace::Dump(std::ostream& os) const {
Mathieu Chartier2fde5332012-09-14 14:51:54 -0700546 os << GetType()
547 << "begin=" << reinterpret_cast<void*>(Begin())
548 << ",end=" << reinterpret_cast<void*>(End())
549 << ",size=" << PrettySize(Size()) << ",capacity=" << PrettySize(Capacity())
550 << ",name=\"" << GetName() << "\"]";
551}
552
553void ImageSpace::Dump(std::ostream& os) const {
554 os << GetType()
555 << "begin=" << reinterpret_cast<void*>(Begin())
556 << ",end=" << reinterpret_cast<void*>(End())
557 << ",size=" << PrettySize(Size())
558 << ",name=\"" << GetName() << "\"]";
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700559}
560
Carl Shapiro69759ea2011-07-21 18:13:35 -0700561} // namespace art