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