PageRenderTime 107ms CodeModel.GetById 20ms RepoModel.GetById 0ms app.codeStats 1ms

/src/bin/bash/subst.c

http://github.com/Barrett17/Haiku-services-branch
C | 8841 lines | 7859 code | 439 blank | 543 comment | 787 complexity | d804a2ddf1a7916284077ec07a47ec1e MD5 | raw file
Possible License(s): GPL-2.0, GPL-3.0, LGPL-2.0, LGPL-2.1, BSD-2-Clause, ISC, Apache-2.0, AGPL-1.0, MIT, MPL-2.0-no-copyleft-exception, Unlicense, BSD-3-Clause, LGPL-3.0
  1. /* subst.c -- The part of the shell that does parameter, command, arithmetic,
  2. and globbing substitutions. */
  3. /* ``Have a little faith, there's magic in the night. You ain't a
  4. beauty, but, hey, you're alright.'' */
  5. /* Copyright (C) 1987-2009 Free Software Foundation, Inc.
  6. This file is part of GNU Bash, the Bourne Again SHell.
  7. Bash is free software: you can redistribute it and/or modify
  8. it under the terms of the GNU General Public License as published by
  9. the Free Software Foundation, either version 3 of the License, or
  10. (at your option) any later version.
  11. Bash 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
  14. GNU General Public License for more details.
  15. You should have received a copy of the GNU General Public License
  16. along with Bash. If not, see <http://www.gnu.org/licenses/>.
  17. */
  18. #include "config.h"
  19. #include "bashtypes.h"
  20. #include <stdio.h>
  21. #include "chartypes.h"
  22. #if defined (HAVE_PWD_H)
  23. # include <pwd.h>
  24. #endif
  25. #include <signal.h>
  26. #include <errno.h>
  27. #if defined (HAVE_UNISTD_H)
  28. # include <unistd.h>
  29. #endif
  30. #include "bashansi.h"
  31. #include "posixstat.h"
  32. #include "bashintl.h"
  33. #include "shell.h"
  34. #include "flags.h"
  35. #include "jobs.h"
  36. #include "execute_cmd.h"
  37. #include "filecntl.h"
  38. #include "trap.h"
  39. #include "pathexp.h"
  40. #include "mailcheck.h"
  41. #include "shmbutil.h"
  42. #include "builtins/getopt.h"
  43. #include "builtins/common.h"
  44. #include "builtins/builtext.h"
  45. #include <tilde/tilde.h>
  46. #include <glob/strmatch.h>
  47. #if !defined (errno)
  48. extern int errno;
  49. #endif /* !errno */
  50. /* The size that strings change by. */
  51. #define DEFAULT_INITIAL_ARRAY_SIZE 112
  52. #define DEFAULT_ARRAY_SIZE 128
  53. /* Variable types. */
  54. #define VT_VARIABLE 0
  55. #define VT_POSPARMS 1
  56. #define VT_ARRAYVAR 2
  57. #define VT_ARRAYMEMBER 3
  58. #define VT_ASSOCVAR 4
  59. #define VT_STARSUB 128 /* $* or ${array[*]} -- used to split */
  60. /* Flags for quoted_strchr */
  61. #define ST_BACKSL 0x01
  62. #define ST_CTLESC 0x02
  63. #define ST_SQUOTE 0x04 /* unused yet */
  64. #define ST_DQUOTE 0x08 /* unused yet */
  65. /* Flags for the `pflags' argument to param_expand() */
  66. #define PF_NOCOMSUB 0x01 /* Do not perform command substitution */
  67. #define PF_IGNUNBOUND 0x02 /* ignore unbound vars even if -u set */
  68. /* These defs make it easier to use the editor. */
  69. #define LBRACE '{'
  70. #define RBRACE '}'
  71. #define LPAREN '('
  72. #define RPAREN ')'
  73. /* Evaluates to 1 if C is one of the shell's special parameters whose length
  74. can be taken, but is also one of the special expansion characters. */
  75. #define VALID_SPECIAL_LENGTH_PARAM(c) \
  76. ((c) == '-' || (c) == '?' || (c) == '#')
  77. /* Evaluates to 1 if C is one of the shell's special parameters for which an
  78. indirect variable reference may be made. */
  79. #define VALID_INDIR_PARAM(c) \
  80. ((c) == '#' || (c) == '?' || (c) == '@' || (c) == '*')
  81. /* Evaluates to 1 if C is one of the OP characters that follows the parameter
  82. in ${parameter[:]OPword}. */
  83. #define VALID_PARAM_EXPAND_CHAR(c) (sh_syntaxtab[(unsigned char)c] & CSUBSTOP)
  84. /* Evaluates to 1 if this is one of the shell's special variables. */
  85. #define SPECIAL_VAR(name, wi) \
  86. ((DIGIT (*name) && all_digits (name)) || \
  87. (name[1] == '\0' && (sh_syntaxtab[(unsigned char)*name] & CSPECVAR)) || \
  88. (wi && name[2] == '\0' && VALID_INDIR_PARAM (name[1])))
  89. /* An expansion function that takes a string and a quoted flag and returns
  90. a WORD_LIST *. Used as the type of the third argument to
  91. expand_string_if_necessary(). */
  92. typedef WORD_LIST *EXPFUNC __P((char *, int));
  93. /* Process ID of the last command executed within command substitution. */
  94. pid_t last_command_subst_pid = NO_PID;
  95. pid_t current_command_subst_pid = NO_PID;
  96. /* Variables used to keep track of the characters in IFS. */
  97. SHELL_VAR *ifs_var;
  98. char *ifs_value;
  99. unsigned char ifs_cmap[UCHAR_MAX + 1];
  100. #if defined (HANDLE_MULTIBYTE)
  101. unsigned char ifs_firstc[MB_LEN_MAX];
  102. size_t ifs_firstc_len;
  103. #else
  104. unsigned char ifs_firstc;
  105. #endif
  106. int assigning_in_environment;
  107. /* Extern functions and variables from different files. */
  108. extern int last_command_exit_value, last_command_exit_signal;
  109. extern int subshell_environment;
  110. extern int subshell_level, parse_and_execute_level;
  111. extern int eof_encountered;
  112. extern int return_catch_flag, return_catch_value;
  113. extern pid_t dollar_dollar_pid;
  114. extern int posixly_correct;
  115. extern char *this_command_name;
  116. extern struct fd_bitmap *current_fds_to_close;
  117. extern int wordexp_only;
  118. extern int expanding_redir;
  119. extern int tempenv_assign_error;
  120. #if !defined (HAVE_WCSDUP) && defined (HANDLE_MULTIBYTE)
  121. extern wchar_t *wcsdup __P((const wchar_t *));
  122. #endif
  123. /* Non-zero means to allow unmatched globbed filenames to expand to
  124. a null file. */
  125. int allow_null_glob_expansion;
  126. /* Non-zero means to throw an error when globbing fails to match anything. */
  127. int fail_glob_expansion;
  128. #if 0
  129. /* Variables to keep track of which words in an expanded word list (the
  130. output of expand_word_list_internal) are the result of globbing
  131. expansions. GLOB_ARGV_FLAGS is used by execute_cmd.c.
  132. (CURRENTLY UNUSED). */
  133. char *glob_argv_flags;
  134. static int glob_argv_flags_size;
  135. #endif
  136. static WORD_LIST expand_word_error, expand_word_fatal;
  137. static WORD_DESC expand_wdesc_error, expand_wdesc_fatal;
  138. static char expand_param_error, expand_param_fatal;
  139. static char extract_string_error, extract_string_fatal;
  140. /* Tell the expansion functions to not longjmp back to top_level on fatal
  141. errors. Enabled when doing completion and prompt string expansion. */
  142. static int no_longjmp_on_fatal_error = 0;
  143. /* Set by expand_word_unsplit; used to inhibit splitting and re-joining
  144. $* on $IFS, primarily when doing assignment statements. */
  145. static int expand_no_split_dollar_star = 0;
  146. /* Used to hold a list of variable assignments preceding a command. Global
  147. so the SIGCHLD handler in jobs.c can unwind-protect it when it runs a
  148. SIGCHLD trap. */
  149. WORD_LIST *subst_assign_varlist = (WORD_LIST *)NULL;
  150. /* A WORD_LIST of words to be expanded by expand_word_list_internal,
  151. without any leading variable assignments. */
  152. static WORD_LIST *garglist = (WORD_LIST *)NULL;
  153. static char *quoted_substring __P((char *, int, int));
  154. static int quoted_strlen __P((char *));
  155. static char *quoted_strchr __P((char *, int, int));
  156. static char *expand_string_if_necessary __P((char *, int, EXPFUNC *));
  157. static inline char *expand_string_to_string_internal __P((char *, int, EXPFUNC *));
  158. static WORD_LIST *call_expand_word_internal __P((WORD_DESC *, int, int, int *, int *));
  159. static WORD_LIST *expand_string_internal __P((char *, int));
  160. static WORD_LIST *expand_string_leave_quoted __P((char *, int));
  161. static WORD_LIST *expand_string_for_rhs __P((char *, int, int *, int *));
  162. static WORD_LIST *list_quote_escapes __P((WORD_LIST *));
  163. static char *make_quoted_char __P((int));
  164. static WORD_LIST *quote_list __P((WORD_LIST *));
  165. static int unquoted_substring __P((char *, char *));
  166. static int unquoted_member __P((int, char *));
  167. #if defined (ARRAY_VARS)
  168. static SHELL_VAR *do_compound_assignment __P((char *, char *, int));
  169. #endif
  170. static int do_assignment_internal __P((const WORD_DESC *, int));
  171. static char *string_extract_verbatim __P((char *, size_t, int *, char *, int));
  172. static char *string_extract __P((char *, int *, char *, int));
  173. static char *string_extract_double_quoted __P((char *, int *, int));
  174. static inline char *string_extract_single_quoted __P((char *, int *));
  175. static inline int skip_single_quoted __P((const char *, size_t, int));
  176. static int skip_double_quoted __P((char *, size_t, int));
  177. static char *extract_delimited_string __P((char *, int *, char *, char *, char *, int));
  178. static char *extract_dollar_brace_string __P((char *, int *, int, int));
  179. static int skip_matched_pair __P((const char *, int, int, int, int));
  180. static char *pos_params __P((char *, int, int, int));
  181. static unsigned char *mb_getcharlens __P((char *, int));
  182. static char *remove_upattern __P((char *, char *, int));
  183. #if defined (HANDLE_MULTIBYTE)
  184. static wchar_t *remove_wpattern __P((wchar_t *, size_t, wchar_t *, int));
  185. #endif
  186. static char *remove_pattern __P((char *, char *, int));
  187. static int match_pattern_char __P((char *, char *));
  188. static int match_upattern __P((char *, char *, int, char **, char **));
  189. #if defined (HANDLE_MULTIBYTE)
  190. static int match_pattern_wchar __P((wchar_t *, wchar_t *));
  191. static int match_wpattern __P((wchar_t *, char **, size_t, wchar_t *, int, char **, char **));
  192. #endif
  193. static int match_pattern __P((char *, char *, int, char **, char **));
  194. static int getpatspec __P((int, char *));
  195. static char *getpattern __P((char *, int, int));
  196. static char *variable_remove_pattern __P((char *, char *, int, int));
  197. static char *list_remove_pattern __P((WORD_LIST *, char *, int, int, int));
  198. static char *parameter_list_remove_pattern __P((int, char *, int, int));
  199. #ifdef ARRAY_VARS
  200. static char *array_remove_pattern __P((SHELL_VAR *, char *, int, char *, int));
  201. #endif
  202. static char *parameter_brace_remove_pattern __P((char *, char *, char *, int, int));
  203. static char *process_substitute __P((char *, int));
  204. static char *read_comsub __P((int, int, int *));
  205. #ifdef ARRAY_VARS
  206. static arrayind_t array_length_reference __P((char *));
  207. #endif
  208. static int valid_brace_expansion_word __P((char *, int));
  209. static int chk_atstar __P((char *, int, int *, int *));
  210. static int chk_arithsub __P((const char *, int));
  211. static WORD_DESC *parameter_brace_expand_word __P((char *, int, int, int));
  212. static WORD_DESC *parameter_brace_expand_indir __P((char *, int, int, int *, int *));
  213. static WORD_DESC *parameter_brace_expand_rhs __P((char *, char *, int, int, int *, int *));
  214. static void parameter_brace_expand_error __P((char *, char *));
  215. static int valid_length_expression __P((char *));
  216. static intmax_t parameter_brace_expand_length __P((char *));
  217. static char *skiparith __P((char *, int));
  218. static int verify_substring_values __P((SHELL_VAR *, char *, char *, int, intmax_t *, intmax_t *));
  219. static int get_var_and_type __P((char *, char *, int, SHELL_VAR **, char **));
  220. static char *mb_substring __P((char *, int, int));
  221. static char *parameter_brace_substring __P((char *, char *, char *, int));
  222. static char *pos_params_pat_subst __P((char *, char *, char *, int));
  223. static char *parameter_brace_patsub __P((char *, char *, char *, int));
  224. static char *pos_params_casemod __P((char *, char *, int, int));
  225. static char *parameter_brace_casemod __P((char *, char *, int, char *, int));
  226. static WORD_DESC *parameter_brace_expand __P((char *, int *, int, int *, int *));
  227. static WORD_DESC *param_expand __P((char *, int *, int, int *, int *, int *, int *, int));
  228. static WORD_LIST *expand_word_internal __P((WORD_DESC *, int, int, int *, int *));
  229. static WORD_LIST *word_list_split __P((WORD_LIST *));
  230. static void exp_jump_to_top_level __P((int));
  231. static WORD_LIST *separate_out_assignments __P((WORD_LIST *));
  232. static WORD_LIST *glob_expand_word_list __P((WORD_LIST *, int));
  233. #ifdef BRACE_EXPANSION
  234. static WORD_LIST *brace_expand_word_list __P((WORD_LIST *, int));
  235. #endif
  236. #if defined (ARRAY_VARS)
  237. static int make_internal_declare __P((char *, char *));
  238. #endif
  239. static WORD_LIST *shell_expand_word_list __P((WORD_LIST *, int));
  240. static WORD_LIST *expand_word_list_internal __P((WORD_LIST *, int));
  241. /* **************************************************************** */
  242. /* */
  243. /* Utility Functions */
  244. /* */
  245. /* **************************************************************** */
  246. #ifdef INCLUDE_UNUSED
  247. static char *
  248. quoted_substring (string, start, end)
  249. char *string;
  250. int start, end;
  251. {
  252. register int len, l;
  253. register char *result, *s, *r;
  254. len = end - start;
  255. /* Move to string[start], skipping quoted characters. */
  256. for (s = string, l = 0; *s && l < start; )
  257. {
  258. if (*s == CTLESC)
  259. {
  260. s++;
  261. continue;
  262. }
  263. l++;
  264. if (*s == 0)
  265. break;
  266. }
  267. r = result = (char *)xmalloc (2*len + 1); /* save room for quotes */
  268. /* Copy LEN characters, including quote characters. */
  269. s = string + l;
  270. for (l = 0; l < len; s++)
  271. {
  272. if (*s == CTLESC)
  273. *r++ = *s++;
  274. *r++ = *s;
  275. l++;
  276. if (*s == 0)
  277. break;
  278. }
  279. *r = '\0';
  280. return result;
  281. }
  282. #endif
  283. #ifdef INCLUDE_UNUSED
  284. /* Return the length of S, skipping over quoted characters */
  285. static int
  286. quoted_strlen (s)
  287. char *s;
  288. {
  289. register char *p;
  290. int i;
  291. i = 0;
  292. for (p = s; *p; p++)
  293. {
  294. if (*p == CTLESC)
  295. {
  296. p++;
  297. if (*p == 0)
  298. return (i + 1);
  299. }
  300. i++;
  301. }
  302. return i;
  303. }
  304. #endif
  305. /* Find the first occurrence of character C in string S, obeying shell
  306. quoting rules. If (FLAGS & ST_BACKSL) is non-zero, backslash-escaped
  307. characters are skipped. If (FLAGS & ST_CTLESC) is non-zero, characters
  308. escaped with CTLESC are skipped. */
  309. static char *
  310. quoted_strchr (s, c, flags)
  311. char *s;
  312. int c, flags;
  313. {
  314. register char *p;
  315. for (p = s; *p; p++)
  316. {
  317. if (((flags & ST_BACKSL) && *p == '\\')
  318. || ((flags & ST_CTLESC) && *p == CTLESC))
  319. {
  320. p++;
  321. if (*p == '\0')
  322. return ((char *)NULL);
  323. continue;
  324. }
  325. else if (*p == c)
  326. return p;
  327. }
  328. return ((char *)NULL);
  329. }
  330. /* Return 1 if CHARACTER appears in an unquoted portion of
  331. STRING. Return 0 otherwise. CHARACTER must be a single-byte character. */
  332. static int
  333. unquoted_member (character, string)
  334. int character;
  335. char *string;
  336. {
  337. size_t slen;
  338. int sindex, c;
  339. DECLARE_MBSTATE;
  340. slen = strlen (string);
  341. sindex = 0;
  342. while (c = string[sindex])
  343. {
  344. if (c == character)
  345. return (1);
  346. switch (c)
  347. {
  348. default:
  349. ADVANCE_CHAR (string, slen, sindex);
  350. break;
  351. case '\\':
  352. sindex++;
  353. if (string[sindex])
  354. ADVANCE_CHAR (string, slen, sindex);
  355. break;
  356. case '\'':
  357. sindex = skip_single_quoted (string, slen, ++sindex);
  358. break;
  359. case '"':
  360. sindex = skip_double_quoted (string, slen, ++sindex);
  361. break;
  362. }
  363. }
  364. return (0);
  365. }
  366. /* Return 1 if SUBSTR appears in an unquoted portion of STRING. */
  367. static int
  368. unquoted_substring (substr, string)
  369. char *substr, *string;
  370. {
  371. size_t slen;
  372. int sindex, c, sublen;
  373. DECLARE_MBSTATE;
  374. if (substr == 0 || *substr == '\0')
  375. return (0);
  376. slen = strlen (string);
  377. sublen = strlen (substr);
  378. for (sindex = 0; c = string[sindex]; )
  379. {
  380. if (STREQN (string + sindex, substr, sublen))
  381. return (1);
  382. switch (c)
  383. {
  384. case '\\':
  385. sindex++;
  386. if (string[sindex])
  387. ADVANCE_CHAR (string, slen, sindex);
  388. break;
  389. case '\'':
  390. sindex = skip_single_quoted (string, slen, ++sindex);
  391. break;
  392. case '"':
  393. sindex = skip_double_quoted (string, slen, ++sindex);
  394. break;
  395. default:
  396. ADVANCE_CHAR (string, slen, sindex);
  397. break;
  398. }
  399. }
  400. return (0);
  401. }
  402. /* Most of the substitutions must be done in parallel. In order
  403. to avoid using tons of unclear goto's, I have some functions
  404. for manipulating malloc'ed strings. They all take INDX, a
  405. pointer to an integer which is the offset into the string
  406. where manipulation is taking place. They also take SIZE, a
  407. pointer to an integer which is the current length of the
  408. character array for this string. */
  409. /* Append SOURCE to TARGET at INDEX. SIZE is the current amount
  410. of space allocated to TARGET. SOURCE can be NULL, in which
  411. case nothing happens. Gets rid of SOURCE by freeing it.
  412. Returns TARGET in case the location has changed. */
  413. INLINE char *
  414. sub_append_string (source, target, indx, size)
  415. char *source, *target;
  416. int *indx, *size;
  417. {
  418. if (source)
  419. {
  420. int srclen, n;
  421. srclen = STRLEN (source);
  422. if (srclen >= (int)(*size - *indx))
  423. {
  424. n = srclen + *indx;
  425. n = (n + DEFAULT_ARRAY_SIZE) - (n % DEFAULT_ARRAY_SIZE);
  426. target = (char *)xrealloc (target, (*size = n));
  427. }
  428. FASTCOPY (source, target + *indx, srclen);
  429. *indx += srclen;
  430. target[*indx] = '\0';
  431. free (source);
  432. }
  433. return (target);
  434. }
  435. #if 0
  436. /* UNUSED */
  437. /* Append the textual representation of NUMBER to TARGET.
  438. INDX and SIZE are as in SUB_APPEND_STRING. */
  439. char *
  440. sub_append_number (number, target, indx, size)
  441. intmax_t number;
  442. int *indx, *size;
  443. char *target;
  444. {
  445. char *temp;
  446. temp = itos (number);
  447. return (sub_append_string (temp, target, indx, size));
  448. }
  449. #endif
  450. /* Extract a substring from STRING, starting at SINDEX and ending with
  451. one of the characters in CHARLIST. Don't make the ending character
  452. part of the string. Leave SINDEX pointing at the ending character.
  453. Understand about backslashes in the string. If (flags & SX_VARNAME)
  454. is non-zero, and array variables have been compiled into the shell,
  455. everything between a `[' and a corresponding `]' is skipped over.
  456. If (flags & SX_NOALLOC) is non-zero, don't return the substring, just
  457. update SINDEX. If (flags & SX_REQMATCH) is non-zero, the string must
  458. contain a closing character from CHARLIST. */
  459. static char *
  460. string_extract (string, sindex, charlist, flags)
  461. char *string;
  462. int *sindex;
  463. char *charlist;
  464. int flags;
  465. {
  466. register int c, i;
  467. int found;
  468. size_t slen;
  469. char *temp;
  470. DECLARE_MBSTATE;
  471. slen = (MB_CUR_MAX > 1) ? strlen (string + *sindex) + *sindex : 0;
  472. i = *sindex;
  473. found = 0;
  474. while (c = string[i])
  475. {
  476. if (c == '\\')
  477. {
  478. if (string[i + 1])
  479. i++;
  480. else
  481. break;
  482. }
  483. #if defined (ARRAY_VARS)
  484. else if ((flags & SX_VARNAME) && c == '[')
  485. {
  486. int ni;
  487. /* If this is an array subscript, skip over it and continue. */
  488. ni = skipsubscript (string, i);
  489. if (string[ni] == ']')
  490. i = ni;
  491. }
  492. #endif
  493. else if (MEMBER (c, charlist))
  494. {
  495. found = 1;
  496. break;
  497. }
  498. ADVANCE_CHAR (string, slen, i);
  499. }
  500. /* If we had to have a matching delimiter and didn't find one, return an
  501. error and let the caller deal with it. */
  502. if ((flags & SX_REQMATCH) && found == 0)
  503. {
  504. *sindex = i;
  505. return (&extract_string_error);
  506. }
  507. temp = (flags & SX_NOALLOC) ? (char *)NULL : substring (string, *sindex, i);
  508. *sindex = i;
  509. return (temp);
  510. }
  511. /* Extract the contents of STRING as if it is enclosed in double quotes.
  512. SINDEX, when passed in, is the offset of the character immediately
  513. following the opening double quote; on exit, SINDEX is left pointing after
  514. the closing double quote. If STRIPDQ is non-zero, unquoted double
  515. quotes are stripped and the string is terminated by a null byte.
  516. Backslashes between the embedded double quotes are processed. If STRIPDQ
  517. is zero, an unquoted `"' terminates the string. */
  518. static char *
  519. string_extract_double_quoted (string, sindex, stripdq)
  520. char *string;
  521. int *sindex, stripdq;
  522. {
  523. size_t slen;
  524. char *send;
  525. int j, i, t;
  526. unsigned char c;
  527. char *temp, *ret; /* The new string we return. */
  528. int pass_next, backquote, si; /* State variables for the machine. */
  529. int dquote;
  530. DECLARE_MBSTATE;
  531. slen = strlen (string + *sindex) + *sindex;
  532. send = string + slen;
  533. pass_next = backquote = dquote = 0;
  534. temp = (char *)xmalloc (1 + slen - *sindex);
  535. j = 0;
  536. i = *sindex;
  537. while (c = string[i])
  538. {
  539. /* Process a character that was quoted by a backslash. */
  540. if (pass_next)
  541. {
  542. /* Posix.2 sez:
  543. ``The backslash shall retain its special meaning as an escape
  544. character only when followed by one of the characters:
  545. $ ` " \ <newline>''.
  546. If STRIPDQ is zero, we handle the double quotes here and let
  547. expand_word_internal handle the rest. If STRIPDQ is non-zero,
  548. we have already been through one round of backslash stripping,
  549. and want to strip these backslashes only if DQUOTE is non-zero,
  550. indicating that we are inside an embedded double-quoted string. */
  551. /* If we are in an embedded quoted string, then don't strip
  552. backslashes before characters for which the backslash
  553. retains its special meaning, but remove backslashes in
  554. front of other characters. If we are not in an
  555. embedded quoted string, don't strip backslashes at all.
  556. This mess is necessary because the string was already
  557. surrounded by double quotes (and sh has some really weird
  558. quoting rules).
  559. The returned string will be run through expansion as if
  560. it were double-quoted. */
  561. if ((stripdq == 0 && c != '"') ||
  562. (stripdq && ((dquote && (sh_syntaxtab[c] & CBSDQUOTE)) || dquote == 0)))
  563. temp[j++] = '\\';
  564. pass_next = 0;
  565. add_one_character:
  566. COPY_CHAR_I (temp, j, string, send, i);
  567. continue;
  568. }
  569. /* A backslash protects the next character. The code just above
  570. handles preserving the backslash in front of any character but
  571. a double quote. */
  572. if (c == '\\')
  573. {
  574. pass_next++;
  575. i++;
  576. continue;
  577. }
  578. /* Inside backquotes, ``the portion of the quoted string from the
  579. initial backquote and the characters up to the next backquote
  580. that is not preceded by a backslash, having escape characters
  581. removed, defines that command''. */
  582. if (backquote)
  583. {
  584. if (c == '`')
  585. backquote = 0;
  586. temp[j++] = c;
  587. i++;
  588. continue;
  589. }
  590. if (c == '`')
  591. {
  592. temp[j++] = c;
  593. backquote++;
  594. i++;
  595. continue;
  596. }
  597. /* Pass everything between `$(' and the matching `)' or a quoted
  598. ${ ... } pair through according to the Posix.2 specification. */
  599. if (c == '$' && ((string[i + 1] == LPAREN) || (string[i + 1] == LBRACE)))
  600. {
  601. int free_ret = 1;
  602. si = i + 2;
  603. if (string[i + 1] == LPAREN)
  604. ret = extract_command_subst (string, &si, 0);
  605. else
  606. ret = extract_dollar_brace_string (string, &si, 1, 0);
  607. temp[j++] = '$';
  608. temp[j++] = string[i + 1];
  609. /* Just paranoia; ret will not be 0 unless no_longjmp_on_fatal_error
  610. is set. */
  611. if (ret == 0 && no_longjmp_on_fatal_error)
  612. {
  613. free_ret = 0;
  614. ret = string + i + 2;
  615. }
  616. for (t = 0; ret[t]; t++, j++)
  617. temp[j] = ret[t];
  618. temp[j] = string[si];
  619. if (string[si])
  620. {
  621. j++;
  622. i = si + 1;
  623. }
  624. else
  625. i = si;
  626. if (free_ret)
  627. free (ret);
  628. continue;
  629. }
  630. /* Add any character but a double quote to the quoted string we're
  631. accumulating. */
  632. if (c != '"')
  633. goto add_one_character;
  634. /* c == '"' */
  635. if (stripdq)
  636. {
  637. dquote ^= 1;
  638. i++;
  639. continue;
  640. }
  641. break;
  642. }
  643. temp[j] = '\0';
  644. /* Point to after the closing quote. */
  645. if (c)
  646. i++;
  647. *sindex = i;
  648. return (temp);
  649. }
  650. /* This should really be another option to string_extract_double_quoted. */
  651. static int
  652. skip_double_quoted (string, slen, sind)
  653. char *string;
  654. size_t slen;
  655. int sind;
  656. {
  657. int c, i;
  658. char *ret;
  659. int pass_next, backquote, si;
  660. DECLARE_MBSTATE;
  661. pass_next = backquote = 0;
  662. i = sind;
  663. while (c = string[i])
  664. {
  665. if (pass_next)
  666. {
  667. pass_next = 0;
  668. ADVANCE_CHAR (string, slen, i);
  669. continue;
  670. }
  671. else if (c == '\\')
  672. {
  673. pass_next++;
  674. i++;
  675. continue;
  676. }
  677. else if (backquote)
  678. {
  679. if (c == '`')
  680. backquote = 0;
  681. ADVANCE_CHAR (string, slen, i);
  682. continue;
  683. }
  684. else if (c == '`')
  685. {
  686. backquote++;
  687. i++;
  688. continue;
  689. }
  690. else if (c == '$' && ((string[i + 1] == LPAREN) || (string[i + 1] == LBRACE)))
  691. {
  692. si = i + 2;
  693. if (string[i + 1] == LPAREN)
  694. ret = extract_command_subst (string, &si, SX_NOALLOC);
  695. else
  696. ret = extract_dollar_brace_string (string, &si, 1, SX_NOALLOC);
  697. i = si + 1;
  698. continue;
  699. }
  700. else if (c != '"')
  701. {
  702. ADVANCE_CHAR (string, slen, i);
  703. continue;
  704. }
  705. else
  706. break;
  707. }
  708. if (c)
  709. i++;
  710. return (i);
  711. }
  712. /* Extract the contents of STRING as if it is enclosed in single quotes.
  713. SINDEX, when passed in, is the offset of the character immediately
  714. following the opening single quote; on exit, SINDEX is left pointing after
  715. the closing single quote. */
  716. static inline char *
  717. string_extract_single_quoted (string, sindex)
  718. char *string;
  719. int *sindex;
  720. {
  721. register int i;
  722. size_t slen;
  723. char *t;
  724. DECLARE_MBSTATE;
  725. /* Don't need slen for ADVANCE_CHAR unless multibyte chars possible. */
  726. slen = (MB_CUR_MAX > 1) ? strlen (string + *sindex) + *sindex : 0;
  727. i = *sindex;
  728. while (string[i] && string[i] != '\'')
  729. ADVANCE_CHAR (string, slen, i);
  730. t = substring (string, *sindex, i);
  731. if (string[i])
  732. i++;
  733. *sindex = i;
  734. return (t);
  735. }
  736. static inline int
  737. skip_single_quoted (string, slen, sind)
  738. const char *string;
  739. size_t slen;
  740. int sind;
  741. {
  742. register int c;
  743. DECLARE_MBSTATE;
  744. c = sind;
  745. while (string[c] && string[c] != '\'')
  746. ADVANCE_CHAR (string, slen, c);
  747. if (string[c])
  748. c++;
  749. return c;
  750. }
  751. /* Just like string_extract, but doesn't hack backslashes or any of
  752. that other stuff. Obeys CTLESC quoting. Used to do splitting on $IFS. */
  753. static char *
  754. string_extract_verbatim (string, slen, sindex, charlist, flags)
  755. char *string;
  756. size_t slen;
  757. int *sindex;
  758. char *charlist;
  759. int flags;
  760. {
  761. register int i = *sindex;
  762. #if defined (HANDLE_MULTIBYTE)
  763. size_t clen;
  764. wchar_t *wcharlist;
  765. #endif
  766. int c;
  767. char *temp;
  768. DECLARE_MBSTATE;
  769. if (charlist[0] == '\'' && charlist[1] == '\0')
  770. {
  771. temp = string_extract_single_quoted (string, sindex);
  772. --*sindex; /* leave *sindex at separator character */
  773. return temp;
  774. }
  775. i = *sindex;
  776. #if 0
  777. /* See how the MBLEN and ADVANCE_CHAR macros work to understand why we need
  778. this only if MB_CUR_MAX > 1. */
  779. slen = (MB_CUR_MAX > 1) ? strlen (string + *sindex) + *sindex : 1;
  780. #endif
  781. #if defined (HANDLE_MULTIBYTE)
  782. clen = strlen (charlist);
  783. wcharlist = 0;
  784. #endif
  785. while (c = string[i])
  786. {
  787. #if defined (HANDLE_MULTIBYTE)
  788. size_t mblength;
  789. #endif
  790. if ((flags & SX_NOCTLESC) == 0 && c == CTLESC)
  791. {
  792. i += 2;
  793. continue;
  794. }
  795. /* Even if flags contains SX_NOCTLESC, we let CTLESC quoting CTLNUL
  796. through, to protect the CTLNULs from later calls to
  797. remove_quoted_nulls. */
  798. else if ((flags & SX_NOESCCTLNUL) == 0 && c == CTLESC && string[i+1] == CTLNUL)
  799. {
  800. i += 2;
  801. continue;
  802. }
  803. #if defined (HANDLE_MULTIBYTE)
  804. mblength = MBLEN (string + i, slen - i);
  805. if (mblength > 1)
  806. {
  807. wchar_t wc;
  808. mblength = mbtowc (&wc, string + i, slen - i);
  809. if (MB_INVALIDCH (mblength))
  810. {
  811. if (MEMBER (c, charlist))
  812. break;
  813. }
  814. else
  815. {
  816. if (wcharlist == 0)
  817. {
  818. size_t len;
  819. len = mbstowcs (wcharlist, charlist, 0);
  820. if (len == -1)
  821. len = 0;
  822. wcharlist = (wchar_t *)xmalloc (sizeof (wchar_t) * (len + 1));
  823. mbstowcs (wcharlist, charlist, len + 1);
  824. }
  825. if (wcschr (wcharlist, wc))
  826. break;
  827. }
  828. }
  829. else
  830. #endif
  831. if (MEMBER (c, charlist))
  832. break;
  833. ADVANCE_CHAR (string, slen, i);
  834. }
  835. #if defined (HANDLE_MULTIBYTE)
  836. FREE (wcharlist);
  837. #endif
  838. temp = substring (string, *sindex, i);
  839. *sindex = i;
  840. return (temp);
  841. }
  842. /* Extract the $( construct in STRING, and return a new string.
  843. Start extracting at (SINDEX) as if we had just seen "$(".
  844. Make (SINDEX) get the position of the matching ")". )
  845. XFLAGS is additional flags to pass to other extraction functions, */
  846. char *
  847. extract_command_subst (string, sindex, xflags)
  848. char *string;
  849. int *sindex;
  850. int xflags;
  851. {
  852. if (string[*sindex] == '(') /*)*/
  853. return (extract_delimited_string (string, sindex, "$(", "(", ")", xflags|SX_COMMAND)); /*)*/
  854. else
  855. {
  856. xflags |= (no_longjmp_on_fatal_error ? SX_NOLONGJMP : 0);
  857. return (xparse_dolparen (string, string+*sindex, sindex, xflags));
  858. }
  859. }
  860. /* Extract the $[ construct in STRING, and return a new string. (])
  861. Start extracting at (SINDEX) as if we had just seen "$[".
  862. Make (SINDEX) get the position of the matching "]". */
  863. char *
  864. extract_arithmetic_subst (string, sindex)
  865. char *string;
  866. int *sindex;
  867. {
  868. return (extract_delimited_string (string, sindex, "$[", "[", "]", 0)); /*]*/
  869. }
  870. #if defined (PROCESS_SUBSTITUTION)
  871. /* Extract the <( or >( construct in STRING, and return a new string.
  872. Start extracting at (SINDEX) as if we had just seen "<(".
  873. Make (SINDEX) get the position of the matching ")". */ /*))*/
  874. char *
  875. extract_process_subst (string, starter, sindex)
  876. char *string;
  877. char *starter;
  878. int *sindex;
  879. {
  880. return (extract_delimited_string (string, sindex, starter, "(", ")", 0));
  881. }
  882. #endif /* PROCESS_SUBSTITUTION */
  883. #if defined (ARRAY_VARS)
  884. /* This can be fooled by unquoted right parens in the passed string. If
  885. each caller verifies that the last character in STRING is a right paren,
  886. we don't even need to call extract_delimited_string. */
  887. char *
  888. extract_array_assignment_list (string, sindex)
  889. char *string;
  890. int *sindex;
  891. {
  892. int slen;
  893. char *ret;
  894. slen = strlen (string); /* ( */
  895. if (string[slen - 1] == ')')
  896. {
  897. ret = substring (string, *sindex, slen - 1);
  898. *sindex = slen - 1;
  899. return ret;
  900. }
  901. return 0;
  902. }
  903. #endif
  904. /* Extract and create a new string from the contents of STRING, a
  905. character string delimited with OPENER and CLOSER. SINDEX is
  906. the address of an int describing the current offset in STRING;
  907. it should point to just after the first OPENER found. On exit,
  908. SINDEX gets the position of the last character of the matching CLOSER.
  909. If OPENER is more than a single character, ALT_OPENER, if non-null,
  910. contains a character string that can also match CLOSER and thus
  911. needs to be skipped. */
  912. static char *
  913. extract_delimited_string (string, sindex, opener, alt_opener, closer, flags)
  914. char *string;
  915. int *sindex;
  916. char *opener, *alt_opener, *closer;
  917. int flags;
  918. {
  919. int i, c, si;
  920. size_t slen;
  921. char *t, *result;
  922. int pass_character, nesting_level, in_comment;
  923. int len_closer, len_opener, len_alt_opener;
  924. DECLARE_MBSTATE;
  925. slen = strlen (string + *sindex) + *sindex;
  926. len_opener = STRLEN (opener);
  927. len_alt_opener = STRLEN (alt_opener);
  928. len_closer = STRLEN (closer);
  929. pass_character = in_comment = 0;
  930. nesting_level = 1;
  931. i = *sindex;
  932. while (nesting_level)
  933. {
  934. c = string[i];
  935. if (c == 0)
  936. break;
  937. if (in_comment)
  938. {
  939. if (c == '\n')
  940. in_comment = 0;
  941. ADVANCE_CHAR (string, slen, i);
  942. continue;
  943. }
  944. if (pass_character) /* previous char was backslash */
  945. {
  946. pass_character = 0;
  947. ADVANCE_CHAR (string, slen, i);
  948. continue;
  949. }
  950. /* Not exactly right yet; should handle shell metacharacters and
  951. multibyte characters, too. */
  952. if ((flags & SX_COMMAND) && c == '#' && (i == 0 || string[i - 1] == '\n' || shellblank (string[i - 1])))
  953. {
  954. in_comment = 1;
  955. ADVANCE_CHAR (string, slen, i);
  956. continue;
  957. }
  958. if (c == CTLESC || c == '\\')
  959. {
  960. pass_character++;
  961. i++;
  962. continue;
  963. }
  964. /* Process a nested OPENER. */
  965. if (STREQN (string + i, opener, len_opener))
  966. {
  967. si = i + len_opener;
  968. t = extract_delimited_string (string, &si, opener, alt_opener, closer, flags|SX_NOALLOC);
  969. i = si + 1;
  970. continue;
  971. }
  972. /* Process a nested ALT_OPENER */
  973. if (len_alt_opener && STREQN (string + i, alt_opener, len_alt_opener))
  974. {
  975. si = i + len_alt_opener;
  976. t = extract_delimited_string (string, &si, alt_opener, alt_opener, closer, flags|SX_NOALLOC);
  977. i = si + 1;
  978. continue;
  979. }
  980. /* If the current substring terminates the delimited string, decrement
  981. the nesting level. */
  982. if (STREQN (string + i, closer, len_closer))
  983. {
  984. i += len_closer - 1; /* move to last byte of the closer */
  985. nesting_level--;
  986. if (nesting_level == 0)
  987. break;
  988. }
  989. /* Pass old-style command substitution through verbatim. */
  990. if (c == '`')
  991. {
  992. si = i + 1;
  993. t = string_extract (string, &si, "`", flags|SX_NOALLOC);
  994. i = si + 1;
  995. continue;
  996. }
  997. /* Pass single-quoted and double-quoted strings through verbatim. */
  998. if (c == '\'' || c == '"')
  999. {
  1000. si = i + 1;
  1001. i = (c == '\'') ? skip_single_quoted (string, slen, si)
  1002. : skip_double_quoted (string, slen, si);
  1003. continue;
  1004. }
  1005. /* move past this character, which was not special. */
  1006. ADVANCE_CHAR (string, slen, i);
  1007. }
  1008. if (c == 0 && nesting_level)
  1009. {
  1010. if (no_longjmp_on_fatal_error == 0)
  1011. {
  1012. report_error (_("bad substitution: no closing `%s' in %s"), closer, string);
  1013. last_command_exit_value = EXECUTION_FAILURE;
  1014. exp_jump_to_top_level (DISCARD);
  1015. }
  1016. else
  1017. {
  1018. *sindex = i;
  1019. return (char *)NULL;
  1020. }
  1021. }
  1022. si = i - *sindex - len_closer + 1;
  1023. if (flags & SX_NOALLOC)
  1024. result = (char *)NULL;
  1025. else
  1026. {
  1027. result = (char *)xmalloc (1 + si);
  1028. strncpy (result, string + *sindex, si);
  1029. result[si] = '\0';
  1030. }
  1031. *sindex = i;
  1032. return (result);
  1033. }
  1034. /* Extract a parameter expansion expression within ${ and } from STRING.
  1035. Obey the Posix.2 rules for finding the ending `}': count braces while
  1036. skipping over enclosed quoted strings and command substitutions.
  1037. SINDEX is the address of an int describing the current offset in STRING;
  1038. it should point to just after the first `{' found. On exit, SINDEX
  1039. gets the position of the matching `}'. QUOTED is non-zero if this
  1040. occurs inside double quotes. */
  1041. /* XXX -- this is very similar to extract_delimited_string -- XXX */
  1042. static char *
  1043. extract_dollar_brace_string (string, sindex, quoted, flags)
  1044. char *string;
  1045. int *sindex, quoted, flags;
  1046. {
  1047. register int i, c;
  1048. size_t slen;
  1049. int pass_character, nesting_level, si;
  1050. char *result, *t;
  1051. DECLARE_MBSTATE;
  1052. pass_character = 0;
  1053. nesting_level = 1;
  1054. slen = strlen (string + *sindex) + *sindex;
  1055. i = *sindex;
  1056. while (c = string[i])
  1057. {
  1058. if (pass_character)
  1059. {
  1060. pass_character = 0;
  1061. ADVANCE_CHAR (string, slen, i);
  1062. continue;
  1063. }
  1064. /* CTLESCs and backslashes quote the next character. */
  1065. if (c == CTLESC || c == '\\')
  1066. {
  1067. pass_character++;
  1068. i++;
  1069. continue;
  1070. }
  1071. if (string[i] == '$' && string[i+1] == LBRACE)
  1072. {
  1073. nesting_level++;
  1074. i += 2;
  1075. continue;
  1076. }
  1077. if (c == RBRACE)
  1078. {
  1079. nesting_level--;
  1080. if (nesting_level == 0)
  1081. break;
  1082. i++;
  1083. continue;
  1084. }
  1085. /* Pass the contents of old-style command substitutions through
  1086. verbatim. */
  1087. if (c == '`')
  1088. {
  1089. si = i + 1;
  1090. t = string_extract (string, &si, "`", flags|SX_NOALLOC);
  1091. i = si + 1;
  1092. continue;
  1093. }
  1094. /* Pass the contents of new-style command substitutions and
  1095. arithmetic substitutions through verbatim. */
  1096. if (string[i] == '$' && string[i+1] == LPAREN)
  1097. {
  1098. si = i + 2;
  1099. t = extract_command_subst (string, &si, flags|SX_NOALLOC);
  1100. i = si + 1;
  1101. continue;
  1102. }
  1103. /* Pass the contents of single-quoted and double-quoted strings
  1104. through verbatim. */
  1105. if (c == '\'' || c == '"')
  1106. {
  1107. si = i + 1;
  1108. i = (c == '\'') ? skip_single_quoted (string, slen, si)
  1109. : skip_double_quoted (string, slen, si);
  1110. /* skip_XXX_quoted leaves index one past close quote */
  1111. continue;
  1112. }
  1113. /* move past this character, which was not special. */
  1114. ADVANCE_CHAR (string, slen, i);
  1115. }
  1116. if (c == 0 && nesting_level)
  1117. {
  1118. if (no_longjmp_on_fatal_error == 0)
  1119. { /* { */
  1120. report_error (_("bad substitution: no closing `%s' in %s"), "}", string);
  1121. last_command_exit_value = EXECUTION_FAILURE;
  1122. exp_jump_to_top_level (DISCARD);
  1123. }
  1124. else
  1125. {
  1126. *sindex = i;
  1127. return ((char *)NULL);
  1128. }
  1129. }
  1130. result = (flags & SX_NOALLOC) ? (char *)NULL : substring (string, *sindex, i);
  1131. *sindex = i;
  1132. return (result);
  1133. }
  1134. /* Remove backslashes which are quoting backquotes from STRING. Modifies
  1135. STRING, and returns a pointer to it. */
  1136. char *
  1137. de_backslash (string)
  1138. char *string;
  1139. {
  1140. register size_t slen;
  1141. register int i, j, prev_i;
  1142. DECLARE_MBSTATE;
  1143. slen = strlen (string);
  1144. i = j = 0;
  1145. /* Loop copying string[i] to string[j], i >= j. */
  1146. while (i < slen)
  1147. {
  1148. if (string[i] == '\\' && (string[i + 1] == '`' || string[i + 1] == '\\' ||
  1149. string[i + 1] == '$'))
  1150. i++;
  1151. prev_i = i;
  1152. ADVANCE_CHAR (string, slen, i);
  1153. if (j < prev_i)
  1154. do string[j++] = string[prev_i++]; while (prev_i < i);
  1155. else
  1156. j = i;
  1157. }
  1158. string[j] = '\0';
  1159. return (string);
  1160. }
  1161. #if 0
  1162. /*UNUSED*/
  1163. /* Replace instances of \! in a string with !. */
  1164. void
  1165. unquote_bang (string)
  1166. char *string;
  1167. {
  1168. register int i, j;
  1169. register char *temp;
  1170. temp = (char *)xmalloc (1 + strlen (string));
  1171. for (i = 0, j = 0; (temp[j] = string[i]); i++, j++)
  1172. {
  1173. if (string[i] == '\\' && string[i + 1] == '!')
  1174. {
  1175. temp[j] = '!';
  1176. i++;
  1177. }
  1178. }
  1179. strcpy (string, temp);
  1180. free (temp);
  1181. }
  1182. #endif
  1183. #define CQ_RETURN(x) do { no_longjmp_on_fatal_error = 0; return (x); } while (0)
  1184. /* This function assumes s[i] == open; returns with s[ret] == close; used to
  1185. parse array subscripts. FLAGS currently unused. */
  1186. static int
  1187. skip_matched_pair (string, start, open, close, flags)
  1188. const char *string;
  1189. int start, open, close, flags;
  1190. {
  1191. int i, pass_next, backq, si, c, count;
  1192. size_t slen;
  1193. char *temp, *ss;
  1194. DECLARE_MBSTATE;
  1195. slen = strlen (string + start) + start;
  1196. no_longjmp_on_fatal_error = 1;
  1197. i = start + 1; /* skip over leading bracket */
  1198. count = 1;
  1199. pass_next = backq = 0;
  1200. ss = (char *)string;
  1201. while (c = string[i])
  1202. {
  1203. if (pass_next)
  1204. {
  1205. pass_next = 0;
  1206. if (c == 0)
  1207. CQ_RETURN(i);
  1208. ADVANCE_CHAR (string, slen, i);
  1209. continue;
  1210. }
  1211. else if (c == '\\')
  1212. {
  1213. pass_next = 1;
  1214. i++;
  1215. continue;
  1216. }
  1217. else if (backq)
  1218. {
  1219. if (c == '`')
  1220. backq = 0;
  1221. ADVANCE_CHAR (string, slen, i);
  1222. continue;
  1223. }
  1224. else if (c == '`')
  1225. {
  1226. backq = 1;
  1227. i++;
  1228. continue;
  1229. }
  1230. else if (c == open)
  1231. {
  1232. count++;
  1233. i++;
  1234. continue;
  1235. }
  1236. else if (c == close)
  1237. {
  1238. count--;
  1239. if (count == 0)
  1240. break;
  1241. i++;
  1242. continue;
  1243. }
  1244. else if (c == '\'' || c == '"')
  1245. {
  1246. i = (c == '\'') ? skip_single_quoted (ss, slen, ++i)
  1247. : skip_double_quoted (ss, slen, ++i);
  1248. /* no increment, the skip functions increment past the closing quote. */
  1249. }
  1250. else if (c == '$' && (string[i+1] == LPAREN || string[i+1] == LBRACE))
  1251. {
  1252. si = i + 2;
  1253. if (string[si] == '\0')
  1254. CQ_RETURN(si);
  1255. if (string[i+1] == LPAREN)
  1256. temp = extract_delimited_string (ss, &si, "$(", "(", ")", SX_NOALLOC|SX_COMMAND); /* ) */
  1257. else
  1258. temp = extract_dollar_brace_string (ss, &si, 0, SX_NOALLOC);
  1259. i = si;
  1260. if (string[i] == '\0') /* don't increment i past EOS in loop */
  1261. break;
  1262. i++;
  1263. continue;
  1264. }
  1265. else
  1266. ADVANCE_CHAR (string, slen, i);
  1267. }
  1268. CQ_RETURN(i);
  1269. }
  1270. #if defined (ARRAY_VARS)
  1271. int
  1272. skipsubscript (string, start)
  1273. const char *string;
  1274. int start;
  1275. {
  1276. return (skip_matched_pair (string, start, '[', ']', 0));
  1277. }
  1278. #endif
  1279. /* Skip characters in STRING until we find a character in DELIMS, and return
  1280. the index of that character. START is the index into string at which we
  1281. begin. This is similar in spirit to strpbrk, but it returns an index into
  1282. STRING and takes a starting index. This little piece of code knows quite
  1283. a lot of shell syntax. It's very similar to skip_double_quoted and other
  1284. functions of that ilk. */
  1285. int
  1286. skip_to_delim (string, start, delims, flags)
  1287. char *string;
  1288. int start;
  1289. char *delims;
  1290. int flags;
  1291. {
  1292. int i, pass_next, backq, si, c, invert;
  1293. size_t slen;
  1294. char *temp;
  1295. DECLARE_MBSTATE;
  1296. slen = strlen (string + start) + start;
  1297. if (flags & SD_NOJMP)
  1298. no_longjmp_on_fatal_error = 1;
  1299. invert = (flags & SD_INVERT);
  1300. i = start;
  1301. pass_next = backq = 0;
  1302. while (c = string[i])
  1303. {
  1304. if (pass_next)
  1305. {
  1306. pass_next = 0;
  1307. if (c == 0)
  1308. CQ_RETURN(i);
  1309. ADVANCE_CHAR (string, slen, i);
  1310. continue;
  1311. }
  1312. else if (c == '\\')
  1313. {
  1314. pass_next = 1;
  1315. i++;
  1316. continue;
  1317. }
  1318. else if (backq)
  1319. {
  1320. if (c == '`')
  1321. backq = 0;
  1322. ADVANCE_CHAR (string, slen, i);
  1323. continue;
  1324. }
  1325. else if (c == '`')
  1326. {
  1327. backq = 1;
  1328. i++;
  1329. continue;
  1330. }
  1331. else if (invert == 0 && member (c, delims))
  1332. break;
  1333. else if (c == '\'' || c == '"')
  1334. {
  1335. i = (c == '\'') ? skip_single_quoted (string, slen, ++i)
  1336. : skip_double_quoted (string, slen, ++i);
  1337. /* no increment, the skip functions increment past the closing quote. */
  1338. }
  1339. else if (c == '$' && (string[i+1] == LPAREN || string[i+1] == LBRACE))
  1340. {
  1341. si = i + 2;
  1342. if (string[si] == '\0')
  1343. CQ_RETURN(si);
  1344. if (string[i+1] == LPAREN)
  1345. temp = extract_delimited_string (string, &si, "$(", "(", ")", SX_NOALLOC|SX_COMMAND); /* ) */
  1346. else
  1347. temp = extract_dollar_brace_string (string, &si, 0, SX_NOALLOC);
  1348. i = si;
  1349. if (string[i] == '\0') /* don't increment i past EOS in loop */
  1350. break;
  1351. i++;
  1352. continue;
  1353. }
  1354. else if (invert && (member (c, delims) == 0))
  1355. break;
  1356. else
  1357. ADVANCE_CHAR (string, slen, i);
  1358. }
  1359. CQ_RETURN(i);
  1360. }
  1361. #if defined (READLINE)
  1362. /* Return 1 if the portion of STRING ending at EINDEX is quoted (there is
  1363. an unclosed quoted string), or if the character at EINDEX is quoted
  1364. by a backslash. NO_LONGJMP_ON_FATAL_ERROR is used to flag that the various
  1365. single and double-quoted string parsing functions should not return an
  1366. error if there are unclosed quotes or braces. The characters that this
  1367. recognizes need to be the same as the contents of
  1368. rl_completer_quote_characters. */
  1369. int
  1370. char_is_quoted (string, eindex)
  1371. char *string;
  1372. int eindex;
  1373. {
  1374. int i, pass_next, c;
  1375. size_t slen;
  1376. DECLARE_MBSTATE;
  1377. slen = strlen (string);
  1378. no_longjmp_on_fatal_error = 1;
  1379. i = pass_next = 0;
  1380. while (i <= eindex)
  1381. {
  1382. c = string[i];
  1383. if (pass_next)
  1384. {
  1385. pass_next = 0;
  1386. if (i >= eindex) /* XXX was if (i >= eindex - 1) */
  1387. CQ_RETURN(1);
  1388. ADVANCE_CHAR (string, slen, i);
  1389. continue;
  1390. }
  1391. else if (c == '\\')
  1392. {
  1393. pass_next = 1;
  1394. i++;
  1395. continue;
  1396. }
  1397. else if (c == '\'' || c == '"')
  1398. {
  1399. i = (c == '\'') ? skip_single_quoted (string, slen, ++i)
  1400. : skip_double_quoted (string, slen, ++i);
  1401. if (i > eindex)
  1402. CQ_RETURN(1);
  1403. /* no increment, the skip_xxx functions go one past end */
  1404. }
  1405. else
  1406. ADVANCE_CHAR (string, slen, i);
  1407. }
  1408. CQ_RETURN(0);
  1409. }
  1410. int
  1411. unclosed_pair (string, eindex, openstr)
  1412. char *string;
  1413. int eindex;
  1414. char *openstr;
  1415. {
  1416. int i, pass_next, openc, olen;
  1417. size_t slen;
  1418. DECLARE_MBSTATE;
  1419. slen = strlen (string);
  1420. olen = strlen (openstr);
  1421. i = pass_next = openc = 0;
  1422. while (i <= eindex)
  1423. {
  1424. if (pass_next)
  1425. {
  1426. pass_next = 0;
  1427. if (i >= eindex) /* XXX was if (i >= eindex - 1) */
  1428. return 0;
  1429. ADVANCE_CHAR (string, slen, i);
  1430. continue;
  1431. }
  1432. else if (string[i] == '\\')
  1433. {
  1434. pass_next = 1;
  1435. i++;
  1436. continue;
  1437. }
  1438. else if (STREQN (string + i, openstr, olen))
  1439. {
  1440. openc = 1 - openc;
  1441. i += olen;
  1442. }
  1443. else if (string[i] == '\'' || string[i] == '"')
  1444. {
  1445. i = (string[i] == '\'') ? skip_single_quoted (string, slen, i)
  1446. : skip_double_quoted (string, slen, i);
  1447. if (i > eindex)
  1448. return 0;
  1449. }
  1450. else
  1451. ADVANCE_CHAR (string, slen, i);
  1452. }
  1453. return (openc);
  1454. }
  1455. /* Split STRING (length SLEN) at DELIMS, and return a WORD_LIST with the
  1456. individual words. If DELIMS is NULL, the current value of $IFS is used
  1457. to split the string, and the function follows the shell field splitting
  1458. rules. SENTINEL is an index to look for. NWP, if non-NULL,
  1459. gets the number of words in the returned list. CWP, if non-NULL, gets
  1460. the index of the word containing SENTINEL. Non-whitespace chars in
  1461. DELIMS delimit separate fields. */
  1462. WORD_LIST *
  1463. split_at_delims (string, slen, delims, sentinel, nwp, cwp)
  1464. char *string;
  1465. int slen;
  1466. char *delims;
  1467. int sentinel;
  1468. int *nwp, *cwp;
  1469. {
  1470. int ts, te, i, nw, cw, ifs_split;
  1471. char *token, *d, *d2;
  1472. WORD_LIST *ret, *tl;
  1473. if (string == 0 || *string == '\0')
  1474. {
  1475. if (nwp)
  1476. *nwp = 0;
  1477. if (cwp)
  1478. *cwp = 0;
  1479. return ((WORD_LIST *)NULL);
  1480. }
  1481. d = (delims == 0) ? ifs_value : delims;
  1482. ifs_split = delims == 0;
  1483. /* Make d2 the non-whitespace characters in delims */
  1484. d2 = 0;
  1485. if (delims)
  1486. {
  1487. size_t slength;
  1488. #if defined (HANDLE_MULTIBYTE)
  1489. size_t mblength = 1;
  1490. #endif
  1491. DECLARE_MBSTATE;
  1492. slength = strlen (delims);
  1493. d2 = (char *)xmalloc (slength + 1);
  1494. i = ts = 0;
  1495. while (delims[i])
  1496. {
  1497. #if defined (HANDLE_MULTIBYTE)
  1498. mbstate_t state_bak;
  1499. state_bak = state;
  1500. mblength = MBRLEN (delims + i, slength, &state);
  1501. if (MB_INVALIDCH (mblength))
  1502. state = state_bak;
  1503. else if (mblength > 1)
  1504. {
  1505. memcpy (d2 + ts, delims + i, mblength);
  1506. ts += mblength;
  1507. i += mblength;
  1508. slength -= mblength;
  1509. continue;
  1510. }
  1511. #endif
  1512. if (whitespace (delims[i]) == 0)
  1513. d2[ts++] = delims[i];
  1514. i++;
  1515. slength--;
  1516. }
  1517. d2[ts] = '\0';
  1518. }
  1519. ret = (WORD_LIST *)NULL;
  1520. /* Remove sequences of whitspace characters at the start of the string, as
  1521. long as those characters are delimiters. */
  1522. for (i = 0; member (string[i], d) && spctabnl (string[i]); i++)
  1523. ;
  1524. if (string[i] == '\0')
  1525. return (ret);
  1526. ts = i;
  1527. nw = 0;
  1528. cw = -1;
  1529. while (1)
  1530. {
  1531. te = skip_to_delim (string, ts, d, SD_NOJMP);
  1532. /* If we have a non-whitespace delimiter character, use it to make a
  1533. separate field. This is just about what $IFS splitting does and
  1534. is closer to the behavior of the shell parser. */
  1535. if (ts == te && d2 && member (string[ts], d2))
  1536. {
  1537. te = ts + 1;
  1538. /* If we're using IFS splitting, the non-whitespace delimiter char
  1539. and any additional IFS whitespace delimits a field. */
  1540. if (ifs_split)
  1541. while (member (string[te], d) && spctabnl (string[te]))
  1542. te++;
  1543. else
  1544. while (member (string[te], d2))
  1545. te++;
  1546. }
  1547. token = substring (string, ts, te);
  1548. ret = add_string_to_list (token, ret);
  1549. free (token);
  1550. nw++;
  1551. if (sentinel >= ts && sentinel <= te)
  1552. cw = nw;
  1553. /* If the cursor is at whitespace just before word start, set the
  1554. sentinel word to the current word. */
  1555. if (cwp && cw == -1 && sentinel == ts-1)
  1556. cw = nw;
  1557. /* If the cursor is at whitespace between two words, make a new, empty
  1558. word, add it before (well, after, since the list is in reverse order)
  1559. the word we just added, and set the current word to that one. */
  1560. if (cwp && cw == -1 && sentinel < ts)
  1561. {
  1562. tl = make_word_list (make_word (""), ret->next);
  1563. ret->next = tl;
  1564. cw = nw;
  1565. nw++;
  1566. }
  1567. if (string[te] == 0)
  1568. break;
  1569. i = te;
  1570. while (member (string[i], d) && (ifs_split || spctabnl(string[i])))
  1571. i++;
  1572. if (string[i])
  1573. ts = i;
  1574. else
  1575. break;
  1576. }
  1577. /* Special case for SENTINEL at the end of STRING. If we haven't found
  1578. the word containing SENTINEL yet, and the index we're looking for is at
  1579. the end of STRING, add an additional null argument and set the current
  1580. word pointer to that. */
  1581. if (cwp && cw == -1 && sentinel >= slen)
  1582. {
  1583. if (whitespace (string[sentinel - 1]))
  1584. {
  1585. token = "";
  1586. ret = add_string_to_list (token, ret);
  1587. nw++;
  1588. }
  1589. cw = nw;
  1590. }
  1591. if (nwp)
  1592. *nwp = nw;
  1593. if (cwp)
  1594. *cwp = cw;
  1595. return (REVERSE_LIST (ret, WORD_LIST *));
  1596. }
  1597. #endif /* READLINE */
  1598. #if 0
  1599. /* UNUSED */
  1600. /* Extract the name of the variable to bind to from the assignment string. */
  1601. char *
  1602. assignment_name (string)
  1603. char *string;
  1604. {
  1605. int offset;
  1606. char *temp;
  1607. offset = assignment (string, 0);
  1608. if (offset == 0)
  1609. return (char *)NULL;
  1610. temp = substring (string, 0, offset);
  1611. return (temp);
  1612. }
  1613. #endif
  1614. /* **************************************************************** */
  1615. /* */
  1616. /* Functions to convert strings to WORD_LISTs and vice versa */
  1617. /* */
  1618. /* **************************************************************** */
  1619. /* Return a single string of all the words in LIST. SEP is the separator
  1620. to put between individual elements of LIST in the output string. */
  1621. char *
  1622. string_list_internal (list, sep)
  1623. WORD_LIST *list;
  1624. char *sep;
  1625. {
  1626. register WORD_LIST *t;
  1627. char *result, *r;
  1628. int word_len, sep_len, result_size;
  1629. if (list == 0)
  1630. return ((char *)NULL);
  1631. /* Short-circuit quickly if we don't need to separate anything. */
  1632. if (list->next == 0)
  1633. return (savestring (list->word->word));
  1634. /* This is nearly always called with either sep[0] == 0 or sep[1] == 0. */
  1635. sep_len = STRLEN (sep);
  1636. result_size = 0;
  1637. for (t = list; t; t = t->next)
  1638. {
  1639. if (t != list)
  1640. result_size += sep_len;
  1641. result_size += strlen (t->word->word);
  1642. }
  1643. r = result = (char *)xmalloc (result_size + 1);
  1644. for (t = list; t; t = t->next)
  1645. {
  1646. if (t != list && sep_len)
  1647. {
  1648. if (sep_len > 1)
  1649. {
  1650. FASTCOPY (sep, r, sep_len);
  1651. r += sep_len;
  1652. }
  1653. else
  1654. *r++ = sep[0];
  1655. }
  1656. word_len = strlen (t->word->word);
  1657. FASTCOPY (t->word->word, r, word_len);
  1658. r += word_len;
  1659. }
  1660. *r = '\0';
  1661. return (result);
  1662. }
  1663. /* Return a single string of all the words present in LIST, separating
  1664. each word with a space. */
  1665. char *
  1666. string_list (list)
  1667. WORD_LIST *list;
  1668. {
  1669. return (string_list_internal (list, " "));
  1670. }
  1671. /* An external interface that can be used by the rest of the shell to
  1672. obtain a string containing the first character in $IFS. Handles all
  1673. the multibyte complications. If LENP is non-null, it is set to the
  1674. length of the returned string. */
  1675. char *
  1676. ifs_firstchar (lenp)
  1677. int *lenp;
  1678. {
  1679. char *ret;
  1680. int len;
  1681. ret = xmalloc (MB_LEN_MAX + 1);
  1682. #if defined (HANDLE_MULTIBYTE)
  1683. if (ifs_firstc_len == 1)
  1684. {
  1685. ret[0] = ifs_firstc[0];
  1686. ret[1] = '\0';
  1687. len = ret[0] ? 1 : 0;
  1688. }
  1689. else
  1690. {
  1691. memcpy (ret, ifs_firstc, ifs_firstc_len);
  1692. ret[len = ifs_firstc_len] = '\0';
  1693. }
  1694. #else
  1695. ret[0] = ifs_firstc;
  1696. ret[1] = '\0';
  1697. len = ret[0] ? 0 : 1;
  1698. #endif
  1699. if (lenp)
  1700. *lenp = len;
  1701. return ret;
  1702. }
  1703. /* Return a single string of all the words present in LIST, obeying the
  1704. quoting rules for "$*", to wit: (P1003.2, draft 11, 3.5.2) "If the
  1705. expansion [of $*] appears within a double quoted string, it expands
  1706. to a single field with the value of each parameter separated by the
  1707. first character of the IFS variable, or by a <space> if IFS is unset." */
  1708. char *
  1709. string_list_dollar_star (list)
  1710. WORD_LIST *list;
  1711. {
  1712. char *ret;
  1713. #if defined (HANDLE_MULTIBYTE)
  1714. # if defined (__GNUC__)
  1715. char sep[MB_CUR_MAX + 1];
  1716. # else
  1717. char *sep = 0;
  1718. # endif
  1719. #else
  1720. char sep[2];
  1721. #endif
  1722. #if defined (HANDLE_MULTIBYTE)
  1723. # if !defined (__GNUC__)
  1724. sep = (char *)xmalloc (MB_CUR_MAX + 1);
  1725. # endif /* !__GNUC__ */
  1726. if (ifs_firstc_len == 1)
  1727. {
  1728. sep[0] = ifs_firstc[0];
  1729. sep[1] = '\0';
  1730. }
  1731. else
  1732. {
  1733. memcpy (sep, ifs_firstc, ifs_firstc_len);
  1734. sep[ifs_firstc_len] = '\0';
  1735. }
  1736. #else
  1737. sep[0] = ifs_firstc;
  1738. sep[1] = '\0';
  1739. #endif
  1740. ret = string_list_internal (list, sep);
  1741. #if defined (HANDLE_MULTIBYTE) && !defined (__GNUC__)
  1742. free (sep);
  1743. #endif
  1744. return ret;
  1745. }
  1746. /* Turn $@ into a string. If (quoted & (Q_HERE_DOCUMENT|Q_DOUBLE_QUOTES))
  1747. is non-zero, the $@ appears within double quotes, and we should quote
  1748. the list before converting it into a string. If IFS is unset, and the
  1749. word is not quoted, we just need to quote CTLESC and CTLNUL characters
  1750. in the words in the list, because the default value of $IFS is
  1751. <space><tab><newline>, IFS characters in the words in the list should
  1752. also be split. If IFS is null, and the word is not quoted, we need
  1753. to quote the words in the list to preserve the positional parameters
  1754. exactly. */
  1755. char *
  1756. string_list_dollar_at (list, quoted)
  1757. WORD_LIST *list;
  1758. int quoted;
  1759. {
  1760. char *ifs, *ret;
  1761. #if defined (HANDLE_MULTIBYTE)
  1762. # if defined (__GNUC__)
  1763. char sep[MB_CUR_MAX + 1];
  1764. # else
  1765. char *sep = 0;
  1766. # endif /* !__GNUC__ */
  1767. #else
  1768. char sep[2];
  1769. #endif
  1770. WORD_LIST *tlist;
  1771. /* XXX this could just be ifs = ifs_value; */
  1772. ifs = ifs_var ? value_cell (ifs_var) : (char *)0;
  1773. #if defined (HANDLE_MULTIBYTE)
  1774. # if !defined (__GNUC__)
  1775. sep = (char *)xmalloc (MB_CUR_MAX + 1);
  1776. # endif /* !__GNUC__ */
  1777. if (ifs && *ifs)
  1778. {
  1779. if (ifs_firstc_len == 1)
  1780. {
  1781. sep[0] = ifs_firstc[0];
  1782. sep[1] = '\0';
  1783. }
  1784. else
  1785. {
  1786. memcpy (sep, ifs_firstc, ifs_firstc_len);
  1787. sep[ifs_firstc_len] = '\0';
  1788. }
  1789. }
  1790. else
  1791. {
  1792. sep[0] = ' ';
  1793. sep[1] = '\0';
  1794. }
  1795. #else
  1796. sep[0] = (ifs == 0 || *ifs == 0) ? ' ' : *ifs;
  1797. sep[1] = '\0';
  1798. #endif
  1799. /* XXX -- why call quote_list if ifs == 0? we can get away without doing
  1800. it now that quote_escapes quotes spaces */
  1801. #if 0
  1802. tlist = ((quoted & (Q_HERE_DOCUMENT|Q_DOUBLE_QUOTES)) || (ifs && *ifs == 0))
  1803. #else
  1804. tlist = (quoted & (Q_HERE_DOCUMENT|Q_DOUBLE_QUOTES))
  1805. #endif
  1806. ? quote_list (list)
  1807. : list_quote_escapes (list);
  1808. ret = string_list_internal (tlist, sep);
  1809. #if defined (HANDLE_MULTIBYTE) && !defined (__GNUC__)
  1810. free (sep);
  1811. #endif
  1812. return ret;
  1813. }
  1814. /* Turn the positional paramters into a string, understanding quoting and
  1815. the various subtleties of using the first character of $IFS as the
  1816. separator. Calls string_list_dollar_at, string_list_dollar_star, and
  1817. string_list as appropriate. */
  1818. char *
  1819. string_list_pos_params (pchar, list, quoted)
  1820. int pchar;
  1821. WORD_LIST *list;
  1822. int quoted;
  1823. {
  1824. char *ret;
  1825. WORD_LIST *tlist;
  1826. if (pchar == '*' && (quoted & Q_DOUBLE_QUOTES))
  1827. {
  1828. tlist = quote_list (list);
  1829. word_list_remove_quoted_nulls (tlist);
  1830. ret = string_list_dollar_star (tlist);
  1831. }
  1832. else if (pchar == '*' && (quoted & Q_HERE_DOCUMENT))
  1833. {
  1834. tlist = quote_list (list);
  1835. word_list_remove_quoted_nulls (tlist);
  1836. ret = string_list (tlist);
  1837. }
  1838. else if (pchar == '*')
  1839. {
  1840. /* Even when unquoted, string_list_dollar_star does the right thing
  1841. making sure that the first character of $IFS is used as the
  1842. separator. */
  1843. ret = string_list_dollar_star (list);
  1844. }
  1845. else if (pchar == '@' && (quoted & (Q_HERE_DOCUMENT|Q_DOUBLE_QUOTES)))
  1846. /* We use string_list_dollar_at, but only if the string is quoted, since
  1847. that quotes the escapes if it's not, which we don't want. We could
  1848. use string_list (the old code did), but that doesn't do the right
  1849. thing if the first character of $IFS is not a space. We use
  1850. string_list_dollar_star if the string is unquoted so we make sure that
  1851. the elements of $@ are separated by the first character of $IFS for
  1852. later splitting. */
  1853. ret = string_list_dollar_at (list, quoted);
  1854. else if (pchar == '@')
  1855. ret = string_list_dollar_star (list);
  1856. else
  1857. ret = string_list ((quoted & (Q_HERE_DOCUMENT|Q_DOUBLE_QUOTES)) ? quote_list (list) : list);
  1858. return ret;
  1859. }
  1860. /* Return the list of words present in STRING. Separate the string into
  1861. words at any of the characters found in SEPARATORS. If QUOTED is
  1862. non-zero then word in the list will have its quoted flag set, otherwise
  1863. the quoted flag is left as make_word () deemed fit.
  1864. This obeys the P1003.2 word splitting semantics. If `separators' is
  1865. exactly <space><tab><newline>, then the splitting algorithm is that of
  1866. the Bourne shell, which treats any sequence of characters from `separators'
  1867. as a delimiter. If IFS is unset, which results in `separators' being set
  1868. to "", no splitting occurs. If separators has some other value, the
  1869. following rules are applied (`IFS white space' means zero or more
  1870. occurrences of <space>, <tab>, or <newline>, as long as those characters
  1871. are in `separators'):
  1872. 1) IFS white space is ignored at the start and the end of the
  1873. string.
  1874. 2) Each occurrence of a character in `separators' that is not
  1875. IFS white space, along with any adjacent occurrences of
  1876. IFS white space delimits a field.
  1877. 3) Any nonzero-length sequence of IFS white space delimits a field.
  1878. */
  1879. /* BEWARE! list_string strips null arguments. Don't call it twice and
  1880. expect to have "" preserved! */
  1881. /* This performs word splitting and quoted null character removal on
  1882. STRING. */
  1883. #define issep(c) \
  1884. (((separators)[0]) ? ((separators)[1] ? isifs(c) \
  1885. : (c) == (separators)[0]) \
  1886. : 0)
  1887. WORD_LIST *
  1888. list_string (string, separators, quoted)
  1889. register char *string, *separators;
  1890. int quoted;
  1891. {
  1892. WORD_LIST *result;
  1893. WORD_DESC *t;
  1894. char *current_word, *s;
  1895. int sindex, sh_style_split, whitesep, xflags;
  1896. size_t slen;
  1897. if (!string || !*string)
  1898. return ((WORD_LIST *)NULL);
  1899. sh_style_split = separators && separators[0] == ' ' &&
  1900. separators[1] == '\t' &&
  1901. separators[2] == '\n' &&
  1902. separators[3] == '\0';
  1903. for (xflags = 0, s = ifs_value; s && *s; s++)
  1904. {
  1905. if (*s == CTLESC) xflags |= SX_NOCTLESC;
  1906. else if (*s == CTLNUL) xflags |= SX_NOESCCTLNUL;
  1907. }
  1908. slen = 0;
  1909. /* Remove sequences of whitespace at the beginning of STRING, as
  1910. long as those characters appear in IFS. Do not do this if
  1911. STRING is quoted or if there are no separator characters. */
  1912. if (!quoted || !separators || !*separators)
  1913. {
  1914. for (s = string; *s && spctabnl (*s) && issep (*s); s++);
  1915. if (!*s)
  1916. return ((WORD_LIST *)NULL);
  1917. string = s;
  1918. }
  1919. /* OK, now STRING points to a word that does not begin with white space.
  1920. The splitting algorithm is:
  1921. extract a word, stopping at a separator
  1922. skip sequences of spc, tab, or nl as long as they are separators
  1923. This obeys the field splitting rules in Posix.2. */
  1924. slen = (MB_CUR_MAX > 1) ? strlen (string) : 1;
  1925. for (result = (WORD_LIST *)NULL, sindex = 0; string[sindex]; )
  1926. {
  1927. /* Don't need string length in ADVANCE_CHAR or string_extract_verbatim
  1928. unless multibyte chars are possible. */
  1929. current_word = string_extract_verbatim (string, slen, &sindex, separators, xflags);
  1930. if (current_word == 0)
  1931. break;
  1932. /* If we have a quoted empty string, add a quoted null argument. We
  1933. want to preserve the quoted null character iff this is a quoted
  1934. empty string; otherwise the quoted null characters are removed
  1935. below. */
  1936. if (QUOTED_NULL (current_word))
  1937. {
  1938. t = alloc_word_desc ();
  1939. t->word = make_quoted_char ('\0');
  1940. t->flags |= W_QUOTED|W_HASQUOTEDNULL;
  1941. result = make_word_list (t, result);
  1942. }
  1943. else if (current_word[0] != '\0')
  1944. {
  1945. /* If we have something, then add it regardless. However,
  1946. perform quoted null character removal on the current word. */
  1947. remove_quoted_nulls (current_word);
  1948. result = add_string_to_list (current_word, result);
  1949. result->word->flags &= ~W_HASQUOTEDNULL; /* just to be sure */
  1950. if (quoted & (Q_DOUBLE_QUOTES|Q_HERE_DOCUMENT))
  1951. result->word->flags |= W_QUOTED;
  1952. }
  1953. /* If we're not doing sequences of separators in the traditional
  1954. Bourne shell style, then add a quoted null argument. */
  1955. else if (!sh_style_split && !spctabnl (string[sindex]))
  1956. {
  1957. t = alloc_word_desc ();
  1958. t->word = make_quoted_char ('\0');
  1959. t->flags |= W_QUOTED|W_HASQUOTEDNULL;
  1960. result = make_word_list (t, result);
  1961. }
  1962. free (current_word);
  1963. /* Note whether or not the separator is IFS whitespace, used later. */
  1964. whitesep = string[sindex] && spctabnl (string[sindex]);
  1965. /* Move past the current separator character. */
  1966. if (string[sindex])
  1967. {
  1968. DECLARE_MBSTATE;
  1969. ADVANCE_CHAR (string, slen, sindex);
  1970. }
  1971. /* Now skip sequences of space, tab, or newline characters if they are
  1972. in the list of separators. */
  1973. while (string[sindex] && spctabnl (string[sindex]) && issep (string[sindex]))
  1974. sindex++;
  1975. /* If the first separator was IFS whitespace and the current character
  1976. is a non-whitespace IFS character, it should be part of the current
  1977. field delimiter, not a separate delimiter that would result in an
  1978. empty field. Look at POSIX.2, 3.6.5, (3)(b). */
  1979. if (string[sindex] && whitesep && issep (string[sindex]) && !spctabnl (string[sindex]))
  1980. {
  1981. sindex++;
  1982. /* An IFS character that is not IFS white space, along with any
  1983. adjacent IFS white space, shall delimit a field. (SUSv3) */
  1984. while (string[sindex] && spctabnl (string[sindex]) && isifs (string[sindex]))
  1985. sindex++;
  1986. }
  1987. }
  1988. return (REVERSE_LIST (result, WORD_LIST *));
  1989. }
  1990. /* Parse a single word from STRING, using SEPARATORS to separate fields.
  1991. ENDPTR is set to the first character after the word. This is used by
  1992. the `read' builtin. This is never called with SEPARATORS != $IFS;
  1993. it should be simplified.
  1994. XXX - this function is very similar to list_string; they should be
  1995. combined - XXX */
  1996. char *
  1997. get_word_from_string (stringp, separators, endptr)
  1998. char **stringp, *separators, **endptr;
  1999. {
  2000. register char *s;
  2001. char *current_word;
  2002. int sindex, sh_style_split, whitesep, xflags;
  2003. size_t slen;
  2004. if (!stringp || !*stringp || !**stringp)
  2005. return ((char *)NULL);
  2006. sh_style_split = separators && separators[0] == ' ' &&
  2007. separators[1] == '\t' &&
  2008. separators[2] == '\n' &&
  2009. separators[3] == '\0';
  2010. for (xflags = 0, s = ifs_value; s && *s; s++)
  2011. {
  2012. if (*s == CTLESC) xflags |= SX_NOCTLESC;
  2013. if (*s == CTLNUL) xflags |= SX_NOESCCTLNUL;
  2014. }
  2015. s = *stringp;
  2016. slen = 0;
  2017. /* Remove sequences of whitespace at the beginning of STRING, as
  2018. long as those characters appear in IFS. */
  2019. if (sh_style_split || !separators || !*separators)
  2020. {
  2021. for (; *s && spctabnl (*s) && isifs (*s); s++);
  2022. /* If the string is nothing but whitespace, update it and return. */
  2023. if (!*s)
  2024. {
  2025. *stringp = s;
  2026. if (endptr)
  2027. *endptr = s;
  2028. return ((char *)NULL);
  2029. }
  2030. }
  2031. /* OK, S points to a word that does not begin with white space.
  2032. Now extract a word, stopping at a separator, save a pointer to
  2033. the first character after the word, then skip sequences of spc,
  2034. tab, or nl as long as they are separators.
  2035. This obeys the field splitting rules in Posix.2. */
  2036. sindex = 0;
  2037. /* Don't need string length in ADVANCE_CHAR or string_extract_verbatim
  2038. unless multibyte chars are possible. */
  2039. slen = (MB_CUR_MAX > 1) ? strlen (s) : 1;
  2040. current_word = string_extract_verbatim (s, slen, &sindex, separators, xflags);
  2041. /* Set ENDPTR to the first character after the end of the word. */
  2042. if (endptr)
  2043. *endptr = s + sindex;
  2044. /* Note whether or not the separator is IFS whitespace, used later. */
  2045. whitesep = s[sindex] && spctabnl (s[sindex]);
  2046. /* Move past the current separator character. */
  2047. if (s[sindex])
  2048. {
  2049. DECLARE_MBSTATE;
  2050. ADVANCE_CHAR (s, slen, sindex);
  2051. }
  2052. /* Now skip sequences of space, tab, or newline characters if they are
  2053. in the list of separators. */
  2054. while (s[sindex] && spctabnl (s[sindex]) && isifs (s[sindex]))
  2055. sindex++;
  2056. /* If the first separator was IFS whitespace and the current character is
  2057. a non-whitespace IFS character, it should be part of the current field
  2058. delimiter, not a separate delimiter that would result in an empty field.
  2059. Look at POSIX.2, 3.6.5, (3)(b). */
  2060. if (s[sindex] && whitesep && isifs (s[sindex]) && !spctabnl (s[sindex]))
  2061. {
  2062. sindex++;
  2063. /* An IFS character that is not IFS white space, along with any adjacent
  2064. IFS white space, shall delimit a field. */
  2065. while (s[sindex] && spctabnl (s[sindex]) && isifs (s[sindex]))
  2066. sindex++;
  2067. }
  2068. /* Update STRING to point to the next field. */
  2069. *stringp = s + sindex;
  2070. return (current_word);
  2071. }
  2072. /* Remove IFS white space at the end of STRING. Start at the end
  2073. of the string and walk backwards until the beginning of the string
  2074. or we find a character that's not IFS white space and not CTLESC.
  2075. Only let CTLESC escape a white space character if SAW_ESCAPE is
  2076. non-zero. */
  2077. char *
  2078. strip_trailing_ifs_whitespace (string, separators, saw_escape)
  2079. char *string, *separators;
  2080. int saw_escape;
  2081. {
  2082. char *s;
  2083. s = string + STRLEN (string) - 1;
  2084. while (s > string && ((spctabnl (*s) && isifs (*s)) ||
  2085. (saw_escape && *s == CTLESC && spctabnl (s[1]))))
  2086. s--;
  2087. *++s = '\0';
  2088. return string;
  2089. }
  2090. #if 0
  2091. /* UNUSED */
  2092. /* Split STRING into words at whitespace. Obeys shell-style quoting with
  2093. backslashes, single and double quotes. */
  2094. WORD_LIST *
  2095. list_string_with_quotes (string)
  2096. char *string;
  2097. {
  2098. WORD_LIST *list;
  2099. char *token, *s;
  2100. size_t s_len;
  2101. int c, i, tokstart, len;
  2102. for (s = string; s && *s && spctabnl (*s); s++)
  2103. ;
  2104. if (s == 0 || *s == 0)
  2105. return ((WORD_LIST *)NULL);
  2106. s_len = strlen (s);
  2107. tokstart = i = 0;
  2108. list = (WORD_LIST *)NULL;
  2109. while (1)
  2110. {
  2111. c = s[i];
  2112. if (c == '\\')
  2113. {
  2114. i++;
  2115. if (s[i])
  2116. i++;
  2117. }
  2118. else if (c == '\'')
  2119. i = skip_single_quoted (s, s_len, ++i);
  2120. else if (c == '"')
  2121. i = skip_double_quoted (s, s_len, ++i);
  2122. else if (c == 0 || spctabnl (c))
  2123. {
  2124. /* We have found the end of a token. Make a word out of it and
  2125. add it to the word list. */
  2126. token = substring (s, tokstart, i);
  2127. list = add_string_to_list (token, list);
  2128. free (token);
  2129. while (spctabnl (s[i]))
  2130. i++;
  2131. if (s[i])
  2132. tokstart = i;
  2133. else
  2134. break;
  2135. }
  2136. else
  2137. i++; /* normal character */
  2138. }
  2139. return (REVERSE_LIST (list, WORD_LIST *));
  2140. }
  2141. #endif
  2142. /********************************************************/
  2143. /* */
  2144. /* Functions to perform assignment statements */
  2145. /* */
  2146. /********************************************************/
  2147. #if defined (ARRAY_VARS)
  2148. static SHELL_VAR *
  2149. do_compound_assignment (name, value, flags)
  2150. char *name, *value;
  2151. int flags;
  2152. {
  2153. SHELL_VAR *v;
  2154. int mklocal, mkassoc;
  2155. WORD_LIST *list;
  2156. mklocal = flags & ASS_MKLOCAL;
  2157. mkassoc = flags & ASS_MKASSOC;
  2158. if (mklocal && variable_context)
  2159. {
  2160. v = find_variable (name);
  2161. list = expand_compound_array_assignment (v, value, flags);
  2162. if (mkassoc)
  2163. v = make_local_assoc_variable (name);
  2164. else if (v == 0 || (array_p (v) == 0 && assoc_p (v) == 0) || v->context != variable_context)
  2165. v = make_local_array_variable (name);
  2166. assign_compound_array_list (v, list, flags);
  2167. }
  2168. else
  2169. v = assign_array_from_string (name, value, flags);
  2170. return (v);
  2171. }
  2172. #endif
  2173. /* Given STRING, an assignment string, get the value of the right side
  2174. of the `=', and bind it to the left side. If EXPAND is true, then
  2175. perform parameter expansion, command substitution, and arithmetic
  2176. expansion on the right-hand side. Perform tilde expansion in any
  2177. case. Do not perform word splitting on the result of expansion. */
  2178. static int
  2179. do_assignment_internal (word, expand)
  2180. const WORD_DESC *word;
  2181. int expand;
  2182. {
  2183. int offset, tlen, appendop, assign_list, aflags, retval;
  2184. char *name, *value;
  2185. SHELL_VAR *entry;
  2186. #if defined (ARRAY_VARS)
  2187. char *t;
  2188. int ni;
  2189. #endif
  2190. const char *string;
  2191. if (word == 0 || word->word == 0)
  2192. return 0;
  2193. appendop = assign_list = aflags = 0;
  2194. string = word->word;
  2195. offset = assignment (string, 0);
  2196. name = savestring (string);
  2197. value = (char *)NULL;
  2198. if (name[offset] == '=')
  2199. {
  2200. char *temp;
  2201. if (name[offset - 1] == '+')
  2202. {
  2203. appendop = 1;
  2204. name[offset - 1] = '\0';
  2205. }
  2206. name[offset] = 0; /* might need this set later */
  2207. temp = name + offset + 1;
  2208. tlen = STRLEN (temp);
  2209. #if defined (ARRAY_VARS)
  2210. if (expand && (word->flags & W_COMPASSIGN))
  2211. {
  2212. assign_list = ni = 1;
  2213. value = extract_array_assignment_list (temp, &ni);
  2214. }
  2215. else
  2216. #endif
  2217. if (expand && temp[0])
  2218. value = expand_string_if_necessary (temp, 0, expand_string_assignment);
  2219. else
  2220. value = savestring (temp);
  2221. }
  2222. if (value == 0)
  2223. {
  2224. value = (char *)xmalloc (1);
  2225. value[0] = '\0';
  2226. }
  2227. if (echo_command_at_execute)
  2228. {
  2229. if (appendop)
  2230. name[offset - 1] = '+';
  2231. xtrace_print_assignment (name, value, assign_list, 1);
  2232. if (appendop)
  2233. name[offset - 1] = '\0';
  2234. }
  2235. #define ASSIGN_RETURN(r) do { FREE (value); free (name); return (r); } while (0)
  2236. if (appendop)
  2237. aflags |= ASS_APPEND;
  2238. #if defined (ARRAY_VARS)
  2239. if (t = xstrchr (name, '[')) /*]*/
  2240. {
  2241. if (assign_list)
  2242. {
  2243. report_error (_("%s: cannot assign list to array member"), name);
  2244. ASSIGN_RETURN (0);
  2245. }
  2246. entry = assign_array_element (name, value, aflags);
  2247. if (entry == 0)
  2248. ASSIGN_RETURN (0);
  2249. }
  2250. else if (assign_list)
  2251. {
  2252. if (word->flags & W_ASSIGNARG)
  2253. aflags |= ASS_MKLOCAL;
  2254. if (word->flags & W_ASSIGNASSOC)
  2255. aflags |= ASS_MKASSOC;
  2256. entry = do_compound_assignment (name, value, aflags);
  2257. }
  2258. else
  2259. #endif /* ARRAY_VARS */
  2260. entry = bind_variable (name, value, aflags);
  2261. stupidly_hack_special_variables (name);
  2262. #if 1
  2263. /* Return 1 if the assignment seems to have been performed correctly. */
  2264. if (entry == 0 || readonly_p (entry))
  2265. retval = 0; /* assignment failure */
  2266. else if (noassign_p (entry))
  2267. {
  2268. last_command_exit_value = EXECUTION_FAILURE;
  2269. retval = 1; /* error status, but not assignment failure */
  2270. }
  2271. else
  2272. retval = 1;
  2273. if (entry && retval != 0 && noassign_p (entry) == 0)
  2274. VUNSETATTR (entry, att_invisible);
  2275. ASSIGN_RETURN (retval);
  2276. #else
  2277. if (entry)
  2278. VUNSETATTR (entry, att_invisible);
  2279. ASSIGN_RETURN (entry ? ((readonly_p (entry) == 0) && noassign_p (entry) == 0) : 0);
  2280. #endif
  2281. }
  2282. /* Perform the assignment statement in STRING, and expand the
  2283. right side by doing tilde, command and parameter expansion. */
  2284. int
  2285. do_assignment (string)
  2286. char *string;
  2287. {
  2288. WORD_DESC td;
  2289. td.flags = W_ASSIGNMENT;
  2290. td.word = string;
  2291. return do_assignment_internal (&td, 1);
  2292. }
  2293. int
  2294. do_word_assignment (word)
  2295. WORD_DESC *word;
  2296. {
  2297. return do_assignment_internal (word, 1);
  2298. }
  2299. /* Given STRING, an assignment string, get the value of the right side
  2300. of the `=', and bind it to the left side. Do not perform any word
  2301. expansions on the right hand side. */
  2302. int
  2303. do_assignment_no_expand (string)
  2304. char *string;
  2305. {
  2306. WORD_DESC td;
  2307. td.flags = W_ASSIGNMENT;
  2308. td.word = string;
  2309. return (do_assignment_internal (&td, 0));
  2310. }
  2311. /***************************************************
  2312. * *
  2313. * Functions to manage the positional parameters *
  2314. * *
  2315. ***************************************************/
  2316. /* Return the word list that corresponds to `$*'. */
  2317. WORD_LIST *
  2318. list_rest_of_args ()
  2319. {
  2320. register WORD_LIST *list, *args;
  2321. int i;
  2322. /* Break out of the loop as soon as one of the dollar variables is null. */
  2323. for (i = 1, list = (WORD_LIST *)NULL; i < 10 && dollar_vars[i]; i++)
  2324. list = make_word_list (make_bare_word (dollar_vars[i]), list);
  2325. for (args = rest_of_args; args; args = args->next)
  2326. list = make_word_list (make_bare_word (args->word->word), list);
  2327. return (REVERSE_LIST (list, WORD_LIST *));
  2328. }
  2329. int
  2330. number_of_args ()
  2331. {
  2332. register WORD_LIST *list;
  2333. int n;
  2334. for (n = 0; n < 9 && dollar_vars[n+1]; n++)
  2335. ;
  2336. for (list = rest_of_args; list; list = list->next)
  2337. n++;
  2338. return n;
  2339. }
  2340. /* Return the value of a positional parameter. This handles values > 10. */
  2341. char *
  2342. get_dollar_var_value (ind)
  2343. intmax_t ind;
  2344. {
  2345. char *temp;
  2346. WORD_LIST *p;
  2347. if (ind < 10)
  2348. temp = dollar_vars[ind] ? savestring (dollar_vars[ind]) : (char *)NULL;
  2349. else /* We want something like ${11} */
  2350. {
  2351. ind -= 10;
  2352. for (p = rest_of_args; p && ind--; p = p->next)
  2353. ;
  2354. temp = p ? savestring (p->word->word) : (char *)NULL;
  2355. }
  2356. return (temp);
  2357. }
  2358. /* Make a single large string out of the dollar digit variables,
  2359. and the rest_of_args. If DOLLAR_STAR is 1, then obey the special
  2360. case of "$*" with respect to IFS. */
  2361. char *
  2362. string_rest_of_args (dollar_star)
  2363. int dollar_star;
  2364. {
  2365. register WORD_LIST *list;
  2366. char *string;
  2367. list = list_rest_of_args ();
  2368. string = dollar_star ? string_list_dollar_star (list) : string_list (list);
  2369. dispose_words (list);
  2370. return (string);
  2371. }
  2372. /* Return a string containing the positional parameters from START to
  2373. END, inclusive. If STRING[0] == '*', we obey the rules for $*,
  2374. which only makes a difference if QUOTED is non-zero. If QUOTED includes
  2375. Q_HERE_DOCUMENT or Q_DOUBLE_QUOTES, this returns a quoted list, otherwise
  2376. no quoting chars are added. */
  2377. static char *
  2378. pos_params (string, start, end, quoted)
  2379. char *string;
  2380. int start, end, quoted;
  2381. {
  2382. WORD_LIST *save, *params, *h, *t;
  2383. char *ret;
  2384. int i;
  2385. /* see if we can short-circuit. if start == end, we want 0 parameters. */
  2386. if (start == end)
  2387. return ((char *)NULL);
  2388. save = params = list_rest_of_args ();
  2389. if (save == 0)
  2390. return ((char *)NULL);
  2391. if (start == 0) /* handle ${@:0[:x]} specially */
  2392. {
  2393. t = make_word_list (make_word (dollar_vars[0]), params);
  2394. save = params = t;
  2395. }
  2396. for (i = 1; params && i < start; i++)
  2397. params = params->next;
  2398. if (params == 0)
  2399. return ((char *)NULL);
  2400. for (h = t = params; params && i < end; i++)
  2401. {
  2402. t = params;
  2403. params = params->next;
  2404. }
  2405. t->next = (WORD_LIST *)NULL;
  2406. ret = string_list_pos_params (string[0], h, quoted);
  2407. if (t != params)
  2408. t->next = params;
  2409. dispose_words (save);
  2410. return (ret);
  2411. }
  2412. /******************************************************************/
  2413. /* */
  2414. /* Functions to expand strings to strings or WORD_LISTs */
  2415. /* */
  2416. /******************************************************************/
  2417. #if defined (PROCESS_SUBSTITUTION)
  2418. #define EXP_CHAR(s) (s == '$' || s == '`' || s == '<' || s == '>' || s == CTLESC || s == '~')
  2419. #else
  2420. #define EXP_CHAR(s) (s == '$' || s == '`' || s == CTLESC || s == '~')
  2421. #endif
  2422. /* If there are any characters in STRING that require full expansion,
  2423. then call FUNC to expand STRING; otherwise just perform quote
  2424. removal if necessary. This returns a new string. */
  2425. static char *
  2426. expand_string_if_necessary (string, quoted, func)
  2427. char *string;
  2428. int quoted;
  2429. EXPFUNC *func;
  2430. {
  2431. WORD_LIST *list;
  2432. size_t slen;
  2433. int i, saw_quote;
  2434. char *ret;
  2435. DECLARE_MBSTATE;
  2436. /* Don't need string length for ADVANCE_CHAR unless multibyte chars possible. */
  2437. slen = (MB_CUR_MAX > 1) ? strlen (string) : 0;
  2438. i = saw_quote = 0;
  2439. while (string[i])
  2440. {
  2441. if (EXP_CHAR (string[i]))
  2442. break;
  2443. else if (string[i] == '\'' || string[i] == '\\' || string[i] == '"')
  2444. saw_quote = 1;
  2445. ADVANCE_CHAR (string, slen, i);
  2446. }
  2447. if (string[i])
  2448. {
  2449. list = (*func) (string, quoted);
  2450. if (list)
  2451. {
  2452. ret = string_list (list);
  2453. dispose_words (list);
  2454. }
  2455. else
  2456. ret = (char *)NULL;
  2457. }
  2458. else if (saw_quote && ((quoted & (Q_HERE_DOCUMENT|Q_DOUBLE_QUOTES)) == 0))
  2459. ret = string_quote_removal (string, quoted);
  2460. else
  2461. ret = savestring (string);
  2462. return ret;
  2463. }
  2464. static inline char *
  2465. expand_string_to_string_internal (string, quoted, func)
  2466. char *string;
  2467. int quoted;
  2468. EXPFUNC *func;
  2469. {
  2470. WORD_LIST *list;
  2471. char *ret;
  2472. if (string == 0 || *string == '\0')
  2473. return ((char *)NULL);
  2474. list = (*func) (string, quoted);
  2475. if (list)
  2476. {
  2477. ret = string_list (list);
  2478. dispose_words (list);
  2479. }
  2480. else
  2481. ret = (char *)NULL;
  2482. return (ret);
  2483. }
  2484. char *
  2485. expand_string_to_string (string, quoted)
  2486. char *string;
  2487. int quoted;
  2488. {
  2489. return (expand_string_to_string_internal (string, quoted, expand_string));
  2490. }
  2491. char *
  2492. expand_string_unsplit_to_string (string, quoted)
  2493. char *string;
  2494. int quoted;
  2495. {
  2496. return (expand_string_to_string_internal (string, quoted, expand_string_unsplit));
  2497. }
  2498. char *
  2499. expand_assignment_string_to_string (string, quoted)
  2500. char *string;
  2501. int quoted;
  2502. {
  2503. return (expand_string_to_string_internal (string, quoted, expand_string_assignment));
  2504. }
  2505. char *
  2506. expand_arith_string (string, quoted)
  2507. char *string;
  2508. int quoted;
  2509. {
  2510. return (expand_string_if_necessary (string, quoted, expand_string));
  2511. }
  2512. #if defined (COND_COMMAND)
  2513. /* Just remove backslashes in STRING. Returns a new string. */
  2514. char *
  2515. remove_backslashes (string)
  2516. char *string;
  2517. {
  2518. char *r, *ret, *s;
  2519. r = ret = (char *)xmalloc (strlen (string) + 1);
  2520. for (s = string; s && *s; )
  2521. {
  2522. if (*s == '\\')
  2523. s++;
  2524. if (*s == 0)
  2525. break;
  2526. *r++ = *s++;
  2527. }
  2528. *r = '\0';
  2529. return ret;
  2530. }
  2531. /* This needs better error handling. */
  2532. /* Expand W for use as an argument to a unary or binary operator in a
  2533. [[...]] expression. If SPECIAL is 1, this is the rhs argument
  2534. to the != or == operator, and should be treated as a pattern. In
  2535. this case, we quote the string specially for the globbing code. If
  2536. SPECIAL is 2, this is an rhs argument for the =~ operator, and should
  2537. be quoted appropriately for regcomp/regexec. The caller is responsible
  2538. for removing the backslashes if the unquoted word is needed later. */
  2539. char *
  2540. cond_expand_word (w, special)
  2541. WORD_DESC *w;
  2542. int special;
  2543. {
  2544. char *r, *p;
  2545. WORD_LIST *l;
  2546. int qflags;
  2547. if (w->word == 0 || w->word[0] == '\0')
  2548. return ((char *)NULL);
  2549. l = call_expand_word_internal (w, 0, 0, (int *)0, (int *)0);
  2550. if (l)
  2551. {
  2552. if (special == 0)
  2553. {
  2554. dequote_list (l);
  2555. r = string_list (l);
  2556. }
  2557. else
  2558. {
  2559. qflags = QGLOB_CVTNULL;
  2560. if (special == 2)
  2561. qflags |= QGLOB_REGEXP;
  2562. p = string_list (l);
  2563. r = quote_string_for_globbing (p, qflags);
  2564. free (p);
  2565. }
  2566. dispose_words (l);
  2567. }
  2568. else
  2569. r = (char *)NULL;
  2570. return r;
  2571. }
  2572. #endif
  2573. /* Call expand_word_internal to expand W and handle error returns.
  2574. A convenience function for functions that don't want to handle
  2575. any errors or free any memory before aborting. */
  2576. static WORD_LIST *
  2577. call_expand_word_internal (w, q, i, c, e)
  2578. WORD_DESC *w;
  2579. int q, i, *c, *e;
  2580. {
  2581. WORD_LIST *result;
  2582. result = expand_word_internal (w, q, i, c, e);
  2583. if (result == &expand_word_error || result == &expand_word_fatal)
  2584. {
  2585. /* By convention, each time this error is returned, w->word has
  2586. already been freed (it sometimes may not be in the fatal case,
  2587. but that doesn't result in a memory leak because we're going
  2588. to exit in most cases). */
  2589. w->word = (char *)NULL;
  2590. last_command_exit_value = EXECUTION_FAILURE;
  2591. exp_jump_to_top_level ((result == &expand_word_error) ? DISCARD : FORCE_EOF);
  2592. /* NOTREACHED */
  2593. }
  2594. else
  2595. return (result);
  2596. }
  2597. /* Perform parameter expansion, command substitution, and arithmetic
  2598. expansion on STRING, as if it were a word. Leave the result quoted. */
  2599. static WORD_LIST *
  2600. expand_string_internal (string, quoted)
  2601. char *string;
  2602. int quoted;
  2603. {
  2604. WORD_DESC td;
  2605. WORD_LIST *tresult;
  2606. if (string == 0 || *string == 0)
  2607. return ((WORD_LIST *)NULL);
  2608. td.flags = 0;
  2609. td.word = savestring (string);
  2610. tresult = call_expand_word_internal (&td, quoted, 0, (int *)NULL, (int *)NULL);
  2611. FREE (td.word);
  2612. return (tresult);
  2613. }
  2614. /* Expand STRING by performing parameter expansion, command substitution,
  2615. and arithmetic expansion. Dequote the resulting WORD_LIST before
  2616. returning it, but do not perform word splitting. The call to
  2617. remove_quoted_nulls () is in here because word splitting normally
  2618. takes care of quote removal. */
  2619. WORD_LIST *
  2620. expand_string_unsplit (string, quoted)
  2621. char *string;
  2622. int quoted;
  2623. {
  2624. WORD_LIST *value;
  2625. if (string == 0 || *string == '\0')
  2626. return ((WORD_LIST *)NULL);
  2627. expand_no_split_dollar_star = 1;
  2628. value = expand_string_internal (string, quoted);
  2629. expand_no_split_dollar_star = 0;
  2630. if (value)
  2631. {
  2632. if (value->word)
  2633. {
  2634. remove_quoted_nulls (value->word->word);
  2635. value->word->flags &= ~W_HASQUOTEDNULL;
  2636. }
  2637. dequote_list (value);
  2638. }
  2639. return (value);
  2640. }
  2641. /* Expand the rhs of an assignment statement */
  2642. WORD_LIST *
  2643. expand_string_assignment (string, quoted)
  2644. char *string;
  2645. int quoted;
  2646. {
  2647. WORD_DESC td;
  2648. WORD_LIST *value;
  2649. if (string == 0 || *string == '\0')
  2650. return ((WORD_LIST *)NULL);
  2651. expand_no_split_dollar_star = 1;
  2652. td.flags = W_ASSIGNRHS;
  2653. td.word = savestring (string);
  2654. value = call_expand_word_internal (&td, quoted, 0, (int *)NULL, (int *)NULL);
  2655. FREE (td.word);
  2656. expand_no_split_dollar_star = 0;
  2657. if (value)
  2658. {
  2659. if (value->word)
  2660. {
  2661. remove_quoted_nulls (value->word->word);
  2662. value->word->flags &= ~W_HASQUOTEDNULL;
  2663. }
  2664. dequote_list (value);
  2665. }
  2666. return (value);
  2667. }
  2668. /* Expand one of the PS? prompt strings. This is a sort of combination of
  2669. expand_string_unsplit and expand_string_internal, but returns the
  2670. passed string when an error occurs. Might want to trap other calls
  2671. to jump_to_top_level here so we don't endlessly loop. */
  2672. WORD_LIST *
  2673. expand_prompt_string (string, quoted, wflags)
  2674. char *string;
  2675. int quoted;
  2676. int wflags;
  2677. {
  2678. WORD_LIST *value;
  2679. WORD_DESC td;
  2680. if (string == 0 || *string == 0)
  2681. return ((WORD_LIST *)NULL);
  2682. td.flags = wflags;
  2683. td.word = savestring (string);
  2684. no_longjmp_on_fatal_error = 1;
  2685. value = expand_word_internal (&td, quoted, 0, (int *)NULL, (int *)NULL);
  2686. no_longjmp_on_fatal_error = 0;
  2687. if (value == &expand_word_error || value == &expand_word_fatal)
  2688. {
  2689. value = make_word_list (make_bare_word (string), (WORD_LIST *)NULL);
  2690. return value;
  2691. }
  2692. FREE (td.word);
  2693. if (value)
  2694. {
  2695. if (value->word)
  2696. {
  2697. remove_quoted_nulls (value->word->word);
  2698. value->word->flags &= ~W_HASQUOTEDNULL;
  2699. }
  2700. dequote_list (value);
  2701. }
  2702. return (value);
  2703. }
  2704. /* Expand STRING just as if you were expanding a word, but do not dequote
  2705. the resultant WORD_LIST. This is called only from within this file,
  2706. and is used to correctly preserve quoted characters when expanding
  2707. things like ${1+"$@"}. This does parameter expansion, command
  2708. substitution, arithmetic expansion, and word splitting. */
  2709. static WORD_LIST *
  2710. expand_string_leave_quoted (string, quoted)
  2711. char *string;
  2712. int quoted;
  2713. {
  2714. WORD_LIST *tlist;
  2715. WORD_LIST *tresult;
  2716. if (string == 0 || *string == '\0')
  2717. return ((WORD_LIST *)NULL);
  2718. tlist = expand_string_internal (string, quoted);
  2719. if (tlist)
  2720. {
  2721. tresult = word_list_split (tlist);
  2722. dispose_words (tlist);
  2723. return (tresult);
  2724. }
  2725. return ((WORD_LIST *)NULL);
  2726. }
  2727. /* This does not perform word splitting or dequote the WORD_LIST
  2728. it returns. */
  2729. static WORD_LIST *
  2730. expand_string_for_rhs (string, quoted, dollar_at_p, has_dollar_at)
  2731. char *string;
  2732. int quoted, *dollar_at_p, *has_dollar_at;
  2733. {
  2734. WORD_DESC td;
  2735. WORD_LIST *tresult;
  2736. if (string == 0 || *string == '\0')
  2737. return (WORD_LIST *)NULL;
  2738. td.flags = 0;
  2739. td.word = string;
  2740. tresult = call_expand_word_internal (&td, quoted, 1, dollar_at_p, has_dollar_at);
  2741. return (tresult);
  2742. }
  2743. /* Expand STRING just as if you were expanding a word. This also returns
  2744. a list of words. Note that filename globbing is *NOT* done for word
  2745. or string expansion, just when the shell is expanding a command. This
  2746. does parameter expansion, command substitution, arithmetic expansion,
  2747. and word splitting. Dequote the resultant WORD_LIST before returning. */
  2748. WORD_LIST *
  2749. expand_string (string, quoted)
  2750. char *string;
  2751. int quoted;
  2752. {
  2753. WORD_LIST *result;
  2754. if (string == 0 || *string == '\0')
  2755. return ((WORD_LIST *)NULL);
  2756. result = expand_string_leave_quoted (string, quoted);
  2757. return (result ? dequote_list (result) : result);
  2758. }
  2759. /***************************************************
  2760. * *
  2761. * Functions to handle quoting chars *
  2762. * *
  2763. ***************************************************/
  2764. /* Conventions:
  2765. A string with s[0] == CTLNUL && s[1] == 0 is a quoted null string.
  2766. The parser passes CTLNUL as CTLESC CTLNUL. */
  2767. /* Quote escape characters in string s, but no other characters. This is
  2768. used to protect CTLESC and CTLNUL in variable values from the rest of
  2769. the word expansion process after the variable is expanded (word splitting
  2770. and filename generation). If IFS is null, we quote spaces as well, just
  2771. in case we split on spaces later (in the case of unquoted $@, we will
  2772. eventually attempt to split the entire word on spaces). Corresponding
  2773. code exists in dequote_escapes. Even if we don't end up splitting on
  2774. spaces, quoting spaces is not a problem. This should never be called on
  2775. a string that is quoted with single or double quotes or part of a here
  2776. document (effectively double-quoted). */
  2777. char *
  2778. quote_escapes (string)
  2779. char *string;
  2780. {
  2781. register char *s, *t;
  2782. size_t slen;
  2783. char *result, *send;
  2784. int quote_spaces, skip_ctlesc, skip_ctlnul;
  2785. DECLARE_MBSTATE;
  2786. slen = strlen (string);
  2787. send = string + slen;
  2788. quote_spaces = (ifs_value && *ifs_value == 0);
  2789. for (skip_ctlesc = skip_ctlnul = 0, s = ifs_value; s && *s; s++)
  2790. skip_ctlesc |= *s == CTLESC, skip_ctlnul |= *s == CTLNUL;
  2791. t = result = (char *)xmalloc ((slen * 2) + 1);
  2792. s = string;
  2793. while (*s)
  2794. {
  2795. if ((skip_ctlesc == 0 && *s == CTLESC) || (skip_ctlnul == 0 && *s == CTLNUL) || (quote_spaces && *s == ' '))
  2796. *t++ = CTLESC;
  2797. COPY_CHAR_P (t, s, send);
  2798. }
  2799. *t = '\0';
  2800. return (result);
  2801. }
  2802. static WORD_LIST *
  2803. list_quote_escapes (list)
  2804. WORD_LIST *list;
  2805. {
  2806. register WORD_LIST *w;
  2807. char *t;
  2808. for (w = list; w; w = w->next)
  2809. {
  2810. t = w->word->word;
  2811. w->word->word = quote_escapes (t);
  2812. free (t);
  2813. }
  2814. return list;
  2815. }
  2816. /* Inverse of quote_escapes; remove CTLESC protecting CTLESC or CTLNUL.
  2817. The parser passes us CTLESC as CTLESC CTLESC and CTLNUL as CTLESC CTLNUL.
  2818. This is necessary to make unquoted CTLESC and CTLNUL characters in the
  2819. data stream pass through properly.
  2820. We need to remove doubled CTLESC characters inside quoted strings before
  2821. quoting the entire string, so we do not double the number of CTLESC
  2822. characters.
  2823. Also used by parts of the pattern substitution code. */
  2824. char *
  2825. dequote_escapes (string)
  2826. char *string;
  2827. {
  2828. register char *s, *t, *s1;
  2829. size_t slen;
  2830. char *result, *send;
  2831. int quote_spaces;
  2832. DECLARE_MBSTATE;
  2833. if (string == 0)
  2834. return string;
  2835. slen = strlen (string);
  2836. send = string + slen;
  2837. t = result = (char *)xmalloc (slen + 1);
  2838. if (strchr (string, CTLESC) == 0)
  2839. return (strcpy (result, string));
  2840. quote_spaces = (ifs_value && *ifs_value == 0);
  2841. s = string;
  2842. while (*s)
  2843. {
  2844. if (*s == CTLESC && (s[1] == CTLESC || s[1] == CTLNUL || (quote_spaces && s[1] == ' ')))
  2845. {
  2846. s++;
  2847. if (*s == '\0')
  2848. break;
  2849. }
  2850. COPY_CHAR_P (t, s, send);
  2851. }
  2852. *t = '\0';
  2853. return result;
  2854. }
  2855. /* Return a new string with the quoted representation of character C.
  2856. This turns "" into QUOTED_NULL, so the W_HASQUOTEDNULL flag needs to be
  2857. set in any resultant WORD_DESC where this value is the word. */
  2858. static char *
  2859. make_quoted_char (c)
  2860. int c;
  2861. {
  2862. char *temp;
  2863. temp = (char *)xmalloc (3);
  2864. if (c == 0)
  2865. {
  2866. temp[0] = CTLNUL;
  2867. temp[1] = '\0';
  2868. }
  2869. else
  2870. {
  2871. temp[0] = CTLESC;
  2872. temp[1] = c;
  2873. temp[2] = '\0';
  2874. }
  2875. return (temp);
  2876. }
  2877. /* Quote STRING, returning a new string. This turns "" into QUOTED_NULL, so
  2878. the W_HASQUOTEDNULL flag needs to be set in any resultant WORD_DESC where
  2879. this value is the word. */
  2880. char *
  2881. quote_string (string)
  2882. char *string;
  2883. {
  2884. register char *t;
  2885. size_t slen;
  2886. char *result, *send;
  2887. if (*string == 0)
  2888. {
  2889. result = (char *)xmalloc (2);
  2890. result[0] = CTLNUL;
  2891. result[1] = '\0';
  2892. }
  2893. else
  2894. {
  2895. DECLARE_MBSTATE;
  2896. slen = strlen (string);
  2897. send = string + slen;
  2898. result = (char *)xmalloc ((slen * 2) + 1);
  2899. for (t = result; string < send; )
  2900. {
  2901. *t++ = CTLESC;
  2902. COPY_CHAR_P (t, string, send);
  2903. }
  2904. *t = '\0';
  2905. }
  2906. return (result);
  2907. }
  2908. /* De-quote quoted characters in STRING. */
  2909. char *
  2910. dequote_string (string)
  2911. char *string;
  2912. {
  2913. register char *s, *t;
  2914. size_t slen;
  2915. char *result, *send;
  2916. DECLARE_MBSTATE;
  2917. slen = strlen (string);
  2918. t = result = (char *)xmalloc (slen + 1);
  2919. if (QUOTED_NULL (string))
  2920. {
  2921. result[0] = '\0';
  2922. return (result);
  2923. }
  2924. /* If no character in the string can be quoted, don't bother examining
  2925. each character. Just return a copy of the string passed to us. */
  2926. if (strchr (string, CTLESC) == NULL)
  2927. return (strcpy (result, string));
  2928. send = string + slen;
  2929. s = string;
  2930. while (*s)
  2931. {
  2932. if (*s == CTLESC)
  2933. {
  2934. s++;
  2935. if (*s == '\0')
  2936. break;
  2937. }
  2938. COPY_CHAR_P (t, s, send);
  2939. }
  2940. *t = '\0';
  2941. return (result);
  2942. }
  2943. /* Quote the entire WORD_LIST list. */
  2944. static WORD_LIST *
  2945. quote_list (list)
  2946. WORD_LIST *list;
  2947. {
  2948. register WORD_LIST *w;
  2949. char *t;
  2950. for (w = list; w; w = w->next)
  2951. {
  2952. t = w->word->word;
  2953. w->word->word = quote_string (t);
  2954. if (*t == 0)
  2955. w->word->flags |= W_HASQUOTEDNULL; /* XXX - turn on W_HASQUOTEDNULL here? */
  2956. w->word->flags |= W_QUOTED;
  2957. free (t);
  2958. }
  2959. return list;
  2960. }
  2961. /* De-quote quoted characters in each word in LIST. */
  2962. WORD_LIST *
  2963. dequote_list (list)
  2964. WORD_LIST *list;
  2965. {
  2966. register char *s;
  2967. register WORD_LIST *tlist;
  2968. for (tlist = list; tlist; tlist = tlist->next)
  2969. {
  2970. s = dequote_string (tlist->word->word);
  2971. if (QUOTED_NULL (tlist->word->word))
  2972. tlist->word->flags &= ~W_HASQUOTEDNULL;
  2973. free (tlist->word->word);
  2974. tlist->word->word = s;
  2975. }
  2976. return list;
  2977. }
  2978. /* Remove CTLESC protecting a CTLESC or CTLNUL in place. Return the passed
  2979. string. */
  2980. char *
  2981. remove_quoted_escapes (string)
  2982. char *string;
  2983. {
  2984. char *t;
  2985. if (string)
  2986. {
  2987. t = dequote_escapes (string);
  2988. strcpy (string, t);
  2989. free (t);
  2990. }
  2991. return (string);
  2992. }
  2993. /* Perform quoted null character removal on STRING. We don't allow any
  2994. quoted null characters in the middle or at the ends of strings because
  2995. of how expand_word_internal works. remove_quoted_nulls () turns
  2996. STRING into an empty string iff it only consists of a quoted null,
  2997. and removes all unquoted CTLNUL characters. */
  2998. char *
  2999. remove_quoted_nulls (string)
  3000. char *string;
  3001. {
  3002. register size_t slen;
  3003. register int i, j, prev_i;
  3004. DECLARE_MBSTATE;
  3005. if (strchr (string, CTLNUL) == 0) /* XXX */
  3006. return string; /* XXX */
  3007. slen = strlen (string);
  3008. i = j = 0;
  3009. while (i < slen)
  3010. {
  3011. if (string[i] == CTLESC)
  3012. {
  3013. /* Old code had j++, but we cannot assume that i == j at this
  3014. point -- what if a CTLNUL has already been removed from the
  3015. string? We don't want to drop the CTLESC or recopy characters
  3016. that we've already copied down. */
  3017. i++; string[j++] = CTLESC;
  3018. if (i == slen)
  3019. break;
  3020. }
  3021. else if (string[i] == CTLNUL)
  3022. i++;
  3023. prev_i = i;
  3024. ADVANCE_CHAR (string, slen, i);
  3025. if (j < prev_i)
  3026. {
  3027. do string[j++] = string[prev_i++]; while (prev_i < i);
  3028. }
  3029. else
  3030. j = i;
  3031. }
  3032. string[j] = '\0';
  3033. return (string);
  3034. }
  3035. /* Perform quoted null character removal on each element of LIST.
  3036. This modifies LIST. */
  3037. void
  3038. word_list_remove_quoted_nulls (list)
  3039. WORD_LIST *list;
  3040. {
  3041. register WORD_LIST *t;
  3042. for (t = list; t; t = t->next)
  3043. {
  3044. remove_quoted_nulls (t->word->word);
  3045. t->word->flags &= ~W_HASQUOTEDNULL;
  3046. }
  3047. }
  3048. /* **************************************************************** */
  3049. /* */
  3050. /* Functions for Matching and Removing Patterns */
  3051. /* */
  3052. /* **************************************************************** */
  3053. #if defined (HANDLE_MULTIBYTE)
  3054. #if 0 /* Currently unused */
  3055. static unsigned char *
  3056. mb_getcharlens (string, len)
  3057. char *string;
  3058. int len;
  3059. {
  3060. int i, offset, last;
  3061. unsigned char *ret;
  3062. char *p;
  3063. DECLARE_MBSTATE;
  3064. i = offset = 0;
  3065. last = 0;
  3066. ret = (unsigned char *)xmalloc (len);
  3067. memset (ret, 0, len);
  3068. while (string[last])
  3069. {
  3070. ADVANCE_CHAR (string, len, offset);
  3071. ret[last] = offset - last;
  3072. last = offset;
  3073. }
  3074. return ret;
  3075. }
  3076. #endif
  3077. #endif
  3078. /* Remove the portion of PARAM matched by PATTERN according to OP, where OP
  3079. can have one of 4 values:
  3080. RP_LONG_LEFT remove longest matching portion at start of PARAM
  3081. RP_SHORT_LEFT remove shortest matching portion at start of PARAM
  3082. RP_LONG_RIGHT remove longest matching portion at end of PARAM
  3083. RP_SHORT_RIGHT remove shortest matching portion at end of PARAM
  3084. */
  3085. #define RP_LONG_LEFT 1
  3086. #define RP_SHORT_LEFT 2
  3087. #define RP_LONG_RIGHT 3
  3088. #define RP_SHORT_RIGHT 4
  3089. static char *
  3090. remove_upattern (param, pattern, op)
  3091. char *param, *pattern;
  3092. int op;
  3093. {
  3094. register int len;
  3095. register char *end;
  3096. register char *p, *ret, c;
  3097. len = STRLEN (param);
  3098. end = param + len;
  3099. switch (op)
  3100. {
  3101. case RP_LONG_LEFT: /* remove longest match at start */
  3102. for (p = end; p >= param; p--)
  3103. {
  3104. c = *p; *p = '\0';
  3105. if (strmatch (pattern, param, FNMATCH_EXTFLAG) != FNM_NOMATCH)
  3106. {
  3107. *p = c;
  3108. return (savestring (p));
  3109. }
  3110. *p = c;
  3111. }
  3112. break;
  3113. case RP_SHORT_LEFT: /* remove shortest match at start */
  3114. for (p = param; p <= end; p++)
  3115. {
  3116. c = *p; *p = '\0';
  3117. if (strmatch (pattern, param, FNMATCH_EXTFLAG) != FNM_NOMATCH)
  3118. {
  3119. *p = c;
  3120. return (savestring (p));
  3121. }
  3122. *p = c;
  3123. }
  3124. break;
  3125. case RP_LONG_RIGHT: /* remove longest match at end */
  3126. for (p = param; p <= end; p++)
  3127. {
  3128. if (strmatch (pattern, p, FNMATCH_EXTFLAG) != FNM_NOMATCH)
  3129. {
  3130. c = *p; *p = '\0';
  3131. ret = savestring (param);
  3132. *p = c;
  3133. return (ret);
  3134. }
  3135. }
  3136. break;
  3137. case RP_SHORT_RIGHT: /* remove shortest match at end */
  3138. for (p = end; p >= param; p--)
  3139. {
  3140. if (strmatch (pattern, p, FNMATCH_EXTFLAG) != FNM_NOMATCH)
  3141. {
  3142. c = *p; *p = '\0';
  3143. ret = savestring (param);
  3144. *p = c;
  3145. return (ret);
  3146. }
  3147. }
  3148. break;
  3149. }
  3150. return (savestring (param)); /* no match, return original string */
  3151. }
  3152. #if defined (HANDLE_MULTIBYTE)
  3153. static wchar_t *
  3154. remove_wpattern (wparam, wstrlen, wpattern, op)
  3155. wchar_t *wparam;
  3156. size_t wstrlen;
  3157. wchar_t *wpattern;
  3158. int op;
  3159. {
  3160. wchar_t wc, *ret;
  3161. int n;
  3162. switch (op)
  3163. {
  3164. case RP_LONG_LEFT: /* remove longest match at start */
  3165. for (n = wstrlen; n >= 0; n--)
  3166. {
  3167. wc = wparam[n]; wparam[n] = L'\0';
  3168. if (wcsmatch (wpattern, wparam, FNMATCH_EXTFLAG) != FNM_NOMATCH)
  3169. {
  3170. wparam[n] = wc;
  3171. return (wcsdup (wparam + n));
  3172. }
  3173. wparam[n] = wc;
  3174. }
  3175. break;
  3176. case RP_SHORT_LEFT: /* remove shortest match at start */
  3177. for (n = 0; n <= wstrlen; n++)
  3178. {
  3179. wc = wparam[n]; wparam[n] = L'\0';
  3180. if (wcsmatch (wpattern, wparam, FNMATCH_EXTFLAG) != FNM_NOMATCH)
  3181. {
  3182. wparam[n] = wc;
  3183. return (wcsdup (wparam + n));
  3184. }
  3185. wparam[n] = wc;
  3186. }
  3187. break;
  3188. case RP_LONG_RIGHT: /* remove longest match at end */
  3189. for (n = 0; n <= wstrlen; n++)
  3190. {
  3191. if (wcsmatch (wpattern, wparam + n, FNMATCH_EXTFLAG) != FNM_NOMATCH)
  3192. {
  3193. wc = wparam[n]; wparam[n] = L'\0';
  3194. ret = wcsdup (wparam);
  3195. wparam[n] = wc;
  3196. return (ret);
  3197. }
  3198. }
  3199. break;
  3200. case RP_SHORT_RIGHT: /* remove shortest match at end */
  3201. for (n = wstrlen; n >= 0; n--)
  3202. {
  3203. if (wcsmatch (wpattern, wparam + n, FNMATCH_EXTFLAG) != FNM_NOMATCH)
  3204. {
  3205. wc = wparam[n]; wparam[n] = L'\0';
  3206. ret = wcsdup (wparam);
  3207. wparam[n] = wc;
  3208. return (ret);
  3209. }
  3210. }
  3211. break;
  3212. }
  3213. return (wcsdup (wparam)); /* no match, return original string */
  3214. }
  3215. #endif /* HANDLE_MULTIBYTE */
  3216. static char *
  3217. remove_pattern (param, pattern, op)
  3218. char *param, *pattern;
  3219. int op;
  3220. {
  3221. if (param == NULL)
  3222. return (param);
  3223. if (*param == '\0' || pattern == NULL || *pattern == '\0') /* minor optimization */
  3224. return (savestring (param));
  3225. #if defined (HANDLE_MULTIBYTE)
  3226. if (MB_CUR_MAX > 1)
  3227. {
  3228. wchar_t *ret, *oret;
  3229. size_t n;
  3230. wchar_t *wparam, *wpattern;
  3231. mbstate_t ps;
  3232. char *xret;
  3233. n = xdupmbstowcs (&wpattern, NULL, pattern);
  3234. if (n == (size_t)-1)
  3235. return (remove_upattern (param, pattern, op));
  3236. n = xdupmbstowcs (&wparam, NULL, param);
  3237. if (n == (size_t)-1)
  3238. {
  3239. free (wpattern);
  3240. return (remove_upattern (param, pattern, op));
  3241. }
  3242. oret = ret = remove_wpattern (wparam, n, wpattern, op);
  3243. free (wparam);
  3244. free (wpattern);
  3245. n = strlen (param);
  3246. xret = (char *)xmalloc (n + 1);
  3247. memset (&ps, '\0', sizeof (mbstate_t));
  3248. n = wcsrtombs (xret, (const wchar_t **)&ret, n, &ps);
  3249. xret[n] = '\0'; /* just to make sure */
  3250. free (oret);
  3251. return xret;
  3252. }
  3253. else
  3254. #endif
  3255. return (remove_upattern (param, pattern, op));
  3256. }
  3257. /* Return 1 of the first character of STRING could match the first
  3258. character of pattern PAT. Used to avoid n2 calls to strmatch(). */
  3259. static int
  3260. match_pattern_char (pat, string)
  3261. char *pat, *string;
  3262. {
  3263. char c;
  3264. if (*string == 0)
  3265. return (0);
  3266. switch (c = *pat++)
  3267. {
  3268. default:
  3269. return (*string == c);
  3270. case '\\':
  3271. return (*string == *pat);
  3272. case '?':
  3273. return (*pat == LPAREN ? 1 : (*string != '\0'));
  3274. case '*':
  3275. return (1);
  3276. case '+':
  3277. case '!':
  3278. case '@':
  3279. return (*pat == LPAREN ? 1 : (*string == c));
  3280. case '[':
  3281. return (*string != '\0');
  3282. }
  3283. }
  3284. /* Match PAT anywhere in STRING and return the match boundaries.
  3285. This returns 1 in case of a successful match, 0 otherwise. SP
  3286. and EP are pointers into the string where the match begins and
  3287. ends, respectively. MTYPE controls what kind of match is attempted.
  3288. MATCH_BEG and MATCH_END anchor the match at the beginning and end
  3289. of the string, respectively. The longest match is returned. */
  3290. static int
  3291. match_upattern (string, pat, mtype, sp, ep)
  3292. char *string, *pat;
  3293. int mtype;
  3294. char **sp, **ep;
  3295. {
  3296. int c, len;
  3297. register char *p, *p1, *npat;
  3298. char *end;
  3299. /* If the pattern doesn't match anywhere in the string, go ahead and
  3300. short-circuit right away. A minor optimization, saves a bunch of
  3301. unnecessary calls to strmatch (up to N calls for a string of N
  3302. characters) if the match is unsuccessful. To preserve the semantics
  3303. of the substring matches below, we make sure that the pattern has
  3304. `*' as first and last character, making a new pattern if necessary. */
  3305. /* XXX - check this later if I ever implement `**' with special meaning,
  3306. since this will potentially result in `**' at the beginning or end */
  3307. len = STRLEN (pat);
  3308. if (pat[0] != '*' || (pat[0] == '*' && pat[1] == '(' && extended_glob) || pat[len - 1] != '*') /*)*/
  3309. {
  3310. p = npat = (char *)xmalloc (len + 3);
  3311. p1 = pat;
  3312. if (*p1 != '*' || (*p1 == '*' && p1[1] == '(' && extended_glob)) /*)*/
  3313. *p++ = '*';
  3314. while (*p1)
  3315. *p++ = *p1++;
  3316. if (p1[-1] != '*' || p[-2] == '\\')
  3317. *p++ = '*';
  3318. *p = '\0';
  3319. }
  3320. else
  3321. npat = pat;
  3322. c = strmatch (npat, string, FNMATCH_EXTFLAG);
  3323. if (npat != pat)
  3324. free (npat);
  3325. if (c == FNM_NOMATCH)
  3326. return (0);
  3327. len = STRLEN (string);
  3328. end = string + len;
  3329. switch (mtype)
  3330. {
  3331. case MATCH_ANY:
  3332. for (p = string; p <= end; p++)
  3333. {
  3334. if (match_pattern_char (pat, p))
  3335. {
  3336. for (p1 = end; p1 >= p; p1--)
  3337. {
  3338. c = *p1; *p1 = '\0';
  3339. if (strmatch (pat, p, FNMATCH_EXTFLAG) == 0)
  3340. {
  3341. *p1 = c;
  3342. *sp = p;
  3343. *ep = p1;
  3344. return 1;
  3345. }
  3346. *p1 = c;
  3347. }
  3348. }
  3349. }
  3350. return (0);
  3351. case MATCH_BEG:
  3352. if (match_pattern_char (pat, string) == 0)
  3353. return (0);
  3354. for (p = end; p >= string; p--)
  3355. {
  3356. c = *p; *p = '\0';
  3357. if (strmatch (pat, string, FNMATCH_EXTFLAG) == 0)
  3358. {
  3359. *p = c;
  3360. *sp = string;
  3361. *ep = p;
  3362. return 1;
  3363. }
  3364. *p = c;
  3365. }
  3366. return (0);
  3367. case MATCH_END:
  3368. for (p = string; p <= end; p++)
  3369. {
  3370. if (strmatch (pat, p, FNMATCH_EXTFLAG) == 0)
  3371. {
  3372. *sp = p;
  3373. *ep = end;
  3374. return 1;
  3375. }
  3376. }
  3377. return (0);
  3378. }
  3379. return (0);
  3380. }
  3381. #if defined (HANDLE_MULTIBYTE)
  3382. /* Return 1 of the first character of WSTRING could match the first
  3383. character of pattern WPAT. Wide character version. */
  3384. static int
  3385. match_pattern_wchar (wpat, wstring)
  3386. wchar_t *wpat, *wstring;
  3387. {
  3388. wchar_t wc;
  3389. if (*wstring == 0)
  3390. return (0);
  3391. switch (wc = *wpat++)
  3392. {
  3393. default:
  3394. return (*wstring == wc);
  3395. case L'\\':
  3396. return (*wstring == *wpat);
  3397. case L'?':
  3398. return (*wpat == LPAREN ? 1 : (*wstring != L'\0'));
  3399. case L'*':
  3400. return (1);
  3401. case L'+':
  3402. case L'!':
  3403. case L'@':
  3404. return (*wpat == LPAREN ? 1 : (*wstring == wc));
  3405. case L'[':
  3406. return (*wstring != L'\0');
  3407. }
  3408. }
  3409. /* Match WPAT anywhere in WSTRING and return the match boundaries.
  3410. This returns 1 in case of a successful match, 0 otherwise. Wide
  3411. character version. */
  3412. static int
  3413. match_wpattern (wstring, indices, wstrlen, wpat, mtype, sp, ep)
  3414. wchar_t *wstring;
  3415. char **indices;
  3416. size_t wstrlen;
  3417. wchar_t *wpat;
  3418. int mtype;
  3419. char **sp, **ep;
  3420. {
  3421. wchar_t wc, *wp, *nwpat, *wp1;
  3422. int len;
  3423. #if 0
  3424. size_t n, n1; /* Apple's gcc seems to miscompile this badly */
  3425. #else
  3426. int n, n1;
  3427. #endif
  3428. /* If the pattern doesn't match anywhere in the string, go ahead and
  3429. short-circuit right away. A minor optimization, saves a bunch of
  3430. unnecessary calls to strmatch (up to N calls for a string of N
  3431. characters) if the match is unsuccessful. To preserve the semantics
  3432. of the substring matches below, we make sure that the pattern has
  3433. `*' as first and last character, making a new pattern if necessary. */
  3434. /* XXX - check this later if I ever implement `**' with special meaning,
  3435. since this will potentially result in `**' at the beginning or end */
  3436. len = wcslen (wpat);
  3437. if (wpat[0] != L'*' || (wpat[0] == L'*' && wpat[1] == L'(' && extended_glob) || wpat[len - 1] != L'*') /*)*/
  3438. {
  3439. wp = nwpat = (wchar_t *)xmalloc ((len + 3) * sizeof (wchar_t));
  3440. wp1 = wpat;
  3441. if (*wp1 != L'*' || (*wp1 == '*' && wp1[1] == '(' && extended_glob)) /*)*/
  3442. *wp++ = L'*';
  3443. while (*wp1 != L'\0')
  3444. *wp++ = *wp1++;
  3445. if (wp1[-1] != L'*' || wp1[-2] == L'\\')
  3446. *wp++ = L'*';
  3447. *wp = '\0';
  3448. }
  3449. else
  3450. nwpat = wpat;
  3451. len = wcsmatch (nwpat, wstring, FNMATCH_EXTFLAG);
  3452. if (nwpat != wpat)
  3453. free (nwpat);
  3454. if (len == FNM_NOMATCH)
  3455. return (0);
  3456. switch (mtype)
  3457. {
  3458. case MATCH_ANY:
  3459. for (n = 0; n <= wstrlen; n++)
  3460. {
  3461. if (match_pattern_wchar (wpat, wstring + n))
  3462. {
  3463. for (n1 = wstrlen; n1 >= n; n1--)
  3464. {
  3465. wc = wstring[n1]; wstring[n1] = L'\0';
  3466. if (wcsmatch (wpat, wstring + n, FNMATCH_EXTFLAG) == 0)
  3467. {
  3468. wstring[n1] = wc;
  3469. *sp = indices[n];
  3470. *ep = indices[n1];
  3471. return 1;
  3472. }
  3473. wstring[n1] = wc;
  3474. }
  3475. }
  3476. }
  3477. return (0);
  3478. case MATCH_BEG:
  3479. if (match_pattern_wchar (wpat, wstring) == 0)
  3480. return (0);
  3481. for (n = wstrlen; n >= 0; n--)
  3482. {
  3483. wc = wstring[n]; wstring[n] = L'\0';
  3484. if (wcsmatch (wpat, wstring, FNMATCH_EXTFLAG) == 0)
  3485. {
  3486. wstring[n] = wc;
  3487. *sp = indices[0];
  3488. *ep = indices[n];
  3489. return 1;
  3490. }
  3491. wstring[n] = wc;
  3492. }
  3493. return (0);
  3494. case MATCH_END:
  3495. for (n = 0; n <= wstrlen; n++)
  3496. {
  3497. if (wcsmatch (wpat, wstring + n, FNMATCH_EXTFLAG) == 0)
  3498. {
  3499. *sp = indices[n];
  3500. *ep = indices[wstrlen];
  3501. return 1;
  3502. }
  3503. }
  3504. return (0);
  3505. }
  3506. return (0);
  3507. }
  3508. #endif /* HANDLE_MULTIBYTE */
  3509. static int
  3510. match_pattern (string, pat, mtype, sp, ep)
  3511. char *string, *pat;
  3512. int mtype;
  3513. char **sp, **ep;
  3514. {
  3515. #if defined (HANDLE_MULTIBYTE)
  3516. int ret;
  3517. size_t n;
  3518. wchar_t *wstring, *wpat;
  3519. char **indices;
  3520. #endif
  3521. if (string == 0 || *string == 0 || pat == 0 || *pat == 0)
  3522. return (0);
  3523. #if defined (HANDLE_MULTIBYTE)
  3524. if (MB_CUR_MAX > 1)
  3525. {
  3526. n = xdupmbstowcs (&wpat, NULL, pat);
  3527. if (n == (size_t)-1)
  3528. return (match_upattern (string, pat, mtype, sp, ep));
  3529. n = xdupmbstowcs (&wstring, &indices, string);
  3530. if (n == (size_t)-1)
  3531. {
  3532. free (wpat);
  3533. return (match_upattern (string, pat, mtype, sp, ep));
  3534. }
  3535. ret = match_wpattern (wstring, indices, n, wpat, mtype, sp, ep);
  3536. free (wpat);
  3537. free (wstring);
  3538. free (indices);
  3539. return (ret);
  3540. }
  3541. else
  3542. #endif
  3543. return (match_upattern (string, pat, mtype, sp, ep));
  3544. }
  3545. static int
  3546. getpatspec (c, value)
  3547. int c;
  3548. char *value;
  3549. {
  3550. if (c == '#')
  3551. return ((*value == '#') ? RP_LONG_LEFT : RP_SHORT_LEFT);
  3552. else /* c == '%' */
  3553. return ((*value == '%') ? RP_LONG_RIGHT : RP_SHORT_RIGHT);
  3554. }
  3555. /* Posix.2 says that the WORD should be run through tilde expansion,
  3556. parameter expansion, command substitution and arithmetic expansion.
  3557. This leaves the result quoted, so quote_string_for_globbing () has
  3558. to be called to fix it up for strmatch (). If QUOTED is non-zero,
  3559. it means that the entire expression was enclosed in double quotes.
  3560. This means that quoting characters in the pattern do not make any
  3561. special pattern characters quoted. For example, the `*' in the
  3562. following retains its special meaning: "${foo#'*'}". */
  3563. static char *
  3564. getpattern (value, quoted, expandpat)
  3565. char *value;
  3566. int quoted, expandpat;
  3567. {
  3568. char *pat, *tword;
  3569. WORD_LIST *l;
  3570. #if 0
  3571. int i;
  3572. #endif
  3573. /* There is a problem here: how to handle single or double quotes in the
  3574. pattern string when the whole expression is between double quotes?
  3575. POSIX.2 says that enclosing double quotes do not cause the pattern to
  3576. be quoted, but does that leave us a problem with @ and array[@] and their
  3577. expansions inside a pattern? */
  3578. #if 0
  3579. if (expandpat && (quoted & (Q_HERE_DOCUMENT|Q_DOUBLE_QUOTES)) && *tword)
  3580. {
  3581. i = 0;
  3582. pat = string_extract_double_quoted (tword, &i, 1);
  3583. free (tword);
  3584. tword = pat;
  3585. }
  3586. #endif
  3587. /* expand_string_for_rhs () leaves WORD quoted and does not perform
  3588. word splitting. */
  3589. l = *value ? expand_string_for_rhs (value,
  3590. (quoted & (Q_HERE_DOCUMENT|Q_DOUBLE_QUOTES)) ? Q_PATQUOTE : quoted,
  3591. (int *)NULL, (int *)NULL)
  3592. : (WORD_LIST *)0;
  3593. pat = string_list (l);
  3594. dispose_words (l);
  3595. if (pat)
  3596. {
  3597. tword = quote_string_for_globbing (pat, QGLOB_CVTNULL);
  3598. free (pat);
  3599. pat = tword;
  3600. }
  3601. return (pat);
  3602. }
  3603. #if 0
  3604. /* Handle removing a pattern from a string as a result of ${name%[%]value}
  3605. or ${name#[#]value}. */
  3606. static char *
  3607. variable_remove_pattern (value, pattern, patspec, quoted)
  3608. char *value, *pattern;
  3609. int patspec, quoted;
  3610. {
  3611. char *tword;
  3612. tword = remove_pattern (value, pattern, patspec);
  3613. return (tword);
  3614. }
  3615. #endif
  3616. static char *
  3617. list_remove_pattern (list, pattern, patspec, itype, quoted)
  3618. WORD_LIST *list;
  3619. char *pattern;
  3620. int patspec, itype, quoted;
  3621. {
  3622. WORD_LIST *new, *l;
  3623. WORD_DESC *w;
  3624. char *tword;
  3625. for (new = (WORD_LIST *)NULL, l = list; l; l = l->next)
  3626. {
  3627. tword = remove_pattern (l->word->word, pattern, patspec);
  3628. w = alloc_word_desc ();
  3629. w->word = tword ? tword : savestring ("");
  3630. new = make_word_list (w, new);
  3631. }
  3632. l = REVERSE_LIST (new, WORD_LIST *);
  3633. tword = string_list_pos_params (itype, l, quoted);
  3634. dispose_words (l);
  3635. return (tword);
  3636. }
  3637. static char *
  3638. parameter_list_remove_pattern (itype, pattern, patspec, quoted)
  3639. int itype;
  3640. char *pattern;
  3641. int patspec, quoted;
  3642. {
  3643. char *ret;
  3644. WORD_LIST *list;
  3645. list = list_rest_of_args ();
  3646. if (list == 0)
  3647. return ((char *)NULL);
  3648. ret = list_remove_pattern (list, pattern, patspec, itype, quoted);
  3649. dispose_words (list);
  3650. return (ret);
  3651. }
  3652. #if defined (ARRAY_VARS)
  3653. static char *
  3654. array_remove_pattern (var, pattern, patspec, varname, quoted)
  3655. SHELL_VAR *var;
  3656. char *pattern;
  3657. int patspec;
  3658. char *varname; /* so we can figure out how it's indexed */
  3659. int quoted;
  3660. {
  3661. ARRAY *a;
  3662. HASH_TABLE *h;
  3663. int itype;
  3664. char *ret;
  3665. WORD_LIST *list;
  3666. SHELL_VAR *v;
  3667. /* compute itype from varname here */
  3668. v = array_variable_part (varname, &ret, 0);
  3669. itype = ret[0];
  3670. a = (v && array_p (v)) ? array_cell (v) : 0;
  3671. h = (v && assoc_p (v)) ? assoc_cell (v) : 0;
  3672. list = a ? array_to_word_list (a) : (h ? assoc_to_word_list (h) : 0);
  3673. if (list == 0)
  3674. return ((char *)NULL);
  3675. ret = list_remove_pattern (list, pattern, patspec, itype, quoted);
  3676. dispose_words (list);
  3677. return ret;
  3678. }
  3679. #endif /* ARRAY_VARS */
  3680. static char *
  3681. parameter_brace_remove_pattern (varname, value, patstr, rtype, quoted)
  3682. char *varname, *value, *patstr;
  3683. int rtype, quoted;
  3684. {
  3685. int vtype, patspec, starsub;
  3686. char *temp1, *val, *pattern;
  3687. SHELL_VAR *v;
  3688. if (value == 0)
  3689. return ((char *)NULL);
  3690. this_command_name = varname;
  3691. vtype = get_var_and_type (varname, value, quoted, &v, &val);
  3692. if (vtype == -1)
  3693. return ((char *)NULL);
  3694. starsub = vtype & VT_STARSUB;
  3695. vtype &= ~VT_STARSUB;
  3696. patspec = getpatspec (rtype, patstr);
  3697. if (patspec == RP_LONG_LEFT || patspec == RP_LONG_RIGHT)
  3698. patstr++;
  3699. /* Need to pass getpattern newly-allocated memory in case of expansion --
  3700. the expansion code will free the passed string on an error. */
  3701. temp1 = savestring (patstr);
  3702. pattern = getpattern (temp1, quoted, 1);
  3703. free (temp1);
  3704. temp1 = (char *)NULL; /* shut up gcc */
  3705. switch (vtype)
  3706. {
  3707. case VT_VARIABLE:
  3708. case VT_ARRAYMEMBER:
  3709. temp1 = remove_pattern (val, pattern, patspec);
  3710. if (vtype == VT_VARIABLE)
  3711. FREE (val);
  3712. if (temp1)
  3713. {
  3714. val = (quoted & (Q_HERE_DOCUMENT|Q_DOUBLE_QUOTES))
  3715. ? quote_string (temp1)
  3716. : quote_escapes (temp1);
  3717. free (temp1);
  3718. temp1 = val;
  3719. }
  3720. break;
  3721. #if defined (ARRAY_VARS)
  3722. case VT_ARRAYVAR:
  3723. temp1 = array_remove_pattern (v, pattern, patspec, varname, quoted);
  3724. if (temp1 && ((quoted & (Q_HERE_DOCUMENT|Q_DOUBLE_QUOTES)) == 0))
  3725. {
  3726. val = quote_escapes (temp1);
  3727. free (temp1);
  3728. temp1 = val;
  3729. }
  3730. break;
  3731. #endif
  3732. case VT_POSPARMS:
  3733. temp1 = parameter_list_remove_pattern (varname[0], pattern, patspec, quoted);
  3734. if (temp1 && ((quoted & (Q_HERE_DOCUMENT|Q_DOUBLE_QUOTES)) == 0))
  3735. {
  3736. val = quote_escapes (temp1);
  3737. free (temp1);
  3738. temp1 = val;
  3739. }
  3740. break;
  3741. }
  3742. FREE (pattern);
  3743. return temp1;
  3744. }
  3745. /*******************************************
  3746. * *
  3747. * Functions to expand WORD_DESCs *
  3748. * *
  3749. *******************************************/
  3750. /* Expand WORD, performing word splitting on the result. This does
  3751. parameter expansion, command substitution, arithmetic expansion,
  3752. word splitting, and quote removal. */
  3753. WORD_LIST *
  3754. expand_word (word, quoted)
  3755. WORD_DESC *word;
  3756. int quoted;
  3757. {
  3758. WORD_LIST *result, *tresult;
  3759. tresult = call_expand_word_internal (word, quoted, 0, (int *)NULL, (int *)NULL);
  3760. result = word_list_split (tresult);
  3761. dispose_words (tresult);
  3762. return (result ? dequote_list (result) : result);
  3763. }
  3764. /* Expand WORD, but do not perform word splitting on the result. This
  3765. does parameter expansion, command substitution, arithmetic expansion,
  3766. and quote removal. */
  3767. WORD_LIST *
  3768. expand_word_unsplit (word, quoted)
  3769. WORD_DESC *word;
  3770. int quoted;
  3771. {
  3772. WORD_LIST *result;
  3773. expand_no_split_dollar_star = 1;
  3774. result = call_expand_word_internal (word, quoted, 0, (int *)NULL, (int *)NULL);
  3775. expand_no_split_dollar_star = 0;
  3776. return (result ? dequote_list (result) : result);
  3777. }
  3778. /* Perform shell expansions on WORD, but do not perform word splitting or
  3779. quote removal on the result. */
  3780. WORD_LIST *
  3781. expand_word_leave_quoted (word, quoted)
  3782. WORD_DESC *word;
  3783. int quoted;
  3784. {
  3785. return (call_expand_word_internal (word, quoted, 0, (int *)NULL, (int *)NULL));
  3786. }
  3787. #if defined (PROCESS_SUBSTITUTION)
  3788. /*****************************************************************/
  3789. /* */
  3790. /* Hacking Process Substitution */
  3791. /* */
  3792. /*****************************************************************/
  3793. #if !defined (HAVE_DEV_FD)
  3794. /* Named pipes must be removed explicitly with `unlink'. This keeps a list
  3795. of FIFOs the shell has open. unlink_fifo_list will walk the list and
  3796. unlink all of them. add_fifo_list adds the name of an open FIFO to the
  3797. list. NFIFO is a count of the number of FIFOs in the list. */
  3798. #define FIFO_INCR 20
  3799. struct temp_fifo {
  3800. char *file;
  3801. pid_t proc;
  3802. };
  3803. static struct temp_fifo *fifo_list = (struct temp_fifo *)NULL;
  3804. static int nfifo;
  3805. static int fifo_list_size;
  3806. static void
  3807. add_fifo_list (pathname)
  3808. char *pathname;
  3809. {
  3810. if (nfifo >= fifo_list_size - 1)
  3811. {
  3812. fifo_list_size += FIFO_INCR;
  3813. fifo_list = (struct temp_fifo *)xrealloc (fifo_list,
  3814. fifo_list_size * sizeof (struct temp_fifo));
  3815. }
  3816. fifo_list[nfifo].file = savestring (pathname);
  3817. nfifo++;
  3818. }
  3819. void
  3820. unlink_fifo_list ()
  3821. {
  3822. int saved, i, j;
  3823. if (nfifo == 0)
  3824. return;
  3825. for (i = saved = 0; i < nfifo; i++)
  3826. {
  3827. if ((fifo_list[i].proc == -1) || (kill(fifo_list[i].proc, 0) == -1))
  3828. {
  3829. unlink (fifo_list[i].file);
  3830. free (fifo_list[i].file);
  3831. fifo_list[i].file = (char *)NULL;
  3832. fifo_list[i].proc = -1;
  3833. }
  3834. else
  3835. saved++;
  3836. }
  3837. /* If we didn't remove some of the FIFOs, compact the list. */
  3838. if (saved)
  3839. {
  3840. for (i = j = 0; i < nfifo; i++)
  3841. if (fifo_list[i].file)
  3842. {
  3843. fifo_list[j].file = fifo_list[i].file;
  3844. fifo_list[j].proc = fifo_list[i].proc;
  3845. j++;
  3846. }
  3847. nfifo = j;
  3848. }
  3849. else
  3850. nfifo = 0;
  3851. }
  3852. int
  3853. fifos_pending ()
  3854. {
  3855. return nfifo;
  3856. }
  3857. static char *
  3858. make_named_pipe ()
  3859. {
  3860. char *tname;
  3861. tname = sh_mktmpname ("sh-np", MT_USERANDOM|MT_USETMPDIR);
  3862. if (mkfifo (tname, 0600) < 0)
  3863. {
  3864. free (tname);
  3865. return ((char *)NULL);
  3866. }
  3867. add_fifo_list (tname);
  3868. return (tname);
  3869. }
  3870. #else /* HAVE_DEV_FD */
  3871. /* DEV_FD_LIST is a bitmap of file descriptors attached to pipes the shell
  3872. has open to children. NFDS is a count of the number of bits currently
  3873. set in DEV_FD_LIST. TOTFDS is a count of the highest possible number
  3874. of open files. */
  3875. static char *dev_fd_list = (char *)NULL;
  3876. static int nfds;
  3877. static int totfds; /* The highest possible number of open files. */
  3878. static void
  3879. add_fifo_list (fd)
  3880. int fd;
  3881. {
  3882. if (!dev_fd_list || fd >= totfds)
  3883. {
  3884. int ofds;
  3885. ofds = totfds;
  3886. totfds = getdtablesize ();
  3887. if (totfds < 0 || totfds > 256)
  3888. totfds = 256;
  3889. if (fd >= totfds)
  3890. totfds = fd + 2;
  3891. dev_fd_list = (char *)xrealloc (dev_fd_list, totfds);
  3892. memset (dev_fd_list + ofds, '\0', totfds - ofds);
  3893. }
  3894. dev_fd_list[fd] = 1;
  3895. nfds++;
  3896. }
  3897. int
  3898. fifos_pending ()
  3899. {
  3900. return 0; /* used for cleanup; not needed with /dev/fd */
  3901. }
  3902. void
  3903. unlink_fifo_list ()
  3904. {
  3905. register int i;
  3906. if (nfds == 0)
  3907. return;
  3908. for (i = 0; nfds && i < totfds; i++)
  3909. if (dev_fd_list[i])
  3910. {
  3911. close (i);
  3912. dev_fd_list[i] = 0;
  3913. nfds--;
  3914. }
  3915. nfds = 0;
  3916. }
  3917. #if defined (NOTDEF)
  3918. print_dev_fd_list ()
  3919. {
  3920. register int i;
  3921. fprintf (stderr, "pid %ld: dev_fd_list:", (long)getpid ());
  3922. fflush (stderr);
  3923. for (i = 0; i < totfds; i++)
  3924. {
  3925. if (dev_fd_list[i])
  3926. fprintf (stderr, " %d", i);
  3927. }
  3928. fprintf (stderr, "\n");
  3929. }
  3930. #endif /* NOTDEF */
  3931. static char *
  3932. make_dev_fd_filename (fd)
  3933. int fd;
  3934. {
  3935. char *ret, intbuf[INT_STRLEN_BOUND (int) + 1], *p;
  3936. ret = (char *)xmalloc (sizeof (DEV_FD_PREFIX) + 8);
  3937. strcpy (ret, DEV_FD_PREFIX);
  3938. p = inttostr (fd, intbuf, sizeof (intbuf));
  3939. strcpy (ret + sizeof (DEV_FD_PREFIX) - 1, p);
  3940. add_fifo_list (fd);
  3941. return (ret);
  3942. }
  3943. #endif /* HAVE_DEV_FD */
  3944. /* Return a filename that will open a connection to the process defined by
  3945. executing STRING. HAVE_DEV_FD, if defined, means open a pipe and return
  3946. a filename in /dev/fd corresponding to a descriptor that is one of the
  3947. ends of the pipe. If not defined, we use named pipes on systems that have
  3948. them. Systems without /dev/fd and named pipes are out of luck.
  3949. OPEN_FOR_READ_IN_CHILD, if 1, means open the named pipe for reading or
  3950. use the read end of the pipe and dup that file descriptor to fd 0 in
  3951. the child. If OPEN_FOR_READ_IN_CHILD is 0, we open the named pipe for
  3952. writing or use the write end of the pipe in the child, and dup that
  3953. file descriptor to fd 1 in the child. The parent does the opposite. */
  3954. static char *
  3955. process_substitute (string, open_for_read_in_child)
  3956. char *string;
  3957. int open_for_read_in_child;
  3958. {
  3959. char *pathname;
  3960. int fd, result;
  3961. pid_t old_pid, pid;
  3962. #if defined (HAVE_DEV_FD)
  3963. int parent_pipe_fd, child_pipe_fd;
  3964. int fildes[2];
  3965. #endif /* HAVE_DEV_FD */
  3966. #if defined (JOB_CONTROL)
  3967. pid_t old_pipeline_pgrp;
  3968. #endif
  3969. if (!string || !*string || wordexp_only)
  3970. return ((char *)NULL);
  3971. #if !defined (HAVE_DEV_FD)
  3972. pathname = make_named_pipe ();
  3973. #else /* HAVE_DEV_FD */
  3974. if (pipe (fildes) < 0)
  3975. {
  3976. sys_error (_("cannot make pipe for process substitution"));
  3977. return ((char *)NULL);
  3978. }
  3979. /* If OPEN_FOR_READ_IN_CHILD == 1, we want to use the write end of
  3980. the pipe in the parent, otherwise the read end. */
  3981. parent_pipe_fd = fildes[open_for_read_in_child];
  3982. child_pipe_fd = fildes[1 - open_for_read_in_child];
  3983. /* Move the parent end of the pipe to some high file descriptor, to
  3984. avoid clashes with FDs used by the script. */
  3985. parent_pipe_fd = move_to_high_fd (parent_pipe_fd, 1, 64);
  3986. pathname = make_dev_fd_filename (parent_pipe_fd);
  3987. #endif /* HAVE_DEV_FD */
  3988. if (pathname == 0)
  3989. {
  3990. sys_error (_("cannot make pipe for process substitution"));
  3991. return ((char *)NULL);
  3992. }
  3993. old_pid = last_made_pid;
  3994. #if defined (JOB_CONTROL)
  3995. old_pipeline_pgrp = pipeline_pgrp;
  3996. pipeline_pgrp = shell_pgrp;
  3997. save_pipeline (1);
  3998. #endif /* JOB_CONTROL */
  3999. pid = make_child ((char *)NULL, 1);
  4000. if (pid == 0)
  4001. {
  4002. reset_terminating_signals (); /* XXX */
  4003. free_pushed_string_input ();
  4004. /* Cancel traps, in trap.c. */
  4005. restore_original_signals ();
  4006. setup_async_signals ();
  4007. subshell_environment |= SUBSHELL_COMSUB|SUBSHELL_PROCSUB;
  4008. }
  4009. #if defined (JOB_CONTROL)
  4010. set_sigchld_handler ();
  4011. stop_making_children ();
  4012. /* XXX - should we only do this in the parent? (as in command subst) */
  4013. pipeline_pgrp = old_pipeline_pgrp;
  4014. #endif /* JOB_CONTROL */
  4015. if (pid < 0)
  4016. {
  4017. sys_error (_("cannot make child for process substitution"));
  4018. free (pathname);
  4019. #if defined (HAVE_DEV_FD)
  4020. close (parent_pipe_fd);
  4021. close (child_pipe_fd);
  4022. #endif /* HAVE_DEV_FD */
  4023. return ((char *)NULL);
  4024. }
  4025. if (pid > 0)
  4026. {
  4027. #if defined (JOB_CONTROL)
  4028. restore_pipeline (1);
  4029. #endif
  4030. #if !defined (HAVE_DEV_FD)
  4031. fifo_list[nfifo-1].proc = pid;
  4032. #endif
  4033. last_made_pid = old_pid;
  4034. #if defined (JOB_CONTROL) && defined (PGRP_PIPE)
  4035. close_pgrp_pipe ();
  4036. #endif /* JOB_CONTROL && PGRP_PIPE */
  4037. #if defined (HAVE_DEV_FD)
  4038. close (child_pipe_fd);
  4039. #endif /* HAVE_DEV_FD */
  4040. return (pathname);
  4041. }
  4042. set_sigint_handler ();
  4043. #if defined (JOB_CONTROL)
  4044. set_job_control (0);
  4045. #endif /* JOB_CONTROL */
  4046. #if !defined (HAVE_DEV_FD)
  4047. /* Open the named pipe in the child. */
  4048. fd = open (pathname, open_for_read_in_child ? O_RDONLY|O_NONBLOCK : O_WRONLY);
  4049. if (fd < 0)
  4050. {
  4051. /* Two separate strings for ease of translation. */
  4052. if (open_for_read_in_child)
  4053. sys_error (_("cannot open named pipe %s for reading"), pathname);
  4054. else
  4055. sys_error (_("cannot open named pipe %s for writing"), pathname);
  4056. exit (127);
  4057. }
  4058. if (open_for_read_in_child)
  4059. {
  4060. if (sh_unset_nodelay_mode (fd) < 0)
  4061. {
  4062. sys_error (_("cannot reset nodelay mode for fd %d"), fd);
  4063. exit (127);
  4064. }
  4065. }
  4066. #else /* HAVE_DEV_FD */
  4067. fd = child_pipe_fd;
  4068. #endif /* HAVE_DEV_FD */
  4069. if (dup2 (fd, open_for_read_in_child ? 0 : 1) < 0)
  4070. {
  4071. sys_error (_("cannot duplicate named pipe %s as fd %d"), pathname,
  4072. open_for_read_in_child ? 0 : 1);
  4073. exit (127);
  4074. }
  4075. if (fd != (open_for_read_in_child ? 0 : 1))
  4076. close (fd);
  4077. /* Need to close any files that this process has open to pipes inherited
  4078. from its parent. */
  4079. if (current_fds_to_close)
  4080. {
  4081. close_fd_bitmap (current_fds_to_close);
  4082. current_fds_to_close = (struct fd_bitmap *)NULL;
  4083. }
  4084. #if defined (HAVE_DEV_FD)
  4085. /* Make sure we close the parent's end of the pipe and clear the slot
  4086. in the fd list so it is not closed later, if reallocated by, for
  4087. instance, pipe(2). */
  4088. close (parent_pipe_fd);
  4089. dev_fd_list[parent_pipe_fd] = 0;
  4090. #endif /* HAVE_DEV_FD */
  4091. result = parse_and_execute (string, "process substitution", (SEVAL_NONINT|SEVAL_NOHIST));
  4092. #if !defined (HAVE_DEV_FD)
  4093. /* Make sure we close the named pipe in the child before we exit. */
  4094. close (open_for_read_in_child ? 0 : 1);
  4095. #endif /* !HAVE_DEV_FD */
  4096. exit (result);
  4097. /*NOTREACHED*/
  4098. }
  4099. #endif /* PROCESS_SUBSTITUTION */
  4100. /***********************************/
  4101. /* */
  4102. /* Command Substitution */
  4103. /* */
  4104. /***********************************/
  4105. static char *
  4106. read_comsub (fd, quoted, rflag)
  4107. int fd, quoted;
  4108. int *rflag;
  4109. {
  4110. char *istring, buf[128], *bufp, *s;
  4111. int istring_index, istring_size, c, tflag, skip_ctlesc, skip_ctlnul;
  4112. ssize_t bufn;
  4113. istring = (char *)NULL;
  4114. istring_index = istring_size = bufn = tflag = 0;
  4115. for (skip_ctlesc = skip_ctlnul = 0, s = ifs_value; s && *s; s++)
  4116. skip_ctlesc |= *s == CTLESC, skip_ctlnul |= *s == CTLNUL;
  4117. #ifdef __CYGWIN__
  4118. setmode (fd, O_TEXT); /* we don't want CR/LF, we want Unix-style */
  4119. #endif
  4120. /* Read the output of the command through the pipe. This may need to be
  4121. changed to understand multibyte characters in the future. */
  4122. while (1)
  4123. {
  4124. if (fd < 0)
  4125. break;
  4126. if (--bufn <= 0)
  4127. {
  4128. bufn = zread (fd, buf, sizeof (buf));
  4129. if (bufn <= 0)
  4130. break;
  4131. bufp = buf;
  4132. }
  4133. c = *bufp++;
  4134. if (c == 0)
  4135. {
  4136. #if 0
  4137. internal_warning ("read_comsub: ignored null byte in input");
  4138. #endif
  4139. continue;
  4140. }
  4141. /* Add the character to ISTRING, possibly after resizing it. */
  4142. RESIZE_MALLOCED_BUFFER (istring, istring_index, 2, istring_size, DEFAULT_ARRAY_SIZE);
  4143. /* This is essentially quote_string inline */
  4144. if ((quoted & (Q_HERE_DOCUMENT|Q_DOUBLE_QUOTES)) /* || c == CTLESC || c == CTLNUL */)
  4145. istring[istring_index++] = CTLESC;
  4146. /* Escape CTLESC and CTLNUL in the output to protect those characters
  4147. from the rest of the word expansions (word splitting and globbing.)
  4148. This is essentially quote_escapes inline. */
  4149. else if (skip_ctlesc == 0 && c == CTLESC)
  4150. {
  4151. tflag |= W_HASCTLESC;
  4152. istring[istring_index++] = CTLESC;
  4153. }
  4154. else if ((skip_ctlnul == 0 && c == CTLNUL) || (c == ' ' && (ifs_value && *ifs_value == 0)))
  4155. istring[istring_index++] = CTLESC;
  4156. istring[istring_index++] = c;
  4157. #if 0
  4158. #if defined (__CYGWIN__)
  4159. if (c == '\n' && istring_index > 1 && istring[istring_index - 2] == '\r')
  4160. {
  4161. istring_index--;
  4162. istring[istring_index - 1] = '\n';
  4163. }
  4164. #endif
  4165. #endif
  4166. }
  4167. if (istring)
  4168. istring[istring_index] = '\0';
  4169. /* If we read no output, just return now and save ourselves some
  4170. trouble. */
  4171. if (istring_index == 0)
  4172. {
  4173. FREE (istring);
  4174. if (rflag)
  4175. *rflag = tflag;
  4176. return (char *)NULL;
  4177. }
  4178. /* Strip trailing newlines from the output of the command. */
  4179. if (quoted & (Q_HERE_DOCUMENT|Q_DOUBLE_QUOTES))
  4180. {
  4181. while (istring_index > 0)
  4182. {
  4183. if (istring[istring_index - 1] == '\n')
  4184. {
  4185. --istring_index;
  4186. /* If the newline was quoted, remove the quoting char. */
  4187. if (istring[istring_index - 1] == CTLESC)
  4188. --istring_index;
  4189. }
  4190. else
  4191. break;
  4192. }
  4193. istring[istring_index] = '\0';
  4194. }
  4195. else
  4196. strip_trailing (istring, istring_index - 1, 1);
  4197. if (rflag)
  4198. *rflag = tflag;
  4199. return istring;
  4200. }
  4201. /* Perform command substitution on STRING. This returns a WORD_DESC * with the
  4202. contained string possibly quoted. */
  4203. WORD_DESC *
  4204. command_substitute (string, quoted)
  4205. char *string;
  4206. int quoted;
  4207. {
  4208. pid_t pid, old_pid, old_pipeline_pgrp, old_async_pid;
  4209. char *istring;
  4210. int result, fildes[2], function_value, pflags, rc, tflag;
  4211. WORD_DESC *ret;
  4212. istring = (char *)NULL;
  4213. /* Don't fork () if there is no need to. In the case of no command to
  4214. run, just return NULL. */
  4215. if (!string || !*string || (string[0] == '\n' && !string[1]))
  4216. return ((WORD_DESC *)NULL);
  4217. if (wordexp_only && read_but_dont_execute)
  4218. {
  4219. last_command_exit_value = 125;
  4220. jump_to_top_level (EXITPROG);
  4221. }
  4222. /* We're making the assumption here that the command substitution will
  4223. eventually run a command from the file system. Since we'll run
  4224. maybe_make_export_env in this subshell before executing that command,
  4225. the parent shell and any other shells it starts will have to remake
  4226. the environment. If we make it before we fork, other shells won't
  4227. have to. Don't bother if we have any temporary variable assignments,
  4228. though, because the export environment will be remade after this
  4229. command completes anyway, but do it if all the words to be expanded
  4230. are variable assignments. */
  4231. if (subst_assign_varlist == 0 || garglist == 0)
  4232. maybe_make_export_env (); /* XXX */
  4233. /* Flags to pass to parse_and_execute() */
  4234. pflags = interactive ? SEVAL_RESETLINE : 0;
  4235. /* Pipe the output of executing STRING into the current shell. */
  4236. if (pipe (fildes) < 0)
  4237. {
  4238. sys_error (_("cannot make pipe for command substitution"));
  4239. goto error_exit;
  4240. }
  4241. old_pid = last_made_pid;
  4242. #if defined (JOB_CONTROL)
  4243. old_pipeline_pgrp = pipeline_pgrp;
  4244. /* Don't reset the pipeline pgrp if we're already a subshell in a pipeline. */
  4245. if ((subshell_environment & SUBSHELL_PIPE) == 0)
  4246. pipeline_pgrp = shell_pgrp;
  4247. cleanup_the_pipeline ();
  4248. #endif /* JOB_CONTROL */
  4249. old_async_pid = last_asynchronous_pid;
  4250. pid = make_child ((char *)NULL, subshell_environment&SUBSHELL_ASYNC);
  4251. last_asynchronous_pid = old_async_pid;
  4252. if (pid == 0)
  4253. /* Reset the signal handlers in the child, but don't free the
  4254. trap strings. */
  4255. reset_signal_handlers ();
  4256. #if defined (JOB_CONTROL)
  4257. /* XXX DO THIS ONLY IN PARENT ? XXX */
  4258. set_sigchld_handler ();
  4259. stop_making_children ();
  4260. if (pid != 0)
  4261. pipeline_pgrp = old_pipeline_pgrp;
  4262. #else
  4263. stop_making_children ();
  4264. #endif /* JOB_CONTROL */
  4265. if (pid < 0)
  4266. {
  4267. sys_error (_("cannot make child for command substitution"));
  4268. error_exit:
  4269. FREE (istring);
  4270. close (fildes[0]);
  4271. close (fildes[1]);
  4272. return ((WORD_DESC *)NULL);
  4273. }
  4274. if (pid == 0)
  4275. {
  4276. set_sigint_handler (); /* XXX */
  4277. free_pushed_string_input ();
  4278. if (dup2 (fildes[1], 1) < 0)
  4279. {
  4280. sys_error (_("command_substitute: cannot duplicate pipe as fd 1"));
  4281. exit (EXECUTION_FAILURE);
  4282. }
  4283. /* If standard output is closed in the parent shell
  4284. (such as after `exec >&-'), file descriptor 1 will be
  4285. the lowest available file descriptor, and end up in
  4286. fildes[0]. This can happen for stdin and stderr as well,
  4287. but stdout is more important -- it will cause no output
  4288. to be generated from this command. */
  4289. if ((fildes[1] != fileno (stdin)) &&
  4290. (fildes[1] != fileno (stdout)) &&
  4291. (fildes[1] != fileno (stderr)))
  4292. close (fildes[1]);
  4293. if ((fildes[0] != fileno (stdin)) &&
  4294. (fildes[0] != fileno (stdout)) &&
  4295. (fildes[0] != fileno (stderr)))
  4296. close (fildes[0]);
  4297. /* The currently executing shell is not interactive. */
  4298. interactive = 0;
  4299. /* This is a subshell environment. */
  4300. subshell_environment |= SUBSHELL_COMSUB;
  4301. /* When not in POSIX mode, command substitution does not inherit
  4302. the -e flag. */
  4303. if (posixly_correct == 0)
  4304. exit_immediately_on_error = 0;
  4305. remove_quoted_escapes (string);
  4306. startup_state = 2; /* see if we can avoid a fork */
  4307. /* Give command substitution a place to jump back to on failure,
  4308. so we don't go back up to main (). */
  4309. result = setjmp (top_level);
  4310. /* If we're running a command substitution inside a shell function,
  4311. trap `return' so we don't return from the function in the subshell
  4312. and go off to never-never land. */
  4313. if (result == 0 && return_catch_flag)
  4314. function_value = setjmp (return_catch);
  4315. else
  4316. function_value = 0;
  4317. if (result == ERREXIT)
  4318. rc = last_command_exit_value;
  4319. else if (result == EXITPROG)
  4320. rc = last_command_exit_value;
  4321. else if (result)
  4322. rc = EXECUTION_FAILURE;
  4323. else if (function_value)
  4324. rc = return_catch_value;
  4325. else
  4326. {
  4327. subshell_level++;
  4328. rc = parse_and_execute (string, "command substitution", pflags|SEVAL_NOHIST);
  4329. subshell_level--;
  4330. }
  4331. last_command_exit_value = rc;
  4332. rc = run_exit_trap ();
  4333. #if defined (PROCESS_SUBSTITUTION)
  4334. unlink_fifo_list ();
  4335. #endif
  4336. exit (rc);
  4337. }
  4338. else
  4339. {
  4340. #if defined (JOB_CONTROL) && defined (PGRP_PIPE)
  4341. close_pgrp_pipe ();
  4342. #endif /* JOB_CONTROL && PGRP_PIPE */
  4343. close (fildes[1]);
  4344. tflag = 0;
  4345. istring = read_comsub (fildes[0], quoted, &tflag);
  4346. close (fildes[0]);
  4347. current_command_subst_pid = pid;
  4348. last_command_exit_value = wait_for (pid);
  4349. last_command_subst_pid = pid;
  4350. last_made_pid = old_pid;
  4351. #if defined (JOB_CONTROL)
  4352. /* If last_command_exit_value > 128, then the substituted command
  4353. was terminated by a signal. If that signal was SIGINT, then send
  4354. SIGINT to ourselves. This will break out of loops, for instance. */
  4355. if (last_command_exit_value == (128 + SIGINT) && last_command_exit_signal == SIGINT)
  4356. kill (getpid (), SIGINT);
  4357. /* wait_for gives the terminal back to shell_pgrp. If some other
  4358. process group should have it, give it away to that group here.
  4359. pipeline_pgrp is non-zero only while we are constructing a
  4360. pipline, so what we are concerned about is whether or not that
  4361. pipeline was started in the background. A pipeline started in
  4362. the background should never get the tty back here. */
  4363. #if 0
  4364. if (interactive && pipeline_pgrp != (pid_t)0 && pipeline_pgrp != last_asynchronous_pid)
  4365. #else
  4366. if (interactive && pipeline_pgrp != (pid_t)0 && (subshell_environment & SUBSHELL_ASYNC) == 0)
  4367. #endif
  4368. give_terminal_to (pipeline_pgrp, 0);
  4369. #endif /* JOB_CONTROL */
  4370. ret = alloc_word_desc ();
  4371. ret->word = istring;
  4372. ret->flags = tflag;
  4373. return ret;
  4374. }
  4375. }
  4376. /********************************************************
  4377. * *
  4378. * Utility functions for parameter expansion *
  4379. * *
  4380. ********************************************************/
  4381. #if defined (ARRAY_VARS)
  4382. static arrayind_t
  4383. array_length_reference (s)
  4384. char *s;
  4385. {
  4386. int len;
  4387. arrayind_t ind;
  4388. char *akey;
  4389. char *t, c;
  4390. ARRAY *array;
  4391. SHELL_VAR *var;
  4392. var = array_variable_part (s, &t, &len);
  4393. /* If unbound variables should generate an error, report one and return
  4394. failure. */
  4395. if ((var == 0 || (assoc_p (var) == 0 && array_p (var) == 0)) && unbound_vars_is_error)
  4396. {
  4397. c = *--t;
  4398. *t = '\0';
  4399. err_unboundvar (s);
  4400. *t = c;
  4401. return (-1);
  4402. }
  4403. else if (var == 0)
  4404. return 0;
  4405. /* We support a couple of expansions for variables that are not arrays.
  4406. We'll return the length of the value for v[0], and 1 for v[@] or
  4407. v[*]. Return 0 for everything else. */
  4408. array = array_p (var) ? array_cell (var) : (ARRAY *)NULL;
  4409. if (ALL_ELEMENT_SUB (t[0]) && t[1] == ']')
  4410. {
  4411. if (assoc_p (var))
  4412. return (assoc_num_elements (assoc_cell (var)));
  4413. else if (array_p (var))
  4414. return (array_num_elements (array));
  4415. else
  4416. return 1;
  4417. }
  4418. if (assoc_p (var))
  4419. {
  4420. t[len - 1] = '\0';
  4421. akey = expand_assignment_string_to_string (t, 0); /* [ */
  4422. t[len - 1] = ']';
  4423. if (akey == 0 || *akey == 0)
  4424. {
  4425. err_badarraysub (t);
  4426. return (-1);
  4427. }
  4428. t = assoc_reference (assoc_cell (var), akey);
  4429. }
  4430. else
  4431. {
  4432. ind = array_expand_index (t, len);
  4433. if (ind < 0)
  4434. {
  4435. err_badarraysub (t);
  4436. return (-1);
  4437. }
  4438. if (array_p (var))
  4439. t = array_reference (array, ind);
  4440. else
  4441. t = (ind == 0) ? value_cell (var) : (char *)NULL;
  4442. }
  4443. len = MB_STRLEN (t);
  4444. return (len);
  4445. }
  4446. #endif /* ARRAY_VARS */
  4447. static int
  4448. valid_brace_expansion_word (name, var_is_special)
  4449. char *name;
  4450. int var_is_special;
  4451. {
  4452. if (DIGIT (*name) && all_digits (name))
  4453. return 1;
  4454. else if (var_is_special)
  4455. return 1;
  4456. #if defined (ARRAY_VARS)
  4457. else if (valid_array_reference (name))
  4458. return 1;
  4459. #endif /* ARRAY_VARS */
  4460. else if (legal_identifier (name))
  4461. return 1;
  4462. else
  4463. return 0;
  4464. }
  4465. static int
  4466. chk_atstar (name, quoted, quoted_dollar_atp, contains_dollar_at)
  4467. char *name;
  4468. int quoted;
  4469. int *quoted_dollar_atp, *contains_dollar_at;
  4470. {
  4471. char *temp1;
  4472. if (name == 0)
  4473. {
  4474. if (quoted_dollar_atp)
  4475. *quoted_dollar_atp = 0;
  4476. if (contains_dollar_at)
  4477. *contains_dollar_at = 0;
  4478. return 0;
  4479. }
  4480. /* check for $@ and $* */
  4481. if (name[0] == '@' && name[1] == 0)
  4482. {
  4483. if ((quoted & (Q_HERE_DOCUMENT|Q_DOUBLE_QUOTES)) && quoted_dollar_atp)
  4484. *quoted_dollar_atp = 1;
  4485. if (contains_dollar_at)
  4486. *contains_dollar_at = 1;
  4487. return 1;
  4488. }
  4489. else if (name[0] == '*' && name[1] == '\0' && quoted == 0)
  4490. {
  4491. if (contains_dollar_at)
  4492. *contains_dollar_at = 1;
  4493. return 1;
  4494. }
  4495. /* Now check for ${array[@]} and ${array[*]} */
  4496. #if defined (ARRAY_VARS)
  4497. else if (valid_array_reference (name))
  4498. {
  4499. temp1 = xstrchr (name, '[');
  4500. if (temp1 && temp1[1] == '@' && temp1[2] == ']')
  4501. {
  4502. if ((quoted & (Q_HERE_DOCUMENT|Q_DOUBLE_QUOTES)) && quoted_dollar_atp)
  4503. *quoted_dollar_atp = 1;
  4504. if (contains_dollar_at)
  4505. *contains_dollar_at = 1;
  4506. return 1;
  4507. } /* [ */
  4508. /* ${array[*]}, when unquoted, should be treated like ${array[@]},
  4509. which should result in separate words even when IFS is unset. */
  4510. if (temp1 && temp1[1] == '*' && temp1[2] == ']' && quoted == 0)
  4511. {
  4512. if (contains_dollar_at)
  4513. *contains_dollar_at = 1;
  4514. return 1;
  4515. }
  4516. }
  4517. #endif
  4518. return 0;
  4519. }
  4520. /* Parameter expand NAME, and return a new string which is the expansion,
  4521. or NULL if there was no expansion.
  4522. VAR_IS_SPECIAL is non-zero if NAME is one of the special variables in
  4523. the shell, e.g., "@", "$", "*", etc. QUOTED, if non-zero, means that
  4524. NAME was found inside of a double-quoted expression. */
  4525. static WORD_DESC *
  4526. parameter_brace_expand_word (name, var_is_special, quoted, pflags)
  4527. char *name;
  4528. int var_is_special, quoted, pflags;
  4529. {
  4530. WORD_DESC *ret;
  4531. char *temp, *tt;
  4532. intmax_t arg_index;
  4533. SHELL_VAR *var;
  4534. int atype, rflags;
  4535. ret = 0;
  4536. temp = 0;
  4537. rflags = 0;
  4538. /* Handle multiple digit arguments, as in ${11}. */
  4539. if (legal_number (name, &arg_index))
  4540. {
  4541. tt = get_dollar_var_value (arg_index);
  4542. if (tt)
  4543. temp = (*tt && (quoted & (Q_DOUBLE_QUOTES|Q_HERE_DOCUMENT)))
  4544. ? quote_string (tt)
  4545. : quote_escapes (tt);
  4546. else
  4547. temp = (char *)NULL;
  4548. FREE (tt);
  4549. }
  4550. else if (var_is_special) /* ${@} */
  4551. {
  4552. int sindex;
  4553. tt = (char *)xmalloc (2 + strlen (name));
  4554. tt[sindex = 0] = '$';
  4555. strcpy (tt + 1, name);
  4556. ret = param_expand (tt, &sindex, quoted, (int *)NULL, (int *)NULL,
  4557. (int *)NULL, (int *)NULL, pflags);
  4558. free (tt);
  4559. }
  4560. #if defined (ARRAY_VARS)
  4561. else if (valid_array_reference (name))
  4562. {
  4563. temp = array_value (name, quoted, &atype);
  4564. if (atype == 0 && temp)
  4565. temp = (*temp && (quoted & (Q_DOUBLE_QUOTES|Q_HERE_DOCUMENT)))
  4566. ? quote_string (temp)
  4567. : quote_escapes (temp);
  4568. else if (atype == 1 && temp && QUOTED_NULL (temp) && (quoted & (Q_DOUBLE_QUOTES|Q_HERE_DOCUMENT)))
  4569. rflags |= W_HASQUOTEDNULL;
  4570. }
  4571. #endif
  4572. else if (var = find_variable (name))
  4573. {
  4574. if (var_isset (var) && invisible_p (var) == 0)
  4575. {
  4576. #if defined (ARRAY_VARS)
  4577. if (assoc_p (var))
  4578. temp = assoc_reference (assoc_cell (var), "0");
  4579. else if (array_p (var))
  4580. temp = array_reference (array_cell (var), 0);
  4581. else
  4582. temp = value_cell (var);
  4583. #else
  4584. temp = value_cell (var);
  4585. #endif
  4586. if (temp)
  4587. temp = (*temp && (quoted & (Q_DOUBLE_QUOTES|Q_HERE_DOCUMENT)))
  4588. ? quote_string (temp)
  4589. : quote_escapes (temp);
  4590. }
  4591. else
  4592. temp = (char *)NULL;
  4593. }
  4594. else
  4595. temp = (char *)NULL;
  4596. if (ret == 0)
  4597. {
  4598. ret = alloc_word_desc ();
  4599. ret->word = temp;
  4600. ret->flags |= rflags;
  4601. }
  4602. return ret;
  4603. }
  4604. /* Expand an indirect reference to a variable: ${!NAME} expands to the
  4605. value of the variable whose name is the value of NAME. */
  4606. static WORD_DESC *
  4607. parameter_brace_expand_indir (name, var_is_special, quoted, quoted_dollar_atp, contains_dollar_at)
  4608. char *name;
  4609. int var_is_special, quoted;
  4610. int *quoted_dollar_atp, *contains_dollar_at;
  4611. {
  4612. char *temp, *t;
  4613. WORD_DESC *w;
  4614. w = parameter_brace_expand_word (name, var_is_special, quoted, PF_IGNUNBOUND);
  4615. t = w->word;
  4616. /* Have to dequote here if necessary */
  4617. if (t)
  4618. {
  4619. temp = (quoted & (Q_DOUBLE_QUOTES|Q_HERE_DOCUMENT))
  4620. ? dequote_string (t)
  4621. : dequote_escapes (t);
  4622. free (t);
  4623. t = temp;
  4624. }
  4625. dispose_word_desc (w);
  4626. chk_atstar (t, quoted, quoted_dollar_atp, contains_dollar_at);
  4627. if (t == 0)
  4628. return (WORD_DESC *)NULL;
  4629. w = parameter_brace_expand_word (t, SPECIAL_VAR(t, 0), quoted, 0);
  4630. free (t);
  4631. return w;
  4632. }
  4633. /* Expand the right side of a parameter expansion of the form ${NAMEcVALUE},
  4634. depending on the value of C, the separating character. C can be one of
  4635. "-", "+", or "=". QUOTED is true if the entire brace expression occurs
  4636. between double quotes. */
  4637. static WORD_DESC *
  4638. parameter_brace_expand_rhs (name, value, c, quoted, qdollaratp, hasdollarat)
  4639. char *name, *value;
  4640. int c, quoted, *qdollaratp, *hasdollarat;
  4641. {
  4642. WORD_DESC *w;
  4643. WORD_LIST *l;
  4644. char *t, *t1, *temp;
  4645. int hasdol;
  4646. /* If the entire expression is between double quotes, we want to treat
  4647. the value as a double-quoted string, with the exception that we strip
  4648. embedded unescaped double quotes (for sh backwards compatibility). */
  4649. if ((quoted & (Q_HERE_DOCUMENT|Q_DOUBLE_QUOTES)) && *value)
  4650. {
  4651. hasdol = 0;
  4652. temp = string_extract_double_quoted (value, &hasdol, 1);
  4653. }
  4654. else
  4655. temp = value;
  4656. w = alloc_word_desc ();
  4657. hasdol = 0;
  4658. /* XXX was 0 not quoted */
  4659. l = *temp ? expand_string_for_rhs (temp, quoted, &hasdol, (int *)NULL)
  4660. : (WORD_LIST *)0;
  4661. if (hasdollarat)
  4662. *hasdollarat = hasdol || (l && l->next);
  4663. if (temp != value)
  4664. free (temp);
  4665. if (l)
  4666. {
  4667. /* The expansion of TEMP returned something. We need to treat things
  4668. slightly differently if HASDOL is non-zero. If we have "$@", the
  4669. individual words have already been quoted. We need to turn them
  4670. into a string with the words separated by the first character of
  4671. $IFS without any additional quoting, so string_list_dollar_at won't
  4672. do the right thing. We use string_list_dollar_star instead. */
  4673. temp = (hasdol || l->next) ? string_list_dollar_star (l) : string_list (l);
  4674. /* If l->next is not null, we know that TEMP contained "$@", since that
  4675. is the only expansion that creates more than one word. */
  4676. if (qdollaratp && ((hasdol && quoted) || l->next))
  4677. *qdollaratp = 1;
  4678. dispose_words (l);
  4679. }
  4680. else if ((quoted & (Q_HERE_DOCUMENT|Q_DOUBLE_QUOTES)) && hasdol)
  4681. {
  4682. /* The brace expansion occurred between double quotes and there was
  4683. a $@ in TEMP. It does not matter if the $@ is quoted, as long as
  4684. it does not expand to anything. In this case, we want to return
  4685. a quoted empty string. */
  4686. temp = make_quoted_char ('\0');
  4687. w->flags |= W_HASQUOTEDNULL;
  4688. }
  4689. else
  4690. temp = (char *)NULL;
  4691. if (c == '-' || c == '+')
  4692. {
  4693. w->word = temp;
  4694. return w;
  4695. }
  4696. /* c == '=' */
  4697. t = temp ? savestring (temp) : savestring ("");
  4698. t1 = dequote_string (t);
  4699. free (t);
  4700. #if defined (ARRAY_VARS)
  4701. if (valid_array_reference (name))
  4702. assign_array_element (name, t1, 0);
  4703. else
  4704. #endif /* ARRAY_VARS */
  4705. bind_variable (name, t1, 0);
  4706. free (t1);
  4707. w->word = temp;
  4708. return w;
  4709. }
  4710. /* Deal with the right hand side of a ${name:?value} expansion in the case
  4711. that NAME is null or not set. If VALUE is non-null it is expanded and
  4712. used as the error message to print, otherwise a standard message is
  4713. printed. */
  4714. static void
  4715. parameter_brace_expand_error (name, value)
  4716. char *name, *value;
  4717. {
  4718. WORD_LIST *l;
  4719. char *temp;
  4720. if (value && *value)
  4721. {
  4722. l = expand_string (value, 0);
  4723. temp = string_list (l);
  4724. report_error ("%s: %s", name, temp ? temp : ""); /* XXX was value not "" */
  4725. FREE (temp);
  4726. dispose_words (l);
  4727. }
  4728. else
  4729. report_error (_("%s: parameter null or not set"), name);
  4730. /* Free the data we have allocated during this expansion, since we
  4731. are about to longjmp out. */
  4732. free (name);
  4733. FREE (value);
  4734. }
  4735. /* Return 1 if NAME is something for which parameter_brace_expand_length is
  4736. OK to do. */
  4737. static int
  4738. valid_length_expression (name)
  4739. char *name;
  4740. {
  4741. return (name[1] == '\0' || /* ${#} */
  4742. ((sh_syntaxtab[(unsigned char) name[1]] & CSPECVAR) && name[2] == '\0') || /* special param */
  4743. (DIGIT (name[1]) && all_digits (name + 1)) || /* ${#11} */
  4744. #if defined (ARRAY_VARS)
  4745. valid_array_reference (name + 1) || /* ${#a[7]} */
  4746. #endif
  4747. legal_identifier (name + 1)); /* ${#PS1} */
  4748. }
  4749. #if defined (HANDLE_MULTIBYTE)
  4750. size_t
  4751. mbstrlen (s)
  4752. const char *s;
  4753. {
  4754. size_t clen, nc;
  4755. mbstate_t mbs, mbsbak;
  4756. nc = 0;
  4757. memset (&mbs, 0, sizeof (mbs));
  4758. mbsbak = mbs;
  4759. while ((clen = mbrlen(s, MB_CUR_MAX, &mbs)) != 0)
  4760. {
  4761. if (MB_INVALIDCH(clen))
  4762. {
  4763. clen = 1; /* assume single byte */
  4764. mbs = mbsbak;
  4765. }
  4766. s += clen;
  4767. nc++;
  4768. mbsbak = mbs;
  4769. }
  4770. return nc;
  4771. }
  4772. #endif
  4773. /* Handle the parameter brace expansion that requires us to return the
  4774. length of a parameter. */
  4775. static intmax_t
  4776. parameter_brace_expand_length (name)
  4777. char *name;
  4778. {
  4779. char *t, *newname;
  4780. intmax_t number, arg_index;
  4781. WORD_LIST *list;
  4782. #if defined (ARRAY_VARS)
  4783. SHELL_VAR *var;
  4784. #endif
  4785. if (name[1] == '\0') /* ${#} */
  4786. number = number_of_args ();
  4787. else if ((name[1] == '@' || name[1] == '*') && name[2] == '\0') /* ${#@}, ${#*} */
  4788. number = number_of_args ();
  4789. else if ((sh_syntaxtab[(unsigned char) name[1]] & CSPECVAR) && name[2] == '\0')
  4790. {
  4791. /* Take the lengths of some of the shell's special parameters. */
  4792. switch (name[1])
  4793. {
  4794. case '-':
  4795. t = which_set_flags ();
  4796. break;
  4797. case '?':
  4798. t = itos (last_command_exit_value);
  4799. break;
  4800. case '$':
  4801. t = itos (dollar_dollar_pid);
  4802. break;
  4803. case '!':
  4804. if (last_asynchronous_pid == NO_PID)
  4805. t = (char *)NULL;
  4806. else
  4807. t = itos (last_asynchronous_pid);
  4808. break;
  4809. case '#':
  4810. t = itos (number_of_args ());
  4811. break;
  4812. }
  4813. number = STRLEN (t);
  4814. FREE (t);
  4815. }
  4816. #if defined (ARRAY_VARS)
  4817. else if (valid_array_reference (name + 1))
  4818. number = array_length_reference (name + 1);
  4819. #endif /* ARRAY_VARS */
  4820. else
  4821. {
  4822. number = 0;
  4823. if (legal_number (name + 1, &arg_index)) /* ${#1} */
  4824. {
  4825. t = get_dollar_var_value (arg_index);
  4826. number = MB_STRLEN (t);
  4827. FREE (t);
  4828. }
  4829. #if defined (ARRAY_VARS)
  4830. else if ((var = find_variable (name + 1)) && (invisible_p (var) == 0) && (array_p (var) || assoc_p (var)))
  4831. {
  4832. if (assoc_p (var))
  4833. t = assoc_reference (assoc_cell (var), "0");
  4834. else
  4835. t = array_reference (array_cell (var), 0);
  4836. number = MB_STRLEN (t);
  4837. }
  4838. #endif
  4839. else /* ${#PS1} */
  4840. {
  4841. newname = savestring (name);
  4842. newname[0] = '$';
  4843. list = expand_string (newname, Q_DOUBLE_QUOTES);
  4844. t = list ? string_list (list) : (char *)NULL;
  4845. free (newname);
  4846. if (list)
  4847. dispose_words (list);
  4848. number = MB_STRLEN (t);
  4849. FREE (t);
  4850. }
  4851. }
  4852. return (number);
  4853. }
  4854. /* Skip characters in SUBSTR until DELIM. SUBSTR is an arithmetic expression,
  4855. so we do some ad-hoc parsing of an arithmetic expression to find
  4856. the first DELIM, instead of using strchr(3). Two rules:
  4857. 1. If the substring contains a `(', read until closing `)'.
  4858. 2. If the substring contains a `?', read past one `:' for each `?'.
  4859. */
  4860. static char *
  4861. skiparith (substr, delim)
  4862. char *substr;
  4863. int delim;
  4864. {
  4865. size_t sublen;
  4866. int skipcol, pcount, i;
  4867. DECLARE_MBSTATE;
  4868. sublen = strlen (substr);
  4869. i = skipcol = pcount = 0;
  4870. while (substr[i])
  4871. {
  4872. /* Balance parens */
  4873. if (substr[i] == LPAREN)
  4874. {
  4875. pcount++;
  4876. i++;
  4877. continue;
  4878. }
  4879. if (substr[i] == RPAREN && pcount)
  4880. {
  4881. pcount--;
  4882. i++;
  4883. continue;
  4884. }
  4885. if (pcount)
  4886. {
  4887. ADVANCE_CHAR (substr, sublen, i);
  4888. continue;
  4889. }
  4890. /* Skip one `:' for each `?' */
  4891. if (substr[i] == ':' && skipcol)
  4892. {
  4893. skipcol--;
  4894. i++;
  4895. continue;
  4896. }
  4897. if (substr[i] == delim)
  4898. break;
  4899. if (substr[i] == '?')
  4900. {
  4901. skipcol++;
  4902. i++;
  4903. continue;
  4904. }
  4905. ADVANCE_CHAR (substr, sublen, i);
  4906. }
  4907. return (substr + i);
  4908. }
  4909. /* Verify and limit the start and end of the desired substring. If
  4910. VTYPE == 0, a regular shell variable is being used; if it is 1,
  4911. then the positional parameters are being used; if it is 2, then
  4912. VALUE is really a pointer to an array variable that should be used.
  4913. Return value is 1 if both values were OK, 0 if there was a problem
  4914. with an invalid expression, or -1 if the values were out of range. */
  4915. static int
  4916. verify_substring_values (v, value, substr, vtype, e1p, e2p)
  4917. SHELL_VAR *v;
  4918. char *value, *substr;
  4919. int vtype;
  4920. intmax_t *e1p, *e2p;
  4921. {
  4922. char *t, *temp1, *temp2;
  4923. arrayind_t len;
  4924. int expok;
  4925. #if defined (ARRAY_VARS)
  4926. ARRAY *a;
  4927. HASH_TABLE *h;
  4928. #endif
  4929. /* duplicate behavior of strchr(3) */
  4930. t = skiparith (substr, ':');
  4931. if (*t && *t == ':')
  4932. *t = '\0';
  4933. else
  4934. t = (char *)0;
  4935. temp1 = expand_arith_string (substr, Q_DOUBLE_QUOTES);
  4936. *e1p = evalexp (temp1, &expok);
  4937. free (temp1);
  4938. if (expok == 0)
  4939. return (0);
  4940. len = -1; /* paranoia */
  4941. switch (vtype)
  4942. {
  4943. case VT_VARIABLE:
  4944. case VT_ARRAYMEMBER:
  4945. len = MB_STRLEN (value);
  4946. break;
  4947. case VT_POSPARMS:
  4948. len = number_of_args () + 1;
  4949. if (*e1p == 0)
  4950. len++; /* add one arg if counting from $0 */
  4951. break;
  4952. #if defined (ARRAY_VARS)
  4953. case VT_ARRAYVAR:
  4954. /* For arrays, the first value deals with array indices. Negative
  4955. offsets count from one past the array's maximum index. Associative
  4956. arrays treat the number of elements as the maximum index. */
  4957. if (assoc_p (v))
  4958. {
  4959. h = assoc_cell (v);
  4960. len = assoc_num_elements (h) + (*e1p < 0);
  4961. }
  4962. else
  4963. {
  4964. a = (ARRAY *)value;
  4965. len = array_max_index (a) + (*e1p < 0); /* arrays index from 0 to n - 1 */
  4966. }
  4967. break;
  4968. #endif
  4969. }
  4970. if (len == -1) /* paranoia */
  4971. return -1;
  4972. if (*e1p < 0) /* negative offsets count from end */
  4973. *e1p += len;
  4974. if (*e1p > len || *e1p < 0)
  4975. return (-1);
  4976. #if defined (ARRAY_VARS)
  4977. /* For arrays, the second offset deals with the number of elements. */
  4978. if (vtype == VT_ARRAYVAR)
  4979. len = assoc_p (v) ? assoc_num_elements (h) : array_num_elements (a);
  4980. #endif
  4981. if (t)
  4982. {
  4983. t++;
  4984. temp2 = savestring (t);
  4985. temp1 = expand_arith_string (temp2, Q_DOUBLE_QUOTES);
  4986. free (temp2);
  4987. t[-1] = ':';
  4988. *e2p = evalexp (temp1, &expok);
  4989. free (temp1);
  4990. if (expok == 0)
  4991. return (0);
  4992. if (*e2p < 0)
  4993. {
  4994. internal_error (_("%s: substring expression < 0"), t);
  4995. return (0);
  4996. }
  4997. #if defined (ARRAY_VARS)
  4998. /* In order to deal with sparse arrays, push the intelligence about how
  4999. to deal with the number of elements desired down to the array-
  5000. specific functions. */
  5001. if (vtype != VT_ARRAYVAR)
  5002. #endif
  5003. {
  5004. *e2p += *e1p; /* want E2 chars starting at E1 */
  5005. if (*e2p > len)
  5006. *e2p = len;
  5007. }
  5008. }
  5009. else
  5010. *e2p = len;
  5011. return (1);
  5012. }
  5013. /* Return the type of variable specified by VARNAME (simple variable,
  5014. positional param, or array variable). Also return the value specified
  5015. by VARNAME (value of a variable or a reference to an array element).
  5016. If this returns VT_VARIABLE, the caller assumes that CTLESC and CTLNUL
  5017. characters in the value are quoted with CTLESC and takes appropriate
  5018. steps. For convenience, *VALP is set to the dequoted VALUE. */
  5019. static int
  5020. get_var_and_type (varname, value, quoted, varp, valp)
  5021. char *varname, *value;
  5022. int quoted;
  5023. SHELL_VAR **varp;
  5024. char **valp;
  5025. {
  5026. int vtype;
  5027. char *temp;
  5028. #if defined (ARRAY_VARS)
  5029. SHELL_VAR *v;
  5030. #endif
  5031. /* This sets vtype to VT_VARIABLE or VT_POSPARMS */
  5032. vtype = (varname[0] == '@' || varname[0] == '*') && varname[1] == '\0';
  5033. if (vtype == VT_POSPARMS && varname[0] == '*')
  5034. vtype |= VT_STARSUB;
  5035. *varp = (SHELL_VAR *)NULL;
  5036. #if defined (ARRAY_VARS)
  5037. if (valid_array_reference (varname))
  5038. {
  5039. v = array_variable_part (varname, &temp, (int *)0);
  5040. if (v && (array_p (v) || assoc_p (v)))
  5041. { /* [ */
  5042. if (ALL_ELEMENT_SUB (temp[0]) && temp[1] == ']')
  5043. {
  5044. /* Callers have to differentiate betwen indexed and associative */
  5045. vtype = VT_ARRAYVAR;
  5046. if (temp[0] == '*')
  5047. vtype |= VT_STARSUB;
  5048. *valp = array_p (v) ? (char *)array_cell (v) : (char *)assoc_cell (v);
  5049. }
  5050. else
  5051. {
  5052. vtype = VT_ARRAYMEMBER;
  5053. *valp = array_value (varname, 1, (int *)NULL);
  5054. }
  5055. *varp = v;
  5056. }
  5057. else if (v && (ALL_ELEMENT_SUB (temp[0]) && temp[1] == ']'))
  5058. {
  5059. vtype = VT_VARIABLE;
  5060. *varp = v;
  5061. if (quoted & (Q_DOUBLE_QUOTES|Q_HERE_DOCUMENT))
  5062. *valp = dequote_string (value);
  5063. else
  5064. *valp = dequote_escapes (value);
  5065. }
  5066. else
  5067. {
  5068. vtype = VT_ARRAYMEMBER;
  5069. *varp = v;
  5070. *valp = array_value (varname, 1, (int *)NULL);
  5071. }
  5072. }
  5073. else if ((v = find_variable (varname)) && (invisible_p (v) == 0) && (assoc_p (v) || array_p (v)))
  5074. {
  5075. vtype = VT_ARRAYMEMBER;
  5076. *varp = v;
  5077. *valp = assoc_p (v) ? assoc_reference (assoc_cell (v), "0") : array_reference (array_cell (v), 0);
  5078. }
  5079. else
  5080. #endif
  5081. {
  5082. if (value && vtype == VT_VARIABLE)
  5083. {
  5084. if (quoted & (Q_DOUBLE_QUOTES|Q_HERE_DOCUMENT))
  5085. *valp = dequote_string (value);
  5086. else
  5087. *valp = dequote_escapes (value);
  5088. }
  5089. else
  5090. *valp = value;
  5091. }
  5092. return vtype;
  5093. }
  5094. /******************************************************/
  5095. /* */
  5096. /* Functions to extract substrings of variable values */
  5097. /* */
  5098. /******************************************************/
  5099. #if defined (HANDLE_MULTIBYTE)
  5100. /* Character-oriented rather than strictly byte-oriented substrings. S and
  5101. E, rather being strict indices into STRING, indicate character (possibly
  5102. multibyte character) positions that require calculation.
  5103. Used by the ${param:offset[:length]} expansion. */
  5104. static char *
  5105. mb_substring (string, s, e)
  5106. char *string;
  5107. int s, e;
  5108. {
  5109. char *tt;
  5110. int start, stop, i, slen;
  5111. DECLARE_MBSTATE;
  5112. start = 0;
  5113. /* Don't need string length in ADVANCE_CHAR unless multibyte chars possible. */
  5114. slen = (MB_CUR_MAX > 1) ? STRLEN (string) : 0;
  5115. i = s;
  5116. while (string[start] && i--)
  5117. ADVANCE_CHAR (string, slen, start);
  5118. stop = start;
  5119. i = e - s;
  5120. while (string[stop] && i--)
  5121. ADVANCE_CHAR (string, slen, stop);
  5122. tt = substring (string, start, stop);
  5123. return tt;
  5124. }
  5125. #endif
  5126. /* Process a variable substring expansion: ${name:e1[:e2]}. If VARNAME
  5127. is `@', use the positional parameters; otherwise, use the value of
  5128. VARNAME. If VARNAME is an array variable, use the array elements. */
  5129. static char *
  5130. parameter_brace_substring (varname, value, substr, quoted)
  5131. char *varname, *value, *substr;
  5132. int quoted;
  5133. {
  5134. intmax_t e1, e2;
  5135. int vtype, r, starsub;
  5136. char *temp, *val, *tt, *oname;
  5137. SHELL_VAR *v;
  5138. if (value == 0)
  5139. return ((char *)NULL);
  5140. oname = this_command_name;
  5141. this_command_name = varname;
  5142. vtype = get_var_and_type (varname, value, quoted, &v, &val);
  5143. if (vtype == -1)
  5144. {
  5145. this_command_name = oname;
  5146. return ((char *)NULL);
  5147. }
  5148. starsub = vtype & VT_STARSUB;
  5149. vtype &= ~VT_STARSUB;
  5150. r = verify_substring_values (v, val, substr, vtype, &e1, &e2);
  5151. this_command_name = oname;
  5152. if (r <= 0)
  5153. return ((r == 0) ? &expand_param_error : (char *)NULL);
  5154. switch (vtype)
  5155. {
  5156. case VT_VARIABLE:
  5157. case VT_ARRAYMEMBER:
  5158. #if defined (HANDLE_MULTIBYTE)
  5159. if (MB_CUR_MAX > 1)
  5160. tt = mb_substring (val, e1, e2);
  5161. else
  5162. #endif
  5163. tt = substring (val, e1, e2);
  5164. if (vtype == VT_VARIABLE)
  5165. FREE (val);
  5166. if (quoted & (Q_DOUBLE_QUOTES|Q_HERE_DOCUMENT))
  5167. temp = quote_string (tt);
  5168. else
  5169. temp = tt ? quote_escapes (tt) : (char *)NULL;
  5170. FREE (tt);
  5171. break;
  5172. case VT_POSPARMS:
  5173. tt = pos_params (varname, e1, e2, quoted);
  5174. if ((quoted & (Q_DOUBLE_QUOTES|Q_HERE_DOCUMENT)) == 0)
  5175. {
  5176. temp = tt ? quote_escapes (tt) : (char *)NULL;
  5177. FREE (tt);
  5178. }
  5179. else
  5180. temp = tt;
  5181. break;
  5182. #if defined (ARRAY_VARS)
  5183. case VT_ARRAYVAR:
  5184. if (assoc_p (v))
  5185. /* we convert to list and take first e2 elements starting at e1th
  5186. element -- officially undefined for now */
  5187. temp = assoc_subrange (assoc_cell (v), e1, e2, starsub, quoted);
  5188. else
  5189. /* We want E2 to be the number of elements desired (arrays can be sparse,
  5190. so verify_substring_values just returns the numbers specified and we
  5191. rely on array_subrange to understand how to deal with them). */
  5192. temp = array_subrange (array_cell (v), e1, e2, starsub, quoted);
  5193. /* array_subrange now calls array_quote_escapes as appropriate, so the
  5194. caller no longer needs to. */
  5195. break;
  5196. #endif
  5197. default:
  5198. temp = (char *)NULL;
  5199. }
  5200. return temp;
  5201. }
  5202. /****************************************************************/
  5203. /* */
  5204. /* Functions to perform pattern substitution on variable values */
  5205. /* */
  5206. /****************************************************************/
  5207. char *
  5208. pat_subst (string, pat, rep, mflags)
  5209. char *string, *pat, *rep;
  5210. int mflags;
  5211. {
  5212. char *ret, *s, *e, *str;
  5213. int rsize, rptr, l, replen, mtype;
  5214. mtype = mflags & MATCH_TYPEMASK;
  5215. /* Special cases:
  5216. * 1. A null pattern with mtype == MATCH_BEG means to prefix STRING
  5217. * with REP and return the result.
  5218. * 2. A null pattern with mtype == MATCH_END means to append REP to
  5219. * STRING and return the result.
  5220. */
  5221. if ((pat == 0 || *pat == 0) && (mtype == MATCH_BEG || mtype == MATCH_END))
  5222. {
  5223. replen = STRLEN (rep);
  5224. l = strlen (string);
  5225. ret = (char *)xmalloc (replen + l + 2);
  5226. if (replen == 0)
  5227. strcpy (ret, string);
  5228. else if (mtype == MATCH_BEG)
  5229. {
  5230. strcpy (ret, rep);
  5231. strcpy (ret + replen, string);
  5232. }
  5233. else
  5234. {
  5235. strcpy (ret, string);
  5236. strcpy (ret + l, rep);
  5237. }
  5238. return (ret);
  5239. }
  5240. ret = (char *)xmalloc (rsize = 64);
  5241. ret[0] = '\0';
  5242. for (replen = STRLEN (rep), rptr = 0, str = string;;)
  5243. {
  5244. if (match_pattern (str, pat, mtype, &s, &e) == 0)
  5245. break;
  5246. l = s - str;
  5247. RESIZE_MALLOCED_BUFFER (ret, rptr, (l + replen), rsize, 64);
  5248. /* OK, now copy the leading unmatched portion of the string (from
  5249. str to s) to ret starting at rptr (the current offset). Then copy
  5250. the replacement string at ret + rptr + (s - str). Increment
  5251. rptr (if necessary) and str and go on. */
  5252. if (l)
  5253. {
  5254. strncpy (ret + rptr, str, l);
  5255. rptr += l;
  5256. }
  5257. if (replen)
  5258. {
  5259. strncpy (ret + rptr, rep, replen);
  5260. rptr += replen;
  5261. }
  5262. str = e; /* e == end of match */
  5263. if (((mflags & MATCH_GLOBREP) == 0) || mtype != MATCH_ANY)
  5264. break;
  5265. if (s == e)
  5266. e++, str++; /* avoid infinite recursion on zero-length match */
  5267. }
  5268. /* Now copy the unmatched portion of the input string */
  5269. if (*str)
  5270. {
  5271. RESIZE_MALLOCED_BUFFER (ret, rptr, STRLEN(str) + 1, rsize, 64);
  5272. strcpy (ret + rptr, str);
  5273. }
  5274. else
  5275. ret[rptr] = '\0';
  5276. return ret;
  5277. }
  5278. /* Do pattern match and replacement on the positional parameters. */
  5279. static char *
  5280. pos_params_pat_subst (string, pat, rep, mflags)
  5281. char *string, *pat, *rep;
  5282. int mflags;
  5283. {
  5284. WORD_LIST *save, *params;
  5285. WORD_DESC *w;
  5286. char *ret;
  5287. int pchar, qflags;
  5288. save = params = list_rest_of_args ();
  5289. if (save == 0)
  5290. return ((char *)NULL);
  5291. for ( ; params; params = params->next)
  5292. {
  5293. ret = pat_subst (params->word->word, pat, rep, mflags);
  5294. w = alloc_word_desc ();
  5295. w->word = ret ? ret : savestring ("");
  5296. dispose_word (params->word);
  5297. params->word = w;
  5298. }
  5299. pchar = (mflags & MATCH_STARSUB) == MATCH_STARSUB ? '*' : '@';
  5300. qflags = (mflags & MATCH_QUOTED) == MATCH_QUOTED ? Q_DOUBLE_QUOTES : 0;
  5301. #if 0
  5302. if ((mflags & (MATCH_QUOTED|MATCH_STARSUB)) == (MATCH_QUOTED|MATCH_STARSUB))
  5303. ret = string_list_dollar_star (quote_list (save));
  5304. else if ((mflags & MATCH_STARSUB) == MATCH_STARSUB)
  5305. ret = string_list_dollar_star (save);
  5306. else if ((mflags & MATCH_QUOTED) == MATCH_QUOTED)
  5307. ret = string_list_dollar_at (save, qflags);
  5308. else
  5309. ret = string_list_dollar_star (save);
  5310. #else
  5311. ret = string_list_pos_params (pchar, save, qflags);
  5312. #endif
  5313. dispose_words (save);
  5314. return (ret);
  5315. }
  5316. /* Perform pattern substitution on VALUE, which is the expansion of
  5317. VARNAME. PATSUB is an expression supplying the pattern to match
  5318. and the string to substitute. QUOTED is a flags word containing
  5319. the type of quoting currently in effect. */
  5320. static char *
  5321. parameter_brace_patsub (varname, value, patsub, quoted)
  5322. char *varname, *value, *patsub;
  5323. int quoted;
  5324. {
  5325. int vtype, mflags, starsub, delim;
  5326. char *val, *temp, *pat, *rep, *p, *lpatsub, *tt;
  5327. SHELL_VAR *v;
  5328. if (value == 0)
  5329. return ((char *)NULL);
  5330. this_command_name = varname;
  5331. vtype = get_var_and_type (varname, value, quoted, &v, &val);
  5332. if (vtype == -1)
  5333. return ((char *)NULL);
  5334. starsub = vtype & VT_STARSUB;
  5335. vtype &= ~VT_STARSUB;
  5336. mflags = 0;
  5337. if (patsub && *patsub == '/')
  5338. {
  5339. mflags |= MATCH_GLOBREP;
  5340. patsub++;
  5341. }
  5342. /* Malloc this because expand_string_if_necessary or one of the expansion
  5343. functions in its call chain may free it on a substitution error. */
  5344. lpatsub = savestring (patsub);
  5345. if (quoted & (Q_HERE_DOCUMENT|Q_DOUBLE_QUOTES))
  5346. mflags |= MATCH_QUOTED;
  5347. if (starsub)
  5348. mflags |= MATCH_STARSUB;
  5349. /* If the pattern starts with a `/', make sure we skip over it when looking
  5350. for the replacement delimiter. */
  5351. #if 0
  5352. if (rep = quoted_strchr ((*patsub == '/') ? lpatsub+1 : lpatsub, '/', ST_BACKSL))
  5353. *rep++ = '\0';
  5354. else
  5355. rep = (char *)NULL;
  5356. #else
  5357. delim = skip_to_delim (lpatsub, ((*patsub == '/') ? 1 : 0), "/", 0);
  5358. if (lpatsub[delim] == '/')
  5359. {
  5360. lpatsub[delim] = 0;
  5361. rep = lpatsub + delim + 1;
  5362. }
  5363. else
  5364. rep = (char *)NULL;
  5365. #endif
  5366. if (rep && *rep == '\0')
  5367. rep = (char *)NULL;
  5368. /* Perform the same expansions on the pattern as performed by the
  5369. pattern removal expansions. */
  5370. pat = getpattern (lpatsub, quoted, 1);
  5371. if (rep)
  5372. {
  5373. if ((mflags & MATCH_QUOTED) == 0)
  5374. rep = expand_string_if_necessary (rep, quoted, expand_string_unsplit);
  5375. else
  5376. rep = expand_string_to_string_internal (rep, quoted, expand_string_unsplit);
  5377. }
  5378. /* ksh93 doesn't allow the match specifier to be a part of the expanded
  5379. pattern. This is an extension. Make sure we don't anchor the pattern
  5380. at the beginning or end of the string if we're doing global replacement,
  5381. though. */
  5382. p = pat;
  5383. if (mflags & MATCH_GLOBREP)
  5384. mflags |= MATCH_ANY;
  5385. else if (pat && pat[0] == '#')
  5386. {
  5387. mflags |= MATCH_BEG;
  5388. p++;
  5389. }
  5390. else if (pat && pat[0] == '%')
  5391. {
  5392. mflags |= MATCH_END;
  5393. p++;
  5394. }
  5395. else
  5396. mflags |= MATCH_ANY;
  5397. /* OK, we now want to substitute REP for PAT in VAL. If
  5398. flags & MATCH_GLOBREP is non-zero, the substitution is done
  5399. everywhere, otherwise only the first occurrence of PAT is
  5400. replaced. The pattern matching code doesn't understand
  5401. CTLESC quoting CTLESC and CTLNUL so we use the dequoted variable
  5402. values passed in (VT_VARIABLE) so the pattern substitution
  5403. code works right. We need to requote special chars after
  5404. we're done for VT_VARIABLE and VT_ARRAYMEMBER, and for the
  5405. other cases if QUOTED == 0, since the posparams and arrays
  5406. indexed by * or @ do special things when QUOTED != 0. */
  5407. switch (vtype)
  5408. {
  5409. case VT_VARIABLE:
  5410. case VT_ARRAYMEMBER:
  5411. temp = pat_subst (val, p, rep, mflags);
  5412. if (vtype == VT_VARIABLE)
  5413. FREE (val);
  5414. if (temp)
  5415. {
  5416. tt = (mflags & MATCH_QUOTED) ? quote_string (temp) : quote_escapes (temp);
  5417. free (temp);
  5418. temp = tt;
  5419. }
  5420. break;
  5421. case VT_POSPARMS:
  5422. temp = pos_params_pat_subst (val, p, rep, mflags);
  5423. if (temp && (mflags & MATCH_QUOTED) == 0)
  5424. {
  5425. tt = quote_escapes (temp);
  5426. free (temp);
  5427. temp = tt;
  5428. }
  5429. break;
  5430. #if defined (ARRAY_VARS)
  5431. case VT_ARRAYVAR:
  5432. temp = assoc_p (v) ? assoc_patsub (assoc_cell (v), p, rep, mflags)
  5433. : array_patsub (array_cell (v), p, rep, mflags);
  5434. /* Don't call quote_escapes anymore; array_patsub calls
  5435. array_quote_escapes as appropriate before adding the
  5436. space separators; ditto for assoc_patsub. */
  5437. break;
  5438. #endif
  5439. }
  5440. FREE (pat);
  5441. FREE (rep);
  5442. free (lpatsub);
  5443. return temp;
  5444. }
  5445. /****************************************************************/
  5446. /* */
  5447. /* Functions to perform case modification on variable values */
  5448. /* */
  5449. /****************************************************************/
  5450. /* Do case modification on the positional parameters. */
  5451. static char *
  5452. pos_params_modcase (string, pat, modop, mflags)
  5453. char *string, *pat;
  5454. int modop;
  5455. int mflags;
  5456. {
  5457. WORD_LIST *save, *params;
  5458. WORD_DESC *w;
  5459. char *ret;
  5460. int pchar, qflags;
  5461. save = params = list_rest_of_args ();
  5462. if (save == 0)
  5463. return ((char *)NULL);
  5464. for ( ; params; params = params->next)
  5465. {
  5466. ret = sh_modcase (params->word->word, pat, modop);
  5467. w = alloc_word_desc ();
  5468. w->word = ret ? ret : savestring ("");
  5469. dispose_word (params->word);
  5470. params->word = w;
  5471. }
  5472. pchar = (mflags & MATCH_STARSUB) == MATCH_STARSUB ? '*' : '@';
  5473. qflags = (mflags & MATCH_QUOTED) == MATCH_QUOTED ? Q_DOUBLE_QUOTES : 0;
  5474. ret = string_list_pos_params (pchar, save, qflags);
  5475. dispose_words (save);
  5476. return (ret);
  5477. }
  5478. /* Perform case modification on VALUE, which is the expansion of
  5479. VARNAME. MODSPEC is an expression supplying the type of modification
  5480. to perform. QUOTED is a flags word containing the type of quoting
  5481. currently in effect. */
  5482. static char *
  5483. parameter_brace_casemod (varname, value, modspec, patspec, quoted)
  5484. char *varname, *value;
  5485. int modspec;
  5486. char *patspec;
  5487. int quoted;
  5488. {
  5489. int vtype, starsub, modop, mflags, x;
  5490. char *val, *temp, *pat, *p, *lpat, *tt;
  5491. SHELL_VAR *v;
  5492. if (value == 0)
  5493. return ((char *)NULL);
  5494. this_command_name = varname;
  5495. vtype = get_var_and_type (varname, value, quoted, &v, &val);
  5496. if (vtype == -1)
  5497. return ((char *)NULL);
  5498. starsub = vtype & VT_STARSUB;
  5499. vtype &= ~VT_STARSUB;
  5500. modop = 0;
  5501. mflags = 0;
  5502. if (quoted & (Q_HERE_DOCUMENT|Q_DOUBLE_QUOTES))
  5503. mflags |= MATCH_QUOTED;
  5504. if (starsub)
  5505. mflags |= MATCH_STARSUB;
  5506. p = patspec;
  5507. if (modspec == '^')
  5508. {
  5509. x = p && p[0] == modspec;
  5510. modop = x ? CASE_UPPER : CASE_UPFIRST;
  5511. p += x;
  5512. }
  5513. else if (modspec == ',')
  5514. {
  5515. x = p && p[0] == modspec;
  5516. modop = x ? CASE_LOWER : CASE_LOWFIRST;
  5517. p += x;
  5518. }
  5519. else if (modspec == '~')
  5520. {
  5521. x = p && p[0] == modspec;
  5522. modop = x ? CASE_TOGGLEALL : CASE_TOGGLE;
  5523. p += x;
  5524. }
  5525. lpat = p ? savestring (p) : 0;
  5526. /* Perform the same expansions on the pattern as performed by the
  5527. pattern removal expansions. FOR LATER */
  5528. pat = lpat ? getpattern (lpat, quoted, 1) : 0;
  5529. /* OK, now we do the case modification. */
  5530. switch (vtype)
  5531. {
  5532. case VT_VARIABLE:
  5533. case VT_ARRAYMEMBER:
  5534. temp = sh_modcase (val, pat, modop);
  5535. if (vtype == VT_VARIABLE)
  5536. FREE (val);
  5537. if (temp)
  5538. {
  5539. tt = (mflags & MATCH_QUOTED) ? quote_string (temp) : quote_escapes (temp);
  5540. free (temp);
  5541. temp = tt;
  5542. }
  5543. break;
  5544. case VT_POSPARMS:
  5545. temp = pos_params_modcase (val, pat, modop, mflags);
  5546. if (temp && (mflags & MATCH_QUOTED) == 0)
  5547. {
  5548. tt = quote_escapes (temp);
  5549. free (temp);
  5550. temp = tt;
  5551. }
  5552. break;
  5553. #if defined (ARRAY_VARS)
  5554. case VT_ARRAYVAR:
  5555. temp = assoc_p (v) ? assoc_modcase (assoc_cell (v), pat, modop, mflags)
  5556. : array_modcase (array_cell (v), pat, modop, mflags);
  5557. /* Don't call quote_escapes; array_modcase calls array_quote_escapes
  5558. as appropriate before adding the space separators; ditto for
  5559. assoc_modcase. */
  5560. break;
  5561. #endif
  5562. }
  5563. FREE (pat);
  5564. free (lpat);
  5565. return temp;
  5566. }
  5567. /* Check for unbalanced parens in S, which is the contents of $(( ... )). If
  5568. any occur, this must be a nested command substitution, so return 0.
  5569. Otherwise, return 1. A valid arithmetic expression must always have a
  5570. ( before a matching ), so any cases where there are more right parens
  5571. means that this must not be an arithmetic expression, though the parser
  5572. will not accept it without a balanced total number of parens. */
  5573. static int
  5574. chk_arithsub (s, len)
  5575. const char *s;
  5576. int len;
  5577. {
  5578. int i, count;
  5579. DECLARE_MBSTATE;
  5580. i = count = 0;
  5581. while (i < len)
  5582. {
  5583. if (s[i] == '(')
  5584. count++;
  5585. else if (s[i] == ')')
  5586. {
  5587. count--;
  5588. if (count < 0)
  5589. return 0;
  5590. }
  5591. switch (s[i])
  5592. {
  5593. default:
  5594. ADVANCE_CHAR (s, len, i);
  5595. break;
  5596. case '\\':
  5597. i++;
  5598. if (s[i])
  5599. ADVANCE_CHAR (s, len, i);
  5600. break;
  5601. case '\'':
  5602. i = skip_single_quoted (s, len, ++i);
  5603. break;
  5604. case '"':
  5605. i = skip_double_quoted ((char *)s, len, ++i);
  5606. break;
  5607. }
  5608. }
  5609. return (count == 0);
  5610. }
  5611. /****************************************************************/
  5612. /* */
  5613. /* Functions to perform parameter expansion on a string */
  5614. /* */
  5615. /****************************************************************/
  5616. /* ${[#][!]name[[:][^[^]][,[,]]#[#]%[%]-=?+[word][:e1[:e2]]]} */
  5617. static WORD_DESC *
  5618. parameter_brace_expand (string, indexp, quoted, quoted_dollar_atp, contains_dollar_at)
  5619. char *string;
  5620. int *indexp, quoted, *quoted_dollar_atp, *contains_dollar_at;
  5621. {
  5622. int check_nullness, var_is_set, var_is_null, var_is_special;
  5623. int want_substring, want_indir, want_patsub, want_casemod;
  5624. char *name, *value, *temp, *temp1;
  5625. WORD_DESC *tdesc, *ret;
  5626. int t_index, sindex, c, tflag, modspec;
  5627. intmax_t number;
  5628. temp = temp1 = value = (char *)NULL;
  5629. var_is_set = var_is_null = var_is_special = check_nullness = 0;
  5630. want_substring = want_indir = want_patsub = want_casemod = 0;
  5631. sindex = *indexp;
  5632. t_index = ++sindex;
  5633. /* ${#var} doesn't have any of the other parameter expansions on it. */
  5634. if (string[t_index] == '#' && legal_variable_starter (string[t_index+1])) /* {{ */
  5635. name = string_extract (string, &t_index, "}", SX_VARNAME);
  5636. else
  5637. #if defined (CASEMOD_EXPANSIONS)
  5638. /* To enable case-toggling expansions using the `~' operator character
  5639. change the 1 to 0. */
  5640. # if defined (CASEMOD_CAPCASE)
  5641. name = string_extract (string, &t_index, "#%^,~:-=?+/}", SX_VARNAME);
  5642. # else
  5643. name = string_extract (string, &t_index, "#%^,:-=?+/}", SX_VARNAME);
  5644. # endif /* CASEMOD_CAPCASE */
  5645. #else
  5646. name = string_extract (string, &t_index, "#%:-=?+/}", SX_VARNAME);
  5647. #endif /* CASEMOD_EXPANSIONS */
  5648. ret = 0;
  5649. tflag = 0;
  5650. /* If the name really consists of a special variable, then make sure
  5651. that we have the entire name. We don't allow indirect references
  5652. to special variables except `#', `?', `@' and `*'. */
  5653. if ((sindex == t_index &&
  5654. (string[t_index] == '-' ||
  5655. string[t_index] == '?' ||
  5656. string[t_index] == '#')) ||
  5657. (sindex == t_index - 1 && string[sindex] == '!' &&
  5658. (string[t_index] == '#' ||
  5659. string[t_index] == '?' ||
  5660. string[t_index] == '@' ||
  5661. string[t_index] == '*')))
  5662. {
  5663. t_index++;
  5664. free (name);
  5665. temp1 = string_extract (string, &t_index, "#%:-=?+/}", 0);
  5666. name = (char *)xmalloc (3 + (strlen (temp1)));
  5667. *name = string[sindex];
  5668. if (string[sindex] == '!')
  5669. {
  5670. /* indirect reference of $#, $?, $@, or $* */
  5671. name[1] = string[sindex + 1];
  5672. strcpy (name + 2, temp1);
  5673. }
  5674. else
  5675. strcpy (name + 1, temp1);
  5676. free (temp1);
  5677. }
  5678. sindex = t_index;
  5679. /* Find out what character ended the variable name. Then
  5680. do the appropriate thing. */
  5681. if (c = string[sindex])
  5682. sindex++;
  5683. /* If c is followed by one of the valid parameter expansion
  5684. characters, move past it as normal. If not, assume that
  5685. a substring specification is being given, and do not move
  5686. past it. */
  5687. if (c == ':' && VALID_PARAM_EXPAND_CHAR (string[sindex]))
  5688. {
  5689. check_nullness++;
  5690. if (c = string[sindex])
  5691. sindex++;
  5692. }
  5693. else if (c == ':' && string[sindex] != RBRACE)
  5694. want_substring = 1;
  5695. else if (c == '/' && string[sindex] != RBRACE)
  5696. want_patsub = 1;
  5697. #if defined (CASEMOD_EXPANSIONS)
  5698. else if (c == '^' || c == ',' || c == '~')
  5699. {
  5700. modspec = c;
  5701. want_casemod = 1;
  5702. }
  5703. #endif
  5704. /* Catch the valid and invalid brace expressions that made it through the
  5705. tests above. */
  5706. /* ${#-} is a valid expansion and means to take the length of $-.
  5707. Similarly for ${#?} and ${##}... */
  5708. if (name[0] == '#' && name[1] == '\0' && check_nullness == 0 &&
  5709. VALID_SPECIAL_LENGTH_PARAM (c) && string[sindex] == RBRACE)
  5710. {
  5711. name = (char *)xrealloc (name, 3);
  5712. name[1] = c;
  5713. name[2] = '\0';
  5714. c = string[sindex++];
  5715. }
  5716. /* ...but ${#%}, ${#:}, ${#=}, ${#+}, and ${#/} are errors. */
  5717. if (name[0] == '#' && name[1] == '\0' && check_nullness == 0 &&
  5718. member (c, "%:=+/") && string[sindex] == RBRACE)
  5719. {
  5720. temp = (char *)NULL;
  5721. goto bad_substitution;
  5722. }
  5723. /* Indirect expansion begins with a `!'. A valid indirect expansion is
  5724. either a variable name, one of the positional parameters or a special
  5725. variable that expands to one of the positional parameters. */
  5726. want_indir = *name == '!' &&
  5727. (legal_variable_starter ((unsigned char)name[1]) || DIGIT (name[1])
  5728. || VALID_INDIR_PARAM (name[1]));
  5729. /* Determine the value of this variable. */
  5730. /* Check for special variables, directly referenced. */
  5731. if (SPECIAL_VAR (name, want_indir))
  5732. var_is_special++;
  5733. /* Check for special expansion things, like the length of a parameter */
  5734. if (*name == '#' && name[1])
  5735. {
  5736. /* If we are not pointing at the character just after the
  5737. closing brace, then we haven't gotten all of the name.
  5738. Since it begins with a special character, this is a bad
  5739. substitution. Also check NAME for validity before trying
  5740. to go on. */
  5741. if (string[sindex - 1] != RBRACE || (valid_length_expression (name) == 0))
  5742. {
  5743. temp = (char *)NULL;
  5744. goto bad_substitution;
  5745. }
  5746. number = parameter_brace_expand_length (name);
  5747. free (name);
  5748. *indexp = sindex;
  5749. if (number < 0)
  5750. return (&expand_wdesc_error);
  5751. else
  5752. {
  5753. ret = alloc_word_desc ();
  5754. ret->word = itos (number);
  5755. return ret;
  5756. }
  5757. }
  5758. /* ${@} is identical to $@. */
  5759. if (name[0] == '@' && name[1] == '\0')
  5760. {
  5761. if ((quoted & (Q_HERE_DOCUMENT|Q_DOUBLE_QUOTES)) && quoted_dollar_atp)
  5762. *quoted_dollar_atp = 1;
  5763. if (contains_dollar_at)
  5764. *contains_dollar_at = 1;
  5765. }
  5766. /* Process ${!PREFIX*} expansion. */
  5767. if (want_indir && string[sindex - 1] == RBRACE &&
  5768. (string[sindex - 2] == '*' || string[sindex - 2] == '@') &&
  5769. legal_variable_starter ((unsigned char) name[1]))
  5770. {
  5771. char **x;
  5772. WORD_LIST *xlist;
  5773. temp1 = savestring (name + 1);
  5774. number = strlen (temp1);
  5775. temp1[number - 1] = '\0';
  5776. x = all_variables_matching_prefix (temp1);
  5777. xlist = strvec_to_word_list (x, 0, 0);
  5778. if (string[sindex - 2] == '*')
  5779. temp = string_list_dollar_star (xlist);
  5780. else
  5781. {
  5782. temp = string_list_dollar_at (xlist, quoted);
  5783. if ((quoted & (Q_HERE_DOCUMENT|Q_DOUBLE_QUOTES)) && quoted_dollar_atp)
  5784. *quoted_dollar_atp = 1;
  5785. if (contains_dollar_at)
  5786. *contains_dollar_at = 1;
  5787. }
  5788. free (x);
  5789. dispose_words (xlist);
  5790. free (temp1);
  5791. *indexp = sindex;
  5792. ret = alloc_word_desc ();
  5793. ret->word = temp;
  5794. return ret;
  5795. }
  5796. #if defined (ARRAY_VARS)
  5797. /* Process ${!ARRAY[@]} and ${!ARRAY[*]} expansion. */ /* [ */
  5798. if (want_indir && string[sindex - 1] == RBRACE &&
  5799. string[sindex - 2] == ']' && valid_array_reference (name+1))
  5800. {
  5801. char *x, *x1;
  5802. temp1 = savestring (name + 1);
  5803. x = array_variable_name (temp1, &x1, (int *)0); /* [ */
  5804. FREE (x);
  5805. if (ALL_ELEMENT_SUB (x1[0]) && x1[1] == ']')
  5806. {
  5807. temp = array_keys (temp1, quoted); /* handles assoc vars too */
  5808. if (x1[0] == '@')
  5809. {
  5810. if ((quoted & (Q_HERE_DOCUMENT|Q_DOUBLE_QUOTES)) && quoted_dollar_atp)
  5811. *quoted_dollar_atp = 1;
  5812. if (contains_dollar_at)
  5813. *contains_dollar_at = 1;
  5814. }
  5815. free (temp1);
  5816. *indexp = sindex;
  5817. ret = alloc_word_desc ();
  5818. ret->word = temp;
  5819. return ret;
  5820. }
  5821. free (temp1);
  5822. }
  5823. #endif /* ARRAY_VARS */
  5824. /* Make sure that NAME is valid before trying to go on. */
  5825. if (valid_brace_expansion_word (want_indir ? name + 1 : name,
  5826. var_is_special) == 0)
  5827. {
  5828. temp = (char *)NULL;
  5829. goto bad_substitution;
  5830. }
  5831. if (want_indir)
  5832. tdesc = parameter_brace_expand_indir (name + 1, var_is_special, quoted, quoted_dollar_atp, contains_dollar_at);
  5833. else
  5834. tdesc = parameter_brace_expand_word (name, var_is_special, quoted, PF_IGNUNBOUND);
  5835. if (tdesc)
  5836. {
  5837. temp = tdesc->word;
  5838. tflag = tdesc->flags;
  5839. dispose_word_desc (tdesc);
  5840. }
  5841. else
  5842. temp = (char *)0;
  5843. #if defined (ARRAY_VARS)
  5844. if (valid_array_reference (name))
  5845. chk_atstar (name, quoted, quoted_dollar_atp, contains_dollar_at);
  5846. #endif
  5847. var_is_set = temp != (char *)0;
  5848. var_is_null = check_nullness && (var_is_set == 0 || *temp == 0);
  5849. /* Get the rest of the stuff inside the braces. */
  5850. if (c && c != RBRACE)
  5851. {
  5852. /* Extract the contents of the ${ ... } expansion
  5853. according to the Posix.2 rules. */
  5854. value = extract_dollar_brace_string (string, &sindex, quoted, 0);
  5855. if (string[sindex] == RBRACE)
  5856. sindex++;
  5857. else
  5858. goto bad_substitution;
  5859. }
  5860. else
  5861. value = (char *)NULL;
  5862. *indexp = sindex;
  5863. /* If this is a substring spec, process it and add the result. */
  5864. if (want_substring)
  5865. {
  5866. temp1 = parameter_brace_substring (name, temp, value, quoted);
  5867. FREE (name);
  5868. FREE (value);
  5869. FREE (temp);
  5870. if (temp1 == &expand_param_error)
  5871. return (&expand_wdesc_error);
  5872. else if (temp1 == &expand_param_fatal)
  5873. return (&expand_wdesc_fatal);
  5874. ret = alloc_word_desc ();
  5875. ret->word = temp1;
  5876. if (temp1 && QUOTED_NULL (temp1) && (quoted & (Q_HERE_DOCUMENT|Q_DOUBLE_QUOTES)))
  5877. ret->flags |= W_QUOTED|W_HASQUOTEDNULL;
  5878. return ret;
  5879. }
  5880. else if (want_patsub)
  5881. {
  5882. temp1 = parameter_brace_patsub (name, temp, value, quoted);
  5883. FREE (name);
  5884. FREE (value);
  5885. FREE (temp);
  5886. if (temp1 == &expand_param_error)
  5887. return (&expand_wdesc_error);
  5888. else if (temp1 == &expand_param_fatal)
  5889. return (&expand_wdesc_fatal);
  5890. ret = alloc_word_desc ();
  5891. ret->word = temp1;
  5892. ret = alloc_word_desc ();
  5893. ret->word = temp1;
  5894. if (temp1 && QUOTED_NULL (temp1) && (quoted & (Q_HERE_DOCUMENT|Q_DOUBLE_QUOTES)))
  5895. ret->flags |= W_QUOTED|W_HASQUOTEDNULL;
  5896. return ret;
  5897. }
  5898. #if defined (CASEMOD_EXPANSIONS)
  5899. else if (want_casemod)
  5900. {
  5901. temp1 = parameter_brace_casemod (name, temp, modspec, value, quoted);
  5902. FREE (name);
  5903. FREE (value);
  5904. FREE (temp);
  5905. if (temp1 == &expand_param_error)
  5906. return (&expand_wdesc_error);
  5907. else if (temp1 == &expand_param_fatal)
  5908. return (&expand_wdesc_fatal);
  5909. ret = alloc_word_desc ();
  5910. ret->word = temp1;
  5911. if (temp1 && QUOTED_NULL (temp1) && (quoted & (Q_HERE_DOCUMENT|Q_DOUBLE_QUOTES)))
  5912. ret->flags |= W_QUOTED|W_HASQUOTEDNULL;
  5913. return ret;
  5914. }
  5915. #endif
  5916. /* Do the right thing based on which character ended the variable name. */
  5917. switch (c)
  5918. {
  5919. default:
  5920. case '\0':
  5921. bad_substitution:
  5922. report_error (_("%s: bad substitution"), string ? string : "??");
  5923. FREE (value);
  5924. FREE (temp);
  5925. free (name);
  5926. return &expand_wdesc_error;
  5927. case RBRACE:
  5928. if (var_is_set == 0 && unbound_vars_is_error && ((name[0] != '@' && name[0] != '*') || name[1]))
  5929. {
  5930. last_command_exit_value = EXECUTION_FAILURE;
  5931. err_unboundvar (name);
  5932. FREE (value);
  5933. FREE (temp);
  5934. free (name);
  5935. return (interactive_shell ? &expand_wdesc_error : &expand_wdesc_fatal);
  5936. }
  5937. break;
  5938. case '#': /* ${param#[#]pattern} */
  5939. case '%': /* ${param%[%]pattern} */
  5940. if (value == 0 || *value == '\0' || temp == 0 || *temp == '\0')
  5941. {
  5942. FREE (value);
  5943. break;
  5944. }
  5945. temp1 = parameter_brace_remove_pattern (name, temp, value, c, quoted);
  5946. free (temp);
  5947. free (value);
  5948. ret = alloc_word_desc ();
  5949. ret->word = temp1;
  5950. if (temp1 && QUOTED_NULL (temp1) && (quoted & (Q_HERE_DOCUMENT|Q_DOUBLE_QUOTES)))
  5951. ret->flags |= W_QUOTED|W_HASQUOTEDNULL;
  5952. return ret;
  5953. case '-':
  5954. case '=':
  5955. case '?':
  5956. case '+':
  5957. if (var_is_set && var_is_null == 0)
  5958. {
  5959. /* If the operator is `+', we don't want the value of the named
  5960. variable for anything, just the value of the right hand side. */
  5961. if (c == '+')
  5962. {
  5963. /* XXX -- if we're double-quoted and the named variable is "$@",
  5964. we want to turn off any special handling of "$@" --
  5965. we're not using it, so whatever is on the rhs applies. */
  5966. if ((quoted & (Q_HERE_DOCUMENT|Q_DOUBLE_QUOTES)) && quoted_dollar_atp)
  5967. *quoted_dollar_atp = 0;
  5968. if (contains_dollar_at)
  5969. *contains_dollar_at = 0;
  5970. FREE (temp);
  5971. if (value)
  5972. {
  5973. ret = parameter_brace_expand_rhs (name, value, c,
  5974. quoted,
  5975. quoted_dollar_atp,
  5976. contains_dollar_at);
  5977. /* XXX - fix up later, esp. noting presence of
  5978. W_HASQUOTEDNULL in ret->flags */
  5979. free (value);
  5980. }
  5981. else
  5982. temp = (char *)NULL;
  5983. }
  5984. else
  5985. {
  5986. FREE (value);
  5987. }
  5988. /* Otherwise do nothing; just use the value in TEMP. */
  5989. }
  5990. else /* VAR not set or VAR is NULL. */
  5991. {
  5992. FREE (temp);
  5993. temp = (char *)NULL;
  5994. if (c == '=' && var_is_special)
  5995. {
  5996. report_error (_("$%s: cannot assign in this way"), name);
  5997. free (name);
  5998. free (value);
  5999. return &expand_wdesc_error;
  6000. }
  6001. else if (c == '?')
  6002. {
  6003. parameter_brace_expand_error (name, value);
  6004. return (interactive_shell ? &expand_wdesc_error : &expand_wdesc_fatal);
  6005. }
  6006. else if (c != '+')
  6007. {
  6008. /* XXX -- if we're double-quoted and the named variable is "$@",
  6009. we want to turn off any special handling of "$@" --
  6010. we're not using it, so whatever is on the rhs applies. */
  6011. if ((quoted & (Q_HERE_DOCUMENT|Q_DOUBLE_QUOTES)) && quoted_dollar_atp)
  6012. *quoted_dollar_atp = 0;
  6013. if (contains_dollar_at)
  6014. *contains_dollar_at = 0;
  6015. ret = parameter_brace_expand_rhs (name, value, c, quoted,
  6016. quoted_dollar_atp,
  6017. contains_dollar_at);
  6018. /* XXX - fix up later, esp. noting presence of
  6019. W_HASQUOTEDNULL in tdesc->flags */
  6020. }
  6021. free (value);
  6022. }
  6023. break;
  6024. }
  6025. free (name);
  6026. if (ret == 0)
  6027. {
  6028. ret = alloc_word_desc ();
  6029. ret->flags = tflag;
  6030. ret->word = temp;
  6031. }
  6032. return (ret);
  6033. }
  6034. /* Expand a single ${xxx} expansion. The braces are optional. When
  6035. the braces are used, parameter_brace_expand() does the work,
  6036. possibly calling param_expand recursively. */
  6037. static WORD_DESC *
  6038. param_expand (string, sindex, quoted, expanded_something,
  6039. contains_dollar_at, quoted_dollar_at_p, had_quoted_null_p,
  6040. pflags)
  6041. char *string;
  6042. int *sindex, quoted, *expanded_something, *contains_dollar_at;
  6043. int *quoted_dollar_at_p, *had_quoted_null_p, pflags;
  6044. {
  6045. char *temp, *temp1, uerror[3];
  6046. int zindex, t_index, expok;
  6047. unsigned char c;
  6048. intmax_t number;
  6049. SHELL_VAR *var;
  6050. WORD_LIST *list;
  6051. WORD_DESC *tdesc, *ret;
  6052. int tflag;
  6053. zindex = *sindex;
  6054. c = string[++zindex];
  6055. temp = (char *)NULL;
  6056. ret = tdesc = (WORD_DESC *)NULL;
  6057. tflag = 0;
  6058. /* Do simple cases first. Switch on what follows '$'. */
  6059. switch (c)
  6060. {
  6061. /* $0 .. $9? */
  6062. case '0':
  6063. case '1':
  6064. case '2':
  6065. case '3':
  6066. case '4':
  6067. case '5':
  6068. case '6':
  6069. case '7':
  6070. case '8':
  6071. case '9':
  6072. temp1 = dollar_vars[TODIGIT (c)];
  6073. if (unbound_vars_is_error && temp1 == (char *)NULL)
  6074. {
  6075. uerror[0] = '$';
  6076. uerror[1] = c;
  6077. uerror[2] = '\0';
  6078. err_unboundvar (uerror);
  6079. last_command_exit_value = EXECUTION_FAILURE;
  6080. return (interactive_shell ? &expand_wdesc_error : &expand_wdesc_fatal);
  6081. }
  6082. if (temp1)
  6083. temp = (*temp1 && (quoted & (Q_HERE_DOCUMENT|Q_DOUBLE_QUOTES)))
  6084. ? quote_string (temp1)
  6085. : quote_escapes (temp1);
  6086. else
  6087. temp = (char *)NULL;
  6088. break;
  6089. /* $$ -- pid of the invoking shell. */
  6090. case '$':
  6091. temp = itos (dollar_dollar_pid);
  6092. break;
  6093. /* $# -- number of positional parameters. */
  6094. case '#':
  6095. temp = itos (number_of_args ());
  6096. break;
  6097. /* $? -- return value of the last synchronous command. */
  6098. case '?':
  6099. temp = itos (last_command_exit_value);
  6100. break;
  6101. /* $- -- flags supplied to the shell on invocation or by `set'. */
  6102. case '-':
  6103. temp = which_set_flags ();
  6104. break;
  6105. /* $! -- Pid of the last asynchronous command. */
  6106. case '!':
  6107. /* If no asynchronous pids have been created, expand to nothing.
  6108. If `set -u' has been executed, and no async processes have
  6109. been created, this is an expansion error. */
  6110. if (last_asynchronous_pid == NO_PID)
  6111. {
  6112. if (expanded_something)
  6113. *expanded_something = 0;
  6114. temp = (char *)NULL;
  6115. if (unbound_vars_is_error)
  6116. {
  6117. uerror[0] = '$';
  6118. uerror[1] = c;
  6119. uerror[2] = '\0';
  6120. err_unboundvar (uerror);
  6121. last_command_exit_value = EXECUTION_FAILURE;
  6122. return (interactive_shell ? &expand_wdesc_error : &expand_wdesc_fatal);
  6123. }
  6124. }
  6125. else
  6126. temp = itos (last_asynchronous_pid);
  6127. break;
  6128. /* The only difference between this and $@ is when the arg is quoted. */
  6129. case '*': /* `$*' */
  6130. list = list_rest_of_args ();
  6131. #if 0
  6132. /* According to austin-group posix proposal by Geoff Clare in
  6133. <20090505091501.GA10097@squonk.masqnet> of 5 May 2009:
  6134. "The shell shall write a message to standard error and
  6135. immediately exit when it tries to expand an unset parameter
  6136. other than the '@' and '*' special parameters."
  6137. */
  6138. if (list == 0 && unbound_vars_is_error && (pflags & PF_IGNUNBOUND) == 0)
  6139. {
  6140. uerror[0] = '$';
  6141. uerror[1] = '*';
  6142. uerror[2] = '\0';
  6143. last_command_exit_value = EXECUTION_FAILURE;
  6144. err_unboundvar (uerror);
  6145. return (interactive_shell ? &expand_wdesc_error : &expand_wdesc_fatal);
  6146. }
  6147. #endif
  6148. /* If there are no command-line arguments, this should just
  6149. disappear if there are other characters in the expansion,
  6150. even if it's quoted. */
  6151. if ((quoted & (Q_HERE_DOCUMENT|Q_DOUBLE_QUOTES)) && list == 0)
  6152. temp = (char *)NULL;
  6153. else if (quoted & (Q_HERE_DOCUMENT|Q_DOUBLE_QUOTES))
  6154. {
  6155. /* If we have "$*" we want to make a string of the positional
  6156. parameters, separated by the first character of $IFS, and
  6157. quote the whole string, including the separators. If IFS
  6158. is unset, the parameters are separated by ' '; if $IFS is
  6159. null, the parameters are concatenated. */
  6160. temp = (quoted & Q_DOUBLE_QUOTES) ? string_list_dollar_star (list) : string_list (list);
  6161. temp1 = quote_string (temp);
  6162. if (*temp == 0)
  6163. tflag |= W_HASQUOTEDNULL;
  6164. free (temp);
  6165. temp = temp1;
  6166. }
  6167. else
  6168. {
  6169. /* We check whether or not we're eventually going to split $* here,
  6170. for example when IFS is empty and we are processing the rhs of
  6171. an assignment statement. In that case, we don't separate the
  6172. arguments at all. Otherwise, if the $* is not quoted it is
  6173. identical to $@ */
  6174. #if 1
  6175. # if defined (HANDLE_MULTIBYTE)
  6176. if (expand_no_split_dollar_star && ifs_firstc[0] == 0)
  6177. # else
  6178. if (expand_no_split_dollar_star && ifs_firstc == 0)
  6179. # endif
  6180. temp = string_list_dollar_star (list);
  6181. else
  6182. temp = string_list_dollar_at (list, quoted);
  6183. #else
  6184. temp = string_list_dollar_at (list, quoted);
  6185. #endif
  6186. if (expand_no_split_dollar_star == 0 && contains_dollar_at)
  6187. *contains_dollar_at = 1;
  6188. }
  6189. dispose_words (list);
  6190. break;
  6191. /* When we have "$@" what we want is "$1" "$2" "$3" ... This
  6192. means that we have to turn quoting off after we split into
  6193. the individually quoted arguments so that the final split
  6194. on the first character of $IFS is still done. */
  6195. case '@': /* `$@' */
  6196. list = list_rest_of_args ();
  6197. #if 0
  6198. /* According to austin-group posix proposal by Geoff Clare in
  6199. <20090505091501.GA10097@squonk.masqnet> of 5 May 2009:
  6200. "The shell shall write a message to standard error and
  6201. immediately exit when it tries to expand an unset parameter
  6202. other than the '@' and '*' special parameters."
  6203. */
  6204. if (list == 0 && unbound_vars_is_error && (pflags & PF_IGNUNBOUND) == 0)
  6205. {
  6206. uerror[0] = '$';
  6207. uerror[1] = '@';
  6208. uerror[2] = '\0';
  6209. last_command_exit_value = EXECUTION_FAILURE;
  6210. err_unboundvar (uerror);
  6211. return (interactive_shell ? &expand_wdesc_error : &expand_wdesc_fatal);
  6212. }
  6213. #endif
  6214. /* We want to flag the fact that we saw this. We can't turn
  6215. off quoting entirely, because other characters in the
  6216. string might need it (consider "\"$@\""), but we need some
  6217. way to signal that the final split on the first character
  6218. of $IFS should be done, even though QUOTED is 1. */
  6219. if (quoted_dollar_at_p && (quoted & (Q_HERE_DOCUMENT|Q_DOUBLE_QUOTES)))
  6220. *quoted_dollar_at_p = 1;
  6221. if (contains_dollar_at)
  6222. *contains_dollar_at = 1;
  6223. /* We want to separate the positional parameters with the first
  6224. character of $IFS in case $IFS is something other than a space.
  6225. We also want to make sure that splitting is done no matter what --
  6226. according to POSIX.2, this expands to a list of the positional
  6227. parameters no matter what IFS is set to. */
  6228. temp = string_list_dollar_at (list, quoted);
  6229. dispose_words (list);
  6230. break;
  6231. case LBRACE:
  6232. tdesc = parameter_brace_expand (string, &zindex, quoted,
  6233. quoted_dollar_at_p,
  6234. contains_dollar_at);
  6235. if (tdesc == &expand_wdesc_error || tdesc == &expand_wdesc_fatal)
  6236. return (tdesc);
  6237. temp = tdesc ? tdesc->word : (char *)0;
  6238. /* XXX */
  6239. /* Quoted nulls should be removed if there is anything else
  6240. in the string. */
  6241. /* Note that we saw the quoted null so we can add one back at
  6242. the end of this function if there are no other characters
  6243. in the string, discard TEMP, and go on. The exception to
  6244. this is when we have "${@}" and $1 is '', since $@ needs
  6245. special handling. */
  6246. if (tdesc && tdesc->word && (tdesc->flags & W_HASQUOTEDNULL) && QUOTED_NULL (temp))
  6247. {
  6248. if (had_quoted_null_p)
  6249. *had_quoted_null_p = 1;
  6250. if (*quoted_dollar_at_p == 0)
  6251. {
  6252. free (temp);
  6253. tdesc->word = temp = (char *)NULL;
  6254. }
  6255. }
  6256. ret = tdesc;
  6257. goto return0;
  6258. /* Do command or arithmetic substitution. */
  6259. case LPAREN:
  6260. /* We have to extract the contents of this paren substitution. */
  6261. t_index = zindex + 1;
  6262. temp = extract_command_subst (string, &t_index, 0);
  6263. zindex = t_index;
  6264. /* For Posix.2-style `$(( ))' arithmetic substitution,
  6265. extract the expression and pass it to the evaluator. */
  6266. if (temp && *temp == LPAREN)
  6267. {
  6268. char *temp2;
  6269. temp1 = temp + 1;
  6270. temp2 = savestring (temp1);
  6271. t_index = strlen (temp2) - 1;
  6272. if (temp2[t_index] != RPAREN)
  6273. {
  6274. free (temp2);
  6275. goto comsub;
  6276. }
  6277. /* Cut off ending `)' */
  6278. temp2[t_index] = '\0';
  6279. if (chk_arithsub (temp2, t_index) == 0)
  6280. {
  6281. free (temp2);
  6282. goto comsub;
  6283. }
  6284. /* Expand variables found inside the expression. */
  6285. temp1 = expand_arith_string (temp2, Q_DOUBLE_QUOTES);
  6286. free (temp2);
  6287. arithsub:
  6288. /* No error messages. */
  6289. this_command_name = (char *)NULL;
  6290. number = evalexp (temp1, &expok);
  6291. free (temp);
  6292. free (temp1);
  6293. if (expok == 0)
  6294. {
  6295. if (interactive_shell == 0 && posixly_correct)
  6296. {
  6297. last_command_exit_value = EXECUTION_FAILURE;
  6298. return (&expand_wdesc_fatal);
  6299. }
  6300. else
  6301. return (&expand_wdesc_error);
  6302. }
  6303. temp = itos (number);
  6304. break;
  6305. }
  6306. comsub:
  6307. if (pflags & PF_NOCOMSUB)
  6308. /* we need zindex+1 because string[zindex] == RPAREN */
  6309. temp1 = substring (string, *sindex, zindex+1);
  6310. else
  6311. {
  6312. tdesc = command_substitute (temp, quoted);
  6313. temp1 = tdesc ? tdesc->word : (char *)NULL;
  6314. if (tdesc)
  6315. dispose_word_desc (tdesc);
  6316. }
  6317. FREE (temp);
  6318. temp = temp1;
  6319. break;
  6320. /* Do POSIX.2d9-style arithmetic substitution. This will probably go
  6321. away in a future bash release. */
  6322. case '[':
  6323. /* Extract the contents of this arithmetic substitution. */
  6324. t_index = zindex + 1;
  6325. temp = extract_arithmetic_subst (string, &t_index);
  6326. zindex = t_index;
  6327. if (temp == 0)
  6328. {
  6329. temp = savestring (string);
  6330. if (expanded_something)
  6331. *expanded_something = 0;
  6332. goto return0;
  6333. }
  6334. /* Do initial variable expansion. */
  6335. temp1 = expand_arith_string (temp, Q_DOUBLE_QUOTES);
  6336. goto arithsub;
  6337. default:
  6338. /* Find the variable in VARIABLE_LIST. */
  6339. temp = (char *)NULL;
  6340. for (t_index = zindex; (c = string[zindex]) && legal_variable_char (c); zindex++)
  6341. ;
  6342. temp1 = (zindex > t_index) ? substring (string, t_index, zindex) : (char *)NULL;
  6343. /* If this isn't a variable name, then just output the `$'. */
  6344. if (temp1 == 0 || *temp1 == '\0')
  6345. {
  6346. FREE (temp1);
  6347. temp = (char *)xmalloc (2);
  6348. temp[0] = '$';
  6349. temp[1] = '\0';
  6350. if (expanded_something)
  6351. *expanded_something = 0;
  6352. goto return0;
  6353. }
  6354. /* If the variable exists, return its value cell. */
  6355. var = find_variable (temp1);
  6356. if (var && invisible_p (var) == 0 && var_isset (var))
  6357. {
  6358. #if defined (ARRAY_VARS)
  6359. if (assoc_p (var) || array_p (var))
  6360. {
  6361. temp = array_p (var) ? array_reference (array_cell (var), 0)
  6362. : assoc_reference (assoc_cell (var), "0");
  6363. if (temp)
  6364. temp = (*temp && (quoted & (Q_HERE_DOCUMENT|Q_DOUBLE_QUOTES)))
  6365. ? quote_string (temp)
  6366. : quote_escapes (temp);
  6367. else if (unbound_vars_is_error)
  6368. goto unbound_variable;
  6369. }
  6370. else
  6371. #endif
  6372. {
  6373. temp = value_cell (var);
  6374. temp = (*temp && (quoted & (Q_HERE_DOCUMENT|Q_DOUBLE_QUOTES)))
  6375. ? quote_string (temp)
  6376. : quote_escapes (temp);
  6377. }
  6378. free (temp1);
  6379. goto return0;
  6380. }
  6381. temp = (char *)NULL;
  6382. unbound_variable:
  6383. if (unbound_vars_is_error)
  6384. err_unboundvar (temp1);
  6385. else
  6386. {
  6387. free (temp1);
  6388. goto return0;
  6389. }
  6390. free (temp1);
  6391. last_command_exit_value = EXECUTION_FAILURE;
  6392. return ((unbound_vars_is_error && interactive_shell == 0)
  6393. ? &expand_wdesc_fatal
  6394. : &expand_wdesc_error);
  6395. }
  6396. if (string[zindex])
  6397. zindex++;
  6398. return0:
  6399. *sindex = zindex;
  6400. if (ret == 0)
  6401. {
  6402. ret = alloc_word_desc ();
  6403. ret->flags = tflag; /* XXX */
  6404. ret->word = temp;
  6405. }
  6406. return ret;
  6407. }
  6408. /* Make a word list which is the result of parameter and variable
  6409. expansion, command substitution, arithmetic substitution, and
  6410. quote removal of WORD. Return a pointer to a WORD_LIST which is
  6411. the result of the expansion. If WORD contains a null word, the
  6412. word list returned is also null.
  6413. QUOTED contains flag values defined in shell.h.
  6414. ISEXP is used to tell expand_word_internal that the word should be
  6415. treated as the result of an expansion. This has implications for
  6416. how IFS characters in the word are treated.
  6417. CONTAINS_DOLLAR_AT and EXPANDED_SOMETHING are return values; when non-null
  6418. they point to an integer value which receives information about expansion.
  6419. CONTAINS_DOLLAR_AT gets non-zero if WORD contained "$@", else zero.
  6420. EXPANDED_SOMETHING get non-zero if WORD contained any parameter expansions,
  6421. else zero.
  6422. This only does word splitting in the case of $@ expansion. In that
  6423. case, we split on ' '. */
  6424. /* Values for the local variable quoted_state. */
  6425. #define UNQUOTED 0
  6426. #define PARTIALLY_QUOTED 1
  6427. #define WHOLLY_QUOTED 2
  6428. static WORD_LIST *
  6429. expand_word_internal (word, quoted, isexp, contains_dollar_at, expanded_something)
  6430. WORD_DESC *word;
  6431. int quoted, isexp;
  6432. int *contains_dollar_at;
  6433. int *expanded_something;
  6434. {
  6435. WORD_LIST *list;
  6436. WORD_DESC *tword;
  6437. /* The intermediate string that we build while expanding. */
  6438. char *istring;
  6439. /* The current size of the above object. */
  6440. int istring_size;
  6441. /* Index into ISTRING. */
  6442. int istring_index;
  6443. /* Temporary string storage. */
  6444. char *temp, *temp1;
  6445. /* The text of WORD. */
  6446. register char *string;
  6447. /* The size of STRING. */
  6448. size_t string_size;
  6449. /* The index into STRING. */
  6450. int sindex;
  6451. /* This gets 1 if we see a $@ while quoted. */
  6452. int quoted_dollar_at;
  6453. /* One of UNQUOTED, PARTIALLY_QUOTED, or WHOLLY_QUOTED, depending on
  6454. whether WORD contains no quoting characters, a partially quoted
  6455. string (e.g., "xx"ab), or is fully quoted (e.g., "xxab"). */
  6456. int quoted_state;
  6457. /* State flags */
  6458. int had_quoted_null;
  6459. int has_dollar_at;
  6460. int tflag;
  6461. int assignoff; /* If assignment, offset of `=' */
  6462. register unsigned char c; /* Current character. */
  6463. int t_index; /* For calls to string_extract_xxx. */
  6464. char twochars[2];
  6465. DECLARE_MBSTATE;
  6466. istring = (char *)xmalloc (istring_size = DEFAULT_INITIAL_ARRAY_SIZE);
  6467. istring[istring_index = 0] = '\0';
  6468. quoted_dollar_at = had_quoted_null = has_dollar_at = 0;
  6469. quoted_state = UNQUOTED;
  6470. string = word->word;
  6471. if (string == 0)
  6472. goto finished_with_string;
  6473. /* Don't need the string length for the SADD... and COPY_ macros unless
  6474. multibyte characters are possible. */
  6475. string_size = (MB_CUR_MAX > 1) ? strlen (string) : 1;
  6476. if (contains_dollar_at)
  6477. *contains_dollar_at = 0;
  6478. assignoff = -1;
  6479. /* Begin the expansion. */
  6480. for (sindex = 0; ;)
  6481. {
  6482. c = string[sindex];
  6483. /* Case on toplevel character. */
  6484. switch (c)
  6485. {
  6486. case '\0':
  6487. goto finished_with_string;
  6488. case CTLESC:
  6489. sindex++;
  6490. #if HANDLE_MULTIBYTE
  6491. if (MB_CUR_MAX > 1 && string[sindex])
  6492. {
  6493. SADD_MBQCHAR_BODY(temp, string, sindex, string_size);
  6494. }
  6495. else
  6496. #endif
  6497. {
  6498. temp = (char *)xmalloc (3);
  6499. temp[0] = CTLESC;
  6500. temp[1] = c = string[sindex];
  6501. temp[2] = '\0';
  6502. }
  6503. dollar_add_string:
  6504. if (string[sindex])
  6505. sindex++;
  6506. add_string:
  6507. if (temp)
  6508. {
  6509. istring = sub_append_string (temp, istring, &istring_index, &istring_size);
  6510. temp = (char *)0;
  6511. }
  6512. break;
  6513. #if defined (PROCESS_SUBSTITUTION)
  6514. /* Process substitution. */
  6515. case '<':
  6516. case '>':
  6517. {
  6518. if (string[++sindex] != LPAREN || (quoted & (Q_HERE_DOCUMENT|Q_DOUBLE_QUOTES)) || (word->flags & (W_DQUOTE|W_NOPROCSUB)) || posixly_correct)
  6519. {
  6520. sindex--; /* add_character: label increments sindex */
  6521. goto add_character;
  6522. }
  6523. else
  6524. t_index = sindex + 1; /* skip past both '<' and LPAREN */
  6525. temp1 = extract_process_subst (string, (c == '<') ? "<(" : ">(", &t_index); /*))*/
  6526. sindex = t_index;
  6527. /* If the process substitution specification is `<()', we want to
  6528. open the pipe for writing in the child and produce output; if
  6529. it is `>()', we want to open the pipe for reading in the child
  6530. and consume input. */
  6531. temp = temp1 ? process_substitute (temp1, (c == '>')) : (char *)0;
  6532. FREE (temp1);
  6533. goto dollar_add_string;
  6534. }
  6535. #endif /* PROCESS_SUBSTITUTION */
  6536. case '=':
  6537. /* Posix.2 section 3.6.1 says that tildes following `=' in words
  6538. which are not assignment statements are not expanded. If the
  6539. shell isn't in posix mode, though, we perform tilde expansion
  6540. on `likely candidate' unquoted assignment statements (flags
  6541. include W_ASSIGNMENT but not W_QUOTED). A likely candidate
  6542. contains an unquoted :~ or =~. Something to think about: we
  6543. now have a flag that says to perform tilde expansion on arguments
  6544. to `assignment builtins' like declare and export that look like
  6545. assignment statements. We now do tilde expansion on such words
  6546. even in POSIX mode. */
  6547. if (word->flags & (W_ASSIGNRHS|W_NOTILDE))
  6548. {
  6549. if (isexp == 0 && isifs (c))
  6550. goto add_ifs_character;
  6551. else
  6552. goto add_character;
  6553. }
  6554. /* If we're not in posix mode or forcing assignment-statement tilde
  6555. expansion, note where the `=' appears in the word and prepare to
  6556. do tilde expansion following the first `='. */
  6557. if ((word->flags & W_ASSIGNMENT) &&
  6558. (posixly_correct == 0 || (word->flags & W_TILDEEXP)) &&
  6559. assignoff == -1 && sindex > 0)
  6560. assignoff = sindex;
  6561. if (sindex == assignoff && string[sindex+1] == '~') /* XXX */
  6562. word->flags |= W_ITILDE;
  6563. #if 0
  6564. else if ((word->flags & W_ASSIGNMENT) &&
  6565. (posixly_correct == 0 || (word->flags & W_TILDEEXP)) &&
  6566. string[sindex+1] == '~')
  6567. word->flags |= W_ITILDE;
  6568. #endif
  6569. if (isexp == 0 && isifs (c))
  6570. goto add_ifs_character;
  6571. else
  6572. goto add_character;
  6573. case ':':
  6574. if (word->flags & W_NOTILDE)
  6575. {
  6576. if (isexp == 0 && isifs (c))
  6577. goto add_ifs_character;
  6578. else
  6579. goto add_character;
  6580. }
  6581. if ((word->flags & (W_ASSIGNMENT|W_ASSIGNRHS|W_TILDEEXP)) &&
  6582. string[sindex+1] == '~')
  6583. word->flags |= W_ITILDE;
  6584. if (isexp == 0 && isifs (c))
  6585. goto add_ifs_character;
  6586. else
  6587. goto add_character;
  6588. case '~':
  6589. /* If the word isn't supposed to be tilde expanded, or we're not
  6590. at the start of a word or after an unquoted : or = in an
  6591. assignment statement, we don't do tilde expansion. */
  6592. if ((word->flags & (W_NOTILDE|W_DQUOTE)) ||
  6593. (sindex > 0 && ((word->flags & W_ITILDE) == 0)) ||
  6594. (quoted & (Q_DOUBLE_QUOTES|Q_HERE_DOCUMENT)))
  6595. {
  6596. word->flags &= ~W_ITILDE;
  6597. if (isexp == 0 && isifs (c) && (quoted & (Q_DOUBLE_QUOTES|Q_HERE_DOCUMENT)) == 0)
  6598. goto add_ifs_character;
  6599. else
  6600. goto add_character;
  6601. }
  6602. if (word->flags & W_ASSIGNRHS)
  6603. tflag = 2;
  6604. else if (word->flags & (W_ASSIGNMENT|W_TILDEEXP))
  6605. tflag = 1;
  6606. else
  6607. tflag = 0;
  6608. temp = bash_tilde_find_word (string + sindex, tflag, &t_index);
  6609. word->flags &= ~W_ITILDE;
  6610. if (temp && *temp && t_index > 0)
  6611. {
  6612. temp1 = bash_tilde_expand (temp, tflag);
  6613. if (temp1 && *temp1 == '~' && STREQ (temp, temp1))
  6614. {
  6615. FREE (temp);
  6616. FREE (temp1);
  6617. goto add_character; /* tilde expansion failed */
  6618. }
  6619. free (temp);
  6620. temp = temp1;
  6621. sindex += t_index;
  6622. goto add_quoted_string; /* XXX was add_string */
  6623. }
  6624. else
  6625. {
  6626. FREE (temp);
  6627. goto add_character;
  6628. }
  6629. case '$':
  6630. if (expanded_something)
  6631. *expanded_something = 1;
  6632. has_dollar_at = 0;
  6633. tword = param_expand (string, &sindex, quoted, expanded_something,
  6634. &has_dollar_at, &quoted_dollar_at,
  6635. &had_quoted_null,
  6636. (word->flags & W_NOCOMSUB) ? PF_NOCOMSUB : 0);
  6637. if (tword == &expand_wdesc_error || tword == &expand_wdesc_fatal)
  6638. {
  6639. free (string);
  6640. free (istring);
  6641. return ((tword == &expand_wdesc_error) ? &expand_word_error
  6642. : &expand_word_fatal);
  6643. }
  6644. if (contains_dollar_at && has_dollar_at)
  6645. *contains_dollar_at = 1;
  6646. if (tword && (tword->flags & W_HASQUOTEDNULL))
  6647. had_quoted_null = 1;
  6648. temp = tword->word;
  6649. dispose_word_desc (tword);
  6650. goto add_string;
  6651. break;
  6652. case '`': /* Backquoted command substitution. */
  6653. {
  6654. t_index = sindex++;
  6655. temp = string_extract (string, &sindex, "`", SX_REQMATCH);
  6656. /* The test of sindex against t_index is to allow bare instances of
  6657. ` to pass through, for backwards compatibility. */
  6658. if (temp == &extract_string_error || temp == &extract_string_fatal)
  6659. {
  6660. if (sindex - 1 == t_index)
  6661. {
  6662. sindex = t_index;
  6663. goto add_character;
  6664. }
  6665. report_error (_("bad substitution: no closing \"`\" in %s") , string+t_index);
  6666. free (string);
  6667. free (istring);
  6668. return ((temp == &extract_string_error) ? &expand_word_error
  6669. : &expand_word_fatal);
  6670. }
  6671. if (expanded_something)
  6672. *expanded_something = 1;
  6673. if (word->flags & W_NOCOMSUB)
  6674. /* sindex + 1 because string[sindex] == '`' */
  6675. temp1 = substring (string, t_index, sindex + 1);
  6676. else
  6677. {
  6678. de_backslash (temp);
  6679. tword = command_substitute (temp, quoted);
  6680. temp1 = tword ? tword->word : (char *)NULL;
  6681. if (tword)
  6682. dispose_word_desc (tword);
  6683. }
  6684. FREE (temp);
  6685. temp = temp1;
  6686. goto dollar_add_string;
  6687. }
  6688. case '\\':
  6689. if (string[sindex + 1] == '\n')
  6690. {
  6691. sindex += 2;
  6692. continue;
  6693. }
  6694. c = string[++sindex];
  6695. if (quoted & Q_HERE_DOCUMENT)
  6696. tflag = CBSHDOC;
  6697. else if (quoted & Q_DOUBLE_QUOTES)
  6698. tflag = CBSDQUOTE;
  6699. else
  6700. tflag = 0;
  6701. if ((quoted & (Q_HERE_DOCUMENT|Q_DOUBLE_QUOTES)) && ((sh_syntaxtab[c] & tflag) == 0))
  6702. {
  6703. SCOPY_CHAR_I (twochars, '\\', c, string, sindex, string_size);
  6704. }
  6705. else if (c == 0)
  6706. {
  6707. c = CTLNUL;
  6708. sindex--; /* add_character: label increments sindex */
  6709. goto add_character;
  6710. }
  6711. else
  6712. {
  6713. SCOPY_CHAR_I (twochars, CTLESC, c, string, sindex, string_size);
  6714. }
  6715. sindex++;
  6716. add_twochars:
  6717. /* BEFORE jumping here, we need to increment sindex if appropriate */
  6718. RESIZE_MALLOCED_BUFFER (istring, istring_index, 2, istring_size,
  6719. DEFAULT_ARRAY_SIZE);
  6720. istring[istring_index++] = twochars[0];
  6721. istring[istring_index++] = twochars[1];
  6722. istring[istring_index] = '\0';
  6723. break;
  6724. case '"':
  6725. #if 0
  6726. if ((quoted & (Q_DOUBLE_QUOTES|Q_HERE_DOCUMENT)) || (word->flags & W_DQUOTE))
  6727. #else
  6728. if ((quoted & (Q_DOUBLE_QUOTES|Q_HERE_DOCUMENT)))
  6729. #endif
  6730. goto add_character;
  6731. t_index = ++sindex;
  6732. temp = string_extract_double_quoted (string, &sindex, 0);
  6733. /* If the quotes surrounded the entire string, then the
  6734. whole word was quoted. */
  6735. quoted_state = (t_index == 1 && string[sindex] == '\0')
  6736. ? WHOLLY_QUOTED
  6737. : PARTIALLY_QUOTED;
  6738. if (temp && *temp)
  6739. {
  6740. tword = alloc_word_desc ();
  6741. tword->word = temp;
  6742. temp = (char *)NULL;
  6743. has_dollar_at = 0;
  6744. /* Need to get W_HASQUOTEDNULL flag through this function. */
  6745. list = expand_word_internal (tword, Q_DOUBLE_QUOTES, 0, &has_dollar_at, (int *)NULL);
  6746. if (list == &expand_word_error || list == &expand_word_fatal)
  6747. {
  6748. free (istring);
  6749. free (string);
  6750. /* expand_word_internal has already freed temp_word->word
  6751. for us because of the way it prints error messages. */
  6752. tword->word = (char *)NULL;
  6753. dispose_word (tword);
  6754. return list;
  6755. }
  6756. dispose_word (tword);
  6757. /* "$@" (a double-quoted dollar-at) expands into nothing,
  6758. not even a NULL word, when there are no positional
  6759. parameters. */
  6760. if (list == 0 && has_dollar_at)
  6761. {
  6762. quoted_dollar_at++;
  6763. break;
  6764. }
  6765. /* If we get "$@", we know we have expanded something, so we
  6766. need to remember it for the final split on $IFS. This is
  6767. a special case; it's the only case where a quoted string
  6768. can expand into more than one word. It's going to come back
  6769. from the above call to expand_word_internal as a list with
  6770. a single word, in which all characters are quoted and
  6771. separated by blanks. What we want to do is to turn it back
  6772. into a list for the next piece of code. */
  6773. if (list)
  6774. dequote_list (list);
  6775. if (list && list->word && (list->word->flags & W_HASQUOTEDNULL))
  6776. had_quoted_null = 1;
  6777. if (has_dollar_at)
  6778. {
  6779. quoted_dollar_at++;
  6780. if (contains_dollar_at)
  6781. *contains_dollar_at = 1;
  6782. if (expanded_something)
  6783. *expanded_something = 1;
  6784. }
  6785. }
  6786. else
  6787. {
  6788. /* What we have is "". This is a minor optimization. */
  6789. FREE (temp);
  6790. list = (WORD_LIST *)NULL;
  6791. }
  6792. /* The code above *might* return a list (consider the case of "$@",
  6793. where it returns "$1", "$2", etc.). We can't throw away the
  6794. rest of the list, and we have to make sure each word gets added
  6795. as quoted. We test on tresult->next: if it is non-NULL, we
  6796. quote the whole list, save it to a string with string_list, and
  6797. add that string. We don't need to quote the results of this
  6798. (and it would be wrong, since that would quote the separators
  6799. as well), so we go directly to add_string. */
  6800. if (list)
  6801. {
  6802. if (list->next)
  6803. {
  6804. /* Testing quoted_dollar_at makes sure that "$@" is
  6805. split correctly when $IFS does not contain a space. */
  6806. temp = quoted_dollar_at
  6807. ? string_list_dollar_at (list, Q_DOUBLE_QUOTES)
  6808. : string_list (quote_list (list));
  6809. dispose_words (list);
  6810. goto add_string;
  6811. }
  6812. else
  6813. {
  6814. temp = savestring (list->word->word);
  6815. tflag = list->word->flags;
  6816. dispose_words (list);
  6817. /* If the string is not a quoted null string, we want
  6818. to remove any embedded unquoted CTLNUL characters.
  6819. We do not want to turn quoted null strings back into
  6820. the empty string, though. We do this because we
  6821. want to remove any quoted nulls from expansions that
  6822. contain other characters. For example, if we have
  6823. x"$*"y or "x$*y" and there are no positional parameters,
  6824. the $* should expand into nothing. */
  6825. /* We use the W_HASQUOTEDNULL flag to differentiate the
  6826. cases: a quoted null character as above and when
  6827. CTLNUL is contained in the (non-null) expansion
  6828. of some variable. We use the had_quoted_null flag to
  6829. pass the value through this function to its caller. */
  6830. if ((tflag & W_HASQUOTEDNULL) && QUOTED_NULL (temp) == 0)
  6831. remove_quoted_nulls (temp); /* XXX */
  6832. }
  6833. }
  6834. else
  6835. temp = (char *)NULL;
  6836. /* We do not want to add quoted nulls to strings that are only
  6837. partially quoted; we can throw them away. */
  6838. if (temp == 0 && quoted_state == PARTIALLY_QUOTED)
  6839. continue;
  6840. add_quoted_string:
  6841. if (temp)
  6842. {
  6843. temp1 = temp;
  6844. temp = quote_string (temp);
  6845. free (temp1);
  6846. goto add_string;
  6847. }
  6848. else
  6849. {
  6850. /* Add NULL arg. */
  6851. c = CTLNUL;
  6852. sindex--; /* add_character: label increments sindex */
  6853. goto add_character;
  6854. }
  6855. /* break; */
  6856. case '\'':
  6857. #if 0
  6858. if ((quoted & (Q_DOUBLE_QUOTES|Q_HERE_DOCUMENT)) || (word->flags & W_DQUOTE))
  6859. #else
  6860. if ((quoted & (Q_DOUBLE_QUOTES|Q_HERE_DOCUMENT)))
  6861. #endif
  6862. goto add_character;
  6863. t_index = ++sindex;
  6864. temp = string_extract_single_quoted (string, &sindex);
  6865. /* If the entire STRING was surrounded by single quotes,
  6866. then the string is wholly quoted. */
  6867. quoted_state = (t_index == 1 && string[sindex] == '\0')
  6868. ? WHOLLY_QUOTED
  6869. : PARTIALLY_QUOTED;
  6870. /* If all we had was '', it is a null expansion. */
  6871. if (*temp == '\0')
  6872. {
  6873. free (temp);
  6874. temp = (char *)NULL;
  6875. }
  6876. else
  6877. remove_quoted_escapes (temp); /* ??? */
  6878. /* We do not want to add quoted nulls to strings that are only
  6879. partially quoted; such nulls are discarded. */
  6880. if (temp == 0 && (quoted_state == PARTIALLY_QUOTED))
  6881. continue;
  6882. /* If we have a quoted null expansion, add a quoted NULL to istring. */
  6883. if (temp == 0)
  6884. {
  6885. c = CTLNUL;
  6886. sindex--; /* add_character: label increments sindex */
  6887. goto add_character;
  6888. }
  6889. else
  6890. goto add_quoted_string;
  6891. /* break; */
  6892. default:
  6893. /* This is the fix for " $@ " */
  6894. add_ifs_character:
  6895. if ((quoted & (Q_HERE_DOCUMENT|Q_DOUBLE_QUOTES)) || (isexp == 0 && isifs (c)))
  6896. {
  6897. if (string[sindex]) /* from old goto dollar_add_string */
  6898. sindex++;
  6899. if (c == 0)
  6900. {
  6901. c = CTLNUL;
  6902. goto add_character;
  6903. }
  6904. else
  6905. {
  6906. #if HANDLE_MULTIBYTE
  6907. if (MB_CUR_MAX > 1)
  6908. sindex--;
  6909. if (MB_CUR_MAX > 1)
  6910. {
  6911. SADD_MBQCHAR_BODY(temp, string, sindex, string_size);
  6912. }
  6913. else
  6914. #endif
  6915. {
  6916. twochars[0] = CTLESC;
  6917. twochars[1] = c;
  6918. goto add_twochars;
  6919. }
  6920. }
  6921. }
  6922. SADD_MBCHAR (temp, string, sindex, string_size);
  6923. add_character:
  6924. RESIZE_MALLOCED_BUFFER (istring, istring_index, 1, istring_size,
  6925. DEFAULT_ARRAY_SIZE);
  6926. istring[istring_index++] = c;
  6927. istring[istring_index] = '\0';
  6928. /* Next character. */
  6929. sindex++;
  6930. }
  6931. }
  6932. finished_with_string:
  6933. /* OK, we're ready to return. If we have a quoted string, and
  6934. quoted_dollar_at is not set, we do no splitting at all; otherwise
  6935. we split on ' '. The routines that call this will handle what to
  6936. do if nothing has been expanded. */
  6937. /* Partially and wholly quoted strings which expand to the empty
  6938. string are retained as an empty arguments. Unquoted strings
  6939. which expand to the empty string are discarded. The single
  6940. exception is the case of expanding "$@" when there are no
  6941. positional parameters. In that case, we discard the expansion. */
  6942. /* Because of how the code that handles "" and '' in partially
  6943. quoted strings works, we need to make ISTRING into a QUOTED_NULL
  6944. if we saw quoting characters, but the expansion was empty.
  6945. "" and '' are tossed away before we get to this point when
  6946. processing partially quoted strings. This makes "" and $xxx""
  6947. equivalent when xxx is unset. We also look to see whether we
  6948. saw a quoted null from a ${} expansion and add one back if we
  6949. need to. */
  6950. /* If we expand to nothing and there were no single or double quotes
  6951. in the word, we throw it away. Otherwise, we return a NULL word.
  6952. The single exception is for $@ surrounded by double quotes when
  6953. there are no positional parameters. In that case, we also throw
  6954. the word away. */
  6955. if (*istring == '\0')
  6956. {
  6957. if (quoted_dollar_at == 0 && (had_quoted_null || quoted_state == PARTIALLY_QUOTED))
  6958. {
  6959. istring[0] = CTLNUL;
  6960. istring[1] = '\0';
  6961. tword = make_bare_word (istring);
  6962. tword->flags |= W_HASQUOTEDNULL; /* XXX */
  6963. list = make_word_list (tword, (WORD_LIST *)NULL);
  6964. if (quoted & (Q_HERE_DOCUMENT|Q_DOUBLE_QUOTES))
  6965. tword->flags |= W_QUOTED;
  6966. }
  6967. /* According to sh, ksh, and Posix.2, if a word expands into nothing
  6968. and a double-quoted "$@" appears anywhere in it, then the entire
  6969. word is removed. */
  6970. else if (quoted_state == UNQUOTED || quoted_dollar_at)
  6971. list = (WORD_LIST *)NULL;
  6972. #if 0
  6973. else
  6974. {
  6975. tword = make_bare_word (istring);
  6976. if (quoted & (Q_HERE_DOCUMENT|Q_DOUBLE_QUOTES))
  6977. tword->flags |= W_QUOTED;
  6978. list = make_word_list (tword, (WORD_LIST *)NULL);
  6979. }
  6980. #else
  6981. else
  6982. list = (WORD_LIST *)NULL;
  6983. #endif
  6984. }
  6985. else if (word->flags & W_NOSPLIT)
  6986. {
  6987. tword = make_bare_word (istring);
  6988. if (word->flags & W_ASSIGNMENT)
  6989. tword->flags |= W_ASSIGNMENT; /* XXX */
  6990. if (word->flags & W_COMPASSIGN)
  6991. tword->flags |= W_COMPASSIGN; /* XXX */
  6992. if (word->flags & W_NOGLOB)
  6993. tword->flags |= W_NOGLOB; /* XXX */
  6994. if (word->flags & W_NOEXPAND)
  6995. tword->flags |= W_NOEXPAND; /* XXX */
  6996. if (quoted & (Q_HERE_DOCUMENT|Q_DOUBLE_QUOTES))
  6997. tword->flags |= W_QUOTED;
  6998. if (had_quoted_null)
  6999. tword->flags |= W_HASQUOTEDNULL;
  7000. list = make_word_list (tword, (WORD_LIST *)NULL);
  7001. }
  7002. else
  7003. {
  7004. char *ifs_chars;
  7005. ifs_chars = (quoted_dollar_at || has_dollar_at) ? ifs_value : (char *)NULL;
  7006. /* If we have $@, we need to split the results no matter what. If
  7007. IFS is unset or NULL, string_list_dollar_at has separated the
  7008. positional parameters with a space, so we split on space (we have
  7009. set ifs_chars to " \t\n" above if ifs is unset). If IFS is set,
  7010. string_list_dollar_at has separated the positional parameters
  7011. with the first character of $IFS, so we split on $IFS. */
  7012. if (has_dollar_at && ifs_chars)
  7013. list = list_string (istring, *ifs_chars ? ifs_chars : " ", 1);
  7014. else
  7015. {
  7016. tword = make_bare_word (istring);
  7017. if ((quoted & (Q_DOUBLE_QUOTES|Q_HERE_DOCUMENT)) || (quoted_state == WHOLLY_QUOTED))
  7018. tword->flags |= W_QUOTED;
  7019. if (word->flags & W_ASSIGNMENT)
  7020. tword->flags |= W_ASSIGNMENT;
  7021. if (word->flags & W_COMPASSIGN)
  7022. tword->flags |= W_COMPASSIGN;
  7023. if (word->flags & W_NOGLOB)
  7024. tword->flags |= W_NOGLOB;
  7025. if (word->flags & W_NOEXPAND)
  7026. tword->flags |= W_NOEXPAND;
  7027. if (had_quoted_null)
  7028. tword->flags |= W_HASQUOTEDNULL; /* XXX */
  7029. list = make_word_list (tword, (WORD_LIST *)NULL);
  7030. }
  7031. }
  7032. free (istring);
  7033. return (list);
  7034. }
  7035. /* **************************************************************** */
  7036. /* */
  7037. /* Functions for Quote Removal */
  7038. /* */
  7039. /* **************************************************************** */
  7040. /* Perform quote removal on STRING. If QUOTED > 0, assume we are obeying the
  7041. backslash quoting rules for within double quotes or a here document. */
  7042. char *
  7043. string_quote_removal (string, quoted)
  7044. char *string;
  7045. int quoted;
  7046. {
  7047. size_t slen;
  7048. char *r, *result_string, *temp, *send;
  7049. int sindex, tindex, dquote;
  7050. unsigned char c;
  7051. DECLARE_MBSTATE;
  7052. /* The result can be no longer than the original string. */
  7053. slen = strlen (string);
  7054. send = string + slen;
  7055. r = result_string = (char *)xmalloc (slen + 1);
  7056. for (dquote = sindex = 0; c = string[sindex];)
  7057. {
  7058. switch (c)
  7059. {
  7060. case '\\':
  7061. c = string[++sindex];
  7062. if (c == 0)
  7063. {
  7064. *r++ = '\\';
  7065. break;
  7066. }
  7067. if (((quoted & (Q_HERE_DOCUMENT|Q_DOUBLE_QUOTES)) || dquote) && (sh_syntaxtab[c] & CBSDQUOTE) == 0)
  7068. *r++ = '\\';
  7069. /* FALLTHROUGH */
  7070. default:
  7071. SCOPY_CHAR_M (r, string, send, sindex);
  7072. break;
  7073. case '\'':
  7074. if ((quoted & (Q_HERE_DOCUMENT|Q_DOUBLE_QUOTES)) || dquote)
  7075. {
  7076. *r++ = c;
  7077. sindex++;
  7078. break;
  7079. }
  7080. tindex = sindex + 1;
  7081. temp = string_extract_single_quoted (string, &tindex);
  7082. if (temp)
  7083. {
  7084. strcpy (r, temp);
  7085. r += strlen (r);
  7086. free (temp);
  7087. }
  7088. sindex = tindex;
  7089. break;
  7090. case '"':
  7091. dquote = 1 - dquote;
  7092. sindex++;
  7093. break;
  7094. }
  7095. }
  7096. *r = '\0';
  7097. return (result_string);
  7098. }
  7099. #if 0
  7100. /* UNUSED */
  7101. /* Perform quote removal on word WORD. This allocates and returns a new
  7102. WORD_DESC *. */
  7103. WORD_DESC *
  7104. word_quote_removal (word, quoted)
  7105. WORD_DESC *word;
  7106. int quoted;
  7107. {
  7108. WORD_DESC *w;
  7109. char *t;
  7110. t = string_quote_removal (word->word, quoted);
  7111. w = alloc_word_desc ();
  7112. w->word = t ? t : savestring ("");
  7113. return (w);
  7114. }
  7115. /* Perform quote removal on all words in LIST. If QUOTED is non-zero,
  7116. the members of the list are treated as if they are surrounded by
  7117. double quotes. Return a new list, or NULL if LIST is NULL. */
  7118. WORD_LIST *
  7119. word_list_quote_removal (list, quoted)
  7120. WORD_LIST *list;
  7121. int quoted;
  7122. {
  7123. WORD_LIST *result, *t, *tresult, *e;
  7124. for (t = list, result = (WORD_LIST *)NULL; t; t = t->next)
  7125. {
  7126. tresult = make_word_list (word_quote_removal (t->word, quoted), (WORD_LIST *)NULL);
  7127. #if 0
  7128. result = (WORD_LIST *) list_append (result, tresult);
  7129. #else
  7130. if (result == 0)
  7131. result = e = tresult;
  7132. else
  7133. {
  7134. e->next = tresult;
  7135. while (e->next)
  7136. e = e->next;
  7137. }
  7138. #endif
  7139. }
  7140. return (result);
  7141. }
  7142. #endif
  7143. /*******************************************
  7144. * *
  7145. * Functions to perform word splitting *
  7146. * *
  7147. *******************************************/
  7148. void
  7149. setifs (v)
  7150. SHELL_VAR *v;
  7151. {
  7152. char *t;
  7153. unsigned char uc;
  7154. ifs_var = v;
  7155. ifs_value = (v && value_cell (v)) ? value_cell (v) : " \t\n";
  7156. /* Should really merge ifs_cmap with sh_syntaxtab. XXX - doesn't yet
  7157. handle multibyte chars in IFS */
  7158. memset (ifs_cmap, '\0', sizeof (ifs_cmap));
  7159. for (t = ifs_value ; t && *t; t++)
  7160. {
  7161. uc = *t;
  7162. ifs_cmap[uc] = 1;
  7163. }
  7164. #if defined (HANDLE_MULTIBYTE)
  7165. if (ifs_value == 0)
  7166. {
  7167. ifs_firstc[0] = '\0';
  7168. ifs_firstc_len = 1;
  7169. }
  7170. else
  7171. {
  7172. size_t ifs_len;
  7173. ifs_len = strnlen (ifs_value, MB_CUR_MAX);
  7174. ifs_firstc_len = MBLEN (ifs_value, ifs_len);
  7175. if (ifs_firstc_len == 1 || ifs_firstc_len == 0 || MB_INVALIDCH (ifs_firstc_len))
  7176. {
  7177. ifs_firstc[0] = ifs_value[0];
  7178. ifs_firstc[1] = '\0';
  7179. ifs_firstc_len = 1;
  7180. }
  7181. else
  7182. memcpy (ifs_firstc, ifs_value, ifs_firstc_len);
  7183. }
  7184. #else
  7185. ifs_firstc = ifs_value ? *ifs_value : 0;
  7186. #endif
  7187. }
  7188. char *
  7189. getifs ()
  7190. {
  7191. return ifs_value;
  7192. }
  7193. /* This splits a single word into a WORD LIST on $IFS, but only if the word
  7194. is not quoted. list_string () performs quote removal for us, even if we
  7195. don't do any splitting. */
  7196. WORD_LIST *
  7197. word_split (w, ifs_chars)
  7198. WORD_DESC *w;
  7199. char *ifs_chars;
  7200. {
  7201. WORD_LIST *result;
  7202. if (w)
  7203. {
  7204. char *xifs;
  7205. xifs = ((w->flags & W_QUOTED) || ifs_chars == 0) ? "" : ifs_chars;
  7206. result = list_string (w->word, xifs, w->flags & W_QUOTED);
  7207. }
  7208. else
  7209. result = (WORD_LIST *)NULL;
  7210. return (result);
  7211. }
  7212. /* Perform word splitting on LIST and return the RESULT. It is possible
  7213. to return (WORD_LIST *)NULL. */
  7214. static WORD_LIST *
  7215. word_list_split (list)
  7216. WORD_LIST *list;
  7217. {
  7218. WORD_LIST *result, *t, *tresult, *e;
  7219. for (t = list, result = (WORD_LIST *)NULL; t; t = t->next)
  7220. {
  7221. tresult = word_split (t->word, ifs_value);
  7222. if (result == 0)
  7223. result = e = tresult;
  7224. else
  7225. {
  7226. e->next = tresult;
  7227. while (e->next)
  7228. e = e->next;
  7229. }
  7230. }
  7231. return (result);
  7232. }
  7233. /**************************************************
  7234. * *
  7235. * Functions to expand an entire WORD_LIST *
  7236. * *
  7237. **************************************************/
  7238. /* Do any word-expansion-specific cleanup and jump to top_level */
  7239. static void
  7240. exp_jump_to_top_level (v)
  7241. int v;
  7242. {
  7243. set_pipestatus_from_exit (last_command_exit_value);
  7244. /* Cleanup code goes here. */
  7245. expand_no_split_dollar_star = 0; /* XXX */
  7246. expanding_redir = 0;
  7247. assigning_in_environment = 0;
  7248. if (parse_and_execute_level == 0)
  7249. top_level_cleanup (); /* from sig.c */
  7250. jump_to_top_level (v);
  7251. }
  7252. /* Put NLIST (which is a WORD_LIST * of only one element) at the front of
  7253. ELIST, and set ELIST to the new list. */
  7254. #define PREPEND_LIST(nlist, elist) \
  7255. do { nlist->next = elist; elist = nlist; } while (0)
  7256. /* Separate out any initial variable assignments from TLIST. If set -k has
  7257. been executed, remove all assignment statements from TLIST. Initial
  7258. variable assignments and other environment assignments are placed
  7259. on SUBST_ASSIGN_VARLIST. */
  7260. static WORD_LIST *
  7261. separate_out_assignments (tlist)
  7262. WORD_LIST *tlist;
  7263. {
  7264. register WORD_LIST *vp, *lp;
  7265. if (!tlist)
  7266. return ((WORD_LIST *)NULL);
  7267. if (subst_assign_varlist)
  7268. dispose_words (subst_assign_varlist); /* Clean up after previous error */
  7269. subst_assign_varlist = (WORD_LIST *)NULL;
  7270. vp = lp = tlist;
  7271. /* Separate out variable assignments at the start of the command.
  7272. Loop invariant: vp->next == lp
  7273. Loop postcondition:
  7274. lp = list of words left after assignment statements skipped
  7275. tlist = original list of words
  7276. */
  7277. while (lp && (lp->word->flags & W_ASSIGNMENT))
  7278. {
  7279. vp = lp;
  7280. lp = lp->next;
  7281. }
  7282. /* If lp != tlist, we have some initial assignment statements.
  7283. We make SUBST_ASSIGN_VARLIST point to the list of assignment
  7284. words and TLIST point to the remaining words. */
  7285. if (lp != tlist)
  7286. {
  7287. subst_assign_varlist = tlist;
  7288. /* ASSERT(vp->next == lp); */
  7289. vp->next = (WORD_LIST *)NULL; /* terminate variable list */
  7290. tlist = lp; /* remainder of word list */
  7291. }
  7292. /* vp == end of variable list */
  7293. /* tlist == remainder of original word list without variable assignments */
  7294. if (!tlist)
  7295. /* All the words in tlist were assignment statements */
  7296. return ((WORD_LIST *)NULL);
  7297. /* ASSERT(tlist != NULL); */
  7298. /* ASSERT((tlist->word->flags & W_ASSIGNMENT) == 0); */
  7299. /* If the -k option is in effect, we need to go through the remaining
  7300. words, separate out the assignment words, and place them on
  7301. SUBST_ASSIGN_VARLIST. */
  7302. if (place_keywords_in_env)
  7303. {
  7304. WORD_LIST *tp; /* tp == running pointer into tlist */
  7305. tp = tlist;
  7306. lp = tlist->next;
  7307. /* Loop Invariant: tp->next == lp */
  7308. /* Loop postcondition: tlist == word list without assignment statements */
  7309. while (lp)
  7310. {
  7311. if (lp->word->flags & W_ASSIGNMENT)
  7312. {
  7313. /* Found an assignment statement, add this word to end of
  7314. subst_assign_varlist (vp). */
  7315. if (!subst_assign_varlist)
  7316. subst_assign_varlist = vp = lp;
  7317. else
  7318. {
  7319. vp->next = lp;
  7320. vp = lp;
  7321. }
  7322. /* Remove the word pointed to by LP from TLIST. */
  7323. tp->next = lp->next;
  7324. /* ASSERT(vp == lp); */
  7325. lp->next = (WORD_LIST *)NULL;
  7326. lp = tp->next;
  7327. }
  7328. else
  7329. {
  7330. tp = lp;
  7331. lp = lp->next;
  7332. }
  7333. }
  7334. }
  7335. return (tlist);
  7336. }
  7337. #define WEXP_VARASSIGN 0x001
  7338. #define WEXP_BRACEEXP 0x002
  7339. #define WEXP_TILDEEXP 0x004
  7340. #define WEXP_PARAMEXP 0x008
  7341. #define WEXP_PATHEXP 0x010
  7342. /* All of the expansions, including variable assignments at the start of
  7343. the list. */
  7344. #define WEXP_ALL (WEXP_VARASSIGN|WEXP_BRACEEXP|WEXP_TILDEEXP|WEXP_PARAMEXP|WEXP_PATHEXP)
  7345. /* All of the expansions except variable assignments at the start of
  7346. the list. */
  7347. #define WEXP_NOVARS (WEXP_BRACEEXP|WEXP_TILDEEXP|WEXP_PARAMEXP|WEXP_PATHEXP)
  7348. /* All of the `shell expansions': brace expansion, tilde expansion, parameter
  7349. expansion, command substitution, arithmetic expansion, word splitting, and
  7350. quote removal. */
  7351. #define WEXP_SHELLEXP (WEXP_BRACEEXP|WEXP_TILDEEXP|WEXP_PARAMEXP)
  7352. /* Take the list of words in LIST and do the various substitutions. Return
  7353. a new list of words which is the expanded list, and without things like
  7354. variable assignments. */
  7355. WORD_LIST *
  7356. expand_words (list)
  7357. WORD_LIST *list;
  7358. {
  7359. return (expand_word_list_internal (list, WEXP_ALL));
  7360. }
  7361. /* Same as expand_words (), but doesn't hack variable or environment
  7362. variables. */
  7363. WORD_LIST *
  7364. expand_words_no_vars (list)
  7365. WORD_LIST *list;
  7366. {
  7367. return (expand_word_list_internal (list, WEXP_NOVARS));
  7368. }
  7369. WORD_LIST *
  7370. expand_words_shellexp (list)
  7371. WORD_LIST *list;
  7372. {
  7373. return (expand_word_list_internal (list, WEXP_SHELLEXP));
  7374. }
  7375. static WORD_LIST *
  7376. glob_expand_word_list (tlist, eflags)
  7377. WORD_LIST *tlist;
  7378. int eflags;
  7379. {
  7380. char **glob_array, *temp_string;
  7381. register int glob_index;
  7382. WORD_LIST *glob_list, *output_list, *disposables, *next;
  7383. WORD_DESC *tword;
  7384. output_list = disposables = (WORD_LIST *)NULL;
  7385. glob_array = (char **)NULL;
  7386. while (tlist)
  7387. {
  7388. /* For each word, either globbing is attempted or the word is
  7389. added to orig_list. If globbing succeeds, the results are
  7390. added to orig_list and the word (tlist) is added to the list
  7391. of disposable words. If globbing fails and failed glob
  7392. expansions are left unchanged (the shell default), the
  7393. original word is added to orig_list. If globbing fails and
  7394. failed glob expansions are removed, the original word is
  7395. added to the list of disposable words. orig_list ends up
  7396. in reverse order and requires a call to REVERSE_LIST to
  7397. be set right. After all words are examined, the disposable
  7398. words are freed. */
  7399. next = tlist->next;
  7400. /* If the word isn't an assignment and contains an unquoted
  7401. pattern matching character, then glob it. */
  7402. if ((tlist->word->flags & W_NOGLOB) == 0 &&
  7403. unquoted_glob_pattern_p (tlist->word->word))
  7404. {
  7405. glob_array = shell_glob_filename (tlist->word->word);
  7406. /* Handle error cases.
  7407. I don't think we should report errors like "No such file
  7408. or directory". However, I would like to report errors
  7409. like "Read failed". */
  7410. if (glob_array == 0 || GLOB_FAILED (glob_array))
  7411. {
  7412. glob_array = (char **)xmalloc (sizeof (char *));
  7413. glob_array[0] = (char *)NULL;
  7414. }
  7415. /* Dequote the current word in case we have to use it. */
  7416. if (glob_array[0] == NULL)
  7417. {
  7418. temp_string = dequote_string (tlist->word->word);
  7419. free (tlist->word->word);
  7420. tlist->word->word = temp_string;
  7421. }
  7422. /* Make the array into a word list. */
  7423. glob_list = (WORD_LIST *)NULL;
  7424. for (glob_index = 0; glob_array[glob_index]; glob_index++)
  7425. {
  7426. tword = make_bare_word (glob_array[glob_index]);
  7427. tword->flags |= W_GLOBEXP; /* XXX */
  7428. glob_list = make_word_list (tword, glob_list);
  7429. }
  7430. if (glob_list)
  7431. {
  7432. output_list = (WORD_LIST *)list_append (glob_list, output_list);
  7433. PREPEND_LIST (tlist, disposables);
  7434. }
  7435. else if (fail_glob_expansion != 0)
  7436. {
  7437. report_error (_("no match: %s"), tlist->word->word);
  7438. exp_jump_to_top_level (DISCARD);
  7439. }
  7440. else if (allow_null_glob_expansion == 0)
  7441. {
  7442. /* Failed glob expressions are left unchanged. */
  7443. PREPEND_LIST (tlist, output_list);
  7444. }
  7445. else
  7446. {
  7447. /* Failed glob expressions are removed. */
  7448. PREPEND_LIST (tlist, disposables);
  7449. }
  7450. }
  7451. else
  7452. {
  7453. /* Dequote the string. */
  7454. temp_string = dequote_string (tlist->word->word);
  7455. free (tlist->word->word);
  7456. tlist->word->word = temp_string;
  7457. PREPEND_LIST (tlist, output_list);
  7458. }
  7459. strvec_dispose (glob_array);
  7460. glob_array = (char **)NULL;
  7461. tlist = next;
  7462. }
  7463. if (disposables)
  7464. dispose_words (disposables);
  7465. if (output_list)
  7466. output_list = REVERSE_LIST (output_list, WORD_LIST *);
  7467. return (output_list);
  7468. }
  7469. #if defined (BRACE_EXPANSION)
  7470. static WORD_LIST *
  7471. brace_expand_word_list (tlist, eflags)
  7472. WORD_LIST *tlist;
  7473. int eflags;
  7474. {
  7475. register char **expansions;
  7476. char *temp_string;
  7477. WORD_LIST *disposables, *output_list, *next;
  7478. WORD_DESC *w;
  7479. int eindex;
  7480. for (disposables = output_list = (WORD_LIST *)NULL; tlist; tlist = next)
  7481. {
  7482. next = tlist->next;
  7483. /* Only do brace expansion if the word has a brace character. If
  7484. not, just add the word list element to BRACES and continue. In
  7485. the common case, at least when running shell scripts, this will
  7486. degenerate to a bunch of calls to `xstrchr', and then what is
  7487. basically a reversal of TLIST into BRACES, which is corrected
  7488. by a call to REVERSE_LIST () on BRACES when the end of TLIST
  7489. is reached. */
  7490. if (xstrchr (tlist->word->word, LBRACE))
  7491. {
  7492. expansions = brace_expand (tlist->word->word);
  7493. for (eindex = 0; temp_string = expansions[eindex]; eindex++)
  7494. {
  7495. w = make_word (temp_string);
  7496. /* If brace expansion didn't change the word, preserve
  7497. the flags. We may want to preserve the flags
  7498. unconditionally someday -- XXX */
  7499. if (STREQ (temp_string, tlist->word->word))
  7500. w->flags = tlist->word->flags;
  7501. output_list = make_word_list (w, output_list);
  7502. free (expansions[eindex]);
  7503. }
  7504. free (expansions);
  7505. /* Add TLIST to the list of words to be freed after brace
  7506. expansion has been performed. */
  7507. PREPEND_LIST (tlist, disposables);
  7508. }
  7509. else
  7510. PREPEND_LIST (tlist, output_list);
  7511. }
  7512. if (disposables)
  7513. dispose_words (disposables);
  7514. if (output_list)
  7515. output_list = REVERSE_LIST (output_list, WORD_LIST *);
  7516. return (output_list);
  7517. }
  7518. #endif
  7519. #if defined (ARRAY_VARS)
  7520. /* Take WORD, a compound associative array assignment, and internally run
  7521. 'declare -A w', where W is the variable name portion of WORD. */
  7522. static int
  7523. make_internal_declare (word, option)
  7524. char *word;
  7525. char *option;
  7526. {
  7527. int t;
  7528. WORD_LIST *wl;
  7529. WORD_DESC *w;
  7530. w = make_word (word);
  7531. t = assignment (w->word, 0);
  7532. w->word[t] = '\0';
  7533. wl = make_word_list (w, (WORD_LIST *)NULL);
  7534. wl = make_word_list (make_word (option), wl);
  7535. return (declare_builtin (wl));
  7536. }
  7537. #endif
  7538. static WORD_LIST *
  7539. shell_expand_word_list (tlist, eflags)
  7540. WORD_LIST *tlist;
  7541. int eflags;
  7542. {
  7543. WORD_LIST *expanded, *orig_list, *new_list, *next, *temp_list;
  7544. int expanded_something, has_dollar_at;
  7545. char *temp_string;
  7546. /* We do tilde expansion all the time. This is what 1003.2 says. */
  7547. new_list = (WORD_LIST *)NULL;
  7548. for (orig_list = tlist; tlist; tlist = next)
  7549. {
  7550. temp_string = tlist->word->word;
  7551. next = tlist->next;
  7552. #if defined (ARRAY_VARS)
  7553. /* If this is a compound array assignment to a builtin that accepts
  7554. such assignments (e.g., `declare'), take the assignment and perform
  7555. it separately, handling the semantics of declarations inside shell
  7556. functions. This avoids the double-evaluation of such arguments,
  7557. because `declare' does some evaluation of compound assignments on
  7558. its own. */
  7559. if ((tlist->word->flags & (W_COMPASSIGN|W_ASSIGNARG)) == (W_COMPASSIGN|W_ASSIGNARG))
  7560. {
  7561. int t;
  7562. if (tlist->word->flags & W_ASSIGNASSOC)
  7563. make_internal_declare (tlist->word->word, "-A");
  7564. t = do_word_assignment (tlist->word);
  7565. if (t == 0)
  7566. {
  7567. last_command_exit_value = EXECUTION_FAILURE;
  7568. exp_jump_to_top_level (DISCARD);
  7569. }
  7570. /* Now transform the word as ksh93 appears to do and go on */
  7571. t = assignment (tlist->word->word, 0);
  7572. tlist->word->word[t] = '\0';
  7573. tlist->word->flags &= ~(W_ASSIGNMENT|W_NOSPLIT|W_COMPASSIGN|W_ASSIGNARG|W_ASSIGNASSOC);
  7574. }
  7575. #endif
  7576. expanded_something = 0;
  7577. expanded = expand_word_internal
  7578. (tlist->word, 0, 0, &has_dollar_at, &expanded_something);
  7579. if (expanded == &expand_word_error || expanded == &expand_word_fatal)
  7580. {
  7581. /* By convention, each time this error is returned,
  7582. tlist->word->word has already been freed. */
  7583. tlist->word->word = (char *)NULL;
  7584. /* Dispose our copy of the original list. */
  7585. dispose_words (orig_list);
  7586. /* Dispose the new list we're building. */
  7587. dispose_words (new_list);
  7588. last_command_exit_value = EXECUTION_FAILURE;
  7589. if (expanded == &expand_word_error)
  7590. exp_jump_to_top_level (DISCARD);
  7591. else
  7592. exp_jump_to_top_level (FORCE_EOF);
  7593. }
  7594. /* Don't split words marked W_NOSPLIT. */
  7595. if (expanded_something && (tlist->word->flags & W_NOSPLIT) == 0)
  7596. {
  7597. temp_list = word_list_split (expanded);
  7598. dispose_words (expanded);
  7599. }
  7600. else
  7601. {
  7602. /* If no parameter expansion, command substitution, process
  7603. substitution, or arithmetic substitution took place, then
  7604. do not do word splitting. We still have to remove quoted
  7605. null characters from the result. */
  7606. word_list_remove_quoted_nulls (expanded);
  7607. temp_list = expanded;
  7608. }
  7609. expanded = REVERSE_LIST (temp_list, WORD_LIST *);
  7610. new_list = (WORD_LIST *)list_append (expanded, new_list);
  7611. }
  7612. if (orig_list)
  7613. dispose_words (orig_list);
  7614. if (new_list)
  7615. new_list = REVERSE_LIST (new_list, WORD_LIST *);
  7616. return (new_list);
  7617. }
  7618. /* The workhorse for expand_words () and expand_words_no_vars ().
  7619. First arg is LIST, a WORD_LIST of words.
  7620. Second arg EFLAGS is a flags word controlling which expansions are
  7621. performed.
  7622. This does all of the substitutions: brace expansion, tilde expansion,
  7623. parameter expansion, command substitution, arithmetic expansion,
  7624. process substitution, word splitting, and pathname expansion, according
  7625. to the bits set in EFLAGS. Words with the W_QUOTED or W_NOSPLIT bits
  7626. set, or for which no expansion is done, do not undergo word splitting.
  7627. Words with the W_NOGLOB bit set do not undergo pathname expansion. */
  7628. static WORD_LIST *
  7629. expand_word_list_internal (list, eflags)
  7630. WORD_LIST *list;
  7631. int eflags;
  7632. {
  7633. WORD_LIST *new_list, *temp_list;
  7634. int tint;
  7635. if (list == 0)
  7636. return ((WORD_LIST *)NULL);
  7637. garglist = new_list = copy_word_list (list);
  7638. if (eflags & WEXP_VARASSIGN)
  7639. {
  7640. garglist = new_list = separate_out_assignments (new_list);
  7641. if (new_list == 0)
  7642. {
  7643. if (subst_assign_varlist)
  7644. {
  7645. /* All the words were variable assignments, so they are placed
  7646. into the shell's environment. */
  7647. for (temp_list = subst_assign_varlist; temp_list; temp_list = temp_list->next)
  7648. {
  7649. this_command_name = (char *)NULL; /* no arithmetic errors */
  7650. tint = do_word_assignment (temp_list->word);
  7651. /* Variable assignment errors in non-interactive shells
  7652. running in Posix.2 mode cause the shell to exit. */
  7653. if (tint == 0)
  7654. {
  7655. last_command_exit_value = EXECUTION_FAILURE;
  7656. if (interactive_shell == 0 && posixly_correct)
  7657. exp_jump_to_top_level (FORCE_EOF);
  7658. else
  7659. exp_jump_to_top_level (DISCARD);
  7660. }
  7661. }
  7662. dispose_words (subst_assign_varlist);
  7663. subst_assign_varlist = (WORD_LIST *)NULL;
  7664. }
  7665. return ((WORD_LIST *)NULL);
  7666. }
  7667. }
  7668. /* Begin expanding the words that remain. The expansions take place on
  7669. things that aren't really variable assignments. */
  7670. #if defined (BRACE_EXPANSION)
  7671. /* Do brace expansion on this word if there are any brace characters
  7672. in the string. */
  7673. if ((eflags & WEXP_BRACEEXP) && brace_expansion && new_list)
  7674. new_list = brace_expand_word_list (new_list, eflags);
  7675. #endif /* BRACE_EXPANSION */
  7676. /* Perform the `normal' shell expansions: tilde expansion, parameter and
  7677. variable substitution, command substitution, arithmetic expansion,
  7678. and word splitting. */
  7679. new_list = shell_expand_word_list (new_list, eflags);
  7680. /* Okay, we're almost done. Now let's just do some filename
  7681. globbing. */
  7682. if (new_list)
  7683. {
  7684. if ((eflags & WEXP_PATHEXP) && disallow_filename_globbing == 0)
  7685. /* Glob expand the word list unless globbing has been disabled. */
  7686. new_list = glob_expand_word_list (new_list, eflags);
  7687. else
  7688. /* Dequote the words, because we're not performing globbing. */
  7689. new_list = dequote_list (new_list);
  7690. }
  7691. if ((eflags & WEXP_VARASSIGN) && subst_assign_varlist)
  7692. {
  7693. sh_wassign_func_t *assign_func;
  7694. /* If the remainder of the words expand to nothing, Posix.2 requires
  7695. that the variable and environment assignments affect the shell's
  7696. environment. */
  7697. assign_func = new_list ? assign_in_env : do_word_assignment;
  7698. tempenv_assign_error = 0;
  7699. for (temp_list = subst_assign_varlist; temp_list; temp_list = temp_list->next)
  7700. {
  7701. this_command_name = (char *)NULL;
  7702. assigning_in_environment = (assign_func == assign_in_env);
  7703. tint = (*assign_func) (temp_list->word);
  7704. assigning_in_environment = 0;
  7705. /* Variable assignment errors in non-interactive shells running
  7706. in Posix.2 mode cause the shell to exit. */
  7707. if (tint == 0)
  7708. {
  7709. if (assign_func == do_word_assignment)
  7710. {
  7711. last_command_exit_value = EXECUTION_FAILURE;
  7712. if (interactive_shell == 0 && posixly_correct)
  7713. exp_jump_to_top_level (FORCE_EOF);
  7714. else
  7715. exp_jump_to_top_level (DISCARD);
  7716. }
  7717. else
  7718. tempenv_assign_error++;
  7719. }
  7720. }
  7721. dispose_words (subst_assign_varlist);
  7722. subst_assign_varlist = (WORD_LIST *)NULL;
  7723. }
  7724. #if 0
  7725. tint = list_length (new_list) + 1;
  7726. RESIZE_MALLOCED_BUFFER (glob_argv_flags, 0, tint, glob_argv_flags_size, 16);
  7727. for (tint = 0, temp_list = new_list; temp_list; temp_list = temp_list->next)
  7728. glob_argv_flags[tint++] = (temp_list->word->flags & W_GLOBEXP) ? '1' : '0';
  7729. glob_argv_flags[tint] = '\0';
  7730. #endif
  7731. return (new_list);
  7732. }