blob: 16d449cfab0a09788d25ab6cbcbcf30083adc139 [file] [log] [blame]
H. Peter Anvin304b6052007-09-28 10:50:20 -07001/*
2 * vsnprintf()
3 *
4 * Poor substitute for a real vsnprintf() function for systems
5 * that don't have them...
6 */
7
H. Peter Anvinfe501952007-10-02 21:53:51 -07008#include "compiler.h"
9
H. Peter Anvin304b6052007-09-28 10:50:20 -070010#include <stdio.h>
11#include <stdlib.h>
12#include <stdarg.h>
13#include <string.h>
14
15#include "nasmlib.h"
16
Cyrill Gorcunov5d269782010-04-01 01:09:35 +040017#define BUFFER_SIZE 65536 /* Bigger than any string we might print... */
H. Peter Anvin304b6052007-09-28 10:50:20 -070018
19static char snprintf_buffer[BUFFER_SIZE];
20
21int vsnprintf(char *str, size_t size, const char *format, va_list ap)
22{
23 int rv, bytes;
24
25 if (size > BUFFER_SIZE) {
Cyrill Gorcunov5d269782010-04-01 01:09:35 +040026 nasm_malloc_error(ERR_PANIC|ERR_NOFILE,
27 "snprintf: size (%d) > BUFFER_SIZE (%d)",
28 size, BUFFER_SIZE);
29 size = BUFFER_SIZE;
H. Peter Anvin304b6052007-09-28 10:50:20 -070030 }
31
32 rv = vsprintf(snprintf_buffer, format, ap);
H. Peter Anvin43827652007-09-28 12:01:55 -070033 if (rv >= BUFFER_SIZE) {
Cyrill Gorcunov5d269782010-04-01 01:09:35 +040034 nasm_malloc_error(ERR_PANIC|ERR_NOFILE,
35 "snprintf buffer overflow");
H. Peter Anvin304b6052007-09-28 10:50:20 -070036 }
37
H. Peter Anvin304b6052007-09-28 10:50:20 -070038 if (size > 0) {
Cyrill Gorcunov5d269782010-04-01 01:09:35 +040039 if ((size_t)rv < size-1)
40 bytes = rv;
41 else
42 bytes = size-1;
43 memcpy(str, snprintf_buffer, bytes);
44 str[bytes] = '\0';
H. Peter Anvin304b6052007-09-28 10:50:20 -070045 }
46
47 return rv;
48}