1 /* Copyright (c) 2008-2021. The SimGrid Team. All rights reserved. */
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. */
14 #include <sys/types.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
30 # define mach_vm_region vm_region
36 # include <sys/mman.h>
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>
52 #include "memory_map.hpp"
54 // abort with a message if `expr' is false
57 fprintf(stderr, "CHECK FAILED: %s:%d: %s\n", __FILE__, __LINE__, #expr); \
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.
71 std::vector<VmMap> get_memory_map(pid_t pid)
73 std::vector<VmMap> ret;
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");
85 * Darwin do not give us the number of mappings, so we read entries until
86 * we get a KERN_INVALID_ADDRESS return.
88 mach_vm_address_t address = VM_MIN_ADDRESS;
91 memory_object_name_t object;
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;
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;
109 (vm_region_info_t)&info,
112 if (kr == KERN_INVALID_ADDRESS) {
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");
124 memreg.start_addr = address;
125 memreg.end_addr = address + size;
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;
136 /* Private (copy-on-write) or shared? */
139 memreg.flags |= MAP_SHARED;
141 memreg.flags |= MAP_PRIVATE;
144 memreg.offset = info.offset;
146 /* Device : not sure this can be mapped to something outside of Linux? */
147 memreg.dev_major = 0;
148 memreg.dev_minor = 0;
155 if (dladdr(reinterpret_cast<void*>(address), &dlinfo))
156 memreg.pathname = dlinfo.dli_fname;
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());
164 ret.push_back(std::move(memreg));
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";
174 fp.rdbuf()->pubsetbuf(nullptr, 0);
177 std::perror("open failed");
178 std::fprintf(stderr, "Cannot open %s to investigate the memory map of the process.\n", path.c_str());
182 /* Read one line at the time, parse it and add it to the memory map to be returned */
184 while (std::getline(fp, sline)) {
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>
189 char* line = &sline[0];
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);
197 for (i = 1; i < 6 && lfields[i - 1] != nullptr; i++) {
198 lfields[i] = strtok_r(nullptr, " ", &saveptr);
201 /* Check to see if we got the expected amount of columns */
203 std::fprintf(stderr, "The memory map apparently only supplied less than 6 columns. Recovery impossible.\n");
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) {
212 "Start and end address of the map are not concatenated by a hyphen (-). Recovery impossible.\n");
218 memreg.start_addr = std::strtoull(tok, &endptr, 16);
219 /* Make sure that the entire string was an hex number */
220 CHECK(*endptr == '\0');
222 tok = strtok_r(nullptr, "-", &saveptr);
223 CHECK(tok != nullptr);
225 memreg.end_addr = std::strtoull(tok, &endptr, 16);
226 /* Make sure that the entire string was an hex number */
227 CHECK(*endptr == '\0');
229 /* Get the permissions flags */
230 CHECK(std::strlen(lfields[1]) >= 4);
233 for (i = 0; i < 3; i++){
234 switch(lfields[1][i]){
236 memreg.prot |= PROT_READ;
239 memreg.prot |= PROT_WRITE;
242 memreg.prot |= PROT_EXEC;
248 if (memreg.prot == 0)
249 memreg.prot |= PROT_NONE;
252 if (lfields[1][3] == 'p') {
253 memreg.flags |= MAP_PRIVATE;
255 memreg.flags |= MAP_SHARED;
256 if (lfields[1][3] != 's')
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",
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');
268 /* Get the device major:minor bytes */
269 tok = strtok_r(lfields[3], ":", &saveptr);
270 CHECK(tok != nullptr);
272 memreg.dev_major = (char) strtoul(tok, &endptr, 16);
273 /* Make sure that the entire string was an hex number */
274 CHECK(*endptr == '\0');
276 tok = strtok_r(nullptr, ":", &saveptr);
277 CHECK(tok != nullptr);
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');
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');
287 /* And finally get the pathname */
289 memreg.pathname = lfields[5];
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)");
295 ret.push_back(std::move(memreg));
299 #elif defined __FreeBSD__
300 struct procstat *prstat;
301 struct kinfo_proc *proc;
302 struct kinfo_vmentry *vmentries;
305 if ((prstat = procstat_open_sysctl()) == NULL) {
306 std::perror("procstat_open_sysctl failed");
307 std::fprintf(stderr, "Cannot access kernel state information\n");
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");
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");
320 for (unsigned int i = 0; i < cnt; i++) {
324 memreg.start_addr = vmentries[i].kve_start;
325 memreg.end_addr = vmentries[i].kve_end;
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;
336 /* Private (copy-on-write) or shared? */
338 if (vmentries[i].kve_flags & KVME_FLAG_COW)
339 memreg.flags |= MAP_PRIVATE;
341 memreg.flags |= MAP_SHARED;
344 memreg.offset = vmentries[i].kve_offset;
346 /* Device : not sure this can be mapped to something outside of Linux? */
347 memreg.dev_major = 0;
348 memreg.dev_minor = 0;
351 memreg.inode = vmentries[i].kve_vn_fileid;
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.
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]";
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.
373 if (vmentries[i].kve_type == KVME_TYPE_VNODE && not(vmentries[i].kve_flags & KVME_FLAG_NEEDS_COPY))
374 memreg.prot &= ~PROT_WRITE;
376 ret.push_back(std::move(memreg));
378 procstat_freevmmap(prstat, vmentries);
379 procstat_freeprocs(prstat, proc);
380 procstat_close(prstat);
382 std::fprintf(stderr, "Could not get memory map from process %lli\n", (long long int)pid);