10 #include "hashtable.h"
17 /** PageAlignedAdressUpdate return a page aligned address for the
18 * address being added as a side effect the numBytes are also changed.
20 static void * PageAlignAddressUpward(void *addr)
22 return (void *)((((uintptr_t)addr) + PAGESIZE - 1) & ~(PAGESIZE - 1));
25 #if USE_MPROTECT_SNAPSHOT
27 /* Each SnapShotRecord lists the firstbackingpage that must be written to
28 * revert to that snapshot */
29 struct SnapShotRecord {
30 unsigned int firstBackingPage;
33 /** @brief Backing store page */
34 typedef unsigned char snapshot_page_t[PAGESIZE];
36 /* List the base address of the corresponding page in the backing store so we
37 * know where to copy it to */
38 struct BackingPageRecord {
42 /* Struct for each memory region */
44 void *basePtr; // base of memory region
45 int sizeInPages; // size of memory region in pages
48 /** ReturnPageAlignedAddress returns a page aligned address for the
49 * address being added as a side effect the numBytes are also changed.
51 static void * ReturnPageAlignedAddress(void *addr)
53 return (void *)(((uintptr_t)addr) & ~(PAGESIZE - 1));
56 /* Primary struct for snapshotting system */
57 struct mprot_snapshotter {
58 mprot_snapshotter(unsigned int numbackingpages, unsigned int numsnapshots, unsigned int nummemoryregions);
61 struct MemoryRegion *regionsToSnapShot; //This pointer references an array of memory regions to snapshot
62 snapshot_page_t *backingStore; //This pointer references an array of snapshotpage's that form the backing store
63 void *backingStoreBasePtr; //This pointer references an array of snapshotpage's that form the backing store
64 struct BackingPageRecord *backingRecords; //This pointer references an array of backingpagerecord's (same number of elements as backingstore
65 struct SnapShotRecord *snapShots; //This pointer references the snapshot array
67 unsigned int lastSnapShot; //Stores the next snapshot record we should use
68 unsigned int lastBackingPage; //Stores the next backingpage we should use
69 unsigned int lastRegion; //Stores the next memory region to be used
71 unsigned int maxRegions; //Stores the max number of memory regions we support
72 unsigned int maxBackingPages; //Stores the total number of backing pages
73 unsigned int maxSnapShots; //Stores the total number of snapshots we allow
78 static struct mprot_snapshotter *mprot_snap = NULL;
80 mprot_snapshotter::mprot_snapshotter(unsigned int backing_pages, unsigned int snapshots, unsigned int regions) :
85 maxBackingPages(backing_pages),
86 maxSnapShots(snapshots)
88 regionsToSnapShot = (struct MemoryRegion *)model_malloc(sizeof(struct MemoryRegion) * regions);
89 backingStoreBasePtr = (void *)model_malloc(sizeof(snapshot_page_t) * (backing_pages + 1));
90 //Page align the backingstorepages
91 backingStore = (snapshot_page_t *)PageAlignAddressUpward(backingStoreBasePtr);
92 backingRecords = (struct BackingPageRecord *)model_malloc(sizeof(struct BackingPageRecord) * backing_pages);
93 snapShots = (struct SnapShotRecord *)model_malloc(sizeof(struct SnapShotRecord) * snapshots);
96 mprot_snapshotter::~mprot_snapshotter()
98 model_free(regionsToSnapShot);
99 model_free(backingStoreBasePtr);
100 model_free(backingRecords);
101 model_free(snapShots);
104 /** mprot_handle_pf is the page fault handler for mprotect based snapshotting
107 static void mprot_handle_pf(int sig, siginfo_t *si, void *unused)
109 if (si->si_code == SEGV_MAPERR) {
110 model_print("Segmentation fault at %p\n", si->si_addr);
111 model_print("For debugging, place breakpoint at: %s:%d\n",
113 // print_trace(); // Trace printing may cause dynamic memory allocation
116 void* addr = ReturnPageAlignedAddress(si->si_addr);
118 unsigned int backingpage = mprot_snap->lastBackingPage++; //Could run out of pages...
119 if (backingpage == mprot_snap->maxBackingPages) {
120 model_print("Out of backing pages at %p\n", si->si_addr);
125 memcpy(&(mprot_snap->backingStore[backingpage]), addr, sizeof(snapshot_page_t));
126 //remember where to copy page back to
127 mprot_snap->backingRecords[backingpage].basePtrOfPage = addr;
128 //set protection to read/write
129 if (mprotect(addr, sizeof(snapshot_page_t), PROT_READ | PROT_WRITE)) {
131 // Handle error by quitting?
135 static void mprot_snapshot_init(unsigned int numbackingpages,
136 unsigned int numsnapshots, unsigned int nummemoryregions,
137 unsigned int numheappages)
139 /* Setup a stack for our signal handler.... */
141 ss.ss_sp = PageAlignAddressUpward(model_malloc(SIGSTACKSIZE + PAGESIZE - 1));
142 ss.ss_size = SIGSTACKSIZE;
144 sigaltstack(&ss, NULL);
147 sa.sa_flags = SA_SIGINFO | SA_NODEFER | SA_RESTART | SA_ONSTACK;
148 sigemptyset(&sa.sa_mask);
149 sa.sa_sigaction = mprot_handle_pf;
151 if (sigaction(SIGBUS, &sa, NULL) == -1) {
152 perror("sigaction(SIGBUS)");
156 if (sigaction(SIGSEGV, &sa, NULL) == -1) {
157 perror("sigaction(SIGSEGV)");
161 mprot_snap = new mprot_snapshotter(numbackingpages, numsnapshots, nummemoryregions);
163 // EVIL HACK: We need to make sure that calls into the mprot_handle_pf method don't cause dynamic links
164 // The problem is that we end up protecting state in the dynamic linker...
165 // Solution is to call our signal handler before we start protecting stuff...
168 memset(&si, 0, sizeof(si));
169 si.si_addr = ss.ss_sp;
170 mprot_handle_pf(SIGSEGV, &si, NULL);
171 mprot_snap->lastBackingPage--; //remove the fake page we copied
173 void *basemySpace = model_malloc((numheappages + 1) * PAGESIZE);
174 void *pagealignedbase = PageAlignAddressUpward(basemySpace);
175 user_snapshot_space = create_mspace_with_base(pagealignedbase, numheappages * PAGESIZE, 1);
176 snapshot_add_memory_region(pagealignedbase, numheappages);
178 void *base_model_snapshot_space = model_malloc((numheappages + 1) * PAGESIZE);
179 pagealignedbase = PageAlignAddressUpward(base_model_snapshot_space);
180 model_snapshot_space = create_mspace_with_base(pagealignedbase, numheappages * PAGESIZE, 1);
181 snapshot_add_memory_region(pagealignedbase, numheappages);
184 static void mprot_startExecution(ucontext_t * context, VoidFuncPtr entryPoint) {
185 /* setup the shared-stack context */
186 create_context(context, fork_snap->mStackBase, model_calloc(STACK_SIZE_DEFAULT, 1), STACK_SIZE_DEFAULT, entryPoint);
189 static void mprot_add_to_snapshot(void *addr, unsigned int numPages)
191 unsigned int memoryregion = mprot_snap->lastRegion++;
192 if (memoryregion == mprot_snap->maxRegions) {
193 model_print("Exceeded supported number of memory regions!\n");
197 DEBUG("snapshot region %p-%p (%u page%s)\n",
198 addr, (char *)addr + numPages * PAGESIZE, numPages,
199 numPages > 1 ? "s" : "");
200 mprot_snap->regionsToSnapShot[memoryregion].basePtr = addr;
201 mprot_snap->regionsToSnapShot[memoryregion].sizeInPages = numPages;
204 static snapshot_id mprot_take_snapshot()
206 for (unsigned int region = 0;region < mprot_snap->lastRegion;region++) {
207 if (mprotect(mprot_snap->regionsToSnapShot[region].basePtr, mprot_snap->regionsToSnapShot[region].sizeInPages * sizeof(snapshot_page_t), PROT_READ) == -1) {
209 model_print("Failed to mprotect inside of takeSnapShot\n");
213 unsigned int snapshot = mprot_snap->lastSnapShot++;
214 if (snapshot == mprot_snap->maxSnapShots) {
215 model_print("Out of snapshots\n");
218 mprot_snap->snapShots[snapshot].firstBackingPage = mprot_snap->lastBackingPage;
223 static void mprot_roll_back(snapshot_id theID)
225 #if USE_MPROTECT_SNAPSHOT == 2
226 if (mprot_snap->lastSnapShot == (theID + 1)) {
227 for (unsigned int page = mprot_snap->snapShots[theID].firstBackingPage;page < mprot_snap->lastBackingPage;page++) {
228 memcpy(mprot_snap->backingRecords[page].basePtrOfPage, &mprot_snap->backingStore[page], sizeof(snapshot_page_t));
234 HashTable< void *, bool, uintptr_t, 4, model_malloc, model_calloc, model_free> duplicateMap;
235 for (unsigned int region = 0;region < mprot_snap->lastRegion;region++) {
236 if (mprotect(mprot_snap->regionsToSnapShot[region].basePtr, mprot_snap->regionsToSnapShot[region].sizeInPages * sizeof(snapshot_page_t), PROT_READ | PROT_WRITE) == -1) {
238 model_print("Failed to mprotect inside of takeSnapShot\n");
242 for (unsigned int page = mprot_snap->snapShots[theID].firstBackingPage;page < mprot_snap->lastBackingPage;page++) {
243 if (!duplicateMap.contains(mprot_snap->backingRecords[page].basePtrOfPage)) {
244 duplicateMap.put(mprot_snap->backingRecords[page].basePtrOfPage, true);
245 memcpy(mprot_snap->backingRecords[page].basePtrOfPage, &mprot_snap->backingStore[page], sizeof(snapshot_page_t));
248 mprot_snap->lastSnapShot = theID;
249 mprot_snap->lastBackingPage = mprot_snap->snapShots[theID].firstBackingPage;
250 mprot_take_snapshot(); //Make sure current snapshot is still good...All later ones are cleared
253 #else /* !USE_MPROTECT_SNAPSHOT */
255 #define SHARED_MEMORY_DEFAULT (200 * ((size_t)1 << 20)) // 100mb for the shared memory
256 #define STACK_SIZE_DEFAULT (((size_t)1 << 20) * 20) // 20 mb out of the above 100 mb for my stack
258 struct fork_snapshotter {
259 /** @brief Pointer to the shared (non-snapshot) memory heap base
260 * (NOTE: this has size SHARED_MEMORY_DEFAULT - sizeof(*fork_snap)) */
261 void *mSharedMemoryBase;
263 /** @brief Pointer to the shared (non-snapshot) stack region */
266 /** @brief Size of the shared stack */
270 * @brief Stores the ID that we are attempting to roll back to
272 * Used in inter-process communication so that each process can
273 * determine whether or not to take over execution (w/ matching ID) or
274 * exit (we're rolling back even further). Dubiously marked 'volatile'
275 * to prevent compiler optimizations from messing with the
276 * inter-process behavior.
278 volatile snapshot_id mIDToRollback;
281 * @brief The context for the shared (non-snapshot) stack
283 * This context is passed between the various processes which represent
284 * various snapshot states. It should be used primarily for the
285 * "client-side" code, not the main snapshot loop.
287 ucontext_t shared_ctxt;
289 /** @brief Inter-process tracking of the next snapshot ID */
290 snapshot_id currSnapShotID;
293 static struct fork_snapshotter *fork_snap = NULL;
296 * These variables are necessary because the stack is shared region and
297 * there exists a race between all processes executing the same function.
298 * To avoid the problem above, we require variables allocated in 'safe' regions.
299 * The bug was actually observed with the forkID, these variables below are
300 * used to indicate the various contexts to which to switch to.
302 * @private_ctxt: the context which is internal to the current process. Used
303 * for running the internal snapshot/rollback loop.
304 * @exit_ctxt: a special context used just for exiting from a process (so we
305 * can use swapcontext() instead of setcontext() + hacks)
306 * @snapshotid: it is a running counter for the various forked processes
307 * snapshotid. it is incremented and set in a persistently shared record
309 static ucontext_t private_ctxt;
310 static ucontext_t exit_ctxt;
311 static snapshot_id snapshotid = 0;
314 * @brief Create a new context, with a given stack and entry function
315 * @param ctxt The context structure to fill
316 * @param stack The stack to run the new context in
317 * @param stacksize The size of the stack
318 * @param func The entry point function for the context
320 static void create_context(ucontext_t *ctxt, void *stack, size_t stacksize,
324 ctxt->uc_stack.ss_sp = stack;
325 ctxt->uc_stack.ss_size = stacksize;
326 ctxt->uc_link = NULL;
327 makecontext(ctxt, func, 0);
330 /** @brief An empty function, used for an "empty" context which just exits a
332 static void fork_exit()
337 static void createSharedMemory()
339 //step 1. create shared memory.
340 void *memMapBase = mmap(0, SHARED_MEMORY_DEFAULT + STACK_SIZE_DEFAULT, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANON, -1, 0);
341 if (memMapBase == MAP_FAILED) {
346 //Setup snapshot record at top of free region
347 fork_snap = (struct fork_snapshotter *)memMapBase;
348 fork_snap->mSharedMemoryBase = (void *)((uintptr_t)memMapBase + sizeof(*fork_snap));
349 fork_snap->mStackBase = (void *)((uintptr_t)memMapBase + SHARED_MEMORY_DEFAULT);
350 fork_snap->mStackSize = STACK_SIZE_DEFAULT;
351 fork_snap->mIDToRollback = -1;
352 fork_snap->currSnapShotID = 0;
356 * Create a new mspace pointer for the non-snapshotting (i.e., inter-process
357 * shared) memory region. Only for fork-based snapshotting.
359 * @return The shared memory mspace
361 mspace create_shared_mspace()
364 createSharedMemory();
365 return create_mspace_with_base((void *)(fork_snap->mSharedMemoryBase), SHARED_MEMORY_DEFAULT - sizeof(*fork_snap), 1);
368 static void fork_snapshot_init(unsigned int numbackingpages,
369 unsigned int numsnapshots, unsigned int nummemoryregions,
370 unsigned int numheappages)
373 createSharedMemory();
375 model_snapshot_space = create_mspace(numheappages * PAGESIZE, 1);
378 volatile int forklock = 0;
380 static void fork_loop() {
381 /* switch back here when takesnapshot is called */
382 snapshotid = fork_snap->currSnapShotID;
383 if (model->params.nofork) {
384 setcontext(&fork_snap->shared_ctxt);
390 fork_snap->currSnapShotID = snapshotid + 1;
397 setcontext(&fork_snap->shared_ctxt);
399 DEBUG("parent PID: %d, child PID: %d, snapshot ID: %d\n",
400 getpid(), forkedID, snapshotid);
402 while (waitpid(forkedID, NULL, 0) < 0) {
403 /* waitpid() may be interrupted */
404 if (errno != EINTR) {
410 if (fork_snap->mIDToRollback != snapshotid)
416 static void fork_startExecution(ucontext_t *context, VoidFuncPtr entryPoint) {
417 /* setup an "exiting" context */
419 create_context(&exit_ctxt, stack, sizeof(stack), fork_exit);
421 /* setup the system context */
422 create_context(context, fork_snap->mStackBase, STACK_SIZE_DEFAULT, entryPoint);
423 /* switch to a new entryPoint context, on a new stack */
424 create_context(&private_ctxt, snapshot_calloc(STACK_SIZE_DEFAULT, 1), STACK_SIZE_DEFAULT, fork_loop);
427 static snapshot_id fork_take_snapshot() {
428 model_swapcontext(&fork_snap->shared_ctxt, &private_ctxt);
429 DEBUG("TAKESNAPSHOT RETURN\n");
433 static void fork_roll_back(snapshot_id theID)
436 fork_snap->mIDToRollback = theID;
437 model_swapcontext(&fork_snap->shared_ctxt, &exit_ctxt);
438 fork_snap->mIDToRollback = -1;
441 #endif /* !USE_MPROTECT_SNAPSHOT */
444 * @brief Initializes the snapshot system
445 * @param entryPoint the function that should run the program.
447 void snapshot_system_init(unsigned int numbackingpages,
448 unsigned int numsnapshots, unsigned int nummemoryregions,
449 unsigned int numheappages)
451 #if USE_MPROTECT_SNAPSHOT
452 mprot_snapshot_init(numbackingpages, numsnapshots, nummemoryregions, numheappages);
454 fork_snapshot_init(numbackingpages, numsnapshots, nummemoryregions, numheappages);
458 void startExecution(ucontext_t *context, VoidFuncPtr entryPoint)
460 #if USE_MPROTECT_SNAPSHOT
461 mprot_startExecution(context, entryPoint);
463 fork_startExecution(context, entryPoint);
467 /** Assumes that addr is page aligned. */
468 void snapshot_add_memory_region(void *addr, unsigned int numPages)
470 #if USE_MPROTECT_SNAPSHOT
471 mprot_add_to_snapshot(addr, numPages);
473 /* not needed for fork-based snapshotting */
477 /** Takes a snapshot of memory.
478 * @return The snapshot identifier.
480 snapshot_id take_snapshot()
482 #if USE_MPROTECT_SNAPSHOT
483 return mprot_take_snapshot();
485 return fork_take_snapshot();
489 /** Rolls the memory state back to the given snapshot identifier.
490 * @param theID is the snapshot identifier to rollback to.
492 void snapshot_roll_back(snapshot_id theID)
494 #if USE_MPROTECT_SNAPSHOT
495 mprot_roll_back(theID);
497 fork_roll_back(theID);