10 #include "hashtable.h"
18 #if USE_MPROTECT_SNAPSHOT
20 /** PageAlignedAdressUpdate return a page aligned address for the
21 * address being added as a side effect the numBytes are also changed.
23 static void * PageAlignAddressUpward(void *addr)
25 return (void *)((((uintptr_t)addr) + PAGESIZE - 1) & ~(PAGESIZE - 1));
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 /** ReturnPageAlignedAddress returns a page aligned address for the
50 * address being added as a side effect the numBytes are also changed.
52 static void * ReturnPageAlignedAddress(void *addr)
54 return (void *)(((uintptr_t)addr) & ~(PAGESIZE - 1));
57 /* Primary struct for snapshotting system */
58 struct mprot_snapshotter {
59 mprot_snapshotter(unsigned int numbackingpages, unsigned int numsnapshots, unsigned int nummemoryregions);
62 struct MemoryRegion *regionsToSnapShot; //This pointer references an array of memory regions to snapshot
63 snapshot_page_t *backingStore; //This pointer references an array of snapshotpage's that form the backing store
64 void *backingStoreBasePtr; //This pointer references an array of snapshotpage's that form the backing store
65 struct BackingPageRecord *backingRecords; //This pointer references an array of backingpagerecord's (same number of elements as backingstore
66 struct SnapShotRecord *snapShots; //This pointer references the snapshot array
68 unsigned int lastSnapShot; //Stores the next snapshot record we should use
69 unsigned int lastBackingPage; //Stores the next backingpage we should use
70 unsigned int lastRegion; //Stores the next memory region to be used
72 unsigned int maxRegions; //Stores the max number of memory regions we support
73 unsigned int maxBackingPages; //Stores the total number of backing pages
74 unsigned int maxSnapShots; //Stores the total number of snapshots we allow
79 static struct mprot_snapshotter *mprot_snap = NULL;
81 mprot_snapshotter::mprot_snapshotter(unsigned int backing_pages, unsigned int snapshots, unsigned int regions) :
86 maxBackingPages(backing_pages),
87 maxSnapShots(snapshots)
89 regionsToSnapShot = (struct MemoryRegion *)model_malloc(sizeof(struct MemoryRegion) * regions);
90 backingStoreBasePtr = (void *)model_malloc(sizeof(snapshot_page_t) * (backing_pages + 1));
91 //Page align the backingstorepages
92 backingStore = (snapshot_page_t *)PageAlignAddressUpward(backingStoreBasePtr);
93 backingRecords = (struct BackingPageRecord *)model_malloc(sizeof(struct BackingPageRecord) * backing_pages);
94 snapShots = (struct SnapShotRecord *)model_malloc(sizeof(struct SnapShotRecord) * snapshots);
97 mprot_snapshotter::~mprot_snapshotter()
99 model_free(regionsToSnapShot);
100 model_free(backingStoreBasePtr);
101 model_free(backingRecords);
102 model_free(snapShots);
105 /** mprot_handle_pf is the page fault handler for mprotect based snapshotting
108 static void mprot_handle_pf(int sig, siginfo_t *si, void *unused)
110 if (si->si_code == SEGV_MAPERR) {
111 model_print("Segmentation fault at %p\n", si->si_addr);
112 model_print("For debugging, place breakpoint at: %s:%d\n",
114 // print_trace(); // Trace printing may cause dynamic memory allocation
117 void* addr = ReturnPageAlignedAddress(si->si_addr);
119 unsigned int backingpage = mprot_snap->lastBackingPage++; //Could run out of pages...
120 if (backingpage == mprot_snap->maxBackingPages) {
121 model_print("Out of backing pages at %p\n", si->si_addr);
126 memcpy(&(mprot_snap->backingStore[backingpage]), addr, sizeof(snapshot_page_t));
127 //remember where to copy page back to
128 mprot_snap->backingRecords[backingpage].basePtrOfPage = addr;
129 //set protection to read/write
130 if (mprotect(addr, sizeof(snapshot_page_t), PROT_READ | PROT_WRITE)) {
132 // Handle error by quitting?
136 static void mprot_snapshot_init(unsigned int numbackingpages,
137 unsigned int numsnapshots, unsigned int nummemoryregions,
138 unsigned int numheappages)
140 /* Setup a stack for our signal handler.... */
142 ss.ss_sp = PageAlignAddressUpward(model_malloc(SIGSTACKSIZE + PAGESIZE - 1));
143 ss.ss_size = SIGSTACKSIZE;
145 sigaltstack(&ss, NULL);
148 sa.sa_flags = SA_SIGINFO | SA_NODEFER | SA_RESTART | SA_ONSTACK;
149 sigemptyset(&sa.sa_mask);
150 sa.sa_sigaction = mprot_handle_pf;
152 if (sigaction(SIGBUS, &sa, NULL) == -1) {
153 perror("sigaction(SIGBUS)");
157 if (sigaction(SIGSEGV, &sa, NULL) == -1) {
158 perror("sigaction(SIGSEGV)");
162 mprot_snap = new mprot_snapshotter(numbackingpages, numsnapshots, nummemoryregions);
164 // EVIL HACK: We need to make sure that calls into the mprot_handle_pf method don't cause dynamic links
165 // The problem is that we end up protecting state in the dynamic linker...
166 // Solution is to call our signal handler before we start protecting stuff...
169 memset(&si, 0, sizeof(si));
170 si.si_addr = ss.ss_sp;
171 mprot_handle_pf(SIGSEGV, &si, NULL);
172 mprot_snap->lastBackingPage--; //remove the fake page we copied
174 void *basemySpace = model_malloc((numheappages + 1) * PAGESIZE);
175 void *pagealignedbase = PageAlignAddressUpward(basemySpace);
176 user_snapshot_space = create_mspace_with_base(pagealignedbase, numheappages * PAGESIZE, 1);
177 snapshot_add_memory_region(pagealignedbase, numheappages);
179 void *base_model_snapshot_space = model_malloc((numheappages + 1) * PAGESIZE);
180 pagealignedbase = PageAlignAddressUpward(base_model_snapshot_space);
181 model_snapshot_space = create_mspace_with_base(pagealignedbase, numheappages * PAGESIZE, 1);
182 snapshot_add_memory_region(pagealignedbase, numheappages);
185 static void mprot_startExecution(ucontext_t * context, VoidFuncPtr entryPoint) {
186 /* setup the shared-stack context */
187 create_context(context, fork_snap->mStackBase, model_calloc(STACK_SIZE_DEFAULT, 1), STACK_SIZE_DEFAULT, entryPoint);
190 static void mprot_add_to_snapshot(void *addr, unsigned int numPages)
192 unsigned int memoryregion = mprot_snap->lastRegion++;
193 if (memoryregion == mprot_snap->maxRegions) {
194 model_print("Exceeded supported number of memory regions!\n");
198 DEBUG("snapshot region %p-%p (%u page%s)\n",
199 addr, (char *)addr + numPages * PAGESIZE, numPages,
200 numPages > 1 ? "s" : "");
201 mprot_snap->regionsToSnapShot[memoryregion].basePtr = addr;
202 mprot_snap->regionsToSnapShot[memoryregion].sizeInPages = numPages;
205 static snapshot_id mprot_take_snapshot()
207 for (unsigned int region = 0;region < mprot_snap->lastRegion;region++) {
208 if (mprotect(mprot_snap->regionsToSnapShot[region].basePtr, mprot_snap->regionsToSnapShot[region].sizeInPages * sizeof(snapshot_page_t), PROT_READ) == -1) {
210 model_print("Failed to mprotect inside of takeSnapShot\n");
214 unsigned int snapshot = mprot_snap->lastSnapShot++;
215 if (snapshot == mprot_snap->maxSnapShots) {
216 model_print("Out of snapshots\n");
219 mprot_snap->snapShots[snapshot].firstBackingPage = mprot_snap->lastBackingPage;
224 static void mprot_roll_back(snapshot_id theID)
226 #if USE_MPROTECT_SNAPSHOT == 2
227 if (mprot_snap->lastSnapShot == (theID + 1)) {
228 for (unsigned int page = mprot_snap->snapShots[theID].firstBackingPage;page < mprot_snap->lastBackingPage;page++) {
229 memcpy(mprot_snap->backingRecords[page].basePtrOfPage, &mprot_snap->backingStore[page], sizeof(snapshot_page_t));
235 HashTable< void *, bool, uintptr_t, 4, model_malloc, model_calloc, model_free> duplicateMap;
236 for (unsigned int region = 0;region < mprot_snap->lastRegion;region++) {
237 if (mprotect(mprot_snap->regionsToSnapShot[region].basePtr, mprot_snap->regionsToSnapShot[region].sizeInPages * sizeof(snapshot_page_t), PROT_READ | PROT_WRITE) == -1) {
239 model_print("Failed to mprotect inside of takeSnapShot\n");
243 for (unsigned int page = mprot_snap->snapShots[theID].firstBackingPage;page < mprot_snap->lastBackingPage;page++) {
244 if (!duplicateMap.contains(mprot_snap->backingRecords[page].basePtrOfPage)) {
245 duplicateMap.put(mprot_snap->backingRecords[page].basePtrOfPage, true);
246 memcpy(mprot_snap->backingRecords[page].basePtrOfPage, &mprot_snap->backingStore[page], sizeof(snapshot_page_t));
249 mprot_snap->lastSnapShot = theID;
250 mprot_snap->lastBackingPage = mprot_snap->snapShots[theID].firstBackingPage;
251 mprot_take_snapshot(); //Make sure current snapshot is still good...All later ones are cleared
254 #else /* !USE_MPROTECT_SNAPSHOT */
256 #define SHARED_MEMORY_DEFAULT (200 * ((size_t)1 << 20)) // 100mb for the shared memory
257 #define STACK_SIZE_DEFAULT (((size_t)1 << 20) * 20) // 20 mb out of the above 100 mb for my stack
259 struct fork_snapshotter {
260 /** @brief Pointer to the shared (non-snapshot) memory heap base
261 * (NOTE: this has size SHARED_MEMORY_DEFAULT - sizeof(*fork_snap)) */
262 void *mSharedMemoryBase;
264 /** @brief Pointer to the shared (non-snapshot) stack region */
267 /** @brief Size of the shared stack */
271 * @brief Stores the ID that we are attempting to roll back to
273 * Used in inter-process communication so that each process can
274 * determine whether or not to take over execution (w/ matching ID) or
275 * exit (we're rolling back even further). Dubiously marked 'volatile'
276 * to prevent compiler optimizations from messing with the
277 * inter-process behavior.
279 volatile snapshot_id mIDToRollback;
283 /** @brief Inter-process tracking of the next snapshot ID */
284 snapshot_id currSnapShotID;
287 static struct fork_snapshotter *fork_snap = NULL;
288 ucontext_t shared_ctxt;
291 * These variables are necessary because the stack is shared region and
292 * there exists a race between all processes executing the same function.
293 * To avoid the problem above, we require variables allocated in 'safe' regions.
294 * The bug was actually observed with the forkID, these variables below are
295 * used to indicate the various contexts to which to switch to.
297 * @private_ctxt: the context which is internal to the current process. Used
298 * for running the internal snapshot/rollback loop.
299 * @exit_ctxt: a special context used just for exiting from a process (so we
300 * can use swapcontext() instead of setcontext() + hacks)
301 * @snapshotid: it is a running counter for the various forked processes
302 * snapshotid. it is incremented and set in a persistently shared record
304 static ucontext_t private_ctxt;
305 static ucontext_t exit_ctxt;
306 static snapshot_id snapshotid = 0;
309 * @brief Create a new context, with a given stack and entry function
310 * @param ctxt The context structure to fill
311 * @param stack The stack to run the new context in
312 * @param stacksize The size of the stack
313 * @param func The entry point function for the context
315 static void create_context(ucontext_t *ctxt, void *stack, size_t stacksize,
319 ctxt->uc_stack.ss_sp = stack;
320 ctxt->uc_stack.ss_size = stacksize;
321 ctxt->uc_link = NULL;
322 makecontext(ctxt, func, 0);
325 /** @brief An empty function, used for an "empty" context which just exits a
327 static void fork_exit()
332 static void createSharedMemory()
334 //step 1. create shared memory.
335 void *memMapBase = mmap(0, SHARED_MEMORY_DEFAULT + STACK_SIZE_DEFAULT, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANON, -1, 0);
336 if (memMapBase == MAP_FAILED) {
341 //Setup snapshot record at top of free region
342 fork_snap = (struct fork_snapshotter *)memMapBase;
343 fork_snap->mSharedMemoryBase = (void *)((uintptr_t)memMapBase + sizeof(*fork_snap));
344 fork_snap->mStackBase = (void *)((uintptr_t)memMapBase + SHARED_MEMORY_DEFAULT);
345 fork_snap->mStackSize = STACK_SIZE_DEFAULT;
346 fork_snap->mIDToRollback = -1;
347 fork_snap->currSnapShotID = 0;
351 * Create a new mspace pointer for the non-snapshotting (i.e., inter-process
352 * shared) memory region. Only for fork-based snapshotting.
354 * @return The shared memory mspace
356 mspace create_shared_mspace()
359 createSharedMemory();
360 return create_mspace_with_base((void *)(fork_snap->mSharedMemoryBase), SHARED_MEMORY_DEFAULT - sizeof(*fork_snap), 1);
363 static void fork_snapshot_init(unsigned int numbackingpages,
364 unsigned int numsnapshots, unsigned int nummemoryregions,
365 unsigned int numheappages)
368 createSharedMemory();
370 model_snapshot_space = create_mspace(numheappages * PAGESIZE, 1);
373 volatile int modellock = 0;
375 static void fork_loop() {
376 /* switch back here when takesnapshot is called */
377 snapshotid = fork_snap->currSnapShotID;
378 if (model->params.nofork) {
379 setcontext(&shared_ctxt);
385 fork_snap->currSnapShotID = snapshotid + 1;
392 setcontext(&shared_ctxt);
394 DEBUG("parent PID: %d, child PID: %d, snapshot ID: %d\n",
395 getpid(), forkedID, snapshotid);
397 while (waitpid(forkedID, NULL, 0) < 0) {
398 /* waitpid() may be interrupted */
399 if (errno != EINTR) {
405 if (fork_snap->mIDToRollback != snapshotid)
411 static void fork_startExecution(ucontext_t *context, VoidFuncPtr entryPoint) {
412 /* setup an "exiting" context */
413 int exit_stack_size = 256;
414 create_context(&exit_ctxt, snapshot_calloc(exit_stack_size, 1), exit_stack_size, fork_exit);
416 /* setup the system context */
417 create_context(context, fork_snap->mStackBase, STACK_SIZE_DEFAULT, entryPoint);
418 /* switch to a new entryPoint context, on a new stack */
419 create_context(&private_ctxt, snapshot_calloc(STACK_SIZE_DEFAULT, 1), STACK_SIZE_DEFAULT, fork_loop);
422 static snapshot_id fork_take_snapshot() {
423 model_swapcontext(&shared_ctxt, &private_ctxt);
424 DEBUG("TAKESNAPSHOT RETURN\n");
428 static void fork_roll_back(snapshot_id theID)
431 fork_snap->mIDToRollback = theID;
432 model_swapcontext(model->get_system_context(), &exit_ctxt);
433 fork_snap->mIDToRollback = -1;
436 #endif /* !USE_MPROTECT_SNAPSHOT */
439 * @brief Initializes the snapshot system
440 * @param entryPoint the function that should run the program.
442 void snapshot_system_init(unsigned int numbackingpages,
443 unsigned int numsnapshots, unsigned int nummemoryregions,
444 unsigned int numheappages)
446 #if USE_MPROTECT_SNAPSHOT
447 mprot_snapshot_init(numbackingpages, numsnapshots, nummemoryregions, numheappages);
449 fork_snapshot_init(numbackingpages, numsnapshots, nummemoryregions, numheappages);
453 void startExecution(ucontext_t *context, VoidFuncPtr entryPoint)
455 #if USE_MPROTECT_SNAPSHOT
456 mprot_startExecution(context, entryPoint);
458 fork_startExecution(context, entryPoint);
462 /** Assumes that addr is page aligned. */
463 void snapshot_add_memory_region(void *addr, unsigned int numPages)
465 #if USE_MPROTECT_SNAPSHOT
466 mprot_add_to_snapshot(addr, numPages);
468 /* not needed for fork-based snapshotting */
472 /** Takes a snapshot of memory.
473 * @return The snapshot identifier.
475 snapshot_id take_snapshot()
477 #if USE_MPROTECT_SNAPSHOT
478 return mprot_take_snapshot();
480 return fork_take_snapshot();
484 /** Rolls the memory state back to the given snapshot identifier.
485 * @param theID is the snapshot identifier to rollback to.
487 void snapshot_roll_back(snapshot_id theID)
489 #if USE_MPROTECT_SNAPSHOT
490 mprot_roll_back(theID);
492 fork_roll_back(theID);