Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
32be2092c8f6c5f416acb65d95d6f62ebacbdc9a
[simgrid.git] / src / mc / remote / RemoteClient.cpp
1 /* Copyright (c) 2014-2017. The SimGrid Team. All rights reserved.          */
2
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. */
5
6 #define _FILE_OFFSET_BITS 64 /* needed for pread_whole to work as expected on 32bits */
7
8 #include <algorithm>
9 #include <cassert>
10 #include <cerrno>
11 #include <cstddef>
12 #include <cstdint>
13 #include <regex>
14 #include <string>
15 #include <vector>
16
17 #include <sys/ptrace.h>
18
19 #include <cstdio>
20
21 #include <fcntl.h>
22 #include <sys/mman.h> // PROT_*
23 #include <sys/types.h>
24 #include <unistd.h>
25
26 #include <pthread.h>
27
28 #include <libgen.h>
29
30 #include <libunwind-ptrace.h>
31 #include <libunwind.h>
32
33 #include "xbt/base.h"
34 #include "xbt/file.hpp"
35 #include "xbt/log.h"
36 #include <xbt/mmalloc.h>
37
38 #include "src/mc/mc_smx.hpp"
39 #include "src/mc/mc_snapshot.hpp"
40 #include "src/mc/mc_unw.hpp"
41
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"
46
47 using simgrid::mc::remote;
48
49 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(mc_process, mc, "MC process information");
50
51 namespace simgrid {
52 namespace mc {
53
54 // ***** Helper stuff
55
56 // List of library which memory segments are not considered:
57 static const std::vector<std::string> filtered_libraries = {
58 #ifdef __linux__
59     "ld",
60 #elif defined __FreeBSD__
61     "ld-elf",
62     "ld-elf32",
63     "libkvm",      /* kernel data access library */
64     "libprocstat", /* process and file information retrieval */
65     "libthr",      /* thread library */
66     "libutil",
67 #endif
68     "libasan", /* gcc sanitizers */
69     "libargp", /* workarounds for glibc-less systems */
70     "libtsan",
71     "libubsan",
72     "libbz2",
73     "libboost_chrono",
74     "libboost_context",
75     "libboost_context-mt",
76     "libboost_system",
77     "libboost_thread",
78     "libc",
79     "libc++",
80     "libcdt",
81     "libcgraph",
82     "libcrypto",
83     "libcxxrt",
84     "libdl",
85     "libdw",
86     "libelf",
87     "libevent",
88     "libgcc_s",
89     "liblua5.1",
90     "liblua5.3",
91     "liblzma",
92     "libm",
93     "libpthread",
94     "librt",
95     "libstdc++",
96     "libunwind",
97     "libunwind-x86_64",
98     "libunwind-x86",
99     "libunwind-ptrace",
100     "libz"};
101
102 static bool is_simgrid_lib(const std::string& libname)
103 {
104   return libname == "libsimgrid";
105 }
106
107 static bool is_filtered_lib(const std::string& libname)
108 {
109   return std::find(begin(filtered_libraries), end(filtered_libraries), libname) != end(filtered_libraries);
110 }
111
112 static std::string get_lib_name(const std::string& pathname)
113 {
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();
117   std::string libname;
118
119   std::smatch match;
120   if (std::regex_search(map_basename, match, so_re)) {
121     libname = match.prefix();
122
123     // Strip the version suffix:
124     if (std::regex_search(libname, match, version_re))
125       libname = match.prefix();
126   }
127
128   return libname;
129 }
130
131 static ssize_t pread_whole(int fd, void* buf, size_t count, off_t offset)
132 {
133   char* buffer       = (char*)buf;
134   ssize_t real_count = count;
135   while (count) {
136     ssize_t res = pread(fd, buffer, count, offset);
137     if (res > 0) {
138       count -= res;
139       buffer += res;
140       offset += res;
141     } else if (res == 0)
142       return -1;
143     else if (errno != EINTR) {
144       perror("pread_whole");
145       return -1;
146     }
147   }
148   return real_count;
149 }
150
151 static ssize_t pwrite_whole(int fd, const void* buf, size_t count, off_t offset)
152 {
153   const char* buffer = (const char*)buf;
154   ssize_t real_count = count;
155   while (count) {
156     ssize_t res = pwrite(fd, buffer, count, offset);
157     if (res > 0) {
158       count -= res;
159       buffer += res;
160       offset += res;
161     } else if (res == 0)
162       return -1;
163     else if (errno != EINTR)
164       return -1;
165   }
166   return real_count;
167 }
168
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;
172
173 static void zero_buffer_init()
174 {
175   int fd = open("/dev/zero", O_RDONLY);
176   if (fd < 0)
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");
181   close(fd);
182 }
183
184 int open_vm(pid_t pid, int flags)
185 {
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;
191     return -1;
192   }
193   return open(buffer, flags);
194 }
195
196 // ***** Process
197
198 RemoteClient::RemoteClient(pid_t pid, int sockfd) : AddressSpace(this), pid_(pid), channel_(sockfd), running_(true)
199 {
200 }
201
202 void RemoteClient::init()
203 {
204   this->memory_map_ = simgrid::xbt::get_memory_map(this->pid_);
205   this->init_memory_map_info();
206
207   int fd = open_vm(this->pid_, O_RDWR);
208   if (fd < 0)
209     xbt_die("Could not open file for process virtual address space");
210   this->memory_file = fd;
211
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);
220
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_);
226 }
227
228 RemoteClient::~RemoteClient()
229 {
230   if (this->memory_file >= 0)
231     close(this->memory_file);
232
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);
238   }
239
240   unw_destroy_addr_space(this->unw_addr_space);
241 }
242
243 /** Refresh the information about the process
244  *
245  *  Do not use directly, this is used by the getters when appropriate
246  *  in order to have fresh data.
247  */
248 void RemoteClient::refresh_heap()
249 {
250   // Read/dereference/refresh the std_heap pointer:
251   if (not this->heap)
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;
255 }
256
257 /** Refresh the information about the process
258  *
259  *  Do not use direclty, this is used by the getters when appropriate
260  *  in order to have fresh data.
261  * */
262 void RemoteClient::refresh_malloc_info()
263 {
264   // Refresh process->heapinfo:
265   if (this->cache_flags_ & RemoteClient::cache_malloc)
266     return;
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;
273 }
274
275 /** @brief Finds the range of the different memory segments and binary paths */
276 void RemoteClient::init_memory_map_info()
277 {
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;
284
285   std::vector<simgrid::xbt::VmMap> const& maps = this->memory_map_;
286
287   const char* current_name = nullptr;
288
289   this->object_infos.clear();
290
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();
294
295     // Nothing to do
296     if (maps[i].pathname.empty()) {
297       current_name = nullptr;
298       continue;
299     }
300
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);
306       }
307       current_name = nullptr;
308       continue;
309     }
310
311     if (current_name && strcmp(current_name, pathname) == 0)
312       continue;
313
314     current_name = pathname;
315     if (not(reg.prot & PROT_READ) && (reg.prot & PROT_EXEC))
316       continue;
317
318     const bool is_executable = not i;
319     std::string libname;
320     if (not is_executable) {
321       libname = get_lib_name(pathname);
322       if (is_filtered_lib(libname)) {
323         continue;
324       }
325     }
326
327     std::shared_ptr<simgrid::mc::ObjectInformation> info =
328         simgrid::mc::createObjectInformation(this->memory_map_, pathname);
329     this->object_infos.push_back(info);
330     if (is_executable)
331       this->binary_info = info;
332     else if (is_simgrid_lib(libname))
333       this->libsimgrid_info = info;
334   }
335
336   // Resolve time (including across different objects):
337   for (auto const& object_info : this->object_infos)
338     postProcessObjectInformation(this, object_info.get());
339
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");
342
343   XBT_DEBUG("Get debug information done !");
344 }
345
346 std::shared_ptr<simgrid::mc::ObjectInformation> RemoteClient::find_object_info(RemotePtr<void> addr) const
347 {
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)
350       return object_info;
351   return nullptr;
352 }
353
354 std::shared_ptr<ObjectInformation> RemoteClient::find_object_info_exec(RemotePtr<void> addr) const
355 {
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)
358       return info;
359   return nullptr;
360 }
361
362 std::shared_ptr<ObjectInformation> RemoteClient::find_object_info_rw(RemotePtr<void> addr) const
363 {
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)
366       return info;
367   return nullptr;
368 }
369
370 simgrid::mc::Frame* RemoteClient::find_function(RemotePtr<void> ip) const
371 {
372   std::shared_ptr<simgrid::mc::ObjectInformation> info = this->find_object_info_exec(ip);
373   return info ? info->find_function((void*)ip.address()) : nullptr;
374 }
375
376 /** Find (one occurrence of) the named variable definition
377  */
378 simgrid::mc::Variable* RemoteClient::find_variable(const char* name) const
379 {
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);
387     if (var)
388       return var;
389   }
390
391   for (std::shared_ptr<simgrid::mc::ObjectInformation> const& info : this->object_infos) {
392     simgrid::mc::Variable* var = info->find_variable(name);
393     if (var)
394       return var;
395   }
396
397   return nullptr;
398 }
399
400 void RemoteClient::read_variable(const char* name, void* target, size_t size) const
401 {
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));
408 }
409
410 std::string RemoteClient::read_string(RemotePtr<char> address) const
411 {
412   if (not address)
413     return {};
414
415   // TODO, use std::vector with .data() in C++17 to avoid useless copies
416   std::vector<char> res(128);
417   off_t off = 0;
418
419   while (1) {
420     ssize_t c = pread(this->memory_file, res.data() + off, res.size() - off, (off_t)address.address() + off);
421     if (c == -1) {
422       if (errno == EINTR)
423         continue;
424       else
425         xbt_die("Could not read from from remote process");
426     }
427     if (c == 0)
428       xbt_die("Could not read string from remote process");
429
430     void* p = memchr(res.data() + off, '\0', c);
431     if (p)
432       return std::string(res.data());
433
434     off += c;
435     if (off == (off_t)res.size())
436       res.resize(res.size() * 2);
437   }
438 }
439
440 const void* RemoteClient::read_bytes(void* buffer, std::size_t size, RemotePtr<void> address, int process_index,
441                                      ReadOptions options) const
442 {
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.
446 #if HAVE_SMPI
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");
452
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");
456
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));
460
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);
464     }
465 #endif
466   }
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_);
469   return buffer;
470 }
471
472 /** Write data to a process memory
473  *
474  *  @param buffer   local memory address (source)
475  *  @param len      data size
476  *  @param address  target process memory address (target)
477  */
478 void RemoteClient::write_bytes(const void* buffer, size_t len, RemotePtr<void> address)
479 {
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_);
482 }
483
484 void RemoteClient::clear_bytes(RemotePtr<void> address, size_t len)
485 {
486   pthread_once(&zero_buffer_flag, zero_buffer_init);
487   while (len) {
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);
491     len -= s;
492   }
493 }
494
495 void RemoteClient::ignore_region(std::uint64_t addr, std::size_t size)
496 {
497   IgnoredRegion region;
498   region.addr = addr;
499   region.size = size;
500
501   if (ignored_regions_.empty()) {
502     ignored_regions_.push_back(region);
503     return;
504   }
505
506   unsigned int cursor           = 0;
507   IgnoredRegion* current_region = nullptr;
508
509   int start = 0;
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)
516         return;
517       else if (current_region->size < size)
518         start = cursor + 1;
519       else
520         end = cursor - 1;
521     } else if (current_region->addr < addr)
522       start = cursor + 1;
523     else
524       end = cursor - 1;
525   }
526
527   std::size_t position;
528   if (current_region->addr == addr) {
529     if (current_region->size < size)
530       position = cursor + 1;
531     else
532       position = cursor;
533   } else if (current_region->addr < addr)
534     position = cursor + 1;
535   else
536     position = cursor;
537   ignored_regions_.insert(ignored_regions_.begin() + position, region);
538 }
539
540 void RemoteClient::ignore_heap(IgnoredHeapRegion const& region)
541 {
542   if (ignored_heap_.empty()) {
543     ignored_heap_.push_back(std::move(region));
544     return;
545   }
546
547   typedef std::vector<IgnoredHeapRegion>::size_type size_type;
548
549   size_type start = 0;
550   size_type end   = ignored_heap_.size() - 1;
551
552   // Binary search the position of insertion:
553   size_type cursor;
554   while (start <= end) {
555     cursor               = start + (end - start) / 2;
556     auto& current_region = ignored_heap_[cursor];
557     if (current_region.address == region.address)
558       return;
559     else if (current_region.address < region.address)
560       start = cursor + 1;
561     else if (cursor != 0)
562       end = cursor - 1;
563     // Avoid underflow:
564     else
565       break;
566   }
567
568   // Insert it mc_heap_ignore_region_t:
569   if (ignored_heap_[cursor].address < region.address)
570     ++cursor;
571   ignored_heap_.insert(ignored_heap_.begin() + cursor, region);
572 }
573
574 void RemoteClient::unignore_heap(void* address, size_t size)
575 {
576   typedef std::vector<IgnoredHeapRegion>::size_type size_type;
577
578   size_type start = 0;
579   size_type end   = ignored_heap_.size() - 1;
580
581   // Binary search:
582   size_type cursor;
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);
588       return;
589     } else if (region.address < address)
590       start = cursor + 1;
591     else if ((char*)region.address <= ((char*)address + size)) {
592       ignored_heap_.erase(ignored_heap_.begin() + cursor);
593       return;
594     } else if (cursor != 0)
595       end = cursor - 1;
596     // Avoid underflow:
597     else
598       break;
599   }
600 }
601
602 void RemoteClient::ignore_local_variable(const char* var_name, const char* frame_name)
603 {
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);
608 }
609
610 std::vector<simgrid::mc::ActorInformation>& RemoteClient::actors()
611 {
612   this->refresh_simix();
613   return smx_actors_infos;
614 }
615
616 std::vector<simgrid::mc::ActorInformation>& RemoteClient::dead_actors()
617 {
618   this->refresh_simix();
619   return smx_dead_actors_infos;
620 }
621
622 void RemoteClient::dumpStack()
623 {
624   unw_addr_space_t as = unw_create_addr_space(&_UPT_accessors, BYTE_ORDER);
625   if (as == nullptr) {
626     XBT_ERROR("Could not initialize ptrace address space");
627     return;
628   }
629
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");
634     return;
635   }
636
637   unw_cursor_t cursor;
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");
642     return;
643   }
644
645   simgrid::mc::dumpStack(stderr, cursor);
646
647   _UPT_destroy(context);
648   unw_destroy_addr_space(as);
649   return;
650 }
651
652 bool RemoteClient::actor_is_enabled(aid_t pid)
653 {
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;
660 }
661 }
662 }