blob: 66870d58184649864b830d01204b2dcf711a2fd8 [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 Kortchinsky43917722017-08-16 16:40:48 +000019#include "scudo_flags.h"
Kostya Kortchinskyb59abb22017-09-26 17:20:02 +000020#include "scudo_tsd.h"
Kostya Serebryany712fc982016-06-07 01:20:26 +000021#include "scudo_utils.h"
22
Alex Shlyapnikov42bea012017-07-18 19:11:04 +000023#include "sanitizer_common/sanitizer_allocator_checks.h"
Kostya Serebryany712fc982016-06-07 01:20:26 +000024#include "sanitizer_common/sanitizer_allocator_interface.h"
25#include "sanitizer_common/sanitizer_quarantine.h"
26
Kostya Kortchinsky8d4ba5f2017-10-12 15:01:09 +000027#include <errno.h>
Kostya Kortchinsky006805d2017-04-20 15:11:00 +000028#include <string.h>
Kostya Serebryany712fc982016-06-07 01:20:26 +000029
30namespace __scudo {
31
Kostya Serebryany712fc982016-06-07 01:20:26 +000032// Global static cookie, initialized at start-up.
Kostya Kortchinsky1148dc52016-11-30 17:32:20 +000033static uptr Cookie;
34
Kostya Kortchinsky1148dc52016-11-30 17:32:20 +000035// We default to software CRC32 if the alternatives are not supported, either
36// at compilation or at runtime.
37static atomic_uint8_t HashAlgorithm = { CRC32Software };
38
Kostya Kortchinsky43917722017-08-16 16:40:48 +000039INLINE u32 computeCRC32(u32 Crc, uptr Value, uptr *Array, uptr ArraySize) {
Kostya Kortchinskyb0e96eb2017-05-09 15:12:38 +000040 // If the hardware CRC32 feature is defined here, it was enabled everywhere,
41 // as opposed to only for scudo_crc32.cpp. This means that other hardware
42 // specific instructions were likely emitted at other places, and as a
43 // result there is no reason to not use it here.
Kostya Kortchinskyb39dff42017-01-18 17:11:17 +000044#if defined(__SSE4_2__) || defined(__ARM_FEATURE_CRC32)
Kostya Kortchinskyb0e96eb2017-05-09 15:12:38 +000045 Crc = CRC32_INTRINSIC(Crc, Value);
46 for (uptr i = 0; i < ArraySize; i++)
47 Crc = CRC32_INTRINSIC(Crc, Array[i]);
48 return Crc;
Kostya Kortchinskyb39dff42017-01-18 17:11:17 +000049#else
Kostya Kortchinskyb0e96eb2017-05-09 15:12:38 +000050 if (atomic_load_relaxed(&HashAlgorithm) == CRC32Hardware) {
51 Crc = computeHardwareCRC32(Crc, Value);
52 for (uptr i = 0; i < ArraySize; i++)
53 Crc = computeHardwareCRC32(Crc, Array[i]);
54 return Crc;
55 }
56 Crc = computeSoftwareCRC32(Crc, Value);
57 for (uptr i = 0; i < ArraySize; i++)
58 Crc = computeSoftwareCRC32(Crc, Array[i]);
59 return Crc;
60#endif // defined(__SSE4_2__) || defined(__ARM_FEATURE_CRC32)
Kostya Kortchinsky1148dc52016-11-30 17:32:20 +000061}
Kostya Serebryany712fc982016-06-07 01:20:26 +000062
Kostya Kortchinsky36b34342017-04-27 20:21:16 +000063static ScudoBackendAllocator &getBackendAllocator();
64
Kostya Serebryany712fc982016-06-07 01:20:26 +000065struct ScudoChunk : UnpackedHeader {
66 // We can't use the offset member of the chunk itself, as we would double
67 // fetch it without any warranty that it wouldn't have been tampered. To
68 // prevent this, we work with a local copy of the header.
Kostya Kortchinsky71dcc332016-10-26 16:16:58 +000069 void *getAllocBeg(UnpackedHeader *Header) {
Kostya Serebryany712fc982016-06-07 01:20:26 +000070 return reinterpret_cast<void *>(
71 reinterpret_cast<uptr>(this) - (Header->Offset << MinAlignmentLog));
72 }
73
Kostya Kortchinsky1148dc52016-11-30 17:32:20 +000074 // Returns the usable size for a chunk, meaning the amount of bytes from the
75 // beginning of the user data to the end of the backend allocated chunk.
76 uptr getUsableSize(UnpackedHeader *Header) {
Kostya Kortchinsky01a66fc2017-05-11 21:40:45 +000077 uptr Size =
Kostya Kortchinskyb44364d2017-07-13 21:01:19 +000078 getBackendAllocator().getActuallyAllocatedSize(getAllocBeg(Header),
Kostya Kortchinsky01a66fc2017-05-11 21:40:45 +000079 Header->FromPrimary);
Kostya Kortchinsky1148dc52016-11-30 17:32:20 +000080 if (Size == 0)
Kostya Kortchinsky006805d2017-04-20 15:11:00 +000081 return 0;
Kostya Kortchinsky1148dc52016-11-30 17:32:20 +000082 return Size - AlignedChunkHeaderSize - (Header->Offset << MinAlignmentLog);
83 }
84
85 // Compute the checksum of the Chunk pointer and its ChunkHeader.
Kostya Kortchinsky71dcc332016-10-26 16:16:58 +000086 u16 computeChecksum(UnpackedHeader *Header) const {
Kostya Kortchinsky1148dc52016-11-30 17:32:20 +000087 UnpackedHeader ZeroChecksumHeader = *Header;
88 ZeroChecksumHeader.Checksum = 0;
89 uptr HeaderHolder[sizeof(UnpackedHeader) / sizeof(uptr)];
90 memcpy(&HeaderHolder, &ZeroChecksumHeader, sizeof(HeaderHolder));
Kostya Kortchinsky43917722017-08-16 16:40:48 +000091 u32 Crc = computeCRC32(static_cast<u32>(Cookie),
92 reinterpret_cast<uptr>(this), HeaderHolder,
Kostya Kortchinskyb0e96eb2017-05-09 15:12:38 +000093 ARRAY_SIZE(HeaderHolder));
Kostya Kortchinskyb39dff42017-01-18 17:11:17 +000094 return static_cast<u16>(Crc);
Kostya Kortchinsky1148dc52016-11-30 17:32:20 +000095 }
96
Kostya Kortchinsky006805d2017-04-20 15:11:00 +000097 // Checks the validity of a chunk by verifying its checksum. It doesn't
98 // incur termination in the event of an invalid chunk.
Kostya Kortchinsky1148dc52016-11-30 17:32:20 +000099 bool isValid() {
100 UnpackedHeader NewUnpackedHeader;
101 const AtomicPackedHeader *AtomicHeader =
102 reinterpret_cast<const AtomicPackedHeader *>(this);
Kostya Kortchinskya00b9222017-01-20 18:32:18 +0000103 PackedHeader NewPackedHeader = atomic_load_relaxed(AtomicHeader);
Kostya Kortchinsky1148dc52016-11-30 17:32:20 +0000104 NewUnpackedHeader = bit_cast<UnpackedHeader>(NewPackedHeader);
105 return (NewUnpackedHeader.Checksum == computeChecksum(&NewUnpackedHeader));
Kostya Serebryany712fc982016-06-07 01:20:26 +0000106 }
107
Kostya Kortchinsky006805d2017-04-20 15:11:00 +0000108 // Nulls out a chunk header. When returning the chunk to the backend, there
109 // is no need to store a valid ChunkAvailable header, as this would be
110 // computationally expensive. Zeroing out serves the same purpose by making
111 // the header invalid. In the extremely rare event where 0 would be a valid
112 // checksum for the chunk, the state of the chunk is ChunkAvailable anyway.
113 COMPILER_CHECK(ChunkAvailable == 0);
114 void eraseHeader() {
115 PackedHeader NullPackedHeader = 0;
116 AtomicPackedHeader *AtomicHeader =
117 reinterpret_cast<AtomicPackedHeader *>(this);
118 atomic_store_relaxed(AtomicHeader, NullPackedHeader);
119 }
120
Kostya Serebryany712fc982016-06-07 01:20:26 +0000121 // Loads and unpacks the header, verifying the checksum in the process.
122 void loadHeader(UnpackedHeader *NewUnpackedHeader) const {
123 const AtomicPackedHeader *AtomicHeader =
124 reinterpret_cast<const AtomicPackedHeader *>(this);
Kostya Kortchinskya00b9222017-01-20 18:32:18 +0000125 PackedHeader NewPackedHeader = atomic_load_relaxed(AtomicHeader);
Kostya Serebryany712fc982016-06-07 01:20:26 +0000126 *NewUnpackedHeader = bit_cast<UnpackedHeader>(NewPackedHeader);
Kostya Kortchinsky006805d2017-04-20 15:11:00 +0000127 if (UNLIKELY(NewUnpackedHeader->Checksum !=
128 computeChecksum(NewUnpackedHeader))) {
Kostya Serebryany712fc982016-06-07 01:20:26 +0000129 dieWithMessage("ERROR: corrupted chunk header at address %p\n", this);
130 }
131 }
132
133 // Packs and stores the header, computing the checksum in the process.
134 void storeHeader(UnpackedHeader *NewUnpackedHeader) {
Kostya Kortchinsky71dcc332016-10-26 16:16:58 +0000135 NewUnpackedHeader->Checksum = computeChecksum(NewUnpackedHeader);
Kostya Serebryany712fc982016-06-07 01:20:26 +0000136 PackedHeader NewPackedHeader = bit_cast<PackedHeader>(*NewUnpackedHeader);
137 AtomicPackedHeader *AtomicHeader =
138 reinterpret_cast<AtomicPackedHeader *>(this);
Kostya Kortchinskya00b9222017-01-20 18:32:18 +0000139 atomic_store_relaxed(AtomicHeader, NewPackedHeader);
Kostya Serebryany712fc982016-06-07 01:20:26 +0000140 }
141
142 // Packs and stores the header, computing the checksum in the process. We
143 // compare the current header with the expected provided one to ensure that
144 // we are not being raced by a corruption occurring in another thread.
145 void compareExchangeHeader(UnpackedHeader *NewUnpackedHeader,
146 UnpackedHeader *OldUnpackedHeader) {
Kostya Kortchinsky71dcc332016-10-26 16:16:58 +0000147 NewUnpackedHeader->Checksum = computeChecksum(NewUnpackedHeader);
Kostya Serebryany712fc982016-06-07 01:20:26 +0000148 PackedHeader NewPackedHeader = bit_cast<PackedHeader>(*NewUnpackedHeader);
149 PackedHeader OldPackedHeader = bit_cast<PackedHeader>(*OldUnpackedHeader);
150 AtomicPackedHeader *AtomicHeader =
151 reinterpret_cast<AtomicPackedHeader *>(this);
Kostya Kortchinsky006805d2017-04-20 15:11:00 +0000152 if (UNLIKELY(!atomic_compare_exchange_strong(AtomicHeader,
153 &OldPackedHeader,
154 NewPackedHeader,
155 memory_order_relaxed))) {
Kostya Serebryany712fc982016-06-07 01:20:26 +0000156 dieWithMessage("ERROR: race on chunk header at address %p\n", this);
157 }
158 }
159};
160
Kostya Kortchinsky006805d2017-04-20 15:11:00 +0000161ScudoChunk *getScudoChunk(uptr UserBeg) {
162 return reinterpret_cast<ScudoChunk *>(UserBeg - AlignedChunkHeaderSize);
163}
164
Kostya Serebryany712fc982016-06-07 01:20:26 +0000165struct QuarantineCallback {
166 explicit QuarantineCallback(AllocatorCache *Cache)
167 : Cache_(Cache) {}
168
Kostya Kortchinsky01a66fc2017-05-11 21:40:45 +0000169 // Chunk recycling function, returns a quarantined chunk to the backend,
170 // first making sure it hasn't been tampered with.
Kostya Serebryany712fc982016-06-07 01:20:26 +0000171 void Recycle(ScudoChunk *Chunk) {
172 UnpackedHeader Header;
173 Chunk->loadHeader(&Header);
Kostya Kortchinsky006805d2017-04-20 15:11:00 +0000174 if (UNLIKELY(Header.State != ChunkQuarantine)) {
Kostya Serebryany712fc982016-06-07 01:20:26 +0000175 dieWithMessage("ERROR: invalid chunk state when recycling address %p\n",
176 Chunk);
177 }
Kostya Kortchinsky006805d2017-04-20 15:11:00 +0000178 Chunk->eraseHeader();
Kostya Kortchinsky71dcc332016-10-26 16:16:58 +0000179 void *Ptr = Chunk->getAllocBeg(&Header);
Kostya Kortchinskyb44364d2017-07-13 21:01:19 +0000180 if (Header.FromPrimary)
181 getBackendAllocator().deallocatePrimary(Cache_, Ptr);
182 else
183 getBackendAllocator().deallocateSecondary(Ptr);
Kostya Serebryany712fc982016-06-07 01:20:26 +0000184 }
185
Kostya Kortchinsky01a66fc2017-05-11 21:40:45 +0000186 // Internal quarantine allocation and deallocation functions. We first check
187 // that the batches are indeed serviced by the Primary.
188 // TODO(kostyak): figure out the best way to protect the batches.
189 COMPILER_CHECK(sizeof(QuarantineBatch) < SizeClassMap::kMaxSize);
Kostya Serebryany712fc982016-06-07 01:20:26 +0000190 void *Allocate(uptr Size) {
Kostya Kortchinskyb44364d2017-07-13 21:01:19 +0000191 return getBackendAllocator().allocatePrimary(Cache_, Size);
Kostya Serebryany712fc982016-06-07 01:20:26 +0000192 }
193
194 void Deallocate(void *Ptr) {
Kostya Kortchinskyb44364d2017-07-13 21:01:19 +0000195 getBackendAllocator().deallocatePrimary(Cache_, Ptr);
Kostya Serebryany712fc982016-06-07 01:20:26 +0000196 }
197
198 AllocatorCache *Cache_;
199};
200
201typedef Quarantine<QuarantineCallback, ScudoChunk> ScudoQuarantine;
Kostya Kortchinsky006805d2017-04-20 15:11:00 +0000202typedef ScudoQuarantine::Cache ScudoQuarantineCache;
Kostya Kortchinsky36b34342017-04-27 20:21:16 +0000203COMPILER_CHECK(sizeof(ScudoQuarantineCache) <=
Kostya Kortchinsky39248092017-09-22 15:35:37 +0000204 sizeof(ScudoTSD::QuarantineCachePlaceHolder));
Kostya Serebryany712fc982016-06-07 01:20:26 +0000205
Kostya Kortchinsky39248092017-09-22 15:35:37 +0000206ScudoQuarantineCache *getQuarantineCache(ScudoTSD *TSD) {
207 return reinterpret_cast<ScudoQuarantineCache *>(
208 TSD->QuarantineCachePlaceHolder);
Kostya Serebryany712fc982016-06-07 01:20:26 +0000209}
210
Kostya Kortchinsky006805d2017-04-20 15:11:00 +0000211struct ScudoAllocator {
Kostya Kortchinsky71dcc332016-10-26 16:16:58 +0000212 static const uptr MaxAllowedMallocSize =
213 FIRST_32_SECOND_64(2UL << 30, 1ULL << 40);
Kostya Serebryany712fc982016-06-07 01:20:26 +0000214
Alex Shlyapnikovccab11b2017-06-20 21:23:02 +0000215 typedef ReturnNullOrDieOnFailure FailureHandler;
216
Kostya Kortchinsky006805d2017-04-20 15:11:00 +0000217 ScudoBackendAllocator BackendAllocator;
Kostya Serebryany712fc982016-06-07 01:20:26 +0000218 ScudoQuarantine AllocatorQuarantine;
219
Kostya Kortchinskyb44364d2017-07-13 21:01:19 +0000220 StaticSpinMutex GlobalPrngMutex;
221 ScudoPrng GlobalPrng;
222
Kostya Kortchinsky2d944052017-07-24 15:29:38 +0000223 u32 QuarantineChunksUpToSize;
224
Kostya Serebryany712fc982016-06-07 01:20:26 +0000225 bool DeallocationTypeMismatch;
226 bool ZeroContents;
227 bool DeleteSizeMismatch;
228
Kostya Kortchinsky58f2656d2017-11-15 16:40:27 +0000229 bool CheckRssLimit;
230 uptr HardRssLimitMb;
231 uptr SoftRssLimitMb;
232 atomic_uint8_t RssLimitExceeded;
233 atomic_uint64_t RssLastCheckedAtNS;
234
Kostya Kortchinsky006805d2017-04-20 15:11:00 +0000235 explicit ScudoAllocator(LinkerInitialized)
Kostya Kortchinsky22396c22017-09-25 15:12:08 +0000236 : AllocatorQuarantine(LINKER_INITIALIZED) {}
Kostya Serebryany712fc982016-06-07 01:20:26 +0000237
Kostya Kortchinskya2b715f2017-11-14 16:14:53 +0000238 void init() {
239 SanitizerToolName = "Scudo";
240 initFlags();
241
Kostya Serebryany712fc982016-06-07 01:20:26 +0000242 // Verify that the header offset field can hold the maximum offset. In the
Kostya Kortchinsky71dcc332016-10-26 16:16:58 +0000243 // case of the Secondary allocator, it takes care of alignment and the
244 // offset will always be 0. In the case of the Primary, the worst case
245 // scenario happens in the last size class, when the backend allocation
246 // would already be aligned on the requested alignment, which would happen
247 // to be the maximum alignment that would fit in that size class. As a
248 // result, the maximum offset will be at most the maximum alignment for the
249 // last size class minus the header size, in multiples of MinAlignment.
Kostya Serebryany712fc982016-06-07 01:20:26 +0000250 UnpackedHeader Header = {};
Kostya Kortchinskyb44364d2017-07-13 21:01:19 +0000251 uptr MaxPrimaryAlignment =
252 1 << MostSignificantSetBitIndex(SizeClassMap::kMaxSize - MinAlignment);
253 uptr MaxOffset =
254 (MaxPrimaryAlignment - AlignedChunkHeaderSize) >> MinAlignmentLog;
Kostya Kortchinsky1148dc52016-11-30 17:32:20 +0000255 Header.Offset = MaxOffset;
256 if (Header.Offset != MaxOffset) {
Kostya Serebryany712fc982016-06-07 01:20:26 +0000257 dieWithMessage("ERROR: the maximum possible offset doesn't fit in the "
258 "header\n");
259 }
Kostya Kortchinskyfff8e062017-04-20 18:07:17 +0000260 // Verify that we can fit the maximum size or amount of unused bytes in the
261 // header. Given that the Secondary fits the allocation to a page, the worst
262 // case scenario happens in the Primary. It will depend on the second to
263 // last and last class sizes, as well as the dynamic base for the Primary.
264 // The following is an over-approximation that works for our needs.
265 uptr MaxSizeOrUnusedBytes = SizeClassMap::kMaxSize - 1;
266 Header.SizeOrUnusedBytes = MaxSizeOrUnusedBytes;
267 if (Header.SizeOrUnusedBytes != MaxSizeOrUnusedBytes) {
Kostya Kortchinsky1148dc52016-11-30 17:32:20 +0000268 dieWithMessage("ERROR: the maximum possible unused bytes doesn't fit in "
269 "the header\n");
270 }
Kostya Serebryany712fc982016-06-07 01:20:26 +0000271
Kostya Kortchinskya2b715f2017-11-14 16:14:53 +0000272 // Check if hardware CRC32 is supported in the binary and by the platform,
273 // if so, opt for the CRC32 hardware version of the checksum.
274 if (computeHardwareCRC32 && testCPUFeature(CRC32CPUFeature))
275 atomic_store_relaxed(&HashAlgorithm, CRC32Hardware);
276
277 SetAllocatorMayReturnNull(common_flags()->allocator_may_return_null);
278 BackendAllocator.init(common_flags()->allocator_release_to_os_interval_ms);
Kostya Kortchinsky58f2656d2017-11-15 16:40:27 +0000279 HardRssLimitMb = common_flags()->hard_rss_limit_mb;
280 SoftRssLimitMb = common_flags()->soft_rss_limit_mb;
Kostya Kortchinsky71dcc332016-10-26 16:16:58 +0000281 AllocatorQuarantine.Init(
Kostya Kortchinskya2b715f2017-11-14 16:14:53 +0000282 static_cast<uptr>(getFlags()->QuarantineSizeKb) << 10,
283 static_cast<uptr>(getFlags()->ThreadLocalQuarantineSizeKb) << 10);
284 QuarantineChunksUpToSize = getFlags()->QuarantineChunksUpToSize;
285 DeallocationTypeMismatch = getFlags()->DeallocationTypeMismatch;
286 DeleteSizeMismatch = getFlags()->DeleteSizeMismatch;
287 ZeroContents = getFlags()->ZeroContents;
288
Kostya Kortchinskyb44364d2017-07-13 21:01:19 +0000289 GlobalPrng.init();
290 Cookie = GlobalPrng.getU64();
Kostya Kortchinsky58f2656d2017-11-15 16:40:27 +0000291
292 CheckRssLimit = HardRssLimitMb || SoftRssLimitMb;
293 if (CheckRssLimit)
294 atomic_store_relaxed(&RssLastCheckedAtNS, NanoTime());
Kostya Serebryany712fc982016-06-07 01:20:26 +0000295 }
296
Kostya Kortchinsky006805d2017-04-20 15:11:00 +0000297 // Helper function that checks for a valid Scudo chunk. nullptr isn't.
Kostya Kortchinsky1148dc52016-11-30 17:32:20 +0000298 bool isValidPointer(const void *UserPtr) {
Kostya Kortchinsky36b34342017-04-27 20:21:16 +0000299 initThreadMaybe();
Kostya Kortchinsky0ce49992017-06-29 16:45:20 +0000300 if (UNLIKELY(!UserPtr))
Kostya Kortchinsky1148dc52016-11-30 17:32:20 +0000301 return false;
Kostya Kortchinsky006805d2017-04-20 15:11:00 +0000302 uptr UserBeg = reinterpret_cast<uptr>(UserPtr);
303 if (!IsAligned(UserBeg, MinAlignment))
304 return false;
305 return getScudoChunk(UserBeg)->isValid();
Kostya Kortchinsky1148dc52016-11-30 17:32:20 +0000306 }
307
Kostya Kortchinsky58f2656d2017-11-15 16:40:27 +0000308 // Opportunistic RSS limit check. This will update the RSS limit status, if
309 // it can, every 100ms, otherwise it will just return the current one.
310 bool isRssLimitExceeded() {
311 u64 LastCheck = atomic_load_relaxed(&RssLastCheckedAtNS);
312 const u64 CurrentCheck = NanoTime();
313 if (LIKELY(CurrentCheck < LastCheck + (100ULL * 1000000ULL)))
314 return atomic_load_relaxed(&RssLimitExceeded);
315 if (!atomic_compare_exchange_weak(&RssLastCheckedAtNS, &LastCheck,
316 CurrentCheck, memory_order_relaxed))
317 return atomic_load_relaxed(&RssLimitExceeded);
318 // TODO(kostyak): We currently use sanitizer_common's GetRSS which reads the
319 // RSS from /proc/self/statm by default. We might want to
320 // call getrusage directly, even if it's less accurate.
321 const uptr CurrentRssMb = GetRSS() >> 20;
322 if (HardRssLimitMb && HardRssLimitMb < CurrentRssMb) {
323 Report("%s: hard RSS limit exhausted (%zdMb vs %zdMb)\n",
324 SanitizerToolName, HardRssLimitMb, CurrentRssMb);
325 DumpProcessMap();
326 Die();
327 }
328 if (SoftRssLimitMb) {
329 if (atomic_load_relaxed(&RssLimitExceeded)) {
330 if (CurrentRssMb <= SoftRssLimitMb)
331 atomic_store_relaxed(&RssLimitExceeded, false);
332 } else {
333 if (CurrentRssMb > SoftRssLimitMb) {
334 atomic_store_relaxed(&RssLimitExceeded, true);
335 Report("%s: soft RSS limit exhausted (%zdMb vs %zdMb)\n",
336 SanitizerToolName, SoftRssLimitMb, CurrentRssMb);
337 }
338 }
339 }
340 return atomic_load_relaxed(&RssLimitExceeded);
341 }
342
Kostya Serebryany712fc982016-06-07 01:20:26 +0000343 // Allocates a chunk.
Kostya Kortchinsky006805d2017-04-20 15:11:00 +0000344 void *allocate(uptr Size, uptr Alignment, AllocType Type,
345 bool ForceZeroContents = false) {
Kostya Kortchinsky36b34342017-04-27 20:21:16 +0000346 initThreadMaybe();
Kostya Kortchinsky0ce49992017-06-29 16:45:20 +0000347 if (UNLIKELY(Alignment > MaxAlignment))
Alex Shlyapnikovccab11b2017-06-20 21:23:02 +0000348 return FailureHandler::OnBadRequest();
Kostya Kortchinsky0ce49992017-06-29 16:45:20 +0000349 if (UNLIKELY(Alignment < MinAlignment))
Kostya Serebryany712fc982016-06-07 01:20:26 +0000350 Alignment = MinAlignment;
Kostya Kortchinsky0ce49992017-06-29 16:45:20 +0000351 if (UNLIKELY(Size >= MaxAllowedMallocSize))
Alex Shlyapnikovccab11b2017-06-20 21:23:02 +0000352 return FailureHandler::OnBadRequest();
Kostya Kortchinsky0ce49992017-06-29 16:45:20 +0000353 if (UNLIKELY(Size == 0))
Kostya Kortchinsky006805d2017-04-20 15:11:00 +0000354 Size = 1;
Kostya Kortchinskyc74da7c2016-12-13 19:31:54 +0000355
356 uptr NeededSize = RoundUpTo(Size, MinAlignment) + AlignedChunkHeaderSize;
Kostya Kortchinsky01a66fc2017-05-11 21:40:45 +0000357 uptr AlignedSize = (Alignment > MinAlignment) ?
358 NeededSize + (Alignment - AlignedChunkHeaderSize) : NeededSize;
Kostya Kortchinsky0ce49992017-06-29 16:45:20 +0000359 if (UNLIKELY(AlignedSize >= MaxAllowedMallocSize))
Alex Shlyapnikovccab11b2017-06-20 21:23:02 +0000360 return FailureHandler::OnBadRequest();
Kostya Kortchinskyc74da7c2016-12-13 19:31:54 +0000361
Kostya Kortchinsky58f2656d2017-11-15 16:40:27 +0000362 if (CheckRssLimit && UNLIKELY(isRssLimitExceeded()))
363 return FailureHandler::OnOOM();
364
Kostya Kortchinsky01a66fc2017-05-11 21:40:45 +0000365 // Primary and Secondary backed allocations have a different treatment. We
366 // deal with alignment requirements of Primary serviced allocations here,
367 // but the Secondary will take care of its own alignment needs.
368 bool FromPrimary = PrimaryAllocator::CanAllocate(AlignedSize, MinAlignment);
Kostya Serebryany712fc982016-06-07 01:20:26 +0000369
370 void *Ptr;
Kostya Kortchinsky00582562017-07-12 15:29:08 +0000371 u8 Salt;
Kostya Kortchinskyb44364d2017-07-13 21:01:19 +0000372 uptr AllocSize;
373 if (FromPrimary) {
374 AllocSize = AlignedSize;
Kostya Kortchinsky39248092017-09-22 15:35:37 +0000375 ScudoTSD *TSD = getTSDAndLock();
Kostya Kortchinsky22396c22017-09-25 15:12:08 +0000376 Salt = TSD->Prng.getU8();
377 Ptr = BackendAllocator.allocatePrimary(&TSD->Cache, AllocSize);
378 TSD->unlock();
Kostya Serebryany712fc982016-06-07 01:20:26 +0000379 } else {
Kostya Kortchinskyb44364d2017-07-13 21:01:19 +0000380 {
381 SpinMutexLock l(&GlobalPrngMutex);
382 Salt = GlobalPrng.getU8();
383 }
384 AllocSize = NeededSize;
385 Ptr = BackendAllocator.allocateSecondary(AllocSize, Alignment);
Kostya Serebryany712fc982016-06-07 01:20:26 +0000386 }
Kostya Kortchinsky0ce49992017-06-29 16:45:20 +0000387 if (UNLIKELY(!Ptr))
Alex Shlyapnikovccab11b2017-06-20 21:23:02 +0000388 return FailureHandler::OnOOM();
Kostya Serebryany712fc982016-06-07 01:20:26 +0000389
Kostya Kortchinsky1148dc52016-11-30 17:32:20 +0000390 // If requested, we will zero out the entire contents of the returned chunk.
Kostya Kortchinsky006805d2017-04-20 15:11:00 +0000391 if ((ForceZeroContents || ZeroContents) && FromPrimary)
Kostya Kortchinskyb44364d2017-07-13 21:01:19 +0000392 memset(Ptr, 0, BackendAllocator.getActuallyAllocatedSize(
393 Ptr, /*FromPrimary=*/true));
Kostya Kortchinsky1148dc52016-11-30 17:32:20 +0000394
Kostya Serebryany712fc982016-06-07 01:20:26 +0000395 UnpackedHeader Header = {};
Kostya Kortchinsky01a66fc2017-05-11 21:40:45 +0000396 uptr AllocBeg = reinterpret_cast<uptr>(Ptr);
397 uptr UserBeg = AllocBeg + AlignedChunkHeaderSize;
Kostya Kortchinsky0ce49992017-06-29 16:45:20 +0000398 if (UNLIKELY(!IsAligned(UserBeg, Alignment))) {
Kostya Kortchinsky01a66fc2017-05-11 21:40:45 +0000399 // Since the Secondary takes care of alignment, a non-aligned pointer
400 // means it is from the Primary. It is also the only case where the offset
401 // field of the header would be non-zero.
402 CHECK(FromPrimary);
403 UserBeg = RoundUpTo(UserBeg, Alignment);
404 uptr Offset = UserBeg - AlignedChunkHeaderSize - AllocBeg;
405 Header.Offset = Offset >> MinAlignmentLog;
406 }
Kostya Kortchinskyb44364d2017-07-13 21:01:19 +0000407 CHECK_LE(UserBeg + Size, AllocBeg + AllocSize);
Kostya Serebryany712fc982016-06-07 01:20:26 +0000408 Header.State = ChunkAllocated;
Kostya Serebryany712fc982016-06-07 01:20:26 +0000409 Header.AllocType = Type;
Kostya Kortchinskyfff8e062017-04-20 18:07:17 +0000410 if (FromPrimary) {
Kostya Kortchinskyb44364d2017-07-13 21:01:19 +0000411 Header.FromPrimary = 1;
Kostya Kortchinskyfff8e062017-04-20 18:07:17 +0000412 Header.SizeOrUnusedBytes = Size;
413 } else {
414 // The secondary fits the allocations to a page, so the amount of unused
415 // bytes is the difference between the end of the user allocation and the
416 // next page boundary.
417 uptr PageSize = GetPageSizeCached();
418 uptr TrailingBytes = (UserBeg + Size) & (PageSize - 1);
419 if (TrailingBytes)
420 Header.SizeOrUnusedBytes = PageSize - TrailingBytes;
421 }
Kostya Kortchinskyb44364d2017-07-13 21:01:19 +0000422 Header.Salt = Salt;
Kostya Kortchinsky006805d2017-04-20 15:11:00 +0000423 getScudoChunk(UserBeg)->storeHeader(&Header);
424 void *UserPtr = reinterpret_cast<void *>(UserBeg);
Kostya Serebryany712fc982016-06-07 01:20:26 +0000425 // if (&__sanitizer_malloc_hook) __sanitizer_malloc_hook(UserPtr, Size);
426 return UserPtr;
427 }
428
Kostya Kortchinsky2d944052017-07-24 15:29:38 +0000429 // Place a chunk in the quarantine or directly deallocate it in the event of
430 // a zero-sized quarantine, or if the size of the chunk is greater than the
431 // quarantine chunk size threshold.
Kostya Kortchinskyf1a54fd2017-04-21 18:10:53 +0000432 void quarantineOrDeallocateChunk(ScudoChunk *Chunk, UnpackedHeader *Header,
433 uptr Size) {
Kostya Kortchinsky2d944052017-07-24 15:29:38 +0000434 const bool BypassQuarantine = (AllocatorQuarantine.GetCacheSize() == 0) ||
435 (Size > QuarantineChunksUpToSize);
Kostya Kortchinskyf1a54fd2017-04-21 18:10:53 +0000436 if (BypassQuarantine) {
437 Chunk->eraseHeader();
438 void *Ptr = Chunk->getAllocBeg(Header);
Kostya Kortchinsky2d944052017-07-24 15:29:38 +0000439 if (Header->FromPrimary) {
Kostya Kortchinsky39248092017-09-22 15:35:37 +0000440 ScudoTSD *TSD = getTSDAndLock();
Kostya Kortchinsky22396c22017-09-25 15:12:08 +0000441 getBackendAllocator().deallocatePrimary(&TSD->Cache, Ptr);
442 TSD->unlock();
Kostya Kortchinskyf1a54fd2017-04-21 18:10:53 +0000443 } else {
Kostya Kortchinskyb44364d2017-07-13 21:01:19 +0000444 getBackendAllocator().deallocateSecondary(Ptr);
Kostya Kortchinskyf1a54fd2017-04-21 18:10:53 +0000445 }
446 } else {
Kostya Kortchinsky2d944052017-07-24 15:29:38 +0000447 // If a small memory amount was allocated with a larger alignment, we want
448 // to take that into account. Otherwise the Quarantine would be filled
449 // with tiny chunks, taking a lot of VA memory. This is an approximation
450 // of the usable size, that allows us to not call
451 // GetActuallyAllocatedSize.
452 uptr EstimatedSize = Size + (Header->Offset << MinAlignmentLog);
Kostya Kortchinskyf1a54fd2017-04-21 18:10:53 +0000453 UnpackedHeader NewHeader = *Header;
454 NewHeader.State = ChunkQuarantine;
455 Chunk->compareExchangeHeader(&NewHeader, Header);
Kostya Kortchinsky39248092017-09-22 15:35:37 +0000456 ScudoTSD *TSD = getTSDAndLock();
Kostya Kortchinsky22396c22017-09-25 15:12:08 +0000457 AllocatorQuarantine.Put(getQuarantineCache(TSD),
458 QuarantineCallback(&TSD->Cache),
459 Chunk, EstimatedSize);
460 TSD->unlock();
Kostya Kortchinskyf1a54fd2017-04-21 18:10:53 +0000461 }
462 }
463
Kostya Serebryany712fc982016-06-07 01:20:26 +0000464 // Deallocates a Chunk, which means adding it to the delayed free list (or
465 // Quarantine).
466 void deallocate(void *UserPtr, uptr DeleteSize, AllocType Type) {
Kostya Kortchinsky040c2112017-09-11 19:59:40 +0000467 // For a deallocation, we only ensure minimal initialization, meaning thread
468 // local data will be left uninitialized for now (when using ELF TLS). The
469 // fallback cache will be used instead. This is a workaround for a situation
470 // where the only heap operation performed in a thread would be a free past
471 // the TLS destructors, ending up in initialized thread specific data never
472 // being destroyed properly. Any other heap operation will do a full init.
473 initThreadMaybe(/*MinimalInit=*/true);
Kostya Serebryany712fc982016-06-07 01:20:26 +0000474 // if (&__sanitizer_free_hook) __sanitizer_free_hook(UserPtr);
Kostya Kortchinsky0ce49992017-06-29 16:45:20 +0000475 if (UNLIKELY(!UserPtr))
Kostya Serebryany712fc982016-06-07 01:20:26 +0000476 return;
Kostya Kortchinsky006805d2017-04-20 15:11:00 +0000477 uptr UserBeg = reinterpret_cast<uptr>(UserPtr);
478 if (UNLIKELY(!IsAligned(UserBeg, MinAlignment))) {
Kostya Serebryany712fc982016-06-07 01:20:26 +0000479 dieWithMessage("ERROR: attempted to deallocate a chunk not properly "
480 "aligned at address %p\n", UserPtr);
481 }
Kostya Kortchinsky006805d2017-04-20 15:11:00 +0000482 ScudoChunk *Chunk = getScudoChunk(UserBeg);
Kostya Kortchinsky2d944052017-07-24 15:29:38 +0000483 UnpackedHeader Header;
484 Chunk->loadHeader(&Header);
485 if (UNLIKELY(Header.State != ChunkAllocated)) {
Kostya Serebryany712fc982016-06-07 01:20:26 +0000486 dieWithMessage("ERROR: invalid chunk state when deallocating address "
Kostya Kortchinsky1148dc52016-11-30 17:32:20 +0000487 "%p\n", UserPtr);
Kostya Serebryany712fc982016-06-07 01:20:26 +0000488 }
Kostya Serebryany712fc982016-06-07 01:20:26 +0000489 if (DeallocationTypeMismatch) {
490 // The deallocation type has to match the allocation one.
Kostya Kortchinsky2d944052017-07-24 15:29:38 +0000491 if (Header.AllocType != Type) {
Kostya Serebryany712fc982016-06-07 01:20:26 +0000492 // With the exception of memalign'd Chunks, that can be still be free'd.
Kostya Kortchinsky2d944052017-07-24 15:29:38 +0000493 if (Header.AllocType != FromMemalign || Type != FromMalloc) {
Kostya Kortchinsky43917722017-08-16 16:40:48 +0000494 dieWithMessage("ERROR: allocation type mismatch when deallocating "
495 "address %p\n", UserPtr);
Kostya Serebryany712fc982016-06-07 01:20:26 +0000496 }
497 }
498 }
Kostya Kortchinsky2d944052017-07-24 15:29:38 +0000499 uptr Size = Header.FromPrimary ? Header.SizeOrUnusedBytes :
500 Chunk->getUsableSize(&Header) - Header.SizeOrUnusedBytes;
Kostya Serebryany712fc982016-06-07 01:20:26 +0000501 if (DeleteSizeMismatch) {
502 if (DeleteSize && DeleteSize != Size) {
503 dieWithMessage("ERROR: invalid sized delete on chunk at address %p\n",
Kostya Kortchinsky006805d2017-04-20 15:11:00 +0000504 UserPtr);
Kostya Serebryany712fc982016-06-07 01:20:26 +0000505 }
506 }
Kostya Kortchinsky2d944052017-07-24 15:29:38 +0000507 quarantineOrDeallocateChunk(Chunk, &Header, Size);
Kostya Serebryany712fc982016-06-07 01:20:26 +0000508 }
509
Kostya Serebryany712fc982016-06-07 01:20:26 +0000510 // Reallocates a chunk. We can save on a new allocation if the new requested
511 // size still fits in the chunk.
512 void *reallocate(void *OldPtr, uptr NewSize) {
Kostya Kortchinsky36b34342017-04-27 20:21:16 +0000513 initThreadMaybe();
Kostya Kortchinsky006805d2017-04-20 15:11:00 +0000514 uptr UserBeg = reinterpret_cast<uptr>(OldPtr);
515 if (UNLIKELY(!IsAligned(UserBeg, MinAlignment))) {
516 dieWithMessage("ERROR: attempted to reallocate a chunk not properly "
517 "aligned at address %p\n", OldPtr);
518 }
519 ScudoChunk *Chunk = getScudoChunk(UserBeg);
Kostya Kortchinsky1148dc52016-11-30 17:32:20 +0000520 UnpackedHeader OldHeader;
521 Chunk->loadHeader(&OldHeader);
Kostya Kortchinsky006805d2017-04-20 15:11:00 +0000522 if (UNLIKELY(OldHeader.State != ChunkAllocated)) {
Kostya Kortchinsky1148dc52016-11-30 17:32:20 +0000523 dieWithMessage("ERROR: invalid chunk state when reallocating address "
524 "%p\n", OldPtr);
525 }
Kostya Kortchinsky43917722017-08-16 16:40:48 +0000526 if (DeallocationTypeMismatch) {
527 if (UNLIKELY(OldHeader.AllocType != FromMalloc)) {
528 dieWithMessage("ERROR: allocation type mismatch when reallocating "
529 "address %p\n", OldPtr);
530 }
Kostya Serebryany712fc982016-06-07 01:20:26 +0000531 }
Kostya Kortchinsky006805d2017-04-20 15:11:00 +0000532 uptr UsableSize = Chunk->getUsableSize(&OldHeader);
Kostya Kortchinskyfff8e062017-04-20 18:07:17 +0000533 // The new size still fits in the current chunk, and the size difference
534 // is reasonable.
535 if (NewSize <= UsableSize &&
536 (UsableSize - NewSize) < (SizeClassMap::kMaxSize / 2)) {
Kostya Kortchinskyf1a54fd2017-04-21 18:10:53 +0000537 UnpackedHeader NewHeader = OldHeader;
Kostya Kortchinskyfff8e062017-04-20 18:07:17 +0000538 NewHeader.SizeOrUnusedBytes =
539 OldHeader.FromPrimary ? NewSize : UsableSize - NewSize;
Kostya Serebryany712fc982016-06-07 01:20:26 +0000540 Chunk->compareExchangeHeader(&NewHeader, &OldHeader);
541 return OldPtr;
542 }
543 // Otherwise, we have to allocate a new chunk and copy the contents of the
544 // old one.
545 void *NewPtr = allocate(NewSize, MinAlignment, FromMalloc);
546 if (NewPtr) {
Kostya Kortchinskyfff8e062017-04-20 18:07:17 +0000547 uptr OldSize = OldHeader.FromPrimary ? OldHeader.SizeOrUnusedBytes :
548 UsableSize - OldHeader.SizeOrUnusedBytes;
Kostya Kortchinsky43917722017-08-16 16:40:48 +0000549 memcpy(NewPtr, OldPtr, Min(NewSize, UsableSize));
Kostya Kortchinsky2d944052017-07-24 15:29:38 +0000550 quarantineOrDeallocateChunk(Chunk, &OldHeader, OldSize);
Kostya Serebryany712fc982016-06-07 01:20:26 +0000551 }
552 return NewPtr;
553 }
554
Kostya Kortchinsky1148dc52016-11-30 17:32:20 +0000555 // Helper function that returns the actual usable size of a chunk.
556 uptr getUsableSize(const void *Ptr) {
Kostya Kortchinsky36b34342017-04-27 20:21:16 +0000557 initThreadMaybe();
Kostya Kortchinsky0ce49992017-06-29 16:45:20 +0000558 if (UNLIKELY(!Ptr))
Kostya Kortchinsky1148dc52016-11-30 17:32:20 +0000559 return 0;
Kostya Kortchinsky006805d2017-04-20 15:11:00 +0000560 uptr UserBeg = reinterpret_cast<uptr>(Ptr);
561 ScudoChunk *Chunk = getScudoChunk(UserBeg);
Kostya Kortchinsky1148dc52016-11-30 17:32:20 +0000562 UnpackedHeader Header;
563 Chunk->loadHeader(&Header);
564 // Getting the usable size of a chunk only makes sense if it's allocated.
Kostya Kortchinsky006805d2017-04-20 15:11:00 +0000565 if (UNLIKELY(Header.State != ChunkAllocated)) {
Kostya Kortchinsky1148dc52016-11-30 17:32:20 +0000566 dieWithMessage("ERROR: invalid chunk state when sizing address %p\n",
567 Ptr);
568 }
569 return Chunk->getUsableSize(&Header);
570 }
571
Kostya Serebryany712fc982016-06-07 01:20:26 +0000572 void *calloc(uptr NMemB, uptr Size) {
Kostya Kortchinsky36b34342017-04-27 20:21:16 +0000573 initThreadMaybe();
Kostya Kortchinskyb44364d2017-07-13 21:01:19 +0000574 if (UNLIKELY(CheckForCallocOverflow(NMemB, Size)))
Alex Shlyapnikovccab11b2017-06-20 21:23:02 +0000575 return FailureHandler::OnBadRequest();
Kostya Kortchinsky0ce49992017-06-29 16:45:20 +0000576 return allocate(NMemB * Size, MinAlignment, FromMalloc, true);
Kostya Serebryany712fc982016-06-07 01:20:26 +0000577 }
578
Kostya Kortchinsky39248092017-09-22 15:35:37 +0000579 void commitBack(ScudoTSD *TSD) {
580 AllocatorQuarantine.Drain(getQuarantineCache(TSD),
581 QuarantineCallback(&TSD->Cache));
582 BackendAllocator.destroyCache(&TSD->Cache);
Kostya Serebryany712fc982016-06-07 01:20:26 +0000583 }
Kostya Kortchinsky8d6257b2017-02-03 20:49:42 +0000584
585 uptr getStats(AllocatorStat StatType) {
Kostya Kortchinsky36b34342017-04-27 20:21:16 +0000586 initThreadMaybe();
Kostya Kortchinsky8d6257b2017-02-03 20:49:42 +0000587 uptr stats[AllocatorStatCount];
Kostya Kortchinskyb44364d2017-07-13 21:01:19 +0000588 BackendAllocator.getStats(stats);
Kostya Kortchinsky8d6257b2017-02-03 20:49:42 +0000589 return stats[StatType];
590 }
Kostya Kortchinsky26e689f2017-09-14 20:34:32 +0000591
592 void *handleBadRequest() {
593 initThreadMaybe();
594 return FailureHandler::OnBadRequest();
595 }
Kostya Serebryany712fc982016-06-07 01:20:26 +0000596};
597
Kostya Kortchinsky006805d2017-04-20 15:11:00 +0000598static ScudoAllocator Instance(LINKER_INITIALIZED);
Kostya Serebryany712fc982016-06-07 01:20:26 +0000599
Kostya Kortchinsky006805d2017-04-20 15:11:00 +0000600static ScudoBackendAllocator &getBackendAllocator() {
Kostya Serebryany712fc982016-06-07 01:20:26 +0000601 return Instance.BackendAllocator;
602}
603
Kostya Kortchinskya2b715f2017-11-14 16:14:53 +0000604void initScudo() {
605 Instance.init();
Kostya Serebryany712fc982016-06-07 01:20:26 +0000606}
607
Kostya Kortchinsky22396c22017-09-25 15:12:08 +0000608void ScudoTSD::init(bool Shared) {
609 UnlockRequired = Shared;
Kostya Kortchinskyb44364d2017-07-13 21:01:19 +0000610 getBackendAllocator().initCache(&Cache);
Kostya Kortchinsky00582562017-07-12 15:29:08 +0000611 Prng.init();
Kostya Kortchinsky36b34342017-04-27 20:21:16 +0000612 memset(QuarantineCachePlaceHolder, 0, sizeof(QuarantineCachePlaceHolder));
613}
614
Kostya Kortchinsky39248092017-09-22 15:35:37 +0000615void ScudoTSD::commitBack() {
Kostya Kortchinsky36b34342017-04-27 20:21:16 +0000616 Instance.commitBack(this);
Kostya Serebryany712fc982016-06-07 01:20:26 +0000617}
618
619void *scudoMalloc(uptr Size, AllocType Type) {
Alex Shlyapnikov42bea012017-07-18 19:11:04 +0000620 return SetErrnoOnNull(Instance.allocate(Size, MinAlignment, Type));
Kostya Serebryany712fc982016-06-07 01:20:26 +0000621}
622
623void scudoFree(void *Ptr, AllocType Type) {
624 Instance.deallocate(Ptr, 0, Type);
625}
626
627void scudoSizedFree(void *Ptr, uptr Size, AllocType Type) {
628 Instance.deallocate(Ptr, Size, Type);
629}
630
631void *scudoRealloc(void *Ptr, uptr Size) {
632 if (!Ptr)
Alex Shlyapnikov42bea012017-07-18 19:11:04 +0000633 return SetErrnoOnNull(Instance.allocate(Size, MinAlignment, FromMalloc));
Kostya Serebryany712fc982016-06-07 01:20:26 +0000634 if (Size == 0) {
635 Instance.deallocate(Ptr, 0, FromMalloc);
636 return nullptr;
637 }
Alex Shlyapnikov42bea012017-07-18 19:11:04 +0000638 return SetErrnoOnNull(Instance.reallocate(Ptr, Size));
Kostya Serebryany712fc982016-06-07 01:20:26 +0000639}
640
641void *scudoCalloc(uptr NMemB, uptr Size) {
Alex Shlyapnikov42bea012017-07-18 19:11:04 +0000642 return SetErrnoOnNull(Instance.calloc(NMemB, Size));
Kostya Serebryany712fc982016-06-07 01:20:26 +0000643}
644
645void *scudoValloc(uptr Size) {
Alex Shlyapnikov42bea012017-07-18 19:11:04 +0000646 return SetErrnoOnNull(
647 Instance.allocate(Size, GetPageSizeCached(), FromMemalign));
Kostya Serebryany712fc982016-06-07 01:20:26 +0000648}
649
Kostya Serebryany712fc982016-06-07 01:20:26 +0000650void *scudoPvalloc(uptr Size) {
651 uptr PageSize = GetPageSizeCached();
Kostya Kortchinsky65fdf672017-07-25 21:18:02 +0000652 if (UNLIKELY(CheckForPvallocOverflow(Size, PageSize))) {
Kostya Kortchinsky8d4ba5f2017-10-12 15:01:09 +0000653 errno = ENOMEM;
Kostya Kortchinsky26e689f2017-09-14 20:34:32 +0000654 return Instance.handleBadRequest();
Kostya Kortchinsky65fdf672017-07-25 21:18:02 +0000655 }
Alex Shlyapnikovdf18cbb2017-07-14 21:17:16 +0000656 // pvalloc(0) should allocate one page.
657 Size = Size ? RoundUpTo(Size, PageSize) : PageSize;
Alex Shlyapnikov42bea012017-07-18 19:11:04 +0000658 return SetErrnoOnNull(Instance.allocate(Size, PageSize, FromMemalign));
Kostya Serebryany712fc982016-06-07 01:20:26 +0000659}
660
Kostya Kortchinsky0ce49992017-06-29 16:45:20 +0000661void *scudoMemalign(uptr Alignment, uptr Size) {
Alex Shlyapnikovdf18cbb2017-07-14 21:17:16 +0000662 if (UNLIKELY(!IsPowerOfTwo(Alignment))) {
Kostya Kortchinsky8d4ba5f2017-10-12 15:01:09 +0000663 errno = EINVAL;
Kostya Kortchinsky26e689f2017-09-14 20:34:32 +0000664 return Instance.handleBadRequest();
Alex Shlyapnikovdf18cbb2017-07-14 21:17:16 +0000665 }
Alex Shlyapnikov42bea012017-07-18 19:11:04 +0000666 return SetErrnoOnNull(Instance.allocate(Size, Alignment, FromMemalign));
Kostya Kortchinsky0ce49992017-06-29 16:45:20 +0000667}
668
Kostya Serebryany712fc982016-06-07 01:20:26 +0000669int scudoPosixMemalign(void **MemPtr, uptr Alignment, uptr Size) {
Alex Shlyapnikov42bea012017-07-18 19:11:04 +0000670 if (UNLIKELY(!CheckPosixMemalignAlignment(Alignment))) {
Kostya Kortchinsky26e689f2017-09-14 20:34:32 +0000671 Instance.handleBadRequest();
Kostya Kortchinsky8d4ba5f2017-10-12 15:01:09 +0000672 return EINVAL;
Kostya Kortchinsky0ce49992017-06-29 16:45:20 +0000673 }
Alex Shlyapnikovdf18cbb2017-07-14 21:17:16 +0000674 void *Ptr = Instance.allocate(Size, Alignment, FromMemalign);
Alex Shlyapnikov42bea012017-07-18 19:11:04 +0000675 if (UNLIKELY(!Ptr))
Kostya Kortchinsky8d4ba5f2017-10-12 15:01:09 +0000676 return ENOMEM;
Alex Shlyapnikovdf18cbb2017-07-14 21:17:16 +0000677 *MemPtr = Ptr;
Kostya Serebryany712fc982016-06-07 01:20:26 +0000678 return 0;
679}
680
681void *scudoAlignedAlloc(uptr Alignment, uptr Size) {
Alex Shlyapnikov42bea012017-07-18 19:11:04 +0000682 if (UNLIKELY(!CheckAlignedAllocAlignmentAndSize(Alignment, Size))) {
Kostya Kortchinsky8d4ba5f2017-10-12 15:01:09 +0000683 errno = EINVAL;
Kostya Kortchinsky26e689f2017-09-14 20:34:32 +0000684 return Instance.handleBadRequest();
Alex Shlyapnikovdf18cbb2017-07-14 21:17:16 +0000685 }
Alex Shlyapnikov42bea012017-07-18 19:11:04 +0000686 return SetErrnoOnNull(Instance.allocate(Size, Alignment, FromMalloc));
Kostya Serebryany712fc982016-06-07 01:20:26 +0000687}
688
689uptr scudoMallocUsableSize(void *Ptr) {
690 return Instance.getUsableSize(Ptr);
691}
692
Kostya Kortchinsky1148dc52016-11-30 17:32:20 +0000693} // namespace __scudo
Kostya Serebryany712fc982016-06-07 01:20:26 +0000694
695using namespace __scudo;
696
697// MallocExtension helper functions
698
699uptr __sanitizer_get_current_allocated_bytes() {
Kostya Kortchinsky8d6257b2017-02-03 20:49:42 +0000700 return Instance.getStats(AllocatorStatAllocated);
Kostya Serebryany712fc982016-06-07 01:20:26 +0000701}
702
703uptr __sanitizer_get_heap_size() {
Kostya Kortchinsky8d6257b2017-02-03 20:49:42 +0000704 return Instance.getStats(AllocatorStatMapped);
Kostya Serebryany712fc982016-06-07 01:20:26 +0000705}
706
707uptr __sanitizer_get_free_bytes() {
708 return 1;
709}
710
711uptr __sanitizer_get_unmapped_bytes() {
712 return 1;
713}
714
715uptr __sanitizer_get_estimated_allocated_size(uptr size) {
716 return size;
717}
718
Kostya Kortchinsky1148dc52016-11-30 17:32:20 +0000719int __sanitizer_get_ownership(const void *Ptr) {
720 return Instance.isValidPointer(Ptr);
Kostya Serebryany712fc982016-06-07 01:20:26 +0000721}
722
Kostya Kortchinsky1148dc52016-11-30 17:32:20 +0000723uptr __sanitizer_get_allocated_size(const void *Ptr) {
724 return Instance.getUsableSize(Ptr);
Kostya Serebryany712fc982016-06-07 01:20:26 +0000725}