blob: 6f30ee9875137530212ba223cd85dd1340db1552 [file] [log] [blame]
Kostya Serebryany712fc982016-06-07 01:20:26 +00001//===-- scudo_allocator.cpp -------------------------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9///
10/// Scudo Hardened Allocator implementation.
11/// It uses the sanitizer_common allocator as a base and aims at mitigating
12/// heap corruption vulnerabilities. It provides a checksum-guarded chunk
13/// header, a delayed free list, and additional sanity checks.
14///
15//===----------------------------------------------------------------------===//
16
17#include "scudo_allocator.h"
Kostya Kortchinskyb0e96eb2017-05-09 15:12:38 +000018#include "scudo_crc32.h"
Kostya Kortchinsky36b34342017-04-27 20:21:16 +000019#include "scudo_tls.h"
Kostya Serebryany712fc982016-06-07 01:20:26 +000020#include "scudo_utils.h"
21
Alex Shlyapnikov42bea012017-07-18 19:11:04 +000022#include "sanitizer_common/sanitizer_allocator_checks.h"
Kostya Serebryany712fc982016-06-07 01:20:26 +000023#include "sanitizer_common/sanitizer_allocator_interface.h"
Alex Shlyapnikovdf18cbb2017-07-14 21:17:16 +000024#include "sanitizer_common/sanitizer_errno.h"
Kostya Serebryany712fc982016-06-07 01:20:26 +000025#include "sanitizer_common/sanitizer_quarantine.h"
26
Kostya Kortchinsky006805d2017-04-20 15:11:00 +000027#include <string.h>
Kostya Serebryany712fc982016-06-07 01:20:26 +000028
29namespace __scudo {
30
Kostya Serebryany712fc982016-06-07 01:20:26 +000031// Global static cookie, initialized at start-up.
Kostya Kortchinsky1148dc52016-11-30 17:32:20 +000032static uptr Cookie;
33
Kostya Kortchinsky1148dc52016-11-30 17:32:20 +000034// We default to software CRC32 if the alternatives are not supported, either
35// at compilation or at runtime.
36static atomic_uint8_t HashAlgorithm = { CRC32Software };
37
Kostya Kortchinskyb0e96eb2017-05-09 15:12:38 +000038INLINE u32 computeCRC32(uptr Crc, uptr Value, uptr *Array, uptr ArraySize) {
39 // If the hardware CRC32 feature is defined here, it was enabled everywhere,
40 // as opposed to only for scudo_crc32.cpp. This means that other hardware
41 // specific instructions were likely emitted at other places, and as a
42 // result there is no reason to not use it here.
Kostya Kortchinskyb39dff42017-01-18 17:11:17 +000043#if defined(__SSE4_2__) || defined(__ARM_FEATURE_CRC32)
Kostya Kortchinskyb0e96eb2017-05-09 15:12:38 +000044 Crc = CRC32_INTRINSIC(Crc, Value);
45 for (uptr i = 0; i < ArraySize; i++)
46 Crc = CRC32_INTRINSIC(Crc, Array[i]);
47 return Crc;
Kostya Kortchinskyb39dff42017-01-18 17:11:17 +000048#else
Kostya Kortchinskyb0e96eb2017-05-09 15:12:38 +000049 if (atomic_load_relaxed(&HashAlgorithm) == CRC32Hardware) {
50 Crc = computeHardwareCRC32(Crc, Value);
51 for (uptr i = 0; i < ArraySize; i++)
52 Crc = computeHardwareCRC32(Crc, Array[i]);
53 return Crc;
54 }
55 Crc = computeSoftwareCRC32(Crc, Value);
56 for (uptr i = 0; i < ArraySize; i++)
57 Crc = computeSoftwareCRC32(Crc, Array[i]);
58 return Crc;
59#endif // defined(__SSE4_2__) || defined(__ARM_FEATURE_CRC32)
Kostya Kortchinsky1148dc52016-11-30 17:32:20 +000060}
Kostya Serebryany712fc982016-06-07 01:20:26 +000061
Kostya Kortchinsky36b34342017-04-27 20:21:16 +000062static ScudoBackendAllocator &getBackendAllocator();
63
Kostya Serebryany712fc982016-06-07 01:20:26 +000064struct ScudoChunk : UnpackedHeader {
65 // We can't use the offset member of the chunk itself, as we would double
66 // fetch it without any warranty that it wouldn't have been tampered. To
67 // prevent this, we work with a local copy of the header.
Kostya Kortchinsky71dcc332016-10-26 16:16:58 +000068 void *getAllocBeg(UnpackedHeader *Header) {
Kostya Serebryany712fc982016-06-07 01:20:26 +000069 return reinterpret_cast<void *>(
70 reinterpret_cast<uptr>(this) - (Header->Offset << MinAlignmentLog));
71 }
72
Kostya Kortchinsky1148dc52016-11-30 17:32:20 +000073 // Returns the usable size for a chunk, meaning the amount of bytes from the
74 // beginning of the user data to the end of the backend allocated chunk.
75 uptr getUsableSize(UnpackedHeader *Header) {
Kostya Kortchinsky01a66fc2017-05-11 21:40:45 +000076 uptr Size =
Kostya Kortchinskyb44364d2017-07-13 21:01:19 +000077 getBackendAllocator().getActuallyAllocatedSize(getAllocBeg(Header),
Kostya Kortchinsky01a66fc2017-05-11 21:40:45 +000078 Header->FromPrimary);
Kostya Kortchinsky1148dc52016-11-30 17:32:20 +000079 if (Size == 0)
Kostya Kortchinsky006805d2017-04-20 15:11:00 +000080 return 0;
Kostya Kortchinsky1148dc52016-11-30 17:32:20 +000081 return Size - AlignedChunkHeaderSize - (Header->Offset << MinAlignmentLog);
82 }
83
84 // Compute the checksum of the Chunk pointer and its ChunkHeader.
Kostya Kortchinsky71dcc332016-10-26 16:16:58 +000085 u16 computeChecksum(UnpackedHeader *Header) const {
Kostya Kortchinsky1148dc52016-11-30 17:32:20 +000086 UnpackedHeader ZeroChecksumHeader = *Header;
87 ZeroChecksumHeader.Checksum = 0;
88 uptr HeaderHolder[sizeof(UnpackedHeader) / sizeof(uptr)];
89 memcpy(&HeaderHolder, &ZeroChecksumHeader, sizeof(HeaderHolder));
Kostya Kortchinskyb0e96eb2017-05-09 15:12:38 +000090 u32 Crc = computeCRC32(Cookie, reinterpret_cast<uptr>(this), HeaderHolder,
91 ARRAY_SIZE(HeaderHolder));
Kostya Kortchinskyb39dff42017-01-18 17:11:17 +000092 return static_cast<u16>(Crc);
Kostya Kortchinsky1148dc52016-11-30 17:32:20 +000093 }
94
Kostya Kortchinsky006805d2017-04-20 15:11:00 +000095 // Checks the validity of a chunk by verifying its checksum. It doesn't
96 // incur termination in the event of an invalid chunk.
Kostya Kortchinsky1148dc52016-11-30 17:32:20 +000097 bool isValid() {
98 UnpackedHeader NewUnpackedHeader;
99 const AtomicPackedHeader *AtomicHeader =
100 reinterpret_cast<const AtomicPackedHeader *>(this);
Kostya Kortchinskya00b9222017-01-20 18:32:18 +0000101 PackedHeader NewPackedHeader = atomic_load_relaxed(AtomicHeader);
Kostya Kortchinsky1148dc52016-11-30 17:32:20 +0000102 NewUnpackedHeader = bit_cast<UnpackedHeader>(NewPackedHeader);
103 return (NewUnpackedHeader.Checksum == computeChecksum(&NewUnpackedHeader));
Kostya Serebryany712fc982016-06-07 01:20:26 +0000104 }
105
Kostya Kortchinsky006805d2017-04-20 15:11:00 +0000106 // Nulls out a chunk header. When returning the chunk to the backend, there
107 // is no need to store a valid ChunkAvailable header, as this would be
108 // computationally expensive. Zeroing out serves the same purpose by making
109 // the header invalid. In the extremely rare event where 0 would be a valid
110 // checksum for the chunk, the state of the chunk is ChunkAvailable anyway.
111 COMPILER_CHECK(ChunkAvailable == 0);
112 void eraseHeader() {
113 PackedHeader NullPackedHeader = 0;
114 AtomicPackedHeader *AtomicHeader =
115 reinterpret_cast<AtomicPackedHeader *>(this);
116 atomic_store_relaxed(AtomicHeader, NullPackedHeader);
117 }
118
Kostya Serebryany712fc982016-06-07 01:20:26 +0000119 // Loads and unpacks the header, verifying the checksum in the process.
120 void loadHeader(UnpackedHeader *NewUnpackedHeader) const {
121 const AtomicPackedHeader *AtomicHeader =
122 reinterpret_cast<const AtomicPackedHeader *>(this);
Kostya Kortchinskya00b9222017-01-20 18:32:18 +0000123 PackedHeader NewPackedHeader = atomic_load_relaxed(AtomicHeader);
Kostya Serebryany712fc982016-06-07 01:20:26 +0000124 *NewUnpackedHeader = bit_cast<UnpackedHeader>(NewPackedHeader);
Kostya Kortchinsky006805d2017-04-20 15:11:00 +0000125 if (UNLIKELY(NewUnpackedHeader->Checksum !=
126 computeChecksum(NewUnpackedHeader))) {
Kostya Serebryany712fc982016-06-07 01:20:26 +0000127 dieWithMessage("ERROR: corrupted chunk header at address %p\n", this);
128 }
129 }
130
131 // Packs and stores the header, computing the checksum in the process.
132 void storeHeader(UnpackedHeader *NewUnpackedHeader) {
Kostya Kortchinsky71dcc332016-10-26 16:16:58 +0000133 NewUnpackedHeader->Checksum = computeChecksum(NewUnpackedHeader);
Kostya Serebryany712fc982016-06-07 01:20:26 +0000134 PackedHeader NewPackedHeader = bit_cast<PackedHeader>(*NewUnpackedHeader);
135 AtomicPackedHeader *AtomicHeader =
136 reinterpret_cast<AtomicPackedHeader *>(this);
Kostya Kortchinskya00b9222017-01-20 18:32:18 +0000137 atomic_store_relaxed(AtomicHeader, NewPackedHeader);
Kostya Serebryany712fc982016-06-07 01:20:26 +0000138 }
139
140 // Packs and stores the header, computing the checksum in the process. We
141 // compare the current header with the expected provided one to ensure that
142 // we are not being raced by a corruption occurring in another thread.
143 void compareExchangeHeader(UnpackedHeader *NewUnpackedHeader,
144 UnpackedHeader *OldUnpackedHeader) {
Kostya Kortchinsky71dcc332016-10-26 16:16:58 +0000145 NewUnpackedHeader->Checksum = computeChecksum(NewUnpackedHeader);
Kostya Serebryany712fc982016-06-07 01:20:26 +0000146 PackedHeader NewPackedHeader = bit_cast<PackedHeader>(*NewUnpackedHeader);
147 PackedHeader OldPackedHeader = bit_cast<PackedHeader>(*OldUnpackedHeader);
148 AtomicPackedHeader *AtomicHeader =
149 reinterpret_cast<AtomicPackedHeader *>(this);
Kostya Kortchinsky006805d2017-04-20 15:11:00 +0000150 if (UNLIKELY(!atomic_compare_exchange_strong(AtomicHeader,
151 &OldPackedHeader,
152 NewPackedHeader,
153 memory_order_relaxed))) {
Kostya Serebryany712fc982016-06-07 01:20:26 +0000154 dieWithMessage("ERROR: race on chunk header at address %p\n", this);
155 }
156 }
157};
158
Kostya Kortchinsky006805d2017-04-20 15:11:00 +0000159ScudoChunk *getScudoChunk(uptr UserBeg) {
160 return reinterpret_cast<ScudoChunk *>(UserBeg - AlignedChunkHeaderSize);
161}
162
Kostya Kortchinsky36b34342017-04-27 20:21:16 +0000163struct AllocatorOptions {
164 u32 QuarantineSizeMb;
165 u32 ThreadLocalQuarantineSizeKb;
166 bool MayReturnNull;
167 s32 ReleaseToOSIntervalMs;
168 bool DeallocationTypeMismatch;
169 bool DeleteSizeMismatch;
170 bool ZeroContents;
Kostya Serebryany712fc982016-06-07 01:20:26 +0000171
Kostya Kortchinsky36b34342017-04-27 20:21:16 +0000172 void setFrom(const Flags *f, const CommonFlags *cf);
173 void copyTo(Flags *f, CommonFlags *cf) const;
174};
Kostya Serebryany712fc982016-06-07 01:20:26 +0000175
Kostya Kortchinsky36b34342017-04-27 20:21:16 +0000176void AllocatorOptions::setFrom(const Flags *f, const CommonFlags *cf) {
177 MayReturnNull = cf->allocator_may_return_null;
178 ReleaseToOSIntervalMs = cf->allocator_release_to_os_interval_ms;
179 QuarantineSizeMb = f->QuarantineSizeMb;
180 ThreadLocalQuarantineSizeKb = f->ThreadLocalQuarantineSizeKb;
181 DeallocationTypeMismatch = f->DeallocationTypeMismatch;
182 DeleteSizeMismatch = f->DeleteSizeMismatch;
183 ZeroContents = f->ZeroContents;
Kostya Serebryany712fc982016-06-07 01:20:26 +0000184}
185
Kostya Kortchinsky36b34342017-04-27 20:21:16 +0000186void AllocatorOptions::copyTo(Flags *f, CommonFlags *cf) const {
187 cf->allocator_may_return_null = MayReturnNull;
188 cf->allocator_release_to_os_interval_ms = ReleaseToOSIntervalMs;
189 f->QuarantineSizeMb = QuarantineSizeMb;
190 f->ThreadLocalQuarantineSizeKb = ThreadLocalQuarantineSizeKb;
191 f->DeallocationTypeMismatch = DeallocationTypeMismatch;
192 f->DeleteSizeMismatch = DeleteSizeMismatch;
193 f->ZeroContents = ZeroContents;
194}
195
196static void initScudoInternal(const AllocatorOptions &Options);
197
198static bool ScudoInitIsRunning = false;
199
200void initScudo() {
Kostya Serebryany712fc982016-06-07 01:20:26 +0000201 SanitizerToolName = "Scudo";
202 CHECK(!ScudoInitIsRunning && "Scudo init calls itself!");
203 ScudoInitIsRunning = true;
204
Kostya Kortchinskyb0e96eb2017-05-09 15:12:38 +0000205 // Check if hardware CRC32 is supported in the binary and by the platform, if
206 // so, opt for the CRC32 hardware version of the checksum.
207 if (computeHardwareCRC32 && testCPUFeature(CRC32CPUFeature))
Kostya Kortchinsky1148dc52016-11-30 17:32:20 +0000208 atomic_store_relaxed(&HashAlgorithm, CRC32Hardware);
Kostya Kortchinsky1148dc52016-11-30 17:32:20 +0000209
Kostya Serebryany712fc982016-06-07 01:20:26 +0000210 initFlags();
211
212 AllocatorOptions Options;
213 Options.setFrom(getFlags(), common_flags());
Kostya Kortchinsky36b34342017-04-27 20:21:16 +0000214 initScudoInternal(Options);
Kostya Serebryany712fc982016-06-07 01:20:26 +0000215
Kostya Kortchinsky36b34342017-04-27 20:21:16 +0000216 // TODO(kostyak): determine if MaybeStartBackgroudThread could be of some use.
Kostya Kortchinsky71dcc332016-10-26 16:16:58 +0000217
Kostya Serebryany712fc982016-06-07 01:20:26 +0000218 ScudoInitIsRunning = false;
219}
220
Kostya Serebryany712fc982016-06-07 01:20:26 +0000221struct QuarantineCallback {
222 explicit QuarantineCallback(AllocatorCache *Cache)
223 : Cache_(Cache) {}
224
Kostya Kortchinsky01a66fc2017-05-11 21:40:45 +0000225 // Chunk recycling function, returns a quarantined chunk to the backend,
226 // first making sure it hasn't been tampered with.
Kostya Serebryany712fc982016-06-07 01:20:26 +0000227 void Recycle(ScudoChunk *Chunk) {
228 UnpackedHeader Header;
229 Chunk->loadHeader(&Header);
Kostya Kortchinsky006805d2017-04-20 15:11:00 +0000230 if (UNLIKELY(Header.State != ChunkQuarantine)) {
Kostya Serebryany712fc982016-06-07 01:20:26 +0000231 dieWithMessage("ERROR: invalid chunk state when recycling address %p\n",
232 Chunk);
233 }
Kostya Kortchinsky006805d2017-04-20 15:11:00 +0000234 Chunk->eraseHeader();
Kostya Kortchinsky71dcc332016-10-26 16:16:58 +0000235 void *Ptr = Chunk->getAllocBeg(&Header);
Kostya Kortchinskyb44364d2017-07-13 21:01:19 +0000236 if (Header.FromPrimary)
237 getBackendAllocator().deallocatePrimary(Cache_, Ptr);
238 else
239 getBackendAllocator().deallocateSecondary(Ptr);
Kostya Serebryany712fc982016-06-07 01:20:26 +0000240 }
241
Kostya Kortchinsky01a66fc2017-05-11 21:40:45 +0000242 // Internal quarantine allocation and deallocation functions. We first check
243 // that the batches are indeed serviced by the Primary.
244 // TODO(kostyak): figure out the best way to protect the batches.
245 COMPILER_CHECK(sizeof(QuarantineBatch) < SizeClassMap::kMaxSize);
Kostya Serebryany712fc982016-06-07 01:20:26 +0000246 void *Allocate(uptr Size) {
Kostya Kortchinskyb44364d2017-07-13 21:01:19 +0000247 return getBackendAllocator().allocatePrimary(Cache_, Size);
Kostya Serebryany712fc982016-06-07 01:20:26 +0000248 }
249
250 void Deallocate(void *Ptr) {
Kostya Kortchinskyb44364d2017-07-13 21:01:19 +0000251 getBackendAllocator().deallocatePrimary(Cache_, Ptr);
Kostya Serebryany712fc982016-06-07 01:20:26 +0000252 }
253
254 AllocatorCache *Cache_;
255};
256
257typedef Quarantine<QuarantineCallback, ScudoChunk> ScudoQuarantine;
Kostya Kortchinsky006805d2017-04-20 15:11:00 +0000258typedef ScudoQuarantine::Cache ScudoQuarantineCache;
Kostya Kortchinsky36b34342017-04-27 20:21:16 +0000259COMPILER_CHECK(sizeof(ScudoQuarantineCache) <=
260 sizeof(ScudoThreadContext::QuarantineCachePlaceHolder));
Kostya Serebryany712fc982016-06-07 01:20:26 +0000261
Kostya Kortchinsky36b34342017-04-27 20:21:16 +0000262AllocatorCache *getAllocatorCache(ScudoThreadContext *ThreadContext) {
263 return &ThreadContext->Cache;
Kostya Serebryany712fc982016-06-07 01:20:26 +0000264}
265
Kostya Kortchinsky36b34342017-04-27 20:21:16 +0000266ScudoQuarantineCache *getQuarantineCache(ScudoThreadContext *ThreadContext) {
267 return reinterpret_cast<
268 ScudoQuarantineCache *>(ThreadContext->QuarantineCachePlaceHolder);
269}
270
Kostya Kortchinsky00582562017-07-12 15:29:08 +0000271ScudoPrng *getPrng(ScudoThreadContext *ThreadContext) {
Kostya Kortchinsky36b34342017-04-27 20:21:16 +0000272 return &ThreadContext->Prng;
Kostya Serebryany712fc982016-06-07 01:20:26 +0000273}
274
Kostya Kortchinsky006805d2017-04-20 15:11:00 +0000275struct ScudoAllocator {
Kostya Kortchinsky71dcc332016-10-26 16:16:58 +0000276 static const uptr MaxAllowedMallocSize =
277 FIRST_32_SECOND_64(2UL << 30, 1ULL << 40);
Kostya Serebryany712fc982016-06-07 01:20:26 +0000278
Alex Shlyapnikovccab11b2017-06-20 21:23:02 +0000279 typedef ReturnNullOrDieOnFailure FailureHandler;
280
Kostya Kortchinsky006805d2017-04-20 15:11:00 +0000281 ScudoBackendAllocator BackendAllocator;
Kostya Serebryany712fc982016-06-07 01:20:26 +0000282 ScudoQuarantine AllocatorQuarantine;
283
Kostya Kortchinskyb44364d2017-07-13 21:01:19 +0000284 StaticSpinMutex GlobalPrngMutex;
285 ScudoPrng GlobalPrng;
286
Kostya Serebryany712fc982016-06-07 01:20:26 +0000287 // The fallback caches are used when the thread local caches have been
288 // 'detroyed' on thread tear-down. They are protected by a Mutex as they can
289 // be accessed by different threads.
290 StaticSpinMutex FallbackMutex;
291 AllocatorCache FallbackAllocatorCache;
Kostya Kortchinsky006805d2017-04-20 15:11:00 +0000292 ScudoQuarantineCache FallbackQuarantineCache;
Kostya Kortchinsky00582562017-07-12 15:29:08 +0000293 ScudoPrng FallbackPrng;
Kostya Serebryany712fc982016-06-07 01:20:26 +0000294
295 bool DeallocationTypeMismatch;
296 bool ZeroContents;
297 bool DeleteSizeMismatch;
298
Kostya Kortchinsky006805d2017-04-20 15:11:00 +0000299 explicit ScudoAllocator(LinkerInitialized)
Kostya Serebryany712fc982016-06-07 01:20:26 +0000300 : AllocatorQuarantine(LINKER_INITIALIZED),
301 FallbackQuarantineCache(LINKER_INITIALIZED) {}
302
303 void init(const AllocatorOptions &Options) {
Kostya Serebryany712fc982016-06-07 01:20:26 +0000304 // Verify that the header offset field can hold the maximum offset. In the
Kostya Kortchinsky71dcc332016-10-26 16:16:58 +0000305 // case of the Secondary allocator, it takes care of alignment and the
306 // offset will always be 0. In the case of the Primary, the worst case
307 // scenario happens in the last size class, when the backend allocation
308 // would already be aligned on the requested alignment, which would happen
309 // to be the maximum alignment that would fit in that size class. As a
310 // result, the maximum offset will be at most the maximum alignment for the
311 // last size class minus the header size, in multiples of MinAlignment.
Kostya Serebryany712fc982016-06-07 01:20:26 +0000312 UnpackedHeader Header = {};
Kostya Kortchinskyb44364d2017-07-13 21:01:19 +0000313 uptr MaxPrimaryAlignment =
314 1 << MostSignificantSetBitIndex(SizeClassMap::kMaxSize - MinAlignment);
315 uptr MaxOffset =
316 (MaxPrimaryAlignment - AlignedChunkHeaderSize) >> MinAlignmentLog;
Kostya Kortchinsky1148dc52016-11-30 17:32:20 +0000317 Header.Offset = MaxOffset;
318 if (Header.Offset != MaxOffset) {
Kostya Serebryany712fc982016-06-07 01:20:26 +0000319 dieWithMessage("ERROR: the maximum possible offset doesn't fit in the "
320 "header\n");
321 }
Kostya Kortchinskyfff8e062017-04-20 18:07:17 +0000322 // Verify that we can fit the maximum size or amount of unused bytes in the
323 // header. Given that the Secondary fits the allocation to a page, the worst
324 // case scenario happens in the Primary. It will depend on the second to
325 // last and last class sizes, as well as the dynamic base for the Primary.
326 // The following is an over-approximation that works for our needs.
327 uptr MaxSizeOrUnusedBytes = SizeClassMap::kMaxSize - 1;
328 Header.SizeOrUnusedBytes = MaxSizeOrUnusedBytes;
329 if (Header.SizeOrUnusedBytes != MaxSizeOrUnusedBytes) {
Kostya Kortchinsky1148dc52016-11-30 17:32:20 +0000330 dieWithMessage("ERROR: the maximum possible unused bytes doesn't fit in "
331 "the header\n");
332 }
Kostya Serebryany712fc982016-06-07 01:20:26 +0000333
334 DeallocationTypeMismatch = Options.DeallocationTypeMismatch;
335 DeleteSizeMismatch = Options.DeleteSizeMismatch;
336 ZeroContents = Options.ZeroContents;
Alex Shlyapnikovccab11b2017-06-20 21:23:02 +0000337 SetAllocatorMayReturnNull(Options.MayReturnNull);
Kostya Kortchinskyb44364d2017-07-13 21:01:19 +0000338 BackendAllocator.init(Options.ReleaseToOSIntervalMs);
Kostya Kortchinsky71dcc332016-10-26 16:16:58 +0000339 AllocatorQuarantine.Init(
340 static_cast<uptr>(Options.QuarantineSizeMb) << 20,
341 static_cast<uptr>(Options.ThreadLocalQuarantineSizeKb) << 10);
Kostya Kortchinskyb44364d2017-07-13 21:01:19 +0000342 GlobalPrng.init();
343 Cookie = GlobalPrng.getU64();
344 BackendAllocator.initCache(&FallbackAllocatorCache);
Kostya Kortchinsky00582562017-07-12 15:29:08 +0000345 FallbackPrng.init();
Kostya Serebryany712fc982016-06-07 01:20:26 +0000346 }
347
Kostya Kortchinsky006805d2017-04-20 15:11:00 +0000348 // Helper function that checks for a valid Scudo chunk. nullptr isn't.
Kostya Kortchinsky1148dc52016-11-30 17:32:20 +0000349 bool isValidPointer(const void *UserPtr) {
Kostya Kortchinsky36b34342017-04-27 20:21:16 +0000350 initThreadMaybe();
Kostya Kortchinsky0ce49992017-06-29 16:45:20 +0000351 if (UNLIKELY(!UserPtr))
Kostya Kortchinsky1148dc52016-11-30 17:32:20 +0000352 return false;
Kostya Kortchinsky006805d2017-04-20 15:11:00 +0000353 uptr UserBeg = reinterpret_cast<uptr>(UserPtr);
354 if (!IsAligned(UserBeg, MinAlignment))
355 return false;
356 return getScudoChunk(UserBeg)->isValid();
Kostya Kortchinsky1148dc52016-11-30 17:32:20 +0000357 }
358
Kostya Serebryany712fc982016-06-07 01:20:26 +0000359 // Allocates a chunk.
Kostya Kortchinsky006805d2017-04-20 15:11:00 +0000360 void *allocate(uptr Size, uptr Alignment, AllocType Type,
361 bool ForceZeroContents = false) {
Kostya Kortchinsky36b34342017-04-27 20:21:16 +0000362 initThreadMaybe();
Kostya Kortchinsky0ce49992017-06-29 16:45:20 +0000363 if (UNLIKELY(Alignment > MaxAlignment))
Alex Shlyapnikovccab11b2017-06-20 21:23:02 +0000364 return FailureHandler::OnBadRequest();
Kostya Kortchinsky0ce49992017-06-29 16:45:20 +0000365 if (UNLIKELY(Alignment < MinAlignment))
Kostya Serebryany712fc982016-06-07 01:20:26 +0000366 Alignment = MinAlignment;
Kostya Kortchinsky0ce49992017-06-29 16:45:20 +0000367 if (UNLIKELY(Size >= MaxAllowedMallocSize))
Alex Shlyapnikovccab11b2017-06-20 21:23:02 +0000368 return FailureHandler::OnBadRequest();
Kostya Kortchinsky0ce49992017-06-29 16:45:20 +0000369 if (UNLIKELY(Size == 0))
Kostya Kortchinsky006805d2017-04-20 15:11:00 +0000370 Size = 1;
Kostya Kortchinskyc74da7c2016-12-13 19:31:54 +0000371
372 uptr NeededSize = RoundUpTo(Size, MinAlignment) + AlignedChunkHeaderSize;
Kostya Kortchinsky01a66fc2017-05-11 21:40:45 +0000373 uptr AlignedSize = (Alignment > MinAlignment) ?
374 NeededSize + (Alignment - AlignedChunkHeaderSize) : NeededSize;
Kostya Kortchinsky0ce49992017-06-29 16:45:20 +0000375 if (UNLIKELY(AlignedSize >= MaxAllowedMallocSize))
Alex Shlyapnikovccab11b2017-06-20 21:23:02 +0000376 return FailureHandler::OnBadRequest();
Kostya Kortchinskyc74da7c2016-12-13 19:31:54 +0000377
Kostya Kortchinsky01a66fc2017-05-11 21:40:45 +0000378 // Primary and Secondary backed allocations have a different treatment. We
379 // deal with alignment requirements of Primary serviced allocations here,
380 // but the Secondary will take care of its own alignment needs.
381 bool FromPrimary = PrimaryAllocator::CanAllocate(AlignedSize, MinAlignment);
Kostya Serebryany712fc982016-06-07 01:20:26 +0000382
383 void *Ptr;
Kostya Kortchinsky00582562017-07-12 15:29:08 +0000384 u8 Salt;
Kostya Kortchinskyb44364d2017-07-13 21:01:19 +0000385 uptr AllocSize;
386 if (FromPrimary) {
387 AllocSize = AlignedSize;
388 ScudoThreadContext *ThreadContext = getThreadContextAndLock();
389 if (LIKELY(ThreadContext)) {
390 Salt = getPrng(ThreadContext)->getU8();
391 Ptr = BackendAllocator.allocatePrimary(getAllocatorCache(ThreadContext),
392 AllocSize);
393 ThreadContext->unlock();
394 } else {
395 SpinMutexLock l(&FallbackMutex);
396 Salt = FallbackPrng.getU8();
397 Ptr = BackendAllocator.allocatePrimary(&FallbackAllocatorCache,
398 AllocSize);
399 }
Kostya Serebryany712fc982016-06-07 01:20:26 +0000400 } else {
Kostya Kortchinskyb44364d2017-07-13 21:01:19 +0000401 {
402 SpinMutexLock l(&GlobalPrngMutex);
403 Salt = GlobalPrng.getU8();
404 }
405 AllocSize = NeededSize;
406 Ptr = BackendAllocator.allocateSecondary(AllocSize, Alignment);
Kostya Serebryany712fc982016-06-07 01:20:26 +0000407 }
Kostya Kortchinsky0ce49992017-06-29 16:45:20 +0000408 if (UNLIKELY(!Ptr))
Alex Shlyapnikovccab11b2017-06-20 21:23:02 +0000409 return FailureHandler::OnOOM();
Kostya Serebryany712fc982016-06-07 01:20:26 +0000410
Kostya Kortchinsky1148dc52016-11-30 17:32:20 +0000411 // If requested, we will zero out the entire contents of the returned chunk.
Kostya Kortchinsky006805d2017-04-20 15:11:00 +0000412 if ((ForceZeroContents || ZeroContents) && FromPrimary)
Kostya Kortchinskyb44364d2017-07-13 21:01:19 +0000413 memset(Ptr, 0, BackendAllocator.getActuallyAllocatedSize(
414 Ptr, /*FromPrimary=*/true));
Kostya Kortchinsky1148dc52016-11-30 17:32:20 +0000415
Kostya Serebryany712fc982016-06-07 01:20:26 +0000416 UnpackedHeader Header = {};
Kostya Kortchinsky01a66fc2017-05-11 21:40:45 +0000417 uptr AllocBeg = reinterpret_cast<uptr>(Ptr);
418 uptr UserBeg = AllocBeg + AlignedChunkHeaderSize;
Kostya Kortchinsky0ce49992017-06-29 16:45:20 +0000419 if (UNLIKELY(!IsAligned(UserBeg, Alignment))) {
Kostya Kortchinsky01a66fc2017-05-11 21:40:45 +0000420 // Since the Secondary takes care of alignment, a non-aligned pointer
421 // means it is from the Primary. It is also the only case where the offset
422 // field of the header would be non-zero.
423 CHECK(FromPrimary);
424 UserBeg = RoundUpTo(UserBeg, Alignment);
425 uptr Offset = UserBeg - AlignedChunkHeaderSize - AllocBeg;
426 Header.Offset = Offset >> MinAlignmentLog;
427 }
Kostya Kortchinskyb44364d2017-07-13 21:01:19 +0000428 CHECK_LE(UserBeg + Size, AllocBeg + AllocSize);
Kostya Serebryany712fc982016-06-07 01:20:26 +0000429 Header.State = ChunkAllocated;
Kostya Serebryany712fc982016-06-07 01:20:26 +0000430 Header.AllocType = Type;
Kostya Kortchinskyfff8e062017-04-20 18:07:17 +0000431 if (FromPrimary) {
Kostya Kortchinskyb44364d2017-07-13 21:01:19 +0000432 Header.FromPrimary = 1;
Kostya Kortchinskyfff8e062017-04-20 18:07:17 +0000433 Header.SizeOrUnusedBytes = Size;
434 } else {
435 // The secondary fits the allocations to a page, so the amount of unused
436 // bytes is the difference between the end of the user allocation and the
437 // next page boundary.
438 uptr PageSize = GetPageSizeCached();
439 uptr TrailingBytes = (UserBeg + Size) & (PageSize - 1);
440 if (TrailingBytes)
441 Header.SizeOrUnusedBytes = PageSize - TrailingBytes;
442 }
Kostya Kortchinskyb44364d2017-07-13 21:01:19 +0000443 Header.Salt = Salt;
Kostya Kortchinsky006805d2017-04-20 15:11:00 +0000444 getScudoChunk(UserBeg)->storeHeader(&Header);
445 void *UserPtr = reinterpret_cast<void *>(UserBeg);
Kostya Serebryany712fc982016-06-07 01:20:26 +0000446 // if (&__sanitizer_malloc_hook) __sanitizer_malloc_hook(UserPtr, Size);
447 return UserPtr;
448 }
449
Kostya Kortchinskyf1a54fd2017-04-21 18:10:53 +0000450 // Place a chunk in the quarantine. In the event of a zero-sized quarantine,
451 // we directly deallocate the chunk, otherwise the flow would lead to the
Kostya Kortchinsky36b34342017-04-27 20:21:16 +0000452 // chunk being loaded (and checked) twice, and stored (and checksummed) once,
453 // with no additional security value.
Kostya Kortchinskyf1a54fd2017-04-21 18:10:53 +0000454 void quarantineOrDeallocateChunk(ScudoChunk *Chunk, UnpackedHeader *Header,
455 uptr Size) {
Kostya Kortchinsky01a66fc2017-05-11 21:40:45 +0000456 bool FromPrimary = Header->FromPrimary;
Kostya Kortchinskyf1a54fd2017-04-21 18:10:53 +0000457 bool BypassQuarantine = (AllocatorQuarantine.GetCacheSize() == 0);
458 if (BypassQuarantine) {
459 Chunk->eraseHeader();
460 void *Ptr = Chunk->getAllocBeg(Header);
Kostya Kortchinskyb44364d2017-07-13 21:01:19 +0000461 if (FromPrimary) {
462 ScudoThreadContext *ThreadContext = getThreadContextAndLock();
463 if (LIKELY(ThreadContext)) {
464 getBackendAllocator().deallocatePrimary(
465 getAllocatorCache(ThreadContext), Ptr);
466 ThreadContext->unlock();
467 } else {
468 SpinMutexLock Lock(&FallbackMutex);
469 getBackendAllocator().deallocatePrimary(&FallbackAllocatorCache, Ptr);
470 }
Kostya Kortchinskyf1a54fd2017-04-21 18:10:53 +0000471 } else {
Kostya Kortchinskyb44364d2017-07-13 21:01:19 +0000472 getBackendAllocator().deallocateSecondary(Ptr);
Kostya Kortchinskyf1a54fd2017-04-21 18:10:53 +0000473 }
474 } else {
475 UnpackedHeader NewHeader = *Header;
476 NewHeader.State = ChunkQuarantine;
477 Chunk->compareExchangeHeader(&NewHeader, Header);
Kostya Kortchinskyee0695762017-05-05 21:38:22 +0000478 ScudoThreadContext *ThreadContext = getThreadContextAndLock();
Kostya Kortchinsky36b34342017-04-27 20:21:16 +0000479 if (LIKELY(ThreadContext)) {
480 AllocatorQuarantine.Put(getQuarantineCache(ThreadContext),
481 QuarantineCallback(
482 getAllocatorCache(ThreadContext)),
483 Chunk, Size);
Kostya Kortchinskyee0695762017-05-05 21:38:22 +0000484 ThreadContext->unlock();
Kostya Kortchinskyf1a54fd2017-04-21 18:10:53 +0000485 } else {
486 SpinMutexLock l(&FallbackMutex);
487 AllocatorQuarantine.Put(&FallbackQuarantineCache,
488 QuarantineCallback(&FallbackAllocatorCache),
489 Chunk, Size);
490 }
491 }
492 }
493
Kostya Serebryany712fc982016-06-07 01:20:26 +0000494 // Deallocates a Chunk, which means adding it to the delayed free list (or
495 // Quarantine).
496 void deallocate(void *UserPtr, uptr DeleteSize, AllocType Type) {
Kostya Kortchinsky36b34342017-04-27 20:21:16 +0000497 initThreadMaybe();
Kostya Serebryany712fc982016-06-07 01:20:26 +0000498 // if (&__sanitizer_free_hook) __sanitizer_free_hook(UserPtr);
Kostya Kortchinsky0ce49992017-06-29 16:45:20 +0000499 if (UNLIKELY(!UserPtr))
Kostya Serebryany712fc982016-06-07 01:20:26 +0000500 return;
Kostya Kortchinsky006805d2017-04-20 15:11:00 +0000501 uptr UserBeg = reinterpret_cast<uptr>(UserPtr);
502 if (UNLIKELY(!IsAligned(UserBeg, MinAlignment))) {
Kostya Serebryany712fc982016-06-07 01:20:26 +0000503 dieWithMessage("ERROR: attempted to deallocate a chunk not properly "
504 "aligned at address %p\n", UserPtr);
505 }
Kostya Kortchinsky006805d2017-04-20 15:11:00 +0000506 ScudoChunk *Chunk = getScudoChunk(UserBeg);
Kostya Serebryany712fc982016-06-07 01:20:26 +0000507 UnpackedHeader OldHeader;
508 Chunk->loadHeader(&OldHeader);
Kostya Kortchinsky006805d2017-04-20 15:11:00 +0000509 if (UNLIKELY(OldHeader.State != ChunkAllocated)) {
Kostya Serebryany712fc982016-06-07 01:20:26 +0000510 dieWithMessage("ERROR: invalid chunk state when deallocating address "
Kostya Kortchinsky1148dc52016-11-30 17:32:20 +0000511 "%p\n", UserPtr);
Kostya Serebryany712fc982016-06-07 01:20:26 +0000512 }
Kostya Serebryany712fc982016-06-07 01:20:26 +0000513 if (DeallocationTypeMismatch) {
514 // The deallocation type has to match the allocation one.
Kostya Kortchinsky006805d2017-04-20 15:11:00 +0000515 if (OldHeader.AllocType != Type) {
Kostya Serebryany712fc982016-06-07 01:20:26 +0000516 // With the exception of memalign'd Chunks, that can be still be free'd.
Kostya Kortchinsky006805d2017-04-20 15:11:00 +0000517 if (OldHeader.AllocType != FromMemalign || Type != FromMalloc) {
Kostya Serebryany712fc982016-06-07 01:20:26 +0000518 dieWithMessage("ERROR: allocation type mismatch on address %p\n",
Kostya Kortchinsky006805d2017-04-20 15:11:00 +0000519 UserPtr);
Kostya Serebryany712fc982016-06-07 01:20:26 +0000520 }
521 }
522 }
Kostya Kortchinskyfff8e062017-04-20 18:07:17 +0000523 uptr Size = OldHeader.FromPrimary ? OldHeader.SizeOrUnusedBytes :
524 Chunk->getUsableSize(&OldHeader) - OldHeader.SizeOrUnusedBytes;
Kostya Serebryany712fc982016-06-07 01:20:26 +0000525 if (DeleteSizeMismatch) {
526 if (DeleteSize && DeleteSize != Size) {
527 dieWithMessage("ERROR: invalid sized delete on chunk at address %p\n",
Kostya Kortchinsky006805d2017-04-20 15:11:00 +0000528 UserPtr);
Kostya Serebryany712fc982016-06-07 01:20:26 +0000529 }
530 }
Kostya Kortchinsky1148dc52016-11-30 17:32:20 +0000531
Kostya Kortchinskyfff8e062017-04-20 18:07:17 +0000532 // If a small memory amount was allocated with a larger alignment, we want
533 // to take that into account. Otherwise the Quarantine would be filled with
Kostya Kortchinskyf1a54fd2017-04-21 18:10:53 +0000534 // tiny chunks, taking a lot of VA memory. This is an approximation of the
Kostya Kortchinskyfff8e062017-04-20 18:07:17 +0000535 // usable size, that allows us to not call GetActuallyAllocatedSize.
536 uptr LiableSize = Size + (OldHeader.Offset << MinAlignment);
Kostya Kortchinskyf1a54fd2017-04-21 18:10:53 +0000537 quarantineOrDeallocateChunk(Chunk, &OldHeader, LiableSize);
Kostya Serebryany712fc982016-06-07 01:20:26 +0000538 }
539
Kostya Serebryany712fc982016-06-07 01:20:26 +0000540 // Reallocates a chunk. We can save on a new allocation if the new requested
541 // size still fits in the chunk.
542 void *reallocate(void *OldPtr, uptr NewSize) {
Kostya Kortchinsky36b34342017-04-27 20:21:16 +0000543 initThreadMaybe();
Kostya Kortchinsky006805d2017-04-20 15:11:00 +0000544 uptr UserBeg = reinterpret_cast<uptr>(OldPtr);
545 if (UNLIKELY(!IsAligned(UserBeg, MinAlignment))) {
546 dieWithMessage("ERROR: attempted to reallocate a chunk not properly "
547 "aligned at address %p\n", OldPtr);
548 }
549 ScudoChunk *Chunk = getScudoChunk(UserBeg);
Kostya Kortchinsky1148dc52016-11-30 17:32:20 +0000550 UnpackedHeader OldHeader;
551 Chunk->loadHeader(&OldHeader);
Kostya Kortchinsky006805d2017-04-20 15:11:00 +0000552 if (UNLIKELY(OldHeader.State != ChunkAllocated)) {
Kostya Kortchinsky1148dc52016-11-30 17:32:20 +0000553 dieWithMessage("ERROR: invalid chunk state when reallocating address "
554 "%p\n", OldPtr);
555 }
Kostya Kortchinsky006805d2017-04-20 15:11:00 +0000556 if (UNLIKELY(OldHeader.AllocType != FromMalloc)) {
Kostya Serebryany712fc982016-06-07 01:20:26 +0000557 dieWithMessage("ERROR: invalid chunk type when reallocating address %p\n",
Kostya Kortchinsky006805d2017-04-20 15:11:00 +0000558 OldPtr);
Kostya Serebryany712fc982016-06-07 01:20:26 +0000559 }
Kostya Kortchinsky006805d2017-04-20 15:11:00 +0000560 uptr UsableSize = Chunk->getUsableSize(&OldHeader);
Kostya Kortchinskyfff8e062017-04-20 18:07:17 +0000561 // The new size still fits in the current chunk, and the size difference
562 // is reasonable.
563 if (NewSize <= UsableSize &&
564 (UsableSize - NewSize) < (SizeClassMap::kMaxSize / 2)) {
Kostya Kortchinskyf1a54fd2017-04-21 18:10:53 +0000565 UnpackedHeader NewHeader = OldHeader;
Kostya Kortchinskyfff8e062017-04-20 18:07:17 +0000566 NewHeader.SizeOrUnusedBytes =
567 OldHeader.FromPrimary ? NewSize : UsableSize - NewSize;
Kostya Serebryany712fc982016-06-07 01:20:26 +0000568 Chunk->compareExchangeHeader(&NewHeader, &OldHeader);
569 return OldPtr;
570 }
571 // Otherwise, we have to allocate a new chunk and copy the contents of the
572 // old one.
573 void *NewPtr = allocate(NewSize, MinAlignment, FromMalloc);
574 if (NewPtr) {
Kostya Kortchinskyfff8e062017-04-20 18:07:17 +0000575 uptr OldSize = OldHeader.FromPrimary ? OldHeader.SizeOrUnusedBytes :
576 UsableSize - OldHeader.SizeOrUnusedBytes;
Kostya Serebryany712fc982016-06-07 01:20:26 +0000577 memcpy(NewPtr, OldPtr, Min(NewSize, OldSize));
Kostya Kortchinskyf1a54fd2017-04-21 18:10:53 +0000578 quarantineOrDeallocateChunk(Chunk, &OldHeader, UsableSize);
Kostya Serebryany712fc982016-06-07 01:20:26 +0000579 }
580 return NewPtr;
581 }
582
Kostya Kortchinsky1148dc52016-11-30 17:32:20 +0000583 // Helper function that returns the actual usable size of a chunk.
584 uptr getUsableSize(const void *Ptr) {
Kostya Kortchinsky36b34342017-04-27 20:21:16 +0000585 initThreadMaybe();
Kostya Kortchinsky0ce49992017-06-29 16:45:20 +0000586 if (UNLIKELY(!Ptr))
Kostya Kortchinsky1148dc52016-11-30 17:32:20 +0000587 return 0;
Kostya Kortchinsky006805d2017-04-20 15:11:00 +0000588 uptr UserBeg = reinterpret_cast<uptr>(Ptr);
589 ScudoChunk *Chunk = getScudoChunk(UserBeg);
Kostya Kortchinsky1148dc52016-11-30 17:32:20 +0000590 UnpackedHeader Header;
591 Chunk->loadHeader(&Header);
592 // Getting the usable size of a chunk only makes sense if it's allocated.
Kostya Kortchinsky006805d2017-04-20 15:11:00 +0000593 if (UNLIKELY(Header.State != ChunkAllocated)) {
Kostya Kortchinsky1148dc52016-11-30 17:32:20 +0000594 dieWithMessage("ERROR: invalid chunk state when sizing address %p\n",
595 Ptr);
596 }
597 return Chunk->getUsableSize(&Header);
598 }
599
Kostya Serebryany712fc982016-06-07 01:20:26 +0000600 void *calloc(uptr NMemB, uptr Size) {
Kostya Kortchinsky36b34342017-04-27 20:21:16 +0000601 initThreadMaybe();
Kostya Kortchinskyb44364d2017-07-13 21:01:19 +0000602 if (UNLIKELY(CheckForCallocOverflow(NMemB, Size)))
Alex Shlyapnikovccab11b2017-06-20 21:23:02 +0000603 return FailureHandler::OnBadRequest();
Kostya Kortchinsky0ce49992017-06-29 16:45:20 +0000604 return allocate(NMemB * Size, MinAlignment, FromMalloc, true);
Kostya Serebryany712fc982016-06-07 01:20:26 +0000605 }
606
Kostya Kortchinsky36b34342017-04-27 20:21:16 +0000607 void commitBack(ScudoThreadContext *ThreadContext) {
608 AllocatorCache *Cache = getAllocatorCache(ThreadContext);
609 AllocatorQuarantine.Drain(getQuarantineCache(ThreadContext),
610 QuarantineCallback(Cache));
Kostya Kortchinskyb44364d2017-07-13 21:01:19 +0000611 BackendAllocator.destroyCache(Cache);
Kostya Serebryany712fc982016-06-07 01:20:26 +0000612 }
Kostya Kortchinsky8d6257b2017-02-03 20:49:42 +0000613
614 uptr getStats(AllocatorStat StatType) {
Kostya Kortchinsky36b34342017-04-27 20:21:16 +0000615 initThreadMaybe();
Kostya Kortchinsky8d6257b2017-02-03 20:49:42 +0000616 uptr stats[AllocatorStatCount];
Kostya Kortchinskyb44364d2017-07-13 21:01:19 +0000617 BackendAllocator.getStats(stats);
Kostya Kortchinsky8d6257b2017-02-03 20:49:42 +0000618 return stats[StatType];
619 }
Kostya Serebryany712fc982016-06-07 01:20:26 +0000620};
621
Kostya Kortchinsky006805d2017-04-20 15:11:00 +0000622static ScudoAllocator Instance(LINKER_INITIALIZED);
Kostya Serebryany712fc982016-06-07 01:20:26 +0000623
Kostya Kortchinsky006805d2017-04-20 15:11:00 +0000624static ScudoBackendAllocator &getBackendAllocator() {
Kostya Serebryany712fc982016-06-07 01:20:26 +0000625 return Instance.BackendAllocator;
626}
627
Kostya Kortchinsky36b34342017-04-27 20:21:16 +0000628static void initScudoInternal(const AllocatorOptions &Options) {
Kostya Serebryany712fc982016-06-07 01:20:26 +0000629 Instance.init(Options);
630}
631
Kostya Kortchinsky36b34342017-04-27 20:21:16 +0000632void ScudoThreadContext::init() {
Kostya Kortchinskyb44364d2017-07-13 21:01:19 +0000633 getBackendAllocator().initCache(&Cache);
Kostya Kortchinsky00582562017-07-12 15:29:08 +0000634 Prng.init();
Kostya Kortchinsky36b34342017-04-27 20:21:16 +0000635 memset(QuarantineCachePlaceHolder, 0, sizeof(QuarantineCachePlaceHolder));
636}
637
638void ScudoThreadContext::commitBack() {
639 Instance.commitBack(this);
Kostya Serebryany712fc982016-06-07 01:20:26 +0000640}
641
642void *scudoMalloc(uptr Size, AllocType Type) {
Alex Shlyapnikov42bea012017-07-18 19:11:04 +0000643 return SetErrnoOnNull(Instance.allocate(Size, MinAlignment, Type));
Kostya Serebryany712fc982016-06-07 01:20:26 +0000644}
645
646void scudoFree(void *Ptr, AllocType Type) {
647 Instance.deallocate(Ptr, 0, Type);
648}
649
650void scudoSizedFree(void *Ptr, uptr Size, AllocType Type) {
651 Instance.deallocate(Ptr, Size, Type);
652}
653
654void *scudoRealloc(void *Ptr, uptr Size) {
655 if (!Ptr)
Alex Shlyapnikov42bea012017-07-18 19:11:04 +0000656 return SetErrnoOnNull(Instance.allocate(Size, MinAlignment, FromMalloc));
Kostya Serebryany712fc982016-06-07 01:20:26 +0000657 if (Size == 0) {
658 Instance.deallocate(Ptr, 0, FromMalloc);
659 return nullptr;
660 }
Alex Shlyapnikov42bea012017-07-18 19:11:04 +0000661 return SetErrnoOnNull(Instance.reallocate(Ptr, Size));
Kostya Serebryany712fc982016-06-07 01:20:26 +0000662}
663
664void *scudoCalloc(uptr NMemB, uptr Size) {
Alex Shlyapnikov42bea012017-07-18 19:11:04 +0000665 return SetErrnoOnNull(Instance.calloc(NMemB, Size));
Kostya Serebryany712fc982016-06-07 01:20:26 +0000666}
667
668void *scudoValloc(uptr Size) {
Alex Shlyapnikov42bea012017-07-18 19:11:04 +0000669 return SetErrnoOnNull(
670 Instance.allocate(Size, GetPageSizeCached(), FromMemalign));
Kostya Serebryany712fc982016-06-07 01:20:26 +0000671}
672
Kostya Serebryany712fc982016-06-07 01:20:26 +0000673void *scudoPvalloc(uptr Size) {
674 uptr PageSize = GetPageSizeCached();
Alex Shlyapnikovdf18cbb2017-07-14 21:17:16 +0000675 // pvalloc(0) should allocate one page.
676 Size = Size ? RoundUpTo(Size, PageSize) : PageSize;
Alex Shlyapnikov42bea012017-07-18 19:11:04 +0000677 return SetErrnoOnNull(Instance.allocate(Size, PageSize, FromMemalign));
Kostya Serebryany712fc982016-06-07 01:20:26 +0000678}
679
Kostya Kortchinsky0ce49992017-06-29 16:45:20 +0000680void *scudoMemalign(uptr Alignment, uptr Size) {
Alex Shlyapnikovdf18cbb2017-07-14 21:17:16 +0000681 if (UNLIKELY(!IsPowerOfTwo(Alignment))) {
682 errno = errno_EINVAL;
Kostya Kortchinsky0ce49992017-06-29 16:45:20 +0000683 return ScudoAllocator::FailureHandler::OnBadRequest();
Alex Shlyapnikovdf18cbb2017-07-14 21:17:16 +0000684 }
Alex Shlyapnikov42bea012017-07-18 19:11:04 +0000685 return SetErrnoOnNull(Instance.allocate(Size, Alignment, FromMemalign));
Kostya Kortchinsky0ce49992017-06-29 16:45:20 +0000686}
687
Kostya Serebryany712fc982016-06-07 01:20:26 +0000688int scudoPosixMemalign(void **MemPtr, uptr Alignment, uptr Size) {
Alex Shlyapnikov42bea012017-07-18 19:11:04 +0000689 if (UNLIKELY(!CheckPosixMemalignAlignment(Alignment))) {
Alex Shlyapnikovdf18cbb2017-07-14 21:17:16 +0000690 ScudoAllocator::FailureHandler::OnBadRequest();
691 return errno_EINVAL;
Kostya Kortchinsky0ce49992017-06-29 16:45:20 +0000692 }
Alex Shlyapnikovdf18cbb2017-07-14 21:17:16 +0000693 void *Ptr = Instance.allocate(Size, Alignment, FromMemalign);
Alex Shlyapnikov42bea012017-07-18 19:11:04 +0000694 if (UNLIKELY(!Ptr))
Alex Shlyapnikovdf18cbb2017-07-14 21:17:16 +0000695 return errno_ENOMEM;
696 *MemPtr = Ptr;
Kostya Serebryany712fc982016-06-07 01:20:26 +0000697 return 0;
698}
699
700void *scudoAlignedAlloc(uptr Alignment, uptr Size) {
Alex Shlyapnikov42bea012017-07-18 19:11:04 +0000701 if (UNLIKELY(!CheckAlignedAllocAlignmentAndSize(Alignment, Size))) {
Alex Shlyapnikovdf18cbb2017-07-14 21:17:16 +0000702 errno = errno_EINVAL;
Kostya Kortchinsky0ce49992017-06-29 16:45:20 +0000703 return ScudoAllocator::FailureHandler::OnBadRequest();
Alex Shlyapnikovdf18cbb2017-07-14 21:17:16 +0000704 }
Alex Shlyapnikov42bea012017-07-18 19:11:04 +0000705 return SetErrnoOnNull(Instance.allocate(Size, Alignment, FromMalloc));
Kostya Serebryany712fc982016-06-07 01:20:26 +0000706}
707
708uptr scudoMallocUsableSize(void *Ptr) {
709 return Instance.getUsableSize(Ptr);
710}
711
Kostya Kortchinsky1148dc52016-11-30 17:32:20 +0000712} // namespace __scudo
Kostya Serebryany712fc982016-06-07 01:20:26 +0000713
714using namespace __scudo;
715
716// MallocExtension helper functions
717
718uptr __sanitizer_get_current_allocated_bytes() {
Kostya Kortchinsky8d6257b2017-02-03 20:49:42 +0000719 return Instance.getStats(AllocatorStatAllocated);
Kostya Serebryany712fc982016-06-07 01:20:26 +0000720}
721
722uptr __sanitizer_get_heap_size() {
Kostya Kortchinsky8d6257b2017-02-03 20:49:42 +0000723 return Instance.getStats(AllocatorStatMapped);
Kostya Serebryany712fc982016-06-07 01:20:26 +0000724}
725
726uptr __sanitizer_get_free_bytes() {
727 return 1;
728}
729
730uptr __sanitizer_get_unmapped_bytes() {
731 return 1;
732}
733
734uptr __sanitizer_get_estimated_allocated_size(uptr size) {
735 return size;
736}
737
Kostya Kortchinsky1148dc52016-11-30 17:32:20 +0000738int __sanitizer_get_ownership(const void *Ptr) {
739 return Instance.isValidPointer(Ptr);
Kostya Serebryany712fc982016-06-07 01:20:26 +0000740}
741
Kostya Kortchinsky1148dc52016-11-30 17:32:20 +0000742uptr __sanitizer_get_allocated_size(const void *Ptr) {
743 return Instance.getUsableSize(Ptr);
Kostya Serebryany712fc982016-06-07 01:20:26 +0000744}