argv.c 13 KB

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