[PATCH v4 8/9] loop:refactor: extract subfunction set_loop_dev()

Xiaoming Ni nixiaoming at huawei.com
Mon Nov 21 13:58:18 UTC 2022


Step 8 of micro-refactoring the set_loop():
    Extract subfunction open_file() from set_loop_dev()

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

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

diff --git a/libbb/loop.c b/libbb/loop.c
index ec4fcf883..03b73e658 100644
--- a/libbb/loop.c
+++ b/libbb/loop.c
@@ -203,6 +203,26 @@ static int do_stat_and_mknod(const char *dev, const char *device, int i)
 	return -1;
 }
 
+static int set_loop_dev(const char *dev, int *mode, int ffd, const bb_loop_info *loopinfo)
+{
+	int rc;
+	/* Open the sucker and check its loopiness */
+	int lfd = open(dev, *mode);
+	if (lfd < 0 && errno == EROFS) {
+		*mode = O_RDONLY;
+		lfd = open(dev, *mode);
+	}
+	if (lfd < 0) {
+		return lfd;
+	}
+	rc = set_loop_info(ffd, lfd, loopinfo);
+	if (rc == lfd) {
+		return lfd;
+	}
+	close(lfd);
+	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
@@ -213,7 +233,7 @@ int FAST_FUNC set_loop(char **device, const char *file, unsigned long long offse
 {
 	char dev[LOOP_NAMESIZE];
 	char *try;
-	int i, lfd, ffd, mode, rc;
+	int i, ffd, mode, rc;
 	bb_loop_info loopinfo;
 
 	ffd = open_file(file, flags, &mode);
@@ -244,30 +264,19 @@ int FAST_FUNC set_loop(char **device, const char *file, unsigned long long offse
 			break;
 		}
  open_lfd:
-		/* Open the sucker and check its loopiness */
-		lfd = rc = open(try, mode);
-		if (lfd < 0 && errno == EROFS) {
-			mode = O_RDONLY;
-			lfd = rc = open(try, mode);
-		}
-		if (lfd < 0) {
+		rc = set_loop_dev(try, &mode, ffd, &loopinfo);
+		if (rc == -1) {
 			if (errno == ENXIO) {
 				/* Happens if loop module is not loaded */
 				/* rc is -1; */
 				break;
 			}
-			goto try_next_loopN;
-		}
-		rc = set_loop_info(ffd, lfd, &loopinfo);
-		if (rc == lfd) {
+		} else {
 			/* SUCCESS! */
 			if (!*device)
 				*device = xstrdup(try);
 			break;
 		}
-		close(lfd);
- try_next_loopN:
-		rc = -1;
 		if (*device) /* was looking for a particular "/dev/loopN"? */
 			break; /* yes, do not try other names */
 	} /* for() */
-- 
2.27.0



More information about the busybox mailing list