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