snapshot: remove 'extern "C"' block
[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 struct Snapshot_t * sTheRecord = NULL;
32 #else
33 struct Snapshot_t * sTheRecord = NULL;
34 #endif
35
36 #if !USE_MPROTECT_SNAPSHOT
37 static ucontext_t savedSnapshotContext;
38 static ucontext_t savedUserSnapshotContext;
39 static snapshot_id snapshotid = 0;
40 #endif
41
42 #if USE_MPROTECT_SNAPSHOT
43
44 /** The initSnapShotRecord method initialized the snapshotting data
45  *  structures for the mprotect based snapshot. 
46  */
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 void createSharedLibrary(){
110 #if !USE_MPROTECT_SNAPSHOT
111         //step 1. create shared memory.
112         if( sTheRecord ) return;
113         int fd = shm_open( "/ModelChecker-Snapshotter", O_RDWR | O_CREAT, 0777 ); //universal permissions.
114         if( -1 == fd ) FAILURE("shm_open");
115         if( -1 == ftruncate( fd, ( size_t )SHARED_MEMORY_DEFAULT + ( size_t )STACK_SIZE_DEFAULT ) ) FAILURE( "ftruncate" );
116         char * memMapBase = ( char * ) mmap( 0, ( size_t )SHARED_MEMORY_DEFAULT + ( size_t )STACK_SIZE_DEFAULT, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0 );
117         if( MAP_FAILED == memMapBase ) FAILURE("mmap");
118         sTheRecord = ( struct Snapshot_t * )memMapBase;
119         sTheRecord->mSharedMemoryBase = memMapBase + sizeof( struct Snapshot_t );
120         sTheRecord->mStackBase = ( char * )memMapBase + ( size_t )SHARED_MEMORY_DEFAULT;
121         sTheRecord->mStackSize = STACK_SIZE_DEFAULT;
122         sTheRecord->mIDToRollback = -1;
123         sTheRecord->currSnapShotID = 0;
124         sTheRecord->mbFinalize = false;
125 #endif
126 }
127
128 /** The initSnapShotLibrary function initializes the Snapshot library.
129  *  @param entryPoint the function that should run the program.
130  */
131 void initSnapShotLibrary(unsigned int numbackingpages,
132                 unsigned int numsnapshots, unsigned int nummemoryregions,
133                 unsigned int numheappages, VoidFuncPtr entryPoint) {
134 #if USE_MPROTECT_SNAPSHOT
135         /* Setup a stack for our signal handler....  */
136         stack_t ss;
137         ss.ss_sp = MYMALLOC(SIGSTACKSIZE);
138         ss.ss_size = SIGSTACKSIZE;
139         ss.ss_flags = 0;
140         sigaltstack(&ss, NULL);
141
142         struct sigaction sa;
143         sa.sa_flags = SA_SIGINFO | SA_NODEFER | SA_RESTART | SA_ONSTACK;
144         sigemptyset( &sa.sa_mask );
145         sa.sa_sigaction = HandlePF;
146 #ifdef MAC
147         if( sigaction( SIGBUS, &sa, NULL ) == -1 ){
148                 printf("SIGACTION CANNOT BE INSTALLED\n");
149                 exit(EXIT_FAILURE);
150         }
151 #endif
152         if( sigaction( SIGSEGV, &sa, NULL ) == -1 ){
153                 printf("SIGACTION CANNOT BE INSTALLED\n");
154                 exit(EXIT_FAILURE);
155         }
156
157         initSnapShotRecord(numbackingpages, numsnapshots, nummemoryregions);
158
159         // EVIL HACK: We need to make sure that calls into the HandlePF method don't cause dynamic links
160         // The problem is that we end up protecting state in the dynamic linker...
161         // Solution is to call our signal handler before we start protecting stuff...
162
163         siginfo_t si;
164         memset(&si, 0, sizeof(si));
165         si.si_addr=ss.ss_sp;
166         HandlePF(SIGSEGV, &si, NULL);
167         snapshotrecord->lastBackingPage--; //remove the fake page we copied
168
169         basemySpace=MYMALLOC((numheappages+1)*PAGESIZE);
170         void * pagealignedbase=PageAlignAddressUpward(basemySpace);
171         mySpace = create_mspace_with_base(pagealignedbase,  numheappages*PAGESIZE, 1 );
172         addMemoryRegionToSnapShot(pagealignedbase, numheappages);
173         entryPoint();
174 #else
175
176         basemySpace=system_malloc((numheappages+1)*PAGESIZE);
177         void * pagealignedbase=PageAlignAddressUpward(basemySpace);
178         mySpace = create_mspace_with_base(pagealignedbase,  numheappages*PAGESIZE, 1 );
179         createSharedLibrary();
180
181         //step 2 setup the stack context.
182
183         int alreadySwapped = 0;
184         getcontext( &savedSnapshotContext );
185         if( !alreadySwapped ){
186                 alreadySwapped = 1;
187                 ucontext_t currentContext, swappedContext, newContext;
188                 getcontext( &newContext );
189                 newContext.uc_stack.ss_sp = sTheRecord->mStackBase;
190                 newContext.uc_stack.ss_size = STACK_SIZE_DEFAULT;
191                 newContext.uc_link = &currentContext;
192                 makecontext( &newContext, entryPoint, 0 );
193                 swapcontext( &swappedContext, &newContext );
194         }
195
196         //add the code to take a snapshot here...
197         //to return to user process, do a second swapcontext...
198         pid_t forkedID = 0;
199         snapshotid = sTheRecord->currSnapShotID;
200         bool swapContext = false;
201         while( !sTheRecord->mbFinalize ){
202                 sTheRecord->currSnapShotID=snapshotid+1;
203                 forkedID = fork();
204                 if( 0 == forkedID ){
205                         ucontext_t currentContext;
206 #if 0
207                         int dbg = 0;
208                         while( !dbg );
209 #endif
210                         if( swapContext )
211                                 swapcontext( &currentContext, &( sTheRecord->mContextToRollback ) );
212                         else{
213                                 swapcontext( &currentContext, &savedUserSnapshotContext );
214                         }
215                 } else {
216                         int status;
217                         int retVal;
218
219                         SSDEBUG("The process id of child is %d and the process id of this process is %d and snapshot id is %d",
220                                 forkedID, getpid(), snapshotid );
221
222                         do {
223                                 retVal=waitpid( forkedID, &status, 0 );
224                         } while( -1 == retVal && errno == EINTR );
225
226                         if( sTheRecord->mIDToRollback != snapshotid )
227                                 exit(EXIT_SUCCESS);
228                         else{
229                                 swapContext = true;
230                         }
231                 }
232         }
233
234 #endif
235 }
236
237 /** The addMemoryRegionToSnapShot function assumes that addr is page aligned. 
238  */
239 void addMemoryRegionToSnapShot( void * addr, unsigned int numPages) {
240 #if USE_MPROTECT_SNAPSHOT
241         unsigned int memoryregion=snapshotrecord->lastRegion++;
242         if (memoryregion==snapshotrecord->maxRegions) {
243                 printf("Exceeded supported number of memory regions!\n");
244                 exit(EXIT_FAILURE);
245         }
246
247         snapshotrecord->regionsToSnapShot[ memoryregion ].basePtr=addr;
248         snapshotrecord->regionsToSnapShot[ memoryregion ].sizeInPages=numPages;
249 #endif //NOT REQUIRED IN THE CASE OF FORK BASED SNAPSHOTS.
250 }
251
252 /** The takeSnapshot function takes a snapshot.
253  * @return The snapshot identifier.
254  */
255
256 snapshot_id takeSnapshot( ){
257 #if USE_MPROTECT_SNAPSHOT
258         for(unsigned int region=0; region<snapshotrecord->lastRegion;region++) {
259                 if( mprotect(snapshotrecord->regionsToSnapShot[region].basePtr, snapshotrecord->regionsToSnapShot[region].sizeInPages*sizeof(struct SnapShotPage), PROT_READ ) == -1 ){
260                         perror("mprotect");
261                         printf("Failed to mprotect inside of takeSnapShot\n");
262                         exit(EXIT_FAILURE);
263                 }
264         }
265         unsigned int snapshot=snapshotrecord->lastSnapShot++;
266         if (snapshot==snapshotrecord->maxSnapShots) {
267                 printf("Out of snapshots\n");
268                 exit(EXIT_FAILURE);
269         }
270         snapshotrecord->snapShots[snapshot].firstBackingPage=snapshotrecord->lastBackingPage;
271
272         return snapshot;
273 #else
274         swapcontext( &savedUserSnapshotContext, &savedSnapshotContext );
275         return snapshotid;
276 #endif
277 }
278
279 /** The rollBack function rollback to the given snapshot identifier.
280  *  @param theID is the snapshot identifier to rollback to.
281  */
282
283 void rollBack( snapshot_id theID ){
284 #if USE_MPROTECT_SNAPSHOT
285         std::map< void *, bool, std::less< void * >, MyAlloc< std::pair< const void *, bool > > > duplicateMap;
286         for(unsigned int region=0; region<snapshotrecord->lastRegion;region++) {
287                 if( mprotect(snapshotrecord->regionsToSnapShot[region].basePtr, snapshotrecord->regionsToSnapShot[region].sizeInPages*sizeof(struct SnapShotPage), PROT_READ | PROT_WRITE ) == -1 ){
288                         perror("mprotect");
289                         printf("Failed to mprotect inside of takeSnapShot\n");
290                         exit(EXIT_FAILURE);
291                 }
292         }
293         for(unsigned int page=snapshotrecord->snapShots[theID].firstBackingPage; page<snapshotrecord->lastBackingPage; page++) {
294                 bool oldVal = false;
295                 if( duplicateMap.find( snapshotrecord->backingRecords[page].basePtrOfPage ) != duplicateMap.end() ){
296                         oldVal = true;
297                 }
298                 else{
299                         duplicateMap[ snapshotrecord->backingRecords[page].basePtrOfPage ] = true;
300                 }
301                 if(  !oldVal ){
302                         memcpy(snapshotrecord->backingRecords[page].basePtrOfPage, &snapshotrecord->backingStore[page], sizeof(struct SnapShotPage));
303                 }
304         }
305         snapshotrecord->lastSnapShot=theID;
306         snapshotrecord->lastBackingPage=snapshotrecord->snapShots[theID].firstBackingPage;
307         takeSnapshot(); //Make sure current snapshot is still good...All later ones are cleared
308 #else
309         sTheRecord->mIDToRollback = theID;
310         int sTemp = 0;
311         getcontext( &sTheRecord->mContextToRollback );
312         if( !sTemp ){
313                 sTemp = 1;
314                 SSDEBUG("Invoked rollback");
315                 exit(EXIT_SUCCESS);
316         }
317 #endif
318 }
319
320 /** The finalize method shuts down the snapshotting system.  */
321 //Subramanian -- remove this function from the external interface and
322 //have us call it internally
323
324 void finalize(){
325 #if !USE_MPROTECT_SNAPSHOT
326         sTheRecord->mbFinalize = true;
327 #endif
328 }
329