Logo AND Algorithmique Numérique Distribuée

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