Logo AND Algorithmique Numérique Distribuée

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