10 #include "snapshotimp.h"
15 #include <semaphore.h>
20 #define FAILURE(mesg) { printf("failed in the API: %s with errno relative message: %s\n", mesg, strerror( errno ) ); exit(EXIT_FAILURE); }
23 #define SSDEBUG printf
25 #define SSDEBUG(...) do { } while (0)
28 /* extern declaration definition */
29 #if USE_MPROTECT_SNAPSHOT
30 struct SnapShot * snapshotrecord = NULL;
32 struct Snapshot * sTheRecord = NULL;
35 #if !USE_MPROTECT_SNAPSHOT
37 * These variables are necessary because the stack is shared region and
38 * there exists a race between all processes executing the same function.
39 * To avoid the problem above, we require variables allocated in 'safe' regions.
40 * The bug was actually observed with the forkID, these variables below are
41 * used to indicate the various contexts to which to switch to.
43 * @savedSnapshotContext: contains the point to which takesnapshot() call should switch to.
44 * @savedUserSnapshotContext: contains the point to which the process whose snapshotid is equal to the rollbackid should switch to
45 * @snapshotid: it is a running counter for the various forked processes snapshotid. it is incremented and set in a persistently shared record
47 static ucontext_t savedSnapshotContext;
48 static ucontext_t savedUserSnapshotContext;
49 static snapshot_id snapshotid = 0;
52 /** PageAlignedAdressUpdate return a page aligned address for the
53 * address being added as a side effect the numBytes are also changed.
55 static void * PageAlignAddressUpward(void * addr) {
56 return (void *)((((uintptr_t)addr)+PAGESIZE-1)&~(PAGESIZE-1));
59 #if USE_MPROTECT_SNAPSHOT
61 /** ReturnPageAlignedAddress returns a page aligned address for the
62 * address being added as a side effect the numBytes are also changed.
64 static void * ReturnPageAlignedAddress(void * addr) {
65 return (void *)(((uintptr_t)addr)&~(PAGESIZE-1));
68 /** The initSnapShotRecord method initialized the snapshotting data
69 * structures for the mprotect based snapshot.
71 static void initSnapShotRecord(unsigned int numbackingpages, unsigned int numsnapshots, unsigned int nummemoryregions) {
72 snapshotrecord=( struct SnapShot * )MYMALLOC(sizeof(struct SnapShot));
73 snapshotrecord->regionsToSnapShot=( struct MemoryRegion * )MYMALLOC(sizeof(struct MemoryRegion)*nummemoryregions);
74 snapshotrecord->backingStoreBasePtr= ( struct SnapShotPage * )MYMALLOC( sizeof( struct SnapShotPage ) * (numbackingpages + 1) );
75 //Page align the backingstorepages
76 snapshotrecord->backingStore=( struct SnapShotPage * )PageAlignAddressUpward(snapshotrecord->backingStoreBasePtr);
77 snapshotrecord->backingRecords=( struct BackingPageRecord * )MYMALLOC(sizeof(struct BackingPageRecord)*numbackingpages);
78 snapshotrecord->snapShots= ( struct SnapShotRecord * )MYMALLOC(sizeof(struct SnapShotRecord)*numsnapshots);
79 snapshotrecord->lastSnapShot=0;
80 snapshotrecord->lastBackingPage=0;
81 snapshotrecord->lastRegion=0;
82 snapshotrecord->maxRegions=nummemoryregions;
83 snapshotrecord->maxBackingPages=numbackingpages;
84 snapshotrecord->maxSnapShots=numsnapshots;
87 /** HandlePF is the page fault handler for mprotect based snapshotting
90 static void HandlePF( int sig, siginfo_t *si, void * unused){
91 if( si->si_code == SEGV_MAPERR ){
92 printf("Real Fault at %p\n", si->si_addr);
95 void* addr = ReturnPageAlignedAddress(si->si_addr);
97 unsigned int backingpage=snapshotrecord->lastBackingPage++; //Could run out of pages...
98 if (backingpage==snapshotrecord->maxBackingPages) {
99 printf("Out of backing pages at %p\n", si->si_addr);
100 exit( EXIT_FAILURE );
104 memcpy(&(snapshotrecord->backingStore[backingpage]), addr, sizeof(struct SnapShotPage));
105 //remember where to copy page back to
106 snapshotrecord->backingRecords[backingpage].basePtrOfPage=addr;
107 //set protection to read/write
108 if (mprotect( addr, sizeof(struct SnapShotPage), PROT_READ | PROT_WRITE )) {
110 // Handle error by quitting?
113 #endif //nothing to handle for non snapshotting case.
115 void createSharedLibrary(){
116 #if !USE_MPROTECT_SNAPSHOT
117 //step 1. create shared memory.
120 int fd = shm_open( "/ModelChecker-Snapshotter", O_RDWR | O_CREAT, 0777 ); //universal permissions.
123 if ( -1 == ftruncate( fd, SHARED_MEMORY_DEFAULT + STACK_SIZE_DEFAULT ) )
124 FAILURE( "ftruncate" );
125 void * memMapBase = mmap( 0, SHARED_MEMORY_DEFAULT + STACK_SIZE_DEFAULT, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0 );
126 if( MAP_FAILED == memMapBase )
128 sTheRecord = ( struct Snapshot * )memMapBase;
129 sTheRecord->mSharedMemoryBase = (void *)((uintptr_t)memMapBase + sizeof(struct Snapshot));
130 sTheRecord->mStackBase = (void *)((uintptr_t)memMapBase + SHARED_MEMORY_DEFAULT);
131 sTheRecord->mStackSize = STACK_SIZE_DEFAULT;
132 sTheRecord->mIDToRollback = -1;
133 sTheRecord->currSnapShotID = 0;
137 /** The initSnapShotLibrary function initializes the Snapshot library.
138 * @param entryPoint the function that should run the program.
140 void initSnapShotLibrary(unsigned int numbackingpages,
141 unsigned int numsnapshots, unsigned int nummemoryregions,
142 unsigned int numheappages, VoidFuncPtr entryPoint) {
143 #if USE_MPROTECT_SNAPSHOT
144 /* Setup a stack for our signal handler.... */
146 ss.ss_sp = MYMALLOC(SIGSTACKSIZE);
147 ss.ss_size = SIGSTACKSIZE;
149 sigaltstack(&ss, NULL);
152 sa.sa_flags = SA_SIGINFO | SA_NODEFER | SA_RESTART | SA_ONSTACK;
153 sigemptyset( &sa.sa_mask );
154 sa.sa_sigaction = HandlePF;
156 if( sigaction( SIGBUS, &sa, NULL ) == -1 ){
157 printf("SIGACTION CANNOT BE INSTALLED\n");
161 if( sigaction( SIGSEGV, &sa, NULL ) == -1 ){
162 printf("SIGACTION CANNOT BE INSTALLED\n");
166 initSnapShotRecord(numbackingpages, numsnapshots, nummemoryregions);
168 // EVIL HACK: We need to make sure that calls into the HandlePF method don't cause dynamic links
169 // The problem is that we end up protecting state in the dynamic linker...
170 // Solution is to call our signal handler before we start protecting stuff...
173 memset(&si, 0, sizeof(si));
175 HandlePF(SIGSEGV, &si, NULL);
176 snapshotrecord->lastBackingPage--; //remove the fake page we copied
178 basemySpace=MYMALLOC((numheappages+1)*PAGESIZE);
179 void * pagealignedbase=PageAlignAddressUpward(basemySpace);
180 mySpace = create_mspace_with_base(pagealignedbase, numheappages*PAGESIZE, 1 );
181 addMemoryRegionToSnapShot(pagealignedbase, numheappages);
185 basemySpace=system_malloc((numheappages+1)*PAGESIZE);
186 void * pagealignedbase=PageAlignAddressUpward(basemySpace);
187 mySpace = create_mspace_with_base(pagealignedbase, numheappages*PAGESIZE, 1 );
188 createSharedLibrary();
190 //step 2 setup the stack context.
191 ucontext_t newContext;
192 getcontext( &newContext );
193 newContext.uc_stack.ss_sp = sTheRecord->mStackBase;
194 newContext.uc_stack.ss_size = STACK_SIZE_DEFAULT;
195 makecontext( &newContext, entryPoint, 0 );
196 /* switch to a new entryPoint context, on a new stack */
197 swapcontext(&savedSnapshotContext, &newContext);
199 /* switch back here when takesnapshot is called */
201 snapshotid = sTheRecord->currSnapShotID;
202 bool swapContext = false;
204 sTheRecord->currSnapShotID=snapshotid+1;
207 ucontext_t currentContext;
208 /*If the rollback bool is set{ see below }, switch to the context we need to return to during a rollback*/
210 swapcontext( ¤tContext, &( sTheRecord->mContextToRollback ) );
212 /*Child process which is forked as a result of takesnapshot call should switch back to the takesnapshot context*/
213 swapcontext( ¤tContext, &savedUserSnapshotContext );
219 SSDEBUG("The process id of child is %d and the process id of this process is %d and snapshot id is %d",
220 forkedID, getpid(), snapshotid );
223 retVal=waitpid( forkedID, &status, 0 );
224 } while( -1 == retVal && errno == EINTR );
226 if( sTheRecord->mIDToRollback != snapshotid )
229 /*This bool indicates that the current process's snapshotid is same as the id to which the rollback needs to occur*/
238 /** The addMemoryRegionToSnapShot function assumes that addr is page aligned.
240 void addMemoryRegionToSnapShot( void * addr, unsigned int numPages) {
241 #if USE_MPROTECT_SNAPSHOT
242 unsigned int memoryregion=snapshotrecord->lastRegion++;
243 if (memoryregion==snapshotrecord->maxRegions) {
244 printf("Exceeded supported number of memory regions!\n");
248 snapshotrecord->regionsToSnapShot[ memoryregion ].basePtr=addr;
249 snapshotrecord->regionsToSnapShot[ memoryregion ].sizeInPages=numPages;
250 #endif //NOT REQUIRED IN THE CASE OF FORK BASED SNAPSHOTS.
253 /** The takeSnapshot function takes a snapshot.
254 * @return The snapshot identifier.
256 snapshot_id takeSnapshot( ){
257 #if USE_MPROTECT_SNAPSHOT
258 for(unsigned int region=0; region<snapshotrecord->lastRegion;region++) {
259 if( mprotect(snapshotrecord->regionsToSnapShot[region].basePtr, snapshotrecord->regionsToSnapShot[region].sizeInPages*sizeof(struct SnapShotPage), PROT_READ ) == -1 ){
261 printf("Failed to mprotect inside of takeSnapShot\n");
265 unsigned int snapshot=snapshotrecord->lastSnapShot++;
266 if (snapshot==snapshotrecord->maxSnapShots) {
267 printf("Out of snapshots\n");
270 snapshotrecord->snapShots[snapshot].firstBackingPage=snapshotrecord->lastBackingPage;
274 swapcontext( &savedUserSnapshotContext, &savedSnapshotContext );
279 /** The rollBack function rollback to the given snapshot identifier.
280 * @param theID is the snapshot identifier to rollback to.
282 void rollBack( snapshot_id theID ){
283 #if USE_MPROTECT_SNAPSHOT
284 std::map< void *, bool, std::less< void * >, MyAlloc< std::pair< const void *, bool > > > duplicateMap;
285 for(unsigned int region=0; region<snapshotrecord->lastRegion;region++) {
286 if( mprotect(snapshotrecord->regionsToSnapShot[region].basePtr, snapshotrecord->regionsToSnapShot[region].sizeInPages*sizeof(struct SnapShotPage), PROT_READ | PROT_WRITE ) == -1 ){
288 printf("Failed to mprotect inside of takeSnapShot\n");
292 for(unsigned int page=snapshotrecord->snapShots[theID].firstBackingPage; page<snapshotrecord->lastBackingPage; page++) {
294 if( duplicateMap.find( snapshotrecord->backingRecords[page].basePtrOfPage ) != duplicateMap.end() ){
298 duplicateMap[ snapshotrecord->backingRecords[page].basePtrOfPage ] = true;
301 memcpy(snapshotrecord->backingRecords[page].basePtrOfPage, &snapshotrecord->backingStore[page], sizeof(struct SnapShotPage));
304 snapshotrecord->lastSnapShot=theID;
305 snapshotrecord->lastBackingPage=snapshotrecord->snapShots[theID].firstBackingPage;
306 takeSnapshot(); //Make sure current snapshot is still good...All later ones are cleared
308 sTheRecord->mIDToRollback = theID;
310 getcontext( &sTheRecord->mContextToRollback );
312 * This is used to quit the process on rollback, so that
313 * the process which needs to rollback can quit allowing the process whose snapshotid matches the rollbackid to switch to
314 * this context and continue....
318 SSDEBUG("Invoked rollback");
322 * This fix obviates the need for a finalize call. hence less dependences for model-checker....
325 sTheRecord->mIDToRollback = -1;