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