Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Merge branch 'master' of git+ssh://scm.gforge.inria.fr//gitroot/simgrid/simgrid
[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     //fprintf(stderr,"%s", line);
191
192     /* Wipeout the new line character */
193     line[read - 1] = '\0';
194
195     /* Tokenize the line using spaces as delimiters and store each token in lfields array. We expect 5 tokens for 6 fields */
196     char* lfields[6];
197     lfields[0] = strtok(line, " ");
198
199     int i;
200     for (i = 1; i < 6 && lfields[i - 1] != nullptr; i++) {
201       lfields[i] = std::strtok(nullptr, " ");
202     }
203
204     /* Check to see if we got the expected amount of columns */
205     if (i < 6)
206       xbt_die("The memory map apparently only supplied less than 6 columns. Recovery impossible.");
207
208     /* Ok we are good enough to try to get the info we need */
209     /* First get the start and the end address of the map   */
210     char *tok = std::strtok(lfields[0], "-");
211     if (tok == nullptr)
212       xbt_die("Start and end address of the map are not concatenated by a hyphen (-). Recovery impossible.");
213
214     VmMap memreg;
215     char *endptr;
216     memreg.start_addr = std::strtoull(tok, &endptr, 16);
217     /* Make sure that the entire string was an hex number */
218     if (*endptr != '\0')
219       xbt_abort();
220
221     tok = std::strtok(nullptr, "-");
222     if (tok == nullptr)
223       xbt_abort();
224
225     memreg.end_addr = std::strtoull(tok, &endptr, 16);
226     /* Make sure that the entire string was an hex number */
227     if (*endptr != '\0')
228       xbt_abort();
229
230     /* Get the permissions flags */
231     if (std::strlen(lfields[1]) < 4)
232       xbt_abort();
233
234     memreg.prot = 0;
235
236     for (i = 0; i < 3; i++){
237       switch(lfields[1][i]){
238         case 'r':
239           memreg.prot |= PROT_READ;
240           break;
241         case 'w':
242           memreg.prot |= PROT_WRITE;
243           break;
244         case 'x':
245           memreg.prot |= PROT_EXEC;
246           break;
247         default:
248           break;
249       }
250     }
251     if (memreg.prot == 0)
252       memreg.prot |= PROT_NONE;
253
254     if (lfields[1][3] == 'p') {
255       memreg.flags |= MAP_PRIVATE;
256     } else {
257       memreg.flags |= MAP_SHARED;
258       if (lfields[1][3] != 's')
259         XBT_WARN("The protection is neither 'p' (private) nor 's' (shared) but '%s'. Let's assume shared, as on b0rken "
260                  "win-ubuntu systems.\nFull line: %s\n",
261                  lfields[1], line);
262     }
263
264     /* Get the offset value */
265     memreg.offset = std::strtoull(lfields[2], &endptr, 16);
266     /* Make sure that the entire string was an hex number */
267     if (*endptr != '\0')
268       xbt_abort();
269
270     /* Get the device major:minor bytes */
271     tok = std::strtok(lfields[3], ":");
272     if (tok == nullptr)
273       xbt_abort();
274
275     memreg.dev_major = (char) strtoul(tok, &endptr, 16);
276     /* Make sure that the entire string was an hex number */
277     if (*endptr != '\0')
278       xbt_abort();
279
280     tok = std::strtok(nullptr, ":");
281     if (tok == nullptr)
282       xbt_abort();
283
284     memreg.dev_minor = (char) std::strtoul(tok, &endptr, 16);
285     /* Make sure that the entire string was an hex number */
286     if (*endptr != '\0')
287       xbt_abort();
288
289     /* Get the inode number and make sure that the entire string was a long int */
290     memreg.inode = strtoul(lfields[4], &endptr, 10);
291     if (*endptr != '\0')
292       xbt_abort();
293
294     /* And finally get the pathname */
295     if (lfields[5])
296       memreg.pathname = lfields[5];
297
298     /* Create space for a new map region in the region's array and copy the */
299     /* parsed stuff from the temporal memreg variable */
300     XBT_DEBUG("Found region for %s", not memreg.pathname.empty() ? memreg.pathname.c_str() : "(null)");
301
302     ret.push_back(std::move(memreg));
303   }
304
305   std::free(line);
306   std::fclose(fp);
307 #elif defined __FreeBSD__
308   struct procstat *prstat;
309   struct kinfo_proc *proc;
310   struct kinfo_vmentry *vmentries;
311   unsigned int cnt;
312
313   if ((prstat = procstat_open_sysctl()) == NULL) {
314     std::perror("procstat_open_sysctl failed");
315     xbt_die("Cannot access kernel state information");
316   }
317   if ((proc = procstat_getprocs(prstat, KERN_PROC_PID, pid, &cnt)) == NULL) {
318     std::perror("procstat_open_sysctl failed");
319     xbt_die("Cannot access process information");
320   }
321   if ((vmentries = procstat_getvmmap(prstat, proc, &cnt)) == NULL) {
322     std::perror("procstat_getvmmap failed");
323     xbt_die("Cannot access process memory mappings");
324   }
325   for (unsigned int i = 0; i < cnt; i++) {
326     VmMap memreg;
327
328     /* Addresses */
329     memreg.start_addr = vmentries[i].kve_start;
330     memreg.end_addr = vmentries[i].kve_end;
331
332     /* Permissions */
333     memreg.prot = PROT_NONE;
334     if (vmentries[i].kve_protection & KVME_PROT_READ)
335       memreg.prot |= PROT_READ;
336     if (vmentries[i].kve_protection & KVME_PROT_WRITE)
337       memreg.prot |= PROT_WRITE;
338     if (vmentries[i].kve_protection & KVME_PROT_EXEC)
339       memreg.prot |= PROT_EXEC;
340
341     /* Private (copy-on-write) or shared? */
342     memreg.flags = 0;
343     if (vmentries[i].kve_flags & KVME_FLAG_COW)
344       memreg.flags |= MAP_PRIVATE;
345     else
346       memreg.flags |= MAP_SHARED;
347
348     /* Offset */
349     memreg.offset = vmentries[i].kve_offset;
350
351     /* Device : not sure this can be mapped to something outside of Linux? */
352     memreg.dev_major = 0;
353     memreg.dev_minor = 0;
354
355     /* Inode */
356     memreg.inode = vmentries[i].kve_vn_fileid;
357
358      /*
359       * Path. Linuxize result by giving an anonymous mapping a path from
360       * the previous mapping, provided previous is vnode and has a path,
361       * and mark the stack.
362       */
363     if (vmentries[i].kve_path[0] != '\0')
364       memreg.pathname = vmentries[i].kve_path;
365     else if (vmentries[i].kve_type == KVME_TYPE_DEFAULT && vmentries[i - 1].kve_type == KVME_TYPE_VNODE &&
366              vmentries[i - 1].kve_path[0] != '\0')
367       memreg.pathname = vmentries[i-1].kve_path;
368     else if (vmentries[i].kve_type == KVME_TYPE_DEFAULT
369         && vmentries[i].kve_flags & KVME_FLAG_GROWS_DOWN)
370       memreg.pathname = "[stack]";
371
372     /*
373      * One last dirty modification: remove write permission from shared
374      * libraries private clean pages. This is necessary because simgrid
375      * later identifies mappings based on the permissions that are expected
376      * when running the Linux kernel.
377      */
378     if (vmentries[i].kve_type == KVME_TYPE_VNODE && not(vmentries[i].kve_flags & KVME_FLAG_NEEDS_COPY))
379       memreg.prot &= ~PROT_WRITE;
380
381     ret.push_back(std::move(memreg));
382   }
383   procstat_freevmmap(prstat, vmentries);
384   procstat_freeprocs(prstat, proc);
385   procstat_close(prstat);
386 #else
387   xbt_die("Could not get memory map from process %lli", (long long int) pid);
388 #endif
389   return ret;
390 }
391
392 }
393 }