#include "src/unistd/dup2.h"
#include "src/__support/OSUtil/syscall.h"
#include "src/__support/common.h"
#include "src/__support/macros/config.h"
#include "src/errno/libc_errno.h"
#include <fcntl.h>
#include <sys/syscall.h>
namespace LIBC_NAMESPACE_DECL {
LLVM_LIBC_FUNCTION(int, dup2, (int oldfd, int newfd)) {
#ifdef SYS_dup2
int ret = LIBC_NAMESPACE::syscall_impl<int>(SYS_dup2, oldfd, newfd);
#elif defined(SYS_dup3)
if (oldfd == newfd) {
#if SYS_fcntl
int ret = LIBC_NAMESPACE::syscall_impl<int>(SYS_fcntl, oldfd, F_GETFD);
#elif defined(SYS_fcntl64)
static_assert(sizeof(off_t) == 8);
int ret = LIBC_NAMESPACE::syscall_impl<int>(SYS_fcntl64, oldfd, F_GETFD);
#else
#error "SYS_fcntl and SYS_fcntl64 syscalls not available."
#endif
if (ret >= 0)
return oldfd;
libc_errno = -ret;
return -1;
}
int ret = LIBC_NAMESPACE::syscall_impl<int>(SYS_dup3, oldfd, newfd, 0);
#else
#error "dup2 and dup3 syscalls not available."
#endif
if (ret < 0) {
libc_errno = -ret;
return -1;
}
return ret;
}
}