Skip to content

Commit a29e051

Browse files
committed
[UR] Add ur_close_fd and ur_duplicate_fd to utils
1 parent ee8b38f commit a29e051

File tree

2 files changed

+51
-1
lines changed

2 files changed

+51
-1
lines changed

source/common/ur_util.cpp

Lines changed: 49 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,15 +9,63 @@
99
*/
1010

1111
#include "ur_util.hpp"
12+
#include "logger/ur_logger.hpp"
1213

1314
#ifdef _WIN32
1415
#include <windows.h>
1516
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+
1627
#else
1728

29+
#include <sys/syscall.h>
1830
#include <unistd.h>
1931
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 */
2169

2270
std::optional<std::string> ur_getenv(const char *name) {
2371
#if defined(_WIN32)

source/common/ur_util.hpp

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,8 @@
2727
#include <vector>
2828

2929
int ur_getpid(void);
30+
int ur_close_fd(int fd);
31+
int ur_duplicate_fd(int pid, int fd_in);
3032

3133
/* for compatibility with non-clang compilers */
3234
#if defined(__has_feature)

0 commit comments

Comments
 (0)