Skip to content

Commit

Permalink
com: fix loop/crash in dpvsnprintf() error handling
Browse files Browse the repository at this point in the history
Somehow I didn't notice Sys_Printf() calls dpvsnprintf(), see
21fa901.

Also fixes a minor bug where Sys_Print() could output more bytes than it
should, introduced in 01642af.

Signed-off-by: bones_was_here <[email protected]>
  • Loading branch information
bones-was-here committed Jul 23, 2024
1 parent ffc8287 commit e0ae552
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 5 deletions.
23 changes: 19 additions & 4 deletions common.c
Original file line number Diff line number Diff line change
Expand Up @@ -1018,12 +1018,27 @@ int dpvsnprintf (char *buffer, size_t buffersize, const char *format, va_list ar
#endif
if (result < 0 || (size_t)result >= buffersize)
{
buffer[buffersize - 1] = '\0';
// we could be inside Con_Printf
// _vsnprintf_s returns -1 on error and on truncation (indistinguishable),
// vsnprintf returns negative on error and the desired strlen on truncation.
buffer[buffersize - 1] = '\0'; // should be unnecessary, but just in case
// Basic stdout only: we could be inside Con_Printf, Sys_Printf calls dpvsnprintf,
// Windows console doesn't support colours.
if (result < 0)
Sys_Printf("dpvsnprintf: output error, buffer size %lu\n", (unsigned long)buffersize);
Sys_Print("dpvsnprintf: output error!\n", 27);
else
Sys_Printf("dpvsnprintf: truncated to %lu bytes: \"%s\"\n", (unsigned long)buffersize - 1, buffer);
{
char msg[MAX_INPUTLINE];
#if _MSC_VER >= 1400
result = _snprintf_s(msg, sizeof(msg), _TRUNCATE, "dpvsnprintf: truncated to %lu bytes: \"%s\"\n", (unsigned long)buffersize - 1, buffer);
#else
result = snprintf(msg, sizeof(msg), "dpvsnprintf: truncated to %lu bytes: \"%s\"\n", (unsigned long)buffersize - 1, buffer);
#endif
if (result > 0)
{
msg[sizeof(msg) - 1] = '\n'; // may have been lost in truncation
Sys_Print(msg, min((size_t)result, sizeof(msg)));
}
}
return -1;
}

Expand Down
3 changes: 2 additions & 1 deletion sys_shared.c
Original file line number Diff line number Diff line change
Expand Up @@ -629,12 +629,13 @@ void Sys_Print(const char *text, size_t textlen)
#else
#define write _write
#endif
while(*text)
while(*text && textlen)
{
fs_offset_t written = (fs_offset_t)write(sys.outfd, text, textlen);
if(written <= 0)
break; // sorry, I cannot do anything about this error - without an output
text += written;
textlen -= written;
}
#ifndef WIN32
if (sys_stdout_blocks.integer)
Expand Down

0 comments on commit e0ae552

Please sign in to comment.