Logo AND Algorithmique Numérique Distribuée

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