Debian Codegraph @

lib/util/vasprintf.c

raw
1 #define _C99_SOURCE /* Make sure snprintf() is in stdio.h */
2 #define _GNU_SOURCE
3 /* Because of conditional compilation, this is GNU source only if the C
4 library is GNU.
5 */
6 #include <stdlib.h>
7 #include <string.h>
8 #include <stdio.h>
9
10 #include "pm_config.h"
11 #include "pm_c_util.h"
12
13 #include "nstring.h"
14
15
16
17 void
18 pm_vasprintf(const char ** const resultP,
19 const char * const format,
20 va_list varargs) {
21
22 char * result;
23
24 #if HAVE_VASPRINTF
25 int rc;
26
27 rc = vasprintf(&result, format, varargs);
28
29 if (rc < 0)
30 *resultP = pm_strsol;
31 else
32 *resultP = result;
33 #else
34 /* We have a big compromise here. To do this right, without a
35 huge amount of work, we need to go through the variable
36 arguments twice: once to determine how much memory to allocate,
37 and once to format the string. On some machines, you can
38 simply make two copies of the va_list variable in normal C
39 fashion, but on others you need va_copy, which is a relatively
40 recent invention. In particular, the simple va_list copy
41 failed on an AMD64 Gcc Linux system in March 2006.
42
43 So instead, we just allocate 4K and truncate or waste as
44 necessary.
45
46 Note that we don't recognize the floating point specifiers (%f, %e, %g)
47 - we render them as 'f', 'e', and 'g'. It would be too much work to
48 make this code handle those, just for the few systems on which it runs.
49 Instead, we have pm_vasprintf_knows_float(), and any caller that cares
50 enough can avoid using these specifiers where they don't work.
51 */
52 size_t const allocSize = 4096;
53 result = malloc(allocSize);
54
55 if (result == NULL)
56 *resultP = pm_strsol;
57 else {
58 size_t realLen;
59
60 realLen = vsnprintf(result, allocSize, format, varargs);
61
62 if (realLen >= allocSize)
63 strcpy(result + allocSize - 15, "<<<TRUNCATED");
64
65 *resultP = result;
66 }
67 #endif
68 }
69
70
71
72 bool
73 pm_vasprintf_knows_float(void) {
74 #if HAVE_VASPRINTF
75 return true;
76 #else
77 return false;
78 #endif
79 }
80
81
82