Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
more than 100 codacy treats, not bad
[simgrid.git] / src / xbt / memory_map.cpp
1 /* Copyright (c) 2008-2015. The SimGrid Team.
2  * All rights reserved.                                                     */
3
4 /* This program is free software; you can redistribute it and/or modify it
5  * under the terms of the license (GNU LGPL) which comes with this package. */
6
7 #include <cstdlib>
8 #include <cstdio>
9 #include <cstring>
10
11 #include <sys/types.h>
12
13 #if defined __APPLE__
14 # include <mach/mach_init.h>
15 # include <mach/mach_traps.h>
16 # include <mach/mach_port.h>
17 # include <mach/mach_vm.h>
18 # include <sys/mman.h>
19 # include <sys/param.h>
20 # include <libproc.h>
21 # if __MAC_OS_X_VERSION_MIN_REQUIRED < 1050
22 #  define mach_vm_address_t vm_address_t
23 #  define mach_vm_size_t vm_size_t
24 #  if defined __ppc64__ || defined __x86_64__
25 #    define mach_vm_region vm_region64
26 #  else
27 #    define mach_vm_region vm_region
28 #  endif
29 # endif
30 #endif
31
32 #if defined __linux__
33 # include <sys/mman.h>
34 #endif
35
36 #if defined __FreeBSD__
37 # include <sys/types.h>
38 # include <sys/mman.h>
39 # include <sys/param.h>
40 # include <sys/queue.h>
41 # include <sys/socket.h>
42 # include <sys/sysctl.h>
43 # include <sys/user.h>
44 # include <libprocstat.h>
45 #endif
46
47 #include <xbt/sysdep.h>
48 #include <xbt/base.h>
49 #include <xbt/file.h>
50 #include <xbt/log.h>
51
52 #include "memory_map.hpp"
53
54 extern "C" {
55 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(xbt_memory_map, xbt, "Logging specific to algorithms for memory_map");
56 }
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     memregs.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 #if 0 /* Display mappings for debug */
155     fprintf(stderr,
156         "%#014llx - %#014llx | %c%c%c | %s\n",
157         memreg.start_addr, memreg.end_addr,
158         (memreg.prot & PROT_READ) ? 'r' : '-',
159         (memreg.prot & PROT_WRITE) ? 'w' : '-',
160         (memreg.prot & PROT_EXEC) ? 'x' : '-',
161         memreg.pathname.c_str());
162 #endif
163
164     ret.push_back(std::move(memreg));
165     address += size;
166   }
167
168   mach_port_deallocate(mach_task_self(), map);
169 #elif defined __linux__
170   /* Open the actual process's proc maps file and create the memory_map_t */
171   /* to be returned. */
172   char* path = bprintf("/proc/%i/maps", (int) pid);
173   FILE *fp = std::fopen(path, "r");
174   if (fp == nullptr) {
175     std::perror("fopen failed");
176     xbt_die("Cannot open %s to investigate the memory map of the process.", path);
177   }
178   free(path);
179   setbuf(fp, nullptr);
180
181   /* Read one line at the time, parse it and add it to the memory map to be returned */
182   ssize_t read; /* Number of bytes readed */
183   char* line = nullptr;
184   std::size_t n = 0; /* Amount of bytes to read by xbt_getline */
185   while ((read = xbt_getline(&line, &n, fp)) != -1) {
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
191     //fprintf(stderr,"%s", line);
192
193     /* Wipeout the new line character */
194     line[read - 1] = '\0';
195
196     /* Tokenize the line using spaces as delimiters and store each token in lfields array. We expect 5 tokens for 6 fields */
197     char* lfields[6];
198     lfields[0] = strtok(line, " ");
199
200     int i;
201     for (i = 1; i < 6 && lfields[i - 1] != nullptr; i++) {
202       lfields[i] = std::strtok(nullptr, " ");
203     }
204
205     /* Check to see if we got the expected amount of columns */
206     if (i < 6)
207       xbt_die("The memory map apparently only supplied less than 6 columns. Recovery impossible.");
208
209     /* Ok we are good enough to try to get the info we need */
210     /* First get the start and the end address of the map   */
211     char *tok = std::strtok(lfields[0], "-");
212     if (tok == nullptr)
213       xbt_die("Start and end address of the map are not concatenated by a hyphen (-). Recovery impossible.");
214
215     VmMap memreg;
216     char *endptr;
217     memreg.start_addr = std::strtoull(tok, &endptr, 16);
218     /* Make sure that the entire string was an hex number */
219     if (*endptr != '\0')
220       xbt_abort();
221
222     tok = std::strtok(nullptr, "-");
223     if (tok == nullptr)
224       xbt_abort();
225
226     memreg.end_addr = std::strtoull(tok, &endptr, 16);
227     /* Make sure that the entire string was an hex number */
228     if (*endptr != '\0')
229       xbt_abort();
230
231     /* Get the permissions flags */
232     if (std::strlen(lfields[1]) < 4)
233       xbt_abort();
234
235     memreg.prot = 0;
236
237     for (i = 0; i < 3; i++){
238       switch(lfields[1][i]){
239         case 'r':
240           memreg.prot |= PROT_READ;
241           break;
242         case 'w':
243           memreg.prot |= PROT_WRITE;
244           break;
245         case 'x':
246           memreg.prot |= PROT_EXEC;
247           break;
248         default:
249           break;
250       }
251     }
252     if (memreg.prot == 0)
253       memreg.prot |= PROT_NONE;
254
255     if (lfields[1][3] == 'p') {
256       memreg.flags |= MAP_PRIVATE;
257     } else {
258       memreg.flags |= MAP_SHARED;
259       if (lfields[1][3] != 's')
260         XBT_WARN("The protection is neither 'p' (private) nor 's' (shared) but '%s'. Let's assume shared, as on b0rken "
261                  "win-ubuntu systems.\nFull line: %s\n",
262                  lfields[1], line);
263     }
264
265     /* Get the offset value */
266     memreg.offset = std::strtoull(lfields[2], &endptr, 16);
267     /* Make sure that the entire string was an hex number */
268     if (*endptr != '\0')
269       xbt_abort();
270
271     /* Get the device major:minor bytes */
272     tok = std::strtok(lfields[3], ":");
273     if (tok == nullptr)
274       xbt_abort();
275
276     memreg.dev_major = (char) strtoul(tok, &endptr, 16);
277     /* Make sure that the entire string was an hex number */
278     if (*endptr != '\0')
279       xbt_abort();
280
281     tok = std::strtok(nullptr, ":");
282     if (tok == nullptr)
283       xbt_abort();
284
285     memreg.dev_minor = (char) std::strtoul(tok, &endptr, 16);
286     /* Make sure that the entire string was an hex number */
287     if (*endptr != '\0')
288       xbt_abort();
289
290     /* Get the inode number and make sure that the entire string was a long int */
291     memreg.inode = strtoul(lfields[4], &endptr, 10);
292     if (*endptr != '\0')
293       xbt_abort();
294
295     /* And finally get the pathname */
296     if (lfields[5])
297       memreg.pathname = lfields[5];
298
299     /* Create space for a new map region in the region's array and copy the */
300     /* parsed stuff from the temporal memreg variable */
301     XBT_DEBUG("Found region for %s", not memreg.pathname.empty() ? memreg.pathname.c_str() : "(null)");
302
303     ret.push_back(std::move(memreg));
304   }
305
306   std::free(line);
307   std::fclose(fp);
308 #elif defined __FreeBSD__
309   struct procstat *prstat;
310   struct kinfo_proc *proc;
311   struct kinfo_vmentry *vmentries;
312   unsigned int cnt;
313
314   if ((prstat = procstat_open_sysctl()) == NULL) {
315     std::perror("procstat_open_sysctl failed");
316     xbt_die("Cannot access kernel state information");
317   }
318   if ((proc = procstat_getprocs(prstat, KERN_PROC_PID, pid, &cnt)) == NULL) {
319     std::perror("procstat_open_sysctl failed");
320     xbt_die("Cannot access process information");
321   }
322   if ((vmentries = procstat_getvmmap(prstat, proc, &cnt)) == NULL) {
323     std::perror("procstat_getvmmap failed");
324     xbt_die("Cannot access process memory mappings");
325   }
326   for (unsigned int i = 0; i < cnt; i++) {
327     VmMap memreg;
328
329     /* Addresses */
330     memreg.start_addr = vmentries[i].kve_start;
331     memreg.end_addr = vmentries[i].kve_end;
332
333     /* Permissions */
334     memreg.prot = PROT_NONE;
335     if (vmentries[i].kve_protection & KVME_PROT_READ)
336       memreg.prot |= PROT_READ;
337     if (vmentries[i].kve_protection & KVME_PROT_WRITE)
338       memreg.prot |= PROT_WRITE;
339     if (vmentries[i].kve_protection & KVME_PROT_EXEC)
340       memreg.prot |= PROT_EXEC;
341
342     /* Private (copy-on-write) or shared? */
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
379         && ! (vmentries[i].kve_flags & KVME_FLAG_NEEDS_COPY))
380       memreg.prot &= ~PROT_WRITE;
381
382     ret.push_back(std::move(memreg));
383   }
384   procstat_freevmmap(prstat, vmentries);
385   procstat_freeprocs(prstat, proc);
386   procstat_close(prstat);
387 #else
388   xbt_die("Could not get memory map from process %lli", (long long int) pid);
389 #endif
390   return ret;
391 }
392
393 }
394 }