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