Logo AND Algorithmique Numérique Distribuée

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