Make SDL error string formatting deal with nasty corner cases.

We continued looping while maxlen > 0, but maxlen was unsigned, so an overflow
 would make it a large number instead of negative. Fixed.

Some snprintf() implementations might return a negative value if there isn't
 enough space, and we now check for that.

Don't overrun the SDL error message buffer, if snprintf() returned the number
 of chars it wanted to write instead of the number it did.

snprintf is a portability mess, we should just never use the C runtime for it.

Fixes Bugzilla #2049.
This commit is contained in:
Ryan C. Gordon 2015-03-24 03:12:35 -04:00
parent 54f4725a12
commit d9f378530b

View File

@ -120,7 +120,7 @@ SDL_SetError(SDL_PRINTF_FORMAT_STRING const char *fmt, ...)
so that it supports internationalization and thread-safe errors.
*/
static char *
SDL_GetErrorMsg(char *errstr, unsigned int maxlen)
SDL_GetErrorMsg(char *errstr, int maxlen)
{
SDL_error *error;
@ -163,37 +163,55 @@ SDL_GetErrorMsg(char *errstr, unsigned int maxlen)
len =
SDL_snprintf(msg, maxlen, tmp,
error->args[argi++].value_i);
if (len > 0) {
msg += len;
maxlen -= len;
}
break;
case 'f':
len =
SDL_snprintf(msg, maxlen, tmp,
error->args[argi++].value_f);
if (len > 0) {
msg += len;
maxlen -= len;
}
break;
case 'p':
len =
SDL_snprintf(msg, maxlen, tmp,
error->args[argi++].value_ptr);
if (len > 0) {
msg += len;
maxlen -= len;
}
break;
case 's':
len =
SDL_snprintf(msg, maxlen, tmp,
SDL_LookupString(error->args[argi++].
buf));
if (len > 0) {
msg += len;
maxlen -= len;
}
break;
}
} else {
*msg++ = *fmt++;
maxlen -= 1;
}
}
/* slide back if we've overshot the end of our buffer. */
if (maxlen < 0) {
msg -= (-maxlen) + 1;
}
*msg = 0; /* NULL terminate the string */
}
return (errstr);