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/macros/config.h" 16 #include "src/errno/libc_errno.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 static_assert(sizeof(off_t) == 8); 36 int ret = LIBC_NAMESPACE::syscall_impl<int>(SYS_fcntl64, oldfd, F_GETFD); 37 #else 38 #error "SYS_fcntl and SYS_fcntl64 syscalls not available." 39 #endif 40 if (ret >= 0) 41 return oldfd; 42 libc_errno = -ret; 43 return -1; 44 } 45 int ret = LIBC_NAMESPACE::syscall_impl<int>(SYS_dup3, oldfd, newfd, 0); 46 #else 47 #error "dup2 and dup3 syscalls not available." 48 #endif 49 if (ret < 0) { 50 libc_errno = -ret; 51 return -1; 52 } 53 return ret; 54 } 55 56 } // namespace LIBC_NAMESPACE_DECL 57