Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
fbf411dd7c1f7edfff68a4d0b83435fe45d8bde2
[simgrid.git] / src / 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_object_info.h"
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 #include "mc/Process.hpp"
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_chrono",
58   "libboost_context",
59   "libboost_system",
60   "libboost_thread",
61   "libc",
62   "libc++",
63   "libcdt",
64   "libcgraph",
65   "libdl",
66   "libdw",
67   "libelf",
68   "libgcc_s",
69   "liblua5.1",
70   "liblzma",
71   "libm",
72   "libpthread",
73   "librt",
74   "libsigc",
75   "libstdc++",
76   "libunwind",
77   "libunwind-x86_64",
78   "libunwind-x86",
79   "libunwind-ptrace",
80   "libz"
81 };
82
83 static bool MC_is_simgrid_lib(const char* libname)
84 {
85   return !strcmp(libname, "libsimgrid");
86 }
87
88 static bool MC_is_filtered_lib(const char* libname)
89 {
90   for (const char* filtered_lib : FILTERED_LIBS)
91     if (strcmp(libname, filtered_lib)==0)
92       return true;
93   return false;
94 }
95
96 struct s_mc_memory_map_re {
97   regex_t so_re;
98   regex_t version_re;
99 };
100
101 static char* MC_get_lib_name(const char* pathname, struct s_mc_memory_map_re* res)
102 {
103   const char* map_basename = basename((char*) pathname);
104
105   regmatch_t match;
106   if(regexec(&res->so_re, map_basename, 1, &match, 0))
107     return NULL;
108
109   char* libname = strndup(map_basename, match.rm_so);
110
111   // Strip the version suffix:
112   if(libname && !regexec(&res->version_re, libname, 1, &match, 0)) {
113     char* temp = libname;
114     libname = strndup(temp, match.rm_so);
115     free(temp);
116   }
117
118   return libname;
119 }
120
121 static ssize_t pread_whole(int fd, void *buf, size_t count, std::uint64_t offset)
122 {
123   char* buffer = (char*) buf;
124   ssize_t real_count = count;
125   while (count) {
126     ssize_t res = pread(fd, buffer, count, (std::int64_t) offset);
127     if (res > 0) {
128       count  -= res;
129       buffer += res;
130       offset += res;
131     } else if (res==0) {
132       return -1;
133     } else if (errno != EINTR) {
134       perror("pread_whole");
135       return -1;
136     }
137   }
138   return real_count;
139 }
140
141 static ssize_t pwrite_whole(int fd, const void *buf, size_t count, off_t offset)
142 {
143   const char* buffer = (const char*) buf;
144   ssize_t real_count = count;
145   while (count) {
146     ssize_t res = pwrite(fd, buffer, count, offset);
147     if (res > 0) {
148       count  -= res;
149       buffer += res;
150       offset += res;
151     } else if (res==0) {
152       return -1;
153     } else if (errno != EINTR) {
154       return -1;
155     }
156   }
157   return real_count;
158 }
159
160 static pthread_once_t zero_buffer_flag = PTHREAD_ONCE_INIT;
161 static const void* zero_buffer;
162 static const size_t zero_buffer_size = 10 * 4096;
163
164 static void MC_zero_buffer_init(void)
165 {
166   int fd = open("/dev/zero", O_RDONLY);
167   if (fd<0)
168     xbt_die("Could not open /dev/zero");
169   zero_buffer = mmap(NULL, zero_buffer_size, PROT_READ, MAP_SHARED, fd, 0);
170   if (zero_buffer == MAP_FAILED)
171     xbt_die("Could not map the zero buffer");
172   close(fd);
173 }
174
175 static
176 int open_process_file(pid_t pid, const char* file, int flags)
177 {
178   char buff[50];
179   snprintf(buff, sizeof(buff), "/proc/%li/%s", (long) pid, file);
180   return open(buff, flags);
181 }
182
183 }
184
185 namespace simgrid {
186 namespace mc {
187
188 int open_vm(pid_t pid, int flags)
189 {
190   const size_t buffer_size = 30;
191   char buffer[buffer_size];
192   int res = snprintf(buffer, buffer_size, "/proc/%lli/mem", (long long) pid);
193   if (res < 0 || (size_t) res >= buffer_size) {
194     errno = ENAMETOOLONG;
195     return -1;
196   }
197   return open(buffer, flags);
198 }
199
200   
201 }
202 }
203
204 // ***** Process
205
206 namespace simgrid {
207 namespace mc {
208
209 Process::Process(pid_t pid, int sockfd)
210 {
211   Process* process = this;
212   process->socket_ = sockfd;
213   process->pid_ = pid;
214   process->running_ = true;
215   process->status_ = 0;
216   process->memory_map_ = get_memory_map(pid);
217   process->cache_flags = MC_PROCESS_CACHE_FLAG_NONE;
218   process->heap = NULL;
219   process->heap_info = NULL;
220   process->init_memory_map_info();
221   process->clear_refs_fd_ = -1;
222   process->pagemap_fd_ = -1;
223
224   int fd = open_vm(process->pid_, O_RDWR);
225   if (fd<0)
226     xbt_die("Could not open file for process virtual address space");
227   process->memory_file = fd;
228
229   // Read std_heap (is a struct mdesc*):
230   simgrid::mc::Variable* std_heap_var = process->find_variable("__mmalloc_default_mdp");
231   if (!std_heap_var)
232     xbt_die("No heap information in the target process");
233   if(!std_heap_var->address)
234     xbt_die("No constant address for this variable");
235   process->read_bytes(&process->heap_address, sizeof(struct mdesc*),
236     remote(std_heap_var->address),
237     simgrid::mc::ProcessIndexDisabled);
238
239   process->smx_process_infos = MC_smx_process_info_list_new();
240   process->smx_old_process_infos = MC_smx_process_info_list_new();
241   process->unw_addr_space = unw_create_addr_space(&mc_unw_accessors  , __BYTE_ORDER);
242   process->unw_underlying_addr_space = unw_create_addr_space(&mc_unw_vmread_accessors, __BYTE_ORDER);
243   process->unw_underlying_context = _UPT_create(pid);
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->pid_ = 0;
254
255   process->maestro_stack_start_ = nullptr;
256   process->maestro_stack_end_ = nullptr;
257
258   xbt_dynar_free(&process->smx_process_infos);
259   xbt_dynar_free(&process->smx_old_process_infos);
260
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   if (process->clear_refs_fd_ >= 0)
284     close(process->clear_refs_fd_);
285   if (process->pagemap_fd_ >= 0)
286     close(process->pagemap_fd_);
287 }
288
289 /** Refresh the information about the process
290  *
291  *  Do not use direclty, this is used by the getters when appropriate
292  *  in order to have fresh data.
293  */
294 void Process::refresh_heap()
295 {
296   xbt_assert(mc_mode == MC_MODE_SERVER);
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   if (!(this->cache_flags & MC_PROCESS_CACHE_FLAG_HEAP))
315     this->refresh_heap();
316   // Refresh process->heapinfo:
317   size_t malloc_info_bytesize =
318     (this->heap->heaplimit + 1) * sizeof(malloc_info);
319   this->heap_info = (malloc_info*) realloc(this->heap_info, malloc_info_bytesize);
320   this->read_bytes(this->heap_info, malloc_info_bytesize,
321     remote(this->heap->heapinfo), simgrid::mc::ProcessIndexDisabled);
322   this->cache_flags |= MC_PROCESS_CACHE_FLAG_MALLOC_INFO;
323 }
324
325 /** @brief Finds the range of the different memory segments and binary paths */
326 void Process::init_memory_map_info()
327 {
328   XBT_DEBUG("Get debug information ...");
329   this->maestro_stack_start_ = nullptr;
330   this->maestro_stack_end_ = nullptr;
331   this->object_infos.resize(0);
332   this->binary_info = NULL;
333   this->libsimgrid_info = NULL;
334
335   struct s_mc_memory_map_re res;
336
337   if(regcomp(&res.so_re, SO_RE, 0) || regcomp(&res.version_re, VERSION_RE, 0))
338     xbt_die(".so regexp did not compile");
339
340   std::vector<simgrid::mc::VmMap> const& maps = this->memory_map_;
341
342   const char* current_name = NULL;
343
344   this->object_infos.resize(0);
345
346   for (size_t i=0; i < maps.size(); i++) {
347     simgrid::mc::VmMap const& reg = maps[i];
348     const char* pathname = maps[i].pathname.c_str();
349
350     // Nothing to do
351     if (maps[i].pathname.empty()) {
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_ = remote(reg.start_addr);
360         this->maestro_stack_end_ = remote(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     std::shared_ptr<simgrid::mc::ObjectInformation> info =
386       MC_find_object_info(this->memory_map_, pathname, is_executable);
387     this->object_infos.push_back(info);
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 (auto const& object_info : this->object_infos)
400     MC_post_process_object_info(this, object_info.get());
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 std::shared_ptr<simgrid::mc::ObjectInformation> Process::find_object_info(remote_ptr<void> addr) const
409 {
410   for (auto const& object_info : this->object_infos) {
411     if (addr.address() >= (std::uint64_t)object_info->start
412         && addr.address() <= (std::uint64_t)object_info->end) {
413       return object_info;
414     }
415   }
416   return NULL;
417 }
418
419 std::shared_ptr<ObjectInformation> Process::find_object_info_exec(remote_ptr<void> addr) const
420 {
421   for (std::shared_ptr<ObjectInformation> const& info : this->object_infos) {
422     if (addr.address() >= (std::uint64_t) info->start_exec
423         && addr.address() <= (std::uint64_t) info->end_exec) {
424       return info;
425     }
426   }
427   return nullptr;
428 }
429
430 std::shared_ptr<ObjectInformation> Process::find_object_info_rw(remote_ptr<void> addr) const
431 {
432   for (std::shared_ptr<ObjectInformation> const& info : this->object_infos) {
433     if (addr.address() >= (std::uint64_t)info->start_rw
434         && addr.address() <= (std::uint64_t)info->end_rw) {
435       return info;
436     }
437   }
438   return nullptr;
439 }
440
441 simgrid::mc::Frame* Process::find_function(remote_ptr<void> ip) const
442 {
443   std::shared_ptr<simgrid::mc::ObjectInformation> info = this->find_object_info_exec(ip);
444   return info ? info->find_function((void*) ip.address()) : nullptr;
445 }
446
447 /** Find (one occurence of) the named variable definition
448  */
449 simgrid::mc::Variable* Process::find_variable(const char* name) const
450 {
451   // First lookup the variable in the executable shared object.
452   // A global variable used directly by the executable code from a library
453   // is reinstanciated in the executable memory .data/.bss.
454   // We need to look up the variable in the execvutable first.
455   if (this->binary_info) {
456     std::shared_ptr<simgrid::mc::ObjectInformation> const& info = this->binary_info;
457     simgrid::mc::Variable* var = info->find_variable(name);
458     if (var)
459       return var;
460   }
461
462   for (std::shared_ptr<simgrid::mc::ObjectInformation> const& info : this->object_infos) {
463     simgrid::mc::Variable* var = info->find_variable(name);
464     if (var)
465       return var;
466   }
467
468   return NULL;
469 }
470
471 void Process::read_variable(const char* name, void* target, size_t size) const
472 {
473   simgrid::mc::Variable* var = this->find_variable(name);
474   if (!var->address)
475     xbt_die("No simple location for this variable");
476   if (!var->type->full_type)
477     xbt_die("Partial type for %s, cannot check size", name);
478   if ((size_t) var->type->full_type->byte_size != size)
479     xbt_die("Unexpected size for %s (expected %zi, was %zi)",
480       name, size, (size_t) var->type->full_type->byte_size);
481   this->read_bytes(target, size, remote(var->address));
482 }
483
484 char* Process::read_string(remote_ptr<void> address) const
485 {
486   if (!address)
487     return NULL;
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 #ifdef HAVE_SMPI
525     if (info.get() && info.get()->privatized()) {
526       if (process_index < 0)
527         xbt_die("Missing process index");
528       if (process_index >= (int) MC_smpi_process_count())
529         xbt_die("Invalid process index");
530
531       // Read smpi_privatisation_regions from MCed:
532       smpi_privatisation_region_t remote_smpi_privatisation_regions =
533         mc_model_checker->process().read_variable<smpi_privatisation_region_t>(
534           "smpi_privatisation_regions");
535
536       s_smpi_privatisation_region_t privatisation_region =
537         mc_model_checker->process().read<s_smpi_privatisation_region_t>(
538           remote(remote_smpi_privatisation_regions + process_index));
539
540       // Address translation in the privaization segment:
541       size_t offset = address.address() - (std::uint64_t)info->start_rw;
542       address = remote((char*)privatisation_region.address + offset);
543     }
544 #endif
545   }
546
547   if (pread_whole(this->memory_file, buffer, size, address.address()) < 0)
548     xbt_die("Read from process %lli failed", (long long) this->pid_);
549   return buffer;
550 }
551
552 /** Write data to a process memory
553  *
554  *  @param process the process
555  *  @param local   local memory address (source)
556  *  @param remote  target process memory address (target)
557  *  @param len     data size
558  */
559 void Process::write_bytes(const void* buffer, size_t len, remote_ptr<void> address)
560 {
561   if (pwrite_whole(this->memory_file, buffer, len, address.address()) < 0)
562     xbt_die("Write to process %lli failed", (long long) this->pid_);
563 }
564
565 void Process::clear_bytes(remote_ptr<void> address, size_t len)
566 {
567   pthread_once(&zero_buffer_flag, MC_zero_buffer_init);
568   while (len) {
569     size_t s = len > zero_buffer_size ? zero_buffer_size : len;
570     this->write_bytes(zero_buffer, s, address);
571     address = remote((char*) address.address() + s);
572     len -= s;
573   }
574 }
575
576 void Process::ignore_region(std::uint64_t addr, std::size_t size)
577 {
578   IgnoredRegion region;
579   region.addr = addr;
580   region.size = size;
581
582   if (ignored_regions_.empty()) {
583     ignored_regions_.push_back(region);
584     return;
585   }
586
587   unsigned int cursor = 0;
588   IgnoredRegion* current_region = nullptr;
589
590   int start = 0;
591   int end = ignored_regions_.size() - 1;
592   while (start <= end) {
593     cursor = (start + end) / 2;
594     current_region = &ignored_regions_[cursor];
595     if (current_region->addr == addr) {
596       if (current_region->size == size)
597         return;
598       else if (current_region->size < size)
599         start = cursor + 1;
600       else
601         end = cursor - 1;
602     } else if (current_region->addr < addr)
603       start = cursor + 1;
604     else
605       end = cursor - 1;
606   }
607
608   std::size_t position;
609   if (current_region->addr == addr) {
610     if (current_region->size < size) {
611       position = cursor + 1;
612     } else {
613       position = cursor;
614     }
615   } else if (current_region->addr < addr) {
616     position = cursor + 1;
617   } else {
618     position = cursor;
619   }
620   ignored_regions_.insert(
621     ignored_regions_.begin() + position, region);
622 }
623
624 void Process::reset_soft_dirty()
625 {
626   if (this->clear_refs_fd_ < 0) {
627     this->clear_refs_fd_ = open_process_file(pid_, "clear_refs", O_WRONLY|O_CLOEXEC);
628     if (this->clear_refs_fd_ < 0)
629       xbt_die("Could not open clear_refs file for soft-dirty tracking. Run as root?");
630   }
631   if(::write(this->clear_refs_fd_, "4\n", 2) != 2)
632     xbt_die("Could not reset softdirty bits");
633 }
634
635 void Process::read_pagemap(uint64_t* pagemap, size_t page_start, size_t page_count)
636 {
637   if (pagemap_fd_ < 0) {
638     pagemap_fd_ = open_process_file(pid_, "pagemap", O_RDONLY|O_CLOEXEC);
639     if (pagemap_fd_ < 0)
640       xbt_die("Could not open pagemap file for soft-dirty tracking. Run as root?");
641   }
642   ssize_t bytesize = sizeof(uint64_t) * page_count;
643   off_t offset = sizeof(uint64_t) * page_start;
644   if (pread_whole(pagemap_fd_, pagemap, bytesize, offset) != bytesize)
645     xbt_die("Could not read pagemap");
646 }
647
648 }
649 }