merging stuff...made need to clean up some stuff...but need to push it somewhere...
[cdsspec-compiler.git] / mymemory.cc
1
2 #include "mymemory.h"
3 #include "snapshot.h"
4 #include "snapshotimp.h"
5 #include <stdio.h>
6 #include <dlfcn.h>
7 #define MSPACE_SIZE ( 1 << 20 )
8 #if !USE_CHECKPOINTING
9 static mspace sStaticSpace = NULL;
10 #endif
11 void *MYMALLOC(size_t size)
12 {
13 #if USE_CHECKPOINTING
14   static void *(*mallocp)(size_t size);
15   char *error;
16   void *ptr;
17
18   /* get address of libc malloc */
19   if (!mallocp) {
20   mallocp = ( void * ( * )( size_t ) )dlsym(RTLD_NEXT, "malloc");
21   if ((error = dlerror()) != NULL) {
22       fputs(error, stderr);
23       exit(1);
24   }
25   }
26   ptr = mallocp(size);     
27   return ptr;
28 #else
29   if( !sTheRecord ){
30     createSharedLibrary();
31   }
32   if( NULL == sStaticSpace )
33   sStaticSpace = create_mspace_with_base( ( void * )( sTheRecord->mSharedMemoryBase ), SHARED_MEMORY_DEFAULT -sizeof( struct Snapshot_t ), 1 );
34   return mspace_malloc( sStaticSpace, size );
35 #endif
36 }
37
38 void MYFREE(void *ptr)
39 {
40 #if USE_CHECKPOINTING
41   static void (*freep)(void *);
42   char *error;
43
44   /* get address of libc free */
45   if (!freep) {
46     freep = ( void  ( * )( void * ) )dlsym(RTLD_NEXT, "free");
47     if ((error = dlerror()) != NULL) {
48       fputs(error, stderr);
49       exit(1);
50     }
51   }
52   freep(ptr);
53 #else
54   mspace_free( sStaticSpace, ptr );
55 #endif
56 }
57 static mspace mySpace = NULL;
58 void *malloc( size_t size ){
59         if( NULL == mySpace ){
60                 //void * mem = MYMALLOC( MSPACE_SIZE );
61                 mySpace = create_mspace( MSPACE_SIZE, 1 );
62         AddUserHeapToSnapshot();
63         }
64         return mspace_malloc( mySpace, size );
65 }
66
67 void free( void * ptr ){
68         mspace_free( mySpace, ptr );
69 }
70
71 void AddUserHeapToSnapshot(){
72     static bool alreadySnapshotted = false;
73     if( alreadySnapshotted ) return;
74     addMemoryRegionToSnapShot( mySpace, MSPACE_SIZE / PAGESIZE );
75 }