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/>. */
33 #include <sys/param.h>
36 #include <sys/types.h>
37 #include <sys/types.h>
42 #include <kernel-features.h>
43 #include <scratch_buffer.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 */
304 /* POSIX.2 says ~ expands to $HOME and if HOME is unset the
305 results are unspecified. We do a lookup on the uid if
308 home
= getenv ("HOME");
311 *word
= w_addstr (*word
, word_length
, max_length
, home
);
317 struct passwd pwd
, *tpwd
;
318 uid_t uid
= __getuid ();
320 struct scratch_buffer tmpbuf
;
321 scratch_buffer_init (&tmpbuf
);
323 while ((result
= __getpwuid_r (uid
, &pwd
,
324 tmpbuf
.data
, tmpbuf
.length
,
327 if (!scratch_buffer_grow (&tmpbuf
))
330 if (result
== 0 && tpwd
!= NULL
&& pwd
.pw_dir
!= NULL
)
332 *word
= w_addstr (*word
, word_length
, max_length
, pwd
.pw_dir
);
335 scratch_buffer_free (&tmpbuf
);
341 *word
= w_addchar (*word
, word_length
, max_length
, '~');
344 scratch_buffer_free (&tmpbuf
);
348 scratch_buffer_free (&tmpbuf
);
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 struct scratch_buffer tmpbuf
;
358 scratch_buffer_init (&tmpbuf
);
360 while ((result
= __getpwnam_r (user
, &pwd
, tmpbuf
.data
, tmpbuf
.length
,
363 if (!scratch_buffer_grow (&tmpbuf
))
366 if (result
== 0 && tpwd
!= NULL
&& pwd
.pw_dir
)
367 *word
= w_addstr (*word
, word_length
, max_length
, pwd
.pw_dir
);
370 /* (invalid login name) */
371 *word
= w_addchar (*word
, word_length
, max_length
, '~');
373 *word
= w_addstr (*word
, word_length
, max_length
, user
);
376 scratch_buffer_free (&tmpbuf
);
380 return *word
? 0 : WRDE_NOSPACE
;
385 do_parse_glob (const char *glob_word
, char **word
, size_t *word_length
,
386 size_t *max_length
, wordexp_t
*pwordexp
, const char *ifs
,
387 const char *ifs_white
)
393 error
= glob (glob_word
, GLOB_NOCHECK
, NULL
, &globbuf
);
397 /* We can only run into memory problems. */
398 assert (error
== GLOB_NOSPACE
);
404 /* No field splitting allowed. */
405 assert (globbuf
.gl_pathv
[0] != NULL
);
406 *word
= w_addstr (*word
, word_length
, max_length
, globbuf
.gl_pathv
[0]);
407 for (match
= 1; match
< globbuf
.gl_pathc
&& *word
!= NULL
; ++match
)
409 *word
= w_addchar (*word
, word_length
, max_length
, ' ');
411 *word
= w_addstr (*word
, word_length
, max_length
,
412 globbuf
.gl_pathv
[match
]);
416 return *word
? 0 : WRDE_NOSPACE
;
419 assert (ifs
== NULL
|| *ifs
!= '\0');
423 *word
= w_newword (word_length
, max_length
);
426 for (match
= 0; match
< globbuf
.gl_pathc
; ++match
)
428 char *matching_word
= __strdup (globbuf
.gl_pathv
[match
]);
429 if (matching_word
== NULL
|| w_addword (pwordexp
, matching_word
))
441 parse_glob (char **word
, size_t *word_length
, size_t *max_length
,
442 const char *words
, size_t *offset
, int flags
,
443 wordexp_t
*pwordexp
, const char *ifs
, const char *ifs_white
)
445 /* We are poised just after a '*', a '[' or a '?'. */
446 int error
= WRDE_NOSPACE
;
447 int quoted
= 0; /* 1 if singly-quoted, 2 if doubly */
449 wordexp_t glob_list
; /* List of words to glob */
451 glob_list
.we_wordc
= 0;
452 glob_list
.we_wordv
= NULL
;
453 glob_list
.we_offs
= 0;
454 for (; words
[*offset
] != '\0'; ++*offset
)
456 if (strchr (ifs
, words
[*offset
]) != NULL
)
460 /* Sort out quoting */
461 if (words
[*offset
] == '\'')
468 else if (quoted
== 1)
474 else if (words
[*offset
] == '"')
481 else if (quoted
== 2)
488 /* Sort out other special characters */
489 if (quoted
!= 1 && words
[*offset
] == '$')
491 error
= parse_dollars (word
, word_length
, max_length
, words
,
492 offset
, flags
, &glob_list
, ifs
, ifs_white
,
499 else if (words
[*offset
] == '\\')
502 error
= parse_qtd_backslash (word
, word_length
, max_length
,
505 error
= parse_backslash (word
, word_length
, max_length
,
514 *word
= w_addchar (*word
, word_length
, max_length
, words
[*offset
]);
519 /* Don't forget to re-parse the character we stopped at. */
523 error
= w_addword (&glob_list
, *word
);
524 *word
= w_newword (word_length
, max_length
);
525 for (i
= 0; error
== 0 && i
< glob_list
.we_wordc
; i
++)
526 error
= do_parse_glob (glob_list
.we_wordv
[i
], word
, word_length
,
527 max_length
, pwordexp
, ifs
, ifs_white
);
531 wordfree (&glob_list
);
536 parse_squote (char **word
, size_t *word_length
, size_t *max_length
,
537 const char *words
, size_t *offset
)
539 /* We are poised just after a single quote */
540 for (; words
[*offset
]; ++(*offset
))
542 if (words
[*offset
] != '\'')
544 *word
= w_addchar (*word
, word_length
, max_length
, words
[*offset
]);
551 /* Unterminated string */
555 /* Functions to evaluate an arithmetic expression */
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);
591 eval_expr_multdiv (char **expr
, long int *result
)
596 if (eval_expr_val (expr
, result
) != 0)
601 /* Skip white space */
602 for (; *expr
&& **expr
&& isspace (**expr
); ++(*expr
));
607 if (eval_expr_val (expr
, &arg
) != 0)
612 else if (**expr
== '/')
615 if (eval_expr_val (expr
, &arg
) != 0)
618 /* Division by zero or integer overflow. */
619 if (arg
== 0 || (arg
== -1 && *result
== LONG_MIN
))
631 eval_expr (char *expr
, long int *result
)
636 if (eval_expr_multdiv (&expr
, result
) != 0)
641 /* Skip white space */
642 for (; expr
&& *expr
&& isspace (*expr
); ++expr
);
647 if (eval_expr_multdiv (&expr
, &arg
) != 0)
652 else if (*expr
== '-')
655 if (eval_expr_multdiv (&expr
, &arg
) != 0)
667 parse_arith (char **word
, size_t *word_length
, size_t *max_length
,
668 const char *words
, size_t *offset
, int flags
, int bracket
)
670 /* We are poised just after "$((" or "$[" */
677 expr
= w_newword (&expr_length
, &expr_maxlen
);
678 for (; words
[*offset
]; ++(*offset
))
680 switch (words
[*offset
])
683 error
= parse_dollars (&expr
, &expr_length
, &expr_maxlen
,
684 words
, offset
, flags
, NULL
, NULL
, NULL
, 1);
685 /* The ``1'' here is to tell parse_dollars not to
697 error
= parse_backtick (&expr
, &expr_length
, &expr_maxlen
,
698 words
, offset
, flags
, NULL
, NULL
, NULL
);
699 /* The first NULL here is to tell parse_backtick not to
710 error
= parse_qtd_backslash (&expr
, &expr_length
, &expr_maxlen
,
717 /* I think that a backslash within an
718 * arithmetic expansion is bound to
719 * cause an error sooner or later anyway though.
724 if (--paren_depth
== 0)
726 char result
[21]; /* 21 = ceil(log10(2^64)) + 1 */
727 long int numresult
= 0;
728 long long int convertme
;
730 if (bracket
|| words
[1 + *offset
] != ')')
739 if (*expr
&& eval_expr (expr
, &numresult
) != 0)
747 convertme
= -numresult
;
748 *word
= w_addchar (*word
, word_length
, max_length
, '-');
756 convertme
= numresult
;
759 *word
= w_addstr (*word
, word_length
, max_length
,
760 _itoa (convertme
, &result
[20], 10, 0));
762 return *word
? 0 : WRDE_NOSPACE
;
764 expr
= w_addchar (expr
, &expr_length
, &expr_maxlen
, words
[*offset
]);
771 if (bracket
&& paren_depth
== 1)
773 char result
[21]; /* 21 = ceil(log10(2^64)) + 1 */
774 long int numresult
= 0;
777 if (*expr
&& eval_expr (expr
, &numresult
) != 0)
784 *word
= w_addstr (*word
, word_length
, max_length
,
785 _itoa_word (numresult
, &result
[20], 10, 0));
787 return *word
? 0 : WRDE_NOSPACE
;
803 expr
= w_addchar (expr
, &expr_length
, &expr_maxlen
, words
[*offset
]);
814 /* Function called by child process in exec_comm() */
816 __attribute__ ((always_inline
))
817 exec_comm_child (char *comm
, int *fildes
, int showerr
, int noexec
)
819 const char *args
[4] = { _PATH_BSHELL
, "-c", comm
, NULL
};
821 /* Execute the command, or just check syntax? */
825 /* Redirect output. */
826 if (__glibc_likely (fildes
[1] != STDOUT_FILENO
))
828 __dup2 (fildes
[1], STDOUT_FILENO
);
832 /* Reset the close-on-exec flag (if necessary). */
833 __fcntl (fildes
[1], F_SETFD
, 0);
835 /* Redirect stderr to /dev/null if we have to. */
840 __close (STDERR_FILENO
);
841 fd
= __open (_PATH_DEVNULL
, O_WRONLY
);
842 if (fd
>= 0 && fd
!= STDERR_FILENO
)
844 __dup2 (fd
, STDERR_FILENO
);
847 /* Be paranoid. Check that we actually opened the /dev/null
849 if (__builtin_expect (__fxstat64 (_STAT_VER
, STDERR_FILENO
, &st
), 0) != 0
850 || __builtin_expect (S_ISCHR (st
.st_mode
), 1) == 0
851 #if defined DEV_NULL_MAJOR && defined DEV_NULL_MINOR
852 || st
.st_rdev
!= __gnu_dev_makedev (DEV_NULL_MAJOR
, DEV_NULL_MINOR
)
855 /* It's not the /dev/null device. Stop right here. The
856 problem is: how do we stop? We use _exit() with an
857 hopefully unusual exit code. */
861 /* Make sure the subshell doesn't field-split on our behalf. */
865 __execve (_PATH_BSHELL
, (char *const *) args
, __environ
);
871 /* Function to execute a command and retrieve the results */
872 /* pwordexp contains NULL if field-splitting is forbidden */
874 exec_comm (char *comm
, char **word
, size_t *word_length
, size_t *max_length
,
875 int flags
, wordexp_t
*pwordexp
, const char *ifs
,
876 const char *ifs_white
)
883 size_t maxnewlines
= 0;
884 char buffer
[bufsize
];
888 /* Do nothing if command substitution should not succeed. */
889 if (flags
& WRDE_NOCMD
)
892 /* Don't fork() unless necessary */
896 if (__pipe2 (fildes
, O_CLOEXEC
) < 0)
900 if ((pid
= __fork ()) < 0)
909 exec_comm_child (comm
, fildes
, noexec
? 0 : flags
& WRDE_SHOWERR
, noexec
);
913 /* If we are just testing the syntax, only wait. */
915 return (TEMP_FAILURE_RETRY (__waitpid (pid
, &status
, 0)) == pid
916 && status
!= 0) ? WRDE_SYNTAX
: 0;
922 /* Quoted - no field splitting */
926 if ((buflen
= TEMP_FAILURE_RETRY (__read (fildes
[0], buffer
,
929 /* If read returned 0 then the process has closed its
930 stdout. Don't use WNOHANG in that case to avoid busy
931 looping until the process eventually exits. */
932 if (TEMP_FAILURE_RETRY (__waitpid (pid
, &status
,
933 buflen
== 0 ? 0 : WNOHANG
))
936 if ((buflen
= TEMP_FAILURE_RETRY (__read (fildes
[0], buffer
,
941 maxnewlines
+= buflen
;
943 *word
= w_addmem (*word
, word_length
, max_length
, buffer
, buflen
);
949 /* Not quoted - split fields */
953 * 0 when searching for first character in a field not IFS white space
954 * 1 when copying the text of a field
955 * 2 when searching for possible non-whitespace IFS
956 * 3 when searching for non-newline after copying field
961 if ((buflen
= TEMP_FAILURE_RETRY (__read (fildes
[0], buffer
,
964 /* If read returned 0 then the process has closed its
965 stdout. Don't use WNOHANG in that case to avoid busy
966 looping until the process eventually exits. */
967 if (TEMP_FAILURE_RETRY (__waitpid (pid
, &status
,
968 buflen
== 0 ? 0 : WNOHANG
))
971 if ((buflen
= TEMP_FAILURE_RETRY (__read (fildes
[0], buffer
,
976 for (i
= 0; i
< buflen
; ++i
)
978 if (strchr (ifs
, buffer
[i
]) != NULL
)
980 /* Current character is IFS */
981 if (strchr (ifs_white
, buffer
[i
]) == NULL
)
983 /* Current character is IFS but not whitespace */
989 * eg: text<space><comma><space>moretext
991 * So, strip whitespace IFS (like at the start)
998 /* fall through and delimit field.. */
1002 if (buffer
[i
] == '\n')
1004 /* Current character is (IFS) newline */
1006 /* If copying a field, this is the end of it,
1007 but maybe all that's left is trailing newlines.
1008 So start searching for a non-newline. */
1016 /* Current character is IFS white space, but
1019 /* If not either copying a field or searching
1020 for non-newline after a field, ignore it */
1021 if (copying
!= 1 && copying
!= 3)
1024 /* End of field (search for non-ws IFS afterwards) */
1029 /* First IFS white space (non-newline), or IFS non-whitespace.
1030 * Delimit the field. Nulls are converted by w_addword. */
1031 if (w_addword (pwordexp
, *word
) == WRDE_NOSPACE
)
1034 *word
= w_newword (word_length
, max_length
);
1037 /* fall back round the loop.. */
1041 /* Not IFS character */
1045 /* Nothing but (IFS) newlines since the last field,
1046 so delimit it here before starting new word */
1047 if (w_addword (pwordexp
, *word
) == WRDE_NOSPACE
)
1050 *word
= w_newword (word_length
, max_length
);
1055 if (buffer
[i
] == '\n') /* happens if newline not in IFS */
1060 *word
= w_addchar (*word
, word_length
, max_length
,
1069 /* Chop off trailing newlines (required by POSIX.2) */
1070 /* Ensure we don't go back further than the beginning of the
1071 substitution (i.e. remove maxnewlines bytes at most) */
1072 while (maxnewlines
-- != 0 &&
1073 *word_length
> 0 && (*word
)[*word_length
- 1] == '\n')
1075 (*word
)[--*word_length
] = '\0';
1077 /* If the last word was entirely newlines, turn it into a new word
1078 * which can be ignored if there's nothing following it. */
1079 if (*word_length
== 0)
1082 *word
= w_newword (word_length
, max_length
);
1087 __close (fildes
[0]);
1090 /* Check for syntax error (re-execute but with "-n" flag) */
1091 if (buflen
< 1 && status
!= 0)
1100 __kill (pid
, SIGKILL
);
1101 TEMP_FAILURE_RETRY (__waitpid (pid
, NULL
, 0));
1102 __close (fildes
[0]);
1103 return WRDE_NOSPACE
;
1107 parse_comm (char **word
, size_t *word_length
, size_t *max_length
,
1108 const char *words
, size_t *offset
, int flags
, wordexp_t
*pwordexp
,
1109 const char *ifs
, const char *ifs_white
)
1111 /* We are poised just after "$(" */
1112 int paren_depth
= 1;
1114 int quoted
= 0; /* 1 for singly-quoted, 2 for doubly-quoted */
1117 char *comm
= w_newword (&comm_length
, &comm_maxlen
);
1119 for (; words
[*offset
]; ++(*offset
))
1121 switch (words
[*offset
])
1126 else if (quoted
== 1)
1134 else if (quoted
== 2)
1140 if (!quoted
&& --paren_depth
== 0)
1142 /* Go -- give script to the shell */
1145 #ifdef __libc_ptf_call
1146 /* We do not want the exec_comm call to be cut short
1147 by a thread cancellation since cleanup is very
1148 ugly. Therefore disable cancellation for
1150 // XXX Ideally we do want the thread being cancelable.
1151 // XXX If demand is there we'll change it.
1152 int state
= PTHREAD_CANCEL_ENABLE
;
1153 __libc_ptf_call (__pthread_setcancelstate
,
1154 (PTHREAD_CANCEL_DISABLE
, &state
), 0);
1157 error
= exec_comm (comm
, word
, word_length
, max_length
,
1158 flags
, pwordexp
, ifs
, ifs_white
);
1160 #ifdef __libc_ptf_call
1161 __libc_ptf_call (__pthread_setcancelstate
,
1171 /* This is just part of the script */
1179 comm
= w_addchar (comm
, &comm_length
, &comm_maxlen
, words
[*offset
]);
1181 return WRDE_NOSPACE
;
1184 /* Premature end. */
1190 #define CHAR_IN_SET(ch, char_set) \
1191 (memchr (char_set "", ch, sizeof (char_set) - 1) != NULL)
1194 parse_param (char **word
, size_t *word_length
, size_t *max_length
,
1195 const char *words
, size_t *offset
, int flags
, wordexp_t
*pwordexp
,
1196 const char *ifs
, const char *ifs_white
, int quoted
)
1198 /* We are poised just after "$" */
1202 ACT_RP_SHORT_LEFT
= '#',
1203 ACT_RP_LONG_LEFT
= 'L',
1204 ACT_RP_SHORT_RIGHT
= '%',
1205 ACT_RP_LONG_RIGHT
= 'R',
1206 ACT_NULL_ERROR
= '?',
1207 ACT_NULL_SUBST
= '-',
1208 ACT_NONNULL_SUBST
= '+',
1209 ACT_NULL_ASSIGN
= '='
1215 size_t start
= *offset
;
1219 enum action action
= ACT_NONE
;
1224 int pattern_is_quoted
= 0; /* 1 for singly-quoted, 2 for doubly-quoted */
1228 int brace
= words
[*offset
] == '{';
1230 env
= w_newword (&env_length
, &env_maxlen
);
1231 pattern
= w_newword (&pat_length
, &pat_maxlen
);
1236 /* First collect the parameter name. */
1238 if (words
[*offset
] == '#')
1246 if (isalpha (words
[*offset
]) || words
[*offset
] == '_')
1248 /* Normal parameter name. */
1251 env
= w_addchar (env
, &env_length
, &env_maxlen
,
1256 while (isalnum (words
[++*offset
]) || words
[*offset
] == '_');
1258 else if (isdigit (words
[*offset
]))
1260 /* Numeric parameter name. */
1264 env
= w_addchar (env
, &env_length
, &env_maxlen
,
1271 while (isdigit(words
[++*offset
]));
1273 else if (CHAR_IN_SET (words
[*offset
], "*@$"))
1275 /* Special parameter. */
1277 env
= w_addchar (env
, &env_length
, &env_maxlen
,
1291 /* Check for special action to be applied to the value. */
1292 switch (words
[*offset
])
1299 action
= ACT_RP_SHORT_LEFT
;
1300 if (words
[1 + *offset
] == '#')
1303 action
= ACT_RP_LONG_LEFT
;
1308 action
= ACT_RP_SHORT_RIGHT
;
1309 if (words
[1 + *offset
] == '%')
1312 action
= ACT_RP_LONG_RIGHT
;
1317 if (!CHAR_IN_SET (words
[1 + *offset
], "-=?+"))
1321 action
= words
[++*offset
];
1328 action
= words
[*offset
];
1335 /* Now collect the pattern, but don't expand it yet. */
1337 for (; words
[*offset
]; ++(*offset
))
1339 switch (words
[*offset
])
1342 if (!pattern_is_quoted
)
1347 if (!pattern_is_quoted
)
1356 if (pattern_is_quoted
)
1357 /* Quoted; treat as normal character. */
1360 /* Otherwise, it's an escape: next character is literal. */
1361 if (words
[++*offset
] == '\0')
1364 pattern
= w_addchar (pattern
, &pat_length
, &pat_maxlen
, '\\');
1365 if (pattern
== NULL
)
1371 if (pattern_is_quoted
== 0)
1372 pattern_is_quoted
= 1;
1373 else if (pattern_is_quoted
== 1)
1374 pattern_is_quoted
= 0;
1379 if (pattern_is_quoted
== 0)
1380 pattern_is_quoted
= 2;
1381 else if (pattern_is_quoted
== 2)
1382 pattern_is_quoted
= 0;
1387 pattern
= w_addchar (pattern
, &pat_length
, &pat_maxlen
,
1389 if (pattern
== NULL
)
1394 /* End of input string -- remember to reparse the character that we
1399 if (words
[start
] == '{' && words
[*offset
] != '}')
1406 /* $# expands to the number of positional parameters */
1408 value
= _itoa_word (__libc_argc
- 1, &buffer
[20], 10, 0);
1413 /* Just $ on its own */
1414 *offset
= start
- 1;
1415 *word
= w_addchar (*word
, word_length
, max_length
, '$');
1416 return *word
? 0 : WRDE_NOSPACE
;
1419 /* Is it a numeric parameter? */
1420 else if (isdigit (env
[0]))
1424 if (n
>= __libc_argc
)
1425 /* Substitute NULL. */
1428 /* Replace with appropriate positional parameter. */
1429 value
= __libc_argv
[n
];
1431 /* Is it a special parameter? */
1438 value
= _itoa_word (__getpid (), &buffer
[20], 10, 0);
1440 /* Is it `${#*}' or `${#@}'? */
1441 else if ((*env
== '*' || *env
== '@') && seen_hash
)
1444 value
= _itoa_word (__libc_argc
> 0 ? __libc_argc
- 1 : 0,
1445 &buffer
[20], 10, 0);
1446 *word
= w_addstr (*word
, word_length
, max_length
, value
);
1449 return *word
? 0 : WRDE_NOSPACE
;
1451 /* Is it `$*' or `$@' (unquoted) ? */
1452 else if (*env
== '*' || (*env
== '@' && !quoted
))
1454 size_t plist_len
= 0;
1458 /* Build up value parameter by parameter (copy them) */
1459 for (p
= 1; __libc_argv
[p
]; ++p
)
1460 plist_len
+= strlen (__libc_argv
[p
]) + 1; /* for space */
1461 value
= malloc (plist_len
);
1466 for (p
= 1; __libc_argv
[p
]; ++p
)
1470 end
= __stpcpy (end
, __libc_argv
[p
]);
1477 /* Must be a quoted `$@' */
1478 assert (*env
== '@' && quoted
);
1480 /* Each parameter is a separate word ("$@") */
1481 if (__libc_argc
== 2)
1482 value
= __libc_argv
[1];
1483 else if (__libc_argc
> 2)
1487 /* Append first parameter to current word. */
1488 value
= w_addstr (*word
, word_length
, max_length
,
1490 if (value
== NULL
|| w_addword (pwordexp
, value
))
1493 for (p
= 2; __libc_argv
[p
+ 1]; p
++)
1495 char *newword
= __strdup (__libc_argv
[p
]);
1496 if (newword
== NULL
|| w_addword (pwordexp
, newword
))
1500 /* Start a new word with the last parameter. */
1501 *word
= w_newword (word_length
, max_length
);
1502 value
= __libc_argv
[p
];
1513 value
= getenv (env
);
1515 if (value
== NULL
&& (flags
& WRDE_UNDEF
))
1517 /* Variable not defined. */
1518 error
= WRDE_BADVAL
;
1522 if (action
!= ACT_NONE
)
1524 int expand_pattern
= 0;
1526 /* First, find out if we need to expand pattern (i.e. if we will
1530 case ACT_RP_SHORT_LEFT
:
1531 case ACT_RP_LONG_LEFT
:
1532 case ACT_RP_SHORT_RIGHT
:
1533 case ACT_RP_LONG_RIGHT
:
1534 /* Always expand for these. */
1538 case ACT_NULL_ERROR
:
1539 case ACT_NULL_SUBST
:
1540 case ACT_NULL_ASSIGN
:
1541 if (!value
|| (!*value
&& colon_seen
))
1542 /* If param is unset, or set but null and a colon has been seen,
1543 the expansion of the pattern will be needed. */
1548 case ACT_NONNULL_SUBST
:
1549 /* Expansion of word will be needed if parameter is set and not null,
1550 or set null but no colon has been seen. */
1551 if (value
&& (*value
|| !colon_seen
))
1557 assert (! "Unrecognised action!");
1562 /* We need to perform tilde expansion, parameter expansion,
1563 command substitution, and arithmetic expansion. We also
1564 have to be a bit careful with wildcard characters, as
1565 pattern might be given to fnmatch soon. To do this, we
1566 convert quotes to escapes. */
1572 int quoted
= 0; /* 1: single quotes; 2: double */
1574 expanded
= w_newword (&exp_len
, &exp_maxl
);
1575 for (p
= pattern
; p
&& *p
; p
++)
1584 else if (quoted
== 0)
1593 else if (quoted
== 0)
1603 /* Convert quoted wildchar to escaped wildchar. */
1604 expanded
= w_addchar (expanded
, &exp_len
,
1607 if (expanded
== NULL
)
1614 error
= parse_dollars (&expanded
, &exp_len
, &exp_maxl
, p
,
1615 &offset
, flags
, NULL
, NULL
, NULL
, 1);
1630 if (quoted
|| exp_len
)
1634 error
= parse_tilde (&expanded
, &exp_len
, &exp_maxl
, p
,
1650 expanded
= w_addchar (expanded
, &exp_len
, &exp_maxl
, '\\');
1652 assert (*p
); /* checked when extracted initially */
1653 if (expanded
== NULL
)
1657 expanded
= w_addchar (expanded
, &exp_len
, &exp_maxl
, *p
);
1659 if (expanded
== NULL
)
1670 case ACT_RP_SHORT_LEFT
:
1671 case ACT_RP_LONG_LEFT
:
1672 case ACT_RP_SHORT_RIGHT
:
1673 case ACT_RP_LONG_RIGHT
:
1679 if (value
== NULL
|| pattern
== NULL
|| *pattern
== '\0')
1682 end
= value
+ strlen (value
);
1686 case ACT_RP_SHORT_LEFT
:
1687 for (p
= value
; p
<= end
; ++p
)
1691 if (fnmatch (pattern
, value
, 0) != FNM_NOMATCH
)
1696 char *newval
= __strdup (p
);
1714 case ACT_RP_LONG_LEFT
:
1715 for (p
= end
; p
>= value
; --p
)
1719 if (fnmatch (pattern
, value
, 0) != FNM_NOMATCH
)
1724 char *newval
= __strdup (p
);
1742 case ACT_RP_SHORT_RIGHT
:
1743 for (p
= end
; p
>= value
; --p
)
1745 if (fnmatch (pattern
, p
, 0) != FNM_NOMATCH
)
1748 newval
= malloc (p
- value
+ 1);
1757 *(char *) __mempcpy (newval
, value
, p
- value
) = '\0';
1768 case ACT_RP_LONG_RIGHT
:
1769 for (p
= value
; p
<= end
; ++p
)
1771 if (fnmatch (pattern
, p
, 0) != FNM_NOMATCH
)
1774 newval
= malloc (p
- value
+ 1);
1783 *(char *) __mempcpy (newval
, value
, p
- value
) = '\0';
1801 case ACT_NULL_ERROR
:
1802 if (value
&& *value
)
1803 /* Substitute parameter */
1807 if (!colon_seen
&& value
)
1808 /* Substitute NULL */
1812 const char *str
= pattern
;
1815 str
= _("parameter null or not set");
1817 __fxprintf (NULL
, "%s: %s\n", env
, str
);
1824 case ACT_NULL_SUBST
:
1825 if (value
&& *value
)
1826 /* Substitute parameter */
1832 if (!colon_seen
&& value
)
1833 /* Substitute NULL */
1836 value
= pattern
? __strdup (pattern
) : pattern
;
1839 if (pattern
&& !value
)
1844 case ACT_NONNULL_SUBST
:
1845 if (value
&& (*value
|| !colon_seen
))
1850 value
= pattern
? __strdup (pattern
) : pattern
;
1853 if (pattern
&& !value
)
1859 /* Substitute NULL */
1864 case ACT_NULL_ASSIGN
:
1865 if (value
&& *value
)
1866 /* Substitute parameter */
1869 if (!colon_seen
&& value
)
1871 /* Substitute NULL */
1880 value
= pattern
? __strdup (pattern
) : pattern
;
1883 if (pattern
&& !value
)
1886 __setenv (env
, value
?: "", 1);
1890 assert (! "Unrecognised action!");
1901 char param_length
[21];
1902 param_length
[20] = '\0';
1903 *word
= w_addstr (*word
, word_length
, max_length
,
1904 _itoa_word (value
? strlen (value
) : 0,
1905 ¶m_length
[20], 10, 0));
1908 assert (value
!= NULL
);
1912 return *word
? 0 : WRDE_NOSPACE
;
1918 if (quoted
|| !pwordexp
)
1920 /* Quoted - no field split */
1921 *word
= w_addstr (*word
, word_length
, max_length
, value
);
1925 return *word
? 0 : WRDE_NOSPACE
;
1929 /* Need to field-split */
1930 char *value_copy
= __strdup (value
); /* Don't modify value */
1931 char *field_begin
= value_copy
;
1932 int seen_nonws_ifs
= 0;
1937 if (value_copy
== NULL
)
1942 char *field_end
= field_begin
;
1945 /* If this isn't the first field, start a new word */
1946 if (field_begin
!= value_copy
)
1948 if (w_addword (pwordexp
, *word
) == WRDE_NOSPACE
)
1954 *word
= w_newword (word_length
, max_length
);
1957 /* Skip IFS whitespace before the field */
1958 field_begin
+= strspn (field_begin
, ifs_white
);
1960 if (!seen_nonws_ifs
&& *field_begin
== 0)
1961 /* Nothing but whitespace */
1964 /* Search for the end of the field */
1965 field_end
= field_begin
+ strcspn (field_begin
, ifs
);
1967 /* Set up pointer to the character after end of field and
1968 skip whitespace IFS after it. */
1969 next_field
= field_end
+ strspn (field_end
, ifs_white
);
1971 /* Skip at most one non-whitespace IFS character after the field */
1973 if (*next_field
&& strchr (ifs
, *next_field
))
1979 /* Null-terminate it */
1982 /* Tag a copy onto the current word */
1983 *word
= w_addstr (*word
, word_length
, max_length
, field_begin
);
1985 if (*word
== NULL
&& *field_begin
!= '\0')
1991 field_begin
= next_field
;
1993 while (seen_nonws_ifs
|| *field_begin
);
2005 error
= WRDE_NOSPACE
;
2009 error
= WRDE_SYNTAX
;
2022 parse_dollars (char **word
, size_t *word_length
, size_t *max_length
,
2023 const char *words
, size_t *offset
, int flags
,
2024 wordexp_t
*pwordexp
, const char *ifs
, const char *ifs_white
,
2027 /* We are poised _at_ "$" */
2028 switch (words
[1 + *offset
])
2033 *word
= w_addchar (*word
, word_length
, max_length
, '$');
2034 return *word
? 0 : WRDE_NOSPACE
;
2037 if (words
[2 + *offset
] == '(')
2039 /* Differentiate between $((1+3)) and $((echo);(ls)) */
2040 int i
= 3 + *offset
;
2042 while (words
[i
] && !(depth
== 0 && words
[i
] == ')'))
2044 if (words
[i
] == '(')
2046 else if (words
[i
] == ')')
2052 if (words
[i
] == ')' && words
[i
+ 1] == ')')
2055 /* Call parse_arith -- 0 is for "no brackets" */
2056 return parse_arith (word
, word_length
, max_length
, words
, offset
,
2062 return parse_comm (word
, word_length
, max_length
, words
, offset
, flags
,
2063 quoted
? NULL
: pwordexp
, ifs
, ifs_white
);
2067 /* Call parse_arith -- 1 is for "brackets" */
2068 return parse_arith (word
, word_length
, max_length
, words
, offset
, flags
,
2073 ++(*offset
); /* parse_param needs to know if "{" is there */
2074 return parse_param (word
, word_length
, max_length
, words
, offset
, flags
,
2075 pwordexp
, ifs
, ifs_white
, quoted
);
2080 parse_backtick (char **word
, size_t *word_length
, size_t *max_length
,
2081 const char *words
, size_t *offset
, int flags
,
2082 wordexp_t
*pwordexp
, const char *ifs
, const char *ifs_white
)
2084 /* We are poised just after "`" */
2089 char *comm
= w_newword (&comm_length
, &comm_maxlen
);
2091 for (; words
[*offset
]; ++(*offset
))
2093 switch (words
[*offset
])
2096 /* Go -- give the script to the shell */
2097 error
= exec_comm (comm
, word
, word_length
, max_length
, flags
,
2098 pwordexp
, ifs
, ifs_white
);
2105 error
= parse_qtd_backslash (&comm
, &comm_length
, &comm_maxlen
,
2117 error
= parse_backslash (&comm
, &comm_length
, &comm_maxlen
, words
,
2129 squoting
= 1 - squoting
;
2131 comm
= w_addchar (comm
, &comm_length
, &comm_maxlen
, words
[*offset
]);
2133 return WRDE_NOSPACE
;
2143 parse_dquote (char **word
, size_t *word_length
, size_t *max_length
,
2144 const char *words
, size_t *offset
, int flags
,
2145 wordexp_t
*pwordexp
, const char * ifs
, const char * ifs_white
)
2147 /* We are poised just after a double-quote */
2150 for (; words
[*offset
]; ++(*offset
))
2152 switch (words
[*offset
])
2158 error
= parse_dollars (word
, word_length
, max_length
, words
, offset
,
2159 flags
, pwordexp
, ifs
, ifs_white
, 1);
2160 /* The ``1'' here is to tell parse_dollars not to
2161 * split the fields. It may need to, however ("$@").
2170 error
= parse_backtick (word
, word_length
, max_length
, words
,
2171 offset
, flags
, NULL
, NULL
, NULL
);
2172 /* The first NULL here is to tell parse_backtick not to
2181 error
= parse_qtd_backslash (word
, word_length
, max_length
, words
,
2190 *word
= w_addchar (*word
, word_length
, max_length
, words
[*offset
]);
2192 return WRDE_NOSPACE
;
2196 /* Unterminated string */
2201 * wordfree() is to be called after pwordexp is finished with.
2205 wordfree (wordexp_t
*pwordexp
)
2208 /* wordexp can set pwordexp to NULL */
2209 if (pwordexp
&& pwordexp
->we_wordv
)
2211 char **wordv
= pwordexp
->we_wordv
;
2213 for (wordv
+= pwordexp
->we_offs
; *wordv
; ++wordv
)
2216 free (pwordexp
->we_wordv
);
2217 pwordexp
->we_wordv
= NULL
;
2220 libc_hidden_def (wordfree
)
2227 wordexp (const char *words
, wordexp_t
*pwordexp
, int flags
)
2229 size_t words_offset
;
2232 char *word
= w_newword (&word_length
, &max_length
);
2236 wordexp_t old_word
= *pwordexp
;
2238 if (flags
& WRDE_REUSE
)
2240 /* Minimal implementation of WRDE_REUSE for now */
2241 wordfree (pwordexp
);
2242 old_word
.we_wordv
= NULL
;
2245 if ((flags
& WRDE_APPEND
) == 0)
2247 pwordexp
->we_wordc
= 0;
2249 if (flags
& WRDE_DOOFFS
)
2251 pwordexp
->we_wordv
= calloc (1 + pwordexp
->we_offs
, sizeof (char *));
2252 if (pwordexp
->we_wordv
== NULL
)
2254 error
= WRDE_NOSPACE
;
2260 pwordexp
->we_wordv
= calloc (1, sizeof (char *));
2261 if (pwordexp
->we_wordv
== NULL
)
2263 error
= WRDE_NOSPACE
;
2267 pwordexp
->we_offs
= 0;
2271 /* Find out what the field separators are.
2272 * There are two types: whitespace and non-whitespace.
2274 ifs
= getenv ("IFS");
2277 /* IFS unset - use <space><tab><newline>. */
2278 ifs
= strcpy (ifs_white
, " \t\n");
2282 char *whch
= ifs_white
;
2284 while (*ifsch
!= '\0')
2286 if (*ifsch
== ' ' || *ifsch
== '\t' || *ifsch
== '\n')
2288 /* Whitespace IFS. See first whether it is already in our
2290 char *runp
= ifs_white
;
2292 while (runp
< whch
&& *runp
!= *ifsch
)
2304 for (words_offset
= 0 ; words
[words_offset
] ; ++words_offset
)
2305 switch (words
[words_offset
])
2308 error
= parse_backslash (&word
, &word_length
, &max_length
, words
,
2317 error
= parse_dollars (&word
, &word_length
, &max_length
, words
,
2318 &words_offset
, flags
, pwordexp
, ifs
, ifs_white
,
2328 error
= parse_backtick (&word
, &word_length
, &max_length
, words
,
2329 &words_offset
, flags
, pwordexp
, ifs
,
2339 error
= parse_dquote (&word
, &word_length
, &max_length
, words
,
2340 &words_offset
, flags
, pwordexp
, ifs
, ifs_white
);
2347 error
= w_addword (pwordexp
, NULL
);
2357 error
= parse_squote (&word
, &word_length
, &max_length
, words
,
2365 error
= w_addword (pwordexp
, NULL
);
2374 error
= parse_tilde (&word
, &word_length
, &max_length
, words
,
2375 &words_offset
, pwordexp
->we_wordc
);
2385 error
= parse_glob (&word
, &word_length
, &max_length
, words
,
2386 &words_offset
, flags
, pwordexp
, ifs
, ifs_white
);
2394 /* Is it a word separator? */
2395 if (strchr (" \t", words
[words_offset
]) == NULL
)
2397 char ch
= words
[words_offset
];
2399 /* Not a word separator -- but is it a valid word char? */
2400 if (strchr ("\n|&;<>(){}", ch
))
2403 error
= WRDE_BADCHAR
;
2407 /* "Ordinary" character -- add it to word */
2408 word
= w_addchar (word
, &word_length
, &max_length
,
2412 error
= WRDE_NOSPACE
;
2419 /* If a word has been delimited, add it to the list. */
2422 error
= w_addword (pwordexp
, word
);
2427 word
= w_newword (&word_length
, &max_length
);
2432 /* There was a word separator at the end */
2433 if (word
== NULL
) /* i.e. w_newword */
2436 /* There was no field separator at the end */
2437 return w_addword (pwordexp
, word
);
2441 * free memory used (unless error is WRDE_NOSPACE), and
2442 * set pwordexp members back to what they were.
2447 if (error
== WRDE_NOSPACE
)
2448 return WRDE_NOSPACE
;
2450 if ((flags
& WRDE_APPEND
) == 0)
2451 wordfree (pwordexp
);
2453 *pwordexp
= old_word
;