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
36 static ucontext_t savedSnapshotContext;
37 static ucontext_t savedUserSnapshotContext;
38 static snapshot_id snapshotid = 0;
41 /** PageAlignedAdressUpdate return a page aligned address for the
42 * address being added as a side effect the numBytes are also changed.
44 static void * PageAlignAddressUpward(void * addr) {
45 return (void *)((((uintptr_t)addr)+PAGESIZE-1)&~(PAGESIZE-1));
48 #if USE_MPROTECT_SNAPSHOT
50 /** ReturnPageAlignedAddress returns a page aligned address for the
51 * address being added as a side effect the numBytes are also changed.
53 static void * ReturnPageAlignedAddress(void * addr) {
54 return (void *)(((uintptr_t)addr)&~(PAGESIZE-1));
57 /** The initSnapShotRecord method initialized the snapshotting data
58 * structures for the mprotect based snapshot.
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;
76 /** HandlePF is the page fault handler for mprotect based snapshotting
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);
84 void* addr = ReturnPageAlignedAddress(si->si_addr);
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);
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 )) {
99 // Handle error by quitting?
102 #endif //nothing to handle for non snapshotting case.
104 void createSharedLibrary(){
105 #if !USE_MPROTECT_SNAPSHOT
106 //step 1. create shared memory.
109 int fd = shm_open( "/ModelChecker-Snapshotter", O_RDWR | O_CREAT, 0777 ); //universal permissions.
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 )
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;
126 /** The initSnapShotLibrary function initializes the Snapshot library.
127 * @param entryPoint the function that should run the program.
129 void initSnapShotLibrary(unsigned int numbackingpages,
130 unsigned int numsnapshots, unsigned int nummemoryregions,
131 unsigned int numheappages, VoidFuncPtr entryPoint) {
132 #if USE_MPROTECT_SNAPSHOT
133 /* Setup a stack for our signal handler.... */
135 ss.ss_sp = MYMALLOC(SIGSTACKSIZE);
136 ss.ss_size = SIGSTACKSIZE;
138 sigaltstack(&ss, NULL);
141 sa.sa_flags = SA_SIGINFO | SA_NODEFER | SA_RESTART | SA_ONSTACK;
142 sigemptyset( &sa.sa_mask );
143 sa.sa_sigaction = HandlePF;
145 if( sigaction( SIGBUS, &sa, NULL ) == -1 ){
146 printf("SIGACTION CANNOT BE INSTALLED\n");
150 if( sigaction( SIGSEGV, &sa, NULL ) == -1 ){
151 printf("SIGACTION CANNOT BE INSTALLED\n");
155 initSnapShotRecord(numbackingpages, numsnapshots, nummemoryregions);
157 // EVIL HACK: We need to make sure that calls into the HandlePF method don't cause dynamic links
158 // The problem is that we end up protecting state in the dynamic linker...
159 // Solution is to call our signal handler before we start protecting stuff...
162 memset(&si, 0, sizeof(si));
164 HandlePF(SIGSEGV, &si, NULL);
165 snapshotrecord->lastBackingPage--; //remove the fake page we copied
167 basemySpace=MYMALLOC((numheappages+1)*PAGESIZE);
168 void * pagealignedbase=PageAlignAddressUpward(basemySpace);
169 mySpace = create_mspace_with_base(pagealignedbase, numheappages*PAGESIZE, 1 );
170 addMemoryRegionToSnapShot(pagealignedbase, numheappages);
174 basemySpace=system_malloc((numheappages+1)*PAGESIZE);
175 void * pagealignedbase=PageAlignAddressUpward(basemySpace);
176 mySpace = create_mspace_with_base(pagealignedbase, numheappages*PAGESIZE, 1 );
177 createSharedLibrary();
179 //step 2 setup the stack context.
180 ucontext_t newContext;
181 getcontext( &newContext );
182 newContext.uc_stack.ss_sp = sTheRecord->mStackBase;
183 newContext.uc_stack.ss_size = STACK_SIZE_DEFAULT;
184 makecontext( &newContext, entryPoint, 0 );
185 /* switch to a new entryPoint context, on a new stack */
186 swapcontext(&savedSnapshotContext, &newContext);
188 //add the code to take a snapshot here...
189 //to return to user process, do a second swapcontext...
191 snapshotid = sTheRecord->currSnapShotID;
192 bool swapContext = false;
194 sTheRecord->currSnapShotID=snapshotid+1;
197 ucontext_t currentContext;
203 swapcontext( ¤tContext, &( sTheRecord->mContextToRollback ) );
205 swapcontext( ¤tContext, &savedUserSnapshotContext );
211 SSDEBUG("The process id of child is %d and the process id of this process is %d and snapshot id is %d",
212 forkedID, getpid(), snapshotid );
215 retVal=waitpid( forkedID, &status, 0 );
216 } while( -1 == retVal && errno == EINTR );
218 if( sTheRecord->mIDToRollback != snapshotid )
229 /** The addMemoryRegionToSnapShot function assumes that addr is page aligned.
231 void addMemoryRegionToSnapShot( void * addr, unsigned int numPages) {
232 #if USE_MPROTECT_SNAPSHOT
233 unsigned int memoryregion=snapshotrecord->lastRegion++;
234 if (memoryregion==snapshotrecord->maxRegions) {
235 printf("Exceeded supported number of memory regions!\n");
239 snapshotrecord->regionsToSnapShot[ memoryregion ].basePtr=addr;
240 snapshotrecord->regionsToSnapShot[ memoryregion ].sizeInPages=numPages;
241 #endif //NOT REQUIRED IN THE CASE OF FORK BASED SNAPSHOTS.
244 /** The takeSnapshot function takes a snapshot.
245 * @return The snapshot identifier.
247 snapshot_id takeSnapshot( ){
248 #if USE_MPROTECT_SNAPSHOT
249 for(unsigned int region=0; region<snapshotrecord->lastRegion;region++) {
250 if( mprotect(snapshotrecord->regionsToSnapShot[region].basePtr, snapshotrecord->regionsToSnapShot[region].sizeInPages*sizeof(struct SnapShotPage), PROT_READ ) == -1 ){
252 printf("Failed to mprotect inside of takeSnapShot\n");
256 unsigned int snapshot=snapshotrecord->lastSnapShot++;
257 if (snapshot==snapshotrecord->maxSnapShots) {
258 printf("Out of snapshots\n");
261 snapshotrecord->snapShots[snapshot].firstBackingPage=snapshotrecord->lastBackingPage;
265 swapcontext( &savedUserSnapshotContext, &savedSnapshotContext );
270 /** The rollBack function rollback to the given snapshot identifier.
271 * @param theID is the snapshot identifier to rollback to.
273 void rollBack( snapshot_id theID ){
274 #if USE_MPROTECT_SNAPSHOT
275 std::map< void *, bool, std::less< void * >, MyAlloc< std::pair< const void *, bool > > > duplicateMap;
276 for(unsigned int region=0; region<snapshotrecord->lastRegion;region++) {
277 if( mprotect(snapshotrecord->regionsToSnapShot[region].basePtr, snapshotrecord->regionsToSnapShot[region].sizeInPages*sizeof(struct SnapShotPage), PROT_READ | PROT_WRITE ) == -1 ){
279 printf("Failed to mprotect inside of takeSnapShot\n");
283 for(unsigned int page=snapshotrecord->snapShots[theID].firstBackingPage; page<snapshotrecord->lastBackingPage; page++) {
285 if( duplicateMap.find( snapshotrecord->backingRecords[page].basePtrOfPage ) != duplicateMap.end() ){
289 duplicateMap[ snapshotrecord->backingRecords[page].basePtrOfPage ] = true;
292 memcpy(snapshotrecord->backingRecords[page].basePtrOfPage, &snapshotrecord->backingStore[page], sizeof(struct SnapShotPage));
295 snapshotrecord->lastSnapShot=theID;
296 snapshotrecord->lastBackingPage=snapshotrecord->snapShots[theID].firstBackingPage;
297 takeSnapshot(); //Make sure current snapshot is still good...All later ones are cleared
299 sTheRecord->mIDToRollback = theID;
301 getcontext( &sTheRecord->mContextToRollback );
304 SSDEBUG("Invoked rollback");
307 sTheRecord->mIDToRollback = -1;