Logo AND Algorithmique Numérique Distribuée

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