Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
add libraries to excludes to please mc
[simgrid.git] / src / mc / remote / RemoteClient.cpp
1 /* Copyright (c) 2014-2018. 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 <string>
14 #include <vector>
15
16 #include <sys/ptrace.h>
17
18 #include <cstdio>
19
20 #include <fcntl.h>
21 #include <sys/mman.h> // PROT_*
22 #include <sys/types.h>
23 #include <unistd.h>
24
25 #include <pthread.h>
26
27 #include <libgen.h>
28
29 #include <libunwind-ptrace.h>
30 #include <libunwind.h>
31
32 #include "xbt/base.h"
33 #include "xbt/file.hpp"
34 #include "xbt/log.h"
35 #include <xbt/mmalloc.h>
36
37 #include "src/mc/mc_smx.hpp"
38 #include "src/mc/mc_unw.hpp"
39 #include "src/mc/sosp/mc_snapshot.hpp"
40
41 #include "src/mc/AddressSpace.hpp"
42 #include "src/mc/ObjectInformation.hpp"
43 #include "src/mc/Variable.hpp"
44 #include "src/mc/remote/RemoteClient.hpp"
45
46 using simgrid::mc::remote;
47
48 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(mc_process, mc, "MC process information");
49
50 namespace simgrid {
51 namespace mc {
52
53 // ***** Helper stuff
54
55 // List of library which memory segments are not considered:
56 static const std::vector<std::string> filtered_libraries = {
57 #ifdef __linux__
58     "ld",
59 #elif defined __FreeBSD__
60     "ld-elf",
61     "ld-elf32",
62     "libkvm",      /* kernel data access library */
63     "libprocstat", /* process and file information retrieval */
64     "libthr",      /* thread library */
65     "libutil",
66 #endif
67     "libasan", /* gcc sanitizers */
68     "libargp", /* workarounds for glibc-less systems */
69     "libtsan",
70     "libubsan",
71     "libbz2",
72     "libboost_chrono",
73     "libboost_context",
74     "libboost_context-mt",
75     "libboost_system",
76     "libboost_thread",
77     "libboost_timer",
78     "libboost_unit_test_framework",
79     "libc",
80     "libc++",
81     "libcdt",
82     "libcgraph",
83     "libcrypto",
84     "libcxxrt",
85     "libdl",
86     "libdw",
87     "libelf",
88     "libflang",
89     "libevent",
90     "libgcc_s",
91     "libgfortran",
92     "libimf",
93     "libintlc",
94     "libirng",
95     "liblua5.1",
96     "liblua5.3",
97     "liblzma",
98     "libm",
99     "libpapi",
100     "libpfm",
101     "libpthread",
102     "libquadmath",
103     "librt",
104     "libstdc++",
105     "libsvml",
106     "libunwind",
107     "libunwind-x86_64",
108     "libunwind-x86",
109     "libunwind-ptrace",
110     "libz"};
111
112 static bool is_simgrid_lib(const std::string& libname)
113 {
114   return libname == "libsimgrid";
115 }
116
117 static bool is_filtered_lib(const std::string& libname)
118 {
119   return std::find(begin(filtered_libraries), end(filtered_libraries), libname) != end(filtered_libraries);
120 }
121
122 static std::string get_lib_name(const std::string& pathname)
123 {
124   std::string map_basename = simgrid::xbt::Path(pathname).get_base_name();
125   std::string libname;
126
127   size_t pos = map_basename.rfind(".so");
128   if (pos != std::string::npos) {
129     // strip the extension (matching regex "\.so.*$")
130     libname.assign(map_basename, 0, pos);
131
132     // strip the version suffix (matching regex "-[.0-9-]*$")
133     while (true) {
134       pos = libname.rfind('-');
135       if (pos == std::string::npos || libname.find_first_not_of(".0123456789", pos + 1) != std::string::npos)
136         break;
137       libname.erase(pos);
138     }
139   }
140
141   return libname;
142 }
143
144 static ssize_t pread_whole(int fd, void* buf, size_t count, off_t offset)
145 {
146   char* buffer       = (char*)buf;
147   ssize_t real_count = count;
148   while (count) {
149     ssize_t res = pread(fd, buffer, count, offset);
150     if (res > 0) {
151       count -= res;
152       buffer += res;
153       offset += res;
154     } else if (res == 0)
155       return -1;
156     else if (errno != EINTR) {
157       perror("pread_whole");
158       return -1;
159     }
160   }
161   return real_count;
162 }
163
164 static ssize_t pwrite_whole(int fd, const void* buf, size_t count, off_t offset)
165 {
166   const char* buffer = (const char*)buf;
167   ssize_t real_count = count;
168   while (count) {
169     ssize_t res = pwrite(fd, buffer, count, offset);
170     if (res > 0) {
171       count -= res;
172       buffer += res;
173       offset += res;
174     } else if (res == 0)
175       return -1;
176     else if (errno != EINTR)
177       return -1;
178   }
179   return real_count;
180 }
181
182 static pthread_once_t zero_buffer_flag = PTHREAD_ONCE_INIT;
183 static const void* zero_buffer;
184 static const size_t zero_buffer_size = 10 * 4096;
185
186 static void zero_buffer_init()
187 {
188   int fd = open("/dev/zero", O_RDONLY);
189   if (fd < 0)
190     xbt_die("Could not open /dev/zero");
191   zero_buffer = mmap(nullptr, zero_buffer_size, PROT_READ, MAP_SHARED, fd, 0);
192   if (zero_buffer == MAP_FAILED)
193     xbt_die("Could not map the zero buffer");
194   close(fd);
195 }
196
197 int open_vm(pid_t pid, int flags)
198 {
199   const size_t buffer_size = 30;
200   char buffer[buffer_size];
201   int res = snprintf(buffer, buffer_size, "/proc/%lli/mem", (long long)pid);
202   if (res < 0 || (size_t)res >= buffer_size) {
203     errno = ENAMETOOLONG;
204     return -1;
205   }
206   return open(buffer, flags);
207 }
208
209 // ***** Process
210
211 RemoteClient::RemoteClient(pid_t pid, int sockfd) : AddressSpace(this), pid_(pid), channel_(sockfd), running_(true)
212 {
213 }
214
215 void RemoteClient::init()
216 {
217   this->memory_map_ = simgrid::xbt::get_memory_map(this->pid_);
218   this->init_memory_map_info();
219
220   int fd = open_vm(this->pid_, O_RDWR);
221   if (fd < 0)
222     xbt_die("Could not open file for process virtual address space");
223   this->memory_file = fd;
224
225   // Read std_heap (is a struct mdesc*):
226   simgrid::mc::Variable* std_heap_var = this->find_variable("__mmalloc_default_mdp");
227   if (not std_heap_var)
228     xbt_die("No heap information in the target process");
229   if (not std_heap_var->address)
230     xbt_die("No constant address for this variable");
231   this->read_bytes(&this->heap_address, sizeof(mdesc*), remote(std_heap_var->address),
232                    simgrid::mc::ProcessIndexDisabled);
233
234   this->smx_actors_infos.clear();
235   this->smx_dead_actors_infos.clear();
236   this->unw_addr_space            = simgrid::mc::UnwindContext::createUnwindAddressSpace();
237   this->unw_underlying_addr_space = simgrid::unw::create_addr_space();
238   this->unw_underlying_context    = simgrid::unw::create_context(this->unw_underlying_addr_space, this->pid_);
239 }
240
241 RemoteClient::~RemoteClient()
242 {
243   if (this->memory_file >= 0)
244     close(this->memory_file);
245
246   if (this->unw_underlying_addr_space != unw_local_addr_space) {
247     if (this->unw_underlying_addr_space)
248       unw_destroy_addr_space(this->unw_underlying_addr_space);
249     if (this->unw_underlying_context)
250       _UPT_destroy(this->unw_underlying_context);
251   }
252
253   unw_destroy_addr_space(this->unw_addr_space);
254 }
255
256 /** Refresh the information about the process
257  *
258  *  Do not use directly, this is used by the getters when appropriate
259  *  in order to have fresh data.
260  */
261 void RemoteClient::refresh_heap()
262 {
263   // Read/dereference/refresh the std_heap pointer:
264   if (not this->heap)
265     this->heap = std::unique_ptr<s_xbt_mheap_t>(new s_xbt_mheap_t());
266   this->read_bytes(this->heap.get(), sizeof(mdesc), remote(this->heap_address), simgrid::mc::ProcessIndexDisabled);
267   this->cache_flags_ |= RemoteClient::cache_heap;
268 }
269
270 /** Refresh the information about the process
271  *
272  *  Do not use direclty, this is used by the getters when appropriate
273  *  in order to have fresh data.
274  * */
275 void RemoteClient::refresh_malloc_info()
276 {
277   // Refresh process->heapinfo:
278   if (this->cache_flags_ & RemoteClient::cache_malloc)
279     return;
280   size_t count = this->heap->heaplimit + 1;
281   if (this->heap_info.size() < count)
282     this->heap_info.resize(count);
283   this->read_bytes(this->heap_info.data(), count * sizeof(malloc_info), remote(this->heap->heapinfo),
284                    simgrid::mc::ProcessIndexDisabled);
285   this->cache_flags_ |= RemoteClient::cache_malloc;
286 }
287
288 /** @brief Finds the range of the different memory segments and binary paths */
289 void RemoteClient::init_memory_map_info()
290 {
291   XBT_DEBUG("Get debug information ...");
292   this->maestro_stack_start_ = nullptr;
293   this->maestro_stack_end_   = nullptr;
294   this->object_infos.resize(0);
295   this->binary_info     = nullptr;
296   this->libsimgrid_info = nullptr;
297
298   std::vector<simgrid::xbt::VmMap> const& maps = this->memory_map_;
299
300   const char* current_name = nullptr;
301
302   this->object_infos.clear();
303
304   for (size_t i = 0; i < maps.size(); i++) {
305     simgrid::xbt::VmMap const& reg = maps[i];
306     const char* pathname           = maps[i].pathname.c_str();
307
308     // Nothing to do
309     if (maps[i].pathname.empty()) {
310       current_name = nullptr;
311       continue;
312     }
313
314     // [stack], [vvar], [vsyscall], [vdso] ...
315     if (pathname[0] == '[') {
316       if ((reg.prot & PROT_WRITE) && not memcmp(pathname, "[stack]", 7)) {
317         this->maestro_stack_start_ = remote(reg.start_addr);
318         this->maestro_stack_end_   = remote(reg.end_addr);
319       }
320       current_name = nullptr;
321       continue;
322     }
323
324     if (current_name && strcmp(current_name, pathname) == 0)
325       continue;
326
327     current_name = pathname;
328     if (not(reg.prot & PROT_READ) && (reg.prot & PROT_EXEC))
329       continue;
330
331     const bool is_executable = not i;
332     std::string libname;
333     if (not is_executable) {
334       libname = get_lib_name(pathname);
335       if (is_filtered_lib(libname)) {
336         continue;
337       }
338     }
339
340     std::shared_ptr<simgrid::mc::ObjectInformation> info =
341         simgrid::mc::createObjectInformation(this->memory_map_, pathname);
342     this->object_infos.push_back(info);
343     if (is_executable)
344       this->binary_info = info;
345     else if (is_simgrid_lib(libname))
346       this->libsimgrid_info = info;
347   }
348
349   // Resolve time (including across different objects):
350   for (auto const& object_info : this->object_infos)
351     postProcessObjectInformation(this, object_info.get());
352
353   xbt_assert(this->maestro_stack_start_, "Did not find maestro_stack_start");
354   xbt_assert(this->maestro_stack_end_, "Did not find maestro_stack_end");
355
356   XBT_DEBUG("Get debug information done !");
357 }
358
359 std::shared_ptr<simgrid::mc::ObjectInformation> RemoteClient::find_object_info(RemotePtr<void> addr) const
360 {
361   for (auto const& object_info : this->object_infos)
362     if (addr.address() >= (std::uint64_t)object_info->start && addr.address() <= (std::uint64_t)object_info->end)
363       return object_info;
364   return nullptr;
365 }
366
367 std::shared_ptr<ObjectInformation> RemoteClient::find_object_info_exec(RemotePtr<void> addr) const
368 {
369   for (std::shared_ptr<ObjectInformation> const& info : this->object_infos)
370     if (addr.address() >= (std::uint64_t)info->start_exec && addr.address() <= (std::uint64_t)info->end_exec)
371       return info;
372   return nullptr;
373 }
374
375 std::shared_ptr<ObjectInformation> RemoteClient::find_object_info_rw(RemotePtr<void> addr) const
376 {
377   for (std::shared_ptr<ObjectInformation> const& info : this->object_infos)
378     if (addr.address() >= (std::uint64_t)info->start_rw && addr.address() <= (std::uint64_t)info->end_rw)
379       return info;
380   return nullptr;
381 }
382
383 simgrid::mc::Frame* RemoteClient::find_function(RemotePtr<void> ip) const
384 {
385   std::shared_ptr<simgrid::mc::ObjectInformation> info = this->find_object_info_exec(ip);
386   return info ? info->find_function((void*)ip.address()) : nullptr;
387 }
388
389 /** Find (one occurrence of) the named variable definition
390  */
391 simgrid::mc::Variable* RemoteClient::find_variable(const char* name) const
392 {
393   // First lookup the variable in the executable shared object.
394   // A global variable used directly by the executable code from a library
395   // is reinstanciated in the executable memory .data/.bss.
396   // We need to look up the variable in the executable first.
397   if (this->binary_info) {
398     std::shared_ptr<simgrid::mc::ObjectInformation> const& info = this->binary_info;
399     simgrid::mc::Variable* var                                  = info->find_variable(name);
400     if (var)
401       return var;
402   }
403
404   for (std::shared_ptr<simgrid::mc::ObjectInformation> const& info : this->object_infos) {
405     simgrid::mc::Variable* var = info->find_variable(name);
406     if (var)
407       return var;
408   }
409
410   return nullptr;
411 }
412
413 void RemoteClient::read_variable(const char* name, void* target, size_t size) const
414 {
415   simgrid::mc::Variable* var = this->find_variable(name);
416   xbt_assert(var->address, "No simple location for this variable");
417   xbt_assert(var->type->full_type, "Partial type for %s, cannot check size", name);
418   xbt_assert((size_t)var->type->full_type->byte_size == size, "Unexpected size for %s (expected %zu, was %zu)", name,
419              size, (size_t)var->type->full_type->byte_size);
420   this->read_bytes(target, size, remote(var->address));
421 }
422
423 std::string RemoteClient::read_string(RemotePtr<char> address) const
424 {
425   if (not address)
426     return {};
427
428   std::vector<char> res(128);
429   off_t off = 0;
430
431   while (1) {
432     ssize_t c = pread(this->memory_file, res.data() + off, res.size() - off, (off_t)address.address() + off);
433     if (c == -1) {
434       if (errno == EINTR)
435         continue;
436       else
437         xbt_die("Could not read from from remote process");
438     }
439     if (c == 0)
440       xbt_die("Could not read string from remote process");
441
442     void* p = memchr(res.data() + off, '\0', c);
443     if (p)
444       return std::string(res.data());
445
446     off += c;
447     if (off == (off_t)res.size())
448       res.resize(res.size() * 2);
449   }
450 }
451
452 const void* RemoteClient::read_bytes(void* buffer, std::size_t size, RemotePtr<void> address, int process_index,
453                                      ReadOptions options) const
454 {
455   if (process_index != simgrid::mc::ProcessIndexDisabled) {
456     std::shared_ptr<simgrid::mc::ObjectInformation> const& info = this->find_object_info_rw(address);
457 // Segment overlap is not handled.
458 #if HAVE_SMPI
459     if (info.get() && this->privatized(*info)) {
460       if (process_index < 0)
461         xbt_die("Missing process index");
462       if (process_index >= (int)MC_smpi_process_count())
463         xbt_die("Invalid process index");
464
465       // Read smpi_privatization_regions from MCed:
466       smpi_privatization_region_t remote_smpi_privatization_regions =
467           mc_model_checker->process().read_variable<smpi_privatization_region_t>("smpi_privatization_regions");
468
469       s_smpi_privatization_region_t privatization_region =
470           mc_model_checker->process().read<s_smpi_privatization_region_t>(
471               remote(remote_smpi_privatization_regions + process_index));
472
473       // Address translation in the privatization segment:
474       size_t offset = address.address() - (std::uint64_t)info->start_rw;
475       address       = remote((char*)privatization_region.address + offset);
476     }
477 #endif
478   }
479   if (pread_whole(this->memory_file, buffer, size, (size_t)address.address()) < 0)
480     xbt_die("Read at %p from process %lli failed", (void*)address.address(), (long long)this->pid_);
481   return buffer;
482 }
483
484 /** Write data to a process memory
485  *
486  *  @param buffer   local memory address (source)
487  *  @param len      data size
488  *  @param address  target process memory address (target)
489  */
490 void RemoteClient::write_bytes(const void* buffer, size_t len, RemotePtr<void> address)
491 {
492   if (pwrite_whole(this->memory_file, buffer, len, (size_t)address.address()) < 0)
493     xbt_die("Write to process %lli failed", (long long)this->pid_);
494 }
495
496 void RemoteClient::clear_bytes(RemotePtr<void> address, size_t len)
497 {
498   pthread_once(&zero_buffer_flag, zero_buffer_init);
499   while (len) {
500     size_t s = len > zero_buffer_size ? zero_buffer_size : len;
501     this->write_bytes(zero_buffer, s, address);
502     address = remote((char*)address.address() + s);
503     len -= s;
504   }
505 }
506
507 void RemoteClient::ignore_region(std::uint64_t addr, std::size_t size)
508 {
509   IgnoredRegion region;
510   region.addr = addr;
511   region.size = size;
512
513   if (ignored_regions_.empty()) {
514     ignored_regions_.push_back(region);
515     return;
516   }
517
518   unsigned int cursor           = 0;
519   IgnoredRegion* current_region = nullptr;
520
521   int start = 0;
522   int end   = ignored_regions_.size() - 1;
523   while (start <= end) {
524     cursor         = (start + end) / 2;
525     current_region = &ignored_regions_[cursor];
526     if (current_region->addr == addr) {
527       if (current_region->size == size)
528         return;
529       else if (current_region->size < size)
530         start = cursor + 1;
531       else
532         end = cursor - 1;
533     } else if (current_region->addr < addr)
534       start = cursor + 1;
535     else
536       end = cursor - 1;
537   }
538
539   std::size_t position;
540   if (current_region->addr == addr) {
541     if (current_region->size < size)
542       position = cursor + 1;
543     else
544       position = cursor;
545   } else if (current_region->addr < addr)
546     position = cursor + 1;
547   else
548     position = cursor;
549   ignored_regions_.insert(ignored_regions_.begin() + position, region);
550 }
551
552 void RemoteClient::ignore_heap(IgnoredHeapRegion const& region)
553 {
554   if (ignored_heap_.empty()) {
555     ignored_heap_.push_back(std::move(region));
556     return;
557   }
558
559   typedef std::vector<IgnoredHeapRegion>::size_type size_type;
560
561   size_type start = 0;
562   size_type end   = ignored_heap_.size() - 1;
563
564   // Binary search the position of insertion:
565   size_type cursor;
566   while (start <= end) {
567     cursor               = start + (end - start) / 2;
568     auto& current_region = ignored_heap_[cursor];
569     if (current_region.address == region.address)
570       return;
571     else if (current_region.address < region.address)
572       start = cursor + 1;
573     else if (cursor != 0)
574       end = cursor - 1;
575     // Avoid underflow:
576     else
577       break;
578   }
579
580   // Insert it mc_heap_ignore_region_t:
581   if (ignored_heap_[cursor].address < region.address)
582     ++cursor;
583   ignored_heap_.insert(ignored_heap_.begin() + cursor, region);
584 }
585
586 void RemoteClient::unignore_heap(void* address, size_t size)
587 {
588   typedef std::vector<IgnoredHeapRegion>::size_type size_type;
589
590   size_type start = 0;
591   size_type end   = ignored_heap_.size() - 1;
592
593   // Binary search:
594   size_type cursor;
595   while (start <= end) {
596     cursor       = (start + end) / 2;
597     auto& region = ignored_heap_[cursor];
598     if (region.address < address)
599       start = cursor + 1;
600     else if ((char*)region.address <= ((char*)address + size)) {
601       ignored_heap_.erase(ignored_heap_.begin() + cursor);
602       return;
603     } else if (cursor != 0)
604       end = cursor - 1;
605     // Avoid underflow:
606     else
607       break;
608   }
609 }
610
611 void RemoteClient::ignore_local_variable(const char* var_name, const char* frame_name)
612 {
613   if (frame_name != nullptr && strcmp(frame_name, "*") == 0)
614     frame_name = nullptr;
615   for (std::shared_ptr<simgrid::mc::ObjectInformation> const& info : this->object_infos)
616     info->remove_local_variable(var_name, frame_name);
617 }
618
619 std::vector<simgrid::mc::ActorInformation>& RemoteClient::actors()
620 {
621   this->refresh_simix();
622   return smx_actors_infos;
623 }
624
625 std::vector<simgrid::mc::ActorInformation>& RemoteClient::dead_actors()
626 {
627   this->refresh_simix();
628   return smx_dead_actors_infos;
629 }
630
631 void RemoteClient::dumpStack()
632 {
633   unw_addr_space_t as = unw_create_addr_space(&_UPT_accessors, BYTE_ORDER);
634   if (as == nullptr) {
635     XBT_ERROR("Could not initialize ptrace address space");
636     return;
637   }
638
639   void* context = _UPT_create(this->pid_);
640   if (context == nullptr) {
641     unw_destroy_addr_space(as);
642     XBT_ERROR("Could not initialize ptrace context");
643     return;
644   }
645
646   unw_cursor_t cursor;
647   if (unw_init_remote(&cursor, as, context) != 0) {
648     _UPT_destroy(context);
649     unw_destroy_addr_space(as);
650     XBT_ERROR("Could not initialiez ptrace cursor");
651     return;
652   }
653
654   simgrid::mc::dumpStack(stderr, cursor);
655
656   _UPT_destroy(context);
657   unw_destroy_addr_space(as);
658 }
659
660 bool RemoteClient::actor_is_enabled(aid_t pid)
661 {
662   s_mc_message_actor_enabled_t msg{MC_MESSAGE_ACTOR_ENABLED, pid};
663   process()->getChannel().send(msg);
664   char buff[MC_MESSAGE_LENGTH];
665   ssize_t received = process()->getChannel().receive(buff, MC_MESSAGE_LENGTH, true);
666   xbt_assert(received == sizeof(s_mc_message_int_t), "Unexpected size in answer to ACTOR_ENABLED");
667   return ((s_mc_message_int_t*)buff)->value;
668 }
669 }
670 }