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 void HandlePF( int sig, siginfo_t *si, void * unused){
65 #if USE_MPROTECT_SNAPSHOT
66 if( si->si_code == SEGV_MAPERR ){
67 printf("Real Fault at %p\n", si->si_addr);
70 void* addr = ReturnPageAlignedAddress(si->si_addr);
72 unsigned int backingpage=snapshotrecord->lastBackingPage++; //Could run out of pages...
73 if (backingpage==snapshotrecord->maxBackingPages) {
74 printf("Out of backing pages at %p\n", si->si_addr);
79 memcpy(&(snapshotrecord->backingStore[backingpage]), addr, sizeof(struct SnapShotPage));
80 //remember where to copy page back to
81 snapshotrecord->backingRecords[backingpage].basePtrOfPage=addr;
82 //set protection to read/write
83 if (mprotect( addr, sizeof(struct SnapShotPage), PROT_READ | PROT_WRITE )) {
85 // Handle error by quitting?
87 #endif //nothing to handle for non snapshotting case.
90 //Return a page aligned address for the address being added
91 //as a side effect the numBytes are also changed.
92 void * ReturnPageAlignedAddress(void * addr) {
93 return (void *)(((uintptr_t)addr)&~(PAGESIZE-1));
96 //Return a page aligned address for the address being added
97 //as a side effect the numBytes are also changed.
98 void * PageAlignAddressUpward(void * addr) {
99 return (void *)((((uintptr_t)addr)+PAGESIZE-1)&~(PAGESIZE-1));
104 void createSharedLibrary(){
105 #if !USE_MPROTECT_SNAPSHOT
106 //step 1. create shared memory.
107 if( sTheRecord ) return;
108 int fd = shm_open( "/ModelChecker-Snapshotter", O_RDWR | O_CREAT, 0777 ); //universal permissions.
109 if( -1 == fd ) FAILURE("shm_open");
110 if( -1 == ftruncate( fd, ( size_t )SHARED_MEMORY_DEFAULT + ( size_t )STACK_SIZE_DEFAULT ) ) FAILURE( "ftruncate" );
111 char * memMapBase = ( char * ) mmap( 0, ( size_t )SHARED_MEMORY_DEFAULT + ( size_t )STACK_SIZE_DEFAULT, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0 );
112 if( MAP_FAILED == memMapBase ) FAILURE("mmap");
113 sTheRecord = ( struct Snapshot_t * )memMapBase;
114 sTheRecord->mSharedMemoryBase = memMapBase + sizeof( struct Snapshot_t );
115 sTheRecord->mStackBase = ( char * )memMapBase + ( size_t )SHARED_MEMORY_DEFAULT;
116 sTheRecord->mStackSize = STACK_SIZE_DEFAULT;
117 sTheRecord->mIDToRollback = -1;
118 sTheRecord->currSnapShotID = 0;
119 sTheRecord->mbFinalize = false;
125 void initSnapShotLibrary(unsigned int numbackingpages,
126 unsigned int numsnapshots, unsigned int nummemoryregions,
127 unsigned int numheappages, VoidFuncPtr entryPoint) {
128 #if USE_MPROTECT_SNAPSHOT
129 /* Setup a stack for our signal handler.... */
131 ss.ss_sp = MYMALLOC(SIGSTACKSIZE);
132 ss.ss_size = SIGSTACKSIZE;
134 sigaltstack(&ss, NULL);
137 sa.sa_flags = SA_SIGINFO | SA_NODEFER | SA_RESTART | SA_ONSTACK;
138 sigemptyset( &sa.sa_mask );
139 sa.sa_sigaction = HandlePF;
141 if( sigaction( SIGBUS, &sa, NULL ) == -1 ){
142 printf("SIGACTION CANNOT BE INSTALLED\n");
146 if( sigaction( SIGSEGV, &sa, NULL ) == -1 ){
147 printf("SIGACTION CANNOT BE INSTALLED\n");
151 initSnapShotRecord(numbackingpages, numsnapshots, nummemoryregions);
153 // EVIL HACK: We need to make sure that calls into the HandlePF method don't cause dynamic links
154 // The problem is that we end up protecting state in the dynamic linker...
155 // Solution is to call our signal handler before we start protecting stuff...
158 memset(&si, 0, sizeof(si));
160 HandlePF(SIGSEGV, &si, NULL);
161 snapshotrecord->lastBackingPage--; //remove the fake page we copied
163 basemySpace=MYMALLOC((numheappages+1)*PAGESIZE);
164 void * pagealignedbase=PageAlignAddressUpward(basemySpace);
165 mySpace = create_mspace_with_base(pagealignedbase, numheappages*PAGESIZE, 1 );
166 addMemoryRegionToSnapShot(pagealignedbase, numheappages);
170 basemySpace=system_malloc((numheappages+1)*PAGESIZE);
171 void * pagealignedbase=PageAlignAddressUpward(basemySpace);
172 mySpace = create_mspace_with_base(pagealignedbase, numheappages*PAGESIZE, 1 );
173 createSharedLibrary();
175 //step 2 setup the stack context.
177 int alreadySwapped = 0;
178 getcontext( &savedSnapshotContext );
179 if( !alreadySwapped ){
181 ucontext_t currentContext, swappedContext, newContext;
182 getcontext( &newContext );
183 newContext.uc_stack.ss_sp = sTheRecord->mStackBase;
184 newContext.uc_stack.ss_size = STACK_SIZE_DEFAULT;
185 newContext.uc_link = ¤tContext;
186 makecontext( &newContext, entryPoint, 0 );
187 swapcontext( &swappedContext, &newContext );
190 //add the code to take a snapshot here...
191 //to return to user process, do a second swapcontext...
193 snapshotid = sTheRecord->currSnapShotID;
194 bool swapContext = false;
195 while( !sTheRecord->mbFinalize ){
196 sTheRecord->currSnapShotID=snapshotid+1;
199 ucontext_t currentContext;
205 swapcontext( ¤tContext, &( sTheRecord->mContextToRollback ) );
207 swapcontext( ¤tContext, &savedUserSnapshotContext );
213 char mesg[ 1024 ] = { 0 };
214 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 );
215 DumpIntoLog( "ModelSnapshot", mesg );
218 retVal=waitpid( forkedID, &status, 0 );
219 } while( -1 == retVal && errno == EINTR );
221 if( sTheRecord->mIDToRollback != snapshotid )
231 /* This function assumes that addr is page aligned */
232 void addMemoryRegionToSnapShot( void * addr, unsigned int numPages) {
233 #if USE_MPROTECT_SNAPSHOT
234 unsigned int memoryregion=snapshotrecord->lastRegion++;
235 if (memoryregion==snapshotrecord->maxRegions) {
236 printf("Exceeded supported number of memory regions!\n");
240 snapshotrecord->regionsToSnapShot[ memoryregion ].basePtr=addr;
241 snapshotrecord->regionsToSnapShot[ memoryregion ].sizeInPages=numPages;
242 #endif //NOT REQUIRED IN THE CASE OF FORK BASED SNAPSHOTS.
245 snapshot_id takeSnapshot( ){
246 #if USE_MPROTECT_SNAPSHOT
247 for(unsigned int region=0; region<snapshotrecord->lastRegion;region++) {
248 if( mprotect(snapshotrecord->regionsToSnapShot[region].basePtr, snapshotrecord->regionsToSnapShot[region].sizeInPages*sizeof(struct SnapShotPage), PROT_READ ) == -1 ){
250 printf("Failed to mprotect inside of takeSnapShot\n");
254 unsigned int snapshot=snapshotrecord->lastSnapShot++;
255 if (snapshot==snapshotrecord->maxSnapShots) {
256 printf("Out of snapshots\n");
259 snapshotrecord->snapShots[snapshot].firstBackingPage=snapshotrecord->lastBackingPage;
263 swapcontext( &savedUserSnapshotContext, &savedSnapshotContext );
267 void rollBack( snapshot_id theID ){
268 #if USE_MPROTECT_SNAPSHOT
269 std::map< void *, bool, std::less< void * >, MyAlloc< std::pair< const void *, bool > > > duplicateMap;
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 | PROT_WRITE ) == -1 ){
273 printf("Failed to mprotect inside of takeSnapShot\n");
277 for(unsigned int page=snapshotrecord->snapShots[theID].firstBackingPage; page<snapshotrecord->lastBackingPage; page++) {
279 if( duplicateMap.find( snapshotrecord->backingRecords[page].basePtrOfPage ) != duplicateMap.end() ){
283 duplicateMap[ snapshotrecord->backingRecords[page].basePtrOfPage ] = true;
286 memcpy(snapshotrecord->backingRecords[page].basePtrOfPage, &snapshotrecord->backingStore[page], sizeof(struct SnapShotPage));
289 snapshotrecord->lastSnapShot=theID;
290 snapshotrecord->lastBackingPage=snapshotrecord->snapShots[theID].firstBackingPage;
291 takeSnapshot(); //Make sure current snapshot is still good...All later ones are cleared
293 sTheRecord->mIDToRollback = theID;
295 getcontext( &sTheRecord->mContextToRollback );
299 DumpIntoLog( "ModelSnapshot", "Invoked rollback" );
307 #if !USE_MPROTECT_SNAPSHOT
308 sTheRecord->mbFinalize = true;