Logo AND Algorithmique Numérique Distribuée

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