Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Merge branch 'master' of scm.gforge.inria.fr:/gitroot/simgrid/simgrid
[simgrid.git] / src / mc / mc_checkpoint.cpp
1 /* Copyright (c) 2008-2015. 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 #include <unistd.h>
8
9 #include <fcntl.h>
10 #include <string.h>
11 #include <link.h>
12 #include <dirent.h>
13
14 #ifndef WIN32
15 #include <sys/mman.h>
16 #endif
17
18 #include "src/internal_config.h"
19 #include "src/mc/mc_private.h"
20 #include "xbt/module.h"
21 #include <xbt/mmalloc.h>
22 #include <xbt/memory.hpp>
23 #include "src/smpi/private.h"
24
25 #include "src/xbt/mmalloc/mmprivate.h"
26
27 #include "src/simix/smx_private.h"
28
29 #include <libunwind.h>
30 #include <libelf.h>
31
32 #include "src/mc/mc_private.h"
33 #include <mc/mc.h>
34
35 #include "src/mc/mc_snapshot.h"
36 #include "src/mc/mc_mmu.h"
37 #include "src/mc/mc_unw.h"
38 #include "src/mc/mc_protocol.h"
39 #include "src/mc/mc_smx.h"
40 #include "mc_hash.hpp"
41
42 #include "src/mc/RegionSnapshot.hpp"
43 #include "src/mc/ObjectInformation.hpp"
44 #include "src/mc/Frame.hpp"
45 #include "src/mc/Variable.hpp"
46
47 using simgrid::mc::remote;
48
49 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(mc_checkpoint, mc,
50                                 "Logging specific to mc_checkpoint");
51
52 namespace simgrid {
53 namespace mc {
54
55 /************************************  Free functions **************************************/
56 /*****************************************************************************************/
57
58 /** @brief Restore a region from a snapshot
59  *
60  *  @param reg     Target region
61  */
62 static void restore(mc_mem_region_t region)
63 {
64   switch(region->storage_type()) {
65   case simgrid::mc::StorageType::NoData:
66   default:
67     xbt_die("Storage type not supported");
68     break;
69
70   case simgrid::mc::StorageType::Flat:
71     mc_model_checker->process().write_bytes(region->flat_data().get(),
72       region->size(), region->permanent_address());
73     break;
74
75   case simgrid::mc::StorageType::Chunked:
76     mc_region_restore_sparse(&mc_model_checker->process(), region);
77     break;
78
79   case simgrid::mc::StorageType::Privatized:
80     for (auto& p : region->privatized_data())
81       restore(&p);
82     break;
83   }
84 }
85
86 #if HAVE_SMPI
87 RegionSnapshot privatized_region(
88     RegionType region_type, void *start_addr, void* permanent_addr,
89     std::size_t size, const RegionSnapshot* ref_region
90     )
91 {
92   size_t process_count = MC_smpi_process_count();
93
94   // Read smpi_privatisation_regions from MCed:
95   smpi_privatisation_region_t remote_smpi_privatisation_regions;
96   mc_model_checker->process().read_variable(
97     "smpi_privatisation_regions",
98     &remote_smpi_privatisation_regions, sizeof(remote_smpi_privatisation_regions));
99   s_smpi_privatisation_region_t privatisation_regions[process_count];
100   mc_model_checker->process().read_bytes(
101     &privatisation_regions, sizeof(privatisation_regions),
102     remote(remote_smpi_privatisation_regions));
103
104   std::vector<simgrid::mc::RegionSnapshot> data;
105   data.reserve(process_count);
106   for (size_t i = 0; i < process_count; i++) {
107     const simgrid::mc::RegionSnapshot* ref_privatized_region = nullptr;
108     if (ref_region && ref_region->storage_type() == StorageType::Privatized)
109       ref_privatized_region = &ref_region->privatized_data()[i];
110     data.push_back(simgrid::mc::region(region_type, start_addr,
111       privatisation_regions[i].address, size, ref_privatized_region));
112   }
113
114   simgrid::mc::RegionSnapshot region = simgrid::mc::RegionSnapshot(
115     region_type, start_addr, permanent_addr, size);
116   region.privatized_data(std::move(data));
117   return region;
118 }
119 #endif
120
121 static
122 void add_region(int index, simgrid::mc::Snapshot* snapshot,
123                                   simgrid::mc::RegionType type,
124                                   simgrid::mc::ObjectInformation* object_info,
125                                   void *start_addr, void* permanent_addr,
126                                   std::size_t size)
127 {
128   if (type == simgrid::mc::RegionType::Data)
129     xbt_assert(object_info, "Missing object info for object.");
130   else if (type == simgrid::mc::RegionType::Heap)
131     xbt_assert(!object_info, "Unexpected object info for heap region.");
132
133   simgrid::mc::RegionSnapshot const* ref_region = nullptr;
134   if (mc_model_checker->parent_snapshot_)
135     ref_region = mc_model_checker->parent_snapshot_->snapshot_regions[index].get();
136
137   simgrid::mc::RegionSnapshot region;
138 #if HAVE_SMPI
139   const bool privatization_aware = object_info
140     && mc_model_checker->process().privatized(*object_info);
141   if (privatization_aware && MC_smpi_process_count())
142     region = simgrid::mc::privatized_region(
143       type, start_addr, permanent_addr, size, ref_region);
144   else
145 #endif
146     region = simgrid::mc::region(type, start_addr, permanent_addr, size, ref_region);
147
148   region.object_info(object_info);
149   snapshot->snapshot_regions[index]
150     = std::unique_ptr<simgrid::mc::RegionSnapshot>(
151       new simgrid::mc::RegionSnapshot(std::move(region)));
152   return;
153 }
154
155 static void get_memory_regions(simgrid::mc::Process* process, simgrid::mc::Snapshot* snapshot)
156 {
157   const size_t n = process->object_infos.size();
158   snapshot->snapshot_regions.resize(n + 1);
159   int i = 0;
160   for (auto const& object_info : process->object_infos)
161     add_region(i++, snapshot, simgrid::mc::RegionType::Data,
162       object_info.get(),
163       object_info->start_rw, object_info->start_rw,
164       object_info->end_rw - object_info->start_rw);
165
166   xbt_mheap_t heap = process->get_heap();
167   void *start_heap = heap->base;
168   void *end_heap = heap->breakval;
169
170   add_region(n, snapshot, simgrid::mc::RegionType::Heap, nullptr,
171                         start_heap, start_heap,
172                         (char *) end_heap - (char *) start_heap);
173   snapshot->heap_bytes_used = mmalloc_get_bytes_used_remote(
174     heap->heaplimit,
175     process->get_malloc_info());
176
177 #if HAVE_SMPI
178   if (mc_model_checker->process().privatized() && MC_smpi_process_count())
179     // snapshot->privatization_index = smpi_loaded_page
180     mc_model_checker->process().read_variable(
181       "smpi_loaded_page", &snapshot->privatization_index,
182       sizeof(snapshot->privatization_index));
183   else
184 #endif
185     snapshot->privatization_index = simgrid::mc::ProcessIndexMissing;
186 }
187
188 #define PROT_RWX (PROT_READ | PROT_WRITE | PROT_EXEC)
189 #define PROT_RW (PROT_READ | PROT_WRITE)
190 #define PROT_RX (PROT_READ | PROT_EXEC)
191
192 /** \brief Fills the position of the segments (executable, read-only, read/write).
193  * */
194 // TODO, use the ELF segment information for more robustness
195 void find_object_address(
196   std::vector<simgrid::xbt::VmMap> const& maps,
197   simgrid::mc::ObjectInformation* result)
198 {
199   char* name = xbt_basename(result->file_name.c_str());
200
201   for (size_t i = 0; i < maps.size(); ++i) {
202     simgrid::xbt::VmMap const& reg = maps[i];
203     if (maps[i].pathname.empty())
204       continue;
205     char* map_basename = xbt_basename(maps[i].pathname.c_str());
206     if (strcmp(name, map_basename) != 0) {
207       free(map_basename);
208       continue;
209     }
210     free(map_basename);
211
212     // This is the non-GNU_RELRO-part of the data segment:
213     if (reg.prot == PROT_RW) {
214       xbt_assert(!result->start_rw,
215                  "Multiple read-write segments for %s, not supported",
216                  maps[i].pathname.c_str());
217       result->start_rw = (char*) reg.start_addr;
218       result->end_rw = (char*) reg.end_addr;
219
220       // The next VMA might be end of the data segment:
221       if (i + 1 < maps.size()
222           && maps[i + 1].pathname.empty()
223           && maps[i + 1].prot == PROT_RW
224           && maps[i + 1].start_addr == reg.end_addr)
225         result->end_rw = (char*) maps[i + 1].end_addr;
226     }
227
228     // This is the text segment:
229     else if (reg.prot == PROT_RX) {
230       xbt_assert(!result->start_exec,
231                  "Multiple executable segments for %s, not supported",
232                  maps[i].pathname.c_str());
233       result->start_exec = (char*) reg.start_addr;
234       result->end_exec = (char*) reg.end_addr;
235
236       // The next VMA might be end of the data segment:
237       if (i + 1 < maps.size()
238           && maps[i + 1].pathname.empty()
239           && maps[i + 1].prot == PROT_RW
240           && maps[i + 1].start_addr == reg.end_addr) {
241         result->start_rw = (char*) maps[i + 1].start_addr;
242         result->end_rw = (char*) maps[i + 1].end_addr;
243       }
244     }
245
246     // This is the GNU_RELRO-part of the data segment:
247     else if (reg.prot == PROT_READ) {
248       xbt_assert(!result->start_ro,
249                  "Multiple read only segments for %s, not supported",
250                  maps[i].pathname.c_str());
251       result->start_ro = (char*) reg.start_addr;
252       result->end_ro = (char*) reg.end_addr;
253     }
254   }
255
256   result->start = result->start_rw;
257   if ((const void*) result->start_ro > result->start)
258     result->start = result->start_ro;
259   if ((const void*) result->start_exec > result->start)
260     result->start = result->start_exec;
261
262   result->end = result->end_rw;
263   if (result->end_ro && (const void*) result->end_ro < result->end)
264     result->end = result->end_ro;
265   if (result->end_exec && (const void*) result->end_exec > result->end)
266     result->end = result->end_exec;
267
268   xbt_assert(result->start_exec || result->start_rw || result->start_ro);
269
270   free(name);
271 }
272
273 /************************************* Take Snapshot ************************************/
274 /****************************************************************************************/
275
276 /** \brief Checks whether the variable is in scope for a given IP.
277  *
278  *  A variable may be defined only from a given value of IP.
279  *
280  *  \param var   Variable description
281  *  \param frame Scope description
282  *  \param ip    Instruction pointer
283  *  \return      true if the variable is valid
284  * */
285 static bool valid_variable(simgrid::mc::Variable* var,
286                               simgrid::mc::Frame* scope,
287                               const void *ip)
288 {
289   // The variable is not yet valid:
290   if (scope->range.begin() + var->start_scope > (std::uint64_t) ip)
291     return false;
292   else
293     return true;
294 }
295
296 static void fill_local_variables_values(mc_stack_frame_t stack_frame,
297                                            simgrid::mc::Frame* scope,
298                                            int process_index,
299                                            std::vector<s_local_variable>& result)
300 {
301   simgrid::mc::Process* process = &mc_model_checker->process();
302
303   if (!scope->range.contain(stack_frame->ip))
304     return;
305
306   for(simgrid::mc::Variable& current_variable :
307       scope->variables) {
308
309     if (!valid_variable(&current_variable, scope, (void *) stack_frame->ip))
310       continue;
311
312     int region_type;
313     // FIXME, get rid of `region_type`
314     if ((long) stack_frame->ip > (long) process->libsimgrid_info->start_exec)
315       region_type = 1;
316     else
317       region_type = 2;
318
319     s_local_variable_t new_var;
320     new_var.subprogram = stack_frame->frame;
321     new_var.ip = stack_frame->ip;
322     new_var.name = current_variable.name;
323     new_var.type = current_variable.type;
324     new_var.region = region_type;
325     new_var.address = nullptr;
326
327     if (current_variable.address != nullptr)
328       new_var.address = current_variable.address;
329     else if (!current_variable.location_list.empty()) {
330       simgrid::dwarf::Location location =
331         simgrid::dwarf::resolve(
332           current_variable.location_list,
333           current_variable.object_info,
334           &(stack_frame->unw_cursor),
335           (void *) stack_frame->frame_base,
336           &mc_model_checker->process(), process_index);
337
338       if (!location.in_memory())
339         xbt_die("Cannot handle non-address variable");
340       new_var.address = location.address();
341
342     } else
343       xbt_die("No address");
344
345     result.push_back(std::move(new_var));
346   }
347
348   // Recursive processing of nested scopes:
349   for(simgrid::mc::Frame& nested_scope : scope->scopes)
350     fill_local_variables_values(
351       stack_frame, &nested_scope, process_index, result);
352 }
353
354 static std::vector<s_local_variable> get_local_variables_values(
355   std::vector<s_mc_stack_frame_t>& stack_frames, int process_index)
356 {
357   std::vector<s_local_variable> variables;
358   for (s_mc_stack_frame_t& stack_frame : stack_frames)
359     fill_local_variables_values(&stack_frame, stack_frame.frame, process_index, variables);
360   return variables;
361 }
362
363 static std::vector<s_mc_stack_frame_t> unwind_stack_frames(simgrid::mc::UnwindContext* stack_context)
364 {
365   simgrid::mc::Process* process = &mc_model_checker->process();
366   std::vector<s_mc_stack_frame_t> result;
367
368   unw_cursor_t c = stack_context->cursor();
369
370   // TODO, check condition check (unw_init_local==0 means end of frame)
371
372     while (1) {
373
374       s_mc_stack_frame_t stack_frame;
375
376       stack_frame.unw_cursor = c;
377
378       unw_word_t ip, sp;
379
380       unw_get_reg(&c, UNW_REG_IP, &ip);
381       unw_get_reg(&c, UNW_REG_SP, &sp);
382
383       stack_frame.ip = ip;
384       stack_frame.sp = sp;
385
386       // TODO, use real addresses in frame_t instead of fixing it here
387
388       simgrid::mc::Frame* frame = process->find_function(remote(ip));
389       stack_frame.frame = frame;
390
391       if (frame) {
392         stack_frame.frame_name = frame->name;
393         stack_frame.frame_base =
394             (unw_word_t) frame->frame_base(c);
395       } else {
396         stack_frame.frame_base = 0;
397         stack_frame.frame_name = std::string();
398       }
399
400       result.push_back(std::move(stack_frame));
401
402       /* Stop before context switch with maestro */
403       if (frame != nullptr &&
404           frame->name == "smx_ctx_sysv_wrapper")
405         break;
406
407       int ret = unw_step(&c);
408       if (ret == 0)
409         xbt_die("Unexpected end of stack.");
410       else if (ret < 0)
411         xbt_die("Error while unwinding stack");
412     }
413
414   if (result.empty()) {
415     XBT_INFO("unw_init_local failed");
416     xbt_abort();
417   }
418
419   return result;
420 };
421
422 static std::vector<s_mc_snapshot_stack_t> take_snapshot_stacks(simgrid::mc::Snapshot* snapshot)
423 {
424   std::vector<s_mc_snapshot_stack_t> res;
425
426   for (auto const& stack : mc_model_checker->process().stack_areas()) {
427     s_mc_snapshot_stack_t st;
428
429     // Read the context from remote process:
430     unw_context_t context;
431     mc_model_checker->process().read_bytes(
432       &context, sizeof(context), remote(stack.context));
433
434     st.context.initialize(&mc_model_checker->process(), &context);
435
436     st.stack_frames = unwind_stack_frames(&st.context);
437     st.local_variables = get_local_variables_values(st.stack_frames, stack.process_index);
438     st.process_index = stack.process_index;
439
440     unw_word_t sp = st.stack_frames[0].sp;
441
442     res.push_back(std::move(st));
443
444     size_t stack_size =
445       (char*) stack.address + stack.size - (char*) sp;
446     snapshot->stack_sizes.push_back(stack_size);
447   }
448
449   return res;
450
451 }
452
453 static void snapshot_handle_ignore(simgrid::mc::Snapshot* snapshot)
454 {
455   xbt_assert(snapshot->process());
456   
457   // Copy the memory:
458   for (auto const& region : mc_model_checker->process().ignored_regions()) {
459     s_mc_snapshot_ignored_data_t ignored_data;
460     ignored_data.start = (void*)region.addr;
461     ignored_data.data.resize(region.size);
462     // TODO, we should do this once per privatization segment:
463     snapshot->process()->read_bytes(
464       ignored_data.data.data(), region.size, remote(region.addr),
465       simgrid::mc::ProcessIndexDisabled);
466     snapshot->ignored_data.push_back(std::move(ignored_data));
467   }
468
469   // Zero the memory:
470   for(auto const& region : mc_model_checker->process().ignored_regions())
471     snapshot->process()->clear_bytes(remote(region.addr), region.size);
472
473 }
474
475 static void snapshot_ignore_restore(simgrid::mc::Snapshot* snapshot)
476 {
477   for (auto const& ignored_data : snapshot->ignored_data)
478     snapshot->process()->write_bytes(
479       ignored_data.data.data(), ignored_data.data.size(),
480       remote(ignored_data.start));
481 }
482
483 static std::vector<s_fd_infos_t> get_current_fds(pid_t pid)
484 {
485   const size_t fd_dir_path_size = 20;
486   char fd_dir_path[fd_dir_path_size];
487   int res = snprintf(fd_dir_path, fd_dir_path_size,
488     "/proc/%lli/fd", (long long int) pid);
489   xbt_assert(res >= 0);
490   if ((size_t) res > fd_dir_path_size)
491     xbt_die("Unexpected buffer is too small for fd_dir_path");
492
493   DIR* fd_dir = opendir(fd_dir_path);
494   if (fd_dir == nullptr)
495     xbt_die("Cannot open directory '/proc/self/fd'\n");
496
497   std::vector<s_fd_infos_t> fds;
498
499   struct dirent* fd_number;
500   while ((fd_number = readdir(fd_dir))) {
501
502     int fd_value = xbt_str_parse_int(fd_number->d_name, "Found a non-numerical FD: %s. Freaking out!");
503
504     if(fd_value < 3)
505       continue;
506
507     const size_t source_size = 25;
508     char source[25];
509     int res = snprintf(source, source_size, "/proc/%lli/fd/%s",
510         (long long int) pid, fd_number->d_name);
511     xbt_assert(res >= 0);
512     if ((size_t) res > source_size)
513       xbt_die("Unexpected buffer is too small for fd %s", fd_number->d_name);
514
515     const size_t link_size = 200;
516     char link[200];
517     res = readlink(source, link, link_size);
518
519     if (res<0)
520       xbt_die("Could not read link for %s", source);
521     if (res==200)
522       xbt_die("Buffer to small for link of %s", source);
523
524     link[res] = '\0';
525
526 #if HAVE_SMPI
527     if(smpi_is_privatisation_file(link))
528       continue;
529 #endif
530
531     // This is (probably) the DIR* we are reading:
532     // TODO, read all the file entries at once and close the DIR.*
533     if(strcmp(fd_dir_path, link) == 0)
534       continue;
535
536     // We don't handle them.
537     // It does not mean we should silently ignore them however.
538     if (strncmp(link, "pipe:", 5) == 0 || strncmp(link, "socket:", 7) == 0)
539       continue;
540
541     // If dot_output enabled, do not handle the corresponding file
542     if (dot_output != nullptr) {
543       char* link_basename = xbt_basename(link);
544       if (strcmp(link_basename, _sg_mc_dot_output_file) == 0) {
545         free(link_basename);
546         continue;
547       }
548       free(link_basename);
549     }
550
551     // This is probably a shared memory used by lttng-ust:
552     if(strncmp("/dev/shm/ust-shm-tmp-", link, 21)==0)
553       continue;
554
555     // Add an entry for this FD in the snapshot:
556     s_fd_infos_t fd;
557     fd.filename = std::string(link);
558     fd.number = fd_value;
559     fd.flags = fcntl(fd_value, F_GETFL) | fcntl(fd_value, F_GETFD) ;
560     fd.current_position = lseek(fd_value, 0, SEEK_CUR);
561     fds.push_back(std::move(fd));
562   }
563
564   closedir (fd_dir);
565   return fds;
566 }
567
568 std::shared_ptr<simgrid::mc::Snapshot> take_snapshot(int num_state)
569 {
570   XBT_DEBUG("Taking snapshot %i", num_state);
571
572   simgrid::mc::Process* mc_process = &mc_model_checker->process();
573
574   std::shared_ptr<simgrid::mc::Snapshot> snapshot =
575     std::make_shared<simgrid::mc::Snapshot>(mc_process);
576
577   snapshot->num_state = num_state;
578
579   for (auto& p : mc_model_checker->process().simix_processes())
580     snapshot->enabled_processes.insert(p.copy.pid);
581
582   snapshot_handle_ignore(snapshot.get());
583
584   if (_sg_mc_snapshot_fds)
585     snapshot->current_fds = get_current_fds(mc_model_checker->process().pid());
586
587   const bool use_soft_dirty = _sg_mc_sparse_checkpoint && _sg_mc_soft_dirty;
588
589   /* Save the std heap and the writable mapped pages of libsimgrid and binary */
590   get_memory_regions(mc_process, snapshot.get());
591   if (use_soft_dirty)
592     mc_process->reset_soft_dirty();
593
594   snapshot->to_ignore = mc_model_checker->process().ignored_heap();
595
596   if (_sg_mc_visited > 0 || strcmp(_sg_mc_property_file, "")) {
597     snapshot->stacks = take_snapshot_stacks(snapshot.get());
598     if (_sg_mc_hash)
599       snapshot->hash = simgrid::mc::hash(*snapshot);
600     else
601       snapshot->hash = 0;
602   } else
603     snapshot->hash = 0;
604
605   snapshot_ignore_restore(snapshot.get());
606   if (use_soft_dirty)
607     mc_model_checker->parent_snapshot_ = snapshot;
608   return snapshot;
609 }
610
611 static inline
612 void restore_snapshot_regions(simgrid::mc::Snapshot* snapshot)
613 {
614   for(std::unique_ptr<s_mc_mem_region_t> const& region : snapshot->snapshot_regions) {
615     // For privatized, variables we decided it was not necessary to take the snapshot:
616     if (region)
617       restore(region.get());
618   }
619
620 #if HAVE_SMPI
621   // TODO, send a message to implement this in the MCed process
622   if(snapshot->privatization_index >= 0) {
623     // Fix the privatization mmap:
624     s_mc_restore_message message;
625     message.type = MC_MESSAGE_RESTORE;
626     message.index = snapshot->privatization_index;
627     mc_model_checker->process().getChannel().send(message);
628   }
629 #endif
630 }
631
632 static inline
633 void restore_snapshot_fds(simgrid::mc::Snapshot* snapshot)
634 {
635   if (mc_mode == MC_MODE_SERVER)
636     xbt_die("FD snapshot not implemented in client/server mode.");
637
638   for (auto const& fd : snapshot->current_fds) {
639     
640     int new_fd = open(fd.filename.c_str(), fd.flags);
641     if (new_fd < 0)
642       xbt_die("Could not reopen the file %s fo restoring the file descriptor",
643         fd.filename.c_str());
644     if (new_fd != fd.number) {
645       dup2(new_fd, fd.number);
646       close(new_fd);
647     };
648     lseek(fd.number, fd.current_position, SEEK_SET);
649   }
650 }
651
652 void restore_snapshot(std::shared_ptr<simgrid::mc::Snapshot> snapshot)
653 {
654   XBT_DEBUG("Restore snapshot %i", snapshot->num_state);
655   const bool use_soft_dirty = _sg_mc_sparse_checkpoint && _sg_mc_soft_dirty;
656   restore_snapshot_regions(snapshot.get());
657   if (_sg_mc_snapshot_fds)
658     restore_snapshot_fds(snapshot.get());
659   if (use_soft_dirty)
660     mc_model_checker->process().reset_soft_dirty();
661   snapshot_ignore_restore(snapshot.get());
662   mc_model_checker->process().clear_cache();
663   if (use_soft_dirty)
664     mc_model_checker->parent_snapshot_ = snapshot;
665 }
666
667 }
668 }