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