snapshot: remove extra blank lines
[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 static ucontext_t savedSnapshotContext;
37 static ucontext_t savedUserSnapshotContext;
38 static snapshot_id snapshotid = 0;
39 #endif
40
41 /** PageAlignedAdressUpdate return a page aligned address for the
42  * address being added as a side effect the numBytes are also changed.
43  */
44 static void * PageAlignAddressUpward(void * addr) {
45         return (void *)((((uintptr_t)addr)+PAGESIZE-1)&~(PAGESIZE-1));
46 }
47
48 #if USE_MPROTECT_SNAPSHOT
49
50 /** ReturnPageAlignedAddress returns a page aligned address for the
51  * address being added as a side effect the numBytes are also changed.
52  */
53 static void * ReturnPageAlignedAddress(void * addr) {
54         return (void *)(((uintptr_t)addr)&~(PAGESIZE-1));
55 }
56
57 /** The initSnapShotRecord method initialized the snapshotting data
58  *  structures for the mprotect based snapshot. 
59  */
60 static void initSnapShotRecord(unsigned int numbackingpages, unsigned int numsnapshots, unsigned int nummemoryregions) {
61         snapshotrecord=( struct SnapShot * )MYMALLOC(sizeof(struct SnapShot));
62         snapshotrecord->regionsToSnapShot=( struct MemoryRegion * )MYMALLOC(sizeof(struct MemoryRegion)*nummemoryregions);
63         snapshotrecord->backingStoreBasePtr= ( struct SnapShotPage * )MYMALLOC( sizeof( struct SnapShotPage ) * (numbackingpages + 1) );
64         //Page align the backingstorepages
65         snapshotrecord->backingStore=( struct SnapShotPage * )PageAlignAddressUpward(snapshotrecord->backingStoreBasePtr);
66         snapshotrecord->backingRecords=( struct BackingPageRecord * )MYMALLOC(sizeof(struct BackingPageRecord)*numbackingpages);
67         snapshotrecord->snapShots= ( struct SnapShotRecord * )MYMALLOC(sizeof(struct SnapShotRecord)*numsnapshots);
68         snapshotrecord->lastSnapShot=0;
69         snapshotrecord->lastBackingPage=0;
70         snapshotrecord->lastRegion=0;
71         snapshotrecord->maxRegions=nummemoryregions;
72         snapshotrecord->maxBackingPages=numbackingpages;
73         snapshotrecord->maxSnapShots=numsnapshots;
74 }
75 #endif //nothing to initialize for the fork based snapshotting.
76
77 /** HandlePF is the page fault handler for mprotect based snapshotting
78  * algorithm.
79  */
80 static void HandlePF( int sig, siginfo_t *si, void * unused){
81 #if USE_MPROTECT_SNAPSHOT
82         if( si->si_code == SEGV_MAPERR ){
83                 printf("Real Fault at %p\n", si->si_addr);
84                 exit( EXIT_FAILURE );
85         }
86         void* addr = ReturnPageAlignedAddress(si->si_addr);
87
88         unsigned int backingpage=snapshotrecord->lastBackingPage++; //Could run out of pages...
89         if (backingpage==snapshotrecord->maxBackingPages) {
90                 printf("Out of backing pages at %p\n", si->si_addr);
91                 exit( EXIT_FAILURE );
92         }
93
94         //copy page
95         memcpy(&(snapshotrecord->backingStore[backingpage]), addr, sizeof(struct SnapShotPage));
96         //remember where to copy page back to
97         snapshotrecord->backingRecords[backingpage].basePtrOfPage=addr;
98         //set protection to read/write
99         if (mprotect( addr, sizeof(struct SnapShotPage), PROT_READ | PROT_WRITE )) {
100                 perror("mprotect");
101                 // Handle error by quitting?
102         }
103 #endif //nothing to handle for non snapshotting case.
104 }
105
106 void createSharedLibrary(){
107 #if !USE_MPROTECT_SNAPSHOT
108         //step 1. create shared memory.
109         if( sTheRecord ) return;
110         int fd = shm_open( "/ModelChecker-Snapshotter", O_RDWR | O_CREAT, 0777 ); //universal permissions.
111         if( -1 == fd ) FAILURE("shm_open");
112         if( -1 == ftruncate( fd, ( size_t )SHARED_MEMORY_DEFAULT + ( size_t )STACK_SIZE_DEFAULT ) ) FAILURE( "ftruncate" );
113         char * memMapBase = ( char * ) mmap( 0, ( size_t )SHARED_MEMORY_DEFAULT + ( size_t )STACK_SIZE_DEFAULT, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0 );
114         if( MAP_FAILED == memMapBase ) FAILURE("mmap");
115         sTheRecord = ( struct Snapshot * )memMapBase;
116         sTheRecord->mSharedMemoryBase = memMapBase + sizeof( struct Snapshot );
117         sTheRecord->mStackBase = ( char * )memMapBase + ( size_t )SHARED_MEMORY_DEFAULT;
118         sTheRecord->mStackSize = STACK_SIZE_DEFAULT;
119         sTheRecord->mIDToRollback = -1;
120         sTheRecord->currSnapShotID = 0;
121         sTheRecord->mbFinalize = false;
122 #endif
123 }
124
125 /** The initSnapShotLibrary function initializes the Snapshot library.
126  *  @param entryPoint the function that should run the program.
127  */
128 void initSnapShotLibrary(unsigned int numbackingpages,
129                 unsigned int numsnapshots, unsigned int nummemoryregions,
130                 unsigned int numheappages, VoidFuncPtr entryPoint) {
131 #if USE_MPROTECT_SNAPSHOT
132         /* Setup a stack for our signal handler....  */
133         stack_t ss;
134         ss.ss_sp = MYMALLOC(SIGSTACKSIZE);
135         ss.ss_size = SIGSTACKSIZE;
136         ss.ss_flags = 0;
137         sigaltstack(&ss, NULL);
138
139         struct sigaction sa;
140         sa.sa_flags = SA_SIGINFO | SA_NODEFER | SA_RESTART | SA_ONSTACK;
141         sigemptyset( &sa.sa_mask );
142         sa.sa_sigaction = HandlePF;
143 #ifdef MAC
144         if( sigaction( SIGBUS, &sa, NULL ) == -1 ){
145                 printf("SIGACTION CANNOT BE INSTALLED\n");
146                 exit(EXIT_FAILURE);
147         }
148 #endif
149         if( sigaction( SIGSEGV, &sa, NULL ) == -1 ){
150                 printf("SIGACTION CANNOT BE INSTALLED\n");
151                 exit(EXIT_FAILURE);
152         }
153
154         initSnapShotRecord(numbackingpages, numsnapshots, nummemoryregions);
155
156         // EVIL HACK: We need to make sure that calls into the HandlePF method don't cause dynamic links
157         // The problem is that we end up protecting state in the dynamic linker...
158         // Solution is to call our signal handler before we start protecting stuff...
159
160         siginfo_t si;
161         memset(&si, 0, sizeof(si));
162         si.si_addr=ss.ss_sp;
163         HandlePF(SIGSEGV, &si, NULL);
164         snapshotrecord->lastBackingPage--; //remove the fake page we copied
165
166         basemySpace=MYMALLOC((numheappages+1)*PAGESIZE);
167         void * pagealignedbase=PageAlignAddressUpward(basemySpace);
168         mySpace = create_mspace_with_base(pagealignedbase,  numheappages*PAGESIZE, 1 );
169         addMemoryRegionToSnapShot(pagealignedbase, numheappages);
170         entryPoint();
171 #else
172
173         basemySpace=system_malloc((numheappages+1)*PAGESIZE);
174         void * pagealignedbase=PageAlignAddressUpward(basemySpace);
175         mySpace = create_mspace_with_base(pagealignedbase,  numheappages*PAGESIZE, 1 );
176         createSharedLibrary();
177
178         //step 2 setup the stack context.
179
180         int alreadySwapped = 0;
181         getcontext( &savedSnapshotContext );
182         if( !alreadySwapped ){
183                 alreadySwapped = 1;
184                 ucontext_t currentContext, swappedContext, newContext;
185                 getcontext( &newContext );
186                 newContext.uc_stack.ss_sp = sTheRecord->mStackBase;
187                 newContext.uc_stack.ss_size = STACK_SIZE_DEFAULT;
188                 newContext.uc_link = &currentContext;
189                 makecontext( &newContext, entryPoint, 0 );
190                 swapcontext( &swappedContext, &newContext );
191         }
192
193         //add the code to take a snapshot here...
194         //to return to user process, do a second swapcontext...
195         pid_t forkedID = 0;
196         snapshotid = sTheRecord->currSnapShotID;
197         bool swapContext = false;
198         while( !sTheRecord->mbFinalize ){
199                 sTheRecord->currSnapShotID=snapshotid+1;
200                 forkedID = fork();
201                 if( 0 == forkedID ){
202                         ucontext_t currentContext;
203 #if 0
204                         int dbg = 0;
205                         while( !dbg );
206 #endif
207                         if( swapContext )
208                                 swapcontext( &currentContext, &( sTheRecord->mContextToRollback ) );
209                         else{
210                                 swapcontext( &currentContext, &savedUserSnapshotContext );
211                         }
212                 } else {
213                         int status;
214                         int retVal;
215
216                         SSDEBUG("The process id of child is %d and the process id of this process is %d and snapshot id is %d",
217                                 forkedID, getpid(), snapshotid );
218
219                         do {
220                                 retVal=waitpid( forkedID, &status, 0 );
221                         } while( -1 == retVal && errno == EINTR );
222
223                         if( sTheRecord->mIDToRollback != snapshotid )
224                                 exit(EXIT_SUCCESS);
225                         else{
226                                 swapContext = true;
227                         }
228                 }
229         }
230
231 #endif
232 }
233
234 /** The addMemoryRegionToSnapShot function assumes that addr is page aligned. 
235  */
236 void addMemoryRegionToSnapShot( void * addr, unsigned int numPages) {
237 #if USE_MPROTECT_SNAPSHOT
238         unsigned int memoryregion=snapshotrecord->lastRegion++;
239         if (memoryregion==snapshotrecord->maxRegions) {
240                 printf("Exceeded supported number of memory regions!\n");
241                 exit(EXIT_FAILURE);
242         }
243
244         snapshotrecord->regionsToSnapShot[ memoryregion ].basePtr=addr;
245         snapshotrecord->regionsToSnapShot[ memoryregion ].sizeInPages=numPages;
246 #endif //NOT REQUIRED IN THE CASE OF FORK BASED SNAPSHOTS.
247 }
248
249 /** The takeSnapshot function takes a snapshot.
250  * @return The snapshot identifier.
251  */
252 snapshot_id takeSnapshot( ){
253 #if USE_MPROTECT_SNAPSHOT
254         for(unsigned int region=0; region<snapshotrecord->lastRegion;region++) {
255                 if( mprotect(snapshotrecord->regionsToSnapShot[region].basePtr, snapshotrecord->regionsToSnapShot[region].sizeInPages*sizeof(struct SnapShotPage), PROT_READ ) == -1 ){
256                         perror("mprotect");
257                         printf("Failed to mprotect inside of takeSnapShot\n");
258                         exit(EXIT_FAILURE);
259                 }
260         }
261         unsigned int snapshot=snapshotrecord->lastSnapShot++;
262         if (snapshot==snapshotrecord->maxSnapShots) {
263                 printf("Out of snapshots\n");
264                 exit(EXIT_FAILURE);
265         }
266         snapshotrecord->snapShots[snapshot].firstBackingPage=snapshotrecord->lastBackingPage;
267
268         return snapshot;
269 #else
270         swapcontext( &savedUserSnapshotContext, &savedSnapshotContext );
271         return snapshotid;
272 #endif
273 }
274
275 /** The rollBack function rollback to the given snapshot identifier.
276  *  @param theID is the snapshot identifier to rollback to.
277  */
278 void rollBack( snapshot_id theID ){
279 #if USE_MPROTECT_SNAPSHOT
280         std::map< void *, bool, std::less< void * >, MyAlloc< std::pair< const void *, bool > > > duplicateMap;
281         for(unsigned int region=0; region<snapshotrecord->lastRegion;region++) {
282                 if( mprotect(snapshotrecord->regionsToSnapShot[region].basePtr, snapshotrecord->regionsToSnapShot[region].sizeInPages*sizeof(struct SnapShotPage), PROT_READ | PROT_WRITE ) == -1 ){
283                         perror("mprotect");
284                         printf("Failed to mprotect inside of takeSnapShot\n");
285                         exit(EXIT_FAILURE);
286                 }
287         }
288         for(unsigned int page=snapshotrecord->snapShots[theID].firstBackingPage; page<snapshotrecord->lastBackingPage; page++) {
289                 bool oldVal = false;
290                 if( duplicateMap.find( snapshotrecord->backingRecords[page].basePtrOfPage ) != duplicateMap.end() ){
291                         oldVal = true;
292                 }
293                 else{
294                         duplicateMap[ snapshotrecord->backingRecords[page].basePtrOfPage ] = true;
295                 }
296                 if(  !oldVal ){
297                         memcpy(snapshotrecord->backingRecords[page].basePtrOfPage, &snapshotrecord->backingStore[page], sizeof(struct SnapShotPage));
298                 }
299         }
300         snapshotrecord->lastSnapShot=theID;
301         snapshotrecord->lastBackingPage=snapshotrecord->snapShots[theID].firstBackingPage;
302         takeSnapshot(); //Make sure current snapshot is still good...All later ones are cleared
303 #else
304         sTheRecord->mIDToRollback = theID;
305         int sTemp = 0;
306         getcontext( &sTheRecord->mContextToRollback );
307         if( !sTemp ){
308                 sTemp = 1;
309                 SSDEBUG("Invoked rollback");
310                 exit(EXIT_SUCCESS);
311         }
312 #endif
313 }
314
315 /** The finalize method shuts down the snapshotting system.  */
316 //Subramanian -- remove this function from the external interface and
317 //have us call it internally
318 void finalize(){
319 #if !USE_MPROTECT_SNAPSHOT
320         sTheRecord->mbFinalize = true;
321 #endif
322 }