Logo AND Algorithmique Numérique Distribuée

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