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;
31 struct Snapshot_t * sTheRecord = NULL;
33 struct Snapshot_t * sTheRecord = NULL;
36 #if !USE_MPROTECT_SNAPSHOT
37 static ucontext_t savedSnapshotContext;
38 static ucontext_t savedUserSnapshotContext;
39 static snapshot_id snapshotid = 0;
42 #if USE_MPROTECT_SNAPSHOT
44 /** The initSnapShotRecord method initialized the snapshotting data
45 * structures for the mprotect based 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));
109 void createSharedLibrary(){
110 #if !USE_MPROTECT_SNAPSHOT
111 //step 1. create shared memory.
112 if( sTheRecord ) return;
113 int fd = shm_open( "/ModelChecker-Snapshotter", O_RDWR | O_CREAT, 0777 ); //universal permissions.
114 if( -1 == fd ) FAILURE("shm_open");
115 if( -1 == ftruncate( fd, ( size_t )SHARED_MEMORY_DEFAULT + ( size_t )STACK_SIZE_DEFAULT ) ) FAILURE( "ftruncate" );
116 char * memMapBase = ( char * ) mmap( 0, ( size_t )SHARED_MEMORY_DEFAULT + ( size_t )STACK_SIZE_DEFAULT, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0 );
117 if( MAP_FAILED == memMapBase ) FAILURE("mmap");
118 sTheRecord = ( struct Snapshot_t * )memMapBase;
119 sTheRecord->mSharedMemoryBase = memMapBase + sizeof( struct Snapshot_t );
120 sTheRecord->mStackBase = ( char * )memMapBase + ( size_t )SHARED_MEMORY_DEFAULT;
121 sTheRecord->mStackSize = STACK_SIZE_DEFAULT;
122 sTheRecord->mIDToRollback = -1;
123 sTheRecord->currSnapShotID = 0;
124 sTheRecord->mbFinalize = false;
128 /** The initSnapShotLibrary function initializes the Snapshot library.
129 * @param entryPoint the function that should run the program.
131 void initSnapShotLibrary(unsigned int numbackingpages,
132 unsigned int numsnapshots, unsigned int nummemoryregions,
133 unsigned int numheappages, VoidFuncPtr entryPoint) {
134 #if USE_MPROTECT_SNAPSHOT
135 /* Setup a stack for our signal handler.... */
137 ss.ss_sp = MYMALLOC(SIGSTACKSIZE);
138 ss.ss_size = SIGSTACKSIZE;
140 sigaltstack(&ss, NULL);
143 sa.sa_flags = SA_SIGINFO | SA_NODEFER | SA_RESTART | SA_ONSTACK;
144 sigemptyset( &sa.sa_mask );
145 sa.sa_sigaction = HandlePF;
147 if( sigaction( SIGBUS, &sa, NULL ) == -1 ){
148 printf("SIGACTION CANNOT BE INSTALLED\n");
152 if( sigaction( SIGSEGV, &sa, NULL ) == -1 ){
153 printf("SIGACTION CANNOT BE INSTALLED\n");
157 initSnapShotRecord(numbackingpages, numsnapshots, nummemoryregions);
159 // EVIL HACK: We need to make sure that calls into the HandlePF method don't cause dynamic links
160 // The problem is that we end up protecting state in the dynamic linker...
161 // Solution is to call our signal handler before we start protecting stuff...
164 memset(&si, 0, sizeof(si));
166 HandlePF(SIGSEGV, &si, NULL);
167 snapshotrecord->lastBackingPage--; //remove the fake page we copied
169 basemySpace=MYMALLOC((numheappages+1)*PAGESIZE);
170 void * pagealignedbase=PageAlignAddressUpward(basemySpace);
171 mySpace = create_mspace_with_base(pagealignedbase, numheappages*PAGESIZE, 1 );
172 addMemoryRegionToSnapShot(pagealignedbase, numheappages);
176 basemySpace=system_malloc((numheappages+1)*PAGESIZE);
177 void * pagealignedbase=PageAlignAddressUpward(basemySpace);
178 mySpace = create_mspace_with_base(pagealignedbase, numheappages*PAGESIZE, 1 );
179 createSharedLibrary();
181 //step 2 setup the stack context.
183 int alreadySwapped = 0;
184 getcontext( &savedSnapshotContext );
185 if( !alreadySwapped ){
187 ucontext_t currentContext, swappedContext, newContext;
188 getcontext( &newContext );
189 newContext.uc_stack.ss_sp = sTheRecord->mStackBase;
190 newContext.uc_stack.ss_size = STACK_SIZE_DEFAULT;
191 newContext.uc_link = ¤tContext;
192 makecontext( &newContext, entryPoint, 0 );
193 swapcontext( &swappedContext, &newContext );
196 //add the code to take a snapshot here...
197 //to return to user process, do a second swapcontext...
199 snapshotid = sTheRecord->currSnapShotID;
200 bool swapContext = false;
201 while( !sTheRecord->mbFinalize ){
202 sTheRecord->currSnapShotID=snapshotid+1;
205 ucontext_t currentContext;
211 swapcontext( ¤tContext, &( sTheRecord->mContextToRollback ) );
213 swapcontext( ¤tContext, &savedUserSnapshotContext );
219 SSDEBUG("The process id of child is %d and the process id of this process is %d and snapshot id is %d",
220 forkedID, getpid(), snapshotid );
223 retVal=waitpid( forkedID, &status, 0 );
224 } while( -1 == retVal && errno == EINTR );
226 if( sTheRecord->mIDToRollback != snapshotid )
237 /** The addMemoryRegionToSnapShot function assumes that addr is page aligned.
239 void addMemoryRegionToSnapShot( void * addr, unsigned int numPages) {
240 #if USE_MPROTECT_SNAPSHOT
241 unsigned int memoryregion=snapshotrecord->lastRegion++;
242 if (memoryregion==snapshotrecord->maxRegions) {
243 printf("Exceeded supported number of memory regions!\n");
247 snapshotrecord->regionsToSnapShot[ memoryregion ].basePtr=addr;
248 snapshotrecord->regionsToSnapShot[ memoryregion ].sizeInPages=numPages;
249 #endif //NOT REQUIRED IN THE CASE OF FORK BASED SNAPSHOTS.
252 /** The takeSnapshot function takes a snapshot.
253 * @return The snapshot identifier.
256 snapshot_id takeSnapshot( ){
257 #if USE_MPROTECT_SNAPSHOT
258 for(unsigned int region=0; region<snapshotrecord->lastRegion;region++) {
259 if( mprotect(snapshotrecord->regionsToSnapShot[region].basePtr, snapshotrecord->regionsToSnapShot[region].sizeInPages*sizeof(struct SnapShotPage), PROT_READ ) == -1 ){
261 printf("Failed to mprotect inside of takeSnapShot\n");
265 unsigned int snapshot=snapshotrecord->lastSnapShot++;
266 if (snapshot==snapshotrecord->maxSnapShots) {
267 printf("Out of snapshots\n");
270 snapshotrecord->snapShots[snapshot].firstBackingPage=snapshotrecord->lastBackingPage;
274 swapcontext( &savedUserSnapshotContext, &savedSnapshotContext );
279 /** The rollBack function rollback to the given snapshot identifier.
280 * @param theID is the snapshot identifier to rollback to.
283 void rollBack( snapshot_id theID ){
284 #if USE_MPROTECT_SNAPSHOT
285 std::map< void *, bool, std::less< void * >, MyAlloc< std::pair< const void *, bool > > > duplicateMap;
286 for(unsigned int region=0; region<snapshotrecord->lastRegion;region++) {
287 if( mprotect(snapshotrecord->regionsToSnapShot[region].basePtr, snapshotrecord->regionsToSnapShot[region].sizeInPages*sizeof(struct SnapShotPage), PROT_READ | PROT_WRITE ) == -1 ){
289 printf("Failed to mprotect inside of takeSnapShot\n");
293 for(unsigned int page=snapshotrecord->snapShots[theID].firstBackingPage; page<snapshotrecord->lastBackingPage; page++) {
295 if( duplicateMap.find( snapshotrecord->backingRecords[page].basePtrOfPage ) != duplicateMap.end() ){
299 duplicateMap[ snapshotrecord->backingRecords[page].basePtrOfPage ] = true;
302 memcpy(snapshotrecord->backingRecords[page].basePtrOfPage, &snapshotrecord->backingStore[page], sizeof(struct SnapShotPage));
305 snapshotrecord->lastSnapShot=theID;
306 snapshotrecord->lastBackingPage=snapshotrecord->snapShots[theID].firstBackingPage;
307 takeSnapshot(); //Make sure current snapshot is still good...All later ones are cleared
309 sTheRecord->mIDToRollback = theID;
311 getcontext( &sTheRecord->mContextToRollback );
314 SSDEBUG("Invoked rollback");
320 /** The finalize method shuts down the snapshotting system. */
321 //Subramanian -- remove this function from the external interface and
322 //have us call it internally
325 #if !USE_MPROTECT_SNAPSHOT
326 sTheRecord->mbFinalize = true;