Logo AND Algorithmique Numérique Distribuée

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