b6e20fd7691a037bab3e5d83b30b860dc6ab713c
[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 <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 * sTheRecord = NULL;
33 #endif
34
35 #if !USE_MPROTECT_SNAPSHOT
36 /** @statics
37 *   These variables are necessary because the stack is shared region and
38 *   there exists a race between all processes executing the same function.
39 *   To avoid the problem above, we require variables allocated in 'safe' regions.
40 *   The bug was actually observed with the forkID, these variables below are
41 *   used to indicate the various contexts to which to switch to.
42 *
43 *   @savedSnapshotContext: contains the point to which takesnapshot() call should switch to.
44 *   @savedUserSnapshotContext: contains the point to which the process whose snapshotid is equal to the rollbackid should switch to
45 *   @snapshotid: it is a running counter for the various forked processes snapshotid. it is incremented and set in a persistently shared record
46 */
47 static ucontext_t savedSnapshotContext;
48 static ucontext_t savedUserSnapshotContext;
49 static snapshot_id snapshotid = 0;
50 #endif
51
52 /** PageAlignedAdressUpdate return a page aligned address for the
53  * address being added as a side effect the numBytes are also changed.
54  */
55 static void * PageAlignAddressUpward(void * addr) {
56         return (void *)((((uintptr_t)addr)+PAGESIZE-1)&~(PAGESIZE-1));
57 }
58
59 #if USE_MPROTECT_SNAPSHOT
60
61 /** ReturnPageAlignedAddress returns a page aligned address for the
62  * address being added as a side effect the numBytes are also changed.
63  */
64 static void * ReturnPageAlignedAddress(void * addr) {
65         return (void *)(((uintptr_t)addr)&~(PAGESIZE-1));
66 }
67
68 /** The initSnapShotRecord method initialized the snapshotting data
69  *  structures for the mprotect based snapshot.
70  */
71 static void initSnapShotRecord(unsigned int numbackingpages, unsigned int numsnapshots, unsigned int nummemoryregions) {
72         snapshotrecord=( struct SnapShot * )MYMALLOC(sizeof(struct SnapShot));
73         snapshotrecord->regionsToSnapShot=( struct MemoryRegion * )MYMALLOC(sizeof(struct MemoryRegion)*nummemoryregions);
74         snapshotrecord->backingStoreBasePtr= ( struct SnapShotPage * )MYMALLOC( sizeof( struct SnapShotPage ) * (numbackingpages + 1) );
75         //Page align the backingstorepages
76         snapshotrecord->backingStore=( struct SnapShotPage * )PageAlignAddressUpward(snapshotrecord->backingStoreBasePtr);
77         snapshotrecord->backingRecords=( struct BackingPageRecord * )MYMALLOC(sizeof(struct BackingPageRecord)*numbackingpages);
78         snapshotrecord->snapShots= ( struct SnapShotRecord * )MYMALLOC(sizeof(struct SnapShotRecord)*numsnapshots);
79         snapshotrecord->lastSnapShot=0;
80         snapshotrecord->lastBackingPage=0;
81         snapshotrecord->lastRegion=0;
82         snapshotrecord->maxRegions=nummemoryregions;
83         snapshotrecord->maxBackingPages=numbackingpages;
84         snapshotrecord->maxSnapShots=numsnapshots;
85 }
86
87 /** HandlePF is the page fault handler for mprotect based snapshotting
88  * algorithm.
89  */
90 static void HandlePF( int sig, siginfo_t *si, void * unused){
91         if( si->si_code == SEGV_MAPERR ){
92                 printf("Real Fault at %p\n", si->si_addr);
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 //nothing to handle for non snapshotting case.
114
115 void createSharedLibrary(){
116 #if !USE_MPROTECT_SNAPSHOT
117         //step 1. create shared memory.
118         if ( sTheRecord )
119                 return;
120         int fd = shm_open( "/ModelChecker-Snapshotter", O_RDWR | O_CREAT, 0777 ); //universal permissions.
121         if ( -1 == fd )
122                 FAILURE("shm_open");
123         if ( -1 == ftruncate( fd, SHARED_MEMORY_DEFAULT + STACK_SIZE_DEFAULT ) )
124                 FAILURE( "ftruncate" );
125         void * memMapBase = mmap( 0, SHARED_MEMORY_DEFAULT + STACK_SIZE_DEFAULT, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0 );
126         if( MAP_FAILED == memMapBase )
127                 FAILURE("mmap");
128         sTheRecord = ( struct Snapshot * )memMapBase;
129         sTheRecord->mSharedMemoryBase = (void *)((uintptr_t)memMapBase + sizeof(struct Snapshot));
130         sTheRecord->mStackBase = (void *)((uintptr_t)memMapBase + SHARED_MEMORY_DEFAULT);
131         sTheRecord->mStackSize = STACK_SIZE_DEFAULT;
132         sTheRecord->mIDToRollback = -1;
133         sTheRecord->currSnapShotID = 0;
134 #endif
135 }
136
137 /** The initSnapShotLibrary function initializes the Snapshot library.
138  *  @param entryPoint the function that should run the program.
139  */
140 void initSnapShotLibrary(unsigned int numbackingpages,
141                 unsigned int numsnapshots, unsigned int nummemoryregions,
142                 unsigned int numheappages, VoidFuncPtr entryPoint) {
143 #if USE_MPROTECT_SNAPSHOT
144         /* Setup a stack for our signal handler....  */
145         stack_t ss;
146         ss.ss_sp = MYMALLOC(SIGSTACKSIZE);
147         ss.ss_size = SIGSTACKSIZE;
148         ss.ss_flags = 0;
149         sigaltstack(&ss, NULL);
150
151         struct sigaction sa;
152         sa.sa_flags = SA_SIGINFO | SA_NODEFER | SA_RESTART | SA_ONSTACK;
153         sigemptyset( &sa.sa_mask );
154         sa.sa_sigaction = HandlePF;
155 #ifdef MAC
156         if( sigaction( SIGBUS, &sa, NULL ) == -1 ){
157                 printf("SIGACTION CANNOT BE INSTALLED\n");
158                 exit(EXIT_FAILURE);
159         }
160 #endif
161         if( sigaction( SIGSEGV, &sa, NULL ) == -1 ){
162                 printf("SIGACTION CANNOT BE INSTALLED\n");
163                 exit(EXIT_FAILURE);
164         }
165
166         initSnapShotRecord(numbackingpages, numsnapshots, nummemoryregions);
167
168         // EVIL HACK: We need to make sure that calls into the HandlePF method don't cause dynamic links
169         // The problem is that we end up protecting state in the dynamic linker...
170         // Solution is to call our signal handler before we start protecting stuff...
171
172         siginfo_t si;
173         memset(&si, 0, sizeof(si));
174         si.si_addr=ss.ss_sp;
175         HandlePF(SIGSEGV, &si, NULL);
176         snapshotrecord->lastBackingPage--; //remove the fake page we copied
177
178         basemySpace=MYMALLOC((numheappages+1)*PAGESIZE);
179         void * pagealignedbase=PageAlignAddressUpward(basemySpace);
180         mySpace = create_mspace_with_base(pagealignedbase,  numheappages*PAGESIZE, 1 );
181         addMemoryRegionToSnapShot(pagealignedbase, numheappages);
182         entryPoint();
183 #else
184
185         basemySpace=system_malloc((numheappages+1)*PAGESIZE);
186         void * pagealignedbase=PageAlignAddressUpward(basemySpace);
187         mySpace = create_mspace_with_base(pagealignedbase,  numheappages*PAGESIZE, 1 );
188         createSharedLibrary();
189
190         //step 2 setup the stack context.
191         ucontext_t newContext;
192         getcontext( &newContext );
193         newContext.uc_stack.ss_sp = sTheRecord->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 = sTheRecord->currSnapShotID;
202         bool swapContext = false;
203         while( true ){
204                 sTheRecord->currSnapShotID=snapshotid+1;
205                 forkedID = fork();
206                 if( 0 == forkedID ){
207                         ucontext_t currentContext;
208                         /*If the rollback bool is set{ see below }, switch to the context we need to return to during a rollback*/
209                         if( swapContext )
210                                 swapcontext( &currentContext, &( sTheRecord->mContextToRollback ) );
211                         else{
212                                 /*Child process which is forked as a result of takesnapshot call should switch back to the takesnapshot context*/
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                                 /*This bool indicates that the current process's snapshotid is same as the id to which the rollback needs to occur*/
230                                 swapContext = true;
231                         }
232                 }
233         }
234
235 #endif
236 }
237
238 /** The addMemoryRegionToSnapShot function assumes that addr is page aligned.
239  */
240 void addMemoryRegionToSnapShot( void * addr, unsigned int numPages) {
241 #if USE_MPROTECT_SNAPSHOT
242         unsigned int memoryregion=snapshotrecord->lastRegion++;
243         if (memoryregion==snapshotrecord->maxRegions) {
244                 printf("Exceeded supported number of memory regions!\n");
245                 exit(EXIT_FAILURE);
246         }
247
248         snapshotrecord->regionsToSnapShot[ memoryregion ].basePtr=addr;
249         snapshotrecord->regionsToSnapShot[ memoryregion ].sizeInPages=numPages;
250 #endif //NOT REQUIRED IN THE CASE OF FORK BASED SNAPSHOTS.
251 }
252
253 /** The takeSnapshot function takes a snapshot.
254  * @return The snapshot identifier.
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 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         /*
312         * This is used to quit the process on rollback, so that
313         * the process which needs to rollback can quit allowing the process whose snapshotid matches the rollbackid to switch to
314         * this context and continue....
315         */
316         if( !sTemp ){
317                 sTemp = 1;
318                 SSDEBUG("Invoked rollback");
319                 exit(EXIT_SUCCESS);
320         }
321     /*
322         * This fix obviates the need for a finalize call. hence less dependences for model-checker....
323     *
324     */
325         sTheRecord->mIDToRollback = -1;
326 #endif
327 }
328