Introduce string_appendf/string_vappendf
[external/binutils.git] / gdb / common / common-utils.c
1 /* Shared general utility routines for GDB, the GNU debugger.
2
3    Copyright (C) 1986-2017 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 "common-utils.h"
22 #include "host-defs.h"
23 #include <ctype.h>
24
25 /* The xmalloc() (libiberty.h) family of memory management routines.
26
27    These are like the ISO-C malloc() family except that they implement
28    consistent semantics and guard against typical memory management
29    problems.  */
30
31 /* NOTE: These are declared using PTR to ensure consistency with
32    "libiberty.h".  xfree() is GDB local.  */
33
34 PTR                            /* ARI: PTR */
35 xmalloc (size_t size)
36 {
37   void *val;
38
39   /* See libiberty/xmalloc.c.  This function need's to match that's
40      semantics.  It never returns NULL.  */
41   if (size == 0)
42     size = 1;
43
44   val = malloc (size);         /* ARI: malloc */
45   if (val == NULL)
46     malloc_failure (size);
47
48   return val;
49 }
50
51 PTR                              /* ARI: PTR */
52 xrealloc (PTR ptr, size_t size)          /* ARI: PTR */
53 {
54   void *val;
55
56   /* See libiberty/xmalloc.c.  This function need's to match that's
57      semantics.  It never returns NULL.  */
58   if (size == 0)
59     size = 1;
60
61   if (ptr != NULL)
62     val = realloc (ptr, size);  /* ARI: realloc */
63   else
64     val = malloc (size);                /* ARI: malloc */
65   if (val == NULL)
66     malloc_failure (size);
67
68   return val;
69 }
70
71 PTR                            /* ARI: PTR */           
72 xcalloc (size_t number, size_t size)
73 {
74   void *mem;
75
76   /* See libiberty/xmalloc.c.  This function need's to match that's
77      semantics.  It never returns NULL.  */
78   if (number == 0 || size == 0)
79     {
80       number = 1;
81       size = 1;
82     }
83
84   mem = calloc (number, size);      /* ARI: xcalloc */
85   if (mem == NULL)
86     malloc_failure (number * size);
87
88   return mem;
89 }
90
91 void *
92 xzalloc (size_t size)
93 {
94   return xcalloc (1, size);
95 }
96
97 void
98 xfree (void *ptr)
99 {
100   if (ptr != NULL)
101     free (ptr);         /* ARI: free */
102 }
103
104 void
105 xmalloc_failed (size_t size)
106 {
107   malloc_failure (size);
108 }
109
110 /* Like asprintf/vasprintf but get an internal_error if the call
111    fails. */
112
113 char *
114 xstrprintf (const char *format, ...)
115 {
116   char *ret;
117   va_list args;
118
119   va_start (args, format);
120   ret = xstrvprintf (format, args);
121   va_end (args);
122   return ret;
123 }
124
125 char *
126 xstrvprintf (const char *format, va_list ap)
127 {
128   char *ret = NULL;
129   int status = vasprintf (&ret, format, ap);
130
131   /* NULL is returned when there was a memory allocation problem, or
132      any other error (for instance, a bad format string).  A negative
133      status (the printed length) with a non-NULL buffer should never
134      happen, but just to be sure.  */
135   if (ret == NULL || status < 0)
136     internal_error (__FILE__, __LINE__, _("vasprintf call failed"));
137   return ret;
138 }
139
140 int
141 xsnprintf (char *str, size_t size, const char *format, ...)
142 {
143   va_list args;
144   int ret;
145
146   va_start (args, format);
147   ret = vsnprintf (str, size, format, args);
148   gdb_assert (ret < size);
149   va_end (args);
150
151   return ret;
152 }
153
154 /* See documentation in common-utils.h.  */
155
156 std::string
157 string_printf (const char* fmt, ...)
158 {
159   va_list vp;
160   int size;
161
162   va_start (vp, fmt);
163   size = vsnprintf (NULL, 0, fmt, vp);
164   va_end (vp);
165
166   std::string str (size, '\0');
167
168   /* C++11 and later guarantee std::string uses contiguous memory and
169      always includes the terminating '\0'.  */
170   va_start (vp, fmt);
171   vsprintf (&str[0], fmt, vp);
172   va_end (vp);
173
174   return str;
175 }
176
177 /* See documentation in common-utils.h.  */
178
179 std::string
180 string_vprintf (const char* fmt, va_list args)
181 {
182   va_list vp;
183   size_t size;
184
185   va_copy (vp, args);
186   size = vsnprintf (NULL, 0, fmt, vp);
187   va_end (vp);
188
189   std::string str (size, '\0');
190
191   /* C++11 and later guarantee std::string uses contiguous memory and
192      always includes the terminating '\0'.  */
193   vsprintf (&str[0], fmt, args);
194
195   return str;
196 }
197
198
199 /* See documentation in common-utils.h.  */
200
201 void
202 string_appendf (std::string &str, const char *fmt, ...)
203 {
204   va_list vp;
205
206   va_start (vp, fmt);
207   string_vappendf (str, fmt, vp);
208   va_end (vp);
209 }
210
211
212 /* See documentation in common-utils.h.  */
213
214 void
215 string_vappendf (std::string &str, const char *fmt, va_list args)
216 {
217   va_list vp;
218   int grow_size;
219
220   va_copy (vp, args);
221   grow_size = vsnprintf (NULL, 0, fmt, vp);
222   va_end (vp);
223
224   size_t curr_size = str.size ();
225   str.resize (curr_size + grow_size);
226
227   /* C++11 and later guarantee std::string uses contiguous memory and
228      always includes the terminating '\0'.  */
229   vsprintf (&str[curr_size], fmt, args);
230 }
231
232 char *
233 savestring (const char *ptr, size_t len)
234 {
235   char *p = (char *) xmalloc (len + 1);
236
237   memcpy (p, ptr, len);
238   p[len] = 0;
239   return p;
240 }
241
242 /* The bit offset of the highest byte in a ULONGEST, for overflow
243    checking.  */
244
245 #define HIGH_BYTE_POSN ((sizeof (ULONGEST) - 1) * HOST_CHAR_BIT)
246
247 /* True (non-zero) iff DIGIT is a valid digit in radix BASE,
248    where 2 <= BASE <= 36.  */
249
250 static int
251 is_digit_in_base (unsigned char digit, int base)
252 {
253   if (!isalnum (digit))
254     return 0;
255   if (base <= 10)
256     return (isdigit (digit) && digit < base + '0');
257   else
258     return (isdigit (digit) || tolower (digit) < base - 10 + 'a');
259 }
260
261 static int
262 digit_to_int (unsigned char c)
263 {
264   if (isdigit (c))
265     return c - '0';
266   else
267     return tolower (c) - 'a' + 10;
268 }
269
270 /* As for strtoul, but for ULONGEST results.  */
271
272 ULONGEST
273 strtoulst (const char *num, const char **trailer, int base)
274 {
275   unsigned int high_part;
276   ULONGEST result;
277   int minus = 0;
278   int i = 0;
279
280   /* Skip leading whitespace.  */
281   while (isspace (num[i]))
282     i++;
283
284   /* Handle prefixes.  */
285   if (num[i] == '+')
286     i++;
287   else if (num[i] == '-')
288     {
289       minus = 1;
290       i++;
291     }
292
293   if (base == 0 || base == 16)
294     {
295       if (num[i] == '0' && (num[i + 1] == 'x' || num[i + 1] == 'X'))
296         {
297           i += 2;
298           if (base == 0)
299             base = 16;
300         }
301     }
302
303   if (base == 0 && num[i] == '0')
304     base = 8;
305
306   if (base == 0)
307     base = 10;
308
309   if (base < 2 || base > 36)
310     {
311       errno = EINVAL;
312       return 0;
313     }
314
315   result = high_part = 0;
316   for (; is_digit_in_base (num[i], base); i += 1)
317     {
318       result = result * base + digit_to_int (num[i]);
319       high_part = high_part * base + (unsigned int) (result >> HIGH_BYTE_POSN);
320       result &= ((ULONGEST) 1 << HIGH_BYTE_POSN) - 1;
321       if (high_part > 0xff)
322         {
323           errno = ERANGE;
324           result = ~ (ULONGEST) 0;
325           high_part = 0;
326           minus = 0;
327           break;
328         }
329     }
330
331   if (trailer != NULL)
332     *trailer = &num[i];
333
334   result = result + ((ULONGEST) high_part << HIGH_BYTE_POSN);
335   if (minus)
336     return -result;
337   else
338     return result;
339 }
340
341 /* See documentation in common-utils.h.  */
342
343 char *
344 skip_spaces (char *chp)
345 {
346   if (chp == NULL)
347     return NULL;
348   while (*chp && isspace (*chp))
349     chp++;
350   return chp;
351 }
352
353 /* A const-correct version of the above.  */
354
355 const char *
356 skip_spaces (const char *chp)
357 {
358   if (chp == NULL)
359     return NULL;
360   while (*chp && isspace (*chp))
361     chp++;
362   return chp;
363 }
364
365 /* See documentation in common-utils.h.  */
366
367 const char *
368 skip_to_space (const char *chp)
369 {
370   if (chp == NULL)
371     return NULL;
372   while (*chp && !isspace (*chp))
373     chp++;
374   return chp;
375 }
376
377 /* See documentation in common-utils.h.  */
378
379 char *
380 skip_to_space (char *chp)
381 {
382   return (char *) skip_to_space ((const char *) chp);
383 }
384
385 /* See common/common-utils.h.  */
386
387 void
388 free_vector_argv (std::vector<char *> &v)
389 {
390   for (char *el : v)
391     xfree (el);
392
393   v.clear ();
394 }
395
396 /* See common/common-utils.h.  */
397
398 std::string
399 stringify_argv (const std::vector<char *> &args)
400 {
401   std::string ret;
402
403   if (!args.empty () && args[0] != NULL)
404     {
405       for (auto s : args)
406         if (s != NULL)
407           {
408             ret += s;
409             ret += ' ';
410           }
411
412       /* Erase the last whitespace.  */
413       ret.erase (ret.end () - 1);
414     }
415
416   return ret;
417 }