diff --git a/src/trace.c b/src/trace.c index 70b209de..77a0e91b 100644 --- a/src/trace.c +++ b/src/trace.c @@ -108,6 +108,43 @@ void tf_trace_counter(tf_trace_t* trace, const char* name, int argc, const char* trace->callback(trace, line, p, trace->user_data); } +static int _tf_trace_escape_name(char* out, size_t out_size, const char* name) +{ + int p = 0; + for (const char* c = name; *c && (size_t)p < out_size; c++) + { + switch (*c) + { + case '"': + case '\\': + out[p++] = '\\'; + if ((size_t)p + 1 < out_size) + { + out[p++] = *c; + } + break; + case '\t': + out[p++] = '\\'; + if ((size_t)p + 1 < out_size) + { + out[p++] = 't'; + } + break; + case '\n': + out[p++] = '\\'; + if ((size_t)p + 1 < out_size) + { + out[p++] = 'n'; + } + break; + default: + out[p++] = *c; + break; + } + } + return p; +} + void tf_trace_begin(tf_trace_t* trace, const char* name) { if (!trace) @@ -131,23 +168,7 @@ void tf_trace_begin(tf_trace_t* trace, const char* name) char line[1024]; int p = snprintf(line, sizeof(line), "{\"ph\": \"B\", \"pid\": %d, \"tid\": 0, \"ts\": %" PRId64 ", \"name\": \"", getpid(), _trace_ts()); - for (const char* c = name; *c && p < (int)sizeof(line); c++) - { - switch (*c) - { - case '"': - case '\\': - line[p++] = '\\'; - if (p < (int)sizeof(line)) - { - line[p++] = *c; - } - break; - default: - line[p++] = *c; - break; - } - } + p += _tf_trace_escape_name(line + p, sizeof(line) - p, name); p += snprintf(line + p, sizeof(line) - p, "\"},"); trace->callback(trace, line, p, trace->user_data); } @@ -177,23 +198,7 @@ void tf_trace_end(tf_trace_t* trace) char line[1024]; int p = snprintf(line, sizeof(line), "{\"ph\": \"E\", \"pid\": %d, \"tid\": 0, \"ts\": %" PRId64 ", \"name\": \"", getpid(), _trace_ts()); - for (const char* c = name; *c && p < (int)sizeof(line); c++) - { - switch (*c) - { - case '"': - case '\\': - line[p++] = '\\'; - if (p < (int)sizeof(line)) - { - line[p++] = *c; - } - break; - default: - line[p++] = *c; - break; - } - } + p += _tf_trace_escape_name(line + p, sizeof(line) - p, name); p += snprintf(line + p, sizeof(line) - p, "\"},"); trace->callback(trace, line, p, trace->user_data); }