Logo AND Algorithmique Numérique Distribuée

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