1 /* vi: set sw=4 ts=4: */
2 /* POSIX.2 wordexp implementation.
3 Copyright (C) 1997, 1998, 1999 Free Software Foundation, Inc.
4 This file is part of the GNU C Library.
5 Contributed by Tim Waugh <tim@cyberelk.demon.co.uk>.
7 The GNU C Library is free software; you can redistribute it and/or
8 modify it under the terms of the GNU Library General Public License as
9 published by the Free Software Foundation; either version 2 of the
10 License, or (at your option) any later version.
12 The GNU C Library is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 Library General Public License for more details.
17 You should have received a copy of the GNU Library General Public
18 License along with the GNU C Library; see the file COPYING.LIB. If not,
19 write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
20 Boston, MA 02111-1307, USA. */
23 #include <sys/types.h>
38 #define __WORDEXP_FULL
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;*/
46 /*extern char **__libc_argv;*/
49 int attribute_hidden __libc_argc;
50 char attribute_hidden **__libc_argv;
52 /* Some forward declarations */
53 static int parse_dollars(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,
58 static int parse_backtick(char **word, size_t * word_length,
59 size_t * max_length, const char *words,
60 size_t * offset, int flags, wordexp_t * pwordexp,
61 const char *ifs, const char *ifs_white);
62 static int parse_dquote(char **word, size_t * word_length,
63 size_t * max_length, const char *words,
64 size_t * offset, int flags, wordexp_t * pwordexp,
65 const char *ifs, const char *ifs_white);
69 /* The w_*() functions manipulate word lists. */
72 /* Result of w_newword will be ignored if it's the last word. */
73 static __inline__ char *w_newword(size_t * actlen, size_t * maxlen)
75 *actlen = *maxlen = 0;
79 /* Add a character to the buffer, allocating room for it if needed. */
80 static __inline__ char *w_addchar(char *buffer, size_t * actlen,
81 size_t * maxlen, char ch)
82 /* (lengths exclude trailing zero) */
85 if (*actlen == *maxlen) {
86 char *old_buffer = buffer;
87 assert(buffer == NULL || *maxlen != 0);
89 buffer = realloc(buffer, 1 + *maxlen);
96 buffer[++(*actlen)] = '\0';
102 #define MAX( a, b ) ( ( ( a ) > ( b ) ) ? ( a ) : ( b ) )
103 static char *w_addmem(char *buffer, size_t * actlen, size_t * maxlen,
104 const char *str, size_t len)
106 /* Add a string to the buffer, allocating room for it if needed.
108 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);
117 if (buffer != NULL) {
118 *((char *) mempcpy(&buffer[*actlen], str, len)) = '\0';
124 /* Add a string to the buffer, allocating room for it if needed. */
125 static char *w_addstr(char *buffer, size_t * actlen, size_t * maxlen,
127 /* (lengths exclude trailing zero) */
130 assert(str != NULL); /* w_addstr only called from this file */
133 return w_addmem(buffer, actlen, maxlen, str, len);
136 /* Add a word to the wordlist */
137 static int w_addword(wordexp_t * pwordexp, char *word)
142 /* Internally, NULL acts like "". Convert NULLs to "" before
143 * the caller sees them.
151 num_p = 2 + pwordexp->we_wordc + pwordexp->we_offs;
152 new_wordv = realloc(pwordexp->we_wordv, sizeof(char *) * num_p);
153 if (new_wordv != NULL) {
154 pwordexp->we_wordv = new_wordv;
155 pwordexp->we_wordv[pwordexp->we_offs + pwordexp->we_wordc++] = word;
156 pwordexp->we_wordv[pwordexp->we_offs + pwordexp->we_wordc] = NULL;
164 /* The parse_*() functions should leave *offset being the offset in 'words'
165 * to the last character processed.
168 parse_backslash(char **word, size_t * word_length, size_t * max_length,
169 const char *words, size_t * offset)
171 /* We are poised _at_ a backslash, not in quotes */
173 switch (words[1 + *offset]) {
175 /* Backslash is last character of input words */
183 *word = w_addchar(*word, word_length, max_length, words[1 + *offset]);
195 parse_qtd_backslash(char **word, size_t * word_length, size_t * max_length,
196 const char *words, size_t * offset)
198 /* We are poised _at_ a backslash, inside quotes */
200 switch (words[1 + *offset]) {
202 /* Backslash is last character of input words */
214 w_addchar(*word, word_length, max_length, words[1 + *offset]);
222 *word = w_addchar(*word, word_length, max_length, words[*offset]);
225 w_addchar(*word, word_length, max_length,
239 parse_tilde(char **word, size_t * word_length, size_t * max_length,
240 const char *words, size_t * offset, size_t wordc)
242 /* We are poised _at_ a tilde */
245 if (*word_length != 0) {
246 if (!((*word)[*word_length - 1] == '=' && wordc == 0)) {
247 if (!((*word)[*word_length - 1] == ':'
248 && strchr(*word, '=') && wordc == 0)) {
249 *word = w_addchar(*word, word_length, max_length, '~');
250 return *word ? 0 : WRDE_NOSPACE;
255 for (i = 1 + *offset; words[i]; i++) {
256 if (words[i] == ':' || words[i] == '/' || words[i] == ' ' ||
257 words[i] == '\t' || words[i] == 0)
260 if (words[i] == '\\') {
261 *word = w_addchar(*word, word_length, max_length, '~');
262 return *word ? 0 : WRDE_NOSPACE;
266 if (i == 1 + *offset) {
267 /* Tilde appears on its own */
269 struct passwd pwd, *tpwd;
275 /* POSIX.2 says ~ expands to $HOME and if HOME is unset the
276 results are unspecified. We do a lookup on the uid if
279 home = getenv("HOME");
281 *word = w_addstr(*word, word_length, max_length, home);
286 buffer = alloca(buflen);
288 while ((result = getpwuid_r(uid, &pwd, buffer, buflen, &tpwd))
289 != 0 && errno == ERANGE)
292 buffer = alloca(buflen);
295 if (result == 0 && tpwd != NULL && pwd.pw_dir != NULL) {
296 *word = w_addstr(*word, word_length, max_length, pwd.pw_dir);
300 *word = w_addchar(*word, word_length, max_length, '~');
306 /* Look up user name in database to get home directory */
307 char *user = strndup(&words[1 + *offset], i - (1 + *offset));
308 struct passwd pwd, *tpwd;
310 char *buffer = alloca(buflen);
313 while ((result = getpwnam_r(user, &pwd, buffer, buflen, &tpwd)) != 0
314 && errno == ERANGE) {
316 buffer = alloca(buflen);
319 if (result == 0 && tpwd != NULL && pwd.pw_dir)
320 *word = w_addstr(*word, word_length, max_length, pwd.pw_dir);
322 /* (invalid login name) */
323 *word = w_addchar(*word, word_length, max_length, '~');
325 *word = w_addstr(*word, word_length, max_length, user);
330 return *word ? 0 : WRDE_NOSPACE;
335 do_parse_glob(const char *glob_word, char **word, size_t * word_length,
336 size_t * max_length, wordexp_t * pwordexp, const char *ifs
337 /*, const char *ifs_white*/)
343 error = glob(glob_word, GLOB_NOCHECK, NULL, &globbuf);
346 /* We can only run into memory problems. */
347 assert(error == GLOB_NOSPACE);
352 /* No field splitting allowed. */
353 assert(globbuf.gl_pathv[0] != NULL);
354 *word = w_addstr(*word, word_length, max_length, globbuf.gl_pathv[0]);
355 for (match = 1; match < globbuf.gl_pathc && *word != NULL; ++match) {
356 *word = w_addchar(*word, word_length, max_length, ' ');
358 *word = w_addstr(*word, word_length, max_length,
359 globbuf.gl_pathv[match]);
363 return *word ? 0 : WRDE_NOSPACE;
366 assert(ifs == NULL || *ifs != '\0');
369 *word = w_newword(word_length, max_length);
372 for (match = 0; match < globbuf.gl_pathc; ++match) {
373 char *matching_word = strdup(globbuf.gl_pathv[match]);
375 if (matching_word == NULL || w_addword(pwordexp, matching_word)) {
386 parse_glob(char **word, size_t * word_length, size_t * max_length,
387 const char *words, size_t * offset, int flags,
388 wordexp_t * pwordexp, const char *ifs, const char *ifs_white)
390 /* We are poised just after a '*', a '[' or a '?'. */
391 int error = WRDE_NOSPACE;
392 int quoted = 0; /* 1 if singly-quoted, 2 if doubly */
394 wordexp_t glob_list; /* List of words to glob */
396 glob_list.we_wordc = 0;
397 glob_list.we_wordv = NULL;
398 glob_list.we_offs = 0;
399 for (; words[*offset] != '\0'; ++*offset) {
400 if ((ifs && strchr(ifs, words[*offset])) ||
401 (!ifs && strchr(" \t\n", words[*offset])))
405 /* Sort out quoting */
406 if (words[*offset] == '\'') {
410 } else if (quoted == 1) {
414 } else if (words[*offset] == '"') {
418 } else if (quoted == 2) {
424 /* Sort out other special characters */
425 if (quoted != 1 && words[*offset] == '$') {
426 error = parse_dollars(word, word_length, max_length, words,
427 offset, flags, &glob_list, ifs,
428 ifs_white, quoted == 2);
433 } else if (words[*offset] == '\\') {
435 error = parse_qtd_backslash(word, word_length, max_length,
438 error = parse_backslash(word, word_length, max_length,
447 *word = w_addchar(*word, word_length, max_length, words[*offset]);
452 /* Don't forget to re-parse the character we stopped at. */
456 error = w_addword(&glob_list, *word);
457 *word = w_newword(word_length, max_length);
458 for (i = 0; error == 0 && i < glob_list.we_wordc; i++)
459 error = do_parse_glob(glob_list.we_wordv[i], word, word_length,
460 max_length, pwordexp, ifs /*, ifs_white*/);
464 wordfree(&glob_list);
469 parse_squote(char **word, size_t * word_length, size_t * max_length,
470 const char *words, size_t * offset)
472 /* We are poised just after a single quote */
473 for (; words[*offset]; ++(*offset)) {
474 if (words[*offset] != '\'') {
475 *word = w_addchar(*word, word_length, max_length, words[*offset]);
482 /* Unterminated string */
486 #ifdef __WORDEXP_FULL
487 static int eval_expr(char *expr, long int *result);
489 static char *_itoa(unsigned long long int value, char *buflim)
491 sprintf(buflim, "%llu", value);
495 /* Functions to evaluate an arithmetic expression */
496 static int eval_expr_val(char **expr, long int *result)
501 /* Skip white space */
502 for (digit = *expr; digit && *digit && isspace(*digit); ++digit);
507 /* Scan for closing paren */
508 for (++digit; **expr && **expr != ')'; ++(*expr));
516 if (eval_expr(digit, result))
521 case '+': /* Positive value */
525 case '-': /* Negative value */
531 if (!isdigit(*digit))
536 for (; *digit && isdigit(*digit); ++digit)
537 *result = (*result * 10) + (*digit - '0');
544 static int eval_expr_multdiv(char **expr, long int *result)
549 if (eval_expr_val(expr, result) != 0)
553 /* Skip white space */
554 for (; *expr && **expr && isspace(**expr); ++(*expr));
558 if (eval_expr_val(expr, &arg) != 0)
562 } else if (**expr == '/') {
564 if (eval_expr_val(expr, &arg) != 0)
575 static int eval_expr(char *expr, long int *result)
580 if (eval_expr_multdiv(&expr, result) != 0)
584 /* Skip white space */
585 for (; expr && *expr && isspace(*expr); ++expr);
589 if (eval_expr_multdiv(&expr, &arg) != 0)
593 } else if (*expr == '-') {
595 if (eval_expr_multdiv(&expr, &arg) != 0)
607 parse_arith(char **word, size_t * word_length, size_t * max_length,
608 const char *words, size_t * offset, int flags, int bracket)
610 /* We are poised just after "$((" or "$[" */
617 expr = w_newword(&expr_length, &expr_maxlen);
618 for (; words[*offset]; ++(*offset)) {
619 switch (words[*offset]) {
621 error = parse_dollars(&expr, &expr_length, &expr_maxlen,
622 words, offset, flags, NULL, NULL, NULL,
624 /* The ``1'' here is to tell parse_dollars not to
635 error = parse_backtick(&expr, &expr_length, &expr_maxlen,
636 words, offset, flags, NULL, NULL, NULL);
637 /* The first NULL here is to tell parse_backtick not to
647 error = parse_qtd_backslash(&expr, &expr_length, &expr_maxlen,
653 /* I think that a backslash within an
654 * arithmetic expansion is bound to
655 * cause an error sooner or later anyway though.
660 if (--paren_depth == 0) {
661 char result[21]; /* 21 = ceil(log10(2^64)) + 1 */
662 long int numresult = 0;
663 long long int convertme;
665 if (bracket || words[1 + *offset] != ')') {
673 if (*expr && eval_expr(expr, &numresult) != 0) {
679 convertme = -numresult;
680 *word = w_addchar(*word, word_length, max_length, '-');
686 convertme = numresult;
689 *word = w_addstr(*word, word_length, max_length,
690 _itoa(convertme, &result[20]));
692 return *word ? 0 : WRDE_NOSPACE;
695 w_addchar(expr, &expr_length, &expr_maxlen,
703 if (bracket && paren_depth == 1) {
704 char result[21]; /* 21 = ceil(log10(2^64)) + 1 */
705 long int numresult = 0;
708 if (*expr && eval_expr(expr, &numresult) != 0) {
714 *word = w_addstr(*word, word_length, max_length,
715 _itoa(numresult, &result[20]));
717 return *word ? 0 : WRDE_NOSPACE;
734 w_addchar(expr, &expr_length, &expr_maxlen,
746 /* Function called by child process in exec_comm() */
747 static void attribute_noreturn
748 exec_comm_child(char *comm, int *fildes, int showerr, int noexec)
751 const char *args[4] = { _PATH_BSHELL, "-c", comm, NULL };
753 /* Execute the command, or just check syntax? */
757 /* Redirect output. */
764 /* Redirect stderr to /dev/null if we have to. */
767 fd = open(_PATH_DEVNULL, O_WRONLY);
768 if (fd >= 0 && fd != 2) {
774 /* Make sure the subshell doesn't field-split on our behalf. */
779 execve(_PATH_BSHELL, (char *const *) args, __environ);
785 /* Function to execute a command and retrieve the results */
786 /* pwordexp contains NULL if field-splitting is forbidden */
788 exec_comm(char *comm, char **word, size_t * word_length,
789 size_t * max_length, int flags, wordexp_t * pwordexp,
790 const char *ifs, const char *ifs_white)
797 size_t maxnewlines = 0;
801 /* Don't fork() unless necessary */
809 if ((pid = fork()) < 0) {
817 exec_comm_child(comm, fildes, (flags & WRDE_SHOWERR), 0);
822 buffer = alloca(bufsize);
825 /* Quoted - no field splitting */
828 if ((buflen = read(fildes[0], buffer, bufsize)) < 1) {
829 if (waitpid(pid, &status, WNOHANG) == 0)
831 if ((buflen = read(fildes[0], buffer, bufsize)) < 1)
835 maxnewlines += buflen;
837 *word = w_addmem(*word, word_length, max_length, buffer, buflen);
842 /* Not quoted - split fields */
847 * 0 when searching for first character in a field not IFS white space
848 * 1 when copying the text of a field
849 * 2 when searching for possible non-whitespace IFS
850 * 3 when searching for non-newline after copying field
854 if ((buflen = read(fildes[0], buffer, bufsize)) < 1) {
855 if (waitpid(pid, &status, WNOHANG) == 0)
857 if ((buflen = read(fildes[0], buffer, bufsize)) < 1)
861 for (i = 0; i < buflen; ++i) {
862 if (strchr(ifs, buffer[i]) != NULL) {
863 /* Current character is IFS */
864 if (strchr(ifs_white, buffer[i]) == NULL) {
865 /* Current character is IFS but not whitespace */
870 * eg: text<space><comma><space>moretext
872 * So, strip whitespace IFS (like at the start)
879 /* fall through and delimit field.. */
881 if (buffer[i] == '\n') {
882 /* Current character is (IFS) newline */
884 /* If copying a field, this is the end of it,
885 but maybe all that's left is trailing newlines.
886 So start searching for a non-newline. */
892 /* Current character is IFS white space, but
895 /* If not either copying a field or searching
896 for non-newline after a field, ignore it */
897 if (copying != 1 && copying != 3)
900 /* End of field (search for non-ws IFS afterwards) */
905 /* First IFS white space (non-newline), or IFS non-whitespace.
906 * Delimit the field. Nulls are converted by w_addword. */
907 if (w_addword(pwordexp, *word) == WRDE_NOSPACE)
910 *word = w_newword(word_length, max_length);
913 /* fall back round the loop.. */
915 /* Not IFS character */
918 /* Nothing but (IFS) newlines since the last field,
919 so delimit it here before starting new word */
920 if (w_addword(pwordexp, *word) == WRDE_NOSPACE)
923 *word = w_newword(word_length, max_length);
928 if (buffer[i] == '\n') /* happens if newline not in IFS */
933 *word = w_addchar(*word, word_length, max_length,
942 /* Chop off trailing newlines (required by POSIX.2) */
943 /* Ensure we don't go back further than the beginning of the
944 substitution (i.e. remove maxnewlines bytes at most) */
945 while (maxnewlines-- != 0 &&
946 *word_length > 0 && (*word)[*word_length - 1] == '\n') {
947 (*word)[--*word_length] = '\0';
949 /* If the last word was entirely newlines, turn it into a new word
950 * which can be ignored if there's nothing following it. */
951 if (*word_length == 0) {
953 *word = w_newword(word_length, max_length);
960 /* Check for syntax error (re-execute but with "-n" flag) */
961 if (buflen < 1 && status != 0) {
962 if ((pid = fork()) < 0) {
968 fildes[0] = fildes[1] = -1;
969 exec_comm_child(comm, fildes, 0, 1);
972 if (waitpid(pid, &status, 0) == pid && status != 0)
980 waitpid(pid, NULL, 0);
986 parse_comm(char **word, size_t * word_length, size_t * max_length,
987 const char *words, size_t * offset, int flags,
988 wordexp_t * pwordexp, const char *ifs, const char *ifs_white)
990 /* We are poised just after "$(" */
993 int quoted = 0; /* 1 for singly-quoted, 2 for doubly-quoted */
996 char *comm = w_newword(&comm_length, &comm_maxlen);
998 for (; words[*offset]; ++(*offset)) {
999 switch (words[*offset]) {
1003 else if (quoted == 1)
1011 else if (quoted == 2)
1017 if (!quoted && --paren_depth == 0) {
1018 /* Go -- give script to the shell */
1020 error = exec_comm(comm, word, word_length, max_length,
1021 flags, pwordexp, ifs, ifs_white);
1028 /* This is just part of the script */
1036 comm = w_addchar(comm, &comm_length, &comm_maxlen, words[*offset]);
1038 return WRDE_NOSPACE;
1048 parse_backtick(char **word, size_t * word_length, size_t * max_length,
1049 const char *words, size_t * offset, int flags,
1050 wordexp_t * pwordexp, const char *ifs,
1051 const char *ifs_white)
1053 /* We are poised just after "`" */
1058 char *comm = w_newword(&comm_length, &comm_maxlen);
1060 for (; words[*offset]; ++(*offset)) {
1061 switch (words[*offset]) {
1063 /* Go -- give the script to the shell */
1064 error = exec_comm(comm, word, word_length, max_length, flags,
1065 pwordexp, ifs, ifs_white);
1071 error = parse_qtd_backslash(&comm, &comm_length, &comm_maxlen,
1083 error = parse_backslash(&comm, &comm_length, &comm_maxlen, words,
1094 squoting = 1 - squoting;
1096 comm = w_addchar(comm, &comm_length, &comm_maxlen,
1099 return WRDE_NOSPACE;
1109 parse_param(char **word, size_t * word_length, size_t * max_length,
1110 const char *words, size_t * offset, int flags,
1111 wordexp_t * pwordexp, const char *ifs, const char *ifs_white,
1114 /* We are poised just after "$" */
1117 ACT_RP_SHORT_LEFT = '#',
1118 ACT_RP_LONG_LEFT = 'L',
1119 ACT_RP_SHORT_RIGHT = '%',
1120 ACT_RP_LONG_RIGHT = 'R',
1121 ACT_NULL_ERROR = '?',
1122 ACT_NULL_SUBST = '-',
1123 ACT_NONNULL_SUBST = '+',
1124 ACT_NULL_ASSIGN = '='
1130 size_t start = *offset;
1134 enum action action = ACT_NONE;
1139 int pattern_is_quoted = 0; /* 1 for singly-quoted, 2 for doubly-quoted */
1143 int brace = words[*offset] == '{';
1145 env = w_newword(&env_length, &env_maxlen);
1146 pattern = w_newword(&pat_length, &pat_maxlen);
1151 /* First collect the parameter name. */
1153 if (words[*offset] == '#') {
1160 if (isalpha(words[*offset]) || words[*offset] == '_') {
1161 /* Normal parameter name. */
1163 env = w_addchar(env, &env_length, &env_maxlen, words[*offset]);
1167 while (isalnum(words[++*offset]) || words[*offset] == '_');
1168 } else if (isdigit(words[*offset])) {
1169 /* Numeric parameter name. */
1172 env = w_addchar(env, &env_length, &env_maxlen, words[*offset]);
1178 while (isdigit(words[++*offset]));
1179 } else if (strchr("*@$", words[*offset]) != NULL) {
1180 /* Special parameter. */
1182 env = w_addchar(env, &env_length, &env_maxlen, words[*offset]);
1192 /* Check for special action to be applied to the value. */
1193 switch (words[*offset]) {
1199 action = ACT_RP_SHORT_LEFT;
1200 if (words[1 + *offset] == '#') {
1202 action = ACT_RP_LONG_LEFT;
1207 action = ACT_RP_SHORT_RIGHT;
1208 if (words[1 + *offset] == '%') {
1210 action = ACT_RP_LONG_RIGHT;
1215 if (strchr("-=?+", words[1 + *offset]) == NULL)
1219 action = words[++*offset];
1226 action = words[*offset];
1233 /* Now collect the pattern, but don't expand it yet. */
1235 for (; words[*offset]; ++(*offset)) {
1236 switch (words[*offset]) {
1238 if (!pattern_is_quoted)
1243 if (!pattern_is_quoted) {
1251 if (pattern_is_quoted)
1252 /* Quoted; treat as normal character. */
1255 /* Otherwise, it's an escape: next character is literal. */
1256 if (words[++*offset] == '\0')
1259 pattern = w_addchar(pattern, &pat_length, &pat_maxlen, '\\');
1260 if (pattern == NULL)
1266 if (pattern_is_quoted == 0)
1267 pattern_is_quoted = 1;
1268 else if (pattern_is_quoted == 1)
1269 pattern_is_quoted = 0;
1274 if (pattern_is_quoted == 0)
1275 pattern_is_quoted = 2;
1276 else if (pattern_is_quoted == 2)
1277 pattern_is_quoted = 0;
1282 pattern = w_addchar(pattern, &pat_length, &pat_maxlen,
1284 if (pattern == NULL)
1289 /* End of input string -- remember to reparse the character that we
1294 if (words[start] == '{' && words[*offset] != '}')
1299 /* $# expands to the number of positional parameters */
1301 value = _itoa(__libc_argc - 1, &buffer[20]);
1304 /* Just $ on its own */
1305 *offset = start - 1;
1306 *word = w_addchar(*word, word_length, max_length, '$');
1307 return *word ? 0 : WRDE_NOSPACE;
1310 /* Is it a numeric parameter? */
1311 else if (isdigit(env[0])) {
1314 if (n >= __libc_argc)
1315 /* Substitute NULL. */
1318 /* Replace with appropriate positional parameter. */
1319 value = __libc_argv[n];
1321 /* Is it a special parameter? */
1326 value = _itoa(getpid(), &buffer[20]);
1328 /* Is it `${#*}' or `${#@}'? */
1329 else if ((*env == '*' || *env == '@') && seen_hash) {
1331 value = _itoa(__libc_argc > 0 ? __libc_argc - 1 : 0,
1333 *word = w_addstr(*word, word_length, max_length, value);
1336 return *word ? 0 : WRDE_NOSPACE;
1338 /* Is it `$*' or `$@' (unquoted) ? */
1339 else if (*env == '*' || (*env == '@' && !quoted)) {
1340 size_t plist_len = 0;
1344 /* Build up value parameter by parameter (copy them) */
1345 for (p = 1; __libc_argv[p]; ++p)
1346 plist_len += strlen(__libc_argv[p]) + 1; /* for space */
1347 value = malloc(plist_len);
1352 for (p = 1; __libc_argv[p]; ++p) {
1355 end = stpcpy(end, __libc_argv[p]);
1360 /* Must be a quoted `$@' */
1361 assert(*env == '@' && quoted);
1363 /* Each parameter is a separate word ("$@") */
1364 if (__libc_argc == 2)
1365 value = __libc_argv[1];
1366 else if (__libc_argc > 2) {
1369 /* Append first parameter to current word. */
1370 value = w_addstr(*word, word_length, max_length,
1372 if (value == NULL || w_addword(pwordexp, value))
1375 for (p = 2; __libc_argv[p + 1]; p++) {
1376 char *newword = strdup(__libc_argv[p]);
1378 if (newword == NULL || w_addword(pwordexp, newword))
1382 /* Start a new word with the last parameter. */
1383 *word = w_newword(word_length, max_length);
1384 value = __libc_argv[p];
1392 value = getenv(env);
1394 if (value == NULL && (flags & WRDE_UNDEF)) {
1395 /* Variable not defined. */
1396 error = WRDE_BADVAL;
1400 if (action != ACT_NONE) {
1401 int expand_pattern = 0;
1403 /* First, find out if we need to expand pattern (i.e. if we will
1406 case ACT_RP_SHORT_LEFT:
1407 case ACT_RP_LONG_LEFT:
1408 case ACT_RP_SHORT_RIGHT:
1409 case ACT_RP_LONG_RIGHT:
1410 /* Always expand for these. */
1414 case ACT_NULL_ERROR:
1415 case ACT_NULL_SUBST:
1416 case ACT_NULL_ASSIGN:
1417 if (!value || (!*value && colon_seen))
1418 /* If param is unset, or set but null and a colon has been seen,
1419 the expansion of the pattern will be needed. */
1424 case ACT_NONNULL_SUBST:
1425 /* Expansion of word will be needed if parameter is set and not null,
1426 or set null but no colon has been seen. */
1427 if (value && (*value || !colon_seen))
1433 assert(!"Unrecognised action!");
1436 if (expand_pattern) {
1437 /* We need to perform tilde expansion, parameter expansion,
1438 command substitution, and arithmetic expansion. We also
1439 have to be a bit careful with wildcard characters, as
1440 pattern might be given to fnmatch soon. To do this, we
1441 convert quotes to escapes. */
1447 int quotes = 0; /* 1: single quotes; 2: double */
1449 expanded = w_newword(&exp_len, &exp_maxl);
1450 for (p = pattern; p && *p; p++) {
1457 else if (quotes == 0)
1467 else if (quotes == 0)
1477 /* Convert quoted wildchar to escaped wildchar. */
1478 expanded = w_addchar(expanded, &exp_len,
1481 if (expanded == NULL)
1488 error = parse_dollars(&expanded, &exp_len, &exp_maxl, p,
1489 &_offset, flags, NULL, NULL, NULL, 1);
1503 if (quotes || exp_len)
1507 error = parse_tilde(&expanded, &exp_len, &exp_maxl, p,
1522 expanded = w_addchar(expanded, &exp_len, &exp_maxl, '\\');
1524 assert(*p); /* checked when extracted initially */
1525 if (expanded == NULL)
1529 expanded = w_addchar(expanded, &exp_len, &exp_maxl, *p);
1531 if (expanded == NULL)
1541 case ACT_RP_SHORT_LEFT:
1542 case ACT_RP_LONG_LEFT:
1543 case ACT_RP_SHORT_RIGHT:
1544 case ACT_RP_LONG_RIGHT:
1550 if (value == NULL || pattern == NULL || *pattern == '\0')
1553 end = value + strlen(value);
1556 case ACT_RP_SHORT_LEFT:
1557 for (p = value; p <= end; ++p) {
1560 if (fnmatch(pattern, value, 0) != FNM_NOMATCH) {
1563 char *newval = strdup(p);
1565 if (newval == NULL) {
1580 case ACT_RP_LONG_LEFT:
1581 for (p = end; p >= value; --p) {
1584 if (fnmatch(pattern, value, 0) != FNM_NOMATCH) {
1587 char *newval = strdup(p);
1589 if (newval == NULL) {
1604 case ACT_RP_SHORT_RIGHT:
1605 for (p = end; p >= value; --p) {
1606 if (fnmatch(pattern, p, 0) != FNM_NOMATCH) {
1609 newval = malloc(p - value + 1);
1611 if (newval == NULL) {
1617 *(char *) mempcpy(newval, value, p - value) = '\0';
1628 case ACT_RP_LONG_RIGHT:
1629 for (p = value; p <= end; ++p) {
1630 if (fnmatch(pattern, p, 0) != FNM_NOMATCH) {
1633 newval = malloc(p - value + 1);
1635 if (newval == NULL) {
1641 *(char *) mempcpy(newval, value, p - value) = '\0';
1659 case ACT_NULL_ERROR:
1660 if (value && *value)
1661 /* Substitute parameter */
1665 if (!colon_seen && value)
1666 /* Substitute NULL */
1669 fprintf(stderr, "%s: %s\n", env, pattern);
1671 fprintf(stderr, "%s: parameter null or not set\n", env);
1672 error = WRDE_BADVAL;
1679 case ACT_NULL_SUBST:
1680 if (value && *value)
1681 /* Substitute parameter */
1687 if (!colon_seen && value)
1688 /* Substitute NULL */
1691 value = pattern ? strdup(pattern) : pattern;
1694 if (pattern && !value)
1699 case ACT_NONNULL_SUBST:
1700 if (value && (*value || !colon_seen)) {
1704 value = pattern ? strdup(pattern) : pattern;
1707 if (pattern && !value)
1713 /* Substitute NULL */
1718 case ACT_NULL_ASSIGN:
1719 if (value && *value)
1720 /* Substitute parameter */
1723 if (!colon_seen && value) {
1724 /* Substitute NULL */
1733 value = pattern ? strdup(pattern) : pattern;
1736 if (pattern && !value)
1739 setenv(env, value, 1);
1743 assert(!"Unrecognised action!");
1753 char param_length[21];
1755 param_length[20] = '\0';
1756 *word = w_addstr(*word, word_length, max_length,
1757 _itoa(value ? strlen(value) : 0,
1758 ¶m_length[20]));
1760 assert(value != NULL);
1764 return *word ? 0 : WRDE_NOSPACE;
1770 if (quoted || !pwordexp) {
1771 /* Quoted - no field split */
1772 *word = w_addstr(*word, word_length, max_length, value);
1776 return *word ? 0 : WRDE_NOSPACE;
1778 /* Need to field-split */
1779 char *value_copy = strdup(value); /* Don't modify value */
1780 char *field_begin = value_copy;
1781 int seen_nonws_ifs = 0;
1786 if (value_copy == NULL)
1790 char *field_end = field_begin;
1793 /* If this isn't the first field, start a new word */
1794 if (field_begin != value_copy) {
1795 if (w_addword(pwordexp, *word) == WRDE_NOSPACE) {
1800 *word = w_newword(word_length, max_length);
1803 /* Skip IFS whitespace before the field */
1804 field_begin += strspn(field_begin, ifs_white);
1806 if (!seen_nonws_ifs && *field_begin == 0)
1807 /* Nothing but whitespace */
1810 /* Search for the end of the field */
1811 field_end = field_begin + strcspn(field_begin, ifs);
1813 /* Set up pointer to the character after end of field and
1814 skip whitespace IFS after it. */
1815 next_field = field_end + strspn(field_end, ifs_white);
1817 /* Skip at most one non-whitespace IFS character after the field */
1819 if (*next_field && strchr(ifs, *next_field)) {
1824 /* Null-terminate it */
1827 /* Tag a copy onto the current word */
1828 *word = w_addstr(*word, word_length, max_length, field_begin);
1830 if (*word == NULL && *field_begin != '\0') {
1835 field_begin = next_field;
1837 while (seen_nonws_ifs || *field_begin);
1849 error = WRDE_NOSPACE;
1853 error = WRDE_SYNTAX;
1863 static __inline__ int
1864 parse_backtick(char **word, size_t * word_length, size_t * max_length,
1865 const char *words, size_t * offset, int flags,
1866 wordexp_t * pwordexp, const char *ifs,
1867 const char *ifs_white)
1874 parse_dollars(char **word, size_t * word_length, size_t * max_length,
1875 const char *words, size_t * offset, int flags,
1876 wordexp_t * pwordexp, const char *ifs, const char *ifs_white,
1879 /* We are poised _at_ "$" */
1880 switch (words[1 + *offset]) {
1884 *word = w_addchar(*word, word_length, max_length, '$');
1885 return *word ? 0 : WRDE_NOSPACE;
1887 #ifdef __WORDEXP_FULL
1889 if (words[2 + *offset] == '(') {
1890 /* Differentiate between $((1+3)) and $((echo);(ls)) */
1891 int i = 3 + *offset;
1894 while (words[i] && !(depth == 0 && words[i] == ')')) {
1895 if (words[i] == '(')
1897 else if (words[i] == ')')
1903 if (words[i] == ')' && words[i + 1] == ')') {
1905 /* Call parse_arith -- 0 is for "no brackets" */
1906 return parse_arith(word, word_length, max_length, words,
1911 if (flags & WRDE_NOCMD)
1915 return parse_comm(word, word_length, max_length, words, offset,
1916 flags, quoted ? NULL : pwordexp, ifs, ifs_white);
1920 /* Call parse_arith -- 1 is for "brackets" */
1921 return parse_arith(word, word_length, max_length, words, offset,
1926 ++(*offset); /* parse_param needs to know if "{" is there */
1927 return parse_param(word, word_length, max_length, words, offset,
1928 flags, pwordexp, ifs, ifs_white, quoted);
1931 ++(*offset); /* parse_param needs to know if "{" is there */
1938 parse_dquote(char **word, size_t * word_length, size_t * max_length,
1939 const char *words, size_t * offset, int flags,
1940 wordexp_t * pwordexp, const char *ifs, const char *ifs_white)
1942 /* We are poised just after a double-quote */
1945 for (; words[*offset]; ++(*offset)) {
1946 switch (words[*offset]) {
1951 error = parse_dollars(word, word_length, max_length, words, offset,
1952 flags, pwordexp, ifs, ifs_white, 1);
1953 /* The ``1'' here is to tell parse_dollars not to
1954 * split the fields. It may need to, however ("$@").
1962 if (flags & WRDE_NOCMD)
1966 error = parse_backtick(word, word_length, max_length, words,
1967 offset, flags, NULL, NULL, NULL);
1968 /* The first NULL here is to tell parse_backtick not to
1977 error = parse_qtd_backslash(word, word_length, max_length, words,
1986 *word = w_addchar(*word, word_length, max_length, words[*offset]);
1988 return WRDE_NOSPACE;
1992 /* Unterminated string */
1997 * wordfree() is to be called after pwordexp is finished with.
2000 void wordfree(wordexp_t * pwordexp)
2003 /* wordexp can set pwordexp to NULL */
2004 if (pwordexp && pwordexp->we_wordv) {
2005 char **wordv = pwordexp->we_wordv;
2007 for (wordv += pwordexp->we_offs; *wordv; ++wordv)
2010 free(pwordexp->we_wordv);
2011 pwordexp->we_wordv = NULL;
2014 libc_hidden_def(wordfree)
2020 int wordexp(const char *words, wordexp_t * we, int flags)
2022 size_t words_offset;
2025 char *word = w_newword(&word_length, &max_length);
2029 wordexp_t old_word = *we;
2031 if (flags & WRDE_REUSE) {
2032 /* Minimal implementation of WRDE_REUSE for now */
2034 old_word.we_wordv = NULL;
2037 if ((flags & WRDE_APPEND) == 0) {
2040 if (flags & WRDE_DOOFFS) {
2041 we->we_wordv = calloc(1 + we->we_offs, sizeof(char *));
2042 if (we->we_wordv == NULL) {
2043 error = WRDE_NOSPACE;
2047 we->we_wordv = calloc(1, sizeof(char *));
2048 if (we->we_wordv == NULL) {
2049 error = WRDE_NOSPACE;
2057 /* Find out what the field separators are.
2058 * There are two types: whitespace and non-whitespace.
2060 ifs = getenv("IFS");
2063 /* IFS unset - use <space><tab><newline>. */
2064 ifs = strcpy(ifs_white, " \t\n");
2067 char *whch = ifs_white;
2069 /* Start off with no whitespace IFS characters */
2070 ifs_white[0] = '\0';
2072 while (*ifsch != '\0') {
2073 if ((*ifsch == ' ') || (*ifsch == '\t') || (*ifsch == '\n')) {
2074 /* Whitespace IFS. See first whether it is already in our
2076 char *runp = ifs_white;
2078 while (runp < whch && *runp != '\0' && *runp != *ifsch)
2090 for (words_offset = 0; words[words_offset]; ++words_offset)
2091 switch (words[words_offset]) {
2093 error = parse_backslash(&word, &word_length, &max_length, words,
2102 error = parse_dollars(&word, &word_length, &max_length, words,
2103 &words_offset, flags, we, ifs, ifs_white,
2112 if (flags & WRDE_NOCMD) {
2113 error = WRDE_CMDSUB;
2118 error = parse_backtick(&word, &word_length, &max_length, words,
2119 &words_offset, flags, we, ifs,
2129 error = parse_dquote(&word, &word_length, &max_length, words,
2130 &words_offset, flags, we, ifs, ifs_white);
2136 error = w_addword(we, NULL);
2146 error = parse_squote(&word, &word_length, &max_length, words,
2153 error = w_addword(we, NULL);
2162 error = parse_tilde(&word, &word_length, &max_length, words,
2163 &words_offset, we->we_wordc);
2173 error = parse_glob(&word, &word_length, &max_length, words,
2174 &words_offset, flags, we, ifs, ifs_white);
2182 /* Is it a word separator? */
2183 if (strchr(" \t", words[words_offset]) == NULL) {
2184 char ch = words[words_offset];
2186 /* Not a word separator -- but is it a valid word char? */
2187 if (strchr("\n|&;<>(){}", ch)) {
2189 error = WRDE_BADCHAR;
2193 /* "Ordinary" character -- add it to word */
2194 word = w_addchar(word, &word_length, &max_length, ch);
2196 error = WRDE_NOSPACE;
2203 /* If a word has been delimited, add it to the list. */
2205 error = w_addword(we, word);
2210 word = w_newword(&word_length, &max_length);
2215 /* There was a word separator at the end */
2216 if (word == NULL) /* i.e. w_newword */
2219 /* There was no field separator at the end */
2220 return w_addword(we, word);
2224 * free memory used (unless error is WRDE_NOSPACE), and
2225 * set we members back to what they were.
2230 if (error == WRDE_NOSPACE)
2231 return WRDE_NOSPACE;
2233 if ((flags & WRDE_APPEND) == 0)