[PATCH v3 7/9] loop:refactor: Extract subfunction do_stat_and_mknod()

Xiaoming Ni nixiaoming at huawei.com
Mon Nov 21 02:46:37 UTC 2022


Step 7 of micro-refactoring the set_loop():
	Extract subfunction do_stat_and_mknod()

function                                             old     new   delta
set_loop                                             720     700     -20
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 0/1 up/down: 0/-20)             Total: -20 bytes

Signed-off-by: Xiaoming Ni <nixiaoming at huawei.com>
---
 libbb/loop.c | 38 ++++++++++++++++++++++++--------------
 1 file changed, 24 insertions(+), 14 deletions(-)

diff --git a/libbb/loop.c b/libbb/loop.c
index 0b1336a02..8b207b929 100644
--- a/libbb/loop.c
+++ b/libbb/loop.c
@@ -180,6 +180,27 @@ static void init_bb_loop_info(bb_loop_info *loopinfo, const char *file,
 	loopinfo->lo_flags = (flags & ~BB_LO_FLAGS_READ_ONLY);
 }
 
+static int do_stat_and_mknod(const char *dev, const char *device, int i)
+{
+	struct stat statbuf;
+
+	IF_FEATURE_MOUNT_LOOP_CREATE(errno = 0;)
+	if (stat(dev, &statbuf) == 0 && S_ISBLK(statbuf.st_mode))
+		return 0;
+	if (ENABLE_FEATURE_MOUNT_LOOP_CREATE
+			&& errno == ENOENT
+			&& (!device)
+	   ) {
+		/* Node doesn't exist, try to create it */
+		if (mknod(dev, S_IFBLK|0644, makedev(7, i)) == 0) {
+			return 0;
+		}
+	}
+	/* Ran out of block devices, return failure */
+	return -1;
+}
+
+
 /* Returns opened fd to the loop device, <0 on error.
  * *device is loop device to use, or if *device==NULL finds a loop device to
  * mount it on and sets *device to a strdup of that loop device name.
@@ -189,7 +210,6 @@ int FAST_FUNC set_loop(char **device, const char *file, unsigned long long offse
 {
 	char dev[LOOP_NAMESIZE];
 	char *try;
-	struct stat statbuf;
 	int i, lfd, ffd, mode, rc;
 	bb_loop_info loopinfo;
 
@@ -216,18 +236,8 @@ int FAST_FUNC set_loop(char **device, const char *file, unsigned long long offse
 			}
 		}
 
-		IF_FEATURE_MOUNT_LOOP_CREATE(errno = 0;)
-		if (stat(try, &statbuf) != 0 || !S_ISBLK(statbuf.st_mode)) {
-			if (ENABLE_FEATURE_MOUNT_LOOP_CREATE
-			 && errno == ENOENT
-			 && (!*device)
-			) {
-				/* Node doesn't exist, try to create it */
-				if (mknod(dev, S_IFBLK|0644, makedev(7, i)) == 0)
-					goto open_lfd;
-			}
-			/* Ran out of block devices, return failure */
-			rc = -1;
+		rc = do_stat_and_mknod(try, *device, i);
+		if (rc == -1) {
 			break;
 		}
  open_lfd:
@@ -249,7 +259,7 @@ int FAST_FUNC set_loop(char **device, const char *file, unsigned long long offse
 		if (rc == lfd) {
 			/* SUCCESS! */
 			if (!*device)
-				*device = xstrdup(dev);
+				*device = xstrdup(try);
 			break;
 		}
 		close(lfd);
-- 
2.27.0



More information about the busybox mailing list