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 "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.
19 namespace LIBC_NAMESPACE_DECL
{
21 LLVM_LIBC_FUNCTION(int, dup2
, (int oldfd
, int newfd
)) {
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.
30 // Check if oldfd is actually a valid file descriptor.
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
);
38 #error "SYS_fcntl and SYS_fcntl64 syscalls not available."
45 int ret
= LIBC_NAMESPACE::syscall_impl
<int>(SYS_dup3
, oldfd
, newfd
, 0);
47 #error "dup2 and dup3 syscalls not available."
56 } // namespace LIBC_NAMESPACE_DECL