| 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 "hdr/fcntl_macros.h" |
| 15 | #include "src/__support/libc_errno.h" |
| 16 | #include "src/__support/macros/config.h" |
| 17 | #include <sys/syscall.h> // For syscall numbers. |
| 18 | |
| 19 | namespace LIBC_NAMESPACE_DECL { |
| 20 | |
| 21 | LLVM_LIBC_FUNCTION(int, dup2, (int oldfd, int newfd)) { |
| 22 | #ifdef SYS_dup2 |
| 23 | // If dup2 syscall is available, we make use of directly. |
| 24 | int ret = LIBC_NAMESPACE::syscall_impl<int>(SYS_dup2, oldfd, newfd); |
| 25 | #elif defined(SYS_dup3) |
| 26 | // If dup2 syscall is not available, we try using the dup3 syscall. However, |
| 27 | // dup3 fails if oldfd is the same as newfd. So, we handle that case |
| 28 | // separately before making the dup3 syscall. |
| 29 | if (oldfd == newfd) { |
| 30 | // Check if oldfd is actually a valid file descriptor. |
| 31 | #if SYS_fcntl |
| 32 | int ret = LIBC_NAMESPACE::syscall_impl<int>(SYS_fcntl, oldfd, F_GETFD); |
| 33 | #elif defined(SYS_fcntl64) |
| 34 | // Same as fcntl but can handle large offsets |
| 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_DECL |
| 56 | |