1 /* POSIX.2 wordexp implementation.
2 Copyright (C) 1997-2020 Free Software Foundation, Inc.
3 This file is part of the GNU C Library.
4 Contributed by Tim Waugh <tim@cyberelk.demon.co.uk>.
6 The GNU C Library is free software; you can redistribute it and/or
7 modify it under the terms of the GNU Lesser General Public
8 License as published by the Free Software Foundation; either
9 version 2.1 of the License, or (at your option) any later version.
11 The GNU C Library is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 Lesser General Public License for more details.
16 You should have received a copy of the GNU Lesser General Public
17 License along with the GNU C Library; if not, see
18 <https://www.gnu.org/licenses/>. */
31 #include <sys/param.h>
36 #include <scratch_buffer.h>
41 * This is a recursive-descent-style word expansion routine.
44 /* These variables are defined and initialized in the startup code. */
45 extern int __libc_argc attribute_hidden
;
46 extern char **__libc_argv attribute_hidden
;
48 /* Some forward declarations */
49 static int parse_dollars (char **word
, size_t *word_length
, size_t *max_length
,
50 const char *words
, size_t *offset
, int flags
,
51 wordexp_t
*pwordexp
, const char *ifs
,
52 const char *ifs_white
, int quoted
);
53 static int parse_backtick (char **word
, size_t *word_length
,
54 size_t *max_length
, const char *words
,
55 size_t *offset
, int flags
, wordexp_t
*pwordexp
,
56 const char *ifs
, const char *ifs_white
);
57 static int parse_dquote (char **word
, size_t *word_length
, size_t *max_length
,
58 const char *words
, size_t *offset
, int flags
,
59 wordexp_t
*pwordexp
, const char *ifs
,
60 const char *ifs_white
);
61 static int eval_expr (char *expr
, long int *result
);
63 /* The w_*() functions manipulate word lists. */
67 /* Result of w_newword will be ignored if it's the last word. */
69 w_newword (size_t *actlen
, size_t *maxlen
)
71 *actlen
= *maxlen
= 0;
76 w_addchar (char *buffer
, size_t *actlen
, size_t *maxlen
, char ch
)
77 /* (lengths exclude trailing zero) */
79 /* Add a character to the buffer, allocating room for it if needed. */
81 if (*actlen
== *maxlen
)
83 char *old_buffer
= buffer
;
84 assert (buffer
== NULL
|| *maxlen
!= 0);
86 buffer
= (char *) realloc (buffer
, 1 + *maxlen
);
95 buffer
[++(*actlen
)] = '\0';
102 w_addmem (char *buffer
, size_t *actlen
, size_t *maxlen
, const char *str
,
105 /* Add a string to the buffer, allocating room for it if needed.
107 if (*actlen
+ len
> *maxlen
)
109 char *old_buffer
= buffer
;
110 assert (buffer
== NULL
|| *maxlen
!= 0);
111 *maxlen
+= MAX (2 * len
, W_CHUNK
);
112 buffer
= realloc (old_buffer
, 1 + *maxlen
);
120 *((char *) __mempcpy (&buffer
[*actlen
], str
, len
)) = '\0';
128 w_addstr (char *buffer
, size_t *actlen
, size_t *maxlen
, const char *str
)
129 /* (lengths exclude trailing zero) */
131 /* Add a string to the buffer, allocating room for it if needed.
135 assert (str
!= NULL
); /* w_addstr only called from this file */
138 return w_addmem (buffer
, actlen
, maxlen
, str
, len
);
142 w_addword (wordexp_t
*pwordexp
, char *word
)
144 /* Add a word to the wordlist */
147 bool allocated
= false;
149 /* Internally, NULL acts like "". Convert NULLs to "" before
150 * the caller sees them.
154 word
= __strdup ("");
160 num_p
= 2 + pwordexp
->we_wordc
+ pwordexp
->we_offs
;
161 new_wordv
= realloc (pwordexp
->we_wordv
, sizeof (char *) * num_p
);
162 if (new_wordv
!= NULL
)
164 pwordexp
->we_wordv
= new_wordv
;
165 pwordexp
->we_wordv
[pwordexp
->we_offs
+ pwordexp
->we_wordc
++] = word
;
166 pwordexp
->we_wordv
[pwordexp
->we_offs
+ pwordexp
->we_wordc
] = NULL
;
177 /* The parse_*() functions should leave *offset being the offset in 'words'
178 * to the last character processed.
182 parse_backslash (char **word
, size_t *word_length
, size_t *max_length
,
183 const char *words
, size_t *offset
)
185 /* We are poised _at_ a backslash, not in quotes */
187 switch (words
[1 + *offset
])
190 /* Backslash is last character of input words */
198 *word
= w_addchar (*word
, word_length
, max_length
, words
[1 + *offset
]);
210 parse_qtd_backslash (char **word
, size_t *word_length
, size_t *max_length
,
211 const char *words
, size_t *offset
)
213 /* We are poised _at_ a backslash, inside quotes */
215 switch (words
[1 + *offset
])
218 /* Backslash is last character of input words */
229 *word
= w_addchar (*word
, word_length
, max_length
, words
[1 + *offset
]);
237 *word
= w_addchar (*word
, word_length
, max_length
, words
[*offset
]);
239 *word
= w_addchar (*word
, word_length
, max_length
, words
[1 + *offset
]);
252 parse_tilde (char **word
, size_t *word_length
, size_t *max_length
,
253 const char *words
, size_t *offset
, size_t wordc
)
255 /* We are poised _at_ a tilde */
258 if (*word_length
!= 0)
260 if (!((*word
)[*word_length
- 1] == '=' && wordc
== 0))
262 if (!((*word
)[*word_length
- 1] == ':'
263 && strchr (*word
, '=') && wordc
== 0))
265 *word
= w_addchar (*word
, word_length
, max_length
, '~');
266 return *word
? 0 : WRDE_NOSPACE
;
271 for (i
= 1 + *offset
; words
[i
]; i
++)
273 if (words
[i
] == ':' || words
[i
] == '/' || words
[i
] == ' '
274 || words
[i
] == '\t' || words
[i
] == 0 )
277 if (words
[i
] == '\\')
279 *word
= w_addchar (*word
, word_length
, max_length
, '~');
280 return *word
? 0 : WRDE_NOSPACE
;
284 if (i
== 1 + *offset
)
286 /* Tilde appears on its own */
289 /* POSIX.2 says ~ expands to $HOME and if HOME is unset the
290 results are unspecified. We do a lookup on the uid if
293 home
= getenv ("HOME");
296 *word
= w_addstr (*word
, word_length
, max_length
, home
);
302 struct passwd pwd
, *tpwd
;
303 uid_t uid
= __getuid ();
305 struct scratch_buffer tmpbuf
;
306 scratch_buffer_init (&tmpbuf
);
308 while ((result
= __getpwuid_r (uid
, &pwd
,
309 tmpbuf
.data
, tmpbuf
.length
,
312 if (!scratch_buffer_grow (&tmpbuf
))
315 if (result
== 0 && tpwd
!= NULL
&& pwd
.pw_dir
!= NULL
)
317 *word
= w_addstr (*word
, word_length
, max_length
, pwd
.pw_dir
);
320 scratch_buffer_free (&tmpbuf
);
326 *word
= w_addchar (*word
, word_length
, max_length
, '~');
329 scratch_buffer_free (&tmpbuf
);
333 scratch_buffer_free (&tmpbuf
);
338 /* Look up user name in database to get home directory */
339 char *user
= strndupa (&words
[1 + *offset
], i
- (1 + *offset
));
340 struct passwd pwd
, *tpwd
;
342 struct scratch_buffer tmpbuf
;
343 scratch_buffer_init (&tmpbuf
);
345 while ((result
= __getpwnam_r (user
, &pwd
, tmpbuf
.data
, tmpbuf
.length
,
348 if (!scratch_buffer_grow (&tmpbuf
))
351 if (result
== 0 && tpwd
!= NULL
&& pwd
.pw_dir
)
352 *word
= w_addstr (*word
, word_length
, max_length
, pwd
.pw_dir
);
355 /* (invalid login name) */
356 *word
= w_addchar (*word
, word_length
, max_length
, '~');
358 *word
= w_addstr (*word
, word_length
, max_length
, user
);
361 scratch_buffer_free (&tmpbuf
);
365 return *word
? 0 : WRDE_NOSPACE
;
370 do_parse_glob (const char *glob_word
, char **word
, size_t *word_length
,
371 size_t *max_length
, wordexp_t
*pwordexp
, const char *ifs
,
372 const char *ifs_white
)
378 error
= glob (glob_word
, GLOB_NOCHECK
, NULL
, &globbuf
);
382 /* We can only run into memory problems. */
383 assert (error
== GLOB_NOSPACE
);
389 /* No field splitting allowed. */
390 assert (globbuf
.gl_pathv
[0] != NULL
);
391 *word
= w_addstr (*word
, word_length
, max_length
, globbuf
.gl_pathv
[0]);
392 for (match
= 1; match
< globbuf
.gl_pathc
&& *word
!= NULL
; ++match
)
394 *word
= w_addchar (*word
, word_length
, max_length
, ' ');
396 *word
= w_addstr (*word
, word_length
, max_length
,
397 globbuf
.gl_pathv
[match
]);
401 return *word
? 0 : WRDE_NOSPACE
;
404 assert (ifs
== NULL
|| *ifs
!= '\0');
408 *word
= w_newword (word_length
, max_length
);
411 for (match
= 0; match
< globbuf
.gl_pathc
; ++match
)
413 char *matching_word
= __strdup (globbuf
.gl_pathv
[match
]);
414 if (matching_word
== NULL
|| w_addword (pwordexp
, matching_word
))
426 parse_glob (char **word
, size_t *word_length
, size_t *max_length
,
427 const char *words
, size_t *offset
, int flags
,
428 wordexp_t
*pwordexp
, const char *ifs
, const char *ifs_white
)
430 /* We are poised just after a '*', a '[' or a '?'. */
431 int error
= WRDE_NOSPACE
;
432 int quoted
= 0; /* 1 if singly-quoted, 2 if doubly */
434 wordexp_t glob_list
; /* List of words to glob */
436 glob_list
.we_wordc
= 0;
437 glob_list
.we_wordv
= NULL
;
438 glob_list
.we_offs
= 0;
439 for (; words
[*offset
] != '\0'; ++*offset
)
441 if (strchr (ifs
, words
[*offset
]) != NULL
)
445 /* Sort out quoting */
446 if (words
[*offset
] == '\'')
453 else if (quoted
== 1)
459 else if (words
[*offset
] == '"')
466 else if (quoted
== 2)
473 /* Sort out other special characters */
474 if (quoted
!= 1 && words
[*offset
] == '$')
476 error
= parse_dollars (word
, word_length
, max_length
, words
,
477 offset
, flags
, &glob_list
, ifs
, ifs_white
,
484 else if (words
[*offset
] == '\\')
487 error
= parse_qtd_backslash (word
, word_length
, max_length
,
490 error
= parse_backslash (word
, word_length
, max_length
,
499 *word
= w_addchar (*word
, word_length
, max_length
, words
[*offset
]);
504 /* Don't forget to re-parse the character we stopped at. */
508 error
= w_addword (&glob_list
, *word
);
509 *word
= w_newword (word_length
, max_length
);
510 for (i
= 0; error
== 0 && i
< glob_list
.we_wordc
; i
++)
511 error
= do_parse_glob (glob_list
.we_wordv
[i
], word
, word_length
,
512 max_length
, pwordexp
, ifs
, ifs_white
);
516 wordfree (&glob_list
);
521 parse_squote (char **word
, size_t *word_length
, size_t *max_length
,
522 const char *words
, size_t *offset
)
524 /* We are poised just after a single quote */
525 for (; words
[*offset
]; ++(*offset
))
527 if (words
[*offset
] != '\'')
529 *word
= w_addchar (*word
, word_length
, max_length
, words
[*offset
]);
536 /* Unterminated string */
540 /* Functions to evaluate an arithmetic expression */
542 eval_expr_val (char **expr
, long int *result
)
546 /* Skip white space */
547 for (digit
= *expr
; digit
&& *digit
&& isspace (*digit
); ++digit
);
551 /* Scan for closing paren */
552 for (++digit
; **expr
&& **expr
!= ')'; ++(*expr
));
560 if (eval_expr (digit
, result
))
566 /* POSIX requires that decimal, octal, and hexadecimal constants are
567 recognized. Therefore we pass 0 as the third parameter to strtol. */
568 *result
= strtol (digit
, expr
, 0);
576 eval_expr_multdiv (char **expr
, long int *result
)
581 if (eval_expr_val (expr
, result
) != 0)
586 /* Skip white space */
587 for (; *expr
&& **expr
&& isspace (**expr
); ++(*expr
));
592 if (eval_expr_val (expr
, &arg
) != 0)
597 else if (**expr
== '/')
600 if (eval_expr_val (expr
, &arg
) != 0)
603 /* Division by zero or integer overflow. */
604 if (arg
== 0 || (arg
== -1 && *result
== LONG_MIN
))
616 eval_expr (char *expr
, long int *result
)
621 if (eval_expr_multdiv (&expr
, result
) != 0)
626 /* Skip white space */
627 for (; expr
&& *expr
&& isspace (*expr
); ++expr
);
632 if (eval_expr_multdiv (&expr
, &arg
) != 0)
637 else if (*expr
== '-')
640 if (eval_expr_multdiv (&expr
, &arg
) != 0)
652 parse_arith (char **word
, size_t *word_length
, size_t *max_length
,
653 const char *words
, size_t *offset
, int flags
, int bracket
)
655 /* We are poised just after "$((" or "$[" */
662 expr
= w_newword (&expr_length
, &expr_maxlen
);
663 for (; words
[*offset
]; ++(*offset
))
665 switch (words
[*offset
])
668 error
= parse_dollars (&expr
, &expr_length
, &expr_maxlen
,
669 words
, offset
, flags
, NULL
, NULL
, NULL
, 1);
670 /* The ``1'' here is to tell parse_dollars not to
682 error
= parse_backtick (&expr
, &expr_length
, &expr_maxlen
,
683 words
, offset
, flags
, NULL
, NULL
, NULL
);
684 /* The first NULL here is to tell parse_backtick not to
695 error
= parse_qtd_backslash (&expr
, &expr_length
, &expr_maxlen
,
702 /* I think that a backslash within an
703 * arithmetic expansion is bound to
704 * cause an error sooner or later anyway though.
709 if (--paren_depth
== 0)
711 char result
[21]; /* 21 = ceil(log10(2^64)) + 1 */
712 long int numresult
= 0;
713 long long int convertme
;
715 if (bracket
|| words
[1 + *offset
] != ')')
724 if (*expr
&& eval_expr (expr
, &numresult
) != 0)
732 convertme
= -numresult
;
733 *word
= w_addchar (*word
, word_length
, max_length
, '-');
741 convertme
= numresult
;
744 *word
= w_addstr (*word
, word_length
, max_length
,
745 _itoa (convertme
, &result
[20], 10, 0));
747 return *word
? 0 : WRDE_NOSPACE
;
749 expr
= w_addchar (expr
, &expr_length
, &expr_maxlen
, words
[*offset
]);
756 if (bracket
&& paren_depth
== 1)
758 char result
[21]; /* 21 = ceil(log10(2^64)) + 1 */
759 long int numresult
= 0;
762 if (*expr
&& eval_expr (expr
, &numresult
) != 0)
769 *word
= w_addstr (*word
, word_length
, max_length
,
770 _itoa_word (numresult
, &result
[20], 10, 0));
772 return *word
? 0 : WRDE_NOSPACE
;
789 expr
= w_addchar (expr
, &expr_length
, &expr_maxlen
, words
[*offset
]);
800 #define DYNARRAY_STRUCT strlist
801 #define DYNARRAY_ELEMENT char *
802 #define DYNARRAY_PREFIX strlist_
803 /* Allocates about 512/1024 (32/64 bit) on stack. */
804 #define DYNARRAY_INITIAL_SIZE 128
805 #include <malloc/dynarray-skeleton.c>
807 /* Function called by child process in exec_comm() */
809 exec_comm_child (char *comm
, int *fildes
, bool showerr
, bool noexec
)
813 /* Execute the command, or just check syntax? */
814 const char *args
[] = { _PATH_BSHELL
, noexec
? "-nc" : "-c", comm
, NULL
};
816 posix_spawn_file_actions_t fa
;
817 /* posix_spawn_file_actions_init does not fail. */
818 __posix_spawn_file_actions_init (&fa
);
820 /* Redirect output. For check syntax only (noexec being true), exec_comm
821 explicits sets fildes[1] to -1, so check its value to avoid a failure in
822 __posix_spawn_file_actions_adddup2. */
825 if (__glibc_likely (fildes
[1] != STDOUT_FILENO
))
827 if (__posix_spawn_file_actions_adddup2 (&fa
, fildes
[1],
829 || __posix_spawn_file_actions_addclose (&fa
, fildes
[1]) != 0)
833 /* Reset the close-on-exec flag (if necessary). */
834 if (__posix_spawn_file_actions_adddup2 (&fa
, fildes
[1], fildes
[1])
839 /* Redirect stderr to /dev/null if we have to. */
841 if (__posix_spawn_file_actions_addopen (&fa
, STDERR_FILENO
, _PATH_DEVNULL
,
845 struct strlist newenv
;
846 strlist_init (&newenv
);
848 bool recreate_env
= getenv ("IFS") != NULL
;
851 for (char **ep
= __environ
; *ep
!= NULL
; ep
++)
852 if (strncmp (*ep
, "IFS=", strlen ("IFS=")) != 0)
853 strlist_add (&newenv
, *ep
);
854 strlist_add (&newenv
, NULL
);
855 if (strlist_has_failed (&newenv
))
859 /* pid is not set if posix_spawn fails, so it keep the original value
861 __posix_spawn (&pid
, _PATH_BSHELL
, &fa
, NULL
, (char *const *) args
,
862 recreate_env
? strlist_begin (&newenv
) : __environ
);
864 strlist_free (&newenv
);
867 __posix_spawn_file_actions_destroy (&fa
);
872 /* Function to execute a command and retrieve the results */
873 /* pwordexp contains NULL if field-splitting is forbidden */
875 exec_comm (char *comm
, char **word
, size_t *word_length
, size_t *max_length
,
876 int flags
, wordexp_t
*pwordexp
, const char *ifs
,
877 const char *ifs_white
)
884 size_t maxnewlines
= 0;
885 char buffer
[bufsize
];
889 /* Do nothing if command substitution should not succeed. */
890 if (flags
& WRDE_NOCMD
)
893 /* Don't posix_spawn unless necessary */
897 if (__pipe2 (fildes
, O_CLOEXEC
) < 0)
901 pid
= exec_comm_child (comm
, fildes
, noexec
? false : flags
& WRDE_SHOWERR
,
910 /* If we are just testing the syntax, only wait. */
912 return (TEMP_FAILURE_RETRY (__waitpid (pid
, &status
, 0)) == pid
913 && status
!= 0) ? WRDE_SYNTAX
: 0;
919 /* Quoted - no field splitting */
923 if ((buflen
= TEMP_FAILURE_RETRY (__read (fildes
[0], buffer
,
926 /* If read returned 0 then the process has closed its
927 stdout. Don't use WNOHANG in that case to avoid busy
928 looping until the process eventually exits. */
929 if (TEMP_FAILURE_RETRY (__waitpid (pid
, &status
,
930 buflen
== 0 ? 0 : WNOHANG
))
933 if ((buflen
= TEMP_FAILURE_RETRY (__read (fildes
[0], buffer
,
938 maxnewlines
+= buflen
;
940 *word
= w_addmem (*word
, word_length
, max_length
, buffer
, buflen
);
946 /* Not quoted - split fields */
950 * 0 when searching for first character in a field not IFS white space
951 * 1 when copying the text of a field
952 * 2 when searching for possible non-whitespace IFS
953 * 3 when searching for non-newline after copying field
958 if ((buflen
= TEMP_FAILURE_RETRY (__read (fildes
[0], buffer
,
961 /* If read returned 0 then the process has closed its
962 stdout. Don't use WNOHANG in that case to avoid busy
963 looping until the process eventually exits. */
964 if (TEMP_FAILURE_RETRY (__waitpid (pid
, &status
,
965 buflen
== 0 ? 0 : WNOHANG
))
968 if ((buflen
= TEMP_FAILURE_RETRY (__read (fildes
[0], buffer
,
973 for (i
= 0; i
< buflen
; ++i
)
975 if (strchr (ifs
, buffer
[i
]) != NULL
)
977 /* Current character is IFS */
978 if (strchr (ifs_white
, buffer
[i
]) == NULL
)
980 /* Current character is IFS but not whitespace */
986 * eg: text<space><comma><space>moretext
988 * So, strip whitespace IFS (like at the start)
995 /* fall through and delimit field.. */
999 if (buffer
[i
] == '\n')
1001 /* Current character is (IFS) newline */
1003 /* If copying a field, this is the end of it,
1004 but maybe all that's left is trailing newlines.
1005 So start searching for a non-newline. */
1013 /* Current character is IFS white space, but
1016 /* If not either copying a field or searching
1017 for non-newline after a field, ignore it */
1018 if (copying
!= 1 && copying
!= 3)
1021 /* End of field (search for non-ws IFS afterwards) */
1026 /* First IFS white space (non-newline), or IFS non-whitespace.
1027 * Delimit the field. Nulls are converted by w_addword. */
1028 if (w_addword (pwordexp
, *word
) == WRDE_NOSPACE
)
1031 *word
= w_newword (word_length
, max_length
);
1034 /* fall back round the loop.. */
1038 /* Not IFS character */
1042 /* Nothing but (IFS) newlines since the last field,
1043 so delimit it here before starting new word */
1044 if (w_addword (pwordexp
, *word
) == WRDE_NOSPACE
)
1047 *word
= w_newword (word_length
, max_length
);
1052 if (buffer
[i
] == '\n') /* happens if newline not in IFS */
1057 *word
= w_addchar (*word
, word_length
, max_length
,
1066 /* Chop off trailing newlines (required by POSIX.2) */
1067 /* Ensure we don't go back further than the beginning of the
1068 substitution (i.e. remove maxnewlines bytes at most) */
1069 while (maxnewlines
-- != 0
1070 && *word_length
> 0 && (*word
)[*word_length
- 1] == '\n')
1072 (*word
)[--*word_length
] = '\0';
1074 /* If the last word was entirely newlines, turn it into a new word
1075 * which can be ignored if there's nothing following it. */
1076 if (*word_length
== 0)
1079 *word
= w_newword (word_length
, max_length
);
1084 __close (fildes
[0]);
1087 /* Check for syntax error (re-execute but with "-n" flag) */
1088 if (buflen
< 1 && status
!= 0)
1097 __kill (pid
, SIGKILL
);
1098 TEMP_FAILURE_RETRY (__waitpid (pid
, NULL
, 0));
1099 __close (fildes
[0]);
1100 return WRDE_NOSPACE
;
1104 parse_comm (char **word
, size_t *word_length
, size_t *max_length
,
1105 const char *words
, size_t *offset
, int flags
, wordexp_t
*pwordexp
,
1106 const char *ifs
, const char *ifs_white
)
1108 /* We are poised just after "$(" */
1109 int paren_depth
= 1;
1111 int quoted
= 0; /* 1 for singly-quoted, 2 for doubly-quoted */
1114 char *comm
= w_newword (&comm_length
, &comm_maxlen
);
1116 for (; words
[*offset
]; ++(*offset
))
1118 switch (words
[*offset
])
1123 else if (quoted
== 1)
1131 else if (quoted
== 2)
1137 if (!quoted
&& --paren_depth
== 0)
1139 /* Go -- give script to the shell */
1142 /* posix_spawn already handles thread cancellation. */
1143 error
= exec_comm (comm
, word
, word_length
, max_length
,
1144 flags
, pwordexp
, ifs
, ifs_white
);
1151 /* This is just part of the script */
1159 comm
= w_addchar (comm
, &comm_length
, &comm_maxlen
, words
[*offset
]);
1161 return WRDE_NOSPACE
;
1164 /* Premature end. */
1170 #define CHAR_IN_SET(ch, char_set) \
1171 (memchr (char_set "", ch, sizeof (char_set) - 1) != NULL)
1174 parse_param (char **word
, size_t *word_length
, size_t *max_length
,
1175 const char *words
, size_t *offset
, int flags
, wordexp_t
*pwordexp
,
1176 const char *ifs
, const char *ifs_white
, int quoted
)
1178 /* We are poised just after "$" */
1182 ACT_RP_SHORT_LEFT
= '#',
1183 ACT_RP_LONG_LEFT
= 'L',
1184 ACT_RP_SHORT_RIGHT
= '%',
1185 ACT_RP_LONG_RIGHT
= 'R',
1186 ACT_NULL_ERROR
= '?',
1187 ACT_NULL_SUBST
= '-',
1188 ACT_NONNULL_SUBST
= '+',
1189 ACT_NULL_ASSIGN
= '='
1195 size_t start
= *offset
;
1199 enum action action
= ACT_NONE
;
1204 int pattern_is_quoted
= 0; /* 1 for singly-quoted, 2 for doubly-quoted */
1208 int brace
= words
[*offset
] == '{';
1210 env
= w_newword (&env_length
, &env_maxlen
);
1211 pattern
= w_newword (&pat_length
, &pat_maxlen
);
1216 /* First collect the parameter name. */
1218 if (words
[*offset
] == '#')
1226 if (isalpha (words
[*offset
]) || words
[*offset
] == '_')
1228 /* Normal parameter name. */
1231 env
= w_addchar (env
, &env_length
, &env_maxlen
,
1236 while (isalnum (words
[++*offset
]) || words
[*offset
] == '_');
1238 else if (isdigit (words
[*offset
]))
1240 /* Numeric parameter name. */
1244 env
= w_addchar (env
, &env_length
, &env_maxlen
,
1251 while (isdigit(words
[++*offset
]));
1253 else if (CHAR_IN_SET (words
[*offset
], "*@$"))
1255 /* Special parameter. */
1257 env
= w_addchar (env
, &env_length
, &env_maxlen
,
1271 /* Check for special action to be applied to the value. */
1272 switch (words
[*offset
])
1279 action
= ACT_RP_SHORT_LEFT
;
1280 if (words
[1 + *offset
] == '#')
1283 action
= ACT_RP_LONG_LEFT
;
1288 action
= ACT_RP_SHORT_RIGHT
;
1289 if (words
[1 + *offset
] == '%')
1292 action
= ACT_RP_LONG_RIGHT
;
1297 if (!CHAR_IN_SET (words
[1 + *offset
], "-=?+"))
1301 action
= words
[++*offset
];
1308 action
= words
[*offset
];
1315 /* Now collect the pattern, but don't expand it yet. */
1317 for (; words
[*offset
]; ++(*offset
))
1319 switch (words
[*offset
])
1322 if (!pattern_is_quoted
)
1327 if (!pattern_is_quoted
)
1336 if (pattern_is_quoted
)
1337 /* Quoted; treat as normal character. */
1340 /* Otherwise, it's an escape: next character is literal. */
1341 if (words
[++*offset
] == '\0')
1344 pattern
= w_addchar (pattern
, &pat_length
, &pat_maxlen
, '\\');
1345 if (pattern
== NULL
)
1351 if (pattern_is_quoted
== 0)
1352 pattern_is_quoted
= 1;
1353 else if (pattern_is_quoted
== 1)
1354 pattern_is_quoted
= 0;
1359 if (pattern_is_quoted
== 0)
1360 pattern_is_quoted
= 2;
1361 else if (pattern_is_quoted
== 2)
1362 pattern_is_quoted
= 0;
1367 pattern
= w_addchar (pattern
, &pat_length
, &pat_maxlen
,
1369 if (pattern
== NULL
)
1374 /* End of input string -- remember to reparse the character that we
1379 if (words
[start
] == '{' && words
[*offset
] != '}')
1386 /* $# expands to the number of positional parameters */
1388 value
= _itoa_word (__libc_argc
- 1, &buffer
[20], 10, 0);
1393 /* Just $ on its own */
1394 *offset
= start
- 1;
1395 *word
= w_addchar (*word
, word_length
, max_length
, '$');
1396 return *word
? 0 : WRDE_NOSPACE
;
1399 /* Is it a numeric parameter? */
1400 else if (isdigit (env
[0]))
1404 if (n
>= __libc_argc
)
1405 /* Substitute NULL. */
1408 /* Replace with appropriate positional parameter. */
1409 value
= __libc_argv
[n
];
1411 /* Is it a special parameter? */
1418 value
= _itoa_word (__getpid (), &buffer
[20], 10, 0);
1420 /* Is it `${#*}' or `${#@}'? */
1421 else if ((*env
== '*' || *env
== '@') && seen_hash
)
1424 value
= _itoa_word (__libc_argc
> 0 ? __libc_argc
- 1 : 0,
1425 &buffer
[20], 10, 0);
1426 *word
= w_addstr (*word
, word_length
, max_length
, value
);
1429 return *word
? 0 : WRDE_NOSPACE
;
1431 /* Is it `$*' or `$@' (unquoted) ? */
1432 else if (*env
== '*' || (*env
== '@' && !quoted
))
1434 size_t plist_len
= 0;
1438 /* Build up value parameter by parameter (copy them) */
1439 for (p
= 1; __libc_argv
[p
]; ++p
)
1440 plist_len
+= strlen (__libc_argv
[p
]) + 1; /* for space */
1441 value
= malloc (plist_len
);
1446 for (p
= 1; __libc_argv
[p
]; ++p
)
1450 end
= __stpcpy (end
, __libc_argv
[p
]);
1457 /* Must be a quoted `$@' */
1458 assert (*env
== '@' && quoted
);
1460 /* Each parameter is a separate word ("$@") */
1461 if (__libc_argc
== 2)
1462 value
= __libc_argv
[1];
1463 else if (__libc_argc
> 2)
1467 /* Append first parameter to current word. */
1468 value
= w_addstr (*word
, word_length
, max_length
,
1470 if (value
== NULL
|| w_addword (pwordexp
, value
))
1473 for (p
= 2; __libc_argv
[p
+ 1]; p
++)
1475 char *newword
= __strdup (__libc_argv
[p
]);
1476 if (newword
== NULL
|| w_addword (pwordexp
, newword
))
1480 /* Start a new word with the last parameter. */
1481 *word
= w_newword (word_length
, max_length
);
1482 value
= __libc_argv
[p
];
1493 value
= getenv (env
);
1495 if (value
== NULL
&& (flags
& WRDE_UNDEF
))
1497 /* Variable not defined. */
1498 error
= WRDE_BADVAL
;
1502 if (action
!= ACT_NONE
)
1504 int expand_pattern
= 0;
1506 /* First, find out if we need to expand pattern (i.e. if we will
1510 case ACT_RP_SHORT_LEFT
:
1511 case ACT_RP_LONG_LEFT
:
1512 case ACT_RP_SHORT_RIGHT
:
1513 case ACT_RP_LONG_RIGHT
:
1514 /* Always expand for these. */
1518 case ACT_NULL_ERROR
:
1519 case ACT_NULL_SUBST
:
1520 case ACT_NULL_ASSIGN
:
1521 if (!value
|| (!*value
&& colon_seen
))
1522 /* If param is unset, or set but null and a colon has been seen,
1523 the expansion of the pattern will be needed. */
1528 case ACT_NONNULL_SUBST
:
1529 /* Expansion of word will be needed if parameter is set and not null,
1530 or set null but no colon has been seen. */
1531 if (value
&& (*value
|| !colon_seen
))
1537 assert (! "Unrecognised action!");
1542 /* We need to perform tilde expansion, parameter expansion,
1543 command substitution, and arithmetic expansion. We also
1544 have to be a bit careful with wildcard characters, as
1545 pattern might be given to fnmatch soon. To do this, we
1546 convert quotes to escapes. */
1552 int quoted
= 0; /* 1: single quotes; 2: double */
1554 expanded
= w_newword (&exp_len
, &exp_maxl
);
1555 for (p
= pattern
; p
&& *p
; p
++)
1564 else if (quoted
== 0)
1573 else if (quoted
== 0)
1583 /* Convert quoted wildchar to escaped wildchar. */
1584 expanded
= w_addchar (expanded
, &exp_len
,
1587 if (expanded
== NULL
)
1594 error
= parse_dollars (&expanded
, &exp_len
, &exp_maxl
, p
,
1595 &offset
, flags
, NULL
, NULL
, NULL
, 1);
1610 if (quoted
|| exp_len
)
1614 error
= parse_tilde (&expanded
, &exp_len
, &exp_maxl
, p
,
1630 expanded
= w_addchar (expanded
, &exp_len
, &exp_maxl
, '\\');
1632 assert (*p
); /* checked when extracted initially */
1633 if (expanded
== NULL
)
1637 expanded
= w_addchar (expanded
, &exp_len
, &exp_maxl
, *p
);
1639 if (expanded
== NULL
)
1650 case ACT_RP_SHORT_LEFT
:
1651 case ACT_RP_LONG_LEFT
:
1652 case ACT_RP_SHORT_RIGHT
:
1653 case ACT_RP_LONG_RIGHT
:
1659 if (value
== NULL
|| pattern
== NULL
|| *pattern
== '\0')
1662 end
= value
+ strlen (value
);
1666 case ACT_RP_SHORT_LEFT
:
1667 for (p
= value
; p
<= end
; ++p
)
1671 if (fnmatch (pattern
, value
, 0) != FNM_NOMATCH
)
1676 char *newval
= __strdup (p
);
1694 case ACT_RP_LONG_LEFT
:
1695 for (p
= end
; p
>= value
; --p
)
1699 if (fnmatch (pattern
, value
, 0) != FNM_NOMATCH
)
1704 char *newval
= __strdup (p
);
1722 case ACT_RP_SHORT_RIGHT
:
1723 for (p
= end
; p
>= value
; --p
)
1725 if (fnmatch (pattern
, p
, 0) != FNM_NOMATCH
)
1728 newval
= malloc (p
- value
+ 1);
1737 *(char *) __mempcpy (newval
, value
, p
- value
) = '\0';
1748 case ACT_RP_LONG_RIGHT
:
1749 for (p
= value
; p
<= end
; ++p
)
1751 if (fnmatch (pattern
, p
, 0) != FNM_NOMATCH
)
1754 newval
= malloc (p
- value
+ 1);
1763 *(char *) __mempcpy (newval
, value
, p
- value
) = '\0';
1781 case ACT_NULL_ERROR
:
1782 if (value
&& *value
)
1783 /* Substitute parameter */
1787 if (!colon_seen
&& value
)
1788 /* Substitute NULL */
1792 const char *str
= pattern
;
1795 str
= _("parameter null or not set");
1797 __fxprintf (NULL
, "%s: %s\n", env
, str
);
1804 case ACT_NULL_SUBST
:
1805 if (value
&& *value
)
1806 /* Substitute parameter */
1812 if (!colon_seen
&& value
)
1813 /* Substitute NULL */
1816 value
= pattern
? __strdup (pattern
) : pattern
;
1819 if (pattern
&& !value
)
1824 case ACT_NONNULL_SUBST
:
1825 if (value
&& (*value
|| !colon_seen
))
1830 value
= pattern
? __strdup (pattern
) : pattern
;
1833 if (pattern
&& !value
)
1839 /* Substitute NULL */
1844 case ACT_NULL_ASSIGN
:
1845 if (value
&& *value
)
1846 /* Substitute parameter */
1849 if (!colon_seen
&& value
)
1851 /* Substitute NULL */
1860 value
= pattern
? __strdup (pattern
) : pattern
;
1863 if (pattern
&& !value
)
1866 __setenv (env
, value
?: "", 1);
1870 assert (! "Unrecognised action!");
1881 char param_length
[21];
1882 param_length
[20] = '\0';
1883 *word
= w_addstr (*word
, word_length
, max_length
,
1884 _itoa_word (value
? strlen (value
) : 0,
1885 ¶m_length
[20], 10, 0));
1888 assert (value
!= NULL
);
1892 return *word
? 0 : WRDE_NOSPACE
;
1898 if (quoted
|| !pwordexp
)
1900 /* Quoted - no field split */
1901 *word
= w_addstr (*word
, word_length
, max_length
, value
);
1905 return *word
? 0 : WRDE_NOSPACE
;
1909 /* Need to field-split */
1910 char *value_copy
= __strdup (value
); /* Don't modify value */
1911 char *field_begin
= value_copy
;
1912 int seen_nonws_ifs
= 0;
1917 if (value_copy
== NULL
)
1922 char *field_end
= field_begin
;
1925 /* If this isn't the first field, start a new word */
1926 if (field_begin
!= value_copy
)
1928 if (w_addword (pwordexp
, *word
) == WRDE_NOSPACE
)
1934 *word
= w_newword (word_length
, max_length
);
1937 /* Skip IFS whitespace before the field */
1938 field_begin
+= strspn (field_begin
, ifs_white
);
1940 if (!seen_nonws_ifs
&& *field_begin
== 0)
1941 /* Nothing but whitespace */
1944 /* Search for the end of the field */
1945 field_end
= field_begin
+ strcspn (field_begin
, ifs
);
1947 /* Set up pointer to the character after end of field and
1948 skip whitespace IFS after it. */
1949 next_field
= field_end
+ strspn (field_end
, ifs_white
);
1951 /* Skip at most one non-whitespace IFS character after the field */
1953 if (*next_field
&& strchr (ifs
, *next_field
))
1959 /* Null-terminate it */
1962 /* Tag a copy onto the current word */
1963 *word
= w_addstr (*word
, word_length
, max_length
, field_begin
);
1965 if (*word
== NULL
&& *field_begin
!= '\0')
1971 field_begin
= next_field
;
1973 while (seen_nonws_ifs
|| *field_begin
);
1985 error
= WRDE_NOSPACE
;
1989 error
= WRDE_SYNTAX
;
2002 parse_dollars (char **word
, size_t *word_length
, size_t *max_length
,
2003 const char *words
, size_t *offset
, int flags
,
2004 wordexp_t
*pwordexp
, const char *ifs
, const char *ifs_white
,
2007 /* We are poised _at_ "$" */
2008 switch (words
[1 + *offset
])
2013 *word
= w_addchar (*word
, word_length
, max_length
, '$');
2014 return *word
? 0 : WRDE_NOSPACE
;
2017 if (words
[2 + *offset
] == '(')
2019 /* Differentiate between $((1+3)) and $((echo);(ls)) */
2020 int i
= 3 + *offset
;
2022 while (words
[i
] && !(depth
== 0 && words
[i
] == ')'))
2024 if (words
[i
] == '(')
2026 else if (words
[i
] == ')')
2032 if (words
[i
] == ')' && words
[i
+ 1] == ')')
2035 /* Call parse_arith -- 0 is for "no brackets" */
2036 return parse_arith (word
, word_length
, max_length
, words
, offset
,
2042 return parse_comm (word
, word_length
, max_length
, words
, offset
, flags
,
2043 quoted
? NULL
: pwordexp
, ifs
, ifs_white
);
2047 /* Call parse_arith -- 1 is for "brackets" */
2048 return parse_arith (word
, word_length
, max_length
, words
, offset
, flags
,
2053 ++(*offset
); /* parse_param needs to know if "{" is there */
2054 return parse_param (word
, word_length
, max_length
, words
, offset
, flags
,
2055 pwordexp
, ifs
, ifs_white
, quoted
);
2060 parse_backtick (char **word
, size_t *word_length
, size_t *max_length
,
2061 const char *words
, size_t *offset
, int flags
,
2062 wordexp_t
*pwordexp
, const char *ifs
, const char *ifs_white
)
2064 /* We are poised just after "`" */
2069 char *comm
= w_newword (&comm_length
, &comm_maxlen
);
2071 for (; words
[*offset
]; ++(*offset
))
2073 switch (words
[*offset
])
2076 /* Go -- give the script to the shell */
2077 error
= exec_comm (comm
, word
, word_length
, max_length
, flags
,
2078 pwordexp
, ifs
, ifs_white
);
2085 error
= parse_qtd_backslash (&comm
, &comm_length
, &comm_maxlen
,
2097 error
= parse_backslash (&comm
, &comm_length
, &comm_maxlen
, words
,
2109 squoting
= 1 - squoting
;
2112 comm
= w_addchar (comm
, &comm_length
, &comm_maxlen
, words
[*offset
]);
2114 return WRDE_NOSPACE
;
2124 parse_dquote (char **word
, size_t *word_length
, size_t *max_length
,
2125 const char *words
, size_t *offset
, int flags
,
2126 wordexp_t
*pwordexp
, const char * ifs
, const char * ifs_white
)
2128 /* We are poised just after a double-quote */
2131 for (; words
[*offset
]; ++(*offset
))
2133 switch (words
[*offset
])
2139 error
= parse_dollars (word
, word_length
, max_length
, words
, offset
,
2140 flags
, pwordexp
, ifs
, ifs_white
, 1);
2141 /* The ``1'' here is to tell parse_dollars not to
2142 * split the fields. It may need to, however ("$@").
2151 error
= parse_backtick (word
, word_length
, max_length
, words
,
2152 offset
, flags
, NULL
, NULL
, NULL
);
2153 /* The first NULL here is to tell parse_backtick not to
2162 error
= parse_qtd_backslash (word
, word_length
, max_length
, words
,
2171 *word
= w_addchar (*word
, word_length
, max_length
, words
[*offset
]);
2173 return WRDE_NOSPACE
;
2177 /* Unterminated string */
2182 * wordfree() is to be called after pwordexp is finished with.
2186 wordfree (wordexp_t
*pwordexp
)
2189 /* wordexp can set pwordexp to NULL */
2190 if (pwordexp
&& pwordexp
->we_wordv
)
2192 char **wordv
= pwordexp
->we_wordv
;
2194 for (wordv
+= pwordexp
->we_offs
; *wordv
; ++wordv
)
2197 free (pwordexp
->we_wordv
);
2198 pwordexp
->we_wordv
= NULL
;
2201 libc_hidden_def (wordfree
)
2208 wordexp (const char *words
, wordexp_t
*pwordexp
, int flags
)
2210 size_t words_offset
;
2213 char *word
= w_newword (&word_length
, &max_length
);
2217 wordexp_t old_word
= *pwordexp
;
2219 if (flags
& WRDE_REUSE
)
2221 /* Minimal implementation of WRDE_REUSE for now */
2222 wordfree (pwordexp
);
2223 old_word
.we_wordv
= NULL
;
2226 if ((flags
& WRDE_APPEND
) == 0)
2228 pwordexp
->we_wordc
= 0;
2230 if (flags
& WRDE_DOOFFS
)
2232 pwordexp
->we_wordv
= calloc (1 + pwordexp
->we_offs
, sizeof (char *));
2233 if (pwordexp
->we_wordv
== NULL
)
2235 error
= WRDE_NOSPACE
;
2241 pwordexp
->we_wordv
= calloc (1, sizeof (char *));
2242 if (pwordexp
->we_wordv
== NULL
)
2244 error
= WRDE_NOSPACE
;
2248 pwordexp
->we_offs
= 0;
2252 /* Find out what the field separators are.
2253 * There are two types: whitespace and non-whitespace.
2255 ifs
= getenv ("IFS");
2258 /* IFS unset - use <space><tab><newline>. */
2259 ifs
= strcpy (ifs_white
, " \t\n");
2263 char *whch
= ifs_white
;
2265 while (*ifsch
!= '\0')
2267 if (*ifsch
== ' ' || *ifsch
== '\t' || *ifsch
== '\n')
2269 /* Whitespace IFS. See first whether it is already in our
2271 char *runp
= ifs_white
;
2273 while (runp
< whch
&& *runp
!= *ifsch
)
2285 for (words_offset
= 0 ; words
[words_offset
] ; ++words_offset
)
2286 switch (words
[words_offset
])
2289 error
= parse_backslash (&word
, &word_length
, &max_length
, words
,
2298 error
= parse_dollars (&word
, &word_length
, &max_length
, words
,
2299 &words_offset
, flags
, pwordexp
, ifs
, ifs_white
,
2309 error
= parse_backtick (&word
, &word_length
, &max_length
, words
,
2310 &words_offset
, flags
, pwordexp
, ifs
,
2320 error
= parse_dquote (&word
, &word_length
, &max_length
, words
,
2321 &words_offset
, flags
, pwordexp
, ifs
, ifs_white
);
2328 error
= w_addword (pwordexp
, NULL
);
2338 error
= parse_squote (&word
, &word_length
, &max_length
, words
,
2346 error
= w_addword (pwordexp
, NULL
);
2355 error
= parse_tilde (&word
, &word_length
, &max_length
, words
,
2356 &words_offset
, pwordexp
->we_wordc
);
2366 error
= parse_glob (&word
, &word_length
, &max_length
, words
,
2367 &words_offset
, flags
, pwordexp
, ifs
, ifs_white
);
2375 /* Is it a word separator? */
2376 if (strchr (" \t", words
[words_offset
]) == NULL
)
2378 char ch
= words
[words_offset
];
2380 /* Not a word separator -- but is it a valid word char? */
2381 if (strchr ("\n|&;<>(){}", ch
))
2384 error
= WRDE_BADCHAR
;
2388 /* "Ordinary" character -- add it to word */
2389 word
= w_addchar (word
, &word_length
, &max_length
,
2393 error
= WRDE_NOSPACE
;
2400 /* If a word has been delimited, add it to the list. */
2403 error
= w_addword (pwordexp
, word
);
2408 word
= w_newword (&word_length
, &max_length
);
2413 /* There was a word separator at the end */
2414 if (word
== NULL
) /* i.e. w_newword */
2417 /* There was no field separator at the end */
2418 return w_addword (pwordexp
, word
);
2422 * free memory used (unless error is WRDE_NOSPACE), and
2423 * set pwordexp members back to what they were.
2428 if (error
== WRDE_NOSPACE
)
2429 return WRDE_NOSPACE
;
2431 if ((flags
& WRDE_APPEND
) == 0)
2432 wordfree (pwordexp
);
2434 *pwordexp
= old_word
;