From fc5982cb60b1aa1d0c807d49bada84662a80ca35 Mon Sep 17 00:00:00 2001 From: Mohan Yelugoti Date: Fri, 30 Aug 2024 19:27:41 -0400 Subject: [PATCH] v.in.dwg: Avoid using same variable as parameter and dest in sprintf Currently, one instance of sprintf has same variable as parameter and destination in sprintf. This scneario leads to undefined behavior in C. Modify the code to: 1. Write initial error string using snprintf() onto the buffer. Using snprintf() makes sure that we stay within the buffer size and avoid overflow errors. 2. Use snprintf() again to write another error string at the end of previous error string in the same buffer. We again use snprintf() to make sure we are not overflowing the buffer with data. Signed-off-by: Mohan Yelugoti --- vector/v.in.dwg/main.c | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/vector/v.in.dwg/main.c b/vector/v.in.dwg/main.c index e21602ecb90..cc7b9a217b1 100644 --- a/vector/v.in.dwg/main.c +++ b/vector/v.in.dwg/main.c @@ -66,7 +66,8 @@ int main(int argc, char *argv[]) struct GModule *module; struct Option *out_opt, *in_opt; struct Flag *z_flag, *circle_flag, *l_flag, *int_flag; - char buf[2000]; + const size_t BUFSIZE = 2000; + char buf[BUFSIZE]; /* DWG */ char path[2000]; @@ -135,10 +136,13 @@ int main(int argc, char *argv[]) /* Init OpenDWG */ sprintf(path, "%s/etc/adinit.dat", G_gisbase()); if (!adInitAd2(path, &initerror)) { - sprintf(buf, _("Unable to initialize OpenDWG Toolkit, error: %d: %s."), - initerror, adErrorStr(initerror)); + snprintf(buf, BUFSIZE, + _("Unable to initialize OpenDWG Toolkit, error: %d: %s."), + initerror, adErrorStr(initerror)); + size_t buflen = strlen(buf); if (initerror == AD_UNABLE_TO_OPEN_INIT_FILE) - sprintf(buf, _("%s Cannot open %s"), buf, path); + snprintf(buf + buflen, BUFSIZE - buflen, _(" Cannot open %s"), + path); G_fatal_error(buf); } adSetupDwgRead();