Logo AND Algorithmique Numérique Distribuée

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