[RFC PATCH 10/28] cli: lil: Add printf-style format helper for errors
Sean Anderson
seanga2 at gmail.com
Thu Jul 1 08:15:53 CEST 2021
This adds a helper for dynamically-created error messages.
Signed-off-by: Sean Anderson <seanga2 at gmail.com>
---
common/cli_lil.c | 43 ++++++++++++++++++++++++++++++++-----------
1 file changed, 32 insertions(+), 11 deletions(-)
diff --git a/common/cli_lil.c b/common/cli_lil.c
index 1bdf0e5265..f29c8065d8 100644
--- a/common/cli_lil.c
+++ b/common/cli_lil.c
@@ -113,6 +113,9 @@ struct expreval {
static struct lil_value *next_word(struct lil *lil);
static void register_stdcmds(struct lil *lil);
static void lil_set_error(struct lil *lil, enum lil_error err, const char *msg);
+static void lil_set_errorf(struct lil *lil, enum lil_error err,
+ const char *fmt, ...)
+ __attribute((format(__printf__, 3, 4)));
#ifdef LIL_ENABLE_POOLS
static struct lil_value **pool;
@@ -1121,12 +1124,9 @@ struct lil_value *lil_parse(struct lil *lil, const char *code, size_t codelen,
if (!cmd) {
if (words->v[0]->l) {
- char msg[64];
-
- snprintf(msg, sizeof(msg),
- "unknown function %s",
- words->v[0]->d);
- lil_set_error(lil, LIL_ERR_NOCMD, msg);
+ lil_set_errorf(lil, LIL_ERR_NOCMD,
+ "unknown function %s",
+ words->v[0]->d);
goto cleanup;
}
} else {
@@ -1180,6 +1180,30 @@ static void lil_set_error(struct lil *lil, enum lil_error err, const char *msg)
lil->err_msg = strdup(msg);
}
+static void lil_set_errorf(struct lil *lil, enum lil_error err,
+ const char *fmt, ...)
+{
+ va_list args, saveargs;
+ size_t n;
+
+ assert(!lil->err);
+ free(lil->err_msg);
+ lil->err = err;
+
+ va_start(args, fmt);
+ va_copy(saveargs, args);
+ n = vsnprintf(NULL, 0, fmt, args) + 1;
+ va_end(args);
+
+ lil->err_msg = calloc(1, n);
+ if (!lil->err_msg) {
+ lil->err = LIL_ERR_OOM;
+ return;
+ }
+ vsnprintf(lil->err_msg, n, fmt, saveargs);
+ va_end(saveargs);
+}
+
enum lil_error lil_error(struct lil *lil, const char **msg)
{
enum lil_error err = lil->err;
@@ -1968,11 +1992,8 @@ static struct lil_value *fnc_rename(struct lil *lil, size_t argc,
newname = lil_to_string(argv[1]);
func = lil_find_cmd(lil, oldname);
if (!func) {
- char *msg = malloc(24 + strlen(oldname));
-
- sprintf(msg, "unknown function '%s'", oldname);
- lil_set_error(lil, LIL_ERR_NOCMD, msg);
- free(msg);
+ lil_set_errorf(lil, LIL_ERR_NOCMD, "unknown function %s",
+ oldname);
return NULL;
}
--
2.32.0
More information about the U-Boot
mailing list