Logo AND Algorithmique Numérique Distribuée

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