Logo AND Algorithmique Numérique Distribuée

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