Introduce string_printf
[external/binutils.git] / gdb / common / common-utils.c
1 /* Shared general utility routines for GDB, the GNU debugger.
2
3    Copyright (C) 1986-2016 Free Software Foundation, Inc.
4
5    This file is part of GDB.
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 3 of the License, or
10    (at your option) 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    You should have received a copy of the GNU General Public License
18    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
19
20 #include "common-defs.h"
21 #include "host-defs.h"
22 #include <ctype.h>
23
24 /* The xmalloc() (libiberty.h) family of memory management routines.
25
26    These are like the ISO-C malloc() family except that they implement
27    consistent semantics and guard against typical memory management
28    problems.  */
29
30 /* NOTE: These are declared using PTR to ensure consistency with
31    "libiberty.h".  xfree() is GDB local.  */
32
33 PTR                            /* ARI: PTR */
34 xmalloc (size_t size)
35 {
36   void *val;
37
38   /* See libiberty/xmalloc.c.  This function need's to match that's
39      semantics.  It never returns NULL.  */
40   if (size == 0)
41     size = 1;
42
43   val = malloc (size);         /* ARI: malloc */
44   if (val == NULL)
45     malloc_failure (size);
46
47   return val;
48 }
49
50 PTR                              /* ARI: PTR */
51 xrealloc (PTR ptr, size_t size)          /* ARI: PTR */
52 {
53   void *val;
54
55   /* See libiberty/xmalloc.c.  This function need's to match that's
56      semantics.  It never returns NULL.  */
57   if (size == 0)
58     size = 1;
59
60   if (ptr != NULL)
61     val = realloc (ptr, size);  /* ARI: realloc */
62   else
63     val = malloc (size);                /* ARI: malloc */
64   if (val == NULL)
65     malloc_failure (size);
66
67   return val;
68 }
69
70 PTR                            /* ARI: PTR */           
71 xcalloc (size_t number, size_t size)
72 {
73   void *mem;
74
75   /* See libiberty/xmalloc.c.  This function need's to match that's
76      semantics.  It never returns NULL.  */
77   if (number == 0 || size == 0)
78     {
79       number = 1;
80       size = 1;
81     }
82
83   mem = calloc (number, size);      /* ARI: xcalloc */
84   if (mem == NULL)
85     malloc_failure (number * size);
86
87   return mem;
88 }
89
90 void *
91 xzalloc (size_t size)
92 {
93   return xcalloc (1, size);
94 }
95
96 void
97 xfree (void *ptr)
98 {
99   if (ptr != NULL)
100     free (ptr);         /* ARI: free */
101 }
102
103 void
104 xmalloc_failed (size_t size)
105 {
106   malloc_failure (size);
107 }
108
109 /* Like asprintf/vasprintf but get an internal_error if the call
110    fails. */
111
112 char *
113 xstrprintf (const char *format, ...)
114 {
115   char *ret;
116   va_list args;
117
118   va_start (args, format);
119   ret = xstrvprintf (format, args);
120   va_end (args);
121   return ret;
122 }
123
124 char *
125 xstrvprintf (const char *format, va_list ap)
126 {
127   char *ret = NULL;
128   int status = vasprintf (&ret, format, ap);
129
130   /* NULL is returned when there was a memory allocation problem, or
131      any other error (for instance, a bad format string).  A negative
132      status (the printed length) with a non-NULL buffer should never
133      happen, but just to be sure.  */
134   if (ret == NULL || status < 0)
135     internal_error (__FILE__, __LINE__, _("vasprintf call failed"));
136   return ret;
137 }
138
139 int
140 xsnprintf (char *str, size_t size, const char *format, ...)
141 {
142   va_list args;
143   int ret;
144
145   va_start (args, format);
146   ret = vsnprintf (str, size, format, args);
147   gdb_assert (ret < size);
148   va_end (args);
149
150   return ret;
151 }
152
153 /* See documentation in common-utils.h.  */
154
155 std::string
156 string_printf (const char* fmt, ...)
157 {
158   va_list vp;
159   int size;
160
161   va_start (vp, fmt);
162   size = vsnprintf (NULL, 0, fmt, vp);
163   va_end (vp);
164
165   std::string str (size, '\0');
166
167   /* C++11 and later guarantee std::string uses contiguous memory and
168      always includes the terminating '\0'.  */
169   va_start (vp, fmt);
170   vsprintf (&str[0], fmt, vp);
171   va_end (vp);
172
173   return str;
174 }
175
176 char *
177 savestring (const char *ptr, size_t len)
178 {
179   char *p = (char *) xmalloc (len + 1);
180
181   memcpy (p, ptr, len);
182   p[len] = 0;
183   return p;
184 }
185
186 /* The bit offset of the highest byte in a ULONGEST, for overflow
187    checking.  */
188
189 #define HIGH_BYTE_POSN ((sizeof (ULONGEST) - 1) * HOST_CHAR_BIT)
190
191 /* True (non-zero) iff DIGIT is a valid digit in radix BASE,
192    where 2 <= BASE <= 36.  */
193
194 static int
195 is_digit_in_base (unsigned char digit, int base)
196 {
197   if (!isalnum (digit))
198     return 0;
199   if (base <= 10)
200     return (isdigit (digit) && digit < base + '0');
201   else
202     return (isdigit (digit) || tolower (digit) < base - 10 + 'a');
203 }
204
205 static int
206 digit_to_int (unsigned char c)
207 {
208   if (isdigit (c))
209     return c - '0';
210   else
211     return tolower (c) - 'a' + 10;
212 }
213
214 /* As for strtoul, but for ULONGEST results.  */
215
216 ULONGEST
217 strtoulst (const char *num, const char **trailer, int base)
218 {
219   unsigned int high_part;
220   ULONGEST result;
221   int minus = 0;
222   int i = 0;
223
224   /* Skip leading whitespace.  */
225   while (isspace (num[i]))
226     i++;
227
228   /* Handle prefixes.  */
229   if (num[i] == '+')
230     i++;
231   else if (num[i] == '-')
232     {
233       minus = 1;
234       i++;
235     }
236
237   if (base == 0 || base == 16)
238     {
239       if (num[i] == '0' && (num[i + 1] == 'x' || num[i + 1] == 'X'))
240         {
241           i += 2;
242           if (base == 0)
243             base = 16;
244         }
245     }
246
247   if (base == 0 && num[i] == '0')
248     base = 8;
249
250   if (base == 0)
251     base = 10;
252
253   if (base < 2 || base > 36)
254     {
255       errno = EINVAL;
256       return 0;
257     }
258
259   result = high_part = 0;
260   for (; is_digit_in_base (num[i], base); i += 1)
261     {
262       result = result * base + digit_to_int (num[i]);
263       high_part = high_part * base + (unsigned int) (result >> HIGH_BYTE_POSN);
264       result &= ((ULONGEST) 1 << HIGH_BYTE_POSN) - 1;
265       if (high_part > 0xff)
266         {
267           errno = ERANGE;
268           result = ~ (ULONGEST) 0;
269           high_part = 0;
270           minus = 0;
271           break;
272         }
273     }
274
275   if (trailer != NULL)
276     *trailer = &num[i];
277
278   result = result + ((ULONGEST) high_part << HIGH_BYTE_POSN);
279   if (minus)
280     return -result;
281   else
282     return result;
283 }
284
285 /* See documentation in common-utils.h.  */
286
287 char *
288 skip_spaces (char *chp)
289 {
290   if (chp == NULL)
291     return NULL;
292   while (*chp && isspace (*chp))
293     chp++;
294   return chp;
295 }
296
297 /* A const-correct version of the above.  */
298
299 const char *
300 skip_spaces_const (const char *chp)
301 {
302   if (chp == NULL)
303     return NULL;
304   while (*chp && isspace (*chp))
305     chp++;
306   return chp;
307 }
308
309 /* See documentation in common-utils.h.  */
310
311 const char *
312 skip_to_space_const (const char *chp)
313 {
314   if (chp == NULL)
315     return NULL;
316   while (*chp && !isspace (*chp))
317     chp++;
318   return chp;
319 }