Logo AND Algorithmique Numérique Distribuée

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