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