1 /* POSIX.2 wordexp implementation.
2 Copyright (C) 1997-2003,2005,2006,2008,2011 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, write to the Free
18 Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
34 #include <sys/param.h>
37 #include <sys/types.h>
38 #include <sys/types.h>
43 #include <kernel-features.h>
45 #include <bits/libc-lock.h>
46 #include <stdio-common/_itoa.h>
48 /* Undefine the following line for the production version. */
49 /* #define NDEBUG 1 */
52 /* Get some device information. */
53 #include <device-nrs.h>
56 * This is a recursive-descent-style word expansion routine.
59 /* These variables are defined and initialized in the startup code. */
60 extern int __libc_argc attribute_hidden;
61 extern char **__libc_argv attribute_hidden;
63 /* Some forward declarations */
64 static int parse_dollars (char **word, size_t *word_length, size_t *max_length,
65 const char *words, size_t *offset, int flags,
66 wordexp_t *pwordexp, const char *ifs,
67 const char *ifs_white, int quoted)
69 static int parse_backtick (char **word, size_t *word_length,
70 size_t *max_length, const char *words,
71 size_t *offset, int flags, wordexp_t *pwordexp,
72 const char *ifs, const char *ifs_white)
74 static int parse_dquote (char **word, size_t *word_length, size_t *max_length,
75 const char *words, size_t *offset, int flags,
76 wordexp_t *pwordexp, const char *ifs,
77 const char *ifs_white)
79 static int eval_expr (char *expr, long int *result) internal_function;
81 /* The w_*() functions manipulate word lists. */
85 /* Result of w_newword will be ignored if it's the last word. */
87 w_newword (size_t *actlen, size_t *maxlen)
89 *actlen = *maxlen = 0;
94 w_addchar (char *buffer, size_t *actlen, size_t *maxlen, char ch)
95 /* (lengths exclude trailing zero) */
97 /* Add a character to the buffer, allocating room for it if needed. */
99 if (*actlen == *maxlen)
101 char *old_buffer = buffer;
102 assert (buffer == NULL || *maxlen != 0);
104 buffer = (char *) realloc (buffer, 1 + *maxlen);
112 buffer[*actlen] = ch;
113 buffer[++(*actlen)] = '\0';
121 w_addmem (char *buffer, size_t *actlen, size_t *maxlen, const char *str,
124 /* Add a string to the buffer, allocating room for it if needed.
126 if (*actlen + len > *maxlen)
128 char *old_buffer = buffer;
129 assert (buffer == NULL || *maxlen != 0);
130 *maxlen += MAX (2 * len, W_CHUNK);
131 buffer = realloc (old_buffer, 1 + *maxlen);
139 *((char *) __mempcpy (&buffer[*actlen], str, len)) = '\0';
148 w_addstr (char *buffer, size_t *actlen, size_t *maxlen, const char *str)
149 /* (lengths exclude trailing zero) */
151 /* Add a string to the buffer, allocating room for it if needed.
155 assert (str != NULL); /* w_addstr only called from this file */
158 return w_addmem (buffer, actlen, maxlen, str, len);
163 w_addword (wordexp_t *pwordexp, char *word)
165 /* Add a word to the wordlist */
168 bool allocated = false;
170 /* Internally, NULL acts like "". Convert NULLs to "" before
171 * the caller sees them.
175 word = __strdup ("");
181 num_p = 2 + pwordexp->we_wordc + pwordexp->we_offs;
182 new_wordv = realloc (pwordexp->we_wordv, sizeof (char *) * num_p);
183 if (new_wordv != NULL)
185 pwordexp->we_wordv = new_wordv;
186 pwordexp->we_wordv[pwordexp->we_offs + pwordexp->we_wordc++] = word;
187 pwordexp->we_wordv[pwordexp->we_offs + pwordexp->we_wordc] = NULL;
198 /* The parse_*() functions should leave *offset being the offset in 'words'
199 * to the last character processed.
204 parse_backslash (char **word, size_t *word_length, size_t *max_length,
205 const char *words, size_t *offset)
207 /* We are poised _at_ a backslash, not in quotes */
209 switch (words[1 + *offset])
212 /* Backslash is last character of input words */
220 *word = w_addchar (*word, word_length, max_length, words[1 + *offset]);
233 parse_qtd_backslash (char **word, size_t *word_length, size_t *max_length,
234 const char *words, size_t *offset)
236 /* We are poised _at_ a backslash, inside quotes */
238 switch (words[1 + *offset])
241 /* Backslash is last character of input words */
252 *word = w_addchar (*word, word_length, max_length, words[1 + *offset]);
260 *word = w_addchar (*word, word_length, max_length, words[*offset]);
262 *word = w_addchar (*word, word_length, max_length, words[1 + *offset]);
276 parse_tilde (char **word, size_t *word_length, size_t *max_length,
277 const char *words, size_t *offset, size_t wordc)
279 /* We are poised _at_ a tilde */
282 if (*word_length != 0)
284 if (!((*word)[*word_length - 1] == '=' && wordc == 0))
286 if (!((*word)[*word_length - 1] == ':'
287 && strchr (*word, '=') && wordc == 0))
289 *word = w_addchar (*word, word_length, max_length, '~');
290 return *word ? 0 : WRDE_NOSPACE;
295 for (i = 1 + *offset; words[i]; i++)
297 if (words[i] == ':' || words[i] == '/' || words[i] == ' ' ||
298 words[i] == '\t' || words[i] == 0 )
301 if (words[i] == '\\')
303 *word = w_addchar (*word, word_length, max_length, '~');
304 return *word ? 0 : WRDE_NOSPACE;
308 if (i == 1 + *offset)
310 /* Tilde appears on its own */
312 struct passwd pwd, *tpwd;
318 /* POSIX.2 says ~ expands to $HOME and if HOME is unset the
319 results are unspecified. We do a lookup on the uid if
322 home = getenv ("HOME");
325 *word = w_addstr (*word, word_length, max_length, home);
332 buffer = __alloca (buflen);
334 while ((result = __getpwuid_r (uid, &pwd, buffer, buflen, &tpwd)) != 0
336 buffer = extend_alloca (buffer, buflen, buflen + 1000);
338 if (result == 0 && tpwd != NULL && pwd.pw_dir != NULL)
340 *word = w_addstr (*word, word_length, max_length, pwd.pw_dir);
346 *word = w_addchar (*word, word_length, max_length, '~');
354 /* Look up user name in database to get home directory */
355 char *user = strndupa (&words[1 + *offset], i - (1 + *offset));
356 struct passwd pwd, *tpwd;
358 char* buffer = __alloca (buflen);
361 while ((result = __getpwnam_r (user, &pwd, buffer, buflen, &tpwd)) != 0
363 buffer = extend_alloca (buffer, buflen, buflen + 1000);
365 if (result == 0 && tpwd != NULL && pwd.pw_dir)
366 *word = w_addstr (*word, word_length, max_length, pwd.pw_dir);
369 /* (invalid login name) */
370 *word = w_addchar (*word, word_length, max_length, '~');
372 *word = w_addstr (*word, word_length, max_length, user);
377 return *word ? 0 : WRDE_NOSPACE;
383 do_parse_glob (const char *glob_word, char **word, size_t *word_length,
384 size_t *max_length, wordexp_t *pwordexp, const char *ifs,
385 const char *ifs_white)
391 error = glob (glob_word, GLOB_NOCHECK, NULL, &globbuf);
395 /* We can only run into memory problems. */
396 assert (error == GLOB_NOSPACE);
402 /* No field splitting allowed. */
403 assert (globbuf.gl_pathv[0] != NULL);
404 *word = w_addstr (*word, word_length, max_length, globbuf.gl_pathv[0]);
405 for (match = 1; match < globbuf.gl_pathc && *word != NULL; ++match)
407 *word = w_addchar (*word, word_length, max_length, ' ');
409 *word = w_addstr (*word, word_length, max_length,
410 globbuf.gl_pathv[match]);
414 return *word ? 0 : WRDE_NOSPACE;
417 assert (ifs == NULL || *ifs != '\0');
421 *word = w_newword (word_length, max_length);
424 for (match = 0; match < globbuf.gl_pathc; ++match)
426 char *matching_word = __strdup (globbuf.gl_pathv[match]);
427 if (matching_word == NULL || w_addword (pwordexp, matching_word))
440 parse_glob (char **word, size_t *word_length, size_t *max_length,
441 const char *words, size_t *offset, int flags,
442 wordexp_t *pwordexp, const char *ifs, const char *ifs_white)
444 /* We are poised just after a '*', a '[' or a '?'. */
445 int error = WRDE_NOSPACE;
446 int quoted = 0; /* 1 if singly-quoted, 2 if doubly */
448 wordexp_t glob_list; /* List of words to glob */
450 glob_list.we_wordc = 0;
451 glob_list.we_wordv = NULL;
452 glob_list.we_offs = 0;
453 for (; words[*offset] != '\0'; ++*offset)
455 if (strchr (ifs, words[*offset]) != NULL)
459 /* Sort out quoting */
460 if (words[*offset] == '\'')
467 else if (quoted == 1)
473 else if (words[*offset] == '"')
480 else if (quoted == 2)
487 /* Sort out other special characters */
488 if (quoted != 1 && words[*offset] == '$')
490 error = parse_dollars (word, word_length, max_length, words,
491 offset, flags, &glob_list, ifs, ifs_white,
498 else if (words[*offset] == '\\')
501 error = parse_qtd_backslash (word, word_length, max_length,
504 error = parse_backslash (word, word_length, max_length,
513 *word = w_addchar (*word, word_length, max_length, words[*offset]);
518 /* Don't forget to re-parse the character we stopped at. */
522 error = w_addword (&glob_list, *word);
523 *word = w_newword (word_length, max_length);
524 for (i = 0; error == 0 && i < glob_list.we_wordc; i++)
525 error = do_parse_glob (glob_list.we_wordv[i], word, word_length,
526 max_length, pwordexp, ifs, ifs_white);
530 wordfree (&glob_list);
536 parse_squote (char **word, size_t *word_length, size_t *max_length,
537 const char *words, size_t *offset)
539 /* We are poised just after a single quote */
540 for (; words[*offset]; ++(*offset))
542 if (words[*offset] != '\'')
544 *word = w_addchar (*word, word_length, max_length, words[*offset]);
551 /* Unterminated string */
555 /* Functions to evaluate an arithmetic expression */
558 eval_expr_val (char **expr, long int *result)
562 /* Skip white space */
563 for (digit = *expr; digit && *digit && isspace (*digit); ++digit);
567 /* Scan for closing paren */
568 for (++digit; **expr && **expr != ')'; ++(*expr));
576 if (eval_expr (digit, result))
582 /* POSIX requires that decimal, octal, and hexadecimal constants are
583 recognized. Therefore we pass 0 as the third parameter to strtol. */
584 *result = strtol (digit, expr, 0);
593 eval_expr_multdiv (char **expr, long int *result)
598 if (eval_expr_val (expr, result) != 0)
603 /* Skip white space */
604 for (; *expr && **expr && isspace (**expr); ++(*expr));
609 if (eval_expr_val (expr, &arg) != 0)
614 else if (**expr == '/')
617 if (eval_expr_val (expr, &arg) != 0)
630 eval_expr (char *expr, long int *result)
635 if (eval_expr_multdiv (&expr, result) != 0)
640 /* Skip white space */
641 for (; expr && *expr && isspace (*expr); ++expr);
646 if (eval_expr_multdiv (&expr, &arg) != 0)
651 else if (*expr == '-')
654 if (eval_expr_multdiv (&expr, &arg) != 0)
667 parse_arith (char **word, size_t *word_length, size_t *max_length,
668 const char *words, size_t *offset, int flags, int bracket)
670 /* We are poised just after "$((" or "$[" */
677 expr = w_newword (&expr_length, &expr_maxlen);
678 for (; words[*offset]; ++(*offset))
680 switch (words[*offset])
683 error = parse_dollars (&expr, &expr_length, &expr_maxlen,
684 words, offset, flags, NULL, NULL, NULL, 1);
685 /* The ``1'' here is to tell parse_dollars not to
697 error = parse_backtick (&expr, &expr_length, &expr_maxlen,
698 words, offset, flags, NULL, NULL, NULL);
699 /* The first NULL here is to tell parse_backtick not to
710 error = parse_qtd_backslash (&expr, &expr_length, &expr_maxlen,
717 /* I think that a backslash within an
718 * arithmetic expansion is bound to
719 * cause an error sooner or later anyway though.
724 if (--paren_depth == 0)
726 char result[21]; /* 21 = ceil(log10(2^64)) + 1 */
727 long int numresult = 0;
728 long long int convertme;
730 if (bracket || words[1 + *offset] != ')')
739 if (*expr && eval_expr (expr, &numresult) != 0)
747 convertme = -numresult;
748 *word = w_addchar (*word, word_length, max_length, '-');
756 convertme = numresult;
759 *word = w_addstr (*word, word_length, max_length,
760 _itoa (convertme, &result[20], 10, 0));
762 return *word ? 0 : WRDE_NOSPACE;
764 expr = w_addchar (expr, &expr_length, &expr_maxlen, words[*offset]);
771 if (bracket && paren_depth == 1)
773 char result[21]; /* 21 = ceil(log10(2^64)) + 1 */
774 long int numresult = 0;
777 if (*expr && eval_expr (expr, &numresult) != 0)
784 *word = w_addstr (*word, word_length, max_length,
785 _itoa_word (numresult, &result[20], 10, 0));
787 return *word ? 0 : WRDE_NOSPACE;
803 expr = w_addchar (expr, &expr_length, &expr_maxlen, words[*offset]);
814 /* Function called by child process in exec_comm() */
816 internal_function __attribute__ ((always_inline))
817 exec_comm_child (char *comm, int *fildes, int showerr, int noexec)
819 const char *args[4] = { _PATH_BSHELL, "-c", comm, NULL };
821 /* Execute the command, or just check syntax? */
825 /* Redirect output. */
826 if (__builtin_expect (fildes[1] != STDOUT_FILENO, 1))
828 __dup2 (fildes[1], STDOUT_FILENO);
834 /* Reset the close-on-exec flag (if necessary). */
835 # ifndef __ASSUME_PIPE2
836 if (__have_pipe2 > 0)
838 __fcntl (fildes[1], F_SETFD, 0);
842 /* Redirect stderr to /dev/null if we have to. */
847 __close (STDERR_FILENO);
848 fd = __open (_PATH_DEVNULL, O_WRONLY);
849 if (fd >= 0 && fd != STDERR_FILENO)
851 __dup2 (fd, STDERR_FILENO);
854 /* Be paranoid. Check that we actually opened the /dev/null
856 if (__builtin_expect (__fxstat64 (_STAT_VER, STDERR_FILENO, &st), 0) != 0
857 || __builtin_expect (S_ISCHR (st.st_mode), 1) == 0
858 #if defined DEV_NULL_MAJOR && defined DEV_NULL_MINOR
859 || st.st_rdev != makedev (DEV_NULL_MAJOR, DEV_NULL_MINOR)
862 /* It's not the /dev/null device. Stop right here. The
863 problem is: how do we stop? We use _exit() with an
864 hopefully unusual exit code. */
868 /* Make sure the subshell doesn't field-split on our behalf. */
872 __execve (_PATH_BSHELL, (char *const *) args, __environ);
878 /* Function to execute a command and retrieve the results */
879 /* pwordexp contains NULL if field-splitting is forbidden */
882 exec_comm (char *comm, char **word, size_t *word_length, size_t *max_length,
883 int flags, wordexp_t *pwordexp, const char *ifs,
884 const char *ifs_white)
891 size_t maxnewlines = 0;
892 char buffer[bufsize];
896 /* Don't fork() unless necessary */
901 # ifndef __ASSUME_PIPE2
902 if (__have_pipe2 >= 0)
905 int r = __pipe2 (fildes, O_CLOEXEC);
906 # ifndef __ASSUME_PIPE2
907 if (__have_pipe2 == 0)
908 __have_pipe2 = r != -1 || errno != ENOSYS ? 1 : -1;
910 if (__have_pipe2 > 0)
917 #ifndef __ASSUME_PIPE2
919 if (__have_pipe2 < 0)
921 if (__pipe (fildes) < 0)
927 if ((pid = __fork ()) < 0)
936 exec_comm_child (comm, fildes, noexec ? 0 : flags & WRDE_SHOWERR, noexec);
940 /* If we are just testing the syntax, only wait. */
942 return (TEMP_FAILURE_RETRY (__waitpid (pid, &status, 0)) == pid
943 && status != 0) ? WRDE_SYNTAX : 0;
949 /* Quoted - no field splitting */
953 if ((buflen = TEMP_FAILURE_RETRY (__read (fildes[0], buffer,
956 if (TEMP_FAILURE_RETRY (__waitpid (pid, &status, WNOHANG)) == 0)
958 if ((buflen = TEMP_FAILURE_RETRY (__read (fildes[0], buffer,
963 maxnewlines += buflen;
965 *word = w_addmem (*word, word_length, max_length, buffer, buflen);
971 /* Not quoted - split fields */
975 * 0 when searching for first character in a field not IFS white space
976 * 1 when copying the text of a field
977 * 2 when searching for possible non-whitespace IFS
978 * 3 when searching for non-newline after copying field
983 if ((buflen = TEMP_FAILURE_RETRY (__read (fildes[0], buffer,
986 if (TEMP_FAILURE_RETRY (__waitpid (pid, &status, WNOHANG)) == 0)
988 if ((buflen = TEMP_FAILURE_RETRY (__read (fildes[0], buffer,
993 for (i = 0; i < buflen; ++i)
995 if (strchr (ifs, buffer[i]) != NULL)
997 /* Current character is IFS */
998 if (strchr (ifs_white, buffer[i]) == NULL)
1000 /* Current character is IFS but not whitespace */
1003 /* current character
1006 * eg: text<space><comma><space>moretext
1008 * So, strip whitespace IFS (like at the start)
1015 /* fall through and delimit field.. */
1019 if (buffer[i] == '\n')
1021 /* Current character is (IFS) newline */
1023 /* If copying a field, this is the end of it,
1024 but maybe all that's left is trailing newlines.
1025 So start searching for a non-newline. */
1033 /* Current character is IFS white space, but
1036 /* If not either copying a field or searching
1037 for non-newline after a field, ignore it */
1038 if (copying != 1 && copying != 3)
1041 /* End of field (search for non-ws IFS afterwards) */
1046 /* First IFS white space (non-newline), or IFS non-whitespace.
1047 * Delimit the field. Nulls are converted by w_addword. */
1048 if (w_addword (pwordexp, *word) == WRDE_NOSPACE)
1051 *word = w_newword (word_length, max_length);
1054 /* fall back round the loop.. */
1058 /* Not IFS character */
1062 /* Nothing but (IFS) newlines since the last field,
1063 so delimit it here before starting new word */
1064 if (w_addword (pwordexp, *word) == WRDE_NOSPACE)
1067 *word = w_newword (word_length, max_length);
1072 if (buffer[i] == '\n') /* happens if newline not in IFS */
1077 *word = w_addchar (*word, word_length, max_length,
1086 /* Chop off trailing newlines (required by POSIX.2) */
1087 /* Ensure we don't go back further than the beginning of the
1088 substitution (i.e. remove maxnewlines bytes at most) */
1089 while (maxnewlines-- != 0 &&
1090 *word_length > 0 && (*word)[*word_length - 1] == '\n')
1092 (*word)[--*word_length] = '\0';
1094 /* If the last word was entirely newlines, turn it into a new word
1095 * which can be ignored if there's nothing following it. */
1096 if (*word_length == 0)
1099 *word = w_newword (word_length, max_length);
1104 __close (fildes[0]);
1107 /* Check for syntax error (re-execute but with "-n" flag) */
1108 if (buflen < 1 && status != 0)
1117 __kill (pid, SIGKILL);
1118 TEMP_FAILURE_RETRY (__waitpid (pid, NULL, 0));
1119 __close (fildes[0]);
1120 return WRDE_NOSPACE;
1125 parse_comm (char **word, size_t *word_length, size_t *max_length,
1126 const char *words, size_t *offset, int flags, wordexp_t *pwordexp,
1127 const char *ifs, const char *ifs_white)
1129 /* We are poised just after "$(" */
1130 int paren_depth = 1;
1132 int quoted = 0; /* 1 for singly-quoted, 2 for doubly-quoted */
1135 char *comm = w_newword (&comm_length, &comm_maxlen);
1137 for (; words[*offset]; ++(*offset))
1139 switch (words[*offset])
1144 else if (quoted == 1)
1152 else if (quoted == 2)
1158 if (!quoted && --paren_depth == 0)
1160 /* Go -- give script to the shell */
1163 #ifdef __libc_ptf_call
1164 /* We do not want the exec_comm call to be cut short
1165 by a thread cancellation since cleanup is very
1166 ugly. Therefore disable cancellation for
1168 // XXX Ideally we do want the thread being cancelable.
1169 // XXX If demand is there we'll change it.
1170 int state = PTHREAD_CANCEL_ENABLE;
1171 __libc_ptf_call (pthread_setcancelstate,
1172 (PTHREAD_CANCEL_DISABLE, &state), 0);
1175 error = exec_comm (comm, word, word_length, max_length,
1176 flags, pwordexp, ifs, ifs_white);
1178 #ifdef __libc_ptf_call
1179 __libc_ptf_call (pthread_setcancelstate, (state, NULL), 0);
1188 /* This is just part of the script */
1196 comm = w_addchar (comm, &comm_length, &comm_maxlen, words[*offset]);
1198 return WRDE_NOSPACE;
1201 /* Premature end. */
1209 parse_param (char **word, size_t *word_length, size_t *max_length,
1210 const char *words, size_t *offset, int flags, wordexp_t *pwordexp,
1211 const char *ifs, const char *ifs_white, int quoted)
1213 /* We are poised just after "$" */
1217 ACT_RP_SHORT_LEFT = '#',
1218 ACT_RP_LONG_LEFT = 'L',
1219 ACT_RP_SHORT_RIGHT = '%',
1220 ACT_RP_LONG_RIGHT = 'R',
1221 ACT_NULL_ERROR = '?',
1222 ACT_NULL_SUBST = '-',
1223 ACT_NONNULL_SUBST = '+',
1224 ACT_NULL_ASSIGN = '='
1230 size_t start = *offset;
1234 enum action action = ACT_NONE;
1239 int pattern_is_quoted = 0; /* 1 for singly-quoted, 2 for doubly-quoted */
1243 int brace = words[*offset] == '{';
1245 env = w_newword (&env_length, &env_maxlen);
1246 pattern = w_newword (&pat_length, &pat_maxlen);
1251 /* First collect the parameter name. */
1253 if (words[*offset] == '#')
1261 if (isalpha (words[*offset]) || words[*offset] == '_')
1263 /* Normal parameter name. */
1266 env = w_addchar (env, &env_length, &env_maxlen,
1271 while (isalnum (words[++*offset]) || words[*offset] == '_');
1273 else if (isdigit (words[*offset]))
1275 /* Numeric parameter name. */
1279 env = w_addchar (env, &env_length, &env_maxlen,
1286 while (isdigit(words[++*offset]));
1288 else if (strchr ("*@$", words[*offset]) != NULL)
1290 /* Special parameter. */
1292 env = w_addchar (env, &env_length, &env_maxlen,
1306 /* Check for special action to be applied to the value. */
1307 switch (words[*offset])
1314 action = ACT_RP_SHORT_LEFT;
1315 if (words[1 + *offset] == '#')
1318 action = ACT_RP_LONG_LEFT;
1323 action = ACT_RP_SHORT_RIGHT;
1324 if (words[1 + *offset] == '%')
1327 action = ACT_RP_LONG_RIGHT;
1332 if (strchr ("-=?+", words[1 + *offset]) == NULL)
1336 action = words[++*offset];
1343 action = words[*offset];
1350 /* Now collect the pattern, but don't expand it yet. */
1352 for (; words[*offset]; ++(*offset))
1354 switch (words[*offset])
1357 if (!pattern_is_quoted)
1362 if (!pattern_is_quoted)
1371 if (pattern_is_quoted)
1372 /* Quoted; treat as normal character. */
1375 /* Otherwise, it's an escape: next character is literal. */
1376 if (words[++*offset] == '\0')
1379 pattern = w_addchar (pattern, &pat_length, &pat_maxlen, '\\');
1380 if (pattern == NULL)
1386 if (pattern_is_quoted == 0)
1387 pattern_is_quoted = 1;
1388 else if (pattern_is_quoted == 1)
1389 pattern_is_quoted = 0;
1394 if (pattern_is_quoted == 0)
1395 pattern_is_quoted = 2;
1396 else if (pattern_is_quoted == 2)
1397 pattern_is_quoted = 0;
1402 pattern = w_addchar (pattern, &pat_length, &pat_maxlen,
1404 if (pattern == NULL)
1409 /* End of input string -- remember to reparse the character that we
1414 if (words[start] == '{' && words[*offset] != '}')
1421 /* $# expands to the number of positional parameters */
1423 value = _itoa_word (__libc_argc - 1, &buffer[20], 10, 0);
1428 /* Just $ on its own */
1429 *offset = start - 1;
1430 *word = w_addchar (*word, word_length, max_length, '$');
1431 return *word ? 0 : WRDE_NOSPACE;
1434 /* Is it a numeric parameter? */
1435 else if (isdigit (env[0]))
1439 if (n >= __libc_argc)
1440 /* Substitute NULL. */
1443 /* Replace with appropriate positional parameter. */
1444 value = __libc_argv[n];
1446 /* Is it a special parameter? */
1453 value = _itoa_word (__getpid (), &buffer[20], 10, 0);
1455 /* Is it `${#*}' or `${#@}'? */
1456 else if ((*env == '*' || *env == '@') && seen_hash)
1459 value = _itoa_word (__libc_argc > 0 ? __libc_argc - 1 : 0,
1460 &buffer[20], 10, 0);
1461 *word = w_addstr (*word, word_length, max_length, value);
1464 return *word ? 0 : WRDE_NOSPACE;
1466 /* Is it `$*' or `$@' (unquoted) ? */
1467 else if (*env == '*' || (*env == '@' && !quoted))
1469 size_t plist_len = 0;
1473 /* Build up value parameter by parameter (copy them) */
1474 for (p = 1; __libc_argv[p]; ++p)
1475 plist_len += strlen (__libc_argv[p]) + 1; /* for space */
1476 value = malloc (plist_len);
1481 for (p = 1; __libc_argv[p]; ++p)
1485 end = __stpcpy (end, __libc_argv[p]);
1492 /* Must be a quoted `$@' */
1493 assert (*env == '@' && quoted);
1495 /* Each parameter is a separate word ("$@") */
1496 if (__libc_argc == 2)
1497 value = __libc_argv[1];
1498 else if (__libc_argc > 2)
1502 /* Append first parameter to current word. */
1503 value = w_addstr (*word, word_length, max_length,
1505 if (value == NULL || w_addword (pwordexp, value))
1508 for (p = 2; __libc_argv[p + 1]; p++)
1510 char *newword = __strdup (__libc_argv[p]);
1511 if (newword == NULL || w_addword (pwordexp, newword))
1515 /* Start a new word with the last parameter. */
1516 *word = w_newword (word_length, max_length);
1517 value = __libc_argv[p];
1528 value = getenv (env);
1530 if (value == NULL && (flags & WRDE_UNDEF))
1532 /* Variable not defined. */
1533 error = WRDE_BADVAL;
1537 if (action != ACT_NONE)
1539 int expand_pattern = 0;
1541 /* First, find out if we need to expand pattern (i.e. if we will
1545 case ACT_RP_SHORT_LEFT:
1546 case ACT_RP_LONG_LEFT:
1547 case ACT_RP_SHORT_RIGHT:
1548 case ACT_RP_LONG_RIGHT:
1549 /* Always expand for these. */
1553 case ACT_NULL_ERROR:
1554 case ACT_NULL_SUBST:
1555 case ACT_NULL_ASSIGN:
1556 if (!value || (!*value && colon_seen))
1557 /* If param is unset, or set but null and a colon has been seen,
1558 the expansion of the pattern will be needed. */
1563 case ACT_NONNULL_SUBST:
1564 /* Expansion of word will be needed if parameter is set and not null,
1565 or set null but no colon has been seen. */
1566 if (value && (*value || !colon_seen))
1572 assert (! "Unrecognised action!");
1577 /* We need to perform tilde expansion, parameter expansion,
1578 command substitution, and arithmetic expansion. We also
1579 have to be a bit careful with wildcard characters, as
1580 pattern might be given to fnmatch soon. To do this, we
1581 convert quotes to escapes. */
1587 int quoted = 0; /* 1: single quotes; 2: double */
1589 expanded = w_newword (&exp_len, &exp_maxl);
1590 for (p = pattern; p && *p; p++)
1599 else if (quoted == 0)
1608 else if (quoted == 0)
1618 /* Convert quoted wildchar to escaped wildchar. */
1619 expanded = w_addchar (expanded, &exp_len,
1622 if (expanded == NULL)
1629 error = parse_dollars (&expanded, &exp_len, &exp_maxl, p,
1630 &offset, flags, NULL, NULL, NULL, 1);
1645 if (quoted || exp_len)
1649 error = parse_tilde (&expanded, &exp_len, &exp_maxl, p,
1665 expanded = w_addchar (expanded, &exp_len, &exp_maxl, '\\');
1667 assert (*p); /* checked when extracted initially */
1668 if (expanded == NULL)
1672 expanded = w_addchar (expanded, &exp_len, &exp_maxl, *p);
1674 if (expanded == NULL)
1685 case ACT_RP_SHORT_LEFT:
1686 case ACT_RP_LONG_LEFT:
1687 case ACT_RP_SHORT_RIGHT:
1688 case ACT_RP_LONG_RIGHT:
1694 if (value == NULL || pattern == NULL || *pattern == '\0')
1697 end = value + strlen (value);
1701 case ACT_RP_SHORT_LEFT:
1702 for (p = value; p <= end; ++p)
1706 if (fnmatch (pattern, value, 0) != FNM_NOMATCH)
1711 char *newval = __strdup (p);
1729 case ACT_RP_LONG_LEFT:
1730 for (p = end; p >= value; --p)
1734 if (fnmatch (pattern, value, 0) != FNM_NOMATCH)
1739 char *newval = __strdup (p);
1757 case ACT_RP_SHORT_RIGHT:
1758 for (p = end; p >= value; --p)
1760 if (fnmatch (pattern, p, 0) != FNM_NOMATCH)
1763 newval = malloc (p - value + 1);
1772 *(char *) __mempcpy (newval, value, p - value) = '\0';
1783 case ACT_RP_LONG_RIGHT:
1784 for (p = value; p <= end; ++p)
1786 if (fnmatch (pattern, p, 0) != FNM_NOMATCH)
1789 newval = malloc (p - value + 1);
1798 *(char *) __mempcpy (newval, value, p - value) = '\0';
1816 case ACT_NULL_ERROR:
1817 if (value && *value)
1818 /* Substitute parameter */
1822 if (!colon_seen && value)
1823 /* Substitute NULL */
1827 const char *str = pattern;
1830 str = _("parameter null or not set");
1832 __fxprintf (NULL, "%s: %s\n", env, str);
1839 case ACT_NULL_SUBST:
1840 if (value && *value)
1841 /* Substitute parameter */
1847 if (!colon_seen && value)
1848 /* Substitute NULL */
1851 value = pattern ? __strdup (pattern) : pattern;
1854 if (pattern && !value)
1859 case ACT_NONNULL_SUBST:
1860 if (value && (*value || !colon_seen))
1865 value = pattern ? __strdup (pattern) : pattern;
1868 if (pattern && !value)
1874 /* Substitute NULL */
1879 case ACT_NULL_ASSIGN:
1880 if (value && *value)
1881 /* Substitute parameter */
1884 if (!colon_seen && value)
1886 /* Substitute NULL */
1895 value = pattern ? __strdup (pattern) : pattern;
1898 if (pattern && !value)
1901 __setenv (env, value, 1);
1905 assert (! "Unrecognised action!");
1916 char param_length[21];
1917 param_length[20] = '\0';
1918 *word = w_addstr (*word, word_length, max_length,
1919 _itoa_word (value ? strlen (value) : 0,
1920 ¶m_length[20], 10, 0));
1923 assert (value != NULL);
1927 return *word ? 0 : WRDE_NOSPACE;
1933 if (quoted || !pwordexp)
1935 /* Quoted - no field split */
1936 *word = w_addstr (*word, word_length, max_length, value);
1940 return *word ? 0 : WRDE_NOSPACE;
1944 /* Need to field-split */
1945 char *value_copy = __strdup (value); /* Don't modify value */
1946 char *field_begin = value_copy;
1947 int seen_nonws_ifs = 0;
1952 if (value_copy == NULL)
1957 char *field_end = field_begin;
1960 /* If this isn't the first field, start a new word */
1961 if (field_begin != value_copy)
1963 if (w_addword (pwordexp, *word) == WRDE_NOSPACE)
1969 *word = w_newword (word_length, max_length);
1972 /* Skip IFS whitespace before the field */
1973 field_begin += strspn (field_begin, ifs_white);
1975 if (!seen_nonws_ifs && *field_begin == 0)
1976 /* Nothing but whitespace */
1979 /* Search for the end of the field */
1980 field_end = field_begin + strcspn (field_begin, ifs);
1982 /* Set up pointer to the character after end of field and
1983 skip whitespace IFS after it. */
1984 next_field = field_end + strspn (field_end, ifs_white);
1986 /* Skip at most one non-whitespace IFS character after the field */
1988 if (*next_field && strchr (ifs, *next_field))
1994 /* Null-terminate it */
1997 /* Tag a copy onto the current word */
1998 *word = w_addstr (*word, word_length, max_length, field_begin);
2000 if (*word == NULL && *field_begin != '\0')
2006 field_begin = next_field;
2008 while (seen_nonws_ifs || *field_begin);
2020 error = WRDE_NOSPACE;
2024 error = WRDE_SYNTAX;
2036 parse_dollars (char **word, size_t *word_length, size_t *max_length,
2037 const char *words, size_t *offset, int flags,
2038 wordexp_t *pwordexp, const char *ifs, const char *ifs_white,
2041 /* We are poised _at_ "$" */
2042 switch (words[1 + *offset])
2047 *word = w_addchar (*word, word_length, max_length, '$');
2048 return *word ? 0 : WRDE_NOSPACE;
2051 if (words[2 + *offset] == '(')
2053 /* Differentiate between $((1+3)) and $((echo);(ls)) */
2054 int i = 3 + *offset;
2056 while (words[i] && !(depth == 0 && words[i] == ')'))
2058 if (words[i] == '(')
2060 else if (words[i] == ')')
2066 if (words[i] == ')' && words[i + 1] == ')')
2069 /* Call parse_arith -- 0 is for "no brackets" */
2070 return parse_arith (word, word_length, max_length, words, offset,
2075 if (flags & WRDE_NOCMD)
2079 return parse_comm (word, word_length, max_length, words, offset, flags,
2080 quoted? NULL : pwordexp, ifs, ifs_white);
2084 /* Call parse_arith -- 1 is for "brackets" */
2085 return parse_arith (word, word_length, max_length, words, offset, flags,
2090 ++(*offset); /* parse_param needs to know if "{" is there */
2091 return parse_param (word, word_length, max_length, words, offset, flags,
2092 pwordexp, ifs, ifs_white, quoted);
2098 parse_backtick (char **word, size_t *word_length, size_t *max_length,
2099 const char *words, size_t *offset, int flags,
2100 wordexp_t *pwordexp, const char *ifs, const char *ifs_white)
2102 /* We are poised just after "`" */
2107 char *comm = w_newword (&comm_length, &comm_maxlen);
2109 for (; words[*offset]; ++(*offset))
2111 switch (words[*offset])
2114 /* Go -- give the script to the shell */
2115 error = exec_comm (comm, word, word_length, max_length, flags,
2116 pwordexp, ifs, ifs_white);
2123 error = parse_qtd_backslash (&comm, &comm_length, &comm_maxlen,
2136 error = parse_backslash (&comm, &comm_length, &comm_maxlen, words,
2148 squoting = 1 - squoting;
2150 comm = w_addchar (comm, &comm_length, &comm_maxlen, words[*offset]);
2152 return WRDE_NOSPACE;
2163 parse_dquote (char **word, size_t *word_length, size_t *max_length,
2164 const char *words, size_t *offset, int flags,
2165 wordexp_t *pwordexp, const char * ifs, const char * ifs_white)
2167 /* We are poised just after a double-quote */
2170 for (; words[*offset]; ++(*offset))
2172 switch (words[*offset])
2178 error = parse_dollars (word, word_length, max_length, words, offset,
2179 flags, pwordexp, ifs, ifs_white, 1);
2180 /* The ``1'' here is to tell parse_dollars not to
2181 * split the fields. It may need to, however ("$@").
2189 if (flags & WRDE_NOCMD)
2193 error = parse_backtick (word, word_length, max_length, words,
2194 offset, flags, NULL, NULL, NULL);
2195 /* The first NULL here is to tell parse_backtick not to
2204 error = parse_qtd_backslash (word, word_length, max_length, words,
2213 *word = w_addchar (*word, word_length, max_length, words[*offset]);
2215 return WRDE_NOSPACE;
2219 /* Unterminated string */
2224 * wordfree() is to be called after pwordexp is finished with.
2228 wordfree (wordexp_t *pwordexp)
2231 /* wordexp can set pwordexp to NULL */
2232 if (pwordexp && pwordexp->we_wordv)
2234 char **wordv = pwordexp->we_wordv;
2236 for (wordv += pwordexp->we_offs; *wordv; ++wordv)
2239 free (pwordexp->we_wordv);
2240 pwordexp->we_wordv = NULL;
2243 libc_hidden_def (wordfree)
2250 wordexp (const char *words, wordexp_t *pwordexp, int flags)
2252 size_t words_offset;
2255 char *word = w_newword (&word_length, &max_length);
2259 wordexp_t old_word = *pwordexp;
2261 if (flags & WRDE_REUSE)
2263 /* Minimal implementation of WRDE_REUSE for now */
2264 wordfree (pwordexp);
2265 old_word.we_wordv = NULL;
2268 if ((flags & WRDE_APPEND) == 0)
2270 pwordexp->we_wordc = 0;
2272 if (flags & WRDE_DOOFFS)
2274 pwordexp->we_wordv = calloc (1 + pwordexp->we_offs, sizeof (char *));
2275 if (pwordexp->we_wordv == NULL)
2277 error = WRDE_NOSPACE;
2283 pwordexp->we_wordv = calloc (1, sizeof (char *));
2284 if (pwordexp->we_wordv == NULL)
2286 error = WRDE_NOSPACE;
2290 pwordexp->we_offs = 0;
2294 /* Find out what the field separators are.
2295 * There are two types: whitespace and non-whitespace.
2297 ifs = getenv ("IFS");
2300 /* IFS unset - use <space><tab><newline>. */
2301 ifs = strcpy (ifs_white, " \t\n");
2305 char *whch = ifs_white;
2307 while (*ifsch != '\0')
2309 if (*ifsch == ' ' || *ifsch == '\t' || *ifsch == '\n')
2311 /* Whitespace IFS. See first whether it is already in our
2313 char *runp = ifs_white;
2315 while (runp < whch && *runp != *ifsch)
2327 for (words_offset = 0 ; words[words_offset] ; ++words_offset)
2328 switch (words[words_offset])
2331 error = parse_backslash (&word, &word_length, &max_length, words,
2340 error = parse_dollars (&word, &word_length, &max_length, words,
2341 &words_offset, flags, pwordexp, ifs, ifs_white,
2350 if (flags & WRDE_NOCMD)
2352 error = WRDE_CMDSUB;
2357 error = parse_backtick (&word, &word_length, &max_length, words,
2358 &words_offset, flags, pwordexp, ifs,
2368 error = parse_dquote (&word, &word_length, &max_length, words,
2369 &words_offset, flags, pwordexp, ifs, ifs_white);
2376 error = w_addword (pwordexp, NULL);
2386 error = parse_squote (&word, &word_length, &max_length, words,
2394 error = w_addword (pwordexp, NULL);
2403 error = parse_tilde (&word, &word_length, &max_length, words,
2404 &words_offset, pwordexp->we_wordc);
2414 error = parse_glob (&word, &word_length, &max_length, words,
2415 &words_offset, flags, pwordexp, ifs, ifs_white);
2423 /* Is it a word separator? */
2424 if (strchr (" \t", words[words_offset]) == NULL)
2426 char ch = words[words_offset];
2428 /* Not a word separator -- but is it a valid word char? */
2429 if (strchr ("\n|&;<>(){}", ch))
2432 error = WRDE_BADCHAR;
2436 /* "Ordinary" character -- add it to word */
2437 word = w_addchar (word, &word_length, &max_length,
2441 error = WRDE_NOSPACE;
2448 /* If a word has been delimited, add it to the list. */
2451 error = w_addword (pwordexp, word);
2456 word = w_newword (&word_length, &max_length);
2461 /* There was a word separator at the end */
2462 if (word == NULL) /* i.e. w_newword */
2465 /* There was no field separator at the end */
2466 return w_addword (pwordexp, word);
2470 * free memory used (unless error is WRDE_NOSPACE), and
2471 * set pwordexp members back to what they were.
2476 if (error == WRDE_NOSPACE)
2477 return WRDE_NOSPACE;
2479 if ((flags & WRDE_APPEND) == 0)
2480 wordfree (pwordexp);
2482 *pwordexp = old_word;