authorgravatar for 124872+jedisct1@users.noreply.github.comFrank Denis <124872+jedisct1@users.noreply.github.com> 2022-11-28 19:58:03+01:00
committergravatar for noreply@github.comGitHub <noreply@github.com> 2022-11-28 19:58:03+01:00
logda9c530d9937abd1c17b9eeabec199076428a177
tree4856f810ac58e5ea7b4dcb12b092ffba7a559911
parent4e078941d032c6ac0e1ea3c85989fd5d9a8747ba
signaturebadge-question-mark Signed by PGP key 4AEE18F83AFDEB23

Update wasi-libc to a00bf321eeeca836ee2a0d2d25aeb8524107b8cc (#13626)

* Update wasi-libc to a00bf321eeeca836ee2a0d2d25aeb8524107b8cc It includes a port of emscripten's allocator that performs performs much better than the old one. Most importantly, it includes the prerequisites to later add support for POSIX threads.

101 files changed, 2411 insertions(+), 7382 deletions(-)

lib/libc/include/wasm-wasi-musl/__header_dirent.h+6
...@@ -11,6 +11,12 @@...@@ -11,6 +11,12 @@
11#define DT_REG __WASI_FILETYPE_REGULAR_FILE11#define DT_REG __WASI_FILETYPE_REGULAR_FILE
12#define DT_UNKNOWN __WASI_FILETYPE_UNKNOWN12#define DT_UNKNOWN __WASI_FILETYPE_UNKNOWN
1313
14#define IFTODT(x) (__wasilibc_iftodt(x))
15#define DTTOIF(x) (__wasilibc_dttoif(x))
16
17int __wasilibc_iftodt(int x);
18int __wasilibc_dttoif(int x);
19
14#include <__struct_dirent.h>20#include <__struct_dirent.h>
15#include <__typedef_DIR.h>21#include <__typedef_DIR.h>
1622
lib/libc/include/wasm-wasi-musl/__header_time.h-4
...@@ -16,12 +16,8 @@...@@ -16,12 +16,8 @@
1616
17extern const struct __clockid _CLOCK_MONOTONIC;17extern const struct __clockid _CLOCK_MONOTONIC;
18#define CLOCK_MONOTONIC (&_CLOCK_MONOTONIC)18#define CLOCK_MONOTONIC (&_CLOCK_MONOTONIC)
19extern const struct __clockid _CLOCK_PROCESS_CPUTIME_ID;
20#define CLOCK_PROCESS_CPUTIME_ID (&_CLOCK_PROCESS_CPUTIME_ID)
21extern const struct __clockid _CLOCK_REALTIME;19extern const struct __clockid _CLOCK_REALTIME;
22#define CLOCK_REALTIME (&_CLOCK_REALTIME)20#define CLOCK_REALTIME (&_CLOCK_REALTIME)
23extern const struct __clockid _CLOCK_THREAD_CPUTIME_ID;
24#define CLOCK_THREAD_CPUTIME_ID (&_CLOCK_THREAD_CPUTIME_ID)
2521
26/*22/*
27 * TIME_UTC is the only standardized time base value.23 * TIME_UTC is the only standardized time base value.
lib/libc/include/wasm-wasi-musl/__macro_PAGESIZE.h+5
...@@ -5,6 +5,11 @@...@@ -5,6 +5,11 @@
5 * The page size in WebAssembly is fixed at 64 KiB. If this ever changes,5 * The page size in WebAssembly is fixed at 64 KiB. If this ever changes,
6 * it's expected that applications will need to opt in, so we can change6 * it's expected that applications will need to opt in, so we can change
7 * this.7 * this.
8 *
9 * If this ever needs to be a value outside the range of an `int`, the
10 * `getpagesize` function which returns this value will need special
11 * consideration. POSIX has deprecated `getpagesize` in favor of
12 * `sysconf(_SC_PAGESIZE)` which does not have this problem.
8 */13 */
9#define PAGESIZE (0x10000)14#define PAGESIZE (0x10000)
1015
lib/libc/include/wasm-wasi-musl/__struct_sockaddr.h+1-1
...@@ -7,7 +7,7 @@...@@ -7,7 +7,7 @@
7#include <__typedef_sa_family_t.h>7#include <__typedef_sa_family_t.h>
88
9struct sockaddr {9struct sockaddr {
10 _Alignas(max_align_t) sa_family_t sa_family;10 __attribute__((aligned(__BIGGEST_ALIGNMENT__))) sa_family_t sa_family;
11 char sa_data[0];11 char sa_data[0];
12};12};
1313
lib/libc/include/wasm-wasi-musl/ctype.h+2
...@@ -64,7 +64,9 @@ int isascii(int);...@@ -64,7 +64,9 @@ int isascii(int);
64int toascii(int);64int toascii(int);
65#define _tolower(a) ((a)|0x20)65#define _tolower(a) ((a)|0x20)
66#define _toupper(a) ((a)&0x5f)66#define _toupper(a) ((a)&0x5f)
67#ifndef __cplusplus
67#define isascii(a) (0 ? isascii(a) : (unsigned)(a) < 128)68#define isascii(a) (0 ? isascii(a) : (unsigned)(a) < 128)
69#endif
6870
69#endif71#endif
7072
lib/libc/include/wasm-wasi-musl/limits.h+1-1
...@@ -70,7 +70,7 @@...@@ -70,7 +70,7 @@
70#define PTHREAD_STACK_MIN 204870#define PTHREAD_STACK_MIN 2048
71#define PTHREAD_DESTRUCTOR_ITERATIONS 471#define PTHREAD_DESTRUCTOR_ITERATIONS 4
72#endif72#endif
73#ifdef __wasilibc_unmodified_upstream /* WASI has no semaphores */73#if defined(__wasilibc_unmodified_upstream) || defined(_REENTRANT)
74#define SEM_VALUE_MAX 0x7fffffff74#define SEM_VALUE_MAX 0x7fffffff
75#define SEM_NSEMS_MAX 25675#define SEM_NSEMS_MAX 256
76#endif76#endif
lib/libc/include/wasm-wasi-musl/locale.h+3-1
...@@ -8,7 +8,9 @@ extern "C" {...@@ -8,7 +8,9 @@ extern "C" {
8#include <features.h>8#include <features.h>
99
10#ifdef __wasilibc_unmodified_upstream /* Use the compiler's definition of NULL */10#ifdef __wasilibc_unmodified_upstream /* Use the compiler's definition of NULL */
11#ifdef __cplusplus11#if __cplusplus >= 201103L
12#define NULL nullptr
13#elif defined(__cplusplus)
12#define NULL 0L14#define NULL 0L
13#else15#else
14#define NULL ((void*)0)16#define NULL ((void*)0)
lib/libc/include/wasm-wasi-musl/netinet/in.h+1
...@@ -60,6 +60,7 @@ struct ipv6_mreq {...@@ -60,6 +60,7 @@ struct ipv6_mreq {
60#define INADDR_BROADCAST ((in_addr_t) 0xffffffff)60#define INADDR_BROADCAST ((in_addr_t) 0xffffffff)
61#define INADDR_NONE ((in_addr_t) 0xffffffff)61#define INADDR_NONE ((in_addr_t) 0xffffffff)
62#define INADDR_LOOPBACK ((in_addr_t) 0x7f000001)62#define INADDR_LOOPBACK ((in_addr_t) 0x7f000001)
63#define INADDR_DUMMY ((in_addr_t) 0xc0000008)
6364
64#define INADDR_UNSPEC_GROUP ((in_addr_t) 0xe0000000)65#define INADDR_UNSPEC_GROUP ((in_addr_t) 0xe0000000)
65#define INADDR_ALLHOSTS_GROUP ((in_addr_t) 0xe0000001)66#define INADDR_ALLHOSTS_GROUP ((in_addr_t) 0xe0000001)
lib/libc/include/wasm-wasi-musl/netinet/tcp.h+11
...@@ -80,6 +80,8 @@ enum {...@@ -80,6 +80,8 @@ enum {
80 TCP_NLA_SRTT,80 TCP_NLA_SRTT,
81 TCP_NLA_TIMEOUT_REHASH,81 TCP_NLA_TIMEOUT_REHASH,
82 TCP_NLA_BYTES_NOTSENT,82 TCP_NLA_BYTES_NOTSENT,
83 TCP_NLA_EDT,
84 TCP_NLA_TTL,
83};85};
8486
85#if defined(_GNU_SOURCE) || defined(_BSD_SOURCE)87#if defined(_GNU_SOURCE) || defined(_BSD_SOURCE)
...@@ -281,12 +283,21 @@ struct tcp_repair_window {...@@ -281,12 +283,21 @@ struct tcp_repair_window {
281 uint32_t rcv_wup;283 uint32_t rcv_wup;
282};284};
283285
286#define TCP_RECEIVE_ZEROCOPY_FLAG_TLB_CLEAN_HINT 0x1
287
284struct tcp_zerocopy_receive {288struct tcp_zerocopy_receive {
285 uint64_t address;289 uint64_t address;
286 uint32_t length;290 uint32_t length;
287 uint32_t recv_skip_hint;291 uint32_t recv_skip_hint;
288 uint32_t inq;292 uint32_t inq;
289 int32_t err;293 int32_t err;
294 uint64_t copybuf_address;
295 int32_t copybuf_len;
296 uint32_t flags;
297 uint64_t msg_control;
298 uint64_t msg_controllen;
299 uint32_t msg_flags;
300 uint32_t reserved;
290};301};
291302
292#endif303#endif
lib/libc/include/wasm-wasi-musl/signal.h+8
...@@ -82,6 +82,8 @@ typedef struct sigaltstack stack_t;...@@ -82,6 +82,8 @@ typedef struct sigaltstack stack_t;
82#define SEGV_ACCERR 282#define SEGV_ACCERR 2
83#define SEGV_BNDERR 383#define SEGV_BNDERR 3
84#define SEGV_PKUERR 484#define SEGV_PKUERR 4
85#define SEGV_MTEAERR 8
86#define SEGV_MTESERR 9
8587
86#define BUS_ADRALN 188#define BUS_ADRALN 1
87#define BUS_ADRERR 289#define BUS_ADRERR 2
...@@ -183,6 +185,9 @@ struct sigaction {...@@ -183,6 +185,9 @@ struct sigaction {
183#define sa_handler __sa_handler.sa_handler185#define sa_handler __sa_handler.sa_handler
184#define sa_sigaction __sa_handler.sa_sigaction186#define sa_sigaction __sa_handler.sa_sigaction
185187
188#define SA_UNSUPPORTED 0x00000400
189#define SA_EXPOSE_TAGBITS 0x00000800
190
186struct sigevent {191struct sigevent {
187 union sigval sigev_value;192 union sigval sigev_value;
188 int sigev_signo;193 int sigev_signo;
...@@ -277,6 +282,9 @@ void (*sigset(int, void (*)(int)))(int);...@@ -277,6 +282,9 @@ void (*sigset(int, void (*)(int)))(int);
277#if defined(_BSD_SOURCE) || defined(_GNU_SOURCE)282#if defined(_BSD_SOURCE) || defined(_GNU_SOURCE)
278#define NSIG _NSIG283#define NSIG _NSIG
279typedef void (*sig_t)(int);284typedef void (*sig_t)(int);
285
286#define SYS_SECCOMP 1
287#define SYS_USER_DISPATCH 2
280#endif288#endif
281289
282#ifdef _GNU_SOURCE290#ifdef _GNU_SOURCE
lib/libc/include/wasm-wasi-musl/stdc-predef.h+3
...@@ -7,4 +7,7 @@...@@ -7,4 +7,7 @@
7#define __STDC_IEC_559__ 17#define __STDC_IEC_559__ 1
8#endif8#endif
99
10#define __STDC_UTF_16__ 1
11#define __STDC_UTF_32__ 1
12
10#endif13#endif
lib/libc/include/wasm-wasi-musl/stdio.h+3-1
...@@ -28,7 +28,9 @@ extern "C" {...@@ -28,7 +28,9 @@ extern "C" {
28#include <bits/alltypes.h>28#include <bits/alltypes.h>
2929
30#ifdef __wasilibc_unmodified_upstream /* Use the compiler's definition of NULL */30#ifdef __wasilibc_unmodified_upstream /* Use the compiler's definition of NULL */
31#ifdef __cplusplus31#if __cplusplus >= 201103L
32#define NULL nullptr
33#elif defined(__cplusplus)
32#define NULL 0L34#define NULL 0L
33#else35#else
34#define NULL ((void*)0)36#define NULL ((void*)0)
lib/libc/include/wasm-wasi-musl/stdlib.h+4-1
...@@ -13,7 +13,9 @@ extern "C" {...@@ -13,7 +13,9 @@ extern "C" {
13#include <features.h>13#include <features.h>
1414
15#ifdef __wasilibc_unmodified_upstream /* Use the compiler's definition of NULL */15#ifdef __wasilibc_unmodified_upstream /* Use the compiler's definition of NULL */
16#ifdef __cplusplus16#if __cplusplus >= 201103L
17#define NULL nullptr
18#elif defined(__cplusplus)
17#define NULL 0L19#define NULL 0L
18#else20#else
19#define NULL ((void*)0)21#define NULL ((void*)0)
...@@ -171,6 +173,7 @@ int clearenv(void);...@@ -171,6 +173,7 @@ int clearenv(void);
171#define WCOREDUMP(s) ((s) & 0x80)173#define WCOREDUMP(s) ((s) & 0x80)
172#define WIFCONTINUED(s) ((s) == 0xffff)174#define WIFCONTINUED(s) ((s) == 0xffff)
173void *reallocarray (void *, size_t, size_t);175void *reallocarray (void *, size_t, size_t);
176void qsort_r (void *, size_t, size_t, int (*)(const void *, const void *, void *), void *);
174#endif177#endif
175#endif178#endif
176179
lib/libc/include/wasm-wasi-musl/string.h+3-1
...@@ -12,7 +12,9 @@ extern "C" {...@@ -12,7 +12,9 @@ extern "C" {
12#include <features.h>12#include <features.h>
1313
14#ifdef __wasilibc_unmodified_upstream /* Use the compiler's definition of NULL */14#ifdef __wasilibc_unmodified_upstream /* Use the compiler's definition of NULL */
15#ifdef __cplusplus15#if __cplusplus >= 201103L
16#define NULL nullptr
17#elif defined(__cplusplus)
16#define NULL 0L18#define NULL 0L
17#else19#else
18#define NULL ((void*)0)20#define NULL ((void*)0)
lib/libc/include/wasm-wasi-musl/sys/mman.h+1
...@@ -44,6 +44,7 @@ extern "C" {...@@ -44,6 +44,7 @@ extern "C" {
4444
45#define MAP_HUGE_SHIFT 2645#define MAP_HUGE_SHIFT 26
46#define MAP_HUGE_MASK 0x3f46#define MAP_HUGE_MASK 0x3f
47#define MAP_HUGE_16KB (14 << 26)
47#define MAP_HUGE_64KB (16 << 26)48#define MAP_HUGE_64KB (16 << 26)
48#define MAP_HUGE_512KB (19 << 26)49#define MAP_HUGE_512KB (19 << 26)
49#define MAP_HUGE_1MB (20 << 26)50#define MAP_HUGE_1MB (20 << 26)
lib/libc/include/wasm-wasi-musl/sys/socket.h+4-1
...@@ -298,6 +298,8 @@ struct linger {...@@ -298,6 +298,8 @@ struct linger {
298#define SCM_TXTIME SO_TXTIME298#define SCM_TXTIME SO_TXTIME
299#define SO_BINDTOIFINDEX 62299#define SO_BINDTOIFINDEX 62
300#define SO_DETACH_REUSEPORT_BPF 68300#define SO_DETACH_REUSEPORT_BPF 68
301#define SO_PREFER_BUSY_POLL 69
302#define SO_BUSY_POLL_BUDGET 70
301303
302#ifndef SOL_SOCKET304#ifndef SOL_SOCKET
303#define SOL_SOCKET 1305#define SOL_SOCKET 1
...@@ -404,9 +406,10 @@ int shutdown (int, int);...@@ -404,9 +406,10 @@ int shutdown (int, int);
404int bind (int, const struct sockaddr *, socklen_t);406int bind (int, const struct sockaddr *, socklen_t);
405int connect (int, const struct sockaddr *, socklen_t);407int connect (int, const struct sockaddr *, socklen_t);
406int listen (int, int);408int listen (int, int);
409#endif
410
407int accept (int, struct sockaddr *__restrict, socklen_t *__restrict);411int accept (int, struct sockaddr *__restrict, socklen_t *__restrict);
408int accept4(int, struct sockaddr *__restrict, socklen_t *__restrict, int);412int accept4(int, struct sockaddr *__restrict, socklen_t *__restrict, int);
409#endif
410413
411#ifdef __wasilibc_unmodified_upstream /* WASI has no getsockname/getpeername */414#ifdef __wasilibc_unmodified_upstream /* WASI has no getsockname/getpeername */
412int getsockname (int, struct sockaddr *__restrict, socklen_t *__restrict);415int getsockname (int, struct sockaddr *__restrict, socklen_t *__restrict);
lib/libc/include/wasm-wasi-musl/sys/time.h+2-2
...@@ -23,9 +23,7 @@ struct itimerval {...@@ -23,9 +23,7 @@ struct itimerval {
23int getitimer (int, struct itimerval *);23int getitimer (int, struct itimerval *);
24int setitimer (int, const struct itimerval *__restrict, struct itimerval *__restrict);24int setitimer (int, const struct itimerval *__restrict, struct itimerval *__restrict);
25#endif25#endif
26#ifdef __wasilibc_unmodified_upstream /* WASI libc doesn't build the legacy functions */
27int utimes (const char *, const struct timeval [2]);26int utimes (const char *, const struct timeval [2]);
28#endif
2927
30#if defined(_GNU_SOURCE) || defined(_BSD_SOURCE)28#if defined(_GNU_SOURCE) || defined(_BSD_SOURCE)
31struct timezone {29struct timezone {
...@@ -34,7 +32,9 @@ struct timezone {...@@ -34,7 +32,9 @@ struct timezone {
34};32};
35#ifdef __wasilibc_unmodified_upstream /* WASI libc doesn't build the legacy functions */33#ifdef __wasilibc_unmodified_upstream /* WASI libc doesn't build the legacy functions */
36int futimes(int, const struct timeval [2]);34int futimes(int, const struct timeval [2]);
35#endif
37int futimesat(int, const char *, const struct timeval [2]);36int futimesat(int, const char *, const struct timeval [2]);
37#ifdef __wasilibc_unmodified_upstream /* WASI libc doesn't build the legacy functions */
38int lutimes(const char *, const struct timeval [2]);38int lutimes(const char *, const struct timeval [2]);
39#endif39#endif
40#ifdef __wasilibc_unmodified_upstream /* WASI has no way to set the time */40#ifdef __wasilibc_unmodified_upstream /* WASI has no way to set the time */
lib/libc/include/wasm-wasi-musl/time.h+3-1
...@@ -8,7 +8,9 @@ extern "C" {...@@ -8,7 +8,9 @@ extern "C" {
8#include <features.h>8#include <features.h>
99
10#ifdef __wasilibc_unmodified_upstream /* Use the compiler's definition of NULL */10#ifdef __wasilibc_unmodified_upstream /* Use the compiler's definition of NULL */
11#ifdef __cplusplus11#if __cplusplus >= 201103L
12#define NULL nullptr
13#elif defined(__cplusplus)
12#define NULL 0L14#define NULL 0L
13#else15#else
14#define NULL ((void*)0)16#define NULL ((void*)0)
lib/libc/include/wasm-wasi-musl/unistd.h+7-1
...@@ -15,12 +15,16 @@ extern "C" {...@@ -15,12 +15,16 @@ extern "C" {
15#define SEEK_SET 015#define SEEK_SET 0
16#define SEEK_CUR 116#define SEEK_CUR 1
17#define SEEK_END 217#define SEEK_END 2
18#define SEEK_DATA 3
19#define SEEK_HOLE 4
18#else20#else
19#include <__header_unistd.h>21#include <__header_unistd.h>
20#endif22#endif
2123
22#ifdef __wasilibc_unmodified_upstream /* Use the compiler's definition of NULL */24#ifdef __wasilibc_unmodified_upstream /* Use the compiler's definition of NULL */
23#ifdef __cplusplus25#if __cplusplus >= 201103L
26#define NULL nullptr
27#elif defined(__cplusplus)
24#define NULL 0L28#define NULL 0L
25#else29#else
26#define NULL ((void*)0)30#define NULL ((void*)0)
...@@ -240,7 +244,9 @@ void *sbrk(intptr_t);...@@ -240,7 +244,9 @@ void *sbrk(intptr_t);
240pid_t vfork(void);244pid_t vfork(void);
241int vhangup(void);245int vhangup(void);
242int chroot(const char *);246int chroot(const char *);
247#endif
243int getpagesize(void);248int getpagesize(void);
249#ifdef __wasilibc_unmodified_upstream /* WASI has no processes */
244int getdtablesize(void);250int getdtablesize(void);
245int sethostname(const char *, size_t);251int sethostname(const char *, size_t);
246int getdomainname(char *, size_t);252int getdomainname(char *, size_t);
lib/libc/include/wasm-wasi-musl/wasi/api.h+49-214
...@@ -1,13 +1,9 @@...@@ -1,13 +1,9 @@
1/**1/**
2 * THIS FILE IS AUTO-GENERATED from the following files:2 * <wasi/api.h>. This file contains declarations describing the WASI ABI
3 * wasi_snapshot_preview1.witx3 * as of "snapshot preview1". It was originally auto-generated from
4 *4 * wasi_snapshot_preview1.witx, however WASI is in the process of
5 * To regenerate this file execute:5 * transitioning to a new IDL and header file generator, and this file
6 *6 * is temporarily being manually maintained.
7 * cargo run --manifest-path tools/wasi-headers/Cargo.toml generate-libc
8 *
9 * Modifications to this file will cause CI to fail, the code generator tool
10 * must be modified to change this file.
11 *7 *
12 * @file8 * @file
13 * This file describes the [WASI] interface, consisting of functions, types,9 * This file describes the [WASI] interface, consisting of functions, types,
...@@ -661,6 +657,11 @@ typedef uint64_t __wasi_rights_t;...@@ -661,6 +657,11 @@ typedef uint64_t __wasi_rights_t;
661 */657 */
662#define __WASI_RIGHTS_SOCK_SHUTDOWN ((__wasi_rights_t)(1 << 28))658#define __WASI_RIGHTS_SOCK_SHUTDOWN ((__wasi_rights_t)(1 << 28))
663659
660/**
661 * The right to invoke `sock_accept`.
662 */
663#define __WASI_RIGHTS_SOCK_ACCEPT ((__wasi_rights_t)(1 << 29))
664
664/**665/**
665 * A file descriptor handle.666 * A file descriptor handle.
666 */667 */
...@@ -1300,200 +1301,6 @@ typedef uint32_t __wasi_exitcode_t;...@@ -1300,200 +1301,6 @@ typedef uint32_t __wasi_exitcode_t;
1300_Static_assert(sizeof(__wasi_exitcode_t) == 4, "witx calculated size");1301_Static_assert(sizeof(__wasi_exitcode_t) == 4, "witx calculated size");
1301_Static_assert(_Alignof(__wasi_exitcode_t) == 4, "witx calculated align");1302_Static_assert(_Alignof(__wasi_exitcode_t) == 4, "witx calculated align");
13021303
1303/**
1304 * Signal condition.
1305 */
1306typedef uint8_t __wasi_signal_t;
1307
1308/**
1309 * No signal. Note that POSIX has special semantics for `kill(pid, 0)`,
1310 * so this value is reserved.
1311 */
1312#define __WASI_SIGNAL_NONE (UINT8_C(0))
1313
1314/**
1315 * Hangup.
1316 * Action: Terminates the process.
1317 */
1318#define __WASI_SIGNAL_HUP (UINT8_C(1))
1319
1320/**
1321 * Terminate interrupt signal.
1322 * Action: Terminates the process.
1323 */
1324#define __WASI_SIGNAL_INT (UINT8_C(2))
1325
1326/**
1327 * Terminal quit signal.
1328 * Action: Terminates the process.
1329 */
1330#define __WASI_SIGNAL_QUIT (UINT8_C(3))
1331
1332/**
1333 * Illegal instruction.
1334 * Action: Terminates the process.
1335 */
1336#define __WASI_SIGNAL_ILL (UINT8_C(4))
1337
1338/**
1339 * Trace/breakpoint trap.
1340 * Action: Terminates the process.
1341 */
1342#define __WASI_SIGNAL_TRAP (UINT8_C(5))
1343
1344/**
1345 * Process abort signal.
1346 * Action: Terminates the process.
1347 */
1348#define __WASI_SIGNAL_ABRT (UINT8_C(6))
1349
1350/**
1351 * Access to an undefined portion of a memory object.
1352 * Action: Terminates the process.
1353 */
1354#define __WASI_SIGNAL_BUS (UINT8_C(7))
1355
1356/**
1357 * Erroneous arithmetic operation.
1358 * Action: Terminates the process.
1359 */
1360#define __WASI_SIGNAL_FPE (UINT8_C(8))
1361
1362/**
1363 * Kill.
1364 * Action: Terminates the process.
1365 */
1366#define __WASI_SIGNAL_KILL (UINT8_C(9))
1367
1368/**
1369 * User-defined signal 1.
1370 * Action: Terminates the process.
1371 */
1372#define __WASI_SIGNAL_USR1 (UINT8_C(10))
1373
1374/**
1375 * Invalid memory reference.
1376 * Action: Terminates the process.
1377 */
1378#define __WASI_SIGNAL_SEGV (UINT8_C(11))
1379
1380/**
1381 * User-defined signal 2.
1382 * Action: Terminates the process.
1383 */
1384#define __WASI_SIGNAL_USR2 (UINT8_C(12))
1385
1386/**
1387 * Write on a pipe with no one to read it.
1388 * Action: Ignored.
1389 */
1390#define __WASI_SIGNAL_PIPE (UINT8_C(13))
1391
1392/**
1393 * Alarm clock.
1394 * Action: Terminates the process.
1395 */
1396#define __WASI_SIGNAL_ALRM (UINT8_C(14))
1397
1398/**
1399 * Termination signal.
1400 * Action: Terminates the process.
1401 */
1402#define __WASI_SIGNAL_TERM (UINT8_C(15))
1403
1404/**
1405 * Child process terminated, stopped, or continued.
1406 * Action: Ignored.
1407 */
1408#define __WASI_SIGNAL_CHLD (UINT8_C(16))
1409
1410/**
1411 * Continue executing, if stopped.
1412 * Action: Continues executing, if stopped.
1413 */
1414#define __WASI_SIGNAL_CONT (UINT8_C(17))
1415
1416/**
1417 * Stop executing.
1418 * Action: Stops executing.
1419 */
1420#define __WASI_SIGNAL_STOP (UINT8_C(18))
1421
1422/**
1423 * Terminal stop signal.
1424 * Action: Stops executing.
1425 */
1426#define __WASI_SIGNAL_TSTP (UINT8_C(19))
1427
1428/**
1429 * Background process attempting read.
1430 * Action: Stops executing.
1431 */
1432#define __WASI_SIGNAL_TTIN (UINT8_C(20))
1433
1434/**
1435 * Background process attempting write.
1436 * Action: Stops executing.
1437 */
1438#define __WASI_SIGNAL_TTOU (UINT8_C(21))
1439
1440/**
1441 * High bandwidth data is available at a socket.
1442 * Action: Ignored.
1443 */
1444#define __WASI_SIGNAL_URG (UINT8_C(22))
1445
1446/**
1447 * CPU time limit exceeded.
1448 * Action: Terminates the process.
1449 */
1450#define __WASI_SIGNAL_XCPU (UINT8_C(23))
1451
1452/**
1453 * File size limit exceeded.
1454 * Action: Terminates the process.
1455 */
1456#define __WASI_SIGNAL_XFSZ (UINT8_C(24))
1457
1458/**
1459 * Virtual timer expired.
1460 * Action: Terminates the process.
1461 */
1462#define __WASI_SIGNAL_VTALRM (UINT8_C(25))
1463
1464/**
1465 * Profiling timer expired.
1466 * Action: Terminates the process.
1467 */
1468#define __WASI_SIGNAL_PROF (UINT8_C(26))
1469
1470/**
1471 * Window changed.
1472 * Action: Ignored.
1473 */
1474#define __WASI_SIGNAL_WINCH (UINT8_C(27))
1475
1476/**
1477 * I/O possible.
1478 * Action: Terminates the process.
1479 */
1480#define __WASI_SIGNAL_POLL (UINT8_C(28))
1481
1482/**
1483 * Power failure.
1484 * Action: Terminates the process.
1485 */
1486#define __WASI_SIGNAL_PWR (UINT8_C(29))
1487
1488/**
1489 * Bad system call.
1490 * Action: Terminates the process.
1491 */
1492#define __WASI_SIGNAL_SYS (UINT8_C(30))
1493
1494_Static_assert(sizeof(__wasi_signal_t) == 1, "witx calculated size");
1495_Static_assert(_Alignof(__wasi_signal_t) == 1, "witx calculated align");
1496
1497/**1304/**
1498 * Flags provided to `sock_recv`.1305 * Flags provided to `sock_recv`.
1499 */1306 */
...@@ -1592,7 +1399,8 @@ _Static_assert(_Alignof(__wasi_prestat_t) == 4, "witx calculated align");...@@ -1592,7 +1399,8 @@ _Static_assert(_Alignof(__wasi_prestat_t) == 4, "witx calculated align");
15921399
1593/**1400/**
1594 * Read command-line argument data.1401 * Read command-line argument data.
1595 * The size of the array should match that returned by `args_sizes_get`1402 * The size of the array should match that returned by `args_sizes_get`.
1403 * Each argument is expected to be `\0` terminated.
1596 */1404 */
1597__wasi_errno_t __wasi_args_get(1405__wasi_errno_t __wasi_args_get(
1598 uint8_t * * argv,1406 uint8_t * * argv,
...@@ -1611,6 +1419,7 @@ __wasi_errno_t __wasi_args_sizes_get(...@@ -1611,6 +1419,7 @@ __wasi_errno_t __wasi_args_sizes_get(
1611/**1419/**
1612 * Read environment variable data.1420 * Read environment variable data.
1613 * The sizes of the buffers should match that returned by `environ_sizes_get`.1421 * The sizes of the buffers should match that returned by `environ_sizes_get`.
1422 * Key/value pairs are expected to be joined with `=`s, and terminated with `\0`s.
1614 */1423 */
1615__wasi_errno_t __wasi_environ_get(1424__wasi_errno_t __wasi_environ_get(
1616 uint8_t * * environ,1425 uint8_t * * environ,
...@@ -2181,16 +1990,6 @@ _Noreturn void __wasi_proc_exit(...@@ -2181,16 +1990,6 @@ _Noreturn void __wasi_proc_exit(
2181 */1990 */
2182 __wasi_exitcode_t rval1991 __wasi_exitcode_t rval
2183);1992);
2184/**
2185 * Send a signal to the process of the calling thread.
2186 * Note: This is similar to `raise` in POSIX.
2187 */
2188__wasi_errno_t __wasi_proc_raise(
2189 /**
2190 * The signal condition to trigger.
2191 */
2192 __wasi_signal_t sig
2193) __attribute__((__warn_unused_result__));
2194/**1993/**
2195 * Temporarily yield execution of the calling thread.1994 * Temporarily yield execution of the calling thread.
2196 * Note: This is similar to `sched_yield` in POSIX.1995 * Note: This is similar to `sched_yield` in POSIX.
...@@ -2213,6 +2012,23 @@ __wasi_errno_t __wasi_random_get(...@@ -2213,6 +2012,23 @@ __wasi_errno_t __wasi_random_get(
2213 uint8_t * buf,2012 uint8_t * buf,
2214 __wasi_size_t buf_len2013 __wasi_size_t buf_len
2215) __attribute__((__warn_unused_result__));2014) __attribute__((__warn_unused_result__));
2015/**
2016 * Accept a new incoming connection.
2017 * Note: This is similar to `accept` in POSIX.
2018 * @return
2019 * New socket connection
2020 */
2021__wasi_errno_t __wasi_sock_accept(
2022 /**
2023 * The listening socket.
2024 */
2025 __wasi_fd_t fd,
2026 /**
2027 * The desired values of the file descriptor flags.
2028 */
2029 __wasi_fdflags_t flags,
2030 __wasi_fd_t *retptr0
2031) __attribute__((__warn_unused_result__));
2216/**2032/**
2217 * Receive a message from a socket.2033 * Receive a message from a socket.
2218 * Note: This is similar to `recv` in POSIX, though it also supports reading2034 * Note: This is similar to `recv` in POSIX, though it also supports reading
...@@ -2273,6 +2089,25 @@ __wasi_errno_t __wasi_sock_shutdown(...@@ -2273,6 +2089,25 @@ __wasi_errno_t __wasi_sock_shutdown(
2273) __attribute__((__warn_unused_result__));2089) __attribute__((__warn_unused_result__));
2274/** @} */2090/** @} */
22752091
2092#ifdef _REENTRANT
2093/**
2094 * Request a new thread to be created by the host.
2095 *
2096 * The host will create a new instance of the current module sharing its
2097 * memory, find an exported entry function--`wasi_thread_start`--, and call the
2098 * entry function with `start_arg` in the new thread.
2099 *
2100 * @see https://github.com/WebAssembly/wasi-threads/#readme
2101 */
2102__wasi_errno_t __wasi_thread_spawn(
2103 /**
2104 * A pointer to an opaque struct to be passed to the module's entry
2105 * function.
2106 */
2107 void *start_arg
2108) __attribute__((__warn_unused_result__));
2109#endif
2110
2276#ifdef __cplusplus2111#ifdef __cplusplus
2277}2112}
2278#endif2113#endif
lib/libc/include/wasm-wasi-musl/wasi/libc-environ.h+17
...@@ -1,6 +1,10 @@...@@ -1,6 +1,10 @@
1#ifndef __wasi_libc_environ_h1#ifndef __wasi_libc_environ_h
2#define __wasi_libc_environ_h2#define __wasi_libc_environ_h
33
4/// This header file is a WASI-libc-specific interface, and is not needed by
5/// most programs. Most programs should just use the standard `getenv` and
6/// related APIs, which take care of all of the details automatically.
7
4#ifdef __cplusplus8#ifdef __cplusplus
5extern "C" {9extern "C" {
6#endif10#endif
...@@ -12,6 +16,19 @@ void __wasilibc_initialize_environ(void);...@@ -12,6 +16,19 @@ void __wasilibc_initialize_environ(void);
12/// If `__wasilibc_initialize_environ` has not yet been called, call it.16/// If `__wasilibc_initialize_environ` has not yet been called, call it.
13void __wasilibc_ensure_environ(void);17void __wasilibc_ensure_environ(void);
1418
19/// De-initialize the global environment variable state, so that subsequent
20/// calls to `__wasilibc_ensure_environ` call `__wasilibc_initialize_environ`.
21void __wasilibc_deinitialize_environ(void);
22
23/// Call `__wasilibc_initialize_environ` only if `environ` and `_environ` are
24/// referenced in the program.
25void __wasilibc_maybe_reinitialize_environ_eagerly(void);
26
27/// Return the value of the `environ` variable. Using `environ` directly
28/// requires eager initialization of the environment variables. Using this
29/// function instead of `environ` allows initialization to happen lazily.
30char **__wasilibc_get_environ(void);
31
15#ifdef __cplusplus32#ifdef __cplusplus
16}33}
17#endif34#endif
lib/libc/include/wasm-wasi-musl/wasi/libc-find-relpath.h+1-1
...@@ -70,7 +70,7 @@ int __wasilibc_find_relpath_alloc(...@@ -70,7 +70,7 @@ int __wasilibc_find_relpath_alloc(
70 char **relative,70 char **relative,
71 size_t *relative_len,71 size_t *relative_len,
72 int can_realloc72 int can_realloc
73) __attribute__((weak));73) __attribute__((__weak__));
7474
75#ifdef __cplusplus75#ifdef __cplusplus
76}76}
lib/libc/include/wasm-wasi-musl/wchar.h+3-1
...@@ -41,7 +41,9 @@ extern "C" {...@@ -41,7 +41,9 @@ extern "C" {
41#endif41#endif
4242
43#ifdef __wasilibc_unmodified_upstream /* Use the compiler's definition of NULL */43#ifdef __wasilibc_unmodified_upstream /* Use the compiler's definition of NULL */
44#ifdef __cplusplus44#if __cplusplus >= 201103L
45#define NULL nullptr
46#elif defined(__cplusplus)
45#define NULL 0L47#define NULL 0L
46#else48#else
47#define NULL ((void*)0)49#define NULL ((void*)0)
lib/libc/wasi/LICENSE+1
...@@ -7,6 +7,7 @@ Portions of this software are derived from third-party works covered by...@@ -7,6 +7,7 @@ Portions of this software are derived from third-party works covered by
7their own licenses:7their own licenses:
88
9dlmalloc/ - CC0; see the notice in malloc.c for details9dlmalloc/ - CC0; see the notice in malloc.c for details
10emmalloc/ - MIT; see the notice in emmalloc.c for details
10libc-bottom-half/cloudlibc/ - BSD-2-Clause; see the LICENSE file for details11libc-bottom-half/cloudlibc/ - BSD-2-Clause; see the LICENSE file for details
11libc-top-half/musl/ - MIT; see the COPYRIGHT file for details12libc-top-half/musl/ - MIT; see the COPYRIGHT file for details
1213
lib/libc/wasi/dlmalloc/include/unistd.h deleted-10
...@@ -1,10 +0,0 @@
1/* Stub include file to support dlmalloc. */
2
3#include <stdint.h>
4#include <__macro_PAGESIZE.h>
5
6#define sysconf(name) PAGESIZE
7#define _SC_PAGESIZE
8
9/* Declare sbrk. */
10void *sbrk(intptr_t increment) __attribute__((__warn_unused_result__));
lib/libc/wasi/dlmalloc/src/dlmalloc.c deleted-98
...@@ -1,98 +0,0 @@
1// This file is a wrapper around malloc.c, which is the upstream source file.
2// It sets configuration flags and controls which symbols are exported.
3
4#include <stddef.h>
5#include <malloc.h>
6
7// Define configuration macros for dlmalloc.
8
9// WebAssembly doesn't have mmap-style memory allocation.
10#define HAVE_MMAP 0
11
12// WebAssembly doesn't support shrinking linear memory.
13#define MORECORE_CANNOT_TRIM 1
14
15// Disable sanity checks to reduce code size.
16#define ABORT __builtin_unreachable()
17
18// If threads are enabled, enable support for threads.
19#ifdef _REENTRANT
20#define USE_LOCKS 1
21#endif
22
23// Make malloc deterministic.
24#define LACKS_TIME_H 1
25
26// Disable malloc statistics generation to reduce code size.
27#define NO_MALLINFO 1
28#define NO_MALLOC_STATS 1
29
30// Align malloc regions to 16, to avoid unaligned SIMD accesses.
31#define MALLOC_ALIGNMENT 16
32
33// Declare errno values used by dlmalloc. We define them like this to avoid
34// putting specific errno values in the ABI.
35extern const int __ENOMEM;
36#define ENOMEM __ENOMEM
37extern const int __EINVAL;
38#define EINVAL __EINVAL
39
40// Define USE_DL_PREFIX so that we leave dlmalloc's names prefixed with 'dl'.
41// We define them as "static", and we wrap them with public names below. This
42// serves two purposes:
43//
44// One is to make it easy to control which symbols are exported; dlmalloc
45// defines several non-standard functions and we wish to explicitly control
46// which functions are part of our public-facing interface.
47//
48// The other is to protect against compilers optimizing based on the assumption
49// that they know what functions with names like "malloc" do. Code in the
50// implementation will call functions like "dlmalloc" and assume it can use
51// the resulting pointers to access the metadata outside of the nominally
52// allocated objects. However, if the function were named "malloc", compilers
53// might see code like that and assume it has undefined behavior and can be
54// optimized away. By using "dlmalloc" in the implementation, we don't need
55// -fno-builtin to avoid this problem.
56#define USE_DL_PREFIX 1
57#define DLMALLOC_EXPORT static inline
58
59// This isn't declared with DLMALLOC_EXPORT so make it static explicitly.
60static size_t dlmalloc_usable_size(void*);
61
62// Include the upstream dlmalloc's malloc.c.
63#include "malloc.c"
64
65// Export the public names.
66
67void *malloc(size_t size) {
68 return dlmalloc(size);
69}
70
71void free(void *ptr) {
72 dlfree(ptr);
73}
74
75void *calloc(size_t nmemb, size_t size) {
76 return dlcalloc(nmemb, size);
77}
78
79void *realloc(void *ptr, size_t size) {
80 return dlrealloc(ptr, size);
81}
82
83int posix_memalign(void **memptr, size_t alignment, size_t size) {
84 return dlposix_memalign(memptr, alignment, size);
85}
86
87void* aligned_alloc(size_t alignment, size_t bytes) {
88 return dlmemalign(alignment, bytes);
89}
90
91size_t malloc_usable_size(void *ptr) {
92 return dlmalloc_usable_size(ptr);
93}
94
95// Define these to satisfy musl references.
96void *__libc_malloc(size_t) __attribute__((alias("malloc")));
97void __libc_free(void *) __attribute__((alias("free")));
98void *__libc_calloc(size_t nmemb, size_t size) __attribute__((alias("calloc")));
lib/libc/wasi/dlmalloc/src/malloc.c deleted-6352
...@@ -1,6352 +0,0 @@
1/*
2 This is a version (aka dlmalloc) of malloc/free/realloc written by
3 Doug Lea and released to the public domain, as explained at
4 http://creativecommons.org/publicdomain/zero/1.0/ Send questions,
5 comments, complaints, performance data, etc to dl@cs.oswego.edu
6
7* Version 2.8.6 Wed Aug 29 06:57:58 2012 Doug Lea
8 Note: There may be an updated version of this malloc obtainable at
9 ftp://gee.cs.oswego.edu/pub/misc/malloc.c
10 Check before installing!
11
12* Quickstart
13
14 This library is all in one file to simplify the most common usage:
15 ftp it, compile it (-O3), and link it into another program. All of
16 the compile-time options default to reasonable values for use on
17 most platforms. You might later want to step through various
18 compile-time and dynamic tuning options.
19
20 For convenience, an include file for code using this malloc is at:
21 ftp://gee.cs.oswego.edu/pub/misc/malloc-2.8.6.h
22 You don't really need this .h file unless you call functions not
23 defined in your system include files. The .h file contains only the
24 excerpts from this file needed for using this malloc on ANSI C/C++
25 systems, so long as you haven't changed compile-time options about
26 naming and tuning parameters. If you do, then you can create your
27 own malloc.h that does include all settings by cutting at the point
28 indicated below. Note that you may already by default be using a C
29 library containing a malloc that is based on some version of this
30 malloc (for example in linux). You might still want to use the one
31 in this file to customize settings or to avoid overheads associated
32 with library versions.
33
34* Vital statistics:
35
36 Supported pointer/size_t representation: 4 or 8 bytes
37 size_t MUST be an unsigned type of the same width as
38 pointers. (If you are using an ancient system that declares
39 size_t as a signed type, or need it to be a different width
40 than pointers, you can use a previous release of this malloc
41 (e.g. 2.7.2) supporting these.)
42
43 Alignment: 8 bytes (minimum)
44 This suffices for nearly all current machines and C compilers.
45 However, you can define MALLOC_ALIGNMENT to be wider than this
46 if necessary (up to 128bytes), at the expense of using more space.
47
48 Minimum overhead per allocated chunk: 4 or 8 bytes (if 4byte sizes)
49 8 or 16 bytes (if 8byte sizes)
50 Each malloced chunk has a hidden word of overhead holding size
51 and status information, and additional cross-check word
52 if FOOTERS is defined.
53
54 Minimum allocated size: 4-byte ptrs: 16 bytes (including overhead)
55 8-byte ptrs: 32 bytes (including overhead)
56
57 Even a request for zero bytes (i.e., malloc(0)) returns a
58 pointer to something of the minimum allocatable size.
59 The maximum overhead wastage (i.e., number of extra bytes
60 allocated than were requested in malloc) is less than or equal
61 to the minimum size, except for requests >= mmap_threshold that
62 are serviced via mmap(), where the worst case wastage is about
63 32 bytes plus the remainder from a system page (the minimal
64 mmap unit); typically 4096 or 8192 bytes.
65
66 Security: static-safe; optionally more or less
67 The "security" of malloc refers to the ability of malicious
68 code to accentuate the effects of errors (for example, freeing
69 space that is not currently malloc'ed or overwriting past the
70 ends of chunks) in code that calls malloc. This malloc
71 guarantees not to modify any memory locations below the base of
72 heap, i.e., static variables, even in the presence of usage
73 errors. The routines additionally detect most improper frees
74 and reallocs. All this holds as long as the static bookkeeping
75 for malloc itself is not corrupted by some other means. This
76 is only one aspect of security -- these checks do not, and
77 cannot, detect all possible programming errors.
78
79 If FOOTERS is defined nonzero, then each allocated chunk
80 carries an additional check word to verify that it was malloced
81 from its space. These check words are the same within each
82 execution of a program using malloc, but differ across
83 executions, so externally crafted fake chunks cannot be
84 freed. This improves security by rejecting frees/reallocs that
85 could corrupt heap memory, in addition to the checks preventing
86 writes to statics that are always on. This may further improve
87 security at the expense of time and space overhead. (Note that
88 FOOTERS may also be worth using with MSPACES.)
89
90 By default detected errors cause the program to abort (calling
91 "abort()"). You can override this to instead proceed past
92 errors by defining PROCEED_ON_ERROR. In this case, a bad free
93 has no effect, and a malloc that encounters a bad address
94 caused by user overwrites will ignore the bad address by
95 dropping pointers and indices to all known memory. This may
96 be appropriate for programs that should continue if at all
97 possible in the face of programming errors, although they may
98 run out of memory because dropped memory is never reclaimed.
99
100 If you don't like either of these options, you can define
101 CORRUPTION_ERROR_ACTION and USAGE_ERROR_ACTION to do anything
102 else. And if if you are sure that your program using malloc has
103 no errors or vulnerabilities, you can define INSECURE to 1,
104 which might (or might not) provide a small performance improvement.
105
106 It is also possible to limit the maximum total allocatable
107 space, using malloc_set_footprint_limit. This is not
108 designed as a security feature in itself (calls to set limits
109 are not screened or privileged), but may be useful as one
110 aspect of a secure implementation.
111
112 Thread-safety: NOT thread-safe unless USE_LOCKS defined non-zero
113 When USE_LOCKS is defined, each public call to malloc, free,
114 etc is surrounded with a lock. By default, this uses a plain
115 pthread mutex, win32 critical section, or a spin-lock if if
116 available for the platform and not disabled by setting
117 USE_SPIN_LOCKS=0. However, if USE_RECURSIVE_LOCKS is defined,
118 recursive versions are used instead (which are not required for
119 base functionality but may be needed in layered extensions).
120 Using a global lock is not especially fast, and can be a major
121 bottleneck. It is designed only to provide minimal protection
122 in concurrent environments, and to provide a basis for
123 extensions. If you are using malloc in a concurrent program,
124 consider instead using nedmalloc
125 (http://www.nedprod.com/programs/portable/nedmalloc/) or
126 ptmalloc (See http://www.malloc.de), which are derived from
127 versions of this malloc.
128
129 System requirements: Any combination of MORECORE and/or MMAP/MUNMAP
130 This malloc can use unix sbrk or any emulation (invoked using
131 the CALL_MORECORE macro) and/or mmap/munmap or any emulation
132 (invoked using CALL_MMAP/CALL_MUNMAP) to get and release system
133 memory. On most unix systems, it tends to work best if both
134 MORECORE and MMAP are enabled. On Win32, it uses emulations
135 based on VirtualAlloc. It also uses common C library functions
136 like memset.
137
138 Compliance: I believe it is compliant with the Single Unix Specification
139 (See http://www.unix.org). Also SVID/XPG, ANSI C, and probably
140 others as well.
141
142* Overview of algorithms
143
144 This is not the fastest, most space-conserving, most portable, or
145 most tunable malloc ever written. However it is among the fastest
146 while also being among the most space-conserving, portable and
147 tunable. Consistent balance across these factors results in a good
148 general-purpose allocator for malloc-intensive programs.
149
150 In most ways, this malloc is a best-fit allocator. Generally, it
151 chooses the best-fitting existing chunk for a request, with ties
152 broken in approximately least-recently-used order. (This strategy
153 normally maintains low fragmentation.) However, for requests less
154 than 256bytes, it deviates from best-fit when there is not an
155 exactly fitting available chunk by preferring to use space adjacent
156 to that used for the previous small request, as well as by breaking
157 ties in approximately most-recently-used order. (These enhance
158 locality of series of small allocations.) And for very large requests
159 (>= 256Kb by default), it relies on system memory mapping
160 facilities, if supported. (This helps avoid carrying around and
161 possibly fragmenting memory used only for large chunks.)
162
163 All operations (except malloc_stats and mallinfo) have execution
164 times that are bounded by a constant factor of the number of bits in
165 a size_t, not counting any clearing in calloc or copying in realloc,
166 or actions surrounding MORECORE and MMAP that have times
167 proportional to the number of non-contiguous regions returned by
168 system allocation routines, which is often just 1. In real-time
169 applications, you can optionally suppress segment traversals using
170 NO_SEGMENT_TRAVERSAL, which assures bounded execution even when
171 system allocators return non-contiguous spaces, at the typical
172 expense of carrying around more memory and increased fragmentation.
173
174 The implementation is not very modular and seriously overuses
175 macros. Perhaps someday all C compilers will do as good a job
176 inlining modular code as can now be done by brute-force expansion,
177 but now, enough of them seem not to.
178
179 Some compilers issue a lot of warnings about code that is
180 dead/unreachable only on some platforms, and also about intentional
181 uses of negation on unsigned types. All known cases of each can be
182 ignored.
183
184 For a longer but out of date high-level description, see
185 http://gee.cs.oswego.edu/dl/html/malloc.html
186
187* MSPACES
188 If MSPACES is defined, then in addition to malloc, free, etc.,
189 this file also defines mspace_malloc, mspace_free, etc. These
190 are versions of malloc routines that take an "mspace" argument
191 obtained using create_mspace, to control all internal bookkeeping.
192 If ONLY_MSPACES is defined, only these versions are compiled.
193 So if you would like to use this allocator for only some allocations,
194 and your system malloc for others, you can compile with
195 ONLY_MSPACES and then do something like...
196 static mspace mymspace = create_mspace(0,0); // for example
197 #define mymalloc(bytes) mspace_malloc(mymspace, bytes)
198
199 (Note: If you only need one instance of an mspace, you can instead
200 use "USE_DL_PREFIX" to relabel the global malloc.)
201
202 You can similarly create thread-local allocators by storing
203 mspaces as thread-locals. For example:
204 static __thread mspace tlms = 0;
205 void* tlmalloc(size_t bytes) {
206 if (tlms == 0) tlms = create_mspace(0, 0);
207 return mspace_malloc(tlms, bytes);
208 }
209 void tlfree(void* mem) { mspace_free(tlms, mem); }
210
211 Unless FOOTERS is defined, each mspace is completely independent.
212 You cannot allocate from one and free to another (although
213 conformance is only weakly checked, so usage errors are not always
214 caught). If FOOTERS is defined, then each chunk carries around a tag
215 indicating its originating mspace, and frees are directed to their
216 originating spaces. Normally, this requires use of locks.
217
218 ------------------------- Compile-time options ---------------------------
219
220Be careful in setting #define values for numerical constants of type
221size_t. On some systems, literal values are not automatically extended
222to size_t precision unless they are explicitly casted. You can also
223use the symbolic values MAX_SIZE_T, SIZE_T_ONE, etc below.
224
225WIN32 default: defined if _WIN32 defined
226 Defining WIN32 sets up defaults for MS environment and compilers.
227 Otherwise defaults are for unix. Beware that there seem to be some
228 cases where this malloc might not be a pure drop-in replacement for
229 Win32 malloc: Random-looking failures from Win32 GDI API's (eg;
230 SetDIBits()) may be due to bugs in some video driver implementations
231 when pixel buffers are malloc()ed, and the region spans more than
232 one VirtualAlloc()ed region. Because dlmalloc uses a small (64Kb)
233 default granularity, pixel buffers may straddle virtual allocation
234 regions more often than when using the Microsoft allocator. You can
235 avoid this by using VirtualAlloc() and VirtualFree() for all pixel
236 buffers rather than using malloc(). If this is not possible,
237 recompile this malloc with a larger DEFAULT_GRANULARITY. Note:
238 in cases where MSC and gcc (cygwin) are known to differ on WIN32,
239 conditions use _MSC_VER to distinguish them.
240
241DLMALLOC_EXPORT default: extern
242 Defines how public APIs are declared. If you want to export via a
243 Windows DLL, you might define this as
244 #define DLMALLOC_EXPORT extern __declspec(dllexport)
245 If you want a POSIX ELF shared object, you might use
246 #define DLMALLOC_EXPORT extern __attribute__((visibility("default")))
247
248MALLOC_ALIGNMENT default: (size_t)(2 * sizeof(void *))
249 Controls the minimum alignment for malloc'ed chunks. It must be a
250 power of two and at least 8, even on machines for which smaller
251 alignments would suffice. It may be defined as larger than this
252 though. Note however that code and data structures are optimized for
253 the case of 8-byte alignment.
254
255MSPACES default: 0 (false)
256 If true, compile in support for independent allocation spaces.
257 This is only supported if HAVE_MMAP is true.
258
259ONLY_MSPACES default: 0 (false)
260 If true, only compile in mspace versions, not regular versions.
261
262USE_LOCKS default: 0 (false)
263 Causes each call to each public routine to be surrounded with
264 pthread or WIN32 mutex lock/unlock. (If set true, this can be
265 overridden on a per-mspace basis for mspace versions.) If set to a
266 non-zero value other than 1, locks are used, but their
267 implementation is left out, so lock functions must be supplied manually,
268 as described below.
269
270USE_SPIN_LOCKS default: 1 iff USE_LOCKS and spin locks available
271 If true, uses custom spin locks for locking. This is currently
272 supported only gcc >= 4.1, older gccs on x86 platforms, and recent
273 MS compilers. Otherwise, posix locks or win32 critical sections are
274 used.
275
276USE_RECURSIVE_LOCKS default: not defined
277 If defined nonzero, uses recursive (aka reentrant) locks, otherwise
278 uses plain mutexes. This is not required for malloc proper, but may
279 be needed for layered allocators such as nedmalloc.
280
281LOCK_AT_FORK default: not defined
282 If defined nonzero, performs pthread_atfork upon initialization
283 to initialize child lock while holding parent lock. The implementation
284 assumes that pthread locks (not custom locks) are being used. In other
285 cases, you may need to customize the implementation.
286
287FOOTERS default: 0
288 If true, provide extra checking and dispatching by placing
289 information in the footers of allocated chunks. This adds
290 space and time overhead.
291
292INSECURE default: 0
293 If true, omit checks for usage errors and heap space overwrites.
294
295USE_DL_PREFIX default: NOT defined
296 Causes compiler to prefix all public routines with the string 'dl'.
297 This can be useful when you only want to use this malloc in one part
298 of a program, using your regular system malloc elsewhere.
299
300MALLOC_INSPECT_ALL default: NOT defined
301 If defined, compiles malloc_inspect_all and mspace_inspect_all, that
302 perform traversal of all heap space. Unless access to these
303 functions is otherwise restricted, you probably do not want to
304 include them in secure implementations.
305
306ABORT default: defined as abort()
307 Defines how to abort on failed checks. On most systems, a failed
308 check cannot die with an "assert" or even print an informative
309 message, because the underlying print routines in turn call malloc,
310 which will fail again. Generally, the best policy is to simply call
311 abort(). It's not very useful to do more than this because many
312 errors due to overwriting will show up as address faults (null, odd
313 addresses etc) rather than malloc-triggered checks, so will also
314 abort. Also, most compilers know that abort() does not return, so
315 can better optimize code conditionally calling it.
316
317PROCEED_ON_ERROR default: defined as 0 (false)
318 Controls whether detected bad addresses cause them to bypassed
319 rather than aborting. If set, detected bad arguments to free and
320 realloc are ignored. And all bookkeeping information is zeroed out
321 upon a detected overwrite of freed heap space, thus losing the
322 ability to ever return it from malloc again, but enabling the
323 application to proceed. If PROCEED_ON_ERROR is defined, the
324 static variable malloc_corruption_error_count is compiled in
325 and can be examined to see if errors have occurred. This option
326 generates slower code than the default abort policy.
327
328DEBUG default: NOT defined
329 The DEBUG setting is mainly intended for people trying to modify
330 this code or diagnose problems when porting to new platforms.
331 However, it may also be able to better isolate user errors than just
332 using runtime checks. The assertions in the check routines spell
333 out in more detail the assumptions and invariants underlying the
334 algorithms. The checking is fairly extensive, and will slow down
335 execution noticeably. Calling malloc_stats or mallinfo with DEBUG
336 set will attempt to check every non-mmapped allocated and free chunk
337 in the course of computing the summaries.
338
339ABORT_ON_ASSERT_FAILURE default: defined as 1 (true)
340 Debugging assertion failures can be nearly impossible if your
341 version of the assert macro causes malloc to be called, which will
342 lead to a cascade of further failures, blowing the runtime stack.
343 ABORT_ON_ASSERT_FAILURE cause assertions failures to call abort(),
344 which will usually make debugging easier.
345
346MALLOC_FAILURE_ACTION default: sets errno to ENOMEM, or no-op on win32
347 The action to take before "return 0" when malloc fails to be able to
348 return memory because there is none available.
349
350HAVE_MORECORE default: 1 (true) unless win32 or ONLY_MSPACES
351 True if this system supports sbrk or an emulation of it.
352
353MORECORE default: sbrk
354 The name of the sbrk-style system routine to call to obtain more
355 memory. See below for guidance on writing custom MORECORE
356 functions. The type of the argument to sbrk/MORECORE varies across
357 systems. It cannot be size_t, because it supports negative
358 arguments, so it is normally the signed type of the same width as
359 size_t (sometimes declared as "intptr_t"). It doesn't much matter
360 though. Internally, we only call it with arguments less than half
361 the max value of a size_t, which should work across all reasonable
362 possibilities, although sometimes generating compiler warnings.
363
364MORECORE_CONTIGUOUS default: 1 (true) if HAVE_MORECORE
365 If true, take advantage of fact that consecutive calls to MORECORE
366 with positive arguments always return contiguous increasing
367 addresses. This is true of unix sbrk. It does not hurt too much to
368 set it true anyway, since malloc copes with non-contiguities.
369 Setting it false when definitely non-contiguous saves time
370 and possibly wasted space it would take to discover this though.
371
372MORECORE_CANNOT_TRIM default: NOT defined
373 True if MORECORE cannot release space back to the system when given
374 negative arguments. This is generally necessary only if you are
375 using a hand-crafted MORECORE function that cannot handle negative
376 arguments.
377
378NO_SEGMENT_TRAVERSAL default: 0
379 If non-zero, suppresses traversals of memory segments
380 returned by either MORECORE or CALL_MMAP. This disables
381 merging of segments that are contiguous, and selectively
382 releasing them to the OS if unused, but bounds execution times.
383
384HAVE_MMAP default: 1 (true)
385 True if this system supports mmap or an emulation of it. If so, and
386 HAVE_MORECORE is not true, MMAP is used for all system
387 allocation. If set and HAVE_MORECORE is true as well, MMAP is
388 primarily used to directly allocate very large blocks. It is also
389 used as a backup strategy in cases where MORECORE fails to provide
390 space from system. Note: A single call to MUNMAP is assumed to be
391 able to unmap memory that may have be allocated using multiple calls
392 to MMAP, so long as they are adjacent.
393
394HAVE_MREMAP default: 1 on linux, else 0
395 If true realloc() uses mremap() to re-allocate large blocks and
396 extend or shrink allocation spaces.
397
398MMAP_CLEARS default: 1 except on WINCE.
399 True if mmap clears memory so calloc doesn't need to. This is true
400 for standard unix mmap using /dev/zero and on WIN32 except for WINCE.
401
402USE_BUILTIN_FFS default: 0 (i.e., not used)
403 Causes malloc to use the builtin ffs() function to compute indices.
404 Some compilers may recognize and intrinsify ffs to be faster than the
405 supplied C version. Also, the case of x86 using gcc is special-cased
406 to an asm instruction, so is already as fast as it can be, and so
407 this setting has no effect. Similarly for Win32 under recent MS compilers.
408 (On most x86s, the asm version is only slightly faster than the C version.)
409
410malloc_getpagesize default: derive from system includes, or 4096.
411 The system page size. To the extent possible, this malloc manages
412 memory from the system in page-size units. This may be (and
413 usually is) a function rather than a constant. This is ignored
414 if WIN32, where page size is determined using getSystemInfo during
415 initialization.
416
417USE_DEV_RANDOM default: 0 (i.e., not used)
418 Causes malloc to use /dev/random to initialize secure magic seed for
419 stamping footers. Otherwise, the current time is used.
420
421NO_MALLINFO default: 0
422 If defined, don't compile "mallinfo". This can be a simple way
423 of dealing with mismatches between system declarations and
424 those in this file.
425
426MALLINFO_FIELD_TYPE default: size_t
427 The type of the fields in the mallinfo struct. This was originally
428 defined as "int" in SVID etc, but is more usefully defined as
429 size_t. The value is used only if HAVE_USR_INCLUDE_MALLOC_H is not set
430
431NO_MALLOC_STATS default: 0
432 If defined, don't compile "malloc_stats". This avoids calls to
433 fprintf and bringing in stdio dependencies you might not want.
434
435REALLOC_ZERO_BYTES_FREES default: not defined
436 This should be set if a call to realloc with zero bytes should
437 be the same as a call to free. Some people think it should. Otherwise,
438 since this malloc returns a unique pointer for malloc(0), so does
439 realloc(p, 0).
440
441LACKS_UNISTD_H, LACKS_FCNTL_H, LACKS_SYS_PARAM_H, LACKS_SYS_MMAN_H
442LACKS_STRINGS_H, LACKS_STRING_H, LACKS_SYS_TYPES_H, LACKS_ERRNO_H
443LACKS_STDLIB_H LACKS_SCHED_H LACKS_TIME_H default: NOT defined unless on WIN32
444 Define these if your system does not have these header files.
445 You might need to manually insert some of the declarations they provide.
446
447DEFAULT_GRANULARITY default: page size if MORECORE_CONTIGUOUS,
448 system_info.dwAllocationGranularity in WIN32,
449 otherwise 64K.
450 Also settable using mallopt(M_GRANULARITY, x)
451 The unit for allocating and deallocating memory from the system. On
452 most systems with contiguous MORECORE, there is no reason to
453 make this more than a page. However, systems with MMAP tend to
454 either require or encourage larger granularities. You can increase
455 this value to prevent system allocation functions to be called so
456 often, especially if they are slow. The value must be at least one
457 page and must be a power of two. Setting to 0 causes initialization
458 to either page size or win32 region size. (Note: In previous
459 versions of malloc, the equivalent of this option was called
460 "TOP_PAD")
461
462DEFAULT_TRIM_THRESHOLD default: 2MB
463 Also settable using mallopt(M_TRIM_THRESHOLD, x)
464 The maximum amount of unused top-most memory to keep before
465 releasing via malloc_trim in free(). Automatic trimming is mainly
466 useful in long-lived programs using contiguous MORECORE. Because
467 trimming via sbrk can be slow on some systems, and can sometimes be
468 wasteful (in cases where programs immediately afterward allocate
469 more large chunks) the value should be high enough so that your
470 overall system performance would improve by releasing this much
471 memory. As a rough guide, you might set to a value close to the
472 average size of a process (program) running on your system.
473 Releasing this much memory would allow such a process to run in
474 memory. Generally, it is worth tuning trim thresholds when a
475 program undergoes phases where several large chunks are allocated
476 and released in ways that can reuse each other's storage, perhaps
477 mixed with phases where there are no such chunks at all. The trim
478 value must be greater than page size to have any useful effect. To
479 disable trimming completely, you can set to MAX_SIZE_T. Note that the trick
480 some people use of mallocing a huge space and then freeing it at
481 program startup, in an attempt to reserve system memory, doesn't
482 have the intended effect under automatic trimming, since that memory
483 will immediately be returned to the system.
484
485DEFAULT_MMAP_THRESHOLD default: 256K
486 Also settable using mallopt(M_MMAP_THRESHOLD, x)
487 The request size threshold for using MMAP to directly service a
488 request. Requests of at least this size that cannot be allocated
489 using already-existing space will be serviced via mmap. (If enough
490 normal freed space already exists it is used instead.) Using mmap
491 segregates relatively large chunks of memory so that they can be
492 individually obtained and released from the host system. A request
493 serviced through mmap is never reused by any other request (at least
494 not directly; the system may just so happen to remap successive
495 requests to the same locations). Segregating space in this way has
496 the benefits that: Mmapped space can always be individually released
497 back to the system, which helps keep the system level memory demands
498 of a long-lived program low. Also, mapped memory doesn't become
499 `locked' between other chunks, as can happen with normally allocated
500 chunks, which means that even trimming via malloc_trim would not
501 release them. However, it has the disadvantage that the space
502 cannot be reclaimed, consolidated, and then used to service later
503 requests, as happens with normal chunks. The advantages of mmap
504 nearly always outweigh disadvantages for "large" chunks, but the
505 value of "large" may vary across systems. The default is an
506 empirically derived value that works well in most systems. You can
507 disable mmap by setting to MAX_SIZE_T.
508
509MAX_RELEASE_CHECK_RATE default: 4095 unless not HAVE_MMAP
510 The number of consolidated frees between checks to release
511 unused segments when freeing. When using non-contiguous segments,
512 especially with multiple mspaces, checking only for topmost space
513 doesn't always suffice to trigger trimming. To compensate for this,
514 free() will, with a period of MAX_RELEASE_CHECK_RATE (or the
515 current number of segments, if greater) try to release unused
516 segments to the OS when freeing chunks that result in
517 consolidation. The best value for this parameter is a compromise
518 between slowing down frees with relatively costly checks that
519 rarely trigger versus holding on to unused memory. To effectively
520 disable, set to MAX_SIZE_T. This may lead to a very slight speed
521 improvement at the expense of carrying around more memory.
522*/
523
524/* Version identifier to allow people to support multiple versions */
525#ifndef DLMALLOC_VERSION
526#define DLMALLOC_VERSION 20806
527#endif /* DLMALLOC_VERSION */
528
529#ifndef DLMALLOC_EXPORT
530#define DLMALLOC_EXPORT extern
531#endif
532
533#ifndef WIN32
534#ifdef _WIN32
535#define WIN32 1
536#endif /* _WIN32 */
537#ifdef _WIN32_WCE
538#define LACKS_FCNTL_H
539#define WIN32 1
540#endif /* _WIN32_WCE */
541#endif /* WIN32 */
542#ifdef WIN32
543#define WIN32_LEAN_AND_MEAN
544#include <windows.h>
545#include <tchar.h>
546#define HAVE_MMAP 1
547#define HAVE_MORECORE 0
548#define LACKS_UNISTD_H
549#define LACKS_SYS_PARAM_H
550#define LACKS_SYS_MMAN_H
551#define LACKS_STRING_H
552#define LACKS_STRINGS_H
553#define LACKS_SYS_TYPES_H
554#define LACKS_ERRNO_H
555#define LACKS_SCHED_H
556#ifndef MALLOC_FAILURE_ACTION
557#define MALLOC_FAILURE_ACTION
558#endif /* MALLOC_FAILURE_ACTION */
559#ifndef MMAP_CLEARS
560#ifdef _WIN32_WCE /* WINCE reportedly does not clear */
561#define MMAP_CLEARS 0
562#else
563#define MMAP_CLEARS 1
564#endif /* _WIN32_WCE */
565#endif /*MMAP_CLEARS */
566#endif /* WIN32 */
567
568#if defined(DARWIN) || defined(_DARWIN)
569/* Mac OSX docs advise not to use sbrk; it seems better to use mmap */
570#ifndef HAVE_MORECORE
571#define HAVE_MORECORE 0
572#define HAVE_MMAP 1
573/* OSX allocators provide 16 byte alignment */
574#ifndef MALLOC_ALIGNMENT
575#define MALLOC_ALIGNMENT ((size_t)16U)
576#endif
577#endif /* HAVE_MORECORE */
578#endif /* DARWIN */
579
580#ifndef LACKS_SYS_TYPES_H
581#include <sys/types.h> /* For size_t */
582#endif /* LACKS_SYS_TYPES_H */
583
584/* The maximum possible size_t value has all bits set */
585#define MAX_SIZE_T (~(size_t)0)
586
587#ifndef USE_LOCKS /* ensure true if spin or recursive locks set */
588#if 0
589#define USE_LOCKS ((defined(USE_SPIN_LOCKS) && USE_SPIN_LOCKS != 0) || \
590 (defined(USE_RECURSIVE_LOCKS) && USE_RECURSIVE_LOCKS != 0))
591#else
592/* Avoid a -Wexpansion-to-defined compiler warning. */
593#if (defined(USE_SPIN_LOCKS) && USE_SPIN_LOCKS != 0) || \
594 (defined(USE_RECURSIVE_LOCKS) && USE_RECURSIVE_LOCKS != 0)
595#define USE_LOCKS 1
596#else
597#define USE_LOCKS 0
598#endif
599#endif
600#endif /* USE_LOCKS */
601
602#if USE_LOCKS /* Spin locks for gcc >= 4.1, older gcc on x86, MSC >= 1310 */
603#if ((defined(__GNUC__) && \
604 ((__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 1)) || \
605 defined(__i386__) || defined(__x86_64__))) || \
606 (defined(_MSC_VER) && _MSC_VER>=1310))
607#ifndef USE_SPIN_LOCKS
608#define USE_SPIN_LOCKS 1
609#endif /* USE_SPIN_LOCKS */
610#elif USE_SPIN_LOCKS
611#error "USE_SPIN_LOCKS defined without implementation"
612#endif /* ... locks available... */
613#elif !defined(USE_SPIN_LOCKS)
614#define USE_SPIN_LOCKS 0
615#endif /* USE_LOCKS */
616
617#ifndef ONLY_MSPACES
618#define ONLY_MSPACES 0
619#endif /* ONLY_MSPACES */
620#ifndef MSPACES
621#if ONLY_MSPACES
622#define MSPACES 1
623#else /* ONLY_MSPACES */
624#define MSPACES 0
625#endif /* ONLY_MSPACES */
626#endif /* MSPACES */
627#ifndef MALLOC_ALIGNMENT
628#define MALLOC_ALIGNMENT ((size_t)(2 * sizeof(void *)))
629#endif /* MALLOC_ALIGNMENT */
630#ifndef FOOTERS
631#define FOOTERS 0
632#endif /* FOOTERS */
633#ifndef ABORT
634#define ABORT abort()
635#endif /* ABORT */
636#ifndef ABORT_ON_ASSERT_FAILURE
637#define ABORT_ON_ASSERT_FAILURE 1
638#endif /* ABORT_ON_ASSERT_FAILURE */
639#ifndef PROCEED_ON_ERROR
640#define PROCEED_ON_ERROR 0
641#endif /* PROCEED_ON_ERROR */
642
643#ifndef INSECURE
644#define INSECURE 0
645#endif /* INSECURE */
646#ifndef MALLOC_INSPECT_ALL
647#define MALLOC_INSPECT_ALL 0
648#endif /* MALLOC_INSPECT_ALL */
649#ifndef HAVE_MMAP
650#define HAVE_MMAP 1
651#endif /* HAVE_MMAP */
652#ifndef MMAP_CLEARS
653#define MMAP_CLEARS 1
654#endif /* MMAP_CLEARS */
655#ifndef HAVE_MREMAP
656#ifdef linux
657#define HAVE_MREMAP 1
658#define _GNU_SOURCE /* Turns on mremap() definition */
659#else /* linux */
660#define HAVE_MREMAP 0
661#endif /* linux */
662#endif /* HAVE_MREMAP */
663#ifndef MALLOC_FAILURE_ACTION
664#define MALLOC_FAILURE_ACTION errno = ENOMEM;
665#endif /* MALLOC_FAILURE_ACTION */
666#ifndef HAVE_MORECORE
667#if ONLY_MSPACES
668#define HAVE_MORECORE 0
669#else /* ONLY_MSPACES */
670#define HAVE_MORECORE 1
671#endif /* ONLY_MSPACES */
672#endif /* HAVE_MORECORE */
673#if !HAVE_MORECORE
674#define MORECORE_CONTIGUOUS 0
675#else /* !HAVE_MORECORE */
676#define MORECORE_DEFAULT sbrk
677#ifndef MORECORE_CONTIGUOUS
678#define MORECORE_CONTIGUOUS 1
679#endif /* MORECORE_CONTIGUOUS */
680#endif /* HAVE_MORECORE */
681#ifndef DEFAULT_GRANULARITY
682#if (MORECORE_CONTIGUOUS || defined(WIN32))
683#define DEFAULT_GRANULARITY (0) /* 0 means to compute in init_mparams */
684#else /* MORECORE_CONTIGUOUS */
685#define DEFAULT_GRANULARITY ((size_t)64U * (size_t)1024U)
686#endif /* MORECORE_CONTIGUOUS */
687#endif /* DEFAULT_GRANULARITY */
688#ifndef DEFAULT_TRIM_THRESHOLD
689#ifndef MORECORE_CANNOT_TRIM
690#define DEFAULT_TRIM_THRESHOLD ((size_t)2U * (size_t)1024U * (size_t)1024U)
691#else /* MORECORE_CANNOT_TRIM */
692#define DEFAULT_TRIM_THRESHOLD MAX_SIZE_T
693#endif /* MORECORE_CANNOT_TRIM */
694#endif /* DEFAULT_TRIM_THRESHOLD */
695#ifndef DEFAULT_MMAP_THRESHOLD
696#if HAVE_MMAP
697#define DEFAULT_MMAP_THRESHOLD ((size_t)256U * (size_t)1024U)
698#else /* HAVE_MMAP */
699#define DEFAULT_MMAP_THRESHOLD MAX_SIZE_T
700#endif /* HAVE_MMAP */
701#endif /* DEFAULT_MMAP_THRESHOLD */
702#ifndef MAX_RELEASE_CHECK_RATE
703#if HAVE_MMAP
704#define MAX_RELEASE_CHECK_RATE 4095
705#else
706#define MAX_RELEASE_CHECK_RATE MAX_SIZE_T
707#endif /* HAVE_MMAP */
708#endif /* MAX_RELEASE_CHECK_RATE */
709#ifndef USE_BUILTIN_FFS
710#define USE_BUILTIN_FFS 0
711#endif /* USE_BUILTIN_FFS */
712#ifndef USE_DEV_RANDOM
713#define USE_DEV_RANDOM 0
714#endif /* USE_DEV_RANDOM */
715#ifndef NO_MALLINFO
716#define NO_MALLINFO 0
717#endif /* NO_MALLINFO */
718#ifndef MALLINFO_FIELD_TYPE
719#define MALLINFO_FIELD_TYPE size_t
720#endif /* MALLINFO_FIELD_TYPE */
721#ifndef NO_MALLOC_STATS
722#define NO_MALLOC_STATS 0
723#endif /* NO_MALLOC_STATS */
724#ifndef NO_SEGMENT_TRAVERSAL
725#define NO_SEGMENT_TRAVERSAL 0
726#endif /* NO_SEGMENT_TRAVERSAL */
727
728/*
729 mallopt tuning options. SVID/XPG defines four standard parameter
730 numbers for mallopt, normally defined in malloc.h. None of these
731 are used in this malloc, so setting them has no effect. But this
732 malloc does support the following options.
733*/
734
735#define M_TRIM_THRESHOLD (-1)
736#define M_GRANULARITY (-2)
737#define M_MMAP_THRESHOLD (-3)
738
739/* ------------------------ Mallinfo declarations ------------------------ */
740
741#if !NO_MALLINFO
742/*
743 This version of malloc supports the standard SVID/XPG mallinfo
744 routine that returns a struct containing usage properties and
745 statistics. It should work on any system that has a
746 /usr/include/malloc.h defining struct mallinfo. The main
747 declaration needed is the mallinfo struct that is returned (by-copy)
748 by mallinfo(). The malloinfo struct contains a bunch of fields that
749 are not even meaningful in this version of malloc. These fields are
750 are instead filled by mallinfo() with other numbers that might be of
751 interest.
752
753 HAVE_USR_INCLUDE_MALLOC_H should be set if you have a
754 /usr/include/malloc.h file that includes a declaration of struct
755 mallinfo. If so, it is included; else a compliant version is
756 declared below. These must be precisely the same for mallinfo() to
757 work. The original SVID version of this struct, defined on most
758 systems with mallinfo, declares all fields as ints. But some others
759 define as unsigned long. If your system defines the fields using a
760 type of different width than listed here, you MUST #include your
761 system version and #define HAVE_USR_INCLUDE_MALLOC_H.
762*/
763
764/* #define HAVE_USR_INCLUDE_MALLOC_H */
765
766#ifdef HAVE_USR_INCLUDE_MALLOC_H
767#include "/usr/include/malloc.h"
768#else /* HAVE_USR_INCLUDE_MALLOC_H */
769#ifndef STRUCT_MALLINFO_DECLARED
770/* HP-UX (and others?) redefines mallinfo unless _STRUCT_MALLINFO is defined */
771#define _STRUCT_MALLINFO
772#define STRUCT_MALLINFO_DECLARED 1
773struct mallinfo {
774 MALLINFO_FIELD_TYPE arena; /* non-mmapped space allocated from system */
775 MALLINFO_FIELD_TYPE ordblks; /* number of free chunks */
776 MALLINFO_FIELD_TYPE smblks; /* always 0 */
777 MALLINFO_FIELD_TYPE hblks; /* always 0 */
778 MALLINFO_FIELD_TYPE hblkhd; /* space in mmapped regions */
779 MALLINFO_FIELD_TYPE usmblks; /* maximum total allocated space */
780 MALLINFO_FIELD_TYPE fsmblks; /* always 0 */
781 MALLINFO_FIELD_TYPE uordblks; /* total allocated space */
782 MALLINFO_FIELD_TYPE fordblks; /* total free space */
783 MALLINFO_FIELD_TYPE keepcost; /* releasable (via malloc_trim) space */
784};
785#endif /* STRUCT_MALLINFO_DECLARED */
786#endif /* HAVE_USR_INCLUDE_MALLOC_H */
787#endif /* NO_MALLINFO */
788
789/*
790 Try to persuade compilers to inline. The most critical functions for
791 inlining are defined as macros, so these aren't used for them.
792*/
793
794#ifndef FORCEINLINE
795 #if defined(__GNUC__)
796#define FORCEINLINE __inline __attribute__ ((always_inline))
797 #elif defined(_MSC_VER)
798 #define FORCEINLINE __forceinline
799 #endif
800#endif
801#ifndef NOINLINE
802 #if defined(__GNUC__)
803 #define NOINLINE __attribute__ ((noinline))
804 #elif defined(_MSC_VER)
805 #define NOINLINE __declspec(noinline)
806 #else
807 #define NOINLINE
808 #endif
809#endif
810
811#ifdef __cplusplus
812extern "C" {
813#ifndef FORCEINLINE
814 #define FORCEINLINE inline
815#endif
816#endif /* __cplusplus */
817#ifndef FORCEINLINE
818 #define FORCEINLINE
819#endif
820
821#if !ONLY_MSPACES
822
823/* ------------------- Declarations of public routines ------------------- */
824
825#ifndef USE_DL_PREFIX
826#define dlcalloc calloc
827#define dlfree free
828#define dlmalloc malloc
829#define dlmemalign memalign
830#define dlposix_memalign posix_memalign
831#define dlrealloc realloc
832#define dlrealloc_in_place realloc_in_place
833#define dlvalloc valloc
834#define dlpvalloc pvalloc
835#define dlmallinfo mallinfo
836#define dlmallopt mallopt
837#define dlmalloc_trim malloc_trim
838#define dlmalloc_stats malloc_stats
839#define dlmalloc_usable_size malloc_usable_size
840#define dlmalloc_footprint malloc_footprint
841#define dlmalloc_max_footprint malloc_max_footprint
842#define dlmalloc_footprint_limit malloc_footprint_limit
843#define dlmalloc_set_footprint_limit malloc_set_footprint_limit
844#define dlmalloc_inspect_all malloc_inspect_all
845#define dlindependent_calloc independent_calloc
846#define dlindependent_comalloc independent_comalloc
847#define dlbulk_free bulk_free
848#endif /* USE_DL_PREFIX */
849
850/*
851 malloc(size_t n)
852 Returns a pointer to a newly allocated chunk of at least n bytes, or
853 null if no space is available, in which case errno is set to ENOMEM
854 on ANSI C systems.
855
856 If n is zero, malloc returns a minimum-sized chunk. (The minimum
857 size is 16 bytes on most 32bit systems, and 32 bytes on 64bit
858 systems.) Note that size_t is an unsigned type, so calls with
859 arguments that would be negative if signed are interpreted as
860 requests for huge amounts of space, which will often fail. The
861 maximum supported value of n differs across systems, but is in all
862 cases less than the maximum representable value of a size_t.
863*/
864DLMALLOC_EXPORT void* dlmalloc(size_t);
865
866/*
867 free(void* p)
868 Releases the chunk of memory pointed to by p, that had been previously
869 allocated using malloc or a related routine such as realloc.
870 It has no effect if p is null. If p was not malloced or already
871 freed, free(p) will by default cause the current program to abort.
872*/
873DLMALLOC_EXPORT void dlfree(void*);
874
875/*
876 calloc(size_t n_elements, size_t element_size);
877 Returns a pointer to n_elements * element_size bytes, with all locations
878 set to zero.
879*/
880DLMALLOC_EXPORT void* dlcalloc(size_t, size_t);
881
882/*
883 realloc(void* p, size_t n)
884 Returns a pointer to a chunk of size n that contains the same data
885 as does chunk p up to the minimum of (n, p's size) bytes, or null
886 if no space is available.
887
888 The returned pointer may or may not be the same as p. The algorithm
889 prefers extending p in most cases when possible, otherwise it
890 employs the equivalent of a malloc-copy-free sequence.
891
892 If p is null, realloc is equivalent to malloc.
893
894 If space is not available, realloc returns null, errno is set (if on
895 ANSI) and p is NOT freed.
896
897 if n is for fewer bytes than already held by p, the newly unused
898 space is lopped off and freed if possible. realloc with a size
899 argument of zero (re)allocates a minimum-sized chunk.
900
901 The old unix realloc convention of allowing the last-free'd chunk
902 to be used as an argument to realloc is not supported.
903*/
904DLMALLOC_EXPORT void* dlrealloc(void*, size_t);
905
906/*
907 realloc_in_place(void* p, size_t n)
908 Resizes the space allocated for p to size n, only if this can be
909 done without moving p (i.e., only if there is adjacent space
910 available if n is greater than p's current allocated size, or n is
911 less than or equal to p's size). This may be used instead of plain
912 realloc if an alternative allocation strategy is needed upon failure
913 to expand space; for example, reallocation of a buffer that must be
914 memory-aligned or cleared. You can use realloc_in_place to trigger
915 these alternatives only when needed.
916
917 Returns p if successful; otherwise null.
918*/
919DLMALLOC_EXPORT void* dlrealloc_in_place(void*, size_t);
920
921/*
922 memalign(size_t alignment, size_t n);
923 Returns a pointer to a newly allocated chunk of n bytes, aligned
924 in accord with the alignment argument.
925
926 The alignment argument should be a power of two. If the argument is
927 not a power of two, the nearest greater power is used.
928 8-byte alignment is guaranteed by normal malloc calls, so don't
929 bother calling memalign with an argument of 8 or less.
930
931 Overreliance on memalign is a sure way to fragment space.
932*/
933DLMALLOC_EXPORT void* dlmemalign(size_t, size_t);
934
935/*
936 int posix_memalign(void** pp, size_t alignment, size_t n);
937 Allocates a chunk of n bytes, aligned in accord with the alignment
938 argument. Differs from memalign only in that it (1) assigns the
939 allocated memory to *pp rather than returning it, (2) fails and
940 returns EINVAL if the alignment is not a power of two (3) fails and
941 returns ENOMEM if memory cannot be allocated.
942*/
943DLMALLOC_EXPORT int dlposix_memalign(void**, size_t, size_t);
944
945/*
946 valloc(size_t n);
947 Equivalent to memalign(pagesize, n), where pagesize is the page
948 size of the system. If the pagesize is unknown, 4096 is used.
949*/
950DLMALLOC_EXPORT void* dlvalloc(size_t);
951
952/*
953 mallopt(int parameter_number, int parameter_value)
954 Sets tunable parameters The format is to provide a
955 (parameter-number, parameter-value) pair. mallopt then sets the
956 corresponding parameter to the argument value if it can (i.e., so
957 long as the value is meaningful), and returns 1 if successful else
958 0. To workaround the fact that mallopt is specified to use int,
959 not size_t parameters, the value -1 is specially treated as the
960 maximum unsigned size_t value.
961
962 SVID/XPG/ANSI defines four standard param numbers for mallopt,
963 normally defined in malloc.h. None of these are use in this malloc,
964 so setting them has no effect. But this malloc also supports other
965 options in mallopt. See below for details. Briefly, supported
966 parameters are as follows (listed defaults are for "typical"
967 configurations).
968
969 Symbol param # default allowed param values
970 M_TRIM_THRESHOLD -1 2*1024*1024 any (-1 disables)
971 M_GRANULARITY -2 page size any power of 2 >= page size
972 M_MMAP_THRESHOLD -3 256*1024 any (or 0 if no MMAP support)
973*/
974DLMALLOC_EXPORT int dlmallopt(int, int);
975
976/*
977 malloc_footprint();
978 Returns the number of bytes obtained from the system. The total
979 number of bytes allocated by malloc, realloc etc., is less than this
980 value. Unlike mallinfo, this function returns only a precomputed
981 result, so can be called frequently to monitor memory consumption.
982 Even if locks are otherwise defined, this function does not use them,
983 so results might not be up to date.
984*/
985DLMALLOC_EXPORT size_t dlmalloc_footprint(void);
986
987/*
988 malloc_max_footprint();
989 Returns the maximum number of bytes obtained from the system. This
990 value will be greater than current footprint if deallocated space
991 has been reclaimed by the system. The peak number of bytes allocated
992 by malloc, realloc etc., is less than this value. Unlike mallinfo,
993 this function returns only a precomputed result, so can be called
994 frequently to monitor memory consumption. Even if locks are
995 otherwise defined, this function does not use them, so results might
996 not be up to date.
997*/
998DLMALLOC_EXPORT size_t dlmalloc_max_footprint(void);
999
1000/*
1001 malloc_footprint_limit();
1002 Returns the number of bytes that the heap is allowed to obtain from
1003 the system, returning the last value returned by
1004 malloc_set_footprint_limit, or the maximum size_t value if
1005 never set. The returned value reflects a permission. There is no
1006 guarantee that this number of bytes can actually be obtained from
1007 the system.
1008*/
1009DLMALLOC_EXPORT size_t dlmalloc_footprint_limit();
1010
1011/*
1012 malloc_set_footprint_limit();
1013 Sets the maximum number of bytes to obtain from the system, causing
1014 failure returns from malloc and related functions upon attempts to
1015 exceed this value. The argument value may be subject to page
1016 rounding to an enforceable limit; this actual value is returned.
1017 Using an argument of the maximum possible size_t effectively
1018 disables checks. If the argument is less than or equal to the
1019 current malloc_footprint, then all future allocations that require
1020 additional system memory will fail. However, invocation cannot
1021 retroactively deallocate existing used memory.
1022*/
1023DLMALLOC_EXPORT size_t dlmalloc_set_footprint_limit(size_t bytes);
1024
1025#if MALLOC_INSPECT_ALL
1026/*
1027 malloc_inspect_all(void(*handler)(void *start,
1028 void *end,
1029 size_t used_bytes,
1030 void* callback_arg),
1031 void* arg);
1032 Traverses the heap and calls the given handler for each managed
1033 region, skipping all bytes that are (or may be) used for bookkeeping
1034 purposes. Traversal does not include include chunks that have been
1035 directly memory mapped. Each reported region begins at the start
1036 address, and continues up to but not including the end address. The
1037 first used_bytes of the region contain allocated data. If
1038 used_bytes is zero, the region is unallocated. The handler is
1039 invoked with the given callback argument. If locks are defined, they
1040 are held during the entire traversal. It is a bad idea to invoke
1041 other malloc functions from within the handler.
1042
1043 For example, to count the number of in-use chunks with size greater
1044 than 1000, you could write:
1045 static int count = 0;
1046 void count_chunks(void* start, void* end, size_t used, void* arg) {
1047 if (used >= 1000) ++count;
1048 }
1049 then:
1050 malloc_inspect_all(count_chunks, NULL);
1051
1052 malloc_inspect_all is compiled only if MALLOC_INSPECT_ALL is defined.
1053*/
1054DLMALLOC_EXPORT void dlmalloc_inspect_all(void(*handler)(void*, void *, size_t, void*),
1055 void* arg);
1056
1057#endif /* MALLOC_INSPECT_ALL */
1058
1059#if !NO_MALLINFO
1060/*
1061 mallinfo()
1062 Returns (by copy) a struct containing various summary statistics:
1063
1064 arena: current total non-mmapped bytes allocated from system
1065 ordblks: the number of free chunks
1066 smblks: always zero.
1067 hblks: current number of mmapped regions
1068 hblkhd: total bytes held in mmapped regions
1069 usmblks: the maximum total allocated space. This will be greater
1070 than current total if trimming has occurred.
1071 fsmblks: always zero
1072 uordblks: current total allocated space (normal or mmapped)
1073 fordblks: total free space
1074 keepcost: the maximum number of bytes that could ideally be released
1075 back to system via malloc_trim. ("ideally" means that
1076 it ignores page restrictions etc.)
1077
1078 Because these fields are ints, but internal bookkeeping may
1079 be kept as longs, the reported values may wrap around zero and
1080 thus be inaccurate.
1081*/
1082DLMALLOC_EXPORT struct mallinfo dlmallinfo(void);
1083#endif /* NO_MALLINFO */
1084
1085/*
1086 independent_calloc(size_t n_elements, size_t element_size, void* chunks[]);
1087
1088 independent_calloc is similar to calloc, but instead of returning a
1089 single cleared space, it returns an array of pointers to n_elements
1090 independent elements that can hold contents of size elem_size, each
1091 of which starts out cleared, and can be independently freed,
1092 realloc'ed etc. The elements are guaranteed to be adjacently
1093 allocated (this is not guaranteed to occur with multiple callocs or
1094 mallocs), which may also improve cache locality in some
1095 applications.
1096
1097 The "chunks" argument is optional (i.e., may be null, which is
1098 probably the most typical usage). If it is null, the returned array
1099 is itself dynamically allocated and should also be freed when it is
1100 no longer needed. Otherwise, the chunks array must be of at least
1101 n_elements in length. It is filled in with the pointers to the
1102 chunks.
1103
1104 In either case, independent_calloc returns this pointer array, or
1105 null if the allocation failed. If n_elements is zero and "chunks"
1106 is null, it returns a chunk representing an array with zero elements
1107 (which should be freed if not wanted).
1108
1109 Each element must be freed when it is no longer needed. This can be
1110 done all at once using bulk_free.
1111
1112 independent_calloc simplifies and speeds up implementations of many
1113 kinds of pools. It may also be useful when constructing large data
1114 structures that initially have a fixed number of fixed-sized nodes,
1115 but the number is not known at compile time, and some of the nodes
1116 may later need to be freed. For example:
1117
1118 struct Node { int item; struct Node* next; };
1119
1120 struct Node* build_list() {
1121 struct Node** pool;
1122 int n = read_number_of_nodes_needed();
1123 if (n <= 0) return 0;
1124 pool = (struct Node**)(independent_calloc(n, sizeof(struct Node), 0);
1125 if (pool == 0) die();
1126 // organize into a linked list...
1127 struct Node* first = pool[0];
1128 for (i = 0; i < n-1; ++i)
1129 pool[i]->next = pool[i+1];
1130 free(pool); // Can now free the array (or not, if it is needed later)
1131 return first;
1132 }
1133*/
1134DLMALLOC_EXPORT void** dlindependent_calloc(size_t, size_t, void**);
1135
1136/*
1137 independent_comalloc(size_t n_elements, size_t sizes[], void* chunks[]);
1138
1139 independent_comalloc allocates, all at once, a set of n_elements
1140 chunks with sizes indicated in the "sizes" array. It returns
1141 an array of pointers to these elements, each of which can be
1142 independently freed, realloc'ed etc. The elements are guaranteed to
1143 be adjacently allocated (this is not guaranteed to occur with
1144 multiple callocs or mallocs), which may also improve cache locality
1145 in some applications.
1146
1147 The "chunks" argument is optional (i.e., may be null). If it is null
1148 the returned array is itself dynamically allocated and should also
1149 be freed when it is no longer needed. Otherwise, the chunks array
1150 must be of at least n_elements in length. It is filled in with the
1151 pointers to the chunks.
1152
1153 In either case, independent_comalloc returns this pointer array, or
1154 null if the allocation failed. If n_elements is zero and chunks is
1155 null, it returns a chunk representing an array with zero elements
1156 (which should be freed if not wanted).
1157
1158 Each element must be freed when it is no longer needed. This can be
1159 done all at once using bulk_free.
1160
1161 independent_comallac differs from independent_calloc in that each
1162 element may have a different size, and also that it does not
1163 automatically clear elements.
1164
1165 independent_comalloc can be used to speed up allocation in cases
1166 where several structs or objects must always be allocated at the
1167 same time. For example:
1168
1169 struct Head { ... }
1170 struct Foot { ... }
1171
1172 void send_message(char* msg) {
1173 int msglen = strlen(msg);
1174 size_t sizes[3] = { sizeof(struct Head), msglen, sizeof(struct Foot) };
1175 void* chunks[3];
1176 if (independent_comalloc(3, sizes, chunks) == 0)
1177 die();
1178 struct Head* head = (struct Head*)(chunks[0]);
1179 char* body = (char*)(chunks[1]);
1180 struct Foot* foot = (struct Foot*)(chunks[2]);
1181 // ...
1182 }
1183
1184 In general though, independent_comalloc is worth using only for
1185 larger values of n_elements. For small values, you probably won't
1186 detect enough difference from series of malloc calls to bother.
1187
1188 Overuse of independent_comalloc can increase overall memory usage,
1189 since it cannot reuse existing noncontiguous small chunks that
1190 might be available for some of the elements.
1191*/
1192DLMALLOC_EXPORT void** dlindependent_comalloc(size_t, size_t*, void**);
1193
1194/*
1195 bulk_free(void* array[], size_t n_elements)
1196 Frees and clears (sets to null) each non-null pointer in the given
1197 array. This is likely to be faster than freeing them one-by-one.
1198 If footers are used, pointers that have been allocated in different
1199 mspaces are not freed or cleared, and the count of all such pointers
1200 is returned. For large arrays of pointers with poor locality, it
1201 may be worthwhile to sort this array before calling bulk_free.
1202*/
1203DLMALLOC_EXPORT size_t dlbulk_free(void**, size_t n_elements);
1204
1205/*
1206 pvalloc(size_t n);
1207 Equivalent to valloc(minimum-page-that-holds(n)), that is,
1208 round up n to nearest pagesize.
1209 */
1210DLMALLOC_EXPORT void* dlpvalloc(size_t);
1211
1212/*
1213 malloc_trim(size_t pad);
1214
1215 If possible, gives memory back to the system (via negative arguments
1216 to sbrk) if there is unused memory at the `high' end of the malloc
1217 pool or in unused MMAP segments. You can call this after freeing
1218 large blocks of memory to potentially reduce the system-level memory
1219 requirements of a program. However, it cannot guarantee to reduce
1220 memory. Under some allocation patterns, some large free blocks of
1221 memory will be locked between two used chunks, so they cannot be
1222 given back to the system.
1223
1224 The `pad' argument to malloc_trim represents the amount of free
1225 trailing space to leave untrimmed. If this argument is zero, only
1226 the minimum amount of memory to maintain internal data structures
1227 will be left. Non-zero arguments can be supplied to maintain enough
1228 trailing space to service future expected allocations without having
1229 to re-obtain memory from the system.
1230
1231 Malloc_trim returns 1 if it actually released any memory, else 0.
1232*/
1233DLMALLOC_EXPORT int dlmalloc_trim(size_t);
1234
1235/*
1236 malloc_stats();
1237 Prints on stderr the amount of space obtained from the system (both
1238 via sbrk and mmap), the maximum amount (which may be more than
1239 current if malloc_trim and/or munmap got called), and the current
1240 number of bytes allocated via malloc (or realloc, etc) but not yet
1241 freed. Note that this is the number of bytes allocated, not the
1242 number requested. It will be larger than the number requested
1243 because of alignment and bookkeeping overhead. Because it includes
1244 alignment wastage as being in use, this figure may be greater than
1245 zero even when no user-level chunks are allocated.
1246
1247 The reported current and maximum system memory can be inaccurate if
1248 a program makes other calls to system memory allocation functions
1249 (normally sbrk) outside of malloc.
1250
1251 malloc_stats prints only the most commonly interesting statistics.
1252 More information can be obtained by calling mallinfo.
1253*/
1254DLMALLOC_EXPORT void dlmalloc_stats(void);
1255
1256/*
1257 malloc_usable_size(void* p);
1258
1259 Returns the number of bytes you can actually use in
1260 an allocated chunk, which may be more than you requested (although
1261 often not) due to alignment and minimum size constraints.
1262 You can use this many bytes without worrying about
1263 overwriting other allocated objects. This is not a particularly great
1264 programming practice. malloc_usable_size can be more useful in
1265 debugging and assertions, for example:
1266
1267 p = malloc(n);
1268 assert(malloc_usable_size(p) >= 256);
1269*/
1270size_t dlmalloc_usable_size(void*);
1271
1272#endif /* ONLY_MSPACES */
1273
1274#if MSPACES
1275
1276/*
1277 mspace is an opaque type representing an independent
1278 region of space that supports mspace_malloc, etc.
1279*/
1280typedef void* mspace;
1281
1282/*
1283 create_mspace creates and returns a new independent space with the
1284 given initial capacity, or, if 0, the default granularity size. It
1285 returns null if there is no system memory available to create the
1286 space. If argument locked is non-zero, the space uses a separate
1287 lock to control access. The capacity of the space will grow
1288 dynamically as needed to service mspace_malloc requests. You can
1289 control the sizes of incremental increases of this space by
1290 compiling with a different DEFAULT_GRANULARITY or dynamically
1291 setting with mallopt(M_GRANULARITY, value).
1292*/
1293DLMALLOC_EXPORT mspace create_mspace(size_t capacity, int locked);
1294
1295/*
1296 destroy_mspace destroys the given space, and attempts to return all
1297 of its memory back to the system, returning the total number of
1298 bytes freed. After destruction, the results of access to all memory
1299 used by the space become undefined.
1300*/
1301DLMALLOC_EXPORT size_t destroy_mspace(mspace msp);
1302
1303/*
1304 create_mspace_with_base uses the memory supplied as the initial base
1305 of a new mspace. Part (less than 128*sizeof(size_t) bytes) of this
1306 space is used for bookkeeping, so the capacity must be at least this
1307 large. (Otherwise 0 is returned.) When this initial space is
1308 exhausted, additional memory will be obtained from the system.
1309 Destroying this space will deallocate all additionally allocated
1310 space (if possible) but not the initial base.
1311*/
1312DLMALLOC_EXPORT mspace create_mspace_with_base(void* base, size_t capacity, int locked);
1313
1314/*
1315 mspace_track_large_chunks controls whether requests for large chunks
1316 are allocated in their own untracked mmapped regions, separate from
1317 others in this mspace. By default large chunks are not tracked,
1318 which reduces fragmentation. However, such chunks are not
1319 necessarily released to the system upon destroy_mspace. Enabling
1320 tracking by setting to true may increase fragmentation, but avoids
1321 leakage when relying on destroy_mspace to release all memory
1322 allocated using this space. The function returns the previous
1323 setting.
1324*/
1325DLMALLOC_EXPORT int mspace_track_large_chunks(mspace msp, int enable);
1326
1327
1328/*
1329 mspace_malloc behaves as malloc, but operates within
1330 the given space.
1331*/
1332DLMALLOC_EXPORT void* mspace_malloc(mspace msp, size_t bytes);
1333
1334/*
1335 mspace_free behaves as free, but operates within
1336 the given space.
1337
1338 If compiled with FOOTERS==1, mspace_free is not actually needed.
1339 free may be called instead of mspace_free because freed chunks from
1340 any space are handled by their originating spaces.
1341*/
1342DLMALLOC_EXPORT void mspace_free(mspace msp, void* mem);
1343
1344/*
1345 mspace_realloc behaves as realloc, but operates within
1346 the given space.
1347
1348 If compiled with FOOTERS==1, mspace_realloc is not actually
1349 needed. realloc may be called instead of mspace_realloc because
1350 realloced chunks from any space are handled by their originating
1351 spaces.
1352*/
1353DLMALLOC_EXPORT void* mspace_realloc(mspace msp, void* mem, size_t newsize);
1354
1355/*
1356 mspace_calloc behaves as calloc, but operates within
1357 the given space.
1358*/
1359DLMALLOC_EXPORT void* mspace_calloc(mspace msp, size_t n_elements, size_t elem_size);
1360
1361/*
1362 mspace_memalign behaves as memalign, but operates within
1363 the given space.
1364*/
1365DLMALLOC_EXPORT void* mspace_memalign(mspace msp, size_t alignment, size_t bytes);
1366
1367/*
1368 mspace_independent_calloc behaves as independent_calloc, but
1369 operates within the given space.
1370*/
1371DLMALLOC_EXPORT void** mspace_independent_calloc(mspace msp, size_t n_elements,
1372 size_t elem_size, void* chunks[]);
1373
1374/*
1375 mspace_independent_comalloc behaves as independent_comalloc, but
1376 operates within the given space.
1377*/
1378DLMALLOC_EXPORT void** mspace_independent_comalloc(mspace msp, size_t n_elements,
1379 size_t sizes[], void* chunks[]);
1380
1381/*
1382 mspace_footprint() returns the number of bytes obtained from the
1383 system for this space.
1384*/
1385DLMALLOC_EXPORT size_t mspace_footprint(mspace msp);
1386
1387/*
1388 mspace_max_footprint() returns the peak number of bytes obtained from the
1389 system for this space.
1390*/
1391DLMALLOC_EXPORT size_t mspace_max_footprint(mspace msp);
1392
1393
1394#if !NO_MALLINFO
1395/*
1396 mspace_mallinfo behaves as mallinfo, but reports properties of
1397 the given space.
1398*/
1399DLMALLOC_EXPORT struct mallinfo mspace_mallinfo(mspace msp);
1400#endif /* NO_MALLINFO */
1401
1402/*
1403 malloc_usable_size(void* p) behaves the same as malloc_usable_size;
1404*/
1405DLMALLOC_EXPORT size_t mspace_usable_size(const void* mem);
1406
1407/*
1408 mspace_malloc_stats behaves as malloc_stats, but reports
1409 properties of the given space.
1410*/
1411DLMALLOC_EXPORT void mspace_malloc_stats(mspace msp);
1412
1413/*
1414 mspace_trim behaves as malloc_trim, but
1415 operates within the given space.
1416*/
1417DLMALLOC_EXPORT int mspace_trim(mspace msp, size_t pad);
1418
1419/*
1420 An alias for mallopt.
1421*/
1422DLMALLOC_EXPORT int mspace_mallopt(int, int);
1423
1424#endif /* MSPACES */
1425
1426#ifdef __cplusplus
1427} /* end of extern "C" */
1428#endif /* __cplusplus */
1429
1430/*
1431 ========================================================================
1432 To make a fully customizable malloc.h header file, cut everything
1433 above this line, put into file malloc.h, edit to suit, and #include it
1434 on the next line, as well as in programs that use this malloc.
1435 ========================================================================
1436*/
1437
1438/* #include "malloc.h" */
1439
1440/*------------------------------ internal #includes ---------------------- */
1441
1442#ifdef _MSC_VER
1443#pragma warning( disable : 4146 ) /* no "unsigned" warnings */
1444#endif /* _MSC_VER */
1445#if !NO_MALLOC_STATS
1446#include <stdio.h> /* for printing in malloc_stats */
1447#endif /* NO_MALLOC_STATS */
1448#ifndef LACKS_ERRNO_H
1449#include <errno.h> /* for MALLOC_FAILURE_ACTION */
1450#endif /* LACKS_ERRNO_H */
1451#ifdef DEBUG
1452#if ABORT_ON_ASSERT_FAILURE
1453#undef assert
1454#define assert(x) if(!(x)) ABORT
1455#else /* ABORT_ON_ASSERT_FAILURE */
1456#include <assert.h>
1457#endif /* ABORT_ON_ASSERT_FAILURE */
1458#else /* DEBUG */
1459#ifndef assert
1460#define assert(x)
1461#endif
1462#define DEBUG 0
1463#endif /* DEBUG */
1464#if !defined(WIN32) && !defined(LACKS_TIME_H)
1465#include <time.h> /* for magic initialization */
1466#endif /* WIN32 */
1467#ifndef LACKS_STDLIB_H
1468#include <stdlib.h> /* for abort() */
1469#endif /* LACKS_STDLIB_H */
1470#ifndef LACKS_STRING_H
1471#include <string.h> /* for memset etc */
1472#endif /* LACKS_STRING_H */
1473#if USE_BUILTIN_FFS
1474#ifndef LACKS_STRINGS_H
1475#include <strings.h> /* for ffs */
1476#endif /* LACKS_STRINGS_H */
1477#endif /* USE_BUILTIN_FFS */
1478#if HAVE_MMAP
1479#ifndef LACKS_SYS_MMAN_H
1480/* On some versions of linux, mremap decl in mman.h needs __USE_GNU set */
1481#if (defined(linux) && !defined(__USE_GNU))
1482#define __USE_GNU 1
1483#include <sys/mman.h> /* for mmap */
1484#undef __USE_GNU
1485#else
1486#include <sys/mman.h> /* for mmap */
1487#endif /* linux */
1488#endif /* LACKS_SYS_MMAN_H */
1489#ifndef LACKS_FCNTL_H
1490#include <fcntl.h>
1491#endif /* LACKS_FCNTL_H */
1492#endif /* HAVE_MMAP */
1493#ifndef LACKS_UNISTD_H
1494#include <unistd.h> /* for sbrk, sysconf */
1495#else /* LACKS_UNISTD_H */
1496#if !defined(__FreeBSD__) && !defined(__OpenBSD__) && !defined(__NetBSD__)
1497extern void* sbrk(ptrdiff_t);
1498#endif /* FreeBSD etc */
1499#endif /* LACKS_UNISTD_H */
1500
1501/* Declarations for locking */
1502#if USE_LOCKS
1503#ifndef WIN32
1504#if defined (__SVR4) && defined (__sun) /* solaris */
1505#include <thread.h>
1506#elif !defined(LACKS_SCHED_H)
1507#include <sched.h>
1508#endif /* solaris or LACKS_SCHED_H */
1509#if (defined(USE_RECURSIVE_LOCKS) && USE_RECURSIVE_LOCKS != 0) || !USE_SPIN_LOCKS
1510#include <pthread.h>
1511#endif /* USE_RECURSIVE_LOCKS ... */
1512#elif defined(_MSC_VER)
1513#ifndef _M_AMD64
1514/* These are already defined on AMD64 builds */
1515#ifdef __cplusplus
1516extern "C" {
1517#endif /* __cplusplus */
1518LONG __cdecl _InterlockedCompareExchange(LONG volatile *Dest, LONG Exchange, LONG Comp);
1519LONG __cdecl _InterlockedExchange(LONG volatile *Target, LONG Value);
1520#ifdef __cplusplus
1521}
1522#endif /* __cplusplus */
1523#endif /* _M_AMD64 */
1524#pragma intrinsic (_InterlockedCompareExchange)
1525#pragma intrinsic (_InterlockedExchange)
1526#define interlockedcompareexchange _InterlockedCompareExchange
1527#define interlockedexchange _InterlockedExchange
1528#elif defined(WIN32) && defined(__GNUC__)
1529#define interlockedcompareexchange(a, b, c) __sync_val_compare_and_swap(a, c, b)
1530#define interlockedexchange __sync_lock_test_and_set
1531#endif /* Win32 */
1532#else /* USE_LOCKS */
1533#endif /* USE_LOCKS */
1534
1535#ifndef LOCK_AT_FORK
1536#define LOCK_AT_FORK 0
1537#endif
1538
1539/* Declarations for bit scanning on win32 */
1540#if defined(_MSC_VER) && _MSC_VER>=1300
1541#ifndef BitScanForward /* Try to avoid pulling in WinNT.h */
1542#ifdef __cplusplus
1543extern "C" {
1544#endif /* __cplusplus */
1545unsigned char _BitScanForward(unsigned long *index, unsigned long mask);
1546unsigned char _BitScanReverse(unsigned long *index, unsigned long mask);
1547#ifdef __cplusplus
1548}
1549#endif /* __cplusplus */
1550
1551#define BitScanForward _BitScanForward
1552#define BitScanReverse _BitScanReverse
1553#pragma intrinsic(_BitScanForward)
1554#pragma intrinsic(_BitScanReverse)
1555#endif /* BitScanForward */
1556#endif /* defined(_MSC_VER) && _MSC_VER>=1300 */
1557
1558#ifndef WIN32
1559#ifndef malloc_getpagesize
1560# ifdef _SC_PAGESIZE /* some SVR4 systems omit an underscore */
1561# ifndef _SC_PAGE_SIZE
1562# define _SC_PAGE_SIZE _SC_PAGESIZE
1563# endif
1564# endif
1565# ifdef _SC_PAGE_SIZE
1566# define malloc_getpagesize sysconf(_SC_PAGE_SIZE)
1567# else
1568# if defined(BSD) || defined(DGUX) || defined(HAVE_GETPAGESIZE)
1569 extern size_t getpagesize();
1570# define malloc_getpagesize getpagesize()
1571# else
1572# ifdef WIN32 /* use supplied emulation of getpagesize */
1573# define malloc_getpagesize getpagesize()
1574# else
1575# ifndef LACKS_SYS_PARAM_H
1576# include <sys/param.h>
1577# endif
1578# ifdef EXEC_PAGESIZE
1579# define malloc_getpagesize EXEC_PAGESIZE
1580# else
1581# ifdef NBPG
1582# ifndef CLSIZE
1583# define malloc_getpagesize NBPG
1584# else
1585# define malloc_getpagesize (NBPG * CLSIZE)
1586# endif
1587# else
1588# ifdef NBPC
1589# define malloc_getpagesize NBPC
1590# else
1591# ifdef PAGESIZE
1592# define malloc_getpagesize PAGESIZE
1593# else /* just guess */
1594# define malloc_getpagesize ((size_t)4096U)
1595# endif
1596# endif
1597# endif
1598# endif
1599# endif
1600# endif
1601# endif
1602#endif
1603#endif
1604
1605/* ------------------- size_t and alignment properties -------------------- */
1606
1607/* The byte and bit size of a size_t */
1608#define SIZE_T_SIZE (sizeof(size_t))
1609#define SIZE_T_BITSIZE (sizeof(size_t) << 3)
1610
1611/* Some constants coerced to size_t */
1612/* Annoying but necessary to avoid errors on some platforms */
1613#define SIZE_T_ZERO ((size_t)0)
1614#define SIZE_T_ONE ((size_t)1)
1615#define SIZE_T_TWO ((size_t)2)
1616#define SIZE_T_FOUR ((size_t)4)
1617#define TWO_SIZE_T_SIZES (SIZE_T_SIZE<<1)
1618#define FOUR_SIZE_T_SIZES (SIZE_T_SIZE<<2)
1619#define SIX_SIZE_T_SIZES (FOUR_SIZE_T_SIZES+TWO_SIZE_T_SIZES)
1620#define HALF_MAX_SIZE_T (MAX_SIZE_T / 2U)
1621
1622/* The bit mask value corresponding to MALLOC_ALIGNMENT */
1623#define CHUNK_ALIGN_MASK (MALLOC_ALIGNMENT - SIZE_T_ONE)
1624
1625/* True if address a has acceptable alignment */
1626#define is_aligned(A) (((size_t)((A)) & (CHUNK_ALIGN_MASK)) == 0)
1627
1628/* the number of bytes to offset an address to align it */
1629#define align_offset(A)\
1630 ((((size_t)(A) & CHUNK_ALIGN_MASK) == 0)? 0 :\
1631 ((MALLOC_ALIGNMENT - ((size_t)(A) & CHUNK_ALIGN_MASK)) & CHUNK_ALIGN_MASK))
1632
1633/* -------------------------- MMAP preliminaries ------------------------- */
1634
1635/*
1636 If HAVE_MORECORE or HAVE_MMAP are false, we just define calls and
1637 checks to fail so compiler optimizer can delete code rather than
1638 using so many "#if"s.
1639*/
1640
1641
1642/* MORECORE and MMAP must return MFAIL on failure */
1643#define MFAIL ((void*)(MAX_SIZE_T))
1644#define CMFAIL ((char*)(MFAIL)) /* defined for convenience */
1645
1646#if HAVE_MMAP
1647
1648#ifndef WIN32
1649#define MUNMAP_DEFAULT(a, s) munmap((a), (s))
1650#define MMAP_PROT (PROT_READ|PROT_WRITE)
1651#if !defined(MAP_ANONYMOUS) && defined(MAP_ANON)
1652#define MAP_ANONYMOUS MAP_ANON
1653#endif /* MAP_ANON */
1654#ifdef MAP_ANONYMOUS
1655#define MMAP_FLAGS (MAP_PRIVATE|MAP_ANONYMOUS)
1656#define MMAP_DEFAULT(s) mmap(0, (s), MMAP_PROT, MMAP_FLAGS, -1, 0)
1657#else /* MAP_ANONYMOUS */
1658/*
1659 Nearly all versions of mmap support MAP_ANONYMOUS, so the following
1660 is unlikely to be needed, but is supplied just in case.
1661*/
1662#define MMAP_FLAGS (MAP_PRIVATE)
1663static int dev_zero_fd = -1; /* Cached file descriptor for /dev/zero. */
1664#define MMAP_DEFAULT(s) ((dev_zero_fd < 0) ? \
1665 (dev_zero_fd = open("/dev/zero", O_RDWR), \
1666 mmap(0, (s), MMAP_PROT, MMAP_FLAGS, dev_zero_fd, 0)) : \
1667 mmap(0, (s), MMAP_PROT, MMAP_FLAGS, dev_zero_fd, 0))
1668#endif /* MAP_ANONYMOUS */
1669
1670#define DIRECT_MMAP_DEFAULT(s) MMAP_DEFAULT(s)
1671
1672#else /* WIN32 */
1673
1674/* Win32 MMAP via VirtualAlloc */
1675static FORCEINLINE void* win32mmap(size_t size) {
1676 void* ptr = VirtualAlloc(0, size, MEM_RESERVE|MEM_COMMIT, PAGE_READWRITE);
1677 return (ptr != 0)? ptr: MFAIL;
1678}
1679
1680/* For direct MMAP, use MEM_TOP_DOWN to minimize interference */
1681static FORCEINLINE void* win32direct_mmap(size_t size) {
1682 void* ptr = VirtualAlloc(0, size, MEM_RESERVE|MEM_COMMIT|MEM_TOP_DOWN,
1683 PAGE_READWRITE);
1684 return (ptr != 0)? ptr: MFAIL;
1685}
1686
1687/* This function supports releasing coalesed segments */
1688static FORCEINLINE int win32munmap(void* ptr, size_t size) {
1689 MEMORY_BASIC_INFORMATION minfo;
1690 char* cptr = (char*)ptr;
1691 while (size) {
1692 if (VirtualQuery(cptr, &minfo, sizeof(minfo)) == 0)
1693 return -1;
1694 if (minfo.BaseAddress != cptr || minfo.AllocationBase != cptr ||
1695 minfo.State != MEM_COMMIT || minfo.RegionSize > size)
1696 return -1;
1697 if (VirtualFree(cptr, 0, MEM_RELEASE) == 0)
1698 return -1;
1699 cptr += minfo.RegionSize;
1700 size -= minfo.RegionSize;
1701 }
1702 return 0;
1703}
1704
1705#define MMAP_DEFAULT(s) win32mmap(s)
1706#define MUNMAP_DEFAULT(a, s) win32munmap((a), (s))
1707#define DIRECT_MMAP_DEFAULT(s) win32direct_mmap(s)
1708#endif /* WIN32 */
1709#endif /* HAVE_MMAP */
1710
1711#if HAVE_MREMAP
1712#ifndef WIN32
1713#define MREMAP_DEFAULT(addr, osz, nsz, mv) mremap((addr), (osz), (nsz), (mv))
1714#endif /* WIN32 */
1715#endif /* HAVE_MREMAP */
1716
1717/**
1718 * Define CALL_MORECORE
1719 */
1720#if HAVE_MORECORE
1721 #ifdef MORECORE
1722 #define CALL_MORECORE(S) MORECORE(S)
1723 #else /* MORECORE */
1724 #define CALL_MORECORE(S) MORECORE_DEFAULT(S)
1725 #endif /* MORECORE */
1726#else /* HAVE_MORECORE */
1727 #define CALL_MORECORE(S) MFAIL
1728#endif /* HAVE_MORECORE */
1729
1730/**
1731 * Define CALL_MMAP/CALL_MUNMAP/CALL_DIRECT_MMAP
1732 */
1733#if HAVE_MMAP
1734 #define USE_MMAP_BIT (SIZE_T_ONE)
1735
1736 #ifdef MMAP
1737 #define CALL_MMAP(s) MMAP(s)
1738 #else /* MMAP */
1739 #define CALL_MMAP(s) MMAP_DEFAULT(s)
1740 #endif /* MMAP */
1741 #ifdef MUNMAP
1742 #define CALL_MUNMAP(a, s) MUNMAP((a), (s))
1743 #else /* MUNMAP */
1744 #define CALL_MUNMAP(a, s) MUNMAP_DEFAULT((a), (s))
1745 #endif /* MUNMAP */
1746 #ifdef DIRECT_MMAP
1747 #define CALL_DIRECT_MMAP(s) DIRECT_MMAP(s)
1748 #else /* DIRECT_MMAP */
1749 #define CALL_DIRECT_MMAP(s) DIRECT_MMAP_DEFAULT(s)
1750 #endif /* DIRECT_MMAP */
1751#else /* HAVE_MMAP */
1752 #define USE_MMAP_BIT (SIZE_T_ZERO)
1753
1754 #define MMAP(s) MFAIL
1755 #define MUNMAP(a, s) (-1)
1756 #define DIRECT_MMAP(s) MFAIL
1757 #define CALL_DIRECT_MMAP(s) DIRECT_MMAP(s)
1758 #define CALL_MMAP(s) MMAP(s)
1759 #define CALL_MUNMAP(a, s) MUNMAP((a), (s))
1760#endif /* HAVE_MMAP */
1761
1762/**
1763 * Define CALL_MREMAP
1764 */
1765#if HAVE_MMAP && HAVE_MREMAP
1766 #ifdef MREMAP
1767 #define CALL_MREMAP(addr, osz, nsz, mv) MREMAP((addr), (osz), (nsz), (mv))
1768 #else /* MREMAP */
1769 #define CALL_MREMAP(addr, osz, nsz, mv) MREMAP_DEFAULT((addr), (osz), (nsz), (mv))
1770 #endif /* MREMAP */
1771#else /* HAVE_MMAP && HAVE_MREMAP */
1772 #define CALL_MREMAP(addr, osz, nsz, mv) MFAIL
1773#endif /* HAVE_MMAP && HAVE_MREMAP */
1774
1775/* mstate bit set if continguous morecore disabled or failed */
1776#define USE_NONCONTIGUOUS_BIT (4U)
1777
1778/* segment bit set in create_mspace_with_base */
1779#define EXTERN_BIT (8U)
1780
1781
1782/* --------------------------- Lock preliminaries ------------------------ */
1783
1784/*
1785 When locks are defined, there is one global lock, plus
1786 one per-mspace lock.
1787
1788 The global lock_ensures that mparams.magic and other unique
1789 mparams values are initialized only once. It also protects
1790 sequences of calls to MORECORE. In many cases sys_alloc requires
1791 two calls, that should not be interleaved with calls by other
1792 threads. This does not protect against direct calls to MORECORE
1793 by other threads not using this lock, so there is still code to
1794 cope the best we can on interference.
1795
1796 Per-mspace locks surround calls to malloc, free, etc.
1797 By default, locks are simple non-reentrant mutexes.
1798
1799 Because lock-protected regions generally have bounded times, it is
1800 OK to use the supplied simple spinlocks. Spinlocks are likely to
1801 improve performance for lightly contended applications, but worsen
1802 performance under heavy contention.
1803
1804 If USE_LOCKS is > 1, the definitions of lock routines here are
1805 bypassed, in which case you will need to define the type MLOCK_T,
1806 and at least INITIAL_LOCK, DESTROY_LOCK, ACQUIRE_LOCK, RELEASE_LOCK
1807 and TRY_LOCK. You must also declare a
1808 static MLOCK_T malloc_global_mutex = { initialization values };.
1809
1810*/
1811
1812#if !USE_LOCKS
1813#define USE_LOCK_BIT (0U)
1814#define INITIAL_LOCK(l) (0)
1815#define DESTROY_LOCK(l) (0)
1816#define ACQUIRE_MALLOC_GLOBAL_LOCK()
1817#define RELEASE_MALLOC_GLOBAL_LOCK()
1818
1819#else
1820#if USE_LOCKS > 1
1821/* ----------------------- User-defined locks ------------------------ */
1822/* Define your own lock implementation here */
1823/* #define INITIAL_LOCK(lk) ... */
1824/* #define DESTROY_LOCK(lk) ... */
1825/* #define ACQUIRE_LOCK(lk) ... */
1826/* #define RELEASE_LOCK(lk) ... */
1827/* #define TRY_LOCK(lk) ... */
1828/* static MLOCK_T malloc_global_mutex = ... */
1829
1830#elif USE_SPIN_LOCKS
1831
1832/* First, define CAS_LOCK and CLEAR_LOCK on ints */
1833/* Note CAS_LOCK defined to return 0 on success */
1834
1835#if defined(__GNUC__)&& (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 1))
1836#define CAS_LOCK(sl) __sync_lock_test_and_set(sl, 1)
1837#define CLEAR_LOCK(sl) __sync_lock_release(sl)
1838
1839#elif (defined(__GNUC__) && (defined(__i386__) || defined(__x86_64__)))
1840/* Custom spin locks for older gcc on x86 */
1841static FORCEINLINE int x86_cas_lock(int *sl) {
1842 int ret;
1843 int val = 1;
1844 int cmp = 0;
1845 __asm__ __volatile__ ("lock; cmpxchgl %1, %2"
1846 : "=a" (ret)
1847 : "r" (val), "m" (*(sl)), "0"(cmp)
1848 : "memory", "cc");
1849 return ret;
1850}
1851
1852static FORCEINLINE void x86_clear_lock(int* sl) {
1853 assert(*sl != 0);
1854 int prev = 0;
1855 int ret;
1856 __asm__ __volatile__ ("lock; xchgl %0, %1"
1857 : "=r" (ret)
1858 : "m" (*(sl)), "0"(prev)
1859 : "memory");
1860}
1861
1862#define CAS_LOCK(sl) x86_cas_lock(sl)
1863#define CLEAR_LOCK(sl) x86_clear_lock(sl)
1864
1865#else /* Win32 MSC */
1866#define CAS_LOCK(sl) interlockedexchange(sl, (LONG)1)
1867#define CLEAR_LOCK(sl) interlockedexchange (sl, (LONG)0)
1868
1869#endif /* ... gcc spins locks ... */
1870
1871/* How to yield for a spin lock */
1872#define SPINS_PER_YIELD 63
1873#if defined(_MSC_VER)
1874#define SLEEP_EX_DURATION 50 /* delay for yield/sleep */
1875#define SPIN_LOCK_YIELD SleepEx(SLEEP_EX_DURATION, FALSE)
1876#elif defined (__SVR4) && defined (__sun) /* solaris */
1877#define SPIN_LOCK_YIELD thr_yield();
1878#elif !defined(LACKS_SCHED_H)
1879#define SPIN_LOCK_YIELD sched_yield();
1880#else
1881#define SPIN_LOCK_YIELD
1882#endif /* ... yield ... */
1883
1884#if !defined(USE_RECURSIVE_LOCKS) || USE_RECURSIVE_LOCKS == 0
1885/* Plain spin locks use single word (embedded in malloc_states) */
1886static int spin_acquire_lock(int *sl) {
1887 int spins = 0;
1888 while (*(volatile int *)sl != 0 || CAS_LOCK(sl)) {
1889 if ((++spins & SPINS_PER_YIELD) == 0) {
1890 SPIN_LOCK_YIELD;
1891 }
1892 }
1893 return 0;
1894}
1895
1896#define MLOCK_T int
1897#define TRY_LOCK(sl) !CAS_LOCK(sl)
1898#define RELEASE_LOCK(sl) CLEAR_LOCK(sl)
1899#define ACQUIRE_LOCK(sl) (CAS_LOCK(sl)? spin_acquire_lock(sl) : 0)
1900#define INITIAL_LOCK(sl) (*sl = 0)
1901#define DESTROY_LOCK(sl) (0)
1902static MLOCK_T malloc_global_mutex = 0;
1903
1904#else /* USE_RECURSIVE_LOCKS */
1905/* types for lock owners */
1906#ifdef WIN32
1907#define THREAD_ID_T DWORD
1908#define CURRENT_THREAD GetCurrentThreadId()
1909#define EQ_OWNER(X,Y) ((X) == (Y))
1910#else
1911/*
1912 Note: the following assume that pthread_t is a type that can be
1913 initialized to (casted) zero. If this is not the case, you will need to
1914 somehow redefine these or not use spin locks.
1915*/
1916#define THREAD_ID_T pthread_t
1917#define CURRENT_THREAD pthread_self()
1918#define EQ_OWNER(X,Y) pthread_equal(X, Y)
1919#endif
1920
1921struct malloc_recursive_lock {
1922 int sl;
1923 unsigned int c;
1924 THREAD_ID_T threadid;
1925};
1926
1927#define MLOCK_T struct malloc_recursive_lock
1928static MLOCK_T malloc_global_mutex = { 0, 0, (THREAD_ID_T)0};
1929
1930static FORCEINLINE void recursive_release_lock(MLOCK_T *lk) {
1931 assert(lk->sl != 0);
1932 if (--lk->c == 0) {
1933 CLEAR_LOCK(&lk->sl);
1934 }
1935}
1936
1937static FORCEINLINE int recursive_acquire_lock(MLOCK_T *lk) {
1938 THREAD_ID_T mythreadid = CURRENT_THREAD;
1939 int spins = 0;
1940 for (;;) {
1941 if (*((volatile int *)(&lk->sl)) == 0) {
1942 if (!CAS_LOCK(&lk->sl)) {
1943 lk->threadid = mythreadid;
1944 lk->c = 1;
1945 return 0;
1946 }
1947 }
1948 else if (EQ_OWNER(lk->threadid, mythreadid)) {
1949 ++lk->c;
1950 return 0;
1951 }
1952 if ((++spins & SPINS_PER_YIELD) == 0) {
1953 SPIN_LOCK_YIELD;
1954 }
1955 }
1956}
1957
1958static FORCEINLINE int recursive_try_lock(MLOCK_T *lk) {
1959 THREAD_ID_T mythreadid = CURRENT_THREAD;
1960 if (*((volatile int *)(&lk->sl)) == 0) {
1961 if (!CAS_LOCK(&lk->sl)) {
1962 lk->threadid = mythreadid;
1963 lk->c = 1;
1964 return 1;
1965 }
1966 }
1967 else if (EQ_OWNER(lk->threadid, mythreadid)) {
1968 ++lk->c;
1969 return 1;
1970 }
1971 return 0;
1972}
1973
1974#define RELEASE_LOCK(lk) recursive_release_lock(lk)
1975#define TRY_LOCK(lk) recursive_try_lock(lk)
1976#define ACQUIRE_LOCK(lk) recursive_acquire_lock(lk)
1977#define INITIAL_LOCK(lk) ((lk)->threadid = (THREAD_ID_T)0, (lk)->sl = 0, (lk)->c = 0)
1978#define DESTROY_LOCK(lk) (0)
1979#endif /* USE_RECURSIVE_LOCKS */
1980
1981#elif defined(WIN32) /* Win32 critical sections */
1982#define MLOCK_T CRITICAL_SECTION
1983#define ACQUIRE_LOCK(lk) (EnterCriticalSection(lk), 0)
1984#define RELEASE_LOCK(lk) LeaveCriticalSection(lk)
1985#define TRY_LOCK(lk) TryEnterCriticalSection(lk)
1986#define INITIAL_LOCK(lk) (!InitializeCriticalSectionAndSpinCount((lk), 0x80000000|4000))
1987#define DESTROY_LOCK(lk) (DeleteCriticalSection(lk), 0)
1988#define NEED_GLOBAL_LOCK_INIT
1989
1990static MLOCK_T malloc_global_mutex;
1991static volatile LONG malloc_global_mutex_status;
1992
1993/* Use spin loop to initialize global lock */
1994static void init_malloc_global_mutex() {
1995 for (;;) {
1996 long stat = malloc_global_mutex_status;
1997 if (stat > 0)
1998 return;
1999 /* transition to < 0 while initializing, then to > 0) */
2000 if (stat == 0 &&
2001 interlockedcompareexchange(&malloc_global_mutex_status, (LONG)-1, (LONG)0) == 0) {
2002 InitializeCriticalSection(&malloc_global_mutex);
2003 interlockedexchange(&malloc_global_mutex_status, (LONG)1);
2004 return;
2005 }
2006 SleepEx(0, FALSE);
2007 }
2008}
2009
2010#else /* pthreads-based locks */
2011#define MLOCK_T pthread_mutex_t
2012#define ACQUIRE_LOCK(lk) pthread_mutex_lock(lk)
2013#define RELEASE_LOCK(lk) pthread_mutex_unlock(lk)
2014#define TRY_LOCK(lk) (!pthread_mutex_trylock(lk))
2015#define INITIAL_LOCK(lk) pthread_init_lock(lk)
2016#define DESTROY_LOCK(lk) pthread_mutex_destroy(lk)
2017
2018#if defined(USE_RECURSIVE_LOCKS) && USE_RECURSIVE_LOCKS != 0 && defined(linux) && !defined(PTHREAD_MUTEX_RECURSIVE)
2019/* Cope with old-style linux recursive lock initialization by adding */
2020/* skipped internal declaration from pthread.h */
2021extern int pthread_mutexattr_setkind_np __P ((pthread_mutexattr_t *__attr,
2022 int __kind));
2023#define PTHREAD_MUTEX_RECURSIVE PTHREAD_MUTEX_RECURSIVE_NP
2024#define pthread_mutexattr_settype(x,y) pthread_mutexattr_setkind_np(x,y)
2025#endif /* USE_RECURSIVE_LOCKS ... */
2026
2027static MLOCK_T malloc_global_mutex = PTHREAD_MUTEX_INITIALIZER;
2028
2029static int pthread_init_lock (MLOCK_T *lk) {
2030 pthread_mutexattr_t attr;
2031 if (pthread_mutexattr_init(&attr)) return 1;
2032#if defined(USE_RECURSIVE_LOCKS) && USE_RECURSIVE_LOCKS != 0
2033 if (pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE)) return 1;
2034#endif
2035 if (pthread_mutex_init(lk, &attr)) return 1;
2036 if (pthread_mutexattr_destroy(&attr)) return 1;
2037 return 0;
2038}
2039
2040#endif /* ... lock types ... */
2041
2042/* Common code for all lock types */
2043#define USE_LOCK_BIT (2U)
2044
2045#ifndef ACQUIRE_MALLOC_GLOBAL_LOCK
2046#define ACQUIRE_MALLOC_GLOBAL_LOCK() ACQUIRE_LOCK(&malloc_global_mutex);
2047#endif
2048
2049#ifndef RELEASE_MALLOC_GLOBAL_LOCK
2050#define RELEASE_MALLOC_GLOBAL_LOCK() RELEASE_LOCK(&malloc_global_mutex);
2051#endif
2052
2053#endif /* USE_LOCKS */
2054
2055/* ----------------------- Chunk representations ------------------------ */
2056
2057/*
2058 (The following includes lightly edited explanations by Colin Plumb.)
2059
2060 The malloc_chunk declaration below is misleading (but accurate and
2061 necessary). It declares a "view" into memory allowing access to
2062 necessary fields at known offsets from a given base.
2063
2064 Chunks of memory are maintained using a `boundary tag' method as
2065 originally described by Knuth. (See the paper by Paul Wilson
2066 ftp://ftp.cs.utexas.edu/pub/garbage/allocsrv.ps for a survey of such
2067 techniques.) Sizes of free chunks are stored both in the front of
2068 each chunk and at the end. This makes consolidating fragmented
2069 chunks into bigger chunks fast. The head fields also hold bits
2070 representing whether chunks are free or in use.
2071
2072 Here are some pictures to make it clearer. They are "exploded" to
2073 show that the state of a chunk can be thought of as extending from
2074 the high 31 bits of the head field of its header through the
2075 prev_foot and PINUSE_BIT bit of the following chunk header.
2076
2077 A chunk that's in use looks like:
2078
2079 chunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
2080 | Size of previous chunk (if P = 0) |
2081 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
2082 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ |P|
2083 | Size of this chunk 1| +-+
2084 mem-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
2085 | |
2086 +- -+
2087 | |
2088 +- -+
2089 | :
2090 +- size - sizeof(size_t) available payload bytes -+
2091 : |
2092 chunk-> +- -+
2093 | |
2094 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
2095 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ |1|
2096 | Size of next chunk (may or may not be in use) | +-+
2097 mem-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
2098
2099 And if it's free, it looks like this:
2100
2101 chunk-> +- -+
2102 | User payload (must be in use, or we would have merged!) |
2103 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
2104 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ |P|
2105 | Size of this chunk 0| +-+
2106 mem-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
2107 | Next pointer |
2108 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
2109 | Prev pointer |
2110 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
2111 | :
2112 +- size - sizeof(struct chunk) unused bytes -+
2113 : |
2114 chunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
2115 | Size of this chunk |
2116 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
2117 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ |0|
2118 | Size of next chunk (must be in use, or we would have merged)| +-+
2119 mem-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
2120 | :
2121 +- User payload -+
2122 : |
2123 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
2124 |0|
2125 +-+
2126 Note that since we always merge adjacent free chunks, the chunks
2127 adjacent to a free chunk must be in use.
2128
2129 Given a pointer to a chunk (which can be derived trivially from the
2130 payload pointer) we can, in O(1) time, find out whether the adjacent
2131 chunks are free, and if so, unlink them from the lists that they
2132 are on and merge them with the current chunk.
2133
2134 Chunks always begin on even word boundaries, so the mem portion
2135 (which is returned to the user) is also on an even word boundary, and
2136 thus at least double-word aligned.
2137
2138 The P (PINUSE_BIT) bit, stored in the unused low-order bit of the
2139 chunk size (which is always a multiple of two words), is an in-use
2140 bit for the *previous* chunk. If that bit is *clear*, then the
2141 word before the current chunk size contains the previous chunk
2142 size, and can be used to find the front of the previous chunk.
2143 The very first chunk allocated always has this bit set, preventing
2144 access to non-existent (or non-owned) memory. If pinuse is set for
2145 any given chunk, then you CANNOT determine the size of the
2146 previous chunk, and might even get a memory addressing fault when
2147 trying to do so.
2148
2149 The C (CINUSE_BIT) bit, stored in the unused second-lowest bit of
2150 the chunk size redundantly records whether the current chunk is
2151 inuse (unless the chunk is mmapped). This redundancy enables usage
2152 checks within free and realloc, and reduces indirection when freeing
2153 and consolidating chunks.
2154
2155 Each freshly allocated chunk must have both cinuse and pinuse set.
2156 That is, each allocated chunk borders either a previously allocated
2157 and still in-use chunk, or the base of its memory arena. This is
2158 ensured by making all allocations from the `lowest' part of any
2159 found chunk. Further, no free chunk physically borders another one,
2160 so each free chunk is known to be preceded and followed by either
2161 inuse chunks or the ends of memory.
2162
2163 Note that the `foot' of the current chunk is actually represented
2164 as the prev_foot of the NEXT chunk. This makes it easier to
2165 deal with alignments etc but can be very confusing when trying
2166 to extend or adapt this code.
2167
2168 The exceptions to all this are
2169
2170 1. The special chunk `top' is the top-most available chunk (i.e.,
2171 the one bordering the end of available memory). It is treated
2172 specially. Top is never included in any bin, is used only if
2173 no other chunk is available, and is released back to the
2174 system if it is very large (see M_TRIM_THRESHOLD). In effect,
2175 the top chunk is treated as larger (and thus less well
2176 fitting) than any other available chunk. The top chunk
2177 doesn't update its trailing size field since there is no next
2178 contiguous chunk that would have to index off it. However,
2179 space is still allocated for it (TOP_FOOT_SIZE) to enable
2180 separation or merging when space is extended.
2181
2182 3. Chunks allocated via mmap, have both cinuse and pinuse bits
2183 cleared in their head fields. Because they are allocated
2184 one-by-one, each must carry its own prev_foot field, which is
2185 also used to hold the offset this chunk has within its mmapped
2186 region, which is needed to preserve alignment. Each mmapped
2187 chunk is trailed by the first two fields of a fake next-chunk
2188 for sake of usage checks.
2189
2190*/
2191
2192struct malloc_chunk {
2193 size_t prev_foot; /* Size of previous chunk (if free). */
2194 size_t head; /* Size and inuse bits. */
2195 struct malloc_chunk* fd; /* double links -- used only if free. */
2196 struct malloc_chunk* bk;
2197};
2198
2199typedef struct malloc_chunk mchunk;
2200typedef struct malloc_chunk* mchunkptr;
2201typedef struct malloc_chunk* sbinptr; /* The type of bins of chunks */
2202typedef unsigned int bindex_t; /* Described below */
2203typedef unsigned int binmap_t; /* Described below */
2204typedef unsigned int flag_t; /* The type of various bit flag sets */
2205
2206/* ------------------- Chunks sizes and alignments ----------------------- */
2207
2208#define MCHUNK_SIZE (sizeof(mchunk))
2209
2210#if FOOTERS
2211#define CHUNK_OVERHEAD (TWO_SIZE_T_SIZES)
2212#else /* FOOTERS */
2213#define CHUNK_OVERHEAD (SIZE_T_SIZE)
2214#endif /* FOOTERS */
2215
2216/* MMapped chunks need a second word of overhead ... */
2217#define MMAP_CHUNK_OVERHEAD (TWO_SIZE_T_SIZES)
2218/* ... and additional padding for fake next-chunk at foot */
2219#define MMAP_FOOT_PAD (FOUR_SIZE_T_SIZES)
2220
2221/* The smallest size we can malloc is an aligned minimal chunk */
2222#define MIN_CHUNK_SIZE\
2223 ((MCHUNK_SIZE + CHUNK_ALIGN_MASK) & ~CHUNK_ALIGN_MASK)
2224
2225/* conversion from malloc headers to user pointers, and back */
2226#define chunk2mem(p) ((void*)((char*)(p) + TWO_SIZE_T_SIZES))
2227#define mem2chunk(mem) ((mchunkptr)((char*)(mem) - TWO_SIZE_T_SIZES))
2228/* chunk associated with aligned address A */
2229#define align_as_chunk(A) (mchunkptr)((A) + align_offset(chunk2mem(A)))
2230
2231/* Bounds on request (not chunk) sizes. */
2232#define MAX_REQUEST ((-MIN_CHUNK_SIZE) << 2)
2233#define MIN_REQUEST (MIN_CHUNK_SIZE - CHUNK_OVERHEAD - SIZE_T_ONE)
2234
2235/* pad request bytes into a usable size */
2236#define pad_request(req) \
2237 (((req) + CHUNK_OVERHEAD + CHUNK_ALIGN_MASK) & ~CHUNK_ALIGN_MASK)
2238
2239/* pad request, checking for minimum (but not maximum) */
2240#define request2size(req) \
2241 (((req) < MIN_REQUEST)? MIN_CHUNK_SIZE : pad_request(req))
2242
2243
2244/* ------------------ Operations on head and foot fields ----------------- */
2245
2246/*
2247 The head field of a chunk is or'ed with PINUSE_BIT when previous
2248 adjacent chunk in use, and or'ed with CINUSE_BIT if this chunk is in
2249 use, unless mmapped, in which case both bits are cleared.
2250
2251 FLAG4_BIT is not used by this malloc, but might be useful in extensions.
2252*/
2253
2254#define PINUSE_BIT (SIZE_T_ONE)
2255#define CINUSE_BIT (SIZE_T_TWO)
2256#define FLAG4_BIT (SIZE_T_FOUR)
2257#define INUSE_BITS (PINUSE_BIT|CINUSE_BIT)
2258#define FLAG_BITS (PINUSE_BIT|CINUSE_BIT|FLAG4_BIT)
2259
2260/* Head value for fenceposts */
2261#define FENCEPOST_HEAD (INUSE_BITS|SIZE_T_SIZE)
2262
2263/* extraction of fields from head words */
2264#define cinuse(p) ((p)->head & CINUSE_BIT)
2265#define pinuse(p) ((p)->head & PINUSE_BIT)
2266#define flag4inuse(p) ((p)->head & FLAG4_BIT)
2267#define is_inuse(p) (((p)->head & INUSE_BITS) != PINUSE_BIT)
2268#define is_mmapped(p) (((p)->head & INUSE_BITS) == 0)
2269
2270#define chunksize(p) ((p)->head & ~(FLAG_BITS))
2271
2272#define clear_pinuse(p) ((p)->head &= ~PINUSE_BIT)
2273#define set_flag4(p) ((p)->head |= FLAG4_BIT)
2274#define clear_flag4(p) ((p)->head &= ~FLAG4_BIT)
2275
2276/* Treat space at ptr +/- offset as a chunk */
2277#define chunk_plus_offset(p, s) ((mchunkptr)(((char*)(p)) + (s)))
2278#define chunk_minus_offset(p, s) ((mchunkptr)(((char*)(p)) - (s)))
2279
2280/* Ptr to next or previous physical malloc_chunk. */
2281#define next_chunk(p) ((mchunkptr)( ((char*)(p)) + ((p)->head & ~FLAG_BITS)))
2282#define prev_chunk(p) ((mchunkptr)( ((char*)(p)) - ((p)->prev_foot) ))
2283
2284/* extract next chunk's pinuse bit */
2285#define next_pinuse(p) ((next_chunk(p)->head) & PINUSE_BIT)
2286
2287/* Get/set size at footer */
2288#define get_foot(p, s) (((mchunkptr)((char*)(p) + (s)))->prev_foot)
2289#define set_foot(p, s) (((mchunkptr)((char*)(p) + (s)))->prev_foot = (s))
2290
2291/* Set size, pinuse bit, and foot */
2292#define set_size_and_pinuse_of_free_chunk(p, s)\
2293 ((p)->head = (s|PINUSE_BIT), set_foot(p, s))
2294
2295/* Set size, pinuse bit, foot, and clear next pinuse */
2296#define set_free_with_pinuse(p, s, n)\
2297 (clear_pinuse(n), set_size_and_pinuse_of_free_chunk(p, s))
2298
2299/* Get the internal overhead associated with chunk p */
2300#define overhead_for(p)\
2301 (is_mmapped(p)? MMAP_CHUNK_OVERHEAD : CHUNK_OVERHEAD)
2302
2303/* Return true if malloced space is not necessarily cleared */
2304#if MMAP_CLEARS
2305#define calloc_must_clear(p) (!is_mmapped(p))
2306#else /* MMAP_CLEARS */
2307#define calloc_must_clear(p) (1)
2308#endif /* MMAP_CLEARS */
2309
2310/* ---------------------- Overlaid data structures ----------------------- */
2311
2312/*
2313 When chunks are not in use, they are treated as nodes of either
2314 lists or trees.
2315
2316 "Small" chunks are stored in circular doubly-linked lists, and look
2317 like this:
2318
2319 chunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
2320 | Size of previous chunk |
2321 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
2322 `head:' | Size of chunk, in bytes |P|
2323 mem-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
2324 | Forward pointer to next chunk in list |
2325 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
2326 | Back pointer to previous chunk in list |
2327 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
2328 | Unused space (may be 0 bytes long) .
2329 . .
2330 . |
2331nextchunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
2332 `foot:' | Size of chunk, in bytes |
2333 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
2334
2335 Larger chunks are kept in a form of bitwise digital trees (aka
2336 tries) keyed on chunksizes. Because malloc_tree_chunks are only for
2337 free chunks greater than 256 bytes, their size doesn't impose any
2338 constraints on user chunk sizes. Each node looks like:
2339
2340 chunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
2341 | Size of previous chunk |
2342 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
2343 `head:' | Size of chunk, in bytes |P|
2344 mem-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
2345 | Forward pointer to next chunk of same size |
2346 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
2347 | Back pointer to previous chunk of same size |
2348 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
2349 | Pointer to left child (child[0]) |
2350 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
2351 | Pointer to right child (child[1]) |
2352 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
2353 | Pointer to parent |
2354 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
2355 | bin index of this chunk |
2356 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
2357 | Unused space .
2358 . |
2359nextchunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
2360 `foot:' | Size of chunk, in bytes |
2361 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
2362
2363 Each tree holding treenodes is a tree of unique chunk sizes. Chunks
2364 of the same size are arranged in a circularly-linked list, with only
2365 the oldest chunk (the next to be used, in our FIFO ordering)
2366 actually in the tree. (Tree members are distinguished by a non-null
2367 parent pointer.) If a chunk with the same size an an existing node
2368 is inserted, it is linked off the existing node using pointers that
2369 work in the same way as fd/bk pointers of small chunks.
2370
2371 Each tree contains a power of 2 sized range of chunk sizes (the
2372 smallest is 0x100 <= x < 0x180), which is is divided in half at each
2373 tree level, with the chunks in the smaller half of the range (0x100
2374 <= x < 0x140 for the top nose) in the left subtree and the larger
2375 half (0x140 <= x < 0x180) in the right subtree. This is, of course,
2376 done by inspecting individual bits.
2377
2378 Using these rules, each node's left subtree contains all smaller
2379 sizes than its right subtree. However, the node at the root of each
2380 subtree has no particular ordering relationship to either. (The
2381 dividing line between the subtree sizes is based on trie relation.)
2382 If we remove the last chunk of a given size from the interior of the
2383 tree, we need to replace it with a leaf node. The tree ordering
2384 rules permit a node to be replaced by any leaf below it.
2385
2386 The smallest chunk in a tree (a common operation in a best-fit
2387 allocator) can be found by walking a path to the leftmost leaf in
2388 the tree. Unlike a usual binary tree, where we follow left child
2389 pointers until we reach a null, here we follow the right child
2390 pointer any time the left one is null, until we reach a leaf with
2391 both child pointers null. The smallest chunk in the tree will be
2392 somewhere along that path.
2393
2394 The worst case number of steps to add, find, or remove a node is
2395 bounded by the number of bits differentiating chunks within
2396 bins. Under current bin calculations, this ranges from 6 up to 21
2397 (for 32 bit sizes) or up to 53 (for 64 bit sizes). The typical case
2398 is of course much better.
2399*/
2400
2401struct malloc_tree_chunk {
2402 /* The first four fields must be compatible with malloc_chunk */
2403 size_t prev_foot;
2404 size_t head;
2405 struct malloc_tree_chunk* fd;
2406 struct malloc_tree_chunk* bk;
2407
2408 struct malloc_tree_chunk* child[2];
2409 struct malloc_tree_chunk* parent;
2410 bindex_t index;
2411};
2412
2413typedef struct malloc_tree_chunk tchunk;
2414typedef struct malloc_tree_chunk* tchunkptr;
2415typedef struct malloc_tree_chunk* tbinptr; /* The type of bins of trees */
2416
2417/* A little helper macro for trees */
2418#define leftmost_child(t) ((t)->child[0] != 0? (t)->child[0] : (t)->child[1])
2419
2420/* ----------------------------- Segments -------------------------------- */
2421
2422/*
2423 Each malloc space may include non-contiguous segments, held in a
2424 list headed by an embedded malloc_segment record representing the
2425 top-most space. Segments also include flags holding properties of
2426 the space. Large chunks that are directly allocated by mmap are not
2427 included in this list. They are instead independently created and
2428 destroyed without otherwise keeping track of them.
2429
2430 Segment management mainly comes into play for spaces allocated by
2431 MMAP. Any call to MMAP might or might not return memory that is
2432 adjacent to an existing segment. MORECORE normally contiguously
2433 extends the current space, so this space is almost always adjacent,
2434 which is simpler and faster to deal with. (This is why MORECORE is
2435 used preferentially to MMAP when both are available -- see
2436 sys_alloc.) When allocating using MMAP, we don't use any of the
2437 hinting mechanisms (inconsistently) supported in various
2438 implementations of unix mmap, or distinguish reserving from
2439 committing memory. Instead, we just ask for space, and exploit
2440 contiguity when we get it. It is probably possible to do
2441 better than this on some systems, but no general scheme seems
2442 to be significantly better.
2443
2444 Management entails a simpler variant of the consolidation scheme
2445 used for chunks to reduce fragmentation -- new adjacent memory is
2446 normally prepended or appended to an existing segment. However,
2447 there are limitations compared to chunk consolidation that mostly
2448 reflect the fact that segment processing is relatively infrequent
2449 (occurring only when getting memory from system) and that we
2450 don't expect to have huge numbers of segments:
2451
2452 * Segments are not indexed, so traversal requires linear scans. (It
2453 would be possible to index these, but is not worth the extra
2454 overhead and complexity for most programs on most platforms.)
2455 * New segments are only appended to old ones when holding top-most
2456 memory; if they cannot be prepended to others, they are held in
2457 different segments.
2458
2459 Except for the top-most segment of an mstate, each segment record
2460 is kept at the tail of its segment. Segments are added by pushing
2461 segment records onto the list headed by &mstate.seg for the
2462 containing mstate.
2463
2464 Segment flags control allocation/merge/deallocation policies:
2465 * If EXTERN_BIT set, then we did not allocate this segment,
2466 and so should not try to deallocate or merge with others.
2467 (This currently holds only for the initial segment passed
2468 into create_mspace_with_base.)
2469 * If USE_MMAP_BIT set, the segment may be merged with
2470 other surrounding mmapped segments and trimmed/de-allocated
2471 using munmap.
2472 * If neither bit is set, then the segment was obtained using
2473 MORECORE so can be merged with surrounding MORECORE'd segments
2474 and deallocated/trimmed using MORECORE with negative arguments.
2475*/
2476
2477struct malloc_segment {
2478 char* base; /* base address */
2479 size_t size; /* allocated size */
2480 struct malloc_segment* next; /* ptr to next segment */
2481 flag_t sflags; /* mmap and extern flag */
2482};
2483
2484#define is_mmapped_segment(S) ((S)->sflags & USE_MMAP_BIT)
2485#define is_extern_segment(S) ((S)->sflags & EXTERN_BIT)
2486
2487typedef struct malloc_segment msegment;
2488typedef struct malloc_segment* msegmentptr;
2489
2490/* ---------------------------- malloc_state ----------------------------- */
2491
2492/*
2493 A malloc_state holds all of the bookkeeping for a space.
2494 The main fields are:
2495
2496 Top
2497 The topmost chunk of the currently active segment. Its size is
2498 cached in topsize. The actual size of topmost space is
2499 topsize+TOP_FOOT_SIZE, which includes space reserved for adding
2500 fenceposts and segment records if necessary when getting more
2501 space from the system. The size at which to autotrim top is
2502 cached from mparams in trim_check, except that it is disabled if
2503 an autotrim fails.
2504
2505 Designated victim (dv)
2506 This is the preferred chunk for servicing small requests that
2507 don't have exact fits. It is normally the chunk split off most
2508 recently to service another small request. Its size is cached in
2509 dvsize. The link fields of this chunk are not maintained since it
2510 is not kept in a bin.
2511
2512 SmallBins
2513 An array of bin headers for free chunks. These bins hold chunks
2514 with sizes less than MIN_LARGE_SIZE bytes. Each bin contains
2515 chunks of all the same size, spaced 8 bytes apart. To simplify
2516 use in double-linked lists, each bin header acts as a malloc_chunk
2517 pointing to the real first node, if it exists (else pointing to
2518 itself). This avoids special-casing for headers. But to avoid
2519 waste, we allocate only the fd/bk pointers of bins, and then use
2520 repositioning tricks to treat these as the fields of a chunk.
2521
2522 TreeBins
2523 Treebins are pointers to the roots of trees holding a range of
2524 sizes. There are 2 equally spaced treebins for each power of two
2525 from TREE_SHIFT to TREE_SHIFT+16. The last bin holds anything
2526 larger.
2527
2528 Bin maps
2529 There is one bit map for small bins ("smallmap") and one for
2530 treebins ("treemap). Each bin sets its bit when non-empty, and
2531 clears the bit when empty. Bit operations are then used to avoid
2532 bin-by-bin searching -- nearly all "search" is done without ever
2533 looking at bins that won't be selected. The bit maps
2534 conservatively use 32 bits per map word, even if on 64bit system.
2535 For a good description of some of the bit-based techniques used
2536 here, see Henry S. Warren Jr's book "Hacker's Delight" (and
2537 supplement at http://hackersdelight.org/). Many of these are
2538 intended to reduce the branchiness of paths through malloc etc, as
2539 well as to reduce the number of memory locations read or written.
2540
2541 Segments
2542 A list of segments headed by an embedded malloc_segment record
2543 representing the initial space.
2544
2545 Address check support
2546 The least_addr field is the least address ever obtained from
2547 MORECORE or MMAP. Attempted frees and reallocs of any address less
2548 than this are trapped (unless INSECURE is defined).
2549
2550 Magic tag
2551 A cross-check field that should always hold same value as mparams.magic.
2552
2553 Max allowed footprint
2554 The maximum allowed bytes to allocate from system (zero means no limit)
2555
2556 Flags
2557 Bits recording whether to use MMAP, locks, or contiguous MORECORE
2558
2559 Statistics
2560 Each space keeps track of current and maximum system memory
2561 obtained via MORECORE or MMAP.
2562
2563 Trim support
2564 Fields holding the amount of unused topmost memory that should trigger
2565 trimming, and a counter to force periodic scanning to release unused
2566 non-topmost segments.
2567
2568 Locking
2569 If USE_LOCKS is defined, the "mutex" lock is acquired and released
2570 around every public call using this mspace.
2571
2572 Extension support
2573 A void* pointer and a size_t field that can be used to help implement
2574 extensions to this malloc.
2575*/
2576
2577/* Bin types, widths and sizes */
2578#define NSMALLBINS (32U)
2579#define NTREEBINS (32U)
2580#define SMALLBIN_SHIFT (3U)
2581#define SMALLBIN_WIDTH (SIZE_T_ONE << SMALLBIN_SHIFT)
2582#define TREEBIN_SHIFT (8U)
2583#define MIN_LARGE_SIZE (SIZE_T_ONE << TREEBIN_SHIFT)
2584#define MAX_SMALL_SIZE (MIN_LARGE_SIZE - SIZE_T_ONE)
2585#define MAX_SMALL_REQUEST (MAX_SMALL_SIZE - CHUNK_ALIGN_MASK - CHUNK_OVERHEAD)
2586
2587struct malloc_state {
2588 binmap_t smallmap;
2589 binmap_t treemap;
2590 size_t dvsize;
2591 size_t topsize;
2592 char* least_addr;
2593 mchunkptr dv;
2594 mchunkptr top;
2595 size_t trim_check;
2596 size_t release_checks;
2597 size_t magic;
2598 mchunkptr smallbins[(NSMALLBINS+1)*2];
2599 tbinptr treebins[NTREEBINS];
2600 size_t footprint;
2601 size_t max_footprint;
2602 size_t footprint_limit; /* zero means no limit */
2603 flag_t mflags;
2604#if USE_LOCKS
2605 MLOCK_T mutex; /* locate lock among fields that rarely change */
2606#endif /* USE_LOCKS */
2607 msegment seg;
2608 void* extp; /* Unused but available for extensions */
2609 size_t exts;
2610};
2611
2612typedef struct malloc_state* mstate;
2613
2614/* ------------- Global malloc_state and malloc_params ------------------- */
2615
2616/*
2617 malloc_params holds global properties, including those that can be
2618 dynamically set using mallopt. There is a single instance, mparams,
2619 initialized in init_mparams. Note that the non-zeroness of "magic"
2620 also serves as an initialization flag.
2621*/
2622
2623struct malloc_params {
2624 size_t magic;
2625 size_t page_size;
2626 size_t granularity;
2627 size_t mmap_threshold;
2628 size_t trim_threshold;
2629 flag_t default_mflags;
2630};
2631
2632static struct malloc_params mparams;
2633
2634/* Ensure mparams initialized */
2635#define ensure_initialization() (void)(mparams.magic != 0 || init_mparams())
2636
2637#if !ONLY_MSPACES
2638
2639/* The global malloc_state used for all non-"mspace" calls */
2640static struct malloc_state _gm_;
2641#define gm (&_gm_)
2642#define is_global(M) ((M) == &_gm_)
2643
2644#endif /* !ONLY_MSPACES */
2645
2646#define is_initialized(M) ((M)->top != 0)
2647
2648/* -------------------------- system alloc setup ------------------------- */
2649
2650/* Operations on mflags */
2651
2652#define use_lock(M) ((M)->mflags & USE_LOCK_BIT)
2653#define enable_lock(M) ((M)->mflags |= USE_LOCK_BIT)
2654#if USE_LOCKS
2655#define disable_lock(M) ((M)->mflags &= ~USE_LOCK_BIT)
2656#else
2657#define disable_lock(M)
2658#endif
2659
2660#define use_mmap(M) ((M)->mflags & USE_MMAP_BIT)
2661#define enable_mmap(M) ((M)->mflags |= USE_MMAP_BIT)
2662#if HAVE_MMAP
2663#define disable_mmap(M) ((M)->mflags &= ~USE_MMAP_BIT)
2664#else
2665#define disable_mmap(M)
2666#endif
2667
2668#define use_noncontiguous(M) ((M)->mflags & USE_NONCONTIGUOUS_BIT)
2669#define disable_contiguous(M) ((M)->mflags |= USE_NONCONTIGUOUS_BIT)
2670
2671#define set_lock(M,L)\
2672 ((M)->mflags = (L)?\
2673 ((M)->mflags | USE_LOCK_BIT) :\
2674 ((M)->mflags & ~USE_LOCK_BIT))
2675
2676/* page-align a size */
2677#define page_align(S)\
2678 (((S) + (mparams.page_size - SIZE_T_ONE)) & ~(mparams.page_size - SIZE_T_ONE))
2679
2680/* granularity-align a size */
2681#define granularity_align(S)\
2682 (((S) + (mparams.granularity - SIZE_T_ONE))\
2683 & ~(mparams.granularity - SIZE_T_ONE))
2684
2685
2686/* For mmap, use granularity alignment on windows, else page-align */
2687#ifdef WIN32
2688#define mmap_align(S) granularity_align(S)
2689#else
2690#define mmap_align(S) page_align(S)
2691#endif
2692
2693/* For sys_alloc, enough padding to ensure can malloc request on success */
2694#define SYS_ALLOC_PADDING (TOP_FOOT_SIZE + MALLOC_ALIGNMENT)
2695
2696#define is_page_aligned(S)\
2697 (((size_t)(S) & (mparams.page_size - SIZE_T_ONE)) == 0)
2698#define is_granularity_aligned(S)\
2699 (((size_t)(S) & (mparams.granularity - SIZE_T_ONE)) == 0)
2700
2701/* True if segment S holds address A */
2702#define segment_holds(S, A)\
2703 ((char*)(A) >= S->base && (char*)(A) < S->base + S->size)
2704
2705/* Return segment holding given address */
2706static msegmentptr segment_holding(mstate m, char* addr) {
2707 msegmentptr sp = &m->seg;
2708 for (;;) {
2709 if (addr >= sp->base && addr < sp->base + sp->size)
2710 return sp;
2711 if ((sp = sp->next) == 0)
2712 return 0;
2713 }
2714}
2715
2716/* Return true if segment contains a segment link */
2717static int has_segment_link(mstate m, msegmentptr ss) {
2718 msegmentptr sp = &m->seg;
2719 for (;;) {
2720 if ((char*)sp >= ss->base && (char*)sp < ss->base + ss->size)
2721 return 1;
2722 if ((sp = sp->next) == 0)
2723 return 0;
2724 }
2725}
2726
2727#ifndef MORECORE_CANNOT_TRIM
2728#define should_trim(M,s) ((s) > (M)->trim_check)
2729#else /* MORECORE_CANNOT_TRIM */
2730#define should_trim(M,s) (0)
2731#endif /* MORECORE_CANNOT_TRIM */
2732
2733/*
2734 TOP_FOOT_SIZE is padding at the end of a segment, including space
2735 that may be needed to place segment records and fenceposts when new
2736 noncontiguous segments are added.
2737*/
2738#define TOP_FOOT_SIZE\
2739 (align_offset(chunk2mem(0))+pad_request(sizeof(struct malloc_segment))+MIN_CHUNK_SIZE)
2740
2741
2742/* ------------------------------- Hooks -------------------------------- */
2743
2744/*
2745 PREACTION should be defined to return 0 on success, and nonzero on
2746 failure. If you are not using locking, you can redefine these to do
2747 anything you like.
2748*/
2749
2750#if USE_LOCKS
2751#define PREACTION(M) ((use_lock(M))? ACQUIRE_LOCK(&(M)->mutex) : 0)
2752#define POSTACTION(M) { if (use_lock(M)) RELEASE_LOCK(&(M)->mutex); }
2753#else /* USE_LOCKS */
2754
2755#ifndef PREACTION
2756#define PREACTION(M) (0)
2757#endif /* PREACTION */
2758
2759#ifndef POSTACTION
2760#define POSTACTION(M)
2761#endif /* POSTACTION */
2762
2763#endif /* USE_LOCKS */
2764
2765/*
2766 CORRUPTION_ERROR_ACTION is triggered upon detected bad addresses.
2767 USAGE_ERROR_ACTION is triggered on detected bad frees and
2768 reallocs. The argument p is an address that might have triggered the
2769 fault. It is ignored by the two predefined actions, but might be
2770 useful in custom actions that try to help diagnose errors.
2771*/
2772
2773#if PROCEED_ON_ERROR
2774
2775/* A count of the number of corruption errors causing resets */
2776int malloc_corruption_error_count;
2777
2778/* default corruption action */
2779static void reset_on_error(mstate m);
2780
2781#define CORRUPTION_ERROR_ACTION(m) reset_on_error(m)
2782#define USAGE_ERROR_ACTION(m, p)
2783
2784#else /* PROCEED_ON_ERROR */
2785
2786#ifndef CORRUPTION_ERROR_ACTION
2787#define CORRUPTION_ERROR_ACTION(m) ABORT
2788#endif /* CORRUPTION_ERROR_ACTION */
2789
2790#ifndef USAGE_ERROR_ACTION
2791#define USAGE_ERROR_ACTION(m,p) ABORT
2792#endif /* USAGE_ERROR_ACTION */
2793
2794#endif /* PROCEED_ON_ERROR */
2795
2796
2797/* -------------------------- Debugging setup ---------------------------- */
2798
2799#if ! DEBUG
2800
2801#define check_free_chunk(M,P)
2802#define check_inuse_chunk(M,P)
2803#define check_malloced_chunk(M,P,N)
2804#define check_mmapped_chunk(M,P)
2805#define check_malloc_state(M)
2806#define check_top_chunk(M,P)
2807
2808#else /* DEBUG */
2809#define check_free_chunk(M,P) do_check_free_chunk(M,P)
2810#define check_inuse_chunk(M,P) do_check_inuse_chunk(M,P)
2811#define check_top_chunk(M,P) do_check_top_chunk(M,P)
2812#define check_malloced_chunk(M,P,N) do_check_malloced_chunk(M,P,N)
2813#define check_mmapped_chunk(M,P) do_check_mmapped_chunk(M,P)
2814#define check_malloc_state(M) do_check_malloc_state(M)
2815
2816static void do_check_any_chunk(mstate m, mchunkptr p);
2817static void do_check_top_chunk(mstate m, mchunkptr p);
2818static void do_check_mmapped_chunk(mstate m, mchunkptr p);
2819static void do_check_inuse_chunk(mstate m, mchunkptr p);
2820static void do_check_free_chunk(mstate m, mchunkptr p);
2821static void do_check_malloced_chunk(mstate m, void* mem, size_t s);
2822static void do_check_tree(mstate m, tchunkptr t);
2823static void do_check_treebin(mstate m, bindex_t i);
2824static void do_check_smallbin(mstate m, bindex_t i);
2825static void do_check_malloc_state(mstate m);
2826static int bin_find(mstate m, mchunkptr x);
2827static size_t traverse_and_check(mstate m);
2828#endif /* DEBUG */
2829
2830/* ---------------------------- Indexing Bins ---------------------------- */
2831
2832#define is_small(s) (((s) >> SMALLBIN_SHIFT) < NSMALLBINS)
2833#define small_index(s) (bindex_t)((s) >> SMALLBIN_SHIFT)
2834#define small_index2size(i) ((i) << SMALLBIN_SHIFT)
2835#define MIN_SMALL_INDEX (small_index(MIN_CHUNK_SIZE))
2836
2837/* addressing by index. See above about smallbin repositioning */
2838#define smallbin_at(M, i) ((sbinptr)((char*)&((M)->smallbins[(i)<<1])))
2839#define treebin_at(M,i) (&((M)->treebins[i]))
2840
2841/* assign tree index for size S to variable I. Use x86 asm if possible */
2842#if defined(__GNUC__) && (defined(__i386__) || defined(__x86_64__))
2843#define compute_tree_index(S, I)\
2844{\
2845 unsigned int X = S >> TREEBIN_SHIFT;\
2846 if (X == 0)\
2847 I = 0;\
2848 else if (X > 0xFFFF)\
2849 I = NTREEBINS-1;\
2850 else {\
2851 unsigned int K = (unsigned) sizeof(X)*__CHAR_BIT__ - 1 - (unsigned) __builtin_clz(X); \
2852 I = (bindex_t)((K << 1) + ((S >> (K + (TREEBIN_SHIFT-1)) & 1)));\
2853 }\
2854}
2855
2856#elif defined (__INTEL_COMPILER)
2857#define compute_tree_index(S, I)\
2858{\
2859 size_t X = S >> TREEBIN_SHIFT;\
2860 if (X == 0)\
2861 I = 0;\
2862 else if (X > 0xFFFF)\
2863 I = NTREEBINS-1;\
2864 else {\
2865 unsigned int K = _bit_scan_reverse (X); \
2866 I = (bindex_t)((K << 1) + ((S >> (K + (TREEBIN_SHIFT-1)) & 1)));\
2867 }\
2868}
2869
2870#elif defined(_MSC_VER) && _MSC_VER>=1300
2871#define compute_tree_index(S, I)\
2872{\
2873 size_t X = S >> TREEBIN_SHIFT;\
2874 if (X == 0)\
2875 I = 0;\
2876 else if (X > 0xFFFF)\
2877 I = NTREEBINS-1;\
2878 else {\
2879 unsigned int K;\
2880 _BitScanReverse((DWORD *) &K, (DWORD) X);\
2881 I = (bindex_t)((K << 1) + ((S >> (K + (TREEBIN_SHIFT-1)) & 1)));\
2882 }\
2883}
2884
2885#else /* GNUC */
2886#define compute_tree_index(S, I)\
2887{\
2888 size_t X = S >> TREEBIN_SHIFT;\
2889 if (X == 0)\
2890 I = 0;\
2891 else if (X > 0xFFFF)\
2892 I = NTREEBINS-1;\
2893 else {\
2894 unsigned int Y = (unsigned int)X;\
2895 unsigned int N = ((Y - 0x100) >> 16) & 8;\
2896 unsigned int K = (((Y <<= N) - 0x1000) >> 16) & 4;\
2897 N += K;\
2898 N += K = (((Y <<= K) - 0x4000) >> 16) & 2;\
2899 K = 14 - N + ((Y <<= K) >> 15);\
2900 I = (K << 1) + ((S >> (K + (TREEBIN_SHIFT-1)) & 1));\
2901 }\
2902}
2903#endif /* GNUC */
2904
2905/* Bit representing maximum resolved size in a treebin at i */
2906#define bit_for_tree_index(i) \
2907 (i == NTREEBINS-1)? (SIZE_T_BITSIZE-1) : (((i) >> 1) + TREEBIN_SHIFT - 2)
2908
2909/* Shift placing maximum resolved bit in a treebin at i as sign bit */
2910#define leftshift_for_tree_index(i) \
2911 ((i == NTREEBINS-1)? 0 : \
2912 ((SIZE_T_BITSIZE-SIZE_T_ONE) - (((i) >> 1) + TREEBIN_SHIFT - 2)))
2913
2914/* The size of the smallest chunk held in bin with index i */
2915#define minsize_for_tree_index(i) \
2916 ((SIZE_T_ONE << (((i) >> 1) + TREEBIN_SHIFT)) | \
2917 (((size_t)((i) & SIZE_T_ONE)) << (((i) >> 1) + TREEBIN_SHIFT - 1)))
2918
2919
2920/* ------------------------ Operations on bin maps ----------------------- */
2921
2922/* bit corresponding to given index */
2923#define idx2bit(i) ((binmap_t)(1) << (i))
2924
2925/* Mark/Clear bits with given index */
2926#define mark_smallmap(M,i) ((M)->smallmap |= idx2bit(i))
2927#define clear_smallmap(M,i) ((M)->smallmap &= ~idx2bit(i))
2928#define smallmap_is_marked(M,i) ((M)->smallmap & idx2bit(i))
2929
2930#define mark_treemap(M,i) ((M)->treemap |= idx2bit(i))
2931#define clear_treemap(M,i) ((M)->treemap &= ~idx2bit(i))
2932#define treemap_is_marked(M,i) ((M)->treemap & idx2bit(i))
2933
2934/* isolate the least set bit of a bitmap */
2935#define least_bit(x) ((x) & -(x))
2936
2937/* mask with all bits to left of least bit of x on */
2938#define left_bits(x) ((x<<1) | -(x<<1))
2939
2940/* mask with all bits to left of or equal to least bit of x on */
2941#define same_or_left_bits(x) ((x) | -(x))
2942
2943/* index corresponding to given bit. Use x86 asm if possible */
2944
2945#if defined(__GNUC__) && (defined(__i386__) || defined(__x86_64__))
2946#define compute_bit2idx(X, I)\
2947{\
2948 unsigned int J;\
2949 J = __builtin_ctz(X); \
2950 I = (bindex_t)J;\
2951}
2952
2953#elif defined (__INTEL_COMPILER)
2954#define compute_bit2idx(X, I)\
2955{\
2956 unsigned int J;\
2957 J = _bit_scan_forward (X); \
2958 I = (bindex_t)J;\
2959}
2960
2961#elif defined(_MSC_VER) && _MSC_VER>=1300
2962#define compute_bit2idx(X, I)\
2963{\
2964 unsigned int J;\
2965 _BitScanForward((DWORD *) &J, X);\
2966 I = (bindex_t)J;\
2967}
2968
2969#elif USE_BUILTIN_FFS
2970#define compute_bit2idx(X, I) I = ffs(X)-1
2971
2972#else
2973#define compute_bit2idx(X, I)\
2974{\
2975 unsigned int Y = X - 1;\
2976 unsigned int K = Y >> (16-4) & 16;\
2977 unsigned int N = K; Y >>= K;\
2978 N += K = Y >> (8-3) & 8; Y >>= K;\
2979 N += K = Y >> (4-2) & 4; Y >>= K;\
2980 N += K = Y >> (2-1) & 2; Y >>= K;\
2981 N += K = Y >> (1-0) & 1; Y >>= K;\
2982 I = (bindex_t)(N + Y);\
2983}
2984#endif /* GNUC */
2985
2986
2987/* ----------------------- Runtime Check Support ------------------------- */
2988
2989/*
2990 For security, the main invariant is that malloc/free/etc never
2991 writes to a static address other than malloc_state, unless static
2992 malloc_state itself has been corrupted, which cannot occur via
2993 malloc (because of these checks). In essence this means that we
2994 believe all pointers, sizes, maps etc held in malloc_state, but
2995 check all of those linked or offsetted from other embedded data
2996 structures. These checks are interspersed with main code in a way
2997 that tends to minimize their run-time cost.
2998
2999 When FOOTERS is defined, in addition to range checking, we also
3000 verify footer fields of inuse chunks, which can be used guarantee
3001 that the mstate controlling malloc/free is intact. This is a
3002 streamlined version of the approach described by William Robertson
3003 et al in "Run-time Detection of Heap-based Overflows" LISA'03
3004 http://www.usenix.org/events/lisa03/tech/robertson.html The footer
3005 of an inuse chunk holds the xor of its mstate and a random seed,
3006 that is checked upon calls to free() and realloc(). This is
3007 (probabalistically) unguessable from outside the program, but can be
3008 computed by any code successfully malloc'ing any chunk, so does not
3009 itself provide protection against code that has already broken
3010 security through some other means. Unlike Robertson et al, we
3011 always dynamically check addresses of all offset chunks (previous,
3012 next, etc). This turns out to be cheaper than relying on hashes.
3013*/
3014
3015#if !INSECURE
3016/* Check if address a is at least as high as any from MORECORE or MMAP */
3017#define ok_address(M, a) ((char*)(a) >= (M)->least_addr)
3018/* Check if address of next chunk n is higher than base chunk p */
3019#define ok_next(p, n) ((char*)(p) < (char*)(n))
3020/* Check if p has inuse status */
3021#define ok_inuse(p) is_inuse(p)
3022/* Check if p has its pinuse bit on */
3023#define ok_pinuse(p) pinuse(p)
3024
3025#else /* !INSECURE */
3026#define ok_address(M, a) (1)
3027#define ok_next(b, n) (1)
3028#define ok_inuse(p) (1)
3029#define ok_pinuse(p) (1)
3030#endif /* !INSECURE */
3031
3032#if (FOOTERS && !INSECURE)
3033/* Check if (alleged) mstate m has expected magic field */
3034#define ok_magic(M) ((M)->magic == mparams.magic)
3035#else /* (FOOTERS && !INSECURE) */
3036#define ok_magic(M) (1)
3037#endif /* (FOOTERS && !INSECURE) */
3038
3039/* In gcc, use __builtin_expect to minimize impact of checks */
3040#if !INSECURE
3041#if defined(__GNUC__) && __GNUC__ >= 3
3042#define RTCHECK(e) __builtin_expect(e, 1)
3043#else /* GNUC */
3044#define RTCHECK(e) (e)
3045#endif /* GNUC */
3046#else /* !INSECURE */
3047#define RTCHECK(e) (1)
3048#endif /* !INSECURE */
3049
3050/* macros to set up inuse chunks with or without footers */
3051
3052#if !FOOTERS
3053
3054#define mark_inuse_foot(M,p,s)
3055
3056/* Macros for setting head/foot of non-mmapped chunks */
3057
3058/* Set cinuse bit and pinuse bit of next chunk */
3059#define set_inuse(M,p,s)\
3060 ((p)->head = (((p)->head & PINUSE_BIT)|s|CINUSE_BIT),\
3061 ((mchunkptr)(((char*)(p)) + (s)))->head |= PINUSE_BIT)
3062
3063/* Set cinuse and pinuse of this chunk and pinuse of next chunk */
3064#define set_inuse_and_pinuse(M,p,s)\
3065 ((p)->head = (s|PINUSE_BIT|CINUSE_BIT),\
3066 ((mchunkptr)(((char*)(p)) + (s)))->head |= PINUSE_BIT)
3067
3068/* Set size, cinuse and pinuse bit of this chunk */
3069#define set_size_and_pinuse_of_inuse_chunk(M, p, s)\
3070 ((p)->head = (s|PINUSE_BIT|CINUSE_BIT))
3071
3072#else /* FOOTERS */
3073
3074/* Set foot of inuse chunk to be xor of mstate and seed */
3075#define mark_inuse_foot(M,p,s)\
3076 (((mchunkptr)((char*)(p) + (s)))->prev_foot = ((size_t)(M) ^ mparams.magic))
3077
3078#define get_mstate_for(p)\
3079 ((mstate)(((mchunkptr)((char*)(p) +\
3080 (chunksize(p))))->prev_foot ^ mparams.magic))
3081
3082#define set_inuse(M,p,s)\
3083 ((p)->head = (((p)->head & PINUSE_BIT)|s|CINUSE_BIT),\
3084 (((mchunkptr)(((char*)(p)) + (s)))->head |= PINUSE_BIT), \
3085 mark_inuse_foot(M,p,s))
3086
3087#define set_inuse_and_pinuse(M,p,s)\
3088 ((p)->head = (s|PINUSE_BIT|CINUSE_BIT),\
3089 (((mchunkptr)(((char*)(p)) + (s)))->head |= PINUSE_BIT),\
3090 mark_inuse_foot(M,p,s))
3091
3092#define set_size_and_pinuse_of_inuse_chunk(M, p, s)\
3093 ((p)->head = (s|PINUSE_BIT|CINUSE_BIT),\
3094 mark_inuse_foot(M, p, s))
3095
3096#endif /* !FOOTERS */
3097
3098/* ---------------------------- setting mparams -------------------------- */
3099
3100#if LOCK_AT_FORK
3101static void pre_fork(void) { ACQUIRE_LOCK(&(gm)->mutex); }
3102static void post_fork_parent(void) { RELEASE_LOCK(&(gm)->mutex); }
3103static void post_fork_child(void) { INITIAL_LOCK(&(gm)->mutex); }
3104#endif /* LOCK_AT_FORK */
3105
3106/* Initialize mparams */
3107static int init_mparams(void) {
3108#ifdef NEED_GLOBAL_LOCK_INIT
3109 if (malloc_global_mutex_status <= 0)
3110 init_malloc_global_mutex();
3111#endif
3112
3113 ACQUIRE_MALLOC_GLOBAL_LOCK();
3114 if (mparams.magic == 0) {
3115 size_t magic;
3116 size_t psize;
3117 size_t gsize;
3118
3119#ifndef WIN32
3120 psize = malloc_getpagesize;
3121 gsize = ((DEFAULT_GRANULARITY != 0)? DEFAULT_GRANULARITY : psize);
3122#else /* WIN32 */
3123 {
3124 SYSTEM_INFO system_info;
3125 GetSystemInfo(&system_info);
3126 psize = system_info.dwPageSize;
3127 gsize = ((DEFAULT_GRANULARITY != 0)?
3128 DEFAULT_GRANULARITY : system_info.dwAllocationGranularity);
3129 }
3130#endif /* WIN32 */
3131
3132 /* Sanity-check configuration:
3133 size_t must be unsigned and as wide as pointer type.
3134 ints must be at least 4 bytes.
3135 alignment must be at least 8.
3136 Alignment, min chunk size, and page size must all be powers of 2.
3137 */
3138 if ((sizeof(size_t) != sizeof(char*)) ||
3139 (MAX_SIZE_T < MIN_CHUNK_SIZE) ||
3140 (sizeof(int) < 4) ||
3141 (MALLOC_ALIGNMENT < (size_t)8U) ||
3142 ((MALLOC_ALIGNMENT & (MALLOC_ALIGNMENT-SIZE_T_ONE)) != 0) ||
3143 ((MCHUNK_SIZE & (MCHUNK_SIZE-SIZE_T_ONE)) != 0) ||
3144 ((gsize & (gsize-SIZE_T_ONE)) != 0) ||
3145 ((psize & (psize-SIZE_T_ONE)) != 0))
3146 ABORT;
3147 mparams.granularity = gsize;
3148 mparams.page_size = psize;
3149 mparams.mmap_threshold = DEFAULT_MMAP_THRESHOLD;
3150 mparams.trim_threshold = DEFAULT_TRIM_THRESHOLD;
3151#if MORECORE_CONTIGUOUS
3152 mparams.default_mflags = USE_LOCK_BIT|USE_MMAP_BIT;
3153#else /* MORECORE_CONTIGUOUS */
3154 mparams.default_mflags = USE_LOCK_BIT|USE_MMAP_BIT|USE_NONCONTIGUOUS_BIT;
3155#endif /* MORECORE_CONTIGUOUS */
3156
3157#if !ONLY_MSPACES
3158 /* Set up lock for main malloc area */
3159 gm->mflags = mparams.default_mflags;
3160 (void)INITIAL_LOCK(&gm->mutex);
3161#endif
3162#if LOCK_AT_FORK
3163 pthread_atfork(&pre_fork, &post_fork_parent, &post_fork_child);
3164#endif
3165
3166 {
3167#if USE_DEV_RANDOM
3168 int fd;
3169 unsigned char buf[sizeof(size_t)];
3170 /* Try to use /dev/urandom, else fall back on using time */
3171 if ((fd = open("/dev/urandom", O_RDONLY)) >= 0 &&
3172 read(fd, buf, sizeof(buf)) == sizeof(buf)) {
3173 magic = *((size_t *) buf);
3174 close(fd);
3175 }
3176 else
3177#endif /* USE_DEV_RANDOM */
3178#ifdef WIN32
3179 magic = (size_t)(GetTickCount() ^ (size_t)0x55555555U);
3180#elif defined(LACKS_TIME_H)
3181 magic = (size_t)&magic ^ (size_t)0x55555555U;
3182#else
3183 magic = (size_t)(time(0) ^ (size_t)0x55555555U);
3184#endif
3185 magic |= (size_t)8U; /* ensure nonzero */
3186 magic &= ~(size_t)7U; /* improve chances of fault for bad values */
3187 /* Until memory modes commonly available, use volatile-write */
3188 (*(volatile size_t *)(&(mparams.magic))) = magic;
3189 }
3190 }
3191
3192 RELEASE_MALLOC_GLOBAL_LOCK();
3193 return 1;
3194}
3195
3196/* support for mallopt */
3197static int change_mparam(int param_number, int value) {
3198 size_t val;
3199 ensure_initialization();
3200 val = (value == -1)? MAX_SIZE_T : (size_t)value;
3201 switch(param_number) {
3202 case M_TRIM_THRESHOLD:
3203 mparams.trim_threshold = val;
3204 return 1;
3205 case M_GRANULARITY:
3206 if (val >= mparams.page_size && ((val & (val-1)) == 0)) {
3207 mparams.granularity = val;
3208 return 1;
3209 }
3210 else
3211 return 0;
3212 case M_MMAP_THRESHOLD:
3213 mparams.mmap_threshold = val;
3214 return 1;
3215 default:
3216 return 0;
3217 }
3218}
3219
3220#if DEBUG
3221/* ------------------------- Debugging Support --------------------------- */
3222
3223/* Check properties of any chunk, whether free, inuse, mmapped etc */
3224static void do_check_any_chunk(mstate m, mchunkptr p) {
3225 assert((is_aligned(chunk2mem(p))) || (p->head == FENCEPOST_HEAD));
3226 assert(ok_address(m, p));
3227}
3228
3229/* Check properties of top chunk */
3230static void do_check_top_chunk(mstate m, mchunkptr p) {
3231 msegmentptr sp = segment_holding(m, (char*)p);
3232 size_t sz = p->head & ~INUSE_BITS; /* third-lowest bit can be set! */
3233 assert(sp != 0);
3234 assert((is_aligned(chunk2mem(p))) || (p->head == FENCEPOST_HEAD));
3235 assert(ok_address(m, p));
3236 assert(sz == m->topsize);
3237 assert(sz > 0);
3238 assert(sz == ((sp->base + sp->size) - (char*)p) - TOP_FOOT_SIZE);
3239 assert(pinuse(p));
3240 assert(!pinuse(chunk_plus_offset(p, sz)));
3241}
3242
3243/* Check properties of (inuse) mmapped chunks */
3244static void do_check_mmapped_chunk(mstate m, mchunkptr p) {
3245 size_t sz = chunksize(p);
3246 size_t len = (sz + (p->prev_foot) + MMAP_FOOT_PAD);
3247 assert(is_mmapped(p));
3248 assert(use_mmap(m));
3249 assert((is_aligned(chunk2mem(p))) || (p->head == FENCEPOST_HEAD));
3250 assert(ok_address(m, p));
3251 assert(!is_small(sz));
3252 assert((len & (mparams.page_size-SIZE_T_ONE)) == 0);
3253 assert(chunk_plus_offset(p, sz)->head == FENCEPOST_HEAD);
3254 assert(chunk_plus_offset(p, sz+SIZE_T_SIZE)->head == 0);
3255}
3256
3257/* Check properties of inuse chunks */
3258static void do_check_inuse_chunk(mstate m, mchunkptr p) {
3259 do_check_any_chunk(m, p);
3260 assert(is_inuse(p));
3261 assert(next_pinuse(p));
3262 /* If not pinuse and not mmapped, previous chunk has OK offset */
3263 assert(is_mmapped(p) || pinuse(p) || next_chunk(prev_chunk(p)) == p);
3264 if (is_mmapped(p))
3265 do_check_mmapped_chunk(m, p);
3266}
3267
3268/* Check properties of free chunks */
3269static void do_check_free_chunk(mstate m, mchunkptr p) {
3270 size_t sz = chunksize(p);
3271 mchunkptr next = chunk_plus_offset(p, sz);
3272 do_check_any_chunk(m, p);
3273 assert(!is_inuse(p));
3274 assert(!next_pinuse(p));
3275 assert (!is_mmapped(p));
3276 if (p != m->dv && p != m->top) {
3277 if (sz >= MIN_CHUNK_SIZE) {
3278 assert((sz & CHUNK_ALIGN_MASK) == 0);
3279 assert(is_aligned(chunk2mem(p)));
3280 assert(next->prev_foot == sz);
3281 assert(pinuse(p));
3282 assert (next == m->top || is_inuse(next));
3283 assert(p->fd->bk == p);
3284 assert(p->bk->fd == p);
3285 }
3286 else /* markers are always of size SIZE_T_SIZE */
3287 assert(sz == SIZE_T_SIZE);
3288 }
3289}
3290
3291/* Check properties of malloced chunks at the point they are malloced */
3292static void do_check_malloced_chunk(mstate m, void* mem, size_t s) {
3293 if (mem != 0) {
3294 mchunkptr p = mem2chunk(mem);
3295 size_t sz = p->head & ~INUSE_BITS;
3296 do_check_inuse_chunk(m, p);
3297 assert((sz & CHUNK_ALIGN_MASK) == 0);
3298 assert(sz >= MIN_CHUNK_SIZE);
3299 assert(sz >= s);
3300 /* unless mmapped, size is less than MIN_CHUNK_SIZE more than request */
3301 assert(is_mmapped(p) || sz < (s + MIN_CHUNK_SIZE));
3302 }
3303}
3304
3305/* Check a tree and its subtrees. */
3306static void do_check_tree(mstate m, tchunkptr t) {
3307 tchunkptr head = 0;
3308 tchunkptr u = t;
3309 bindex_t tindex = t->index;
3310 size_t tsize = chunksize(t);
3311 bindex_t idx;
3312 compute_tree_index(tsize, idx);
3313 assert(tindex == idx);
3314 assert(tsize >= MIN_LARGE_SIZE);
3315 assert(tsize >= minsize_for_tree_index(idx));
3316 assert((idx == NTREEBINS-1) || (tsize < minsize_for_tree_index((idx+1))));
3317
3318 do { /* traverse through chain of same-sized nodes */
3319 do_check_any_chunk(m, ((mchunkptr)u));
3320 assert(u->index == tindex);
3321 assert(chunksize(u) == tsize);
3322 assert(!is_inuse(u));
3323 assert(!next_pinuse(u));
3324 assert(u->fd->bk == u);
3325 assert(u->bk->fd == u);
3326 if (u->parent == 0) {
3327 assert(u->child[0] == 0);
3328 assert(u->child[1] == 0);
3329 }
3330 else {
3331 assert(head == 0); /* only one node on chain has parent */
3332 head = u;
3333 assert(u->parent != u);
3334 assert (u->parent->child[0] == u ||
3335 u->parent->child[1] == u ||
3336 *((tbinptr*)(u->parent)) == u);
3337 if (u->child[0] != 0) {
3338 assert(u->child[0]->parent == u);
3339 assert(u->child[0] != u);
3340 do_check_tree(m, u->child[0]);
3341 }
3342 if (u->child[1] != 0) {
3343 assert(u->child[1]->parent == u);
3344 assert(u->child[1] != u);
3345 do_check_tree(m, u->child[1]);
3346 }
3347 if (u->child[0] != 0 && u->child[1] != 0) {
3348 assert(chunksize(u->child[0]) < chunksize(u->child[1]));
3349 }
3350 }
3351 u = u->fd;
3352 } while (u != t);
3353 assert(head != 0);
3354}
3355
3356/* Check all the chunks in a treebin. */
3357static void do_check_treebin(mstate m, bindex_t i) {
3358 tbinptr* tb = treebin_at(m, i);
3359 tchunkptr t = *tb;
3360 int empty = (m->treemap & (1U << i)) == 0;
3361 if (t == 0)
3362 assert(empty);
3363 if (!empty)
3364 do_check_tree(m, t);
3365}
3366
3367/* Check all the chunks in a smallbin. */
3368static void do_check_smallbin(mstate m, bindex_t i) {
3369 sbinptr b = smallbin_at(m, i);
3370 mchunkptr p = b->bk;
3371 unsigned int empty = (m->smallmap & (1U << i)) == 0;
3372 if (p == b)
3373 assert(empty);
3374 if (!empty) {
3375 for (; p != b; p = p->bk) {
3376 size_t size = chunksize(p);
3377 mchunkptr q;
3378 /* each chunk claims to be free */
3379 do_check_free_chunk(m, p);
3380 /* chunk belongs in bin */
3381 assert(small_index(size) == i);
3382 assert(p->bk == b || chunksize(p->bk) == chunksize(p));
3383 /* chunk is followed by an inuse chunk */
3384 q = next_chunk(p);
3385 if (q->head != FENCEPOST_HEAD)
3386 do_check_inuse_chunk(m, q);
3387 }
3388 }
3389}
3390
3391/* Find x in a bin. Used in other check functions. */
3392static int bin_find(mstate m, mchunkptr x) {
3393 size_t size = chunksize(x);
3394 if (is_small(size)) {
3395 bindex_t sidx = small_index(size);
3396 sbinptr b = smallbin_at(m, sidx);
3397 if (smallmap_is_marked(m, sidx)) {
3398 mchunkptr p = b;
3399 do {
3400 if (p == x)
3401 return 1;
3402 } while ((p = p->fd) != b);
3403 }
3404 }
3405 else {
3406 bindex_t tidx;
3407 compute_tree_index(size, tidx);
3408 if (treemap_is_marked(m, tidx)) {
3409 tchunkptr t = *treebin_at(m, tidx);
3410 size_t sizebits = size << leftshift_for_tree_index(tidx);
3411 while (t != 0 && chunksize(t) != size) {
3412 t = t->child[(sizebits >> (SIZE_T_BITSIZE-SIZE_T_ONE)) & 1];
3413 sizebits <<= 1;
3414 }
3415 if (t != 0) {
3416 tchunkptr u = t;
3417 do {
3418 if (u == (tchunkptr)x)
3419 return 1;
3420 } while ((u = u->fd) != t);
3421 }
3422 }
3423 }
3424 return 0;
3425}
3426
3427/* Traverse each chunk and check it; return total */
3428static size_t traverse_and_check(mstate m) {
3429 size_t sum = 0;
3430 if (is_initialized(m)) {
3431 msegmentptr s = &m->seg;
3432 sum += m->topsize + TOP_FOOT_SIZE;
3433 while (s != 0) {
3434 mchunkptr q = align_as_chunk(s->base);
3435 mchunkptr lastq = 0;
3436 assert(pinuse(q));
3437 while (segment_holds(s, q) &&
3438 q != m->top && q->head != FENCEPOST_HEAD) {
3439 sum += chunksize(q);
3440 if (is_inuse(q)) {
3441 assert(!bin_find(m, q));
3442 do_check_inuse_chunk(m, q);
3443 }
3444 else {
3445 assert(q == m->dv || bin_find(m, q));
3446 assert(lastq == 0 || is_inuse(lastq)); /* Not 2 consecutive free */
3447 do_check_free_chunk(m, q);
3448 }
3449 lastq = q;
3450 q = next_chunk(q);
3451 }
3452 s = s->next;
3453 }
3454 }
3455 return sum;
3456}
3457
3458
3459/* Check all properties of malloc_state. */
3460static void do_check_malloc_state(mstate m) {
3461 bindex_t i;
3462 size_t total;
3463 /* check bins */
3464 for (i = 0; i < NSMALLBINS; ++i)
3465 do_check_smallbin(m, i);
3466 for (i = 0; i < NTREEBINS; ++i)
3467 do_check_treebin(m, i);
3468
3469 if (m->dvsize != 0) { /* check dv chunk */
3470 do_check_any_chunk(m, m->dv);
3471 assert(m->dvsize == chunksize(m->dv));
3472 assert(m->dvsize >= MIN_CHUNK_SIZE);
3473 assert(bin_find(m, m->dv) == 0);
3474 }
3475
3476 if (m->top != 0) { /* check top chunk */
3477 do_check_top_chunk(m, m->top);
3478 /*assert(m->topsize == chunksize(m->top)); redundant */
3479 assert(m->topsize > 0);
3480 assert(bin_find(m, m->top) == 0);
3481 }
3482
3483 total = traverse_and_check(m);
3484 assert(total <= m->footprint);
3485 assert(m->footprint <= m->max_footprint);
3486}
3487#endif /* DEBUG */
3488
3489/* ----------------------------- statistics ------------------------------ */
3490
3491#if !NO_MALLINFO
3492static struct mallinfo internal_mallinfo(mstate m) {
3493 struct mallinfo nm = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
3494 ensure_initialization();
3495 if (!PREACTION(m)) {
3496 check_malloc_state(m);
3497 if (is_initialized(m)) {
3498 size_t nfree = SIZE_T_ONE; /* top always free */
3499 size_t mfree = m->topsize + TOP_FOOT_SIZE;
3500 size_t sum = mfree;
3501 msegmentptr s = &m->seg;
3502 while (s != 0) {
3503 mchunkptr q = align_as_chunk(s->base);
3504 while (segment_holds(s, q) &&
3505 q != m->top && q->head != FENCEPOST_HEAD) {
3506 size_t sz = chunksize(q);
3507 sum += sz;
3508 if (!is_inuse(q)) {
3509 mfree += sz;
3510 ++nfree;
3511 }
3512 q = next_chunk(q);
3513 }
3514 s = s->next;
3515 }
3516
3517 nm.arena = sum;
3518 nm.ordblks = nfree;
3519 nm.hblkhd = m->footprint - sum;
3520 nm.usmblks = m->max_footprint;
3521 nm.uordblks = m->footprint - mfree;
3522 nm.fordblks = mfree;
3523 nm.keepcost = m->topsize;
3524 }
3525
3526 POSTACTION(m);
3527 }
3528 return nm;
3529}
3530#endif /* !NO_MALLINFO */
3531
3532#if !NO_MALLOC_STATS
3533static void internal_malloc_stats(mstate m) {
3534 ensure_initialization();
3535 if (!PREACTION(m)) {
3536 size_t maxfp = 0;
3537 size_t fp = 0;
3538 size_t used = 0;
3539 check_malloc_state(m);
3540 if (is_initialized(m)) {
3541 msegmentptr s = &m->seg;
3542 maxfp = m->max_footprint;
3543 fp = m->footprint;
3544 used = fp - (m->topsize + TOP_FOOT_SIZE);
3545
3546 while (s != 0) {
3547 mchunkptr q = align_as_chunk(s->base);
3548 while (segment_holds(s, q) &&
3549 q != m->top && q->head != FENCEPOST_HEAD) {
3550 if (!is_inuse(q))
3551 used -= chunksize(q);
3552 q = next_chunk(q);
3553 }
3554 s = s->next;
3555 }
3556 }
3557 POSTACTION(m); /* drop lock */
3558 fprintf(stderr, "max system bytes = %10lu\n", (unsigned long)(maxfp));
3559 fprintf(stderr, "system bytes = %10lu\n", (unsigned long)(fp));
3560 fprintf(stderr, "in use bytes = %10lu\n", (unsigned long)(used));
3561 }
3562}
3563#endif /* NO_MALLOC_STATS */
3564
3565/* ----------------------- Operations on smallbins ----------------------- */
3566
3567/*
3568 Various forms of linking and unlinking are defined as macros. Even
3569 the ones for trees, which are very long but have very short typical
3570 paths. This is ugly but reduces reliance on inlining support of
3571 compilers.
3572*/
3573
3574/* Link a free chunk into a smallbin */
3575#define insert_small_chunk(M, P, S) {\
3576 bindex_t I = small_index(S);\
3577 mchunkptr B = smallbin_at(M, I);\
3578 mchunkptr F = B;\
3579 assert(S >= MIN_CHUNK_SIZE);\
3580 if (!smallmap_is_marked(M, I))\
3581 mark_smallmap(M, I);\
3582 else if (RTCHECK(ok_address(M, B->fd)))\
3583 F = B->fd;\
3584 else {\
3585 CORRUPTION_ERROR_ACTION(M);\
3586 }\
3587 B->fd = P;\
3588 F->bk = P;\
3589 P->fd = F;\
3590 P->bk = B;\
3591}
3592
3593/* Unlink a chunk from a smallbin */
3594#define unlink_small_chunk(M, P, S) {\
3595 mchunkptr F = P->fd;\
3596 mchunkptr B = P->bk;\
3597 bindex_t I = small_index(S);\
3598 assert(P != B);\
3599 assert(P != F);\
3600 assert(chunksize(P) == small_index2size(I));\
3601 if (RTCHECK(F == smallbin_at(M,I) || (ok_address(M, F) && F->bk == P))) { \
3602 if (B == F) {\
3603 clear_smallmap(M, I);\
3604 }\
3605 else if (RTCHECK(B == smallbin_at(M,I) ||\
3606 (ok_address(M, B) && B->fd == P))) {\
3607 F->bk = B;\
3608 B->fd = F;\
3609 }\
3610 else {\
3611 CORRUPTION_ERROR_ACTION(M);\
3612 }\
3613 }\
3614 else {\
3615 CORRUPTION_ERROR_ACTION(M);\
3616 }\
3617}
3618
3619/* Unlink the first chunk from a smallbin */
3620#define unlink_first_small_chunk(M, B, P, I) {\
3621 mchunkptr F = P->fd;\
3622 assert(P != B);\
3623 assert(P != F);\
3624 assert(chunksize(P) == small_index2size(I));\
3625 if (B == F) {\
3626 clear_smallmap(M, I);\
3627 }\
3628 else if (RTCHECK(ok_address(M, F) && F->bk == P)) {\
3629 F->bk = B;\
3630 B->fd = F;\
3631 }\
3632 else {\
3633 CORRUPTION_ERROR_ACTION(M);\
3634 }\
3635}
3636
3637/* Replace dv node, binning the old one */
3638/* Used only when dvsize known to be small */
3639#define replace_dv(M, P, S) {\
3640 size_t DVS = M->dvsize;\
3641 assert(is_small(DVS));\
3642 if (DVS != 0) {\
3643 mchunkptr DV = M->dv;\
3644 insert_small_chunk(M, DV, DVS);\
3645 }\
3646 M->dvsize = S;\
3647 M->dv = P;\
3648}
3649
3650/* ------------------------- Operations on trees ------------------------- */
3651
3652/* Insert chunk into tree */
3653#define insert_large_chunk(M, X, S) {\
3654 tbinptr* H;\
3655 bindex_t I;\
3656 compute_tree_index(S, I);\
3657 H = treebin_at(M, I);\
3658 X->index = I;\
3659 X->child[0] = X->child[1] = 0;\
3660 if (!treemap_is_marked(M, I)) {\
3661 mark_treemap(M, I);\
3662 *H = X;\
3663 X->parent = (tchunkptr)H;\
3664 X->fd = X->bk = X;\
3665 }\
3666 else {\
3667 tchunkptr T = *H;\
3668 size_t K = S << leftshift_for_tree_index(I);\
3669 for (;;) {\
3670 if (chunksize(T) != S) {\
3671 tchunkptr* C = &(T->child[(K >> (SIZE_T_BITSIZE-SIZE_T_ONE)) & 1]);\
3672 K <<= 1;\
3673 if (*C != 0)\
3674 T = *C;\
3675 else if (RTCHECK(ok_address(M, C))) {\
3676 *C = X;\
3677 X->parent = T;\
3678 X->fd = X->bk = X;\
3679 break;\
3680 }\
3681 else {\
3682 CORRUPTION_ERROR_ACTION(M);\
3683 break;\
3684 }\
3685 }\
3686 else {\
3687 tchunkptr F = T->fd;\
3688 if (RTCHECK(ok_address(M, T) && ok_address(M, F))) {\
3689 T->fd = F->bk = X;\
3690 X->fd = F;\
3691 X->bk = T;\
3692 X->parent = 0;\
3693 break;\
3694 }\
3695 else {\
3696 CORRUPTION_ERROR_ACTION(M);\
3697 break;\
3698 }\
3699 }\
3700 }\
3701 }\
3702}
3703
3704/*
3705 Unlink steps:
3706
3707 1. If x is a chained node, unlink it from its same-sized fd/bk links
3708 and choose its bk node as its replacement.
3709 2. If x was the last node of its size, but not a leaf node, it must
3710 be replaced with a leaf node (not merely one with an open left or
3711 right), to make sure that lefts and rights of descendents
3712 correspond properly to bit masks. We use the rightmost descendent
3713 of x. We could use any other leaf, but this is easy to locate and
3714 tends to counteract removal of leftmosts elsewhere, and so keeps
3715 paths shorter than minimally guaranteed. This doesn't loop much
3716 because on average a node in a tree is near the bottom.
3717 3. If x is the base of a chain (i.e., has parent links) relink
3718 x's parent and children to x's replacement (or null if none).
3719*/
3720
3721#define unlink_large_chunk(M, X) {\
3722 tchunkptr XP = X->parent;\
3723 tchunkptr R;\
3724 if (X->bk != X) {\
3725 tchunkptr F = X->fd;\
3726 R = X->bk;\
3727 if (RTCHECK(ok_address(M, F) && F->bk == X && R->fd == X)) {\
3728 F->bk = R;\
3729 R->fd = F;\
3730 }\
3731 else {\
3732 CORRUPTION_ERROR_ACTION(M);\
3733 }\
3734 }\
3735 else {\
3736 tchunkptr* RP;\
3737 if (((R = *(RP = &(X->child[1]))) != 0) ||\
3738 ((R = *(RP = &(X->child[0]))) != 0)) {\
3739 tchunkptr* CP;\
3740 while ((*(CP = &(R->child[1])) != 0) ||\
3741 (*(CP = &(R->child[0])) != 0)) {\
3742 R = *(RP = CP);\
3743 }\
3744 if (RTCHECK(ok_address(M, RP)))\
3745 *RP = 0;\
3746 else {\
3747 CORRUPTION_ERROR_ACTION(M);\
3748 }\
3749 }\
3750 }\
3751 if (XP != 0) {\
3752 tbinptr* H = treebin_at(M, X->index);\
3753 if (X == *H) {\
3754 if ((*H = R) == 0) \
3755 clear_treemap(M, X->index);\
3756 }\
3757 else if (RTCHECK(ok_address(M, XP))) {\
3758 if (XP->child[0] == X) \
3759 XP->child[0] = R;\
3760 else \
3761 XP->child[1] = R;\
3762 }\
3763 else\
3764 CORRUPTION_ERROR_ACTION(M);\
3765 if (R != 0) {\
3766 if (RTCHECK(ok_address(M, R))) {\
3767 tchunkptr C0, C1;\
3768 R->parent = XP;\
3769 if ((C0 = X->child[0]) != 0) {\
3770 if (RTCHECK(ok_address(M, C0))) {\
3771 R->child[0] = C0;\
3772 C0->parent = R;\
3773 }\
3774 else\
3775 CORRUPTION_ERROR_ACTION(M);\
3776 }\
3777 if ((C1 = X->child[1]) != 0) {\
3778 if (RTCHECK(ok_address(M, C1))) {\
3779 R->child[1] = C1;\
3780 C1->parent = R;\
3781 }\
3782 else\
3783 CORRUPTION_ERROR_ACTION(M);\
3784 }\
3785 }\
3786 else\
3787 CORRUPTION_ERROR_ACTION(M);\
3788 }\
3789 }\
3790}
3791
3792/* Relays to large vs small bin operations */
3793
3794#define insert_chunk(M, P, S)\
3795 if (is_small(S)) insert_small_chunk(M, P, S)\
3796 else { tchunkptr TP = (tchunkptr)(P); insert_large_chunk(M, TP, S); }
3797
3798#define unlink_chunk(M, P, S)\
3799 if (is_small(S)) unlink_small_chunk(M, P, S)\
3800 else { tchunkptr TP = (tchunkptr)(P); unlink_large_chunk(M, TP); }
3801
3802
3803/* Relays to internal calls to malloc/free from realloc, memalign etc */
3804
3805#if ONLY_MSPACES
3806#define internal_malloc(m, b) mspace_malloc(m, b)
3807#define internal_free(m, mem) mspace_free(m,mem);
3808#else /* ONLY_MSPACES */
3809#if MSPACES
3810#define internal_malloc(m, b)\
3811 ((m == gm)? dlmalloc(b) : mspace_malloc(m, b))
3812#define internal_free(m, mem)\
3813 if (m == gm) dlfree(mem); else mspace_free(m,mem);
3814#else /* MSPACES */
3815#define internal_malloc(m, b) dlmalloc(b)
3816#define internal_free(m, mem) dlfree(mem)
3817#endif /* MSPACES */
3818#endif /* ONLY_MSPACES */
3819
3820/* ----------------------- Direct-mmapping chunks ----------------------- */
3821
3822/*
3823 Directly mmapped chunks are set up with an offset to the start of
3824 the mmapped region stored in the prev_foot field of the chunk. This
3825 allows reconstruction of the required argument to MUNMAP when freed,
3826 and also allows adjustment of the returned chunk to meet alignment
3827 requirements (especially in memalign).
3828*/
3829
3830/* Malloc using mmap */
3831static void* mmap_alloc(mstate m, size_t nb) {
3832 size_t mmsize = mmap_align(nb + SIX_SIZE_T_SIZES + CHUNK_ALIGN_MASK);
3833 if (m->footprint_limit != 0) {
3834 size_t fp = m->footprint + mmsize;
3835 if (fp <= m->footprint || fp > m->footprint_limit)
3836 return 0;
3837 }
3838 if (mmsize > nb) { /* Check for wrap around 0 */
3839 char* mm = (char*)(CALL_DIRECT_MMAP(mmsize));
3840 if (mm != CMFAIL) {
3841 size_t offset = align_offset(chunk2mem(mm));
3842 size_t psize = mmsize - offset - MMAP_FOOT_PAD;
3843 mchunkptr p = (mchunkptr)(mm + offset);
3844 p->prev_foot = offset;
3845 p->head = psize;
3846 mark_inuse_foot(m, p, psize);
3847 chunk_plus_offset(p, psize)->head = FENCEPOST_HEAD;
3848 chunk_plus_offset(p, psize+SIZE_T_SIZE)->head = 0;
3849
3850 if (m->least_addr == 0 || mm < m->least_addr)
3851 m->least_addr = mm;
3852 if ((m->footprint += mmsize) > m->max_footprint)
3853 m->max_footprint = m->footprint;
3854 assert(is_aligned(chunk2mem(p)));
3855 check_mmapped_chunk(m, p);
3856 return chunk2mem(p);
3857 }
3858 }
3859 return 0;
3860}
3861
3862/* Realloc using mmap */
3863static mchunkptr mmap_resize(mstate m, mchunkptr oldp, size_t nb, int flags) {
3864 size_t oldsize = chunksize(oldp);
3865 (void)flags; /* placate people compiling -Wunused */
3866 if (is_small(nb)) /* Can't shrink mmap regions below small size */
3867 return 0;
3868 /* Keep old chunk if big enough but not too big */
3869 if (oldsize >= nb + SIZE_T_SIZE &&
3870 (oldsize - nb) <= (mparams.granularity << 1))
3871 return oldp;
3872 else {
3873 size_t offset = oldp->prev_foot;
3874 size_t oldmmsize = oldsize + offset + MMAP_FOOT_PAD;
3875 size_t newmmsize = mmap_align(nb + SIX_SIZE_T_SIZES + CHUNK_ALIGN_MASK);
3876 char* cp = (char*)CALL_MREMAP((char*)oldp - offset,
3877 oldmmsize, newmmsize, flags);
3878 if (cp != CMFAIL) {
3879 mchunkptr newp = (mchunkptr)(cp + offset);
3880 size_t psize = newmmsize - offset - MMAP_FOOT_PAD;
3881 newp->head = psize;
3882 mark_inuse_foot(m, newp, psize);
3883 chunk_plus_offset(newp, psize)->head = FENCEPOST_HEAD;
3884 chunk_plus_offset(newp, psize+SIZE_T_SIZE)->head = 0;
3885
3886 if (cp < m->least_addr)
3887 m->least_addr = cp;
3888 if ((m->footprint += newmmsize - oldmmsize) > m->max_footprint)
3889 m->max_footprint = m->footprint;
3890 check_mmapped_chunk(m, newp);
3891 return newp;
3892 }
3893 }
3894 return 0;
3895}
3896
3897
3898/* -------------------------- mspace management -------------------------- */
3899
3900/* Initialize top chunk and its size */
3901static void init_top(mstate m, mchunkptr p, size_t psize) {
3902 /* Ensure alignment */
3903 size_t offset = align_offset(chunk2mem(p));
3904 p = (mchunkptr)((char*)p + offset);
3905 psize -= offset;
3906
3907 m->top = p;
3908 m->topsize = psize;
3909 p->head = psize | PINUSE_BIT;
3910 /* set size of fake trailing chunk holding overhead space only once */
3911 chunk_plus_offset(p, psize)->head = TOP_FOOT_SIZE;
3912 m->trim_check = mparams.trim_threshold; /* reset on each update */
3913}
3914
3915/* Initialize bins for a new mstate that is otherwise zeroed out */
3916static void init_bins(mstate m) {
3917 /* Establish circular links for smallbins */
3918 bindex_t i;
3919 for (i = 0; i < NSMALLBINS; ++i) {
3920 sbinptr bin = smallbin_at(m,i);
3921 bin->fd = bin->bk = bin;
3922 }
3923}
3924
3925#if PROCEED_ON_ERROR
3926
3927/* default corruption action */
3928static void reset_on_error(mstate m) {
3929 int i;
3930 ++malloc_corruption_error_count;
3931 /* Reinitialize fields to forget about all memory */
3932 m->smallmap = m->treemap = 0;
3933 m->dvsize = m->topsize = 0;
3934 m->seg.base = 0;
3935 m->seg.size = 0;
3936 m->seg.next = 0;
3937 m->top = m->dv = 0;
3938 for (i = 0; i < NTREEBINS; ++i)
3939 *treebin_at(m, i) = 0;
3940 init_bins(m);
3941}
3942#endif /* PROCEED_ON_ERROR */
3943
3944/* Allocate chunk and prepend remainder with chunk in successor base. */
3945static void* prepend_alloc(mstate m, char* newbase, char* oldbase,
3946 size_t nb) {
3947 mchunkptr p = align_as_chunk(newbase);
3948 mchunkptr oldfirst = align_as_chunk(oldbase);
3949 size_t psize = (char*)oldfirst - (char*)p;
3950 mchunkptr q = chunk_plus_offset(p, nb);
3951 size_t qsize = psize - nb;
3952 set_size_and_pinuse_of_inuse_chunk(m, p, nb);
3953
3954 assert((char*)oldfirst > (char*)q);
3955 assert(pinuse(oldfirst));
3956 assert(qsize >= MIN_CHUNK_SIZE);
3957
3958 /* consolidate remainder with first chunk of old base */
3959 if (oldfirst == m->top) {
3960 size_t tsize = m->topsize += qsize;
3961 m->top = q;
3962 q->head = tsize | PINUSE_BIT;
3963 check_top_chunk(m, q);
3964 }
3965 else if (oldfirst == m->dv) {
3966 size_t dsize = m->dvsize += qsize;
3967 m->dv = q;
3968 set_size_and_pinuse_of_free_chunk(q, dsize);
3969 }
3970 else {
3971 if (!is_inuse(oldfirst)) {
3972 size_t nsize = chunksize(oldfirst);
3973 unlink_chunk(m, oldfirst, nsize);
3974 oldfirst = chunk_plus_offset(oldfirst, nsize);
3975 qsize += nsize;
3976 }
3977 set_free_with_pinuse(q, qsize, oldfirst);
3978 insert_chunk(m, q, qsize);
3979 check_free_chunk(m, q);
3980 }
3981
3982 check_malloced_chunk(m, chunk2mem(p), nb);
3983 return chunk2mem(p);
3984}
3985
3986/* Add a segment to hold a new noncontiguous region */
3987static void add_segment(mstate m, char* tbase, size_t tsize, flag_t mmapped) {
3988 /* Determine locations and sizes of segment, fenceposts, old top */
3989 char* old_top = (char*)m->top;
3990 msegmentptr oldsp = segment_holding(m, old_top);
3991 char* old_end = oldsp->base + oldsp->size;
3992 size_t ssize = pad_request(sizeof(struct malloc_segment));
3993 char* rawsp = old_end - (ssize + FOUR_SIZE_T_SIZES + CHUNK_ALIGN_MASK);
3994 size_t offset = align_offset(chunk2mem(rawsp));
3995 char* asp = rawsp + offset;
3996 char* csp = (asp < (old_top + MIN_CHUNK_SIZE))? old_top : asp;
3997 mchunkptr sp = (mchunkptr)csp;
3998 msegmentptr ss = (msegmentptr)(chunk2mem(sp));
3999 mchunkptr tnext = chunk_plus_offset(sp, ssize);
4000 mchunkptr p = tnext;
4001 int nfences = 0;
4002
4003 /* reset top to new space */
4004 init_top(m, (mchunkptr)tbase, tsize - TOP_FOOT_SIZE);
4005
4006 /* Set up segment record */
4007 assert(is_aligned(ss));
4008 set_size_and_pinuse_of_inuse_chunk(m, sp, ssize);
4009 *ss = m->seg; /* Push current record */
4010 m->seg.base = tbase;
4011 m->seg.size = tsize;
4012 m->seg.sflags = mmapped;
4013 m->seg.next = ss;
4014
4015 /* Insert trailing fenceposts */
4016 for (;;) {
4017 mchunkptr nextp = chunk_plus_offset(p, SIZE_T_SIZE);
4018 p->head = FENCEPOST_HEAD;
4019 ++nfences;
4020 if ((char*)(&(nextp->head)) < old_end)
4021 p = nextp;
4022 else
4023 break;
4024 }
4025 assert(nfences >= 2);
4026
4027 /* Insert the rest of old top into a bin as an ordinary free chunk */
4028 if (csp != old_top) {
4029 mchunkptr q = (mchunkptr)old_top;
4030 size_t psize = csp - old_top;
4031 mchunkptr tn = chunk_plus_offset(q, psize);
4032 set_free_with_pinuse(q, psize, tn);
4033 insert_chunk(m, q, psize);
4034 }
4035
4036 check_top_chunk(m, m->top);
4037}
4038
4039/* -------------------------- System allocation -------------------------- */
4040
4041/* Get memory from system using MORECORE or MMAP */
4042static void* sys_alloc(mstate m, size_t nb) {
4043 char* tbase = CMFAIL;
4044 size_t tsize = 0;
4045 flag_t mmap_flag = 0;
4046 size_t asize; /* allocation size */
4047
4048 ensure_initialization();
4049
4050 /* Directly map large chunks, but only if already initialized */
4051 if (use_mmap(m) && nb >= mparams.mmap_threshold && m->topsize != 0) {
4052 void* mem = mmap_alloc(m, nb);
4053 if (mem != 0)
4054 return mem;
4055 }
4056
4057 asize = granularity_align(nb + SYS_ALLOC_PADDING);
4058#ifdef __wasilibc_unmodified_upstream // Bug fix: set ENOMEM on size overflow
4059 if (asize <= nb)
4060 return 0; /* wraparound */
4061#else
4062 if (asize <= nb) {
4063 MALLOC_FAILURE_ACTION;
4064 return 0; /* wraparound */
4065 }
4066#endif
4067 if (m->footprint_limit != 0) {
4068 size_t fp = m->footprint + asize;
4069#ifdef __wasilibc_unmodified_upstream // Bug fix: set ENOMEM on footprint overrun
4070 if (fp <= m->footprint || fp > m->footprint_limit)
4071 return 0;
4072#else
4073 if (fp <= m->footprint || fp > m->footprint_limit) {
4074 MALLOC_FAILURE_ACTION;
4075 return 0;
4076 }
4077#endif
4078 }
4079
4080 /*
4081 Try getting memory in any of three ways (in most-preferred to
4082 least-preferred order):
4083 1. A call to MORECORE that can normally contiguously extend memory.
4084 (disabled if not MORECORE_CONTIGUOUS or not HAVE_MORECORE or
4085 or main space is mmapped or a previous contiguous call failed)
4086 2. A call to MMAP new space (disabled if not HAVE_MMAP).
4087 Note that under the default settings, if MORECORE is unable to
4088 fulfill a request, and HAVE_MMAP is true, then mmap is
4089 used as a noncontiguous system allocator. This is a useful backup
4090 strategy for systems with holes in address spaces -- in this case
4091 sbrk cannot contiguously expand the heap, but mmap may be able to
4092 find space.
4093 3. A call to MORECORE that cannot usually contiguously extend memory.
4094 (disabled if not HAVE_MORECORE)
4095
4096 In all cases, we need to request enough bytes from system to ensure
4097 we can malloc nb bytes upon success, so pad with enough space for
4098 top_foot, plus alignment-pad to make sure we don't lose bytes if
4099 not on boundary, and round this up to a granularity unit.
4100 */
4101
4102 if (MORECORE_CONTIGUOUS && !use_noncontiguous(m)) {
4103 char* br = CMFAIL;
4104 size_t ssize = asize; /* sbrk call size */
4105 msegmentptr ss = (m->top == 0)? 0 : segment_holding(m, (char*)m->top);
4106 ACQUIRE_MALLOC_GLOBAL_LOCK();
4107
4108 if (ss == 0) { /* First time through or recovery */
4109 char* base = (char*)CALL_MORECORE(0);
4110 if (base != CMFAIL) {
4111 size_t fp;
4112 /* Adjust to end on a page boundary */
4113 if (!is_page_aligned(base))
4114 ssize += (page_align((size_t)base) - (size_t)base);
4115 fp = m->footprint + ssize; /* recheck limits */
4116 if (ssize > nb && ssize < HALF_MAX_SIZE_T &&
4117 (m->footprint_limit == 0 ||
4118 (fp > m->footprint && fp <= m->footprint_limit)) &&
4119 (br = (char*)(CALL_MORECORE(ssize))) == base) {
4120 tbase = base;
4121 tsize = ssize;
4122 }
4123 }
4124 }
4125 else {
4126 /* Subtract out existing available top space from MORECORE request. */
4127 ssize = granularity_align(nb - m->topsize + SYS_ALLOC_PADDING);
4128 /* Use mem here only if it did continuously extend old space */
4129 if (ssize < HALF_MAX_SIZE_T &&
4130 (br = (char*)(CALL_MORECORE(ssize))) == ss->base+ss->size) {
4131 tbase = br;
4132 tsize = ssize;
4133 }
4134 }
4135
4136 if (tbase == CMFAIL) { /* Cope with partial failure */
4137 if (br != CMFAIL) { /* Try to use/extend the space we did get */
4138 if (ssize < HALF_MAX_SIZE_T &&
4139 ssize < nb + SYS_ALLOC_PADDING) {
4140 size_t esize = granularity_align(nb + SYS_ALLOC_PADDING - ssize);
4141 if (esize < HALF_MAX_SIZE_T) {
4142 char* end = (char*)CALL_MORECORE(esize);
4143 if (end != CMFAIL)
4144 ssize += esize;
4145 else { /* Can't use; try to release */
4146 (void) CALL_MORECORE(-ssize);
4147 br = CMFAIL;
4148 }
4149 }
4150 }
4151 }
4152 if (br != CMFAIL) { /* Use the space we did get */
4153 tbase = br;
4154 tsize = ssize;
4155 }
4156 else
4157 disable_contiguous(m); /* Don't try contiguous path in the future */
4158 }
4159
4160 RELEASE_MALLOC_GLOBAL_LOCK();
4161 }
4162
4163 if (HAVE_MMAP && tbase == CMFAIL) { /* Try MMAP */
4164 char* mp = (char*)(CALL_MMAP(asize));
4165 if (mp != CMFAIL) {
4166 tbase = mp;
4167 tsize = asize;
4168 mmap_flag = USE_MMAP_BIT;
4169 }
4170 }
4171
4172 if (HAVE_MORECORE && tbase == CMFAIL) { /* Try noncontiguous MORECORE */
4173 if (asize < HALF_MAX_SIZE_T) {
4174 char* br = CMFAIL;
4175 char* end = CMFAIL;
4176 ACQUIRE_MALLOC_GLOBAL_LOCK();
4177 br = (char*)(CALL_MORECORE(asize));
4178 end = (char*)(CALL_MORECORE(0));
4179 RELEASE_MALLOC_GLOBAL_LOCK();
4180 if (br != CMFAIL && end != CMFAIL && br < end) {
4181 size_t ssize = end - br;
4182 if (ssize > nb + TOP_FOOT_SIZE) {
4183 tbase = br;
4184 tsize = ssize;
4185 }
4186 }
4187 }
4188 }
4189
4190 if (tbase != CMFAIL) {
4191
4192 if ((m->footprint += tsize) > m->max_footprint)
4193 m->max_footprint = m->footprint;
4194
4195 if (!is_initialized(m)) { /* first-time initialization */
4196 if (m->least_addr == 0 || tbase < m->least_addr)
4197 m->least_addr = tbase;
4198 m->seg.base = tbase;
4199 m->seg.size = tsize;
4200 m->seg.sflags = mmap_flag;
4201 m->magic = mparams.magic;
4202 m->release_checks = MAX_RELEASE_CHECK_RATE;
4203 init_bins(m);
4204#if !ONLY_MSPACES
4205 if (is_global(m))
4206 init_top(m, (mchunkptr)tbase, tsize - TOP_FOOT_SIZE);
4207 else
4208#endif
4209 {
4210 /* Offset top by embedded malloc_state */
4211 mchunkptr mn = next_chunk(mem2chunk(m));
4212 init_top(m, mn, (size_t)((tbase + tsize) - (char*)mn) -TOP_FOOT_SIZE);
4213 }
4214 }
4215
4216 else {
4217 /* Try to merge with an existing segment */
4218 msegmentptr sp = &m->seg;
4219 /* Only consider most recent segment if traversal suppressed */
4220 while (sp != 0 && tbase != sp->base + sp->size)
4221 sp = (NO_SEGMENT_TRAVERSAL) ? 0 : sp->next;
4222 if (sp != 0 &&
4223 !is_extern_segment(sp) &&
4224 (sp->sflags & USE_MMAP_BIT) == mmap_flag &&
4225 segment_holds(sp, m->top)) { /* append */
4226 sp->size += tsize;
4227 init_top(m, m->top, m->topsize + tsize);
4228 }
4229 else {
4230 if (tbase < m->least_addr)
4231 m->least_addr = tbase;
4232 sp = &m->seg;
4233 while (sp != 0 && sp->base != tbase + tsize)
4234 sp = (NO_SEGMENT_TRAVERSAL) ? 0 : sp->next;
4235 if (sp != 0 &&
4236 !is_extern_segment(sp) &&
4237 (sp->sflags & USE_MMAP_BIT) == mmap_flag) {
4238 char* oldbase = sp->base;
4239 sp->base = tbase;
4240 sp->size += tsize;
4241 return prepend_alloc(m, tbase, oldbase, nb);
4242 }
4243 else
4244 add_segment(m, tbase, tsize, mmap_flag);
4245 }
4246 }
4247
4248 if (nb < m->topsize) { /* Allocate from new or extended top space */
4249 size_t rsize = m->topsize -= nb;
4250 mchunkptr p = m->top;
4251 mchunkptr r = m->top = chunk_plus_offset(p, nb);
4252 r->head = rsize | PINUSE_BIT;
4253 set_size_and_pinuse_of_inuse_chunk(m, p, nb);
4254 check_top_chunk(m, m->top);
4255 check_malloced_chunk(m, chunk2mem(p), nb);
4256 return chunk2mem(p);
4257 }
4258 }
4259
4260 MALLOC_FAILURE_ACTION;
4261 return 0;
4262}
4263
4264/* ----------------------- system deallocation -------------------------- */
4265
4266/* Unmap and unlink any mmapped segments that don't contain used chunks */
4267static size_t release_unused_segments(mstate m) {
4268 size_t released = 0;
4269 int nsegs = 0;
4270 msegmentptr pred = &m->seg;
4271 msegmentptr sp = pred->next;
4272 while (sp != 0) {
4273 char* base = sp->base;
4274 size_t size = sp->size;
4275 msegmentptr next = sp->next;
4276 ++nsegs;
4277 if (is_mmapped_segment(sp) && !is_extern_segment(sp)) {
4278 mchunkptr p = align_as_chunk(base);
4279 size_t psize = chunksize(p);
4280 /* Can unmap if first chunk holds entire segment and not pinned */
4281 if (!is_inuse(p) && (char*)p + psize >= base + size - TOP_FOOT_SIZE) {
4282 tchunkptr tp = (tchunkptr)p;
4283 assert(segment_holds(sp, (char*)sp));
4284 if (p == m->dv) {
4285 m->dv = 0;
4286 m->dvsize = 0;
4287 }
4288 else {
4289 unlink_large_chunk(m, tp);
4290 }
4291 if (CALL_MUNMAP(base, size) == 0) {
4292 released += size;
4293 m->footprint -= size;
4294 /* unlink obsoleted record */
4295 sp = pred;
4296 sp->next = next;
4297 }
4298 else { /* back out if cannot unmap */
4299 insert_large_chunk(m, tp, psize);
4300 }
4301 }
4302 }
4303 if (NO_SEGMENT_TRAVERSAL) /* scan only first segment */
4304 break;
4305 pred = sp;
4306 sp = next;
4307 }
4308 /* Reset check counter */
4309 m->release_checks = (((size_t) nsegs > (size_t) MAX_RELEASE_CHECK_RATE)?
4310 (size_t) nsegs : (size_t) MAX_RELEASE_CHECK_RATE);
4311 return released;
4312}
4313
4314static int sys_trim(mstate m, size_t pad) {
4315 size_t released = 0;
4316 ensure_initialization();
4317 if (pad < MAX_REQUEST && is_initialized(m)) {
4318 pad += TOP_FOOT_SIZE; /* ensure enough room for segment overhead */
4319
4320 if (m->topsize > pad) {
4321 /* Shrink top space in granularity-size units, keeping at least one */
4322 size_t unit = mparams.granularity;
4323 size_t extra = ((m->topsize - pad + (unit - SIZE_T_ONE)) / unit -
4324 SIZE_T_ONE) * unit;
4325 msegmentptr sp = segment_holding(m, (char*)m->top);
4326
4327 if (!is_extern_segment(sp)) {
4328 if (is_mmapped_segment(sp)) {
4329 if (HAVE_MMAP &&
4330 sp->size >= extra &&
4331 !has_segment_link(m, sp)) { /* can't shrink if pinned */
4332 size_t newsize = sp->size - extra;
4333 (void)newsize; /* placate people compiling -Wunused-variable */
4334 /* Prefer mremap, fall back to munmap */
4335 if ((CALL_MREMAP(sp->base, sp->size, newsize, 0) != MFAIL) ||
4336 (CALL_MUNMAP(sp->base + newsize, extra) == 0)) {
4337 released = extra;
4338 }
4339 }
4340 }
4341 else if (HAVE_MORECORE) {
4342 if (extra >= HALF_MAX_SIZE_T) /* Avoid wrapping negative */
4343 extra = (HALF_MAX_SIZE_T) + SIZE_T_ONE - unit;
4344 ACQUIRE_MALLOC_GLOBAL_LOCK();
4345 {
4346 /* Make sure end of memory is where we last set it. */
4347 char* old_br = (char*)(CALL_MORECORE(0));
4348 if (old_br == sp->base + sp->size) {
4349 char* rel_br = (char*)(CALL_MORECORE(-extra));
4350 char* new_br = (char*)(CALL_MORECORE(0));
4351 if (rel_br != CMFAIL && new_br < old_br)
4352 released = old_br - new_br;
4353 }
4354 }
4355 RELEASE_MALLOC_GLOBAL_LOCK();
4356 }
4357 }
4358
4359 if (released != 0) {
4360 sp->size -= released;
4361 m->footprint -= released;
4362 init_top(m, m->top, m->topsize - released);
4363 check_top_chunk(m, m->top);
4364 }
4365 }
4366
4367 /* Unmap any unused mmapped segments */
4368 if (HAVE_MMAP)
4369 released += release_unused_segments(m);
4370
4371 /* On failure, disable autotrim to avoid repeated failed future calls */
4372 if (released == 0 && m->topsize > m->trim_check)
4373 m->trim_check = MAX_SIZE_T;
4374 }
4375
4376 return (released != 0)? 1 : 0;
4377}
4378
4379/* Consolidate and bin a chunk. Differs from exported versions
4380 of free mainly in that the chunk need not be marked as inuse.
4381*/
4382static void dispose_chunk(mstate m, mchunkptr p, size_t psize) {
4383 mchunkptr next = chunk_plus_offset(p, psize);
4384 if (!pinuse(p)) {
4385 mchunkptr prev;
4386 size_t prevsize = p->prev_foot;
4387 if (is_mmapped(p)) {
4388 psize += prevsize + MMAP_FOOT_PAD;
4389 if (CALL_MUNMAP((char*)p - prevsize, psize) == 0)
4390 m->footprint -= psize;
4391 return;
4392 }
4393 prev = chunk_minus_offset(p, prevsize);
4394 psize += prevsize;
4395 p = prev;
4396 if (RTCHECK(ok_address(m, prev))) { /* consolidate backward */
4397 if (p != m->dv) {
4398 unlink_chunk(m, p, prevsize);
4399 }
4400 else if ((next->head & INUSE_BITS) == INUSE_BITS) {
4401 m->dvsize = psize;
4402 set_free_with_pinuse(p, psize, next);
4403 return;
4404 }
4405 }
4406 else {
4407 CORRUPTION_ERROR_ACTION(m);
4408 return;
4409 }
4410 }
4411 if (RTCHECK(ok_address(m, next))) {
4412 if (!cinuse(next)) { /* consolidate forward */
4413 if (next == m->top) {
4414 size_t tsize = m->topsize += psize;
4415 m->top = p;
4416 p->head = tsize | PINUSE_BIT;
4417 if (p == m->dv) {
4418 m->dv = 0;
4419 m->dvsize = 0;
4420 }
4421 return;
4422 }
4423 else if (next == m->dv) {
4424 size_t dsize = m->dvsize += psize;
4425 m->dv = p;
4426 set_size_and_pinuse_of_free_chunk(p, dsize);
4427 return;
4428 }
4429 else {
4430 size_t nsize = chunksize(next);
4431 psize += nsize;
4432 unlink_chunk(m, next, nsize);
4433 set_size_and_pinuse_of_free_chunk(p, psize);
4434 if (p == m->dv) {
4435 m->dvsize = psize;
4436 return;
4437 }
4438 }
4439 }
4440 else {
4441 set_free_with_pinuse(p, psize, next);
4442 }
4443 insert_chunk(m, p, psize);
4444 }
4445 else {
4446 CORRUPTION_ERROR_ACTION(m);
4447 }
4448}
4449
4450/* ---------------------------- malloc --------------------------- */
4451
4452/* allocate a large request from the best fitting chunk in a treebin */
4453static void* tmalloc_large(mstate m, size_t nb) {
4454 tchunkptr v = 0;
4455 size_t rsize = -nb; /* Unsigned negation */
4456 tchunkptr t;
4457 bindex_t idx;
4458 compute_tree_index(nb, idx);
4459 if ((t = *treebin_at(m, idx)) != 0) {
4460 /* Traverse tree for this bin looking for node with size == nb */
4461 size_t sizebits = nb << leftshift_for_tree_index(idx);
4462 tchunkptr rst = 0; /* The deepest untaken right subtree */
4463 for (;;) {
4464 tchunkptr rt;
4465 size_t trem = chunksize(t) - nb;
4466 if (trem < rsize) {
4467 v = t;
4468 if ((rsize = trem) == 0)
4469 break;
4470 }
4471 rt = t->child[1];
4472 t = t->child[(sizebits >> (SIZE_T_BITSIZE-SIZE_T_ONE)) & 1];
4473 if (rt != 0 && rt != t)
4474 rst = rt;
4475 if (t == 0) {
4476 t = rst; /* set t to least subtree holding sizes > nb */
4477 break;
4478 }
4479 sizebits <<= 1;
4480 }
4481 }
4482 if (t == 0 && v == 0) { /* set t to root of next non-empty treebin */
4483 binmap_t leftbits = left_bits(idx2bit(idx)) & m->treemap;
4484 if (leftbits != 0) {
4485 bindex_t i;
4486 binmap_t leastbit = least_bit(leftbits);
4487 compute_bit2idx(leastbit, i);
4488 t = *treebin_at(m, i);
4489 }
4490 }
4491
4492 while (t != 0) { /* find smallest of tree or subtree */
4493 size_t trem = chunksize(t) - nb;
4494 if (trem < rsize) {
4495 rsize = trem;
4496 v = t;
4497 }
4498 t = leftmost_child(t);
4499 }
4500
4501 /* If dv is a better fit, return 0 so malloc will use it */
4502 if (v != 0 && rsize < (size_t)(m->dvsize - nb)) {
4503 if (RTCHECK(ok_address(m, v))) { /* split */
4504 mchunkptr r = chunk_plus_offset(v, nb);
4505 assert(chunksize(v) == rsize + nb);
4506 if (RTCHECK(ok_next(v, r))) {
4507 unlink_large_chunk(m, v);
4508 if (rsize < MIN_CHUNK_SIZE)
4509 set_inuse_and_pinuse(m, v, (rsize + nb));
4510 else {
4511 set_size_and_pinuse_of_inuse_chunk(m, v, nb);
4512 set_size_and_pinuse_of_free_chunk(r, rsize);
4513 insert_chunk(m, r, rsize);
4514 }
4515 return chunk2mem(v);
4516 }
4517 }
4518 CORRUPTION_ERROR_ACTION(m);
4519 }
4520 return 0;
4521}
4522
4523/* allocate a small request from the best fitting chunk in a treebin */
4524static void* tmalloc_small(mstate m, size_t nb) {
4525 tchunkptr t, v;
4526 size_t rsize;
4527 bindex_t i;
4528 binmap_t leastbit = least_bit(m->treemap);
4529 compute_bit2idx(leastbit, i);
4530 v = t = *treebin_at(m, i);
4531 rsize = chunksize(t) - nb;
4532
4533 while ((t = leftmost_child(t)) != 0) {
4534 size_t trem = chunksize(t) - nb;
4535 if (trem < rsize) {
4536 rsize = trem;
4537 v = t;
4538 }
4539 }
4540
4541 if (RTCHECK(ok_address(m, v))) {
4542 mchunkptr r = chunk_plus_offset(v, nb);
4543 assert(chunksize(v) == rsize + nb);
4544 if (RTCHECK(ok_next(v, r))) {
4545 unlink_large_chunk(m, v);
4546 if (rsize < MIN_CHUNK_SIZE)
4547 set_inuse_and_pinuse(m, v, (rsize + nb));
4548 else {
4549 set_size_and_pinuse_of_inuse_chunk(m, v, nb);
4550 set_size_and_pinuse_of_free_chunk(r, rsize);
4551 replace_dv(m, r, rsize);
4552 }
4553 return chunk2mem(v);
4554 }
4555 }
4556
4557 CORRUPTION_ERROR_ACTION(m);
4558 return 0;
4559}
4560
4561#if !ONLY_MSPACES
4562
4563#if __wasilibc_unmodified_upstream // Forward declaration of try_init_allocator.
4564#else
4565static void try_init_allocator(void);
4566#endif
4567
4568void* dlmalloc(size_t bytes) {
4569 /*
4570 Basic algorithm:
4571 If a small request (< 256 bytes minus per-chunk overhead):
4572 1. If one exists, use a remainderless chunk in associated smallbin.
4573 (Remainderless means that there are too few excess bytes to
4574 represent as a chunk.)
4575 2. If it is big enough, use the dv chunk, which is normally the
4576 chunk adjacent to the one used for the most recent small request.
4577 3. If one exists, split the smallest available chunk in a bin,
4578 saving remainder in dv.
4579 4. If it is big enough, use the top chunk.
4580 5. If available, get memory from system and use it
4581 Otherwise, for a large request:
4582 1. Find the smallest available binned chunk that fits, and use it
4583 if it is better fitting than dv chunk, splitting if necessary.
4584 2. If better fitting than any binned chunk, use the dv chunk.
4585 3. If it is big enough, use the top chunk.
4586 4. If request size >= mmap threshold, try to directly mmap this chunk.
4587 5. If available, get memory from system and use it
4588
4589 The ugly goto's here ensure that postaction occurs along all paths.
4590 */
4591
4592#if USE_LOCKS
4593 ensure_initialization(); /* initialize in sys_alloc if not using locks */
4594#endif
4595
4596#if __wasilibc_unmodified_upstream // Try to initialize the allocator.
4597#else
4598 if (!is_initialized(gm)) {
4599 try_init_allocator();
4600 }
4601#endif
4602
4603 if (!PREACTION(gm)) {
4604 void* mem;
4605 size_t nb;
4606 if (bytes <= MAX_SMALL_REQUEST) {
4607 bindex_t idx;
4608 binmap_t smallbits;
4609 nb = (bytes < MIN_REQUEST)? MIN_CHUNK_SIZE : pad_request(bytes);
4610 idx = small_index(nb);
4611 smallbits = gm->smallmap >> idx;
4612
4613 if ((smallbits & 0x3U) != 0) { /* Remainderless fit to a smallbin. */
4614 mchunkptr b, p;
4615 idx += ~smallbits & 1; /* Uses next bin if idx empty */
4616 b = smallbin_at(gm, idx);
4617 p = b->fd;
4618 assert(chunksize(p) == small_index2size(idx));
4619 unlink_first_small_chunk(gm, b, p, idx);
4620 set_inuse_and_pinuse(gm, p, small_index2size(idx));
4621 mem = chunk2mem(p);
4622 check_malloced_chunk(gm, mem, nb);
4623 goto postaction;
4624 }
4625
4626 else if (nb > gm->dvsize) {
4627 if (smallbits != 0) { /* Use chunk in next nonempty smallbin */
4628 mchunkptr b, p, r;
4629 size_t rsize;
4630 bindex_t i;
4631 binmap_t leftbits = (smallbits << idx) & left_bits(idx2bit(idx));
4632 binmap_t leastbit = least_bit(leftbits);
4633 compute_bit2idx(leastbit, i);
4634 b = smallbin_at(gm, i);
4635 p = b->fd;
4636 assert(chunksize(p) == small_index2size(i));
4637 unlink_first_small_chunk(gm, b, p, i);
4638 rsize = small_index2size(i) - nb;
4639 /* Fit here cannot be remainderless if 4byte sizes */
4640 if (SIZE_T_SIZE != 4 && rsize < MIN_CHUNK_SIZE)
4641 set_inuse_and_pinuse(gm, p, small_index2size(i));
4642 else {
4643 set_size_and_pinuse_of_inuse_chunk(gm, p, nb);
4644 r = chunk_plus_offset(p, nb);
4645 set_size_and_pinuse_of_free_chunk(r, rsize);
4646 replace_dv(gm, r, rsize);
4647 }
4648 mem = chunk2mem(p);
4649 check_malloced_chunk(gm, mem, nb);
4650 goto postaction;
4651 }
4652
4653 else if (gm->treemap != 0 && (mem = tmalloc_small(gm, nb)) != 0) {
4654 check_malloced_chunk(gm, mem, nb);
4655 goto postaction;
4656 }
4657 }
4658 }
4659 else if (bytes >= MAX_REQUEST)
4660 nb = MAX_SIZE_T; /* Too big to allocate. Force failure (in sys alloc) */
4661 else {
4662 nb = pad_request(bytes);
4663 if (gm->treemap != 0 && (mem = tmalloc_large(gm, nb)) != 0) {
4664 check_malloced_chunk(gm, mem, nb);
4665 goto postaction;
4666 }
4667 }
4668
4669 if (nb <= gm->dvsize) {
4670 size_t rsize = gm->dvsize - nb;
4671 mchunkptr p = gm->dv;
4672 if (rsize >= MIN_CHUNK_SIZE) { /* split dv */
4673 mchunkptr r = gm->dv = chunk_plus_offset(p, nb);
4674 gm->dvsize = rsize;
4675 set_size_and_pinuse_of_free_chunk(r, rsize);
4676 set_size_and_pinuse_of_inuse_chunk(gm, p, nb);
4677 }
4678 else { /* exhaust dv */
4679 size_t dvs = gm->dvsize;
4680 gm->dvsize = 0;
4681 gm->dv = 0;
4682 set_inuse_and_pinuse(gm, p, dvs);
4683 }
4684 mem = chunk2mem(p);
4685 check_malloced_chunk(gm, mem, nb);
4686 goto postaction;
4687 }
4688
4689 else if (nb < gm->topsize) { /* Split top */
4690 size_t rsize = gm->topsize -= nb;
4691 mchunkptr p = gm->top;
4692 mchunkptr r = gm->top = chunk_plus_offset(p, nb);
4693 r->head = rsize | PINUSE_BIT;
4694 set_size_and_pinuse_of_inuse_chunk(gm, p, nb);
4695 mem = chunk2mem(p);
4696 check_top_chunk(gm, gm->top);
4697 check_malloced_chunk(gm, mem, nb);
4698 goto postaction;
4699 }
4700
4701 mem = sys_alloc(gm, nb);
4702
4703 postaction:
4704 POSTACTION(gm);
4705 return mem;
4706 }
4707
4708 return 0;
4709}
4710
4711/* ---------------------------- free --------------------------- */
4712
4713void dlfree(void* mem) {
4714 /*
4715 Consolidate freed chunks with preceeding or succeeding bordering
4716 free chunks, if they exist, and then place in a bin. Intermixed
4717 with special cases for top, dv, mmapped chunks, and usage errors.
4718 */
4719
4720 if (mem != 0) {
4721 mchunkptr p = mem2chunk(mem);
4722#if FOOTERS
4723 mstate fm = get_mstate_for(p);
4724 if (!ok_magic(fm)) {
4725 USAGE_ERROR_ACTION(fm, p);
4726 return;
4727 }
4728#else /* FOOTERS */
4729#define fm gm
4730#endif /* FOOTERS */
4731 if (!PREACTION(fm)) {
4732 check_inuse_chunk(fm, p);
4733 if (RTCHECK(ok_address(fm, p) && ok_inuse(p))) {
4734 size_t psize = chunksize(p);
4735 mchunkptr next = chunk_plus_offset(p, psize);
4736 if (!pinuse(p)) {
4737 size_t prevsize = p->prev_foot;
4738 if (is_mmapped(p)) {
4739 psize += prevsize + MMAP_FOOT_PAD;
4740 if (CALL_MUNMAP((char*)p - prevsize, psize) == 0)
4741 fm->footprint -= psize;
4742 goto postaction;
4743 }
4744 else {
4745 mchunkptr prev = chunk_minus_offset(p, prevsize);
4746 psize += prevsize;
4747 p = prev;
4748 if (RTCHECK(ok_address(fm, prev))) { /* consolidate backward */
4749 if (p != fm->dv) {
4750 unlink_chunk(fm, p, prevsize);
4751 }
4752 else if ((next->head & INUSE_BITS) == INUSE_BITS) {
4753 fm->dvsize = psize;
4754 set_free_with_pinuse(p, psize, next);
4755 goto postaction;
4756 }
4757 }
4758 else
4759 goto erroraction;
4760 }
4761 }
4762
4763 if (RTCHECK(ok_next(p, next) && ok_pinuse(next))) {
4764 if (!cinuse(next)) { /* consolidate forward */
4765 if (next == fm->top) {
4766 size_t tsize = fm->topsize += psize;
4767 fm->top = p;
4768 p->head = tsize | PINUSE_BIT;
4769 if (p == fm->dv) {
4770 fm->dv = 0;
4771 fm->dvsize = 0;
4772 }
4773 if (should_trim(fm, tsize))
4774 sys_trim(fm, 0);
4775 goto postaction;
4776 }
4777 else if (next == fm->dv) {
4778 size_t dsize = fm->dvsize += psize;
4779 fm->dv = p;
4780 set_size_and_pinuse_of_free_chunk(p, dsize);
4781 goto postaction;
4782 }
4783 else {
4784 size_t nsize = chunksize(next);
4785 psize += nsize;
4786 unlink_chunk(fm, next, nsize);
4787 set_size_and_pinuse_of_free_chunk(p, psize);
4788 if (p == fm->dv) {
4789 fm->dvsize = psize;
4790 goto postaction;
4791 }
4792 }
4793 }
4794 else
4795 set_free_with_pinuse(p, psize, next);
4796
4797 if (is_small(psize)) {
4798 insert_small_chunk(fm, p, psize);
4799 check_free_chunk(fm, p);
4800 }
4801 else {
4802 tchunkptr tp = (tchunkptr)p;
4803 insert_large_chunk(fm, tp, psize);
4804 check_free_chunk(fm, p);
4805 if (--fm->release_checks == 0)
4806 release_unused_segments(fm);
4807 }
4808 goto postaction;
4809 }
4810 }
4811 erroraction:
4812 USAGE_ERROR_ACTION(fm, p);
4813 postaction:
4814 POSTACTION(fm);
4815 }
4816 }
4817#if !FOOTERS
4818#undef fm
4819#endif /* FOOTERS */
4820}
4821
4822void* dlcalloc(size_t n_elements, size_t elem_size) {
4823 void* mem;
4824 size_t req = 0;
4825 if (n_elements != 0) {
4826 req = n_elements * elem_size;
4827 if (((n_elements | elem_size) & ~(size_t)0xffff) &&
4828 (req / n_elements != elem_size))
4829 req = MAX_SIZE_T; /* force downstream failure on overflow */
4830 }
4831 mem = dlmalloc(req);
4832 if (mem != 0 && calloc_must_clear(mem2chunk(mem)))
4833 memset(mem, 0, req);
4834 return mem;
4835}
4836
4837#endif /* !ONLY_MSPACES */
4838
4839/* ------------ Internal support for realloc, memalign, etc -------------- */
4840
4841/* Try to realloc; only in-place unless can_move true */
4842static mchunkptr try_realloc_chunk(mstate m, mchunkptr p, size_t nb,
4843 int can_move) {
4844 mchunkptr newp = 0;
4845 size_t oldsize = chunksize(p);
4846 mchunkptr next = chunk_plus_offset(p, oldsize);
4847 if (RTCHECK(ok_address(m, p) && ok_inuse(p) &&
4848 ok_next(p, next) && ok_pinuse(next))) {
4849 if (is_mmapped(p)) {
4850 newp = mmap_resize(m, p, nb, can_move);
4851 }
4852 else if (oldsize >= nb) { /* already big enough */
4853 size_t rsize = oldsize - nb;
4854 if (rsize >= MIN_CHUNK_SIZE) { /* split off remainder */
4855 mchunkptr r = chunk_plus_offset(p, nb);
4856 set_inuse(m, p, nb);
4857 set_inuse(m, r, rsize);
4858 dispose_chunk(m, r, rsize);
4859 }
4860 newp = p;
4861 }
4862 else if (next == m->top) { /* extend into top */
4863 if (oldsize + m->topsize > nb) {
4864 size_t newsize = oldsize + m->topsize;
4865 size_t newtopsize = newsize - nb;
4866 mchunkptr newtop = chunk_plus_offset(p, nb);
4867 set_inuse(m, p, nb);
4868 newtop->head = newtopsize |PINUSE_BIT;
4869 m->top = newtop;
4870 m->topsize = newtopsize;
4871 newp = p;
4872 }
4873 }
4874 else if (next == m->dv) { /* extend into dv */
4875 size_t dvs = m->dvsize;
4876 if (oldsize + dvs >= nb) {
4877 size_t dsize = oldsize + dvs - nb;
4878 if (dsize >= MIN_CHUNK_SIZE) {
4879 mchunkptr r = chunk_plus_offset(p, nb);
4880 mchunkptr n = chunk_plus_offset(r, dsize);
4881 set_inuse(m, p, nb);
4882 set_size_and_pinuse_of_free_chunk(r, dsize);
4883 clear_pinuse(n);
4884 m->dvsize = dsize;
4885 m->dv = r;
4886 }
4887 else { /* exhaust dv */
4888 size_t newsize = oldsize + dvs;
4889 set_inuse(m, p, newsize);
4890 m->dvsize = 0;
4891 m->dv = 0;
4892 }
4893 newp = p;
4894 }
4895 }
4896 else if (!cinuse(next)) { /* extend into next free chunk */
4897 size_t nextsize = chunksize(next);
4898 if (oldsize + nextsize >= nb) {
4899 size_t rsize = oldsize + nextsize - nb;
4900 unlink_chunk(m, next, nextsize);
4901 if (rsize < MIN_CHUNK_SIZE) {
4902 size_t newsize = oldsize + nextsize;
4903 set_inuse(m, p, newsize);
4904 }
4905 else {
4906 mchunkptr r = chunk_plus_offset(p, nb);
4907 set_inuse(m, p, nb);
4908 set_inuse(m, r, rsize);
4909 dispose_chunk(m, r, rsize);
4910 }
4911 newp = p;
4912 }
4913 }
4914 }
4915 else {
4916 USAGE_ERROR_ACTION(m, chunk2mem(p));
4917 }
4918 return newp;
4919}
4920
4921static void* internal_memalign(mstate m, size_t alignment, size_t bytes) {
4922 void* mem = 0;
4923 if (alignment < MIN_CHUNK_SIZE) /* must be at least a minimum chunk size */
4924 alignment = MIN_CHUNK_SIZE;
4925 if ((alignment & (alignment-SIZE_T_ONE)) != 0) {/* Ensure a power of 2 */
4926 size_t a = MALLOC_ALIGNMENT << 1;
4927 while (a < alignment) a <<= 1;
4928 alignment = a;
4929 }
4930 if (bytes >= MAX_REQUEST - alignment) {
4931 if (m != 0) { /* Test isn't needed but avoids compiler warning */
4932 MALLOC_FAILURE_ACTION;
4933 }
4934 }
4935 else {
4936 size_t nb = request2size(bytes);
4937 size_t req = nb + alignment + MIN_CHUNK_SIZE - CHUNK_OVERHEAD;
4938 mem = internal_malloc(m, req);
4939 if (mem != 0) {
4940 mchunkptr p = mem2chunk(mem);
4941 if (PREACTION(m))
4942 return 0;
4943 if ((((size_t)(mem)) & (alignment - 1)) != 0) { /* misaligned */
4944 /*
4945 Find an aligned spot inside chunk. Since we need to give
4946 back leading space in a chunk of at least MIN_CHUNK_SIZE, if
4947 the first calculation places us at a spot with less than
4948 MIN_CHUNK_SIZE leader, we can move to the next aligned spot.
4949 We've allocated enough total room so that this is always
4950 possible.
4951 */
4952 char* br = (char*)mem2chunk((size_t)(((size_t)((char*)mem + alignment -
4953 SIZE_T_ONE)) &
4954 -alignment));
4955 char* pos = ((size_t)(br - (char*)(p)) >= MIN_CHUNK_SIZE)?
4956 br : br+alignment;
4957 mchunkptr newp = (mchunkptr)pos;
4958 size_t leadsize = pos - (char*)(p);
4959 size_t newsize = chunksize(p) - leadsize;
4960
4961 if (is_mmapped(p)) { /* For mmapped chunks, just adjust offset */
4962 newp->prev_foot = p->prev_foot + leadsize;
4963 newp->head = newsize;
4964 }
4965 else { /* Otherwise, give back leader, use the rest */
4966 set_inuse(m, newp, newsize);
4967 set_inuse(m, p, leadsize);
4968 dispose_chunk(m, p, leadsize);
4969 }
4970 p = newp;
4971 }
4972
4973 /* Give back spare room at the end */
4974 if (!is_mmapped(p)) {
4975 size_t size = chunksize(p);
4976 if (size > nb + MIN_CHUNK_SIZE) {
4977 size_t remainder_size = size - nb;
4978 mchunkptr remainder = chunk_plus_offset(p, nb);
4979 set_inuse(m, p, nb);
4980 set_inuse(m, remainder, remainder_size);
4981 dispose_chunk(m, remainder, remainder_size);
4982 }
4983 }
4984
4985 mem = chunk2mem(p);
4986 assert (chunksize(p) >= nb);
4987 assert(((size_t)mem & (alignment - 1)) == 0);
4988 check_inuse_chunk(m, p);
4989 POSTACTION(m);
4990 }
4991 }
4992 return mem;
4993}
4994
4995/*
4996 Common support for independent_X routines, handling
4997 all of the combinations that can result.
4998 The opts arg has:
4999 bit 0 set if all elements are same size (using sizes[0])
5000 bit 1 set if elements should be zeroed
5001*/
5002static void** ialloc(mstate m,
5003 size_t n_elements,
5004 size_t* sizes,
5005 int opts,
5006 void* chunks[]) {
5007
5008 size_t element_size; /* chunksize of each element, if all same */
5009 size_t contents_size; /* total size of elements */
5010 size_t array_size; /* request size of pointer array */
5011 void* mem; /* malloced aggregate space */
5012 mchunkptr p; /* corresponding chunk */
5013 size_t remainder_size; /* remaining bytes while splitting */
5014 void** marray; /* either "chunks" or malloced ptr array */
5015 mchunkptr array_chunk; /* chunk for malloced ptr array */
5016 flag_t was_enabled; /* to disable mmap */
5017 size_t size;
5018 size_t i;
5019
5020 ensure_initialization();
5021 /* compute array length, if needed */
5022 if (chunks != 0) {
5023 if (n_elements == 0)
5024 return chunks; /* nothing to do */
5025 marray = chunks;
5026 array_size = 0;
5027 }
5028 else {
5029 /* if empty req, must still return chunk representing empty array */
5030 if (n_elements == 0)
5031 return (void**)internal_malloc(m, 0);
5032 marray = 0;
5033 array_size = request2size(n_elements * (sizeof(void*)));
5034 }
5035
5036 /* compute total element size */
5037 if (opts & 0x1) { /* all-same-size */
5038 element_size = request2size(*sizes);
5039 contents_size = n_elements * element_size;
5040 }
5041 else { /* add up all the sizes */
5042 element_size = 0;
5043 contents_size = 0;
5044 for (i = 0; i != n_elements; ++i)
5045 contents_size += request2size(sizes[i]);
5046 }
5047
5048 size = contents_size + array_size;
5049
5050 /*
5051 Allocate the aggregate chunk. First disable direct-mmapping so
5052 malloc won't use it, since we would not be able to later
5053 free/realloc space internal to a segregated mmap region.
5054 */
5055 was_enabled = use_mmap(m);
5056 disable_mmap(m);
5057 mem = internal_malloc(m, size - CHUNK_OVERHEAD);
5058 if (was_enabled)
5059 enable_mmap(m);
5060 if (mem == 0)
5061 return 0;
5062
5063 if (PREACTION(m)) return 0;
5064 p = mem2chunk(mem);
5065 remainder_size = chunksize(p);
5066
5067 assert(!is_mmapped(p));
5068
5069 if (opts & 0x2) { /* optionally clear the elements */
5070 memset((size_t*)mem, 0, remainder_size - SIZE_T_SIZE - array_size);
5071 }
5072
5073 /* If not provided, allocate the pointer array as final part of chunk */
5074 if (marray == 0) {
5075 size_t array_chunk_size;
5076 array_chunk = chunk_plus_offset(p, contents_size);
5077 array_chunk_size = remainder_size - contents_size;
5078 marray = (void**) (chunk2mem(array_chunk));
5079 set_size_and_pinuse_of_inuse_chunk(m, array_chunk, array_chunk_size);
5080 remainder_size = contents_size;
5081 }
5082
5083 /* split out elements */
5084 for (i = 0; ; ++i) {
5085 marray[i] = chunk2mem(p);
5086 if (i != n_elements-1) {
5087 if (element_size != 0)
5088 size = element_size;
5089 else
5090 size = request2size(sizes[i]);
5091 remainder_size -= size;
5092 set_size_and_pinuse_of_inuse_chunk(m, p, size);
5093 p = chunk_plus_offset(p, size);
5094 }
5095 else { /* the final element absorbs any overallocation slop */
5096 set_size_and_pinuse_of_inuse_chunk(m, p, remainder_size);
5097 break;
5098 }
5099 }
5100
5101#if DEBUG
5102 if (marray != chunks) {
5103 /* final element must have exactly exhausted chunk */
5104 if (element_size != 0) {
5105 assert(remainder_size == element_size);
5106 }
5107 else {
5108 assert(remainder_size == request2size(sizes[i]));
5109 }
5110 check_inuse_chunk(m, mem2chunk(marray));
5111 }
5112 for (i = 0; i != n_elements; ++i)
5113 check_inuse_chunk(m, mem2chunk(marray[i]));
5114
5115#endif /* DEBUG */
5116
5117 POSTACTION(m);
5118 return marray;
5119}
5120
5121/* Try to free all pointers in the given array.
5122 Note: this could be made faster, by delaying consolidation,
5123 at the price of disabling some user integrity checks, We
5124 still optimize some consolidations by combining adjacent
5125 chunks before freeing, which will occur often if allocated
5126 with ialloc or the array is sorted.
5127*/
5128static size_t internal_bulk_free(mstate m, void* array[], size_t nelem) {
5129 size_t unfreed = 0;
5130 if (!PREACTION(m)) {
5131 void** a;
5132 void** fence = &(array[nelem]);
5133 for (a = array; a != fence; ++a) {
5134 void* mem = *a;
5135 if (mem != 0) {
5136 mchunkptr p = mem2chunk(mem);
5137 size_t psize = chunksize(p);
5138#if FOOTERS
5139 if (get_mstate_for(p) != m) {
5140 ++unfreed;
5141 continue;
5142 }
5143#endif
5144 check_inuse_chunk(m, p);
5145 *a = 0;
5146 if (RTCHECK(ok_address(m, p) && ok_inuse(p))) {
5147 void ** b = a + 1; /* try to merge with next chunk */
5148 mchunkptr next = next_chunk(p);
5149 if (b != fence && *b == chunk2mem(next)) {
5150 size_t newsize = chunksize(next) + psize;
5151 set_inuse(m, p, newsize);
5152 *b = chunk2mem(p);
5153 }
5154 else
5155 dispose_chunk(m, p, psize);
5156 }
5157 else {
5158 CORRUPTION_ERROR_ACTION(m);
5159 break;
5160 }
5161 }
5162 }
5163 if (should_trim(m, m->topsize))
5164 sys_trim(m, 0);
5165 POSTACTION(m);
5166 }
5167 return unfreed;
5168}
5169
5170/* Traversal */
5171#if MALLOC_INSPECT_ALL
5172static void internal_inspect_all(mstate m,
5173 void(*handler)(void *start,
5174 void *end,
5175 size_t used_bytes,
5176 void* callback_arg),
5177 void* arg) {
5178 if (is_initialized(m)) {
5179 mchunkptr top = m->top;
5180 msegmentptr s;
5181 for (s = &m->seg; s != 0; s = s->next) {
5182 mchunkptr q = align_as_chunk(s->base);
5183 while (segment_holds(s, q) && q->head != FENCEPOST_HEAD) {
5184 mchunkptr next = next_chunk(q);
5185 size_t sz = chunksize(q);
5186 size_t used;
5187 void* start;
5188 if (is_inuse(q)) {
5189 used = sz - CHUNK_OVERHEAD; /* must not be mmapped */
5190 start = chunk2mem(q);
5191 }
5192 else {
5193 used = 0;
5194 if (is_small(sz)) { /* offset by possible bookkeeping */
5195 start = (void*)((char*)q + sizeof(struct malloc_chunk));
5196 }
5197 else {
5198 start = (void*)((char*)q + sizeof(struct malloc_tree_chunk));
5199 }
5200 }
5201 if (start < (void*)next) /* skip if all space is bookkeeping */
5202 handler(start, next, used, arg);
5203 if (q == top)
5204 break;
5205 q = next;
5206 }
5207 }
5208 }
5209}
5210#endif /* MALLOC_INSPECT_ALL */
5211
5212#ifdef __wasilibc_unmodified_upstream // Define a function that initializes the initial state of dlmalloc.
5213#else
5214/* ------------------ Exported try_init_allocator -------------------- */
5215
5216/* Symbol marking the end of data, bss and explicit stack, provided by wasm-ld. */
5217extern unsigned char __heap_base;
5218
5219/* Initialize the initial state of dlmalloc to be able to use free memory between __heap_base and initial. */
5220static void try_init_allocator(void) {
5221 /* Check that it is a first-time initialization. */
5222 assert(!is_initialized(gm));
5223
5224 char *base = (char *)&__heap_base;
5225 /* Calls sbrk(0) that returns the initial memory position. */
5226 char *init = (char *)CALL_MORECORE(0);
5227 int initial_heap_size = init - base;
5228
5229 /* Check that initial heap is long enough to serve a minimal allocation request. */
5230 if (initial_heap_size <= MIN_CHUNK_SIZE + TOP_FOOT_SIZE + MALLOC_ALIGNMENT) {
5231 return;
5232 }
5233
5234 /* Initialize mstate. */
5235 ensure_initialization();
5236
5237 /* Initialize the dlmalloc internal state. */
5238 gm->least_addr = base;
5239 gm->seg.base = base;
5240 gm->seg.size = initial_heap_size;
5241 gm->magic = mparams.magic;
5242 gm->release_checks = MAX_RELEASE_CHECK_RATE;
5243 init_bins(gm);
5244 init_top(gm, (mchunkptr)base, initial_heap_size - TOP_FOOT_SIZE);
5245}
5246#endif
5247
5248/* ------------------ Exported realloc, memalign, etc -------------------- */
5249
5250#if !ONLY_MSPACES
5251
5252void* dlrealloc(void* oldmem, size_t bytes) {
5253 void* mem = 0;
5254 if (oldmem == 0) {
5255 mem = dlmalloc(bytes);
5256 }
5257 else if (bytes >= MAX_REQUEST) {
5258 MALLOC_FAILURE_ACTION;
5259 }
5260#ifdef REALLOC_ZERO_BYTES_FREES
5261 else if (bytes == 0) {
5262 dlfree(oldmem);
5263 }
5264#endif /* REALLOC_ZERO_BYTES_FREES */
5265 else {
5266 size_t nb = request2size(bytes);
5267 mchunkptr oldp = mem2chunk(oldmem);
5268#if ! FOOTERS
5269 mstate m = gm;
5270#else /* FOOTERS */
5271 mstate m = get_mstate_for(oldp);
5272 if (!ok_magic(m)) {
5273 USAGE_ERROR_ACTION(m, oldmem);
5274 return 0;
5275 }
5276#endif /* FOOTERS */
5277 if (!PREACTION(m)) {
5278 mchunkptr newp = try_realloc_chunk(m, oldp, nb, 1);
5279 POSTACTION(m);
5280 if (newp != 0) {
5281 check_inuse_chunk(m, newp);
5282 mem = chunk2mem(newp);
5283 }
5284 else {
5285 mem = internal_malloc(m, bytes);
5286 if (mem != 0) {
5287 size_t oc = chunksize(oldp) - overhead_for(oldp);
5288 memcpy(mem, oldmem, (oc < bytes)? oc : bytes);
5289 internal_free(m, oldmem);
5290 }
5291 }
5292 }
5293 }
5294 return mem;
5295}
5296
5297void* dlrealloc_in_place(void* oldmem, size_t bytes) {
5298 void* mem = 0;
5299 if (oldmem != 0) {
5300 if (bytes >= MAX_REQUEST) {
5301 MALLOC_FAILURE_ACTION;
5302 }
5303 else {
5304 size_t nb = request2size(bytes);
5305 mchunkptr oldp = mem2chunk(oldmem);
5306#if ! FOOTERS
5307 mstate m = gm;
5308#else /* FOOTERS */
5309 mstate m = get_mstate_for(oldp);
5310 if (!ok_magic(m)) {
5311 USAGE_ERROR_ACTION(m, oldmem);
5312 return 0;
5313 }
5314#endif /* FOOTERS */
5315 if (!PREACTION(m)) {
5316 mchunkptr newp = try_realloc_chunk(m, oldp, nb, 0);
5317 POSTACTION(m);
5318 if (newp == oldp) {
5319 check_inuse_chunk(m, newp);
5320 mem = oldmem;
5321 }
5322 }
5323 }
5324 }
5325 return mem;
5326}
5327
5328void* dlmemalign(size_t alignment, size_t bytes) {
5329 if (alignment <= MALLOC_ALIGNMENT) {
5330 return dlmalloc(bytes);
5331 }
5332 return internal_memalign(gm, alignment, bytes);
5333}
5334
5335int dlposix_memalign(void** pp, size_t alignment, size_t bytes) {
5336 void* mem = 0;
5337 if (alignment == MALLOC_ALIGNMENT)
5338 mem = dlmalloc(bytes);
5339 else {
5340 size_t d = alignment / sizeof(void*);
5341 size_t r = alignment % sizeof(void*);
5342 if (r != 0 || d == 0 || (d & (d-SIZE_T_ONE)) != 0)
5343 return EINVAL;
5344 else if (bytes <= MAX_REQUEST - alignment) {
5345 if (alignment < MIN_CHUNK_SIZE)
5346 alignment = MIN_CHUNK_SIZE;
5347 mem = internal_memalign(gm, alignment, bytes);
5348 }
5349 }
5350 if (mem == 0)
5351 return ENOMEM;
5352 else {
5353 *pp = mem;
5354 return 0;
5355 }
5356}
5357
5358void* dlvalloc(size_t bytes) {
5359 size_t pagesz;
5360 ensure_initialization();
5361 pagesz = mparams.page_size;
5362 return dlmemalign(pagesz, bytes);
5363}
5364
5365void* dlpvalloc(size_t bytes) {
5366 size_t pagesz;
5367 ensure_initialization();
5368 pagesz = mparams.page_size;
5369 return dlmemalign(pagesz, (bytes + pagesz - SIZE_T_ONE) & ~(pagesz - SIZE_T_ONE));
5370}
5371
5372void** dlindependent_calloc(size_t n_elements, size_t elem_size,
5373 void* chunks[]) {
5374 size_t sz = elem_size; /* serves as 1-element array */
5375 return ialloc(gm, n_elements, &sz, 3, chunks);
5376}
5377
5378void** dlindependent_comalloc(size_t n_elements, size_t sizes[],
5379 void* chunks[]) {
5380 return ialloc(gm, n_elements, sizes, 0, chunks);
5381}
5382
5383size_t dlbulk_free(void* array[], size_t nelem) {
5384 return internal_bulk_free(gm, array, nelem);
5385}
5386
5387#if MALLOC_INSPECT_ALL
5388void dlmalloc_inspect_all(void(*handler)(void *start,
5389 void *end,
5390 size_t used_bytes,
5391 void* callback_arg),
5392 void* arg) {
5393 ensure_initialization();
5394 if (!PREACTION(gm)) {
5395 internal_inspect_all(gm, handler, arg);
5396 POSTACTION(gm);
5397 }
5398}
5399#endif /* MALLOC_INSPECT_ALL */
5400
5401int dlmalloc_trim(size_t pad) {
5402 int result = 0;
5403 ensure_initialization();
5404 if (!PREACTION(gm)) {
5405 result = sys_trim(gm, pad);
5406 POSTACTION(gm);
5407 }
5408 return result;
5409}
5410
5411size_t dlmalloc_footprint(void) {
5412 return gm->footprint;
5413}
5414
5415size_t dlmalloc_max_footprint(void) {
5416 return gm->max_footprint;
5417}
5418
5419size_t dlmalloc_footprint_limit(void) {
5420 size_t maf = gm->footprint_limit;
5421 return maf == 0 ? MAX_SIZE_T : maf;
5422}
5423
5424size_t dlmalloc_set_footprint_limit(size_t bytes) {
5425 size_t result; /* invert sense of 0 */
5426 if (bytes == 0)
5427 result = granularity_align(1); /* Use minimal size */
5428 if (bytes == MAX_SIZE_T)
5429 result = 0; /* disable */
5430 else
5431 result = granularity_align(bytes);
5432 return gm->footprint_limit = result;
5433}
5434
5435#if !NO_MALLINFO
5436struct mallinfo dlmallinfo(void) {
5437 return internal_mallinfo(gm);
5438}
5439#endif /* NO_MALLINFO */
5440
5441#if !NO_MALLOC_STATS
5442void dlmalloc_stats() {
5443 internal_malloc_stats(gm);
5444}
5445#endif /* NO_MALLOC_STATS */
5446
5447int dlmallopt(int param_number, int value) {
5448 return change_mparam(param_number, value);
5449}
5450
5451size_t dlmalloc_usable_size(void* mem) {
5452 if (mem != 0) {
5453 mchunkptr p = mem2chunk(mem);
5454 if (is_inuse(p))
5455 return chunksize(p) - overhead_for(p);
5456 }
5457 return 0;
5458}
5459
5460#endif /* !ONLY_MSPACES */
5461
5462/* ----------------------------- user mspaces ---------------------------- */
5463
5464#if MSPACES
5465
5466static mstate init_user_mstate(char* tbase, size_t tsize) {
5467 size_t msize = pad_request(sizeof(struct malloc_state));
5468 mchunkptr mn;
5469 mchunkptr msp = align_as_chunk(tbase);
5470 mstate m = (mstate)(chunk2mem(msp));
5471 memset(m, 0, msize);
5472 (void)INITIAL_LOCK(&m->mutex);
5473 msp->head = (msize|INUSE_BITS);
5474 m->seg.base = m->least_addr = tbase;
5475 m->seg.size = m->footprint = m->max_footprint = tsize;
5476 m->magic = mparams.magic;
5477 m->release_checks = MAX_RELEASE_CHECK_RATE;
5478 m->mflags = mparams.default_mflags;
5479 m->extp = 0;
5480 m->exts = 0;
5481 disable_contiguous(m);
5482 init_bins(m);
5483 mn = next_chunk(mem2chunk(m));
5484 init_top(m, mn, (size_t)((tbase + tsize) - (char*)mn) - TOP_FOOT_SIZE);
5485 check_top_chunk(m, m->top);
5486 return m;
5487}
5488
5489mspace create_mspace(size_t capacity, int locked) {
5490 mstate m = 0;
5491 size_t msize;
5492 ensure_initialization();
5493 msize = pad_request(sizeof(struct malloc_state));
5494 if (capacity < (size_t) -(msize + TOP_FOOT_SIZE + mparams.page_size)) {
5495 size_t rs = ((capacity == 0)? mparams.granularity :
5496 (capacity + TOP_FOOT_SIZE + msize));
5497 size_t tsize = granularity_align(rs);
5498 char* tbase = (char*)(CALL_MMAP(tsize));
5499 if (tbase != CMFAIL) {
5500 m = init_user_mstate(tbase, tsize);
5501 m->seg.sflags = USE_MMAP_BIT;
5502 set_lock(m, locked);
5503 }
5504 }
5505 return (mspace)m;
5506}
5507
5508mspace create_mspace_with_base(void* base, size_t capacity, int locked) {
5509 mstate m = 0;
5510 size_t msize;
5511 ensure_initialization();
5512 msize = pad_request(sizeof(struct malloc_state));
5513 if (capacity > msize + TOP_FOOT_SIZE &&
5514 capacity < (size_t) -(msize + TOP_FOOT_SIZE + mparams.page_size)) {
5515 m = init_user_mstate((char*)base, capacity);
5516 m->seg.sflags = EXTERN_BIT;
5517 set_lock(m, locked);
5518 }
5519 return (mspace)m;
5520}
5521
5522int mspace_track_large_chunks(mspace msp, int enable) {
5523 int ret = 0;
5524 mstate ms = (mstate)msp;
5525 if (!PREACTION(ms)) {
5526 if (!use_mmap(ms)) {
5527 ret = 1;
5528 }
5529 if (!enable) {
5530 enable_mmap(ms);
5531 } else {
5532 disable_mmap(ms);
5533 }
5534 POSTACTION(ms);
5535 }
5536 return ret;
5537}
5538
5539size_t destroy_mspace(mspace msp) {
5540 size_t freed = 0;
5541 mstate ms = (mstate)msp;
5542 if (ok_magic(ms)) {
5543 msegmentptr sp = &ms->seg;
5544 (void)DESTROY_LOCK(&ms->mutex); /* destroy before unmapped */
5545 while (sp != 0) {
5546 char* base = sp->base;
5547 size_t size = sp->size;
5548 flag_t flag = sp->sflags;
5549 (void)base; /* placate people compiling -Wunused-variable */
5550 sp = sp->next;
5551 if ((flag & USE_MMAP_BIT) && !(flag & EXTERN_BIT) &&
5552 CALL_MUNMAP(base, size) == 0)
5553 freed += size;
5554 }
5555 }
5556 else {
5557 USAGE_ERROR_ACTION(ms,ms);
5558 }
5559 return freed;
5560}
5561
5562/*
5563 mspace versions of routines are near-clones of the global
5564 versions. This is not so nice but better than the alternatives.
5565*/
5566
5567void* mspace_malloc(mspace msp, size_t bytes) {
5568 mstate ms = (mstate)msp;
5569 if (!ok_magic(ms)) {
5570 USAGE_ERROR_ACTION(ms,ms);
5571 return 0;
5572 }
5573 if (!PREACTION(ms)) {
5574 void* mem;
5575 size_t nb;
5576 if (bytes <= MAX_SMALL_REQUEST) {
5577 bindex_t idx;
5578 binmap_t smallbits;
5579 nb = (bytes < MIN_REQUEST)? MIN_CHUNK_SIZE : pad_request(bytes);
5580 idx = small_index(nb);
5581 smallbits = ms->smallmap >> idx;
5582
5583 if ((smallbits & 0x3U) != 0) { /* Remainderless fit to a smallbin. */
5584 mchunkptr b, p;
5585 idx += ~smallbits & 1; /* Uses next bin if idx empty */
5586 b = smallbin_at(ms, idx);
5587 p = b->fd;
5588 assert(chunksize(p) == small_index2size(idx));
5589 unlink_first_small_chunk(ms, b, p, idx);
5590 set_inuse_and_pinuse(ms, p, small_index2size(idx));
5591 mem = chunk2mem(p);
5592 check_malloced_chunk(ms, mem, nb);
5593 goto postaction;
5594 }
5595
5596 else if (nb > ms->dvsize) {
5597 if (smallbits != 0) { /* Use chunk in next nonempty smallbin */
5598 mchunkptr b, p, r;
5599 size_t rsize;
5600 bindex_t i;
5601 binmap_t leftbits = (smallbits << idx) & left_bits(idx2bit(idx));
5602 binmap_t leastbit = least_bit(leftbits);
5603 compute_bit2idx(leastbit, i);
5604 b = smallbin_at(ms, i);
5605 p = b->fd;
5606 assert(chunksize(p) == small_index2size(i));
5607 unlink_first_small_chunk(ms, b, p, i);
5608 rsize = small_index2size(i) - nb;
5609 /* Fit here cannot be remainderless if 4byte sizes */
5610 if (SIZE_T_SIZE != 4 && rsize < MIN_CHUNK_SIZE)
5611 set_inuse_and_pinuse(ms, p, small_index2size(i));
5612 else {
5613 set_size_and_pinuse_of_inuse_chunk(ms, p, nb);
5614 r = chunk_plus_offset(p, nb);
5615 set_size_and_pinuse_of_free_chunk(r, rsize);
5616 replace_dv(ms, r, rsize);
5617 }
5618 mem = chunk2mem(p);
5619 check_malloced_chunk(ms, mem, nb);
5620 goto postaction;
5621 }
5622
5623 else if (ms->treemap != 0 && (mem = tmalloc_small(ms, nb)) != 0) {
5624 check_malloced_chunk(ms, mem, nb);
5625 goto postaction;
5626 }
5627 }
5628 }
5629 else if (bytes >= MAX_REQUEST)
5630 nb = MAX_SIZE_T; /* Too big to allocate. Force failure (in sys alloc) */
5631 else {
5632 nb = pad_request(bytes);
5633 if (ms->treemap != 0 && (mem = tmalloc_large(ms, nb)) != 0) {
5634 check_malloced_chunk(ms, mem, nb);
5635 goto postaction;
5636 }
5637 }
5638
5639 if (nb <= ms->dvsize) {
5640 size_t rsize = ms->dvsize - nb;
5641 mchunkptr p = ms->dv;
5642 if (rsize >= MIN_CHUNK_SIZE) { /* split dv */
5643 mchunkptr r = ms->dv = chunk_plus_offset(p, nb);
5644 ms->dvsize = rsize;
5645 set_size_and_pinuse_of_free_chunk(r, rsize);
5646 set_size_and_pinuse_of_inuse_chunk(ms, p, nb);
5647 }
5648 else { /* exhaust dv */
5649 size_t dvs = ms->dvsize;
5650 ms->dvsize = 0;
5651 ms->dv = 0;
5652 set_inuse_and_pinuse(ms, p, dvs);
5653 }
5654 mem = chunk2mem(p);
5655 check_malloced_chunk(ms, mem, nb);
5656 goto postaction;
5657 }
5658
5659 else if (nb < ms->topsize) { /* Split top */
5660 size_t rsize = ms->topsize -= nb;
5661 mchunkptr p = ms->top;
5662 mchunkptr r = ms->top = chunk_plus_offset(p, nb);
5663 r->head = rsize | PINUSE_BIT;
5664 set_size_and_pinuse_of_inuse_chunk(ms, p, nb);
5665 mem = chunk2mem(p);
5666 check_top_chunk(ms, ms->top);
5667 check_malloced_chunk(ms, mem, nb);
5668 goto postaction;
5669 }
5670
5671 mem = sys_alloc(ms, nb);
5672
5673 postaction:
5674 POSTACTION(ms);
5675 return mem;
5676 }
5677
5678 return 0;
5679}
5680
5681void mspace_free(mspace msp, void* mem) {
5682 if (mem != 0) {
5683 mchunkptr p = mem2chunk(mem);
5684#if FOOTERS
5685 mstate fm = get_mstate_for(p);
5686 (void)msp; /* placate people compiling -Wunused */
5687#else /* FOOTERS */
5688 mstate fm = (mstate)msp;
5689#endif /* FOOTERS */
5690 if (!ok_magic(fm)) {
5691 USAGE_ERROR_ACTION(fm, p);
5692 return;
5693 }
5694 if (!PREACTION(fm)) {
5695 check_inuse_chunk(fm, p);
5696 if (RTCHECK(ok_address(fm, p) && ok_inuse(p))) {
5697 size_t psize = chunksize(p);
5698 mchunkptr next = chunk_plus_offset(p, psize);
5699 if (!pinuse(p)) {
5700 size_t prevsize = p->prev_foot;
5701 if (is_mmapped(p)) {
5702 psize += prevsize + MMAP_FOOT_PAD;
5703 if (CALL_MUNMAP((char*)p - prevsize, psize) == 0)
5704 fm->footprint -= psize;
5705 goto postaction;
5706 }
5707 else {
5708 mchunkptr prev = chunk_minus_offset(p, prevsize);
5709 psize += prevsize;
5710 p = prev;
5711 if (RTCHECK(ok_address(fm, prev))) { /* consolidate backward */
5712 if (p != fm->dv) {
5713 unlink_chunk(fm, p, prevsize);
5714 }
5715 else if ((next->head & INUSE_BITS) == INUSE_BITS) {
5716 fm->dvsize = psize;
5717 set_free_with_pinuse(p, psize, next);
5718 goto postaction;
5719 }
5720 }
5721 else
5722 goto erroraction;
5723 }
5724 }
5725
5726 if (RTCHECK(ok_next(p, next) && ok_pinuse(next))) {
5727 if (!cinuse(next)) { /* consolidate forward */
5728 if (next == fm->top) {
5729 size_t tsize = fm->topsize += psize;
5730 fm->top = p;
5731 p->head = tsize | PINUSE_BIT;
5732 if (p == fm->dv) {
5733 fm->dv = 0;
5734 fm->dvsize = 0;
5735 }
5736 if (should_trim(fm, tsize))
5737 sys_trim(fm, 0);
5738 goto postaction;
5739 }
5740 else if (next == fm->dv) {
5741 size_t dsize = fm->dvsize += psize;
5742 fm->dv = p;
5743 set_size_and_pinuse_of_free_chunk(p, dsize);
5744 goto postaction;
5745 }
5746 else {
5747 size_t nsize = chunksize(next);
5748 psize += nsize;
5749 unlink_chunk(fm, next, nsize);
5750 set_size_and_pinuse_of_free_chunk(p, psize);
5751 if (p == fm->dv) {
5752 fm->dvsize = psize;
5753 goto postaction;
5754 }
5755 }
5756 }
5757 else
5758 set_free_with_pinuse(p, psize, next);
5759
5760 if (is_small(psize)) {
5761 insert_small_chunk(fm, p, psize);
5762 check_free_chunk(fm, p);
5763 }
5764 else {
5765 tchunkptr tp = (tchunkptr)p;
5766 insert_large_chunk(fm, tp, psize);
5767 check_free_chunk(fm, p);
5768 if (--fm->release_checks == 0)
5769 release_unused_segments(fm);
5770 }
5771 goto postaction;
5772 }
5773 }
5774 erroraction:
5775 USAGE_ERROR_ACTION(fm, p);
5776 postaction:
5777 POSTACTION(fm);
5778 }
5779 }
5780}
5781
5782void* mspace_calloc(mspace msp, size_t n_elements, size_t elem_size) {
5783 void* mem;
5784 size_t req = 0;
5785 mstate ms = (mstate)msp;
5786 if (!ok_magic(ms)) {
5787 USAGE_ERROR_ACTION(ms,ms);
5788 return 0;
5789 }
5790 if (n_elements != 0) {
5791 req = n_elements * elem_size;
5792 if (((n_elements | elem_size) & ~(size_t)0xffff) &&
5793 (req / n_elements != elem_size))
5794 req = MAX_SIZE_T; /* force downstream failure on overflow */
5795 }
5796 mem = internal_malloc(ms, req);
5797 if (mem != 0 && calloc_must_clear(mem2chunk(mem)))
5798 memset(mem, 0, req);
5799 return mem;
5800}
5801
5802void* mspace_realloc(mspace msp, void* oldmem, size_t bytes) {
5803 void* mem = 0;
5804 if (oldmem == 0) {
5805 mem = mspace_malloc(msp, bytes);
5806 }
5807 else if (bytes >= MAX_REQUEST) {
5808 MALLOC_FAILURE_ACTION;
5809 }
5810#ifdef REALLOC_ZERO_BYTES_FREES
5811 else if (bytes == 0) {
5812 mspace_free(msp, oldmem);
5813 }
5814#endif /* REALLOC_ZERO_BYTES_FREES */
5815 else {
5816 size_t nb = request2size(bytes);
5817 mchunkptr oldp = mem2chunk(oldmem);
5818#if ! FOOTERS
5819 mstate m = (mstate)msp;
5820#else /* FOOTERS */
5821 mstate m = get_mstate_for(oldp);
5822 if (!ok_magic(m)) {
5823 USAGE_ERROR_ACTION(m, oldmem);
5824 return 0;
5825 }
5826#endif /* FOOTERS */
5827 if (!PREACTION(m)) {
5828 mchunkptr newp = try_realloc_chunk(m, oldp, nb, 1);
5829 POSTACTION(m);
5830 if (newp != 0) {
5831 check_inuse_chunk(m, newp);
5832 mem = chunk2mem(newp);
5833 }
5834 else {
5835 mem = mspace_malloc(m, bytes);
5836 if (mem != 0) {
5837 size_t oc = chunksize(oldp) - overhead_for(oldp);
5838 memcpy(mem, oldmem, (oc < bytes)? oc : bytes);
5839 mspace_free(m, oldmem);
5840 }
5841 }
5842 }
5843 }
5844 return mem;
5845}
5846
5847void* mspace_realloc_in_place(mspace msp, void* oldmem, size_t bytes) {
5848 void* mem = 0;
5849 if (oldmem != 0) {
5850 if (bytes >= MAX_REQUEST) {
5851 MALLOC_FAILURE_ACTION;
5852 }
5853 else {
5854 size_t nb = request2size(bytes);
5855 mchunkptr oldp = mem2chunk(oldmem);
5856#if ! FOOTERS
5857 mstate m = (mstate)msp;
5858#else /* FOOTERS */
5859 mstate m = get_mstate_for(oldp);
5860 (void)msp; /* placate people compiling -Wunused */
5861 if (!ok_magic(m)) {
5862 USAGE_ERROR_ACTION(m, oldmem);
5863 return 0;
5864 }
5865#endif /* FOOTERS */
5866 if (!PREACTION(m)) {
5867 mchunkptr newp = try_realloc_chunk(m, oldp, nb, 0);
5868 POSTACTION(m);
5869 if (newp == oldp) {
5870 check_inuse_chunk(m, newp);
5871 mem = oldmem;
5872 }
5873 }
5874 }
5875 }
5876 return mem;
5877}
5878
5879void* mspace_memalign(mspace msp, size_t alignment, size_t bytes) {
5880 mstate ms = (mstate)msp;
5881 if (!ok_magic(ms)) {
5882 USAGE_ERROR_ACTION(ms,ms);
5883 return 0;
5884 }
5885 if (alignment <= MALLOC_ALIGNMENT)
5886 return mspace_malloc(msp, bytes);
5887 return internal_memalign(ms, alignment, bytes);
5888}
5889
5890void** mspace_independent_calloc(mspace msp, size_t n_elements,
5891 size_t elem_size, void* chunks[]) {
5892 size_t sz = elem_size; /* serves as 1-element array */
5893 mstate ms = (mstate)msp;
5894 if (!ok_magic(ms)) {
5895 USAGE_ERROR_ACTION(ms,ms);
5896 return 0;
5897 }
5898 return ialloc(ms, n_elements, &sz, 3, chunks);
5899}
5900
5901void** mspace_independent_comalloc(mspace msp, size_t n_elements,
5902 size_t sizes[], void* chunks[]) {
5903 mstate ms = (mstate)msp;
5904 if (!ok_magic(ms)) {
5905 USAGE_ERROR_ACTION(ms,ms);
5906 return 0;
5907 }
5908 return ialloc(ms, n_elements, sizes, 0, chunks);
5909}
5910
5911size_t mspace_bulk_free(mspace msp, void* array[], size_t nelem) {
5912 return internal_bulk_free((mstate)msp, array, nelem);
5913}
5914
5915#if MALLOC_INSPECT_ALL
5916void mspace_inspect_all(mspace msp,
5917 void(*handler)(void *start,
5918 void *end,
5919 size_t used_bytes,
5920 void* callback_arg),
5921 void* arg) {
5922 mstate ms = (mstate)msp;
5923 if (ok_magic(ms)) {
5924 if (!PREACTION(ms)) {
5925 internal_inspect_all(ms, handler, arg);
5926 POSTACTION(ms);
5927 }
5928 }
5929 else {
5930 USAGE_ERROR_ACTION(ms,ms);
5931 }
5932}
5933#endif /* MALLOC_INSPECT_ALL */
5934
5935int mspace_trim(mspace msp, size_t pad) {
5936 int result = 0;
5937 mstate ms = (mstate)msp;
5938 if (ok_magic(ms)) {
5939 if (!PREACTION(ms)) {
5940 result = sys_trim(ms, pad);
5941 POSTACTION(ms);
5942 }
5943 }
5944 else {
5945 USAGE_ERROR_ACTION(ms,ms);
5946 }
5947 return result;
5948}
5949
5950#if !NO_MALLOC_STATS
5951void mspace_malloc_stats(mspace msp) {
5952 mstate ms = (mstate)msp;
5953 if (ok_magic(ms)) {
5954 internal_malloc_stats(ms);
5955 }
5956 else {
5957 USAGE_ERROR_ACTION(ms,ms);
5958 }
5959}
5960#endif /* NO_MALLOC_STATS */
5961
5962size_t mspace_footprint(mspace msp) {
5963 size_t result = 0;
5964 mstate ms = (mstate)msp;
5965 if (ok_magic(ms)) {
5966 result = ms->footprint;
5967 }
5968 else {
5969 USAGE_ERROR_ACTION(ms,ms);
5970 }
5971 return result;
5972}
5973
5974size_t mspace_max_footprint(mspace msp) {
5975 size_t result = 0;
5976 mstate ms = (mstate)msp;
5977 if (ok_magic(ms)) {
5978 result = ms->max_footprint;
5979 }
5980 else {
5981 USAGE_ERROR_ACTION(ms,ms);
5982 }
5983 return result;
5984}
5985
5986size_t mspace_footprint_limit(mspace msp) {
5987 size_t result = 0;
5988 mstate ms = (mstate)msp;
5989 if (ok_magic(ms)) {
5990 size_t maf = ms->footprint_limit;
5991 result = (maf == 0) ? MAX_SIZE_T : maf;
5992 }
5993 else {
5994 USAGE_ERROR_ACTION(ms,ms);
5995 }
5996 return result;
5997}
5998
5999size_t mspace_set_footprint_limit(mspace msp, size_t bytes) {
6000 size_t result = 0;
6001 mstate ms = (mstate)msp;
6002 if (ok_magic(ms)) {
6003 if (bytes == 0)
6004 result = granularity_align(1); /* Use minimal size */
6005 if (bytes == MAX_SIZE_T)
6006 result = 0; /* disable */
6007 else
6008 result = granularity_align(bytes);
6009 ms->footprint_limit = result;
6010 }
6011 else {
6012 USAGE_ERROR_ACTION(ms,ms);
6013 }
6014 return result;
6015}
6016
6017#if !NO_MALLINFO
6018struct mallinfo mspace_mallinfo(mspace msp) {
6019 mstate ms = (mstate)msp;
6020 if (!ok_magic(ms)) {
6021 USAGE_ERROR_ACTION(ms,ms);
6022 }
6023 return internal_mallinfo(ms);
6024}
6025#endif /* NO_MALLINFO */
6026
6027size_t mspace_usable_size(const void* mem) {
6028 if (mem != 0) {
6029 mchunkptr p = mem2chunk(mem);
6030 if (is_inuse(p))
6031 return chunksize(p) - overhead_for(p);
6032 }
6033 return 0;
6034}
6035
6036int mspace_mallopt(int param_number, int value) {
6037 return change_mparam(param_number, value);
6038}
6039
6040#endif /* MSPACES */
6041
6042
6043/* -------------------- Alternative MORECORE functions ------------------- */
6044
6045/*
6046 Guidelines for creating a custom version of MORECORE:
6047
6048 * For best performance, MORECORE should allocate in multiples of pagesize.
6049 * MORECORE may allocate more memory than requested. (Or even less,
6050 but this will usually result in a malloc failure.)
6051 * MORECORE must not allocate memory when given argument zero, but
6052 instead return one past the end address of memory from previous
6053 nonzero call.
6054 * For best performance, consecutive calls to MORECORE with positive
6055 arguments should return increasing addresses, indicating that
6056 space has been contiguously extended.
6057 * Even though consecutive calls to MORECORE need not return contiguous
6058 addresses, it must be OK for malloc'ed chunks to span multiple
6059 regions in those cases where they do happen to be contiguous.
6060 * MORECORE need not handle negative arguments -- it may instead
6061 just return MFAIL when given negative arguments.
6062 Negative arguments are always multiples of pagesize. MORECORE
6063 must not misinterpret negative args as large positive unsigned
6064 args. You can suppress all such calls from even occurring by defining
6065 MORECORE_CANNOT_TRIM,
6066
6067 As an example alternative MORECORE, here is a custom allocator
6068 kindly contributed for pre-OSX macOS. It uses virtually but not
6069 necessarily physically contiguous non-paged memory (locked in,
6070 present and won't get swapped out). You can use it by uncommenting
6071 this section, adding some #includes, and setting up the appropriate
6072 defines above:
6073
6074 #define MORECORE osMoreCore
6075
6076 There is also a shutdown routine that should somehow be called for
6077 cleanup upon program exit.
6078
6079 #define MAX_POOL_ENTRIES 100
6080 #define MINIMUM_MORECORE_SIZE (64 * 1024U)
6081 static int next_os_pool;
6082 void *our_os_pools[MAX_POOL_ENTRIES];
6083
6084 void *osMoreCore(int size)
6085 {
6086 void *ptr = 0;
6087 static void *sbrk_top = 0;
6088
6089 if (size > 0)
6090 {
6091 if (size < MINIMUM_MORECORE_SIZE)
6092 size = MINIMUM_MORECORE_SIZE;
6093 if (CurrentExecutionLevel() == kTaskLevel)
6094 ptr = PoolAllocateResident(size + RM_PAGE_SIZE, 0);
6095 if (ptr == 0)
6096 {
6097 return (void *) MFAIL;
6098 }
6099 // save ptrs so they can be freed during cleanup
6100 our_os_pools[next_os_pool] = ptr;
6101 next_os_pool++;
6102 ptr = (void *) ((((size_t) ptr) + RM_PAGE_MASK) & ~RM_PAGE_MASK);
6103 sbrk_top = (char *) ptr + size;
6104 return ptr;
6105 }
6106 else if (size < 0)
6107 {
6108 // we don't currently support shrink behavior
6109 return (void *) MFAIL;
6110 }
6111 else
6112 {
6113 return sbrk_top;
6114 }
6115 }
6116
6117 // cleanup any allocated memory pools
6118 // called as last thing before shutting down driver
6119
6120 void osCleanupMem(void)
6121 {
6122 void **ptr;
6123
6124 for (ptr = our_os_pools; ptr < &our_os_pools[MAX_POOL_ENTRIES]; ptr++)
6125 if (*ptr)
6126 {
6127 PoolDeallocate(*ptr);
6128 *ptr = 0;
6129 }
6130 }
6131
6132*/
6133
6134
6135/* -----------------------------------------------------------------------
6136History:
6137 v2.8.6 Wed Aug 29 06:57:58 2012 Doug Lea
6138 * fix bad comparison in dlposix_memalign
6139 * don't reuse adjusted asize in sys_alloc
6140 * add LOCK_AT_FORK -- thanks to Kirill Artamonov for the suggestion
6141 * reduce compiler warnings -- thanks to all who reported/suggested these
6142
6143 v2.8.5 Sun May 22 10:26:02 2011 Doug Lea (dl at gee)
6144 * Always perform unlink checks unless INSECURE
6145 * Add posix_memalign.
6146 * Improve realloc to expand in more cases; expose realloc_in_place.
6147 Thanks to Peter Buhr for the suggestion.
6148 * Add footprint_limit, inspect_all, bulk_free. Thanks
6149 to Barry Hayes and others for the suggestions.
6150 * Internal refactorings to avoid calls while holding locks
6151 * Use non-reentrant locks by default. Thanks to Roland McGrath
6152 for the suggestion.
6153 * Small fixes to mspace_destroy, reset_on_error.
6154 * Various configuration extensions/changes. Thanks
6155 to all who contributed these.
6156
6157 V2.8.4a Thu Apr 28 14:39:43 2011 (dl at gee.cs.oswego.edu)
6158 * Update Creative Commons URL
6159
6160 V2.8.4 Wed May 27 09:56:23 2009 Doug Lea (dl at gee)
6161 * Use zeros instead of prev foot for is_mmapped
6162 * Add mspace_track_large_chunks; thanks to Jean Brouwers
6163 * Fix set_inuse in internal_realloc; thanks to Jean Brouwers
6164 * Fix insufficient sys_alloc padding when using 16byte alignment
6165 * Fix bad error check in mspace_footprint
6166 * Adaptations for ptmalloc; thanks to Wolfram Gloger.
6167 * Reentrant spin locks; thanks to Earl Chew and others
6168 * Win32 improvements; thanks to Niall Douglas and Earl Chew
6169 * Add NO_SEGMENT_TRAVERSAL and MAX_RELEASE_CHECK_RATE options
6170 * Extension hook in malloc_state
6171 * Various small adjustments to reduce warnings on some compilers
6172 * Various configuration extensions/changes for more platforms. Thanks
6173 to all who contributed these.
6174
6175 V2.8.3 Thu Sep 22 11:16:32 2005 Doug Lea (dl at gee)
6176 * Add max_footprint functions
6177 * Ensure all appropriate literals are size_t
6178 * Fix conditional compilation problem for some #define settings
6179 * Avoid concatenating segments with the one provided
6180 in create_mspace_with_base
6181 * Rename some variables to avoid compiler shadowing warnings
6182 * Use explicit lock initialization.
6183 * Better handling of sbrk interference.
6184 * Simplify and fix segment insertion, trimming and mspace_destroy
6185 * Reinstate REALLOC_ZERO_BYTES_FREES option from 2.7.x
6186 * Thanks especially to Dennis Flanagan for help on these.
6187
6188 V2.8.2 Sun Jun 12 16:01:10 2005 Doug Lea (dl at gee)
6189 * Fix memalign brace error.
6190
6191 V2.8.1 Wed Jun 8 16:11:46 2005 Doug Lea (dl at gee)
6192 * Fix improper #endif nesting in C++
6193 * Add explicit casts needed for C++
6194
6195 V2.8.0 Mon May 30 14:09:02 2005 Doug Lea (dl at gee)
6196 * Use trees for large bins
6197 * Support mspaces
6198 * Use segments to unify sbrk-based and mmap-based system allocation,
6199 removing need for emulation on most platforms without sbrk.
6200 * Default safety checks
6201 * Optional footer checks. Thanks to William Robertson for the idea.
6202 * Internal code refactoring
6203 * Incorporate suggestions and platform-specific changes.
6204 Thanks to Dennis Flanagan, Colin Plumb, Niall Douglas,
6205 Aaron Bachmann, Emery Berger, and others.
6206 * Speed up non-fastbin processing enough to remove fastbins.
6207 * Remove useless cfree() to avoid conflicts with other apps.
6208 * Remove internal memcpy, memset. Compilers handle builtins better.
6209 * Remove some options that no one ever used and rename others.
6210
6211 V2.7.2 Sat Aug 17 09:07:30 2002 Doug Lea (dl at gee)
6212 * Fix malloc_state bitmap array misdeclaration
6213
6214 V2.7.1 Thu Jul 25 10:58:03 2002 Doug Lea (dl at gee)
6215 * Allow tuning of FIRST_SORTED_BIN_SIZE
6216 * Use PTR_UINT as type for all ptr->int casts. Thanks to John Belmonte.
6217 * Better detection and support for non-contiguousness of MORECORE.
6218 Thanks to Andreas Mueller, Conal Walsh, and Wolfram Gloger
6219 * Bypass most of malloc if no frees. Thanks To Emery Berger.
6220 * Fix freeing of old top non-contiguous chunk im sysmalloc.
6221 * Raised default trim and map thresholds to 256K.
6222 * Fix mmap-related #defines. Thanks to Lubos Lunak.
6223 * Fix copy macros; added LACKS_FCNTL_H. Thanks to Neal Walfield.
6224 * Branch-free bin calculation
6225 * Default trim and mmap thresholds now 256K.
6226
6227 V2.7.0 Sun Mar 11 14:14:06 2001 Doug Lea (dl at gee)
6228 * Introduce independent_comalloc and independent_calloc.
6229 Thanks to Michael Pachos for motivation and help.
6230 * Make optional .h file available
6231 * Allow > 2GB requests on 32bit systems.
6232 * new WIN32 sbrk, mmap, munmap, lock code from <Walter@GeNeSys-e.de>.
6233 Thanks also to Andreas Mueller <a.mueller at paradatec.de>,
6234 and Anonymous.
6235 * Allow override of MALLOC_ALIGNMENT (Thanks to Ruud Waij for
6236 helping test this.)
6237 * memalign: check alignment arg
6238 * realloc: don't try to shift chunks backwards, since this
6239 leads to more fragmentation in some programs and doesn't
6240 seem to help in any others.
6241 * Collect all cases in malloc requiring system memory into sysmalloc
6242 * Use mmap as backup to sbrk
6243 * Place all internal state in malloc_state
6244 * Introduce fastbins (although similar to 2.5.1)
6245 * Many minor tunings and cosmetic improvements
6246 * Introduce USE_PUBLIC_MALLOC_WRAPPERS, USE_MALLOC_LOCK
6247 * Introduce MALLOC_FAILURE_ACTION, MORECORE_CONTIGUOUS
6248 Thanks to Tony E. Bennett <tbennett@nvidia.com> and others.
6249 * Include errno.h to support default failure action.
6250
6251 V2.6.6 Sun Dec 5 07:42:19 1999 Doug Lea (dl at gee)
6252 * return null for negative arguments
6253 * Added Several WIN32 cleanups from Martin C. Fong <mcfong at yahoo.com>
6254 * Add 'LACKS_SYS_PARAM_H' for those systems without 'sys/param.h'
6255 (e.g. WIN32 platforms)
6256 * Cleanup header file inclusion for WIN32 platforms
6257 * Cleanup code to avoid Microsoft Visual C++ compiler complaints
6258 * Add 'USE_DL_PREFIX' to quickly allow co-existence with existing
6259 memory allocation routines
6260 * Set 'malloc_getpagesize' for WIN32 platforms (needs more work)
6261 * Use 'assert' rather than 'ASSERT' in WIN32 code to conform to
6262 usage of 'assert' in non-WIN32 code
6263 * Improve WIN32 'sbrk()' emulation's 'findRegion()' routine to
6264 avoid infinite loop
6265 * Always call 'fREe()' rather than 'free()'
6266
6267 V2.6.5 Wed Jun 17 15:57:31 1998 Doug Lea (dl at gee)
6268 * Fixed ordering problem with boundary-stamping
6269
6270 V2.6.3 Sun May 19 08:17:58 1996 Doug Lea (dl at gee)
6271 * Added pvalloc, as recommended by H.J. Liu
6272 * Added 64bit pointer support mainly from Wolfram Gloger
6273 * Added anonymously donated WIN32 sbrk emulation
6274 * Malloc, calloc, getpagesize: add optimizations from Raymond Nijssen
6275 * malloc_extend_top: fix mask error that caused wastage after
6276 foreign sbrks
6277 * Add linux mremap support code from HJ Liu
6278
6279 V2.6.2 Tue Dec 5 06:52:55 1995 Doug Lea (dl at gee)
6280 * Integrated most documentation with the code.
6281 * Add support for mmap, with help from
6282 Wolfram Gloger (Gloger@lrz.uni-muenchen.de).
6283 * Use last_remainder in more cases.
6284 * Pack bins using idea from colin@nyx10.cs.du.edu
6285 * Use ordered bins instead of best-fit threshhold
6286 * Eliminate block-local decls to simplify tracing and debugging.
6287 * Support another case of realloc via move into top
6288 * Fix error occuring when initial sbrk_base not word-aligned.
6289 * Rely on page size for units instead of SBRK_UNIT to
6290 avoid surprises about sbrk alignment conventions.
6291 * Add mallinfo, mallopt. Thanks to Raymond Nijssen
6292 (raymond@es.ele.tue.nl) for the suggestion.
6293 * Add `pad' argument to malloc_trim and top_pad mallopt parameter.
6294 * More precautions for cases where other routines call sbrk,
6295 courtesy of Wolfram Gloger (Gloger@lrz.uni-muenchen.de).
6296 * Added macros etc., allowing use in linux libc from
6297 H.J. Lu (hjl@gnu.ai.mit.edu)
6298 * Inverted this history list
6299
6300 V2.6.1 Sat Dec 2 14:10:57 1995 Doug Lea (dl at gee)
6301 * Re-tuned and fixed to behave more nicely with V2.6.0 changes.
6302 * Removed all preallocation code since under current scheme
6303 the work required to undo bad preallocations exceeds
6304 the work saved in good cases for most test programs.
6305 * No longer use return list or unconsolidated bins since
6306 no scheme using them consistently outperforms those that don't
6307 given above changes.
6308 * Use best fit for very large chunks to prevent some worst-cases.
6309 * Added some support for debugging
6310
6311 V2.6.0 Sat Nov 4 07:05:23 1995 Doug Lea (dl at gee)
6312 * Removed footers when chunks are in use. Thanks to
6313 Paul Wilson (wilson@cs.texas.edu) for the suggestion.
6314
6315 V2.5.4 Wed Nov 1 07:54:51 1995 Doug Lea (dl at gee)
6316 * Added malloc_trim, with help from Wolfram Gloger
6317 (wmglo@Dent.MED.Uni-Muenchen.DE).
6318
6319 V2.5.3 Tue Apr 26 10:16:01 1994 Doug Lea (dl at g)
6320
6321 V2.5.2 Tue Apr 5 16:20:40 1994 Doug Lea (dl at g)
6322 * realloc: try to expand in both directions
6323 * malloc: swap order of clean-bin strategy;
6324 * realloc: only conditionally expand backwards
6325 * Try not to scavenge used bins
6326 * Use bin counts as a guide to preallocation
6327 * Occasionally bin return list chunks in first scan
6328 * Add a few optimizations from colin@nyx10.cs.du.edu
6329
6330 V2.5.1 Sat Aug 14 15:40:43 1993 Doug Lea (dl at g)
6331 * faster bin computation & slightly different binning
6332 * merged all consolidations to one part of malloc proper
6333 (eliminating old malloc_find_space & malloc_clean_bin)
6334 * Scan 2 returns chunks (not just 1)
6335 * Propagate failure in realloc if malloc returns 0
6336 * Add stuff to allow compilation on non-ANSI compilers
6337 from kpv@research.att.com
6338
6339 V2.5 Sat Aug 7 07:41:59 1993 Doug Lea (dl at g.oswego.edu)
6340 * removed potential for odd address access in prev_chunk
6341 * removed dependency on getpagesize.h
6342 * misc cosmetics and a bit more internal documentation
6343 * anticosmetics: mangled names in macros to evade debugger strangeness
6344 * tested on sparc, hp-700, dec-mips, rs6000
6345 with gcc & native cc (hp, dec only) allowing
6346 Detlefs & Zorn comparison study (in SIGPLAN Notices.)
6347
6348 Trial version Fri Aug 28 13:14:29 1992 Doug Lea (dl at g.oswego.edu)
6349 * Based loosely on libg++-1.2X malloc. (It retains some of the overall
6350 structure of old version, but most details differ.)
6351
6352*/
lib/libc/wasi/emmalloc/emmalloc.c created+1535
...@@ -0,0 +1,1535 @@
1/*
2 * Copyright 2018 The Emscripten Authors. All rights reserved.
3 * Emscripten is available under two separate licenses, the MIT license and the
4 * University of Illinois/NCSA Open Source License. Both these licenses can be
5 * found in the LICENSE file.
6 *
7 * Simple minimalistic but efficient sbrk()-based malloc/free that works in
8 * singlethreaded and multithreaded builds.
9 *
10 * Assumptions:
11 *
12 * - sbrk() is used to claim new memory (sbrk handles geometric/linear
13 * - overallocation growth)
14 * - sbrk() can be used by other code outside emmalloc.
15 * - sbrk() is very fast in most cases (internal wasm call).
16 * - sbrk() returns pointers with an alignment of alignof(max_align_t)
17 *
18 * Invariants:
19 *
20 * - Per-allocation header overhead is 8 bytes, smallest allocated payload
21 * amount is 8 bytes, and a multiple of 4 bytes.
22 * - Acquired memory blocks are subdivided into disjoint regions that lie
23 * next to each other.
24 * - A region is either in used or free.
25 * Used regions may be adjacent, and a used and unused region
26 * may be adjacent, but not two unused ones - they would be
27 * merged.
28 * - Memory allocation takes constant time, unless the alloc needs to sbrk()
29 * or memory is very close to being exhausted.
30 *
31 * Debugging:
32 *
33 * - If not NDEBUG, runtime assert()s are in use.
34 * - If EMMALLOC_MEMVALIDATE is defined, a large amount of extra checks are done.
35 * - If EMMALLOC_VERBOSE is defined, a lot of operations are logged
36 * out, in addition to EMMALLOC_MEMVALIDATE.
37 * - Debugging and logging directly uses console.log via uses EM_ASM, not
38 * printf etc., to minimize any risk of debugging or logging depending on
39 * malloc.
40 */
41
42#include <stdalign.h>
43#include <stdbool.h>
44#include <stddef.h>
45#include <stdint.h>
46#include <unistd.h>
47#include <memory.h>
48#include <assert.h>
49#include <malloc.h>
50#include <limits.h>
51#include <stdlib.h>
52
53#ifdef __EMSCRIPTEN_TRACING__
54#include <emscripten/trace.h>
55#endif
56
57// Defind by the linker to have the address of the start of the heap.
58extern unsigned char __heap_base;
59
60// Behavior of right shifting a signed integer is compiler implementation defined.
61static_assert((((int32_t)0x80000000U) >> 31) == -1, "This malloc implementation requires that right-shifting a signed integer produces a sign-extending (arithmetic) shift!");
62
63// Configuration: specifies the minimum alignment that malloc()ed memory outputs. Allocation requests with smaller alignment
64// than this will yield an allocation with this much alignment.
65#define MALLOC_ALIGNMENT alignof(max_align_t)
66static_assert(alignof(max_align_t) == 16, "max_align_t must be correct");
67
68#define EMMALLOC_EXPORT __attribute__((__weak__))
69
70#define MIN(x, y) ((x) < (y) ? (x) : (y))
71#define MAX(x, y) ((x) > (y) ? (x) : (y))
72
73#define NUM_FREE_BUCKETS 64
74#define BUCKET_BITMASK_T uint64_t
75
76// Dynamic memory is subdivided into regions, in the format
77
78// <size:uint32_t> ..... <size:uint32_t> | <size:uint32_t> ..... <size:uint32_t> | <size:uint32_t> ..... <size:uint32_t> | .....
79
80// That is, at the bottom and top end of each memory region, the size of that region is stored. That allows traversing the
81// memory regions backwards and forwards. Because each allocation must be at least a multiple of 4 bytes, the lowest two bits of
82// each size field is unused. Free regions are distinguished by used regions by having the FREE_REGION_FLAG bit present
83// in the size field. I.e. for free regions, the size field is odd, and for used regions, the size field reads even.
84#define FREE_REGION_FLAG 0x1u
85
86// Attempts to malloc() more than this many bytes would cause an overflow when calculating the size of a region,
87// therefore allocations larger than this are short-circuited immediately on entry.
88#define MAX_ALLOC_SIZE 0xFFFFFFC7u
89
90// A free region has the following structure:
91// <size:size_t> <prevptr> <nextptr> ... <size:size_t>
92
93typedef struct Region
94{
95 size_t size;
96 // Use a circular doubly linked list to represent free region data.
97 struct Region *prev, *next;
98 // ... N bytes of free data
99 size_t _at_the_end_of_this_struct_size; // do not dereference, this is present for convenient struct sizeof() computation only
100} Region;
101
102// Each memory block starts with a RootRegion at the beginning.
103// The RootRegion specifies the size of the region block, and forms a linked
104// list of all RootRegions in the program, starting with `listOfAllRegions`
105// below.
106typedef struct RootRegion
107{
108 uint32_t size;
109 struct RootRegion *next;
110 uint8_t* endPtr;
111} RootRegion;
112
113#if defined(__EMSCRIPTEN_PTHREADS__)
114// In multithreaded builds, use a simple global spinlock strategy to acquire/release access to the memory allocator.
115static volatile uint8_t multithreadingLock = 0;
116#define MALLOC_ACQUIRE() while(__sync_lock_test_and_set(&multithreadingLock, 1)) { while(multithreadingLock) { /*nop*/ } }
117#define MALLOC_RELEASE() __sync_lock_release(&multithreadingLock)
118// Test code to ensure we have tight malloc acquire/release guards in place.
119#define ASSERT_MALLOC_IS_ACQUIRED() assert(multithreadingLock == 1)
120#else
121// In singlethreaded builds, no need for locking.
122#define MALLOC_ACQUIRE() ((void)0)
123#define MALLOC_RELEASE() ((void)0)
124#define ASSERT_MALLOC_IS_ACQUIRED() ((void)0)
125#endif
126
127#define IS_POWER_OF_2(val) (((val) & ((val)-1)) == 0)
128#define ALIGN_UP(ptr, alignment) ((uint8_t*)((((uintptr_t)(ptr)) + ((alignment)-1)) & ~((alignment)-1)))
129#define HAS_ALIGNMENT(ptr, alignment) ((((uintptr_t)(ptr)) & ((alignment)-1)) == 0)
130
131static_assert(IS_POWER_OF_2(MALLOC_ALIGNMENT), "MALLOC_ALIGNMENT must be a power of two value!");
132static_assert(MALLOC_ALIGNMENT >= 4, "Smallest possible MALLOC_ALIGNMENT if 4!");
133
134// A region that contains as payload a single forward linked list of pointers to
135// root regions of each disjoint region blocks.
136static RootRegion *listOfAllRegions = NULL;
137
138// For each of the buckets, maintain a linked list head node. The head node for each
139// free region is a sentinel node that does not actually represent any free space, but
140// the sentinel is used to avoid awkward testing against (if node == freeRegionHeadNode)
141// when adding and removing elements from the linked list, i.e. we are guaranteed that
142// the sentinel node is always fixed and there, and the actual free region list elements
143// start at freeRegionBuckets[i].next each.
144static Region freeRegionBuckets[NUM_FREE_BUCKETS] = {
145 { .prev = &freeRegionBuckets[0], .next = &freeRegionBuckets[0] },
146 { .prev = &freeRegionBuckets[1], .next = &freeRegionBuckets[1] },
147 { .prev = &freeRegionBuckets[2], .next = &freeRegionBuckets[2] },
148 { .prev = &freeRegionBuckets[3], .next = &freeRegionBuckets[3] },
149 { .prev = &freeRegionBuckets[4], .next = &freeRegionBuckets[4] },
150 { .prev = &freeRegionBuckets[5], .next = &freeRegionBuckets[5] },
151 { .prev = &freeRegionBuckets[6], .next = &freeRegionBuckets[6] },
152 { .prev = &freeRegionBuckets[7], .next = &freeRegionBuckets[7] },
153 { .prev = &freeRegionBuckets[8], .next = &freeRegionBuckets[8] },
154 { .prev = &freeRegionBuckets[9], .next = &freeRegionBuckets[9] },
155 { .prev = &freeRegionBuckets[10], .next = &freeRegionBuckets[10] },
156 { .prev = &freeRegionBuckets[11], .next = &freeRegionBuckets[11] },
157 { .prev = &freeRegionBuckets[12], .next = &freeRegionBuckets[12] },
158 { .prev = &freeRegionBuckets[13], .next = &freeRegionBuckets[13] },
159 { .prev = &freeRegionBuckets[14], .next = &freeRegionBuckets[14] },
160 { .prev = &freeRegionBuckets[15], .next = &freeRegionBuckets[15] },
161 { .prev = &freeRegionBuckets[16], .next = &freeRegionBuckets[16] },
162 { .prev = &freeRegionBuckets[17], .next = &freeRegionBuckets[17] },
163 { .prev = &freeRegionBuckets[18], .next = &freeRegionBuckets[18] },
164 { .prev = &freeRegionBuckets[19], .next = &freeRegionBuckets[19] },
165 { .prev = &freeRegionBuckets[20], .next = &freeRegionBuckets[20] },
166 { .prev = &freeRegionBuckets[21], .next = &freeRegionBuckets[21] },
167 { .prev = &freeRegionBuckets[22], .next = &freeRegionBuckets[22] },
168 { .prev = &freeRegionBuckets[23], .next = &freeRegionBuckets[23] },
169 { .prev = &freeRegionBuckets[24], .next = &freeRegionBuckets[24] },
170 { .prev = &freeRegionBuckets[25], .next = &freeRegionBuckets[25] },
171 { .prev = &freeRegionBuckets[26], .next = &freeRegionBuckets[26] },
172 { .prev = &freeRegionBuckets[27], .next = &freeRegionBuckets[27] },
173 { .prev = &freeRegionBuckets[28], .next = &freeRegionBuckets[28] },
174 { .prev = &freeRegionBuckets[29], .next = &freeRegionBuckets[29] },
175 { .prev = &freeRegionBuckets[30], .next = &freeRegionBuckets[30] },
176 { .prev = &freeRegionBuckets[31], .next = &freeRegionBuckets[31] },
177 { .prev = &freeRegionBuckets[32], .next = &freeRegionBuckets[32] },
178 { .prev = &freeRegionBuckets[33], .next = &freeRegionBuckets[33] },
179 { .prev = &freeRegionBuckets[34], .next = &freeRegionBuckets[34] },
180 { .prev = &freeRegionBuckets[35], .next = &freeRegionBuckets[35] },
181 { .prev = &freeRegionBuckets[36], .next = &freeRegionBuckets[36] },
182 { .prev = &freeRegionBuckets[37], .next = &freeRegionBuckets[37] },
183 { .prev = &freeRegionBuckets[38], .next = &freeRegionBuckets[38] },
184 { .prev = &freeRegionBuckets[39], .next = &freeRegionBuckets[39] },
185 { .prev = &freeRegionBuckets[40], .next = &freeRegionBuckets[40] },
186 { .prev = &freeRegionBuckets[41], .next = &freeRegionBuckets[41] },
187 { .prev = &freeRegionBuckets[42], .next = &freeRegionBuckets[42] },
188 { .prev = &freeRegionBuckets[43], .next = &freeRegionBuckets[43] },
189 { .prev = &freeRegionBuckets[44], .next = &freeRegionBuckets[44] },
190 { .prev = &freeRegionBuckets[45], .next = &freeRegionBuckets[45] },
191 { .prev = &freeRegionBuckets[46], .next = &freeRegionBuckets[46] },
192 { .prev = &freeRegionBuckets[47], .next = &freeRegionBuckets[47] },
193 { .prev = &freeRegionBuckets[48], .next = &freeRegionBuckets[48] },
194 { .prev = &freeRegionBuckets[49], .next = &freeRegionBuckets[49] },
195 { .prev = &freeRegionBuckets[50], .next = &freeRegionBuckets[50] },
196 { .prev = &freeRegionBuckets[51], .next = &freeRegionBuckets[51] },
197 { .prev = &freeRegionBuckets[52], .next = &freeRegionBuckets[52] },
198 { .prev = &freeRegionBuckets[53], .next = &freeRegionBuckets[53] },
199 { .prev = &freeRegionBuckets[54], .next = &freeRegionBuckets[54] },
200 { .prev = &freeRegionBuckets[55], .next = &freeRegionBuckets[55] },
201 { .prev = &freeRegionBuckets[56], .next = &freeRegionBuckets[56] },
202 { .prev = &freeRegionBuckets[57], .next = &freeRegionBuckets[57] },
203 { .prev = &freeRegionBuckets[58], .next = &freeRegionBuckets[58] },
204 { .prev = &freeRegionBuckets[59], .next = &freeRegionBuckets[59] },
205 { .prev = &freeRegionBuckets[60], .next = &freeRegionBuckets[60] },
206 { .prev = &freeRegionBuckets[61], .next = &freeRegionBuckets[61] },
207 { .prev = &freeRegionBuckets[62], .next = &freeRegionBuckets[62] },
208 { .prev = &freeRegionBuckets[63], .next = &freeRegionBuckets[63] },
209};
210
211// A bitmask that tracks the population status for each of the 64 distinct memory regions:
212// a zero at bit position i means that the free list bucket i is empty. This bitmask is
213// used to avoid redundant scanning of the 64 different free region buckets: instead by
214// looking at the bitmask we can find in constant time an index to a free region bucket
215// that contains free memory of desired size.
216static BUCKET_BITMASK_T freeRegionBucketsUsed = 0;
217
218// Amount of bytes taken up by allocation header data
219#define REGION_HEADER_SIZE (2*sizeof(size_t))
220
221// Smallest allocation size that is possible is 2*pointer size, since payload of each region must at least contain space
222// to store the free region linked list prev and next pointers. An allocation size smaller than this will be rounded up
223// to this size.
224#define SMALLEST_ALLOCATION_SIZE (2*sizeof(void*))
225
226/* Subdivide regions of free space into distinct circular doubly linked lists, where each linked list
227represents a range of free space blocks. The following function compute_free_list_bucket() converts
228an allocation size to the bucket index that should be looked at. The buckets are grouped as follows:
229
230 Bucket 0: [8, 15], range size=8
231 Bucket 1: [16, 23], range size=8
232 Bucket 2: [24, 31], range size=8
233 Bucket 3: [32, 39], range size=8
234 Bucket 4: [40, 47], range size=8
235 Bucket 5: [48, 55], range size=8
236 Bucket 6: [56, 63], range size=8
237 Bucket 7: [64, 71], range size=8
238 Bucket 8: [72, 79], range size=8
239 Bucket 9: [80, 87], range size=8
240 Bucket 10: [88, 95], range size=8
241 Bucket 11: [96, 103], range size=8
242 Bucket 12: [104, 111], range size=8
243 Bucket 13: [112, 119], range size=8
244 Bucket 14: [120, 159], range size=40
245 Bucket 15: [160, 191], range size=32
246 Bucket 16: [192, 223], range size=32
247 Bucket 17: [224, 255], range size=32
248 Bucket 18: [256, 319], range size=64
249 Bucket 19: [320, 383], range size=64
250 Bucket 20: [384, 447], range size=64
251 Bucket 21: [448, 511], range size=64
252 Bucket 22: [512, 639], range size=128
253 Bucket 23: [640, 767], range size=128
254 Bucket 24: [768, 895], range size=128
255 Bucket 25: [896, 1023], range size=128
256 Bucket 26: [1024, 1279], range size=256
257 Bucket 27: [1280, 1535], range size=256
258 Bucket 28: [1536, 1791], range size=256
259 Bucket 29: [1792, 2047], range size=256
260 Bucket 30: [2048, 2559], range size=512
261 Bucket 31: [2560, 3071], range size=512
262 Bucket 32: [3072, 3583], range size=512
263 Bucket 33: [3584, 6143], range size=2560
264 Bucket 34: [6144, 8191], range size=2048
265 Bucket 35: [8192, 12287], range size=4096
266 Bucket 36: [12288, 16383], range size=4096
267 Bucket 37: [16384, 24575], range size=8192
268 Bucket 38: [24576, 32767], range size=8192
269 Bucket 39: [32768, 49151], range size=16384
270 Bucket 40: [49152, 65535], range size=16384
271 Bucket 41: [65536, 98303], range size=32768
272 Bucket 42: [98304, 131071], range size=32768
273 Bucket 43: [131072, 196607], range size=65536
274 Bucket 44: [196608, 262143], range size=65536
275 Bucket 45: [262144, 393215], range size=131072
276 Bucket 46: [393216, 524287], range size=131072
277 Bucket 47: [524288, 786431], range size=262144
278 Bucket 48: [786432, 1048575], range size=262144
279 Bucket 49: [1048576, 1572863], range size=524288
280 Bucket 50: [1572864, 2097151], range size=524288
281 Bucket 51: [2097152, 3145727], range size=1048576
282 Bucket 52: [3145728, 4194303], range size=1048576
283 Bucket 53: [4194304, 6291455], range size=2097152
284 Bucket 54: [6291456, 8388607], range size=2097152
285 Bucket 55: [8388608, 12582911], range size=4194304
286 Bucket 56: [12582912, 16777215], range size=4194304
287 Bucket 57: [16777216, 25165823], range size=8388608
288 Bucket 58: [25165824, 33554431], range size=8388608
289 Bucket 59: [33554432, 50331647], range size=16777216
290 Bucket 60: [50331648, 67108863], range size=16777216
291 Bucket 61: [67108864, 100663295], range size=33554432
292 Bucket 62: [100663296, 134217727], range size=33554432
293 Bucket 63: 134217728 bytes and larger. */
294static_assert(NUM_FREE_BUCKETS == 64, "Following function is tailored specifically for NUM_FREE_BUCKETS == 64 case");
295static int compute_free_list_bucket(size_t allocSize)
296{
297 if (allocSize < 128) return (allocSize >> 3) - 1;
298 int clz = __builtin_clz(allocSize);
299 int bucketIndex = (clz > 19) ? 110 - (clz<<2) + ((allocSize >> (29-clz)) ^ 4) : MIN(71 - (clz<<1) + ((allocSize >> (30-clz)) ^ 2), NUM_FREE_BUCKETS-1);
300 assert(bucketIndex >= 0);
301 assert(bucketIndex < NUM_FREE_BUCKETS);
302 return bucketIndex;
303}
304
305#define DECODE_CEILING_SIZE(size) ((size_t)((size) & ~FREE_REGION_FLAG))
306
307static Region *prev_region(Region *region)
308{
309 size_t prevRegionSize = ((size_t*)region)[-1];
310 prevRegionSize = DECODE_CEILING_SIZE(prevRegionSize);
311 return (Region*)((uint8_t*)region - prevRegionSize);
312}
313
314static Region *next_region(Region *region)
315{
316 return (Region*)((uint8_t*)region + region->size);
317}
318
319static size_t region_ceiling_size(Region *region)
320{
321 return ((size_t*)((uint8_t*)region + region->size))[-1];
322}
323
324static bool region_is_free(Region *r)
325{
326 return region_ceiling_size(r) & FREE_REGION_FLAG;
327}
328
329static bool region_is_in_use(Region *r)
330{
331 return r->size == region_ceiling_size(r);
332}
333
334static size_t size_of_region_from_ceiling(Region *r)
335{
336 size_t size = region_ceiling_size(r);
337 return DECODE_CEILING_SIZE(size);
338}
339
340static bool debug_region_is_consistent(Region *r)
341{
342 assert(r);
343 size_t sizeAtBottom = r->size;
344 size_t sizeAtCeiling = size_of_region_from_ceiling(r);
345 return sizeAtBottom == sizeAtCeiling;
346}
347
348static uint8_t *region_payload_start_ptr(Region *region)
349{
350 return (uint8_t*)region + sizeof(size_t);
351}
352
353static uint8_t *region_payload_end_ptr(Region *region)
354{
355 return (uint8_t*)region + region->size - sizeof(size_t);
356}
357
358static void create_used_region(void *ptr, size_t size)
359{
360 assert(ptr);
361 assert(HAS_ALIGNMENT(ptr, sizeof(size_t)));
362 assert(HAS_ALIGNMENT(size, sizeof(size_t)));
363 assert(size >= sizeof(Region));
364 *(size_t*)ptr = size;
365 ((size_t*)ptr)[(size/sizeof(size_t))-1] = size;
366}
367
368static void create_free_region(void *ptr, size_t size)
369{
370 assert(ptr);
371 assert(HAS_ALIGNMENT(ptr, sizeof(size_t)));
372 assert(HAS_ALIGNMENT(size, sizeof(size_t)));
373 assert(size >= sizeof(Region));
374 Region *freeRegion = (Region*)ptr;
375 freeRegion->size = size;
376 ((size_t*)ptr)[(size/sizeof(size_t))-1] = size | FREE_REGION_FLAG;
377}
378
379static void prepend_to_free_list(Region *region, Region *prependTo)
380{
381 assert(region);
382 assert(prependTo);
383 // N.b. the region we are prepending to is always the sentinel node,
384 // which represents a dummy node that is technically not a free node, so
385 // region_is_free(prependTo) does not hold.
386 assert(region_is_free((Region*)region));
387 region->next = prependTo;
388 region->prev = prependTo->prev;
389 assert(region->prev);
390 prependTo->prev = region;
391 region->prev->next = region;
392}
393
394static void unlink_from_free_list(Region *region)
395{
396 assert(region);
397 assert(region_is_free((Region*)region));
398 assert(region->prev);
399 assert(region->next);
400 region->prev->next = region->next;
401 region->next->prev = region->prev;
402}
403
404static void link_to_free_list(Region *freeRegion)
405{
406 assert(freeRegion);
407 assert(freeRegion->size >= sizeof(Region));
408 int bucketIndex = compute_free_list_bucket(freeRegion->size-REGION_HEADER_SIZE);
409 Region *freeListHead = freeRegionBuckets + bucketIndex;
410 freeRegion->prev = freeListHead;
411 freeRegion->next = freeListHead->next;
412 assert(freeRegion->next);
413 freeListHead->next = freeRegion;
414 freeRegion->next->prev = freeRegion;
415 freeRegionBucketsUsed |= ((BUCKET_BITMASK_T)1) << bucketIndex;
416}
417
418#if 0
419static void dump_memory_regions()
420{
421 ASSERT_MALLOC_IS_ACQUIRED();
422 RootRegion *root = listOfAllRegions;
423 MAIN_THREAD_ASYNC_EM_ASM(console.log('All memory regions:'));
424 while(root)
425 {
426 Region *r = (Region*)root;
427 assert(debug_region_is_consistent(r));
428 uint8_t *lastRegionEnd = root->endPtr;
429 MAIN_THREAD_ASYNC_EM_ASM(console.log('Region block 0x'+($0>>>0).toString(16)+' - 0x'+($1>>>0).toString(16)+ ' ('+($2>>>0)+' bytes):'),
430 r, lastRegionEnd, lastRegionEnd-(uint8_t*)r);
431 while((uint8_t*)r < lastRegionEnd)
432 {
433 MAIN_THREAD_ASYNC_EM_ASM(console.log('Region 0x'+($0>>>0).toString(16)+', size: '+($1>>>0)+' ('+($2?"used":"--FREE--")+')'),
434 r, r->size, region_ceiling_size(r) == r->size);
435
436 assert(debug_region_is_consistent(r));
437 size_t sizeFromCeiling = size_of_region_from_ceiling(r);
438 if (sizeFromCeiling != r->size)
439 MAIN_THREAD_ASYNC_EM_ASM(console.log('Corrupt region! Size marker at the end of the region does not match: '+($0>>>0)), sizeFromCeiling);
440 if (r->size == 0)
441 break;
442 r = next_region(r);
443 }
444 root = root->next;
445 MAIN_THREAD_ASYNC_EM_ASM(console.log(""));
446 }
447 MAIN_THREAD_ASYNC_EM_ASM(console.log('Free regions:'));
448 for(int i = 0; i < NUM_FREE_BUCKETS; ++i)
449 {
450 Region *prev = &freeRegionBuckets[i];
451 Region *fr = freeRegionBuckets[i].next;
452 while(fr != &freeRegionBuckets[i])
453 {
454 MAIN_THREAD_ASYNC_EM_ASM(console.log('In bucket '+$0+', free region 0x'+($1>>>0).toString(16)+', size: ' + ($2>>>0) + ' (size at ceiling: '+($3>>>0)+'), prev: 0x' + ($4>>>0).toString(16) + ', next: 0x' + ($5>>>0).toString(16)),
455 i, fr, fr->size, size_of_region_from_ceiling(fr), fr->prev, fr->next);
456 assert(debug_region_is_consistent(fr));
457 assert(region_is_free(fr));
458 assert(fr->prev == prev);
459 prev = fr;
460 assert(fr->next != fr);
461 assert(fr->prev != fr);
462 fr = fr->next;
463 }
464 }
465 MAIN_THREAD_ASYNC_EM_ASM(console.log('Free bucket index map: ' + ($0>>>0).toString(2) + ' ' + ($1>>>0).toString(2)), (uint32_t)(freeRegionBucketsUsed >> 32), (uint32_t)freeRegionBucketsUsed);
466 MAIN_THREAD_ASYNC_EM_ASM(console.log(""));
467}
468
469void emmalloc_dump_memory_regions()
470{
471 MALLOC_ACQUIRE();
472 dump_memory_regions();
473 MALLOC_RELEASE();
474}
475
476static int validate_memory_regions()
477{
478 ASSERT_MALLOC_IS_ACQUIRED();
479 RootRegion *root = listOfAllRegions;
480 while(root)
481 {
482 Region *r = (Region*)root;
483 if (!debug_region_is_consistent(r))
484 {
485 MAIN_THREAD_ASYNC_EM_ASM(console.error('Used region 0x'+($0>>>0).toString(16)+', size: '+($1>>>0)+' ('+($2?"used":"--FREE--")+') is corrupt (size markers in the beginning and at the end of the region do not match!)'),
486 r, r->size, region_ceiling_size(r) == r->size);
487 return 1;
488 }
489 uint8_t *lastRegionEnd = root->endPtr;
490 while((uint8_t*)r < lastRegionEnd)
491 {
492 if (!debug_region_is_consistent(r))
493 {
494 MAIN_THREAD_ASYNC_EM_ASM(console.error('Used region 0x'+($0>>>0).toString(16)+', size: '+($1>>>0)+' ('+($2?"used":"--FREE--")+') is corrupt (size markers in the beginning and at the end of the region do not match!)'),
495 r, r->size, region_ceiling_size(r) == r->size);
496 return 1;
497 }
498 if (r->size == 0)
499 break;
500 r = next_region(r);
501 }
502 root = root->next;
503 }
504 for(int i = 0; i < NUM_FREE_BUCKETS; ++i)
505 {
506 Region *prev = &freeRegionBuckets[i];
507 Region *fr = freeRegionBuckets[i].next;
508 while(fr != &freeRegionBuckets[i])
509 {
510 if (!debug_region_is_consistent(fr) || !region_is_free(fr) || fr->prev != prev || fr->next == fr || fr->prev == fr)
511 {
512 MAIN_THREAD_ASYNC_EM_ASM(console.log('In bucket '+$0+', free region 0x'+($1>>>0).toString(16)+', size: ' + ($2>>>0) + ' (size at ceiling: '+($3>>>0)+'), prev: 0x' + ($4>>>0).toString(16) + ', next: 0x' + ($5>>>0).toString(16) + ' is corrupt!'),
513 i, fr, fr->size, size_of_region_from_ceiling(fr), fr->prev, fr->next);
514 return 1;
515 }
516 prev = fr;
517 fr = fr->next;
518 }
519 }
520 return 0;
521}
522
523int emmalloc_validate_memory_regions()
524{
525 MALLOC_ACQUIRE();
526 int memoryError = validate_memory_regions();
527 MALLOC_RELEASE();
528 return memoryError;
529}
530#endif
531
532static bool claim_more_memory(size_t numBytes)
533{
534#ifdef EMMALLOC_VERBOSE
535 MAIN_THREAD_ASYNC_EM_ASM(console.log('claim_more_memory(numBytes='+($0>>>0)+ ')'), numBytes);
536#endif
537
538#ifdef EMMALLOC_MEMVALIDATE
539 validate_memory_regions();
540#endif
541
542 uint8_t *startPtr;
543 uint8_t *endPtr;
544 do {
545 // If this is the first time we're called, see if we can use
546 // the initial heap memory set up by wasm-ld.
547 if (!listOfAllRegions) {
548 unsigned char *heap_end = sbrk(0);
549 if (numBytes <= (size_t)(heap_end - &__heap_base)) {
550 startPtr = &__heap_base;
551 endPtr = heap_end;
552 break;
553 }
554 }
555
556 // Round numBytes up to the nearest page size.
557 numBytes = (numBytes + (PAGE_SIZE-1)) & -PAGE_SIZE;
558
559 // Claim memory via sbrk
560 startPtr = (uint8_t*)sbrk(numBytes);
561 if ((intptr_t)startPtr == -1)
562 {
563#ifdef EMMALLOC_VERBOSE
564 MAIN_THREAD_ASYNC_EM_ASM(console.error('claim_more_memory: sbrk failed!'));
565#endif
566 return false;
567 }
568#ifdef EMMALLOC_VERBOSE
569 MAIN_THREAD_ASYNC_EM_ASM(console.log('claim_more_memory: claimed 0x' + ($0>>>0).toString(16) + ' - 0x' + ($1>>>0).toString(16) + ' (' + ($2>>>0) + ' bytes) via sbrk()'), startPtr, startPtr + numBytes, numBytes);
570#endif
571 assert(HAS_ALIGNMENT(startPtr, alignof(size_t)));
572 endPtr = startPtr + numBytes;
573 } while (0);
574
575 // Create a sentinel region at the end of the new heap block
576 Region *endSentinelRegion = (Region*)(endPtr - sizeof(Region));
577 create_used_region(endSentinelRegion, sizeof(Region));
578
579 // If we are the sole user of sbrk(), it will feed us continuous/consecutive memory addresses - take advantage
580 // of that if so: instead of creating two disjoint memory regions blocks, expand the previous one to a larger size.
581 uint8_t *previousSbrkEndAddress = listOfAllRegions ? listOfAllRegions->endPtr : 0;
582 if (startPtr == previousSbrkEndAddress)
583 {
584 Region *prevEndSentinel = prev_region((Region*)startPtr);
585 assert(debug_region_is_consistent(prevEndSentinel));
586 assert(region_is_in_use(prevEndSentinel));
587 Region *prevRegion = prev_region(prevEndSentinel);
588 assert(debug_region_is_consistent(prevRegion));
589
590 listOfAllRegions->endPtr = endPtr;
591
592 // Two scenarios, either the last region of the previous block was in use, in which case we need to create
593 // a new free region in the newly allocated space; or it was free, in which case we can extend that region
594 // to cover a larger size.
595 if (region_is_free(prevRegion))
596 {
597 size_t newFreeRegionSize = (uint8_t*)endSentinelRegion - (uint8_t*)prevRegion;
598 unlink_from_free_list(prevRegion);
599 create_free_region(prevRegion, newFreeRegionSize);
600 link_to_free_list(prevRegion);
601 return true;
602 }
603 // else: last region of the previous block was in use. Since we are joining two consecutive sbrk() blocks,
604 // we can swallow the end sentinel of the previous block away.
605 startPtr -= sizeof(Region);
606 }
607 else
608 {
609 // Create a root region at the start of the heap block
610 create_used_region(startPtr, sizeof(Region));
611
612 // Dynamic heap start region:
613 RootRegion *newRegionBlock = (RootRegion*)startPtr;
614 newRegionBlock->next = listOfAllRegions; // Pointer to next region block head
615 newRegionBlock->endPtr = endPtr; // Pointer to the end address of this region block
616 listOfAllRegions = newRegionBlock;
617 startPtr += sizeof(Region);
618 }
619
620 // Create a new memory region for the new claimed free space.
621 create_free_region(startPtr, (uint8_t*)endSentinelRegion - startPtr);
622 link_to_free_list((Region*)startPtr);
623 return true;
624}
625
626#if 0
627// Initialize emmalloc during static initialization.
628// See system/lib/README.md for static constructor ordering.
629__attribute__((constructor(47)))
630static void initialize_emmalloc_heap()
631{
632 // Initialize circular doubly linked lists representing free space
633 // Never useful to unroll this for loop, just takes up code size.
634#pragma clang loop unroll(disable)
635 for(int i = 0; i < NUM_FREE_BUCKETS; ++i)
636 freeRegionBuckets[i].prev = freeRegionBuckets[i].next = &freeRegionBuckets[i];
637
638#ifdef EMMALLOC_VERBOSE
639 MAIN_THREAD_ASYNC_EM_ASM(console.log('initialize_emmalloc_heap()'));
640#endif
641
642 // Start with a tiny dynamic region.
643 claim_more_memory(3*sizeof(Region));
644}
645
646void emmalloc_blank_slate_from_orbit()
647{
648 MALLOC_ACQUIRE();
649 listOfAllRegions = NULL;
650 freeRegionBucketsUsed = 0;
651 initialize_emmalloc_heap();
652 MALLOC_RELEASE();
653}
654#endif
655
656static void *attempt_allocate(Region *freeRegion, size_t alignment, size_t size)
657{
658 ASSERT_MALLOC_IS_ACQUIRED();
659 assert(freeRegion);
660 // Look at the next potential free region to allocate into.
661 // First, we should check if the free region has enough of payload bytes contained
662 // in it to accommodate the new allocation. This check needs to take account the
663 // requested allocation alignment, so the payload memory area needs to be rounded
664 // upwards to the desired alignment.
665 uint8_t *payloadStartPtr = region_payload_start_ptr(freeRegion);
666 uint8_t *payloadStartPtrAligned = ALIGN_UP(payloadStartPtr, alignment);
667 uint8_t *payloadEndPtr = region_payload_end_ptr(freeRegion);
668
669 // Do we have enough free space, taking into account alignment?
670 if (payloadStartPtrAligned + size > payloadEndPtr)
671 return NULL;
672
673 // We have enough free space, so the memory allocation will be made into this region. Remove this free region
674 // from the list of free regions: whatever slop remains will be later added back to the free region pool.
675 unlink_from_free_list(freeRegion);
676
677 // Before we proceed further, fix up the boundary of this region and the region that precedes this one,
678 // so that the boundary between the two regions happens at a right spot for the payload to be aligned.
679 if (payloadStartPtr != payloadStartPtrAligned)
680 {
681 Region *prevRegion = prev_region((Region*)freeRegion);
682 // We never have two free regions adjacent to each other, so the region before this free
683 // region should be in use.
684 assert(region_is_in_use(prevRegion));
685 size_t regionBoundaryBumpAmount = payloadStartPtrAligned - payloadStartPtr;
686 size_t newThisRegionSize = freeRegion->size - regionBoundaryBumpAmount;
687 create_used_region(prevRegion, prevRegion->size + regionBoundaryBumpAmount);
688 freeRegion = (Region *)((uint8_t*)freeRegion + regionBoundaryBumpAmount);
689 freeRegion->size = newThisRegionSize;
690 }
691 // Next, we need to decide whether this region is so large that it should be split into two regions,
692 // one representing the newly used memory area, and at the high end a remaining leftover free area.
693 // This splitting to two is done always if there is enough space for the high end to fit a region.
694 // Carve 'size' bytes of payload off this region. So,
695 // [sz prev next sz]
696 // becomes
697 // [sz payload sz] [sz prev next sz]
698 if (sizeof(Region) + REGION_HEADER_SIZE + size <= freeRegion->size)
699 {
700 // There is enough space to keep a free region at the end of the carved out block
701 // -> construct the new block
702 Region *newFreeRegion = (Region *)((uint8_t*)freeRegion + REGION_HEADER_SIZE + size);
703 create_free_region(newFreeRegion, freeRegion->size - size - REGION_HEADER_SIZE);
704 link_to_free_list(newFreeRegion);
705
706 // Recreate the resized Region under its new size.
707 create_used_region(freeRegion, size + REGION_HEADER_SIZE);
708 }
709 else
710 {
711 // There is not enough space to split the free memory region into used+free parts, so consume the whole
712 // region as used memory, not leaving a free memory region behind.
713 // Initialize the free region as used by resetting the ceiling size to the same value as the size at bottom.
714 ((size_t*)((uint8_t*)freeRegion + freeRegion->size))[-1] = freeRegion->size;
715 }
716
717#ifdef __EMSCRIPTEN_TRACING__
718 emscripten_trace_record_allocation(freeRegion, freeRegion->size);
719#endif
720
721#ifdef EMMALLOC_VERBOSE
722 MAIN_THREAD_ASYNC_EM_ASM(console.log('attempt_allocate - succeeded allocating memory, region ptr=0x' + ($0>>>0).toString(16) + ', align=' + $1 + ', payload size=' + ($2>>>0) + ' bytes)'), freeRegion, alignment, size);
723#endif
724
725 return (uint8_t*)freeRegion + sizeof(size_t);
726}
727
728static size_t validate_alloc_alignment(size_t alignment)
729{
730 // Cannot perform allocations that are less than 4 byte aligned, because the Region
731 // control structures need to be aligned. Also round up to minimum outputted alignment.
732 alignment = MAX(alignment, MALLOC_ALIGNMENT);
733 // Arbitrary upper limit on alignment - very likely a programming bug if alignment is higher than this.
734 assert(alignment <= 1024*1024);
735 return alignment;
736}
737
738static size_t validate_alloc_size(size_t size)
739{
740 assert(size + REGION_HEADER_SIZE > size);
741
742 // Allocation sizes must be a multiple of pointer sizes, and at least 2*sizeof(pointer).
743 size_t validatedSize = size > SMALLEST_ALLOCATION_SIZE ? (size_t)ALIGN_UP(size, sizeof(Region*)) : SMALLEST_ALLOCATION_SIZE;
744 assert(validatedSize >= size); // 32-bit wraparound should not occur, too large sizes should be stopped before
745
746 return validatedSize;
747}
748
749static void *allocate_memory(size_t alignment, size_t size)
750{
751 ASSERT_MALLOC_IS_ACQUIRED();
752
753#ifdef EMMALLOC_VERBOSE
754 MAIN_THREAD_ASYNC_EM_ASM(console.log('allocate_memory(align=' + $0 + ', size=' + ($1>>>0) + ' bytes)'), alignment, size);
755#endif
756
757#ifdef EMMALLOC_MEMVALIDATE
758 validate_memory_regions();
759#endif
760
761 if (!IS_POWER_OF_2(alignment))
762 {
763#ifdef EMMALLOC_VERBOSE
764 MAIN_THREAD_ASYNC_EM_ASM(console.log('Allocation failed: alignment not power of 2!'));
765#endif
766 return 0;
767 }
768
769 if (size > MAX_ALLOC_SIZE)
770 {
771#ifdef EMMALLOC_VERBOSE
772 MAIN_THREAD_ASYNC_EM_ASM(console.log('Allocation failed: attempted allocation size is too large: ' + ($0 >>> 0) + 'bytes! (negative integer wraparound?)'), size);
773#endif
774 return 0;
775 }
776
777 alignment = validate_alloc_alignment(alignment);
778 size = validate_alloc_size(size);
779
780 // Attempt to allocate memory starting from smallest bucket that can contain the required amount of memory.
781 // Under normal alignment conditions this should always be the first or second bucket we look at, but if
782 // performing an allocation with complex alignment, we may need to look at multiple buckets.
783 int bucketIndex = compute_free_list_bucket(size);
784 BUCKET_BITMASK_T bucketMask = freeRegionBucketsUsed >> bucketIndex;
785
786 // Loop through each bucket that has free regions in it, based on bits set in freeRegionBucketsUsed bitmap.
787 while(bucketMask)
788 {
789 BUCKET_BITMASK_T indexAdd = __builtin_ctzll(bucketMask);
790 bucketIndex += indexAdd;
791 bucketMask >>= indexAdd;
792 assert(bucketIndex >= 0);
793 assert(bucketIndex <= NUM_FREE_BUCKETS-1);
794 assert(freeRegionBucketsUsed & (((BUCKET_BITMASK_T)1) << bucketIndex));
795
796 Region *freeRegion = freeRegionBuckets[bucketIndex].next;
797 assert(freeRegion);
798 if (freeRegion != &freeRegionBuckets[bucketIndex])
799 {
800 void *ptr = attempt_allocate(freeRegion, alignment, size);
801 if (ptr)
802 return ptr;
803
804 // We were not able to allocate from the first region found in this bucket, so penalize
805 // the region by cycling it to the end of the doubly circular linked list. (constant time)
806 // This provides a randomized guarantee that when performing allocations of size k to a
807 // bucket of [k-something, k+something] range, we will not always attempt to satisfy the
808 // allocation from the same available region at the front of the list, but we try each
809 // region in turn.
810 unlink_from_free_list(freeRegion);
811 prepend_to_free_list(freeRegion, &freeRegionBuckets[bucketIndex]);
812 // But do not stick around to attempt to look at other regions in this bucket - move
813 // to search the next populated bucket index if this did not fit. This gives a practical
814 // "allocation in constant time" guarantee, since the next higher bucket will only have
815 // regions that are all of strictly larger size than the requested allocation. Only if
816 // there is a difficult alignment requirement we may fail to perform the allocation from
817 // a region in the next bucket, and if so, we keep trying higher buckets until one of them
818 // works.
819 ++bucketIndex;
820 bucketMask >>= 1;
821 }
822 else
823 {
824 // This bucket was not populated after all with any regions,
825 // but we just had a stale bit set to mark a populated bucket.
826 // Reset the bit to update latest status so that we do not
827 // redundantly look at this bucket again.
828 freeRegionBucketsUsed &= ~(((BUCKET_BITMASK_T)1) << bucketIndex);
829 bucketMask ^= 1;
830 }
831 // Instead of recomputing bucketMask from scratch at the end of each loop, it is updated as we go,
832 // to avoid undefined behavior with (x >> 32)/(x >> 64) when bucketIndex reaches 32/64, (the shift would comes out as a no-op instead of 0).
833
834 assert((bucketIndex == NUM_FREE_BUCKETS && bucketMask == 0) || (bucketMask == freeRegionBucketsUsed >> bucketIndex));
835 }
836
837 // None of the buckets were able to accommodate an allocation. If this happens we are almost out of memory.
838 // The largest bucket might contain some suitable regions, but we only looked at one region in that bucket, so
839 // as a last resort, loop through more free regions in the bucket that represents the largest allocations available.
840 // But only if the bucket representing largest allocations available is not any of the first thirty buckets,
841 // these represent allocatable areas less than <1024 bytes - which could be a lot of scrap.
842 // In such case, prefer to sbrk() in more memory right away.
843 int largestBucketIndex = NUM_FREE_BUCKETS - 1 - __builtin_clzll(freeRegionBucketsUsed);
844 // freeRegion will be null if there is absolutely no memory left. (all buckets are 100% used)
845 Region *freeRegion = freeRegionBucketsUsed ? freeRegionBuckets[largestBucketIndex].next : 0;
846 if (freeRegionBucketsUsed >> 30)
847 {
848 // Look only at a constant number of regions in this bucket max, to avoid bad worst case behavior.
849 // If this many regions cannot find free space, we give up and prefer to sbrk() more instead.
850 const int maxRegionsToTryBeforeGivingUp = 99;
851 int numTriesLeft = maxRegionsToTryBeforeGivingUp;
852 while(freeRegion != &freeRegionBuckets[largestBucketIndex] && numTriesLeft-- > 0)
853 {
854 void *ptr = attempt_allocate(freeRegion, alignment, size);
855 if (ptr)
856 return ptr;
857 freeRegion = freeRegion->next;
858 }
859 }
860
861 // We were unable to find a free memory region. Must sbrk() in more memory!
862 size_t numBytesToClaim = size+sizeof(Region)*3;
863 assert(numBytesToClaim > size); // 32-bit wraparound should not happen here, allocation size has been validated above!
864 bool success = claim_more_memory(numBytesToClaim);
865 if (success)
866 return allocate_memory(alignment, size); // Recurse back to itself to try again
867
868 // also sbrk() failed, we are really really constrained :( As a last resort, go back to looking at the
869 // bucket we already looked at above, continuing where the above search left off - perhaps there are
870 // regions we overlooked the first time that might be able to satisfy the allocation.
871 if (freeRegion)
872 {
873 while(freeRegion != &freeRegionBuckets[largestBucketIndex])
874 {
875 void *ptr = attempt_allocate(freeRegion, alignment, size);
876 if (ptr)
877 return ptr;
878 freeRegion = freeRegion->next;
879 }
880 }
881
882#ifdef EMMALLOC_VERBOSE
883 MAIN_THREAD_ASYNC_EM_ASM(console.log('Could not find a free memory block!'));
884#endif
885
886 return 0;
887}
888
889static
890void *emmalloc_memalign(size_t alignment, size_t size)
891{
892 MALLOC_ACQUIRE();
893 void *ptr = allocate_memory(alignment, size);
894 MALLOC_RELEASE();
895 return ptr;
896}
897
898#if 0
899void * EMMALLOC_EXPORT memalign(size_t alignment, size_t size)
900{
901 return emmalloc_memalign(alignment, size);
902}
903#endif
904
905void * EMMALLOC_EXPORT aligned_alloc(size_t alignment, size_t size)
906{
907 if ((alignment % sizeof(void *) != 0) || (size % alignment) != 0)
908 return 0;
909 return emmalloc_memalign(alignment, size);
910}
911
912static
913void *emmalloc_malloc(size_t size)
914{
915 return emmalloc_memalign(MALLOC_ALIGNMENT, size);
916}
917
918void * EMMALLOC_EXPORT malloc(size_t size)
919{
920 return emmalloc_malloc(size);
921}
922
923static
924size_t emmalloc_usable_size(void *ptr)
925{
926 if (!ptr)
927 return 0;
928
929 uint8_t *regionStartPtr = (uint8_t*)ptr - sizeof(size_t);
930 Region *region = (Region*)(regionStartPtr);
931 assert(HAS_ALIGNMENT(region, sizeof(size_t)));
932
933 MALLOC_ACQUIRE();
934
935 size_t size = region->size;
936 assert(size >= sizeof(Region));
937 assert(region_is_in_use(region));
938
939 MALLOC_RELEASE();
940
941 return size - REGION_HEADER_SIZE;
942}
943
944size_t EMMALLOC_EXPORT malloc_usable_size(void *ptr)
945{
946 return emmalloc_usable_size(ptr);
947}
948
949static
950void emmalloc_free(void *ptr)
951{
952#ifdef EMMALLOC_MEMVALIDATE
953 emmalloc_validate_memory_regions();
954#endif
955
956 if (!ptr)
957 return;
958
959#ifdef EMMALLOC_VERBOSE
960 MAIN_THREAD_ASYNC_EM_ASM(console.log('free(ptr=0x'+($0>>>0).toString(16)+')'), ptr);
961#endif
962
963 uint8_t *regionStartPtr = (uint8_t*)ptr - sizeof(size_t);
964 Region *region = (Region*)(regionStartPtr);
965 assert(HAS_ALIGNMENT(region, sizeof(size_t)));
966
967 MALLOC_ACQUIRE();
968
969 size_t size = region->size;
970#ifdef EMMALLOC_VERBOSE
971 if (size < sizeof(Region) || !region_is_in_use(region))
972 {
973 if (debug_region_is_consistent(region))
974 // LLVM wasm backend bug: cannot use MAIN_THREAD_ASYNC_EM_ASM() here, that generates internal compiler error
975 // Reproducible by running e.g. other.test_alloc_3GB
976 EM_ASM(console.error('Double free at region ptr 0x' + ($0>>>0).toString(16) + ', region->size: 0x' + ($1>>>0).toString(16) + ', region->sizeAtCeiling: 0x' + ($2>>>0).toString(16) + ')'), region, size, region_ceiling_size(region));
977 else
978 MAIN_THREAD_ASYNC_EM_ASM(console.error('Corrupt region at region ptr 0x' + ($0>>>0).toString(16) + ' region->size: 0x' + ($1>>>0).toString(16) + ', region->sizeAtCeiling: 0x' + ($2>>>0).toString(16) + ')'), region, size, region_ceiling_size(region));
979 }
980#endif
981 assert(size >= sizeof(Region));
982 assert(region_is_in_use(region));
983
984#ifdef __EMSCRIPTEN_TRACING__
985 emscripten_trace_record_free(region);
986#endif
987
988 // Check merging with left side
989 size_t prevRegionSizeField = ((size_t*)region)[-1];
990 size_t prevRegionSize = prevRegionSizeField & ~FREE_REGION_FLAG;
991 if (prevRegionSizeField != prevRegionSize) // Previous region is free?
992 {
993 Region *prevRegion = (Region*)((uint8_t*)region - prevRegionSize);
994 assert(debug_region_is_consistent(prevRegion));
995 unlink_from_free_list(prevRegion);
996 regionStartPtr = (uint8_t*)prevRegion;
997 size += prevRegionSize;
998 }
999
1000 // Check merging with right side
1001 Region *nextRegion = next_region(region);
1002 assert(debug_region_is_consistent(nextRegion));
1003 size_t sizeAtEnd = *(size_t*)region_payload_end_ptr(nextRegion);
1004 if (nextRegion->size != sizeAtEnd)
1005 {
1006 unlink_from_free_list(nextRegion);
1007 size += nextRegion->size;
1008 }
1009
1010 create_free_region(regionStartPtr, size);
1011 link_to_free_list((Region*)regionStartPtr);
1012
1013 MALLOC_RELEASE();
1014
1015#ifdef EMMALLOC_MEMVALIDATE
1016 emmalloc_validate_memory_regions();
1017#endif
1018}
1019
1020void EMMALLOC_EXPORT free(void *ptr)
1021{
1022 emmalloc_free(ptr);
1023}
1024
1025// Can be called to attempt to increase or decrease the size of the given region
1026// to a new size (in-place). Returns 1 if resize succeeds, and 0 on failure.
1027static int attempt_region_resize(Region *region, size_t size)
1028{
1029 ASSERT_MALLOC_IS_ACQUIRED();
1030 assert(size > 0);
1031 assert(HAS_ALIGNMENT(size, sizeof(size_t)));
1032
1033#ifdef EMMALLOC_VERBOSE
1034 MAIN_THREAD_ASYNC_EM_ASM(console.log('attempt_region_resize(region=0x' + ($0>>>0).toString(16) + ', size=' + ($1>>>0) + ' bytes)'), region, size);
1035#endif
1036
1037 // First attempt to resize this region, if the next region that follows this one
1038 // is a free region.
1039 Region *nextRegion = next_region(region);
1040 uint8_t *nextRegionEndPtr = (uint8_t*)nextRegion + nextRegion->size;
1041 size_t sizeAtCeiling = ((size_t*)nextRegionEndPtr)[-1];
1042 if (nextRegion->size != sizeAtCeiling) // Next region is free?
1043 {
1044 assert(region_is_free(nextRegion));
1045 uint8_t *newNextRegionStartPtr = (uint8_t*)region + size;
1046 assert(HAS_ALIGNMENT(newNextRegionStartPtr, sizeof(size_t)));
1047 // Next region does not shrink to too small size?
1048 if (newNextRegionStartPtr + sizeof(Region) <= nextRegionEndPtr)
1049 {
1050 unlink_from_free_list(nextRegion);
1051 create_free_region(newNextRegionStartPtr, nextRegionEndPtr - newNextRegionStartPtr);
1052 link_to_free_list((Region*)newNextRegionStartPtr);
1053 create_used_region(region, newNextRegionStartPtr - (uint8_t*)region);
1054 return 1;
1055 }
1056 // If we remove the next region altogether, allocation is satisfied?
1057 if (newNextRegionStartPtr <= nextRegionEndPtr)
1058 {
1059 unlink_from_free_list(nextRegion);
1060 create_used_region(region, region->size + nextRegion->size);
1061 return 1;
1062 }
1063 }
1064 else
1065 {
1066 // Next region is an used region - we cannot change its starting address. However if we are shrinking the
1067 // size of this region, we can create a new free region between this and the next used region.
1068 if (size + sizeof(Region) <= region->size)
1069 {
1070 size_t freeRegionSize = region->size - size;
1071 create_used_region(region, size);
1072 Region *freeRegion = (Region *)((uint8_t*)region + size);
1073 create_free_region(freeRegion, freeRegionSize);
1074 link_to_free_list(freeRegion);
1075 return 1;
1076 }
1077 else if (size <= region->size)
1078 {
1079 // Caller was asking to shrink the size, but due to not being able to fit a full Region in the shrunk
1080 // area, we cannot actually do anything. This occurs if the shrink amount is really small. In such case,
1081 // just call it success without doing any work.
1082 return 1;
1083 }
1084 }
1085#ifdef EMMALLOC_VERBOSE
1086 MAIN_THREAD_ASYNC_EM_ASM(console.log('attempt_region_resize failed.'));
1087#endif
1088 return 0;
1089}
1090
1091static int acquire_and_attempt_region_resize(Region *region, size_t size)
1092{
1093 MALLOC_ACQUIRE();
1094 int success = attempt_region_resize(region, size);
1095 MALLOC_RELEASE();
1096 return success;
1097}
1098
1099static
1100void *emmalloc_aligned_realloc(void *ptr, size_t alignment, size_t size)
1101{
1102#ifdef EMMALLOC_VERBOSE
1103 MAIN_THREAD_ASYNC_EM_ASM(console.log('aligned_realloc(ptr=0x' + ($0>>>0).toString(16) + ', alignment=' + $1 + ', size=' + ($2>>>0)), ptr, alignment, size);
1104#endif
1105
1106 if (!ptr)
1107 return emmalloc_memalign(alignment, size);
1108
1109 if (size == 0)
1110 {
1111 free(ptr);
1112 return 0;
1113 }
1114
1115 if (size > MAX_ALLOC_SIZE)
1116 {
1117#ifdef EMMALLOC_VERBOSE
1118 MAIN_THREAD_ASYNC_EM_ASM(console.log('Allocation failed: attempted allocation size is too large: ' + ($0 >>> 0) + 'bytes! (negative integer wraparound?)'), size);
1119#endif
1120 return 0;
1121 }
1122
1123 assert(IS_POWER_OF_2(alignment));
1124 // aligned_realloc() cannot be used to ask to change the alignment of a pointer.
1125 assert(HAS_ALIGNMENT(ptr, alignment));
1126 size = validate_alloc_size(size);
1127
1128 // Calculate the region start address of the original allocation
1129 Region *region = (Region*)((uint8_t*)ptr - sizeof(size_t));
1130
1131 // First attempt to resize the given region to avoid having to copy memory around
1132 if (acquire_and_attempt_region_resize(region, size + REGION_HEADER_SIZE))
1133 {
1134#ifdef __EMSCRIPTEN_TRACING__
1135 emscripten_trace_record_reallocation(ptr, ptr, size);
1136#endif
1137 return ptr;
1138 }
1139
1140 // If resize failed, we must allocate a new region, copy the data over, and then
1141 // free the old region.
1142 void *newptr = emmalloc_memalign(alignment, size);
1143 if (newptr)
1144 {
1145 memcpy(newptr, ptr, MIN(size, region->size - REGION_HEADER_SIZE));
1146 free(ptr);
1147 }
1148 // N.B. If there is not enough memory, the old memory block should not be freed and
1149 // null pointer is returned.
1150 return newptr;
1151}
1152
1153#if 0
1154void * EMMALLOC_EXPORT aligned_realloc(void *ptr, size_t alignment, size_t size)
1155{
1156 return emmalloc_aligned_realloc(ptr, alignment, size);
1157}
1158#endif
1159
1160#if 0
1161// realloc_try() is like realloc(), but only attempts to try to resize the existing memory
1162// area. If resizing the existing memory area fails, then realloc_try() will return 0
1163// (the original memory block is not freed or modified). If resizing succeeds, previous
1164// memory contents will be valid up to min(old length, new length) bytes.
1165void *emmalloc_realloc_try(void *ptr, size_t size)
1166{
1167 if (!ptr)
1168 return 0;
1169
1170 if (size == 0)
1171 {
1172 free(ptr);
1173 return 0;
1174 }
1175
1176 if (size > MAX_ALLOC_SIZE)
1177 {
1178#ifdef EMMALLOC_VERBOSE
1179 MAIN_THREAD_ASYNC_EM_ASM(console.log('Allocation failed: attempted allocation size is too large: ' + ($0 >>> 0) + 'bytes! (negative integer wraparound?)'), size);
1180#endif
1181 return 0;
1182 }
1183
1184 size = validate_alloc_size(size);
1185
1186 // Calculate the region start address of the original allocation
1187 Region *region = (Region*)((uint8_t*)ptr - sizeof(size_t));
1188
1189 // Attempt to resize the given region to avoid having to copy memory around
1190 int success = acquire_and_attempt_region_resize(region, size + REGION_HEADER_SIZE);
1191#ifdef __EMSCRIPTEN_TRACING__
1192 if (success)
1193 emscripten_trace_record_reallocation(ptr, ptr, size);
1194#endif
1195 return success ? ptr : 0;
1196}
1197
1198// emmalloc_aligned_realloc_uninitialized() is like aligned_realloc(), but old memory contents
1199// will be undefined after reallocation. (old memory is not preserved in any case)
1200void *emmalloc_aligned_realloc_uninitialized(void *ptr, size_t alignment, size_t size)
1201{
1202 if (!ptr)
1203 return emmalloc_memalign(alignment, size);
1204
1205 if (size == 0)
1206 {
1207 free(ptr);
1208 return 0;
1209 }
1210
1211 if (size > MAX_ALLOC_SIZE)
1212 {
1213#ifdef EMMALLOC_VERBOSE
1214 MAIN_THREAD_ASYNC_EM_ASM(console.log('Allocation failed: attempted allocation size is too large: ' + ($0 >>> 0) + 'bytes! (negative integer wraparound?)'), size);
1215#endif
1216 return 0;
1217 }
1218
1219 size = validate_alloc_size(size);
1220
1221 // Calculate the region start address of the original allocation
1222 Region *region = (Region*)((uint8_t*)ptr - sizeof(size_t));
1223
1224 // First attempt to resize the given region to avoid having to copy memory around
1225 if (acquire_and_attempt_region_resize(region, size + REGION_HEADER_SIZE))
1226 {
1227#ifdef __EMSCRIPTEN_TRACING__
1228 emscripten_trace_record_reallocation(ptr, ptr, size);
1229#endif
1230 return ptr;
1231 }
1232
1233 // If resize failed, drop the old region and allocate a new region. Memory is not
1234 // copied over
1235 free(ptr);
1236 return emmalloc_memalign(alignment, size);
1237}
1238#endif
1239
1240static
1241void *emmalloc_realloc(void *ptr, size_t size)
1242{
1243 return emmalloc_aligned_realloc(ptr, MALLOC_ALIGNMENT, size);
1244}
1245
1246void * EMMALLOC_EXPORT realloc(void *ptr, size_t size)
1247{
1248 return emmalloc_realloc(ptr, size);
1249}
1250
1251#if 0
1252// realloc_uninitialized() is like realloc(), but old memory contents
1253// will be undefined after reallocation. (old memory is not preserved in any case)
1254void *emmalloc_realloc_uninitialized(void *ptr, size_t size)
1255{
1256 return emmalloc_aligned_realloc_uninitialized(ptr, MALLOC_ALIGNMENT, size);
1257}
1258#endif
1259
1260static
1261int emmalloc_posix_memalign(void **memptr, size_t alignment, size_t size)
1262{
1263 assert(memptr);
1264 if (alignment % sizeof(void *) != 0)
1265 return 22/* EINVAL*/;
1266 *memptr = emmalloc_memalign(alignment, size);
1267 return *memptr ? 0 : 12/*ENOMEM*/;
1268}
1269
1270int EMMALLOC_EXPORT posix_memalign(void **memptr, size_t alignment, size_t size)
1271{
1272 return emmalloc_posix_memalign(memptr, alignment, size);
1273}
1274
1275static
1276void *emmalloc_calloc(size_t num, size_t size)
1277{
1278 size_t bytes = num*size;
1279 void *ptr = emmalloc_memalign(MALLOC_ALIGNMENT, bytes);
1280 if (ptr)
1281 memset(ptr, 0, bytes);
1282 return ptr;
1283}
1284
1285void * EMMALLOC_EXPORT calloc(size_t num, size_t size)
1286{
1287 return emmalloc_calloc(num, size);
1288}
1289
1290#if 0
1291static int count_linked_list_size(Region *list)
1292{
1293 int size = 1;
1294 for(Region *i = list->next; i != list; list = list->next)
1295 ++size;
1296 return size;
1297}
1298
1299static size_t count_linked_list_space(Region *list)
1300{
1301 size_t space = 0;
1302 for(Region *i = list->next; i != list; list = list->next)
1303 space += region_payload_end_ptr(i) - region_payload_start_ptr(i);
1304 return space;
1305}
1306
1307struct mallinfo emmalloc_mallinfo()
1308{
1309 MALLOC_ACQUIRE();
1310
1311 struct mallinfo info;
1312 // Non-mmapped space allocated (bytes): For emmalloc,
1313 // let's define this as the difference between heap size and dynamic top end.
1314 info.arena = emscripten_get_heap_size() - (size_t)sbrk(0);
1315 // Number of "ordinary" blocks. Let's define this as the number of highest
1316 // size blocks. (subtract one from each, since there is a sentinel node in each list)
1317 info.ordblks = count_linked_list_size(&freeRegionBuckets[NUM_FREE_BUCKETS-1])-1;
1318 // Number of free "fastbin" blocks. For emmalloc, define this as the number
1319 // of blocks that are not in the largest pristine block.
1320 info.smblks = 0;
1321 // The total number of bytes in free "fastbin" blocks.
1322 info.fsmblks = 0;
1323 for(int i = 0; i < NUM_FREE_BUCKETS-1; ++i)
1324 {
1325 info.smblks += count_linked_list_size(&freeRegionBuckets[i])-1;
1326 info.fsmblks += count_linked_list_space(&freeRegionBuckets[i]);
1327 }
1328
1329 info.hblks = 0; // Number of mmapped regions: always 0. (no mmap support)
1330 info.hblkhd = 0; // Amount of bytes in mmapped regions: always 0. (no mmap support)
1331
1332 // Walk through all the heap blocks to report the following data:
1333 // The "highwater mark" for allocated space—that is, the maximum amount of
1334 // space that was ever allocated. Emmalloc does not want to pay code to
1335 // track this, so this is only reported from current allocation data, and
1336 // may not be accurate.
1337 info.usmblks = 0;
1338 info.uordblks = 0; // The total number of bytes used by in-use allocations.
1339 info.fordblks = 0; // The total number of bytes in free blocks.
1340 // The total amount of releasable free space at the top of the heap.
1341 // This is the maximum number of bytes that could ideally be released by malloc_trim(3).
1342 Region *lastActualRegion = prev_region((Region*)(listOfAllRegions->endPtr - sizeof(Region)));
1343 info.keepcost = region_is_free(lastActualRegion) ? lastActualRegion->size : 0;
1344
1345 RootRegion *root = listOfAllRegions;
1346 while(root)
1347 {
1348 Region *r = (Region*)root;
1349 assert(debug_region_is_consistent(r));
1350 uint8_t *lastRegionEnd = root->endPtr;
1351 while((uint8_t*)r < lastRegionEnd)
1352 {
1353 assert(debug_region_is_consistent(r));
1354
1355 if (region_is_free(r))
1356 {
1357 // Count only the payload of the free block towards free memory.
1358 info.fordblks += region_payload_end_ptr(r) - region_payload_start_ptr(r);
1359 // But the header data of the free block goes towards used memory.
1360 info.uordblks += REGION_HEADER_SIZE;
1361 }
1362 else
1363 {
1364 info.uordblks += r->size;
1365 }
1366 // Update approximate watermark data
1367 info.usmblks = MAX(info.usmblks, (intptr_t)r + r->size);
1368
1369 if (r->size == 0)
1370 break;
1371 r = next_region(r);
1372 }
1373 root = root->next;
1374 }
1375
1376 MALLOC_RELEASE();
1377 return info;
1378}
1379
1380struct mallinfo EMMALLOC_EXPORT mallinfo()
1381{
1382 return emmalloc_mallinfo();
1383}
1384
1385// Note! This function is not fully multithreadin safe: while this function is running, other threads should not be
1386// allowed to call sbrk()!
1387static int trim_dynamic_heap_reservation(size_t pad)
1388{
1389 ASSERT_MALLOC_IS_ACQUIRED();
1390
1391 if (!listOfAllRegions)
1392 return 0; // emmalloc is not controlling any dynamic memory at all - cannot release memory.
1393 uint8_t *previousSbrkEndAddress = listOfAllRegions->endPtr;
1394 assert(sbrk(0) == previousSbrkEndAddress);
1395 size_t lastMemoryRegionSize = ((size_t*)previousSbrkEndAddress)[-1];
1396 assert(lastMemoryRegionSize == 16); // // The last memory region should be a sentinel node of exactly 16 bytes in size.
1397 Region *endSentinelRegion = (Region*)(previousSbrkEndAddress - sizeof(Region));
1398 Region *lastActualRegion = prev_region(endSentinelRegion);
1399
1400 // Round padding up to multiple of 4 bytes to keep sbrk() and memory region alignment intact.
1401 // Also have at least 8 bytes of payload so that we can form a full free region.
1402 size_t newRegionSize = (size_t)ALIGN_UP(pad, 4);
1403 if (pad > 0)
1404 newRegionSize += sizeof(Region) - (newRegionSize - pad);
1405
1406 if (!region_is_free(lastActualRegion) || lastActualRegion->size <= newRegionSize)
1407 return 0; // Last actual region is in use, or caller desired to leave more free memory intact than there is.
1408
1409 // This many bytes will be shrunk away.
1410 size_t shrinkAmount = lastActualRegion->size - newRegionSize;
1411 assert(HAS_ALIGNMENT(shrinkAmount, 4));
1412
1413 unlink_from_free_list(lastActualRegion);
1414 // If pad == 0, we should delete the last free region altogether. If pad > 0,
1415 // shrink the last free region to the desired size.
1416 if (newRegionSize > 0)
1417 {
1418 create_free_region(lastActualRegion, newRegionSize);
1419 link_to_free_list(lastActualRegion);
1420 }
1421
1422 // Recreate the sentinel region at the end of the last free region
1423 endSentinelRegion = (Region*)((uint8_t*)lastActualRegion + newRegionSize);
1424 create_used_region(endSentinelRegion, sizeof(Region));
1425
1426 // And update the size field of the whole region block.
1427 listOfAllRegions->endPtr = (uint8_t*)endSentinelRegion + sizeof(Region);
1428
1429 // Finally call sbrk() to shrink the memory area.
1430 void *oldSbrk = sbrk(-(intptr_t)shrinkAmount);
1431 assert((intptr_t)oldSbrk != -1); // Shrinking with sbrk() should never fail.
1432 assert(oldSbrk == previousSbrkEndAddress); // Another thread should not have raced to increase sbrk() on us!
1433
1434 // All successful, and we actually trimmed memory!
1435 return 1;
1436}
1437
1438int emmalloc_trim(size_t pad)
1439{
1440 MALLOC_ACQUIRE();
1441 int success = trim_dynamic_heap_reservation(pad);
1442 MALLOC_RELEASE();
1443 return success;
1444}
1445
1446int EMMALLOC_EXPORT malloc_trim(size_t pad)
1447{
1448 return emmalloc_trim(pad);
1449}
1450
1451size_t emmalloc_dynamic_heap_size()
1452{
1453 size_t dynamicHeapSize = 0;
1454
1455 MALLOC_ACQUIRE();
1456 RootRegion *root = listOfAllRegions;
1457 while(root)
1458 {
1459 dynamicHeapSize += root->endPtr - (uint8_t*)root;
1460 root = root->next;
1461 }
1462 MALLOC_RELEASE();
1463 return dynamicHeapSize;
1464}
1465
1466size_t emmalloc_free_dynamic_memory()
1467{
1468 size_t freeDynamicMemory = 0;
1469
1470 int bucketIndex = 0;
1471
1472 MALLOC_ACQUIRE();
1473 BUCKET_BITMASK_T bucketMask = freeRegionBucketsUsed;
1474
1475 // Loop through each bucket that has free regions in it, based on bits set in freeRegionBucketsUsed bitmap.
1476 while(bucketMask)
1477 {
1478 BUCKET_BITMASK_T indexAdd = __builtin_ctzll(bucketMask);
1479 bucketIndex += indexAdd;
1480 bucketMask >>= indexAdd;
1481 for(Region *freeRegion = freeRegionBuckets[bucketIndex].next;
1482 freeRegion != &freeRegionBuckets[bucketIndex];
1483 freeRegion = freeRegion->next)
1484 {
1485 freeDynamicMemory += freeRegion->size - REGION_HEADER_SIZE;
1486 }
1487 ++bucketIndex;
1488 bucketMask >>= 1;
1489 }
1490 MALLOC_RELEASE();
1491 return freeDynamicMemory;
1492}
1493
1494size_t emmalloc_compute_free_dynamic_memory_fragmentation_map(size_t freeMemorySizeMap[32])
1495{
1496 memset((void*)freeMemorySizeMap, 0, sizeof(freeMemorySizeMap[0])*32);
1497
1498 size_t numFreeMemoryRegions = 0;
1499 int bucketIndex = 0;
1500 MALLOC_ACQUIRE();
1501 BUCKET_BITMASK_T bucketMask = freeRegionBucketsUsed;
1502
1503 // Loop through each bucket that has free regions in it, based on bits set in freeRegionBucketsUsed bitmap.
1504 while(bucketMask)
1505 {
1506 BUCKET_BITMASK_T indexAdd = __builtin_ctzll(bucketMask);
1507 bucketIndex += indexAdd;
1508 bucketMask >>= indexAdd;
1509 for(Region *freeRegion = freeRegionBuckets[bucketIndex].next;
1510 freeRegion != &freeRegionBuckets[bucketIndex];
1511 freeRegion = freeRegion->next)
1512 {
1513 ++numFreeMemoryRegions;
1514 size_t freeDynamicMemory = freeRegion->size - REGION_HEADER_SIZE;
1515 if (freeDynamicMemory > 0)
1516 ++freeMemorySizeMap[31-__builtin_clz(freeDynamicMemory)];
1517 else
1518 ++freeMemorySizeMap[0];
1519 }
1520 ++bucketIndex;
1521 bucketMask >>= 1;
1522 }
1523 MALLOC_RELEASE();
1524 return numFreeMemoryRegions;
1525}
1526
1527size_t emmalloc_unclaimed_heap_memory(void) {
1528 return emscripten_get_heap_max() - (size_t)sbrk(0);
1529}
1530#endif
1531
1532// Define these to satisfy musl references.
1533void *__libc_malloc(size_t) __attribute__((alias("malloc")));
1534void __libc_free(void *) __attribute__((alias("free")));
1535void *__libc_calloc(size_t nmemb, size_t size) __attribute__((alias("calloc")));
lib/libc/wasi/libc-bottom-half/cloudlibc/src/common/errno.h deleted-22
...@@ -1,22 +0,0 @@
1// Copyright (c) 2015-2016 Nuxi, https://nuxi.nl/
2//
3// SPDX-License-Identifier: BSD-2-Clause
4
5#ifndef COMMON_ERRNO_H
6#define COMMON_ERRNO_H
7
8#include <wasi/api.h>
9
10// WASI syscalls should just return ENOTDIR if that's what the problem is.
11static inline __wasi_errno_t errno_fixup_directory(__wasi_fd_t fd,
12 __wasi_errno_t error) {
13 return error;
14}
15
16// WASI syscalls should just return ENOTSOCK if that's what the problem is.
17static inline __wasi_errno_t errno_fixup_socket(__wasi_fd_t fd,
18 __wasi_errno_t error) {
19 return error;
20}
21
22#endif
lib/libc/wasi/libc-bottom-half/cloudlibc/src/common/overflow.h deleted-15
...@@ -1,15 +0,0 @@
1// Copyright (c) 2015-2016 Nuxi, https://nuxi.nl/
2//
3// SPDX-License-Identifier: BSD-2-Clause
4
5#ifndef COMMON_OVERFLOW_H
6#define COMMON_OVERFLOW_H
7
8// Performs an addition, subtraction or multiplication operation,
9// returning whether the computation caused an overflow. These
10// intrinsics are available as of Clang 3.8 and GCC 5.
11#define add_overflow(x, y, out) __builtin_add_overflow(x, y, out)
12#define sub_overflow(x, y, out) __builtin_sub_overflow(x, y, out)
13#define mul_overflow(x, y, out) __builtin_mul_overflow(x, y, out)
14
15#endif
lib/libc/wasi/libc-bottom-half/cloudlibc/src/common/time.h+4-42
...@@ -6,7 +6,6 @@...@@ -6,7 +6,6 @@
6#define COMMON_TIME_H6#define COMMON_TIME_H
77
8#include <common/limits.h>8#include <common/limits.h>
9#include <common/overflow.h>
109
11#include <sys/time.h>10#include <sys/time.h>
1211
...@@ -16,43 +15,6 @@...@@ -16,43 +15,6 @@
1615
17#define NSEC_PER_SEC 100000000016#define NSEC_PER_SEC 1000000000
1817
19// Timezone agnostic conversion routines.
20int __localtime_utc(time_t, struct tm *);
21void __mktime_utc(const struct tm *, struct timespec *);
22
23static inline bool is_leap(time_t year) {
24 year %= 400;
25 if (year < 0)
26 year += 400;
27 return ((year % 4) == 0 && (year % 100) != 0) || year == 100;
28}
29
30// Gets the length of the months in a year.
31static inline const char *get_months(time_t year) {
32 static const char leap[12] = {
33 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31,
34 };
35 static const char common[12] = {
36 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31,
37 };
38 return is_leap(year) ? leap : common;
39}
40
41// Gets the cumulative length of the months in a year.
42static inline const short *get_months_cumulative(time_t year) {
43 static const short leap[13] = {
44 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366,
45 };
46 static const short common[13] = {
47 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365,
48 };
49 return is_leap(year) ? leap : common;
50}
51
52static inline short get_ydays(time_t year) {
53 return is_leap(year) ? 366 : 365;
54}
55
56static inline bool timespec_to_timestamp_exact(18static inline bool timespec_to_timestamp_exact(
57 const struct timespec *timespec, __wasi_timestamp_t *timestamp) {19 const struct timespec *timespec, __wasi_timestamp_t *timestamp) {
58 // Invalid nanoseconds field.20 // Invalid nanoseconds field.
...@@ -64,8 +26,8 @@ static inline bool timespec_to_timestamp_exact(...@@ -64,8 +26,8 @@ static inline bool timespec_to_timestamp_exact(
64 return false;26 return false;
6527
66 // Make sure our timestamp does not overflow.28 // Make sure our timestamp does not overflow.
67 return !mul_overflow(timespec->tv_sec, NSEC_PER_SEC, timestamp) &&29 return !__builtin_mul_overflow(timespec->tv_sec, NSEC_PER_SEC, timestamp) &&
68 !add_overflow(*timestamp, timespec->tv_nsec, timestamp);30 !__builtin_add_overflow(*timestamp, timespec->tv_nsec, timestamp);
69}31}
7032
71static inline bool timespec_to_timestamp_clamp(33static inline bool timespec_to_timestamp_clamp(
...@@ -77,8 +39,8 @@ static inline bool timespec_to_timestamp_clamp(...@@ -77,8 +39,8 @@ static inline bool timespec_to_timestamp_clamp(
77 if (timespec->tv_sec < 0) {39 if (timespec->tv_sec < 0) {
78 // Timestamps before the Epoch are not supported.40 // Timestamps before the Epoch are not supported.
79 *timestamp = 0;41 *timestamp = 0;
80 } else if (mul_overflow(timespec->tv_sec, NSEC_PER_SEC, timestamp) ||42 } else if (__builtin_mul_overflow(timespec->tv_sec, NSEC_PER_SEC, timestamp) ||
81 add_overflow(*timestamp, timespec->tv_nsec, timestamp)) {43 __builtin_add_overflow(*timestamp, timespec->tv_nsec, timestamp)) {
82 // Make sure our timestamp does not overflow.44 // Make sure our timestamp does not overflow.
83 *timestamp = NUMERIC_MAX(__wasi_timestamp_t);45 *timestamp = NUMERIC_MAX(__wasi_timestamp_t);
84 }46 }
lib/libc/wasi/libc-bottom-half/cloudlibc/src/include/_/cdefs.h-113
...@@ -24,126 +24,13 @@...@@ -24,126 +24,13 @@
24#ifndef ___CDEFS_H_24#ifndef ___CDEFS_H_
25#define ___CDEFS_H_25#define ___CDEFS_H_
2626
27// Version information.
28#define __cloudlibc__ 1
29#define __cloudlibc_major__ 0
30#define __cloudlibc_minor__ 102
31
32#ifdef __cplusplus
33#define __BEGIN_DECLS extern "C" {
34#define __END_DECLS }
35#else
36#define __BEGIN_DECLS
37#define __END_DECLS
38#endif
39
40// Whether we should provide inline versions of functions. Due to C++'s
41// support for namespaces, it is generally a bad idea to declare
42// function macros.
43#ifdef __cplusplus
44#define _CLOUDLIBC_INLINE_FUNCTIONS 0
45#else
46#define _CLOUDLIBC_INLINE_FUNCTIONS 1
47#endif
48
49// Compiler-independent annotations.27// Compiler-independent annotations.
5028
51#ifndef __has_builtin
52#define __has_builtin(x) 0
53#endif
54#ifndef __has_extension
55#define __has_extension(x) __has_feature(x)
56#endif
57#ifndef __has_feature
58#define __has_feature(x) 0
59#endif
60
61#define __offsetof(type, member) __builtin_offsetof(type, member)
62#define __containerof(ptr, type, member) \
63 ((type *)((char *)(ptr)-__offsetof(type, member)))
64
65#define __extname(x) __asm__(x)
66#define __malloc_like __attribute__((__malloc__))
67#define __pure2 __attribute__((__const__))
68#define __pure __attribute__((__pure__))
69#define __section(x) __attribute__((__section__(x)))
70#define __unused __attribute__((__unused__))
71#define __used __attribute__((__used__))
72#define __weak_symbol __attribute__((__weak__))
73
74// Format string argument type checking.
75#define __printflike(format, va) \
76 __attribute__((__format__(__printf__, format, va)))
77#define __scanflike(format, va) \
78 __attribute__((__format__(__scanf__, format, va)))
79// TODO(ed): Enable this once supported by LLVM:
80// https://llvm.org/bugs/show_bug.cgi?id=16810
81#define __wprintflike(format, va)
82#define __wscanflike(format, va)
83
84#define __strong_reference(oldsym, newsym) \29#define __strong_reference(oldsym, newsym) \
85 extern __typeof__(oldsym) newsym __attribute__((__alias__(#oldsym)))30 extern __typeof__(oldsym) newsym __attribute__((__alias__(#oldsym)))
8631
87// Convenience macros.32// Convenience macros.
8833
89#define __arraycount(x) (sizeof(x) / sizeof((x)[0]))34#define __arraycount(x) (sizeof(x) / sizeof((x)[0]))
90#define __howmany(x, y) (((x) + (y)-1) / (y))
91#define __rounddown(x, y) (((x) / (y)) * (y))
92#define __roundup(x, y) ((((x) + (y)-1) / (y)) * (y))
93
94// Lock annotations.
95
96#if __has_extension(c_thread_safety_attributes)
97#define __lock_annotate(x) __attribute__((x))
98#else
99#define __lock_annotate(x)
100#endif
101
102#define __lockable __lock_annotate(lockable)
103
104#define __locks_exclusive(...) \
105 __lock_annotate(exclusive_lock_function(__VA_ARGS__))
106#define __locks_shared(...) __lock_annotate(shared_lock_function(__VA_ARGS__))
107
108#define __trylocks_exclusive(...) \
109 __lock_annotate(exclusive_trylock_function(__VA_ARGS__))
110#define __trylocks_shared(...) \
111 __lock_annotate(shared_trylock_function(__VA_ARGS__))
112
113#define __unlocks(...) __lock_annotate(unlock_function(__VA_ARGS__))
114
115#define __asserts_exclusive(...) \
116 __lock_annotate(assert_exclusive_lock(__VA_ARGS__))
117#define __asserts_shared(...) __lock_annotate(assert_shared_lock(__VA_ARGS__))
118
119#define __requires_exclusive(...) \
120 __lock_annotate(exclusive_locks_required(__VA_ARGS__))
121#define __requires_shared(...) \
122 __lock_annotate(shared_locks_required(__VA_ARGS__))
123#define __requires_unlocked(...) __lock_annotate(locks_excluded(__VA_ARGS__))
124
125#define __no_lock_analysis __lock_annotate(no_thread_safety_analysis)
126
127#define __guarded_by(x) __lock_annotate(guarded_by(x))
128#define __pt_guarded_by(x) __lock_annotate(pt_guarded_by(x))
129
130// Const preservation.
131//
132// Functions like strchr() allow you to silently discard a const
133// qualifier from a string. This macro can be used to wrap such
134// functions to propagate the const keyword where possible.
135//
136// This macro has many limitations, such as only being able to detect
137// constness for void, char and wchar_t. For Clang, it also doesn't seem
138// to work on string literals.
139
140#define __preserve_const(type, name, arg, ...) \
141 _Generic(arg, \
142 const void *: (const type *)name(__VA_ARGS__), \
143 const char *: (const type *)name(__VA_ARGS__), \
144 const signed char *: (const type *)name(__VA_ARGS__), \
145 const unsigned char *: (const type *)name(__VA_ARGS__), \
146 const __wchar_t *: (const type *)name(__VA_ARGS__), \
147 default: name(__VA_ARGS__))
14835
149#endif36#endif
lib/libc/wasi/libc-bottom-half/cloudlibc/src/include/stdlib.h deleted-241
...@@ -1,241 +0,0 @@
1// Copyright (c) 2015-2017 Nuxi, https://nuxi.nl/
2//
3// Redistribution and use in source and binary forms, with or without
4// modification, are permitted provided that the following conditions
5// are met:
6// 1. Redistributions of source code must retain the above copyright
7// notice, this list of conditions and the following disclaimer.
8// 2. Redistributions in binary form must reproduce the above copyright
9// notice, this list of conditions and the following disclaimer in the
10// documentation and/or other materials provided with the distribution.
11//
12// THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
13// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
14// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
15// ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
16// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
17// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
18// OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
19// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
20// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
21// OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
22// SUCH DAMAGE.
23
24// <stdlib.h> - standard library definitions
25//
26// Extensions:
27// - MB_CUR_MAX_L(), mblen_l(), mbstowcs_l(), mbtowc_l(), wcstombs_l()
28// and wctomb_l():
29// Regular functions always use the C locale. Available on many other
30// operating systems.
31// - alloca():
32// Present on most other operating systems.
33// - arc4random(), arc4random_buf() and arc4random_uniform():
34// Secure random number generator. Available on many other operating
35// systems.
36// - l64a_r():
37// Thread-safe replacement for l64a(). Part of the SVID, 4th edition.
38// - qsort_r():
39// Available on many other operating systems, although the prototype
40// is not consistent. This implementation is compatible with glibc.
41// It is expected that this version will be standardized in the future.
42// - reallocarray():
43// Allows for reallocation of buffers without integer overflows.
44//
45// Features missing:
46// - initstate(), lcong48(), seed48(), setstate(), srand(), srand48()
47// and srandom():
48// Randomizer is seeded securely by default. There is no need to seed
49// manually.
50// - WEXITSTATUS(), WIFEXITED(), WIFSIGNALED(), WIFSTOPPED(), WNOHANG,
51// WSTOPSIG(), WTERMSIG(), WUNTRACED:
52// Only useful if system() would actually work.
53// - l64a():
54// Not thread-safe. Use l64a_r() instead.
55// - putenv(), setenv() and unsetenv():
56// Environment variables are not available.
57// - grantpt(), posix_openpt(), ptsname() and unlockpt():
58// Pseudo-terminals are not available.
59// - mkdtemp(), mkstemp() and realpath():
60// Requires global filesystem namespace.
61// - setkey():
62// Password database and encryption schemes not available.
63// - system():
64// Requires a command shell.
65
66#ifndef _STDLIB_H_
67#define _STDLIB_H_
68
69#include <_/limits.h>
70#include <_/types.h>
71
72__BEGIN_DECLS
73_Noreturn void _Exit(int);
74_Noreturn void abort(void);
75void *calloc(size_t, size_t);
76_Noreturn void exit(int);
77void free(void *);
78void *malloc(size_t);
79void qsort(void *, size_t, size_t, int (*)(const void *, const void *));
80void *realloc(void *, size_t);
81__END_DECLS
82
83#if _CLOUDLIBC_INLINE_FUNCTIONS
84
85// qsort_r() implementation from Bentley and McIlroy's
86// "Engineering a Sort Function".
87//
88// This sorting function is inlined into this header, so that the
89// compiler can create an optimized version that takes the alignment and
90// size of the elements into account. It also reduces the overhead of
91// indirect function calls.
92
93static __inline void __qsort_r(void *, size_t, size_t,
94 int (*)(const void *, const void *, void *),
95 void *);
96
97static __inline size_t __qsort_min(size_t __a, size_t __b) {
98 return __a < __b ? __a : __b;
99}
100
101// Swaps the contents of two buffers.
102static __inline void __qsort_swap(char *__a, char *__b, size_t __n) {
103 char __t;
104
105 while (__n-- > 0) {
106 __t = *__a;
107 *__a++ = *__b;
108 *__b++ = __t;
109 }
110}
111
112// Implementation of insertionsort for small lists.
113static __inline void __qsort_insertionsort(
114 char *__a, size_t __nel, size_t __width,
115 int (*__cmp)(const void *, const void *, void *), void *__thunk) {
116 char *__pm, *__pl;
117
118 for (__pm = __a + __width; __pm < __a + __nel * __width; __pm += __width)
119 for (__pl = __pm; __pl > __a && __cmp(__pl - __width, __pl, __thunk) > 0;
120 __pl -= __width)
121 __qsort_swap(__pl, __pl - __width, __width);
122}
123
124// Returns the median of three elements.
125static __inline char *__qsort_med3(char *__a, char *__b, char *__c,
126 int (*__cmp)(const void *, const void *,
127 void *),
128 void *__thunk) {
129 return __cmp(__a, __b, __thunk) < 0
130 ? (__cmp(__b, __c, __thunk) < 0
131 ? __b
132 : __cmp(__a, __c, __thunk) < 0 ? __c : __a)
133 : (__cmp(__b, __c, __thunk) > 0
134 ? __b
135 : __cmp(__a, __c, __thunk) > 0 ? __c : __a);
136}
137
138// Picks a pivot based on a pseudo-median of three or nine.
139// TODO(ed): Does this still guarantee an O(n log n) running time?
140static __inline char *__qsort_pickpivot(char *__a, size_t __nel, size_t __width,
141 int (*__cmp)(const void *, const void *,
142 void *),
143 void *__thunk) {
144 char *__pl, *__pm, *__pn;
145 size_t __s;
146
147 __pl = __a;
148 __pm = __a + (__nel / 2) * __width;
149 __pn = __a + (__nel - 1) * __width;
150 if (__nel > 40) {
151 __s = (__nel / 8) * __width;
152 __pl = __qsort_med3(__pl, __pl + __s, __pl + 2 * __s, __cmp, __thunk);
153 __pm = __qsort_med3(__pm - __s, __pm, __pm + __s, __cmp, __thunk);
154 __pn = __qsort_med3(__pn - 2 * __s, __pn - __s, __pn, __cmp, __thunk);
155 }
156 return __qsort_med3(__pl, __pm, __pn, __cmp, __thunk);
157}
158
159// Implementation of quicksort for larger lists.
160static __inline void __qsort_quicksort(char *__a, size_t __nel, size_t __width,
161 int (*__cmp)(const void *, const void *,
162 void *),
163 void *__thunk) {
164 char *__pa, *__pb, *__pc, *__pd, *__pn;
165 int __r;
166 size_t __s;
167
168 // Select pivot and move it to the head of the list.
169 __qsort_swap(__a, __qsort_pickpivot(__a, __nel, __width, __cmp, __thunk),
170 __width);
171
172 // Perform partitioning.
173 __pa = __pb = __a;
174 __pc = __pd = __a + (__nel - 1) * __width;
175 for (;;) {
176 while (__pb <= __pc && (__r = __cmp(__pb, __a, __thunk)) <= 0) {
177 if (__r == 0) {
178 __qsort_swap(__pa, __pb, __width);
179 __pa += __width;
180 }
181 __pb += __width;
182 }
183 while (__pc >= __pb && (__r = __cmp(__pc, __a, __thunk)) >= 0) {
184 if (__r == 0) {
185 __qsort_swap(__pc, __pd, __width);
186 __pd -= __width;
187 }
188 __pc -= __width;
189 }
190 if (__pb > __pc)
191 break;
192 __qsort_swap(__pb, __pc, __width);
193 __pb += __width;
194 __pc -= __width;
195 }
196
197 // Store pivot between the two partitions.
198 __pn = __a + __nel * __width;
199 __s = __qsort_min((size_t)(__pa - __a), (size_t)(__pb - __pa));
200 __qsort_swap(__a, __pb - __s, __s);
201 __s = __qsort_min((size_t)(__pd - __pc), (size_t)(__pn - __pd) - __width);
202 __qsort_swap(__pb, __pn - __s, __s);
203
204 // Sort the two partitions.
205 __s = (size_t)(__pb - __pa);
206 __qsort_r(__a, __s / __width, __width, __cmp, __thunk);
207 __s = (size_t)(__pd - __pc);
208 __qsort_r(__pn - __s, __s / __width, __width, __cmp, __thunk);
209}
210
211static __inline void __qsort_r(void *__base, size_t __nel, size_t __width,
212 int (*__cmp)(const void *, const void *, void *),
213 void *__thunk) {
214 char *__a;
215
216 __a = (char *)__base;
217 if (__nel < 8) {
218 __qsort_insertionsort(__a, __nel, __width, __cmp, __thunk);
219 } else {
220 __qsort_quicksort(__a, __nel, __width, __cmp, __thunk);
221 }
222}
223#define qsort_r(base, nel, width, compar, thunk) \
224 __qsort_r(base, nel, width, compar, thunk)
225
226// qsort(): Call into qsort_r(), providing the callback as the thunk.
227// We assume that the optimizer is smart enough to simplify.
228
229static __inline int __qsort_cmp(const void *__a, const void *__b,
230 void *__thunk) {
231 return ((int (*)(const void *, const void *))__thunk)(__a, __b);
232}
233
234static __inline void __qsort(void *__base, size_t __nel, size_t __width,
235 int (*__cmp)(const void *, const void *)) {
236 qsort_r(__base, __nel, __width, __qsort_cmp, (void *)__cmp);
237}
238#define qsort(base, nel, width, compar) __qsort(base, nel, width, compar)
239#endif
240
241#endif
lib/libc/wasi/libc-bottom-half/cloudlibc/src/libc/dirent/fdopendir.c+1-3
...@@ -2,8 +2,6 @@...@@ -2,8 +2,6 @@
2//2//
3// SPDX-License-Identifier: BSD-2-Clause3// SPDX-License-Identifier: BSD-2-Clause
44
5#include <common/errno.h>
6
7#include <wasi/api.h>5#include <wasi/api.h>
8#include <dirent.h>6#include <dirent.h>
9#include <errno.h>7#include <errno.h>
...@@ -31,7 +29,7 @@ DIR *fdopendir(int fd) {...@@ -31,7 +29,7 @@ DIR *fdopendir(int fd) {
31 if (error != 0) {29 if (error != 0) {
32 free(dirp->buffer);30 free(dirp->buffer);
33 free(dirp);31 free(dirp);
34 errno = errno_fixup_directory(fd, error);32 errno = error;
35 return NULL;33 return NULL;
36 }34 }
3735
lib/libc/wasi/libc-bottom-half/cloudlibc/src/libc/fcntl/openat.c+1-3
...@@ -2,8 +2,6 @@...@@ -2,8 +2,6 @@
2//2//
3// SPDX-License-Identifier: BSD-2-Clause3// SPDX-License-Identifier: BSD-2-Clause
44
5#include <common/errno.h>
6
7#include <assert.h>5#include <assert.h>
8#include <wasi/api.h>6#include <wasi/api.h>
9#include <wasi/libc.h>7#include <wasi/libc.h>
...@@ -75,7 +73,7 @@ int __wasilibc_nocwd_openat_nomode(int fd, const char *path, int oflag) {...@@ -75,7 +73,7 @@ int __wasilibc_nocwd_openat_nomode(int fd, const char *path, int oflag) {
75 fs_rights_base, fs_rights_inheriting, fs_flags,73 fs_rights_base, fs_rights_inheriting, fs_flags,
76 &newfd);74 &newfd);
77 if (error != 0) {75 if (error != 0) {
78 errno = errno_fixup_directory(fd, error);76 errno = error;
79 return -1;77 return -1;
80 }78 }
81 return newfd;79 return newfd;
lib/libc/wasi/libc-bottom-half/cloudlibc/src/libc/stdio/renameat.c+1-3
...@@ -2,8 +2,6 @@...@@ -2,8 +2,6 @@
2//2//
3// SPDX-License-Identifier: BSD-2-Clause3// SPDX-License-Identifier: BSD-2-Clause
44
5#include <common/errno.h>
6
7#include <wasi/api.h>5#include <wasi/api.h>
8#include <errno.h>6#include <errno.h>
9#include <stdio.h>7#include <stdio.h>
...@@ -12,7 +10,7 @@...@@ -12,7 +10,7 @@
12int __wasilibc_nocwd_renameat(int oldfd, const char *old, int newfd, const char *new) {10int __wasilibc_nocwd_renameat(int oldfd, const char *old, int newfd, const char *new) {
13 __wasi_errno_t error = __wasi_path_rename(oldfd, old, newfd, new);11 __wasi_errno_t error = __wasi_path_rename(oldfd, old, newfd, new);
14 if (error != 0) {12 if (error != 0) {
15 errno = errno_fixup_directory(oldfd, errno_fixup_directory(newfd, error));13 errno = error;
16 return -1;14 return -1;
17 }15 }
18 return 0;16 return 0;
lib/libc/wasi/libc-bottom-half/cloudlibc/src/libc/stdlib/_Exit.c+1-1
...@@ -3,7 +3,7 @@...@@ -3,7 +3,7 @@
3// SPDX-License-Identifier: BSD-2-Clause3// SPDX-License-Identifier: BSD-2-Clause
44
5#include <wasi/api.h>5#include <wasi/api.h>
6#include <stdlib.h>6#include <_/cdefs.h>
7#include <stdnoreturn.h>7#include <stdnoreturn.h>
8#include <unistd.h>8#include <unistd.h>
99
lib/libc/wasi/libc-bottom-half/cloudlibc/src/libc/sys/socket/recv.c+1-3
...@@ -2,8 +2,6 @@...@@ -2,8 +2,6 @@
2//2//
3// SPDX-License-Identifier: BSD-2-Clause3// SPDX-License-Identifier: BSD-2-Clause
44
5#include <common/errno.h>
6
7#include <sys/socket.h>5#include <sys/socket.h>
86
9#include <assert.h>7#include <assert.h>
...@@ -35,7 +33,7 @@ ssize_t recv(int socket, void *restrict buffer, size_t length, int flags) {...@@ -35,7 +33,7 @@ ssize_t recv(int socket, void *restrict buffer, size_t length, int flags) {
35 &ro_datalen,33 &ro_datalen,
36 &ro_flags);34 &ro_flags);
37 if (error != 0) {35 if (error != 0) {
38 errno = errno_fixup_socket(socket, error);36 errno = error;
39 return -1;37 return -1;
40 }38 }
41 return ro_datalen;39 return ro_datalen;
lib/libc/wasi/libc-bottom-half/cloudlibc/src/libc/sys/socket/send.c+1-3
...@@ -2,8 +2,6 @@...@@ -2,8 +2,6 @@
2//2//
3// SPDX-License-Identifier: BSD-2-Clause3// SPDX-License-Identifier: BSD-2-Clause
44
5#include <common/errno.h>
6
7#include <sys/socket.h>5#include <sys/socket.h>
86
9#include <assert.h>7#include <assert.h>
...@@ -27,7 +25,7 @@ ssize_t send(int socket, const void *buffer, size_t length, int flags) {...@@ -27,7 +25,7 @@ ssize_t send(int socket, const void *buffer, size_t length, int flags) {
27 size_t so_datalen;25 size_t so_datalen;
28 __wasi_errno_t error = __wasi_sock_send(socket, si_data, si_data_len, si_flags, &so_datalen);26 __wasi_errno_t error = __wasi_sock_send(socket, si_data, si_data_len, si_flags, &so_datalen);
29 if (error != 0) {27 if (error != 0) {
30 errno = errno_fixup_socket(socket, error);28 errno = error;
31 return -1;29 return -1;
32 }30 }
33 return so_datalen;31 return so_datalen;
lib/libc/wasi/libc-bottom-half/cloudlibc/src/libc/sys/socket/shutdown.c+1-3
...@@ -2,8 +2,6 @@...@@ -2,8 +2,6 @@
2//2//
3// SPDX-License-Identifier: BSD-2-Clause3// SPDX-License-Identifier: BSD-2-Clause
44
5#include <common/errno.h>
6
7#include <sys/socket.h>5#include <sys/socket.h>
86
9#include <assert.h>7#include <assert.h>
...@@ -22,7 +20,7 @@ int shutdown(int socket, int how) {...@@ -22,7 +20,7 @@ int shutdown(int socket, int how) {
2220
23 __wasi_errno_t error = __wasi_sock_shutdown(socket, how);21 __wasi_errno_t error = __wasi_sock_shutdown(socket, how);
24 if (error != 0) {22 if (error != 0) {
25 errno = errno_fixup_socket(socket, error);23 errno = error;
26 return -1;24 return -1;
27 }25 }
28 return error;26 return error;
lib/libc/wasi/libc-bottom-half/cloudlibc/src/libc/sys/stat/fstatat.c+1-3
...@@ -2,8 +2,6 @@...@@ -2,8 +2,6 @@
2//2//
3// SPDX-License-Identifier: BSD-2-Clause3// SPDX-License-Identifier: BSD-2-Clause
44
5#include <common/errno.h>
6
7#include <sys/stat.h>5#include <sys/stat.h>
86
9#include <wasi/api.h>7#include <wasi/api.h>
...@@ -25,7 +23,7 @@ int __wasilibc_nocwd_fstatat(int fd, const char *restrict path, struct stat *res...@@ -25,7 +23,7 @@ int __wasilibc_nocwd_fstatat(int fd, const char *restrict path, struct stat *res
25 __wasi_errno_t error =23 __wasi_errno_t error =
26 __wasi_path_filestat_get(fd, lookup_flags, path, &internal_stat);24 __wasi_path_filestat_get(fd, lookup_flags, path, &internal_stat);
27 if (error != 0) {25 if (error != 0) {
28 errno = errno_fixup_directory(fd, error);26 errno = error;
29 return -1;27 return -1;
30 }28 }
31 to_public_stat(&internal_stat, buf);29 to_public_stat(&internal_stat, buf);
lib/libc/wasi/libc-bottom-half/cloudlibc/src/libc/sys/stat/mkdirat.c+1-3
...@@ -2,8 +2,6 @@...@@ -2,8 +2,6 @@
2//2//
3// SPDX-License-Identifier: BSD-2-Clause3// SPDX-License-Identifier: BSD-2-Clause
44
5#include <common/errno.h>
6
7#include <sys/stat.h>5#include <sys/stat.h>
86
9#include <wasi/api.h>7#include <wasi/api.h>
...@@ -13,7 +11,7 @@...@@ -13,7 +11,7 @@
13int __wasilibc_nocwd_mkdirat_nomode(int fd, const char *path) {11int __wasilibc_nocwd_mkdirat_nomode(int fd, const char *path) {
14 __wasi_errno_t error = __wasi_path_create_directory(fd, path);12 __wasi_errno_t error = __wasi_path_create_directory(fd, path);
15 if (error != 0) {13 if (error != 0) {
16 errno = errno_fixup_directory(fd, error);14 errno = error;
17 return -1;15 return -1;
18 }16 }
19 return 0;17 return 0;
lib/libc/wasi/libc-bottom-half/cloudlibc/src/libc/sys/stat/utimensat.c+1-3
...@@ -2,8 +2,6 @@...@@ -2,8 +2,6 @@
2//2//
3// SPDX-License-Identifier: BSD-2-Clause3// SPDX-License-Identifier: BSD-2-Clause
44
5#include <common/errno.h>
6
7#include <sys/stat.h>5#include <sys/stat.h>
86
9#include <wasi/api.h>7#include <wasi/api.h>
...@@ -33,7 +31,7 @@ int __wasilibc_nocwd_utimensat(int fd, const char *path, const struct timespec t...@@ -33,7 +31,7 @@ int __wasilibc_nocwd_utimensat(int fd, const char *path, const struct timespec t
33 __wasi_errno_t error =31 __wasi_errno_t error =
34 __wasi_path_filestat_set_times(fd, lookup_flags, path, st_atim, st_mtim, flags);32 __wasi_path_filestat_set_times(fd, lookup_flags, path, st_atim, st_mtim, flags);
35 if (error != 0) {33 if (error != 0) {
36 errno = errno_fixup_directory(fd, error);34 errno = error;
37 return -1;35 return -1;
38 }36 }
39 return 0;37 return 0;
lib/libc/wasi/libc-bottom-half/cloudlibc/src/libc/time/CLOCK_PROCESS_CPUTIME_ID.c deleted-12
...@@ -1,12 +0,0 @@
1// Copyright (c) 2016 Nuxi, https://nuxi.nl/
2//
3// SPDX-License-Identifier: BSD-2-Clause
4
5#include <common/clock.h>
6
7#include <wasi/api.h>
8#include <time.h>
9
10const struct __clockid _CLOCK_PROCESS_CPUTIME_ID = {
11 .id = __WASI_CLOCKID_PROCESS_CPUTIME_ID,
12};
lib/libc/wasi/libc-bottom-half/cloudlibc/src/libc/time/CLOCK_THREAD_CPUTIME_ID.c deleted-12
...@@ -1,12 +0,0 @@
1// Copyright (c) 2016 Nuxi, https://nuxi.nl/
2//
3// SPDX-License-Identifier: BSD-2-Clause
4
5#include <common/clock.h>
6
7#include <wasi/api.h>
8#include <time.h>
9
10const struct __clockid _CLOCK_THREAD_CPUTIME_ID = {
11 .id = __WASI_CLOCKID_THREAD_CPUTIME_ID,
12};
lib/libc/wasi/libc-bottom-half/cloudlibc/src/libc/time/clock_gettime.c+1-1
...@@ -19,4 +19,4 @@ int __clock_gettime(clockid_t clock_id, struct timespec *tp) {...@@ -19,4 +19,4 @@ int __clock_gettime(clockid_t clock_id, struct timespec *tp) {
19 *tp = timestamp_to_timespec(ts);19 *tp = timestamp_to_timespec(ts);
20 return 0;20 return 0;
21}21}
22extern __typeof(__clock_gettime) clock_gettime __attribute__((weak, alias("__clock_gettime")));22weak_alias(__clock_gettime, clock_gettime);
lib/libc/wasi/libc-bottom-half/cloudlibc/src/libc/time/clock_nanosleep.c+2
...@@ -33,3 +33,5 @@ int clock_nanosleep(clockid_t clock_id, int flags, const struct timespec *rqtp,...@@ -33,3 +33,5 @@ int clock_nanosleep(clockid_t clock_id, int flags, const struct timespec *rqtp,
33 __wasi_errno_t error = __wasi_poll_oneoff(&sub, &ev, 1, &nevents);33 __wasi_errno_t error = __wasi_poll_oneoff(&sub, &ev, 1, &nevents);
34 return error == 0 && ev.error == 0 ? 0 : ENOTSUP;34 return error == 0 && ev.error == 0 ? 0 : ENOTSUP;
35}35}
36
37weak_alias(clock_nanosleep, __clock_nanosleep);
lib/libc/wasi/libc-bottom-half/cloudlibc/src/libc/time/nanosleep.c-5
...@@ -3,7 +3,6 @@...@@ -3,7 +3,6 @@
3// SPDX-License-Identifier: BSD-2-Clause3// SPDX-License-Identifier: BSD-2-Clause
44
5#include <errno.h>5#include <errno.h>
6#include <threads.h>
7#include <time.h>6#include <time.h>
87
9int nanosleep(const struct timespec *rqtp, struct timespec *rem) {8int nanosleep(const struct timespec *rqtp, struct timespec *rem) {
...@@ -14,7 +13,3 @@ int nanosleep(const struct timespec *rqtp, struct timespec *rem) {...@@ -14,7 +13,3 @@ int nanosleep(const struct timespec *rqtp, struct timespec *rem) {
14 }13 }
15 return 0;14 return 0;
16}15}
17
18#if defined(_REENTRANT)
19__strong_reference(nanosleep, thrd_sleep);
20#endif
lib/libc/wasi/libc-bottom-half/cloudlibc/src/libc/unistd/faccessat.c+1-3
...@@ -2,8 +2,6 @@...@@ -2,8 +2,6 @@
2//2//
3// SPDX-License-Identifier: BSD-2-Clause3// SPDX-License-Identifier: BSD-2-Clause
44
5#include <common/errno.h>
6
7#include <wasi/api.h>5#include <wasi/api.h>
8#include <errno.h>6#include <errno.h>
9#include <fcntl.h>7#include <fcntl.h>
...@@ -24,7 +22,7 @@ int __wasilibc_nocwd_faccessat(int fd, const char *path, int amode, int flag) {...@@ -24,7 +22,7 @@ int __wasilibc_nocwd_faccessat(int fd, const char *path, int amode, int flag) {
24 __wasi_errno_t error =22 __wasi_errno_t error =
25 __wasi_path_filestat_get(fd, lookup_flags, path, &file);23 __wasi_path_filestat_get(fd, lookup_flags, path, &file);
26 if (error != 0) {24 if (error != 0) {
27 errno = errno_fixup_directory(fd, error);25 errno = error;
28 return -1;26 return -1;
29 }27 }
3028
lib/libc/wasi/libc-bottom-half/cloudlibc/src/libc/unistd/linkat.c+1-3
...@@ -2,8 +2,6 @@...@@ -2,8 +2,6 @@
2//2//
3// SPDX-License-Identifier: BSD-2-Clause3// SPDX-License-Identifier: BSD-2-Clause
44
5#include <common/errno.h>
6
7#include <wasi/api.h>5#include <wasi/api.h>
8#include <errno.h>6#include <errno.h>
9#include <fcntl.h>7#include <fcntl.h>
...@@ -19,7 +17,7 @@ int __wasilibc_nocwd_linkat(int fd1, const char *path1, int fd2, const char *pat...@@ -19,7 +17,7 @@ int __wasilibc_nocwd_linkat(int fd1, const char *path1, int fd2, const char *pat
19 // Perform system call.17 // Perform system call.
20 __wasi_errno_t error = __wasi_path_link(fd1, lookup1_flags, path1, fd2, path2);18 __wasi_errno_t error = __wasi_path_link(fd1, lookup1_flags, path1, fd2, path2);
21 if (error != 0) {19 if (error != 0) {
22 errno = errno_fixup_directory(fd1, errno_fixup_directory(fd2, error));20 errno = error;
23 return -1;21 return -1;
24 }22 }
25 return 0;23 return 0;
lib/libc/wasi/libc-bottom-half/cloudlibc/src/libc/unistd/lseek.c+1-1
...@@ -22,4 +22,4 @@ off_t __lseek(int fildes, off_t offset, int whence) {...@@ -22,4 +22,4 @@ off_t __lseek(int fildes, off_t offset, int whence) {
22 return new_offset;22 return new_offset;
23}23}
2424
25extern __typeof(__lseek) lseek __attribute__((weak, alias("__lseek")));25weak_alias(__lseek, lseek);
lib/libc/wasi/libc-bottom-half/cloudlibc/src/libc/unistd/readlinkat.c+1-3
...@@ -2,8 +2,6 @@...@@ -2,8 +2,6 @@
2//2//
3// SPDX-License-Identifier: BSD-2-Clause3// SPDX-License-Identifier: BSD-2-Clause
44
5#include <common/errno.h>
6
7#include <wasi/api.h>5#include <wasi/api.h>
8#include <errno.h>6#include <errno.h>
9#include <string.h>7#include <string.h>
...@@ -16,7 +14,7 @@ ssize_t __wasilibc_nocwd_readlinkat(int fd, const char *restrict path, char *res...@@ -16,7 +14,7 @@ ssize_t __wasilibc_nocwd_readlinkat(int fd, const char *restrict path, char *res
16 __wasi_errno_t error = __wasi_path_readlink(fd, path,14 __wasi_errno_t error = __wasi_path_readlink(fd, path,
17 (uint8_t*)buf, bufsize, &bufused);15 (uint8_t*)buf, bufsize, &bufused);
18 if (error != 0) {16 if (error != 0) {
19 errno = errno_fixup_directory(fd, error);17 errno = error;
20 return -1;18 return -1;
21 }19 }
22 return bufused;20 return bufused;
lib/libc/wasi/libc-bottom-half/cloudlibc/src/libc/unistd/symlinkat.c+1-3
...@@ -2,8 +2,6 @@...@@ -2,8 +2,6 @@
2//2//
3// SPDX-License-Identifier: BSD-2-Clause3// SPDX-License-Identifier: BSD-2-Clause
44
5#include <common/errno.h>
6
7#include <wasi/api.h>5#include <wasi/api.h>
8#include <errno.h>6#include <errno.h>
9#include <string.h>7#include <string.h>
...@@ -12,7 +10,7 @@...@@ -12,7 +10,7 @@
12int __wasilibc_nocwd_symlinkat(const char *path1, int fd, const char *path2) {10int __wasilibc_nocwd_symlinkat(const char *path1, int fd, const char *path2) {
13 __wasi_errno_t error = __wasi_path_symlink(path1, fd, path2);11 __wasi_errno_t error = __wasi_path_symlink(path1, fd, path2);
14 if (error != 0) {12 if (error != 0) {
15 errno = errno_fixup_directory(fd, error);13 errno = error;
16 return -1;14 return -1;
17 }15 }
18 return 0;16 return 0;
lib/libc/wasi/libc-bottom-half/cloudlibc/src/libc/unistd/unlinkat.c-2
...@@ -2,8 +2,6 @@...@@ -2,8 +2,6 @@
2//2//
3// SPDX-License-Identifier: BSD-2-Clause3// SPDX-License-Identifier: BSD-2-Clause
44
5#include <common/errno.h>
6
7#include <wasi/api.h>5#include <wasi/api.h>
8#include <wasi/libc.h>6#include <wasi/libc.h>
9#include <errno.h>7#include <errno.h>
lib/libc/wasi/libc-bottom-half/crt/crt1-command.c+43-8
...@@ -1,18 +1,53 @@...@@ -1,18 +1,53 @@
1#ifdef _REENTRANT
2#include <stdatomic.h>
3extern void __wasi_init_tp(void);
4#endif
1#include <wasi/api.h>5#include <wasi/api.h>
2#include <stdlib.h>
3extern void __wasm_call_ctors(void);6extern void __wasm_call_ctors(void);
4extern int __original_main(void);7extern int __main_void(void);
5extern void __wasm_call_dtors(void);8extern void __wasm_call_dtors(void);
69
7__attribute__((export_name("_start")))10__attribute__((export_name("_start")))
8void _start(void) {11void _start(void) {
9 // Call `__original_main` which will either be the application's zero-argument12 // Commands should only be called once per instance. This simple check
10 // `__original_main` function or a libc routine which calls `__main_void`.13 // ensures that the `_start` function isn't started more than once.
11 // TODO: Call `main` directly once we no longer have to support old compilers.14 //
12 int r = __original_main();15 // We use `volatile` here to prevent the store to `started` from being
16 // sunk past any subsequent code, and to prevent any compiler from
17 // optimizing based on the knowledge that `_start` is the program
18 // entrypoint.
19#ifdef _REENTRANT
20 static volatile _Atomic int started = 0;
21 int expected = 0;
22 if (!atomic_compare_exchange_strong(&started, &expected, 1)) {
23 __builtin_trap();
24 }
25#else
26 static volatile int started = 0;
27 if (started != 0) {
28 __builtin_trap();
29 }
30 started = 1;
31#endif
32
33#ifdef _REENTRANT
34 __wasi_init_tp();
35#endif
36
37 // The linker synthesizes this to call constructors.
38 __wasm_call_ctors();
39
40 // Call `__main_void` which will either be the application's zero-argument
41 // `__main_void` function or a libc routine which obtains the command-line
42 // arguments and calls `__main_argv_argc`.
43 int r = __main_void();
44
45 // Call atexit functions, destructors, stdio cleanup, etc.
46 __wasm_call_dtors();
1347
14 // If main exited successfully, just return, otherwise call `exit`.48 // If main exited successfully, just return, otherwise call
49 // `__wasi_proc_exit`.
15 if (r != 0) {50 if (r != 0) {
16 exit(r);51 __wasi_proc_exit(r);
17 }52 }
18}53}
lib/libc/wasi/libc-bottom-half/headers/private/stdlib.h+2
...@@ -4,3 +4,5 @@...@@ -4,3 +4,5 @@
4#include <stddef.h>4#include <stddef.h>
55
6#include_next <stdlib.h>6#include_next <stdlib.h>
7
8int clearenv(void);
lib/libc/wasi/libc-bottom-half/signal/signal.c+3-3
...@@ -24,7 +24,7 @@ void __SIG_ERR(int sig) {...@@ -24,7 +24,7 @@ void __SIG_ERR(int sig) {
2424
25_Noreturn25_Noreturn
26static void core_handler(int sig) {26static void core_handler(int sig) {
27 fprintf(stderr, "Program recieved fatal signal: %s\n", strsignal(sig));27 fprintf(stderr, "Program received fatal signal: %s\n", strsignal(sig));
28 abort();28 abort();
29}29}
3030
...@@ -138,5 +138,5 @@ void (*signal(int sig, void (*func)(int)))(int) {...@@ -138,5 +138,5 @@ void (*signal(int sig, void (*func)(int)))(int) {
138 return old;138 return old;
139}139}
140140
141extern __typeof(signal) bsd_signal __attribute__((weak, alias("signal")));141extern __typeof(signal) bsd_signal __attribute__((__weak__, alias("signal")));
142extern __typeof(signal) __sysv_signal __attribute__((weak, alias("signal")));142extern __typeof(signal) __sysv_signal __attribute__((__weak__, alias("signal")));
lib/libc/wasi/libc-bottom-half/sources/__main_argc_argv.c deleted-10
...@@ -1,10 +0,0 @@
1// New compilers define `__main_argc_argv`. If that doesn't exist, we
2// may get called here. Old compilers define `main` expecting an
3// argv/argc, so call that.
4// TODO: Remove this layer when we no longer have to support old compilers.
5int __wasilibc_main(int argc, char *argv[]) asm("main");
6
7__attribute__((weak, nodebug))
8int __main_argc_argv(int argc, char *argv[]) {
9 return __wasilibc_main(argc, argv);
10}
lib/libc/wasi/libc-bottom-half/sources/__main_void.c+7-2
...@@ -2,13 +2,18 @@...@@ -2,13 +2,18 @@
2#include <stdlib.h>2#include <stdlib.h>
3#include <sysexits.h>3#include <sysexits.h>
44
5int __wasilibc_main(int argc, char *argv[]) asm("main");
6
5// The user's `main` function, expecting arguments.7// The user's `main` function, expecting arguments.
6int __main_argc_argv(int argc, char *argv[]);8__attribute__((__weak__, nodebug))
9int __main_argc_argv(int argc, char *argv[]) {
10 return __wasilibc_main(argc, argv);
11}
712
8// If the user's `main` function expects arguments, the compiler will rename13// If the user's `main` function expects arguments, the compiler will rename
9// it to `__main_argc_argv`, and this version will get linked in, which14// it to `__main_argc_argv`, and this version will get linked in, which
10// initializes the argument data and calls `__main_argc_argv`.15// initializes the argument data and calls `__main_argc_argv`.
11__attribute__((weak, nodebug))16__attribute__((__weak__, nodebug))
12int __main_void(void) {17int __main_void(void) {
13 __wasi_errno_t err;18 __wasi_errno_t err;
1419
lib/libc/wasi/libc-bottom-half/sources/__original_main.c deleted-10
...@@ -1,10 +0,0 @@
1// Old compilers define `__original_main`. If that doesn't exist, we
2// get called here. New compilers define `__main_void`. If that doesn't
3// exist, we'll try something else.
4// TODO: Remove this layer when we no longer have to support old compilers.
5int __main_void(void);
6
7__attribute__((weak))
8int __original_main(void) {
9 return __main_void();
10}
lib/libc/wasi/libc-bottom-half/sources/__wasilibc_dt.c created+34
...@@ -0,0 +1,34 @@
1#include <__header_dirent.h>
2#include <__mode_t.h>
3
4int __wasilibc_iftodt(int x) {
5 switch (x) {
6 case S_IFDIR: return DT_DIR;
7 case S_IFCHR: return DT_CHR;
8 case S_IFBLK: return DT_BLK;
9 case S_IFREG: return DT_REG;
10 case S_IFIFO: return DT_FIFO;
11 case S_IFLNK: return DT_LNK;
12#ifdef DT_SOCK
13 case S_IFSOCK: return DT_SOCK;
14#endif
15 default: return DT_UNKNOWN;
16 }
17}
18
19int __wasilibc_dttoif(int x) {
20 switch (x) {
21 case DT_DIR: return S_IFDIR;
22 case DT_CHR: return S_IFCHR;
23 case DT_BLK: return S_IFBLK;
24 case DT_REG: return S_IFREG;
25 case DT_FIFO: return S_IFIFO;
26 case DT_LNK: return S_IFLNK;
27#ifdef DT_SOCK
28 case DT_SOCK: return S_IFSOCK;
29#endif
30 case DT_UNKNOWN:
31 default:
32 return S_IFSOCK;
33 }
34}
lib/libc/wasi/libc-bottom-half/sources/__wasilibc_environ.c created+14
...@@ -0,0 +1,14 @@
1#include <wasi/libc-environ.h>
2
3extern char **__wasilibc_environ;
4
5// See the comments in libc-environ.h.
6char **__wasilibc_get_environ(void) {
7 // Perform lazy initialization if needed.
8 __wasilibc_ensure_environ();
9
10 // Return `environ`. Use the `__wasilibc_`-prefixed name so that we don't
11 // pull in the `environ` symbol directly, which would lead to eager
12 // initialization being done instead.
13 return __wasilibc_environ;
14}
lib/libc/wasi/libc-bottom-half/sources/__wasilibc_initialize_environ.c+17-1
...@@ -11,7 +11,7 @@...@@ -11,7 +11,7 @@
11/// Statically-initialize it to an invalid pointer value so that we can11/// Statically-initialize it to an invalid pointer value so that we can
12/// detect if it's been explicitly initialized (we can't use `NULL` because12/// detect if it's been explicitly initialized (we can't use `NULL` because
13/// `clearenv` sets it to NULL.13/// `clearenv` sets it to NULL.
14char **__wasilibc_environ __attribute__((weak)) = (char **)-1;14weak char **__wasilibc_environ = (char **)-1;
1515
16// See the comments in libc-environ.h.16// See the comments in libc-environ.h.
17void __wasilibc_ensure_environ(void) {17void __wasilibc_ensure_environ(void) {
...@@ -75,3 +75,19 @@ oserr:...@@ -75,3 +75,19 @@ oserr:
75software:75software:
76 _Exit(EX_SOFTWARE);76 _Exit(EX_SOFTWARE);
77}77}
78
79// See the comments in libc-environ.h.
80void __wasilibc_deinitialize_environ(void) {
81 if (__wasilibc_environ != (char **)-1) {
82 // Let libc-top-half clear the old environment-variable strings.
83 clearenv();
84 // Set the pointer to the special init value.
85 __wasilibc_environ = (char **)-1;
86 }
87}
88
89// See the comments in libc-environ.h.
90weak void __wasilibc_maybe_reinitialize_environ_eagerly(void) {
91 // This version does nothing. It may be overridden by a version which does
92 // something if `environ` is used.
93}
lib/libc/wasi/libc-bottom-half/sources/__wasilibc_real.c+25
...@@ -599,6 +599,20 @@ __wasi_errno_t __wasi_random_get(...@@ -599,6 +599,20 @@ __wasi_errno_t __wasi_random_get(
599 return (uint16_t) ret;599 return (uint16_t) ret;
600}600}
601601
602int32_t __imported_wasi_snapshot_preview1_sock_accept(int32_t arg0, int32_t arg1, int32_t arg2) __attribute__((
603 __import_module__("wasi_snapshot_preview1"),
604 __import_name__("sock_accept")
605));
606
607__wasi_errno_t __wasi_sock_accept(
608 __wasi_fd_t fd,
609 __wasi_fdflags_t flags,
610 __wasi_fd_t *retptr0
611){
612 int32_t ret = __imported_wasi_snapshot_preview1_sock_accept((int32_t) fd, flags, (int32_t) retptr0);
613 return (uint16_t) ret;
614}
615
602int32_t __imported_wasi_snapshot_preview1_sock_recv(int32_t arg0, int32_t arg1, int32_t arg2, int32_t arg3, int32_t arg4, int32_t arg5) __attribute__((616int32_t __imported_wasi_snapshot_preview1_sock_recv(int32_t arg0, int32_t arg1, int32_t arg2, int32_t arg3, int32_t arg4, int32_t arg5) __attribute__((
603 __import_module__("wasi_snapshot_preview1"),617 __import_module__("wasi_snapshot_preview1"),
604 __import_name__("sock_recv")618 __import_name__("sock_recv")
...@@ -645,3 +659,14 @@ __wasi_errno_t __wasi_sock_shutdown(...@@ -645,3 +659,14 @@ __wasi_errno_t __wasi_sock_shutdown(
645 return (uint16_t) ret;659 return (uint16_t) ret;
646}660}
647661
662#ifdef _REENTRANT
663int32_t __imported_wasi_thread_spawn(int32_t arg0) __attribute__((
664 __import_module__("wasi"),
665 __import_name__("thread_spawn")
666));
667
668__wasi_errno_t __wasi_thread_spawn(void* start_arg) {
669 int32_t ret = __imported_wasi_thread_spawn((int32_t) start_arg);
670 return (uint16_t) ret;
671}
672#endif
lib/libc/wasi/libc-bottom-half/sources/__wasilibc_rmdirat.c+1-2
...@@ -1,4 +1,3 @@...@@ -1,4 +1,3 @@
1#include <common/errno.h>
2#include <wasi/api.h>1#include <wasi/api.h>
3#include <wasi/libc.h>2#include <wasi/libc.h>
4#include <errno.h>3#include <errno.h>
...@@ -6,7 +5,7 @@...@@ -6,7 +5,7 @@
6int __wasilibc_nocwd___wasilibc_rmdirat(int fd, const char *path) {5int __wasilibc_nocwd___wasilibc_rmdirat(int fd, const char *path) {
7 __wasi_errno_t error = __wasi_path_remove_directory(fd, path);6 __wasi_errno_t error = __wasi_path_remove_directory(fd, path);
8 if (error != 0) {7 if (error != 0) {
9 errno = errno_fixup_directory(fd, error);8 errno = error;
10 return -1;9 return -1;
11 }10 }
12 return 0;11 return 0;
lib/libc/wasi/libc-bottom-half/sources/__wasilibc_unlinkat.c-1
...@@ -1,4 +1,3 @@...@@ -1,4 +1,3 @@
1#include <common/errno.h>
2#include <wasi/api.h>1#include <wasi/api.h>
3#include <wasi/libc.h>2#include <wasi/libc.h>
4#include <errno.h>3#include <errno.h>
lib/libc/wasi/libc-bottom-half/sources/chdir.c+27-8
...@@ -9,9 +9,12 @@...@@ -9,9 +9,12 @@
9#include <wasi/libc.h>9#include <wasi/libc.h>
1010
11#ifdef _REENTRANT11#ifdef _REENTRANT
12#error "chdir doesn't yet support multiple threads"12void __wasilibc_cwd_lock(void);
13void __wasilibc_cwd_unlock(void);
14#else
15#define __wasilibc_cwd_lock() (void)0
16#define __wasilibc_cwd_unlock() (void)0
13#endif17#endif
14
15extern char *__wasilibc_cwd;18extern char *__wasilibc_cwd;
16static int __wasilibc_cwd_mallocd = 0;19static int __wasilibc_cwd_mallocd = 0;
1720
...@@ -43,10 +46,10 @@ int chdir(const char *path)...@@ -43,10 +46,10 @@ int chdir(const char *path)
43 //46 //
44 // If `relative_buf` is equal to "." or `abs` is equal to the empty string,47 // If `relative_buf` is equal to "." or `abs` is equal to the empty string,
45 // however, we skip that part and the middle slash.48 // however, we skip that part and the middle slash.
46 size_t len = strlen(abs) + 1;49 size_t abs_len = strlen(abs);
47 int copy_relative = strcmp(relative_buf, ".") != 0;50 int copy_relative = strcmp(relative_buf, ".") != 0;
48 int mid = copy_relative && abs[0] != 0;51 int mid = copy_relative && abs[0] != 0;
49 char *new_cwd = malloc(len + (copy_relative ? strlen(relative_buf) + mid: 0)+1);52 char *new_cwd = malloc(1 + abs_len + mid + (copy_relative ? strlen(relative_buf) : 0) + 1);
50 if (new_cwd == NULL) {53 if (new_cwd == NULL) {
51 errno = ENOMEM;54 errno = ENOMEM;
52 return -1;55 return -1;
...@@ -54,14 +57,16 @@ int chdir(const char *path)...@@ -54,14 +57,16 @@ int chdir(const char *path)
54 new_cwd[0] = '/';57 new_cwd[0] = '/';
55 strcpy(new_cwd + 1, abs);58 strcpy(new_cwd + 1, abs);
56 if (mid)59 if (mid)
57 new_cwd[len] = '/';60 new_cwd[1 + abs_len] = '/';
58 if (copy_relative)61 if (copy_relative)
59 strcpy(new_cwd + 1 + mid + strlen(abs), relative_buf);62 strcpy(new_cwd + 1 + abs_len + mid, relative_buf);
6063
61 // And set our new malloc'd buffer into the global cwd, freeing the64 // And set our new malloc'd buffer into the global cwd, freeing the
62 // previous one if necessary.65 // previous one if necessary.
66 __wasilibc_cwd_lock();
63 char *prev_cwd = __wasilibc_cwd;67 char *prev_cwd = __wasilibc_cwd;
64 __wasilibc_cwd = new_cwd;68 __wasilibc_cwd = new_cwd;
69 __wasilibc_cwd_unlock();
65 if (__wasilibc_cwd_mallocd)70 if (__wasilibc_cwd_mallocd)
66 free(prev_cwd);71 free(prev_cwd);
67 __wasilibc_cwd_mallocd = 1;72 __wasilibc_cwd_mallocd = 1;
...@@ -77,11 +82,13 @@ static const char *make_absolute(const char *path) {...@@ -77,11 +82,13 @@ static const char *make_absolute(const char *path) {
77 return path;82 return path;
78 }83 }
7984
85#ifndef _REENTRANT
80 // If the path is empty, or points to the current directory, then return86 // If the path is empty, or points to the current directory, then return
81 // the current directory.87 // the current directory.
82 if (path[0] == 0 || !strcmp(path, ".") || !strcmp(path, "./")) {88 if (path[0] == 0 || !strcmp(path, ".") || !strcmp(path, "./")) {
83 return __wasilibc_cwd;89 return __wasilibc_cwd;
84 }90 }
91#endif
8592
86 // If the path starts with `./` then we won't be appending that to the cwd.93 // If the path starts with `./` then we won't be appending that to the cwd.
87 if (path[0] == '.' && path[1] == '/')94 if (path[0] == '.' && path[1] == '/')
...@@ -90,18 +97,30 @@ static const char *make_absolute(const char *path) {...@@ -90,18 +97,30 @@ static const char *make_absolute(const char *path) {
90 // Otherwise we'll take the current directory, add a `/`, and then add the97 // Otherwise we'll take the current directory, add a `/`, and then add the
91 // input `path`. Note that this doesn't do any normalization (like removing98 // input `path`. Note that this doesn't do any normalization (like removing
92 // `/./`).99 // `/./`).
100 __wasilibc_cwd_lock();
93 size_t cwd_len = strlen(__wasilibc_cwd);101 size_t cwd_len = strlen(__wasilibc_cwd);
94 size_t path_len = strlen(path);102 size_t path_len = path ? strlen(path) : 0;
103 __wasilibc_cwd_unlock();
95 int need_slash = __wasilibc_cwd[cwd_len - 1] == '/' ? 0 : 1;104 int need_slash = __wasilibc_cwd[cwd_len - 1] == '/' ? 0 : 1;
96 size_t alloc_len = cwd_len + path_len + 1 + need_slash;105 size_t alloc_len = cwd_len + path_len + 1 + need_slash;
97 if (alloc_len > make_absolute_len) {106 if (alloc_len > make_absolute_len) {
98 char *tmp = realloc(make_absolute_buf, alloc_len);107 char *tmp = realloc(make_absolute_buf, alloc_len);
99 if (tmp == NULL)108 if (tmp == NULL) {
109 __wasilibc_cwd_unlock();
100 return NULL;110 return NULL;
111 }
101 make_absolute_buf = tmp;112 make_absolute_buf = tmp;
102 make_absolute_len = alloc_len;113 make_absolute_len = alloc_len;
103 }114 }
104 strcpy(make_absolute_buf, __wasilibc_cwd);115 strcpy(make_absolute_buf, __wasilibc_cwd);
116 __wasilibc_cwd_unlock();
117
118#ifdef _REENTRANT
119 if (path[0] == 0 || !strcmp(path, ".") || !strcmp(path, "./")) {
120 return make_absolute_buf;
121 }
122#endif
123
105 if (need_slash)124 if (need_slash)
106 strcpy(make_absolute_buf + cwd_len, "/");125 strcpy(make_absolute_buf + cwd_len, "/");
107 strcpy(make_absolute_buf + cwd_len + need_slash, path);126 strcpy(make_absolute_buf + cwd_len + need_slash, path);
lib/libc/wasi/libc-bottom-half/sources/environ.c+9-4
...@@ -9,10 +9,8 @@...@@ -9,10 +9,8 @@
9// `__wasilibc_environ`, which is initialized with a constructor function, so9// `__wasilibc_environ`, which is initialized with a constructor function, so
10// that it's initialized whenever user code might want to access it.10// that it's initialized whenever user code might want to access it.
11char **__wasilibc_environ;11char **__wasilibc_environ;
12extern __typeof(__wasilibc_environ) _environ12weak_alias(__wasilibc_environ, _environ);
13 __attribute__((weak, alias("__wasilibc_environ")));13weak_alias(__wasilibc_environ, environ);
14extern __typeof(__wasilibc_environ) environ
15 __attribute__((weak, alias("__wasilibc_environ")));
1614
17// We define this function here in the same source file as15// We define this function here in the same source file as
18// `__wasilibc_environ`, so that this function is called in iff environment16// `__wasilibc_environ`, so that this function is called in iff environment
...@@ -24,3 +22,10 @@ __attribute__((constructor(50)))...@@ -24,3 +22,10 @@ __attribute__((constructor(50)))
24static void __wasilibc_initialize_environ_eagerly(void) {22static void __wasilibc_initialize_environ_eagerly(void) {
25 __wasilibc_initialize_environ();23 __wasilibc_initialize_environ();
26}24}
25
26// See the comments in libc-environ.h.
27void __wasilibc_maybe_reinitialize_environ_eagerly(void) {
28 // This translation unit is linked in if `environ` is used, meaning we need
29 // to eagerly reinitialize the environment variables.
30 __wasilibc_initialize_environ();
31}
lib/libc/wasi/libc-bottom-half/sources/getcwd.c+13-4
...@@ -1,30 +1,39 @@...@@ -1,30 +1,39 @@
1#include <unistd.h>1#include <unistd.h>
2#include <errno.h>2#include <errno.h>
3#include <string.h>3#include <string.h>
4#include "lock.h"
5
6char *__wasilibc_cwd = "/";
47
5// For threads this needs to synchronize with chdir
6#ifdef _REENTRANT8#ifdef _REENTRANT
7#error "getcwd doesn't yet support multiple threads"9static volatile int lock[1];
10void __wasilibc_cwd_lock(void) { LOCK(lock); }
11void __wasilibc_cwd_unlock(void) { UNLOCK(lock); }
12#else
13#define __wasilibc_cwd_lock() (void)0
14#define __wasilibc_cwd_unlock() (void)0
8#endif15#endif
916
10char *__wasilibc_cwd = "/";
11
12char *getcwd(char *buf, size_t size)17char *getcwd(char *buf, size_t size)
13{18{
19 __wasilibc_cwd_lock();
14 if (!buf) {20 if (!buf) {
15 buf = strdup(__wasilibc_cwd);21 buf = strdup(__wasilibc_cwd);
16 if (!buf) {22 if (!buf) {
17 errno = ENOMEM;23 errno = ENOMEM;
24 __wasilibc_cwd_unlock();
18 return NULL;25 return NULL;
19 }26 }
20 } else {27 } else {
21 size_t len = strlen(__wasilibc_cwd);28 size_t len = strlen(__wasilibc_cwd);
22 if (size < len + 1) {29 if (size < len + 1) {
23 errno = ERANGE;30 errno = ERANGE;
31 __wasilibc_cwd_unlock();
24 return NULL;32 return NULL;
25 }33 }
26 strcpy(buf, __wasilibc_cwd);34 strcpy(buf, __wasilibc_cwd);
27 }35 }
36 __wasilibc_cwd_unlock();
28 return buf;37 return buf;
29}38}
3039
lib/libc/wasi/libc-bottom-half/sources/getentropy.c+2-6
...@@ -1,10 +1,6 @@...@@ -1,10 +1,6 @@
1#include <wasi/api.h>
2#include <errno.h>1#include <errno.h>
3#include <unistd.h>2#include <unistd.h>
43#include <wasi/api.h>
5#ifdef _REENTRANT
6#error With threads support, getentropy is not intended to be a cancellation point.
7#endif
84
9int __getentropy(void *buffer, size_t len) {5int __getentropy(void *buffer, size_t len) {
10 if (len > 256) {6 if (len > 256) {
...@@ -21,4 +17,4 @@ int __getentropy(void *buffer, size_t len) {...@@ -21,4 +17,4 @@ int __getentropy(void *buffer, size_t len) {
2117
22 return 0;18 return 0;
23}19}
24extern __typeof(__getentropy) getentropy __attribute__((weak, alias("__getentropy")));20weak_alias(__getentropy, getentropy);
lib/libc/wasi/libc-bottom-half/sources/isatty.c+1-1
...@@ -19,4 +19,4 @@ int __isatty(int fd) {...@@ -19,4 +19,4 @@ int __isatty(int fd) {
1919
20 return 1;20 return 1;
21}21}
22extern __typeof(__isatty) isatty __attribute__((weak, alias("__isatty")));22extern __typeof(__isatty) isatty __attribute__((__weak__, alias("__isatty")));
lib/libc/wasi/libc-bottom-half/sources/preopens.c+23-7
...@@ -2,14 +2,11 @@...@@ -2,14 +2,11 @@
2//! environment, with associated path prefixes, which can be used to map2//! environment, with associated path prefixes, which can be used to map
3//! absolute paths to capabilities with relative paths.3//! absolute paths to capabilities with relative paths.
44
5#ifdef _REENTRANT
6#error "__wasilibc_register_preopened_fd doesn't yet support multiple threads"
7#endif
8
9#include <assert.h>5#include <assert.h>
10#include <errno.h>6#include <errno.h>
11#include <fcntl.h>7#include <fcntl.h>
12#include <limits.h>8#include <limits.h>
9#include <lock.h>
13#include <stdbool.h>10#include <stdbool.h>
14#include <stdlib.h>11#include <stdlib.h>
15#include <string.h>12#include <string.h>
...@@ -32,6 +29,12 @@ static preopen *preopens;...@@ -32,6 +29,12 @@ static preopen *preopens;
32static size_t num_preopens;29static size_t num_preopens;
33static size_t preopen_capacity;30static size_t preopen_capacity;
3431
32/// Access to the the above preopen must be protected in the presence of
33/// threads.
34#ifdef _REENTRANT
35static volatile int lock[1];
36#endif
37
35#ifdef NDEBUG38#ifdef NDEBUG
36#define assert_invariants() // assertions disabled39#define assert_invariants() // assertions disabled
37#else40#else
...@@ -55,14 +58,17 @@ static void assert_invariants(void) {...@@ -55,14 +58,17 @@ static void assert_invariants(void) {
5558
56/// Allocate space for more preopens. Returns 0 on success and -1 on failure.59/// Allocate space for more preopens. Returns 0 on success and -1 on failure.
57static int resize(void) {60static int resize(void) {
61 LOCK(lock);
58 size_t start_capacity = 4;62 size_t start_capacity = 4;
59 size_t old_capacity = preopen_capacity;63 size_t old_capacity = preopen_capacity;
60 size_t new_capacity = old_capacity == 0 ? start_capacity : old_capacity * 2;64 size_t new_capacity = old_capacity == 0 ? start_capacity : old_capacity * 2;
6165
62 preopen *old_preopens = preopens;66 preopen *old_preopens = preopens;
63 preopen *new_preopens = calloc(sizeof(preopen), new_capacity);67 preopen *new_preopens = calloc(sizeof(preopen), new_capacity);
64 if (new_preopens == NULL)68 if (new_preopens == NULL) {
69 UNLOCK(lock);
65 return -1;70 return -1;
71 }
6672
67 memcpy(new_preopens, old_preopens, num_preopens * sizeof(preopen));73 memcpy(new_preopens, old_preopens, num_preopens * sizeof(preopen));
68 preopens = new_preopens;74 preopens = new_preopens;
...@@ -70,6 +76,7 @@ static int resize(void) {...@@ -70,6 +76,7 @@ static int resize(void) {
70 free(old_preopens);76 free(old_preopens);
7177
72 assert_invariants();78 assert_invariants();
79 UNLOCK(lock);
73 return 0;80 return 0;
74}81}
7582
...@@ -97,21 +104,28 @@ static const char *strip_prefixes(const char *path) {...@@ -97,21 +104,28 @@ static const char *strip_prefixes(const char *path) {
97///104///
98/// This function takes ownership of `prefix`.105/// This function takes ownership of `prefix`.
99static int internal_register_preopened_fd(__wasi_fd_t fd, const char *relprefix) {106static int internal_register_preopened_fd(__wasi_fd_t fd, const char *relprefix) {
107 LOCK(lock);
108
100 // Check preconditions.109 // Check preconditions.
101 assert_invariants();110 assert_invariants();
102 assert(fd != AT_FDCWD);111 assert(fd != AT_FDCWD);
103 assert(fd != -1);112 assert(fd != -1);
104 assert(relprefix != NULL);113 assert(relprefix != NULL);
105114
106 if (num_preopens == preopen_capacity && resize() != 0)115 if (num_preopens == preopen_capacity && resize() != 0) {
116 UNLOCK(lock);
107 return -1;117 return -1;
118 }
108119
109 char *prefix = strdup(strip_prefixes(relprefix));120 char *prefix = strdup(strip_prefixes(relprefix));
110 if (prefix == NULL)121 if (prefix == NULL) {
122 UNLOCK(lock);
111 return -1;123 return -1;
124 }
112 preopens[num_preopens++] = (preopen) { prefix, fd, };125 preopens[num_preopens++] = (preopen) { prefix, fd, };
113126
114 assert_invariants();127 assert_invariants();
128 UNLOCK(lock);
115 return 0;129 return 0;
116}130}
117131
...@@ -166,6 +180,7 @@ int __wasilibc_find_abspath(const char *path,...@@ -166,6 +180,7 @@ int __wasilibc_find_abspath(const char *path,
166 // recently added preopens take precedence over less recently addded ones.180 // recently added preopens take precedence over less recently addded ones.
167 size_t match_len = 0;181 size_t match_len = 0;
168 int fd = -1;182 int fd = -1;
183 LOCK(lock);
169 for (size_t i = num_preopens; i > 0; --i) {184 for (size_t i = num_preopens; i > 0; --i) {
170 const preopen *pre = &preopens[i - 1];185 const preopen *pre = &preopens[i - 1];
171 const char *prefix = pre->prefix;186 const char *prefix = pre->prefix;
...@@ -182,6 +197,7 @@ int __wasilibc_find_abspath(const char *path,...@@ -182,6 +197,7 @@ int __wasilibc_find_abspath(const char *path,
182 *abs_prefix = prefix;197 *abs_prefix = prefix;
183 }198 }
184 }199 }
200 UNLOCK(lock);
185201
186 if (fd == -1) {202 if (fd == -1) {
187 errno = ENOENT;203 errno = ENOENT;
lib/libc/wasi/libc-top-half/musl/arch/wasm32/atomic_arch.h-4
...@@ -1,7 +1,3 @@...@@ -1,7 +1,3 @@
1#ifdef _REENTRANT
2#error "multiple threads not supported in musl yet"
3#endif
4
5#define a_barrier() (__sync_synchronize())1#define a_barrier() (__sync_synchronize())
6#define a_cas(p, t, s) (__sync_val_compare_and_swap((p), (t), (s)))2#define a_cas(p, t, s) (__sync_val_compare_and_swap((p), (t), (s)))
7#define a_crash() (__builtin_trap())3#define a_crash() (__builtin_trap())
lib/libc/wasi/libc-top-half/musl/arch/wasm32/pthread_arch.h+3-10
...@@ -1,12 +1,5 @@...@@ -1,12 +1,5 @@
1#ifdef _REENTRANT1extern _Thread_local struct __pthread __wasilibc_pthread_self;
2#error "multiple threads not supported in musl yet"
3#endif
42
5static inline struct pthread *__pthread_self(void)3static inline uintptr_t __get_tp() {
6{4 return (uintptr_t)&__wasilibc_pthread_self;
7 return (struct pthread *)-1;
8}5}
9
10#define TP_ADJ(p) (p)
11
12#define tls_mod_off_t unsigned long long
lib/libc/wasi/libc-top-half/musl/include/limits.h+1-1
...@@ -70,7 +70,7 @@...@@ -70,7 +70,7 @@
70#define PTHREAD_STACK_MIN 204870#define PTHREAD_STACK_MIN 2048
71#define PTHREAD_DESTRUCTOR_ITERATIONS 471#define PTHREAD_DESTRUCTOR_ITERATIONS 4
72#endif72#endif
73#ifdef __wasilibc_unmodified_upstream /* WASI has no semaphores */73#if defined(__wasilibc_unmodified_upstream) || defined(_REENTRANT)
74#define SEM_VALUE_MAX 0x7fffffff74#define SEM_VALUE_MAX 0x7fffffff
75#define SEM_NSEMS_MAX 25675#define SEM_NSEMS_MAX 256
76#endif76#endif
lib/libc/wasi/libc-top-half/musl/include/pthread.h+4
...@@ -103,8 +103,10 @@ int pthread_setcanceltype(int, int *);...@@ -103,8 +103,10 @@ int pthread_setcanceltype(int, int *);
103void pthread_testcancel(void);103void pthread_testcancel(void);
104int pthread_cancel(pthread_t);104int pthread_cancel(pthread_t);
105105
106#ifdef __wasilibc_unmodified_upstream /* WASI has no CPU scheduling support. */
106int pthread_getschedparam(pthread_t, int *__restrict, struct sched_param *__restrict);107int pthread_getschedparam(pthread_t, int *__restrict, struct sched_param *__restrict);
107int pthread_setschedparam(pthread_t, int, const struct sched_param *);108int pthread_setschedparam(pthread_t, int, const struct sched_param *);
109#endif
108int pthread_setschedprio(pthread_t, int);110int pthread_setschedprio(pthread_t, int);
109111
110int pthread_once(pthread_once_t *, void (*)(void));112int pthread_once(pthread_once_t *, void (*)(void));
...@@ -167,8 +169,10 @@ int pthread_attr_getscope(const pthread_attr_t *__restrict, int *__restrict);...@@ -167,8 +169,10 @@ int pthread_attr_getscope(const pthread_attr_t *__restrict, int *__restrict);
167int pthread_attr_setscope(pthread_attr_t *, int);169int pthread_attr_setscope(pthread_attr_t *, int);
168int pthread_attr_getschedpolicy(const pthread_attr_t *__restrict, int *__restrict);170int pthread_attr_getschedpolicy(const pthread_attr_t *__restrict, int *__restrict);
169int pthread_attr_setschedpolicy(pthread_attr_t *, int);171int pthread_attr_setschedpolicy(pthread_attr_t *, int);
172#ifdef __wasilibc_unmodified_upstream /* WASI has no CPU scheduling support. */
170int pthread_attr_getschedparam(const pthread_attr_t *__restrict, struct sched_param *__restrict);173int pthread_attr_getschedparam(const pthread_attr_t *__restrict, struct sched_param *__restrict);
171int pthread_attr_setschedparam(pthread_attr_t *__restrict, const struct sched_param *__restrict);174int pthread_attr_setschedparam(pthread_attr_t *__restrict, const struct sched_param *__restrict);
175#endif
172int pthread_attr_getinheritsched(const pthread_attr_t *__restrict, int *__restrict);176int pthread_attr_getinheritsched(const pthread_attr_t *__restrict, int *__restrict);
173int pthread_attr_setinheritsched(pthread_attr_t *, int);177int pthread_attr_setinheritsched(pthread_attr_t *, int);
174178
lib/libc/wasi/libc-top-half/musl/include/unistd.h+2
...@@ -244,7 +244,9 @@ void *sbrk(intptr_t);...@@ -244,7 +244,9 @@ void *sbrk(intptr_t);
244pid_t vfork(void);244pid_t vfork(void);
245int vhangup(void);245int vhangup(void);
246int chroot(const char *);246int chroot(const char *);
247#endif
247int getpagesize(void);248int getpagesize(void);
249#ifdef __wasilibc_unmodified_upstream /* WASI has no processes */
248int getdtablesize(void);250int getdtablesize(void);
249int sethostname(const char *, size_t);251int sethostname(const char *, size_t);
250int getdomainname(char *, size_t);252int getdomainname(char *, size_t);
lib/libc/wasi/libc-top-half/musl/src/conf/sysconf.c+2-2
...@@ -251,7 +251,7 @@ long sysconf(int name)...@@ -251,7 +251,7 @@ long sysconf(int name)
251 return DELAYTIMER_MAX;251 return DELAYTIMER_MAX;
252 case JT_NPROCESSORS_CONF & 255:252 case JT_NPROCESSORS_CONF & 255:
253 case JT_NPROCESSORS_ONLN & 255: ;253 case JT_NPROCESSORS_ONLN & 255: ;
254#if defined(__wasilibc_unmodified_upstream) || defined(_REENTRANT)254#ifdef __wasilibc_unmodified_upstream
255 unsigned char set[128] = {1};255 unsigned char set[128] = {1};
256 int i, cnt;256 int i, cnt;
257 __syscall(SYS_sched_getaffinity, 0, sizeof set, set);257 __syscall(SYS_sched_getaffinity, 0, sizeof set, set);
...@@ -259,7 +259,7 @@ long sysconf(int name)...@@ -259,7 +259,7 @@ long sysconf(int name)
259 for (; set[i]; set[i]&=set[i]-1, cnt++);259 for (; set[i]; set[i]&=set[i]-1, cnt++);
260 return cnt;260 return cnt;
261#else261#else
262 // With no thread support, just say there's 1 processor.262 // WASI has no way to query the processor count
263 return 1;263 return 1;
264#endif264#endif
265#ifdef __wasilibc_unmodified_upstream // WASI has no sysinfo265#ifdef __wasilibc_unmodified_upstream // WASI has no sysinfo
lib/libc/wasi/libc-top-half/musl/src/env/__init_tls.c+33
...@@ -1,7 +1,11 @@...@@ -1,7 +1,11 @@
1#ifdef __wasilibc_unmodified_upstream
1#define SYSCALL_NO_TLS 12#define SYSCALL_NO_TLS 1
2#include <elf.h>3#include <elf.h>
4#endif
3#include <limits.h>5#include <limits.h>
6#ifdef __wasilibc_unmodified_upstream
4#include <sys/mman.h>7#include <sys/mman.h>
8#endif
5#include <string.h>9#include <string.h>
6#include <stddef.h>10#include <stddef.h>
7#include "pthread_impl.h"11#include "pthread_impl.h"
...@@ -11,15 +15,23 @@...@@ -11,15 +15,23 @@
1115
12volatile int __thread_list_lock;16volatile int __thread_list_lock;
1317
18#ifndef __wasilibc_unmodified_upstream
19void __wasi_init_tp() {
20 __init_tp((void *)__get_tp());
21}
22#endif
23
14int __init_tp(void *p)24int __init_tp(void *p)
15{25{
16 pthread_t td = p;26 pthread_t td = p;
17 td->self = td;27 td->self = td;
28#ifdef __wasilibc_unmodified_upstream
18 int r = __set_thread_area(TP_ADJ(p));29 int r = __set_thread_area(TP_ADJ(p));
19 if (r < 0) return -1;30 if (r < 0) return -1;
20 if (!r) libc.can_do_threads = 1;31 if (!r) libc.can_do_threads = 1;
21 td->detach_state = DT_JOINABLE;32 td->detach_state = DT_JOINABLE;
22 td->tid = __syscall(SYS_set_tid_address, &__thread_list_lock);33 td->tid = __syscall(SYS_set_tid_address, &__thread_list_lock);
34#endif
23 td->locale = &libc.global_locale;35 td->locale = &libc.global_locale;
24 td->robust_list.head = &td->robust_list.head;36 td->robust_list.head = &td->robust_list.head;
25 td->sysinfo = __sysinfo;37 td->sysinfo = __sysinfo;
...@@ -27,6 +39,8 @@ int __init_tp(void *p)...@@ -27,6 +39,8 @@ int __init_tp(void *p)
27 return 0;39 return 0;
28}40}
2941
42#ifdef __wasilibc_unmodified_upstream
43
30static struct builtin_tls {44static struct builtin_tls {
31 char c;45 char c;
32 struct pthread pt;46 struct pthread pt;
...@@ -35,9 +49,15 @@ static struct builtin_tls {...@@ -35,9 +49,15 @@ static struct builtin_tls {
35#define MIN_TLS_ALIGN offsetof(struct builtin_tls, pt)49#define MIN_TLS_ALIGN offsetof(struct builtin_tls, pt)
3650
37static struct tls_module main_tls;51static struct tls_module main_tls;
52#endif
53
54#ifndef __wasilibc_unmodified_upstream
55extern void __wasm_init_tls(void*);
56#endif
3857
39void *__copy_tls(unsigned char *mem)58void *__copy_tls(unsigned char *mem)
40{59{
60#ifdef __wasilibc_unmodified_upstream
41 pthread_t td;61 pthread_t td;
42 struct tls_module *p;62 struct tls_module *p;
43 size_t i;63 size_t i;
...@@ -69,8 +89,20 @@ void *__copy_tls(unsigned char *mem)...@@ -69,8 +89,20 @@ void *__copy_tls(unsigned char *mem)
69 dtv[0] = libc.tls_cnt;89 dtv[0] = libc.tls_cnt;
70 td->dtv = dtv;90 td->dtv = dtv;
71 return td;91 return td;
92#else
93 size_t tls_align = __builtin_wasm_tls_align();
94 volatile void* tls_base = __builtin_wasm_tls_base();
95 mem += tls_align;
96 mem -= (uintptr_t)mem & (tls_align-1);
97 __wasm_init_tls(mem);
98 __asm__("local.get %0\n"
99 "global.set __tls_base\n"
100 :: "r"(tls_base));
101 return mem;
102#endif
72}103}
73104
105#ifdef __wasilibc_unmodified_upstream
74#if ULONG_MAX == 0xffffffff106#if ULONG_MAX == 0xffffffff
75typedef Elf32_Phdr Phdr;107typedef Elf32_Phdr Phdr;
76#else108#else
...@@ -151,3 +183,4 @@ static void static_init_tls(size_t *aux)...@@ -151,3 +183,4 @@ static void static_init_tls(size_t *aux)
151}183}
152184
153weak_alias(static_init_tls, __init_tls);185weak_alias(static_init_tls, __init_tls);
186#endif
lib/libc/wasi/libc-top-half/musl/src/internal/libc.h+4-2
...@@ -18,8 +18,10 @@ struct tls_module {...@@ -18,8 +18,10 @@ struct tls_module {
18};18};
1919
20struct __libc {20struct __libc {
21#if defined(__wasilibc_unmodified_upstream) || defined(_REENTRANT)21#ifdef __wasilibc_unmodified_upstream
22 char can_do_threads;22 char can_do_threads;
23#endif
24#if defined(__wasilibc_unmodified_upstream) || defined(_REENTRANT)
23 char threaded;25 char threaded;
24#endif26#endif
25#ifdef __wasilibc_unmodified_upstream // WASI doesn't currently use any code that needs "secure" mode27#ifdef __wasilibc_unmodified_upstream // WASI doesn't currently use any code that needs "secure" mode
...@@ -32,7 +34,7 @@ struct __libc {...@@ -32,7 +34,7 @@ struct __libc {
32#ifdef __wasilibc_unmodified_upstream // WASI has no auxv34#ifdef __wasilibc_unmodified_upstream // WASI has no auxv
33 size_t *auxv;35 size_t *auxv;
34#endif36#endif
35#if defined(__wasilibc_unmodified_upstream) || defined(_REENTRANT)37#ifdef __wasilibc_unmodified_upstream // WASI use different TLS implement
36 struct tls_module *tls_head;38 struct tls_module *tls_head;
37 size_t tls_size, tls_align, tls_cnt;39 size_t tls_size, tls_align, tls_cnt;
38#endif40#endif
lib/libc/wasi/libc-top-half/musl/src/internal/pthread_impl.h+21
...@@ -2,12 +2,18 @@...@@ -2,12 +2,18 @@
2#define _PTHREAD_IMPL_H2#define _PTHREAD_IMPL_H
33
4#include <pthread.h>4#include <pthread.h>
5#ifdef __wasilibc_unmodified_upstream
5#include <signal.h>6#include <signal.h>
7#endif
6#include <errno.h>8#include <errno.h>
7#include <limits.h>9#include <limits.h>
10#ifdef __wasilibc_unmodified_upstream
8#include <sys/mman.h>11#include <sys/mman.h>
12#endif
9#include "libc.h"13#include "libc.h"
14#ifdef __wasilibc_unmodified_upstream
10#include "syscall.h"15#include "syscall.h"
16#endif
11#include "atomic.h"17#include "atomic.h"
12#include "futex.h"18#include "futex.h"
1319
...@@ -19,8 +25,10 @@ struct pthread {...@@ -19,8 +25,10 @@ struct pthread {
19 /* Part 1 -- these fields may be external or25 /* Part 1 -- these fields may be external or
20 * internal (accessed via asm) ABI. Do not change. */26 * internal (accessed via asm) ABI. Do not change. */
21 struct pthread *self;27 struct pthread *self;
28#ifdef __wasilibc_unmodified_upstream
22#ifndef TLS_ABOVE_TP29#ifndef TLS_ABOVE_TP
23 uintptr_t *dtv;30 uintptr_t *dtv;
31#endif
24#endif32#endif
25 struct pthread *prev, *next; /* non-ABI */33 struct pthread *prev, *next; /* non-ABI */
26 uintptr_t sysinfo;34 uintptr_t sysinfo;
...@@ -159,9 +167,14 @@ extern hidden volatile int __eintr_valid_flag;...@@ -159,9 +167,14 @@ extern hidden volatile int __eintr_valid_flag;
159167
160hidden int __clone(int (*)(void *), void *, int, void *, ...);168hidden int __clone(int (*)(void *), void *, int, void *, ...);
161hidden int __set_thread_area(void *);169hidden int __set_thread_area(void *);
170#ifdef __wasilibc_unmodified_upstream /* WASI has no sigaction */
162hidden int __libc_sigaction(int, const struct sigaction *, struct sigaction *);171hidden int __libc_sigaction(int, const struct sigaction *, struct sigaction *);
172#endif
163hidden void __unmapself(void *, size_t);173hidden void __unmapself(void *, size_t);
164174
175#ifndef __wasilibc_unmodified_upstream
176hidden int __wasilibc_futex_wait(volatile void *, int, int, int64_t);
177#endif
165hidden int __timedwait(volatile int *, int, clockid_t, const struct timespec *, int);178hidden int __timedwait(volatile int *, int, clockid_t, const struct timespec *, int);
166hidden int __timedwait_cp(volatile int *, int, clockid_t, const struct timespec *, int);179hidden int __timedwait_cp(volatile int *, int, clockid_t, const struct timespec *, int);
167hidden void __wait(volatile int *, volatile int *, int, int);180hidden void __wait(volatile int *, volatile int *, int, int);
...@@ -169,14 +182,22 @@ static inline void __wake(volatile void *addr, int cnt, int priv)...@@ -169,14 +182,22 @@ static inline void __wake(volatile void *addr, int cnt, int priv)
169{182{
170 if (priv) priv = FUTEX_PRIVATE;183 if (priv) priv = FUTEX_PRIVATE;
171 if (cnt<0) cnt = INT_MAX;184 if (cnt<0) cnt = INT_MAX;
185#ifdef __wasilibc_unmodified_upstream
172 __syscall(SYS_futex, addr, FUTEX_WAKE|priv, cnt) != -ENOSYS ||186 __syscall(SYS_futex, addr, FUTEX_WAKE|priv, cnt) != -ENOSYS ||
173 __syscall(SYS_futex, addr, FUTEX_WAKE, cnt);187 __syscall(SYS_futex, addr, FUTEX_WAKE, cnt);
188#else
189 __builtin_wasm_memory_atomic_notify((int*)addr, cnt);
190#endif
174}191}
175static inline void __futexwait(volatile void *addr, int val, int priv)192static inline void __futexwait(volatile void *addr, int val, int priv)
176{193{
194#ifdef __wasilibc_unmodified_upstream
177 if (priv) priv = FUTEX_PRIVATE;195 if (priv) priv = FUTEX_PRIVATE;
178 __syscall(SYS_futex, addr, FUTEX_WAIT|priv, val, 0) != -ENOSYS ||196 __syscall(SYS_futex, addr, FUTEX_WAIT|priv, val, 0) != -ENOSYS ||
179 __syscall(SYS_futex, addr, FUTEX_WAIT, val, 0);197 __syscall(SYS_futex, addr, FUTEX_WAIT, val, 0);
198#else
199 __wait(addr, NULL, val, priv);
200#endif
180}201}
181202
182hidden void __acquire_ptc(void);203hidden void __acquire_ptc(void);
lib/libc/wasi/libc-top-half/musl/src/internal/syscall.h+2
...@@ -1,3 +1,4 @@...@@ -1,3 +1,4 @@
1#ifdef __wasilibc_unmodified_upstream
1#ifndef _INTERNAL_SYSCALL_H2#ifndef _INTERNAL_SYSCALL_H
2#define _INTERNAL_SYSCALL_H3#define _INTERNAL_SYSCALL_H
34
...@@ -396,3 +397,4 @@ hidden void __procfdname(char __buf[static 15+3*sizeof(int)], unsigned);...@@ -396,3 +397,4 @@ hidden void __procfdname(char __buf[static 15+3*sizeof(int)], unsigned);
396hidden void *__vdsosym(const char *, const char *);397hidden void *__vdsosym(const char *, const char *);
397398
398#endif399#endif
400#endif
lib/libc/wasi/libc-top-half/musl/src/prng/random.c+1-1
...@@ -23,7 +23,7 @@ static int n = 31;...@@ -23,7 +23,7 @@ static int n = 31;
23static int i = 3;23static int i = 3;
24static int j = 0;24static int j = 0;
25static uint32_t *x = init+1;25static uint32_t *x = init+1;
26#ifdef __wasilibc_unmodified_upstream26#if defined(__wasilibc_unmodified_upstream) || defined(_REENTRANT)
27static volatile int lock[1];27static volatile int lock[1];
28volatile int *const __random_lockptr = lock;28volatile int *const __random_lockptr = lock;
29#endif29#endif
lib/libc/wasi/libc-top-half/musl/src/string/memcpy.c+4
...@@ -4,6 +4,10 @@...@@ -4,6 +4,10 @@
44
5void *memcpy(void *restrict dest, const void *restrict src, size_t n)5void *memcpy(void *restrict dest, const void *restrict src, size_t n)
6{6{
7#if defined(__wasm_bulk_memory__)
8 if (n > BULK_MEMORY_THRESHOLD)
9 return __builtin_memcpy(dest, src, n);
10#endif
7 unsigned char *d = dest;11 unsigned char *d = dest;
8 const unsigned char *s = src;12 const unsigned char *s = src;
913
lib/libc/wasi/libc-top-half/musl/src/string/memmove.c+4
...@@ -8,6 +8,10 @@ typedef __attribute__((__may_alias__)) size_t WT;...@@ -8,6 +8,10 @@ typedef __attribute__((__may_alias__)) size_t WT;
88
9void *memmove(void *dest, const void *src, size_t n)9void *memmove(void *dest, const void *src, size_t n)
10{10{
11#if defined(__wasm_bulk_memory__)
12 if (n > BULK_MEMORY_THRESHOLD)
13 return __builtin_memmove(dest, src, n);
14#endif
11 char *d = dest;15 char *d = dest;
12 const char *s = src;16 const char *s = src;
1317
lib/libc/wasi/libc-top-half/musl/src/string/memset.c+4
...@@ -3,6 +3,10 @@...@@ -3,6 +3,10 @@
33
4void *memset(void *dest, int c, size_t n)4void *memset(void *dest, int c, size_t n)
5{5{
6#if defined(__wasm_bulk_memory__)
7 if (n > BULK_MEMORY_THRESHOLD)
8 return __builtin_memset(dest, c, n);
9#endif
6 unsigned char *s = dest;10 unsigned char *s = dest;
7 size_t k;11 size_t k;
812
lib/libc/wasi/libc-top-half/musl/src/thread/__timedwait.c+13
...@@ -5,6 +5,7 @@...@@ -5,6 +5,7 @@
5#include "syscall.h"5#include "syscall.h"
6#include "pthread_impl.h"6#include "pthread_impl.h"
77
8#ifdef __wasilibc_unmodified_upstream
8#define IS32BIT(x) !((x)+0x80000000ULL>>32)9#define IS32BIT(x) !((x)+0x80000000ULL>>32)
9#define CLAMP(x) (int)(IS32BIT(x) ? (x) : 0x7fffffffU+((0ULL+(x))>>63))10#define CLAMP(x) (int)(IS32BIT(x) ? (x) : 0x7fffffffU+((0ULL+(x))>>63))
1011
...@@ -28,6 +29,16 @@ static int __futex4_cp(volatile void *addr, int op, int val, const struct timesp...@@ -28,6 +29,16 @@ static int __futex4_cp(volatile void *addr, int op, int val, const struct timesp
2829
29static volatile int dummy = 0;30static volatile int dummy = 0;
30weak_alias(dummy, __eintr_valid_flag);31weak_alias(dummy, __eintr_valid_flag);
32#else
33static int __futex4_cp(volatile void *addr, int op, int val, const struct timespec *to)
34{
35 int64_t max_wait_ns = -1;
36 if (to) {
37 max_wait_ns = (int64_t)(to->tv_sec * 1000000000 + to->tv_nsec);
38 }
39 return __wasilibc_futex_wait(addr, op, val, max_wait_ns);
40}
41#endif
3142
32int __timedwait_cp(volatile int *addr, int val,43int __timedwait_cp(volatile int *addr, int val,
33 clockid_t clk, const struct timespec *at, int priv)44 clockid_t clk, const struct timespec *at, int priv)
...@@ -51,11 +62,13 @@ int __timedwait_cp(volatile int *addr, int val,...@@ -51,11 +62,13 @@ int __timedwait_cp(volatile int *addr, int val,
5162
52 r = -__futex4_cp(addr, FUTEX_WAIT|priv, val, top);63 r = -__futex4_cp(addr, FUTEX_WAIT|priv, val, top);
53 if (r != EINTR && r != ETIMEDOUT && r != ECANCELED) r = 0;64 if (r != EINTR && r != ETIMEDOUT && r != ECANCELED) r = 0;
65#ifdef __wasilibc_unmodified_upstream
54 /* Mitigate bug in old kernels wrongly reporting EINTR for non-66 /* Mitigate bug in old kernels wrongly reporting EINTR for non-
55 * interrupting (SA_RESTART) signal handlers. This is only practical67 * interrupting (SA_RESTART) signal handlers. This is only practical
56 * when NO interrupting signal handlers have been installed, and68 * when NO interrupting signal handlers have been installed, and
57 * works by sigaction tracking whether that's the case. */69 * works by sigaction tracking whether that's the case. */
58 if (r == EINTR && !__eintr_valid_flag) r = 0;70 if (r == EINTR && !__eintr_valid_flag) r = 0;
71#endif
5972
60 return r;73 return r;
61}74}
lib/libc/wasi/libc-top-half/musl/src/thread/__wait.c+38
...@@ -1,4 +1,38 @@...@@ -1,4 +1,38 @@
1#include "pthread_impl.h"1#include "pthread_impl.h"
2#ifndef __wasilibc_unmodified_upstream
3#include "assert.h"
4#endif
5
6#ifndef __wasilibc_unmodified_upstream
7// Use WebAssembly's `wait` instruction to implement a futex. Note that `op` is
8// unused but retained as a parameter to match the original signature of the
9// syscall and that, for `max_wait_ns`, -1 (or any negative number) means wait
10// indefinitely.
11//
12// Adapted from Emscripten: see
13// https://github.com/emscripten-core/emscripten/blob/058a9fff/system/lib/pthread/emscripten_futex_wait.c#L111-L150.
14int __wasilibc_futex_wait(volatile void *addr, int op, int val, int64_t max_wait_ns)
15{
16 if ((((intptr_t)addr) & 3) != 0) {
17 return -EINVAL;
18 }
19
20 int ret = __builtin_wasm_memory_atomic_wait32((int *)addr, val, max_wait_ns);
21
22 // memory.atomic.wait32 returns:
23 // 0 => "ok", woken by another agent.
24 // 1 => "not-equal", loaded value != expected value
25 // 2 => "timed-out", the timeout expired
26 if (ret == 1) {
27 return -EWOULDBLOCK;
28 }
29 if (ret == 2) {
30 return -ETIMEDOUT;
31 }
32 assert(ret == 0);
33 return 0;
34}
35#endif
236
3void __wait(volatile int *addr, volatile int *waiters, int val, int priv)37void __wait(volatile int *addr, volatile int *waiters, int val, int priv)
4{38{
...@@ -10,8 +44,12 @@ void __wait(volatile int *addr, volatile int *waiters, int val, int priv)...@@ -10,8 +44,12 @@ void __wait(volatile int *addr, volatile int *waiters, int val, int priv)
10 }44 }
11 if (waiters) a_inc(waiters);45 if (waiters) a_inc(waiters);
12 while (*addr==val) {46 while (*addr==val) {
47#ifdef __wasilibc_unmodified_upstream
13 __syscall(SYS_futex, addr, FUTEX_WAIT|priv, val, 0) != -ENOSYS48 __syscall(SYS_futex, addr, FUTEX_WAIT|priv, val, 0) != -ENOSYS
14 || __syscall(SYS_futex, addr, FUTEX_WAIT, val, 0);49 || __syscall(SYS_futex, addr, FUTEX_WAIT, val, 0);
50#else
51 __wasilibc_futex_wait(addr, FUTEX_WAIT, val, 0);
52#endif
15 }53 }
16 if (waiters) a_dec(waiters);54 if (waiters) a_dec(waiters);
17}55}
lib/libc/wasi/libc-top-half/musl/src/thread/pthread_cond_timedwait.c+17
...@@ -1,5 +1,9 @@...@@ -1,5 +1,9 @@
1#include "pthread_impl.h"1#include "pthread_impl.h"
22
3#ifndef __wasilibc_unmodified_upstream
4#include <common/clock.h>
5#endif
6
3/*7/*
4 * struct waiter8 * struct waiter
5 *9 *
...@@ -48,9 +52,15 @@ static inline void unlock(volatile int *l)...@@ -48,9 +52,15 @@ static inline void unlock(volatile int *l)
48static inline void unlock_requeue(volatile int *l, volatile int *r, int w)52static inline void unlock_requeue(volatile int *l, volatile int *r, int w)
49{53{
50 a_store(l, 0);54 a_store(l, 0);
55#ifdef __wasilibc_unmodified_upstream
51 if (w) __wake(l, 1, 1);56 if (w) __wake(l, 1, 1);
52 else __syscall(SYS_futex, l, FUTEX_REQUEUE|FUTEX_PRIVATE, 0, 1, r) != -ENOSYS57 else __syscall(SYS_futex, l, FUTEX_REQUEUE|FUTEX_PRIVATE, 0, 1, r) != -ENOSYS
53 || __syscall(SYS_futex, l, FUTEX_REQUEUE, 0, 1, r);58 || __syscall(SYS_futex, l, FUTEX_REQUEUE, 0, 1, r);
59#else
60 // Always wake due to lack of requeue system call in WASI
61 // This can impact the performance, so we might need to re-visit that decision
62 __wake(l, 1, 1);
63#endif
54}64}
5565
56enum {66enum {
...@@ -63,6 +73,9 @@ int __pthread_cond_timedwait(pthread_cond_t *restrict c, pthread_mutex_t *restri...@@ -63,6 +73,9 @@ int __pthread_cond_timedwait(pthread_cond_t *restrict c, pthread_mutex_t *restri
63{73{
64 struct waiter node = { 0 };74 struct waiter node = { 0 };
65 int e, seq, clock = c->_c_clock, cs, shared=0, oldstate, tmp;75 int e, seq, clock = c->_c_clock, cs, shared=0, oldstate, tmp;
76#ifndef __wasilibc_unmodified_upstream
77 struct __clockid clock_id = { .id = clock };
78#endif
66 volatile int *fut;79 volatile int *fut;
6780
68 if ((m->_m_type&15) && (m->_m_lock&INT_MAX) != __pthread_self()->tid)81 if ((m->_m_type&15) && (m->_m_lock&INT_MAX) != __pthread_self()->tid)
...@@ -97,7 +110,11 @@ int __pthread_cond_timedwait(pthread_cond_t *restrict c, pthread_mutex_t *restri...@@ -97,7 +110,11 @@ int __pthread_cond_timedwait(pthread_cond_t *restrict c, pthread_mutex_t *restri
97 __pthread_setcancelstate(PTHREAD_CANCEL_MASKED, &cs);110 __pthread_setcancelstate(PTHREAD_CANCEL_MASKED, &cs);
98 if (cs == PTHREAD_CANCEL_DISABLE) __pthread_setcancelstate(cs, 0);111 if (cs == PTHREAD_CANCEL_DISABLE) __pthread_setcancelstate(cs, 0);
99112
113#ifdef __wasilibc_unmodified_upstream
100 do e = __timedwait_cp(fut, seq, clock, ts, !shared);114 do e = __timedwait_cp(fut, seq, clock, ts, !shared);
115#else
116 do e = __timedwait_cp(fut, seq, &clock_id, ts, !shared);
117#endif
101 while (*fut==seq && (!e || e==EINTR));118 while (*fut==seq && (!e || e==EINTR));
102 if (e == EINTR) e = 0;119 if (e == EINTR) e = 0;
103120
lib/libc/wasi/libc-top-half/musl/src/thread/pthread_condattr_setclock.c+12
...@@ -1,9 +1,21 @@...@@ -1,9 +1,21 @@
1#include "pthread_impl.h"1#include "pthread_impl.h"
22
3#ifndef __wasilibc_unmodified_upstream
4#include <common/clock.h>
5#endif
6
3int pthread_condattr_setclock(pthread_condattr_t *a, clockid_t clk)7int pthread_condattr_setclock(pthread_condattr_t *a, clockid_t clk)
4{8{
9#ifdef __wasilibc_unmodified_upstream
5 if (clk < 0 || clk-2U < 2) return EINVAL;10 if (clk < 0 || clk-2U < 2) return EINVAL;
11#else
12 if (clk->id < 0 || clk->id-2U < 2) return EINVAL;
13#endif
6 a->__attr &= 0x80000000;14 a->__attr &= 0x80000000;
15#ifdef __wasilibc_unmodified_upstream
7 a->__attr |= clk;16 a->__attr |= clk;
17#else
18 a->__attr |= clk->id;
19#endif
8 return 0;20 return 0;
9}21}
lib/libc/wasi/libc-top-half/musl/src/thread/pthread_create.c+174-2
...@@ -3,9 +3,16 @@...@@ -3,9 +3,16 @@
3#include "stdio_impl.h"3#include "stdio_impl.h"
4#include "libc.h"4#include "libc.h"
5#include "lock.h"5#include "lock.h"
6#ifdef __wasilibc_unmodified_upstream
6#include <sys/mman.h>7#include <sys/mman.h>
8#endif
7#include <string.h>9#include <string.h>
8#include <stddef.h>10#include <stddef.h>
11#ifndef __wasilibc_unmodified_upstream
12#include <stdatomic.h>
13#endif
14
15#include <stdalign.h>
916
10static void dummy_0()17static void dummy_0()
11{18{
...@@ -14,8 +21,10 @@ weak_alias(dummy_0, __acquire_ptc);...@@ -14,8 +21,10 @@ weak_alias(dummy_0, __acquire_ptc);
14weak_alias(dummy_0, __release_ptc);21weak_alias(dummy_0, __release_ptc);
15weak_alias(dummy_0, __pthread_tsd_run_dtors);22weak_alias(dummy_0, __pthread_tsd_run_dtors);
16weak_alias(dummy_0, __do_orphaned_stdio_locks);23weak_alias(dummy_0, __do_orphaned_stdio_locks);
24#ifdef __wasilibc_unmodified_upstream
17weak_alias(dummy_0, __dl_thread_cleanup);25weak_alias(dummy_0, __dl_thread_cleanup);
18weak_alias(dummy_0, __membarrier_init);26weak_alias(dummy_0, __membarrier_init);
27#endif
1928
20static int tl_lock_count;29static int tl_lock_count;
21static int tl_lock_waiters;30static int tl_lock_waiters;
...@@ -69,7 +78,9 @@ _Noreturn void __pthread_exit(void *result)...@@ -69,7 +78,9 @@ _Noreturn void __pthread_exit(void *result)
6978
70 __pthread_tsd_run_dtors();79 __pthread_tsd_run_dtors();
7180
81#ifdef __wasilibc_unmodified_upstream
72 __block_app_sigs(&set);82 __block_app_sigs(&set);
83#endif
7384
74 /* This atomic potentially competes with a concurrent pthread_detach85 /* This atomic potentially competes with a concurrent pthread_detach
75 * call; the loser is responsible for freeing thread resources. */86 * call; the loser is responsible for freeing thread resources. */
...@@ -80,7 +91,9 @@ _Noreturn void __pthread_exit(void *result)...@@ -80,7 +91,9 @@ _Noreturn void __pthread_exit(void *result)
80 * explicitly wait for vmlock holders first. This must be91 * explicitly wait for vmlock holders first. This must be
81 * done before any locks are taken, to avoid lock ordering92 * done before any locks are taken, to avoid lock ordering
82 * issues that could lead to deadlock. */93 * issues that could lead to deadlock. */
94#ifdef __wasilibc_unmodified_upstream
83 __vm_wait();95 __vm_wait();
96#endif
84 }97 }
8598
86 /* Access to target the exiting thread with syscalls that use99 /* Access to target the exiting thread with syscalls that use
...@@ -101,16 +114,20 @@ _Noreturn void __pthread_exit(void *result)...@@ -101,16 +114,20 @@ _Noreturn void __pthread_exit(void *result)
101 __tl_unlock();114 __tl_unlock();
102 UNLOCK(self->killlock);115 UNLOCK(self->killlock);
103 self->detach_state = state;116 self->detach_state = state;
117#ifdef __wasilibc_unmodified_upstream
104 __restore_sigs(&set);118 __restore_sigs(&set);
119#endif
105 exit(0);120 exit(0);
106 }121 }
107122
108 /* At this point we are committed to thread termination. */123 /* At this point we are committed to thread termination. */
109124
125#ifdef __wasilibc_unmodified_upstream
110 /* Process robust list in userspace to handle non-pshared mutexes126 /* Process robust list in userspace to handle non-pshared mutexes
111 * and the detached thread case where the robust list head will127 * and the detached thread case where the robust list head will
112 * be invalid when the kernel would process it. */128 * be invalid when the kernel would process it. */
113 __vm_lock();129 __vm_lock();
130#endif
114 volatile void *volatile *rp;131 volatile void *volatile *rp;
115 while ((rp=self->robust_list.head) && rp != &self->robust_list.head) {132 while ((rp=self->robust_list.head) && rp != &self->robust_list.head) {
116 pthread_mutex_t *m = (void *)((char *)rp133 pthread_mutex_t *m = (void *)((char *)rp
...@@ -124,10 +141,14 @@ _Noreturn void __pthread_exit(void *result)...@@ -124,10 +141,14 @@ _Noreturn void __pthread_exit(void *result)
124 if (cont < 0 || waiters)141 if (cont < 0 || waiters)
125 __wake(&m->_m_lock, 1, priv);142 __wake(&m->_m_lock, 1, priv);
126 }143 }
144#ifdef __wasilibc_unmodified_upstream
127 __vm_unlock();145 __vm_unlock();
146#endif
128147
129 __do_orphaned_stdio_locks();148 __do_orphaned_stdio_locks();
149#ifdef __wasilibc_unmodified_upstream
130 __dl_thread_cleanup();150 __dl_thread_cleanup();
151#endif
131152
132 /* Last, unlink thread from the list. This change will not be visible153 /* Last, unlink thread from the list. This change will not be visible
133 * until the lock is released, which only happens after SYS_exit154 * until the lock is released, which only happens after SYS_exit
...@@ -139,6 +160,15 @@ _Noreturn void __pthread_exit(void *result)...@@ -139,6 +160,15 @@ _Noreturn void __pthread_exit(void *result)
139 self->prev->next = self->next;160 self->prev->next = self->next;
140 self->prev = self->next = self;161 self->prev = self->next = self;
141162
163#ifndef __wasilibc_unmodified_upstream
164 /* On Linux, the thread is created with CLONE_CHILD_CLEARTID,
165 * and this lock will unlock by kernel when this thread terminates.
166 * So we should unlock it here in WebAssembly.
167 * See also set_tid_address(2) */
168 __tl_unlock();
169#endif
170
171#ifdef __wasilibc_unmodified_upstream
142 if (state==DT_DETACHED && self->map_base) {172 if (state==DT_DETACHED && self->map_base) {
143 /* Detached threads must block even implementation-internal173 /* Detached threads must block even implementation-internal
144 * signals, since they will not have a stack in their last174 * signals, since they will not have a stack in their last
...@@ -154,6 +184,16 @@ _Noreturn void __pthread_exit(void *result)...@@ -154,6 +184,16 @@ _Noreturn void __pthread_exit(void *result)
154 * and then exits without touching the stack. */184 * and then exits without touching the stack. */
155 __unmapself(self->map_base, self->map_size);185 __unmapself(self->map_base, self->map_size);
156 }186 }
187#else
188 if (state==DT_DETACHED && self->map_base) {
189 // __syscall(SYS_exit) would unlock the thread, list
190 // do it manually here
191 __tl_unlock();
192 free(self->map_base);
193 // Can't use `exit()` here, because it is too high level
194 for (;;) __wasi_proc_exit(0);
195 }
196#endif
157197
158 /* Wake any joiner. */198 /* Wake any joiner. */
159 a_store(&self->detach_state, DT_EXITED);199 a_store(&self->detach_state, DT_EXITED);
...@@ -165,7 +205,15 @@ _Noreturn void __pthread_exit(void *result)...@@ -165,7 +205,15 @@ _Noreturn void __pthread_exit(void *result)
165 self->tid = 0;205 self->tid = 0;
166 UNLOCK(self->killlock);206 UNLOCK(self->killlock);
167207
208#ifdef __wasilibc_unmodified_upstream
168 for (;;) __syscall(SYS_exit, 0);209 for (;;) __syscall(SYS_exit, 0);
210#else
211 // __syscall(SYS_exit) would unlock the thread, list
212 // do it manually here
213 __tl_unlock();
214 // Can't use `exit()` here, because it is too high level
215 for (;;) __wasi_proc_exit(0);
216#endif
169}217}
170218
171void __do_cleanup_push(struct __ptcb *cb)219void __do_cleanup_push(struct __ptcb *cb)
...@@ -181,12 +229,19 @@ void __do_cleanup_pop(struct __ptcb *cb)...@@ -181,12 +229,19 @@ void __do_cleanup_pop(struct __ptcb *cb)
181}229}
182230
183struct start_args {231struct start_args {
232#ifdef __wasilibc_unmodified_upstream
184 void *(*start_func)(void *);233 void *(*start_func)(void *);
185 void *start_arg;234 void *start_arg;
186 volatile int control;235 volatile int control;
187 unsigned long sig_mask[_NSIG/8/sizeof(long)];236 unsigned long sig_mask[_NSIG/8/sizeof(long)];
237#else
238 void *(*start_func)(void *);
239 void *start_arg;
240 void *tls_base;
241#endif
188};242};
189243
244#ifdef __wasilibc_unmodified_upstream
190static int start(void *p)245static int start(void *p)
191{246{
192 struct start_args *args = p;247 struct start_args *args = p;
...@@ -195,11 +250,15 @@ static int start(void *p)...@@ -195,11 +250,15 @@ static int start(void *p)
195 if (a_cas(&args->control, 1, 2)==1)250 if (a_cas(&args->control, 1, 2)==1)
196 __wait(&args->control, 0, 2, 1);251 __wait(&args->control, 0, 2, 1);
197 if (args->control) {252 if (args->control) {
253#ifdef __wasilibc_unmodified_upstream
198 __syscall(SYS_set_tid_address, &args->control);254 __syscall(SYS_set_tid_address, &args->control);
199 for (;;) __syscall(SYS_exit, 0);255 for (;;) __syscall(SYS_exit, 0);
256#endif
200 }257 }
201 }258 }
259#ifdef __wasilibc_unmodified_upstream
202 __syscall(SYS_rt_sigprocmask, SIG_SETMASK, &args->sig_mask, 0, _NSIG/8);260 __syscall(SYS_rt_sigprocmask, SIG_SETMASK, &args->sig_mask, 0, _NSIG/8);
261#endif
203 __pthread_exit(args->start_func(args->start_arg));262 __pthread_exit(args->start_func(args->start_arg));
204 return 0;263 return 0;
205}264}
...@@ -211,6 +270,31 @@ static int start_c11(void *p)...@@ -211,6 +270,31 @@ static int start_c11(void *p)
211 __pthread_exit((void *)(uintptr_t)start(args->start_arg));270 __pthread_exit((void *)(uintptr_t)start(args->start_arg));
212 return 0;271 return 0;
213}272}
273#else
274__attribute__((export_name("wasi_thread_start")))
275_Noreturn void wasi_thread_start(int tid, void *p)
276{
277 struct start_args *args = p;
278 __asm__(".globaltype __tls_base, i32\n"
279 "local.get %0\n"
280 "global.set __tls_base\n"
281 :: "r"(args->tls_base));
282 pthread_t self = __pthread_self();
283 // Set the thread ID (TID) on the pthread structure. The TID is stored
284 // atomically since it is also stored by the parent thread; this way,
285 // whichever thread (parent or child) reaches this point first can proceed
286 // without waiting.
287 atomic_store((atomic_int *) &(self->tid), tid);
288 // Set the stack pointer.
289 __asm__(".globaltype __stack_pointer, i32\n"
290 "local.get %0\n"
291 "global.set __stack_pointer\n"
292 :: "r"(self->stack));
293 // Execute the user's start function.
294 int (*start)(void*) = (int(*)(void*)) args->start_func;
295 __pthread_exit((void *)(uintptr_t)start(args->start_arg));
296}
297#endif
214298
215#define ROUND(x) (((x)+PAGE_SIZE-1)&-PAGE_SIZE)299#define ROUND(x) (((x)+PAGE_SIZE-1)&-PAGE_SIZE)
216300
...@@ -236,13 +320,25 @@ int __pthread_create(pthread_t *restrict res, const pthread_attr_t *restrict att...@@ -236,13 +320,25 @@ int __pthread_create(pthread_t *restrict res, const pthread_attr_t *restrict att
236 size_t size, guard;320 size_t size, guard;
237 struct pthread *self, *new;321 struct pthread *self, *new;
238 unsigned char *map = 0, *stack = 0, *tsd = 0, *stack_limit;322 unsigned char *map = 0, *stack = 0, *tsd = 0, *stack_limit;
323#ifdef __wasilibc_unmodified_upstream
239 unsigned flags = CLONE_VM | CLONE_FS | CLONE_FILES | CLONE_SIGHAND324 unsigned flags = CLONE_VM | CLONE_FS | CLONE_FILES | CLONE_SIGHAND
240 | CLONE_THREAD | CLONE_SYSVSEM | CLONE_SETTLS325 | CLONE_THREAD | CLONE_SYSVSEM | CLONE_SETTLS
241 | CLONE_PARENT_SETTID | CLONE_CHILD_CLEARTID | CLONE_DETACHED;326 | CLONE_PARENT_SETTID | CLONE_CHILD_CLEARTID | CLONE_DETACHED;
327#endif
242 pthread_attr_t attr = { 0 };328 pthread_attr_t attr = { 0 };
243 sigset_t set;329 sigset_t set;
244330#ifndef __wasilibc_unmodified_upstream
331 size_t tls_size = __builtin_wasm_tls_size();
332 size_t tls_align = __builtin_wasm_tls_align();
333 void* tls_base = __builtin_wasm_tls_base();
334 void* new_tls_base;
335 size_t tls_offset;
336 tls_size += tls_align;
337#endif
338
339#ifdef __wasilibc_unmodified_upstream
245 if (!libc.can_do_threads) return ENOSYS;340 if (!libc.can_do_threads) return ENOSYS;
341#endif
246 self = __pthread_self();342 self = __pthread_self();
247 if (!libc.threaded) {343 if (!libc.threaded) {
248 for (FILE *f=*__ofl_lock(); f; f=f->next)344 for (FILE *f=*__ofl_lock(); f; f=f->next)
...@@ -251,9 +347,13 @@ int __pthread_create(pthread_t *restrict res, const pthread_attr_t *restrict att...@@ -251,9 +347,13 @@ int __pthread_create(pthread_t *restrict res, const pthread_attr_t *restrict att
251 init_file_lock(__stdin_used);347 init_file_lock(__stdin_used);
252 init_file_lock(__stdout_used);348 init_file_lock(__stdout_used);
253 init_file_lock(__stderr_used);349 init_file_lock(__stderr_used);
350#ifdef __wasilibc_unmodified_upstream
254 __syscall(SYS_rt_sigprocmask, SIG_UNBLOCK, SIGPT_SET, 0, _NSIG/8);351 __syscall(SYS_rt_sigprocmask, SIG_UNBLOCK, SIGPT_SET, 0, _NSIG/8);
352#endif
255 self->tsd = (void **)__pthread_tsd_main;353 self->tsd = (void **)__pthread_tsd_main;
354#ifdef __wasilibc_unmodified_upstream
256 __membarrier_init();355 __membarrier_init();
356#endif
257 libc.threaded = 1;357 libc.threaded = 1;
258 }358 }
259 if (attrp && !c11) attr = *attrp;359 if (attrp && !c11) attr = *attrp;
...@@ -265,7 +365,11 @@ int __pthread_create(pthread_t *restrict res, const pthread_attr_t *restrict att...@@ -265,7 +365,11 @@ int __pthread_create(pthread_t *restrict res, const pthread_attr_t *restrict att
265 }365 }
266366
267 if (attr._a_stackaddr) {367 if (attr._a_stackaddr) {
368#ifdef __wasilibc_unmodified_upstream
268 size_t need = libc.tls_size + __pthread_tsd_size;369 size_t need = libc.tls_size + __pthread_tsd_size;
370#else
371 size_t need = tls_size + __pthread_tsd_size;
372#endif
269 size = attr._a_stacksize;373 size = attr._a_stacksize;
270 stack = (void *)(attr._a_stackaddr & -16);374 stack = (void *)(attr._a_stackaddr & -16);
271 stack_limit = (void *)(attr._a_stackaddr - size);375 stack_limit = (void *)(attr._a_stackaddr - size);
...@@ -274,7 +378,11 @@ int __pthread_create(pthread_t *restrict res, const pthread_attr_t *restrict att...@@ -274,7 +378,11 @@ int __pthread_create(pthread_t *restrict res, const pthread_attr_t *restrict att
274 * application's stack space. */378 * application's stack space. */
275 if (need < size/8 && need < 2048) {379 if (need < size/8 && need < 2048) {
276 tsd = stack - __pthread_tsd_size;380 tsd = stack - __pthread_tsd_size;
381#ifdef __wasilibc_unmodified_upstream
277 stack = tsd - libc.tls_size;382 stack = tsd - libc.tls_size;
383#else
384 stack = tsd - tls_size;
385#endif
278 memset(stack, 0, need);386 memset(stack, 0, need);
279 } else {387 } else {
280 size = ROUND(need);388 size = ROUND(need);
...@@ -283,10 +391,15 @@ int __pthread_create(pthread_t *restrict res, const pthread_attr_t *restrict att...@@ -283,10 +391,15 @@ int __pthread_create(pthread_t *restrict res, const pthread_attr_t *restrict att
283 } else {391 } else {
284 guard = ROUND(attr._a_guardsize);392 guard = ROUND(attr._a_guardsize);
285 size = guard + ROUND(attr._a_stacksize393 size = guard + ROUND(attr._a_stacksize
394#ifdef __wasilibc_unmodified_upstream
286 + libc.tls_size + __pthread_tsd_size);395 + libc.tls_size + __pthread_tsd_size);
396#else
397 + tls_size + __pthread_tsd_size);
398#endif
287 }399 }
288400
289 if (!tsd) {401 if (!tsd) {
402#ifdef __wasilibc_unmodified_upstream
290 if (guard) {403 if (guard) {
291 map = __mmap(0, size, PROT_NONE, MAP_PRIVATE|MAP_ANON, -1, 0);404 map = __mmap(0, size, PROT_NONE, MAP_PRIVATE|MAP_ANON, -1, 0);
292 if (map == MAP_FAILED) goto fail;405 if (map == MAP_FAILED) goto fail;
...@@ -299,14 +412,28 @@ int __pthread_create(pthread_t *restrict res, const pthread_attr_t *restrict att...@@ -299,14 +412,28 @@ int __pthread_create(pthread_t *restrict res, const pthread_attr_t *restrict att
299 map = __mmap(0, size, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANON, -1, 0);412 map = __mmap(0, size, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANON, -1, 0);
300 if (map == MAP_FAILED) goto fail;413 if (map == MAP_FAILED) goto fail;
301 }414 }
415#else
416 map = malloc(size);
417 if (!map) goto fail;
418#endif
302 tsd = map + size - __pthread_tsd_size;419 tsd = map + size - __pthread_tsd_size;
303 if (!stack) {420 if (!stack) {
421#ifdef __wasilibc_unmodified_upstream
304 stack = tsd - libc.tls_size;422 stack = tsd - libc.tls_size;
423#else
424 stack = tsd - tls_size;
425#endif
305 stack_limit = map + guard;426 stack_limit = map + guard;
306 }427 }
307 }428 }
308429
430#ifdef __wasilibc_unmodified_upstream
309 new = __copy_tls(tsd - libc.tls_size);431 new = __copy_tls(tsd - libc.tls_size);
432#else
433 new_tls_base = __copy_tls(tsd - tls_size);
434 tls_offset = new_tls_base - tls_base;
435 new = (void*)((uintptr_t)self + tls_offset);
436#endif
310 new->map_base = map;437 new->map_base = map;
311 new->map_size = size;438 new->map_size = size;
312 new->stack = stack;439 new->stack = stack;
...@@ -327,6 +454,7 @@ int __pthread_create(pthread_t *restrict res, const pthread_attr_t *restrict att...@@ -327,6 +454,7 @@ int __pthread_create(pthread_t *restrict res, const pthread_attr_t *restrict att
327 /* Setup argument structure for the new thread on its stack.454 /* Setup argument structure for the new thread on its stack.
328 * It's safe to access from the caller only until the thread455 * It's safe to access from the caller only until the thread
329 * list is unlocked. */456 * list is unlocked. */
457#ifdef __wasilibc_unmodified_upstream
330 stack -= (uintptr_t)stack % sizeof(uintptr_t);458 stack -= (uintptr_t)stack % sizeof(uintptr_t);
331 stack -= sizeof(struct start_args);459 stack -= sizeof(struct start_args);
332 struct start_args *args = (void *)stack;460 struct start_args *args = (void *)stack;
...@@ -345,11 +473,35 @@ int __pthread_create(pthread_t *restrict res, const pthread_attr_t *restrict att...@@ -345,11 +473,35 @@ int __pthread_create(pthread_t *restrict res, const pthread_attr_t *restrict att
345 memcpy(&args->sig_mask, &set, sizeof args->sig_mask);473 memcpy(&args->sig_mask, &set, sizeof args->sig_mask);
346 args->sig_mask[(SIGCANCEL-1)/8/sizeof(long)] &=474 args->sig_mask[(SIGCANCEL-1)/8/sizeof(long)] &=
347 ~(1UL<<((SIGCANCEL-1)%(8*sizeof(long))));475 ~(1UL<<((SIGCANCEL-1)%(8*sizeof(long))));
476#else
477 /* Align the stack to struct start_args */
478 stack -= sizeof(struct start_args);
479 stack -= (uintptr_t)stack % alignof(struct start_args);
480 struct start_args *args = (void *)stack;
481
482 /* Align the stack to 16 and store it */
483 new->stack = (void *)((uintptr_t) stack & -16);
484 /* Correct the stack size */
485 new->stack_size = stack - stack_limit;
486
487 args->start_func = entry;
488 args->start_arg = arg;
489 args->tls_base = (void*)new_tls_base;
490#endif
348491
349 __tl_lock();492 __tl_lock();
350 if (!libc.threads_minus_1++) libc.need_locks = 1;493 if (!libc.threads_minus_1++) libc.need_locks = 1;
494#ifdef __wasilibc_unmodified_upstream
351 ret = __clone((c11 ? start_c11 : start), stack, flags, args, &new->tid, TP_ADJ(new), &__thread_list_lock);495 ret = __clone((c11 ? start_c11 : start), stack, flags, args, &new->tid, TP_ADJ(new), &__thread_list_lock);
352496#else
497 /* Instead of `__clone`, WASI uses a host API to instantiate a new version
498 * of the current module and start executing the entry function. The
499 * wasi-threads specification requires the module to export a
500 * `wasi_thread_start` function, which is invoked with `args`. */
501 ret = __wasi_thread_spawn((void *) args);
502#endif
503
504#ifdef __wasilibc_unmodified_upstream
353 /* All clone failures translate to EAGAIN. If explicit scheduling505 /* All clone failures translate to EAGAIN. If explicit scheduling
354 * was requested, attempt it before unlocking the thread list so506 * was requested, attempt it before unlocking the thread list so
355 * that the failed thread is never exposed and so that we can507 * that the failed thread is never exposed and so that we can
...@@ -364,6 +516,20 @@ int __pthread_create(pthread_t *restrict res, const pthread_attr_t *restrict att...@@ -364,6 +516,20 @@ int __pthread_create(pthread_t *restrict res, const pthread_attr_t *restrict att
364 if (ret)516 if (ret)
365 __wait(&args->control, 0, 3, 0);517 __wait(&args->control, 0, 3, 0);
366 }518 }
519#else
520 /* `wasi_thread_spawn` will either return a host-provided thread ID (TID)
521 * (`>= 0`) or an error code (`< 0`). As in the unmodified version, all
522 * spawn failures translate to EAGAIN; unlike the modified version, there is
523 * no need to "start up" the child thread--the host does this. If the spawn
524 * did succeed, then we store the TID atomically, since this parent thread
525 * is racing with the child thread to set this field; this way, whichever
526 * thread reaches this point first can continue without waiting. */
527 if (ret < 0) {
528 ret = -EAGAIN;
529 } else {
530 atomic_store((atomic_int *) &(new->tid), ret);
531 }
532#endif
367533
368 if (ret >= 0) {534 if (ret >= 0) {
369 new->next = self->next;535 new->next = self->next;
...@@ -374,11 +540,17 @@ int __pthread_create(pthread_t *restrict res, const pthread_attr_t *restrict att...@@ -374,11 +540,17 @@ int __pthread_create(pthread_t *restrict res, const pthread_attr_t *restrict att
374 if (!--libc.threads_minus_1) libc.need_locks = 0;540 if (!--libc.threads_minus_1) libc.need_locks = 0;
375 }541 }
376 __tl_unlock();542 __tl_unlock();
543#ifdef __wasilibc_unmodified_upstream
377 __restore_sigs(&set);544 __restore_sigs(&set);
545#endif
378 __release_ptc();546 __release_ptc();
379547
380 if (ret < 0) {548 if (ret < 0) {
549#ifdef __wasilibc_unmodified_upstream
381 if (map) __munmap(map, size);550 if (map) __munmap(map, size);
551#else
552 free(map);
553#endif
382 return -ret;554 return -ret;
383 }555 }
384556
lib/libc/wasi/libc-top-half/musl/src/thread/pthread_join.c+6
...@@ -1,6 +1,8 @@...@@ -1,6 +1,8 @@
1#define _GNU_SOURCE1#define _GNU_SOURCE
2#include "pthread_impl.h"2#include "pthread_impl.h"
3#ifdef __wasilibc_unmodified_upstream
3#include <sys/mman.h>4#include <sys/mman.h>
5#endif
46
5static void dummy1(pthread_t t)7static void dummy1(pthread_t t)
6{8{
...@@ -21,7 +23,11 @@ static int __pthread_timedjoin_np(pthread_t t, void **res, const struct timespec...@@ -21,7 +23,11 @@ static int __pthread_timedjoin_np(pthread_t t, void **res, const struct timespec
21 if (r == ETIMEDOUT || r == EINVAL) return r;23 if (r == ETIMEDOUT || r == EINVAL) return r;
22 __tl_sync(t);24 __tl_sync(t);
23 if (res) *res = t->result;25 if (res) *res = t->result;
26#ifdef __wasilibc_unmodified_upstream
24 if (t->map_base) __munmap(t->map_base, t->map_size);27 if (t->map_base) __munmap(t->map_base, t->map_size);
28#else
29 if (t->map_base) free(t->map_base);
30#endif
25 return 0;31 return 0;
26}32}
2733
lib/libc/wasi/libc-top-half/musl/src/thread/pthread_mutex_destroy.c+8
...@@ -2,9 +2,17 @@...@@ -2,9 +2,17 @@
22
3int pthread_mutex_destroy(pthread_mutex_t *mutex)3int pthread_mutex_destroy(pthread_mutex_t *mutex)
4{4{
5#ifdef __wasilibc_unmodified_upstream
5 /* If the mutex being destroyed is process-shared and has nontrivial6 /* If the mutex being destroyed is process-shared and has nontrivial
6 * type (tracking ownership), it might be in the pending slot of a7 * type (tracking ownership), it might be in the pending slot of a
7 * robust_list; wait for quiescence. */8 * robust_list; wait for quiescence. */
8 if (mutex->_m_type > 128) __vm_wait();9 if (mutex->_m_type > 128) __vm_wait();
10#else
11 /* For now, wasi-libc chooses to avoid implementing robust mutex support
12 * though this could be added later. The error code indicates that the
13 * mutex was an invalid type, but it would be more accurate as
14 * "unimplemented". */
15 if (mutex->_m_type > 128) return EINVAL;
16#endif
9 return 0;17 return 0;
10}18}
lib/libc/wasi/libc-top-half/musl/src/thread/pthread_mutex_timedlock.c+5-1
...@@ -1,5 +1,6 @@...@@ -1,5 +1,6 @@
1#include "pthread_impl.h"1#include "pthread_impl.h"
22
3#ifdef __wasilibc_unmodified_upstream
3#define IS32BIT(x) !((x)+0x80000000ULL>>32)4#define IS32BIT(x) !((x)+0x80000000ULL>>32)
4#define CLAMP(x) (int)(IS32BIT(x) ? (x) : 0x7fffffffU+((0ULL+(x))>>63))5#define CLAMP(x) (int)(IS32BIT(x) ? (x) : 0x7fffffffU+((0ULL+(x))>>63))
56
...@@ -52,6 +53,7 @@ static int pthread_mutex_timedlock_pi(pthread_mutex_t *restrict m, const struct...@@ -52,6 +53,7 @@ static int pthread_mutex_timedlock_pi(pthread_mutex_t *restrict m, const struct
52 while (e != ETIMEDOUT);53 while (e != ETIMEDOUT);
53 return e;54 return e;
54}55}
56#endif
5557
56int __pthread_mutex_timedlock(pthread_mutex_t *restrict m, const struct timespec *restrict at)58int __pthread_mutex_timedlock(pthread_mutex_t *restrict m, const struct timespec *restrict at)
57{59{
...@@ -65,8 +67,10 @@ int __pthread_mutex_timedlock(pthread_mutex_t *restrict m, const struct timespec...@@ -65,8 +67,10 @@ int __pthread_mutex_timedlock(pthread_mutex_t *restrict m, const struct timespec
65 r = __pthread_mutex_trylock(m);67 r = __pthread_mutex_trylock(m);
66 if (r != EBUSY) return r;68 if (r != EBUSY) return r;
6769
70#ifdef __wasilibc_unmodified_upstream
68 if (type&8) return pthread_mutex_timedlock_pi(m, at);71 if (type&8) return pthread_mutex_timedlock_pi(m, at);
69 72#endif
73
70 int spins = 100;74 int spins = 100;
71 while (spins-- && m->_m_lock && !m->_m_waiters) a_spin();75 while (spins-- && m->_m_lock && !m->_m_waiters) a_spin();
7276
lib/libc/wasi/libc-top-half/musl/src/thread/pthread_mutex_trylock.c+4
...@@ -27,7 +27,9 @@ int __pthread_mutex_trylock_owner(pthread_mutex_t *m)...@@ -27,7 +27,9 @@ int __pthread_mutex_trylock_owner(pthread_mutex_t *m)
27 if (type & 128) {27 if (type & 128) {
28 if (!self->robust_list.off) {28 if (!self->robust_list.off) {
29 self->robust_list.off = (char*)&m->_m_lock-(char *)&m->_m_next;29 self->robust_list.off = (char*)&m->_m_lock-(char *)&m->_m_next;
30#ifdef __wasilibc_unmodified_upstream
30 __syscall(SYS_set_robust_list, &self->robust_list, 3*sizeof(long));31 __syscall(SYS_set_robust_list, &self->robust_list, 3*sizeof(long));
32#endif
31 }33 }
32 if (m->_m_waiters) tid |= 0x80000000;34 if (m->_m_waiters) tid |= 0x80000000;
33 self->robust_list.pending = &m->_m_next;35 self->robust_list.pending = &m->_m_next;
...@@ -43,7 +45,9 @@ int __pthread_mutex_trylock_owner(pthread_mutex_t *m)...@@ -43,7 +45,9 @@ int __pthread_mutex_trylock_owner(pthread_mutex_t *m)
43success:45success:
44 if ((type&8) && m->_m_waiters) {46 if ((type&8) && m->_m_waiters) {
45 int priv = (type & 128) ^ 128;47 int priv = (type & 128) ^ 128;
48#ifdef __wasilibc_unmodified_upstream
46 __syscall(SYS_futex, &m->_m_lock, FUTEX_UNLOCK_PI|priv);49 __syscall(SYS_futex, &m->_m_lock, FUTEX_UNLOCK_PI|priv);
50#endif
47 self->robust_list.pending = 0;51 self->robust_list.pending = 0;
48 return (type&4) ? ENOTRECOVERABLE : EBUSY;52 return (type&4) ? ENOTRECOVERABLE : EBUSY;
49 }53 }
lib/libc/wasi/libc-top-half/musl/src/thread/pthread_mutex_unlock.c+8
...@@ -22,7 +22,9 @@ int __pthread_mutex_unlock(pthread_mutex_t *m)...@@ -22,7 +22,9 @@ int __pthread_mutex_unlock(pthread_mutex_t *m)
22 new = 0x7fffffff;22 new = 0x7fffffff;
23 if (!priv) {23 if (!priv) {
24 self->robust_list.pending = &m->_m_next;24 self->robust_list.pending = &m->_m_next;
25#ifdef __wasilibc_unmodified_upstream
25 __vm_lock();26 __vm_lock();
27#endif
26 }28 }
27 volatile void *prev = m->_m_prev;29 volatile void *prev = m->_m_prev;
28 volatile void *next = m->_m_next;30 volatile void *next = m->_m_next;
...@@ -30,6 +32,7 @@ int __pthread_mutex_unlock(pthread_mutex_t *m)...@@ -30,6 +32,7 @@ int __pthread_mutex_unlock(pthread_mutex_t *m)
30 if (next != &self->robust_list.head) *(volatile void *volatile *)32 if (next != &self->robust_list.head) *(volatile void *volatile *)
31 ((char *)next - sizeof(void *)) = prev;33 ((char *)next - sizeof(void *)) = prev;
32 }34 }
35#ifdef __wasilibc_unmodified_upstream
33 if (type&8) {36 if (type&8) {
34 if (old<0 || a_cas(&m->_m_lock, old, new)!=old) {37 if (old<0 || a_cas(&m->_m_lock, old, new)!=old) {
35 if (new) a_store(&m->_m_waiters, -1);38 if (new) a_store(&m->_m_waiters, -1);
...@@ -40,9 +43,14 @@ int __pthread_mutex_unlock(pthread_mutex_t *m)...@@ -40,9 +43,14 @@ int __pthread_mutex_unlock(pthread_mutex_t *m)
40 } else {43 } else {
41 cont = a_swap(&m->_m_lock, new);44 cont = a_swap(&m->_m_lock, new);
42 }45 }
46#else
47 cont = a_swap(&m->_m_lock, new);
48#endif
43 if (type != PTHREAD_MUTEX_NORMAL && !priv) {49 if (type != PTHREAD_MUTEX_NORMAL && !priv) {
44 self->robust_list.pending = 0;50 self->robust_list.pending = 0;
51#ifdef __wasilibc_unmodified_upstream
45 __vm_unlock();52 __vm_unlock();
53#endif
46 }54 }
47 if (waiters || cont<0)55 if (waiters || cont<0)
48 __wake(&m->_m_lock, 1, priv);56 __wake(&m->_m_lock, 1, priv);
lib/libc/wasi/libc-top-half/musl/src/thread/pthread_mutexattr_setprotocol.c+4
...@@ -11,6 +11,7 @@ int pthread_mutexattr_setprotocol(pthread_mutexattr_t *a, int protocol)...@@ -11,6 +11,7 @@ int pthread_mutexattr_setprotocol(pthread_mutexattr_t *a, int protocol)
11 a->__attr &= ~8;11 a->__attr &= ~8;
12 return 0;12 return 0;
13 case PTHREAD_PRIO_INHERIT:13 case PTHREAD_PRIO_INHERIT:
14#ifdef __wasilibc_unmodified_upstream
14 r = check_pi_result;15 r = check_pi_result;
15 if (r < 0) {16 if (r < 0) {
16 volatile int lk = 0;17 volatile int lk = 0;
...@@ -20,6 +21,9 @@ int pthread_mutexattr_setprotocol(pthread_mutexattr_t *a, int protocol)...@@ -20,6 +21,9 @@ int pthread_mutexattr_setprotocol(pthread_mutexattr_t *a, int protocol)
20 if (r) return r;21 if (r) return r;
21 a->__attr |= 8;22 a->__attr |= 8;
22 return 0;23 return 0;
24#else
25 return ENOTSUP;
26#endif
23 case PTHREAD_PRIO_PROTECT:27 case PTHREAD_PRIO_PROTECT:
24 return ENOTSUP;28 return ENOTSUP;
25 default:29 default:
lib/libc/wasi/libc-top-half/musl/src/thread/pthread_mutexattr_setrobust.c+4
...@@ -5,6 +5,7 @@ static volatile int check_robust_result = -1;...@@ -5,6 +5,7 @@ static volatile int check_robust_result = -1;
55
6int pthread_mutexattr_setrobust(pthread_mutexattr_t *a, int robust)6int pthread_mutexattr_setrobust(pthread_mutexattr_t *a, int robust)
7{7{
8#ifdef __wasilibc_unmodified_upstream
8 if (robust > 1U) return EINVAL;9 if (robust > 1U) return EINVAL;
9 if (robust) {10 if (robust) {
10 int r = check_robust_result;11 int r = check_robust_result;
...@@ -20,4 +21,7 @@ int pthread_mutexattr_setrobust(pthread_mutexattr_t *a, int robust)...@@ -20,4 +21,7 @@ int pthread_mutexattr_setrobust(pthread_mutexattr_t *a, int robust)
20 }21 }
21 a->__attr &= ~4;22 a->__attr &= ~4;
22 return 0;23 return 0;
24#else
25 return EINVAL;
26#endif
23}27}
lib/libc/wasi/libc-top-half/musl/src/thread/pthread_self.c+5
...@@ -1,6 +1,11 @@...@@ -1,6 +1,11 @@
1#include "pthread_impl.h"1#include "pthread_impl.h"
2#include <threads.h>2#include <threads.h>
33
4#if !defined(__wasilibc_unmodified_upstream) && defined(__wasm__) && \
5 defined(_REENTRANT)
6_Thread_local struct pthread __wasilibc_pthread_self;
7#endif
8
4static pthread_t __pthread_self_internal()9static pthread_t __pthread_self_internal()
5{10{
6 return __pthread_self();11 return __pthread_self();
lib/libc/wasi/libc-top-half/musl/src/thread/pthread_setcancelstate.c+2
...@@ -2,10 +2,12 @@...@@ -2,10 +2,12 @@
22
3int __pthread_setcancelstate(int new, int *old)3int __pthread_setcancelstate(int new, int *old)
4{4{
5#if defined(__wasilibc_unmodified_upstream) || defined(_REENTRANT)
5 if (new > 2U) return EINVAL;6 if (new > 2U) return EINVAL;
6 struct pthread *self = __pthread_self();7 struct pthread *self = __pthread_self();
7 if (old) *old = self->canceldisable;8 if (old) *old = self->canceldisable;
8 self->canceldisable = new;9 self->canceldisable = new;
10#endif
9 return 0;11 return 0;
10}12}
1113
src/wasi_libc.zig+109-95
...@@ -100,20 +100,10 @@ pub fn buildCRTFile(comp: *Compilation, crt_file: CRTFile) !void {...@@ -100,20 +100,10 @@ pub fn buildCRTFile(comp: *Compilation, crt_file: CRTFile) !void {
100 var libc_sources = std.ArrayList(Compilation.CSourceFile).init(arena);100 var libc_sources = std.ArrayList(Compilation.CSourceFile).init(arena);
101101
102 {102 {
103 // Compile dlmalloc.103 // Compile emmalloc.
104 var args = std.ArrayList([]const u8).init(arena);104 var args = std.ArrayList([]const u8).init(arena);
105 try addCCArgs(comp, arena, &args, true);105 try addCCArgs(comp, arena, &args, true);
106 try args.appendSlice(&[_][]const u8{106 for (emmalloc_src_files) |file_path| {
107 "-I",
108 try comp.zig_lib_directory.join(arena, &[_][]const u8{
109 "libc",
110 "wasi",
111 "dlmalloc",
112 "include",
113 }),
114 });
115
116 for (dlmalloc_src_files) |file_path| {
117 try libc_sources.append(.{107 try libc_sources.append(.{
118 .src_path = try comp.zig_lib_directory.join(arena, &[_][]const u8{108 .src_path = try comp.zig_lib_directory.join(arena, &[_][]const u8{
119 "libc", try sanitize(arena, file_path),109 "libc", try sanitize(arena, file_path),
...@@ -323,6 +313,26 @@ fn addLibcBottomHalfIncludes(...@@ -323,6 +313,26 @@ fn addLibcBottomHalfIncludes(
323 "cloudlibc",313 "cloudlibc",
324 "src",314 "src",
325 }),315 }),
316
317 "-I",
318 try comp.zig_lib_directory.join(arena, &[_][]const u8{
319 "libc",
320 "wasi",
321 "libc-top-half",
322 "musl",
323 "src",
324 "include",
325 }),
326
327 "-I",
328 try comp.zig_lib_directory.join(arena, &[_][]const u8{
329 "libc",
330 "wasi",
331 "libc-top-half",
332 "musl",
333 "src",
334 "internal",
335 }),
326 });336 });
327}337}
328338
...@@ -383,21 +393,21 @@ fn addLibcTopHalfIncludes(...@@ -383,21 +393,21 @@ fn addLibcTopHalfIncludes(
383 });393 });
384}394}
385395
386const dlmalloc_src_files = [_][]const u8{396const emmalloc_src_files = [_][]const u8{
387 "wasi/dlmalloc/src/dlmalloc.c",397 "wasi/emmalloc/emmalloc.c",
388};398};
389399
390const libc_bottom_half_src_files = [_][]const u8{400const libc_bottom_half_src_files = [_][]const u8{
391 "wasi/libc-bottom-half/cloudlibc/src/libc/dirent/closedir.c",401 "wasi/libc-bottom-half/cloudlibc/src/libc/dirent/closedir.c",
392 "wasi/libc-bottom-half/cloudlibc/src/libc/dirent/dirfd.c",402 "wasi/libc-bottom-half/cloudlibc/src/libc/dirent/dirfd.c",
393 "wasi/libc-bottom-half/cloudlibc/src/libc/dirent/fdopendir.c",
394 "wasi/libc-bottom-half/cloudlibc/src/libc/dirent/readdir.c",
395 "wasi/libc-bottom-half/cloudlibc/src/libc/dirent/scandirat.c",
396 "wasi/libc-bottom-half/cloudlibc/src/libc/dirent/telldir.c",
397 "wasi/libc-bottom-half/cloudlibc/src/libc/dirent/fdclosedir.c",403 "wasi/libc-bottom-half/cloudlibc/src/libc/dirent/fdclosedir.c",
404 "wasi/libc-bottom-half/cloudlibc/src/libc/dirent/fdopendir.c",
398 "wasi/libc-bottom-half/cloudlibc/src/libc/dirent/opendirat.c",405 "wasi/libc-bottom-half/cloudlibc/src/libc/dirent/opendirat.c",
406 "wasi/libc-bottom-half/cloudlibc/src/libc/dirent/readdir.c",
399 "wasi/libc-bottom-half/cloudlibc/src/libc/dirent/rewinddir.c",407 "wasi/libc-bottom-half/cloudlibc/src/libc/dirent/rewinddir.c",
408 "wasi/libc-bottom-half/cloudlibc/src/libc/dirent/scandirat.c",
400 "wasi/libc-bottom-half/cloudlibc/src/libc/dirent/seekdir.c",409 "wasi/libc-bottom-half/cloudlibc/src/libc/dirent/seekdir.c",
410 "wasi/libc-bottom-half/cloudlibc/src/libc/dirent/telldir.c",
401 "wasi/libc-bottom-half/cloudlibc/src/libc/errno/errno.c",411 "wasi/libc-bottom-half/cloudlibc/src/libc/errno/errno.c",
402 "wasi/libc-bottom-half/cloudlibc/src/libc/fcntl/fcntl.c",412 "wasi/libc-bottom-half/cloudlibc/src/libc/fcntl/fcntl.c",
403 "wasi/libc-bottom-half/cloudlibc/src/libc/fcntl/openat.c",413 "wasi/libc-bottom-half/cloudlibc/src/libc/fcntl/openat.c",
...@@ -414,8 +424,8 @@ const libc_bottom_half_src_files = [_][]const u8{...@@ -414,8 +424,8 @@ const libc_bottom_half_src_files = [_][]const u8{
414 "wasi/libc-bottom-half/cloudlibc/src/libc/sys/socket/recv.c",424 "wasi/libc-bottom-half/cloudlibc/src/libc/sys/socket/recv.c",
415 "wasi/libc-bottom-half/cloudlibc/src/libc/sys/socket/send.c",425 "wasi/libc-bottom-half/cloudlibc/src/libc/sys/socket/send.c",
416 "wasi/libc-bottom-half/cloudlibc/src/libc/sys/socket/shutdown.c",426 "wasi/libc-bottom-half/cloudlibc/src/libc/sys/socket/shutdown.c",
417 "wasi/libc-bottom-half/cloudlibc/src/libc/sys/stat/fstatat.c",
418 "wasi/libc-bottom-half/cloudlibc/src/libc/sys/stat/fstat.c",427 "wasi/libc-bottom-half/cloudlibc/src/libc/sys/stat/fstat.c",
428 "wasi/libc-bottom-half/cloudlibc/src/libc/sys/stat/fstatat.c",
419 "wasi/libc-bottom-half/cloudlibc/src/libc/sys/stat/futimens.c",429 "wasi/libc-bottom-half/cloudlibc/src/libc/sys/stat/futimens.c",
420 "wasi/libc-bottom-half/cloudlibc/src/libc/sys/stat/mkdirat.c",430 "wasi/libc-bottom-half/cloudlibc/src/libc/sys/stat/mkdirat.c",
421 "wasi/libc-bottom-half/cloudlibc/src/libc/sys/stat/utimensat.c",431 "wasi/libc-bottom-half/cloudlibc/src/libc/sys/stat/utimensat.c",
...@@ -424,13 +434,11 @@ const libc_bottom_half_src_files = [_][]const u8{...@@ -424,13 +434,11 @@ const libc_bottom_half_src_files = [_][]const u8{
424 "wasi/libc-bottom-half/cloudlibc/src/libc/sys/uio/pwritev.c",434 "wasi/libc-bottom-half/cloudlibc/src/libc/sys/uio/pwritev.c",
425 "wasi/libc-bottom-half/cloudlibc/src/libc/sys/uio/readv.c",435 "wasi/libc-bottom-half/cloudlibc/src/libc/sys/uio/readv.c",
426 "wasi/libc-bottom-half/cloudlibc/src/libc/sys/uio/writev.c",436 "wasi/libc-bottom-half/cloudlibc/src/libc/sys/uio/writev.c",
437 "wasi/libc-bottom-half/cloudlibc/src/libc/time/CLOCK_MONOTONIC.c",
438 "wasi/libc-bottom-half/cloudlibc/src/libc/time/CLOCK_REALTIME.c",
427 "wasi/libc-bottom-half/cloudlibc/src/libc/time/clock_getres.c",439 "wasi/libc-bottom-half/cloudlibc/src/libc/time/clock_getres.c",
428 "wasi/libc-bottom-half/cloudlibc/src/libc/time/clock_gettime.c",440 "wasi/libc-bottom-half/cloudlibc/src/libc/time/clock_gettime.c",
429 "wasi/libc-bottom-half/cloudlibc/src/libc/time/CLOCK_MONOTONIC.c",
430 "wasi/libc-bottom-half/cloudlibc/src/libc/time/clock_nanosleep.c",441 "wasi/libc-bottom-half/cloudlibc/src/libc/time/clock_nanosleep.c",
431 "wasi/libc-bottom-half/cloudlibc/src/libc/time/CLOCK_PROCESS_CPUTIME_ID.c",
432 "wasi/libc-bottom-half/cloudlibc/src/libc/time/CLOCK_REALTIME.c",
433 "wasi/libc-bottom-half/cloudlibc/src/libc/time/CLOCK_THREAD_CPUTIME_ID.c",
434 "wasi/libc-bottom-half/cloudlibc/src/libc/time/nanosleep.c",442 "wasi/libc-bottom-half/cloudlibc/src/libc/time/nanosleep.c",
435 "wasi/libc-bottom-half/cloudlibc/src/libc/time/time.c",443 "wasi/libc-bottom-half/cloudlibc/src/libc/time/time.c",
436 "wasi/libc-bottom-half/cloudlibc/src/libc/unistd/close.c",444 "wasi/libc-bottom-half/cloudlibc/src/libc/unistd/close.c",
...@@ -449,7 +457,17 @@ const libc_bottom_half_src_files = [_][]const u8{...@@ -449,7 +457,17 @@ const libc_bottom_half_src_files = [_][]const u8{
449 "wasi/libc-bottom-half/cloudlibc/src/libc/unistd/unlinkat.c",457 "wasi/libc-bottom-half/cloudlibc/src/libc/unistd/unlinkat.c",
450 "wasi/libc-bottom-half/cloudlibc/src/libc/unistd/usleep.c",458 "wasi/libc-bottom-half/cloudlibc/src/libc/unistd/usleep.c",
451 "wasi/libc-bottom-half/cloudlibc/src/libc/unistd/write.c",459 "wasi/libc-bottom-half/cloudlibc/src/libc/unistd/write.c",
460 "wasi/libc-bottom-half/sources/__main_void.c",
461 "wasi/libc-bottom-half/sources/__wasilibc_dt.c",
462 "wasi/libc-bottom-half/sources/__wasilibc_environ.c",
463 "wasi/libc-bottom-half/sources/__wasilibc_fd_renumber.c",
464 "wasi/libc-bottom-half/sources/__wasilibc_initialize_environ.c",
465 "wasi/libc-bottom-half/sources/__wasilibc_real.c",
466 "wasi/libc-bottom-half/sources/__wasilibc_rmdirat.c",
467 "wasi/libc-bottom-half/sources/__wasilibc_tell.c",
468 "wasi/libc-bottom-half/sources/__wasilibc_unlinkat.c",
452 "wasi/libc-bottom-half/sources/abort.c",469 "wasi/libc-bottom-half/sources/abort.c",
470 "wasi/libc-bottom-half/sources/accept.c",
453 "wasi/libc-bottom-half/sources/at_fdcwd.c",471 "wasi/libc-bottom-half/sources/at_fdcwd.c",
454 "wasi/libc-bottom-half/sources/complex-builtins.c",472 "wasi/libc-bottom-half/sources/complex-builtins.c",
455 "wasi/libc-bottom-half/sources/environ.c",473 "wasi/libc-bottom-half/sources/environ.c",
...@@ -457,22 +475,13 @@ const libc_bottom_half_src_files = [_][]const u8{...@@ -457,22 +475,13 @@ const libc_bottom_half_src_files = [_][]const u8{
457 "wasi/libc-bottom-half/sources/getcwd.c",475 "wasi/libc-bottom-half/sources/getcwd.c",
458 "wasi/libc-bottom-half/sources/getentropy.c",476 "wasi/libc-bottom-half/sources/getentropy.c",
459 "wasi/libc-bottom-half/sources/isatty.c",477 "wasi/libc-bottom-half/sources/isatty.c",
460 "wasi/libc-bottom-half/sources/__main_argc_argv.c",478 "wasi/libc-bottom-half/sources/math/fmin-fmax.c",
461 "wasi/libc-bottom-half/sources/__main_void.c",479 "wasi/libc-bottom-half/sources/math/math-builtins.c",
462 "wasi/libc-bottom-half/sources/__original_main.c",
463 "wasi/libc-bottom-half/sources/posix.c",480 "wasi/libc-bottom-half/sources/posix.c",
464 "wasi/libc-bottom-half/sources/preopens.c",481 "wasi/libc-bottom-half/sources/preopens.c",
465 "wasi/libc-bottom-half/sources/reallocarray.c",482 "wasi/libc-bottom-half/sources/reallocarray.c",
466 "wasi/libc-bottom-half/sources/sbrk.c",483 "wasi/libc-bottom-half/sources/sbrk.c",
467 "wasi/libc-bottom-half/sources/truncate.c",484 "wasi/libc-bottom-half/sources/truncate.c",
468 "wasi/libc-bottom-half/sources/__wasilibc_fd_renumber.c",
469 "wasi/libc-bottom-half/sources/__wasilibc_initialize_environ.c",
470 "wasi/libc-bottom-half/sources/__wasilibc_real.c",
471 "wasi/libc-bottom-half/sources/__wasilibc_rmdirat.c",
472 "wasi/libc-bottom-half/sources/__wasilibc_tell.c",
473 "wasi/libc-bottom-half/sources/__wasilibc_unlinkat.c",
474 "wasi/libc-bottom-half/sources/math/fmin-fmax.c",
475 "wasi/libc-bottom-half/sources/math/math-builtins.c",
476 // TODO apparently, due to a bug in LLD, the weak refs are garbled485 // TODO apparently, due to a bug in LLD, the weak refs are garbled
477 // unless chdir.c is last in the archive486 // unless chdir.c is last in the archive
478 // https://reviews.llvm.org/D85567487 // https://reviews.llvm.org/D85567
...@@ -546,19 +555,34 @@ const libc_top_half_src_files = [_][]const u8{...@@ -546,19 +555,34 @@ const libc_top_half_src_files = [_][]const u8{
546 "wasi/libc-top-half/musl/src/env/setenv.c",555 "wasi/libc-top-half/musl/src/env/setenv.c",
547 "wasi/libc-top-half/musl/src/env/unsetenv.c",556 "wasi/libc-top-half/musl/src/env/unsetenv.c",
548 "wasi/libc-top-half/musl/src/unistd/posix_close.c",557 "wasi/libc-top-half/musl/src/unistd/posix_close.c",
558 "wasi/libc-top-half/musl/src/stat/futimesat.c",
559 "wasi/libc-top-half/musl/src/legacy/getpagesize.c",
560 "wasi/libc-top-half/musl/src/thread/thrd_sleep.c",
549 "wasi/libc-top-half/musl/src/internal/defsysinfo.c",561 "wasi/libc-top-half/musl/src/internal/defsysinfo.c",
550 "wasi/libc-top-half/musl/src/internal/floatscan.c",562 "wasi/libc-top-half/musl/src/internal/floatscan.c",
551 "wasi/libc-top-half/musl/src/internal/intscan.c",563 "wasi/libc-top-half/musl/src/internal/intscan.c",
552 "wasi/libc-top-half/musl/src/internal/libc.c",564 "wasi/libc-top-half/musl/src/internal/libc.c",
553 "wasi/libc-top-half/musl/src/internal/shgetc.c",565 "wasi/libc-top-half/musl/src/internal/shgetc.c",
566 "wasi/libc-top-half/musl/src/stdio/__fclose_ca.c",
567 "wasi/libc-top-half/musl/src/stdio/__fdopen.c",
568 "wasi/libc-top-half/musl/src/stdio/__fmodeflags.c",
569 "wasi/libc-top-half/musl/src/stdio/__fopen_rb_ca.c",
570 "wasi/libc-top-half/musl/src/stdio/__overflow.c",
571 "wasi/libc-top-half/musl/src/stdio/__stdio_close.c",
572 "wasi/libc-top-half/musl/src/stdio/__stdio_exit.c",
573 "wasi/libc-top-half/musl/src/stdio/__stdio_read.c",
574 "wasi/libc-top-half/musl/src/stdio/__stdio_seek.c",
575 "wasi/libc-top-half/musl/src/stdio/__stdio_write.c",
576 "wasi/libc-top-half/musl/src/stdio/__stdout_write.c",
577 "wasi/libc-top-half/musl/src/stdio/__toread.c",
578 "wasi/libc-top-half/musl/src/stdio/__towrite.c",
579 "wasi/libc-top-half/musl/src/stdio/__uflow.c",
554 "wasi/libc-top-half/musl/src/stdio/asprintf.c",580 "wasi/libc-top-half/musl/src/stdio/asprintf.c",
555 "wasi/libc-top-half/musl/src/stdio/clearerr.c",581 "wasi/libc-top-half/musl/src/stdio/clearerr.c",
556 "wasi/libc-top-half/musl/src/stdio/dprintf.c",582 "wasi/libc-top-half/musl/src/stdio/dprintf.c",
557 "wasi/libc-top-half/musl/src/stdio/ext2.c",
558 "wasi/libc-top-half/musl/src/stdio/ext.c",583 "wasi/libc-top-half/musl/src/stdio/ext.c",
584 "wasi/libc-top-half/musl/src/stdio/ext2.c",
559 "wasi/libc-top-half/musl/src/stdio/fclose.c",585 "wasi/libc-top-half/musl/src/stdio/fclose.c",
560 "wasi/libc-top-half/musl/src/stdio/__fclose_ca.c",
561 "wasi/libc-top-half/musl/src/stdio/__fdopen.c",
562 "wasi/libc-top-half/musl/src/stdio/feof.c",586 "wasi/libc-top-half/musl/src/stdio/feof.c",
563 "wasi/libc-top-half/musl/src/stdio/ferror.c",587 "wasi/libc-top-half/musl/src/stdio/ferror.c",
564 "wasi/libc-top-half/musl/src/stdio/fflush.c",588 "wasi/libc-top-half/musl/src/stdio/fflush.c",
...@@ -570,10 +594,8 @@ const libc_top_half_src_files = [_][]const u8{...@@ -570,10 +594,8 @@ const libc_top_half_src_files = [_][]const u8{
570 "wasi/libc-top-half/musl/src/stdio/fgetws.c",594 "wasi/libc-top-half/musl/src/stdio/fgetws.c",
571 "wasi/libc-top-half/musl/src/stdio/fileno.c",595 "wasi/libc-top-half/musl/src/stdio/fileno.c",
572 "wasi/libc-top-half/musl/src/stdio/fmemopen.c",596 "wasi/libc-top-half/musl/src/stdio/fmemopen.c",
573 "wasi/libc-top-half/musl/src/stdio/__fmodeflags.c",
574 "wasi/libc-top-half/musl/src/stdio/fopen.c",597 "wasi/libc-top-half/musl/src/stdio/fopen.c",
575 "wasi/libc-top-half/musl/src/stdio/fopencookie.c",598 "wasi/libc-top-half/musl/src/stdio/fopencookie.c",
576 "wasi/libc-top-half/musl/src/stdio/__fopen_rb_ca.c",
577 "wasi/libc-top-half/musl/src/stdio/fprintf.c",599 "wasi/libc-top-half/musl/src/stdio/fprintf.c",
578 "wasi/libc-top-half/musl/src/stdio/fputc.c",600 "wasi/libc-top-half/musl/src/stdio/fputc.c",
579 "wasi/libc-top-half/musl/src/stdio/fputs.c",601 "wasi/libc-top-half/musl/src/stdio/fputs.c",
...@@ -590,25 +612,24 @@ const libc_top_half_src_files = [_][]const u8{...@@ -590,25 +612,24 @@ const libc_top_half_src_files = [_][]const u8{
590 "wasi/libc-top-half/musl/src/stdio/fwrite.c",612 "wasi/libc-top-half/musl/src/stdio/fwrite.c",
591 "wasi/libc-top-half/musl/src/stdio/fwscanf.c",613 "wasi/libc-top-half/musl/src/stdio/fwscanf.c",
592 "wasi/libc-top-half/musl/src/stdio/getc.c",614 "wasi/libc-top-half/musl/src/stdio/getc.c",
615 "wasi/libc-top-half/musl/src/stdio/getc_unlocked.c",
593 "wasi/libc-top-half/musl/src/stdio/getchar.c",616 "wasi/libc-top-half/musl/src/stdio/getchar.c",
594 "wasi/libc-top-half/musl/src/stdio/getchar_unlocked.c",617 "wasi/libc-top-half/musl/src/stdio/getchar_unlocked.c",
595 "wasi/libc-top-half/musl/src/stdio/getc_unlocked.c",
596 "wasi/libc-top-half/musl/src/stdio/getdelim.c",618 "wasi/libc-top-half/musl/src/stdio/getdelim.c",
597 "wasi/libc-top-half/musl/src/stdio/getline.c",619 "wasi/libc-top-half/musl/src/stdio/getline.c",
598 "wasi/libc-top-half/musl/src/stdio/getw.c",620 "wasi/libc-top-half/musl/src/stdio/getw.c",
599 "wasi/libc-top-half/musl/src/stdio/getwc.c",621 "wasi/libc-top-half/musl/src/stdio/getwc.c",
600 "wasi/libc-top-half/musl/src/stdio/getwchar.c",622 "wasi/libc-top-half/musl/src/stdio/getwchar.c",
601 "wasi/libc-top-half/musl/src/stdio/ofl_add.c",
602 "wasi/libc-top-half/musl/src/stdio/ofl.c",623 "wasi/libc-top-half/musl/src/stdio/ofl.c",
624 "wasi/libc-top-half/musl/src/stdio/ofl_add.c",
603 "wasi/libc-top-half/musl/src/stdio/open_memstream.c",625 "wasi/libc-top-half/musl/src/stdio/open_memstream.c",
604 "wasi/libc-top-half/musl/src/stdio/open_wmemstream.c",626 "wasi/libc-top-half/musl/src/stdio/open_wmemstream.c",
605 "wasi/libc-top-half/musl/src/stdio/__overflow.c",
606 "wasi/libc-top-half/musl/src/stdio/perror.c",627 "wasi/libc-top-half/musl/src/stdio/perror.c",
607 "wasi/libc-top-half/musl/src/stdio/printf.c",628 "wasi/libc-top-half/musl/src/stdio/printf.c",
608 "wasi/libc-top-half/musl/src/stdio/putc.c",629 "wasi/libc-top-half/musl/src/stdio/putc.c",
630 "wasi/libc-top-half/musl/src/stdio/putc_unlocked.c",
609 "wasi/libc-top-half/musl/src/stdio/putchar.c",631 "wasi/libc-top-half/musl/src/stdio/putchar.c",
610 "wasi/libc-top-half/musl/src/stdio/putchar_unlocked.c",632 "wasi/libc-top-half/musl/src/stdio/putchar_unlocked.c",
611 "wasi/libc-top-half/musl/src/stdio/putc_unlocked.c",
612 "wasi/libc-top-half/musl/src/stdio/puts.c",633 "wasi/libc-top-half/musl/src/stdio/puts.c",
613 "wasi/libc-top-half/musl/src/stdio/putw.c",634 "wasi/libc-top-half/musl/src/stdio/putw.c",
614 "wasi/libc-top-half/musl/src/stdio/putwc.c",635 "wasi/libc-top-half/musl/src/stdio/putwc.c",
...@@ -624,18 +645,9 @@ const libc_top_half_src_files = [_][]const u8{...@@ -624,18 +645,9 @@ const libc_top_half_src_files = [_][]const u8{
624 "wasi/libc-top-half/musl/src/stdio/sscanf.c",645 "wasi/libc-top-half/musl/src/stdio/sscanf.c",
625 "wasi/libc-top-half/musl/src/stdio/stderr.c",646 "wasi/libc-top-half/musl/src/stdio/stderr.c",
626 "wasi/libc-top-half/musl/src/stdio/stdin.c",647 "wasi/libc-top-half/musl/src/stdio/stdin.c",
627 "wasi/libc-top-half/musl/src/stdio/__stdio_close.c",
628 "wasi/libc-top-half/musl/src/stdio/__stdio_exit.c",
629 "wasi/libc-top-half/musl/src/stdio/__stdio_read.c",
630 "wasi/libc-top-half/musl/src/stdio/__stdio_seek.c",
631 "wasi/libc-top-half/musl/src/stdio/__stdio_write.c",
632 "wasi/libc-top-half/musl/src/stdio/stdout.c",648 "wasi/libc-top-half/musl/src/stdio/stdout.c",
633 "wasi/libc-top-half/musl/src/stdio/__stdout_write.c",
634 "wasi/libc-top-half/musl/src/stdio/swprintf.c",649 "wasi/libc-top-half/musl/src/stdio/swprintf.c",
635 "wasi/libc-top-half/musl/src/stdio/swscanf.c",650 "wasi/libc-top-half/musl/src/stdio/swscanf.c",
636 "wasi/libc-top-half/musl/src/stdio/__toread.c",
637 "wasi/libc-top-half/musl/src/stdio/__towrite.c",
638 "wasi/libc-top-half/musl/src/stdio/__uflow.c",
639 "wasi/libc-top-half/musl/src/stdio/ungetc.c",651 "wasi/libc-top-half/musl/src/stdio/ungetc.c",
640 "wasi/libc-top-half/musl/src/stdio/ungetwc.c",652 "wasi/libc-top-half/musl/src/stdio/ungetwc.c",
641 "wasi/libc-top-half/musl/src/stdio/vasprintf.c",653 "wasi/libc-top-half/musl/src/stdio/vasprintf.c",
...@@ -728,24 +740,25 @@ const libc_top_half_src_files = [_][]const u8{...@@ -728,24 +740,25 @@ const libc_top_half_src_files = [_][]const u8{
728 "wasi/libc-top-half/musl/src/string/wmemcpy.c",740 "wasi/libc-top-half/musl/src/string/wmemcpy.c",
729 "wasi/libc-top-half/musl/src/string/wmemmove.c",741 "wasi/libc-top-half/musl/src/string/wmemmove.c",
730 "wasi/libc-top-half/musl/src/string/wmemset.c",742 "wasi/libc-top-half/musl/src/string/wmemset.c",
743 "wasi/libc-top-half/musl/src/locale/__lctrans.c",
744 "wasi/libc-top-half/musl/src/locale/__mo_lookup.c",
745 "wasi/libc-top-half/musl/src/locale/c_locale.c",
731 "wasi/libc-top-half/musl/src/locale/catclose.c",746 "wasi/libc-top-half/musl/src/locale/catclose.c",
732 "wasi/libc-top-half/musl/src/locale/catgets.c",747 "wasi/libc-top-half/musl/src/locale/catgets.c",
733 "wasi/libc-top-half/musl/src/locale/catopen.c",748 "wasi/libc-top-half/musl/src/locale/catopen.c",
734 "wasi/libc-top-half/musl/src/locale/c_locale.c",
735 "wasi/libc-top-half/musl/src/locale/duplocale.c",749 "wasi/libc-top-half/musl/src/locale/duplocale.c",
736 "wasi/libc-top-half/musl/src/locale/freelocale.c",750 "wasi/libc-top-half/musl/src/locale/freelocale.c",
737 "wasi/libc-top-half/musl/src/locale/iconv.c",751 "wasi/libc-top-half/musl/src/locale/iconv.c",
738 "wasi/libc-top-half/musl/src/locale/iconv_close.c",752 "wasi/libc-top-half/musl/src/locale/iconv_close.c",
739 "wasi/libc-top-half/musl/src/locale/langinfo.c",753 "wasi/libc-top-half/musl/src/locale/langinfo.c",
740 "wasi/libc-top-half/musl/src/locale/__lctrans.c",
741 "wasi/libc-top-half/musl/src/locale/localeconv.c",
742 "wasi/libc-top-half/musl/src/locale/locale_map.c",754 "wasi/libc-top-half/musl/src/locale/locale_map.c",
743 "wasi/libc-top-half/musl/src/locale/__mo_lookup.c",755 "wasi/libc-top-half/musl/src/locale/localeconv.c",
744 "wasi/libc-top-half/musl/src/locale/newlocale.c",756 "wasi/libc-top-half/musl/src/locale/newlocale.c",
745 "wasi/libc-top-half/musl/src/locale/pleval.c",757 "wasi/libc-top-half/musl/src/locale/pleval.c",
746 "wasi/libc-top-half/musl/src/locale/setlocale.c",758 "wasi/libc-top-half/musl/src/locale/setlocale.c",
747 "wasi/libc-top-half/musl/src/locale/strcoll.c",759 "wasi/libc-top-half/musl/src/locale/strcoll.c",
748 "wasi/libc-top-half/musl/src/locale/strfmon.c",760 "wasi/libc-top-half/musl/src/locale/strfmon.c",
761 "wasi/libc-top-half/musl/src/locale/strtod_l.c",
749 "wasi/libc-top-half/musl/src/locale/strxfrm.c",762 "wasi/libc-top-half/musl/src/locale/strxfrm.c",
750 "wasi/libc-top-half/musl/src/locale/uselocale.c",763 "wasi/libc-top-half/musl/src/locale/uselocale.c",
751 "wasi/libc-top-half/musl/src/locale/wcscoll.c",764 "wasi/libc-top-half/musl/src/locale/wcscoll.c",
...@@ -767,6 +780,7 @@ const libc_top_half_src_files = [_][]const u8{...@@ -767,6 +780,7 @@ const libc_top_half_src_files = [_][]const u8{
767 "wasi/libc-top-half/musl/src/stdlib/llabs.c",780 "wasi/libc-top-half/musl/src/stdlib/llabs.c",
768 "wasi/libc-top-half/musl/src/stdlib/lldiv.c",781 "wasi/libc-top-half/musl/src/stdlib/lldiv.c",
769 "wasi/libc-top-half/musl/src/stdlib/qsort.c",782 "wasi/libc-top-half/musl/src/stdlib/qsort.c",
783 "wasi/libc-top-half/musl/src/stdlib/qsort_nr.c",
770 "wasi/libc-top-half/musl/src/stdlib/strtod.c",784 "wasi/libc-top-half/musl/src/stdlib/strtod.c",
771 "wasi/libc-top-half/musl/src/stdlib/strtol.c",785 "wasi/libc-top-half/musl/src/stdlib/strtol.c",
772 "wasi/libc-top-half/musl/src/stdlib/wcstod.c",786 "wasi/libc-top-half/musl/src/stdlib/wcstod.c",
...@@ -805,15 +819,15 @@ const libc_top_half_src_files = [_][]const u8{...@@ -805,15 +819,15 @@ const libc_top_half_src_files = [_][]const u8{
805 "wasi/libc-top-half/musl/src/regex/regerror.c",819 "wasi/libc-top-half/musl/src/regex/regerror.c",
806 "wasi/libc-top-half/musl/src/regex/regexec.c",820 "wasi/libc-top-half/musl/src/regex/regexec.c",
807 "wasi/libc-top-half/musl/src/regex/tre-mem.c",821 "wasi/libc-top-half/musl/src/regex/tre-mem.c",
822 "wasi/libc-top-half/musl/src/prng/__rand48_step.c",
823 "wasi/libc-top-half/musl/src/prng/__seed48.c",
808 "wasi/libc-top-half/musl/src/prng/drand48.c",824 "wasi/libc-top-half/musl/src/prng/drand48.c",
809 "wasi/libc-top-half/musl/src/prng/lcong48.c",825 "wasi/libc-top-half/musl/src/prng/lcong48.c",
810 "wasi/libc-top-half/musl/src/prng/lrand48.c",826 "wasi/libc-top-half/musl/src/prng/lrand48.c",
811 "wasi/libc-top-half/musl/src/prng/mrand48.c",827 "wasi/libc-top-half/musl/src/prng/mrand48.c",
812 "wasi/libc-top-half/musl/src/prng/__rand48_step.c",
813 "wasi/libc-top-half/musl/src/prng/rand.c",828 "wasi/libc-top-half/musl/src/prng/rand.c",
814 "wasi/libc-top-half/musl/src/prng/random.c",
815 "wasi/libc-top-half/musl/src/prng/rand_r.c",829 "wasi/libc-top-half/musl/src/prng/rand_r.c",
816 "wasi/libc-top-half/musl/src/prng/__seed48.c",830 "wasi/libc-top-half/musl/src/prng/random.c",
817 "wasi/libc-top-half/musl/src/prng/seed48.c",831 "wasi/libc-top-half/musl/src/prng/seed48.c",
818 "wasi/libc-top-half/musl/src/prng/srand48.c",832 "wasi/libc-top-half/musl/src/prng/srand48.c",
819 "wasi/libc-top-half/musl/src/conf/confstr.c",833 "wasi/libc-top-half/musl/src/conf/confstr.c",
...@@ -858,6 +872,34 @@ const libc_top_half_src_files = [_][]const u8{...@@ -858,6 +872,34 @@ const libc_top_half_src_files = [_][]const u8{
858 "wasi/libc-top-half/musl/src/ctype/wcswidth.c",872 "wasi/libc-top-half/musl/src/ctype/wcswidth.c",
859 "wasi/libc-top-half/musl/src/ctype/wctrans.c",873 "wasi/libc-top-half/musl/src/ctype/wctrans.c",
860 "wasi/libc-top-half/musl/src/ctype/wcwidth.c",874 "wasi/libc-top-half/musl/src/ctype/wcwidth.c",
875 "wasi/libc-top-half/musl/src/math/__cos.c",
876 "wasi/libc-top-half/musl/src/math/__cosdf.c",
877 "wasi/libc-top-half/musl/src/math/__cosl.c",
878 "wasi/libc-top-half/musl/src/math/__expo2.c",
879 "wasi/libc-top-half/musl/src/math/__expo2f.c",
880 "wasi/libc-top-half/musl/src/math/__invtrigl.c",
881 "wasi/libc-top-half/musl/src/math/__math_divzero.c",
882 "wasi/libc-top-half/musl/src/math/__math_divzerof.c",
883 "wasi/libc-top-half/musl/src/math/__math_invalid.c",
884 "wasi/libc-top-half/musl/src/math/__math_invalidf.c",
885 "wasi/libc-top-half/musl/src/math/__math_invalidl.c",
886 "wasi/libc-top-half/musl/src/math/__math_oflow.c",
887 "wasi/libc-top-half/musl/src/math/__math_oflowf.c",
888 "wasi/libc-top-half/musl/src/math/__math_uflow.c",
889 "wasi/libc-top-half/musl/src/math/__math_uflowf.c",
890 "wasi/libc-top-half/musl/src/math/__math_xflow.c",
891 "wasi/libc-top-half/musl/src/math/__math_xflowf.c",
892 "wasi/libc-top-half/musl/src/math/__polevll.c",
893 "wasi/libc-top-half/musl/src/math/__rem_pio2.c",
894 "wasi/libc-top-half/musl/src/math/__rem_pio2_large.c",
895 "wasi/libc-top-half/musl/src/math/__rem_pio2f.c",
896 "wasi/libc-top-half/musl/src/math/__rem_pio2l.c",
897 "wasi/libc-top-half/musl/src/math/__sin.c",
898 "wasi/libc-top-half/musl/src/math/__sindf.c",
899 "wasi/libc-top-half/musl/src/math/__sinl.c",
900 "wasi/libc-top-half/musl/src/math/__tan.c",
901 "wasi/libc-top-half/musl/src/math/__tandf.c",
902 "wasi/libc-top-half/musl/src/math/__tanl.c",
861 "wasi/libc-top-half/musl/src/math/acos.c",903 "wasi/libc-top-half/musl/src/math/acos.c",
862 "wasi/libc-top-half/musl/src/math/acosf.c",904 "wasi/libc-top-half/musl/src/math/acosf.c",
863 "wasi/libc-top-half/musl/src/math/acosh.c",905 "wasi/libc-top-half/musl/src/math/acosh.c",
...@@ -870,10 +912,10 @@ const libc_top_half_src_files = [_][]const u8{...@@ -870,10 +912,10 @@ const libc_top_half_src_files = [_][]const u8{
870 "wasi/libc-top-half/musl/src/math/asinhf.c",912 "wasi/libc-top-half/musl/src/math/asinhf.c",
871 "wasi/libc-top-half/musl/src/math/asinhl.c",913 "wasi/libc-top-half/musl/src/math/asinhl.c",
872 "wasi/libc-top-half/musl/src/math/asinl.c",914 "wasi/libc-top-half/musl/src/math/asinl.c",
915 "wasi/libc-top-half/musl/src/math/atan.c",
873 "wasi/libc-top-half/musl/src/math/atan2.c",916 "wasi/libc-top-half/musl/src/math/atan2.c",
874 "wasi/libc-top-half/musl/src/math/atan2f.c",917 "wasi/libc-top-half/musl/src/math/atan2f.c",
875 "wasi/libc-top-half/musl/src/math/atan2l.c",918 "wasi/libc-top-half/musl/src/math/atan2l.c",
876 "wasi/libc-top-half/musl/src/math/atan.c",
877 "wasi/libc-top-half/musl/src/math/atanf.c",919 "wasi/libc-top-half/musl/src/math/atanf.c",
878 "wasi/libc-top-half/musl/src/math/atanh.c",920 "wasi/libc-top-half/musl/src/math/atanh.c",
879 "wasi/libc-top-half/musl/src/math/atanhf.c",921 "wasi/libc-top-half/musl/src/math/atanhf.c",
...@@ -884,18 +926,16 @@ const libc_top_half_src_files = [_][]const u8{...@@ -884,18 +926,16 @@ const libc_top_half_src_files = [_][]const u8{
884 "wasi/libc-top-half/musl/src/math/cbrtl.c",926 "wasi/libc-top-half/musl/src/math/cbrtl.c",
885 "wasi/libc-top-half/musl/src/math/ceill.c",927 "wasi/libc-top-half/musl/src/math/ceill.c",
886 "wasi/libc-top-half/musl/src/math/copysignl.c",928 "wasi/libc-top-half/musl/src/math/copysignl.c",
887 "wasi/libc-top-half/musl/src/math/__cos.c",
888 "wasi/libc-top-half/musl/src/math/cos.c",929 "wasi/libc-top-half/musl/src/math/cos.c",
889 "wasi/libc-top-half/musl/src/math/__cosdf.c",
890 "wasi/libc-top-half/musl/src/math/cosf.c",930 "wasi/libc-top-half/musl/src/math/cosf.c",
891 "wasi/libc-top-half/musl/src/math/cosh.c",931 "wasi/libc-top-half/musl/src/math/cosh.c",
892 "wasi/libc-top-half/musl/src/math/coshf.c",932 "wasi/libc-top-half/musl/src/math/coshf.c",
893 "wasi/libc-top-half/musl/src/math/coshl.c",933 "wasi/libc-top-half/musl/src/math/coshl.c",
894 "wasi/libc-top-half/musl/src/math/__cosl.c",
895 "wasi/libc-top-half/musl/src/math/cosl.c",934 "wasi/libc-top-half/musl/src/math/cosl.c",
896 "wasi/libc-top-half/musl/src/math/erf.c",935 "wasi/libc-top-half/musl/src/math/erf.c",
897 "wasi/libc-top-half/musl/src/math/erff.c",936 "wasi/libc-top-half/musl/src/math/erff.c",
898 "wasi/libc-top-half/musl/src/math/erfl.c",937 "wasi/libc-top-half/musl/src/math/erfl.c",
938 "wasi/libc-top-half/musl/src/math/exp.c",
899 "wasi/libc-top-half/musl/src/math/exp10.c",939 "wasi/libc-top-half/musl/src/math/exp10.c",
900 "wasi/libc-top-half/musl/src/math/exp10f.c",940 "wasi/libc-top-half/musl/src/math/exp10f.c",
901 "wasi/libc-top-half/musl/src/math/exp10l.c",941 "wasi/libc-top-half/musl/src/math/exp10l.c",
...@@ -903,15 +943,12 @@ const libc_top_half_src_files = [_][]const u8{...@@ -903,15 +943,12 @@ const libc_top_half_src_files = [_][]const u8{
903 "wasi/libc-top-half/musl/src/math/exp2f.c",943 "wasi/libc-top-half/musl/src/math/exp2f.c",
904 "wasi/libc-top-half/musl/src/math/exp2f_data.c",944 "wasi/libc-top-half/musl/src/math/exp2f_data.c",
905 "wasi/libc-top-half/musl/src/math/exp2l.c",945 "wasi/libc-top-half/musl/src/math/exp2l.c",
906 "wasi/libc-top-half/musl/src/math/exp.c",
907 "wasi/libc-top-half/musl/src/math/exp_data.c",946 "wasi/libc-top-half/musl/src/math/exp_data.c",
908 "wasi/libc-top-half/musl/src/math/expf.c",947 "wasi/libc-top-half/musl/src/math/expf.c",
909 "wasi/libc-top-half/musl/src/math/expl.c",948 "wasi/libc-top-half/musl/src/math/expl.c",
910 "wasi/libc-top-half/musl/src/math/expm1.c",949 "wasi/libc-top-half/musl/src/math/expm1.c",
911 "wasi/libc-top-half/musl/src/math/expm1f.c",950 "wasi/libc-top-half/musl/src/math/expm1f.c",
912 "wasi/libc-top-half/musl/src/math/expm1l.c",951 "wasi/libc-top-half/musl/src/math/expm1l.c",
913 "wasi/libc-top-half/musl/src/math/__expo2.c",
914 "wasi/libc-top-half/musl/src/math/__expo2f.c",
915 "wasi/libc-top-half/musl/src/math/fabsl.c",952 "wasi/libc-top-half/musl/src/math/fabsl.c",
916 "wasi/libc-top-half/musl/src/math/fdim.c",953 "wasi/libc-top-half/musl/src/math/fdim.c",
917 "wasi/libc-top-half/musl/src/math/fdimf.c",954 "wasi/libc-top-half/musl/src/math/fdimf.c",
...@@ -936,7 +973,6 @@ const libc_top_half_src_files = [_][]const u8{...@@ -936,7 +973,6 @@ const libc_top_half_src_files = [_][]const u8{
936 "wasi/libc-top-half/musl/src/math/ilogb.c",973 "wasi/libc-top-half/musl/src/math/ilogb.c",
937 "wasi/libc-top-half/musl/src/math/ilogbf.c",974 "wasi/libc-top-half/musl/src/math/ilogbf.c",
938 "wasi/libc-top-half/musl/src/math/ilogbl.c",975 "wasi/libc-top-half/musl/src/math/ilogbl.c",
939 "wasi/libc-top-half/musl/src/math/__invtrigl.c",
940 "wasi/libc-top-half/musl/src/math/j0.c",976 "wasi/libc-top-half/musl/src/math/j0.c",
941 "wasi/libc-top-half/musl/src/math/j0f.c",977 "wasi/libc-top-half/musl/src/math/j0f.c",
942 "wasi/libc-top-half/musl/src/math/j1.c",978 "wasi/libc-top-half/musl/src/math/j1.c",
...@@ -947,16 +983,17 @@ const libc_top_half_src_files = [_][]const u8{...@@ -947,16 +983,17 @@ const libc_top_half_src_files = [_][]const u8{
947 "wasi/libc-top-half/musl/src/math/ldexpf.c",983 "wasi/libc-top-half/musl/src/math/ldexpf.c",
948 "wasi/libc-top-half/musl/src/math/ldexpl.c",984 "wasi/libc-top-half/musl/src/math/ldexpl.c",
949 "wasi/libc-top-half/musl/src/math/lgamma.c",985 "wasi/libc-top-half/musl/src/math/lgamma.c",
986 "wasi/libc-top-half/musl/src/math/lgamma_r.c",
950 "wasi/libc-top-half/musl/src/math/lgammaf.c",987 "wasi/libc-top-half/musl/src/math/lgammaf.c",
951 "wasi/libc-top-half/musl/src/math/lgammaf_r.c",988 "wasi/libc-top-half/musl/src/math/lgammaf_r.c",
952 "wasi/libc-top-half/musl/src/math/lgammal.c",989 "wasi/libc-top-half/musl/src/math/lgammal.c",
953 "wasi/libc-top-half/musl/src/math/lgamma_r.c",
954 "wasi/libc-top-half/musl/src/math/llrint.c",990 "wasi/libc-top-half/musl/src/math/llrint.c",
955 "wasi/libc-top-half/musl/src/math/llrintf.c",991 "wasi/libc-top-half/musl/src/math/llrintf.c",
956 "wasi/libc-top-half/musl/src/math/llrintl.c",992 "wasi/libc-top-half/musl/src/math/llrintl.c",
957 "wasi/libc-top-half/musl/src/math/llround.c",993 "wasi/libc-top-half/musl/src/math/llround.c",
958 "wasi/libc-top-half/musl/src/math/llroundf.c",994 "wasi/libc-top-half/musl/src/math/llroundf.c",
959 "wasi/libc-top-half/musl/src/math/llroundl.c",995 "wasi/libc-top-half/musl/src/math/llroundl.c",
996 "wasi/libc-top-half/musl/src/math/log.c",
960 "wasi/libc-top-half/musl/src/math/log10.c",997 "wasi/libc-top-half/musl/src/math/log10.c",
961 "wasi/libc-top-half/musl/src/math/log10f.c",998 "wasi/libc-top-half/musl/src/math/log10f.c",
962 "wasi/libc-top-half/musl/src/math/log10l.c",999 "wasi/libc-top-half/musl/src/math/log10l.c",
...@@ -968,11 +1005,10 @@ const libc_top_half_src_files = [_][]const u8{...@@ -968,11 +1005,10 @@ const libc_top_half_src_files = [_][]const u8{
968 "wasi/libc-top-half/musl/src/math/log2f.c",1005 "wasi/libc-top-half/musl/src/math/log2f.c",
969 "wasi/libc-top-half/musl/src/math/log2f_data.c",1006 "wasi/libc-top-half/musl/src/math/log2f_data.c",
970 "wasi/libc-top-half/musl/src/math/log2l.c",1007 "wasi/libc-top-half/musl/src/math/log2l.c",
1008 "wasi/libc-top-half/musl/src/math/log_data.c",
971 "wasi/libc-top-half/musl/src/math/logb.c",1009 "wasi/libc-top-half/musl/src/math/logb.c",
972 "wasi/libc-top-half/musl/src/math/logbf.c",1010 "wasi/libc-top-half/musl/src/math/logbf.c",
973 "wasi/libc-top-half/musl/src/math/logbl.c",1011 "wasi/libc-top-half/musl/src/math/logbl.c",
974 "wasi/libc-top-half/musl/src/math/log.c",
975 "wasi/libc-top-half/musl/src/math/log_data.c",
976 "wasi/libc-top-half/musl/src/math/logf.c",1012 "wasi/libc-top-half/musl/src/math/logf.c",
977 "wasi/libc-top-half/musl/src/math/logf_data.c",1013 "wasi/libc-top-half/musl/src/math/logf_data.c",
978 "wasi/libc-top-half/musl/src/math/logl.c",1014 "wasi/libc-top-half/musl/src/math/logl.c",
...@@ -982,17 +1018,6 @@ const libc_top_half_src_files = [_][]const u8{...@@ -982,17 +1018,6 @@ const libc_top_half_src_files = [_][]const u8{
982 "wasi/libc-top-half/musl/src/math/lround.c",1018 "wasi/libc-top-half/musl/src/math/lround.c",
983 "wasi/libc-top-half/musl/src/math/lroundf.c",1019 "wasi/libc-top-half/musl/src/math/lroundf.c",
984 "wasi/libc-top-half/musl/src/math/lroundl.c",1020 "wasi/libc-top-half/musl/src/math/lroundl.c",
985 "wasi/libc-top-half/musl/src/math/__math_divzero.c",
986 "wasi/libc-top-half/musl/src/math/__math_divzerof.c",
987 "wasi/libc-top-half/musl/src/math/__math_invalid.c",
988 "wasi/libc-top-half/musl/src/math/__math_invalidf.c",
989 "wasi/libc-top-half/musl/src/math/__math_invalidl.c",
990 "wasi/libc-top-half/musl/src/math/__math_oflow.c",
991 "wasi/libc-top-half/musl/src/math/__math_oflowf.c",
992 "wasi/libc-top-half/musl/src/math/__math_uflow.c",
993 "wasi/libc-top-half/musl/src/math/__math_uflowf.c",
994 "wasi/libc-top-half/musl/src/math/__math_xflow.c",
995 "wasi/libc-top-half/musl/src/math/__math_xflowf.c",
996 "wasi/libc-top-half/musl/src/math/modf.c",1021 "wasi/libc-top-half/musl/src/math/modf.c",
997 "wasi/libc-top-half/musl/src/math/modff.c",1022 "wasi/libc-top-half/musl/src/math/modff.c",
998 "wasi/libc-top-half/musl/src/math/modfl.c",1023 "wasi/libc-top-half/musl/src/math/modfl.c",
...@@ -1006,7 +1031,6 @@ const libc_top_half_src_files = [_][]const u8{...@@ -1006,7 +1031,6 @@ const libc_top_half_src_files = [_][]const u8{
1006 "wasi/libc-top-half/musl/src/math/nexttoward.c",1031 "wasi/libc-top-half/musl/src/math/nexttoward.c",
1007 "wasi/libc-top-half/musl/src/math/nexttowardf.c",1032 "wasi/libc-top-half/musl/src/math/nexttowardf.c",
1008 "wasi/libc-top-half/musl/src/math/nexttowardl.c",1033 "wasi/libc-top-half/musl/src/math/nexttowardl.c",
1009 "wasi/libc-top-half/musl/src/math/__polevll.c",
1010 "wasi/libc-top-half/musl/src/math/pow.c",1034 "wasi/libc-top-half/musl/src/math/pow.c",
1011 "wasi/libc-top-half/musl/src/math/pow_data.c",1035 "wasi/libc-top-half/musl/src/math/pow_data.c",
1012 "wasi/libc-top-half/musl/src/math/powf.c",1036 "wasi/libc-top-half/musl/src/math/powf.c",
...@@ -1015,10 +1039,6 @@ const libc_top_half_src_files = [_][]const u8{...@@ -1015,10 +1039,6 @@ const libc_top_half_src_files = [_][]const u8{
1015 "wasi/libc-top-half/musl/src/math/remainder.c",1039 "wasi/libc-top-half/musl/src/math/remainder.c",
1016 "wasi/libc-top-half/musl/src/math/remainderf.c",1040 "wasi/libc-top-half/musl/src/math/remainderf.c",
1017 "wasi/libc-top-half/musl/src/math/remainderl.c",1041 "wasi/libc-top-half/musl/src/math/remainderl.c",
1018 "wasi/libc-top-half/musl/src/math/__rem_pio2.c",
1019 "wasi/libc-top-half/musl/src/math/__rem_pio2f.c",
1020 "wasi/libc-top-half/musl/src/math/__rem_pio2_large.c",
1021 "wasi/libc-top-half/musl/src/math/__rem_pio2l.c",
1022 "wasi/libc-top-half/musl/src/math/remquo.c",1042 "wasi/libc-top-half/musl/src/math/remquo.c",
1023 "wasi/libc-top-half/musl/src/math/remquof.c",1043 "wasi/libc-top-half/musl/src/math/remquof.c",
1024 "wasi/libc-top-half/musl/src/math/remquol.c",1044 "wasi/libc-top-half/musl/src/math/remquol.c",
...@@ -1037,33 +1057,29 @@ const libc_top_half_src_files = [_][]const u8{...@@ -1037,33 +1057,29 @@ const libc_top_half_src_files = [_][]const u8{
1037 "wasi/libc-top-half/musl/src/math/signgam.c",1057 "wasi/libc-top-half/musl/src/math/signgam.c",
1038 "wasi/libc-top-half/musl/src/math/significand.c",1058 "wasi/libc-top-half/musl/src/math/significand.c",
1039 "wasi/libc-top-half/musl/src/math/significandf.c",1059 "wasi/libc-top-half/musl/src/math/significandf.c",
1040 "wasi/libc-top-half/musl/src/math/__sin.c",
1041 "wasi/libc-top-half/musl/src/math/sin.c",1060 "wasi/libc-top-half/musl/src/math/sin.c",
1042 "wasi/libc-top-half/musl/src/math/sincos.c",1061 "wasi/libc-top-half/musl/src/math/sincos.c",
1043 "wasi/libc-top-half/musl/src/math/sincosf.c",1062 "wasi/libc-top-half/musl/src/math/sincosf.c",
1044 "wasi/libc-top-half/musl/src/math/sincosl.c",1063 "wasi/libc-top-half/musl/src/math/sincosl.c",
1045 "wasi/libc-top-half/musl/src/math/__sindf.c",
1046 "wasi/libc-top-half/musl/src/math/sinf.c",1064 "wasi/libc-top-half/musl/src/math/sinf.c",
1047 "wasi/libc-top-half/musl/src/math/sinh.c",1065 "wasi/libc-top-half/musl/src/math/sinh.c",
1048 "wasi/libc-top-half/musl/src/math/sinhf.c",1066 "wasi/libc-top-half/musl/src/math/sinhf.c",
1049 "wasi/libc-top-half/musl/src/math/sinhl.c",1067 "wasi/libc-top-half/musl/src/math/sinhl.c",
1050 "wasi/libc-top-half/musl/src/math/__sinl.c",
1051 "wasi/libc-top-half/musl/src/math/sinl.c",1068 "wasi/libc-top-half/musl/src/math/sinl.c",
1052 "wasi/libc-top-half/musl/src/math/sqrt_data.c",1069 "wasi/libc-top-half/musl/src/math/sqrt_data.c",
1053 "wasi/libc-top-half/musl/src/math/sqrtl.c",1070 "wasi/libc-top-half/musl/src/math/sqrtl.c",
1054 "wasi/libc-top-half/musl/src/math/__tan.c",
1055 "wasi/libc-top-half/musl/src/math/tan.c",1071 "wasi/libc-top-half/musl/src/math/tan.c",
1056 "wasi/libc-top-half/musl/src/math/__tandf.c",
1057 "wasi/libc-top-half/musl/src/math/tanf.c",1072 "wasi/libc-top-half/musl/src/math/tanf.c",
1058 "wasi/libc-top-half/musl/src/math/tanh.c",1073 "wasi/libc-top-half/musl/src/math/tanh.c",
1059 "wasi/libc-top-half/musl/src/math/tanhf.c",1074 "wasi/libc-top-half/musl/src/math/tanhf.c",
1060 "wasi/libc-top-half/musl/src/math/tanhl.c",1075 "wasi/libc-top-half/musl/src/math/tanhl.c",
1061 "wasi/libc-top-half/musl/src/math/__tanl.c",
1062 "wasi/libc-top-half/musl/src/math/tanl.c",1076 "wasi/libc-top-half/musl/src/math/tanl.c",
1063 "wasi/libc-top-half/musl/src/math/tgamma.c",1077 "wasi/libc-top-half/musl/src/math/tgamma.c",
1064 "wasi/libc-top-half/musl/src/math/tgammaf.c",1078 "wasi/libc-top-half/musl/src/math/tgammaf.c",
1065 "wasi/libc-top-half/musl/src/math/tgammal.c",1079 "wasi/libc-top-half/musl/src/math/tgammal.c",
1066 "wasi/libc-top-half/musl/src/math/truncl.c",1080 "wasi/libc-top-half/musl/src/math/truncl.c",
1081 "wasi/libc-top-half/musl/src/complex/__cexp.c",
1082 "wasi/libc-top-half/musl/src/complex/__cexpf.c",
1067 "wasi/libc-top-half/musl/src/complex/cabs.c",1083 "wasi/libc-top-half/musl/src/complex/cabs.c",
1068 "wasi/libc-top-half/musl/src/complex/cabsf.c",1084 "wasi/libc-top-half/musl/src/complex/cabsf.c",
1069 "wasi/libc-top-half/musl/src/complex/cabsl.c",1085 "wasi/libc-top-half/musl/src/complex/cabsl.c",
...@@ -1094,9 +1110,7 @@ const libc_top_half_src_files = [_][]const u8{...@@ -1094,9 +1110,7 @@ const libc_top_half_src_files = [_][]const u8{
1094 "wasi/libc-top-half/musl/src/complex/ccoshf.c",1110 "wasi/libc-top-half/musl/src/complex/ccoshf.c",
1095 "wasi/libc-top-half/musl/src/complex/ccoshl.c",1111 "wasi/libc-top-half/musl/src/complex/ccoshl.c",
1096 "wasi/libc-top-half/musl/src/complex/ccosl.c",1112 "wasi/libc-top-half/musl/src/complex/ccosl.c",
1097 "wasi/libc-top-half/musl/src/complex/__cexp.c",
1098 "wasi/libc-top-half/musl/src/complex/cexp.c",1113 "wasi/libc-top-half/musl/src/complex/cexp.c",
1099 "wasi/libc-top-half/musl/src/complex/__cexpf.c",
1100 "wasi/libc-top-half/musl/src/complex/cexpf.c",1114 "wasi/libc-top-half/musl/src/complex/cexpf.c",
1101 "wasi/libc-top-half/musl/src/complex/cexpl.c",1115 "wasi/libc-top-half/musl/src/complex/cexpl.c",
1102 "wasi/libc-top-half/musl/src/complex/clog.c",1116 "wasi/libc-top-half/musl/src/complex/clog.c",
...@@ -1126,8 +1140,8 @@ const libc_top_half_src_files = [_][]const u8{...@@ -1126,8 +1140,8 @@ const libc_top_half_src_files = [_][]const u8{
1126 "wasi/libc-top-half/musl/src/complex/ctanhf.c",1140 "wasi/libc-top-half/musl/src/complex/ctanhf.c",
1127 "wasi/libc-top-half/musl/src/complex/ctanhl.c",1141 "wasi/libc-top-half/musl/src/complex/ctanhl.c",
1128 "wasi/libc-top-half/musl/src/complex/ctanl.c",1142 "wasi/libc-top-half/musl/src/complex/ctanl.c",
1129 "wasi/libc-top-half/musl/src/crypt/crypt_blowfish.c",
1130 "wasi/libc-top-half/musl/src/crypt/crypt.c",1143 "wasi/libc-top-half/musl/src/crypt/crypt.c",
1144 "wasi/libc-top-half/musl/src/crypt/crypt_blowfish.c",
1131 "wasi/libc-top-half/musl/src/crypt/crypt_des.c",1145 "wasi/libc-top-half/musl/src/crypt/crypt_des.c",
1132 "wasi/libc-top-half/musl/src/crypt/crypt_md5.c",1146 "wasi/libc-top-half/musl/src/crypt/crypt_md5.c",
1133 "wasi/libc-top-half/musl/src/crypt/crypt_r.c",1147 "wasi/libc-top-half/musl/src/crypt/crypt_r.c",