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