Logo AND Algorithmique Numérique Distribuée

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