[PATCH v3 1/3] keytoc: mark keyspec user input as readonly

Marco Felsch m.felsch at pengutronix.de
Mon Aug 18 10:08:13 PDT 2025


Don't manipulate the user input and intead allocate the keyname and path
always to drop the usage of freep. Move the keyspec parsing code into a
helper to increase the readability further while on it.

This prepares keytoc handle a keyspec provided by a single environment
variable.

Signed-off-by: Marco Felsch <m.felsch at pengutronix.de>
---
Changelog:
v3:
- no changes
v2:
- new patch

 scripts/keytoc.c | 54 +++++++++++++++++++++++++++++++++---------------
 1 file changed, 37 insertions(+), 17 deletions(-)

diff --git a/scripts/keytoc.c b/scripts/keytoc.c
index c92465707f65..617317d6607e 100644
--- a/scripts/keytoc.c
+++ b/scripts/keytoc.c
@@ -653,6 +653,34 @@ static int gen_key(const char *keyname, const char *path)
 	return ret;
 }
 
+static void get_name_path(const char *keyspec, char **keyname, char **path)
+{
+	char *sep, *spec;
+
+	spec = strdup(keyspec);
+	if (!spec)
+		enomem_exit(__func__);
+
+	/* Split <key-hint>:<key-path> pair, <key-hint> is optional */
+	sep = strchr(spec, ':');
+	if (!sep) {
+		*path = spec;
+		return;
+	}
+
+	*sep = 0;
+	*keyname = strdup(spec);
+	if (!*keyname)
+		enomem_exit(__func__);
+
+	sep++;
+	*path = strdup(sep);
+	if (!*path)
+		enomem_exit(__func__);
+
+	free(spec);
+}
+
 int main(int argc, char *argv[])
 {
 	int i, opt, ret;
@@ -705,35 +733,27 @@ int main(int argc, char *argv[])
 	}
 
 	for (i = optind; i < argc; i++) {
-		char *keyspec = argv[i];
+		const char *keyspec = argv[i];
 		char *keyname = NULL;
-		char *path, *freep = NULL;
+		char *path = NULL;
 
-		if (!strncmp(keyspec, "pkcs11:", 7)) {
-			path = keyspec;
-		} else {
-			path = strchr(keyspec, ':');
-			if (path) {
-				*path = 0;
-				path++;
-				keyname = keyspec;
-			} else {
-				path = keyspec;
-			}
-		}
+		if (!strncmp(keyspec, "pkcs11:", 7))
+			path = strdup(keyspec);
+		else
+			get_name_path(keyspec, &keyname, &path);
 
 		if (!keyname) {
-			ret = asprintf(&freep, "key_%d", keynum++);
+			ret = asprintf(&keyname, "key_%d", keynum++);
 			if (ret < 0)
 				enomem_exit("asprintf");
-			keyname = freep;
 		}
 
 		ret = gen_key(keyname, path);
 		if (ret)
 			exit(1);
 
-		free(freep);
+		free(keyname);
+		free(path);
 	}
 
 	if (dts) {
-- 
2.39.5




More information about the barebox mailing list