|
25 | 25 | #include "private.h"
|
26 | 26 | #include "tjs.h"
|
27 | 27 |
|
| 28 | +#include <mimalloc.h> |
28 | 29 | #include <string.h>
|
29 | 30 |
|
30 | 31 |
|
31 | 32 | #define TJS__DEFAULT_STACK_SIZE 1048576
|
32 | 33 |
|
| 34 | +static void *tjs__malloc(JSMallocState *s, size_t size) |
| 35 | +{ |
| 36 | + void *ptr; |
| 37 | + |
| 38 | + /* Do not allocate zero bytes: behavior is platform dependent */ |
| 39 | + assert(size != 0); |
| 40 | + |
| 41 | + if (unlikely(s->malloc_size + size > s->malloc_limit)) |
| 42 | + return NULL; |
| 43 | + |
| 44 | + ptr = mi_malloc(size); |
| 45 | + if (!ptr) |
| 46 | + return NULL; |
| 47 | + |
| 48 | + s->malloc_count++; |
| 49 | + s->malloc_size += mi_malloc_usable_size(ptr); |
| 50 | + return ptr; |
| 51 | +} |
| 52 | + |
| 53 | +static void tjs__free(JSMallocState *s, void *ptr) |
| 54 | +{ |
| 55 | + if (!ptr) |
| 56 | + return; |
| 57 | + |
| 58 | + s->malloc_count--; |
| 59 | + s->malloc_size -= mi_malloc_usable_size(ptr); |
| 60 | + mi_free(ptr); |
| 61 | +} |
| 62 | + |
| 63 | +static void *tjs__realloc(JSMallocState *s, void *ptr, size_t size) |
| 64 | +{ |
| 65 | + size_t old_size; |
| 66 | + |
| 67 | + if (!ptr) { |
| 68 | + if (size == 0) |
| 69 | + return NULL; |
| 70 | + return tjs__malloc(s, size); |
| 71 | + } |
| 72 | + old_size = mi_malloc_usable_size(ptr); |
| 73 | + if (size == 0) { |
| 74 | + s->malloc_count--; |
| 75 | + s->malloc_size -= old_size; |
| 76 | + mi_free(ptr); |
| 77 | + return NULL; |
| 78 | + } |
| 79 | + if (s->malloc_size + size - old_size > s->malloc_limit) |
| 80 | + return NULL; |
| 81 | + |
| 82 | + ptr = mi_realloc(ptr, size); |
| 83 | + if (!ptr) |
| 84 | + return NULL; |
| 85 | + |
| 86 | + s->malloc_size += mi_malloc_usable_size(ptr) - old_size; |
| 87 | + return ptr; |
| 88 | +} |
| 89 | + |
| 90 | +static const JSMallocFunctions tjs_mf = { |
| 91 | + tjs__malloc, |
| 92 | + tjs__free, |
| 93 | + tjs__realloc, |
| 94 | + mi_malloc_usable_size |
| 95 | +}; |
| 96 | + |
33 | 97 | /* core */
|
34 | 98 | extern const uint8_t tjs__core[];
|
35 | 99 | extern const uint32_t tjs__core_size;
|
@@ -161,7 +225,7 @@ TJSRuntime *TJS_NewRuntimeInternal(bool is_worker, TJSRunOptions *options) {
|
161 | 225 |
|
162 | 226 | memcpy(&qrt->options, options, sizeof(*options));
|
163 | 227 |
|
164 |
| - qrt->rt = JS_NewRuntime(); |
| 228 | + qrt->rt = JS_NewRuntime2(&tjs_mf, NULL); |
165 | 229 | CHECK_NOT_NULL(qrt->rt);
|
166 | 230 |
|
167 | 231 | qrt->ctx = JS_NewContext(qrt->rt);
|
|
0 commit comments