1 /* Create and destroy argument vectors (argv's)
2 Copyright (C) 1992-2025 Free Software Foundation, Inc.
3 Written by Fred Fish @ Cygnus Support
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.
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.
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. */
22 /* Create and destroy argument vectors. An argument vector is simply an
23 array of string pointers, terminated by a NULL pointer. */
29 #include "libiberty.h"
30 #include "safe-ctype.h"
32 /* Routines imported from standard C runtime libraries. */
38 #include <sys/types.h>
54 #define INITIAL_MAXARGC 8 /* Number of args + NULL in initial argv */
59 @deftypefn Extension char** dupargv (char * const *@var{vector})
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
72 dupargv (char * const *argv
)
81 for (argc
= 0; argv
[argc
] != NULL
; argc
++);
82 copy
= (char **) xmalloc ((argc
+ 1) * sizeof (char *));
85 for (argc
= 0; argv
[argc
] != NULL
; argc
++)
86 copy
[argc
] = xstrdup (argv
[argc
]);
93 @deftypefn Extension void freeargv (char **@var{vector})
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}
104 void freeargv (char **vector
)
106 register char **scan
;
110 for (scan
= vector
; *scan
!= NULL
; scan
++)
119 consume_whitespace (const char **input
)
121 while (ISSPACE (**input
))
129 @deftypefn Extension char** buildargv (char *@var{sp})
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
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.
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.
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
153 The memory for the argv array is dynamically expanded as necessary.
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.
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.
167 char **buildargv (const char *input
)
181 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. */
186 /* Pick off argv[argc] */
187 consume_whitespace (&input
);
189 if ((maxargc
== 0) || (argc
>= (maxargc
- 1)))
191 /* argv needs initialization, or expansion */
194 maxargc
= INITIAL_MAXARGC
;
195 nargv
= (char **) xmalloc (maxargc
* sizeof (char *));
200 nargv
= (char **) xrealloc (argv
, maxargc
* sizeof (char *));
205 /* Begin scanning arg */
209 while (*input
!= EOS
)
211 if (ISSPACE (*input
) && !squote
&& !dquote
&& !bsquote
)
223 else if (*input
== '\\'
226 || strchr ("$`\"\\\n", *(input
+ 1)) != NULL
))
258 else if (*input
== '"')
271 argv
[argc
] = xstrdup (copybuf
);
276 consume_whitespace (&input
);
278 while (*input
!= EOS
);
287 @deftypefn Extension int writeargv (char * const *@var{argv}, FILE *@var{file})
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.
298 writeargv (char * const *argv
, FILE *f
)
303 while (*argv
!= NULL
)
305 const char *arg
= *argv
;
311 if (ISSPACE(c
) || c
== '\\' || c
== '\'' || c
== '"')
312 if (EOF
== fputc ('\\', f
))
315 if (EOF
== fputc (c
, f
))
321 /* Write out a pair of quotes for an empty argument. */
323 if (EOF
== fputs ("\"\"", f
))
326 if (EOF
== fputc ('\n', f
))
337 @deftypefn Extension void expandargv (int *@var{argcp}, char ***@var{argvp})
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.
359 expandargv (int *argcp
, char ***argvp
)
361 /* The argument we are currently processing. */
363 /* To check if ***argvp has been dynamically allocated. */
364 char ** const original_argv
= *argvp
;
365 /* Limit the number of response files that we parse in order
366 to prevent infinite recursion. */
367 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. */
372 /* The name of the response file. */
373 const char *filename
;
374 /* The response file. */
376 /* An upper bound on the number of characters in the response
379 /* The number of characters in the response file, when actually
382 /* A dynamically allocated buffer used to hold options read from a
385 /* Dynamically allocated storage for the options read from the
388 /* The number of options read from the response file, if any. */
393 /* We are only interested in options of the form "@file". */
394 filename
= (*argvp
)[i
];
395 if (filename
[0] != '@')
397 /* If we have iterated too many times then stop. */
398 if (-- iteration_limit
== 0)
400 fprintf (stderr
, "%s: error: too many @-files encountered\n", (*argvp
)[0]);
404 if (stat (filename
+1, &sb
) < 0)
406 if (S_ISDIR(sb
.st_mode
))
408 fprintf (stderr
, "%s: error: @-file refers to a directory\n", (*argvp
)[0]);
412 /* Read the contents of the file. */
413 f
= fopen (++filename
, "r");
416 if (fseek (f
, 0L, SEEK_END
) == -1)
421 if (fseek (f
, 0L, SEEK_SET
) == -1)
423 buffer
= (char *) xmalloc (pos
* sizeof (char) + 1);
424 len
= fread (buffer
, sizeof (char), pos
, f
);
425 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. */
434 /* Add a NUL terminator. */
436 /* Parse the string. */
437 file_argv
= buildargv (buffer
);
438 /* If *ARGVP is not already dynamically allocated, copy it. */
439 if (*argvp
== original_argv
)
440 *argvp
= dupargv (*argvp
);
441 /* Count the number of arguments. */
443 while (file_argv
[file_argc
])
445 /* Free the original option's memory. */
447 /* Now, insert FILE_ARGV into ARGV. The "+1" below handles the
448 NULL terminator at the end of ARGV. */
451 (*argcp
+ file_argc
+ 1) * sizeof (char *)));
452 memmove (*argvp
+ i
+ file_argc
, *argvp
+ i
+ 1,
453 (*argcp
- i
) * sizeof (char *));
454 memcpy (*argvp
+ i
, file_argv
, file_argc
* sizeof (char *));
455 /* The original option has been replaced by all the new
457 *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. */
463 /* Rescan all of the arguments just read to support response
464 files that include other response files. */
467 /* We're all done with the file now. */
474 @deftypefn Extension int countargv (char * const *@var{argv})
476 Return the number of elements in @var{argv}.
477 Returns zero if @var{argv} is NULL.
484 countargv (char * const *argv
)
490 for (argc
= 0; argv
[argc
] != NULL
; argc
++)
497 /* Simple little test driver. */
499 static const char *const tests
[] =
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",
509 /* This should be expanded into only one argument. */
510 "trailing-whitespace ",
520 const char *const *test
;
523 for (test
= tests
; *test
!= NULL
; test
++)
525 printf ("buildargv(\"%s\")\n", *test
);
526 if ((argv
= buildargv (*test
)) == NULL
)
528 printf ("failed!\n\n");
532 for (targs
= argv
; *targs
!= NULL
; targs
++)
534 printf ("\t\"%s\"\n", *targs
);