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