I started to convert this to openat() when I realized it should just use devname() instead. This should never fail since it operates on a mounted file system (and devname() will fall back to trawling /dev anyway if it needs to).
I also changed a QUAD_MAX to INT64_T since daddr_t is int64_t. - todd Index: sbin/badsect/badsect.c =================================================================== RCS file: /cvs/src/sbin/badsect/badsect.c,v retrieving revision 1.27 diff -u -p -u -r1.27 badsect.c --- sbin/badsect/badsect.c 12 Nov 2015 22:33:07 -0000 1.27 +++ sbin/badsect/badsect.c 12 Jun 2017 20:48:30 -0000 @@ -47,8 +47,10 @@ #include <ufs/ufs/dinode.h> #include <dirent.h> +#include <errno.h> #include <fcntl.h> #include <paths.h> +#include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> @@ -77,10 +79,9 @@ int main(int argc, char *argv[]) { daddr_t number; - struct stat stbuf, devstat; - struct dirent *dp; - DIR *dirp; - char name[BUFSIZ]; + struct stat stbuf; + char name[PATH_MAX]; + char *bdev; int len; if (argc < 3) { @@ -90,20 +91,10 @@ main(int argc, char *argv[]) if (chdir(argv[1]) < 0 || stat(".", &stbuf) < 0) err(2, "%s", argv[1]); - strlcpy(name, _PATH_DEV, sizeof name); - len = strlen(name); - if ((dirp = opendir(name)) == NULL) - err(3, "%s", name); - - while ((dp = readdir(dirp)) != NULL) { - strlcpy(&name[len], dp->d_name, sizeof name - len); - if (stat(name, &devstat) < 0) - err(4, "%s", name); - - if (stbuf.st_dev == devstat.st_rdev && - S_ISBLK(devstat.st_mode)) - break; - } + bdev = devname(stbuf.st_dev, S_IFBLK); + if (strcmp(bdev, "??") == 0) + err(5, "Cannot find dev 0%o corresponding to %s", + stbuf.st_rdev, argv[1]); /* * We've found the block device, but since the filesystem @@ -112,20 +103,16 @@ main(int argc, char *argv[]) * /dev that doesn't follow standard naming conventions, but * it's all we've got. */ - name[len] = 'r'; - strlcpy(&name[len+1], dp->d_name, sizeof name - (len+1)); - closedir(dirp); - if (dp == NULL) - err(5, "Cannot find dev 0%o corresponding to %s", - stbuf.st_rdev, argv[1]); - + len = snprintf(name, sizeof(name), "%sr%s", _PATH_DEV, bdev); + if (len >= sizeof(name)) + errc(6, ENAMETOOLONG, "%sr%s", _PATH_DEV, bdev); if ((fsi = open(name, O_RDONLY)) < 0) - err(6, "%s", name); + err(7, "%s", name); fs = &sblock; rdfs(SBOFF, SBSIZE, (char *)fs); for (argc -= 2, argv += 2; argc > 0; argc--, argv++) { - number = strtonum(*argv, 0, QUAD_MAX, NULL); + number = strtonum(*argv, 0, INT64_MAX, NULL); if (chkuse(number, 1)) continue; if (mknod(*argv, S_IFMT|S_IRUSR|S_IWUSR,