From e8249497eb0e83b5831e6e5465fae650fb70e9e9 Mon Sep 17 00:00:00 2001 From: Elliott Slaughter Date: Wed, 19 Jun 2024 16:16:14 -0700 Subject: [PATCH] Switch to snprintf throughout codebase (#664) --- src/lparser.cpp | 12 ++++++------ src/tcwrapper.cpp | 2 +- src/terra.cpp | 5 +++-- 3 files changed, 10 insertions(+), 9 deletions(-) diff --git a/src/lparser.cpp b/src/lparser.cpp index 5843f2c9f..82ac34a10 100644 --- a/src/lparser.cpp +++ b/src/lparser.cpp @@ -961,14 +961,14 @@ static void doquote(LexState *ls, int isexp) { } // buf should be at least 128 chars -static void number_type(LexState *ls, int flags, char *buf) { +static void number_type(LexState *ls, int flags, char *buf, size_t bufsiz) { if (ls->in_terra) { if (flags & F_ISINTEGER) { const char *sign = (flags & F_ISUNSIGNED) ? "u" : ""; const char *sz = (flags & F_IS8BYTES) ? "64" : ""; - sprintf(buf, "%sint%s", sign, sz); + snprintf(buf, bufsiz, "%sint%s", sign, sz); } else { - sprintf(buf, "%s", (flags & F_IS8BYTES) ? "double" : "float"); + snprintf(buf, bufsiz, "%s", (flags & F_IS8BYTES) ? "double" : "float"); } } } @@ -997,11 +997,11 @@ static void simpleexp(LexState *ls) { case TK_NUMBER: { char buf[128]; int flags = ls->t.seminfo.flags; - number_type(ls, flags, &buf[0]); + number_type(ls, flags, &buf[0], sizeof(buf)); if (flags & F_ISINTEGER) { push_integer(ls, ls->t.seminfo.i); push_literal(ls, buf); - sprintf(buf, "%" PRIu64, ls->t.seminfo.i); + snprintf(buf, sizeof(buf), "%" PRIu64, ls->t.seminfo.i); push_string(ls, buf); add_field(ls, -2, "stringvalue"); @@ -2053,7 +2053,7 @@ static void converttokentolua(LexState *ls, Token *t) { lua_pushstring(ls->L, ""); lua_setfield(ls->L, -2, "type"); int flags = t->seminfo.flags; - number_type(ls, flags, &buf[0]); + number_type(ls, flags, &buf[0], sizeof(buf)); push_type(ls, buf); lua_setfield(ls->L, -2, "valuetype"); if (flags & F_IS8BYTES && flags & F_ISINTEGER) { diff --git a/src/tcwrapper.cpp b/src/tcwrapper.cpp index 24c5881a5..6fd5b0aa5 100644 --- a/src/tcwrapper.cpp +++ b/src/tcwrapper.cpp @@ -99,7 +99,7 @@ class IncludeCVisitor : public RecursiveASTVisitor { std::string declstr; if (it->isAnonymousStructOrUnion()) { char buf[32]; - sprintf(buf, "_%d", anonname++); + snprintf(buf, sizeof(buf), "_%d", anonname++); declstr = buf; } else { declstr = declname.getAsString(); diff --git a/src/terra.cpp b/src/terra.cpp index e06372a48..d5405434c 100644 --- a/src/terra.cpp +++ b/src/terra.cpp @@ -572,8 +572,9 @@ int terra_loadfile(lua_State *L, const char *file) { if (c == '\n') ungetc(c, ctx.fp); /* keep line count accurate */ } if (file) { - char *name = (char *)malloc(strlen(file) + 2); - sprintf(name, "@%s", file); + size_t name_size = strlen(file) + 2; + char *name = (char *)malloc(name_size); + snprintf(name, name_size, "@%s", file); int r = terra_load(L, reader_file, &ctx, name); free(name); fclose(ctx.fp);