
#include "mystdlib.h"
#include "string.h"
#include "exception.h"
#include "stdio.h"
#include "debug.h"





static void __mem_append_m(map_def** m , void* p);


void __mem_clear(map_def **m){
  if(!(*m)){
    return;
  }
  size_t *map=(*m)->mem_map;
  size_t size=(*m)->map_size;
  for(size_t i=0;i<size;i++){
    if(map[i]){
      free((void *)map[i]);
      DBG_INFO("clear eme_p=%08lx\n",map[i]);
    }
  }
  free(*m);
  *m=0;
}



void __mem_mov(map_def **d,map_def **s){
  if(!(*s)){
    return;
  }
  size_t *map=(*s)->mem_map;
  for(size_t i=0;i<(*s)->map_size;i++){
    if(map[i]){
      __mem_append_m(d,(void *)map[i]);
    }
  }
  free(*s);
  (*s)=0;
  DBG_INFO("mem mov end.\n");
}




void mem_free(void *p){
  exception_def *th=exception();
  map_def **m=&th->jmp_head->mem;
  if(*m){
    for(size_t i=0;i<(*m)->map_size;i++){
      if((*m)->mem_map[i]==(size_t)p){
        (*m)->mem_map[i]=0;
        DBG_INFO("free eme_p=%08lx\n",(size_t)p);
        (*m)->mam_used--;
        break;
      }
    }
  }
  free(p);
}

static void __mem_append_m(map_def **m,void *p){
  if(!(*m)){
    (*m)=calloc(sizeof(map_def)+MAP_SIZE_STEP*sizeof(size_t),1);
    (*m)->map_size=MAP_SIZE_STEP;
  }
  if((*m)->mam_used>=(*m)->map_size){
    map_def *mt=*m;
    *m=calloc(sizeof(map_def)+((*m)->map_size+ MAP_SIZE_STEP)*sizeof(size_t),1);
    (*m)->mam_used=mt->mam_used;
    (*m)->map_size=mt->map_size+MAP_SIZE_STEP;
    memcpy((*m)->mem_map,mt->mem_map,mt->map_size*sizeof(size_t));
    free(mt);
  }
  if((*m)->mam_used<(*m)->map_size){
    for(size_t i=0;i<(*m)->map_size;i++){
      if((*m)->mem_map[i]==0){
        (*m)->mem_map[i]=(size_t)p;
        DBG_INFO("append eme_p=%08lx\n",(size_t)p);
        (*m)->mam_used++;
        break;
      }
    }
  }
}

static void __mem_append(void *p){
  exception_def *th=exception();
  map_def **m=&th->jmp_head->mem;
  __mem_append_m(m,p);
}

void *mem_malloc(size_t size){
  void *p=malloc(size);
  __mem_append(p);
  return p;
}

void *mem_calloc(size_t memb_num, size_t memb_size){
  void *p=calloc(memb_num, memb_size);
  __mem_append(p);
  return p;
}



