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