static void ufree_check(void *md, void *ptr) { struct hdr *hdr = ((struct hdr *) ptr) - 1; struct mdesc *mdp; mdp = MD_TO_MDP(md); checkhdr(mdp, hdr); hdr->magic = MAGICWORDFREE; mdp->ufree_hook = NULL; ufree(md, (void *) hdr); mdp->ufree_hook = ufree_check; }
void mcheck_check_all (void) { /* Walk through all the active blocks and test whether they were tampered with. */ struct hdr *runp = root; /* Temporarily turn off the checks. */ pedantic = 0; while (runp != NULL) { (void) checkhdr (runp); runp = runp->next; } /* Turn checks on again. */ pedantic = 1; }
static void *urealloc_check(void *md, void *ptr, uintptr_t size) { struct hdr *hdr = ((struct hdr *) ptr) - 1; struct mdesc *mdp; uintptr_t nbytes; mdp = MD_TO_MDP(md); checkhdr(mdp, hdr); mdp->ufree_hook = NULL; mdp->umalloc_hook = NULL; mdp->urealloc_hook = NULL; nbytes = sizeof(struct hdr) + size + 1; hdr = (struct hdr *) urealloc(md, (void *) hdr, nbytes); mdp->ufree_hook = ufree_check; mdp->umalloc_hook = umalloc_check; mdp->urealloc_hook = urealloc_check; if (hdr != NULL) { hdr->size = size; hdr++; *((char *) hdr + size) = MAGICBYTE; } return ((void *) hdr); }
static void freehook (__ptr_t ptr, const __ptr_t caller) { if (pedantic) mcheck_check_all (); if (ptr) { struct hdr *hdr = ((struct hdr *) ptr) - 1; checkhdr (hdr); hdr->magic = MAGICFREE; hdr->magic2 = MAGICFREE; unlink_blk (hdr); hdr->prev = hdr->next = NULL; flood (ptr, FREEFLOOD, hdr->size); ptr = hdr->block; } __free_hook = old_free_hook; if (old_free_hook != NULL) (*old_free_hook)(ptr, caller); else free (ptr); __free_hook = freehook; }
static __ptr_t reallochook (__ptr_t ptr, size_t size, const __ptr_t caller) { if (size == 0) { freehook (ptr, caller); return NULL; } struct hdr *hdr; size_t osize; if (pedantic) mcheck_check_all (); if (size > ~((size_t) 0) - (sizeof (struct hdr) + 1)) { __set_errno (ENOMEM); return NULL; } if (ptr) { hdr = ((struct hdr *) ptr) - 1; osize = hdr->size; checkhdr (hdr); unlink_blk (hdr); if (size < osize) flood ((char *) ptr + size, FREEFLOOD, osize - size); } else { osize = 0; hdr = NULL; } __free_hook = old_free_hook; __malloc_hook = old_malloc_hook; __memalign_hook = old_memalign_hook; __realloc_hook = old_realloc_hook; if (old_realloc_hook != NULL) hdr = (struct hdr *) (*old_realloc_hook)((__ptr_t) hdr, sizeof (struct hdr) + size + 1, caller); else hdr = (struct hdr *) realloc ((__ptr_t) hdr, sizeof (struct hdr) + size + 1); __free_hook = freehook; __malloc_hook = mallochook; __memalign_hook = memalignhook; __realloc_hook = reallochook; if (hdr == NULL) return NULL; hdr->size = size; link_blk (hdr); hdr->block = hdr; hdr->magic2 = (uintptr_t) hdr ^ MAGICWORD; ((char *) &hdr[1])[size] = MAGICBYTE; if (size > osize) flood ((char *) (hdr + 1) + osize, MALLOCFLOOD, size - osize); return (__ptr_t) (hdr + 1); }
enum mcheck_status mprobe (__ptr_t ptr) { return mcheck_used ? checkhdr (((struct hdr *) ptr) - 1) : MCHECK_DISABLED; }