Bug 1845715 - Check for failure when getting RegExp match result template r=iain
[gecko.git] / memory / build / mozjemalloc.cpp
blob672c893a71e98c700ec0467368b9f6ca6c911e1a
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/. */
7 // Portions of this file were originally under the following license:
8 //
9 // Copyright (C) 2006-2008 Jason Evans <jasone@FreeBSD.org>.
10 // All rights reserved.
11 // Copyright (C) 2007-2017 Mozilla Foundation.
13 // Redistribution and use in source and binary forms, with or without
14 // modification, are permitted provided that the following conditions
15 // are met:
16 // 1. Redistributions of source code must retain the above copyright
17 // notice(s), this list of conditions and the following disclaimer as
18 // the first lines of this file unmodified other than the possible
19 // addition of one or more copyright notices.
20 // 2. Redistributions in binary form must reproduce the above copyright
21 // notice(s), this list of conditions and the following disclaimer in
22 // the documentation and/or other materials provided with the
23 // distribution.
25 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER(S) ``AS IS'' AND ANY
26 // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
27 // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
28 // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER(S) BE
29 // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
30 // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
31 // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
32 // BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
33 // WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
34 // OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
35 // EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
37 // *****************************************************************************
39 // This allocator implementation is designed to provide scalable performance
40 // for multi-threaded programs on multi-processor systems. The following
41 // features are included for this purpose:
43 // + Multiple arenas are used if there are multiple CPUs, which reduces lock
44 // contention and cache sloshing.
46 // + Cache line sharing between arenas is avoided for internal data
47 // structures.
49 // + Memory is managed in chunks and runs (chunks can be split into runs),
50 // rather than as individual pages. This provides a constant-time
51 // mechanism for associating allocations with particular arenas.
53 // Allocation requests are rounded up to the nearest size class, and no record
54 // of the original request size is maintained. Allocations are broken into
55 // categories according to size class. Assuming runtime defaults, the size
56 // classes in each category are as follows (for x86, x86_64 and Apple Silicon):
58 // |=========================================================|
59 // | Category | Subcategory | x86 | x86_64 | Mac ARM |
60 // |---------------------------+---------+---------+---------|
61 // | Word size | 32 bit | 64 bit | 64 bit |
62 // | Page size | 4 Kb | 4 Kb | 16 Kb |
63 // |=========================================================|
64 // | Small | Tiny | 4/-w | -w | - |
65 // | | | 8 | 8/-w | 8 |
66 // | |----------------+---------|---------|---------|
67 // | | Quantum-spaced | 16 | 16 | 16 |
68 // | | | 32 | 32 | 32 |
69 // | | | 48 | 48 | 48 |
70 // | | | ... | ... | ... |
71 // | | | 480 | 480 | 480 |
72 // | | | 496 | 496 | 496 |
73 // | |----------------+---------|---------|---------|
74 // | | Quantum-wide- | 512 | 512 | 512 |
75 // | | spaced | 768 | 768 | 768 |
76 // | | | ... | ... | ... |
77 // | | | 3584 | 3584 | 3584 |
78 // | | | 3840 | 3840 | 3840 |
79 // | |----------------+---------|---------|---------|
80 // | | Sub-page | - | - | 4096 |
81 // | | | - | - | 8 kB |
82 // |=========================================================|
83 // | Large | 4 kB | 4 kB | - |
84 // | | 8 kB | 8 kB | - |
85 // | | 12 kB | 12 kB | - |
86 // | | 16 kB | 16 kB | 16 kB |
87 // | | ... | ... | - |
88 // | | 32 kB | 32 kB | 32 kB |
89 // | | ... | ... | ... |
90 // | | 1008 kB | 1008 kB | 1008 kB |
91 // | | 1012 kB | 1012 kB | - |
92 // | | 1016 kB | 1016 kB | - |
93 // | | 1020 kB | 1020 kB | - |
94 // |=========================================================|
95 // | Huge | 1 MB | 1 MB | 1 MB |
96 // | | 2 MB | 2 MB | 2 MB |
97 // | | 3 MB | 3 MB | 3 MB |
98 // | | ... | ... | ... |
99 // |=========================================================|
101 // Legend:
102 // n: Size class exists for this platform.
103 // n/-w: This size class doesn't exist on Windows (see kMinTinyClass).
104 // -: This size class doesn't exist for this platform.
105 // ...: Size classes follow a pattern here.
107 // NOTE: Due to Mozilla bug 691003, we cannot reserve less than one word for an
108 // allocation on Linux or Mac. So on 32-bit *nix, the smallest bucket size is
109 // 4 bytes, and on 64-bit, the smallest bucket size is 8 bytes.
111 // A different mechanism is used for each category:
113 // Small : Each size class is segregated into its own set of runs. Each run
114 // maintains a bitmap of which regions are free/allocated.
116 // Large : Each allocation is backed by a dedicated run. Metadata are stored
117 // in the associated arena chunk header maps.
119 // Huge : Each allocation is backed by a dedicated contiguous set of chunks.
120 // Metadata are stored in a separate red-black tree.
122 // *****************************************************************************
124 #include "mozmemory_wrap.h"
125 #include "mozjemalloc.h"
126 #include "mozjemalloc_types.h"
128 #include <cstring>
129 #include <cerrno>
130 #include <optional>
131 #include <type_traits>
132 #ifdef XP_WIN
133 # include <io.h>
134 # include <windows.h>
135 #else
136 # include <sys/mman.h>
137 # include <unistd.h>
138 #endif
139 #ifdef XP_DARWIN
140 # include <libkern/OSAtomic.h>
141 # include <mach/mach_init.h>
142 # include <mach/vm_map.h>
143 #endif
145 #include "mozilla/Atomics.h"
146 #include "mozilla/Alignment.h"
147 #include "mozilla/ArrayUtils.h"
148 #include "mozilla/Assertions.h"
149 #include "mozilla/CheckedInt.h"
150 #include "mozilla/DoublyLinkedList.h"
151 #include "mozilla/HelperMacros.h"
152 #include "mozilla/Likely.h"
153 #include "mozilla/MathAlgorithms.h"
154 #include "mozilla/RandomNum.h"
155 // Note: MozTaggedAnonymousMmap() could call an LD_PRELOADed mmap
156 // instead of the one defined here; use only MozTagAnonymousMemory().
157 #include "mozilla/TaggedAnonymousMemory.h"
158 #include "mozilla/ThreadLocal.h"
159 #include "mozilla/UniquePtr.h"
160 #include "mozilla/Unused.h"
161 #include "mozilla/XorShift128PlusRNG.h"
162 #include "mozilla/fallible.h"
163 #include "rb.h"
164 #include "Mutex.h"
165 #include "Utils.h"
167 #if defined(XP_WIN)
168 # include "mozmemory_utils.h"
169 #endif
171 // For GetGeckoProcessType(), when it's used.
172 #if defined(XP_WIN) && !defined(JS_STANDALONE)
173 # include "mozilla/ProcessType.h"
174 #endif
176 using namespace mozilla;
178 // On Linux, we use madvise(MADV_DONTNEED) to release memory back to the
179 // operating system. If we release 1MB of live pages with MADV_DONTNEED, our
180 // RSS will decrease by 1MB (almost) immediately.
182 // On Mac, we use madvise(MADV_FREE). Unlike MADV_DONTNEED on Linux, MADV_FREE
183 // on Mac doesn't cause the OS to release the specified pages immediately; the
184 // OS keeps them in our process until the machine comes under memory pressure.
186 // It's therefore difficult to measure the process's RSS on Mac, since, in the
187 // absence of memory pressure, the contribution from the heap to RSS will not
188 // decrease due to our madvise calls.
190 // We therefore define MALLOC_DOUBLE_PURGE on Mac. This causes jemalloc to
191 // track which pages have been MADV_FREE'd. You can then call
192 // jemalloc_purge_freed_pages(), which will force the OS to release those
193 // MADV_FREE'd pages, making the process's RSS reflect its true memory usage.
195 // The jemalloc_purge_freed_pages definition in memory/build/mozmemory.h needs
196 // to be adjusted if MALLOC_DOUBLE_PURGE is ever enabled on Linux.
198 #ifdef XP_DARWIN
199 # define MALLOC_DOUBLE_PURGE
200 #endif
202 #ifdef XP_WIN
203 # define MALLOC_DECOMMIT
204 #endif
206 // Define MALLOC_RUNTIME_CONFIG depending on MOZ_DEBUG. Overriding this as
207 // a build option allows us to build mozjemalloc/firefox without runtime asserts
208 // but with runtime configuration. Making some testing easier.
210 #ifdef MOZ_DEBUG
211 # define MALLOC_RUNTIME_CONFIG
212 #endif
214 // When MALLOC_STATIC_PAGESIZE is defined, the page size is fixed at
215 // compile-time for better performance, as opposed to determined at
216 // runtime. Some platforms can have different page sizes at runtime
217 // depending on kernel configuration, so they are opted out by default.
218 // Debug builds are opted out too, for test coverage.
219 #ifndef MALLOC_RUNTIME_CONFIG
220 # if !defined(__ia64__) && !defined(__sparc__) && !defined(__mips__) && \
221 !defined(__aarch64__) && !defined(__powerpc__) && !defined(XP_MACOSX) && \
222 !defined(__loongarch__)
223 # define MALLOC_STATIC_PAGESIZE 1
224 # endif
225 #endif
227 #ifdef XP_WIN
228 # define STDERR_FILENO 2
230 // Implement getenv without using malloc.
231 static char mozillaMallocOptionsBuf[64];
233 # define getenv xgetenv
234 static char* getenv(const char* name) {
235 if (GetEnvironmentVariableA(name, mozillaMallocOptionsBuf,
236 sizeof(mozillaMallocOptionsBuf)) > 0) {
237 return mozillaMallocOptionsBuf;
240 return nullptr;
242 #endif
244 #ifndef XP_WIN
245 // Newer Linux systems support MADV_FREE, but we're not supporting
246 // that properly. bug #1406304.
247 # if defined(XP_LINUX) && defined(MADV_FREE)
248 # undef MADV_FREE
249 # endif
250 # ifndef MADV_FREE
251 # define MADV_FREE MADV_DONTNEED
252 # endif
253 #endif
255 // Some tools, such as /dev/dsp wrappers, LD_PRELOAD libraries that
256 // happen to override mmap() and call dlsym() from their overridden
257 // mmap(). The problem is that dlsym() calls malloc(), and this ends
258 // up in a dead lock in jemalloc.
259 // On these systems, we prefer to directly use the system call.
260 // We do that for Linux systems and kfreebsd with GNU userland.
261 // Note sanity checks are not done (alignment of offset, ...) because
262 // the uses of mmap are pretty limited, in jemalloc.
264 // On Alpha, glibc has a bug that prevents syscall() to work for system
265 // calls with 6 arguments.
266 #if (defined(XP_LINUX) && !defined(__alpha__)) || \
267 (defined(__FreeBSD_kernel__) && defined(__GLIBC__))
268 # include <sys/syscall.h>
269 # if defined(SYS_mmap) || defined(SYS_mmap2)
270 static inline void* _mmap(void* addr, size_t length, int prot, int flags,
271 int fd, off_t offset) {
272 // S390 only passes one argument to the mmap system call, which is a
273 // pointer to a structure containing the arguments.
274 # ifdef __s390__
275 struct {
276 void* addr;
277 size_t length;
278 long prot;
279 long flags;
280 long fd;
281 off_t offset;
282 } args = {addr, length, prot, flags, fd, offset};
283 return (void*)syscall(SYS_mmap, &args);
284 # else
285 # if defined(ANDROID) && defined(__aarch64__) && defined(SYS_mmap2)
286 // Android NDK defines SYS_mmap2 for AArch64 despite it not supporting mmap2.
287 # undef SYS_mmap2
288 # endif
289 # ifdef SYS_mmap2
290 return (void*)syscall(SYS_mmap2, addr, length, prot, flags, fd, offset >> 12);
291 # else
292 return (void*)syscall(SYS_mmap, addr, length, prot, flags, fd, offset);
293 # endif
294 # endif
296 # define mmap _mmap
297 # define munmap(a, l) syscall(SYS_munmap, a, l)
298 # endif
299 #endif
301 // ***************************************************************************
302 // Structures for chunk headers for chunks used for non-huge allocations.
304 struct arena_t;
306 // Each element of the chunk map corresponds to one page within the chunk.
307 struct arena_chunk_map_t {
308 // Linkage for run trees. There are two disjoint uses:
310 // 1) arena_t's tree or available runs.
311 // 2) arena_run_t conceptually uses this linkage for in-use non-full
312 // runs, rather than directly embedding linkage.
313 RedBlackTreeNode<arena_chunk_map_t> link;
315 // Run address (or size) and various flags are stored together. The bit
316 // layout looks like (assuming 32-bit system):
318 // ???????? ???????? ????---- -mckdzla
320 // ? : Unallocated: Run address for first/last pages, unset for internal
321 // pages.
322 // Small: Run address.
323 // Large: Run size for first page, unset for trailing pages.
324 // - : Unused.
325 // m : MADV_FREE/MADV_DONTNEED'ed?
326 // c : decommitted?
327 // k : key?
328 // d : dirty?
329 // z : zeroed?
330 // l : large?
331 // a : allocated?
333 // Following are example bit patterns for the three types of runs.
335 // r : run address
336 // s : run size
337 // x : don't care
338 // - : 0
339 // [cdzla] : bit set
341 // Unallocated:
342 // ssssssss ssssssss ssss---- --c-----
343 // xxxxxxxx xxxxxxxx xxxx---- ----d---
344 // ssssssss ssssssss ssss---- -----z--
346 // Small:
347 // rrrrrrrr rrrrrrrr rrrr---- -------a
348 // rrrrrrrr rrrrrrrr rrrr---- -------a
349 // rrrrrrrr rrrrrrrr rrrr---- -------a
351 // Large:
352 // ssssssss ssssssss ssss---- ------la
353 // -------- -------- -------- ------la
354 // -------- -------- -------- ------la
355 size_t bits;
357 // Note that CHUNK_MAP_DECOMMITTED's meaning varies depending on whether
358 // MALLOC_DECOMMIT and MALLOC_DOUBLE_PURGE are defined.
360 // If MALLOC_DECOMMIT is defined, a page which is CHUNK_MAP_DECOMMITTED must be
361 // re-committed with pages_commit() before it may be touched. If
362 // MALLOC_DECOMMIT is defined, MALLOC_DOUBLE_PURGE may not be defined.
364 // If neither MALLOC_DECOMMIT nor MALLOC_DOUBLE_PURGE is defined, pages which
365 // are madvised (with either MADV_DONTNEED or MADV_FREE) are marked with
366 // CHUNK_MAP_MADVISED.
368 // Otherwise, if MALLOC_DECOMMIT is not defined and MALLOC_DOUBLE_PURGE is
369 // defined, then a page which is madvised is marked as CHUNK_MAP_MADVISED.
370 // When it's finally freed with jemalloc_purge_freed_pages, the page is marked
371 // as CHUNK_MAP_DECOMMITTED.
372 #define CHUNK_MAP_MADVISED ((size_t)0x40U)
373 #define CHUNK_MAP_DECOMMITTED ((size_t)0x20U)
374 #define CHUNK_MAP_MADVISED_OR_DECOMMITTED \
375 (CHUNK_MAP_MADVISED | CHUNK_MAP_DECOMMITTED)
376 #define CHUNK_MAP_KEY ((size_t)0x10U)
377 #define CHUNK_MAP_DIRTY ((size_t)0x08U)
378 #define CHUNK_MAP_ZEROED ((size_t)0x04U)
379 #define CHUNK_MAP_LARGE ((size_t)0x02U)
380 #define CHUNK_MAP_ALLOCATED ((size_t)0x01U)
383 // Arena chunk header.
384 struct arena_chunk_t {
385 // Arena that owns the chunk.
386 arena_t* arena;
388 // Linkage for the arena's tree of dirty chunks.
389 RedBlackTreeNode<arena_chunk_t> link_dirty;
391 #ifdef MALLOC_DOUBLE_PURGE
392 // If we're double-purging, we maintain a linked list of chunks which
393 // have pages which have been madvise(MADV_FREE)'d but not explicitly
394 // purged.
396 // We're currently lazy and don't remove a chunk from this list when
397 // all its madvised pages are recommitted.
398 DoublyLinkedListElement<arena_chunk_t> chunks_madvised_elem;
399 #endif
401 // Number of dirty pages.
402 size_t ndirty;
404 // Map of pages within chunk that keeps track of free/large/small.
405 arena_chunk_map_t map[1]; // Dynamically sized.
408 // ***************************************************************************
409 // Constants defining allocator size classes and behavior.
411 // Maximum size of L1 cache line. This is used to avoid cache line aliasing,
412 // so over-estimates are okay (up to a point), but under-estimates will
413 // negatively affect performance.
414 static const size_t kCacheLineSize = 64;
416 // Our size classes are inclusive ranges of memory sizes. By describing the
417 // minimums and how memory is allocated in each range the maximums can be
418 // calculated.
420 // Smallest size class to support. On Windows the smallest allocation size
421 // must be 8 bytes on 32-bit, 16 bytes on 64-bit. On Linux and Mac, even
422 // malloc(1) must reserve a word's worth of memory (see Mozilla bug 691003).
423 #ifdef XP_WIN
424 static const size_t kMinTinyClass = sizeof(void*) * 2;
425 #else
426 static const size_t kMinTinyClass = sizeof(void*);
427 #endif
429 // Maximum tiny size class.
430 static const size_t kMaxTinyClass = 8;
432 // Smallest quantum-spaced size classes. It could actually also be labelled a
433 // tiny allocation, and is spaced as such from the largest tiny size class.
434 // Tiny classes being powers of 2, this is twice as large as the largest of
435 // them.
436 static const size_t kMinQuantumClass = kMaxTinyClass * 2;
437 static const size_t kMinQuantumWideClass = 512;
438 static const size_t kMinSubPageClass = 4_KiB;
440 // Amount (quantum) separating quantum-spaced size classes.
441 static const size_t kQuantum = 16;
442 static const size_t kQuantumMask = kQuantum - 1;
443 static const size_t kQuantumWide = 256;
444 static const size_t kQuantumWideMask = kQuantumWide - 1;
446 static const size_t kMaxQuantumClass = kMinQuantumWideClass - kQuantum;
447 static const size_t kMaxQuantumWideClass = kMinSubPageClass - kQuantumWide;
449 // We can optimise some divisions to shifts if these are powers of two.
450 static_assert(mozilla::IsPowerOfTwo(kQuantum),
451 "kQuantum is not a power of two");
452 static_assert(mozilla::IsPowerOfTwo(kQuantumWide),
453 "kQuantumWide is not a power of two");
455 static_assert(kMaxQuantumClass % kQuantum == 0,
456 "kMaxQuantumClass is not a multiple of kQuantum");
457 static_assert(kMaxQuantumWideClass % kQuantumWide == 0,
458 "kMaxQuantumWideClass is not a multiple of kQuantumWide");
459 static_assert(kQuantum < kQuantumWide,
460 "kQuantum must be smaller than kQuantumWide");
461 static_assert(mozilla::IsPowerOfTwo(kMinSubPageClass),
462 "kMinSubPageClass is not a power of two");
464 // Number of (2^n)-spaced tiny classes.
465 static const size_t kNumTinyClasses =
466 LOG2(kMaxTinyClass) - LOG2(kMinTinyClass) + 1;
468 // Number of quantum-spaced classes. We add kQuantum(Max) before subtracting to
469 // avoid underflow when a class is empty (Max<Min).
470 static const size_t kNumQuantumClasses =
471 (kMaxQuantumClass + kQuantum - kMinQuantumClass) / kQuantum;
472 static const size_t kNumQuantumWideClasses =
473 (kMaxQuantumWideClass + kQuantumWide - kMinQuantumWideClass) / kQuantumWide;
475 // Size and alignment of memory chunks that are allocated by the OS's virtual
476 // memory system.
477 static const size_t kChunkSize = 1_MiB;
478 static const size_t kChunkSizeMask = kChunkSize - 1;
480 #ifdef MALLOC_STATIC_PAGESIZE
481 // VM page size. It must divide the runtime CPU page size or the code
482 // will abort.
483 // Platform specific page size conditions copied from js/public/HeapAPI.h
484 # if defined(__powerpc64__)
485 static const size_t gPageSize = 64_KiB;
486 # elif defined(__loongarch64)
487 static const size_t gPageSize = 16_KiB;
488 # else
489 static const size_t gPageSize = 4_KiB;
490 # endif
491 static const size_t gRealPageSize = gPageSize;
493 #else
494 // When MALLOC_OPTIONS contains one or several `P`s, the page size used
495 // across the allocator is multiplied by 2 for each `P`, but we also keep
496 // the real page size for code paths that need it. gPageSize is thus a
497 // power of two greater or equal to gRealPageSize.
498 static size_t gRealPageSize;
499 static size_t gPageSize;
500 #endif
502 #ifdef MALLOC_STATIC_PAGESIZE
503 # define DECLARE_GLOBAL(type, name)
504 # define DEFINE_GLOBALS
505 # define END_GLOBALS
506 # define DEFINE_GLOBAL(type) static const type
507 # define GLOBAL_LOG2 LOG2
508 # define GLOBAL_ASSERT_HELPER1(x) static_assert(x, #x)
509 # define GLOBAL_ASSERT_HELPER2(x, y) static_assert(x, y)
510 # define GLOBAL_ASSERT(...) \
511 MACRO_CALL( \
512 MOZ_PASTE_PREFIX_AND_ARG_COUNT(GLOBAL_ASSERT_HELPER, __VA_ARGS__), \
513 (__VA_ARGS__))
514 # define GLOBAL_CONSTEXPR constexpr
515 #else
516 # define DECLARE_GLOBAL(type, name) static type name;
517 # define DEFINE_GLOBALS static void DefineGlobals() {
518 # define END_GLOBALS }
519 # define DEFINE_GLOBAL(type)
520 # define GLOBAL_LOG2 FloorLog2
521 # define GLOBAL_ASSERT MOZ_RELEASE_ASSERT
522 # define GLOBAL_CONSTEXPR
523 #endif
525 DECLARE_GLOBAL(size_t, gMaxSubPageClass)
526 DECLARE_GLOBAL(uint8_t, gNumSubPageClasses)
527 DECLARE_GLOBAL(uint8_t, gPageSize2Pow)
528 DECLARE_GLOBAL(size_t, gPageSizeMask)
529 DECLARE_GLOBAL(size_t, gChunkNumPages)
530 DECLARE_GLOBAL(size_t, gChunkHeaderNumPages)
531 DECLARE_GLOBAL(size_t, gMaxLargeClass)
533 DEFINE_GLOBALS
535 // Largest sub-page size class, or zero if there are none
536 DEFINE_GLOBAL(size_t)
537 gMaxSubPageClass = gPageSize / 2 >= kMinSubPageClass ? gPageSize / 2 : 0;
539 // Max size class for bins.
540 #define gMaxBinClass \
541 (gMaxSubPageClass ? gMaxSubPageClass : kMaxQuantumWideClass)
543 // Number of sub-page bins.
544 DEFINE_GLOBAL(uint8_t)
545 gNumSubPageClasses = []() GLOBAL_CONSTEXPR -> uint8_t {
546 if GLOBAL_CONSTEXPR (gMaxSubPageClass != 0) {
547 return FloorLog2(gMaxSubPageClass) - LOG2(kMinSubPageClass) + 1;
549 return 0;
550 }();
552 DEFINE_GLOBAL(uint8_t) gPageSize2Pow = GLOBAL_LOG2(gPageSize);
553 DEFINE_GLOBAL(size_t) gPageSizeMask = gPageSize - 1;
555 // Number of pages in a chunk.
556 DEFINE_GLOBAL(size_t) gChunkNumPages = kChunkSize >> gPageSize2Pow;
558 // Number of pages necessary for a chunk header plus a guard page.
559 DEFINE_GLOBAL(size_t)
560 gChunkHeaderNumPages =
561 1 + (((sizeof(arena_chunk_t) +
562 sizeof(arena_chunk_map_t) * (gChunkNumPages - 1) + gPageSizeMask) &
563 ~gPageSizeMask) >>
564 gPageSize2Pow);
566 // One chunk, minus the header, minus a guard page
567 DEFINE_GLOBAL(size_t)
568 gMaxLargeClass =
569 kChunkSize - gPageSize - (gChunkHeaderNumPages << gPageSize2Pow);
571 // Various sanity checks that regard configuration.
572 GLOBAL_ASSERT(1ULL << gPageSize2Pow == gPageSize,
573 "Page size is not a power of two");
574 GLOBAL_ASSERT(kQuantum >= sizeof(void*));
575 GLOBAL_ASSERT(kQuantum <= kQuantumWide);
576 GLOBAL_ASSERT(!kNumQuantumWideClasses ||
577 kQuantumWide <= (kMinSubPageClass - kMaxQuantumClass));
579 GLOBAL_ASSERT(kQuantumWide <= kMaxQuantumClass);
581 GLOBAL_ASSERT(gMaxSubPageClass >= kMinSubPageClass || gMaxSubPageClass == 0);
582 GLOBAL_ASSERT(gMaxLargeClass >= gMaxSubPageClass);
583 GLOBAL_ASSERT(kChunkSize >= gPageSize);
584 GLOBAL_ASSERT(kQuantum * 4 <= kChunkSize);
586 END_GLOBALS
588 // Recycle at most 128 MiB of chunks. This means we retain at most
589 // 6.25% of the process address space on a 32-bit OS for later use.
590 static const size_t gRecycleLimit = 128_MiB;
592 // The current amount of recycled bytes, updated atomically.
593 static Atomic<size_t, ReleaseAcquire> gRecycledSize;
595 // Maximum number of dirty pages per arena.
596 #define DIRTY_MAX_DEFAULT (1U << 8)
598 static size_t opt_dirty_max = DIRTY_MAX_DEFAULT;
600 // Return the smallest chunk multiple that is >= s.
601 #define CHUNK_CEILING(s) (((s) + kChunkSizeMask) & ~kChunkSizeMask)
603 // Return the smallest cacheline multiple that is >= s.
604 #define CACHELINE_CEILING(s) \
605 (((s) + (kCacheLineSize - 1)) & ~(kCacheLineSize - 1))
607 // Return the smallest quantum multiple that is >= a.
608 #define QUANTUM_CEILING(a) (((a) + (kQuantumMask)) & ~(kQuantumMask))
609 #define QUANTUM_WIDE_CEILING(a) \
610 (((a) + (kQuantumWideMask)) & ~(kQuantumWideMask))
612 // Return the smallest sub page-size that is >= a.
613 #define SUBPAGE_CEILING(a) (RoundUpPow2(a))
615 // Return the smallest pagesize multiple that is >= s.
616 #define PAGE_CEILING(s) (((s) + gPageSizeMask) & ~gPageSizeMask)
618 // Number of all the small-allocated classes
619 #define NUM_SMALL_CLASSES \
620 (kNumTinyClasses + kNumQuantumClasses + kNumQuantumWideClasses + \
621 gNumSubPageClasses)
623 // ***************************************************************************
624 // MALLOC_DECOMMIT and MALLOC_DOUBLE_PURGE are mutually exclusive.
625 #if defined(MALLOC_DECOMMIT) && defined(MALLOC_DOUBLE_PURGE)
626 # error MALLOC_DECOMMIT and MALLOC_DOUBLE_PURGE are mutually exclusive.
627 #endif
629 static void* base_alloc(size_t aSize);
631 // Set to true once the allocator has been initialized.
632 #if defined(_MSC_VER) && !defined(__clang__)
633 // MSVC may create a static initializer for an Atomic<bool>, which may actually
634 // run after `malloc_init` has been called once, which triggers multiple
635 // initializations.
636 // We work around the problem by not using an Atomic<bool> at all. There is a
637 // theoretical problem with using `malloc_initialized` non-atomically, but
638 // practically, this is only true if `malloc_init` is never called before
639 // threads are created.
640 static bool malloc_initialized;
641 #else
642 static Atomic<bool, SequentiallyConsistent> malloc_initialized;
643 #endif
645 static StaticMutex gInitLock MOZ_UNANNOTATED = {STATIC_MUTEX_INIT};
647 // ***************************************************************************
648 // Statistics data structures.
650 struct arena_stats_t {
651 // Number of bytes currently mapped.
652 size_t mapped;
654 // Current number of committed pages.
655 size_t committed;
657 // Per-size-category statistics.
658 size_t allocated_small;
660 size_t allocated_large;
663 // ***************************************************************************
664 // Extent data structures.
666 enum ChunkType {
667 UNKNOWN_CHUNK,
668 ZEROED_CHUNK, // chunk only contains zeroes.
669 ARENA_CHUNK, // used to back arena runs created by arena_t::AllocRun.
670 HUGE_CHUNK, // used to back huge allocations (e.g. arena_t::MallocHuge).
671 RECYCLED_CHUNK, // chunk has been stored for future use by chunk_recycle.
674 // Tree of extents.
675 struct extent_node_t {
676 union {
677 // Linkage for the size/address-ordered tree for chunk recycling.
678 RedBlackTreeNode<extent_node_t> mLinkBySize;
679 // Arena id for huge allocations. It's meant to match mArena->mId,
680 // which only holds true when the arena hasn't been disposed of.
681 arena_id_t mArenaId;
684 // Linkage for the address-ordered tree.
685 RedBlackTreeNode<extent_node_t> mLinkByAddr;
687 // Pointer to the extent that this tree node is responsible for.
688 void* mAddr;
690 // Total region size.
691 size_t mSize;
693 union {
694 // What type of chunk is there; used for chunk recycling.
695 ChunkType mChunkType;
697 // A pointer to the associated arena, for huge allocations.
698 arena_t* mArena;
702 struct ExtentTreeSzTrait {
703 static RedBlackTreeNode<extent_node_t>& GetTreeNode(extent_node_t* aThis) {
704 return aThis->mLinkBySize;
707 static inline Order Compare(extent_node_t* aNode, extent_node_t* aOther) {
708 Order ret = CompareInt(aNode->mSize, aOther->mSize);
709 return (ret != Order::eEqual) ? ret
710 : CompareAddr(aNode->mAddr, aOther->mAddr);
714 struct ExtentTreeTrait {
715 static RedBlackTreeNode<extent_node_t>& GetTreeNode(extent_node_t* aThis) {
716 return aThis->mLinkByAddr;
719 static inline Order Compare(extent_node_t* aNode, extent_node_t* aOther) {
720 return CompareAddr(aNode->mAddr, aOther->mAddr);
724 struct ExtentTreeBoundsTrait : public ExtentTreeTrait {
725 static inline Order Compare(extent_node_t* aKey, extent_node_t* aNode) {
726 uintptr_t key_addr = reinterpret_cast<uintptr_t>(aKey->mAddr);
727 uintptr_t node_addr = reinterpret_cast<uintptr_t>(aNode->mAddr);
728 size_t node_size = aNode->mSize;
730 // Is aKey within aNode?
731 if (node_addr <= key_addr && key_addr < node_addr + node_size) {
732 return Order::eEqual;
735 return CompareAddr(aKey->mAddr, aNode->mAddr);
739 // Describe size classes to which allocations are rounded up to.
740 // TODO: add large and huge types when the arena allocation code
741 // changes in a way that allows it to be beneficial.
742 class SizeClass {
743 public:
744 enum ClassType {
745 Tiny,
746 Quantum,
747 QuantumWide,
748 SubPage,
749 Large,
752 explicit inline SizeClass(size_t aSize) {
753 if (aSize <= kMaxTinyClass) {
754 mType = Tiny;
755 mSize = std::max(RoundUpPow2(aSize), kMinTinyClass);
756 } else if (aSize <= kMaxQuantumClass) {
757 mType = Quantum;
758 mSize = QUANTUM_CEILING(aSize);
759 } else if (aSize <= kMaxQuantumWideClass) {
760 mType = QuantumWide;
761 mSize = QUANTUM_WIDE_CEILING(aSize);
762 } else if (aSize <= gMaxSubPageClass) {
763 mType = SubPage;
764 mSize = SUBPAGE_CEILING(aSize);
765 } else if (aSize <= gMaxLargeClass) {
766 mType = Large;
767 mSize = PAGE_CEILING(aSize);
768 } else {
769 MOZ_MAKE_COMPILER_ASSUME_IS_UNREACHABLE("Invalid size");
773 SizeClass& operator=(const SizeClass& aOther) = default;
775 bool operator==(const SizeClass& aOther) { return aOther.mSize == mSize; }
777 size_t Size() { return mSize; }
779 ClassType Type() { return mType; }
781 SizeClass Next() { return SizeClass(mSize + 1); }
783 private:
784 ClassType mType;
785 size_t mSize;
788 // Fast division
790 // During deallocation we want to divide by the size class. This class
791 // provides a routine and sets up a constant as follows.
793 // To divide by a number D that is not a power of two we multiply by (2^17 /
794 // D) and then right shift by 17 positions.
796 // X / D
798 // becomes
800 // (X * m) >> p
802 // Where m is calculated during the FastDivisor constructor similarly to:
804 // m = 2^p / D
806 template <typename T>
807 class FastDivisor {
808 private:
809 // The shift amount (p) is chosen to minimise the size of m while
810 // working for divisors up to 65536 in steps of 16. I arrived at 17
811 // experimentally. I wanted a low number to minimise the range of m
812 // so it can fit in a uint16_t, 16 didn't work but 17 worked perfectly.
814 // We'd need to increase this if we allocated memory on smaller boundaries
815 // than 16.
816 static const unsigned p = 17;
818 // We can fit the inverted divisor in 16 bits, but we template it here for
819 // convenience.
820 T m;
822 public:
823 // Needed so mBins can be constructed.
824 FastDivisor() : m(0) {}
826 FastDivisor(unsigned div, unsigned max) {
827 MOZ_ASSERT(div <= max);
829 // divide_inv_shift is large enough.
830 MOZ_ASSERT((1U << p) >= div);
832 // The calculation here for m is formula 26 from Section
833 // 10-9 "Unsigned Division by Divisors >= 1" in
834 // Henry S. Warren, Jr.'s Hacker's Delight, 2nd Ed.
835 unsigned m_ = ((1U << p) + div - 1 - (((1U << p) - 1) % div)) / div;
837 // Make sure that max * m does not overflow.
838 MOZ_DIAGNOSTIC_ASSERT(max < UINT_MAX / m_);
840 MOZ_ASSERT(m_ <= std::numeric_limits<T>::max());
841 m = static_cast<T>(m_);
843 // Initialisation made m non-zero.
844 MOZ_ASSERT(m);
846 // Test that all the divisions in the range we expected would work.
847 #ifdef MOZ_DEBUG
848 for (unsigned num = 0; num < max; num += div) {
849 MOZ_ASSERT(num / div == divide(num));
851 #endif
854 // Note that this always occurs in uint32_t regardless of m's type. If m is
855 // a uint16_t it will be zero-extended before the multiplication. We also use
856 // uint32_t rather than something that could possibly be larger because it is
857 // most-likely the cheapest multiplication.
858 inline uint32_t divide(uint32_t num) const {
859 // Check that m was initialised.
860 MOZ_ASSERT(m);
861 return (num * m) >> p;
865 template <typename T>
866 unsigned inline operator/(unsigned num, FastDivisor<T> divisor) {
867 return divisor.divide(num);
870 // ***************************************************************************
871 // Radix tree data structures.
873 // The number of bits passed to the template is the number of significant bits
874 // in an address to do a radix lookup with.
876 // An address is looked up by splitting it in kBitsPerLevel bit chunks, except
877 // the most significant bits, where the bit chunk is kBitsAtLevel1 which can be
878 // different if Bits is not a multiple of kBitsPerLevel.
880 // With e.g. sizeof(void*)=4, Bits=16 and kBitsPerLevel=8, an address is split
881 // like the following:
882 // 0x12345678 -> mRoot[0x12][0x34]
883 template <size_t Bits>
884 class AddressRadixTree {
885 // Size of each radix tree node (as a power of 2).
886 // This impacts tree depth.
887 #ifdef HAVE_64BIT_BUILD
888 static const size_t kNodeSize = kCacheLineSize;
889 #else
890 static const size_t kNodeSize = 16_KiB;
891 #endif
892 static const size_t kBitsPerLevel = LOG2(kNodeSize) - LOG2(sizeof(void*));
893 static const size_t kBitsAtLevel1 =
894 (Bits % kBitsPerLevel) ? Bits % kBitsPerLevel : kBitsPerLevel;
895 static const size_t kHeight = (Bits + kBitsPerLevel - 1) / kBitsPerLevel;
896 static_assert(kBitsAtLevel1 + (kHeight - 1) * kBitsPerLevel == Bits,
897 "AddressRadixTree parameters don't work out");
899 Mutex mLock MOZ_UNANNOTATED;
900 void** mRoot;
902 public:
903 bool Init();
905 inline void* Get(void* aAddr);
907 // Returns whether the value was properly set.
908 inline bool Set(void* aAddr, void* aValue);
910 inline bool Unset(void* aAddr) { return Set(aAddr, nullptr); }
912 private:
913 inline void** GetSlot(void* aAddr, bool aCreate = false);
916 // ***************************************************************************
917 // Arena data structures.
919 struct arena_bin_t;
921 struct ArenaChunkMapLink {
922 static RedBlackTreeNode<arena_chunk_map_t>& GetTreeNode(
923 arena_chunk_map_t* aThis) {
924 return aThis->link;
928 struct ArenaRunTreeTrait : public ArenaChunkMapLink {
929 static inline Order Compare(arena_chunk_map_t* aNode,
930 arena_chunk_map_t* aOther) {
931 MOZ_ASSERT(aNode);
932 MOZ_ASSERT(aOther);
933 return CompareAddr(aNode, aOther);
937 struct ArenaAvailTreeTrait : public ArenaChunkMapLink {
938 static inline Order Compare(arena_chunk_map_t* aNode,
939 arena_chunk_map_t* aOther) {
940 size_t size1 = aNode->bits & ~gPageSizeMask;
941 size_t size2 = aOther->bits & ~gPageSizeMask;
942 Order ret = CompareInt(size1, size2);
943 return (ret != Order::eEqual)
944 ? ret
945 : CompareAddr((aNode->bits & CHUNK_MAP_KEY) ? nullptr : aNode,
946 aOther);
950 struct ArenaDirtyChunkTrait {
951 static RedBlackTreeNode<arena_chunk_t>& GetTreeNode(arena_chunk_t* aThis) {
952 return aThis->link_dirty;
955 static inline Order Compare(arena_chunk_t* aNode, arena_chunk_t* aOther) {
956 MOZ_ASSERT(aNode);
957 MOZ_ASSERT(aOther);
958 return CompareAddr(aNode, aOther);
962 #ifdef MALLOC_DOUBLE_PURGE
963 namespace mozilla {
965 template <>
966 struct GetDoublyLinkedListElement<arena_chunk_t> {
967 static DoublyLinkedListElement<arena_chunk_t>& Get(arena_chunk_t* aThis) {
968 return aThis->chunks_madvised_elem;
971 } // namespace mozilla
972 #endif
974 struct arena_run_t {
975 #if defined(MOZ_DIAGNOSTIC_ASSERT_ENABLED)
976 uint32_t mMagic;
977 # define ARENA_RUN_MAGIC 0x384adf93
979 // On 64-bit platforms, having the arena_bin_t pointer following
980 // the mMagic field means there's padding between both fields, making
981 // the run header larger than necessary.
982 // But when MOZ_DIAGNOSTIC_ASSERT_ENABLED is not set, starting the
983 // header with this field followed by the arena_bin_t pointer yields
984 // the same padding. We do want the mMagic field to appear first, so
985 // depending whether MOZ_DIAGNOSTIC_ASSERT_ENABLED is set or not, we
986 // move some field to avoid padding.
988 // Number of free regions in run.
989 unsigned mNumFree;
990 #endif
992 // Bin this run is associated with.
993 arena_bin_t* mBin;
995 // Index of first element that might have a free region.
996 unsigned mRegionsMinElement;
998 #if !defined(MOZ_DIAGNOSTIC_ASSERT_ENABLED)
999 // Number of free regions in run.
1000 unsigned mNumFree;
1001 #endif
1003 // Bitmask of in-use regions (0: in use, 1: free).
1004 unsigned mRegionsMask[1]; // Dynamically sized.
1007 struct arena_bin_t {
1008 // Current run being used to service allocations of this bin's size
1009 // class.
1010 arena_run_t* mCurrentRun;
1012 // Tree of non-full runs. This tree is used when looking for an
1013 // existing run when mCurrentRun is no longer usable. We choose the
1014 // non-full run that is lowest in memory; this policy tends to keep
1015 // objects packed well, and it can also help reduce the number of
1016 // almost-empty chunks.
1017 RedBlackTree<arena_chunk_map_t, ArenaRunTreeTrait> mNonFullRuns;
1019 // Bin's size class.
1020 size_t mSizeClass;
1022 // Total number of regions in a run for this bin's size class.
1023 uint32_t mRunNumRegions;
1025 // Number of elements in a run's mRegionsMask for this bin's size class.
1026 uint32_t mRunNumRegionsMask;
1028 // Offset of first region in a run for this bin's size class.
1029 uint32_t mRunFirstRegionOffset;
1031 // Current number of runs in this bin, full or otherwise.
1032 uint32_t mNumRuns;
1034 // A constant for fast division by size class. This value is 16 bits wide so
1035 // it is placed last.
1036 FastDivisor<uint16_t> mSizeDivisor;
1038 // Total number of pages in a run for this bin's size class.
1039 uint8_t mRunSizePages;
1041 // Amount of overhead runs are allowed to have.
1042 static constexpr double kRunOverhead = 1.6_percent;
1043 static constexpr double kRunRelaxedOverhead = 2.4_percent;
1045 // Initialize a bin for the given size class.
1046 // The generated run sizes, for a page size of 4 KiB, are:
1047 // size|run size|run size|run size|run
1048 // class|size class|size class|size class|size
1049 // 4 4 KiB 8 4 KiB 16 4 KiB 32 4 KiB
1050 // 48 4 KiB 64 4 KiB 80 4 KiB 96 4 KiB
1051 // 112 4 KiB 128 8 KiB 144 4 KiB 160 8 KiB
1052 // 176 4 KiB 192 4 KiB 208 8 KiB 224 4 KiB
1053 // 240 8 KiB 256 16 KiB 272 8 KiB 288 4 KiB
1054 // 304 12 KiB 320 12 KiB 336 4 KiB 352 8 KiB
1055 // 368 4 KiB 384 8 KiB 400 20 KiB 416 16 KiB
1056 // 432 12 KiB 448 4 KiB 464 16 KiB 480 8 KiB
1057 // 496 20 KiB 512 32 KiB 768 16 KiB 1024 64 KiB
1058 // 1280 24 KiB 1536 32 KiB 1792 16 KiB 2048 128 KiB
1059 // 2304 16 KiB 2560 48 KiB 2816 36 KiB 3072 64 KiB
1060 // 3328 36 KiB 3584 32 KiB 3840 64 KiB
1061 inline void Init(SizeClass aSizeClass);
1064 // We try to keep the above structure aligned with common cache lines sizes,
1065 // often that's 64 bytes on x86 and ARM, we don't make assumptions for other
1066 // architectures.
1067 #if defined(__x86_64__) || defined(__aarch64__)
1068 // On 64bit platforms this structure is often 48 bytes
1069 // long, which means every other array element will be properly aligned.
1070 static_assert(sizeof(arena_bin_t) == 48);
1071 #elif defined(__x86__) || defined(__arm__)
1072 static_assert(sizeof(arena_bin_t) == 32);
1073 #endif
1075 struct arena_t {
1076 #if defined(MOZ_DIAGNOSTIC_ASSERT_ENABLED)
1077 uint32_t mMagic;
1078 # define ARENA_MAGIC 0x947d3d24
1079 #endif
1081 // Linkage for the tree of arenas by id.
1082 RedBlackTreeNode<arena_t> mLink;
1084 // Arena id, that we keep away from the beginning of the struct so that
1085 // free list pointers in TypedBaseAlloc<arena_t> don't overflow in it,
1086 // and it keeps the value it had after the destructor.
1087 arena_id_t mId;
1089 // All operations on this arena require that lock be locked. The MaybeMutex
1090 // class well elude locking if the arena is accessed from a single thread
1091 // only.
1092 MaybeMutex mLock MOZ_UNANNOTATED;
1094 arena_stats_t mStats;
1096 private:
1097 // Tree of dirty-page-containing chunks this arena manages.
1098 RedBlackTree<arena_chunk_t, ArenaDirtyChunkTrait> mChunksDirty;
1100 #ifdef MALLOC_DOUBLE_PURGE
1101 // Head of a linked list of MADV_FREE'd-page-containing chunks this
1102 // arena manages.
1103 DoublyLinkedList<arena_chunk_t> mChunksMAdvised;
1104 #endif
1106 // In order to avoid rapid chunk allocation/deallocation when an arena
1107 // oscillates right on the cusp of needing a new chunk, cache the most
1108 // recently freed chunk. The spare is left in the arena's chunk trees
1109 // until it is deleted.
1111 // There is one spare chunk per arena, rather than one spare total, in
1112 // order to avoid interactions between multiple threads that could make
1113 // a single spare inadequate.
1114 arena_chunk_t* mSpare;
1116 // A per-arena opt-in to randomize the offset of small allocations
1117 bool mRandomizeSmallAllocations;
1119 // Whether this is a private arena. Multiple public arenas are just a
1120 // performance optimization and not a safety feature.
1122 // Since, for example, we don't want thread-local arenas to grow too much, we
1123 // use the default arena for bigger allocations. We use this member to allow
1124 // realloc() to switch out of our arena if needed (which is not allowed for
1125 // private arenas for security).
1126 bool mIsPrivate;
1128 // A pseudorandom number generator. Initially null, it gets initialized
1129 // on first use to avoid recursive malloc initialization (e.g. on OSX
1130 // arc4random allocates memory).
1131 mozilla::non_crypto::XorShift128PlusRNG* mPRNG;
1133 public:
1134 // Current count of pages within unused runs that are potentially
1135 // dirty, and for which madvise(... MADV_FREE) has not been called. By
1136 // tracking this, we can institute a limit on how much dirty unused
1137 // memory is mapped for each arena.
1138 size_t mNumDirty;
1140 // Maximum value allowed for mNumDirty.
1141 size_t mMaxDirty;
1143 int32_t mMaxDirtyIncreaseOverride;
1144 int32_t mMaxDirtyDecreaseOverride;
1146 private:
1147 // Size/address-ordered tree of this arena's available runs. This tree
1148 // is used for first-best-fit run allocation.
1149 RedBlackTree<arena_chunk_map_t, ArenaAvailTreeTrait> mRunsAvail;
1151 public:
1152 // mBins is used to store rings of free regions of the following sizes,
1153 // assuming a 16-byte quantum, 4kB pagesize, and default MALLOC_OPTIONS.
1155 // | mBins[i] | size |
1156 // +----------+------+
1157 // | 0 | 2 |
1158 // | 1 | 4 |
1159 // | 2 | 8 |
1160 // +----------+------+
1161 // | 3 | 16 |
1162 // | 4 | 32 |
1163 // | 5 | 48 |
1164 // | 6 | 64 |
1165 // | : :
1166 // | : :
1167 // | 33 | 496 |
1168 // | 34 | 512 |
1169 // +----------+------+
1170 // | 35 | 768 |
1171 // | 36 | 1024 |
1172 // | : :
1173 // | : :
1174 // | 46 | 3584 |
1175 // | 47 | 3840 |
1176 // +----------+------+
1177 arena_bin_t mBins[1]; // Dynamically sized.
1179 explicit arena_t(arena_params_t* aParams, bool aIsPrivate);
1180 ~arena_t();
1182 private:
1183 void InitChunk(arena_chunk_t* aChunk, bool aZeroed);
1185 // This may return a chunk that should be destroyed with chunk_dealloc outside
1186 // of the arena lock. It is not the same chunk as was passed in (since that
1187 // chunk now becomes mSpare).
1188 [[nodiscard]] arena_chunk_t* DeallocChunk(arena_chunk_t* aChunk);
1190 arena_run_t* AllocRun(size_t aSize, bool aLarge, bool aZero);
1192 arena_chunk_t* DallocRun(arena_run_t* aRun, bool aDirty);
1194 [[nodiscard]] bool SplitRun(arena_run_t* aRun, size_t aSize, bool aLarge,
1195 bool aZero);
1197 void TrimRunHead(arena_chunk_t* aChunk, arena_run_t* aRun, size_t aOldSize,
1198 size_t aNewSize);
1200 void TrimRunTail(arena_chunk_t* aChunk, arena_run_t* aRun, size_t aOldSize,
1201 size_t aNewSize, bool dirty);
1203 arena_run_t* GetNonFullBinRun(arena_bin_t* aBin);
1205 inline uint8_t FindFreeBitInMask(uint32_t aMask, uint32_t& aRng);
1207 inline void* ArenaRunRegAlloc(arena_run_t* aRun, arena_bin_t* aBin);
1209 inline void* MallocSmall(size_t aSize, bool aZero);
1211 void* MallocLarge(size_t aSize, bool aZero);
1213 void* MallocHuge(size_t aSize, bool aZero);
1215 void* PallocLarge(size_t aAlignment, size_t aSize, size_t aAllocSize);
1217 void* PallocHuge(size_t aSize, size_t aAlignment, bool aZero);
1219 void RallocShrinkLarge(arena_chunk_t* aChunk, void* aPtr, size_t aSize,
1220 size_t aOldSize);
1222 bool RallocGrowLarge(arena_chunk_t* aChunk, void* aPtr, size_t aSize,
1223 size_t aOldSize);
1225 void* RallocSmallOrLarge(void* aPtr, size_t aSize, size_t aOldSize);
1227 void* RallocHuge(void* aPtr, size_t aSize, size_t aOldSize);
1229 public:
1230 inline void* Malloc(size_t aSize, bool aZero);
1232 void* Palloc(size_t aAlignment, size_t aSize);
1234 // This may return a chunk that should be destroyed with chunk_dealloc outside
1235 // of the arena lock. It is not the same chunk as was passed in (since that
1236 // chunk now becomes mSpare).
1237 [[nodiscard]] inline arena_chunk_t* DallocSmall(arena_chunk_t* aChunk,
1238 void* aPtr,
1239 arena_chunk_map_t* aMapElm);
1241 [[nodiscard]] arena_chunk_t* DallocLarge(arena_chunk_t* aChunk, void* aPtr);
1243 void* Ralloc(void* aPtr, size_t aSize, size_t aOldSize);
1245 size_t EffectiveMaxDirty();
1247 // Passing one means purging all.
1248 void Purge(size_t aMaxDirty);
1250 void HardPurge();
1252 void* operator new(size_t aCount) = delete;
1254 void* operator new(size_t aCount, const fallible_t&) noexcept;
1256 void operator delete(void*);
1259 struct ArenaTreeTrait {
1260 static RedBlackTreeNode<arena_t>& GetTreeNode(arena_t* aThis) {
1261 return aThis->mLink;
1264 static inline Order Compare(arena_t* aNode, arena_t* aOther) {
1265 MOZ_ASSERT(aNode);
1266 MOZ_ASSERT(aOther);
1267 return CompareInt(aNode->mId, aOther->mId);
1271 // Bookkeeping for all the arenas used by the allocator.
1272 // Arenas are separated in two categories:
1273 // - "private" arenas, used through the moz_arena_* API
1274 // - all the other arenas: the default arena, and thread-local arenas,
1275 // used by the standard API.
1276 class ArenaCollection {
1277 public:
1278 bool Init() {
1279 mArenas.Init();
1280 mPrivateArenas.Init();
1281 arena_params_t params;
1282 // The main arena allows more dirty pages than the default for other arenas.
1283 params.mMaxDirty = opt_dirty_max;
1284 mDefaultArena =
1285 mLock.Init() ? CreateArena(/* aIsPrivate = */ false, &params) : nullptr;
1286 return bool(mDefaultArena);
1289 inline arena_t* GetById(arena_id_t aArenaId, bool aIsPrivate);
1291 arena_t* CreateArena(bool aIsPrivate, arena_params_t* aParams);
1293 void DisposeArena(arena_t* aArena) {
1294 MutexAutoLock lock(mLock);
1295 MOZ_RELEASE_ASSERT(mPrivateArenas.Search(aArena),
1296 "Can only dispose of private arenas");
1297 mPrivateArenas.Remove(aArena);
1298 delete aArena;
1301 void SetDefaultMaxDirtyPageModifier(int32_t aModifier) {
1302 mDefaultMaxDirtyPageModifier = aModifier;
1304 int32_t DefaultMaxDirtyPageModifier() { return mDefaultMaxDirtyPageModifier; }
1306 using Tree = RedBlackTree<arena_t, ArenaTreeTrait>;
1308 struct Iterator : Tree::Iterator {
1309 explicit Iterator(Tree* aTree, Tree* aSecondTree)
1310 : Tree::Iterator(aTree), mNextTree(aSecondTree) {}
1312 Item<Iterator> begin() {
1313 return Item<Iterator>(this, *Tree::Iterator::begin());
1316 Item<Iterator> end() { return Item<Iterator>(this, nullptr); }
1318 arena_t* Next() {
1319 arena_t* result = Tree::Iterator::Next();
1320 if (!result && mNextTree) {
1321 new (this) Iterator(mNextTree, nullptr);
1322 result = *Tree::Iterator::begin();
1324 return result;
1327 private:
1328 Tree* mNextTree;
1331 Iterator iter() { return Iterator(&mArenas, &mPrivateArenas); }
1333 inline arena_t* GetDefault() { return mDefaultArena; }
1335 Mutex mLock MOZ_UNANNOTATED;
1337 // We're running on the main thread which is set by a call to SetMainThread().
1338 bool IsOnMainThread() const {
1339 return mMainThreadId.isSome() && mMainThreadId.value() == GetThreadId();
1342 // We're running on the main thread or SetMainThread() has never been called.
1343 bool IsOnMainThreadWeak() const {
1344 return mMainThreadId.isNothing() || IsOnMainThread();
1347 // After a fork set the new thread ID in the child.
1348 void PostForkFixMainThread() {
1349 if (mMainThreadId.isSome()) {
1350 // Only if the main thread has been defined.
1351 mMainThreadId = Some(GetThreadId());
1355 void SetMainThread() {
1356 MutexAutoLock lock(mLock);
1357 MOZ_ASSERT(mMainThreadId.isNothing());
1358 mMainThreadId = Some(GetThreadId());
1361 private:
1362 inline arena_t* GetByIdInternal(arena_id_t aArenaId, bool aIsPrivate);
1364 arena_t* mDefaultArena;
1365 arena_id_t mLastPublicArenaId;
1366 Tree mArenas;
1367 Tree mPrivateArenas;
1368 Atomic<int32_t> mDefaultMaxDirtyPageModifier;
1369 Maybe<ThreadId> mMainThreadId;
1372 static ArenaCollection gArenas;
1374 // ******
1375 // Chunks.
1376 static AddressRadixTree<(sizeof(void*) << 3) - LOG2(kChunkSize)> gChunkRTree;
1378 // Protects chunk-related data structures.
1379 static Mutex chunks_mtx;
1381 // Trees of chunks that were previously allocated (trees differ only in node
1382 // ordering). These are used when allocating chunks, in an attempt to re-use
1383 // address space. Depending on function, different tree orderings are needed,
1384 // which is why there are two trees with the same contents.
1385 static RedBlackTree<extent_node_t, ExtentTreeSzTrait> gChunksBySize
1386 MOZ_GUARDED_BY(chunks_mtx);
1387 static RedBlackTree<extent_node_t, ExtentTreeTrait> gChunksByAddress
1388 MOZ_GUARDED_BY(chunks_mtx);
1390 // Protects huge allocation-related data structures.
1391 static Mutex huge_mtx;
1393 // Tree of chunks that are stand-alone huge allocations.
1394 static RedBlackTree<extent_node_t, ExtentTreeTrait> huge
1395 MOZ_GUARDED_BY(huge_mtx);
1397 // Huge allocation statistics.
1398 static size_t huge_allocated MOZ_GUARDED_BY(huge_mtx);
1399 static size_t huge_mapped MOZ_GUARDED_BY(huge_mtx);
1401 // **************************
1402 // base (internal allocation).
1404 static Mutex base_mtx;
1406 // Current pages that are being used for internal memory allocations. These
1407 // pages are carved up in cacheline-size quanta, so that there is no chance of
1408 // false cache line sharing.
1409 static void* base_pages MOZ_GUARDED_BY(base_mtx);
1410 static void* base_next_addr MOZ_GUARDED_BY(base_mtx);
1411 static void* base_next_decommitted MOZ_GUARDED_BY(base_mtx);
1412 // Address immediately past base_pages.
1413 static void* base_past_addr MOZ_GUARDED_BY(base_mtx);
1414 static size_t base_mapped MOZ_GUARDED_BY(base_mtx);
1415 static size_t base_committed MOZ_GUARDED_BY(base_mtx);
1417 // ******
1418 // Arenas.
1420 // The arena associated with the current thread (per
1421 // jemalloc_thread_local_arena) On OSX, __thread/thread_local circles back
1422 // calling malloc to allocate storage on first access on each thread, which
1423 // leads to an infinite loop, but pthread-based TLS somehow doesn't have this
1424 // problem.
1425 #if !defined(XP_DARWIN)
1426 static MOZ_THREAD_LOCAL(arena_t*) thread_arena;
1427 #else
1428 static detail::ThreadLocal<arena_t*, detail::ThreadLocalKeyStorage>
1429 thread_arena;
1430 #endif
1432 // *****************************
1433 // Runtime configuration options.
1435 // Junk - write "junk" to freshly allocated cells.
1436 // Poison - write "poison" to cells upon deallocation.
1438 const uint8_t kAllocJunk = 0xe4;
1439 const uint8_t kAllocPoison = 0xe5;
1441 #ifdef MALLOC_RUNTIME_CONFIG
1442 static bool opt_junk = true;
1443 static bool opt_poison = true;
1444 static bool opt_zero = false;
1445 #else
1446 static const bool opt_junk = false;
1447 static const bool opt_poison = true;
1448 static const bool opt_zero = false;
1449 #endif
1450 static bool opt_randomize_small = true;
1452 // ***************************************************************************
1453 // Begin forward declarations.
1455 static void* chunk_alloc(size_t aSize, size_t aAlignment, bool aBase,
1456 bool* aZeroed = nullptr);
1457 static void chunk_dealloc(void* aChunk, size_t aSize, ChunkType aType);
1458 static void chunk_ensure_zero(void* aPtr, size_t aSize, bool aZeroed);
1459 static void huge_dalloc(void* aPtr, arena_t* aArena);
1460 static bool malloc_init_hard();
1462 #ifndef XP_WIN
1463 # ifdef XP_DARWIN
1464 # define FORK_HOOK extern "C"
1465 # else
1466 # define FORK_HOOK static
1467 # endif
1468 FORK_HOOK void _malloc_prefork(void);
1469 FORK_HOOK void _malloc_postfork_parent(void);
1470 FORK_HOOK void _malloc_postfork_child(void);
1471 #endif
1473 // End forward declarations.
1474 // ***************************************************************************
1476 // FreeBSD's pthreads implementation calls malloc(3), so the malloc
1477 // implementation has to take pains to avoid infinite recursion during
1478 // initialization.
1479 // Returns whether the allocator was successfully initialized.
1480 static inline bool malloc_init() {
1481 if (malloc_initialized == false) {
1482 return malloc_init_hard();
1485 return true;
1488 static void _malloc_message(const char* p) {
1489 #if !defined(XP_WIN)
1490 # define _write write
1491 #endif
1492 // Pretend to check _write() errors to suppress gcc warnings about
1493 // warn_unused_result annotations in some versions of glibc headers.
1494 if (_write(STDERR_FILENO, p, (unsigned int)strlen(p)) < 0) {
1495 return;
1499 template <typename... Args>
1500 static void _malloc_message(const char* p, Args... args) {
1501 _malloc_message(p);
1502 _malloc_message(args...);
1505 #ifdef ANDROID
1506 // Android's pthread.h does not declare pthread_atfork() until SDK 21.
1507 extern "C" MOZ_EXPORT int pthread_atfork(void (*)(void), void (*)(void),
1508 void (*)(void));
1509 #endif
1511 // ***************************************************************************
1512 // Begin Utility functions/macros.
1514 // Return the chunk address for allocation address a.
1515 static inline arena_chunk_t* GetChunkForPtr(const void* aPtr) {
1516 return (arena_chunk_t*)(uintptr_t(aPtr) & ~kChunkSizeMask);
1519 // Return the chunk offset of address a.
1520 static inline size_t GetChunkOffsetForPtr(const void* aPtr) {
1521 return (size_t)(uintptr_t(aPtr) & kChunkSizeMask);
1524 static inline const char* _getprogname(void) { return "<jemalloc>"; }
1526 static inline void MaybePoison(void* aPtr, size_t aSize) {
1527 if (opt_poison) {
1528 memset(aPtr, kAllocPoison, aSize);
1532 // Fill the given range of memory with zeroes or junk depending on opt_junk and
1533 // opt_zero.
1534 static inline void ApplyZeroOrJunk(void* aPtr, size_t aSize) {
1535 if (opt_junk) {
1536 memset(aPtr, kAllocJunk, aSize);
1537 } else if (opt_zero) {
1538 memset(aPtr, 0, aSize);
1542 // On Windows, delay crashing on OOM.
1543 #ifdef XP_WIN
1545 // Implementation of VirtualAlloc wrapper (bug 1716727).
1546 namespace MozAllocRetries {
1548 // Maximum retry count on OOM.
1549 constexpr size_t kMaxAttempts = 10;
1550 // Minimum delay time between retries. (The actual delay time may be larger. See
1551 // Microsoft's documentation for ::Sleep() for details.)
1552 constexpr size_t kDelayMs = 50;
1554 using StallSpecs = ::mozilla::StallSpecs;
1556 static constexpr StallSpecs maxStall = {.maxAttempts = kMaxAttempts,
1557 .delayMs = kDelayMs};
1559 static inline StallSpecs GetStallSpecs() {
1560 # if defined(JS_STANDALONE)
1561 // GetGeckoProcessType() isn't available in this configuration. (SpiderMonkey
1562 // on Windows mostly skips this in favor of directly calling ::VirtualAlloc(),
1563 // though, so it's probably not going to matter whether we stall here or not.)
1564 return maxStall;
1565 # else
1566 switch (GetGeckoProcessType()) {
1567 // For the main process, stall for the maximum permissible time period. (The
1568 // main process is the most important one to keep alive.)
1569 case GeckoProcessType::GeckoProcessType_Default:
1570 return maxStall;
1572 // For all other process types, stall for at most half as long.
1573 default:
1574 return {.maxAttempts = maxStall.maxAttempts / 2,
1575 .delayMs = maxStall.delayMs};
1577 # endif
1580 // Drop-in wrapper around VirtualAlloc. When out of memory, may attempt to stall
1581 // and retry rather than returning immediately, in hopes that the page file is
1582 // about to be expanded by Windows.
1584 // Ref: https://docs.microsoft.com/en-us/troubleshoot/windows-client/performance/slow-page-file-growth-memory-allocation-errors
1585 [[nodiscard]] void* MozVirtualAlloc(LPVOID lpAddress, SIZE_T dwSize,
1586 DWORD flAllocationType, DWORD flProtect) {
1587 DWORD const lastError = ::GetLastError();
1589 constexpr auto IsOOMError = [] {
1590 switch (::GetLastError()) {
1591 // This is the usual error result from VirtualAlloc for OOM.
1592 case ERROR_COMMITMENT_LIMIT:
1593 // Although rare, this has also been observed in low-memory situations.
1594 // (Presumably this means Windows can't allocate enough kernel-side space
1595 // for its own internal representation of the process's virtual address
1596 // space.)
1597 case ERROR_NOT_ENOUGH_MEMORY:
1598 return true;
1600 return false;
1604 void* ptr = ::VirtualAlloc(lpAddress, dwSize, flAllocationType, flProtect);
1605 if (MOZ_LIKELY(ptr)) return ptr;
1607 // We can't do anything for errors other than OOM...
1608 if (!IsOOMError()) return nullptr;
1609 // ... or if this wasn't a request to commit memory in the first place.
1610 // (This function has no strategy for resolving MEM_RESERVE failures.)
1611 if (!(flAllocationType & MEM_COMMIT)) return nullptr;
1614 // Retry as many times as desired (possibly zero).
1615 const StallSpecs stallSpecs = GetStallSpecs();
1617 const auto ret =
1618 stallSpecs.StallAndRetry(&::Sleep, [&]() -> std::optional<void*> {
1619 void* ptr =
1620 ::VirtualAlloc(lpAddress, dwSize, flAllocationType, flProtect);
1622 if (ptr) {
1623 // The OOM status has been handled, and should not be reported to
1624 // telemetry.
1625 if (IsOOMError()) {
1626 ::SetLastError(lastError);
1628 return ptr;
1631 // Failure for some reason other than OOM.
1632 if (!IsOOMError()) {
1633 return nullptr;
1636 return std::nullopt;
1639 return ret.value_or(nullptr);
1641 } // namespace MozAllocRetries
1643 using MozAllocRetries::MozVirtualAlloc;
1645 namespace mozilla {
1646 MOZ_JEMALLOC_API StallSpecs GetAllocatorStallSpecs() {
1647 return ::MozAllocRetries::GetStallSpecs();
1649 } // namespace mozilla
1651 #endif // XP_WIN
1653 // ***************************************************************************
1655 static inline void pages_decommit(void* aAddr, size_t aSize) {
1656 #ifdef XP_WIN
1657 // The region starting at addr may have been allocated in multiple calls
1658 // to VirtualAlloc and recycled, so decommitting the entire region in one
1659 // go may not be valid. However, since we allocate at least a chunk at a
1660 // time, we may touch any region in chunksized increments.
1661 size_t pages_size = std::min(aSize, kChunkSize - GetChunkOffsetForPtr(aAddr));
1662 while (aSize > 0) {
1663 // This will cause Access Violation on read and write and thus act as a
1664 // guard page or region as well.
1665 if (!VirtualFree(aAddr, pages_size, MEM_DECOMMIT)) {
1666 MOZ_CRASH();
1668 aAddr = (void*)((uintptr_t)aAddr + pages_size);
1669 aSize -= pages_size;
1670 pages_size = std::min(aSize, kChunkSize);
1672 #else
1673 if (mmap(aAddr, aSize, PROT_NONE, MAP_FIXED | MAP_PRIVATE | MAP_ANON, -1,
1674 0) == MAP_FAILED) {
1675 // We'd like to report the OOM for our tooling, but we can't allocate
1676 // memory at this point, so avoid the use of printf.
1677 const char out_of_mappings[] =
1678 "[unhandlable oom] Failed to mmap, likely no more mappings "
1679 "available " __FILE__ " : " MOZ_STRINGIFY(__LINE__);
1680 if (errno == ENOMEM) {
1681 # ifndef ANDROID
1682 fputs(out_of_mappings, stderr);
1683 fflush(stderr);
1684 # endif
1685 MOZ_CRASH_ANNOTATE(out_of_mappings);
1687 MOZ_REALLY_CRASH(__LINE__);
1689 MozTagAnonymousMemory(aAddr, aSize, "jemalloc-decommitted");
1690 #endif
1693 // Commit pages. Returns whether pages were committed.
1694 [[nodiscard]] static inline bool pages_commit(void* aAddr, size_t aSize) {
1695 #ifdef XP_WIN
1696 // The region starting at addr may have been allocated in multiple calls
1697 // to VirtualAlloc and recycled, so committing the entire region in one
1698 // go may not be valid. However, since we allocate at least a chunk at a
1699 // time, we may touch any region in chunksized increments.
1700 size_t pages_size = std::min(aSize, kChunkSize - GetChunkOffsetForPtr(aAddr));
1701 while (aSize > 0) {
1702 if (!MozVirtualAlloc(aAddr, pages_size, MEM_COMMIT, PAGE_READWRITE)) {
1703 return false;
1705 aAddr = (void*)((uintptr_t)aAddr + pages_size);
1706 aSize -= pages_size;
1707 pages_size = std::min(aSize, kChunkSize);
1709 #else
1710 if (mmap(aAddr, aSize, PROT_READ | PROT_WRITE,
1711 MAP_FIXED | MAP_PRIVATE | MAP_ANON, -1, 0) == MAP_FAILED) {
1712 return false;
1714 MozTagAnonymousMemory(aAddr, aSize, "jemalloc");
1715 #endif
1716 return true;
1719 static bool base_pages_alloc(size_t minsize) MOZ_REQUIRES(base_mtx) {
1720 size_t csize;
1721 size_t pminsize;
1723 MOZ_ASSERT(minsize != 0);
1724 csize = CHUNK_CEILING(minsize);
1725 base_pages = chunk_alloc(csize, kChunkSize, true);
1726 if (!base_pages) {
1727 return true;
1729 base_next_addr = base_pages;
1730 base_past_addr = (void*)((uintptr_t)base_pages + csize);
1731 // Leave enough pages for minsize committed, since otherwise they would
1732 // have to be immediately recommitted.
1733 pminsize = PAGE_CEILING(minsize);
1734 base_next_decommitted = (void*)((uintptr_t)base_pages + pminsize);
1735 if (pminsize < csize) {
1736 pages_decommit(base_next_decommitted, csize - pminsize);
1738 base_mapped += csize;
1739 base_committed += pminsize;
1741 return false;
1744 static void* base_alloc(size_t aSize) {
1745 void* ret;
1746 size_t csize;
1748 // Round size up to nearest multiple of the cacheline size.
1749 csize = CACHELINE_CEILING(aSize);
1751 MutexAutoLock lock(base_mtx);
1752 // Make sure there's enough space for the allocation.
1753 if ((uintptr_t)base_next_addr + csize > (uintptr_t)base_past_addr) {
1754 if (base_pages_alloc(csize)) {
1755 return nullptr;
1758 // Allocate.
1759 ret = base_next_addr;
1760 base_next_addr = (void*)((uintptr_t)base_next_addr + csize);
1761 // Make sure enough pages are committed for the new allocation.
1762 if ((uintptr_t)base_next_addr > (uintptr_t)base_next_decommitted) {
1763 void* pbase_next_addr = (void*)(PAGE_CEILING((uintptr_t)base_next_addr));
1765 if (!pages_commit(
1766 base_next_decommitted,
1767 (uintptr_t)pbase_next_addr - (uintptr_t)base_next_decommitted)) {
1768 return nullptr;
1771 base_committed +=
1772 (uintptr_t)pbase_next_addr - (uintptr_t)base_next_decommitted;
1773 base_next_decommitted = pbase_next_addr;
1776 return ret;
1779 static void* base_calloc(size_t aNumber, size_t aSize) {
1780 void* ret = base_alloc(aNumber * aSize);
1781 if (ret) {
1782 memset(ret, 0, aNumber * aSize);
1784 return ret;
1787 // A specialization of the base allocator with a free list.
1788 template <typename T>
1789 struct TypedBaseAlloc {
1790 static T* sFirstFree;
1792 static size_t size_of() { return sizeof(T); }
1794 static T* alloc() {
1795 T* ret;
1797 base_mtx.Lock();
1798 if (sFirstFree) {
1799 ret = sFirstFree;
1800 sFirstFree = *(T**)ret;
1801 base_mtx.Unlock();
1802 } else {
1803 base_mtx.Unlock();
1804 ret = (T*)base_alloc(size_of());
1807 return ret;
1810 static void dealloc(T* aNode) {
1811 MutexAutoLock lock(base_mtx);
1812 *(T**)aNode = sFirstFree;
1813 sFirstFree = aNode;
1817 using ExtentAlloc = TypedBaseAlloc<extent_node_t>;
1819 template <>
1820 extent_node_t* ExtentAlloc::sFirstFree = nullptr;
1822 template <>
1823 arena_t* TypedBaseAlloc<arena_t>::sFirstFree = nullptr;
1825 template <>
1826 size_t TypedBaseAlloc<arena_t>::size_of() {
1827 // Allocate enough space for trailing bins.
1828 return sizeof(arena_t) + (sizeof(arena_bin_t) * (NUM_SMALL_CLASSES - 1));
1831 template <typename T>
1832 struct BaseAllocFreePolicy {
1833 void operator()(T* aPtr) { TypedBaseAlloc<T>::dealloc(aPtr); }
1836 using UniqueBaseNode =
1837 UniquePtr<extent_node_t, BaseAllocFreePolicy<extent_node_t>>;
1839 // End Utility functions/macros.
1840 // ***************************************************************************
1841 // Begin chunk management functions.
1843 #ifdef XP_WIN
1845 static void* pages_map(void* aAddr, size_t aSize) {
1846 void* ret = nullptr;
1847 ret = MozVirtualAlloc(aAddr, aSize, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);
1848 return ret;
1851 static void pages_unmap(void* aAddr, size_t aSize) {
1852 if (VirtualFree(aAddr, 0, MEM_RELEASE) == 0) {
1853 _malloc_message(_getprogname(), ": (malloc) Error in VirtualFree()\n");
1856 #else
1858 static void pages_unmap(void* aAddr, size_t aSize) {
1859 if (munmap(aAddr, aSize) == -1) {
1860 char buf[64];
1862 if (strerror_r(errno, buf, sizeof(buf)) == 0) {
1863 _malloc_message(_getprogname(), ": (malloc) Error in munmap(): ", buf,
1864 "\n");
1869 static void* pages_map(void* aAddr, size_t aSize) {
1870 void* ret;
1871 # if defined(__ia64__) || \
1872 (defined(__sparc__) && defined(__arch64__) && defined(__linux__))
1873 // The JS engine assumes that all allocated pointers have their high 17 bits
1874 // clear, which ia64's mmap doesn't support directly. However, we can emulate
1875 // it by passing mmap an "addr" parameter with those bits clear. The mmap will
1876 // return that address, or the nearest available memory above that address,
1877 // providing a near-guarantee that those bits are clear. If they are not, we
1878 // return nullptr below to indicate out-of-memory.
1880 // The addr is chosen as 0x0000070000000000, which still allows about 120TB of
1881 // virtual address space.
1883 // See Bug 589735 for more information.
1884 bool check_placement = true;
1885 if (!aAddr) {
1886 aAddr = (void*)0x0000070000000000;
1887 check_placement = false;
1889 # endif
1891 # if defined(__sparc__) && defined(__arch64__) && defined(__linux__)
1892 const uintptr_t start = 0x0000070000000000ULL;
1893 const uintptr_t end = 0x0000800000000000ULL;
1895 // Copied from js/src/gc/Memory.cpp and adapted for this source
1896 uintptr_t hint;
1897 void* region = MAP_FAILED;
1898 for (hint = start; region == MAP_FAILED && hint + aSize <= end;
1899 hint += kChunkSize) {
1900 region = mmap((void*)hint, aSize, PROT_READ | PROT_WRITE,
1901 MAP_PRIVATE | MAP_ANON, -1, 0);
1902 if (region != MAP_FAILED) {
1903 if (((size_t)region + (aSize - 1)) & 0xffff800000000000) {
1904 if (munmap(region, aSize)) {
1905 MOZ_ASSERT(errno == ENOMEM);
1907 region = MAP_FAILED;
1911 ret = region;
1912 # else
1913 // We don't use MAP_FIXED here, because it can cause the *replacement*
1914 // of existing mappings, and we only want to create new mappings.
1915 ret =
1916 mmap(aAddr, aSize, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANON, -1, 0);
1917 MOZ_ASSERT(ret);
1918 # endif
1919 if (ret == MAP_FAILED) {
1920 ret = nullptr;
1922 # if defined(__ia64__) || \
1923 (defined(__sparc__) && defined(__arch64__) && defined(__linux__))
1924 // If the allocated memory doesn't have its upper 17 bits clear, consider it
1925 // as out of memory.
1926 else if ((long long)ret & 0xffff800000000000) {
1927 munmap(ret, aSize);
1928 ret = nullptr;
1930 // If the caller requested a specific memory location, verify that's what mmap
1931 // returned.
1932 else if (check_placement && ret != aAddr) {
1933 # else
1934 else if (aAddr && ret != aAddr) {
1935 # endif
1936 // We succeeded in mapping memory, but not in the right place.
1937 pages_unmap(ret, aSize);
1938 ret = nullptr;
1940 if (ret) {
1941 MozTagAnonymousMemory(ret, aSize, "jemalloc");
1944 # if defined(__ia64__) || \
1945 (defined(__sparc__) && defined(__arch64__) && defined(__linux__))
1946 MOZ_ASSERT(!ret || (!check_placement && ret) ||
1947 (check_placement && ret == aAddr));
1948 # else
1949 MOZ_ASSERT(!ret || (!aAddr && ret != aAddr) || (aAddr && ret == aAddr));
1950 # endif
1951 return ret;
1953 #endif
1955 #ifdef XP_DARWIN
1956 # define VM_COPY_MIN kChunkSize
1957 static inline void pages_copy(void* dest, const void* src, size_t n) {
1958 MOZ_ASSERT((void*)((uintptr_t)dest & ~gPageSizeMask) == dest);
1959 MOZ_ASSERT(n >= VM_COPY_MIN);
1960 MOZ_ASSERT((void*)((uintptr_t)src & ~gPageSizeMask) == src);
1962 kern_return_t r = vm_copy(mach_task_self(), (vm_address_t)src, (vm_size_t)n,
1963 (vm_address_t)dest);
1964 if (r != KERN_SUCCESS) {
1965 MOZ_CRASH("vm_copy() failed");
1969 #endif
1971 template <size_t Bits>
1972 bool AddressRadixTree<Bits>::Init() {
1973 mLock.Init();
1974 mRoot = (void**)base_calloc(1 << kBitsAtLevel1, sizeof(void*));
1975 return mRoot;
1978 template <size_t Bits>
1979 void** AddressRadixTree<Bits>::GetSlot(void* aKey, bool aCreate) {
1980 uintptr_t key = reinterpret_cast<uintptr_t>(aKey);
1981 uintptr_t subkey;
1982 unsigned i, lshift, height, bits;
1983 void** node;
1984 void** child;
1986 for (i = lshift = 0, height = kHeight, node = mRoot; i < height - 1;
1987 i++, lshift += bits, node = child) {
1988 bits = i ? kBitsPerLevel : kBitsAtLevel1;
1989 subkey = (key << lshift) >> ((sizeof(void*) << 3) - bits);
1990 child = (void**)node[subkey];
1991 if (!child && aCreate) {
1992 child = (void**)base_calloc(1 << kBitsPerLevel, sizeof(void*));
1993 if (child) {
1994 node[subkey] = child;
1997 if (!child) {
1998 return nullptr;
2002 // node is a leaf, so it contains values rather than node
2003 // pointers.
2004 bits = i ? kBitsPerLevel : kBitsAtLevel1;
2005 subkey = (key << lshift) >> ((sizeof(void*) << 3) - bits);
2006 return &node[subkey];
2009 template <size_t Bits>
2010 void* AddressRadixTree<Bits>::Get(void* aKey) {
2011 void* ret = nullptr;
2013 void** slot = GetSlot(aKey);
2015 if (slot) {
2016 ret = *slot;
2018 #ifdef MOZ_DEBUG
2019 MutexAutoLock lock(mLock);
2021 // Suppose that it were possible for a jemalloc-allocated chunk to be
2022 // munmap()ped, followed by a different allocator in another thread re-using
2023 // overlapping virtual memory, all without invalidating the cached rtree
2024 // value. The result would be a false positive (the rtree would claim that
2025 // jemalloc owns memory that it had actually discarded). I don't think this
2026 // scenario is possible, but the following assertion is a prudent sanity
2027 // check.
2028 if (!slot) {
2029 // In case a slot has been created in the meantime.
2030 slot = GetSlot(aKey);
2032 if (slot) {
2033 // The MutexAutoLock above should act as a memory barrier, forcing
2034 // the compiler to emit a new read instruction for *slot.
2035 MOZ_ASSERT(ret == *slot);
2036 } else {
2037 MOZ_ASSERT(ret == nullptr);
2039 #endif
2040 return ret;
2043 template <size_t Bits>
2044 bool AddressRadixTree<Bits>::Set(void* aKey, void* aValue) {
2045 MutexAutoLock lock(mLock);
2046 void** slot = GetSlot(aKey, /* aCreate = */ true);
2047 if (slot) {
2048 *slot = aValue;
2050 return slot;
2053 // pages_trim, chunk_alloc_mmap_slow and chunk_alloc_mmap were cherry-picked
2054 // from upstream jemalloc 3.4.1 to fix Mozilla bug 956501.
2056 // Return the offset between a and the nearest aligned address at or below a.
2057 #define ALIGNMENT_ADDR2OFFSET(a, alignment) \
2058 ((size_t)((uintptr_t)(a) & ((alignment)-1)))
2060 // Return the smallest alignment multiple that is >= s.
2061 #define ALIGNMENT_CEILING(s, alignment) \
2062 (((s) + ((alignment)-1)) & (~((alignment)-1)))
2064 static void* pages_trim(void* addr, size_t alloc_size, size_t leadsize,
2065 size_t size) {
2066 void* ret = (void*)((uintptr_t)addr + leadsize);
2068 MOZ_ASSERT(alloc_size >= leadsize + size);
2069 #ifdef XP_WIN
2071 void* new_addr;
2073 pages_unmap(addr, alloc_size);
2074 new_addr = pages_map(ret, size);
2075 if (new_addr == ret) {
2076 return ret;
2078 if (new_addr) {
2079 pages_unmap(new_addr, size);
2081 return nullptr;
2083 #else
2085 size_t trailsize = alloc_size - leadsize - size;
2087 if (leadsize != 0) {
2088 pages_unmap(addr, leadsize);
2090 if (trailsize != 0) {
2091 pages_unmap((void*)((uintptr_t)ret + size), trailsize);
2093 return ret;
2095 #endif
2098 static void* chunk_alloc_mmap_slow(size_t size, size_t alignment) {
2099 void *ret, *pages;
2100 size_t alloc_size, leadsize;
2102 alloc_size = size + alignment - gRealPageSize;
2103 // Beware size_t wrap-around.
2104 if (alloc_size < size) {
2105 return nullptr;
2107 do {
2108 pages = pages_map(nullptr, alloc_size);
2109 if (!pages) {
2110 return nullptr;
2112 leadsize =
2113 ALIGNMENT_CEILING((uintptr_t)pages, alignment) - (uintptr_t)pages;
2114 ret = pages_trim(pages, alloc_size, leadsize, size);
2115 } while (!ret);
2117 MOZ_ASSERT(ret);
2118 return ret;
2121 static void* chunk_alloc_mmap(size_t size, size_t alignment) {
2122 void* ret;
2123 size_t offset;
2125 // Ideally, there would be a way to specify alignment to mmap() (like
2126 // NetBSD has), but in the absence of such a feature, we have to work
2127 // hard to efficiently create aligned mappings. The reliable, but
2128 // slow method is to create a mapping that is over-sized, then trim the
2129 // excess. However, that always results in one or two calls to
2130 // pages_unmap().
2132 // Optimistically try mapping precisely the right amount before falling
2133 // back to the slow method, with the expectation that the optimistic
2134 // approach works most of the time.
2135 ret = pages_map(nullptr, size);
2136 if (!ret) {
2137 return nullptr;
2139 offset = ALIGNMENT_ADDR2OFFSET(ret, alignment);
2140 if (offset != 0) {
2141 pages_unmap(ret, size);
2142 return chunk_alloc_mmap_slow(size, alignment);
2145 MOZ_ASSERT(ret);
2146 return ret;
2149 // Purge and release the pages in the chunk of length `length` at `addr` to
2150 // the OS.
2151 // Returns whether the pages are guaranteed to be full of zeroes when the
2152 // function returns.
2153 // The force_zero argument explicitly requests that the memory is guaranteed
2154 // to be full of zeroes when the function returns.
2155 static bool pages_purge(void* addr, size_t length, bool force_zero) {
2156 pages_decommit(addr, length);
2157 return true;
2160 static void* chunk_recycle(size_t aSize, size_t aAlignment, bool* aZeroed) {
2161 extent_node_t key;
2163 size_t alloc_size = aSize + aAlignment - kChunkSize;
2164 // Beware size_t wrap-around.
2165 if (alloc_size < aSize) {
2166 return nullptr;
2168 key.mAddr = nullptr;
2169 key.mSize = alloc_size;
2170 chunks_mtx.Lock();
2171 extent_node_t* node = gChunksBySize.SearchOrNext(&key);
2172 if (!node) {
2173 chunks_mtx.Unlock();
2174 return nullptr;
2176 size_t leadsize = ALIGNMENT_CEILING((uintptr_t)node->mAddr, aAlignment) -
2177 (uintptr_t)node->mAddr;
2178 MOZ_ASSERT(node->mSize >= leadsize + aSize);
2179 size_t trailsize = node->mSize - leadsize - aSize;
2180 void* ret = (void*)((uintptr_t)node->mAddr + leadsize);
2181 ChunkType chunk_type = node->mChunkType;
2182 if (aZeroed) {
2183 *aZeroed = (chunk_type == ZEROED_CHUNK);
2185 // Remove node from the tree.
2186 gChunksBySize.Remove(node);
2187 gChunksByAddress.Remove(node);
2188 if (leadsize != 0) {
2189 // Insert the leading space as a smaller chunk.
2190 node->mSize = leadsize;
2191 gChunksBySize.Insert(node);
2192 gChunksByAddress.Insert(node);
2193 node = nullptr;
2195 if (trailsize != 0) {
2196 // Insert the trailing space as a smaller chunk.
2197 if (!node) {
2198 // An additional node is required, but
2199 // TypedBaseAlloc::alloc() can cause a new base chunk to be
2200 // allocated. Drop chunks_mtx in order to avoid
2201 // deadlock, and if node allocation fails, deallocate
2202 // the result before returning an error.
2203 chunks_mtx.Unlock();
2204 node = ExtentAlloc::alloc();
2205 if (!node) {
2206 chunk_dealloc(ret, aSize, chunk_type);
2207 return nullptr;
2209 chunks_mtx.Lock();
2211 node->mAddr = (void*)((uintptr_t)(ret) + aSize);
2212 node->mSize = trailsize;
2213 node->mChunkType = chunk_type;
2214 gChunksBySize.Insert(node);
2215 gChunksByAddress.Insert(node);
2216 node = nullptr;
2219 gRecycledSize -= aSize;
2221 chunks_mtx.Unlock();
2223 if (node) {
2224 ExtentAlloc::dealloc(node);
2226 if (!pages_commit(ret, aSize)) {
2227 return nullptr;
2229 // pages_commit is guaranteed to zero the chunk.
2230 if (aZeroed) {
2231 *aZeroed = true;
2234 return ret;
2237 #ifdef XP_WIN
2238 // On Windows, calls to VirtualAlloc and VirtualFree must be matched, making it
2239 // awkward to recycle allocations of varying sizes. Therefore we only allow
2240 // recycling when the size equals the chunksize, unless deallocation is entirely
2241 // disabled.
2242 # define CAN_RECYCLE(size) ((size) == kChunkSize)
2243 #else
2244 # define CAN_RECYCLE(size) true
2245 #endif
2247 // Allocates `size` bytes of system memory aligned for `alignment`.
2248 // `base` indicates whether the memory will be used for the base allocator
2249 // (e.g. base_alloc).
2250 // `zeroed` is an outvalue that returns whether the allocated memory is
2251 // guaranteed to be full of zeroes. It can be omitted when the caller doesn't
2252 // care about the result.
2253 static void* chunk_alloc(size_t aSize, size_t aAlignment, bool aBase,
2254 bool* aZeroed) {
2255 void* ret = nullptr;
2257 MOZ_ASSERT(aSize != 0);
2258 MOZ_ASSERT((aSize & kChunkSizeMask) == 0);
2259 MOZ_ASSERT(aAlignment != 0);
2260 MOZ_ASSERT((aAlignment & kChunkSizeMask) == 0);
2262 // Base allocations can't be fulfilled by recycling because of
2263 // possible deadlock or infinite recursion.
2264 if (CAN_RECYCLE(aSize) && !aBase) {
2265 ret = chunk_recycle(aSize, aAlignment, aZeroed);
2267 if (!ret) {
2268 ret = chunk_alloc_mmap(aSize, aAlignment);
2269 if (aZeroed) {
2270 *aZeroed = true;
2273 if (ret && !aBase) {
2274 if (!gChunkRTree.Set(ret, ret)) {
2275 chunk_dealloc(ret, aSize, UNKNOWN_CHUNK);
2276 return nullptr;
2280 MOZ_ASSERT(GetChunkOffsetForPtr(ret) == 0);
2281 return ret;
2284 static void chunk_ensure_zero(void* aPtr, size_t aSize, bool aZeroed) {
2285 if (aZeroed == false) {
2286 memset(aPtr, 0, aSize);
2288 #ifdef MOZ_DEBUG
2289 else {
2290 size_t i;
2291 size_t* p = (size_t*)(uintptr_t)aPtr;
2293 for (i = 0; i < aSize / sizeof(size_t); i++) {
2294 MOZ_ASSERT(p[i] == 0);
2297 #endif
2300 static void chunk_record(void* aChunk, size_t aSize, ChunkType aType) {
2301 extent_node_t key;
2303 if (aType != ZEROED_CHUNK) {
2304 if (pages_purge(aChunk, aSize, aType == HUGE_CHUNK)) {
2305 aType = ZEROED_CHUNK;
2309 // Allocate a node before acquiring chunks_mtx even though it might not
2310 // be needed, because TypedBaseAlloc::alloc() may cause a new base chunk to
2311 // be allocated, which could cause deadlock if chunks_mtx were already
2312 // held.
2313 UniqueBaseNode xnode(ExtentAlloc::alloc());
2314 // Use xprev to implement conditional deferred deallocation of prev.
2315 UniqueBaseNode xprev;
2317 // RAII deallocates xnode and xprev defined above after unlocking
2318 // in order to avoid potential dead-locks
2319 MutexAutoLock lock(chunks_mtx);
2320 key.mAddr = (void*)((uintptr_t)aChunk + aSize);
2321 extent_node_t* node = gChunksByAddress.SearchOrNext(&key);
2322 // Try to coalesce forward.
2323 if (node && node->mAddr == key.mAddr) {
2324 // Coalesce chunk with the following address range. This does
2325 // not change the position within gChunksByAddress, so only
2326 // remove/insert from/into gChunksBySize.
2327 gChunksBySize.Remove(node);
2328 node->mAddr = aChunk;
2329 node->mSize += aSize;
2330 if (node->mChunkType != aType) {
2331 node->mChunkType = RECYCLED_CHUNK;
2333 gChunksBySize.Insert(node);
2334 } else {
2335 // Coalescing forward failed, so insert a new node.
2336 if (!xnode) {
2337 // TypedBaseAlloc::alloc() failed, which is an exceedingly
2338 // unlikely failure. Leak chunk; its pages have
2339 // already been purged, so this is only a virtual
2340 // memory leak.
2341 return;
2343 node = xnode.release();
2344 node->mAddr = aChunk;
2345 node->mSize = aSize;
2346 node->mChunkType = aType;
2347 gChunksByAddress.Insert(node);
2348 gChunksBySize.Insert(node);
2351 // Try to coalesce backward.
2352 extent_node_t* prev = gChunksByAddress.Prev(node);
2353 if (prev && (void*)((uintptr_t)prev->mAddr + prev->mSize) == aChunk) {
2354 // Coalesce chunk with the previous address range. This does
2355 // not change the position within gChunksByAddress, so only
2356 // remove/insert node from/into gChunksBySize.
2357 gChunksBySize.Remove(prev);
2358 gChunksByAddress.Remove(prev);
2360 gChunksBySize.Remove(node);
2361 node->mAddr = prev->mAddr;
2362 node->mSize += prev->mSize;
2363 if (node->mChunkType != prev->mChunkType) {
2364 node->mChunkType = RECYCLED_CHUNK;
2366 gChunksBySize.Insert(node);
2368 xprev.reset(prev);
2371 gRecycledSize += aSize;
2374 static void chunk_dealloc(void* aChunk, size_t aSize, ChunkType aType) {
2375 MOZ_ASSERT(aChunk);
2376 MOZ_ASSERT(GetChunkOffsetForPtr(aChunk) == 0);
2377 MOZ_ASSERT(aSize != 0);
2378 MOZ_ASSERT((aSize & kChunkSizeMask) == 0);
2380 gChunkRTree.Unset(aChunk);
2382 if (CAN_RECYCLE(aSize)) {
2383 size_t recycled_so_far = gRecycledSize;
2384 // In case some race condition put us above the limit.
2385 if (recycled_so_far < gRecycleLimit) {
2386 size_t recycle_remaining = gRecycleLimit - recycled_so_far;
2387 size_t to_recycle;
2388 if (aSize > recycle_remaining) {
2389 to_recycle = recycle_remaining;
2390 // Drop pages that would overflow the recycle limit
2391 pages_trim(aChunk, aSize, 0, to_recycle);
2392 } else {
2393 to_recycle = aSize;
2395 chunk_record(aChunk, to_recycle, aType);
2396 return;
2400 pages_unmap(aChunk, aSize);
2403 #undef CAN_RECYCLE
2405 // End chunk management functions.
2406 // ***************************************************************************
2407 // Begin arena.
2409 static inline arena_t* thread_local_arena(bool enabled) {
2410 arena_t* arena;
2412 if (enabled) {
2413 // The arena will essentially be leaked if this function is
2414 // called with `false`, but it doesn't matter at the moment.
2415 // because in practice nothing actually calls this function
2416 // with `false`, except maybe at shutdown.
2417 arena =
2418 gArenas.CreateArena(/* aIsPrivate = */ false, /* aParams = */ nullptr);
2419 } else {
2420 arena = gArenas.GetDefault();
2422 thread_arena.set(arena);
2423 return arena;
2426 template <>
2427 inline void MozJemalloc::jemalloc_thread_local_arena(bool aEnabled) {
2428 if (malloc_init()) {
2429 thread_local_arena(aEnabled);
2433 // Choose an arena based on a per-thread value.
2434 static inline arena_t* choose_arena(size_t size) {
2435 arena_t* ret = nullptr;
2437 // We can only use TLS if this is a PIC library, since for the static
2438 // library version, libc's malloc is used by TLS allocation, which
2439 // introduces a bootstrapping issue.
2441 if (size > kMaxQuantumClass) {
2442 // Force the default arena for larger allocations.
2443 ret = gArenas.GetDefault();
2444 } else {
2445 // Check TLS to see if our thread has requested a pinned arena.
2446 ret = thread_arena.get();
2447 if (!ret) {
2448 // Nothing in TLS. Pin this thread to the default arena.
2449 ret = thread_local_arena(false);
2453 MOZ_DIAGNOSTIC_ASSERT(ret);
2454 return ret;
2457 inline uint8_t arena_t::FindFreeBitInMask(uint32_t aMask, uint32_t& aRng) {
2458 if (mPRNG != nullptr) {
2459 if (aRng == UINT_MAX) {
2460 aRng = mPRNG->next() % 32;
2462 uint8_t bitIndex;
2463 // RotateRight asserts when provided bad input.
2464 aMask = aRng ? RotateRight(aMask, aRng)
2465 : aMask; // Rotate the mask a random number of slots
2466 bitIndex = CountTrailingZeroes32(aMask);
2467 return (bitIndex + aRng) % 32;
2469 return CountTrailingZeroes32(aMask);
2472 inline void* arena_t::ArenaRunRegAlloc(arena_run_t* aRun, arena_bin_t* aBin) {
2473 void* ret;
2474 unsigned i, mask, bit, regind;
2475 uint32_t rndPos = UINT_MAX;
2477 MOZ_DIAGNOSTIC_ASSERT(aRun->mMagic == ARENA_RUN_MAGIC);
2478 MOZ_ASSERT(aRun->mRegionsMinElement < aBin->mRunNumRegionsMask);
2480 // Move the first check outside the loop, so that aRun->mRegionsMinElement can
2481 // be updated unconditionally, without the possibility of updating it
2482 // multiple times.
2483 i = aRun->mRegionsMinElement;
2484 mask = aRun->mRegionsMask[i];
2485 if (mask != 0) {
2486 bit = FindFreeBitInMask(mask, rndPos);
2488 regind = ((i << (LOG2(sizeof(int)) + 3)) + bit);
2489 MOZ_ASSERT(regind < aBin->mRunNumRegions);
2490 ret = (void*)(((uintptr_t)aRun) + aBin->mRunFirstRegionOffset +
2491 (aBin->mSizeClass * regind));
2493 // Clear bit.
2494 mask ^= (1U << bit);
2495 aRun->mRegionsMask[i] = mask;
2497 return ret;
2500 for (i++; i < aBin->mRunNumRegionsMask; i++) {
2501 mask = aRun->mRegionsMask[i];
2502 if (mask != 0) {
2503 bit = FindFreeBitInMask(mask, rndPos);
2505 regind = ((i << (LOG2(sizeof(int)) + 3)) + bit);
2506 MOZ_ASSERT(regind < aBin->mRunNumRegions);
2507 ret = (void*)(((uintptr_t)aRun) + aBin->mRunFirstRegionOffset +
2508 (aBin->mSizeClass * regind));
2510 // Clear bit.
2511 mask ^= (1U << bit);
2512 aRun->mRegionsMask[i] = mask;
2514 // Make a note that nothing before this element
2515 // contains a free region.
2516 aRun->mRegionsMinElement = i; // Low payoff: + (mask == 0);
2518 return ret;
2521 // Not reached.
2522 MOZ_DIAGNOSTIC_ASSERT(0);
2523 return nullptr;
2526 static inline void arena_run_reg_dalloc(arena_run_t* run, arena_bin_t* bin,
2527 void* ptr, size_t size) {
2528 uint32_t diff, regind;
2529 unsigned elm, bit;
2531 MOZ_DIAGNOSTIC_ASSERT(run->mMagic == ARENA_RUN_MAGIC);
2533 // Avoid doing division with a variable divisor if possible. Using
2534 // actual division here can reduce allocator throughput by over 20%!
2535 diff =
2536 (uint32_t)((uintptr_t)ptr - (uintptr_t)run - bin->mRunFirstRegionOffset);
2538 MOZ_ASSERT(diff <=
2539 (static_cast<unsigned>(bin->mRunSizePages) << gPageSize2Pow));
2540 regind = diff / bin->mSizeDivisor;
2542 MOZ_DIAGNOSTIC_ASSERT(diff == regind * size);
2543 MOZ_DIAGNOSTIC_ASSERT(regind < bin->mRunNumRegions);
2545 elm = regind >> (LOG2(sizeof(int)) + 3);
2546 if (elm < run->mRegionsMinElement) {
2547 run->mRegionsMinElement = elm;
2549 bit = regind - (elm << (LOG2(sizeof(int)) + 3));
2550 MOZ_RELEASE_ASSERT((run->mRegionsMask[elm] & (1U << bit)) == 0,
2551 "Double-free?");
2552 run->mRegionsMask[elm] |= (1U << bit);
2555 bool arena_t::SplitRun(arena_run_t* aRun, size_t aSize, bool aLarge,
2556 bool aZero) {
2557 arena_chunk_t* chunk;
2558 size_t old_ndirty, run_ind, total_pages, need_pages, rem_pages, i;
2560 chunk = GetChunkForPtr(aRun);
2561 old_ndirty = chunk->ndirty;
2562 run_ind = (unsigned)((uintptr_t(aRun) - uintptr_t(chunk)) >> gPageSize2Pow);
2563 total_pages = (chunk->map[run_ind].bits & ~gPageSizeMask) >> gPageSize2Pow;
2564 need_pages = (aSize >> gPageSize2Pow);
2565 MOZ_ASSERT(need_pages > 0);
2566 MOZ_ASSERT(need_pages <= total_pages);
2567 rem_pages = total_pages - need_pages;
2569 for (i = 0; i < need_pages; i++) {
2570 // Commit decommitted pages if necessary. If a decommitted
2571 // page is encountered, commit all needed adjacent decommitted
2572 // pages in one operation, in order to reduce system call
2573 // overhead.
2574 if (chunk->map[run_ind + i].bits & CHUNK_MAP_MADVISED_OR_DECOMMITTED) {
2575 size_t j;
2577 // Advance i+j to just past the index of the last page
2578 // to commit. Clear CHUNK_MAP_DECOMMITTED and
2579 // CHUNK_MAP_MADVISED along the way.
2580 for (j = 0; i + j < need_pages && (chunk->map[run_ind + i + j].bits &
2581 CHUNK_MAP_MADVISED_OR_DECOMMITTED);
2582 j++) {
2583 // DECOMMITTED and MADVISED are mutually exclusive.
2584 MOZ_ASSERT(!(chunk->map[run_ind + i + j].bits & CHUNK_MAP_DECOMMITTED &&
2585 chunk->map[run_ind + i + j].bits & CHUNK_MAP_MADVISED));
2587 chunk->map[run_ind + i + j].bits &= ~CHUNK_MAP_MADVISED_OR_DECOMMITTED;
2590 #ifdef MALLOC_DECOMMIT
2591 bool committed = pages_commit(
2592 (void*)(uintptr_t(chunk) + ((run_ind + i) << gPageSize2Pow)),
2593 j << gPageSize2Pow);
2594 // pages_commit zeroes pages, so mark them as such if it succeeded.
2595 // That's checked further below to avoid manually zeroing the pages.
2596 for (size_t k = 0; k < j; k++) {
2597 chunk->map[run_ind + i + k].bits |=
2598 committed ? CHUNK_MAP_ZEROED : CHUNK_MAP_DECOMMITTED;
2600 if (!committed) {
2601 return false;
2603 #endif
2605 mStats.committed += j;
2609 mRunsAvail.Remove(&chunk->map[run_ind]);
2611 // Keep track of trailing unused pages for later use.
2612 if (rem_pages > 0) {
2613 chunk->map[run_ind + need_pages].bits =
2614 (rem_pages << gPageSize2Pow) |
2615 (chunk->map[run_ind + need_pages].bits & gPageSizeMask);
2616 chunk->map[run_ind + total_pages - 1].bits =
2617 (rem_pages << gPageSize2Pow) |
2618 (chunk->map[run_ind + total_pages - 1].bits & gPageSizeMask);
2619 mRunsAvail.Insert(&chunk->map[run_ind + need_pages]);
2622 for (i = 0; i < need_pages; i++) {
2623 // Zero if necessary.
2624 if (aZero) {
2625 if ((chunk->map[run_ind + i].bits & CHUNK_MAP_ZEROED) == 0) {
2626 memset((void*)(uintptr_t(chunk) + ((run_ind + i) << gPageSize2Pow)), 0,
2627 gPageSize);
2628 // CHUNK_MAP_ZEROED is cleared below.
2632 // Update dirty page accounting.
2633 if (chunk->map[run_ind + i].bits & CHUNK_MAP_DIRTY) {
2634 chunk->ndirty--;
2635 mNumDirty--;
2636 // CHUNK_MAP_DIRTY is cleared below.
2639 // Initialize the chunk map.
2640 if (aLarge) {
2641 chunk->map[run_ind + i].bits = CHUNK_MAP_LARGE | CHUNK_MAP_ALLOCATED;
2642 } else {
2643 chunk->map[run_ind + i].bits = size_t(aRun) | CHUNK_MAP_ALLOCATED;
2647 // Set the run size only in the first element for large runs. This is
2648 // primarily a debugging aid, since the lack of size info for trailing
2649 // pages only matters if the application tries to operate on an
2650 // interior pointer.
2651 if (aLarge) {
2652 chunk->map[run_ind].bits |= aSize;
2655 if (chunk->ndirty == 0 && old_ndirty > 0) {
2656 mChunksDirty.Remove(chunk);
2658 return true;
2661 void arena_t::InitChunk(arena_chunk_t* aChunk, bool aZeroed) {
2662 size_t i;
2663 // WARNING: The following relies on !aZeroed meaning "used to be an arena
2664 // chunk".
2665 // When the chunk we're initializating as an arena chunk is zeroed, we
2666 // mark all runs are decommitted and zeroed.
2667 // When it is not, which we can assume means it's a recycled arena chunk,
2668 // all it can contain is an arena chunk header (which we're overwriting),
2669 // and zeroed or poisoned memory (because a recycled arena chunk will
2670 // have been emptied before being recycled). In that case, we can get
2671 // away with reusing the chunk as-is, marking all runs as madvised.
2673 size_t flags =
2674 aZeroed ? CHUNK_MAP_DECOMMITTED | CHUNK_MAP_ZEROED : CHUNK_MAP_MADVISED;
2676 mStats.mapped += kChunkSize;
2678 aChunk->arena = this;
2680 // Claim that no pages are in use, since the header is merely overhead.
2681 aChunk->ndirty = 0;
2683 // Initialize the map to contain one maximal free untouched run.
2684 arena_run_t* run = (arena_run_t*)(uintptr_t(aChunk) +
2685 (gChunkHeaderNumPages << gPageSize2Pow));
2687 // Clear the bits for the real header pages.
2688 for (i = 0; i < gChunkHeaderNumPages - 1; i++) {
2689 aChunk->map[i].bits = 0;
2691 // Mark the leading guard page (last header page) as decommitted.
2692 aChunk->map[i++].bits = CHUNK_MAP_DECOMMITTED;
2694 // Mark the area usable for runs as available, note size at start and end
2695 aChunk->map[i++].bits = gMaxLargeClass | flags;
2696 for (; i < gChunkNumPages - 2; i++) {
2697 aChunk->map[i].bits = flags;
2699 aChunk->map[gChunkNumPages - 2].bits = gMaxLargeClass | flags;
2701 // Mark the trailing guard page as decommitted.
2702 aChunk->map[gChunkNumPages - 1].bits = CHUNK_MAP_DECOMMITTED;
2704 #ifdef MALLOC_DECOMMIT
2705 // Start out decommitted, in order to force a closer correspondence
2706 // between dirty pages and committed untouched pages. This includes
2707 // leading and trailing guard pages.
2708 pages_decommit((void*)(uintptr_t(run) - gPageSize),
2709 gMaxLargeClass + 2 * gPageSize);
2710 #else
2711 // Decommit the last header page (=leading page) as a guard.
2712 pages_decommit((void*)(uintptr_t(run) - gPageSize), gPageSize);
2713 // Decommit the last page as a guard.
2714 pages_decommit((void*)(uintptr_t(aChunk) + kChunkSize - gPageSize),
2715 gPageSize);
2716 #endif
2718 mStats.committed += gChunkHeaderNumPages;
2720 // Insert the run into the tree of available runs.
2721 mRunsAvail.Insert(&aChunk->map[gChunkHeaderNumPages]);
2723 #ifdef MALLOC_DOUBLE_PURGE
2724 new (&aChunk->chunks_madvised_elem) DoublyLinkedListElement<arena_chunk_t>();
2725 #endif
2728 arena_chunk_t* arena_t::DeallocChunk(arena_chunk_t* aChunk) {
2729 if (mSpare) {
2730 if (mSpare->ndirty > 0) {
2731 aChunk->arena->mChunksDirty.Remove(mSpare);
2732 mNumDirty -= mSpare->ndirty;
2733 mStats.committed -= mSpare->ndirty;
2736 #ifdef MALLOC_DOUBLE_PURGE
2737 if (mChunksMAdvised.ElementProbablyInList(mSpare)) {
2738 mChunksMAdvised.remove(mSpare);
2740 #endif
2742 mStats.mapped -= kChunkSize;
2743 mStats.committed -= gChunkHeaderNumPages;
2746 // Remove run from the tree of available runs, so that the arena does not use
2747 // it. Dirty page flushing only uses the tree of dirty chunks, so leaving this
2748 // chunk in the chunks_* trees is sufficient for that purpose.
2749 mRunsAvail.Remove(&aChunk->map[gChunkHeaderNumPages]);
2751 arena_chunk_t* chunk_dealloc = mSpare;
2752 mSpare = aChunk;
2753 return chunk_dealloc;
2756 arena_run_t* arena_t::AllocRun(size_t aSize, bool aLarge, bool aZero) {
2757 arena_run_t* run;
2758 arena_chunk_map_t* mapelm;
2759 arena_chunk_map_t key;
2761 MOZ_ASSERT(aSize <= gMaxLargeClass);
2762 MOZ_ASSERT((aSize & gPageSizeMask) == 0);
2764 // Search the arena's chunks for the lowest best fit.
2765 key.bits = aSize | CHUNK_MAP_KEY;
2766 mapelm = mRunsAvail.SearchOrNext(&key);
2767 if (mapelm) {
2768 arena_chunk_t* chunk = GetChunkForPtr(mapelm);
2769 size_t pageind =
2770 (uintptr_t(mapelm) - uintptr_t(chunk->map)) / sizeof(arena_chunk_map_t);
2772 run = (arena_run_t*)(uintptr_t(chunk) + (pageind << gPageSize2Pow));
2773 } else if (mSpare) {
2774 // Use the spare.
2775 arena_chunk_t* chunk = mSpare;
2776 mSpare = nullptr;
2777 run = (arena_run_t*)(uintptr_t(chunk) +
2778 (gChunkHeaderNumPages << gPageSize2Pow));
2779 // Insert the run into the tree of available runs.
2780 mRunsAvail.Insert(&chunk->map[gChunkHeaderNumPages]);
2781 } else {
2782 // No usable runs. Create a new chunk from which to allocate
2783 // the run.
2784 bool zeroed;
2785 arena_chunk_t* chunk =
2786 (arena_chunk_t*)chunk_alloc(kChunkSize, kChunkSize, false, &zeroed);
2787 if (!chunk) {
2788 return nullptr;
2791 InitChunk(chunk, zeroed);
2792 run = (arena_run_t*)(uintptr_t(chunk) +
2793 (gChunkHeaderNumPages << gPageSize2Pow));
2795 // Update page map.
2796 return SplitRun(run, aSize, aLarge, aZero) ? run : nullptr;
2799 size_t arena_t::EffectiveMaxDirty() {
2800 int32_t modifier = gArenas.DefaultMaxDirtyPageModifier();
2801 if (modifier) {
2802 int32_t arenaOverride =
2803 modifier > 0 ? mMaxDirtyIncreaseOverride : mMaxDirtyDecreaseOverride;
2804 if (arenaOverride) {
2805 modifier = arenaOverride;
2809 return modifier >= 0 ? mMaxDirty << modifier : mMaxDirty >> -modifier;
2812 void arena_t::Purge(size_t aMaxDirty) {
2813 arena_chunk_t* chunk;
2814 size_t i, npages;
2816 #ifdef MOZ_DEBUG
2817 size_t ndirty = 0;
2818 for (auto chunk : mChunksDirty.iter()) {
2819 ndirty += chunk->ndirty;
2821 MOZ_ASSERT(ndirty == mNumDirty);
2822 #endif
2823 MOZ_DIAGNOSTIC_ASSERT(aMaxDirty == 1 || (mNumDirty > aMaxDirty));
2825 // Iterate downward through chunks until enough dirty memory has been
2826 // purged. Terminate as soon as possible in order to minimize the
2827 // number of system calls, even if a chunk has only been partially
2828 // purged.
2829 while (mNumDirty > (aMaxDirty >> 1)) {
2830 #ifdef MALLOC_DOUBLE_PURGE
2831 bool madvised = false;
2832 #endif
2833 chunk = mChunksDirty.Last();
2834 MOZ_DIAGNOSTIC_ASSERT(chunk);
2835 // Last page is DECOMMITTED as a guard page.
2836 MOZ_ASSERT((chunk->map[gChunkNumPages - 1].bits & CHUNK_MAP_DECOMMITTED) !=
2838 for (i = gChunkNumPages - 2; chunk->ndirty > 0; i--) {
2839 MOZ_DIAGNOSTIC_ASSERT(i >= gChunkHeaderNumPages);
2841 if (chunk->map[i].bits & CHUNK_MAP_DIRTY) {
2842 #ifdef MALLOC_DECOMMIT
2843 const size_t free_operation = CHUNK_MAP_DECOMMITTED;
2844 #else
2845 const size_t free_operation = CHUNK_MAP_MADVISED;
2846 #endif
2847 MOZ_ASSERT((chunk->map[i].bits & CHUNK_MAP_MADVISED_OR_DECOMMITTED) ==
2849 chunk->map[i].bits ^= free_operation | CHUNK_MAP_DIRTY;
2850 // Find adjacent dirty run(s).
2851 for (npages = 1; i > gChunkHeaderNumPages &&
2852 (chunk->map[i - 1].bits & CHUNK_MAP_DIRTY);
2853 npages++) {
2854 i--;
2855 MOZ_ASSERT((chunk->map[i].bits & CHUNK_MAP_MADVISED_OR_DECOMMITTED) ==
2857 chunk->map[i].bits ^= free_operation | CHUNK_MAP_DIRTY;
2859 chunk->ndirty -= npages;
2860 mNumDirty -= npages;
2862 #ifdef MALLOC_DECOMMIT
2863 pages_decommit((void*)(uintptr_t(chunk) + (i << gPageSize2Pow)),
2864 (npages << gPageSize2Pow));
2865 #endif
2866 mStats.committed -= npages;
2868 #ifndef MALLOC_DECOMMIT
2869 # ifdef XP_SOLARIS
2870 posix_madvise((void*)(uintptr_t(chunk) + (i << gPageSize2Pow)),
2871 (npages << gPageSize2Pow), MADV_FREE);
2872 # else
2873 madvise((void*)(uintptr_t(chunk) + (i << gPageSize2Pow)),
2874 (npages << gPageSize2Pow), MADV_FREE);
2875 # endif
2876 # ifdef MALLOC_DOUBLE_PURGE
2877 madvised = true;
2878 # endif
2879 #endif
2880 if (mNumDirty <= (aMaxDirty >> 1)) {
2881 break;
2886 if (chunk->ndirty == 0) {
2887 mChunksDirty.Remove(chunk);
2889 #ifdef MALLOC_DOUBLE_PURGE
2890 if (madvised) {
2891 // The chunk might already be in the list, but this
2892 // makes sure it's at the front.
2893 if (mChunksMAdvised.ElementProbablyInList(chunk)) {
2894 mChunksMAdvised.remove(chunk);
2896 mChunksMAdvised.pushFront(chunk);
2898 #endif
2902 arena_chunk_t* arena_t::DallocRun(arena_run_t* aRun, bool aDirty) {
2903 arena_chunk_t* chunk;
2904 size_t size, run_ind, run_pages;
2906 chunk = GetChunkForPtr(aRun);
2907 run_ind = (size_t)((uintptr_t(aRun) - uintptr_t(chunk)) >> gPageSize2Pow);
2908 MOZ_DIAGNOSTIC_ASSERT(run_ind >= gChunkHeaderNumPages);
2909 MOZ_RELEASE_ASSERT(run_ind < gChunkNumPages - 1);
2910 if ((chunk->map[run_ind].bits & CHUNK_MAP_LARGE) != 0) {
2911 size = chunk->map[run_ind].bits & ~gPageSizeMask;
2912 run_pages = (size >> gPageSize2Pow);
2913 } else {
2914 run_pages = aRun->mBin->mRunSizePages;
2915 size = run_pages << gPageSize2Pow;
2918 // Mark pages as unallocated in the chunk map.
2919 if (aDirty) {
2920 size_t i;
2922 for (i = 0; i < run_pages; i++) {
2923 MOZ_DIAGNOSTIC_ASSERT((chunk->map[run_ind + i].bits & CHUNK_MAP_DIRTY) ==
2925 chunk->map[run_ind + i].bits = CHUNK_MAP_DIRTY;
2928 if (chunk->ndirty == 0) {
2929 mChunksDirty.Insert(chunk);
2931 chunk->ndirty += run_pages;
2932 mNumDirty += run_pages;
2933 } else {
2934 size_t i;
2936 for (i = 0; i < run_pages; i++) {
2937 chunk->map[run_ind + i].bits &= ~(CHUNK_MAP_LARGE | CHUNK_MAP_ALLOCATED);
2940 chunk->map[run_ind].bits = size | (chunk->map[run_ind].bits & gPageSizeMask);
2941 chunk->map[run_ind + run_pages - 1].bits =
2942 size | (chunk->map[run_ind + run_pages - 1].bits & gPageSizeMask);
2944 // Try to coalesce forward.
2945 if (run_ind + run_pages < gChunkNumPages - 1 &&
2946 (chunk->map[run_ind + run_pages].bits & CHUNK_MAP_ALLOCATED) == 0) {
2947 size_t nrun_size = chunk->map[run_ind + run_pages].bits & ~gPageSizeMask;
2949 // Remove successor from tree of available runs; the coalesced run is
2950 // inserted later.
2951 mRunsAvail.Remove(&chunk->map[run_ind + run_pages]);
2953 size += nrun_size;
2954 run_pages = size >> gPageSize2Pow;
2956 MOZ_DIAGNOSTIC_ASSERT((chunk->map[run_ind + run_pages - 1].bits &
2957 ~gPageSizeMask) == nrun_size);
2958 chunk->map[run_ind].bits =
2959 size | (chunk->map[run_ind].bits & gPageSizeMask);
2960 chunk->map[run_ind + run_pages - 1].bits =
2961 size | (chunk->map[run_ind + run_pages - 1].bits & gPageSizeMask);
2964 // Try to coalesce backward.
2965 if (run_ind > gChunkHeaderNumPages &&
2966 (chunk->map[run_ind - 1].bits & CHUNK_MAP_ALLOCATED) == 0) {
2967 size_t prun_size = chunk->map[run_ind - 1].bits & ~gPageSizeMask;
2969 run_ind -= prun_size >> gPageSize2Pow;
2971 // Remove predecessor from tree of available runs; the coalesced run is
2972 // inserted later.
2973 mRunsAvail.Remove(&chunk->map[run_ind]);
2975 size += prun_size;
2976 run_pages = size >> gPageSize2Pow;
2978 MOZ_DIAGNOSTIC_ASSERT((chunk->map[run_ind].bits & ~gPageSizeMask) ==
2979 prun_size);
2980 chunk->map[run_ind].bits =
2981 size | (chunk->map[run_ind].bits & gPageSizeMask);
2982 chunk->map[run_ind + run_pages - 1].bits =
2983 size | (chunk->map[run_ind + run_pages - 1].bits & gPageSizeMask);
2986 // Insert into tree of available runs, now that coalescing is complete.
2987 mRunsAvail.Insert(&chunk->map[run_ind]);
2989 // Deallocate chunk if it is now completely unused.
2990 arena_chunk_t* chunk_dealloc = nullptr;
2991 if ((chunk->map[gChunkHeaderNumPages].bits &
2992 (~gPageSizeMask | CHUNK_MAP_ALLOCATED)) == gMaxLargeClass) {
2993 chunk_dealloc = DeallocChunk(chunk);
2996 size_t maxDirty = EffectiveMaxDirty();
2997 if (mNumDirty > maxDirty) {
2998 Purge(maxDirty);
3001 return chunk_dealloc;
3004 void arena_t::TrimRunHead(arena_chunk_t* aChunk, arena_run_t* aRun,
3005 size_t aOldSize, size_t aNewSize) {
3006 size_t pageind = (uintptr_t(aRun) - uintptr_t(aChunk)) >> gPageSize2Pow;
3007 size_t head_npages = (aOldSize - aNewSize) >> gPageSize2Pow;
3009 MOZ_ASSERT(aOldSize > aNewSize);
3011 // Update the chunk map so that arena_t::RunDalloc() can treat the
3012 // leading run as separately allocated.
3013 aChunk->map[pageind].bits =
3014 (aOldSize - aNewSize) | CHUNK_MAP_LARGE | CHUNK_MAP_ALLOCATED;
3015 aChunk->map[pageind + head_npages].bits =
3016 aNewSize | CHUNK_MAP_LARGE | CHUNK_MAP_ALLOCATED;
3018 #ifdef MOZ_DEBUG
3019 arena_chunk_t* no_chunk =
3020 #endif
3021 DallocRun(aRun, false);
3022 // This will never release a chunk as there's still at least one allocated
3023 // run.
3024 MOZ_ASSERT(!no_chunk);
3027 void arena_t::TrimRunTail(arena_chunk_t* aChunk, arena_run_t* aRun,
3028 size_t aOldSize, size_t aNewSize, bool aDirty) {
3029 size_t pageind = (uintptr_t(aRun) - uintptr_t(aChunk)) >> gPageSize2Pow;
3030 size_t npages = aNewSize >> gPageSize2Pow;
3032 MOZ_ASSERT(aOldSize > aNewSize);
3034 // Update the chunk map so that arena_t::RunDalloc() can treat the
3035 // trailing run as separately allocated.
3036 aChunk->map[pageind].bits = aNewSize | CHUNK_MAP_LARGE | CHUNK_MAP_ALLOCATED;
3037 aChunk->map[pageind + npages].bits =
3038 (aOldSize - aNewSize) | CHUNK_MAP_LARGE | CHUNK_MAP_ALLOCATED;
3040 #ifdef MOZ_DEBUG
3041 arena_chunk_t* no_chunk =
3042 #endif
3043 DallocRun((arena_run_t*)(uintptr_t(aRun) + aNewSize), aDirty);
3045 // This will never release a chunk as there's still at least one allocated
3046 // run.
3047 MOZ_ASSERT(!no_chunk);
3050 arena_run_t* arena_t::GetNonFullBinRun(arena_bin_t* aBin) {
3051 arena_chunk_map_t* mapelm;
3052 arena_run_t* run;
3053 unsigned i, remainder;
3055 // Look for a usable run.
3056 mapelm = aBin->mNonFullRuns.First();
3057 if (mapelm) {
3058 // run is guaranteed to have available space.
3059 aBin->mNonFullRuns.Remove(mapelm);
3060 run = (arena_run_t*)(mapelm->bits & ~gPageSizeMask);
3061 return run;
3063 // No existing runs have any space available.
3065 // Allocate a new run.
3066 run = AllocRun(static_cast<size_t>(aBin->mRunSizePages) << gPageSize2Pow,
3067 false, false);
3068 if (!run) {
3069 return nullptr;
3071 // Don't initialize if a race in arena_t::RunAlloc() allowed an existing
3072 // run to become usable.
3073 if (run == aBin->mCurrentRun) {
3074 return run;
3077 // Initialize run internals.
3078 run->mBin = aBin;
3080 for (i = 0; i < aBin->mRunNumRegionsMask - 1; i++) {
3081 run->mRegionsMask[i] = UINT_MAX;
3083 remainder = aBin->mRunNumRegions & ((1U << (LOG2(sizeof(int)) + 3)) - 1);
3084 if (remainder == 0) {
3085 run->mRegionsMask[i] = UINT_MAX;
3086 } else {
3087 // The last element has spare bits that need to be unset.
3088 run->mRegionsMask[i] =
3089 (UINT_MAX >> ((1U << (LOG2(sizeof(int)) + 3)) - remainder));
3092 run->mRegionsMinElement = 0;
3094 run->mNumFree = aBin->mRunNumRegions;
3095 #if defined(MOZ_DIAGNOSTIC_ASSERT_ENABLED)
3096 run->mMagic = ARENA_RUN_MAGIC;
3097 #endif
3099 aBin->mNumRuns++;
3100 return run;
3103 void arena_bin_t::Init(SizeClass aSizeClass) {
3104 size_t try_run_size;
3105 unsigned try_nregs, try_mask_nelms, try_reg0_offset;
3106 // Size of the run header, excluding mRegionsMask.
3107 static const size_t kFixedHeaderSize = offsetof(arena_run_t, mRegionsMask);
3109 MOZ_ASSERT(aSizeClass.Size() <= gMaxBinClass);
3111 try_run_size = gPageSize;
3113 mCurrentRun = nullptr;
3114 mNonFullRuns.Init();
3115 mSizeClass = aSizeClass.Size();
3116 mNumRuns = 0;
3118 // Run size expansion loop.
3119 while (true) {
3120 try_nregs = ((try_run_size - kFixedHeaderSize) / mSizeClass) +
3121 1; // Counter-act try_nregs-- in loop.
3123 // The do..while loop iteratively reduces the number of regions until
3124 // the run header and the regions no longer overlap. A closed formula
3125 // would be quite messy, since there is an interdependency between the
3126 // header's mask length and the number of regions.
3127 do {
3128 try_nregs--;
3129 try_mask_nelms =
3130 (try_nregs >> (LOG2(sizeof(int)) + 3)) +
3131 ((try_nregs & ((1U << (LOG2(sizeof(int)) + 3)) - 1)) ? 1 : 0);
3132 try_reg0_offset = try_run_size - (try_nregs * mSizeClass);
3133 } while (kFixedHeaderSize + (sizeof(unsigned) * try_mask_nelms) >
3134 try_reg0_offset);
3136 // Try to keep the run overhead below kRunOverhead.
3137 if (Fraction(try_reg0_offset, try_run_size) <= kRunOverhead) {
3138 break;
3141 // If the overhead is larger than the size class, it means the size class
3142 // is small and doesn't align very well with the header. It's desirable to
3143 // have smaller run sizes for them, so relax the overhead requirement.
3144 if (try_reg0_offset > mSizeClass) {
3145 if (Fraction(try_reg0_offset, try_run_size) <= kRunRelaxedOverhead) {
3146 break;
3150 // The run header includes one bit per region of the given size. For sizes
3151 // small enough, the number of regions is large enough that growing the run
3152 // size barely moves the needle for the overhead because of all those bits.
3153 // For example, for a size of 8 bytes, adding 4KiB to the run size adds
3154 // close to 512 bits to the header, which is 64 bytes.
3155 // With such overhead, there is no way to get to the wanted overhead above,
3156 // so we give up if the required size for mRegionsMask more than doubles the
3157 // size of the run header.
3158 if (try_mask_nelms * sizeof(unsigned) >= kFixedHeaderSize) {
3159 break;
3162 // If next iteration is going to be larger than the largest possible large
3163 // size class, then we didn't find a setup where the overhead is small
3164 // enough, and we can't do better than the current settings, so just use
3165 // that.
3166 if (try_run_size + gPageSize > gMaxLargeClass) {
3167 break;
3170 // Try more aggressive settings.
3171 try_run_size += gPageSize;
3174 MOZ_ASSERT(kFixedHeaderSize + (sizeof(unsigned) * try_mask_nelms) <=
3175 try_reg0_offset);
3176 MOZ_ASSERT((try_mask_nelms << (LOG2(sizeof(int)) + 3)) >= try_nregs);
3178 // Copy final settings.
3179 MOZ_ASSERT((try_run_size >> gPageSize2Pow) <= UINT8_MAX);
3180 mRunSizePages = static_cast<uint8_t>(try_run_size >> gPageSize2Pow);
3181 mRunNumRegions = try_nregs;
3182 mRunNumRegionsMask = try_mask_nelms;
3183 mRunFirstRegionOffset = try_reg0_offset;
3184 mSizeDivisor = FastDivisor<uint16_t>(aSizeClass.Size(), try_run_size);
3187 void* arena_t::MallocSmall(size_t aSize, bool aZero) {
3188 void* ret;
3189 arena_bin_t* bin;
3190 arena_run_t* run;
3191 SizeClass sizeClass(aSize);
3192 aSize = sizeClass.Size();
3194 switch (sizeClass.Type()) {
3195 case SizeClass::Tiny:
3196 bin = &mBins[FloorLog2(aSize / kMinTinyClass)];
3197 break;
3198 case SizeClass::Quantum:
3199 // Although we divide 2 things by kQuantum, the compiler will
3200 // reduce `kMinQuantumClass / kQuantum` and `kNumTinyClasses` to a
3201 // single constant.
3202 bin = &mBins[kNumTinyClasses + (aSize / kQuantum) -
3203 (kMinQuantumClass / kQuantum)];
3204 break;
3205 case SizeClass::QuantumWide:
3206 bin =
3207 &mBins[kNumTinyClasses + kNumQuantumClasses + (aSize / kQuantumWide) -
3208 (kMinQuantumWideClass / kQuantumWide)];
3209 break;
3210 case SizeClass::SubPage:
3211 bin =
3212 &mBins[kNumTinyClasses + kNumQuantumClasses + kNumQuantumWideClasses +
3213 (FloorLog2(aSize) - LOG2(kMinSubPageClass))];
3214 break;
3215 default:
3216 MOZ_MAKE_COMPILER_ASSUME_IS_UNREACHABLE("Unexpected size class type");
3218 MOZ_DIAGNOSTIC_ASSERT(aSize == bin->mSizeClass);
3221 // Before we lock, we determine if we need to randomize the allocation
3222 // because if we do, we need to create the PRNG which might require
3223 // allocating memory (arc4random on OSX for example) and we need to
3224 // avoid the deadlock
3225 if (MOZ_UNLIKELY(mRandomizeSmallAllocations && mPRNG == nullptr)) {
3226 // This is frustrating. Because the code backing RandomUint64 (arc4random
3227 // for example) may allocate memory, and because
3228 // mRandomizeSmallAllocations is true and we haven't yet initilized mPRNG,
3229 // we would re-enter this same case and cause a deadlock inside e.g.
3230 // arc4random. So we temporarily disable mRandomizeSmallAllocations to
3231 // skip this case and then re-enable it
3232 mRandomizeSmallAllocations = false;
3233 mozilla::Maybe<uint64_t> prngState1 = mozilla::RandomUint64();
3234 mozilla::Maybe<uint64_t> prngState2 = mozilla::RandomUint64();
3235 void* backing =
3236 base_alloc(sizeof(mozilla::non_crypto::XorShift128PlusRNG));
3237 mPRNG = new (backing) mozilla::non_crypto::XorShift128PlusRNG(
3238 prngState1.valueOr(0), prngState2.valueOr(0));
3239 mRandomizeSmallAllocations = true;
3241 MOZ_ASSERT(!mRandomizeSmallAllocations || mPRNG);
3243 MaybeMutexAutoLock lock(mLock);
3244 run = bin->mCurrentRun;
3245 if (MOZ_UNLIKELY(!run || run->mNumFree == 0)) {
3246 run = bin->mCurrentRun = GetNonFullBinRun(bin);
3248 if (MOZ_UNLIKELY(!run)) {
3249 return nullptr;
3251 MOZ_DIAGNOSTIC_ASSERT(run->mMagic == ARENA_RUN_MAGIC);
3252 MOZ_DIAGNOSTIC_ASSERT(run->mNumFree > 0);
3253 ret = ArenaRunRegAlloc(run, bin);
3254 MOZ_DIAGNOSTIC_ASSERT(ret);
3255 run->mNumFree--;
3256 if (!ret) {
3257 return nullptr;
3260 mStats.allocated_small += aSize;
3263 if (!aZero) {
3264 ApplyZeroOrJunk(ret, aSize);
3265 } else {
3266 memset(ret, 0, aSize);
3269 return ret;
3272 void* arena_t::MallocLarge(size_t aSize, bool aZero) {
3273 void* ret;
3275 // Large allocation.
3276 aSize = PAGE_CEILING(aSize);
3279 MaybeMutexAutoLock lock(mLock);
3280 ret = AllocRun(aSize, true, aZero);
3281 if (!ret) {
3282 return nullptr;
3284 mStats.allocated_large += aSize;
3287 if (!aZero) {
3288 ApplyZeroOrJunk(ret, aSize);
3291 return ret;
3294 void* arena_t::Malloc(size_t aSize, bool aZero) {
3295 MOZ_DIAGNOSTIC_ASSERT(mMagic == ARENA_MAGIC);
3296 MOZ_ASSERT(aSize != 0);
3298 if (aSize <= gMaxBinClass) {
3299 return MallocSmall(aSize, aZero);
3301 if (aSize <= gMaxLargeClass) {
3302 return MallocLarge(aSize, aZero);
3304 return MallocHuge(aSize, aZero);
3307 // Only handles large allocations that require more than page alignment.
3308 void* arena_t::PallocLarge(size_t aAlignment, size_t aSize, size_t aAllocSize) {
3309 void* ret;
3310 size_t offset;
3311 arena_chunk_t* chunk;
3313 MOZ_ASSERT((aSize & gPageSizeMask) == 0);
3314 MOZ_ASSERT((aAlignment & gPageSizeMask) == 0);
3317 MaybeMutexAutoLock lock(mLock);
3318 ret = AllocRun(aAllocSize, true, false);
3319 if (!ret) {
3320 return nullptr;
3323 chunk = GetChunkForPtr(ret);
3325 offset = uintptr_t(ret) & (aAlignment - 1);
3326 MOZ_ASSERT((offset & gPageSizeMask) == 0);
3327 MOZ_ASSERT(offset < aAllocSize);
3328 if (offset == 0) {
3329 TrimRunTail(chunk, (arena_run_t*)ret, aAllocSize, aSize, false);
3330 } else {
3331 size_t leadsize, trailsize;
3333 leadsize = aAlignment - offset;
3334 if (leadsize > 0) {
3335 TrimRunHead(chunk, (arena_run_t*)ret, aAllocSize,
3336 aAllocSize - leadsize);
3337 ret = (void*)(uintptr_t(ret) + leadsize);
3340 trailsize = aAllocSize - leadsize - aSize;
3341 if (trailsize != 0) {
3342 // Trim trailing space.
3343 MOZ_ASSERT(trailsize < aAllocSize);
3344 TrimRunTail(chunk, (arena_run_t*)ret, aSize + trailsize, aSize, false);
3348 mStats.allocated_large += aSize;
3351 ApplyZeroOrJunk(ret, aSize);
3352 return ret;
3355 void* arena_t::Palloc(size_t aAlignment, size_t aSize) {
3356 void* ret;
3357 size_t ceil_size;
3359 // Round size up to the nearest multiple of alignment.
3361 // This done, we can take advantage of the fact that for each small
3362 // size class, every object is aligned at the smallest power of two
3363 // that is non-zero in the base two representation of the size. For
3364 // example:
3366 // Size | Base 2 | Minimum alignment
3367 // -----+----------+------------------
3368 // 96 | 1100000 | 32
3369 // 144 | 10100000 | 32
3370 // 192 | 11000000 | 64
3372 // Depending on runtime settings, it is possible that arena_malloc()
3373 // will further round up to a power of two, but that never causes
3374 // correctness issues.
3375 ceil_size = ALIGNMENT_CEILING(aSize, aAlignment);
3377 // (ceil_size < aSize) protects against the combination of maximal
3378 // alignment and size greater than maximal alignment.
3379 if (ceil_size < aSize) {
3380 // size_t overflow.
3381 return nullptr;
3384 if (ceil_size <= gPageSize ||
3385 (aAlignment <= gPageSize && ceil_size <= gMaxLargeClass)) {
3386 ret = Malloc(ceil_size, false);
3387 } else {
3388 size_t run_size;
3390 // We can't achieve sub-page alignment, so round up alignment
3391 // permanently; it makes later calculations simpler.
3392 aAlignment = PAGE_CEILING(aAlignment);
3393 ceil_size = PAGE_CEILING(aSize);
3395 // (ceil_size < aSize) protects against very large sizes within
3396 // pagesize of SIZE_T_MAX.
3398 // (ceil_size + aAlignment < ceil_size) protects against the
3399 // combination of maximal alignment and ceil_size large enough
3400 // to cause overflow. This is similar to the first overflow
3401 // check above, but it needs to be repeated due to the new
3402 // ceil_size value, which may now be *equal* to maximal
3403 // alignment, whereas before we only detected overflow if the
3404 // original size was *greater* than maximal alignment.
3405 if (ceil_size < aSize || ceil_size + aAlignment < ceil_size) {
3406 // size_t overflow.
3407 return nullptr;
3410 // Calculate the size of the over-size run that arena_palloc()
3411 // would need to allocate in order to guarantee the alignment.
3412 if (ceil_size >= aAlignment) {
3413 run_size = ceil_size + aAlignment - gPageSize;
3414 } else {
3415 // It is possible that (aAlignment << 1) will cause
3416 // overflow, but it doesn't matter because we also
3417 // subtract pagesize, which in the case of overflow
3418 // leaves us with a very large run_size. That causes
3419 // the first conditional below to fail, which means
3420 // that the bogus run_size value never gets used for
3421 // anything important.
3422 run_size = (aAlignment << 1) - gPageSize;
3425 if (run_size <= gMaxLargeClass) {
3426 ret = PallocLarge(aAlignment, ceil_size, run_size);
3427 } else if (aAlignment <= kChunkSize) {
3428 ret = MallocHuge(ceil_size, false);
3429 } else {
3430 ret = PallocHuge(ceil_size, aAlignment, false);
3434 MOZ_ASSERT((uintptr_t(ret) & (aAlignment - 1)) == 0);
3435 return ret;
3438 class AllocInfo {
3439 public:
3440 template <bool Validate = false>
3441 static inline AllocInfo Get(const void* aPtr) {
3442 // If the allocator is not initialized, the pointer can't belong to it.
3443 if (Validate && malloc_initialized == false) {
3444 return AllocInfo();
3447 auto chunk = GetChunkForPtr(aPtr);
3448 if (Validate) {
3449 if (!chunk || !gChunkRTree.Get(chunk)) {
3450 return AllocInfo();
3454 if (chunk != aPtr) {
3455 MOZ_DIAGNOSTIC_ASSERT(chunk->arena->mMagic == ARENA_MAGIC);
3456 size_t pageind = (((uintptr_t)aPtr - (uintptr_t)chunk) >> gPageSize2Pow);
3457 return GetInChunk(aPtr, chunk, pageind);
3460 extent_node_t key;
3462 // Huge allocation
3463 key.mAddr = chunk;
3464 MutexAutoLock lock(huge_mtx);
3465 extent_node_t* node = huge.Search(&key);
3466 if (Validate && !node) {
3467 return AllocInfo();
3469 return AllocInfo(node->mSize, node);
3472 // Get the allocation information for a pointer we know is within a chunk
3473 // (Small or large, not huge).
3474 static inline AllocInfo GetInChunk(const void* aPtr, arena_chunk_t* aChunk,
3475 size_t pageind) {
3476 size_t mapbits = aChunk->map[pageind].bits;
3477 MOZ_DIAGNOSTIC_ASSERT((mapbits & CHUNK_MAP_ALLOCATED) != 0);
3479 size_t size;
3480 if ((mapbits & CHUNK_MAP_LARGE) == 0) {
3481 arena_run_t* run = (arena_run_t*)(mapbits & ~gPageSizeMask);
3482 MOZ_DIAGNOSTIC_ASSERT(run->mMagic == ARENA_RUN_MAGIC);
3483 size = run->mBin->mSizeClass;
3484 } else {
3485 size = mapbits & ~gPageSizeMask;
3486 MOZ_DIAGNOSTIC_ASSERT(size != 0);
3489 return AllocInfo(size, aChunk);
3492 // Validate ptr before assuming that it points to an allocation. Currently,
3493 // the following validation is performed:
3495 // + Check that ptr is not nullptr.
3497 // + Check that ptr lies within a mapped chunk.
3498 static inline AllocInfo GetValidated(const void* aPtr) {
3499 return Get<true>(aPtr);
3502 AllocInfo() : mSize(0), mChunk(nullptr) {}
3504 explicit AllocInfo(size_t aSize, arena_chunk_t* aChunk)
3505 : mSize(aSize), mChunk(aChunk) {
3506 MOZ_ASSERT(mSize <= gMaxLargeClass);
3509 explicit AllocInfo(size_t aSize, extent_node_t* aNode)
3510 : mSize(aSize), mNode(aNode) {
3511 MOZ_ASSERT(mSize > gMaxLargeClass);
3514 size_t Size() { return mSize; }
3516 arena_t* Arena() {
3517 if (mSize <= gMaxLargeClass) {
3518 return mChunk->arena;
3520 // Best effort detection that we're not trying to access an already
3521 // disposed arena. In the case of a disposed arena, the memory location
3522 // pointed by mNode->mArena is either free (but still a valid memory
3523 // region, per TypedBaseAlloc<arena_t>), in which case its id was reset,
3524 // or has been reallocated for a new region, and its id is very likely
3525 // different (per randomness). In both cases, the id is unlikely to
3526 // match what it was for the disposed arena.
3527 MOZ_RELEASE_ASSERT(mNode->mArenaId == mNode->mArena->mId);
3528 return mNode->mArena;
3531 bool IsValid() const { return !!mSize; }
3533 private:
3534 size_t mSize;
3535 union {
3536 // Pointer to the chunk associated with the allocation for small
3537 // and large allocations.
3538 arena_chunk_t* mChunk;
3540 // Pointer to the extent node for huge allocations.
3541 extent_node_t* mNode;
3545 template <>
3546 inline void MozJemalloc::jemalloc_ptr_info(const void* aPtr,
3547 jemalloc_ptr_info_t* aInfo) {
3548 arena_chunk_t* chunk = GetChunkForPtr(aPtr);
3550 // Is the pointer null, or within one chunk's size of null?
3551 // Alternatively, if the allocator is not initialized yet, the pointer
3552 // can't be known.
3553 if (!chunk || !malloc_initialized) {
3554 *aInfo = {TagUnknown, nullptr, 0, 0};
3555 return;
3558 // Look for huge allocations before looking for |chunk| in gChunkRTree.
3559 // This is necessary because |chunk| won't be in gChunkRTree if it's
3560 // the second or subsequent chunk in a huge allocation.
3561 extent_node_t* node;
3562 extent_node_t key;
3564 MutexAutoLock lock(huge_mtx);
3565 key.mAddr = const_cast<void*>(aPtr);
3566 node =
3567 reinterpret_cast<RedBlackTree<extent_node_t, ExtentTreeBoundsTrait>*>(
3568 &huge)
3569 ->Search(&key);
3570 if (node) {
3571 *aInfo = {TagLiveAlloc, node->mAddr, node->mSize, node->mArena->mId};
3572 return;
3576 // It's not a huge allocation. Check if we have a known chunk.
3577 if (!gChunkRTree.Get(chunk)) {
3578 *aInfo = {TagUnknown, nullptr, 0, 0};
3579 return;
3582 MOZ_DIAGNOSTIC_ASSERT(chunk->arena->mMagic == ARENA_MAGIC);
3584 // Get the page number within the chunk.
3585 size_t pageind = (((uintptr_t)aPtr - (uintptr_t)chunk) >> gPageSize2Pow);
3586 if (pageind < gChunkHeaderNumPages) {
3587 // Within the chunk header.
3588 *aInfo = {TagUnknown, nullptr, 0, 0};
3589 return;
3592 size_t mapbits = chunk->map[pageind].bits;
3594 if (!(mapbits & CHUNK_MAP_ALLOCATED)) {
3595 void* pageaddr = (void*)(uintptr_t(aPtr) & ~gPageSizeMask);
3596 *aInfo = {TagFreedPage, pageaddr, gPageSize, chunk->arena->mId};
3597 return;
3600 if (mapbits & CHUNK_MAP_LARGE) {
3601 // It's a large allocation. Only the first page of a large
3602 // allocation contains its size, so if the address is not in
3603 // the first page, scan back to find the allocation size.
3604 size_t size;
3605 while (true) {
3606 size = mapbits & ~gPageSizeMask;
3607 if (size != 0) {
3608 break;
3611 // The following two return paths shouldn't occur in
3612 // practice unless there is heap corruption.
3613 pageind--;
3614 MOZ_DIAGNOSTIC_ASSERT(pageind >= gChunkHeaderNumPages);
3615 if (pageind < gChunkHeaderNumPages) {
3616 *aInfo = {TagUnknown, nullptr, 0, 0};
3617 return;
3620 mapbits = chunk->map[pageind].bits;
3621 MOZ_DIAGNOSTIC_ASSERT(mapbits & CHUNK_MAP_LARGE);
3622 if (!(mapbits & CHUNK_MAP_LARGE)) {
3623 *aInfo = {TagUnknown, nullptr, 0, 0};
3624 return;
3628 void* addr = ((char*)chunk) + (pageind << gPageSize2Pow);
3629 *aInfo = {TagLiveAlloc, addr, size, chunk->arena->mId};
3630 return;
3633 // It must be a small allocation.
3634 auto run = (arena_run_t*)(mapbits & ~gPageSizeMask);
3635 MOZ_DIAGNOSTIC_ASSERT(run->mMagic == ARENA_RUN_MAGIC);
3637 // The allocation size is stored in the run metadata.
3638 size_t size = run->mBin->mSizeClass;
3640 // Address of the first possible pointer in the run after its headers.
3641 uintptr_t reg0_addr = (uintptr_t)run + run->mBin->mRunFirstRegionOffset;
3642 if (aPtr < (void*)reg0_addr) {
3643 // In the run header.
3644 *aInfo = {TagUnknown, nullptr, 0, 0};
3645 return;
3648 // Position in the run.
3649 unsigned regind = ((uintptr_t)aPtr - reg0_addr) / size;
3651 // Pointer to the allocation's base address.
3652 void* addr = (void*)(reg0_addr + regind * size);
3654 // Check if the allocation has been freed.
3655 unsigned elm = regind >> (LOG2(sizeof(int)) + 3);
3656 unsigned bit = regind - (elm << (LOG2(sizeof(int)) + 3));
3657 PtrInfoTag tag =
3658 ((run->mRegionsMask[elm] & (1U << bit))) ? TagFreedAlloc : TagLiveAlloc;
3660 *aInfo = {tag, addr, size, chunk->arena->mId};
3663 namespace Debug {
3664 // Helper for debuggers. We don't want it to be inlined and optimized out.
3665 MOZ_NEVER_INLINE jemalloc_ptr_info_t* jemalloc_ptr_info(const void* aPtr) {
3666 static jemalloc_ptr_info_t info;
3667 MozJemalloc::jemalloc_ptr_info(aPtr, &info);
3668 return &info;
3670 } // namespace Debug
3672 arena_chunk_t* arena_t::DallocSmall(arena_chunk_t* aChunk, void* aPtr,
3673 arena_chunk_map_t* aMapElm) {
3674 arena_run_t* run;
3675 arena_bin_t* bin;
3676 size_t size;
3678 run = (arena_run_t*)(aMapElm->bits & ~gPageSizeMask);
3679 MOZ_DIAGNOSTIC_ASSERT(run->mMagic == ARENA_RUN_MAGIC);
3680 bin = run->mBin;
3681 size = bin->mSizeClass;
3682 MOZ_DIAGNOSTIC_ASSERT(uintptr_t(aPtr) >=
3683 uintptr_t(run) + bin->mRunFirstRegionOffset);
3685 arena_run_reg_dalloc(run, bin, aPtr, size);
3686 run->mNumFree++;
3687 arena_chunk_t* dealloc_chunk = nullptr;
3689 if (run->mNumFree == bin->mRunNumRegions) {
3690 // Deallocate run.
3691 if (run == bin->mCurrentRun) {
3692 bin->mCurrentRun = nullptr;
3693 } else if (bin->mRunNumRegions != 1) {
3694 size_t run_pageind =
3695 (uintptr_t(run) - uintptr_t(aChunk)) >> gPageSize2Pow;
3696 arena_chunk_map_t* run_mapelm = &aChunk->map[run_pageind];
3698 // This block's conditional is necessary because if the
3699 // run only contains one region, then it never gets
3700 // inserted into the non-full runs tree.
3701 MOZ_DIAGNOSTIC_ASSERT(bin->mNonFullRuns.Search(run_mapelm) == run_mapelm);
3702 bin->mNonFullRuns.Remove(run_mapelm);
3704 #if defined(MOZ_DIAGNOSTIC_ASSERT_ENABLED)
3705 run->mMagic = 0;
3706 #endif
3707 dealloc_chunk = DallocRun(run, true);
3708 bin->mNumRuns--;
3709 } else if (run->mNumFree == 1 && run != bin->mCurrentRun) {
3710 // Make sure that bin->mCurrentRun always refers to the lowest
3711 // non-full run, if one exists.
3712 if (!bin->mCurrentRun) {
3713 bin->mCurrentRun = run;
3714 } else if (uintptr_t(run) < uintptr_t(bin->mCurrentRun)) {
3715 // Switch mCurrentRun.
3716 if (bin->mCurrentRun->mNumFree > 0) {
3717 arena_chunk_t* runcur_chunk = GetChunkForPtr(bin->mCurrentRun);
3718 size_t runcur_pageind =
3719 (uintptr_t(bin->mCurrentRun) - uintptr_t(runcur_chunk)) >>
3720 gPageSize2Pow;
3721 arena_chunk_map_t* runcur_mapelm = &runcur_chunk->map[runcur_pageind];
3723 // Insert runcur.
3724 MOZ_DIAGNOSTIC_ASSERT(!bin->mNonFullRuns.Search(runcur_mapelm));
3725 bin->mNonFullRuns.Insert(runcur_mapelm);
3727 bin->mCurrentRun = run;
3728 } else {
3729 size_t run_pageind =
3730 (uintptr_t(run) - uintptr_t(aChunk)) >> gPageSize2Pow;
3731 arena_chunk_map_t* run_mapelm = &aChunk->map[run_pageind];
3733 MOZ_DIAGNOSTIC_ASSERT(bin->mNonFullRuns.Search(run_mapelm) == nullptr);
3734 bin->mNonFullRuns.Insert(run_mapelm);
3737 mStats.allocated_small -= size;
3739 return dealloc_chunk;
3742 arena_chunk_t* arena_t::DallocLarge(arena_chunk_t* aChunk, void* aPtr) {
3743 MOZ_DIAGNOSTIC_ASSERT((uintptr_t(aPtr) & gPageSizeMask) == 0);
3744 size_t pageind = (uintptr_t(aPtr) - uintptr_t(aChunk)) >> gPageSize2Pow;
3745 size_t size = aChunk->map[pageind].bits & ~gPageSizeMask;
3747 mStats.allocated_large -= size;
3749 return DallocRun((arena_run_t*)aPtr, true);
3752 static inline void arena_dalloc(void* aPtr, size_t aOffset, arena_t* aArena) {
3753 MOZ_ASSERT(aPtr);
3754 MOZ_ASSERT(aOffset != 0);
3755 MOZ_ASSERT(GetChunkOffsetForPtr(aPtr) == aOffset);
3757 auto chunk = (arena_chunk_t*)((uintptr_t)aPtr - aOffset);
3758 auto arena = chunk->arena;
3759 MOZ_ASSERT(arena);
3760 MOZ_DIAGNOSTIC_ASSERT(arena->mMagic == ARENA_MAGIC);
3761 MOZ_RELEASE_ASSERT(!aArena || arena == aArena);
3763 size_t pageind = aOffset >> gPageSize2Pow;
3764 if (opt_poison) {
3765 AllocInfo info = AllocInfo::GetInChunk(aPtr, chunk, pageind);
3766 MOZ_ASSERT(info.IsValid());
3767 MaybePoison(aPtr, info.Size());
3770 arena_chunk_t* chunk_dealloc_delay = nullptr;
3773 MaybeMutexAutoLock lock(arena->mLock);
3774 arena_chunk_map_t* mapelm = &chunk->map[pageind];
3775 MOZ_RELEASE_ASSERT((mapelm->bits & CHUNK_MAP_DECOMMITTED) == 0,
3776 "Freeing in decommitted page.");
3777 MOZ_RELEASE_ASSERT((mapelm->bits & CHUNK_MAP_ALLOCATED) != 0,
3778 "Double-free?");
3779 if ((mapelm->bits & CHUNK_MAP_LARGE) == 0) {
3780 // Small allocation.
3781 chunk_dealloc_delay = arena->DallocSmall(chunk, aPtr, mapelm);
3782 } else {
3783 // Large allocation.
3784 chunk_dealloc_delay = arena->DallocLarge(chunk, aPtr);
3788 if (chunk_dealloc_delay) {
3789 chunk_dealloc((void*)chunk_dealloc_delay, kChunkSize, ARENA_CHUNK);
3793 static inline void idalloc(void* ptr, arena_t* aArena) {
3794 size_t offset;
3796 MOZ_ASSERT(ptr);
3798 offset = GetChunkOffsetForPtr(ptr);
3799 if (offset != 0) {
3800 arena_dalloc(ptr, offset, aArena);
3801 } else {
3802 huge_dalloc(ptr, aArena);
3806 void arena_t::RallocShrinkLarge(arena_chunk_t* aChunk, void* aPtr, size_t aSize,
3807 size_t aOldSize) {
3808 MOZ_ASSERT(aSize < aOldSize);
3810 // Shrink the run, and make trailing pages available for other
3811 // allocations.
3812 MaybeMutexAutoLock lock(mLock);
3813 TrimRunTail(aChunk, (arena_run_t*)aPtr, aOldSize, aSize, true);
3814 mStats.allocated_large -= aOldSize - aSize;
3817 // Returns whether reallocation was successful.
3818 bool arena_t::RallocGrowLarge(arena_chunk_t* aChunk, void* aPtr, size_t aSize,
3819 size_t aOldSize) {
3820 size_t pageind = (uintptr_t(aPtr) - uintptr_t(aChunk)) >> gPageSize2Pow;
3821 size_t npages = aOldSize >> gPageSize2Pow;
3823 MaybeMutexAutoLock lock(mLock);
3824 MOZ_DIAGNOSTIC_ASSERT(aOldSize ==
3825 (aChunk->map[pageind].bits & ~gPageSizeMask));
3827 // Try to extend the run.
3828 MOZ_ASSERT(aSize > aOldSize);
3829 if (pageind + npages < gChunkNumPages - 1 &&
3830 (aChunk->map[pageind + npages].bits & CHUNK_MAP_ALLOCATED) == 0 &&
3831 (aChunk->map[pageind + npages].bits & ~gPageSizeMask) >=
3832 aSize - aOldSize) {
3833 // The next run is available and sufficiently large. Split the
3834 // following run, then merge the first part with the existing
3835 // allocation.
3836 if (!SplitRun((arena_run_t*)(uintptr_t(aChunk) +
3837 ((pageind + npages) << gPageSize2Pow)),
3838 aSize - aOldSize, true, false)) {
3839 return false;
3842 aChunk->map[pageind].bits = aSize | CHUNK_MAP_LARGE | CHUNK_MAP_ALLOCATED;
3843 aChunk->map[pageind + npages].bits = CHUNK_MAP_LARGE | CHUNK_MAP_ALLOCATED;
3845 mStats.allocated_large += aSize - aOldSize;
3846 return true;
3849 return false;
3852 void* arena_t::RallocSmallOrLarge(void* aPtr, size_t aSize, size_t aOldSize) {
3853 void* ret;
3854 size_t copysize;
3855 SizeClass sizeClass(aSize);
3857 // Try to avoid moving the allocation.
3858 if (aOldSize <= gMaxLargeClass && sizeClass.Size() == aOldSize) {
3859 if (aSize < aOldSize) {
3860 MaybePoison((void*)(uintptr_t(aPtr) + aSize), aOldSize - aSize);
3862 return aPtr;
3864 if (sizeClass.Type() == SizeClass::Large && aOldSize > gMaxBinClass &&
3865 aOldSize <= gMaxLargeClass) {
3866 arena_chunk_t* chunk = GetChunkForPtr(aPtr);
3867 if (sizeClass.Size() < aOldSize) {
3868 // Fill before shrinking in order to avoid a race.
3869 MaybePoison((void*)((uintptr_t)aPtr + aSize), aOldSize - aSize);
3870 RallocShrinkLarge(chunk, aPtr, sizeClass.Size(), aOldSize);
3871 return aPtr;
3873 if (RallocGrowLarge(chunk, aPtr, sizeClass.Size(), aOldSize)) {
3874 ApplyZeroOrJunk((void*)((uintptr_t)aPtr + aOldSize), aSize - aOldSize);
3875 return aPtr;
3879 // If we get here, then aSize and aOldSize are different enough that we
3880 // need to move the object. In that case, fall back to allocating new
3881 // space and copying. Allow non-private arenas to switch arenas.
3882 ret = (mIsPrivate ? this : choose_arena(aSize))->Malloc(aSize, false);
3883 if (!ret) {
3884 return nullptr;
3887 // Junk/zero-filling were already done by arena_t::Malloc().
3888 copysize = (aSize < aOldSize) ? aSize : aOldSize;
3889 #ifdef VM_COPY_MIN
3890 if (copysize >= VM_COPY_MIN) {
3891 pages_copy(ret, aPtr, copysize);
3892 } else
3893 #endif
3895 memcpy(ret, aPtr, copysize);
3897 idalloc(aPtr, this);
3898 return ret;
3901 void* arena_t::Ralloc(void* aPtr, size_t aSize, size_t aOldSize) {
3902 MOZ_DIAGNOSTIC_ASSERT(mMagic == ARENA_MAGIC);
3903 MOZ_ASSERT(aPtr);
3904 MOZ_ASSERT(aSize != 0);
3906 return (aSize <= gMaxLargeClass) ? RallocSmallOrLarge(aPtr, aSize, aOldSize)
3907 : RallocHuge(aPtr, aSize, aOldSize);
3910 void* arena_t::operator new(size_t aCount, const fallible_t&) noexcept {
3911 MOZ_ASSERT(aCount == sizeof(arena_t));
3912 return TypedBaseAlloc<arena_t>::alloc();
3915 void arena_t::operator delete(void* aPtr) {
3916 TypedBaseAlloc<arena_t>::dealloc((arena_t*)aPtr);
3919 arena_t::arena_t(arena_params_t* aParams, bool aIsPrivate) {
3920 unsigned i;
3922 memset(&mLink, 0, sizeof(mLink));
3923 memset(&mStats, 0, sizeof(arena_stats_t));
3924 mId = 0;
3926 // Initialize chunks.
3927 mChunksDirty.Init();
3928 #ifdef MALLOC_DOUBLE_PURGE
3929 new (&mChunksMAdvised) DoublyLinkedList<arena_chunk_t>();
3930 #endif
3931 mSpare = nullptr;
3933 mRandomizeSmallAllocations = opt_randomize_small;
3934 MaybeMutex::DoLock doLock = MaybeMutex::MUST_LOCK;
3935 if (aParams) {
3936 uint32_t randFlags = aParams->mFlags & ARENA_FLAG_RANDOMIZE_SMALL_MASK;
3937 switch (randFlags) {
3938 case ARENA_FLAG_RANDOMIZE_SMALL_ENABLED:
3939 mRandomizeSmallAllocations = true;
3940 break;
3941 case ARENA_FLAG_RANDOMIZE_SMALL_DISABLED:
3942 mRandomizeSmallAllocations = false;
3943 break;
3944 case ARENA_FLAG_RANDOMIZE_SMALL_DEFAULT:
3945 default:
3946 break;
3949 uint32_t threadFlags = aParams->mFlags & ARENA_FLAG_THREAD_MASK;
3950 if (threadFlags == ARENA_FLAG_THREAD_MAIN_THREAD_ONLY) {
3951 // At the moment we require that any ARENA_FLAG_THREAD_MAIN_THREAD_ONLY
3952 // arenas are created and therefore always accessed by the main thread.
3953 // This is for two reasons:
3954 // * it allows jemalloc_stats to read their statistics (we also require
3955 // that jemalloc_stats is only used on the main thread).
3956 // * Only main-thread or threadsafe arenas can be guanteed to be in a
3957 // consistent state after a fork() from the main thread. If fork()
3958 // occurs off-thread then the new child process cannot use these arenas
3959 // (new children should usually exec() or exit() since other data may
3960 // also be inconsistent).
3961 MOZ_ASSERT(gArenas.IsOnMainThread());
3962 doLock = MaybeMutex::AVOID_LOCK_UNSAFE;
3965 mMaxDirtyIncreaseOverride = aParams->mMaxDirtyIncreaseOverride;
3966 mMaxDirtyDecreaseOverride = aParams->mMaxDirtyDecreaseOverride;
3967 } else {
3968 mMaxDirtyIncreaseOverride = 0;
3969 mMaxDirtyDecreaseOverride = 0;
3972 MOZ_RELEASE_ASSERT(mLock.Init(doLock));
3974 mPRNG = nullptr;
3976 mIsPrivate = aIsPrivate;
3978 mNumDirty = 0;
3979 // The default maximum amount of dirty pages allowed on arenas is a fraction
3980 // of opt_dirty_max.
3981 mMaxDirty = (aParams && aParams->mMaxDirty) ? aParams->mMaxDirty
3982 : (opt_dirty_max / 8);
3984 mRunsAvail.Init();
3986 // Initialize bins.
3987 SizeClass sizeClass(1);
3989 for (i = 0;; i++) {
3990 arena_bin_t& bin = mBins[i];
3991 bin.Init(sizeClass);
3993 // SizeClass doesn't want sizes larger than gMaxBinClass for now.
3994 if (sizeClass.Size() == gMaxBinClass) {
3995 break;
3997 sizeClass = sizeClass.Next();
3999 MOZ_ASSERT(i == NUM_SMALL_CLASSES - 1);
4001 #if defined(MOZ_DIAGNOSTIC_ASSERT_ENABLED)
4002 mMagic = ARENA_MAGIC;
4003 #endif
4006 arena_t::~arena_t() {
4007 size_t i;
4008 MaybeMutexAutoLock lock(mLock);
4009 MOZ_RELEASE_ASSERT(!mLink.Left() && !mLink.Right(),
4010 "Arena is still registered");
4011 MOZ_RELEASE_ASSERT(!mStats.allocated_small && !mStats.allocated_large,
4012 "Arena is not empty");
4013 if (mSpare) {
4014 chunk_dealloc(mSpare, kChunkSize, ARENA_CHUNK);
4016 for (i = 0; i < NUM_SMALL_CLASSES; i++) {
4017 MOZ_RELEASE_ASSERT(!mBins[i].mNonFullRuns.First(), "Bin is not empty");
4019 #ifdef MOZ_DEBUG
4021 MutexAutoLock lock(huge_mtx);
4022 // This is an expensive check, so we only do it on debug builds.
4023 for (auto node : huge.iter()) {
4024 MOZ_RELEASE_ASSERT(node->mArenaId != mId, "Arena has huge allocations");
4027 #endif
4028 mId = 0;
4031 arena_t* ArenaCollection::CreateArena(bool aIsPrivate,
4032 arena_params_t* aParams) {
4033 arena_t* ret = new (fallible) arena_t(aParams, aIsPrivate);
4034 if (!ret) {
4035 // Only reached if there is an OOM error.
4037 // OOM here is quite inconvenient to propagate, since dealing with it
4038 // would require a check for failure in the fast path. Instead, punt
4039 // by using the first arena.
4040 // In practice, this is an extremely unlikely failure.
4041 _malloc_message(_getprogname(), ": (malloc) Error initializing arena\n");
4043 return mDefaultArena;
4046 MutexAutoLock lock(mLock);
4048 // For public arenas, it's fine to just use incrementing arena id
4049 if (!aIsPrivate) {
4050 ret->mId = mLastPublicArenaId++;
4051 mArenas.Insert(ret);
4052 return ret;
4055 // For private arenas, generate a cryptographically-secure random id for the
4056 // new arena. If an attacker manages to get control of the process, this
4057 // should make it more difficult for them to "guess" the ID of a memory
4058 // arena, stopping them from getting data they may want
4060 while (true) {
4061 mozilla::Maybe<uint64_t> maybeRandomId = mozilla::RandomUint64();
4062 MOZ_RELEASE_ASSERT(maybeRandomId.isSome());
4064 // Avoid 0 as an arena Id. We use 0 for disposed arenas.
4065 if (!maybeRandomId.value()) {
4066 continue;
4069 // Keep looping until we ensure that the random number we just generated
4070 // isn't already in use by another active arena
4071 arena_t* existingArena =
4072 GetByIdInternal(maybeRandomId.value(), true /*aIsPrivate*/);
4074 if (!existingArena) {
4075 ret->mId = static_cast<arena_id_t>(maybeRandomId.value());
4076 mPrivateArenas.Insert(ret);
4077 return ret;
4082 // End arena.
4083 // ***************************************************************************
4084 // Begin general internal functions.
4086 void* arena_t::MallocHuge(size_t aSize, bool aZero) {
4087 return PallocHuge(aSize, kChunkSize, aZero);
4090 void* arena_t::PallocHuge(size_t aSize, size_t aAlignment, bool aZero) {
4091 void* ret;
4092 size_t csize;
4093 size_t psize;
4094 extent_node_t* node;
4095 bool zeroed;
4097 // We're going to configure guard pages in the region between the
4098 // page-aligned size and the chunk-aligned size, so if those are the same
4099 // then we need to force that region into existence.
4100 csize = CHUNK_CEILING(aSize + gPageSize);
4101 if (csize < aSize) {
4102 // size is large enough to cause size_t wrap-around.
4103 return nullptr;
4106 // Allocate an extent node with which to track the chunk.
4107 node = ExtentAlloc::alloc();
4108 if (!node) {
4109 return nullptr;
4112 // Allocate one or more contiguous chunks for this request.
4113 ret = chunk_alloc(csize, aAlignment, false, &zeroed);
4114 if (!ret) {
4115 ExtentAlloc::dealloc(node);
4116 return nullptr;
4118 psize = PAGE_CEILING(aSize);
4119 if (aZero) {
4120 // We will decommit anything past psize so there is no need to zero
4121 // further.
4122 chunk_ensure_zero(ret, psize, zeroed);
4125 // Insert node into huge.
4126 node->mAddr = ret;
4127 node->mSize = psize;
4128 node->mArena = this;
4129 node->mArenaId = mId;
4132 MutexAutoLock lock(huge_mtx);
4133 huge.Insert(node);
4135 // Although we allocated space for csize bytes, we indicate that we've
4136 // allocated only psize bytes.
4138 // If DECOMMIT is defined, this is a reasonable thing to do, since
4139 // we'll explicitly decommit the bytes in excess of psize.
4141 // If DECOMMIT is not defined, then we're relying on the OS to be lazy
4142 // about how it allocates physical pages to mappings. If we never
4143 // touch the pages in excess of psize, the OS won't allocate a physical
4144 // page, and we won't use more than psize bytes of physical memory.
4146 // A correct program will only touch memory in excess of how much it
4147 // requested if it first calls malloc_usable_size and finds out how
4148 // much space it has to play with. But because we set node->mSize =
4149 // psize above, malloc_usable_size will return psize, not csize, and
4150 // the program will (hopefully) never touch bytes in excess of psize.
4151 // Thus those bytes won't take up space in physical memory, and we can
4152 // reasonably claim we never "allocated" them in the first place.
4153 huge_allocated += psize;
4154 huge_mapped += csize;
4157 pages_decommit((void*)((uintptr_t)ret + psize), csize - psize);
4159 if (!aZero) {
4160 ApplyZeroOrJunk(ret, psize);
4163 return ret;
4166 void* arena_t::RallocHuge(void* aPtr, size_t aSize, size_t aOldSize) {
4167 void* ret;
4168 size_t copysize;
4170 // Avoid moving the allocation if the size class would not change.
4171 if (aOldSize > gMaxLargeClass &&
4172 CHUNK_CEILING(aSize + gPageSize) == CHUNK_CEILING(aOldSize + gPageSize)) {
4173 size_t psize = PAGE_CEILING(aSize);
4174 if (aSize < aOldSize) {
4175 MaybePoison((void*)((uintptr_t)aPtr + aSize), aOldSize - aSize);
4177 if (psize < aOldSize) {
4178 extent_node_t key;
4180 pages_decommit((void*)((uintptr_t)aPtr + psize), aOldSize - psize);
4182 // Update recorded size.
4183 MutexAutoLock lock(huge_mtx);
4184 key.mAddr = const_cast<void*>(aPtr);
4185 extent_node_t* node = huge.Search(&key);
4186 MOZ_ASSERT(node);
4187 MOZ_ASSERT(node->mSize == aOldSize);
4188 MOZ_RELEASE_ASSERT(node->mArena == this);
4189 huge_allocated -= aOldSize - psize;
4190 // No need to change huge_mapped, because we didn't (un)map anything.
4191 node->mSize = psize;
4192 } else if (psize > aOldSize) {
4193 if (!pages_commit((void*)((uintptr_t)aPtr + aOldSize),
4194 psize - aOldSize)) {
4195 return nullptr;
4198 // We need to update the recorded size if the size increased,
4199 // so malloc_usable_size doesn't return a value smaller than
4200 // what was requested via realloc().
4201 extent_node_t key;
4202 MutexAutoLock lock(huge_mtx);
4203 key.mAddr = const_cast<void*>(aPtr);
4204 extent_node_t* node = huge.Search(&key);
4205 MOZ_ASSERT(node);
4206 MOZ_ASSERT(node->mSize == aOldSize);
4207 MOZ_RELEASE_ASSERT(node->mArena == this);
4208 huge_allocated += psize - aOldSize;
4209 // No need to change huge_mapped, because we didn't
4210 // (un)map anything.
4211 node->mSize = psize;
4214 if (aSize > aOldSize) {
4215 ApplyZeroOrJunk((void*)((uintptr_t)aPtr + aOldSize), aSize - aOldSize);
4217 return aPtr;
4220 // If we get here, then aSize and aOldSize are different enough that we
4221 // need to use a different size class. In that case, fall back to allocating
4222 // new space and copying. Allow non-private arenas to switch arenas.
4223 ret = (mIsPrivate ? this : choose_arena(aSize))->MallocHuge(aSize, false);
4224 if (!ret) {
4225 return nullptr;
4228 copysize = (aSize < aOldSize) ? aSize : aOldSize;
4229 #ifdef VM_COPY_MIN
4230 if (copysize >= VM_COPY_MIN) {
4231 pages_copy(ret, aPtr, copysize);
4232 } else
4233 #endif
4235 memcpy(ret, aPtr, copysize);
4237 idalloc(aPtr, this);
4238 return ret;
4241 static void huge_dalloc(void* aPtr, arena_t* aArena) {
4242 extent_node_t* node;
4243 size_t mapped = 0;
4245 extent_node_t key;
4246 MutexAutoLock lock(huge_mtx);
4248 // Extract from tree of huge allocations.
4249 key.mAddr = aPtr;
4250 node = huge.Search(&key);
4251 MOZ_RELEASE_ASSERT(node, "Double-free?");
4252 MOZ_ASSERT(node->mAddr == aPtr);
4253 MOZ_RELEASE_ASSERT(!aArena || node->mArena == aArena);
4254 // See AllocInfo::Arena.
4255 MOZ_RELEASE_ASSERT(node->mArenaId == node->mArena->mId);
4256 huge.Remove(node);
4258 mapped = CHUNK_CEILING(node->mSize + gPageSize);
4259 huge_allocated -= node->mSize;
4260 huge_mapped -= mapped;
4263 // Unmap chunk.
4264 chunk_dealloc(node->mAddr, mapped, HUGE_CHUNK);
4266 ExtentAlloc::dealloc(node);
4269 static size_t GetKernelPageSize() {
4270 static size_t kernel_page_size = ([]() {
4271 #ifdef XP_WIN
4272 SYSTEM_INFO info;
4273 GetSystemInfo(&info);
4274 return info.dwPageSize;
4275 #else
4276 long result = sysconf(_SC_PAGESIZE);
4277 MOZ_ASSERT(result != -1);
4278 return result;
4279 #endif
4280 })();
4281 return kernel_page_size;
4284 // Returns whether the allocator was successfully initialized.
4285 static bool malloc_init_hard() {
4286 unsigned i;
4287 const char* opts;
4289 AutoLock<StaticMutex> lock(gInitLock);
4291 if (malloc_initialized) {
4292 // Another thread initialized the allocator before this one
4293 // acquired gInitLock.
4294 return true;
4297 if (!thread_arena.init()) {
4298 return true;
4301 // Get page size and number of CPUs
4302 const size_t result = GetKernelPageSize();
4303 // We assume that the page size is a power of 2.
4304 MOZ_ASSERT(((result - 1) & result) == 0);
4305 #ifdef MALLOC_STATIC_PAGESIZE
4306 if (gPageSize % result) {
4307 _malloc_message(
4308 _getprogname(),
4309 "Compile-time page size does not divide the runtime one.\n");
4310 MOZ_CRASH();
4312 #else
4313 gRealPageSize = gPageSize = result;
4314 #endif
4316 // Get runtime configuration.
4317 if ((opts = getenv("MALLOC_OPTIONS"))) {
4318 for (i = 0; opts[i] != '\0'; i++) {
4319 unsigned j, nreps;
4320 bool nseen;
4322 // Parse repetition count, if any.
4323 for (nreps = 0, nseen = false;; i++, nseen = true) {
4324 switch (opts[i]) {
4325 case '0':
4326 case '1':
4327 case '2':
4328 case '3':
4329 case '4':
4330 case '5':
4331 case '6':
4332 case '7':
4333 case '8':
4334 case '9':
4335 nreps *= 10;
4336 nreps += opts[i] - '0';
4337 break;
4338 default:
4339 goto MALLOC_OUT;
4342 MALLOC_OUT:
4343 if (nseen == false) {
4344 nreps = 1;
4347 for (j = 0; j < nreps; j++) {
4348 switch (opts[i]) {
4349 case 'f':
4350 opt_dirty_max >>= 1;
4351 break;
4352 case 'F':
4353 if (opt_dirty_max == 0) {
4354 opt_dirty_max = 1;
4355 } else if ((opt_dirty_max << 1) != 0) {
4356 opt_dirty_max <<= 1;
4358 break;
4359 #ifdef MALLOC_RUNTIME_CONFIG
4360 case 'j':
4361 opt_junk = false;
4362 break;
4363 case 'J':
4364 opt_junk = true;
4365 break;
4366 case 'q':
4367 opt_poison = false;
4368 break;
4369 case 'Q':
4370 opt_poison = true;
4371 break;
4372 case 'z':
4373 opt_zero = false;
4374 break;
4375 case 'Z':
4376 opt_zero = true;
4377 break;
4378 # ifndef MALLOC_STATIC_PAGESIZE
4379 case 'P':
4380 if (gPageSize < 64_KiB) {
4381 gPageSize <<= 1;
4383 break;
4384 # endif
4385 #endif
4386 case 'r':
4387 opt_randomize_small = false;
4388 break;
4389 case 'R':
4390 opt_randomize_small = true;
4391 break;
4392 default: {
4393 char cbuf[2];
4395 cbuf[0] = opts[i];
4396 cbuf[1] = '\0';
4397 _malloc_message(_getprogname(),
4398 ": (malloc) Unsupported character "
4399 "in malloc options: '",
4400 cbuf, "'\n");
4407 #ifndef MALLOC_STATIC_PAGESIZE
4408 DefineGlobals();
4409 #endif
4410 gRecycledSize = 0;
4412 // Initialize chunks data.
4413 chunks_mtx.Init();
4414 MOZ_PUSH_IGNORE_THREAD_SAFETY
4415 gChunksBySize.Init();
4416 gChunksByAddress.Init();
4417 MOZ_POP_THREAD_SAFETY
4419 // Initialize huge allocation data.
4420 huge_mtx.Init();
4421 MOZ_PUSH_IGNORE_THREAD_SAFETY
4422 huge.Init();
4423 huge_allocated = 0;
4424 huge_mapped = 0;
4425 MOZ_POP_THREAD_SAFETY
4427 // Initialize base allocation data structures.
4428 base_mtx.Init();
4429 MOZ_PUSH_IGNORE_THREAD_SAFETY
4430 base_mapped = 0;
4431 base_committed = 0;
4432 MOZ_POP_THREAD_SAFETY
4434 // Initialize arenas collection here.
4435 if (!gArenas.Init()) {
4436 return false;
4439 // Assign the default arena to the initial thread.
4440 thread_arena.set(gArenas.GetDefault());
4442 if (!gChunkRTree.Init()) {
4443 return false;
4446 malloc_initialized = true;
4448 // Dummy call so that the function is not removed by dead-code elimination
4449 Debug::jemalloc_ptr_info(nullptr);
4451 #if !defined(XP_WIN) && !defined(XP_DARWIN)
4452 // Prevent potential deadlock on malloc locks after fork.
4453 pthread_atfork(_malloc_prefork, _malloc_postfork_parent,
4454 _malloc_postfork_child);
4455 #endif
4457 return true;
4460 // End general internal functions.
4461 // ***************************************************************************
4462 // Begin malloc(3)-compatible functions.
4464 // The BaseAllocator class is a helper class that implements the base allocator
4465 // functions (malloc, calloc, realloc, free, memalign) for a given arena,
4466 // or an appropriately chosen arena (per choose_arena()) when none is given.
4467 struct BaseAllocator {
4468 #define MALLOC_DECL(name, return_type, ...) \
4469 inline return_type name(__VA_ARGS__);
4471 #define MALLOC_FUNCS MALLOC_FUNCS_MALLOC_BASE
4472 #include "malloc_decls.h"
4474 explicit BaseAllocator(arena_t* aArena) : mArena(aArena) {}
4476 private:
4477 arena_t* mArena;
4480 #define MALLOC_DECL(name, return_type, ...) \
4481 template <> \
4482 inline return_type MozJemalloc::name( \
4483 ARGS_HELPER(TYPED_ARGS, ##__VA_ARGS__)) { \
4484 BaseAllocator allocator(nullptr); \
4485 return allocator.name(ARGS_HELPER(ARGS, ##__VA_ARGS__)); \
4487 #define MALLOC_FUNCS MALLOC_FUNCS_MALLOC_BASE
4488 #include "malloc_decls.h"
4490 inline void* BaseAllocator::malloc(size_t aSize) {
4491 void* ret;
4492 arena_t* arena;
4494 if (!malloc_init()) {
4495 ret = nullptr;
4496 goto RETURN;
4499 if (aSize == 0) {
4500 aSize = 1;
4502 arena = mArena ? mArena : choose_arena(aSize);
4503 ret = arena->Malloc(aSize, /* aZero = */ false);
4505 RETURN:
4506 if (!ret) {
4507 errno = ENOMEM;
4510 return ret;
4513 inline void* BaseAllocator::memalign(size_t aAlignment, size_t aSize) {
4514 MOZ_ASSERT(((aAlignment - 1) & aAlignment) == 0);
4516 if (!malloc_init()) {
4517 return nullptr;
4520 if (aSize == 0) {
4521 aSize = 1;
4524 aAlignment = aAlignment < sizeof(void*) ? sizeof(void*) : aAlignment;
4525 arena_t* arena = mArena ? mArena : choose_arena(aSize);
4526 return arena->Palloc(aAlignment, aSize);
4529 inline void* BaseAllocator::calloc(size_t aNum, size_t aSize) {
4530 void* ret;
4532 if (malloc_init()) {
4533 CheckedInt<size_t> checkedSize = CheckedInt<size_t>(aNum) * aSize;
4534 if (checkedSize.isValid()) {
4535 size_t allocSize = checkedSize.value();
4536 if (allocSize == 0) {
4537 allocSize = 1;
4539 arena_t* arena = mArena ? mArena : choose_arena(allocSize);
4540 ret = arena->Malloc(allocSize, /* aZero = */ true);
4541 } else {
4542 ret = nullptr;
4544 } else {
4545 ret = nullptr;
4548 if (!ret) {
4549 errno = ENOMEM;
4552 return ret;
4555 inline void* BaseAllocator::realloc(void* aPtr, size_t aSize) {
4556 void* ret;
4558 if (aSize == 0) {
4559 aSize = 1;
4562 if (aPtr) {
4563 MOZ_RELEASE_ASSERT(malloc_initialized);
4565 auto info = AllocInfo::Get(aPtr);
4566 auto arena = info.Arena();
4567 MOZ_RELEASE_ASSERT(!mArena || arena == mArena);
4568 ret = arena->Ralloc(aPtr, aSize, info.Size());
4569 } else {
4570 if (!malloc_init()) {
4571 ret = nullptr;
4572 } else {
4573 arena_t* arena = mArena ? mArena : choose_arena(aSize);
4574 ret = arena->Malloc(aSize, /* aZero = */ false);
4578 if (!ret) {
4579 errno = ENOMEM;
4581 return ret;
4584 inline void BaseAllocator::free(void* aPtr) {
4585 size_t offset;
4587 // A version of idalloc that checks for nullptr pointer.
4588 offset = GetChunkOffsetForPtr(aPtr);
4589 if (offset != 0) {
4590 MOZ_RELEASE_ASSERT(malloc_initialized);
4591 arena_dalloc(aPtr, offset, mArena);
4592 } else if (aPtr) {
4593 MOZ_RELEASE_ASSERT(malloc_initialized);
4594 huge_dalloc(aPtr, mArena);
4598 template <void* (*memalign)(size_t, size_t)>
4599 struct AlignedAllocator {
4600 static inline int posix_memalign(void** aMemPtr, size_t aAlignment,
4601 size_t aSize) {
4602 void* result;
4604 // alignment must be a power of two and a multiple of sizeof(void*)
4605 if (((aAlignment - 1) & aAlignment) != 0 || aAlignment < sizeof(void*)) {
4606 return EINVAL;
4609 // The 0-->1 size promotion is done in the memalign() call below
4610 result = memalign(aAlignment, aSize);
4612 if (!result) {
4613 return ENOMEM;
4616 *aMemPtr = result;
4617 return 0;
4620 static inline void* aligned_alloc(size_t aAlignment, size_t aSize) {
4621 if (aSize % aAlignment) {
4622 return nullptr;
4624 return memalign(aAlignment, aSize);
4627 static inline void* valloc(size_t aSize) {
4628 return memalign(GetKernelPageSize(), aSize);
4632 template <>
4633 inline int MozJemalloc::posix_memalign(void** aMemPtr, size_t aAlignment,
4634 size_t aSize) {
4635 return AlignedAllocator<memalign>::posix_memalign(aMemPtr, aAlignment, aSize);
4638 template <>
4639 inline void* MozJemalloc::aligned_alloc(size_t aAlignment, size_t aSize) {
4640 return AlignedAllocator<memalign>::aligned_alloc(aAlignment, aSize);
4643 template <>
4644 inline void* MozJemalloc::valloc(size_t aSize) {
4645 return AlignedAllocator<memalign>::valloc(aSize);
4648 // End malloc(3)-compatible functions.
4649 // ***************************************************************************
4650 // Begin non-standard functions.
4652 // This was added by Mozilla for use by SQLite.
4653 template <>
4654 inline size_t MozJemalloc::malloc_good_size(size_t aSize) {
4655 if (aSize <= gMaxLargeClass) {
4656 // Small or large
4657 aSize = SizeClass(aSize).Size();
4658 } else {
4659 // Huge. We use PAGE_CEILING to get psize, instead of using
4660 // CHUNK_CEILING to get csize. This ensures that this
4661 // malloc_usable_size(malloc(n)) always matches
4662 // malloc_good_size(n).
4663 aSize = PAGE_CEILING(aSize);
4665 return aSize;
4668 template <>
4669 inline size_t MozJemalloc::malloc_usable_size(usable_ptr_t aPtr) {
4670 return AllocInfo::GetValidated(aPtr).Size();
4673 template <>
4674 inline void MozJemalloc::jemalloc_stats_internal(
4675 jemalloc_stats_t* aStats, jemalloc_bin_stats_t* aBinStats) {
4676 size_t non_arena_mapped, chunk_header_size;
4678 if (!aStats) {
4679 return;
4681 if (!malloc_init()) {
4682 memset(aStats, 0, sizeof(*aStats));
4683 return;
4685 if (aBinStats) {
4686 memset(aBinStats, 0, sizeof(jemalloc_bin_stats_t) * NUM_SMALL_CLASSES);
4689 // Gather runtime settings.
4690 aStats->opt_junk = opt_junk;
4691 aStats->opt_zero = opt_zero;
4692 aStats->quantum = kQuantum;
4693 aStats->quantum_max = kMaxQuantumClass;
4694 aStats->quantum_wide = kQuantumWide;
4695 aStats->quantum_wide_max = kMaxQuantumWideClass;
4696 aStats->subpage_max = gMaxSubPageClass;
4697 aStats->large_max = gMaxLargeClass;
4698 aStats->chunksize = kChunkSize;
4699 aStats->page_size = gPageSize;
4700 aStats->dirty_max = opt_dirty_max;
4702 // Gather current memory usage statistics.
4703 aStats->narenas = 0;
4704 aStats->mapped = 0;
4705 aStats->allocated = 0;
4706 aStats->waste = 0;
4707 aStats->page_cache = 0;
4708 aStats->bookkeeping = 0;
4709 aStats->bin_unused = 0;
4711 non_arena_mapped = 0;
4713 // Get huge mapped/allocated.
4715 MutexAutoLock lock(huge_mtx);
4716 non_arena_mapped += huge_mapped;
4717 aStats->allocated += huge_allocated;
4718 MOZ_ASSERT(huge_mapped >= huge_allocated);
4721 // Get base mapped/allocated.
4723 MutexAutoLock lock(base_mtx);
4724 non_arena_mapped += base_mapped;
4725 aStats->bookkeeping += base_committed;
4726 MOZ_ASSERT(base_mapped >= base_committed);
4729 gArenas.mLock.Lock();
4731 // Stats can only read complete information if its run on the main thread.
4732 MOZ_ASSERT(gArenas.IsOnMainThreadWeak());
4734 // Iterate over arenas.
4735 for (auto arena : gArenas.iter()) {
4736 // Cannot safely read stats for this arena and therefore stats would be
4737 // incomplete.
4738 MOZ_ASSERT(arena->mLock.SafeOnThisThread());
4740 size_t arena_mapped, arena_allocated, arena_committed, arena_dirty, j,
4741 arena_unused, arena_headers;
4743 arena_headers = 0;
4744 arena_unused = 0;
4747 MaybeMutexAutoLock lock(arena->mLock);
4749 arena_mapped = arena->mStats.mapped;
4751 // "committed" counts dirty and allocated memory.
4752 arena_committed = arena->mStats.committed << gPageSize2Pow;
4754 arena_allocated =
4755 arena->mStats.allocated_small + arena->mStats.allocated_large;
4757 arena_dirty = arena->mNumDirty << gPageSize2Pow;
4759 for (j = 0; j < NUM_SMALL_CLASSES; j++) {
4760 arena_bin_t* bin = &arena->mBins[j];
4761 size_t bin_unused = 0;
4762 size_t num_non_full_runs = 0;
4764 for (auto mapelm : bin->mNonFullRuns.iter()) {
4765 arena_run_t* run = (arena_run_t*)(mapelm->bits & ~gPageSizeMask);
4766 bin_unused += run->mNumFree * bin->mSizeClass;
4767 num_non_full_runs++;
4770 if (bin->mCurrentRun) {
4771 bin_unused += bin->mCurrentRun->mNumFree * bin->mSizeClass;
4772 num_non_full_runs++;
4775 arena_unused += bin_unused;
4776 arena_headers += bin->mNumRuns * bin->mRunFirstRegionOffset;
4777 if (aBinStats) {
4778 aBinStats[j].size = bin->mSizeClass;
4779 aBinStats[j].num_non_full_runs += num_non_full_runs;
4780 aBinStats[j].num_runs += bin->mNumRuns;
4781 aBinStats[j].bytes_unused += bin_unused;
4782 size_t bytes_per_run = static_cast<size_t>(bin->mRunSizePages)
4783 << gPageSize2Pow;
4784 aBinStats[j].bytes_total +=
4785 bin->mNumRuns * (bytes_per_run - bin->mRunFirstRegionOffset);
4786 aBinStats[j].bytes_per_run = bytes_per_run;
4791 MOZ_ASSERT(arena_mapped >= arena_committed);
4792 MOZ_ASSERT(arena_committed >= arena_allocated + arena_dirty);
4794 aStats->mapped += arena_mapped;
4795 aStats->allocated += arena_allocated;
4796 aStats->page_cache += arena_dirty;
4797 // "waste" is committed memory that is neither dirty nor
4798 // allocated. If you change this definition please update
4799 // memory/replace/logalloc/replay/Replay.cpp's jemalloc_stats calculation of
4800 // committed.
4801 aStats->waste += arena_committed - arena_allocated - arena_dirty -
4802 arena_unused - arena_headers;
4803 aStats->bin_unused += arena_unused;
4804 aStats->bookkeeping += arena_headers;
4805 aStats->narenas++;
4807 gArenas.mLock.Unlock();
4809 // Account for arena chunk headers in bookkeeping rather than waste.
4810 chunk_header_size =
4811 ((aStats->mapped / aStats->chunksize) * gChunkHeaderNumPages)
4812 << gPageSize2Pow;
4814 aStats->mapped += non_arena_mapped;
4815 aStats->bookkeeping += chunk_header_size;
4816 aStats->waste -= chunk_header_size;
4818 MOZ_ASSERT(aStats->mapped >= aStats->allocated + aStats->waste +
4819 aStats->page_cache + aStats->bookkeeping);
4822 template <>
4823 inline size_t MozJemalloc::jemalloc_stats_num_bins() {
4824 return NUM_SMALL_CLASSES;
4827 template <>
4828 inline void MozJemalloc::jemalloc_set_main_thread() {
4829 MOZ_ASSERT(malloc_initialized);
4830 gArenas.SetMainThread();
4833 #ifdef MALLOC_DOUBLE_PURGE
4835 // Explicitly remove all of this chunk's MADV_FREE'd pages from memory.
4836 static void hard_purge_chunk(arena_chunk_t* aChunk) {
4837 // See similar logic in arena_t::Purge().
4838 for (size_t i = gChunkHeaderNumPages; i < gChunkNumPages; i++) {
4839 // Find all adjacent pages with CHUNK_MAP_MADVISED set.
4840 size_t npages;
4841 for (npages = 0; aChunk->map[i + npages].bits & CHUNK_MAP_MADVISED &&
4842 i + npages < gChunkNumPages;
4843 npages++) {
4844 // Turn off the chunk's MADV_FREED bit and turn on its
4845 // DECOMMITTED bit.
4846 MOZ_DIAGNOSTIC_ASSERT(
4847 !(aChunk->map[i + npages].bits & CHUNK_MAP_DECOMMITTED));
4848 aChunk->map[i + npages].bits ^= CHUNK_MAP_MADVISED_OR_DECOMMITTED;
4851 // We could use mincore to find out which pages are actually
4852 // present, but it's not clear that's better.
4853 if (npages > 0) {
4854 pages_decommit(((char*)aChunk) + (i << gPageSize2Pow),
4855 npages << gPageSize2Pow);
4856 Unused << pages_commit(((char*)aChunk) + (i << gPageSize2Pow),
4857 npages << gPageSize2Pow);
4859 i += npages;
4863 // Explicitly remove all of this arena's MADV_FREE'd pages from memory.
4864 void arena_t::HardPurge() {
4865 MaybeMutexAutoLock lock(mLock);
4867 while (!mChunksMAdvised.isEmpty()) {
4868 arena_chunk_t* chunk = mChunksMAdvised.popFront();
4869 hard_purge_chunk(chunk);
4873 template <>
4874 inline void MozJemalloc::jemalloc_purge_freed_pages() {
4875 if (malloc_initialized) {
4876 MutexAutoLock lock(gArenas.mLock);
4877 MOZ_ASSERT(gArenas.IsOnMainThreadWeak());
4878 for (auto arena : gArenas.iter()) {
4879 arena->HardPurge();
4884 #else // !defined MALLOC_DOUBLE_PURGE
4886 template <>
4887 inline void MozJemalloc::jemalloc_purge_freed_pages() {
4888 // Do nothing.
4891 #endif // defined MALLOC_DOUBLE_PURGE
4893 template <>
4894 inline void MozJemalloc::jemalloc_free_dirty_pages(void) {
4895 if (malloc_initialized) {
4896 MutexAutoLock lock(gArenas.mLock);
4897 MOZ_ASSERT(gArenas.IsOnMainThreadWeak());
4898 for (auto arena : gArenas.iter()) {
4899 MaybeMutexAutoLock arena_lock(arena->mLock);
4900 arena->Purge(1);
4905 inline arena_t* ArenaCollection::GetByIdInternal(arena_id_t aArenaId,
4906 bool aIsPrivate) {
4907 // Use AlignedStorage2 to avoid running the arena_t constructor, while
4908 // we only need it as a placeholder for mId.
4909 mozilla::AlignedStorage2<arena_t> key;
4910 key.addr()->mId = aArenaId;
4911 return (aIsPrivate ? mPrivateArenas : mArenas).Search(key.addr());
4914 inline arena_t* ArenaCollection::GetById(arena_id_t aArenaId, bool aIsPrivate) {
4915 if (!malloc_initialized) {
4916 return nullptr;
4919 MutexAutoLock lock(mLock);
4920 arena_t* result = GetByIdInternal(aArenaId, aIsPrivate);
4921 MOZ_RELEASE_ASSERT(result);
4922 return result;
4925 template <>
4926 inline arena_id_t MozJemalloc::moz_create_arena_with_params(
4927 arena_params_t* aParams) {
4928 if (malloc_init()) {
4929 arena_t* arena = gArenas.CreateArena(/* IsPrivate = */ true, aParams);
4930 return arena->mId;
4932 return 0;
4935 template <>
4936 inline void MozJemalloc::moz_dispose_arena(arena_id_t aArenaId) {
4937 arena_t* arena = gArenas.GetById(aArenaId, /* IsPrivate = */ true);
4938 MOZ_RELEASE_ASSERT(arena);
4939 gArenas.DisposeArena(arena);
4942 template <>
4943 inline void MozJemalloc::moz_set_max_dirty_page_modifier(int32_t aModifier) {
4944 gArenas.SetDefaultMaxDirtyPageModifier(aModifier);
4947 #define MALLOC_DECL(name, return_type, ...) \
4948 template <> \
4949 inline return_type MozJemalloc::moz_arena_##name( \
4950 arena_id_t aArenaId, ARGS_HELPER(TYPED_ARGS, ##__VA_ARGS__)) { \
4951 BaseAllocator allocator( \
4952 gArenas.GetById(aArenaId, /* IsPrivate = */ true)); \
4953 return allocator.name(ARGS_HELPER(ARGS, ##__VA_ARGS__)); \
4955 #define MALLOC_FUNCS MALLOC_FUNCS_MALLOC_BASE
4956 #include "malloc_decls.h"
4958 // End non-standard functions.
4959 // ***************************************************************************
4960 #ifndef XP_WIN
4961 // Begin library-private functions, used by threading libraries for protection
4962 // of malloc during fork(). These functions are only called if the program is
4963 // running in threaded mode, so there is no need to check whether the program
4964 // is threaded here.
4966 // Note that the only way to keep the main-thread-only arenas in a consistent
4967 // state for the child is if fork is called from the main thread only. Or the
4968 // child must not use them, eg it should call exec(). We attempt to prevent the
4969 // child for accessing these arenas by refusing to re-initialise them.
4970 static pthread_t gForkingThread;
4972 FORK_HOOK
4973 void _malloc_prefork(void) MOZ_NO_THREAD_SAFETY_ANALYSIS {
4974 // Acquire all mutexes in a safe order.
4975 gArenas.mLock.Lock();
4976 gForkingThread = pthread_self();
4978 for (auto arena : gArenas.iter()) {
4979 if (arena->mLock.LockIsEnabled()) {
4980 arena->mLock.Lock();
4984 base_mtx.Lock();
4986 huge_mtx.Lock();
4989 FORK_HOOK
4990 void _malloc_postfork_parent(void) MOZ_NO_THREAD_SAFETY_ANALYSIS {
4991 // Release all mutexes, now that fork() has completed.
4992 huge_mtx.Unlock();
4994 base_mtx.Unlock();
4996 for (auto arena : gArenas.iter()) {
4997 if (arena->mLock.LockIsEnabled()) {
4998 arena->mLock.Unlock();
5002 gArenas.mLock.Unlock();
5005 FORK_HOOK
5006 void _malloc_postfork_child(void) {
5007 // Reinitialize all mutexes, now that fork() has completed.
5008 huge_mtx.Init();
5010 base_mtx.Init();
5012 for (auto arena : gArenas.iter()) {
5013 arena->mLock.Reinit(gForkingThread);
5016 gArenas.PostForkFixMainThread();
5017 gArenas.mLock.Init();
5019 #endif // XP_WIN
5021 // End library-private functions.
5022 // ***************************************************************************
5023 #ifdef MOZ_REPLACE_MALLOC
5024 // Windows doesn't come with weak imports as they are possible with
5025 // LD_PRELOAD or DYLD_INSERT_LIBRARIES on Linux/OSX. On this platform,
5026 // the replacement functions are defined as variable pointers to the
5027 // function resolved with GetProcAddress() instead of weak definitions
5028 // of functions. On Android, the same needs to happen as well, because
5029 // the Android linker doesn't handle weak linking with non LD_PRELOADed
5030 // libraries, but LD_PRELOADing is not very convenient on Android, with
5031 // the zygote.
5032 # ifdef XP_DARWIN
5033 # define MOZ_REPLACE_WEAK __attribute__((weak_import))
5034 # elif defined(XP_WIN) || defined(ANDROID)
5035 # define MOZ_DYNAMIC_REPLACE_INIT
5036 # define replace_init replace_init_decl
5037 # elif defined(__GNUC__)
5038 # define MOZ_REPLACE_WEAK __attribute__((weak))
5039 # endif
5041 # include "replace_malloc.h"
5043 # define MALLOC_DECL(name, return_type, ...) MozJemalloc::name,
5045 // The default malloc table, i.e. plain allocations. It never changes. It's
5046 // used by init(), and not used after that.
5047 static const malloc_table_t gDefaultMallocTable = {
5048 # include "malloc_decls.h"
5051 // The malloc table installed by init(). It never changes from that point
5052 // onward. It will be the same as gDefaultMallocTable if no replace-malloc tool
5053 // is enabled at startup.
5054 static malloc_table_t gOriginalMallocTable = {
5055 # include "malloc_decls.h"
5058 // The malloc table installed by jemalloc_replace_dynamic(). (Read the
5059 // comments above that function for more details.)
5060 static malloc_table_t gDynamicMallocTable = {
5061 # include "malloc_decls.h"
5064 // This briefly points to gDefaultMallocTable at startup. After that, it points
5065 // to either gOriginalMallocTable or gDynamicMallocTable. It's atomic to avoid
5066 // races when switching between tables.
5067 static Atomic<malloc_table_t const*, mozilla::MemoryOrdering::Relaxed>
5068 gMallocTablePtr;
5070 # ifdef MOZ_DYNAMIC_REPLACE_INIT
5071 # undef replace_init
5072 typedef decltype(replace_init_decl) replace_init_impl_t;
5073 static replace_init_impl_t* replace_init = nullptr;
5074 # endif
5076 # ifdef XP_WIN
5077 typedef HMODULE replace_malloc_handle_t;
5079 static replace_malloc_handle_t replace_malloc_handle() {
5080 wchar_t replace_malloc_lib[1024];
5081 if (GetEnvironmentVariableW(L"MOZ_REPLACE_MALLOC_LIB", replace_malloc_lib,
5082 ArrayLength(replace_malloc_lib)) > 0) {
5083 return LoadLibraryW(replace_malloc_lib);
5085 return nullptr;
5088 # define REPLACE_MALLOC_GET_INIT_FUNC(handle) \
5089 (replace_init_impl_t*)GetProcAddress(handle, "replace_init")
5091 # elif defined(ANDROID)
5092 # include <dlfcn.h>
5094 typedef void* replace_malloc_handle_t;
5096 static replace_malloc_handle_t replace_malloc_handle() {
5097 const char* replace_malloc_lib = getenv("MOZ_REPLACE_MALLOC_LIB");
5098 if (replace_malloc_lib && *replace_malloc_lib) {
5099 return dlopen(replace_malloc_lib, RTLD_LAZY);
5101 return nullptr;
5104 # define REPLACE_MALLOC_GET_INIT_FUNC(handle) \
5105 (replace_init_impl_t*)dlsym(handle, "replace_init")
5107 # endif
5109 static void replace_malloc_init_funcs(malloc_table_t*);
5111 # ifdef MOZ_REPLACE_MALLOC_STATIC
5112 extern "C" void logalloc_init(malloc_table_t*, ReplaceMallocBridge**);
5114 extern "C" void dmd_init(malloc_table_t*, ReplaceMallocBridge**);
5116 extern "C" void phc_init(malloc_table_t*, ReplaceMallocBridge**);
5117 # endif
5119 bool Equals(const malloc_table_t& aTable1, const malloc_table_t& aTable2) {
5120 return memcmp(&aTable1, &aTable2, sizeof(malloc_table_t)) == 0;
5123 // Below is the malloc implementation overriding jemalloc and calling the
5124 // replacement functions if they exist.
5125 static ReplaceMallocBridge* gReplaceMallocBridge = nullptr;
5126 static void init() {
5127 malloc_table_t tempTable = gDefaultMallocTable;
5129 # ifdef MOZ_DYNAMIC_REPLACE_INIT
5130 replace_malloc_handle_t handle = replace_malloc_handle();
5131 if (handle) {
5132 replace_init = REPLACE_MALLOC_GET_INIT_FUNC(handle);
5134 # endif
5136 // Set this *before* calling replace_init, otherwise if replace_init calls
5137 // malloc() we'll get an infinite loop.
5138 gMallocTablePtr = &gDefaultMallocTable;
5140 // Pass in the default allocator table so replace functions can copy and use
5141 // it for their allocations. The replace_init() function should modify the
5142 // table if it wants to be active, otherwise leave it unmodified.
5143 if (replace_init) {
5144 replace_init(&tempTable, &gReplaceMallocBridge);
5146 # ifdef MOZ_REPLACE_MALLOC_STATIC
5147 if (Equals(tempTable, gDefaultMallocTable)) {
5148 logalloc_init(&tempTable, &gReplaceMallocBridge);
5150 # ifdef MOZ_DMD
5151 if (Equals(tempTable, gDefaultMallocTable)) {
5152 dmd_init(&tempTable, &gReplaceMallocBridge);
5154 # endif
5155 # ifdef MOZ_PHC
5156 if (Equals(tempTable, gDefaultMallocTable)) {
5157 phc_init(&tempTable, &gReplaceMallocBridge);
5159 # endif
5160 # endif
5161 if (!Equals(tempTable, gDefaultMallocTable)) {
5162 replace_malloc_init_funcs(&tempTable);
5164 gOriginalMallocTable = tempTable;
5165 gMallocTablePtr = &gOriginalMallocTable;
5168 // WARNING WARNING WARNING: this function should be used with extreme care. It
5169 // is not as general-purpose as it looks. It is currently used by
5170 // tools/profiler/core/memory_hooks.cpp for counting allocations and probably
5171 // should not be used for any other purpose.
5173 // This function allows the original malloc table to be temporarily replaced by
5174 // a different malloc table. Or, if the argument is nullptr, it switches back to
5175 // the original malloc table.
5177 // Limitations:
5179 // - It is not threadsafe. If multiple threads pass it the same
5180 // `replace_init_func` at the same time, there will be data races writing to
5181 // the malloc_table_t within that function.
5183 // - Only one replacement can be installed. No nesting is allowed.
5185 // - The new malloc table must be able to free allocations made by the original
5186 // malloc table, and upon removal the original malloc table must be able to
5187 // free allocations made by the new malloc table. This means the new malloc
5188 // table can only do simple things like recording extra information, while
5189 // delegating actual allocation/free operations to the original malloc table.
5191 MOZ_JEMALLOC_API void jemalloc_replace_dynamic(
5192 jemalloc_init_func replace_init_func) {
5193 if (replace_init_func) {
5194 malloc_table_t tempTable = gOriginalMallocTable;
5195 (*replace_init_func)(&tempTable, &gReplaceMallocBridge);
5196 if (!Equals(tempTable, gOriginalMallocTable)) {
5197 replace_malloc_init_funcs(&tempTable);
5199 // Temporarily switch back to the original malloc table. In the
5200 // (supported) non-nested case, this is a no-op. But just in case this is
5201 // a (unsupported) nested call, it makes the overwriting of
5202 // gDynamicMallocTable less racy, because ongoing calls to malloc() and
5203 // friends won't go through gDynamicMallocTable.
5204 gMallocTablePtr = &gOriginalMallocTable;
5206 gDynamicMallocTable = tempTable;
5207 gMallocTablePtr = &gDynamicMallocTable;
5208 // We assume that dynamic replaces don't occur close enough for a
5209 // thread to still have old copies of the table pointer when the 2nd
5210 // replace occurs.
5212 } else {
5213 // Switch back to the original malloc table.
5214 gMallocTablePtr = &gOriginalMallocTable;
5218 # define MALLOC_DECL(name, return_type, ...) \
5219 template <> \
5220 inline return_type ReplaceMalloc::name( \
5221 ARGS_HELPER(TYPED_ARGS, ##__VA_ARGS__)) { \
5222 if (MOZ_UNLIKELY(!gMallocTablePtr)) { \
5223 init(); \
5225 return (*gMallocTablePtr).name(ARGS_HELPER(ARGS, ##__VA_ARGS__)); \
5227 # include "malloc_decls.h"
5229 MOZ_JEMALLOC_API struct ReplaceMallocBridge* get_bridge(void) {
5230 if (MOZ_UNLIKELY(!gMallocTablePtr)) {
5231 init();
5233 return gReplaceMallocBridge;
5236 // posix_memalign, aligned_alloc, memalign and valloc all implement some kind
5237 // of aligned memory allocation. For convenience, a replace-malloc library can
5238 // skip defining replace_posix_memalign, replace_aligned_alloc and
5239 // replace_valloc, and default implementations will be automatically derived
5240 // from replace_memalign.
5241 static void replace_malloc_init_funcs(malloc_table_t* table) {
5242 if (table->posix_memalign == MozJemalloc::posix_memalign &&
5243 table->memalign != MozJemalloc::memalign) {
5244 table->posix_memalign =
5245 AlignedAllocator<ReplaceMalloc::memalign>::posix_memalign;
5247 if (table->aligned_alloc == MozJemalloc::aligned_alloc &&
5248 table->memalign != MozJemalloc::memalign) {
5249 table->aligned_alloc =
5250 AlignedAllocator<ReplaceMalloc::memalign>::aligned_alloc;
5252 if (table->valloc == MozJemalloc::valloc &&
5253 table->memalign != MozJemalloc::memalign) {
5254 table->valloc = AlignedAllocator<ReplaceMalloc::memalign>::valloc;
5256 if (table->moz_create_arena_with_params ==
5257 MozJemalloc::moz_create_arena_with_params &&
5258 table->malloc != MozJemalloc::malloc) {
5259 # define MALLOC_DECL(name, ...) \
5260 table->name = DummyArenaAllocator<ReplaceMalloc>::name;
5261 # define MALLOC_FUNCS MALLOC_FUNCS_ARENA_BASE
5262 # include "malloc_decls.h"
5264 if (table->moz_arena_malloc == MozJemalloc::moz_arena_malloc &&
5265 table->malloc != MozJemalloc::malloc) {
5266 # define MALLOC_DECL(name, ...) \
5267 table->name = DummyArenaAllocator<ReplaceMalloc>::name;
5268 # define MALLOC_FUNCS MALLOC_FUNCS_ARENA_ALLOC
5269 # include "malloc_decls.h"
5273 #endif // MOZ_REPLACE_MALLOC
5274 // ***************************************************************************
5275 // Definition of all the _impl functions
5276 // GENERIC_MALLOC_DECL2_MINGW is only used for the MinGW build, and aliases
5277 // the malloc funcs (e.g. malloc) to the je_ versions. It does not generate
5278 // aliases for the other functions (jemalloc and arena functions).
5280 // We do need aliases for the other mozglue.def-redirected functions though,
5281 // these are done at the bottom of mozmemory_wrap.cpp
5282 #define GENERIC_MALLOC_DECL2_MINGW(name, name_impl, return_type, ...) \
5283 return_type name(ARGS_HELPER(TYPED_ARGS, ##__VA_ARGS__)) \
5284 __attribute__((alias(MOZ_STRINGIFY(name_impl))));
5286 #define GENERIC_MALLOC_DECL2(attributes, name, name_impl, return_type, ...) \
5287 return_type name_impl(ARGS_HELPER(TYPED_ARGS, ##__VA_ARGS__)) attributes { \
5288 return DefaultMalloc::name(ARGS_HELPER(ARGS, ##__VA_ARGS__)); \
5291 #ifndef __MINGW32__
5292 # define GENERIC_MALLOC_DECL(attributes, name, return_type, ...) \
5293 GENERIC_MALLOC_DECL2(attributes, name, name##_impl, return_type, \
5294 ##__VA_ARGS__)
5295 #else
5296 # define GENERIC_MALLOC_DECL(attributes, name, return_type, ...) \
5297 GENERIC_MALLOC_DECL2(attributes, name, name##_impl, return_type, \
5298 ##__VA_ARGS__) \
5299 GENERIC_MALLOC_DECL2_MINGW(name, name##_impl, return_type, ##__VA_ARGS__)
5300 #endif
5302 #define NOTHROW_MALLOC_DECL(...) \
5303 MOZ_MEMORY_API MACRO_CALL(GENERIC_MALLOC_DECL, (noexcept(true), __VA_ARGS__))
5304 #define MALLOC_DECL(...) \
5305 MOZ_MEMORY_API MACRO_CALL(GENERIC_MALLOC_DECL, (, __VA_ARGS__))
5306 #define MALLOC_FUNCS MALLOC_FUNCS_MALLOC
5307 #include "malloc_decls.h"
5309 #undef GENERIC_MALLOC_DECL
5310 #define GENERIC_MALLOC_DECL(attributes, name, return_type, ...) \
5311 GENERIC_MALLOC_DECL2(attributes, name, name, return_type, ##__VA_ARGS__)
5313 #define MALLOC_DECL(...) \
5314 MOZ_JEMALLOC_API MACRO_CALL(GENERIC_MALLOC_DECL, (, __VA_ARGS__))
5315 #define MALLOC_FUNCS (MALLOC_FUNCS_JEMALLOC | MALLOC_FUNCS_ARENA)
5316 #include "malloc_decls.h"
5317 // ***************************************************************************
5319 #ifdef HAVE_DLOPEN
5320 # include <dlfcn.h>
5321 #endif
5323 #if defined(__GLIBC__) && !defined(__UCLIBC__)
5324 // glibc provides the RTLD_DEEPBIND flag for dlopen which can make it possible
5325 // to inconsistently reference libc's malloc(3)-compatible functions
5326 // (bug 493541).
5328 // These definitions interpose hooks in glibc. The functions are actually
5329 // passed an extra argument for the caller return address, which will be
5330 // ignored.
5332 extern "C" {
5333 MOZ_EXPORT void (*__free_hook)(void*) = free_impl;
5334 MOZ_EXPORT void* (*__malloc_hook)(size_t) = malloc_impl;
5335 MOZ_EXPORT void* (*__realloc_hook)(void*, size_t) = realloc_impl;
5336 MOZ_EXPORT void* (*__memalign_hook)(size_t, size_t) = memalign_impl;
5339 #elif defined(RTLD_DEEPBIND)
5340 // XXX On systems that support RTLD_GROUP or DF_1_GROUP, do their
5341 // implementations permit similar inconsistencies? Should STV_SINGLETON
5342 // visibility be used for interposition where available?
5343 # error \
5344 "Interposing malloc is unsafe on this system without libc malloc hooks."
5345 #endif
5347 #ifdef XP_WIN
5348 MOZ_EXPORT void* _recalloc(void* aPtr, size_t aCount, size_t aSize) {
5349 size_t oldsize = aPtr ? AllocInfo::Get(aPtr).Size() : 0;
5350 CheckedInt<size_t> checkedSize = CheckedInt<size_t>(aCount) * aSize;
5352 if (!checkedSize.isValid()) {
5353 return nullptr;
5356 size_t newsize = checkedSize.value();
5358 // In order for all trailing bytes to be zeroed, the caller needs to
5359 // use calloc(), followed by recalloc(). However, the current calloc()
5360 // implementation only zeros the bytes requested, so if recalloc() is
5361 // to work 100% correctly, calloc() will need to change to zero
5362 // trailing bytes.
5363 aPtr = DefaultMalloc::realloc(aPtr, newsize);
5364 if (aPtr && oldsize < newsize) {
5365 memset((void*)((uintptr_t)aPtr + oldsize), 0, newsize - oldsize);
5368 return aPtr;
5371 // This impl of _expand doesn't ever actually expand or shrink blocks: it
5372 // simply replies that you may continue using a shrunk block.
5373 MOZ_EXPORT void* _expand(void* aPtr, size_t newsize) {
5374 if (AllocInfo::Get(aPtr).Size() >= newsize) {
5375 return aPtr;
5378 return nullptr;
5381 MOZ_EXPORT size_t _msize(void* aPtr) {
5382 return DefaultMalloc::malloc_usable_size(aPtr);
5384 #endif