Logo AND Algorithmique Numérique Distribuée

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