Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
[mc] Move cross process reading support for SBT structure in a separate file
[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 = MC_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->checkpoint_ignore = MC_checkpoint_ignore_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   process->process_flags = MC_PROCESS_NO_FLAG;
245   process->pid = 0;
246
247   MC_free_memory_map(process->memory_map);
248   process->memory_map = NULL;
249
250   process->maestro_stack_start = NULL;
251   process->maestro_stack_end = NULL;
252
253   xbt_dynar_free(&process->checkpoint_ignore);
254
255   xbt_dynar_free(&process->smx_process_infos);
256   xbt_dynar_free(&process->smx_old_process_infos);
257
258   size_t i;
259   for (i=0; i!=process->object_infos_size; ++i) {
260     MC_free_object_info(&process->object_infos[i]);
261   }
262   free(process->object_infos);
263   process->object_infos = NULL;
264   process->object_infos_size = 0;
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 = NULL;
331   this->maestro_stack_end = NULL;
332   this->object_infos = NULL;
333   this->object_infos_size = 0;
334   this->binary_info = NULL;
335   this->libsimgrid_info = NULL;
336
337   struct s_mc_memory_map_re res;
338
339   if(regcomp(&res.so_re, SO_RE, 0) || regcomp(&res.version_re, VERSION_RE, 0))
340     xbt_die(".so regexp did not compile");
341
342   memory_map_t maps = this->memory_map;
343
344   const char* current_name = NULL;
345
346   for (ssize_t i=0; i < maps->mapsize; i++) {
347     map_region_t reg = &(maps->regions[i]);
348     const char* pathname = maps->regions[i].pathname;
349
350     // Nothing to do
351     if (maps->regions[i].pathname == NULL) {
352       current_name = NULL;
353       continue;
354     }
355
356     // [stack], [vvar], [vsyscall], [vdso] ...
357     if (pathname[0] == '[') {
358       if ((reg->prot & PROT_WRITE) && !memcmp(pathname, "[stack]", 7)) {
359         this->maestro_stack_start = reg->start_addr;
360         this->maestro_stack_end = reg->end_addr;
361       }
362       current_name = NULL;
363       continue;
364     }
365
366     if (current_name && strcmp(current_name, pathname)==0)
367       continue;
368
369     current_name = pathname;
370     if (!(reg->prot & PROT_READ) && (reg->prot & PROT_EXEC))
371       continue;
372
373     const bool is_executable = !i;
374     char* libname = NULL;
375     if (!is_executable) {
376       libname = MC_get_lib_name(pathname, &res);
377       if(!libname)
378         continue;
379       if (MC_is_filtered_lib(libname)) {
380         free(libname);
381         continue;
382       }
383     }
384
385     mc_object_info_t info =
386       MC_find_object_info(this->memory_map, pathname, is_executable);
387     this->object_infos = (mc_object_info_t*) realloc(this->object_infos,
388       (this->object_infos_size+1) * sizeof(mc_object_info_t*));
389     this->object_infos[this->object_infos_size] = info;
390     this->object_infos_size++;
391     if (is_executable)
392       this->binary_info = info;
393     else if (libname && MC_is_simgrid_lib(libname))
394       this->libsimgrid_info = info;
395     free(libname);
396   }
397
398   regfree(&res.so_re);
399   regfree(&res.version_re);
400
401   // Resolve time (including accross differents objects):
402   for (size_t i=0; i!=this->object_infos_size; ++i)
403     MC_post_process_object_info(this, this->object_infos[i]);
404
405   xbt_assert(this->maestro_stack_start, "Did not find maestro_stack_start");
406   xbt_assert(this->maestro_stack_end, "Did not find maestro_stack_end");
407
408   XBT_DEBUG("Get debug information done !");
409 }
410
411 mc_object_info_t Process::find_object_info(remote_ptr<void> addr) const
412 {
413   size_t i;
414   for (i = 0; i != this->object_infos_size; ++i) {
415     if (addr.address() >= (std::uint64_t)this->object_infos[i]->start
416         && addr.address() <= (std::uint64_t)this->object_infos[i]->end) {
417       return this->object_infos[i];
418     }
419   }
420   return NULL;
421 }
422
423 mc_object_info_t Process::find_object_info_exec(remote_ptr<void> addr) const
424 {
425   size_t i;
426   for (i = 0; i != this->object_infos_size; ++i) {
427     if (addr.address() >= (std::uint64_t)this->object_infos[i]->start_exec
428         && addr.address() <= (std::uint64_t)this->object_infos[i]->end_exec) {
429       return this->object_infos[i];
430     }
431   }
432   return NULL;
433 }
434
435 mc_object_info_t Process::find_object_info_rw(remote_ptr<void> addr) const
436 {
437   size_t i;
438   for (i = 0; i != this->object_infos_size; ++i) {
439     if (addr.address() >= (std::uint64_t)this->object_infos[i]->start_rw
440         && addr.address() <= (std::uint64_t)this->object_infos[i]->end_rw) {
441       return this->object_infos[i];
442     }
443   }
444   return NULL;
445 }
446
447 dw_frame_t Process::find_function(remote_ptr<void> ip) const
448 {
449   mc_object_info_t info = this->find_object_info_exec(ip);
450   if (info == NULL)
451     return NULL;
452   else
453     return MC_file_object_info_find_function(info, (void*) ip.address());
454 }
455
456 /** Find (one occurence of) the named variable definition
457  */
458 dw_variable_t Process::find_variable(const char* name) const
459 {
460   const size_t n = this->object_infos_size;
461   size_t i;
462
463   // First lookup the variable in the executable shared object.
464   // A global variable used directly by the executable code from a library
465   // is reinstanciated in the executable memory .data/.bss.
466   // We need to look up the variable in the execvutable first.
467   if (this->binary_info) {
468     mc_object_info_t info = this->binary_info;
469     dw_variable_t var = MC_file_object_info_find_variable_by_name(info, name);
470     if (var)
471       return var;
472   }
473
474   for (i=0; i!=n; ++i) {
475     mc_object_info_t info = this->object_infos[i];
476     dw_variable_t var = MC_file_object_info_find_variable_by_name(info, name);
477     if (var)
478       return var;
479   }
480
481   return NULL;
482 }
483
484 void Process::read_variable(const char* name, void* target, size_t size) const
485 {
486   dw_variable_t var = this->find_variable(name);
487   if (!var->address)
488     xbt_die("No simple location for this variable");
489   if (!var->type->full_type)
490     xbt_die("Partial type for %s, cannot check size", name);
491   if ((size_t) var->type->full_type->byte_size != size)
492     xbt_die("Unexpected size for %s (expected %zi, was %zi)",
493       name, size, (size_t) var->type->full_type->byte_size);
494   this->read_bytes(target, size, remote(var->address));
495 }
496
497 char* Process::read_string(remote_ptr<void> address) const
498 {
499   if (!address)
500     return NULL;
501   if (this->is_self())
502     return strdup((char*) address.address());
503
504   off_t len = 128;
505   char* res = (char*) malloc(len);
506   off_t off = 0;
507
508   while (1) {
509     ssize_t c = pread(this->memory_file, res + off, len - off, (off_t) address.address() + off);
510     if (c == -1) {
511       if (errno == EINTR)
512         continue;
513       else
514         xbt_die("Could not read from from remote process");
515     }
516     if (c==0)
517       xbt_die("Could not read string from remote process");
518
519     void* p = memchr(res + off, '\0', c);
520     if (p)
521       return res;
522
523     off += c;
524     if (off == len) {
525       len *= 2;
526       res = (char*) realloc(res, len);
527     }
528   }
529 }
530
531 const void *Process::read_bytes(void* buffer, std::size_t size,
532   remote_ptr<void> address, int process_index,
533   AddressSpace::ReadMode mode) const
534 {
535   if (process_index != simgrid::mc::ProcessIndexDisabled) {
536     mc_object_info_t info = this->find_object_info_rw((void*)address.address());
537     // Segment overlap is not handled.
538     if (MC_object_info_is_privatized(info)) {
539       if (process_index < 0)
540         xbt_die("Missing process index");
541       // Address translation in the privaization segment:
542       // TODO, fix me (broken)
543       size_t offset = address.address() - (std::uint64_t)info->start_rw;
544       address = remote(address.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, (off_t) 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 }
595 }