/* * CS5600 University of Utah * Charles McGarvey * mcgarvey@eng.utah.edu */ #include #include #include #include #include #include #include #include "common.h" static void* (*_mem_fn)(void*, size_t) = NULL; static int _mem_blocks = 0; /* * Check the result of the allocation function and call the callback function * if it failed. */ INLINE_MAYBE void* _mem_check(void* mem, void* old, size_t size) { if (mem == NULL && size != 0) { if (_mem_fn) { mem = _mem_fn(old, size); if (mem != NULL) { goto done; } } fprintf(stderr, "Memory allocation failed: %s\n", strerror(errno)); abort(); } done: if (old == NULL) { ++_mem_blocks; } return mem; } void* mem_alloc(size_t size) { void* mem = _mem_check(malloc(size), NULL, size); #if MEM_TRACE fprintf(stderr, "alloc %6d %18p %10zd\n", _mem_blocks - 1, mem, size); #endif return mem; } void* mem_realloc(void* mem, size_t size) { void* old = mem; mem = _mem_check(realloc(mem, size), mem, size); #if MEM_TRACE fprintf(stderr, "realloc %6d %18p %10zd (was %p)\n", _mem_blocks - 1, mem, size, old); #endif return mem; } void mem_free(void* mem) { --_mem_blocks; #if MEM_TRACE fprintf(stderr, "free %6d %18p\n", _mem_blocks, mem); #endif free(mem); } void mem_set_fn(void* (*fn)(void*, size_t)) { _mem_fn = fn; } int mem_blocks() { return _mem_blocks; } void rtrim(char *str) { char *m; for (m = str + strlen(str) - 1; str <= m && isspace((int)*m); --m); m[1] = '\0'; } void ltrim(char *str) { char *m; for (m = str; *m && isspace((int)*m); ++m); memmove(str, m, strlen(m) + 1); } static struct timeval _timer = {0, 0l}; static struct timeval timer_diff(struct timeval a, struct timeval b) { struct timeval tv; if ((b.tv_usec - a.tv_usec) < 0) { tv.tv_sec = b.tv_sec - a.tv_sec - 1; tv.tv_usec = 1000000l + b.tv_usec - a.tv_usec; } else { tv.tv_sec = b.tv_sec - a.tv_sec; tv.tv_usec = b.tv_usec - a.tv_usec; } return tv; } void timer_start() { int result = gettimeofday(&_timer, NULL); assert(result == 0 && "umm... gettimeofday failed!?"); } long timer_stop() { struct timeval tv; int result = gettimeofday(&tv, NULL); assert(result == 0 && "umm... gettimeofday failed!?"); tv = timer_diff(_timer, tv); return (long)tv.tv_sec * 1000000l + tv.tv_usec; }