typos
[model-checker.git] / snapshot.cc
1 #include <inttypes.h>
2 #include <sys/mman.h>
3 #include <unistd.h>
4 #include <signal.h>
5 #include <stdlib.h>
6 #include <string.h>
7 #include <errno.h>
8 #include <sys/wait.h>
9
10 #include "hashtable.h"
11 #include "snapshot.h"
12 #include "mymemory.h"
13 #include "common.h"
14 #include "context.h"
15
16 /** PageAlignedAdressUpdate return a page aligned address for the
17  * address being added as a side effect the numBytes are also changed.
18  */
19 static void * PageAlignAddressUpward(void *addr)
20 {
21         return (void *)((((uintptr_t)addr) + PAGESIZE - 1) & ~(PAGESIZE - 1));
22 }
23
24 #if USE_MPROTECT_SNAPSHOT
25
26 /* Each SnapShotRecord lists the firstbackingpage that must be written to
27  * revert to that snapshot */
28 struct SnapShotRecord {
29         unsigned int firstBackingPage;
30 };
31
32 /** @brief Backing store page */
33 typedef unsigned char snapshot_page_t[PAGESIZE];
34
35 /* List the base address of the corresponding page in the backing store so we
36  * know where to copy it to */
37 struct BackingPageRecord {
38         void *basePtrOfPage;
39 };
40
41 /* Struct for each memory region */
42 struct MemoryRegion {
43         void *basePtr; // base of memory region
44         int sizeInPages; // size of memory region in pages
45 };
46
47 /** ReturnPageAlignedAddress returns a page aligned address for the
48  * address being added as a side effect the numBytes are also changed.
49  */
50 static void * ReturnPageAlignedAddress(void *addr)
51 {
52         return (void *)(((uintptr_t)addr) & ~(PAGESIZE - 1));
53 }
54
55 /* Primary struct for snapshotting system */
56 struct mprot_snapshotter {
57         mprot_snapshotter(unsigned int numbackingpages, unsigned int numsnapshots, unsigned int nummemoryregions);
58         ~mprot_snapshotter();
59
60         struct MemoryRegion *regionsToSnapShot; //This pointer references an array of memory regions to snapshot
61         snapshot_page_t *backingStore; //This pointer references an array of snapshotpage's that form the backing store
62         void *backingStoreBasePtr; //This pointer references an array of snapshotpage's that form the backing store
63         struct BackingPageRecord *backingRecords; //This pointer references an array of backingpagerecord's (same number of elements as backingstore
64         struct SnapShotRecord *snapShots; //This pointer references the snapshot array
65
66         unsigned int lastSnapShot; //Stores the next snapshot record we should use
67         unsigned int lastBackingPage; //Stores the next backingpage we should use
68         unsigned int lastRegion; //Stores the next memory region to be used
69
70         unsigned int maxRegions; //Stores the max number of memory regions we support
71         unsigned int maxBackingPages; //Stores the total number of backing pages
72         unsigned int maxSnapShots; //Stores the total number of snapshots we allow
73
74         MEMALLOC
75 };
76
77 static struct mprot_snapshotter *mprot_snap = NULL;
78
79 mprot_snapshotter::mprot_snapshotter(unsigned int backing_pages, unsigned int snapshots, unsigned int regions) :
80         lastSnapShot(0),
81         lastBackingPage(0),
82         lastRegion(0),
83         maxRegions(regions),
84         maxBackingPages(backing_pages),
85         maxSnapShots(snapshots)
86 {
87         regionsToSnapShot = (struct MemoryRegion *)model_malloc(sizeof(struct MemoryRegion) * regions);
88         backingStoreBasePtr = (void *)model_malloc(sizeof(snapshot_page_t) * (backing_pages + 1));
89         //Page align the backingstorepages
90         backingStore = (snapshot_page_t *)PageAlignAddressUpward(backingStoreBasePtr);
91         backingRecords = (struct BackingPageRecord *)model_malloc(sizeof(struct BackingPageRecord) * backing_pages);
92         snapShots = (struct SnapShotRecord *)model_malloc(sizeof(struct SnapShotRecord) * snapshots);
93 }
94
95 mprot_snapshotter::~mprot_snapshotter()
96 {
97         model_free(regionsToSnapShot);
98         model_free(backingStoreBasePtr);
99         model_free(backingRecords);
100         model_free(snapShots);
101 }
102
103 /** mprot_handle_pf is the page fault handler for mprotect based snapshotting
104  * algorithm.
105  */
106 static void mprot_handle_pf(int sig, siginfo_t *si, void *unused)
107 {
108         if (si->si_code == SEGV_MAPERR) {
109                 model_print("Segmentation fault at %p\n", si->si_addr);
110                 model_print("For debugging, place breakpoint at: %s:%d\n",
111                                 __FILE__, __LINE__);
112                 // print_trace(); // Trace printing may cause dynamic memory allocation
113                 exit(EXIT_FAILURE);
114         }
115         void* addr = ReturnPageAlignedAddress(si->si_addr);
116
117         unsigned int backingpage = mprot_snap->lastBackingPage++; //Could run out of pages...
118         if (backingpage == mprot_snap->maxBackingPages) {
119                 model_print("Out of backing pages at %p\n", si->si_addr);
120                 exit(EXIT_FAILURE);
121         }
122
123         //copy page
124         memcpy(&(mprot_snap->backingStore[backingpage]), addr, sizeof(snapshot_page_t));
125         //remember where to copy page back to
126         mprot_snap->backingRecords[backingpage].basePtrOfPage = addr;
127         //set protection to read/write
128         if (mprotect(addr, sizeof(snapshot_page_t), PROT_READ | PROT_WRITE)) {
129                 perror("mprotect");
130                 // Handle error by quitting?
131         }
132 }
133
134 static void mprot_snapshot_init(unsigned int numbackingpages,
135                 unsigned int numsnapshots, unsigned int nummemoryregions,
136                 unsigned int numheappages, VoidFuncPtr entryPoint)
137 {
138         /* Setup a stack for our signal handler....  */
139         stack_t ss;
140         ss.ss_sp = PageAlignAddressUpward(model_malloc(SIGSTACKSIZE + PAGESIZE - 1));
141         ss.ss_size = SIGSTACKSIZE;
142         ss.ss_flags = 0;
143         sigaltstack(&ss, NULL);
144
145         struct sigaction sa;
146         sa.sa_flags = SA_SIGINFO | SA_NODEFER | SA_RESTART | SA_ONSTACK;
147         sigemptyset(&sa.sa_mask);
148         sa.sa_sigaction = mprot_handle_pf;
149 #ifdef MAC
150         if (sigaction(SIGBUS, &sa, NULL) == -1) {
151                 perror("sigaction(SIGBUS)");
152                 exit(EXIT_FAILURE);
153         }
154 #endif
155         if (sigaction(SIGSEGV, &sa, NULL) == -1) {
156                 perror("sigaction(SIGSEGV)");
157                 exit(EXIT_FAILURE);
158         }
159
160         mprot_snap = new mprot_snapshotter(numbackingpages, numsnapshots, nummemoryregions);
161
162         // EVIL HACK: We need to make sure that calls into the mprot_handle_pf method don't cause dynamic links
163         // The problem is that we end up protecting state in the dynamic linker...
164         // Solution is to call our signal handler before we start protecting stuff...
165
166         siginfo_t si;
167         memset(&si, 0, sizeof(si));
168         si.si_addr = ss.ss_sp;
169         mprot_handle_pf(SIGSEGV, &si, NULL);
170         mprot_snap->lastBackingPage--; //remove the fake page we copied
171
172         void *basemySpace = model_malloc((numheappages + 1) * PAGESIZE);
173         void *pagealignedbase = PageAlignAddressUpward(basemySpace);
174         user_snapshot_space = create_mspace_with_base(pagealignedbase, numheappages * PAGESIZE, 1);
175         snapshot_add_memory_region(pagealignedbase, numheappages);
176
177         void *base_model_snapshot_space = model_malloc((numheappages + 1) * PAGESIZE);
178         pagealignedbase = PageAlignAddressUpward(base_model_snapshot_space);
179         model_snapshot_space = create_mspace_with_base(pagealignedbase, numheappages * PAGESIZE, 1);
180         snapshot_add_memory_region(pagealignedbase, numheappages);
181
182         entryPoint();
183 }
184
185 static void mprot_add_to_snapshot(void *addr, unsigned int numPages)
186 {
187         unsigned int memoryregion = mprot_snap->lastRegion++;
188         if (memoryregion == mprot_snap->maxRegions) {
189                 model_print("Exceeded supported number of memory regions!\n");
190                 exit(EXIT_FAILURE);
191         }
192
193         DEBUG("snapshot region %p-%p (%u page%s)\n",
194                         addr, (char *)addr + numPages * PAGESIZE, numPages,
195                         numPages > 1 ? "s" : "");
196         mprot_snap->regionsToSnapShot[memoryregion].basePtr = addr;
197         mprot_snap->regionsToSnapShot[memoryregion].sizeInPages = numPages;
198 }
199
200 static snapshot_id mprot_take_snapshot()
201 {
202         for (unsigned int region = 0; region < mprot_snap->lastRegion; region++) {
203                 if (mprotect(mprot_snap->regionsToSnapShot[region].basePtr, mprot_snap->regionsToSnapShot[region].sizeInPages * sizeof(snapshot_page_t), PROT_READ) == -1) {
204                         perror("mprotect");
205                         model_print("Failed to mprotect inside of takeSnapShot\n");
206                         exit(EXIT_FAILURE);
207                 }
208         }
209         unsigned int snapshot = mprot_snap->lastSnapShot++;
210         if (snapshot == mprot_snap->maxSnapShots) {
211                 model_print("Out of snapshots\n");
212                 exit(EXIT_FAILURE);
213         }
214         mprot_snap->snapShots[snapshot].firstBackingPage = mprot_snap->lastBackingPage;
215
216         return snapshot;
217 }
218
219 static void mprot_roll_back(snapshot_id theID)
220 {
221 #if USE_MPROTECT_SNAPSHOT == 2
222         if (mprot_snap->lastSnapShot == (theID + 1)) {
223                 for (unsigned int page = mprot_snap->snapShots[theID].firstBackingPage; page < mprot_snap->lastBackingPage; page++) {
224                         memcpy(mprot_snap->backingRecords[page].basePtrOfPage, &mprot_snap->backingStore[page], sizeof(snapshot_page_t));
225                 }
226                 return;
227         }
228 #endif
229
230         HashTable< void *, bool, uintptr_t, 4, model_malloc, model_calloc, model_free> duplicateMap;
231         for (unsigned int region = 0; region < mprot_snap->lastRegion; region++) {
232                 if (mprotect(mprot_snap->regionsToSnapShot[region].basePtr, mprot_snap->regionsToSnapShot[region].sizeInPages * sizeof(snapshot_page_t), PROT_READ | PROT_WRITE) == -1) {
233                         perror("mprotect");
234                         model_print("Failed to mprotect inside of takeSnapShot\n");
235                         exit(EXIT_FAILURE);
236                 }
237         }
238         for (unsigned int page = mprot_snap->snapShots[theID].firstBackingPage; page < mprot_snap->lastBackingPage; page++) {
239                 if (!duplicateMap.contains(mprot_snap->backingRecords[page].basePtrOfPage)) {
240                         duplicateMap.put(mprot_snap->backingRecords[page].basePtrOfPage, true);
241                         memcpy(mprot_snap->backingRecords[page].basePtrOfPage, &mprot_snap->backingStore[page], sizeof(snapshot_page_t));
242                 }
243         }
244         mprot_snap->lastSnapShot = theID;
245         mprot_snap->lastBackingPage = mprot_snap->snapShots[theID].firstBackingPage;
246         mprot_take_snapshot(); //Make sure current snapshot is still good...All later ones are cleared
247 }
248
249 #else /* !USE_MPROTECT_SNAPSHOT */
250
251 #define SHARED_MEMORY_DEFAULT  (100 * ((size_t)1 << 20)) // 100mb for the shared memory
252 #define STACK_SIZE_DEFAULT      (((size_t)1 << 20) * 20)  // 20 mb out of the above 100 mb for my stack
253
254 struct fork_snapshotter {
255         /** @brief Pointer to the shared (non-snapshot) memory heap base
256          * (NOTE: this has size SHARED_MEMORY_DEFAULT - sizeof(*fork_snap)) */
257         void *mSharedMemoryBase;
258
259         /** @brief Pointer to the shared (non-snapshot) stack region */
260         void *mStackBase;
261
262         /** @brief Size of the shared stack */
263         size_t mStackSize;
264
265         /**
266          * @brief Stores the ID that we are attempting to roll back to
267          *
268          * Used in inter-process communication so that each process can
269          * determine whether or not to take over execution (w/ matching ID) or
270          * exit (we're rolling back even further). Dubiously marked 'volatile'
271          * to prevent compiler optimizations from messing with the
272          * inter-process behavior.
273          */
274         volatile snapshot_id mIDToRollback;
275
276         /**
277          * @brief The context for the shared (non-snapshot) stack
278          *
279          * This context is passed between the various processes which represent
280          * various snapshot states. It should be used primarily for the
281          * "client-side" code, not the main snapshot loop.
282          */
283         ucontext_t shared_ctxt;
284
285         /** @brief Inter-process tracking of the next snapshot ID */
286         snapshot_id currSnapShotID;
287 };
288
289 static struct fork_snapshotter *fork_snap = NULL;
290
291 /** @statics
292 *   These variables are necessary because the stack is shared region and
293 *   there exists a race between all processes executing the same function.
294 *   To avoid the problem above, we require variables allocated in 'safe' regions.
295 *   The bug was actually observed with the forkID, these variables below are
296 *   used to indicate the various contexts to which to switch to.
297 *
298 *   @private_ctxt: the context which is internal to the current process. Used
299 *   for running the internal snapshot/rollback loop.
300 *   @exit_ctxt: a special context used just for exiting from a process (so we
301 *   can use swapcontext() instead of setcontext() + hacks)
302 *   @snapshotid: it is a running counter for the various forked processes
303 *   snapshotid. it is incremented and set in a persistently shared record
304 */
305 static ucontext_t private_ctxt;
306 static ucontext_t exit_ctxt;
307 static snapshot_id snapshotid = 0;
308
309 /**
310  * @brief Create a new context, with a given stack and entry function
311  * @param ctxt The context structure to fill
312  * @param stack The stack to run the new context in
313  * @param stacksize The size of the stack
314  * @param func The entry point function for the context
315  */
316 static void create_context(ucontext_t *ctxt, void *stack, size_t stacksize,
317                 void (*func)(void))
318 {
319         getcontext(ctxt);
320         ctxt->uc_stack.ss_sp = stack;
321         ctxt->uc_stack.ss_size = stacksize;
322         makecontext(ctxt, func, 0);
323 }
324
325 /** @brief An empty function, used for an "empty" context which just exits a
326  *  process */
327 static void fork_exit()
328 {
329         /* Intentionally empty */
330 }
331
332 static void createSharedMemory()
333 {
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) {
337                 perror("mmap");
338                 exit(EXIT_FAILURE);
339         }
340
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;
348 }
349
350 /**
351  * Create a new mspace pointer for the non-snapshotting (i.e., inter-process
352  * shared) memory region. Only for fork-based snapshotting.
353  *
354  * @return The shared memory mspace
355  */
356 mspace create_shared_mspace()
357 {
358         if (!fork_snap)
359                 createSharedMemory();
360         return create_mspace_with_base((void *)(fork_snap->mSharedMemoryBase), SHARED_MEMORY_DEFAULT - sizeof(*fork_snap), 1);
361 }
362
363 static void fork_snapshot_init(unsigned int numbackingpages,
364                 unsigned int numsnapshots, unsigned int nummemoryregions,
365                 unsigned int numheappages, VoidFuncPtr entryPoint)
366 {
367         if (!fork_snap)
368                 createSharedMemory();
369
370         void *base_model_snapshot_space = malloc((numheappages + 1) * PAGESIZE);
371         void *pagealignedbase = PageAlignAddressUpward(base_model_snapshot_space);
372         model_snapshot_space = create_mspace_with_base(pagealignedbase, numheappages * PAGESIZE, 1);
373
374         /* setup an "exiting" context */
375         char stack[128];
376         create_context(&exit_ctxt, stack, sizeof(stack), fork_exit);
377
378         /* setup the shared-stack context */
379         create_context(&fork_snap->shared_ctxt, fork_snap->mStackBase,
380                         STACK_SIZE_DEFAULT, entryPoint);
381         /* switch to a new entryPoint context, on a new stack */
382         model_swapcontext(&private_ctxt, &fork_snap->shared_ctxt);
383
384         /* switch back here when takesnapshot is called */
385         snapshotid = fork_snap->currSnapShotID;
386
387         while (true) {
388                 pid_t forkedID;
389                 fork_snap->currSnapShotID = snapshotid + 1;
390                 forkedID = fork();
391
392                 if (0 == forkedID) {
393                         setcontext(&fork_snap->shared_ctxt);
394                 } else {
395                         DEBUG("parent PID: %d, child PID: %d, snapshot ID: %d\n",
396                                 getpid(), forkedID, snapshotid);
397
398                         while (waitpid(forkedID, NULL, 0) < 0) {
399                                 /* waitpid() may be interrupted */
400                                 if (errno != EINTR) {
401                                         perror("waitpid");
402                                         exit(EXIT_FAILURE);
403                                 }
404                         }
405
406                         if (fork_snap->mIDToRollback != snapshotid)
407                                 exit(EXIT_SUCCESS);
408                 }
409         }
410 }
411
412 static snapshot_id fork_take_snapshot()
413 {
414         model_swapcontext(&fork_snap->shared_ctxt, &private_ctxt);
415         DEBUG("TAKESNAPSHOT RETURN\n");
416         return snapshotid;
417 }
418
419 static void fork_roll_back(snapshot_id theID)
420 {
421         DEBUG("Rollback\n");
422         fork_snap->mIDToRollback = theID;
423         model_swapcontext(&fork_snap->shared_ctxt, &exit_ctxt);
424         fork_snap->mIDToRollback = -1;
425 }
426
427 #endif /* !USE_MPROTECT_SNAPSHOT */
428
429 /**
430  * @brief Initializes the snapshot system
431  * @param entryPoint the function that should run the program.
432  */
433 void snapshot_system_init(unsigned int numbackingpages,
434                 unsigned int numsnapshots, unsigned int nummemoryregions,
435                 unsigned int numheappages, VoidFuncPtr entryPoint)
436 {
437 #if USE_MPROTECT_SNAPSHOT
438         mprot_snapshot_init(numbackingpages, numsnapshots, nummemoryregions, numheappages, entryPoint);
439 #else
440         fork_snapshot_init(numbackingpages, numsnapshots, nummemoryregions, numheappages, entryPoint);
441 #endif
442 }
443
444 /** Assumes that addr is page aligned. */
445 void snapshot_add_memory_region(void *addr, unsigned int numPages)
446 {
447 #if USE_MPROTECT_SNAPSHOT
448         mprot_add_to_snapshot(addr, numPages);
449 #else
450         /* not needed for fork-based snapshotting */
451 #endif
452 }
453
454 /** Takes a snapshot of memory.
455  * @return The snapshot identifier.
456  */
457 snapshot_id take_snapshot()
458 {
459 #if USE_MPROTECT_SNAPSHOT
460         return mprot_take_snapshot();
461 #else
462         return fork_take_snapshot();
463 #endif
464 }
465
466 /** Rolls the memory state back to the given snapshot identifier.
467  *  @param theID is the snapshot identifier to rollback to.
468  */
469 void snapshot_roll_back(snapshot_id theID)
470 {
471 #if USE_MPROTECT_SNAPSHOT
472         mprot_roll_back(theID);
473 #else
474         fork_roll_back(theID);
475 #endif
476 }