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
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;
62 #endif //nothing to initialize for the fork based snapshotting.
64 /** HandlePF is the page fault handler for mprotect based snapshotting
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);
74 void* addr = ReturnPageAlignedAddress(si->si_addr);
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);
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 )) {
89 // Handle error by quitting?
91 #endif //nothing to handle for non snapshotting case.
94 /** ReturnPageAlignedAddress returns a page aligned address for the
95 * address being added as a side effect the numBytes are also changed.
98 void * ReturnPageAlignedAddress(void * addr) {
99 return (void *)(((uintptr_t)addr)&~(PAGESIZE-1));
102 /** PageAlignedAdressUpdate return a page aligned address for the
103 * address being added as a side effect the numBytes are also changed.
106 void * PageAlignAddressUpward(void * addr) {
107 return (void *)((((uintptr_t)addr)+PAGESIZE-1)&~(PAGESIZE-1));
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;
134 /** The initSnapShotLibrary function initializes the Snapshot library.
135 * @param entryPoint the function that should run the program.
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.... */
143 ss.ss_sp = MYMALLOC(SIGSTACKSIZE);
144 ss.ss_size = SIGSTACKSIZE;
146 sigaltstack(&ss, NULL);
149 sa.sa_flags = SA_SIGINFO | SA_NODEFER | SA_RESTART | SA_ONSTACK;
150 sigemptyset( &sa.sa_mask );
151 sa.sa_sigaction = HandlePF;
153 if( sigaction( SIGBUS, &sa, NULL ) == -1 ){
154 printf("SIGACTION CANNOT BE INSTALLED\n");
158 if( sigaction( SIGSEGV, &sa, NULL ) == -1 ){
159 printf("SIGACTION CANNOT BE INSTALLED\n");
163 initSnapShotRecord(numbackingpages, numsnapshots, nummemoryregions);
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...
170 memset(&si, 0, sizeof(si));
172 HandlePF(SIGSEGV, &si, NULL);
173 snapshotrecord->lastBackingPage--; //remove the fake page we copied
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);
182 basemySpace=system_malloc((numheappages+1)*PAGESIZE);
183 void * pagealignedbase=PageAlignAddressUpward(basemySpace);
184 mySpace = create_mspace_with_base(pagealignedbase, numheappages*PAGESIZE, 1 );
185 createSharedLibrary();
187 //step 2 setup the stack context.
189 int alreadySwapped = 0;
190 getcontext( &savedSnapshotContext );
191 if( !alreadySwapped ){
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 = ¤tContext;
198 makecontext( &newContext, entryPoint, 0 );
199 swapcontext( &swappedContext, &newContext );
202 //add the code to take a snapshot here...
203 //to return to user process, do a second swapcontext...
205 snapshotid = sTheRecord->currSnapShotID;
206 bool swapContext = false;
207 while( !sTheRecord->mbFinalize ){
208 sTheRecord->currSnapShotID=snapshotid+1;
211 ucontext_t currentContext;
217 swapcontext( ¤tContext, &( sTheRecord->mContextToRollback ) );
219 swapcontext( ¤tContext, &savedUserSnapshotContext );
225 char mesg[ 1024 ] = { 0 };
226 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 );
227 DumpIntoLog( "ModelSnapshot", mesg );
230 retVal=waitpid( forkedID, &status, 0 );
231 } while( -1 == retVal && errno == EINTR );
233 if( sTheRecord->mIDToRollback != snapshotid )
244 /** The addMemoryRegionToSnapShot function assumes that addr is page aligned.
246 void addMemoryRegionToSnapShot( void * addr, unsigned int numPages) {
247 #if USE_MPROTECT_SNAPSHOT
248 unsigned int memoryregion=snapshotrecord->lastRegion++;
249 if (memoryregion==snapshotrecord->maxRegions) {
250 printf("Exceeded supported number of memory regions!\n");
254 snapshotrecord->regionsToSnapShot[ memoryregion ].basePtr=addr;
255 snapshotrecord->regionsToSnapShot[ memoryregion ].sizeInPages=numPages;
256 #endif //NOT REQUIRED IN THE CASE OF FORK BASED SNAPSHOTS.
259 /** The takeSnapshot function takes a snapshot.
260 * @return The snapshot identifier.
263 snapshot_id takeSnapshot( ){
264 #if USE_MPROTECT_SNAPSHOT
265 for(unsigned int region=0; region<snapshotrecord->lastRegion;region++) {
266 if( mprotect(snapshotrecord->regionsToSnapShot[region].basePtr, snapshotrecord->regionsToSnapShot[region].sizeInPages*sizeof(struct SnapShotPage), PROT_READ ) == -1 ){
268 printf("Failed to mprotect inside of takeSnapShot\n");
272 unsigned int snapshot=snapshotrecord->lastSnapShot++;
273 if (snapshot==snapshotrecord->maxSnapShots) {
274 printf("Out of snapshots\n");
277 snapshotrecord->snapShots[snapshot].firstBackingPage=snapshotrecord->lastBackingPage;
281 swapcontext( &savedUserSnapshotContext, &savedSnapshotContext );
286 /** The rollBack function rollback to the given snapshot identifier.
287 * @param theID is the snapshot identifier to rollback to.
290 void rollBack( snapshot_id theID ){
291 #if USE_MPROTECT_SNAPSHOT
292 std::map< void *, bool, std::less< void * >, MyAlloc< std::pair< const void *, bool > > > duplicateMap;
293 for(unsigned int region=0; region<snapshotrecord->lastRegion;region++) {
294 if( mprotect(snapshotrecord->regionsToSnapShot[region].basePtr, snapshotrecord->regionsToSnapShot[region].sizeInPages*sizeof(struct SnapShotPage), PROT_READ | PROT_WRITE ) == -1 ){
296 printf("Failed to mprotect inside of takeSnapShot\n");
300 for(unsigned int page=snapshotrecord->snapShots[theID].firstBackingPage; page<snapshotrecord->lastBackingPage; page++) {
302 if( duplicateMap.find( snapshotrecord->backingRecords[page].basePtrOfPage ) != duplicateMap.end() ){
306 duplicateMap[ snapshotrecord->backingRecords[page].basePtrOfPage ] = true;
309 memcpy(snapshotrecord->backingRecords[page].basePtrOfPage, &snapshotrecord->backingStore[page], sizeof(struct SnapShotPage));
312 snapshotrecord->lastSnapShot=theID;
313 snapshotrecord->lastBackingPage=snapshotrecord->snapShots[theID].firstBackingPage;
314 takeSnapshot(); //Make sure current snapshot is still good...All later ones are cleared
316 sTheRecord->mIDToRollback = theID;
318 getcontext( &sTheRecord->mContextToRollback );
322 DumpIntoLog( "ModelSnapshot", "Invoked rollback" );
329 /** The finalize method shuts down the snapshotting system. */
332 #if !USE_MPROTECT_SNAPSHOT
333 sTheRecord->mbFinalize = true;