Brute force memory tracking.

git-svn-id: https://www.unprompted.com/svn/projects/tildefriends/trunk@4186 ed5197a5-7fde-0310-b194-c3ffbd925b24
This commit is contained in:
2023-02-18 21:00:39 +00:00
parent 53cb80ebf7
commit 88c7d91858
8 changed files with 347 additions and 66 deletions

View File

@ -4,6 +4,7 @@
#include "task.h"
#include "trace.h"
#include <backtrace.h>
#include <openssl/crypto.h>
#include <openssl/sha.h>
#include <picohttpparser.h>
@ -13,6 +14,12 @@
#include <string.h>
#ifndef _WIN32
#ifndef __ANDROID__
#include <execinfo.h>
#endif
#endif
static JSValue _util_utf8_encode(JSContext* context, JSValueConst this_val, int argc, JSValueConst* argv)
{
size_t length = 0;
@ -417,3 +424,60 @@ size_t tf_base64_decode(const char* source, size_t source_length, uint8_t* out,
size_t actual_length = 0;
return sodium_base642bin(out, out_length, source, source_length, NULL, &actual_length, NULL, sodium_base64_VARIANT_ORIGINAL) == 0 ? actual_length : 0;
}
static int _tf_util_backtrace_callback(void* data, uintptr_t pc, const char* filename, int line_number, const char* function)
{
char** stack = data;
char line[256];
int length = snprintf(line, sizeof(line), "%p %s:%d %s\n", (void*)pc, filename, line_number, function);
int current = *stack ? strlen(*stack) : 0;
*stack = tf_resize_vec(*stack, current + length + 1);
memcpy(*stack + current, line, length + 1);
return 0;
}
static void _tf_util_backtrace_error(void* data, const char* message, int error)
{
char** stack = data;
int length = strlen(message);
if (message)
{
int current = *stack ? strlen(*stack) : 0;
*stack = tf_resize_vec(*stack, current + length + 1);
memcpy(*stack + current, message, length + 1);
}
}
const char* tf_util_backtrace_to_string(void* const* buffer, int count)
{
extern struct backtrace_state* g_backtrace_state;
char* string = NULL;
for (int i = 0; i < count; i++)
{
backtrace_pcinfo(
g_backtrace_state,
(uintptr_t)buffer[i],
_tf_util_backtrace_callback,
_tf_util_backtrace_error,
&string);
}
return string;
}
const char* tf_util_backtrace_string()
{
void* buffer[32];
int count = tf_util_backtrace(buffer, sizeof(buffer) / sizeof(*buffer));
return tf_util_backtrace_to_string(buffer, count);
}
int tf_util_backtrace(void** buffer, int count)
{
#ifdef _WIN32
return CaptureStackBackTrace(0, count, buffer, NULL);
#elif !defined(__ANDROID__)
return backtrace(buffer, count);
#else
return 0;
#endif
}