Browse Source

Memory: refactor hex_dump to use buffer with DEBUG output

congestion
Evgeny 5 months ago
parent
commit
f195d1d91e
  1. 28
      lib/mem.c

28
lib/mem.c

@ -51,27 +51,29 @@ static void init_mutex() {
static void* allocated_head = NULL;
static size_t allocated_count = 0;
static void hex_dump(const void* mem, size_t len) {
static void hex_dump_buf(const void* mem, size_t len, char* buf, size_t buf_size) {
const uint8_t* data = (const uint8_t*)mem;
for (size_t i = 0; i < len; i += 16) {
printf("%08zx: ", i);
size_t off = 0;
for (size_t i = 0; i < len && i < 256; i += 16) {
if (off >= buf_size - 80) break;
off += snprintf(buf + off, buf_size - off, "%08zx: ", i);
for (size_t j = 0; j < 16; j++) {
if (i + j < len) {
printf("%02x ", data[i + j]);
off += snprintf(buf + off, buf_size - off, "%02x ", data[i + j]);
} else {
printf(" ");
off += snprintf(buf + off, buf_size - off, " ");
}
}
printf(" ");
off += snprintf(buf + off, buf_size - off, " ");
for (size_t j = 0; j < 16; j++) {
if (i + j < len) {
uint8_t c = data[i + j];
printf("%c", (c >= 32 && c <= 126) ? c : '.');
off += snprintf(buf + off, buf_size - off, "%c", (c >= 32 && c <= 126) ? c : '.');
} else {
printf(" ");
off += snprintf(buf + off, buf_size - off, " ");
}
}
printf("\n");
off += snprintf(buf + off, buf_size - off, "\n");
}
}
@ -115,7 +117,9 @@ void u_check(void* ptr, const char* text, const char* location) {
printf("%s: %s: Allocated at: %s\n", location, text, alloc_loc);
printf("%s: %s: Memory block size (user): %u bytes, total allocated: %u bytes\n", location, text, size, total);
printf("%s: %s: Full memory dump at base %p:\n", location, text, base);
hex_dump(base, total);
char dump_buf[4096];
hex_dump_buf(base, total, dump_buf, sizeof(dump_buf));
DEBUG_ERROR(DEBUG_CATEGORY_MEMORY, "%s", dump_buf);
exit(EXIT_FAILURE);
}
}
@ -227,7 +231,9 @@ void u_report_unfreed_blocks(void) {
u_check(user_ptr, "unfreed_check", "u_report_unfreed_blocks");
DEBUG_ERROR(DEBUG_CATEGORY_MEMORY, " - Allocated at: %s, size: %u bytes\n", alloc_loc, size);
DEBUG_ERROR(DEBUG_CATEGORY_MEMORY, " Full memory dump at %p:\n", user_ptr);
hex_dump(user_ptr, size);
char dump_buf[4096];
hex_dump_buf(user_ptr, size, dump_buf, sizeof(dump_buf));
DEBUG_ERROR(DEBUG_CATEGORY_MEMORY, "%s", dump_buf);
curr = *(void**)((uint8_t*)curr + NEXT_OFFSET);
}
}

Loading…
Cancel
Save