1 | //===-- Linux implementation of dup2 --------------------------------------===// |
2 | // |
3 | // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. |
4 | // See https://llvm.org/LICENSE.txt for license information. |
5 | // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
6 | // |
7 | //===----------------------------------------------------------------------===// |
8 | |
9 | #include "src/unistd/dup2.h" |
10 | |
11 | #include "src/__support/OSUtil/syscall.h" // For internal syscall function. |
12 | #include "src/__support/common.h" |
13 | |
14 | #include "src/errno/libc_errno.h" |
15 | #include <fcntl.h> |
16 | #include <sys/syscall.h> // For syscall numbers. |
17 | |
18 | namespace LIBC_NAMESPACE { |
19 | |
20 | LLVM_LIBC_FUNCTION(int, dup2, (int oldfd, int newfd)) { |
21 | #ifdef SYS_dup2 |
22 | // If dup2 syscall is available, we make use of directly. |
23 | int ret = LIBC_NAMESPACE::syscall_impl<int>(SYS_dup2, ts: oldfd, ts: newfd); |
24 | #elif defined(SYS_dup3) |
25 | // If dup2 syscall is not available, we try using the dup3 syscall. However, |
26 | // dup3 fails if oldfd is the same as newfd. So, we handle that case |
27 | // separately before making the dup3 syscall. |
28 | if (oldfd == newfd) { |
29 | // Check if oldfd is actually a valid file descriptor. |
30 | #if SYS_fcntl |
31 | int ret = LIBC_NAMESPACE::syscall_impl<int>(SYS_fcntl, oldfd, F_GETFD); |
32 | #elif defined(SYS_fcntl64) |
33 | // Same as fcntl but can handle large offsets |
34 | static_assert(sizeof(off_t) == 8); |
35 | int ret = LIBC_NAMESPACE::syscall_impl<int>(SYS_fcntl64, oldfd, F_GETFD); |
36 | #else |
37 | #error "SYS_fcntl and SYS_fcntl64 syscalls not available." |
38 | #endif |
39 | if (ret >= 0) |
40 | return oldfd; |
41 | libc_errno = -ret; |
42 | return -1; |
43 | } |
44 | int ret = LIBC_NAMESPACE::syscall_impl<int>(SYS_dup3, oldfd, newfd, 0); |
45 | #else |
46 | #error "dup2 and dup3 syscalls not available." |
47 | #endif |
48 | if (ret < 0) { |
49 | libc_errno = -ret; |
50 | return -1; |
51 | } |
52 | return ret; |
53 | } |
54 | |
55 | } // namespace LIBC_NAMESPACE |
56 | |