Logo AND Algorithmique Numérique Distribuée

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