We are currently migrating Bugzilla to GitHub issues.
Any changes made to the bug tracker now will be lost, so please do not post new bugs or make changes to them.
When we're done, all bug URLs will redirect to their equivalent location on the new bug tracker.

Bug 3769

Summary: make sure SDL_vsnprintf() nul terminates if it's using _vsnprintf
Product: SDL Reporter: Ozkan Sezer <sezeroz>
Component: *don't know*Assignee: Ryan C. Gordon <icculus>
Status: RESOLVED FIXED QA Contact: Sam Lantinga <slouken>
Severity: normal    
Priority: P2 CC: metalcaedes
Version: HG 2.0   
Hardware: All   
OS: All   

Description Ozkan Sezer 2017-08-21 23:13:09 UTC
The following patch makes sure that SDL_vsnprintf() nul terminates
if it's using _vsnprintf() for the job.

I made the patch for watcom, whose _vsnprintf() doesn't guarantee
nul termination.  The preprocessor check can be extended to windows
too if required.

----

diff -r 23000b73ce4e src/stdlib/SDL_string.c
--- a/src/stdlib/SDL_string.c
+++ b/src/stdlib/SDL_string.c
@@ -1323,7 +1323,18 @@ SDL_snprintf(SDL_OUT_Z_CAP(maxlen) char 
     return retval;
 }
 
-#ifdef HAVE_VSNPRINTF
+#if defined(HAVE_LIBC) && defined(__WATCOMC__)
+/* _vsnprintf() doesn't ensure nul termination */
+int SDL_vsnprintf(SDL_OUT_Z_CAP(maxlen) char *text, size_t maxlen, const char *fmt, va_list ap)
+{
+    int retval;
+    if (!fmt) fmt = "";
+    retval = _vsnprintf(text, maxlen, fmt, ap);
+    if (maxlen > 0) text[maxlen-1] = '\0';
+    if (retval < 0) retval = (int) maxlen;
+    return retval;
+}
+#elif defined(HAVE_VSNPRINTF)
 int SDL_vsnprintf(SDL_OUT_Z_CAP(maxlen) char *text, size_t maxlen, const char *fmt, va_list ap)
 {
     if (!fmt) {
Comment 1 Ozkan Sezer 2018-05-10 06:04:13 UTC
I pushed this change as http://hg.libsdl.org/SDL/rev/5e1341f8c467
Comment 2 Daniel Gibson 2018-05-11 03:15:37 UTC
MSVC _vsnprintf() has the same issue, btw.
Comment 3 Daniel Gibson 2018-05-11 03:15:48 UTC
MSVC _vsnprintf() has the same issue, btw.
Comment 4 Ozkan Sezer 2018-05-11 05:08:52 UTC
(In reply to Daniel Gibson from comment #3)
> MSVC _vsnprintf() has the same issue, btw.

Yes, of course. However, the official windows builds are done without
system libc support so I didn't touch that.