Logo AND Algorithmique Numérique Distribuée

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