Logo AND Algorithmique Numérique Distribuée

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