/** * xclaim: * @addr: address * @filen: new filename * @line: new allocation line * * Coerces information in allocation table about allocation file and * line to be @filen and @line. This is used by the evil * block_alloc() and should probably not be used anywhere else ever. **/ void xclaim(void *addr, const char *filen, int line) { alloc_blk *m; chk_header *ch; ch = ((chk_header *)addr) - 1; m = mem_item_find(ch->key); if (chk_header_okay(ch) == FALSE) { fprintf(stderr, "xclaim: memory corrupted\n"); abort(); } if (m == NULL) { fprintf(stderr, "xclaim: block not found\n"); abort(); } free(m->filen); m->filen = strdup(filen); m->length = strlen(filen); m->line = line; m->est = tick++; }
/** * xfree: * @p: pointer to block to freed. * * Free block of memory. Semantically equivalent to free(), but * checks for bounds overruns in @p and tidies up state associated * additional functionality. * * Must be used to free memory allocated with xmalloc(), xrealloc(), * and xstrdup(). **/ void xfree(void *p) { alloc_blk *m; chk_header *ch; uint32_t size, delta, magic, idx; if (p == NULL) { printf("ERROR: Attempt to free NULL pointer!\n"); abort(); } ch = ((chk_header*)p) - 1; printf("free at %p\n", ch); /* Validate entry */ if (chk_header_okay(ch) == FALSE) { printf("ERROR: Freeing corrupted block\n"); abort(); } /* Locate in table */ m = mem_item_find(ch->key); if (m == NULL) { printf("ERROR: Freeing unallocated or already free'd block\n"); abort(); } /* Trash memory of allocated block, maybe noticed by apps when * deref'ing free'd */ size = ch->size + sizeof(chk_header) + MAGIC_MEMORY_SIZE; magic = MAGIC_MEMORY; p = (uint8_t*)ch; while (size > 0) { delta = min(size, 4); memcpy(p, &magic, delta); (uint8_t*)p += delta; size -= delta; } /* Free memory */ free(ch); free(m->filen); /* Remove from table */ idx = m - mem_item; if (naddr - idx > 0) { memmove(&mem_item[idx], &mem_item[idx + 1], (naddr - idx - 1) * sizeof(alloc_blk)); } naddr--; xmemchk(); }
void * _xrealloc(void *p, unsigned size, const char *filen, int line) { alloc_blk *m; chk_header *ch; uint8_t *t; assert(p != NULL); assert(filen != NULL); ch = ((chk_header*) p) - 1; m = mem_item_find(ch->key); if (m != NULL) { /* Attempt reallocation */ m->addr = realloc((void*)ch, size + sizeof(chk_header) + MAGIC_MEMORY_SIZE); if (m->addr == NULL) { debug_msg("realloc failed\n"); return NULL; } /* update ch/p */ ch = (chk_header*)m->addr; p = (void*)(ch+1); /* Update table */ free(m->filen); m->filen = (char *) strdup(filen); m->line = line; m->length = strlen(filen); m->est = tick++; /* Fix chunk header */ ch->size = size; /* Fix trailer */ t = (uint8_t*)p + size; memcpy(t, &ch->magic, MAGIC_MEMORY_SIZE); /* Check block is okay */ if (chk_header_okay(ch) == FALSE) { fprintf(stderr, "Implementation Error\n"); abort(); } return p; } debug_msg("Trying to xrealloc() memory not which is not allocated\n"); abort(); return 0; }