opkg: run pre-install check before listing upgradable packages to ensure all
[project/opkg-lede.git] / libopkg / sprintf_alloc.c
1 /* sprintf_alloc.c -- like sprintf with memory allocation
2
3 Carl D. Worth
4
5 Copyright (C) 2001 University of Southern California
6
7 This program is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 2, or (at your option)
10 any later version.
11
12 This program is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
16 */
17
18 #include "includes.h"
19 #include <stdarg.h>
20
21 #include "sprintf_alloc.h"
22
23 int sprintf_alloc(char **str, const char *fmt, ...)
24 {
25 va_list ap;
26 char *new_str;
27 int n, size = 100;
28
29 if (!str) {
30 fprintf(stderr, "Null string pointer passed to sprintf_alloc\n");
31 return -1;
32 }
33 if (!fmt) {
34 fprintf(stderr, "Null fmt string passed to sprintf_alloc\n");
35 return -1;
36 }
37
38 /* On x86_64 systems, any strings over 100 were segfaulting.
39 It seems that the ap needs to be reinitalized before every
40 use of the v*printf() functions. I pulled the functionality out
41 of vsprintf_alloc and combined it all here instead.
42 */
43
44
45 /* ripped more or less straight out of PRINTF(3) */
46
47 if ((new_str = malloc(size)) == NULL)
48 return -1;
49
50 *str = new_str;
51 while(1) {
52 va_start(ap, fmt);
53 n = vsnprintf (new_str, size, fmt, ap);
54 va_end(ap);
55 /* If that worked, return the size. */
56 if (n > -1 && n < size)
57 return n;
58 /* Else try again with more space. */
59 if (n > -1) /* glibc 2.1 */
60 size = n+1; /* precisely what is needed */
61 else /* glibc 2.0 */
62 size *= 2; /* twice the old size */
63 new_str = realloc(new_str, size);
64 if (new_str == NULL) {
65 free(new_str);
66 *str = NULL;
67 return -1;
68 }
69 *str = new_str;
70 }
71
72 return -1; /* Just to be correct - it probably won't get here */
73 }