Logo AND Algorithmique Numérique Distribuée

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