Logo AND Algorithmique Numérique Distribuée

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