Track our own quickjs memory usage so that we can avoid expensive calls to JS_ComputeMemoryUsage.

git-svn-id: https://www.unprompted.com/svn/projects/tildefriends/trunk@3915 ed5197a5-7fde-0310-b194-c3ffbd925b24
This commit is contained in:
2022-06-20 17:57:07 +00:00
parent f69e74ce53
commit c9e01f220d
5 changed files with 81 additions and 9 deletions

View File

@ -6,11 +6,14 @@
#include <openssl/crypto.h>
#endif
#include <quickjs.h>
#include <string.h>
static int64_t s_tf_malloc_size;
static int64_t s_uv_malloc_size;
static int64_t s_tls_malloc_size;
static int64_t s_js_malloc_size;
static void* _tf_alloc(int64_t* total, size_t size)
{
@ -184,3 +187,65 @@ size_t tf_mem_get_tf_malloc_size()
{
return s_tf_malloc_size;
}
static void* _tf_js_malloc(JSMallocState* state, size_t size)
{
int64_t delta = 0;
void* ptr = _tf_alloc(&delta, size);
if (ptr)
{
__atomic_add_fetch(&s_js_malloc_size, delta, __ATOMIC_RELAXED);
state->malloc_count++;
state->malloc_size += delta;
}
return ptr;
}
static void _tf_js_free(JSMallocState* state, void* ptr)
{
if (ptr)
{
int64_t delta = 0;
_tf_free(&delta, ptr);
__atomic_add_fetch(&s_js_malloc_size, delta, __ATOMIC_RELAXED);
state->malloc_count--;
state->malloc_size += delta;
}
}
static void* _tf_js_realloc(JSMallocState* state, void* ptr, size_t size)
{
int64_t delta = 0;
void* result = _tf_realloc(&delta, ptr, size);
__atomic_add_fetch(&s_js_malloc_size, delta, __ATOMIC_RELAXED);
state->malloc_count += (ptr ? -1 : 0) + (result ? 1 : 0);
state->malloc_size += delta;
return result;
}
static size_t _tf_js_malloc_usable_size(const void* ptr)
{
void* old_ptr = ptr ? (void*)((intptr_t)ptr - sizeof(size_t)) : NULL;
size_t old_size = 0;
if (old_ptr)
{
memcpy(&old_size, old_ptr, sizeof(size_t));
}
return old_size;
}
void tf_get_js_malloc_functions(JSMallocFunctions* out)
{
*out = (JSMallocFunctions)
{
.js_malloc = _tf_js_malloc,
.js_free = _tf_js_free,
.js_realloc = _tf_js_realloc,
.js_malloc_usable_size = _tf_js_malloc_usable_size,
};
}
size_t tf_mem_get_js_malloc_size()
{
return s_js_malloc_size;
}