|
9 | 9 | */
|
10 | 10 |
|
11 | 11 | #include "ur_util.hpp"
|
| 12 | +#include "logger/ur_logger.hpp" |
12 | 13 |
|
13 | 14 | #ifdef _WIN32
|
14 | 15 | #include <windows.h>
|
15 | 16 | int ur_getpid(void) { return static_cast<int>(GetCurrentProcessId()); }
|
| 17 | + |
| 18 | +int ur_close_fd(int fd) { return -1; } |
| 19 | + |
| 20 | +int ur_duplicate_fd(int pid, int fd_in) { |
| 21 | + // TODO: find another way to obtain a duplicate of another process's file descriptor |
| 22 | + (void)pid; // unused |
| 23 | + (void)fd_in; // unused |
| 24 | + return -1; |
| 25 | +} |
| 26 | + |
16 | 27 | #else
|
17 | 28 |
|
| 29 | +#include <sys/syscall.h> |
18 | 30 | #include <unistd.h>
|
19 | 31 | int ur_getpid(void) { return static_cast<int>(getpid()); }
|
20 |
| -#endif |
| 32 | + |
| 33 | +int ur_close_fd(int fd) { return close(fd); } |
| 34 | + |
| 35 | +int ur_duplicate_fd(int pid, int fd_in) { |
| 36 | +// pidfd_getfd(2) is used to obtain a duplicate of another process's file descriptor. |
| 37 | +// Permission to duplicate another process's file descriptor |
| 38 | +// is governed by a ptrace access mode PTRACE_MODE_ATTACH_REALCREDS check (see ptrace(2)) |
| 39 | +// that can be changed using the /proc/sys/kernel/yama/ptrace_scope interface. |
| 40 | +// pidfd_getfd(2) is supported since Linux 5.6 |
| 41 | +// pidfd_open(2) is supported since Linux 5.3 |
| 42 | +#if defined(__NR_pidfd_open) && defined(__NR_pidfd_getfd) |
| 43 | + errno = 0; |
| 44 | + int pid_fd = syscall(SYS_pidfd_open, pid, 0); |
| 45 | + if (pid_fd == -1) { |
| 46 | + logger::error("SYS_pidfd_open"); |
| 47 | + return -1; |
| 48 | + } |
| 49 | + |
| 50 | + int fd_dup = syscall(SYS_pidfd_getfd, pid_fd, fd_in, 0); |
| 51 | + close(pid_fd); |
| 52 | + if (fd_dup == -1) { |
| 53 | + logger::error("SYS_pidfd_getfd"); |
| 54 | + return -1; |
| 55 | + } |
| 56 | + |
| 57 | + return fd_dup; |
| 58 | +#else |
| 59 | + // TODO: find another way to obtain a duplicate of another process's file descriptor |
| 60 | + (void)pid; // unused |
| 61 | + (void)fd_in; // unused |
| 62 | + errno = ENOTSUP; // unsupported |
| 63 | + logger::error("__NR_pidfd_open or __NR_pidfd_getfd not available"); |
| 64 | + return -1; |
| 65 | +#endif /* defined(__NR_pidfd_open) && defined(__NR_pidfd_getfd) */ |
| 66 | +} |
| 67 | + |
| 68 | +#endif /* _WIN32 */ |
21 | 69 |
|
22 | 70 | std::optional<std::string> ur_getenv(const char *name) {
|
23 | 71 | #if defined(_WIN32)
|
|
0 commit comments