]> git.ipfire.org Git - thirdparty/bash.git/blob - subst.c
bash-5.0 distribution sources and documentation
[thirdparty/bash.git] / subst.c
1 /* subst.c -- The part of the shell that does parameter, command, arithmetic,
2 and globbing substitutions. */
3
4 /* ``Have a little faith, there's magic in the night. You ain't a
5 beauty, but, hey, you're alright.'' */
6
7 /* Copyright (C) 1987-2018 Free Software Foundation, Inc.
8
9 This file is part of GNU Bash, the Bourne Again SHell.
10
11 Bash is free software: you can redistribute it and/or modify
12 it under the terms of the GNU General Public License as published by
13 the Free Software Foundation, either version 3 of the License, or
14 (at your option) any later version.
15
16 Bash is distributed in the hope that it will be useful,
17 but WITHOUT ANY WARRANTY; without even the implied warranty of
18 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 GNU General Public License for more details.
20
21 You should have received a copy of the GNU General Public License
22 along with Bash. If not, see <http://www.gnu.org/licenses/>.
23 */
24
25 #include "config.h"
26
27 #include "bashtypes.h"
28 #include <stdio.h>
29 #include "chartypes.h"
30 #if defined (HAVE_PWD_H)
31 # include <pwd.h>
32 #endif
33 #include <signal.h>
34 #include <errno.h>
35
36 #if defined (HAVE_UNISTD_H)
37 # include <unistd.h>
38 #endif
39
40 #define NEED_FPURGE_DECL
41
42 #include "bashansi.h"
43 #include "posixstat.h"
44 #include "bashintl.h"
45
46 #include "shell.h"
47 #include "parser.h"
48 #include "flags.h"
49 #include "jobs.h"
50 #include "execute_cmd.h"
51 #include "filecntl.h"
52 #include "trap.h"
53 #include "pathexp.h"
54 #include "mailcheck.h"
55
56 #include "shmbutil.h"
57 #if defined (HAVE_MBSTR_H) && defined (HAVE_MBSCHR)
58 # include <mbstr.h> /* mbschr */
59 #endif
60 #include "typemax.h"
61
62 #include "builtins/getopt.h"
63 #include "builtins/common.h"
64
65 #include "builtins/builtext.h"
66
67 #include <tilde/tilde.h>
68 #include <glob/strmatch.h>
69
70 #if !defined (errno)
71 extern int errno;
72 #endif /* !errno */
73
74 /* The size that strings change by. */
75 #define DEFAULT_INITIAL_ARRAY_SIZE 112
76 #define DEFAULT_ARRAY_SIZE 128
77
78 /* Variable types. */
79 #define VT_VARIABLE 0
80 #define VT_POSPARMS 1
81 #define VT_ARRAYVAR 2
82 #define VT_ARRAYMEMBER 3
83 #define VT_ASSOCVAR 4
84
85 #define VT_STARSUB 128 /* $* or ${array[*]} -- used to split */
86
87 /* Flags for quoted_strchr */
88 #define ST_BACKSL 0x01
89 #define ST_CTLESC 0x02
90 #define ST_SQUOTE 0x04 /* unused yet */
91 #define ST_DQUOTE 0x08 /* unused yet */
92
93 /* These defs make it easier to use the editor. */
94 #define LBRACE '{'
95 #define RBRACE '}'
96 #define LPAREN '('
97 #define RPAREN ')'
98 #define LBRACK '['
99 #define RBRACK ']'
100
101 #if defined (HANDLE_MULTIBYTE)
102 #define WLPAREN L'('
103 #define WRPAREN L')'
104 #endif
105
106 #define DOLLAR_AT_STAR(c) ((c) == '@' || (c) == '*')
107 #define STR_DOLLAR_AT_STAR(s) (DOLLAR_AT_STAR ((s)[0]) && (s)[1] == '\0')
108
109 /* Evaluates to 1 if C is one of the shell's special parameters whose length
110 can be taken, but is also one of the special expansion characters. */
111 #define VALID_SPECIAL_LENGTH_PARAM(c) \
112 ((c) == '-' || (c) == '?' || (c) == '#' || (c) == '@')
113
114 /* Evaluates to 1 if C is one of the shell's special parameters for which an
115 indirect variable reference may be made. */
116 #define VALID_INDIR_PARAM(c) \
117 ((posixly_correct == 0 && (c) == '#') || (posixly_correct == 0 && (c) == '?') || (c) == '@' || (c) == '*')
118
119 /* Evaluates to 1 if C is one of the OP characters that follows the parameter
120 in ${parameter[:]OPword}. */
121 #define VALID_PARAM_EXPAND_CHAR(c) (sh_syntaxtab[(unsigned char)c] & CSUBSTOP)
122
123 /* Evaluates to 1 if this is one of the shell's special variables. */
124 #define SPECIAL_VAR(name, wi) \
125 (*name && ((DIGIT (*name) && all_digits (name)) || \
126 (name[1] == '\0' && (sh_syntaxtab[(unsigned char)*name] & CSPECVAR)) || \
127 (wi && name[2] == '\0' && VALID_INDIR_PARAM (name[1]))))
128
129 /* This can be used by all of the *_extract_* functions that have a similar
130 structure. It can't just be wrapped in a do...while(0) loop because of
131 the embedded `break'. The dangling else accommodates a trailing semicolon;
132 we could also put in a do ; while (0) */
133
134 #define CHECK_STRING_OVERRUN(oind, ind, len, ch) \
135 if (ind >= len) \
136 { \
137 oind = len; \
138 ch = 0; \
139 break; \
140 } \
141 else \
142
143 /* An expansion function that takes a string and a quoted flag and returns
144 a WORD_LIST *. Used as the type of the third argument to
145 expand_string_if_necessary(). */
146 typedef WORD_LIST *EXPFUNC __P((char *, int));
147
148 /* Process ID of the last command executed within command substitution. */
149 pid_t last_command_subst_pid = NO_PID;
150 pid_t current_command_subst_pid = NO_PID;
151
152 /* Variables used to keep track of the characters in IFS. */
153 SHELL_VAR *ifs_var;
154 char *ifs_value;
155 unsigned char ifs_cmap[UCHAR_MAX + 1];
156 int ifs_is_set, ifs_is_null;
157
158 #if defined (HANDLE_MULTIBYTE)
159 unsigned char ifs_firstc[MB_LEN_MAX];
160 size_t ifs_firstc_len;
161 #else
162 unsigned char ifs_firstc;
163 #endif
164
165 /* If non-zero, command substitution inherits the value of errexit option */
166 int inherit_errexit = 0;
167
168 /* Sentinel to tell when we are performing variable assignments preceding a
169 command name and putting them into the environment. Used to make sure
170 we use the temporary environment when looking up variable values. */
171 int assigning_in_environment;
172
173 /* Used to hold a list of variable assignments preceding a command. Global
174 so the SIGCHLD handler in jobs.c can unwind-protect it when it runs a
175 SIGCHLD trap and so it can be saved and restored by the trap handlers. */
176 WORD_LIST *subst_assign_varlist = (WORD_LIST *)NULL;
177
178 /* Tell the expansion functions to not longjmp back to top_level on fatal
179 errors. Enabled when doing completion and prompt string expansion. */
180 int no_longjmp_on_fatal_error = 0;
181
182 /* Non-zero means to allow unmatched globbed filenames to expand to
183 a null file. */
184 int allow_null_glob_expansion;
185
186 /* Non-zero means to throw an error when globbing fails to match anything. */
187 int fail_glob_expansion;
188
189 /* Extern functions and variables from different files. */
190 extern struct fd_bitmap *current_fds_to_close;
191 extern int wordexp_only;
192
193 #if defined (JOB_CONTROL) && defined (PROCESS_SUBSTITUTION)
194 extern PROCESS *last_procsub_child;
195 #endif
196
197 #if !defined (HAVE_WCSDUP) && defined (HANDLE_MULTIBYTE)
198 extern wchar_t *wcsdup __P((const wchar_t *));
199 #endif
200
201 #if 0
202 /* Variables to keep track of which words in an expanded word list (the
203 output of expand_word_list_internal) are the result of globbing
204 expansions. GLOB_ARGV_FLAGS is used by execute_cmd.c.
205 (CURRENTLY UNUSED). */
206 char *glob_argv_flags;
207 static int glob_argv_flags_size;
208 #endif
209
210 static WORD_LIST *cached_quoted_dollar_at = 0;
211
212 /* Distinguished error values to return from expansion functions */
213 static WORD_LIST expand_word_error, expand_word_fatal;
214 static WORD_DESC expand_wdesc_error, expand_wdesc_fatal;
215 static char expand_param_error, expand_param_fatal, expand_param_unset;
216 static char extract_string_error, extract_string_fatal;
217
218 /* Set by expand_word_unsplit and several of the expand_string_XXX functions;
219 used to inhibit splitting and re-joining $* on $IFS, primarily when doing
220 assignment statements. The idea is that if we're in a context where this
221 is set, we're not going to be performing word splitting, so we use the same
222 rules to expand $* as we would if it appeared within double quotes. */
223 static int expand_no_split_dollar_star = 0;
224
225 /* A WORD_LIST of words to be expanded by expand_word_list_internal,
226 without any leading variable assignments. */
227 static WORD_LIST *garglist = (WORD_LIST *)NULL;
228
229 static char *quoted_substring __P((char *, int, int));
230 static int quoted_strlen __P((char *));
231 static char *quoted_strchr __P((char *, int, int));
232
233 static char *expand_string_if_necessary __P((char *, int, EXPFUNC *));
234 static inline char *expand_string_to_string_internal __P((char *, int, EXPFUNC *));
235 static WORD_LIST *call_expand_word_internal __P((WORD_DESC *, int, int, int *, int *));
236 static WORD_LIST *expand_string_internal __P((char *, int));
237 static WORD_LIST *expand_string_leave_quoted __P((char *, int));
238 static WORD_LIST *expand_string_for_rhs __P((char *, int, int, int, int *, int *));
239 static WORD_LIST *expand_string_for_pat __P((char *, int, int *, int *));
240
241 static char *quote_escapes_internal __P((const char *, int));
242
243 static WORD_LIST *list_quote_escapes __P((WORD_LIST *));
244 static WORD_LIST *list_dequote_escapes __P((WORD_LIST *));
245
246 static char *make_quoted_char __P((int));
247 static WORD_LIST *quote_list __P((WORD_LIST *));
248
249 static int unquoted_substring __P((char *, char *));
250 static int unquoted_member __P((int, char *));
251
252 #if defined (ARRAY_VARS)
253 static SHELL_VAR *do_compound_assignment __P((char *, char *, int));
254 #endif
255 static int do_assignment_internal __P((const WORD_DESC *, int));
256
257 static char *string_extract_verbatim __P((char *, size_t, int *, char *, int));
258 static char *string_extract __P((char *, int *, char *, int));
259 static char *string_extract_double_quoted __P((char *, int *, int));
260 static inline char *string_extract_single_quoted __P((char *, int *));
261 static inline int skip_single_quoted __P((const char *, size_t, int, int));
262 static int skip_double_quoted __P((char *, size_t, int, int));
263 static char *extract_delimited_string __P((char *, int *, char *, char *, char *, int));
264 static char *extract_dollar_brace_string __P((char *, int *, int, int));
265 static int skip_matched_pair __P((const char *, int, int, int, int));
266
267 static char *pos_params __P((char *, int, int, int));
268
269 static unsigned char *mb_getcharlens __P((char *, int));
270
271 static char *remove_upattern __P((char *, char *, int));
272 #if defined (HANDLE_MULTIBYTE)
273 static wchar_t *remove_wpattern __P((wchar_t *, size_t, wchar_t *, int));
274 #endif
275 static char *remove_pattern __P((char *, char *, int));
276
277 static int match_upattern __P((char *, char *, int, char **, char **));
278 #if defined (HANDLE_MULTIBYTE)
279 static int match_wpattern __P((wchar_t *, char **, size_t, wchar_t *, int, char **, char **));
280 #endif
281 static int match_pattern __P((char *, char *, int, char **, char **));
282 static int getpatspec __P((int, char *));
283 static char *getpattern __P((char *, int, int));
284 static char *variable_remove_pattern __P((char *, char *, int, int));
285 static char *list_remove_pattern __P((WORD_LIST *, char *, int, int, int));
286 static char *parameter_list_remove_pattern __P((int, char *, int, int));
287 #ifdef ARRAY_VARS
288 static char *array_remove_pattern __P((SHELL_VAR *, char *, int, char *, int));
289 #endif
290 static char *parameter_brace_remove_pattern __P((char *, char *, int, char *, int, int, int));
291
292 static char *string_var_assignment __P((SHELL_VAR *, char *));
293 #if defined (ARRAY_VARS)
294 static char *array_var_assignment __P((SHELL_VAR *, int, int));
295 #endif
296 static char *pos_params_assignment __P((WORD_LIST *, int, int));
297 static char *string_transform __P((int, SHELL_VAR *, char *));
298 static char *list_transform __P((int, SHELL_VAR *, WORD_LIST *, int, int));
299 static char *parameter_list_transform __P((int, int, int));
300 #if defined ARRAY_VARS
301 static char *array_transform __P((int, SHELL_VAR *, char *, int));
302 #endif
303 static char *parameter_brace_transform __P((char *, char *, int, char *, int, int, int, int));
304
305 static char *process_substitute __P((char *, int));
306
307 static char *read_comsub __P((int, int, int, int *));
308
309 #ifdef ARRAY_VARS
310 static arrayind_t array_length_reference __P((char *));
311 #endif
312
313 static int valid_brace_expansion_word __P((char *, int));
314 static int chk_atstar __P((char *, int, int *, int *));
315 static int chk_arithsub __P((const char *, int));
316
317 static WORD_DESC *parameter_brace_expand_word __P((char *, int, int, int, arrayind_t *));
318 static char *parameter_brace_find_indir __P((char *, int, int, int));
319 static WORD_DESC *parameter_brace_expand_indir __P((char *, int, int, int *, int *));
320 static WORD_DESC *parameter_brace_expand_rhs __P((char *, char *, int, int, int, int *, int *));
321 static void parameter_brace_expand_error __P((char *, char *, int));
322
323 static int valid_length_expression __P((char *));
324 static intmax_t parameter_brace_expand_length __P((char *));
325
326 static char *skiparith __P((char *, int));
327 static int verify_substring_values __P((SHELL_VAR *, char *, char *, int, intmax_t *, intmax_t *));
328 static int get_var_and_type __P((char *, char *, arrayind_t, int, int, SHELL_VAR **, char **));
329 static char *mb_substring __P((char *, int, int));
330 static char *parameter_brace_substring __P((char *, char *, int, char *, int, int, int));
331
332 static int shouldexp_replacement __P((char *));
333
334 static char *pos_params_pat_subst __P((char *, char *, char *, int));
335
336 static char *parameter_brace_patsub __P((char *, char *, int, char *, int, int, int));
337
338 static char *pos_params_casemod __P((char *, char *, int, int));
339 static char *parameter_brace_casemod __P((char *, char *, int, int, char *, int, int, int));
340
341 static WORD_DESC *parameter_brace_expand __P((char *, int *, int, int, int *, int *));
342 static WORD_DESC *param_expand __P((char *, int *, int, int *, int *, int *, int *, int));
343
344 static WORD_LIST *expand_word_internal __P((WORD_DESC *, int, int, int *, int *));
345
346 static WORD_LIST *word_list_split __P((WORD_LIST *));
347
348 static void exp_jump_to_top_level __P((int));
349
350 static WORD_LIST *separate_out_assignments __P((WORD_LIST *));
351 static WORD_LIST *glob_expand_word_list __P((WORD_LIST *, int));
352 #ifdef BRACE_EXPANSION
353 static WORD_LIST *brace_expand_word_list __P((WORD_LIST *, int));
354 #endif
355 #if defined (ARRAY_VARS)
356 static int make_internal_declare __P((char *, char *, char *));
357 #endif
358 static WORD_LIST *shell_expand_word_list __P((WORD_LIST *, int));
359 static WORD_LIST *expand_word_list_internal __P((WORD_LIST *, int));
360
361 /* **************************************************************** */
362 /* */
363 /* Utility Functions */
364 /* */
365 /* **************************************************************** */
366
367 #if defined (DEBUG)
368 void
369 dump_word_flags (flags)
370 int flags;
371 {
372 int f;
373
374 f = flags;
375 fprintf (stderr, "%d -> ", f);
376 if (f & W_ARRAYIND)
377 {
378 f &= ~W_ARRAYIND;
379 fprintf (stderr, "W_ARRAYIND%s", f ? "|" : "");
380 }
381 if (f & W_ASSIGNASSOC)
382 {
383 f &= ~W_ASSIGNASSOC;
384 fprintf (stderr, "W_ASSIGNASSOC%s", f ? "|" : "");
385 }
386 if (f & W_ASSIGNARRAY)
387 {
388 f &= ~W_ASSIGNARRAY;
389 fprintf (stderr, "W_ASSIGNARRAY%s", f ? "|" : "");
390 }
391 if (f & W_SAWQUOTEDNULL)
392 {
393 f &= ~W_SAWQUOTEDNULL;
394 fprintf (stderr, "W_SAWQUOTEDNULL%s", f ? "|" : "");
395 }
396 if (f & W_NOPROCSUB)
397 {
398 f &= ~W_NOPROCSUB;
399 fprintf (stderr, "W_NOPROCSUB%s", f ? "|" : "");
400 }
401 if (f & W_DQUOTE)
402 {
403 f &= ~W_DQUOTE;
404 fprintf (stderr, "W_DQUOTE%s", f ? "|" : "");
405 }
406 if (f & W_HASQUOTEDNULL)
407 {
408 f &= ~W_HASQUOTEDNULL;
409 fprintf (stderr, "W_HASQUOTEDNULL%s", f ? "|" : "");
410 }
411 if (f & W_ASSIGNARG)
412 {
413 f &= ~W_ASSIGNARG;
414 fprintf (stderr, "W_ASSIGNARG%s", f ? "|" : "");
415 }
416 if (f & W_ASSNBLTIN)
417 {
418 f &= ~W_ASSNBLTIN;
419 fprintf (stderr, "W_ASSNBLTIN%s", f ? "|" : "");
420 }
421 if (f & W_ASSNGLOBAL)
422 {
423 f &= ~W_ASSNGLOBAL;
424 fprintf (stderr, "W_ASSNGLOBAL%s", f ? "|" : "");
425 }
426 if (f & W_COMPASSIGN)
427 {
428 f &= ~W_COMPASSIGN;
429 fprintf (stderr, "W_COMPASSIGN%s", f ? "|" : "");
430 }
431 if (f & W_NOEXPAND)
432 {
433 f &= ~W_NOEXPAND;
434 fprintf (stderr, "W_NOEXPAND%s", f ? "|" : "");
435 }
436 if (f & W_ITILDE)
437 {
438 f &= ~W_ITILDE;
439 fprintf (stderr, "W_ITILDE%s", f ? "|" : "");
440 }
441 if (f & W_NOTILDE)
442 {
443 f &= ~W_NOTILDE;
444 fprintf (stderr, "W_NOTILDE%s", f ? "|" : "");
445 }
446 if (f & W_ASSIGNRHS)
447 {
448 f &= ~W_ASSIGNRHS;
449 fprintf (stderr, "W_ASSIGNRHS%s", f ? "|" : "");
450 }
451 if (f & W_NOASSNTILDE)
452 {
453 f &= ~W_NOASSNTILDE;
454 fprintf (stderr, "W_NOASSNTILDE%s", f ? "|" : "");
455 }
456 if (f & W_NOCOMSUB)
457 {
458 f &= ~W_NOCOMSUB;
459 fprintf (stderr, "W_NOCOMSUB%s", f ? "|" : "");
460 }
461 if (f & W_DOLLARSTAR)
462 {
463 f &= ~W_DOLLARSTAR;
464 fprintf (stderr, "W_DOLLARSTAR%s", f ? "|" : "");
465 }
466 if (f & W_DOLLARAT)
467 {
468 f &= ~W_DOLLARAT;
469 fprintf (stderr, "W_DOLLARAT%s", f ? "|" : "");
470 }
471 if (f & W_TILDEEXP)
472 {
473 f &= ~W_TILDEEXP;
474 fprintf (stderr, "W_TILDEEXP%s", f ? "|" : "");
475 }
476 if (f & W_NOSPLIT2)
477 {
478 f &= ~W_NOSPLIT2;
479 fprintf (stderr, "W_NOSPLIT2%s", f ? "|" : "");
480 }
481 if (f & W_NOSPLIT)
482 {
483 f &= ~W_NOSPLIT;
484 fprintf (stderr, "W_NOSPLIT%s", f ? "|" : "");
485 }
486 if (f & W_NOBRACE)
487 {
488 f &= ~W_NOBRACE;
489 fprintf (stderr, "W_NOBRACE%s", f ? "|" : "");
490 }
491 if (f & W_NOGLOB)
492 {
493 f &= ~W_NOGLOB;
494 fprintf (stderr, "W_NOGLOB%s", f ? "|" : "");
495 }
496 if (f & W_SPLITSPACE)
497 {
498 f &= ~W_SPLITSPACE;
499 fprintf (stderr, "W_SPLITSPACE%s", f ? "|" : "");
500 }
501 if (f & W_ASSIGNMENT)
502 {
503 f &= ~W_ASSIGNMENT;
504 fprintf (stderr, "W_ASSIGNMENT%s", f ? "|" : "");
505 }
506 if (f & W_QUOTED)
507 {
508 f &= ~W_QUOTED;
509 fprintf (stderr, "W_QUOTED%s", f ? "|" : "");
510 }
511 if (f & W_HASDOLLAR)
512 {
513 f &= ~W_HASDOLLAR;
514 fprintf (stderr, "W_HASDOLLAR%s", f ? "|" : "");
515 }
516 if (f & W_COMPLETE)
517 {
518 f &= ~W_COMPLETE;
519 fprintf (stderr, "W_COMPLETE%s", f ? "|" : "");
520 }
521 if (f & W_CHKLOCAL)
522 {
523 f &= ~W_CHKLOCAL;
524 fprintf (stderr, "W_CHKLOCAL%s", f ? "|" : "");
525 }
526
527 fprintf (stderr, "\n");
528 fflush (stderr);
529 }
530 #endif
531
532 #ifdef INCLUDE_UNUSED
533 static char *
534 quoted_substring (string, start, end)
535 char *string;
536 int start, end;
537 {
538 register int len, l;
539 register char *result, *s, *r;
540
541 len = end - start;
542
543 /* Move to string[start], skipping quoted characters. */
544 for (s = string, l = 0; *s && l < start; )
545 {
546 if (*s == CTLESC)
547 {
548 s++;
549 continue;
550 }
551 l++;
552 if (*s == 0)
553 break;
554 }
555
556 r = result = (char *)xmalloc (2*len + 1); /* save room for quotes */
557
558 /* Copy LEN characters, including quote characters. */
559 s = string + l;
560 for (l = 0; l < len; s++)
561 {
562 if (*s == CTLESC)
563 *r++ = *s++;
564 *r++ = *s;
565 l++;
566 if (*s == 0)
567 break;
568 }
569 *r = '\0';
570 return result;
571 }
572 #endif
573
574 #ifdef INCLUDE_UNUSED
575 /* Return the length of S, skipping over quoted characters */
576 static int
577 quoted_strlen (s)
578 char *s;
579 {
580 register char *p;
581 int i;
582
583 i = 0;
584 for (p = s; *p; p++)
585 {
586 if (*p == CTLESC)
587 {
588 p++;
589 if (*p == 0)
590 return (i + 1);
591 }
592 i++;
593 }
594
595 return i;
596 }
597 #endif
598
599 #ifdef INCLUDE_UNUSED
600 /* Find the first occurrence of character C in string S, obeying shell
601 quoting rules. If (FLAGS & ST_BACKSL) is non-zero, backslash-escaped
602 characters are skipped. If (FLAGS & ST_CTLESC) is non-zero, characters
603 escaped with CTLESC are skipped. */
604 static char *
605 quoted_strchr (s, c, flags)
606 char *s;
607 int c, flags;
608 {
609 register char *p;
610
611 for (p = s; *p; p++)
612 {
613 if (((flags & ST_BACKSL) && *p == '\\')
614 || ((flags & ST_CTLESC) && *p == CTLESC))
615 {
616 p++;
617 if (*p == '\0')
618 return ((char *)NULL);
619 continue;
620 }
621 else if (*p == c)
622 return p;
623 }
624 return ((char *)NULL);
625 }
626
627 /* Return 1 if CHARACTER appears in an unquoted portion of
628 STRING. Return 0 otherwise. CHARACTER must be a single-byte character. */
629 static int
630 unquoted_member (character, string)
631 int character;
632 char *string;
633 {
634 size_t slen;
635 int sindex, c;
636 DECLARE_MBSTATE;
637
638 slen = strlen (string);
639 sindex = 0;
640 while (c = string[sindex])
641 {
642 if (c == character)
643 return (1);
644
645 switch (c)
646 {
647 default:
648 ADVANCE_CHAR (string, slen, sindex);
649 break;
650
651 case '\\':
652 sindex++;
653 if (string[sindex])
654 ADVANCE_CHAR (string, slen, sindex);
655 break;
656
657 case '\'':
658 sindex = skip_single_quoted (string, slen, ++sindex, 0);
659 break;
660
661 case '"':
662 sindex = skip_double_quoted (string, slen, ++sindex, 0);
663 break;
664 }
665 }
666 return (0);
667 }
668
669 /* Return 1 if SUBSTR appears in an unquoted portion of STRING. */
670 static int
671 unquoted_substring (substr, string)
672 char *substr, *string;
673 {
674 size_t slen;
675 int sindex, c, sublen;
676 DECLARE_MBSTATE;
677
678 if (substr == 0 || *substr == '\0')
679 return (0);
680
681 slen = strlen (string);
682 sublen = strlen (substr);
683 for (sindex = 0; c = string[sindex]; )
684 {
685 if (STREQN (string + sindex, substr, sublen))
686 return (1);
687
688 switch (c)
689 {
690 case '\\':
691 sindex++;
692 if (string[sindex])
693 ADVANCE_CHAR (string, slen, sindex);
694 break;
695
696 case '\'':
697 sindex = skip_single_quoted (string, slen, ++sindex, 0);
698 break;
699
700 case '"':
701 sindex = skip_double_quoted (string, slen, ++sindex, 0);
702 break;
703
704 default:
705 ADVANCE_CHAR (string, slen, sindex);
706 break;
707 }
708 }
709 return (0);
710 }
711 #endif
712
713 /* Most of the substitutions must be done in parallel. In order
714 to avoid using tons of unclear goto's, I have some functions
715 for manipulating malloc'ed strings. They all take INDX, a
716 pointer to an integer which is the offset into the string
717 where manipulation is taking place. They also take SIZE, a
718 pointer to an integer which is the current length of the
719 character array for this string. */
720
721 /* Append SOURCE to TARGET at INDEX. SIZE is the current amount
722 of space allocated to TARGET. SOURCE can be NULL, in which
723 case nothing happens. Gets rid of SOURCE by freeing it.
724 Returns TARGET in case the location has changed. */
725 INLINE char *
726 sub_append_string (source, target, indx, size)
727 char *source, *target;
728 int *indx;
729 size_t *size;
730 {
731 if (source)
732 {
733 int n;
734 size_t srclen;
735
736 srclen = STRLEN (source);
737 if (srclen >= (int)(*size - *indx))
738 {
739 n = srclen + *indx;
740 n = (n + DEFAULT_ARRAY_SIZE) - (n % DEFAULT_ARRAY_SIZE);
741 target = (char *)xrealloc (target, (*size = n));
742 }
743
744 FASTCOPY (source, target + *indx, srclen);
745 *indx += srclen;
746 target[*indx] = '\0';
747
748 free (source);
749 }
750 return (target);
751 }
752
753 #if 0
754 /* UNUSED */
755 /* Append the textual representation of NUMBER to TARGET.
756 INDX and SIZE are as in SUB_APPEND_STRING. */
757 char *
758 sub_append_number (number, target, indx, size)
759 intmax_t number;
760 char *target;
761 int *indx;
762 size_t *size;
763 {
764 char *temp;
765
766 temp = itos (number);
767 return (sub_append_string (temp, target, indx, size));
768 }
769 #endif
770
771 /* Extract a substring from STRING, starting at SINDEX and ending with
772 one of the characters in CHARLIST. Don't make the ending character
773 part of the string. Leave SINDEX pointing at the ending character.
774 Understand about backslashes in the string. If (flags & SX_VARNAME)
775 is non-zero, and array variables have been compiled into the shell,
776 everything between a `[' and a corresponding `]' is skipped over.
777 If (flags & SX_NOALLOC) is non-zero, don't return the substring, just
778 update SINDEX. If (flags & SX_REQMATCH) is non-zero, the string must
779 contain a closing character from CHARLIST. */
780 static char *
781 string_extract (string, sindex, charlist, flags)
782 char *string;
783 int *sindex;
784 char *charlist;
785 int flags;
786 {
787 register int c, i;
788 int found;
789 size_t slen;
790 char *temp;
791 DECLARE_MBSTATE;
792
793 slen = (MB_CUR_MAX > 1) ? strlen (string + *sindex) + *sindex : 0;
794 i = *sindex;
795 found = 0;
796 while (c = string[i])
797 {
798 if (c == '\\')
799 {
800 if (string[i + 1])
801 i++;
802 else
803 break;
804 }
805 #if defined (ARRAY_VARS)
806 else if ((flags & SX_VARNAME) && c == LBRACK)
807 {
808 int ni;
809 /* If this is an array subscript, skip over it and continue. */
810 ni = skipsubscript (string, i, 0);
811 if (string[ni] == RBRACK)
812 i = ni;
813 }
814 #endif
815 else if (MEMBER (c, charlist))
816 {
817 found = 1;
818 break;
819 }
820
821 ADVANCE_CHAR (string, slen, i);
822 }
823
824 /* If we had to have a matching delimiter and didn't find one, return an
825 error and let the caller deal with it. */
826 if ((flags & SX_REQMATCH) && found == 0)
827 {
828 *sindex = i;
829 return (&extract_string_error);
830 }
831
832 temp = (flags & SX_NOALLOC) ? (char *)NULL : substring (string, *sindex, i);
833 *sindex = i;
834
835 return (temp);
836 }
837
838 /* Extract the contents of STRING as if it is enclosed in double quotes.
839 SINDEX, when passed in, is the offset of the character immediately
840 following the opening double quote; on exit, SINDEX is left pointing after
841 the closing double quote. If STRIPDQ is non-zero, unquoted double
842 quotes are stripped and the string is terminated by a null byte.
843 Backslashes between the embedded double quotes are processed. If STRIPDQ
844 is zero, an unquoted `"' terminates the string. */
845 static char *
846 string_extract_double_quoted (string, sindex, flags)
847 char *string;
848 int *sindex, flags;
849 {
850 size_t slen;
851 char *send;
852 int j, i, t;
853 unsigned char c;
854 char *temp, *ret; /* The new string we return. */
855 int pass_next, backquote, si; /* State variables for the machine. */
856 int dquote;
857 int stripdq;
858 DECLARE_MBSTATE;
859
860 slen = strlen (string + *sindex) + *sindex;
861 send = string + slen;
862
863 stripdq = (flags & SX_STRIPDQ);
864
865 pass_next = backquote = dquote = 0;
866 temp = (char *)xmalloc (1 + slen - *sindex);
867
868 j = 0;
869 i = *sindex;
870 while (c = string[i])
871 {
872 /* Process a character that was quoted by a backslash. */
873 if (pass_next)
874 {
875 /* XXX - take another look at this in light of Interp 221 */
876 /* Posix.2 sez:
877
878 ``The backslash shall retain its special meaning as an escape
879 character only when followed by one of the characters:
880 $ ` " \ <newline>''.
881
882 If STRIPDQ is zero, we handle the double quotes here and let
883 expand_word_internal handle the rest. If STRIPDQ is non-zero,
884 we have already been through one round of backslash stripping,
885 and want to strip these backslashes only if DQUOTE is non-zero,
886 indicating that we are inside an embedded double-quoted string. */
887
888 /* If we are in an embedded quoted string, then don't strip
889 backslashes before characters for which the backslash
890 retains its special meaning, but remove backslashes in
891 front of other characters. If we are not in an
892 embedded quoted string, don't strip backslashes at all.
893 This mess is necessary because the string was already
894 surrounded by double quotes (and sh has some really weird
895 quoting rules).
896 The returned string will be run through expansion as if
897 it were double-quoted. */
898 if ((stripdq == 0 && c != '"') ||
899 (stripdq && ((dquote && (sh_syntaxtab[c] & CBSDQUOTE)) || dquote == 0)))
900 temp[j++] = '\\';
901 pass_next = 0;
902
903 add_one_character:
904 COPY_CHAR_I (temp, j, string, send, i);
905 continue;
906 }
907
908 /* A backslash protects the next character. The code just above
909 handles preserving the backslash in front of any character but
910 a double quote. */
911 if (c == '\\')
912 {
913 pass_next++;
914 i++;
915 continue;
916 }
917
918 /* Inside backquotes, ``the portion of the quoted string from the
919 initial backquote and the characters up to the next backquote
920 that is not preceded by a backslash, having escape characters
921 removed, defines that command''. */
922 if (backquote)
923 {
924 if (c == '`')
925 backquote = 0;
926 temp[j++] = c; /* COPY_CHAR_I? */
927 i++;
928 continue;
929 }
930
931 if (c == '`')
932 {
933 temp[j++] = c;
934 backquote++;
935 i++;
936 continue;
937 }
938
939 /* Pass everything between `$(' and the matching `)' or a quoted
940 ${ ... } pair through according to the Posix.2 specification. */
941 if (c == '$' && ((string[i + 1] == LPAREN) || (string[i + 1] == LBRACE)))
942 {
943 int free_ret = 1;
944
945 si = i + 2;
946 if (string[i + 1] == LPAREN)
947 ret = extract_command_subst (string, &si, (flags & SX_COMPLETE));
948 else
949 ret = extract_dollar_brace_string (string, &si, Q_DOUBLE_QUOTES, 0);
950
951 temp[j++] = '$';
952 temp[j++] = string[i + 1];
953
954 /* Just paranoia; ret will not be 0 unless no_longjmp_on_fatal_error
955 is set. */
956 if (ret == 0 && no_longjmp_on_fatal_error)
957 {
958 free_ret = 0;
959 ret = string + i + 2;
960 }
961
962 /* XXX - CHECK_STRING_OVERRUN here? */
963 for (t = 0; ret[t]; t++, j++)
964 temp[j] = ret[t];
965 temp[j] = string[si];
966
967 if (string[si])
968 {
969 j++;
970 i = si + 1;
971 }
972 else
973 i = si;
974
975 if (free_ret)
976 free (ret);
977 continue;
978 }
979
980 /* Add any character but a double quote to the quoted string we're
981 accumulating. */
982 if (c != '"')
983 goto add_one_character;
984
985 /* c == '"' */
986 if (stripdq)
987 {
988 dquote ^= 1;
989 i++;
990 continue;
991 }
992
993 break;
994 }
995 temp[j] = '\0';
996
997 /* Point to after the closing quote. */
998 if (c)
999 i++;
1000 *sindex = i;
1001
1002 return (temp);
1003 }
1004
1005 /* This should really be another option to string_extract_double_quoted. */
1006 static int
1007 skip_double_quoted (string, slen, sind, flags)
1008 char *string;
1009 size_t slen;
1010 int sind;
1011 int flags;
1012 {
1013 int c, i;
1014 char *ret;
1015 int pass_next, backquote, si;
1016 DECLARE_MBSTATE;
1017
1018 pass_next = backquote = 0;
1019 i = sind;
1020 while (c = string[i])
1021 {
1022 if (pass_next)
1023 {
1024 pass_next = 0;
1025 ADVANCE_CHAR (string, slen, i);
1026 continue;
1027 }
1028 else if (c == '\\')
1029 {
1030 pass_next++;
1031 i++;
1032 continue;
1033 }
1034 else if (backquote)
1035 {
1036 if (c == '`')
1037 backquote = 0;
1038 ADVANCE_CHAR (string, slen, i);
1039 continue;
1040 }
1041 else if (c == '`')
1042 {
1043 backquote++;
1044 i++;
1045 continue;
1046 }
1047 else if (c == '$' && ((string[i + 1] == LPAREN) || (string[i + 1] == LBRACE)))
1048 {
1049 si = i + 2;
1050 if (string[i + 1] == LPAREN)
1051 ret = extract_command_subst (string, &si, SX_NOALLOC|(flags&SX_COMPLETE));
1052 else
1053 ret = extract_dollar_brace_string (string, &si, Q_DOUBLE_QUOTES, SX_NOALLOC);
1054
1055 /* These can consume the entire string if they are unterminated */
1056 CHECK_STRING_OVERRUN (i, si, slen, c);
1057
1058 i = si + 1;
1059 continue;
1060 }
1061 else if (c != '"')
1062 {
1063 ADVANCE_CHAR (string, slen, i);
1064 continue;
1065 }
1066 else
1067 break;
1068 }
1069
1070 if (c)
1071 i++;
1072
1073 return (i);
1074 }
1075
1076 /* Extract the contents of STRING as if it is enclosed in single quotes.
1077 SINDEX, when passed in, is the offset of the character immediately
1078 following the opening single quote; on exit, SINDEX is left pointing after
1079 the closing single quote. */
1080 static inline char *
1081 string_extract_single_quoted (string, sindex)
1082 char *string;
1083 int *sindex;
1084 {
1085 register int i;
1086 size_t slen;
1087 char *t;
1088 DECLARE_MBSTATE;
1089
1090 /* Don't need slen for ADVANCE_CHAR unless multibyte chars possible. */
1091 slen = (MB_CUR_MAX > 1) ? strlen (string + *sindex) + *sindex : 0;
1092 i = *sindex;
1093 while (string[i] && string[i] != '\'')
1094 ADVANCE_CHAR (string, slen, i);
1095
1096 t = substring (string, *sindex, i);
1097
1098 if (string[i])
1099 i++;
1100 *sindex = i;
1101
1102 return (t);
1103 }
1104
1105 /* Skip over a single-quoted string. We overload the SX_COMPLETE flag to mean
1106 that we are splitting out words for completion and have encountered a $'...'
1107 string, which allows backslash-escaped single quotes. */
1108 static inline int
1109 skip_single_quoted (string, slen, sind, flags)
1110 const char *string;
1111 size_t slen;
1112 int sind;
1113 int flags;
1114 {
1115 register int c;
1116 DECLARE_MBSTATE;
1117
1118 c = sind;
1119 while (string[c] && string[c] != '\'')
1120 {
1121 if ((flags & SX_COMPLETE) && string[c] == '\\' && string[c+1] == '\'' && string[c+2])
1122 ADVANCE_CHAR (string, slen, c);
1123 ADVANCE_CHAR (string, slen, c);
1124 }
1125
1126 if (string[c])
1127 c++;
1128 return c;
1129 }
1130
1131 /* Just like string_extract, but doesn't hack backslashes or any of
1132 that other stuff. Obeys CTLESC quoting. Used to do splitting on $IFS. */
1133 static char *
1134 string_extract_verbatim (string, slen, sindex, charlist, flags)
1135 char *string;
1136 size_t slen;
1137 int *sindex;
1138 char *charlist;
1139 int flags;
1140 {
1141 register int i;
1142 #if defined (HANDLE_MULTIBYTE)
1143 wchar_t *wcharlist;
1144 #endif
1145 int c;
1146 char *temp;
1147 DECLARE_MBSTATE;
1148
1149 if ((flags & SX_NOCTLESC) && charlist[0] == '\'' && charlist[1] == '\0')
1150 {
1151 temp = string_extract_single_quoted (string, sindex);
1152 --*sindex; /* leave *sindex at separator character */
1153 return temp;
1154 }
1155
1156 i = *sindex;
1157 #if defined (HANDLE_MULTIBYTE)
1158 wcharlist = 0;
1159 #endif
1160 while (c = string[i])
1161 {
1162 #if defined (HANDLE_MULTIBYTE)
1163 size_t mblength;
1164 #endif
1165 if ((flags & SX_NOCTLESC) == 0 && c == CTLESC)
1166 {
1167 i += 2;
1168 CHECK_STRING_OVERRUN (i, i, slen, c);
1169 continue;
1170 }
1171 /* Even if flags contains SX_NOCTLESC, we let CTLESC quoting CTLNUL
1172 through, to protect the CTLNULs from later calls to
1173 remove_quoted_nulls. */
1174 else if ((flags & SX_NOESCCTLNUL) == 0 && c == CTLESC && string[i+1] == CTLNUL)
1175 {
1176 i += 2;
1177 CHECK_STRING_OVERRUN (i, i, slen, c);
1178 continue;
1179 }
1180
1181 #if defined (HANDLE_MULTIBYTE)
1182 if (locale_utf8locale && slen > i && UTF8_SINGLEBYTE (string[i]))
1183 mblength = (string[i] != 0) ? 1 : 0;
1184 else
1185 mblength = MBLEN (string + i, slen - i);
1186 if (mblength > 1)
1187 {
1188 wchar_t wc;
1189 mblength = mbtowc (&wc, string + i, slen - i);
1190 if (MB_INVALIDCH (mblength))
1191 {
1192 if (MEMBER (c, charlist))
1193 break;
1194 }
1195 else
1196 {
1197 if (wcharlist == 0)
1198 {
1199 size_t len;
1200 len = mbstowcs (wcharlist, charlist, 0);
1201 if (len == -1)
1202 len = 0;
1203 wcharlist = (wchar_t *)xmalloc (sizeof (wchar_t) * (len + 1));
1204 mbstowcs (wcharlist, charlist, len + 1);
1205 }
1206
1207 if (wcschr (wcharlist, wc))
1208 break;
1209 }
1210 }
1211 else
1212 #endif
1213 if (MEMBER (c, charlist))
1214 break;
1215
1216 ADVANCE_CHAR (string, slen, i);
1217 }
1218
1219 #if defined (HANDLE_MULTIBYTE)
1220 FREE (wcharlist);
1221 #endif
1222
1223 temp = substring (string, *sindex, i);
1224 *sindex = i;
1225
1226 return (temp);
1227 }
1228
1229 /* Extract the $( construct in STRING, and return a new string.
1230 Start extracting at (SINDEX) as if we had just seen "$(".
1231 Make (SINDEX) get the position of the matching ")". )
1232 XFLAGS is additional flags to pass to other extraction functions. */
1233 char *
1234 extract_command_subst (string, sindex, xflags)
1235 char *string;
1236 int *sindex;
1237 int xflags;
1238 {
1239 char *ret;
1240
1241 if (string[*sindex] == LPAREN || (xflags & SX_COMPLETE))
1242 return (extract_delimited_string (string, sindex, "$(", "(", ")", xflags|SX_COMMAND)); /*)*/
1243 else
1244 {
1245 xflags |= (no_longjmp_on_fatal_error ? SX_NOLONGJMP : 0);
1246 ret = xparse_dolparen (string, string+*sindex, sindex, xflags);
1247 return ret;
1248 }
1249 }
1250
1251 /* Extract the $[ construct in STRING, and return a new string. (])
1252 Start extracting at (SINDEX) as if we had just seen "$[".
1253 Make (SINDEX) get the position of the matching "]". */
1254 char *
1255 extract_arithmetic_subst (string, sindex)
1256 char *string;
1257 int *sindex;
1258 {
1259 return (extract_delimited_string (string, sindex, "$[", "[", "]", 0)); /*]*/
1260 }
1261
1262 #if defined (PROCESS_SUBSTITUTION)
1263 /* Extract the <( or >( construct in STRING, and return a new string.
1264 Start extracting at (SINDEX) as if we had just seen "<(".
1265 Make (SINDEX) get the position of the matching ")". */ /*))*/
1266 char *
1267 extract_process_subst (string, starter, sindex, xflags)
1268 char *string;
1269 char *starter;
1270 int *sindex;
1271 int xflags;
1272 {
1273 #if 0
1274 /* XXX - check xflags&SX_COMPLETE here? */
1275 return (extract_delimited_string (string, sindex, starter, "(", ")", SX_COMMAND));
1276 #else
1277 xflags |= (no_longjmp_on_fatal_error ? SX_NOLONGJMP : 0);
1278 return (xparse_dolparen (string, string+*sindex, sindex, xflags));
1279 #endif
1280 }
1281 #endif /* PROCESS_SUBSTITUTION */
1282
1283 #if defined (ARRAY_VARS)
1284 /* This can be fooled by unquoted right parens in the passed string. If
1285 each caller verifies that the last character in STRING is a right paren,
1286 we don't even need to call extract_delimited_string. */
1287 char *
1288 extract_array_assignment_list (string, sindex)
1289 char *string;
1290 int *sindex;
1291 {
1292 int slen;
1293 char *ret;
1294
1295 slen = strlen (string);
1296 if (string[slen - 1] == RPAREN)
1297 {
1298 ret = substring (string, *sindex, slen - 1);
1299 *sindex = slen - 1;
1300 return ret;
1301 }
1302 return 0;
1303 }
1304 #endif
1305
1306 /* Extract and create a new string from the contents of STRING, a
1307 character string delimited with OPENER and CLOSER. SINDEX is
1308 the address of an int describing the current offset in STRING;
1309 it should point to just after the first OPENER found. On exit,
1310 SINDEX gets the position of the last character of the matching CLOSER.
1311 If OPENER is more than a single character, ALT_OPENER, if non-null,
1312 contains a character string that can also match CLOSER and thus
1313 needs to be skipped. */
1314 static char *
1315 extract_delimited_string (string, sindex, opener, alt_opener, closer, flags)
1316 char *string;
1317 int *sindex;
1318 char *opener, *alt_opener, *closer;
1319 int flags;
1320 {
1321 int i, c, si;
1322 size_t slen;
1323 char *t, *result;
1324 int pass_character, nesting_level, in_comment;
1325 int len_closer, len_opener, len_alt_opener;
1326 DECLARE_MBSTATE;
1327
1328 slen = strlen (string + *sindex) + *sindex;
1329 len_opener = STRLEN (opener);
1330 len_alt_opener = STRLEN (alt_opener);
1331 len_closer = STRLEN (closer);
1332
1333 pass_character = in_comment = 0;
1334
1335 nesting_level = 1;
1336 i = *sindex;
1337
1338 while (nesting_level)
1339 {
1340 c = string[i];
1341
1342 /* If a recursive call or a call to ADVANCE_CHAR leaves the index beyond
1343 the end of the string, catch it and cut the loop. */
1344 if (i > slen)
1345 {
1346 i = slen;
1347 c = string[i = slen];
1348 break;
1349 }
1350
1351 if (c == 0)
1352 break;
1353
1354 if (in_comment)
1355 {
1356 if (c == '\n')
1357 in_comment = 0;
1358 ADVANCE_CHAR (string, slen, i);
1359 continue;
1360 }
1361
1362 if (pass_character) /* previous char was backslash */
1363 {
1364 pass_character = 0;
1365 ADVANCE_CHAR (string, slen, i);
1366 continue;
1367 }
1368
1369 /* Not exactly right yet; should handle shell metacharacters and
1370 multibyte characters, too. See COMMENT_BEGIN define in parse.y */
1371 if ((flags & SX_COMMAND) && c == '#' && (i == 0 || string[i - 1] == '\n' || shellblank (string[i - 1])))
1372 {
1373 in_comment = 1;
1374 ADVANCE_CHAR (string, slen, i);
1375 continue;
1376 }
1377
1378 if (c == CTLESC || c == '\\')
1379 {
1380 pass_character++;
1381 i++;
1382 continue;
1383 }
1384
1385 /* Process a nested command substitution, but only if we're parsing an
1386 arithmetic substitution. */
1387 if ((flags & SX_COMMAND) && string[i] == '$' && string[i+1] == LPAREN)
1388 {
1389 si = i + 2;
1390 t = extract_command_subst (string, &si, flags|SX_NOALLOC);
1391 CHECK_STRING_OVERRUN (i, si, slen, c);
1392 i = si + 1;
1393 continue;
1394 }
1395
1396 /* Process a nested OPENER. */
1397 if (STREQN (string + i, opener, len_opener))
1398 {
1399 si = i + len_opener;
1400 t = extract_delimited_string (string, &si, opener, alt_opener, closer, flags|SX_NOALLOC);
1401 CHECK_STRING_OVERRUN (i, si, slen, c);
1402 i = si + 1;
1403 continue;
1404 }
1405
1406 /* Process a nested ALT_OPENER */
1407 if (len_alt_opener && STREQN (string + i, alt_opener, len_alt_opener))
1408 {
1409 si = i + len_alt_opener;
1410 t = extract_delimited_string (string, &si, alt_opener, alt_opener, closer, flags|SX_NOALLOC);
1411 CHECK_STRING_OVERRUN (i, si, slen, c);
1412 i = si + 1;
1413 continue;
1414 }
1415
1416 /* If the current substring terminates the delimited string, decrement
1417 the nesting level. */
1418 if (STREQN (string + i, closer, len_closer))
1419 {
1420 i += len_closer - 1; /* move to last byte of the closer */
1421 nesting_level--;
1422 if (nesting_level == 0)
1423 break;
1424 }
1425
1426 /* Pass old-style command substitution through verbatim. */
1427 if (c == '`')
1428 {
1429 si = i + 1;
1430 t = string_extract (string, &si, "`", flags|SX_NOALLOC);
1431 CHECK_STRING_OVERRUN (i, si, slen, c);
1432 i = si + 1;
1433 continue;
1434 }
1435
1436 /* Pass single-quoted and double-quoted strings through verbatim. */
1437 if (c == '\'' || c == '"')
1438 {
1439 si = i + 1;
1440 i = (c == '\'') ? skip_single_quoted (string, slen, si, 0)
1441 : skip_double_quoted (string, slen, si, 0);
1442 continue;
1443 }
1444
1445 /* move past this character, which was not special. */
1446 ADVANCE_CHAR (string, slen, i);
1447 }
1448
1449 if (c == 0 && nesting_level)
1450 {
1451 if (no_longjmp_on_fatal_error == 0)
1452 {
1453 last_command_exit_value = EXECUTION_FAILURE;
1454 report_error (_("bad substitution: no closing `%s' in %s"), closer, string);
1455 exp_jump_to_top_level (DISCARD);
1456 }
1457 else
1458 {
1459 *sindex = i;
1460 return (char *)NULL;
1461 }
1462 }
1463
1464 si = i - *sindex - len_closer + 1;
1465 if (flags & SX_NOALLOC)
1466 result = (char *)NULL;
1467 else
1468 {
1469 result = (char *)xmalloc (1 + si);
1470 strncpy (result, string + *sindex, si);
1471 result[si] = '\0';
1472 }
1473 *sindex = i;
1474
1475 return (result);
1476 }
1477
1478 /* Extract a parameter expansion expression within ${ and } from STRING.
1479 Obey the Posix.2 rules for finding the ending `}': count braces while
1480 skipping over enclosed quoted strings and command substitutions.
1481 SINDEX is the address of an int describing the current offset in STRING;
1482 it should point to just after the first `{' found. On exit, SINDEX
1483 gets the position of the matching `}'. QUOTED is non-zero if this
1484 occurs inside double quotes. */
1485 /* XXX -- this is very similar to extract_delimited_string -- XXX */
1486 static char *
1487 extract_dollar_brace_string (string, sindex, quoted, flags)
1488 char *string;
1489 int *sindex, quoted, flags;
1490 {
1491 register int i, c;
1492 size_t slen;
1493 int pass_character, nesting_level, si, dolbrace_state;
1494 char *result, *t;
1495 DECLARE_MBSTATE;
1496
1497 pass_character = 0;
1498 nesting_level = 1;
1499 slen = strlen (string + *sindex) + *sindex;
1500
1501 /* The handling of dolbrace_state needs to agree with the code in parse.y:
1502 parse_matched_pair(). The different initial value is to handle the
1503 case where this function is called to parse the word in
1504 ${param op word} (SX_WORD). */
1505 dolbrace_state = (flags & SX_WORD) ? DOLBRACE_WORD : DOLBRACE_PARAM;
1506 if ((quoted & (Q_HERE_DOCUMENT|Q_DOUBLE_QUOTES)) && (flags & SX_POSIXEXP))
1507 dolbrace_state = DOLBRACE_QUOTE;
1508
1509 i = *sindex;
1510 while (c = string[i])
1511 {
1512 if (pass_character)
1513 {
1514 pass_character = 0;
1515 ADVANCE_CHAR (string, slen, i);
1516 continue;
1517 }
1518
1519 /* CTLESCs and backslashes quote the next character. */
1520 if (c == CTLESC || c == '\\')
1521 {
1522 pass_character++;
1523 i++;
1524 continue;
1525 }
1526
1527 if (string[i] == '$' && string[i+1] == LBRACE)
1528 {
1529 nesting_level++;
1530 i += 2;
1531 continue;
1532 }
1533
1534 if (c == RBRACE)
1535 {
1536 nesting_level--;
1537 if (nesting_level == 0)
1538 break;
1539 i++;
1540 continue;
1541 }
1542
1543 /* Pass the contents of old-style command substitutions through
1544 verbatim. */
1545 if (c == '`')
1546 {
1547 si = i + 1;
1548 t = string_extract (string, &si, "`", flags|SX_NOALLOC);
1549
1550 CHECK_STRING_OVERRUN (i, si, slen, c);
1551
1552 i = si + 1;
1553 continue;
1554 }
1555
1556 /* Pass the contents of new-style command substitutions and
1557 arithmetic substitutions through verbatim. */
1558 if (string[i] == '$' && string[i+1] == LPAREN)
1559 {
1560 si = i + 2;
1561 t = extract_command_subst (string, &si, flags|SX_NOALLOC);
1562
1563 CHECK_STRING_OVERRUN (i, si, slen, c);
1564
1565 i = si + 1;
1566 continue;
1567 }
1568
1569 #if defined (PROCESS_SUBSTITUTION)
1570 /* Technically this should only work at the start of a word */
1571 if ((string[i] == '<' || string[i] == '>') && string[i+1] == LPAREN)
1572 {
1573 si = i + 2;
1574 t = extract_process_subst (string, (string[i] == '<' ? "<(" : ">)"), &si, flags|SX_NOALLOC);
1575
1576 CHECK_STRING_OVERRUN (i, si, slen, c);
1577
1578 i = si + 1;
1579 continue;
1580 }
1581 #endif
1582
1583 /* Pass the contents of double-quoted strings through verbatim. */
1584 if (c == '"')
1585 {
1586 si = i + 1;
1587 i = skip_double_quoted (string, slen, si, 0);
1588 /* skip_XXX_quoted leaves index one past close quote */
1589 continue;
1590 }
1591
1592 if (c == '\'')
1593 {
1594 /*itrace("extract_dollar_brace_string: c == single quote flags = %d quoted = %d dolbrace_state = %d", flags, quoted, dolbrace_state);*/
1595 if (posixly_correct && shell_compatibility_level > 42 && dolbrace_state != DOLBRACE_QUOTE && (quoted & (Q_HERE_DOCUMENT|Q_DOUBLE_QUOTES)))
1596 ADVANCE_CHAR (string, slen, i);
1597 else
1598 {
1599 si = i + 1;
1600 i = skip_single_quoted (string, slen, si, 0);
1601 }
1602
1603 continue;
1604 }
1605
1606 #if defined (ARRAY_VARS)
1607 if (c == LBRACK && dolbrace_state == DOLBRACE_PARAM)
1608 {
1609 si = skipsubscript (string, i, 0);
1610 CHECK_STRING_OVERRUN (i, si, slen, c);
1611 if (string[si] == RBRACK)
1612 c = string[i = si];
1613 }
1614 #endif
1615
1616 /* move past this character, which was not special. */
1617 ADVANCE_CHAR (string, slen, i);
1618
1619 /* This logic must agree with parse.y:parse_matched_pair, since they
1620 share the same defines. */
1621 if (dolbrace_state == DOLBRACE_PARAM && c == '%' && (i - *sindex) > 1)
1622 dolbrace_state = DOLBRACE_QUOTE;
1623 else if (dolbrace_state == DOLBRACE_PARAM && c == '#' && (i - *sindex) > 1)
1624 dolbrace_state = DOLBRACE_QUOTE;
1625 else if (dolbrace_state == DOLBRACE_PARAM && c == '/' && (i - *sindex) > 1)
1626 dolbrace_state = DOLBRACE_QUOTE2; /* XXX */
1627 else if (dolbrace_state == DOLBRACE_PARAM && c == '^' && (i - *sindex) > 1)
1628 dolbrace_state = DOLBRACE_QUOTE;
1629 else if (dolbrace_state == DOLBRACE_PARAM && c == ',' && (i - *sindex) > 1)
1630 dolbrace_state = DOLBRACE_QUOTE;
1631 /* This is intended to handle all of the [:]op expansions and the substring/
1632 length/pattern removal/pattern substitution expansions. */
1633 else if (dolbrace_state == DOLBRACE_PARAM && strchr ("#%^,~:-=?+/", c) != 0)
1634 dolbrace_state = DOLBRACE_OP;
1635 else if (dolbrace_state == DOLBRACE_OP && strchr ("#%^,~:-=?+/", c) == 0)
1636 dolbrace_state = DOLBRACE_WORD;
1637 }
1638
1639 if (c == 0 && nesting_level)
1640 {
1641 if (no_longjmp_on_fatal_error == 0)
1642 { /* { */
1643 last_command_exit_value = EXECUTION_FAILURE;
1644 report_error (_("bad substitution: no closing `%s' in %s"), "}", string);
1645 exp_jump_to_top_level (DISCARD);
1646 }
1647 else
1648 {
1649 *sindex = i;
1650 return ((char *)NULL);
1651 }
1652 }
1653
1654 result = (flags & SX_NOALLOC) ? (char *)NULL : substring (string, *sindex, i);
1655 *sindex = i;
1656
1657 return (result);
1658 }
1659
1660 /* Remove backslashes which are quoting backquotes from STRING. Modifies
1661 STRING, and returns a pointer to it. */
1662 char *
1663 de_backslash (string)
1664 char *string;
1665 {
1666 register size_t slen;
1667 register int i, j, prev_i;
1668 DECLARE_MBSTATE;
1669
1670 slen = strlen (string);
1671 i = j = 0;
1672
1673 /* Loop copying string[i] to string[j], i >= j. */
1674 while (i < slen)
1675 {
1676 if (string[i] == '\\' && (string[i + 1] == '`' || string[i + 1] == '\\' ||
1677 string[i + 1] == '$'))
1678 i++;
1679 prev_i = i;
1680 ADVANCE_CHAR (string, slen, i);
1681 if (j < prev_i)
1682 do string[j++] = string[prev_i++]; while (prev_i < i);
1683 else
1684 j = i;
1685 }
1686 string[j] = '\0';
1687
1688 return (string);
1689 }
1690
1691 #if 0
1692 /*UNUSED*/
1693 /* Replace instances of \! in a string with !. */
1694 void
1695 unquote_bang (string)
1696 char *string;
1697 {
1698 register int i, j;
1699 register char *temp;
1700
1701 temp = (char *)xmalloc (1 + strlen (string));
1702
1703 for (i = 0, j = 0; (temp[j] = string[i]); i++, j++)
1704 {
1705 if (string[i] == '\\' && string[i + 1] == '!')
1706 {
1707 temp[j] = '!';
1708 i++;
1709 }
1710 }
1711 strcpy (string, temp);
1712 free (temp);
1713 }
1714 #endif
1715
1716 #define CQ_RETURN(x) do { no_longjmp_on_fatal_error = oldjmp; return (x); } while (0)
1717
1718 /* This function assumes s[i] == open; returns with s[ret] == close; used to
1719 parse array subscripts. FLAGS & 1 means to not attempt to skip over
1720 matched pairs of quotes or backquotes, or skip word expansions; it is
1721 intended to be used after expansion has been performed and during final
1722 assignment parsing (see arrayfunc.c:assign_compound_array_list()) or
1723 during execution by a builtin which has already undergone word expansion. */
1724 static int
1725 skip_matched_pair (string, start, open, close, flags)
1726 const char *string;
1727 int start, open, close, flags;
1728 {
1729 int i, pass_next, backq, si, c, count, oldjmp;
1730 size_t slen;
1731 char *temp, *ss;
1732 DECLARE_MBSTATE;
1733
1734 slen = strlen (string + start) + start;
1735 oldjmp = no_longjmp_on_fatal_error;
1736 no_longjmp_on_fatal_error = 1;
1737
1738 i = start + 1; /* skip over leading bracket */
1739 count = 1;
1740 pass_next = backq = 0;
1741 ss = (char *)string;
1742 while (c = string[i])
1743 {
1744 if (pass_next)
1745 {
1746 pass_next = 0;
1747 if (c == 0)
1748 CQ_RETURN(i);
1749 ADVANCE_CHAR (string, slen, i);
1750 continue;
1751 }
1752 else if ((flags & 1) == 0 && c == '\\')
1753 {
1754 pass_next = 1;
1755 i++;
1756 continue;
1757 }
1758 else if (backq)
1759 {
1760 if (c == '`')
1761 backq = 0;
1762 ADVANCE_CHAR (string, slen, i);
1763 continue;
1764 }
1765 else if ((flags & 1) == 0 && c == '`')
1766 {
1767 backq = 1;
1768 i++;
1769 continue;
1770 }
1771 else if ((flags & 1) == 0 && c == open)
1772 {
1773 count++;
1774 i++;
1775 continue;
1776 }
1777 else if (c == close)
1778 {
1779 count--;
1780 if (count == 0)
1781 break;
1782 i++;
1783 continue;
1784 }
1785 else if ((flags & 1) == 0 && (c == '\'' || c == '"'))
1786 {
1787 i = (c == '\'') ? skip_single_quoted (ss, slen, ++i, 0)
1788 : skip_double_quoted (ss, slen, ++i, 0);
1789 /* no increment, the skip functions increment past the closing quote. */
1790 }
1791 else if ((flags&1) == 0 && c == '$' && (string[i+1] == LPAREN || string[i+1] == LBRACE))
1792 {
1793 si = i + 2;
1794 if (string[si] == '\0')
1795 CQ_RETURN(si);
1796
1797 /* XXX - extract_command_subst here? */
1798 if (string[i+1] == LPAREN)
1799 temp = extract_delimited_string (ss, &si, "$(", "(", ")", SX_NOALLOC|SX_COMMAND); /* ) */
1800 else
1801 temp = extract_dollar_brace_string (ss, &si, 0, SX_NOALLOC);
1802
1803 CHECK_STRING_OVERRUN (i, si, slen, c);
1804
1805 i = si;
1806 if (string[i] == '\0') /* don't increment i past EOS in loop */
1807 break;
1808 i++;
1809 continue;
1810 }
1811 else
1812 ADVANCE_CHAR (string, slen, i);
1813 }
1814
1815 CQ_RETURN(i);
1816 }
1817
1818 #if defined (ARRAY_VARS)
1819 /* Flags has 1 as a reserved value, since skip_matched_pair uses it for
1820 skipping over quoted strings and taking the first instance of the
1821 closing character. */
1822 int
1823 skipsubscript (string, start, flags)
1824 const char *string;
1825 int start, flags;
1826 {
1827 return (skip_matched_pair (string, start, '[', ']', flags));
1828 }
1829 #endif
1830
1831 /* Skip characters in STRING until we find a character in DELIMS, and return
1832 the index of that character. START is the index into string at which we
1833 begin. This is similar in spirit to strpbrk, but it returns an index into
1834 STRING and takes a starting index. This little piece of code knows quite
1835 a lot of shell syntax. It's very similar to skip_double_quoted and other
1836 functions of that ilk. */
1837 int
1838 skip_to_delim (string, start, delims, flags)
1839 char *string;
1840 int start;
1841 char *delims;
1842 int flags;
1843 {
1844 int i, pass_next, backq, dquote, si, c, oldjmp;
1845 int invert, skipquote, skipcmd, noprocsub, completeflag;
1846 int arithexp, skipcol;
1847 size_t slen;
1848 char *temp, open[3];
1849 DECLARE_MBSTATE;
1850
1851 slen = strlen (string + start) + start;
1852 oldjmp = no_longjmp_on_fatal_error;
1853 if (flags & SD_NOJMP)
1854 no_longjmp_on_fatal_error = 1;
1855 invert = (flags & SD_INVERT);
1856 skipcmd = (flags & SD_NOSKIPCMD) == 0;
1857 noprocsub = (flags & SD_NOPROCSUB);
1858 completeflag = (flags & SD_COMPLETE) ? SX_COMPLETE : 0;
1859
1860 arithexp = (flags & SD_ARITHEXP);
1861 skipcol = 0;
1862
1863 i = start;
1864 pass_next = backq = dquote = 0;
1865 while (c = string[i])
1866 {
1867 /* If this is non-zero, we should not let quote characters be delimiters
1868 and the current character is a single or double quote. We should not
1869 test whether or not it's a delimiter until after we skip single- or
1870 double-quoted strings. */
1871 skipquote = ((flags & SD_NOQUOTEDELIM) && (c == '\'' || c =='"'));
1872 if (pass_next)
1873 {
1874 pass_next = 0;
1875 if (c == 0)
1876 CQ_RETURN(i);
1877 ADVANCE_CHAR (string, slen, i);
1878 continue;
1879 }
1880 else if (c == '\\')
1881 {
1882 pass_next = 1;
1883 i++;
1884 continue;
1885 }
1886 else if (backq)
1887 {
1888 if (c == '`')
1889 backq = 0;
1890 ADVANCE_CHAR (string, slen, i);
1891 continue;
1892 }
1893 else if (c == '`')
1894 {
1895 backq = 1;
1896 i++;
1897 continue;
1898 }
1899 else if (arithexp && skipcol && c == ':')
1900 {
1901 skipcol--;
1902 i++;
1903 continue;
1904 }
1905 else if (arithexp && c == '?')
1906 {
1907 skipcol++;
1908 i++;
1909 continue;
1910 }
1911 else if (skipquote == 0 && invert == 0 && member (c, delims))
1912 break;
1913 /* the usual case is to use skip_xxx_quoted, but we don't skip over double
1914 quoted strings when looking for the history expansion character as a
1915 delimiter. */
1916 /* special case for programmable completion which takes place before
1917 parser converts backslash-escaped single quotes between $'...' to
1918 `regular' single-quoted strings. */
1919 else if (completeflag && i > 0 && string[i-1] == '$' && c == '\'')
1920 i = skip_single_quoted (string, slen, ++i, SX_COMPLETE);
1921 else if (c == '\'')
1922 i = skip_single_quoted (string, slen, ++i, 0);
1923 else if (c == '"')
1924 i = skip_double_quoted (string, slen, ++i, completeflag);
1925 else if (c == LPAREN && arithexp)
1926 {
1927 si = i + 1;
1928 if (string[si] == '\0')
1929 CQ_RETURN(si);
1930
1931 temp = extract_delimited_string (string, &si, "(", "(", ")", SX_NOALLOC); /* ) */
1932 i = si;
1933 if (string[i] == '\0') /* don't increment i past EOS in loop */
1934 break;
1935 i++;
1936 continue;
1937 }
1938 else if (c == '$' && ((skipcmd && string[i+1] == LPAREN) || string[i+1] == LBRACE))
1939 {
1940 si = i + 2;
1941 if (string[si] == '\0')
1942 CQ_RETURN(si);
1943
1944 if (string[i+1] == LPAREN)
1945 temp = extract_delimited_string (string, &si, "$(", "(", ")", SX_NOALLOC|SX_COMMAND); /* ) */
1946 else
1947 temp = extract_dollar_brace_string (string, &si, 0, SX_NOALLOC);
1948 CHECK_STRING_OVERRUN (i, si, slen, c);
1949 i = si;
1950 if (string[i] == '\0') /* don't increment i past EOS in loop */
1951 break;
1952 i++;
1953 continue;
1954 }
1955 #if defined (PROCESS_SUBSTITUTION)
1956 else if (skipcmd && noprocsub == 0 && (c == '<' || c == '>') && string[i+1] == LPAREN)
1957 {
1958 si = i + 2;
1959 if (string[si] == '\0')
1960 CQ_RETURN(si);
1961
1962 temp = extract_delimited_string (string, &si, (c == '<') ? "<(" : ">(", "(", ")", SX_COMMAND|SX_NOALLOC); /* )) */
1963 CHECK_STRING_OVERRUN (i, si, slen, c);
1964 i = si;
1965 if (string[i] == '\0')
1966 break;
1967 i++;
1968 continue;
1969 }
1970 #endif /* PROCESS_SUBSTITUTION */
1971 #if defined (EXTENDED_GLOB)
1972 else if ((flags & SD_EXTGLOB) && extended_glob && string[i+1] == LPAREN && member (c, "?*+!@"))
1973 {
1974 si = i + 2;
1975 if (string[si] == '\0')
1976 CQ_RETURN(si);
1977
1978 open[0] = c;
1979 open[1] = LPAREN;
1980 open[2] = '\0';
1981 temp = extract_delimited_string (string, &si, open, "(", ")", SX_NOALLOC); /* ) */
1982
1983 CHECK_STRING_OVERRUN (i, si, slen, c);
1984 i = si;
1985 if (string[i] == '\0') /* don't increment i past EOS in loop */
1986 break;
1987 i++;
1988 continue;
1989 }
1990 #endif
1991 else if ((flags & SD_GLOB) && c == LBRACK)
1992 {
1993 si = i + 1;
1994 if (string[si] == '\0')
1995 CQ_RETURN(si);
1996
1997 temp = extract_delimited_string (string, &si, "[", "[", "]", SX_NOALLOC); /* ] */
1998
1999 i = si;
2000 if (string[i] == '\0') /* don't increment i past EOS in loop */
2001 break;
2002 i++;
2003 continue;
2004 }
2005 else if ((skipquote || invert) && (member (c, delims) == 0))
2006 break;
2007 else
2008 ADVANCE_CHAR (string, slen, i);
2009 }
2010
2011 CQ_RETURN(i);
2012 }
2013
2014 #if defined (BANG_HISTORY)
2015 /* Skip to the history expansion character (delims[0]), paying attention to
2016 quoted strings and command and process substitution. This is a stripped-
2017 down version of skip_to_delims. The essential difference is that this
2018 resets the quoting state when starting a command substitution */
2019 int
2020 skip_to_histexp (string, start, delims, flags)
2021 char *string;
2022 int start;
2023 char *delims;
2024 int flags;
2025 {
2026 int i, pass_next, backq, dquote, c, oldjmp;
2027 int histexp_comsub, histexp_backq, old_dquote;
2028 size_t slen;
2029 DECLARE_MBSTATE;
2030
2031 slen = strlen (string + start) + start;
2032 oldjmp = no_longjmp_on_fatal_error;
2033 if (flags & SD_NOJMP)
2034 no_longjmp_on_fatal_error = 1;
2035
2036 histexp_comsub = histexp_backq = old_dquote = 0;
2037
2038 i = start;
2039 pass_next = backq = dquote = 0;
2040 while (c = string[i])
2041 {
2042 if (pass_next)
2043 {
2044 pass_next = 0;
2045 if (c == 0)
2046 CQ_RETURN(i);
2047 ADVANCE_CHAR (string, slen, i);
2048 continue;
2049 }
2050 else if (c == '\\')
2051 {
2052 pass_next = 1;
2053 i++;
2054 continue;
2055 }
2056 else if (backq && c == '`')
2057 {
2058 backq = 0;
2059 histexp_backq--;
2060 dquote = old_dquote;
2061 i++;
2062 continue;
2063 }
2064 else if (c == '`')
2065 {
2066 backq = 1;
2067 histexp_backq++;
2068 old_dquote = dquote; /* simple - one level for now */
2069 dquote = 0;
2070 i++;
2071 continue;
2072 }
2073 /* When in double quotes, act as if the double quote is a member of
2074 history_no_expand_chars, like the history library does */
2075 else if (dquote && c == delims[0] && string[i+1] == '"')
2076 {
2077 i++;
2078 continue;
2079 }
2080 else if (c == delims[0])
2081 break;
2082 /* the usual case is to use skip_xxx_quoted, but we don't skip over double
2083 quoted strings when looking for the history expansion character as a
2084 delimiter. */
2085 else if (dquote && c == '\'')
2086 {
2087 i++;
2088 continue;
2089 }
2090 else if (c == '\'')
2091 i = skip_single_quoted (string, slen, ++i, 0);
2092 /* The posixly_correct test makes posix-mode shells allow double quotes
2093 to quote the history expansion character */
2094 else if (posixly_correct == 0 && c == '"')
2095 {
2096 dquote = 1 - dquote;
2097 i++;
2098 continue;
2099 }
2100 else if (c == '"')
2101 i = skip_double_quoted (string, slen, ++i, 0);
2102 #if defined (PROCESS_SUBSTITUTION)
2103 else if ((c == '$' || c == '<' || c == '>') && string[i+1] == LPAREN && string[i+2] != LPAREN)
2104 #else
2105 else if (c == '$' && string[i+1] == LPAREN && string[i+2] != LPAREN)
2106 #endif
2107 {
2108 if (string[i+2] == '\0')
2109 CQ_RETURN(i+2);
2110 i += 2;
2111 histexp_comsub++;
2112 old_dquote = dquote;
2113 dquote = 0;
2114 }
2115 else if (histexp_comsub && c == RPAREN)
2116 {
2117 histexp_comsub--;
2118 dquote = old_dquote;
2119 i++;
2120 continue;
2121 }
2122 else if (backq) /* placeholder */
2123 {
2124 ADVANCE_CHAR (string, slen, i);
2125 continue;
2126 }
2127 else
2128 ADVANCE_CHAR (string, slen, i);
2129 }
2130
2131 CQ_RETURN(i);
2132 }
2133 #endif /* BANG_HISTORY */
2134
2135 #if defined (READLINE)
2136 /* Return 1 if the portion of STRING ending at EINDEX is quoted (there is
2137 an unclosed quoted string), or if the character at EINDEX is quoted
2138 by a backslash. NO_LONGJMP_ON_FATAL_ERROR is used to flag that the various
2139 single and double-quoted string parsing functions should not return an
2140 error if there are unclosed quotes or braces. The characters that this
2141 recognizes need to be the same as the contents of
2142 rl_completer_quote_characters. */
2143
2144 int
2145 char_is_quoted (string, eindex)
2146 char *string;
2147 int eindex;
2148 {
2149 int i, pass_next, c, oldjmp;
2150 size_t slen;
2151 DECLARE_MBSTATE;
2152
2153 slen = strlen (string);
2154 oldjmp = no_longjmp_on_fatal_error;
2155 no_longjmp_on_fatal_error = 1;
2156 i = pass_next = 0;
2157 while (i <= eindex)
2158 {
2159 c = string[i];
2160
2161 if (pass_next)
2162 {
2163 pass_next = 0;
2164 if (i >= eindex) /* XXX was if (i >= eindex - 1) */
2165 CQ_RETURN(1);
2166 ADVANCE_CHAR (string, slen, i);
2167 continue;
2168 }
2169 else if (c == '\\')
2170 {
2171 pass_next = 1;
2172 i++;
2173 continue;
2174 }
2175 else if (c == '$' && string[i+1] == '\'' && string[i+2])
2176 {
2177 i += 2;
2178 i = skip_single_quoted (string, slen, i, SX_COMPLETE);
2179 if (i > eindex)
2180 CQ_RETURN (i);
2181 }
2182 else if (c == '\'' || c == '"')
2183 {
2184 i = (c == '\'') ? skip_single_quoted (string, slen, ++i, 0)
2185 : skip_double_quoted (string, slen, ++i, SX_COMPLETE);
2186 if (i > eindex)
2187 CQ_RETURN(1);
2188 /* no increment, the skip_xxx functions go one past end */
2189 }
2190 else
2191 ADVANCE_CHAR (string, slen, i);
2192 }
2193
2194 CQ_RETURN(0);
2195 }
2196
2197 int
2198 unclosed_pair (string, eindex, openstr)
2199 char *string;
2200 int eindex;
2201 char *openstr;
2202 {
2203 int i, pass_next, openc, olen;
2204 size_t slen;
2205 DECLARE_MBSTATE;
2206
2207 slen = strlen (string);
2208 olen = strlen (openstr);
2209 i = pass_next = openc = 0;
2210 while (i <= eindex)
2211 {
2212 if (pass_next)
2213 {
2214 pass_next = 0;
2215 if (i >= eindex) /* XXX was if (i >= eindex - 1) */
2216 return 0;
2217 ADVANCE_CHAR (string, slen, i);
2218 continue;
2219 }
2220 else if (string[i] == '\\')
2221 {
2222 pass_next = 1;
2223 i++;
2224 continue;
2225 }
2226 else if (STREQN (string + i, openstr, olen))
2227 {
2228 openc = 1 - openc;
2229 i += olen;
2230 }
2231 /* XXX - may want to handle $'...' specially here */
2232 else if (string[i] == '\'' || string[i] == '"')
2233 {
2234 i = (string[i] == '\'') ? skip_single_quoted (string, slen, i, 0)
2235 : skip_double_quoted (string, slen, i, SX_COMPLETE);
2236 if (i > eindex)
2237 return 0;
2238 }
2239 else
2240 ADVANCE_CHAR (string, slen, i);
2241 }
2242 return (openc);
2243 }
2244
2245 /* Split STRING (length SLEN) at DELIMS, and return a WORD_LIST with the
2246 individual words. If DELIMS is NULL, the current value of $IFS is used
2247 to split the string, and the function follows the shell field splitting
2248 rules. SENTINEL is an index to look for. NWP, if non-NULL,
2249 gets the number of words in the returned list. CWP, if non-NULL, gets
2250 the index of the word containing SENTINEL. Non-whitespace chars in
2251 DELIMS delimit separate fields. This is used by programmable completion. */
2252 WORD_LIST *
2253 split_at_delims (string, slen, delims, sentinel, flags, nwp, cwp)
2254 char *string;
2255 int slen;
2256 char *delims;
2257 int sentinel, flags;
2258 int *nwp, *cwp;
2259 {
2260 int ts, te, i, nw, cw, ifs_split, dflags;
2261 char *token, *d, *d2;
2262 WORD_LIST *ret, *tl;
2263
2264 if (string == 0 || *string == '\0')
2265 {
2266 if (nwp)
2267 *nwp = 0;
2268 if (cwp)
2269 *cwp = 0;
2270 return ((WORD_LIST *)NULL);
2271 }
2272
2273 d = (delims == 0) ? ifs_value : delims;
2274 ifs_split = delims == 0;
2275
2276 /* Make d2 the non-whitespace characters in delims */
2277 d2 = 0;
2278 if (delims)
2279 {
2280 size_t slength;
2281 #if defined (HANDLE_MULTIBYTE)
2282 size_t mblength = 1;
2283 #endif
2284 DECLARE_MBSTATE;
2285
2286 slength = strlen (delims);
2287 d2 = (char *)xmalloc (slength + 1);
2288 i = ts = 0;
2289 while (delims[i])
2290 {
2291 #if defined (HANDLE_MULTIBYTE)
2292 mbstate_t state_bak;
2293 state_bak = state;
2294 mblength = MBRLEN (delims + i, slength, &state);
2295 if (MB_INVALIDCH (mblength))
2296 state = state_bak;
2297 else if (mblength > 1)
2298 {
2299 memcpy (d2 + ts, delims + i, mblength);
2300 ts += mblength;
2301 i += mblength;
2302 slength -= mblength;
2303 continue;
2304 }
2305 #endif
2306 if (whitespace (delims[i]) == 0)
2307 d2[ts++] = delims[i];
2308
2309 i++;
2310 slength--;
2311 }
2312 d2[ts] = '\0';
2313 }
2314
2315 ret = (WORD_LIST *)NULL;
2316
2317 /* Remove sequences of whitespace characters at the start of the string, as
2318 long as those characters are delimiters. */
2319 for (i = 0; member (string[i], d) && spctabnl (string[i]); i++)
2320 ;
2321 if (string[i] == '\0')
2322 {
2323 FREE (d2);
2324 return (ret);
2325 }
2326
2327 ts = i;
2328 nw = 0;
2329 cw = -1;
2330 dflags = flags|SD_NOJMP;
2331 while (1)
2332 {
2333 te = skip_to_delim (string, ts, d, dflags);
2334
2335 /* If we have a non-whitespace delimiter character, use it to make a
2336 separate field. This is just about what $IFS splitting does and
2337 is closer to the behavior of the shell parser. */
2338 if (ts == te && d2 && member (string[ts], d2))
2339 {
2340 te = ts + 1;
2341 /* If we're using IFS splitting, the non-whitespace delimiter char
2342 and any additional IFS whitespace delimits a field. */
2343 if (ifs_split)
2344 while (member (string[te], d) && spctabnl (string[te]) && ((flags&SD_NOQUOTEDELIM) == 0 || (string[te] != '\'' && string[te] != '"')))
2345 te++;
2346 else
2347 while (member (string[te], d2) && ((flags&SD_NOQUOTEDELIM) == 0 || (string[te] != '\'' && string[te] != '"')))
2348 te++;
2349 }
2350
2351 token = substring (string, ts, te);
2352
2353 ret = add_string_to_list (token, ret);
2354 free (token);
2355 nw++;
2356
2357 if (sentinel >= ts && sentinel <= te)
2358 cw = nw;
2359
2360 /* If the cursor is at whitespace just before word start, set the
2361 sentinel word to the current word. */
2362 if (cwp && cw == -1 && sentinel == ts-1)
2363 cw = nw;
2364
2365 /* If the cursor is at whitespace between two words, make a new, empty
2366 word, add it before (well, after, since the list is in reverse order)
2367 the word we just added, and set the current word to that one. */
2368 if (cwp && cw == -1 && sentinel < ts)
2369 {
2370 tl = make_word_list (make_word (""), ret->next);
2371 ret->next = tl;
2372 cw = nw;
2373 nw++;
2374 }
2375
2376 if (string[te] == 0)
2377 break;
2378
2379 i = te;
2380 /* XXX - honor SD_NOQUOTEDELIM here */
2381 while (member (string[i], d) && (ifs_split || spctabnl(string[i])) && ((flags&SD_NOQUOTEDELIM) == 0 || (string[te] != '\'' && string[te] != '"')))
2382 i++;
2383
2384 if (string[i])
2385 ts = i;
2386 else
2387 break;
2388 }
2389
2390 /* Special case for SENTINEL at the end of STRING. If we haven't found
2391 the word containing SENTINEL yet, and the index we're looking for is at
2392 the end of STRING (or past the end of the previously-found token,
2393 possible if the end of the line is composed solely of IFS whitespace)
2394 add an additional null argument and set the current word pointer to that. */
2395 if (cwp && cw == -1 && (sentinel >= slen || sentinel >= te))
2396 {
2397 if (whitespace (string[sentinel - 1]))
2398 {
2399 token = "";
2400 ret = add_string_to_list (token, ret);
2401 nw++;
2402 }
2403 cw = nw;
2404 }
2405
2406 if (nwp)
2407 *nwp = nw;
2408 if (cwp)
2409 *cwp = cw;
2410
2411 FREE (d2);
2412
2413 return (REVERSE_LIST (ret, WORD_LIST *));
2414 }
2415 #endif /* READLINE */
2416
2417 #if 0
2418 /* UNUSED */
2419 /* Extract the name of the variable to bind to from the assignment string. */
2420 char *
2421 assignment_name (string)
2422 char *string;
2423 {
2424 int offset;
2425 char *temp;
2426
2427 offset = assignment (string, 0);
2428 if (offset == 0)
2429 return (char *)NULL;
2430 temp = substring (string, 0, offset);
2431 return (temp);
2432 }
2433 #endif
2434
2435 /* **************************************************************** */
2436 /* */
2437 /* Functions to convert strings to WORD_LISTs and vice versa */
2438 /* */
2439 /* **************************************************************** */
2440
2441 /* Return a single string of all the words in LIST. SEP is the separator
2442 to put between individual elements of LIST in the output string. */
2443 char *
2444 string_list_internal (list, sep)
2445 WORD_LIST *list;
2446 char *sep;
2447 {
2448 register WORD_LIST *t;
2449 char *result, *r;
2450 size_t word_len, sep_len, result_size;
2451
2452 if (list == 0)
2453 return ((char *)NULL);
2454
2455 /* Short-circuit quickly if we don't need to separate anything. */
2456 if (list->next == 0)
2457 return (savestring (list->word->word));
2458
2459 /* This is nearly always called with either sep[0] == 0 or sep[1] == 0. */
2460 sep_len = STRLEN (sep);
2461 result_size = 0;
2462
2463 for (t = list; t; t = t->next)
2464 {
2465 if (t != list)
2466 result_size += sep_len;
2467 result_size += strlen (t->word->word);
2468 }
2469
2470 r = result = (char *)xmalloc (result_size + 1);
2471
2472 for (t = list; t; t = t->next)
2473 {
2474 if (t != list && sep_len)
2475 {
2476 if (sep_len > 1)
2477 {
2478 FASTCOPY (sep, r, sep_len);
2479 r += sep_len;
2480 }
2481 else
2482 *r++ = sep[0];
2483 }
2484
2485 word_len = strlen (t->word->word);
2486 FASTCOPY (t->word->word, r, word_len);
2487 r += word_len;
2488 }
2489
2490 *r = '\0';
2491 return (result);
2492 }
2493
2494 /* Return a single string of all the words present in LIST, separating
2495 each word with a space. */
2496 char *
2497 string_list (list)
2498 WORD_LIST *list;
2499 {
2500 return (string_list_internal (list, " "));
2501 }
2502
2503 /* An external interface that can be used by the rest of the shell to
2504 obtain a string containing the first character in $IFS. Handles all
2505 the multibyte complications. If LENP is non-null, it is set to the
2506 length of the returned string. */
2507 char *
2508 ifs_firstchar (lenp)
2509 int *lenp;
2510 {
2511 char *ret;
2512 int len;
2513
2514 ret = xmalloc (MB_LEN_MAX + 1);
2515 #if defined (HANDLE_MULTIBYTE)
2516 if (ifs_firstc_len == 1)
2517 {
2518 ret[0] = ifs_firstc[0];
2519 ret[1] = '\0';
2520 len = ret[0] ? 1 : 0;
2521 }
2522 else
2523 {
2524 memcpy (ret, ifs_firstc, ifs_firstc_len);
2525 ret[len = ifs_firstc_len] = '\0';
2526 }
2527 #else
2528 ret[0] = ifs_firstc;
2529 ret[1] = '\0';
2530 len = ret[0] ? 0 : 1;
2531 #endif
2532
2533 if (lenp)
2534 *lenp = len;
2535
2536 return ret;
2537 }
2538
2539 /* Return a single string of all the words present in LIST, obeying the
2540 quoting rules for "$*", to wit: (P1003.2, draft 11, 3.5.2) "If the
2541 expansion [of $*] appears within a double quoted string, it expands
2542 to a single field with the value of each parameter separated by the
2543 first character of the IFS variable, or by a <space> if IFS is unset." */
2544 /* Posix interpretation 888 changes this when IFS is null by specifying
2545 that when unquoted, this expands to separate arguments */
2546 char *
2547 string_list_dollar_star (list, quoted, flags)
2548 WORD_LIST *list;
2549 int quoted, flags;
2550 {
2551 char *ret;
2552 #if defined (HANDLE_MULTIBYTE)
2553 # if defined (__GNUC__)
2554 char sep[MB_CUR_MAX + 1];
2555 # else
2556 char *sep = 0;
2557 # endif
2558 #else
2559 char sep[2];
2560 #endif
2561
2562 #if defined (HANDLE_MULTIBYTE)
2563 # if !defined (__GNUC__)
2564 sep = (char *)xmalloc (MB_CUR_MAX + 1);
2565 # endif /* !__GNUC__ */
2566 if (ifs_firstc_len == 1)
2567 {
2568 sep[0] = ifs_firstc[0];
2569 sep[1] = '\0';
2570 }
2571 else
2572 {
2573 memcpy (sep, ifs_firstc, ifs_firstc_len);
2574 sep[ifs_firstc_len] = '\0';
2575 }
2576 #else
2577 sep[0] = ifs_firstc;
2578 sep[1] = '\0';
2579 #endif
2580
2581 ret = string_list_internal (list, sep);
2582 #if defined (HANDLE_MULTIBYTE) && !defined (__GNUC__)
2583 free (sep);
2584 #endif
2585 return ret;
2586 }
2587
2588 /* Turn $@ into a string. If (quoted & (Q_HERE_DOCUMENT|Q_DOUBLE_QUOTES))
2589 is non-zero, the $@ appears within double quotes, and we should quote
2590 the list before converting it into a string. If IFS is unset, and the
2591 word is not quoted, we just need to quote CTLESC and CTLNUL characters
2592 in the words in the list, because the default value of $IFS is
2593 <space><tab><newline>, IFS characters in the words in the list should
2594 also be split. If IFS is null, and the word is not quoted, we need
2595 to quote the words in the list to preserve the positional parameters
2596 exactly.
2597 Valid values for the FLAGS argument are the PF_ flags in command.h,
2598 the only one we care about is PF_ASSIGNRHS. $@ is supposed to expand
2599 to the positional parameters separated by spaces no matter what IFS is
2600 set to if in a context where word splitting is not performed. The only
2601 one that we didn't handle before is assignment statement arguments to
2602 declaration builtins like `declare'. */
2603 char *
2604 string_list_dollar_at (list, quoted, flags)
2605 WORD_LIST *list;
2606 int quoted;
2607 int flags;
2608 {
2609 char *ifs, *ret;
2610 #if defined (HANDLE_MULTIBYTE)
2611 # if defined (__GNUC__)
2612 char sep[MB_CUR_MAX + 1];
2613 # else
2614 char *sep = 0;
2615 # endif /* !__GNUC__ */
2616 #else
2617 char sep[2];
2618 #endif
2619 WORD_LIST *tlist;
2620
2621 /* XXX this could just be ifs = ifs_value; */
2622 ifs = ifs_var ? value_cell (ifs_var) : (char *)0;
2623
2624 #if defined (HANDLE_MULTIBYTE)
2625 # if !defined (__GNUC__)
2626 sep = (char *)xmalloc (MB_CUR_MAX + 1);
2627 # endif /* !__GNUC__ */
2628 /* XXX - testing PF_ASSIGNRHS to make sure positional parameters are
2629 separated with a space even when word splitting will not occur. */
2630 if (flags & PF_ASSIGNRHS)
2631 {
2632 sep[0] = ' ';
2633 sep[1] = '\0';
2634 }
2635 else if (ifs && *ifs)
2636 {
2637 if (ifs_firstc_len == 1)
2638 {
2639 sep[0] = ifs_firstc[0];
2640 sep[1] = '\0';
2641 }
2642 else
2643 {
2644 memcpy (sep, ifs_firstc, ifs_firstc_len);
2645 sep[ifs_firstc_len] = '\0';
2646 }
2647 }
2648 else
2649 {
2650 sep[0] = ' ';
2651 sep[1] = '\0';
2652 }
2653 #else /* !HANDLE_MULTIBYTE */
2654 /* XXX - PF_ASSIGNRHS means no word splitting, so we want positional
2655 parameters separated by a space. */
2656 sep[0] = ((flags & PF_ASSIGNRHS) || ifs == 0 || *ifs == 0) ? ' ' : *ifs;
2657 sep[1] = '\0';
2658 #endif /* !HANDLE_MULTIBYTE */
2659
2660 /* XXX -- why call quote_list if ifs == 0? we can get away without doing
2661 it now that quote_escapes quotes spaces */
2662 tlist = (quoted & (Q_HERE_DOCUMENT|Q_DOUBLE_QUOTES|Q_PATQUOTE))
2663 ? quote_list (list)
2664 : list_quote_escapes (list);
2665
2666 ret = string_list_internal (tlist, sep);
2667 #if defined (HANDLE_MULTIBYTE) && !defined (__GNUC__)
2668 free (sep);
2669 #endif
2670 return ret;
2671 }
2672
2673 /* Turn the positional parameters into a string, understanding quoting and
2674 the various subtleties of using the first character of $IFS as the
2675 separator. Calls string_list_dollar_at, string_list_dollar_star, and
2676 string_list as appropriate. */
2677 char *
2678 string_list_pos_params (pchar, list, quoted)
2679 int pchar;
2680 WORD_LIST *list;
2681 int quoted;
2682 {
2683 char *ret;
2684 WORD_LIST *tlist;
2685
2686 if (pchar == '*' && (quoted & Q_DOUBLE_QUOTES))
2687 {
2688 tlist = quote_list (list);
2689 word_list_remove_quoted_nulls (tlist);
2690 ret = string_list_dollar_star (tlist, 0, 0);
2691 }
2692 else if (pchar == '*' && (quoted & Q_HERE_DOCUMENT))
2693 {
2694 tlist = quote_list (list);
2695 word_list_remove_quoted_nulls (tlist);
2696 ret = string_list (tlist);
2697 }
2698 else if (pchar == '*' && quoted == 0 && ifs_is_null) /* XXX */
2699 ret = expand_no_split_dollar_star ? string_list_dollar_star (list, quoted, 0) : string_list_dollar_at (list, quoted, 0); /* Posix interp 888 */
2700 else if (pchar == '*')
2701 {
2702 /* Even when unquoted, string_list_dollar_star does the right thing
2703 making sure that the first character of $IFS is used as the
2704 separator. */
2705 ret = string_list_dollar_star (list, quoted, 0);
2706 }
2707 else if (pchar == '@' && (quoted & (Q_HERE_DOCUMENT|Q_DOUBLE_QUOTES)))
2708 /* We use string_list_dollar_at, but only if the string is quoted, since
2709 that quotes the escapes if it's not, which we don't want. We could
2710 use string_list (the old code did), but that doesn't do the right
2711 thing if the first character of $IFS is not a space. We use
2712 string_list_dollar_star if the string is unquoted so we make sure that
2713 the elements of $@ are separated by the first character of $IFS for
2714 later splitting. */
2715 ret = string_list_dollar_at (list, quoted, 0);
2716 else if (pchar == '@' && quoted == 0 && ifs_is_null) /* XXX */
2717 ret = string_list_dollar_at (list, quoted, 0); /* Posix interp 888 */
2718 else if (pchar == '@')
2719 ret = string_list_dollar_star (list, quoted, 0);
2720 else
2721 ret = string_list ((quoted & (Q_HERE_DOCUMENT|Q_DOUBLE_QUOTES)) ? quote_list (list) : list);
2722
2723 return ret;
2724 }
2725
2726 /* Return the list of words present in STRING. Separate the string into
2727 words at any of the characters found in SEPARATORS. If QUOTED is
2728 non-zero then word in the list will have its quoted flag set, otherwise
2729 the quoted flag is left as make_word () deemed fit.
2730
2731 This obeys the P1003.2 word splitting semantics. If `separators' is
2732 exactly <space><tab><newline>, then the splitting algorithm is that of
2733 the Bourne shell, which treats any sequence of characters from `separators'
2734 as a delimiter. If IFS is unset, which results in `separators' being set
2735 to "", no splitting occurs. If separators has some other value, the
2736 following rules are applied (`IFS white space' means zero or more
2737 occurrences of <space>, <tab>, or <newline>, as long as those characters
2738 are in `separators'):
2739
2740 1) IFS white space is ignored at the start and the end of the
2741 string.
2742 2) Each occurrence of a character in `separators' that is not
2743 IFS white space, along with any adjacent occurrences of
2744 IFS white space delimits a field.
2745 3) Any nonzero-length sequence of IFS white space delimits a field.
2746 */
2747
2748 /* BEWARE! list_string strips null arguments. Don't call it twice and
2749 expect to have "" preserved! */
2750
2751 /* This performs word splitting and quoted null character removal on
2752 STRING. */
2753 #define issep(c) \
2754 (((separators)[0]) ? ((separators)[1] ? isifs(c) \
2755 : (c) == (separators)[0]) \
2756 : 0)
2757
2758 /* member of the space character class in the current locale */
2759 #define ifs_whitespace(c) ISSPACE(c)
2760
2761 /* "adjacent IFS white space" */
2762 #define ifs_whitesep(c) ((sh_style_split || separators == 0) ? spctabnl (c) \
2763 : ifs_whitespace (c))
2764
2765 WORD_LIST *
2766 list_string (string, separators, quoted)
2767 register char *string, *separators;
2768 int quoted;
2769 {
2770 WORD_LIST *result;
2771 WORD_DESC *t;
2772 char *current_word, *s;
2773 int sindex, sh_style_split, whitesep, xflags;
2774 size_t slen;
2775
2776 if (!string || !*string)
2777 return ((WORD_LIST *)NULL);
2778
2779 sh_style_split = separators && separators[0] == ' ' &&
2780 separators[1] == '\t' &&
2781 separators[2] == '\n' &&
2782 separators[3] == '\0';
2783 for (xflags = 0, s = ifs_value; s && *s; s++)
2784 {
2785 if (*s == CTLESC) xflags |= SX_NOCTLESC;
2786 else if (*s == CTLNUL) xflags |= SX_NOESCCTLNUL;
2787 }
2788
2789 slen = 0;
2790 /* Remove sequences of whitespace at the beginning of STRING, as
2791 long as those characters appear in IFS. Do not do this if
2792 STRING is quoted or if there are no separator characters. We use the
2793 Posix definition of whitespace as a member of the space character
2794 class in the current locale. */
2795 if (!quoted || !separators || !*separators)
2796 {
2797 for (s = string; *s && issep (*s) && ifs_whitespace (*s); s++);
2798
2799 if (!*s)
2800 return ((WORD_LIST *)NULL);
2801
2802 string = s;
2803 }
2804
2805 /* OK, now STRING points to a word that does not begin with white space.
2806 The splitting algorithm is:
2807 extract a word, stopping at a separator
2808 skip sequences of whitespace characters as long as they are separators
2809 This obeys the field splitting rules in Posix.2. */
2810 slen = STRLEN (string);
2811 for (result = (WORD_LIST *)NULL, sindex = 0; string[sindex]; )
2812 {
2813 /* Don't need string length in ADVANCE_CHAR unless multibyte chars are
2814 possible, but need it in string_extract_verbatim for bounds checking */
2815 current_word = string_extract_verbatim (string, slen, &sindex, separators, xflags);
2816 if (current_word == 0)
2817 break;
2818
2819 /* If we have a quoted empty string, add a quoted null argument. We
2820 want to preserve the quoted null character iff this is a quoted
2821 empty string; otherwise the quoted null characters are removed
2822 below. */
2823 if (QUOTED_NULL (current_word))
2824 {
2825 t = alloc_word_desc ();
2826 t->word = make_quoted_char ('\0');
2827 t->flags |= W_QUOTED|W_HASQUOTEDNULL;
2828 result = make_word_list (t, result);
2829 }
2830 else if (current_word[0] != '\0')
2831 {
2832 /* If we have something, then add it regardless. However,
2833 perform quoted null character removal on the current word. */
2834 remove_quoted_nulls (current_word);
2835 result = add_string_to_list (current_word, result);
2836 result->word->flags &= ~W_HASQUOTEDNULL; /* just to be sure */
2837 if (quoted & (Q_DOUBLE_QUOTES|Q_HERE_DOCUMENT))
2838 result->word->flags |= W_QUOTED;
2839 }
2840
2841 /* If we're not doing sequences of separators in the traditional
2842 Bourne shell style, then add a quoted null argument. */
2843 else if (!sh_style_split && !ifs_whitespace (string[sindex]))
2844 {
2845 t = alloc_word_desc ();
2846 t->word = make_quoted_char ('\0');
2847 t->flags |= W_QUOTED|W_HASQUOTEDNULL;
2848 result = make_word_list (t, result);
2849 }
2850
2851 free (current_word);
2852
2853 /* Note whether or not the separator is IFS whitespace, used later. */
2854 whitesep = string[sindex] && ifs_whitesep (string[sindex]);
2855
2856 /* Move past the current separator character. */
2857 if (string[sindex])
2858 {
2859 DECLARE_MBSTATE;
2860 ADVANCE_CHAR (string, slen, sindex);
2861 }
2862
2863 /* Now skip sequences of whitespace characters if they are
2864 in the list of separators. */
2865 while (string[sindex] && ifs_whitesep (string[sindex]) && issep (string[sindex]))
2866 sindex++;
2867
2868 /* If the first separator was IFS whitespace and the current character
2869 is a non-whitespace IFS character, it should be part of the current
2870 field delimiter, not a separate delimiter that would result in an
2871 empty field. Look at POSIX.2, 3.6.5, (3)(b). */
2872 if (string[sindex] && whitesep && issep (string[sindex]) && !ifs_whitesep (string[sindex]))
2873 {
2874 sindex++;
2875 /* An IFS character that is not IFS white space, along with any
2876 adjacent IFS white space, shall delimit a field. (SUSv3) */
2877 while (string[sindex] && ifs_whitesep (string[sindex]) && isifs (string[sindex]))
2878 sindex++;
2879 }
2880 }
2881 return (REVERSE_LIST (result, WORD_LIST *));
2882 }
2883
2884 /* Parse a single word from STRING, using SEPARATORS to separate fields.
2885 ENDPTR is set to the first character after the word. This is used by
2886 the `read' builtin.
2887
2888 This is never called with SEPARATORS != $IFS, and takes advantage of that.
2889
2890 XXX - this function is very similar to list_string; they should be
2891 combined - XXX */
2892
2893 /* character is in $IFS */
2894 #define islocalsep(c) (local_cmap[(unsigned char)(c)] != 0)
2895
2896 char *
2897 get_word_from_string (stringp, separators, endptr)
2898 char **stringp, *separators, **endptr;
2899 {
2900 register char *s;
2901 char *current_word;
2902 int sindex, sh_style_split, whitesep, xflags;
2903 unsigned char local_cmap[UCHAR_MAX+1]; /* really only need single-byte chars here */
2904 size_t slen;
2905
2906 if (!stringp || !*stringp || !**stringp)
2907 return ((char *)NULL);
2908
2909 sh_style_split = separators && separators[0] == ' ' &&
2910 separators[1] == '\t' &&
2911 separators[2] == '\n' &&
2912 separators[3] == '\0';
2913 memset (local_cmap, '\0', sizeof (local_cmap));
2914 for (xflags = 0, s = separators; s && *s; s++)
2915 {
2916 if (*s == CTLESC) xflags |= SX_NOCTLESC;
2917 if (*s == CTLNUL) xflags |= SX_NOESCCTLNUL;
2918 local_cmap[(unsigned char)*s] = 1; /* local charmap of separators */
2919 }
2920
2921 s = *stringp;
2922 slen = 0;
2923
2924 /* Remove sequences of whitespace at the beginning of STRING, as
2925 long as those characters appear in SEPARATORS. This happens if
2926 SEPARATORS == $' \t\n' or if IFS is unset. */
2927 if (sh_style_split || separators == 0)
2928 for (; *s && spctabnl (*s) && islocalsep (*s); s++);
2929 else
2930 for (; *s && ifs_whitespace (*s) && islocalsep (*s); s++);
2931
2932 /* If the string is nothing but whitespace, update it and return. */
2933 if (!*s)
2934 {
2935 *stringp = s;
2936 if (endptr)
2937 *endptr = s;
2938 return ((char *)NULL);
2939 }
2940
2941 /* OK, S points to a word that does not begin with white space.
2942 Now extract a word, stopping at a separator, save a pointer to
2943 the first character after the word, then skip sequences of spc,
2944 tab, or nl as long as they are separators.
2945
2946 This obeys the field splitting rules in Posix.2. */
2947 sindex = 0;
2948 /* Don't need string length in ADVANCE_CHAR unless multibyte chars are
2949 possible, but need it in string_extract_verbatim for bounds checking */
2950 slen = STRLEN (s);
2951 current_word = string_extract_verbatim (s, slen, &sindex, separators, xflags);
2952
2953 /* Set ENDPTR to the first character after the end of the word. */
2954 if (endptr)
2955 *endptr = s + sindex;
2956
2957 /* Note whether or not the separator is IFS whitespace, used later. */
2958 whitesep = s[sindex] && ifs_whitesep (s[sindex]);
2959
2960 /* Move past the current separator character. */
2961 if (s[sindex])
2962 {
2963 DECLARE_MBSTATE;
2964 ADVANCE_CHAR (s, slen, sindex);
2965 }
2966
2967 /* Now skip sequences of space, tab, or newline characters if they are
2968 in the list of separators. */
2969 while (s[sindex] && spctabnl (s[sindex]) && islocalsep (s[sindex]))
2970 sindex++;
2971
2972 /* If the first separator was IFS whitespace and the current character is
2973 a non-whitespace IFS character, it should be part of the current field
2974 delimiter, not a separate delimiter that would result in an empty field.
2975 Look at POSIX.2, 3.6.5, (3)(b). */
2976 if (s[sindex] && whitesep && islocalsep (s[sindex]) && !ifs_whitesep (s[sindex]))
2977 {
2978 sindex++;
2979 /* An IFS character that is not IFS white space, along with any adjacent
2980 IFS white space, shall delimit a field. */
2981 while (s[sindex] && ifs_whitesep (s[sindex]) && islocalsep(s[sindex]))
2982 sindex++;
2983 }
2984
2985 /* Update STRING to point to the next field. */
2986 *stringp = s + sindex;
2987 return (current_word);
2988 }
2989
2990 /* Remove IFS white space at the end of STRING. Start at the end
2991 of the string and walk backwards until the beginning of the string
2992 or we find a character that's not IFS white space and not CTLESC.
2993 Only let CTLESC escape a white space character if SAW_ESCAPE is
2994 non-zero. */
2995 char *
2996 strip_trailing_ifs_whitespace (string, separators, saw_escape)
2997 char *string, *separators;
2998 int saw_escape;
2999 {
3000 char *s;
3001
3002 s = string + STRLEN (string) - 1;
3003 while (s > string && ((spctabnl (*s) && isifs (*s)) ||
3004 (saw_escape && *s == CTLESC && spctabnl (s[1]))))
3005 s--;
3006 *++s = '\0';
3007 return string;
3008 }
3009
3010 #if 0
3011 /* UNUSED */
3012 /* Split STRING into words at whitespace. Obeys shell-style quoting with
3013 backslashes, single and double quotes. */
3014 WORD_LIST *
3015 list_string_with_quotes (string)
3016 char *string;
3017 {
3018 WORD_LIST *list;
3019 char *token, *s;
3020 size_t s_len;
3021 int c, i, tokstart, len;
3022
3023 for (s = string; s && *s && spctabnl (*s); s++)
3024 ;
3025 if (s == 0 || *s == 0)
3026 return ((WORD_LIST *)NULL);
3027
3028 s_len = strlen (s);
3029 tokstart = i = 0;
3030 list = (WORD_LIST *)NULL;
3031 while (1)
3032 {
3033 c = s[i];
3034 if (c == '\\')
3035 {
3036 i++;
3037 if (s[i])
3038 i++;
3039 }
3040 else if (c == '\'')
3041 i = skip_single_quoted (s, s_len, ++i, 0);
3042 else if (c == '"')
3043 i = skip_double_quoted (s, s_len, ++i, 0);
3044 else if (c == 0 || spctabnl (c))
3045 {
3046 /* We have found the end of a token. Make a word out of it and
3047 add it to the word list. */
3048 token = substring (s, tokstart, i);
3049 list = add_string_to_list (token, list);
3050 free (token);
3051 while (spctabnl (s[i]))
3052 i++;
3053 if (s[i])
3054 tokstart = i;
3055 else
3056 break;
3057 }
3058 else
3059 i++; /* normal character */
3060 }
3061 return (REVERSE_LIST (list, WORD_LIST *));
3062 }
3063 #endif
3064
3065 /********************************************************/
3066 /* */
3067 /* Functions to perform assignment statements */
3068 /* */
3069 /********************************************************/
3070
3071 #if defined (ARRAY_VARS)
3072 static SHELL_VAR *
3073 do_compound_assignment (name, value, flags)
3074 char *name, *value;
3075 int flags;
3076 {
3077 SHELL_VAR *v;
3078 int mklocal, mkassoc, mkglobal, chklocal;
3079 WORD_LIST *list;
3080 char *newname; /* used for local nameref references */
3081
3082 mklocal = flags & ASS_MKLOCAL;
3083 mkassoc = flags & ASS_MKASSOC;
3084 mkglobal = flags & ASS_MKGLOBAL;
3085 chklocal = flags & ASS_CHKLOCAL;
3086
3087 if (mklocal && variable_context)
3088 {
3089 v = find_variable (name); /* follows namerefs */
3090 newname = (v == 0) ? nameref_transform_name (name, flags) : v->name;
3091 if (v && ((readonly_p (v) && (flags & ASS_FORCE) == 0) || noassign_p (v)))
3092 {
3093 if (readonly_p (v))
3094 err_readonly (name);
3095 return (v); /* XXX */
3096 }
3097 list = expand_compound_array_assignment (v, value, flags);
3098 if (mkassoc)
3099 v = make_local_assoc_variable (newname, 0);
3100 else if (v == 0 || (array_p (v) == 0 && assoc_p (v) == 0) || v->context != variable_context)
3101 v = make_local_array_variable (newname, 0);
3102 if (v)
3103 assign_compound_array_list (v, list, flags);
3104 if (list)
3105 dispose_words (list);
3106 }
3107 /* In a function but forcing assignment in global context. CHKLOCAL means to
3108 check for an existing local variable first. */
3109 else if (mkglobal && variable_context)
3110 {
3111 v = chklocal ? find_variable (name) : 0;
3112 if (v && (local_p (v) == 0 || v->context != variable_context))
3113 v = 0;
3114 if (v == 0)
3115 v = find_global_variable (name);
3116 if (v && ((readonly_p (v) && (flags & ASS_FORCE) == 0) || noassign_p (v)))
3117 {
3118 if (readonly_p (v))
3119 err_readonly (name);
3120 return (v); /* XXX */
3121 }
3122 /* sanity check */
3123 newname = (v == 0) ? nameref_transform_name (name, flags) : name;
3124 list = expand_compound_array_assignment (v, value, flags);
3125 if (v == 0 && mkassoc)
3126 v = make_new_assoc_variable (newname);
3127 else if (v && mkassoc && assoc_p (v) == 0)
3128 v = convert_var_to_assoc (v);
3129 else if (v == 0)
3130 v = make_new_array_variable (newname);
3131 else if (v && mkassoc == 0 && array_p (v) == 0)
3132 v = convert_var_to_array (v);
3133 if (v)
3134 assign_compound_array_list (v, list, flags);
3135 if (list)
3136 dispose_words (list);
3137 }
3138 else
3139 {
3140 v = assign_array_from_string (name, value, flags);
3141 if (v && ((readonly_p (v) && (flags & ASS_FORCE) == 0) || noassign_p (v)))
3142 {
3143 if (readonly_p (v))
3144 err_readonly (name);
3145 return (v); /* XXX */
3146 }
3147 }
3148
3149 return (v);
3150 }
3151 #endif
3152
3153 /* Given STRING, an assignment string, get the value of the right side
3154 of the `=', and bind it to the left side. If EXPAND is true, then
3155 perform parameter expansion, command substitution, and arithmetic
3156 expansion on the right-hand side. Perform tilde expansion in any
3157 case. Do not perform word splitting on the result of expansion. */
3158 static int
3159 do_assignment_internal (word, expand)
3160 const WORD_DESC *word;
3161 int expand;
3162 {
3163 int offset, appendop, assign_list, aflags, retval;
3164 char *name, *value, *temp;
3165 SHELL_VAR *entry;
3166 #if defined (ARRAY_VARS)
3167 char *t;
3168 int ni;
3169 #endif
3170 const char *string;
3171
3172 if (word == 0 || word->word == 0)
3173 return 0;
3174
3175 appendop = assign_list = aflags = 0;
3176 string = word->word;
3177 offset = assignment (string, 0);
3178 name = savestring (string);
3179 value = (char *)NULL;
3180
3181 if (name[offset] == '=')
3182 {
3183 if (name[offset - 1] == '+')
3184 {
3185 appendop = 1;
3186 name[offset - 1] = '\0';
3187 }
3188
3189 name[offset] = 0; /* might need this set later */
3190 temp = name + offset + 1;
3191
3192 #if defined (ARRAY_VARS)
3193 if (expand && (word->flags & W_COMPASSIGN))
3194 {
3195 assign_list = ni = 1;
3196 value = extract_array_assignment_list (temp, &ni);
3197 }
3198 else
3199 #endif
3200 if (expand && temp[0])
3201 value = expand_string_if_necessary (temp, 0, expand_string_assignment);
3202 else
3203 value = savestring (temp);
3204 }
3205
3206 if (value == 0)
3207 {
3208 value = (char *)xmalloc (1);
3209 value[0] = '\0';
3210 }
3211
3212 if (echo_command_at_execute)
3213 {
3214 if (appendop)
3215 name[offset - 1] = '+';
3216 xtrace_print_assignment (name, value, assign_list, 1);
3217 if (appendop)
3218 name[offset - 1] = '\0';
3219 }
3220
3221 #define ASSIGN_RETURN(r) do { FREE (value); free (name); return (r); } while (0)
3222
3223 if (appendop)
3224 aflags |= ASS_APPEND;
3225
3226 #if defined (ARRAY_VARS)
3227 if (t = mbschr (name, LBRACK))
3228 {
3229 if (assign_list)
3230 {
3231 report_error (_("%s: cannot assign list to array member"), name);
3232 ASSIGN_RETURN (0);
3233 }
3234 entry = assign_array_element (name, value, aflags);
3235 if (entry == 0)
3236 ASSIGN_RETURN (0);
3237 }
3238 else if (assign_list)
3239 {
3240 if ((word->flags & W_ASSIGNARG) && (word->flags & W_CHKLOCAL))
3241 aflags |= ASS_CHKLOCAL;
3242 if ((word->flags & W_ASSIGNARG) && (word->flags & W_ASSNGLOBAL) == 0)
3243 aflags |= ASS_MKLOCAL;
3244 if ((word->flags & W_ASSIGNARG) && (word->flags & W_ASSNGLOBAL))
3245 aflags |= ASS_MKGLOBAL;
3246 if (word->flags & W_ASSIGNASSOC)
3247 aflags |= ASS_MKASSOC;
3248 entry = do_compound_assignment (name, value, aflags);
3249 }
3250 else
3251 #endif /* ARRAY_VARS */
3252 entry = bind_variable (name, value, aflags);
3253
3254 stupidly_hack_special_variables (name);
3255
3256 /* Return 1 if the assignment seems to have been performed correctly. */
3257 if (entry == 0 || readonly_p (entry))
3258 retval = 0; /* assignment failure */
3259 else if (noassign_p (entry))
3260 {
3261 last_command_exit_value = EXECUTION_FAILURE;
3262 retval = 1; /* error status, but not assignment failure */
3263 }
3264 else
3265 retval = 1;
3266
3267 if (entry && retval != 0 && noassign_p (entry) == 0)
3268 VUNSETATTR (entry, att_invisible);
3269
3270 ASSIGN_RETURN (retval);
3271 }
3272
3273 /* Perform the assignment statement in STRING, and expand the
3274 right side by doing tilde, command and parameter expansion. */
3275 int
3276 do_assignment (string)
3277 char *string;
3278 {
3279 WORD_DESC td;
3280
3281 td.flags = W_ASSIGNMENT;
3282 td.word = string;
3283
3284 return do_assignment_internal (&td, 1);
3285 }
3286
3287 int
3288 do_word_assignment (word, flags)
3289 WORD_DESC *word;
3290 int flags;
3291 {
3292 return do_assignment_internal (word, 1);
3293 }
3294
3295 /* Given STRING, an assignment string, get the value of the right side
3296 of the `=', and bind it to the left side. Do not perform any word
3297 expansions on the right hand side. */
3298 int
3299 do_assignment_no_expand (string)
3300 char *string;
3301 {
3302 WORD_DESC td;
3303
3304 td.flags = W_ASSIGNMENT;
3305 td.word = string;
3306
3307 return (do_assignment_internal (&td, 0));
3308 }
3309
3310 /***************************************************
3311 * *
3312 * Functions to manage the positional parameters *
3313 * *
3314 ***************************************************/
3315
3316 /* Return the word list that corresponds to `$*'. */
3317 WORD_LIST *
3318 list_rest_of_args ()
3319 {
3320 register WORD_LIST *list, *args;
3321 int i;
3322
3323 /* Break out of the loop as soon as one of the dollar variables is null. */
3324 for (i = 1, list = (WORD_LIST *)NULL; i < 10 && dollar_vars[i]; i++)
3325 list = make_word_list (make_bare_word (dollar_vars[i]), list);
3326
3327 for (args = rest_of_args; args; args = args->next)
3328 list = make_word_list (make_bare_word (args->word->word), list);
3329
3330 return (REVERSE_LIST (list, WORD_LIST *));
3331 }
3332
3333 int
3334 number_of_args ()
3335 {
3336 register WORD_LIST *list;
3337 int n;
3338
3339 for (n = 0; n < 9 && dollar_vars[n+1]; n++)
3340 ;
3341 for (list = rest_of_args; list; list = list->next)
3342 n++;
3343 return n;
3344 }
3345
3346 /* Return the value of a positional parameter. This handles values > 10. */
3347 char *
3348 get_dollar_var_value (ind)
3349 intmax_t ind;
3350 {
3351 char *temp;
3352 WORD_LIST *p;
3353
3354 if (ind < 10)
3355 temp = dollar_vars[ind] ? savestring (dollar_vars[ind]) : (char *)NULL;
3356 else /* We want something like ${11} */
3357 {
3358 ind -= 10;
3359 for (p = rest_of_args; p && ind--; p = p->next)
3360 ;
3361 temp = p ? savestring (p->word->word) : (char *)NULL;
3362 }
3363 return (temp);
3364 }
3365
3366 /* Make a single large string out of the dollar digit variables,
3367 and the rest_of_args. If DOLLAR_STAR is 1, then obey the special
3368 case of "$*" with respect to IFS. */
3369 char *
3370 string_rest_of_args (dollar_star)
3371 int dollar_star;
3372 {
3373 register WORD_LIST *list;
3374 char *string;
3375
3376 list = list_rest_of_args ();
3377 string = dollar_star ? string_list_dollar_star (list, 0, 0) : string_list (list);
3378 dispose_words (list);
3379 return (string);
3380 }
3381
3382 /* Return a string containing the positional parameters from START to
3383 END, inclusive. If STRING[0] == '*', we obey the rules for $*,
3384 which only makes a difference if QUOTED is non-zero. If QUOTED includes
3385 Q_HERE_DOCUMENT or Q_DOUBLE_QUOTES, this returns a quoted list, otherwise
3386 no quoting chars are added. */
3387 static char *
3388 pos_params (string, start, end, quoted)
3389 char *string;
3390 int start, end, quoted;
3391 {
3392 WORD_LIST *save, *params, *h, *t;
3393 char *ret;
3394 int i;
3395
3396 /* see if we can short-circuit. if start == end, we want 0 parameters. */
3397 if (start == end)
3398 return ((char *)NULL);
3399
3400 save = params = list_rest_of_args ();
3401 if (save == 0 && start > 0)
3402 return ((char *)NULL);
3403
3404 if (start == 0) /* handle ${@:0[:x]} specially */
3405 {
3406 t = make_word_list (make_word (dollar_vars[0]), params);
3407 save = params = t;
3408 }
3409
3410 for (i = start ? 1 : 0; params && i < start; i++)
3411 params = params->next;
3412 if (params == 0)
3413 {
3414 dispose_words (save);
3415 return ((char *)NULL);
3416 }
3417 for (h = t = params; params && i < end; i++)
3418 {
3419 t = params;
3420 params = params->next;
3421 }
3422 t->next = (WORD_LIST *)NULL;
3423
3424 ret = string_list_pos_params (string[0], h, quoted);
3425
3426 if (t != params)
3427 t->next = params;
3428
3429 dispose_words (save);
3430 return (ret);
3431 }
3432
3433 /******************************************************************/
3434 /* */
3435 /* Functions to expand strings to strings or WORD_LISTs */
3436 /* */
3437 /******************************************************************/
3438
3439 #if defined (PROCESS_SUBSTITUTION)
3440 #define EXP_CHAR(s) (s == '$' || s == '`' || s == '<' || s == '>' || s == CTLESC || s == '~')
3441 #else
3442 #define EXP_CHAR(s) (s == '$' || s == '`' || s == CTLESC || s == '~')
3443 #endif
3444
3445 /* If there are any characters in STRING that require full expansion,
3446 then call FUNC to expand STRING; otherwise just perform quote
3447 removal if necessary. This returns a new string. */
3448 static char *
3449 expand_string_if_necessary (string, quoted, func)
3450 char *string;
3451 int quoted;
3452 EXPFUNC *func;
3453 {
3454 WORD_LIST *list;
3455 size_t slen;
3456 int i, saw_quote;
3457 char *ret;
3458 DECLARE_MBSTATE;
3459
3460 /* Don't need string length for ADVANCE_CHAR unless multibyte chars possible. */
3461 slen = (MB_CUR_MAX > 1) ? strlen (string) : 0;
3462 i = saw_quote = 0;
3463 while (string[i])
3464 {
3465 if (EXP_CHAR (string[i]))
3466 break;
3467 else if (string[i] == '\'' || string[i] == '\\' || string[i] == '"')
3468 saw_quote = 1;
3469 ADVANCE_CHAR (string, slen, i);
3470 }
3471
3472 if (string[i])
3473 {
3474 list = (*func) (string, quoted);
3475 if (list)
3476 {
3477 ret = string_list (list);
3478 dispose_words (list);
3479 }
3480 else
3481 ret = (char *)NULL;
3482 }
3483 else if (saw_quote && ((quoted & (Q_HERE_DOCUMENT|Q_DOUBLE_QUOTES)) == 0))
3484 ret = string_quote_removal (string, quoted);
3485 else
3486 ret = savestring (string);
3487
3488 return ret;
3489 }
3490
3491 static inline char *
3492 expand_string_to_string_internal (string, quoted, func)
3493 char *string;
3494 int quoted;
3495 EXPFUNC *func;
3496 {
3497 WORD_LIST *list;
3498 char *ret;
3499
3500 if (string == 0 || *string == '\0')
3501 return ((char *)NULL);
3502
3503 list = (*func) (string, quoted);
3504 if (list)
3505 {
3506 ret = string_list (list);
3507 dispose_words (list);
3508 }
3509 else
3510 ret = (char *)NULL;
3511
3512 return (ret);
3513 }
3514
3515 char *
3516 expand_string_to_string (string, quoted)
3517 char *string;
3518 int quoted;
3519 {
3520 return (expand_string_to_string_internal (string, quoted, expand_string));
3521 }
3522
3523 char *
3524 expand_string_unsplit_to_string (string, quoted)
3525 char *string;
3526 int quoted;
3527 {
3528 return (expand_string_to_string_internal (string, quoted, expand_string_unsplit));
3529 }
3530
3531 char *
3532 expand_assignment_string_to_string (string, quoted)
3533 char *string;
3534 int quoted;
3535 {
3536 return (expand_string_to_string_internal (string, quoted, expand_string_assignment));
3537 }
3538
3539 char *
3540 expand_arith_string (string, quoted)
3541 char *string;
3542 int quoted;
3543 {
3544 WORD_DESC td;
3545 WORD_LIST *list, *tlist;
3546 size_t slen;
3547 int i, saw_quote;
3548 char *ret;
3549 DECLARE_MBSTATE;
3550
3551 /* Don't need string length for ADVANCE_CHAR unless multibyte chars possible. */
3552 slen = (MB_CUR_MAX > 1) ? strlen (string) : 0;
3553 i = saw_quote = 0;
3554 while (string[i])
3555 {
3556 if (EXP_CHAR (string[i]))
3557 break;
3558 else if (string[i] == '\'' || string[i] == '\\' || string[i] == '"')
3559 saw_quote = 1;
3560 ADVANCE_CHAR (string, slen, i);
3561 }
3562
3563 if (string[i])
3564 {
3565 /* This is expanded version of expand_string_internal as it's called by
3566 expand_string_leave_quoted */
3567 td.flags = W_NOPROCSUB|W_NOTILDE; /* don't want process substitution or tilde expansion */
3568 td.word = savestring (string);
3569 list = call_expand_word_internal (&td, quoted, 0, (int *)NULL, (int *)NULL);
3570 /* This takes care of the calls from expand_string_leave_quoted and
3571 expand_string */
3572 if (list)
3573 {
3574 tlist = word_list_split (list);
3575 dispose_words (list);
3576 list = tlist;
3577 if (list)
3578 dequote_list (list);
3579 }
3580 /* This comes from expand_string_if_necessary */
3581 if (list)
3582 {
3583 ret = string_list (list);
3584 dispose_words (list);
3585 }
3586 else
3587 ret = (char *)NULL;
3588 FREE (td.word);
3589 }
3590 else if (saw_quote && (quoted & Q_ARITH))
3591 ret = string_quote_removal (string, quoted);
3592 else if (saw_quote && ((quoted & (Q_HERE_DOCUMENT|Q_DOUBLE_QUOTES)) == 0))
3593 ret = string_quote_removal (string, quoted);
3594 else
3595 ret = savestring (string);
3596
3597 return ret;
3598 }
3599
3600 #if defined (COND_COMMAND)
3601 /* Just remove backslashes in STRING. Returns a new string. */
3602 char *
3603 remove_backslashes (string)
3604 char *string;
3605 {
3606 char *r, *ret, *s;
3607
3608 r = ret = (char *)xmalloc (strlen (string) + 1);
3609 for (s = string; s && *s; )
3610 {
3611 if (*s == '\\')
3612 s++;
3613 if (*s == 0)
3614 break;
3615 *r++ = *s++;
3616 }
3617 *r = '\0';
3618 return ret;
3619 }
3620
3621 /* This needs better error handling. */
3622 /* Expand W for use as an argument to a unary or binary operator in a
3623 [[...]] expression. If SPECIAL is 1, this is the rhs argument
3624 to the != or == operator, and should be treated as a pattern. In
3625 this case, we quote the string specially for the globbing code. If
3626 SPECIAL is 2, this is an rhs argument for the =~ operator, and should
3627 be quoted appropriately for regcomp/regexec. The caller is responsible
3628 for removing the backslashes if the unquoted word is needed later. */
3629 char *
3630 cond_expand_word (w, special)
3631 WORD_DESC *w;
3632 int special;
3633 {
3634 char *r, *p;
3635 WORD_LIST *l;
3636 int qflags;
3637
3638 if (w->word == 0 || w->word[0] == '\0')
3639 return ((char *)NULL);
3640
3641 expand_no_split_dollar_star = 1;
3642 w->flags |= W_NOSPLIT2;
3643 l = call_expand_word_internal (w, 0, 0, (int *)0, (int *)0);
3644 expand_no_split_dollar_star = 0;
3645 if (l)
3646 {
3647 if (special == 0) /* LHS */
3648 {
3649 dequote_list (l);
3650 r = string_list (l);
3651 }
3652 else
3653 {
3654 /* Need to figure out whether or not we should call dequote_escapes
3655 or a new dequote_ctlnul function here, and under what
3656 circumstances. */
3657 qflags = QGLOB_CVTNULL|QGLOB_CTLESC;
3658 if (special == 2)
3659 qflags |= QGLOB_REGEXP;
3660 word_list_remove_quoted_nulls (l);
3661 p = string_list (l);
3662 r = quote_string_for_globbing (p, qflags);
3663 free (p);
3664 }
3665 dispose_words (l);
3666 }
3667 else
3668 r = (char *)NULL;
3669
3670 return r;
3671 }
3672 #endif
3673
3674 /* Call expand_word_internal to expand W and handle error returns.
3675 A convenience function for functions that don't want to handle
3676 any errors or free any memory before aborting. */
3677 static WORD_LIST *
3678 call_expand_word_internal (w, q, i, c, e)
3679 WORD_DESC *w;
3680 int q, i, *c, *e;
3681 {
3682 WORD_LIST *result;
3683
3684 result = expand_word_internal (w, q, i, c, e);
3685 if (result == &expand_word_error || result == &expand_word_fatal)
3686 {
3687 /* By convention, each time this error is returned, w->word has
3688 already been freed (it sometimes may not be in the fatal case,
3689 but that doesn't result in a memory leak because we're going
3690 to exit in most cases). */
3691 w->word = (char *)NULL;
3692 last_command_exit_value = EXECUTION_FAILURE;
3693 exp_jump_to_top_level ((result == &expand_word_error) ? DISCARD : FORCE_EOF);
3694 /* NOTREACHED */
3695 return (NULL);
3696 }
3697 else
3698 return (result);
3699 }
3700
3701 /* Perform parameter expansion, command substitution, and arithmetic
3702 expansion on STRING, as if it were a word. Leave the result quoted.
3703 Since this does not perform word splitting, it leaves quoted nulls
3704 in the result. */
3705 static WORD_LIST *
3706 expand_string_internal (string, quoted)
3707 char *string;
3708 int quoted;
3709 {
3710 WORD_DESC td;
3711 WORD_LIST *tresult;
3712
3713 if (string == 0 || *string == 0)
3714 return ((WORD_LIST *)NULL);
3715
3716 td.flags = 0;
3717 td.word = savestring (string);
3718
3719 tresult = call_expand_word_internal (&td, quoted, 0, (int *)NULL, (int *)NULL);
3720
3721 FREE (td.word);
3722 return (tresult);
3723 }
3724
3725 /* Expand STRING by performing parameter expansion, command substitution,
3726 and arithmetic expansion. Dequote the resulting WORD_LIST before
3727 returning it, but do not perform word splitting. The call to
3728 remove_quoted_nulls () is in here because word splitting normally
3729 takes care of quote removal. */
3730 WORD_LIST *
3731 expand_string_unsplit (string, quoted)
3732 char *string;
3733 int quoted;
3734 {
3735 WORD_LIST *value;
3736
3737 if (string == 0 || *string == '\0')
3738 return ((WORD_LIST *)NULL);
3739
3740 expand_no_split_dollar_star = 1;
3741 value = expand_string_internal (string, quoted);
3742 expand_no_split_dollar_star = 0;
3743
3744 if (value)
3745 {
3746 if (value->word)
3747 {
3748 remove_quoted_nulls (value->word->word);
3749 value->word->flags &= ~W_HASQUOTEDNULL;
3750 }
3751 dequote_list (value);
3752 }
3753 return (value);
3754 }
3755
3756 /* Expand the rhs of an assignment statement */
3757 WORD_LIST *
3758 expand_string_assignment (string, quoted)
3759 char *string;
3760 int quoted;
3761 {
3762 WORD_DESC td;
3763 WORD_LIST *value;
3764
3765 if (string == 0 || *string == '\0')
3766 return ((WORD_LIST *)NULL);
3767
3768 expand_no_split_dollar_star = 1;
3769
3770 #if 0
3771 /* Other shells (ksh93) do it this way, which affects how $@ is expanded
3772 in constructs like bar=${@#0} (preserves the spaces resulting from the
3773 expansion of $@ in a context where you don't do word splitting); Posix
3774 interp 888 makes the expansion of $@ in contexts where word splitting
3775 is not performed unspecified. */
3776 td.flags = W_ASSIGNRHS|W_NOSPLIT2; /* Posix interp 888 */
3777 #else
3778 td.flags = W_ASSIGNRHS;
3779 #endif
3780 td.word = savestring (string);
3781 value = call_expand_word_internal (&td, quoted, 0, (int *)NULL, (int *)NULL);
3782 FREE (td.word);
3783
3784 expand_no_split_dollar_star = 0;
3785
3786 if (value)
3787 {
3788 if (value->word)
3789 {
3790 remove_quoted_nulls (value->word->word);
3791 value->word->flags &= ~W_HASQUOTEDNULL;
3792 }
3793 dequote_list (value);
3794 }
3795 return (value);
3796 }
3797
3798
3799 /* Expand one of the PS? prompt strings. This is a sort of combination of
3800 expand_string_unsplit and expand_string_internal, but returns the
3801 passed string when an error occurs. Might want to trap other calls
3802 to jump_to_top_level here so we don't endlessly loop. */
3803 WORD_LIST *
3804 expand_prompt_string (string, quoted, wflags)
3805 char *string;
3806 int quoted;
3807 int wflags;
3808 {
3809 WORD_LIST *value;
3810 WORD_DESC td;
3811
3812 if (string == 0 || *string == 0)
3813 return ((WORD_LIST *)NULL);
3814
3815 td.flags = wflags;
3816 td.word = savestring (string);
3817
3818 no_longjmp_on_fatal_error = 1;
3819 value = expand_word_internal (&td, quoted, 0, (int *)NULL, (int *)NULL);
3820 no_longjmp_on_fatal_error = 0;
3821
3822 if (value == &expand_word_error || value == &expand_word_fatal)
3823 {
3824 value = make_word_list (make_bare_word (string), (WORD_LIST *)NULL);
3825 return value;
3826 }
3827 FREE (td.word);
3828 if (value)
3829 {
3830 if (value->word)
3831 {
3832 remove_quoted_nulls (value->word->word);
3833 value->word->flags &= ~W_HASQUOTEDNULL;
3834 }
3835 dequote_list (value);
3836 }
3837 return (value);
3838 }
3839
3840 /* Expand STRING just as if you were expanding a word, but do not dequote
3841 the resultant WORD_LIST. This is called only from within this file,
3842 and is used to correctly preserve quoted characters when expanding
3843 things like ${1+"$@"}. This does parameter expansion, command
3844 substitution, arithmetic expansion, and word splitting. */
3845 static WORD_LIST *
3846 expand_string_leave_quoted (string, quoted)
3847 char *string;
3848 int quoted;
3849 {
3850 WORD_LIST *tlist;
3851 WORD_LIST *tresult;
3852
3853 if (string == 0 || *string == '\0')
3854 return ((WORD_LIST *)NULL);
3855
3856 tlist = expand_string_internal (string, quoted);
3857
3858 if (tlist)
3859 {
3860 tresult = word_list_split (tlist);
3861 dispose_words (tlist);
3862 return (tresult);
3863 }
3864 return ((WORD_LIST *)NULL);
3865 }
3866
3867 /* This does not perform word splitting or dequote the WORD_LIST
3868 it returns. */
3869 static WORD_LIST *
3870 expand_string_for_rhs (string, quoted, op, pflags, dollar_at_p, expanded_p)
3871 char *string;
3872 int quoted, op, pflags;
3873 int *dollar_at_p, *expanded_p;
3874 {
3875 WORD_DESC td;
3876 WORD_LIST *tresult;
3877 int old_nosplit;
3878
3879 if (string == 0 || *string == '\0')
3880 return (WORD_LIST *)NULL;
3881
3882 /* We want field splitting to be determined by what is going to be done with
3883 the entire ${parameterOPword} expansion, so we don't want to split the RHS
3884 we expand here. However, the expansion of $* is determined by whether we
3885 are going to eventually perform word splitting, so we want to set this
3886 depending on whether or not are are going to be splitting: if the expansion
3887 is quoted, if the OP is `=', or if IFS is set to the empty string, we
3888 are not going to be splitting, so we set expand_no_split_dollar_star to
3889 We pass through PF_ASSIGNRHS as W_ASSIGNRHS if this is on the RHS of an
3890 assignment statement. */
3891 /* The updated treatment of $* is the result of Posix interp 888 */
3892 /* This was further clarified on the austin-group list in March, 2017 and
3893 in Posix bug 1129 */
3894 old_nosplit = expand_no_split_dollar_star;
3895 expand_no_split_dollar_star = (quoted & (Q_DOUBLE_QUOTES|Q_HERE_DOCUMENT)) || op == '=' || ifs_is_null == 0; /* XXX - was 1 */
3896 td.flags = W_NOSPLIT2; /* no splitting, remove "" and '' */
3897 if (pflags & PF_ASSIGNRHS) /* pass through */
3898 td.flags |= W_ASSIGNRHS;
3899 if (op == '=')
3900 #if 0
3901 td.flags |= W_ASSIGNRHS; /* expand b in ${a=b} like assignment */
3902 #else
3903 td.flags |= W_ASSIGNRHS|W_NOASSNTILDE; /* expand b in ${a=b} like assignment */
3904 #endif
3905 td.word = string;
3906 tresult = call_expand_word_internal (&td, quoted, 1, dollar_at_p, expanded_p);
3907 expand_no_split_dollar_star = old_nosplit;
3908
3909 return (tresult);
3910 }
3911
3912 /* This does not perform word splitting or dequote the WORD_LIST
3913 it returns and it treats $* as if it were quoted. */
3914 static WORD_LIST *
3915 expand_string_for_pat (string, quoted, dollar_at_p, expanded_p)
3916 char *string;
3917 int quoted, *dollar_at_p, *expanded_p;
3918 {
3919 WORD_DESC td;
3920 WORD_LIST *tresult;
3921 int oexp;
3922
3923 if (string == 0 || *string == '\0')
3924 return (WORD_LIST *)NULL;
3925
3926 oexp = expand_no_split_dollar_star;
3927 expand_no_split_dollar_star = 1;
3928 td.flags = W_NOSPLIT2; /* no splitting, remove "" and '' */
3929 td.word = string;
3930 tresult = call_expand_word_internal (&td, quoted, 1, dollar_at_p, expanded_p);
3931 expand_no_split_dollar_star = oexp;
3932
3933 return (tresult);
3934 }
3935
3936 /* Expand STRING just as if you were expanding a word. This also returns
3937 a list of words. Note that filename globbing is *NOT* done for word
3938 or string expansion, just when the shell is expanding a command. This
3939 does parameter expansion, command substitution, arithmetic expansion,
3940 and word splitting. Dequote the resultant WORD_LIST before returning. */
3941 WORD_LIST *
3942 expand_string (string, quoted)
3943 char *string;
3944 int quoted;
3945 {
3946 WORD_LIST *result;
3947
3948 if (string == 0 || *string == '\0')
3949 return ((WORD_LIST *)NULL);
3950
3951 result = expand_string_leave_quoted (string, quoted);
3952 return (result ? dequote_list (result) : result);
3953 }
3954
3955 /*******************************************
3956 * *
3957 * Functions to expand WORD_DESCs *
3958 * *
3959 *******************************************/
3960
3961 /* Expand WORD, performing word splitting on the result. This does
3962 parameter expansion, command substitution, arithmetic expansion,
3963 word splitting, and quote removal. */
3964
3965 WORD_LIST *
3966 expand_word (word, quoted)
3967 WORD_DESC *word;
3968 int quoted;
3969 {
3970 WORD_LIST *result, *tresult;
3971
3972 tresult = call_expand_word_internal (word, quoted, 0, (int *)NULL, (int *)NULL);
3973 result = word_list_split (tresult);
3974 dispose_words (tresult);
3975 return (result ? dequote_list (result) : result);
3976 }
3977
3978 /* Expand WORD, but do not perform word splitting on the result. This
3979 does parameter expansion, command substitution, arithmetic expansion,
3980 and quote removal. */
3981 WORD_LIST *
3982 expand_word_unsplit (word, quoted)
3983 WORD_DESC *word;
3984 int quoted;
3985 {
3986 WORD_LIST *result;
3987
3988 result = expand_word_leave_quoted (word, quoted);
3989 return (result ? dequote_list (result) : result);
3990 }
3991
3992 /* Perform shell expansions on WORD, but do not perform word splitting or
3993 quote removal on the result. Virtually identical to expand_word_unsplit;
3994 could be combined if implementations don't diverge. */
3995 WORD_LIST *
3996 expand_word_leave_quoted (word, quoted)
3997 WORD_DESC *word;
3998 int quoted;
3999 {
4000 WORD_LIST *result;
4001
4002 expand_no_split_dollar_star = 1;
4003 if (ifs_is_null)
4004 word->flags |= W_NOSPLIT;
4005 word->flags |= W_NOSPLIT2;
4006 result = call_expand_word_internal (word, quoted, 0, (int *)NULL, (int *)NULL);
4007 expand_no_split_dollar_star = 0;
4008
4009 return result;
4010 }
4011
4012 /***************************************************
4013 * *
4014 * Functions to handle quoting chars *
4015 * *
4016 ***************************************************/
4017
4018 /* Conventions:
4019
4020 A string with s[0] == CTLNUL && s[1] == 0 is a quoted null string.
4021 The parser passes CTLNUL as CTLESC CTLNUL. */
4022
4023 /* Quote escape characters in string s, but no other characters. This is
4024 used to protect CTLESC and CTLNUL in variable values from the rest of
4025 the word expansion process after the variable is expanded (word splitting
4026 and filename generation). If IFS is null, we quote spaces as well, just
4027 in case we split on spaces later (in the case of unquoted $@, we will
4028 eventually attempt to split the entire word on spaces). Corresponding
4029 code exists in dequote_escapes. Even if we don't end up splitting on
4030 spaces, quoting spaces is not a problem. This should never be called on
4031 a string that is quoted with single or double quotes or part of a here
4032 document (effectively double-quoted).
4033 FLAGS says whether or not we are going to split the result. If we are not,
4034 and there is a CTLESC or CTLNUL in IFS, we need to quote CTLESC and CTLNUL,
4035 respectively, to prevent them from being removed as part of dequoting. */
4036 static char *
4037 quote_escapes_internal (string, flags)
4038 const char *string;
4039 int flags;
4040 {
4041 const char *s, *send;
4042 char *t, *result;
4043 size_t slen;
4044 int quote_spaces, skip_ctlesc, skip_ctlnul, nosplit;
4045 DECLARE_MBSTATE;
4046
4047 slen = strlen (string);
4048 send = string + slen;
4049
4050 quote_spaces = (ifs_value && *ifs_value == 0);
4051 nosplit = (flags & PF_NOSPLIT2);
4052
4053 for (skip_ctlesc = skip_ctlnul = 0, s = ifs_value; s && *s; s++)
4054 {
4055 skip_ctlesc |= (nosplit == 0 && *s == CTLESC);
4056 skip_ctlnul |= (nosplit == 0 && *s == CTLNUL);
4057 }
4058
4059 t = result = (char *)xmalloc ((slen * 2) + 1);
4060 s = string;
4061
4062 while (*s)
4063 {
4064 if ((skip_ctlesc == 0 && *s == CTLESC) || (skip_ctlnul == 0 && *s == CTLNUL) || (quote_spaces && *s == ' '))
4065 *t++ = CTLESC;
4066 COPY_CHAR_P (t, s, send);
4067 }
4068 *t = '\0';
4069
4070 return (result);
4071 }
4072
4073 char *
4074 quote_escapes (string)
4075 const char *string;
4076 {
4077 return (quote_escapes_internal (string, 0));
4078 }
4079
4080 char *
4081 quote_rhs (string)
4082 const char *string;
4083 {
4084 return (quote_escapes_internal (string, PF_NOSPLIT2));
4085 }
4086
4087 static WORD_LIST *
4088 list_quote_escapes (list)
4089 WORD_LIST *list;
4090 {
4091 register WORD_LIST *w;
4092 char *t;
4093
4094 for (w = list; w; w = w->next)
4095 {
4096 t = w->word->word;
4097 w->word->word = quote_escapes (t);
4098 free (t);
4099 }
4100 return list;
4101 }
4102
4103 /* Inverse of quote_escapes; remove CTLESC protecting CTLESC or CTLNUL.
4104
4105 The parser passes us CTLESC as CTLESC CTLESC and CTLNUL as CTLESC CTLNUL.
4106 This is necessary to make unquoted CTLESC and CTLNUL characters in the
4107 data stream pass through properly.
4108
4109 We need to remove doubled CTLESC characters inside quoted strings before
4110 quoting the entire string, so we do not double the number of CTLESC
4111 characters.
4112
4113 Also used by parts of the pattern substitution code. */
4114 char *
4115 dequote_escapes (string)
4116 const char *string;
4117 {
4118 const char *s, *send;
4119 char *t, *result;
4120 size_t slen;
4121 int quote_spaces;
4122 DECLARE_MBSTATE;
4123
4124 if (string == 0)
4125 return (char *)0;
4126
4127 slen = strlen (string);
4128 send = string + slen;
4129
4130 t = result = (char *)xmalloc (slen + 1);
4131
4132 if (strchr (string, CTLESC) == 0)
4133 return (strcpy (result, string));
4134
4135 quote_spaces = (ifs_value && *ifs_value == 0);
4136
4137 s = string;
4138 while (*s)
4139 {
4140 if (*s == CTLESC && (s[1] == CTLESC || s[1] == CTLNUL || (quote_spaces && s[1] == ' ')))
4141 {
4142 s++;
4143 if (*s == '\0')
4144 break;
4145 }
4146 COPY_CHAR_P (t, s, send);
4147 }
4148 *t = '\0';
4149
4150 return result;
4151 }
4152
4153 #if defined (INCLUDE_UNUSED)
4154 static WORD_LIST *
4155 list_dequote_escapes (list)
4156 WORD_LIST *list;
4157 {
4158 register WORD_LIST *w;
4159 char *t;
4160
4161 for (w = list; w; w = w->next)
4162 {
4163 t = w->word->word;
4164 w->word->word = dequote_escapes (t);
4165 free (t);
4166 }
4167 return list;
4168 }
4169 #endif
4170
4171 /* Return a new string with the quoted representation of character C.
4172 This turns "" into QUOTED_NULL, so the W_HASQUOTEDNULL flag needs to be
4173 set in any resultant WORD_DESC where this value is the word. */
4174 static char *
4175 make_quoted_char (c)
4176 int c;
4177 {
4178 char *temp;
4179
4180 temp = (char *)xmalloc (3);
4181 if (c == 0)
4182 {
4183 temp[0] = CTLNUL;
4184 temp[1] = '\0';
4185 }
4186 else
4187 {
4188 temp[0] = CTLESC;
4189 temp[1] = c;
4190 temp[2] = '\0';
4191 }
4192 return (temp);
4193 }
4194
4195 /* Quote STRING, returning a new string. This turns "" into QUOTED_NULL, so
4196 the W_HASQUOTEDNULL flag needs to be set in any resultant WORD_DESC where
4197 this value is the word. */
4198 char *
4199 quote_string (string)
4200 char *string;
4201 {
4202 register char *t;
4203 size_t slen;
4204 char *result, *send;
4205
4206 if (*string == 0)
4207 {
4208 result = (char *)xmalloc (2);
4209 result[0] = CTLNUL;
4210 result[1] = '\0';
4211 }
4212 else
4213 {
4214 DECLARE_MBSTATE;
4215
4216 slen = strlen (string);
4217 send = string + slen;
4218
4219 result = (char *)xmalloc ((slen * 2) + 1);
4220
4221 for (t = result; string < send; )
4222 {
4223 *t++ = CTLESC;
4224 COPY_CHAR_P (t, string, send);
4225 }
4226 *t = '\0';
4227 }
4228 return (result);
4229 }
4230
4231 /* De-quote quoted characters in STRING. */
4232 char *
4233 dequote_string (string)
4234 char *string;
4235 {
4236 register char *s, *t;
4237 size_t slen;
4238 char *result, *send;
4239 DECLARE_MBSTATE;
4240
4241 #if defined (DEBUG)
4242 if (string[0] == CTLESC && string[1] == 0)
4243 internal_inform ("dequote_string: string with bare CTLESC");
4244 #endif
4245
4246 slen = STRLEN (string);
4247
4248 t = result = (char *)xmalloc (slen + 1);
4249
4250 if (QUOTED_NULL (string))
4251 {
4252 result[0] = '\0';
4253 return (result);
4254 }
4255
4256 /* A string consisting of only a single CTLESC should pass through unchanged */
4257 if (string[0] == CTLESC && string[1] == 0)
4258 {
4259 result[0] = CTLESC;
4260 result[1] = '\0';
4261 return (result);
4262 }
4263
4264 /* If no character in the string can be quoted, don't bother examining
4265 each character. Just return a copy of the string passed to us. */
4266 if (strchr (string, CTLESC) == NULL)
4267 return (strcpy (result, string));
4268
4269 send = string + slen;
4270 s = string;
4271 while (*s)
4272 {
4273 if (*s == CTLESC)
4274 {
4275 s++;
4276 if (*s == '\0')
4277 break;
4278 }
4279 COPY_CHAR_P (t, s, send);
4280 }
4281
4282 *t = '\0';
4283 return (result);
4284 }
4285
4286 /* Quote the entire WORD_LIST list. */
4287 static WORD_LIST *
4288 quote_list (list)
4289 WORD_LIST *list;
4290 {
4291 register WORD_LIST *w;
4292 char *t;
4293
4294 for (w = list; w; w = w->next)
4295 {
4296 t = w->word->word;
4297 w->word->word = quote_string (t);
4298 if (*t == 0)
4299 w->word->flags |= W_HASQUOTEDNULL; /* XXX - turn on W_HASQUOTEDNULL here? */
4300 w->word->flags |= W_QUOTED;
4301 free (t);
4302 }
4303 return list;
4304 }
4305
4306 WORD_DESC *
4307 dequote_word (word)
4308 WORD_DESC *word;
4309 {
4310 register char *s;
4311
4312 s = dequote_string (word->word);
4313 if (QUOTED_NULL (word->word))
4314 word->flags &= ~W_HASQUOTEDNULL;
4315 free (word->word);
4316 word->word = s;
4317
4318 return word;
4319 }
4320
4321 /* De-quote quoted characters in each word in LIST. */
4322 WORD_LIST *
4323 dequote_list (list)
4324 WORD_LIST *list;
4325 {
4326 register char *s;
4327 register WORD_LIST *tlist;
4328
4329 for (tlist = list; tlist; tlist = tlist->next)
4330 {
4331 s = dequote_string (tlist->word->word);
4332 if (QUOTED_NULL (tlist->word->word))
4333 tlist->word->flags &= ~W_HASQUOTEDNULL;
4334 free (tlist->word->word);
4335 tlist->word->word = s;
4336 }
4337 return list;
4338 }
4339
4340 /* Remove CTLESC protecting a CTLESC or CTLNUL in place. Return the passed
4341 string. */
4342 char *
4343 remove_quoted_escapes (string)
4344 char *string;
4345 {
4346 char *t;
4347
4348 if (string)
4349 {
4350 t = dequote_escapes (string);
4351 strcpy (string, t);
4352 free (t);
4353 }
4354
4355 return (string);
4356 }
4357
4358 /* Remove quoted $IFS characters from STRING. Quoted IFS characters are
4359 added to protect them from word splitting, but we need to remove them
4360 if no word splitting takes place. This returns newly-allocated memory,
4361 so callers can use it to replace savestring(). */
4362 char *
4363 remove_quoted_ifs (string)
4364 char *string;
4365 {
4366 register size_t slen;
4367 register int i, j;
4368 char *ret, *send;
4369 DECLARE_MBSTATE;
4370
4371 slen = strlen (string);
4372 send = string + slen;
4373
4374 i = j = 0;
4375 ret = (char *)xmalloc (slen + 1);
4376
4377 while (i < slen)
4378 {
4379 if (string[i] == CTLESC)
4380 {
4381 i++;
4382 if (string[i] == 0 || isifs (string[i]) == 0)
4383 ret[j++] = CTLESC;
4384 if (i == slen)
4385 break;
4386 }
4387
4388 COPY_CHAR_I (ret, j, string, send, i);
4389 }
4390 ret[j] = '\0';
4391
4392 return (ret);
4393 }
4394
4395 char *
4396 remove_quoted_nulls (string)
4397 char *string;
4398 {
4399 register size_t slen;
4400 register int i, j, prev_i;
4401 DECLARE_MBSTATE;
4402
4403 if (strchr (string, CTLNUL) == 0) /* XXX */
4404 return string; /* XXX */
4405
4406 slen = strlen (string);
4407 i = j = 0;
4408
4409 while (i < slen)
4410 {
4411 if (string[i] == CTLESC)
4412 {
4413 /* Old code had j++, but we cannot assume that i == j at this
4414 point -- what if a CTLNUL has already been removed from the
4415 string? We don't want to drop the CTLESC or recopy characters
4416 that we've already copied down. */
4417 i++;
4418 string[j++] = CTLESC;
4419 if (i == slen)
4420 break;
4421 }
4422 else if (string[i] == CTLNUL)
4423 {
4424 i++;
4425 continue;
4426 }
4427
4428 prev_i = i;
4429 ADVANCE_CHAR (string, slen, i); /* COPY_CHAR_I? */
4430 if (j < prev_i)
4431 {
4432 do string[j++] = string[prev_i++]; while (prev_i < i);
4433 }
4434 else
4435 j = i;
4436 }
4437 string[j] = '\0';
4438
4439 return (string);
4440 }
4441
4442 /* Perform quoted null character removal on each element of LIST.
4443 This modifies LIST. */
4444 void
4445 word_list_remove_quoted_nulls (list)
4446 WORD_LIST *list;
4447 {
4448 register WORD_LIST *t;
4449
4450 for (t = list; t; t = t->next)
4451 {
4452 remove_quoted_nulls (t->word->word);
4453 t->word->flags &= ~W_HASQUOTEDNULL;
4454 }
4455 }
4456
4457 /* **************************************************************** */
4458 /* */
4459 /* Functions for Matching and Removing Patterns */
4460 /* */
4461 /* **************************************************************** */
4462
4463 #if defined (HANDLE_MULTIBYTE)
4464 # ifdef INCLUDE_UNUSED
4465 static unsigned char *
4466 mb_getcharlens (string, len)
4467 char *string;
4468 int len;
4469 {
4470 int i, offset, last;
4471 unsigned char *ret;
4472 char *p;
4473 DECLARE_MBSTATE;
4474
4475 i = offset = 0;
4476 last = 0;
4477 ret = (unsigned char *)xmalloc (len);
4478 memset (ret, 0, len);
4479 while (string[last])
4480 {
4481 ADVANCE_CHAR (string, len, offset);
4482 ret[last] = offset - last;
4483 last = offset;
4484 }
4485 return ret;
4486 }
4487 # endif
4488 #endif
4489
4490 /* Remove the portion of PARAM matched by PATTERN according to OP, where OP
4491 can have one of 4 values:
4492 RP_LONG_LEFT remove longest matching portion at start of PARAM
4493 RP_SHORT_LEFT remove shortest matching portion at start of PARAM
4494 RP_LONG_RIGHT remove longest matching portion at end of PARAM
4495 RP_SHORT_RIGHT remove shortest matching portion at end of PARAM
4496 */
4497
4498 #define RP_LONG_LEFT 1
4499 #define RP_SHORT_LEFT 2
4500 #define RP_LONG_RIGHT 3
4501 #define RP_SHORT_RIGHT 4
4502
4503 /* Returns its first argument if nothing matched; new memory otherwise */
4504 static char *
4505 remove_upattern (param, pattern, op)
4506 char *param, *pattern;
4507 int op;
4508 {
4509 register size_t len;
4510 register char *end;
4511 register char *p, *ret, c;
4512
4513 len = STRLEN (param);
4514 end = param + len;
4515
4516 switch (op)
4517 {
4518 case RP_LONG_LEFT: /* remove longest match at start */
4519 for (p = end; p >= param; p--)
4520 {
4521 c = *p; *p = '\0';
4522 if (strmatch (pattern, param, FNMATCH_EXTFLAG) != FNM_NOMATCH)
4523 {
4524 *p = c;
4525 return (savestring (p));
4526 }
4527 *p = c;
4528
4529 }
4530 break;
4531
4532 case RP_SHORT_LEFT: /* remove shortest match at start */
4533 for (p = param; p <= end; p++)
4534 {
4535 c = *p; *p = '\0';
4536 if (strmatch (pattern, param, FNMATCH_EXTFLAG) != FNM_NOMATCH)
4537 {
4538 *p = c;
4539 return (savestring (p));
4540 }
4541 *p = c;
4542 }
4543 break;
4544
4545 case RP_LONG_RIGHT: /* remove longest match at end */
4546 for (p = param; p <= end; p++)
4547 {
4548 if (strmatch (pattern, p, FNMATCH_EXTFLAG) != FNM_NOMATCH)
4549 {
4550 c = *p; *p = '\0';
4551 ret = savestring (param);
4552 *p = c;
4553 return (ret);
4554 }
4555 }
4556 break;
4557
4558 case RP_SHORT_RIGHT: /* remove shortest match at end */
4559 for (p = end; p >= param; p--)
4560 {
4561 if (strmatch (pattern, p, FNMATCH_EXTFLAG) != FNM_NOMATCH)
4562 {
4563 c = *p; *p = '\0';
4564 ret = savestring (param);
4565 *p = c;
4566 return (ret);
4567 }
4568 }
4569 break;
4570 }
4571
4572 return (param); /* no match, return original string */
4573 }
4574
4575 #if defined (HANDLE_MULTIBYTE)
4576 /* Returns its first argument if nothing matched; new memory otherwise */
4577 static wchar_t *
4578 remove_wpattern (wparam, wstrlen, wpattern, op)
4579 wchar_t *wparam;
4580 size_t wstrlen;
4581 wchar_t *wpattern;
4582 int op;
4583 {
4584 wchar_t wc, *ret;
4585 int n;
4586
4587 switch (op)
4588 {
4589 case RP_LONG_LEFT: /* remove longest match at start */
4590 for (n = wstrlen; n >= 0; n--)
4591 {
4592 wc = wparam[n]; wparam[n] = L'\0';
4593 if (wcsmatch (wpattern, wparam, FNMATCH_EXTFLAG) != FNM_NOMATCH)
4594 {
4595 wparam[n] = wc;
4596 return (wcsdup (wparam + n));
4597 }
4598 wparam[n] = wc;
4599 }
4600 break;
4601
4602 case RP_SHORT_LEFT: /* remove shortest match at start */
4603 for (n = 0; n <= wstrlen; n++)
4604 {
4605 wc = wparam[n]; wparam[n] = L'\0';
4606 if (wcsmatch (wpattern, wparam, FNMATCH_EXTFLAG) != FNM_NOMATCH)
4607 {
4608 wparam[n] = wc;
4609 return (wcsdup (wparam + n));
4610 }
4611 wparam[n] = wc;
4612 }
4613 break;
4614
4615 case RP_LONG_RIGHT: /* remove longest match at end */
4616 for (n = 0; n <= wstrlen; n++)
4617 {
4618 if (wcsmatch (wpattern, wparam + n, FNMATCH_EXTFLAG) != FNM_NOMATCH)
4619 {
4620 wc = wparam[n]; wparam[n] = L'\0';
4621 ret = wcsdup (wparam);
4622 wparam[n] = wc;
4623 return (ret);
4624 }
4625 }
4626 break;
4627
4628 case RP_SHORT_RIGHT: /* remove shortest match at end */
4629 for (n = wstrlen; n >= 0; n--)
4630 {
4631 if (wcsmatch (wpattern, wparam + n, FNMATCH_EXTFLAG) != FNM_NOMATCH)
4632 {
4633 wc = wparam[n]; wparam[n] = L'\0';
4634 ret = wcsdup (wparam);
4635 wparam[n] = wc;
4636 return (ret);
4637 }
4638 }
4639 break;
4640 }
4641
4642 return (wparam); /* no match, return original string */
4643 }
4644 #endif /* HANDLE_MULTIBYTE */
4645
4646 static char *
4647 remove_pattern (param, pattern, op)
4648 char *param, *pattern;
4649 int op;
4650 {
4651 char *xret;
4652
4653 if (param == NULL)
4654 return (param);
4655 if (*param == '\0' || pattern == NULL || *pattern == '\0') /* minor optimization */
4656 return (savestring (param));
4657
4658 #if defined (HANDLE_MULTIBYTE)
4659 if (MB_CUR_MAX > 1)
4660 {
4661 wchar_t *ret, *oret;
4662 size_t n;
4663 wchar_t *wparam, *wpattern;
4664 mbstate_t ps;
4665
4666 /* XXX - could optimize here by checking param and pattern for multibyte
4667 chars with mbsmbchar and calling remove_upattern. */
4668
4669 n = xdupmbstowcs (&wpattern, NULL, pattern);
4670 if (n == (size_t)-1)
4671 {
4672 xret = remove_upattern (param, pattern, op);
4673 return ((xret == param) ? savestring (param) : xret);
4674 }
4675 n = xdupmbstowcs (&wparam, NULL, param);
4676
4677 if (n == (size_t)-1)
4678 {
4679 free (wpattern);
4680 xret = remove_upattern (param, pattern, op);
4681 return ((xret == param) ? savestring (param) : xret);
4682 }
4683 oret = ret = remove_wpattern (wparam, n, wpattern, op);
4684 /* Don't bother to convert wparam back to multibyte string if nothing
4685 matched; just return copy of original string */
4686 if (ret == wparam)
4687 {
4688 free (wparam);
4689 free (wpattern);
4690 return (savestring (param));
4691 }
4692
4693 free (wparam);
4694 free (wpattern);
4695
4696 n = strlen (param);
4697 xret = (char *)xmalloc (n + 1);
4698 memset (&ps, '\0', sizeof (mbstate_t));
4699 n = wcsrtombs (xret, (const wchar_t **)&ret, n, &ps);
4700 xret[n] = '\0'; /* just to make sure */
4701 free (oret);
4702 return xret;
4703 }
4704 else
4705 #endif
4706 {
4707 xret = remove_upattern (param, pattern, op);
4708 return ((xret == param) ? savestring (param) : xret);
4709 }
4710 }
4711
4712 /* Match PAT anywhere in STRING and return the match boundaries.
4713 This returns 1 in case of a successful match, 0 otherwise. SP
4714 and EP are pointers into the string where the match begins and
4715 ends, respectively. MTYPE controls what kind of match is attempted.
4716 MATCH_BEG and MATCH_END anchor the match at the beginning and end
4717 of the string, respectively. The longest match is returned. */
4718 static int
4719 match_upattern (string, pat, mtype, sp, ep)
4720 char *string, *pat;
4721 int mtype;
4722 char **sp, **ep;
4723 {
4724 int c, mlen;
4725 size_t len;
4726 register char *p, *p1, *npat;
4727 char *end;
4728
4729 /* If the pattern doesn't match anywhere in the string, go ahead and
4730 short-circuit right away. A minor optimization, saves a bunch of
4731 unnecessary calls to strmatch (up to N calls for a string of N
4732 characters) if the match is unsuccessful. To preserve the semantics
4733 of the substring matches below, we make sure that the pattern has
4734 `*' as first and last character, making a new pattern if necessary. */
4735 /* XXX - check this later if I ever implement `**' with special meaning,
4736 since this will potentially result in `**' at the beginning or end */
4737 len = STRLEN (pat);
4738 if (pat[0] != '*' || (pat[0] == '*' && pat[1] == LPAREN && extended_glob) || pat[len - 1] != '*')
4739 {
4740 int unescaped_backslash;
4741 char *pp;
4742
4743 p = npat = (char *)xmalloc (len + 3);
4744 p1 = pat;
4745 if ((mtype != MATCH_BEG) && (*p1 != '*' || (*p1 == '*' && p1[1] == LPAREN && extended_glob)))
4746 *p++ = '*';
4747 while (*p1)
4748 *p++ = *p1++;
4749 #if 1
4750 /* Need to also handle a pattern that ends with an unescaped backslash.
4751 For right now, we ignore it because the pattern matching code will
4752 fail the match anyway */
4753 /* If the pattern ends with a `*' we leave it alone if it's preceded by
4754 an even number of backslashes, but if it's escaped by a backslash
4755 we need to add another `*'. */
4756 if ((mtype != MATCH_END) && (p1[-1] == '*' && (unescaped_backslash = p1[-2] == '\\')))
4757 {
4758 pp = p1 - 3;
4759 while (pp >= pat && *pp-- == '\\')
4760 unescaped_backslash = 1 - unescaped_backslash;
4761 if (unescaped_backslash)
4762 *p++ = '*';
4763 }
4764 else if (mtype != MATCH_END && p1[-1] != '*')
4765 *p++ = '*';
4766 #else
4767 if (p1[-1] != '*' || p1[-2] == '\\')
4768 *p++ = '*';
4769 #endif
4770 *p = '\0';
4771 }
4772 else
4773 npat = pat;
4774 c = strmatch (npat, string, FNMATCH_EXTFLAG | FNMATCH_IGNCASE);
4775 if (npat != pat)
4776 free (npat);
4777 if (c == FNM_NOMATCH)
4778 return (0);
4779
4780 len = STRLEN (string);
4781 end = string + len;
4782
4783 mlen = umatchlen (pat, len);
4784
4785 switch (mtype)
4786 {
4787 case MATCH_ANY:
4788 for (p = string; p <= end; p++)
4789 {
4790 if (match_pattern_char (pat, p, FNMATCH_IGNCASE))
4791 {
4792 p1 = (mlen == -1) ? end : p + mlen;
4793 /* p1 - p = length of portion of string to be considered
4794 p = current position in string
4795 mlen = number of characters consumed by match (-1 for entire string)
4796 end = end of string
4797 we want to break immediately if the potential match len
4798 is greater than the number of characters remaining in the
4799 string
4800 */
4801 if (p1 > end)
4802 break;
4803 for ( ; p1 >= p; p1--)
4804 {
4805 c = *p1; *p1 = '\0';
4806 if (strmatch (pat, p, FNMATCH_EXTFLAG | FNMATCH_IGNCASE) == 0)
4807 {
4808 *p1 = c;
4809 *sp = p;
4810 *ep = p1;
4811 return 1;
4812 }
4813 *p1 = c;
4814 #if 1
4815 /* If MLEN != -1, we have a fixed length pattern. */
4816 if (mlen != -1)
4817 break;
4818 #endif
4819 }
4820 }
4821 }
4822
4823 return (0);
4824
4825 case MATCH_BEG:
4826 if (match_pattern_char (pat, string, FNMATCH_IGNCASE) == 0)
4827 return (0);
4828
4829 for (p = (mlen == -1) ? end : string + mlen; p >= string; p--)
4830 {
4831 c = *p; *p = '\0';
4832 if (strmatch (pat, string, FNMATCH_EXTFLAG | FNMATCH_IGNCASE) == 0)
4833 {
4834 *p = c;
4835 *sp = string;
4836 *ep = p;
4837 return 1;
4838 }
4839 *p = c;
4840 /* If MLEN != -1, we have a fixed length pattern. */
4841 if (mlen != -1)
4842 break;
4843 }
4844
4845 return (0);
4846
4847 case MATCH_END:
4848 for (p = end - ((mlen == -1) ? len : mlen); p <= end; p++)
4849 {
4850 if (strmatch (pat, p, FNMATCH_EXTFLAG | FNMATCH_IGNCASE) == 0)
4851 {
4852 *sp = p;
4853 *ep = end;
4854 return 1;
4855 }
4856 /* If MLEN != -1, we have a fixed length pattern. */
4857 if (mlen != -1)
4858 break;
4859 }
4860
4861 return (0);
4862 }
4863
4864 return (0);
4865 }
4866
4867 #if defined (HANDLE_MULTIBYTE)
4868
4869 #define WFOLD(c) (match_ignore_case && iswupper (c) ? towlower (c) : (c))
4870
4871 /* Match WPAT anywhere in WSTRING and return the match boundaries.
4872 This returns 1 in case of a successful match, 0 otherwise. Wide
4873 character version. */
4874 static int
4875 match_wpattern (wstring, indices, wstrlen, wpat, mtype, sp, ep)
4876 wchar_t *wstring;
4877 char **indices;
4878 size_t wstrlen;
4879 wchar_t *wpat;
4880 int mtype;
4881 char **sp, **ep;
4882 {
4883 wchar_t wc, *wp, *nwpat, *wp1;
4884 size_t len;
4885 int mlen;
4886 int n, n1, n2, simple;
4887
4888 simple = (wpat[0] != L'\\' && wpat[0] != L'*' && wpat[0] != L'?' && wpat[0] != L'[');
4889 #if defined (EXTENDED_GLOB)
4890 if (extended_glob)
4891 simple &= (wpat[1] != L'(' || (wpat[0] != L'*' && wpat[0] != L'?' && wpat[0] != L'+' && wpat[0] != L'!' && wpat[0] != L'@')); /*)*/
4892 #endif
4893
4894 /* If the pattern doesn't match anywhere in the string, go ahead and
4895 short-circuit right away. A minor optimization, saves a bunch of
4896 unnecessary calls to strmatch (up to N calls for a string of N
4897 characters) if the match is unsuccessful. To preserve the semantics
4898 of the substring matches below, we make sure that the pattern has
4899 `*' as first and last character, making a new pattern if necessary. */
4900 len = wcslen (wpat);
4901 if (wpat[0] != L'*' || (wpat[0] == L'*' && wpat[1] == WLPAREN && extended_glob) || wpat[len - 1] != L'*')
4902 {
4903 int unescaped_backslash;
4904 wchar_t *wpp;
4905
4906 wp = nwpat = (wchar_t *)xmalloc ((len + 3) * sizeof (wchar_t));
4907 wp1 = wpat;
4908 if (*wp1 != L'*' || (*wp1 == '*' && wp1[1] == WLPAREN && extended_glob))
4909 *wp++ = L'*';
4910 while (*wp1 != L'\0')
4911 *wp++ = *wp1++;
4912 #if 1
4913 /* See comments above in match_upattern. */
4914 if (wp1[-1] == L'*' && (unescaped_backslash = wp1[-2] == L'\\'))
4915 {
4916 wpp = wp1 - 3;
4917 while (wpp >= wpat && *wpp-- == L'\\')
4918 unescaped_backslash = 1 - unescaped_backslash;
4919 if (unescaped_backslash)
4920 *wp++ = L'*';
4921 }
4922 else if (wp1[-1] != L'*')
4923 *wp++ = L'*';
4924 #else
4925 if (wp1[-1] != L'*' || wp1[-2] == L'\\')
4926 *wp++ = L'*';
4927 #endif
4928 *wp = '\0';
4929 }
4930 else
4931 nwpat = wpat;
4932 len = wcsmatch (nwpat, wstring, FNMATCH_EXTFLAG | FNMATCH_IGNCASE);
4933 if (nwpat != wpat)
4934 free (nwpat);
4935 if (len == FNM_NOMATCH)
4936 return (0);
4937
4938 mlen = wmatchlen (wpat, wstrlen);
4939
4940 /* itrace("wmatchlen (%ls) -> %d", wpat, mlen); */
4941 switch (mtype)
4942 {
4943 case MATCH_ANY:
4944 for (n = 0; n <= wstrlen; n++)
4945 {
4946 n2 = simple ? (WFOLD(*wpat) == WFOLD(wstring[n])) : match_pattern_wchar (wpat, wstring + n, FNMATCH_IGNCASE);
4947 if (n2)
4948 {
4949 n1 = (mlen == -1) ? wstrlen : n + mlen;
4950 if (n1 > wstrlen)
4951 break;
4952
4953 for ( ; n1 >= n; n1--)
4954 {
4955 wc = wstring[n1]; wstring[n1] = L'\0';
4956 if (wcsmatch (wpat, wstring + n, FNMATCH_EXTFLAG | FNMATCH_IGNCASE) == 0)
4957 {
4958 wstring[n1] = wc;
4959 *sp = indices[n];
4960 *ep = indices[n1];
4961 return 1;
4962 }
4963 wstring[n1] = wc;
4964 /* If MLEN != -1, we have a fixed length pattern. */
4965 if (mlen != -1)
4966 break;
4967 }
4968 }
4969 }
4970
4971 return (0);
4972
4973 case MATCH_BEG:
4974 if (match_pattern_wchar (wpat, wstring, FNMATCH_IGNCASE) == 0)
4975 return (0);
4976
4977 for (n = (mlen == -1) ? wstrlen : mlen; n >= 0; n--)
4978 {
4979 wc = wstring[n]; wstring[n] = L'\0';
4980 if (wcsmatch (wpat, wstring, FNMATCH_EXTFLAG | FNMATCH_IGNCASE) == 0)
4981 {
4982 wstring[n] = wc;
4983 *sp = indices[0];
4984 *ep = indices[n];
4985 return 1;
4986 }
4987 wstring[n] = wc;
4988 /* If MLEN != -1, we have a fixed length pattern. */
4989 if (mlen != -1)
4990 break;
4991 }
4992
4993 return (0);
4994
4995 case MATCH_END:
4996 for (n = wstrlen - ((mlen == -1) ? wstrlen : mlen); n <= wstrlen; n++)
4997 {
4998 if (wcsmatch (wpat, wstring + n, FNMATCH_EXTFLAG | FNMATCH_IGNCASE) == 0)
4999 {
5000 *sp = indices[n];
5001 *ep = indices[wstrlen];
5002 return 1;
5003 }
5004 /* If MLEN != -1, we have a fixed length pattern. */
5005 if (mlen != -1)
5006 break;
5007 }
5008
5009 return (0);
5010 }
5011
5012 return (0);
5013 }
5014 #undef WFOLD
5015 #endif /* HANDLE_MULTIBYTE */
5016
5017 static int
5018 match_pattern (string, pat, mtype, sp, ep)
5019 char *string, *pat;
5020 int mtype;
5021 char **sp, **ep;
5022 {
5023 #if defined (HANDLE_MULTIBYTE)
5024 int ret;
5025 size_t n;
5026 wchar_t *wstring, *wpat;
5027 char **indices;
5028 #endif
5029
5030 if (string == 0 || pat == 0 || *pat == 0)
5031 return (0);
5032
5033 #if defined (HANDLE_MULTIBYTE)
5034 if (MB_CUR_MAX > 1)
5035 {
5036 if (mbsmbchar (string) == 0 && mbsmbchar (pat) == 0)
5037 return (match_upattern (string, pat, mtype, sp, ep));
5038
5039 n = xdupmbstowcs (&wpat, NULL, pat);
5040 if (n == (size_t)-1)
5041 return (match_upattern (string, pat, mtype, sp, ep));
5042 n = xdupmbstowcs (&wstring, &indices, string);
5043 if (n == (size_t)-1)
5044 {
5045 free (wpat);
5046 return (match_upattern (string, pat, mtype, sp, ep));
5047 }
5048 ret = match_wpattern (wstring, indices, n, wpat, mtype, sp, ep);
5049
5050 free (wpat);
5051 free (wstring);
5052 free (indices);
5053
5054 return (ret);
5055 }
5056 else
5057 #endif
5058 return (match_upattern (string, pat, mtype, sp, ep));
5059 }
5060
5061 static int
5062 getpatspec (c, value)
5063 int c;
5064 char *value;
5065 {
5066 if (c == '#')
5067 return ((*value == '#') ? RP_LONG_LEFT : RP_SHORT_LEFT);
5068 else /* c == '%' */
5069 return ((*value == '%') ? RP_LONG_RIGHT : RP_SHORT_RIGHT);
5070 }
5071
5072 /* Posix.2 says that the WORD should be run through tilde expansion,
5073 parameter expansion, command substitution and arithmetic expansion.
5074 This leaves the result quoted, so quote_string_for_globbing () has
5075 to be called to fix it up for strmatch (). If QUOTED is non-zero,
5076 it means that the entire expression was enclosed in double quotes.
5077 This means that quoting characters in the pattern do not make any
5078 special pattern characters quoted. For example, the `*' in the
5079 following retains its special meaning: "${foo#'*'}". */
5080 static char *
5081 getpattern (value, quoted, expandpat)
5082 char *value;
5083 int quoted, expandpat;
5084 {
5085 char *pat, *tword;
5086 WORD_LIST *l;
5087 #if 0
5088 int i;
5089 #endif
5090 /* There is a problem here: how to handle single or double quotes in the
5091 pattern string when the whole expression is between double quotes?
5092 POSIX.2 says that enclosing double quotes do not cause the pattern to
5093 be quoted, but does that leave us a problem with @ and array[@] and their
5094 expansions inside a pattern? */
5095 #if 0
5096 if (expandpat && (quoted & (Q_HERE_DOCUMENT|Q_DOUBLE_QUOTES)) && *tword)
5097 {
5098 i = 0;
5099 pat = string_extract_double_quoted (tword, &i, SX_STRIPDQ);
5100 free (tword);
5101 tword = pat;
5102 }
5103 #endif
5104
5105 /* expand_string_for_pat () leaves WORD quoted and does not perform
5106 word splitting. */
5107 l = *value ? expand_string_for_pat (value,
5108 (quoted & (Q_HERE_DOCUMENT|Q_DOUBLE_QUOTES)) ? Q_PATQUOTE : quoted,
5109 (int *)NULL, (int *)NULL)
5110 : (WORD_LIST *)0;
5111 pat = string_list (l);
5112 dispose_words (l);
5113 if (pat)
5114 {
5115 tword = quote_string_for_globbing (pat, QGLOB_CVTNULL);
5116 free (pat);
5117 pat = tword;
5118 }
5119 return (pat);
5120 }
5121
5122 #if 0
5123 /* Handle removing a pattern from a string as a result of ${name%[%]value}
5124 or ${name#[#]value}. */
5125 static char *
5126 variable_remove_pattern (value, pattern, patspec, quoted)
5127 char *value, *pattern;
5128 int patspec, quoted;
5129 {
5130 char *tword;
5131
5132 tword = remove_pattern (value, pattern, patspec);
5133
5134 return (tword);
5135 }
5136 #endif
5137
5138 static char *
5139 list_remove_pattern (list, pattern, patspec, itype, quoted)
5140 WORD_LIST *list;
5141 char *pattern;
5142 int patspec, itype, quoted;
5143 {
5144 WORD_LIST *new, *l;
5145 WORD_DESC *w;
5146 char *tword;
5147
5148 for (new = (WORD_LIST *)NULL, l = list; l; l = l->next)
5149 {
5150 tword = remove_pattern (l->word->word, pattern, patspec);
5151 w = alloc_word_desc ();
5152 w->word = tword ? tword : savestring ("");
5153 new = make_word_list (w, new);
5154 }
5155
5156 l = REVERSE_LIST (new, WORD_LIST *);
5157 tword = string_list_pos_params (itype, l, quoted);
5158 dispose_words (l);
5159
5160 return (tword);
5161 }
5162
5163 static char *
5164 parameter_list_remove_pattern (itype, pattern, patspec, quoted)
5165 int itype;
5166 char *pattern;
5167 int patspec, quoted;
5168 {
5169 char *ret;
5170 WORD_LIST *list;
5171
5172 list = list_rest_of_args ();
5173 if (list == 0)
5174 return ((char *)NULL);
5175 ret = list_remove_pattern (list, pattern, patspec, itype, quoted);
5176 dispose_words (list);
5177 return (ret);
5178 }
5179
5180 #if defined (ARRAY_VARS)
5181 static char *
5182 array_remove_pattern (var, pattern, patspec, varname, quoted)
5183 SHELL_VAR *var;
5184 char *pattern;
5185 int patspec;
5186 char *varname; /* so we can figure out how it's indexed */
5187 int quoted;
5188 {
5189 ARRAY *a;
5190 HASH_TABLE *h;
5191 int itype;
5192 char *ret;
5193 WORD_LIST *list;
5194 SHELL_VAR *v;
5195
5196 /* compute itype from varname here */
5197 v = array_variable_part (varname, 0, &ret, 0);
5198
5199 /* XXX */
5200 if (v && invisible_p (v))
5201 return ((char *)NULL);
5202
5203 itype = ret[0];
5204
5205 a = (v && array_p (v)) ? array_cell (v) : 0;
5206 h = (v && assoc_p (v)) ? assoc_cell (v) : 0;
5207
5208 list = a ? array_to_word_list (a) : (h ? assoc_to_word_list (h) : 0);
5209 if (list == 0)
5210 return ((char *)NULL);
5211 ret = list_remove_pattern (list, pattern, patspec, itype, quoted);
5212 dispose_words (list);
5213
5214 return ret;
5215 }
5216 #endif /* ARRAY_VARS */
5217
5218 static char *
5219 parameter_brace_remove_pattern (varname, value, ind, patstr, rtype, quoted, flags)
5220 char *varname, *value;
5221 int ind;
5222 char *patstr;
5223 int rtype, quoted, flags;
5224 {
5225 int vtype, patspec, starsub;
5226 char *temp1, *val, *pattern, *oname;
5227 SHELL_VAR *v;
5228
5229 if (value == 0)
5230 return ((char *)NULL);
5231
5232 oname = this_command_name;
5233 this_command_name = varname;
5234
5235 vtype = get_var_and_type (varname, value, ind, quoted, flags, &v, &val);
5236 if (vtype == -1)
5237 {
5238 this_command_name = oname;
5239 return ((char *)NULL);
5240 }
5241
5242 starsub = vtype & VT_STARSUB;
5243 vtype &= ~VT_STARSUB;
5244
5245 patspec = getpatspec (rtype, patstr);
5246 if (patspec == RP_LONG_LEFT || patspec == RP_LONG_RIGHT)
5247 patstr++;
5248
5249 /* Need to pass getpattern newly-allocated memory in case of expansion --
5250 the expansion code will free the passed string on an error. */
5251 temp1 = savestring (patstr);
5252 pattern = getpattern (temp1, quoted, 1);
5253 free (temp1);
5254
5255 temp1 = (char *)NULL; /* shut up gcc */
5256 switch (vtype)
5257 {
5258 case VT_VARIABLE:
5259 case VT_ARRAYMEMBER:
5260 temp1 = remove_pattern (val, pattern, patspec);
5261 if (vtype == VT_VARIABLE)
5262 FREE (val);
5263 if (temp1)
5264 {
5265 val = (quoted & (Q_HERE_DOCUMENT|Q_DOUBLE_QUOTES))
5266 ? quote_string (temp1)
5267 : quote_escapes (temp1);
5268 free (temp1);
5269 temp1 = val;
5270 }
5271 break;
5272 #if defined (ARRAY_VARS)
5273 case VT_ARRAYVAR:
5274 temp1 = array_remove_pattern (v, pattern, patspec, varname, quoted);
5275 if (temp1 && ((quoted & (Q_HERE_DOCUMENT|Q_DOUBLE_QUOTES)) == 0))
5276 {
5277 val = quote_escapes (temp1);
5278 free (temp1);
5279 temp1 = val;
5280 }
5281 break;
5282 #endif
5283 case VT_POSPARMS:
5284 temp1 = parameter_list_remove_pattern (varname[0], pattern, patspec, quoted);
5285 if (temp1 && quoted == 0 && ifs_is_null)
5286 {
5287 /* Posix interp 888 */
5288 }
5289 else if (temp1 && ((quoted & (Q_HERE_DOCUMENT|Q_DOUBLE_QUOTES)) == 0))
5290 {
5291 val = quote_escapes (temp1);
5292 free (temp1);
5293 temp1 = val;
5294 }
5295 break;
5296 }
5297
5298 this_command_name = oname;
5299
5300 FREE (pattern);
5301 return temp1;
5302 }
5303
5304 #if defined (PROCESS_SUBSTITUTION)
5305
5306 /*****************************************************************/
5307 /* */
5308 /* Hacking Process Substitution */
5309 /* */
5310 /*****************************************************************/
5311
5312 #if !defined (HAVE_DEV_FD)
5313 /* Named pipes must be removed explicitly with `unlink'. This keeps a list
5314 of FIFOs the shell has open. unlink_fifo_list will walk the list and
5315 unlink all of them. add_fifo_list adds the name of an open FIFO to the
5316 list. NFIFO is a count of the number of FIFOs in the list. */
5317 #define FIFO_INCR 20
5318
5319 /* PROC value of -1 means the process has been reaped and the FIFO needs to
5320 be removed. PROC value of 0 means the slot is unused. */
5321 struct temp_fifo {
5322 char *file;
5323 pid_t proc;
5324 };
5325
5326 static struct temp_fifo *fifo_list = (struct temp_fifo *)NULL;
5327 static int nfifo;
5328 static int fifo_list_size;
5329
5330 void
5331 clear_fifo_list ()
5332 {
5333 }
5334
5335 char *
5336 copy_fifo_list (sizep)
5337 int *sizep;
5338 {
5339 if (sizep)
5340 *sizep = 0;
5341 return (char *)NULL;
5342 }
5343
5344 static void
5345 add_fifo_list (pathname)
5346 char *pathname;
5347 {
5348 int osize, i;
5349
5350 if (nfifo >= fifo_list_size - 1)
5351 {
5352 osize = fifo_list_size;
5353 fifo_list_size += FIFO_INCR;
5354 fifo_list = (struct temp_fifo *)xrealloc (fifo_list,
5355 fifo_list_size * sizeof (struct temp_fifo));
5356 for (i = osize; i < fifo_list_size; i++)
5357 {
5358 fifo_list[i].file = (char *)NULL;
5359 fifo_list[i].proc = 0; /* unused */
5360 }
5361 }
5362
5363 fifo_list[nfifo].file = savestring (pathname);
5364 nfifo++;
5365 }
5366
5367 void
5368 unlink_fifo (i)
5369 int i;
5370 {
5371 if ((fifo_list[i].proc == (pid_t)-1) || (fifo_list[i].proc > 0 && (kill(fifo_list[i].proc, 0) == -1)))
5372 {
5373 unlink (fifo_list[i].file);
5374 free (fifo_list[i].file);
5375 fifo_list[i].file = (char *)NULL;
5376 fifo_list[i].proc = 0;
5377 }
5378 }
5379
5380 void
5381 unlink_fifo_list ()
5382 {
5383 int saved, i, j;
5384
5385 if (nfifo == 0)
5386 return;
5387
5388 for (i = saved = 0; i < nfifo; i++)
5389 {
5390 if ((fifo_list[i].proc == (pid_t)-1) || (fifo_list[i].proc > 0 && (kill(fifo_list[i].proc, 0) == -1)))
5391 {
5392 unlink (fifo_list[i].file);
5393 free (fifo_list[i].file);
5394 fifo_list[i].file = (char *)NULL;
5395 fifo_list[i].proc = 0;
5396 }
5397 else
5398 saved++;
5399 }
5400
5401 /* If we didn't remove some of the FIFOs, compact the list. */
5402 if (saved)
5403 {
5404 for (i = j = 0; i < nfifo; i++)
5405 if (fifo_list[i].file)
5406 {
5407 fifo_list[j].file = fifo_list[i].file;
5408 fifo_list[j].proc = fifo_list[i].proc;
5409 j++;
5410 }
5411 nfifo = j;
5412 }
5413 else
5414 nfifo = 0;
5415 }
5416
5417 /* Take LIST, which is a bitmap denoting active FIFOs in fifo_list
5418 from some point in the past, and close all open FIFOs in fifo_list
5419 that are not marked as active in LIST. If LIST is NULL, close
5420 everything in fifo_list. LSIZE is the number of elements in LIST, in
5421 case it's larger than fifo_list_size (size of fifo_list). */
5422 void
5423 close_new_fifos (list, lsize)
5424 char *list;
5425 int lsize;
5426 {
5427 int i;
5428
5429 if (list == 0)
5430 {
5431 unlink_fifo_list ();
5432 return;
5433 }
5434
5435 for (i = 0; i < lsize; i++)
5436 if (list[i] == 0 && i < fifo_list_size && fifo_list[i].proc != -1)
5437 unlink_fifo (i);
5438
5439 for (i = lsize; i < fifo_list_size; i++)
5440 unlink_fifo (i);
5441 }
5442
5443 int
5444 find_procsub_child (pid)
5445 pid_t pid;
5446 {
5447 int i;
5448
5449 for (i = 0; i < nfifo; i++)
5450 if (fifo_list[i].proc == pid)
5451 return i;
5452 return -1;
5453 }
5454
5455 void
5456 set_procsub_status (ind, pid, status)
5457 int ind;
5458 pid_t pid;
5459 int status;
5460 {
5461 if (ind >= 0 && ind < nfifo)
5462 fifo_list[ind].proc = (pid_t)-1; /* sentinel */
5463 }
5464
5465 /* If we've marked the process for this procsub as dead, close the
5466 associated file descriptor and delete the FIFO. */
5467 void
5468 reap_procsubs ()
5469 {
5470 int i;
5471
5472 for (i = 0; i < nfifo; i++)
5473 if (fifo_list[i].proc == (pid_t)-1) /* reaped */
5474 unlink_fifo (i);
5475 }
5476
5477 void
5478 wait_procsubs ()
5479 {
5480 int i, r;
5481
5482 for (i = 0; i < nfifo; i++)
5483 {
5484 if (fifo_list[i].proc != (pid_t)-1 && fifo_list[i].proc > 0)
5485 {
5486 r = wait_for (fifo_list[i].proc);
5487 fifo_list[i].proc = (pid_t)-1;
5488 }
5489 }
5490 }
5491
5492 int
5493 fifos_pending ()
5494 {
5495 return nfifo;
5496 }
5497
5498 int
5499 num_fifos ()
5500 {
5501 return nfifo;
5502 }
5503
5504 static char *
5505 make_named_pipe ()
5506 {
5507 char *tname;
5508
5509 tname = sh_mktmpname ("sh-np", MT_USERANDOM|MT_USETMPDIR);
5510 if (mkfifo (tname, 0600) < 0)
5511 {
5512 free (tname);
5513 return ((char *)NULL);
5514 }
5515
5516 add_fifo_list (tname);
5517 return (tname);
5518 }
5519
5520 #else /* HAVE_DEV_FD */
5521
5522 /* DEV_FD_LIST is a bitmap of file descriptors attached to pipes the shell
5523 has open to children. NFDS is a count of the number of bits currently
5524 set in DEV_FD_LIST. TOTFDS is a count of the highest possible number
5525 of open files. */
5526 /* dev_fd_list[I] value of -1 means the process has been reaped and file
5527 descriptor I needs to be closed. Value of 0 means the slot is unused. */
5528
5529 static pid_t *dev_fd_list = (pid_t *)NULL;
5530 static int nfds;
5531 static int totfds; /* The highest possible number of open files. */
5532
5533 void
5534 clear_fifo (i)
5535 int i;
5536 {
5537 if (dev_fd_list[i])
5538 {
5539 dev_fd_list[i] = 0;
5540 nfds--;
5541 }
5542 }
5543
5544 void
5545 clear_fifo_list ()
5546 {
5547 register int i;
5548
5549 if (nfds == 0)
5550 return;
5551
5552 for (i = 0; nfds && i < totfds; i++)
5553 clear_fifo (i);
5554
5555 nfds = 0;
5556 }
5557
5558 char *
5559 copy_fifo_list (sizep)
5560 int *sizep;
5561 {
5562 char *ret;
5563
5564 if (nfds == 0 || totfds == 0)
5565 {
5566 if (sizep)
5567 *sizep = 0;
5568 return (char *)NULL;
5569 }
5570
5571 if (sizep)
5572 *sizep = totfds;
5573 ret = (char *)xmalloc (totfds * sizeof (pid_t));
5574 return (memcpy (ret, dev_fd_list, totfds * sizeof (pid_t)));
5575 }
5576
5577 static void
5578 add_fifo_list (fd)
5579 int fd;
5580 {
5581 if (dev_fd_list == 0 || fd >= totfds)
5582 {
5583 int ofds;
5584
5585 ofds = totfds;
5586 totfds = getdtablesize ();
5587 if (totfds < 0 || totfds > 256)
5588 totfds = 256;
5589 if (fd >= totfds)
5590 totfds = fd + 2;
5591
5592 dev_fd_list = (pid_t *)xrealloc (dev_fd_list, totfds * sizeof (dev_fd_list[0]));
5593 /* XXX - might need a loop for this */
5594 memset (dev_fd_list + ofds, '\0', (totfds - ofds) * sizeof (pid_t));
5595 }
5596
5597 dev_fd_list[fd] = 1; /* marker; updated later */
5598 nfds++;
5599 }
5600
5601 int
5602 fifos_pending ()
5603 {
5604 return 0; /* used for cleanup; not needed with /dev/fd */
5605 }
5606
5607 int
5608 num_fifos ()
5609 {
5610 return nfds;
5611 }
5612
5613 void
5614 unlink_fifo (fd)
5615 int fd;
5616 {
5617 if (dev_fd_list[fd])
5618 {
5619 close (fd);
5620 dev_fd_list[fd] = 0;
5621 nfds--;
5622 }
5623 }
5624
5625 void
5626 unlink_fifo_list ()
5627 {
5628 register int i;
5629
5630 if (nfds == 0)
5631 return;
5632
5633 for (i = totfds-1; nfds && i >= 0; i--)
5634 unlink_fifo (i);
5635
5636 nfds = 0;
5637 }
5638
5639 /* Take LIST, which is a snapshot copy of dev_fd_list from some point in
5640 the past, and close all open fds in dev_fd_list that are not marked
5641 as open in LIST. If LIST is NULL, close everything in dev_fd_list.
5642 LSIZE is the number of elements in LIST, in case it's larger than
5643 totfds (size of dev_fd_list). */
5644 void
5645 close_new_fifos (list, lsize)
5646 char *list;
5647 int lsize;
5648 {
5649 int i;
5650
5651 if (list == 0)
5652 {
5653 unlink_fifo_list ();
5654 return;
5655 }
5656
5657 for (i = 0; i < lsize; i++)
5658 if (list[i] == 0 && i < totfds && dev_fd_list[i])
5659 unlink_fifo (i);
5660
5661 for (i = lsize; i < totfds; i++)
5662 unlink_fifo (i);
5663 }
5664
5665 int
5666 find_procsub_child (pid)
5667 pid_t pid;
5668 {
5669 int i;
5670
5671 if (nfds == 0)
5672 return -1;
5673
5674 for (i = 0; i < totfds; i++)
5675 if (dev_fd_list[i] == pid)
5676 return i;
5677
5678 return -1;
5679 }
5680
5681 void
5682 set_procsub_status (ind, pid, status)
5683 int ind;
5684 pid_t pid;
5685 int status;
5686 {
5687 if (ind >= 0 && ind < totfds)
5688 dev_fd_list[ind] = (pid_t)-1; /* sentinel */
5689 }
5690
5691 /* If we've marked the process for this procsub as dead, close the
5692 associated file descriptor. */
5693 void
5694 reap_procsubs ()
5695 {
5696 int i;
5697
5698 for (i = 0; nfds > 0 && i < totfds; i++)
5699 if (dev_fd_list[i] == (pid_t)-1)
5700 unlink_fifo (i);
5701 }
5702
5703 void
5704 wait_procsubs ()
5705 {
5706 int i, r;
5707
5708 for (i = 0; nfds > 0 && i < totfds; i++)
5709 {
5710 if (dev_fd_list[i] != (pid_t)-1 && dev_fd_list[i] > 0)
5711 {
5712 r = wait_for (dev_fd_list[i]);
5713 dev_fd_list[i] = (pid_t)-1;
5714 }
5715 }
5716 }
5717
5718 #if defined (NOTDEF)
5719 print_dev_fd_list ()
5720 {
5721 register int i;
5722
5723 fprintf (stderr, "pid %ld: dev_fd_list:", (long)getpid ());
5724 fflush (stderr);
5725
5726 for (i = 0; i < totfds; i++)
5727 {
5728 if (dev_fd_list[i])
5729 fprintf (stderr, " %d", i);
5730 }
5731 fprintf (stderr, "\n");
5732 }
5733 #endif /* NOTDEF */
5734
5735 static char *
5736 make_dev_fd_filename (fd)
5737 int fd;
5738 {
5739 char *ret, intbuf[INT_STRLEN_BOUND (int) + 1], *p;
5740
5741 ret = (char *)xmalloc (sizeof (DEV_FD_PREFIX) + 8);
5742
5743 strcpy (ret, DEV_FD_PREFIX);
5744 p = inttostr (fd, intbuf, sizeof (intbuf));
5745 strcpy (ret + sizeof (DEV_FD_PREFIX) - 1, p);
5746
5747 add_fifo_list (fd);
5748 return (ret);
5749 }
5750
5751 #endif /* HAVE_DEV_FD */
5752
5753 /* Return a filename that will open a connection to the process defined by
5754 executing STRING. HAVE_DEV_FD, if defined, means open a pipe and return
5755 a filename in /dev/fd corresponding to a descriptor that is one of the
5756 ends of the pipe. If not defined, we use named pipes on systems that have
5757 them. Systems without /dev/fd and named pipes are out of luck.
5758
5759 OPEN_FOR_READ_IN_CHILD, if 1, means open the named pipe for reading or
5760 use the read end of the pipe and dup that file descriptor to fd 0 in
5761 the child. If OPEN_FOR_READ_IN_CHILD is 0, we open the named pipe for
5762 writing or use the write end of the pipe in the child, and dup that
5763 file descriptor to fd 1 in the child. The parent does the opposite. */
5764
5765 static char *
5766 process_substitute (string, open_for_read_in_child)
5767 char *string;
5768 int open_for_read_in_child;
5769 {
5770 char *pathname;
5771 int fd, result, rc, function_value;
5772 pid_t old_pid, pid;
5773 #if defined (HAVE_DEV_FD)
5774 int parent_pipe_fd, child_pipe_fd;
5775 int fildes[2];
5776 #endif /* HAVE_DEV_FD */
5777 #if defined (JOB_CONTROL)
5778 pid_t old_pipeline_pgrp;
5779 #endif
5780
5781 if (!string || !*string || wordexp_only)
5782 return ((char *)NULL);
5783
5784 #if !defined (HAVE_DEV_FD)
5785 pathname = make_named_pipe ();
5786 #else /* HAVE_DEV_FD */
5787 if (pipe (fildes) < 0)
5788 {
5789 sys_error ("%s", _("cannot make pipe for process substitution"));
5790 return ((char *)NULL);
5791 }
5792 /* If OPEN_FOR_READ_IN_CHILD == 1, we want to use the write end of
5793 the pipe in the parent, otherwise the read end. */
5794 parent_pipe_fd = fildes[open_for_read_in_child];
5795 child_pipe_fd = fildes[1 - open_for_read_in_child];
5796 /* Move the parent end of the pipe to some high file descriptor, to
5797 avoid clashes with FDs used by the script. */
5798 parent_pipe_fd = move_to_high_fd (parent_pipe_fd, 1, 64);
5799
5800 pathname = make_dev_fd_filename (parent_pipe_fd);
5801 #endif /* HAVE_DEV_FD */
5802
5803 if (pathname == 0)
5804 {
5805 sys_error ("%s", _("cannot make pipe for process substitution"));
5806 return ((char *)NULL);
5807 }
5808
5809 old_pid = last_made_pid;
5810
5811 #if defined (JOB_CONTROL)
5812 old_pipeline_pgrp = pipeline_pgrp;
5813 if (pipeline_pgrp == 0 || (subshell_environment & (SUBSHELL_PIPE|SUBSHELL_FORK|SUBSHELL_ASYNC)) == 0)
5814 pipeline_pgrp = shell_pgrp;
5815 save_pipeline (1);
5816 #endif /* JOB_CONTROL */
5817
5818 pid = make_child ((char *)NULL, 1);
5819 if (pid == 0)
5820 {
5821 reset_terminating_signals (); /* XXX */
5822 free_pushed_string_input ();
5823 /* Cancel traps, in trap.c. */
5824 restore_original_signals (); /* XXX - what about special builtins? bash-4.2 */
5825 QUIT; /* catch any interrupts we got post-fork */
5826 setup_async_signals ();
5827 subshell_environment |= SUBSHELL_COMSUB|SUBSHELL_PROCSUB;
5828
5829 /* We don't inherit the verbose option for command substitutions now, so
5830 let's try it for process substitutions. */
5831 change_flag ('v', FLAG_OFF);
5832
5833 /* if we're expanding a redirection, we shouldn't have access to the
5834 temporary environment, but commands in the subshell should have
5835 access to their own temporary environment. */
5836 if (expanding_redir)
5837 flush_temporary_env ();
5838 }
5839
5840 #if defined (JOB_CONTROL)
5841 set_sigchld_handler ();
5842 stop_making_children ();
5843 /* XXX - should we only do this in the parent? (as in command subst) */
5844 pipeline_pgrp = old_pipeline_pgrp;
5845 #else
5846 stop_making_children ();
5847 #endif /* JOB_CONTROL */
5848
5849 if (pid < 0)
5850 {
5851 sys_error ("%s", _("cannot make child for process substitution"));
5852 free (pathname);
5853 #if defined (HAVE_DEV_FD)
5854 close (parent_pipe_fd);
5855 close (child_pipe_fd);
5856 #endif /* HAVE_DEV_FD */
5857 #if defined (JOB_CONTROL)
5858 restore_pipeline (1);
5859 #endif
5860 return ((char *)NULL);
5861 }
5862
5863 if (pid > 0)
5864 {
5865 #if defined (JOB_CONTROL)
5866 if (last_procsub_child)
5867 discard_last_procsub_child ();
5868 last_procsub_child = restore_pipeline (0);
5869 #endif
5870
5871 #if defined (HAVE_DEV_FD)
5872 dev_fd_list[parent_pipe_fd] = pid;
5873 #else
5874 fifo_list[nfifo-1].proc = pid;
5875 #endif
5876
5877 last_made_pid = old_pid;
5878
5879 #if defined (JOB_CONTROL) && defined (PGRP_PIPE)
5880 close_pgrp_pipe ();
5881 #endif /* JOB_CONTROL && PGRP_PIPE */
5882
5883 #if defined (HAVE_DEV_FD)
5884 close (child_pipe_fd);
5885 #endif /* HAVE_DEV_FD */
5886
5887 return (pathname);
5888 }
5889
5890 set_sigint_handler ();
5891
5892 #if defined (JOB_CONTROL)
5893 /* make sure we don't have any job control */
5894 set_job_control (0);
5895
5896 /* The idea is that we want all the jobs we start from an async process
5897 substitution to be in the same process group, but not the same pgrp
5898 as our parent shell, since we don't want to affect our parent shell's
5899 jobs if we get a SIGHUP and end up calling hangup_all_jobs, for example.
5900 If pipeline_pgrp != shell_pgrp, we assume that there is a job control
5901 shell somewhere in our parent process chain (since make_child initializes
5902 pipeline_pgrp to shell_pgrp if job_control == 0). What we do in this
5903 case is to set pipeline_pgrp to our PID, so all jobs started by this
5904 process have that same pgrp and we are basically the process group leader.
5905 This should not have negative effects on child processes surviving
5906 after we exit, since we wait for the children we create, but that is
5907 something to watch for. */
5908
5909 if (pipeline_pgrp != shell_pgrp)
5910 pipeline_pgrp = getpid ();
5911 #endif /* JOB_CONTROL */
5912
5913 #if !defined (HAVE_DEV_FD)
5914 /* Open the named pipe in the child. */
5915 fd = open (pathname, open_for_read_in_child ? O_RDONLY : O_WRONLY);
5916 if (fd < 0)
5917 {
5918 /* Two separate strings for ease of translation. */
5919 if (open_for_read_in_child)
5920 sys_error (_("cannot open named pipe %s for reading"), pathname);
5921 else
5922 sys_error (_("cannot open named pipe %s for writing"), pathname);
5923
5924 exit (127);
5925 }
5926 if (open_for_read_in_child)
5927 {
5928 if (sh_unset_nodelay_mode (fd) < 0)
5929 {
5930 sys_error (_("cannot reset nodelay mode for fd %d"), fd);
5931 exit (127);
5932 }
5933 }
5934 #else /* HAVE_DEV_FD */
5935 fd = child_pipe_fd;
5936 #endif /* HAVE_DEV_FD */
5937
5938 /* Discard buffered stdio output before replacing the underlying file
5939 descriptor. */
5940 if (open_for_read_in_child == 0)
5941 fpurge (stdout);
5942
5943 if (dup2 (fd, open_for_read_in_child ? 0 : 1) < 0)
5944 {
5945 sys_error (_("cannot duplicate named pipe %s as fd %d"), pathname,
5946 open_for_read_in_child ? 0 : 1);
5947 exit (127);
5948 }
5949
5950 if (fd != (open_for_read_in_child ? 0 : 1))
5951 close (fd);
5952
5953 /* Need to close any files that this process has open to pipes inherited
5954 from its parent. */
5955 if (current_fds_to_close)
5956 {
5957 close_fd_bitmap (current_fds_to_close);
5958 current_fds_to_close = (struct fd_bitmap *)NULL;
5959 }
5960
5961 #if defined (HAVE_DEV_FD)
5962 /* Make sure we close the parent's end of the pipe and clear the slot
5963 in the fd list so it is not closed later, if reallocated by, for
5964 instance, pipe(2). */
5965 close (parent_pipe_fd);
5966 dev_fd_list[parent_pipe_fd] = 0;
5967 #endif /* HAVE_DEV_FD */
5968
5969 /* subshells shouldn't have this flag, which controls using the temporary
5970 environment for variable lookups. We have already flushed the temporary
5971 environment above in the case we're expanding a redirection, so processes
5972 executed by this command need to be able to set it independently of their
5973 parent. */
5974 expanding_redir = 0;
5975
5976 remove_quoted_escapes (string);
5977
5978 /* Give process substitution a place to jump back to on failure,
5979 so we don't go back up to main (). */
5980 result = setjmp_nosigs (top_level);
5981
5982 /* If we're running a process substitution inside a shell function,
5983 trap `return' so we don't return from the function in the subshell
5984 and go off to never-never land. */
5985 if (result == 0 && return_catch_flag)
5986 function_value = setjmp_nosigs (return_catch);
5987 else
5988 function_value = 0;
5989
5990 if (result == ERREXIT)
5991 rc = last_command_exit_value;
5992 else if (result == EXITPROG)
5993 rc = last_command_exit_value;
5994 else if (result)
5995 rc = EXECUTION_FAILURE;
5996 else if (function_value)
5997 rc = return_catch_value;
5998 else
5999 {
6000 subshell_level++;
6001 rc = parse_and_execute (string, "process substitution", (SEVAL_NONINT|SEVAL_NOHIST));
6002 /* leave subshell level intact for any exit trap */
6003 }
6004
6005 #if !defined (HAVE_DEV_FD)
6006 /* Make sure we close the named pipe in the child before we exit. */
6007 close (open_for_read_in_child ? 0 : 1);
6008 #endif /* !HAVE_DEV_FD */
6009
6010 last_command_exit_value = rc;
6011 rc = run_exit_trap ();
6012 exit (rc);
6013 /*NOTREACHED*/
6014 }
6015 #endif /* PROCESS_SUBSTITUTION */
6016
6017 /***********************************/
6018 /* */
6019 /* Command Substitution */
6020 /* */
6021 /***********************************/
6022
6023 static char *
6024 read_comsub (fd, quoted, flags, rflag)
6025 int fd, quoted, flags;
6026 int *rflag;
6027 {
6028 char *istring, buf[128], *bufp;
6029 int istring_index, c, tflag, skip_ctlesc, skip_ctlnul;
6030 size_t istring_size;
6031 ssize_t bufn;
6032 int nullbyte;
6033
6034 istring = (char *)NULL;
6035 istring_index = istring_size = bufn = tflag = 0;
6036
6037 skip_ctlesc = ifs_cmap[CTLESC];
6038 skip_ctlnul = ifs_cmap[CTLNUL];
6039
6040 nullbyte = 0;
6041
6042 /* Read the output of the command through the pipe. This may need to be
6043 changed to understand multibyte characters in the future. */
6044 while (1)
6045 {
6046 if (fd < 0)
6047 break;
6048 if (--bufn <= 0)
6049 {
6050 bufn = zread (fd, buf, sizeof (buf));
6051 if (bufn <= 0)
6052 break;
6053 bufp = buf;
6054 }
6055 c = *bufp++;
6056
6057 if (c == 0)
6058 {
6059 #if 1
6060 if (nullbyte == 0)
6061 {
6062 internal_warning ("%s", _("command substitution: ignored null byte in input"));
6063 nullbyte = 1;
6064 }
6065 #endif
6066 continue;
6067 }
6068
6069 /* Add the character to ISTRING, possibly after resizing it. */
6070 RESIZE_MALLOCED_BUFFER (istring, istring_index, 2, istring_size, DEFAULT_ARRAY_SIZE);
6071
6072 /* This is essentially quote_string inline */
6073 if ((quoted & (Q_HERE_DOCUMENT|Q_DOUBLE_QUOTES)) /* || c == CTLESC || c == CTLNUL */)
6074 istring[istring_index++] = CTLESC;
6075 else if ((flags & PF_ASSIGNRHS) && skip_ctlesc && c == CTLESC)
6076 istring[istring_index++] = CTLESC;
6077 /* Escape CTLESC and CTLNUL in the output to protect those characters
6078 from the rest of the word expansions (word splitting and globbing.)
6079 This is essentially quote_escapes inline. */
6080 else if (skip_ctlesc == 0 && c == CTLESC)
6081 istring[istring_index++] = CTLESC;
6082 else if ((skip_ctlnul == 0 && c == CTLNUL) || (c == ' ' && (ifs_value && *ifs_value == 0)))
6083 istring[istring_index++] = CTLESC;
6084
6085 istring[istring_index++] = c;
6086
6087 #if 0
6088 #if defined (__CYGWIN__)
6089 if (c == '\n' && istring_index > 1 && istring[istring_index - 2] == '\r')
6090 {
6091 istring_index--;
6092 istring[istring_index - 1] = '\n';
6093 }
6094 #endif
6095 #endif
6096 }
6097
6098 if (istring)
6099 istring[istring_index] = '\0';
6100
6101 /* If we read no output, just return now and save ourselves some
6102 trouble. */
6103 if (istring_index == 0)
6104 {
6105 FREE (istring);
6106 if (rflag)
6107 *rflag = tflag;
6108 return (char *)NULL;
6109 }
6110
6111 /* Strip trailing newlines from the output of the command. */
6112 if (quoted & (Q_HERE_DOCUMENT|Q_DOUBLE_QUOTES))
6113 {
6114 while (istring_index > 0)
6115 {
6116 if (istring[istring_index - 1] == '\n')
6117 {
6118 --istring_index;
6119
6120 /* If the newline was quoted, remove the quoting char. */
6121 if (istring[istring_index - 1] == CTLESC)
6122 --istring_index;
6123 }
6124 else
6125 break;
6126 }
6127 istring[istring_index] = '\0';
6128 }
6129 else
6130 strip_trailing (istring, istring_index - 1, 1);
6131
6132 if (rflag)
6133 *rflag = tflag;
6134 return istring;
6135 }
6136
6137 /* Perform command substitution on STRING. This returns a WORD_DESC * with the
6138 contained string possibly quoted. */
6139 WORD_DESC *
6140 command_substitute (string, quoted, flags)
6141 char *string;
6142 int quoted;
6143 int flags;
6144 {
6145 pid_t pid, old_pid, old_pipeline_pgrp, old_async_pid;
6146 char *istring, *s;
6147 int result, fildes[2], function_value, pflags, rc, tflag;
6148 WORD_DESC *ret;
6149
6150 istring = (char *)NULL;
6151
6152 /* Don't fork () if there is no need to. In the case of no command to
6153 run, just return NULL. */
6154 #if 1
6155 for (s = string; s && *s && (shellblank (*s) || *s == '\n'); s++)
6156 ;
6157 if (s == 0 || *s == 0)
6158 return ((WORD_DESC *)NULL);
6159 #else
6160 if (!string || !*string || (string[0] == '\n' && !string[1]))
6161 return ((WORD_DESC *)NULL);
6162 #endif
6163
6164 if (wordexp_only && read_but_dont_execute)
6165 {
6166 last_command_exit_value = EX_WEXPCOMSUB;
6167 jump_to_top_level (EXITPROG);
6168 }
6169
6170 /* We're making the assumption here that the command substitution will
6171 eventually run a command from the file system. Since we'll run
6172 maybe_make_export_env in this subshell before executing that command,
6173 the parent shell and any other shells it starts will have to remake
6174 the environment. If we make it before we fork, other shells won't
6175 have to. Don't bother if we have any temporary variable assignments,
6176 though, because the export environment will be remade after this
6177 command completes anyway, but do it if all the words to be expanded
6178 are variable assignments. */
6179 if (subst_assign_varlist == 0 || garglist == 0)
6180 maybe_make_export_env (); /* XXX */
6181
6182 /* Flags to pass to parse_and_execute() */
6183 pflags = (interactive && sourcelevel == 0) ? SEVAL_RESETLINE : 0;
6184
6185 old_pid = last_made_pid;
6186
6187 /* Pipe the output of executing STRING into the current shell. */
6188 if (pipe (fildes) < 0)
6189 {
6190 sys_error ("%s", _("cannot make pipe for command substitution"));
6191 goto error_exit;
6192 }
6193
6194 #if defined (JOB_CONTROL)
6195 old_pipeline_pgrp = pipeline_pgrp;
6196 /* Don't reset the pipeline pgrp if we're already a subshell in a pipeline. */
6197 if ((subshell_environment & SUBSHELL_PIPE) == 0)
6198 pipeline_pgrp = shell_pgrp;
6199 cleanup_the_pipeline ();
6200 #endif /* JOB_CONTROL */
6201
6202 old_async_pid = last_asynchronous_pid;
6203 pid = make_child ((char *)NULL, subshell_environment&SUBSHELL_ASYNC);
6204 last_asynchronous_pid = old_async_pid;
6205
6206 if (pid == 0)
6207 {
6208 /* Reset the signal handlers in the child, but don't free the
6209 trap strings. Set a flag noting that we have to free the
6210 trap strings if we run trap to change a signal disposition. */
6211 reset_signal_handlers ();
6212 if (ISINTERRUPT)
6213 {
6214 kill (getpid (), SIGINT);
6215 CLRINTERRUPT; /* if we're ignoring SIGINT somehow */
6216 }
6217 QUIT; /* catch any interrupts we got post-fork */
6218 subshell_environment |= SUBSHELL_RESETTRAP;
6219 }
6220
6221 #if defined (JOB_CONTROL)
6222 /* XXX DO THIS ONLY IN PARENT ? XXX */
6223 set_sigchld_handler ();
6224 stop_making_children ();
6225 if (pid != 0)
6226 pipeline_pgrp = old_pipeline_pgrp;
6227 #else
6228 stop_making_children ();
6229 #endif /* JOB_CONTROL */
6230
6231 if (pid < 0)
6232 {
6233 sys_error (_("cannot make child for command substitution"));
6234 error_exit:
6235
6236 last_made_pid = old_pid;
6237
6238 FREE (istring);
6239 close (fildes[0]);
6240 close (fildes[1]);
6241 return ((WORD_DESC *)NULL);
6242 }
6243
6244 if (pid == 0)
6245 {
6246 /* The currently executing shell is not interactive. */
6247 interactive = 0;
6248
6249 set_sigint_handler (); /* XXX */
6250
6251 free_pushed_string_input ();
6252
6253 /* Discard buffered stdio output before replacing the underlying file
6254 descriptor. */
6255 fpurge (stdout);
6256
6257 if (dup2 (fildes[1], 1) < 0)
6258 {
6259 sys_error ("%s", _("command_substitute: cannot duplicate pipe as fd 1"));
6260 exit (EXECUTION_FAILURE);
6261 }
6262
6263 /* If standard output is closed in the parent shell
6264 (such as after `exec >&-'), file descriptor 1 will be
6265 the lowest available file descriptor, and end up in
6266 fildes[0]. This can happen for stdin and stderr as well,
6267 but stdout is more important -- it will cause no output
6268 to be generated from this command. */
6269 if ((fildes[1] != fileno (stdin)) &&
6270 (fildes[1] != fileno (stdout)) &&
6271 (fildes[1] != fileno (stderr)))
6272 close (fildes[1]);
6273
6274 if ((fildes[0] != fileno (stdin)) &&
6275 (fildes[0] != fileno (stdout)) &&
6276 (fildes[0] != fileno (stderr)))
6277 close (fildes[0]);
6278
6279 #ifdef __CYGWIN__
6280 /* Let stdio know the fd may have changed from text to binary mode, and
6281 make sure to preserve stdout line buffering. */
6282 freopen (NULL, "w", stdout);
6283 sh_setlinebuf (stdout);
6284 #endif /* __CYGWIN__ */
6285
6286 /* This is a subshell environment. */
6287 subshell_environment |= SUBSHELL_COMSUB;
6288
6289 /* Many shells do not appear to inherit the -v option for command
6290 substitutions. */
6291 change_flag ('v', FLAG_OFF);
6292
6293 /* When inherit_errexit option is not enabled, command substitution does
6294 not inherit the -e flag. It is enabled when Posix mode is enabled */
6295 if (inherit_errexit == 0)
6296 {
6297 builtin_ignoring_errexit = 0;
6298 change_flag ('e', FLAG_OFF);
6299 }
6300 set_shellopts ();
6301
6302 /* If we are expanding a redirection, we can dispose of any temporary
6303 environment we received, since redirections are not supposed to have
6304 access to the temporary environment. We will have to see whether this
6305 affects temporary environments supplied to `eval', but the temporary
6306 environment gets copied to builtin_env at some point. */
6307 if (expanding_redir)
6308 {
6309 flush_temporary_env ();
6310 expanding_redir = 0;
6311 }
6312
6313 remove_quoted_escapes (string);
6314
6315 startup_state = 2; /* see if we can avoid a fork */
6316 parse_and_execute_level = 0;
6317
6318 /* Give command substitution a place to jump back to on failure,
6319 so we don't go back up to main (). */
6320 result = setjmp_nosigs (top_level);
6321
6322 /* If we're running a command substitution inside a shell function,
6323 trap `return' so we don't return from the function in the subshell
6324 and go off to never-never land. */
6325 if (result == 0 && return_catch_flag)
6326 function_value = setjmp_nosigs (return_catch);
6327 else
6328 function_value = 0;
6329
6330 if (result == ERREXIT)
6331 rc = last_command_exit_value;
6332 else if (result == EXITPROG)
6333 rc = last_command_exit_value;
6334 else if (result)
6335 rc = EXECUTION_FAILURE;
6336 else if (function_value)
6337 rc = return_catch_value;
6338 else
6339 {
6340 subshell_level++;
6341 rc = parse_and_execute (string, "command substitution", pflags|SEVAL_NOHIST);
6342 /* leave subshell level intact for any exit trap */
6343 }
6344
6345 last_command_exit_value = rc;
6346 rc = run_exit_trap ();
6347 #if defined (PROCESS_SUBSTITUTION)
6348 unlink_fifo_list ();
6349 #endif
6350 exit (rc);
6351 }
6352 else
6353 {
6354 #if defined (JOB_CONTROL) && defined (PGRP_PIPE)
6355 close_pgrp_pipe ();
6356 #endif /* JOB_CONTROL && PGRP_PIPE */
6357
6358 close (fildes[1]);
6359
6360 tflag = 0;
6361 istring = read_comsub (fildes[0], quoted, flags, &tflag);
6362
6363 close (fildes[0]);
6364
6365 current_command_subst_pid = pid;
6366 last_command_exit_value = wait_for (pid);
6367 last_command_subst_pid = pid;
6368 last_made_pid = old_pid;
6369
6370 #if defined (JOB_CONTROL)
6371 /* If last_command_exit_value > 128, then the substituted command
6372 was terminated by a signal. If that signal was SIGINT, then send
6373 SIGINT to ourselves. This will break out of loops, for instance. */
6374 if (last_command_exit_value == (128 + SIGINT) && last_command_exit_signal == SIGINT)
6375 kill (getpid (), SIGINT);
6376
6377 /* wait_for gives the terminal back to shell_pgrp. If some other
6378 process group should have it, give it away to that group here.
6379 pipeline_pgrp is non-zero only while we are constructing a
6380 pipeline, so what we are concerned about is whether or not that
6381 pipeline was started in the background. A pipeline started in
6382 the background should never get the tty back here. We duplicate
6383 the conditions that wait_for tests to make sure we only give
6384 the terminal back to pipeline_pgrp under the conditions that wait_for
6385 gave it to shell_pgrp. If wait_for doesn't mess with the terminal
6386 pgrp, we should not either. */
6387 if (interactive && pipeline_pgrp != (pid_t)0 && running_in_background == 0 &&
6388 (subshell_environment & (SUBSHELL_ASYNC|SUBSHELL_PIPE)) == 0)
6389 give_terminal_to (pipeline_pgrp, 0);
6390 #endif /* JOB_CONTROL */
6391
6392 ret = alloc_word_desc ();
6393 ret->word = istring;
6394 ret->flags = tflag;
6395
6396 return ret;
6397 }
6398 }
6399
6400 /********************************************************
6401 * *
6402 * Utility functions for parameter expansion *
6403 * *
6404 ********************************************************/
6405
6406 #if defined (ARRAY_VARS)
6407
6408 static arrayind_t
6409 array_length_reference (s)
6410 char *s;
6411 {
6412 int len;
6413 arrayind_t ind;
6414 char *akey;
6415 char *t, c;
6416 ARRAY *array;
6417 HASH_TABLE *h;
6418 SHELL_VAR *var;
6419
6420 var = array_variable_part (s, 0, &t, &len);
6421
6422 /* If unbound variables should generate an error, report one and return
6423 failure. */
6424 if ((var == 0 || invisible_p (var) || (assoc_p (var) == 0 && array_p (var) == 0)) && unbound_vars_is_error)
6425 {
6426 c = *--t;
6427 *t = '\0';
6428 last_command_exit_value = EXECUTION_FAILURE;
6429 err_unboundvar (s);
6430 *t = c;
6431 return (-1);
6432 }
6433 else if (var == 0 || invisible_p (var))
6434 return 0;
6435
6436 /* We support a couple of expansions for variables that are not arrays.
6437 We'll return the length of the value for v[0], and 1 for v[@] or
6438 v[*]. Return 0 for everything else. */
6439
6440 array = array_p (var) ? array_cell (var) : (ARRAY *)NULL;
6441 h = assoc_p (var) ? assoc_cell (var) : (HASH_TABLE *)NULL;
6442
6443 if (ALL_ELEMENT_SUB (t[0]) && t[1] == RBRACK)
6444 {
6445 if (assoc_p (var))
6446 return (h ? assoc_num_elements (h) : 0);
6447 else if (array_p (var))
6448 return (array ? array_num_elements (array) : 0);
6449 else
6450 return (var_isset (var) ? 1 : 0);
6451 }
6452
6453 if (assoc_p (var))
6454 {
6455 t[len - 1] = '\0';
6456 akey = expand_assignment_string_to_string (t, 0); /* [ */
6457 t[len - 1] = RBRACK;
6458 if (akey == 0 || *akey == 0)
6459 {
6460 err_badarraysub (t);
6461 FREE (akey);
6462 return (-1);
6463 }
6464 t = assoc_reference (assoc_cell (var), akey);
6465 free (akey);
6466 }
6467 else
6468 {
6469 ind = array_expand_index (var, t, len, 0);
6470 /* negative subscripts to indexed arrays count back from end */
6471 if (var && array_p (var) && ind < 0)
6472 ind = array_max_index (array_cell (var)) + 1 + ind;
6473 if (ind < 0)
6474 {
6475 err_badarraysub (t);
6476 return (-1);
6477 }
6478 if (array_p (var))
6479 t = array_reference (array, ind);
6480 else
6481 t = (ind == 0) ? value_cell (var) : (char *)NULL;
6482 }
6483
6484 len = MB_STRLEN (t);
6485 return (len);
6486 }
6487 #endif /* ARRAY_VARS */
6488
6489 static int
6490 valid_brace_expansion_word (name, var_is_special)
6491 char *name;
6492 int var_is_special;
6493 {
6494 if (DIGIT (*name) && all_digits (name))
6495 return 1;
6496 else if (var_is_special)
6497 return 1;
6498 #if defined (ARRAY_VARS)
6499 else if (valid_array_reference (name, 0))
6500 return 1;
6501 #endif /* ARRAY_VARS */
6502 else if (legal_identifier (name))
6503 return 1;
6504 else
6505 return 0;
6506 }
6507
6508 static int
6509 chk_atstar (name, quoted, quoted_dollar_atp, contains_dollar_at)
6510 char *name;
6511 int quoted;
6512 int *quoted_dollar_atp, *contains_dollar_at;
6513 {
6514 char *temp1;
6515
6516 if (name == 0)
6517 {
6518 if (quoted_dollar_atp)
6519 *quoted_dollar_atp = 0;
6520 if (contains_dollar_at)
6521 *contains_dollar_at = 0;
6522 return 0;
6523 }
6524
6525 /* check for $@ and $* */
6526 if (name[0] == '@' && name[1] == 0)
6527 {
6528 if ((quoted & (Q_HERE_DOCUMENT|Q_DOUBLE_QUOTES)) && quoted_dollar_atp)
6529 *quoted_dollar_atp = 1;
6530 if (contains_dollar_at)
6531 *contains_dollar_at = 1;
6532 return 1;
6533 }
6534 else if (name[0] == '*' && name[1] == '\0' && quoted == 0)
6535 {
6536 if (contains_dollar_at)
6537 *contains_dollar_at = 1;
6538 return 1;
6539 }
6540
6541 /* Now check for ${array[@]} and ${array[*]} */
6542 #if defined (ARRAY_VARS)
6543 else if (valid_array_reference (name, 0))
6544 {
6545 temp1 = mbschr (name, LBRACK);
6546 if (temp1 && temp1[1] == '@' && temp1[2] == RBRACK)
6547 {
6548 if ((quoted & (Q_HERE_DOCUMENT|Q_DOUBLE_QUOTES)) && quoted_dollar_atp)
6549 *quoted_dollar_atp = 1;
6550 if (contains_dollar_at)
6551 *contains_dollar_at = 1;
6552 return 1;
6553 }
6554 /* ${array[*]}, when unquoted, should be treated like ${array[@]},
6555 which should result in separate words even when IFS is unset. */
6556 if (temp1 && temp1[1] == '*' && temp1[2] == RBRACK && quoted == 0)
6557 {
6558 if (contains_dollar_at)
6559 *contains_dollar_at = 1;
6560 return 1;
6561 }
6562 }
6563 #endif
6564 return 0;
6565 }
6566
6567 /* Parameter expand NAME, and return a new string which is the expansion,
6568 or NULL if there was no expansion. NAME is as given in ${NAMEcWORD}.
6569 VAR_IS_SPECIAL is non-zero if NAME is one of the special variables in
6570 the shell, e.g., "@", "$", "*", etc. QUOTED, if non-zero, means that
6571 NAME was found inside of a double-quoted expression. */
6572 static WORD_DESC *
6573 parameter_brace_expand_word (name, var_is_special, quoted, pflags, indp)
6574 char *name;
6575 int var_is_special, quoted, pflags;
6576 arrayind_t *indp;
6577 {
6578 WORD_DESC *ret;
6579 char *temp, *tt;
6580 intmax_t arg_index;
6581 SHELL_VAR *var;
6582 int atype, rflags;
6583 arrayind_t ind;
6584
6585 ret = 0;
6586 temp = 0;
6587 rflags = 0;
6588
6589 if (indp)
6590 *indp = INTMAX_MIN;
6591
6592 /* Handle multiple digit arguments, as in ${11}. */
6593 if (legal_number (name, &arg_index))
6594 {
6595 tt = get_dollar_var_value (arg_index);
6596 if (tt)
6597 temp = (*tt && (quoted & (Q_DOUBLE_QUOTES|Q_HERE_DOCUMENT)))
6598 ? quote_string (tt)
6599 : quote_escapes (tt);
6600 else
6601 temp = (char *)NULL;
6602 FREE (tt);
6603 }
6604 else if (var_is_special) /* ${@} */
6605 {
6606 int sindex;
6607 tt = (char *)xmalloc (2 + strlen (name));
6608 tt[sindex = 0] = '$';
6609 strcpy (tt + 1, name);
6610
6611 ret = param_expand (tt, &sindex, quoted, (int *)NULL, (int *)NULL,
6612 (int *)NULL, (int *)NULL, pflags);
6613 free (tt);
6614 }
6615 #if defined (ARRAY_VARS)
6616 else if (valid_array_reference (name, 0))
6617 {
6618 expand_arrayref:
6619 var = array_variable_part (name, 0, &tt, (int *)0);
6620 /* These are the cases where word splitting will not be performed */
6621 if (pflags & PF_ASSIGNRHS)
6622 {
6623 if (ALL_ELEMENT_SUB (tt[0]) && tt[1] == RBRACK)
6624 {
6625 /* Only treat as double quoted if array variable */
6626 if (var && (array_p (var) || assoc_p (var)))
6627 temp = array_value (name, quoted|Q_DOUBLE_QUOTES, AV_ASSIGNRHS, &atype, &ind);
6628 else
6629 temp = array_value (name, quoted, 0, &atype, &ind);
6630 }
6631 else
6632 temp = array_value (name, quoted, 0, &atype, &ind);
6633 }
6634 /* Posix interp 888 */
6635 else if (pflags & PF_NOSPLIT2)
6636 {
6637 /* Special cases, then general case, for each of A[@], A[*], A[n] */
6638 #if defined (HANDLE_MULTIBYTE)
6639 if (tt[0] == '@' && tt[1] == RBRACK && var && quoted == 0 && ifs_is_set && ifs_is_null == 0 && ifs_firstc[0] != ' ')
6640 #else
6641 if (tt[0] == '@' && tt[1] == RBRACK && var && quoted == 0 && ifs_is_set && ifs_is_null == 0 && ifs_firstc != ' ')
6642 #endif
6643 temp = array_value (name, Q_DOUBLE_QUOTES, AV_ASSIGNRHS, &atype, &ind);
6644 else if (tt[0] == '@' && tt[1] == RBRACK)
6645 temp = array_value (name, quoted, 0, &atype, &ind);
6646 else if (tt[0] == '*' && tt[1] == RBRACK && expand_no_split_dollar_star && ifs_is_null)
6647 temp = array_value (name, Q_DOUBLE_QUOTES|Q_HERE_DOCUMENT, 0, &atype, &ind);
6648 else if (tt[0] == '*' && tt[1] == RBRACK)
6649 temp = array_value (name, quoted, 0, &atype, &ind);
6650 else
6651 temp = array_value (name, quoted, 0, &atype, &ind);
6652 }
6653 else if (tt[0] == '*' && tt[1] == RBRACK && expand_no_split_dollar_star && ifs_is_null)
6654 temp = array_value (name, Q_DOUBLE_QUOTES|Q_HERE_DOCUMENT, 0, &atype, &ind);
6655 else
6656 temp = array_value (name, quoted, 0, &atype, &ind);
6657 if (atype == 0 && temp)
6658 {
6659 temp = (*temp && (quoted & (Q_DOUBLE_QUOTES|Q_HERE_DOCUMENT)))
6660 ? quote_string (temp)
6661 : quote_escapes (temp);
6662 rflags |= W_ARRAYIND;
6663 if (indp)
6664 *indp = ind;
6665 }
6666 else if (atype == 1 && temp && QUOTED_NULL (temp) && (quoted & (Q_DOUBLE_QUOTES|Q_HERE_DOCUMENT)))
6667 rflags |= W_HASQUOTEDNULL;
6668 }
6669 #endif
6670 else if (var = find_variable (name))
6671 {
6672 if (var_isset (var) && invisible_p (var) == 0)
6673 {
6674 #if defined (ARRAY_VARS)
6675 if (assoc_p (var))
6676 temp = assoc_reference (assoc_cell (var), "0");
6677 else if (array_p (var))
6678 temp = array_reference (array_cell (var), 0);
6679 else
6680 temp = value_cell (var);
6681 #else
6682 temp = value_cell (var);
6683 #endif
6684
6685 if (temp)
6686 temp = (*temp && (quoted & (Q_DOUBLE_QUOTES|Q_HERE_DOCUMENT)))
6687 ? quote_string (temp)
6688 : ((pflags & PF_ASSIGNRHS) ? quote_rhs (temp)
6689 : quote_escapes (temp));
6690 }
6691 else
6692 temp = (char *)NULL;
6693 }
6694 else if (var = find_variable_last_nameref (name, 0))
6695 {
6696 temp = nameref_cell (var);
6697 #if defined (ARRAY_VARS)
6698 /* Handle expanding nameref whose value is x[n] */
6699 if (temp && *temp && valid_array_reference (temp, 0))
6700 {
6701 name = temp;
6702 goto expand_arrayref;
6703 }
6704 else
6705 #endif
6706 /* y=2 ; typeset -n x=y; echo ${x} is not the same as echo ${2} in ksh */
6707 if (temp && *temp && legal_identifier (temp) == 0)
6708 {
6709 last_command_exit_value = EXECUTION_FAILURE;
6710 report_error (_("%s: invalid variable name for name reference"), temp);
6711 temp = &expand_param_error;
6712 }
6713 else
6714 temp = (char *)NULL;
6715 }
6716 else
6717 temp = (char *)NULL;
6718
6719 if (ret == 0)
6720 {
6721 ret = alloc_word_desc ();
6722 ret->word = temp;
6723 ret->flags |= rflags;
6724 }
6725 return ret;
6726 }
6727
6728 static char *
6729 parameter_brace_find_indir (name, var_is_special, quoted, find_nameref)
6730 char *name;
6731 int var_is_special, quoted, find_nameref;
6732 {
6733 char *temp, *t;
6734 WORD_DESC *w;
6735 SHELL_VAR *v;
6736 int pflags, oldex;
6737
6738 if (find_nameref && var_is_special == 0 && (v = find_variable_last_nameref (name, 0)) &&
6739 nameref_p (v) && (t = nameref_cell (v)) && *t)
6740 return (savestring (t));
6741
6742 /* If var_is_special == 0, and name is not an array reference, this does
6743 more expansion than necessary. It should really look up the variable's
6744 value and not try to expand it. */
6745 pflags = PF_IGNUNBOUND;
6746 /* Note that we're not going to be doing word splitting here */
6747 if (var_is_special)
6748 {
6749 pflags |= PF_ASSIGNRHS; /* suppresses word splitting */
6750 oldex = expand_no_split_dollar_star;
6751 expand_no_split_dollar_star = 1;
6752 }
6753 w = parameter_brace_expand_word (name, var_is_special, quoted, pflags, 0);
6754 if (var_is_special)
6755 expand_no_split_dollar_star = oldex;
6756
6757 t = w->word;
6758 /* Have to dequote here if necessary */
6759 if (t)
6760 {
6761 temp = ((quoted & (Q_DOUBLE_QUOTES|Q_HERE_DOCUMENT)) || var_is_special)
6762 ? dequote_string (t)
6763 : dequote_escapes (t);
6764 free (t);
6765 t = temp;
6766 }
6767 dispose_word_desc (w);
6768
6769 return t;
6770 }
6771
6772 /* Expand an indirect reference to a variable: ${!NAME} expands to the
6773 value of the variable whose name is the value of NAME. */
6774 static WORD_DESC *
6775 parameter_brace_expand_indir (name, var_is_special, quoted, quoted_dollar_atp, contains_dollar_at)
6776 char *name;
6777 int var_is_special, quoted;
6778 int *quoted_dollar_atp, *contains_dollar_at;
6779 {
6780 char *t;
6781 WORD_DESC *w;
6782 SHELL_VAR *v;
6783
6784 /* See if it's a nameref first, behave in ksh93-compatible fashion.
6785 There is at least one incompatibility: given ${!foo[0]} where foo=bar,
6786 bash performs an indirect lookup on foo[0] and expands the result;
6787 ksh93 expands bar[0]. We could do that here -- there are enough usable
6788 primitives to do that -- but do not at this point. */
6789 if (var_is_special == 0 && (v = find_variable_last_nameref (name, 0)))
6790 {
6791 if (nameref_p (v) && (t = nameref_cell (v)) && *t)
6792 {
6793 w = alloc_word_desc ();
6794 w->word = savestring (t);
6795 w->flags = 0;
6796 return w;
6797 }
6798 }
6799
6800 /* An indirect reference to a positional parameter or a special parameter
6801 is ok. Indirect references to array references, as explained above, are
6802 ok (currently). Only references to unset variables are errors at this
6803 point. */
6804 if (legal_identifier (name) && v == 0)
6805 {
6806 report_error (_("%s: invalid indirect expansion"), name);
6807 w = alloc_word_desc ();
6808 w->word = &expand_param_error;
6809 w->flags = 0;
6810 return (w);
6811 }
6812
6813 t = parameter_brace_find_indir (name, var_is_special, quoted, 0);
6814
6815 chk_atstar (t, quoted, quoted_dollar_atp, contains_dollar_at);
6816
6817 #if defined (ARRAY_VARS)
6818 /* Array references to unset variables are also an error */
6819 if (t == 0 && valid_array_reference (name, 0))
6820 {
6821 v = array_variable_part (name, 0, (char **)0, (int *)0);
6822 if (v == 0)
6823 {
6824 report_error (_("%s: invalid indirect expansion"), name);
6825 w = alloc_word_desc ();
6826 w->word = &expand_param_error;
6827 w->flags = 0;
6828 return (w);
6829 }
6830 else
6831 return (WORD_DESC *)NULL;
6832 }
6833 #endif
6834
6835 if (t == 0)
6836 return (WORD_DESC *)NULL;
6837
6838 if (valid_brace_expansion_word (t, SPECIAL_VAR (t, 0)) == 0)
6839 {
6840 report_error (_("%s: invalid variable name"), t);
6841 free (t);
6842 w = alloc_word_desc ();
6843 w->word = &expand_param_error;
6844 w->flags = 0;
6845 return (w);
6846 }
6847
6848 w = parameter_brace_expand_word (t, SPECIAL_VAR(t, 0), quoted, 0, 0);
6849 free (t);
6850
6851 return w;
6852 }
6853
6854 /* Expand the right side of a parameter expansion of the form ${NAMEcVALUE},
6855 depending on the value of C, the separating character. C can be one of
6856 "-", "+", or "=". QUOTED is true if the entire brace expression occurs
6857 between double quotes. */
6858 static WORD_DESC *
6859 parameter_brace_expand_rhs (name, value, op, quoted, pflags, qdollaratp, hasdollarat)
6860 char *name, *value;
6861 int op, quoted, pflags, *qdollaratp, *hasdollarat;
6862 {
6863 WORD_DESC *w;
6864 WORD_LIST *l;
6865 char *t, *t1, *temp, *vname;
6866 int l_hasdollat, sindex;
6867 SHELL_VAR *v;
6868
6869 /*itrace("parameter_brace_expand_rhs: %s:%s pflags = %d", name, value, pflags);*/
6870 /* If the entire expression is between double quotes, we want to treat
6871 the value as a double-quoted string, with the exception that we strip
6872 embedded unescaped double quotes (for sh backwards compatibility). */
6873 if ((quoted & (Q_HERE_DOCUMENT|Q_DOUBLE_QUOTES)) && *value)
6874 {
6875 sindex = 0;
6876 temp = string_extract_double_quoted (value, &sindex, SX_STRIPDQ);
6877 }
6878 else
6879 temp = value;
6880
6881 w = alloc_word_desc ();
6882 l_hasdollat = 0;
6883 l = *temp ? expand_string_for_rhs (temp, quoted, op, pflags, &l_hasdollat, (int *)NULL)
6884 : (WORD_LIST *)0;
6885 if (hasdollarat)
6886 *hasdollarat = l_hasdollat || (l && l->next);
6887 if (temp != value)
6888 free (temp);
6889 if (l)
6890 {
6891 /* If l->next is not null, we know that TEMP contained "$@", since that
6892 is the only expansion that creates more than one word. */
6893 if (qdollaratp && ((l_hasdollat && quoted) || l->next))
6894 {
6895 /*itrace("parameter_brace_expand_rhs: %s:%s: l != NULL, set *qdollaratp", name, value);*/
6896 *qdollaratp = 1;
6897 }
6898
6899 /* The expansion of TEMP returned something. We need to treat things
6900 slightly differently if L_HASDOLLAT is non-zero. If we have "$@",
6901 the individual words have already been quoted. We need to turn them
6902 into a string with the words separated by the first character of
6903 $IFS without any additional quoting, so string_list_dollar_at won't
6904 do the right thing. If IFS is null, we want "$@" to split into
6905 separate arguments, not be concatenated, so we use string_list_internal
6906 and mark the word to be split on spaces later. We use
6907 string_list_dollar_star for "$@" otherwise. */
6908 if (l->next && ifs_is_null)
6909 {
6910 temp = string_list_internal (l, " ");
6911 w->flags |= W_SPLITSPACE;
6912 }
6913 else if (l_hasdollat || l->next)
6914 temp = string_list_dollar_star (l, quoted, 0);
6915 else
6916 {
6917 temp = string_list (l);
6918 if (temp && (QUOTED_NULL (temp) == 0) && (l->word->flags & W_SAWQUOTEDNULL))
6919 w->flags |= W_SAWQUOTEDNULL; /* XXX */
6920 }
6921
6922 /* If we have a quoted null result (QUOTED_NULL(temp)) and the word is
6923 a quoted null (l->next == 0 && QUOTED_NULL(l->word->word)), the
6924 flags indicate it (l->word->flags & W_HASQUOTEDNULL), and the
6925 expansion is quoted (quoted & (Q_HERE_DOCUMENT|Q_DOUBLE_QUOTES))
6926 (which is more paranoia than anything else), we need to return the
6927 quoted null string and set the flags to indicate it. */
6928 if (l->next == 0 && (quoted & (Q_HERE_DOCUMENT|Q_DOUBLE_QUOTES)) && QUOTED_NULL (temp) && QUOTED_NULL (l->word->word) && (l->word->flags & W_HASQUOTEDNULL))
6929 {
6930 w->flags |= W_HASQUOTEDNULL;
6931 /*itrace("parameter_brace_expand_rhs (%s:%s): returning quoted null, turning off qdollaratp", name, value);*/
6932 /* If we return a quoted null with L_HASDOLLARAT, we either have a
6933 construct like "${@-$@}" or "${@-${@-$@}}" with no positional
6934 parameters or a quoted expansion of "$@" with $1 == ''. In either
6935 case, we don't want to enable special handling of $@. */
6936 if (qdollaratp && l_hasdollat)
6937 *qdollaratp = 0;
6938 }
6939 dispose_words (l);
6940 }
6941 else if ((quoted & (Q_HERE_DOCUMENT|Q_DOUBLE_QUOTES)) && l_hasdollat)
6942 {
6943 /* Posix interp 221 changed the rules on this. The idea is that
6944 something like "$xxx$@" should expand the same as "${foo-$xxx$@}"
6945 when foo and xxx are unset. The problem is that it's not in any
6946 way backwards compatible and few other shells do it. We're eventually
6947 going to try and split the difference (heh) a little bit here. */
6948 /* l_hasdollat == 1 means we saw a quoted dollar at. */
6949
6950 /* The brace expansion occurred between double quotes and there was
6951 a $@ in TEMP. It does not matter if the $@ is quoted, as long as
6952 it does not expand to anything. In this case, we want to return
6953 a quoted empty string. Posix interp 888 */
6954 temp = make_quoted_char ('\0');
6955 w->flags |= W_HASQUOTEDNULL;
6956 /*itrace("parameter_brace_expand_rhs (%s:%s): returning quoted null", name, value);*/
6957 }
6958 else
6959 temp = (char *)NULL;
6960
6961 if (op == '-' || op == '+')
6962 {
6963 w->word = temp;
6964 return w;
6965 }
6966
6967 /* op == '=' */
6968 t1 = temp ? dequote_string (temp) : savestring ("");
6969 free (temp);
6970
6971 /* bash-4.4/5.0 */
6972 vname = name;
6973 if (*name == '!' &&
6974 (legal_variable_starter ((unsigned char)name[1]) || DIGIT (name[1]) || VALID_INDIR_PARAM (name[1])))
6975 {
6976 vname = parameter_brace_find_indir (name + 1, SPECIAL_VAR (name, 1), quoted, 1);
6977 if (vname == 0 || *vname == 0)
6978 {
6979 report_error (_("%s: invalid indirect expansion"), name);
6980 free (vname);
6981 free (t1);
6982 dispose_word (w);
6983 return &expand_wdesc_error;
6984 }
6985 if (legal_identifier (vname) == 0)
6986 {
6987 report_error (_("%s: invalid variable name"), vname);
6988 free (vname);
6989 free (t1);
6990 dispose_word (w);
6991 return &expand_wdesc_error;
6992 }
6993 }
6994
6995 #if defined (ARRAY_VARS)
6996 if (valid_array_reference (vname, 0))
6997 v = assign_array_element (vname, t1, 0);
6998 else
6999 #endif /* ARRAY_VARS */
7000 v = bind_variable (vname, t1, 0);
7001
7002 if (v == 0 || readonly_p (v) || noassign_p (v)) /* expansion error */
7003 {
7004 if ((v == 0 || readonly_p (v)) && interactive_shell == 0 && posixly_correct)
7005 {
7006 last_command_exit_value = EXECUTION_FAILURE;
7007 exp_jump_to_top_level (FORCE_EOF);
7008 }
7009 else
7010 {
7011 if (vname != name)
7012 free (vname);
7013 last_command_exit_value = EX_BADUSAGE;
7014 exp_jump_to_top_level (DISCARD);
7015 }
7016 }
7017
7018 stupidly_hack_special_variables (vname);
7019
7020 if (vname != name)
7021 free (vname);
7022
7023 /* From Posix group discussion Feb-March 2010. Issue 7 0000221 */
7024
7025 /* If we are double-quoted or if we are not going to be performing word
7026 splitting, we want to quote the value we return appropriately, like
7027 the other expansions this function handles. */
7028 w->word = (quoted & (Q_DOUBLE_QUOTES|Q_HERE_DOCUMENT)) ? quote_string (t1) : quote_escapes (t1);
7029 free (t1);
7030
7031 return w;
7032 }
7033
7034 /* Deal with the right hand side of a ${name:?value} expansion in the case
7035 that NAME is null or not set. If VALUE is non-null it is expanded and
7036 used as the error message to print, otherwise a standard message is
7037 printed. */
7038 static void
7039 parameter_brace_expand_error (name, value, check_null)
7040 char *name, *value;
7041 int check_null;
7042 {
7043 WORD_LIST *l;
7044 char *temp;
7045
7046 last_command_exit_value = EXECUTION_FAILURE; /* ensure it's non-zero */
7047 if (value && *value)
7048 {
7049 l = expand_string (value, 0);
7050 temp = string_list (l);
7051 report_error ("%s: %s", name, temp ? temp : ""); /* XXX was value not "" */
7052 FREE (temp);
7053 dispose_words (l);
7054 }
7055 else if (check_null == 0)
7056 report_error (_("%s: parameter not set"), name);
7057 else
7058 report_error (_("%s: parameter null or not set"), name);
7059
7060 /* Free the data we have allocated during this expansion, since we
7061 are about to longjmp out. */
7062 free (name);
7063 FREE (value);
7064 }
7065
7066 /* Return 1 if NAME is something for which parameter_brace_expand_length is
7067 OK to do. */
7068 static int
7069 valid_length_expression (name)
7070 char *name;
7071 {
7072 return (name[1] == '\0' || /* ${#} */
7073 ((sh_syntaxtab[(unsigned char) name[1]] & CSPECVAR) && name[2] == '\0') || /* special param */
7074 (DIGIT (name[1]) && all_digits (name + 1)) || /* ${#11} */
7075 #if defined (ARRAY_VARS)
7076 valid_array_reference (name + 1, 0) || /* ${#a[7]} */
7077 #endif
7078 legal_identifier (name + 1)); /* ${#PS1} */
7079 }
7080
7081 /* Handle the parameter brace expansion that requires us to return the
7082 length of a parameter. */
7083 static intmax_t
7084 parameter_brace_expand_length (name)
7085 char *name;
7086 {
7087 char *t, *newname;
7088 intmax_t number, arg_index;
7089 WORD_LIST *list;
7090 #if defined (ARRAY_VARS)
7091 SHELL_VAR *var;
7092 #endif
7093
7094 if (name[1] == '\0') /* ${#} */
7095 number = number_of_args ();
7096 else if (DOLLAR_AT_STAR (name[1]) && name[2] == '\0') /* ${#@}, ${#*} */
7097 number = number_of_args ();
7098 else if ((sh_syntaxtab[(unsigned char) name[1]] & CSPECVAR) && name[2] == '\0')
7099 {
7100 /* Take the lengths of some of the shell's special parameters. */
7101 switch (name[1])
7102 {
7103 case '-':
7104 t = which_set_flags ();
7105 break;
7106 case '?':
7107 t = itos (last_command_exit_value);
7108 break;
7109 case '$':
7110 t = itos (dollar_dollar_pid);
7111 break;
7112 case '!':
7113 if (last_asynchronous_pid == NO_PID)
7114 t = (char *)NULL; /* XXX - error if set -u set? */
7115 else
7116 t = itos (last_asynchronous_pid);
7117 break;
7118 case '#':
7119 t = itos (number_of_args ());
7120 break;
7121 }
7122 number = STRLEN (t);
7123 FREE (t);
7124 }
7125 #if defined (ARRAY_VARS)
7126 else if (valid_array_reference (name + 1, 0))
7127 number = array_length_reference (name + 1);
7128 #endif /* ARRAY_VARS */
7129 else
7130 {
7131 number = 0;
7132
7133 if (legal_number (name + 1, &arg_index)) /* ${#1} */
7134 {
7135 t = get_dollar_var_value (arg_index);
7136 if (t == 0 && unbound_vars_is_error)
7137 return INTMAX_MIN;
7138 number = MB_STRLEN (t);
7139 FREE (t);
7140 }
7141 #if defined (ARRAY_VARS)
7142 else if ((var = find_variable (name + 1)) && (invisible_p (var) == 0) && (array_p (var) || assoc_p (var)))
7143 {
7144 if (assoc_p (var))
7145 t = assoc_reference (assoc_cell (var), "0");
7146 else
7147 t = array_reference (array_cell (var), 0);
7148 if (t == 0 && unbound_vars_is_error)
7149 return INTMAX_MIN;
7150 number = MB_STRLEN (t);
7151 }
7152 #endif
7153 else /* ${#PS1} */
7154 {
7155 newname = savestring (name);
7156 newname[0] = '$';
7157 list = expand_string (newname, Q_DOUBLE_QUOTES);
7158 t = list ? string_list (list) : (char *)NULL;
7159 free (newname);
7160 if (list)
7161 dispose_words (list);
7162
7163 number = t ? MB_STRLEN (t) : 0;
7164 FREE (t);
7165 }
7166 }
7167
7168 return (number);
7169 }
7170
7171 /* Skip characters in SUBSTR until DELIM. SUBSTR is an arithmetic expression,
7172 so we do some ad-hoc parsing of an arithmetic expression to find
7173 the first DELIM, instead of using strchr(3). Two rules:
7174 1. If the substring contains a `(', read until closing `)'.
7175 2. If the substring contains a `?', read past one `:' for each `?'.
7176 The SD_ARITHEXP flag to skip_to_delim takes care of doing this.
7177 */
7178
7179 static char *
7180 skiparith (substr, delim)
7181 char *substr;
7182 int delim;
7183 {
7184 int i;
7185 char delims[2];
7186
7187 delims[0] = delim;
7188 delims[1] = '\0';
7189
7190 i = skip_to_delim (substr, 0, delims, SD_ARITHEXP);
7191 return (substr + i);
7192 }
7193
7194 /* Verify and limit the start and end of the desired substring. If
7195 VTYPE == 0, a regular shell variable is being used; if it is 1,
7196 then the positional parameters are being used; if it is 2, then
7197 VALUE is really a pointer to an array variable that should be used.
7198 Return value is 1 if both values were OK, 0 if there was a problem
7199 with an invalid expression, or -1 if the values were out of range. */
7200 static int
7201 verify_substring_values (v, value, substr, vtype, e1p, e2p)
7202 SHELL_VAR *v;
7203 char *value, *substr;
7204 int vtype;
7205 intmax_t *e1p, *e2p;
7206 {
7207 char *t, *temp1, *temp2;
7208 arrayind_t len;
7209 int expok;
7210 #if defined (ARRAY_VARS)
7211 ARRAY *a;
7212 HASH_TABLE *h;
7213 #endif
7214
7215 /* duplicate behavior of strchr(3) */
7216 t = skiparith (substr, ':');
7217 if (*t && *t == ':')
7218 *t = '\0';
7219 else
7220 t = (char *)0;
7221
7222 temp1 = expand_arith_string (substr, Q_DOUBLE_QUOTES);
7223 *e1p = evalexp (temp1, 0, &expok); /* XXX - EXP_EXPANDED? */
7224 free (temp1);
7225 if (expok == 0)
7226 return (0);
7227
7228 len = -1; /* paranoia */
7229 switch (vtype)
7230 {
7231 case VT_VARIABLE:
7232 case VT_ARRAYMEMBER:
7233 len = MB_STRLEN (value);
7234 break;
7235 case VT_POSPARMS:
7236 len = number_of_args () + 1;
7237 if (*e1p == 0)
7238 len++; /* add one arg if counting from $0 */
7239 break;
7240 #if defined (ARRAY_VARS)
7241 case VT_ARRAYVAR:
7242 /* For arrays, the first value deals with array indices. Negative
7243 offsets count from one past the array's maximum index. Associative
7244 arrays treat the number of elements as the maximum index. */
7245 if (assoc_p (v))
7246 {
7247 h = assoc_cell (v);
7248 len = assoc_num_elements (h) + (*e1p < 0);
7249 }
7250 else
7251 {
7252 a = (ARRAY *)value;
7253 len = array_max_index (a) + (*e1p < 0); /* arrays index from 0 to n - 1 */
7254 }
7255 break;
7256 #endif
7257 }
7258
7259 if (len == -1) /* paranoia */
7260 return -1;
7261
7262 if (*e1p < 0) /* negative offsets count from end */
7263 *e1p += len;
7264
7265 if (*e1p > len || *e1p < 0)
7266 return (-1);
7267
7268 #if defined (ARRAY_VARS)
7269 /* For arrays, the second offset deals with the number of elements. */
7270 if (vtype == VT_ARRAYVAR)
7271 len = assoc_p (v) ? assoc_num_elements (h) : array_num_elements (a);
7272 #endif
7273
7274 if (t)
7275 {
7276 t++;
7277 temp2 = savestring (t);
7278 temp1 = expand_arith_string (temp2, Q_DOUBLE_QUOTES);
7279 free (temp2);
7280 t[-1] = ':';
7281 *e2p = evalexp (temp1, 0, &expok); /* XXX - EXP_EXPANDED? */
7282 free (temp1);
7283 if (expok == 0)
7284 return (0);
7285
7286 /* Should we allow positional parameter length < 0 to count backwards
7287 from end of positional parameters? */
7288 #if 1
7289 if ((vtype == VT_ARRAYVAR || vtype == VT_POSPARMS) && *e2p < 0)
7290 #else
7291 /* XXX - TAG: bash-5.1 */
7292 if (vtype == VT_ARRAYVAR && *e2p < 0)
7293 #endif
7294 {
7295 internal_error (_("%s: substring expression < 0"), t);
7296 return (0);
7297 }
7298 #if defined (ARRAY_VARS)
7299 /* In order to deal with sparse arrays, push the intelligence about how
7300 to deal with the number of elements desired down to the array-
7301 specific functions. */
7302 if (vtype != VT_ARRAYVAR)
7303 #endif
7304 {
7305 if (*e2p < 0)
7306 {
7307 *e2p += len;
7308 if (*e2p < 0 || *e2p < *e1p)
7309 {
7310 internal_error (_("%s: substring expression < 0"), t);
7311 return (0);
7312 }
7313 }
7314 else
7315 *e2p += *e1p; /* want E2 chars starting at E1 */
7316 if (*e2p > len)
7317 *e2p = len;
7318 }
7319 }
7320 else
7321 *e2p = len;
7322
7323 return (1);
7324 }
7325
7326 /* Return the type of variable specified by VARNAME (simple variable,
7327 positional param, or array variable). Also return the value specified
7328 by VARNAME (value of a variable or a reference to an array element).
7329 QUOTED is the standard description of quoting state, using Q_* defines.
7330 FLAGS is currently a set of flags to pass to array_value. If IND is
7331 non-null and not INTMAX_MIN, and FLAGS includes AV_USEIND, IND is
7332 passed to array_value so the array index is not computed again.
7333 If this returns VT_VARIABLE, the caller assumes that CTLESC and CTLNUL
7334 characters in the value are quoted with CTLESC and takes appropriate
7335 steps. For convenience, *VALP is set to the dequoted VALUE. */
7336 static int
7337 get_var_and_type (varname, value, ind, quoted, flags, varp, valp)
7338 char *varname, *value;
7339 arrayind_t ind;
7340 int quoted, flags;
7341 SHELL_VAR **varp;
7342 char **valp;
7343 {
7344 int vtype, want_indir;
7345 char *temp, *vname;
7346 SHELL_VAR *v;
7347 arrayind_t lind;
7348
7349 want_indir = *varname == '!' &&
7350 (legal_variable_starter ((unsigned char)varname[1]) || DIGIT (varname[1])
7351 || VALID_INDIR_PARAM (varname[1]));
7352 if (want_indir)
7353 vname = parameter_brace_find_indir (varname+1, SPECIAL_VAR (varname, 1), quoted, 1);
7354 /* XXX - what if vname == 0 || *vname == 0 ? */
7355 else
7356 vname = varname;
7357
7358 if (vname == 0)
7359 {
7360 vtype = VT_VARIABLE;
7361 *varp = (SHELL_VAR *)NULL;
7362 *valp = (char *)NULL;
7363 return (vtype);
7364 }
7365
7366 /* This sets vtype to VT_VARIABLE or VT_POSPARMS */
7367 vtype = STR_DOLLAR_AT_STAR (vname);
7368 if (vtype == VT_POSPARMS && vname[0] == '*')
7369 vtype |= VT_STARSUB;
7370 *varp = (SHELL_VAR *)NULL;
7371
7372 #if defined (ARRAY_VARS)
7373 if (valid_array_reference (vname, 0))
7374 {
7375 v = array_variable_part (vname, 0, &temp, (int *)0);
7376 /* If we want to signal array_value to use an already-computed index,
7377 set LIND to that index */
7378 lind = (ind != INTMAX_MIN && (flags & AV_USEIND)) ? ind : 0;
7379 if (v && invisible_p (v))
7380 {
7381 vtype = VT_ARRAYMEMBER;
7382 *varp = (SHELL_VAR *)NULL;
7383 *valp = (char *)NULL;
7384 }
7385 if (v && (array_p (v) || assoc_p (v)))
7386 {
7387 if (ALL_ELEMENT_SUB (temp[0]) && temp[1] == RBRACK)
7388 {
7389 /* Callers have to differentiate between indexed and associative */
7390 vtype = VT_ARRAYVAR;
7391 if (temp[0] == '*')
7392 vtype |= VT_STARSUB;
7393 *valp = array_p (v) ? (char *)array_cell (v) : (char *)assoc_cell (v);
7394 }
7395 else
7396 {
7397 vtype = VT_ARRAYMEMBER;
7398 *valp = array_value (vname, Q_DOUBLE_QUOTES, flags, (int *)NULL, &lind);
7399 }
7400 *varp = v;
7401 }
7402 else if (v && (ALL_ELEMENT_SUB (temp[0]) && temp[1] == RBRACK))
7403 {
7404 vtype = VT_VARIABLE;
7405 *varp = v;
7406 if (quoted & (Q_DOUBLE_QUOTES|Q_HERE_DOCUMENT))
7407 *valp = value ? dequote_string (value) : savestring ("");
7408 else
7409 *valp = value ? dequote_escapes (value) : (char *)NULL;
7410 }
7411 else
7412 {
7413 vtype = VT_ARRAYMEMBER;
7414 *varp = v;
7415 *valp = array_value (vname, Q_DOUBLE_QUOTES, flags, (int *)NULL, &lind);
7416 }
7417 }
7418 else if ((v = find_variable (vname)) && (invisible_p (v) == 0) && (assoc_p (v) || array_p (v)))
7419 {
7420 vtype = VT_ARRAYMEMBER;
7421 *varp = v;
7422 *valp = assoc_p (v) ? assoc_reference (assoc_cell (v), "0") : array_reference (array_cell (v), 0);
7423 }
7424 else
7425 #endif
7426 {
7427 if (value && vtype == VT_VARIABLE)
7428 {
7429 *varp = find_variable (vname);
7430 if (quoted & (Q_DOUBLE_QUOTES|Q_HERE_DOCUMENT))
7431 *valp = dequote_string (value);
7432 else
7433 *valp = dequote_escapes (value);
7434 }
7435 else
7436 *valp = value;
7437 }
7438
7439 if (want_indir)
7440 free (vname);
7441
7442 return vtype;
7443 }
7444
7445 /***********************************************************/
7446 /* */
7447 /* Functions to perform transformations on variable values */
7448 /* */
7449 /***********************************************************/
7450
7451 static char *
7452 string_var_assignment (v, s)
7453 SHELL_VAR *v;
7454 char *s;
7455 {
7456 char flags[MAX_ATTRIBUTES], *ret, *val;
7457 int i;
7458
7459 val = sh_quote_reusable (s, 0);
7460 i = var_attribute_string (v, 0, flags);
7461 ret = (char *)xmalloc (i + strlen (val) + strlen (v->name) + 16 + MAX_ATTRIBUTES);
7462 if (i > 0)
7463 sprintf (ret, "declare -%s %s=%s", flags, v->name, val);
7464 else
7465 sprintf (ret, "%s=%s", v->name, val);
7466 free (val);
7467 return ret;
7468 }
7469
7470 #if defined (ARRAY_VARS)
7471 static char *
7472 array_var_assignment (v, itype, quoted)
7473 SHELL_VAR *v;
7474 int itype, quoted;
7475 {
7476 char *ret, *val, flags[MAX_ATTRIBUTES];
7477 int i;
7478
7479 if (v == 0)
7480 return (char *)NULL;
7481 val = array_p (v) ? array_to_assign (array_cell (v), 0)
7482 : assoc_to_assign (assoc_cell (v), 0);
7483 if (val == 0)
7484 {
7485 val = (char *)xmalloc (3);
7486 val[0] = LPAREN;
7487 val[1] = RPAREN;
7488 val[2] = 0;
7489 }
7490 else
7491 {
7492 ret = (quoted & (Q_DOUBLE_QUOTES|Q_HERE_DOCUMENT)) ? quote_string (val) : quote_escapes (val);
7493 free (val);
7494 val = ret;
7495 }
7496 i = var_attribute_string (v, 0, flags);
7497 ret = (char *)xmalloc (i + strlen (val) + strlen (v->name) + 16);
7498 sprintf (ret, "declare -%s %s=%s", flags, v->name, val);
7499 free (val);
7500 return ret;
7501 }
7502 #endif
7503
7504 static char *
7505 pos_params_assignment (list, itype, quoted)
7506 WORD_LIST *list;
7507 int itype;
7508 int quoted;
7509 {
7510 char *temp, *ret;
7511
7512 /* first, we transform the list to quote each word. */
7513 temp = list_transform ('Q', (SHELL_VAR *)0, list, itype, quoted);
7514 ret = (char *)xmalloc (strlen (temp) + 8);
7515 strcpy (ret, "set -- ");
7516 strcpy (ret + 7, temp);
7517 free (temp);
7518 return ret;
7519 }
7520
7521 static char *
7522 string_transform (xc, v, s)
7523 int xc;
7524 SHELL_VAR *v;
7525 char *s;
7526 {
7527 char *ret, flags[MAX_ATTRIBUTES], *t;
7528 int i;
7529
7530 if (((xc == 'A' || xc == 'a') && v == 0) || (xc != 'a' && s == 0))
7531 return (char *)NULL;
7532
7533 switch (xc)
7534 {
7535 /* Transformations that interrogate the variable */
7536 case 'a':
7537 i = var_attribute_string (v, 0, flags);
7538 ret = (i > 0) ? savestring (flags) : (char *)NULL;
7539 break;
7540 case 'A':
7541 ret = string_var_assignment (v, s);
7542 break;
7543 /* Transformations that modify the variable's value */
7544 case 'E':
7545 t = ansiexpand (s, 0, strlen (s), (int *)0);
7546 ret = dequote_escapes (t);
7547 free (t);
7548 break;
7549 case 'P':
7550 ret = decode_prompt_string (s);
7551 break;
7552 case 'Q':
7553 ret = sh_quote_reusable (s, 0);
7554 break;
7555 default:
7556 ret = (char *)NULL;
7557 break;
7558 }
7559 return ret;
7560 }
7561
7562 static char *
7563 list_transform (xc, v, list, itype, quoted)
7564 int xc;
7565 SHELL_VAR *v;
7566 WORD_LIST *list;
7567 int itype, quoted;
7568 {
7569 WORD_LIST *new, *l;
7570 WORD_DESC *w;
7571 char *tword;
7572 int qflags;
7573
7574 for (new = (WORD_LIST *)NULL, l = list; l; l = l->next)
7575 {
7576 tword = string_transform (xc, v, l->word->word);
7577 w = alloc_word_desc ();
7578 w->word = tword ? tword : savestring (""); /* XXX */
7579 new = make_word_list (w, new);
7580 }
7581 l = REVERSE_LIST (new, WORD_LIST *);
7582
7583 qflags = quoted;
7584 /* If we are expanding in a context where word splitting will not be
7585 performed, treat as quoted. This changes how $* will be expanded. */
7586 if (itype == '*' && expand_no_split_dollar_star && ifs_is_null)
7587 qflags |= Q_DOUBLE_QUOTES; /* Posix interp 888 */
7588
7589 tword = string_list_pos_params (itype, l, qflags);
7590 dispose_words (l);
7591
7592 return (tword);
7593 }
7594
7595 static char *
7596 parameter_list_transform (xc, itype, quoted)
7597 int xc;
7598 int itype;
7599 int quoted;
7600 {
7601 char *ret;
7602 WORD_LIST *list;
7603
7604 list = list_rest_of_args ();
7605 if (list == 0)
7606 return ((char *)NULL);
7607 if (xc == 'A')
7608 ret = pos_params_assignment (list, itype, quoted);
7609 else
7610 ret = list_transform (xc, (SHELL_VAR *)0, list, itype, quoted);
7611 dispose_words (list);
7612 return (ret);
7613 }
7614
7615 #if defined (ARRAY_VARS)
7616 static char *
7617 array_transform (xc, var, varname, quoted)
7618 int xc;
7619 SHELL_VAR *var;
7620 char *varname; /* so we can figure out how it's indexed */
7621 int quoted;
7622 {
7623 ARRAY *a;
7624 HASH_TABLE *h;
7625 int itype;
7626 char *ret;
7627 WORD_LIST *list;
7628 SHELL_VAR *v;
7629
7630 /* compute itype from varname here */
7631 v = array_variable_part (varname, 0, &ret, 0);
7632
7633 /* XXX */
7634 if (v && invisible_p (v))
7635 return ((char *)NULL);
7636
7637 itype = ret[0];
7638
7639 if (xc == 'A')
7640 return (array_var_assignment (v, itype, quoted));
7641
7642 a = (v && array_p (v)) ? array_cell (v) : 0;
7643 h = (v && assoc_p (v)) ? assoc_cell (v) : 0;
7644
7645 list = a ? array_to_word_list (a) : (h ? assoc_to_word_list (h) : 0);
7646 if (list == 0)
7647 return ((char *)NULL);
7648 ret = list_transform (xc, v, list, itype, quoted);
7649 dispose_words (list);
7650
7651 return ret;
7652 }
7653 #endif /* ARRAY_VARS */
7654
7655 static char *
7656 parameter_brace_transform (varname, value, ind, xform, rtype, quoted, pflags, flags)
7657 char *varname, *value;
7658 int ind;
7659 char *xform;
7660 int rtype, quoted, pflags, flags;
7661 {
7662 int vtype, xc;
7663 char *temp1, *val, *oname;
7664 SHELL_VAR *v;
7665
7666 xc = xform[0];
7667 if (value == 0 && xc != 'A' && xc != 'a')
7668 return ((char *)NULL);
7669
7670 oname = this_command_name;
7671 this_command_name = varname;
7672
7673 vtype = get_var_and_type (varname, value, ind, quoted, flags, &v, &val);
7674 if (vtype == -1)
7675 {
7676 this_command_name = oname;
7677 return ((char *)NULL);
7678 }
7679
7680 /* check for valid values of xc */
7681 switch (xc)
7682 {
7683 case 'a': /* expand to a string with just attributes */
7684 case 'A': /* expand as an assignment statement with attributes */
7685 case 'E': /* expand like $'...' */
7686 case 'P': /* expand like prompt string */
7687 case 'Q': /* quote reusably */
7688 break;
7689 default:
7690 this_command_name = oname;
7691 return &expand_param_error;
7692 }
7693
7694 /* If we are asked to display the attributes of an unset variable, V will
7695 be NULL after the call to get_var_and_type. Double-check here. */
7696 if (xc == 'a' && vtype == VT_VARIABLE && varname && v == 0)
7697 v = find_variable (varname);
7698
7699 temp1 = (char *)NULL; /* shut up gcc */
7700 switch (vtype & ~VT_STARSUB)
7701 {
7702 case VT_VARIABLE:
7703 case VT_ARRAYMEMBER:
7704 temp1 = string_transform (xc, v, val);
7705 if (vtype == VT_VARIABLE)
7706 FREE (val);
7707 if (temp1)
7708 {
7709 val = (quoted & (Q_HERE_DOCUMENT|Q_DOUBLE_QUOTES))
7710 ? quote_string (temp1)
7711 : quote_escapes (temp1);
7712 free (temp1);
7713 temp1 = val;
7714 }
7715 break;
7716 #if defined (ARRAY_VARS)
7717 case VT_ARRAYVAR:
7718 temp1 = array_transform (xc, v, varname, quoted);
7719 if (temp1 && quoted == 0 && ifs_is_null)
7720 {
7721 /* Posix interp 888 */
7722 }
7723 else if (temp1 && ((quoted & (Q_HERE_DOCUMENT|Q_DOUBLE_QUOTES)) == 0))
7724 {
7725 val = quote_escapes (temp1);
7726 free (temp1);
7727 temp1 = val;
7728 }
7729 break;
7730 #endif
7731 case VT_POSPARMS:
7732 temp1 = parameter_list_transform (xc, varname[0], quoted);
7733 if (temp1 && quoted == 0 && ifs_is_null)
7734 {
7735 /* Posix interp 888 */
7736 }
7737 else if (temp1 && ((quoted & (Q_HERE_DOCUMENT|Q_DOUBLE_QUOTES)) == 0))
7738 {
7739 val = quote_escapes (temp1);
7740 free (temp1);
7741 temp1 = val;
7742 }
7743 break;
7744 }
7745
7746 this_command_name = oname;
7747 return temp1;
7748 }
7749
7750 /******************************************************/
7751 /* */
7752 /* Functions to extract substrings of variable values */
7753 /* */
7754 /******************************************************/
7755
7756 #if defined (HANDLE_MULTIBYTE)
7757 /* Character-oriented rather than strictly byte-oriented substrings. S and
7758 E, rather being strict indices into STRING, indicate character (possibly
7759 multibyte character) positions that require calculation.
7760 Used by the ${param:offset[:length]} expansion. */
7761 static char *
7762 mb_substring (string, s, e)
7763 char *string;
7764 int s, e;
7765 {
7766 char *tt;
7767 int start, stop, i;
7768 size_t slen;
7769 DECLARE_MBSTATE;
7770
7771 start = 0;
7772 /* Don't need string length in ADVANCE_CHAR unless multibyte chars possible. */
7773 slen = (MB_CUR_MAX > 1) ? STRLEN (string) : 0;
7774
7775 i = s;
7776 while (string[start] && i--)
7777 ADVANCE_CHAR (string, slen, start);
7778 stop = start;
7779 i = e - s;
7780 while (string[stop] && i--)
7781 ADVANCE_CHAR (string, slen, stop);
7782 tt = substring (string, start, stop);
7783 return tt;
7784 }
7785 #endif
7786
7787 /* Process a variable substring expansion: ${name:e1[:e2]}. If VARNAME
7788 is `@', use the positional parameters; otherwise, use the value of
7789 VARNAME. If VARNAME is an array variable, use the array elements. */
7790
7791 static char *
7792 parameter_brace_substring (varname, value, ind, substr, quoted, pflags, flags)
7793 char *varname, *value;
7794 int ind;
7795 char *substr;
7796 int quoted, pflags, flags;
7797 {
7798 intmax_t e1, e2;
7799 int vtype, r, starsub;
7800 char *temp, *val, *tt, *oname;
7801 SHELL_VAR *v;
7802
7803 if (value == 0 && ((varname[0] != '@' && varname[0] != '*') || varname[1]))
7804 return ((char *)NULL);
7805
7806 oname = this_command_name;
7807 this_command_name = varname;
7808
7809 vtype = get_var_and_type (varname, value, ind, quoted, flags, &v, &val);
7810 if (vtype == -1)
7811 {
7812 this_command_name = oname;
7813 return ((char *)NULL);
7814 }
7815
7816 starsub = vtype & VT_STARSUB;
7817 vtype &= ~VT_STARSUB;
7818
7819 r = verify_substring_values (v, val, substr, vtype, &e1, &e2);
7820 this_command_name = oname;
7821 if (r <= 0)
7822 {
7823 if (vtype == VT_VARIABLE)
7824 FREE (val);
7825 return ((r == 0) ? &expand_param_error : (char *)NULL);
7826 }
7827
7828 switch (vtype)
7829 {
7830 case VT_VARIABLE:
7831 case VT_ARRAYMEMBER:
7832 #if defined (HANDLE_MULTIBYTE)
7833 if (MB_CUR_MAX > 1)
7834 tt = mb_substring (val, e1, e2);
7835 else
7836 #endif
7837 tt = substring (val, e1, e2);
7838
7839 if (vtype == VT_VARIABLE)
7840 FREE (val);
7841 if (quoted & (Q_DOUBLE_QUOTES|Q_HERE_DOCUMENT))
7842 temp = quote_string (tt);
7843 else
7844 temp = tt ? quote_escapes (tt) : (char *)NULL;
7845 FREE (tt);
7846 break;
7847 case VT_POSPARMS:
7848 case VT_ARRAYVAR:
7849 if (vtype == VT_POSPARMS)
7850 tt = pos_params (varname, e1, e2, quoted);
7851 #if defined (ARRAY_VARS)
7852 /* assoc_subrange and array_subrange both call string_list_pos_params,
7853 so we can treat this case just like VT_POSPARAMS. */
7854 else if (assoc_p (v))
7855 /* we convert to list and take first e2 elements starting at e1th
7856 element -- officially undefined for now */
7857 tt = assoc_subrange (assoc_cell (v), e1, e2, starsub, quoted);
7858 else
7859 /* We want E2 to be the number of elements desired (arrays can be
7860 sparse, so verify_substring_values just returns the numbers
7861 specified and we rely on array_subrange to understand how to
7862 deal with them). */
7863 tt = array_subrange (array_cell (v), e1, e2, starsub, quoted);
7864 #endif
7865 /* We want to leave this alone in every case where pos_params/
7866 string_list_pos_params quotes the list members */
7867 if (tt && quoted == 0 && ifs_is_null)
7868 {
7869 temp = tt; /* Posix interp 888 */
7870 }
7871 else if ((quoted & (Q_DOUBLE_QUOTES|Q_HERE_DOCUMENT)) == 0)
7872 {
7873 temp = tt ? quote_escapes (tt) : (char *)NULL;
7874 FREE (tt);
7875 }
7876 else
7877 temp = tt;
7878 break;
7879
7880 default:
7881 temp = (char *)NULL;
7882 }
7883
7884 return temp;
7885 }
7886
7887 /****************************************************************/
7888 /* */
7889 /* Functions to perform pattern substitution on variable values */
7890 /* */
7891 /****************************************************************/
7892
7893 #ifdef INCLUDE_UNUSED
7894 static int
7895 shouldexp_replacement (s)
7896 char *s;
7897 {
7898 register char *p;
7899
7900 for (p = s; p && *p; p++)
7901 {
7902 if (*p == '\\')
7903 p++;
7904 else if (*p == '&')
7905 return 1;
7906 }
7907 return 0;
7908 }
7909 #endif
7910
7911 char *
7912 pat_subst (string, pat, rep, mflags)
7913 char *string, *pat, *rep;
7914 int mflags;
7915 {
7916 char *ret, *s, *e, *str, *rstr, *mstr;
7917 int rptr, mtype, rxpand, mlen;
7918 size_t rsize, l, replen, rslen;
7919
7920 if (string == 0)
7921 return (savestring (""));
7922
7923 mtype = mflags & MATCH_TYPEMASK;
7924
7925 #if 0 /* bash-4.2 ? */
7926 rxpand = (rep && *rep) ? shouldexp_replacement (rep) : 0;
7927 #else
7928 rxpand = 0;
7929 #endif
7930
7931 /* Special cases:
7932 * 1. A null pattern with mtype == MATCH_BEG means to prefix STRING
7933 * with REP and return the result.
7934 * 2. A null pattern with mtype == MATCH_END means to append REP to
7935 * STRING and return the result.
7936 * 3. A null STRING with a matching pattern means to append REP to
7937 * STRING and return the result.
7938 * These don't understand or process `&' in the replacement string.
7939 */
7940 if ((pat == 0 || *pat == 0) && (mtype == MATCH_BEG || mtype == MATCH_END))
7941 {
7942 replen = STRLEN (rep);
7943 l = STRLEN (string);
7944 ret = (char *)xmalloc (replen + l + 2);
7945 if (replen == 0)
7946 strcpy (ret, string);
7947 else if (mtype == MATCH_BEG)
7948 {
7949 strcpy (ret, rep);
7950 strcpy (ret + replen, string);
7951 }
7952 else
7953 {
7954 strcpy (ret, string);
7955 strcpy (ret + l, rep);
7956 }
7957 return (ret);
7958 }
7959 else if (*string == 0 && (match_pattern (string, pat, mtype, &s, &e) != 0))
7960 {
7961 replen = STRLEN (rep);
7962 ret = (char *)xmalloc (replen + 1);
7963 if (replen == 0)
7964 ret[0] = '\0';
7965 else
7966 strcpy (ret, rep);
7967 return (ret);
7968 }
7969
7970 ret = (char *)xmalloc (rsize = 64);
7971 ret[0] = '\0';
7972
7973 for (replen = STRLEN (rep), rptr = 0, str = string; *str;)
7974 {
7975 if (match_pattern (str, pat, mtype, &s, &e) == 0)
7976 break;
7977 l = s - str;
7978
7979 if (rep && rxpand)
7980 {
7981 int x;
7982 mlen = e - s;
7983 mstr = xmalloc (mlen + 1);
7984 for (x = 0; x < mlen; x++)
7985 mstr[x] = s[x];
7986 mstr[mlen] = '\0';
7987 rstr = strcreplace (rep, '&', mstr, 0);
7988 free (mstr);
7989 rslen = strlen (rstr);
7990 }
7991 else
7992 {
7993 rstr = rep;
7994 rslen = replen;
7995 }
7996
7997 RESIZE_MALLOCED_BUFFER (ret, rptr, (l + rslen), rsize, 64);
7998
7999 /* OK, now copy the leading unmatched portion of the string (from
8000 str to s) to ret starting at rptr (the current offset). Then copy
8001 the replacement string at ret + rptr + (s - str). Increment
8002 rptr (if necessary) and str and go on. */
8003 if (l)
8004 {
8005 strncpy (ret + rptr, str, l);
8006 rptr += l;
8007 }
8008 if (replen)
8009 {
8010 strncpy (ret + rptr, rstr, rslen);
8011 rptr += rslen;
8012 }
8013 str = e; /* e == end of match */
8014
8015 if (rstr != rep)
8016 free (rstr);
8017
8018 if (((mflags & MATCH_GLOBREP) == 0) || mtype != MATCH_ANY)
8019 break;
8020
8021 if (s == e)
8022 {
8023 /* On a zero-length match, make sure we copy one character, since
8024 we increment one character to avoid infinite recursion. */
8025 RESIZE_MALLOCED_BUFFER (ret, rptr, 1, rsize, 64);
8026 ret[rptr++] = *str++;
8027 e++; /* avoid infinite recursion on zero-length match */
8028 }
8029 }
8030
8031 /* Now copy the unmatched portion of the input string */
8032 if (str && *str)
8033 {
8034 RESIZE_MALLOCED_BUFFER (ret, rptr, STRLEN(str) + 1, rsize, 64);
8035 strcpy (ret + rptr, str);
8036 }
8037 else
8038 ret[rptr] = '\0';
8039
8040 return ret;
8041 }
8042
8043 /* Do pattern match and replacement on the positional parameters. */
8044 static char *
8045 pos_params_pat_subst (string, pat, rep, mflags)
8046 char *string, *pat, *rep;
8047 int mflags;
8048 {
8049 WORD_LIST *save, *params;
8050 WORD_DESC *w;
8051 char *ret;
8052 int pchar, qflags;
8053
8054 save = params = list_rest_of_args ();
8055 if (save == 0)
8056 return ((char *)NULL);
8057
8058 for ( ; params; params = params->next)
8059 {
8060 ret = pat_subst (params->word->word, pat, rep, mflags);
8061 w = alloc_word_desc ();
8062 w->word = ret ? ret : savestring ("");
8063 dispose_word (params->word);
8064 params->word = w;
8065 }
8066
8067 pchar = (mflags & MATCH_STARSUB) == MATCH_STARSUB ? '*' : '@';
8068 qflags = (mflags & MATCH_QUOTED) == MATCH_QUOTED ? Q_DOUBLE_QUOTES : 0;
8069
8070 /* If we are expanding in a context where word splitting will not be
8071 performed, treat as quoted. This changes how $* will be expanded. */
8072 if (pchar == '*' && (mflags & MATCH_ASSIGNRHS) && expand_no_split_dollar_star && ifs_is_null)
8073 qflags |= Q_DOUBLE_QUOTES; /* Posix interp 888 */
8074
8075 ret = string_list_pos_params (pchar, save, qflags);
8076 dispose_words (save);
8077
8078 return (ret);
8079 }
8080
8081 /* Perform pattern substitution on VALUE, which is the expansion of
8082 VARNAME. PATSUB is an expression supplying the pattern to match
8083 and the string to substitute. QUOTED is a flags word containing
8084 the type of quoting currently in effect. */
8085 static char *
8086 parameter_brace_patsub (varname, value, ind, patsub, quoted, pflags, flags)
8087 char *varname, *value;
8088 int ind;
8089 char *patsub;
8090 int quoted, pflags, flags;
8091 {
8092 int vtype, mflags, starsub, delim;
8093 char *val, *temp, *pat, *rep, *p, *lpatsub, *tt, *oname;
8094 SHELL_VAR *v;
8095
8096 if (value == 0)
8097 return ((char *)NULL);
8098
8099 oname = this_command_name;
8100 this_command_name = varname; /* error messages */
8101
8102 vtype = get_var_and_type (varname, value, ind, quoted, flags, &v, &val);
8103 if (vtype == -1)
8104 {
8105 this_command_name = oname;
8106 return ((char *)NULL);
8107 }
8108
8109 starsub = vtype & VT_STARSUB;
8110 vtype &= ~VT_STARSUB;
8111
8112 mflags = 0;
8113 /* PATSUB is never NULL when this is called. */
8114 if (*patsub == '/')
8115 {
8116 mflags |= MATCH_GLOBREP;
8117 patsub++;
8118 }
8119
8120 /* Malloc this because expand_string_if_necessary or one of the expansion
8121 functions in its call chain may free it on a substitution error. */
8122 lpatsub = savestring (patsub);
8123
8124 if (quoted & (Q_HERE_DOCUMENT|Q_DOUBLE_QUOTES))
8125 mflags |= MATCH_QUOTED;
8126
8127 if (starsub)
8128 mflags |= MATCH_STARSUB;
8129
8130 if (pflags & PF_ASSIGNRHS)
8131 mflags |= MATCH_ASSIGNRHS;
8132
8133 /* If the pattern starts with a `/', make sure we skip over it when looking
8134 for the replacement delimiter. */
8135 delim = skip_to_delim (lpatsub, ((*patsub == '/') ? 1 : 0), "/", 0);
8136 if (lpatsub[delim] == '/')
8137 {
8138 lpatsub[delim] = 0;
8139 rep = lpatsub + delim + 1;
8140 }
8141 else
8142 rep = (char *)NULL;
8143
8144 if (rep && *rep == '\0')
8145 rep = (char *)NULL;
8146
8147 /* Perform the same expansions on the pattern as performed by the
8148 pattern removal expansions. */
8149 pat = getpattern (lpatsub, quoted, 1);
8150
8151 if (rep)
8152 {
8153 /* We want to perform quote removal on the expanded replacement even if
8154 the entire expansion is double-quoted because the parser and string
8155 extraction functions treated quotes in the replacement string as
8156 special. THIS IS NOT BACKWARDS COMPATIBLE WITH BASH-4.2. */
8157 if (shell_compatibility_level > 42)
8158 rep = expand_string_if_necessary (rep, quoted & ~(Q_DOUBLE_QUOTES|Q_HERE_DOCUMENT), expand_string_unsplit);
8159 /* This is the bash-4.2 code. */
8160 else if ((mflags & MATCH_QUOTED) == 0)
8161 rep = expand_string_if_necessary (rep, quoted, expand_string_unsplit);
8162 else
8163 rep = expand_string_to_string_internal (rep, quoted, expand_string_unsplit);
8164 }
8165
8166 /* ksh93 doesn't allow the match specifier to be a part of the expanded
8167 pattern. This is an extension. Make sure we don't anchor the pattern
8168 at the beginning or end of the string if we're doing global replacement,
8169 though. */
8170 p = pat;
8171 if (mflags & MATCH_GLOBREP)
8172 mflags |= MATCH_ANY;
8173 else if (pat && pat[0] == '#')
8174 {
8175 mflags |= MATCH_BEG;
8176 p++;
8177 }
8178 else if (pat && pat[0] == '%')
8179 {
8180 mflags |= MATCH_END;
8181 p++;
8182 }
8183 else
8184 mflags |= MATCH_ANY;
8185
8186 /* OK, we now want to substitute REP for PAT in VAL. If
8187 flags & MATCH_GLOBREP is non-zero, the substitution is done
8188 everywhere, otherwise only the first occurrence of PAT is
8189 replaced. The pattern matching code doesn't understand
8190 CTLESC quoting CTLESC and CTLNUL so we use the dequoted variable
8191 values passed in (VT_VARIABLE) so the pattern substitution
8192 code works right. We need to requote special chars after
8193 we're done for VT_VARIABLE and VT_ARRAYMEMBER, and for the
8194 other cases if QUOTED == 0, since the posparams and arrays
8195 indexed by * or @ do special things when QUOTED != 0. */
8196
8197 switch (vtype)
8198 {
8199 case VT_VARIABLE:
8200 case VT_ARRAYMEMBER:
8201 temp = pat_subst (val, p, rep, mflags);
8202 if (vtype == VT_VARIABLE)
8203 FREE (val);
8204 if (temp)
8205 {
8206 tt = (mflags & MATCH_QUOTED) ? quote_string (temp) : quote_escapes (temp);
8207 free (temp);
8208 temp = tt;
8209 }
8210 break;
8211 case VT_POSPARMS:
8212 /* This does the right thing for the case where we are not performing
8213 word splitting. MATCH_STARSUB restricts it to ${* /foo/bar}, and
8214 pos_params_pat_subst/string_list_pos_params will do the right thing
8215 in turn for the case where ifs_is_null. Posix interp 888 */
8216 if ((pflags & PF_NOSPLIT2) && (mflags & MATCH_STARSUB))
8217 mflags |= MATCH_ASSIGNRHS;
8218 temp = pos_params_pat_subst (val, p, rep, mflags);
8219 if (temp && quoted == 0 && ifs_is_null)
8220 {
8221 /* Posix interp 888 */
8222 }
8223 else if (temp && (mflags & MATCH_QUOTED) == 0)
8224 {
8225 tt = quote_escapes (temp);
8226 free (temp);
8227 temp = tt;
8228 }
8229 break;
8230 #if defined (ARRAY_VARS)
8231 case VT_ARRAYVAR:
8232 /* If we are expanding in a context where word splitting will not be
8233 performed, treat as quoted. This changes how ${A[*]} will be
8234 expanded to make it identical to $*. */
8235 if ((mflags & MATCH_STARSUB) && (mflags & MATCH_ASSIGNRHS) && ifs_is_null)
8236 mflags |= MATCH_QUOTED; /* Posix interp 888 */
8237
8238 /* these eventually call string_list_pos_params */
8239 if (assoc_p (v))
8240 temp = assoc_patsub (assoc_cell (v), p, rep, mflags);
8241 else
8242 temp = array_patsub (array_cell (v), p, rep, mflags);
8243
8244 if (temp && quoted == 0 && ifs_is_null)
8245 {
8246 /* Posix interp 888 */
8247 }
8248 else if (temp && (mflags & MATCH_QUOTED) == 0)
8249 {
8250 tt = quote_escapes (temp);
8251 free (temp);
8252 temp = tt;
8253 }
8254 break;
8255 #endif
8256 }
8257
8258 FREE (pat);
8259 FREE (rep);
8260 free (lpatsub);
8261
8262 this_command_name = oname;
8263
8264 return temp;
8265 }
8266
8267 /****************************************************************/
8268 /* */
8269 /* Functions to perform case modification on variable values */
8270 /* */
8271 /****************************************************************/
8272
8273 /* Do case modification on the positional parameters. */
8274
8275 static char *
8276 pos_params_modcase (string, pat, modop, mflags)
8277 char *string, *pat;
8278 int modop;
8279 int mflags;
8280 {
8281 WORD_LIST *save, *params;
8282 WORD_DESC *w;
8283 char *ret;
8284 int pchar, qflags;
8285
8286 save = params = list_rest_of_args ();
8287 if (save == 0)
8288 return ((char *)NULL);
8289
8290 for ( ; params; params = params->next)
8291 {
8292 ret = sh_modcase (params->word->word, pat, modop);
8293 w = alloc_word_desc ();
8294 w->word = ret ? ret : savestring ("");
8295 dispose_word (params->word);
8296 params->word = w;
8297 }
8298
8299 pchar = (mflags & MATCH_STARSUB) == MATCH_STARSUB ? '*' : '@';
8300 qflags = (mflags & MATCH_QUOTED) == MATCH_QUOTED ? Q_DOUBLE_QUOTES : 0;
8301
8302 /* If we are expanding in a context where word splitting will not be
8303 performed, treat as quoted. This changes how $* will be expanded. */
8304 if (pchar == '*' && (mflags & MATCH_ASSIGNRHS) && ifs_is_null)
8305 qflags |= Q_DOUBLE_QUOTES; /* Posix interp 888 */
8306
8307 ret = string_list_pos_params (pchar, save, qflags);
8308 dispose_words (save);
8309
8310 return (ret);
8311 }
8312
8313 /* Perform case modification on VALUE, which is the expansion of
8314 VARNAME. MODSPEC is an expression supplying the type of modification
8315 to perform. QUOTED is a flags word containing the type of quoting
8316 currently in effect. */
8317 static char *
8318 parameter_brace_casemod (varname, value, ind, modspec, patspec, quoted, pflags, flags)
8319 char *varname, *value;
8320 int ind, modspec;
8321 char *patspec;
8322 int quoted, pflags, flags;
8323 {
8324 int vtype, starsub, modop, mflags, x;
8325 char *val, *temp, *pat, *p, *lpat, *tt, *oname;
8326 SHELL_VAR *v;
8327
8328 if (value == 0)
8329 return ((char *)NULL);
8330
8331 oname = this_command_name;
8332 this_command_name = varname;
8333
8334 vtype = get_var_and_type (varname, value, ind, quoted, flags, &v, &val);
8335 if (vtype == -1)
8336 {
8337 this_command_name = oname;
8338 return ((char *)NULL);
8339 }
8340
8341 starsub = vtype & VT_STARSUB;
8342 vtype &= ~VT_STARSUB;
8343
8344 modop = 0;
8345 mflags = 0;
8346 if (quoted & (Q_HERE_DOCUMENT|Q_DOUBLE_QUOTES))
8347 mflags |= MATCH_QUOTED;
8348 if (starsub)
8349 mflags |= MATCH_STARSUB;
8350 if (pflags & PF_ASSIGNRHS)
8351 mflags |= MATCH_ASSIGNRHS;
8352
8353 p = patspec;
8354 if (modspec == '^')
8355 {
8356 x = p && p[0] == modspec;
8357 modop = x ? CASE_UPPER : CASE_UPFIRST;
8358 p += x;
8359 }
8360 else if (modspec == ',')
8361 {
8362 x = p && p[0] == modspec;
8363 modop = x ? CASE_LOWER : CASE_LOWFIRST;
8364 p += x;
8365 }
8366 else if (modspec == '~')
8367 {
8368 x = p && p[0] == modspec;
8369 modop = x ? CASE_TOGGLEALL : CASE_TOGGLE;
8370 p += x;
8371 }
8372
8373 lpat = p ? savestring (p) : 0;
8374 /* Perform the same expansions on the pattern as performed by the
8375 pattern removal expansions. */
8376 pat = lpat ? getpattern (lpat, quoted, 1) : 0;
8377
8378 /* OK, now we do the case modification. */
8379 switch (vtype)
8380 {
8381 case VT_VARIABLE:
8382 case VT_ARRAYMEMBER:
8383 temp = sh_modcase (val, pat, modop);
8384 if (vtype == VT_VARIABLE)
8385 FREE (val);
8386 if (temp)
8387 {
8388 tt = (mflags & MATCH_QUOTED) ? quote_string (temp) : quote_escapes (temp);
8389 free (temp);
8390 temp = tt;
8391 }
8392 break;
8393
8394 case VT_POSPARMS:
8395 temp = pos_params_modcase (val, pat, modop, mflags);
8396 if (temp && quoted == 0 && ifs_is_null)
8397 {
8398 /* Posix interp 888 */
8399 }
8400 else if (temp && (mflags & MATCH_QUOTED) == 0)
8401 {
8402 tt = quote_escapes (temp);
8403 free (temp);
8404 temp = tt;
8405 }
8406 break;
8407
8408 #if defined (ARRAY_VARS)
8409 case VT_ARRAYVAR:
8410 /* If we are expanding in a context where word splitting will not be
8411 performed, treat as quoted. This changes how ${A[*]} will be
8412 expanded to make it identical to $*. */
8413 if ((mflags & MATCH_STARSUB) && (mflags & MATCH_ASSIGNRHS) && ifs_is_null)
8414 mflags |= MATCH_QUOTED; /* Posix interp 888 */
8415
8416 temp = assoc_p (v) ? assoc_modcase (assoc_cell (v), pat, modop, mflags)
8417 : array_modcase (array_cell (v), pat, modop, mflags);
8418
8419 if (temp && quoted == 0 && ifs_is_null)
8420 {
8421 /* Posix interp 888 */
8422 }
8423 else if (temp && (mflags & MATCH_QUOTED) == 0)
8424 {
8425 tt = quote_escapes (temp);
8426 free (temp);
8427 temp = tt;
8428 }
8429
8430 break;
8431 #endif
8432 }
8433
8434 FREE (pat);
8435 free (lpat);
8436
8437 this_command_name = oname;
8438
8439 return temp;
8440 }
8441
8442 /* Check for unbalanced parens in S, which is the contents of $(( ... )). If
8443 any occur, this must be a nested command substitution, so return 0.
8444 Otherwise, return 1. A valid arithmetic expression must always have a
8445 ( before a matching ), so any cases where there are more right parens
8446 means that this must not be an arithmetic expression, though the parser
8447 will not accept it without a balanced total number of parens. */
8448 static int
8449 chk_arithsub (s, len)
8450 const char *s;
8451 int len;
8452 {
8453 int i, count;
8454 DECLARE_MBSTATE;
8455
8456 i = count = 0;
8457 while (i < len)
8458 {
8459 if (s[i] == LPAREN)
8460 count++;
8461 else if (s[i] == RPAREN)
8462 {
8463 count--;
8464 if (count < 0)
8465 return 0;
8466 }
8467
8468 switch (s[i])
8469 {
8470 default:
8471 ADVANCE_CHAR (s, len, i);
8472 break;
8473
8474 case '\\':
8475 i++;
8476 if (s[i])
8477 ADVANCE_CHAR (s, len, i);
8478 break;
8479
8480 case '\'':
8481 i = skip_single_quoted (s, len, ++i, 0);
8482 break;
8483
8484 case '"':
8485 i = skip_double_quoted ((char *)s, len, ++i, 0);
8486 break;
8487 }
8488 }
8489
8490 return (count == 0);
8491 }
8492
8493 /****************************************************************/
8494 /* */
8495 /* Functions to perform parameter expansion on a string */
8496 /* */
8497 /****************************************************************/
8498
8499 /* ${[#][!]name[[:][^[^]][,[,]]#[#]%[%]-=?+[word][:e1[:e2]]]} */
8500 static WORD_DESC *
8501 parameter_brace_expand (string, indexp, quoted, pflags, quoted_dollar_atp, contains_dollar_at)
8502 char *string;
8503 int *indexp, quoted, pflags, *quoted_dollar_atp, *contains_dollar_at;
8504 {
8505 int check_nullness, var_is_set, var_is_null, var_is_special;
8506 int want_substring, want_indir, want_patsub, want_casemod;
8507 char *name, *value, *temp, *temp1;
8508 WORD_DESC *tdesc, *ret;
8509 int t_index, sindex, c, tflag, modspec, all_element_arrayref;
8510 intmax_t number;
8511 arrayind_t ind;
8512
8513 temp = temp1 = value = (char *)NULL;
8514 var_is_set = var_is_null = var_is_special = check_nullness = 0;
8515 want_substring = want_indir = want_patsub = want_casemod = 0;
8516
8517 all_element_arrayref = 0;
8518
8519 sindex = *indexp;
8520 t_index = ++sindex;
8521 /* ${#var} doesn't have any of the other parameter expansions on it. */
8522 if (string[t_index] == '#' && legal_variable_starter (string[t_index+1])) /* {{ */
8523 name = string_extract (string, &t_index, "}", SX_VARNAME);
8524 else
8525 #if defined (CASEMOD_EXPANSIONS)
8526 /* To enable case-toggling expansions using the `~' operator character
8527 change the 1 to 0. */
8528 # if defined (CASEMOD_CAPCASE)
8529 name = string_extract (string, &t_index, "#%^,~:-=?+/@}", SX_VARNAME);
8530 # else
8531 name = string_extract (string, &t_index, "#%^,:-=?+/@}", SX_VARNAME);
8532 # endif /* CASEMOD_CAPCASE */
8533 #else
8534 name = string_extract (string, &t_index, "#%:-=?+/@}", SX_VARNAME);
8535 #endif /* CASEMOD_EXPANSIONS */
8536
8537 /* Handle ${@[stuff]} now that @ is a word expansion operator. Not exactly
8538 the cleanest code ever. */
8539 if (*name == 0 && sindex == t_index && string[sindex] == '@')
8540 {
8541 name = (char *)xrealloc (name, 2);
8542 name[0] = '@';
8543 name[1] = '\0';
8544 t_index++;
8545 }
8546 else if (*name == '!' && t_index > sindex && string[t_index] == '@' && string[t_index+1] == RBRACE)
8547 {
8548 name = (char *)xrealloc (name, t_index - sindex + 2);
8549 name[t_index - sindex] = '@';
8550 name[t_index - sindex + 1] = '\0';
8551 t_index++;
8552 }
8553
8554 ret = 0;
8555 tflag = 0;
8556
8557 ind = INTMAX_MIN;
8558
8559 /* If the name really consists of a special variable, then make sure
8560 that we have the entire name. We don't allow indirect references
8561 to special variables except `#', `?', `@' and `*'. This clause is
8562 designed to handle ${#SPECIAL} and ${!SPECIAL}, not anything more
8563 general. */
8564 if ((sindex == t_index && VALID_SPECIAL_LENGTH_PARAM (string[t_index])) ||
8565 (sindex == t_index && string[sindex] == '#' && VALID_SPECIAL_LENGTH_PARAM (string[sindex + 1])) ||
8566 (sindex == t_index - 1 && string[sindex] == '!' && VALID_INDIR_PARAM (string[t_index])))
8567 {
8568 t_index++;
8569 temp1 = string_extract (string, &t_index, "#%:-=?+/@}", 0);
8570 name = (char *)xrealloc (name, 3 + (strlen (temp1)));
8571 *name = string[sindex];
8572 if (string[sindex] == '!')
8573 {
8574 /* indirect reference of $#, $?, $@, or $* */
8575 name[1] = string[sindex + 1];
8576 strcpy (name + 2, temp1);
8577 }
8578 else
8579 strcpy (name + 1, temp1);
8580 free (temp1);
8581 }
8582 sindex = t_index;
8583
8584 /* Find out what character ended the variable name. Then
8585 do the appropriate thing. */
8586 if (c = string[sindex])
8587 sindex++;
8588
8589 /* If c is followed by one of the valid parameter expansion
8590 characters, move past it as normal. If not, assume that
8591 a substring specification is being given, and do not move
8592 past it. */
8593 if (c == ':' && VALID_PARAM_EXPAND_CHAR (string[sindex]))
8594 {
8595 check_nullness++;
8596 if (c = string[sindex])
8597 sindex++;
8598 }
8599 else if (c == ':' && string[sindex] != RBRACE)
8600 want_substring = 1;
8601 else if (c == '/' /* && string[sindex] != RBRACE */) /* XXX */
8602 want_patsub = 1;
8603 #if defined (CASEMOD_EXPANSIONS)
8604 else if (c == '^' || c == ',' || c == '~')
8605 {
8606 modspec = c;
8607 want_casemod = 1;
8608 }
8609 #endif
8610
8611 /* Catch the valid and invalid brace expressions that made it through the
8612 tests above. */
8613 /* ${#-} is a valid expansion and means to take the length of $-.
8614 Similarly for ${#?} and ${##}... */
8615 if (name[0] == '#' && name[1] == '\0' && check_nullness == 0 &&
8616 VALID_SPECIAL_LENGTH_PARAM (c) && string[sindex] == RBRACE)
8617 {
8618 name = (char *)xrealloc (name, 3);
8619 name[1] = c;
8620 name[2] = '\0';
8621 c = string[sindex++];
8622 }
8623
8624 /* ...but ${#%}, ${#:}, ${#=}, ${#+}, and ${#/} are errors. */
8625 if (name[0] == '#' && name[1] == '\0' && check_nullness == 0 &&
8626 member (c, "%:=+/") && string[sindex] == RBRACE)
8627 {
8628 temp = (char *)NULL;
8629 goto bad_substitution; /* XXX - substitution error */
8630 }
8631
8632 /* Indirect expansion begins with a `!'. A valid indirect expansion is
8633 either a variable name, one of the positional parameters or a special
8634 variable that expands to one of the positional parameters. */
8635 want_indir = *name == '!' &&
8636 (legal_variable_starter ((unsigned char)name[1]) || DIGIT (name[1])
8637 || VALID_INDIR_PARAM (name[1]));
8638
8639 /* Determine the value of this variable whose name is NAME. */
8640
8641 /* Check for special variables, directly referenced. */
8642 if (SPECIAL_VAR (name, want_indir))
8643 var_is_special++;
8644
8645 /* Check for special expansion things, like the length of a parameter */
8646 if (*name == '#' && name[1])
8647 {
8648 /* If we are not pointing at the character just after the
8649 closing brace, then we haven't gotten all of the name.
8650 Since it begins with a special character, this is a bad
8651 substitution. Also check NAME for validity before trying
8652 to go on. */
8653 if (string[sindex - 1] != RBRACE || (valid_length_expression (name) == 0))
8654 {
8655 temp = (char *)NULL;
8656 goto bad_substitution; /* substitution error */
8657 }
8658
8659 number = parameter_brace_expand_length (name);
8660 if (number == INTMAX_MIN && unbound_vars_is_error)
8661 {
8662 last_command_exit_value = EXECUTION_FAILURE;
8663 err_unboundvar (name+1);
8664 free (name);
8665 return (interactive_shell ? &expand_wdesc_error : &expand_wdesc_fatal);
8666 }
8667 free (name);
8668
8669 *indexp = sindex;
8670 if (number < 0)
8671 return (&expand_wdesc_error);
8672 else
8673 {
8674 ret = alloc_word_desc ();
8675 ret->word = itos (number);
8676 return ret;
8677 }
8678 }
8679
8680 /* ${@} is identical to $@. */
8681 if (name[0] == '@' && name[1] == '\0')
8682 {
8683 if ((quoted & (Q_HERE_DOCUMENT|Q_DOUBLE_QUOTES)) && quoted_dollar_atp)
8684 *quoted_dollar_atp = 1;
8685
8686 if (contains_dollar_at)
8687 *contains_dollar_at = 1;
8688
8689 tflag |= W_DOLLARAT;
8690 }
8691
8692 /* Process ${!PREFIX*} expansion. */
8693 if (want_indir && string[sindex - 1] == RBRACE &&
8694 (string[sindex - 2] == '*' || string[sindex - 2] == '@') &&
8695 legal_variable_starter ((unsigned char) name[1]))
8696 {
8697 char **x;
8698 WORD_LIST *xlist;
8699
8700 temp1 = savestring (name + 1);
8701 number = strlen (temp1);
8702 temp1[number - 1] = '\0';
8703 x = all_variables_matching_prefix (temp1);
8704 xlist = strvec_to_word_list (x, 0, 0);
8705 if (string[sindex - 2] == '*')
8706 temp = string_list_dollar_star (xlist, quoted, 0);
8707 else
8708 {
8709 temp = string_list_dollar_at (xlist, quoted, 0);
8710 if ((quoted & (Q_HERE_DOCUMENT|Q_DOUBLE_QUOTES)) && quoted_dollar_atp)
8711 *quoted_dollar_atp = 1;
8712 if (contains_dollar_at)
8713 *contains_dollar_at = 1;
8714
8715 tflag |= W_DOLLARAT;
8716 }
8717 free (x);
8718 dispose_words (xlist);
8719 free (temp1);
8720 *indexp = sindex;
8721
8722 free (name);
8723
8724 ret = alloc_word_desc ();
8725 ret->word = temp;
8726 ret->flags = tflag; /* XXX */
8727 return ret;
8728 }
8729
8730 #if defined (ARRAY_VARS)
8731 /* Process ${!ARRAY[@]} and ${!ARRAY[*]} expansion. */
8732 if (want_indir && string[sindex - 1] == RBRACE &&
8733 string[sindex - 2] == RBRACK && valid_array_reference (name+1, 0))
8734 {
8735 char *x, *x1;
8736
8737 temp1 = savestring (name + 1);
8738 x = array_variable_name (temp1, 0, &x1, (int *)0);
8739 FREE (x);
8740 if (ALL_ELEMENT_SUB (x1[0]) && x1[1] == RBRACK)
8741 {
8742 temp = array_keys (temp1, quoted); /* handles assoc vars too */
8743 if (x1[0] == '@')
8744 {
8745 if ((quoted & (Q_HERE_DOCUMENT|Q_DOUBLE_QUOTES)) && quoted_dollar_atp)
8746 *quoted_dollar_atp = 1;
8747 if (contains_dollar_at)
8748 *contains_dollar_at = 1;
8749
8750 tflag |= W_DOLLARAT;
8751 }
8752
8753 free (name);
8754 free (temp1);
8755 *indexp = sindex;
8756
8757 ret = alloc_word_desc ();
8758 ret->word = temp;
8759 ret->flags = tflag; /* XXX */
8760 return ret;
8761 }
8762
8763 free (temp1);
8764 }
8765 #endif /* ARRAY_VARS */
8766
8767 /* Make sure that NAME is valid before trying to go on. */
8768 if (valid_brace_expansion_word (want_indir ? name + 1 : name,
8769 var_is_special) == 0)
8770 {
8771 temp = (char *)NULL;
8772 goto bad_substitution; /* substitution error */
8773 }
8774
8775 if (want_indir)
8776 {
8777 tdesc = parameter_brace_expand_indir (name + 1, var_is_special, quoted, quoted_dollar_atp, contains_dollar_at);
8778 if (tdesc == &expand_wdesc_error || tdesc == &expand_wdesc_fatal)
8779 {
8780 temp = (char *)NULL;
8781 goto bad_substitution;
8782 }
8783
8784 /* Turn off the W_ARRAYIND flag because there is no way for this function
8785 to return the index we're supposed to be using. */
8786 if (tdesc && tdesc->flags)
8787 tdesc->flags &= ~W_ARRAYIND;
8788 }
8789 else
8790 tdesc = parameter_brace_expand_word (name, var_is_special, quoted, PF_IGNUNBOUND|(pflags&(PF_NOSPLIT2|PF_ASSIGNRHS)), &ind);
8791
8792 if (tdesc == &expand_wdesc_error || tdesc == &expand_wdesc_fatal)
8793 {
8794 tflag = 0;
8795 tdesc = 0;
8796 }
8797
8798 if (tdesc)
8799 {
8800 temp = tdesc->word;
8801 tflag = tdesc->flags;
8802 dispose_word_desc (tdesc);
8803 }
8804 else
8805 temp = (char *)0;
8806
8807 if (temp == &expand_param_error || temp == &expand_param_fatal)
8808 {
8809 FREE (name);
8810 FREE (value);
8811 return (temp == &expand_param_error ? &expand_wdesc_error : &expand_wdesc_fatal);
8812 }
8813
8814 #if defined (ARRAY_VARS)
8815 if (valid_array_reference (name, 0))
8816 {
8817 int qflags;
8818 char *t;
8819
8820 qflags = quoted;
8821 /* If in a context where word splitting will not take place, treat as
8822 if double-quoted. Has effects with $* and ${array[*]} */
8823
8824 if (pflags & PF_ASSIGNRHS)
8825 qflags |= Q_DOUBLE_QUOTES;
8826 /* We duplicate a little code here */
8827 t = mbschr (name, LBRACK);
8828 if (t && ALL_ELEMENT_SUB (t[1]) && t[2] == RBRACK)
8829 {
8830 all_element_arrayref = 1;
8831 if (expand_no_split_dollar_star && t[1] == '*') /* XXX */
8832 qflags |= Q_DOUBLE_QUOTES;
8833 }
8834 chk_atstar (name, qflags, quoted_dollar_atp, contains_dollar_at);
8835 }
8836 #endif
8837
8838 var_is_set = temp != (char *)0;
8839 var_is_null = check_nullness && (var_is_set == 0 || *temp == 0);
8840 /* XXX - this may not need to be restricted to special variables */
8841 if (check_nullness)
8842 var_is_null |= var_is_set && var_is_special && (quoted & (Q_HERE_DOCUMENT|Q_DOUBLE_QUOTES)) && QUOTED_NULL (temp);
8843 #if defined (ARRAY_VARS)
8844 if (check_nullness)
8845 var_is_null |= var_is_set &&
8846 (quoted & (Q_HERE_DOCUMENT|Q_DOUBLE_QUOTES)) &&
8847 QUOTED_NULL (temp) &&
8848 valid_array_reference (name, 0) &&
8849 chk_atstar (name, 0, (int *)0, (int *)0);
8850 #endif
8851
8852 /* Get the rest of the stuff inside the braces. */
8853 if (c && c != RBRACE)
8854 {
8855 /* Extract the contents of the ${ ... } expansion
8856 according to the Posix.2 rules. */
8857 value = extract_dollar_brace_string (string, &sindex, quoted, (c == '%' || c == '#' || c =='/' || c == '^' || c == ',' || c ==':') ? SX_POSIXEXP|SX_WORD : SX_WORD);
8858 if (string[sindex] == RBRACE)
8859 sindex++;
8860 else
8861 goto bad_substitution; /* substitution error */
8862 }
8863 else
8864 value = (char *)NULL;
8865
8866 *indexp = sindex;
8867
8868 /* All the cases where an expansion can possibly generate an unbound
8869 variable error. */
8870 if (want_substring || want_patsub || want_casemod || c == '#' || c == '%' || c == RBRACE)
8871 {
8872 if (var_is_set == 0 && unbound_vars_is_error && ((name[0] != '@' && name[0] != '*') || name[1]) && all_element_arrayref == 0)
8873 {
8874 last_command_exit_value = EXECUTION_FAILURE;
8875 err_unboundvar (name);
8876 FREE (value);
8877 FREE (temp);
8878 free (name);
8879 return (interactive_shell ? &expand_wdesc_error : &expand_wdesc_fatal);
8880 }
8881 }
8882
8883 /* If this is a substring spec, process it and add the result. */
8884 if (want_substring)
8885 {
8886 temp1 = parameter_brace_substring (name, temp, ind, value, quoted, pflags, (tflag & W_ARRAYIND) ? AV_USEIND : 0);
8887 FREE (value);
8888 FREE (temp);
8889
8890 if (temp1 == &expand_param_error || temp1 == &expand_param_fatal)
8891 {
8892 FREE (name);
8893 return (temp1 == &expand_param_error ? &expand_wdesc_error : &expand_wdesc_fatal);
8894 }
8895
8896 ret = alloc_word_desc ();
8897 ret->word = temp1;
8898 /* We test quoted_dollar_atp because we want variants with double-quoted
8899 "$@" to take a different code path. In fact, we make sure at the end
8900 of expand_word_internal that we're only looking at these flags if
8901 quoted_dollar_at == 0. */
8902 if (temp1 &&
8903 (quoted_dollar_atp == 0 || *quoted_dollar_atp == 0) &&
8904 QUOTED_NULL (temp1) && (quoted & (Q_HERE_DOCUMENT|Q_DOUBLE_QUOTES)))
8905 ret->flags |= W_QUOTED|W_HASQUOTEDNULL;
8906 /* Special handling for $* when unquoted and $IFS is null. Posix interp 888 */
8907 else if (temp1 && (name[0] == '*' && name[1] == 0) && quoted == 0 && ifs_is_null)
8908 ret->flags |= W_SPLITSPACE; /* Posix interp 888 */
8909
8910 FREE (name);
8911 return ret;
8912 }
8913 else if (want_patsub)
8914 {
8915 temp1 = parameter_brace_patsub (name, temp, ind, value, quoted, pflags, (tflag & W_ARRAYIND) ? AV_USEIND : 0);
8916 FREE (value);
8917 FREE (temp);
8918
8919 if (temp1 == &expand_param_error || temp1 == &expand_param_fatal)
8920 {
8921 FREE (name);
8922 return (temp1 == &expand_param_error ? &expand_wdesc_error : &expand_wdesc_fatal);
8923 }
8924
8925 ret = alloc_word_desc ();
8926 ret->word = temp1;
8927 if (temp1 &&
8928 (quoted_dollar_atp == 0 || *quoted_dollar_atp == 0) &&
8929 QUOTED_NULL (temp1) && (quoted & (Q_HERE_DOCUMENT|Q_DOUBLE_QUOTES)))
8930 ret->flags |= W_QUOTED|W_HASQUOTEDNULL;
8931 /* Special handling for $* when unquoted and $IFS is null. Posix interp 888 */
8932 else if (temp1 && (name[0] == '*' && name[1] == 0) && quoted == 0 && ifs_is_null)
8933 ret->flags |= W_SPLITSPACE; /* Posix interp 888 */
8934
8935 FREE (name);
8936 return ret;
8937 }
8938 #if defined (CASEMOD_EXPANSIONS)
8939 else if (want_casemod)
8940 {
8941 temp1 = parameter_brace_casemod (name, temp, ind, modspec, value, quoted, pflags, (tflag & W_ARRAYIND) ? AV_USEIND : 0);
8942 FREE (value);
8943 FREE (temp);
8944
8945 if (temp1 == &expand_param_error || temp1 == &expand_param_fatal)
8946 {
8947 FREE (name);
8948 return (temp1 == &expand_param_error ? &expand_wdesc_error : &expand_wdesc_fatal);
8949 }
8950
8951 ret = alloc_word_desc ();
8952 ret->word = temp1;
8953 if (temp1 &&
8954 (quoted_dollar_atp == 0 || *quoted_dollar_atp == 0) &&
8955 QUOTED_NULL (temp1) && (quoted & (Q_HERE_DOCUMENT|Q_DOUBLE_QUOTES)))
8956 ret->flags |= W_QUOTED|W_HASQUOTEDNULL;
8957 /* Special handling for $* when unquoted and $IFS is null. Posix interp 888 */
8958 else if (temp1 && (name[0] == '*' && name[1] == 0) && quoted == 0 && ifs_is_null)
8959 ret->flags |= W_SPLITSPACE; /* Posix interp 888 */
8960
8961 FREE (name);
8962 return ret;
8963 }
8964 #endif
8965
8966 /* Do the right thing based on which character ended the variable name. */
8967 switch (c)
8968 {
8969 default:
8970 case '\0':
8971 bad_substitution:
8972 last_command_exit_value = EXECUTION_FAILURE;
8973 report_error (_("%s: bad substitution"), string ? string : "??");
8974 FREE (value);
8975 FREE (temp);
8976 free (name);
8977 if (shell_compatibility_level <= 43)
8978 return &expand_wdesc_error;
8979 else
8980 return ((posixly_correct && interactive_shell == 0) ? &expand_wdesc_fatal : &expand_wdesc_error);
8981
8982 case RBRACE:
8983 break;
8984
8985 case '@':
8986 temp1 = parameter_brace_transform (name, temp, ind, value, c, quoted, pflags, (tflag & W_ARRAYIND) ? AV_USEIND : 0);
8987 free (temp);
8988 free (value);
8989
8990 if (temp1 == &expand_param_error || temp1 == &expand_param_fatal)
8991 {
8992 free (name);
8993 last_command_exit_value = EXECUTION_FAILURE;
8994 report_error (_("%s: bad substitution"), string ? string : "??");
8995 return (temp1 == &expand_param_error ? &expand_wdesc_error : &expand_wdesc_fatal);
8996 }
8997
8998 ret = alloc_word_desc ();
8999 ret->word = temp1;
9000 if (temp1 && QUOTED_NULL (temp1) && (quoted & (Q_HERE_DOCUMENT|Q_DOUBLE_QUOTES)))
9001 ret->flags |= W_QUOTED|W_HASQUOTEDNULL;
9002 /* Special handling for $* when unquoted and $IFS is null. Posix interp 888 */
9003 else if (temp1 && (name[0] == '*' && name[1] == 0) && quoted == 0 && ifs_is_null)
9004 ret->flags |= W_SPLITSPACE; /* Posix interp 888 */
9005
9006 free (name);
9007 return ret;
9008
9009 case '#': /* ${param#[#]pattern} */
9010 case '%': /* ${param%[%]pattern} */
9011 if (value == 0 || *value == '\0' || temp == 0 || *temp == '\0')
9012 {
9013 FREE (value);
9014 break;
9015 }
9016 temp1 = parameter_brace_remove_pattern (name, temp, ind, value, c, quoted, (tflag & W_ARRAYIND) ? AV_USEIND : 0);
9017 free (temp);
9018 free (value);
9019
9020 ret = alloc_word_desc ();
9021 ret->word = temp1;
9022 if (temp1 && QUOTED_NULL (temp1) && (quoted & (Q_HERE_DOCUMENT|Q_DOUBLE_QUOTES)))
9023 ret->flags |= W_QUOTED|W_HASQUOTEDNULL;
9024 /* Special handling for $* when unquoted and $IFS is null. Posix interp 888 */
9025 else if (temp1 && (name[0] == '*' && name[1] == 0) && quoted == 0 && ifs_is_null)
9026 ret->flags |= W_SPLITSPACE; /* Posix interp 888 */
9027
9028 free (name);
9029 return ret;
9030
9031 case '-':
9032 case '=':
9033 case '?':
9034 case '+':
9035 if (var_is_set && var_is_null == 0)
9036 {
9037 /* If the operator is `+', we don't want the value of the named
9038 variable for anything, just the value of the right hand side. */
9039 if (c == '+')
9040 {
9041 /* XXX -- if we're double-quoted and the named variable is "$@",
9042 we want to turn off any special handling of "$@" --
9043 we're not using it, so whatever is on the rhs applies. */
9044 if ((quoted & (Q_HERE_DOCUMENT|Q_DOUBLE_QUOTES)) && quoted_dollar_atp)
9045 *quoted_dollar_atp = 0;
9046 if (contains_dollar_at)
9047 *contains_dollar_at = 0;
9048
9049 FREE (temp);
9050 if (value)
9051 {
9052 /* From Posix discussion on austin-group list. Issue 221
9053 requires that backslashes escaping `}' inside
9054 double-quoted ${...} be removed. */
9055 if (quoted & (Q_HERE_DOCUMENT|Q_DOUBLE_QUOTES))
9056 quoted |= Q_DOLBRACE;
9057 ret = parameter_brace_expand_rhs (name, value, c,
9058 quoted,
9059 pflags,
9060 quoted_dollar_atp,
9061 contains_dollar_at);
9062 /* XXX - fix up later, esp. noting presence of
9063 W_HASQUOTEDNULL in ret->flags */
9064 free (value);
9065 }
9066 else
9067 temp = (char *)NULL;
9068 }
9069 else
9070 {
9071 FREE (value);
9072 }
9073 /* Otherwise do nothing; just use the value in TEMP. */
9074 }
9075 else /* VAR not set or VAR is NULL. */
9076 {
9077 FREE (temp);
9078 temp = (char *)NULL;
9079 if (c == '=' && var_is_special)
9080 {
9081 last_command_exit_value = EXECUTION_FAILURE;
9082 report_error (_("$%s: cannot assign in this way"), name);
9083 free (name);
9084 free (value);
9085 return &expand_wdesc_error;
9086 }
9087 else if (c == '?')
9088 {
9089 parameter_brace_expand_error (name, value, check_nullness);
9090 return (interactive_shell ? &expand_wdesc_error : &expand_wdesc_fatal);
9091 }
9092 else if (c != '+')
9093 {
9094 /* XXX -- if we're double-quoted and the named variable is "$@",
9095 we want to turn off any special handling of "$@" --
9096 we're not using it, so whatever is on the rhs applies. */
9097 if ((quoted & (Q_HERE_DOCUMENT|Q_DOUBLE_QUOTES)) && quoted_dollar_atp)
9098 *quoted_dollar_atp = 0;
9099 if (contains_dollar_at)
9100 *contains_dollar_at = 0;
9101
9102 /* From Posix discussion on austin-group list. Issue 221 requires
9103 that backslashes escaping `}' inside double-quoted ${...} be
9104 removed. */
9105 if (quoted & (Q_HERE_DOCUMENT|Q_DOUBLE_QUOTES))
9106 quoted |= Q_DOLBRACE;
9107 ret = parameter_brace_expand_rhs (name, value, c, quoted, pflags,
9108 quoted_dollar_atp,
9109 contains_dollar_at);
9110 /* XXX - fix up later, esp. noting presence of
9111 W_HASQUOTEDNULL in tdesc->flags */
9112 }
9113 free (value);
9114 }
9115
9116 break;
9117 }
9118 free (name);
9119
9120 if (ret == 0)
9121 {
9122 ret = alloc_word_desc ();
9123 ret->flags = tflag;
9124 ret->word = temp;
9125 }
9126 return (ret);
9127 }
9128
9129 /* Expand a single ${xxx} expansion. The braces are optional. When
9130 the braces are used, parameter_brace_expand() does the work,
9131 possibly calling param_expand recursively. */
9132 static WORD_DESC *
9133 param_expand (string, sindex, quoted, expanded_something,
9134 contains_dollar_at, quoted_dollar_at_p, had_quoted_null_p,
9135 pflags)
9136 char *string;
9137 int *sindex, quoted, *expanded_something, *contains_dollar_at;
9138 int *quoted_dollar_at_p, *had_quoted_null_p, pflags;
9139 {
9140 char *temp, *temp1, uerror[3], *savecmd;
9141 int zindex, t_index, expok;
9142 unsigned char c;
9143 intmax_t number;
9144 SHELL_VAR *var;
9145 WORD_LIST *list;
9146 WORD_DESC *tdesc, *ret;
9147 int tflag;
9148
9149 /*itrace("param_expand: `%s' pflags = %d", string+*sindex, pflags);*/
9150 zindex = *sindex;
9151 c = string[++zindex];
9152
9153 temp = (char *)NULL;
9154 ret = tdesc = (WORD_DESC *)NULL;
9155 tflag = 0;
9156
9157 /* Do simple cases first. Switch on what follows '$'. */
9158 switch (c)
9159 {
9160 /* $0 .. $9? */
9161 case '0':
9162 case '1':
9163 case '2':
9164 case '3':
9165 case '4':
9166 case '5':
9167 case '6':
9168 case '7':
9169 case '8':
9170 case '9':
9171 temp1 = dollar_vars[TODIGIT (c)];
9172 /* This doesn't get called when (pflags&PF_IGNUNBOUND) != 0 */
9173 if (unbound_vars_is_error && temp1 == (char *)NULL)
9174 {
9175 uerror[0] = '$';
9176 uerror[1] = c;
9177 uerror[2] = '\0';
9178 last_command_exit_value = EXECUTION_FAILURE;
9179 err_unboundvar (uerror);
9180 return (interactive_shell ? &expand_wdesc_error : &expand_wdesc_fatal);
9181 }
9182 if (temp1)
9183 temp = (*temp1 && (quoted & (Q_HERE_DOCUMENT|Q_DOUBLE_QUOTES)))
9184 ? quote_string (temp1)
9185 : quote_escapes (temp1);
9186 else
9187 temp = (char *)NULL;
9188
9189 break;
9190
9191 /* $$ -- pid of the invoking shell. */
9192 case '$':
9193 temp = itos (dollar_dollar_pid);
9194 break;
9195
9196 /* $# -- number of positional parameters. */
9197 case '#':
9198 temp = itos (number_of_args ());
9199 break;
9200
9201 /* $? -- return value of the last synchronous command. */
9202 case '?':
9203 temp = itos (last_command_exit_value);
9204 break;
9205
9206 /* $- -- flags supplied to the shell on invocation or by `set'. */
9207 case '-':
9208 temp = which_set_flags ();
9209 break;
9210
9211 /* $! -- Pid of the last asynchronous command. */
9212 case '!':
9213 /* If no asynchronous pids have been created, expand to nothing.
9214 If `set -u' has been executed, and no async processes have
9215 been created, this is an expansion error. */
9216 if (last_asynchronous_pid == NO_PID)
9217 {
9218 if (expanded_something)
9219 *expanded_something = 0;
9220 temp = (char *)NULL;
9221 if (unbound_vars_is_error && (pflags & PF_IGNUNBOUND) == 0)
9222 {
9223 uerror[0] = '$';
9224 uerror[1] = c;
9225 uerror[2] = '\0';
9226 last_command_exit_value = EXECUTION_FAILURE;
9227 err_unboundvar (uerror);
9228 return (interactive_shell ? &expand_wdesc_error : &expand_wdesc_fatal);
9229 }
9230 }
9231 else
9232 temp = itos (last_asynchronous_pid);
9233 break;
9234
9235 /* The only difference between this and $@ is when the arg is quoted. */
9236 case '*': /* `$*' */
9237 list = list_rest_of_args ();
9238
9239 #if 0
9240 /* According to austin-group posix proposal by Geoff Clare in
9241 <20090505091501.GA10097@squonk.masqnet> of 5 May 2009:
9242
9243 "The shell shall write a message to standard error and
9244 immediately exit when it tries to expand an unset parameter
9245 other than the '@' and '*' special parameters."
9246 */
9247
9248 if (list == 0 && unbound_vars_is_error && (pflags & PF_IGNUNBOUND) == 0)
9249 {
9250 uerror[0] = '$';
9251 uerror[1] = '*';
9252 uerror[2] = '\0';
9253 last_command_exit_value = EXECUTION_FAILURE;
9254 err_unboundvar (uerror);
9255 return (interactive_shell ? &expand_wdesc_error : &expand_wdesc_fatal);
9256 }
9257 #endif
9258
9259 /* If there are no command-line arguments, this should just
9260 disappear if there are other characters in the expansion,
9261 even if it's quoted. */
9262 if ((quoted & (Q_HERE_DOCUMENT|Q_DOUBLE_QUOTES)) && list == 0)
9263 temp = (char *)NULL;
9264 else if (quoted & (Q_HERE_DOCUMENT|Q_DOUBLE_QUOTES|Q_PATQUOTE))
9265 {
9266 /* If we have "$*" we want to make a string of the positional
9267 parameters, separated by the first character of $IFS, and
9268 quote the whole string, including the separators. If IFS
9269 is unset, the parameters are separated by ' '; if $IFS is
9270 null, the parameters are concatenated. */
9271 temp = (quoted & (Q_DOUBLE_QUOTES|Q_PATQUOTE)) ? string_list_dollar_star (list, quoted, 0) : string_list (list);
9272 if (temp)
9273 {
9274 temp1 = (quoted & Q_DOUBLE_QUOTES) ? quote_string (temp) : temp;
9275 if (*temp == 0)
9276 tflag |= W_HASQUOTEDNULL;
9277 if (temp != temp1)
9278 free (temp);
9279 temp = temp1;
9280 }
9281 }
9282 else
9283 {
9284 /* We check whether or not we're eventually going to split $* here,
9285 for example when IFS is empty and we are processing the rhs of
9286 an assignment statement. In that case, we don't separate the
9287 arguments at all. Otherwise, if the $* is not quoted it is
9288 identical to $@ */
9289 if (expand_no_split_dollar_star && quoted == 0 && ifs_is_set == 0 && (pflags & PF_ASSIGNRHS))
9290 {
9291 /* Posix interp 888: RHS of assignment, IFS unset */
9292 temp = string_list_dollar_at (list, Q_DOUBLE_QUOTES, pflags);
9293 tflag |= W_SPLITSPACE;
9294 }
9295 else if (expand_no_split_dollar_star && quoted == 0 && ifs_is_null && (pflags & PF_ASSIGNRHS))
9296 {
9297 /* Posix interp 888: RHS of assignment, IFS set to '' */
9298 temp1 = string_list_dollar_star (list, quoted, pflags);
9299 temp = temp1 ? quote_escapes (temp1) : temp1;
9300 FREE (temp1);
9301 }
9302 else if (expand_no_split_dollar_star && quoted == 0 && ifs_is_set && ifs_is_null == 0 && (pflags & PF_ASSIGNRHS))
9303 {
9304 /* Posix interp 888: RHS of assignment, IFS set to non-null value */
9305 temp1 = string_list_dollar_star (list, quoted, pflags);
9306 temp = temp1 ? quote_string (temp1) : temp1;
9307 FREE (temp1);
9308 }
9309 /* XXX - should we check ifs_is_set here as well? */
9310 # if defined (HANDLE_MULTIBYTE)
9311 else if (expand_no_split_dollar_star && ifs_firstc[0] == 0)
9312 # else
9313 else if (expand_no_split_dollar_star && ifs_firstc == 0)
9314 # endif
9315 /* Posix interp 888: not RHS, no splitting, IFS set to '' */
9316 temp = string_list_dollar_star (list, quoted, 0);
9317 else
9318 {
9319 temp = string_list_dollar_at (list, quoted, 0);
9320 /* Set W_SPLITSPACE to make sure the individual positional
9321 parameters are split into separate arguments */
9322 #if 0
9323 if (quoted == 0 && (ifs_is_set == 0 || ifs_is_null))
9324 #else /* change with bash-5.0 */
9325 if (quoted == 0 && ifs_is_null)
9326 #endif
9327 tflag |= W_SPLITSPACE;
9328 /* If we're not quoted but we still don't want word splitting, make
9329 we quote the IFS characters to protect them from splitting (e.g.,
9330 when $@ is in the string as well). */
9331 else if (temp && quoted == 0 && ifs_is_set && (pflags & PF_ASSIGNRHS))
9332 {
9333 temp1 = quote_string (temp);
9334 free (temp);
9335 temp = temp1;
9336 }
9337 }
9338
9339 if (expand_no_split_dollar_star == 0 && contains_dollar_at)
9340 *contains_dollar_at = 1;
9341 }
9342
9343 dispose_words (list);
9344 break;
9345
9346 /* When we have "$@" what we want is "$1" "$2" "$3" ... This
9347 means that we have to turn quoting off after we split into
9348 the individually quoted arguments so that the final split
9349 on the first character of $IFS is still done. */
9350 case '@': /* `$@' */
9351 list = list_rest_of_args ();
9352
9353 #if 0
9354 /* According to austin-group posix proposal by Geoff Clare in
9355 <20090505091501.GA10097@squonk.masqnet> of 5 May 2009:
9356
9357 "The shell shall write a message to standard error and
9358 immediately exit when it tries to expand an unset parameter
9359 other than the '@' and '*' special parameters."
9360 */
9361
9362 if (list == 0 && unbound_vars_is_error && (pflags & PF_IGNUNBOUND) == 0)
9363 {
9364 uerror[0] = '$';
9365 uerror[1] = '@';
9366 uerror[2] = '\0';
9367 last_command_exit_value = EXECUTION_FAILURE;
9368 err_unboundvar (uerror);
9369 return (interactive_shell ? &expand_wdesc_error : &expand_wdesc_fatal);
9370 }
9371 #endif
9372
9373 /* We want to flag the fact that we saw this. We can't turn
9374 off quoting entirely, because other characters in the
9375 string might need it (consider "\"$@\""), but we need some
9376 way to signal that the final split on the first character
9377 of $IFS should be done, even though QUOTED is 1. */
9378 /* XXX - should this test include Q_PATQUOTE? */
9379 if (quoted_dollar_at_p && (quoted & (Q_HERE_DOCUMENT|Q_DOUBLE_QUOTES)))
9380 *quoted_dollar_at_p = 1;
9381 if (contains_dollar_at)
9382 *contains_dollar_at = 1;
9383
9384 /* We want to separate the positional parameters with the first
9385 character of $IFS in case $IFS is something other than a space.
9386 We also want to make sure that splitting is done no matter what --
9387 according to POSIX.2, this expands to a list of the positional
9388 parameters no matter what IFS is set to. */
9389 /* XXX - what to do when in a context where word splitting is not
9390 performed? Even when IFS is not the default, posix seems to imply
9391 that we behave like unquoted $* ? See below for how we use
9392 PF_NOSPLIT2 here. */
9393
9394 /* These are the cases where word splitting will not be performed. */
9395 if (pflags & PF_ASSIGNRHS)
9396 temp = string_list_dollar_at (list, (quoted|Q_DOUBLE_QUOTES), pflags);
9397 /* This needs to match what expand_word_internal does with non-quoted $@
9398 does with separating with spaces. Passing Q_DOUBLE_QUOTES means that
9399 the characters in LIST will be quoted, and PF_ASSIGNRHS ensures that
9400 they will separated by spaces. After doing this, we need the special
9401 handling for PF_NOSPLIT2 in expand_word_internal to remove the CTLESC
9402 quotes. */
9403 else if (pflags & PF_NOSPLIT2)
9404 {
9405 #if defined (HANDLE_MULTIBYTE)
9406 if (quoted == 0 && ifs_is_set && ifs_is_null == 0 && ifs_firstc[0] != ' ')
9407 #else
9408 if (quoted == 0 && ifs_is_set && ifs_is_null == 0 && ifs_firstc != ' ')
9409 #endif
9410 /* Posix interp 888 */
9411 temp = string_list_dollar_at (list, Q_DOUBLE_QUOTES, pflags);
9412 else
9413 temp = string_list_dollar_at (list, quoted, pflags);
9414 }
9415 else
9416 temp = string_list_dollar_at (list, quoted, pflags);
9417
9418 tflag |= W_DOLLARAT;
9419 dispose_words (list);
9420 break;
9421
9422 case LBRACE:
9423 tdesc = parameter_brace_expand (string, &zindex, quoted, pflags,
9424 quoted_dollar_at_p,
9425 contains_dollar_at);
9426
9427 if (tdesc == &expand_wdesc_error || tdesc == &expand_wdesc_fatal)
9428 return (tdesc);
9429 temp = tdesc ? tdesc->word : (char *)0;
9430
9431 /* XXX */
9432 /* Quoted nulls should be removed if there is anything else
9433 in the string. */
9434 /* Note that we saw the quoted null so we can add one back at
9435 the end of this function if there are no other characters
9436 in the string, discard TEMP, and go on. The exception to
9437 this is when we have "${@}" and $1 is '', since $@ needs
9438 special handling. */
9439 if (tdesc && tdesc->word && (tdesc->flags & W_HASQUOTEDNULL) && QUOTED_NULL (temp))
9440 {
9441 if (had_quoted_null_p)
9442 *had_quoted_null_p = 1;
9443 if (*quoted_dollar_at_p == 0)
9444 {
9445 free (temp);
9446 tdesc->word = temp = (char *)NULL;
9447 }
9448
9449 }
9450
9451 ret = tdesc;
9452 goto return0;
9453
9454 /* Do command or arithmetic substitution. */
9455 case LPAREN:
9456 /* We have to extract the contents of this paren substitution. */
9457 t_index = zindex + 1;
9458 /* XXX - might want to check for string[t_index+2] == LPAREN and parse
9459 as arithmetic substitution immediately. */
9460 temp = extract_command_subst (string, &t_index, (pflags&PF_COMPLETE) ? SX_COMPLETE : 0);
9461 zindex = t_index;
9462
9463 /* For Posix.2-style `$(( ))' arithmetic substitution,
9464 extract the expression and pass it to the evaluator. */
9465 if (temp && *temp == LPAREN)
9466 {
9467 char *temp2;
9468 temp1 = temp + 1;
9469 temp2 = savestring (temp1);
9470 t_index = strlen (temp2) - 1;
9471
9472 if (temp2[t_index] != RPAREN)
9473 {
9474 free (temp2);
9475 goto comsub;
9476 }
9477
9478 /* Cut off ending `)' */
9479 temp2[t_index] = '\0';
9480
9481 if (chk_arithsub (temp2, t_index) == 0)
9482 {
9483 free (temp2);
9484 #if 0
9485 internal_warning (_("future versions of the shell will force evaluation as an arithmetic substitution"));
9486 #endif
9487 goto comsub;
9488 }
9489
9490 /* Expand variables found inside the expression. */
9491 temp1 = expand_arith_string (temp2, Q_DOUBLE_QUOTES|Q_ARITH);
9492 free (temp2);
9493
9494 arithsub:
9495 /* No error messages. */
9496 savecmd = this_command_name;
9497 this_command_name = (char *)NULL;
9498 number = evalexp (temp1, EXP_EXPANDED, &expok);
9499 this_command_name = savecmd;
9500 free (temp);
9501 free (temp1);
9502 if (expok == 0)
9503 {
9504 if (interactive_shell == 0 && posixly_correct)
9505 {
9506 last_command_exit_value = EXECUTION_FAILURE;
9507 return (&expand_wdesc_fatal);
9508 }
9509 else
9510 return (&expand_wdesc_error);
9511 }
9512 temp = itos (number);
9513 break;
9514 }
9515
9516 comsub:
9517 if (pflags & PF_NOCOMSUB)
9518 /* we need zindex+1 because string[zindex] == RPAREN */
9519 temp1 = substring (string, *sindex, zindex+1);
9520 else
9521 {
9522 tdesc = command_substitute (temp, quoted, pflags&PF_ASSIGNRHS);
9523 temp1 = tdesc ? tdesc->word : (char *)NULL;
9524 if (tdesc)
9525 dispose_word_desc (tdesc);
9526 }
9527 FREE (temp);
9528 temp = temp1;
9529 break;
9530
9531 /* Do POSIX.2d9-style arithmetic substitution. This will probably go
9532 away in a future bash release. */
9533 case '[': /*]*/
9534 /* Extract the contents of this arithmetic substitution. */
9535 t_index = zindex + 1;
9536 temp = extract_arithmetic_subst (string, &t_index);
9537 zindex = t_index;
9538 if (temp == 0)
9539 {
9540 temp = savestring (string);
9541 if (expanded_something)
9542 *expanded_something = 0;
9543 goto return0;
9544 }
9545
9546 /* Do initial variable expansion. */
9547 temp1 = expand_arith_string (temp, Q_DOUBLE_QUOTES|Q_ARITH);
9548
9549 goto arithsub;
9550
9551 default:
9552 /* Find the variable in VARIABLE_LIST. */
9553 temp = (char *)NULL;
9554
9555 for (t_index = zindex; (c = string[zindex]) && legal_variable_char (c); zindex++)
9556 ;
9557 temp1 = (zindex > t_index) ? substring (string, t_index, zindex) : (char *)NULL;
9558
9559 /* If this isn't a variable name, then just output the `$'. */
9560 if (temp1 == 0 || *temp1 == '\0')
9561 {
9562 FREE (temp1);
9563 temp = (char *)xmalloc (2);
9564 temp[0] = '$';
9565 temp[1] = '\0';
9566 if (expanded_something)
9567 *expanded_something = 0;
9568 goto return0;
9569 }
9570
9571 /* If the variable exists, return its value cell. */
9572 var = find_variable (temp1);
9573
9574 if (var && invisible_p (var) == 0 && var_isset (var))
9575 {
9576 #if defined (ARRAY_VARS)
9577 if (assoc_p (var) || array_p (var))
9578 {
9579 temp = array_p (var) ? array_reference (array_cell (var), 0)
9580 : assoc_reference (assoc_cell (var), "0");
9581 if (temp)
9582 temp = (*temp && (quoted & (Q_HERE_DOCUMENT|Q_DOUBLE_QUOTES)))
9583 ? quote_string (temp)
9584 : quote_escapes (temp);
9585 else if (unbound_vars_is_error)
9586 goto unbound_variable;
9587 }
9588 else
9589 #endif
9590 {
9591 temp = value_cell (var);
9592
9593 temp = (*temp && (quoted & (Q_HERE_DOCUMENT|Q_DOUBLE_QUOTES)))
9594 ? quote_string (temp)
9595 : ((pflags & PF_ASSIGNRHS) ? quote_rhs (temp)
9596 : quote_escapes (temp));
9597 }
9598
9599 free (temp1);
9600
9601 goto return0;
9602 }
9603 else if (var && (invisible_p (var) || var_isset (var) == 0))
9604 temp = (char *)NULL;
9605 else if ((var = find_variable_last_nameref (temp1, 0)) && var_isset (var) && invisible_p (var) == 0)
9606 {
9607 temp = nameref_cell (var);
9608 #if defined (ARRAY_VARS)
9609 if (temp && *temp && valid_array_reference (temp, 0))
9610 {
9611 tdesc = parameter_brace_expand_word (temp, SPECIAL_VAR (temp, 0), quoted, pflags, (arrayind_t *)NULL);
9612 if (tdesc == &expand_wdesc_error || tdesc == &expand_wdesc_fatal)
9613 return (tdesc);
9614 ret = tdesc;
9615 goto return0;
9616 }
9617 else
9618 #endif
9619 /* y=2 ; typeset -n x=y; echo $x is not the same as echo $2 in ksh */
9620 if (temp && *temp && legal_identifier (temp) == 0)
9621 {
9622 last_command_exit_value = EXECUTION_FAILURE;
9623 report_error (_("%s: invalid variable name for name reference"), temp);
9624 return (&expand_wdesc_error); /* XXX */
9625 }
9626 else
9627 temp = (char *)NULL;
9628 }
9629
9630 temp = (char *)NULL;
9631
9632 unbound_variable:
9633 if (unbound_vars_is_error)
9634 {
9635 last_command_exit_value = EXECUTION_FAILURE;
9636 err_unboundvar (temp1);
9637 }
9638 else
9639 {
9640 free (temp1);
9641 goto return0;
9642 }
9643
9644 free (temp1);
9645 last_command_exit_value = EXECUTION_FAILURE;
9646 return ((unbound_vars_is_error && interactive_shell == 0)
9647 ? &expand_wdesc_fatal
9648 : &expand_wdesc_error);
9649 }
9650
9651 if (string[zindex])
9652 zindex++;
9653
9654 return0:
9655 *sindex = zindex;
9656
9657 if (ret == 0)
9658 {
9659 ret = alloc_word_desc ();
9660 ret->flags = tflag; /* XXX */
9661 ret->word = temp;
9662 }
9663 return ret;
9664 }
9665
9666 void
9667 invalidate_cached_quoted_dollar_at ()
9668 {
9669 dispose_words (cached_quoted_dollar_at);
9670 cached_quoted_dollar_at = 0;
9671 }
9672
9673 /* Make a word list which is the result of parameter and variable
9674 expansion, command substitution, arithmetic substitution, and
9675 quote removal of WORD. Return a pointer to a WORD_LIST which is
9676 the result of the expansion. If WORD contains a null word, the
9677 word list returned is also null.
9678
9679 QUOTED contains flag values defined in shell.h.
9680
9681 ISEXP is used to tell expand_word_internal that the word should be
9682 treated as the result of an expansion. This has implications for
9683 how IFS characters in the word are treated.
9684
9685 CONTAINS_DOLLAR_AT and EXPANDED_SOMETHING are return values; when non-null
9686 they point to an integer value which receives information about expansion.
9687 CONTAINS_DOLLAR_AT gets non-zero if WORD contained "$@", else zero.
9688 EXPANDED_SOMETHING get non-zero if WORD contained any parameter expansions,
9689 else zero.
9690
9691 This only does word splitting in the case of $@ expansion. In that
9692 case, we split on ' '. */
9693
9694 /* Values for the local variable quoted_state. */
9695 #define UNQUOTED 0
9696 #define PARTIALLY_QUOTED 1
9697 #define WHOLLY_QUOTED 2
9698
9699 static WORD_LIST *
9700 expand_word_internal (word, quoted, isexp, contains_dollar_at, expanded_something)
9701 WORD_DESC *word;
9702 int quoted, isexp;
9703 int *contains_dollar_at;
9704 int *expanded_something;
9705 {
9706 WORD_LIST *list;
9707 WORD_DESC *tword;
9708
9709 /* The intermediate string that we build while expanding. */
9710 char *istring;
9711
9712 /* The current size of the above object. */
9713 size_t istring_size;
9714
9715 /* Index into ISTRING. */
9716 int istring_index;
9717
9718 /* Temporary string storage. */
9719 char *temp, *temp1;
9720
9721 /* The text of WORD. */
9722 register char *string;
9723
9724 /* The size of STRING. */
9725 size_t string_size;
9726
9727 /* The index into STRING. */
9728 int sindex;
9729
9730 /* This gets 1 if we see a $@ while quoted. */
9731 int quoted_dollar_at;
9732
9733 /* One of UNQUOTED, PARTIALLY_QUOTED, or WHOLLY_QUOTED, depending on
9734 whether WORD contains no quoting characters, a partially quoted
9735 string (e.g., "xx"ab), or is fully quoted (e.g., "xxab"). */
9736 int quoted_state;
9737
9738 /* State flags */
9739 int had_quoted_null;
9740 int has_quoted_ifs; /* did we add a quoted $IFS character here? */
9741 int has_dollar_at, temp_has_dollar_at;
9742 int split_on_spaces;
9743 int local_expanded;
9744 int tflag;
9745 int pflags; /* flags passed to param_expand */
9746 int mb_cur_max;
9747
9748 int assignoff; /* If assignment, offset of `=' */
9749
9750 register unsigned char c; /* Current character. */
9751 int t_index; /* For calls to string_extract_xxx. */
9752
9753 char twochars[2];
9754
9755 DECLARE_MBSTATE;
9756
9757 /* OK, let's see if we can optimize a common idiom: "$@" */
9758 if (STREQ (word->word, "\"$@\"") &&
9759 (word->flags == (W_HASDOLLAR|W_QUOTED)) &&
9760 dollar_vars[1]) /* XXX - check IFS here as well? */
9761 {
9762 if (contains_dollar_at)
9763 *contains_dollar_at = 1;
9764 if (expanded_something)
9765 *expanded_something = 1;
9766 if (cached_quoted_dollar_at)
9767 return (copy_word_list (cached_quoted_dollar_at));
9768 list = list_rest_of_args ();
9769 list = quote_list (list);
9770 cached_quoted_dollar_at = copy_word_list (list);
9771 return (list);
9772 }
9773
9774 istring = (char *)xmalloc (istring_size = DEFAULT_INITIAL_ARRAY_SIZE);
9775 istring[istring_index = 0] = '\0';
9776 quoted_dollar_at = had_quoted_null = has_dollar_at = 0;
9777 has_quoted_ifs = 0;
9778 split_on_spaces = 0;
9779 quoted_state = UNQUOTED;
9780
9781 string = word->word;
9782 if (string == 0)
9783 goto finished_with_string;
9784 mb_cur_max = MB_CUR_MAX;
9785
9786 /* Don't need the string length for the SADD... and COPY_ macros unless
9787 multibyte characters are possible, but do need it for bounds checking. */
9788 string_size = (mb_cur_max > 1) ? strlen (string) : 1;
9789
9790 if (contains_dollar_at)
9791 *contains_dollar_at = 0;
9792
9793 assignoff = -1;
9794
9795 /* Begin the expansion. */
9796
9797 for (sindex = 0; ;)
9798 {
9799 c = string[sindex];
9800
9801 /* Case on top-level character. */
9802 switch (c)
9803 {
9804 case '\0':
9805 goto finished_with_string;
9806
9807 case CTLESC:
9808 sindex++;
9809 #if HANDLE_MULTIBYTE
9810 if (mb_cur_max > 1 && string[sindex])
9811 {
9812 SADD_MBQCHAR_BODY(temp, string, sindex, string_size);
9813 }
9814 else
9815 #endif
9816 {
9817 temp = (char *)xmalloc (3);
9818 temp[0] = CTLESC;
9819 temp[1] = c = string[sindex];
9820 temp[2] = '\0';
9821 }
9822
9823 dollar_add_string:
9824 if (string[sindex])
9825 sindex++;
9826
9827 add_string:
9828 if (temp)
9829 {
9830 istring = sub_append_string (temp, istring, &istring_index, &istring_size);
9831 temp = (char *)0;
9832 }
9833
9834 break;
9835
9836 #if defined (PROCESS_SUBSTITUTION)
9837 /* Process substitution. */
9838 case '<':
9839 case '>':
9840 {
9841 /* XXX - technically this should only be expanded at the start
9842 of a word */
9843 if (string[++sindex] != LPAREN || (quoted & (Q_HERE_DOCUMENT|Q_DOUBLE_QUOTES)) || (word->flags & (W_DQUOTE|W_NOPROCSUB)) || posixly_correct)
9844 {
9845 sindex--; /* add_character: label increments sindex */
9846 goto add_character;
9847 }
9848 else
9849 t_index = sindex + 1; /* skip past both '<' and LPAREN */
9850
9851 temp1 = extract_process_subst (string, (c == '<') ? "<(" : ">(", &t_index, 0); /*))*/
9852 sindex = t_index;
9853
9854 /* If the process substitution specification is `<()', we want to
9855 open the pipe for writing in the child and produce output; if
9856 it is `>()', we want to open the pipe for reading in the child
9857 and consume input. */
9858 temp = temp1 ? process_substitute (temp1, (c == '>')) : (char *)0;
9859
9860 FREE (temp1);
9861
9862 goto dollar_add_string;
9863 }
9864 #endif /* PROCESS_SUBSTITUTION */
9865
9866 case '=':
9867 /* Posix.2 section 3.6.1 says that tildes following `=' in words
9868 which are not assignment statements are not expanded. If the
9869 shell isn't in posix mode, though, we perform tilde expansion
9870 on `likely candidate' unquoted assignment statements (flags
9871 include W_ASSIGNMENT but not W_QUOTED). A likely candidate
9872 contains an unquoted :~ or =~. Something to think about: we
9873 now have a flag that says to perform tilde expansion on arguments
9874 to `assignment builtins' like declare and export that look like
9875 assignment statements. We now do tilde expansion on such words
9876 even in POSIX mode. */
9877 if (word->flags & (W_ASSIGNRHS|W_NOTILDE))
9878 {
9879 if (isexp == 0 && (word->flags & (W_NOSPLIT|W_NOSPLIT2)) == 0 && isifs (c))
9880 goto add_ifs_character;
9881 else
9882 goto add_character;
9883 }
9884 /* If we're not in posix mode or forcing assignment-statement tilde
9885 expansion, note where the `=' appears in the word and prepare to
9886 do tilde expansion following the first `='. */
9887 if ((word->flags & W_ASSIGNMENT) &&
9888 (posixly_correct == 0 || (word->flags & W_TILDEEXP)) &&
9889 assignoff == -1 && sindex > 0)
9890 assignoff = sindex;
9891 if (sindex == assignoff && string[sindex+1] == '~') /* XXX */
9892 word->flags |= W_ITILDE;
9893 #if 0
9894 else if ((word->flags & W_ASSIGNMENT) &&
9895 (posixly_correct == 0 || (word->flags & W_TILDEEXP)) &&
9896 string[sindex+1] == '~')
9897 word->flags |= W_ITILDE;
9898 #endif
9899
9900 if (word->flags & W_ASSIGNARG)
9901 word->flags |= W_ASSIGNRHS; /* affects $@ */
9902
9903 if (isexp == 0 && (word->flags & (W_NOSPLIT|W_NOSPLIT2)) == 0 && isifs (c))
9904 {
9905 has_quoted_ifs++;
9906 goto add_ifs_character;
9907 }
9908 else
9909 goto add_character;
9910
9911 case ':':
9912 if (word->flags & (W_NOTILDE|W_NOASSNTILDE))
9913 {
9914 if (isexp == 0 && (word->flags & (W_NOSPLIT|W_NOSPLIT2)) == 0 && isifs (c))
9915 goto add_ifs_character;
9916 else
9917 goto add_character;
9918 }
9919
9920 if ((word->flags & (W_ASSIGNMENT|W_ASSIGNRHS|W_TILDEEXP)) &&
9921 string[sindex+1] == '~')
9922 word->flags |= W_ITILDE;
9923
9924 if (isexp == 0 && (word->flags & (W_NOSPLIT|W_NOSPLIT2)) == 0 && isifs (c))
9925 goto add_ifs_character;
9926 else
9927 goto add_character;
9928
9929 case '~':
9930 /* If the word isn't supposed to be tilde expanded, or we're not
9931 at the start of a word or after an unquoted : or = in an
9932 assignment statement, we don't do tilde expansion. We don't
9933 do tilde expansion if quoted or in an arithmetic context. */
9934
9935 if ((word->flags & (W_NOTILDE|W_DQUOTE)) ||
9936 (sindex > 0 && ((word->flags & W_ITILDE) == 0)) ||
9937 (quoted & (Q_DOUBLE_QUOTES|Q_HERE_DOCUMENT)))
9938 {
9939 word->flags &= ~W_ITILDE;
9940 if (isexp == 0 && (word->flags & (W_NOSPLIT|W_NOSPLIT2)) == 0 && isifs (c) && (quoted & (Q_DOUBLE_QUOTES|Q_HERE_DOCUMENT)) == 0)
9941 goto add_ifs_character;
9942 else
9943 goto add_character;
9944 }
9945
9946 if (word->flags & W_ASSIGNRHS)
9947 tflag = 2;
9948 else if (word->flags & (W_ASSIGNMENT|W_TILDEEXP))
9949 tflag = 1;
9950 else
9951 tflag = 0;
9952
9953 temp = bash_tilde_find_word (string + sindex, tflag, &t_index);
9954
9955 word->flags &= ~W_ITILDE;
9956
9957 if (temp && *temp && t_index > 0)
9958 {
9959 temp1 = bash_tilde_expand (temp, tflag);
9960 if (temp1 && *temp1 == '~' && STREQ (temp, temp1))
9961 {
9962 FREE (temp);
9963 FREE (temp1);
9964 goto add_character; /* tilde expansion failed */
9965 }
9966 free (temp);
9967 temp = temp1;
9968 sindex += t_index;
9969 goto add_quoted_string; /* XXX was add_string */
9970 }
9971 else
9972 {
9973 FREE (temp);
9974 goto add_character;
9975 }
9976
9977 case '$':
9978 if (expanded_something)
9979 *expanded_something = 1;
9980 local_expanded = 1;
9981
9982 temp_has_dollar_at = 0;
9983 pflags = (word->flags & W_NOCOMSUB) ? PF_NOCOMSUB : 0;
9984 if (word->flags & W_NOSPLIT2)
9985 pflags |= PF_NOSPLIT2;
9986 if (word->flags & W_ASSIGNRHS)
9987 pflags |= PF_ASSIGNRHS;
9988 if (word->flags & W_COMPLETE)
9989 pflags |= PF_COMPLETE;
9990 tword = param_expand (string, &sindex, quoted, expanded_something,
9991 &temp_has_dollar_at, &quoted_dollar_at,
9992 &had_quoted_null, pflags);
9993 has_dollar_at += temp_has_dollar_at;
9994 split_on_spaces += (tword->flags & W_SPLITSPACE);
9995
9996 if (tword == &expand_wdesc_error || tword == &expand_wdesc_fatal)
9997 {
9998 free (string);
9999 free (istring);
10000 return ((tword == &expand_wdesc_error) ? &expand_word_error
10001 : &expand_word_fatal);
10002 }
10003 if (contains_dollar_at && has_dollar_at)
10004 *contains_dollar_at = 1;
10005
10006 if (tword && (tword->flags & W_HASQUOTEDNULL))
10007 had_quoted_null = 1; /* note for later */
10008 if (tword && (tword->flags & W_SAWQUOTEDNULL))
10009 had_quoted_null = 1; /* XXX */
10010
10011 temp = tword ? tword->word : (char *)NULL;
10012 dispose_word_desc (tword);
10013
10014 /* Kill quoted nulls; we will add them back at the end of
10015 expand_word_internal if nothing else in the string */
10016 if (had_quoted_null && temp && QUOTED_NULL (temp))
10017 {
10018 FREE (temp);
10019 temp = (char *)NULL;
10020 }
10021
10022 goto add_string;
10023 break;
10024
10025 case '`': /* Backquoted command substitution. */
10026 {
10027 t_index = sindex++;
10028
10029 temp = string_extract (string, &sindex, "`", SX_REQMATCH);
10030 /* The test of sindex against t_index is to allow bare instances of
10031 ` to pass through, for backwards compatibility. */
10032 if (temp == &extract_string_error || temp == &extract_string_fatal)
10033 {
10034 if (sindex - 1 == t_index)
10035 {
10036 sindex = t_index;
10037 goto add_character;
10038 }
10039 last_command_exit_value = EXECUTION_FAILURE;
10040 report_error (_("bad substitution: no closing \"`\" in %s") , string+t_index);
10041 free (string);
10042 free (istring);
10043 return ((temp == &extract_string_error) ? &expand_word_error
10044 : &expand_word_fatal);
10045 }
10046
10047 if (expanded_something)
10048 *expanded_something = 1;
10049 local_expanded = 1;
10050
10051 if (word->flags & W_NOCOMSUB)
10052 /* sindex + 1 because string[sindex] == '`' */
10053 temp1 = substring (string, t_index, sindex + 1);
10054 else
10055 {
10056 de_backslash (temp);
10057 tword = command_substitute (temp, quoted, 0);
10058 temp1 = tword ? tword->word : (char *)NULL;
10059 if (tword)
10060 dispose_word_desc (tword);
10061 }
10062 FREE (temp);
10063 temp = temp1;
10064 goto dollar_add_string;
10065 }
10066
10067 case '\\':
10068 if (string[sindex + 1] == '\n')
10069 {
10070 sindex += 2;
10071 continue;
10072 }
10073
10074 c = string[++sindex];
10075
10076 if (quoted & Q_HERE_DOCUMENT)
10077 tflag = CBSHDOC;
10078 else if (quoted & Q_DOUBLE_QUOTES)
10079 tflag = CBSDQUOTE;
10080 else
10081 tflag = 0;
10082
10083 /* From Posix discussion on austin-group list: Backslash escaping
10084 a } in ${...} is removed. Issue 0000221 */
10085 if ((quoted & Q_DOLBRACE) && c == RBRACE)
10086 {
10087 SCOPY_CHAR_I (twochars, CTLESC, c, string, sindex, string_size);
10088 }
10089 /* This is the fix for " $@\ " */
10090 else if ((quoted & (Q_HERE_DOCUMENT|Q_DOUBLE_QUOTES)) && ((sh_syntaxtab[c] & tflag) == 0) && isexp == 0 && isifs (c))
10091 {
10092 RESIZE_MALLOCED_BUFFER (istring, istring_index, 2, istring_size,
10093 DEFAULT_ARRAY_SIZE);
10094 istring[istring_index++] = CTLESC;
10095 istring[istring_index++] = '\\';
10096 istring[istring_index] = '\0';
10097
10098 SCOPY_CHAR_I (twochars, CTLESC, c, string, sindex, string_size);
10099 }
10100 else if ((quoted & (Q_HERE_DOCUMENT|Q_DOUBLE_QUOTES)) && c == 0)
10101 {
10102 RESIZE_MALLOCED_BUFFER (istring, istring_index, 2, istring_size,
10103 DEFAULT_ARRAY_SIZE);
10104 istring[istring_index++] = CTLESC;
10105 istring[istring_index++] = '\\';
10106 istring[istring_index] = '\0';
10107 break;
10108 }
10109 else if ((quoted & (Q_HERE_DOCUMENT|Q_DOUBLE_QUOTES)) && ((sh_syntaxtab[c] & tflag) == 0))
10110 {
10111 SCOPY_CHAR_I (twochars, '\\', c, string, sindex, string_size);
10112 }
10113 else if (c == 0)
10114 {
10115 c = CTLNUL;
10116 sindex--; /* add_character: label increments sindex */
10117 goto add_character;
10118 }
10119 else
10120 {
10121 SCOPY_CHAR_I (twochars, CTLESC, c, string, sindex, string_size);
10122 }
10123
10124 sindex++;
10125 add_twochars:
10126 /* BEFORE jumping here, we need to increment sindex if appropriate */
10127 RESIZE_MALLOCED_BUFFER (istring, istring_index, 2, istring_size,
10128 DEFAULT_ARRAY_SIZE);
10129 istring[istring_index++] = twochars[0];
10130 istring[istring_index++] = twochars[1];
10131 istring[istring_index] = '\0';
10132
10133 break;
10134
10135 case '"':
10136 if ((quoted & (Q_DOUBLE_QUOTES|Q_HERE_DOCUMENT)) && ((quoted & Q_ARITH) == 0))
10137 goto add_character;
10138
10139 t_index = ++sindex;
10140 temp = string_extract_double_quoted (string, &sindex, (word->flags & W_COMPLETE) ? SX_COMPLETE : 0);
10141
10142 /* If the quotes surrounded the entire string, then the
10143 whole word was quoted. */
10144 quoted_state = (t_index == 1 && string[sindex] == '\0')
10145 ? WHOLLY_QUOTED
10146 : PARTIALLY_QUOTED;
10147
10148 if (temp && *temp)
10149 {
10150 tword = alloc_word_desc ();
10151 tword->word = temp;
10152
10153 if (word->flags & W_ASSIGNARG)
10154 tword->flags |= word->flags & (W_ASSIGNARG|W_ASSIGNRHS); /* affects $@ */
10155 if (word->flags & W_COMPLETE)
10156 tword->flags |= W_COMPLETE; /* for command substitutions */
10157 if (word->flags & W_NOCOMSUB)
10158 tword->flags |= W_NOCOMSUB;
10159 if (word->flags & W_NOPROCSUB)
10160 tword->flags |= W_NOPROCSUB;
10161
10162 temp = (char *)NULL;
10163
10164 temp_has_dollar_at = 0; /* does this quoted (sub)string include $@? */
10165 /* Need to get W_HASQUOTEDNULL flag through this function. */
10166 list = expand_word_internal (tword, Q_DOUBLE_QUOTES, 0, &temp_has_dollar_at, (int *)NULL);
10167 has_dollar_at += temp_has_dollar_at;
10168
10169 if (list == &expand_word_error || list == &expand_word_fatal)
10170 {
10171 free (istring);
10172 free (string);
10173 /* expand_word_internal has already freed temp_word->word
10174 for us because of the way it prints error messages. */
10175 tword->word = (char *)NULL;
10176 dispose_word (tword);
10177 return list;
10178 }
10179
10180 dispose_word (tword);
10181
10182 /* "$@" (a double-quoted dollar-at) expands into nothing,
10183 not even a NULL word, when there are no positional
10184 parameters. Posix interp 888 says that other parts of the
10185 word that expand to quoted nulls result in quoted nulls, so
10186 we can't just throw the entire word away if we have "$@"
10187 anywhere in it. We use had_quoted_null to keep track */
10188 if (list == 0 && temp_has_dollar_at) /* XXX - was has_dollar_at */
10189 {
10190 quoted_dollar_at++;
10191 break;
10192 }
10193
10194 /* If this list comes back with a quoted null from expansion,
10195 we have either "$x" or "$@" with $1 == ''. In either case,
10196 we need to make sure we add a quoted null argument and
10197 disable the special handling that "$@" gets. */
10198 if (list && list->word && list->next == 0 && (list->word->flags & W_HASQUOTEDNULL))
10199 {
10200 /* If we already saw a quoted null, we don't need to add
10201 another one */
10202 if (had_quoted_null && temp_has_dollar_at)
10203 {
10204 quoted_dollar_at++;
10205 break;
10206 }
10207 had_quoted_null = 1; /* XXX */
10208 }
10209
10210 /* If we get "$@", we know we have expanded something, so we
10211 need to remember it for the final split on $IFS. This is
10212 a special case; it's the only case where a quoted string
10213 can expand into more than one word. It's going to come back
10214 from the above call to expand_word_internal as a list with
10215 a single word, in which all characters are quoted and
10216 separated by blanks. What we want to do is to turn it back
10217 into a list for the next piece of code. */
10218 if (list)
10219 dequote_list (list);
10220
10221 if (temp_has_dollar_at) /* XXX - was has_dollar_at */
10222 {
10223 quoted_dollar_at++;
10224 if (contains_dollar_at)
10225 *contains_dollar_at = 1;
10226 if (expanded_something)
10227 *expanded_something = 1;
10228 local_expanded = 1;
10229 }
10230 }
10231 else
10232 {
10233 /* What we have is "". This is a minor optimization. */
10234 FREE (temp);
10235 list = (WORD_LIST *)NULL;
10236 had_quoted_null = 1; /* note for later */
10237 }
10238
10239 /* The code above *might* return a list (consider the case of "$@",
10240 where it returns "$1", "$2", etc.). We can't throw away the
10241 rest of the list, and we have to make sure each word gets added
10242 as quoted. We test on tresult->next: if it is non-NULL, we
10243 quote the whole list, save it to a string with string_list, and
10244 add that string. We don't need to quote the results of this
10245 (and it would be wrong, since that would quote the separators
10246 as well), so we go directly to add_string. */
10247 if (list)
10248 {
10249 if (list->next)
10250 {
10251 /* Testing quoted_dollar_at makes sure that "$@" is
10252 split correctly when $IFS does not contain a space. */
10253 temp = quoted_dollar_at
10254 ? string_list_dollar_at (list, Q_DOUBLE_QUOTES, 0)
10255 : string_list (quote_list (list));
10256 dispose_words (list);
10257 goto add_string;
10258 }
10259 else
10260 {
10261 temp = savestring (list->word->word);
10262 tflag = list->word->flags;
10263 dispose_words (list);
10264
10265 /* If the string is not a quoted null string, we want
10266 to remove any embedded unquoted CTLNUL characters.
10267 We do not want to turn quoted null strings back into
10268 the empty string, though. We do this because we
10269 want to remove any quoted nulls from expansions that
10270 contain other characters. For example, if we have
10271 x"$*"y or "x$*y" and there are no positional parameters,
10272 the $* should expand into nothing. */
10273 /* We use the W_HASQUOTEDNULL flag to differentiate the
10274 cases: a quoted null character as above and when
10275 CTLNUL is contained in the (non-null) expansion
10276 of some variable. We use the had_quoted_null flag to
10277 pass the value through this function to its caller. */
10278 if ((tflag & W_HASQUOTEDNULL) && QUOTED_NULL (temp) == 0)
10279 remove_quoted_nulls (temp); /* XXX */
10280 }
10281 }
10282 else
10283 temp = (char *)NULL;
10284
10285 if (temp == 0 && quoted_state == PARTIALLY_QUOTED)
10286 had_quoted_null = 1; /* note for later */
10287
10288 /* We do not want to add quoted nulls to strings that are only
10289 partially quoted; we can throw them away. The exception to
10290 this is when we are going to be performing word splitting,
10291 since we have to preserve a null argument if the next character
10292 will cause word splitting. */
10293 if (temp == 0 && quoted_state == PARTIALLY_QUOTED && (word->flags & (W_NOSPLIT|W_NOSPLIT2)))
10294 continue;
10295
10296 add_quoted_string:
10297
10298 if (temp)
10299 {
10300 temp1 = temp;
10301 temp = quote_string (temp);
10302 free (temp1);
10303 goto add_string;
10304 }
10305 else
10306 {
10307 /* Add NULL arg. */
10308 c = CTLNUL;
10309 sindex--; /* add_character: label increments sindex */
10310 had_quoted_null = 1; /* note for later */
10311 goto add_character;
10312 }
10313
10314 /* break; */
10315
10316 case '\'':
10317 if ((quoted & (Q_DOUBLE_QUOTES|Q_HERE_DOCUMENT)))
10318 goto add_character;
10319
10320 t_index = ++sindex;
10321 temp = string_extract_single_quoted (string, &sindex);
10322
10323 /* If the entire STRING was surrounded by single quotes,
10324 then the string is wholly quoted. */
10325 quoted_state = (t_index == 1 && string[sindex] == '\0')
10326 ? WHOLLY_QUOTED
10327 : PARTIALLY_QUOTED;
10328
10329 /* If all we had was '', it is a null expansion. */
10330 if (*temp == '\0')
10331 {
10332 free (temp);
10333 temp = (char *)NULL;
10334 }
10335 else
10336 remove_quoted_escapes (temp); /* ??? */
10337
10338 if (temp == 0 && quoted_state == PARTIALLY_QUOTED)
10339 had_quoted_null = 1; /* note for later */
10340
10341 /* We do not want to add quoted nulls to strings that are only
10342 partially quoted; such nulls are discarded. See above for the
10343 exception, which is when the string is going to be split.
10344 Posix interp 888 */
10345 if (temp == 0 && (quoted_state == PARTIALLY_QUOTED) && (word->flags & (W_NOSPLIT|W_NOSPLIT2)))
10346 continue;
10347
10348 /* If we have a quoted null expansion, add a quoted NULL to istring. */
10349 if (temp == 0)
10350 {
10351 c = CTLNUL;
10352 sindex--; /* add_character: label increments sindex */
10353 goto add_character;
10354 }
10355 else
10356 goto add_quoted_string;
10357
10358 /* break; */
10359
10360 default:
10361 /* This is the fix for " $@ " */
10362 add_ifs_character:
10363 if ((quoted & (Q_HERE_DOCUMENT|Q_DOUBLE_QUOTES)) || (isexp == 0 && isifs (c) && (word->flags & (W_NOSPLIT|W_NOSPLIT2)) == 0))
10364 {
10365 if ((quoted&(Q_HERE_DOCUMENT|Q_DOUBLE_QUOTES)) == 0)
10366 has_quoted_ifs++;
10367 if (string[sindex]) /* from old goto dollar_add_string */
10368 sindex++;
10369 if (c == 0)
10370 {
10371 c = CTLNUL;
10372 goto add_character;
10373 }
10374 else
10375 {
10376 #if HANDLE_MULTIBYTE
10377 /* XXX - should make sure that c is actually multibyte,
10378 otherwise we can use the twochars branch */
10379 if (mb_cur_max > 1)
10380 sindex--;
10381
10382 if (mb_cur_max > 1)
10383 {
10384 SADD_MBQCHAR_BODY(temp, string, sindex, string_size);
10385 }
10386 else
10387 #endif
10388 {
10389 twochars[0] = CTLESC;
10390 twochars[1] = c;
10391 goto add_twochars;
10392 }
10393 }
10394 }
10395
10396 SADD_MBCHAR (temp, string, sindex, string_size);
10397
10398 add_character:
10399 RESIZE_MALLOCED_BUFFER (istring, istring_index, 1, istring_size,
10400 DEFAULT_ARRAY_SIZE);
10401 istring[istring_index++] = c;
10402 istring[istring_index] = '\0';
10403
10404 /* Next character. */
10405 sindex++;
10406 }
10407 }
10408
10409 finished_with_string:
10410 /* OK, we're ready to return. If we have a quoted string, and
10411 quoted_dollar_at is not set, we do no splitting at all; otherwise
10412 we split on ' '. The routines that call this will handle what to
10413 do if nothing has been expanded. */
10414
10415 /* Partially and wholly quoted strings which expand to the empty
10416 string are retained as an empty arguments. Unquoted strings
10417 which expand to the empty string are discarded. The single
10418 exception is the case of expanding "$@" when there are no
10419 positional parameters. In that case, we discard the expansion. */
10420
10421 /* Because of how the code that handles "" and '' in partially
10422 quoted strings works, we need to make ISTRING into a QUOTED_NULL
10423 if we saw quoting characters, but the expansion was empty.
10424 "" and '' are tossed away before we get to this point when
10425 processing partially quoted strings. This makes "" and $xxx""
10426 equivalent when xxx is unset. We also look to see whether we
10427 saw a quoted null from a ${} expansion and add one back if we
10428 need to. */
10429
10430 /* If we expand to nothing and there were no single or double quotes
10431 in the word, we throw it away. Otherwise, we return a NULL word.
10432 The single exception is for $@ surrounded by double quotes when
10433 there are no positional parameters. In that case, we also throw
10434 the word away. */
10435
10436 if (*istring == '\0')
10437 {
10438 if (quoted_dollar_at == 0 && (had_quoted_null || quoted_state == PARTIALLY_QUOTED))
10439 {
10440 istring[0] = CTLNUL;
10441 istring[1] = '\0';
10442 tword = alloc_word_desc ();
10443 tword->word = istring;
10444 istring = 0; /* avoid later free() */
10445 tword->flags |= W_HASQUOTEDNULL; /* XXX */
10446 list = make_word_list (tword, (WORD_LIST *)NULL);
10447 if (quoted & (Q_HERE_DOCUMENT|Q_DOUBLE_QUOTES))
10448 tword->flags |= W_QUOTED;
10449 }
10450 /* According to sh, ksh, and Posix.2, if a word expands into nothing
10451 and a double-quoted "$@" appears anywhere in it, then the entire
10452 word is removed. */
10453 /* XXX - exception appears to be that quoted null strings result in
10454 null arguments */
10455 else if (quoted_state == UNQUOTED || quoted_dollar_at)
10456 list = (WORD_LIST *)NULL;
10457 else
10458 list = (WORD_LIST *)NULL;
10459 }
10460 else if (word->flags & W_NOSPLIT)
10461 {
10462 tword = alloc_word_desc ();
10463 tword->word = istring;
10464 if (had_quoted_null && QUOTED_NULL (istring))
10465 tword->flags |= W_HASQUOTEDNULL;
10466 istring = 0; /* avoid later free() */
10467 if (word->flags & W_ASSIGNMENT)
10468 tword->flags |= W_ASSIGNMENT; /* XXX */
10469 if (word->flags & W_COMPASSIGN)
10470 tword->flags |= W_COMPASSIGN; /* XXX */
10471 if (word->flags & W_NOGLOB)
10472 tword->flags |= W_NOGLOB; /* XXX */
10473 if (word->flags & W_NOBRACE)
10474 tword->flags |= W_NOBRACE; /* XXX */
10475 if (word->flags & W_NOEXPAND)
10476 tword->flags |= W_NOEXPAND; /* XXX */
10477 if (quoted & (Q_HERE_DOCUMENT|Q_DOUBLE_QUOTES))
10478 tword->flags |= W_QUOTED;
10479 list = make_word_list (tword, (WORD_LIST *)NULL);
10480 }
10481 else
10482 {
10483 char *ifs_chars;
10484
10485 ifs_chars = (quoted_dollar_at || has_dollar_at) ? ifs_value : (char *)NULL;
10486
10487 /* If we have $@, we need to split the results no matter what. If
10488 IFS is unset or NULL, string_list_dollar_at has separated the
10489 positional parameters with a space, so we split on space (we have
10490 set ifs_chars to " \t\n" above if ifs is unset). If IFS is set,
10491 string_list_dollar_at has separated the positional parameters
10492 with the first character of $IFS, so we split on $IFS. If
10493 SPLIT_ON_SPACES is set, we expanded $* (unquoted) with IFS either
10494 unset or null, and we want to make sure that we split on spaces
10495 regardless of what else has happened to IFS since the expansion,
10496 or we expanded "$@" with IFS null and we need to split the positional
10497 parameters into separate words. */
10498 if (split_on_spaces)
10499 {
10500 /* If IFS is not set, and the word is not quoted, we want to split
10501 the individual words on $' \t\n'. We rely on previous steps to
10502 quote the portions of the word that should not be split */
10503 if (ifs_is_set == 0)
10504 list = list_string (istring, " \t\n", 1); /* XXX quoted == 1? */
10505 else
10506 list = list_string (istring, " ", 1); /* XXX quoted == 1? */
10507 }
10508
10509 /* If we have $@ (has_dollar_at != 0) and we are in a context where we
10510 don't want to split the result (W_NOSPLIT2), and we are not quoted,
10511 we have already separated the arguments with the first character of
10512 $IFS. In this case, we want to return a list with a single word
10513 with the separator possibly replaced with a space (it's what other
10514 shells seem to do).
10515 quoted_dollar_at is internal to this function and is set if we are
10516 passed an argument that is unquoted (quoted == 0) but we encounter a
10517 double-quoted $@ while expanding it. */
10518 else if (has_dollar_at && quoted_dollar_at == 0 && ifs_chars && quoted == 0 && (word->flags & W_NOSPLIT2))
10519 {
10520 tword = alloc_word_desc ();
10521 /* Only split and rejoin if we have to */
10522 if (*ifs_chars && *ifs_chars != ' ')
10523 {
10524 /* list_string dequotes CTLESCs in the string it's passed, so we
10525 need it to get the space separation right if space isn't the
10526 first character in IFS (but is present) and to remove the
10527 quoting we added back in param_expand(). */
10528 list = list_string (istring, *ifs_chars ? ifs_chars : " ", 1);
10529 /* This isn't exactly right in the case where we're expanding
10530 the RHS of an expansion like ${var-$@} where IFS=: (for
10531 example). The W_NOSPLIT2 means we do the separation with :;
10532 the list_string removes the quotes and breaks the string into
10533 a list, and the string_list rejoins it on spaces. When we
10534 return, we expect to be able to split the results, but the
10535 space separation means the right split doesn't happen. */
10536 tword->word = string_list (list);
10537 }
10538 else
10539 tword->word = istring;
10540 if (had_quoted_null && QUOTED_NULL (istring))
10541 tword->flags |= W_HASQUOTEDNULL; /* XXX */
10542 if (tword->word != istring)
10543 free (istring);
10544 istring = 0; /* avoid later free() */
10545 goto set_word_flags;
10546 }
10547 else if (has_dollar_at && ifs_chars)
10548 list = list_string (istring, *ifs_chars ? ifs_chars : " ", 1);
10549 else
10550 {
10551 tword = alloc_word_desc ();
10552 if (expanded_something && *expanded_something == 0 && has_quoted_ifs)
10553 tword->word = remove_quoted_ifs (istring);
10554 else
10555 tword->word = istring;
10556 if (had_quoted_null && QUOTED_NULL (istring))
10557 tword->flags |= W_HASQUOTEDNULL; /* XXX */
10558 else if (had_quoted_null)
10559 tword->flags |= W_SAWQUOTEDNULL; /* XXX */
10560 if (tword->word != istring)
10561 free (istring);
10562 istring = 0; /* avoid later free() */
10563 set_word_flags:
10564 if ((quoted & (Q_DOUBLE_QUOTES|Q_HERE_DOCUMENT)) || (quoted_state == WHOLLY_QUOTED))
10565 tword->flags |= W_QUOTED;
10566 if (word->flags & W_ASSIGNMENT)
10567 tword->flags |= W_ASSIGNMENT;
10568 if (word->flags & W_COMPASSIGN)
10569 tword->flags |= W_COMPASSIGN;
10570 if (word->flags & W_NOGLOB)
10571 tword->flags |= W_NOGLOB;
10572 if (word->flags & W_NOBRACE)
10573 tword->flags |= W_NOBRACE;
10574 if (word->flags & W_NOEXPAND)
10575 tword->flags |= W_NOEXPAND;
10576 list = make_word_list (tword, (WORD_LIST *)NULL);
10577 }
10578 }
10579
10580 free (istring);
10581 return (list);
10582 }
10583
10584 /* **************************************************************** */
10585 /* */
10586 /* Functions for Quote Removal */
10587 /* */
10588 /* **************************************************************** */
10589
10590 /* Perform quote removal on STRING. If QUOTED > 0, assume we are obeying the
10591 backslash quoting rules for within double quotes or a here document. */
10592 char *
10593 string_quote_removal (string, quoted)
10594 char *string;
10595 int quoted;
10596 {
10597 size_t slen;
10598 char *r, *result_string, *temp, *send;
10599 int sindex, tindex, dquote;
10600 unsigned char c;
10601 DECLARE_MBSTATE;
10602
10603 /* The result can be no longer than the original string. */
10604 slen = strlen (string);
10605 send = string + slen;
10606
10607 r = result_string = (char *)xmalloc (slen + 1);
10608
10609 for (dquote = sindex = 0; c = string[sindex];)
10610 {
10611 switch (c)
10612 {
10613 case '\\':
10614 c = string[++sindex];
10615 if (c == 0)
10616 {
10617 *r++ = '\\';
10618 break;
10619 }
10620 if (((quoted & (Q_HERE_DOCUMENT|Q_DOUBLE_QUOTES)) || dquote) && (sh_syntaxtab[c] & CBSDQUOTE) == 0)
10621 *r++ = '\\';
10622 /* FALLTHROUGH */
10623
10624 default:
10625 SCOPY_CHAR_M (r, string, send, sindex);
10626 break;
10627
10628 case '\'':
10629 if ((quoted & (Q_HERE_DOCUMENT|Q_DOUBLE_QUOTES)) || dquote)
10630 {
10631 *r++ = c;
10632 sindex++;
10633 break;
10634 }
10635 tindex = sindex + 1;
10636 temp = string_extract_single_quoted (string, &tindex);
10637 if (temp)
10638 {
10639 strcpy (r, temp);
10640 r += strlen (r);
10641 free (temp);
10642 }
10643 sindex = tindex;
10644 break;
10645
10646 case '"':
10647 dquote = 1 - dquote;
10648 sindex++;
10649 break;
10650 }
10651 }
10652 *r = '\0';
10653 return (result_string);
10654 }
10655
10656 #if 0
10657 /* UNUSED */
10658 /* Perform quote removal on word WORD. This allocates and returns a new
10659 WORD_DESC *. */
10660 WORD_DESC *
10661 word_quote_removal (word, quoted)
10662 WORD_DESC *word;
10663 int quoted;
10664 {
10665 WORD_DESC *w;
10666 char *t;
10667
10668 t = string_quote_removal (word->word, quoted);
10669 w = alloc_word_desc ();
10670 w->word = t ? t : savestring ("");
10671 return (w);
10672 }
10673
10674 /* Perform quote removal on all words in LIST. If QUOTED is non-zero,
10675 the members of the list are treated as if they are surrounded by
10676 double quotes. Return a new list, or NULL if LIST is NULL. */
10677 WORD_LIST *
10678 word_list_quote_removal (list, quoted)
10679 WORD_LIST *list;
10680 int quoted;
10681 {
10682 WORD_LIST *result, *t, *tresult, *e;
10683
10684 for (t = list, result = (WORD_LIST *)NULL; t; t = t->next)
10685 {
10686 tresult = make_word_list (word_quote_removal (t->word, quoted), (WORD_LIST *)NULL);
10687 #if 0
10688 result = (WORD_LIST *) list_append (result, tresult);
10689 #else
10690 if (result == 0)
10691 result = e = tresult;
10692 else
10693 {
10694 e->next = tresult;
10695 while (e->next)
10696 e = e->next;
10697 }
10698 #endif
10699 }
10700 return (result);
10701 }
10702 #endif
10703
10704 /*******************************************
10705 * *
10706 * Functions to perform word splitting *
10707 * *
10708 *******************************************/
10709
10710 void
10711 setifs (v)
10712 SHELL_VAR *v;
10713 {
10714 char *t;
10715 unsigned char uc;
10716
10717 ifs_var = v;
10718 ifs_value = (v && value_cell (v)) ? value_cell (v) : " \t\n";
10719
10720 ifs_is_set = ifs_var != 0;
10721 ifs_is_null = ifs_is_set && (*ifs_value == 0);
10722
10723 /* Should really merge ifs_cmap with sh_syntaxtab. XXX - doesn't yet
10724 handle multibyte chars in IFS */
10725 memset (ifs_cmap, '\0', sizeof (ifs_cmap));
10726 for (t = ifs_value ; t && *t; t++)
10727 {
10728 uc = *t;
10729 ifs_cmap[uc] = 1;
10730 }
10731
10732 #if defined (HANDLE_MULTIBYTE)
10733 if (ifs_value == 0)
10734 {
10735 ifs_firstc[0] = '\0'; /* XXX - ? */
10736 ifs_firstc_len = 1;
10737 }
10738 else
10739 {
10740 if (locale_utf8locale && UTF8_SINGLEBYTE (*ifs_value))
10741 ifs_firstc_len = (*ifs_value != 0) ? 1 : 0;
10742 else
10743 {
10744 size_t ifs_len;
10745 ifs_len = strnlen (ifs_value, MB_CUR_MAX);
10746 ifs_firstc_len = MBLEN (ifs_value, ifs_len);
10747 }
10748 if (ifs_firstc_len == 1 || ifs_firstc_len == 0 || MB_INVALIDCH (ifs_firstc_len))
10749 {
10750 ifs_firstc[0] = ifs_value[0];
10751 ifs_firstc[1] = '\0';
10752 ifs_firstc_len = 1;
10753 }
10754 else
10755 memcpy (ifs_firstc, ifs_value, ifs_firstc_len);
10756 }
10757 #else
10758 ifs_firstc = ifs_value ? *ifs_value : 0;
10759 #endif
10760 }
10761
10762 char *
10763 getifs ()
10764 {
10765 return ifs_value;
10766 }
10767
10768 /* This splits a single word into a WORD LIST on $IFS, but only if the word
10769 is not quoted. list_string () performs quote removal for us, even if we
10770 don't do any splitting. */
10771 WORD_LIST *
10772 word_split (w, ifs_chars)
10773 WORD_DESC *w;
10774 char *ifs_chars;
10775 {
10776 WORD_LIST *result;
10777
10778 if (w)
10779 {
10780 char *xifs;
10781
10782 xifs = ((w->flags & W_QUOTED) || ifs_chars == 0) ? "" : ifs_chars;
10783 result = list_string (w->word, xifs, w->flags & W_QUOTED);
10784 }
10785 else
10786 result = (WORD_LIST *)NULL;
10787
10788 return (result);
10789 }
10790
10791 /* Perform word splitting on LIST and return the RESULT. It is possible
10792 to return (WORD_LIST *)NULL. */
10793 static WORD_LIST *
10794 word_list_split (list)
10795 WORD_LIST *list;
10796 {
10797 WORD_LIST *result, *t, *tresult, *e;
10798 WORD_DESC *w;
10799
10800 for (t = list, result = (WORD_LIST *)NULL; t; t = t->next)
10801 {
10802 tresult = word_split (t->word, ifs_value);
10803 /* POSIX 2.6: "If the complete expansion appropriate for a word results
10804 in an empty field, that empty field shall be deleted from the list
10805 of fields that form the completely expanded command, unless the
10806 original word contained single-quote or double-quote characters."
10807 This is where we handle these words that contain quoted null strings
10808 and other characters that expand to nothing after word splitting. */
10809 if (tresult == 0 && t->word && (t->word->flags & W_SAWQUOTEDNULL)) /* XXX */
10810 {
10811 w = alloc_word_desc ();
10812 w->word = (char *)xmalloc (1);
10813 w->word[0] = '\0';
10814 tresult = make_word_list (w, (WORD_LIST *)NULL);
10815 }
10816 if (result == 0)
10817 result = e = tresult;
10818 else
10819 {
10820 e->next = tresult;
10821 while (e->next)
10822 e = e->next;
10823 }
10824 }
10825 return (result);
10826 }
10827
10828 /**************************************************
10829 * *
10830 * Functions to expand an entire WORD_LIST *
10831 * *
10832 **************************************************/
10833
10834 /* Do any word-expansion-specific cleanup and jump to top_level */
10835 static void
10836 exp_jump_to_top_level (v)
10837 int v;
10838 {
10839 set_pipestatus_from_exit (last_command_exit_value);
10840
10841 /* Cleanup code goes here. */
10842 expand_no_split_dollar_star = 0; /* XXX */
10843 if (expanding_redir)
10844 undo_partial_redirects ();
10845 expanding_redir = 0;
10846 assigning_in_environment = 0;
10847
10848 if (parse_and_execute_level == 0)
10849 top_level_cleanup (); /* from sig.c */
10850
10851 jump_to_top_level (v);
10852 }
10853
10854 /* Put NLIST (which is a WORD_LIST * of only one element) at the front of
10855 ELIST, and set ELIST to the new list. */
10856 #define PREPEND_LIST(nlist, elist) \
10857 do { nlist->next = elist; elist = nlist; } while (0)
10858
10859 /* Separate out any initial variable assignments from TLIST. If set -k has
10860 been executed, remove all assignment statements from TLIST. Initial
10861 variable assignments and other environment assignments are placed
10862 on SUBST_ASSIGN_VARLIST. */
10863 static WORD_LIST *
10864 separate_out_assignments (tlist)
10865 WORD_LIST *tlist;
10866 {
10867 register WORD_LIST *vp, *lp;
10868
10869 if (tlist == 0)
10870 return ((WORD_LIST *)NULL);
10871
10872 if (subst_assign_varlist)
10873 dispose_words (subst_assign_varlist); /* Clean up after previous error */
10874
10875 subst_assign_varlist = (WORD_LIST *)NULL;
10876 vp = lp = tlist;
10877
10878 /* Separate out variable assignments at the start of the command.
10879 Loop invariant: vp->next == lp
10880 Loop postcondition:
10881 lp = list of words left after assignment statements skipped
10882 tlist = original list of words
10883 */
10884 while (lp && (lp->word->flags & W_ASSIGNMENT))
10885 {
10886 vp = lp;
10887 lp = lp->next;
10888 }
10889
10890 /* If lp != tlist, we have some initial assignment statements.
10891 We make SUBST_ASSIGN_VARLIST point to the list of assignment
10892 words and TLIST point to the remaining words. */
10893 if (lp != tlist)
10894 {
10895 subst_assign_varlist = tlist;
10896 /* ASSERT(vp->next == lp); */
10897 vp->next = (WORD_LIST *)NULL; /* terminate variable list */
10898 tlist = lp; /* remainder of word list */
10899 }
10900
10901 /* vp == end of variable list */
10902 /* tlist == remainder of original word list without variable assignments */
10903 if (!tlist)
10904 /* All the words in tlist were assignment statements */
10905 return ((WORD_LIST *)NULL);
10906
10907 /* ASSERT(tlist != NULL); */
10908 /* ASSERT((tlist->word->flags & W_ASSIGNMENT) == 0); */
10909
10910 /* If the -k option is in effect, we need to go through the remaining
10911 words, separate out the assignment words, and place them on
10912 SUBST_ASSIGN_VARLIST. */
10913 if (place_keywords_in_env)
10914 {
10915 WORD_LIST *tp; /* tp == running pointer into tlist */
10916
10917 tp = tlist;
10918 lp = tlist->next;
10919
10920 /* Loop Invariant: tp->next == lp */
10921 /* Loop postcondition: tlist == word list without assignment statements */
10922 while (lp)
10923 {
10924 if (lp->word->flags & W_ASSIGNMENT)
10925 {
10926 /* Found an assignment statement, add this word to end of
10927 subst_assign_varlist (vp). */
10928 if (!subst_assign_varlist)
10929 subst_assign_varlist = vp = lp;
10930 else
10931 {
10932 vp->next = lp;
10933 vp = lp;
10934 }
10935
10936 /* Remove the word pointed to by LP from TLIST. */
10937 tp->next = lp->next;
10938 /* ASSERT(vp == lp); */
10939 lp->next = (WORD_LIST *)NULL;
10940 lp = tp->next;
10941 }
10942 else
10943 {
10944 tp = lp;
10945 lp = lp->next;
10946 }
10947 }
10948 }
10949 return (tlist);
10950 }
10951
10952 #define WEXP_VARASSIGN 0x001
10953 #define WEXP_BRACEEXP 0x002
10954 #define WEXP_TILDEEXP 0x004
10955 #define WEXP_PARAMEXP 0x008
10956 #define WEXP_PATHEXP 0x010
10957
10958 /* All of the expansions, including variable assignments at the start of
10959 the list. */
10960 #define WEXP_ALL (WEXP_VARASSIGN|WEXP_BRACEEXP|WEXP_TILDEEXP|WEXP_PARAMEXP|WEXP_PATHEXP)
10961
10962 /* All of the expansions except variable assignments at the start of
10963 the list. */
10964 #define WEXP_NOVARS (WEXP_BRACEEXP|WEXP_TILDEEXP|WEXP_PARAMEXP|WEXP_PATHEXP)
10965
10966 /* All of the `shell expansions': brace expansion, tilde expansion, parameter
10967 expansion, command substitution, arithmetic expansion, word splitting, and
10968 quote removal. */
10969 #define WEXP_SHELLEXP (WEXP_BRACEEXP|WEXP_TILDEEXP|WEXP_PARAMEXP)
10970
10971 /* Take the list of words in LIST and do the various substitutions. Return
10972 a new list of words which is the expanded list, and without things like
10973 variable assignments. */
10974
10975 WORD_LIST *
10976 expand_words (list)
10977 WORD_LIST *list;
10978 {
10979 return (expand_word_list_internal (list, WEXP_ALL));
10980 }
10981
10982 /* Same as expand_words (), but doesn't hack variable or environment
10983 variables. */
10984 WORD_LIST *
10985 expand_words_no_vars (list)
10986 WORD_LIST *list;
10987 {
10988 return (expand_word_list_internal (list, WEXP_NOVARS));
10989 }
10990
10991 WORD_LIST *
10992 expand_words_shellexp (list)
10993 WORD_LIST *list;
10994 {
10995 return (expand_word_list_internal (list, WEXP_SHELLEXP));
10996 }
10997
10998 static WORD_LIST *
10999 glob_expand_word_list (tlist, eflags)
11000 WORD_LIST *tlist;
11001 int eflags;
11002 {
11003 char **glob_array, *temp_string;
11004 register int glob_index;
11005 WORD_LIST *glob_list, *output_list, *disposables, *next;
11006 WORD_DESC *tword;
11007
11008 output_list = disposables = (WORD_LIST *)NULL;
11009 glob_array = (char **)NULL;
11010 while (tlist)
11011 {
11012 /* For each word, either globbing is attempted or the word is
11013 added to orig_list. If globbing succeeds, the results are
11014 added to orig_list and the word (tlist) is added to the list
11015 of disposable words. If globbing fails and failed glob
11016 expansions are left unchanged (the shell default), the
11017 original word is added to orig_list. If globbing fails and
11018 failed glob expansions are removed, the original word is
11019 added to the list of disposable words. orig_list ends up
11020 in reverse order and requires a call to REVERSE_LIST to
11021 be set right. After all words are examined, the disposable
11022 words are freed. */
11023 next = tlist->next;
11024
11025 /* If the word isn't an assignment and contains an unquoted
11026 pattern matching character, then glob it. */
11027 if ((tlist->word->flags & W_NOGLOB) == 0 &&
11028 unquoted_glob_pattern_p (tlist->word->word))
11029 {
11030 glob_array = shell_glob_filename (tlist->word->word);
11031
11032 /* Handle error cases.
11033 I don't think we should report errors like "No such file
11034 or directory". However, I would like to report errors
11035 like "Read failed". */
11036
11037 if (glob_array == 0 || GLOB_FAILED (glob_array))
11038 {
11039 glob_array = (char **)xmalloc (sizeof (char *));
11040 glob_array[0] = (char *)NULL;
11041 }
11042
11043 /* Dequote the current word in case we have to use it. */
11044 if (glob_array[0] == NULL)
11045 {
11046 temp_string = dequote_string (tlist->word->word);
11047 free (tlist->word->word);
11048 tlist->word->word = temp_string;
11049 }
11050
11051 /* Make the array into a word list. */
11052 glob_list = (WORD_LIST *)NULL;
11053 for (glob_index = 0; glob_array[glob_index]; glob_index++)
11054 {
11055 tword = make_bare_word (glob_array[glob_index]);
11056 glob_list = make_word_list (tword, glob_list);
11057 }
11058
11059 if (glob_list)
11060 {
11061 output_list = (WORD_LIST *)list_append (glob_list, output_list);
11062 PREPEND_LIST (tlist, disposables);
11063 }
11064 else if (fail_glob_expansion != 0)
11065 {
11066 last_command_exit_value = EXECUTION_FAILURE;
11067 report_error (_("no match: %s"), tlist->word->word);
11068 exp_jump_to_top_level (DISCARD);
11069 }
11070 else if (allow_null_glob_expansion == 0)
11071 {
11072 /* Failed glob expressions are left unchanged. */
11073 PREPEND_LIST (tlist, output_list);
11074 }
11075 else
11076 {
11077 /* Failed glob expressions are removed. */
11078 PREPEND_LIST (tlist, disposables);
11079 }
11080 }
11081 else
11082 {
11083 /* Dequote the string. */
11084 temp_string = dequote_string (tlist->word->word);
11085 free (tlist->word->word);
11086 tlist->word->word = temp_string;
11087 PREPEND_LIST (tlist, output_list);
11088 }
11089
11090 strvec_dispose (glob_array);
11091 glob_array = (char **)NULL;
11092
11093 tlist = next;
11094 }
11095
11096 if (disposables)
11097 dispose_words (disposables);
11098
11099 if (output_list)
11100 output_list = REVERSE_LIST (output_list, WORD_LIST *);
11101
11102 return (output_list);
11103 }
11104
11105 #if defined (BRACE_EXPANSION)
11106 static WORD_LIST *
11107 brace_expand_word_list (tlist, eflags)
11108 WORD_LIST *tlist;
11109 int eflags;
11110 {
11111 register char **expansions;
11112 char *temp_string;
11113 WORD_LIST *disposables, *output_list, *next;
11114 WORD_DESC *w;
11115 int eindex;
11116
11117 for (disposables = output_list = (WORD_LIST *)NULL; tlist; tlist = next)
11118 {
11119 next = tlist->next;
11120
11121 if (tlist->word->flags & W_NOBRACE)
11122 {
11123 /*itrace("brace_expand_word_list: %s: W_NOBRACE", tlist->word->word);*/
11124 PREPEND_LIST (tlist, output_list);
11125 continue;
11126 }
11127
11128 if ((tlist->word->flags & (W_COMPASSIGN|W_ASSIGNARG)) == (W_COMPASSIGN|W_ASSIGNARG))
11129 {
11130 /*itrace("brace_expand_word_list: %s: W_COMPASSIGN|W_ASSIGNARG", tlist->word->word);*/
11131 PREPEND_LIST (tlist, output_list);
11132 continue;
11133 }
11134
11135 /* Only do brace expansion if the word has a brace character. If
11136 not, just add the word list element to BRACES and continue. In
11137 the common case, at least when running shell scripts, this will
11138 degenerate to a bunch of calls to `mbschr', and then what is
11139 basically a reversal of TLIST into BRACES, which is corrected
11140 by a call to REVERSE_LIST () on BRACES when the end of TLIST
11141 is reached. */
11142 if (mbschr (tlist->word->word, LBRACE))
11143 {
11144 expansions = brace_expand (tlist->word->word);
11145
11146 for (eindex = 0; temp_string = expansions[eindex]; eindex++)
11147 {
11148 w = alloc_word_desc ();
11149 w->word = temp_string;
11150
11151 /* If brace expansion didn't change the word, preserve
11152 the flags. We may want to preserve the flags
11153 unconditionally someday -- XXX */
11154 if (STREQ (temp_string, tlist->word->word))
11155 w->flags = tlist->word->flags;
11156 else
11157 w = make_word_flags (w, temp_string);
11158
11159 output_list = make_word_list (w, output_list);
11160 }
11161 free (expansions);
11162
11163 /* Add TLIST to the list of words to be freed after brace
11164 expansion has been performed. */
11165 PREPEND_LIST (tlist, disposables);
11166 }
11167 else
11168 PREPEND_LIST (tlist, output_list);
11169 }
11170
11171 if (disposables)
11172 dispose_words (disposables);
11173
11174 if (output_list)
11175 output_list = REVERSE_LIST (output_list, WORD_LIST *);
11176
11177 return (output_list);
11178 }
11179 #endif
11180
11181 #if defined (ARRAY_VARS)
11182 /* Take WORD, a compound associative array assignment, and internally run
11183 'declare -A w', where W is the variable name portion of WORD. */
11184 static int
11185 make_internal_declare (word, option, cmd)
11186 char *word;
11187 char *option;
11188 char *cmd;
11189 {
11190 int t, r;
11191 WORD_LIST *wl;
11192 WORD_DESC *w;
11193
11194 w = make_word (word);
11195
11196 t = assignment (w->word, 0);
11197 if (w->word[t] == '=')
11198 {
11199 w->word[t] = '\0';
11200 if (w->word[t - 1] == '+') /* cut off any append op */
11201 w->word[t - 1] = '\0';
11202 }
11203
11204 wl = make_word_list (w, (WORD_LIST *)NULL);
11205 wl = make_word_list (make_word (option), wl);
11206
11207 r = declare_builtin (wl);
11208
11209 dispose_words (wl);
11210 return r;
11211 }
11212 #endif
11213
11214 static WORD_LIST *
11215 shell_expand_word_list (tlist, eflags)
11216 WORD_LIST *tlist;
11217 int eflags;
11218 {
11219 WORD_LIST *expanded, *orig_list, *new_list, *next, *temp_list, *wcmd;
11220 int expanded_something, has_dollar_at;
11221
11222 /* We do tilde expansion all the time. This is what 1003.2 says. */
11223 new_list = (WORD_LIST *)NULL;
11224 for (wcmd = tlist; wcmd; wcmd = wcmd->next)
11225 if (wcmd->word->flags & W_ASSNBLTIN)
11226 break;
11227
11228 for (orig_list = tlist; tlist; tlist = next)
11229 {
11230 next = tlist->next;
11231
11232 #if defined (ARRAY_VARS)
11233 /* If this is a compound array assignment to a builtin that accepts
11234 such assignments (e.g., `declare'), take the assignment and perform
11235 it separately, handling the semantics of declarations inside shell
11236 functions. This avoids the double-evaluation of such arguments,
11237 because `declare' does some evaluation of compound assignments on
11238 its own. */
11239 if ((tlist->word->flags & (W_COMPASSIGN|W_ASSIGNARG)) == (W_COMPASSIGN|W_ASSIGNARG))
11240 {
11241 int t;
11242 char opts[16];
11243 int opti;
11244
11245 opti = 0;
11246 if (tlist->word->flags & (W_ASSIGNASSOC|W_ASSNGLOBAL|W_CHKLOCAL|W_ASSIGNARRAY))
11247 opts[opti++] = '-';
11248
11249 if ((tlist->word->flags & (W_ASSIGNASSOC|W_ASSNGLOBAL)) == (W_ASSIGNASSOC|W_ASSNGLOBAL))
11250 {
11251 opts[opti++] = 'g';
11252 opts[opti++] = 'A';
11253 }
11254 else if (tlist->word->flags & W_ASSIGNASSOC)
11255 opts[opti++] = 'A';
11256 else if ((tlist->word->flags & (W_ASSIGNARRAY|W_ASSNGLOBAL)) == (W_ASSIGNARRAY|W_ASSNGLOBAL))
11257 {
11258 opts[opti++] = 'g';
11259 opts[opti++] = 'a';
11260 }
11261 else if (tlist->word->flags & W_ASSIGNARRAY)
11262 opts[opti++] = 'a';
11263 else if (tlist->word->flags & W_ASSNGLOBAL)
11264 opts[opti++] = 'g';
11265
11266 if (tlist->word->flags & W_CHKLOCAL)
11267 opts[opti++] = 'G';
11268
11269 /* If we have special handling note the integer attribute and others
11270 that transform the value upon assignment. What we do is take all
11271 of the option arguments and scan through them looking for options
11272 that cause such transformations, and add them to the `opts' array. */
11273 /* if (opti > 0) */
11274 {
11275 char omap[128];
11276 int oind;
11277 WORD_LIST *l;
11278
11279 memset (omap, '\0', sizeof (omap));
11280 for (l = orig_list->next; l != tlist; l = l->next)
11281 {
11282 if (l->word->word[0] != '-')
11283 break; /* non-option argument */
11284 if (l->word->word[0] == '-' && l->word->word[1] == '-' && l->word->word[2] == 0)
11285 break; /* -- signals end of options */
11286 for (oind = 1; l->word->word[oind]; oind++)
11287 switch (l->word->word[oind])
11288 {
11289 case 'i':
11290 case 'l':
11291 case 'u':
11292 case 'c':
11293 omap[l->word->word[oind]] = 1;
11294 if (opti == 0)
11295 opts[opti++] = '-';
11296 break;
11297 default:
11298 break;
11299 }
11300 }
11301
11302 for (oind = 0; oind < sizeof (omap); oind++)
11303 if (omap[oind])
11304 opts[opti++] = oind;
11305 }
11306
11307 opts[opti] = '\0';
11308 if (opti > 0)
11309 {
11310 t = make_internal_declare (tlist->word->word, opts, wcmd ? wcmd->word->word : (char *)0);
11311 if (t != EXECUTION_SUCCESS)
11312 {
11313 last_command_exit_value = t;
11314 exp_jump_to_top_level (DISCARD);
11315 }
11316 }
11317
11318 t = do_word_assignment (tlist->word, 0);
11319 if (t == 0)
11320 {
11321 last_command_exit_value = EXECUTION_FAILURE;
11322 exp_jump_to_top_level (DISCARD);
11323 }
11324
11325 /* Now transform the word as ksh93 appears to do and go on */
11326 t = assignment (tlist->word->word, 0);
11327 tlist->word->word[t] = '\0';
11328 if (tlist->word->word[t - 1] == '+')
11329 tlist->word->word[t - 1] = '\0'; /* cut off append op */
11330 tlist->word->flags &= ~(W_ASSIGNMENT|W_NOSPLIT|W_COMPASSIGN|W_ASSIGNARG|W_ASSIGNASSOC|W_ASSIGNARRAY);
11331 }
11332 #endif
11333
11334 expanded_something = 0;
11335 expanded = expand_word_internal
11336 (tlist->word, 0, 0, &has_dollar_at, &expanded_something);
11337
11338 if (expanded == &expand_word_error || expanded == &expand_word_fatal)
11339 {
11340 /* By convention, each time this error is returned,
11341 tlist->word->word has already been freed. */
11342 tlist->word->word = (char *)NULL;
11343
11344 /* Dispose our copy of the original list. */
11345 dispose_words (orig_list);
11346 /* Dispose the new list we're building. */
11347 dispose_words (new_list);
11348
11349 last_command_exit_value = EXECUTION_FAILURE;
11350 if (expanded == &expand_word_error)
11351 exp_jump_to_top_level (DISCARD);
11352 else
11353 exp_jump_to_top_level (FORCE_EOF);
11354 }
11355
11356 /* Don't split words marked W_NOSPLIT. */
11357 if (expanded_something && (tlist->word->flags & W_NOSPLIT) == 0)
11358 {
11359 temp_list = word_list_split (expanded);
11360 dispose_words (expanded);
11361 }
11362 else
11363 {
11364 /* If no parameter expansion, command substitution, process
11365 substitution, or arithmetic substitution took place, then
11366 do not do word splitting. We still have to remove quoted
11367 null characters from the result. */
11368 word_list_remove_quoted_nulls (expanded);
11369 temp_list = expanded;
11370 }
11371
11372 expanded = REVERSE_LIST (temp_list, WORD_LIST *);
11373 new_list = (WORD_LIST *)list_append (expanded, new_list);
11374 }
11375
11376 if (orig_list)
11377 dispose_words (orig_list);
11378
11379 if (new_list)
11380 new_list = REVERSE_LIST (new_list, WORD_LIST *);
11381
11382 return (new_list);
11383 }
11384
11385 /* The workhorse for expand_words () and expand_words_no_vars ().
11386 First arg is LIST, a WORD_LIST of words.
11387 Second arg EFLAGS is a flags word controlling which expansions are
11388 performed.
11389
11390 This does all of the substitutions: brace expansion, tilde expansion,
11391 parameter expansion, command substitution, arithmetic expansion,
11392 process substitution, word splitting, and pathname expansion, according
11393 to the bits set in EFLAGS. Words with the W_QUOTED or W_NOSPLIT bits
11394 set, or for which no expansion is done, do not undergo word splitting.
11395 Words with the W_NOGLOB bit set do not undergo pathname expansion; words
11396 with W_NOBRACE set do not undergo brace expansion (see
11397 brace_expand_word_list above). */
11398 static WORD_LIST *
11399 expand_word_list_internal (list, eflags)
11400 WORD_LIST *list;
11401 int eflags;
11402 {
11403 WORD_LIST *new_list, *temp_list;
11404 int tint;
11405 char *savecmd;
11406
11407 tempenv_assign_error = 0;
11408 if (list == 0)
11409 return ((WORD_LIST *)NULL);
11410
11411 garglist = new_list = copy_word_list (list);
11412 if (eflags & WEXP_VARASSIGN)
11413 {
11414 garglist = new_list = separate_out_assignments (new_list);
11415 if (new_list == 0)
11416 {
11417 if (subst_assign_varlist)
11418 {
11419 /* All the words were variable assignments, so they are placed
11420 into the shell's environment. */
11421 for (temp_list = subst_assign_varlist; temp_list; temp_list = temp_list->next)
11422 {
11423 savecmd = this_command_name;
11424 this_command_name = (char *)NULL; /* no arithmetic errors */
11425 tint = do_word_assignment (temp_list->word, 0);
11426 this_command_name = savecmd;
11427 /* Variable assignment errors in non-interactive shells
11428 running in Posix.2 mode cause the shell to exit, unless
11429 they are being run by the `command' builtin. */
11430 if (tint == 0)
11431 {
11432 last_command_exit_value = EXECUTION_FAILURE;
11433 if (interactive_shell == 0 && posixly_correct && executing_command_builtin == 0)
11434 exp_jump_to_top_level (FORCE_EOF);
11435 else
11436 exp_jump_to_top_level (DISCARD);
11437 }
11438 }
11439 dispose_words (subst_assign_varlist);
11440 subst_assign_varlist = (WORD_LIST *)NULL;
11441 }
11442 return ((WORD_LIST *)NULL);
11443 }
11444 }
11445
11446 /* Begin expanding the words that remain. The expansions take place on
11447 things that aren't really variable assignments. */
11448
11449 #if defined (BRACE_EXPANSION)
11450 /* Do brace expansion on this word if there are any brace characters
11451 in the string. */
11452 if ((eflags & WEXP_BRACEEXP) && brace_expansion && new_list)
11453 new_list = brace_expand_word_list (new_list, eflags);
11454 #endif /* BRACE_EXPANSION */
11455
11456 /* Perform the `normal' shell expansions: tilde expansion, parameter and
11457 variable substitution, command substitution, arithmetic expansion,
11458 and word splitting. */
11459 new_list = shell_expand_word_list (new_list, eflags);
11460
11461 /* Okay, we're almost done. Now let's just do some filename
11462 globbing. */
11463 if (new_list)
11464 {
11465 if ((eflags & WEXP_PATHEXP) && disallow_filename_globbing == 0)
11466 /* Glob expand the word list unless globbing has been disabled. */
11467 new_list = glob_expand_word_list (new_list, eflags);
11468 else
11469 /* Dequote the words, because we're not performing globbing. */
11470 new_list = dequote_list (new_list);
11471 }
11472
11473 if ((eflags & WEXP_VARASSIGN) && subst_assign_varlist)
11474 {
11475 sh_wassign_func_t *assign_func;
11476 int is_special_builtin, is_builtin_or_func;
11477
11478 /* If the remainder of the words expand to nothing, Posix.2 requires
11479 that the variable and environment assignments affect the shell's
11480 environment. */
11481 assign_func = new_list ? assign_in_env : do_word_assignment;
11482 tempenv_assign_error = 0;
11483
11484 is_builtin_or_func = (new_list && new_list->word && (find_shell_builtin (new_list->word->word) || find_function (new_list->word->word)));
11485 /* Posix says that special builtins exit if a variable assignment error
11486 occurs in an assignment preceding it. */
11487 is_special_builtin = (posixly_correct && new_list && new_list->word && find_special_builtin (new_list->word->word));
11488
11489 for (temp_list = subst_assign_varlist; temp_list; temp_list = temp_list->next)
11490 {
11491 savecmd = this_command_name;
11492 this_command_name = (char *)NULL;
11493 assigning_in_environment = (assign_func == assign_in_env);
11494 tint = (*assign_func) (temp_list->word, is_builtin_or_func);
11495 assigning_in_environment = 0;
11496 this_command_name = savecmd;
11497 /* Variable assignment errors in non-interactive shells running
11498 in Posix.2 mode cause the shell to exit. */
11499 if (tint == 0)
11500 {
11501 if (assign_func == do_word_assignment)
11502 {
11503 last_command_exit_value = EXECUTION_FAILURE;
11504 if (interactive_shell == 0 && posixly_correct)
11505 exp_jump_to_top_level (FORCE_EOF);
11506 else
11507 exp_jump_to_top_level (DISCARD);
11508 }
11509 else if (interactive_shell == 0 && is_special_builtin)
11510 {
11511 last_command_exit_value = EXECUTION_FAILURE;
11512 exp_jump_to_top_level (FORCE_EOF);
11513 }
11514 else
11515 tempenv_assign_error++;
11516 }
11517 }
11518
11519 dispose_words (subst_assign_varlist);
11520 subst_assign_varlist = (WORD_LIST *)NULL;
11521 }
11522
11523 return (new_list);
11524 }