1 /* Copyright (c) 2015-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. */
6 #include "src/mc/inspect/mc_unw.hpp"
7 #include "src/mc/remote/RemoteProcess.hpp"
13 #include <libunwind-ptrace.h>
14 #include <libunwind.h>
17 * Libunwind namespace implementation using process_vm_readv.
20 /** Partial structure of libunwind-ptrace context in order to get the PID
22 * HACK, The context type for libunwind-race is an opaque type.
23 * We need to get the PID which is the first field. This is a hack
24 * which might break if the libunwind-ptrace structure changes.
31 /** Get the PID of a `libunwind-ptrace` context
33 static inline pid_t _UPT_getpid(void* arg)
35 const _UPT_info* info = static_cast<_UPT_info*>(arg);
39 /** Read from the memory, avoid using `ptrace` (libunwind method) */
40 static int access_mem(const unw_addr_space_t as, const unw_word_t addr, unw_word_t* const valp, const int write,
45 pid_t pid = _UPT_getpid(arg);
46 size_t size = sizeof(unw_word_t);
48 #if HAVE_PROCESS_VM_READV /* linux but not freebsd */
49 // process_vm_read implementation.
50 // This is only available since Linux 3.2.
52 struct iovec local = {valp, size};
53 struct iovec remote = {(void*)addr, size};
54 ssize_t s = process_vm_readv(pid, &local, 1, &remote, 1, 0);
56 if ((size_t)s != size)
60 } else if (errno != ENOSYS) {
65 // /proc/${pid}/mem implementation.
66 // On recent kernels, we do not need to ptrace the target process.
67 // On older kernels, it is necessary to ptrace the target process.
69 auto off = static_cast<off_t>(addr);
70 auto* buf = reinterpret_cast<char*>(valp);
71 int fd = simgrid::mc::open_vm(pid, O_RDONLY);
76 ssize_t nread = pread(fd, buf, count, off);
82 // ptrace implementation.
83 // We need to have PTRACE_ATTACH-ed it before.
84 return _UPT_access_mem(as, addr, valp, write, arg);
97 unw_addr_space_t create_addr_space()
99 /** Virtual table for our `libunwind-process_vm_readv` implementation.
101 * This implementation reuse most the code of `libunwind-ptrace` but
102 * does not use ptrace() to read the target process memory by
103 * `process_vm_readv()` or `/dev/${pid}/mem` if possible.
105 * Does not support any MC-specific behavior (privatization, snapshots)
108 * It works with `void*` contexts allocated with `_UPT_create(pid)`.
110 // TODO, we could get rid of this if we properly stop the model-checked
111 // process before reading the memory.
112 unw_accessors_t accessors = {&_UPT_find_proc_info, &_UPT_put_unwind_info, &_UPT_get_dyn_info_list_addr,
113 &access_mem, &_UPT_access_reg, &_UPT_access_fpreg,
114 &_UPT_resume, &_UPT_get_proc_name};
115 return unw_create_addr_space(&accessors, BYTE_ORDER);
118 void* create_context(unw_addr_space_t /*as*/, pid_t pid)
120 return _UPT_create(pid);
124 } // namespace simgrid