Logo AND Algorithmique Numérique Distribuée

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