trace: Fix a crash and source of invalid json.

This commit is contained in:
Cory McWilliams 2025-03-07 12:37:02 -05:00
parent 951a80389a
commit 942f582329

View File

@ -4,6 +4,7 @@
#include "trace.h"
#include "log.h"
#include "mem.h"
#include "util.js.h"
@ -149,25 +150,37 @@ static int _tf_trace_escape_name(char* out, size_t out_size, const char* name)
{
case '"':
case '\\':
out[p++] = '\\';
if ((size_t)p + 1 < out_size)
if ((size_t)p + 2 < out_size)
{
out[p++] = '\\';
out[p++] = *c;
}
else
{
out[p++] = '$';
}
break;
case '\t':
out[p++] = '\\';
if ((size_t)p + 1 < out_size)
if ((size_t)p + 2 < out_size)
{
out[p++] = '\\';
out[p++] = 't';
}
else
{
out[p++] = '$';
}
break;
case '\n':
out[p++] = '\\';
if ((size_t)p + 1 < out_size)
if ((size_t)p + 2 < out_size)
{
out[p++] = '\\';
out[p++] = 'n';
}
else
{
out[p++] = '$';
}
break;
default:
out[p++] = *c;
@ -320,21 +333,22 @@ char* tf_trace_export(tf_trace_t* trace)
}
static const int k_extra_size = 1024;
char* buffer = tf_malloc(k_buffer_size + k_extra_size);
static const size_t k_out_buffer_size = k_buffer_size + k_extra_size;
char* buffer = tf_malloc(k_out_buffer_size);
uv_mutex_lock(&trace->mutex);
const char* newline = strchr(trace->buffer + trace->write_offset, '\n');
int begin = newline ? newline - trace->buffer : 0;
size_t size = 0;
size += snprintf(buffer, k_buffer_size, "{\"displayTimeUnit\": \"ns\",\n\"traceEvents\": [\n");
size += snprintf(buffer, k_out_buffer_size, "{\"displayTimeUnit\": \"ns\",\n\"traceEvents\": [\n");
if (*trace->process_name)
{
size += snprintf(buffer + size, k_buffer_size - size, "{\"ph\":\"M\",\"pid\":%d,\"name\":\"process_name\",\"args\":{\"name\":\"%s\"}},\n", getpid(), trace->process_name);
size += snprintf(buffer + size, k_out_buffer_size - size, "{\"ph\":\"M\",\"pid\":%d,\"name\":\"process_name\",\"args\":{\"name\":\"%s\"}},\n", getpid(), trace->process_name);
}
uv_rwlock_rdlock(&trace->threads_lock);
for (int i = 0; i < trace->threads_count; i++)
{
tf_trace_thread_t* thread = trace->threads[i];
size += snprintf(buffer + size, k_buffer_size - size, "{\"ph\":\"M\",\"pid\":%d,\"tid\":%d,\"name\":\"thread_name\",\"args\":{\"name\":\"%s\"}},\n", getpid(),
size += snprintf(buffer + size, k_out_buffer_size - size, "{\"ph\":\"M\",\"pid\":%d,\"tid\":%d,\"name\":\"thread_name\",\"args\":{\"name\":\"%s\"}},\n", getpid(),
thread->index, thread->name);
}
uv_rwlock_rdunlock(&trace->threads_lock);
@ -352,8 +366,8 @@ char* tf_trace_export(tf_trace_t* trace)
buffer[size - 2] = '\n';
size--;
}
size += snprintf(buffer + size, k_buffer_size - size, "]}\n");
assert(size < (size_t)k_buffer_size + k_extra_size);
size += snprintf(buffer + size, k_out_buffer_size - size, "]}\n");
assert(size < k_out_buffer_size);
buffer[size] = '\0';
return buffer;
}