66d61615a9ddd14d9ad29d2744bd5a6284086e2c
[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 xmalloc_failed (size_t size)
99 {
100   malloc_failure (size);
101 }
102
103 /* Like asprintf/vasprintf but get an internal_error if the call
104    fails. */
105
106 char *
107 xstrprintf (const char *format, ...)
108 {
109   char *ret;
110   va_list args;
111
112   va_start (args, format);
113   ret = xstrvprintf (format, args);
114   va_end (args);
115   return ret;
116 }
117
118 char *
119 xstrvprintf (const char *format, va_list ap)
120 {
121   char *ret = NULL;
122   int status = vasprintf (&ret, format, ap);
123
124   /* NULL is returned when there was a memory allocation problem, or
125      any other error (for instance, a bad format string).  A negative
126      status (the printed length) with a non-NULL buffer should never
127      happen, but just to be sure.  */
128   if (ret == NULL || status < 0)
129     internal_error (__FILE__, __LINE__, _("vasprintf call failed"));
130   return ret;
131 }
132
133 int
134 xsnprintf (char *str, size_t size, const char *format, ...)
135 {
136   va_list args;
137   int ret;
138
139   va_start (args, format);
140   ret = vsnprintf (str, size, format, args);
141   gdb_assert (ret < size);
142   va_end (args);
143
144   return ret;
145 }
146
147 /* See documentation in common-utils.h.  */
148
149 std::string
150 string_printf (const char* fmt, ...)
151 {
152   va_list vp;
153   int size;
154
155   va_start (vp, fmt);
156   size = vsnprintf (NULL, 0, fmt, vp);
157   va_end (vp);
158
159   std::string str (size, '\0');
160
161   /* C++11 and later guarantee std::string uses contiguous memory and
162      always includes the terminating '\0'.  */
163   va_start (vp, fmt);
164   vsprintf (&str[0], fmt, vp);
165   va_end (vp);
166
167   return str;
168 }
169
170 /* See documentation in common-utils.h.  */
171
172 std::string
173 string_vprintf (const char* fmt, va_list args)
174 {
175   va_list vp;
176   size_t size;
177
178   va_copy (vp, args);
179   size = vsnprintf (NULL, 0, fmt, vp);
180   va_end (vp);
181
182   std::string str (size, '\0');
183
184   /* C++11 and later guarantee std::string uses contiguous memory and
185      always includes the terminating '\0'.  */
186   vsprintf (&str[0], fmt, args);
187
188   return str;
189 }
190
191
192 /* See documentation in common-utils.h.  */
193
194 void
195 string_appendf (std::string &str, const char *fmt, ...)
196 {
197   va_list vp;
198
199   va_start (vp, fmt);
200   string_vappendf (str, fmt, vp);
201   va_end (vp);
202 }
203
204
205 /* See documentation in common-utils.h.  */
206
207 void
208 string_vappendf (std::string &str, const char *fmt, va_list args)
209 {
210   va_list vp;
211   int grow_size;
212
213   va_copy (vp, args);
214   grow_size = vsnprintf (NULL, 0, fmt, vp);
215   va_end (vp);
216
217   size_t curr_size = str.size ();
218   str.resize (curr_size + grow_size);
219
220   /* C++11 and later guarantee std::string uses contiguous memory and
221      always includes the terminating '\0'.  */
222   vsprintf (&str[curr_size], fmt, args);
223 }
224
225 char *
226 savestring (const char *ptr, size_t len)
227 {
228   char *p = (char *) xmalloc (len + 1);
229
230   memcpy (p, ptr, len);
231   p[len] = 0;
232   return p;
233 }
234
235 /* The bit offset of the highest byte in a ULONGEST, for overflow
236    checking.  */
237
238 #define HIGH_BYTE_POSN ((sizeof (ULONGEST) - 1) * HOST_CHAR_BIT)
239
240 /* True (non-zero) iff DIGIT is a valid digit in radix BASE,
241    where 2 <= BASE <= 36.  */
242
243 static int
244 is_digit_in_base (unsigned char digit, int base)
245 {
246   if (!isalnum (digit))
247     return 0;
248   if (base <= 10)
249     return (isdigit (digit) && digit < base + '0');
250   else
251     return (isdigit (digit) || tolower (digit) < base - 10 + 'a');
252 }
253
254 static int
255 digit_to_int (unsigned char c)
256 {
257   if (isdigit (c))
258     return c - '0';
259   else
260     return tolower (c) - 'a' + 10;
261 }
262
263 /* As for strtoul, but for ULONGEST results.  */
264
265 ULONGEST
266 strtoulst (const char *num, const char **trailer, int base)
267 {
268   unsigned int high_part;
269   ULONGEST result;
270   int minus = 0;
271   int i = 0;
272
273   /* Skip leading whitespace.  */
274   while (isspace (num[i]))
275     i++;
276
277   /* Handle prefixes.  */
278   if (num[i] == '+')
279     i++;
280   else if (num[i] == '-')
281     {
282       minus = 1;
283       i++;
284     }
285
286   if (base == 0 || base == 16)
287     {
288       if (num[i] == '0' && (num[i + 1] == 'x' || num[i + 1] == 'X'))
289         {
290           i += 2;
291           if (base == 0)
292             base = 16;
293         }
294     }
295
296   if (base == 0 && num[i] == '0')
297     base = 8;
298
299   if (base == 0)
300     base = 10;
301
302   if (base < 2 || base > 36)
303     {
304       errno = EINVAL;
305       return 0;
306     }
307
308   result = high_part = 0;
309   for (; is_digit_in_base (num[i], base); i += 1)
310     {
311       result = result * base + digit_to_int (num[i]);
312       high_part = high_part * base + (unsigned int) (result >> HIGH_BYTE_POSN);
313       result &= ((ULONGEST) 1 << HIGH_BYTE_POSN) - 1;
314       if (high_part > 0xff)
315         {
316           errno = ERANGE;
317           result = ~ (ULONGEST) 0;
318           high_part = 0;
319           minus = 0;
320           break;
321         }
322     }
323
324   if (trailer != NULL)
325     *trailer = &num[i];
326
327   result = result + ((ULONGEST) high_part << HIGH_BYTE_POSN);
328   if (minus)
329     return -result;
330   else
331     return result;
332 }
333
334 /* See documentation in common-utils.h.  */
335
336 char *
337 skip_spaces (char *chp)
338 {
339   if (chp == NULL)
340     return NULL;
341   while (*chp && isspace (*chp))
342     chp++;
343   return chp;
344 }
345
346 /* A const-correct version of the above.  */
347
348 const char *
349 skip_spaces (const char *chp)
350 {
351   if (chp == NULL)
352     return NULL;
353   while (*chp && isspace (*chp))
354     chp++;
355   return chp;
356 }
357
358 /* See documentation in common-utils.h.  */
359
360 const char *
361 skip_to_space (const char *chp)
362 {
363   if (chp == NULL)
364     return NULL;
365   while (*chp && !isspace (*chp))
366     chp++;
367   return chp;
368 }
369
370 /* See documentation in common-utils.h.  */
371
372 char *
373 skip_to_space (char *chp)
374 {
375   return (char *) skip_to_space ((const char *) chp);
376 }
377
378 /* See common/common-utils.h.  */
379
380 void
381 free_vector_argv (std::vector<char *> &v)
382 {
383   for (char *el : v)
384     xfree (el);
385
386   v.clear ();
387 }
388
389 /* See common/common-utils.h.  */
390
391 std::string
392 stringify_argv (const std::vector<char *> &args)
393 {
394   std::string ret;
395
396   if (!args.empty () && args[0] != NULL)
397     {
398       for (auto s : args)
399         if (s != NULL)
400           {
401             ret += s;
402             ret += ' ';
403           }
404
405       /* Erase the last whitespace.  */
406       ret.erase (ret.end () - 1);
407     }
408
409   return ret;
410 }