Debian Codegraph @

js/src/gc/Memory.cpp

raw
1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*-
2 * vim: set ts=8 sts=2 et sw=2 tw=80:
3 * This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6
7 #include "gc/Memory.h"
8
9 #include "mozilla/MathAlgorithms.h"
10 #include "mozilla/RandomNum.h"
11 #include "mozilla/TaggedAnonymousMemory.h"
12
13 #include "jit/JitOptions.h"
14 #include "js/HeapAPI.h"
15 #include "js/Utility.h"
16
17 #ifdef MOZ_MEMORY
18 # include "mozmemory_utils.h"
19 #endif
20
21 #include "util/Memory.h"
22
23 #ifdef XP_WIN
24
25 # include "util/WindowsWrapper.h"
26 # include <psapi.h>
27
28 #else
29
30 # include <algorithm>
31 # include <errno.h>
32 # include <unistd.h>
33
34 # if !defined(__wasi__)
35 # include <sys/mman.h>
36 # include <sys/resource.h>
37 # include <sys/stat.h>
38 # include <sys/types.h>
39 # endif // !defined(__wasi__)
40
41 #endif // !XP_WIN
42
43 #if defined(XP_WIN) && !defined(MOZ_MEMORY)
44 namespace mozilla {
45 // On Windows platforms, mozjemalloc provides MozVirtualAlloc, a version of
46 // VirtualAlloc that will sleep and retry on failure. This is a shim for when
47 // that function is not available.
48 MOZ_ALWAYS_INLINE void* MozVirtualAlloc(LPVOID lpAddress, SIZE_T dwSize,
49 DWORD flAllocationType,
50 DWORD flProtect) {
51 return VirtualAlloc(lpAddress, dwSize, flAllocationType, flProtect);
52 }
53 } // namespace mozilla
54 #endif // defined(XP_WIN) && !defined(MOZ_MEMORY)
55
56 namespace js::gc {
57
58 /*
59 * System allocation functions generally require the allocation size
60 * to be an integer multiple of the page size of the running process.
61 */
62 static size_t pageSize = 0;
63
64 /* The OS allocation granularity may not match the page size. */
65 static size_t allocGranularity = 0;
66
67 /* The number of bits used by addresses on this platform. */
68 static size_t numAddressBits = 0;
69
70 /* An estimate of the number of bytes available for virtual memory. */
71 static size_t virtualMemoryLimit = size_t(-1);
72
73 /* Whether decommit is enabled. */
74 static bool decommitEnabled = false;
75
76 /* Whether DisableDecommit() has been called. */
77 static bool disableDecommitRequested = false;
78
79 /*
80 * System allocation functions may hand out regions of memory in increasing or
81 * decreasing order. This ordering is used as a hint during chunk alignment to
82 * reduce the number of system calls. On systems with 48-bit addresses, our
83 * workarounds to obtain 47-bit pointers cause addresses to be handed out in
84 * increasing order.
85 *
86 * We do not use the growth direction on Windows, as constraints on VirtualAlloc
87 * would make its application failure prone and complex. Tests indicate that
88 * VirtualAlloc always hands out regions of memory in increasing order.
89 */
90 #if defined(XP_DARWIN)
91 static mozilla::Atomic<int, mozilla::Relaxed> growthDirection(1);
92 #elif defined(XP_UNIX)
93 static mozilla::Atomic<int, mozilla::Relaxed> growthDirection(0);
94 #endif
95
96 /*
97 * Data from OOM crashes shows there may be up to 24 chunk-sized but unusable
98 * chunks available in low memory situations. These chunks may all need to be
99 * used up before we gain access to remaining *alignable* chunk-sized regions,
100 * so we use a generous limit of 32 unusable chunks to ensure we reach them.
101 */
102 static const int MaxLastDitchAttempts = 32;
103
104 #ifdef JS_64BIT
105 /*
106 * On some 64-bit platforms we can use a random, scattershot allocator that
107 * tries addresses from the available range at random. If the address range
108 * is large enough this will have a high chance of success and additionally
109 * makes the memory layout of our process less predictable.
110 *
111 * However, not all 64-bit platforms have a very large address range. For
112 * example, AArch64 on Linux defaults to using 39-bit addresses to limit the
113 * number of translation tables used. On such configurations the scattershot
114 * approach to allocation creates a conflict with our desire to reserve large
115 * regions of memory for applications like WebAssembly: Small allocations may
116 * inadvertently block off all available 4-6GiB regions, and conversely
117 * reserving such regions may lower the success rate for smaller allocations to
118 * unacceptable levels.
119 *
120 * So we make a compromise: Instead of using the scattershot on all 64-bit
121 * platforms, we only use it on platforms that meet a minimum requirement for
122 * the available address range. In addition we split the address range,
123 * reserving the upper half for huge allocations and the lower half for smaller
124 * allocations. We use a limit of 43 bits so that at least 42 bits are available
125 * for huge allocations - this matches the 8TiB per process address space limit
126 * that we're already subject to on Windows.
127 */
128 static const size_t MinAddressBitsForRandomAlloc = 43;
129
130 /* The lower limit for huge allocations. This is fairly arbitrary. */
131 static const size_t HugeAllocationSize = 1024 * 1024 * 1024;
132
133 /* The minimum and maximum valid addresses that can be allocated into. */
134 static size_t minValidAddress = 0;
135 static size_t maxValidAddress = 0;
136
137 /* The upper limit for smaller allocations and the lower limit for huge ones. */
138 static size_t hugeSplit = 0;
139 #endif
140
141 /* Running totals to report to the profiler. */
142 mozilla::Atomic<size_t, mozilla::Relaxed> gMappedMemorySizeBytes;
143 mozilla::Atomic<uint64_t, mozilla::Relaxed> gMappedMemoryOperations;
144
145 size_t SystemPageSize() { return pageSize; }
146
147 size_t SystemAddressBits() { return numAddressBits; }
148
149 size_t VirtualMemoryLimit() { return virtualMemoryLimit; }
150
151 bool UsingScattershotAllocator() {
152 #ifdef JS_64BIT
153 return numAddressBits >= MinAddressBitsForRandomAlloc;
154 #else
155 return false;
156 #endif
157 }
158
159 enum class Commit : bool {
160 No = false,
161 Yes = true,
162 };
163
164 #ifdef XP_WIN
165 enum class PageAccess : DWORD {
166 None = PAGE_NOACCESS,
167 Read = PAGE_READONLY,
168 ReadWrite = PAGE_READWRITE,
169 Execute = PAGE_EXECUTE,
170 ReadExecute = PAGE_EXECUTE_READ,
171 ReadWriteExecute = PAGE_EXECUTE_READWRITE,
172 };
173 #elif defined(__wasi__)
174 enum class PageAccess : int {
175 None = 0,
176 Read = 0,
177 ReadWrite = 0,
178 Execute = 0,
179 ReadExecute = 0,
180 ReadWriteExecute = 0,
181 };
182 #else
183 enum class PageAccess : int {
184 None = PROT_NONE,
185 Read = PROT_READ,
186 ReadWrite = PROT_READ | PROT_WRITE,
187 Execute = PROT_EXEC,
188 ReadExecute = PROT_READ | PROT_EXEC,
189 ReadWriteExecute = PROT_READ | PROT_WRITE | PROT_EXEC,
190 };
191 #endif
192
193 template <bool AlwaysGetNew = true>
194 static bool TryToAlignChunk(void** aRegion, void** aRetainedRegion,
195 size_t length, size_t alignment);
196
197 #ifndef __wasi__
198 static void* MapAlignedPagesSlow(size_t length, size_t alignment);
199 #endif // wasi
200 static void* MapAlignedPagesLastDitch(size_t length, size_t alignment,
201 StallAndRetry stallAndRetry);
202
203 #ifdef JS_64BIT
204 static void* MapAlignedPagesRandom(size_t length, size_t alignment);
205 #endif
206
207 void* TestMapAlignedPagesLastDitch(size_t length, size_t alignment) {
208 void* region = MapAlignedPagesLastDitch(length, alignment, StallAndRetry::No);
209 if (region) {
210 RecordMemoryAlloc(length);
211 }
212 return region;
213 }
214
215 bool DecommitEnabled() { return decommitEnabled; }
216
217 void DisableDecommit() {
218 MOZ_RELEASE_ASSERT(
219 pageSize == 0,
220 "DisableDecommit should be called before InitMemorySubsystem");
221 disableDecommitRequested = true;
222 }
223
224 /* Returns the offset from the nearest aligned address at or below |region|. */
225 static inline size_t OffsetFromAligned(void* region, size_t alignment) {
226 return uintptr_t(region) % alignment;
227 }
228
229 template <Commit commit, StallAndRetry retry = StallAndRetry::No>
230 static inline void* MapInternal(void* desired, size_t length) {
231 void* region = nullptr;
232 #ifdef XP_WIN
233 DWORD flags =
234 (commit == Commit::Yes ? MEM_RESERVE | MEM_COMMIT : MEM_RESERVE);
235 if constexpr (retry == StallAndRetry::Yes) {
236 region = mozilla::MozVirtualAlloc(desired, length, flags,
237 DWORD(PageAccess::ReadWrite));
238 } else {
239 region = VirtualAlloc(desired, length, flags, DWORD(PageAccess::ReadWrite));
240 }
241 #elif defined(__wasi__)
242 if (int err = posix_memalign(&region, gc::SystemPageSize(), length)) {
243 MOZ_RELEASE_ASSERT(err == ENOMEM);
244 return nullptr;
245 }
246 if (region) {
247 memset(region, 0, length);
248 }
249 #else
250 int flags = MAP_PRIVATE | MAP_ANON;
251 region = MozTaggedAnonymousMmap(desired, length, int(PageAccess::ReadWrite),
252 flags, -1, 0, "js-gc-heap");
253 if (region == MAP_FAILED) {
254 return nullptr;
255 }
256 #endif
257 return region;
258 }
259
260 static inline void UnmapInternal(void* region, size_t length) {
261 MOZ_ASSERT(region && OffsetFromAligned(region, allocGranularity) == 0);
262 MOZ_ASSERT(length > 0 && length % pageSize == 0);
263
264 #ifdef XP_WIN
265 MOZ_RELEASE_ASSERT(VirtualFree(region, 0, MEM_RELEASE) != 0);
266 #elif defined(__wasi__)
267 free(region);
268 #else
269 if (munmap(region, length)) {
270 MOZ_RELEASE_ASSERT(errno == ENOMEM);
271 }
272 #endif
273 }
274
275 template <Commit commit = Commit::Yes, StallAndRetry retry = StallAndRetry::No>
276 static inline void* MapMemory(size_t length) {
277 MOZ_ASSERT(length > 0);
278
279 return MapInternal<commit, retry>(nullptr, length);
280 }
281
282 /*
283 * Attempts to map memory at the given address, but allows the system
284 * to return a different address that may still be suitable.
285 */
286 template <Commit commit = Commit::Yes>
287 static inline void* MapMemoryAtFuzzy(void* desired, size_t length) {
288 MOZ_ASSERT(desired && OffsetFromAligned(desired, allocGranularity) == 0);
289 MOZ_ASSERT(length > 0);
290
291 // Note that some platforms treat the requested address as a hint, so the
292 // returned address might not match the requested address.
293 return MapInternal<commit>(desired, length);
294 }
295
296 /*
297 * Attempts to map memory at the given address, returning nullptr if
298 * the system returns any address other than the requested one.
299 */
300 template <Commit commit = Commit::Yes>
301 static inline void* MapMemoryAt(void* desired, size_t length) {
302 MOZ_ASSERT(desired && OffsetFromAligned(desired, allocGranularity) == 0);
303 MOZ_ASSERT(length > 0);
304
305 void* region = MapInternal<commit>(desired, length);
306 if (!region) {
307 return nullptr;
308 }
309
310 // On some platforms mmap treats the desired address as a hint, so
311 // check that the address we got is the address we requested.
312 if (region != desired) {
313 UnmapInternal(region, length);
314 return nullptr;
315 }
316 return region;
317 }
318
319 #ifdef JS_64BIT
320
321 /* Returns a random number in the given range. */
322 static inline uint64_t GetNumberInRange(uint64_t minNum, uint64_t maxNum) {
323 const uint64_t MaxRand = UINT64_C(0xffffffffffffffff);
324 maxNum -= minNum;
325 uint64_t binSize = 1 + (MaxRand - maxNum) / (maxNum + 1);
326
327 uint64_t rndNum;
328 do {
329 mozilla::Maybe<uint64_t> result;
330 do {
331 result = mozilla::RandomUint64();
332 } while (!result);
333 rndNum = result.value() / binSize;
334 } while (rndNum > maxNum);
335
336 return minNum + rndNum;
337 }
338
339 # ifndef XP_WIN
340 static inline uint64_t FindAddressLimitInner(size_t highBit, size_t tries);
341
342 /*
343 * The address range available to applications depends on both hardware and
344 * kernel configuration. For example, AArch64 on Linux uses addresses with
345 * 39 significant bits by default, but can be configured to use addresses with
346 * 48 significant bits by enabling a 4th translation table. Unfortunately,
347 * there appears to be no standard way to query the limit at runtime
348 * (Windows exposes this via GetSystemInfo()).
349 *
350 * This function tries to find the address limit by performing a binary search
351 * on the index of the most significant set bit in the addresses it attempts to
352 * allocate. As the requested address is often treated as a hint by the
353 * operating system, we use the actual returned addresses to narrow the range.
354 * We return the number of bits of an address that may be set.
355 */
356 static size_t FindAddressLimit() {
357 // Use 32 bits as a lower bound in case we keep getting nullptr.
358 uint64_t low = 31;
359 uint64_t highestSeen = (UINT64_C(1) << 32) - allocGranularity - 1;
360
361 // Exclude 48-bit and 47-bit addresses first.
362 uint64_t high = 47;
363 for (; high >= std::max(low, UINT64_C(46)); --high) {
364 highestSeen = std::max(FindAddressLimitInner(high, 4), highestSeen);
365 low = mozilla::FloorLog2(highestSeen);
366 }
367 // If those didn't work, perform a modified binary search.
368 while (high - 1 > low) {
369 uint64_t middle = low + (high - low) / 2;
370 highestSeen = std::max(FindAddressLimitInner(middle, 4), highestSeen);
371 low = mozilla::FloorLog2(highestSeen);
372 if (highestSeen < (UINT64_C(1) << middle)) {
373 high = middle;
374 }
375 }
376 // We can be sure of the lower bound, but check the upper bound again.
377 do {
378 high = low + 1;
379 highestSeen = std::max(FindAddressLimitInner(high, 8), highestSeen);
380 low = mozilla::FloorLog2(highestSeen);
381 } while (low >= high);
382
383 // `low` is the highest set bit, so `low + 1` is the number of bits.
384 return low + 1;
385 }
386
387 static inline uint64_t FindAddressLimitInner(size_t highBit, size_t tries) {
388 const size_t length = allocGranularity; // Used as both length and alignment.
389
390 uint64_t highestSeen = 0;
391 uint64_t startRaw = UINT64_C(1) << highBit;
392 uint64_t endRaw = 2 * startRaw - length - 1;
393 uint64_t start = (startRaw + length - 1) / length;
394 uint64_t end = (endRaw - (length - 1)) / length;
395 for (size_t i = 0; i < tries; ++i) {
396 uint64_t desired = length * GetNumberInRange(start, end);
397 void* address = MapMemoryAtFuzzy(reinterpret_cast<void*>(desired), length);
398 uint64_t actual = uint64_t(address);
399 if (address) {
400 UnmapInternal(address, length);
401 }
402 if (actual > highestSeen) {
403 highestSeen = actual;
404 if (actual >= startRaw) {
405 break;
406 }
407 }
408 }
409 return highestSeen;
410 }
411 # endif // !defined(XP_WIN)
412
413 #endif // defined(JS_64BIT)
414
415 void InitMemorySubsystem() {
416 if (pageSize == 0) {
417 #ifdef XP_WIN
418 SYSTEM_INFO sysinfo;
419 GetSystemInfo(&sysinfo);
420 pageSize = sysinfo.dwPageSize;
421 allocGranularity = sysinfo.dwAllocationGranularity;
422 #else
423 pageSize = size_t(sysconf(_SC_PAGESIZE));
424 allocGranularity = pageSize;
425 #endif
426
427 // Decommit is supported if the system page size is the size as the
428 // compile time constant and has not been disabled.
429 decommitEnabled = pageSize == PageSize && !disableDecommitRequested;
430
431 #ifdef JS_64BIT
432 # ifdef XP_WIN
433 minValidAddress = size_t(sysinfo.lpMinimumApplicationAddress);
434 maxValidAddress = size_t(sysinfo.lpMaximumApplicationAddress);
435 numAddressBits = mozilla::FloorLog2(maxValidAddress) + 1;
436 # else
437 // No standard way to determine these, so fall back to FindAddressLimit().
438 numAddressBits = FindAddressLimit();
439 minValidAddress = allocGranularity;
440 maxValidAddress = (UINT64_C(1) << numAddressBits) - 1 - allocGranularity;
441 # endif
442 // Sanity check the address to ensure we don't use more than 47 bits.
443 uint64_t maxJSAddress = UINT64_C(0x00007fffffffffff) - allocGranularity;
444 if (maxValidAddress > maxJSAddress) {
445 maxValidAddress = maxJSAddress;
446 hugeSplit = UINT64_C(0x00003fffffffffff) - allocGranularity;
447 } else {
448 hugeSplit = (UINT64_C(1) << (numAddressBits - 1)) - 1 - allocGranularity;
449 }
450 #else // !defined(JS_64BIT)
451 numAddressBits = 32;
452 #endif
453 #ifdef RLIMIT_AS
454 if (jit::HasJitBackend()) {
455 rlimit as_limit;
456 if (getrlimit(RLIMIT_AS, &as_limit) == 0 &&
457 as_limit.rlim_max != RLIM_INFINITY) {
458 virtualMemoryLimit = as_limit.rlim_max;
459 }
460 }
461 #endif
462 }
463
464 MOZ_ASSERT(gMappedMemorySizeBytes == 0);
465 }
466
467 void CheckMemorySubsystemOnShutDown() {
468 MOZ_ASSERT(gMappedMemorySizeBytes == 0);
469 }
470
471 #ifdef JS_64BIT
472 /* The JS engine uses 47-bit pointers; all higher bits must be clear. */
473 static inline bool IsInvalidRegion(void* region, size_t length) {
474 const uint64_t invalidPointerMask = UINT64_C(0xffff800000000000);
475 return (uintptr_t(region) + length - 1) & invalidPointerMask;
476 }
477 #endif
478
479 void* MapAlignedPages(size_t length, size_t alignment,
480 StallAndRetry stallAndRetry) {
481 MOZ_RELEASE_ASSERT(length > 0 && alignment > 0);
482 MOZ_RELEASE_ASSERT(length % pageSize == 0);
483 MOZ_RELEASE_ASSERT(std::max(alignment, allocGranularity) %
484 std::min(alignment, allocGranularity) ==
485 0);
486
487 // Smaller alignments aren't supported by the allocation functions.
488 if (alignment < allocGranularity) {
489 alignment = allocGranularity;
490 }
491
492 #ifdef __wasi__
493 void* region = nullptr;
494 if (int err = posix_memalign(&region, alignment, length)) {
495 MOZ_ASSERT(err == ENOMEM);
496 (void)err;
497 return nullptr;
498 }
499 MOZ_ASSERT(region != nullptr);
500 memset(region, 0, length);
501 return region;
502 #else
503
504 # ifdef JS_64BIT
505 // Use the scattershot allocator if the address range is large enough.
506 if (UsingScattershotAllocator()) {
507 void* region = MapAlignedPagesRandom(length, alignment);
508
509 MOZ_RELEASE_ASSERT(!IsInvalidRegion(region, length));
510 MOZ_ASSERT(OffsetFromAligned(region, alignment) == 0);
511
512 RecordMemoryAlloc(length);
513 return region;
514 }
515 # endif
516
517 // Try to allocate the region.
518 void* region = MapMemory(length);
519 if (!region) {
520 return nullptr;
521 }
522
523 // If the returned address is aligned, we're done.
524 if (OffsetFromAligned(region, alignment) == 0) {
525 RecordMemoryAlloc(length);
526 return region;
527 }
528
529 // Try to align the region. On success, TryToAlignChunk() returns
530 // true and we can return the aligned region immediately.
531 void* retainedRegion;
532 if (TryToAlignChunk(&region, &retainedRegion, length, alignment)) {
533 MOZ_ASSERT(region && OffsetFromAligned(region, alignment) == 0);
534 MOZ_ASSERT(!retainedRegion);
535 RecordMemoryAlloc(length);
536 return region;
537 }
538
539 // On failure, the unaligned region is retained unless we OOMed. We don't
540 // use the retained region on this path (see the last ditch allocator).
541 if (retainedRegion) {
542 UnmapInternal(retainedRegion, length);
543 }
544
545 // If it fails to align the given region, TryToAlignChunk() returns the
546 // next valid region that we might be able to align (unless we OOMed).
547 if (region) {
548 MOZ_ASSERT(OffsetFromAligned(region, alignment) != 0);
549 UnmapInternal(region, length);
550 }
551
552 // Since we couldn't align the first region, fall back to allocating a
553 // region large enough that we can definitely align it.
554 region = MapAlignedPagesSlow(length, alignment);
555 if (!region) {
556 // If there wasn't enough contiguous address space left for that,
557 // try to find an alignable region using the last ditch allocator.
558 region = MapAlignedPagesLastDitch(length, alignment, stallAndRetry);
559 if (!region) {
560 return nullptr;
561 }
562 }
563
564 // At this point we should have an aligned region.
565 MOZ_ASSERT(OffsetFromAligned(region, alignment) == 0);
566
567 RecordMemoryAlloc(length);
568 return region;
569 #endif // !__wasi__
570 }
571
572 #ifdef JS_64BIT
573
574 /*
575 * This allocator takes advantage of the large address range on some 64-bit
576 * platforms to allocate in a scattershot manner, choosing addresses at random
577 * from the range. By controlling the range we can avoid returning addresses
578 * that have more than 47 significant bits (as required by SpiderMonkey).
579 * This approach also has some other advantages over the methods employed by
580 * the other allocation functions in this file:
581 * 1) Allocations are extremely likely to succeed on the first try.
582 * 2) The randomness makes our memory layout becomes harder to predict.
583 * 3) The low probability of reusing regions guards against use-after-free.
584 *
585 * The main downside is that detecting physical OOM situations becomes more
586 * difficult; to guard against this, we occasionally try a regular allocation.
587 * In addition, sprinkling small allocations throughout the full address range
588 * might get in the way of large address space reservations such as those
589 * employed by WebAssembly. To avoid this (or the opposite problem of such
590 * reservations reducing the chance of success for smaller allocations) we
591 * split the address range in half, with one half reserved for huge allocations
592 * and the other for regular (usually chunk sized) allocations.
593 */
594 static void* MapAlignedPagesRandom(size_t length, size_t alignment) {
595 uint64_t minNum, maxNum;
596 if (length < HugeAllocationSize) {
597 // Use the lower half of the range.
598 minNum = (minValidAddress + alignment - 1) / alignment;
599 maxNum = (hugeSplit - (length - 1)) / alignment;
600 } else {
601 // Use the upper half of the range.
602 minNum = (hugeSplit + 1 + alignment - 1) / alignment;
603 maxNum = (maxValidAddress - (length - 1)) / alignment;
604 }
605
606 // Try to allocate in random aligned locations.
607 void* region = nullptr;
608 for (size_t i = 1; i <= 1024; ++i) {
609 if (i & 0xf) {
610 uint64_t desired = alignment * GetNumberInRange(minNum, maxNum);
611 region = MapMemoryAtFuzzy(reinterpret_cast<void*>(desired), length);
612 if (!region) {
613 continue;
614 }
615 } else {
616 // Check for OOM.
617 region = MapMemory(length);
618 if (!region) {
619 return nullptr;
620 }
621 }
622 if (IsInvalidRegion(region, length)) {
623 UnmapInternal(region, length);
624 continue;
625 }
626 if (OffsetFromAligned(region, alignment) == 0) {
627 return region;
628 }
629 void* retainedRegion = nullptr;
630 if (TryToAlignChunk<false>(&region, &retainedRegion, length, alignment)) {
631 MOZ_ASSERT(region && OffsetFromAligned(region, alignment) == 0);
632 MOZ_ASSERT(!retainedRegion);
633 return region;
634 }
635 MOZ_ASSERT(region && !retainedRegion);
636 UnmapInternal(region, length);
637 }
638
639 if (numAddressBits < 48) {
640 // Try the reliable fallback of overallocating.
641 // Note: This will not respect the address space split.
642 region = MapAlignedPagesSlow(length, alignment);
643 if (region) {
644 return region;
645 }
646 }
647 if (length < HugeAllocationSize) {
648 MOZ_CRASH("Couldn't allocate even after 1000 tries!");
649 }
650
651 return nullptr;
652 }
653
654 #endif // defined(JS_64BIT)
655
656 #ifndef __wasi__
657 static void* MapAlignedPagesSlow(size_t length, size_t alignment) {
658 void* alignedRegion = nullptr;
659 do {
660 size_t reserveLength = length + alignment - pageSize;
661 # ifdef XP_WIN
662 // Don't commit the requested pages as we won't use the region directly.
663 void* region = MapMemory<Commit::No>(reserveLength);
664 # else
665 void* region = MapMemory(reserveLength);
666 # endif
667 if (!region) {
668 return nullptr;
669 }
670 alignedRegion =
671 reinterpret_cast<void*>(AlignBytes(uintptr_t(region), alignment));
672 # ifdef XP_WIN
673 // Windows requires that map and unmap calls be matched, so deallocate
674 // and immediately reallocate at the desired (aligned) address.
675 UnmapInternal(region, reserveLength);
676 alignedRegion = MapMemoryAt(alignedRegion, length);
677 # else
678 // munmap allows us to simply unmap the pages that don't interest us.
679 if (alignedRegion != region) {
680 UnmapInternal(region, uintptr_t(alignedRegion) - uintptr_t(region));
681 }
682 void* regionEnd =
683 reinterpret_cast<void*>(uintptr_t(region) + reserveLength);
684 void* alignedEnd =
685 reinterpret_cast<void*>(uintptr_t(alignedRegion) + length);
686 if (alignedEnd != regionEnd) {
687 UnmapInternal(alignedEnd, uintptr_t(regionEnd) - uintptr_t(alignedEnd));
688 }
689 # endif
690 // On Windows we may have raced with another thread; if so, try again.
691 } while (!alignedRegion);
692
693 return alignedRegion;
694 }
695 #endif // wasi
696
697 /*
698 * In a low memory or high fragmentation situation, alignable chunks of the
699 * desired length may still be available, even if there are no more contiguous
700 * free chunks that meet the |length + alignment - pageSize| requirement of
701 * MapAlignedPagesSlow. In this case, try harder to find an alignable chunk
702 * by temporarily holding onto the unaligned parts of each chunk until the
703 * allocator gives us a chunk that either is, or can be aligned.
704 */
705 static void* MapAlignedPagesLastDitch(size_t length, size_t alignment,
706 StallAndRetry stallAndRetry) {
707 void* tempMaps[MaxLastDitchAttempts];
708 int attempt = 0;
709 void* region;
710
711 if (stallAndRetry == StallAndRetry::Yes) {
712 region = MapMemory<Commit::Yes, StallAndRetry::Yes>(length);
713 } else {
714 region = MapMemory<Commit::Yes, StallAndRetry::No>(length);
715 }
716
717 if (OffsetFromAligned(region, alignment) == 0) {
718 return region;
719 }
720 for (; attempt < MaxLastDitchAttempts; ++attempt) {
721 if (TryToAlignChunk(&region, tempMaps + attempt, length, alignment)) {
722 MOZ_ASSERT(region && OffsetFromAligned(region, alignment) == 0);
723 MOZ_ASSERT(!tempMaps[attempt]);
724 break; // Success!
725 }
726 if (!region || !tempMaps[attempt]) {
727 break; // We ran out of memory, so give up.
728 }
729 }
730 if (OffsetFromAligned(region, alignment)) {
731 UnmapInternal(region, length);
732 region = nullptr;
733 }
734 while (--attempt >= 0) {
735 UnmapInternal(tempMaps[attempt], length);
736 }
737 return region;
738 }
739
740 #ifdef XP_WIN
741
742 /*
743 * On Windows, map and unmap calls must be matched, so we deallocate the
744 * unaligned chunk, then reallocate the unaligned part to block off the
745 * old address and force the allocator to give us a new one.
746 */
747 template <bool>
748 static bool TryToAlignChunk(void** aRegion, void** aRetainedRegion,
749 size_t length, size_t alignment) {
750 void* region = *aRegion;
751 MOZ_ASSERT(region && OffsetFromAligned(region, alignment) != 0);
752
753 size_t retainedLength = 0;
754 void* retainedRegion = nullptr;
755 do {
756 size_t offset = OffsetFromAligned(region, alignment);
757 if (offset == 0) {
758 // If the address is aligned, either we hit OOM or we're done.
759 break;
760 }
761 UnmapInternal(region, length);
762 retainedLength = alignment - offset;
763 retainedRegion = MapMemoryAt<Commit::No>(region, retainedLength);
764 region = MapMemory(length);
765
766 // If retainedRegion is null here, we raced with another thread.
767 } while (!retainedRegion);
768
769 bool result = OffsetFromAligned(region, alignment) == 0;
770 if (result && retainedRegion) {
771 UnmapInternal(retainedRegion, retainedLength);
772 retainedRegion = nullptr;
773 }
774
775 *aRegion = region;
776 *aRetainedRegion = retainedRegion;
777 return region && result;
778 }
779
780 #else // !defined(XP_WIN)
781
782 /*
783 * mmap calls don't have to be matched with calls to munmap, so we can unmap
784 * just the pages we don't need. However, as we don't know a priori if addresses
785 * are handed out in increasing or decreasing order, we have to try both
786 * directions (depending on the environment, one will always fail).
787 */
788 template <bool AlwaysGetNew>
789 static bool TryToAlignChunk(void** aRegion, void** aRetainedRegion,
790 size_t length, size_t alignment) {
791 void* regionStart = *aRegion;
792 MOZ_ASSERT(regionStart && OffsetFromAligned(regionStart, alignment) != 0);
793
794 bool addressesGrowUpward = growthDirection > 0;
795 bool directionUncertain = -8 < growthDirection && growthDirection <= 8;
796 size_t offsetLower = OffsetFromAligned(regionStart, alignment);
797 size_t offsetUpper = alignment - offsetLower;
798 for (size_t i = 0; i < 2; ++i) {
799 if (addressesGrowUpward) {
800 void* upperStart =
801 reinterpret_cast<void*>(uintptr_t(regionStart) + offsetUpper);
802 void* regionEnd =
803 reinterpret_cast<void*>(uintptr_t(regionStart) + length);
804 if (MapMemoryAt(regionEnd, offsetUpper)) {
805 UnmapInternal(regionStart, offsetUpper);
806 if (directionUncertain) {
807 ++growthDirection;
808 }
809 regionStart = upperStart;
810 break;
811 }
812 } else {
813 auto* lowerStart =
814 reinterpret_cast<void*>(uintptr_t(regionStart) - offsetLower);
815 auto* lowerEnd = reinterpret_cast<void*>(uintptr_t(lowerStart) + length);
816 if (MapMemoryAt(lowerStart, offsetLower)) {
817 UnmapInternal(lowerEnd, offsetLower);
818 if (directionUncertain) {
819 --growthDirection;
820 }
821 regionStart = lowerStart;
822 break;
823 }
824 }
825 // If we're confident in the growth direction, don't try the other.
826 if (!directionUncertain) {
827 break;
828 }
829 addressesGrowUpward = !addressesGrowUpward;
830 }
831
832 void* retainedRegion = nullptr;
833 bool result = OffsetFromAligned(regionStart, alignment) == 0;
834 if (AlwaysGetNew && !result) {
835 // If our current chunk cannot be aligned, just get a new one.
836 retainedRegion = regionStart;
837 regionStart = MapMemory(length);
838 // Our new region might happen to already be aligned.
839 result = OffsetFromAligned(regionStart, alignment) == 0;
840 if (result) {
841 UnmapInternal(retainedRegion, length);
842 retainedRegion = nullptr;
843 }
844 }
845
846 *aRegion = regionStart;
847 *aRetainedRegion = retainedRegion;
848 return regionStart && result;
849 }
850
851 #endif
852
853 void UnmapPages(void* region, size_t length) {
854 MOZ_RELEASE_ASSERT(region &&
855 OffsetFromAligned(region, allocGranularity) == 0);
856 MOZ_RELEASE_ASSERT(length > 0 && length % pageSize == 0);
857
858 // ASan does not automatically unpoison memory, so we have to do this here.
859 MOZ_MAKE_MEM_UNDEFINED(region, length);
860
861 UnmapInternal(region, length);
862
863 #ifndef __wasi__
864 RecordMemoryFree(length);
865 #endif
866 }
867
868 static void CheckDecommit(void* region, size_t length) {
869 MOZ_RELEASE_ASSERT(region);
870 MOZ_RELEASE_ASSERT(length > 0);
871
872 // pageSize == ArenaSize doesn't necessarily hold, but this function is
873 // used by the GC to decommit unused Arenas, so we don't want to assert
874 // if pageSize > ArenaSize.
875 MOZ_ASSERT(OffsetFromAligned(region, ArenaSize) == 0);
876 MOZ_ASSERT(length % ArenaSize == 0);
877
878 MOZ_RELEASE_ASSERT(OffsetFromAligned(region, pageSize) == 0);
879 MOZ_RELEASE_ASSERT(length % pageSize == 0);
880 }
881
882 bool MarkPagesUnusedSoft(void* region, size_t length) {
883 MOZ_ASSERT(DecommitEnabled());
884 CheckDecommit(region, length);
885
886 MOZ_MAKE_MEM_NOACCESS(region, length);
887
888 #if defined(XP_WIN)
889 return VirtualAlloc(region, length, MEM_RESET,
890 DWORD(PageAccess::ReadWrite)) == region;
891 #elif defined(__wasi__)
892 return 0;
893 #else
894 int status;
895 do {
896 # if defined(XP_DARWIN)
897 // Note: we use MADV_FREE instead of MADV_FREE_REUSABLE + MADV_FREE_REUSE to
898 // work around a kernel bug on macOS Tahoe. We should change this back once
899 // that bug is fixed. See bug 2015359.
900 status = madvise(region, length, MADV_FREE);
901 # elif defined(XP_SOLARIS)
902 status = posix_madvise(region, length, POSIX_MADV_DONTNEED);
903 # else
904 status = madvise(region, length, MADV_DONTNEED);
905 # endif
906 } while (status == -1 && errno == EAGAIN);
907 return status == 0;
908 #endif
909 }
910
911 bool MarkPagesUnusedHard(void* region, size_t length) {
912 CheckDecommit(region, length);
913
914 MOZ_MAKE_MEM_NOACCESS(region, length);
915
916 if (!DecommitEnabled()) {
917 return true;
918 }
919
920 #if defined(XP_WIN)
921 return VirtualFree(region, length, MEM_DECOMMIT);
922 #else
923 return MarkPagesUnusedSoft(region, length);
924 #endif
925 }
926
927 void MarkPagesInUseSoft(void* region, size_t length) {
928 MOZ_ASSERT(DecommitEnabled());
929 CheckDecommit(region, length);
930
931 MOZ_MAKE_MEM_UNDEFINED(region, length);
932 }
933
934 bool MarkPagesInUseHard(void* region, size_t length) {
935 if (js::oom::ShouldFailWithOOM()) {
936 return false;
937 }
938
939 CheckDecommit(region, length);
940
941 MOZ_MAKE_MEM_UNDEFINED(region, length);
942
943 if (!DecommitEnabled()) {
944 return true;
945 }
946
947 #if defined(XP_WIN)
948 return VirtualAlloc(region, length, MEM_COMMIT,
949 DWORD(PageAccess::ReadWrite)) == region;
950 #else
951 return true;
952 #endif
953 }
954
955 size_t GetPageFaultCount() {
956 #ifdef XP_WIN
957 PROCESS_MEMORY_COUNTERS pmc;
958 if (GetProcessMemoryInfo(GetCurrentProcess(), &pmc, sizeof(pmc)) == 0) {
959 return 0;
960 }
961 return pmc.PageFaultCount;
962 #elif defined(__wasi__)
963 return 0;
964 #else
965 struct rusage usage;
966 int err = getrusage(RUSAGE_SELF, &usage);
967 if (err) {
968 return 0;
969 }
970 return usage.ru_majflt;
971 #endif
972 }
973
974 void* AllocateMappedContent(int fd, size_t offset, size_t length,
975 size_t alignment) {
976 #ifdef __wasi__
977 MOZ_CRASH("Not yet supported for WASI");
978 #else
979 if (length == 0 || alignment == 0 || offset % alignment != 0 ||
980 std::max(alignment, allocGranularity) %
981 std::min(alignment, allocGranularity) !=
982 0) {
983 return nullptr;
984 }
985
986 size_t alignedOffset = offset - (offset % allocGranularity);
987 size_t alignedLength = length + (offset % allocGranularity);
988
989 // We preallocate the mapping using MapAlignedPages, which expects
990 // the length parameter to be an integer multiple of the page size.
991 size_t mappedLength = alignedLength;
992 if (alignedLength % pageSize != 0) {
993 mappedLength += pageSize - alignedLength % pageSize;
994 }
995
996 # ifdef XP_WIN
997 HANDLE hFile = reinterpret_cast<HANDLE>(intptr_t(fd));
998
999 // This call will fail if the file does not exist.
1000 HANDLE hMap =
1001 CreateFileMappingW(hFile, nullptr, PAGE_READONLY, 0, 0, nullptr);
1002 if (!hMap) {
1003 return nullptr;
1004 }
1005
1006 DWORD offsetH = uint32_t(uint64_t(alignedOffset) >> 32);
1007 DWORD offsetL = uint32_t(alignedOffset);
1008
1009 uint8_t* map = nullptr;
1010 for (;;) {
1011 // The value of a pointer is technically only defined while the region
1012 // it points to is allocated, so explicitly treat this one as a number.
1013 uintptr_t region = uintptr_t(MapAlignedPages(mappedLength, alignment));
1014 if (region == 0) {
1015 break;
1016 }
1017 UnmapInternal(reinterpret_cast<void*>(region), mappedLength);
1018 // If the offset or length are out of bounds, this call will fail.
1019 map = static_cast<uint8_t*>(
1020 MapViewOfFileEx(hMap, FILE_MAP_COPY, offsetH, offsetL, alignedLength,
1021 reinterpret_cast<void*>(region)));
1022 if (map) {
1023 break;
1024 }
1025
1026 RecordMemoryFree(mappedLength);
1027
1028 // Retry if another thread mapped the address we were trying to use.
1029 if (GetLastError() != ERROR_INVALID_ADDRESS) {
1030 break;
1031 }
1032 }
1033
1034 // This just decreases the file mapping object's internal reference count;
1035 // it won't actually be destroyed until we unmap the associated view.
1036 CloseHandle(hMap);
1037
1038 if (!map) {
1039 return nullptr;
1040 }
1041 # else // !defined(XP_WIN)
1042 // Sanity check the offset and length, as mmap does not do this for us.
1043 struct stat st;
1044 if (fstat(fd, &st) || offset >= uint64_t(st.st_size) ||
1045 length > uint64_t(st.st_size) - offset) {
1046 return nullptr;
1047 }
1048
1049 void* region = MapAlignedPages(mappedLength, alignment);
1050 if (!region) {
1051 return nullptr;
1052 }
1053
1054 // Calling mmap with MAP_FIXED will replace the previous mapping, allowing
1055 // us to reuse the region we obtained without racing with other threads.
1056 uint8_t* map =
1057 static_cast<uint8_t*>(mmap(region, alignedLength, PROT_READ | PROT_WRITE,
1058 MAP_PRIVATE | MAP_FIXED, fd, alignedOffset));
1059 if (map == MAP_FAILED) {
1060 UnmapInternal(region, mappedLength);
1061 return nullptr;
1062 }
1063 # endif
1064
1065 # ifdef DEBUG
1066 // Zero out data before and after the desired mapping to catch errors early.
1067 if (offset != alignedOffset) {
1068 memset(map, 0, offset - alignedOffset);
1069 }
1070 if (alignedLength % pageSize) {
1071 memset(map + alignedLength, 0, pageSize - (alignedLength % pageSize));
1072 }
1073 # endif
1074
1075 return map + (offset - alignedOffset);
1076 #endif // __wasi__
1077 }
1078
1079 void DeallocateMappedContent(void* region, size_t length) {
1080 #ifdef __wasi__
1081 MOZ_CRASH("Not yet supported for WASI");
1082 #else
1083 if (!region) {
1084 return;
1085 }
1086
1087 // Due to bug 1502562, the following assertion does not currently hold.
1088 // MOZ_RELEASE_ASSERT(length > 0);
1089
1090 // Calculate the address originally returned by the system call.
1091 // This is needed because AllocateMappedContent returns a pointer
1092 // that might be offset from the mapping, as the beginning of a
1093 // mapping must be aligned with the allocation granularity.
1094 uintptr_t map = uintptr_t(region) - (uintptr_t(region) % allocGranularity);
1095
1096 size_t alignedLength = length + (uintptr_t(region) % allocGranularity);
1097
1098 size_t mappedLength = alignedLength;
1099 if (alignedLength % pageSize != 0) {
1100 mappedLength += pageSize - alignedLength % pageSize;
1101 }
1102
1103 # ifdef XP_WIN
1104 MOZ_RELEASE_ASSERT(UnmapViewOfFile(reinterpret_cast<void*>(map)) != 0);
1105 # else
1106 if (munmap(reinterpret_cast<void*>(map), alignedLength)) {
1107 MOZ_RELEASE_ASSERT(errno == ENOMEM);
1108 }
1109 # endif
1110
1111 RecordMemoryFree(mappedLength);
1112
1113 #endif // __wasi__
1114 }
1115
1116 static inline void ProtectMemory(void* region, size_t length, PageAccess prot) {
1117 MOZ_RELEASE_ASSERT(region && OffsetFromAligned(region, pageSize) == 0);
1118 MOZ_RELEASE_ASSERT(length > 0 && length % pageSize == 0);
1119 #ifdef XP_WIN
1120 DWORD oldProtect;
1121 MOZ_RELEASE_ASSERT(VirtualProtect(region, length, DWORD(prot), &oldProtect) !=
1122 0);
1123 #elif defined(__wasi__)
1124 /* nothing */
1125 #else
1126 MOZ_RELEASE_ASSERT(mprotect(region, length, int(prot)) == 0);
1127 #endif
1128 }
1129
1130 void ProtectPages(void* region, size_t length) {
1131 ProtectMemory(region, length, PageAccess::None);
1132 }
1133
1134 void MakePagesReadOnly(void* region, size_t length) {
1135 ProtectMemory(region, length, PageAccess::Read);
1136 }
1137
1138 void UnprotectPages(void* region, size_t length) {
1139 ProtectMemory(region, length, PageAccess::ReadWrite);
1140 }
1141
1142 void RecordMemoryAlloc(size_t bytes) {
1143 MOZ_ASSERT(bytes);
1144 MOZ_ASSERT((bytes % pageSize) == 0);
1145
1146 gMappedMemorySizeBytes += bytes;
1147 gMappedMemoryOperations++;
1148 }
1149
1150 void RecordMemoryFree(size_t bytes) {
1151 MOZ_ASSERT(bytes);
1152 MOZ_ASSERT((bytes % pageSize) == 0);
1153 MOZ_ASSERT(bytes <= gMappedMemorySizeBytes);
1154
1155 gMappedMemorySizeBytes -= bytes;
1156 gMappedMemoryOperations++;
1157 }
1158
1159 JS_PUBLIC_API ProfilerMemoryCounts GetProfilerMemoryCounts() {
1160 return {gc::gMappedMemorySizeBytes, gc::gMappedMemoryOperations};
1161 }
1162
1163 } // namespace js::gc