Logo AND Algorithmique Numérique Distribuée

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