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