test: add AB/BA deadlock test
[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 /** PageAlignedAdressUpdate return a page aligned address for the
34  * address being added as a side effect the numBytes are also changed.
35  */
36 static void * PageAlignAddressUpward(void * addr) {
37         return (void *)((((uintptr_t)addr)+PAGESIZE-1)&~(PAGESIZE-1));
38 }
39
40 #if !USE_MPROTECT_SNAPSHOT
41 /** @statics
42 *   These variables are necessary because the stack is shared region and
43 *   there exists a race between all processes executing the same function.
44 *   To avoid the problem above, we require variables allocated in 'safe' regions.
45 *   The bug was actually observed with the forkID, these variables below are
46 *   used to indicate the various contexts to which to switch to.
47 *
48 *   @savedSnapshotContext: contains the point to which takesnapshot() call should switch to.
49 *   @savedUserSnapshotContext: contains the point to which the process whose snapshotid is equal to the rollbackid should switch to
50 *   @snapshotid: it is a running counter for the various forked processes snapshotid. it is incremented and set in a persistently shared record
51 */
52 static ucontext_t savedSnapshotContext;
53 static ucontext_t savedUserSnapshotContext;
54 static snapshot_id snapshotid = 0;
55
56 #else /* USE_MPROTECT_SNAPSHOT */
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                 printf("For debugging, place breakpoint at: %s:%d\n",
92                                 __FILE__, __LINE__);
93                 exit( EXIT_FAILURE );
94         }
95         void* addr = ReturnPageAlignedAddress(si->si_addr);
96
97         unsigned int backingpage=snapshotrecord->lastBackingPage++; //Could run out of pages...
98         if (backingpage==snapshotrecord->maxBackingPages) {
99                 printf("Out of backing pages at %p\n", si->si_addr);
100                 exit( EXIT_FAILURE );
101         }
102
103         //copy page
104         memcpy(&(snapshotrecord->backingStore[backingpage]), addr, sizeof(struct SnapShotPage));
105         //remember where to copy page back to
106         snapshotrecord->backingRecords[backingpage].basePtrOfPage=addr;
107         //set protection to read/write
108         if (mprotect( addr, sizeof(struct SnapShotPage), PROT_READ | PROT_WRITE )) {
109                 perror("mprotect");
110                 // Handle error by quitting?
111         }
112 }
113 #endif /* USE_MPROTECT_SNAPSHOT */
114
115 #if !USE_MPROTECT_SNAPSHOT
116 void createSharedMemory(){
117         //step 1. create shared memory.
118         void * memMapBase = mmap( 0, SHARED_MEMORY_DEFAULT + STACK_SIZE_DEFAULT, PROT_READ | PROT_WRITE, MAP_SHARED|MAP_ANON, -1, 0 );
119         if( MAP_FAILED == memMapBase )
120                 FAILURE("mmap");
121
122         //Setup snapshot record at top of free region
123         snapshotrecord = ( struct SnapShot * )memMapBase;
124         snapshotrecord->mSharedMemoryBase = (void *)((uintptr_t)memMapBase + sizeof(struct SnapShot));
125         snapshotrecord->mStackBase = (void *)((uintptr_t)memMapBase + SHARED_MEMORY_DEFAULT);
126         snapshotrecord->mStackSize = STACK_SIZE_DEFAULT;
127         snapshotrecord->mIDToRollback = -1;
128         snapshotrecord->currSnapShotID = 0;
129 }
130 #endif
131
132
133 /** The initSnapshotLibrary function initializes the snapshot library.
134  *  @param entryPoint the function that should run the program.
135  */
136 #if USE_MPROTECT_SNAPSHOT
137
138 void initSnapshotLibrary(unsigned int numbackingpages,
139                 unsigned int numsnapshots, unsigned int nummemoryregions,
140                 unsigned int numheappages, VoidFuncPtr entryPoint) {
141         /* Setup a stack for our signal handler....  */
142         stack_t ss;
143         ss.ss_sp = PageAlignAddressUpward(model_malloc(SIGSTACKSIZE+PAGESIZE-1));
144         ss.ss_size = SIGSTACKSIZE;
145         ss.ss_flags = 0;
146         sigaltstack(&ss, NULL);
147
148         struct sigaction sa;
149         sa.sa_flags = SA_SIGINFO | SA_NODEFER | SA_RESTART | SA_ONSTACK;
150         sigemptyset( &sa.sa_mask );
151         sa.sa_sigaction = HandlePF;
152 #ifdef MAC
153         if( sigaction( SIGBUS, &sa, NULL ) == -1 ){
154                 printf("SIGACTION CANNOT BE INSTALLED\n");
155                 exit(EXIT_FAILURE);
156         }
157 #endif
158         if( sigaction( SIGSEGV, &sa, NULL ) == -1 ){
159                 printf("SIGACTION CANNOT BE INSTALLED\n");
160                 exit(EXIT_FAILURE);
161         }
162
163         initSnapShotRecord(numbackingpages, numsnapshots, nummemoryregions);
164
165         // EVIL HACK: We need to make sure that calls into the HandlePF method don't cause dynamic links
166         // The problem is that we end up protecting state in the dynamic linker...
167         // Solution is to call our signal handler before we start protecting stuff...
168
169         siginfo_t si;
170         memset(&si, 0, sizeof(si));
171         si.si_addr=ss.ss_sp;
172         HandlePF(SIGSEGV, &si, NULL);
173         snapshotrecord->lastBackingPage--; //remove the fake page we copied
174
175         void *basemySpace = model_malloc((numheappages+1)*PAGESIZE);
176         void * pagealignedbase=PageAlignAddressUpward(basemySpace);
177         user_snapshot_space = create_mspace_with_base(pagealignedbase, numheappages * PAGESIZE, 1);
178         addMemoryRegionToSnapShot(pagealignedbase, numheappages);
179
180         void *base_model_snapshot_space = model_malloc((numheappages + 1) * PAGESIZE);
181         pagealignedbase = PageAlignAddressUpward(base_model_snapshot_space);
182         model_snapshot_space = create_mspace_with_base(pagealignedbase, numheappages * PAGESIZE, 1);
183         addMemoryRegionToSnapShot(pagealignedbase, numheappages);
184
185         entryPoint();
186 }
187 #else
188 void initSnapshotLibrary(unsigned int numbackingpages,
189                 unsigned int numsnapshots, unsigned int nummemoryregions,
190                 unsigned int numheappages, VoidFuncPtr entryPoint) {
191         if (!snapshotrecord)
192                 createSharedMemory();
193
194         void *base_model_snapshot_space = malloc((numheappages + 1) * PAGESIZE);
195         void *pagealignedbase = PageAlignAddressUpward(base_model_snapshot_space);
196         model_snapshot_space = create_mspace_with_base(pagealignedbase, numheappages * PAGESIZE, 1);
197
198         //step 2 setup the stack context.
199         ucontext_t newContext;
200         getcontext( &newContext );
201         newContext.uc_stack.ss_sp = snapshotrecord->mStackBase;
202         newContext.uc_stack.ss_size = STACK_SIZE_DEFAULT;
203         makecontext( &newContext, entryPoint, 0 );
204         /* switch to a new entryPoint context, on a new stack */
205         swapcontext(&savedSnapshotContext, &newContext);
206
207         /* switch back here when takesnapshot is called */
208         pid_t forkedID = 0;
209         snapshotid = snapshotrecord->currSnapShotID;
210         /* This bool indicates that the current process's snapshotid is same
211                  as the id to which the rollback needs to occur */
212
213         bool rollback = false;
214         while( true ){
215                 snapshotrecord->currSnapShotID=snapshotid+1;
216                 forkedID = fork();
217
218                 if( 0 == forkedID ){
219                         /* If the rollback bool is set, switch to the context we need to
220                                  return to during a rollback. */
221                         if( rollback) {
222                                 setcontext( &( snapshotrecord->mContextToRollback ) );
223                         } else {
224                                 /*Child process which is forked as a result of takesnapshot
225                                         call should switch back to the takesnapshot context*/
226                                 setcontext( &savedUserSnapshotContext );
227                         }
228                 } else {
229                         int status;
230                         int retVal;
231
232                         SSDEBUG("The process id of child is %d and the process id of this process is %d and snapshot id is %d\n",
233                                 forkedID, getpid(), snapshotid );
234
235                         do {
236                                 retVal=waitpid( forkedID, &status, 0 );
237                         } while( -1 == retVal && errno == EINTR );
238
239                         if( snapshotrecord->mIDToRollback != snapshotid ) {
240                                 exit(EXIT_SUCCESS);
241                         }
242                         rollback = true;
243                 }
244         }
245 }
246 #endif
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 snapshot_id takeSnapshot( ){
267 #if USE_MPROTECT_SNAPSHOT
268         for(unsigned int region=0; region<snapshotrecord->lastRegion;region++) {
269                 if( mprotect(snapshotrecord->regionsToSnapShot[region].basePtr, snapshotrecord->regionsToSnapShot[region].sizeInPages*sizeof(struct SnapShotPage), PROT_READ ) == -1 ){
270                         perror("mprotect");
271                         printf("Failed to mprotect inside of takeSnapShot\n");
272                         exit(EXIT_FAILURE);
273                 }
274         }
275         unsigned int snapshot=snapshotrecord->lastSnapShot++;
276         if (snapshot==snapshotrecord->maxSnapShots) {
277                 printf("Out of snapshots\n");
278                 exit(EXIT_FAILURE);
279         }
280         snapshotrecord->snapShots[snapshot].firstBackingPage=snapshotrecord->lastBackingPage;
281
282         return snapshot;
283 #else
284         swapcontext( &savedUserSnapshotContext, &savedSnapshotContext );
285         SSDEBUG("TAKESNAPSHOT RETURN\n");
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 void rollBack( snapshot_id theID ){
294 #if USE_MPROTECT_SNAPSHOT==2
295         if (snapshotrecord->lastSnapShot==(theID+1)) {
296                 for(unsigned int page=snapshotrecord->snapShots[theID].firstBackingPage; page<snapshotrecord->lastBackingPage; page++) {
297                         memcpy(snapshotrecord->backingRecords[page].basePtrOfPage, &snapshotrecord->backingStore[page], sizeof(struct SnapShotPage));
298                 }
299                 return;
300         }
301 #endif
302
303 #if USE_MPROTECT_SNAPSHOT
304         HashTable< void *, bool, uintptr_t, 4, model_malloc, model_calloc, model_free> duplicateMap;
305         for(unsigned int region=0; region<snapshotrecord->lastRegion;region++) {
306                 if( mprotect(snapshotrecord->regionsToSnapShot[region].basePtr, snapshotrecord->regionsToSnapShot[region].sizeInPages*sizeof(struct SnapShotPage), PROT_READ | PROT_WRITE ) == -1 ){
307                         perror("mprotect");
308                         printf("Failed to mprotect inside of takeSnapShot\n");
309                         exit(EXIT_FAILURE);
310                 }
311         }
312         for(unsigned int page=snapshotrecord->snapShots[theID].firstBackingPage; page<snapshotrecord->lastBackingPage; page++) {
313                 if( !duplicateMap.contains(snapshotrecord->backingRecords[page].basePtrOfPage )) {
314                         duplicateMap.put(snapshotrecord->backingRecords[page].basePtrOfPage, true);
315                         memcpy(snapshotrecord->backingRecords[page].basePtrOfPage, &snapshotrecord->backingStore[page], sizeof(struct SnapShotPage));
316                 }
317         }
318         snapshotrecord->lastSnapShot=theID;
319         snapshotrecord->lastBackingPage=snapshotrecord->snapShots[theID].firstBackingPage;
320         takeSnapshot(); //Make sure current snapshot is still good...All later ones are cleared
321 #else
322         snapshotrecord->mIDToRollback = theID;
323         volatile int sTemp = 0;
324         getcontext( &snapshotrecord->mContextToRollback );
325         /*
326          * This is used to quit the process on rollback, so that the process
327          * which needs to rollback can quit allowing the process whose
328          * snapshotid matches the rollbackid to switch to this context and
329          * continue....
330          */
331         if( !sTemp ){
332                 sTemp = 1;
333                 SSDEBUG("Invoked rollback\n");
334                 exit(EXIT_SUCCESS);
335         }
336         /*
337          * This fix obviates the need for a finalize call. hence less dependences for model-checker....
338          *
339          */
340         snapshotrecord->mIDToRollback = -1;
341 #endif
342 }
343