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