snapshot: use snapshot_space only in mprotect-based
[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
49 #else /* USE_MPROTECT_SNAPSHOT */
50
51 /** PageAlignedAdressUpdate return a page aligned address for the
52  * address being added as a side effect the numBytes are also changed.
53  */
54 static void * PageAlignAddressUpward(void * addr) {
55         return (void *)((((uintptr_t)addr)+PAGESIZE-1)&~(PAGESIZE-1));
56 }
57
58 /** ReturnPageAlignedAddress returns a page aligned address for the
59  * address being added as a side effect the numBytes are also changed.
60  */
61 static void * ReturnPageAlignedAddress(void * addr) {
62         return (void *)(((uintptr_t)addr)&~(PAGESIZE-1));
63 }
64
65 /** The initSnapShotRecord method initialized the snapshotting data
66  *  structures for the mprotect based snapshot.
67  */
68 static void initSnapShotRecord(unsigned int numbackingpages, unsigned int numsnapshots, unsigned int nummemoryregions) {
69         snapshotrecord=( struct SnapShot * )model_malloc(sizeof(struct SnapShot));
70         snapshotrecord->regionsToSnapShot=( struct MemoryRegion * )model_malloc(sizeof(struct MemoryRegion)*nummemoryregions);
71         snapshotrecord->backingStoreBasePtr= ( struct SnapShotPage * )model_malloc( sizeof( struct SnapShotPage ) * (numbackingpages + 1) );
72         //Page align the backingstorepages
73         snapshotrecord->backingStore=( struct SnapShotPage * )PageAlignAddressUpward(snapshotrecord->backingStoreBasePtr);
74         snapshotrecord->backingRecords=( struct BackingPageRecord * )model_malloc(sizeof(struct BackingPageRecord)*numbackingpages);
75         snapshotrecord->snapShots= ( struct SnapShotRecord * )model_malloc(sizeof(struct SnapShotRecord)*numsnapshots);
76         snapshotrecord->lastSnapShot=0;
77         snapshotrecord->lastBackingPage=0;
78         snapshotrecord->lastRegion=0;
79         snapshotrecord->maxRegions=nummemoryregions;
80         snapshotrecord->maxBackingPages=numbackingpages;
81         snapshotrecord->maxSnapShots=numsnapshots;
82 }
83
84 /** HandlePF is the page fault handler for mprotect based snapshotting
85  * algorithm.
86  */
87 static void HandlePF( int sig, siginfo_t *si, void * unused){
88         if( si->si_code == SEGV_MAPERR ){
89                 printf("Real Fault at %p\n", si->si_addr);
90                 print_trace();
91                 exit( EXIT_FAILURE );
92         }
93         void* addr = ReturnPageAlignedAddress(si->si_addr);
94
95         unsigned int backingpage=snapshotrecord->lastBackingPage++; //Could run out of pages...
96         if (backingpage==snapshotrecord->maxBackingPages) {
97                 printf("Out of backing pages at %p\n", si->si_addr);
98                 exit( EXIT_FAILURE );
99         }
100
101         //copy page
102         memcpy(&(snapshotrecord->backingStore[backingpage]), addr, sizeof(struct SnapShotPage));
103         //remember where to copy page back to
104         snapshotrecord->backingRecords[backingpage].basePtrOfPage=addr;
105         //set protection to read/write
106         if (mprotect( addr, sizeof(struct SnapShotPage), PROT_READ | PROT_WRITE )) {
107                 perror("mprotect");
108                 // Handle error by quitting?
109         }
110 }
111 #endif /* USE_MPROTECT_SNAPSHOT */
112
113 #if !USE_MPROTECT_SNAPSHOT
114 void createSharedMemory(){
115         //step 1. create shared memory.
116         void * memMapBase = mmap( 0, SHARED_MEMORY_DEFAULT + STACK_SIZE_DEFAULT, PROT_READ | PROT_WRITE, MAP_SHARED|MAP_ANON, -1, 0 );
117         if( MAP_FAILED == memMapBase )
118                 FAILURE("mmap");
119
120         //Setup snapshot record at top of free region
121         snapshotrecord = ( struct SnapShot * )memMapBase;
122         snapshotrecord->mSharedMemoryBase = (void *)((uintptr_t)memMapBase + sizeof(struct SnapShot));
123         snapshotrecord->mStackBase = (void *)((uintptr_t)memMapBase + SHARED_MEMORY_DEFAULT);
124         snapshotrecord->mStackSize = STACK_SIZE_DEFAULT;
125         snapshotrecord->mIDToRollback = -1;
126         snapshotrecord->currSnapShotID = 0;
127 }
128 #endif
129
130
131 /** The initSnapshotLibrary function initializes the snapshot library.
132  *  @param entryPoint the function that should run the program.
133  */
134 #if USE_MPROTECT_SNAPSHOT
135
136 void initSnapshotLibrary(unsigned int numbackingpages,
137                 unsigned int numsnapshots, unsigned int nummemoryregions,
138                 unsigned int numheappages, VoidFuncPtr entryPoint) {
139         /* Setup a stack for our signal handler....  */
140         stack_t ss;
141         ss.ss_sp = PageAlignAddressUpward(model_malloc(SIGSTACKSIZE+PAGESIZE-1));
142         ss.ss_size = SIGSTACKSIZE;
143         ss.ss_flags = 0;
144         sigaltstack(&ss, NULL);
145
146         struct sigaction sa;
147         sa.sa_flags = SA_SIGINFO | SA_NODEFER | SA_RESTART | SA_ONSTACK;
148         sigemptyset( &sa.sa_mask );
149         sa.sa_sigaction = HandlePF;
150 #ifdef MAC
151         if( sigaction( SIGBUS, &sa, NULL ) == -1 ){
152                 printf("SIGACTION CANNOT BE INSTALLED\n");
153                 exit(EXIT_FAILURE);
154         }
155 #endif
156         if( sigaction( SIGSEGV, &sa, NULL ) == -1 ){
157                 printf("SIGACTION CANNOT BE INSTALLED\n");
158                 exit(EXIT_FAILURE);
159         }
160
161         initSnapShotRecord(numbackingpages, numsnapshots, nummemoryregions);
162
163         // EVIL HACK: We need to make sure that calls into the HandlePF method don't cause dynamic links
164         // The problem is that we end up protecting state in the dynamic linker...
165         // Solution is to call our signal handler before we start protecting stuff...
166
167         siginfo_t si;
168         memset(&si, 0, sizeof(si));
169         si.si_addr=ss.ss_sp;
170         HandlePF(SIGSEGV, &si, NULL);
171         snapshotrecord->lastBackingPage--; //remove the fake page we copied
172
173         void *basemySpace = model_malloc((numheappages+1)*PAGESIZE);
174         void * pagealignedbase=PageAlignAddressUpward(basemySpace);
175         snapshot_space = create_mspace_with_base(pagealignedbase, numheappages*PAGESIZE, 1 );
176         addMemoryRegionToSnapShot(pagealignedbase, numheappages);
177         entryPoint();
178 }
179 #else
180 void initSnapshotLibrary(unsigned int numbackingpages,
181                 unsigned int numsnapshots, unsigned int nummemoryregions,
182                 unsigned int numheappages, VoidFuncPtr entryPoint) {
183         if (!snapshotrecord)
184                 createSharedMemory();
185
186         //step 2 setup the stack context.
187         ucontext_t newContext;
188         getcontext( &newContext );
189         newContext.uc_stack.ss_sp = snapshotrecord->mStackBase;
190         newContext.uc_stack.ss_size = STACK_SIZE_DEFAULT;
191         makecontext( &newContext, entryPoint, 0 );
192         /* switch to a new entryPoint context, on a new stack */
193         swapcontext(&savedSnapshotContext, &newContext);
194
195         /* switch back here when takesnapshot is called */
196         pid_t forkedID = 0;
197         snapshotid = snapshotrecord->currSnapShotID;
198         /* This bool indicates that the current process's snapshotid is same
199                  as the id to which the rollback needs to occur */
200
201         bool rollback = false;
202         while( true ){
203                 snapshotrecord->currSnapShotID=snapshotid+1;
204                 forkedID = fork();
205
206                 if( 0 == forkedID ){
207                         /* If the rollback bool is set, switch to the context we need to
208                                  return to during a rollback. */
209                         if( rollback) {
210                                 setcontext( &( snapshotrecord->mContextToRollback ) );
211                         } else {
212                                 /*Child process which is forked as a result of takesnapshot
213                                         call should switch back to the takesnapshot context*/
214                                 setcontext( &savedUserSnapshotContext );
215                         }
216                 } else {
217                         int status;
218                         int retVal;
219
220                         SSDEBUG("The process id of child is %d and the process id of this process is %d and snapshot id is %d\n",
221                                 forkedID, getpid(), snapshotid );
222
223                         do {
224                                 retVal=waitpid( forkedID, &status, 0 );
225                         } while( -1 == retVal && errno == EINTR );
226
227                         if( snapshotrecord->mIDToRollback != snapshotid ) {
228                                 exit(EXIT_SUCCESS);
229                         }
230                         rollback = true;
231                 }
232         }
233 }
234 #endif
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 snapshot_id takeSnapshot( ){
255 #if USE_MPROTECT_SNAPSHOT
256         for(unsigned int region=0; region<snapshotrecord->lastRegion;region++) {
257                 if( mprotect(snapshotrecord->regionsToSnapShot[region].basePtr, snapshotrecord->regionsToSnapShot[region].sizeInPages*sizeof(struct SnapShotPage), PROT_READ ) == -1 ){
258                         perror("mprotect");
259                         printf("Failed to mprotect inside of takeSnapShot\n");
260                         exit(EXIT_FAILURE);
261                 }
262         }
263         unsigned int snapshot=snapshotrecord->lastSnapShot++;
264         if (snapshot==snapshotrecord->maxSnapShots) {
265                 printf("Out of snapshots\n");
266                 exit(EXIT_FAILURE);
267         }
268         snapshotrecord->snapShots[snapshot].firstBackingPage=snapshotrecord->lastBackingPage;
269
270         return snapshot;
271 #else
272         swapcontext( &savedUserSnapshotContext, &savedSnapshotContext );
273         SSDEBUG("TAKESNAPSHOT RETURN\n");
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 void rollBack( snapshot_id theID ){
282 #if USE_MPROTECT_SNAPSHOT==2
283         if (snapshotrecord->lastSnapShot==(theID+1)) {
284                 for(unsigned int page=snapshotrecord->snapShots[theID].firstBackingPage; page<snapshotrecord->lastBackingPage; page++) {
285                         memcpy(snapshotrecord->backingRecords[page].basePtrOfPage, &snapshotrecord->backingStore[page], sizeof(struct SnapShotPage));
286                 }
287                 return;
288         }
289 #endif
290
291 #if USE_MPROTECT_SNAPSHOT
292         HashTable< void *, bool, uintptr_t, 4, model_malloc, model_calloc, model_free> 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                 if( !duplicateMap.contains(snapshotrecord->backingRecords[page].basePtrOfPage )) {
302                         duplicateMap.put(snapshotrecord->backingRecords[page].basePtrOfPage, true);
303                         memcpy(snapshotrecord->backingRecords[page].basePtrOfPage, &snapshotrecord->backingStore[page], sizeof(struct SnapShotPage));
304                 }
305         }
306         snapshotrecord->lastSnapShot=theID;
307         snapshotrecord->lastBackingPage=snapshotrecord->snapShots[theID].firstBackingPage;
308         takeSnapshot(); //Make sure current snapshot is still good...All later ones are cleared
309 #else
310         snapshotrecord->mIDToRollback = theID;
311         volatile int sTemp = 0;
312         getcontext( &snapshotrecord->mContextToRollback );
313         /*
314          * This is used to quit the process on rollback, so that the process
315          * which needs to rollback can quit allowing the process whose
316          * snapshotid matches the rollbackid to switch to this context and
317          * continue....
318          */
319         if( !sTemp ){
320                 sTemp = 1;
321                 SSDEBUG("Invoked rollback\n");
322                 exit(EXIT_SUCCESS);
323         }
324         /*
325          * This fix obviates the need for a finalize call. hence less dependences for model-checker....
326          *
327          */
328         snapshotrecord->mIDToRollback = -1;
329 #endif
330 }
331