Logo AND Algorithmique Numérique Distribuée

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