fix one segfault bug...something is still strange, but has to do with stack
[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 SSDEBUG
35 struct timeval *starttime = NULL;
36 #endif
37 void DumpIntoLog( const char * filename, const char * message ){
38 #if SSDEBUG
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 #if !USE_CHECKPOINTING
53 static ucontext_t savedSnapshotContext;
54 static ucontext_t savedUserSnapshotContext;
55 static int snapshotid = 0;
56 #endif
57 /* Initialize snapshot data structure */
58 #if USE_CHECKPOINTING
59 void initSnapShotRecord(unsigned int numbackingpages, unsigned int numsnapshots, unsigned int nummemoryregions) {
60         snapshotrecord=( struct SnapShot * )MYMALLOC(sizeof(struct SnapShot));
61         snapshotrecord->regionsToSnapShot=( struct MemoryRegion * )MYMALLOC(sizeof(struct MemoryRegion)*nummemoryregions);
62         snapshotrecord->backingStoreBasePtr= ( struct SnapShotPage * )MYMALLOC( sizeof( struct SnapShotPage ) * (numbackingpages + 1) );
63         //Page align the backingstorepages
64         snapshotrecord->backingStore=( struct SnapShotPage * )PageAlignAddressUpward(snapshotrecord->backingStoreBasePtr);
65         snapshotrecord->backingRecords=( struct BackingPageRecord * )MYMALLOC(sizeof(struct BackingPageRecord)*numbackingpages);
66         snapshotrecord->snapShots= ( struct SnapShotRecord * )MYMALLOC(sizeof(struct SnapShotRecord)*numsnapshots);
67         snapshotrecord->lastSnapShot=0;
68         snapshotrecord->lastBackingPage=0;
69         snapshotrecord->lastRegion=0;
70         snapshotrecord->maxRegions=nummemoryregions;
71         snapshotrecord->maxBackingPages=numbackingpages;
72         snapshotrecord->maxSnapShots=numsnapshots;
73 }
74 #endif //nothing to initialize for the fork based snapshotting.
75
76 void HandlePF( int sig, siginfo_t *si, void * unused){
77 #if USE_CHECKPOINTING
78         if( si->si_code == SEGV_MAPERR ){
79                 printf("Real Fault at %llx\n", ( long long )si->si_addr);
80                 exit( EXIT_FAILURE );   
81         }
82         void* addr = ReturnPageAlignedAddress(si->si_addr);
83         unsigned int backingpage=snapshotrecord->lastBackingPage++; //Could run out of pages...
84         if (backingpage==snapshotrecord->maxBackingPages) {
85                 printf("Out of backing pages at %llx\n", ( long long )si->si_addr);
86                 exit( EXIT_FAILURE );   
87         }
88
89         //copy page
90         memcpy(&(snapshotrecord->backingStore[backingpage]), addr, sizeof(struct SnapShotPage));
91         //remember where to copy page back to
92         snapshotrecord->backingRecords[backingpage].basePtrOfPage=addr;
93         //set protection to read/write
94         if (mprotect( addr, sizeof(struct SnapShotPage), PROT_READ | PROT_WRITE )) {
95                 perror("mprotect");
96                 // Handle error by quitting?
97         }
98 #endif //nothing to handle for non snapshotting case.
99 }
100
101 //Return a page aligned address for the address being added
102 //as a side effect the numBytes are also changed.
103 void * ReturnPageAlignedAddress(void * addr) {
104         return (void *)(((uintptr_t)addr)&~(PAGESIZE-1));
105 }
106
107 //Return a page aligned address for the address being added
108 //as a side effect the numBytes are also changed.
109 void * PageAlignAddressUpward(void * addr) {
110         return (void *)((((uintptr_t)addr)+PAGESIZE-1)&~(PAGESIZE-1));
111 }
112 #ifdef __cplusplus
113 extern "C" {
114 #endif
115         void createSharedLibrary(){
116 #if !USE_CHECKPOINTING
117                 //step 1. create shared memory.
118                 if( sTheRecord ) return;
119                 int fd = shm_open( "/ModelChecker-Snapshotter", O_RDWR | O_CREAT, 0777 ); //universal permissions.
120                 if( -1 == fd ) FAILURE("shm_open");
121                 if( -1 == ftruncate( fd, ( size_t )SHARED_MEMORY_DEFAULT + ( size_t )STACK_SIZE_DEFAULT ) ) FAILURE( "ftruncate" );
122                 char * memMapBase = ( char * ) mmap( 0, ( size_t )SHARED_MEMORY_DEFAULT + ( size_t )STACK_SIZE_DEFAULT, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0 );
123                 if( MAP_FAILED == memMapBase ) FAILURE("mmap");
124                 sTheRecord = ( struct Snapshot_t * )memMapBase;
125                 sTheRecord->mSharedMemoryBase = memMapBase + sizeof( struct Snapshot_t );
126                 sTheRecord->mStackBase = ( char * )memMapBase + ( size_t )SHARED_MEMORY_DEFAULT;
127                 sTheRecord->mStackSize = STACK_SIZE_DEFAULT;
128                 sTheRecord->mIDToRollback = -1;
129                 sTheRecord->currSnapShotID = 0;
130 #endif
131         }
132 #ifdef __cplusplus
133 }
134 #endif
135 void initSnapShotLibrary(unsigned int numbackingpages, unsigned int numsnapshots, unsigned int nummemoryregions, unsigned int numheappages, MyFuncPtr entryPoint){
136 #if USE_CHECKPOINTING
137         struct sigaction sa;
138         sa.sa_flags = SA_SIGINFO | SA_NODEFER | SA_RESTART;
139         sigemptyset( &sa.sa_mask );
140         sa.sa_sigaction = HandlePF;
141         if( sigaction( SIGSEGV, &sa, NULL ) == -1 ){
142                 printf("SIGACTION CANNOT BE INSTALLED\n");
143                 exit(-1);
144         }
145         initSnapShotRecord(numbackingpages, numsnapshots, nummemoryregions);
146         
147         basemySpace=MYMALLOC((numheappages+1)*PAGESIZE);
148         void * pagealignedbase=PageAlignAddressUpward(basemySpace);
149         mySpace = create_mspace_with_base(pagealignedbase,  numheappages*PAGESIZE, 1 );
150         addMemoryRegionToSnapShot(pagealignedbase, numheappages);
151         entryPoint();
152 #else
153         //add a signal to indicate that the process is going to terminate.
154         struct sigaction sa;
155         sa.sa_flags = SA_SIGINFO | SA_NODEFER | SA_RESTART;
156         sigemptyset( &sa.sa_mask );
157         sa.sa_sigaction = HandlePF;
158         if( sigaction( SIGUSR1, &sa, NULL ) == -1 ){
159                 printf("SIGACTION CANNOT BE INSTALLED\n");
160                 exit(-1);
161         }
162         createSharedLibrary();
163 #if SSDEBUG
164         starttime = &(sTheRecord->startTimeGlobal);
165         gettimeofday( starttime, NULL );
166 #endif
167         //step 2 setup the stack context.
168  
169         int alreadySwapped = 0;
170         getcontext( &savedSnapshotContext );
171         if( !alreadySwapped ){
172                 alreadySwapped = 1;
173                 ucontext_t currentContext, swappedContext, newContext;
174                 getcontext( &newContext );
175                 newContext.uc_stack.ss_sp = sTheRecord->mStackBase;
176                 newContext.uc_stack.ss_size = STACK_SIZE_DEFAULT;
177                 newContext.uc_link = &currentContext;
178                 makecontext( &newContext, entryPoint, 0 );
179                 swapcontext( &swappedContext, &newContext );
180         }
181   
182         //add the code to take a snapshot here...
183         //to return to user process, do a second swapcontext...
184         pid_t forkedID = 0;
185         snapshotid = sTheRecord->currSnapShotID;
186         bool swapContext = false;
187         while( !sTheRecord->mbFinalize ){
188                 sTheRecord->currSnapShotID=snapshotid+1;
189                 forkedID = fork();
190                 if( 0 == forkedID ){ 
191                         ucontext_t currentContext;
192 #if 0
193                         int dbg = 0;
194                         while( !dbg );
195 #endif
196                         if( swapContext )
197                                 swapcontext( &currentContext, &( sTheRecord->mContextToRollback ) );
198                         else{
199                                 swapcontext( &currentContext, &savedUserSnapshotContext );      
200                         }
201                 } else {
202                         int status;
203                         int retVal;
204 #if SSDEBUG
205                         char mesg[ 1024 ] = { 0 };
206                         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 );
207                         DumpIntoLog( "ModelSnapshot", mesg );
208 #endif
209                         do { 
210                                 retVal=waitpid( forkedID, &status, 0 );
211                         } while( -1 == retVal && errno == EINTR );
212
213                         if( sTheRecord->mIDToRollback != snapshotid )
214                                 exit(0);
215                         else{
216                                 swapContext = true;
217                         }
218                 }
219         }
220   
221 #endif
222 }
223 /* This function assumes that addr is page aligned */
224 void addMemoryRegionToSnapShot( void * addr, unsigned int numPages) {
225 #if USE_CHECKPOINTING
226         unsigned int memoryregion=snapshotrecord->lastRegion++;
227         if (memoryregion==snapshotrecord->maxRegions) {
228                 printf("Exceeded supported number of memory regions!\n");
229                 exit(-1);
230         }
231   
232         snapshotrecord->regionsToSnapShot[ memoryregion ].basePtr=addr;
233         snapshotrecord->regionsToSnapShot[ memoryregion ].sizeInPages=numPages;
234 #endif //NOT REQUIRED IN THE CASE OF FORK BASED SNAPSHOTS.
235 }
236 //take snapshot
237 snapshot_id takeSnapshot( ){
238 #if USE_CHECKPOINTING
239         for(unsigned int region=0; region<snapshotrecord->lastRegion;region++) {
240                 if( mprotect(snapshotrecord->regionsToSnapShot[region].basePtr, snapshotrecord->regionsToSnapShot[region].sizeInPages*sizeof(struct SnapShotPage), PROT_READ ) == -1 ){
241                         perror("mprotect");
242                         printf("Failed to mprotect inside of takeSnapShot\n");
243                         exit(-1);
244                 }               
245         }
246         unsigned int snapshot=snapshotrecord->lastSnapShot++;
247         if (snapshot==snapshotrecord->maxSnapShots) {
248                 printf("Out of snapshots\n");
249                 exit(-1);
250         }
251         snapshotrecord->snapShots[snapshot].firstBackingPage=snapshotrecord->lastBackingPage;
252   
253         return snapshot;
254 #else
255         swapcontext( &savedUserSnapshotContext, &savedSnapshotContext );
256         return snapshotid;
257 #endif
258 }
259 void rollBack( snapshot_id theID ){
260 #if USE_CHECKPOINTING
261         std::map< void *, bool, std::less< void * >, MyAlloc< std::pair< const void *, bool > > > duplicateMap;
262         for(unsigned int region=0; region<snapshotrecord->lastRegion;region++) {
263                 if( mprotect(snapshotrecord->regionsToSnapShot[region].basePtr, snapshotrecord->regionsToSnapShot[region].sizeInPages*sizeof(struct SnapShotPage), PROT_READ | PROT_WRITE ) == -1 ){
264                         perror("mprotect");
265                         printf("Failed to mprotect inside of takeSnapShot\n");
266                         exit(-1);
267                 }               
268         }
269         for(unsigned int page=snapshotrecord->snapShots[theID].firstBackingPage; page<snapshotrecord->lastBackingPage; page++) {
270                 bool oldVal = false;
271                 if( duplicateMap.find( snapshotrecord->backingRecords[page].basePtrOfPage ) != duplicateMap.end() ){
272                         oldVal = true;          
273                 }
274                 else{
275                         duplicateMap[ snapshotrecord->backingRecords[page].basePtrOfPage ] = true;    
276                 }
277                 if(  !oldVal ){
278                         memcpy(snapshotrecord->backingRecords[page].basePtrOfPage, &snapshotrecord->backingStore[page], sizeof(struct SnapShotPage));
279                 }
280         }
281         snapshotrecord->lastSnapShot=theID;
282         snapshotrecord->lastBackingPage=snapshotrecord->snapShots[theID].firstBackingPage;
283         takeSnapshot(); //Make sure current snapshot is still good...All later ones are cleared
284 #else
285         sTheRecord->mIDToRollback = theID;
286         int sTemp = 0;
287         getcontext( &sTheRecord->mContextToRollback );
288         if( !sTemp ){
289                 sTemp = 1;
290 #if SSDEBUG
291                 DumpIntoLog( "ModelSnapshot", "Invoked rollback" ); 
292 #endif
293                 exit( 0 );
294         }
295 #endif
296 }
297
298 void finalize(){
299 #if !USE_CHECKPOINTING
300         sTheRecord->mbFinalize = true;
301 #endif
302 }
303