740027
From 76df06ff8fa39ae0cb0d167b7f622139778dc7d7 Mon Sep 17 00:00:00 2001
740027
From: Kamil Dudka <kdudka@redhat.com>
740027
Date: Thu, 4 Jan 2018 09:42:10 +0100
740027
Subject: [PATCH] mv -n: do not overwrite the destination
740027
740027
... if it is created by another process after mv has checked its
740027
non-existence.
740027
740027
* src/copy.c (copy_internal): Use renameat2 (..., RENAME_NOREPLACE)
740027
if called by mv -n.  If it fails with EEXIST in that case, pretend
740027
successful rename as if the existing destination file was detected
740027
by the preceding lstat call.
740027
740027
Fixes https://bugs.gnu.org/29961
740027
---
740027
 aclocal.m4                    |   1 +
740027
 bootstrap.conf                |   2 +
740027
 gnulib-tests/gnulib.mk        |  18 ++++
740027
 gnulib-tests/test-renameat.c  | 206 ++++++++++++++++++++++++++++++++++++++
740027
 gnulib-tests/test-renameat2.c | 209 ++++++++++++++++++++++++++++++++++++++
740027
 lib/gnulib.mk                 |  21 +++-
740027
 lib/renameat.c                |  25 +++++
740027
 lib/renameat2.c               | 227 ++++++++++++++++++++++++++++++++++++++++++
740027
 lib/renameat2.h               |  30 ++++++
740027
 m4/gnulib-comp.m4             |  22 ++++
740027
 m4/renameat.m4                |  25 +++++
740027
 src/copy.c                    |  27 ++++-
740027
 12 files changed, 808 insertions(+), 5 deletions(-)
740027
 create mode 100644 gnulib-tests/test-renameat.c
740027
 create mode 100644 gnulib-tests/test-renameat2.c
740027
 create mode 100644 lib/renameat.c
740027
 create mode 100644 lib/renameat2.c
740027
 create mode 100644 lib/renameat2.h
740027
 create mode 100644 m4/renameat.m4
740027
740027
diff --git a/aclocal.m4 b/aclocal.m4
740027
index 9c5a2b0..c678967 100644
740027
--- a/aclocal.m4
740027
+++ b/aclocal.m4
740027
@@ -1332,6 +1332,7 @@ m4_include([m4/realloc.m4])
740027
 m4_include([m4/regex.m4])
740027
 m4_include([m4/remove.m4])
740027
 m4_include([m4/rename.m4])
740027
+m4_include([m4/renameat.m4])
740027
 m4_include([m4/rewinddir.m4])
740027
 m4_include([m4/rmdir.m4])
740027
 m4_include([m4/rpmatch.m4])
740027
diff --git a/bootstrap.conf b/bootstrap.conf
740027
index 7def1f9..9b7c913 100644
740027
--- a/bootstrap.conf
740027
+++ b/bootstrap.conf
740027
@@ -199,6 +199,8 @@ gnulib_modules="
740027
   regex
740027
   remove
740027
   rename
740027
+  renameat
740027
+  renameat2
740027
   rmdir
740027
   root-dev-ino
740027
   rpmatch
740027
diff --git a/gnulib-tests/gnulib.mk b/gnulib-tests/gnulib.mk
740027
index b2da030..38d439c 100644
740027
--- a/gnulib-tests/gnulib.mk
740027
+++ b/gnulib-tests/gnulib.mk
740027
@@ -1676,6 +1676,24 @@ EXTRA_DIST += test-rename.h test-rename.c signature.h macros.h
740027
 
740027
 ## end   gnulib module rename-tests
740027
 
740027
+## begin gnulib module renameat-tests
740027
+
740027
+TESTS += test-renameat
740027
+check_PROGRAMS += test-renameat
740027
+test_renameat_LDADD = $(LDADD) @LIBINTL@
740027
+EXTRA_DIST += test-rename.h test-renameat.c signature.h macros.h
740027
+
740027
+## end   gnulib module renameat-tests
740027
+
740027
+## begin gnulib module renameat2-tests
740027
+
740027
+TESTS += test-renameat2
740027
+check_PROGRAMS += test-renameat2
740027
+test_renameat2_LDADD = $(LDADD) @LIBINTL@
740027
+EXTRA_DIST += test-rename.h test-renameat2.c signature.h macros.h
740027
+
740027
+## end   gnulib module renameat2-tests
740027
+
740027
 ## begin gnulib module rmdir-tests
740027
 
740027
 TESTS += test-rmdir
740027
diff --git a/gnulib-tests/test-renameat.c b/gnulib-tests/test-renameat.c
740027
new file mode 100644
740027
index 0000000..ac96d88
740027
--- /dev/null
740027
+++ b/gnulib-tests/test-renameat.c
740027
@@ -0,0 +1,206 @@
740027
+/* Tests of renameat.
740027
+   Copyright (C) 2009-2017 Free Software Foundation, Inc.
740027
+
740027
+   This program is free software: you can redistribute it and/or modify
740027
+   it under the terms of the GNU General Public License as published by
740027
+   the Free Software Foundation; either version 3 of the License, or
740027
+   (at your option) any later version.
740027
+
740027
+   This program is distributed in the hope that it will be useful,
740027
+   but WITHOUT ANY WARRANTY; without even the implied warranty of
740027
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
740027
+   GNU General Public License for more details.
740027
+
740027
+   You should have received a copy of the GNU General Public License
740027
+   along with this program.  If not, see <https://www.gnu.org/licenses/>.  */
740027
+
740027
+/* Written by Eric Blake <ebb9@byu.net>, 2009.  */
740027
+
740027
+#include <config.h>
740027
+
740027
+#include <stdio.h>
740027
+
740027
+#include "signature.h"
740027
+SIGNATURE_CHECK (renameat, int, (int, char const *, int, char const *));
740027
+
740027
+#include <dirent.h>
740027
+#include <fcntl.h>
740027
+#include <errno.h>
740027
+#include <stdbool.h>
740027
+#include <stdlib.h>
740027
+#include <string.h>
740027
+#include <unistd.h>
740027
+#include <sys/stat.h>
740027
+
740027
+#include "filenamecat.h"
740027
+#include "ignore-value.h"
740027
+#include "macros.h"
740027
+
740027
+#define BASE "test-renameat.t"
740027
+
740027
+#include "test-rename.h"
740027
+
740027
+static int dfd1 = AT_FDCWD;
740027
+static int dfd2 = AT_FDCWD;
740027
+
740027
+/* Wrapper to test renameat like rename.  */
740027
+static int
740027
+do_rename (char const *name1, char const *name2)
740027
+{
740027
+  return renameat (dfd1, name1, dfd2, name2);
740027
+}
740027
+
740027
+int
740027
+main (void)
740027
+{
740027
+  int i;
740027
+  int dfd;
740027
+  char *cwd;
740027
+  int result;
740027
+
740027
+  /* Clean up any trash from prior testsuite runs.  */
740027
+  ignore_value (system ("rm -rf " BASE "*"));
740027
+
740027
+  /* Test behaviour for invalid file descriptors.  */
740027
+  {
740027
+    errno = 0;
740027
+    ASSERT (renameat (-1, "foo", AT_FDCWD, "bar") == -1);
740027
+    ASSERT (errno == EBADF);
740027
+  }
740027
+  {
740027
+    close (99);
740027
+    errno = 0;
740027
+    ASSERT (renameat (99, "foo", AT_FDCWD, "bar") == -1);
740027
+    ASSERT (errno == EBADF);
740027
+  }
740027
+  ASSERT (close (creat (BASE "oo", 0600)) == 0);
740027
+  {
740027
+    errno = 0;
740027
+    ASSERT (renameat (AT_FDCWD, BASE "oo", -1, "bar") == -1);
740027
+    ASSERT (errno == EBADF);
740027
+  }
740027
+  {
740027
+    errno = 0;
740027
+    ASSERT (renameat (AT_FDCWD, BASE "oo", 99, "bar") == -1);
740027
+    ASSERT (errno == EBADF);
740027
+  }
740027
+  ASSERT (unlink (BASE "oo") == 0);
740027
+
740027
+  /* Test basic rename functionality, using current directory.  */
740027
+  result = test_rename (do_rename, false);
740027
+  dfd1 = open (".", O_RDONLY);
740027
+  ASSERT (0 <= dfd1);
740027
+  ASSERT (test_rename (do_rename, false) == result);
740027
+  dfd2 = dfd1;
740027
+  ASSERT (test_rename (do_rename, false) == result);
740027
+  dfd1 = AT_FDCWD;
740027
+  ASSERT (test_rename (do_rename, false) == result);
740027
+  ASSERT (close (dfd2) == 0);
740027
+
740027
+  /* Create locations to manipulate.  */
740027
+  ASSERT (mkdir (BASE "sub1", 0700) == 0);
740027
+  ASSERT (mkdir (BASE "sub2", 0700) == 0);
740027
+  dfd = creat (BASE "00", 0600);
740027
+  ASSERT (0 <= dfd);
740027
+  ASSERT (close (dfd) == 0);
740027
+  cwd = getcwd (NULL, 0);
740027
+  ASSERT (cwd);
740027
+
740027
+  dfd = open (BASE "sub1", O_RDONLY);
740027
+  ASSERT (0 <= dfd);
740027
+  ASSERT (chdir (BASE "sub2") == 0);
740027
+
740027
+  /* There are 16 possible scenarios, based on whether an fd is
740027
+     AT_FDCWD or real, and whether a file is absolute or relative.
740027
+
740027
+     To ensure that we test all of the code paths (rather than
740027
+     triggering early normalization optimizations), we use a loop to
740027
+     repeatedly rename a file in the parent directory, use an fd open
740027
+     on subdirectory 1, all while executing in subdirectory 2; all
740027
+     relative names are thus given with a leading "../".  Finally, the
740027
+     last scenario (two relative paths given, neither one AT_FDCWD)
740027
+     has two paths, based on whether the two fds are equivalent, so we
740027
+     do the other variant after the loop.  */
740027
+  for (i = 0; i < 16; i++)
740027
+    {
740027
+      int fd1 = (i & 8) ? dfd : AT_FDCWD;
740027
+      char *file1 = file_name_concat ((i & 4) ? ".." : cwd, BASE "xx", NULL);
740027
+      int fd2 = (i & 2) ? dfd : AT_FDCWD;
740027
+      char *file2 = file_name_concat ((i & 1) ? ".." : cwd, BASE "xx", NULL);
740027
+
740027
+      ASSERT (sprintf (strchr (file1, '\0') - 2, "%02d", i) == 2);
740027
+      ASSERT (sprintf (strchr (file2, '\0') - 2, "%02d", i + 1) == 2);
740027
+      ASSERT (renameat (fd1, file1, fd2, file2) == 0);
740027
+      free (file1);
740027
+      free (file2);
740027
+    }
740027
+  dfd2 = open ("..", O_RDONLY);
740027
+  ASSERT (0 <= dfd2);
740027
+  ASSERT (renameat (dfd, "../" BASE "16", dfd2, BASE "17") == 0);
740027
+  ASSERT (close (dfd2) == 0);
740027
+
740027
+  /* Now we change back to the parent directory, and set dfd to ".";
740027
+     using dfd in remaining tests will expose any bugs if emulation
740027
+     via /proc/self/fd doesn't check for empty names.  */
740027
+  ASSERT (chdir ("..") == 0);
740027
+  ASSERT (close (dfd) == 0);
740027
+  dfd = open (".", O_RDONLY);
740027
+  ASSERT (0 <= dfd);
740027
+
740027
+  ASSERT (close (creat (BASE "sub2/file", 0600)) == 0);
740027
+  errno = 0;
740027
+  ASSERT (renameat (dfd, BASE "sub1", dfd, BASE "sub2") == -1);
740027
+  ASSERT (errno == EEXIST || errno == ENOTEMPTY);
740027
+  ASSERT (unlink (BASE "sub2/file") == 0);
740027
+  errno = 0;
740027
+  ASSERT (renameat (dfd, BASE "sub2", dfd, BASE "sub1/.") == -1);
740027
+  ASSERT (errno == EINVAL || errno == EISDIR || errno == EBUSY
740027
+          || errno == ENOTEMPTY || errno == EEXIST);
740027
+  errno = 0;
740027
+  ASSERT (renameat (dfd, BASE "sub2/.", dfd, BASE "sub1") == -1);
740027
+  ASSERT (errno == EINVAL || errno == EBUSY || errno == EEXIST);
740027
+  errno = 0;
740027
+  ASSERT (renameat (dfd, BASE "17", dfd, BASE "sub1") == -1);
740027
+  ASSERT (errno == EISDIR);
740027
+  errno = 0;
740027
+  ASSERT (renameat (dfd, BASE "nosuch", dfd, BASE "18") == -1);
740027
+  ASSERT (errno == ENOENT);
740027
+  errno = 0;
740027
+  ASSERT (renameat (dfd, "", dfd, BASE "17") == -1);
740027
+  ASSERT (errno == ENOENT);
740027
+  errno = 0;
740027
+  ASSERT (renameat (dfd, BASE "17", dfd, "") == -1);
740027
+  ASSERT (errno == ENOENT);
740027
+  errno = 0;
740027
+  ASSERT (renameat (dfd, BASE "sub2", dfd, BASE "17") == -1);
740027
+  ASSERT (errno == ENOTDIR);
740027
+  errno = 0;
740027
+  ASSERT (renameat (dfd, BASE "17/", dfd, BASE "18") == -1);
740027
+  ASSERT (errno == ENOTDIR);
740027
+  errno = 0;
740027
+  ASSERT (renameat (dfd, BASE "17", dfd, BASE "18/") == -1);
740027
+  ASSERT (errno == ENOTDIR || errno == ENOENT);
740027
+
740027
+  /* Finally, make sure we can overwrite existing files.  */
740027
+  ASSERT (close (creat (BASE "sub2/file", 0600)) == 0);
740027
+  errno = 0;
740027
+  ASSERT (renameat (dfd, BASE "sub2", dfd, BASE "sub1") == 0);
740027
+  ASSERT (renameat (dfd, BASE "sub1/file", dfd, BASE "17") == 0);
740027
+
740027
+  /* Cleanup.  */
740027
+  ASSERT (close (dfd) == 0);
740027
+  errno = 0;
740027
+  ASSERT (unlink (BASE "sub1/file") == -1);
740027
+  ASSERT (errno == ENOENT);
740027
+  ASSERT (unlink (BASE "17") == 0);
740027
+  ASSERT (rmdir (BASE "sub1") == 0);
740027
+  errno = 0;
740027
+  ASSERT (rmdir (BASE "sub2") == -1);
740027
+  ASSERT (errno == ENOENT);
740027
+  free (cwd);
740027
+
740027
+  if (result)
740027
+    fputs ("skipping test: symlinks not supported on this file system\n",
740027
+           stderr);
740027
+  return result;
740027
+}
740027
diff --git a/gnulib-tests/test-renameat2.c b/gnulib-tests/test-renameat2.c
740027
new file mode 100644
740027
index 0000000..7c250ea
740027
--- /dev/null
740027
+++ b/gnulib-tests/test-renameat2.c
740027
@@ -0,0 +1,209 @@
740027
+/* Test renameat2.
740027
+   Copyright (C) 2009-2017 Free Software Foundation, Inc.
740027
+
740027
+   This program is free software: you can redistribute it and/or modify
740027
+   it under the terms of the GNU General Public License as published by
740027
+   the Free Software Foundation; either version 3 of the License, or
740027
+   (at your option) any later version.
740027
+
740027
+   This program is distributed in the hope that it will be useful,
740027
+   but WITHOUT ANY WARRANTY; without even the implied warranty of
740027
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
740027
+   GNU General Public License for more details.
740027
+
740027
+   You should have received a copy of the GNU General Public License
740027
+   along with this program.  If not, see <https://www.gnu.org/licenses/>.  */
740027
+
740027
+/* Written by Eric Blake <ebb9@byu.net>, 2009.  */
740027
+
740027
+#include <config.h>
740027
+
740027
+#include <renameat2.h>
740027
+
740027
+#include <stdio.h>
740027
+
740027
+#include "signature.h"
740027
+SIGNATURE_CHECK (renameat2, int,
740027
+                 (int, char const *, int, char const *, unsigned int));
740027
+
740027
+#include <dirent.h>
740027
+#include <fcntl.h>
740027
+#include <errno.h>
740027
+#include <stdbool.h>
740027
+#include <stdlib.h>
740027
+#include <string.h>
740027
+#include <unistd.h>
740027
+#include <sys/stat.h>
740027
+
740027
+#include "filenamecat.h"
740027
+#include "ignore-value.h"
740027
+#include "macros.h"
740027
+
740027
+#define BASE "test-renameat2.t"
740027
+
740027
+#include "test-rename.h"
740027
+
740027
+static int dfd1 = AT_FDCWD;
740027
+static int dfd2 = AT_FDCWD;
740027
+
740027
+/* Wrapper to test renameat2 like rename.  */
740027
+static int
740027
+do_rename (char const *name1, char const *name2)
740027
+{
740027
+  return renameat2 (dfd1, name1, dfd2, name2, 0);
740027
+}
740027
+
740027
+int
740027
+main (void)
740027
+{
740027
+  int i;
740027
+  int dfd;
740027
+  char *cwd;
740027
+  int result;
740027
+
740027
+  /* Clean up any trash from prior testsuite runs.  */
740027
+  ignore_value (system ("rm -rf " BASE "*"));
740027
+
740027
+  /* Test behaviour for invalid file descriptors.  */
740027
+  {
740027
+    errno = 0;
740027
+    ASSERT (renameat2 (-1, "foo", AT_FDCWD, "bar", 0) == -1);
740027
+    ASSERT (errno == EBADF);
740027
+  }
740027
+  {
740027
+    close (99);
740027
+    errno = 0;
740027
+    ASSERT (renameat2 (99, "foo", AT_FDCWD, "bar", 0) == -1);
740027
+    ASSERT (errno == EBADF);
740027
+  }
740027
+  ASSERT (close (creat (BASE "oo", 0600)) == 0);
740027
+  {
740027
+    errno = 0;
740027
+    ASSERT (renameat2 (AT_FDCWD, BASE "oo", -1, "bar", 0) == -1);
740027
+    ASSERT (errno == EBADF);
740027
+  }
740027
+  {
740027
+    errno = 0;
740027
+    ASSERT (renameat2 (AT_FDCWD, BASE "oo", 99, "bar", 0) == -1);
740027
+    ASSERT (errno == EBADF);
740027
+  }
740027
+  ASSERT (unlink (BASE "oo") == 0);
740027
+
740027
+  /* Test basic rename functionality, using current directory.  */
740027
+  result = test_rename (do_rename, false);
740027
+  dfd1 = open (".", O_RDONLY);
740027
+  ASSERT (0 <= dfd1);
740027
+  ASSERT (test_rename (do_rename, false) == result);
740027
+  dfd2 = dfd1;
740027
+  ASSERT (test_rename (do_rename, false) == result);
740027
+  dfd1 = AT_FDCWD;
740027
+  ASSERT (test_rename (do_rename, false) == result);
740027
+  ASSERT (close (dfd2) == 0);
740027
+
740027
+  /* Create locations to manipulate.  */
740027
+  ASSERT (mkdir (BASE "sub1", 0700) == 0);
740027
+  ASSERT (mkdir (BASE "sub2", 0700) == 0);
740027
+  dfd = creat (BASE "00", 0600);
740027
+  ASSERT (0 <= dfd);
740027
+  ASSERT (close (dfd) == 0);
740027
+  cwd = getcwd (NULL, 0);
740027
+  ASSERT (cwd);
740027
+
740027
+  dfd = open (BASE "sub1", O_RDONLY);
740027
+  ASSERT (0 <= dfd);
740027
+  ASSERT (chdir (BASE "sub2") == 0);
740027
+
740027
+  /* There are 16 possible scenarios, based on whether an fd is
740027
+     AT_FDCWD or real, and whether a file is absolute or relative.
740027
+
740027
+     To ensure that we test all of the code paths (rather than
740027
+     triggering early normalization optimizations), we use a loop to
740027
+     repeatedly rename a file in the parent directory, use an fd open
740027
+     on subdirectory 1, all while executing in subdirectory 2; all
740027
+     relative names are thus given with a leading "../".  Finally, the
740027
+     last scenario (two relative paths given, neither one AT_FDCWD)
740027
+     has two paths, based on whether the two fds are equivalent, so we
740027
+     do the other variant after the loop.  */
740027
+  for (i = 0; i < 16; i++)
740027
+    {
740027
+      int fd1 = (i & 8) ? dfd : AT_FDCWD;
740027
+      char *file1 = file_name_concat ((i & 4) ? ".." : cwd, BASE "xx", NULL);
740027
+      int fd2 = (i & 2) ? dfd : AT_FDCWD;
740027
+      char *file2 = file_name_concat ((i & 1) ? ".." : cwd, BASE "xx", NULL);
740027
+
740027
+      ASSERT (sprintf (strchr (file1, '\0') - 2, "%02d", i) == 2);
740027
+      ASSERT (sprintf (strchr (file2, '\0') - 2, "%02d", i + 1) == 2);
740027
+      ASSERT (renameat2 (fd1, file1, fd2, file2, 0) == 0);
740027
+      free (file1);
740027
+      free (file2);
740027
+    }
740027
+  dfd2 = open ("..", O_RDONLY);
740027
+  ASSERT (0 <= dfd2);
740027
+  ASSERT (renameat2 (dfd, "../" BASE "16", dfd2, BASE "17", 0) == 0);
740027
+  ASSERT (close (dfd2) == 0);
740027
+
740027
+  /* Now we change back to the parent directory, and set dfd to ".";
740027
+     using dfd in remaining tests will expose any bugs if emulation
740027
+     via /proc/self/fd doesn't check for empty names.  */
740027
+  ASSERT (chdir ("..") == 0);
740027
+  ASSERT (close (dfd) == 0);
740027
+  dfd = open (".", O_RDONLY);
740027
+  ASSERT (0 <= dfd);
740027
+
740027
+  ASSERT (close (creat (BASE "sub2/file", 0600)) == 0);
740027
+  errno = 0;
740027
+  ASSERT (renameat2 (dfd, BASE "sub1", dfd, BASE "sub2", 0) == -1);
740027
+  ASSERT (errno == EEXIST || errno == ENOTEMPTY);
740027
+  ASSERT (unlink (BASE "sub2/file") == 0);
740027
+  errno = 0;
740027
+  ASSERT (renameat2 (dfd, BASE "sub2", dfd, BASE "sub1/.", 0) == -1);
740027
+  ASSERT (errno == EINVAL || errno == EISDIR || errno == EBUSY
740027
+          || errno == ENOTEMPTY || errno == EEXIST);
740027
+  errno = 0;
740027
+  ASSERT (renameat2 (dfd, BASE "sub2/.", dfd, BASE "sub1", 0) == -1);
740027
+  ASSERT (errno == EINVAL || errno == EBUSY || errno == EEXIST);
740027
+  errno = 0;
740027
+  ASSERT (renameat2 (dfd, BASE "17", dfd, BASE "sub1", 0) == -1);
740027
+  ASSERT (errno == EISDIR);
740027
+  errno = 0;
740027
+  ASSERT (renameat2 (dfd, BASE "nosuch", dfd, BASE "18", 0) == -1);
740027
+  ASSERT (errno == ENOENT);
740027
+  errno = 0;
740027
+  ASSERT (renameat2 (dfd, "", dfd, BASE "17", 0) == -1);
740027
+  ASSERT (errno == ENOENT);
740027
+  errno = 0;
740027
+  ASSERT (renameat2 (dfd, BASE "17", dfd, "", 0) == -1);
740027
+  ASSERT (errno == ENOENT);
740027
+  errno = 0;
740027
+  ASSERT (renameat2 (dfd, BASE "sub2", dfd, BASE "17", 0) == -1);
740027
+  ASSERT (errno == ENOTDIR);
740027
+  errno = 0;
740027
+  ASSERT (renameat2 (dfd, BASE "17/", dfd, BASE "18", 0) == -1);
740027
+  ASSERT (errno == ENOTDIR);
740027
+  errno = 0;
740027
+  ASSERT (renameat2 (dfd, BASE "17", dfd, BASE "18/", 0) == -1);
740027
+  ASSERT (errno == ENOTDIR || errno == ENOENT);
740027
+
740027
+  /* Finally, make sure we cannot overwrite existing files.  */
740027
+  ASSERT (close (creat (BASE "sub2/file", 0600)) == 0);
740027
+  errno = 0;
740027
+  ASSERT ((renameat2 (dfd, BASE "sub2", dfd, BASE "sub1", RENAME_NOREPLACE)
740027
+           == -1)
740027
+          && errno == EEXIST);
740027
+  ASSERT ((renameat2 (dfd, BASE "sub2/file", dfd, BASE "17", RENAME_NOREPLACE)
740027
+           == -1)
740027
+          && errno == EEXIST);
740027
+
740027
+  /* Cleanup.  */
740027
+  ASSERT (close (dfd) == 0);
740027
+  ASSERT (unlink (BASE "sub2/file") == 0);
740027
+  ASSERT (unlink (BASE "17") == 0);
740027
+  ASSERT (rmdir (BASE "sub1") == 0);
740027
+  ASSERT (rmdir (BASE "sub2") == 0);
740027
+  free (cwd);
740027
+
740027
+  if (result)
740027
+    fputs ("skipping test: symlinks not supported on this file system\n",
740027
+           stderr);
740027
+  return result;
740027
+}
740027
diff --git a/lib/gnulib.mk b/lib/gnulib.mk
740027
index 844791b..76729b0 100644
740027
--- a/lib/gnulib.mk
740027
+++ b/lib/gnulib.mk
740027
@@ -21,7 +21,7 @@
740027
 # the same distribution terms as the rest of that program.
740027
 #
740027
 # Generated by gnulib-tool.
740027
-# Reproduce by: gnulib-tool --import --dir=. --local-dir=gl --lib=libcoreutils --source-base=lib --m4-base=m4 --doc-base=doc --tests-base=gnulib-tests --aux-dir=build-aux --with-tests --avoid=canonicalize-lgpl --avoid=dummy --makefile-name=gnulib.mk --no-conditional-dependencies --no-libtool --macro-prefix=gl acl alignof alloca announce-gen areadlink-with-size argmatch argv-iter assert autobuild backupfile base64 buffer-lcm c-strcase c-strtod c-strtold calloc-gnu canon-host canonicalize chown cloexec closein closeout config-h configmake crypto/md5 crypto/sha1 crypto/sha256 crypto/sha512 cycle-check d-ino d-type di-set diacrit dirfd dirname do-release-commit-and-tag dtoastr dup2 environ error euidaccess exclude exitfail faccessat fadvise fchdir fchmodat fchownat fclose fcntl fcntl-safer fd-reopen fdatasync fdl fdopen fdutimensat file-type fileblocks filemode filenamecat filevercmp fnmatch-gnu fopen-safer fprintftime freopen freopen-safer fseeko fstatat fsusage fsync ftello ftoastr ftruncate fts full-read full-write getgroups gethrxtime getline getloadavg getlogin getndelim2 getopt-gnu getpagesize getpass-gnu gettext-h gettime gettimeofday getugroups getusershell git-version-gen gitlog-to-changelog gnu-make gnu-web-doc-update gnumakefile gnupload group-member hard-locale hash hash-pjw heap host-os human idcache ignore-value inttostr inttypes isapipe isatty isblank largefile lchmod lchown ldtoastr lib-ignore linebuffer link link-follow linkat long-options lstat maintainer-makefile malloc-gnu manywarnings mbrlen mbrtowc mbsalign mbswidth memcasecmp memchr memcmp2 mempcpy memrchr mgetgroups mkancesdirs mkdir mkdir-p mkfifo mknod mkstemp mktime modechange mountlist mpsort netinet_in non-recursive-gnulib-prefix-hack nproc obstack parse-datetime pathmax perl physmem pipe posix-shell posixtm posixver priv-set progname propername pthread putenv quote quotearg randint randperm read-file readlink readtokens readtokens0 readutmp realloc-gnu regex remove rename rmdir root-dev-ino rpmatch safe-read same save-cwd savedir savewd selinux-at settime sig2str sigaction smack ssize_t stat-macros stat-size stat-time statat stdbool stdlib-safer stpcpy stpncpy strdup-posix strftime strncat strnumcmp strpbrk strsignal strtod strtoimax strtoumax symlink sys_ioctl sys_resource sys_stat sys_wait termios timer-time timespec tzset uname unicodeio unistd-safer unlink-busy unlinkat unlocked-io unsetenv update-copyright uptime useless-if-before-free userspec utimecmp utimens vasprintf-posix vc-list-files verify verror version-etc-fsf wcswidth wcwidth winsz-ioctl winsz-termios write-any-file xalloc xfreopen xfts xgetcwd xgetgroups xgethostname xmemcoll xnanosleep xprintf xprintf-posix xreadlink xstrtod xstrtoimax xstrtol xstrtold xstrtoumax yesno
740027
+# Reproduce by: gnulib-tool --import --dir=. --local-dir=gl --lib=libcoreutils --source-base=lib --m4-base=m4 --doc-base=doc --tests-base=gnulib-tests --aux-dir=build-aux --with-tests --avoid=canonicalize-lgpl --avoid=dummy --makefile-name=gnulib.mk --no-conditional-dependencies --no-libtool --macro-prefix=gl acl alignof alloca announce-gen areadlink-with-size argmatch argv-iter assert autobuild backupfile base64 buffer-lcm c-strcase c-strtod c-strtold calloc-gnu canon-host canonicalize chown cloexec closein closeout config-h configmake crypto/md5 crypto/sha1 crypto/sha256 crypto/sha512 cycle-check d-ino d-type di-set diacrit dirfd dirname do-release-commit-and-tag dtoastr dup2 environ error euidaccess exclude exitfail faccessat fadvise fchdir fchmodat fchownat fclose fcntl fcntl-safer fd-reopen fdatasync fdl fdopen fdutimensat file-type fileblocks filemode filenamecat filevercmp fnmatch-gnu fopen-safer fprintftime freopen freopen-safer fseeko fstatat fsusage fsync ftello ftoastr ftruncate fts full-read full-write getgroups gethrxtime getline getloadavg getlogin getndelim2 getopt-gnu getpagesize getpass-gnu gettext-h gettime gettimeofday getugroups getusershell git-version-gen gitlog-to-changelog gnu-make gnu-web-doc-update gnumakefile gnupload group-member hard-locale hash hash-pjw heap host-os human idcache ignore-value inttostr inttypes isapipe isatty isblank largefile lchmod lchown ldtoastr lib-ignore linebuffer link link-follow linkat long-options lstat maintainer-makefile malloc-gnu manywarnings mbrlen mbrtowc mbsalign mbswidth memcasecmp memchr memcmp2 mempcpy memrchr mgetgroups mkancesdirs mkdir mkdir-p mkfifo mknod mkstemp mktime modechange mountlist mpsort netinet_in non-recursive-gnulib-prefix-hack nproc obstack parse-datetime pathmax perl physmem pipe posix-shell posixtm posixver priv-set progname propername pthread putenv quote quotearg randint randperm read-file readlink readtokens readtokens0 readutmp realloc-gnu regex remove rename renameat renameat2 rmdir root-dev-ino rpmatch safe-read same save-cwd savedir savewd selinux-at settime sig2str sigaction smack ssize_t stat-macros stat-size stat-time statat stdbool stdlib-safer stpcpy stpncpy strdup-posix strftime strncat strnumcmp strpbrk strsignal strtod strtoimax strtoumax symlink sys_ioctl sys_resource sys_stat sys_wait termios timer-time timespec tzset uname unicodeio unistd-safer unlink-busy unlinkat unlocked-io unsetenv update-copyright uptime useless-if-before-free userspec utimecmp utimens vasprintf-posix vc-list-files verify verror version-etc-fsf wcswidth wcwidth winsz-ioctl winsz-termios write-any-file xalloc xfreopen xfts xgetcwd xgetgroups xgethostname xmemcoll xnanosleep xprintf xprintf-posix xreadlink xstrtod xstrtoimax xstrtol xstrtold xstrtoumax yesno
740027
 
740027
 
740027
 MOSTLYCLEANFILES += lib/core lib/*.stackdump
740027
@@ -3202,6 +3202,25 @@ EXTRA_lib_libcoreutils_a_SOURCES += lib/rename.c
740027
 
740027
 ## end   gnulib module rename
740027
 
740027
+## begin gnulib module renameat
740027
+
740027
+
740027
+EXTRA_DIST += lib/renameat.c
740027
+
740027
+EXTRA_lib_libcoreutils_a_SOURCES += lib/renameat.c
740027
+
740027
+## end   gnulib module renameat
740027
+
740027
+## begin gnulib module renameat2
740027
+
740027
+lib_libcoreutils_a_SOURCES += lib/renameat2.c
740027
+
740027
+EXTRA_DIST += lib/at-func2.c lib/renameat2.h
740027
+
740027
+EXTRA_lib_libcoreutils_a_SOURCES += lib/at-func2.c
740027
+
740027
+## end   gnulib module renameat2
740027
+
740027
 ## begin gnulib module rewinddir
740027
 
740027
 
740027
diff --git a/lib/renameat.c b/lib/renameat.c
740027
new file mode 100644
740027
index 0000000..48cee4b
740027
--- /dev/null
740027
+++ b/lib/renameat.c
740027
@@ -0,0 +1,25 @@
740027
+/* Rename a file relative to open directories.
740027
+   Copyright 2017 Free Software Foundation, Inc.
740027
+
740027
+   This program is free software: you can redistribute it and/or modify
740027
+   it under the terms of the GNU General Public License as published by
740027
+   the Free Software Foundation; either version 3 of the License, or
740027
+   (at your option) any later version.
740027
+
740027
+   This program is distributed in the hope that it will be useful,
740027
+   but WITHOUT ANY WARRANTY; without even the implied warranty of
740027
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
740027
+   GNU General Public License for more details.
740027
+
740027
+   You should have received a copy of the GNU General Public License
740027
+   along with this program.  If not, see <https://www.gnu.org/licenses/>.  */
740027
+
740027
+#include <config.h>
740027
+#include <stdio.h>
740027
+#include "renameat2.h"
740027
+
740027
+int
740027
+renameat (int fd1, char const *src, int fd2, char const *dst)
740027
+{
740027
+  return renameat2 (fd1, src, fd2, dst, 0);
740027
+}
740027
diff --git a/lib/renameat2.c b/lib/renameat2.c
740027
new file mode 100644
740027
index 0000000..26cde86
740027
--- /dev/null
740027
+++ b/lib/renameat2.c
740027
@@ -0,0 +1,227 @@
740027
+/* Rename a file relative to open directories.
740027
+   Copyright (C) 2009-2017 Free Software Foundation, Inc.
740027
+
740027
+   This program is free software: you can redistribute it and/or modify
740027
+   it under the terms of the GNU General Public License as published by
740027
+   the Free Software Foundation; either version 3 of the License, or
740027
+   (at your option) any later version.
740027
+
740027
+   This program is distributed in the hope that it will be useful,
740027
+   but WITHOUT ANY WARRANTY; without even the implied warranty of
740027
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
740027
+   GNU General Public License for more details.
740027
+
740027
+   You should have received a copy of the GNU General Public License
740027
+   along with this program.  If not, see <https://www.gnu.org/licenses/>.  */
740027
+
740027
+/* written by Eric Blake and Paul Eggert */
740027
+
740027
+#include <config.h>
740027
+
740027
+#include "renameat2.h"
740027
+
740027
+#include <errno.h>
740027
+#include <stdio.h>
740027
+#include <sys/stat.h>
740027
+#include <unistd.h>
740027
+
740027
+#ifdef __linux__
740027
+# include <sys/syscall.h>
740027
+#endif
740027
+
740027
+static int
740027
+errno_fail (int e)
740027
+{
740027
+  errno = e;
740027
+  return -1;
740027
+}
740027
+
740027
+#if HAVE_RENAMEAT
740027
+
740027
+# include <stdbool.h>
740027
+# include <stdlib.h>
740027
+# include <string.h>
740027
+
740027
+# include "dirname.h"
740027
+# include "openat.h"
740027
+
740027
+#else
740027
+# include "openat-priv.h"
740027
+
740027
+static int
740027
+rename_noreplace (char const *src, char const *dst)
740027
+{
740027
+  /* This has a race between the call to lstat and the call to rename.  */
740027
+  struct stat st;
740027
+  return (lstat (dst, &st) == 0 || errno == EOVERFLOW ? errno_fail (EEXIST)
740027
+          : errno == ENOENT ? rename (src, dst)
740027
+          : -1);
740027
+}
740027
+#endif
740027
+
740027
+#undef renameat
740027
+
740027
+/* Rename FILE1, in the directory open on descriptor FD1, to FILE2, in
740027
+   the directory open on descriptor FD2.  If possible, do it without
740027
+   changing the working directory.  Otherwise, resort to using
740027
+   save_cwd/fchdir, then rename/restore_cwd.  If either the save_cwd or
740027
+   the restore_cwd fails, then give a diagnostic and exit nonzero.
740027
+
740027
+   Obey FLAGS when doing the renaming.  If FLAGS is zero, this
740027
+   function is equivalent to renameat (FD1, SRC, FD2, DST).  */
740027
+
740027
+int
740027
+renameat2 (int fd1, char const *src, int fd2, char const *dst,
740027
+           unsigned int flags)
740027
+{
740027
+  int ret_val = -1;
740027
+  int err = EINVAL;
740027
+
740027
+#ifdef SYS_renameat2
740027
+  ret_val = syscall (SYS_renameat2, fd1, src, fd2, dst, flags);
740027
+  err = errno;
740027
+#elif defined RENAME_EXCL
740027
+  if (! (flags & ~(RENAME_EXCHANGE | RENAME_NOREPLACE)))
740027
+    {
740027
+      ret_val = renameatx_np (fd1, src, fd2, dst,
740027
+                             ((flags & RENAME_EXCHANGE ? RENAME_SWAP : 0)
740027
+                              | (flags & RENAME_NOREPLACE ? RENAME_EXCL : 0)));
740027
+      err = errno;
740027
+    }
740027
+#endif
740027
+
740027
+  if (! (ret_val < 0 && (err == EINVAL || err == ENOSYS || err == ENOTSUP)))
740027
+    return ret_val;
740027
+
740027
+#if HAVE_RENAMEAT
740027
+  {
740027
+  size_t src_len;
740027
+  size_t dst_len;
740027
+  char *src_temp = (char *) src;
740027
+  char *dst_temp = (char *) dst;
740027
+  bool src_slash;
740027
+  bool dst_slash;
740027
+  int rename_errno = ENOTDIR;
740027
+  struct stat src_st;
740027
+  struct stat dst_st;
740027
+  bool dst_found_nonexistent = false;
740027
+
740027
+  if (flags != 0)
740027
+    {
740027
+      /* RENAME_NOREPLACE is the only flag currently supported.  */
740027
+      if (flags & ~RENAME_NOREPLACE)
740027
+        return errno_fail (ENOTSUP);
740027
+      else
740027
+        {
740027
+          /* This has a race between the call to lstatat and the calls to
740027
+             renameat below.  */
740027
+          if (lstatat (fd2, dst, &dst_st) == 0 || errno == EOVERFLOW)
740027
+            return errno_fail (EEXIST);
740027
+          if (errno != ENOENT)
740027
+            return -1;
740027
+          dst_found_nonexistent = true;
740027
+        }
740027
+    }
740027
+
740027
+  /* Let strace see any ENOENT failure.  */
740027
+  src_len = strlen (src);
740027
+  dst_len = strlen (dst);
740027
+  if (!src_len || !dst_len)
740027
+    return renameat (fd1, src, fd2, dst);
740027
+
740027
+  src_slash = src[src_len - 1] == '/';
740027
+  dst_slash = dst[dst_len - 1] == '/';
740027
+  if (!src_slash && !dst_slash)
740027
+    return renameat (fd1, src, fd2, dst);
740027
+
740027
+  /* Presence of a trailing slash requires directory semantics.  If
740027
+     the source does not exist, or if the destination cannot be turned
740027
+     into a directory, give up now.  Otherwise, strip trailing slashes
740027
+     before calling rename.  */
740027
+  if (lstatat (fd1, src, &src_st))
740027
+    return -1;
740027
+  if (dst_found_nonexistent)
740027
+    {
740027
+      if (!S_ISDIR (src_st.st_mode))
740027
+        return errno_fail (ENOENT);
740027
+    }
740027
+  else if (lstatat (fd2, dst, &dst_st))
740027
+    {
740027
+      if (errno != ENOENT || !S_ISDIR (src_st.st_mode))
740027
+        return -1;
740027
+    }
740027
+  else if (!S_ISDIR (dst_st.st_mode))
740027
+    return errno_fail (ENOTDIR);
740027
+  else if (!S_ISDIR (src_st.st_mode))
740027
+    return errno_fail (EISDIR);
740027
+
740027
+# if RENAME_TRAILING_SLASH_SOURCE_BUG
740027
+  /* See the lengthy comment in rename.c why Solaris 9 is forced to
740027
+     GNU behavior, while Solaris 10 is left with POSIX behavior,
740027
+     regarding symlinks with trailing slash.  */
740027
+  ret_val = -1;
740027
+  if (src_slash)
740027
+    {
740027
+      src_temp = strdup (src);
740027
+      if (!src_temp)
740027
+        {
740027
+          /* Rather than rely on strdup-posix, we set errno ourselves.  */
740027
+          rename_errno = ENOMEM;
740027
+          goto out;
740027
+        }
740027
+      strip_trailing_slashes (src_temp);
740027
+      if (lstatat (fd1, src_temp, &src_st))
740027
+        {
740027
+          rename_errno = errno;
740027
+          goto out;
740027
+        }
740027
+      if (S_ISLNK (src_st.st_mode))
740027
+        goto out;
740027
+    }
740027
+  if (dst_slash)
740027
+    {
740027
+      dst_temp = strdup (dst);
740027
+      if (!dst_temp)
740027
+        {
740027
+          rename_errno = ENOMEM;
740027
+          goto out;
740027
+        }
740027
+      strip_trailing_slashes (dst_temp);
740027
+      if (lstatat (fd2, dst_temp, &dst_st))
740027
+        {
740027
+          if (errno != ENOENT)
740027
+            {
740027
+              rename_errno = errno;
740027
+              goto out;
740027
+            }
740027
+        }
740027
+      else if (S_ISLNK (dst_st.st_mode))
740027
+        goto out;
740027
+    }
740027
+# endif /* RENAME_TRAILING_SLASH_SOURCE_BUG */
740027
+
740027
+  /* renameat does not honor trailing / on Solaris 10.  Solve it in a
740027
+     similar manner to rename.  No need to worry about bugs not present
740027
+     on Solaris, since all other systems either lack renameat or honor
740027
+     trailing slash correctly.  */
740027
+
740027
+  ret_val = renameat (fd1, src_temp, fd2, dst_temp);
740027
+  rename_errno = errno;
740027
+  goto out;
740027
+ out:
740027
+  if (src_temp != src)
740027
+    free (src_temp);
740027
+  if (dst_temp != dst)
740027
+    free (dst_temp);
740027
+  errno = rename_errno;
740027
+  return ret_val;
740027
+  }
740027
+#else /* !HAVE_RENAMEAT */
740027
+
740027
+  /* RENAME_NOREPLACE is the only flag currently supported.  */
740027
+  if (flags & ~RENAME_NOREPLACE)
740027
+    return errno_fail (ENOTSUP);
740027
+  return at_func2 (fd1, src, fd2, dst, flags ? rename_noreplace : rename);
740027
+
740027
+#endif /* !HAVE_RENAMEAT */
740027
+}
740027
diff --git a/lib/renameat2.h b/lib/renameat2.h
740027
new file mode 100644
740027
index 0000000..179210f
740027
--- /dev/null
740027
+++ b/lib/renameat2.h
740027
@@ -0,0 +1,30 @@
740027
+/* Rename a file relative to open directories.
740027
+   Copyright 2017 Free Software Foundation, Inc.
740027
+
740027
+   This program is free software: you can redistribute it and/or modify
740027
+   it under the terms of the GNU General Public License as published by
740027
+   the Free Software Foundation; either version 3 of the License, or
740027
+   (at your option) any later version.
740027
+
740027
+   This program is distributed in the hope that it will be useful,
740027
+   but WITHOUT ANY WARRANTY; without even the implied warranty of
740027
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
740027
+   GNU General Public License for more details.
740027
+
740027
+   You should have received a copy of the GNU General Public License
740027
+   along with this program.  If not, see <https://www.gnu.org/licenses/>.  */
740027
+
740027
+/* written by Paul Eggert */
740027
+
740027
+/* Get RENAME_* macros from linux/fs.h if present, otherwise supply
740027
+   the traditional Linux values.  */
740027
+#if HAVE_LINUX_FS_H
740027
+# include <linux/fs.h>
740027
+#endif
740027
+#ifndef RENAME_NOREPLACE
740027
+# define RENAME_NOREPLACE  (1 << 0)
740027
+# define RENAME_EXCHANGE   (1 << 1)
740027
+# define RENAME_WHITEOUT   (1 << 2)
740027
+#endif
740027
+
740027
+extern int renameat2 (int, char const *, int, char const *, unsigned int);
740027
diff --git a/m4/gnulib-comp.m4 b/m4/gnulib-comp.m4
740027
index 4ef3c43..309e308 100644
740027
--- a/m4/gnulib-comp.m4
740027
+++ b/m4/gnulib-comp.m4
740027
@@ -547,6 +547,10 @@ AC_DEFUN([gl_EARLY],
740027
   # Code from module remove-tests:
740027
   # Code from module rename:
740027
   # Code from module rename-tests:
740027
+  # Code from module renameat:
740027
+  # Code from module renameat-tests:
740027
+  # Code from module renameat2:
740027
+  # Code from module renameat2-tests:
740027
   # Code from module rewinddir:
740027
   # Code from module rmdir:
740027
   # Code from module rmdir-tests:
740027
@@ -1696,6 +1700,18 @@ AC_DEFUN([gl_INIT],
740027
     AC_LIBOBJ([rename])
740027
   fi
740027
   gl_STDIO_MODULE_INDICATOR([rename])
740027
+  gl_FUNC_RENAMEAT
740027
+  if test $HAVE_RENAMEAT = 0 || test $REPLACE_RENAMEAT = 1; then
740027
+    AC_LIBOBJ([renameat])
740027
+  fi
740027
+  if test $HAVE_RENAMEAT = 0; then
740027
+    AC_LIBOBJ([at-func2])
740027
+  fi
740027
+  gl_STDIO_MODULE_INDICATOR([renameat])
740027
+  gl_FUNC_RENAMEAT
740027
+  if test $HAVE_RENAMEAT = 0; then
740027
+    AC_LIBOBJ([at-func2])
740027
+  fi
740027
   gl_FUNC_REWINDDIR
740027
   if test $HAVE_REWINDDIR = 0; then
740027
     AC_LIBOBJ([rewinddir])
740027
@@ -2868,6 +2884,9 @@ AC_DEFUN([gl_FILE_LIST], [
740027
   lib/regexec.c
740027
   lib/remove.c
740027
   lib/rename.c
740027
+  lib/renameat.c
740027
+  lib/renameat2.c
740027
+  lib/renameat2.h
740027
   lib/rewinddir.c
740027
   lib/rmdir.c
740027
   lib/root-dev-ino.c
740027
@@ -3372,6 +3391,7 @@ AC_DEFUN([gl_FILE_LIST], [
740027
   m4/regex.m4
740027
   m4/remove.m4
740027
   m4/rename.m4
740027
+  m4/renameat.m4
740027
   m4/rewinddir.m4
740027
   m4/rmdir.m4
740027
   m4/rpmatch.m4
740027
@@ -3794,6 +3814,8 @@ AC_DEFUN([gl_FILE_LIST], [
740027
   tests/test-remove.c
740027
   tests/test-rename.c
740027
   tests/test-rename.h
740027
+  tests/test-renameat.c
740027
+  tests/test-renameat2.c
740027
   tests/test-rmdir.c
740027
   tests/test-rmdir.h
740027
   tests/test-sameacls.c
740027
diff --git a/m4/renameat.m4 b/m4/renameat.m4
740027
new file mode 100644
740027
index 0000000..1b97774
740027
--- /dev/null
740027
+++ b/m4/renameat.m4
740027
@@ -0,0 +1,25 @@
740027
+# serial 3
740027
+# See if we need to provide renameat replacement.
740027
+
740027
+dnl Copyright (C) 2009-2017 Free Software Foundation, Inc.
740027
+dnl This file is free software; the Free Software Foundation
740027
+dnl gives unlimited permission to copy and/or distribute it,
740027
+dnl with or without modifications, as long as this notice is preserved.
740027
+
740027
+# Written by Eric Blake.
740027
+
740027
+AC_DEFUN([gl_FUNC_RENAMEAT],
740027
+[
740027
+  AC_REQUIRE([gl_FUNC_OPENAT])
740027
+  AC_REQUIRE([gl_FUNC_RENAME])
740027
+  AC_REQUIRE([gl_STDIO_H_DEFAULTS])
740027
+  AC_REQUIRE([gl_USE_SYSTEM_EXTENSIONS])
740027
+  AC_CHECK_HEADERS([linux/fs.h])
740027
+  AC_CHECK_FUNCS_ONCE([renameat])
740027
+  if test $ac_cv_func_renameat = no; then
740027
+    HAVE_RENAMEAT=0
740027
+  elif test $REPLACE_RENAME = 1; then
740027
+    dnl Solaris 9 and 10 have the same bugs in renameat as in rename.
740027
+    REPLACE_RENAMEAT=1
740027
+  fi
740027
+])
740027
diff --git a/src/copy.c b/src/copy.c
740027
index 2a804945e..be4e357a8 100644
740027
--- a/src/copy.c
740027
+++ b/src/copy.c
740027
@@ -51,6 +51,7 @@
740027
 #include "ignore-value.h"
740027
 #include "ioblksize.h"
740027
 #include "quote.h"
740027
+#include "renameat2.h"
740027
 #include "root-uid.h"
740027
 #include "same.h"
740027
 #include "savedir.h"
740027
@@ -2093,8 +2094,9 @@ copy_internal (char const *src_name, char const *dst_name,
740027
 
740027
   /* If the source is a directory, we don't always create the destination
740027
      directory.  So --verbose should not announce anything until we're
740027
-     sure we'll create a directory. */
740027
-  if (x->verbose && !S_ISDIR (src_mode))
740027
+     sure we'll create a directory.  In move mode we delay the diagnostic
740027
+     message until we know whether renameat2() has actually succeeded. */
740027
+  if (x->verbose && !S_ISDIR (src_mode) && !x->move_mode)
740027
     emit_verbose (src_name, dst_name, backup_succeeded ? dst_backup : NULL);
740027
 
740027
   /* Associate the destination file name with the source device and inode
740027
@@ -2196,9 +2198,14 @@ copy_internal (char const *src_name, char const *dst_name,
740027
 
740027
   if (x->move_mode)
740027
     {
740027
-      if (rename (src_name, dst_name) == 0)
740027
+      int flags = 0;
740027
+      if (x->interactive == I_ALWAYS_NO)
740027
+        /* do not replace DST_NAME if it was created since our last check */
740027
+        flags = RENAME_NOREPLACE;
740027
+
740027
+      if (renameat2 (AT_FDCWD, src_name, AT_FDCWD, dst_name, flags) == 0)
740027
         {
740027
-          if (x->verbose && S_ISDIR (src_mode))
740027
+          if (x->verbose)
740027
             emit_verbose (src_name, dst_name,
740027
                           backup_succeeded ? dst_backup : NULL);
740027
 
740027
@@ -2226,6 +2233,15 @@ copy_internal (char const *src_name, char const *dst_name,
740027
           return true;
740027
         }
740027
 
740027
+      if ((flags & RENAME_NOREPLACE) && (errno == EEXIST))
740027
+        {
740027
+          /* Pretend the rename succeeded, so the caller (mv)
740027
+             doesn't end up removing the source file.  */
740027
+          if (rename_succeeded)
740027
+            *rename_succeeded = true;
740027
+          return true;
740027
+        }
740027
+
740027
       /* FIXME: someday, consider what to do when moving a directory into
740027
          itself but when source and destination are on different devices.  */
740027
 
740027
@@ -2301,6 +2317,9 @@ copy_internal (char const *src_name, char const *dst_name,
740027
           return false;
740027
         }
740027
 
740027
+      if (x->verbose && !S_ISDIR (src_mode))
740027
+        emit_verbose (src_name, dst_name, backup_succeeded ? dst_backup : NULL);
740027
+
740027
       new_dst = true;
740027
     }
740027
 
740027
-- 
740027
2.13.6
740027