1 //===-- Linux implementation of dup2 --------------------------------------===//
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
7 //===----------------------------------------------------------------------===//
9 #include "src/unistd/dup2.h"
11 #include "src/__support/OSUtil/syscall.h" // For internal syscall function.
12 #include "src/__support/common.h"
14 #include "src/errno/libc_errno.h"
16 #include <sys/syscall.h> // For syscall numbers.
18 namespace LIBC_NAMESPACE
{
20 LLVM_LIBC_FUNCTION(int, dup2
, (int oldfd
, int newfd
)) {
22 // If dup2 syscall is available, we make use of directly.
23 int ret
= LIBC_NAMESPACE::syscall_impl
<int>(SYS_dup2
, oldfd
, 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.
29 // Check if oldfd is actually a valid file descriptor.
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
);
37 #error "SYS_fcntl and SYS_fcntl64 syscalls not available."
44 int ret
= LIBC_NAMESPACE::syscall_impl
<int>(SYS_dup3
, oldfd
, newfd
, 0);
46 #error "dup2 and dup3 syscalls not available."
55 } // namespace LIBC_NAMESPACE