1 /* Copyright (c) 2008-2022. 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;
109 kr = mach_vm_region(map, &address, &size, flavor, (vm_region_info_t)&info, &info_count, &object);
110 if (kr == KERN_INVALID_ADDRESS) {
113 } else if (kr != KERN_SUCCESS) {
114 std::perror("mach_vm_region failed");
115 std::fprintf(stderr, "Cannot request authorization for kernel information access (kr=%d)\n", (int)kr);
116 switch (kr) { // https://github.com/apple/darwin-xnu/blob/main/bsd/kern/stackshot.c#L42
118 XBT_INFO("kr=KERN_SUCCESS");
120 case KERN_RESOURCE_SHORTAGE:
121 XBT_INFO("kr=KERN_RESOURCE_SHORTAGE (ENOMEM)");
123 case KERN_INSUFFICIENT_BUFFER_SIZE:
124 XBT_INFO("kr=KERN_INSUFFICIENT_BUFFER_SIZE (ENOSPC)");
127 XBT_INFO("kr=KERN_NO_SPACE (ENOSPC)");
130 XBT_INFO("kr=KERN_NO_ACCESS (EPERM)");
132 case KERN_MEMORY_PRESENT:
133 XBT_INFO("kr=KERN_MEMORY_PRESENT (EEXIST)");
135 case KERN_NOT_SUPPORTED:
136 XBT_INFO("kr=KERN_NOT_SUPPORTED (ENOTSUP)");
138 case KERN_NOT_IN_SET:
139 XBT_INFO("kr=KERN_NOT_IN_SET (ENOENT)");
142 XBT_INFO("kr=KERN_ABORTED (EINTR)");
145 XBT_INFO("kr=KERN_FAILURE (EBUSY)");
147 case KERN_OPERATION_TIMED_OUT:
148 XBT_INFO("kr=KERN_OPERATION_TIMED_OUT (ETIMEDOUT)");
151 XBT_INFO("kr=default case (EINVAL)");
159 memreg.start_addr = address;
160 memreg.end_addr = address + size;
163 memreg.prot = PROT_NONE;
164 if (info.protection & VM_PROT_READ)
165 memreg.prot |= PROT_READ;
166 if (info.protection & VM_PROT_WRITE)
167 memreg.prot |= PROT_WRITE;
168 if (info.protection & VM_PROT_EXECUTE)
169 memreg.prot |= PROT_EXEC;
171 /* Private (copy-on-write) or shared? */
174 memreg.flags |= MAP_SHARED;
176 memreg.flags |= MAP_PRIVATE;
179 memreg.offset = info.offset;
181 /* Device : not sure this can be mapped to something outside of Linux? */
182 memreg.dev_major = 0;
183 memreg.dev_minor = 0;
190 if (dladdr(reinterpret_cast<void*>(address), &dlinfo))
191 memreg.pathname = dlinfo.dli_fname;
193 DEBUG_PRINT("Region: %016" PRIx64 "-%016" PRIx64 " | %c%c%c | %s\n", memreg.start_addr, memreg.end_addr,
194 (memreg.prot & PROT_READ) ? 'r' : '-', (memreg.prot & PROT_WRITE) ? 'w' : '-',
195 (memreg.prot & PROT_EXEC) ? 'x' : '-', memreg.pathname.c_str());
197 ret.push_back(std::move(memreg));
201 mach_port_deallocate(mach_task_self(), map);
202 #elif defined __linux__
203 /* Open the actual process's proc maps file and create the memory_map_t */
204 /* to be returned. */
205 std::string path = std::string("/proc/") + std::to_string(pid) + "/maps";
207 fp.rdbuf()->pubsetbuf(nullptr, 0);
210 std::perror("open failed");
211 std::fprintf(stderr, "Cannot open %s to investigate the memory map of the process.\n", path.c_str());
215 /* Read one line at the time, parse it and add it to the memory map to be returned */
217 while (std::getline(fp, sline)) {
219 * The lines that we read have this format: (This is just an example)
220 * 00602000-00603000 rw-p 00002000 00:28 1837264 <complete-path-to-file>
222 char* line = &sline[0];
224 /* Tokenize the line using spaces as delimiters and store each token in lfields array. We expect 5 tokens for 6 fields */
225 char* saveptr = nullptr; // for strtok_r()
226 std::array<char*, 6> lfields;
227 lfields[0] = strtok_r(line, " ", &saveptr);
230 for (i = 1; i < 6 && lfields[i - 1] != nullptr; i++) {
231 lfields[i] = strtok_r(nullptr, " ", &saveptr);
234 /* Check to see if we got the expected amount of columns */
236 std::fprintf(stderr, "The memory map apparently only supplied less than 6 columns. Recovery impossible.\n");
240 /* Ok we are good enough to try to get the info we need */
241 /* First get the start and the end address of the map */
242 const char* tok = strtok_r(lfields[0], "-", &saveptr);
243 if (tok == nullptr) {
245 "Start and end address of the map are not concatenated by a hyphen (-). Recovery impossible.\n");
251 memreg.start_addr = std::strtoull(tok, &endptr, 16);
252 /* Make sure that the entire string was an hex number */
253 CHECK(*endptr == '\0');
255 tok = strtok_r(nullptr, "-", &saveptr);
256 CHECK(tok != nullptr);
258 memreg.end_addr = std::strtoull(tok, &endptr, 16);
259 /* Make sure that the entire string was an hex number */
260 CHECK(*endptr == '\0');
262 /* Get the permissions flags */
263 CHECK(std::strlen(lfields[1]) >= 4);
266 for (i = 0; i < 3; i++){
267 switch(lfields[1][i]){
269 memreg.prot |= PROT_READ;
272 memreg.prot |= PROT_WRITE;
275 memreg.prot |= PROT_EXEC;
281 if (memreg.prot == 0)
282 memreg.prot |= PROT_NONE;
285 if (lfields[1][3] == 'p') {
286 memreg.flags |= MAP_PRIVATE;
288 memreg.flags |= MAP_SHARED;
289 if (lfields[1][3] != 's')
291 "The protection is neither 'p' (private) nor 's' (shared) but '%s'. Let's assume shared, as on b0rken "
292 "win-ubuntu systems.\nFull line: %s\n",
296 /* Get the offset value */
297 memreg.offset = std::strtoull(lfields[2], &endptr, 16);
298 /* Make sure that the entire string was an hex number */
299 CHECK(*endptr == '\0');
301 /* Get the device major:minor bytes */
302 tok = strtok_r(lfields[3], ":", &saveptr);
303 CHECK(tok != nullptr);
305 memreg.dev_major = (char) strtoul(tok, &endptr, 16);
306 /* Make sure that the entire string was an hex number */
307 CHECK(*endptr == '\0');
309 tok = strtok_r(nullptr, ":", &saveptr);
310 CHECK(tok != nullptr);
312 memreg.dev_minor = (char) std::strtoul(tok, &endptr, 16);
313 /* Make sure that the entire string was an hex number */
314 CHECK(*endptr == '\0');
316 /* Get the inode number and make sure that the entire string was a long int */
317 memreg.inode = strtoul(lfields[4], &endptr, 10);
318 CHECK(*endptr == '\0');
320 /* And finally get the pathname */
322 memreg.pathname = lfields[5];
324 /* Create space for a new map region in the region's array and copy the */
325 /* parsed stuff from the temporal memreg variable */
326 DEBUG_PRINT("Found region for \"%s\"\n", memreg.pathname.c_str());
328 ret.push_back(std::move(memreg));
332 #elif defined __FreeBSD__
333 struct procstat *prstat;
334 struct kinfo_proc *proc;
335 struct kinfo_vmentry *vmentries;
338 if ((prstat = procstat_open_sysctl()) == NULL) {
339 std::perror("procstat_open_sysctl failed");
340 std::fprintf(stderr, "Cannot access kernel state information\n");
343 if ((proc = procstat_getprocs(prstat, KERN_PROC_PID, pid, &cnt)) == NULL) {
344 std::perror("procstat_open_sysctl failed");
345 std::fprintf(stderr, "Cannot access process information\n");
348 if ((vmentries = procstat_getvmmap(prstat, proc, &cnt)) == NULL) {
349 std::perror("procstat_getvmmap failed");
350 std::fprintf(stderr, "Cannot access process memory mappings\n");
353 for (unsigned int i = 0; i < cnt; i++) {
357 memreg.start_addr = vmentries[i].kve_start;
358 memreg.end_addr = vmentries[i].kve_end;
361 memreg.prot = PROT_NONE;
362 if (vmentries[i].kve_protection & KVME_PROT_READ)
363 memreg.prot |= PROT_READ;
364 if (vmentries[i].kve_protection & KVME_PROT_WRITE)
365 memreg.prot |= PROT_WRITE;
366 if (vmentries[i].kve_protection & KVME_PROT_EXEC)
367 memreg.prot |= PROT_EXEC;
369 /* Private (copy-on-write) or shared? */
371 if (vmentries[i].kve_flags & KVME_FLAG_COW)
372 memreg.flags |= MAP_PRIVATE;
374 memreg.flags |= MAP_SHARED;
377 memreg.offset = vmentries[i].kve_offset;
379 /* Device : not sure this can be mapped to something outside of Linux? */
380 memreg.dev_major = 0;
381 memreg.dev_minor = 0;
384 memreg.inode = vmentries[i].kve_vn_fileid;
387 * Path. Linuxize result by giving an anonymous mapping a path from
388 * the previous mapping, provided previous is vnode and has a path,
389 * and mark the stack.
391 if (vmentries[i].kve_path[0] != '\0')
392 memreg.pathname = vmentries[i].kve_path;
393 else if (vmentries[i].kve_type == KVME_TYPE_DEFAULT && vmentries[i - 1].kve_type == KVME_TYPE_VNODE &&
394 vmentries[i - 1].kve_path[0] != '\0')
395 memreg.pathname = vmentries[i-1].kve_path;
396 else if (vmentries[i].kve_type == KVME_TYPE_DEFAULT
397 && vmentries[i].kve_flags & KVME_FLAG_GROWS_DOWN)
398 memreg.pathname = "[stack]";
401 * One last dirty modification: remove write permission from shared
402 * libraries private clean pages. This is necessary because simgrid
403 * later identifies mappings based on the permissions that are expected
404 * when running the Linux kernel.
406 if (vmentries[i].kve_type == KVME_TYPE_VNODE && not(vmentries[i].kve_flags & KVME_FLAG_NEEDS_COPY))
407 memreg.prot &= ~PROT_WRITE;
409 ret.push_back(std::move(memreg));
411 procstat_freevmmap(prstat, vmentries);
412 procstat_freeprocs(prstat, proc);
413 procstat_close(prstat);
415 std::fprintf(stderr, "Could not get memory map from process %lli\n", (long long int)pid);