argv.c 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555
  1. /* Create and destroy argument vectors (argv's)
  2. Copyright (C) 1992-2017 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. if (EOF == fputc ('\n', f))
  272. {
  273. status = 1;
  274. goto done;
  275. }
  276. argv++;
  277. }
  278. done:
  279. return status;
  280. }
  281. /*
  282. @deftypefn Extension void expandargv (int *@var{argcp}, char ***@var{argvp})
  283. The @var{argcp} and @code{argvp} arguments are pointers to the usual
  284. @code{argc} and @code{argv} arguments to @code{main}. This function
  285. looks for arguments that begin with the character @samp{@@}. Any such
  286. arguments are interpreted as ``response files''. The contents of the
  287. response file are interpreted as additional command line options. In
  288. particular, the file is separated into whitespace-separated strings;
  289. each such string is taken as a command-line option. The new options
  290. are inserted in place of the option naming the response file, and
  291. @code{*argcp} and @code{*argvp} will be updated. If the value of
  292. @code{*argvp} is modified by this function, then the new value has
  293. been dynamically allocated and can be deallocated by the caller with
  294. @code{freeargv}. However, most callers will simply call
  295. @code{expandargv} near the beginning of @code{main} and allow the
  296. operating system to free the memory when the program exits.
  297. @end deftypefn
  298. */
  299. void
  300. expandargv (int *argcp, char ***argvp)
  301. {
  302. /* The argument we are currently processing. */
  303. int i = 0;
  304. /* Non-zero if ***argvp has been dynamically allocated. */
  305. int argv_dynamic = 0;
  306. /* Limit the number of response files that we parse in order
  307. to prevent infinite recursion. */
  308. unsigned int iteration_limit = 2000;
  309. /* Loop over the arguments, handling response files. We always skip
  310. ARGVP[0], as that is the name of the program being run. */
  311. while (++i < *argcp)
  312. {
  313. /* The name of the response file. */
  314. const char *filename;
  315. /* The response file. */
  316. FILE *f;
  317. /* An upper bound on the number of characters in the response
  318. file. */
  319. long pos;
  320. /* The number of characters in the response file, when actually
  321. read. */
  322. size_t len;
  323. /* A dynamically allocated buffer used to hold options read from a
  324. response file. */
  325. char *buffer;
  326. /* Dynamically allocated storage for the options read from the
  327. response file. */
  328. char **file_argv;
  329. /* The number of options read from the response file, if any. */
  330. size_t file_argc;
  331. #ifdef S_ISDIR
  332. struct stat sb;
  333. #endif
  334. /* We are only interested in options of the form "@file". */
  335. filename = (*argvp)[i];
  336. if (filename[0] != '@')
  337. continue;
  338. /* If we have iterated too many times then stop. */
  339. if (-- iteration_limit == 0)
  340. {
  341. fprintf (stderr, "%s: error: too many @-files encountered\n", (*argvp)[0]);
  342. xexit (1);
  343. }
  344. #ifdef S_ISDIR
  345. if (stat (filename+1, &sb) < 0)
  346. continue;
  347. if (S_ISDIR(sb.st_mode))
  348. {
  349. fprintf (stderr, "%s: error: @-file refers to a directory\n", (*argvp)[0]);
  350. xexit (1);
  351. }
  352. #endif
  353. /* Read the contents of the file. */
  354. f = fopen (++filename, "r");
  355. if (!f)
  356. continue;
  357. if (fseek (f, 0L, SEEK_END) == -1)
  358. goto error;
  359. pos = ftell (f);
  360. if (pos == -1)
  361. goto error;
  362. if (fseek (f, 0L, SEEK_SET) == -1)
  363. goto error;
  364. buffer = (char *) xmalloc (pos * sizeof (char) + 1);
  365. len = fread (buffer, sizeof (char), pos, f);
  366. if (len != (size_t) pos
  367. /* On Windows, fread may return a value smaller than POS,
  368. due to CR/LF->CR translation when reading text files.
  369. That does not in-and-of itself indicate failure. */
  370. && ferror (f))
  371. goto error;
  372. /* Add a NUL terminator. */
  373. buffer[len] = '\0';
  374. /* If the file is empty or contains only whitespace, buildargv would
  375. return a single empty argument. In this context we want no arguments,
  376. instead. */
  377. if (only_whitespace (buffer))
  378. {
  379. file_argv = (char **) xmalloc (sizeof (char *));
  380. file_argv[0] = NULL;
  381. }
  382. else
  383. /* Parse the string. */
  384. file_argv = buildargv (buffer);
  385. /* If *ARGVP is not already dynamically allocated, copy it. */
  386. if (!argv_dynamic)
  387. *argvp = dupargv (*argvp);
  388. /* Count the number of arguments. */
  389. file_argc = 0;
  390. while (file_argv[file_argc])
  391. ++file_argc;
  392. /* Now, insert FILE_ARGV into ARGV. The "+1" below handles the
  393. NULL terminator at the end of ARGV. */
  394. *argvp = ((char **)
  395. xrealloc (*argvp,
  396. (*argcp + file_argc + 1) * sizeof (char *)));
  397. memmove (*argvp + i + file_argc, *argvp + i + 1,
  398. (*argcp - i) * sizeof (char *));
  399. memcpy (*argvp + i, file_argv, file_argc * sizeof (char *));
  400. /* The original option has been replaced by all the new
  401. options. */
  402. *argcp += file_argc - 1;
  403. /* Free up memory allocated to process the response file. We do
  404. not use freeargv because the individual options in FILE_ARGV
  405. are now in the main ARGV. */
  406. free (file_argv);
  407. free (buffer);
  408. /* Rescan all of the arguments just read to support response
  409. files that include other response files. */
  410. --i;
  411. error:
  412. /* We're all done with the file now. */
  413. fclose (f);
  414. }
  415. }
  416. /*
  417. @deftypefn Extension int countargv (char * const *@var{argv})
  418. Return the number of elements in @var{argv}.
  419. Returns zero if @var{argv} is NULL.
  420. @end deftypefn
  421. */
  422. int
  423. countargv (char * const *argv)
  424. {
  425. int argc;
  426. if (argv == NULL)
  427. return 0;
  428. for (argc = 0; argv[argc] != NULL; argc++)
  429. continue;
  430. return argc;
  431. }
  432. #ifdef MAIN
  433. /* Simple little test driver. */
  434. static const char *const tests[] =
  435. {
  436. "a simple command line",
  437. "arg 'foo' is single quoted",
  438. "arg \"bar\" is double quoted",
  439. "arg \"foo bar\" has embedded whitespace",
  440. "arg 'Jack said \\'hi\\'' has single quotes",
  441. "arg 'Jack said \\\"hi\\\"' has double quotes",
  442. "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",
  443. /* This should be expanded into only one argument. */
  444. "trailing-whitespace ",
  445. "",
  446. NULL
  447. };
  448. int
  449. main (void)
  450. {
  451. char **argv;
  452. const char *const *test;
  453. char **targs;
  454. for (test = tests; *test != NULL; test++)
  455. {
  456. printf ("buildargv(\"%s\")\n", *test);
  457. if ((argv = buildargv (*test)) == NULL)
  458. {
  459. printf ("failed!\n\n");
  460. }
  461. else
  462. {
  463. for (targs = argv; *targs != NULL; targs++)
  464. {
  465. printf ("\t\"%s\"\n", *targs);
  466. }
  467. printf ("\n");
  468. }
  469. freeargv (argv);
  470. }
  471. return 0;
  472. }
  473. #endif /* MAIN */