Selaa lähdekoodia

Correctly handle zero-length buffers.

tags/v0.9.3
Michael Brown 18 vuotta sitten
vanhempi
commit
efd6281a35
1 muutettua tiedostoa jossa 9 lisäystä ja 10 poistoa
  1. 9
    10
      src/core/vsprintf.c

+ 9
- 10
src/core/vsprintf.c Näytä tiedosto

@@ -171,7 +171,7 @@ static char * format_decimal ( char *end, signed long num, int width ) {
171 171
  * @v args		Arguments corresponding to the format string
172 172
  * @ret len		Length of formatted string
173 173
  */
174
-int vcprintf ( struct printf_context *ctx, const char *fmt, va_list args ) {
174
+size_t vcprintf ( struct printf_context *ctx, const char *fmt, va_list args ) {
175 175
 	int flags;
176 176
 	int width;
177 177
 	uint8_t *length;
@@ -296,14 +296,8 @@ static void printf_sputc ( struct printf_context *ctx, unsigned int c ) {
296 296
  */
297 297
 int vsnprintf ( char *buf, size_t size, const char *fmt, va_list args ) {
298 298
 	struct printf_context ctx;
299
-	int len;
300
-
301
-	/* Ensure last byte is NUL if a size is specified.  This
302
-	 * catches the case of the buffer being too small, in which
303
-	 * case a trailing NUL would not otherwise be added.
304
-	 */
305
-	if ( size != PRINTF_NO_LENGTH )
306
-		buf[size-1] = '\0';
299
+	size_t len;
300
+	size_t end;
307 301
 
308 302
 	/* Hand off to vcprintf */
309 303
 	ctx.handler = printf_sputc;
@@ -312,7 +306,12 @@ int vsnprintf ( char *buf, size_t size, const char *fmt, va_list args ) {
312 306
 	len = vcprintf ( &ctx, fmt, args );
313 307
 
314 308
 	/* Add trailing NUL */
315
-	printf_sputc ( &ctx, '\0' );
309
+	if ( size ) {
310
+		end = size - 1;
311
+		if ( len < end )
312
+			end = len;
313
+		buf[end] = '\0';
314
+	}
316 315
 
317 316
 	return len;
318 317
 }

Loading…
Peruuta
Tallenna