snapshot: combine public interfaces
[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 /* Primary struct for snapshotting system */
50 struct SnapShot {
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
56
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
60
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
64 };
65
66 static struct SnapShot *snapshotrecord = NULL;
67
68 /** ReturnPageAlignedAddress returns a page aligned address for the
69  * address being added as a side effect the numBytes are also changed.
70  */
71 static void * ReturnPageAlignedAddress(void *addr)
72 {
73         return (void *)(((uintptr_t)addr) & ~(PAGESIZE - 1));
74 }
75
76 /** The initSnapShotRecord method initialized the snapshotting data
77  *  structures for the mprotect based snapshot.
78  */
79 static void initSnapShotRecord(unsigned int numbackingpages, unsigned int numsnapshots, unsigned int nummemoryregions)
80 {
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;
94 }
95
96 /** HandlePF is the page fault handler for mprotect based snapshotting
97  * algorithm.
98  */
99 static void HandlePF(int sig, siginfo_t *si, void *unused)
100 {
101         if (si->si_code == SEGV_MAPERR) {
102                 model_print("Real Fault at %p\n", si->si_addr);
103                 print_trace();
104                 model_print("For debugging, place breakpoint at: %s:%d\n",
105                                 __FILE__, __LINE__);
106                 exit(EXIT_FAILURE);
107         }
108         void* addr = ReturnPageAlignedAddress(si->si_addr);
109
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);
113                 exit(EXIT_FAILURE);
114         }
115
116         //copy page
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)) {
122                 perror("mprotect");
123                 // Handle error by quitting?
124         }
125 }
126
127 static void mprot_snapshot_init(unsigned int numbackingpages,
128                 unsigned int numsnapshots, unsigned int nummemoryregions,
129                 unsigned int numheappages, VoidFuncPtr entryPoint)
130 {
131         /* Setup a stack for our signal handler....  */
132         stack_t ss;
133         ss.ss_sp = PageAlignAddressUpward(model_malloc(SIGSTACKSIZE + PAGESIZE - 1));
134         ss.ss_size = SIGSTACKSIZE;
135         ss.ss_flags = 0;
136         sigaltstack(&ss, NULL);
137
138         struct sigaction sa;
139         sa.sa_flags = SA_SIGINFO | SA_NODEFER | SA_RESTART | SA_ONSTACK;
140         sigemptyset(&sa.sa_mask);
141         sa.sa_sigaction = HandlePF;
142 #ifdef MAC
143         if (sigaction(SIGBUS, &sa, NULL) == -1) {
144                 model_print("SIGACTION CANNOT BE INSTALLED\n");
145                 exit(EXIT_FAILURE);
146         }
147 #endif
148         if (sigaction(SIGSEGV, &sa, NULL) == -1) {
149                 model_print("SIGACTION CANNOT BE INSTALLED\n");
150                 exit(EXIT_FAILURE);
151         }
152
153         initSnapShotRecord(numbackingpages, numsnapshots, nummemoryregions);
154
155         // EVIL HACK: We need to make sure that calls into the HandlePF method don't cause dynamic links
156         // The problem is that we end up protecting state in the dynamic linker...
157         // Solution is to call our signal handler before we start protecting stuff...
158
159         siginfo_t si;
160         memset(&si, 0, sizeof(si));
161         si.si_addr = ss.ss_sp;
162         HandlePF(SIGSEGV, &si, NULL);
163         snapshotrecord->lastBackingPage--; //remove the fake page we copied
164
165         void *basemySpace = model_malloc((numheappages + 1) * PAGESIZE);
166         void *pagealignedbase = PageAlignAddressUpward(basemySpace);
167         user_snapshot_space = create_mspace_with_base(pagealignedbase, numheappages * PAGESIZE, 1);
168         addMemoryRegionToSnapShot(pagealignedbase, numheappages);
169
170         void *base_model_snapshot_space = model_malloc((numheappages + 1) * PAGESIZE);
171         pagealignedbase = PageAlignAddressUpward(base_model_snapshot_space);
172         model_snapshot_space = create_mspace_with_base(pagealignedbase, numheappages * PAGESIZE, 1);
173         addMemoryRegionToSnapShot(pagealignedbase, numheappages);
174
175         entryPoint();
176 }
177
178 static void mprot_add_to_snapshot(void *addr, unsigned int numPages)
179 {
180         unsigned int memoryregion = snapshotrecord->lastRegion++;
181         if (memoryregion == snapshotrecord->maxRegions) {
182                 model_print("Exceeded supported number of memory regions!\n");
183                 exit(EXIT_FAILURE);
184         }
185
186         snapshotrecord->regionsToSnapShot[memoryregion].basePtr = addr;
187         snapshotrecord->regionsToSnapShot[memoryregion].sizeInPages = numPages;
188 }
189
190 static snapshot_id mprot_take_snapshot()
191 {
192         for (unsigned int region = 0; region < snapshotrecord->lastRegion; region++) {
193                 if (mprotect(snapshotrecord->regionsToSnapShot[region].basePtr, snapshotrecord->regionsToSnapShot[region].sizeInPages * sizeof(snapshot_page_t), PROT_READ) == -1) {
194                         perror("mprotect");
195                         model_print("Failed to mprotect inside of takeSnapShot\n");
196                         exit(EXIT_FAILURE);
197                 }
198         }
199         unsigned int snapshot = snapshotrecord->lastSnapShot++;
200         if (snapshot == snapshotrecord->maxSnapShots) {
201                 model_print("Out of snapshots\n");
202                 exit(EXIT_FAILURE);
203         }
204         snapshotrecord->snapShots[snapshot].firstBackingPage = snapshotrecord->lastBackingPage;
205
206         return snapshot;
207 }
208
209 static void mprot_roll_back(snapshot_id theID)
210 {
211 #if USE_MPROTECT_SNAPSHOT == 2
212         if (snapshotrecord->lastSnapShot == (theID + 1)) {
213                 for (unsigned int page = snapshotrecord->snapShots[theID].firstBackingPage; page < snapshotrecord->lastBackingPage; page++) {
214                         memcpy(snapshotrecord->backingRecords[page].basePtrOfPage, &snapshotrecord->backingStore[page], sizeof(snapshot_page_t));
215                 }
216                 return;
217         }
218 #endif
219
220         HashTable< void *, bool, uintptr_t, 4, model_malloc, model_calloc, model_free> duplicateMap;
221         for (unsigned int region = 0; region < snapshotrecord->lastRegion; region++) {
222                 if (mprotect(snapshotrecord->regionsToSnapShot[region].basePtr, snapshotrecord->regionsToSnapShot[region].sizeInPages * sizeof(snapshot_page_t), PROT_READ | PROT_WRITE) == -1) {
223                         perror("mprotect");
224                         model_print("Failed to mprotect inside of takeSnapShot\n");
225                         exit(EXIT_FAILURE);
226                 }
227         }
228         for (unsigned int page = snapshotrecord->snapShots[theID].firstBackingPage; page < snapshotrecord->lastBackingPage; page++) {
229                 if (!duplicateMap.contains(snapshotrecord->backingRecords[page].basePtrOfPage)) {
230                         duplicateMap.put(snapshotrecord->backingRecords[page].basePtrOfPage, true);
231                         memcpy(snapshotrecord->backingRecords[page].basePtrOfPage, &snapshotrecord->backingStore[page], sizeof(snapshot_page_t));
232                 }
233         }
234         snapshotrecord->lastSnapShot = theID;
235         snapshotrecord->lastBackingPage = snapshotrecord->snapShots[theID].firstBackingPage;
236         mprot_take_snapshot(); //Make sure current snapshot is still good...All later ones are cleared
237 }
238
239 #else /* !USE_MPROTECT_SNAPSHOT */
240
241 #include <ucontext.h>
242
243 #define SHARED_MEMORY_DEFAULT  (100 * ((size_t)1 << 20)) // 100mb for the shared memory
244 #define STACK_SIZE_DEFAULT      (((size_t)1 << 20) * 20)  // 20 mb out of the above 100 mb for my stack
245
246 struct SnapShot {
247         void *mSharedMemoryBase;
248         void *mStackBase;
249         size_t mStackSize;
250         volatile snapshot_id mIDToRollback;
251         ucontext_t mContextToRollback;
252         snapshot_id currSnapShotID;
253 };
254
255 static struct SnapShot *snapshotrecord = NULL;
256
257 /** @statics
258 *   These variables are necessary because the stack is shared region and
259 *   there exists a race between all processes executing the same function.
260 *   To avoid the problem above, we require variables allocated in 'safe' regions.
261 *   The bug was actually observed with the forkID, these variables below are
262 *   used to indicate the various contexts to which to switch to.
263 *
264 *   @savedSnapshotContext: contains the point to which takesnapshot() call should switch to.
265 *   @savedUserSnapshotContext: contains the point to which the process whose snapshotid is equal to the rollbackid should switch to
266 *   @snapshotid: it is a running counter for the various forked processes snapshotid. it is incremented and set in a persistently shared record
267 */
268 static ucontext_t savedSnapshotContext;
269 static ucontext_t savedUserSnapshotContext;
270 static snapshot_id snapshotid = 0;
271
272 static void createSharedMemory()
273 {
274         //step 1. create shared memory.
275         void *memMapBase = mmap(0, SHARED_MEMORY_DEFAULT + STACK_SIZE_DEFAULT, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANON, -1, 0);
276         if (MAP_FAILED == memMapBase)
277                 FAILURE("mmap");
278
279         //Setup snapshot record at top of free region
280         snapshotrecord = (struct SnapShot *)memMapBase;
281         snapshotrecord->mSharedMemoryBase = (void *)((uintptr_t)memMapBase + sizeof(struct SnapShot));
282         snapshotrecord->mStackBase = (void *)((uintptr_t)memMapBase + SHARED_MEMORY_DEFAULT);
283         snapshotrecord->mStackSize = STACK_SIZE_DEFAULT;
284         snapshotrecord->mIDToRollback = -1;
285         snapshotrecord->currSnapShotID = 0;
286 }
287
288 /**
289  * Create a new mspace pointer for the non-snapshotting (i.e., inter-process
290  * shared) memory region. Only for fork-based snapshotting.
291  *
292  * @return The shared memory mspace
293  */
294 mspace create_shared_mspace()
295 {
296         if (!snapshotrecord)
297                 createSharedMemory();
298         return create_mspace_with_base((void *)(snapshotrecord->mSharedMemoryBase), SHARED_MEMORY_DEFAULT - sizeof(struct SnapShot), 1);
299 }
300
301 static void fork_snapshot_init(unsigned int numbackingpages,
302                 unsigned int numsnapshots, unsigned int nummemoryregions,
303                 unsigned int numheappages, VoidFuncPtr entryPoint)
304 {
305         if (!snapshotrecord)
306                 createSharedMemory();
307
308         void *base_model_snapshot_space = malloc((numheappages + 1) * PAGESIZE);
309         void *pagealignedbase = PageAlignAddressUpward(base_model_snapshot_space);
310         model_snapshot_space = create_mspace_with_base(pagealignedbase, numheappages * PAGESIZE, 1);
311
312         //step 2 setup the stack context.
313         ucontext_t newContext;
314         getcontext(&newContext);
315         newContext.uc_stack.ss_sp = snapshotrecord->mStackBase;
316         newContext.uc_stack.ss_size = STACK_SIZE_DEFAULT;
317         makecontext(&newContext, entryPoint, 0);
318         /* switch to a new entryPoint context, on a new stack */
319         swapcontext(&savedSnapshotContext, &newContext);
320
321         /* switch back here when takesnapshot is called */
322         pid_t forkedID = 0;
323         snapshotid = snapshotrecord->currSnapShotID;
324         /* This bool indicates that the current process's snapshotid is same
325                  as the id to which the rollback needs to occur */
326
327         bool rollback = false;
328         while (true) {
329                 snapshotrecord->currSnapShotID = snapshotid + 1;
330                 forkedID = fork();
331
332                 if (0 == forkedID) {
333                         /* If the rollback bool is set, switch to the context we need to
334                                  return to during a rollback. */
335                         if (rollback) {
336                                 setcontext(&(snapshotrecord->mContextToRollback));
337                         } else {
338                                 /*Child process which is forked as a result of takesnapshot
339                                         call should switch back to the takesnapshot context*/
340                                 setcontext(&savedUserSnapshotContext);
341                         }
342                 } else {
343                         int status;
344                         int retVal;
345
346                         DEBUG("The process id of child is %d and the process id of this process is %d and snapshot id is %d\n",
347                                 forkedID, getpid(), snapshotid);
348
349                         do {
350                                 retVal = waitpid(forkedID, &status, 0);
351                         } while (-1 == retVal && errno == EINTR);
352
353                         if (snapshotrecord->mIDToRollback != snapshotid) {
354                                 exit(EXIT_SUCCESS);
355                         }
356                         rollback = true;
357                 }
358         }
359 }
360
361 static snapshot_id fork_take_snapshot()
362 {
363         swapcontext(&savedUserSnapshotContext, &savedSnapshotContext);
364         DEBUG("TAKESNAPSHOT RETURN\n");
365         return snapshotid;
366 }
367
368 static void fork_roll_back(snapshot_id theID)
369 {
370         snapshotrecord->mIDToRollback = theID;
371         volatile int sTemp = 0;
372         getcontext(&snapshotrecord->mContextToRollback);
373         /*
374          * This is used to quit the process on rollback, so that the process
375          * which needs to rollback can quit allowing the process whose
376          * snapshotid matches the rollbackid to switch to this context and
377          * continue....
378          */
379         if (!sTemp) {
380                 sTemp = 1;
381                 DEBUG("Invoked rollback\n");
382                 exit(EXIT_SUCCESS);
383         }
384         /*
385          * This fix obviates the need for a finalize call. hence less dependences for model-checker....
386          */
387         snapshotrecord->mIDToRollback = -1;
388 }
389
390 #endif /* !USE_MPROTECT_SNAPSHOT */
391
392 /** The initSnapshotLibrary function initializes the snapshot library.
393  *  @param entryPoint the function that should run the program.
394  */
395 void initSnapshotLibrary(unsigned int numbackingpages,
396                 unsigned int numsnapshots, unsigned int nummemoryregions,
397                 unsigned int numheappages, VoidFuncPtr entryPoint)
398 {
399 #if USE_MPROTECT_SNAPSHOT
400         mprot_snapshot_init(numbackingpages, numsnapshots, nummemoryregions, numheappages, entryPoint);
401 #else
402         fork_snapshot_init(numbackingpages, numsnapshots, nummemoryregions, numheappages, entryPoint);
403 #endif
404 }
405
406 /** The addMemoryRegionToSnapShot function assumes that addr is page aligned. */
407 void addMemoryRegionToSnapShot(void *addr, unsigned int numPages)
408 {
409 #if USE_MPROTECT_SNAPSHOT
410         mprot_add_to_snapshot(addr, numPages);
411 #else
412         /* not needed for fork-based snapshotting */
413 #endif
414 }
415
416 /** The takeSnapshot function takes a snapshot.
417  * @return The snapshot identifier.
418  */
419 snapshot_id takeSnapshot()
420 {
421 #if USE_MPROTECT_SNAPSHOT
422         return mprot_take_snapshot();
423 #else
424         return fork_take_snapshot();
425 #endif
426 }
427
428 /** The rollBack function rollback to the given snapshot identifier.
429  *  @param theID is the snapshot identifier to rollback to.
430  */
431 void rollBack(snapshot_id theID)
432 {
433 #if USE_MPROTECT_SNAPSHOT
434         mprot_roll_back(theID);
435 #else
436         fork_roll_back(theID);
437 #endif
438 }