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, see
18 <http://www.gnu.org/licenses/>. */
33 #include <sys/param.h>
36 #include <sys/types.h>
37 #include <sys/types.h>
42 #include <kernel-features.h>
44 #include <bits/libc-lock.h>
47 /* Undefine the following line for the production version. */
48 /* #define NDEBUG 1 */
51 /* Get some device information. */
52 #include <device-nrs.h>
55 * This is a recursive-descent-style word expansion routine.
58 /* These variables are defined and initialized in the startup code. */
59 extern int __libc_argc attribute_hidden
;
60 extern char **__libc_argv attribute_hidden
;
62 /* Some forward declarations */
63 static int parse_dollars (char **word
, size_t *word_length
, size_t *max_length
,
64 const char *words
, size_t *offset
, int flags
,
65 wordexp_t
*pwordexp
, const char *ifs
,
66 const char *ifs_white
, int quoted
)
68 static int parse_backtick (char **word
, size_t *word_length
,
69 size_t *max_length
, const char *words
,
70 size_t *offset
, int flags
, wordexp_t
*pwordexp
,
71 const char *ifs
, const char *ifs_white
)
73 static int parse_dquote (char **word
, size_t *word_length
, size_t *max_length
,
74 const char *words
, size_t *offset
, int flags
,
75 wordexp_t
*pwordexp
, const char *ifs
,
76 const char *ifs_white
)
78 static int eval_expr (char *expr
, long int *result
) internal_function
;
80 /* The w_*() functions manipulate word lists. */
84 /* Result of w_newword will be ignored if it's the last word. */
86 w_newword (size_t *actlen
, size_t *maxlen
)
88 *actlen
= *maxlen
= 0;
93 w_addchar (char *buffer
, size_t *actlen
, size_t *maxlen
, char ch
)
94 /* (lengths exclude trailing zero) */
96 /* Add a character to the buffer, allocating room for it if needed. */
98 if (*actlen
== *maxlen
)
100 char *old_buffer
= buffer
;
101 assert (buffer
== NULL
|| *maxlen
!= 0);
103 buffer
= (char *) realloc (buffer
, 1 + *maxlen
);
111 buffer
[*actlen
] = ch
;
112 buffer
[++(*actlen
)] = '\0';
120 w_addmem (char *buffer
, size_t *actlen
, size_t *maxlen
, const char *str
,
123 /* Add a string to the buffer, allocating room for it if needed.
125 if (*actlen
+ len
> *maxlen
)
127 char *old_buffer
= buffer
;
128 assert (buffer
== NULL
|| *maxlen
!= 0);
129 *maxlen
+= MAX (2 * len
, W_CHUNK
);
130 buffer
= realloc (old_buffer
, 1 + *maxlen
);
138 *((char *) __mempcpy (&buffer
[*actlen
], str
, len
)) = '\0';
147 w_addstr (char *buffer
, size_t *actlen
, size_t *maxlen
, const char *str
)
148 /* (lengths exclude trailing zero) */
150 /* Add a string to the buffer, allocating room for it if needed.
154 assert (str
!= NULL
); /* w_addstr only called from this file */
157 return w_addmem (buffer
, actlen
, maxlen
, str
, len
);
162 w_addword (wordexp_t
*pwordexp
, char *word
)
164 /* Add a word to the wordlist */
167 bool allocated
= false;
169 /* Internally, NULL acts like "". Convert NULLs to "" before
170 * the caller sees them.
174 word
= __strdup ("");
180 num_p
= 2 + pwordexp
->we_wordc
+ pwordexp
->we_offs
;
181 new_wordv
= realloc (pwordexp
->we_wordv
, sizeof (char *) * num_p
);
182 if (new_wordv
!= NULL
)
184 pwordexp
->we_wordv
= new_wordv
;
185 pwordexp
->we_wordv
[pwordexp
->we_offs
+ pwordexp
->we_wordc
++] = word
;
186 pwordexp
->we_wordv
[pwordexp
->we_offs
+ pwordexp
->we_wordc
] = NULL
;
197 /* The parse_*() functions should leave *offset being the offset in 'words'
198 * to the last character processed.
203 parse_backslash (char **word
, size_t *word_length
, size_t *max_length
,
204 const char *words
, size_t *offset
)
206 /* We are poised _at_ a backslash, not in quotes */
208 switch (words
[1 + *offset
])
211 /* Backslash is last character of input words */
219 *word
= w_addchar (*word
, word_length
, max_length
, words
[1 + *offset
]);
232 parse_qtd_backslash (char **word
, size_t *word_length
, size_t *max_length
,
233 const char *words
, size_t *offset
)
235 /* We are poised _at_ a backslash, inside quotes */
237 switch (words
[1 + *offset
])
240 /* Backslash is last character of input words */
251 *word
= w_addchar (*word
, word_length
, max_length
, words
[1 + *offset
]);
259 *word
= w_addchar (*word
, word_length
, max_length
, words
[*offset
]);
261 *word
= w_addchar (*word
, word_length
, max_length
, words
[1 + *offset
]);
275 parse_tilde (char **word
, size_t *word_length
, size_t *max_length
,
276 const char *words
, size_t *offset
, size_t wordc
)
278 /* We are poised _at_ a tilde */
281 if (*word_length
!= 0)
283 if (!((*word
)[*word_length
- 1] == '=' && wordc
== 0))
285 if (!((*word
)[*word_length
- 1] == ':'
286 && strchr (*word
, '=') && wordc
== 0))
288 *word
= w_addchar (*word
, word_length
, max_length
, '~');
289 return *word
? 0 : WRDE_NOSPACE
;
294 for (i
= 1 + *offset
; words
[i
]; i
++)
296 if (words
[i
] == ':' || words
[i
] == '/' || words
[i
] == ' ' ||
297 words
[i
] == '\t' || words
[i
] == 0 )
300 if (words
[i
] == '\\')
302 *word
= w_addchar (*word
, word_length
, max_length
, '~');
303 return *word
? 0 : WRDE_NOSPACE
;
307 if (i
== 1 + *offset
)
309 /* Tilde appears on its own */
311 struct passwd pwd
, *tpwd
;
317 /* POSIX.2 says ~ expands to $HOME and if HOME is unset the
318 results are unspecified. We do a lookup on the uid if
321 home
= getenv ("HOME");
324 *word
= w_addstr (*word
, word_length
, max_length
, home
);
331 buffer
= __alloca (buflen
);
333 while ((result
= __getpwuid_r (uid
, &pwd
, buffer
, buflen
, &tpwd
)) != 0
335 buffer
= extend_alloca (buffer
, buflen
, buflen
+ 1000);
337 if (result
== 0 && tpwd
!= NULL
&& pwd
.pw_dir
!= NULL
)
339 *word
= w_addstr (*word
, word_length
, max_length
, pwd
.pw_dir
);
345 *word
= w_addchar (*word
, word_length
, max_length
, '~');
353 /* Look up user name in database to get home directory */
354 char *user
= strndupa (&words
[1 + *offset
], i
- (1 + *offset
));
355 struct passwd pwd
, *tpwd
;
357 char* buffer
= __alloca (buflen
);
360 while ((result
= __getpwnam_r (user
, &pwd
, buffer
, buflen
, &tpwd
)) != 0
362 buffer
= extend_alloca (buffer
, buflen
, buflen
+ 1000);
364 if (result
== 0 && tpwd
!= NULL
&& pwd
.pw_dir
)
365 *word
= w_addstr (*word
, word_length
, max_length
, pwd
.pw_dir
);
368 /* (invalid login name) */
369 *word
= w_addchar (*word
, word_length
, max_length
, '~');
371 *word
= w_addstr (*word
, word_length
, max_length
, user
);
376 return *word
? 0 : WRDE_NOSPACE
;
382 do_parse_glob (const char *glob_word
, char **word
, size_t *word_length
,
383 size_t *max_length
, wordexp_t
*pwordexp
, const char *ifs
,
384 const char *ifs_white
)
390 error
= glob (glob_word
, GLOB_NOCHECK
, NULL
, &globbuf
);
394 /* We can only run into memory problems. */
395 assert (error
== GLOB_NOSPACE
);
401 /* No field splitting allowed. */
402 assert (globbuf
.gl_pathv
[0] != NULL
);
403 *word
= w_addstr (*word
, word_length
, max_length
, globbuf
.gl_pathv
[0]);
404 for (match
= 1; match
< globbuf
.gl_pathc
&& *word
!= NULL
; ++match
)
406 *word
= w_addchar (*word
, word_length
, max_length
, ' ');
408 *word
= w_addstr (*word
, word_length
, max_length
,
409 globbuf
.gl_pathv
[match
]);
413 return *word
? 0 : WRDE_NOSPACE
;
416 assert (ifs
== NULL
|| *ifs
!= '\0');
420 *word
= w_newword (word_length
, max_length
);
423 for (match
= 0; match
< globbuf
.gl_pathc
; ++match
)
425 char *matching_word
= __strdup (globbuf
.gl_pathv
[match
]);
426 if (matching_word
== NULL
|| w_addword (pwordexp
, matching_word
))
439 parse_glob (char **word
, size_t *word_length
, size_t *max_length
,
440 const char *words
, size_t *offset
, int flags
,
441 wordexp_t
*pwordexp
, const char *ifs
, const char *ifs_white
)
443 /* We are poised just after a '*', a '[' or a '?'. */
444 int error
= WRDE_NOSPACE
;
445 int quoted
= 0; /* 1 if singly-quoted, 2 if doubly */
447 wordexp_t glob_list
; /* List of words to glob */
449 glob_list
.we_wordc
= 0;
450 glob_list
.we_wordv
= NULL
;
451 glob_list
.we_offs
= 0;
452 for (; words
[*offset
] != '\0'; ++*offset
)
454 if (strchr (ifs
, words
[*offset
]) != NULL
)
458 /* Sort out quoting */
459 if (words
[*offset
] == '\'')
466 else if (quoted
== 1)
472 else if (words
[*offset
] == '"')
479 else if (quoted
== 2)
486 /* Sort out other special characters */
487 if (quoted
!= 1 && words
[*offset
] == '$')
489 error
= parse_dollars (word
, word_length
, max_length
, words
,
490 offset
, flags
, &glob_list
, ifs
, ifs_white
,
497 else if (words
[*offset
] == '\\')
500 error
= parse_qtd_backslash (word
, word_length
, max_length
,
503 error
= parse_backslash (word
, word_length
, max_length
,
512 *word
= w_addchar (*word
, word_length
, max_length
, words
[*offset
]);
517 /* Don't forget to re-parse the character we stopped at. */
521 error
= w_addword (&glob_list
, *word
);
522 *word
= w_newword (word_length
, max_length
);
523 for (i
= 0; error
== 0 && i
< glob_list
.we_wordc
; i
++)
524 error
= do_parse_glob (glob_list
.we_wordv
[i
], word
, word_length
,
525 max_length
, pwordexp
, ifs
, ifs_white
);
529 wordfree (&glob_list
);
535 parse_squote (char **word
, size_t *word_length
, size_t *max_length
,
536 const char *words
, size_t *offset
)
538 /* We are poised just after a single quote */
539 for (; words
[*offset
]; ++(*offset
))
541 if (words
[*offset
] != '\'')
543 *word
= w_addchar (*word
, word_length
, max_length
, words
[*offset
]);
550 /* Unterminated string */
554 /* Functions to evaluate an arithmetic expression */
557 eval_expr_val (char **expr
, long int *result
)
561 /* Skip white space */
562 for (digit
= *expr
; digit
&& *digit
&& isspace (*digit
); ++digit
);
566 /* Scan for closing paren */
567 for (++digit
; **expr
&& **expr
!= ')'; ++(*expr
));
575 if (eval_expr (digit
, result
))
581 /* POSIX requires that decimal, octal, and hexadecimal constants are
582 recognized. Therefore we pass 0 as the third parameter to strtol. */
583 *result
= strtol (digit
, expr
, 0);
592 eval_expr_multdiv (char **expr
, long int *result
)
597 if (eval_expr_val (expr
, result
) != 0)
602 /* Skip white space */
603 for (; *expr
&& **expr
&& isspace (**expr
); ++(*expr
));
608 if (eval_expr_val (expr
, &arg
) != 0)
613 else if (**expr
== '/')
616 if (eval_expr_val (expr
, &arg
) != 0)
629 eval_expr (char *expr
, long int *result
)
634 if (eval_expr_multdiv (&expr
, result
) != 0)
639 /* Skip white space */
640 for (; expr
&& *expr
&& isspace (*expr
); ++expr
);
645 if (eval_expr_multdiv (&expr
, &arg
) != 0)
650 else if (*expr
== '-')
653 if (eval_expr_multdiv (&expr
, &arg
) != 0)
666 parse_arith (char **word
, size_t *word_length
, size_t *max_length
,
667 const char *words
, size_t *offset
, int flags
, int bracket
)
669 /* We are poised just after "$((" or "$[" */
676 expr
= w_newword (&expr_length
, &expr_maxlen
);
677 for (; words
[*offset
]; ++(*offset
))
679 switch (words
[*offset
])
682 error
= parse_dollars (&expr
, &expr_length
, &expr_maxlen
,
683 words
, offset
, flags
, NULL
, NULL
, NULL
, 1);
684 /* The ``1'' here is to tell parse_dollars not to
696 error
= parse_backtick (&expr
, &expr_length
, &expr_maxlen
,
697 words
, offset
, flags
, NULL
, NULL
, NULL
);
698 /* The first NULL here is to tell parse_backtick not to
709 error
= parse_qtd_backslash (&expr
, &expr_length
, &expr_maxlen
,
716 /* I think that a backslash within an
717 * arithmetic expansion is bound to
718 * cause an error sooner or later anyway though.
723 if (--paren_depth
== 0)
725 char result
[21]; /* 21 = ceil(log10(2^64)) + 1 */
726 long int numresult
= 0;
727 long long int convertme
;
729 if (bracket
|| words
[1 + *offset
] != ')')
738 if (*expr
&& eval_expr (expr
, &numresult
) != 0)
746 convertme
= -numresult
;
747 *word
= w_addchar (*word
, word_length
, max_length
, '-');
755 convertme
= numresult
;
758 *word
= w_addstr (*word
, word_length
, max_length
,
759 _itoa (convertme
, &result
[20], 10, 0));
761 return *word
? 0 : WRDE_NOSPACE
;
763 expr
= w_addchar (expr
, &expr_length
, &expr_maxlen
, words
[*offset
]);
770 if (bracket
&& paren_depth
== 1)
772 char result
[21]; /* 21 = ceil(log10(2^64)) + 1 */
773 long int numresult
= 0;
776 if (*expr
&& eval_expr (expr
, &numresult
) != 0)
783 *word
= w_addstr (*word
, word_length
, max_length
,
784 _itoa_word (numresult
, &result
[20], 10, 0));
786 return *word
? 0 : WRDE_NOSPACE
;
802 expr
= w_addchar (expr
, &expr_length
, &expr_maxlen
, words
[*offset
]);
813 /* Function called by child process in exec_comm() */
815 internal_function
__attribute__ ((always_inline
))
816 exec_comm_child (char *comm
, int *fildes
, int showerr
, int noexec
)
818 const char *args
[4] = { _PATH_BSHELL
, "-c", comm
, NULL
};
820 /* Execute the command, or just check syntax? */
824 /* Redirect output. */
825 if (__builtin_expect (fildes
[1] != STDOUT_FILENO
, 1))
827 __dup2 (fildes
[1], STDOUT_FILENO
);
833 /* Reset the close-on-exec flag (if necessary). */
834 # ifndef __ASSUME_PIPE2
835 if (__have_pipe2
> 0)
837 __fcntl (fildes
[1], F_SETFD
, 0);
841 /* Redirect stderr to /dev/null if we have to. */
846 __close (STDERR_FILENO
);
847 fd
= __open (_PATH_DEVNULL
, O_WRONLY
);
848 if (fd
>= 0 && fd
!= STDERR_FILENO
)
850 __dup2 (fd
, STDERR_FILENO
);
853 /* Be paranoid. Check that we actually opened the /dev/null
855 if (__builtin_expect (__fxstat64 (_STAT_VER
, STDERR_FILENO
, &st
), 0) != 0
856 || __builtin_expect (S_ISCHR (st
.st_mode
), 1) == 0
857 #if defined DEV_NULL_MAJOR && defined DEV_NULL_MINOR
858 || st
.st_rdev
!= makedev (DEV_NULL_MAJOR
, DEV_NULL_MINOR
)
861 /* It's not the /dev/null device. Stop right here. The
862 problem is: how do we stop? We use _exit() with an
863 hopefully unusual exit code. */
867 /* Make sure the subshell doesn't field-split on our behalf. */
871 __execve (_PATH_BSHELL
, (char *const *) args
, __environ
);
877 /* Function to execute a command and retrieve the results */
878 /* pwordexp contains NULL if field-splitting is forbidden */
881 exec_comm (char *comm
, char **word
, size_t *word_length
, size_t *max_length
,
882 int flags
, wordexp_t
*pwordexp
, const char *ifs
,
883 const char *ifs_white
)
890 size_t maxnewlines
= 0;
891 char buffer
[bufsize
];
895 /* Don't fork() unless necessary */
900 # ifndef __ASSUME_PIPE2
901 if (__have_pipe2
>= 0)
904 int r
= __pipe2 (fildes
, O_CLOEXEC
);
905 # ifndef __ASSUME_PIPE2
906 if (__have_pipe2
== 0)
907 __have_pipe2
= r
!= -1 || errno
!= ENOSYS
? 1 : -1;
909 if (__have_pipe2
> 0)
916 #ifndef __ASSUME_PIPE2
918 if (__have_pipe2
< 0)
920 if (__pipe (fildes
) < 0)
926 if ((pid
= __fork ()) < 0)
935 exec_comm_child (comm
, fildes
, noexec
? 0 : flags
& WRDE_SHOWERR
, noexec
);
939 /* If we are just testing the syntax, only wait. */
941 return (TEMP_FAILURE_RETRY (__waitpid (pid
, &status
, 0)) == pid
942 && status
!= 0) ? WRDE_SYNTAX
: 0;
948 /* Quoted - no field splitting */
952 if ((buflen
= TEMP_FAILURE_RETRY (__read (fildes
[0], buffer
,
955 if (TEMP_FAILURE_RETRY (__waitpid (pid
, &status
, WNOHANG
)) == 0)
957 if ((buflen
= TEMP_FAILURE_RETRY (__read (fildes
[0], buffer
,
962 maxnewlines
+= buflen
;
964 *word
= w_addmem (*word
, word_length
, max_length
, buffer
, buflen
);
970 /* Not quoted - split fields */
974 * 0 when searching for first character in a field not IFS white space
975 * 1 when copying the text of a field
976 * 2 when searching for possible non-whitespace IFS
977 * 3 when searching for non-newline after copying field
982 if ((buflen
= TEMP_FAILURE_RETRY (__read (fildes
[0], buffer
,
985 if (TEMP_FAILURE_RETRY (__waitpid (pid
, &status
, WNOHANG
)) == 0)
987 if ((buflen
= TEMP_FAILURE_RETRY (__read (fildes
[0], buffer
,
992 for (i
= 0; i
< buflen
; ++i
)
994 if (strchr (ifs
, buffer
[i
]) != NULL
)
996 /* Current character is IFS */
997 if (strchr (ifs_white
, buffer
[i
]) == NULL
)
999 /* Current character is IFS but not whitespace */
1002 /* current character
1005 * eg: text<space><comma><space>moretext
1007 * So, strip whitespace IFS (like at the start)
1014 /* fall through and delimit field.. */
1018 if (buffer
[i
] == '\n')
1020 /* Current character is (IFS) newline */
1022 /* If copying a field, this is the end of it,
1023 but maybe all that's left is trailing newlines.
1024 So start searching for a non-newline. */
1032 /* Current character is IFS white space, but
1035 /* If not either copying a field or searching
1036 for non-newline after a field, ignore it */
1037 if (copying
!= 1 && copying
!= 3)
1040 /* End of field (search for non-ws IFS afterwards) */
1045 /* First IFS white space (non-newline), or IFS non-whitespace.
1046 * Delimit the field. Nulls are converted by w_addword. */
1047 if (w_addword (pwordexp
, *word
) == WRDE_NOSPACE
)
1050 *word
= w_newword (word_length
, max_length
);
1053 /* fall back round the loop.. */
1057 /* Not IFS character */
1061 /* Nothing but (IFS) newlines since the last field,
1062 so delimit it here before starting new word */
1063 if (w_addword (pwordexp
, *word
) == WRDE_NOSPACE
)
1066 *word
= w_newword (word_length
, max_length
);
1071 if (buffer
[i
] == '\n') /* happens if newline not in IFS */
1076 *word
= w_addchar (*word
, word_length
, max_length
,
1085 /* Chop off trailing newlines (required by POSIX.2) */
1086 /* Ensure we don't go back further than the beginning of the
1087 substitution (i.e. remove maxnewlines bytes at most) */
1088 while (maxnewlines
-- != 0 &&
1089 *word_length
> 0 && (*word
)[*word_length
- 1] == '\n')
1091 (*word
)[--*word_length
] = '\0';
1093 /* If the last word was entirely newlines, turn it into a new word
1094 * which can be ignored if there's nothing following it. */
1095 if (*word_length
== 0)
1098 *word
= w_newword (word_length
, max_length
);
1103 __close (fildes
[0]);
1106 /* Check for syntax error (re-execute but with "-n" flag) */
1107 if (buflen
< 1 && status
!= 0)
1116 __kill (pid
, SIGKILL
);
1117 TEMP_FAILURE_RETRY (__waitpid (pid
, NULL
, 0));
1118 __close (fildes
[0]);
1119 return WRDE_NOSPACE
;
1124 parse_comm (char **word
, size_t *word_length
, size_t *max_length
,
1125 const char *words
, size_t *offset
, int flags
, wordexp_t
*pwordexp
,
1126 const char *ifs
, const char *ifs_white
)
1128 /* We are poised just after "$(" */
1129 int paren_depth
= 1;
1131 int quoted
= 0; /* 1 for singly-quoted, 2 for doubly-quoted */
1134 char *comm
= w_newword (&comm_length
, &comm_maxlen
);
1136 for (; words
[*offset
]; ++(*offset
))
1138 switch (words
[*offset
])
1143 else if (quoted
== 1)
1151 else if (quoted
== 2)
1157 if (!quoted
&& --paren_depth
== 0)
1159 /* Go -- give script to the shell */
1162 #ifdef __libc_ptf_call
1163 /* We do not want the exec_comm call to be cut short
1164 by a thread cancellation since cleanup is very
1165 ugly. Therefore disable cancellation for
1167 // XXX Ideally we do want the thread being cancelable.
1168 // XXX If demand is there we'll change it.
1169 int state
= PTHREAD_CANCEL_ENABLE
;
1170 __libc_ptf_call (pthread_setcancelstate
,
1171 (PTHREAD_CANCEL_DISABLE
, &state
), 0);
1174 error
= exec_comm (comm
, word
, word_length
, max_length
,
1175 flags
, pwordexp
, ifs
, ifs_white
);
1177 #ifdef __libc_ptf_call
1178 __libc_ptf_call (pthread_setcancelstate
, (state
, NULL
), 0);
1187 /* This is just part of the script */
1195 comm
= w_addchar (comm
, &comm_length
, &comm_maxlen
, words
[*offset
]);
1197 return WRDE_NOSPACE
;
1200 /* Premature end. */
1208 parse_param (char **word
, size_t *word_length
, size_t *max_length
,
1209 const char *words
, size_t *offset
, int flags
, wordexp_t
*pwordexp
,
1210 const char *ifs
, const char *ifs_white
, int quoted
)
1212 /* We are poised just after "$" */
1216 ACT_RP_SHORT_LEFT
= '#',
1217 ACT_RP_LONG_LEFT
= 'L',
1218 ACT_RP_SHORT_RIGHT
= '%',
1219 ACT_RP_LONG_RIGHT
= 'R',
1220 ACT_NULL_ERROR
= '?',
1221 ACT_NULL_SUBST
= '-',
1222 ACT_NONNULL_SUBST
= '+',
1223 ACT_NULL_ASSIGN
= '='
1229 size_t start
= *offset
;
1233 enum action action
= ACT_NONE
;
1238 int pattern_is_quoted
= 0; /* 1 for singly-quoted, 2 for doubly-quoted */
1242 int brace
= words
[*offset
] == '{';
1244 env
= w_newword (&env_length
, &env_maxlen
);
1245 pattern
= w_newword (&pat_length
, &pat_maxlen
);
1250 /* First collect the parameter name. */
1252 if (words
[*offset
] == '#')
1260 if (isalpha (words
[*offset
]) || words
[*offset
] == '_')
1262 /* Normal parameter name. */
1265 env
= w_addchar (env
, &env_length
, &env_maxlen
,
1270 while (isalnum (words
[++*offset
]) || words
[*offset
] == '_');
1272 else if (isdigit (words
[*offset
]))
1274 /* Numeric parameter name. */
1278 env
= w_addchar (env
, &env_length
, &env_maxlen
,
1285 while (isdigit(words
[++*offset
]));
1287 else if (strchr ("*@$", words
[*offset
]) != NULL
)
1289 /* Special parameter. */
1291 env
= w_addchar (env
, &env_length
, &env_maxlen
,
1305 /* Check for special action to be applied to the value. */
1306 switch (words
[*offset
])
1313 action
= ACT_RP_SHORT_LEFT
;
1314 if (words
[1 + *offset
] == '#')
1317 action
= ACT_RP_LONG_LEFT
;
1322 action
= ACT_RP_SHORT_RIGHT
;
1323 if (words
[1 + *offset
] == '%')
1326 action
= ACT_RP_LONG_RIGHT
;
1331 if (strchr ("-=?+", words
[1 + *offset
]) == NULL
)
1335 action
= words
[++*offset
];
1342 action
= words
[*offset
];
1349 /* Now collect the pattern, but don't expand it yet. */
1351 for (; words
[*offset
]; ++(*offset
))
1353 switch (words
[*offset
])
1356 if (!pattern_is_quoted
)
1361 if (!pattern_is_quoted
)
1370 if (pattern_is_quoted
)
1371 /* Quoted; treat as normal character. */
1374 /* Otherwise, it's an escape: next character is literal. */
1375 if (words
[++*offset
] == '\0')
1378 pattern
= w_addchar (pattern
, &pat_length
, &pat_maxlen
, '\\');
1379 if (pattern
== NULL
)
1385 if (pattern_is_quoted
== 0)
1386 pattern_is_quoted
= 1;
1387 else if (pattern_is_quoted
== 1)
1388 pattern_is_quoted
= 0;
1393 if (pattern_is_quoted
== 0)
1394 pattern_is_quoted
= 2;
1395 else if (pattern_is_quoted
== 2)
1396 pattern_is_quoted
= 0;
1401 pattern
= w_addchar (pattern
, &pat_length
, &pat_maxlen
,
1403 if (pattern
== NULL
)
1408 /* End of input string -- remember to reparse the character that we
1413 if (words
[start
] == '{' && words
[*offset
] != '}')
1420 /* $# expands to the number of positional parameters */
1422 value
= _itoa_word (__libc_argc
- 1, &buffer
[20], 10, 0);
1427 /* Just $ on its own */
1428 *offset
= start
- 1;
1429 *word
= w_addchar (*word
, word_length
, max_length
, '$');
1430 return *word
? 0 : WRDE_NOSPACE
;
1433 /* Is it a numeric parameter? */
1434 else if (isdigit (env
[0]))
1438 if (n
>= __libc_argc
)
1439 /* Substitute NULL. */
1442 /* Replace with appropriate positional parameter. */
1443 value
= __libc_argv
[n
];
1445 /* Is it a special parameter? */
1452 value
= _itoa_word (__getpid (), &buffer
[20], 10, 0);
1454 /* Is it `${#*}' or `${#@}'? */
1455 else if ((*env
== '*' || *env
== '@') && seen_hash
)
1458 value
= _itoa_word (__libc_argc
> 0 ? __libc_argc
- 1 : 0,
1459 &buffer
[20], 10, 0);
1460 *word
= w_addstr (*word
, word_length
, max_length
, value
);
1463 return *word
? 0 : WRDE_NOSPACE
;
1465 /* Is it `$*' or `$@' (unquoted) ? */
1466 else if (*env
== '*' || (*env
== '@' && !quoted
))
1468 size_t plist_len
= 0;
1472 /* Build up value parameter by parameter (copy them) */
1473 for (p
= 1; __libc_argv
[p
]; ++p
)
1474 plist_len
+= strlen (__libc_argv
[p
]) + 1; /* for space */
1475 value
= malloc (plist_len
);
1480 for (p
= 1; __libc_argv
[p
]; ++p
)
1484 end
= __stpcpy (end
, __libc_argv
[p
]);
1491 /* Must be a quoted `$@' */
1492 assert (*env
== '@' && quoted
);
1494 /* Each parameter is a separate word ("$@") */
1495 if (__libc_argc
== 2)
1496 value
= __libc_argv
[1];
1497 else if (__libc_argc
> 2)
1501 /* Append first parameter to current word. */
1502 value
= w_addstr (*word
, word_length
, max_length
,
1504 if (value
== NULL
|| w_addword (pwordexp
, value
))
1507 for (p
= 2; __libc_argv
[p
+ 1]; p
++)
1509 char *newword
= __strdup (__libc_argv
[p
]);
1510 if (newword
== NULL
|| w_addword (pwordexp
, newword
))
1514 /* Start a new word with the last parameter. */
1515 *word
= w_newword (word_length
, max_length
);
1516 value
= __libc_argv
[p
];
1527 value
= getenv (env
);
1529 if (value
== NULL
&& (flags
& WRDE_UNDEF
))
1531 /* Variable not defined. */
1532 error
= WRDE_BADVAL
;
1536 if (action
!= ACT_NONE
)
1538 int expand_pattern
= 0;
1540 /* First, find out if we need to expand pattern (i.e. if we will
1544 case ACT_RP_SHORT_LEFT
:
1545 case ACT_RP_LONG_LEFT
:
1546 case ACT_RP_SHORT_RIGHT
:
1547 case ACT_RP_LONG_RIGHT
:
1548 /* Always expand for these. */
1552 case ACT_NULL_ERROR
:
1553 case ACT_NULL_SUBST
:
1554 case ACT_NULL_ASSIGN
:
1555 if (!value
|| (!*value
&& colon_seen
))
1556 /* If param is unset, or set but null and a colon has been seen,
1557 the expansion of the pattern will be needed. */
1562 case ACT_NONNULL_SUBST
:
1563 /* Expansion of word will be needed if parameter is set and not null,
1564 or set null but no colon has been seen. */
1565 if (value
&& (*value
|| !colon_seen
))
1571 assert (! "Unrecognised action!");
1576 /* We need to perform tilde expansion, parameter expansion,
1577 command substitution, and arithmetic expansion. We also
1578 have to be a bit careful with wildcard characters, as
1579 pattern might be given to fnmatch soon. To do this, we
1580 convert quotes to escapes. */
1586 int quoted
= 0; /* 1: single quotes; 2: double */
1588 expanded
= w_newword (&exp_len
, &exp_maxl
);
1589 for (p
= pattern
; p
&& *p
; p
++)
1598 else if (quoted
== 0)
1607 else if (quoted
== 0)
1617 /* Convert quoted wildchar to escaped wildchar. */
1618 expanded
= w_addchar (expanded
, &exp_len
,
1621 if (expanded
== NULL
)
1628 error
= parse_dollars (&expanded
, &exp_len
, &exp_maxl
, p
,
1629 &offset
, flags
, NULL
, NULL
, NULL
, 1);
1644 if (quoted
|| exp_len
)
1648 error
= parse_tilde (&expanded
, &exp_len
, &exp_maxl
, p
,
1664 expanded
= w_addchar (expanded
, &exp_len
, &exp_maxl
, '\\');
1666 assert (*p
); /* checked when extracted initially */
1667 if (expanded
== NULL
)
1671 expanded
= w_addchar (expanded
, &exp_len
, &exp_maxl
, *p
);
1673 if (expanded
== NULL
)
1684 case ACT_RP_SHORT_LEFT
:
1685 case ACT_RP_LONG_LEFT
:
1686 case ACT_RP_SHORT_RIGHT
:
1687 case ACT_RP_LONG_RIGHT
:
1693 if (value
== NULL
|| pattern
== NULL
|| *pattern
== '\0')
1696 end
= value
+ strlen (value
);
1700 case ACT_RP_SHORT_LEFT
:
1701 for (p
= value
; p
<= end
; ++p
)
1705 if (fnmatch (pattern
, value
, 0) != FNM_NOMATCH
)
1710 char *newval
= __strdup (p
);
1728 case ACT_RP_LONG_LEFT
:
1729 for (p
= end
; p
>= value
; --p
)
1733 if (fnmatch (pattern
, value
, 0) != FNM_NOMATCH
)
1738 char *newval
= __strdup (p
);
1756 case ACT_RP_SHORT_RIGHT
:
1757 for (p
= end
; p
>= value
; --p
)
1759 if (fnmatch (pattern
, p
, 0) != FNM_NOMATCH
)
1762 newval
= malloc (p
- value
+ 1);
1771 *(char *) __mempcpy (newval
, value
, p
- value
) = '\0';
1782 case ACT_RP_LONG_RIGHT
:
1783 for (p
= value
; p
<= end
; ++p
)
1785 if (fnmatch (pattern
, p
, 0) != FNM_NOMATCH
)
1788 newval
= malloc (p
- value
+ 1);
1797 *(char *) __mempcpy (newval
, value
, p
- value
) = '\0';
1815 case ACT_NULL_ERROR
:
1816 if (value
&& *value
)
1817 /* Substitute parameter */
1821 if (!colon_seen
&& value
)
1822 /* Substitute NULL */
1826 const char *str
= pattern
;
1829 str
= _("parameter null or not set");
1831 __fxprintf (NULL
, "%s: %s\n", env
, str
);
1838 case ACT_NULL_SUBST
:
1839 if (value
&& *value
)
1840 /* Substitute parameter */
1846 if (!colon_seen
&& value
)
1847 /* Substitute NULL */
1850 value
= pattern
? __strdup (pattern
) : pattern
;
1853 if (pattern
&& !value
)
1858 case ACT_NONNULL_SUBST
:
1859 if (value
&& (*value
|| !colon_seen
))
1864 value
= pattern
? __strdup (pattern
) : pattern
;
1867 if (pattern
&& !value
)
1873 /* Substitute NULL */
1878 case ACT_NULL_ASSIGN
:
1879 if (value
&& *value
)
1880 /* Substitute parameter */
1883 if (!colon_seen
&& value
)
1885 /* Substitute NULL */
1894 value
= pattern
? __strdup (pattern
) : pattern
;
1897 if (pattern
&& !value
)
1900 __setenv (env
, value
, 1);
1904 assert (! "Unrecognised action!");
1915 char param_length
[21];
1916 param_length
[20] = '\0';
1917 *word
= w_addstr (*word
, word_length
, max_length
,
1918 _itoa_word (value
? strlen (value
) : 0,
1919 ¶m_length
[20], 10, 0));
1922 assert (value
!= NULL
);
1926 return *word
? 0 : WRDE_NOSPACE
;
1932 if (quoted
|| !pwordexp
)
1934 /* Quoted - no field split */
1935 *word
= w_addstr (*word
, word_length
, max_length
, value
);
1939 return *word
? 0 : WRDE_NOSPACE
;
1943 /* Need to field-split */
1944 char *value_copy
= __strdup (value
); /* Don't modify value */
1945 char *field_begin
= value_copy
;
1946 int seen_nonws_ifs
= 0;
1951 if (value_copy
== NULL
)
1956 char *field_end
= field_begin
;
1959 /* If this isn't the first field, start a new word */
1960 if (field_begin
!= value_copy
)
1962 if (w_addword (pwordexp
, *word
) == WRDE_NOSPACE
)
1968 *word
= w_newword (word_length
, max_length
);
1971 /* Skip IFS whitespace before the field */
1972 field_begin
+= strspn (field_begin
, ifs_white
);
1974 if (!seen_nonws_ifs
&& *field_begin
== 0)
1975 /* Nothing but whitespace */
1978 /* Search for the end of the field */
1979 field_end
= field_begin
+ strcspn (field_begin
, ifs
);
1981 /* Set up pointer to the character after end of field and
1982 skip whitespace IFS after it. */
1983 next_field
= field_end
+ strspn (field_end
, ifs_white
);
1985 /* Skip at most one non-whitespace IFS character after the field */
1987 if (*next_field
&& strchr (ifs
, *next_field
))
1993 /* Null-terminate it */
1996 /* Tag a copy onto the current word */
1997 *word
= w_addstr (*word
, word_length
, max_length
, field_begin
);
1999 if (*word
== NULL
&& *field_begin
!= '\0')
2005 field_begin
= next_field
;
2007 while (seen_nonws_ifs
|| *field_begin
);
2019 error
= WRDE_NOSPACE
;
2023 error
= WRDE_SYNTAX
;
2035 parse_dollars (char **word
, size_t *word_length
, size_t *max_length
,
2036 const char *words
, size_t *offset
, int flags
,
2037 wordexp_t
*pwordexp
, const char *ifs
, const char *ifs_white
,
2040 /* We are poised _at_ "$" */
2041 switch (words
[1 + *offset
])
2046 *word
= w_addchar (*word
, word_length
, max_length
, '$');
2047 return *word
? 0 : WRDE_NOSPACE
;
2050 if (words
[2 + *offset
] == '(')
2052 /* Differentiate between $((1+3)) and $((echo);(ls)) */
2053 int i
= 3 + *offset
;
2055 while (words
[i
] && !(depth
== 0 && words
[i
] == ')'))
2057 if (words
[i
] == '(')
2059 else if (words
[i
] == ')')
2065 if (words
[i
] == ')' && words
[i
+ 1] == ')')
2068 /* Call parse_arith -- 0 is for "no brackets" */
2069 return parse_arith (word
, word_length
, max_length
, words
, offset
,
2074 if (flags
& WRDE_NOCMD
)
2078 return parse_comm (word
, word_length
, max_length
, words
, offset
, flags
,
2079 quoted
? NULL
: pwordexp
, ifs
, ifs_white
);
2083 /* Call parse_arith -- 1 is for "brackets" */
2084 return parse_arith (word
, word_length
, max_length
, words
, offset
, flags
,
2089 ++(*offset
); /* parse_param needs to know if "{" is there */
2090 return parse_param (word
, word_length
, max_length
, words
, offset
, flags
,
2091 pwordexp
, ifs
, ifs_white
, quoted
);
2097 parse_backtick (char **word
, size_t *word_length
, size_t *max_length
,
2098 const char *words
, size_t *offset
, int flags
,
2099 wordexp_t
*pwordexp
, const char *ifs
, const char *ifs_white
)
2101 /* We are poised just after "`" */
2106 char *comm
= w_newword (&comm_length
, &comm_maxlen
);
2108 for (; words
[*offset
]; ++(*offset
))
2110 switch (words
[*offset
])
2113 /* Go -- give the script to the shell */
2114 error
= exec_comm (comm
, word
, word_length
, max_length
, flags
,
2115 pwordexp
, ifs
, ifs_white
);
2122 error
= parse_qtd_backslash (&comm
, &comm_length
, &comm_maxlen
,
2135 error
= parse_backslash (&comm
, &comm_length
, &comm_maxlen
, words
,
2147 squoting
= 1 - squoting
;
2149 comm
= w_addchar (comm
, &comm_length
, &comm_maxlen
, words
[*offset
]);
2151 return WRDE_NOSPACE
;
2162 parse_dquote (char **word
, size_t *word_length
, size_t *max_length
,
2163 const char *words
, size_t *offset
, int flags
,
2164 wordexp_t
*pwordexp
, const char * ifs
, const char * ifs_white
)
2166 /* We are poised just after a double-quote */
2169 for (; words
[*offset
]; ++(*offset
))
2171 switch (words
[*offset
])
2177 error
= parse_dollars (word
, word_length
, max_length
, words
, offset
,
2178 flags
, pwordexp
, ifs
, ifs_white
, 1);
2179 /* The ``1'' here is to tell parse_dollars not to
2180 * split the fields. It may need to, however ("$@").
2188 if (flags
& WRDE_NOCMD
)
2192 error
= parse_backtick (word
, word_length
, max_length
, words
,
2193 offset
, flags
, NULL
, NULL
, NULL
);
2194 /* The first NULL here is to tell parse_backtick not to
2203 error
= parse_qtd_backslash (word
, word_length
, max_length
, words
,
2212 *word
= w_addchar (*word
, word_length
, max_length
, words
[*offset
]);
2214 return WRDE_NOSPACE
;
2218 /* Unterminated string */
2223 * wordfree() is to be called after pwordexp is finished with.
2227 wordfree (wordexp_t
*pwordexp
)
2230 /* wordexp can set pwordexp to NULL */
2231 if (pwordexp
&& pwordexp
->we_wordv
)
2233 char **wordv
= pwordexp
->we_wordv
;
2235 for (wordv
+= pwordexp
->we_offs
; *wordv
; ++wordv
)
2238 free (pwordexp
->we_wordv
);
2239 pwordexp
->we_wordv
= NULL
;
2242 libc_hidden_def (wordfree
)
2249 wordexp (const char *words
, wordexp_t
*pwordexp
, int flags
)
2251 size_t words_offset
;
2254 char *word
= w_newword (&word_length
, &max_length
);
2258 wordexp_t old_word
= *pwordexp
;
2260 if (flags
& WRDE_REUSE
)
2262 /* Minimal implementation of WRDE_REUSE for now */
2263 wordfree (pwordexp
);
2264 old_word
.we_wordv
= NULL
;
2267 if ((flags
& WRDE_APPEND
) == 0)
2269 pwordexp
->we_wordc
= 0;
2271 if (flags
& WRDE_DOOFFS
)
2273 pwordexp
->we_wordv
= calloc (1 + pwordexp
->we_offs
, sizeof (char *));
2274 if (pwordexp
->we_wordv
== NULL
)
2276 error
= WRDE_NOSPACE
;
2282 pwordexp
->we_wordv
= calloc (1, sizeof (char *));
2283 if (pwordexp
->we_wordv
== NULL
)
2285 error
= WRDE_NOSPACE
;
2289 pwordexp
->we_offs
= 0;
2293 /* Find out what the field separators are.
2294 * There are two types: whitespace and non-whitespace.
2296 ifs
= getenv ("IFS");
2299 /* IFS unset - use <space><tab><newline>. */
2300 ifs
= strcpy (ifs_white
, " \t\n");
2304 char *whch
= ifs_white
;
2306 while (*ifsch
!= '\0')
2308 if (*ifsch
== ' ' || *ifsch
== '\t' || *ifsch
== '\n')
2310 /* Whitespace IFS. See first whether it is already in our
2312 char *runp
= ifs_white
;
2314 while (runp
< whch
&& *runp
!= *ifsch
)
2326 for (words_offset
= 0 ; words
[words_offset
] ; ++words_offset
)
2327 switch (words
[words_offset
])
2330 error
= parse_backslash (&word
, &word_length
, &max_length
, words
,
2339 error
= parse_dollars (&word
, &word_length
, &max_length
, words
,
2340 &words_offset
, flags
, pwordexp
, ifs
, ifs_white
,
2349 if (flags
& WRDE_NOCMD
)
2351 error
= WRDE_CMDSUB
;
2356 error
= parse_backtick (&word
, &word_length
, &max_length
, words
,
2357 &words_offset
, flags
, pwordexp
, ifs
,
2367 error
= parse_dquote (&word
, &word_length
, &max_length
, words
,
2368 &words_offset
, flags
, pwordexp
, ifs
, ifs_white
);
2375 error
= w_addword (pwordexp
, NULL
);
2385 error
= parse_squote (&word
, &word_length
, &max_length
, words
,
2393 error
= w_addword (pwordexp
, NULL
);
2402 error
= parse_tilde (&word
, &word_length
, &max_length
, words
,
2403 &words_offset
, pwordexp
->we_wordc
);
2413 error
= parse_glob (&word
, &word_length
, &max_length
, words
,
2414 &words_offset
, flags
, pwordexp
, ifs
, ifs_white
);
2422 /* Is it a word separator? */
2423 if (strchr (" \t", words
[words_offset
]) == NULL
)
2425 char ch
= words
[words_offset
];
2427 /* Not a word separator -- but is it a valid word char? */
2428 if (strchr ("\n|&;<>(){}", ch
))
2431 error
= WRDE_BADCHAR
;
2435 /* "Ordinary" character -- add it to word */
2436 word
= w_addchar (word
, &word_length
, &max_length
,
2440 error
= WRDE_NOSPACE
;
2447 /* If a word has been delimited, add it to the list. */
2450 error
= w_addword (pwordexp
, word
);
2455 word
= w_newword (&word_length
, &max_length
);
2460 /* There was a word separator at the end */
2461 if (word
== NULL
) /* i.e. w_newword */
2464 /* There was no field separator at the end */
2465 return w_addword (pwordexp
, word
);
2469 * free memory used (unless error is WRDE_NOSPACE), and
2470 * set pwordexp members back to what they were.
2475 if (error
== WRDE_NOSPACE
)
2476 return WRDE_NOSPACE
;
2478 if ((flags
& WRDE_APPEND
) == 0)
2479 wordfree (pwordexp
);
2481 *pwordexp
= old_word
;