Logo AND Algorithmique Numérique Distribuée

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