argv.c 14 KB

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