Skip to content

Commit

Permalink
Allow debug output to be delivered via callbacks
Browse files Browse the repository at this point in the history
  • Loading branch information
paulej committed Sep 1, 2023
1 parent 1e2979e commit 67d7f12
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 9 deletions.
1 change: 1 addition & 0 deletions picoquic/picoquic_utils.h
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,7 @@ extern "C" {


void debug_set_stream(FILE *F);
void debug_set_callback(void (*cb)(const char *msg, void *argp), void *argp);
void debug_printf(const char* fmt, ...);
void debug_printf_push_stream(FILE* f);
void debug_printf_pop_stream(void);
Expand Down
54 changes: 45 additions & 9 deletions picoquic/util.c
Original file line number Diff line number Diff line change
Expand Up @@ -111,35 +111,71 @@ char* picoquic_strip_endofline(char* buf, size_t bufmax, char const* line)
}

static FILE* debug_out = NULL;
void (*debug_callback)(const char *msg, void *arg) = NULL;
void *debug_callback_argp = NULL;
static int debug_suspended = 0;

void debug_set_stream(FILE *F)
{
debug_out = F;
debug_callback = NULL;
debug_callback_argp = NULL;
}

void debug_set_callback(void (*cb)(const char *msg, void *argp), void *argp)
{
debug_callback = cb;
debug_callback_argp = argp;
debug_out = NULL;
}

void debug_printf(const char* fmt, ...)
{
if (debug_suspended == 0 && debug_out != NULL) {
va_list args;
va_start(args, fmt);
vfprintf(debug_out, fmt, args);
va_end(args);
if (debug_suspended == 0 && (debug_out != NULL || debug_callback != NULL)) {
if (debug_out) {
va_list args;
va_start(args, fmt);
vfprintf(debug_out, fmt, args);
va_end(args);
} else {
char message[1024];
size_t message_length;
va_list args;
va_start(args, fmt);
vsnprintf(message, sizeof(message), fmt, args);
va_end(args);
message_length = strnlen(message, sizeof(message));
if (message_length > 0) {
// Strip any trailing newline
if (message[message_length - 1] == '\n') {
message[message_length - 1] = '\0';
}
}
debug_callback(message, debug_callback_argp);
}
}
}

void debug_dump(const void * x, int len)
{
if (debug_suspended == 0 && debug_out != NULL) {
if (debug_suspended == 0 && (debug_out != NULL || debug_callback != NULL)) {
char msg[64];
uint8_t * bytes = (uint8_t *)x;

for (int i = 0; i < len;) {
fprintf(debug_out, "%04x: ", (int)i);
size_t mlen = 0;
snprintf(msg, sizeof(msg), "%04x: ", (int) i);
mlen = strnlen(msg, sizeof(msg));

for (int j = 0; j < 16 && i < len; j++, i++) {
fprintf(debug_out, "%02x ", bytes[i]);
snprintf(msg + mlen, sizeof(msg) - mlen, "%02x ", bytes[i]);
mlen = strnlen(msg, sizeof(msg));
}
if (debug_out) {
fprintf(debug_out, "%s\n", msg);
} else {
debug_callback(msg, debug_callback_argp);
}
fprintf(debug_out, "\n");
}
}
}
Expand Down

0 comments on commit 67d7f12

Please sign in to comment.