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