Logo AND Algorithmique Numérique Distribuée

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