Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Merge branch 'master' into actor-yield
[simgrid.git] / src / xbt / memory_map.cpp
1 /* Copyright (c) 2008-2017. The SimGrid Team. All rights reserved.          */
2
3 /* This program is free software; you can redistribute it and/or modify it
4  * under the terms of the license (GNU LGPL) which comes with this package. */
5
6 #include <cstdio>
7 #include <cstdlib>
8 #include <cstring>
9 #include <fstream>
10 #include <iostream>
11 #include <string>
12
13 #include <sys/types.h>
14
15 #if defined __APPLE__
16 # include <mach/mach_init.h>
17 # include <mach/mach_traps.h>
18 # include <mach/mach_port.h>
19 # include <mach/mach_vm.h>
20 # include <sys/mman.h>
21 # include <sys/param.h>
22 # include <libproc.h>
23 # if __MAC_OS_X_VERSION_MIN_REQUIRED < 1050
24 #  define mach_vm_address_t vm_address_t
25 #  define mach_vm_size_t vm_size_t
26 #  if defined __ppc64__ || defined __x86_64__
27 #    define mach_vm_region vm_region64
28 #  else
29 #    define mach_vm_region vm_region
30 #  endif
31 # endif
32 #endif
33
34 #if defined __linux__
35 # include <sys/mman.h>
36 #endif
37
38 #if defined __FreeBSD__
39 # include <sys/types.h>
40 # include <sys/mman.h>
41 # include <sys/param.h>
42 # include <sys/queue.h>
43 # include <sys/socket.h>
44 # include <sys/sysctl.h>
45 # include <sys/user.h>
46 # include <libprocstat.h>
47 #endif
48
49 #include <xbt/sysdep.h>
50 #include <xbt/base.h>
51 #include <xbt/log.h>
52
53 #include "memory_map.hpp"
54
55 extern "C" {
56 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(xbt_memory_map, xbt, "Logging specific to algorithms for memory_map");
57 }
58
59 namespace simgrid {
60 namespace xbt {
61
62 /**
63  * \todo This function contains many cases that do not allow for a
64  *       recovery. Currently, xbt_abort() is called but we should
65  *       much rather die with the specific reason so that it's easier
66  *       to find out what's going on.
67  */
68 XBT_PRIVATE std::vector<VmMap> get_memory_map(pid_t pid)
69 {
70   std::vector<VmMap> ret;
71 #if defined __APPLE__
72   vm_map_t map;
73
74   /* Request authorization to read mappings */
75   if (task_for_pid(mach_task_self(), pid, &map) != KERN_SUCCESS) {
76     std::perror("task_for_pid failed");
77     xbt_die("Cannot request authorization for kernel information access");
78   }
79
80   /*
81    * Darwin do not give us the number of mappings, so we read entries until
82    * we get an KERN_INVALID_ADDRESS return.
83    */
84   mach_vm_address_t address = VM_MIN_ADDRESS;
85   while (true) {
86     kern_return_t kr;
87     memory_object_name_t object;
88     mach_vm_size_t size;
89 #if defined __ppc64__ || defined __x86_64__
90     vm_region_flavor_t flavor = VM_REGION_BASIC_INFO_64;
91     struct vm_region_basic_info_64 info;
92     mach_msg_type_number_t info_count = VM_REGION_BASIC_INFO_COUNT_64;
93 #else
94     vm_region_flavor_t flavor = VM_REGION_BASIC_INFO;
95     struct vm_region_basic_info info;
96     mach_msg_type_number_t info_count = VM_REGION_BASIC_INFO_COUNT;
97 #endif
98
99     kr =
100       mach_vm_region(
101           map,
102           &address,
103           &size,
104           flavor,
105           (vm_region_info_t)&info,
106           &info_count,
107           &object);
108     if (kr == KERN_INVALID_ADDRESS) {
109       break;
110     }
111     else if (kr != KERN_SUCCESS) {
112       std::perror("mach_vm_region failed");
113       xbt_die("Cannot request authorization for kernel information access");
114     }
115
116     VmMap memreg;
117
118     /* Addresses */
119     memreg.start_addr = address;
120     memreg.end_addr = address + size;
121
122     /* Permissions */
123     memreg.prot = PROT_NONE;
124     if (info.protection & VM_PROT_READ)
125       memreg.prot |= PROT_READ;
126     if (info.protection & VM_PROT_WRITE)
127       memreg.prot |= PROT_WRITE;
128     if (info.protection & VM_PROT_EXECUTE)
129       memreg.prot |= PROT_EXEC;
130
131     /* Private (copy-on-write) or shared? */
132     memreg.flags = 0;
133     if (info.shared)
134       memreg.flags |= MAP_SHARED;
135     else
136       memreg.flags |= MAP_PRIVATE;
137
138     /* Offset */
139     memreg.offset = info.offset;
140
141     /* Device : not sure this can be mapped to something outside of Linux? */
142     memreg.dev_major = 0;
143     memreg.dev_minor = 0;
144
145     /* Inode */
146     memreg.inode = 0;
147
148     /* Path */
149     char path[MAXPATHLEN];
150     int pathlen;
151     pathlen = proc_regionfilename(pid, address, path, sizeof(path));
152     path[pathlen]   = '\0';
153     memreg.pathname = path;
154
155 #if 0 /* Display mappings for debug */
156     fprintf(stderr,
157         "%#014llx - %#014llx | %c%c%c | %s\n",
158         memreg.start_addr, memreg.end_addr,
159         (memreg.prot & PROT_READ) ? 'r' : '-',
160         (memreg.prot & PROT_WRITE) ? 'w' : '-',
161         (memreg.prot & PROT_EXEC) ? 'x' : '-',
162         memreg.pathname.c_str());
163 #endif
164
165     ret.push_back(std::move(memreg));
166     address += size;
167   }
168
169   mach_port_deallocate(mach_task_self(), map);
170 #elif defined __linux__
171   /* Open the actual process's proc maps file and create the memory_map_t */
172   /* to be returned. */
173   std::string path = std::string("/proc/") + std::to_string(pid) + "/maps";
174   std::ifstream fp;
175   fp.rdbuf()->pubsetbuf(0, 0);
176   fp.open(path);
177   if (not fp) {
178     std::perror("open failed");
179     xbt_die("Cannot open %s to investigate the memory map of the process.", path.c_str());
180   }
181
182   /* Read one line at the time, parse it and add it to the memory map to be returned */
183   std::string sline;
184   while (std::getline(fp, sline)) {
185     /**
186      * The lines that we read have this format: (This is just an example)
187      * 00602000-00603000 rw-p 00002000 00:28 1837264                            <complete-path-to-file>
188      */
189     char* line = &sline[0];
190
191     /* Tokenize the line using spaces as delimiters and store each token in lfields array. We expect 5 tokens for 6 fields */
192     char* saveptr = nullptr; // for strtok_r()
193     char* lfields[6];
194     lfields[0] = strtok_r(line, " ", &saveptr);
195
196     int i;
197     for (i = 1; i < 6 && lfields[i - 1] != nullptr; i++) {
198       lfields[i] = strtok_r(nullptr, " ", &saveptr);
199     }
200
201     /* Check to see if we got the expected amount of columns */
202     if (i < 6)
203       xbt_die("The memory map apparently only supplied less than 6 columns. Recovery impossible.");
204
205     /* Ok we are good enough to try to get the info we need */
206     /* First get the start and the end address of the map   */
207     char* tok = strtok_r(lfields[0], "-", &saveptr);
208     if (tok == nullptr)
209       xbt_die("Start and end address of the map are not concatenated by a hyphen (-). Recovery impossible.");
210
211     VmMap memreg;
212     char *endptr;
213     memreg.start_addr = std::strtoull(tok, &endptr, 16);
214     /* Make sure that the entire string was an hex number */
215     if (*endptr != '\0')
216       xbt_abort();
217
218     tok = strtok_r(nullptr, "-", &saveptr);
219     if (tok == nullptr)
220       xbt_abort();
221
222     memreg.end_addr = std::strtoull(tok, &endptr, 16);
223     /* Make sure that the entire string was an hex number */
224     if (*endptr != '\0')
225       xbt_abort();
226
227     /* Get the permissions flags */
228     if (std::strlen(lfields[1]) < 4)
229       xbt_abort();
230
231     memreg.prot = 0;
232     for (i = 0; i < 3; i++){
233       switch(lfields[1][i]){
234         case 'r':
235           memreg.prot |= PROT_READ;
236           break;
237         case 'w':
238           memreg.prot |= PROT_WRITE;
239           break;
240         case 'x':
241           memreg.prot |= PROT_EXEC;
242           break;
243         default:
244           break;
245       }
246     }
247     if (memreg.prot == 0)
248       memreg.prot |= PROT_NONE;
249
250     memreg.flags = 0;
251     if (lfields[1][3] == 'p') {
252       memreg.flags |= MAP_PRIVATE;
253     } else {
254       memreg.flags |= MAP_SHARED;
255       if (lfields[1][3] != 's')
256         XBT_WARN("The protection is neither 'p' (private) nor 's' (shared) but '%s'. Let's assume shared, as on b0rken "
257                  "win-ubuntu systems.\nFull line: %s\n",
258                  lfields[1], line);
259     }
260
261     /* Get the offset value */
262     memreg.offset = std::strtoull(lfields[2], &endptr, 16);
263     /* Make sure that the entire string was an hex number */
264     if (*endptr != '\0')
265       xbt_abort();
266
267     /* Get the device major:minor bytes */
268     tok = strtok_r(lfields[3], ":", &saveptr);
269     if (tok == nullptr)
270       xbt_abort();
271
272     memreg.dev_major = (char) strtoul(tok, &endptr, 16);
273     /* Make sure that the entire string was an hex number */
274     if (*endptr != '\0')
275       xbt_abort();
276
277     tok = strtok_r(nullptr, ":", &saveptr);
278     if (tok == nullptr)
279       xbt_abort();
280
281     memreg.dev_minor = (char) std::strtoul(tok, &endptr, 16);
282     /* Make sure that the entire string was an hex number */
283     if (*endptr != '\0')
284       xbt_abort();
285
286     /* Get the inode number and make sure that the entire string was a long int */
287     memreg.inode = strtoul(lfields[4], &endptr, 10);
288     if (*endptr != '\0')
289       xbt_abort();
290
291     /* And finally get the pathname */
292     if (lfields[5])
293       memreg.pathname = lfields[5];
294
295     /* Create space for a new map region in the region's array and copy the */
296     /* parsed stuff from the temporal memreg variable */
297     XBT_DEBUG("Found region for %s", not memreg.pathname.empty() ? memreg.pathname.c_str() : "(null)");
298
299     ret.push_back(std::move(memreg));
300   }
301
302   fp.close();
303 #elif defined __FreeBSD__
304   struct procstat *prstat;
305   struct kinfo_proc *proc;
306   struct kinfo_vmentry *vmentries;
307   unsigned int cnt;
308
309   if ((prstat = procstat_open_sysctl()) == NULL) {
310     std::perror("procstat_open_sysctl failed");
311     xbt_die("Cannot access kernel state information");
312   }
313   if ((proc = procstat_getprocs(prstat, KERN_PROC_PID, pid, &cnt)) == NULL) {
314     std::perror("procstat_open_sysctl failed");
315     xbt_die("Cannot access process information");
316   }
317   if ((vmentries = procstat_getvmmap(prstat, proc, &cnt)) == NULL) {
318     std::perror("procstat_getvmmap failed");
319     xbt_die("Cannot access process memory mappings");
320   }
321   for (unsigned int i = 0; i < cnt; i++) {
322     VmMap memreg;
323
324     /* Addresses */
325     memreg.start_addr = vmentries[i].kve_start;
326     memreg.end_addr = vmentries[i].kve_end;
327
328     /* Permissions */
329     memreg.prot = PROT_NONE;
330     if (vmentries[i].kve_protection & KVME_PROT_READ)
331       memreg.prot |= PROT_READ;
332     if (vmentries[i].kve_protection & KVME_PROT_WRITE)
333       memreg.prot |= PROT_WRITE;
334     if (vmentries[i].kve_protection & KVME_PROT_EXEC)
335       memreg.prot |= PROT_EXEC;
336
337     /* Private (copy-on-write) or shared? */
338     memreg.flags = 0;
339     if (vmentries[i].kve_flags & KVME_FLAG_COW)
340       memreg.flags |= MAP_PRIVATE;
341     else
342       memreg.flags |= MAP_SHARED;
343
344     /* Offset */
345     memreg.offset = vmentries[i].kve_offset;
346
347     /* Device : not sure this can be mapped to something outside of Linux? */
348     memreg.dev_major = 0;
349     memreg.dev_minor = 0;
350
351     /* Inode */
352     memreg.inode = vmentries[i].kve_vn_fileid;
353
354      /*
355       * Path. Linuxize result by giving an anonymous mapping a path from
356       * the previous mapping, provided previous is vnode and has a path,
357       * and mark the stack.
358       */
359     if (vmentries[i].kve_path[0] != '\0')
360       memreg.pathname = vmentries[i].kve_path;
361     else if (vmentries[i].kve_type == KVME_TYPE_DEFAULT && vmentries[i - 1].kve_type == KVME_TYPE_VNODE &&
362              vmentries[i - 1].kve_path[0] != '\0')
363       memreg.pathname = vmentries[i-1].kve_path;
364     else if (vmentries[i].kve_type == KVME_TYPE_DEFAULT
365         && vmentries[i].kve_flags & KVME_FLAG_GROWS_DOWN)
366       memreg.pathname = "[stack]";
367
368     /*
369      * One last dirty modification: remove write permission from shared
370      * libraries private clean pages. This is necessary because simgrid
371      * later identifies mappings based on the permissions that are expected
372      * when running the Linux kernel.
373      */
374     if (vmentries[i].kve_type == KVME_TYPE_VNODE && not(vmentries[i].kve_flags & KVME_FLAG_NEEDS_COPY))
375       memreg.prot &= ~PROT_WRITE;
376
377     ret.push_back(std::move(memreg));
378   }
379   procstat_freevmmap(prstat, vmentries);
380   procstat_freeprocs(prstat, proc);
381   procstat_close(prstat);
382 #else
383   xbt_die("Could not get memory map from process %lli", (long long int) pid);
384 #endif
385   return ret;
386 }
387
388 }
389 }