Adding support to return global segments of the process using the /proc/maps
[c11tester.git] / snapshot.cc~
1 #include <inttypes.h>
2 #include <sys/mman.h>
3 #include <unistd.h>
4 #include <signal.h>
5 #include <stdlib.h>
6 #include <map>
7 #include <set>
8 #include <cstring>
9 #include <cstdio>
10 #include "snapshot.h"
11 #include "snapshotimp.h"
12 #include "mymemory.h"
13 #include <fcntl.h>
14 #include <assert.h>
15 #include <pthread.h>
16 #include <semaphore.h>
17 #include <errno.h>
18 #include <sys/wait.h>
19 #include <ucontext.h>
20 #include <sys/time.h>
21 //extern declaration definition
22 #define FAILURE(mesg) { printf("failed in the API: %s with errno relative message: %s\n", mesg, strerror( errno ) ); exit( -1 ); }
23 #if USE_CHECKPOINTING
24 struct SnapShot * snapshotrecord = NULL;
25 struct Snapshot_t * sTheRecord = NULL;
26 #else
27 struct Snapshot_t * sTheRecord = NULL;
28 #endif
29 void BeginOperation( struct timeval * theStartTime ){
30 #if 1
31         gettimeofday( theStartTime, NULL );
32 #endif
33 }
34 #if DEBUG
35 struct timeval *starttime = NULL;
36 #endif
37 void DumpIntoLog( const char * filename, const char * message ){
38 #if DEBUG
39    static pid_t thePID = getpid();
40    char newFn[ 1024 ] ={ 0 };
41    sprintf( newFn,"%s-%d.txt", filename, thePID );
42    FILE * myFile = fopen( newFn, "w+" );
43    struct timeval theEndTime;
44    BeginOperation( &theEndTime );
45    double elapsed = ( theEndTime.tv_sec - starttime->tv_sec ) + ( theEndTime.tv_usec - starttime->tv_usec ) / 1000000.0;
46    fprintf( myFile, "The timestamp %f:--> the message %s: the process id %d\n", elapsed, message, thePID );
47    fflush( myFile );
48    fclose( myFile );
49    myFile = NULL;
50 #endif
51 }
52 static ucontext_t savedSnapshotContext;
53 static ucontext_t savedUserSnapshotContext;
54 static int snapshotid = 0;
55 /* Initialize snapshot data structure */
56 #if USE_CHECKPOINTING
57 void initSnapShotRecord(unsigned int numbackingpages, unsigned int numsnapshots, unsigned int nummemoryregions) {
58   snapshotrecord=( struct SnapShot * )MYMALLOC(sizeof(struct SnapShot));
59   snapshotrecord->regionsToSnapShot=( struct MemoryRegion * )MYMALLOC(sizeof(struct MemoryRegion)*nummemoryregions);
60   snapshotrecord->backingStoreBasePtr= ( struct SnapShotPage * )MYMALLOC( sizeof( struct SnapShotPage ) * (numbackingpages + 1) );
61   //Page align the backingstorepages
62   snapshotrecord->backingStore=( struct SnapShotPage * )ReturnPageAlignedAddress((void*) ((uintptr_t)(snapshotrecord->backingStoreBasePtr)+sizeof(struct SnapShotPage)-1));
63   snapshotrecord->backingRecords=( struct BackingPageRecord * )MYMALLOC(sizeof(struct BackingPageRecord)*numbackingpages);
64   snapshotrecord->snapShots= ( struct SnapShotRecord * )MYMALLOC(sizeof(struct SnapShotRecord)*numsnapshots);
65   snapshotrecord->lastSnapShot=0;
66   snapshotrecord->lastBackingPage=0;
67   snapshotrecord->lastRegion=0;
68   snapshotrecord->maxRegions=nummemoryregions;
69   snapshotrecord->maxBackingPages=numbackingpages;
70   snapshotrecord->maxSnapShots=numsnapshots;
71 }
72 #endif //nothing to initialize for the fork based snapshotting.
73
74 void HandlePF( int sig, siginfo_t *si, void * unused){
75 #if USE_CHECKPOINTING
76   if( si->si_code == SEGV_MAPERR ){
77     printf("Real Fault at %llx\n", ( long long )si->si_addr);
78     exit( EXIT_FAILURE );       
79   }
80   void* addr = ReturnPageAlignedAddress(si->si_addr);
81   unsigned int backingpage=snapshotrecord->lastBackingPage++; //Could run out of pages...
82   if (backingpage==snapshotrecord->maxBackingPages) {
83     printf("Out of backing pages at %llx\n", ( long long )si->si_addr);
84     exit( EXIT_FAILURE );       
85   }
86
87   //copy page
88   memcpy(&(snapshotrecord->backingStore[backingpage]), addr, sizeof(struct SnapShotPage));
89   //remember where to copy page back to
90   snapshotrecord->backingRecords[backingpage].basePtrOfPage=addr;
91   //set protection to read/write
92   mprotect( addr, sizeof(struct SnapShotPage), PROT_READ | PROT_WRITE );  
93 #endif //nothing to handle for non snapshotting case.
94 }
95
96 //Return a page aligned address for the address being added
97 //as a side effect the numBytes are also changed.
98 void * ReturnPageAlignedAddress(void * addr) {
99   return (void *)(((uintptr_t)addr)&~(PAGESIZE-1));
100 }
101 #ifdef __cplusplus
102 extern "C" {
103 #endif
104 void createSharedLibrary(){
105 #if !USE_CHECKPOINTING
106           //step 1. create shared memory.
107   if( sTheRecord ) return;
108   int fd = shm_open( "/ModelChecker-Snapshotter", O_RDWR | O_CREAT, 0777 ); //universal permissions.
109   if( -1 == fd ) FAILURE("shm_open");
110   if( -1 == ftruncate( fd, ( size_t )SHARED_MEMORY_DEFAULT + ( size_t )STACK_SIZE_DEFAULT ) ) FAILURE( "ftruncate" );
111   char * memMapBase = ( char * ) mmap( 0, ( size_t )SHARED_MEMORY_DEFAULT + ( size_t )STACK_SIZE_DEFAULT, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0 );
112   if( MAP_FAILED == memMapBase ) FAILURE("mmap");
113   sTheRecord = ( struct Snapshot_t * )memMapBase;
114   sTheRecord->mSharedMemoryBase = memMapBase + sizeof( struct Snapshot_t );
115   sTheRecord->mStackBase = ( char * )memMapBase + ( size_t )SHARED_MEMORY_DEFAULT;
116   sTheRecord->mStackSize = STACK_SIZE_DEFAULT;
117   sTheRecord->mIDToRollback = -1;
118   sTheRecord->currSnapShotID = 0;
119 #endif
120 }
121 #ifdef __cplusplus
122 }
123 #endif
124 void initSnapShotLibrary(unsigned int numbackingpages, unsigned int numsnapshots, unsigned int nummemoryregions , MyFuncPtr entryPoint){
125 #if USE_CHECKPOINTING
126   struct sigaction sa;
127   sa.sa_flags = SA_SIGINFO | SA_NODEFER | SA_RESTART;
128   sigemptyset( &sa.sa_mask );
129   sa.sa_sigaction = HandlePF;
130   if( sigaction( SIGSEGV, &sa, NULL ) == -1 ){
131     printf("SIGACTION CANNOT BE INSTALLED\n");
132     exit(-1);
133   }
134   initSnapShotRecord(numbackingpages, numsnapshots, nummemoryregions);
135   entryPoint();
136 #else
137   //add a signal to indicate that the process is going to terminate.
138   struct sigaction sa;
139   sa.sa_flags = SA_SIGINFO | SA_NODEFER | SA_RESTART;
140   sigemptyset( &sa.sa_mask );
141   sa.sa_sigaction = HandlePF;
142   if( sigaction( SIGUSR1, &sa, NULL ) == -1 ){
143     printf("SIGACTION CANNOT BE INSTALLED\n");
144     exit(-1);
145   }
146   createSharedLibrary();
147  #if DEBUG
148   starttime = &(sTheRecord->startTimeGlobal);
149   gettimeofday( starttime, NULL );
150 #endif
151   //step 2 setup the stack context.
152  
153   int alreadySwapped = 0;
154   getcontext( &savedSnapshotContext );
155   if( !alreadySwapped ){
156     alreadySwapped = 1;
157     ucontext_t currentContext, swappedContext, newContext;
158     getcontext( &newContext );
159     newContext.uc_stack.ss_sp = sTheRecord->mStackBase;
160     newContext.uc_stack.ss_size = STACK_SIZE_DEFAULT;
161     newContext.uc_link = &currentContext;
162     makecontext( &newContext, entryPoint, 0 );
163     swapcontext( &swappedContext, &newContext );
164   }
165   
166    //add the code to take a snapshot here...
167         //to return to user process, do a second swapcontext...
168   pid_t forkedID = 0;
169   snapshotid = sTheRecord->currSnapShotID;
170   bool swapContext = false;
171   while( !sTheRecord->mbFinalize ){
172     sTheRecord->currSnapShotID=snapshotid+1;
173     forkedID = fork();
174     if( 0 == forkedID ){ 
175       ucontext_t currentContext;
176 #if 0
177       int dbg = 0;
178       while( !dbg );
179 #endif
180       if( swapContext )
181         swapcontext( &currentContext, &( sTheRecord->mContextToRollback ) );
182                         else{
183                                 swapcontext( &currentContext, &savedUserSnapshotContext );      
184                         }
185     } else {
186       int status;
187       int retVal;
188 #if DEBUG
189       char mesg[ 1024 ] = { 0 };
190       sprintf( mesg, "The process id of child is %d and the process id of this process is %d and snapshot id is %d", forkedID, getpid(), snapshotid );
191       DumpIntoLog( "ModelSnapshot", mesg );
192 #endif
193       do { 
194                                 retVal=waitpid( forkedID, &status, 0 );
195       } while( -1 == retVal && errno == EINTR );
196
197       if( sTheRecord->mIDToRollback != snapshotid )
198                           exit(0);
199       else{
200          swapContext = true;
201       }
202     }
203   }
204   
205 #endif
206 }
207 /* This function assumes that addr is page aligned */
208 void addMemoryRegionToSnapShot( void * addr, unsigned int numPages) {
209 #if USE_CHECKPOINTING
210   unsigned int memoryregion=snapshotrecord->lastRegion++;
211   if (memoryregion==snapshotrecord->maxRegions) {
212     printf("Exceeded supported number of memory regions!\n");
213     exit(-1);
214   }
215   
216   snapshotrecord->regionsToSnapShot[ memoryregion ].basePtr=addr;
217   snapshotrecord->regionsToSnapShot[ memoryregion ].sizeInPages=numPages;
218 #endif //NOT REQUIRED IN THE CASE OF FORK BASED SNAPSHOTS.
219 }
220 //take snapshot
221 snapshot_id takeSnapshot( ){
222 #if USE_CHECKPOINTING
223   for(unsigned int region=0; region<snapshotrecord->lastRegion;region++) {
224     if( mprotect(snapshotrecord->regionsToSnapShot[region].basePtr, snapshotrecord->regionsToSnapShot[region].sizeInPages*sizeof(struct SnapShotPage), PROT_READ ) == -1 ){
225       printf("Failed to mprotect inside of takeSnapShot\n");
226       exit(-1);
227     }           
228   }
229   unsigned int snapshot=snapshotrecord->lastSnapShot++;
230   if (snapshot==snapshotrecord->maxSnapShots) {
231     printf("Out of snapshots\n");
232     exit(-1);
233   }
234   snapshotrecord->snapShots[snapshot].firstBackingPage=snapshotrecord->lastBackingPage;
235   
236   return snapshot;
237 #else
238   swapcontext( &savedUserSnapshotContext, &savedSnapshotContext );
239   return snapshotid;
240 #endif
241 }
242 void rollBack( snapshot_id theID ){
243 #if USE_CHECKPOINTING
244   std::map< void *, bool, std::less< void * >, MyAlloc< std::pair< const void *, bool > > > duplicateMap;
245   for(unsigned int region=0; region<snapshotrecord->lastRegion;region++) {
246   if( mprotect(snapshotrecord->regionsToSnapShot[region].basePtr, snapshotrecord->regionsToSnapShot[region].sizeInPages*sizeof(struct SnapShotPage), PROT_READ | PROT_WRITE ) == -1 ){
247       printf("Failed to mprotect inside of takeSnapShot\n");
248       exit(-1);
249     }           
250   }
251   for(unsigned int page=snapshotrecord->snapShots[theID].firstBackingPage; page<snapshotrecord->lastBackingPage; page++) {
252     bool oldVal = false;
253     if( duplicateMap.find( snapshotrecord->backingRecords[page].basePtrOfPage ) != duplicateMap.end() ){
254       oldVal = true;          
255     }
256     else{
257       duplicateMap[ snapshotrecord->backingRecords[page].basePtrOfPage ] = true;    
258     }
259     if(  !oldVal ){
260       memcpy(snapshotrecord->backingRecords[page].basePtrOfPage, &snapshotrecord->backingStore[page], sizeof(struct SnapShotPage));
261     }
262   }
263   snapshotrecord->lastSnapShot=theID;
264   snapshotrecord->lastBackingPage=snapshotrecord->snapShots[theID].firstBackingPage;
265   takeSnapshot(); //Make sure current snapshot is still good...All later ones are cleared
266 #else
267   sTheRecord->mIDToRollback = theID;
268   int sTemp = 0;
269   getcontext( &sTheRecord->mContextToRollback );
270   if( !sTemp ){
271     sTemp = 1;
272 #if DEBUG
273         DumpIntoLog( "ModelSnapshot", "Invoked rollback" ); 
274 #endif
275         exit( 0 );
276   }
277 #endif
278 }
279
280 void finalize(){
281 #if !USE_CHECKPOINTING
282   sTheRecord->mbFinalize = true;
283 #endif
284 }
285