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