/*-1* SPDX-License-Identifier: BSD-3-Clause2*3* Copyright (c) 1983 Regents of the University of California.4* All rights reserved.5*6* Redistribution and use in source and binary forms, with or without7* modification, are permitted provided that the following conditions8* are met:9* 1. Redistributions of source code must retain the above copyright10* notice, this list of conditions and the following disclaimer.11* 2. Redistributions in binary form must reproduce the above copyright12* notice, this list of conditions and the following disclaimer in the13* documentation and/or other materials provided with the distribution.14* 3. Neither the name of the University nor the names of its contributors15* may be used to endorse or promote products derived from this software16* without specific prior written permission.17*18* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND19* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE20* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE21* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE22* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL23* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS24* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)25* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT26* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY27* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF28* SUCH DAMAGE.29*/303132/*33* malloc.c (Caltech) 2/21/8234* Chris Kingsley, kingsley@cit-20.35*36* This is a very fast storage allocator. It allocates blocks of a small37* number of different sizes, and keeps free lists of each size. Blocks that38* don't exactly fit are passed up to the next larger size. In this39* implementation, the available sizes are 2^n-4 (or 2^n-10) bytes long.40* This is designed for use in a virtual memory environment.41*/4243#include <sys/param.h>44#include <sys/sysctl.h>45#include <sys/mman.h>46#include <errno.h>47#include <stdarg.h>48#include <stddef.h>49#include <string.h>50#include <unistd.h>51#ifdef IN_RTLD52#include "rtld.h"53#include "rtld_printf.h"54#include "rtld_paths.h"55#endif56#include "rtld_malloc.h"5758/*59* Pre-allocate mmap'ed pages60*/61#define NPOOLPAGES (128*1024/pagesz)62static caddr_t pagepool_start, pagepool_end;6364/*65* The overhead on a block is at least 4 bytes. When free, this space66* contains a pointer to the next free block, and the bottom two bits must67* be zero. When in use, the first byte is set to MAGIC, and the second68* byte is the size index. The remaining bytes are for alignment.69*/70union overhead {71union overhead *ov_next; /* when free */72struct {73uint16_t ovu_index; /* bucket # */74uint8_t ovu_magic; /* magic number */75} ovu;76#define ov_magic ovu.ovu_magic77#define ov_index ovu.ovu_index78};7980static void morecore(int bucket);81static int morepages(int n);8283#define MAGIC 0xef /* magic # on accounting info */84#define AMAGIC 0xdf /* magic # for aligned alloc */8586/*87* nextf[i] is the pointer to the next free block of size88* (FIRST_BUCKET_SIZE << i). The overhead information precedes the data89* area returned to the user.90*/91#define LOW_BITS 392#define FIRST_BUCKET_SIZE (1U << LOW_BITS)93#define NBUCKETS 3094static union overhead *nextf[NBUCKETS];9596static int pagesz; /* page size */9798/*99* The array of supported page sizes is provided by the user, i.e., the100* program that calls this storage allocator. That program must initialize101* the array before making its first call to allocate storage. The array102* must contain at least one page size. The page sizes must be stored in103* increasing order.104*/105106static void *107cp2op(void *cp)108{109return (((caddr_t)cp - sizeof(union overhead)));110}111112void *113__crt_malloc(size_t nbytes)114{115union overhead *op;116int bucket;117size_t amt;118119/*120* First time malloc is called, setup page size.121*/122if (pagesz == 0)123pagesz = pagesizes[0];124/*125* Convert amount of memory requested into closest block size126* stored in hash buckets which satisfies request.127* Account for space used per block for accounting.128*/129amt = FIRST_BUCKET_SIZE;130bucket = 0;131while (nbytes > amt - sizeof(*op)) {132amt <<= 1;133bucket++;134if (amt == 0 || bucket >= NBUCKETS)135return (NULL);136}137/*138* If nothing in hash bucket right now,139* request more memory from the system.140*/141if ((op = nextf[bucket]) == NULL) {142morecore(bucket);143if ((op = nextf[bucket]) == NULL)144return (NULL);145}146/* remove from linked list */147nextf[bucket] = op->ov_next;148op->ov_magic = MAGIC;149op->ov_index = bucket;150return ((char *)(op + 1));151}152153void *154__crt_calloc(size_t num, size_t size)155{156void *ret;157158if (size != 0 && (num * size) / size != num) {159/* size_t overflow. */160return (NULL);161}162163if ((ret = __crt_malloc(num * size)) != NULL)164memset(ret, 0, num * size);165166return (ret);167}168169void *170__crt_aligned_alloc_offset(size_t align, size_t size, size_t offset)171{172void *mem, *ov;173union overhead ov1;174uintptr_t x;175176if (align < FIRST_BUCKET_SIZE)177align = FIRST_BUCKET_SIZE;178offset &= align - 1;179mem = __crt_malloc(size + align + offset + sizeof(union overhead));180if (mem == NULL)181return (NULL);182x = roundup2((uintptr_t)mem + sizeof(union overhead), align);183x += offset;184ov = cp2op((void *)x);185ov1.ov_magic = AMAGIC;186ov1.ov_index = x - (uintptr_t)mem + sizeof(union overhead);187memcpy(ov, &ov1, sizeof(ov1));188return ((void *)x);189}190191/*192* Allocate more memory to the indicated bucket.193*/194static void195morecore(int bucket)196{197union overhead *op;198int sz; /* size of desired block */199int amt; /* amount to allocate */200int nblks; /* how many blocks we get */201202sz = FIRST_BUCKET_SIZE << bucket;203if (sz < pagesz) {204amt = pagesz;205nblks = amt / sz;206} else {207amt = sz;208nblks = 1;209}210if (amt > pagepool_end - pagepool_start)211if (morepages(amt / pagesz + NPOOLPAGES) == 0 &&212/* Retry with min required size */213morepages(amt / pagesz) == 0)214return;215op = (union overhead *)pagepool_start;216pagepool_start += amt;217218/*219* Add new memory allocated to that on220* free list for this hash bucket.221*/222nextf[bucket] = op;223while (--nblks > 0) {224op->ov_next = (union overhead *)((caddr_t)op + sz);225op = (union overhead *)((caddr_t)op + sz);226}227}228229void230__crt_free(void *cp)231{232union overhead *op, op1;233void *opx;234int size;235236if (cp == NULL)237return;238opx = cp2op(cp);239memcpy(&op1, opx, sizeof(op1));240op = op1.ov_magic == AMAGIC ? (void *)((caddr_t)cp - op1.ov_index) :241opx;242if (op->ov_magic != MAGIC)243return; /* sanity */244size = op->ov_index;245op->ov_next = nextf[size]; /* also clobbers ov_magic */246nextf[size] = op;247}248249void *250__crt_realloc(void *cp, size_t nbytes)251{252u_int onb;253int i;254union overhead *op;255char *res;256257if (cp == NULL)258return (__crt_malloc(nbytes));259op = cp2op(cp);260if (op->ov_magic != MAGIC)261return (NULL); /* Double-free or bad argument */262i = op->ov_index;263onb = 1 << (i + 3);264if (onb < (u_int)pagesz)265onb -= sizeof(*op);266else267onb += pagesz - sizeof(*op);268/* avoid the copy if same size block */269if (i != 0) {270i = 1 << (i + 2);271if (i < pagesz)272i -= sizeof(*op);273else274i += pagesz - sizeof(*op);275}276if (nbytes <= onb && nbytes > (size_t)i)277return (cp);278if ((res = __crt_malloc(nbytes)) == NULL)279return (NULL);280bcopy(cp, res, (nbytes < onb) ? nbytes : onb);281__crt_free(cp);282return (res);283}284285static int286morepages(int n)287{288caddr_t addr;289int offset;290291if (pagepool_end - pagepool_start > pagesz) {292addr = roundup2(pagepool_start, pagesz);293if (munmap(addr, pagepool_end - addr) != 0) {294#ifdef IN_RTLD295rtld_fdprintf(STDERR_FILENO, _BASENAME_RTLD ": "296"morepages: cannot munmap %p: %s\n",297addr, rtld_strerror(errno));298#endif299}300}301302offset = (uintptr_t)pagepool_start - rounddown2(303(uintptr_t)pagepool_start, pagesz);304305addr = mmap(0, n * pagesz, PROT_READ | PROT_WRITE,306MAP_ANON | MAP_PRIVATE, -1, 0);307if (addr == MAP_FAILED) {308#ifdef IN_RTLD309rtld_fdprintf(STDERR_FILENO, _BASENAME_RTLD ": morepages: "310"cannot mmap anonymous memory: %s\n",311rtld_strerror(errno));312#endif313pagepool_start = pagepool_end = NULL;314return (0);315}316pagepool_start = addr;317pagepool_end = pagepool_start + n * pagesz;318pagepool_start += offset;319320return (n);321}322323324