Logo AND Algorithmique Numérique Distribuée

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