/*
 * Copyright (C) 2019 SAMSUNG S.LSI
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#ifdef ESE_U_BOOT_BUILD
#include <linux/string.h>
#include <malloc.h>
#else
#include <string.h>
#include <stdlib.h>
#endif
#include <qsee_heap.h>
#include <ese_util.h>

#define LOG_TAG	"ESE_UTIL"
#define RELEASE_BUILD

#ifdef RELEASE_BUILD
#define API
#else
#define API __attribute__((visibility("default")))
#endif

#ifdef MEMORY_LEAK_TEST
#define MAX_MEMORY_ALLOC_NUM	100

void *alloc_list[MAX_MEMORY_ALLOC_NUM];

API void *ese_malloc(size_t size)
{
	int i = 0;

	for (i = 0; i < MAX_MEMORY_ALLOC_NUM; i ++) {
		if (alloc_list[i] == NULL) {
			break;
		}
	}

	if (i == MAX_MEMORY_ALLOC_NUM) {
		ESELOG_E("<MEMORY> exceed alloc list size");
		return NULL;
	}

	alloc_list[i] = qsee_malloc(size);
	//ESELOG_I("<MEMORY> malloc addr : %p, size : %u", alloc_list[i], (unsigned int)size);
	return alloc_list[i];
}

API void ese_free(void *ptr)
{
	int i = 0;

	for (i = 0; i < MAX_MEMORY_ALLOC_NUM; i ++) {
		if (alloc_list[i] == ptr) {
			break;
		}
	}

	if (i == MAX_MEMORY_ALLOC_NUM) {
		ESELOG_E("<MEMORY> failed to find memory in alloc list : %p", ptr);
		return;
	}

	alloc_list[i] = NULL;
	qsee_free((void *)ptr);
	//ESELOG_I("<MEMORY> free addr : %p", ptr);
}

void ese_print_list(void)
{
	int i = 0;

	for (i = 0; i < MAX_MEMORY_ALLOC_NUM; i ++) {
		if (alloc_list[i] != NULL) {
			ESELOG_E("<MEMORY> non free memory : %p", alloc_list[i]);
		}
	}
}
#endif
