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 <bits/kernel-features.h>
24 #include <sys/types.h>
39 #define __WORDEXP_FULL
42 * This is a recursive-descent-style word expansion routine.
45 /* These variables are defined and initialized in the startup code. */
46 /*extern int __libc_argc;*/
47 /*extern char **__libc_argv;*/
50 int attribute_hidden __libc_argc;
51 char attribute_hidden **__libc_argv;
53 /* Some forward declarations */
54 static int parse_dollars(char **word, size_t * word_length,
55 size_t * max_length, const char *words,
56 size_t * offset, int flags, wordexp_t * pwordexp,
57 const char *ifs, const char *ifs_white,
59 static int parse_backtick(char **word, size_t * word_length,
60 size_t * max_length, const char *words,
61 size_t * offset, int flags, wordexp_t * pwordexp,
62 const char *ifs, const char *ifs_white);
63 static int parse_dquote(char **word, size_t * word_length,
64 size_t * max_length, const char *words,
65 size_t * offset, int flags, wordexp_t * pwordexp,
66 const char *ifs, const char *ifs_white);
70 /* The w_*() functions manipulate word lists. */
73 /* Result of w_newword will be ignored if it's the last word. */
74 static __inline__ char *w_newword(size_t * actlen, size_t * maxlen)
76 *actlen = *maxlen = 0;
80 /* Add a character to the buffer, allocating room for it if needed. */
81 static __inline__ char *w_addchar(char *buffer, size_t * actlen,
82 size_t * maxlen, char ch)
83 /* (lengths exclude trailing zero) */
86 if (*actlen == *maxlen) {
87 char *old_buffer = buffer;
88 assert(buffer == NULL || *maxlen != 0);
90 buffer = realloc(buffer, 1 + *maxlen);
97 buffer[++(*actlen)] = '\0';
103 #define MAX( a, b ) ( ( ( a ) > ( b ) ) ? ( a ) : ( b ) )
105 static char *w_addmem(char *buffer, size_t * actlen, size_t * maxlen,
106 const char *str, size_t len)
108 /* Add a string to the buffer, allocating room for it if needed.
110 if (*actlen + len > *maxlen) {
111 char *old_buffer = buffer;
112 assert(buffer == NULL || *maxlen != 0);
113 *maxlen += MAX(2 * len, W_CHUNK);
114 buffer = realloc(old_buffer, 1 + *maxlen);
119 if (buffer != NULL) {
120 *((char *) mempcpy(&buffer[*actlen], str, len)) = '\0';
126 /* Add a string to the buffer, allocating room for it if needed. */
127 static char *w_addstr(char *buffer, size_t * actlen, size_t * maxlen,
129 /* (lengths exclude trailing zero) */
132 assert(str != NULL); /* w_addstr only called from this file */
135 return w_addmem(buffer, actlen, maxlen, str, len);
138 /* Add a word to the wordlist */
139 static int w_addword(wordexp_t * pwordexp, char *word)
144 /* Internally, NULL acts like "". Convert NULLs to "" before
145 * the caller sees them.
153 num_p = 2 + pwordexp->we_wordc + pwordexp->we_offs;
154 new_wordv = realloc(pwordexp->we_wordv, sizeof(char *) * num_p);
155 if (new_wordv != NULL) {
156 pwordexp->we_wordv = new_wordv;
157 pwordexp->we_wordv[pwordexp->we_offs + pwordexp->we_wordc++] = word;
158 pwordexp->we_wordv[pwordexp->we_offs + pwordexp->we_wordc] = NULL;
166 /* The parse_*() functions should leave *offset being the offset in 'words'
167 * to the last character processed.
170 parse_backslash(char **word, size_t * word_length, size_t * max_length,
171 const char *words, size_t * offset)
173 /* We are poised _at_ a backslash, not in quotes */
175 switch (words[1 + *offset]) {
177 /* Backslash is last character of input words */
185 *word = w_addchar(*word, word_length, max_length, words[1 + *offset]);
197 parse_qtd_backslash(char **word, size_t * word_length, size_t * max_length,
198 const char *words, size_t * offset)
200 /* We are poised _at_ a backslash, inside quotes */
202 switch (words[1 + *offset]) {
204 /* Backslash is last character of input words */
216 w_addchar(*word, word_length, max_length, words[1 + *offset]);
224 *word = w_addchar(*word, word_length, max_length, words[*offset]);
227 w_addchar(*word, word_length, max_length,
241 parse_tilde(char **word, size_t * word_length, size_t * max_length,
242 const char *words, size_t * offset, size_t wordc)
244 /* We are poised _at_ a tilde */
247 if (*word_length != 0) {
248 if (!((*word)[*word_length - 1] == '=' && wordc == 0)) {
249 if (!((*word)[*word_length - 1] == ':'
250 && strchr(*word, '=') && wordc == 0)) {
251 *word = w_addchar(*word, word_length, max_length, '~');
252 return *word ? 0 : WRDE_NOSPACE;
257 for (i = 1 + *offset; words[i]; i++) {
258 if (words[i] == ':' || words[i] == '/' || words[i] == ' ' ||
259 words[i] == '\t' || words[i] == 0)
262 if (words[i] == '\\') {
263 *word = w_addchar(*word, word_length, max_length, '~');
264 return *word ? 0 : WRDE_NOSPACE;
268 if (i == 1 + *offset) {
269 /* Tilde appears on its own */
271 struct passwd pwd, *tpwd;
277 /* POSIX.2 says ~ expands to $HOME and if HOME is unset the
278 results are unspecified. We do a lookup on the uid if
281 home = getenv("HOME");
283 *word = w_addstr(*word, word_length, max_length, home);
288 buffer = alloca(buflen);
290 while ((result = getpwuid_r(uid, &pwd, buffer, buflen, &tpwd))
291 != 0 && errno == ERANGE)
294 buffer = alloca(buflen);
297 if (result == 0 && tpwd != NULL && pwd.pw_dir != NULL) {
298 *word = w_addstr(*word, word_length, max_length, pwd.pw_dir);
302 *word = w_addchar(*word, word_length, max_length, '~');
308 /* Look up user name in database to get home directory */
309 char *user = strndup(&words[1 + *offset], i - (1 + *offset));
310 struct passwd pwd, *tpwd;
312 char *buffer = alloca(buflen);
315 while ((result = getpwnam_r(user, &pwd, buffer, buflen, &tpwd)) != 0
316 && errno == ERANGE) {
318 buffer = alloca(buflen);
321 if (result == 0 && tpwd != NULL && pwd.pw_dir)
322 *word = w_addstr(*word, word_length, max_length, pwd.pw_dir);
324 /* (invalid login name) */
325 *word = w_addchar(*word, word_length, max_length, '~');
327 *word = w_addstr(*word, word_length, max_length, user);
332 return *word ? 0 : WRDE_NOSPACE;
337 do_parse_glob(const char *glob_word, char **word, size_t * word_length,
338 size_t * max_length, wordexp_t * pwordexp, const char *ifs
339 /*, const char *ifs_white*/)
345 error = glob(glob_word, GLOB_NOCHECK, NULL, &globbuf);
348 /* We can only run into memory problems. */
349 assert(error == GLOB_NOSPACE);
354 /* No field splitting allowed. */
355 assert(globbuf.gl_pathv[0] != NULL);
356 *word = w_addstr(*word, word_length, max_length, globbuf.gl_pathv[0]);
357 for (match = 1; match < globbuf.gl_pathc && *word != NULL; ++match) {
358 *word = w_addchar(*word, word_length, max_length, ' ');
360 *word = w_addstr(*word, word_length, max_length,
361 globbuf.gl_pathv[match]);
365 return *word ? 0 : WRDE_NOSPACE;
368 assert(ifs == NULL || *ifs != '\0');
371 *word = w_newword(word_length, max_length);
374 for (match = 0; match < globbuf.gl_pathc; ++match) {
375 char *matching_word = strdup(globbuf.gl_pathv[match]);
377 if (matching_word == NULL || w_addword(pwordexp, matching_word)) {
388 parse_glob(char **word, size_t * word_length, size_t * max_length,
389 const char *words, size_t * offset, int flags,
390 wordexp_t * pwordexp, const char *ifs, const char *ifs_white)
392 /* We are poised just after a '*', a '[' or a '?'. */
393 int error = WRDE_NOSPACE;
394 int quoted = 0; /* 1 if singly-quoted, 2 if doubly */
396 wordexp_t glob_list; /* List of words to glob */
398 glob_list.we_wordc = 0;
399 glob_list.we_wordv = NULL;
400 glob_list.we_offs = 0;
401 for (; words[*offset] != '\0'; ++*offset) {
402 if ((ifs && strchr(ifs, words[*offset])) ||
403 (!ifs && strchr(" \t\n", words[*offset])))
407 /* Sort out quoting */
408 if (words[*offset] == '\'') {
412 } else if (quoted == 1) {
416 } else if (words[*offset] == '"') {
420 } else if (quoted == 2) {
426 /* Sort out other special characters */
427 if (quoted != 1 && words[*offset] == '$') {
428 error = parse_dollars(word, word_length, max_length, words,
429 offset, flags, &glob_list, ifs,
430 ifs_white, quoted == 2);
435 } else if (words[*offset] == '\\') {
437 error = parse_qtd_backslash(word, word_length, max_length,
440 error = parse_backslash(word, word_length, max_length,
449 *word = w_addchar(*word, word_length, max_length, words[*offset]);
454 /* Don't forget to re-parse the character we stopped at. */
458 error = w_addword(&glob_list, *word);
459 *word = w_newword(word_length, max_length);
460 for (i = 0; error == 0 && i < glob_list.we_wordc; i++)
461 error = do_parse_glob(glob_list.we_wordv[i], word, word_length,
462 max_length, pwordexp, ifs /*, ifs_white*/);
466 wordfree(&glob_list);
471 parse_squote(char **word, size_t * word_length, size_t * max_length,
472 const char *words, size_t * offset)
474 /* We are poised just after a single quote */
475 for (; words[*offset]; ++(*offset)) {
476 if (words[*offset] != '\'') {
477 *word = w_addchar(*word, word_length, max_length, words[*offset]);
484 /* Unterminated string */
488 #ifdef __WORDEXP_FULL
489 static int eval_expr(char *expr, long int *result);
491 static char *_itoa(unsigned long long int value, char *buflim)
493 sprintf(buflim, "%llu", value);
497 /* Functions to evaluate an arithmetic expression */
498 static int eval_expr_val(char **expr, long int *result)
503 /* Skip white space */
504 for (digit = *expr; digit && *digit && isspace(*digit); ++digit);
509 /* Scan for closing paren */
510 for (++digit; **expr && **expr != ')'; ++(*expr));
518 if (eval_expr(digit, result))
523 case '+': /* Positive value */
527 case '-': /* Negative value */
533 if (!isdigit(*digit))
538 for (; *digit && isdigit(*digit); ++digit)
539 *result = (*result * 10) + (*digit - '0');
546 static int eval_expr_multdiv(char **expr, long int *result)
551 if (eval_expr_val(expr, result) != 0)
555 /* Skip white space */
556 for (; *expr && **expr && isspace(**expr); ++(*expr));
560 if (eval_expr_val(expr, &arg) != 0)
564 } else if (**expr == '/') {
566 if (eval_expr_val(expr, &arg) != 0)
577 static int eval_expr(char *expr, long int *result)
582 if (eval_expr_multdiv(&expr, result) != 0)
586 /* Skip white space */
587 for (; expr && *expr && isspace(*expr); ++expr);
591 if (eval_expr_multdiv(&expr, &arg) != 0)
595 } else if (*expr == '-') {
597 if (eval_expr_multdiv(&expr, &arg) != 0)
609 parse_arith(char **word, size_t * word_length, size_t * max_length,
610 const char *words, size_t * offset, int flags, int bracket)
612 /* We are poised just after "$((" or "$[" */
619 expr = w_newword(&expr_length, &expr_maxlen);
620 for (; words[*offset]; ++(*offset)) {
621 switch (words[*offset]) {
623 error = parse_dollars(&expr, &expr_length, &expr_maxlen,
624 words, offset, flags, NULL, NULL, NULL,
626 /* The ``1'' here is to tell parse_dollars not to
637 error = parse_backtick(&expr, &expr_length, &expr_maxlen,
638 words, offset, flags, NULL, NULL, NULL);
639 /* The first NULL here is to tell parse_backtick not to
649 error = parse_qtd_backslash(&expr, &expr_length, &expr_maxlen,
655 /* I think that a backslash within an
656 * arithmetic expansion is bound to
657 * cause an error sooner or later anyway though.
662 if (--paren_depth == 0) {
663 char result[21]; /* 21 = ceil(log10(2^64)) + 1 */
664 long int numresult = 0;
665 long long int convertme;
667 if (bracket || words[1 + *offset] != ')') {
675 if (*expr && eval_expr(expr, &numresult) != 0) {
681 convertme = -numresult;
682 *word = w_addchar(*word, word_length, max_length, '-');
688 convertme = numresult;
691 *word = w_addstr(*word, word_length, max_length,
692 _itoa(convertme, &result[20]));
694 return *word ? 0 : WRDE_NOSPACE;
697 w_addchar(expr, &expr_length, &expr_maxlen,
705 if (bracket && paren_depth == 1) {
706 char result[21]; /* 21 = ceil(log10(2^64)) + 1 */
707 long int numresult = 0;
710 if (*expr && eval_expr(expr, &numresult) != 0) {
716 *word = w_addstr(*word, word_length, max_length,
717 _itoa(numresult, &result[20]));
719 return *word ? 0 : WRDE_NOSPACE;
736 w_addchar(expr, &expr_length, &expr_maxlen,
748 /* Function called by child process in exec_comm() */
749 static void attribute_noreturn
750 exec_comm_child(char *comm, int *fildes, int showerr, int noexec)
753 const char *args[4] = { _PATH_BSHELL, "-c", comm, NULL };
755 /* Execute the command, or just check syntax? */
759 /* Redirect output. */
761 if (likely(fd != STDOUT_FILENO)) {
762 dup2(fd, STDOUT_FILENO);
765 #if defined O_CLOEXEC && defined __UCLIBC_LINUX_SPECIFIC__ && defined __ASSUME_PIPE2
767 /* Reset the close-on-exec flag (if necessary). */
768 fcntl (fd, F_SETFD, 0);
771 /* Redirect stderr to /dev/null if we have to. */
773 close(STDERR_FILENO);
774 fd = open(_PATH_DEVNULL, O_WRONLY);
775 if (fd >= 0 && fd != STDERR_FILENO) {
781 /* Make sure the subshell doesn't field-split on our behalf. */
786 execve(_PATH_BSHELL, (char *const *) args, __environ);
792 /* Function to execute a command and retrieve the results */
793 /* pwordexp contains NULL if field-splitting is forbidden */
795 exec_comm(char *comm, char **word, size_t * word_length,
796 size_t * max_length, int flags, wordexp_t * pwordexp,
797 const char *ifs, const char *ifs_white)
804 size_t maxnewlines = 0;
808 /* Don't fork() unless necessary */
811 #if defined O_CLOEXEC && defined __UCLIBC_LINUX_SPECIFIC__ && defined __ASSUME_PIPE2
812 if (pipe2(fildes, O_CLOEXEC) < 0)
816 if (pipe(fildes) < 0)
821 if ((pid = fork()) < 0) {
829 exec_comm_child(comm, fildes, (flags & WRDE_SHOWERR), 0);
834 buffer = alloca(bufsize);
837 /* Quoted - no field splitting */
840 if ((buflen = read(fildes[0], buffer, bufsize)) < 1) {
841 if (waitpid(pid, &status, WNOHANG) == 0)
843 if ((buflen = read(fildes[0], buffer, bufsize)) < 1)
847 maxnewlines += buflen;
849 *word = w_addmem(*word, word_length, max_length, buffer, buflen);
854 /* Not quoted - split fields */
859 * 0 when searching for first character in a field not IFS white space
860 * 1 when copying the text of a field
861 * 2 when searching for possible non-whitespace IFS
862 * 3 when searching for non-newline after copying field
866 if ((buflen = read(fildes[0], buffer, bufsize)) < 1) {
867 if (waitpid(pid, &status, WNOHANG) == 0)
869 if ((buflen = read(fildes[0], buffer, bufsize)) < 1)
873 for (i = 0; i < buflen; ++i) {
874 if (strchr(ifs, buffer[i]) != NULL) {
875 /* Current character is IFS */
876 if (strchr(ifs_white, buffer[i]) == NULL) {
877 /* Current character is IFS but not whitespace */
882 * eg: text<space><comma><space>moretext
884 * So, strip whitespace IFS (like at the start)
891 /* fall through and delimit field.. */
893 if (buffer[i] == '\n') {
894 /* Current character is (IFS) newline */
896 /* If copying a field, this is the end of it,
897 but maybe all that's left is trailing newlines.
898 So start searching for a non-newline. */
904 /* Current character is IFS white space, but
907 /* If not either copying a field or searching
908 for non-newline after a field, ignore it */
909 if (copying != 1 && copying != 3)
912 /* End of field (search for non-ws IFS afterwards) */
917 /* First IFS white space (non-newline), or IFS non-whitespace.
918 * Delimit the field. Nulls are converted by w_addword. */
919 if (w_addword(pwordexp, *word) == WRDE_NOSPACE)
922 *word = w_newword(word_length, max_length);
925 /* fall back round the loop.. */
927 /* Not IFS character */
930 /* Nothing but (IFS) newlines since the last field,
931 so delimit it here before starting new word */
932 if (w_addword(pwordexp, *word) == WRDE_NOSPACE)
935 *word = w_newword(word_length, max_length);
940 if (buffer[i] == '\n') /* happens if newline not in IFS */
945 *word = w_addchar(*word, word_length, max_length,
954 /* Chop off trailing newlines (required by POSIX.2) */
955 /* Ensure we don't go back further than the beginning of the
956 substitution (i.e. remove maxnewlines bytes at most) */
957 while (maxnewlines-- != 0 &&
958 *word_length > 0 && (*word)[*word_length - 1] == '\n') {
959 (*word)[--*word_length] = '\0';
961 /* If the last word was entirely newlines, turn it into a new word
962 * which can be ignored if there's nothing following it. */
963 if (*word_length == 0) {
965 *word = w_newword(word_length, max_length);
972 /* Check for syntax error (re-execute but with "-n" flag) */
973 if (buflen < 1 && status != 0) {
974 if ((pid = fork()) < 0) {
980 fildes[0] = fildes[1] = -1;
981 exec_comm_child(comm, fildes, 0, 1);
984 if (waitpid(pid, &status, 0) == pid && status != 0)
992 waitpid(pid, NULL, 0);
998 parse_comm(char **word, size_t * word_length, size_t * max_length,
999 const char *words, size_t * offset, int flags,
1000 wordexp_t * pwordexp, const char *ifs, const char *ifs_white)
1002 /* We are poised just after "$(" */
1003 int paren_depth = 1;
1005 int quoted = 0; /* 1 for singly-quoted, 2 for doubly-quoted */
1008 char *comm = w_newword(&comm_length, &comm_maxlen);
1010 for (; words[*offset]; ++(*offset)) {
1011 switch (words[*offset]) {
1015 else if (quoted == 1)
1023 else if (quoted == 2)
1029 if (!quoted && --paren_depth == 0) {
1030 /* Go -- give script to the shell */
1032 error = exec_comm(comm, word, word_length, max_length,
1033 flags, pwordexp, ifs, ifs_white);
1040 /* This is just part of the script */
1048 comm = w_addchar(comm, &comm_length, &comm_maxlen, words[*offset]);
1050 return WRDE_NOSPACE;
1060 parse_backtick(char **word, size_t * word_length, size_t * max_length,
1061 const char *words, size_t * offset, int flags,
1062 wordexp_t * pwordexp, const char *ifs,
1063 const char *ifs_white)
1065 /* We are poised just after "`" */
1070 char *comm = w_newword(&comm_length, &comm_maxlen);
1072 for (; words[*offset]; ++(*offset)) {
1073 switch (words[*offset]) {
1075 /* Go -- give the script to the shell */
1076 error = exec_comm(comm, word, word_length, max_length, flags,
1077 pwordexp, ifs, ifs_white);
1083 error = parse_qtd_backslash(&comm, &comm_length, &comm_maxlen,
1095 error = parse_backslash(&comm, &comm_length, &comm_maxlen, words,
1106 squoting = 1 - squoting;
1108 comm = w_addchar(comm, &comm_length, &comm_maxlen,
1111 return WRDE_NOSPACE;
1121 parse_param(char **word, size_t * word_length, size_t * max_length,
1122 const char *words, size_t * offset, int flags,
1123 wordexp_t * pwordexp, const char *ifs, const char *ifs_white,
1126 /* We are poised just after "$" */
1129 ACT_RP_SHORT_LEFT = '#',
1130 ACT_RP_LONG_LEFT = 'L',
1131 ACT_RP_SHORT_RIGHT = '%',
1132 ACT_RP_LONG_RIGHT = 'R',
1133 ACT_NULL_ERROR = '?',
1134 ACT_NULL_SUBST = '-',
1135 ACT_NONNULL_SUBST = '+',
1136 ACT_NULL_ASSIGN = '='
1142 size_t start = *offset;
1146 enum action action = ACT_NONE;
1151 int pattern_is_quoted = 0; /* 1 for singly-quoted, 2 for doubly-quoted */
1155 int brace = words[*offset] == '{';
1157 env = w_newword(&env_length, &env_maxlen);
1158 pattern = w_newword(&pat_length, &pat_maxlen);
1163 /* First collect the parameter name. */
1165 if (words[*offset] == '#') {
1172 if (isalpha(words[*offset]) || words[*offset] == '_') {
1173 /* Normal parameter name. */
1175 env = w_addchar(env, &env_length, &env_maxlen, words[*offset]);
1179 while (isalnum(words[++*offset]) || words[*offset] == '_');
1180 } else if (isdigit(words[*offset])) {
1181 /* Numeric parameter name. */
1184 env = w_addchar(env, &env_length, &env_maxlen, words[*offset]);
1190 while (isdigit(words[++*offset]));
1191 } else if (strchr("*@$", words[*offset]) != NULL) {
1192 /* Special parameter. */
1194 env = w_addchar(env, &env_length, &env_maxlen, words[*offset]);
1204 /* Check for special action to be applied to the value. */
1205 switch (words[*offset]) {
1211 action = ACT_RP_SHORT_LEFT;
1212 if (words[1 + *offset] == '#') {
1214 action = ACT_RP_LONG_LEFT;
1219 action = ACT_RP_SHORT_RIGHT;
1220 if (words[1 + *offset] == '%') {
1222 action = ACT_RP_LONG_RIGHT;
1227 if (strchr("-=?+", words[1 + *offset]) == NULL)
1231 action = words[++*offset];
1238 action = words[*offset];
1245 /* Now collect the pattern, but don't expand it yet. */
1247 for (; words[*offset]; ++(*offset)) {
1248 switch (words[*offset]) {
1250 if (!pattern_is_quoted)
1255 if (!pattern_is_quoted) {
1263 if (pattern_is_quoted)
1264 /* Quoted; treat as normal character. */
1267 /* Otherwise, it's an escape: next character is literal. */
1268 if (words[++*offset] == '\0')
1271 pattern = w_addchar(pattern, &pat_length, &pat_maxlen, '\\');
1272 if (pattern == NULL)
1278 if (pattern_is_quoted == 0)
1279 pattern_is_quoted = 1;
1280 else if (pattern_is_quoted == 1)
1281 pattern_is_quoted = 0;
1286 if (pattern_is_quoted == 0)
1287 pattern_is_quoted = 2;
1288 else if (pattern_is_quoted == 2)
1289 pattern_is_quoted = 0;
1294 pattern = w_addchar(pattern, &pat_length, &pat_maxlen,
1296 if (pattern == NULL)
1301 /* End of input string -- remember to reparse the character that we
1306 if (words[start] == '{' && words[*offset] != '}')
1311 /* $# expands to the number of positional parameters */
1313 value = _itoa(__libc_argc - 1, &buffer[20]);
1316 /* Just $ on its own */
1317 *offset = start - 1;
1318 *word = w_addchar(*word, word_length, max_length, '$');
1319 return *word ? 0 : WRDE_NOSPACE;
1322 /* Is it a numeric parameter? */
1323 else if (isdigit(env[0])) {
1326 if (n >= __libc_argc)
1327 /* Substitute NULL. */
1330 /* Replace with appropriate positional parameter. */
1331 value = __libc_argv[n];
1333 /* Is it a special parameter? */
1338 value = _itoa(getpid(), &buffer[20]);
1340 /* Is it `${#*}' or `${#@}'? */
1341 else if ((*env == '*' || *env == '@') && seen_hash) {
1343 value = _itoa(__libc_argc > 0 ? __libc_argc - 1 : 0,
1345 *word = w_addstr(*word, word_length, max_length, value);
1348 return *word ? 0 : WRDE_NOSPACE;
1350 /* Is it `$*' or `$@' (unquoted) ? */
1351 else if (*env == '*' || (*env == '@' && !quoted)) {
1352 size_t plist_len = 0;
1356 /* Build up value parameter by parameter (copy them) */
1357 for (p = 1; __libc_argv[p]; ++p)
1358 plist_len += strlen(__libc_argv[p]) + 1; /* for space */
1359 value = malloc(plist_len);
1364 for (p = 1; __libc_argv[p]; ++p) {
1367 end = stpcpy(end, __libc_argv[p]);
1372 /* Must be a quoted `$@' */
1373 assert(*env == '@' && quoted);
1375 /* Each parameter is a separate word ("$@") */
1376 if (__libc_argc == 2)
1377 value = __libc_argv[1];
1378 else if (__libc_argc > 2) {
1381 /* Append first parameter to current word. */
1382 value = w_addstr(*word, word_length, max_length,
1384 if (value == NULL || w_addword(pwordexp, value))
1387 for (p = 2; __libc_argv[p + 1]; p++) {
1388 char *newword = strdup(__libc_argv[p]);
1390 if (newword == NULL || w_addword(pwordexp, newword))
1394 /* Start a new word with the last parameter. */
1395 *word = w_newword(word_length, max_length);
1396 value = __libc_argv[p];
1404 value = getenv(env);
1406 if (value == NULL && (flags & WRDE_UNDEF)) {
1407 /* Variable not defined. */
1408 error = WRDE_BADVAL;
1412 if (action != ACT_NONE) {
1413 int expand_pattern = 0;
1415 /* First, find out if we need to expand pattern (i.e. if we will
1418 case ACT_RP_SHORT_LEFT:
1419 case ACT_RP_LONG_LEFT:
1420 case ACT_RP_SHORT_RIGHT:
1421 case ACT_RP_LONG_RIGHT:
1422 /* Always expand for these. */
1426 case ACT_NULL_ERROR:
1427 case ACT_NULL_SUBST:
1428 case ACT_NULL_ASSIGN:
1429 if (!value || (!*value && colon_seen))
1430 /* If param is unset, or set but null and a colon has been seen,
1431 the expansion of the pattern will be needed. */
1436 case ACT_NONNULL_SUBST:
1437 /* Expansion of word will be needed if parameter is set and not null,
1438 or set null but no colon has been seen. */
1439 if (value && (*value || !colon_seen))
1445 assert(!"Unrecognised action!");
1448 if (expand_pattern) {
1449 /* We need to perform tilde expansion, parameter expansion,
1450 command substitution, and arithmetic expansion. We also
1451 have to be a bit careful with wildcard characters, as
1452 pattern might be given to fnmatch soon. To do this, we
1453 convert quotes to escapes. */
1459 int quotes = 0; /* 1: single quotes; 2: double */
1461 expanded = w_newword(&exp_len, &exp_maxl);
1462 for (p = pattern; p && *p; p++) {
1469 else if (quotes == 0)
1479 else if (quotes == 0)
1489 /* Convert quoted wildchar to escaped wildchar. */
1490 expanded = w_addchar(expanded, &exp_len,
1493 if (expanded == NULL)
1500 error = parse_dollars(&expanded, &exp_len, &exp_maxl, p,
1501 &_offset, flags, NULL, NULL, NULL, 1);
1515 if (quotes || exp_len)
1519 error = parse_tilde(&expanded, &exp_len, &exp_maxl, p,
1534 expanded = w_addchar(expanded, &exp_len, &exp_maxl, '\\');
1536 assert(*p); /* checked when extracted initially */
1537 if (expanded == NULL)
1541 expanded = w_addchar(expanded, &exp_len, &exp_maxl, *p);
1543 if (expanded == NULL)
1553 case ACT_RP_SHORT_LEFT:
1554 case ACT_RP_LONG_LEFT:
1555 case ACT_RP_SHORT_RIGHT:
1556 case ACT_RP_LONG_RIGHT:
1562 if (value == NULL || pattern == NULL || *pattern == '\0')
1565 end = value + strlen(value);
1568 case ACT_RP_SHORT_LEFT:
1569 for (p = value; p <= end; ++p) {
1572 if (fnmatch(pattern, value, 0) != FNM_NOMATCH) {
1575 char *newval = strdup(p);
1577 if (newval == NULL) {
1592 case ACT_RP_LONG_LEFT:
1593 for (p = end; p >= value; --p) {
1596 if (fnmatch(pattern, value, 0) != FNM_NOMATCH) {
1599 char *newval = strdup(p);
1601 if (newval == NULL) {
1616 case ACT_RP_SHORT_RIGHT:
1617 for (p = end; p >= value; --p) {
1618 if (fnmatch(pattern, p, 0) != FNM_NOMATCH) {
1621 newval = malloc(p - value + 1);
1623 if (newval == NULL) {
1629 *(char *) mempcpy(newval, value, p - value) = '\0';
1640 case ACT_RP_LONG_RIGHT:
1641 for (p = value; p <= end; ++p) {
1642 if (fnmatch(pattern, p, 0) != FNM_NOMATCH) {
1645 newval = malloc(p - value + 1);
1647 if (newval == NULL) {
1653 *(char *) mempcpy(newval, value, p - value) = '\0';
1671 case ACT_NULL_ERROR:
1672 if (value && *value)
1673 /* Substitute parameter */
1677 if (!colon_seen && value)
1678 /* Substitute NULL */
1681 fprintf(stderr, "%s: %s\n", env, pattern);
1683 fprintf(stderr, "%s: parameter null or not set\n", env);
1684 error = WRDE_BADVAL;
1691 case ACT_NULL_SUBST:
1692 if (value && *value)
1693 /* Substitute parameter */
1699 if (!colon_seen && value)
1700 /* Substitute NULL */
1703 value = pattern ? strdup(pattern) : pattern;
1706 if (pattern && !value)
1711 case ACT_NONNULL_SUBST:
1712 if (value && (*value || !colon_seen)) {
1716 value = pattern ? strdup(pattern) : pattern;
1719 if (pattern && !value)
1725 /* Substitute NULL */
1730 case ACT_NULL_ASSIGN:
1731 if (value && *value)
1732 /* Substitute parameter */
1735 if (!colon_seen && value) {
1736 /* Substitute NULL */
1745 value = pattern ? strdup(pattern) : pattern;
1748 if (pattern && !value)
1751 setenv(env, value, 1);
1755 assert(!"Unrecognised action!");
1765 char param_length[21];
1767 param_length[20] = '\0';
1768 *word = w_addstr(*word, word_length, max_length,
1769 _itoa(value ? strlen(value) : 0,
1770 ¶m_length[20]));
1772 assert(value != NULL);
1776 return *word ? 0 : WRDE_NOSPACE;
1782 if (quoted || !pwordexp) {
1783 /* Quoted - no field split */
1784 *word = w_addstr(*word, word_length, max_length, value);
1788 return *word ? 0 : WRDE_NOSPACE;
1790 /* Need to field-split */
1791 char *value_copy = strdup(value); /* Don't modify value */
1792 char *field_begin = value_copy;
1793 int seen_nonws_ifs = 0;
1798 if (value_copy == NULL)
1802 char *field_end = field_begin;
1805 /* If this isn't the first field, start a new word */
1806 if (field_begin != value_copy) {
1807 if (w_addword(pwordexp, *word) == WRDE_NOSPACE) {
1812 *word = w_newword(word_length, max_length);
1815 /* Skip IFS whitespace before the field */
1816 field_begin += strspn(field_begin, ifs_white);
1818 if (!seen_nonws_ifs && *field_begin == 0)
1819 /* Nothing but whitespace */
1822 /* Search for the end of the field */
1823 field_end = field_begin + strcspn(field_begin, ifs);
1825 /* Set up pointer to the character after end of field and
1826 skip whitespace IFS after it. */
1827 next_field = field_end + strspn(field_end, ifs_white);
1829 /* Skip at most one non-whitespace IFS character after the field */
1831 if (*next_field && strchr(ifs, *next_field)) {
1836 /* Null-terminate it */
1839 /* Tag a copy onto the current word */
1840 *word = w_addstr(*word, word_length, max_length, field_begin);
1842 if (*word == NULL && *field_begin != '\0') {
1847 field_begin = next_field;
1849 while (seen_nonws_ifs || *field_begin);
1861 error = WRDE_NOSPACE;
1865 error = WRDE_SYNTAX;
1875 static __inline__ int
1876 parse_backtick(char **word, size_t * word_length, size_t * max_length,
1877 const char *words, size_t * offset, int flags,
1878 wordexp_t * pwordexp, const char *ifs,
1879 const char *ifs_white)
1886 parse_dollars(char **word, size_t * word_length, size_t * max_length,
1887 const char *words, size_t * offset, int flags,
1888 wordexp_t * pwordexp, const char *ifs, const char *ifs_white,
1891 /* We are poised _at_ "$" */
1892 switch (words[1 + *offset]) {
1896 *word = w_addchar(*word, word_length, max_length, '$');
1897 return *word ? 0 : WRDE_NOSPACE;
1899 #ifdef __WORDEXP_FULL
1901 if (words[2 + *offset] == '(') {
1902 /* Differentiate between $((1+3)) and $((echo);(ls)) */
1903 int i = 3 + *offset;
1906 while (words[i] && !(depth == 0 && words[i] == ')')) {
1907 if (words[i] == '(')
1909 else if (words[i] == ')')
1915 if (words[i] == ')' && words[i + 1] == ')') {
1917 /* Call parse_arith -- 0 is for "no brackets" */
1918 return parse_arith(word, word_length, max_length, words,
1923 if (flags & WRDE_NOCMD)
1927 return parse_comm(word, word_length, max_length, words, offset,
1928 flags, quoted ? NULL : pwordexp, ifs, ifs_white);
1932 /* Call parse_arith -- 1 is for "brackets" */
1933 return parse_arith(word, word_length, max_length, words, offset,
1938 ++(*offset); /* parse_param needs to know if "{" is there */
1939 return parse_param(word, word_length, max_length, words, offset,
1940 flags, pwordexp, ifs, ifs_white, quoted);
1943 ++(*offset); /* parse_param needs to know if "{" is there */
1950 parse_dquote(char **word, size_t * word_length, size_t * max_length,
1951 const char *words, size_t * offset, int flags,
1952 wordexp_t * pwordexp, const char *ifs, const char *ifs_white)
1954 /* We are poised just after a double-quote */
1957 for (; words[*offset]; ++(*offset)) {
1958 switch (words[*offset]) {
1963 error = parse_dollars(word, word_length, max_length, words, offset,
1964 flags, pwordexp, ifs, ifs_white, 1);
1965 /* The ``1'' here is to tell parse_dollars not to
1966 * split the fields. It may need to, however ("$@").
1974 if (flags & WRDE_NOCMD)
1978 error = parse_backtick(word, word_length, max_length, words,
1979 offset, flags, NULL, NULL, NULL);
1980 /* The first NULL here is to tell parse_backtick not to
1989 error = parse_qtd_backslash(word, word_length, max_length, words,
1998 *word = w_addchar(*word, word_length, max_length, words[*offset]);
2000 return WRDE_NOSPACE;
2004 /* Unterminated string */
2009 * wordfree() is to be called after pwordexp is finished with.
2012 void wordfree(wordexp_t * pwordexp)
2015 /* wordexp can set pwordexp to NULL */
2016 if (pwordexp && pwordexp->we_wordv) {
2017 char **wordv = pwordexp->we_wordv;
2019 for (wordv += pwordexp->we_offs; *wordv; ++wordv)
2022 free(pwordexp->we_wordv);
2023 pwordexp->we_wordv = NULL;
2026 libc_hidden_def(wordfree)
2032 int wordexp(const char *words, wordexp_t * we, int flags)
2034 size_t words_offset;
2037 char *word = w_newword(&word_length, &max_length);
2041 wordexp_t old_word = *we;
2043 if (flags & WRDE_REUSE) {
2044 /* Minimal implementation of WRDE_REUSE for now */
2046 old_word.we_wordv = NULL;
2049 if ((flags & WRDE_APPEND) == 0) {
2052 if (flags & WRDE_DOOFFS) {
2053 we->we_wordv = calloc(1 + we->we_offs, sizeof(char *));
2054 if (we->we_wordv == NULL) {
2055 error = WRDE_NOSPACE;
2059 we->we_wordv = calloc(1, sizeof(char *));
2060 if (we->we_wordv == NULL) {
2061 error = WRDE_NOSPACE;
2069 /* Find out what the field separators are.
2070 * There are two types: whitespace and non-whitespace.
2072 ifs = getenv("IFS");
2075 /* IFS unset - use <space><tab><newline>. */
2076 ifs = strcpy(ifs_white, " \t\n");
2079 char *whch = ifs_white;
2081 /* Start off with no whitespace IFS characters */
2082 ifs_white[0] = '\0';
2084 while (*ifsch != '\0') {
2085 if ((*ifsch == ' ') || (*ifsch == '\t') || (*ifsch == '\n')) {
2086 /* Whitespace IFS. See first whether it is already in our
2088 char *runp = ifs_white;
2090 while (runp < whch && *runp != '\0' && *runp != *ifsch)
2102 for (words_offset = 0; words[words_offset]; ++words_offset)
2103 switch (words[words_offset]) {
2105 error = parse_backslash(&word, &word_length, &max_length, words,
2114 error = parse_dollars(&word, &word_length, &max_length, words,
2115 &words_offset, flags, we, ifs, ifs_white,
2124 if (flags & WRDE_NOCMD) {
2125 error = WRDE_CMDSUB;
2130 error = parse_backtick(&word, &word_length, &max_length, words,
2131 &words_offset, flags, we, ifs,
2141 error = parse_dquote(&word, &word_length, &max_length, words,
2142 &words_offset, flags, we, ifs, ifs_white);
2148 error = w_addword(we, NULL);
2158 error = parse_squote(&word, &word_length, &max_length, words,
2165 error = w_addword(we, NULL);
2174 error = parse_tilde(&word, &word_length, &max_length, words,
2175 &words_offset, we->we_wordc);
2185 error = parse_glob(&word, &word_length, &max_length, words,
2186 &words_offset, flags, we, ifs, ifs_white);
2194 /* Is it a word separator? */
2195 if (strchr(" \t", words[words_offset]) == NULL) {
2196 char ch = words[words_offset];
2198 /* Not a word separator -- but is it a valid word char? */
2199 if (strchr("\n|&;<>(){}", ch)) {
2201 error = WRDE_BADCHAR;
2205 /* "Ordinary" character -- add it to word */
2206 word = w_addchar(word, &word_length, &max_length, ch);
2208 error = WRDE_NOSPACE;
2215 /* If a word has been delimited, add it to the list. */
2217 error = w_addword(we, word);
2222 word = w_newword(&word_length, &max_length);
2227 /* There was a word separator at the end */
2228 if (word == NULL) /* i.e. w_newword */
2231 /* There was no field separator at the end */
2232 return w_addword(we, word);
2236 * free memory used (unless error is WRDE_NOSPACE), and
2237 * set we members back to what they were.
2242 if (error == WRDE_NOSPACE)
2243 return WRDE_NOSPACE;
2245 if ((flags & WRDE_APPEND) == 0)