Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
migrate execute_tasks from simix::Global to kernel::EngineImpl
[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 0 /* 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 #endif
163
164     ret.push_back(std::move(memreg));
165     address += size;
166   }
167
168   mach_port_deallocate(mach_task_self(), map);
169 #elif defined __linux__
170   /* Open the actual process's proc maps file and create the memory_map_t */
171   /* to be returned. */
172   std::string path = std::string("/proc/") + std::to_string(pid) + "/maps";
173   std::ifstream fp;
174   fp.rdbuf()->pubsetbuf(nullptr, 0);
175   fp.open(path);
176   if (not fp) {
177     std::perror("open failed");
178     std::fprintf(stderr, "Cannot open %s to investigate the memory map of the process.\n", path.c_str());
179     abort();
180   }
181
182   /* Read one line at the time, parse it and add it to the memory map to be returned */
183   std::string sline;
184   while (std::getline(fp, sline)) {
185     /**
186      * The lines that we read have this format: (This is just an example)
187      * 00602000-00603000 rw-p 00002000 00:28 1837264                            <complete-path-to-file>
188      */
189     char* line = &sline[0];
190
191     /* Tokenize the line using spaces as delimiters and store each token in lfields array. We expect 5 tokens for 6 fields */
192     char* saveptr = nullptr; // for strtok_r()
193     std::array<char*, 6> lfields;
194     lfields[0] = strtok_r(line, " ", &saveptr);
195
196     int i;
197     for (i = 1; i < 6 && lfields[i - 1] != nullptr; i++) {
198       lfields[i] = strtok_r(nullptr, " ", &saveptr);
199     }
200
201     /* Check to see if we got the expected amount of columns */
202     if (i < 6) {
203       std::fprintf(stderr, "The memory map apparently only supplied less than 6 columns. Recovery impossible.\n");
204       abort();
205     }
206
207     /* Ok we are good enough to try to get the info we need */
208     /* First get the start and the end address of the map   */
209     const char* tok = strtok_r(lfields[0], "-", &saveptr);
210     if (tok == nullptr) {
211       std::fprintf(stderr,
212                    "Start and end address of the map are not concatenated by a hyphen (-). Recovery impossible.\n");
213       abort();
214     }
215
216     VmMap memreg;
217     char *endptr;
218     memreg.start_addr = std::strtoull(tok, &endptr, 16);
219     /* Make sure that the entire string was an hex number */
220     CHECK(*endptr == '\0');
221
222     tok = strtok_r(nullptr, "-", &saveptr);
223     CHECK(tok != nullptr);
224
225     memreg.end_addr = std::strtoull(tok, &endptr, 16);
226     /* Make sure that the entire string was an hex number */
227     CHECK(*endptr == '\0');
228
229     /* Get the permissions flags */
230     CHECK(std::strlen(lfields[1]) >= 4);
231
232     memreg.prot = 0;
233     for (i = 0; i < 3; i++){
234       switch(lfields[1][i]){
235         case 'r':
236           memreg.prot |= PROT_READ;
237           break;
238         case 'w':
239           memreg.prot |= PROT_WRITE;
240           break;
241         case 'x':
242           memreg.prot |= PROT_EXEC;
243           break;
244         default:
245           break;
246       }
247     }
248     if (memreg.prot == 0)
249       memreg.prot |= PROT_NONE;
250
251     memreg.flags = 0;
252     if (lfields[1][3] == 'p') {
253       memreg.flags |= MAP_PRIVATE;
254     } else {
255       memreg.flags |= MAP_SHARED;
256       if (lfields[1][3] != 's')
257         fprintf(stderr,
258                 "The protection is neither 'p' (private) nor 's' (shared) but '%s'. Let's assume shared, as on b0rken "
259                 "win-ubuntu systems.\nFull line: %s\n",
260                 lfields[1], line);
261     }
262
263     /* Get the offset value */
264     memreg.offset = std::strtoull(lfields[2], &endptr, 16);
265     /* Make sure that the entire string was an hex number */
266     CHECK(*endptr == '\0');
267
268     /* Get the device major:minor bytes */
269     tok = strtok_r(lfields[3], ":", &saveptr);
270     CHECK(tok != nullptr);
271
272     memreg.dev_major = (char) strtoul(tok, &endptr, 16);
273     /* Make sure that the entire string was an hex number */
274     CHECK(*endptr == '\0');
275
276     tok = strtok_r(nullptr, ":", &saveptr);
277     CHECK(tok != nullptr);
278
279     memreg.dev_minor = (char) std::strtoul(tok, &endptr, 16);
280     /* Make sure that the entire string was an hex number */
281     CHECK(*endptr == '\0');
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     CHECK(*endptr == '\0');
286
287     /* And finally get the pathname */
288     if (lfields[5])
289       memreg.pathname = lfields[5];
290
291     /* Create space for a new map region in the region's array and copy the */
292     /* parsed stuff from the temporal memreg variable */
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 }