Logo AND Algorithmique Numérique Distribuée

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