Blame SOURCES/coreutils-8.22-mv-n-noreplace.patch

dd59ef
From 76df06ff8fa39ae0cb0d167b7f622139778dc7d7 Mon Sep 17 00:00:00 2001
dd59ef
From: Kamil Dudka <kdudka@redhat.com>
dd59ef
Date: Thu, 4 Jan 2018 09:42:10 +0100
dd59ef
Subject: [PATCH] mv -n: do not overwrite the destination
dd59ef
dd59ef
... if it is created by another process after mv has checked its
dd59ef
non-existence.
dd59ef
dd59ef
* src/copy.c (copy_internal): Use renameat2 (..., RENAME_NOREPLACE)
dd59ef
if called by mv -n.  If it fails with EEXIST in that case, pretend
dd59ef
successful rename as if the existing destination file was detected
dd59ef
by the preceding lstat call.
dd59ef
dd59ef
Fixes https://bugs.gnu.org/29961
dd59ef
---
dd59ef
 aclocal.m4                    |   1 +
dd59ef
 bootstrap.conf                |   2 +
dd59ef
 gnulib-tests/gnulib.mk        |  18 ++++
dd59ef
 gnulib-tests/test-renameat.c  | 206 ++++++++++++++++++++++++++++++++++++++
dd59ef
 gnulib-tests/test-renameat2.c | 209 ++++++++++++++++++++++++++++++++++++++
dd59ef
 lib/gnulib.mk                 |  21 +++-
dd59ef
 lib/renameat.c                |  25 +++++
dd59ef
 lib/renameat2.c               | 227 ++++++++++++++++++++++++++++++++++++++++++
dd59ef
 lib/renameat2.h               |  30 ++++++
dd59ef
 m4/gnulib-comp.m4             |  22 ++++
dd59ef
 m4/renameat.m4                |  25 +++++
dd59ef
 src/copy.c                    |  27 ++++-
dd59ef
 12 files changed, 808 insertions(+), 5 deletions(-)
dd59ef
 create mode 100644 gnulib-tests/test-renameat.c
dd59ef
 create mode 100644 gnulib-tests/test-renameat2.c
dd59ef
 create mode 100644 lib/renameat.c
dd59ef
 create mode 100644 lib/renameat2.c
dd59ef
 create mode 100644 lib/renameat2.h
dd59ef
 create mode 100644 m4/renameat.m4
dd59ef
dd59ef
diff --git a/aclocal.m4 b/aclocal.m4
dd59ef
index 9c5a2b0..c678967 100644
dd59ef
--- a/aclocal.m4
dd59ef
+++ b/aclocal.m4
dd59ef
@@ -1332,6 +1332,7 @@ m4_include([m4/realloc.m4])
dd59ef
 m4_include([m4/regex.m4])
dd59ef
 m4_include([m4/remove.m4])
dd59ef
 m4_include([m4/rename.m4])
dd59ef
+m4_include([m4/renameat.m4])
dd59ef
 m4_include([m4/rewinddir.m4])
dd59ef
 m4_include([m4/rmdir.m4])
dd59ef
 m4_include([m4/rpmatch.m4])
dd59ef
diff --git a/bootstrap.conf b/bootstrap.conf
dd59ef
index 7def1f9..9b7c913 100644
dd59ef
--- a/bootstrap.conf
dd59ef
+++ b/bootstrap.conf
dd59ef
@@ -199,6 +199,8 @@ gnulib_modules="
dd59ef
   regex
dd59ef
   remove
dd59ef
   rename
dd59ef
+  renameat
dd59ef
+  renameat2
dd59ef
   rmdir
dd59ef
   root-dev-ino
dd59ef
   rpmatch
dd59ef
diff --git a/gnulib-tests/gnulib.mk b/gnulib-tests/gnulib.mk
dd59ef
index b2da030..38d439c 100644
dd59ef
--- a/gnulib-tests/gnulib.mk
dd59ef
+++ b/gnulib-tests/gnulib.mk
dd59ef
@@ -1676,6 +1676,24 @@ EXTRA_DIST += test-rename.h test-rename.c signature.h macros.h
dd59ef
 
dd59ef
 ## end   gnulib module rename-tests
dd59ef
 
dd59ef
+## begin gnulib module renameat-tests
dd59ef
+
dd59ef
+TESTS += test-renameat
dd59ef
+check_PROGRAMS += test-renameat
dd59ef
+test_renameat_LDADD = $(LDADD) @LIBINTL@
dd59ef
+EXTRA_DIST += test-rename.h test-renameat.c signature.h macros.h
dd59ef
+
dd59ef
+## end   gnulib module renameat-tests
dd59ef
+
dd59ef
+## begin gnulib module renameat2-tests
dd59ef
+
dd59ef
+TESTS += test-renameat2
dd59ef
+check_PROGRAMS += test-renameat2
dd59ef
+test_renameat2_LDADD = $(LDADD) @LIBINTL@
dd59ef
+EXTRA_DIST += test-rename.h test-renameat2.c signature.h macros.h
dd59ef
+
dd59ef
+## end   gnulib module renameat2-tests
dd59ef
+
dd59ef
 ## begin gnulib module rmdir-tests
dd59ef
 
dd59ef
 TESTS += test-rmdir
dd59ef
diff --git a/gnulib-tests/test-renameat.c b/gnulib-tests/test-renameat.c
dd59ef
new file mode 100644
dd59ef
index 0000000..ac96d88
dd59ef
--- /dev/null
dd59ef
+++ b/gnulib-tests/test-renameat.c
dd59ef
@@ -0,0 +1,206 @@
dd59ef
+/* Tests of renameat.
dd59ef
+   Copyright (C) 2009-2017 Free Software Foundation, Inc.
dd59ef
+
dd59ef
+   This program is free software: you can redistribute it and/or modify
dd59ef
+   it under the terms of the GNU General Public License as published by
dd59ef
+   the Free Software Foundation; either version 3 of the License, or
dd59ef
+   (at your option) any later version.
dd59ef
+
dd59ef
+   This program is distributed in the hope that it will be useful,
dd59ef
+   but WITHOUT ANY WARRANTY; without even the implied warranty of
dd59ef
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
dd59ef
+   GNU General Public License for more details.
dd59ef
+
dd59ef
+   You should have received a copy of the GNU General Public License
dd59ef
+   along with this program.  If not, see <https://www.gnu.org/licenses/>.  */
dd59ef
+
dd59ef
+/* Written by Eric Blake <ebb9@byu.net>, 2009.  */
dd59ef
+
dd59ef
+#include <config.h>
dd59ef
+
dd59ef
+#include <stdio.h>
dd59ef
+
dd59ef
+#include "signature.h"
dd59ef
+SIGNATURE_CHECK (renameat, int, (int, char const *, int, char const *));
dd59ef
+
dd59ef
+#include <dirent.h>
dd59ef
+#include <fcntl.h>
dd59ef
+#include <errno.h>
dd59ef
+#include <stdbool.h>
dd59ef
+#include <stdlib.h>
dd59ef
+#include <string.h>
dd59ef
+#include <unistd.h>
dd59ef
+#include <sys/stat.h>
dd59ef
+
dd59ef
+#include "filenamecat.h"
dd59ef
+#include "ignore-value.h"
dd59ef
+#include "macros.h"
dd59ef
+
dd59ef
+#define BASE "test-renameat.t"
dd59ef
+
dd59ef
+#include "test-rename.h"
dd59ef
+
dd59ef
+static int dfd1 = AT_FDCWD;
dd59ef
+static int dfd2 = AT_FDCWD;
dd59ef
+
dd59ef
+/* Wrapper to test renameat like rename.  */
dd59ef
+static int
dd59ef
+do_rename (char const *name1, char const *name2)
dd59ef
+{
dd59ef
+  return renameat (dfd1, name1, dfd2, name2);
dd59ef
+}
dd59ef
+
dd59ef
+int
dd59ef
+main (void)
dd59ef
+{
dd59ef
+  int i;
dd59ef
+  int dfd;
dd59ef
+  char *cwd;
dd59ef
+  int result;
dd59ef
+
dd59ef
+  /* Clean up any trash from prior testsuite runs.  */
dd59ef
+  ignore_value (system ("rm -rf " BASE "*"));
dd59ef
+
dd59ef
+  /* Test behaviour for invalid file descriptors.  */
dd59ef
+  {
dd59ef
+    errno = 0;
dd59ef
+    ASSERT (renameat (-1, "foo", AT_FDCWD, "bar") == -1);
dd59ef
+    ASSERT (errno == EBADF);
dd59ef
+  }
dd59ef
+  {
dd59ef
+    close (99);
dd59ef
+    errno = 0;
dd59ef
+    ASSERT (renameat (99, "foo", AT_FDCWD, "bar") == -1);
dd59ef
+    ASSERT (errno == EBADF);
dd59ef
+  }
dd59ef
+  ASSERT (close (creat (BASE "oo", 0600)) == 0);
dd59ef
+  {
dd59ef
+    errno = 0;
dd59ef
+    ASSERT (renameat (AT_FDCWD, BASE "oo", -1, "bar") == -1);
dd59ef
+    ASSERT (errno == EBADF);
dd59ef
+  }
dd59ef
+  {
dd59ef
+    errno = 0;
dd59ef
+    ASSERT (renameat (AT_FDCWD, BASE "oo", 99, "bar") == -1);
dd59ef
+    ASSERT (errno == EBADF);
dd59ef
+  }
dd59ef
+  ASSERT (unlink (BASE "oo") == 0);
dd59ef
+
dd59ef
+  /* Test basic rename functionality, using current directory.  */
dd59ef
+  result = test_rename (do_rename, false);
dd59ef
+  dfd1 = open (".", O_RDONLY);
dd59ef
+  ASSERT (0 <= dfd1);
dd59ef
+  ASSERT (test_rename (do_rename, false) == result);
dd59ef
+  dfd2 = dfd1;
dd59ef
+  ASSERT (test_rename (do_rename, false) == result);
dd59ef
+  dfd1 = AT_FDCWD;
dd59ef
+  ASSERT (test_rename (do_rename, false) == result);
dd59ef
+  ASSERT (close (dfd2) == 0);
dd59ef
+
dd59ef
+  /* Create locations to manipulate.  */
dd59ef
+  ASSERT (mkdir (BASE "sub1", 0700) == 0);
dd59ef
+  ASSERT (mkdir (BASE "sub2", 0700) == 0);
dd59ef
+  dfd = creat (BASE "00", 0600);
dd59ef
+  ASSERT (0 <= dfd);
dd59ef
+  ASSERT (close (dfd) == 0);
dd59ef
+  cwd = getcwd (NULL, 0);
dd59ef
+  ASSERT (cwd);
dd59ef
+
dd59ef
+  dfd = open (BASE "sub1", O_RDONLY);
dd59ef
+  ASSERT (0 <= dfd);
dd59ef
+  ASSERT (chdir (BASE "sub2") == 0);
dd59ef
+
dd59ef
+  /* There are 16 possible scenarios, based on whether an fd is
dd59ef
+     AT_FDCWD or real, and whether a file is absolute or relative.
dd59ef
+
dd59ef
+     To ensure that we test all of the code paths (rather than
dd59ef
+     triggering early normalization optimizations), we use a loop to
dd59ef
+     repeatedly rename a file in the parent directory, use an fd open
dd59ef
+     on subdirectory 1, all while executing in subdirectory 2; all
dd59ef
+     relative names are thus given with a leading "../".  Finally, the
dd59ef
+     last scenario (two relative paths given, neither one AT_FDCWD)
dd59ef
+     has two paths, based on whether the two fds are equivalent, so we
dd59ef
+     do the other variant after the loop.  */
dd59ef
+  for (i = 0; i < 16; i++)
dd59ef
+    {
dd59ef
+      int fd1 = (i & 8) ? dfd : AT_FDCWD;
dd59ef
+      char *file1 = file_name_concat ((i & 4) ? ".." : cwd, BASE "xx", NULL);
dd59ef
+      int fd2 = (i & 2) ? dfd : AT_FDCWD;
dd59ef
+      char *file2 = file_name_concat ((i & 1) ? ".." : cwd, BASE "xx", NULL);
dd59ef
+
dd59ef
+      ASSERT (sprintf (strchr (file1, '\0') - 2, "%02d", i) == 2);
dd59ef
+      ASSERT (sprintf (strchr (file2, '\0') - 2, "%02d", i + 1) == 2);
dd59ef
+      ASSERT (renameat (fd1, file1, fd2, file2) == 0);
dd59ef
+      free (file1);
dd59ef
+      free (file2);
dd59ef
+    }
dd59ef
+  dfd2 = open ("..", O_RDONLY);
dd59ef
+  ASSERT (0 <= dfd2);
dd59ef
+  ASSERT (renameat (dfd, "../" BASE "16", dfd2, BASE "17") == 0);
dd59ef
+  ASSERT (close (dfd2) == 0);
dd59ef
+
dd59ef
+  /* Now we change back to the parent directory, and set dfd to ".";
dd59ef
+     using dfd in remaining tests will expose any bugs if emulation
dd59ef
+     via /proc/self/fd doesn't check for empty names.  */
dd59ef
+  ASSERT (chdir ("..") == 0);
dd59ef
+  ASSERT (close (dfd) == 0);
dd59ef
+  dfd = open (".", O_RDONLY);
dd59ef
+  ASSERT (0 <= dfd);
dd59ef
+
dd59ef
+  ASSERT (close (creat (BASE "sub2/file", 0600)) == 0);
dd59ef
+  errno = 0;
dd59ef
+  ASSERT (renameat (dfd, BASE "sub1", dfd, BASE "sub2") == -1);
dd59ef
+  ASSERT (errno == EEXIST || errno == ENOTEMPTY);
dd59ef
+  ASSERT (unlink (BASE "sub2/file") == 0);
dd59ef
+  errno = 0;
dd59ef
+  ASSERT (renameat (dfd, BASE "sub2", dfd, BASE "sub1/.") == -1);
dd59ef
+  ASSERT (errno == EINVAL || errno == EISDIR || errno == EBUSY
dd59ef
+          || errno == ENOTEMPTY || errno == EEXIST);
dd59ef
+  errno = 0;
dd59ef
+  ASSERT (renameat (dfd, BASE "sub2/.", dfd, BASE "sub1") == -1);
dd59ef
+  ASSERT (errno == EINVAL || errno == EBUSY || errno == EEXIST);
dd59ef
+  errno = 0;
dd59ef
+  ASSERT (renameat (dfd, BASE "17", dfd, BASE "sub1") == -1);
dd59ef
+  ASSERT (errno == EISDIR);
dd59ef
+  errno = 0;
dd59ef
+  ASSERT (renameat (dfd, BASE "nosuch", dfd, BASE "18") == -1);
dd59ef
+  ASSERT (errno == ENOENT);
dd59ef
+  errno = 0;
dd59ef
+  ASSERT (renameat (dfd, "", dfd, BASE "17") == -1);
dd59ef
+  ASSERT (errno == ENOENT);
dd59ef
+  errno = 0;
dd59ef
+  ASSERT (renameat (dfd, BASE "17", dfd, "") == -1);
dd59ef
+  ASSERT (errno == ENOENT);
dd59ef
+  errno = 0;
dd59ef
+  ASSERT (renameat (dfd, BASE "sub2", dfd, BASE "17") == -1);
dd59ef
+  ASSERT (errno == ENOTDIR);
dd59ef
+  errno = 0;
dd59ef
+  ASSERT (renameat (dfd, BASE "17/", dfd, BASE "18") == -1);
dd59ef
+  ASSERT (errno == ENOTDIR);
dd59ef
+  errno = 0;
dd59ef
+  ASSERT (renameat (dfd, BASE "17", dfd, BASE "18/") == -1);
dd59ef
+  ASSERT (errno == ENOTDIR || errno == ENOENT);
dd59ef
+
dd59ef
+  /* Finally, make sure we can overwrite existing files.  */
dd59ef
+  ASSERT (close (creat (BASE "sub2/file", 0600)) == 0);
dd59ef
+  errno = 0;
dd59ef
+  ASSERT (renameat (dfd, BASE "sub2", dfd, BASE "sub1") == 0);
dd59ef
+  ASSERT (renameat (dfd, BASE "sub1/file", dfd, BASE "17") == 0);
dd59ef
+
dd59ef
+  /* Cleanup.  */
dd59ef
+  ASSERT (close (dfd) == 0);
dd59ef
+  errno = 0;
dd59ef
+  ASSERT (unlink (BASE "sub1/file") == -1);
dd59ef
+  ASSERT (errno == ENOENT);
dd59ef
+  ASSERT (unlink (BASE "17") == 0);
dd59ef
+  ASSERT (rmdir (BASE "sub1") == 0);
dd59ef
+  errno = 0;
dd59ef
+  ASSERT (rmdir (BASE "sub2") == -1);
dd59ef
+  ASSERT (errno == ENOENT);
dd59ef
+  free (cwd);
dd59ef
+
dd59ef
+  if (result)
dd59ef
+    fputs ("skipping test: symlinks not supported on this file system\n",
dd59ef
+           stderr);
dd59ef
+  return result;
dd59ef
+}
dd59ef
diff --git a/gnulib-tests/test-renameat2.c b/gnulib-tests/test-renameat2.c
dd59ef
new file mode 100644
dd59ef
index 0000000..7c250ea
dd59ef
--- /dev/null
dd59ef
+++ b/gnulib-tests/test-renameat2.c
dd59ef
@@ -0,0 +1,209 @@
dd59ef
+/* Test renameat2.
dd59ef
+   Copyright (C) 2009-2017 Free Software Foundation, Inc.
dd59ef
+
dd59ef
+   This program is free software: you can redistribute it and/or modify
dd59ef
+   it under the terms of the GNU General Public License as published by
dd59ef
+   the Free Software Foundation; either version 3 of the License, or
dd59ef
+   (at your option) any later version.
dd59ef
+
dd59ef
+   This program is distributed in the hope that it will be useful,
dd59ef
+   but WITHOUT ANY WARRANTY; without even the implied warranty of
dd59ef
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
dd59ef
+   GNU General Public License for more details.
dd59ef
+
dd59ef
+   You should have received a copy of the GNU General Public License
dd59ef
+   along with this program.  If not, see <https://www.gnu.org/licenses/>.  */
dd59ef
+
dd59ef
+/* Written by Eric Blake <ebb9@byu.net>, 2009.  */
dd59ef
+
dd59ef
+#include <config.h>
dd59ef
+
dd59ef
+#include <renameat2.h>
dd59ef
+
dd59ef
+#include <stdio.h>
dd59ef
+
dd59ef
+#include "signature.h"
dd59ef
+SIGNATURE_CHECK (renameat2, int,
dd59ef
+                 (int, char const *, int, char const *, unsigned int));
dd59ef
+
dd59ef
+#include <dirent.h>
dd59ef
+#include <fcntl.h>
dd59ef
+#include <errno.h>
dd59ef
+#include <stdbool.h>
dd59ef
+#include <stdlib.h>
dd59ef
+#include <string.h>
dd59ef
+#include <unistd.h>
dd59ef
+#include <sys/stat.h>
dd59ef
+
dd59ef
+#include "filenamecat.h"
dd59ef
+#include "ignore-value.h"
dd59ef
+#include "macros.h"
dd59ef
+
dd59ef
+#define BASE "test-renameat2.t"
dd59ef
+
dd59ef
+#include "test-rename.h"
dd59ef
+
dd59ef
+static int dfd1 = AT_FDCWD;
dd59ef
+static int dfd2 = AT_FDCWD;
dd59ef
+
dd59ef
+/* Wrapper to test renameat2 like rename.  */
dd59ef
+static int
dd59ef
+do_rename (char const *name1, char const *name2)
dd59ef
+{
dd59ef
+  return renameat2 (dfd1, name1, dfd2, name2, 0);
dd59ef
+}
dd59ef
+
dd59ef
+int
dd59ef
+main (void)
dd59ef
+{
dd59ef
+  int i;
dd59ef
+  int dfd;
dd59ef
+  char *cwd;
dd59ef
+  int result;
dd59ef
+
dd59ef
+  /* Clean up any trash from prior testsuite runs.  */
dd59ef
+  ignore_value (system ("rm -rf " BASE "*"));
dd59ef
+
dd59ef
+  /* Test behaviour for invalid file descriptors.  */
dd59ef
+  {
dd59ef
+    errno = 0;
dd59ef
+    ASSERT (renameat2 (-1, "foo", AT_FDCWD, "bar", 0) == -1);
dd59ef
+    ASSERT (errno == EBADF);
dd59ef
+  }
dd59ef
+  {
dd59ef
+    close (99);
dd59ef
+    errno = 0;
dd59ef
+    ASSERT (renameat2 (99, "foo", AT_FDCWD, "bar", 0) == -1);
dd59ef
+    ASSERT (errno == EBADF);
dd59ef
+  }
dd59ef
+  ASSERT (close (creat (BASE "oo", 0600)) == 0);
dd59ef
+  {
dd59ef
+    errno = 0;
dd59ef
+    ASSERT (renameat2 (AT_FDCWD, BASE "oo", -1, "bar", 0) == -1);
dd59ef
+    ASSERT (errno == EBADF);
dd59ef
+  }
dd59ef
+  {
dd59ef
+    errno = 0;
dd59ef
+    ASSERT (renameat2 (AT_FDCWD, BASE "oo", 99, "bar", 0) == -1);
dd59ef
+    ASSERT (errno == EBADF);
dd59ef
+  }
dd59ef
+  ASSERT (unlink (BASE "oo") == 0);
dd59ef
+
dd59ef
+  /* Test basic rename functionality, using current directory.  */
dd59ef
+  result = test_rename (do_rename, false);
dd59ef
+  dfd1 = open (".", O_RDONLY);
dd59ef
+  ASSERT (0 <= dfd1);
dd59ef
+  ASSERT (test_rename (do_rename, false) == result);
dd59ef
+  dfd2 = dfd1;
dd59ef
+  ASSERT (test_rename (do_rename, false) == result);
dd59ef
+  dfd1 = AT_FDCWD;
dd59ef
+  ASSERT (test_rename (do_rename, false) == result);
dd59ef
+  ASSERT (close (dfd2) == 0);
dd59ef
+
dd59ef
+  /* Create locations to manipulate.  */
dd59ef
+  ASSERT (mkdir (BASE "sub1", 0700) == 0);
dd59ef
+  ASSERT (mkdir (BASE "sub2", 0700) == 0);
dd59ef
+  dfd = creat (BASE "00", 0600);
dd59ef
+  ASSERT (0 <= dfd);
dd59ef
+  ASSERT (close (dfd) == 0);
dd59ef
+  cwd = getcwd (NULL, 0);
dd59ef
+  ASSERT (cwd);
dd59ef
+
dd59ef
+  dfd = open (BASE "sub1", O_RDONLY);
dd59ef
+  ASSERT (0 <= dfd);
dd59ef
+  ASSERT (chdir (BASE "sub2") == 0);
dd59ef
+
dd59ef
+  /* There are 16 possible scenarios, based on whether an fd is
dd59ef
+     AT_FDCWD or real, and whether a file is absolute or relative.
dd59ef
+
dd59ef
+     To ensure that we test all of the code paths (rather than
dd59ef
+     triggering early normalization optimizations), we use a loop to
dd59ef
+     repeatedly rename a file in the parent directory, use an fd open
dd59ef
+     on subdirectory 1, all while executing in subdirectory 2; all
dd59ef
+     relative names are thus given with a leading "../".  Finally, the
dd59ef
+     last scenario (two relative paths given, neither one AT_FDCWD)
dd59ef
+     has two paths, based on whether the two fds are equivalent, so we
dd59ef
+     do the other variant after the loop.  */
dd59ef
+  for (i = 0; i < 16; i++)
dd59ef
+    {
dd59ef
+      int fd1 = (i & 8) ? dfd : AT_FDCWD;
dd59ef
+      char *file1 = file_name_concat ((i & 4) ? ".." : cwd, BASE "xx", NULL);
dd59ef
+      int fd2 = (i & 2) ? dfd : AT_FDCWD;
dd59ef
+      char *file2 = file_name_concat ((i & 1) ? ".." : cwd, BASE "xx", NULL);
dd59ef
+
dd59ef
+      ASSERT (sprintf (strchr (file1, '\0') - 2, "%02d", i) == 2);
dd59ef
+      ASSERT (sprintf (strchr (file2, '\0') - 2, "%02d", i + 1) == 2);
dd59ef
+      ASSERT (renameat2 (fd1, file1, fd2, file2, 0) == 0);
dd59ef
+      free (file1);
dd59ef
+      free (file2);
dd59ef
+    }
dd59ef
+  dfd2 = open ("..", O_RDONLY);
dd59ef
+  ASSERT (0 <= dfd2);
dd59ef
+  ASSERT (renameat2 (dfd, "../" BASE "16", dfd2, BASE "17", 0) == 0);
dd59ef
+  ASSERT (close (dfd2) == 0);
dd59ef
+
dd59ef
+  /* Now we change back to the parent directory, and set dfd to ".";
dd59ef
+     using dfd in remaining tests will expose any bugs if emulation
dd59ef
+     via /proc/self/fd doesn't check for empty names.  */
dd59ef
+  ASSERT (chdir ("..") == 0);
dd59ef
+  ASSERT (close (dfd) == 0);
dd59ef
+  dfd = open (".", O_RDONLY);
dd59ef
+  ASSERT (0 <= dfd);
dd59ef
+
dd59ef
+  ASSERT (close (creat (BASE "sub2/file", 0600)) == 0);
dd59ef
+  errno = 0;
dd59ef
+  ASSERT (renameat2 (dfd, BASE "sub1", dfd, BASE "sub2", 0) == -1);
dd59ef
+  ASSERT (errno == EEXIST || errno == ENOTEMPTY);
dd59ef
+  ASSERT (unlink (BASE "sub2/file") == 0);
dd59ef
+  errno = 0;
dd59ef
+  ASSERT (renameat2 (dfd, BASE "sub2", dfd, BASE "sub1/.", 0) == -1);
dd59ef
+  ASSERT (errno == EINVAL || errno == EISDIR || errno == EBUSY
dd59ef
+          || errno == ENOTEMPTY || errno == EEXIST);
dd59ef
+  errno = 0;
dd59ef
+  ASSERT (renameat2 (dfd, BASE "sub2/.", dfd, BASE "sub1", 0) == -1);
dd59ef
+  ASSERT (errno == EINVAL || errno == EBUSY || errno == EEXIST);
dd59ef
+  errno = 0;
dd59ef
+  ASSERT (renameat2 (dfd, BASE "17", dfd, BASE "sub1", 0) == -1);
dd59ef
+  ASSERT (errno == EISDIR);
dd59ef
+  errno = 0;
dd59ef
+  ASSERT (renameat2 (dfd, BASE "nosuch", dfd, BASE "18", 0) == -1);
dd59ef
+  ASSERT (errno == ENOENT);
dd59ef
+  errno = 0;
dd59ef
+  ASSERT (renameat2 (dfd, "", dfd, BASE "17", 0) == -1);
dd59ef
+  ASSERT (errno == ENOENT);
dd59ef
+  errno = 0;
dd59ef
+  ASSERT (renameat2 (dfd, BASE "17", dfd, "", 0) == -1);
dd59ef
+  ASSERT (errno == ENOENT);
dd59ef
+  errno = 0;
dd59ef
+  ASSERT (renameat2 (dfd, BASE "sub2", dfd, BASE "17", 0) == -1);
dd59ef
+  ASSERT (errno == ENOTDIR);
dd59ef
+  errno = 0;
dd59ef
+  ASSERT (renameat2 (dfd, BASE "17/", dfd, BASE "18", 0) == -1);
dd59ef
+  ASSERT (errno == ENOTDIR);
dd59ef
+  errno = 0;
dd59ef
+  ASSERT (renameat2 (dfd, BASE "17", dfd, BASE "18/", 0) == -1);
dd59ef
+  ASSERT (errno == ENOTDIR || errno == ENOENT);
dd59ef
+
dd59ef
+  /* Finally, make sure we cannot overwrite existing files.  */
dd59ef
+  ASSERT (close (creat (BASE "sub2/file", 0600)) == 0);
dd59ef
+  errno = 0;
dd59ef
+  ASSERT ((renameat2 (dfd, BASE "sub2", dfd, BASE "sub1", RENAME_NOREPLACE)
dd59ef
+           == -1)
dd59ef
+          && errno == EEXIST);
dd59ef
+  ASSERT ((renameat2 (dfd, BASE "sub2/file", dfd, BASE "17", RENAME_NOREPLACE)
dd59ef
+           == -1)
dd59ef
+          && errno == EEXIST);
dd59ef
+
dd59ef
+  /* Cleanup.  */
dd59ef
+  ASSERT (close (dfd) == 0);
dd59ef
+  ASSERT (unlink (BASE "sub2/file") == 0);
dd59ef
+  ASSERT (unlink (BASE "17") == 0);
dd59ef
+  ASSERT (rmdir (BASE "sub1") == 0);
dd59ef
+  ASSERT (rmdir (BASE "sub2") == 0);
dd59ef
+  free (cwd);
dd59ef
+
dd59ef
+  if (result)
dd59ef
+    fputs ("skipping test: symlinks not supported on this file system\n",
dd59ef
+           stderr);
dd59ef
+  return result;
dd59ef
+}
dd59ef
diff --git a/lib/gnulib.mk b/lib/gnulib.mk
dd59ef
index 844791b..76729b0 100644
dd59ef
--- a/lib/gnulib.mk
dd59ef
+++ b/lib/gnulib.mk
dd59ef
@@ -21,7 +21,7 @@
dd59ef
 # the same distribution terms as the rest of that program.
dd59ef
 #
dd59ef
 # Generated by gnulib-tool.
dd59ef
-# 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
dd59ef
+# 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
dd59ef
 
dd59ef
 
dd59ef
 MOSTLYCLEANFILES += lib/core lib/*.stackdump
dd59ef
@@ -3202,6 +3202,25 @@ EXTRA_lib_libcoreutils_a_SOURCES += lib/rename.c
dd59ef
 
dd59ef
 ## end   gnulib module rename
dd59ef
 
dd59ef
+## begin gnulib module renameat
dd59ef
+
dd59ef
+
dd59ef
+EXTRA_DIST += lib/renameat.c
dd59ef
+
dd59ef
+EXTRA_lib_libcoreutils_a_SOURCES += lib/renameat.c
dd59ef
+
dd59ef
+## end   gnulib module renameat
dd59ef
+
dd59ef
+## begin gnulib module renameat2
dd59ef
+
dd59ef
+lib_libcoreutils_a_SOURCES += lib/renameat2.c
dd59ef
+
dd59ef
+EXTRA_DIST += lib/at-func2.c lib/renameat2.h
dd59ef
+
dd59ef
+EXTRA_lib_libcoreutils_a_SOURCES += lib/at-func2.c
dd59ef
+
dd59ef
+## end   gnulib module renameat2
dd59ef
+
dd59ef
 ## begin gnulib module rewinddir
dd59ef
 
dd59ef
 
dd59ef
diff --git a/lib/renameat.c b/lib/renameat.c
dd59ef
new file mode 100644
dd59ef
index 0000000..48cee4b
dd59ef
--- /dev/null
dd59ef
+++ b/lib/renameat.c
dd59ef
@@ -0,0 +1,25 @@
dd59ef
+/* Rename a file relative to open directories.
dd59ef
+   Copyright 2017 Free Software Foundation, Inc.
dd59ef
+
dd59ef
+   This program is free software: you can redistribute it and/or modify
dd59ef
+   it under the terms of the GNU General Public License as published by
dd59ef
+   the Free Software Foundation; either version 3 of the License, or
dd59ef
+   (at your option) any later version.
dd59ef
+
dd59ef
+   This program is distributed in the hope that it will be useful,
dd59ef
+   but WITHOUT ANY WARRANTY; without even the implied warranty of
dd59ef
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
dd59ef
+   GNU General Public License for more details.
dd59ef
+
dd59ef
+   You should have received a copy of the GNU General Public License
dd59ef
+   along with this program.  If not, see <https://www.gnu.org/licenses/>.  */
dd59ef
+
dd59ef
+#include <config.h>
dd59ef
+#include <stdio.h>
dd59ef
+#include "renameat2.h"
dd59ef
+
dd59ef
+int
dd59ef
+renameat (int fd1, char const *src, int fd2, char const *dst)
dd59ef
+{
dd59ef
+  return renameat2 (fd1, src, fd2, dst, 0);
dd59ef
+}
dd59ef
diff --git a/lib/renameat2.c b/lib/renameat2.c
dd59ef
new file mode 100644
dd59ef
index 0000000..26cde86
dd59ef
--- /dev/null
dd59ef
+++ b/lib/renameat2.c
dd59ef
@@ -0,0 +1,227 @@
dd59ef
+/* Rename a file relative to open directories.
dd59ef
+   Copyright (C) 2009-2017 Free Software Foundation, Inc.
dd59ef
+
dd59ef
+   This program is free software: you can redistribute it and/or modify
dd59ef
+   it under the terms of the GNU General Public License as published by
dd59ef
+   the Free Software Foundation; either version 3 of the License, or
dd59ef
+   (at your option) any later version.
dd59ef
+
dd59ef
+   This program is distributed in the hope that it will be useful,
dd59ef
+   but WITHOUT ANY WARRANTY; without even the implied warranty of
dd59ef
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
dd59ef
+   GNU General Public License for more details.
dd59ef
+
dd59ef
+   You should have received a copy of the GNU General Public License
dd59ef
+   along with this program.  If not, see <https://www.gnu.org/licenses/>.  */
dd59ef
+
dd59ef
+/* written by Eric Blake and Paul Eggert */
dd59ef
+
dd59ef
+#include <config.h>
dd59ef
+
dd59ef
+#include "renameat2.h"
dd59ef
+
dd59ef
+#include <errno.h>
dd59ef
+#include <stdio.h>
dd59ef
+#include <sys/stat.h>
dd59ef
+#include <unistd.h>
dd59ef
+
dd59ef
+#ifdef __linux__
dd59ef
+# include <sys/syscall.h>
dd59ef
+#endif
dd59ef
+
dd59ef
+static int
dd59ef
+errno_fail (int e)
dd59ef
+{
dd59ef
+  errno = e;
dd59ef
+  return -1;
dd59ef
+}
dd59ef
+
dd59ef
+#if HAVE_RENAMEAT
dd59ef
+
dd59ef
+# include <stdbool.h>
dd59ef
+# include <stdlib.h>
dd59ef
+# include <string.h>
dd59ef
+
dd59ef
+# include "dirname.h"
dd59ef
+# include "openat.h"
dd59ef
+
dd59ef
+#else
dd59ef
+# include "openat-priv.h"
dd59ef
+
dd59ef
+static int
dd59ef
+rename_noreplace (char const *src, char const *dst)
dd59ef
+{
dd59ef
+  /* This has a race between the call to lstat and the call to rename.  */
dd59ef
+  struct stat st;
dd59ef
+  return (lstat (dst, &st) == 0 || errno == EOVERFLOW ? errno_fail (EEXIST)
dd59ef
+          : errno == ENOENT ? rename (src, dst)
dd59ef
+          : -1);
dd59ef
+}
dd59ef
+#endif
dd59ef
+
dd59ef
+#undef renameat
dd59ef
+
dd59ef
+/* Rename FILE1, in the directory open on descriptor FD1, to FILE2, in
dd59ef
+   the directory open on descriptor FD2.  If possible, do it without
dd59ef
+   changing the working directory.  Otherwise, resort to using
dd59ef
+   save_cwd/fchdir, then rename/restore_cwd.  If either the save_cwd or
dd59ef
+   the restore_cwd fails, then give a diagnostic and exit nonzero.
dd59ef
+
dd59ef
+   Obey FLAGS when doing the renaming.  If FLAGS is zero, this
dd59ef
+   function is equivalent to renameat (FD1, SRC, FD2, DST).  */
dd59ef
+
dd59ef
+int
dd59ef
+renameat2 (int fd1, char const *src, int fd2, char const *dst,
dd59ef
+           unsigned int flags)
dd59ef
+{
dd59ef
+  int ret_val = -1;
dd59ef
+  int err = EINVAL;
dd59ef
+
dd59ef
+#ifdef SYS_renameat2
dd59ef
+  ret_val = syscall (SYS_renameat2, fd1, src, fd2, dst, flags);
dd59ef
+  err = errno;
dd59ef
+#elif defined RENAME_EXCL
dd59ef
+  if (! (flags & ~(RENAME_EXCHANGE | RENAME_NOREPLACE)))
dd59ef
+    {
dd59ef
+      ret_val = renameatx_np (fd1, src, fd2, dst,
dd59ef
+                             ((flags & RENAME_EXCHANGE ? RENAME_SWAP : 0)
dd59ef
+                              | (flags & RENAME_NOREPLACE ? RENAME_EXCL : 0)));
dd59ef
+      err = errno;
dd59ef
+    }
dd59ef
+#endif
dd59ef
+
dd59ef
+  if (! (ret_val < 0 && (err == EINVAL || err == ENOSYS || err == ENOTSUP)))
dd59ef
+    return ret_val;
dd59ef
+
dd59ef
+#if HAVE_RENAMEAT
dd59ef
+  {
dd59ef
+  size_t src_len;
dd59ef
+  size_t dst_len;
dd59ef
+  char *src_temp = (char *) src;
dd59ef
+  char *dst_temp = (char *) dst;
dd59ef
+  bool src_slash;
dd59ef
+  bool dst_slash;
dd59ef
+  int rename_errno = ENOTDIR;
dd59ef
+  struct stat src_st;
dd59ef
+  struct stat dst_st;
dd59ef
+  bool dst_found_nonexistent = false;
dd59ef
+
dd59ef
+  if (flags != 0)
dd59ef
+    {
dd59ef
+      /* RENAME_NOREPLACE is the only flag currently supported.  */
dd59ef
+      if (flags & ~RENAME_NOREPLACE)
dd59ef
+        return errno_fail (ENOTSUP);
dd59ef
+      else
dd59ef
+        {
dd59ef
+          /* This has a race between the call to lstatat and the calls to
dd59ef
+             renameat below.  */
dd59ef
+          if (lstatat (fd2, dst, &dst_st) == 0 || errno == EOVERFLOW)
dd59ef
+            return errno_fail (EEXIST);
dd59ef
+          if (errno != ENOENT)
dd59ef
+            return -1;
dd59ef
+          dst_found_nonexistent = true;
dd59ef
+        }
dd59ef
+    }
dd59ef
+
dd59ef
+  /* Let strace see any ENOENT failure.  */
dd59ef
+  src_len = strlen (src);
dd59ef
+  dst_len = strlen (dst);
dd59ef
+  if (!src_len || !dst_len)
dd59ef
+    return renameat (fd1, src, fd2, dst);
dd59ef
+
dd59ef
+  src_slash = src[src_len - 1] == '/';
dd59ef
+  dst_slash = dst[dst_len - 1] == '/';
dd59ef
+  if (!src_slash && !dst_slash)
dd59ef
+    return renameat (fd1, src, fd2, dst);
dd59ef
+
dd59ef
+  /* Presence of a trailing slash requires directory semantics.  If
dd59ef
+     the source does not exist, or if the destination cannot be turned
dd59ef
+     into a directory, give up now.  Otherwise, strip trailing slashes
dd59ef
+     before calling rename.  */
dd59ef
+  if (lstatat (fd1, src, &src_st))
dd59ef
+    return -1;
dd59ef
+  if (dst_found_nonexistent)
dd59ef
+    {
dd59ef
+      if (!S_ISDIR (src_st.st_mode))
dd59ef
+        return errno_fail (ENOENT);
dd59ef
+    }
dd59ef
+  else if (lstatat (fd2, dst, &dst_st))
dd59ef
+    {
dd59ef
+      if (errno != ENOENT || !S_ISDIR (src_st.st_mode))
dd59ef
+        return -1;
dd59ef
+    }
dd59ef
+  else if (!S_ISDIR (dst_st.st_mode))
dd59ef
+    return errno_fail (ENOTDIR);
dd59ef
+  else if (!S_ISDIR (src_st.st_mode))
dd59ef
+    return errno_fail (EISDIR);
dd59ef
+
dd59ef
+# if RENAME_TRAILING_SLASH_SOURCE_BUG
dd59ef
+  /* See the lengthy comment in rename.c why Solaris 9 is forced to
dd59ef
+     GNU behavior, while Solaris 10 is left with POSIX behavior,
dd59ef
+     regarding symlinks with trailing slash.  */
dd59ef
+  ret_val = -1;
dd59ef
+  if (src_slash)
dd59ef
+    {
dd59ef
+      src_temp = strdup (src);
dd59ef
+      if (!src_temp)
dd59ef
+        {
dd59ef
+          /* Rather than rely on strdup-posix, we set errno ourselves.  */
dd59ef
+          rename_errno = ENOMEM;
dd59ef
+          goto out;
dd59ef
+        }
dd59ef
+      strip_trailing_slashes (src_temp);
dd59ef
+      if (lstatat (fd1, src_temp, &src_st))
dd59ef
+        {
dd59ef
+          rename_errno = errno;
dd59ef
+          goto out;
dd59ef
+        }
dd59ef
+      if (S_ISLNK (src_st.st_mode))
dd59ef
+        goto out;
dd59ef
+    }
dd59ef
+  if (dst_slash)
dd59ef
+    {
dd59ef
+      dst_temp = strdup (dst);
dd59ef
+      if (!dst_temp)
dd59ef
+        {
dd59ef
+          rename_errno = ENOMEM;
dd59ef
+          goto out;
dd59ef
+        }
dd59ef
+      strip_trailing_slashes (dst_temp);
dd59ef
+      if (lstatat (fd2, dst_temp, &dst_st))
dd59ef
+        {
dd59ef
+          if (errno != ENOENT)
dd59ef
+            {
dd59ef
+              rename_errno = errno;
dd59ef
+              goto out;
dd59ef
+            }
dd59ef
+        }
dd59ef
+      else if (S_ISLNK (dst_st.st_mode))
dd59ef
+        goto out;
dd59ef
+    }
dd59ef
+# endif /* RENAME_TRAILING_SLASH_SOURCE_BUG */
dd59ef
+
dd59ef
+  /* renameat does not honor trailing / on Solaris 10.  Solve it in a
dd59ef
+     similar manner to rename.  No need to worry about bugs not present
dd59ef
+     on Solaris, since all other systems either lack renameat or honor
dd59ef
+     trailing slash correctly.  */
dd59ef
+
dd59ef
+  ret_val = renameat (fd1, src_temp, fd2, dst_temp);
dd59ef
+  rename_errno = errno;
dd59ef
+  goto out;
dd59ef
+ out:
dd59ef
+  if (src_temp != src)
dd59ef
+    free (src_temp);
dd59ef
+  if (dst_temp != dst)
dd59ef
+    free (dst_temp);
dd59ef
+  errno = rename_errno;
dd59ef
+  return ret_val;
dd59ef
+  }
dd59ef
+#else /* !HAVE_RENAMEAT */
dd59ef
+
dd59ef
+  /* RENAME_NOREPLACE is the only flag currently supported.  */
dd59ef
+  if (flags & ~RENAME_NOREPLACE)
dd59ef
+    return errno_fail (ENOTSUP);
dd59ef
+  return at_func2 (fd1, src, fd2, dst, flags ? rename_noreplace : rename);
dd59ef
+
dd59ef
+#endif /* !HAVE_RENAMEAT */
dd59ef
+}
dd59ef
diff --git a/lib/renameat2.h b/lib/renameat2.h
dd59ef
new file mode 100644
dd59ef
index 0000000..179210f
dd59ef
--- /dev/null
dd59ef
+++ b/lib/renameat2.h
dd59ef
@@ -0,0 +1,30 @@
dd59ef
+/* Rename a file relative to open directories.
dd59ef
+   Copyright 2017 Free Software Foundation, Inc.
dd59ef
+
dd59ef
+   This program is free software: you can redistribute it and/or modify
dd59ef
+   it under the terms of the GNU General Public License as published by
dd59ef
+   the Free Software Foundation; either version 3 of the License, or
dd59ef
+   (at your option) any later version.
dd59ef
+
dd59ef
+   This program is distributed in the hope that it will be useful,
dd59ef
+   but WITHOUT ANY WARRANTY; without even the implied warranty of
dd59ef
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
dd59ef
+   GNU General Public License for more details.
dd59ef
+
dd59ef
+   You should have received a copy of the GNU General Public License
dd59ef
+   along with this program.  If not, see <https://www.gnu.org/licenses/>.  */
dd59ef
+
dd59ef
+/* written by Paul Eggert */
dd59ef
+
dd59ef
+/* Get RENAME_* macros from linux/fs.h if present, otherwise supply
dd59ef
+   the traditional Linux values.  */
dd59ef
+#if HAVE_LINUX_FS_H
dd59ef
+# include <linux/fs.h>
dd59ef
+#endif
dd59ef
+#ifndef RENAME_NOREPLACE
dd59ef
+# define RENAME_NOREPLACE  (1 << 0)
dd59ef
+# define RENAME_EXCHANGE   (1 << 1)
dd59ef
+# define RENAME_WHITEOUT   (1 << 2)
dd59ef
+#endif
dd59ef
+
dd59ef
+extern int renameat2 (int, char const *, int, char const *, unsigned int);
dd59ef
diff --git a/m4/gnulib-comp.m4 b/m4/gnulib-comp.m4
dd59ef
index 4ef3c43..309e308 100644
dd59ef
--- a/m4/gnulib-comp.m4
dd59ef
+++ b/m4/gnulib-comp.m4
dd59ef
@@ -547,6 +547,10 @@ AC_DEFUN([gl_EARLY],
dd59ef
   # Code from module remove-tests:
dd59ef
   # Code from module rename:
dd59ef
   # Code from module rename-tests:
dd59ef
+  # Code from module renameat:
dd59ef
+  # Code from module renameat-tests:
dd59ef
+  # Code from module renameat2:
dd59ef
+  # Code from module renameat2-tests:
dd59ef
   # Code from module rewinddir:
dd59ef
   # Code from module rmdir:
dd59ef
   # Code from module rmdir-tests:
dd59ef
@@ -1696,6 +1700,18 @@ AC_DEFUN([gl_INIT],
dd59ef
     AC_LIBOBJ([rename])
dd59ef
   fi
dd59ef
   gl_STDIO_MODULE_INDICATOR([rename])
dd59ef
+  gl_FUNC_RENAMEAT
dd59ef
+  if test $HAVE_RENAMEAT = 0 || test $REPLACE_RENAMEAT = 1; then
dd59ef
+    AC_LIBOBJ([renameat])
dd59ef
+  fi
dd59ef
+  if test $HAVE_RENAMEAT = 0; then
dd59ef
+    AC_LIBOBJ([at-func2])
dd59ef
+  fi
dd59ef
+  gl_STDIO_MODULE_INDICATOR([renameat])
dd59ef
+  gl_FUNC_RENAMEAT
dd59ef
+  if test $HAVE_RENAMEAT = 0; then
dd59ef
+    AC_LIBOBJ([at-func2])
dd59ef
+  fi
dd59ef
   gl_FUNC_REWINDDIR
dd59ef
   if test $HAVE_REWINDDIR = 0; then
dd59ef
     AC_LIBOBJ([rewinddir])
dd59ef
@@ -2868,6 +2884,9 @@ AC_DEFUN([gl_FILE_LIST], [
dd59ef
   lib/regexec.c
dd59ef
   lib/remove.c
dd59ef
   lib/rename.c
dd59ef
+  lib/renameat.c
dd59ef
+  lib/renameat2.c
dd59ef
+  lib/renameat2.h
dd59ef
   lib/rewinddir.c
dd59ef
   lib/rmdir.c
dd59ef
   lib/root-dev-ino.c
dd59ef
@@ -3372,6 +3391,7 @@ AC_DEFUN([gl_FILE_LIST], [
dd59ef
   m4/regex.m4
dd59ef
   m4/remove.m4
dd59ef
   m4/rename.m4
dd59ef
+  m4/renameat.m4
dd59ef
   m4/rewinddir.m4
dd59ef
   m4/rmdir.m4
dd59ef
   m4/rpmatch.m4
dd59ef
@@ -3794,6 +3814,8 @@ AC_DEFUN([gl_FILE_LIST], [
dd59ef
   tests/test-remove.c
dd59ef
   tests/test-rename.c
dd59ef
   tests/test-rename.h
dd59ef
+  tests/test-renameat.c
dd59ef
+  tests/test-renameat2.c
dd59ef
   tests/test-rmdir.c
dd59ef
   tests/test-rmdir.h
dd59ef
   tests/test-sameacls.c
dd59ef
diff --git a/m4/renameat.m4 b/m4/renameat.m4
dd59ef
new file mode 100644
dd59ef
index 0000000..1b97774
dd59ef
--- /dev/null
dd59ef
+++ b/m4/renameat.m4
dd59ef
@@ -0,0 +1,25 @@
dd59ef
+# serial 3
dd59ef
+# See if we need to provide renameat replacement.
dd59ef
+
dd59ef
+dnl Copyright (C) 2009-2017 Free Software Foundation, Inc.
dd59ef
+dnl This file is free software; the Free Software Foundation
dd59ef
+dnl gives unlimited permission to copy and/or distribute it,
dd59ef
+dnl with or without modifications, as long as this notice is preserved.
dd59ef
+
dd59ef
+# Written by Eric Blake.
dd59ef
+
dd59ef
+AC_DEFUN([gl_FUNC_RENAMEAT],
dd59ef
+[
dd59ef
+  AC_REQUIRE([gl_FUNC_OPENAT])
dd59ef
+  AC_REQUIRE([gl_FUNC_RENAME])
dd59ef
+  AC_REQUIRE([gl_STDIO_H_DEFAULTS])
dd59ef
+  AC_REQUIRE([gl_USE_SYSTEM_EXTENSIONS])
dd59ef
+  AC_CHECK_HEADERS([linux/fs.h])
dd59ef
+  AC_CHECK_FUNCS_ONCE([renameat])
dd59ef
+  if test $ac_cv_func_renameat = no; then
dd59ef
+    HAVE_RENAMEAT=0
dd59ef
+  elif test $REPLACE_RENAME = 1; then
dd59ef
+    dnl Solaris 9 and 10 have the same bugs in renameat as in rename.
dd59ef
+    REPLACE_RENAMEAT=1
dd59ef
+  fi
dd59ef
+])
dd59ef
diff --git a/src/copy.c b/src/copy.c
dd59ef
index 2a804945e..be4e357a8 100644
dd59ef
--- a/src/copy.c
dd59ef
+++ b/src/copy.c
dd59ef
@@ -51,6 +51,7 @@
dd59ef
 #include "ignore-value.h"
dd59ef
 #include "ioblksize.h"
dd59ef
 #include "quote.h"
dd59ef
+#include "renameat2.h"
dd59ef
 #include "root-uid.h"
dd59ef
 #include "same.h"
dd59ef
 #include "savedir.h"
dd59ef
@@ -2093,8 +2094,9 @@ copy_internal (char const *src_name, char const *dst_name,
dd59ef
 
dd59ef
   /* If the source is a directory, we don't always create the destination
dd59ef
      directory.  So --verbose should not announce anything until we're
dd59ef
-     sure we'll create a directory. */
dd59ef
-  if (x->verbose && !S_ISDIR (src_mode))
dd59ef
+     sure we'll create a directory.  In move mode we delay the diagnostic
dd59ef
+     message until we know whether renameat2() has actually succeeded. */
dd59ef
+  if (x->verbose && !S_ISDIR (src_mode) && !x->move_mode)
dd59ef
     emit_verbose (src_name, dst_name, backup_succeeded ? dst_backup : NULL);
dd59ef
 
dd59ef
   /* Associate the destination file name with the source device and inode
dd59ef
@@ -2196,9 +2198,14 @@ copy_internal (char const *src_name, char const *dst_name,
dd59ef
 
dd59ef
   if (x->move_mode)
dd59ef
     {
dd59ef
-      if (rename (src_name, dst_name) == 0)
dd59ef
+      int flags = 0;
dd59ef
+      if (x->interactive == I_ALWAYS_NO)
dd59ef
+        /* do not replace DST_NAME if it was created since our last check */
dd59ef
+        flags = RENAME_NOREPLACE;
dd59ef
+
dd59ef
+      if (renameat2 (AT_FDCWD, src_name, AT_FDCWD, dst_name, flags) == 0)
dd59ef
         {
dd59ef
-          if (x->verbose && S_ISDIR (src_mode))
dd59ef
+          if (x->verbose)
dd59ef
             emit_verbose (src_name, dst_name,
dd59ef
                           backup_succeeded ? dst_backup : NULL);
dd59ef
 
dd59ef
@@ -2226,6 +2233,15 @@ copy_internal (char const *src_name, char const *dst_name,
dd59ef
           return true;
dd59ef
         }
dd59ef
 
dd59ef
+      if ((flags & RENAME_NOREPLACE) && (errno == EEXIST))
dd59ef
+        {
dd59ef
+          /* Pretend the rename succeeded, so the caller (mv)
dd59ef
+             doesn't end up removing the source file.  */
dd59ef
+          if (rename_succeeded)
dd59ef
+            *rename_succeeded = true;
dd59ef
+          return true;
dd59ef
+        }
dd59ef
+
dd59ef
       /* FIXME: someday, consider what to do when moving a directory into
dd59ef
          itself but when source and destination are on different devices.  */
dd59ef
 
dd59ef
@@ -2301,6 +2317,9 @@ copy_internal (char const *src_name, char const *dst_name,
dd59ef
           return false;
dd59ef
         }
dd59ef
 
dd59ef
+      if (x->verbose && !S_ISDIR (src_mode))
dd59ef
+        emit_verbose (src_name, dst_name, backup_succeeded ? dst_backup : NULL);
dd59ef
+
dd59ef
       new_dst = true;
dd59ef
     }
dd59ef
 
dd59ef
-- 
dd59ef
2.13.6
dd59ef