1 /* Copyright (c) 2014-2017. The SimGrid Team. All rights reserved. */
3 /* This program is free software; you can redistribute it and/or modify it
4 * under the terms of the license (GNU LGPL) which comes with this package. */
6 #define _FILE_OFFSET_BITS 64 /* needed for pread_whole to work as expected on 32bits */
17 #include <sys/ptrace.h>
22 #include <sys/mman.h> // PROT_*
23 #include <sys/types.h>
30 #include <libunwind-ptrace.h>
31 #include <libunwind.h>
34 #include "xbt/file.hpp"
36 #include <xbt/mmalloc.h>
38 #include "src/mc/mc_smx.hpp"
39 #include "src/mc/mc_snapshot.hpp"
40 #include "src/mc/mc_unw.hpp"
42 #include "src/mc/AddressSpace.hpp"
43 #include "src/mc/ObjectInformation.hpp"
44 #include "src/mc/Variable.hpp"
45 #include "src/mc/remote/RemoteClient.hpp"
47 using simgrid::mc::remote;
49 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(mc_process, mc, "MC process information");
56 // List of library which memory segments are not considered:
57 static const std::vector<std::string> filtered_libraries = {
60 #elif defined __FreeBSD__
63 "libkvm", /* kernel data access library */
64 "libprocstat", /* process and file information retrieval */
65 "libthr", /* thread library */
68 "libasan", /* gcc sanitizers */
69 "libargp", /* workarounds for glibc-less systems */
75 "libboost_context-mt",
102 static bool is_simgrid_lib(const std::string& libname)
104 return libname == "libsimgrid";
107 static bool is_filtered_lib(const std::string& libname)
109 return std::find(begin(filtered_libraries), end(filtered_libraries), libname) != end(filtered_libraries);
112 static std::string get_lib_name(const std::string& pathname)
114 static const std::regex so_re("\\.so[\\.0-9]*$", std::regex_constants::basic);
115 static const std::regex version_re("-[\\.0-9-]*$", std::regex_constants::basic);
116 std::string map_basename = simgrid::xbt::Path(pathname).getBasename();
120 if (std::regex_search(map_basename, match, so_re)) {
121 libname = match.prefix();
123 // Strip the version suffix:
124 if (std::regex_search(libname, match, version_re))
125 libname = match.prefix();
131 static ssize_t pread_whole(int fd, void* buf, size_t count, off_t offset)
133 char* buffer = (char*)buf;
134 ssize_t real_count = count;
136 ssize_t res = pread(fd, buffer, count, offset);
143 else if (errno != EINTR) {
144 perror("pread_whole");
151 static ssize_t pwrite_whole(int fd, const void* buf, size_t count, off_t offset)
153 const char* buffer = (const char*)buf;
154 ssize_t real_count = count;
156 ssize_t res = pwrite(fd, buffer, count, offset);
163 else if (errno != EINTR)
169 static pthread_once_t zero_buffer_flag = PTHREAD_ONCE_INIT;
170 static const void* zero_buffer;
171 static const size_t zero_buffer_size = 10 * 4096;
173 static void zero_buffer_init()
175 int fd = open("/dev/zero", O_RDONLY);
177 xbt_die("Could not open /dev/zero");
178 zero_buffer = mmap(nullptr, zero_buffer_size, PROT_READ, MAP_SHARED, fd, 0);
179 if (zero_buffer == MAP_FAILED)
180 xbt_die("Could not map the zero buffer");
184 int open_vm(pid_t pid, int flags)
186 const size_t buffer_size = 30;
187 char buffer[buffer_size];
188 int res = snprintf(buffer, buffer_size, "/proc/%lli/mem", (long long)pid);
189 if (res < 0 || (size_t)res >= buffer_size) {
190 errno = ENAMETOOLONG;
193 return open(buffer, flags);
198 RemoteClient::RemoteClient(pid_t pid, int sockfd) : AddressSpace(this), pid_(pid), channel_(sockfd), running_(true)
202 void RemoteClient::init()
204 this->memory_map_ = simgrid::xbt::get_memory_map(this->pid_);
205 this->init_memory_map_info();
207 int fd = open_vm(this->pid_, O_RDWR);
209 xbt_die("Could not open file for process virtual address space");
210 this->memory_file = fd;
212 // Read std_heap (is a struct mdesc*):
213 simgrid::mc::Variable* std_heap_var = this->find_variable("__mmalloc_default_mdp");
214 if (not std_heap_var)
215 xbt_die("No heap information in the target process");
216 if (not std_heap_var->address)
217 xbt_die("No constant address for this variable");
218 this->read_bytes(&this->heap_address, sizeof(mdesc*), remote(std_heap_var->address),
219 simgrid::mc::ProcessIndexDisabled);
221 this->smx_actors_infos.clear();
222 this->smx_dead_actors_infos.clear();
223 this->unw_addr_space = simgrid::mc::UnwindContext::createUnwindAddressSpace();
224 this->unw_underlying_addr_space = simgrid::unw::create_addr_space();
225 this->unw_underlying_context = simgrid::unw::create_context(this->unw_underlying_addr_space, this->pid_);
228 RemoteClient::~RemoteClient()
230 if (this->memory_file >= 0)
231 close(this->memory_file);
233 if (this->unw_underlying_addr_space != unw_local_addr_space) {
234 if (this->unw_underlying_addr_space)
235 unw_destroy_addr_space(this->unw_underlying_addr_space);
236 if (this->unw_underlying_context)
237 _UPT_destroy(this->unw_underlying_context);
240 unw_destroy_addr_space(this->unw_addr_space);
243 /** Refresh the information about the process
245 * Do not use directly, this is used by the getters when appropriate
246 * in order to have fresh data.
248 void RemoteClient::refresh_heap()
250 // Read/dereference/refresh the std_heap pointer:
252 this->heap = std::unique_ptr<s_xbt_mheap_t>(new s_xbt_mheap_t());
253 this->read_bytes(this->heap.get(), sizeof(mdesc), remote(this->heap_address), simgrid::mc::ProcessIndexDisabled);
254 this->cache_flags_ |= RemoteClient::cache_heap;
257 /** Refresh the information about the process
259 * Do not use direclty, this is used by the getters when appropriate
260 * in order to have fresh data.
262 void RemoteClient::refresh_malloc_info()
264 // Refresh process->heapinfo:
265 if (this->cache_flags_ & RemoteClient::cache_malloc)
267 size_t count = this->heap->heaplimit + 1;
268 if (this->heap_info.size() < count)
269 this->heap_info.resize(count);
270 this->read_bytes(this->heap_info.data(), count * sizeof(malloc_info), remote(this->heap->heapinfo),
271 simgrid::mc::ProcessIndexDisabled);
272 this->cache_flags_ |= RemoteClient::cache_malloc;
275 /** @brief Finds the range of the different memory segments and binary paths */
276 void RemoteClient::init_memory_map_info()
278 XBT_DEBUG("Get debug information ...");
279 this->maestro_stack_start_ = nullptr;
280 this->maestro_stack_end_ = nullptr;
281 this->object_infos.resize(0);
282 this->binary_info = nullptr;
283 this->libsimgrid_info = nullptr;
285 std::vector<simgrid::xbt::VmMap> const& maps = this->memory_map_;
287 const char* current_name = nullptr;
289 this->object_infos.clear();
291 for (size_t i = 0; i < maps.size(); i++) {
292 simgrid::xbt::VmMap const& reg = maps[i];
293 const char* pathname = maps[i].pathname.c_str();
296 if (maps[i].pathname.empty()) {
297 current_name = nullptr;
301 // [stack], [vvar], [vsyscall], [vdso] ...
302 if (pathname[0] == '[') {
303 if ((reg.prot & PROT_WRITE) && not memcmp(pathname, "[stack]", 7)) {
304 this->maestro_stack_start_ = remote(reg.start_addr);
305 this->maestro_stack_end_ = remote(reg.end_addr);
307 current_name = nullptr;
311 if (current_name && strcmp(current_name, pathname) == 0)
314 current_name = pathname;
315 if (not(reg.prot & PROT_READ) && (reg.prot & PROT_EXEC))
318 const bool is_executable = not i;
320 if (not is_executable) {
321 libname = get_lib_name(pathname);
322 if (is_filtered_lib(libname)) {
327 std::shared_ptr<simgrid::mc::ObjectInformation> info =
328 simgrid::mc::createObjectInformation(this->memory_map_, pathname);
329 this->object_infos.push_back(info);
331 this->binary_info = info;
332 else if (is_simgrid_lib(libname))
333 this->libsimgrid_info = info;
336 // Resolve time (including across different objects):
337 for (auto const& object_info : this->object_infos)
338 postProcessObjectInformation(this, object_info.get());
340 xbt_assert(this->maestro_stack_start_, "Did not find maestro_stack_start");
341 xbt_assert(this->maestro_stack_end_, "Did not find maestro_stack_end");
343 XBT_DEBUG("Get debug information done !");
346 std::shared_ptr<simgrid::mc::ObjectInformation> RemoteClient::find_object_info(RemotePtr<void> addr) const
348 for (auto const& object_info : this->object_infos)
349 if (addr.address() >= (std::uint64_t)object_info->start && addr.address() <= (std::uint64_t)object_info->end)
354 std::shared_ptr<ObjectInformation> RemoteClient::find_object_info_exec(RemotePtr<void> addr) const
356 for (std::shared_ptr<ObjectInformation> const& info : this->object_infos)
357 if (addr.address() >= (std::uint64_t)info->start_exec && addr.address() <= (std::uint64_t)info->end_exec)
362 std::shared_ptr<ObjectInformation> RemoteClient::find_object_info_rw(RemotePtr<void> addr) const
364 for (std::shared_ptr<ObjectInformation> const& info : this->object_infos)
365 if (addr.address() >= (std::uint64_t)info->start_rw && addr.address() <= (std::uint64_t)info->end_rw)
370 simgrid::mc::Frame* RemoteClient::find_function(RemotePtr<void> ip) const
372 std::shared_ptr<simgrid::mc::ObjectInformation> info = this->find_object_info_exec(ip);
373 return info ? info->find_function((void*)ip.address()) : nullptr;
376 /** Find (one occurrence of) the named variable definition
378 simgrid::mc::Variable* RemoteClient::find_variable(const char* name) const
380 // First lookup the variable in the executable shared object.
381 // A global variable used directly by the executable code from a library
382 // is reinstanciated in the executable memory .data/.bss.
383 // We need to look up the variable in the executable first.
384 if (this->binary_info) {
385 std::shared_ptr<simgrid::mc::ObjectInformation> const& info = this->binary_info;
386 simgrid::mc::Variable* var = info->find_variable(name);
391 for (std::shared_ptr<simgrid::mc::ObjectInformation> const& info : this->object_infos) {
392 simgrid::mc::Variable* var = info->find_variable(name);
400 void RemoteClient::read_variable(const char* name, void* target, size_t size) const
402 simgrid::mc::Variable* var = this->find_variable(name);
403 xbt_assert(var->address, "No simple location for this variable");
404 xbt_assert(var->type->full_type, "Partial type for %s, cannot check size", name);
405 xbt_assert((size_t)var->type->full_type->byte_size == size, "Unexpected size for %s (expected %zu, was %zu)", name,
406 size, (size_t)var->type->full_type->byte_size);
407 this->read_bytes(target, size, remote(var->address));
410 std::string RemoteClient::read_string(RemotePtr<char> address) const
415 // TODO, use std::vector with .data() in C++17 to avoid useless copies
416 std::vector<char> res(128);
420 ssize_t c = pread(this->memory_file, res.data() + off, res.size() - off, (off_t)address.address() + off);
425 xbt_die("Could not read from from remote process");
428 xbt_die("Could not read string from remote process");
430 void* p = memchr(res.data() + off, '\0', c);
432 return std::string(res.data());
435 if (off == (off_t)res.size())
436 res.resize(res.size() * 2);
440 const void* RemoteClient::read_bytes(void* buffer, std::size_t size, RemotePtr<void> address, int process_index,
441 ReadOptions options) const
443 if (process_index != simgrid::mc::ProcessIndexDisabled) {
444 std::shared_ptr<simgrid::mc::ObjectInformation> const& info = this->find_object_info_rw((void*)address.address());
445 // Segment overlap is not handled.
447 if (info.get() && this->privatized(*info)) {
448 if (process_index < 0)
449 xbt_die("Missing process index");
450 if (process_index >= (int)MC_smpi_process_count())
451 xbt_die("Invalid process index");
453 // Read smpi_privatization_regions from MCed:
454 smpi_privatization_region_t remote_smpi_privatization_regions =
455 mc_model_checker->process().read_variable<smpi_privatization_region_t>("smpi_privatization_regions");
457 s_smpi_privatization_region_t privatization_region =
458 mc_model_checker->process().read<s_smpi_privatization_region_t>(
459 remote(remote_smpi_privatization_regions + process_index));
461 // Address translation in the privatization segment:
462 size_t offset = address.address() - (std::uint64_t)info->start_rw;
463 address = remote((char*)privatization_region.address + offset);
467 if (pread_whole(this->memory_file, buffer, size, (size_t)address.address()) < 0)
468 xbt_die("Read at %p from process %lli failed", (void*)address.address(), (long long)this->pid_);
472 /** Write data to a process memory
474 * @param buffer local memory address (source)
475 * @param len data size
476 * @param address target process memory address (target)
478 void RemoteClient::write_bytes(const void* buffer, size_t len, RemotePtr<void> address)
480 if (pwrite_whole(this->memory_file, buffer, len, (size_t)address.address()) < 0)
481 xbt_die("Write to process %lli failed", (long long)this->pid_);
484 void RemoteClient::clear_bytes(RemotePtr<void> address, size_t len)
486 pthread_once(&zero_buffer_flag, zero_buffer_init);
488 size_t s = len > zero_buffer_size ? zero_buffer_size : len;
489 this->write_bytes(zero_buffer, s, address);
490 address = remote((char*)address.address() + s);
495 void RemoteClient::ignore_region(std::uint64_t addr, std::size_t size)
497 IgnoredRegion region;
501 if (ignored_regions_.empty()) {
502 ignored_regions_.push_back(region);
506 unsigned int cursor = 0;
507 IgnoredRegion* current_region = nullptr;
510 int end = ignored_regions_.size() - 1;
511 while (start <= end) {
512 cursor = (start + end) / 2;
513 current_region = &ignored_regions_[cursor];
514 if (current_region->addr == addr) {
515 if (current_region->size == size)
517 else if (current_region->size < size)
521 } else if (current_region->addr < addr)
527 std::size_t position;
528 if (current_region->addr == addr) {
529 if (current_region->size < size)
530 position = cursor + 1;
533 } else if (current_region->addr < addr)
534 position = cursor + 1;
537 ignored_regions_.insert(ignored_regions_.begin() + position, region);
540 void RemoteClient::ignore_heap(IgnoredHeapRegion const& region)
542 if (ignored_heap_.empty()) {
543 ignored_heap_.push_back(std::move(region));
547 typedef std::vector<IgnoredHeapRegion>::size_type size_type;
550 size_type end = ignored_heap_.size() - 1;
552 // Binary search the position of insertion:
554 while (start <= end) {
555 cursor = start + (end - start) / 2;
556 auto& current_region = ignored_heap_[cursor];
557 if (current_region.address == region.address)
559 else if (current_region.address < region.address)
561 else if (cursor != 0)
568 // Insert it mc_heap_ignore_region_t:
569 if (ignored_heap_[cursor].address < region.address)
571 ignored_heap_.insert(ignored_heap_.begin() + cursor, region);
574 void RemoteClient::unignore_heap(void* address, size_t size)
576 typedef std::vector<IgnoredHeapRegion>::size_type size_type;
579 size_type end = ignored_heap_.size() - 1;
583 while (start <= end) {
584 cursor = (start + end) / 2;
585 auto& region = ignored_heap_[cursor];
586 if (region.address == address) {
587 ignored_heap_.erase(ignored_heap_.begin() + cursor);
589 } else if (region.address < address)
591 else if ((char*)region.address <= ((char*)address + size)) {
592 ignored_heap_.erase(ignored_heap_.begin() + cursor);
594 } else if (cursor != 0)
602 void RemoteClient::ignore_local_variable(const char* var_name, const char* frame_name)
604 if (frame_name != nullptr && strcmp(frame_name, "*") == 0)
605 frame_name = nullptr;
606 for (std::shared_ptr<simgrid::mc::ObjectInformation> const& info : this->object_infos)
607 info->remove_local_variable(var_name, frame_name);
610 std::vector<simgrid::mc::ActorInformation>& RemoteClient::actors()
612 this->refresh_simix();
613 return smx_actors_infos;
616 std::vector<simgrid::mc::ActorInformation>& RemoteClient::dead_actors()
618 this->refresh_simix();
619 return smx_dead_actors_infos;
622 void RemoteClient::dumpStack()
624 unw_addr_space_t as = unw_create_addr_space(&_UPT_accessors, BYTE_ORDER);
626 XBT_ERROR("Could not initialize ptrace address space");
630 void* context = _UPT_create(this->pid_);
631 if (context == nullptr) {
632 unw_destroy_addr_space(as);
633 XBT_ERROR("Could not initialize ptrace context");
638 if (unw_init_remote(&cursor, as, context) != 0) {
639 _UPT_destroy(context);
640 unw_destroy_addr_space(as);
641 XBT_ERROR("Could not initialiez ptrace cursor");
645 simgrid::mc::dumpStack(stderr, cursor);
647 _UPT_destroy(context);
648 unw_destroy_addr_space(as);
652 bool RemoteClient::actor_is_enabled(aid_t pid)
654 s_mc_message_actor_enabled msg{MC_MESSAGE_ACTOR_ENABLED, pid};
655 process()->getChannel().send(msg);
656 char buff[MC_MESSAGE_LENGTH];
657 ssize_t received = process()->getChannel().receive(buff, MC_MESSAGE_LENGTH, true);
658 xbt_assert(received == sizeof(s_mc_message_int), "Unexpected size in answer to ACTOR_ENABLED");
659 return ((mc_message_int_t*)buff)->value;