11 #include "hashtable.h"
16 #define FAILURE(mesg) { model_print("failed in the API: %s with errno relative message: %s\n", mesg, strerror(errno)); exit(EXIT_FAILURE); }
18 /** PageAlignedAdressUpdate return a page aligned address for the
19 * address being added as a side effect the numBytes are also changed.
21 static void * PageAlignAddressUpward(void *addr)
23 return (void *)((((uintptr_t)addr) + PAGESIZE - 1) & ~(PAGESIZE - 1));
26 #if USE_MPROTECT_SNAPSHOT
28 /* Each snapshotrecord lists the firstbackingpage that must be written to
29 * revert to that snapshot */
30 struct SnapShotRecord {
31 unsigned int firstBackingPage;
34 /** @brief Backing store page */
35 typedef unsigned char snapshot_page_t[PAGESIZE];
37 /* List the base address of the corresponding page in the backing store so we
38 * know where to copy it to */
39 struct BackingPageRecord {
43 /* Struct for each memory region */
45 void *basePtr; // base of memory region
46 int sizeInPages; // size of memory region in pages
49 /* Primary struct for snapshotting system */
51 struct MemoryRegion *regionsToSnapShot; //This pointer references an array of memory regions to snapshot
52 snapshot_page_t *backingStore; //This pointer references an array of snapshotpage's that form the backing store
53 void *backingStoreBasePtr; //This pointer references an array of snapshotpage's that form the backing store
54 struct BackingPageRecord *backingRecords; //This pointer references an array of backingpagerecord's (same number of elements as backingstore
55 struct SnapShotRecord *snapShots; //This pointer references the snapshot array
57 unsigned int lastSnapShot; //Stores the next snapshot record we should use
58 unsigned int lastBackingPage; //Stores the next backingpage we should use
59 unsigned int lastRegion; //Stores the next memory region to be used
61 unsigned int maxRegions; //Stores the max number of memory regions we support
62 unsigned int maxBackingPages; //Stores the total number of backing pages
63 unsigned int maxSnapShots; //Stores the total number of snapshots we allow
66 static struct SnapShot *snapshotrecord = NULL;
68 /** ReturnPageAlignedAddress returns a page aligned address for the
69 * address being added as a side effect the numBytes are also changed.
71 static void * ReturnPageAlignedAddress(void *addr)
73 return (void *)(((uintptr_t)addr) & ~(PAGESIZE - 1));
76 /** The initSnapShotRecord method initialized the snapshotting data
77 * structures for the mprotect based snapshot.
79 static void initSnapShotRecord(unsigned int numbackingpages, unsigned int numsnapshots, unsigned int nummemoryregions)
81 snapshotrecord = (struct SnapShot *)model_malloc(sizeof(struct SnapShot));
82 snapshotrecord->regionsToSnapShot = (struct MemoryRegion *)model_malloc(sizeof(struct MemoryRegion) * nummemoryregions);
83 snapshotrecord->backingStoreBasePtr = (void *)model_malloc(sizeof(snapshot_page_t) * (numbackingpages + 1));
84 //Page align the backingstorepages
85 snapshotrecord->backingStore = (snapshot_page_t *)PageAlignAddressUpward(snapshotrecord->backingStoreBasePtr);
86 snapshotrecord->backingRecords = (struct BackingPageRecord *)model_malloc(sizeof(struct BackingPageRecord) * numbackingpages);
87 snapshotrecord->snapShots = (struct SnapShotRecord *)model_malloc(sizeof(struct SnapShotRecord) * numsnapshots);
88 snapshotrecord->lastSnapShot = 0;
89 snapshotrecord->lastBackingPage = 0;
90 snapshotrecord->lastRegion = 0;
91 snapshotrecord->maxRegions = nummemoryregions;
92 snapshotrecord->maxBackingPages = numbackingpages;
93 snapshotrecord->maxSnapShots = numsnapshots;
96 /** HandlePF is the page fault handler for mprotect based snapshotting
99 static void HandlePF(int sig, siginfo_t *si, void *unused)
101 if (si->si_code == SEGV_MAPERR) {
102 model_print("Real Fault at %p\n", si->si_addr);
104 model_print("For debugging, place breakpoint at: %s:%d\n",
108 void* addr = ReturnPageAlignedAddress(si->si_addr);
110 unsigned int backingpage = snapshotrecord->lastBackingPage++; //Could run out of pages...
111 if (backingpage == snapshotrecord->maxBackingPages) {
112 model_print("Out of backing pages at %p\n", si->si_addr);
117 memcpy(&(snapshotrecord->backingStore[backingpage]), addr, sizeof(snapshot_page_t));
118 //remember where to copy page back to
119 snapshotrecord->backingRecords[backingpage].basePtrOfPage = addr;
120 //set protection to read/write
121 if (mprotect(addr, sizeof(snapshot_page_t), PROT_READ | PROT_WRITE)) {
123 // Handle error by quitting?
127 /** The initSnapshotLibrary function initializes the snapshot library.
128 * @param entryPoint the function that should run the program.
130 void initSnapshotLibrary(unsigned int numbackingpages,
131 unsigned int numsnapshots, unsigned int nummemoryregions,
132 unsigned int numheappages, VoidFuncPtr entryPoint)
134 /* Setup a stack for our signal handler.... */
136 ss.ss_sp = PageAlignAddressUpward(model_malloc(SIGSTACKSIZE + PAGESIZE - 1));
137 ss.ss_size = SIGSTACKSIZE;
139 sigaltstack(&ss, NULL);
142 sa.sa_flags = SA_SIGINFO | SA_NODEFER | SA_RESTART | SA_ONSTACK;
143 sigemptyset(&sa.sa_mask);
144 sa.sa_sigaction = HandlePF;
146 if (sigaction(SIGBUS, &sa, NULL) == -1) {
147 model_print("SIGACTION CANNOT BE INSTALLED\n");
151 if (sigaction(SIGSEGV, &sa, NULL) == -1) {
152 model_print("SIGACTION CANNOT BE INSTALLED\n");
156 initSnapShotRecord(numbackingpages, numsnapshots, nummemoryregions);
158 // EVIL HACK: We need to make sure that calls into the HandlePF method don't cause dynamic links
159 // The problem is that we end up protecting state in the dynamic linker...
160 // Solution is to call our signal handler before we start protecting stuff...
163 memset(&si, 0, sizeof(si));
164 si.si_addr = ss.ss_sp;
165 HandlePF(SIGSEGV, &si, NULL);
166 snapshotrecord->lastBackingPage--; //remove the fake page we copied
168 void *basemySpace = model_malloc((numheappages + 1) * PAGESIZE);
169 void *pagealignedbase = PageAlignAddressUpward(basemySpace);
170 user_snapshot_space = create_mspace_with_base(pagealignedbase, numheappages * PAGESIZE, 1);
171 addMemoryRegionToSnapShot(pagealignedbase, numheappages);
173 void *base_model_snapshot_space = model_malloc((numheappages + 1) * PAGESIZE);
174 pagealignedbase = PageAlignAddressUpward(base_model_snapshot_space);
175 model_snapshot_space = create_mspace_with_base(pagealignedbase, numheappages * PAGESIZE, 1);
176 addMemoryRegionToSnapShot(pagealignedbase, numheappages);
181 /** The addMemoryRegionToSnapShot function assumes that addr is page aligned. */
182 void addMemoryRegionToSnapShot(void *addr, unsigned int numPages)
184 unsigned int memoryregion = snapshotrecord->lastRegion++;
185 if (memoryregion == snapshotrecord->maxRegions) {
186 model_print("Exceeded supported number of memory regions!\n");
190 snapshotrecord->regionsToSnapShot[memoryregion].basePtr = addr;
191 snapshotrecord->regionsToSnapShot[memoryregion].sizeInPages = numPages;
194 /** The takeSnapshot function takes a snapshot.
195 * @return The snapshot identifier.
197 snapshot_id takeSnapshot()
199 for (unsigned int region = 0; region < snapshotrecord->lastRegion; region++) {
200 if (mprotect(snapshotrecord->regionsToSnapShot[region].basePtr, snapshotrecord->regionsToSnapShot[region].sizeInPages * sizeof(snapshot_page_t), PROT_READ) == -1) {
202 model_print("Failed to mprotect inside of takeSnapShot\n");
206 unsigned int snapshot = snapshotrecord->lastSnapShot++;
207 if (snapshot == snapshotrecord->maxSnapShots) {
208 model_print("Out of snapshots\n");
211 snapshotrecord->snapShots[snapshot].firstBackingPage = snapshotrecord->lastBackingPage;
216 /** The rollBack function rollback to the given snapshot identifier.
217 * @param theID is the snapshot identifier to rollback to.
219 void rollBack(snapshot_id theID)
221 #if USE_MPROTECT_SNAPSHOT == 2
222 if (snapshotrecord->lastSnapShot == (theID + 1)) {
223 for (unsigned int page = snapshotrecord->snapShots[theID].firstBackingPage; page < snapshotrecord->lastBackingPage; page++) {
224 memcpy(snapshotrecord->backingRecords[page].basePtrOfPage, &snapshotrecord->backingStore[page], sizeof(snapshot_page_t));
230 HashTable< void *, bool, uintptr_t, 4, model_malloc, model_calloc, model_free> duplicateMap;
231 for (unsigned int region = 0; region < snapshotrecord->lastRegion; region++) {
232 if (mprotect(snapshotrecord->regionsToSnapShot[region].basePtr, snapshotrecord->regionsToSnapShot[region].sizeInPages * sizeof(snapshot_page_t), PROT_READ | PROT_WRITE) == -1) {
234 model_print("Failed to mprotect inside of takeSnapShot\n");
238 for (unsigned int page = snapshotrecord->snapShots[theID].firstBackingPage; page < snapshotrecord->lastBackingPage; page++) {
239 if (!duplicateMap.contains(snapshotrecord->backingRecords[page].basePtrOfPage)) {
240 duplicateMap.put(snapshotrecord->backingRecords[page].basePtrOfPage, true);
241 memcpy(snapshotrecord->backingRecords[page].basePtrOfPage, &snapshotrecord->backingStore[page], sizeof(snapshot_page_t));
244 snapshotrecord->lastSnapShot = theID;
245 snapshotrecord->lastBackingPage = snapshotrecord->snapShots[theID].firstBackingPage;
246 takeSnapshot(); //Make sure current snapshot is still good...All later ones are cleared
249 #else /* !USE_MPROTECT_SNAPSHOT */
251 #include <ucontext.h>
253 #define SHARED_MEMORY_DEFAULT (100 * ((size_t)1 << 20)) // 100mb for the shared memory
254 #define STACK_SIZE_DEFAULT (((size_t)1 << 20) * 20) // 20 mb out of the above 100 mb for my stack
257 void *mSharedMemoryBase;
260 volatile snapshot_id mIDToRollback;
261 ucontext_t mContextToRollback;
262 snapshot_id currSnapShotID;
265 static struct SnapShot *snapshotrecord = NULL;
268 * These variables are necessary because the stack is shared region and
269 * there exists a race between all processes executing the same function.
270 * To avoid the problem above, we require variables allocated in 'safe' regions.
271 * The bug was actually observed with the forkID, these variables below are
272 * used to indicate the various contexts to which to switch to.
274 * @savedSnapshotContext: contains the point to which takesnapshot() call should switch to.
275 * @savedUserSnapshotContext: contains the point to which the process whose snapshotid is equal to the rollbackid should switch to
276 * @snapshotid: it is a running counter for the various forked processes snapshotid. it is incremented and set in a persistently shared record
278 static ucontext_t savedSnapshotContext;
279 static ucontext_t savedUserSnapshotContext;
280 static snapshot_id snapshotid = 0;
282 static void createSharedMemory()
284 //step 1. create shared memory.
285 void *memMapBase = mmap(0, SHARED_MEMORY_DEFAULT + STACK_SIZE_DEFAULT, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANON, -1, 0);
286 if (MAP_FAILED == memMapBase)
289 //Setup snapshot record at top of free region
290 snapshotrecord = (struct SnapShot *)memMapBase;
291 snapshotrecord->mSharedMemoryBase = (void *)((uintptr_t)memMapBase + sizeof(struct SnapShot));
292 snapshotrecord->mStackBase = (void *)((uintptr_t)memMapBase + SHARED_MEMORY_DEFAULT);
293 snapshotrecord->mStackSize = STACK_SIZE_DEFAULT;
294 snapshotrecord->mIDToRollback = -1;
295 snapshotrecord->currSnapShotID = 0;
299 * Create a new mspace pointer for the non-snapshotting (i.e., inter-process
300 * shared) memory region. Only for fork-based snapshotting.
302 * @return The shared memory mspace
304 mspace create_shared_mspace()
307 createSharedMemory();
308 return create_mspace_with_base((void *)(snapshotrecord->mSharedMemoryBase), SHARED_MEMORY_DEFAULT - sizeof(struct SnapShot), 1);
311 void initSnapshotLibrary(unsigned int numbackingpages,
312 unsigned int numsnapshots, unsigned int nummemoryregions,
313 unsigned int numheappages, VoidFuncPtr entryPoint)
316 createSharedMemory();
318 void *base_model_snapshot_space = malloc((numheappages + 1) * PAGESIZE);
319 void *pagealignedbase = PageAlignAddressUpward(base_model_snapshot_space);
320 model_snapshot_space = create_mspace_with_base(pagealignedbase, numheappages * PAGESIZE, 1);
322 //step 2 setup the stack context.
323 ucontext_t newContext;
324 getcontext(&newContext);
325 newContext.uc_stack.ss_sp = snapshotrecord->mStackBase;
326 newContext.uc_stack.ss_size = STACK_SIZE_DEFAULT;
327 makecontext(&newContext, entryPoint, 0);
328 /* switch to a new entryPoint context, on a new stack */
329 swapcontext(&savedSnapshotContext, &newContext);
331 /* switch back here when takesnapshot is called */
333 snapshotid = snapshotrecord->currSnapShotID;
334 /* This bool indicates that the current process's snapshotid is same
335 as the id to which the rollback needs to occur */
337 bool rollback = false;
339 snapshotrecord->currSnapShotID = snapshotid + 1;
343 /* If the rollback bool is set, switch to the context we need to
344 return to during a rollback. */
346 setcontext(&(snapshotrecord->mContextToRollback));
348 /*Child process which is forked as a result of takesnapshot
349 call should switch back to the takesnapshot context*/
350 setcontext(&savedUserSnapshotContext);
356 DEBUG("The process id of child is %d and the process id of this process is %d and snapshot id is %d\n",
357 forkedID, getpid(), snapshotid);
360 retVal = waitpid(forkedID, &status, 0);
361 } while (-1 == retVal && errno == EINTR);
363 if (snapshotrecord->mIDToRollback != snapshotid) {
371 void addMemoryRegionToSnapShot(void *addr, unsigned int numPages)
373 /* not needed for fork-based snapshotting */
376 snapshot_id takeSnapshot()
378 swapcontext(&savedUserSnapshotContext, &savedSnapshotContext);
379 DEBUG("TAKESNAPSHOT RETURN\n");
383 void rollBack(snapshot_id theID)
385 snapshotrecord->mIDToRollback = theID;
386 volatile int sTemp = 0;
387 getcontext(&snapshotrecord->mContextToRollback);
389 * This is used to quit the process on rollback, so that the process
390 * which needs to rollback can quit allowing the process whose
391 * snapshotid matches the rollbackid to switch to this context and
396 DEBUG("Invoked rollback\n");
400 * This fix obviates the need for a finalize call. hence less dependences for model-checker....
402 snapshotrecord->mIDToRollback = -1;
405 #endif /* !USE_MPROTECT_SNAPSHOT */