more documentation
[model-checker.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 <cstring>
8 #include <cstdio>
9 #include "snapshot.h"
10 #include "snapshotimp.h"
11 #include "mymemory.h"
12 #include <fcntl.h>
13 #include <assert.h>
14 #include <pthread.h>
15 #include <semaphore.h>
16 #include <errno.h>
17 #include <sys/wait.h>
18 #include <ucontext.h>
19
20 //extern declaration definition
21 #define FAILURE(mesg) { printf("failed in the API: %s with errno relative message: %s\n", mesg, strerror( errno ) ); exit(EXIT_FAILURE); }
22 #if USE_MPROTECT_SNAPSHOT
23 struct SnapShot * snapshotrecord = NULL;
24 struct Snapshot_t * sTheRecord = NULL;
25 #else
26 struct Snapshot_t * sTheRecord = NULL;
27 #endif
28 void DumpIntoLog( const char * filename, const char * message ){
29 #if SSDEBUG
30         static pid_t thePID = getpid();
31         char newFn[ 1024 ] ={ 0 };
32         sprintf( newFn,"%s-%d.txt", filename, thePID );
33         FILE * myFile = fopen( newFn, "w+" );
34         fprintf( myFile, "the message %s: the process id %d\n", message, thePID );
35         fflush( myFile );
36         fclose( myFile );
37         myFile = NULL;
38 #endif
39 }
40 #if !USE_MPROTECT_SNAPSHOT
41 static ucontext_t savedSnapshotContext;
42 static ucontext_t savedUserSnapshotContext;
43 static snapshot_id snapshotid = 0;
44 #endif
45 /* Initialize snapshot data structure */
46 #if USE_MPROTECT_SNAPSHOT
47 void initSnapShotRecord(unsigned int numbackingpages, unsigned int numsnapshots, unsigned int nummemoryregions) {
48         snapshotrecord=( struct SnapShot * )MYMALLOC(sizeof(struct SnapShot));
49         snapshotrecord->regionsToSnapShot=( struct MemoryRegion * )MYMALLOC(sizeof(struct MemoryRegion)*nummemoryregions);
50         snapshotrecord->backingStoreBasePtr= ( struct SnapShotPage * )MYMALLOC( sizeof( struct SnapShotPage ) * (numbackingpages + 1) );
51         //Page align the backingstorepages
52         snapshotrecord->backingStore=( struct SnapShotPage * )PageAlignAddressUpward(snapshotrecord->backingStoreBasePtr);
53         snapshotrecord->backingRecords=( struct BackingPageRecord * )MYMALLOC(sizeof(struct BackingPageRecord)*numbackingpages);
54         snapshotrecord->snapShots= ( struct SnapShotRecord * )MYMALLOC(sizeof(struct SnapShotRecord)*numsnapshots);
55         snapshotrecord->lastSnapShot=0;
56         snapshotrecord->lastBackingPage=0;
57         snapshotrecord->lastRegion=0;
58         snapshotrecord->maxRegions=nummemoryregions;
59         snapshotrecord->maxBackingPages=numbackingpages;
60         snapshotrecord->maxSnapShots=numsnapshots;
61 }
62 #endif //nothing to initialize for the fork based snapshotting.
63
64 /** HandlePF is the page fault handler for mprotect based snapshotting
65  * algorithm.
66  */
67
68 void HandlePF( int sig, siginfo_t *si, void * unused){
69 #if USE_MPROTECT_SNAPSHOT
70         if( si->si_code == SEGV_MAPERR ){
71                 printf("Real Fault at %p\n", si->si_addr);
72                 exit( EXIT_FAILURE );
73         }
74         void* addr = ReturnPageAlignedAddress(si->si_addr);
75
76         unsigned int backingpage=snapshotrecord->lastBackingPage++; //Could run out of pages...
77         if (backingpage==snapshotrecord->maxBackingPages) {
78                 printf("Out of backing pages at %p\n", si->si_addr);
79                 exit( EXIT_FAILURE );
80         }
81
82         //copy page
83         memcpy(&(snapshotrecord->backingStore[backingpage]), addr, sizeof(struct SnapShotPage));
84         //remember where to copy page back to
85         snapshotrecord->backingRecords[backingpage].basePtrOfPage=addr;
86         //set protection to read/write
87         if (mprotect( addr, sizeof(struct SnapShotPage), PROT_READ | PROT_WRITE )) {
88                 perror("mprotect");
89                 // Handle error by quitting?
90         }
91 #endif //nothing to handle for non snapshotting case.
92 }
93
94 /** ReturnPageAlignedAddress returns a page aligned address for the
95  * address being added as a side effect the numBytes are also changed.
96  */
97
98 void * ReturnPageAlignedAddress(void * addr) {
99         return (void *)(((uintptr_t)addr)&~(PAGESIZE-1));
100 }
101
102 /** PageAlignedAdressUpdate return a page aligned address for the
103  * address being added as a side effect the numBytes are also changed.
104  */
105
106 void * PageAlignAddressUpward(void * addr) {
107         return (void *)((((uintptr_t)addr)+PAGESIZE-1)&~(PAGESIZE-1));
108 }
109 #ifdef __cplusplus
110 extern "C" {
111 #endif
112         void createSharedLibrary(){
113 #if !USE_MPROTECT_SNAPSHOT
114                 //step 1. create shared memory.
115                 if( sTheRecord ) return;
116                 int fd = shm_open( "/ModelChecker-Snapshotter", O_RDWR | O_CREAT, 0777 ); //universal permissions.
117                 if( -1 == fd ) FAILURE("shm_open");
118                 if( -1 == ftruncate( fd, ( size_t )SHARED_MEMORY_DEFAULT + ( size_t )STACK_SIZE_DEFAULT ) ) FAILURE( "ftruncate" );
119                 char * memMapBase = ( char * ) mmap( 0, ( size_t )SHARED_MEMORY_DEFAULT + ( size_t )STACK_SIZE_DEFAULT, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0 );
120                 if( MAP_FAILED == memMapBase ) FAILURE("mmap");
121                 sTheRecord = ( struct Snapshot_t * )memMapBase;
122                 sTheRecord->mSharedMemoryBase = memMapBase + sizeof( struct Snapshot_t );
123                 sTheRecord->mStackBase = ( char * )memMapBase + ( size_t )SHARED_MEMORY_DEFAULT;
124                 sTheRecord->mStackSize = STACK_SIZE_DEFAULT;
125                 sTheRecord->mIDToRollback = -1;
126                 sTheRecord->currSnapShotID = 0;
127                 sTheRecord->mbFinalize = false;
128 #endif
129         }
130 #ifdef __cplusplus
131 }
132 #endif
133
134 /** The initSnapShotLibrary function initializes the Snapshot library.
135  *  @param entryPoint the function that should run the program.
136  */
137 void initSnapShotLibrary(unsigned int numbackingpages,
138                 unsigned int numsnapshots, unsigned int nummemoryregions,
139                 unsigned int numheappages, VoidFuncPtr entryPoint) {
140 #if USE_MPROTECT_SNAPSHOT
141         /* Setup a stack for our signal handler....  */
142         stack_t ss;
143         ss.ss_sp = MYMALLOC(SIGSTACKSIZE);
144         ss.ss_size = SIGSTACKSIZE;
145         ss.ss_flags = 0;
146         sigaltstack(&ss, NULL);
147
148         struct sigaction sa;
149         sa.sa_flags = SA_SIGINFO | SA_NODEFER | SA_RESTART | SA_ONSTACK;
150         sigemptyset( &sa.sa_mask );
151         sa.sa_sigaction = HandlePF;
152 #ifdef MAC
153         if( sigaction( SIGBUS, &sa, NULL ) == -1 ){
154                 printf("SIGACTION CANNOT BE INSTALLED\n");
155                 exit(EXIT_FAILURE);
156         }
157 #endif
158         if( sigaction( SIGSEGV, &sa, NULL ) == -1 ){
159                 printf("SIGACTION CANNOT BE INSTALLED\n");
160                 exit(EXIT_FAILURE);
161         }
162
163         initSnapShotRecord(numbackingpages, numsnapshots, nummemoryregions);
164
165         // EVIL HACK: We need to make sure that calls into the HandlePF method don't cause dynamic links
166         // The problem is that we end up protecting state in the dynamic linker...
167         // Solution is to call our signal handler before we start protecting stuff...
168
169         siginfo_t si;
170         memset(&si, 0, sizeof(si));
171         si.si_addr=ss.ss_sp;
172         HandlePF(SIGSEGV, &si, NULL);
173         snapshotrecord->lastBackingPage--; //remove the fake page we copied
174
175         basemySpace=MYMALLOC((numheappages+1)*PAGESIZE);
176         void * pagealignedbase=PageAlignAddressUpward(basemySpace);
177         mySpace = create_mspace_with_base(pagealignedbase,  numheappages*PAGESIZE, 1 );
178         addMemoryRegionToSnapShot(pagealignedbase, numheappages);
179         entryPoint();
180 #else
181
182         basemySpace=system_malloc((numheappages+1)*PAGESIZE);
183         void * pagealignedbase=PageAlignAddressUpward(basemySpace);
184         mySpace = create_mspace_with_base(pagealignedbase,  numheappages*PAGESIZE, 1 );
185         createSharedLibrary();
186
187         //step 2 setup the stack context.
188
189         int alreadySwapped = 0;
190         getcontext( &savedSnapshotContext );
191         if( !alreadySwapped ){
192                 alreadySwapped = 1;
193                 ucontext_t currentContext, swappedContext, newContext;
194                 getcontext( &newContext );
195                 newContext.uc_stack.ss_sp = sTheRecord->mStackBase;
196                 newContext.uc_stack.ss_size = STACK_SIZE_DEFAULT;
197                 newContext.uc_link = &currentContext;
198                 makecontext( &newContext, entryPoint, 0 );
199                 swapcontext( &swappedContext, &newContext );
200         }
201
202         //add the code to take a snapshot here...
203         //to return to user process, do a second swapcontext...
204         pid_t forkedID = 0;
205         snapshotid = sTheRecord->currSnapShotID;
206         bool swapContext = false;
207         while( !sTheRecord->mbFinalize ){
208                 sTheRecord->currSnapShotID=snapshotid+1;
209                 forkedID = fork();
210                 if( 0 == forkedID ){
211                         ucontext_t currentContext;
212 #if 0
213                         int dbg = 0;
214                         while( !dbg );
215 #endif
216                         if( swapContext )
217                                 swapcontext( &currentContext, &( sTheRecord->mContextToRollback ) );
218                         else{
219                                 swapcontext( &currentContext, &savedUserSnapshotContext );
220                         }
221                 } else {
222                         int status;
223                         int retVal;
224 #if SSDEBUG
225                         char mesg[ 1024 ] = { 0 };
226                         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 );
227                         DumpIntoLog( "ModelSnapshot", mesg );
228 #endif
229                         do {
230                                 retVal=waitpid( forkedID, &status, 0 );
231                         } while( -1 == retVal && errno == EINTR );
232
233                         if( sTheRecord->mIDToRollback != snapshotid )
234                                 exit(EXIT_SUCCESS);
235                         else{
236                                 swapContext = true;
237                         }
238                 }
239         }
240
241 #endif
242 }
243
244 /** The addMemoryRegionToSnapShot function assumes that addr is page aligned. 
245  */
246 void addMemoryRegionToSnapShot( void * addr, unsigned int numPages) {
247 #if USE_MPROTECT_SNAPSHOT
248         unsigned int memoryregion=snapshotrecord->lastRegion++;
249         if (memoryregion==snapshotrecord->maxRegions) {
250                 printf("Exceeded supported number of memory regions!\n");
251                 exit(EXIT_FAILURE);
252         }
253
254         snapshotrecord->regionsToSnapShot[ memoryregion ].basePtr=addr;
255         snapshotrecord->regionsToSnapShot[ memoryregion ].sizeInPages=numPages;
256 #endif //NOT REQUIRED IN THE CASE OF FORK BASED SNAPSHOTS.
257 }
258
259 /** The takeSnapshot function takes a snapshot.
260  * @return The snapshot identifier.
261  */
262
263 snapshot_id takeSnapshot( ){
264 #if USE_MPROTECT_SNAPSHOT
265         for(unsigned int region=0; region<snapshotrecord->lastRegion;region++) {
266                 if( mprotect(snapshotrecord->regionsToSnapShot[region].basePtr, snapshotrecord->regionsToSnapShot[region].sizeInPages*sizeof(struct SnapShotPage), PROT_READ ) == -1 ){
267                         perror("mprotect");
268                         printf("Failed to mprotect inside of takeSnapShot\n");
269                         exit(EXIT_FAILURE);
270                 }
271         }
272         unsigned int snapshot=snapshotrecord->lastSnapShot++;
273         if (snapshot==snapshotrecord->maxSnapShots) {
274                 printf("Out of snapshots\n");
275                 exit(EXIT_FAILURE);
276         }
277         snapshotrecord->snapShots[snapshot].firstBackingPage=snapshotrecord->lastBackingPage;
278
279         return snapshot;
280 #else
281         swapcontext( &savedUserSnapshotContext, &savedSnapshotContext );
282         return snapshotid;
283 #endif
284 }
285
286 /** The rollBack function rollback to the given snapshot identifier.
287  *  @param theID is the snapshot identifier to rollback to.
288  */
289
290 void rollBack( snapshot_id theID ){
291 #if USE_MPROTECT_SNAPSHOT
292         std::map< void *, bool, std::less< void * >, MyAlloc< std::pair< const void *, bool > > > duplicateMap;
293         for(unsigned int region=0; region<snapshotrecord->lastRegion;region++) {
294                 if( mprotect(snapshotrecord->regionsToSnapShot[region].basePtr, snapshotrecord->regionsToSnapShot[region].sizeInPages*sizeof(struct SnapShotPage), PROT_READ | PROT_WRITE ) == -1 ){
295                         perror("mprotect");
296                         printf("Failed to mprotect inside of takeSnapShot\n");
297                         exit(EXIT_FAILURE);
298                 }
299         }
300         for(unsigned int page=snapshotrecord->snapShots[theID].firstBackingPage; page<snapshotrecord->lastBackingPage; page++) {
301                 bool oldVal = false;
302                 if( duplicateMap.find( snapshotrecord->backingRecords[page].basePtrOfPage ) != duplicateMap.end() ){
303                         oldVal = true;
304                 }
305                 else{
306                         duplicateMap[ snapshotrecord->backingRecords[page].basePtrOfPage ] = true;
307                 }
308                 if(  !oldVal ){
309                         memcpy(snapshotrecord->backingRecords[page].basePtrOfPage, &snapshotrecord->backingStore[page], sizeof(struct SnapShotPage));
310                 }
311         }
312         snapshotrecord->lastSnapShot=theID;
313         snapshotrecord->lastBackingPage=snapshotrecord->snapShots[theID].firstBackingPage;
314         takeSnapshot(); //Make sure current snapshot is still good...All later ones are cleared
315 #else
316         sTheRecord->mIDToRollback = theID;
317         int sTemp = 0;
318         getcontext( &sTheRecord->mContextToRollback );
319         if( !sTemp ){
320                 sTemp = 1;
321 #if SSDEBUG
322                 DumpIntoLog( "ModelSnapshot", "Invoked rollback" );
323 #endif
324                 exit(EXIT_SUCCESS);
325         }
326 #endif
327 }
328
329 /** The finalize method shuts down the snapshotting system.  */
330
331 void finalize(){
332 #if !USE_MPROTECT_SNAPSHOT
333         sTheRecord->mbFinalize = true;
334 #endif
335 }
336