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