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);
166 xbt_mheap_t heap = process->get_heap();
167 void *start_heap = heap->base;
168 void *end_heap = heap->breakval;
170 add_region(n, snapshot, simgrid::mc::RegionType::Heap, nullptr,
171 start_heap, start_heap,
172 (char *) end_heap - (char *) start_heap);
173 snapshot->heap_bytes_used = mmalloc_get_bytes_used_remote(
175 process->get_malloc_info());
178 if (mc_model_checker->process().privatized() && MC_smpi_process_count()) {
179 // snapshot->privatization_index = smpi_loaded_page
180 mc_model_checker->process().read_variable(
181 "smpi_loaded_page", &snapshot->privatization_index,
182 sizeof(snapshot->privatization_index));
186 snapshot->privatization_index = simgrid::mc::ProcessIndexMissing;
190 /** \brief Fills the position of the segments (executable, read-only, read/write).
192 * `dl_iterate_phdr` would be more robust but would not work in cross-process.
194 void find_object_address(
195 std::vector<simgrid::xbt::VmMap> const& maps,
196 simgrid::mc::ObjectInformation* result)
198 char* file_name = xbt_strdup(result->file_name.c_str());
199 const char *name = xbt_basename(file_name);
200 for (size_t i = 0; i < maps.size(); ++i) {
201 simgrid::xbt::VmMap const& reg = maps[i];
202 if (maps[i].pathname.empty()
203 || strcmp(xbt_basename(maps[i].pathname.c_str()), name)) {
205 } else if ((reg.prot & PROT_WRITE)) {
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 // .bss is usually after the .data:
212 simgrid::xbt::VmMap const& next = maps[i + 1];
213 if (next.pathname.empty() && (next.prot & PROT_WRITE)
214 && next.start_addr == reg.end_addr) {
215 result->end_rw = (char*) maps[i + 1].end_addr;
217 } else if ((reg.prot & PROT_READ) && (reg.prot & PROT_EXEC)) {
218 xbt_assert(!result->start_exec,
219 "Multiple executable segments for %s, not supported",
220 maps[i].pathname.c_str());
221 result->start_exec = (char*) reg.start_addr;
222 result->end_exec = (char*) reg.end_addr;
223 } else if ((reg.prot & PROT_READ) && !(reg.prot & PROT_EXEC)) {
224 xbt_assert(!result->start_ro,
225 "Multiple read only segments for %s, not supported",
226 maps[i].pathname.c_str());
227 result->start_ro = (char*) reg.start_addr;
228 result->end_ro = (char*) reg.end_addr;
232 result->start = result->start_rw;
233 if ((const void*) result->start_ro > result->start)
234 result->start = result->start_ro;
235 if ((const void*) result->start_exec > result->start)
236 result->start = result->start_exec;
238 result->end = result->end_rw;
239 if (result->end_ro && (const void*) result->end_ro < result->end)
240 result->end = result->end_ro;
241 if (result->end_exec && (const void*) result->end_exec > result->end)
242 result->end = result->end_exec;
244 xbt_assert(result->start_rw);
245 xbt_assert(result->start_exec);
249 /************************************* Take Snapshot ************************************/
250 /****************************************************************************************/
252 /** \brief Checks whether the variable is in scope for a given IP.
254 * A variable may be defined only from a given value of IP.
256 * \param var Variable description
257 * \param frame Scope description
258 * \param ip Instruction pointer
259 * \return true if the variable is valid
261 static bool valid_variable(simgrid::mc::Variable* var,
262 simgrid::mc::Frame* scope,
265 // The variable is not yet valid:
266 if (scope->range.begin() + var->start_scope > (std::uint64_t) ip)
272 static void fill_local_variables_values(mc_stack_frame_t stack_frame,
273 simgrid::mc::Frame* scope,
275 std::vector<s_local_variable>& result)
277 simgrid::mc::Process* process = &mc_model_checker->process();
279 if (!scope->range.contain(stack_frame->ip))
282 for(simgrid::mc::Variable& current_variable :
285 if (!valid_variable(¤t_variable, scope, (void *) stack_frame->ip))
289 // FIXME, get rid of `region_type`
290 if ((long) stack_frame->ip > (long) process->libsimgrid_info->start_exec)
295 s_local_variable_t new_var;
296 new_var.subprogram = stack_frame->frame;
297 new_var.ip = stack_frame->ip;
298 new_var.name = current_variable.name;
299 new_var.type = current_variable.type;
300 new_var.region = region_type;
301 new_var.address = nullptr;
303 if (current_variable.address != nullptr) {
304 new_var.address = current_variable.address;
305 } else if (!current_variable.location_list.empty()) {
306 simgrid::dwarf::Location location =
307 simgrid::dwarf::resolve(
308 current_variable.location_list,
309 current_variable.object_info,
310 &(stack_frame->unw_cursor),
311 (void *) stack_frame->frame_base,
312 &mc_model_checker->process(), process_index);
314 if (!location.in_memory())
315 xbt_die("Cannot handle non-address variable");
316 new_var.address = location.address();
319 xbt_die("No address");
322 result.push_back(std::move(new_var));
325 // Recursive processing of nested scopes:
326 for(simgrid::mc::Frame& nested_scope : scope->scopes)
327 fill_local_variables_values(
328 stack_frame, &nested_scope, process_index, result);
331 static std::vector<s_local_variable> get_local_variables_values(
332 std::vector<s_mc_stack_frame_t>& stack_frames, int process_index)
334 std::vector<s_local_variable> variables;
335 for (s_mc_stack_frame_t& stack_frame : stack_frames)
336 fill_local_variables_values(&stack_frame, stack_frame.frame, process_index, variables);
337 return std::move(variables);
340 static std::vector<s_mc_stack_frame_t> unwind_stack_frames(mc_unw_context_t stack_context)
342 simgrid::mc::Process* process = &mc_model_checker->process();
343 std::vector<s_mc_stack_frame_t> result;
347 // TODO, check condition check (unw_init_local==0 means end of frame)
348 if (mc_unw_init_cursor(&c, stack_context) != 0) {
350 xbt_die("Could not initialize stack unwinding");
355 s_mc_stack_frame_t stack_frame;
357 stack_frame.unw_cursor = c;
361 unw_get_reg(&c, UNW_REG_IP, &ip);
362 unw_get_reg(&c, UNW_REG_SP, &sp);
367 // TODO, use real addresses in frame_t instead of fixing it here
369 simgrid::mc::Frame* frame = process->find_function(remote(ip));
370 stack_frame.frame = frame;
373 stack_frame.frame_name = frame->name;
374 stack_frame.frame_base =
375 (unw_word_t) frame->frame_base(c);
377 stack_frame.frame_base = 0;
378 stack_frame.frame_name = std::string();
381 result.push_back(std::move(stack_frame));
383 /* Stop before context switch with maestro */
384 if (frame != nullptr &&
385 frame->name == "smx_ctx_sysv_wrapper")
388 int ret = unw_step(&c);
390 xbt_die("Unexpected end of stack.");
391 } else if (ret < 0) {
392 xbt_die("Error while unwinding stack");
396 if (result.empty()) {
397 XBT_INFO("unw_init_local failed");
401 return std::move(result);
404 static std::vector<s_mc_snapshot_stack_t> take_snapshot_stacks(mc_snapshot_t * snapshot)
406 std::vector<s_mc_snapshot_stack_t> res;
408 for (auto const& stack : mc_model_checker->process().stack_areas()) {
409 s_mc_snapshot_stack_t st;
411 // Read the context from remote process:
412 unw_context_t context;
413 mc_model_checker->process().read_bytes(
414 &context, sizeof(context), remote(stack.context));
416 if (mc_unw_init_context(&st.context, &mc_model_checker->process(),
418 xbt_die("Could not initialise the libunwind context.");
420 st.stack_frames = unwind_stack_frames(&st.context);
421 st.local_variables = get_local_variables_values(st.stack_frames, stack.process_index);
422 st.process_index = stack.process_index;
424 unw_word_t sp = st.stack_frames[0].sp;
426 res.push_back(std::move(st));
429 (char*) stack.address + stack.size - (char*) sp;
430 (*snapshot)->stack_sizes.push_back(stack_size);
433 return std::move(res);
437 static void snapshot_handle_ignore(mc_snapshot_t snapshot)
439 xbt_assert(snapshot->process());
442 for (auto const& region : mc_model_checker->process().ignored_regions()) {
443 s_mc_snapshot_ignored_data_t ignored_data;
444 ignored_data.start = (void*)region.addr;
445 ignored_data.data.resize(region.size);
446 // TODO, we should do this once per privatization segment:
447 snapshot->process()->read_bytes(
448 ignored_data.data.data(), region.size, remote(region.addr),
449 simgrid::mc::ProcessIndexDisabled);
450 snapshot->ignored_data.push_back(std::move(ignored_data));
454 for(auto const& region : mc_model_checker->process().ignored_regions()) {
455 snapshot->process()->clear_bytes(remote(region.addr), region.size);
460 static void snapshot_ignore_restore(mc_snapshot_t snapshot)
462 for (auto const& ignored_data : snapshot->ignored_data)
463 snapshot->process()->write_bytes(
464 ignored_data.data.data(), ignored_data.data.size(),
465 remote(ignored_data.start));
468 static std::vector<s_fd_infos_t> get_current_fds(pid_t pid)
470 const size_t fd_dir_path_size = 20;
471 char fd_dir_path[fd_dir_path_size];
472 int res = snprintf(fd_dir_path, fd_dir_path_size,
473 "/proc/%lli/fd", (long long int) pid);
474 xbt_assert(res >= 0);
475 if ((size_t) res > fd_dir_path_size)
476 xbt_die("Unexpected buffer is too small for fd_dir_path");
478 DIR* fd_dir = opendir(fd_dir_path);
479 if (fd_dir == nullptr)
480 xbt_die("Cannot open directory '/proc/self/fd'\n");
482 std::vector<s_fd_infos_t> fds;
484 struct dirent* fd_number;
485 while ((fd_number = readdir(fd_dir))) {
487 int fd_value = xbt_str_parse_int(fd_number->d_name, "Found a non-numerical FD: %s. Freaking out!");
492 const size_t source_size = 25;
494 int res = snprintf(source, source_size, "/proc/%lli/fd/%s",
495 (long long int) pid, fd_number->d_name);
496 xbt_assert(res >= 0);
497 if ((size_t) res > source_size)
498 xbt_die("Unexpected buffer is too small for fd %s", fd_number->d_name);
500 const size_t link_size = 200;
502 res = readlink(source, link, link_size);
504 xbt_die("Could not read link for %s", source);
507 xbt_die("Buffer to small for link of %s", source);
512 if(smpi_is_privatisation_file(link))
516 // This is (probably) the DIR* we are reading:
517 // TODO, read all the file entries at once and close the DIR.*
518 if(strcmp(fd_dir_path, link) == 0)
521 // We don't handle them.
522 // It does not mean we should silently ignore them however.
523 if (strncmp(link, "pipe:", 5) == 0 || strncmp(link, "socket:", 7) == 0)
526 // If dot_output enabled, do not handle the corresponding file
527 if (dot_output != nullptr && strcmp(xbt_basename(link), _sg_mc_dot_output_file) == 0)
530 // This is probably a shared memory used by lttng-ust:
531 if(strncmp("/dev/shm/ust-shm-tmp-", link, 21)==0)
534 // Add an entry for this FD in the snapshot:
536 fd.filename = std::string(link);
537 fd.number = fd_value;
538 fd.flags = fcntl(fd_value, F_GETFL) | fcntl(fd_value, F_GETFD) ;
539 fd.current_position = lseek(fd_value, 0, SEEK_CUR);
540 fds.push_back(std::move(fd));
544 return std::move(fds);
547 mc_snapshot_t take_snapshot(int num_state)
549 XBT_DEBUG("Taking snapshot %i", num_state);
551 simgrid::mc::Process* mc_process = &mc_model_checker->process();
553 mc_snapshot_t snapshot = new simgrid::mc::Snapshot(mc_process);
555 snapshot->num_state = num_state;
557 for (auto& p : mc_model_checker->process().simix_processes())
558 snapshot->enabled_processes.insert(p.copy.pid);
560 snapshot_handle_ignore(snapshot);
562 if (_sg_mc_snapshot_fds)
563 snapshot->current_fds = get_current_fds(mc_model_checker->process().pid());
565 const bool use_soft_dirty = _sg_mc_sparse_checkpoint && _sg_mc_soft_dirty;
567 /* Save the std heap and the writable mapped pages of libsimgrid and binary */
568 get_memory_regions(mc_process, snapshot);
570 mc_process->reset_soft_dirty();
572 snapshot->to_ignore = mc_model_checker->process().ignored_heap();
574 if (_sg_mc_visited > 0 || strcmp(_sg_mc_property_file, "")) {
576 take_snapshot_stacks(&snapshot);
578 snapshot->hash = simgrid::mc::hash(*snapshot);
586 snapshot_ignore_restore(snapshot);
588 mc_model_checker->parent_snapshot_ = snapshot;
593 void restore_snapshot_regions(mc_snapshot_t snapshot)
595 for(std::unique_ptr<s_mc_mem_region_t> const& region : snapshot->snapshot_regions) {
596 // For privatized, variables we decided it was not necessary to take the snapshot:
598 restore(region.get());
602 // TODO, send a message to implement this in the MCed process
603 if(snapshot->privatization_index >= 0) {
604 // Fix the privatization mmap:
605 s_mc_restore_message message;
606 message.type = MC_MESSAGE_RESTORE;
607 message.index = snapshot->privatization_index;
608 mc_model_checker->process().send_message(message);
614 void restore_snapshot_fds(mc_snapshot_t snapshot)
616 if (mc_mode == MC_MODE_SERVER)
617 xbt_die("FD snapshot not implemented in client/server mode.");
619 for (auto const& fd : snapshot->current_fds) {
621 int new_fd = open(fd.filename.c_str(), fd.flags);
623 xbt_die("Could not reopen the file %s fo restoring the file descriptor",
624 fd.filename.c_str());
626 if (new_fd != fd.number) {
627 dup2(new_fd, fd.number);
630 lseek(fd.number, fd.current_position, SEEK_SET);
634 void restore_snapshot(mc_snapshot_t snapshot)
636 XBT_DEBUG("Restore snapshot %i", snapshot->num_state);
637 const bool use_soft_dirty = _sg_mc_sparse_checkpoint && _sg_mc_soft_dirty;
638 restore_snapshot_regions(snapshot);
639 if (_sg_mc_snapshot_fds)
640 restore_snapshot_fds(snapshot);
642 mc_model_checker->process().reset_soft_dirty();
643 snapshot_ignore_restore(snapshot);
644 mc_model_checker->process().cache_flags = 0;
646 mc_model_checker->parent_snapshot_ = snapshot;
653 mc_snapshot_t simcall_HANDLER_mc_snapshot(smx_simcall_t simcall)
655 return simgrid::mc::take_snapshot(1);