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. */
14 #include "src/internal_config.h"
15 #include "src/mc/mc_private.h"
16 #include "xbt/module.h"
17 #include <xbt/mmalloc.h>
18 #include "src/smpi/private.h"
20 #include "src/xbt/mmalloc/mmprivate.h"
22 #include "src/simix/smx_private.h"
24 #include <libunwind.h>
27 #include "src/mc/mc_private.h"
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"
37 #include "src/mc/RegionSnapshot.hpp"
38 #include "src/mc/ObjectInformation.hpp"
39 #include "src/mc/Frame.hpp"
40 #include "src/mc/Variable.hpp"
42 using simgrid::mc::remote;
46 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(mc_checkpoint, mc,
47 "Logging specific to mc_checkpoint");
54 /************************************ Free functions **************************************/
55 /*****************************************************************************************/
57 /** @brief Restore a region from a snapshot
59 * @param reg Target region
61 static void restore(mc_mem_region_t region)
63 switch(region->storage_type()) {
64 case simgrid::mc::StorageType::NoData:
66 xbt_die("Storage type not supported");
69 case simgrid::mc::StorageType::Flat:
70 mc_model_checker->process().write_bytes(region->flat_data().get(),
71 region->size(), region->permanent_address());
74 case simgrid::mc::StorageType::Chunked:
75 mc_region_restore_sparse(&mc_model_checker->process(), region);
78 case simgrid::mc::StorageType::Privatized:
79 for (auto& p : region->privatized_data())
86 RegionSnapshot privatized_region(
87 RegionType region_type, void *start_addr, void* permanent_addr,
88 std::size_t size, const RegionSnapshot* ref_region
91 size_t process_count = MC_smpi_process_count();
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));
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));
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);
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,
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.");
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();
136 simgrid::mc::RegionSnapshot region;
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);
145 region = simgrid::mc::region(type, start_addr, permanent_addr, size, ref_region);
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)));
154 static void get_memory_regions(simgrid::mc::Process* process, mc_snapshot_t snapshot)
156 const size_t n = process->object_infos.size();
157 snapshot->snapshot_regions.resize(n + 1);
159 for (auto const& object_info : process->object_infos)
160 add_region(i++, snapshot, simgrid::mc::RegionType::Data,
162 object_info->start_rw, object_info->start_rw,
163 object_info->end_rw - object_info->start_rw);
165 xbt_mheap_t heap = process->get_heap();
166 void *start_heap = heap->base;
167 void *end_heap = heap->breakval;
169 add_region(n, snapshot, simgrid::mc::RegionType::Heap, nullptr,
170 start_heap, start_heap,
171 (char *) end_heap - (char *) start_heap);
172 snapshot->heap_bytes_used = mmalloc_get_bytes_used_remote(
174 process->get_malloc_info());
177 if (mc_model_checker->process().privatized() && MC_smpi_process_count())
178 // snapshot->privatization_index = smpi_loaded_page
179 mc_model_checker->process().read_variable(
180 "smpi_loaded_page", &snapshot->privatization_index,
181 sizeof(snapshot->privatization_index));
184 snapshot->privatization_index = simgrid::mc::ProcessIndexMissing;
187 /** \brief Fills the position of the segments (executable, read-only, read/write).
189 * `dl_iterate_phdr` would be more robust but would not work in cross-process.
191 void find_object_address(
192 std::vector<simgrid::xbt::VmMap> const& maps,
193 simgrid::mc::ObjectInformation* result)
195 char* file_name = xbt_strdup(result->file_name.c_str());
196 const char *name = xbt_basename(file_name);
197 for (size_t i = 0; i < maps.size(); ++i) {
198 simgrid::xbt::VmMap const& reg = maps[i];
199 if (maps[i].pathname.empty()
200 || strcmp(xbt_basename(maps[i].pathname.c_str()), name)) {
202 } else if ((reg.prot & PROT_WRITE)) {
203 xbt_assert(!result->start_rw,
204 "Multiple read-write segments for %s, not supported",
205 maps[i].pathname.c_str());
206 result->start_rw = (char*) reg.start_addr;
207 result->end_rw = (char*) reg.end_addr;
208 // .bss is usually after the .data:
209 simgrid::xbt::VmMap const& next = maps[i + 1];
210 if (next.pathname.empty() && (next.prot & PROT_WRITE)
211 && next.start_addr == reg.end_addr)
212 result->end_rw = (char*) maps[i + 1].end_addr;
213 } else if ((reg.prot & PROT_READ) && (reg.prot & PROT_EXEC)) {
214 xbt_assert(!result->start_exec,
215 "Multiple executable segments for %s, not supported",
216 maps[i].pathname.c_str());
217 result->start_exec = (char*) reg.start_addr;
218 result->end_exec = (char*) reg.end_addr;
219 } else if ((reg.prot & PROT_READ) && !(reg.prot & PROT_EXEC)) {
220 xbt_assert(!result->start_ro,
221 "Multiple read only segments for %s, not supported",
222 maps[i].pathname.c_str());
223 result->start_ro = (char*) reg.start_addr;
224 result->end_ro = (char*) reg.end_addr;
228 result->start = result->start_rw;
229 if ((const void*) result->start_ro > result->start)
230 result->start = result->start_ro;
231 if ((const void*) result->start_exec > result->start)
232 result->start = result->start_exec;
234 result->end = result->end_rw;
235 if (result->end_ro && (const void*) result->end_ro < result->end)
236 result->end = result->end_ro;
237 if (result->end_exec && (const void*) result->end_exec > result->end)
238 result->end = result->end_exec;
240 xbt_assert(result->start_rw);
241 xbt_assert(result->start_exec);
245 /************************************* Take Snapshot ************************************/
246 /****************************************************************************************/
248 /** \brief Checks whether the variable is in scope for a given IP.
250 * A variable may be defined only from a given value of IP.
252 * \param var Variable description
253 * \param frame Scope description
254 * \param ip Instruction pointer
255 * \return true if the variable is valid
257 static bool valid_variable(simgrid::mc::Variable* var,
258 simgrid::mc::Frame* scope,
261 // The variable is not yet valid:
262 if (scope->range.begin() + var->start_scope > (std::uint64_t) ip)
268 static void fill_local_variables_values(mc_stack_frame_t stack_frame,
269 simgrid::mc::Frame* scope,
271 std::vector<s_local_variable>& result)
273 simgrid::mc::Process* process = &mc_model_checker->process();
275 if (!scope->range.contain(stack_frame->ip))
278 for(simgrid::mc::Variable& current_variable :
281 if (!valid_variable(¤t_variable, scope, (void *) stack_frame->ip))
285 // FIXME, get rid of `region_type`
286 if ((long) stack_frame->ip > (long) process->libsimgrid_info->start_exec)
291 s_local_variable_t new_var;
292 new_var.subprogram = stack_frame->frame;
293 new_var.ip = stack_frame->ip;
294 new_var.name = current_variable.name;
295 new_var.type = current_variable.type;
296 new_var.region = region_type;
297 new_var.address = nullptr;
299 if (current_variable.address != nullptr)
300 new_var.address = current_variable.address;
301 else if (!current_variable.location_list.empty()) {
302 simgrid::dwarf::Location location =
303 simgrid::dwarf::resolve(
304 current_variable.location_list,
305 current_variable.object_info,
306 &(stack_frame->unw_cursor),
307 (void *) stack_frame->frame_base,
308 &mc_model_checker->process(), process_index);
310 if (!location.in_memory())
311 xbt_die("Cannot handle non-address variable");
312 new_var.address = location.address();
315 xbt_die("No address");
317 result.push_back(std::move(new_var));
320 // Recursive processing of nested scopes:
321 for(simgrid::mc::Frame& nested_scope : scope->scopes)
322 fill_local_variables_values(
323 stack_frame, &nested_scope, process_index, result);
326 static std::vector<s_local_variable> get_local_variables_values(
327 std::vector<s_mc_stack_frame_t>& stack_frames, int process_index)
329 std::vector<s_local_variable> variables;
330 for (s_mc_stack_frame_t& stack_frame : stack_frames)
331 fill_local_variables_values(&stack_frame, stack_frame.frame, process_index, variables);
332 return std::move(variables);
335 static std::vector<s_mc_stack_frame_t> unwind_stack_frames(mc_unw_context_t stack_context)
337 simgrid::mc::Process* process = &mc_model_checker->process();
338 std::vector<s_mc_stack_frame_t> result;
342 // TODO, check condition check (unw_init_local==0 means end of frame)
343 if (mc_unw_init_cursor(&c, stack_context) != 0)
344 xbt_die("Could not initialize stack unwinding");
348 s_mc_stack_frame_t stack_frame;
350 stack_frame.unw_cursor = c;
354 unw_get_reg(&c, UNW_REG_IP, &ip);
355 unw_get_reg(&c, UNW_REG_SP, &sp);
360 // TODO, use real addresses in frame_t instead of fixing it here
362 simgrid::mc::Frame* frame = process->find_function(remote(ip));
363 stack_frame.frame = frame;
366 stack_frame.frame_name = frame->name;
367 stack_frame.frame_base =
368 (unw_word_t) frame->frame_base(c);
370 stack_frame.frame_base = 0;
371 stack_frame.frame_name = std::string();
374 result.push_back(std::move(stack_frame));
376 /* Stop before context switch with maestro */
377 if (frame != nullptr &&
378 frame->name == "smx_ctx_sysv_wrapper")
381 int ret = unw_step(&c);
383 xbt_die("Unexpected end of stack.");
385 xbt_die("Error while unwinding stack");
388 if (result.empty()) {
389 XBT_INFO("unw_init_local failed");
393 return std::move(result);
396 static std::vector<s_mc_snapshot_stack_t> take_snapshot_stacks(mc_snapshot_t * snapshot)
398 std::vector<s_mc_snapshot_stack_t> res;
400 for (auto const& stack : mc_model_checker->process().stack_areas()) {
401 s_mc_snapshot_stack_t st;
403 // Read the context from remote process:
404 unw_context_t context;
405 mc_model_checker->process().read_bytes(
406 &context, sizeof(context), remote(stack.context));
408 if (mc_unw_init_context(&st.context, &mc_model_checker->process(),
410 xbt_die("Could not initialise the libunwind context.");
412 st.stack_frames = unwind_stack_frames(&st.context);
413 st.local_variables = get_local_variables_values(st.stack_frames, stack.process_index);
414 st.process_index = stack.process_index;
416 unw_word_t sp = st.stack_frames[0].sp;
418 res.push_back(std::move(st));
421 (char*) stack.address + stack.size - (char*) sp;
422 (*snapshot)->stack_sizes.push_back(stack_size);
425 return std::move(res);
429 static void snapshot_handle_ignore(mc_snapshot_t snapshot)
431 xbt_assert(snapshot->process());
434 for (auto const& region : mc_model_checker->process().ignored_regions()) {
435 s_mc_snapshot_ignored_data_t ignored_data;
436 ignored_data.start = (void*)region.addr;
437 ignored_data.data.resize(region.size);
438 // TODO, we should do this once per privatization segment:
439 snapshot->process()->read_bytes(
440 ignored_data.data.data(), region.size, remote(region.addr),
441 simgrid::mc::ProcessIndexDisabled);
442 snapshot->ignored_data.push_back(std::move(ignored_data));
446 for(auto const& region : mc_model_checker->process().ignored_regions())
447 snapshot->process()->clear_bytes(remote(region.addr), region.size);
451 static void snapshot_ignore_restore(mc_snapshot_t snapshot)
453 for (auto const& ignored_data : snapshot->ignored_data)
454 snapshot->process()->write_bytes(
455 ignored_data.data.data(), ignored_data.data.size(),
456 remote(ignored_data.start));
459 static std::vector<s_fd_infos_t> get_current_fds(pid_t pid)
461 const size_t fd_dir_path_size = 20;
462 char fd_dir_path[fd_dir_path_size];
463 int res = snprintf(fd_dir_path, fd_dir_path_size,
464 "/proc/%lli/fd", (long long int) pid);
465 xbt_assert(res >= 0);
466 if ((size_t) res > fd_dir_path_size)
467 xbt_die("Unexpected buffer is too small for fd_dir_path");
469 DIR* fd_dir = opendir(fd_dir_path);
470 if (fd_dir == nullptr)
471 xbt_die("Cannot open directory '/proc/self/fd'\n");
473 std::vector<s_fd_infos_t> fds;
475 struct dirent* fd_number;
476 while ((fd_number = readdir(fd_dir))) {
478 int fd_value = xbt_str_parse_int(fd_number->d_name, "Found a non-numerical FD: %s. Freaking out!");
483 const size_t source_size = 25;
485 int res = snprintf(source, source_size, "/proc/%lli/fd/%s",
486 (long long int) pid, fd_number->d_name);
487 xbt_assert(res >= 0);
488 if ((size_t) res > source_size)
489 xbt_die("Unexpected buffer is too small for fd %s", fd_number->d_name);
491 const size_t link_size = 200;
493 res = readlink(source, link, link_size);
496 xbt_die("Could not read link for %s", source);
498 xbt_die("Buffer to small for link of %s", source);
503 if(smpi_is_privatisation_file(link))
507 // This is (probably) the DIR* we are reading:
508 // TODO, read all the file entries at once and close the DIR.*
509 if(strcmp(fd_dir_path, link) == 0)
512 // We don't handle them.
513 // It does not mean we should silently ignore them however.
514 if (strncmp(link, "pipe:", 5) == 0 || strncmp(link, "socket:", 7) == 0)
517 // If dot_output enabled, do not handle the corresponding file
518 if (dot_output != nullptr && strcmp(xbt_basename(link), _sg_mc_dot_output_file) == 0)
521 // This is probably a shared memory used by lttng-ust:
522 if(strncmp("/dev/shm/ust-shm-tmp-", link, 21)==0)
525 // Add an entry for this FD in the snapshot:
527 fd.filename = std::string(link);
528 fd.number = fd_value;
529 fd.flags = fcntl(fd_value, F_GETFL) | fcntl(fd_value, F_GETFD) ;
530 fd.current_position = lseek(fd_value, 0, SEEK_CUR);
531 fds.push_back(std::move(fd));
535 return std::move(fds);
538 mc_snapshot_t take_snapshot(int num_state)
540 XBT_DEBUG("Taking snapshot %i", num_state);
542 simgrid::mc::Process* mc_process = &mc_model_checker->process();
544 mc_snapshot_t snapshot = new simgrid::mc::Snapshot(mc_process);
546 snapshot->num_state = num_state;
548 for (auto& p : mc_model_checker->process().simix_processes())
549 snapshot->enabled_processes.insert(p.copy.pid);
551 snapshot_handle_ignore(snapshot);
553 if (_sg_mc_snapshot_fds)
554 snapshot->current_fds = get_current_fds(mc_model_checker->process().pid());
556 const bool use_soft_dirty = _sg_mc_sparse_checkpoint && _sg_mc_soft_dirty;
558 /* Save the std heap and the writable mapped pages of libsimgrid and binary */
559 get_memory_regions(mc_process, snapshot);
561 mc_process->reset_soft_dirty();
563 snapshot->to_ignore = mc_model_checker->process().ignored_heap();
565 if (_sg_mc_visited > 0 || strcmp(_sg_mc_property_file, "")) {
567 take_snapshot_stacks(&snapshot);
569 snapshot->hash = simgrid::mc::hash(*snapshot);
575 snapshot_ignore_restore(snapshot);
577 mc_model_checker->parent_snapshot_ = snapshot;
582 void restore_snapshot_regions(mc_snapshot_t snapshot)
584 for(std::unique_ptr<s_mc_mem_region_t> const& region : snapshot->snapshot_regions) {
585 // For privatized, variables we decided it was not necessary to take the snapshot:
587 restore(region.get());
591 // TODO, send a message to implement this in the MCed process
592 if(snapshot->privatization_index >= 0) {
593 // Fix the privatization mmap:
594 s_mc_restore_message message;
595 message.type = MC_MESSAGE_RESTORE;
596 message.index = snapshot->privatization_index;
597 mc_model_checker->process().send_message(message);
603 void restore_snapshot_fds(mc_snapshot_t snapshot)
605 if (mc_mode == MC_MODE_SERVER)
606 xbt_die("FD snapshot not implemented in client/server mode.");
608 for (auto const& fd : snapshot->current_fds) {
610 int new_fd = open(fd.filename.c_str(), fd.flags);
612 xbt_die("Could not reopen the file %s fo restoring the file descriptor",
613 fd.filename.c_str());
614 if (new_fd != fd.number) {
615 dup2(new_fd, fd.number);
618 lseek(fd.number, fd.current_position, SEEK_SET);
622 void restore_snapshot(mc_snapshot_t snapshot)
624 XBT_DEBUG("Restore snapshot %i", snapshot->num_state);
625 const bool use_soft_dirty = _sg_mc_sparse_checkpoint && _sg_mc_soft_dirty;
626 restore_snapshot_regions(snapshot);
627 if (_sg_mc_snapshot_fds)
628 restore_snapshot_fds(snapshot);
630 mc_model_checker->process().reset_soft_dirty();
631 snapshot_ignore_restore(snapshot);
632 mc_model_checker->process().cache_flags = 0;
634 mc_model_checker->parent_snapshot_ = snapshot;