[PATCH] erofs-utils: lib: avoid trailing '\n' in erofs_nbd_get_identifier()

Gao Xiang hsiangkao at linux.alibaba.com
Fri Sep 5 13:39:55 AEST 2025


The trailing '\n' shouldn't be part of backend.

Fixes: 5d3efc9babf3 ("erofs-utils: mount: enable autoclear for NBD devices")
Cc: Chengyu Zhu <hudson at cyzhu.com>
Signed-off-by: Gao Xiang <hsiangkao at linux.alibaba.com>
---
 lib/backends/nbd.c | 21 +++++++++++++++------
 mount/main.c       | 20 +++++---------------
 2 files changed, 20 insertions(+), 21 deletions(-)

diff --git a/lib/backends/nbd.c b/lib/backends/nbd.c
index b9535dc..2e54814 100644
--- a/lib/backends/nbd.c
+++ b/lib/backends/nbd.c
@@ -183,15 +183,24 @@ char *erofs_nbd_get_identifier(int nbdnum)
 
 	(void)snprintf(s, sizeof(s), "/sys/block/nbd%d/backend", nbdnum);
 	f = fopen(s, "r");
-	if (!f)
+	if (!f) {
+		if (errno == ENOENT)
+			return NULL;
 		return ERR_PTR(-errno);
-
-	if (getline(&line, &n, f) < 0)
+	}
+	err = getline(&line, &n, f);
+	if (err < 0)
 		err = -errno;
-	else
-		err = 0;
 	fclose(f);
-	return err ? ERR_PTR(err) : line;
+	if (err < 0)
+		return ERR_PTR(err);
+	if (!err) {
+		free(line);
+		return NULL;
+	}
+	if (line[err - 1] == '\n')
+		line[err - 1] = '\0';
+	return line;
 }
 
 int erofs_nbd_get_index_from_minor(int minor)
diff --git a/mount/main.c b/mount/main.c
index 149bb53..2826dac 100644
--- a/mount/main.c
+++ b/mount/main.c
@@ -356,10 +356,7 @@ static int erofsmount_nbd_fix_backend_linkage(int num, char **recp)
 	int err;
 
 	newrecp = erofs_nbd_get_identifier(num);
-	if (!IS_ERR(newrecp)) {
-		err = strlen(newrecp);
-		if (newrecp[err - 1] == '\n')
-			newrecp[err - 1] = '\0';
+	if (!IS_ERR(newrecp) && newrecp) {
 		err = strcmp(newrecp, *recp) ? -EFAULT : 0;
 		free(newrecp);
 		return err;
@@ -461,16 +458,11 @@ static int erofsmount_reattach(const char *target)
 	if (nbdnum < 0)
 		return nbdnum;
 	identifier = erofs_nbd_get_identifier(nbdnum);
-	if (IS_ERR(identifier))
+	if (IS_ERR(identifier)) {
+		identifier = NULL;
+	} else if (identifier && *identifier == '\0') {
+		free(identifier);
 		identifier = NULL;
-	else if (identifier) {
-		n = strlen(identifier);
-		if (__erofs_unlikely(!n)) {
-			free(identifier);
-			identifier = NULL;
-		} else if (identifier[n - 1] == '\n') {
-			identifier[n - 1] = '\0';
-		}
 	}
 
 	if (!identifier &&
@@ -596,8 +588,6 @@ static int erofsmount_nbd(const char *source, const char *mountpoint,
 
 		if (!err && is_netlink) {
 			id = erofs_nbd_get_identifier(num);
-			if (id == ERR_PTR(-ENOENT))
-				id = NULL;
 
 			err = IS_ERR(id) ? PTR_ERR(id) :
 				erofs_nbd_nl_reconfigure(num, id, true);
-- 
2.43.5



More information about the Linux-erofs mailing list