Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
[mc] Move ignore_local_variable() into Process
[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
36 #include "src/mc/Process.hpp"
37 #include "src/mc/AddressSpace.hpp"
38 #include "src/mc/ObjectInformation.hpp"
39 #include "src/mc/Variable.hpp"
40
41 using simgrid::mc::remote;
42
43 extern "C" {
44
45 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(mc_process, mc,
46                                 "MC process information");
47
48 // ***** Helper stuff
49
50 #define SO_RE "\\.so[\\.0-9]*$"
51 #define VERSION_RE "-[\\.0-9-]*$"
52
53 static const char *const FILTERED_LIBS[] = {
54   "ld",
55   "libbz2",
56   "libboost_chrono",
57   "libboost_context",
58   "libboost_system",
59   "libboost_thread",
60   "libc",
61   "libc++",
62   "libcdt",
63   "libcgraph",
64   "libdl",
65   "libdw",
66   "libelf",
67   "libgcc_s",
68   "liblua5.1",
69   "liblua5.3",
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) : AddressSpace(this)
210 {
211   Process* process = this;
212   process->socket_ = sockfd;
213   process->pid_ = pid;
214   process->running_ = true;
215   process->memory_map_ = simgrid::xbt::get_memory_map(pid);
216   process->cache_flags = MC_PROCESS_CACHE_FLAG_NONE;
217   process->init_memory_map_info();
218   process->clear_refs_fd_ = -1;
219   process->pagemap_fd_ = -1;
220   process->privatized_ = false;
221
222   int fd = open_vm(process->pid_, O_RDWR);
223   if (fd<0)
224     xbt_die("Could not open file for process virtual address space");
225   process->memory_file = fd;
226
227   // Read std_heap (is a struct mdesc*):
228   simgrid::mc::Variable* std_heap_var = process->find_variable("__mmalloc_default_mdp");
229   if (!std_heap_var)
230     xbt_die("No heap information in the target process");
231   if(!std_heap_var->address)
232     xbt_die("No constant address for this variable");
233   process->read_bytes(&process->heap_address, sizeof(struct mdesc*),
234     remote(std_heap_var->address),
235     simgrid::mc::ProcessIndexDisabled);
236
237   process->smx_process_infos = MC_smx_process_info_list_new();
238   process->smx_old_process_infos = MC_smx_process_info_list_new();
239   process->unw_addr_space = unw_create_addr_space(&mc_unw_accessors  , __BYTE_ORDER);
240   process->unw_underlying_addr_space = unw_create_addr_space(&mc_unw_vmread_accessors, __BYTE_ORDER);
241   process->unw_underlying_context = _UPT_create(pid);
242 }
243
244 Process::~Process()
245 {
246   Process* process = this;
247
248   if (this->socket_ >= 0 && close(this->socket_) < 0)
249     xbt_die("Could not close communication socket");
250
251   process->pid_ = 0;
252
253   process->maestro_stack_start_ = nullptr;
254   process->maestro_stack_end_ = nullptr;
255
256   xbt_dynar_free(&process->smx_process_infos);
257   xbt_dynar_free(&process->smx_old_process_infos);
258
259   if (process->memory_file >= 0) {
260     close(process->memory_file);
261   }
262
263   if (process->unw_underlying_addr_space != unw_local_addr_space) {
264     unw_destroy_addr_space(process->unw_underlying_addr_space);
265     _UPT_destroy(process->unw_underlying_context);
266   }
267   process->unw_underlying_context = NULL;
268   process->unw_underlying_addr_space = NULL;
269
270   unw_destroy_addr_space(process->unw_addr_space);
271   process->unw_addr_space = NULL;
272
273   process->cache_flags = MC_PROCESS_CACHE_FLAG_NONE;
274
275   if (process->clear_refs_fd_ >= 0)
276     close(process->clear_refs_fd_);
277   if (process->pagemap_fd_ >= 0)
278     close(process->pagemap_fd_);
279 }
280
281 /** Refresh the information about the process
282  *
283  *  Do not use direclty, this is used by the getters when appropriate
284  *  in order to have fresh data.
285  */
286 void Process::refresh_heap()
287 {
288   xbt_assert(mc_mode == MC_MODE_SERVER);
289   // Read/dereference/refresh the std_heap pointer:
290   if (!this->heap)
291     this->heap = std::unique_ptr<s_xbt_mheap_t>(new s_xbt_mheap_t());
292   this->read_bytes(this->heap.get(), sizeof(struct mdesc),
293     remote(this->heap_address), simgrid::mc::ProcessIndexDisabled);
294   this->cache_flags |= MC_PROCESS_CACHE_FLAG_HEAP;
295 }
296
297 /** Refresh the information about the process
298  *
299  *  Do not use direclty, this is used by the getters when appropriate
300  *  in order to have fresh data.
301  * */
302 void Process::refresh_malloc_info()
303 {
304   xbt_assert(mc_mode == MC_MODE_SERVER);
305   if (!(this->cache_flags & MC_PROCESS_CACHE_FLAG_HEAP))
306     this->refresh_heap();
307   // Refresh process->heapinfo:
308   size_t count = this->heap->heaplimit + 1;
309   if (this->heap_info.size() < count)
310     this->heap_info.resize(count);
311   this->read_bytes(this->heap_info.data(), count * sizeof(malloc_info),
312     remote(this->heap->heapinfo), simgrid::mc::ProcessIndexDisabled);
313   this->cache_flags |= MC_PROCESS_CACHE_FLAG_MALLOC_INFO;
314 }
315
316 /** @brief Finds the range of the different memory segments and binary paths */
317 void Process::init_memory_map_info()
318 {
319   XBT_DEBUG("Get debug information ...");
320   this->maestro_stack_start_ = nullptr;
321   this->maestro_stack_end_ = nullptr;
322   this->object_infos.resize(0);
323   this->binary_info = NULL;
324   this->libsimgrid_info = NULL;
325
326   struct s_mc_memory_map_re res;
327
328   if(regcomp(&res.so_re, SO_RE, 0) || regcomp(&res.version_re, VERSION_RE, 0))
329     xbt_die(".so regexp did not compile");
330
331   std::vector<simgrid::xbt::VmMap> const& maps = this->memory_map_;
332
333   const char* current_name = NULL;
334
335   this->object_infos.resize(0);
336
337   for (size_t i=0; i < maps.size(); i++) {
338     simgrid::xbt::VmMap const& reg = maps[i];
339     const char* pathname = maps[i].pathname.c_str();
340
341     // Nothing to do
342     if (maps[i].pathname.empty()) {
343       current_name = NULL;
344       continue;
345     }
346
347     // [stack], [vvar], [vsyscall], [vdso] ...
348     if (pathname[0] == '[') {
349       if ((reg.prot & PROT_WRITE) && !memcmp(pathname, "[stack]", 7)) {
350         this->maestro_stack_start_ = remote(reg.start_addr);
351         this->maestro_stack_end_ = remote(reg.end_addr);
352       }
353       current_name = NULL;
354       continue;
355     }
356
357     if (current_name && strcmp(current_name, pathname)==0)
358       continue;
359
360     current_name = pathname;
361     if (!(reg.prot & PROT_READ) && (reg.prot & PROT_EXEC))
362       continue;
363
364     const bool is_executable = !i;
365     char* libname = NULL;
366     if (!is_executable) {
367       libname = MC_get_lib_name(pathname, &res);
368       if(!libname)
369         continue;
370       if (MC_is_filtered_lib(libname)) {
371         free(libname);
372         continue;
373       }
374     }
375
376     std::shared_ptr<simgrid::mc::ObjectInformation> info =
377       MC_find_object_info(this->memory_map_, pathname);
378     this->object_infos.push_back(info);
379     if (is_executable)
380       this->binary_info = info;
381     else if (libname && MC_is_simgrid_lib(libname))
382       this->libsimgrid_info = info;
383     free(libname);
384   }
385
386   regfree(&res.so_re);
387   regfree(&res.version_re);
388
389   // Resolve time (including accross differents objects):
390   for (auto const& object_info : this->object_infos)
391     MC_post_process_object_info(this, object_info.get());
392
393   xbt_assert(this->maestro_stack_start_, "Did not find maestro_stack_start");
394   xbt_assert(this->maestro_stack_end_, "Did not find maestro_stack_end");
395
396   XBT_DEBUG("Get debug information done !");
397 }
398
399 std::shared_ptr<simgrid::mc::ObjectInformation> Process::find_object_info(remote_ptr<void> addr) const
400 {
401   for (auto const& object_info : this->object_infos) {
402     if (addr.address() >= (std::uint64_t)object_info->start
403         && addr.address() <= (std::uint64_t)object_info->end) {
404       return object_info;
405     }
406   }
407   return NULL;
408 }
409
410 std::shared_ptr<ObjectInformation> Process::find_object_info_exec(remote_ptr<void> addr) const
411 {
412   for (std::shared_ptr<ObjectInformation> const& info : this->object_infos) {
413     if (addr.address() >= (std::uint64_t) info->start_exec
414         && addr.address() <= (std::uint64_t) info->end_exec) {
415       return info;
416     }
417   }
418   return nullptr;
419 }
420
421 std::shared_ptr<ObjectInformation> Process::find_object_info_rw(remote_ptr<void> addr) const
422 {
423   for (std::shared_ptr<ObjectInformation> const& info : this->object_infos) {
424     if (addr.address() >= (std::uint64_t)info->start_rw
425         && addr.address() <= (std::uint64_t)info->end_rw) {
426       return info;
427     }
428   }
429   return nullptr;
430 }
431
432 simgrid::mc::Frame* Process::find_function(remote_ptr<void> ip) const
433 {
434   std::shared_ptr<simgrid::mc::ObjectInformation> info = this->find_object_info_exec(ip);
435   return info ? info->find_function((void*) ip.address()) : nullptr;
436 }
437
438 /** Find (one occurence of) the named variable definition
439  */
440 simgrid::mc::Variable* Process::find_variable(const char* name) const
441 {
442   // First lookup the variable in the executable shared object.
443   // A global variable used directly by the executable code from a library
444   // is reinstanciated in the executable memory .data/.bss.
445   // We need to look up the variable in the execvutable first.
446   if (this->binary_info) {
447     std::shared_ptr<simgrid::mc::ObjectInformation> const& info = this->binary_info;
448     simgrid::mc::Variable* var = info->find_variable(name);
449     if (var)
450       return var;
451   }
452
453   for (std::shared_ptr<simgrid::mc::ObjectInformation> const& info : this->object_infos) {
454     simgrid::mc::Variable* var = info->find_variable(name);
455     if (var)
456       return var;
457   }
458
459   return NULL;
460 }
461
462 void Process::read_variable(const char* name, void* target, size_t size) const
463 {
464   simgrid::mc::Variable* var = this->find_variable(name);
465   if (!var->address)
466     xbt_die("No simple location for this variable");
467   if (!var->type->full_type)
468     xbt_die("Partial type for %s, cannot check size", name);
469   if ((size_t) var->type->full_type->byte_size != size)
470     xbt_die("Unexpected size for %s (expected %zi, was %zi)",
471       name, size, (size_t) var->type->full_type->byte_size);
472   this->read_bytes(target, size, remote(var->address));
473 }
474
475 char* Process::read_string(remote_ptr<void> address) const
476 {
477   if (!address)
478     return NULL;
479
480   off_t len = 128;
481   char* res = (char*) malloc(len);
482   off_t off = 0;
483
484   while (1) {
485     ssize_t c = pread(this->memory_file, res + off, len - off, (off_t) address.address() + off);
486     if (c == -1) {
487       if (errno == EINTR)
488         continue;
489       else
490         xbt_die("Could not read from from remote process");
491     }
492     if (c==0)
493       xbt_die("Could not read string from remote process");
494
495     void* p = memchr(res + off, '\0', c);
496     if (p)
497       return res;
498
499     off += c;
500     if (off == len) {
501       len *= 2;
502       res = (char*) realloc(res, len);
503     }
504   }
505 }
506
507 const void *Process::read_bytes(void* buffer, std::size_t size,
508   remote_ptr<void> address, int process_index,
509   AddressSpace::ReadMode mode) const
510 {
511   if (process_index != simgrid::mc::ProcessIndexDisabled) {
512     std::shared_ptr<simgrid::mc::ObjectInformation> const& info =
513       this->find_object_info_rw((void*)address.address());
514     // Segment overlap is not handled.
515 #ifdef HAVE_SMPI
516     if (info.get() && this->privatized(*info)) {
517       if (process_index < 0)
518         xbt_die("Missing process index");
519       if (process_index >= (int) MC_smpi_process_count())
520         xbt_die("Invalid process index");
521
522       // Read smpi_privatisation_regions from MCed:
523       smpi_privatisation_region_t remote_smpi_privatisation_regions =
524         mc_model_checker->process().read_variable<smpi_privatisation_region_t>(
525           "smpi_privatisation_regions");
526
527       s_smpi_privatisation_region_t privatisation_region =
528         mc_model_checker->process().read<s_smpi_privatisation_region_t>(
529           remote(remote_smpi_privatisation_regions + process_index));
530
531       // Address translation in the privaization segment:
532       size_t offset = address.address() - (std::uint64_t)info->start_rw;
533       address = remote((char*)privatisation_region.address + offset);
534     }
535 #endif
536   }
537
538   if (pread_whole(this->memory_file, buffer, size, address.address()) < 0)
539     xbt_die("Read from process %lli failed", (long long) this->pid_);
540   return buffer;
541 }
542
543 /** Write data to a process memory
544  *
545  *  @param process the process
546  *  @param local   local memory address (source)
547  *  @param remote  target process memory address (target)
548  *  @param len     data size
549  */
550 void Process::write_bytes(const void* buffer, size_t len, remote_ptr<void> address)
551 {
552   if (pwrite_whole(this->memory_file, buffer, len, address.address()) < 0)
553     xbt_die("Write to process %lli failed", (long long) this->pid_);
554 }
555
556 void Process::clear_bytes(remote_ptr<void> address, size_t len)
557 {
558   pthread_once(&zero_buffer_flag, MC_zero_buffer_init);
559   while (len) {
560     size_t s = len > zero_buffer_size ? zero_buffer_size : len;
561     this->write_bytes(zero_buffer, s, address);
562     address = remote((char*) address.address() + s);
563     len -= s;
564   }
565 }
566
567 void Process::ignore_region(std::uint64_t addr, std::size_t size)
568 {
569   IgnoredRegion region;
570   region.addr = addr;
571   region.size = size;
572
573   if (ignored_regions_.empty()) {
574     ignored_regions_.push_back(region);
575     return;
576   }
577
578   unsigned int cursor = 0;
579   IgnoredRegion* current_region = nullptr;
580
581   int start = 0;
582   int end = ignored_regions_.size() - 1;
583   while (start <= end) {
584     cursor = (start + end) / 2;
585     current_region = &ignored_regions_[cursor];
586     if (current_region->addr == addr) {
587       if (current_region->size == size)
588         return;
589       else if (current_region->size < size)
590         start = cursor + 1;
591       else
592         end = cursor - 1;
593     } else if (current_region->addr < addr)
594       start = cursor + 1;
595     else
596       end = cursor - 1;
597   }
598
599   std::size_t position;
600   if (current_region->addr == addr) {
601     if (current_region->size < size) {
602       position = cursor + 1;
603     } else {
604       position = cursor;
605     }
606   } else if (current_region->addr < addr) {
607     position = cursor + 1;
608   } else {
609     position = cursor;
610   }
611   ignored_regions_.insert(
612     ignored_regions_.begin() + position, region);
613 }
614
615 void Process::reset_soft_dirty()
616 {
617   if (this->clear_refs_fd_ < 0) {
618     this->clear_refs_fd_ = open_process_file(pid_, "clear_refs", O_WRONLY|O_CLOEXEC);
619     if (this->clear_refs_fd_ < 0)
620       xbt_die("Could not open clear_refs file for soft-dirty tracking. Run as root?");
621   }
622   if(::write(this->clear_refs_fd_, "4\n", 2) != 2)
623     xbt_die("Could not reset softdirty bits");
624 }
625
626 void Process::read_pagemap(uint64_t* pagemap, size_t page_start, size_t page_count)
627 {
628   if (pagemap_fd_ < 0) {
629     pagemap_fd_ = open_process_file(pid_, "pagemap", O_RDONLY|O_CLOEXEC);
630     if (pagemap_fd_ < 0)
631       xbt_die("Could not open pagemap file for soft-dirty tracking. Run as root?");
632   }
633   ssize_t bytesize = sizeof(uint64_t) * page_count;
634   off_t offset = sizeof(uint64_t) * page_start;
635   if (pread_whole(pagemap_fd_, pagemap, bytesize, offset) != bytesize)
636     xbt_die("Could not read pagemap");
637 }
638
639 void Process::ignore_heap(IgnoredHeapRegion const& region)
640 {
641   if (ignored_heap_.empty()) {
642     ignored_heap_.push_back(std::move(region));
643     return;
644   }
645
646   typedef std::vector<IgnoredHeapRegion>::size_type size_type;
647
648   size_type start = 0;
649   size_type end = ignored_heap_.size() - 1;
650
651   // Binary search the position of insertion:
652   size_type cursor;
653   while (start <= end) {
654     cursor = start + (end - start) / 2;
655     auto& current_region = ignored_heap_[cursor];
656     if (current_region.address == region.address)
657       return;
658     else if (current_region.address < region.address)
659       start = cursor + 1;
660     else if (cursor != 0)
661       end = cursor - 1;
662     // Avoid underflow:
663     else
664       break;
665   }
666
667   // Insert it mc_heap_ignore_region_t:
668   if (ignored_heap_[cursor].address < region.address)
669     ++cursor;
670   ignored_heap_.insert( ignored_heap_.begin() + cursor, region);
671 }
672
673 void Process::unignore_heap(void *address, size_t size)
674 {
675   typedef std::vector<IgnoredHeapRegion>::size_type size_type;
676
677   size_type start = 0;
678   size_type end = ignored_heap_.size() - 1;
679
680   // Binary search:
681   size_type cursor;
682   while (start <= end) {
683     cursor = (start + end) / 2;
684     auto& region = ignored_heap_[cursor];
685     if (region.address == address) {
686       ignored_heap_.erase(ignored_heap_.begin() + cursor);
687       return;
688     } else if (region.address < address)
689       start = cursor + 1;
690     else if ((char *) region.address <= ((char *) address + size)) {
691       ignored_heap_.erase(ignored_heap_.begin() + cursor);
692       return;
693     } else if (cursor != 0)
694       end = cursor - 1;
695     // Avoid underflow:
696     else
697       break;
698   }
699 }
700
701 void Process::ignore_local_variable(const char *var_name, const char *frame_name)
702 {
703   if (frame_name != nullptr && strcmp(frame_name, "*") == 0)
704     frame_name = nullptr;
705   for (std::shared_ptr<simgrid::mc::ObjectInformation> const& info :
706       this->object_infos)
707     info->remove_local_variable(var_name, frame_name);
708 }
709
710 }
711 }