+static char const dot = '.';
+
+/* True if the cached directory for calls to openat etc. is DIR, with
+ length DIRLEN. DIR need not be null-terminated. DIRLEN must be
+ less than MAX_PATH_LEN. */
+static bool
+atdir_eq (char const *dir, ptrdiff_t dirlen)
+{
+ if (dirlen == 0)
+ dir = &dot, dirlen = 1;
+ return memcmp (dfname, dir, dirlen) == 0 && !dfname[dirlen];
+}
+
+/* Set the directory used for calls to openat etc. to be the directory
+ DIR, with length DIRLEN. DIR need not be null-terminated.
+ DIRLEN must be less than MAX_PATH_LEN. Return a file descriptor for
+ the directory, or -1 if one could not be obtained. */
+static int
+atdir_set (char const *dir, ptrdiff_t dirlen)
+{
+ /* Don't bother opening directories on older systems that
+ lack openat and unlinkat. It's not worth the porting hassle. */
+ #if HAVE_OPENAT && HAVE_UNLINKAT
+ enum { try_opening_directories = true };
+ #else
+ enum { try_opening_directories = false };
+ #endif
+
+ if (try_opening_directories && ! atdir_eq (dir, dirlen))
+ {
+ if (0 <= dfd)
+ close (dfd);
+ if (dirlen == 0)
+ dir = &dot, dirlen = 1;
+ memcpy (dfname, dir, dirlen);
+ dfname[dirlen] = '\0';
+ dfd = open (dfname, O_SEARCH | O_DIRECTORY);
+ }
+
+ return dfd;
+}
+