1 /* POSIX.2 wordexp implementation.
2 Copyright (C) 1997-2018 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/>. */
34 #include <sys/param.h>
37 #include <sys/types.h>
38 #include <sys/types.h>
43 #include <kernel-features.h>
45 #include <libc-lock.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
);
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
);
72 static int parse_dquote (char **word
, size_t *word_length
, size_t *max_length
,
73 const char *words
, size_t *offset
, int flags
,
74 wordexp_t
*pwordexp
, const char *ifs
,
75 const char *ifs_white
);
76 static int eval_expr (char *expr
, long int *result
);
78 /* The w_*() functions manipulate word lists. */
82 /* Result of w_newword will be ignored if it's the last word. */
84 w_newword (size_t *actlen
, size_t *maxlen
)
86 *actlen
= *maxlen
= 0;
91 w_addchar (char *buffer
, size_t *actlen
, size_t *maxlen
, char ch
)
92 /* (lengths exclude trailing zero) */
94 /* Add a character to the buffer, allocating room for it if needed. */
96 if (*actlen
== *maxlen
)
98 char *old_buffer
= buffer
;
99 assert (buffer
== NULL
|| *maxlen
!= 0);
101 buffer
= (char *) realloc (buffer
, 1 + *maxlen
);
109 buffer
[*actlen
] = ch
;
110 buffer
[++(*actlen
)] = '\0';
117 w_addmem (char *buffer
, size_t *actlen
, size_t *maxlen
, const char *str
,
120 /* Add a string to the buffer, allocating room for it if needed.
122 if (*actlen
+ len
> *maxlen
)
124 char *old_buffer
= buffer
;
125 assert (buffer
== NULL
|| *maxlen
!= 0);
126 *maxlen
+= MAX (2 * len
, W_CHUNK
);
127 buffer
= realloc (old_buffer
, 1 + *maxlen
);
135 *((char *) __mempcpy (&buffer
[*actlen
], str
, len
)) = '\0';
143 w_addstr (char *buffer
, size_t *actlen
, size_t *maxlen
, const char *str
)
144 /* (lengths exclude trailing zero) */
146 /* Add a string to the buffer, allocating room for it if needed.
150 assert (str
!= NULL
); /* w_addstr only called from this file */
153 return w_addmem (buffer
, actlen
, maxlen
, str
, len
);
157 w_addword (wordexp_t
*pwordexp
, char *word
)
159 /* Add a word to the wordlist */
162 bool allocated
= false;
164 /* Internally, NULL acts like "". Convert NULLs to "" before
165 * the caller sees them.
169 word
= __strdup ("");
175 num_p
= 2 + pwordexp
->we_wordc
+ pwordexp
->we_offs
;
176 new_wordv
= realloc (pwordexp
->we_wordv
, sizeof (char *) * num_p
);
177 if (new_wordv
!= NULL
)
179 pwordexp
->we_wordv
= new_wordv
;
180 pwordexp
->we_wordv
[pwordexp
->we_offs
+ pwordexp
->we_wordc
++] = word
;
181 pwordexp
->we_wordv
[pwordexp
->we_offs
+ pwordexp
->we_wordc
] = NULL
;
192 /* The parse_*() functions should leave *offset being the offset in 'words'
193 * to the last character processed.
197 parse_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, not in quotes */
202 switch (words
[1 + *offset
])
205 /* Backslash is last character of input words */
213 *word
= w_addchar (*word
, word_length
, max_length
, words
[1 + *offset
]);
225 parse_qtd_backslash (char **word
, size_t *word_length
, size_t *max_length
,
226 const char *words
, size_t *offset
)
228 /* We are poised _at_ a backslash, inside quotes */
230 switch (words
[1 + *offset
])
233 /* Backslash is last character of input words */
244 *word
= w_addchar (*word
, word_length
, max_length
, words
[1 + *offset
]);
252 *word
= w_addchar (*word
, word_length
, max_length
, words
[*offset
]);
254 *word
= w_addchar (*word
, word_length
, max_length
, words
[1 + *offset
]);
267 parse_tilde (char **word
, size_t *word_length
, size_t *max_length
,
268 const char *words
, size_t *offset
, size_t wordc
)
270 /* We are poised _at_ a tilde */
273 if (*word_length
!= 0)
275 if (!((*word
)[*word_length
- 1] == '=' && wordc
== 0))
277 if (!((*word
)[*word_length
- 1] == ':'
278 && strchr (*word
, '=') && wordc
== 0))
280 *word
= w_addchar (*word
, word_length
, max_length
, '~');
281 return *word
? 0 : WRDE_NOSPACE
;
286 for (i
= 1 + *offset
; words
[i
]; i
++)
288 if (words
[i
] == ':' || words
[i
] == '/' || words
[i
] == ' ' ||
289 words
[i
] == '\t' || words
[i
] == 0 )
292 if (words
[i
] == '\\')
294 *word
= w_addchar (*word
, word_length
, max_length
, '~');
295 return *word
? 0 : WRDE_NOSPACE
;
299 if (i
== 1 + *offset
)
301 /* Tilde appears on its own */
303 struct passwd pwd
, *tpwd
;
309 /* POSIX.2 says ~ expands to $HOME and if HOME is unset the
310 results are unspecified. We do a lookup on the uid if
313 home
= getenv ("HOME");
316 *word
= w_addstr (*word
, word_length
, max_length
, home
);
323 buffer
= __alloca (buflen
);
325 while ((result
= __getpwuid_r (uid
, &pwd
, buffer
, buflen
, &tpwd
)) != 0
327 buffer
= extend_alloca (buffer
, buflen
, buflen
+ 1000);
329 if (result
== 0 && tpwd
!= NULL
&& pwd
.pw_dir
!= NULL
)
331 *word
= w_addstr (*word
, word_length
, max_length
, pwd
.pw_dir
);
337 *word
= w_addchar (*word
, word_length
, max_length
, '~');
345 /* Look up user name in database to get home directory */
346 char *user
= strndupa (&words
[1 + *offset
], i
- (1 + *offset
));
347 struct passwd pwd
, *tpwd
;
349 char* buffer
= __alloca (buflen
);
352 while ((result
= __getpwnam_r (user
, &pwd
, buffer
, buflen
, &tpwd
)) != 0
354 buffer
= extend_alloca (buffer
, buflen
, buflen
+ 1000);
356 if (result
== 0 && tpwd
!= NULL
&& pwd
.pw_dir
)
357 *word
= w_addstr (*word
, word_length
, max_length
, pwd
.pw_dir
);
360 /* (invalid login name) */
361 *word
= w_addchar (*word
, word_length
, max_length
, '~');
363 *word
= w_addstr (*word
, word_length
, max_length
, user
);
368 return *word
? 0 : WRDE_NOSPACE
;
373 do_parse_glob (const char *glob_word
, char **word
, size_t *word_length
,
374 size_t *max_length
, wordexp_t
*pwordexp
, const char *ifs
,
375 const char *ifs_white
)
381 error
= glob (glob_word
, GLOB_NOCHECK
, NULL
, &globbuf
);
385 /* We can only run into memory problems. */
386 assert (error
== GLOB_NOSPACE
);
392 /* No field splitting allowed. */
393 assert (globbuf
.gl_pathv
[0] != NULL
);
394 *word
= w_addstr (*word
, word_length
, max_length
, globbuf
.gl_pathv
[0]);
395 for (match
= 1; match
< globbuf
.gl_pathc
&& *word
!= NULL
; ++match
)
397 *word
= w_addchar (*word
, word_length
, max_length
, ' ');
399 *word
= w_addstr (*word
, word_length
, max_length
,
400 globbuf
.gl_pathv
[match
]);
404 return *word
? 0 : WRDE_NOSPACE
;
407 assert (ifs
== NULL
|| *ifs
!= '\0');
411 *word
= w_newword (word_length
, max_length
);
414 for (match
= 0; match
< globbuf
.gl_pathc
; ++match
)
416 char *matching_word
= __strdup (globbuf
.gl_pathv
[match
]);
417 if (matching_word
== NULL
|| w_addword (pwordexp
, matching_word
))
429 parse_glob (char **word
, size_t *word_length
, size_t *max_length
,
430 const char *words
, size_t *offset
, int flags
,
431 wordexp_t
*pwordexp
, const char *ifs
, const char *ifs_white
)
433 /* We are poised just after a '*', a '[' or a '?'. */
434 int error
= WRDE_NOSPACE
;
435 int quoted
= 0; /* 1 if singly-quoted, 2 if doubly */
437 wordexp_t glob_list
; /* List of words to glob */
439 glob_list
.we_wordc
= 0;
440 glob_list
.we_wordv
= NULL
;
441 glob_list
.we_offs
= 0;
442 for (; words
[*offset
] != '\0'; ++*offset
)
444 if (strchr (ifs
, words
[*offset
]) != NULL
)
448 /* Sort out quoting */
449 if (words
[*offset
] == '\'')
456 else if (quoted
== 1)
462 else if (words
[*offset
] == '"')
469 else if (quoted
== 2)
476 /* Sort out other special characters */
477 if (quoted
!= 1 && words
[*offset
] == '$')
479 error
= parse_dollars (word
, word_length
, max_length
, words
,
480 offset
, flags
, &glob_list
, ifs
, ifs_white
,
487 else if (words
[*offset
] == '\\')
490 error
= parse_qtd_backslash (word
, word_length
, max_length
,
493 error
= parse_backslash (word
, word_length
, max_length
,
502 *word
= w_addchar (*word
, word_length
, max_length
, words
[*offset
]);
507 /* Don't forget to re-parse the character we stopped at. */
511 error
= w_addword (&glob_list
, *word
);
512 *word
= w_newword (word_length
, max_length
);
513 for (i
= 0; error
== 0 && i
< glob_list
.we_wordc
; i
++)
514 error
= do_parse_glob (glob_list
.we_wordv
[i
], word
, word_length
,
515 max_length
, pwordexp
, ifs
, ifs_white
);
519 wordfree (&glob_list
);
524 parse_squote (char **word
, size_t *word_length
, size_t *max_length
,
525 const char *words
, size_t *offset
)
527 /* We are poised just after a single quote */
528 for (; words
[*offset
]; ++(*offset
))
530 if (words
[*offset
] != '\'')
532 *word
= w_addchar (*word
, word_length
, max_length
, words
[*offset
]);
539 /* Unterminated string */
543 /* Functions to evaluate an arithmetic expression */
545 eval_expr_val (char **expr
, long int *result
)
549 /* Skip white space */
550 for (digit
= *expr
; digit
&& *digit
&& isspace (*digit
); ++digit
);
554 /* Scan for closing paren */
555 for (++digit
; **expr
&& **expr
!= ')'; ++(*expr
));
563 if (eval_expr (digit
, result
))
569 /* POSIX requires that decimal, octal, and hexadecimal constants are
570 recognized. Therefore we pass 0 as the third parameter to strtol. */
571 *result
= strtol (digit
, expr
, 0);
579 eval_expr_multdiv (char **expr
, long int *result
)
584 if (eval_expr_val (expr
, result
) != 0)
589 /* Skip white space */
590 for (; *expr
&& **expr
&& isspace (**expr
); ++(*expr
));
595 if (eval_expr_val (expr
, &arg
) != 0)
600 else if (**expr
== '/')
603 if (eval_expr_val (expr
, &arg
) != 0)
606 /* Division by zero or integer overflow. */
607 if (arg
== 0 || (arg
== -1 && *result
== LONG_MIN
))
619 eval_expr (char *expr
, long int *result
)
624 if (eval_expr_multdiv (&expr
, result
) != 0)
629 /* Skip white space */
630 for (; expr
&& *expr
&& isspace (*expr
); ++expr
);
635 if (eval_expr_multdiv (&expr
, &arg
) != 0)
640 else if (*expr
== '-')
643 if (eval_expr_multdiv (&expr
, &arg
) != 0)
655 parse_arith (char **word
, size_t *word_length
, size_t *max_length
,
656 const char *words
, size_t *offset
, int flags
, int bracket
)
658 /* We are poised just after "$((" or "$[" */
665 expr
= w_newword (&expr_length
, &expr_maxlen
);
666 for (; words
[*offset
]; ++(*offset
))
668 switch (words
[*offset
])
671 error
= parse_dollars (&expr
, &expr_length
, &expr_maxlen
,
672 words
, offset
, flags
, NULL
, NULL
, NULL
, 1);
673 /* The ``1'' here is to tell parse_dollars not to
685 error
= parse_backtick (&expr
, &expr_length
, &expr_maxlen
,
686 words
, offset
, flags
, NULL
, NULL
, NULL
);
687 /* The first NULL here is to tell parse_backtick not to
698 error
= parse_qtd_backslash (&expr
, &expr_length
, &expr_maxlen
,
705 /* I think that a backslash within an
706 * arithmetic expansion is bound to
707 * cause an error sooner or later anyway though.
712 if (--paren_depth
== 0)
714 char result
[21]; /* 21 = ceil(log10(2^64)) + 1 */
715 long int numresult
= 0;
716 long long int convertme
;
718 if (bracket
|| words
[1 + *offset
] != ')')
727 if (*expr
&& eval_expr (expr
, &numresult
) != 0)
735 convertme
= -numresult
;
736 *word
= w_addchar (*word
, word_length
, max_length
, '-');
744 convertme
= numresult
;
747 *word
= w_addstr (*word
, word_length
, max_length
,
748 _itoa (convertme
, &result
[20], 10, 0));
750 return *word
? 0 : WRDE_NOSPACE
;
752 expr
= w_addchar (expr
, &expr_length
, &expr_maxlen
, words
[*offset
]);
759 if (bracket
&& paren_depth
== 1)
761 char result
[21]; /* 21 = ceil(log10(2^64)) + 1 */
762 long int numresult
= 0;
765 if (*expr
&& eval_expr (expr
, &numresult
) != 0)
772 *word
= w_addstr (*word
, word_length
, max_length
,
773 _itoa_word (numresult
, &result
[20], 10, 0));
775 return *word
? 0 : WRDE_NOSPACE
;
791 expr
= w_addchar (expr
, &expr_length
, &expr_maxlen
, words
[*offset
]);
802 /* Function called by child process in exec_comm() */
804 __attribute__ ((always_inline
))
805 exec_comm_child (char *comm
, int *fildes
, int showerr
, int noexec
)
807 const char *args
[4] = { _PATH_BSHELL
, "-c", comm
, NULL
};
809 /* Execute the command, or just check syntax? */
813 /* Redirect output. */
814 if (__glibc_likely (fildes
[1] != STDOUT_FILENO
))
816 __dup2 (fildes
[1], STDOUT_FILENO
);
820 /* Reset the close-on-exec flag (if necessary). */
821 __fcntl (fildes
[1], F_SETFD
, 0);
823 /* Redirect stderr to /dev/null if we have to. */
828 __close (STDERR_FILENO
);
829 fd
= __open (_PATH_DEVNULL
, O_WRONLY
);
830 if (fd
>= 0 && fd
!= STDERR_FILENO
)
832 __dup2 (fd
, STDERR_FILENO
);
835 /* Be paranoid. Check that we actually opened the /dev/null
837 if (__builtin_expect (__fxstat64 (_STAT_VER
, STDERR_FILENO
, &st
), 0) != 0
838 || __builtin_expect (S_ISCHR (st
.st_mode
), 1) == 0
839 #if defined DEV_NULL_MAJOR && defined DEV_NULL_MINOR
840 || st
.st_rdev
!= makedev (DEV_NULL_MAJOR
, DEV_NULL_MINOR
)
843 /* It's not the /dev/null device. Stop right here. The
844 problem is: how do we stop? We use _exit() with an
845 hopefully unusual exit code. */
849 /* Make sure the subshell doesn't field-split on our behalf. */
853 __execve (_PATH_BSHELL
, (char *const *) args
, __environ
);
859 /* Function to execute a command and retrieve the results */
860 /* pwordexp contains NULL if field-splitting is forbidden */
862 exec_comm (char *comm
, char **word
, size_t *word_length
, size_t *max_length
,
863 int flags
, wordexp_t
*pwordexp
, const char *ifs
,
864 const char *ifs_white
)
871 size_t maxnewlines
= 0;
872 char buffer
[bufsize
];
876 /* Do nothing if command substitution should not succeed. */
877 if (flags
& WRDE_NOCMD
)
880 /* Don't fork() unless necessary */
884 if (__pipe2 (fildes
, O_CLOEXEC
) < 0)
888 if ((pid
= __fork ()) < 0)
897 exec_comm_child (comm
, fildes
, noexec
? 0 : flags
& WRDE_SHOWERR
, noexec
);
901 /* If we are just testing the syntax, only wait. */
903 return (TEMP_FAILURE_RETRY (__waitpid (pid
, &status
, 0)) == pid
904 && status
!= 0) ? WRDE_SYNTAX
: 0;
910 /* Quoted - no field splitting */
914 if ((buflen
= TEMP_FAILURE_RETRY (__read (fildes
[0], buffer
,
917 /* If read returned 0 then the process has closed its
918 stdout. Don't use WNOHANG in that case to avoid busy
919 looping until the process eventually exits. */
920 if (TEMP_FAILURE_RETRY (__waitpid (pid
, &status
,
921 buflen
== 0 ? 0 : WNOHANG
))
924 if ((buflen
= TEMP_FAILURE_RETRY (__read (fildes
[0], buffer
,
929 maxnewlines
+= buflen
;
931 *word
= w_addmem (*word
, word_length
, max_length
, buffer
, buflen
);
937 /* Not quoted - split fields */
941 * 0 when searching for first character in a field not IFS white space
942 * 1 when copying the text of a field
943 * 2 when searching for possible non-whitespace IFS
944 * 3 when searching for non-newline after copying field
949 if ((buflen
= TEMP_FAILURE_RETRY (__read (fildes
[0], buffer
,
952 /* If read returned 0 then the process has closed its
953 stdout. Don't use WNOHANG in that case to avoid busy
954 looping until the process eventually exits. */
955 if (TEMP_FAILURE_RETRY (__waitpid (pid
, &status
,
956 buflen
== 0 ? 0 : WNOHANG
))
959 if ((buflen
= TEMP_FAILURE_RETRY (__read (fildes
[0], buffer
,
964 for (i
= 0; i
< buflen
; ++i
)
966 if (strchr (ifs
, buffer
[i
]) != NULL
)
968 /* Current character is IFS */
969 if (strchr (ifs_white
, buffer
[i
]) == NULL
)
971 /* Current character is IFS but not whitespace */
977 * eg: text<space><comma><space>moretext
979 * So, strip whitespace IFS (like at the start)
986 /* fall through and delimit field.. */
990 if (buffer
[i
] == '\n')
992 /* Current character is (IFS) newline */
994 /* If copying a field, this is the end of it,
995 but maybe all that's left is trailing newlines.
996 So start searching for a non-newline. */
1004 /* Current character is IFS white space, but
1007 /* If not either copying a field or searching
1008 for non-newline after a field, ignore it */
1009 if (copying
!= 1 && copying
!= 3)
1012 /* End of field (search for non-ws IFS afterwards) */
1017 /* First IFS white space (non-newline), or IFS non-whitespace.
1018 * Delimit the field. Nulls are converted by w_addword. */
1019 if (w_addword (pwordexp
, *word
) == WRDE_NOSPACE
)
1022 *word
= w_newword (word_length
, max_length
);
1025 /* fall back round the loop.. */
1029 /* Not IFS character */
1033 /* Nothing but (IFS) newlines since the last field,
1034 so delimit it here before starting new word */
1035 if (w_addword (pwordexp
, *word
) == WRDE_NOSPACE
)
1038 *word
= w_newword (word_length
, max_length
);
1043 if (buffer
[i
] == '\n') /* happens if newline not in IFS */
1048 *word
= w_addchar (*word
, word_length
, max_length
,
1057 /* Chop off trailing newlines (required by POSIX.2) */
1058 /* Ensure we don't go back further than the beginning of the
1059 substitution (i.e. remove maxnewlines bytes at most) */
1060 while (maxnewlines
-- != 0 &&
1061 *word_length
> 0 && (*word
)[*word_length
- 1] == '\n')
1063 (*word
)[--*word_length
] = '\0';
1065 /* If the last word was entirely newlines, turn it into a new word
1066 * which can be ignored if there's nothing following it. */
1067 if (*word_length
== 0)
1070 *word
= w_newword (word_length
, max_length
);
1075 __close (fildes
[0]);
1078 /* Check for syntax error (re-execute but with "-n" flag) */
1079 if (buflen
< 1 && status
!= 0)
1088 __kill (pid
, SIGKILL
);
1089 TEMP_FAILURE_RETRY (__waitpid (pid
, NULL
, 0));
1090 __close (fildes
[0]);
1091 return WRDE_NOSPACE
;
1095 parse_comm (char **word
, size_t *word_length
, size_t *max_length
,
1096 const char *words
, size_t *offset
, int flags
, wordexp_t
*pwordexp
,
1097 const char *ifs
, const char *ifs_white
)
1099 /* We are poised just after "$(" */
1100 int paren_depth
= 1;
1102 int quoted
= 0; /* 1 for singly-quoted, 2 for doubly-quoted */
1105 char *comm
= w_newword (&comm_length
, &comm_maxlen
);
1107 for (; words
[*offset
]; ++(*offset
))
1109 switch (words
[*offset
])
1114 else if (quoted
== 1)
1122 else if (quoted
== 2)
1128 if (!quoted
&& --paren_depth
== 0)
1130 /* Go -- give script to the shell */
1133 #ifdef __libc_ptf_call
1134 /* We do not want the exec_comm call to be cut short
1135 by a thread cancellation since cleanup is very
1136 ugly. Therefore disable cancellation for
1138 // XXX Ideally we do want the thread being cancelable.
1139 // XXX If demand is there we'll change it.
1140 int state
= PTHREAD_CANCEL_ENABLE
;
1141 __libc_ptf_call (__pthread_setcancelstate
,
1142 (PTHREAD_CANCEL_DISABLE
, &state
), 0);
1145 error
= exec_comm (comm
, word
, word_length
, max_length
,
1146 flags
, pwordexp
, ifs
, ifs_white
);
1148 #ifdef __libc_ptf_call
1149 __libc_ptf_call (__pthread_setcancelstate
,
1159 /* This is just part of the script */
1167 comm
= w_addchar (comm
, &comm_length
, &comm_maxlen
, words
[*offset
]);
1169 return WRDE_NOSPACE
;
1172 /* Premature end. */
1178 #define CHAR_IN_SET(ch, char_set) \
1179 (memchr (char_set "", ch, sizeof (char_set) - 1) != NULL)
1182 parse_param (char **word
, size_t *word_length
, size_t *max_length
,
1183 const char *words
, size_t *offset
, int flags
, wordexp_t
*pwordexp
,
1184 const char *ifs
, const char *ifs_white
, int quoted
)
1186 /* We are poised just after "$" */
1190 ACT_RP_SHORT_LEFT
= '#',
1191 ACT_RP_LONG_LEFT
= 'L',
1192 ACT_RP_SHORT_RIGHT
= '%',
1193 ACT_RP_LONG_RIGHT
= 'R',
1194 ACT_NULL_ERROR
= '?',
1195 ACT_NULL_SUBST
= '-',
1196 ACT_NONNULL_SUBST
= '+',
1197 ACT_NULL_ASSIGN
= '='
1203 size_t start
= *offset
;
1207 enum action action
= ACT_NONE
;
1212 int pattern_is_quoted
= 0; /* 1 for singly-quoted, 2 for doubly-quoted */
1216 int brace
= words
[*offset
] == '{';
1218 env
= w_newword (&env_length
, &env_maxlen
);
1219 pattern
= w_newword (&pat_length
, &pat_maxlen
);
1224 /* First collect the parameter name. */
1226 if (words
[*offset
] == '#')
1234 if (isalpha (words
[*offset
]) || words
[*offset
] == '_')
1236 /* Normal parameter name. */
1239 env
= w_addchar (env
, &env_length
, &env_maxlen
,
1244 while (isalnum (words
[++*offset
]) || words
[*offset
] == '_');
1246 else if (isdigit (words
[*offset
]))
1248 /* Numeric parameter name. */
1252 env
= w_addchar (env
, &env_length
, &env_maxlen
,
1259 while (isdigit(words
[++*offset
]));
1261 else if (CHAR_IN_SET (words
[*offset
], "*@$"))
1263 /* Special parameter. */
1265 env
= w_addchar (env
, &env_length
, &env_maxlen
,
1279 /* Check for special action to be applied to the value. */
1280 switch (words
[*offset
])
1287 action
= ACT_RP_SHORT_LEFT
;
1288 if (words
[1 + *offset
] == '#')
1291 action
= ACT_RP_LONG_LEFT
;
1296 action
= ACT_RP_SHORT_RIGHT
;
1297 if (words
[1 + *offset
] == '%')
1300 action
= ACT_RP_LONG_RIGHT
;
1305 if (!CHAR_IN_SET (words
[1 + *offset
], "-=?+"))
1309 action
= words
[++*offset
];
1316 action
= words
[*offset
];
1323 /* Now collect the pattern, but don't expand it yet. */
1325 for (; words
[*offset
]; ++(*offset
))
1327 switch (words
[*offset
])
1330 if (!pattern_is_quoted
)
1335 if (!pattern_is_quoted
)
1344 if (pattern_is_quoted
)
1345 /* Quoted; treat as normal character. */
1348 /* Otherwise, it's an escape: next character is literal. */
1349 if (words
[++*offset
] == '\0')
1352 pattern
= w_addchar (pattern
, &pat_length
, &pat_maxlen
, '\\');
1353 if (pattern
== NULL
)
1359 if (pattern_is_quoted
== 0)
1360 pattern_is_quoted
= 1;
1361 else if (pattern_is_quoted
== 1)
1362 pattern_is_quoted
= 0;
1367 if (pattern_is_quoted
== 0)
1368 pattern_is_quoted
= 2;
1369 else if (pattern_is_quoted
== 2)
1370 pattern_is_quoted
= 0;
1375 pattern
= w_addchar (pattern
, &pat_length
, &pat_maxlen
,
1377 if (pattern
== NULL
)
1382 /* End of input string -- remember to reparse the character that we
1387 if (words
[start
] == '{' && words
[*offset
] != '}')
1394 /* $# expands to the number of positional parameters */
1396 value
= _itoa_word (__libc_argc
- 1, &buffer
[20], 10, 0);
1401 /* Just $ on its own */
1402 *offset
= start
- 1;
1403 *word
= w_addchar (*word
, word_length
, max_length
, '$');
1404 return *word
? 0 : WRDE_NOSPACE
;
1407 /* Is it a numeric parameter? */
1408 else if (isdigit (env
[0]))
1412 if (n
>= __libc_argc
)
1413 /* Substitute NULL. */
1416 /* Replace with appropriate positional parameter. */
1417 value
= __libc_argv
[n
];
1419 /* Is it a special parameter? */
1426 value
= _itoa_word (__getpid (), &buffer
[20], 10, 0);
1428 /* Is it `${#*}' or `${#@}'? */
1429 else if ((*env
== '*' || *env
== '@') && seen_hash
)
1432 value
= _itoa_word (__libc_argc
> 0 ? __libc_argc
- 1 : 0,
1433 &buffer
[20], 10, 0);
1434 *word
= w_addstr (*word
, word_length
, max_length
, value
);
1437 return *word
? 0 : WRDE_NOSPACE
;
1439 /* Is it `$*' or `$@' (unquoted) ? */
1440 else if (*env
== '*' || (*env
== '@' && !quoted
))
1442 size_t plist_len
= 0;
1446 /* Build up value parameter by parameter (copy them) */
1447 for (p
= 1; __libc_argv
[p
]; ++p
)
1448 plist_len
+= strlen (__libc_argv
[p
]) + 1; /* for space */
1449 value
= malloc (plist_len
);
1454 for (p
= 1; __libc_argv
[p
]; ++p
)
1458 end
= __stpcpy (end
, __libc_argv
[p
]);
1465 /* Must be a quoted `$@' */
1466 assert (*env
== '@' && quoted
);
1468 /* Each parameter is a separate word ("$@") */
1469 if (__libc_argc
== 2)
1470 value
= __libc_argv
[1];
1471 else if (__libc_argc
> 2)
1475 /* Append first parameter to current word. */
1476 value
= w_addstr (*word
, word_length
, max_length
,
1478 if (value
== NULL
|| w_addword (pwordexp
, value
))
1481 for (p
= 2; __libc_argv
[p
+ 1]; p
++)
1483 char *newword
= __strdup (__libc_argv
[p
]);
1484 if (newword
== NULL
|| w_addword (pwordexp
, newword
))
1488 /* Start a new word with the last parameter. */
1489 *word
= w_newword (word_length
, max_length
);
1490 value
= __libc_argv
[p
];
1501 value
= getenv (env
);
1503 if (value
== NULL
&& (flags
& WRDE_UNDEF
))
1505 /* Variable not defined. */
1506 error
= WRDE_BADVAL
;
1510 if (action
!= ACT_NONE
)
1512 int expand_pattern
= 0;
1514 /* First, find out if we need to expand pattern (i.e. if we will
1518 case ACT_RP_SHORT_LEFT
:
1519 case ACT_RP_LONG_LEFT
:
1520 case ACT_RP_SHORT_RIGHT
:
1521 case ACT_RP_LONG_RIGHT
:
1522 /* Always expand for these. */
1526 case ACT_NULL_ERROR
:
1527 case ACT_NULL_SUBST
:
1528 case ACT_NULL_ASSIGN
:
1529 if (!value
|| (!*value
&& colon_seen
))
1530 /* If param is unset, or set but null and a colon has been seen,
1531 the expansion of the pattern will be needed. */
1536 case ACT_NONNULL_SUBST
:
1537 /* Expansion of word will be needed if parameter is set and not null,
1538 or set null but no colon has been seen. */
1539 if (value
&& (*value
|| !colon_seen
))
1545 assert (! "Unrecognised action!");
1550 /* We need to perform tilde expansion, parameter expansion,
1551 command substitution, and arithmetic expansion. We also
1552 have to be a bit careful with wildcard characters, as
1553 pattern might be given to fnmatch soon. To do this, we
1554 convert quotes to escapes. */
1560 int quoted
= 0; /* 1: single quotes; 2: double */
1562 expanded
= w_newword (&exp_len
, &exp_maxl
);
1563 for (p
= pattern
; p
&& *p
; p
++)
1572 else if (quoted
== 0)
1581 else if (quoted
== 0)
1591 /* Convert quoted wildchar to escaped wildchar. */
1592 expanded
= w_addchar (expanded
, &exp_len
,
1595 if (expanded
== NULL
)
1602 error
= parse_dollars (&expanded
, &exp_len
, &exp_maxl
, p
,
1603 &offset
, flags
, NULL
, NULL
, NULL
, 1);
1618 if (quoted
|| exp_len
)
1622 error
= parse_tilde (&expanded
, &exp_len
, &exp_maxl
, p
,
1638 expanded
= w_addchar (expanded
, &exp_len
, &exp_maxl
, '\\');
1640 assert (*p
); /* checked when extracted initially */
1641 if (expanded
== NULL
)
1645 expanded
= w_addchar (expanded
, &exp_len
, &exp_maxl
, *p
);
1647 if (expanded
== NULL
)
1658 case ACT_RP_SHORT_LEFT
:
1659 case ACT_RP_LONG_LEFT
:
1660 case ACT_RP_SHORT_RIGHT
:
1661 case ACT_RP_LONG_RIGHT
:
1667 if (value
== NULL
|| pattern
== NULL
|| *pattern
== '\0')
1670 end
= value
+ strlen (value
);
1674 case ACT_RP_SHORT_LEFT
:
1675 for (p
= value
; p
<= end
; ++p
)
1679 if (fnmatch (pattern
, value
, 0) != FNM_NOMATCH
)
1684 char *newval
= __strdup (p
);
1702 case ACT_RP_LONG_LEFT
:
1703 for (p
= end
; p
>= value
; --p
)
1707 if (fnmatch (pattern
, value
, 0) != FNM_NOMATCH
)
1712 char *newval
= __strdup (p
);
1730 case ACT_RP_SHORT_RIGHT
:
1731 for (p
= end
; p
>= value
; --p
)
1733 if (fnmatch (pattern
, p
, 0) != FNM_NOMATCH
)
1736 newval
= malloc (p
- value
+ 1);
1745 *(char *) __mempcpy (newval
, value
, p
- value
) = '\0';
1756 case ACT_RP_LONG_RIGHT
:
1757 for (p
= value
; p
<= end
; ++p
)
1759 if (fnmatch (pattern
, p
, 0) != FNM_NOMATCH
)
1762 newval
= malloc (p
- value
+ 1);
1771 *(char *) __mempcpy (newval
, value
, p
- value
) = '\0';
1789 case ACT_NULL_ERROR
:
1790 if (value
&& *value
)
1791 /* Substitute parameter */
1795 if (!colon_seen
&& value
)
1796 /* Substitute NULL */
1800 const char *str
= pattern
;
1803 str
= _("parameter null or not set");
1805 __fxprintf (NULL
, "%s: %s\n", env
, str
);
1812 case ACT_NULL_SUBST
:
1813 if (value
&& *value
)
1814 /* Substitute parameter */
1820 if (!colon_seen
&& value
)
1821 /* Substitute NULL */
1824 value
= pattern
? __strdup (pattern
) : pattern
;
1827 if (pattern
&& !value
)
1832 case ACT_NONNULL_SUBST
:
1833 if (value
&& (*value
|| !colon_seen
))
1838 value
= pattern
? __strdup (pattern
) : pattern
;
1841 if (pattern
&& !value
)
1847 /* Substitute NULL */
1852 case ACT_NULL_ASSIGN
:
1853 if (value
&& *value
)
1854 /* Substitute parameter */
1857 if (!colon_seen
&& value
)
1859 /* Substitute NULL */
1868 value
= pattern
? __strdup (pattern
) : pattern
;
1871 if (pattern
&& !value
)
1874 __setenv (env
, value
?: "", 1);
1878 assert (! "Unrecognised action!");
1889 char param_length
[21];
1890 param_length
[20] = '\0';
1891 *word
= w_addstr (*word
, word_length
, max_length
,
1892 _itoa_word (value
? strlen (value
) : 0,
1893 ¶m_length
[20], 10, 0));
1896 assert (value
!= NULL
);
1900 return *word
? 0 : WRDE_NOSPACE
;
1906 if (quoted
|| !pwordexp
)
1908 /* Quoted - no field split */
1909 *word
= w_addstr (*word
, word_length
, max_length
, value
);
1913 return *word
? 0 : WRDE_NOSPACE
;
1917 /* Need to field-split */
1918 char *value_copy
= __strdup (value
); /* Don't modify value */
1919 char *field_begin
= value_copy
;
1920 int seen_nonws_ifs
= 0;
1925 if (value_copy
== NULL
)
1930 char *field_end
= field_begin
;
1933 /* If this isn't the first field, start a new word */
1934 if (field_begin
!= value_copy
)
1936 if (w_addword (pwordexp
, *word
) == WRDE_NOSPACE
)
1942 *word
= w_newword (word_length
, max_length
);
1945 /* Skip IFS whitespace before the field */
1946 field_begin
+= strspn (field_begin
, ifs_white
);
1948 if (!seen_nonws_ifs
&& *field_begin
== 0)
1949 /* Nothing but whitespace */
1952 /* Search for the end of the field */
1953 field_end
= field_begin
+ strcspn (field_begin
, ifs
);
1955 /* Set up pointer to the character after end of field and
1956 skip whitespace IFS after it. */
1957 next_field
= field_end
+ strspn (field_end
, ifs_white
);
1959 /* Skip at most one non-whitespace IFS character after the field */
1961 if (*next_field
&& strchr (ifs
, *next_field
))
1967 /* Null-terminate it */
1970 /* Tag a copy onto the current word */
1971 *word
= w_addstr (*word
, word_length
, max_length
, field_begin
);
1973 if (*word
== NULL
&& *field_begin
!= '\0')
1979 field_begin
= next_field
;
1981 while (seen_nonws_ifs
|| *field_begin
);
1993 error
= WRDE_NOSPACE
;
1997 error
= WRDE_SYNTAX
;
2010 parse_dollars (char **word
, size_t *word_length
, size_t *max_length
,
2011 const char *words
, size_t *offset
, int flags
,
2012 wordexp_t
*pwordexp
, const char *ifs
, const char *ifs_white
,
2015 /* We are poised _at_ "$" */
2016 switch (words
[1 + *offset
])
2021 *word
= w_addchar (*word
, word_length
, max_length
, '$');
2022 return *word
? 0 : WRDE_NOSPACE
;
2025 if (words
[2 + *offset
] == '(')
2027 /* Differentiate between $((1+3)) and $((echo);(ls)) */
2028 int i
= 3 + *offset
;
2030 while (words
[i
] && !(depth
== 0 && words
[i
] == ')'))
2032 if (words
[i
] == '(')
2034 else if (words
[i
] == ')')
2040 if (words
[i
] == ')' && words
[i
+ 1] == ')')
2043 /* Call parse_arith -- 0 is for "no brackets" */
2044 return parse_arith (word
, word_length
, max_length
, words
, offset
,
2050 return parse_comm (word
, word_length
, max_length
, words
, offset
, flags
,
2051 quoted
? NULL
: pwordexp
, ifs
, ifs_white
);
2055 /* Call parse_arith -- 1 is for "brackets" */
2056 return parse_arith (word
, word_length
, max_length
, words
, offset
, flags
,
2061 ++(*offset
); /* parse_param needs to know if "{" is there */
2062 return parse_param (word
, word_length
, max_length
, words
, offset
, flags
,
2063 pwordexp
, ifs
, ifs_white
, quoted
);
2068 parse_backtick (char **word
, size_t *word_length
, size_t *max_length
,
2069 const char *words
, size_t *offset
, int flags
,
2070 wordexp_t
*pwordexp
, const char *ifs
, const char *ifs_white
)
2072 /* We are poised just after "`" */
2077 char *comm
= w_newword (&comm_length
, &comm_maxlen
);
2079 for (; words
[*offset
]; ++(*offset
))
2081 switch (words
[*offset
])
2084 /* Go -- give the script to the shell */
2085 error
= exec_comm (comm
, word
, word_length
, max_length
, flags
,
2086 pwordexp
, ifs
, ifs_white
);
2093 error
= parse_qtd_backslash (&comm
, &comm_length
, &comm_maxlen
,
2105 error
= parse_backslash (&comm
, &comm_length
, &comm_maxlen
, words
,
2117 squoting
= 1 - squoting
;
2119 comm
= w_addchar (comm
, &comm_length
, &comm_maxlen
, words
[*offset
]);
2121 return WRDE_NOSPACE
;
2131 parse_dquote (char **word
, size_t *word_length
, size_t *max_length
,
2132 const char *words
, size_t *offset
, int flags
,
2133 wordexp_t
*pwordexp
, const char * ifs
, const char * ifs_white
)
2135 /* We are poised just after a double-quote */
2138 for (; words
[*offset
]; ++(*offset
))
2140 switch (words
[*offset
])
2146 error
= parse_dollars (word
, word_length
, max_length
, words
, offset
,
2147 flags
, pwordexp
, ifs
, ifs_white
, 1);
2148 /* The ``1'' here is to tell parse_dollars not to
2149 * split the fields. It may need to, however ("$@").
2158 error
= parse_backtick (word
, word_length
, max_length
, words
,
2159 offset
, flags
, NULL
, NULL
, NULL
);
2160 /* The first NULL here is to tell parse_backtick not to
2169 error
= parse_qtd_backslash (word
, word_length
, max_length
, words
,
2178 *word
= w_addchar (*word
, word_length
, max_length
, words
[*offset
]);
2180 return WRDE_NOSPACE
;
2184 /* Unterminated string */
2189 * wordfree() is to be called after pwordexp is finished with.
2193 wordfree (wordexp_t
*pwordexp
)
2196 /* wordexp can set pwordexp to NULL */
2197 if (pwordexp
&& pwordexp
->we_wordv
)
2199 char **wordv
= pwordexp
->we_wordv
;
2201 for (wordv
+= pwordexp
->we_offs
; *wordv
; ++wordv
)
2204 free (pwordexp
->we_wordv
);
2205 pwordexp
->we_wordv
= NULL
;
2208 libc_hidden_def (wordfree
)
2215 wordexp (const char *words
, wordexp_t
*pwordexp
, int flags
)
2217 size_t words_offset
;
2220 char *word
= w_newword (&word_length
, &max_length
);
2224 wordexp_t old_word
= *pwordexp
;
2226 if (flags
& WRDE_REUSE
)
2228 /* Minimal implementation of WRDE_REUSE for now */
2229 wordfree (pwordexp
);
2230 old_word
.we_wordv
= NULL
;
2233 if ((flags
& WRDE_APPEND
) == 0)
2235 pwordexp
->we_wordc
= 0;
2237 if (flags
& WRDE_DOOFFS
)
2239 pwordexp
->we_wordv
= calloc (1 + pwordexp
->we_offs
, sizeof (char *));
2240 if (pwordexp
->we_wordv
== NULL
)
2242 error
= WRDE_NOSPACE
;
2248 pwordexp
->we_wordv
= calloc (1, sizeof (char *));
2249 if (pwordexp
->we_wordv
== NULL
)
2251 error
= WRDE_NOSPACE
;
2255 pwordexp
->we_offs
= 0;
2259 /* Find out what the field separators are.
2260 * There are two types: whitespace and non-whitespace.
2262 ifs
= getenv ("IFS");
2265 /* IFS unset - use <space><tab><newline>. */
2266 ifs
= strcpy (ifs_white
, " \t\n");
2270 char *whch
= ifs_white
;
2272 while (*ifsch
!= '\0')
2274 if (*ifsch
== ' ' || *ifsch
== '\t' || *ifsch
== '\n')
2276 /* Whitespace IFS. See first whether it is already in our
2278 char *runp
= ifs_white
;
2280 while (runp
< whch
&& *runp
!= *ifsch
)
2292 for (words_offset
= 0 ; words
[words_offset
] ; ++words_offset
)
2293 switch (words
[words_offset
])
2296 error
= parse_backslash (&word
, &word_length
, &max_length
, words
,
2305 error
= parse_dollars (&word
, &word_length
, &max_length
, words
,
2306 &words_offset
, flags
, pwordexp
, ifs
, ifs_white
,
2316 error
= parse_backtick (&word
, &word_length
, &max_length
, words
,
2317 &words_offset
, flags
, pwordexp
, ifs
,
2327 error
= parse_dquote (&word
, &word_length
, &max_length
, words
,
2328 &words_offset
, flags
, pwordexp
, ifs
, ifs_white
);
2335 error
= w_addword (pwordexp
, NULL
);
2345 error
= parse_squote (&word
, &word_length
, &max_length
, words
,
2353 error
= w_addword (pwordexp
, NULL
);
2362 error
= parse_tilde (&word
, &word_length
, &max_length
, words
,
2363 &words_offset
, pwordexp
->we_wordc
);
2373 error
= parse_glob (&word
, &word_length
, &max_length
, words
,
2374 &words_offset
, flags
, pwordexp
, ifs
, ifs_white
);
2382 /* Is it a word separator? */
2383 if (strchr (" \t", words
[words_offset
]) == NULL
)
2385 char ch
= words
[words_offset
];
2387 /* Not a word separator -- but is it a valid word char? */
2388 if (strchr ("\n|&;<>(){}", ch
))
2391 error
= WRDE_BADCHAR
;
2395 /* "Ordinary" character -- add it to word */
2396 word
= w_addchar (word
, &word_length
, &max_length
,
2400 error
= WRDE_NOSPACE
;
2407 /* If a word has been delimited, add it to the list. */
2410 error
= w_addword (pwordexp
, word
);
2415 word
= w_newword (&word_length
, &max_length
);
2420 /* There was a word separator at the end */
2421 if (word
== NULL
) /* i.e. w_newword */
2424 /* There was no field separator at the end */
2425 return w_addword (pwordexp
, word
);
2429 * free memory used (unless error is WRDE_NOSPACE), and
2430 * set pwordexp members back to what they were.
2435 if (error
== WRDE_NOSPACE
)
2436 return WRDE_NOSPACE
;
2438 if ((flags
& WRDE_APPEND
) == 0)
2439 wordfree (pwordexp
);
2441 *pwordexp
= old_word
;