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 const char* name = nullptr;
115 switch (kr) { // https://github.com/apple/darwin-xnu/blob/main/bsd/kern/stackshot.c#L42
117 name = "kr=KERN_SUCCESS";
119 case KERN_RESOURCE_SHORTAGE:
120 name = "kr=KERN_RESOURCE_SHORTAGE (ENOMEM)";
122 case KERN_INSUFFICIENT_BUFFER_SIZE:
123 name = "kr=KERN_INSUFFICIENT_BUFFER_SIZE (ENOSPC)";
126 name = "kr=KERN_NO_SPACE (ENOSPC)";
129 name = "kr=KERN_NO_ACCESS (EPERM)";
131 case KERN_MEMORY_PRESENT:
132 name = "kr=KERN_MEMORY_PRESENT (EEXIST)";
134 case KERN_NOT_SUPPORTED:
135 name = "kr=KERN_NOT_SUPPORTED (ENOTSUP)";
137 case KERN_NOT_IN_SET:
138 name = "kr=KERN_NOT_IN_SET (ENOENT)";
141 name = "kr=KERN_ABORTED (EINTR)";
144 name = "kr=KERN_FAILURE (EBUSY)";
146 case KERN_OPERATION_TIMED_OUT:
147 name = "kr=KERN_OPERATION_TIMED_OUT (ETIMEDOUT)";
150 name = "kr=default case (EINVAL)";
152 std::perror("mach_vm_region failed");
153 std::fprintf(stderr, "Cannot request authorization for kernel information access (kr=%d ; %s)\n", (int)kr, name);
160 memreg.start_addr = address;
161 memreg.end_addr = address + size;
164 memreg.prot = PROT_NONE;
165 if (info.protection & VM_PROT_READ)
166 memreg.prot |= PROT_READ;
167 if (info.protection & VM_PROT_WRITE)
168 memreg.prot |= PROT_WRITE;
169 if (info.protection & VM_PROT_EXECUTE)
170 memreg.prot |= PROT_EXEC;
172 /* Private (copy-on-write) or shared? */
175 memreg.flags |= MAP_SHARED;
177 memreg.flags |= MAP_PRIVATE;
180 memreg.offset = info.offset;
182 /* Device : not sure this can be mapped to something outside of Linux? */
183 memreg.dev_major = 0;
184 memreg.dev_minor = 0;
191 if (dladdr(reinterpret_cast<void*>(address), &dlinfo))
192 memreg.pathname = dlinfo.dli_fname;
194 DEBUG_PRINT("Region: %016" PRIx64 "-%016" PRIx64 " | %c%c%c | %s\n", memreg.start_addr, memreg.end_addr,
195 (memreg.prot & PROT_READ) ? 'r' : '-', (memreg.prot & PROT_WRITE) ? 'w' : '-',
196 (memreg.prot & PROT_EXEC) ? 'x' : '-', memreg.pathname.c_str());
198 ret.push_back(std::move(memreg));
202 mach_port_deallocate(mach_task_self(), map);
203 #elif defined __linux__
204 /* Open the actual process's proc maps file and create the memory_map_t */
205 /* to be returned. */
206 std::string path = std::string("/proc/") + std::to_string(pid) + "/maps";
208 fp.rdbuf()->pubsetbuf(nullptr, 0);
211 std::perror("open failed");
212 std::fprintf(stderr, "Cannot open %s to investigate the memory map of the process.\n", path.c_str());
216 /* Read one line at the time, parse it and add it to the memory map to be returned */
218 while (std::getline(fp, sline)) {
220 * The lines that we read have this format: (This is just an example)
221 * 00602000-00603000 rw-p 00002000 00:28 1837264 <complete-path-to-file>
223 char* line = &sline[0];
225 /* Tokenize the line using spaces as delimiters and store each token in lfields array. We expect 5 tokens for 6 fields */
226 char* saveptr = nullptr; // for strtok_r()
227 std::array<char*, 6> lfields;
228 lfields[0] = strtok_r(line, " ", &saveptr);
231 for (i = 1; i < 6 && lfields[i - 1] != nullptr; i++) {
232 lfields[i] = strtok_r(nullptr, " ", &saveptr);
235 /* Check to see if we got the expected amount of columns */
237 std::fprintf(stderr, "The memory map apparently only supplied less than 6 columns. Recovery impossible.\n");
241 /* Ok we are good enough to try to get the info we need */
242 /* First get the start and the end address of the map */
243 const char* tok = strtok_r(lfields[0], "-", &saveptr);
244 if (tok == nullptr) {
246 "Start and end address of the map are not concatenated by a hyphen (-). Recovery impossible.\n");
252 memreg.start_addr = std::strtoull(tok, &endptr, 16);
253 /* Make sure that the entire string was an hex number */
254 CHECK(*endptr == '\0');
256 tok = strtok_r(nullptr, "-", &saveptr);
257 CHECK(tok != nullptr);
259 memreg.end_addr = std::strtoull(tok, &endptr, 16);
260 /* Make sure that the entire string was an hex number */
261 CHECK(*endptr == '\0');
263 /* Get the permissions flags */
264 CHECK(std::strlen(lfields[1]) >= 4);
267 for (i = 0; i < 3; i++){
268 switch(lfields[1][i]){
270 memreg.prot |= PROT_READ;
273 memreg.prot |= PROT_WRITE;
276 memreg.prot |= PROT_EXEC;
282 if (memreg.prot == 0)
283 memreg.prot |= PROT_NONE;
286 if (lfields[1][3] == 'p') {
287 memreg.flags |= MAP_PRIVATE;
289 memreg.flags |= MAP_SHARED;
290 if (lfields[1][3] != 's')
292 "The protection is neither 'p' (private) nor 's' (shared) but '%s'. Let's assume shared, as on b0rken "
293 "win-ubuntu systems.\nFull line: %s\n",
297 /* Get the offset value */
298 memreg.offset = std::strtoull(lfields[2], &endptr, 16);
299 /* Make sure that the entire string was an hex number */
300 CHECK(*endptr == '\0');
302 /* Get the device major:minor bytes */
303 tok = strtok_r(lfields[3], ":", &saveptr);
304 CHECK(tok != nullptr);
306 memreg.dev_major = (char) strtoul(tok, &endptr, 16);
307 /* Make sure that the entire string was an hex number */
308 CHECK(*endptr == '\0');
310 tok = strtok_r(nullptr, ":", &saveptr);
311 CHECK(tok != nullptr);
313 memreg.dev_minor = (char) std::strtoul(tok, &endptr, 16);
314 /* Make sure that the entire string was an hex number */
315 CHECK(*endptr == '\0');
317 /* Get the inode number and make sure that the entire string was a long int */
318 memreg.inode = strtoul(lfields[4], &endptr, 10);
319 CHECK(*endptr == '\0');
321 /* And finally get the pathname */
323 memreg.pathname = lfields[5];
325 /* Create space for a new map region in the region's array and copy the */
326 /* parsed stuff from the temporal memreg variable */
327 DEBUG_PRINT("Found region for \"%s\"\n", memreg.pathname.c_str());
329 ret.push_back(std::move(memreg));
333 #elif defined __FreeBSD__
334 struct procstat *prstat;
335 struct kinfo_proc *proc;
336 struct kinfo_vmentry *vmentries;
339 if ((prstat = procstat_open_sysctl()) == NULL) {
340 std::perror("procstat_open_sysctl failed");
341 std::fprintf(stderr, "Cannot access kernel state information\n");
344 if ((proc = procstat_getprocs(prstat, KERN_PROC_PID, pid, &cnt)) == NULL) {
345 std::perror("procstat_open_sysctl failed");
346 std::fprintf(stderr, "Cannot access process information\n");
349 if ((vmentries = procstat_getvmmap(prstat, proc, &cnt)) == NULL) {
350 std::perror("procstat_getvmmap failed");
351 std::fprintf(stderr, "Cannot access process memory mappings\n");
354 for (unsigned int i = 0; i < cnt; i++) {
358 memreg.start_addr = vmentries[i].kve_start;
359 memreg.end_addr = vmentries[i].kve_end;
362 memreg.prot = PROT_NONE;
363 if (vmentries[i].kve_protection & KVME_PROT_READ)
364 memreg.prot |= PROT_READ;
365 if (vmentries[i].kve_protection & KVME_PROT_WRITE)
366 memreg.prot |= PROT_WRITE;
367 if (vmentries[i].kve_protection & KVME_PROT_EXEC)
368 memreg.prot |= PROT_EXEC;
370 /* Private (copy-on-write) or shared? */
372 if (vmentries[i].kve_flags & KVME_FLAG_COW)
373 memreg.flags |= MAP_PRIVATE;
375 memreg.flags |= MAP_SHARED;
378 memreg.offset = vmentries[i].kve_offset;
380 /* Device : not sure this can be mapped to something outside of Linux? */
381 memreg.dev_major = 0;
382 memreg.dev_minor = 0;
385 memreg.inode = vmentries[i].kve_vn_fileid;
388 * Path. Linuxize result by giving an anonymous mapping a path from
389 * the previous mapping, provided previous is vnode and has a path,
390 * and mark the stack.
392 if (vmentries[i].kve_path[0] != '\0')
393 memreg.pathname = vmentries[i].kve_path;
394 else if (vmentries[i].kve_type == KVME_TYPE_DEFAULT && vmentries[i - 1].kve_type == KVME_TYPE_VNODE &&
395 vmentries[i - 1].kve_path[0] != '\0')
396 memreg.pathname = vmentries[i-1].kve_path;
397 else if (vmentries[i].kve_type == KVME_TYPE_DEFAULT
398 && vmentries[i].kve_flags & KVME_FLAG_GROWS_DOWN)
399 memreg.pathname = "[stack]";
402 * One last dirty modification: remove write permission from shared
403 * libraries private clean pages. This is necessary because simgrid
404 * later identifies mappings based on the permissions that are expected
405 * when running the Linux kernel.
407 if (vmentries[i].kve_type == KVME_TYPE_VNODE && not(vmentries[i].kve_flags & KVME_FLAG_NEEDS_COPY))
408 memreg.prot &= ~PROT_WRITE;
410 ret.push_back(std::move(memreg));
412 procstat_freevmmap(prstat, vmentries);
413 procstat_freeprocs(prstat, proc);
414 procstat_close(prstat);
416 std::fprintf(stderr, "Could not get memory map from process %lli\n", (long long int)pid);