[RELEASE] u22-v03

This version is submitted to U22 breau.
This commit is contained in:
2020-09-14 00:00:00 +00:00
parent 360595de37
commit 84c3a02b9a
357 changed files with 29223 additions and 0 deletions

View File

@@ -0,0 +1,10 @@
add_library(memory
memory.c
)
if (BUILD_TESTING)
add_executable(memory-test test.c)
target_link_libraries(memory-test memory)
add_test(memory-test memory-test)
endif()

81
util/memory/memory.c Normal file
View File

@@ -0,0 +1,81 @@
#include "./memory.h"
#include <assert.h>
#include <stdarg.h>
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#ifdef __linux__
# include <execinfo.h>
#endif
#define MEMORY_LOG_FILE "memory-trace"
void* memory_new(size_t size) {
if (size == 0) return NULL;
void* ptr = malloc(size);
if (ptr == NULL) {
fprintf(stderr, "failed to allocate %zu bytes memory", size);
abort();
}
memory_log("new 0x%tx (%zu bytes)", (ptrdiff_t) ptr, size);
return ptr;
}
void* memory_resize(void* ptr, size_t size) {
if (ptr == NULL) return memory_new(size);
if (size == 0) return ptr;
void* newptr = realloc(ptr, size);
if (newptr == NULL) {
fprintf(stderr,
"failed to allocate %zu bytes memory for resizing 0x%tx",
size, (ptrdiff_t) ptr);
abort();
}
memory_log("resize 0x%tx -> 0x%tx (%zu bytes)",
(ptrdiff_t) ptr, (ptrdiff_t) newptr, size);
return newptr;
}
void memory_delete(void* ptr) {
if (ptr == NULL) return;
free(ptr);
memory_log("delete 0x%tx", (ptrdiff_t) ptr);
}
#ifndef NDEBUG
void memory_log(const char* fmt, ...) {
static FILE* fp = NULL;
if (fp == NULL) {
fp = fopen(MEMORY_LOG_FILE, "w");
assert(fp != NULL);
}
va_list args;
va_start(args, fmt);
vfprintf(fp, fmt, args);
va_end(args);
fprintf(fp, "\n");
# if __linux__
void* callstack[32];
const size_t frames = backtrace(callstack, sizeof(callstack));
char** symbols = backtrace_symbols(callstack, frames);
for (size_t i = 0; i < frames; ++i) {
fprintf(fp, " %s\n", symbols[i]);
}
free(symbols);
# endif /* __linux__ */
fprintf(fp, "\n");
fflush(fp);
}
#endif /* NDEBUG */

29
util/memory/memory.h Normal file
View File

@@ -0,0 +1,29 @@
#pragma once
#include <stddef.h>
void*
memory_new(
size_t size
);
void*
memory_resize(
void* ptr,
size_t size
);
void
memory_delete(
void* ptr
);
#ifndef NDEBUG
void
memory_log(
const char* fmt,
...
);
#else
# define memory_log(fmt, ...) (void) fmt
#endif /* NDEBUG */

8
util/memory/test.c Normal file
View File

@@ -0,0 +1,8 @@
#include "./memory.h"
int main(void) {
void* ptr = memory_new(0x1);
ptr = memory_resize(ptr, 0x2);
memory_delete(ptr);
return 0;
}