Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Update copyright lines for 2022.
[simgrid.git] / src / xbt / memory_map.cpp
1 /* Copyright (c) 2008-2022. 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 #define DEBUG_PRINT(...)                                                                                               \
63   if (false) {                                                                                                         \
64     fprintf(stderr, __VA_ARGS__);                                                                                      \
65   } else                                                                                                               \
66     ((void)0)
67
68 namespace simgrid {
69 namespace xbt {
70
71 /**
72  * \todo This function contains many cases that do not allow for a
73  *       recovery. Currently, abort() is called but we should
74  *       much rather die with the specific reason so that it's easier
75  *       to find out what's going on.
76  */
77 std::vector<VmMap> get_memory_map(pid_t pid)
78 {
79   std::vector<VmMap> ret;
80 #if defined __APPLE__
81   vm_map_t map;
82
83   /* Request authorization to read mappings */
84   if (task_for_pid(mach_task_self(), pid, &map) != KERN_SUCCESS) {
85     std::perror("task_for_pid failed");
86     std::fprintf(stderr, "Cannot request authorization for kernel information access\n");
87     abort();
88   }
89
90   /*
91    * Darwin do not give us the number of mappings, so we read entries until
92    * we get a KERN_INVALID_ADDRESS return.
93    */
94   mach_vm_address_t address = VM_MIN_ADDRESS;
95   while (true) {
96     kern_return_t kr;
97     memory_object_name_t object;
98     mach_vm_size_t size;
99 #if defined __ppc64__ || defined __x86_64__
100     vm_region_flavor_t flavor = VM_REGION_BASIC_INFO_64;
101     struct vm_region_basic_info_64 info;
102     mach_msg_type_number_t info_count = VM_REGION_BASIC_INFO_COUNT_64;
103 #else
104     vm_region_flavor_t flavor = VM_REGION_BASIC_INFO;
105     struct vm_region_basic_info info;
106     mach_msg_type_number_t info_count = VM_REGION_BASIC_INFO_COUNT;
107 #endif
108
109     kr =
110       mach_vm_region(
111           map,
112           &address,
113           &size,
114           flavor,
115           (vm_region_info_t)&info,
116           &info_count,
117           &object);
118     if (kr == KERN_INVALID_ADDRESS) {
119       break;
120     }
121     else if (kr != KERN_SUCCESS) {
122       std::perror("mach_vm_region failed");
123       std::fprintf(stderr, "Cannot request authorization for kernel information access\n");
124       abort();
125     }
126
127     VmMap memreg;
128
129     /* Addresses */
130     memreg.start_addr = address;
131     memreg.end_addr = address + size;
132
133     /* Permissions */
134     memreg.prot = PROT_NONE;
135     if (info.protection & VM_PROT_READ)
136       memreg.prot |= PROT_READ;
137     if (info.protection & VM_PROT_WRITE)
138       memreg.prot |= PROT_WRITE;
139     if (info.protection & VM_PROT_EXECUTE)
140       memreg.prot |= PROT_EXEC;
141
142     /* Private (copy-on-write) or shared? */
143     memreg.flags = 0;
144     if (info.shared)
145       memreg.flags |= MAP_SHARED;
146     else
147       memreg.flags |= MAP_PRIVATE;
148
149     /* Offset */
150     memreg.offset = info.offset;
151
152     /* Device : not sure this can be mapped to something outside of Linux? */
153     memreg.dev_major = 0;
154     memreg.dev_minor = 0;
155
156     /* Inode */
157     memreg.inode = 0;
158
159     /* Path */
160     Dl_info dlinfo;
161     if (dladdr(reinterpret_cast<void*>(address), &dlinfo))
162       memreg.pathname = dlinfo.dli_fname;
163
164     DEBUG_PRINT("Region: %016" PRIx64 "-%016" PRIx64 " | %c%c%c | %s\n", memreg.start_addr, memreg.end_addr,
165                 (memreg.prot & PROT_READ) ? 'r' : '-', (memreg.prot & PROT_WRITE) ? 'w' : '-',
166                 (memreg.prot & PROT_EXEC) ? 'x' : '-', memreg.pathname.c_str());
167
168     ret.push_back(std::move(memreg));
169     address += size;
170   }
171
172   mach_port_deallocate(mach_task_self(), map);
173 #elif defined __linux__
174   /* Open the actual process's proc maps file and create the memory_map_t */
175   /* to be returned. */
176   std::string path = std::string("/proc/") + std::to_string(pid) + "/maps";
177   std::ifstream fp;
178   fp.rdbuf()->pubsetbuf(nullptr, 0);
179   fp.open(path);
180   if (not fp) {
181     std::perror("open failed");
182     std::fprintf(stderr, "Cannot open %s to investigate the memory map of the process.\n", path.c_str());
183     abort();
184   }
185
186   /* Read one line at the time, parse it and add it to the memory map to be returned */
187   std::string sline;
188   while (std::getline(fp, sline)) {
189     /**
190      * The lines that we read have this format: (This is just an example)
191      * 00602000-00603000 rw-p 00002000 00:28 1837264                            <complete-path-to-file>
192      */
193     char* line = &sline[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* saveptr = nullptr; // for strtok_r()
197     std::array<char*, 6> lfields;
198     lfields[0] = strtok_r(line, " ", &saveptr);
199
200     int i;
201     for (i = 1; i < 6 && lfields[i - 1] != nullptr; i++) {
202       lfields[i] = strtok_r(nullptr, " ", &saveptr);
203     }
204
205     /* Check to see if we got the expected amount of columns */
206     if (i < 6) {
207       std::fprintf(stderr, "The memory map apparently only supplied less than 6 columns. Recovery impossible.\n");
208       abort();
209     }
210
211     /* Ok we are good enough to try to get the info we need */
212     /* First get the start and the end address of the map   */
213     const char* tok = strtok_r(lfields[0], "-", &saveptr);
214     if (tok == nullptr) {
215       std::fprintf(stderr,
216                    "Start and end address of the map are not concatenated by a hyphen (-). Recovery impossible.\n");
217       abort();
218     }
219
220     VmMap memreg;
221     char *endptr;
222     memreg.start_addr = std::strtoull(tok, &endptr, 16);
223     /* Make sure that the entire string was an hex number */
224     CHECK(*endptr == '\0');
225
226     tok = strtok_r(nullptr, "-", &saveptr);
227     CHECK(tok != nullptr);
228
229     memreg.end_addr = std::strtoull(tok, &endptr, 16);
230     /* Make sure that the entire string was an hex number */
231     CHECK(*endptr == '\0');
232
233     /* Get the permissions flags */
234     CHECK(std::strlen(lfields[1]) >= 4);
235
236     memreg.prot = 0;
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     memreg.flags = 0;
256     if (lfields[1][3] == 'p') {
257       memreg.flags |= MAP_PRIVATE;
258     } else {
259       memreg.flags |= MAP_SHARED;
260       if (lfields[1][3] != 's')
261         fprintf(stderr,
262                 "The protection is neither 'p' (private) nor 's' (shared) but '%s'. Let's assume shared, as on b0rken "
263                 "win-ubuntu systems.\nFull line: %s\n",
264                 lfields[1], line);
265     }
266
267     /* Get the offset value */
268     memreg.offset = std::strtoull(lfields[2], &endptr, 16);
269     /* Make sure that the entire string was an hex number */
270     CHECK(*endptr == '\0');
271
272     /* Get the device major:minor bytes */
273     tok = strtok_r(lfields[3], ":", &saveptr);
274     CHECK(tok != nullptr);
275
276     memreg.dev_major = (char) strtoul(tok, &endptr, 16);
277     /* Make sure that the entire string was an hex number */
278     CHECK(*endptr == '\0');
279
280     tok = strtok_r(nullptr, ":", &saveptr);
281     CHECK(tok != nullptr);
282
283     memreg.dev_minor = (char) std::strtoul(tok, &endptr, 16);
284     /* Make sure that the entire string was an hex number */
285     CHECK(*endptr == '\0');
286
287     /* Get the inode number and make sure that the entire string was a long int */
288     memreg.inode = strtoul(lfields[4], &endptr, 10);
289     CHECK(*endptr == '\0');
290
291     /* And finally get the pathname */
292     if (lfields[5])
293       memreg.pathname = lfields[5];
294
295     /* Create space for a new map region in the region's array and copy the */
296     /* parsed stuff from the temporal memreg variable */
297     DEBUG_PRINT("Found region for \"%s\"\n", memreg.pathname.c_str());
298
299     ret.push_back(std::move(memreg));
300   }
301
302   fp.close();
303 #elif defined __FreeBSD__
304   struct procstat *prstat;
305   struct kinfo_proc *proc;
306   struct kinfo_vmentry *vmentries;
307   unsigned int cnt;
308
309   if ((prstat = procstat_open_sysctl()) == NULL) {
310     std::perror("procstat_open_sysctl failed");
311     std::fprintf(stderr, "Cannot access kernel state information\n");
312     abort();
313   }
314   if ((proc = procstat_getprocs(prstat, KERN_PROC_PID, pid, &cnt)) == NULL) {
315     std::perror("procstat_open_sysctl failed");
316     std::fprintf(stderr, "Cannot access process information\n");
317     abort();
318   }
319   if ((vmentries = procstat_getvmmap(prstat, proc, &cnt)) == NULL) {
320     std::perror("procstat_getvmmap failed");
321     std::fprintf(stderr, "Cannot access process memory mappings\n");
322     abort();
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   std::fprintf(stderr, "Could not get memory map from process %lli\n", (long long int)pid);
387   abort();
388 #endif
389   return ret;
390 }
391
392 }
393 }