[RFC PATCH mtd-utils 010/110] mkfs.ubifs: Close libubi in error handling paths

Zhihao Cheng chengzhihao1 at huawei.com
Thu Jun 6 21:24:35 PDT 2024


The libubi could be opened in get_options(), don't forget to close it
in error handling paths in main(). Also close libubi in error handling
paths in open_ubi(). To implement that, extract libubi_close() into a
new helper function close_ubi().
Besides, invoke crypto_cleanup() in error handling paths in main().

Fixes: a48340c335dab ("mkfs.ubifs: use libubi to format UBI volume")
Signed-off-by: Zhihao Cheng <chengzhihao1 at huawei.com>
---
 ubifs-utils/mkfs.ubifs/mkfs.ubifs.c | 38 ++++++++++++++++++++++++-------------
 1 file changed, 25 insertions(+), 13 deletions(-)

diff --git a/ubifs-utils/mkfs.ubifs/mkfs.ubifs.c b/ubifs-utils/mkfs.ubifs/mkfs.ubifs.c
index 25c49967..6a4a4588 100644
--- a/ubifs-utils/mkfs.ubifs/mkfs.ubifs.c
+++ b/ubifs-utils/mkfs.ubifs/mkfs.ubifs.c
@@ -521,11 +521,21 @@ static long long get_bytes(const char *str)
 
 	return bytes;
 }
+
+static void close_ubi(void)
+{
+	if (ubi) {
+		libubi_close(ubi);
+		ubi = NULL;
+	}
+}
+
 /**
- * open_ubi - open the UBI volume.
+ * open_ubi - open the libubi.
  * @node: name of the UBI volume character device to fetch information about
  *
- * Returns %0 in case of success and %-1 in case of failure
+ * This function opens libubi, and initialize device & volume information
+ * according to @node. Returns %0 in case of success and %-1 in case of failure.
  */
 static int open_ubi(const char *node)
 {
@@ -537,10 +547,14 @@ static int open_ubi(const char *node)
 	ubi = libubi_open();
 	if (!ubi)
 		return -1;
-	if (ubi_get_vol_info(ubi, node, &c->vi))
+	if (ubi_get_vol_info(ubi, node, &c->vi)) {
+		close_ubi();
 		return -1;
-	if (ubi_get_dev_info1(ubi, c->vi.dev_num, &c->di))
+	}
+	if (ubi_get_dev_info1(ubi, c->vi.dev_num, &c->di)) {
+		close_ubi();
 		return -1;
+	}
 	return 0;
 }
 
@@ -2880,8 +2894,6 @@ static int close_target(void)
 		if (close(out_fd) == -1)
 			return sys_errmsg("cannot close the target '%s'", output);
 	}
-	if (ubi)
-		libubi_close(ubi);
 	if (output)
 		free(output);
 	return 0;
@@ -3062,25 +3074,25 @@ int main(int argc, char *argv[])
 
 	err = get_options(argc, argv);
 	if (err)
-		return err;
+		goto out;
 
 	err = open_target();
 	if (err)
-		return err;
+		goto out;
 
 	err = mkfs();
 	if (err) {
 		close_target();
-		return err;
+		goto out;
 	}
 
 	err = close_target();
-	if (err)
-		return err;
 
-	if (verbose)
+	if (verbose && !err)
 		printf("Success!\n");
 
+out:
+	close_ubi();
 	crypto_cleanup();
-	return 0;
+	return err;
 }
-- 
2.13.6




More information about the linux-mtd mailing list