Logo AND Algorithmique Numérique Distribuée

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