10 #include "snapshotimp.h"
15 #include <semaphore.h>
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;
26 struct Snapshot_t * sTheRecord = NULL;
28 void DumpIntoLog( const char * filename, const char * message ){
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 );
40 #if !USE_MPROTECT_SNAPSHOT
41 static ucontext_t savedSnapshotContext;
42 static ucontext_t savedUserSnapshotContext;
43 static snapshot_id snapshotid = 0;
45 /* Initialize snapshot data structure */
46 #if USE_MPROTECT_SNAPSHOT
48 /** The initSnapShotRecord method initialized the snapshotting data
49 * structures for the mprotect based snapshot.
51 void initSnapShotRecord(unsigned int numbackingpages, unsigned int numsnapshots, unsigned int nummemoryregions) {
52 snapshotrecord=( struct SnapShot * )MYMALLOC(sizeof(struct SnapShot));
53 snapshotrecord->regionsToSnapShot=( struct MemoryRegion * )MYMALLOC(sizeof(struct MemoryRegion)*nummemoryregions);
54 snapshotrecord->backingStoreBasePtr= ( struct SnapShotPage * )MYMALLOC( sizeof( struct SnapShotPage ) * (numbackingpages + 1) );
55 //Page align the backingstorepages
56 snapshotrecord->backingStore=( struct SnapShotPage * )PageAlignAddressUpward(snapshotrecord->backingStoreBasePtr);
57 snapshotrecord->backingRecords=( struct BackingPageRecord * )MYMALLOC(sizeof(struct BackingPageRecord)*numbackingpages);
58 snapshotrecord->snapShots= ( struct SnapShotRecord * )MYMALLOC(sizeof(struct SnapShotRecord)*numsnapshots);
59 snapshotrecord->lastSnapShot=0;
60 snapshotrecord->lastBackingPage=0;
61 snapshotrecord->lastRegion=0;
62 snapshotrecord->maxRegions=nummemoryregions;
63 snapshotrecord->maxBackingPages=numbackingpages;
64 snapshotrecord->maxSnapShots=numsnapshots;
66 #endif //nothing to initialize for the fork based snapshotting.
68 /** HandlePF is the page fault handler for mprotect based snapshotting
72 void HandlePF( int sig, siginfo_t *si, void * unused){
73 #if USE_MPROTECT_SNAPSHOT
74 if( si->si_code == SEGV_MAPERR ){
75 printf("Real Fault at %p\n", si->si_addr);
78 void* addr = ReturnPageAlignedAddress(si->si_addr);
80 unsigned int backingpage=snapshotrecord->lastBackingPage++; //Could run out of pages...
81 if (backingpage==snapshotrecord->maxBackingPages) {
82 printf("Out of backing pages at %p\n", si->si_addr);
87 memcpy(&(snapshotrecord->backingStore[backingpage]), addr, sizeof(struct SnapShotPage));
88 //remember where to copy page back to
89 snapshotrecord->backingRecords[backingpage].basePtrOfPage=addr;
90 //set protection to read/write
91 if (mprotect( addr, sizeof(struct SnapShotPage), PROT_READ | PROT_WRITE )) {
93 // Handle error by quitting?
95 #endif //nothing to handle for non snapshotting case.
98 /** ReturnPageAlignedAddress returns a page aligned address for the
99 * address being added as a side effect the numBytes are also changed.
102 void * ReturnPageAlignedAddress(void * addr) {
103 return (void *)(((uintptr_t)addr)&~(PAGESIZE-1));
106 /** PageAlignedAdressUpdate return a page aligned address for the
107 * address being added as a side effect the numBytes are also changed.
110 void * PageAlignAddressUpward(void * addr) {
111 return (void *)((((uintptr_t)addr)+PAGESIZE-1)&~(PAGESIZE-1));
116 void createSharedLibrary(){
117 #if !USE_MPROTECT_SNAPSHOT
118 //step 1. create shared memory.
119 if( sTheRecord ) return;
120 int fd = shm_open( "/ModelChecker-Snapshotter", O_RDWR | O_CREAT, 0777 ); //universal permissions.
121 if( -1 == fd ) FAILURE("shm_open");
122 if( -1 == ftruncate( fd, ( size_t )SHARED_MEMORY_DEFAULT + ( size_t )STACK_SIZE_DEFAULT ) ) FAILURE( "ftruncate" );
123 char * memMapBase = ( char * ) mmap( 0, ( size_t )SHARED_MEMORY_DEFAULT + ( size_t )STACK_SIZE_DEFAULT, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0 );
124 if( MAP_FAILED == memMapBase ) FAILURE("mmap");
125 sTheRecord = ( struct Snapshot_t * )memMapBase;
126 sTheRecord->mSharedMemoryBase = memMapBase + sizeof( struct Snapshot_t );
127 sTheRecord->mStackBase = ( char * )memMapBase + ( size_t )SHARED_MEMORY_DEFAULT;
128 sTheRecord->mStackSize = STACK_SIZE_DEFAULT;
129 sTheRecord->mIDToRollback = -1;
130 sTheRecord->currSnapShotID = 0;
131 sTheRecord->mbFinalize = false;
138 /** The initSnapShotLibrary function initializes the Snapshot library.
139 * @param entryPoint the function that should run the program.
141 void initSnapShotLibrary(unsigned int numbackingpages,
142 unsigned int numsnapshots, unsigned int nummemoryregions,
143 unsigned int numheappages, VoidFuncPtr entryPoint) {
144 #if USE_MPROTECT_SNAPSHOT
145 /* Setup a stack for our signal handler.... */
147 ss.ss_sp = MYMALLOC(SIGSTACKSIZE);
148 ss.ss_size = SIGSTACKSIZE;
150 sigaltstack(&ss, NULL);
153 sa.sa_flags = SA_SIGINFO | SA_NODEFER | SA_RESTART | SA_ONSTACK;
154 sigemptyset( &sa.sa_mask );
155 sa.sa_sigaction = HandlePF;
157 if( sigaction( SIGBUS, &sa, NULL ) == -1 ){
158 printf("SIGACTION CANNOT BE INSTALLED\n");
162 if( sigaction( SIGSEGV, &sa, NULL ) == -1 ){
163 printf("SIGACTION CANNOT BE INSTALLED\n");
167 initSnapShotRecord(numbackingpages, numsnapshots, nummemoryregions);
169 // EVIL HACK: We need to make sure that calls into the HandlePF method don't cause dynamic links
170 // The problem is that we end up protecting state in the dynamic linker...
171 // Solution is to call our signal handler before we start protecting stuff...
174 memset(&si, 0, sizeof(si));
176 HandlePF(SIGSEGV, &si, NULL);
177 snapshotrecord->lastBackingPage--; //remove the fake page we copied
179 basemySpace=MYMALLOC((numheappages+1)*PAGESIZE);
180 void * pagealignedbase=PageAlignAddressUpward(basemySpace);
181 mySpace = create_mspace_with_base(pagealignedbase, numheappages*PAGESIZE, 1 );
182 addMemoryRegionToSnapShot(pagealignedbase, numheappages);
186 basemySpace=system_malloc((numheappages+1)*PAGESIZE);
187 void * pagealignedbase=PageAlignAddressUpward(basemySpace);
188 mySpace = create_mspace_with_base(pagealignedbase, numheappages*PAGESIZE, 1 );
189 createSharedLibrary();
191 //step 2 setup the stack context.
193 int alreadySwapped = 0;
194 getcontext( &savedSnapshotContext );
195 if( !alreadySwapped ){
197 ucontext_t currentContext, swappedContext, newContext;
198 getcontext( &newContext );
199 newContext.uc_stack.ss_sp = sTheRecord->mStackBase;
200 newContext.uc_stack.ss_size = STACK_SIZE_DEFAULT;
201 newContext.uc_link = ¤tContext;
202 makecontext( &newContext, entryPoint, 0 );
203 swapcontext( &swappedContext, &newContext );
206 //add the code to take a snapshot here...
207 //to return to user process, do a second swapcontext...
209 snapshotid = sTheRecord->currSnapShotID;
210 bool swapContext = false;
211 while( !sTheRecord->mbFinalize ){
212 sTheRecord->currSnapShotID=snapshotid+1;
215 ucontext_t currentContext;
221 swapcontext( ¤tContext, &( sTheRecord->mContextToRollback ) );
223 swapcontext( ¤tContext, &savedUserSnapshotContext );
229 char mesg[ 1024 ] = { 0 };
230 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 );
231 DumpIntoLog( "ModelSnapshot", mesg );
234 retVal=waitpid( forkedID, &status, 0 );
235 } while( -1 == retVal && errno == EINTR );
237 if( sTheRecord->mIDToRollback != snapshotid )
248 /** The addMemoryRegionToSnapShot function assumes that addr is page aligned.
250 void addMemoryRegionToSnapShot( void * addr, unsigned int numPages) {
251 #if USE_MPROTECT_SNAPSHOT
252 unsigned int memoryregion=snapshotrecord->lastRegion++;
253 if (memoryregion==snapshotrecord->maxRegions) {
254 printf("Exceeded supported number of memory regions!\n");
258 snapshotrecord->regionsToSnapShot[ memoryregion ].basePtr=addr;
259 snapshotrecord->regionsToSnapShot[ memoryregion ].sizeInPages=numPages;
260 #endif //NOT REQUIRED IN THE CASE OF FORK BASED SNAPSHOTS.
263 /** The takeSnapshot function takes a snapshot.
264 * @return The snapshot identifier.
267 snapshot_id takeSnapshot( ){
268 #if USE_MPROTECT_SNAPSHOT
269 for(unsigned int region=0; region<snapshotrecord->lastRegion;region++) {
270 if( mprotect(snapshotrecord->regionsToSnapShot[region].basePtr, snapshotrecord->regionsToSnapShot[region].sizeInPages*sizeof(struct SnapShotPage), PROT_READ ) == -1 ){
272 printf("Failed to mprotect inside of takeSnapShot\n");
276 unsigned int snapshot=snapshotrecord->lastSnapShot++;
277 if (snapshot==snapshotrecord->maxSnapShots) {
278 printf("Out of snapshots\n");
281 snapshotrecord->snapShots[snapshot].firstBackingPage=snapshotrecord->lastBackingPage;
285 swapcontext( &savedUserSnapshotContext, &savedSnapshotContext );
290 /** The rollBack function rollback to the given snapshot identifier.
291 * @param theID is the snapshot identifier to rollback to.
294 void rollBack( snapshot_id theID ){
295 #if USE_MPROTECT_SNAPSHOT
296 std::map< void *, bool, std::less< void * >, MyAlloc< std::pair< const void *, bool > > > duplicateMap;
297 for(unsigned int region=0; region<snapshotrecord->lastRegion;region++) {
298 if( mprotect(snapshotrecord->regionsToSnapShot[region].basePtr, snapshotrecord->regionsToSnapShot[region].sizeInPages*sizeof(struct SnapShotPage), PROT_READ | PROT_WRITE ) == -1 ){
300 printf("Failed to mprotect inside of takeSnapShot\n");
304 for(unsigned int page=snapshotrecord->snapShots[theID].firstBackingPage; page<snapshotrecord->lastBackingPage; page++) {
306 if( duplicateMap.find( snapshotrecord->backingRecords[page].basePtrOfPage ) != duplicateMap.end() ){
310 duplicateMap[ snapshotrecord->backingRecords[page].basePtrOfPage ] = true;
313 memcpy(snapshotrecord->backingRecords[page].basePtrOfPage, &snapshotrecord->backingStore[page], sizeof(struct SnapShotPage));
316 snapshotrecord->lastSnapShot=theID;
317 snapshotrecord->lastBackingPage=snapshotrecord->snapShots[theID].firstBackingPage;
318 takeSnapshot(); //Make sure current snapshot is still good...All later ones are cleared
320 sTheRecord->mIDToRollback = theID;
322 getcontext( &sTheRecord->mContextToRollback );
326 DumpIntoLog( "ModelSnapshot", "Invoked rollback" );
333 /** The finalize method shuts down the snapshotting system. */
334 //Subramanian -- remove this function from the external interface and
335 //have us call it internally
338 #if !USE_MPROTECT_SNAPSHOT
339 sTheRecord->mbFinalize = true;