Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
In FreeBSD map backend, mark stack same as in Linux
[simgrid.git] / src / xbt / memory_map.cpp
1 /* Copyright (c) 2008-2015. The SimGrid Team.
2  * All rights reserved.                                                     */
3
4 /* This program is free software; you can redistribute it and/or modify it
5  * under the terms of the license (GNU LGPL) which comes with this package. */
6
7 #include <cstdlib>
8 #include <cstdio>
9 #include <cstring>
10
11 #include <sys/types.h>
12 #ifdef __linux__
13 # include <sys/mman.h>
14 #elif defined __FreeBSD__
15 # include <sys/types.h>
16 # include <sys/mman.h>
17 # include <sys/param.h>
18 # include <sys/queue.h>
19 # include <sys/socket.h>
20 # include <sys/sysctl.h>
21 # include <sys/user.h>
22 # include <libprocstat.h>
23 #endif
24
25 #include <xbt/sysdep.h>
26 #include <xbt/base.h>
27 #include <xbt/file.h>
28 #include <xbt/log.h>
29
30 #include "memory_map.hpp"
31
32 extern "C" {
33 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(xbt_memory_map, xbt, "Logging specific to algorithms for memory_map");
34 }
35
36 namespace simgrid {
37 namespace xbt {
38
39 /**
40  * \todo This function contains many cases that do not allow for a
41  *       recovery. Currently, xbt_abort() is called but we should
42  *       much rather die with the specific reason so that it's easier
43  *       to find out what's going on.
44  */
45 XBT_PRIVATE std::vector<VmMap> get_memory_map(pid_t pid)
46 {
47   std::vector<VmMap> ret;
48 #ifdef __linux__
49   /* Open the actual process's proc maps file and create the memory_map_t */
50   /* to be returned. */
51   char* path = bprintf("/proc/%i/maps", (int) pid);
52   FILE *fp = std::fopen(path, "r");
53   if (fp == nullptr) {
54     std::perror("fopen failed");
55     xbt_die("Cannot open %s to investigate the memory map of the process.", path);
56   }
57   free(path);
58   setbuf(fp, nullptr);
59
60   /* Read one line at the time, parse it and add it to the memory map to be returned */
61   ssize_t read; /* Number of bytes readed */
62   char* line = nullptr;
63   std::size_t n = 0; /* Amount of bytes to read by xbt_getline */
64   while ((read = xbt_getline(&line, &n, fp)) != -1) {
65     /**
66      * The lines that we read have this format: (This is just an example)
67      * 00602000-00603000 rw-p 00002000 00:28 1837264                            <complete-path-to-file>
68      */
69
70     //fprintf(stderr,"%s", line);
71
72     /* Wipeout the new line character */
73     line[read - 1] = '\0';
74
75     /* Tokenize the line using spaces as delimiters and store each token in lfields array. We expect 5 tokens for 6 fields */
76     char* lfields[6];
77     lfields[0] = strtok(line, " ");
78
79     int i;
80     for (i = 1; i < 6 && lfields[i - 1] != nullptr; i++) {
81       lfields[i] = std::strtok(nullptr, " ");
82     }
83
84     /* Check to see if we got the expected amount of columns */
85     if (i < 6)
86       xbt_die("The memory map apparently only supplied less than 6 columns. Recovery impossible.");
87
88     /* Ok we are good enough to try to get the info we need */
89     /* First get the start and the end address of the map   */
90     char *tok = std::strtok(lfields[0], "-");
91     if (tok == nullptr)
92       xbt_die("Start and end address of the map are not concatenated by a hyphen (-). Recovery impossible.");
93
94     VmMap memreg;
95     char *endptr;
96     memreg.start_addr = std::strtoull(tok, &endptr, 16);
97     /* Make sure that the entire string was an hex number */
98     if (*endptr != '\0')
99       xbt_abort();
100
101     tok = std::strtok(nullptr, "-");
102     if (tok == nullptr)
103       xbt_abort();
104
105     memreg.end_addr = std::strtoull(tok, &endptr, 16);
106     /* Make sure that the entire string was an hex number */
107     if (*endptr != '\0')
108       xbt_abort();
109
110     /* Get the permissions flags */
111     if (std::strlen(lfields[1]) < 4)
112       xbt_abort();
113
114     memreg.prot = 0;
115
116     for (i = 0; i < 3; i++){
117       switch(lfields[1][i]){
118         case 'r':
119           memreg.prot |= PROT_READ;
120           break;
121         case 'w':
122           memreg.prot |= PROT_WRITE;
123           break;
124         case 'x':
125           memreg.prot |= PROT_EXEC;
126           break;
127         default:
128           break;
129       }
130     }
131     if (memreg.prot == 0)
132       memreg.prot |= PROT_NONE;
133
134     if (lfields[1][3] == 'p') {
135       memreg.flags |= MAP_PRIVATE;
136     } else {
137       memreg.flags |= MAP_SHARED;
138       if (lfields[1][3] != 's')
139         XBT_WARN("The protection is neither 'p' (private) nor 's' (shared) but '%s'. Let's assume shared, as on b0rken win-ubuntu systems.\nFull line: %s\n",
140                  lfields[1], line);
141     }
142
143     /* Get the offset value */
144     memreg.offset = std::strtoull(lfields[2], &endptr, 16);
145     /* Make sure that the entire string was an hex number */
146     if (*endptr != '\0')
147       xbt_abort();
148
149     /* Get the device major:minor bytes */
150     tok = std::strtok(lfields[3], ":");
151     if (tok == nullptr)
152       xbt_abort();
153
154     memreg.dev_major = (char) strtoul(tok, &endptr, 16);
155     /* Make sure that the entire string was an hex number */
156     if (*endptr != '\0')
157       xbt_abort();
158
159     tok = std::strtok(nullptr, ":");
160     if (tok == nullptr)
161       xbt_abort();
162
163     memreg.dev_minor = (char) std::strtoul(tok, &endptr, 16);
164     /* Make sure that the entire string was an hex number */
165     if (*endptr != '\0')
166       xbt_abort();
167
168     /* Get the inode number and make sure that the entire string was a long int */
169     memreg.inode = strtoul(lfields[4], &endptr, 10);
170     if (*endptr != '\0')
171       xbt_abort();
172
173     /* And finally get the pathname */
174     if (lfields[5])
175       memreg.pathname = lfields[5];
176
177     /* Create space for a new map region in the region's array and copy the */
178     /* parsed stuff from the temporal memreg variable */
179     XBT_DEBUG("Found region for %s", !memreg.pathname.empty() ? memreg.pathname.c_str() : "(null)");
180
181     ret.push_back(std::move(memreg));
182   }
183
184   std::free(line);
185   std::fclose(fp);
186 #elif defined __FreeBSD__
187   struct procstat *prstat;
188   struct kinfo_proc *proc;
189   struct kinfo_vmentry *vmentries;
190   unsigned int cnt;
191
192   if ((prstat = procstat_open_sysctl()) == NULL) {
193     std::perror("procstat_open_sysctl failed");
194     xbt_die("Cannot access kernel state information");
195   }
196   if ((proc = procstat_getprocs(prstat, KERN_PROC_PID, pid, &cnt)) == NULL) {
197     std::perror("procstat_open_sysctl failed");
198     xbt_die("Cannot access process information");
199   }
200   if ((vmentries = procstat_getvmmap(prstat, proc, &cnt)) == NULL) {
201     std::perror("procstat_getvmmap failed");
202     xbt_die("Cannot access process memory mappings");
203   }
204   for (unsigned int i = 0; i < cnt; i++) {
205     VmMap memreg;
206
207     /* Addresses */
208     memreg.start_addr = vmentries[i].kve_start;
209     memreg.end_addr = vmentries[i].kve_end;
210
211     /* Permissions */
212     memreg.prot = 0;
213     if (vmentries[i].kve_protection & KVME_PROT_READ)
214       memreg.prot |= PROT_READ;
215     if (vmentries[i].kve_protection & KVME_PROT_WRITE)
216       memreg.prot |= PROT_WRITE;
217     if (vmentries[i].kve_protection & KVME_PROT_EXEC)
218       memreg.prot |= PROT_EXEC;
219     if (memreg.prot == 0)
220       memreg.prot |= PROT_NONE;
221
222     /* Private (copy-on-write) or shared? */
223     if (vmentries[i].kve_flags & KVME_FLAG_COW)
224       memreg.flags |= MAP_PRIVATE;
225     else
226       memreg.flags |= MAP_SHARED;
227
228     /* Offset */
229     memreg.offset = vmentries[i].kve_offset;
230
231     /* Device : not sure this can be mapped to something outside of Linux? */
232     memreg.dev_major = 0;
233     memreg.dev_minor = 0;
234
235     /* Inode */
236     memreg.inode = vmentries[i].kve_vn_fileid;
237
238      /*
239       * Path. Linuxize result by giving an anonymous mapping a path from
240       * the previous mapping, provided previous is vnode and has a path,
241       * and mark the stack.
242       */
243     if (vmentries[i].kve_path[0] != '\0')
244       memreg.pathname = vmentries[i].kve_path;
245     else if (vmentries[i].kve_type == KVME_TYPE_DEFAULT
246             && vmentries[i-1].kve_type == KVME_TYPE_VNODE
247         && vmentries[i-1].kve_path[0] != '\0')
248       memreg.pathname = vmentries[i-1].kve_path;
249     else if (vmentries[i].kve_type == KVME_TYPE_DEFAULT
250         && vmentries[i].kve_flags & KVME_FLAG_GROWS_DOWN)
251       memreg.pathname = "[stack]";
252
253     ret.push_back(std::move(memreg));
254   }
255   procstat_freevmmap(prstat, vmentries);
256   procstat_freeprocs(prstat, proc);
257   procstat_close(prstat);
258 #else
259   xbt_die("Could not get memory map from process %lli", (long long int) pid);
260 #endif
261   return ret;
262 }
263
264 }
265 }