Source code
Revision control
Copy as Markdown
Other Tools
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=8 sts=2 et sw=2 tw=80: */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
// Portions of this file were originally under the following license:
//
// Copyright (C) 2006-2008 Jason Evans <jasone@FreeBSD.org>.
// All rights reserved.
// Copyright (C) 2007-2017 Mozilla Foundation.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// 1. Redistributions of source code must retain the above copyright
// notice(s), this list of conditions and the following disclaimer as
// the first lines of this file unmodified other than the possible
// addition of one or more copyright notices.
// 2. Redistributions in binary form must reproduce the above copyright
// notice(s), this list of conditions and the following disclaimer in
// the documentation and/or other materials provided with the
// distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER(S) ``AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER(S) BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
// BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
// OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
// EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// *****************************************************************************
//
// This allocator implementation is designed to provide scalable performance
// for multi-threaded programs on multi-processor systems. The following
// features are included for this purpose:
//
// + Multiple arenas are used if there are multiple CPUs, which reduces lock
// contention and cache sloshing.
//
// + Cache line sharing between arenas is avoided for internal data
// structures.
//
// + Memory is managed in chunks and runs (chunks can be split into runs),
// rather than as individual pages. This provides a constant-time
// mechanism for associating allocations with particular arenas.
//
// Allocation requests are rounded up to the nearest size class, and no record
// of the original request size is maintained. Allocations are broken into
// categories according to size class. Assuming runtime defaults, the size
// classes in each category are as follows (for x86, x86_64 and Apple Silicon):
//
// |=========================================================|
// | Category | Subcategory | x86 | x86_64 | Mac ARM |
// |---------------------------+---------+---------+---------|
// | Word size | 32 bit | 64 bit | 64 bit |
// | Page size | 4 Kb | 4 Kb | 16 Kb |
// |=========================================================|
// | Small | Tiny | 4/-w | -w | - |
// | | | 8 | 8/-w | 8 |
// | |----------------+---------|---------|---------|
// | | Quantum-spaced | 16 | 16 | 16 |
// | | | 32 | 32 | 32 |
// | | | 48 | 48 | 48 |
// | | | ... | ... | ... |
// | | | 480 | 480 | 480 |
// | | | 496 | 496 | 496 |
// | |----------------+---------|---------|---------|
// | | Quantum-wide- | 512 | 512 | 512 |
// | | spaced | 768 | 768 | 768 |
// | | | ... | ... | ... |
// | | | 3584 | 3584 | 3584 |
// | | | 3840 | 3840 | 3840 |
// | |----------------+---------|---------|---------|
// | | Sub-page | - | - | 4096 |
// | | | - | - | 8 kB |
// |=========================================================|
// | Large | 4 kB | 4 kB | - |
// | | 8 kB | 8 kB | - |
// | | 12 kB | 12 kB | - |
// | | 16 kB | 16 kB | 16 kB |
// | | ... | ... | - |
// | | 32 kB | 32 kB | 32 kB |
// | | ... | ... | ... |
// | | 1008 kB | 1008 kB | 1008 kB |
// | | 1012 kB | 1012 kB | - |
// | | 1016 kB | 1016 kB | - |
// | | 1020 kB | 1020 kB | - |
// |=========================================================|
// | Huge | 1 MB | 1 MB | 1 MB |
// | | 2 MB | 2 MB | 2 MB |
// | | 3 MB | 3 MB | 3 MB |
// | | ... | ... | ... |
// |=========================================================|
//
// Legend:
// n: Size class exists for this platform.
// n/-w: This size class doesn't exist on Windows (see kMinTinyClass).
// -: This size class doesn't exist for this platform.
// ...: Size classes follow a pattern here.
//
// allocation on Linux or Mac. So on 32-bit *nix, the smallest bucket size is
// 4 bytes, and on 64-bit, the smallest bucket size is 8 bytes.
//
// A different mechanism is used for each category:
//
// Small : Each size class is segregated into its own set of runs. Each run
// maintains a bitmap of which regions are free/allocated.
//
// Large : Each allocation is backed by a dedicated run. Metadata are stored
// in the associated arena chunk header maps.
//
// Huge : Each allocation is backed by a dedicated contiguous set of chunks.
// Metadata are stored in a separate red-black tree.
//
// *****************************************************************************
#include "mozmemory_wrap.h"
#include "mozjemalloc.h"
#include "mozjemalloc_types.h"
#include <cstring>
#include <cerrno>
#include <optional>
#include <type_traits>
#ifdef XP_WIN
# include <io.h>
# include <windows.h>
#else
# include <sys/mman.h>
# include <unistd.h>
#endif
#ifdef XP_DARWIN
# include <libkern/OSAtomic.h>
# include <mach/mach_init.h>
# include <mach/vm_map.h>
#endif
#include "mozilla/Atomics.h"
#include "mozilla/Alignment.h"
#include "mozilla/ArrayUtils.h"
#include "mozilla/Assertions.h"
#include "mozilla/CheckedInt.h"
#include "mozilla/DoublyLinkedList.h"
#include "mozilla/HelperMacros.h"
#include "mozilla/Likely.h"
#include "mozilla/MathAlgorithms.h"
#include "mozilla/RandomNum.h"
// Note: MozTaggedAnonymousMmap() could call an LD_PRELOADed mmap
// instead of the one defined here; use only MozTagAnonymousMemory().
#include "mozilla/TaggedAnonymousMemory.h"
#include "mozilla/ThreadLocal.h"
#include "mozilla/UniquePtr.h"
#include "mozilla/Unused.h"
#include "mozilla/XorShift128PlusRNG.h"
#include "mozilla/fallible.h"
#include "rb.h"
#include "Mutex.h"
#include "PHC.h"
#include "Utils.h"
#if defined(XP_WIN)
# include "mozmemory_utils.h"
#endif
// For GetGeckoProcessType(), when it's used.
#if defined(XP_WIN) && !defined(JS_STANDALONE)
# include "mozilla/ProcessType.h"
#endif
using namespace mozilla;
// On Linux, we use madvise(MADV_DONTNEED) to release memory back to the
// operating system. If we release 1MB of live pages with MADV_DONTNEED, our
// RSS will decrease by 1MB (almost) immediately.
//
// On Mac, we use madvise(MADV_FREE). Unlike MADV_DONTNEED on Linux, MADV_FREE
// on Mac doesn't cause the OS to release the specified pages immediately; the
// OS keeps them in our process until the machine comes under memory pressure.
//
// It's therefore difficult to measure the process's RSS on Mac, since, in the
// absence of memory pressure, the contribution from the heap to RSS will not
// decrease due to our madvise calls.
//
// We therefore define MALLOC_DOUBLE_PURGE on Mac. This causes jemalloc to
// track which pages have been MADV_FREE'd. You can then call
// jemalloc_purge_freed_pages(), which will force the OS to release those
// MADV_FREE'd pages, making the process's RSS reflect its true memory usage.
//
// The jemalloc_purge_freed_pages definition in memory/build/mozmemory.h needs
// to be adjusted if MALLOC_DOUBLE_PURGE is ever enabled on Linux.
#ifdef XP_DARWIN
# define MALLOC_DOUBLE_PURGE
#endif
#ifdef XP_WIN
# define MALLOC_DECOMMIT
#endif
// Define MALLOC_RUNTIME_CONFIG depending on MOZ_DEBUG. Overriding this as
// a build option allows us to build mozjemalloc/firefox without runtime asserts
// but with runtime configuration. Making some testing easier.
#ifdef MOZ_DEBUG
# define MALLOC_RUNTIME_CONFIG
#endif
// When MALLOC_STATIC_PAGESIZE is defined, the page size is fixed at
// compile-time for better performance, as opposed to determined at
// runtime. Some platforms can have different page sizes at runtime
// depending on kernel configuration, so they are opted out by default.
// Debug builds are opted out too, for test coverage.
#ifndef MALLOC_RUNTIME_CONFIG
# if !defined(__ia64__) && !defined(__sparc__) && !defined(__mips__) && \
!defined(__aarch64__) && !defined(__powerpc__) && !defined(XP_MACOSX) && \
!defined(__loongarch__)
# define MALLOC_STATIC_PAGESIZE 1
# endif
#endif
#ifdef XP_WIN
# define STDERR_FILENO 2
// Implement getenv without using malloc.
static char mozillaMallocOptionsBuf[64];
# define getenv xgetenv
static char* getenv(const char* name) {
if (GetEnvironmentVariableA(name, mozillaMallocOptionsBuf,
sizeof(mozillaMallocOptionsBuf)) > 0) {
return mozillaMallocOptionsBuf;
}
return nullptr;
}
#endif
#ifndef XP_WIN
// Newer Linux systems support MADV_FREE, but we're not supporting
// that properly. bug #1406304.
# if defined(XP_LINUX) && defined(MADV_FREE)
# undef MADV_FREE
# endif
# ifndef MADV_FREE
# define MADV_FREE MADV_DONTNEED
# endif
#endif
// Some tools, such as /dev/dsp wrappers, LD_PRELOAD libraries that
// happen to override mmap() and call dlsym() from their overridden
// mmap(). The problem is that dlsym() calls malloc(), and this ends
// up in a dead lock in jemalloc.
// On these systems, we prefer to directly use the system call.
// We do that for Linux systems and kfreebsd with GNU userland.
// Note sanity checks are not done (alignment of offset, ...) because
// the uses of mmap are pretty limited, in jemalloc.
//
// On Alpha, glibc has a bug that prevents syscall() to work for system
// calls with 6 arguments.
#if (defined(XP_LINUX) && !defined(__alpha__)) || \
(defined(__FreeBSD_kernel__) && defined(__GLIBC__))
# include <sys/syscall.h>
# if defined(SYS_mmap) || defined(SYS_mmap2)
static inline void* _mmap(void* addr, size_t length, int prot, int flags,
int fd, off_t offset) {
// S390 only passes one argument to the mmap system call, which is a
// pointer to a structure containing the arguments.
# ifdef __s390__
struct {
void* addr;
size_t length;
long prot;
long flags;
long fd;
off_t offset;
} args = {addr, length, prot, flags, fd, offset};
return (void*)syscall(SYS_mmap, &args);
# else
# if defined(ANDROID) && defined(__aarch64__) && defined(SYS_mmap2)
// Android NDK defines SYS_mmap2 for AArch64 despite it not supporting mmap2.
# undef SYS_mmap2
# endif
# ifdef SYS_mmap2
return (void*)syscall(SYS_mmap2, addr, length, prot, flags, fd, offset >> 12);
# else
return (void*)syscall(SYS_mmap, addr, length, prot, flags, fd, offset);
# endif
# endif
}
# define mmap _mmap
# define munmap(a, l) syscall(SYS_munmap, a, l)
# endif
#endif
// ***************************************************************************
// Structures for chunk headers for chunks used for non-huge allocations.
struct arena_t;
// Each element of the chunk map corresponds to one page within the chunk.
struct arena_chunk_map_t {
// Linkage for run trees. There are two disjoint uses:
//
// 1) arena_t's tree or available runs.
// 2) arena_run_t conceptually uses this linkage for in-use non-full
// runs, rather than directly embedding linkage.
RedBlackTreeNode<arena_chunk_map_t> link;
// Run address (or size) and various flags are stored together. The bit
// layout looks like (assuming 32-bit system):
//
// ???????? ???????? ????---- -mckdzla
//
// ? : Unallocated: Run address for first/last pages, unset for internal
// pages.
// Small: Run address.
// Large: Run size for first page, unset for trailing pages.
// - : Unused.
// m : MADV_FREE/MADV_DONTNEED'ed?
// c : decommitted?
// k : key?
// d : dirty?
// z : zeroed?
// l : large?
// a : allocated?
//
// Following are example bit patterns for the three types of runs.
//
// r : run address
// s : run size
// x : don't care
// - : 0
// [cdzla] : bit set
//
// Unallocated:
// ssssssss ssssssss ssss---- --c-----
// xxxxxxxx xxxxxxxx xxxx---- ----d---
// ssssssss ssssssss ssss---- -----z--
//
// Small:
// rrrrrrrr rrrrrrrr rrrr---- -------a
// rrrrrrrr rrrrrrrr rrrr---- -------a
// rrrrrrrr rrrrrrrr rrrr---- -------a
//
// Large:
// ssssssss ssssssss ssss---- ------la
// -------- -------- -------- ------la
// -------- -------- -------- ------la
size_t bits;
// Note that CHUNK_MAP_DECOMMITTED's meaning varies depending on whether
// MALLOC_DECOMMIT and MALLOC_DOUBLE_PURGE are defined.
//
// If MALLOC_DECOMMIT is defined, a page which is CHUNK_MAP_DECOMMITTED must be
// re-committed with pages_commit() before it may be touched. If
// MALLOC_DECOMMIT is defined, MALLOC_DOUBLE_PURGE may not be defined.
//
// If neither MALLOC_DECOMMIT nor MALLOC_DOUBLE_PURGE is defined, pages which
// are madvised (with either MADV_DONTNEED or MADV_FREE) are marked with
// CHUNK_MAP_MADVISED.
//
// Otherwise, if MALLOC_DECOMMIT is not defined and MALLOC_DOUBLE_PURGE is
// defined, then a page which is madvised is marked as CHUNK_MAP_MADVISED.
// When it's finally freed with jemalloc_purge_freed_pages, the page is marked
// as CHUNK_MAP_DECOMMITTED.
#define CHUNK_MAP_MADVISED ((size_t)0x40U)
#define CHUNK_MAP_DECOMMITTED ((size_t)0x20U)
#define CHUNK_MAP_MADVISED_OR_DECOMMITTED \
(CHUNK_MAP_MADVISED | CHUNK_MAP_DECOMMITTED)
#define CHUNK_MAP_KEY ((size_t)0x10U)
#define CHUNK_MAP_DIRTY ((size_t)0x08U)
#define CHUNK_MAP_ZEROED ((size_t)0x04U)
#define CHUNK_MAP_LARGE ((size_t)0x02U)
#define CHUNK_MAP_ALLOCATED ((size_t)0x01U)
};
// Arena chunk header.
struct arena_chunk_t {
// Arena that owns the chunk.
arena_t* arena;
// Linkage for the arena's tree of dirty chunks.
RedBlackTreeNode<arena_chunk_t> link_dirty;
#ifdef MALLOC_DOUBLE_PURGE
// If we're double-purging, we maintain a linked list of chunks which
// have pages which have been madvise(MADV_FREE)'d but not explicitly
// purged.
//
// We're currently lazy and don't remove a chunk from this list when
// all its madvised pages are recommitted.
DoublyLinkedListElement<arena_chunk_t> chunks_madvised_elem;
#endif
// Number of dirty pages.
size_t ndirty;
// Map of pages within chunk that keeps track of free/large/small.
arena_chunk_map_t map[1]; // Dynamically sized.
};
// ***************************************************************************
// Constants defining allocator size classes and behavior.
// Maximum size of L1 cache line. This is used to avoid cache line aliasing,
// so over-estimates are okay (up to a point), but under-estimates will
// negatively affect performance.
static const size_t kCacheLineSize = 64;
// Our size classes are inclusive ranges of memory sizes. By describing the
// minimums and how memory is allocated in each range the maximums can be
// calculated.
// Smallest size class to support. On Windows the smallest allocation size
// must be 8 bytes on 32-bit, 16 bytes on 64-bit. On Linux and Mac, even
#ifdef XP_WIN
static const size_t kMinTinyClass = sizeof(void*) * 2;
#else
static const size_t kMinTinyClass = sizeof(void*);
#endif
// Maximum tiny size class.
static const size_t kMaxTinyClass = 8;
// Smallest quantum-spaced size classes. It could actually also be labelled a
// tiny allocation, and is spaced as such from the largest tiny size class.
// Tiny classes being powers of 2, this is twice as large as the largest of
// them.
static const size_t kMinQuantumClass = kMaxTinyClass * 2;
static const size_t kMinQuantumWideClass = 512;
static const size_t kMinSubPageClass = 4_KiB;
// Amount (quantum) separating quantum-spaced size classes.
static const size_t kQuantum = 16;
static const size_t kQuantumMask = kQuantum - 1;
static const size_t kQuantumWide = 256;
static const size_t kQuantumWideMask = kQuantumWide - 1;
static const size_t kMaxQuantumClass = kMinQuantumWideClass - kQuantum;
static const size_t kMaxQuantumWideClass = kMinSubPageClass - kQuantumWide;
// We can optimise some divisions to shifts if these are powers of two.
static_assert(mozilla::IsPowerOfTwo(kQuantum),
"kQuantum is not a power of two");
static_assert(mozilla::IsPowerOfTwo(kQuantumWide),
"kQuantumWide is not a power of two");
static_assert(kMaxQuantumClass % kQuantum == 0,
"kMaxQuantumClass is not a multiple of kQuantum");
static_assert(kMaxQuantumWideClass % kQuantumWide == 0,
"kMaxQuantumWideClass is not a multiple of kQuantumWide");
static_assert(kQuantum < kQuantumWide,
"kQuantum must be smaller than kQuantumWide");
static_assert(mozilla::IsPowerOfTwo(kMinSubPageClass),
"kMinSubPageClass is not a power of two");
// Number of (2^n)-spaced tiny classes.
static const size_t kNumTinyClasses =
LOG2(kMaxTinyClass) - LOG2(kMinTinyClass) + 1;
// Number of quantum-spaced classes. We add kQuantum(Max) before subtracting to
// avoid underflow when a class is empty (Max<Min).
static const size_t kNumQuantumClasses =
(kMaxQuantumClass + kQuantum - kMinQuantumClass) / kQuantum;
static const size_t kNumQuantumWideClasses =
(kMaxQuantumWideClass + kQuantumWide - kMinQuantumWideClass) / kQuantumWide;
// Size and alignment of memory chunks that are allocated by the OS's virtual
// memory system.
static const size_t kChunkSize = 1_MiB;
static const size_t kChunkSizeMask = kChunkSize - 1;
#ifdef MALLOC_STATIC_PAGESIZE
// VM page size. It must divide the runtime CPU page size or the code
// will abort.
// Platform specific page size conditions copied from js/public/HeapAPI.h
# if defined(__powerpc64__)
static const size_t gPageSize = 64_KiB;
# elif defined(__loongarch64)
static const size_t gPageSize = 16_KiB;
# else
static const size_t gPageSize = 4_KiB;
# endif
static const size_t gRealPageSize = gPageSize;
#else
// When MALLOC_OPTIONS contains one or several `P`s, the page size used
// across the allocator is multiplied by 2 for each `P`, but we also keep
// the real page size for code paths that need it. gPageSize is thus a
// power of two greater or equal to gRealPageSize.
static size_t gRealPageSize;
static size_t gPageSize;
#endif
#ifdef MALLOC_STATIC_PAGESIZE
# define DECLARE_GLOBAL(type, name)
# define DEFINE_GLOBALS
# define END_GLOBALS
# define DEFINE_GLOBAL(type) static const type
# define GLOBAL_LOG2 LOG2
# define GLOBAL_ASSERT_HELPER1(x) static_assert(x, #x)
# define GLOBAL_ASSERT_HELPER2(x, y) static_assert(x, y)
# define GLOBAL_ASSERT(...) \
MACRO_CALL( \
MOZ_PASTE_PREFIX_AND_ARG_COUNT(GLOBAL_ASSERT_HELPER, __VA_ARGS__), \
(__VA_ARGS__))
# define GLOBAL_CONSTEXPR constexpr
#else
# define DECLARE_GLOBAL(type, name) static type name;
# define DEFINE_GLOBALS static void DefineGlobals() {
# define END_GLOBALS }
# define DEFINE_GLOBAL(type)
# define GLOBAL_LOG2 FloorLog2
# define GLOBAL_ASSERT MOZ_RELEASE_ASSERT
# define GLOBAL_CONSTEXPR
#endif
DECLARE_GLOBAL(size_t, gMaxSubPageClass)
DECLARE_GLOBAL(uint8_t, gNumSubPageClasses)
DECLARE_GLOBAL(uint8_t, gPageSize2Pow)
DECLARE_GLOBAL(size_t, gPageSizeMask)
DECLARE_GLOBAL(size_t, gChunkNumPages)
DECLARE_GLOBAL(size_t, gChunkHeaderNumPages)
DECLARE_GLOBAL(size_t, gMaxLargeClass)
DEFINE_GLOBALS
// Largest sub-page size class, or zero if there are none
DEFINE_GLOBAL(size_t)
gMaxSubPageClass = gPageSize / 2 >= kMinSubPageClass ? gPageSize / 2 : 0;
// Max size class for bins.
#define gMaxBinClass \
(gMaxSubPageClass ? gMaxSubPageClass : kMaxQuantumWideClass)
// Number of sub-page bins.
DEFINE_GLOBAL(uint8_t)
gNumSubPageClasses = []() GLOBAL_CONSTEXPR -> uint8_t {
if GLOBAL_CONSTEXPR (gMaxSubPageClass != 0) {
return FloorLog2(gMaxSubPageClass) - LOG2(kMinSubPageClass) + 1;
}
return 0;
}();
DEFINE_GLOBAL(uint8_t) gPageSize2Pow = GLOBAL_LOG2(gPageSize);
DEFINE_GLOBAL(size_t) gPageSizeMask = gPageSize - 1;
// Number of pages in a chunk.
DEFINE_GLOBAL(size_t) gChunkNumPages = kChunkSize >> gPageSize2Pow;
// Number of pages necessary for a chunk header plus a guard page.
DEFINE_GLOBAL(size_t)
gChunkHeaderNumPages =
1 + (((sizeof(arena_chunk_t) +
sizeof(arena_chunk_map_t) * (gChunkNumPages - 1) + gPageSizeMask) &
~gPageSizeMask) >>
gPageSize2Pow);
// One chunk, minus the header, minus a guard page
DEFINE_GLOBAL(size_t)
gMaxLargeClass =
kChunkSize - gPageSize - (gChunkHeaderNumPages << gPageSize2Pow);
// Various sanity checks that regard configuration.
GLOBAL_ASSERT(1ULL << gPageSize2Pow == gPageSize,
"Page size is not a power of two");
GLOBAL_ASSERT(kQuantum >= sizeof(void*));
GLOBAL_ASSERT(kQuantum <= kQuantumWide);
GLOBAL_ASSERT(!kNumQuantumWideClasses ||
kQuantumWide <= (kMinSubPageClass - kMaxQuantumClass));
GLOBAL_ASSERT(kQuantumWide <= kMaxQuantumClass);
GLOBAL_ASSERT(gMaxSubPageClass >= kMinSubPageClass || gMaxSubPageClass == 0);
GLOBAL_ASSERT(gMaxLargeClass >= gMaxSubPageClass);
GLOBAL_ASSERT(kChunkSize >= gPageSize);
GLOBAL_ASSERT(kQuantum * 4 <= kChunkSize);
END_GLOBALS
// Recycle at most 128 MiB of chunks. This means we retain at most
// 6.25% of the process address space on a 32-bit OS for later use.
static const size_t gRecycleLimit = 128_MiB;
// The current amount of recycled bytes, updated atomically.
static Atomic<size_t, ReleaseAcquire> gRecycledSize;
// Maximum number of dirty pages per arena.
#define DIRTY_MAX_DEFAULT (1U << 8)
static size_t opt_dirty_max = DIRTY_MAX_DEFAULT;
// Return the smallest chunk multiple that is >= s.
#define CHUNK_CEILING(s) (((s) + kChunkSizeMask) & ~kChunkSizeMask)
// Return the smallest cacheline multiple that is >= s.
#define CACHELINE_CEILING(s) \
(((s) + (kCacheLineSize - 1)) & ~(kCacheLineSize - 1))
// Return the smallest quantum multiple that is >= a.
#define QUANTUM_CEILING(a) (((a) + (kQuantumMask)) & ~(kQuantumMask))
#define QUANTUM_WIDE_CEILING(a) \
(((a) + (kQuantumWideMask)) & ~(kQuantumWideMask))
// Return the smallest sub page-size that is >= a.
#define SUBPAGE_CEILING(a) (RoundUpPow2(a))
// Return the smallest pagesize multiple that is >= s.
#define PAGE_CEILING(s) (((s) + gPageSizeMask) & ~gPageSizeMask)
// Number of all the small-allocated classes
#define NUM_SMALL_CLASSES \
(kNumTinyClasses + kNumQuantumClasses + kNumQuantumWideClasses + \
gNumSubPageClasses)
// ***************************************************************************
// MALLOC_DECOMMIT and MALLOC_DOUBLE_PURGE are mutually exclusive.
#if defined(MALLOC_DECOMMIT) && defined(MALLOC_DOUBLE_PURGE)
# error MALLOC_DECOMMIT and MALLOC_DOUBLE_PURGE are mutually exclusive.
#endif
static void* base_alloc(size_t aSize);
// Set to true once the allocator has been initialized.
#if defined(_MSC_VER) && !defined(__clang__)
// MSVC may create a static initializer for an Atomic<bool>, which may actually
// run after `malloc_init` has been called once, which triggers multiple
// initializations.
// We work around the problem by not using an Atomic<bool> at all. There is a
// theoretical problem with using `malloc_initialized` non-atomically, but
// practically, this is only true if `malloc_init` is never called before
// threads are created.
static bool malloc_initialized;
#else
static Atomic<bool, MemoryOrdering::ReleaseAcquire> malloc_initialized;
#endif
static StaticMutex gInitLock MOZ_UNANNOTATED = {STATIC_MUTEX_INIT};
// ***************************************************************************
// Statistics data structures.
struct arena_stats_t {
// Number of bytes currently mapped.
size_t mapped;
// Current number of committed pages.
size_t committed;
// Per-size-category statistics.
size_t allocated_small;
size_t allocated_large;
};
// ***************************************************************************
// Extent data structures.
enum ChunkType {
UNKNOWN_CHUNK,
ZEROED_CHUNK, // chunk only contains zeroes.
ARENA_CHUNK, // used to back arena runs created by arena_t::AllocRun.
HUGE_CHUNK, // used to back huge allocations (e.g. arena_t::MallocHuge).
RECYCLED_CHUNK, // chunk has been stored for future use by chunk_recycle.
};
// Tree of extents.
struct extent_node_t {
union {
// Linkage for the size/address-ordered tree for chunk recycling.
RedBlackTreeNode<extent_node_t> mLinkBySize;
// Arena id for huge allocations. It's meant to match mArena->mId,
// which only holds true when the arena hasn't been disposed of.
arena_id_t mArenaId;
};
// Linkage for the address-ordered tree.
RedBlackTreeNode<extent_node_t> mLinkByAddr;
// Pointer to the extent that this tree node is responsible for.
void* mAddr;
// Total region size.
size_t mSize;
union {
// What type of chunk is there; used for chunk recycling.
ChunkType mChunkType;
// A pointer to the associated arena, for huge allocations.
arena_t* mArena;
};
};
struct ExtentTreeSzTrait {
static RedBlackTreeNode<extent_node_t>& GetTreeNode(extent_node_t* aThis) {
return aThis->mLinkBySize;
}
static inline Order Compare(extent_node_t* aNode, extent_node_t* aOther) {
Order ret = CompareInt(aNode->mSize, aOther->mSize);
return (ret != Order::eEqual) ? ret
: CompareAddr(aNode->mAddr, aOther->mAddr);
}
};
struct ExtentTreeTrait {
static RedBlackTreeNode<extent_node_t>& GetTreeNode(extent_node_t* aThis) {
return aThis->mLinkByAddr;
}
static inline Order Compare(extent_node_t* aNode, extent_node_t* aOther) {
return CompareAddr(aNode->mAddr, aOther->mAddr);
}
};
struct ExtentTreeBoundsTrait : public ExtentTreeTrait {
static inline Order Compare(extent_node_t* aKey, extent_node_t* aNode) {
uintptr_t key_addr = reinterpret_cast<uintptr_t>(aKey->mAddr);
uintptr_t node_addr = reinterpret_cast<uintptr_t>(aNode->mAddr);
size_t node_size = aNode->mSize;
// Is aKey within aNode?
if (node_addr <= key_addr && key_addr < node_addr + node_size) {
return Order::eEqual;
}
return CompareAddr(aKey->mAddr, aNode->mAddr);
}
};
// Describe size classes to which allocations are rounded up to.
// TODO: add large and huge types when the arena allocation code
// changes in a way that allows it to be beneficial.
class SizeClass {
public:
enum ClassType {
Tiny,
Quantum,
QuantumWide,
SubPage,
Large,
};
explicit inline SizeClass(size_t aSize) {
if (aSize <= kMaxTinyClass) {
mType = Tiny;
mSize = std::max(RoundUpPow2(aSize), kMinTinyClass);
} else if (aSize <= kMaxQuantumClass) {
mType = Quantum;
mSize = QUANTUM_CEILING(aSize);
} else if (aSize <= kMaxQuantumWideClass) {
mType = QuantumWide;
mSize = QUANTUM_WIDE_CEILING(aSize);
} else if (aSize <= gMaxSubPageClass) {
mType = SubPage;
mSize = SUBPAGE_CEILING(aSize);
} else if (aSize <= gMaxLargeClass) {
mType = Large;
mSize = PAGE_CEILING(aSize);
} else {
MOZ_MAKE_COMPILER_ASSUME_IS_UNREACHABLE("Invalid size");
}
}
SizeClass& operator=(const SizeClass& aOther) = default;
bool operator==(const SizeClass& aOther) { return aOther.mSize == mSize; }
size_t Size() { return mSize; }
ClassType Type() { return mType; }
SizeClass Next() { return SizeClass(mSize + 1); }
private:
ClassType mType;
size_t mSize;
};
// Fast division
//
// During deallocation we want to divide by the size class. This class
// provides a routine and sets up a constant as follows.
//
// To divide by a number D that is not a power of two we multiply by (2^17 /
// D) and then right shift by 17 positions.
//
// X / D
//
// becomes
//
// (X * m) >> p
//
// Where m is calculated during the FastDivisor constructor similarly to:
//
// m = 2^p / D
//
template <typename T>
class FastDivisor {
private:
// The shift amount (p) is chosen to minimise the size of m while
// working for divisors up to 65536 in steps of 16. I arrived at 17
// experimentally. I wanted a low number to minimise the range of m
// so it can fit in a uint16_t, 16 didn't work but 17 worked perfectly.
//
// We'd need to increase this if we allocated memory on smaller boundaries
// than 16.
static const unsigned p = 17;
// We can fit the inverted divisor in 16 bits, but we template it here for
// convenience.
T m;
public:
// Needed so mBins can be constructed.
FastDivisor() : m(0) {}
FastDivisor(unsigned div, unsigned max) {
MOZ_ASSERT(div <= max);
// divide_inv_shift is large enough.
MOZ_ASSERT((1U << p) >= div);
// The calculation here for m is formula 26 from Section
// 10-9 "Unsigned Division by Divisors >= 1" in
// Henry S. Warren, Jr.'s Hacker's Delight, 2nd Ed.
unsigned m_ = ((1U << p) + div - 1 - (((1U << p) - 1) % div)) / div;
// Make sure that max * m does not overflow.
MOZ_DIAGNOSTIC_ASSERT(max < UINT_MAX / m_);
MOZ_ASSERT(m_ <= std::numeric_limits<T>::max());
m = static_cast<T>(m_);
// Initialisation made m non-zero.
MOZ_ASSERT(m);
// Test that all the divisions in the range we expected would work.
#ifdef MOZ_DEBUG
for (unsigned num = 0; num < max; num += div) {
MOZ_ASSERT(num / div == divide(num));
}
#endif
}
// Note that this always occurs in uint32_t regardless of m's type. If m is
// a uint16_t it will be zero-extended before the multiplication. We also use
// uint32_t rather than something that could possibly be larger because it is
// most-likely the cheapest multiplication.
inline uint32_t divide(uint32_t num) const {
// Check that m was initialised.
MOZ_ASSERT(m);
return (num * m) >> p;
}
};
template <typename T>
unsigned inline operator/(unsigned num, FastDivisor<T> divisor) {
return divisor.divide(num);
}
// ***************************************************************************
// Radix tree data structures.
//
// The number of bits passed to the template is the number of significant bits
// in an address to do a radix lookup with.
//
// An address is looked up by splitting it in kBitsPerLevel bit chunks, except
// the most significant bits, where the bit chunk is kBitsAtLevel1 which can be
// different if Bits is not a multiple of kBitsPerLevel.
//
// With e.g. sizeof(void*)=4, Bits=16 and kBitsPerLevel=8, an address is split
// like the following:
// 0x12345678 -> mRoot[0x12][0x34]
template <size_t Bits>
class AddressRadixTree {
// Size of each radix tree node (as a power of 2).
// This impacts tree depth.
#ifdef HAVE_64BIT_BUILD
static const size_t kNodeSize = kCacheLineSize;
#else
static const size_t kNodeSize = 16_KiB;
#endif
static const size_t kBitsPerLevel = LOG2(kNodeSize) - LOG2(sizeof(void*));
static const size_t kBitsAtLevel1 =
(Bits % kBitsPerLevel) ? Bits % kBitsPerLevel : kBitsPerLevel;
static const size_t kHeight = (Bits + kBitsPerLevel - 1) / kBitsPerLevel;
static_assert(kBitsAtLevel1 + (kHeight - 1) * kBitsPerLevel == Bits,
"AddressRadixTree parameters don't work out");
Mutex mLock MOZ_UNANNOTATED;
void** mRoot;
public:
bool Init();
inline void* Get(void* aAddr);
// Returns whether the value was properly set.
inline bool Set(void* aAddr, void* aValue);
inline bool Unset(void* aAddr) { return Set(aAddr, nullptr); }
private:
inline void** GetSlot(void* aAddr, bool aCreate = false);
};
// ***************************************************************************
// Arena data structures.
struct arena_bin_t;
struct ArenaChunkMapLink {
static RedBlackTreeNode<arena_chunk_map_t>& GetTreeNode(
arena_chunk_map_t* aThis) {
return aThis->link;
}
};
struct ArenaRunTreeTrait : public ArenaChunkMapLink {
static inline Order Compare(arena_chunk_map_t* aNode,
arena_chunk_map_t* aOther) {
MOZ_ASSERT(aNode);
MOZ_ASSERT(aOther);
return CompareAddr(aNode, aOther);
}
};
struct ArenaAvailTreeTrait : public ArenaChunkMapLink {
static inline Order Compare(arena_chunk_map_t* aNode,
arena_chunk_map_t* aOther) {
size_t size1 = aNode->bits & ~gPageSizeMask;
size_t size2 = aOther->bits & ~gPageSizeMask;
Order ret = CompareInt(size1, size2);
return (ret != Order::eEqual)
? ret
: CompareAddr((aNode->bits & CHUNK_MAP_KEY) ? nullptr : aNode,
aOther);
}
};
struct ArenaDirtyChunkTrait {
static RedBlackTreeNode<arena_chunk_t>& GetTreeNode(arena_chunk_t* aThis) {
return aThis->link_dirty;
}
static inline Order Compare(arena_chunk_t* aNode, arena_chunk_t* aOther) {
MOZ_ASSERT(aNode);
MOZ_ASSERT(aOther);
return CompareAddr(aNode, aOther);
}
};
#ifdef MALLOC_DOUBLE_PURGE
namespace mozilla {
template <>
struct GetDoublyLinkedListElement<arena_chunk_t> {
static DoublyLinkedListElement<arena_chunk_t>& Get(arena_chunk_t* aThis) {
return aThis->chunks_madvised_elem;
}
};
} // namespace mozilla
#endif
struct arena_run_t {
#if defined(MOZ_DIAGNOSTIC_ASSERT_ENABLED)
uint32_t mMagic;
# define ARENA_RUN_MAGIC 0x384adf93
// On 64-bit platforms, having the arena_bin_t pointer following
// the mMagic field means there's padding between both fields, making
// the run header larger than necessary.
// But when MOZ_DIAGNOSTIC_ASSERT_ENABLED is not set, starting the
// header with this field followed by the arena_bin_t pointer yields
// the same padding. We do want the mMagic field to appear first, so
// depending whether MOZ_DIAGNOSTIC_ASSERT_ENABLED is set or not, we
// move some field to avoid padding.
// Number of free regions in run.
unsigned mNumFree;
#endif
// Bin this run is associated with.
arena_bin_t* mBin;
// Index of first element that might have a free region.
unsigned mRegionsMinElement;
#if !defined(MOZ_DIAGNOSTIC_ASSERT_ENABLED)
// Number of free regions in run.
unsigned mNumFree;
#endif
// Bitmask of in-use regions (0: in use, 1: free).
unsigned mRegionsMask[1]; // Dynamically sized.
};
struct arena_bin_t {
// Current run being used to service allocations of this bin's size
// class.
arena_run_t* mCurrentRun;
// Tree of non-full runs. This tree is used when looking for an
// existing run when mCurrentRun is no longer usable. We choose the
// non-full run that is lowest in memory; this policy tends to keep
// objects packed well, and it can also help reduce the number of
// almost-empty chunks.
RedBlackTree<arena_chunk_map_t, ArenaRunTreeTrait> mNonFullRuns;
// Bin's size class.
size_t mSizeClass;
// Total number of regions in a run for this bin's size class.
uint32_t mRunNumRegions;
// Number of elements in a run's mRegionsMask for this bin's size class.
uint32_t mRunNumRegionsMask;
// Offset of first region in a run for this bin's size class.
uint32_t mRunFirstRegionOffset;
// Current number of runs in this bin, full or otherwise.
uint32_t mNumRuns;
// A constant for fast division by size class. This value is 16 bits wide so
// it is placed last.
FastDivisor<uint16_t> mSizeDivisor;
// Total number of pages in a run for this bin's size class.
uint8_t mRunSizePages;
// Amount of overhead runs are allowed to have.
static constexpr double kRunOverhead = 1.6_percent;
static constexpr double kRunRelaxedOverhead = 2.4_percent;
// Initialize a bin for the given size class.
// The generated run sizes, for a page size of 4 KiB, are:
// size|run size|run size|run size|run
// class|size class|size class|size class|size
// 4 4 KiB 8 4 KiB 16 4 KiB 32 4 KiB
// 48 4 KiB 64 4 KiB 80 4 KiB 96 4 KiB
// 112 4 KiB 128 8 KiB 144 4 KiB 160 8 KiB
// 176 4 KiB 192 4 KiB 208 8 KiB 224 4 KiB
// 240 8 KiB 256 16 KiB 272 8 KiB 288 4 KiB
// 304 12 KiB 320 12 KiB 336 4 KiB 352 8 KiB
// 368 4 KiB 384 8 KiB 400 20 KiB 416 16 KiB
// 432 12 KiB 448 4 KiB 464 16 KiB 480 8 KiB
// 496 20 KiB 512 32 KiB 768 16 KiB 1024 64 KiB
// 1280 24 KiB 1536 32 KiB 1792 16 KiB 2048 128 KiB
// 2304 16 KiB 2560 48 KiB 2816 36 KiB 3072 64 KiB
// 3328 36 KiB 3584 32 KiB 3840 64 KiB
inline void Init(SizeClass aSizeClass);
};
// We try to keep the above structure aligned with common cache lines sizes,
// often that's 64 bytes on x86 and ARM, we don't make assumptions for other
// architectures.
#if defined(__x86_64__) || defined(__aarch64__)
// On 64bit platforms this structure is often 48 bytes
// long, which means every other array element will be properly aligned.
static_assert(sizeof(arena_bin_t) == 48);
#elif defined(__x86__) || defined(__arm__)
static_assert(sizeof(arena_bin_t) == 32);
#endif
struct arena_t {
#if defined(MOZ_DIAGNOSTIC_ASSERT_ENABLED)
uint32_t mMagic;
# define ARENA_MAGIC 0x947d3d24
#endif
// Linkage for the tree of arenas by id.
RedBlackTreeNode<arena_t> mLink;
// Arena id, that we keep away from the beginning of the struct so that
// free list pointers in TypedBaseAlloc<arena_t> don't overflow in it,
// and it keeps the value it had after the destructor.
arena_id_t mId;
// All operations on this arena require that lock be locked. The MaybeMutex
// class well elude locking if the arena is accessed from a single thread
// only.
MaybeMutex mLock MOZ_UNANNOTATED;
arena_stats_t mStats;
private:
// Tree of dirty-page-containing chunks this arena manages.
RedBlackTree<arena_chunk_t, ArenaDirtyChunkTrait> mChunksDirty;
#ifdef MALLOC_DOUBLE_PURGE
// Head of a linked list of MADV_FREE'd-page-containing chunks this
// arena manages.
DoublyLinkedList<arena_chunk_t> mChunksMAdvised;
#endif
// In order to avoid rapid chunk allocation/deallocation when an arena
// oscillates right on the cusp of needing a new chunk, cache the most
// recently freed chunk. The spare is left in the arena's chunk trees
// until it is deleted.
//
// There is one spare chunk per arena, rather than one spare total, in
// order to avoid interactions between multiple threads that could make
// a single spare inadequate.
arena_chunk_t* mSpare;
// A per-arena opt-in to randomize the offset of small allocations
bool mRandomizeSmallAllocations;
// Whether this is a private arena. Multiple public arenas are just a
// performance optimization and not a safety feature.
//
// Since, for example, we don't want thread-local arenas to grow too much, we
// use the default arena for bigger allocations. We use this member to allow
// realloc() to switch out of our arena if needed (which is not allowed for
// private arenas for security).
bool mIsPrivate;
// A pseudorandom number generator. Initially null, it gets initialized
// on first use to avoid recursive malloc initialization (e.g. on OSX
// arc4random allocates memory).
mozilla::non_crypto::XorShift128PlusRNG* mPRNG;
public:
// Current count of pages within unused runs that are potentially
// dirty, and for which madvise(... MADV_FREE) has not been called. By
// tracking this, we can institute a limit on how much dirty unused
// memory is mapped for each arena.
size_t mNumDirty;
// Maximum value allowed for mNumDirty.
size_t mMaxDirty;
int32_t mMaxDirtyIncreaseOverride;
int32_t mMaxDirtyDecreaseOverride;
private:
// Size/address-ordered tree of this arena's available runs. This tree
// is used for first-best-fit run allocation.
RedBlackTree<arena_chunk_map_t, ArenaAvailTreeTrait> mRunsAvail;
public:
// mBins is used to store rings of free regions of the following sizes,
// assuming a 16-byte quantum, 4kB pagesize, and default MALLOC_OPTIONS.
//
// | mBins[i] | size |
// +----------+------+
// | 0 | 2 |
// | 1 | 4 |
// | 2 | 8 |
// +----------+------+
// | 3 | 16 |
// | 4 | 32 |
// | 5 | 48 |
// | 6 | 64 |
// | : :
// | : :
// | 33 | 496 |
// | 34 | 512 |
// +----------+------+
// | 35 | 768 |
// | 36 | 1024 |
// | : :
// | : :
// | 46 | 3584 |
// | 47 | 3840 |
// +----------+------+
arena_bin_t mBins[1]; // Dynamically sized.
explicit arena_t(arena_params_t* aParams, bool aIsPrivate);
~arena_t();
private:
void InitChunk(arena_chunk_t* aChunk);
// This may return a chunk that should be destroyed with chunk_dealloc outside
// of the arena lock. It is not the same chunk as was passed in (since that
// chunk now becomes mSpare).
[[nodiscard]] arena_chunk_t* DeallocChunk(arena_chunk_t* aChunk);
arena_run_t* AllocRun(size_t aSize, bool aLarge, bool aZero);
arena_chunk_t* DallocRun(arena_run_t* aRun, bool aDirty);
[[nodiscard]] bool SplitRun(arena_run_t* aRun, size_t aSize, bool aLarge,
bool aZero);
void TrimRunHead(arena_chunk_t* aChunk, arena_run_t* aRun, size_t aOldSize,
size_t aNewSize);
void TrimRunTail(arena_chunk_t* aChunk, arena_run_t* aRun, size_t aOldSize,
size_t aNewSize, bool dirty);
arena_run_t* GetNonFullBinRun(arena_bin_t* aBin);
inline uint8_t FindFreeBitInMask(uint32_t aMask, uint32_t& aRng);
inline void* ArenaRunRegAlloc(arena_run_t* aRun, arena_bin_t* aBin);
inline void* MallocSmall(size_t aSize, bool aZero);
void* MallocLarge(size_t aSize, bool aZero);
void* MallocHuge(size_t aSize, bool aZero);
void* PallocLarge(size_t aAlignment, size_t aSize, size_t aAllocSize);
void* PallocHuge(size_t aSize, size_t aAlignment, bool aZero);
void RallocShrinkLarge(arena_chunk_t* aChunk, void* aPtr, size_t aSize,
size_t aOldSize);
bool RallocGrowLarge(arena_chunk_t* aChunk, void* aPtr, size_t aSize,
size_t aOldSize);
void* RallocSmallOrLarge(void* aPtr, size_t aSize, size_t aOldSize);
void* RallocHuge(void* aPtr, size_t aSize, size_t aOldSize);
public:
inline void* Malloc(size_t aSize, bool aZero);
void* Palloc(size_t aAlignment, size_t aSize);
// This may return a chunk that should be destroyed with chunk_dealloc outside
// of the arena lock. It is not the same chunk as was passed in (since that
// chunk now becomes mSpare).
[[nodiscard]] inline arena_chunk_t* DallocSmall(arena_chunk_t* aChunk,
void* aPtr,
arena_chunk_map_t* aMapElm);
[[nodiscard]] arena_chunk_t* DallocLarge(arena_chunk_t* aChunk, void* aPtr);
void* Ralloc(void* aPtr, size_t aSize, size_t aOldSize);
size_t EffectiveMaxDirty();
// Passing one means purging all.
void Purge(size_t aMaxDirty);
void HardPurge();
bool IsMainThreadOnly() const { return !mLock.LockIsEnabled(); }
void* operator new(size_t aCount) = delete;
void* operator new(size_t aCount, const fallible_t&) noexcept;
void operator delete(void*);
};
struct ArenaTreeTrait {
static RedBlackTreeNode<arena_t>& GetTreeNode(arena_t* aThis) {
return aThis->mLink;
}
static inline Order Compare(arena_t* aNode, arena_t* aOther) {
MOZ_ASSERT(aNode);
MOZ_ASSERT(aOther);
return CompareInt(aNode->mId, aOther->mId);
}
};
// Bookkeeping for all the arenas used by the allocator.
// Arenas are separated in two categories:
// - "private" arenas, used through the moz_arena_* API
// - all the other arenas: the default arena, and thread-local arenas,
// used by the standard API.
class ArenaCollection {
public:
bool Init() {
mArenas.Init();
mPrivateArenas.Init();
mMainThreadArenas.Init();
arena_params_t params;
// The main arena allows more dirty pages than the default for other arenas.
params.mMaxDirty = opt_dirty_max;
mDefaultArena =
mLock.Init() ? CreateArena(/* aIsPrivate = */ false, ¶ms) : nullptr;
return bool(mDefaultArena);
}
inline arena_t* GetById(arena_id_t aArenaId, bool aIsPrivate);
arena_t* CreateArena(bool aIsPrivate, arena_params_t* aParams);
void DisposeArena(arena_t* aArena) {
MutexAutoLock lock(mLock);
Tree& tree =
aArena->IsMainThreadOnly() ? mMainThreadArenas : mPrivateArenas;
MOZ_RELEASE_ASSERT(tree.Search(aArena), "Arena not in tree");
tree.Remove(aArena);
delete aArena;
}
void SetDefaultMaxDirtyPageModifier(int32_t aModifier) {
mDefaultMaxDirtyPageModifier = aModifier;
}
int32_t DefaultMaxDirtyPageModifier() { return mDefaultMaxDirtyPageModifier; }
using Tree = RedBlackTree<arena_t, ArenaTreeTrait>;
struct Iterator : Tree::Iterator {
explicit Iterator(Tree* aTree, Tree* aSecondTree,
Tree* aThirdTree = nullptr)
: Tree::Iterator(aTree),
mSecondTree(aSecondTree),
mThirdTree(aThirdTree) {}
Item<Iterator> begin() {
return Item<Iterator>(this, *Tree::Iterator::begin());
}
Item<Iterator> end() { return Item<Iterator>(this, nullptr); }
arena_t* Next() {
arena_t* result = Tree::Iterator::Next();
if (!result && mSecondTree) {
new (this) Iterator(mSecondTree, mThirdTree);
result = *Tree::Iterator::begin();
}
return result;
}
private:
Tree* mSecondTree;
Tree* mThirdTree;
};
Iterator iter() {
if (IsOnMainThreadWeak()) {
return Iterator(&mArenas, &mPrivateArenas, &mMainThreadArenas);
}
return Iterator(&mArenas, &mPrivateArenas);
}
inline arena_t* GetDefault() { return mDefaultArena; }
Mutex mLock MOZ_UNANNOTATED;
// We're running on the main thread which is set by a call to SetMainThread().
bool IsOnMainThread() const {
return mMainThreadId.isSome() && mMainThreadId.value() == GetThreadId();
}
// We're running on the main thread or SetMainThread() has never been called.
bool IsOnMainThreadWeak() const {
return mMainThreadId.isNothing() || IsOnMainThread();
}
// After a fork set the new thread ID in the child.
void PostForkFixMainThread() {
if (mMainThreadId.isSome()) {
// Only if the main thread has been defined.
mMainThreadId = Some(GetThreadId());
}
}
void SetMainThread() {
MutexAutoLock lock(mLock);
MOZ_ASSERT(mMainThreadId.isNothing());
mMainThreadId = Some(GetThreadId());
}
private:
const static arena_id_t MAIN_THREAD_ARENA_BIT = 0x1;
inline arena_t* GetByIdInternal(Tree& aTree, arena_id_t aArenaId);
arena_id_t MakeRandArenaId(bool aIsMainThreadOnly) const;
static bool ArenaIdIsMainThreadOnly(arena_id_t aArenaId) {
return aArenaId & MAIN_THREAD_ARENA_BIT;
}
arena_t* mDefaultArena;
arena_id_t mLastPublicArenaId;
// Accessing mArenas and mPrivateArenas can only be done while holding mLock.
// Since mMainThreadArenas can only be used from the main thread, it can be
// accessed without a lock which is why it is a seperate tree.
Tree mArenas;
Tree mPrivateArenas;
Tree mMainThreadArenas;
Atomic<int32_t, MemoryOrdering::Relaxed> mDefaultMaxDirtyPageModifier;
Maybe<ThreadId> mMainThreadId;
};
static ArenaCollection gArenas;
// ******
// Chunks.
static AddressRadixTree<(sizeof(void*) << 3) - LOG2(kChunkSize)> gChunkRTree;
// Protects chunk-related data structures.
static Mutex chunks_mtx;
// Trees of chunks that were previously allocated (trees differ only in node
// ordering). These are used when allocating chunks, in an attempt to re-use
// address space. Depending on function, different tree orderings are needed,
// which is why there are two trees with the same contents.
static RedBlackTree<extent_node_t, ExtentTreeSzTrait> gChunksBySize
MOZ_GUARDED_BY(chunks_mtx);
static RedBlackTree<extent_node_t, ExtentTreeTrait> gChunksByAddress
MOZ_GUARDED_BY(chunks_mtx);
// Protects huge allocation-related data structures.
static Mutex huge_mtx;
// Tree of chunks that are stand-alone huge allocations.
static RedBlackTree<extent_node_t, ExtentTreeTrait> huge
MOZ_GUARDED_BY(huge_mtx);
// Huge allocation statistics.
static size_t huge_allocated MOZ_GUARDED_BY(huge_mtx);
static size_t huge_mapped MOZ_GUARDED_BY(huge_mtx);
// **************************
// base (internal allocation).
static Mutex base_mtx;
// Current pages that are being used for internal memory allocations. These
// pages are carved up in cacheline-size quanta, so that there is no chance of
// false cache line sharing.
static void* base_pages MOZ_GUARDED_BY(base_mtx);
static void* base_next_addr MOZ_GUARDED_BY(base_mtx);
static void* base_next_decommitted MOZ_GUARDED_BY(base_mtx);
// Address immediately past base_pages.
static void* base_past_addr MOZ_GUARDED_BY(base_mtx);
static size_t base_mapped MOZ_GUARDED_BY(base_mtx);
static size_t base_committed MOZ_GUARDED_BY(base_mtx);
// ******
// Arenas.
// The arena associated with the current thread (per
// jemalloc_thread_local_arena) On OSX, __thread/thread_local circles back
// calling malloc to allocate storage on first access on each thread, which
// leads to an infinite loop, but pthread-based TLS somehow doesn't have this
// problem.
#if !defined(XP_DARWIN)
static MOZ_THREAD_LOCAL(arena_t*) thread_arena;
#else
static detail::ThreadLocal<arena_t*, detail::ThreadLocalKeyStorage>
thread_arena;
#endif
// *****************************
// Runtime configuration options.
#ifdef MALLOC_RUNTIME_CONFIG
# define MALLOC_RUNTIME_VAR static
#else
# define MALLOC_RUNTIME_VAR static const
#endif
enum PoisonType {
NONE,
SOME,
ALL,
};
MALLOC_RUNTIME_VAR bool opt_junk = false;
MALLOC_RUNTIME_VAR bool opt_zero = false;
#ifdef EARLY_BETA_OR_EARLIER
MALLOC_RUNTIME_VAR PoisonType opt_poison = ALL;
#else
MALLOC_RUNTIME_VAR PoisonType opt_poison = SOME;
#endif
MALLOC_RUNTIME_VAR size_t opt_poison_size = kCacheLineSize * 4;
static bool opt_randomize_small = true;
// ***************************************************************************
// Begin forward declarations.
static void* chunk_alloc(size_t aSize, size_t aAlignment, bool aBase);
static void chunk_dealloc(void* aChunk, size_t aSize, ChunkType aType);
#ifdef MOZ_DEBUG
static void chunk_assert_zero(void* aPtr, size_t aSize);
#endif
static void huge_dalloc(void* aPtr, arena_t* aArena);
static bool malloc_init_hard();
#ifndef XP_WIN
# ifdef XP_DARWIN
# define FORK_HOOK extern "C"
# else
# define FORK_HOOK static
# endif
FORK_HOOK void _malloc_prefork(void);
FORK_HOOK void _malloc_postfork_parent(void);
FORK_HOOK void _malloc_postfork_child(void);
#endif
// End forward declarations.
// ***************************************************************************
// FreeBSD's pthreads implementation calls malloc(3), so the malloc
// implementation has to take pains to avoid infinite recursion during
// initialization.
// Returns whether the allocator was successfully initialized.
static inline bool malloc_init() {
if (!malloc_initialized) {
return malloc_init_hard();
}
return true;
}
static void _malloc_message(const char* p) {
#if !defined(XP_WIN)
# define _write write
#endif
// Pretend to check _write() errors to suppress gcc warnings about
// warn_unused_result annotations in some versions of glibc headers.
if (_write(STDERR_FILENO, p, (unsigned int)strlen(p)) < 0) {
return;
}
}
template <typename... Args>
static void _malloc_message(const char* p, Args... args) {
_malloc_message(p);
_malloc_message(args...);
}
#ifdef ANDROID
// Android's pthread.h does not declare pthread_atfork() until SDK 21.
extern "C" MOZ_EXPORT int pthread_atfork(void (*)(void), void (*)(void),
void (*)(void));
#endif
// ***************************************************************************
// Begin Utility functions/macros.
// Return the chunk address for allocation address a.
static inline arena_chunk_t* GetChunkForPtr(const void* aPtr) {
return (arena_chunk_t*)(uintptr_t(aPtr) & ~kChunkSizeMask);
}
// Return the chunk offset of address a.
static inline size_t GetChunkOffsetForPtr(const void* aPtr) {
return (size_t)(uintptr_t(aPtr) & kChunkSizeMask);
}
static inline const char* _getprogname(void) { return "<jemalloc>"; }
static inline void MaybePoison(void* aPtr, size_t aSize) {
size_t size;
switch (opt_poison) {
case NONE:
return;
case SOME:
size = std::min(aSize, opt_poison_size);
break;
case ALL:
size = aSize;
break;
}
MOZ_ASSERT(size != 0 && size <= aSize);
memset(aPtr, kAllocPoison, size);
}
// Fill the given range of memory with zeroes or junk depending on opt_junk and
// opt_zero.
static inline void ApplyZeroOrJunk(void* aPtr, size_t aSize) {
if (opt_junk) {
memset(aPtr, kAllocJunk, aSize);
} else if (opt_zero) {
memset(aPtr, 0, aSize);
}
}
// On Windows, delay crashing on OOM.
#ifdef XP_WIN
namespace MozAllocRetries {
// Maximum retry count on OOM.
constexpr size_t kMaxAttempts = 10;
// Minimum delay time between retries. (The actual delay time may be larger. See
// Microsoft's documentation for ::Sleep() for details.)
constexpr size_t kDelayMs = 50;
using StallSpecs = ::mozilla::StallSpecs;
static constexpr StallSpecs maxStall = {.maxAttempts = kMaxAttempts,
.delayMs = kDelayMs};
static inline StallSpecs GetStallSpecs() {
# if defined(JS_STANDALONE)
// GetGeckoProcessType() isn't available in this configuration. (SpiderMonkey
// on Windows mostly skips this in favor of directly calling ::VirtualAlloc(),
// though, so it's probably not going to matter whether we stall here or not.)
return maxStall;
# else
switch (GetGeckoProcessType()) {
// For the main process, stall for the maximum permissible time period. (The
// main process is the most important one to keep alive.)
case GeckoProcessType::GeckoProcessType_Default:
return maxStall;
// For all other process types, stall for at most half as long.
default:
return {.maxAttempts = maxStall.maxAttempts / 2,
.delayMs = maxStall.delayMs};
}
# endif
}
// Drop-in wrapper around VirtualAlloc. When out of memory, may attempt to stall
// and retry rather than returning immediately, in hopes that the page file is
// about to be expanded by Windows.
//
[[nodiscard]] void* MozVirtualAlloc(LPVOID lpAddress, SIZE_T dwSize,
DWORD flAllocationType, DWORD flProtect) {
DWORD const lastError = ::GetLastError();
constexpr auto IsOOMError = [] {
switch (::GetLastError()) {
// This is the usual error result from VirtualAlloc for OOM.
case ERROR_COMMITMENT_LIMIT:
// Although rare, this has also been observed in low-memory situations.
// (Presumably this means Windows can't allocate enough kernel-side space
// for its own internal representation of the process's virtual address
// space.)
case ERROR_NOT_ENOUGH_MEMORY:
return true;
}
return false;
};
{
void* ptr = ::VirtualAlloc(lpAddress, dwSize, flAllocationType, flProtect);
if (MOZ_LIKELY(ptr)) return ptr;
// We can't do anything for errors other than OOM...
if (!IsOOMError()) return nullptr;
// ... or if this wasn't a request to commit memory in the first place.
// (This function has no strategy for resolving MEM_RESERVE failures.)
if (!(flAllocationType & MEM_COMMIT)) return nullptr;
}
// Retry as many times as desired (possibly zero).
const StallSpecs stallSpecs = GetStallSpecs();
const auto ret =
stallSpecs.StallAndRetry(&::Sleep, [&]() -> std::optional<void*> {
void* ptr =
::VirtualAlloc(lpAddress, dwSize, flAllocationType, flProtect);
if (ptr) {
// The OOM status has been handled, and should not be reported to
// telemetry.
if (IsOOMError()) {
::SetLastError(lastError);
}
return ptr;
}
// Failure for some reason other than OOM.
if (!IsOOMError()) {
return nullptr;
}
return std::nullopt;
});
return ret.value_or(nullptr);
}
} // namespace MozAllocRetries
using MozAllocRetries::MozVirtualAlloc;
namespace mozilla {
MOZ_JEMALLOC_API StallSpecs GetAllocatorStallSpecs() {
return ::MozAllocRetries::GetStallSpecs();
}
} // namespace mozilla
#endif // XP_WIN
// ***************************************************************************
static inline void pages_decommit(void* aAddr, size_t aSize) {
#ifdef XP_WIN
// The region starting at addr may have been allocated in multiple calls
// to VirtualAlloc and recycled, so decommitting the entire region in one
// go may not be valid. However, since we allocate at least a chunk at a
// time, we may touch any region in chunksized increments.
size_t pages_size = std::min(aSize, kChunkSize - GetChunkOffsetForPtr(aAddr));
while (aSize > 0) {
// This will cause Access Violation on read and write and thus act as a
// guard page or region as well.
if (!VirtualFree(aAddr, pages_size, MEM_DECOMMIT)) {
MOZ_CRASH();
}
aAddr = (void*)((uintptr_t)aAddr + pages_size);
aSize -= pages_size;
pages_size = std::min(aSize, kChunkSize);
}
#else
if (mmap(aAddr, aSize, PROT_NONE, MAP_FIXED | MAP_PRIVATE | MAP_ANON, -1,
0) == MAP_FAILED) {
// We'd like to report the OOM for our tooling, but we can't allocate
// memory at this point, so avoid the use of printf.
const char out_of_mappings[] =
"[unhandlable oom] Failed to mmap, likely no more mappings "
"available " __FILE__ " : " MOZ_STRINGIFY(__LINE__);
if (errno == ENOMEM) {
# ifndef ANDROID
fputs(out_of_mappings, stderr);
fflush(stderr);
# endif
MOZ_CRASH_ANNOTATE(out_of_mappings);
}
MOZ_REALLY_CRASH(__LINE__);
}
MozTagAnonymousMemory(aAddr, aSize, "jemalloc-decommitted");
#endif
}
// Commit pages. Returns whether pages were committed.
[[nodiscard]] static inline bool pages_commit(void* aAddr, size_t aSize) {
#ifdef XP_WIN
// The region starting at addr may have been allocated in multiple calls
// to VirtualAlloc and recycled, so committing the entire region in one
// go may not be valid. However, since we allocate at least a chunk at a
// time, we may touch any region in chunksized increments.
size_t pages_size = std::min(aSize, kChunkSize - GetChunkOffsetForPtr(aAddr));
while (aSize > 0) {
if (!MozVirtualAlloc(aAddr, pages_size, MEM_COMMIT, PAGE_READWRITE)) {
return false;
}
aAddr = (void*)((uintptr_t)aAddr + pages_size);
aSize -= pages_size;
pages_size = std::min(aSize, kChunkSize);
}
#else
if (mmap(aAddr, aSize, PROT_READ | PROT_WRITE,
MAP_FIXED | MAP_PRIVATE | MAP_ANON, -1, 0) == MAP_FAILED) {
return false;
}
MozTagAnonymousMemory(aAddr, aSize, "jemalloc");
#endif
return true;
}
static bool base_pages_alloc(size_t minsize) MOZ_REQUIRES(base_mtx) {
size_t csize;
size_t pminsize;
MOZ_ASSERT(minsize != 0);
csize = CHUNK_CEILING(minsize);
base_pages = chunk_alloc(csize, kChunkSize, true);
if (!base_pages) {
return true;
}
base_next_addr = base_pages;
base_past_addr = (void*)((uintptr_t)base_pages + csize);
// Leave enough pages for minsize committed, since otherwise they would
// have to be immediately recommitted.
pminsize = PAGE_CEILING(minsize);
base_next_decommitted = (void*)((uintptr_t)base_pages + pminsize);
if (pminsize < csize) {
pages_decommit(base_next_decommitted, csize - pminsize);
}
base_mapped += csize;
base_committed += pminsize;
return false;
}
static void* base_alloc(size_t aSize) {
void* ret;
size_t csize;
// Round size up to nearest multiple of the cacheline size.
csize = CACHELINE_CEILING(aSize);
MutexAutoLock lock(base_mtx);
// Make sure there's enough space for the allocation.
if ((uintptr_t)base_next_addr + csize > (uintptr_t)base_past_addr) {
if (base_pages_alloc(csize)) {
return nullptr;
}
}
// Allocate.
ret = base_next_addr;
base_next_addr = (void*)((uintptr_t)base_next_addr + csize);
// Make sure enough pages are committed for the new allocation.
if ((uintptr_t)base_next_addr > (uintptr_t)base_next_decommitted) {
void* pbase_next_addr = (void*)(PAGE_CEILING((uintptr_t)base_next_addr));
if (!pages_commit(
base_next_decommitted,
(uintptr_t)pbase_next_addr - (uintptr_t)base_next_decommitted)) {
return nullptr;
}
base_committed +=
(uintptr_t)pbase_next_addr - (uintptr_t)base_next_decommitted;
base_next_decommitted = pbase_next_addr;
}
return ret;
}
static void* base_calloc(size_t aNumber, size_t aSize) {
void* ret = base_alloc(aNumber * aSize);
if (ret) {
memset(ret, 0, aNumber * aSize);
}
return ret;
}
// A specialization of the base allocator with a free list.
template <typename T>
struct TypedBaseAlloc {
static T* sFirstFree;
static size_t size_of() { return sizeof(T); }
static T* alloc() {
T* ret;
base_mtx.Lock();
if (sFirstFree) {
ret = sFirstFree;
sFirstFree = *(T**)ret;
base_mtx.Unlock();
} else {