Logo AND Algorithmique Numérique Distribuée

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