AmendHub

Download:

jcs

/

wikipedia

/

amendments

/

43

util: Add a new style of malloc debugging

This helps find when allocated buffers have been overflowed.

jcs made amendment 43 8 months ago
--- util.c Mon Mar 27 21:32:52 2023 +++ util.c Wed Aug 30 16:00:14 2023 @@ -28,8 +28,16 @@ #include <SetUpA4.h> #include "util.h" +/* + * Define to enable malloc debugging which creates an allocation larger + * than the requested size, then embeds the allocated size and 2 canary + * bytes before and after the allocation. On xfree(), the canary bytes + * are verified and if any are not correct, the program panics. + */ +/* #define MALLOC_DEBUG 1 */ + /* ALRT resources */ -#define ASK_ALERT_ID 130 +#define ASK_ALERT_ID 130 #define ERROR_STRING_SIZE 1024 static char err_str[ERROR_STRING_SIZE]; @@ -110,24 +118,42 @@ util_init(void) void * xmalloc(size_t size) { +#ifdef MALLOC_DEBUG void *ptr; + unsigned char *cptr; +#endif if (size == 0) panic("xmalloc: zero size"); - ptr = NewPtr(size); -#if 0 - if (ptr == NULL) - warn("Insufficient memory available: xmalloc(%lu) failed", size); +#ifdef MALLOC_DEBUG + ptr = NewPtr(size + 8); + + cptr = (unsigned char *)ptr; + cptr[0] = 0xff; + cptr[1] = 0xff; + cptr[2] = (size >> 24) & 0xff; + cptr[3] = (size >> 16) & 0xff; + cptr[4] = (size >> 8) & 0xff; + cptr[5] = size & 0xff; + + cptr[6 + size] = 0xff; + cptr[6 + size + 1] = 0xff; + + return cptr + 6; +#else + return NewPtr(size); #endif - - return ptr; } void xfree(void *ptrptr) { unsigned long *addr = (unsigned long *)ptrptr; +#ifdef MALLOC_DEBUG + size_t size; + unsigned char *cptr; +#endif void *ptr; if (ptrptr == NULL) @@ -136,8 +162,25 @@ xfree(void *ptrptr) ptr = (void *)*addr; if (ptr == NULL) panic("xfree(&NULL) likely a double-free"); + +#ifdef MALLOC_DEBUG + cptr = (unsigned char *)ptr - 6; + if (cptr[0] != 0xff || cptr[1] != 0xff) + panic("xfree() pre-buf canary dead"); + + size = ((unsigned long)(cptr[2]) << 24) | + ((unsigned long)(cptr[3]) << 16) | + ((unsigned long)(cptr[4]) << 8) | + (unsigned long)(cptr[5]); + if (cptr[6 + size] != 0xff || cptr[6 + size + 1] != 0xff) + panic("xfree() post-buf canary dead"); + + DisposePtr(cptr); +#else DisposePtr(ptr); +#endif + *addr = 0L; }