Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
[mc] Make a copy of the libunwind context when snapshoting the stacks
[simgrid.git] / src / mc / mc_checkpoint.c
1 /* Copyright (c) 2008-2014. The SimGrid Team.
2  * All rights reserved.                                                     */
3
4 /* This program is free software; you can redistribute it and/or modify it
5  * under the terms of the license (GNU LGPL) which comes with this package. */
6
7 #define _GNU_SOURCE
8 #define UNW_LOCAL_ONLY
9
10 #include <unistd.h>
11
12 #include <string.h>
13 #include <link.h>
14 #include <dirent.h>
15
16 #include "internal_config.h"
17 #include "mc_memory_map.h"
18 #include "mc_private.h"
19 #include "xbt/module.h"
20 #include <xbt/mmalloc.h>
21 #include "../smpi/private.h"
22 #include <alloca.h>
23
24 #include "xbt/mmalloc/mmprivate.h"
25
26 #include "../simix/smx_private.h"
27
28 #define UNW_LOCAL_ONLY
29 #include <libunwind.h>
30 #include <libelf.h>
31
32 #include "mc_private.h"
33 #include <mc/mc.h>
34
35 #include "mc_snapshot.h"
36 #include "mc_object_info.h"
37 #include "mc_mmu.h"
38
39 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(mc_checkpoint, mc,
40                                 "Logging specific to mc_checkpoint");
41
42 /************************************  Free functions **************************************/
43 /*****************************************************************************************/
44
45 static void MC_snapshot_stack_free(mc_snapshot_stack_t s)
46 {
47   if (s) {
48     xbt_dynar_free(&(s->local_variables));
49     xbt_dynar_free(&(s->stack_frames));
50     xbt_free(s);
51   }
52 }
53
54 static void MC_snapshot_stack_free_voidp(void *s)
55 {
56   MC_snapshot_stack_free((mc_snapshot_stack_t) * (void **) s);
57 }
58
59 static void local_variable_free(local_variable_t v)
60 {
61   xbt_free(v->name);
62   xbt_free(v);
63 }
64
65 static void local_variable_free_voidp(void *v)
66 {
67   local_variable_free((local_variable_t) * (void **) v);
68 }
69
70 void MC_region_destroy(mc_mem_region_t region)
71 {
72   if (!region)
73     return;
74   switch(region->storage_type) {
75     case MC_REGION_STORAGE_TYPE_NONE:
76       break;
77     case MC_REGION_STORAGE_TYPE_FLAT:
78       xbt_free(region->flat.data);
79       break;
80     case MC_REGION_STORAGE_TYPE_CHUNKED:
81       mc_free_page_snapshot_region(region->chunked.page_numbers, mc_page_count(region->size));
82       xbt_free(region->chunked.page_numbers);
83       break;
84     case MC_REGION_STORAGE_TYPE_PRIVATIZED:
85       {
86         size_t regions_count = region->privatized.regions_count;
87         for (size_t i=0; i!=regions_count; ++i) {
88           MC_region_destroy(region->privatized.regions[i]);
89         }
90         free(region->privatized.regions);
91         break;
92       }
93   }
94   xbt_free(region);
95 }
96
97 void MC_free_snapshot(mc_snapshot_t snapshot)
98 {
99   for (size_t i = 0; i < snapshot->snapshot_regions_count; i++) {
100     MC_region_destroy(snapshot->snapshot_regions[i]);
101   }
102   xbt_free(snapshot->snapshot_regions);
103   xbt_free(snapshot->stack_sizes);
104   xbt_dynar_free(&(snapshot->stacks));
105   xbt_dynar_free(&(snapshot->to_ignore));
106   xbt_dynar_free(&snapshot->ignored_data);
107   xbt_free(snapshot);
108 }
109
110 /*******************************  Snapshot regions ********************************/
111 /*********************************************************************************/
112
113 static mc_mem_region_t mc_region_new_dense(
114   mc_region_type_t region_type,
115   void *start_addr, void* permanent_addr, size_t size, mc_mem_region_t ref_reg)
116 {
117   mc_mem_region_t region = xbt_new(s_mc_mem_region_t, 1);
118   region->region_type = region_type;
119   region->storage_type = MC_REGION_STORAGE_TYPE_FLAT;
120   region->start_addr = start_addr;
121   region->permanent_addr = permanent_addr;
122   region->size = size;
123   region->flat.data = xbt_malloc(size);
124   MC_process_read(&mc_model_checker->process, MC_ADDRESS_SPACE_READ_FLAGS_NONE,
125     region->flat.data, permanent_addr, size,
126     MC_PROCESS_INDEX_DISABLED);
127   XBT_DEBUG("New region : type : %d, data : %p (real addr %p), size : %zu",
128             region_type, region->flat.data, permanent_addr, size);
129   return region;
130 }
131
132 /** @brief Take a snapshot of a given region
133  *
134  * @param type
135  * @param start_addr   Address of the region in the simulated process
136  * @param permanent_addr Permanent address of this data (for privatized variables, this is the virtual address of the privatized mapping)
137  * @param size         Size of the data*
138  * @param ref_reg      Reference corresponding region
139  */
140 static mc_mem_region_t MC_region_new(mc_region_type_t type, void *start_addr, void* permanent_addr, size_t size, mc_mem_region_t ref_reg)
141 {
142   if (_sg_mc_sparse_checkpoint) {
143     return mc_region_new_sparse(type, start_addr, permanent_addr, size, ref_reg);
144   } else  {
145     return mc_region_new_dense(type, start_addr, permanent_addr, size, ref_reg);
146   }
147 }
148
149 /** @brief Restore a region from a snapshot
150  *
151  *  If we are using per page snapshots, it is possible to use the reference
152  *  region in order to do an incremental restoration of the region: the
153  *  softclean pages which are shared between the two snapshots do not need
154  *  to be restored.
155  *
156  *  @param reg     Target region
157  *  @param reg_reg Current region (if not NULL), used for lazy per page restoration
158  */
159 static void MC_region_restore(mc_mem_region_t region, mc_mem_region_t ref_region)
160 {
161   switch(region->storage_type) {
162   case MC_REGION_STORAGE_TYPE_NONE:
163   default:
164     xbt_die("Storage type not supported");
165     break;
166
167   case MC_REGION_STORAGE_TYPE_FLAT:
168     MC_process_write(&mc_model_checker->process, region->flat.data,
169       region->permanent_addr, region->size);
170     break;
171
172   case MC_REGION_STORAGE_TYPE_CHUNKED:
173     mc_region_restore_sparse(&mc_model_checker->process, region, ref_region);
174     break;
175
176   case MC_REGION_STORAGE_TYPE_PRIVATIZED:
177     {
178       bool has_ref_regions = ref_region &&
179         ref_region->storage_type == MC_REGION_STORAGE_TYPE_PRIVATIZED;
180       size_t process_count = region->privatized.regions_count;
181       for (size_t i = 0; i < process_count; i++) {
182         MC_region_restore(region->privatized.regions[i],
183           has_ref_regions ? ref_region->privatized.regions[i] : NULL);
184       }
185       break;
186     }
187   }
188 }
189
190 // FIXME, multiple privatisation regions
191 // FIXME, cross-process
192 static inline
193 void* MC_privatization_address(mc_process_t process, int process_index)
194 {
195   xbt_assert(process_index >= 0);
196   return smpi_privatisation_regions[process_index].address;
197 }
198
199 static mc_mem_region_t MC_region_new_privatized(
200     mc_region_type_t region_type, void *start_addr, void* permanent_addr, size_t size,
201     mc_mem_region_t ref_reg)
202 {
203   size_t process_count = smpi_process_count();
204   mc_mem_region_t region = xbt_new(s_mc_mem_region_t, 1);
205   region->region_type = region_type;
206   region->storage_type = MC_REGION_STORAGE_TYPE_PRIVATIZED;
207   region->start_addr = start_addr;
208   region->permanent_addr = permanent_addr;
209   region->size = size;
210   region->privatized.regions_count = process_count;
211   region->privatized.regions = xbt_new(mc_mem_region_t, process_count);
212
213   for (size_t i = 0; i < process_count; i++) {
214     mc_mem_region_t ref_subreg = NULL;
215     if (ref_reg && ref_reg->storage_type == MC_REGION_STORAGE_TYPE_PRIVATIZED)
216       ref_subreg = ref_reg->privatized.regions[i];
217     region->privatized.regions[i] =
218       MC_region_new(region_type, start_addr,
219         MC_privatization_address(&mc_model_checker->process, i), size,
220         ref_subreg);
221   }
222
223   return region;
224 }
225
226 static void MC_snapshot_add_region(int index, mc_snapshot_t snapshot, mc_region_type_t type,
227                                   mc_object_info_t object_info,
228                                   void *start_addr, void* permanent_addr, size_t size)
229 {
230   if (type == MC_REGION_TYPE_DATA)
231     xbt_assert(object_info, "Missing object info for object.");
232   else if (type == MC_REGION_TYPE_HEAP)
233     xbt_assert(!object_info, "Unexpected object info for heap region.");
234
235   mc_mem_region_t ref_reg = NULL;
236   if (mc_model_checker->parent_snapshot)
237     ref_reg = mc_model_checker->parent_snapshot->snapshot_regions[index];
238
239   mc_mem_region_t region;
240   const bool privatization_aware = MC_object_info_is_privatized(object_info);
241   if (privatization_aware && smpi_process_count())
242     region = MC_region_new_privatized(type, start_addr, permanent_addr, size, ref_reg);
243   else
244     region = MC_region_new(type, start_addr, permanent_addr, size, ref_reg);
245
246   region->object_info = object_info;
247   snapshot->snapshot_regions[index] = region;
248   return;
249 }
250
251 static void MC_get_memory_regions(mc_process_t process, mc_snapshot_t snapshot)
252 {
253   const size_t n = process->object_infos_size;
254   snapshot->snapshot_regions_count = n + 1;
255   snapshot->snapshot_regions = xbt_new0(mc_mem_region_t, n + 1);
256
257   for (size_t i = 0; i!=n; ++i) {
258     mc_object_info_t object_info = process->object_infos[i];
259     MC_snapshot_add_region(i, snapshot, MC_REGION_TYPE_DATA, object_info,
260       object_info->start_rw, object_info->start_rw,
261       object_info->end_rw - object_info->start_rw);
262   }
263
264   xbt_mheap_t heap = MC_process_get_heap(process);
265   void *start_heap = heap->base;
266   void *end_heap = heap->breakval;
267
268   MC_snapshot_add_region(n, snapshot, MC_REGION_TYPE_HEAP, NULL,
269                         start_heap, start_heap,
270                         (char *) end_heap - (char *) start_heap);
271   snapshot->heap_bytes_used = mmalloc_get_bytes_used_remote(
272     heap->heaplimit,
273     MC_process_get_malloc_info(process));
274
275 #ifdef HAVE_SMPI
276   if (smpi_privatize_global_variables && smpi_process_count()) {
277     // FIXME, cross-process
278     snapshot->privatization_index = smpi_loaded_page;
279   } else
280 #endif
281   {
282     snapshot->privatization_index = MC_PROCESS_INDEX_MISSING;
283   }
284 }
285
286 /** \brief Fills the position of the segments (executable, read-only, read/write).
287  *
288  *  `dl_iterate_phdr` would be more robust but would not work in cross-process.
289  * */
290 void MC_find_object_address(memory_map_t maps, mc_object_info_t result)
291 {
292   unsigned int i = 0;
293   s_map_region_t reg;
294   const char *name = basename(result->file_name);
295   while (i < maps->mapsize) {
296     reg = maps->regions[i];
297     if (maps->regions[i].pathname == NULL
298         || strcmp(basename(maps->regions[i].pathname), name)) {
299       // Nothing to do
300     } else if ((reg.prot & PROT_WRITE)) {
301       xbt_assert(!result->start_rw,
302                  "Multiple read-write segments for %s, not supported",
303                  maps->regions[i].pathname);
304       result->start_rw = reg.start_addr;
305       result->end_rw = reg.end_addr;
306       // .bss is usually after the .data:
307       s_map_region_t *next = &(maps->regions[i + 1]);
308       if (next->pathname == NULL && (next->prot & PROT_WRITE)
309           && next->start_addr == reg.end_addr) {
310         result->end_rw = maps->regions[i + 1].end_addr;
311       }
312     } else if ((reg.prot & PROT_READ) && (reg.prot & PROT_EXEC)) {
313       xbt_assert(!result->start_exec,
314                  "Multiple executable segments for %s, not supported",
315                  maps->regions[i].pathname);
316       result->start_exec = reg.start_addr;
317       result->end_exec = reg.end_addr;
318     } else if ((reg.prot & PROT_READ) && !(reg.prot & PROT_EXEC)) {
319       xbt_assert(!result->start_ro,
320                  "Multiple read only segments for %s, not supported",
321                  maps->regions[i].pathname);
322       result->start_ro = reg.start_addr;
323       result->end_ro = reg.end_addr;
324     }
325     i++;
326   }
327
328   result->start = result->start_rw;
329   if ((const void*) result->start_ro > result->start)
330     result->start = result->start_ro;
331   if ((const void*) result->start_exec > result->start)
332     result->start = result->start_exec;
333
334   result->end = result->end_rw;
335   if (result->end_ro && (const void*) result->end_ro < result->end)
336     result->end = result->end_ro;
337   if (result->end_exec && (const void*) result->end_exec > result->end)
338     result->end = result->end_exec;
339
340   xbt_assert(result->file_name);
341   xbt_assert(result->start_rw);
342   xbt_assert(result->start_exec);
343 }
344
345 /************************************* Take Snapshot ************************************/
346 /****************************************************************************************/
347
348 /** \brief Checks whether the variable is in scope for a given IP.
349  *
350  *  A variable may be defined only from a given value of IP.
351  *
352  *  \param var   Variable description
353  *  \param frame Scope description
354  *  \param ip    Instruction pointer
355  *  \return      true if the variable is valid
356  * */
357 static bool mc_valid_variable(dw_variable_t var, dw_frame_t scope,
358                               const void *ip)
359 {
360   // The variable is not yet valid:
361   if ((const void *) ((const char *) scope->low_pc + var->start_scope) > ip)
362     return false;
363   else
364     return true;
365 }
366
367 static void mc_fill_local_variables_values(mc_stack_frame_t stack_frame,
368                                            dw_frame_t scope, int process_index, xbt_dynar_t result)
369 {
370   mc_process_t process = &mc_model_checker->process;
371
372   void *ip = (void *) stack_frame->ip;
373   if (ip < scope->low_pc || ip >= scope->high_pc)
374     return;
375
376   unsigned cursor = 0;
377   dw_variable_t current_variable;
378   xbt_dynar_foreach(scope->variables, cursor, current_variable) {
379
380     if (!mc_valid_variable(current_variable, scope, (void *) stack_frame->ip))
381       continue;
382
383     int region_type;
384     // FIXME, get rid of `region_type`
385     if ((long) stack_frame->ip > (long) process->libsimgrid_info->start_exec)
386       region_type = 1;
387     else
388       region_type = 2;
389
390     local_variable_t new_var = xbt_new0(s_local_variable_t, 1);
391     new_var->subprogram = stack_frame->frame;
392     new_var->ip = stack_frame->ip;
393     new_var->name = xbt_strdup(current_variable->name);
394     new_var->type = current_variable->type;
395     new_var->region = region_type;
396
397     if (current_variable->address != NULL) {
398       new_var->address = current_variable->address;
399     } else if (current_variable->locations.size != 0) {
400       s_mc_location_t location;
401       // FIXME, cross-process support
402       mc_dwarf_resolve_locations(&location, &current_variable->locations,
403                                               current_variable->object_info,
404                                               &(stack_frame->unw_cursor),
405                                               (void *) stack_frame->frame_base,
406                                               NULL, process_index);
407
408       switch(mc_get_location_type(&location)) {
409       case MC_LOCATION_TYPE_ADDRESS:
410         new_var->address = location.memory_location;
411         break;
412       case MC_LOCATION_TYPE_REGISTER:
413       default:
414         xbt_die("Cannot handle non-address variable");
415       }
416
417     } else {
418       xbt_die("No address");
419     }
420
421     xbt_dynar_push(result, &new_var);
422   }
423
424   // Recursive processing of nested scopes:
425   dw_frame_t nested_scope = NULL;
426   xbt_dynar_foreach(scope->scopes, cursor, nested_scope) {
427     mc_fill_local_variables_values(stack_frame, nested_scope, process_index, result);
428   }
429 }
430
431 static xbt_dynar_t MC_get_local_variables_values(xbt_dynar_t stack_frames, int process_index)
432 {
433
434   unsigned cursor1 = 0;
435   mc_stack_frame_t stack_frame;
436   xbt_dynar_t variables =
437       xbt_dynar_new(sizeof(local_variable_t), local_variable_free_voidp);
438
439   xbt_dynar_foreach(stack_frames, cursor1, stack_frame) {
440     mc_fill_local_variables_values(stack_frame, stack_frame->frame, process_index, variables);
441   }
442
443   return variables;
444 }
445
446 static void MC_stack_frame_free_voipd(void *s)
447 {
448   mc_stack_frame_t stack_frame = *(mc_stack_frame_t *) s;
449   if (stack_frame) {
450     xbt_free(stack_frame->frame_name);
451     xbt_free(stack_frame);
452   }
453 }
454
455 static xbt_dynar_t MC_unwind_stack_frames(unw_context_t* stack_context)
456 {
457   mc_process_t process = &mc_model_checker->process;
458   xbt_dynar_t result =
459       xbt_dynar_new(sizeof(mc_stack_frame_t), MC_stack_frame_free_voipd);
460
461   unw_cursor_t c;
462
463   // TODO, check condition check (unw_init_local==0 means end of frame)
464   // FIXME, cross-process support
465   if (unw_init_local(&c, stack_context) != 0) {
466
467     xbt_die("Could not initialize stack unwinding");
468
469   } else
470     while (1) {
471
472       mc_stack_frame_t stack_frame = xbt_new(s_mc_stack_frame_t, 1);
473       xbt_dynar_push(result, &stack_frame);
474
475       stack_frame->unw_cursor = c;
476
477       unw_word_t ip, sp;
478
479       unw_get_reg(&c, UNW_REG_IP, &ip);
480       unw_get_reg(&c, UNW_REG_SP, &sp);
481
482       stack_frame->ip = ip;
483       stack_frame->sp = sp;
484
485       // TODO, use real addresses in frame_t instead of fixing it here
486
487       dw_frame_t frame = MC_process_find_function(process, (void *) ip);
488       stack_frame->frame = frame;
489
490       if (frame) {
491         stack_frame->frame_name = xbt_strdup(frame->name);
492         stack_frame->frame_base =
493             (unw_word_t) mc_find_frame_base(frame, frame->object_info, &c);
494       } else {
495         stack_frame->frame_base = 0;
496         stack_frame->frame_name = NULL;
497       }
498
499       /* Stop before context switch with maestro */
500       if (frame != NULL && frame->name != NULL
501           && !strcmp(frame->name, "smx_ctx_sysv_wrapper"))
502         break;
503
504       int ret = ret = unw_step(&c);
505       if (ret == 0) {
506         xbt_die("Unexpected end of stack.");
507       } else if (ret < 0) {
508         xbt_die("Error while unwinding stack.");
509       }
510     }
511
512   if (xbt_dynar_length(result) == 0) {
513     XBT_INFO("unw_init_local failed");
514     xbt_abort();
515   }
516
517   return result;
518 };
519
520 static xbt_dynar_t MC_take_snapshot_stacks(mc_snapshot_t * snapshot)
521 {
522
523   xbt_dynar_t res =
524       xbt_dynar_new(sizeof(s_mc_snapshot_stack_t),
525                     MC_snapshot_stack_free_voidp);
526
527   unsigned int cursor = 0;
528   stack_region_t current_stack;
529
530   // FIXME, cross-process support (stack_areas)
531   xbt_dynar_foreach(stacks_areas, cursor, current_stack) {
532     mc_snapshot_stack_t st = xbt_new(s_mc_snapshot_stack_t, 1);
533
534     // Take a copy of the context for our own purpose:
535     st->context = *(unw_context_t*)current_stack->context;
536 #if defined(PROCESSOR_x86_64) || defined(PROCESSOR_i686)
537     // On x86_64, ucontext_t contains a pointer to itself for FP registers.
538     // We don't really need support for FR registers as they are caller saved
539     // and probably never use those fields as libunwind-x86_64 does not read
540     // FP registers from the unw_context_t
541     // but we fix the pointer in order to avoid dangling pointers:
542     st->context.uc_mcontext.fpregs = &st->context.__fpregs_mem;
543 #else
544     // Do we need to do any fixup like this?
545     #error Target CPU type is not handled.
546 #endif
547
548     st->stack_frames = MC_unwind_stack_frames(&st->context);
549     st->local_variables = MC_get_local_variables_values(st->stack_frames, current_stack->process_index);
550     st->process_index = current_stack->process_index;
551
552     unw_word_t sp = xbt_dynar_get_as(st->stack_frames, 0, mc_stack_frame_t)->sp;
553
554     xbt_dynar_push(res, &st);
555     (*snapshot)->stack_sizes =
556         xbt_realloc((*snapshot)->stack_sizes, (cursor + 1) * sizeof(size_t));
557     (*snapshot)->stack_sizes[cursor] =
558       (char*) current_stack->address + current_stack->size - (char*) sp;
559   }
560
561   return res;
562
563 }
564
565 // FIXME, cross-process support (mc_heap_comparison_ignore)
566 static xbt_dynar_t MC_take_snapshot_ignore()
567 {
568
569   if (mc_heap_comparison_ignore == NULL)
570     return NULL;
571
572   xbt_dynar_t cpy =
573       xbt_dynar_new(sizeof(mc_heap_ignore_region_t),
574                     heap_ignore_region_free_voidp);
575
576   unsigned int cursor = 0;
577   mc_heap_ignore_region_t current_region;
578
579   xbt_dynar_foreach(mc_heap_comparison_ignore, cursor, current_region) {
580     mc_heap_ignore_region_t new_region = NULL;
581     new_region = xbt_new0(s_mc_heap_ignore_region_t, 1);
582     new_region->address = current_region->address;
583     new_region->size = current_region->size;
584     new_region->block = current_region->block;
585     new_region->fragment = current_region->fragment;
586     xbt_dynar_push(cpy, &new_region);
587   }
588
589   return cpy;
590
591 }
592
593 static void mc_free_snapshot_ignored_data_pvoid(void* data) {
594   mc_snapshot_ignored_data_t ignored_data = (mc_snapshot_ignored_data_t) data;
595   free(ignored_data->data);
596 }
597
598 static void MC_snapshot_handle_ignore(mc_snapshot_t snapshot)
599 {
600   xbt_assert(snapshot->process);
601   snapshot->ignored_data = xbt_dynar_new(sizeof(s_mc_snapshot_ignored_data_t), mc_free_snapshot_ignored_data_pvoid);
602
603   // Copy the memory:
604   unsigned int cursor = 0;
605   mc_checkpoint_ignore_region_t region;
606   // FIXME, cross-process support (mc_checkpoint_ignore)
607   xbt_dynar_foreach (mc_checkpoint_ignore, cursor, region) {
608     s_mc_snapshot_ignored_data_t ignored_data;
609     ignored_data.start = region->addr;
610     ignored_data.size = region->size;
611     ignored_data.data = malloc(region->size);
612     // TODO, we should do this once per privatization segment:
613     MC_process_read(snapshot->process,
614       MC_ADDRESS_SPACE_READ_FLAGS_NONE,
615       ignored_data.data, region->addr, region->size, MC_PROCESS_INDEX_DISABLED);
616     xbt_dynar_push(snapshot->ignored_data, &ignored_data);
617   }
618
619   // Zero the memory:
620   xbt_dynar_foreach (mc_checkpoint_ignore, cursor, region) {
621     MC_process_clear_memory(snapshot->process, region->addr, region->size);
622   }
623
624 }
625
626 static void MC_snapshot_ignore_restore(mc_snapshot_t snapshot)
627 {
628   unsigned int cursor = 0;
629   s_mc_snapshot_ignored_data_t ignored_data;
630   xbt_dynar_foreach (snapshot->ignored_data, cursor, ignored_data) {
631     MC_process_write(snapshot->process,
632       ignored_data.data, ignored_data.start, ignored_data.size);
633   }
634 }
635
636 /** @brief Can we remove this snapshot?
637  *
638  * Some snapshots cannot be removed (yet) because we need them
639  * at this point.
640  *
641  * @param snapshot
642  */
643 int mc_important_snapshot(mc_snapshot_t snapshot)
644 {
645   // We need this snapshot in order to know which
646   // pages needs to be stored in the next snapshot.
647   // This field is only non-NULL when using soft-dirty
648   // page tracking.
649   if (snapshot == mc_model_checker->parent_snapshot)
650     return true;
651
652   return false;
653 }
654
655 static void MC_get_current_fd(mc_snapshot_t snapshot)
656 {
657
658   snapshot->total_fd = 0;
659
660   const size_t fd_dir_path_size = 20;
661   char fd_dir_path[fd_dir_path_size];
662   if (snprintf(fd_dir_path, fd_dir_path_size,
663     "/proc/%lli/fd", (long long int) snapshot->process->pid) > fd_dir_path_size)
664     xbt_die("Unexpected buffer is too small for fd_dir_path");
665
666   DIR* fd_dir = opendir(fd_dir_path);
667   if (fd_dir == NULL)
668     xbt_die("Cannot open directory '/proc/self/fd'\n");
669
670   size_t total_fd = 0;
671   struct dirent* fd_number;
672   while ((fd_number = readdir(fd_dir))) {
673
674     int fd_value = atoi(fd_number->d_name);
675
676     if(fd_value < 3)
677       continue;
678
679     const size_t source_size = 25;
680     char source[25];
681     if (snprintf(source, source_size, "/proc/%lli/fd/%s",
682         (long long int) snapshot->process->pid, fd_number->d_name) > source_size)
683       xbt_die("Unexpected buffer is too small for fd %s", fd_number->d_name);
684
685     const size_t link_size = 200;
686     char link[200];
687     int res = readlink(source, link, link_size);
688     if (res<0) {
689       xbt_die("Could not read link for %s", source);
690     }
691     if (res==200) {
692       xbt_die("Buffer to small for link of %s", source);
693     }
694     link[res] = '\0';
695
696     if(smpi_is_privatisation_file(link))
697       continue;
698
699     // This is (probably) the DIR* we are reading:
700     // TODO, read all the file entries at once and close the DIR.*
701     if(strcmp(fd_dir_path, link) == 0)
702       continue;
703
704     // We don't handle them.
705     // It does not mean we should silently ignore them however.
706     if (strncmp(link, "pipe:", 5) == 0 || strncmp(link, "socket:", 7) == 0)
707       continue;
708
709     // This is probably a shared memory used by lttng-ust:
710     if(strncmp("/dev/shm/ust-shm-tmp-", link, 21)==0)
711       continue;
712
713     // Add an entry for this FD in the snapshot:
714     fd_infos_t fd = xbt_new0(s_fd_infos_t, 1);
715     fd->filename = strdup(link);
716     fd->number = fd_value;
717     fd->flags = fcntl(fd_value, F_GETFL) | fcntl(fd_value, F_GETFD) ;
718     fd->current_position = lseek(fd_value, 0, SEEK_CUR);
719     snapshot->current_fd = xbt_realloc(snapshot->current_fd, (total_fd + 1) * sizeof(fd_infos_t));
720     snapshot->current_fd[total_fd] = fd;
721     total_fd++;
722   }
723
724   snapshot->total_fd = total_fd;
725   closedir (fd_dir);
726 }
727
728 static s_mc_address_space_class_t mc_snapshot_class = {
729   .read = (void*) &MC_snapshot_read
730 };
731
732 mc_snapshot_t MC_take_snapshot(int num_state)
733 {
734   mc_process_t mc_process = &mc_model_checker->process;
735   mc_snapshot_t snapshot = xbt_new0(s_mc_snapshot_t, 1);
736   snapshot->process = mc_process;
737   snapshot->address_space.address_space_class = &mc_snapshot_class;
738
739   snapshot->enabled_processes = xbt_dynar_new(sizeof(int), NULL);
740   smx_process_t process;
741   // FIXME, cross-process support (simix_global->process_list)
742   xbt_swag_foreach(process, simix_global->process_list) {
743     xbt_dynar_push_as(snapshot->enabled_processes, int, (int)process->pid);
744   }
745
746   MC_snapshot_handle_ignore(snapshot);
747
748   MC_get_current_fd(snapshot);
749
750   const bool use_soft_dirty = _sg_mc_sparse_checkpoint
751     && _sg_mc_soft_dirty
752     && MC_process_is_self(mc_process);
753
754   /* Save the std heap and the writable mapped pages of libsimgrid and binary */
755   MC_get_memory_regions(mc_process, snapshot);
756   if (use_soft_dirty)
757     mc_softdirty_reset();
758
759   snapshot->to_ignore = MC_take_snapshot_ignore();
760
761   if (_sg_mc_visited > 0 || strcmp(_sg_mc_property_file, "")) {
762     snapshot->stacks =
763         MC_take_snapshot_stacks(&snapshot);
764     if (_sg_mc_hash && snapshot->stacks != NULL) {
765       snapshot->hash = mc_hash_processes_state(num_state, snapshot->stacks);
766     } else {
767       snapshot->hash = 0;
768     }
769   } else {
770     snapshot->hash = 0;
771   }
772
773   MC_snapshot_ignore_restore(snapshot);
774   if (use_soft_dirty)
775     mc_model_checker->parent_snapshot = snapshot;
776   return snapshot;
777 }
778
779 static inline
780 void MC_restore_snapshot_regions(mc_snapshot_t snapshot)
781 {
782   mc_snapshot_t parent_snapshot = mc_model_checker->parent_snapshot;
783
784   const size_t n = snapshot->snapshot_regions_count;
785   for (size_t i = 0; i < n; i++) {
786     // For privatized, variables we decided it was not necessary to take the snapshot:
787     if (snapshot->snapshot_regions[i])
788       MC_region_restore(snapshot->snapshot_regions[i],
789         parent_snapshot ? parent_snapshot->snapshot_regions[i] : NULL);
790   }
791
792 #ifdef HAVE_SMPI
793   if(snapshot->privatization_index >= 0) {
794     // We just rewrote the global variables.
795     // The privatisation segment SMPI thinks
796     // is mapped might be inconsistent with the segment which
797     // is really mapped in memory (kernel state).
798     // We ask politely SMPI to map the segment anyway,
799     // even if it thinks it is the current one:
800     smpi_really_switch_data_segment(snapshot->privatization_index);
801   }
802 #endif
803 }
804
805 // FIXME, cross-process support ~ we need to implement this on the app side
806 // or use some form of [remote syscall execution](http://criu.org/Remote_syscall_execution)
807 // based on [parasite code execution](http://criu.org/Parasite_code).
808 static inline
809 void MC_restore_snapshot_fds(mc_snapshot_t snapshot)
810 {
811   int new_fd;
812   size_t i;
813   for(i=0; i < snapshot->total_fd; i++){
814     
815     new_fd = open(snapshot->current_fd[i]->filename, snapshot->current_fd[i]->flags);
816     if (new_fd <0) {
817       xbt_die("Could not reopen the file %s fo restoring the file descriptor",
818         snapshot->current_fd[i]->filename);
819     }
820     if(new_fd != -1 && new_fd != snapshot->current_fd[i]->number){
821       dup2(new_fd, snapshot->current_fd[i]->number);
822       //fprintf(stderr, "%p\n", fdopen(snapshot->current_fd[i]->number, "rw"));
823       close(new_fd);
824     };
825     lseek(snapshot->current_fd[i]->number, snapshot->current_fd[i]->current_position, SEEK_SET);
826   }
827 }
828
829 void MC_restore_snapshot(mc_snapshot_t snapshot)
830 {
831   const bool use_soft_dirty = _sg_mc_sparse_checkpoint
832     && _sg_mc_soft_dirty
833     && MC_process_is_self(&mc_model_checker->process);
834
835   MC_restore_snapshot_regions(snapshot);
836   MC_restore_snapshot_fds(snapshot);
837   if (use_soft_dirty) {
838     mc_softdirty_reset();
839   }
840   MC_snapshot_ignore_restore(snapshot);
841   if (use_soft_dirty) {
842     mc_model_checker->parent_snapshot = snapshot;
843   }
844
845   mc_model_checker->process.cache_flags = 0;
846 }
847
848 mc_snapshot_t simcall_HANDLER_mc_snapshot(smx_simcall_t simcall)
849 {
850   return MC_take_snapshot(1);
851 }
852
853 void *MC_snapshot(void)
854 {
855   return simcall_mc_snapshot();
856 }