Debian Codegraph @

memory/build/mozjemalloc.cpp

raw
1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* vim: set ts=8 sts=2 et sw=2 tw=80: */
3 /* This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6
7 // Portions of this file were originally under the following license:
8 //
9 // Copyright (C) 2006-2008 Jason Evans <[email protected]>.
10 // All rights reserved.
11 // Copyright (C) 2007-2017 Mozilla Foundation.
12 //
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.
24 //
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.
36 //
37 // *****************************************************************************
38 //
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:
42 //
43 // + Multiple arenas are used if there are multiple CPUs, which reduces lock
44 // contention and cache sloshing.
45 //
46 // + Cache line sharing between arenas is avoided for internal data
47 // structures.
48 //
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.
52 //
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):
57 //
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 // |=========================================================|
100 //
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.
106 //
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.
110 //
111 // A different mechanism is used for each category:
112 //
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.
115 //
116 // Large : Each allocation is backed by a dedicated run. Metadata are stored
117 // in the associated arena chunk header maps.
118 //
119 // Huge : Each allocation is backed by a dedicated contiguous set of chunks.
120 // Metadata are stored in a separate red-black tree.
121 //
122 // *****************************************************************************
123
124 #include "mozmemory_wrap.h"
125 #include "mozjemalloc.h"
126 #include "mozjemalloc_types.h"
127
128 #include <cstring>
129 #include <cerrno>
130 #include <chrono>
131 #include <optional>
132 #include <type_traits>
133 #ifdef XP_WIN
134 # include <io.h>
135 # include <windows.h>
136 #else
137 # include <sys/mman.h>
138 # include <unistd.h>
139 #endif
140 #ifdef XP_DARWIN
141 # include <libkern/OSAtomic.h>
142 # include <mach/mach_init.h>
143 # include <mach/vm_map.h>
144 #endif
145
146 #include "mozilla/Atomics.h"
147 #include "mozilla/Alignment.h"
148 #include "mozilla/ArrayUtils.h"
149 #include "mozilla/Assertions.h"
150 #include "mozilla/CheckedInt.h"
151 #include "mozilla/DebugOnly.h"
152 #include "mozilla/DoublyLinkedList.h"
153 #include "mozilla/HelperMacros.h"
154 #include "mozilla/Likely.h"
155 #include "mozilla/Literals.h"
156 #include "mozilla/MathAlgorithms.h"
157 #include "mozilla/RandomNum.h"
158 // Note: MozTaggedAnonymousMmap() could call an LD_PRELOADed mmap
159 // instead of the one defined here; use only MozTagAnonymousMemory().
160 #include "mozilla/TaggedAnonymousMemory.h"
161 #include "mozilla/ThreadLocal.h"
162 #include "mozilla/UniquePtr.h"
163 #include "mozilla/Unused.h"
164 #include "mozilla/XorShift128PlusRNG.h"
165 #include "mozilla/fallible.h"
166 #include "rb.h"
167 #include "Mutex.h"
168 #include "PHC.h"
169 #include "Utils.h"
170
171 #if defined(XP_WIN)
172 # include "mozmemory_utils.h"
173 #endif
174
175 // For GetGeckoProcessType(), when it's used.
176 #if defined(XP_WIN) && !defined(JS_STANDALONE)
177 # include "mozilla/ProcessType.h"
178 #endif
179
180 using namespace mozilla;
181
182 // On Linux, we use madvise(MADV_DONTNEED) to release memory back to the
183 // operating system. If we release 1MB of live pages with MADV_DONTNEED, our
184 // RSS will decrease by 1MB (almost) immediately.
185 //
186 // On Mac, we use madvise(MADV_FREE). Unlike MADV_DONTNEED on Linux, MADV_FREE
187 // on Mac doesn't cause the OS to release the specified pages immediately; the
188 // OS keeps them in our process until the machine comes under memory pressure.
189 //
190 // It's therefore difficult to measure the process's RSS on Mac, since, in the
191 // absence of memory pressure, the contribution from the heap to RSS will not
192 // decrease due to our madvise calls.
193 //
194 // We therefore define MALLOC_DOUBLE_PURGE on Mac. This causes jemalloc to
195 // track which pages have been MADV_FREE'd. You can then call
196 // jemalloc_purge_freed_pages(), which will force the OS to release those
197 // MADV_FREE'd pages, making the process's RSS reflect its true memory usage.
198
199 #ifdef XP_DARWIN
200 # define MALLOC_DOUBLE_PURGE
201 #endif
202
203 #ifdef XP_WIN
204 # define MALLOC_DECOMMIT
205 #endif
206
207 // Define MALLOC_RUNTIME_CONFIG depending on MOZ_DEBUG. Overriding this as
208 // a build option allows us to build mozjemalloc/firefox without runtime asserts
209 // but with runtime configuration. Making some testing easier.
210
211 #ifdef MOZ_DEBUG
212 # define MALLOC_RUNTIME_CONFIG
213 #endif
214
215 // Uncomment this to enable extra-vigilant assertions. These assertions may run
216 // more expensive checks that are sometimes too slow for regular debug mode.
217 // #define MALLOC_DEBUG_VIGILANT
218
219 // When MALLOC_STATIC_PAGESIZE is defined, the page size is fixed at
220 // compile-time for better performance, as opposed to determined at
221 // runtime. Some platforms can have different page sizes at runtime
222 // depending on kernel configuration, so they are opted out by default.
223 // Debug builds are opted out too, for test coverage.
224 #ifndef MALLOC_RUNTIME_CONFIG
225 # if !defined(__ia64__) && !defined(__sparc__) && !defined(__mips__) && \
226 !defined(__aarch64__) && !defined(__powerpc__) && !defined(XP_MACOSX) && \
227 !defined(__loongarch__)
228 # define MALLOC_STATIC_PAGESIZE 1
229 # endif
230 #endif
231
232 #ifdef XP_WIN
233 # define STDERR_FILENO 2
234
235 // Implement getenv without using malloc.
236 static char mozillaMallocOptionsBuf[64];
237
238 # define getenv xgetenv
239 static char* getenv(const char* name) {
240 if (GetEnvironmentVariableA(name, mozillaMallocOptionsBuf,
241 sizeof(mozillaMallocOptionsBuf)) > 0) {
242 return mozillaMallocOptionsBuf;
243 }
244
245 return nullptr;
246 }
247 #endif
248
249 #ifndef XP_WIN
250 // Newer Linux systems support MADV_FREE, but we're not supporting
251 // that properly. bug #1406304.
252 # if defined(XP_LINUX) && defined(MADV_FREE)
253 # undef MADV_FREE
254 # endif
255 # ifndef MADV_FREE
256 # define MADV_FREE MADV_DONTNEED
257 # endif
258 #endif
259
260 // Some tools, such as /dev/dsp wrappers, LD_PRELOAD libraries that
261 // happen to override mmap() and call dlsym() from their overridden
262 // mmap(). The problem is that dlsym() calls malloc(), and this ends
263 // up in a dead lock in jemalloc.
264 // On these systems, we prefer to directly use the system call.
265 // We do that for Linux systems and kfreebsd with GNU userland.
266 // Note sanity checks are not done (alignment of offset, ...) because
267 // the uses of mmap are pretty limited, in jemalloc.
268 //
269 // On Alpha, glibc has a bug that prevents syscall() to work for system
270 // calls with 6 arguments.
271 #if (defined(XP_LINUX) && !defined(__alpha__)) || \
272 (defined(__FreeBSD_kernel__) && defined(__GLIBC__))
273 # include <sys/syscall.h>
274 # if defined(SYS_mmap) || defined(SYS_mmap2)
275 static inline void* _mmap(void* addr, size_t length, int prot, int flags,
276 int fd, off_t offset) {
277 // S390 only passes one argument to the mmap system call, which is a
278 // pointer to a structure containing the arguments.
279 # ifdef __s390__
280 struct {
281 void* addr;
282 size_t length;
283 long prot;
284 long flags;
285 long fd;
286 off_t offset;
287 } args = {addr, length, prot, flags, fd, offset};
288 return (void*)syscall(SYS_mmap, &args);
289 # else
290 # if defined(ANDROID) && defined(__aarch64__) && defined(SYS_mmap2)
291 // Android NDK defines SYS_mmap2 for AArch64 despite it not supporting mmap2.
292 # undef SYS_mmap2
293 # endif
294 # ifdef SYS_mmap2
295 return (void*)syscall(SYS_mmap2, addr, length, prot, flags, fd, offset >> 12);
296 # else
297 return (void*)syscall(SYS_mmap, addr, length, prot, flags, fd, offset);
298 # endif
299 # endif
300 }
301 # define mmap _mmap
302 # define munmap(a, l) syscall(SYS_munmap, a, l)
303 # endif
304 #endif
305
306 // ***************************************************************************
307 // Structures for chunk headers for chunks used for non-huge allocations.
308
309 struct arena_t;
310
311 // Each element of the chunk map corresponds to one page within the chunk.
312 struct arena_chunk_map_t {
313 // Linkage for run trees. Used for arena_t's tree or available runs.
314 RedBlackTreeNode<arena_chunk_map_t> link;
315
316 // Run address (or size) and various flags are stored together. The bit
317 // layout looks like (assuming 32-bit system):
318 //
319 // ???????? ???????? ????---b fmckdzla
320 //
321 // ? : Unallocated: Run address for first/last pages, unset for internal
322 // pages.
323 // Small: Run address.
324 // Large: Run size for first page, unset for trailing pages.
325 // - : Unused.
326 // b : Busy?
327 // f : Fresh memory?
328 // m : MADV_FREE/MADV_DONTNEED'ed?
329 // c : decommitted?
330 // k : key?
331 // d : dirty?
332 // z : zeroed?
333 // l : large?
334 // a : allocated?
335 //
336 // Following are example bit patterns for consecutive pages from the three
337 // types of runs.
338 //
339 // r : run address
340 // s : run size
341 // x : don't care
342 // - : 0
343 // [cdzla] : bit set
344 //
345 // Unallocated:
346 // ssssssss ssssssss ssss---- --c-----
347 // xxxxxxxx xxxxxxxx xxxx---- ----d---
348 // ssssssss ssssssss ssss---- -----z--
349 //
350 // Note that the size fields are set for the first and last unallocated
351 // page only. The pages in-between have invalid/"don't care" size fields,
352 // they're not cleared during things such as coalescing free runs.
353 //
354 // Pages before the first or after the last page in a free run must be
355 // allocated or busy. Run coalescing depends on the sizes being set in
356 // the first and last page. Purging pages and releasing chunks require
357 // that unallocated pages are always coalesced and the first page has a
358 // correct size.
359 //
360 // Small:
361 // rrrrrrrr rrrrrrrr rrrr---- -------a
362 // rrrrrrrr rrrrrrrr rrrr---- -------a
363 // rrrrrrrr rrrrrrrr rrrr---- -------a
364 //
365 // Large:
366 // ssssssss ssssssss ssss---- ------la
367 // -------- -------- -------- ------la
368 // -------- -------- -------- ------la
369 //
370 // Note that only the first page has the size set.
371 //
372 size_t bits;
373
374 // A page can be in one of several states.
375 //
376 // CHUNK_MAP_ALLOCATED marks allocated pages, the only other bit that can be
377 // combined is CHUNK_MAP_LARGE.
378 //
379 // CHUNK_MAP_LARGE may be combined with CHUNK_MAP_ALLOCATED to show that the
380 // allocation is a "large" allocation (see SizeClass), rather than a run of
381 // small allocations. The interpretation of the gPageSizeMask bits depends onj
382 // this bit, see the description above.
383 //
384 // CHUNK_MAP_DIRTY is used to mark pages that were allocated and are now freed.
385 // They may contain their previous contents (or poison). CHUNK_MAP_DIRTY, when
386 // set, must be the only set bit.
387 //
388 // CHUNK_MAP_MADVISED marks pages which are madvised (with either MADV_DONTNEED
389 // or MADV_FREE). This is only valid if MALLOC_DECOMMIT is not defined. When
390 // set, it must be the only bit set.
391 //
392 // CHUNK_MAP_DECOMMITTED is used if CHUNK_MAP_DECOMMITTED is defined. Unused
393 // dirty pages may be decommitted and marked as CHUNK_MAP_DECOMMITTED. They
394 // must be re-committed with pages_commit() before they can be touched.
395 //
396 // CHUNK_MAP_FRESH is set on pages that have never been used before (the chunk
397 // is newly allocated or they were decommitted and have now been recommitted.
398 // CHUNK_MAP_FRESH is also used for "double purged" pages meaning that they were
399 // madvised and later were unmapped and remapped to force them out of the
400 // program's resident set. This is enabled when MALLOC_DOUBLE_PURGE is defined
401 // (eg on MacOS).
402 //
403 // CHUNK_MAP_BUSY is set by a thread when the thread wants to manipulate the
404 // pages without holding a lock. Other threads must not touch these pages
405 // regardless of whether they hold a lock.
406 //
407 // CHUNK_MAP_ZEROED is set on pages that are known to contain zeros.
408 //
409 // CHUNK_MAP_DIRTY, _DECOMMITED _MADVISED and _FRESH are always mutually
410 // exclusive.
411 //
412 // CHUNK_MAP_KEY is never used on real pages, only on lookup keys.
413 //
414 #define CHUNK_MAP_BUSY ((size_t)0x100U)
415 #define CHUNK_MAP_FRESH ((size_t)0x80U)
416 #define CHUNK_MAP_MADVISED ((size_t)0x40U)
417 #define CHUNK_MAP_DECOMMITTED ((size_t)0x20U)
418 #define CHUNK_MAP_MADVISED_OR_DECOMMITTED \
419 (CHUNK_MAP_MADVISED | CHUNK_MAP_DECOMMITTED)
420 #define CHUNK_MAP_FRESH_MADVISED_OR_DECOMMITTED \
421 (CHUNK_MAP_FRESH | CHUNK_MAP_MADVISED | CHUNK_MAP_DECOMMITTED)
422 #define CHUNK_MAP_FRESH_MADVISED_DECOMMITTED_OR_BUSY \
423 (CHUNK_MAP_FRESH | CHUNK_MAP_MADVISED | CHUNK_MAP_DECOMMITTED | \
424 CHUNK_MAP_BUSY)
425 #define CHUNK_MAP_KEY ((size_t)0x10U)
426 #define CHUNK_MAP_DIRTY ((size_t)0x08U)
427 #define CHUNK_MAP_ZEROED ((size_t)0x04U)
428 #define CHUNK_MAP_LARGE ((size_t)0x02U)
429 #define CHUNK_MAP_ALLOCATED ((size_t)0x01U)
430 };
431
432 // Arena chunk header.
433 struct arena_chunk_t {
434 // Arena that owns the chunk.
435 arena_t* arena;
436
437 // Linkage for the arena's tree of dirty chunks.
438 RedBlackTreeNode<arena_chunk_t> link_dirty;
439
440 #ifdef MALLOC_DOUBLE_PURGE
441 // If we're double-purging, we maintain a linked list of chunks which
442 // have pages which have been madvise(MADV_FREE)'d but not explicitly
443 // purged.
444 //
445 // We're currently lazy and don't remove a chunk from this list when
446 // all its madvised pages are recommitted.
447 DoublyLinkedListElement<arena_chunk_t> chunks_madvised_elem;
448 #endif
449
450 // Number of dirty pages.
451 size_t ndirty;
452
453 bool mIsPurging;
454 bool mDying;
455
456 // Map of pages within chunk that keeps track of free/large/small.
457 arena_chunk_map_t map[]; // Dynamically sized.
458
459 bool IsEmpty();
460 };
461
462 // ***************************************************************************
463 // Constants defining allocator size classes and behavior.
464
465 // Our size classes are inclusive ranges of memory sizes. By describing the
466 // minimums and how memory is allocated in each range the maximums can be
467 // calculated.
468
469 // Smallest size class to support. On Windows the smallest allocation size
470 // must be 8 bytes on 32-bit, 16 bytes on 64-bit. On Linux and Mac, even
471 // malloc(1) must reserve a word's worth of memory (see Mozilla bug 691003).
472 #ifdef XP_WIN
473 static const size_t kMinTinyClass = sizeof(void*) * 2;
474 #else
475 static const size_t kMinTinyClass = sizeof(void*);
476 #endif
477
478 // Maximum tiny size class.
479 static const size_t kMaxTinyClass = 8;
480
481 // Smallest quantum-spaced size classes. It could actually also be labelled a
482 // tiny allocation, and is spaced as such from the largest tiny size class.
483 // Tiny classes being powers of 2, this is twice as large as the largest of
484 // them.
485 static const size_t kMinQuantumClass = kMaxTinyClass * 2;
486 static const size_t kMinQuantumWideClass = 512;
487 static const size_t kMinSubPageClass = 4_KiB;
488
489 // Amount (quantum) separating quantum-spaced size classes.
490 static const size_t kQuantum = 16;
491 static const size_t kQuantumMask = kQuantum - 1;
492 static const size_t kQuantumWide = 256;
493 static const size_t kQuantumWideMask = kQuantumWide - 1;
494
495 static const size_t kMaxQuantumClass = kMinQuantumWideClass - kQuantum;
496 static const size_t kMaxQuantumWideClass = kMinSubPageClass - kQuantumWide;
497
498 // We can optimise some divisions to shifts if these are powers of two.
499 static_assert(mozilla::IsPowerOfTwo(kQuantum),
500 "kQuantum is not a power of two");
501 static_assert(mozilla::IsPowerOfTwo(kQuantumWide),
502 "kQuantumWide is not a power of two");
503
504 static_assert(kMaxQuantumClass % kQuantum == 0,
505 "kMaxQuantumClass is not a multiple of kQuantum");
506 static_assert(kMaxQuantumWideClass % kQuantumWide == 0,
507 "kMaxQuantumWideClass is not a multiple of kQuantumWide");
508 static_assert(kQuantum < kQuantumWide,
509 "kQuantum must be smaller than kQuantumWide");
510 static_assert(mozilla::IsPowerOfTwo(kMinSubPageClass),
511 "kMinSubPageClass is not a power of two");
512
513 // Number of (2^n)-spaced tiny classes.
514 static const size_t kNumTinyClasses =
515 LOG2(kMaxTinyClass) - LOG2(kMinTinyClass) + 1;
516
517 // Number of quantum-spaced classes. We add kQuantum(Max) before subtracting to
518 // avoid underflow when a class is empty (Max<Min).
519 static const size_t kNumQuantumClasses =
520 (kMaxQuantumClass + kQuantum - kMinQuantumClass) / kQuantum;
521 static const size_t kNumQuantumWideClasses =
522 (kMaxQuantumWideClass + kQuantumWide - kMinQuantumWideClass) / kQuantumWide;
523
524 // Size and alignment of memory chunks that are allocated by the OS's virtual
525 // memory system.
526 static const size_t kChunkSize = 1_MiB;
527 static const size_t kChunkSizeMask = kChunkSize - 1;
528
529 #ifdef MALLOC_STATIC_PAGESIZE
530 // VM page size. It must divide the runtime CPU page size or the code
531 // will abort.
532 // Platform specific page size conditions copied from js/public/HeapAPI.h
533 # if defined(__powerpc64__)
534 static const size_t gPageSize = 64_KiB;
535 # elif defined(__loongarch64)
536 static const size_t gPageSize = 16_KiB;
537 # else
538 static const size_t gPageSize = 4_KiB;
539 # endif
540 static const size_t gRealPageSize = gPageSize;
541
542 #else
543 // When MALLOC_OPTIONS contains one or several `P`s, the page size used
544 // across the allocator is multiplied by 2 for each `P`, but we also keep
545 // the real page size for code paths that need it. gPageSize is thus a
546 // power of two greater or equal to gRealPageSize.
547 static size_t gRealPageSize;
548 static size_t gPageSize;
549 #endif
550
551 #ifdef MALLOC_STATIC_PAGESIZE
552 # define DECLARE_GLOBAL(type, name)
553 # define DEFINE_GLOBALS
554 # define END_GLOBALS
555 # define DEFINE_GLOBAL(type) static const type
556 # define GLOBAL_LOG2 LOG2
557 # define GLOBAL_ASSERT_HELPER1(x) static_assert(x, #x)
558 # define GLOBAL_ASSERT_HELPER2(x, y) static_assert(x, y)
559 # define GLOBAL_ASSERT(...) \
560 MACRO_CALL( \
561 MOZ_PASTE_PREFIX_AND_ARG_COUNT(GLOBAL_ASSERT_HELPER, __VA_ARGS__), \
562 (__VA_ARGS__))
563 # define GLOBAL_CONSTEXPR constexpr
564 #else
565 # define DECLARE_GLOBAL(type, name) static type name;
566 # define DEFINE_GLOBALS static void DefineGlobals() {
567 # define END_GLOBALS }
568 # define DEFINE_GLOBAL(type)
569 # define GLOBAL_LOG2 FloorLog2
570 # define GLOBAL_ASSERT MOZ_RELEASE_ASSERT
571 # define GLOBAL_CONSTEXPR
572 #endif
573
574 DECLARE_GLOBAL(size_t, gMaxSubPageClass)
575 DECLARE_GLOBAL(uint8_t, gNumSubPageClasses)
576 DECLARE_GLOBAL(uint8_t, gPageSize2Pow)
577 DECLARE_GLOBAL(size_t, gPageSizeMask)
578 DECLARE_GLOBAL(size_t, gChunkNumPages)
579 DECLARE_GLOBAL(size_t, gChunkHeaderNumPages)
580 DECLARE_GLOBAL(size_t, gMaxLargeClass)
581
582 DEFINE_GLOBALS
583
584 // Largest sub-page size class, or zero if there are none
585 DEFINE_GLOBAL(size_t)
586 gMaxSubPageClass = gPageSize / 2 >= kMinSubPageClass ? gPageSize / 2 : 0;
587
588 // Max size class for bins.
589 #define gMaxBinClass \
590 (gMaxSubPageClass ? gMaxSubPageClass : kMaxQuantumWideClass)
591
592 // Number of sub-page bins.
593 DEFINE_GLOBAL(uint8_t)
594 gNumSubPageClasses = []() GLOBAL_CONSTEXPR -> uint8_t {
595 if GLOBAL_CONSTEXPR (gMaxSubPageClass != 0) {
596 return FloorLog2(gMaxSubPageClass) - LOG2(kMinSubPageClass) + 1;
597 }
598 return 0;
599 }();
600
601 DEFINE_GLOBAL(uint8_t) gPageSize2Pow = GLOBAL_LOG2(gPageSize);
602 DEFINE_GLOBAL(size_t) gPageSizeMask = gPageSize - 1;
603
604 // Number of pages in a chunk.
605 DEFINE_GLOBAL(size_t) gChunkNumPages = kChunkSize >> gPageSize2Pow;
606
607 // Number of pages necessary for a chunk header plus a guard page.
608 DEFINE_GLOBAL(size_t)
609 gChunkHeaderNumPages =
610 1 + (((sizeof(arena_chunk_t) + sizeof(arena_chunk_map_t) * gChunkNumPages +
611 gPageSizeMask) &
612 ~gPageSizeMask) >>
613 gPageSize2Pow);
614
615 // One chunk, minus the header, minus a guard page
616 DEFINE_GLOBAL(size_t)
617 gMaxLargeClass =
618 kChunkSize - gPageSize - (gChunkHeaderNumPages << gPageSize2Pow);
619
620 // Various sanity checks that regard configuration.
621 GLOBAL_ASSERT(1ULL << gPageSize2Pow == gPageSize,
622 "Page size is not a power of two");
623 GLOBAL_ASSERT(kQuantum >= sizeof(void*));
624 GLOBAL_ASSERT(kQuantum <= kQuantumWide);
625 GLOBAL_ASSERT(!kNumQuantumWideClasses ||
626 kQuantumWide <= (kMinSubPageClass - kMaxQuantumClass));
627
628 GLOBAL_ASSERT(kQuantumWide <= kMaxQuantumClass);
629
630 GLOBAL_ASSERT(gMaxSubPageClass >= kMinSubPageClass || gMaxSubPageClass == 0);
631 GLOBAL_ASSERT(gMaxLargeClass >= gMaxSubPageClass);
632 GLOBAL_ASSERT(kChunkSize >= gPageSize);
633 GLOBAL_ASSERT(kQuantum * 4 <= kChunkSize);
634
635 END_GLOBALS
636
637 // Recycle at most 128 MiB of chunks. This means we retain at most
638 // 6.25% of the process address space on a 32-bit OS for later use.
639 static const size_t gRecycleLimit = 128_MiB;
640
641 // The current amount of recycled bytes, updated atomically.
642 static Atomic<size_t> gRecycledSize;
643
644 // Maximum number of dirty pages per arena.
645 #define DIRTY_MAX_DEFAULT (1U << 8)
646
647 static size_t opt_dirty_max = DIRTY_MAX_DEFAULT;
648
649 // Return the smallest chunk multiple that is >= s.
650 #define CHUNK_CEILING(s) (((s) + kChunkSizeMask) & ~kChunkSizeMask)
651
652 // Return the smallest cacheline multiple that is >= s.
653 #define CACHELINE_CEILING(s) \
654 (((s) + (kCacheLineSize - 1)) & ~(kCacheLineSize - 1))
655
656 // Return the smallest quantum multiple that is >= a.
657 #define QUANTUM_CEILING(a) (((a) + (kQuantumMask)) & ~(kQuantumMask))
658 #define QUANTUM_WIDE_CEILING(a) \
659 (((a) + (kQuantumWideMask)) & ~(kQuantumWideMask))
660
661 // Return the smallest sub page-size that is >= a.
662 #define SUBPAGE_CEILING(a) (RoundUpPow2(a))
663
664 // Return the smallest pagesize multiple that is >= s.
665 #define PAGE_CEILING(s) (((s) + gPageSizeMask) & ~gPageSizeMask)
666
667 // Number of all the small-allocated classes
668 #define NUM_SMALL_CLASSES \
669 (kNumTinyClasses + kNumQuantumClasses + kNumQuantumWideClasses + \
670 gNumSubPageClasses)
671
672 // ***************************************************************************
673 // MALLOC_DECOMMIT and MALLOC_DOUBLE_PURGE are mutually exclusive.
674 #if defined(MALLOC_DECOMMIT) && defined(MALLOC_DOUBLE_PURGE)
675 # error MALLOC_DECOMMIT and MALLOC_DOUBLE_PURGE are mutually exclusive.
676 #endif
677
678 static void* base_alloc(size_t aSize);
679
680 // Set to true once the allocator has been initialized.
681 #if defined(_MSC_VER) && !defined(__clang__)
682 // MSVC may create a static initializer for an Atomic<bool>, which may actually
683 // run after `malloc_init` has been called once, which triggers multiple
684 // initializations.
685 // We work around the problem by not using an Atomic<bool> at all. There is a
686 // theoretical problem with using `malloc_initialized` non-atomically, but
687 // practically, this is only true if `malloc_init` is never called before
688 // threads are created.
689 static bool malloc_initialized;
690 #else
691 // We can rely on Relaxed here because this variable is only ever set when
692 // holding gInitLock. A thread that still sees it false while another sets it
693 // true will enter the same lock, synchronize with the former and check the
694 // flag again under the lock.
695 static Atomic<bool, MemoryOrdering::Relaxed> malloc_initialized;
696 #endif
697
698 // This lock must be held while bootstrapping us.
699 static StaticMutex gInitLock MOZ_UNANNOTATED = {STATIC_MUTEX_INIT};
700
701 // ***************************************************************************
702 // Statistics data structures.
703
704 struct arena_stats_t {
705 // Number of bytes currently mapped.
706 size_t mapped;
707
708 // Current number of committed pages (non madvised/decommitted)
709 size_t committed;
710
711 // Per-size-category statistics.
712 size_t allocated_small;
713
714 size_t allocated_large;
715
716 // The number of "memory operations" aka mallocs/frees.
717 uint64_t operations;
718 };
719
720 // ***************************************************************************
721 // Extent data structures.
722
723 enum ChunkType {
724 UNKNOWN_CHUNK,
725 ZEROED_CHUNK, // chunk only contains zeroes.
726 ARENA_CHUNK, // used to back arena runs created by arena_t::AllocRun.
727 HUGE_CHUNK, // used to back huge allocations (e.g. arena_t::MallocHuge).
728 RECYCLED_CHUNK, // chunk has been stored for future use by chunk_recycle.
729 };
730
731 // Tree of extents.
732 struct extent_node_t {
733 union {
734 // Linkage for the size/address-ordered tree for chunk recycling.
735 RedBlackTreeNode<extent_node_t> mLinkBySize;
736 // Arena id for huge allocations. It's meant to match mArena->mId,
737 // which only holds true when the arena hasn't been disposed of.
738 arena_id_t mArenaId;
739 };
740
741 // Linkage for the address-ordered tree.
742 RedBlackTreeNode<extent_node_t> mLinkByAddr;
743
744 // Pointer to the extent that this tree node is responsible for.
745 void* mAddr;
746
747 // Total region size.
748 size_t mSize;
749
750 union {
751 // What type of chunk is there; used for chunk recycling.
752 ChunkType mChunkType;
753
754 // A pointer to the associated arena, for huge allocations.
755 arena_t* mArena;
756 };
757 };
758
759 struct ExtentTreeSzTrait {
760 static RedBlackTreeNode<extent_node_t>& GetTreeNode(extent_node_t* aThis) {
761 return aThis->mLinkBySize;
762 }
763
764 static inline Order Compare(extent_node_t* aNode, extent_node_t* aOther) {
765 Order ret = CompareInt(aNode->mSize, aOther->mSize);
766 return (ret != Order::eEqual) ? ret
767 : CompareAddr(aNode->mAddr, aOther->mAddr);
768 }
769 };
770
771 struct ExtentTreeTrait {
772 static RedBlackTreeNode<extent_node_t>& GetTreeNode(extent_node_t* aThis) {
773 return aThis->mLinkByAddr;
774 }
775
776 static inline Order Compare(extent_node_t* aNode, extent_node_t* aOther) {
777 return CompareAddr(aNode->mAddr, aOther->mAddr);
778 }
779 };
780
781 struct ExtentTreeBoundsTrait : public ExtentTreeTrait {
782 static inline Order Compare(extent_node_t* aKey, extent_node_t* aNode) {
783 uintptr_t key_addr = reinterpret_cast<uintptr_t>(aKey->mAddr);
784 uintptr_t node_addr = reinterpret_cast<uintptr_t>(aNode->mAddr);
785 size_t node_size = aNode->mSize;
786
787 // Is aKey within aNode?
788 if (node_addr <= key_addr && key_addr < node_addr + node_size) {
789 return Order::eEqual;
790 }
791
792 return CompareAddr(aKey->mAddr, aNode->mAddr);
793 }
794 };
795
796 // Describe size classes to which allocations are rounded up to.
797 // TODO: add large and huge types when the arena allocation code
798 // changes in a way that allows it to be beneficial.
799 class SizeClass {
800 public:
801 enum ClassType {
802 Tiny,
803 Quantum,
804 QuantumWide,
805 SubPage,
806 Large,
807 };
808
809 explicit inline SizeClass(size_t aSize) {
810 if (aSize <= kMaxTinyClass) {
811 mType = Tiny;
812 mSize = std::max(RoundUpPow2(aSize), kMinTinyClass);
813 } else if (aSize <= kMaxQuantumClass) {
814 mType = Quantum;
815 mSize = QUANTUM_CEILING(aSize);
816 } else if (aSize <= kMaxQuantumWideClass) {
817 mType = QuantumWide;
818 mSize = QUANTUM_WIDE_CEILING(aSize);
819 } else if (aSize <= gMaxSubPageClass) {
820 mType = SubPage;
821 mSize = SUBPAGE_CEILING(aSize);
822 } else if (aSize <= gMaxLargeClass) {
823 mType = Large;
824 mSize = PAGE_CEILING(aSize);
825 } else {
826 MOZ_MAKE_COMPILER_ASSUME_IS_UNREACHABLE("Invalid size");
827 }
828 }
829
830 SizeClass& operator=(const SizeClass& aOther) = default;
831
832 bool operator==(const SizeClass& aOther) { return aOther.mSize == mSize; }
833
834 size_t Size() { return mSize; }
835
836 ClassType Type() { return mType; }
837
838 SizeClass Next() { return SizeClass(mSize + 1); }
839
840 private:
841 ClassType mType;
842 size_t mSize;
843 };
844
845 // Fast division
846 //
847 // During deallocation we want to divide by the size class. This class
848 // provides a routine and sets up a constant as follows.
849 //
850 // To divide by a number D that is not a power of two we multiply by (2^17 /
851 // D) and then right shift by 17 positions.
852 //
853 // X / D
854 //
855 // becomes
856 //
857 // (X * m) >> p
858 //
859 // Where m is calculated during the FastDivisor constructor similarly to:
860 //
861 // m = 2^p / D
862 //
863 template <typename T>
864 class FastDivisor {
865 private:
866 // The shift amount (p) is chosen to minimise the size of m while
867 // working for divisors up to 65536 in steps of 16. I arrived at 17
868 // experimentally. I wanted a low number to minimise the range of m
869 // so it can fit in a uint16_t, 16 didn't work but 17 worked perfectly.
870 //
871 // We'd need to increase this if we allocated memory on smaller boundaries
872 // than 16.
873 static const unsigned p = 17;
874
875 // We can fit the inverted divisor in 16 bits, but we template it here for
876 // convenience.
877 T m;
878
879 public:
880 // Needed so mBins can be constructed.
881 FastDivisor() : m(0) {}
882
883 FastDivisor(unsigned div, unsigned max) {
884 MOZ_ASSERT(div <= max);
885
886 // divide_inv_shift is large enough.
887 MOZ_ASSERT((1U << p) >= div);
888
889 // The calculation here for m is formula 26 from Section
890 // 10-9 "Unsigned Division by Divisors >= 1" in
891 // Henry S. Warren, Jr.'s Hacker's Delight, 2nd Ed.
892 unsigned m_ = ((1U << p) + div - 1 - (((1U << p) - 1) % div)) / div;
893
894 // Make sure that max * m does not overflow.
895 MOZ_DIAGNOSTIC_ASSERT(max < UINT_MAX / m_);
896
897 MOZ_ASSERT(m_ <= std::numeric_limits<T>::max());
898 m = static_cast<T>(m_);
899
900 // Initialisation made m non-zero.
901 MOZ_ASSERT(m);
902
903 // Test that all the divisions in the range we expected would work.
904 #ifdef MOZ_DEBUG
905 for (unsigned num = 0; num < max; num += div) {
906 MOZ_ASSERT(num / div == divide(num));
907 }
908 #endif
909 }
910
911 // Note that this always occurs in uint32_t regardless of m's type. If m is
912 // a uint16_t it will be zero-extended before the multiplication. We also use
913 // uint32_t rather than something that could possibly be larger because it is
914 // most-likely the cheapest multiplication.
915 inline uint32_t divide(uint32_t num) const {
916 // Check that m was initialised.
917 MOZ_ASSERT(m);
918 return (num * m) >> p;
919 }
920 };
921
922 template <typename T>
923 unsigned inline operator/(unsigned num, FastDivisor<T> divisor) {
924 return divisor.divide(num);
925 }
926
927 // ***************************************************************************
928 // Radix tree data structures.
929 //
930 // The number of bits passed to the template is the number of significant bits
931 // in an address to do a radix lookup with.
932 //
933 // An address is looked up by splitting it in kBitsPerLevel bit chunks, except
934 // the most significant bits, where the bit chunk is kBitsAtLevel1 which can be
935 // different if Bits is not a multiple of kBitsPerLevel.
936 //
937 // With e.g. sizeof(void*)=4, Bits=16 and kBitsPerLevel=8, an address is split
938 // like the following:
939 // 0x12345678 -> mRoot[0x12][0x34]
940 template <size_t Bits>
941 class AddressRadixTree {
942 // Size of each radix tree node (as a power of 2).
943 // This impacts tree depth.
944 #ifdef HAVE_64BIT_BUILD
945 static const size_t kNodeSize = kCacheLineSize;
946 #else
947 static const size_t kNodeSize = 16_KiB;
948 #endif
949 static const size_t kBitsPerLevel = LOG2(kNodeSize) - LOG2(sizeof(void*));
950 static const size_t kBitsAtLevel1 =
951 (Bits % kBitsPerLevel) ? Bits % kBitsPerLevel : kBitsPerLevel;
952 static const size_t kHeight = (Bits + kBitsPerLevel - 1) / kBitsPerLevel;
953 static_assert(kBitsAtLevel1 + (kHeight - 1) * kBitsPerLevel == Bits,
954 "AddressRadixTree parameters don't work out");
955
956 Mutex mLock MOZ_UNANNOTATED;
957 // We guard only the single slot creations and assume read-only is safe
958 // at any time.
959 void** mRoot;
960
961 public:
962 bool Init() MOZ_REQUIRES(gInitLock) MOZ_EXCLUDES(mLock);
963
964 inline void* Get(void* aAddr) MOZ_EXCLUDES(mLock);
965
966 // Returns whether the value was properly set.
967 inline bool Set(void* aAddr, void* aValue) MOZ_EXCLUDES(mLock);
968
969 inline bool Unset(void* aAddr) MOZ_EXCLUDES(mLock) {
970 return Set(aAddr, nullptr);
971 }
972
973 private:
974 // GetSlotInternal is agnostic wrt mLock and used directly only in DEBUG
975 // code.
976 inline void** GetSlotInternal(void* aAddr, bool aCreate);
977
978 inline void** GetSlotIfExists(void* aAddr) MOZ_EXCLUDES(mLock) {
979 return GetSlotInternal(aAddr, false);
980 }
981 inline void** GetOrCreateSlot(void* aAddr) MOZ_REQUIRES(mLock) {
982 return GetSlotInternal(aAddr, true);
983 }
984 };
985
986 // ***************************************************************************
987 // Arena data structures.
988
989 struct arena_bin_t;
990
991 struct ArenaChunkMapLink {
992 static RedBlackTreeNode<arena_chunk_map_t>& GetTreeNode(
993 arena_chunk_map_t* aThis) {
994 return aThis->link;
995 }
996 };
997
998 struct ArenaAvailTreeTrait : public ArenaChunkMapLink {
999 static inline Order Compare(arena_chunk_map_t* aNode,
1000 arena_chunk_map_t* aOther) {
1001 size_t size1 = aNode->bits & ~gPageSizeMask;
1002 size_t size2 = aOther->bits & ~gPageSizeMask;
1003 Order ret = CompareInt(size1, size2);
1004 return (ret != Order::eEqual)
1005 ? ret
1006 : CompareAddr((aNode->bits & CHUNK_MAP_KEY) ? nullptr : aNode,
1007 aOther);
1008 }
1009 };
1010
1011 struct ArenaDirtyChunkTrait {
1012 static RedBlackTreeNode<arena_chunk_t>& GetTreeNode(arena_chunk_t* aThis) {
1013 return aThis->link_dirty;
1014 }
1015
1016 static inline Order Compare(arena_chunk_t* aNode, arena_chunk_t* aOther) {
1017 MOZ_ASSERT(aNode);
1018 MOZ_ASSERT(aOther);
1019 return CompareAddr(aNode, aOther);
1020 }
1021 };
1022
1023 #ifdef MALLOC_DOUBLE_PURGE
1024 namespace mozilla {
1025
1026 template <>
1027 struct GetDoublyLinkedListElement<arena_chunk_t> {
1028 static DoublyLinkedListElement<arena_chunk_t>& Get(arena_chunk_t* aThis) {
1029 return aThis->chunks_madvised_elem;
1030 }
1031 };
1032 } // namespace mozilla
1033 #endif
1034
1035 enum class purge_action_t {
1036 None,
1037 PurgeNow,
1038 Queue,
1039 };
1040
1041 struct arena_run_t {
1042 #if defined(MOZ_DIAGNOSTIC_ASSERT_ENABLED)
1043 uint32_t mMagic;
1044 # define ARENA_RUN_MAGIC 0x384adf93
1045
1046 // On 64-bit platforms, having the arena_bin_t pointer following
1047 // the mMagic field means there's padding between both fields, making
1048 // the run header larger than necessary.
1049 // But when MOZ_DIAGNOSTIC_ASSERT_ENABLED is not set, starting the
1050 // header with this field followed by the arena_bin_t pointer yields
1051 // the same padding. We do want the mMagic field to appear first, so
1052 // depending whether MOZ_DIAGNOSTIC_ASSERT_ENABLED is set or not, we
1053 // move some field to avoid padding.
1054
1055 // Number of free regions in run.
1056 unsigned mNumFree;
1057 #endif
1058
1059 // Used by arena_bin_t::mNonFullRuns.
1060 DoublyLinkedListElement<arena_run_t> mRunListElem;
1061
1062 // Bin this run is associated with.
1063 arena_bin_t* mBin;
1064
1065 // Index of first element that might have a free region.
1066 unsigned mRegionsMinElement;
1067
1068 #if !defined(MOZ_DIAGNOSTIC_ASSERT_ENABLED)
1069 // Number of free regions in run.
1070 unsigned mNumFree;
1071 #endif
1072
1073 // Bitmask of in-use regions (0: in use, 1: free).
1074 unsigned mRegionsMask[]; // Dynamically sized.
1075 };
1076
1077 namespace mozilla {
1078
1079 template <>
1080 struct GetDoublyLinkedListElement<arena_run_t> {
1081 static DoublyLinkedListElement<arena_run_t>& Get(arena_run_t* aThis) {
1082 return aThis->mRunListElem;
1083 }
1084 };
1085
1086 } // namespace mozilla
1087
1088 struct arena_bin_t {
1089 // We use a LIFO ("last-in-first-out") policy to refill non-full runs.
1090 //
1091 // This has the following reasons:
1092 // 1. It is cheap, as all our non-full-runs' book-keeping is O(1), no
1093 // tree-balancing or walking is needed.
1094 // 2. It also helps to increase the probability for CPU cache hits for the
1095 // book-keeping and the reused slots themselves, as the same memory was
1096 // most recently touched during free, especially when used from the same
1097 // core (or via the same shared cache, depending on the architecture).
1098 DoublyLinkedList<arena_run_t> mNonFullRuns;
1099
1100 // Bin's size class.
1101 size_t mSizeClass;
1102
1103 // Total number of regions in a run for this bin's size class.
1104 uint32_t mRunNumRegions;
1105
1106 // Number of elements in a run's mRegionsMask for this bin's size class.
1107 uint32_t mRunNumRegionsMask;
1108
1109 // Offset of first region in a run for this bin's size class.
1110 uint32_t mRunFirstRegionOffset;
1111
1112 // Current number of runs in this bin, full or otherwise.
1113 uint32_t mNumRuns;
1114
1115 // A constant for fast division by size class. This value is 16 bits wide so
1116 // it is placed last.
1117 FastDivisor<uint16_t> mSizeDivisor;
1118
1119 // Total number of pages in a run for this bin's size class.
1120 uint8_t mRunSizePages;
1121
1122 // Amount of overhead runs are allowed to have.
1123 static constexpr double kRunOverhead = 1.6_percent;
1124 static constexpr double kRunRelaxedOverhead = 2.4_percent;
1125
1126 // Initialize a bin for the given size class.
1127 // The generated run sizes, for a page size of 4 KiB, are:
1128 // size|run size|run size|run size|run
1129 // class|size class|size class|size class|size
1130 // 4 4 KiB 8 4 KiB 16 4 KiB 32 4 KiB
1131 // 48 4 KiB 64 4 KiB 80 4 KiB 96 4 KiB
1132 // 112 4 KiB 128 8 KiB 144 4 KiB 160 8 KiB
1133 // 176 4 KiB 192 4 KiB 208 8 KiB 224 4 KiB
1134 // 240 8 KiB 256 16 KiB 272 8 KiB 288 4 KiB
1135 // 304 12 KiB 320 12 KiB 336 4 KiB 352 8 KiB
1136 // 368 4 KiB 384 8 KiB 400 20 KiB 416 16 KiB
1137 // 432 12 KiB 448 4 KiB 464 16 KiB 480 8 KiB
1138 // 496 20 KiB 512 32 KiB 768 16 KiB 1024 64 KiB
1139 // 1280 24 KiB 1536 32 KiB 1792 16 KiB 2048 128 KiB
1140 // 2304 16 KiB 2560 48 KiB 2816 36 KiB 3072 64 KiB
1141 // 3328 36 KiB 3584 32 KiB 3840 64 KiB
1142 inline void Init(SizeClass aSizeClass);
1143 };
1144
1145 // We try to keep the above structure aligned with common cache lines sizes,
1146 // often that's 64 bytes on x86 and ARM, we don't make assumptions for other
1147 // architectures.
1148 #if defined(__x86_64__) || defined(__aarch64__)
1149 // On 64bit platforms this structure is often 48 bytes
1150 // long, which means every other array element will be properly aligned.
1151 static_assert(sizeof(arena_bin_t) == 48);
1152 #elif defined(__x86__) || defined(__arm__)
1153 static_assert(sizeof(arena_bin_t) == 32);
1154 #endif
1155
1156 // We cannot instantiate
1157 // Atomic<std::chrono::time_point<std::chrono::steady_clock>>
1158 // so we explicitly force timestamps to be uint64_t in ns.
1159 uint64_t GetTimestampNS() {
1160 // On most if not all systems we care about the conversion to ns is a no-op,
1161 // so we prefer to keep the precision here for performance, but let's be
1162 // explicit about it.
1163 return std::chrono::floor<std::chrono::nanoseconds>(
1164 std::chrono::steady_clock::now())
1165 .time_since_epoch()
1166 .count();
1167 }
1168
1169 enum PurgeCondition { PurgeIfThreshold, PurgeUnconditional };
1170
1171 struct arena_t {
1172 #if defined(MOZ_DIAGNOSTIC_ASSERT_ENABLED)
1173 uint32_t mMagic;
1174 # define ARENA_MAGIC 0x947d3d24
1175 #endif
1176
1177 // Linkage for the tree of arenas by id.
1178 // This just provides the memory to be used by the collection tree
1179 // and thus needs no arena_t::mLock.
1180 RedBlackTreeNode<arena_t> mLink;
1181
1182 // Arena id, that we keep away from the beginning of the struct so that
1183 // free list pointers in TypedBaseAlloc<arena_t> don't overflow in it,
1184 // and it keeps the value it had after the destructor.
1185 arena_id_t mId;
1186
1187 // Operations on this arena require that lock be locked. The MaybeMutex
1188 // class will elude locking if the arena is accessed from a single thread
1189 // only (currently only the main thread can be used like this).
1190 // Can be acquired while holding gArenas.mLock, but must not be acquired or
1191 // held while holding or acquiring gArenas.mPurgeListLock.
1192 MaybeMutex mLock MOZ_UNANNOTATED;
1193
1194 // The lock is required to write to fields of mStats, but it is not needed to
1195 // read them, so long as inconsistents reads are okay (fields might not make
1196 // sense together).
1197 arena_stats_t mStats MOZ_GUARDED_BY(mLock);
1198
1199 // We can read the allocated counts from mStats without a lock:
1200 size_t AllocatedBytes() const MOZ_NO_THREAD_SAFETY_ANALYSIS {
1201 return mStats.allocated_small + mStats.allocated_large;
1202 }
1203
1204 // We can read the operations field from mStats without a lock:
1205 uint64_t Operations() const MOZ_NO_THREAD_SAFETY_ANALYSIS {
1206 return mStats.operations;
1207 }
1208
1209 private:
1210 // Tree of dirty-page-containing chunks this arena manages.
1211 RedBlackTree<arena_chunk_t, ArenaDirtyChunkTrait> mChunksDirty
1212 MOZ_GUARDED_BY(mLock);
1213
1214 #ifdef MALLOC_DOUBLE_PURGE
1215 // Head of a linked list of MADV_FREE'd-page-containing chunks this
1216 // arena manages.
1217 DoublyLinkedList<arena_chunk_t> mChunksMAdvised MOZ_GUARDED_BY(mLock);
1218 #endif
1219
1220 // In order to avoid rapid chunk allocation/deallocation when an arena
1221 // oscillates right on the cusp of needing a new chunk, cache the most
1222 // recently freed chunk. The spare is left in the arena's chunk trees
1223 // until it is deleted.
1224 //
1225 // There is one spare chunk per arena, rather than one spare total, in
1226 // order to avoid interactions between multiple threads that could make
1227 // a single spare inadequate.
1228 arena_chunk_t* mSpare MOZ_GUARDED_BY(mLock);
1229
1230 // A per-arena opt-in to randomize the offset of small allocations
1231 // Needs no lock, read-only.
1232 bool mRandomizeSmallAllocations;
1233
1234 // A pseudorandom number generator. Initially null, it gets initialized
1235 // on first use to avoid recursive malloc initialization (e.g. on OSX
1236 // arc4random allocates memory).
1237 mozilla::non_crypto::XorShift128PlusRNG* mPRNG MOZ_GUARDED_BY(mLock);
1238 bool mIsPRNGInitializing MOZ_GUARDED_BY(mLock);
1239
1240 public:
1241 // Whether this is a private arena. Multiple public arenas are just a
1242 // performance optimization and not a safety feature.
1243 //
1244 // Since, for example, we don't want thread-local arenas to grow too much, we
1245 // use the default arena for bigger allocations. We use this member to allow
1246 // realloc() to switch out of our arena if needed (which is not allowed for
1247 // private arenas for security).
1248 // Needs no lock, read-only.
1249 bool mIsPrivate;
1250
1251 // Current count of pages within unused runs that are potentially
1252 // dirty, and for which madvise(... MADV_FREE) has not been called. By
1253 // tracking this, we can institute a limit on how much dirty unused
1254 // memory is mapped for each arena.
1255 size_t mNumDirty MOZ_GUARDED_BY(mLock);
1256
1257 // Precalculated value for faster checks.
1258 size_t mMaxDirty MOZ_GUARDED_BY(mLock);
1259
1260 // The current number of pages that are available without a system call (but
1261 // probably a page fault).
1262 size_t mNumMAdvised MOZ_GUARDED_BY(mLock);
1263 size_t mNumFresh MOZ_GUARDED_BY(mLock);
1264
1265 // Maximum value allowed for mNumDirty.
1266 // Needs no lock, read-only.
1267 size_t mMaxDirtyBase;
1268
1269 // Needs no lock, read-only.
1270 int32_t mMaxDirtyIncreaseOverride;
1271 int32_t mMaxDirtyDecreaseOverride;
1272
1273 // The link to gArenas.mOutstandingPurges.
1274 // Note that this must only be accessed while holding gArenas.mPurgeListLock
1275 // (but not arena_t.mLock !) through gArenas.mOutstandingPurges.
1276 DoublyLinkedListElement<arena_t> mPurgeListElem;
1277
1278 // A "significant reuse" is when a dirty page is used for a new allocation,
1279 // it has the CHUNK_MAP_DIRTY bit cleared and CHUNK_MAP_ALLOCATED set.
1280 //
1281 // Timestamp of the last time we saw a significant reuse (in ns).
1282 // Note that this variable is written very often from many threads and read
1283 // only sparsely on the main thread, but when we read it we need to see the
1284 // chronologically latest write asap (so we cannot use Relaxed).
1285 Atomic<uint64_t> mLastSignificantReuseNS;
1286
1287 public:
1288 // A flag that indicates if arena will be Purge()'d.
1289 //
1290 // It is set either when a thread commits to adding it to mOutstandingPurges
1291 // or when imitating a Purge. Cleared only by Purge when we know we are
1292 // completely done. This is used to avoid accessing the list (and list lock)
1293 // on every call to ShouldStartPurge() and to avoid deleting arenas that
1294 // another thread is purging.
1295 bool mIsPurgePending MOZ_GUARDED_BY(mLock);
1296
1297 // A mirror of ArenaCollection::mIsDeferredPurgeEnabled, here only to
1298 // optimize memory reads in ShouldStartPurge().
1299 bool mIsDeferredPurgeEnabled MOZ_GUARDED_BY(mLock);
1300
1301 // True if the arena is in the process of being destroyed, and needs to be
1302 // released after a concurrent purge completes.
1303 bool mMustDeleteAfterPurge MOZ_GUARDED_BY(mLock) = false;
1304
1305 private:
1306 // Size/address-ordered tree of this arena's available runs. This tree
1307 // is used for first-best-fit run allocation.
1308 RedBlackTree<arena_chunk_map_t, ArenaAvailTreeTrait> mRunsAvail
1309 MOZ_GUARDED_BY(mLock);
1310
1311 public:
1312 // mBins is used to store rings of free regions of the following sizes,
1313 // assuming a 16-byte quantum, 4kB pagesize, and default MALLOC_OPTIONS.
1314 //
1315 // | mBins[i] | size |
1316 // +----------+------+
1317 // | 0 | 2 |
1318 // | 1 | 4 |
1319 // | 2 | 8 |
1320 // +----------+------+
1321 // | 3 | 16 |
1322 // | 4 | 32 |
1323 // | 5 | 48 |
1324 // | 6 | 64 |
1325 // | : :
1326 // | : :
1327 // | 33 | 496 |
1328 // | 34 | 512 |
1329 // +----------+------+
1330 // | 35 | 768 |
1331 // | 36 | 1024 |
1332 // | : :
1333 // | : :
1334 // | 46 | 3584 |
1335 // | 47 | 3840 |
1336 // +----------+------+
1337 arena_bin_t mBins[] MOZ_GUARDED_BY(mLock); // Dynamically sized.
1338
1339 explicit arena_t(arena_params_t* aParams, bool aIsPrivate);
1340 ~arena_t();
1341
1342 void ResetSmallAllocRandomization();
1343
1344 void InitPRNG() MOZ_REQUIRES(mLock);
1345
1346 private:
1347 void InitChunk(arena_chunk_t* aChunk, size_t aMinCommittedPages)
1348 MOZ_REQUIRES(mLock);
1349
1350 // Remove the chunk from the arena. This removes it from all the page counts.
1351 // It assumes its run has already been removed and lets the caller clear
1352 // mSpare as necessary.
1353 bool RemoveChunk(arena_chunk_t* aChunk) MOZ_REQUIRES(mLock);
1354
1355 // This may return a chunk that should be destroyed with chunk_dealloc outside
1356 // of the arena lock. It is not the same chunk as was passed in (since that
1357 // chunk now becomes mSpare).
1358 [[nodiscard]] arena_chunk_t* DemoteChunkToSpare(arena_chunk_t* aChunk)
1359 MOZ_REQUIRES(mLock);
1360
1361 // Try to merge the run with its neighbours. Returns the new index of the run
1362 // (since it may have merged with an earlier one).
1363 size_t TryCoalesce(arena_chunk_t* aChunk, size_t run_ind, size_t run_pages,
1364 size_t size) MOZ_REQUIRES(mLock);
1365
1366 arena_run_t* AllocRun(size_t aSize, bool aLarge, bool aZero)
1367 MOZ_REQUIRES(mLock);
1368
1369 arena_chunk_t* DallocRun(arena_run_t* aRun, bool aDirty) MOZ_REQUIRES(mLock);
1370
1371 [[nodiscard]] bool SplitRun(arena_run_t* aRun, size_t aSize, bool aLarge,
1372 bool aZero) MOZ_REQUIRES(mLock);
1373
1374 void TrimRunHead(arena_chunk_t* aChunk, arena_run_t* aRun, size_t aOldSize,
1375 size_t aNewSize) MOZ_REQUIRES(mLock);
1376
1377 void TrimRunTail(arena_chunk_t* aChunk, arena_run_t* aRun, size_t aOldSize,
1378 size_t aNewSize, bool dirty) MOZ_REQUIRES(mLock);
1379
1380 arena_run_t* GetNewEmptyBinRun(arena_bin_t* aBin) MOZ_REQUIRES(mLock);
1381
1382 inline arena_run_t* GetNonFullBinRun(arena_bin_t* aBin) MOZ_REQUIRES(mLock);
1383
1384 inline uint8_t FindFreeBitInMask(uint32_t aMask, uint32_t& aRng)
1385 MOZ_REQUIRES(mLock);
1386
1387 inline void* ArenaRunRegAlloc(arena_run_t* aRun, arena_bin_t* aBin)
1388 MOZ_REQUIRES(mLock);
1389
1390 inline void* MallocSmall(size_t aSize, bool aZero) MOZ_EXCLUDES(mLock);
1391
1392 void* MallocLarge(size_t aSize, bool aZero) MOZ_EXCLUDES(mLock);
1393
1394 void* MallocHuge(size_t aSize, bool aZero) MOZ_EXCLUDES(mLock);
1395
1396 void* PallocLarge(size_t aAlignment, size_t aSize, size_t aAllocSize)
1397 MOZ_EXCLUDES(mLock);
1398
1399 void* PallocHuge(size_t aSize, size_t aAlignment, bool aZero)
1400 MOZ_EXCLUDES(mLock);
1401
1402 void RallocShrinkLarge(arena_chunk_t* aChunk, void* aPtr, size_t aSize,
1403 size_t aOldSize) MOZ_EXCLUDES(mLock);
1404
1405 bool RallocGrowLarge(arena_chunk_t* aChunk, void* aPtr, size_t aSize,
1406 size_t aOldSize) MOZ_EXCLUDES(mLock);
1407
1408 void* RallocSmallOrLarge(void* aPtr, size_t aSize, size_t aOldSize)
1409 MOZ_EXCLUDES(mLock);
1410
1411 void* RallocHuge(void* aPtr, size_t aSize, size_t aOldSize)
1412 MOZ_EXCLUDES(mLock);
1413
1414 public:
1415 inline void* Malloc(size_t aSize, bool aZero) MOZ_EXCLUDES(mLock);
1416
1417 void* Palloc(size_t aAlignment, size_t aSize) MOZ_EXCLUDES(mLock);
1418
1419 // This may return a chunk that should be destroyed with chunk_dealloc outside
1420 // of the arena lock. It is not the same chunk as was passed in (since that
1421 // chunk now becomes mSpare).
1422 [[nodiscard]] inline arena_chunk_t* DallocSmall(arena_chunk_t* aChunk,
1423 void* aPtr,
1424 arena_chunk_map_t* aMapElm)
1425 MOZ_REQUIRES(mLock);
1426
1427 [[nodiscard]] arena_chunk_t* DallocLarge(arena_chunk_t* aChunk, void* aPtr)
1428 MOZ_REQUIRES(mLock);
1429
1430 void* Ralloc(void* aPtr, size_t aSize, size_t aOldSize) MOZ_EXCLUDES(mLock);
1431
1432 void UpdateMaxDirty() MOZ_EXCLUDES(mLock);
1433
1434 #ifdef MALLOC_DECOMMIT
1435 // During a commit operation (for aReqPages) we have the opportunity of
1436 // commiting at most aRemPages additional pages. How many should we commit to
1437 // amortise system calls?
1438 size_t ExtraCommitPages(size_t aReqPages, size_t aRemainingPages)
1439 MOZ_REQUIRES(mLock);
1440 #endif
1441
1442 enum PurgeResult {
1443 // The stop threshold of dirty pages was reached.
1444 Done,
1445
1446 // There's more chunks in this arena that could be purged.
1447 Continue,
1448
1449 // The only chunks with dirty pages are busy being purged by other threads.
1450 Busy,
1451
1452 // The arena needs to be destroyed by the caller.
1453 Dying,
1454 };
1455
1456 // Purge some dirty pages.
1457 //
1458 // When this is called the caller has already tested ShouldStartPurge()
1459 // (possibly on another thread asychronously) or is passing
1460 // PurgeUnconditional. However because it's called without the lock it will
1461 // recheck ShouldContinuePurge() before doing any work.
1462 //
1463 // It may purge a number of runs within a single chunk before returning. It
1464 // will return Continue if there's more work to do in other chunks
1465 // (ShouldContinuePurge()).
1466 //
1467 // To release more pages from other chunks then it's best to call Purge
1468 // in a loop, looping when it returns Continue.
1469 //
1470 // This must be called without the mLock held (it'll take the lock).
1471 //
1472 PurgeResult Purge(PurgeCondition aCond) MOZ_EXCLUDES(mLock);
1473
1474 class PurgeInfo {
1475 private:
1476 size_t mDirtyInd = 0;
1477 size_t mDirtyNPages = 0;
1478 size_t mFreeRunInd = 0;
1479 size_t mFreeRunLen = 0;
1480
1481 public:
1482 arena_t& mArena;
1483
1484 arena_chunk_t* mChunk = nullptr;
1485
1486 size_t FreeRunLenBytes() const { return mFreeRunLen << gPageSize2Pow; }
1487
1488 // The last index of the free run.
1489 size_t FreeRunLastInd() const { return mFreeRunInd + mFreeRunLen - 1; }
1490
1491 void* DirtyPtr() const {
1492 return (void*)(uintptr_t(mChunk) + (mDirtyInd << gPageSize2Pow));
1493 }
1494
1495 size_t DirtyLenBytes() const { return mDirtyNPages << gPageSize2Pow; }
1496
1497 // Purging memory is seperated into 3 phases.
1498 // * FindDirtyPages() which find the dirty pages in a chunk and marks the
1499 // run and chunk as busy while holding the lock.
1500 // * Release the pages (without the lock)
1501 // * UpdatePagesAndCounts() which marks the dirty pages as not-dirty and
1502 // updates other counters (while holding the lock).
1503 //
1504 // FindDirtyPages() will return false purging should not continue purging in
1505 // this chunk. Either because it has no dirty pages or is dying.
1506 bool FindDirtyPages(bool aPurgedOnce) MOZ_REQUIRES(mArena.mLock);
1507
1508 // Returns a pair, the first field indicates if there are more dirty pages
1509 // remaining in the current chunk. The second field if non-null points to a
1510 // chunk that must be released by the caller.
1511 std::pair<bool, arena_chunk_t*> UpdatePagesAndCounts()
1512 MOZ_REQUIRES(mArena.mLock);
1513
1514 // FinishPurgingInChunk() is used whenever we decide to stop purging in a
1515 // chunk, This could be because there are no more dirty pages, or the chunk
1516 // is dying, or we hit the arena-level threshold.
1517 void FinishPurgingInChunk(bool aAddToMAdvised) MOZ_REQUIRES(mArena.mLock);
1518
1519 explicit PurgeInfo(arena_t& arena, arena_chunk_t* chunk)
1520 : mArena(arena), mChunk(chunk) {}
1521 };
1522
1523 void HardPurge();
1524
1525 // Check mNumDirty against EffectiveMaxDirty and return the appropriate
1526 // action to be taken by MayDoOrQueuePurge (outside mLock's scope).
1527 //
1528 // None: Nothing to do.
1529 // PurgeNow: Immediate synchronous purge.
1530 // Queue: Add a new purge request.
1531 //
1532 // Note that in the case of deferred purge this function takes into account
1533 // mIsDeferredPurgeNeeded to avoid useless operations on the purge list
1534 // that would require gArenas.mPurgeListLock.
1535 inline purge_action_t ShouldStartPurge() MOZ_REQUIRES(mLock);
1536
1537 // Take action according to ShouldStartPurge.
1538 inline void MayDoOrQueuePurge(purge_action_t aAction) MOZ_EXCLUDES(mLock);
1539
1540 // Check the EffectiveHalfMaxDirty threshold to decide if we continue purge.
1541 // This threshold is lower than ShouldStartPurge to have some hysteresis.
1542 bool ShouldContinuePurge(PurgeCondition aCond) MOZ_REQUIRES(mLock) {
1543 return (mNumDirty > ((aCond == PurgeUnconditional) ? 0 : mMaxDirty >> 1));
1544 }
1545
1546 // Update the last significant reuse timestamp.
1547 void NotifySignificantReuse() MOZ_EXCLUDES(mLock);
1548
1549 bool IsMainThreadOnly() const { return !mLock.LockIsEnabled(); }
1550
1551 void* operator new(size_t aCount) = delete;
1552
1553 void* operator new(size_t aCount, const fallible_t&) noexcept;
1554
1555 void operator delete(void*);
1556 };
1557
1558 namespace mozilla {
1559
1560 template <>
1561 struct GetDoublyLinkedListElement<arena_t> {
1562 static DoublyLinkedListElement<arena_t>& Get(arena_t* aThis) {
1563 return aThis->mPurgeListElem;
1564 }
1565 };
1566
1567 } // namespace mozilla
1568
1569 struct ArenaTreeTrait {
1570 static RedBlackTreeNode<arena_t>& GetTreeNode(arena_t* aThis) {
1571 return aThis->mLink;
1572 }
1573
1574 static inline Order Compare(arena_t* aNode, arena_t* aOther) {
1575 MOZ_ASSERT(aNode);
1576 MOZ_ASSERT(aOther);
1577 return CompareInt(aNode->mId, aOther->mId);
1578 }
1579 };
1580
1581 // Bookkeeping for all the arenas used by the allocator.
1582 // Arenas are separated in two categories:
1583 // - "private" arenas, used through the moz_arena_* API
1584 // - all the other arenas: the default arena, and thread-local arenas,
1585 // used by the standard API.
1586 class ArenaCollection {
1587 public:
1588 bool Init() MOZ_REQUIRES(gInitLock) MOZ_EXCLUDES(mLock) {
1589 MOZ_PUSH_IGNORE_THREAD_SAFETY
1590 mArenas.Init();
1591 mPrivateArenas.Init();
1592 #ifndef NON_RANDOM_ARENA_IDS
1593 mMainThreadArenas.Init();
1594 #endif
1595 MOZ_POP_THREAD_SAFETY
1596 arena_params_t params;
1597 // The main arena allows more dirty pages than the default for other arenas.
1598 params.mMaxDirty = opt_dirty_max;
1599 mDefaultArena =
1600 mLock.Init() ? CreateArena(/* aIsPrivate = */ false, &params) : nullptr;
1601 mPurgeListLock.Init();
1602 mIsDeferredPurgeEnabled = false;
1603 return bool(mDefaultArena);
1604 }
1605
1606 // The requested arena must exist.
1607 inline arena_t* GetById(arena_id_t aArenaId, bool aIsPrivate)
1608 MOZ_EXCLUDES(mLock);
1609
1610 arena_t* CreateArena(bool aIsPrivate, arena_params_t* aParams)
1611 MOZ_EXCLUDES(mLock);
1612
1613 void DisposeArena(arena_t* aArena) MOZ_EXCLUDES(mLock) {
1614 // This will not call MayPurge but only unlink the element in case.
1615 // It returns true if we successfully removed the item from the list,
1616 // meaning we have exclusive access to it and can delete it.
1617 bool delete_now = RemoveFromOutstandingPurges(aArena);
1618
1619 {
1620 MutexAutoLock lock(mLock);
1621 Tree& tree =
1622 #ifndef NON_RANDOM_ARENA_IDS
1623 aArena->IsMainThreadOnly() ? mMainThreadArenas :
1624 #endif
1625 mPrivateArenas;
1626
1627 MOZ_RELEASE_ASSERT(tree.Search(aArena), "Arena not in tree");
1628 tree.Remove(aArena);
1629 mNumOperationsDisposedArenas += aArena->Operations();
1630 }
1631 {
1632 MutexAutoLock lock(aArena->mLock);
1633 if (!aArena->mIsPurgePending) {
1634 // If no purge was pending then we have exclusive access to the
1635 // arena and must delete it.
1636 delete_now = true;
1637 } else if (!delete_now) {
1638 // The remaining possibility, when we failed to remove the arena from
1639 // the list (because a purging thread alredy did so) then that thread
1640 // will be the last thread holding the arena and is now responsible for
1641 // deleting it.
1642 aArena->mMustDeleteAfterPurge = true;
1643
1644 // Not that it's not possible to have checked the list of pending purges
1645 // BEFORE the arena was added to the list because that would mean that
1646 // an operation on the arena (free or realloc) was running concurrently
1647 // with deletion, which would be a memory error and the assertions in
1648 // the destructor help check for that.
1649 }
1650 }
1651
1652 if (delete_now) {
1653 delete aArena;
1654 }
1655 }
1656
1657 void SetDefaultMaxDirtyPageModifier(int32_t aModifier) {
1658 {
1659 MutexAutoLock lock(mLock);
1660 mDefaultMaxDirtyPageModifier = aModifier;
1661 for (auto* arena : iter()) {
1662 // We can only update max-dirty for main-thread-only arenas from the
1663 // main thread.
1664 if (!arena->IsMainThreadOnly() || IsOnMainThreadWeak()) {
1665 arena->UpdateMaxDirty();
1666 }
1667 }
1668 }
1669 }
1670
1671 int32_t DefaultMaxDirtyPageModifier() { return mDefaultMaxDirtyPageModifier; }
1672
1673 using Tree = RedBlackTree<arena_t, ArenaTreeTrait>;
1674
1675 struct Iterator : Tree::Iterator {
1676 explicit Iterator(Tree* aTree, Tree* aSecondTree,
1677 Tree* aThirdTree = nullptr)
1678 : Tree::Iterator(aTree),
1679 mSecondTree(aSecondTree),
1680 mThirdTree(aThirdTree) {}
1681
1682 Item<Iterator> begin() {
1683 return Item<Iterator>(this, *Tree::Iterator::begin());
1684 }
1685
1686 Item<Iterator> end() { return Item<Iterator>(this, nullptr); }
1687
1688 arena_t* Next() {
1689 arena_t* result = Tree::Iterator::Next();
1690 if (!result && mSecondTree) {
1691 new (this) Iterator(mSecondTree, mThirdTree);
1692 result = *Tree::Iterator::begin();
1693 }
1694 return result;
1695 }
1696
1697 private:
1698 Tree* mSecondTree;
1699 Tree* mThirdTree;
1700 };
1701
1702 Iterator iter() MOZ_REQUIRES(mLock) {
1703 #ifdef NON_RANDOM_ARENA_IDS
1704 return Iterator(&mArenas, &mPrivateArenas);
1705 #else
1706 return Iterator(&mArenas, &mPrivateArenas, &mMainThreadArenas);
1707 #endif
1708 }
1709
1710 inline arena_t* GetDefault() { return mDefaultArena; }
1711
1712 // Guards the collection of arenas. Must not be acquired while holding
1713 // a single arena's lock or mPurgeListLock.
1714 Mutex mLock MOZ_UNANNOTATED;
1715
1716 // Guards only the list of outstanding purge requests. Can be acquired
1717 // while holding gArenas.mLock, but must not be acquired or held while
1718 // holding or acquiring a single arena's lock.
1719 Mutex mPurgeListLock;
1720
1721 // We're running on the main thread which is set by a call to SetMainThread().
1722 bool IsOnMainThread() const {
1723 return mMainThreadId.isSome() &&
1724 ThreadIdEqual(mMainThreadId.value(), GetThreadId());
1725 }
1726
1727 // We're running on the main thread or SetMainThread() has never been called.
1728 bool IsOnMainThreadWeak() const {
1729 return mMainThreadId.isNothing() || IsOnMainThread();
1730 }
1731
1732 // After a fork set the new thread ID in the child.
1733 // This is done as the first thing after a fork, before mLock even re-inits.
1734 void ResetMainThread() MOZ_EXCLUDES(mLock) {
1735 // The post fork handler in the child can run from a MacOS worker thread,
1736 // so we can't set our main thread to it here. Instead we have to clear it.
1737 mMainThreadId = Nothing();
1738 }
1739
1740 void SetMainThread() MOZ_EXCLUDES(mLock) {
1741 MutexAutoLock lock(mLock);
1742 MOZ_ASSERT(mMainThreadId.isNothing());
1743 mMainThreadId = Some(GetThreadId());
1744 }
1745
1746 // This requires the lock to get a consistent count across all the active
1747 // + disposed arenas.
1748 uint64_t OperationsDisposedArenas() MOZ_REQUIRES(mLock) {
1749 return mNumOperationsDisposedArenas;
1750 }
1751
1752 // Enable or disable the lazy purge.
1753 //
1754 // Returns the former state of enablement.
1755 // This is a global setting for all arenas. Changing it may cause an
1756 // immediate purge for all arenas.
1757 bool SetDeferredPurge(bool aEnable) {
1758 MOZ_ASSERT(IsOnMainThreadWeak());
1759
1760 bool ret = mIsDeferredPurgeEnabled;
1761 {
1762 MutexAutoLock lock(mLock);
1763 mIsDeferredPurgeEnabled = aEnable;
1764 for (auto* arena : iter()) {
1765 MaybeMutexAutoLock lock(arena->mLock);
1766 arena->mIsDeferredPurgeEnabled = aEnable;
1767 }
1768 }
1769 if (ret != aEnable) {
1770 MayPurgeAll(PurgeIfThreshold);
1771 }
1772 return ret;
1773 }
1774
1775 bool IsDeferredPurgeEnabled() { return mIsDeferredPurgeEnabled; }
1776
1777 // Set aside a new purge request for aArena.
1778 void AddToOutstandingPurges(arena_t* aArena) MOZ_EXCLUDES(mPurgeListLock);
1779
1780 // Remove an unhandled purge request for aArena. Returns true if the arena
1781 // was in the list.
1782 bool RemoveFromOutstandingPurges(arena_t* aArena)
1783 MOZ_EXCLUDES(mPurgeListLock);
1784
1785 // Execute all outstanding purge requests, if any.
1786 void MayPurgeAll(PurgeCondition aCond);
1787
1788 // Purge some dirty memory, based on purge requests, returns true if there are
1789 // more to process.
1790 //
1791 // Returns a purge_result_t with the following meaning:
1792 // Done: Purge has completed for all arenas.
1793 // NeedsMore: There may be some arenas that needs to be purged now.
1794 // WantsLater: There is at least one arena that might want a purge later,
1795 // according to aReuseGraceMS.
1796 //
1797 // Parameters:
1798 // aPeekOnly: If true, check only if there is work to do without doing it.
1799 // aReuseGraceMS: The time to wait with purge after a
1800 // significant re-use happened for an arena.
1801 // aKeepGoing: If this returns false purging will cease.
1802 //
1803 // This could exit for 3 different reasons.
1804 // - There are no more requests (it returns false)
1805 // - There are more requests but aKeepGoing() returned false. (returns true)
1806 // - One arena is completely purged, (returns true).
1807 //
1808 purge_result_t MayPurgeSteps(bool aPeekOnly, uint32_t aReuseGraceMS,
1809 const Maybe<std::function<bool()>>& aKeepGoing);
1810
1811 private:
1812 const static arena_id_t MAIN_THREAD_ARENA_BIT = 0x1;
1813
1814 #ifndef NON_RANDOM_ARENA_IDS
1815 // Can be called with or without lock, depending on aTree.
1816 inline arena_t* GetByIdInternal(Tree& aTree, arena_id_t aArenaId);
1817
1818 arena_id_t MakeRandArenaId(bool aIsMainThreadOnly) const MOZ_REQUIRES(mLock);
1819 #endif
1820 static bool ArenaIdIsMainThreadOnly(arena_id_t aArenaId) {
1821 return aArenaId & MAIN_THREAD_ARENA_BIT;
1822 }
1823
1824 arena_t* mDefaultArena;
1825 arena_id_t mLastPublicArenaId MOZ_GUARDED_BY(mLock);
1826
1827 // Accessing mArenas and mPrivateArenas can only be done while holding mLock.
1828 Tree mArenas MOZ_GUARDED_BY(mLock);
1829 Tree mPrivateArenas MOZ_GUARDED_BY(mLock);
1830
1831 #ifdef NON_RANDOM_ARENA_IDS
1832 // Arena ids are pseudo-obfuscated/deobfuscated based on these values randomly
1833 // initialized on first use.
1834 arena_id_t mArenaIdKey = 0;
1835 int8_t mArenaIdRotation = 0;
1836 #else
1837 // Some mMainThreadArenas accesses to mMainThreadArenas can (and should) elude
1838 // the lock, see GetById().
1839 Tree mMainThreadArenas MOZ_GUARDED_BY(mLock);
1840 #endif
1841
1842 // Set only rarely and then propagated on the same thread to all arenas via
1843 // UpdateMaxDirty(). But also read in ExtraCommitPages on arbitrary threads.
1844 // TODO: Could ExtraCommitPages use arena_t::mMaxDirty instead ?
1845 Atomic<int32_t> mDefaultMaxDirtyPageModifier;
1846 // This is never changed except for forking, and it does not need mLock.
1847 Maybe<ThreadId> mMainThreadId;
1848
1849 // The number of operations that happened in arenas that have since been
1850 // destroyed.
1851 uint64_t mNumOperationsDisposedArenas = 0;
1852
1853 // Linked list of outstanding purges. This list has no particular order.
1854 // It is ok for an arena to be in this list even if mIsPurgePending is false,
1855 // it will just cause an extra round of a (most likely no-op) purge.
1856 // It is not ok to not be in this list but have mIsPurgePending set to true,
1857 // as this would prevent any future purges for this arena (except for during
1858 // MayPurgeStep or Purge).
1859 DoublyLinkedList<arena_t> mOutstandingPurges MOZ_GUARDED_BY(mPurgeListLock);
1860 // Flag if we should defer purge to later. Only ever set when holding the
1861 // collection lock. Read only during arena_t ctor.
1862 Atomic<bool> mIsDeferredPurgeEnabled;
1863 };
1864
1865 MOZ_RUNINIT static ArenaCollection gArenas;
1866
1867 // ******
1868 // Chunks.
1869 static AddressRadixTree<(sizeof(void*) << 3) - LOG2(kChunkSize)> gChunkRTree;
1870
1871 // Protects chunk-related data structures.
1872 static Mutex chunks_mtx;
1873
1874 // Trees of chunks that were previously allocated (trees differ only in node
1875 // ordering). These are used when allocating chunks, in an attempt to re-use
1876 // address space. Depending on function, different tree orderings are needed,
1877 // which is why there are two trees with the same contents.
1878 static RedBlackTree<extent_node_t, ExtentTreeSzTrait> gChunksBySize
1879 MOZ_GUARDED_BY(chunks_mtx);
1880 static RedBlackTree<extent_node_t, ExtentTreeTrait> gChunksByAddress
1881 MOZ_GUARDED_BY(chunks_mtx);
1882
1883 // Protects huge allocation-related data structures.
1884 static Mutex huge_mtx;
1885
1886 // Tree of chunks that are stand-alone huge allocations.
1887 static RedBlackTree<extent_node_t, ExtentTreeTrait> huge
1888 MOZ_GUARDED_BY(huge_mtx);
1889
1890 // Huge allocation statistics.
1891 static size_t huge_allocated MOZ_GUARDED_BY(huge_mtx);
1892 static size_t huge_mapped MOZ_GUARDED_BY(huge_mtx);
1893 static uint64_t huge_operations MOZ_GUARDED_BY(huge_mtx);
1894
1895 // **************************
1896 // base (internal allocation).
1897
1898 static Mutex base_mtx;
1899
1900 // Current pages that are being used for internal memory allocations. These
1901 // pages are carved up in cacheline-size quanta, so that there is no chance of
1902 // false cache line sharing.
1903 static void* base_pages MOZ_GUARDED_BY(base_mtx);
1904 static void* base_next_addr MOZ_GUARDED_BY(base_mtx);
1905 static void* base_next_decommitted MOZ_GUARDED_BY(base_mtx);
1906 // Address immediately past base_pages.
1907 static void* base_past_addr MOZ_GUARDED_BY(base_mtx);
1908 static size_t base_mapped MOZ_GUARDED_BY(base_mtx);
1909 static size_t base_committed MOZ_GUARDED_BY(base_mtx);
1910
1911 // ******
1912 // Arenas.
1913
1914 // The arena associated with the current thread (per
1915 // jemalloc_thread_local_arena) On OSX, __thread/thread_local circles back
1916 // calling malloc to allocate storage on first access on each thread, which
1917 // leads to an infinite loop, but pthread-based TLS somehow doesn't have this
1918 // problem.
1919 #if !defined(XP_DARWIN)
1920 static MOZ_THREAD_LOCAL(arena_t*) thread_arena;
1921 #else
1922 static detail::ThreadLocal<arena_t*, detail::ThreadLocalKeyStorage>
1923 thread_arena;
1924 #endif
1925
1926 // *****************************
1927 // Runtime configuration options.
1928
1929 #ifdef MALLOC_RUNTIME_CONFIG
1930 # define MALLOC_RUNTIME_VAR static
1931 #else
1932 # define MALLOC_RUNTIME_VAR static const
1933 #endif
1934
1935 enum PoisonType {
1936 NONE,
1937 SOME,
1938 ALL,
1939 };
1940
1941 MALLOC_RUNTIME_VAR bool opt_junk = false;
1942 MALLOC_RUNTIME_VAR bool opt_zero = false;
1943
1944 #ifdef EARLY_BETA_OR_EARLIER
1945 MALLOC_RUNTIME_VAR PoisonType opt_poison = ALL;
1946 #else
1947 MALLOC_RUNTIME_VAR PoisonType opt_poison = SOME;
1948 #endif
1949
1950 // Keep this larger than and ideally a multiple of kCacheLineSize;
1951 MALLOC_RUNTIME_VAR size_t opt_poison_size = 256;
1952 #ifndef MALLOC_RUNTIME_CONFIG
1953 static_assert(opt_poison_size >= kCacheLineSize);
1954 static_assert((opt_poison_size % kCacheLineSize) == 0);
1955 #endif
1956
1957 static bool opt_randomize_small = true;
1958
1959 // ***************************************************************************
1960 // Begin forward declarations.
1961
1962 static void* chunk_alloc(size_t aSize, size_t aAlignment, bool aBase);
1963 static void chunk_dealloc(void* aChunk, size_t aSize, ChunkType aType);
1964 #ifdef MOZ_DEBUG
1965 static void chunk_assert_zero(void* aPtr, size_t aSize);
1966 #endif
1967 static void huge_dalloc(void* aPtr, arena_t* aArena);
1968 static bool malloc_init_hard();
1969
1970 #ifndef XP_WIN
1971 # ifdef XP_DARWIN
1972 # define FORK_HOOK extern "C"
1973 # else
1974 # define FORK_HOOK static
1975 # endif
1976 FORK_HOOK void _malloc_prefork(void);
1977 FORK_HOOK void _malloc_postfork_parent(void);
1978 FORK_HOOK void _malloc_postfork_child(void);
1979 # ifdef XP_DARWIN
1980 FORK_HOOK void _malloc_postfork(void);
1981 # endif
1982 #endif
1983
1984 // End forward declarations.
1985 // ***************************************************************************
1986
1987 // FreeBSD's pthreads implementation calls malloc(3), so the malloc
1988 // implementation has to take pains to avoid infinite recursion during
1989 // initialization.
1990 // Returns whether the allocator was successfully initialized.
1991 static inline bool malloc_init() {
1992 if (!malloc_initialized) {
1993 return malloc_init_hard();
1994 }
1995 return true;
1996 }
1997
1998 static void _malloc_message(const char* p) {
1999 #if !defined(XP_WIN)
2000 # define _write write
2001 #endif
2002 // Pretend to check _write() errors to suppress gcc warnings about
2003 // warn_unused_result annotations in some versions of glibc headers.
2004 if (_write(STDERR_FILENO, p, (unsigned int)strlen(p)) < 0) {
2005 return;
2006 }
2007 }
2008
2009 template <typename... Args>
2010 static void _malloc_message(const char* p, Args... args) {
2011 _malloc_message(p);
2012 _malloc_message(args...);
2013 }
2014
2015 #ifdef ANDROID
2016 // Android's pthread.h does not declare pthread_atfork() until SDK 21.
2017 extern "C" MOZ_EXPORT int pthread_atfork(void (*)(void), void (*)(void),
2018 void (*)(void));
2019 #endif
2020
2021 // ***************************************************************************
2022 // Begin Utility functions/macros.
2023
2024 // Return the chunk address for allocation address a.
2025 static inline arena_chunk_t* GetChunkForPtr(const void* aPtr) {
2026 return (arena_chunk_t*)(uintptr_t(aPtr) & ~kChunkSizeMask);
2027 }
2028
2029 // Return the chunk offset of address a.
2030 static inline size_t GetChunkOffsetForPtr(const void* aPtr) {
2031 return (size_t)(uintptr_t(aPtr) & kChunkSizeMask);
2032 }
2033
2034 static inline const char* _getprogname(void) { return "<jemalloc>"; }
2035
2036 static inline void MaybePoison(void* aPtr, size_t aSize) {
2037 size_t size;
2038 switch (opt_poison) {
2039 case NONE:
2040 return;
2041 case SOME:
2042 size = std::min(aSize, opt_poison_size);
2043 break;
2044 case ALL:
2045 size = aSize;
2046 break;
2047 }
2048 MOZ_ASSERT(size != 0 && size <= aSize);
2049 memset(aPtr, kAllocPoison, size);
2050 }
2051
2052 // Fill the given range of memory with zeroes or junk depending on opt_junk and
2053 // opt_zero.
2054 static inline void ApplyZeroOrJunk(void* aPtr, size_t aSize) {
2055 if (opt_junk) {
2056 memset(aPtr, kAllocJunk, aSize);
2057 } else if (opt_zero) {
2058 memset(aPtr, 0, aSize);
2059 }
2060 }
2061
2062 // On Windows, delay crashing on OOM.
2063 #ifdef XP_WIN
2064
2065 // Implementation of VirtualAlloc wrapper (bug 1716727).
2066 namespace MozAllocRetries {
2067
2068 // Maximum retry count on OOM.
2069 constexpr size_t kMaxAttempts = 10;
2070 // Minimum delay time between retries. (The actual delay time may be larger. See
2071 // Microsoft's documentation for ::Sleep() for details.)
2072 constexpr size_t kDelayMs = 50;
2073
2074 using StallSpecs = ::mozilla::StallSpecs;
2075
2076 static constexpr StallSpecs maxStall = {.maxAttempts = kMaxAttempts,
2077 .delayMs = kDelayMs};
2078
2079 static inline StallSpecs GetStallSpecs() {
2080 # if defined(JS_STANDALONE)
2081 // GetGeckoProcessType() isn't available in this configuration. (SpiderMonkey
2082 // on Windows mostly skips this in favor of directly calling ::VirtualAlloc(),
2083 // though, so it's probably not going to matter whether we stall here or not.)
2084 return maxStall;
2085 # else
2086 switch (GetGeckoProcessType()) {
2087 // For the main process, stall for the maximum permissible time period. (The
2088 // main process is the most important one to keep alive.)
2089 case GeckoProcessType::GeckoProcessType_Default:
2090 return maxStall;
2091
2092 // For all other process types, stall for at most half as long.
2093 default:
2094 return {.maxAttempts = maxStall.maxAttempts / 2,
2095 .delayMs = maxStall.delayMs};
2096 }
2097 # endif
2098 }
2099
2100 } // namespace MozAllocRetries
2101
2102 namespace mozilla {
2103
2104 StallSpecs GetAllocatorStallSpecs() {
2105 return ::MozAllocRetries::GetStallSpecs();
2106 }
2107
2108 // Drop-in wrapper around VirtualAlloc. When out of memory, may attempt to stall
2109 // and retry rather than returning immediately, in hopes that the page file is
2110 // about to be expanded by Windows.
2111 //
2112 // Ref:
2113 // https://docs.microsoft.com/en-us/troubleshoot/windows-client/performance/slow-page-file-growth-memory-allocation-errors
2114 void* MozVirtualAlloc(void* lpAddress, size_t dwSize, uint32_t flAllocationType,
2115 uint32_t flProtect) {
2116 using namespace MozAllocRetries;
2117
2118 DWORD const lastError = ::GetLastError();
2119
2120 constexpr auto IsOOMError = [] {
2121 switch (::GetLastError()) {
2122 // This is the usual error result from VirtualAlloc for OOM.
2123 case ERROR_COMMITMENT_LIMIT:
2124 // Although rare, this has also been observed in low-memory situations.
2125 // (Presumably this means Windows can't allocate enough kernel-side space
2126 // for its own internal representation of the process's virtual address
2127 // space.)
2128 case ERROR_NOT_ENOUGH_MEMORY:
2129 return true;
2130 }
2131 return false;
2132 };
2133
2134 {
2135 void* ptr = ::VirtualAlloc(lpAddress, dwSize, flAllocationType, flProtect);
2136 if (MOZ_LIKELY(ptr)) return ptr;
2137
2138 // We can't do anything for errors other than OOM...
2139 if (!IsOOMError()) return nullptr;
2140 // ... or if this wasn't a request to commit memory in the first place.
2141 // (This function has no strategy for resolving MEM_RESERVE failures.)
2142 if (!(flAllocationType & MEM_COMMIT)) return nullptr;
2143 }
2144
2145 // Retry as many times as desired (possibly zero).
2146 const StallSpecs stallSpecs = GetStallSpecs();
2147
2148 const auto ret =
2149 stallSpecs.StallAndRetry(&::Sleep, [&]() -> std::optional<void*> {
2150 void* ptr =
2151 ::VirtualAlloc(lpAddress, dwSize, flAllocationType, flProtect);
2152
2153 if (ptr) {
2154 // The OOM status has been handled, and should not be reported to
2155 // telemetry.
2156 if (IsOOMError()) {
2157 ::SetLastError(lastError);
2158 }
2159 return ptr;
2160 }
2161
2162 // Failure for some reason other than OOM.
2163 if (!IsOOMError()) {
2164 return nullptr;
2165 }
2166
2167 return std::nullopt;
2168 });
2169
2170 return ret.value_or(nullptr);
2171 }
2172
2173 } // namespace mozilla
2174
2175 #endif // XP_WIN
2176
2177 // ***************************************************************************
2178
2179 static inline void pages_decommit(void* aAddr, size_t aSize) {
2180 #ifdef XP_WIN
2181 // The region starting at addr may have been allocated in multiple calls
2182 // to VirtualAlloc and recycled, so decommitting the entire region in one
2183 // go may not be valid. However, since we allocate at least a chunk at a
2184 // time, we may touch any region in chunksized increments.
2185 size_t pages_size = std::min(aSize, kChunkSize - GetChunkOffsetForPtr(aAddr));
2186 while (aSize > 0) {
2187 // This will cause Access Violation on read and write and thus act as a
2188 // guard page or region as well.
2189 if (!VirtualFree(aAddr, pages_size, MEM_DECOMMIT)) {
2190 MOZ_CRASH();
2191 }
2192 aAddr = (void*)((uintptr_t)aAddr + pages_size);
2193 aSize -= pages_size;
2194 pages_size = std::min(aSize, kChunkSize);
2195 }
2196 #else
2197 if (mmap(aAddr, aSize, PROT_NONE, MAP_FIXED | MAP_PRIVATE | MAP_ANON, -1,
2198 0) == MAP_FAILED) {
2199 // We'd like to report the OOM for our tooling, but we can't allocate
2200 // memory at this point, so avoid the use of printf.
2201 const char out_of_mappings[] =
2202 "[unhandlable oom] Failed to mmap, likely no more mappings "
2203 "available " __FILE__ " : " MOZ_STRINGIFY(__LINE__);
2204 if (errno == ENOMEM) {
2205 # ifndef ANDROID
2206 fputs(out_of_mappings, stderr);
2207 fflush(stderr);
2208 # endif
2209 MOZ_CRASH_ANNOTATE(out_of_mappings);
2210 }
2211 MOZ_REALLY_CRASH(__LINE__);
2212 }
2213 MozTagAnonymousMemory(aAddr, aSize, "jemalloc-decommitted");
2214 #endif
2215 }
2216
2217 // Commit pages. Returns whether pages were committed.
2218 [[nodiscard]] static inline bool pages_commit(void* aAddr, size_t aSize) {
2219 #ifdef XP_WIN
2220 // The region starting at addr may have been allocated in multiple calls
2221 // to VirtualAlloc and recycled, so committing the entire region in one
2222 // go may not be valid. However, since we allocate at least a chunk at a
2223 // time, we may touch any region in chunksized increments.
2224 size_t pages_size = std::min(aSize, kChunkSize - GetChunkOffsetForPtr(aAddr));
2225 while (aSize > 0) {
2226 if (!MozVirtualAlloc(aAddr, pages_size, MEM_COMMIT, PAGE_READWRITE)) {
2227 return false;
2228 }
2229 aAddr = (void*)((uintptr_t)aAddr + pages_size);
2230 aSize -= pages_size;
2231 pages_size = std::min(aSize, kChunkSize);
2232 }
2233 #else
2234 if (mmap(aAddr, aSize, PROT_READ | PROT_WRITE,
2235 MAP_FIXED | MAP_PRIVATE | MAP_ANON, -1, 0) == MAP_FAILED) {
2236 return false;
2237 }
2238 MozTagAnonymousMemory(aAddr, aSize, "jemalloc");
2239 #endif
2240 return true;
2241 }
2242
2243 // Initialize base allocation data structures.
2244 static void base_init() MOZ_REQUIRES(gInitLock) {
2245 base_mtx.Init();
2246 MOZ_PUSH_IGNORE_THREAD_SAFETY
2247 base_mapped = 0;
2248 base_committed = 0;
2249 MOZ_POP_THREAD_SAFETY
2250 }
2251
2252 static bool base_pages_alloc(size_t minsize) MOZ_REQUIRES(base_mtx) {
2253 size_t csize;
2254 size_t pminsize;
2255
2256 MOZ_ASSERT(minsize != 0);
2257 csize = CHUNK_CEILING(minsize);
2258 base_pages = chunk_alloc(csize, kChunkSize, true);
2259 if (!base_pages) {
2260 return true;
2261 }
2262 base_next_addr = base_pages;
2263 base_past_addr = (void*)((uintptr_t)base_pages + csize);
2264 // Leave enough pages for minsize committed, since otherwise they would
2265 // have to be immediately recommitted.
2266 pminsize = PAGE_CEILING(minsize);
2267 base_next_decommitted = (void*)((uintptr_t)base_pages + pminsize);
2268 if (pminsize < csize) {
2269 pages_decommit(base_next_decommitted, csize - pminsize);
2270 }
2271 base_mapped += csize;
2272 base_committed += pminsize;
2273
2274 return false;
2275 }
2276
2277 static void* base_alloc(size_t aSize) {
2278 void* ret;
2279 size_t csize;
2280
2281 // Round size up to nearest multiple of the cacheline size.
2282 csize = CACHELINE_CEILING(aSize);
2283
2284 MutexAutoLock lock(base_mtx);
2285 // Make sure there's enough space for the allocation.
2286 if ((uintptr_t)base_next_addr + csize > (uintptr_t)base_past_addr) {
2287 if (base_pages_alloc(csize)) {
2288 return nullptr;
2289 }
2290 }
2291 // Allocate.
2292 ret = base_next_addr;
2293 base_next_addr = (void*)((uintptr_t)base_next_addr + csize);
2294 // Make sure enough pages are committed for the new allocation.
2295 if ((uintptr_t)base_next_addr > (uintptr_t)base_next_decommitted) {
2296 void* pbase_next_addr = (void*)(PAGE_CEILING((uintptr_t)base_next_addr));
2297
2298 if (!pages_commit(
2299 base_next_decommitted,
2300 (uintptr_t)pbase_next_addr - (uintptr_t)base_next_decommitted)) {
2301 return nullptr;
2302 }
2303
2304 base_committed +=
2305 (uintptr_t)pbase_next_addr - (uintptr_t)base_next_decommitted;
2306 base_next_decommitted = pbase_next_addr;
2307 }
2308
2309 return ret;
2310 }
2311
2312 static void* base_calloc(size_t aNumber, size_t aSize) {
2313 void* ret = base_alloc(aNumber * aSize);
2314 if (ret) {
2315 memset(ret, 0, aNumber * aSize);
2316 }
2317 return ret;
2318 }
2319
2320 // A specialization of the base allocator with a free list.
2321 template <typename T>
2322 struct TypedBaseAlloc {
2323 static T* sFirstFree;
2324
2325 static size_t size_of() { return sizeof(T); }
2326
2327 static T* alloc() {
2328 T* ret;
2329
2330 base_mtx.Lock();
2331 if (sFirstFree) {
2332 ret = sFirstFree;
2333 sFirstFree = *(T**)ret;
2334 base_mtx.Unlock();
2335 } else {
2336 base_mtx.Unlock();
2337 ret = (T*)base_alloc(size_of());
2338 }
2339
2340 return ret;
2341 }
2342
2343 static void dealloc(T* aNode) {
2344 MutexAutoLock lock(base_mtx);
2345 *(T**)aNode = sFirstFree;
2346 sFirstFree = aNode;
2347 }
2348 };
2349
2350 using ExtentAlloc = TypedBaseAlloc<extent_node_t>;
2351
2352 template <>
2353 extent_node_t* ExtentAlloc::sFirstFree = nullptr;
2354
2355 template <>
2356 arena_t* TypedBaseAlloc<arena_t>::sFirstFree = nullptr;
2357
2358 template <>
2359 size_t TypedBaseAlloc<arena_t>::size_of() {
2360 // Allocate enough space for trailing bins.
2361 return sizeof(arena_t) + (sizeof(arena_bin_t) * NUM_SMALL_CLASSES);
2362 }
2363
2364 template <typename T>
2365 struct BaseAllocFreePolicy {
2366 void operator()(T* aPtr) { TypedBaseAlloc<T>::dealloc(aPtr); }
2367 };
2368
2369 using UniqueBaseNode =
2370 UniquePtr<extent_node_t, BaseAllocFreePolicy<extent_node_t>>;
2371
2372 // End Utility functions/macros.
2373 // ***************************************************************************
2374 // Begin chunk management functions.
2375
2376 #ifdef XP_WIN
2377
2378 static void* pages_map(void* aAddr, size_t aSize) {
2379 void* ret = nullptr;
2380 ret = MozVirtualAlloc(aAddr, aSize, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);
2381 return ret;
2382 }
2383
2384 static void pages_unmap(void* aAddr, size_t aSize) {
2385 if (VirtualFree(aAddr, 0, MEM_RELEASE) == 0) {
2386 _malloc_message(_getprogname(), ": (malloc) Error in VirtualFree()\n");
2387 }
2388 }
2389 #else
2390
2391 static void pages_unmap(void* aAddr, size_t aSize) {
2392 if (munmap(aAddr, aSize) == -1) {
2393 char buf[64];
2394
2395 if (strerror_r(errno, buf, sizeof(buf)) == 0) {
2396 _malloc_message(_getprogname(), ": (malloc) Error in munmap(): ", buf,
2397 "\n");
2398 }
2399 }
2400 }
2401
2402 static void* pages_map(void* aAddr, size_t aSize) {
2403 void* ret;
2404 # if defined(__ia64__) || \
2405 (defined(__sparc__) && defined(__arch64__) && defined(__linux__))
2406 // The JS engine assumes that all allocated pointers have their high 17 bits
2407 // clear, which ia64's mmap doesn't support directly. However, we can emulate
2408 // it by passing mmap an "addr" parameter with those bits clear. The mmap will
2409 // return that address, or the nearest available memory above that address,
2410 // providing a near-guarantee that those bits are clear. If they are not, we
2411 // return nullptr below to indicate out-of-memory.
2412 //
2413 // The addr is chosen as 0x0000070000000000, which still allows about 120TB of
2414 // virtual address space.
2415 //
2416 // See Bug 589735 for more information.
2417 bool check_placement = true;
2418 if (!aAddr) {
2419 aAddr = (void*)0x0000070000000000;
2420 check_placement = false;
2421 }
2422 # endif
2423
2424 # if defined(__sparc__) && defined(__arch64__) && defined(__linux__)
2425 const uintptr_t start = 0x0000070000000000ULL;
2426 const uintptr_t end = 0x0000800000000000ULL;
2427
2428 // Copied from js/src/gc/Memory.cpp and adapted for this source
2429 uintptr_t hint;
2430 void* region = MAP_FAILED;
2431 for (hint = start; region == MAP_FAILED && hint + aSize <= end;
2432 hint += kChunkSize) {
2433 region = mmap((void*)hint, aSize, PROT_READ | PROT_WRITE,
2434 MAP_PRIVATE | MAP_ANON, -1, 0);
2435 if (region != MAP_FAILED) {
2436 if (((size_t)region + (aSize - 1)) & 0xffff800000000000) {
2437 if (munmap(region, aSize)) {
2438 MOZ_ASSERT(errno == ENOMEM);
2439 }
2440 region = MAP_FAILED;
2441 }
2442 }
2443 }
2444 ret = region;
2445 # else
2446 // We don't use MAP_FIXED here, because it can cause the *replacement*
2447 // of existing mappings, and we only want to create new mappings.
2448 ret =
2449 mmap(aAddr, aSize, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANON, -1, 0);
2450 MOZ_ASSERT(ret);
2451 # endif
2452 if (ret == MAP_FAILED) {
2453 ret = nullptr;
2454 }
2455 # if defined(__ia64__) || \
2456 (defined(__sparc__) && defined(__arch64__) && defined(__linux__))
2457 // If the allocated memory doesn't have its upper 17 bits clear, consider it
2458 // as out of memory.
2459 else if ((long long)ret & 0xffff800000000000) {
2460 munmap(ret, aSize);
2461 ret = nullptr;
2462 }
2463 // If the caller requested a specific memory location, verify that's what mmap
2464 // returned.
2465 else if (check_placement && ret != aAddr) {
2466 # else
2467 else if (aAddr && ret != aAddr) {
2468 # endif
2469 // We succeeded in mapping memory, but not in the right place.
2470 pages_unmap(ret, aSize);
2471 ret = nullptr;
2472 }
2473 if (ret) {
2474 MozTagAnonymousMemory(ret, aSize, "jemalloc");
2475 }
2476
2477 # if defined(__ia64__) || \
2478 (defined(__sparc__) && defined(__arch64__) && defined(__linux__))
2479 MOZ_ASSERT(!ret || (!check_placement && ret) ||
2480 (check_placement && ret == aAddr));
2481 # else
2482 MOZ_ASSERT(!ret || (!aAddr && ret != aAddr) || (aAddr && ret == aAddr));
2483 # endif
2484 return ret;
2485 }
2486 #endif
2487
2488 #ifdef XP_DARWIN
2489 # define VM_COPY_MIN kChunkSize
2490 static inline void pages_copy(void* dest, const void* src, size_t n) {
2491 MOZ_ASSERT((void*)((uintptr_t)dest & ~gPageSizeMask) == dest);
2492 MOZ_ASSERT(n >= VM_COPY_MIN);
2493 MOZ_ASSERT((void*)((uintptr_t)src & ~gPageSizeMask) == src);
2494
2495 kern_return_t r = vm_copy(mach_task_self(), (vm_address_t)src, (vm_size_t)n,
2496 (vm_address_t)dest);
2497 if (r != KERN_SUCCESS) {
2498 MOZ_CRASH("vm_copy() failed");
2499 }
2500 }
2501
2502 #endif
2503
2504 template <size_t Bits>
2505 bool AddressRadixTree<Bits>::Init() {
2506 mLock.Init();
2507 mRoot = (void**)base_calloc(1 << kBitsAtLevel1, sizeof(void*));
2508 return mRoot;
2509 }
2510
2511 template <size_t Bits>
2512 void** AddressRadixTree<Bits>::GetSlotInternal(void* aAddr, bool aCreate) {
2513 uintptr_t key = reinterpret_cast<uintptr_t>(aAddr);
2514 uintptr_t subkey;
2515 unsigned i, lshift, height, bits;
2516 void** node;
2517 void** child;
2518
2519 for (i = lshift = 0, height = kHeight, node = mRoot; i < height - 1;
2520 i++, lshift += bits, node = child) {
2521 bits = i ? kBitsPerLevel : kBitsAtLevel1;
2522 subkey = (key << lshift) >> ((sizeof(void*) << 3) - bits);
2523 child = (void**)node[subkey];
2524 if (!child && aCreate) {
2525 child = (void**)base_calloc(1 << kBitsPerLevel, sizeof(void*));
2526 if (child) {
2527 node[subkey] = child;
2528 }
2529 }
2530 if (!child) {
2531 return nullptr;
2532 }
2533 }
2534
2535 // node is a leaf, so it contains values rather than node
2536 // pointers.
2537 bits = i ? kBitsPerLevel : kBitsAtLevel1;
2538 subkey = (key << lshift) >> ((sizeof(void*) << 3) - bits);
2539 return &node[subkey];
2540 }
2541
2542 template <size_t Bits>
2543 void* AddressRadixTree<Bits>::Get(void* aAddr) {
2544 void* ret = nullptr;
2545
2546 void** slot = GetSlotIfExists(aAddr);
2547
2548 if (slot) {
2549 ret = *slot;
2550 }
2551 #ifdef MOZ_DEBUG
2552 MutexAutoLock lock(mLock);
2553
2554 // Suppose that it were possible for a jemalloc-allocated chunk to be
2555 // munmap()ped, followed by a different allocator in another thread re-using
2556 // overlapping virtual memory, all without invalidating the cached rtree
2557 // value. The result would be a false positive (the rtree would claim that
2558 // jemalloc owns memory that it had actually discarded). I don't think this
2559 // scenario is possible, but the following assertion is a prudent sanity
2560 // check.
2561 if (!slot) {
2562 // In case a slot has been created in the meantime.
2563 slot = GetSlotInternal(aAddr, false);
2564 }
2565 if (slot) {
2566 // The MutexAutoLock above should act as a memory barrier, forcing
2567 // the compiler to emit a new read instruction for *slot.
2568 MOZ_ASSERT(ret == *slot);
2569 } else {
2570 MOZ_ASSERT(ret == nullptr);
2571 }
2572 #endif
2573 return ret;
2574 }
2575
2576 template <size_t Bits>
2577 bool AddressRadixTree<Bits>::Set(void* aAddr, void* aValue) {
2578 MutexAutoLock lock(mLock);
2579 void** slot = GetOrCreateSlot(aAddr);
2580 if (slot) {
2581 *slot = aValue;
2582 }
2583 return slot;
2584 }
2585
2586 // pages_trim, chunk_alloc_mmap_slow and chunk_alloc_mmap were cherry-picked
2587 // from upstream jemalloc 3.4.1 to fix Mozilla bug 956501.
2588
2589 // Return the offset between a and the nearest aligned address at or below a.
2590 #define ALIGNMENT_ADDR2OFFSET(a, alignment) \
2591 ((size_t)((uintptr_t)(a) & ((alignment) - 1)))
2592
2593 // Return the smallest alignment multiple that is >= s.
2594 #define ALIGNMENT_CEILING(s, alignment) \
2595 (((s) + ((alignment) - 1)) & (~((alignment) - 1)))
2596
2597 static void* pages_trim(void* addr, size_t alloc_size, size_t leadsize,
2598 size_t size) {
2599 void* ret = (void*)((uintptr_t)addr + leadsize);
2600
2601 MOZ_ASSERT(alloc_size >= leadsize + size);
2602 #ifdef XP_WIN
2603 {
2604 void* new_addr;
2605
2606 pages_unmap(addr, alloc_size);
2607 new_addr = pages_map(ret, size);
2608 if (new_addr == ret) {
2609 return ret;
2610 }
2611 if (new_addr) {
2612 pages_unmap(new_addr, size);
2613 }
2614 return nullptr;
2615 }
2616 #else
2617 {
2618 size_t trailsize = alloc_size - leadsize - size;
2619
2620 if (leadsize != 0) {
2621 pages_unmap(addr, leadsize);
2622 }
2623 if (trailsize != 0) {
2624 pages_unmap((void*)((uintptr_t)ret + size), trailsize);
2625 }
2626 return ret;
2627 }
2628 #endif
2629 }
2630
2631 static void* chunk_alloc_mmap_slow(size_t size, size_t alignment) {
2632 void *ret, *pages;
2633 size_t alloc_size, leadsize;
2634
2635 alloc_size = size + alignment - gRealPageSize;
2636 // Beware size_t wrap-around.
2637 if (alloc_size < size) {
2638 return nullptr;
2639 }
2640 do {
2641 pages = pages_map(nullptr, alloc_size);
2642 if (!pages) {
2643 return nullptr;
2644 }
2645 leadsize =
2646 ALIGNMENT_CEILING((uintptr_t)pages, alignment) - (uintptr_t)pages;
2647 ret = pages_trim(pages, alloc_size, leadsize, size);
2648 } while (!ret);
2649
2650 MOZ_ASSERT(ret);
2651 return ret;
2652 }
2653
2654 static void* chunk_alloc_mmap(size_t size, size_t alignment) {
2655 void* ret;
2656 size_t offset;
2657
2658 // Ideally, there would be a way to specify alignment to mmap() (like
2659 // NetBSD has), but in the absence of such a feature, we have to work
2660 // hard to efficiently create aligned mappings. The reliable, but
2661 // slow method is to create a mapping that is over-sized, then trim the
2662 // excess. However, that always results in one or two calls to
2663 // pages_unmap().
2664 //
2665 // Optimistically try mapping precisely the right amount before falling
2666 // back to the slow method, with the expectation that the optimistic
2667 // approach works most of the time.
2668 ret = pages_map(nullptr, size);
2669 if (!ret) {
2670 return nullptr;
2671 }
2672 offset = ALIGNMENT_ADDR2OFFSET(ret, alignment);
2673 if (offset != 0) {
2674 pages_unmap(ret, size);
2675 return chunk_alloc_mmap_slow(size, alignment);
2676 }
2677
2678 MOZ_ASSERT(ret);
2679 return ret;
2680 }
2681
2682 // Purge and release the pages in the chunk of length `length` at `addr` to
2683 // the OS.
2684 // Returns whether the pages are guaranteed to be full of zeroes when the
2685 // function returns.
2686 // The force_zero argument explicitly requests that the memory is guaranteed
2687 // to be full of zeroes when the function returns.
2688 static bool pages_purge(void* addr, size_t length, bool force_zero) {
2689 pages_decommit(addr, length);
2690 return true;
2691 }
2692
2693 static void* chunk_recycle(size_t aSize, size_t aAlignment) {
2694 extent_node_t key;
2695
2696 size_t alloc_size = aSize + aAlignment - kChunkSize;
2697 // Beware size_t wrap-around.
2698 if (alloc_size < aSize) {
2699 return nullptr;
2700 }
2701 key.mAddr = nullptr;
2702 key.mSize = alloc_size;
2703 chunks_mtx.Lock();
2704 extent_node_t* node = gChunksBySize.SearchOrNext(&key);
2705 if (!node) {
2706 chunks_mtx.Unlock();
2707 return nullptr;
2708 }
2709 size_t leadsize = ALIGNMENT_CEILING((uintptr_t)node->mAddr, aAlignment) -
2710 (uintptr_t)node->mAddr;
2711 MOZ_ASSERT(node->mSize >= leadsize + aSize);
2712 size_t trailsize = node->mSize - leadsize - aSize;
2713 void* ret = (void*)((uintptr_t)node->mAddr + leadsize);
2714
2715 // All recycled chunks are zeroed (because they're purged) before being
2716 // recycled.
2717 MOZ_ASSERT(node->mChunkType == ZEROED_CHUNK);
2718
2719 // Remove node from the tree.
2720 gChunksBySize.Remove(node);
2721 gChunksByAddress.Remove(node);
2722 if (leadsize != 0) {
2723 // Insert the leading space as a smaller chunk.
2724 node->mSize = leadsize;
2725 gChunksBySize.Insert(node);
2726 gChunksByAddress.Insert(node);
2727 node = nullptr;
2728 }
2729 if (trailsize != 0) {
2730 // Insert the trailing space as a smaller chunk.
2731 if (!node) {
2732 // An additional node is required, but
2733 // TypedBaseAlloc::alloc() can cause a new base chunk to be
2734 // allocated. Drop chunks_mtx in order to avoid
2735 // deadlock, and if node allocation fails, deallocate
2736 // the result before returning an error.
2737 chunks_mtx.Unlock();
2738 node = ExtentAlloc::alloc();
2739 if (!node) {
2740 chunk_dealloc(ret, aSize, ZEROED_CHUNK);
2741 return nullptr;
2742 }
2743 chunks_mtx.Lock();
2744 }
2745 node->mAddr = (void*)((uintptr_t)(ret) + aSize);
2746 node->mSize = trailsize;
2747 node->mChunkType = ZEROED_CHUNK;
2748 gChunksBySize.Insert(node);
2749 gChunksByAddress.Insert(node);
2750 node = nullptr;
2751 }
2752
2753 gRecycledSize -= aSize;
2754
2755 chunks_mtx.Unlock();
2756
2757 if (node) {
2758 ExtentAlloc::dealloc(node);
2759 }
2760 if (!pages_commit(ret, aSize)) {
2761 return nullptr;
2762 }
2763
2764 return ret;
2765 }
2766
2767 static void chunks_init() MOZ_REQUIRES(gInitLock) {
2768 // Initialize chunks data.
2769 chunks_mtx.Init();
2770 MOZ_PUSH_IGNORE_THREAD_SAFETY
2771 gChunksBySize.Init();
2772 gChunksByAddress.Init();
2773 MOZ_POP_THREAD_SAFETY
2774 }
2775
2776 #ifdef XP_WIN
2777 // On Windows, calls to VirtualAlloc and VirtualFree must be matched, making it
2778 // awkward to recycle allocations of varying sizes. Therefore we only allow
2779 // recycling when the size equals the chunksize, unless deallocation is entirely
2780 // disabled.
2781 # define CAN_RECYCLE(size) ((size) == kChunkSize)
2782 #else
2783 # define CAN_RECYCLE(size) true
2784 #endif
2785
2786 // Allocates `size` bytes of system memory aligned for `alignment`.
2787 // `base` indicates whether the memory will be used for the base allocator
2788 // (e.g. base_alloc).
2789 // `zeroed` is an outvalue that returns whether the allocated memory is
2790 // guaranteed to be full of zeroes. It can be omitted when the caller doesn't
2791 // care about the result.
2792 static void* chunk_alloc(size_t aSize, size_t aAlignment, bool aBase) {
2793 void* ret = nullptr;
2794
2795 MOZ_ASSERT(aSize != 0);
2796 MOZ_ASSERT((aSize & kChunkSizeMask) == 0);
2797 MOZ_ASSERT(aAlignment != 0);
2798 MOZ_ASSERT((aAlignment & kChunkSizeMask) == 0);
2799
2800 // Base allocations can't be fulfilled by recycling because of
2801 // possible deadlock or infinite recursion.
2802 if (CAN_RECYCLE(aSize) && !aBase) {
2803 ret = chunk_recycle(aSize, aAlignment);
2804 }
2805 if (!ret) {
2806 ret = chunk_alloc_mmap(aSize, aAlignment);
2807 }
2808 if (ret && !aBase) {
2809 if (!gChunkRTree.Set(ret, ret)) {
2810 chunk_dealloc(ret, aSize, UNKNOWN_CHUNK);
2811 return nullptr;
2812 }
2813 }
2814
2815 MOZ_ASSERT(GetChunkOffsetForPtr(ret) == 0);
2816 return ret;
2817 }
2818
2819 #ifdef MOZ_DEBUG
2820 static void chunk_assert_zero(void* aPtr, size_t aSize) {
2821 // Only run this expensive check in a vigilant mode.
2822 # ifdef MALLOC_DEBUG_VIGILANT
2823 size_t i;
2824 size_t* p = (size_t*)(uintptr_t)aPtr;
2825
2826 for (i = 0; i < aSize / sizeof(size_t); i++) {
2827 MOZ_ASSERT(p[i] == 0);
2828 }
2829 # endif
2830 }
2831 #endif
2832
2833 static void chunk_record(void* aChunk, size_t aSize, ChunkType aType) {
2834 extent_node_t key;
2835
2836 if (aType != ZEROED_CHUNK) {
2837 if (pages_purge(aChunk, aSize, aType == HUGE_CHUNK)) {
2838 aType = ZEROED_CHUNK;
2839 }
2840 }
2841
2842 // Allocate a node before acquiring chunks_mtx even though it might not
2843 // be needed, because TypedBaseAlloc::alloc() may cause a new base chunk to
2844 // be allocated, which could cause deadlock if chunks_mtx were already
2845 // held.
2846 UniqueBaseNode xnode(ExtentAlloc::alloc());
2847 // Use xprev to implement conditional deferred deallocation of prev.
2848 UniqueBaseNode xprev;
2849
2850 // RAII deallocates xnode and xprev defined above after unlocking
2851 // in order to avoid potential dead-locks
2852 MutexAutoLock lock(chunks_mtx);
2853 key.mAddr = (void*)((uintptr_t)aChunk + aSize);
2854 extent_node_t* node = gChunksByAddress.SearchOrNext(&key);
2855 // Try to coalesce forward.
2856 if (node && node->mAddr == key.mAddr) {
2857 // Coalesce chunk with the following address range. This does
2858 // not change the position within gChunksByAddress, so only
2859 // remove/insert from/into gChunksBySize.
2860 gChunksBySize.Remove(node);
2861 node->mAddr = aChunk;
2862 node->mSize += aSize;
2863 if (node->mChunkType != aType) {
2864 node->mChunkType = RECYCLED_CHUNK;
2865 }
2866 gChunksBySize.Insert(node);
2867 } else {
2868 // Coalescing forward failed, so insert a new node.
2869 if (!xnode) {
2870 // TypedBaseAlloc::alloc() failed, which is an exceedingly
2871 // unlikely failure. Leak chunk; its pages have
2872 // already been purged, so this is only a virtual
2873 // memory leak.
2874 return;
2875 }
2876 node = xnode.release();
2877 node->mAddr = aChunk;
2878 node->mSize = aSize;
2879 node->mChunkType = aType;
2880 gChunksByAddress.Insert(node);
2881 gChunksBySize.Insert(node);
2882 }
2883
2884 // Try to coalesce backward.
2885 extent_node_t* prev = gChunksByAddress.Prev(node);
2886 if (prev && (void*)((uintptr_t)prev->mAddr + prev->mSize) == aChunk) {
2887 // Coalesce chunk with the previous address range. This does
2888 // not change the position within gChunksByAddress, so only
2889 // remove/insert node from/into gChunksBySize.
2890 gChunksBySize.Remove(prev);
2891 gChunksByAddress.Remove(prev);
2892
2893 gChunksBySize.Remove(node);
2894 node->mAddr = prev->mAddr;
2895 node->mSize += prev->mSize;
2896 if (node->mChunkType != prev->mChunkType) {
2897 node->mChunkType = RECYCLED_CHUNK;
2898 }
2899 gChunksBySize.Insert(node);
2900
2901 xprev.reset(prev);
2902 }
2903
2904 gRecycledSize += aSize;
2905 }
2906
2907 static void chunk_dealloc(void* aChunk, size_t aSize, ChunkType aType) {
2908 MOZ_ASSERT(aChunk);
2909 MOZ_ASSERT(GetChunkOffsetForPtr(aChunk) == 0);
2910 MOZ_ASSERT(aSize != 0);
2911 MOZ_ASSERT((aSize & kChunkSizeMask) == 0);
2912
2913 gChunkRTree.Unset(aChunk);
2914
2915 if (CAN_RECYCLE(aSize)) {
2916 size_t recycled_so_far = gRecycledSize;
2917 // In case some race condition put us above the limit.
2918 if (recycled_so_far < gRecycleLimit) {
2919 size_t recycle_remaining = gRecycleLimit - recycled_so_far;
2920 size_t to_recycle;
2921 if (aSize > recycle_remaining) {
2922 to_recycle = recycle_remaining;
2923 // Drop pages that would overflow the recycle limit
2924 pages_trim(aChunk, aSize, 0, to_recycle);
2925 } else {
2926 to_recycle = aSize;
2927 }
2928 chunk_record(aChunk, to_recycle, aType);
2929 return;
2930 }
2931 }
2932
2933 pages_unmap(aChunk, aSize);
2934 }
2935
2936 #undef CAN_RECYCLE
2937
2938 // End chunk management functions.
2939 // ***************************************************************************
2940 // Begin arena.
2941
2942 static inline arena_t* thread_local_arena(bool enabled) {
2943 arena_t* arena;
2944
2945 if (enabled) {
2946 // The arena will essentially be leaked if this function is
2947 // called with `false`, but it doesn't matter at the moment.
2948 // because in practice nothing actually calls this function
2949 // with `false`, except maybe at shutdown.
2950 arena =
2951 gArenas.CreateArena(/* aIsPrivate = */ false, /* aParams = */ nullptr);
2952 } else {
2953 arena = gArenas.GetDefault();
2954 }
2955 thread_arena.set(arena);
2956 return arena;
2957 }
2958
2959 inline void MozJemalloc::jemalloc_thread_local_arena(bool aEnabled) {
2960 if (malloc_init()) {
2961 thread_local_arena(aEnabled);
2962 }
2963 }
2964
2965 // Choose an arena based on a per-thread value.
2966 static inline arena_t* choose_arena(size_t size) {
2967 arena_t* ret = nullptr;
2968
2969 // We can only use TLS if this is a PIC library, since for the static
2970 // library version, libc's malloc is used by TLS allocation, which
2971 // introduces a bootstrapping issue.
2972
2973 if (size > kMaxQuantumClass) {
2974 // Force the default arena for larger allocations.
2975 ret = gArenas.GetDefault();
2976 } else {
2977 // Check TLS to see if our thread has requested a pinned arena.
2978 ret = thread_arena.get();
2979 // If ret is non-null, it must not be in the first page.
2980 MOZ_DIAGNOSTIC_ASSERT_IF(ret, (size_t)ret >= gPageSize);
2981 if (!ret) {
2982 // Nothing in TLS. Pin this thread to the default arena.
2983 ret = thread_local_arena(false);
2984 }
2985 }
2986
2987 MOZ_DIAGNOSTIC_ASSERT(ret);
2988 return ret;
2989 }
2990
2991 inline uint8_t arena_t::FindFreeBitInMask(uint32_t aMask, uint32_t& aRng) {
2992 if (mPRNG != nullptr) {
2993 if (aRng == UINT_MAX) {
2994 aRng = mPRNG->next() % 32;
2995 }
2996 uint8_t bitIndex;
2997 // RotateRight asserts when provided bad input.
2998 aMask = aRng ? RotateRight(aMask, aRng)
2999 : aMask; // Rotate the mask a random number of slots
3000 bitIndex = CountTrailingZeroes32(aMask);
3001 return (bitIndex + aRng) % 32;
3002 }
3003 return CountTrailingZeroes32(aMask);
3004 }
3005
3006 inline void* arena_t::ArenaRunRegAlloc(arena_run_t* aRun, arena_bin_t* aBin) {
3007 void* ret;
3008 unsigned i, mask, bit, regind;
3009 uint32_t rndPos = UINT_MAX;
3010
3011 MOZ_DIAGNOSTIC_ASSERT(aRun->mMagic == ARENA_RUN_MAGIC);
3012 MOZ_ASSERT(aRun->mRegionsMinElement < aBin->mRunNumRegionsMask);
3013
3014 // Move the first check outside the loop, so that aRun->mRegionsMinElement can
3015 // be updated unconditionally, without the possibility of updating it
3016 // multiple times.
3017 i = aRun->mRegionsMinElement;
3018 mask = aRun->mRegionsMask[i];
3019 if (mask != 0) {
3020 bit = FindFreeBitInMask(mask, rndPos);
3021
3022 regind = ((i << (LOG2(sizeof(int)) + 3)) + bit);
3023 MOZ_ASSERT(regind < aBin->mRunNumRegions);
3024 ret = (void*)(((uintptr_t)aRun) + aBin->mRunFirstRegionOffset +
3025 (aBin->mSizeClass * regind));
3026
3027 // Clear bit.
3028 mask ^= (1U << bit);
3029 aRun->mRegionsMask[i] = mask;
3030
3031 return ret;
3032 }
3033
3034 for (i++; i < aBin->mRunNumRegionsMask; i++) {
3035 mask = aRun->mRegionsMask[i];
3036 if (mask != 0) {
3037 bit = FindFreeBitInMask(mask, rndPos);
3038
3039 regind = ((i << (LOG2(sizeof(int)) + 3)) + bit);
3040 MOZ_ASSERT(regind < aBin->mRunNumRegions);
3041 ret = (void*)(((uintptr_t)aRun) + aBin->mRunFirstRegionOffset +
3042 (aBin->mSizeClass * regind));
3043
3044 // Clear bit.
3045 mask ^= (1U << bit);
3046 aRun->mRegionsMask[i] = mask;
3047
3048 // Make a note that nothing before this element
3049 // contains a free region.
3050 aRun->mRegionsMinElement = i; // Low payoff: + (mask == 0);
3051
3052 return ret;
3053 }
3054 }
3055 // Not reached.
3056 MOZ_DIAGNOSTIC_ASSERT(0);
3057 return nullptr;
3058 }
3059
3060 static inline void arena_run_reg_dalloc(arena_run_t* run, arena_bin_t* bin,
3061 void* ptr, size_t size) {
3062 uint32_t diff, regind;
3063 unsigned elm, bit;
3064
3065 MOZ_DIAGNOSTIC_ASSERT(run->mMagic == ARENA_RUN_MAGIC);
3066
3067 // Avoid doing division with a variable divisor if possible. Using
3068 // actual division here can reduce allocator throughput by over 20%!
3069 diff =
3070 (uint32_t)((uintptr_t)ptr - (uintptr_t)run - bin->mRunFirstRegionOffset);
3071
3072 MOZ_ASSERT(diff <=
3073 (static_cast<unsigned>(bin->mRunSizePages) << gPageSize2Pow));
3074 regind = diff / bin->mSizeDivisor;
3075
3076 MOZ_DIAGNOSTIC_ASSERT(diff == regind * size);
3077 MOZ_DIAGNOSTIC_ASSERT(regind < bin->mRunNumRegions);
3078
3079 elm = regind >> (LOG2(sizeof(int)) + 3);
3080 if (elm < run->mRegionsMinElement) {
3081 run->mRegionsMinElement = elm;
3082 }
3083 bit = regind - (elm << (LOG2(sizeof(int)) + 3));
3084 MOZ_RELEASE_ASSERT((run->mRegionsMask[elm] & (1U << bit)) == 0,
3085 "Double-free?");
3086 run->mRegionsMask[elm] |= (1U << bit);
3087 }
3088
3089 bool arena_t::SplitRun(arena_run_t* aRun, size_t aSize, bool aLarge,
3090 bool aZero) {
3091 arena_chunk_t* chunk = GetChunkForPtr(aRun);
3092 size_t old_ndirty = chunk->ndirty;
3093 size_t run_ind =
3094 (unsigned)((uintptr_t(aRun) - uintptr_t(chunk)) >> gPageSize2Pow);
3095 size_t total_pages =
3096 (chunk->map[run_ind].bits & ~gPageSizeMask) >> gPageSize2Pow;
3097 size_t need_pages = (aSize >> gPageSize2Pow);
3098 MOZ_ASSERT(need_pages > 0);
3099 MOZ_ASSERT(need_pages <= total_pages);
3100 size_t rem_pages = total_pages - need_pages;
3101
3102 MOZ_ASSERT((chunk->map[run_ind].bits & CHUNK_MAP_BUSY) == 0);
3103
3104 #ifdef MALLOC_DECOMMIT
3105 size_t i = 0;
3106 while (i < need_pages) {
3107 MOZ_ASSERT((chunk->map[run_ind + i].bits & CHUNK_MAP_BUSY) == 0);
3108
3109 // Commit decommitted pages if necessary. If a decommitted
3110 // page is encountered, commit all needed adjacent decommitted
3111 // pages in one operation, in order to reduce system call
3112 // overhead.
3113 if (chunk->map[run_ind + i].bits & CHUNK_MAP_DECOMMITTED) {
3114 // Advance i+j to just past the index of the last page
3115 // to commit. Clear CHUNK_MAP_DECOMMITTED along the way.
3116 size_t j;
3117 for (j = 0; i + j < need_pages &&
3118 (chunk->map[run_ind + i + j].bits & CHUNK_MAP_DECOMMITTED);
3119 j++) {
3120 // DECOMMITTED, MADVISED and FRESH are mutually exclusive.
3121 MOZ_ASSERT((chunk->map[run_ind + i + j].bits &
3122 (CHUNK_MAP_FRESH | CHUNK_MAP_MADVISED)) == 0);
3123 }
3124
3125 // Consider committing more pages to amortise calls to VirtualAlloc.
3126 // This only makes sense at the edge of our run hence the if condition
3127 // here.
3128 if (i + j == need_pages) {
3129 size_t extra_commit = ExtraCommitPages(j, rem_pages);
3130 for (; i + j < need_pages + extra_commit &&
3131 (chunk->map[run_ind + i + j].bits &
3132 CHUNK_MAP_MADVISED_OR_DECOMMITTED);
3133 j++) {
3134 MOZ_ASSERT((chunk->map[run_ind + i + j].bits &
3135 (CHUNK_MAP_FRESH | CHUNK_MAP_MADVISED)) == 0);
3136 }
3137 }
3138
3139 if (!pages_commit(
3140 (void*)(uintptr_t(chunk) + ((run_ind + i) << gPageSize2Pow)),
3141 j << gPageSize2Pow)) {
3142 return false;
3143 }
3144
3145 // pages_commit zeroes pages, so mark them as such if it succeeded.
3146 // That's checked further below to avoid manually zeroing the pages.
3147 for (size_t k = 0; k < j; k++) {
3148 chunk->map[run_ind + i + k].bits =
3149 (chunk->map[run_ind + i + k].bits & ~CHUNK_MAP_DECOMMITTED) |
3150 CHUNK_MAP_ZEROED | CHUNK_MAP_FRESH;
3151 }
3152
3153 mNumFresh += j;
3154 i += j;
3155 } else {
3156 i++;
3157 }
3158 }
3159 #endif
3160
3161 mRunsAvail.Remove(&chunk->map[run_ind]);
3162
3163 // Keep track of trailing unused pages for later use.
3164 if (rem_pages > 0) {
3165 chunk->map[run_ind + need_pages].bits =
3166 (rem_pages << gPageSize2Pow) |
3167 (chunk->map[run_ind + need_pages].bits & gPageSizeMask);
3168 chunk->map[run_ind + total_pages - 1].bits =
3169 (rem_pages << gPageSize2Pow) |
3170 (chunk->map[run_ind + total_pages - 1].bits & gPageSizeMask);
3171 mRunsAvail.Insert(&chunk->map[run_ind + need_pages]);
3172 }
3173
3174 for (size_t i = 0; i < need_pages; i++) {
3175 // Zero if necessary.
3176 if (aZero) {
3177 if ((chunk->map[run_ind + i].bits & CHUNK_MAP_ZEROED) == 0) {
3178 memset((void*)(uintptr_t(chunk) + ((run_ind + i) << gPageSize2Pow)), 0,
3179 gPageSize);
3180 // CHUNK_MAP_ZEROED is cleared below.
3181 }
3182 }
3183
3184 // Update dirty page accounting.
3185 if (chunk->map[run_ind + i].bits & CHUNK_MAP_DIRTY) {
3186 chunk->ndirty--;
3187 mNumDirty--;
3188 // CHUNK_MAP_DIRTY is cleared below.
3189 } else if (chunk->map[run_ind + i].bits & CHUNK_MAP_MADVISED) {
3190 mStats.committed++;
3191 mNumMAdvised--;
3192 }
3193
3194 if (chunk->map[run_ind + i].bits & CHUNK_MAP_FRESH) {
3195 mStats.committed++;
3196 mNumFresh--;
3197 }
3198
3199 // This bit has already been cleared
3200 MOZ_ASSERT(!(chunk->map[run_ind + i].bits & CHUNK_MAP_DECOMMITTED));
3201
3202 // Initialize the chunk map. This clears the dirty, zeroed and madvised
3203 // bits, decommitted is cleared above.
3204 if (aLarge) {
3205 chunk->map[run_ind + i].bits = CHUNK_MAP_LARGE | CHUNK_MAP_ALLOCATED;
3206 } else {
3207 chunk->map[run_ind + i].bits = size_t(aRun) | CHUNK_MAP_ALLOCATED;
3208 }
3209 }
3210
3211 // Set the run size only in the first element for large runs. This is
3212 // primarily a debugging aid, since the lack of size info for trailing
3213 // pages only matters if the application tries to operate on an
3214 // interior pointer.
3215 if (aLarge) {
3216 chunk->map[run_ind].bits |= aSize;
3217 }
3218
3219 if (chunk->ndirty == 0 && old_ndirty > 0 && !chunk->mIsPurging) {
3220 mChunksDirty.Remove(chunk);
3221 }
3222 return true;
3223 }
3224
3225 void arena_t::InitChunk(arena_chunk_t* aChunk, size_t aMinCommittedPages) {
3226 mStats.mapped += kChunkSize;
3227
3228 aChunk->arena = this;
3229
3230 // Claim that no pages are in use, since the header is merely overhead.
3231 aChunk->ndirty = 0;
3232
3233 aChunk->mIsPurging = false;
3234 aChunk->mDying = false;
3235
3236 // Setup the chunk's pages in two phases. First we mark which pages are
3237 // committed & decommitted and perform the decommit. Then we update the map
3238 // to create the runs.
3239
3240 // Clear the bits for the real header pages.
3241 size_t i;
3242 for (i = 0; i < gChunkHeaderNumPages - 1; i++) {
3243 aChunk->map[i].bits = 0;
3244 }
3245 mStats.committed += gChunkHeaderNumPages - 1;
3246
3247 // Decommit the last header page (=leading page) as a guard.
3248 pages_decommit((void*)(uintptr_t(aChunk) + (i << gPageSize2Pow)), gPageSize);
3249 aChunk->map[i++].bits = CHUNK_MAP_DECOMMITTED;
3250
3251 // If MALLOC_DECOMMIT is enabled then commit only the pages we're about to
3252 // use. Otherwise commit all of them.
3253 #ifdef MALLOC_DECOMMIT
3254 size_t n_fresh_pages =
3255 aMinCommittedPages +
3256 ExtraCommitPages(
3257 aMinCommittedPages,
3258 gChunkNumPages - gChunkHeaderNumPages - aMinCommittedPages - 1);
3259 #else
3260 size_t n_fresh_pages = gChunkNumPages - 1 - gChunkHeaderNumPages;
3261 #endif
3262
3263 // The committed pages are marked as Fresh. Our caller, SplitRun will update
3264 // this when it uses them.
3265 for (size_t j = 0; j < n_fresh_pages; j++) {
3266 aChunk->map[i + j].bits = CHUNK_MAP_ZEROED | CHUNK_MAP_FRESH;
3267 }
3268 i += n_fresh_pages;
3269 mNumFresh += n_fresh_pages;
3270
3271 #ifndef MALLOC_DECOMMIT
3272 // If MALLOC_DECOMMIT isn't defined then all the pages are fresh and setup in
3273 // the loop above.
3274 MOZ_ASSERT(i == gChunkNumPages - 1);
3275 #endif
3276
3277 // If MALLOC_DECOMMIT is defined, then this will decommit the remainder of the
3278 // chunk plus the last page which is a guard page, if it is not defined it
3279 // will only decommit the guard page.
3280 pages_decommit((void*)(uintptr_t(aChunk) + (i << gPageSize2Pow)),
3281 (gChunkNumPages - i) << gPageSize2Pow);
3282 for (; i < gChunkNumPages; i++) {
3283 aChunk->map[i].bits = CHUNK_MAP_DECOMMITTED;
3284 }
3285
3286 // aMinCommittedPages will create a valid run.
3287 MOZ_ASSERT(aMinCommittedPages > 0);
3288 MOZ_ASSERT(aMinCommittedPages <= gChunkNumPages - gChunkHeaderNumPages - 1);
3289
3290 // Create the run.
3291 aChunk->map[gChunkHeaderNumPages].bits |= gMaxLargeClass;
3292 aChunk->map[gChunkNumPages - 2].bits |= gMaxLargeClass;
3293 mRunsAvail.Insert(&aChunk->map[gChunkHeaderNumPages]);
3294
3295 #ifdef MALLOC_DOUBLE_PURGE
3296 new (&aChunk->chunks_madvised_elem) DoublyLinkedListElement<arena_chunk_t>();
3297 #endif
3298 }
3299
3300 bool arena_t::RemoveChunk(arena_chunk_t* aChunk) {
3301 aChunk->mDying = true;
3302
3303 // If the chunk has busy pages that means that a Purge() is in progress.
3304 // We can't remove the chunk now, instead Purge() will do it.
3305 if (aChunk->mIsPurging) {
3306 return false;
3307 }
3308
3309 if (aChunk->ndirty > 0) {
3310 MOZ_ASSERT(aChunk->arena == this);
3311 mChunksDirty.Remove(aChunk);
3312 mNumDirty -= aChunk->ndirty;
3313 mStats.committed -= aChunk->ndirty;
3314 }
3315
3316 // Count the number of madvised/fresh pages and update the stats.
3317 size_t madvised = 0;
3318 size_t fresh = 0;
3319 for (size_t i = gChunkHeaderNumPages; i < gChunkNumPages - 1; i++) {
3320 // There must not be any pages that are not fresh, madvised, decommitted
3321 // or dirty.
3322 MOZ_ASSERT(aChunk->map[i].bits &
3323 (CHUNK_MAP_FRESH_MADVISED_OR_DECOMMITTED | CHUNK_MAP_DIRTY));
3324 MOZ_ASSERT((aChunk->map[i].bits & CHUNK_MAP_BUSY) == 0);
3325
3326 if (aChunk->map[i].bits & CHUNK_MAP_MADVISED) {
3327 madvised++;
3328 } else if (aChunk->map[i].bits & CHUNK_MAP_FRESH) {
3329 fresh++;
3330 }
3331 }
3332
3333 mNumMAdvised -= madvised;
3334 mNumFresh -= fresh;
3335
3336 #ifdef MALLOC_DOUBLE_PURGE
3337 if (mChunksMAdvised.ElementProbablyInList(aChunk)) {
3338 mChunksMAdvised.remove(aChunk);
3339 }
3340 #endif
3341
3342 mStats.mapped -= kChunkSize;
3343 mStats.committed -= gChunkHeaderNumPages - 1;
3344
3345 return true;
3346 }
3347
3348 bool arena_chunk_t::IsEmpty() {
3349 return (map[gChunkHeaderNumPages].bits &
3350 (~gPageSizeMask | CHUNK_MAP_ALLOCATED)) == gMaxLargeClass;
3351 }
3352
3353 arena_chunk_t* arena_t::DemoteChunkToSpare(arena_chunk_t* aChunk) {
3354 if (mSpare) {
3355 if (!RemoveChunk(mSpare)) {
3356 // If we can't remove the spare chunk now purge will finish removing it
3357 // later. Set it to null so that the return below will return null and
3358 // our caller won't delete the chunk before Purge() is finished.
3359 mSpare = nullptr;
3360 }
3361 }
3362
3363 arena_chunk_t* chunk_dealloc = mSpare;
3364 mSpare = aChunk;
3365 return chunk_dealloc;
3366 }
3367
3368 arena_run_t* arena_t::AllocRun(size_t aSize, bool aLarge, bool aZero) {
3369 arena_run_t* run;
3370 arena_chunk_map_t* mapelm;
3371 arena_chunk_map_t key;
3372
3373 MOZ_ASSERT(aSize <= gMaxLargeClass);
3374 MOZ_ASSERT((aSize & gPageSizeMask) == 0);
3375
3376 // Search the arena's chunks for the lowest best fit.
3377 key.bits = aSize | CHUNK_MAP_KEY;
3378 mapelm = mRunsAvail.SearchOrNext(&key);
3379 if (mapelm) {
3380 arena_chunk_t* chunk = GetChunkForPtr(mapelm);
3381 size_t pageind =
3382 (uintptr_t(mapelm) - uintptr_t(chunk->map)) / sizeof(arena_chunk_map_t);
3383
3384 MOZ_ASSERT((chunk->map[pageind].bits & CHUNK_MAP_BUSY) == 0);
3385 run = (arena_run_t*)(uintptr_t(chunk) + (pageind << gPageSize2Pow));
3386 } else if (mSpare && !mSpare->mIsPurging) {
3387 // Use the spare.
3388 arena_chunk_t* chunk = mSpare;
3389 mSpare = nullptr;
3390 run = (arena_run_t*)(uintptr_t(chunk) +
3391 (gChunkHeaderNumPages << gPageSize2Pow));
3392 // Insert the run into the tree of available runs.
3393 MOZ_ASSERT((chunk->map[gChunkHeaderNumPages].bits & CHUNK_MAP_BUSY) == 0);
3394 mRunsAvail.Insert(&chunk->map[gChunkHeaderNumPages]);
3395 } else {
3396 // No usable runs. Create a new chunk from which to allocate
3397 // the run.
3398 arena_chunk_t* chunk =
3399 (arena_chunk_t*)chunk_alloc(kChunkSize, kChunkSize, false);
3400 if (!chunk) {
3401 return nullptr;
3402 }
3403
3404 InitChunk(chunk, aSize >> gPageSize2Pow);
3405 run = (arena_run_t*)(uintptr_t(chunk) +
3406 (gChunkHeaderNumPages << gPageSize2Pow));
3407 }
3408 // Update page map.
3409 return SplitRun(run, aSize, aLarge, aZero) ? run : nullptr;
3410 }
3411
3412 void arena_t::UpdateMaxDirty() {
3413 MaybeMutexAutoLock lock(mLock);
3414 int32_t modifier = gArenas.DefaultMaxDirtyPageModifier();
3415 if (modifier) {
3416 int32_t arenaOverride =
3417 modifier > 0 ? mMaxDirtyIncreaseOverride : mMaxDirtyDecreaseOverride;
3418 if (arenaOverride) {
3419 modifier = arenaOverride;
3420 }
3421 }
3422
3423 mMaxDirty =
3424 modifier >= 0 ? mMaxDirtyBase << modifier : mMaxDirtyBase >> -modifier;
3425 }
3426
3427 #ifdef MALLOC_DECOMMIT
3428
3429 size_t arena_t::ExtraCommitPages(size_t aReqPages, size_t aRemainingPages) {
3430 const int32_t modifier = gArenas.DefaultMaxDirtyPageModifier();
3431 if (modifier < 0) {
3432 return 0;
3433 }
3434
3435 // The maximum size of the page cache
3436 const size_t max_page_cache = mMaxDirty;
3437
3438 // The current size of the page cache, note that we use mNumFresh +
3439 // mNumMAdvised here but Purge() does not.
3440 const size_t page_cache = mNumDirty + mNumFresh + mNumMAdvised;
3441
3442 if (page_cache > max_page_cache) {
3443 // We're already exceeding our dirty page count even though we're trying
3444 // to allocate. This can happen due to fragmentation. Don't commit
3445 // excess memory since we're probably here due to a larger allocation and
3446 // small amounts of memory are certainly available in the page cache.
3447 return 0;
3448 }
3449 if (modifier > 0) {
3450 // If modifier is > 0 then we want to keep all the pages we can, but don't
3451 // exceed the size of the page cache. The subtraction cannot underflow
3452 // because of the condition above.
3453 return std::min(aRemainingPages, max_page_cache - page_cache);
3454 }
3455
3456 // The rest is arbitrary and involves a some assumptions. I've broken it down
3457 // into simple expressions to document them more clearly.
3458
3459 // Assumption 1: a quarter of mMaxDirty is a sensible "minimum
3460 // target" for the dirty page cache. Likewise 3 quarters is a sensible
3461 // "maximum target". Note that for the maximum we avoid using the whole page
3462 // cache now so that a free that follows this allocation doesn't immeidatly
3463 // call Purge (churning memory).
3464 const size_t min = max_page_cache / 4;
3465 const size_t max = 3 * max_page_cache / 4;
3466
3467 // Assumption 2: Committing 32 pages at a time is sufficient to amortise
3468 // VirtualAlloc costs.
3469 size_t amortisation_threshold = 32;
3470
3471 // extra_pages is the number of additional pages needed to meet
3472 // amortisation_threshold.
3473 size_t extra_pages = aReqPages < amortisation_threshold
3474 ? amortisation_threshold - aReqPages
3475 : 0;
3476
3477 // If committing extra_pages isn't enough to hit the minimum target then
3478 // increase it.
3479 if (page_cache + extra_pages < min) {
3480 extra_pages = min - page_cache;
3481 } else if (page_cache + extra_pages > max) {
3482 // If committing extra_pages would exceed our maximum target then it may
3483 // still be useful to allocate extra pages. One of the reasons this can
3484 // happen could be fragmentation of the cache,
3485
3486 // Therefore reduce the amortisation threshold so that we might allocate
3487 // some extra pages but avoid exceeding the dirty page cache.
3488 amortisation_threshold /= 2;
3489 extra_pages = std::min(aReqPages < amortisation_threshold
3490 ? amortisation_threshold - aReqPages
3491 : 0,
3492 max_page_cache - page_cache);
3493 }
3494
3495 // Cap extra_pages to aRemainingPages and adjust aRemainingPages. We will
3496 // commit at least this many extra pages.
3497 extra_pages = std::min(extra_pages, aRemainingPages);
3498
3499 // Finally if commiting a small number of additional pages now can prevent
3500 // a small commit later then try to commit a little more now, provided we
3501 // don't exceed max_page_cache.
3502 if ((aRemainingPages - extra_pages) < amortisation_threshold / 2 &&
3503 (page_cache + aRemainingPages) < max_page_cache) {
3504 return aRemainingPages;
3505 }
3506
3507 return extra_pages;
3508 }
3509 #endif
3510
3511 arena_t::PurgeResult arena_t::Purge(PurgeCondition aCond) {
3512 arena_chunk_t* chunk;
3513
3514 // The first critical section will find a chunk and mark dirty pages in it as
3515 // busy.
3516 {
3517 MaybeMutexAutoLock lock(mLock);
3518
3519 if (mMustDeleteAfterPurge) {
3520 mIsPurgePending = false;
3521 return Dying;
3522 }
3523
3524 #ifdef MOZ_DEBUG
3525 size_t ndirty = 0;
3526 for (auto* chunk : mChunksDirty.iter()) {
3527 ndirty += chunk->ndirty;
3528 }
3529 // Not all dirty chunks are in mChunksDirty as others might be being Purged.
3530 MOZ_ASSERT(ndirty <= mNumDirty);
3531 #endif
3532
3533 if (!ShouldContinuePurge(aCond)) {
3534 mIsPurgePending = false;
3535 return Done;
3536 }
3537
3538 // Take a single chunk and attempt to purge some of its dirty pages. The
3539 // loop below will purge memory from the chunk until either:
3540 // * The dirty page count for the arena hits its target,
3541 // * Another thread attempts to delete this chunk, or
3542 // * The chunk has no more dirty pages.
3543 // In any of these cases the loop will break and Purge() will return, which
3544 // means it may return before the arena meets its dirty page count target,
3545 // the return value is used by the caller to call Purge() again where it
3546 // will take the next chunk with dirty pages.
3547 chunk = mChunksDirty.Last();
3548 if (!chunk) {
3549 // There are chunks with dirty pages (because mNumDirty > 0 above) but
3550 // they're not in mChunksDirty. That can happen if they're busy being
3551 // purged by other threads.
3552 // We have to clear the flag to preserve the invariant that if Purge()
3553 // returns false the flag is clear, if there's more purging work to do in
3554 // other chunks then either other calls to Purge() (in other threads) will
3555 // handle it or we rely on ShouldStartPurge() returning true at some point
3556 // in the future.
3557 mIsPurgePending = false;
3558 return Busy;
3559 }
3560 MOZ_ASSERT(chunk->ndirty > 0);
3561
3562 // Mark the chunk as busy so it won't be deleted and remove it from
3563 // mChunksDirty so we're the only thread purging it.
3564 MOZ_ASSERT(!chunk->mIsPurging);
3565 mChunksDirty.Remove(chunk);
3566 chunk->mIsPurging = true;
3567 } // MaybeMutexAutoLock
3568
3569 // True if we should continue purging memory from this arena.
3570 bool continue_purge_arena = true;
3571
3572 // True if we should continue purging memory in this chunk.
3573 bool continue_purge_chunk = true;
3574
3575 // True if at least one Purge operation has occured and therefore we need to
3576 // call FinishPurgingInChunk() before returning.
3577 bool purged_once = false;
3578
3579 while (continue_purge_chunk && continue_purge_arena) {
3580 // This structure is used to communicate between the two PurgePhase
3581 // functions.
3582 PurgeInfo purge_info(*this, chunk);
3583
3584 {
3585 // Phase 1: Find pages that need purging.
3586 MaybeMutexAutoLock lock(purge_info.mArena.mLock);
3587 MOZ_ASSERT(chunk->mIsPurging);
3588
3589 if (purge_info.mArena.mMustDeleteAfterPurge) {
3590 chunk->mIsPurging = false;
3591 purge_info.mArena.mIsPurgePending = false;
3592 return Dying;
3593 }
3594
3595 continue_purge_chunk = purge_info.FindDirtyPages(purged_once);
3596 continue_purge_arena = purge_info.mArena.ShouldContinuePurge(aCond);
3597
3598 // The code below will exit returning false if these are both false, so
3599 // clear mIsDeferredPurgeNeeded while we still hold the lock.
3600 if (!continue_purge_chunk && !continue_purge_arena) {
3601 purge_info.mArena.mIsPurgePending = false;
3602 }
3603 }
3604 if (!continue_purge_chunk) {
3605 if (chunk->mDying) {
3606 // Phase one already unlinked the chunk from structures, we just need to
3607 // release the memory.
3608 chunk_dealloc((void*)chunk, kChunkSize, ARENA_CHUNK);
3609 }
3610 // There's nothing else to do here, our caller may execute Purge() again
3611 // if continue_purge_arena is true.
3612 return continue_purge_arena ? Continue : Done;
3613 }
3614
3615 #ifdef MALLOC_DECOMMIT
3616 pages_decommit(purge_info.DirtyPtr(), purge_info.DirtyLenBytes());
3617 #else
3618 # ifdef XP_SOLARIS
3619 posix_madvise(purge_info.DirtyPtr(), purge_info.DirtyLenBytes(), MADV_FREE);
3620 # else
3621 madvise(purge_info.DirtyPtr(), purge_info.DirtyLenBytes(), MADV_FREE);
3622 # endif
3623 #endif
3624
3625 arena_chunk_t* chunk_to_release = nullptr;
3626 bool is_dying;
3627 {
3628 // Phase 2: Mark the pages with their final state (madvised or
3629 // decommitted) and fix up any other bookkeeping.
3630 MaybeMutexAutoLock lock(purge_info.mArena.mLock);
3631 MOZ_ASSERT(chunk->mIsPurging);
3632
3633 // We can't early exit if the arena is dying, we have to finish the purge
3634 // (which restores the state so the destructor will check it) and maybe
3635 // release the old spare arena.
3636 is_dying = purge_info.mArena.mMustDeleteAfterPurge;
3637
3638 auto [cpc, ctr] = purge_info.UpdatePagesAndCounts();
3639 continue_purge_chunk = cpc;
3640 chunk_to_release = ctr;
3641 continue_purge_arena = purge_info.mArena.ShouldContinuePurge(aCond);
3642
3643 if (!continue_purge_chunk || !continue_purge_arena) {
3644 // We're going to stop purging here so update the chunk's bookkeeping.
3645 purge_info.FinishPurgingInChunk(true);
3646 purge_info.mArena.mIsPurgePending = false;
3647 }
3648 } // MaybeMutexAutoLock
3649
3650 // Phase 2 can release the spare chunk (not always == chunk) so an extra
3651 // parameter is used to return that chunk.
3652 if (chunk_to_release) {
3653 chunk_dealloc((void*)chunk_to_release, kChunkSize, ARENA_CHUNK);
3654 }
3655 if (is_dying) {
3656 return Dying;
3657 }
3658 purged_once = true;
3659 }
3660
3661 return continue_purge_arena ? Continue : Done;
3662 }
3663
3664 bool arena_t::PurgeInfo::FindDirtyPages(bool aPurgedOnce) {
3665 // It's possible that the previously dirty pages have now been
3666 // allocated or the chunk is dying.
3667 if (mChunk->ndirty == 0 || mChunk->mDying) {
3668 // Add the chunk to the mChunksMAdvised list if it's had at least one
3669 // madvise.
3670 FinishPurgingInChunk(aPurgedOnce);
3671 return false;
3672 }
3673
3674 // Look for the first dirty page, as we do record the beginning of the run
3675 // that contains the dirty page.
3676 bool previous_page_is_allocated = true;
3677 for (size_t i = gChunkHeaderNumPages; i < gChunkNumPages - 1; i++) {
3678 size_t bits = mChunk->map[i].bits;
3679
3680 // We must not find any busy pages because this chunk shouldn't be in
3681 // the dirty list.
3682 MOZ_ASSERT((bits & CHUNK_MAP_BUSY) == 0);
3683
3684 // The first page belonging to a free run has the allocated bit clear
3685 // and a non-zero size. To distinguish it from the last page of a free
3686 // run we track the allocated bit of the previous page, if it's set
3687 // then this is the first.
3688 if ((bits & CHUNK_MAP_ALLOCATED) == 0 && (bits & ~gPageSizeMask) != 0 &&
3689 previous_page_is_allocated) {
3690 mFreeRunInd = i;
3691 mFreeRunLen = bits >> gPageSize2Pow;
3692 }
3693
3694 if (bits & CHUNK_MAP_DIRTY) {
3695 MOZ_ASSERT(
3696 (mChunk->map[i].bits & CHUNK_MAP_FRESH_MADVISED_OR_DECOMMITTED) == 0);
3697 mDirtyInd = i;
3698 break;
3699 }
3700
3701 previous_page_is_allocated = bits & CHUNK_MAP_ALLOCATED;
3702 }
3703 MOZ_ASSERT(mDirtyInd != 0);
3704 MOZ_ASSERT(mFreeRunInd >= gChunkHeaderNumPages);
3705 MOZ_ASSERT(mFreeRunInd <= mDirtyInd);
3706 MOZ_ASSERT(mFreeRunLen > 0);
3707
3708 // Look for the next not-dirty page, it could be the guard page at the end
3709 // of the chunk.
3710 for (size_t i = 0; mDirtyInd + i < gChunkNumPages; i++) {
3711 size_t& bits = mChunk->map[mDirtyInd + i].bits;
3712
3713 // We must not find any busy pages because this chunk shouldn't be in the
3714 // dirty list.
3715 MOZ_ASSERT(!(bits & CHUNK_MAP_BUSY));
3716
3717 if (!(bits & CHUNK_MAP_DIRTY)) {
3718 mDirtyNPages = i;
3719 break;
3720 }
3721 MOZ_ASSERT((bits & CHUNK_MAP_FRESH_MADVISED_OR_DECOMMITTED) == 0);
3722 bits ^= CHUNK_MAP_DIRTY;
3723 }
3724 MOZ_ASSERT(mDirtyNPages > 0);
3725 MOZ_ASSERT(mDirtyNPages <= mChunk->ndirty);
3726 MOZ_ASSERT(mFreeRunInd + mFreeRunLen >= mDirtyInd + mDirtyNPages);
3727
3728 // Mark the run as busy so that another thread freeing memory won't try to
3729 // coalesce it.
3730 mChunk->map[mFreeRunInd].bits |= CHUNK_MAP_BUSY;
3731 mChunk->map[FreeRunLastInd()].bits |= CHUNK_MAP_BUSY;
3732
3733 mChunk->ndirty -= mDirtyNPages;
3734 mArena.mNumDirty -= mDirtyNPages;
3735
3736 // Before we unlock ensure that no other thread can allocate from these
3737 // pages.
3738 if (mArena.mSpare != mChunk) {
3739 mArena.mRunsAvail.Remove(&mChunk->map[mFreeRunInd]);
3740 }
3741 return true;
3742 }
3743
3744 std::pair<bool, arena_chunk_t*> arena_t::PurgeInfo::UpdatePagesAndCounts() {
3745 for (size_t i = 0; i < mDirtyNPages; i++) {
3746 // The page must not have any of the madvised, decommited or dirty bits
3747 // set.
3748 MOZ_ASSERT((mChunk->map[mDirtyInd + i].bits &
3749 (CHUNK_MAP_FRESH_MADVISED_OR_DECOMMITTED | CHUNK_MAP_DIRTY)) ==
3750 0);
3751 #ifdef MALLOC_DECOMMIT
3752 const size_t free_operation = CHUNK_MAP_DECOMMITTED;
3753 #else
3754 const size_t free_operation = CHUNK_MAP_MADVISED;
3755 #endif
3756 mChunk->map[mDirtyInd + i].bits ^= free_operation;
3757 }
3758
3759 // Remove the CHUNK_MAP_BUSY marks from the run.
3760 #ifdef MOZ_DEBUG
3761 MOZ_ASSERT(mChunk->map[mFreeRunInd].bits & CHUNK_MAP_BUSY);
3762 MOZ_ASSERT(mChunk->map[FreeRunLastInd()].bits & CHUNK_MAP_BUSY);
3763 #endif
3764 mChunk->map[mFreeRunInd].bits &= ~CHUNK_MAP_BUSY;
3765 mChunk->map[FreeRunLastInd()].bits &= ~CHUNK_MAP_BUSY;
3766
3767 #ifndef MALLOC_DECOMMIT
3768 mArena.mNumMAdvised += mDirtyNPages;
3769 #endif
3770
3771 mArena.mStats.committed -= mDirtyNPages;
3772
3773 if (mChunk->mDying) {
3774 // A dying chunk doesn't need to be coaleased, it will already have one
3775 // large run.
3776 MOZ_ASSERT(mFreeRunInd == gChunkHeaderNumPages &&
3777 mFreeRunLen == gChunkNumPages - gChunkHeaderNumPages - 1);
3778
3779 return std::make_pair(false, mChunk);
3780 }
3781
3782 bool was_empty = mChunk->IsEmpty();
3783 mFreeRunInd =
3784 mArena.TryCoalesce(mChunk, mFreeRunInd, mFreeRunLen, FreeRunLenBytes());
3785
3786 arena_chunk_t* chunk_to_release = nullptr;
3787 if (!was_empty && mChunk->IsEmpty()) {
3788 // This now-empty chunk will become the spare chunk and the spare
3789 // chunk will be returned for deletion.
3790 chunk_to_release = mArena.DemoteChunkToSpare(mChunk);
3791 }
3792
3793 if (mChunk != mArena.mSpare) {
3794 mArena.mRunsAvail.Insert(&mChunk->map[mFreeRunInd]);
3795 }
3796
3797 return std::make_pair(mChunk->ndirty != 0, chunk_to_release);
3798 }
3799
3800 void arena_t::PurgeInfo::FinishPurgingInChunk(bool aAddToMAdvised) {
3801 // If there's no more purge activity for this chunk then finish up while
3802 // we still have the lock.
3803 MOZ_ASSERT(mChunk->mIsPurging);
3804 mChunk->mIsPurging = false;
3805
3806 if (mChunk->mDying) {
3807 // Another thread tried to delete this chunk while we weren't holding
3808 // the lock. Now it's our responsibility to finish deleting it. First
3809 // clear its dirty pages so that RemoveChunk() doesn't try to remove it
3810 // from mChunksDirty because it won't be there.
3811 mArena.mNumDirty -= mChunk->ndirty;
3812 mArena.mStats.committed -= mChunk->ndirty;
3813 mChunk->ndirty = 0;
3814
3815 DebugOnly<bool> release_chunk = mArena.RemoveChunk(mChunk);
3816 // RemoveChunk() can't return false because mIsPurging was false
3817 // during the call.
3818 MOZ_ASSERT(release_chunk);
3819 return;
3820 }
3821
3822 if (mChunk->ndirty != 0) {
3823 mArena.mChunksDirty.Insert(mChunk);
3824 }
3825
3826 #ifdef MALLOC_DOUBLE_PURGE
3827 if (aAddToMAdvised) {
3828 // The chunk might already be in the list, but this
3829 // makes sure it's at the front.
3830 if (mArena.mChunksMAdvised.ElementProbablyInList(mChunk)) {
3831 mArena.mChunksMAdvised.remove(mChunk);
3832 }
3833 mArena.mChunksMAdvised.pushFront(mChunk);
3834 }
3835 #endif
3836 }
3837
3838 // run_pages and size make each-other redundant. But we use them both and the
3839 // caller computes both so this function requires both and will assert if they
3840 // are inconsistent.
3841 size_t arena_t::TryCoalesce(arena_chunk_t* aChunk, size_t run_ind,
3842 size_t run_pages, size_t size) {
3843 // Copy in/out parameters to local variables so that we don't need '*'
3844 // operators throughout this code but also so that type checking is stricter
3845 // (references are too easily coerced).
3846 MOZ_ASSERT(size == run_pages << gPageSize2Pow);
3847
3848 // Try to coalesce forward.
3849 if (run_ind + run_pages < gChunkNumPages - 1 &&
3850 (aChunk->map[run_ind + run_pages].bits &
3851 (CHUNK_MAP_ALLOCATED | CHUNK_MAP_BUSY)) == 0) {
3852 size_t nrun_size = aChunk->map[run_ind + run_pages].bits & ~gPageSizeMask;
3853
3854 // Remove successor from tree of available runs; the coalesced run is
3855 // inserted later.
3856 mRunsAvail.Remove(&aChunk->map[run_ind + run_pages]);
3857
3858 size += nrun_size;
3859 run_pages = size >> gPageSize2Pow;
3860
3861 MOZ_DIAGNOSTIC_ASSERT((aChunk->map[run_ind + run_pages - 1].bits &
3862 ~gPageSizeMask) == nrun_size);
3863 aChunk->map[run_ind].bits =
3864 size | (aChunk->map[run_ind].bits & gPageSizeMask);
3865 aChunk->map[run_ind + run_pages - 1].bits =
3866 size | (aChunk->map[run_ind + run_pages - 1].bits & gPageSizeMask);
3867 }
3868
3869 // Try to coalesce backward.
3870 if (run_ind > gChunkHeaderNumPages &&
3871 (aChunk->map[run_ind - 1].bits &
3872 (CHUNK_MAP_ALLOCATED | CHUNK_MAP_BUSY)) == 0) {
3873 size_t prun_size = aChunk->map[run_ind - 1].bits & ~gPageSizeMask;
3874
3875 run_ind -= prun_size >> gPageSize2Pow;
3876
3877 // Remove predecessor from tree of available runs; the coalesced run is
3878 // inserted later.
3879 mRunsAvail.Remove(&aChunk->map[run_ind]);
3880
3881 size += prun_size;
3882 run_pages = size >> gPageSize2Pow;
3883
3884 MOZ_DIAGNOSTIC_ASSERT((aChunk->map[run_ind].bits & ~gPageSizeMask) ==
3885 prun_size);
3886 aChunk->map[run_ind].bits =
3887 size | (aChunk->map[run_ind].bits & gPageSizeMask);
3888 aChunk->map[run_ind + run_pages - 1].bits =
3889 size | (aChunk->map[run_ind + run_pages - 1].bits & gPageSizeMask);
3890 }
3891
3892 return run_ind;
3893 }
3894
3895 arena_chunk_t* arena_t::DallocRun(arena_run_t* aRun, bool aDirty) {
3896 arena_chunk_t* chunk;
3897 size_t size, run_ind, run_pages;
3898
3899 chunk = GetChunkForPtr(aRun);
3900 run_ind = (size_t)((uintptr_t(aRun) - uintptr_t(chunk)) >> gPageSize2Pow);
3901 MOZ_DIAGNOSTIC_ASSERT(run_ind >= gChunkHeaderNumPages);
3902 MOZ_RELEASE_ASSERT(run_ind < gChunkNumPages - 1);
3903 if ((chunk->map[run_ind].bits & CHUNK_MAP_LARGE) != 0) {
3904 size = chunk->map[run_ind].bits & ~gPageSizeMask;
3905 run_pages = (size >> gPageSize2Pow);
3906 } else {
3907 run_pages = aRun->mBin->mRunSizePages;
3908 size = run_pages << gPageSize2Pow;
3909 }
3910
3911 // Mark pages as unallocated in the chunk map.
3912 if (aDirty) {
3913 size_t i;
3914
3915 for (i = 0; i < run_pages; i++) {
3916 MOZ_DIAGNOSTIC_ASSERT((chunk->map[run_ind + i].bits & CHUNK_MAP_DIRTY) ==
3917 0);
3918 chunk->map[run_ind + i].bits = CHUNK_MAP_DIRTY;
3919 }
3920
3921 if (chunk->ndirty == 0 && !chunk->mIsPurging) {
3922 mChunksDirty.Insert(chunk);
3923 }
3924 chunk->ndirty += run_pages;
3925 mNumDirty += run_pages;
3926 } else {
3927 size_t i;
3928
3929 for (i = 0; i < run_pages; i++) {
3930 chunk->map[run_ind + i].bits &= ~(CHUNK_MAP_LARGE | CHUNK_MAP_ALLOCATED);
3931 }
3932 }
3933 chunk->map[run_ind].bits = size | (chunk->map[run_ind].bits & gPageSizeMask);
3934 chunk->map[run_ind + run_pages - 1].bits =
3935 size | (chunk->map[run_ind + run_pages - 1].bits & gPageSizeMask);
3936
3937 run_ind = TryCoalesce(chunk, run_ind, run_pages, size);
3938
3939 // Deallocate chunk if it is now completely unused.
3940 arena_chunk_t* chunk_dealloc = nullptr;
3941 if (chunk->IsEmpty()) {
3942 chunk_dealloc = DemoteChunkToSpare(chunk);
3943 } else {
3944 // Insert into tree of available runs, now that coalescing is complete.
3945 mRunsAvail.Insert(&chunk->map[run_ind]);
3946 }
3947
3948 return chunk_dealloc;
3949 }
3950
3951 void arena_t::TrimRunHead(arena_chunk_t* aChunk, arena_run_t* aRun,
3952 size_t aOldSize, size_t aNewSize) {
3953 size_t pageind = (uintptr_t(aRun) - uintptr_t(aChunk)) >> gPageSize2Pow;
3954 size_t head_npages = (aOldSize - aNewSize) >> gPageSize2Pow;
3955
3956 MOZ_ASSERT(aOldSize > aNewSize);
3957
3958 // Update the chunk map so that arena_t::RunDalloc() can treat the
3959 // leading run as separately allocated.
3960 aChunk->map[pageind].bits =
3961 (aOldSize - aNewSize) | CHUNK_MAP_LARGE | CHUNK_MAP_ALLOCATED;
3962 aChunk->map[pageind + head_npages].bits =
3963 aNewSize | CHUNK_MAP_LARGE | CHUNK_MAP_ALLOCATED;
3964
3965 DebugOnly<arena_chunk_t*> no_chunk = DallocRun(aRun, false);
3966 // This will never release a chunk as there's still at least one allocated
3967 // run.
3968 MOZ_ASSERT(!no_chunk);
3969 }
3970
3971 void arena_t::TrimRunTail(arena_chunk_t* aChunk, arena_run_t* aRun,
3972 size_t aOldSize, size_t aNewSize, bool aDirty) {
3973 size_t pageind = (uintptr_t(aRun) - uintptr_t(aChunk)) >> gPageSize2Pow;
3974 size_t npages = aNewSize >> gPageSize2Pow;
3975
3976 MOZ_ASSERT(aOldSize > aNewSize);
3977
3978 // Update the chunk map so that arena_t::RunDalloc() can treat the
3979 // trailing run as separately allocated.
3980 aChunk->map[pageind].bits = aNewSize | CHUNK_MAP_LARGE | CHUNK_MAP_ALLOCATED;
3981 aChunk->map[pageind + npages].bits =
3982 (aOldSize - aNewSize) | CHUNK_MAP_LARGE | CHUNK_MAP_ALLOCATED;
3983
3984 DebugOnly<arena_chunk_t*> no_chunk =
3985 DallocRun((arena_run_t*)(uintptr_t(aRun) + aNewSize), aDirty);
3986
3987 // This will never release a chunk as there's still at least one allocated
3988 // run.
3989 MOZ_ASSERT(!no_chunk);
3990 }
3991
3992 arena_run_t* arena_t::GetNewEmptyBinRun(arena_bin_t* aBin) {
3993 arena_run_t* run;
3994 unsigned i, remainder;
3995
3996 // Allocate a new run.
3997 run = AllocRun(static_cast<size_t>(aBin->mRunSizePages) << gPageSize2Pow,
3998 false, false);
3999 if (!run) {
4000 return nullptr;
4001 }
4002
4003 // Initialize run internals.
4004 run->mBin = aBin;
4005
4006 for (i = 0; i < aBin->mRunNumRegionsMask - 1; i++) {
4007 run->mRegionsMask[i] = UINT_MAX;
4008 }
4009 remainder = aBin->mRunNumRegions & ((1U << (LOG2(sizeof(int)) + 3)) - 1);
4010 if (remainder == 0) {
4011 run->mRegionsMask[i] = UINT_MAX;
4012 } else {
4013 // The last element has spare bits that need to be unset.
4014 run->mRegionsMask[i] =
4015 (UINT_MAX >> ((1U << (LOG2(sizeof(int)) + 3)) - remainder));
4016 }
4017
4018 run->mRegionsMinElement = 0;
4019
4020 run->mNumFree = aBin->mRunNumRegions;
4021 #if defined(MOZ_DIAGNOSTIC_ASSERT_ENABLED)
4022 run->mMagic = ARENA_RUN_MAGIC;
4023 #endif
4024
4025 // Make sure we continue to use this run for subsequent allocations.
4026 new (&run->mRunListElem) DoublyLinkedListElement<arena_run_t>();
4027 aBin->mNonFullRuns.pushFront(run);
4028
4029 aBin->mNumRuns++;
4030 return run;
4031 }
4032
4033 arena_run_t* arena_t::GetNonFullBinRun(arena_bin_t* aBin) {
4034 auto mrf_head = aBin->mNonFullRuns.begin();
4035 if (mrf_head) {
4036 // Take the head and if we are going to fill it, remove it from our list.
4037 arena_run_t* run = &(*mrf_head);
4038 MOZ_DIAGNOSTIC_ASSERT(run->mMagic == ARENA_RUN_MAGIC);
4039 if (run->mNumFree == 1) {
4040 aBin->mNonFullRuns.remove(run);
4041 }
4042 return run;
4043 }
4044 return GetNewEmptyBinRun(aBin);
4045 }
4046
4047 void arena_bin_t::Init(SizeClass aSizeClass) {
4048 size_t try_run_size;
4049 unsigned try_nregs, try_mask_nelms, try_reg0_offset;
4050 // Size of the run header, excluding mRegionsMask.
4051 static const size_t kFixedHeaderSize = offsetof(arena_run_t, mRegionsMask);
4052
4053 MOZ_ASSERT(aSizeClass.Size() <= gMaxBinClass);
4054
4055 try_run_size = gPageSize;
4056
4057 mSizeClass = aSizeClass.Size();
4058 mNumRuns = 0;
4059
4060 // Run size expansion loop.
4061 while (true) {
4062 try_nregs = ((try_run_size - kFixedHeaderSize) / mSizeClass) +
4063 1; // Counter-act try_nregs-- in loop.
4064
4065 // The do..while loop iteratively reduces the number of regions until
4066 // the run header and the regions no longer overlap. A closed formula
4067 // would be quite messy, since there is an interdependency between the
4068 // header's mask length and the number of regions.
4069 do {
4070 try_nregs--;
4071 try_mask_nelms =
4072 (try_nregs >> (LOG2(sizeof(int)) + 3)) +
4073 ((try_nregs & ((1U << (LOG2(sizeof(int)) + 3)) - 1)) ? 1 : 0);
4074 try_reg0_offset = try_run_size - (try_nregs * mSizeClass);
4075 } while (kFixedHeaderSize + (sizeof(unsigned) * try_mask_nelms) >
4076 try_reg0_offset);
4077
4078 // Try to keep the run overhead below kRunOverhead.
4079 if (Fraction(try_reg0_offset, try_run_size) <= kRunOverhead) {
4080 break;
4081 }
4082
4083 // If the overhead is larger than the size class, it means the size class
4084 // is small and doesn't align very well with the header. It's desirable to
4085 // have smaller run sizes for them, so relax the overhead requirement.
4086 if (try_reg0_offset > mSizeClass) {
4087 if (Fraction(try_reg0_offset, try_run_size) <= kRunRelaxedOverhead) {
4088 break;
4089 }
4090 }
4091
4092 // The run header includes one bit per region of the given size. For sizes
4093 // small enough, the number of regions is large enough that growing the run
4094 // size barely moves the needle for the overhead because of all those bits.
4095 // For example, for a size of 8 bytes, adding 4KiB to the run size adds
4096 // close to 512 bits to the header, which is 64 bytes.
4097 // With such overhead, there is no way to get to the wanted overhead above,
4098 // so we give up if the required size for mRegionsMask more than doubles the
4099 // size of the run header.
4100 if (try_mask_nelms * sizeof(unsigned) >= kFixedHeaderSize) {
4101 break;
4102 }
4103
4104 // If next iteration is going to be larger than the largest possible large
4105 // size class, then we didn't find a setup where the overhead is small
4106 // enough, and we can't do better than the current settings, so just use
4107 // that.
4108 if (try_run_size + gPageSize > gMaxLargeClass) {
4109 break;
4110 }
4111
4112 // Try more aggressive settings.
4113 try_run_size += gPageSize;
4114 }
4115
4116 MOZ_ASSERT(kFixedHeaderSize + (sizeof(unsigned) * try_mask_nelms) <=
4117 try_reg0_offset);
4118 MOZ_ASSERT((try_mask_nelms << (LOG2(sizeof(int)) + 3)) >= try_nregs);
4119
4120 // Our list management would break if mRunNumRegions == 1 and we should use
4121 // a large size class instead, anyways.
4122 MOZ_ASSERT(try_nregs > 1);
4123
4124 // Copy final settings.
4125 MOZ_ASSERT((try_run_size >> gPageSize2Pow) <= UINT8_MAX);
4126 mRunSizePages = static_cast<uint8_t>(try_run_size >> gPageSize2Pow);
4127 mRunNumRegions = try_nregs;
4128 mRunNumRegionsMask = try_mask_nelms;
4129 mRunFirstRegionOffset = try_reg0_offset;
4130 mSizeDivisor = FastDivisor<uint16_t>(aSizeClass.Size(), try_run_size);
4131 }
4132
4133 void arena_t::ResetSmallAllocRandomization() {
4134 if (MOZ_UNLIKELY(opt_randomize_small)) {
4135 MaybeMutexAutoLock lock(mLock);
4136 InitPRNG();
4137 }
4138 mRandomizeSmallAllocations = opt_randomize_small;
4139 }
4140
4141 void arena_t::InitPRNG() {
4142 // Both another thread could race and the code backing RandomUint64
4143 // (arc4random for example) may allocate memory while here, so we must
4144 // ensure to start the mPRNG initialization only once and to not hold
4145 // the lock while initializing.
4146 mIsPRNGInitializing = true;
4147 {
4148 mLock.Unlock();
4149 mozilla::Maybe<uint64_t> prngState1 = mozilla::RandomUint64();
4150 mozilla::Maybe<uint64_t> prngState2 = mozilla::RandomUint64();
4151 mLock.Lock();
4152
4153 mozilla::non_crypto::XorShift128PlusRNG prng(prngState1.valueOr(0),
4154 prngState2.valueOr(0));
4155 if (mPRNG) {
4156 *mPRNG = prng;
4157 } else {
4158 void* backing =
4159 base_alloc(sizeof(mozilla::non_crypto::XorShift128PlusRNG));
4160 mPRNG = new (backing)
4161 mozilla::non_crypto::XorShift128PlusRNG(std::move(prng));
4162 }
4163 }
4164 mIsPRNGInitializing = false;
4165 }
4166
4167 void* arena_t::MallocSmall(size_t aSize, bool aZero) {
4168 void* ret;
4169 arena_bin_t* bin;
4170 arena_run_t* run;
4171 SizeClass sizeClass(aSize);
4172 aSize = sizeClass.Size();
4173
4174 switch (sizeClass.Type()) {
4175 case SizeClass::Tiny:
4176 bin = &mBins[FloorLog2(aSize / kMinTinyClass)];
4177 break;
4178 case SizeClass::Quantum:
4179 // Although we divide 2 things by kQuantum, the compiler will
4180 // reduce `kMinQuantumClass / kQuantum` and `kNumTinyClasses` to a
4181 // single constant.
4182 bin = &mBins[kNumTinyClasses + (aSize / kQuantum) -
4183 (kMinQuantumClass / kQuantum)];
4184 break;
4185 case SizeClass::QuantumWide:
4186 bin =
4187 &mBins[kNumTinyClasses + kNumQuantumClasses + (aSize / kQuantumWide) -
4188 (kMinQuantumWideClass / kQuantumWide)];
4189 break;
4190 case SizeClass::SubPage:
4191 bin =
4192 &mBins[kNumTinyClasses + kNumQuantumClasses + kNumQuantumWideClasses +
4193 (FloorLog2(aSize) - LOG2(kMinSubPageClass))];
4194 break;
4195 default:
4196 MOZ_MAKE_COMPILER_ASSUME_IS_UNREACHABLE("Unexpected size class type");
4197 }
4198 MOZ_DIAGNOSTIC_ASSERT(aSize == bin->mSizeClass);
4199
4200 size_t num_dirty_before, num_dirty_after;
4201 {
4202 MaybeMutexAutoLock lock(mLock);
4203
4204 #ifdef MOZ_DEBUG
4205 bool isInitializingThread(false);
4206 #endif
4207
4208 if (MOZ_UNLIKELY(mRandomizeSmallAllocations && mPRNG == nullptr &&
4209 !mIsPRNGInitializing)) {
4210 #ifdef MOZ_DEBUG
4211 isInitializingThread = true;
4212 #endif
4213 InitPRNG();
4214 }
4215
4216 MOZ_ASSERT(!mRandomizeSmallAllocations || mPRNG ||
4217 (mIsPRNGInitializing && !isInitializingThread));
4218
4219 num_dirty_before = mNumDirty;
4220 run = GetNonFullBinRun(bin);
4221 num_dirty_after = mNumDirty;
4222 if (MOZ_UNLIKELY(!run)) {
4223 return nullptr;
4224 }
4225 MOZ_DIAGNOSTIC_ASSERT(run->mMagic == ARENA_RUN_MAGIC);
4226 MOZ_DIAGNOSTIC_ASSERT(run->mNumFree > 0);
4227 ret = ArenaRunRegAlloc(run, bin);
4228 MOZ_DIAGNOSTIC_ASSERT(ret);
4229 run->mNumFree--;
4230 if (!ret) {
4231 return nullptr;
4232 }
4233
4234 mStats.allocated_small += aSize;
4235 mStats.operations++;
4236 }
4237 if (num_dirty_after < num_dirty_before) {
4238 NotifySignificantReuse();
4239 }
4240 if (!aZero) {
4241 ApplyZeroOrJunk(ret, aSize);
4242 } else {
4243 memset(ret, 0, aSize);
4244 }
4245
4246 return ret;
4247 }
4248
4249 void* arena_t::MallocLarge(size_t aSize, bool aZero) {
4250 void* ret;
4251
4252 // Large allocation.
4253 aSize = PAGE_CEILING(aSize);
4254
4255 size_t num_dirty_before, num_dirty_after;
4256 {
4257 MaybeMutexAutoLock lock(mLock);
4258 num_dirty_before = mNumDirty;
4259 ret = AllocRun(aSize, true, aZero);
4260 num_dirty_after = mNumDirty;
4261 if (!ret) {
4262 return nullptr;
4263 }
4264 mStats.allocated_large += aSize;
4265 mStats.operations++;
4266 }
4267 if (num_dirty_after < num_dirty_before) {
4268 NotifySignificantReuse();
4269 }
4270
4271 if (!aZero) {
4272 ApplyZeroOrJunk(ret, aSize);
4273 }
4274
4275 return ret;
4276 }
4277
4278 void* arena_t::Malloc(size_t aSize, bool aZero) {
4279 MOZ_DIAGNOSTIC_ASSERT(mMagic == ARENA_MAGIC);
4280 MOZ_ASSERT(aSize != 0);
4281
4282 if (aSize <= gMaxBinClass) {
4283 return MallocSmall(aSize, aZero);
4284 }
4285 if (aSize <= gMaxLargeClass) {
4286 return MallocLarge(aSize, aZero);
4287 }
4288 return MallocHuge(aSize, aZero);
4289 }
4290
4291 // Only handles large allocations that require more than page alignment.
4292 void* arena_t::PallocLarge(size_t aAlignment, size_t aSize, size_t aAllocSize) {
4293 void* ret;
4294 size_t offset;
4295 arena_chunk_t* chunk;
4296
4297 MOZ_ASSERT((aSize & gPageSizeMask) == 0);
4298 MOZ_ASSERT((aAlignment & gPageSizeMask) == 0);
4299
4300 size_t num_dirty_before, num_dirty_after;
4301 {
4302 MaybeMutexAutoLock lock(mLock);
4303 num_dirty_before = mNumDirty;
4304 ret = AllocRun(aAllocSize, true, false);
4305 if (!ret) {
4306 return nullptr;
4307 }
4308
4309 chunk = GetChunkForPtr(ret);
4310
4311 offset = uintptr_t(ret) & (aAlignment - 1);
4312 MOZ_ASSERT((offset & gPageSizeMask) == 0);
4313 MOZ_ASSERT(offset < aAllocSize);
4314 if (offset == 0) {
4315 TrimRunTail(chunk, (arena_run_t*)ret, aAllocSize, aSize, false);
4316 } else {
4317 size_t leadsize, trailsize;
4318
4319 leadsize = aAlignment - offset;
4320 if (leadsize > 0) {
4321 TrimRunHead(chunk, (arena_run_t*)ret, aAllocSize,
4322 aAllocSize - leadsize);
4323 ret = (void*)(uintptr_t(ret) + leadsize);
4324 }
4325
4326 trailsize = aAllocSize - leadsize - aSize;
4327 if (trailsize != 0) {
4328 // Trim trailing space.
4329 MOZ_ASSERT(trailsize < aAllocSize);
4330 TrimRunTail(chunk, (arena_run_t*)ret, aSize + trailsize, aSize, false);
4331 }
4332 }
4333 num_dirty_after = mNumDirty;
4334
4335 mStats.allocated_large += aSize;
4336 mStats.operations++;
4337 }
4338 if (num_dirty_after < num_dirty_before) {
4339 NotifySignificantReuse();
4340 }
4341 // Note that since Bug 1488780we don't attempt purge dirty memory on this code
4342 // path. In general there won't be dirty memory above the threshold after an
4343 // allocation, only after free. The exception is if the dirty page threshold
4344 // has changed.
4345
4346 ApplyZeroOrJunk(ret, aSize);
4347 return ret;
4348 }
4349
4350 void* arena_t::Palloc(size_t aAlignment, size_t aSize) {
4351 void* ret;
4352 size_t ceil_size;
4353
4354 // Round size up to the nearest multiple of alignment.
4355 //
4356 // This done, we can take advantage of the fact that for each small
4357 // size class, every object is aligned at the smallest power of two
4358 // that is non-zero in the base two representation of the size. For
4359 // example:
4360 //
4361 // Size | Base 2 | Minimum alignment
4362 // -----+----------+------------------
4363 // 96 | 1100000 | 32
4364 // 144 | 10100000 | 32
4365 // 192 | 11000000 | 64
4366 //
4367 // Depending on runtime settings, it is possible that arena_malloc()
4368 // will further round up to a power of two, but that never causes
4369 // correctness issues.
4370 ceil_size = ALIGNMENT_CEILING(aSize, aAlignment);
4371
4372 // (ceil_size < aSize) protects against the combination of maximal
4373 // alignment and size greater than maximal alignment.
4374 if (ceil_size < aSize) {
4375 // size_t overflow.
4376 return nullptr;
4377 }
4378
4379 if (ceil_size <= gPageSize ||
4380 (aAlignment <= gPageSize && ceil_size <= gMaxLargeClass)) {
4381 ret = Malloc(ceil_size, false);
4382 } else {
4383 size_t run_size;
4384
4385 // We can't achieve sub-page alignment, so round up alignment
4386 // permanently; it makes later calculations simpler.
4387 aAlignment = PAGE_CEILING(aAlignment);
4388 ceil_size = PAGE_CEILING(aSize);
4389
4390 // (ceil_size < aSize) protects against very large sizes within
4391 // pagesize of SIZE_T_MAX.
4392 //
4393 // (ceil_size + aAlignment < ceil_size) protects against the
4394 // combination of maximal alignment and ceil_size large enough
4395 // to cause overflow. This is similar to the first overflow
4396 // check above, but it needs to be repeated due to the new
4397 // ceil_size value, which may now be *equal* to maximal
4398 // alignment, whereas before we only detected overflow if the
4399 // original size was *greater* than maximal alignment.
4400 if (ceil_size < aSize || ceil_size + aAlignment < ceil_size) {
4401 // size_t overflow.
4402 return nullptr;
4403 }
4404
4405 // Calculate the size of the over-size run that arena_palloc()
4406 // would need to allocate in order to guarantee the alignment.
4407 if (ceil_size >= aAlignment) {
4408 run_size = ceil_size + aAlignment - gPageSize;
4409 } else {
4410 // It is possible that (aAlignment << 1) will cause
4411 // overflow, but it doesn't matter because we also
4412 // subtract pagesize, which in the case of overflow
4413 // leaves us with a very large run_size. That causes
4414 // the first conditional below to fail, which means
4415 // that the bogus run_size value never gets used for
4416 // anything important.
4417 run_size = (aAlignment << 1) - gPageSize;
4418 }
4419
4420 if (run_size <= gMaxLargeClass) {
4421 ret = PallocLarge(aAlignment, ceil_size, run_size);
4422 } else if (aAlignment <= kChunkSize) {
4423 ret = MallocHuge(ceil_size, false);
4424 } else {
4425 ret = PallocHuge(ceil_size, aAlignment, false);
4426 }
4427 }
4428
4429 MOZ_ASSERT((uintptr_t(ret) & (aAlignment - 1)) == 0);
4430 return ret;
4431 }
4432
4433 class AllocInfo {
4434 public:
4435 template <bool Validate = false>
4436 static inline AllocInfo Get(const void* aPtr) {
4437 // If the allocator is not initialized, the pointer can't belong to it.
4438 if (Validate && !malloc_initialized) {
4439 return AllocInfo();
4440 }
4441
4442 auto chunk = GetChunkForPtr(aPtr);
4443 if (Validate) {
4444 if (!chunk || !gChunkRTree.Get(chunk)) {
4445 return AllocInfo();
4446 }
4447 }
4448
4449 if (chunk != aPtr) {
4450 MOZ_DIAGNOSTIC_ASSERT(chunk->arena->mMagic == ARENA_MAGIC);
4451 size_t pageind = (((uintptr_t)aPtr - (uintptr_t)chunk) >> gPageSize2Pow);
4452 return GetInChunk(aPtr, chunk, pageind);
4453 }
4454
4455 extent_node_t key;
4456
4457 // Huge allocation
4458 key.mAddr = chunk;
4459 MutexAutoLock lock(huge_mtx);
4460 extent_node_t* node = huge.Search(&key);
4461 if (Validate && !node) {
4462 return AllocInfo();
4463 }
4464 return AllocInfo(node->mSize, node);
4465 }
4466
4467 // Get the allocation information for a pointer we know is within a chunk
4468 // (Small or large, not huge).
4469 static inline AllocInfo GetInChunk(const void* aPtr, arena_chunk_t* aChunk,
4470 size_t pageind) {
4471 size_t mapbits = aChunk->map[pageind].bits;
4472 MOZ_DIAGNOSTIC_ASSERT((mapbits & CHUNK_MAP_ALLOCATED) != 0);
4473
4474 size_t size;
4475 if ((mapbits & CHUNK_MAP_LARGE) == 0) {
4476 arena_run_t* run = (arena_run_t*)(mapbits & ~gPageSizeMask);
4477 MOZ_DIAGNOSTIC_ASSERT(run->mMagic == ARENA_RUN_MAGIC);
4478 size = run->mBin->mSizeClass;
4479 } else {
4480 size = mapbits & ~gPageSizeMask;
4481 MOZ_DIAGNOSTIC_ASSERT(size != 0);
4482 }
4483
4484 return AllocInfo(size, aChunk);
4485 }
4486
4487 // Validate ptr before assuming that it points to an allocation. Currently,
4488 // the following validation is performed:
4489 //
4490 // + Check that ptr is not nullptr.
4491 //
4492 // + Check that ptr lies within a mapped chunk.
4493 static inline AllocInfo GetValidated(const void* aPtr) {
4494 return Get<true>(aPtr);
4495 }
4496
4497 AllocInfo() : mSize(0), mChunk(nullptr) {}
4498
4499 explicit AllocInfo(size_t aSize, arena_chunk_t* aChunk)
4500 : mSize(aSize), mChunk(aChunk) {
4501 MOZ_ASSERT(mSize <= gMaxLargeClass);
4502 }
4503
4504 explicit AllocInfo(size_t aSize, extent_node_t* aNode)
4505 : mSize(aSize), mNode(aNode) {
4506 MOZ_ASSERT(mSize > gMaxLargeClass);
4507 }
4508
4509 size_t Size() { return mSize; }
4510
4511 arena_t* Arena() {
4512 if (mSize <= gMaxLargeClass) {
4513 return mChunk->arena;
4514 }
4515 // Best effort detection that we're not trying to access an already
4516 // disposed arena. In the case of a disposed arena, the memory location
4517 // pointed by mNode->mArena is either free (but still a valid memory
4518 // region, per TypedBaseAlloc<arena_t>), in which case its id was reset,
4519 // or has been reallocated for a new region, and its id is very likely
4520 // different (per randomness). In both cases, the id is unlikely to
4521 // match what it was for the disposed arena.
4522 MOZ_RELEASE_ASSERT(mNode->mArenaId == mNode->mArena->mId);
4523 return mNode->mArena;
4524 }
4525
4526 bool IsValid() const { return !!mSize; }
4527
4528 private:
4529 size_t mSize;
4530 union {
4531 // Pointer to the chunk associated with the allocation for small
4532 // and large allocations.
4533 arena_chunk_t* mChunk;
4534
4535 // Pointer to the extent node for huge allocations.
4536 extent_node_t* mNode;
4537 };
4538 };
4539
4540 inline void MozJemalloc::jemalloc_ptr_info(const void* aPtr,
4541 jemalloc_ptr_info_t* aInfo) {
4542 arena_chunk_t* chunk = GetChunkForPtr(aPtr);
4543
4544 // Is the pointer null, or within one chunk's size of null?
4545 // Alternatively, if the allocator is not initialized yet, the pointer
4546 // can't be known.
4547 if (!chunk || !malloc_initialized) {
4548 *aInfo = {TagUnknown, nullptr, 0, 0};
4549 return;
4550 }
4551
4552 // Look for huge allocations before looking for |chunk| in gChunkRTree.
4553 // This is necessary because |chunk| won't be in gChunkRTree if it's
4554 // the second or subsequent chunk in a huge allocation.
4555 extent_node_t* node;
4556 extent_node_t key;
4557 {
4558 MutexAutoLock lock(huge_mtx);
4559 key.mAddr = const_cast<void*>(aPtr);
4560 node =
4561 reinterpret_cast<RedBlackTree<extent_node_t, ExtentTreeBoundsTrait>*>(
4562 &huge)
4563 ->Search(&key);
4564 if (node) {
4565 *aInfo = {TagLiveAlloc, node->mAddr, node->mSize, node->mArena->mId};
4566 return;
4567 }
4568 }
4569
4570 // It's not a huge allocation. Check if we have a known chunk.
4571 if (!gChunkRTree.Get(chunk)) {
4572 *aInfo = {TagUnknown, nullptr, 0, 0};
4573 return;
4574 }
4575
4576 MOZ_DIAGNOSTIC_ASSERT(chunk->arena->mMagic == ARENA_MAGIC);
4577
4578 // Get the page number within the chunk.
4579 size_t pageind = (((uintptr_t)aPtr - (uintptr_t)chunk) >> gPageSize2Pow);
4580 if (pageind < gChunkHeaderNumPages) {
4581 // Within the chunk header.
4582 *aInfo = {TagUnknown, nullptr, 0, 0};
4583 return;
4584 }
4585
4586 size_t mapbits = chunk->map[pageind].bits;
4587
4588 if (!(mapbits & CHUNK_MAP_ALLOCATED)) {
4589 void* pageaddr = (void*)(uintptr_t(aPtr) & ~gPageSizeMask);
4590 *aInfo = {TagFreedPage, pageaddr, gPageSize, chunk->arena->mId};
4591 return;
4592 }
4593
4594 if (mapbits & CHUNK_MAP_LARGE) {
4595 // It's a large allocation. Only the first page of a large
4596 // allocation contains its size, so if the address is not in
4597 // the first page, scan back to find the allocation size.
4598 size_t size;
4599 while (true) {
4600 size = mapbits & ~gPageSizeMask;
4601 if (size != 0) {
4602 break;
4603 }
4604
4605 // The following two return paths shouldn't occur in
4606 // practice unless there is heap corruption.
4607 pageind--;
4608 MOZ_DIAGNOSTIC_ASSERT(pageind >= gChunkHeaderNumPages);
4609 if (pageind < gChunkHeaderNumPages) {
4610 *aInfo = {TagUnknown, nullptr, 0, 0};
4611 return;
4612 }
4613
4614 mapbits = chunk->map[pageind].bits;
4615 MOZ_DIAGNOSTIC_ASSERT(mapbits & CHUNK_MAP_LARGE);
4616 if (!(mapbits & CHUNK_MAP_LARGE)) {
4617 *aInfo = {TagUnknown, nullptr, 0, 0};
4618 return;
4619 }
4620 }
4621
4622 void* addr = ((char*)chunk) + (pageind << gPageSize2Pow);
4623 *aInfo = {TagLiveAlloc, addr, size, chunk->arena->mId};
4624 return;
4625 }
4626
4627 // It must be a small allocation.
4628 auto run = (arena_run_t*)(mapbits & ~gPageSizeMask);
4629 MOZ_DIAGNOSTIC_ASSERT(run->mMagic == ARENA_RUN_MAGIC);
4630
4631 // The allocation size is stored in the run metadata.
4632 size_t size = run->mBin->mSizeClass;
4633
4634 // Address of the first possible pointer in the run after its headers.
4635 uintptr_t reg0_addr = (uintptr_t)run + run->mBin->mRunFirstRegionOffset;
4636 if (aPtr < (void*)reg0_addr) {
4637 // In the run header.
4638 *aInfo = {TagUnknown, nullptr, 0, 0};
4639 return;
4640 }
4641
4642 // Position in the run.
4643 unsigned regind = ((uintptr_t)aPtr - reg0_addr) / size;
4644
4645 // Pointer to the allocation's base address.
4646 void* addr = (void*)(reg0_addr + regind * size);
4647
4648 // Check if the allocation has been freed.
4649 unsigned elm = regind >> (LOG2(sizeof(int)) + 3);
4650 unsigned bit = regind - (elm << (LOG2(sizeof(int)) + 3));
4651 PtrInfoTag tag =
4652 ((run->mRegionsMask[elm] & (1U << bit))) ? TagFreedAlloc : TagLiveAlloc;
4653
4654 *aInfo = {tag, addr, size, chunk->arena->mId};
4655 }
4656
4657 namespace Debug {
4658 // Helper for debuggers. We don't want it to be inlined and optimized out.
4659 MOZ_NEVER_INLINE jemalloc_ptr_info_t* jemalloc_ptr_info(const void* aPtr) {
4660 static jemalloc_ptr_info_t info;
4661 MozJemalloc::jemalloc_ptr_info(aPtr, &info);
4662 return &info;
4663 }
4664 } // namespace Debug
4665
4666 arena_chunk_t* arena_t::DallocSmall(arena_chunk_t* aChunk, void* aPtr,
4667 arena_chunk_map_t* aMapElm) {
4668 arena_run_t* run;
4669 arena_bin_t* bin;
4670 size_t size;
4671
4672 run = (arena_run_t*)(aMapElm->bits & ~gPageSizeMask);
4673 MOZ_DIAGNOSTIC_ASSERT(run->mMagic == ARENA_RUN_MAGIC);
4674 bin = run->mBin;
4675 size = bin->mSizeClass;
4676 MOZ_DIAGNOSTIC_ASSERT(uintptr_t(aPtr) >=
4677 uintptr_t(run) + bin->mRunFirstRegionOffset);
4678
4679 arena_run_reg_dalloc(run, bin, aPtr, size);
4680 run->mNumFree++;
4681 arena_chunk_t* dealloc_chunk = nullptr;
4682
4683 if (run->mNumFree == bin->mRunNumRegions) {
4684 // This run is entirely freed, remove it from our bin.
4685 #if defined(MOZ_DIAGNOSTIC_ASSERT_ENABLED)
4686 run->mMagic = 0;
4687 #endif
4688 MOZ_ASSERT(bin->mNonFullRuns.ElementProbablyInList(run));
4689 bin->mNonFullRuns.remove(run);
4690 dealloc_chunk = DallocRun(run, true);
4691 bin->mNumRuns--;
4692 } else if (run->mNumFree == 1) {
4693 // This is first slot we freed from this run, start tracking.
4694 MOZ_ASSERT(!bin->mNonFullRuns.ElementProbablyInList(run));
4695 bin->mNonFullRuns.pushFront(run);
4696 }
4697 // else we just keep the run in mNonFullRuns where it is.
4698 // Note that we could move it to the head of the list here to get a strict
4699 // "most-recently-freed" order, but some of our benchmarks seem to be more
4700 // sensible to the increased overhead that this brings than to the order
4701 // supposedly slightly better for keeping CPU caches warm if we do.
4702 // In general we cannot foresee the future, so any order we choose might
4703 // perform different for different use cases and needs to be balanced with
4704 // the book-keeping overhead via measurements.
4705
4706 mStats.allocated_small -= size;
4707 mStats.operations++;
4708
4709 return dealloc_chunk;
4710 }
4711
4712 arena_chunk_t* arena_t::DallocLarge(arena_chunk_t* aChunk, void* aPtr) {
4713 MOZ_DIAGNOSTIC_ASSERT((uintptr_t(aPtr) & gPageSizeMask) == 0);
4714 size_t pageind = (uintptr_t(aPtr) - uintptr_t(aChunk)) >> gPageSize2Pow;
4715 size_t size = aChunk->map[pageind].bits & ~gPageSizeMask;
4716
4717 mStats.allocated_large -= size;
4718 mStats.operations++;
4719
4720 return DallocRun((arena_run_t*)aPtr, true);
4721 }
4722
4723 static inline void arena_dalloc(void* aPtr, size_t aOffset, arena_t* aArena) {
4724 MOZ_ASSERT(aPtr);
4725 MOZ_ASSERT(aOffset != 0);
4726 MOZ_ASSERT(GetChunkOffsetForPtr(aPtr) == aOffset);
4727
4728 auto chunk = (arena_chunk_t*)((uintptr_t)aPtr - aOffset);
4729 auto arena = chunk->arena;
4730 MOZ_ASSERT(arena);
4731 MOZ_DIAGNOSTIC_ASSERT(arena->mMagic == ARENA_MAGIC);
4732 MOZ_RELEASE_ASSERT(!aArena || arena == aArena);
4733
4734 size_t pageind = aOffset >> gPageSize2Pow;
4735 if (opt_poison) {
4736 AllocInfo info = AllocInfo::GetInChunk(aPtr, chunk, pageind);
4737 MOZ_ASSERT(info.IsValid());
4738 MaybePoison(aPtr, info.Size());
4739 }
4740
4741 arena_chunk_t* chunk_dealloc_delay = nullptr;
4742 purge_action_t purge_action;
4743 {
4744 MOZ_DIAGNOSTIC_ASSERT(arena->mLock.SafeOnThisThread());
4745 MaybeMutexAutoLock lock(arena->mLock);
4746 arena_chunk_map_t* mapelm = &chunk->map[pageind];
4747 MOZ_RELEASE_ASSERT(
4748 (mapelm->bits &
4749 (CHUNK_MAP_FRESH_MADVISED_OR_DECOMMITTED | CHUNK_MAP_ZEROED)) == 0,
4750 "Freeing in a page with bad bits.");
4751 MOZ_RELEASE_ASSERT((mapelm->bits & CHUNK_MAP_ALLOCATED) != 0,
4752 "Double-free?");
4753 if ((mapelm->bits & CHUNK_MAP_LARGE) == 0) {
4754 // Small allocation.
4755 chunk_dealloc_delay = arena->DallocSmall(chunk, aPtr, mapelm);
4756 } else {
4757 // Large allocation.
4758 chunk_dealloc_delay = arena->DallocLarge(chunk, aPtr);
4759 }
4760
4761 purge_action = arena->ShouldStartPurge();
4762 }
4763
4764 if (chunk_dealloc_delay) {
4765 chunk_dealloc((void*)chunk_dealloc_delay, kChunkSize, ARENA_CHUNK);
4766 }
4767
4768 arena->MayDoOrQueuePurge(purge_action);
4769 }
4770
4771 static inline void idalloc(void* ptr, arena_t* aArena) {
4772 size_t offset;
4773
4774 MOZ_ASSERT(ptr);
4775
4776 offset = GetChunkOffsetForPtr(ptr);
4777 if (offset != 0) {
4778 arena_dalloc(ptr, offset, aArena);
4779 } else {
4780 huge_dalloc(ptr, aArena);
4781 }
4782 }
4783
4784 inline purge_action_t arena_t::ShouldStartPurge() {
4785 if (mNumDirty > mMaxDirty) {
4786 if (!mIsDeferredPurgeEnabled) {
4787 return purge_action_t::PurgeNow;
4788 }
4789 if (mIsPurgePending) {
4790 return purge_action_t::None;
4791 }
4792 mIsPurgePending = true;
4793 return purge_action_t::Queue;
4794 }
4795 return purge_action_t::None;
4796 }
4797
4798 inline void arena_t::MayDoOrQueuePurge(purge_action_t aAction) {
4799 switch (aAction) {
4800 case purge_action_t::Queue:
4801 // Note that this thread committed earlier by setting
4802 // mIsDeferredPurgePending to add us to the list. There is a low
4803 // chance that in the meantime another thread ran Purge() and cleared
4804 // the flag, but that is fine, we'll adjust our bookkeeping when calling
4805 // ShouldStartPurge() or Purge() next time.
4806 gArenas.AddToOutstandingPurges(this);
4807 break;
4808 case purge_action_t::PurgeNow:
4809 PurgeResult pr;
4810 do {
4811 pr = Purge(PurgeIfThreshold);
4812 } while (pr == arena_t::PurgeResult::Continue);
4813 // Arenas cannot die here because the caller is still using the arena, if
4814 // they did it'd be a use-after-free: the arena is destroyed but then used
4815 // afterwards.
4816 MOZ_RELEASE_ASSERT(pr != arena_t::PurgeResult::Dying);
4817 break;
4818 case purge_action_t::None:
4819 // do nothing.
4820 break;
4821 }
4822 }
4823
4824 inline void arena_t::NotifySignificantReuse() {
4825 // Note that there is a chance here for a race between threads calling
4826 // GetTimeStampNS in a different order than writing it to the Atomic,
4827 // resulting in mLastSignificantReuseNS going potentially backwards.
4828 // Our use case is not sensitive to small deviations, the worse that can
4829 // happen is a slightly earlier purge.
4830 mLastSignificantReuseNS = GetTimestampNS();
4831 }
4832
4833 void arena_t::RallocShrinkLarge(arena_chunk_t* aChunk, void* aPtr, size_t aSize,
4834 size_t aOldSize) {
4835 MOZ_ASSERT(aSize < aOldSize);
4836
4837 // Shrink the run, and make trailing pages available for other
4838 // allocations.
4839 purge_action_t purge_action;
4840 {
4841 MaybeMutexAutoLock lock(mLock);
4842 TrimRunTail(aChunk, (arena_run_t*)aPtr, aOldSize, aSize, true);
4843 mStats.allocated_large -= aOldSize - aSize;
4844 mStats.operations++;
4845
4846 purge_action = ShouldStartPurge();
4847 }
4848 MayDoOrQueuePurge(purge_action);
4849 }
4850
4851 // Returns whether reallocation was successful.
4852 bool arena_t::RallocGrowLarge(arena_chunk_t* aChunk, void* aPtr, size_t aSize,
4853 size_t aOldSize) {
4854 size_t pageind = (uintptr_t(aPtr) - uintptr_t(aChunk)) >> gPageSize2Pow;
4855 size_t npages = aOldSize >> gPageSize2Pow;
4856
4857 size_t num_dirty_before, num_dirty_after;
4858 {
4859 MaybeMutexAutoLock lock(mLock);
4860 MOZ_DIAGNOSTIC_ASSERT(aOldSize ==
4861 (aChunk->map[pageind].bits & ~gPageSizeMask));
4862
4863 // Try to extend the run.
4864 MOZ_ASSERT(aSize > aOldSize);
4865 if (pageind + npages < gChunkNumPages - 1 &&
4866 (aChunk->map[pageind + npages].bits &
4867 (CHUNK_MAP_ALLOCATED | CHUNK_MAP_BUSY)) == 0 &&
4868 (aChunk->map[pageind + npages].bits & ~gPageSizeMask) >=
4869 aSize - aOldSize) {
4870 num_dirty_before = mNumDirty;
4871 // The next run is available and sufficiently large. Split the
4872 // following run, then merge the first part with the existing
4873 // allocation.
4874 if (!SplitRun((arena_run_t*)(uintptr_t(aChunk) +
4875 ((pageind + npages) << gPageSize2Pow)),
4876 aSize - aOldSize, true, false)) {
4877 return false;
4878 }
4879
4880 aChunk->map[pageind].bits = aSize | CHUNK_MAP_LARGE | CHUNK_MAP_ALLOCATED;
4881 aChunk->map[pageind + npages].bits =
4882 CHUNK_MAP_LARGE | CHUNK_MAP_ALLOCATED;
4883
4884 mStats.allocated_large += aSize - aOldSize;
4885 mStats.operations++;
4886 num_dirty_after = mNumDirty;
4887 } else {
4888 return false;
4889 }
4890 }
4891 if (num_dirty_after < num_dirty_before) {
4892 NotifySignificantReuse();
4893 }
4894 return true;
4895 }
4896
4897 void* arena_t::RallocSmallOrLarge(void* aPtr, size_t aSize, size_t aOldSize) {
4898 void* ret;
4899 size_t copysize;
4900 SizeClass sizeClass(aSize);
4901
4902 // Try to avoid moving the allocation.
4903 if (aOldSize <= gMaxLargeClass && sizeClass.Size() == aOldSize) {
4904 if (aSize < aOldSize) {
4905 MaybePoison((void*)(uintptr_t(aPtr) + aSize), aOldSize - aSize);
4906 }
4907 return aPtr;
4908 }
4909 if (sizeClass.Type() == SizeClass::Large && aOldSize > gMaxBinClass &&
4910 aOldSize <= gMaxLargeClass) {
4911 arena_chunk_t* chunk = GetChunkForPtr(aPtr);
4912 if (sizeClass.Size() < aOldSize) {
4913 // Fill before shrinking in order to avoid a race.
4914 MaybePoison((void*)((uintptr_t)aPtr + aSize), aOldSize - aSize);
4915 RallocShrinkLarge(chunk, aPtr, sizeClass.Size(), aOldSize);
4916 return aPtr;
4917 }
4918 if (RallocGrowLarge(chunk, aPtr, sizeClass.Size(), aOldSize)) {
4919 ApplyZeroOrJunk((void*)((uintptr_t)aPtr + aOldSize), aSize - aOldSize);
4920 return aPtr;
4921 }
4922 }
4923
4924 // If we get here, then aSize and aOldSize are different enough that we
4925 // need to move the object or the run can't be expanded because the memory
4926 // after it is allocated or busy. In that case, fall back to allocating new
4927 // space and copying. Allow non-private arenas to switch arenas.
4928 ret = (mIsPrivate ? this : choose_arena(aSize))->Malloc(aSize, false);
4929 if (!ret) {
4930 return nullptr;
4931 }
4932
4933 // Junk/zero-filling were already done by arena_t::Malloc().
4934 copysize = (aSize < aOldSize) ? aSize : aOldSize;
4935 #ifdef VM_COPY_MIN
4936 if (copysize >= VM_COPY_MIN) {
4937 pages_copy(ret, aPtr, copysize);
4938 } else
4939 #endif
4940 {
4941 memcpy(ret, aPtr, copysize);
4942 }
4943 idalloc(aPtr, this);
4944 return ret;
4945 }
4946
4947 void* arena_t::Ralloc(void* aPtr, size_t aSize, size_t aOldSize) {
4948 MOZ_DIAGNOSTIC_ASSERT(mMagic == ARENA_MAGIC);
4949 MOZ_ASSERT(aPtr);
4950 MOZ_ASSERT(aSize != 0);
4951
4952 return (aSize <= gMaxLargeClass) ? RallocSmallOrLarge(aPtr, aSize, aOldSize)
4953 : RallocHuge(aPtr, aSize, aOldSize);
4954 }
4955
4956 void* arena_t::operator new(size_t aCount, const fallible_t&) noexcept {
4957 MOZ_ASSERT(aCount == sizeof(arena_t));
4958 return TypedBaseAlloc<arena_t>::alloc();
4959 }
4960
4961 void arena_t::operator delete(void* aPtr) {
4962 TypedBaseAlloc<arena_t>::dealloc((arena_t*)aPtr);
4963 }
4964
4965 arena_t::arena_t(arena_params_t* aParams, bool aIsPrivate) {
4966 unsigned i;
4967
4968 memset(&mLink, 0, sizeof(mLink));
4969 memset(&mStats, 0, sizeof(arena_stats_t));
4970 mId = 0;
4971
4972 // Initialize chunks.
4973 mChunksDirty.Init();
4974 #ifdef MALLOC_DOUBLE_PURGE
4975 new (&mChunksMAdvised) DoublyLinkedList<arena_chunk_t>();
4976 #endif
4977 mSpare = nullptr;
4978
4979 mRandomizeSmallAllocations = opt_randomize_small;
4980 MaybeMutex::DoLock doLock = MaybeMutex::MUST_LOCK;
4981 if (aParams) {
4982 uint32_t randFlags = aParams->mFlags & ARENA_FLAG_RANDOMIZE_SMALL_MASK;
4983 switch (randFlags) {
4984 case ARENA_FLAG_RANDOMIZE_SMALL_ENABLED:
4985 mRandomizeSmallAllocations = true;
4986 break;
4987 case ARENA_FLAG_RANDOMIZE_SMALL_DISABLED:
4988 mRandomizeSmallAllocations = false;
4989 break;
4990 case ARENA_FLAG_RANDOMIZE_SMALL_DEFAULT:
4991 default:
4992 break;
4993 }
4994
4995 uint32_t threadFlags = aParams->mFlags & ARENA_FLAG_THREAD_MASK;
4996 if (threadFlags == ARENA_FLAG_THREAD_MAIN_THREAD_ONLY) {
4997 // At the moment we require that any ARENA_FLAG_THREAD_MAIN_THREAD_ONLY
4998 // arenas are created and therefore always accessed by the main thread.
4999 // This is for two reasons:
5000 // * it allows jemalloc_stats to read their statistics (we also require
5001 // that jemalloc_stats is only used on the main thread).
5002 // * Only main-thread or threadsafe arenas can be guanteed to be in a
5003 // consistent state after a fork() from the main thread. If fork()
5004 // occurs off-thread then the new child process cannot use these arenas
5005 // (new children should usually exec() or exit() since other data may
5006 // also be inconsistent).
5007 MOZ_ASSERT(gArenas.IsOnMainThread());
5008 MOZ_ASSERT(aIsPrivate);
5009 doLock = MaybeMutex::AVOID_LOCK_UNSAFE;
5010 }
5011
5012 mMaxDirtyIncreaseOverride = aParams->mMaxDirtyIncreaseOverride;
5013 mMaxDirtyDecreaseOverride = aParams->mMaxDirtyDecreaseOverride;
5014 } else {
5015 mMaxDirtyIncreaseOverride = 0;
5016 mMaxDirtyDecreaseOverride = 0;
5017 }
5018
5019 mLastSignificantReuseNS = GetTimestampNS();
5020 mIsPurgePending = false;
5021 mIsDeferredPurgeEnabled = gArenas.IsDeferredPurgeEnabled();
5022
5023 MOZ_RELEASE_ASSERT(mLock.Init(doLock));
5024
5025 mPRNG = nullptr;
5026 mIsPRNGInitializing = false;
5027
5028 mIsPrivate = aIsPrivate;
5029
5030 mNumDirty = 0;
5031 mNumFresh = 0;
5032 mNumMAdvised = 0;
5033 // The default maximum amount of dirty pages allowed on arenas is a fraction
5034 // of opt_dirty_max.
5035 mMaxDirtyBase = (aParams && aParams->mMaxDirty) ? aParams->mMaxDirty
5036 : (opt_dirty_max / 8);
5037 UpdateMaxDirty();
5038
5039 mRunsAvail.Init();
5040
5041 // Initialize bins.
5042 SizeClass sizeClass(1);
5043
5044 for (i = 0;; i++) {
5045 arena_bin_t& bin = mBins[i];
5046 bin.Init(sizeClass);
5047
5048 // SizeClass doesn't want sizes larger than gMaxBinClass for now.
5049 if (sizeClass.Size() == gMaxBinClass) {
5050 break;
5051 }
5052 sizeClass = sizeClass.Next();
5053 }
5054 MOZ_ASSERT(i == NUM_SMALL_CLASSES - 1);
5055
5056 #if defined(MOZ_DIAGNOSTIC_ASSERT_ENABLED)
5057 mMagic = ARENA_MAGIC;
5058 #endif
5059 }
5060
5061 arena_t::~arena_t() {
5062 size_t i;
5063 MaybeMutexAutoLock lock(mLock);
5064
5065 MOZ_RELEASE_ASSERT(!mLink.Left() && !mLink.Right(),
5066 "Arena is still registered");
5067 MOZ_RELEASE_ASSERT(!mStats.allocated_small && !mStats.allocated_large,
5068 "Arena is not empty");
5069 if (mSpare) {
5070 chunk_dealloc(mSpare, kChunkSize, ARENA_CHUNK);
5071 }
5072 for (i = 0; i < NUM_SMALL_CLASSES; i++) {
5073 MOZ_RELEASE_ASSERT(mBins[i].mNonFullRuns.isEmpty(), "Bin is not empty");
5074 }
5075 #ifdef MOZ_DEBUG
5076 {
5077 MutexAutoLock lock(huge_mtx);
5078 // This is an expensive check, so we only do it on debug builds.
5079 for (auto node : huge.iter()) {
5080 MOZ_RELEASE_ASSERT(node->mArenaId != mId, "Arena has huge allocations");
5081 }
5082 }
5083 #endif
5084 mId = 0;
5085 }
5086
5087 arena_t* ArenaCollection::CreateArena(bool aIsPrivate,
5088 arena_params_t* aParams) {
5089 arena_t* ret = new (fallible) arena_t(aParams, aIsPrivate);
5090 if (!ret) {
5091 // Only reached if there is an OOM error.
5092
5093 // OOM here is quite inconvenient to propagate, since dealing with it
5094 // would require a check for failure in the fast path. Instead, punt
5095 // by using the first arena.
5096 // In practice, this is an extremely unlikely failure.
5097 _malloc_message(_getprogname(), ": (malloc) Error initializing arena\n");
5098
5099 return mDefaultArena;
5100 }
5101
5102 MutexAutoLock lock(mLock);
5103
5104 // For public arenas, it's fine to just use incrementing arena id
5105 if (!aIsPrivate) {
5106 ret->mId = mLastPublicArenaId++;
5107 mArenas.Insert(ret);
5108 return ret;
5109 }
5110
5111 #ifdef NON_RANDOM_ARENA_IDS
5112 // For private arenas, slightly obfuscate the id by XORing a key generated
5113 // once, and rotate the bits by an amount also generated once.
5114 if (mArenaIdKey == 0) {
5115 mozilla::Maybe<uint64_t> maybeRandom = mozilla::RandomUint64();
5116 MOZ_RELEASE_ASSERT(maybeRandom.isSome());
5117 mArenaIdKey = maybeRandom.value();
5118 maybeRandom = mozilla::RandomUint64();
5119 MOZ_RELEASE_ASSERT(maybeRandom.isSome());
5120 mArenaIdRotation = maybeRandom.value() & (sizeof(void*) * 8 - 1);
5121 }
5122 arena_id_t id = reinterpret_cast<arena_id_t>(ret) ^ mArenaIdKey;
5123 ret->mId =
5124 (id >> mArenaIdRotation) | (id << (sizeof(void*) * 8 - mArenaIdRotation));
5125 mPrivateArenas.Insert(ret);
5126 return ret;
5127 #else
5128 // For private arenas, generate a cryptographically-secure random id for the
5129 // new arena. If an attacker manages to get control of the process, this
5130 // should make it more difficult for them to "guess" the ID of a memory
5131 // arena, stopping them from getting data they may want
5132 Tree& tree = (ret->IsMainThreadOnly()) ? mMainThreadArenas : mPrivateArenas;
5133 arena_id_t arena_id;
5134 do {
5135 arena_id = MakeRandArenaId(ret->IsMainThreadOnly());
5136 // Keep looping until we ensure that the random number we just generated
5137 // isn't already in use by another active arena
5138 } while (GetByIdInternal(tree, arena_id));
5139
5140 ret->mId = arena_id;
5141 tree.Insert(ret);
5142 return ret;
5143 #endif
5144 }
5145
5146 #ifndef NON_RANDOM_ARENA_IDS
5147 arena_id_t ArenaCollection::MakeRandArenaId(bool aIsMainThreadOnly) const {
5148 uint64_t rand;
5149 do {
5150 mozilla::Maybe<uint64_t> maybeRandomId = mozilla::RandomUint64();
5151 MOZ_RELEASE_ASSERT(maybeRandomId.isSome());
5152
5153 rand = maybeRandomId.value();
5154
5155 // Set or clear the least significant bit depending on if this is a
5156 // main-thread-only arena. We use this in GetById.
5157 if (aIsMainThreadOnly) {
5158 rand = rand | MAIN_THREAD_ARENA_BIT;
5159 } else {
5160 rand = rand & ~MAIN_THREAD_ARENA_BIT;
5161 }
5162
5163 // Avoid 0 as an arena Id. We use 0 for disposed arenas.
5164 } while (rand == 0);
5165
5166 return arena_id_t(rand);
5167 }
5168 #endif
5169
5170 // End arena.
5171 // ***************************************************************************
5172 // Begin general internal functions.
5173
5174 // Initialize huge allocation data.
5175 static void huge_init() MOZ_REQUIRES(gInitLock) {
5176 huge_mtx.Init();
5177 MOZ_PUSH_IGNORE_THREAD_SAFETY
5178 huge.Init();
5179 huge_allocated = 0;
5180 huge_mapped = 0;
5181 huge_operations = 0;
5182 MOZ_POP_THREAD_SAFETY
5183 }
5184
5185 void* arena_t::MallocHuge(size_t aSize, bool aZero) {
5186 return PallocHuge(aSize, kChunkSize, aZero);
5187 }
5188
5189 void* arena_t::PallocHuge(size_t aSize, size_t aAlignment, bool aZero) {
5190 void* ret;
5191 size_t csize;
5192 size_t psize;
5193 extent_node_t* node;
5194
5195 // We're going to configure guard pages in the region between the
5196 // page-aligned size and the chunk-aligned size, so if those are the same
5197 // then we need to force that region into existence.
5198 csize = CHUNK_CEILING(aSize + gPageSize);
5199 if (csize < aSize) {
5200 // size is large enough to cause size_t wrap-around.
5201 return nullptr;
5202 }
5203
5204 // Allocate an extent node with which to track the chunk.
5205 node = ExtentAlloc::alloc();
5206 if (!node) {
5207 return nullptr;
5208 }
5209
5210 // Allocate one or more contiguous chunks for this request.
5211 ret = chunk_alloc(csize, aAlignment, false);
5212 if (!ret) {
5213 ExtentAlloc::dealloc(node);
5214 return nullptr;
5215 }
5216 psize = PAGE_CEILING(aSize);
5217 #ifdef MOZ_DEBUG
5218 if (aZero) {
5219 chunk_assert_zero(ret, psize);
5220 }
5221 #endif
5222
5223 // Insert node into huge.
5224 node->mAddr = ret;
5225 node->mSize = psize;
5226 node->mArena = this;
5227 node->mArenaId = mId;
5228
5229 {
5230 MutexAutoLock lock(huge_mtx);
5231 huge.Insert(node);
5232
5233 // Although we allocated space for csize bytes, we indicate that we've
5234 // allocated only psize bytes.
5235 //
5236 // If DECOMMIT is defined, this is a reasonable thing to do, since
5237 // we'll explicitly decommit the bytes in excess of psize.
5238 //
5239 // If DECOMMIT is not defined, then we're relying on the OS to be lazy
5240 // about how it allocates physical pages to mappings. If we never
5241 // touch the pages in excess of psize, the OS won't allocate a physical
5242 // page, and we won't use more than psize bytes of physical memory.
5243 //
5244 // A correct program will only touch memory in excess of how much it
5245 // requested if it first calls malloc_usable_size and finds out how
5246 // much space it has to play with. But because we set node->mSize =
5247 // psize above, malloc_usable_size will return psize, not csize, and
5248 // the program will (hopefully) never touch bytes in excess of psize.
5249 // Thus those bytes won't take up space in physical memory, and we can
5250 // reasonably claim we never "allocated" them in the first place.
5251 huge_allocated += psize;
5252 huge_mapped += csize;
5253 huge_operations++;
5254 }
5255
5256 pages_decommit((void*)((uintptr_t)ret + psize), csize - psize);
5257
5258 if (!aZero) {
5259 ApplyZeroOrJunk(ret, psize);
5260 }
5261
5262 return ret;
5263 }
5264
5265 void* arena_t::RallocHuge(void* aPtr, size_t aSize, size_t aOldSize) {
5266 void* ret;
5267 size_t copysize;
5268
5269 // Avoid moving the allocation if the size class would not change.
5270 if (aOldSize > gMaxLargeClass &&
5271 CHUNK_CEILING(aSize + gPageSize) == CHUNK_CEILING(aOldSize + gPageSize)) {
5272 size_t psize = PAGE_CEILING(aSize);
5273 if (aSize < aOldSize) {
5274 MaybePoison((void*)((uintptr_t)aPtr + aSize), aOldSize - aSize);
5275 }
5276 if (psize < aOldSize) {
5277 extent_node_t key;
5278
5279 pages_decommit((void*)((uintptr_t)aPtr + psize), aOldSize - psize);
5280
5281 // Update recorded size.
5282 MutexAutoLock lock(huge_mtx);
5283 key.mAddr = const_cast<void*>(aPtr);
5284 extent_node_t* node = huge.Search(&key);
5285 MOZ_ASSERT(node);
5286 MOZ_ASSERT(node->mSize == aOldSize);
5287 MOZ_RELEASE_ASSERT(node->mArena == this);
5288 huge_allocated -= aOldSize - psize;
5289 huge_operations++;
5290 // No need to change huge_mapped, because we didn't (un)map anything.
5291 node->mSize = psize;
5292 } else if (psize > aOldSize) {
5293 if (!pages_commit((void*)((uintptr_t)aPtr + aOldSize),
5294 psize - aOldSize)) {
5295 return nullptr;
5296 }
5297
5298 // We need to update the recorded size if the size increased,
5299 // so malloc_usable_size doesn't return a value smaller than
5300 // what was requested via realloc().
5301 extent_node_t key;
5302 MutexAutoLock lock(huge_mtx);
5303 key.mAddr = const_cast<void*>(aPtr);
5304 extent_node_t* node = huge.Search(&key);
5305 MOZ_ASSERT(node);
5306 MOZ_ASSERT(node->mSize == aOldSize);
5307 MOZ_RELEASE_ASSERT(node->mArena == this);
5308 huge_allocated += psize - aOldSize;
5309 huge_operations++;
5310 // No need to change huge_mapped, because we didn't
5311 // (un)map anything.
5312 node->mSize = psize;
5313 }
5314
5315 if (aSize > aOldSize) {
5316 ApplyZeroOrJunk((void*)((uintptr_t)aPtr + aOldSize), aSize - aOldSize);
5317 }
5318 return aPtr;
5319 }
5320
5321 // If we get here, then aSize and aOldSize are different enough that we
5322 // need to use a different size class. In that case, fall back to allocating
5323 // new space and copying. Allow non-private arenas to switch arenas.
5324 ret = (mIsPrivate ? this : choose_arena(aSize))->MallocHuge(aSize, false);
5325 if (!ret) {
5326 return nullptr;
5327 }
5328
5329 copysize = (aSize < aOldSize) ? aSize : aOldSize;
5330 #ifdef VM_COPY_MIN
5331 if (copysize >= VM_COPY_MIN) {
5332 pages_copy(ret, aPtr, copysize);
5333 } else
5334 #endif
5335 {
5336 memcpy(ret, aPtr, copysize);
5337 }
5338 idalloc(aPtr, this);
5339 return ret;
5340 }
5341
5342 static void huge_dalloc(void* aPtr, arena_t* aArena) {
5343 extent_node_t* node;
5344 size_t mapped = 0;
5345 {
5346 extent_node_t key;
5347 MutexAutoLock lock(huge_mtx);
5348
5349 // Extract from tree of huge allocations.
5350 key.mAddr = aPtr;
5351 node = huge.Search(&key);
5352 MOZ_RELEASE_ASSERT(node, "Double-free?");
5353 MOZ_ASSERT(node->mAddr == aPtr);
5354 MOZ_RELEASE_ASSERT(!aArena || node->mArena == aArena);
5355 // See AllocInfo::Arena.
5356 MOZ_RELEASE_ASSERT(node->mArenaId == node->mArena->mId);
5357 huge.Remove(node);
5358
5359 mapped = CHUNK_CEILING(node->mSize + gPageSize);
5360 huge_allocated -= node->mSize;
5361 huge_mapped -= mapped;
5362 huge_operations++;
5363 }
5364
5365 // Unmap chunk.
5366 chunk_dealloc(node->mAddr, mapped, HUGE_CHUNK);
5367
5368 ExtentAlloc::dealloc(node);
5369 }
5370
5371 size_t GetKernelPageSize() {
5372 static size_t kernel_page_size = ([]() {
5373 #ifdef XP_WIN
5374 SYSTEM_INFO info;
5375 GetSystemInfo(&info);
5376 return info.dwPageSize;
5377 #else
5378 long result = sysconf(_SC_PAGESIZE);
5379 MOZ_ASSERT(result != -1);
5380 return result;
5381 #endif
5382 })();
5383 return kernel_page_size;
5384 }
5385
5386 // Returns whether the allocator was successfully initialized.
5387 static bool malloc_init_hard() {
5388 unsigned i;
5389 const char* opts;
5390
5391 AutoLock<StaticMutex> lock(gInitLock);
5392
5393 if (malloc_initialized) {
5394 // Another thread initialized the allocator before this one
5395 // acquired gInitLock.
5396 return true;
5397 }
5398
5399 if (!thread_arena.init()) {
5400 return true;
5401 }
5402
5403 // Get page size and number of CPUs
5404 const size_t page_size = GetKernelPageSize();
5405 // We assume that the page size is a power of 2.
5406 MOZ_ASSERT(IsPowerOfTwo(page_size));
5407 #ifdef MALLOC_STATIC_PAGESIZE
5408 if (gPageSize % page_size) {
5409 _malloc_message(
5410 _getprogname(),
5411 "Compile-time page size does not divide the runtime one.\n");
5412 MOZ_CRASH();
5413 }
5414 #else
5415 gRealPageSize = gPageSize = page_size;
5416 #endif
5417
5418 // Get runtime configuration.
5419 if ((opts = getenv("MALLOC_OPTIONS"))) {
5420 for (i = 0; opts[i] != '\0'; i++) {
5421 // All options are single letters, some take a *prefix* numeric argument.
5422
5423 // Parse the argument.
5424 unsigned prefix_arg = 0;
5425 while (opts[i] >= '0' && opts[i] <= '9') {
5426 prefix_arg *= 10;
5427 prefix_arg += opts[i] - '0';
5428 i++;
5429 }
5430
5431 switch (opts[i]) {
5432 case 'f':
5433 opt_dirty_max >>= prefix_arg ? prefix_arg : 1;
5434 break;
5435 case 'F':
5436 prefix_arg = prefix_arg ? prefix_arg : 1;
5437 if (opt_dirty_max == 0) {
5438 opt_dirty_max = 1;
5439 prefix_arg--;
5440 }
5441 opt_dirty_max <<= prefix_arg;
5442 if (opt_dirty_max == 0) {
5443 // If the shift above overflowed all the bits then clamp the result
5444 // instead. If we started with DIRTY_MAX_DEFAULT then this will
5445 // always be a power of two so choose the maximum power of two that
5446 // fits in a size_t.
5447 opt_dirty_max = size_t(1) << (sizeof(size_t) * CHAR_BIT - 1);
5448 }
5449 break;
5450 #ifdef MALLOC_RUNTIME_CONFIG
5451 case 'j':
5452 opt_junk = false;
5453 break;
5454 case 'J':
5455 opt_junk = true;
5456 break;
5457 case 'q':
5458 // The argument selects how much poisoning to do.
5459 opt_poison = NONE;
5460 break;
5461 case 'Q':
5462 if (opts[i + 1] == 'Q') {
5463 // Maximum poisoning.
5464 i++;
5465 opt_poison = ALL;
5466 } else {
5467 opt_poison = SOME;
5468 opt_poison_size = kCacheLineSize * prefix_arg;
5469 }
5470 break;
5471 case 'z':
5472 opt_zero = false;
5473 break;
5474 case 'Z':
5475 opt_zero = true;
5476 break;
5477 # ifndef MALLOC_STATIC_PAGESIZE
5478 case 'P':
5479 MOZ_ASSERT(gPageSize >= 4_KiB);
5480 MOZ_ASSERT(gPageSize <= 64_KiB);
5481 prefix_arg = prefix_arg ? prefix_arg : 1;
5482 gPageSize <<= prefix_arg;
5483 // We know that if the shift causes gPageSize to be zero then it's
5484 // because it shifted all the bits off. We didn't start with zero.
5485 // Therefore if gPageSize is out of bounds we set it to 64KiB.
5486 if (gPageSize < 4_KiB || gPageSize > 64_KiB) {
5487 gPageSize = 64_KiB;
5488 }
5489 break;
5490 # endif
5491 #endif
5492 case 'r':
5493 opt_randomize_small = false;
5494 break;
5495 case 'R':
5496 opt_randomize_small = true;
5497 break;
5498 default: {
5499 char cbuf[2];
5500
5501 cbuf[0] = opts[i];
5502 cbuf[1] = '\0';
5503 _malloc_message(_getprogname(),
5504 ": (malloc) Unsupported character "
5505 "in malloc options: '",
5506 cbuf, "'\n");
5507 }
5508 }
5509 }
5510 }
5511
5512 #ifndef MALLOC_STATIC_PAGESIZE
5513 DefineGlobals();
5514 #endif
5515 gRecycledSize = 0;
5516
5517 chunks_init();
5518 huge_init();
5519 base_init();
5520
5521 // Initialize arenas collection here.
5522 if (!gArenas.Init()) {
5523 return false;
5524 }
5525
5526 // Assign the default arena to the initial thread.
5527 thread_arena.set(gArenas.GetDefault());
5528
5529 if (!gChunkRTree.Init()) {
5530 return false;
5531 }
5532
5533 malloc_initialized = true;
5534
5535 // Dummy call so that the function is not removed by dead-code elimination
5536 Debug::jemalloc_ptr_info(nullptr);
5537
5538 #if !defined(XP_WIN) && !defined(XP_DARWIN)
5539 // Prevent potential deadlock on malloc locks after fork.
5540 pthread_atfork(_malloc_prefork, _malloc_postfork_parent,
5541 _malloc_postfork_child);
5542 #endif
5543
5544 return true;
5545 }
5546
5547 // End general internal functions.
5548 // ***************************************************************************
5549 // Begin malloc(3)-compatible functions.
5550
5551 // The BaseAllocator class is a helper class that implements the base allocator
5552 // functions (malloc, calloc, realloc, free, memalign) for a given arena,
5553 // or an appropriately chosen arena (per choose_arena()) when none is given.
5554 struct BaseAllocator {
5555 #define MALLOC_DECL(name, return_type, ...) \
5556 inline return_type name(__VA_ARGS__);
5557
5558 #define MALLOC_FUNCS MALLOC_FUNCS_MALLOC_BASE
5559 #include "malloc_decls.h"
5560
5561 explicit BaseAllocator(arena_t* aArena) : mArena(aArena) {}
5562
5563 private:
5564 arena_t* mArena;
5565 };
5566
5567 #define MALLOC_DECL(name, return_type, ...) \
5568 inline return_type MozJemalloc::name( \
5569 ARGS_HELPER(TYPED_ARGS, ##__VA_ARGS__)) { \
5570 BaseAllocator allocator(nullptr); \
5571 return allocator.name(ARGS_HELPER(ARGS, ##__VA_ARGS__)); \
5572 }
5573 #define MALLOC_FUNCS MALLOC_FUNCS_MALLOC_BASE
5574 #include "malloc_decls.h"
5575
5576 inline void* BaseAllocator::malloc(size_t aSize) {
5577 void* ret;
5578 arena_t* arena;
5579
5580 if (!malloc_init()) {
5581 ret = nullptr;
5582 goto RETURN;
5583 }
5584
5585 if (aSize == 0) {
5586 aSize = 1;
5587 }
5588 // If mArena is non-null, it must not be in the first page.
5589 MOZ_DIAGNOSTIC_ASSERT_IF(mArena, (size_t)mArena >= gPageSize);
5590 arena = mArena ? mArena : choose_arena(aSize);
5591 ret = arena->Malloc(aSize, /* aZero = */ false);
5592
5593 RETURN:
5594 if (!ret) {
5595 errno = ENOMEM;
5596 }
5597
5598 return ret;
5599 }
5600
5601 inline void* BaseAllocator::memalign(size_t aAlignment, size_t aSize) {
5602 MOZ_ASSERT(((aAlignment - 1) & aAlignment) == 0);
5603
5604 if (!malloc_init()) {
5605 return nullptr;
5606 }
5607
5608 if (aSize == 0) {
5609 aSize = 1;
5610 }
5611
5612 aAlignment = aAlignment < sizeof(void*) ? sizeof(void*) : aAlignment;
5613 arena_t* arena = mArena ? mArena : choose_arena(aSize);
5614 return arena->Palloc(aAlignment, aSize);
5615 }
5616
5617 inline void* BaseAllocator::calloc(size_t aNum, size_t aSize) {
5618 void* ret;
5619
5620 if (malloc_init()) {
5621 CheckedInt<size_t> checkedSize = CheckedInt<size_t>(aNum) * aSize;
5622 if (checkedSize.isValid()) {
5623 size_t allocSize = checkedSize.value();
5624 if (allocSize == 0) {
5625 allocSize = 1;
5626 }
5627 arena_t* arena = mArena ? mArena : choose_arena(allocSize);
5628 ret = arena->Malloc(allocSize, /* aZero = */ true);
5629 } else {
5630 ret = nullptr;
5631 }
5632 } else {
5633 ret = nullptr;
5634 }
5635
5636 if (!ret) {
5637 errno = ENOMEM;
5638 }
5639
5640 return ret;
5641 }
5642
5643 inline void* BaseAllocator::realloc(void* aPtr, size_t aSize) {
5644 void* ret;
5645
5646 if (aSize == 0) {
5647 aSize = 1;
5648 }
5649
5650 if (aPtr) {
5651 MOZ_RELEASE_ASSERT(malloc_initialized);
5652
5653 auto info = AllocInfo::Get(aPtr);
5654 auto arena = info.Arena();
5655 MOZ_RELEASE_ASSERT(!mArena || arena == mArena);
5656 ret = arena->Ralloc(aPtr, aSize, info.Size());
5657 } else {
5658 if (!malloc_init()) {
5659 ret = nullptr;
5660 } else {
5661 arena_t* arena = mArena ? mArena : choose_arena(aSize);
5662 ret = arena->Malloc(aSize, /* aZero = */ false);
5663 }
5664 }
5665
5666 if (!ret) {
5667 errno = ENOMEM;
5668 }
5669 return ret;
5670 }
5671
5672 inline void BaseAllocator::free(void* aPtr) {
5673 size_t offset;
5674
5675 // A version of idalloc that checks for nullptr pointer.
5676 offset = GetChunkOffsetForPtr(aPtr);
5677 if (offset != 0) {
5678 MOZ_RELEASE_ASSERT(malloc_initialized);
5679 arena_dalloc(aPtr, offset, mArena);
5680 } else if (aPtr) {
5681 MOZ_RELEASE_ASSERT(malloc_initialized);
5682 huge_dalloc(aPtr, mArena);
5683 }
5684 }
5685
5686 inline int MozJemalloc::posix_memalign(void** aMemPtr, size_t aAlignment,
5687 size_t aSize) {
5688 return AlignedAllocator<memalign>::posix_memalign(aMemPtr, aAlignment, aSize);
5689 }
5690
5691 inline void* MozJemalloc::aligned_alloc(size_t aAlignment, size_t aSize) {
5692 return AlignedAllocator<memalign>::aligned_alloc(aAlignment, aSize);
5693 }
5694
5695 inline void* MozJemalloc::valloc(size_t aSize) {
5696 return AlignedAllocator<memalign>::valloc(aSize);
5697 }
5698
5699 // End malloc(3)-compatible functions.
5700 // ***************************************************************************
5701 // Begin non-standard functions.
5702
5703 // This was added by Mozilla for use by SQLite.
5704 inline size_t MozJemalloc::malloc_good_size(size_t aSize) {
5705 if (aSize <= gMaxLargeClass) {
5706 // Small or large
5707 aSize = SizeClass(aSize).Size();
5708 } else {
5709 // Huge. We use PAGE_CEILING to get psize, instead of using
5710 // CHUNK_CEILING to get csize. This ensures that this
5711 // malloc_usable_size(malloc(n)) always matches
5712 // malloc_good_size(n).
5713 aSize = PAGE_CEILING(aSize);
5714 }
5715 return aSize;
5716 }
5717
5718 inline size_t MozJemalloc::malloc_usable_size(usable_ptr_t aPtr) {
5719 return AllocInfo::GetValidated(aPtr).Size();
5720 }
5721
5722 inline void MozJemalloc::jemalloc_stats_internal(
5723 jemalloc_stats_t* aStats, jemalloc_bin_stats_t* aBinStats) {
5724 size_t non_arena_mapped, chunk_header_size;
5725
5726 if (!aStats) {
5727 return;
5728 }
5729 if (!malloc_init()) {
5730 memset(aStats, 0, sizeof(*aStats));
5731 return;
5732 }
5733 if (aBinStats) {
5734 memset(aBinStats, 0, sizeof(jemalloc_bin_stats_t) * NUM_SMALL_CLASSES);
5735 }
5736
5737 // Gather runtime settings.
5738 aStats->opt_junk = opt_junk;
5739 aStats->opt_randomize_small = opt_randomize_small;
5740 aStats->opt_zero = opt_zero;
5741 aStats->quantum = kQuantum;
5742 aStats->quantum_max = kMaxQuantumClass;
5743 aStats->quantum_wide = kQuantumWide;
5744 aStats->quantum_wide_max = kMaxQuantumWideClass;
5745 aStats->subpage_max = gMaxSubPageClass;
5746 aStats->large_max = gMaxLargeClass;
5747 aStats->chunksize = kChunkSize;
5748 aStats->page_size = gPageSize;
5749 aStats->dirty_max = opt_dirty_max;
5750
5751 // Gather current memory usage statistics.
5752 aStats->narenas = 0;
5753 aStats->mapped = 0;
5754 aStats->allocated = 0;
5755 aStats->waste = 0;
5756 aStats->pages_dirty = 0;
5757 aStats->pages_fresh = 0;
5758 aStats->pages_madvised = 0;
5759 aStats->bookkeeping = 0;
5760 aStats->bin_unused = 0;
5761
5762 non_arena_mapped = 0;
5763
5764 // Get huge mapped/allocated.
5765 {
5766 MutexAutoLock lock(huge_mtx);
5767 non_arena_mapped += huge_mapped;
5768 aStats->allocated += huge_allocated;
5769 aStats->num_operations += huge_operations;
5770 MOZ_ASSERT(huge_mapped >= huge_allocated);
5771 }
5772
5773 // Get base mapped/allocated.
5774 {
5775 MutexAutoLock lock(base_mtx);
5776 non_arena_mapped += base_mapped;
5777 aStats->bookkeeping += base_committed;
5778 MOZ_ASSERT(base_mapped >= base_committed);
5779 }
5780
5781 gArenas.mLock.Lock();
5782
5783 // Stats can only read complete information if its run on the main thread.
5784 MOZ_ASSERT(gArenas.IsOnMainThreadWeak());
5785
5786 // Iterate over arenas.
5787 for (auto arena : gArenas.iter()) {
5788 // Cannot safely read stats for this arena and therefore stats would be
5789 // incomplete.
5790 MOZ_ASSERT(arena->mLock.SafeOnThisThread());
5791
5792 size_t arena_mapped, arena_allocated, arena_committed, arena_dirty,
5793 arena_fresh, arena_madvised, j, arena_unused, arena_headers;
5794
5795 arena_headers = 0;
5796 arena_unused = 0;
5797
5798 {
5799 MaybeMutexAutoLock lock(arena->mLock);
5800
5801 arena_mapped = arena->mStats.mapped;
5802
5803 // "committed" counts dirty and allocated memory.
5804 arena_committed = arena->mStats.committed << gPageSize2Pow;
5805
5806 arena_allocated =
5807 arena->mStats.allocated_small + arena->mStats.allocated_large;
5808
5809 arena_dirty = arena->mNumDirty << gPageSize2Pow;
5810 arena_fresh = arena->mNumFresh << gPageSize2Pow;
5811 arena_madvised = arena->mNumMAdvised << gPageSize2Pow;
5812
5813 aStats->num_operations += arena->mStats.operations;
5814
5815 for (j = 0; j < NUM_SMALL_CLASSES; j++) {
5816 arena_bin_t* bin = &arena->mBins[j];
5817 size_t bin_unused = 0;
5818 size_t num_non_full_runs = 0;
5819
5820 for (arena_run_t& run : bin->mNonFullRuns) {
5821 MOZ_DIAGNOSTIC_ASSERT(run.mMagic == ARENA_RUN_MAGIC);
5822 MOZ_RELEASE_ASSERT(run.mNumFree > 0 &&
5823 run.mNumFree < bin->mRunNumRegions);
5824 MOZ_RELEASE_ASSERT(run.mBin == bin);
5825 MOZ_RELEASE_ASSERT(bin->mNonFullRuns.ElementIsLinkedWell(&run));
5826 arena_chunk_t* chunk = GetChunkForPtr(&run);
5827 MOZ_RELEASE_ASSERT(chunk->arena == arena);
5828 bin_unused += run.mNumFree * bin->mSizeClass;
5829 num_non_full_runs++;
5830 }
5831
5832 arena_unused += bin_unused;
5833 arena_headers += bin->mNumRuns * bin->mRunFirstRegionOffset;
5834 if (aBinStats) {
5835 aBinStats[j].size = bin->mSizeClass;
5836 aBinStats[j].num_non_full_runs += num_non_full_runs;
5837 aBinStats[j].num_runs += bin->mNumRuns;
5838 aBinStats[j].bytes_unused += bin_unused;
5839 size_t bytes_per_run = static_cast<size_t>(bin->mRunSizePages)
5840 << gPageSize2Pow;
5841 aBinStats[j].bytes_total +=
5842 bin->mNumRuns * (bytes_per_run - bin->mRunFirstRegionOffset);
5843 aBinStats[j].bytes_per_run = bytes_per_run;
5844 aBinStats[j].regions_per_run = bin->mRunNumRegions;
5845 }
5846 }
5847 }
5848
5849 MOZ_ASSERT(arena_mapped >= arena_committed);
5850 MOZ_ASSERT(arena_committed >= arena_allocated + arena_dirty);
5851
5852 aStats->mapped += arena_mapped;
5853 aStats->allocated += arena_allocated;
5854 aStats->pages_dirty += arena_dirty;
5855 aStats->pages_fresh += arena_fresh;
5856 aStats->pages_madvised += arena_madvised;
5857 // "waste" is committed memory that is neither dirty nor
5858 // allocated. If you change this definition please update
5859 // memory/replace/logalloc/replay/Replay.cpp's jemalloc_stats calculation of
5860 // committed.
5861 MOZ_ASSERT(arena_committed >=
5862 (arena_allocated + arena_dirty + arena_unused + arena_headers));
5863 aStats->waste += arena_committed - arena_allocated - arena_dirty -
5864 arena_unused - arena_headers;
5865 aStats->bin_unused += arena_unused;
5866 aStats->bookkeeping += arena_headers;
5867 aStats->narenas++;
5868 }
5869 gArenas.mLock.Unlock();
5870
5871 // Account for arena chunk headers in bookkeeping rather than waste.
5872 chunk_header_size =
5873 ((aStats->mapped / aStats->chunksize) * (gChunkHeaderNumPages - 1))
5874 << gPageSize2Pow;
5875
5876 aStats->mapped += non_arena_mapped;
5877 aStats->bookkeeping += chunk_header_size;
5878 aStats->waste -= chunk_header_size;
5879
5880 MOZ_ASSERT(aStats->mapped >= aStats->allocated + aStats->waste +
5881 aStats->pages_dirty + aStats->bookkeeping);
5882 }
5883
5884 inline void MozJemalloc::jemalloc_stats_lite(jemalloc_stats_lite_t* aStats) {
5885 if (!aStats) {
5886 return;
5887 }
5888 if (!malloc_init()) {
5889 memset(aStats, 0, sizeof(*aStats));
5890 return;
5891 }
5892
5893 aStats->allocated_bytes = 0;
5894 aStats->num_operations = 0;
5895
5896 // Get huge mapped/allocated.
5897 {
5898 MutexAutoLock lock(huge_mtx);
5899 aStats->allocated_bytes += huge_allocated;
5900 aStats->num_operations += huge_operations;
5901 MOZ_ASSERT(huge_mapped >= huge_allocated);
5902 }
5903
5904 {
5905 MutexAutoLock lock(gArenas.mLock);
5906 for (auto arena : gArenas.iter()) {
5907 // We don't need to lock the arena to access these fields.
5908 aStats->allocated_bytes += arena->AllocatedBytes();
5909 aStats->num_operations += arena->Operations();
5910 }
5911 aStats->num_operations += gArenas.OperationsDisposedArenas();
5912 }
5913 }
5914
5915 inline size_t MozJemalloc::jemalloc_stats_num_bins() {
5916 return NUM_SMALL_CLASSES;
5917 }
5918
5919 inline void MozJemalloc::jemalloc_set_main_thread() {
5920 MOZ_ASSERT(malloc_initialized);
5921 gArenas.SetMainThread();
5922 }
5923
5924 #ifdef MALLOC_DOUBLE_PURGE
5925
5926 // Explicitly remove all of this chunk's MADV_FREE'd pages from memory.
5927 static size_t hard_purge_chunk(arena_chunk_t* aChunk) {
5928 size_t total_npages = 0;
5929 // See similar logic in arena_t::Purge().
5930 for (size_t i = gChunkHeaderNumPages; i < gChunkNumPages; i++) {
5931 // Find all adjacent pages with CHUNK_MAP_MADVISED set.
5932 size_t npages;
5933 for (npages = 0; aChunk->map[i + npages].bits & CHUNK_MAP_MADVISED &&
5934 i + npages < gChunkNumPages;
5935 npages++) {
5936 // Turn off the page's CHUNK_MAP_MADVISED bit and turn on its
5937 // CHUNK_MAP_FRESH bit.
5938 MOZ_DIAGNOSTIC_ASSERT(!(aChunk->map[i + npages].bits &
5939 (CHUNK_MAP_FRESH | CHUNK_MAP_DECOMMITTED)));
5940 aChunk->map[i + npages].bits ^= (CHUNK_MAP_MADVISED | CHUNK_MAP_FRESH);
5941 }
5942
5943 // We could use mincore to find out which pages are actually
5944 // present, but it's not clear that's better.
5945 if (npages > 0) {
5946 pages_decommit(((char*)aChunk) + (i << gPageSize2Pow),
5947 npages << gPageSize2Pow);
5948 Unused << pages_commit(((char*)aChunk) + (i << gPageSize2Pow),
5949 npages << gPageSize2Pow);
5950 }
5951 total_npages += npages;
5952 i += npages;
5953 }
5954
5955 return total_npages;
5956 }
5957
5958 // Explicitly remove all of this arena's MADV_FREE'd pages from memory.
5959 void arena_t::HardPurge() {
5960 MaybeMutexAutoLock lock(mLock);
5961
5962 while (!mChunksMAdvised.isEmpty()) {
5963 arena_chunk_t* chunk = mChunksMAdvised.popFront();
5964 size_t npages = hard_purge_chunk(chunk);
5965 mNumMAdvised -= npages;
5966 mNumFresh += npages;
5967 }
5968 }
5969
5970 inline void MozJemalloc::jemalloc_purge_freed_pages() {
5971 if (malloc_initialized) {
5972 MutexAutoLock lock(gArenas.mLock);
5973 MOZ_ASSERT(gArenas.IsOnMainThreadWeak());
5974 for (auto arena : gArenas.iter()) {
5975 arena->HardPurge();
5976 }
5977 }
5978 }
5979
5980 #else // !defined MALLOC_DOUBLE_PURGE
5981
5982 inline void MozJemalloc::jemalloc_purge_freed_pages() {
5983 // Do nothing.
5984 }
5985
5986 #endif // defined MALLOC_DOUBLE_PURGE
5987
5988 inline void MozJemalloc::jemalloc_free_dirty_pages(void) {
5989 if (malloc_initialized) {
5990 gArenas.MayPurgeAll(PurgeUnconditional);
5991 }
5992 }
5993
5994 inline void MozJemalloc::jemalloc_free_excess_dirty_pages(void) {
5995 if (malloc_initialized) {
5996 gArenas.MayPurgeAll(PurgeIfThreshold);
5997 }
5998 }
5999
6000 #ifndef NON_RANDOM_ARENA_IDS
6001 inline arena_t* ArenaCollection::GetByIdInternal(Tree& aTree,
6002 arena_id_t aArenaId) {
6003 // Use AlignedStorage2 to avoid running the arena_t constructor, while
6004 // we only need it as a placeholder for mId.
6005 mozilla::AlignedStorage2<arena_t> key;
6006 key.addr()->mId = aArenaId;
6007 return aTree.Search(key.addr());
6008 }
6009 #endif
6010
6011 inline arena_t* ArenaCollection::GetById(arena_id_t aArenaId, bool aIsPrivate) {
6012 if (!malloc_initialized) {
6013 return nullptr;
6014 }
6015
6016 #ifdef NON_RANDOM_ARENA_IDS
6017 // This function is never called with aIsPrivate = false, let's make sure it
6018 // doesn't silently change while we're making that assumption below because
6019 // we can't resolve non-private arenas this way.
6020 MOZ_RELEASE_ASSERT(aIsPrivate);
6021 // This function is not expected to be called before at least one private
6022 // arena was created.
6023 // coverity[missing_lock]
6024 MOZ_RELEASE_ASSERT(mArenaIdKey);
6025 arena_id_t id = (aArenaId << mArenaIdRotation) |
6026 (aArenaId >> (sizeof(void*) * 8 - mArenaIdRotation));
6027 arena_t* result = reinterpret_cast<arena_t*>(id ^ mArenaIdKey);
6028 #else
6029 Tree* tree = nullptr;
6030 if (aIsPrivate) {
6031 if (ArenaIdIsMainThreadOnly(aArenaId)) {
6032 // The main thread only arenas support lock free access, so it's desirable
6033 // to do GetById without taking mLock either.
6034 //
6035 // Races can occur between writers and writers, or between writers and
6036 // readers. The only writer is the main thread and it will never race
6037 // against itself so we can elude the lock when the main thread is
6038 // reading.
6039 MOZ_ASSERT(IsOnMainThread());
6040 MOZ_PUSH_IGNORE_THREAD_SAFETY
6041 arena_t* result = GetByIdInternal(mMainThreadArenas, aArenaId);
6042 MOZ_POP_THREAD_SAFETY
6043 MOZ_RELEASE_ASSERT(result);
6044 return result;
6045 }
6046 tree = &mPrivateArenas;
6047 } else {
6048 tree = &mArenas;
6049 }
6050
6051 MutexAutoLock lock(mLock);
6052 arena_t* result = GetByIdInternal(*tree, aArenaId);
6053 #endif
6054 MOZ_RELEASE_ASSERT(result);
6055 MOZ_RELEASE_ASSERT(result->mId == aArenaId);
6056 return result;
6057 }
6058
6059 inline arena_id_t MozJemalloc::moz_create_arena_with_params(
6060 arena_params_t* aParams) {
6061 if (malloc_init()) {
6062 arena_t* arena = gArenas.CreateArena(/* IsPrivate = */ true, aParams);
6063 return arena->mId;
6064 }
6065 return 0;
6066 }
6067
6068 inline void MozJemalloc::moz_dispose_arena(arena_id_t aArenaId) {
6069 arena_t* arena = gArenas.GetById(aArenaId, /* IsPrivate = */ true);
6070 MOZ_RELEASE_ASSERT(arena);
6071 gArenas.DisposeArena(arena);
6072 }
6073
6074 inline void MozJemalloc::moz_set_max_dirty_page_modifier(int32_t aModifier) {
6075 if (malloc_init()) {
6076 gArenas.SetDefaultMaxDirtyPageModifier(aModifier);
6077 }
6078 }
6079
6080 inline void MozJemalloc::jemalloc_reset_small_alloc_randomization(
6081 bool aRandomizeSmall) {
6082 // When this process got forked by ForkServer then it inherited the existing
6083 // state of mozjemalloc. Specifically, parsing of MALLOC_OPTIONS has already
6084 // been done but it may not reflect anymore the current set of options after
6085 // the fork().
6086 //
6087 // Similar behavior is also present on Android where it is also required to
6088 // perform this step.
6089 //
6090 // Content process will have randomization on small malloc disabled via the
6091 // MALLOC_OPTIONS environment variable set by parent process, missing this
6092 // will lead to serious performance regressions because CPU prefetch will
6093 // break, cf bug 1912262. However on forkserver-forked Content processes, the
6094 // environment is not yet reset when the postfork child handler is being
6095 // called.
6096 //
6097 // This API is here to allow those Content processes (spawned by ForkServer or
6098 // Android service) to notify jemalloc to turn off the randomization on small
6099 // allocations and perform the required reinitialization of already existing
6100 // arena's PRNG. It is important to make sure that the PRNG state is properly
6101 // re-initialized otherwise child processes would share all the same state.
6102
6103 {
6104 AutoLock<StaticMutex> lock(gInitLock);
6105 opt_randomize_small = aRandomizeSmall;
6106 }
6107
6108 MutexAutoLock lock(gArenas.mLock);
6109 for (auto* arena : gArenas.iter()) {
6110 // We can only initialize the PRNG for main-thread-only arenas from the main
6111 // thread.
6112 if (!arena->IsMainThreadOnly() || gArenas.IsOnMainThreadWeak()) {
6113 arena->ResetSmallAllocRandomization();
6114 }
6115 }
6116 }
6117
6118 inline bool MozJemalloc::moz_enable_deferred_purge(bool aEnabled) {
6119 return gArenas.SetDeferredPurge(aEnabled);
6120 }
6121
6122 inline purge_result_t MozJemalloc::moz_may_purge_now(
6123 bool aPeekOnly, uint32_t aReuseGraceMS,
6124 const Maybe<std::function<bool()>>& aKeepGoing) {
6125 return gArenas.MayPurgeSteps(aPeekOnly, aReuseGraceMS, aKeepGoing);
6126 }
6127
6128 inline void ArenaCollection::AddToOutstandingPurges(arena_t* aArena) {
6129 MOZ_ASSERT(aArena);
6130
6131 // We cannot trust the caller to know whether the element was already added
6132 // from another thread given we have our own lock.
6133 MutexAutoLock lock(mPurgeListLock);
6134 if (!mOutstandingPurges.ElementProbablyInList(aArena)) {
6135 mOutstandingPurges.pushBack(aArena);
6136 }
6137 }
6138
6139 inline bool ArenaCollection::RemoveFromOutstandingPurges(arena_t* aArena) {
6140 MOZ_ASSERT(aArena);
6141
6142 // We cannot trust the caller to know whether the element was already removed
6143 // from another thread given we have our own lock.
6144 MutexAutoLock lock(mPurgeListLock);
6145 if (mOutstandingPurges.ElementProbablyInList(aArena)) {
6146 mOutstandingPurges.remove(aArena);
6147 return true;
6148 }
6149 return false;
6150 }
6151
6152 purge_result_t ArenaCollection::MayPurgeSteps(
6153 bool aPeekOnly, uint32_t aReuseGraceMS,
6154 const Maybe<std::function<bool()>>& aKeepGoing) {
6155 // This only works on the main thread because it may process main-thread-only
6156 // arenas.
6157 MOZ_ASSERT(IsOnMainThreadWeak());
6158
6159 uint64_t now = GetTimestampNS();
6160 uint64_t reuseGraceNS = (uint64_t)aReuseGraceMS * 1000 * 1000;
6161 arena_t* found = nullptr;
6162 {
6163 MutexAutoLock lock(mPurgeListLock);
6164 if (mOutstandingPurges.isEmpty()) {
6165 return purge_result_t::Done;
6166 }
6167 for (arena_t& arena : mOutstandingPurges) {
6168 if (now - arena.mLastSignificantReuseNS >= reuseGraceNS) {
6169 found = &arena;
6170 break;
6171 }
6172 }
6173
6174 if (!found) {
6175 return purge_result_t::WantsLater;
6176 }
6177 if (aPeekOnly) {
6178 return purge_result_t::NeedsMore;
6179 }
6180
6181 // We need to avoid the invalid state where mIsDeferredPurgePending is set
6182 // but the arena is not in the list or about to be added. So remove the
6183 // arena from the list before calling Purge().
6184 mOutstandingPurges.remove(found);
6185 }
6186
6187 arena_t::PurgeResult pr;
6188 do {
6189 pr = found->Purge(PurgeIfThreshold);
6190 now = GetTimestampNS();
6191 } while (pr == arena_t::PurgeResult::Continue &&
6192 (now - found->mLastSignificantReuseNS >= reuseGraceNS) &&
6193 aKeepGoing && (*aKeepGoing)());
6194
6195 if (pr == arena_t::PurgeResult::Continue) {
6196 // If there's more work to do we re-insert the arena into the purge queue.
6197 // If the arena was busy we don't since the other thread that's purging it
6198 // will finish that work.
6199
6200 // Note that after the above Purge() and taking the lock below there's a
6201 // chance another thread may be purging the arena and clear
6202 // mIsDeferredPurgePending. Resulting in the state of being in the list
6203 // with that flag clear. That's okay since the next time a purge occurs
6204 // (and one will because it's in the list) it'll clear the flag and the
6205 // state will be consistent again.
6206 MutexAutoLock lock(mPurgeListLock);
6207 if (!mOutstandingPurges.ElementProbablyInList(found)) {
6208 // Given we want to continue to purge this arena, push it to the front
6209 // to increase the probability to find it fast.
6210 mOutstandingPurges.pushFront(found);
6211 }
6212 } else if (pr == arena_t::PurgeResult::Dying) {
6213 delete found;
6214 }
6215
6216 // Even if there is no other arena that needs work, let the caller just call
6217 // us again and we will do the above checks then and return their result.
6218 // Note that in the current surrounding setting this may (rarely) cause a
6219 // new slice of our idle task runner if we are exceeding idle budget.
6220 return purge_result_t::NeedsMore;
6221 }
6222
6223 void ArenaCollection::MayPurgeAll(PurgeCondition aCond) {
6224 MutexAutoLock lock(mLock);
6225 for (auto* arena : iter()) {
6226 // Arenas that are not IsMainThreadOnly can be purged from any thread.
6227 // So we do what we can even if called from another thread.
6228 if (!arena->IsMainThreadOnly() || IsOnMainThreadWeak()) {
6229 RemoveFromOutstandingPurges(arena);
6230 arena_t::PurgeResult pr;
6231 do {
6232 pr = arena->Purge(aCond);
6233 } while (pr == arena_t::PurgeResult::Continue);
6234
6235 // No arena can die here because we're holding the arena collection lock.
6236 // Arenas are removed from the collection before setting their mDying
6237 // flag.
6238 MOZ_RELEASE_ASSERT(pr != arena_t::PurgeResult::Dying);
6239 }
6240 }
6241 }
6242
6243 #define MALLOC_DECL(name, return_type, ...) \
6244 inline return_type MozJemalloc::moz_arena_##name( \
6245 arena_id_t aArenaId, ARGS_HELPER(TYPED_ARGS, ##__VA_ARGS__)) { \
6246 BaseAllocator allocator( \
6247 gArenas.GetById(aArenaId, /* IsPrivate = */ true)); \
6248 return allocator.name(ARGS_HELPER(ARGS, ##__VA_ARGS__)); \
6249 }
6250 #define MALLOC_FUNCS MALLOC_FUNCS_MALLOC_BASE
6251 #include "malloc_decls.h"
6252
6253 // End non-standard functions.
6254 // ***************************************************************************
6255 #ifndef XP_WIN
6256 // Begin library-private functions, used by threading libraries for protection
6257 // of malloc during fork(). These functions are only called if the program is
6258 // running in threaded mode, so there is no need to check whether the program
6259 // is threaded here.
6260 //
6261 // Note that the only way to keep the main-thread-only arenas in a consistent
6262 // state for the child is if fork is called from the main thread only. Or the
6263 // child must not use them, eg it should call exec(). We attempt to prevent the
6264 // child for accessing these arenas by refusing to re-initialise them.
6265 //
6266 // This is only accessed in the fork handlers while gArenas.mLock is held.
6267 static pthread_t gForkingThread;
6268
6269 # ifdef XP_DARWIN
6270 // This is only accessed in the fork handlers while gArenas.mLock is held.
6271 static pid_t gForkingProcess;
6272 # endif
6273
6274 FORK_HOOK
6275 void _malloc_prefork(void) MOZ_NO_THREAD_SAFETY_ANALYSIS {
6276 // Acquire all mutexes in a safe order.
6277 gArenas.mLock.Lock();
6278 gForkingThread = pthread_self();
6279 # ifdef XP_DARWIN
6280 gForkingProcess = getpid();
6281 # endif
6282
6283 for (auto arena : gArenas.iter()) {
6284 if (arena->mLock.LockIsEnabled()) {
6285 arena->mLock.Lock();
6286 }
6287 }
6288
6289 gArenas.mPurgeListLock.Lock();
6290
6291 base_mtx.Lock();
6292
6293 huge_mtx.Lock();
6294 }
6295
6296 FORK_HOOK
6297 void _malloc_postfork_parent(void) MOZ_NO_THREAD_SAFETY_ANALYSIS {
6298 // Release all mutexes, now that fork() has completed.
6299 huge_mtx.Unlock();
6300
6301 base_mtx.Unlock();
6302
6303 gArenas.mPurgeListLock.Unlock();
6304
6305 for (auto arena : gArenas.iter()) {
6306 if (arena->mLock.LockIsEnabled()) {
6307 arena->mLock.Unlock();
6308 }
6309 }
6310
6311 gArenas.mLock.Unlock();
6312 }
6313
6314 FORK_HOOK
6315 void _malloc_postfork_child(void) {
6316 // Do this before iterating over the arenas.
6317 gArenas.ResetMainThread();
6318
6319 // Reinitialize all mutexes, now that fork() has completed.
6320 huge_mtx.Init();
6321
6322 base_mtx.Init();
6323
6324 gArenas.mPurgeListLock.Init();
6325
6326 MOZ_PUSH_IGNORE_THREAD_SAFETY
6327 for (auto arena : gArenas.iter()) {
6328 arena->mLock.Reinit(gForkingThread);
6329 }
6330 MOZ_POP_THREAD_SAFETY
6331
6332 gArenas.mLock.Init();
6333 }
6334
6335 # ifdef XP_DARWIN
6336 FORK_HOOK
6337 void _malloc_postfork(void) {
6338 // On MacOS we need to check if this is running in the parent or child
6339 // process.
6340 bool is_in_parent = getpid() == gForkingProcess;
6341 gForkingProcess = 0;
6342 if (is_in_parent) {
6343 _malloc_postfork_parent();
6344 } else {
6345 _malloc_postfork_child();
6346 }
6347 }
6348 # endif // XP_DARWIN
6349 #endif // ! XP_WIN
6350
6351 // End library-private functions.
6352 // ***************************************************************************
6353 #ifdef MOZ_REPLACE_MALLOC
6354 // Windows doesn't come with weak imports as they are possible with
6355 // LD_PRELOAD or DYLD_INSERT_LIBRARIES on Linux/OSX. On this platform,
6356 // the replacement functions are defined as variable pointers to the
6357 // function resolved with GetProcAddress() instead of weak definitions
6358 // of functions. On Android, the same needs to happen as well, because
6359 // the Android linker doesn't handle weak linking with non LD_PRELOADed
6360 // libraries, but LD_PRELOADing is not very convenient on Android, with
6361 // the zygote.
6362 # ifdef XP_DARWIN
6363 # define MOZ_REPLACE_WEAK __attribute__((weak_import))
6364 # elif defined(XP_WIN) || defined(ANDROID)
6365 # define MOZ_DYNAMIC_REPLACE_INIT
6366 # define replace_init replace_init_decl
6367 # elif defined(__GNUC__)
6368 # define MOZ_REPLACE_WEAK __attribute__((weak))
6369 # endif
6370
6371 # include "replace_malloc.h"
6372
6373 # define MALLOC_DECL(name, return_type, ...) CanonicalMalloc::name,
6374
6375 // The default malloc table, i.e. plain allocations. It never changes. It's
6376 // used by init(), and not used after that.
6377 static const malloc_table_t gDefaultMallocTable = {
6378 # include "malloc_decls.h"
6379 };
6380
6381 // The malloc table installed by init(). It never changes from that point
6382 // onward. It will be the same as gDefaultMallocTable if no replace-malloc tool
6383 // is enabled at startup.
6384 static malloc_table_t gOriginalMallocTable = {
6385 # include "malloc_decls.h"
6386 };
6387
6388 // The malloc table installed by jemalloc_replace_dynamic(). (Read the
6389 // comments above that function for more details.)
6390 static malloc_table_t gDynamicMallocTable = {
6391 # include "malloc_decls.h"
6392 };
6393
6394 // This briefly points to gDefaultMallocTable at startup. After that, it points
6395 // to either gOriginalMallocTable or gDynamicMallocTable. It's atomic to avoid
6396 // races when switching between tables.
6397 static Atomic<malloc_table_t const*, mozilla::MemoryOrdering::Relaxed>
6398 gMallocTablePtr;
6399
6400 # ifdef MOZ_DYNAMIC_REPLACE_INIT
6401 # undef replace_init
6402 typedef decltype(replace_init_decl) replace_init_impl_t;
6403 static replace_init_impl_t* replace_init = nullptr;
6404 # endif
6405
6406 # ifdef XP_WIN
6407 typedef HMODULE replace_malloc_handle_t;
6408
6409 static replace_malloc_handle_t replace_malloc_handle() {
6410 wchar_t replace_malloc_lib[1024];
6411 if (GetEnvironmentVariableW(L"MOZ_REPLACE_MALLOC_LIB", replace_malloc_lib,
6412 std::size(replace_malloc_lib)) > 0) {
6413 return LoadLibraryW(replace_malloc_lib);
6414 }
6415 return nullptr;
6416 }
6417
6418 # define REPLACE_MALLOC_GET_INIT_FUNC(handle) \
6419 (replace_init_impl_t*)GetProcAddress(handle, "replace_init")
6420
6421 # elif defined(ANDROID)
6422 # include <dlfcn.h>
6423
6424 typedef void* replace_malloc_handle_t;
6425
6426 static replace_malloc_handle_t replace_malloc_handle() {
6427 const char* replace_malloc_lib = getenv("MOZ_REPLACE_MALLOC_LIB");
6428 if (replace_malloc_lib && *replace_malloc_lib) {
6429 return dlopen(replace_malloc_lib, RTLD_LAZY);
6430 }
6431 return nullptr;
6432 }
6433
6434 # define REPLACE_MALLOC_GET_INIT_FUNC(handle) \
6435 (replace_init_impl_t*)dlsym(handle, "replace_init")
6436
6437 # endif
6438
6439 static void replace_malloc_init_funcs(malloc_table_t*);
6440
6441 # ifdef MOZ_REPLACE_MALLOC_STATIC
6442 extern "C" void logalloc_init(malloc_table_t*, ReplaceMallocBridge**);
6443
6444 extern "C" void dmd_init(malloc_table_t*, ReplaceMallocBridge**);
6445 # endif
6446
6447 void phc_init(malloc_table_t*, ReplaceMallocBridge**);
6448
6449 bool Equals(const malloc_table_t& aTable1, const malloc_table_t& aTable2) {
6450 return memcmp(&aTable1, &aTable2, sizeof(malloc_table_t)) == 0;
6451 }
6452
6453 // Below is the malloc implementation overriding jemalloc and calling the
6454 // replacement functions if they exist.
6455 static ReplaceMallocBridge* gReplaceMallocBridge = nullptr;
6456 static void init() {
6457 malloc_table_t tempTable = gDefaultMallocTable;
6458
6459 # ifdef MOZ_DYNAMIC_REPLACE_INIT
6460 replace_malloc_handle_t handle = replace_malloc_handle();
6461 if (handle) {
6462 replace_init = REPLACE_MALLOC_GET_INIT_FUNC(handle);
6463 }
6464 # endif
6465
6466 // Set this *before* calling replace_init, otherwise if replace_init calls
6467 // malloc() we'll get an infinite loop.
6468 gMallocTablePtr = &gDefaultMallocTable;
6469
6470 // Pass in the default allocator table so replace functions can copy and use
6471 // it for their allocations. The replace_init() function should modify the
6472 // table if it wants to be active, otherwise leave it unmodified.
6473 if (replace_init) {
6474 replace_init(&tempTable, &gReplaceMallocBridge);
6475 }
6476 # ifdef MOZ_REPLACE_MALLOC_STATIC
6477 if (Equals(tempTable, gDefaultMallocTable)) {
6478 logalloc_init(&tempTable, &gReplaceMallocBridge);
6479 }
6480 # ifdef MOZ_DMD
6481 if (Equals(tempTable, gDefaultMallocTable)) {
6482 dmd_init(&tempTable, &gReplaceMallocBridge);
6483 }
6484 # endif
6485 # endif
6486 if (!Equals(tempTable, gDefaultMallocTable)) {
6487 replace_malloc_init_funcs(&tempTable);
6488 }
6489 gOriginalMallocTable = tempTable;
6490 gMallocTablePtr = &gOriginalMallocTable;
6491 }
6492
6493 // WARNING WARNING WARNING: this function should be used with extreme care. It
6494 // is not as general-purpose as it looks. It is currently used by
6495 // tools/profiler/core/memory_hooks.cpp for counting allocations and probably
6496 // should not be used for any other purpose.
6497 //
6498 // This function allows the original malloc table to be temporarily replaced by
6499 // a different malloc table. Or, if the argument is nullptr, it switches back to
6500 // the original malloc table.
6501 //
6502 // Limitations:
6503 //
6504 // - It is not threadsafe. If multiple threads pass it the same
6505 // `replace_init_func` at the same time, there will be data races writing to
6506 // the malloc_table_t within that function.
6507 //
6508 // - Only one replacement can be installed. No nesting is allowed.
6509 //
6510 // - The new malloc table must be able to free allocations made by the original
6511 // malloc table, and upon removal the original malloc table must be able to
6512 // free allocations made by the new malloc table. This means the new malloc
6513 // table can only do simple things like recording extra information, while
6514 // delegating actual allocation/free operations to the original malloc table.
6515 //
6516 MOZ_JEMALLOC_API void jemalloc_replace_dynamic(
6517 jemalloc_init_func replace_init_func) {
6518 if (replace_init_func) {
6519 malloc_table_t tempTable = gOriginalMallocTable;
6520 (*replace_init_func)(&tempTable, &gReplaceMallocBridge);
6521 if (!Equals(tempTable, gOriginalMallocTable)) {
6522 replace_malloc_init_funcs(&tempTable);
6523
6524 // Temporarily switch back to the original malloc table. In the
6525 // (supported) non-nested case, this is a no-op. But just in case this is
6526 // a (unsupported) nested call, it makes the overwriting of
6527 // gDynamicMallocTable less racy, because ongoing calls to malloc() and
6528 // friends won't go through gDynamicMallocTable.
6529 gMallocTablePtr = &gOriginalMallocTable;
6530
6531 gDynamicMallocTable = tempTable;
6532 gMallocTablePtr = &gDynamicMallocTable;
6533 // We assume that dynamic replaces don't occur close enough for a
6534 // thread to still have old copies of the table pointer when the 2nd
6535 // replace occurs.
6536 }
6537 } else {
6538 // Switch back to the original malloc table.
6539 gMallocTablePtr = &gOriginalMallocTable;
6540 }
6541 }
6542
6543 # define MALLOC_DECL(name, return_type, ...) \
6544 inline return_type ReplaceMalloc::name( \
6545 ARGS_HELPER(TYPED_ARGS, ##__VA_ARGS__)) { \
6546 if (MOZ_UNLIKELY(!gMallocTablePtr)) { \
6547 init(); \
6548 } \
6549 return (*gMallocTablePtr).name(ARGS_HELPER(ARGS, ##__VA_ARGS__)); \
6550 }
6551 # include "malloc_decls.h"
6552
6553 MOZ_JEMALLOC_API struct ReplaceMallocBridge* get_bridge(void) {
6554 if (MOZ_UNLIKELY(!gMallocTablePtr)) {
6555 init();
6556 }
6557 return gReplaceMallocBridge;
6558 }
6559
6560 // posix_memalign, aligned_alloc, memalign and valloc all implement some kind
6561 // of aligned memory allocation. For convenience, a replace-malloc library can
6562 // skip defining replace_posix_memalign, replace_aligned_alloc and
6563 // replace_valloc, and default implementations will be automatically derived
6564 // from replace_memalign.
6565 static void replace_malloc_init_funcs(malloc_table_t* table) {
6566 if (table->posix_memalign == CanonicalMalloc::posix_memalign &&
6567 table->memalign != CanonicalMalloc::memalign) {
6568 table->posix_memalign =
6569 AlignedAllocator<ReplaceMalloc::memalign>::posix_memalign;
6570 }
6571 if (table->aligned_alloc == CanonicalMalloc::aligned_alloc &&
6572 table->memalign != CanonicalMalloc::memalign) {
6573 table->aligned_alloc =
6574 AlignedAllocator<ReplaceMalloc::memalign>::aligned_alloc;
6575 }
6576 if (table->valloc == CanonicalMalloc::valloc &&
6577 table->memalign != CanonicalMalloc::memalign) {
6578 table->valloc = AlignedAllocator<ReplaceMalloc::memalign>::valloc;
6579 }
6580 if (table->moz_create_arena_with_params ==
6581 CanonicalMalloc::moz_create_arena_with_params &&
6582 table->malloc != CanonicalMalloc::malloc) {
6583 # define MALLOC_DECL(name, ...) \
6584 table->name = DummyArenaAllocator<ReplaceMalloc>::name;
6585 # define MALLOC_FUNCS MALLOC_FUNCS_ARENA_BASE
6586 # include "malloc_decls.h"
6587 }
6588 if (table->moz_arena_malloc == CanonicalMalloc::moz_arena_malloc &&
6589 table->malloc != CanonicalMalloc::malloc) {
6590 # define MALLOC_DECL(name, ...) \
6591 table->name = DummyArenaAllocator<ReplaceMalloc>::name;
6592 # define MALLOC_FUNCS MALLOC_FUNCS_ARENA_ALLOC
6593 # include "malloc_decls.h"
6594 }
6595 }
6596
6597 #endif // MOZ_REPLACE_MALLOC
6598 // ***************************************************************************
6599 // Definition of all the _impl functions
6600 // GENERIC_MALLOC_DECL2_MINGW is only used for the MinGW build, and aliases
6601 // the malloc funcs (e.g. malloc) to the je_ versions. It does not generate
6602 // aliases for the other functions (jemalloc and arena functions).
6603 //
6604 // We do need aliases for the other mozglue.def-redirected functions though,
6605 // these are done at the bottom of mozmemory_wrap.cpp
6606 #define GENERIC_MALLOC_DECL2_MINGW(name, name_impl, return_type, ...) \
6607 return_type name(ARGS_HELPER(TYPED_ARGS, ##__VA_ARGS__)) \
6608 __attribute__((alias(MOZ_STRINGIFY(name_impl))));
6609
6610 #define GENERIC_MALLOC_DECL2(attributes, name, name_impl, return_type, ...) \
6611 return_type name_impl(ARGS_HELPER(TYPED_ARGS, ##__VA_ARGS__)) attributes { \
6612 return DefaultMalloc::name(ARGS_HELPER(ARGS, ##__VA_ARGS__)); \
6613 }
6614
6615 #ifndef __MINGW32__
6616 # define GENERIC_MALLOC_DECL(attributes, name, return_type, ...) \
6617 GENERIC_MALLOC_DECL2(attributes, name, name##_impl, return_type, \
6618 ##__VA_ARGS__)
6619 #else
6620 # define GENERIC_MALLOC_DECL(attributes, name, return_type, ...) \
6621 GENERIC_MALLOC_DECL2(attributes, name, name##_impl, return_type, \
6622 ##__VA_ARGS__) \
6623 GENERIC_MALLOC_DECL2_MINGW(name, name##_impl, return_type, ##__VA_ARGS__)
6624 #endif
6625
6626 #define NOTHROW_MALLOC_DECL(...) \
6627 MOZ_MEMORY_API MACRO_CALL(GENERIC_MALLOC_DECL, (noexcept(true), __VA_ARGS__))
6628 #define MALLOC_DECL(...) \
6629 MOZ_MEMORY_API MACRO_CALL(GENERIC_MALLOC_DECL, (, __VA_ARGS__))
6630 #define MALLOC_FUNCS MALLOC_FUNCS_MALLOC
6631 #include "malloc_decls.h"
6632
6633 #undef GENERIC_MALLOC_DECL
6634 #define GENERIC_MALLOC_DECL(attributes, name, return_type, ...) \
6635 GENERIC_MALLOC_DECL2(attributes, name, name, return_type, ##__VA_ARGS__)
6636
6637 #define MALLOC_DECL(...) \
6638 MOZ_JEMALLOC_API MACRO_CALL(GENERIC_MALLOC_DECL, (, __VA_ARGS__))
6639 #define MALLOC_FUNCS (MALLOC_FUNCS_JEMALLOC | MALLOC_FUNCS_ARENA)
6640 #include "malloc_decls.h"
6641 // ***************************************************************************
6642
6643 #ifdef HAVE_DLFCN_H
6644 # include <dlfcn.h>
6645 #endif
6646
6647 #if defined(__GLIBC__) && !defined(__UCLIBC__)
6648 // glibc provides the RTLD_DEEPBIND flag for dlopen which can make it possible
6649 // to inconsistently reference libc's malloc(3)-compatible functions
6650 // (bug 493541).
6651 //
6652 // These definitions interpose hooks in glibc. The functions are actually
6653 // passed an extra argument for the caller return address, which will be
6654 // ignored.
6655
6656 extern "C" {
6657 MOZ_EXPORT void (*__free_hook)(void*) = free_impl;
6658 MOZ_EXPORT void* (*__malloc_hook)(size_t) = malloc_impl;
6659 MOZ_EXPORT void* (*__realloc_hook)(void*, size_t) = realloc_impl;
6660 MOZ_EXPORT void* (*__memalign_hook)(size_t, size_t) = memalign_impl;
6661 }
6662
6663 #elif defined(RTLD_DEEPBIND)
6664 // XXX On systems that support RTLD_GROUP or DF_1_GROUP, do their
6665 // implementations permit similar inconsistencies? Should STV_SINGLETON
6666 // visibility be used for interposition where available?
6667 # error \
6668 "Interposing malloc is unsafe on this system without libc malloc hooks."
6669 #endif
6670
6671 #ifdef XP_WIN
6672 MOZ_EXPORT void* _recalloc(void* aPtr, size_t aCount, size_t aSize) {
6673 size_t oldsize = aPtr ? AllocInfo::Get(aPtr).Size() : 0;
6674 CheckedInt<size_t> checkedSize = CheckedInt<size_t>(aCount) * aSize;
6675
6676 if (!checkedSize.isValid()) {
6677 return nullptr;
6678 }
6679
6680 size_t newsize = checkedSize.value();
6681
6682 // In order for all trailing bytes to be zeroed, the caller needs to
6683 // use calloc(), followed by recalloc(). However, the current calloc()
6684 // implementation only zeros the bytes requested, so if recalloc() is
6685 // to work 100% correctly, calloc() will need to change to zero
6686 // trailing bytes.
6687 aPtr = DefaultMalloc::realloc(aPtr, newsize);
6688 if (aPtr && oldsize < newsize) {
6689 memset((void*)((uintptr_t)aPtr + oldsize), 0, newsize - oldsize);
6690 }
6691
6692 return aPtr;
6693 }
6694
6695 // This impl of _expand doesn't ever actually expand or shrink blocks: it
6696 // simply replies that you may continue using a shrunk block.
6697 MOZ_EXPORT void* _expand(void* aPtr, size_t newsize) {
6698 if (AllocInfo::Get(aPtr).Size() >= newsize) {
6699 return aPtr;
6700 }
6701
6702 return nullptr;
6703 }
6704
6705 MOZ_EXPORT size_t _msize(void* aPtr) {
6706 return DefaultMalloc::malloc_usable_size(aPtr);
6707 }
6708 #endif
6709
6710 #ifdef MOZ_PHC
6711 // Compile PHC and mozjemalloc together so that PHC can inline mozjemalloc.
6712 # include "PHC.cpp"
6713 #endif