Reduce memory lost by ArenaAllocator for large allocations.
When allocating from a new arena, check if the old arena has
more remaining space than the new one after the current
allocation. If so, keep using the old arena to reduce the
amount of "lost" arena memory. This can happen when we try
to allocate more than half the default arena size. If the
allocation exceeds the default arena size, it's very likely
to happen even though the ArenaPool could still provide some
much larger previously allocated arena.
Also avoid artithmetic overflow when checking if the
request can be satisfied from the current arena.
And abort immediately if calloc() fails.
Bug: 28173563
Bug: 28256882
Change-Id: I1b4bda5d3f32ecd95fbd11addd1f0ca6dcc33e45
diff --git a/runtime/base/arena_allocator.h b/runtime/base/arena_allocator.h
index 52a1002..4b745f0 100644
--- a/runtime/base/arena_allocator.h
+++ b/runtime/base/arena_allocator.h
@@ -234,6 +234,8 @@
friend class ScopedArenaAllocator;
template <bool kCount> friend class ArenaAllocatorStatsImpl;
+ friend class ArenaAllocatorTest;
+
private:
DISALLOW_COPY_AND_ASSIGN(Arena);
};
@@ -303,14 +305,10 @@
return AllocWithMemoryTool(bytes, kind);
}
bytes = RoundUp(bytes, kAlignment);
- if (UNLIKELY(ptr_ + bytes > end_)) {
- // Obtain a new block.
- ObtainNewArenaForAllocation(bytes);
- if (UNLIKELY(ptr_ == nullptr)) {
- return nullptr;
- }
- }
ArenaAllocatorStats::RecordAlloc(bytes, kind);
+ if (UNLIKELY(bytes > static_cast<size_t>(end_ - ptr_))) {
+ return AllocFromNewArena(bytes);
+ }
uint8_t* ret = ptr_;
ptr_ += bytes;
return ret;
@@ -350,10 +348,6 @@
return static_cast<T*>(Alloc(length * sizeof(T), kind));
}
- void* AllocWithMemoryTool(size_t bytes, ArenaAllocKind kind);
-
- void ObtainNewArenaForAllocation(size_t allocation_size);
-
size_t BytesAllocated() const;
MemStats GetMemStats() const;
@@ -369,6 +363,9 @@
bool Contains(const void* ptr) const;
private:
+ void* AllocWithMemoryTool(size_t bytes, ArenaAllocKind kind);
+ void* AllocFromNewArena(size_t bytes);
+
static constexpr size_t kAlignment = 8;
void UpdateBytesAllocated();
@@ -382,6 +379,8 @@
template <typename U>
friend class ArenaAllocatorAdapter;
+ friend class ArenaAllocatorTest;
+
DISALLOW_COPY_AND_ASSIGN(ArenaAllocator);
}; // ArenaAllocator