Coverage Report

Created: 2025-06-24 06:45

/src/binutils-gdb/libiberty/argv.c
Line
Count
Source (jump to first uncovered line)
1
/* Create and destroy argument vectors (argv's)
2
   Copyright (C) 1992-2025 Free Software Foundation, Inc.
3
   Written by Fred Fish @ Cygnus Support
4
5
This file is part of the libiberty library.
6
Libiberty is free software; you can redistribute it and/or
7
modify it under the terms of the GNU Library General Public
8
License as published by the Free Software Foundation; either
9
version 2 of the License, or (at your option) any later version.
10
11
Libiberty is distributed in the hope that it will be useful,
12
but WITHOUT ANY WARRANTY; without even the implied warranty of
13
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14
Library General Public License for more details.
15
16
You should have received a copy of the GNU Library General Public
17
License along with libiberty; see the file COPYING.LIB.  If
18
not, write to the Free Software Foundation, Inc., 51 Franklin Street - Fifth Floor,
19
Boston, MA 02110-1301, USA.  */
20
21
22
/*  Create and destroy argument vectors.  An argument vector is simply an
23
    array of string pointers, terminated by a NULL pointer. */
24
25
#ifdef HAVE_CONFIG_H
26
#include "config.h"
27
#endif
28
#include "ansidecl.h"
29
#include "libiberty.h"
30
#include "safe-ctype.h"
31
32
/*  Routines imported from standard C runtime libraries. */
33
34
#include <stddef.h>
35
#include <string.h>
36
#include <stdlib.h>
37
#include <stdio.h>
38
#include <sys/types.h>
39
#ifdef HAVE_UNISTD_H
40
#include <unistd.h>
41
#endif
42
#if HAVE_SYS_STAT_H
43
#include <sys/stat.h>
44
#endif
45
46
#ifndef NULL
47
#define NULL 0
48
#endif
49
50
#ifndef EOS
51
0
#define EOS '\0'
52
#endif
53
54
0
#define INITIAL_MAXARGC 8  /* Number of args + NULL in initial argv */
55
56
57
/*
58
59
@deftypefn Extension char** dupargv (char * const *@var{vector})
60
61
Duplicate an argument vector.  Simply scans through @var{vector},
62
duplicating each argument until the terminating @code{NULL} is found.
63
Returns a pointer to the argument vector if successful.  Returns
64
@code{NULL} if there is insufficient memory to complete building the
65
argument vector.
66
67
@end deftypefn
68
69
*/
70
71
char **
72
dupargv (char * const *argv)
73
0
{
74
0
  int argc;
75
0
  char **copy;
76
  
77
0
  if (argv == NULL)
78
0
    return NULL;
79
  
80
  /* the vector */
81
0
  for (argc = 0; argv[argc] != NULL; argc++);
82
0
  copy = (char **) xmalloc ((argc + 1) * sizeof (char *));
83
84
  /* the strings */
85
0
  for (argc = 0; argv[argc] != NULL; argc++)
86
0
    copy[argc] = xstrdup (argv[argc]);
87
0
  copy[argc] = NULL;
88
0
  return copy;
89
0
}
90
91
/*
92
93
@deftypefn Extension void freeargv (char **@var{vector})
94
95
Free an argument vector that was built using @code{buildargv}.  Simply
96
scans through @var{vector}, freeing the memory for each argument until
97
the terminating @code{NULL} is found, and then frees @var{vector}
98
itself.
99
100
@end deftypefn
101
102
*/
103
104
void freeargv (char **vector)
105
0
{
106
0
  register char **scan;
107
108
0
  if (vector != NULL)
109
0
    {
110
0
      for (scan = vector; *scan != NULL; scan++)
111
0
  {
112
0
    free (*scan);
113
0
  }
114
0
      free (vector);
115
0
    }
116
0
}
117
118
static void
119
consume_whitespace (const char **input)
120
0
{
121
0
  while (ISSPACE (**input))
122
0
    {
123
0
      (*input)++;
124
0
    }
125
0
}
126
127
/*
128
129
@deftypefn Extension char** buildargv (char *@var{sp})
130
131
Given a pointer to a string, parse the string extracting fields
132
separated by whitespace and optionally enclosed within either single
133
or double quotes (which are stripped off), and build a vector of
134
pointers to copies of the string for each field.  The input string
135
remains unchanged.  The last element of the vector is followed by a
136
@code{NULL} element.
137
138
All of the memory for the pointer array and copies of the string
139
is obtained from @code{xmalloc}.  All of the memory can be returned to the
140
system with the single function call @code{freeargv}, which takes the
141
returned result of @code{buildargv}, as it's argument.
142
143
Returns a pointer to the argument vector if successful.  Returns
144
@code{NULL} if @var{sp} is @code{NULL} or if there is insufficient
145
memory to complete building the argument vector.
146
147
If the input is a null string (as opposed to a @code{NULL} pointer),
148
then buildarg returns an argument vector that has one arg, a null
149
string.
150
151
@end deftypefn
152
153
The memory for the argv array is dynamically expanded as necessary.
154
155
In order to provide a working buffer for extracting arguments into,
156
with appropriate stripping of quotes and translation of backslash
157
sequences, we allocate a working buffer at least as long as the input
158
string.  This ensures that we always have enough space in which to
159
work, since the extracted arg is never larger than the input string.
160
161
The argument vector is always kept terminated with a @code{NULL} arg
162
pointer, so it can be passed to @code{freeargv} at any time, or
163
returned, as appropriate.
164
165
*/
166
167
char **buildargv (const char *input)
168
0
{
169
0
  char *arg;
170
0
  char *copybuf;
171
0
  int squote = 0;
172
0
  int dquote = 0;
173
0
  int bsquote = 0;
174
0
  int argc = 0;
175
0
  int maxargc = 0;
176
0
  char **argv = NULL;
177
0
  char **nargv;
178
179
0
  if (input != NULL)
180
0
    {
181
0
      copybuf = (char *) xmalloc (strlen (input) + 1);
182
      /* Is a do{}while to always execute the loop once.  Always return an
183
   argv, even for null strings.  See NOTES above, test case below. */
184
0
      do
185
0
  {
186
    /* Pick off argv[argc] */
187
0
    consume_whitespace (&input);
188
189
0
    if ((maxargc == 0) || (argc >= (maxargc - 1)))
190
0
      {
191
        /* argv needs initialization, or expansion */
192
0
        if (argv == NULL)
193
0
    {
194
0
      maxargc = INITIAL_MAXARGC;
195
0
      nargv = (char **) xmalloc (maxargc * sizeof (char *));
196
0
    }
197
0
        else
198
0
    {
199
0
      maxargc *= 2;
200
0
      nargv = (char **) xrealloc (argv, maxargc * sizeof (char *));
201
0
    }
202
0
        argv = nargv;
203
0
        argv[argc] = NULL;
204
0
      }
205
    /* Begin scanning arg */
206
0
    if (*input != EOS)
207
0
      {
208
0
        arg = copybuf;
209
0
        while (*input != EOS)
210
0
    {
211
0
      if (ISSPACE (*input) && !squote && !dquote && !bsquote)
212
0
        {
213
0
          break;
214
0
        }
215
0
      else
216
0
        {
217
0
          if (bsquote)
218
0
      {
219
0
        bsquote = 0;
220
0
        if (*input != '\n')
221
0
          *arg++ = *input;
222
0
      }
223
0
          else if (*input == '\\'
224
0
             && !squote
225
0
             && (!dquote
226
0
           || strchr ("$`\"\\\n", *(input + 1)) != NULL))
227
0
      {
228
0
        bsquote = 1;
229
0
      }
230
0
          else if (squote)
231
0
      {
232
0
        if (*input == '\'')
233
0
          {
234
0
            squote = 0;
235
0
          }
236
0
        else
237
0
          {
238
0
            *arg++ = *input;
239
0
          }
240
0
      }
241
0
          else if (dquote)
242
0
      {
243
0
        if (*input == '"')
244
0
          {
245
0
            dquote = 0;
246
0
          }
247
0
        else
248
0
          {
249
0
            *arg++ = *input;
250
0
          }
251
0
      }
252
0
          else
253
0
      {
254
0
        if (*input == '\'')
255
0
          {
256
0
            squote = 1;
257
0
          }
258
0
        else if (*input == '"')
259
0
          {
260
0
            dquote = 1;
261
0
          }
262
0
        else
263
0
          {
264
0
            *arg++ = *input;
265
0
          }
266
0
      }
267
0
          input++;
268
0
        }
269
0
    }
270
0
        *arg = EOS;
271
0
        argv[argc] = xstrdup (copybuf);
272
0
        argc++;
273
0
      }
274
0
    argv[argc] = NULL;
275
276
0
    consume_whitespace (&input);
277
0
  }
278
0
      while (*input != EOS);
279
280
0
      free (copybuf);
281
0
    }
282
0
  return (argv);
283
0
}
284
285
/*
286
287
@deftypefn Extension int writeargv (char * const *@var{argv}, FILE *@var{file})
288
289
Write each member of ARGV, handling all necessary quoting, to the file
290
associated with FILE, separated by whitespace.  Return 0 on success,
291
non-zero if an error occurred while writing to FILE.
292
293
@end deftypefn
294
295
*/
296
297
int
298
writeargv (char * const *argv, FILE *f)
299
0
{
300
0
  if (f == NULL)
301
0
    return 1;
302
303
0
  while (*argv != NULL)
304
0
    {
305
0
      const char *arg = *argv;
306
307
0
      while (*arg != EOS)
308
0
        {
309
0
          char c = *arg;
310
311
0
          if (ISSPACE(c) || c == '\\' || c == '\'' || c == '"')
312
0
            if (EOF == fputc ('\\', f))
313
0
              return 1;
314
315
0
          if (EOF == fputc (c, f))
316
0
            return 1;
317
    
318
0
          arg++;
319
0
        }
320
321
      /* Write out a pair of quotes for an empty argument.  */
322
0
      if (arg == *argv)
323
0
        if (EOF == fputs ("\"\"", f))
324
0
          return 1;
325
326
0
      if (EOF == fputc ('\n', f))
327
0
        return 1;
328
      
329
0
      argv++;
330
0
    }
331
332
0
  return 0;
333
0
}
334
335
/*
336
337
@deftypefn Extension void expandargv (int *@var{argcp}, char ***@var{argvp})
338
339
The @var{argcp} and @code{argvp} arguments are pointers to the usual
340
@code{argc} and @code{argv} arguments to @code{main}.  This function
341
looks for arguments that begin with the character @samp{@@}.  Any such
342
arguments are interpreted as ``response files''.  The contents of the
343
response file are interpreted as additional command line options.  In
344
particular, the file is separated into whitespace-separated strings;
345
each such string is taken as a command-line option.  The new options
346
are inserted in place of the option naming the response file, and
347
@code{*argcp} and @code{*argvp} will be updated.  If the value of
348
@code{*argvp} is modified by this function, then the new value has
349
been dynamically allocated and can be deallocated by the caller with
350
@code{freeargv}.  However, most callers will simply call
351
@code{expandargv} near the beginning of @code{main} and allow the
352
operating system to free the memory when the program exits.
353
354
@end deftypefn
355
356
*/
357
358
void
359
expandargv (int *argcp, char ***argvp)
360
28
{
361
  /* The argument we are currently processing.  */
362
28
  int i = 0;
363
  /* To check if ***argvp has been dynamically allocated.  */
364
28
  char ** const original_argv = *argvp;
365
  /* Limit the number of response files that we parse in order
366
     to prevent infinite recursion.  */
367
28
  unsigned int iteration_limit = 2000;
368
  /* Loop over the arguments, handling response files.  We always skip
369
     ARGVP[0], as that is the name of the program being run.  */
370
56
  while (++i < *argcp)
371
28
    {
372
      /* The name of the response file.  */
373
28
      const char *filename;
374
      /* The response file.  */
375
28
      FILE *f;
376
      /* An upper bound on the number of characters in the response
377
   file.  */
378
28
      long pos;
379
      /* The number of characters in the response file, when actually
380
   read.  */
381
28
      size_t len;
382
      /* A dynamically allocated buffer used to hold options read from a
383
   response file.  */
384
28
      char *buffer;
385
      /* Dynamically allocated storage for the options read from the
386
   response file.  */
387
28
      char **file_argv;
388
      /* The number of options read from the response file, if any.  */
389
28
      size_t file_argc;
390
28
#ifdef S_ISDIR
391
28
      struct stat sb;
392
28
#endif
393
      /* We are only interested in options of the form "@file".  */
394
28
      filename = (*argvp)[i];
395
28
      if (filename[0] != '@')
396
28
  continue;
397
      /* If we have iterated too many times then stop.  */
398
0
      if (-- iteration_limit == 0)
399
0
  {
400
0
    fprintf (stderr, "%s: error: too many @-files encountered\n", (*argvp)[0]);
401
0
    xexit (1);
402
0
  }
403
0
#ifdef S_ISDIR
404
0
      if (stat (filename+1, &sb) < 0)
405
0
  continue;
406
0
      if (S_ISDIR(sb.st_mode))
407
0
  {
408
0
    fprintf (stderr, "%s: error: @-file refers to a directory\n", (*argvp)[0]);
409
0
    xexit (1);
410
0
  }
411
0
#endif
412
      /* Read the contents of the file.  */
413
0
      f = fopen (++filename, "r");
414
0
      if (!f)
415
0
  continue;
416
0
      if (fseek (f, 0L, SEEK_END) == -1)
417
0
  goto error;
418
0
      pos = ftell (f);
419
0
      if (pos == -1)
420
0
  goto error;
421
0
      if (fseek (f, 0L, SEEK_SET) == -1)
422
0
  goto error;
423
0
      buffer = (char *) xmalloc (pos * sizeof (char) + 1);
424
0
      len = fread (buffer, sizeof (char), pos, f);
425
0
      if (len != (size_t) pos
426
    /* On Windows, fread may return a value smaller than POS,
427
       due to CR/LF->CR translation when reading text files.
428
       That does not in-and-of itself indicate failure.  */
429
0
    && ferror (f))
430
0
  {
431
0
    free (buffer);
432
0
    goto error;
433
0
  }
434
      /* Add a NUL terminator.  */
435
0
      buffer[len] = '\0';
436
      /* Parse the string.  */
437
0
      file_argv = buildargv (buffer);
438
      /* If *ARGVP is not already dynamically allocated, copy it.  */
439
0
      if (*argvp == original_argv)
440
0
  *argvp = dupargv (*argvp);
441
      /* Count the number of arguments.  */
442
0
      file_argc = 0;
443
0
      while (file_argv[file_argc])
444
0
  ++file_argc;
445
      /* Free the original option's memory.  */
446
0
      free ((*argvp)[i]);
447
      /* Now, insert FILE_ARGV into ARGV.  The "+1" below handles the
448
   NULL terminator at the end of ARGV.  */ 
449
0
      *argvp = ((char **) 
450
0
    xrealloc (*argvp, 
451
0
        (*argcp + file_argc + 1) * sizeof (char *)));
452
0
      memmove (*argvp + i + file_argc, *argvp + i + 1, 
453
0
         (*argcp - i) * sizeof (char *));
454
0
      memcpy (*argvp + i, file_argv, file_argc * sizeof (char *));
455
      /* The original option has been replaced by all the new
456
   options.  */
457
0
      *argcp += file_argc - 1;
458
      /* Free up memory allocated to process the response file.  We do
459
   not use freeargv because the individual options in FILE_ARGV
460
   are now in the main ARGV.  */
461
0
      free (file_argv);
462
0
      free (buffer);
463
      /* Rescan all of the arguments just read to support response
464
   files that include other response files.  */
465
0
      --i;
466
0
    error:
467
      /* We're all done with the file now.  */
468
0
      fclose (f);
469
0
    }
470
28
}
471
472
/*
473
474
@deftypefn Extension int countargv (char * const *@var{argv})
475
476
Return the number of elements in @var{argv}.
477
Returns zero if @var{argv} is NULL.
478
479
@end deftypefn
480
481
*/
482
483
int
484
countargv (char * const *argv)
485
0
{
486
0
  int argc;
487
488
0
  if (argv == NULL)
489
0
    return 0;
490
0
  for (argc = 0; argv[argc] != NULL; argc++)
491
0
    continue;
492
0
  return argc;
493
0
}
494
495
#ifdef MAIN
496
497
/* Simple little test driver. */
498
499
static const char *const tests[] =
500
{
501
  "a simple command line",
502
  "arg 'foo' is single quoted",
503
  "arg \"bar\" is double quoted",
504
  "arg \"foo bar\" has embedded whitespace",
505
  "arg 'Jack said \\'hi\\'' has single quotes",
506
  "arg 'Jack said \\\"hi\\\"' has double quotes",
507
  "a b c d e f g h i j k l m n o p q r s t u v w x y z 1 2 3 4 5 6 7 8 9",
508
  
509
  /* This should be expanded into only one argument.  */
510
  "trailing-whitespace ",
511
512
  "",
513
  NULL
514
};
515
516
int
517
main (void)
518
{
519
  char **argv;
520
  const char *const *test;
521
  char **targs;
522
523
  for (test = tests; *test != NULL; test++)
524
    {
525
      printf ("buildargv(\"%s\")\n", *test);
526
      if ((argv = buildargv (*test)) == NULL)
527
  {
528
    printf ("failed!\n\n");
529
  }
530
      else
531
  {
532
    for (targs = argv; *targs != NULL; targs++)
533
      {
534
        printf ("\t\"%s\"\n", *targs);
535
      }
536
    printf ("\n");
537
  }
538
      freeargv (argv);
539
    }
540
541
  return 0;
542
}
543
544
#endif  /* MAIN */