Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Sonar still does not like #undef. Use a local variable to hide _xbt_log_cat_init.
[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 <cstdlib>
7 #include <cstdio>
8 #include <cstring>
9
10 #include <sys/types.h>
11
12 #if defined __APPLE__
13 # include <mach/mach_init.h>
14 # include <mach/mach_traps.h>
15 # include <mach/mach_port.h>
16 # include <mach/mach_vm.h>
17 # include <sys/mman.h>
18 # include <sys/param.h>
19 # include <libproc.h>
20 # if __MAC_OS_X_VERSION_MIN_REQUIRED < 1050
21 #  define mach_vm_address_t vm_address_t
22 #  define mach_vm_size_t vm_size_t
23 #  if defined __ppc64__ || defined __x86_64__
24 #    define mach_vm_region vm_region64
25 #  else
26 #    define mach_vm_region vm_region
27 #  endif
28 # endif
29 #endif
30
31 #if defined __linux__
32 # include <sys/mman.h>
33 #endif
34
35 #if defined __FreeBSD__
36 # include <sys/types.h>
37 # include <sys/mman.h>
38 # include <sys/param.h>
39 # include <sys/queue.h>
40 # include <sys/socket.h>
41 # include <sys/sysctl.h>
42 # include <sys/user.h>
43 # include <libprocstat.h>
44 #endif
45
46 #include <xbt/sysdep.h>
47 #include <xbt/base.h>
48 #include <xbt/file.h>
49 #include <xbt/log.h>
50
51 #include "memory_map.hpp"
52
53 extern "C" {
54 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(xbt_memory_map, xbt, "Logging specific to algorithms for memory_map");
55 }
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   char* path = bprintf("/proc/%i/maps", (int) pid);
172   FILE *fp = std::fopen(path, "r");
173   if (fp == nullptr) {
174     std::perror("fopen failed");
175     xbt_die("Cannot open %s to investigate the memory map of the process.", path);
176   }
177   free(path);
178   setbuf(fp, nullptr);
179
180   /* Read one line at the time, parse it and add it to the memory map to be returned */
181   ssize_t read; /* Number of bytes readed */
182   char* line = nullptr;
183   std::size_t n = 0; /* Amount of bytes to read by xbt_getline */
184   while ((read = xbt_getline(&line, &n, fp)) != -1) {
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
190     /* Wipeout the new line character */
191     line[read - 1] = '\0';
192
193     /* Tokenize the line using spaces as delimiters and store each token in lfields array. We expect 5 tokens for 6 fields */
194     char* saveptr = nullptr; // for strtok_r()
195     char* lfields[6];
196     lfields[0] = strtok_r(line, " ", &saveptr);
197
198     int i;
199     for (i = 1; i < 6 && lfields[i - 1] != nullptr; i++) {
200       lfields[i] = strtok_r(nullptr, " ", &saveptr);
201     }
202
203     /* Check to see if we got the expected amount of columns */
204     if (i < 6)
205       xbt_die("The memory map apparently only supplied less than 6 columns. Recovery impossible.");
206
207     /* Ok we are good enough to try to get the info we need */
208     /* First get the start and the end address of the map   */
209     char* tok = strtok_r(lfields[0], "-", &saveptr);
210     if (tok == nullptr)
211       xbt_die("Start and end address of the map are not concatenated by a hyphen (-). Recovery impossible.");
212
213     VmMap memreg;
214     char *endptr;
215     memreg.start_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     tok = strtok_r(nullptr, "-", &saveptr);
221     if (tok == nullptr)
222       xbt_abort();
223
224     memreg.end_addr = std::strtoull(tok, &endptr, 16);
225     /* Make sure that the entire string was an hex number */
226     if (*endptr != '\0')
227       xbt_abort();
228
229     /* Get the permissions flags */
230     if (std::strlen(lfields[1]) < 4)
231       xbt_abort();
232
233     memreg.prot = 0;
234     for (i = 0; i < 3; i++){
235       switch(lfields[1][i]){
236         case 'r':
237           memreg.prot |= PROT_READ;
238           break;
239         case 'w':
240           memreg.prot |= PROT_WRITE;
241           break;
242         case 'x':
243           memreg.prot |= PROT_EXEC;
244           break;
245         default:
246           break;
247       }
248     }
249     if (memreg.prot == 0)
250       memreg.prot |= PROT_NONE;
251
252     memreg.flags = 0;
253     if (lfields[1][3] == 'p') {
254       memreg.flags |= MAP_PRIVATE;
255     } else {
256       memreg.flags |= MAP_SHARED;
257       if (lfields[1][3] != 's')
258         XBT_WARN("The protection is neither 'p' (private) nor 's' (shared) but '%s'. Let's assume shared, as on b0rken "
259                  "win-ubuntu systems.\nFull line: %s\n",
260                  lfields[1], line);
261     }
262
263     /* Get the offset value */
264     memreg.offset = std::strtoull(lfields[2], &endptr, 16);
265     /* Make sure that the entire string was an hex number */
266     if (*endptr != '\0')
267       xbt_abort();
268
269     /* Get the device major:minor bytes */
270     tok = strtok_r(lfields[3], ":", &saveptr);
271     if (tok == nullptr)
272       xbt_abort();
273
274     memreg.dev_major = (char) strtoul(tok, &endptr, 16);
275     /* Make sure that the entire string was an hex number */
276     if (*endptr != '\0')
277       xbt_abort();
278
279     tok = strtok_r(nullptr, ":", &saveptr);
280     if (tok == nullptr)
281       xbt_abort();
282
283     memreg.dev_minor = (char) std::strtoul(tok, &endptr, 16);
284     /* Make sure that the entire string was an hex number */
285     if (*endptr != '\0')
286       xbt_abort();
287
288     /* Get the inode number and make sure that the entire string was a long int */
289     memreg.inode = strtoul(lfields[4], &endptr, 10);
290     if (*endptr != '\0')
291       xbt_abort();
292
293     /* And finally get the pathname */
294     if (lfields[5])
295       memreg.pathname = lfields[5];
296
297     /* Create space for a new map region in the region's array and copy the */
298     /* parsed stuff from the temporal memreg variable */
299     XBT_DEBUG("Found region for %s", not memreg.pathname.empty() ? memreg.pathname.c_str() : "(null)");
300
301     ret.push_back(std::move(memreg));
302   }
303
304   std::free(line);
305   std::fclose(fp);
306 #elif defined __FreeBSD__
307   struct procstat *prstat;
308   struct kinfo_proc *proc;
309   struct kinfo_vmentry *vmentries;
310   unsigned int cnt;
311
312   if ((prstat = procstat_open_sysctl()) == NULL) {
313     std::perror("procstat_open_sysctl failed");
314     xbt_die("Cannot access kernel state information");
315   }
316   if ((proc = procstat_getprocs(prstat, KERN_PROC_PID, pid, &cnt)) == NULL) {
317     std::perror("procstat_open_sysctl failed");
318     xbt_die("Cannot access process information");
319   }
320   if ((vmentries = procstat_getvmmap(prstat, proc, &cnt)) == NULL) {
321     std::perror("procstat_getvmmap failed");
322     xbt_die("Cannot access process memory mappings");
323   }
324   for (unsigned int i = 0; i < cnt; i++) {
325     VmMap memreg;
326
327     /* Addresses */
328     memreg.start_addr = vmentries[i].kve_start;
329     memreg.end_addr = vmentries[i].kve_end;
330
331     /* Permissions */
332     memreg.prot = PROT_NONE;
333     if (vmentries[i].kve_protection & KVME_PROT_READ)
334       memreg.prot |= PROT_READ;
335     if (vmentries[i].kve_protection & KVME_PROT_WRITE)
336       memreg.prot |= PROT_WRITE;
337     if (vmentries[i].kve_protection & KVME_PROT_EXEC)
338       memreg.prot |= PROT_EXEC;
339
340     /* Private (copy-on-write) or shared? */
341     memreg.flags = 0;
342     if (vmentries[i].kve_flags & KVME_FLAG_COW)
343       memreg.flags |= MAP_PRIVATE;
344     else
345       memreg.flags |= MAP_SHARED;
346
347     /* Offset */
348     memreg.offset = vmentries[i].kve_offset;
349
350     /* Device : not sure this can be mapped to something outside of Linux? */
351     memreg.dev_major = 0;
352     memreg.dev_minor = 0;
353
354     /* Inode */
355     memreg.inode = vmentries[i].kve_vn_fileid;
356
357      /*
358       * Path. Linuxize result by giving an anonymous mapping a path from
359       * the previous mapping, provided previous is vnode and has a path,
360       * and mark the stack.
361       */
362     if (vmentries[i].kve_path[0] != '\0')
363       memreg.pathname = vmentries[i].kve_path;
364     else if (vmentries[i].kve_type == KVME_TYPE_DEFAULT && vmentries[i - 1].kve_type == KVME_TYPE_VNODE &&
365              vmentries[i - 1].kve_path[0] != '\0')
366       memreg.pathname = vmentries[i-1].kve_path;
367     else if (vmentries[i].kve_type == KVME_TYPE_DEFAULT
368         && vmentries[i].kve_flags & KVME_FLAG_GROWS_DOWN)
369       memreg.pathname = "[stack]";
370
371     /*
372      * One last dirty modification: remove write permission from shared
373      * libraries private clean pages. This is necessary because simgrid
374      * later identifies mappings based on the permissions that are expected
375      * when running the Linux kernel.
376      */
377     if (vmentries[i].kve_type == KVME_TYPE_VNODE && not(vmentries[i].kve_flags & KVME_FLAG_NEEDS_COPY))
378       memreg.prot &= ~PROT_WRITE;
379
380     ret.push_back(std::move(memreg));
381   }
382   procstat_freevmmap(prstat, vmentries);
383   procstat_freeprocs(prstat, proc);
384   procstat_close(prstat);
385 #else
386   xbt_die("Could not get memory map from process %lli", (long long int) pid);
387 #endif
388   return ret;
389 }
390
391 }
392 }