-char *
-getwd(np)
- char *np;
-{
- dev_t rdev;
- ino_t rino;
-
- off = -1;
- *np++ = '/';
- name = np;
- stat("/", &d);
- rdev = d.st_dev;
- rino = d.st_ino;
- for (;;) {
- stat(dot, &d);
- if (d.st_ino==rino && d.st_dev==rdev)
- goto done;
- if ((file = opendir(dotdot)) == NULL)
- prexit("getwd: cannot open ..");
- fstat(file->dd_fd, &dd);
- if (chdir(dotdot) < 0)
- prexit("getwd: cannot chdir to ..");
- if (d.st_dev == dd.st_dev) {
- if(d.st_ino == dd.st_ino)
- goto done;
- do
- if ((dir = readdir(file)) == NULL)
- prexit("getwd: read error in ..");
- while (dir->d_ino != d.st_ino);
+ /* Save root values, so know when to stop. */
+ if (stat("/", &s))
+ goto err;
+ root_dev = s.st_dev;
+ root_ino = s.st_ino;
+
+ errno = 0; /* XXX readdir has no error return. */
+
+ for (first = 1;; first = 0) {
+ /* Stat the current level. */
+ if (lstat(up, &s))
+ goto err;
+
+ /* Save current node values. */
+ ino = s.st_ino;
+ dev = s.st_dev;
+
+ /* Check for reaching root. */
+ if (root_dev == dev && root_ino == ino) {
+ *--bpt = '/';
+ /*
+ * It's unclear that it's a requirement to copy the
+ * path to the beginning of the buffer, but it's always
+ * been that way and stuff would probably break.
+ */
+ (void)bcopy(bpt, pt, ept - bpt);
+ free(up);
+ return(pt);
+ }
+
+ /*
+ * Build pointer to the parent directory, allocating memory
+ * as necessary. Max length is 3 for "../", the largest
+ * possible component name, plus a trailing NULL.
+ */
+ if (bup + 3 + MAXNAMLEN + 1 >= eup) {
+ if (!(up = (char *)realloc(up, upsize *= 2)))
+ goto err;
+ eup = up + upsize;
+ }
+ *bup++ = '.';
+ *bup++ = '.';
+ *bup = '\0';
+
+ /* Open and stat parent directory. */
+ if (!(dir = opendir(up)) || fstat(dirfd(dir), &s))
+ goto err;
+
+ /* Add trailing slash for next directory. */
+ *bup++ = '/';
+
+ /*
+ * If it's a mount point, have to stat each element because
+ * the inode number in the directory is for the entry in the
+ * parent directory, not the inode number of the mounted file.
+ */
+ save_errno = 0;
+ if (s.st_dev == dev) {
+ for (;;) {
+ if (!(dp = readdir(dir)))
+ goto notfound;
+ if (dp->d_fileno == ino)
+ break;
+ }