1 /* Copyright (c) 2008-2015. The SimGrid Team.
2 * All rights reserved. */
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. */
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"
19 #include "src/xbt/mmalloc/mmprivate.h"
21 #include "src/simix/smx_private.h"
23 #include <libunwind.h>
26 #include "src/mc/mc_private.h"
29 #include "src/mc/mc_snapshot.h"
30 #include "src/mc/mc_mmu.h"
31 #include "src/mc/mc_unw.h"
32 #include "src/mc/mc_protocol.h"
33 #include "src/mc/mc_smx.h"
34 #include "mc_hash.hpp"
36 #include "src/mc/RegionSnapshot.hpp"
37 #include "src/mc/ObjectInformation.hpp"
38 #include "src/mc/Frame.hpp"
39 #include "src/mc/Variable.hpp"
41 using simgrid::mc::remote;
45 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(mc_checkpoint, mc,
46 "Logging specific to mc_checkpoint");
53 /************************************ Free functions **************************************/
54 /*****************************************************************************************/
56 /** @brief Restore a region from a snapshot
58 * @param reg Target region
60 static void restore(mc_mem_region_t region)
62 switch(region->storage_type()) {
63 case simgrid::mc::StorageType::NoData:
65 xbt_die("Storage type not supported");
68 case simgrid::mc::StorageType::Flat:
69 mc_model_checker->process().write_bytes(region->flat_data().get(),
70 region->size(), region->permanent_address());
73 case simgrid::mc::StorageType::Chunked:
74 mc_region_restore_sparse(&mc_model_checker->process(), region);
77 case simgrid::mc::StorageType::Privatized:
78 for (auto& p : region->privatized_data())
85 RegionSnapshot privatized_region(
86 RegionType region_type, void *start_addr, void* permanent_addr,
87 std::size_t size, const RegionSnapshot* ref_region
90 size_t process_count = MC_smpi_process_count();
92 // Read smpi_privatisation_regions from MCed:
93 smpi_privatisation_region_t remote_smpi_privatisation_regions;
94 mc_model_checker->process().read_variable(
95 "smpi_privatisation_regions",
96 &remote_smpi_privatisation_regions, sizeof(remote_smpi_privatisation_regions));
97 s_smpi_privatisation_region_t privatisation_regions[process_count];
98 mc_model_checker->process().read_bytes(
99 &privatisation_regions, sizeof(privatisation_regions),
100 remote(remote_smpi_privatisation_regions));
102 std::vector<simgrid::mc::RegionSnapshot> data;
103 data.reserve(process_count);
104 for (size_t i = 0; i < process_count; i++) {
105 const simgrid::mc::RegionSnapshot* ref_privatized_region = nullptr;
106 if (ref_region && ref_region->storage_type() == StorageType::Privatized)
107 ref_privatized_region = &ref_region->privatized_data()[i];
108 data.push_back(simgrid::mc::region(region_type, start_addr,
109 privatisation_regions[i].address, size, ref_privatized_region));
112 simgrid::mc::RegionSnapshot region = simgrid::mc::RegionSnapshot(
113 region_type, start_addr, permanent_addr, size);
114 region.privatized_data(std::move(data));
115 return std::move(region);
120 void add_region(int index, mc_snapshot_t snapshot,
121 simgrid::mc::RegionType type,
122 simgrid::mc::ObjectInformation* object_info,
123 void *start_addr, void* permanent_addr,
126 if (type == simgrid::mc::RegionType::Data)
127 xbt_assert(object_info, "Missing object info for object.");
128 else if (type == simgrid::mc::RegionType::Heap)
129 xbt_assert(!object_info, "Unexpected object info for heap region.");
131 simgrid::mc::RegionSnapshot const* ref_region = nullptr;
132 if (mc_model_checker->parent_snapshot_)
133 ref_region = mc_model_checker->parent_snapshot_->snapshot_regions[index].get();
135 simgrid::mc::RegionSnapshot region;
137 const bool privatization_aware = object_info
138 && mc_model_checker->process().privatized(*object_info);
139 if (privatization_aware && MC_smpi_process_count())
140 region = simgrid::mc::privatized_region(
141 type, start_addr, permanent_addr, size, ref_region);
144 region = simgrid::mc::region(type, start_addr, permanent_addr, size, ref_region);
146 region.object_info(object_info);
147 snapshot->snapshot_regions[index]
148 = std::unique_ptr<simgrid::mc::RegionSnapshot>(
149 new simgrid::mc::RegionSnapshot(std::move(region)));
153 static void get_memory_regions(simgrid::mc::Process* process, mc_snapshot_t snapshot)
155 const size_t n = process->object_infos.size();
156 snapshot->snapshot_regions.resize(n + 1);
158 for (auto const& object_info : process->object_infos)
159 add_region(i++, snapshot, simgrid::mc::RegionType::Data,
161 object_info->start_rw, object_info->start_rw,
162 object_info->end_rw - object_info->start_rw);
164 xbt_mheap_t heap = process->get_heap();
165 void *start_heap = heap->base;
166 void *end_heap = heap->breakval;
168 add_region(n, snapshot, simgrid::mc::RegionType::Heap, nullptr,
169 start_heap, start_heap,
170 (char *) end_heap - (char *) start_heap);
171 snapshot->heap_bytes_used = mmalloc_get_bytes_used_remote(
173 process->get_malloc_info());
176 if (mc_model_checker->process().privatized() && MC_smpi_process_count())
177 // snapshot->privatization_index = smpi_loaded_page
178 mc_model_checker->process().read_variable(
179 "smpi_loaded_page", &snapshot->privatization_index,
180 sizeof(snapshot->privatization_index));
183 snapshot->privatization_index = simgrid::mc::ProcessIndexMissing;
186 /** \brief Fills the position of the segments (executable, read-only, read/write).
188 * `dl_iterate_phdr` would be more robust but would not work in cross-process.
190 void find_object_address(
191 std::vector<simgrid::xbt::VmMap> const& maps,
192 simgrid::mc::ObjectInformation* result)
194 char* file_name = xbt_strdup(result->file_name.c_str());
195 const char *name = xbt_basename(file_name);
196 for (size_t i = 0; i < maps.size(); ++i) {
197 simgrid::xbt::VmMap const& reg = maps[i];
198 if (maps[i].pathname.empty()
199 || strcmp(xbt_basename(maps[i].pathname.c_str()), name)) {
201 } else if ((reg.prot & PROT_WRITE)) {
202 xbt_assert(!result->start_rw,
203 "Multiple read-write segments for %s, not supported",
204 maps[i].pathname.c_str());
205 result->start_rw = (char*) reg.start_addr;
206 result->end_rw = (char*) reg.end_addr;
207 // .bss is usually after the .data:
208 simgrid::xbt::VmMap const& next = maps[i + 1];
209 if (next.pathname.empty() && (next.prot & PROT_WRITE)
210 && next.start_addr == reg.end_addr)
211 result->end_rw = (char*) maps[i + 1].end_addr;
212 } else if ((reg.prot & PROT_READ) && (reg.prot & PROT_EXEC)) {
213 xbt_assert(!result->start_exec,
214 "Multiple executable segments for %s, not supported",
215 maps[i].pathname.c_str());
216 result->start_exec = (char*) reg.start_addr;
217 result->end_exec = (char*) reg.end_addr;
218 } else if ((reg.prot & PROT_READ) && !(reg.prot & PROT_EXEC)) {
219 xbt_assert(!result->start_ro,
220 "Multiple read only segments for %s, not supported",
221 maps[i].pathname.c_str());
222 result->start_ro = (char*) reg.start_addr;
223 result->end_ro = (char*) reg.end_addr;
227 result->start = result->start_rw;
228 if ((const void*) result->start_ro > result->start)
229 result->start = result->start_ro;
230 if ((const void*) result->start_exec > result->start)
231 result->start = result->start_exec;
233 result->end = result->end_rw;
234 if (result->end_ro && (const void*) result->end_ro < result->end)
235 result->end = result->end_ro;
236 if (result->end_exec && (const void*) result->end_exec > result->end)
237 result->end = result->end_exec;
239 xbt_assert(result->start_rw);
240 xbt_assert(result->start_exec);
244 /************************************* Take Snapshot ************************************/
245 /****************************************************************************************/
247 /** \brief Checks whether the variable is in scope for a given IP.
249 * A variable may be defined only from a given value of IP.
251 * \param var Variable description
252 * \param frame Scope description
253 * \param ip Instruction pointer
254 * \return true if the variable is valid
256 static bool valid_variable(simgrid::mc::Variable* var,
257 simgrid::mc::Frame* scope,
260 // The variable is not yet valid:
261 if (scope->range.begin() + var->start_scope > (std::uint64_t) ip)
267 static void fill_local_variables_values(mc_stack_frame_t stack_frame,
268 simgrid::mc::Frame* scope,
270 std::vector<s_local_variable>& result)
272 simgrid::mc::Process* process = &mc_model_checker->process();
274 if (!scope->range.contain(stack_frame->ip))
277 for(simgrid::mc::Variable& current_variable :
280 if (!valid_variable(¤t_variable, scope, (void *) stack_frame->ip))
284 // FIXME, get rid of `region_type`
285 if ((long) stack_frame->ip > (long) process->libsimgrid_info->start_exec)
290 s_local_variable_t new_var;
291 new_var.subprogram = stack_frame->frame;
292 new_var.ip = stack_frame->ip;
293 new_var.name = current_variable.name;
294 new_var.type = current_variable.type;
295 new_var.region = region_type;
296 new_var.address = nullptr;
298 if (current_variable.address != nullptr)
299 new_var.address = current_variable.address;
300 else if (!current_variable.location_list.empty()) {
301 simgrid::dwarf::Location location =
302 simgrid::dwarf::resolve(
303 current_variable.location_list,
304 current_variable.object_info,
305 &(stack_frame->unw_cursor),
306 (void *) stack_frame->frame_base,
307 &mc_model_checker->process(), process_index);
309 if (!location.in_memory())
310 xbt_die("Cannot handle non-address variable");
311 new_var.address = location.address();
314 xbt_die("No address");
316 result.push_back(std::move(new_var));
319 // Recursive processing of nested scopes:
320 for(simgrid::mc::Frame& nested_scope : scope->scopes)
321 fill_local_variables_values(
322 stack_frame, &nested_scope, process_index, result);
325 static std::vector<s_local_variable> get_local_variables_values(
326 std::vector<s_mc_stack_frame_t>& stack_frames, int process_index)
328 std::vector<s_local_variable> variables;
329 for (s_mc_stack_frame_t& stack_frame : stack_frames)
330 fill_local_variables_values(&stack_frame, stack_frame.frame, process_index, variables);
331 return std::move(variables);
334 static std::vector<s_mc_stack_frame_t> unwind_stack_frames(mc_unw_context_t stack_context)
336 simgrid::mc::Process* process = &mc_model_checker->process();
337 std::vector<s_mc_stack_frame_t> result;
341 // TODO, check condition check (unw_init_local==0 means end of frame)
342 if (mc_unw_init_cursor(&c, stack_context) != 0)
343 xbt_die("Could not initialize stack unwinding");
347 s_mc_stack_frame_t stack_frame;
349 stack_frame.unw_cursor = c;
353 unw_get_reg(&c, UNW_REG_IP, &ip);
354 unw_get_reg(&c, UNW_REG_SP, &sp);
359 // TODO, use real addresses in frame_t instead of fixing it here
361 simgrid::mc::Frame* frame = process->find_function(remote(ip));
362 stack_frame.frame = frame;
365 stack_frame.frame_name = frame->name;
366 stack_frame.frame_base =
367 (unw_word_t) frame->frame_base(c);
369 stack_frame.frame_base = 0;
370 stack_frame.frame_name = std::string();
373 result.push_back(std::move(stack_frame));
375 /* Stop before context switch with maestro */
376 if (frame != nullptr &&
377 frame->name == "smx_ctx_sysv_wrapper")
380 int ret = unw_step(&c);
382 xbt_die("Unexpected end of stack.");
384 xbt_die("Error while unwinding stack");
387 if (result.empty()) {
388 XBT_INFO("unw_init_local failed");
392 return std::move(result);
395 static std::vector<s_mc_snapshot_stack_t> take_snapshot_stacks(mc_snapshot_t * snapshot)
397 std::vector<s_mc_snapshot_stack_t> res;
399 for (auto const& stack : mc_model_checker->process().stack_areas()) {
400 s_mc_snapshot_stack_t st;
402 // Read the context from remote process:
403 unw_context_t context;
404 mc_model_checker->process().read_bytes(
405 &context, sizeof(context), remote(stack.context));
407 if (mc_unw_init_context(&st.context, &mc_model_checker->process(),
409 xbt_die("Could not initialise the libunwind context.");
411 st.stack_frames = unwind_stack_frames(&st.context);
412 st.local_variables = get_local_variables_values(st.stack_frames, stack.process_index);
413 st.process_index = stack.process_index;
415 unw_word_t sp = st.stack_frames[0].sp;
417 res.push_back(std::move(st));
420 (char*) stack.address + stack.size - (char*) sp;
421 (*snapshot)->stack_sizes.push_back(stack_size);
424 return std::move(res);
428 static void snapshot_handle_ignore(mc_snapshot_t snapshot)
430 xbt_assert(snapshot->process());
433 for (auto const& region : mc_model_checker->process().ignored_regions()) {
434 s_mc_snapshot_ignored_data_t ignored_data;
435 ignored_data.start = (void*)region.addr;
436 ignored_data.data.resize(region.size);
437 // TODO, we should do this once per privatization segment:
438 snapshot->process()->read_bytes(
439 ignored_data.data.data(), region.size, remote(region.addr),
440 simgrid::mc::ProcessIndexDisabled);
441 snapshot->ignored_data.push_back(std::move(ignored_data));
445 for(auto const& region : mc_model_checker->process().ignored_regions())
446 snapshot->process()->clear_bytes(remote(region.addr), region.size);
450 static void snapshot_ignore_restore(mc_snapshot_t snapshot)
452 for (auto const& ignored_data : snapshot->ignored_data)
453 snapshot->process()->write_bytes(
454 ignored_data.data.data(), ignored_data.data.size(),
455 remote(ignored_data.start));
458 static std::vector<s_fd_infos_t> get_current_fds(pid_t pid)
460 const size_t fd_dir_path_size = 20;
461 char fd_dir_path[fd_dir_path_size];
462 int res = snprintf(fd_dir_path, fd_dir_path_size,
463 "/proc/%lli/fd", (long long int) pid);
464 xbt_assert(res >= 0);
465 if ((size_t) res > fd_dir_path_size)
466 xbt_die("Unexpected buffer is too small for fd_dir_path");
468 DIR* fd_dir = opendir(fd_dir_path);
469 if (fd_dir == nullptr)
470 xbt_die("Cannot open directory '/proc/self/fd'\n");
472 std::vector<s_fd_infos_t> fds;
474 struct dirent* fd_number;
475 while ((fd_number = readdir(fd_dir))) {
477 int fd_value = xbt_str_parse_int(fd_number->d_name, "Found a non-numerical FD: %s. Freaking out!");
482 const size_t source_size = 25;
484 int res = snprintf(source, source_size, "/proc/%lli/fd/%s",
485 (long long int) pid, fd_number->d_name);
486 xbt_assert(res >= 0);
487 if ((size_t) res > source_size)
488 xbt_die("Unexpected buffer is too small for fd %s", fd_number->d_name);
490 const size_t link_size = 200;
492 res = readlink(source, link, link_size);
495 xbt_die("Could not read link for %s", source);
497 xbt_die("Buffer to small for link of %s", source);
502 if(smpi_is_privatisation_file(link))
506 // This is (probably) the DIR* we are reading:
507 // TODO, read all the file entries at once and close the DIR.*
508 if(strcmp(fd_dir_path, link) == 0)
511 // We don't handle them.
512 // It does not mean we should silently ignore them however.
513 if (strncmp(link, "pipe:", 5) == 0 || strncmp(link, "socket:", 7) == 0)
516 // If dot_output enabled, do not handle the corresponding file
517 if (dot_output != nullptr && strcmp(xbt_basename(link), _sg_mc_dot_output_file) == 0)
520 // This is probably a shared memory used by lttng-ust:
521 if(strncmp("/dev/shm/ust-shm-tmp-", link, 21)==0)
524 // Add an entry for this FD in the snapshot:
526 fd.filename = std::string(link);
527 fd.number = fd_value;
528 fd.flags = fcntl(fd_value, F_GETFL) | fcntl(fd_value, F_GETFD) ;
529 fd.current_position = lseek(fd_value, 0, SEEK_CUR);
530 fds.push_back(std::move(fd));
534 return std::move(fds);
537 mc_snapshot_t take_snapshot(int num_state)
539 XBT_DEBUG("Taking snapshot %i", num_state);
541 simgrid::mc::Process* mc_process = &mc_model_checker->process();
543 mc_snapshot_t snapshot = new simgrid::mc::Snapshot(mc_process);
545 snapshot->num_state = num_state;
547 for (auto& p : mc_model_checker->process().simix_processes())
548 snapshot->enabled_processes.insert(p.copy.pid);
550 snapshot_handle_ignore(snapshot);
552 if (_sg_mc_snapshot_fds)
553 snapshot->current_fds = get_current_fds(mc_model_checker->process().pid());
555 const bool use_soft_dirty = _sg_mc_sparse_checkpoint && _sg_mc_soft_dirty;
557 /* Save the std heap and the writable mapped pages of libsimgrid and binary */
558 get_memory_regions(mc_process, snapshot);
560 mc_process->reset_soft_dirty();
562 snapshot->to_ignore = mc_model_checker->process().ignored_heap();
564 if (_sg_mc_visited > 0 || strcmp(_sg_mc_property_file, "")) {
566 take_snapshot_stacks(&snapshot);
568 snapshot->hash = simgrid::mc::hash(*snapshot);
574 snapshot_ignore_restore(snapshot);
576 mc_model_checker->parent_snapshot_ = snapshot;
581 void restore_snapshot_regions(mc_snapshot_t snapshot)
583 for(std::unique_ptr<s_mc_mem_region_t> const& region : snapshot->snapshot_regions) {
584 // For privatized, variables we decided it was not necessary to take the snapshot:
586 restore(region.get());
590 // TODO, send a message to implement this in the MCed process
591 if(snapshot->privatization_index >= 0) {
592 // Fix the privatization mmap:
593 s_mc_restore_message message;
594 message.type = MC_MESSAGE_RESTORE;
595 message.index = snapshot->privatization_index;
596 mc_model_checker->process().send_message(message);
602 void restore_snapshot_fds(mc_snapshot_t snapshot)
604 if (mc_mode == MC_MODE_SERVER)
605 xbt_die("FD snapshot not implemented in client/server mode.");
607 for (auto const& fd : snapshot->current_fds) {
609 int new_fd = open(fd.filename.c_str(), fd.flags);
611 xbt_die("Could not reopen the file %s fo restoring the file descriptor",
612 fd.filename.c_str());
613 if (new_fd != fd.number) {
614 dup2(new_fd, fd.number);
617 lseek(fd.number, fd.current_position, SEEK_SET);
621 void restore_snapshot(mc_snapshot_t snapshot)
623 XBT_DEBUG("Restore snapshot %i", snapshot->num_state);
624 const bool use_soft_dirty = _sg_mc_sparse_checkpoint && _sg_mc_soft_dirty;
625 restore_snapshot_regions(snapshot);
626 if (_sg_mc_snapshot_fds)
627 restore_snapshot_fds(snapshot);
629 mc_model_checker->process().reset_soft_dirty();
630 snapshot_ignore_restore(snapshot);
631 mc_model_checker->process().cache_flags = 0;
633 mc_model_checker->parent_snapshot_ = snapshot;