blob: 976b0eac95160bfa80d17b3daccdbc65c7b5dbfb [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
17extern efunc nasm_malloc_error;
18
19#define BUFFER_SIZE 65536 /* Bigger than any string we might print... */
20
21static char snprintf_buffer[BUFFER_SIZE];
22
23int vsnprintf(char *str, size_t size, const char *format, va_list ap)
24{
25 int rv, bytes;
26
27 if (size > BUFFER_SIZE) {
28 nasm_malloc_error(ERR_PANIC|ERR_NOFILE,
29 "snprintf: size (%d) > BUFFER_SIZE (%d)",
30 size, BUFFER_SIZE);
31 size = BUFFER_SIZE;
32 }
33
34 rv = vsprintf(snprintf_buffer, format, ap);
H. Peter Anvin43827652007-09-28 12:01:55 -070035 if (rv >= BUFFER_SIZE) {
H. Peter Anvin304b6052007-09-28 10:50:20 -070036 nasm_malloc_error(ERR_PANIC|ERR_NOFILE,
37 "snprintf buffer overflow");
38 }
39
H. Peter Anvin304b6052007-09-28 10:50:20 -070040 if (size > 0) {
H. Peter Anvin43827652007-09-28 12:01:55 -070041 if ((size_t)rv < size-1)
42 bytes = rv;
43 else
44 bytes = size-1;
45
H. Peter Anvin304b6052007-09-28 10:50:20 -070046 memcpy(str, snprintf_buffer, bytes);
47 str[bytes] = '\0';
48 }
49
50 return rv;
51}