Logo AND Algorithmique Numérique Distribuée

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