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); }
22 /* extern declaration definition */
23 #if USE_MPROTECT_SNAPSHOT
24 struct SnapShot * snapshotrecord = NULL;
25 struct Snapshot_t * sTheRecord = NULL;
27 struct Snapshot_t * sTheRecord = NULL;
29 void DumpIntoLog( const char * filename, const char * message ){
31 static pid_t thePID = getpid();
32 char newFn[ 1024 ] ={ 0 };
33 sprintf( newFn,"%s-%d.txt", filename, thePID );
34 FILE * myFile = fopen( newFn, "w+" );
35 fprintf( myFile, "the message %s: the process id %d\n", message, thePID );
41 #if !USE_MPROTECT_SNAPSHOT
42 static ucontext_t savedSnapshotContext;
43 static ucontext_t savedUserSnapshotContext;
44 static snapshot_id snapshotid = 0;
47 #if USE_MPROTECT_SNAPSHOT
49 /** The initSnapShotRecord method initialized the snapshotting data
50 * structures for the mprotect based snapshot.
52 void initSnapShotRecord(unsigned int numbackingpages, unsigned int numsnapshots, unsigned int nummemoryregions) {
53 snapshotrecord=( struct SnapShot * )MYMALLOC(sizeof(struct SnapShot));
54 snapshotrecord->regionsToSnapShot=( struct MemoryRegion * )MYMALLOC(sizeof(struct MemoryRegion)*nummemoryregions);
55 snapshotrecord->backingStoreBasePtr= ( struct SnapShotPage * )MYMALLOC( sizeof( struct SnapShotPage ) * (numbackingpages + 1) );
56 //Page align the backingstorepages
57 snapshotrecord->backingStore=( struct SnapShotPage * )PageAlignAddressUpward(snapshotrecord->backingStoreBasePtr);
58 snapshotrecord->backingRecords=( struct BackingPageRecord * )MYMALLOC(sizeof(struct BackingPageRecord)*numbackingpages);
59 snapshotrecord->snapShots= ( struct SnapShotRecord * )MYMALLOC(sizeof(struct SnapShotRecord)*numsnapshots);
60 snapshotrecord->lastSnapShot=0;
61 snapshotrecord->lastBackingPage=0;
62 snapshotrecord->lastRegion=0;
63 snapshotrecord->maxRegions=nummemoryregions;
64 snapshotrecord->maxBackingPages=numbackingpages;
65 snapshotrecord->maxSnapShots=numsnapshots;
67 #endif //nothing to initialize for the fork based snapshotting.
69 /** HandlePF is the page fault handler for mprotect based snapshotting
73 void HandlePF( int sig, siginfo_t *si, void * unused){
74 #if USE_MPROTECT_SNAPSHOT
75 if( si->si_code == SEGV_MAPERR ){
76 printf("Real Fault at %p\n", si->si_addr);
79 void* addr = ReturnPageAlignedAddress(si->si_addr);
81 unsigned int backingpage=snapshotrecord->lastBackingPage++; //Could run out of pages...
82 if (backingpage==snapshotrecord->maxBackingPages) {
83 printf("Out of backing pages at %p\n", si->si_addr);
88 memcpy(&(snapshotrecord->backingStore[backingpage]), addr, sizeof(struct SnapShotPage));
89 //remember where to copy page back to
90 snapshotrecord->backingRecords[backingpage].basePtrOfPage=addr;
91 //set protection to read/write
92 if (mprotect( addr, sizeof(struct SnapShotPage), PROT_READ | PROT_WRITE )) {
94 // Handle error by quitting?
96 #endif //nothing to handle for non snapshotting case.
99 /** ReturnPageAlignedAddress returns a page aligned address for the
100 * address being added as a side effect the numBytes are also changed.
103 void * ReturnPageAlignedAddress(void * addr) {
104 return (void *)(((uintptr_t)addr)&~(PAGESIZE-1));
107 /** PageAlignedAdressUpdate return a page aligned address for the
108 * address being added as a side effect the numBytes are also changed.
111 void * PageAlignAddressUpward(void * addr) {
112 return (void *)((((uintptr_t)addr)+PAGESIZE-1)&~(PAGESIZE-1));
117 void createSharedLibrary(){
118 #if !USE_MPROTECT_SNAPSHOT
119 //step 1. create shared memory.
120 if( sTheRecord ) return;
121 int fd = shm_open( "/ModelChecker-Snapshotter", O_RDWR | O_CREAT, 0777 ); //universal permissions.
122 if( -1 == fd ) FAILURE("shm_open");
123 if( -1 == ftruncate( fd, ( size_t )SHARED_MEMORY_DEFAULT + ( size_t )STACK_SIZE_DEFAULT ) ) FAILURE( "ftruncate" );
124 char * memMapBase = ( char * ) mmap( 0, ( size_t )SHARED_MEMORY_DEFAULT + ( size_t )STACK_SIZE_DEFAULT, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0 );
125 if( MAP_FAILED == memMapBase ) FAILURE("mmap");
126 sTheRecord = ( struct Snapshot_t * )memMapBase;
127 sTheRecord->mSharedMemoryBase = memMapBase + sizeof( struct Snapshot_t );
128 sTheRecord->mStackBase = ( char * )memMapBase + ( size_t )SHARED_MEMORY_DEFAULT;
129 sTheRecord->mStackSize = STACK_SIZE_DEFAULT;
130 sTheRecord->mIDToRollback = -1;
131 sTheRecord->currSnapShotID = 0;
132 sTheRecord->mbFinalize = false;
139 /** The initSnapShotLibrary function initializes the Snapshot library.
140 * @param entryPoint the function that should run the program.
142 void initSnapShotLibrary(unsigned int numbackingpages,
143 unsigned int numsnapshots, unsigned int nummemoryregions,
144 unsigned int numheappages, VoidFuncPtr entryPoint) {
145 #if USE_MPROTECT_SNAPSHOT
146 /* Setup a stack for our signal handler.... */
148 ss.ss_sp = MYMALLOC(SIGSTACKSIZE);
149 ss.ss_size = SIGSTACKSIZE;
151 sigaltstack(&ss, NULL);
154 sa.sa_flags = SA_SIGINFO | SA_NODEFER | SA_RESTART | SA_ONSTACK;
155 sigemptyset( &sa.sa_mask );
156 sa.sa_sigaction = HandlePF;
158 if( sigaction( SIGBUS, &sa, NULL ) == -1 ){
159 printf("SIGACTION CANNOT BE INSTALLED\n");
163 if( sigaction( SIGSEGV, &sa, NULL ) == -1 ){
164 printf("SIGACTION CANNOT BE INSTALLED\n");
168 initSnapShotRecord(numbackingpages, numsnapshots, nummemoryregions);
170 // EVIL HACK: We need to make sure that calls into the HandlePF method don't cause dynamic links
171 // The problem is that we end up protecting state in the dynamic linker...
172 // Solution is to call our signal handler before we start protecting stuff...
175 memset(&si, 0, sizeof(si));
177 HandlePF(SIGSEGV, &si, NULL);
178 snapshotrecord->lastBackingPage--; //remove the fake page we copied
180 basemySpace=MYMALLOC((numheappages+1)*PAGESIZE);
181 void * pagealignedbase=PageAlignAddressUpward(basemySpace);
182 mySpace = create_mspace_with_base(pagealignedbase, numheappages*PAGESIZE, 1 );
183 addMemoryRegionToSnapShot(pagealignedbase, numheappages);
187 basemySpace=system_malloc((numheappages+1)*PAGESIZE);
188 void * pagealignedbase=PageAlignAddressUpward(basemySpace);
189 mySpace = create_mspace_with_base(pagealignedbase, numheappages*PAGESIZE, 1 );
190 createSharedLibrary();
192 //step 2 setup the stack context.
194 int alreadySwapped = 0;
195 getcontext( &savedSnapshotContext );
196 if( !alreadySwapped ){
198 ucontext_t currentContext, swappedContext, newContext;
199 getcontext( &newContext );
200 newContext.uc_stack.ss_sp = sTheRecord->mStackBase;
201 newContext.uc_stack.ss_size = STACK_SIZE_DEFAULT;
202 newContext.uc_link = ¤tContext;
203 makecontext( &newContext, entryPoint, 0 );
204 swapcontext( &swappedContext, &newContext );
207 //add the code to take a snapshot here...
208 //to return to user process, do a second swapcontext...
210 snapshotid = sTheRecord->currSnapShotID;
211 bool swapContext = false;
212 while( !sTheRecord->mbFinalize ){
213 sTheRecord->currSnapShotID=snapshotid+1;
216 ucontext_t currentContext;
222 swapcontext( ¤tContext, &( sTheRecord->mContextToRollback ) );
224 swapcontext( ¤tContext, &savedUserSnapshotContext );
230 char mesg[ 1024 ] = { 0 };
231 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 );
232 DumpIntoLog( "ModelSnapshot", mesg );
235 retVal=waitpid( forkedID, &status, 0 );
236 } while( -1 == retVal && errno == EINTR );
238 if( sTheRecord->mIDToRollback != snapshotid )
249 /** The addMemoryRegionToSnapShot function assumes that addr is page aligned.
251 void addMemoryRegionToSnapShot( void * addr, unsigned int numPages) {
252 #if USE_MPROTECT_SNAPSHOT
253 unsigned int memoryregion=snapshotrecord->lastRegion++;
254 if (memoryregion==snapshotrecord->maxRegions) {
255 printf("Exceeded supported number of memory regions!\n");
259 snapshotrecord->regionsToSnapShot[ memoryregion ].basePtr=addr;
260 snapshotrecord->regionsToSnapShot[ memoryregion ].sizeInPages=numPages;
261 #endif //NOT REQUIRED IN THE CASE OF FORK BASED SNAPSHOTS.
264 /** The takeSnapshot function takes a snapshot.
265 * @return The snapshot identifier.
268 snapshot_id takeSnapshot( ){
269 #if USE_MPROTECT_SNAPSHOT
270 for(unsigned int region=0; region<snapshotrecord->lastRegion;region++) {
271 if( mprotect(snapshotrecord->regionsToSnapShot[region].basePtr, snapshotrecord->regionsToSnapShot[region].sizeInPages*sizeof(struct SnapShotPage), PROT_READ ) == -1 ){
273 printf("Failed to mprotect inside of takeSnapShot\n");
277 unsigned int snapshot=snapshotrecord->lastSnapShot++;
278 if (snapshot==snapshotrecord->maxSnapShots) {
279 printf("Out of snapshots\n");
282 snapshotrecord->snapShots[snapshot].firstBackingPage=snapshotrecord->lastBackingPage;
286 swapcontext( &savedUserSnapshotContext, &savedSnapshotContext );
291 /** The rollBack function rollback to the given snapshot identifier.
292 * @param theID is the snapshot identifier to rollback to.
295 void rollBack( snapshot_id theID ){
296 #if USE_MPROTECT_SNAPSHOT
297 std::map< void *, bool, std::less< void * >, MyAlloc< std::pair< const void *, bool > > > duplicateMap;
298 for(unsigned int region=0; region<snapshotrecord->lastRegion;region++) {
299 if( mprotect(snapshotrecord->regionsToSnapShot[region].basePtr, snapshotrecord->regionsToSnapShot[region].sizeInPages*sizeof(struct SnapShotPage), PROT_READ | PROT_WRITE ) == -1 ){
301 printf("Failed to mprotect inside of takeSnapShot\n");
305 for(unsigned int page=snapshotrecord->snapShots[theID].firstBackingPage; page<snapshotrecord->lastBackingPage; page++) {
307 if( duplicateMap.find( snapshotrecord->backingRecords[page].basePtrOfPage ) != duplicateMap.end() ){
311 duplicateMap[ snapshotrecord->backingRecords[page].basePtrOfPage ] = true;
314 memcpy(snapshotrecord->backingRecords[page].basePtrOfPage, &snapshotrecord->backingStore[page], sizeof(struct SnapShotPage));
317 snapshotrecord->lastSnapShot=theID;
318 snapshotrecord->lastBackingPage=snapshotrecord->snapShots[theID].firstBackingPage;
319 takeSnapshot(); //Make sure current snapshot is still good...All later ones are cleared
321 sTheRecord->mIDToRollback = theID;
323 getcontext( &sTheRecord->mContextToRollback );
327 DumpIntoLog( "ModelSnapshot", "Invoked rollback" );
334 /** The finalize method shuts down the snapshotting system. */
335 //Subramanian -- remove this function from the external interface and
336 //have us call it internally
339 #if !USE_MPROTECT_SNAPSHOT
340 sTheRecord->mbFinalize = true;