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); \
62 #define DEBUG_PRINT(...) \
64 fprintf(stderr, __VA_ARGS__); \
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.
77 std::vector<VmMap> get_memory_map(pid_t pid)
79 std::vector<VmMap> ret;
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");
91 * Darwin do not give us the number of mappings, so we read entries until
92 * we get a KERN_INVALID_ADDRESS return.
94 mach_vm_address_t address = VM_MIN_ADDRESS;
97 memory_object_name_t object;
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;
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;
115 (vm_region_info_t)&info,
118 if (kr == KERN_INVALID_ADDRESS) {
121 else if (kr != KERN_SUCCESS) {
122 std::perror("mach_vm_region failed");
123 std::fprintf(stderr, "Cannot request authorization for kernel information access\n");
130 memreg.start_addr = address;
131 memreg.end_addr = address + size;
134 memreg.prot = PROT_NONE;
135 if (info.protection & VM_PROT_READ)
136 memreg.prot |= PROT_READ;
137 if (info.protection & VM_PROT_WRITE)
138 memreg.prot |= PROT_WRITE;
139 if (info.protection & VM_PROT_EXECUTE)
140 memreg.prot |= PROT_EXEC;
142 /* Private (copy-on-write) or shared? */
145 memreg.flags |= MAP_SHARED;
147 memreg.flags |= MAP_PRIVATE;
150 memreg.offset = info.offset;
152 /* Device : not sure this can be mapped to something outside of Linux? */
153 memreg.dev_major = 0;
154 memreg.dev_minor = 0;
161 if (dladdr(reinterpret_cast<void*>(address), &dlinfo))
162 memreg.pathname = dlinfo.dli_fname;
164 DEBUG_PRINT("Region: %016" PRIx64 "-%016" PRIx64 " | %c%c%c | %s\n", memreg.start_addr, memreg.end_addr,
165 (memreg.prot & PROT_READ) ? 'r' : '-', (memreg.prot & PROT_WRITE) ? 'w' : '-',
166 (memreg.prot & PROT_EXEC) ? 'x' : '-', memreg.pathname.c_str());
168 ret.push_back(std::move(memreg));
172 mach_port_deallocate(mach_task_self(), map);
173 #elif defined __linux__
174 /* Open the actual process's proc maps file and create the memory_map_t */
175 /* to be returned. */
176 std::string path = std::string("/proc/") + std::to_string(pid) + "/maps";
178 fp.rdbuf()->pubsetbuf(nullptr, 0);
181 std::perror("open failed");
182 std::fprintf(stderr, "Cannot open %s to investigate the memory map of the process.\n", path.c_str());
186 /* Read one line at the time, parse it and add it to the memory map to be returned */
188 while (std::getline(fp, sline)) {
190 * The lines that we read have this format: (This is just an example)
191 * 00602000-00603000 rw-p 00002000 00:28 1837264 <complete-path-to-file>
193 char* line = &sline[0];
195 /* Tokenize the line using spaces as delimiters and store each token in lfields array. We expect 5 tokens for 6 fields */
196 char* saveptr = nullptr; // for strtok_r()
197 std::array<char*, 6> lfields;
198 lfields[0] = strtok_r(line, " ", &saveptr);
201 for (i = 1; i < 6 && lfields[i - 1] != nullptr; i++) {
202 lfields[i] = strtok_r(nullptr, " ", &saveptr);
205 /* Check to see if we got the expected amount of columns */
207 std::fprintf(stderr, "The memory map apparently only supplied less than 6 columns. Recovery impossible.\n");
211 /* Ok we are good enough to try to get the info we need */
212 /* First get the start and the end address of the map */
213 const char* tok = strtok_r(lfields[0], "-", &saveptr);
214 if (tok == nullptr) {
216 "Start and end address of the map are not concatenated by a hyphen (-). Recovery impossible.\n");
222 memreg.start_addr = std::strtoull(tok, &endptr, 16);
223 /* Make sure that the entire string was an hex number */
224 CHECK(*endptr == '\0');
226 tok = strtok_r(nullptr, "-", &saveptr);
227 CHECK(tok != nullptr);
229 memreg.end_addr = std::strtoull(tok, &endptr, 16);
230 /* Make sure that the entire string was an hex number */
231 CHECK(*endptr == '\0');
233 /* Get the permissions flags */
234 CHECK(std::strlen(lfields[1]) >= 4);
237 for (i = 0; i < 3; i++){
238 switch(lfields[1][i]){
240 memreg.prot |= PROT_READ;
243 memreg.prot |= PROT_WRITE;
246 memreg.prot |= PROT_EXEC;
252 if (memreg.prot == 0)
253 memreg.prot |= PROT_NONE;
256 if (lfields[1][3] == 'p') {
257 memreg.flags |= MAP_PRIVATE;
259 memreg.flags |= MAP_SHARED;
260 if (lfields[1][3] != 's')
262 "The protection is neither 'p' (private) nor 's' (shared) but '%s'. Let's assume shared, as on b0rken "
263 "win-ubuntu systems.\nFull line: %s\n",
267 /* Get the offset value */
268 memreg.offset = std::strtoull(lfields[2], &endptr, 16);
269 /* Make sure that the entire string was an hex number */
270 CHECK(*endptr == '\0');
272 /* Get the device major:minor bytes */
273 tok = strtok_r(lfields[3], ":", &saveptr);
274 CHECK(tok != nullptr);
276 memreg.dev_major = (char) strtoul(tok, &endptr, 16);
277 /* Make sure that the entire string was an hex number */
278 CHECK(*endptr == '\0');
280 tok = strtok_r(nullptr, ":", &saveptr);
281 CHECK(tok != nullptr);
283 memreg.dev_minor = (char) std::strtoul(tok, &endptr, 16);
284 /* Make sure that the entire string was an hex number */
285 CHECK(*endptr == '\0');
287 /* Get the inode number and make sure that the entire string was a long int */
288 memreg.inode = strtoul(lfields[4], &endptr, 10);
289 CHECK(*endptr == '\0');
291 /* And finally get the pathname */
293 memreg.pathname = lfields[5];
295 /* Create space for a new map region in the region's array and copy the */
296 /* parsed stuff from the temporal memreg variable */
297 DEBUG_PRINT("Found region for \"%s\"\n", memreg.pathname.c_str());
299 ret.push_back(std::move(memreg));
303 #elif defined __FreeBSD__
304 struct procstat *prstat;
305 struct kinfo_proc *proc;
306 struct kinfo_vmentry *vmentries;
309 if ((prstat = procstat_open_sysctl()) == NULL) {
310 std::perror("procstat_open_sysctl failed");
311 std::fprintf(stderr, "Cannot access kernel state information\n");
314 if ((proc = procstat_getprocs(prstat, KERN_PROC_PID, pid, &cnt)) == NULL) {
315 std::perror("procstat_open_sysctl failed");
316 std::fprintf(stderr, "Cannot access process information\n");
319 if ((vmentries = procstat_getvmmap(prstat, proc, &cnt)) == NULL) {
320 std::perror("procstat_getvmmap failed");
321 std::fprintf(stderr, "Cannot access process memory mappings\n");
324 for (unsigned int i = 0; i < cnt; i++) {
328 memreg.start_addr = vmentries[i].kve_start;
329 memreg.end_addr = vmentries[i].kve_end;
332 memreg.prot = PROT_NONE;
333 if (vmentries[i].kve_protection & KVME_PROT_READ)
334 memreg.prot |= PROT_READ;
335 if (vmentries[i].kve_protection & KVME_PROT_WRITE)
336 memreg.prot |= PROT_WRITE;
337 if (vmentries[i].kve_protection & KVME_PROT_EXEC)
338 memreg.prot |= PROT_EXEC;
340 /* Private (copy-on-write) or shared? */
342 if (vmentries[i].kve_flags & KVME_FLAG_COW)
343 memreg.flags |= MAP_PRIVATE;
345 memreg.flags |= MAP_SHARED;
348 memreg.offset = vmentries[i].kve_offset;
350 /* Device : not sure this can be mapped to something outside of Linux? */
351 memreg.dev_major = 0;
352 memreg.dev_minor = 0;
355 memreg.inode = vmentries[i].kve_vn_fileid;
358 * Path. Linuxize result by giving an anonymous mapping a path from
359 * the previous mapping, provided previous is vnode and has a path,
360 * and mark the stack.
362 if (vmentries[i].kve_path[0] != '\0')
363 memreg.pathname = vmentries[i].kve_path;
364 else if (vmentries[i].kve_type == KVME_TYPE_DEFAULT && vmentries[i - 1].kve_type == KVME_TYPE_VNODE &&
365 vmentries[i - 1].kve_path[0] != '\0')
366 memreg.pathname = vmentries[i-1].kve_path;
367 else if (vmentries[i].kve_type == KVME_TYPE_DEFAULT
368 && vmentries[i].kve_flags & KVME_FLAG_GROWS_DOWN)
369 memreg.pathname = "[stack]";
372 * One last dirty modification: remove write permission from shared
373 * libraries private clean pages. This is necessary because simgrid
374 * later identifies mappings based on the permissions that are expected
375 * when running the Linux kernel.
377 if (vmentries[i].kve_type == KVME_TYPE_VNODE && not(vmentries[i].kve_flags & KVME_FLAG_NEEDS_COPY))
378 memreg.prot &= ~PROT_WRITE;
380 ret.push_back(std::move(memreg));
382 procstat_freevmmap(prstat, vmentries);
383 procstat_freeprocs(prstat, proc);
384 procstat_close(prstat);
386 std::fprintf(stderr, "Could not get memory map from process %lli\n", (long long int)pid);