/*
 * FILE: util.c
 * PROGRAM: BAT
 * AUTHOR: Isidor Kouvelas
 * 
 * $Revision: 1.1.1.1 $
 * $Date: 1998/08/15 19:16:47 $
 *
 * Copyright (c) 1995,1996 University College London
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, is permitted, for non-commercial use only, provided
 * that the following conditions are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. All advertising materials mentioning features or use of this software
 *    must display the following acknowledgement:
 *      This product includes software developed by the Computer Science
 *      Department at University College London
 * 4. Neither the name of the University nor of the Department may be used
 *    to endorse or promote products derived from this software without
 *    specific prior written permission.
 * Use of this software for commercial purposes is explicitly forbidden
 * unless prior written permission is obtained from the authors.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHORS AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 */

#include "bat_include.h"

#ifdef DEBUG_MEM
static int *addrs[65536];
static char *files[65536];
static int lines[65536];
static int length[65536];
static int  naddr = 0;
#endif

void xmemchk(void)
{
#ifdef DEBUG_MEM
	int i,j;
	if (naddr > 65536) {
		printf("Too many addresses for xmemchk()!\n");
		abort();
	}
	for (i=0; i<naddr; i++) {
		assert(addrs[i] != NULL);
		assert(strlen(files[i]) == length[i]);
#ifndef WIN32
		if ((*addrs[i] != *(addrs[i] + (*addrs[i] / 4) + 2)) || (strncmp(files[i], "src/", 4) != 0)) {
#else
                if ((*addrs[i] != *(addrs[i] + (*addrs[i] / 4) + 2)) ) {
#endif /* WIN32 */
			printf("Memory check failed!\n");
			j = i;
			for (i=0; i<naddr; i++) {
				if (i==j) {                        /* Because occasionally you can't spy the */
					printf("* ");              /* deviant block, we'll highlight it.     */
				} else {
					printf("  ");
				}
				printf("addr: %p", addrs[i]);   				fflush(stdout);
				printf("  size: %6d", *addrs[i]);				fflush(stdout);
				printf("  size: %6d", *(addrs[i] + (*addrs[i] / 4) + 2));	fflush(stdout);
				printf("  file: %s", files[i]);					fflush(stdout);
				printf("  line: %d", lines[i]);					fflush(stdout);
				printf("\n");
			}
			abort();
		}
	}
#endif
}

void xfree(void *y)
{
#ifdef DEBUG_MEM
	char	*x = (char *) y;
	int	i, j;
	assert(x != NULL);
	j = 0;
	for (i = 0; i < naddr - j; i++) {
		if (addrs[i] == (int *)(x-8)) {
			assert(j == 0); /* ...else we're freeing twice! */
			j = 1;
			free(x - 8);
			free(files[i]);
		}
		addrs[i] = addrs[i + j];
		files[i] = files[i + j];
		lines[i] = lines[i + j];
		length[i] = length[i + j];
	}
	assert(j == 1); /* ...else we're freeing something we didn't alloc! */
	naddr -= j;
	xmemchk();
#else
	free(y);
#endif
}

char *
_xmalloc(unsigned size, char *filen, int line)
{
#ifdef DEBUG_MEM
	int  s = ((size/8)*8) + 8;
	int *p = (int *) malloc(s + 16);

	assert(p     != NULL);
	assert(filen != NULL);
/*	assert(strlen(filen) != 0); */
	*p = s;
	*(p+(s/4)+2) = s;
	memset((char *) (p+2), 42, size);
	addrs[naddr]  = p;
	files[naddr]  = strdup(filen);
	lines[naddr]  = line;
	length[naddr] = strlen(filen);
	naddr++;
	xmemchk();
	assert(((char *) (p+2)) != NULL);
	assert(naddr < 65536);	/* ...else we overrun the array of allocated addresses! */
	return (char *) (p+2);
#else
	return (char *) malloc(size);
#endif
}

char *xstrdup(char *s1)
{
  char 	*s2;
  
  s2 = (char *) xmalloc(strlen(s1)+1);
  if (s2!=NULL) {
    strcpy(s2, s1);
  }
  return s2;
}

typedef struct s_block {
	struct s_block  *next;
} block;
 
#define BLOCK_SIZE            5
#define SIZE_TO_INDEX(s)      (((s) - 1) >> BLOCK_SIZE)
#define INDEX_TO_SIZE(i)      (((i) + 1) << BLOCK_SIZE)
#define MAX_SIZE              2048
#define MAX_INDEX             SIZE_TO_INDEX(MAX_SIZE)
 
static block  *blocks[MAX_INDEX];
 
char *
block_alloc(unsigned size)
{
	int     i, *c;
	char    *p;
 
	assert(size > 0);
	assert(size < MAX_SIZE);
 
	i = SIZE_TO_INDEX(size);
 
	if (blocks[i] != NULL) {
		p = (char *)blocks[i];
		blocks[i] = blocks[i]->next;
	} else {
		p = xmalloc(INDEX_TO_SIZE(i) + 8);
		*((int *)p) = INDEX_TO_SIZE(i);
		p += 8;
	}
 
	c = (int *)((char *)p - 8);
	if (size > *c) {
		fprintf(stderr, "block_alloc: block is too small %d %d!\n", size, *c);
	}
	c++;
	*c = size;
 
	assert(p != NULL);
	return p;
}
 
void
block_free(void *p, int size)
{
	int     i, *c;
 
	c = (int *)((char *)p - 8);
	if (size > *c) {
		fprintf(stderr, "block_free: block was too small! %d %d\n", size, *c);
	}
	c++;
	if (size != *c) {
		fprintf(stderr, "block_free: Incorrect block size given! %d %d\n", size, *c);
	}
 
	i = SIZE_TO_INDEX(size);
	((block *)p)->next = blocks[i];
	blocks[i] = (block *)p;
}

