model: we only resolve one promise at a time
[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 #include <ucontext.h>
10
11 #include "hashtable.h"
12 #include "snapshot.h"
13 #include "mymemory.h"
14 #include "common.h"
15
16 #define FAILURE(mesg) { model_print("failed in the API: %s with errno relative message: %s\n", mesg, strerror(errno)); exit(EXIT_FAILURE); }
17
18 /** PageAlignedAdressUpdate return a page aligned address for the
19  * address being added as a side effect the numBytes are also changed.
20  */
21 static void * PageAlignAddressUpward(void *addr)
22 {
23         return (void *)((((uintptr_t)addr) + PAGESIZE - 1) & ~(PAGESIZE - 1));
24 }
25
26 #if USE_MPROTECT_SNAPSHOT
27
28 /* Each SnapShotRecord lists the firstbackingpage that must be written to
29  * revert to that snapshot */
30 struct SnapShotRecord {
31         unsigned int firstBackingPage;
32 };
33
34 /** @brief Backing store page */
35 typedef unsigned char snapshot_page_t[PAGESIZE];
36
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 {
40         void *basePtrOfPage;
41 };
42
43 /* Struct for each memory region */
44 struct MemoryRegion {
45         void *basePtr; // base of memory region
46         int sizeInPages; // size of memory region in pages
47 };
48
49 /** ReturnPageAlignedAddress returns a page aligned address for the
50  * address being added as a side effect the numBytes are also changed.
51  */
52 static void * ReturnPageAlignedAddress(void *addr)
53 {
54         return (void *)(((uintptr_t)addr) & ~(PAGESIZE - 1));
55 }
56
57 /* Primary struct for snapshotting system */
58 struct mprot_snapshotter {
59         mprot_snapshotter(unsigned int numbackingpages, unsigned int numsnapshots, unsigned int nummemoryregions);
60         ~mprot_snapshotter();
61
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
67
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
71
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
75
76         MEMALLOC
77 };
78
79 static struct mprot_snapshotter *mprot_snap = NULL;
80
81 mprot_snapshotter::mprot_snapshotter(unsigned int backing_pages, unsigned int snapshots, unsigned int regions) :
82         lastSnapShot(0),
83         lastBackingPage(0),
84         lastRegion(0),
85         maxRegions(regions),
86         maxBackingPages(backing_pages),
87         maxSnapShots(snapshots)
88 {
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);
95 }
96
97 mprot_snapshotter::~mprot_snapshotter()
98 {
99         model_free(regionsToSnapShot);
100         model_free(backingStoreBasePtr);
101         model_free(backingRecords);
102         model_free(snapShots);
103 }
104
105 /** mprot_handle_pf is the page fault handler for mprotect based snapshotting
106  * algorithm.
107  */
108 static void mprot_handle_pf(int sig, siginfo_t *si, void *unused)
109 {
110         if (si->si_code == SEGV_MAPERR) {
111                 model_print("Real Fault at %p\n", si->si_addr);
112                 print_trace();
113                 model_print("For debugging, place breakpoint at: %s:%d\n",
114                                 __FILE__, __LINE__);
115                 exit(EXIT_FAILURE);
116         }
117         void* addr = ReturnPageAlignedAddress(si->si_addr);
118
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);
122                 exit(EXIT_FAILURE);
123         }
124
125         //copy page
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)) {
131                 perror("mprotect");
132                 // Handle error by quitting?
133         }
134 }
135
136 static void mprot_snapshot_init(unsigned int numbackingpages,
137                 unsigned int numsnapshots, unsigned int nummemoryregions,
138                 unsigned int numheappages, VoidFuncPtr entryPoint)
139 {
140         /* Setup a stack for our signal handler....  */
141         stack_t ss;
142         ss.ss_sp = PageAlignAddressUpward(model_malloc(SIGSTACKSIZE + PAGESIZE - 1));
143         ss.ss_size = SIGSTACKSIZE;
144         ss.ss_flags = 0;
145         sigaltstack(&ss, NULL);
146
147         struct sigaction sa;
148         sa.sa_flags = SA_SIGINFO | SA_NODEFER | SA_RESTART | SA_ONSTACK;
149         sigemptyset(&sa.sa_mask);
150         sa.sa_sigaction = mprot_handle_pf;
151 #ifdef MAC
152         if (sigaction(SIGBUS, &sa, NULL) == -1) {
153                 model_print("SIGACTION CANNOT BE INSTALLED\n");
154                 exit(EXIT_FAILURE);
155         }
156 #endif
157         if (sigaction(SIGSEGV, &sa, NULL) == -1) {
158                 model_print("SIGACTION CANNOT BE INSTALLED\n");
159                 exit(EXIT_FAILURE);
160         }
161
162         mprot_snap = new mprot_snapshotter(numbackingpages, numsnapshots, nummemoryregions);
163
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...
167
168         siginfo_t si;
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
173
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);
178
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);
183
184         entryPoint();
185 }
186
187 static void mprot_add_to_snapshot(void *addr, unsigned int numPages)
188 {
189         unsigned int memoryregion = mprot_snap->lastRegion++;
190         if (memoryregion == mprot_snap->maxRegions) {
191                 model_print("Exceeded supported number of memory regions!\n");
192                 exit(EXIT_FAILURE);
193         }
194
195         mprot_snap->regionsToSnapShot[memoryregion].basePtr = addr;
196         mprot_snap->regionsToSnapShot[memoryregion].sizeInPages = numPages;
197 }
198
199 static snapshot_id mprot_take_snapshot()
200 {
201         for (unsigned int region = 0; region < mprot_snap->lastRegion; region++) {
202                 if (mprotect(mprot_snap->regionsToSnapShot[region].basePtr, mprot_snap->regionsToSnapShot[region].sizeInPages * sizeof(snapshot_page_t), PROT_READ) == -1) {
203                         perror("mprotect");
204                         model_print("Failed to mprotect inside of takeSnapShot\n");
205                         exit(EXIT_FAILURE);
206                 }
207         }
208         unsigned int snapshot = mprot_snap->lastSnapShot++;
209         if (snapshot == mprot_snap->maxSnapShots) {
210                 model_print("Out of snapshots\n");
211                 exit(EXIT_FAILURE);
212         }
213         mprot_snap->snapShots[snapshot].firstBackingPage = mprot_snap->lastBackingPage;
214
215         return snapshot;
216 }
217
218 static void mprot_roll_back(snapshot_id theID)
219 {
220 #if USE_MPROTECT_SNAPSHOT == 2
221         if (mprot_snap->lastSnapShot == (theID + 1)) {
222                 for (unsigned int page = mprot_snap->snapShots[theID].firstBackingPage; page < mprot_snap->lastBackingPage; page++) {
223                         memcpy(mprot_snap->backingRecords[page].basePtrOfPage, &mprot_snap->backingStore[page], sizeof(snapshot_page_t));
224                 }
225                 return;
226         }
227 #endif
228
229         HashTable< void *, bool, uintptr_t, 4, model_malloc, model_calloc, model_free> duplicateMap;
230         for (unsigned int region = 0; region < mprot_snap->lastRegion; region++) {
231                 if (mprotect(mprot_snap->regionsToSnapShot[region].basePtr, mprot_snap->regionsToSnapShot[region].sizeInPages * sizeof(snapshot_page_t), PROT_READ | PROT_WRITE) == -1) {
232                         perror("mprotect");
233                         model_print("Failed to mprotect inside of takeSnapShot\n");
234                         exit(EXIT_FAILURE);
235                 }
236         }
237         for (unsigned int page = mprot_snap->snapShots[theID].firstBackingPage; page < mprot_snap->lastBackingPage; page++) {
238                 if (!duplicateMap.contains(mprot_snap->backingRecords[page].basePtrOfPage)) {
239                         duplicateMap.put(mprot_snap->backingRecords[page].basePtrOfPage, true);
240                         memcpy(mprot_snap->backingRecords[page].basePtrOfPage, &mprot_snap->backingStore[page], sizeof(snapshot_page_t));
241                 }
242         }
243         mprot_snap->lastSnapShot = theID;
244         mprot_snap->lastBackingPage = mprot_snap->snapShots[theID].firstBackingPage;
245         mprot_take_snapshot(); //Make sure current snapshot is still good...All later ones are cleared
246 }
247
248 #else /* !USE_MPROTECT_SNAPSHOT */
249
250 #include <ucontext.h>
251
252 #define SHARED_MEMORY_DEFAULT  (100 * ((size_t)1 << 20)) // 100mb for the shared memory
253 #define STACK_SIZE_DEFAULT      (((size_t)1 << 20) * 20)  // 20 mb out of the above 100 mb for my stack
254
255 struct fork_snapshotter {
256         void *mSharedMemoryBase;
257         void *mStackBase;
258         size_t mStackSize;
259         volatile snapshot_id mIDToRollback;
260         ucontext_t mContextToRollback;
261         snapshot_id currSnapShotID;
262 };
263
264 static struct fork_snapshotter *fork_snap = NULL;
265
266 /** @statics
267 *   These variables are necessary because the stack is shared region and
268 *   there exists a race between all processes executing the same function.
269 *   To avoid the problem above, we require variables allocated in 'safe' regions.
270 *   The bug was actually observed with the forkID, these variables below are
271 *   used to indicate the various contexts to which to switch to.
272 *
273 *   @savedSnapshotContext: contains the point to which takesnapshot() call should switch to.
274 *   @savedUserSnapshotContext: contains the point to which the process whose snapshotid is equal to the rollbackid should switch to
275 *   @snapshotid: it is a running counter for the various forked processes snapshotid. it is incremented and set in a persistently shared record
276 */
277 static ucontext_t savedSnapshotContext;
278 static ucontext_t savedUserSnapshotContext;
279 static snapshot_id snapshotid = 0;
280
281 static void createSharedMemory()
282 {
283         //step 1. create shared memory.
284         void *memMapBase = mmap(0, SHARED_MEMORY_DEFAULT + STACK_SIZE_DEFAULT, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANON, -1, 0);
285         if (MAP_FAILED == memMapBase)
286                 FAILURE("mmap");
287
288         //Setup snapshot record at top of free region
289         fork_snap = (struct fork_snapshotter *)memMapBase;
290         fork_snap->mSharedMemoryBase = (void *)((uintptr_t)memMapBase + sizeof(struct fork_snapshotter));
291         fork_snap->mStackBase = (void *)((uintptr_t)memMapBase + SHARED_MEMORY_DEFAULT);
292         fork_snap->mStackSize = STACK_SIZE_DEFAULT;
293         fork_snap->mIDToRollback = -1;
294         fork_snap->currSnapShotID = 0;
295 }
296
297 /**
298  * Create a new mspace pointer for the non-snapshotting (i.e., inter-process
299  * shared) memory region. Only for fork-based snapshotting.
300  *
301  * @return The shared memory mspace
302  */
303 mspace create_shared_mspace()
304 {
305         if (!fork_snap)
306                 createSharedMemory();
307         return create_mspace_with_base((void *)(fork_snap->mSharedMemoryBase), SHARED_MEMORY_DEFAULT - sizeof(struct fork_snapshotter), 1);
308 }
309
310 static void fork_snapshot_init(unsigned int numbackingpages,
311                 unsigned int numsnapshots, unsigned int nummemoryregions,
312                 unsigned int numheappages, VoidFuncPtr entryPoint)
313 {
314         if (!fork_snap)
315                 createSharedMemory();
316
317         void *base_model_snapshot_space = malloc((numheappages + 1) * PAGESIZE);
318         void *pagealignedbase = PageAlignAddressUpward(base_model_snapshot_space);
319         model_snapshot_space = create_mspace_with_base(pagealignedbase, numheappages * PAGESIZE, 1);
320
321         //step 2 setup the stack context.
322         ucontext_t newContext;
323         getcontext(&newContext);
324         newContext.uc_stack.ss_sp = fork_snap->mStackBase;
325         newContext.uc_stack.ss_size = STACK_SIZE_DEFAULT;
326         makecontext(&newContext, entryPoint, 0);
327         /* switch to a new entryPoint context, on a new stack */
328         swapcontext(&savedSnapshotContext, &newContext);
329
330         /* switch back here when takesnapshot is called */
331         pid_t forkedID = 0;
332         snapshotid = fork_snap->currSnapShotID;
333         /* This bool indicates that the current process's snapshotid is same
334                  as the id to which the rollback needs to occur */
335
336         bool rollback = false;
337         while (true) {
338                 fork_snap->currSnapShotID = snapshotid + 1;
339                 forkedID = fork();
340
341                 if (0 == forkedID) {
342                         /* If the rollback bool is set, switch to the context we need to
343                                  return to during a rollback. */
344                         if (rollback) {
345                                 setcontext(&(fork_snap->mContextToRollback));
346                         } else {
347                                 /*Child process which is forked as a result of takesnapshot
348                                         call should switch back to the takesnapshot context*/
349                                 setcontext(&savedUserSnapshotContext);
350                         }
351                 } else {
352                         int status;
353                         int retVal;
354
355                         DEBUG("The process id of child is %d and the process id of this process is %d and snapshot id is %d\n",
356                                 forkedID, getpid(), snapshotid);
357
358                         do {
359                                 retVal = waitpid(forkedID, &status, 0);
360                         } while (-1 == retVal && errno == EINTR);
361
362                         if (fork_snap->mIDToRollback != snapshotid) {
363                                 exit(EXIT_SUCCESS);
364                         }
365                         rollback = true;
366                 }
367         }
368 }
369
370 static snapshot_id fork_take_snapshot()
371 {
372         swapcontext(&savedUserSnapshotContext, &savedSnapshotContext);
373         DEBUG("TAKESNAPSHOT RETURN\n");
374         return snapshotid;
375 }
376
377 static void fork_roll_back(snapshot_id theID)
378 {
379         fork_snap->mIDToRollback = theID;
380         volatile int sTemp = 0;
381         getcontext(&fork_snap->mContextToRollback);
382         /*
383          * This is used to quit the process on rollback, so that the process
384          * which needs to rollback can quit allowing the process whose
385          * snapshotid matches the rollbackid to switch to this context and
386          * continue....
387          */
388         if (!sTemp) {
389                 sTemp = 1;
390                 DEBUG("Invoked rollback\n");
391                 exit(EXIT_SUCCESS);
392         }
393         /*
394          * This fix obviates the need for a finalize call. hence less dependences for model-checker....
395          */
396         fork_snap->mIDToRollback = -1;
397 }
398
399 #endif /* !USE_MPROTECT_SNAPSHOT */
400
401 /**
402  * @brief Initializes the snapshot system
403  * @param entryPoint the function that should run the program.
404  */
405 void snapshot_system_init(unsigned int numbackingpages,
406                 unsigned int numsnapshots, unsigned int nummemoryregions,
407                 unsigned int numheappages, VoidFuncPtr entryPoint)
408 {
409 #if USE_MPROTECT_SNAPSHOT
410         mprot_snapshot_init(numbackingpages, numsnapshots, nummemoryregions, numheappages, entryPoint);
411 #else
412         fork_snapshot_init(numbackingpages, numsnapshots, nummemoryregions, numheappages, entryPoint);
413 #endif
414 }
415
416 /** Assumes that addr is page aligned. */
417 void snapshot_add_memory_region(void *addr, unsigned int numPages)
418 {
419 #if USE_MPROTECT_SNAPSHOT
420         mprot_add_to_snapshot(addr, numPages);
421 #else
422         /* not needed for fork-based snapshotting */
423 #endif
424 }
425
426 /** Takes a snapshot of memory.
427  * @return The snapshot identifier.
428  */
429 snapshot_id take_snapshot()
430 {
431 #if USE_MPROTECT_SNAPSHOT
432         return mprot_take_snapshot();
433 #else
434         return fork_take_snapshot();
435 #endif
436 }
437
438 /** Rolls the memory state back to the given snapshot identifier.
439  *  @param theID is the snapshot identifier to rollback to.
440  */
441 void snapshot_roll_back(snapshot_id theID)
442 {
443 #if USE_MPROTECT_SNAPSHOT
444         mprot_roll_back(theID);
445 #else
446         fork_roll_back(theID);
447 #endif
448 }