1 /* POSIX.2 wordexp implementation.
2 Copyright (C) 1997-2003, 2005, 2006, 2008 Free Software Foundation, Inc.
3 This file is part of the GNU C Library.
4 Contributed by Tim Waugh <tim@cyberelk.demon.co.uk>.
6 The GNU C Library is free software; you can redistribute it and/or
7 modify it under the terms of the GNU Lesser General Public
8 License as published by the Free Software Foundation; either
9 version 2.1 of the License, or (at your option) any later version.
11 The GNU C Library is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 Lesser General Public License for more details.
16 You should have received a copy of the GNU Lesser General Public
17 License along with the GNU C Library; if not, write to the Free
18 Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
34 #include <sys/param.h>
37 #include <sys/types.h>
38 #include <sys/types.h>
45 #include <kernel-features.h>
47 #include <bits/libc-lock.h>
48 #include <stdio-common/_itoa.h>
50 /* Undefine the following line for the production version. */
51 /* #define NDEBUG 1 */
54 /* Get some device information. */
55 #include <device-nrs.h>
58 * This is a recursive-descent-style word expansion routine.
61 /* These variables are defined and initialized in the startup code. */
62 extern int __libc_argc attribute_hidden
;
63 extern char **__libc_argv attribute_hidden
;
65 /* Some forward declarations */
66 static int parse_dollars (char **word
, size_t *word_length
, size_t *max_length
,
67 const char *words
, size_t *offset
, int flags
,
68 wordexp_t
*pwordexp
, const char *ifs
,
69 const char *ifs_white
, int quoted
)
71 static int parse_backtick (char **word
, size_t *word_length
,
72 size_t *max_length
, const char *words
,
73 size_t *offset
, int flags
, wordexp_t
*pwordexp
,
74 const char *ifs
, const char *ifs_white
)
76 static int parse_dquote (char **word
, size_t *word_length
, size_t *max_length
,
77 const char *words
, size_t *offset
, int flags
,
78 wordexp_t
*pwordexp
, const char *ifs
,
79 const char *ifs_white
)
81 static int eval_expr (char *expr
, long int *result
) internal_function
;
83 /* The w_*() functions manipulate word lists. */
87 /* Result of w_newword will be ignored if it's the last word. */
89 w_newword (size_t *actlen
, size_t *maxlen
)
91 *actlen
= *maxlen
= 0;
96 w_addchar (char *buffer
, size_t *actlen
, size_t *maxlen
, char ch
)
97 /* (lengths exclude trailing zero) */
99 /* Add a character to the buffer, allocating room for it if needed. */
101 if (*actlen
== *maxlen
)
103 char *old_buffer
= buffer
;
104 assert (buffer
== NULL
|| *maxlen
!= 0);
106 buffer
= (char *) realloc (buffer
, 1 + *maxlen
);
114 buffer
[*actlen
] = ch
;
115 buffer
[++(*actlen
)] = '\0';
123 w_addmem (char *buffer
, size_t *actlen
, size_t *maxlen
, const char *str
,
126 /* Add a string to the buffer, allocating room for it if needed.
128 if (*actlen
+ len
> *maxlen
)
130 char *old_buffer
= buffer
;
131 assert (buffer
== NULL
|| *maxlen
!= 0);
132 *maxlen
+= MAX (2 * len
, W_CHUNK
);
133 buffer
= realloc (old_buffer
, 1 + *maxlen
);
141 *((char *) __mempcpy (&buffer
[*actlen
], str
, len
)) = '\0';
150 w_addstr (char *buffer
, size_t *actlen
, size_t *maxlen
, const char *str
)
151 /* (lengths exclude trailing zero) */
153 /* Add a string to the buffer, allocating room for it if needed.
157 assert (str
!= NULL
); /* w_addstr only called from this file */
160 return w_addmem (buffer
, actlen
, maxlen
, str
, len
);
165 w_addword (wordexp_t
*pwordexp
, char *word
)
167 /* Add a word to the wordlist */
170 bool allocated
= false;
172 /* Internally, NULL acts like "". Convert NULLs to "" before
173 * the caller sees them.
177 word
= __strdup ("");
183 num_p
= 2 + pwordexp
->we_wordc
+ pwordexp
->we_offs
;
184 new_wordv
= realloc (pwordexp
->we_wordv
, sizeof (char *) * num_p
);
185 if (new_wordv
!= NULL
)
187 pwordexp
->we_wordv
= new_wordv
;
188 pwordexp
->we_wordv
[pwordexp
->we_offs
+ pwordexp
->we_wordc
++] = word
;
189 pwordexp
->we_wordv
[pwordexp
->we_offs
+ pwordexp
->we_wordc
] = NULL
;
200 /* The parse_*() functions should leave *offset being the offset in 'words'
201 * to the last character processed.
206 parse_backslash (char **word
, size_t *word_length
, size_t *max_length
,
207 const char *words
, size_t *offset
)
209 /* We are poised _at_ a backslash, not in quotes */
211 switch (words
[1 + *offset
])
214 /* Backslash is last character of input words */
222 *word
= w_addchar (*word
, word_length
, max_length
, words
[1 + *offset
]);
235 parse_qtd_backslash (char **word
, size_t *word_length
, size_t *max_length
,
236 const char *words
, size_t *offset
)
238 /* We are poised _at_ a backslash, inside quotes */
240 switch (words
[1 + *offset
])
243 /* Backslash is last character of input words */
254 *word
= w_addchar (*word
, word_length
, max_length
, words
[1 + *offset
]);
262 *word
= w_addchar (*word
, word_length
, max_length
, words
[*offset
]);
264 *word
= w_addchar (*word
, word_length
, max_length
, words
[1 + *offset
]);
278 parse_tilde (char **word
, size_t *word_length
, size_t *max_length
,
279 const char *words
, size_t *offset
, size_t wordc
)
281 /* We are poised _at_ a tilde */
284 if (*word_length
!= 0)
286 if (!((*word
)[*word_length
- 1] == '=' && wordc
== 0))
288 if (!((*word
)[*word_length
- 1] == ':'
289 && strchr (*word
, '=') && wordc
== 0))
291 *word
= w_addchar (*word
, word_length
, max_length
, '~');
292 return *word
? 0 : WRDE_NOSPACE
;
297 for (i
= 1 + *offset
; words
[i
]; i
++)
299 if (words
[i
] == ':' || words
[i
] == '/' || words
[i
] == ' ' ||
300 words
[i
] == '\t' || words
[i
] == 0 )
303 if (words
[i
] == '\\')
305 *word
= w_addchar (*word
, word_length
, max_length
, '~');
306 return *word
? 0 : WRDE_NOSPACE
;
310 if (i
== 1 + *offset
)
312 /* Tilde appears on its own */
314 struct passwd pwd
, *tpwd
;
320 /* POSIX.2 says ~ expands to $HOME and if HOME is unset the
321 results are unspecified. We do a lookup on the uid if
324 home
= getenv ("HOME");
327 *word
= w_addstr (*word
, word_length
, max_length
, home
);
334 buffer
= __alloca (buflen
);
336 while ((result
= __getpwuid_r (uid
, &pwd
, buffer
, buflen
, &tpwd
)) != 0
338 buffer
= extend_alloca (buffer
, buflen
, buflen
+ 1000);
340 if (result
== 0 && tpwd
!= NULL
&& pwd
.pw_dir
!= NULL
)
342 *word
= w_addstr (*word
, word_length
, max_length
, pwd
.pw_dir
);
348 *word
= w_addchar (*word
, word_length
, max_length
, '~');
356 /* Look up user name in database to get home directory */
357 char *user
= strndupa (&words
[1 + *offset
], i
- (1 + *offset
));
358 struct passwd pwd
, *tpwd
;
360 char* buffer
= __alloca (buflen
);
363 while ((result
= __getpwnam_r (user
, &pwd
, buffer
, buflen
, &tpwd
)) != 0
365 buffer
= extend_alloca (buffer
, buflen
, buflen
+ 1000);
367 if (result
== 0 && tpwd
!= NULL
&& pwd
.pw_dir
)
368 *word
= w_addstr (*word
, word_length
, max_length
, pwd
.pw_dir
);
371 /* (invalid login name) */
372 *word
= w_addchar (*word
, word_length
, max_length
, '~');
374 *word
= w_addstr (*word
, word_length
, max_length
, user
);
379 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
))
442 parse_glob (char **word
, size_t *word_length
, size_t *max_length
,
443 const char *words
, size_t *offset
, int flags
,
444 wordexp_t
*pwordexp
, const char *ifs
, const char *ifs_white
)
446 /* We are poised just after a '*', a '[' or a '?'. */
447 int error
= WRDE_NOSPACE
;
448 int quoted
= 0; /* 1 if singly-quoted, 2 if doubly */
450 wordexp_t glob_list
; /* List of words to glob */
452 glob_list
.we_wordc
= 0;
453 glob_list
.we_wordv
= NULL
;
454 glob_list
.we_offs
= 0;
455 for (; words
[*offset
] != '\0'; ++*offset
)
457 if (strchr (ifs
, words
[*offset
]) != NULL
)
461 /* Sort out quoting */
462 if (words
[*offset
] == '\'')
469 else if (quoted
== 1)
475 else if (words
[*offset
] == '"')
482 else if (quoted
== 2)
489 /* Sort out other special characters */
490 if (quoted
!= 1 && words
[*offset
] == '$')
492 error
= parse_dollars (word
, word_length
, max_length
, words
,
493 offset
, flags
, &glob_list
, ifs
, ifs_white
,
500 else if (words
[*offset
] == '\\')
503 error
= parse_qtd_backslash (word
, word_length
, max_length
,
506 error
= parse_backslash (word
, word_length
, max_length
,
515 *word
= w_addchar (*word
, word_length
, max_length
, words
[*offset
]);
520 /* Don't forget to re-parse the character we stopped at. */
524 error
= w_addword (&glob_list
, *word
);
525 *word
= w_newword (word_length
, max_length
);
526 for (i
= 0; error
== 0 && i
< glob_list
.we_wordc
; i
++)
527 error
= do_parse_glob (glob_list
.we_wordv
[i
], word
, word_length
,
528 max_length
, pwordexp
, ifs
, ifs_white
);
532 wordfree (&glob_list
);
538 parse_squote (char **word
, size_t *word_length
, size_t *max_length
,
539 const char *words
, size_t *offset
)
541 /* We are poised just after a single quote */
542 for (; words
[*offset
]; ++(*offset
))
544 if (words
[*offset
] != '\'')
546 *word
= w_addchar (*word
, word_length
, max_length
, words
[*offset
]);
553 /* Unterminated string */
557 /* Functions to evaluate an arithmetic expression */
560 eval_expr_val (char **expr
, long int *result
)
564 /* Skip white space */
565 for (digit
= *expr
; digit
&& *digit
&& isspace (*digit
); ++digit
);
569 /* Scan for closing paren */
570 for (++digit
; **expr
&& **expr
!= ')'; ++(*expr
));
578 if (eval_expr (digit
, result
))
584 /* POSIX requires that decimal, octal, and hexadecimal constants are
585 recognized. Therefore we pass 0 as the third parameter to strtol. */
586 *result
= strtol (digit
, expr
, 0);
595 eval_expr_multdiv (char **expr
, long int *result
)
600 if (eval_expr_val (expr
, result
) != 0)
605 /* Skip white space */
606 for (; *expr
&& **expr
&& isspace (**expr
); ++(*expr
));
611 if (eval_expr_val (expr
, &arg
) != 0)
616 else if (**expr
== '/')
619 if (eval_expr_val (expr
, &arg
) != 0)
632 eval_expr (char *expr
, long int *result
)
637 if (eval_expr_multdiv (&expr
, result
) != 0)
642 /* Skip white space */
643 for (; expr
&& *expr
&& isspace (*expr
); ++expr
);
648 if (eval_expr_multdiv (&expr
, &arg
) != 0)
653 else if (*expr
== '-')
656 if (eval_expr_multdiv (&expr
, &arg
) != 0)
669 parse_arith (char **word
, size_t *word_length
, size_t *max_length
,
670 const char *words
, size_t *offset
, int flags
, int bracket
)
672 /* We are poised just after "$((" or "$[" */
679 expr
= w_newword (&expr_length
, &expr_maxlen
);
680 for (; words
[*offset
]; ++(*offset
))
682 switch (words
[*offset
])
685 error
= parse_dollars (&expr
, &expr_length
, &expr_maxlen
,
686 words
, offset
, flags
, NULL
, NULL
, NULL
, 1);
687 /* The ``1'' here is to tell parse_dollars not to
699 error
= parse_backtick (&expr
, &expr_length
, &expr_maxlen
,
700 words
, offset
, flags
, NULL
, NULL
, NULL
);
701 /* The first NULL here is to tell parse_backtick not to
712 error
= parse_qtd_backslash (&expr
, &expr_length
, &expr_maxlen
,
719 /* I think that a backslash within an
720 * arithmetic expansion is bound to
721 * cause an error sooner or later anyway though.
726 if (--paren_depth
== 0)
728 char result
[21]; /* 21 = ceil(log10(2^64)) + 1 */
729 long int numresult
= 0;
730 long long int convertme
;
732 if (bracket
|| words
[1 + *offset
] != ')')
741 if (*expr
&& eval_expr (expr
, &numresult
) != 0)
749 convertme
= -numresult
;
750 *word
= w_addchar (*word
, word_length
, max_length
, '-');
758 convertme
= numresult
;
761 *word
= w_addstr (*word
, word_length
, max_length
,
762 _itoa (convertme
, &result
[20], 10, 0));
764 return *word
? 0 : WRDE_NOSPACE
;
766 expr
= w_addchar (expr
, &expr_length
, &expr_maxlen
, words
[*offset
]);
773 if (bracket
&& paren_depth
== 1)
775 char result
[21]; /* 21 = ceil(log10(2^64)) + 1 */
776 long int numresult
= 0;
779 if (*expr
&& eval_expr (expr
, &numresult
) != 0)
786 *word
= w_addstr (*word
, word_length
, max_length
,
787 _itoa_word (numresult
, &result
[20], 10, 0));
789 return *word
? 0 : WRDE_NOSPACE
;
805 expr
= w_addchar (expr
, &expr_length
, &expr_maxlen
, words
[*offset
]);
816 /* Function called by child process in exec_comm() */
818 internal_function
__attribute__ ((always_inline
))
819 exec_comm_child (char *comm
, int *fildes
, int showerr
, int noexec
)
821 const char *args
[4] = { _PATH_BSHELL
, "-c", comm
, NULL
};
823 /* Execute the command, or just check syntax? */
827 /* Redirect output. */
828 if (__builtin_expect (fildes
[1] != STDOUT_FILENO
, 1))
830 __dup2 (fildes
[1], STDOUT_FILENO
);
836 /* Reset the close-on-exec flag (if necessary). */
837 # ifndef __ASSUME_PIPE2
838 if (__have_pipe2
> 0)
840 __fcntl (fildes
[1], F_SETFD
, 0);
844 /* Redirect stderr to /dev/null if we have to. */
849 __close (STDERR_FILENO
);
850 fd
= __open (_PATH_DEVNULL
, O_WRONLY
);
851 if (fd
>= 0 && fd
!= STDERR_FILENO
)
853 __dup2 (fd
, STDERR_FILENO
);
856 /* Be paranoid. Check that we actually opened the /dev/null
858 if (__builtin_expect (__fxstat64 (_STAT_VER
, STDERR_FILENO
, &st
), 0) != 0
859 || __builtin_expect (S_ISCHR (st
.st_mode
), 1) == 0
860 #if defined DEV_NULL_MAJOR && defined DEV_NULL_MINOR
861 || st
.st_rdev
!= makedev (DEV_NULL_MAJOR
, DEV_NULL_MINOR
)
864 /* It's not the /dev/null device. Stop right here. The
865 problem is: how do we stop? We use _exit() with an
866 hopefully unusual exit code. */
870 /* Make sure the subshell doesn't field-split on our behalf. */
874 __execve (_PATH_BSHELL
, (char *const *) args
, __environ
);
880 /* Function to execute a command and retrieve the results */
881 /* pwordexp contains NULL if field-splitting is forbidden */
884 exec_comm (char *comm
, char **word
, size_t *word_length
, size_t *max_length
,
885 int flags
, wordexp_t
*pwordexp
, const char *ifs
,
886 const char *ifs_white
)
893 size_t maxnewlines
= 0;
894 char buffer
[bufsize
];
898 /* Don't fork() unless necessary */
903 # ifndef __ASSUME_PIPE2
904 if (__have_pipe2
>= 0)
907 int r
= __pipe2 (fildes
, O_CLOEXEC
);
908 # ifndef __ASSUME_PIPE2
909 if (__have_pipe2
== 0)
910 __have_pipe2
= r
!= -1 || errno
!= ENOSYS
? 1 : -1;
912 if (__have_pipe2
> 0)
919 #ifndef __ASSUME_PIPE2
921 if (__have_pipe2
< 0)
923 if (__pipe (fildes
) < 0)
929 if ((pid
= __fork ()) < 0)
938 exec_comm_child (comm
, fildes
, noexec
? 0 : flags
& WRDE_SHOWERR
, noexec
);
942 /* If we are just testing the syntax, only wait. */
944 return (TEMP_FAILURE_RETRY (__waitpid (pid
, &status
, 0)) == pid
945 && status
!= 0) ? WRDE_SYNTAX
: 0;
951 /* Quoted - no field splitting */
955 if ((buflen
= TEMP_FAILURE_RETRY (__read (fildes
[0], buffer
,
958 if (TEMP_FAILURE_RETRY (__waitpid (pid
, &status
, WNOHANG
)) == 0)
960 if ((buflen
= TEMP_FAILURE_RETRY (__read (fildes
[0], buffer
,
965 maxnewlines
+= buflen
;
967 *word
= w_addmem (*word
, word_length
, max_length
, buffer
, buflen
);
973 /* Not quoted - split fields */
977 * 0 when searching for first character in a field not IFS white space
978 * 1 when copying the text of a field
979 * 2 when searching for possible non-whitespace IFS
980 * 3 when searching for non-newline after copying field
985 if ((buflen
= TEMP_FAILURE_RETRY (__read (fildes
[0], buffer
,
988 if (TEMP_FAILURE_RETRY (__waitpid (pid
, &status
, WNOHANG
)) == 0)
990 if ((buflen
= TEMP_FAILURE_RETRY (__read (fildes
[0], buffer
,
995 for (i
= 0; i
< buflen
; ++i
)
997 if (strchr (ifs
, buffer
[i
]) != NULL
)
999 /* Current character is IFS */
1000 if (strchr (ifs_white
, buffer
[i
]) == NULL
)
1002 /* Current character is IFS but not whitespace */
1005 /* current character
1008 * eg: text<space><comma><space>moretext
1010 * So, strip whitespace IFS (like at the start)
1017 /* fall through and delimit field.. */
1021 if (buffer
[i
] == '\n')
1023 /* Current character is (IFS) newline */
1025 /* If copying a field, this is the end of it,
1026 but maybe all that's left is trailing newlines.
1027 So start searching for a non-newline. */
1035 /* Current character is IFS white space, but
1038 /* If not either copying a field or searching
1039 for non-newline after a field, ignore it */
1040 if (copying
!= 1 && copying
!= 3)
1043 /* End of field (search for non-ws IFS afterwards) */
1048 /* First IFS white space (non-newline), or IFS non-whitespace.
1049 * Delimit the field. Nulls are converted by w_addword. */
1050 if (w_addword (pwordexp
, *word
) == WRDE_NOSPACE
)
1053 *word
= w_newword (word_length
, max_length
);
1056 /* fall back round the loop.. */
1060 /* Not IFS character */
1064 /* Nothing but (IFS) newlines since the last field,
1065 so delimit it here before starting new word */
1066 if (w_addword (pwordexp
, *word
) == WRDE_NOSPACE
)
1069 *word
= w_newword (word_length
, max_length
);
1074 if (buffer
[i
] == '\n') /* happens if newline not in IFS */
1079 *word
= w_addchar (*word
, word_length
, max_length
,
1088 /* Chop off trailing newlines (required by POSIX.2) */
1089 /* Ensure we don't go back further than the beginning of the
1090 substitution (i.e. remove maxnewlines bytes at most) */
1091 while (maxnewlines
-- != 0 &&
1092 *word_length
> 0 && (*word
)[*word_length
- 1] == '\n')
1094 (*word
)[--*word_length
] = '\0';
1096 /* If the last word was entirely newlines, turn it into a new word
1097 * which can be ignored if there's nothing following it. */
1098 if (*word_length
== 0)
1101 *word
= w_newword (word_length
, max_length
);
1106 __close (fildes
[0]);
1109 /* Check for syntax error (re-execute but with "-n" flag) */
1110 if (buflen
< 1 && status
!= 0)
1119 __kill (pid
, SIGKILL
);
1120 TEMP_FAILURE_RETRY (__waitpid (pid
, NULL
, 0));
1121 __close (fildes
[0]);
1122 return WRDE_NOSPACE
;
1127 parse_comm (char **word
, size_t *word_length
, size_t *max_length
,
1128 const char *words
, size_t *offset
, int flags
, wordexp_t
*pwordexp
,
1129 const char *ifs
, const char *ifs_white
)
1131 /* We are poised just after "$(" */
1132 int paren_depth
= 1;
1134 int quoted
= 0; /* 1 for singly-quoted, 2 for doubly-quoted */
1137 char *comm
= w_newword (&comm_length
, &comm_maxlen
);
1139 for (; words
[*offset
]; ++(*offset
))
1141 switch (words
[*offset
])
1146 else if (quoted
== 1)
1154 else if (quoted
== 2)
1160 if (!quoted
&& --paren_depth
== 0)
1162 /* Go -- give script to the shell */
1165 #ifdef __libc_ptf_call
1166 /* We do not want the exec_comm call to be cut short
1167 by a thread cancellation since cleanup is very
1168 ugly. Therefore disable cancellation for
1170 // XXX Ideally we do want the thread being cancelable.
1171 // XXX If demand is there we'll change it.
1172 int state
= PTHREAD_CANCEL_ENABLE
;
1173 __libc_ptf_call (pthread_setcancelstate
,
1174 (PTHREAD_CANCEL_DISABLE
, &state
), 0);
1177 error
= exec_comm (comm
, word
, word_length
, max_length
,
1178 flags
, pwordexp
, ifs
, ifs_white
);
1180 #ifdef __libc_ptf_call
1181 __libc_ptf_call (pthread_setcancelstate
, (state
, NULL
), 0);
1190 /* This is just part of the script */
1198 comm
= w_addchar (comm
, &comm_length
, &comm_maxlen
, words
[*offset
]);
1200 return WRDE_NOSPACE
;
1203 /* Premature end. */
1211 parse_param (char **word
, size_t *word_length
, size_t *max_length
,
1212 const char *words
, size_t *offset
, int flags
, wordexp_t
*pwordexp
,
1213 const char *ifs
, const char *ifs_white
, int quoted
)
1215 /* We are poised just after "$" */
1219 ACT_RP_SHORT_LEFT
= '#',
1220 ACT_RP_LONG_LEFT
= 'L',
1221 ACT_RP_SHORT_RIGHT
= '%',
1222 ACT_RP_LONG_RIGHT
= 'R',
1223 ACT_NULL_ERROR
= '?',
1224 ACT_NULL_SUBST
= '-',
1225 ACT_NONNULL_SUBST
= '+',
1226 ACT_NULL_ASSIGN
= '='
1232 size_t start
= *offset
;
1236 enum action action
= ACT_NONE
;
1241 int pattern_is_quoted
= 0; /* 1 for singly-quoted, 2 for doubly-quoted */
1245 int brace
= words
[*offset
] == '{';
1247 env
= w_newword (&env_length
, &env_maxlen
);
1248 pattern
= w_newword (&pat_length
, &pat_maxlen
);
1253 /* First collect the parameter name. */
1255 if (words
[*offset
] == '#')
1263 if (isalpha (words
[*offset
]) || words
[*offset
] == '_')
1265 /* Normal parameter name. */
1268 env
= w_addchar (env
, &env_length
, &env_maxlen
,
1273 while (isalnum (words
[++*offset
]) || words
[*offset
] == '_');
1275 else if (isdigit (words
[*offset
]))
1277 /* Numeric parameter name. */
1281 env
= w_addchar (env
, &env_length
, &env_maxlen
,
1288 while (isdigit(words
[++*offset
]));
1290 else if (strchr ("*@$", words
[*offset
]) != NULL
)
1292 /* Special parameter. */
1294 env
= w_addchar (env
, &env_length
, &env_maxlen
,
1308 /* Check for special action to be applied to the value. */
1309 switch (words
[*offset
])
1316 action
= ACT_RP_SHORT_LEFT
;
1317 if (words
[1 + *offset
] == '#')
1320 action
= ACT_RP_LONG_LEFT
;
1325 action
= ACT_RP_SHORT_RIGHT
;
1326 if (words
[1 + *offset
] == '%')
1329 action
= ACT_RP_LONG_RIGHT
;
1334 if (strchr ("-=?+", words
[1 + *offset
]) == NULL
)
1338 action
= words
[++*offset
];
1345 action
= words
[*offset
];
1352 /* Now collect the pattern, but don't expand it yet. */
1354 for (; words
[*offset
]; ++(*offset
))
1356 switch (words
[*offset
])
1359 if (!pattern_is_quoted
)
1364 if (!pattern_is_quoted
)
1373 if (pattern_is_quoted
)
1374 /* Quoted; treat as normal character. */
1377 /* Otherwise, it's an escape: next character is literal. */
1378 if (words
[++*offset
] == '\0')
1381 pattern
= w_addchar (pattern
, &pat_length
, &pat_maxlen
, '\\');
1382 if (pattern
== NULL
)
1388 if (pattern_is_quoted
== 0)
1389 pattern_is_quoted
= 1;
1390 else if (pattern_is_quoted
== 1)
1391 pattern_is_quoted
= 0;
1396 if (pattern_is_quoted
== 0)
1397 pattern_is_quoted
= 2;
1398 else if (pattern_is_quoted
== 2)
1399 pattern_is_quoted
= 0;
1404 pattern
= w_addchar (pattern
, &pat_length
, &pat_maxlen
,
1406 if (pattern
== NULL
)
1411 /* End of input string -- remember to reparse the character that we
1416 if (words
[start
] == '{' && words
[*offset
] != '}')
1423 /* $# expands to the number of positional parameters */
1425 value
= _itoa_word (__libc_argc
- 1, &buffer
[20], 10, 0);
1430 /* Just $ on its own */
1431 *offset
= start
- 1;
1432 *word
= w_addchar (*word
, word_length
, max_length
, '$');
1433 return *word
? 0 : WRDE_NOSPACE
;
1436 /* Is it a numeric parameter? */
1437 else if (isdigit (env
[0]))
1441 if (n
>= __libc_argc
)
1442 /* Substitute NULL. */
1445 /* Replace with appropriate positional parameter. */
1446 value
= __libc_argv
[n
];
1448 /* Is it a special parameter? */
1455 value
= _itoa_word (__getpid (), &buffer
[20], 10, 0);
1457 /* Is it `${#*}' or `${#@}'? */
1458 else if ((*env
== '*' || *env
== '@') && seen_hash
)
1461 value
= _itoa_word (__libc_argc
> 0 ? __libc_argc
- 1 : 0,
1462 &buffer
[20], 10, 0);
1463 *word
= w_addstr (*word
, word_length
, max_length
, value
);
1466 return *word
? 0 : WRDE_NOSPACE
;
1468 /* Is it `$*' or `$@' (unquoted) ? */
1469 else if (*env
== '*' || (*env
== '@' && !quoted
))
1471 size_t plist_len
= 0;
1475 /* Build up value parameter by parameter (copy them) */
1476 for (p
= 1; __libc_argv
[p
]; ++p
)
1477 plist_len
+= strlen (__libc_argv
[p
]) + 1; /* for space */
1478 value
= malloc (plist_len
);
1483 for (p
= 1; __libc_argv
[p
]; ++p
)
1487 end
= __stpcpy (end
, __libc_argv
[p
]);
1494 /* Must be a quoted `$@' */
1495 assert (*env
== '@' && quoted
);
1497 /* Each parameter is a separate word ("$@") */
1498 if (__libc_argc
== 2)
1499 value
= __libc_argv
[1];
1500 else if (__libc_argc
> 2)
1504 /* Append first parameter to current word. */
1505 value
= w_addstr (*word
, word_length
, max_length
,
1507 if (value
== NULL
|| w_addword (pwordexp
, value
))
1510 for (p
= 2; __libc_argv
[p
+ 1]; p
++)
1512 char *newword
= __strdup (__libc_argv
[p
]);
1513 if (newword
== NULL
|| w_addword (pwordexp
, newword
))
1517 /* Start a new word with the last parameter. */
1518 *word
= w_newword (word_length
, max_length
);
1519 value
= __libc_argv
[p
];
1530 value
= getenv (env
);
1532 if (value
== NULL
&& (flags
& WRDE_UNDEF
))
1534 /* Variable not defined. */
1535 error
= WRDE_BADVAL
;
1539 if (action
!= ACT_NONE
)
1541 int expand_pattern
= 0;
1543 /* First, find out if we need to expand pattern (i.e. if we will
1547 case ACT_RP_SHORT_LEFT
:
1548 case ACT_RP_LONG_LEFT
:
1549 case ACT_RP_SHORT_RIGHT
:
1550 case ACT_RP_LONG_RIGHT
:
1551 /* Always expand for these. */
1555 case ACT_NULL_ERROR
:
1556 case ACT_NULL_SUBST
:
1557 case ACT_NULL_ASSIGN
:
1558 if (!value
|| (!*value
&& colon_seen
))
1559 /* If param is unset, or set but null and a colon has been seen,
1560 the expansion of the pattern will be needed. */
1565 case ACT_NONNULL_SUBST
:
1566 /* Expansion of word will be needed if parameter is set and not null,
1567 or set null but no colon has been seen. */
1568 if (value
&& (*value
|| !colon_seen
))
1574 assert (! "Unrecognised action!");
1579 /* We need to perform tilde expansion, parameter expansion,
1580 command substitution, and arithmetic expansion. We also
1581 have to be a bit careful with wildcard characters, as
1582 pattern might be given to fnmatch soon. To do this, we
1583 convert quotes to escapes. */
1589 int quoted
= 0; /* 1: single quotes; 2: double */
1591 expanded
= w_newword (&exp_len
, &exp_maxl
);
1592 for (p
= pattern
; p
&& *p
; p
++)
1601 else if (quoted
== 0)
1610 else if (quoted
== 0)
1620 /* Convert quoted wildchar to escaped wildchar. */
1621 expanded
= w_addchar (expanded
, &exp_len
,
1624 if (expanded
== NULL
)
1631 error
= parse_dollars (&expanded
, &exp_len
, &exp_maxl
, p
,
1632 &offset
, flags
, NULL
, NULL
, NULL
, 1);
1647 if (quoted
|| exp_len
)
1651 error
= parse_tilde (&expanded
, &exp_len
, &exp_maxl
, p
,
1667 expanded
= w_addchar (expanded
, &exp_len
, &exp_maxl
, '\\');
1669 assert (*p
); /* checked when extracted initially */
1670 if (expanded
== NULL
)
1674 expanded
= w_addchar (expanded
, &exp_len
, &exp_maxl
, *p
);
1676 if (expanded
== NULL
)
1687 case ACT_RP_SHORT_LEFT
:
1688 case ACT_RP_LONG_LEFT
:
1689 case ACT_RP_SHORT_RIGHT
:
1690 case ACT_RP_LONG_RIGHT
:
1696 if (value
== NULL
|| pattern
== NULL
|| *pattern
== '\0')
1699 end
= value
+ strlen (value
);
1703 case ACT_RP_SHORT_LEFT
:
1704 for (p
= value
; p
<= end
; ++p
)
1708 if (fnmatch (pattern
, value
, 0) != FNM_NOMATCH
)
1713 char *newval
= __strdup (p
);
1731 case ACT_RP_LONG_LEFT
:
1732 for (p
= end
; p
>= value
; --p
)
1736 if (fnmatch (pattern
, value
, 0) != FNM_NOMATCH
)
1741 char *newval
= __strdup (p
);
1759 case ACT_RP_SHORT_RIGHT
:
1760 for (p
= end
; p
>= value
; --p
)
1762 if (fnmatch (pattern
, p
, 0) != FNM_NOMATCH
)
1765 newval
= malloc (p
- value
+ 1);
1774 *(char *) __mempcpy (newval
, value
, p
- value
) = '\0';
1785 case ACT_RP_LONG_RIGHT
:
1786 for (p
= value
; p
<= end
; ++p
)
1788 if (fnmatch (pattern
, p
, 0) != FNM_NOMATCH
)
1791 newval
= malloc (p
- value
+ 1);
1800 *(char *) __mempcpy (newval
, value
, p
- value
) = '\0';
1818 case ACT_NULL_ERROR
:
1819 if (value
&& *value
)
1820 /* Substitute parameter */
1824 if (!colon_seen
&& value
)
1825 /* Substitute NULL */
1829 const char *str
= pattern
;
1832 str
= _("parameter null or not set");
1834 __fxprintf (NULL
, "%s: %s\n", env
, str
);
1841 case ACT_NULL_SUBST
:
1842 if (value
&& *value
)
1843 /* Substitute parameter */
1849 if (!colon_seen
&& value
)
1850 /* Substitute NULL */
1853 value
= pattern
? __strdup (pattern
) : pattern
;
1856 if (pattern
&& !value
)
1861 case ACT_NONNULL_SUBST
:
1862 if (value
&& (*value
|| !colon_seen
))
1867 value
= pattern
? __strdup (pattern
) : pattern
;
1870 if (pattern
&& !value
)
1876 /* Substitute NULL */
1881 case ACT_NULL_ASSIGN
:
1882 if (value
&& *value
)
1883 /* Substitute parameter */
1886 if (!colon_seen
&& value
)
1888 /* Substitute NULL */
1897 value
= pattern
? __strdup (pattern
) : pattern
;
1900 if (pattern
&& !value
)
1903 __setenv (env
, value
, 1);
1907 assert (! "Unrecognised action!");
1918 char param_length
[21];
1919 param_length
[20] = '\0';
1920 *word
= w_addstr (*word
, word_length
, max_length
,
1921 _itoa_word (value
? strlen (value
) : 0,
1922 ¶m_length
[20], 10, 0));
1925 assert (value
!= NULL
);
1929 return *word
? 0 : WRDE_NOSPACE
;
1935 if (quoted
|| !pwordexp
)
1937 /* Quoted - no field split */
1938 *word
= w_addstr (*word
, word_length
, max_length
, value
);
1942 return *word
? 0 : WRDE_NOSPACE
;
1946 /* Need to field-split */
1947 char *value_copy
= __strdup (value
); /* Don't modify value */
1948 char *field_begin
= value_copy
;
1949 int seen_nonws_ifs
= 0;
1954 if (value_copy
== NULL
)
1959 char *field_end
= field_begin
;
1962 /* If this isn't the first field, start a new word */
1963 if (field_begin
!= value_copy
)
1965 if (w_addword (pwordexp
, *word
) == WRDE_NOSPACE
)
1971 *word
= w_newword (word_length
, max_length
);
1974 /* Skip IFS whitespace before the field */
1975 field_begin
+= strspn (field_begin
, ifs_white
);
1977 if (!seen_nonws_ifs
&& *field_begin
== 0)
1978 /* Nothing but whitespace */
1981 /* Search for the end of the field */
1982 field_end
= field_begin
+ strcspn (field_begin
, ifs
);
1984 /* Set up pointer to the character after end of field and
1985 skip whitespace IFS after it. */
1986 next_field
= field_end
+ strspn (field_end
, ifs_white
);
1988 /* Skip at most one non-whitespace IFS character after the field */
1990 if (*next_field
&& strchr (ifs
, *next_field
))
1996 /* Null-terminate it */
1999 /* Tag a copy onto the current word */
2000 *word
= w_addstr (*word
, word_length
, max_length
, field_begin
);
2002 if (*word
== NULL
&& *field_begin
!= '\0')
2008 field_begin
= next_field
;
2010 while (seen_nonws_ifs
|| *field_begin
);
2022 error
= WRDE_NOSPACE
;
2026 error
= WRDE_SYNTAX
;
2038 parse_dollars (char **word
, size_t *word_length
, size_t *max_length
,
2039 const char *words
, size_t *offset
, int flags
,
2040 wordexp_t
*pwordexp
, const char *ifs
, const char *ifs_white
,
2043 /* We are poised _at_ "$" */
2044 switch (words
[1 + *offset
])
2049 *word
= w_addchar (*word
, word_length
, max_length
, '$');
2050 return *word
? 0 : WRDE_NOSPACE
;
2053 if (words
[2 + *offset
] == '(')
2055 /* Differentiate between $((1+3)) and $((echo);(ls)) */
2056 int i
= 3 + *offset
;
2058 while (words
[i
] && !(depth
== 0 && words
[i
] == ')'))
2060 if (words
[i
] == '(')
2062 else if (words
[i
] == ')')
2068 if (words
[i
] == ')' && words
[i
+ 1] == ')')
2071 /* Call parse_arith -- 0 is for "no brackets" */
2072 return parse_arith (word
, word_length
, max_length
, words
, offset
,
2077 if (flags
& WRDE_NOCMD
)
2081 return parse_comm (word
, word_length
, max_length
, words
, offset
, flags
,
2082 quoted
? NULL
: pwordexp
, ifs
, ifs_white
);
2086 /* Call parse_arith -- 1 is for "brackets" */
2087 return parse_arith (word
, word_length
, max_length
, words
, offset
, flags
,
2092 ++(*offset
); /* parse_param needs to know if "{" is there */
2093 return parse_param (word
, word_length
, max_length
, words
, offset
, flags
,
2094 pwordexp
, ifs
, ifs_white
, quoted
);
2100 parse_backtick (char **word
, size_t *word_length
, size_t *max_length
,
2101 const char *words
, size_t *offset
, int flags
,
2102 wordexp_t
*pwordexp
, const char *ifs
, const char *ifs_white
)
2104 /* We are poised just after "`" */
2109 char *comm
= w_newword (&comm_length
, &comm_maxlen
);
2111 for (; words
[*offset
]; ++(*offset
))
2113 switch (words
[*offset
])
2116 /* Go -- give the script to the shell */
2117 error
= exec_comm (comm
, word
, word_length
, max_length
, flags
,
2118 pwordexp
, ifs
, ifs_white
);
2125 error
= parse_qtd_backslash (&comm
, &comm_length
, &comm_maxlen
,
2138 error
= parse_backslash (&comm
, &comm_length
, &comm_maxlen
, words
,
2150 squoting
= 1 - squoting
;
2152 comm
= w_addchar (comm
, &comm_length
, &comm_maxlen
, words
[*offset
]);
2154 return WRDE_NOSPACE
;
2165 parse_dquote (char **word
, size_t *word_length
, size_t *max_length
,
2166 const char *words
, size_t *offset
, int flags
,
2167 wordexp_t
*pwordexp
, const char * ifs
, const char * ifs_white
)
2169 /* We are poised just after a double-quote */
2172 for (; words
[*offset
]; ++(*offset
))
2174 switch (words
[*offset
])
2180 error
= parse_dollars (word
, word_length
, max_length
, words
, offset
,
2181 flags
, pwordexp
, ifs
, ifs_white
, 1);
2182 /* The ``1'' here is to tell parse_dollars not to
2183 * split the fields. It may need to, however ("$@").
2191 if (flags
& WRDE_NOCMD
)
2195 error
= parse_backtick (word
, word_length
, max_length
, words
,
2196 offset
, flags
, NULL
, NULL
, NULL
);
2197 /* The first NULL here is to tell parse_backtick not to
2206 error
= parse_qtd_backslash (word
, word_length
, max_length
, words
,
2215 *word
= w_addchar (*word
, word_length
, max_length
, words
[*offset
]);
2217 return WRDE_NOSPACE
;
2221 /* Unterminated string */
2226 * wordfree() is to be called after pwordexp is finished with.
2230 wordfree (wordexp_t
*pwordexp
)
2233 /* wordexp can set pwordexp to NULL */
2234 if (pwordexp
&& pwordexp
->we_wordv
)
2236 char **wordv
= pwordexp
->we_wordv
;
2238 for (wordv
+= pwordexp
->we_offs
; *wordv
; ++wordv
)
2241 free (pwordexp
->we_wordv
);
2242 pwordexp
->we_wordv
= NULL
;
2245 libc_hidden_def (wordfree
)
2252 wordexp (const char *words
, wordexp_t
*pwordexp
, int flags
)
2254 size_t words_offset
;
2257 char *word
= w_newword (&word_length
, &max_length
);
2261 wordexp_t old_word
= *pwordexp
;
2263 if (flags
& WRDE_REUSE
)
2265 /* Minimal implementation of WRDE_REUSE for now */
2266 wordfree (pwordexp
);
2267 old_word
.we_wordv
= NULL
;
2270 if ((flags
& WRDE_APPEND
) == 0)
2272 pwordexp
->we_wordc
= 0;
2274 if (flags
& WRDE_DOOFFS
)
2276 pwordexp
->we_wordv
= calloc (1 + pwordexp
->we_offs
, sizeof (char *));
2277 if (pwordexp
->we_wordv
== NULL
)
2279 error
= WRDE_NOSPACE
;
2285 pwordexp
->we_wordv
= calloc (1, sizeof (char *));
2286 if (pwordexp
->we_wordv
== NULL
)
2288 error
= WRDE_NOSPACE
;
2292 pwordexp
->we_offs
= 0;
2296 /* Find out what the field separators are.
2297 * There are two types: whitespace and non-whitespace.
2299 ifs
= getenv ("IFS");
2302 /* IFS unset - use <space><tab><newline>. */
2303 ifs
= strcpy (ifs_white
, " \t\n");
2307 char *whch
= ifs_white
;
2309 while (*ifsch
!= '\0')
2311 if (*ifsch
== ' ' || *ifsch
== '\t' || *ifsch
== '\n')
2313 /* Whitespace IFS. See first whether it is already in our
2315 char *runp
= ifs_white
;
2317 while (runp
< whch
&& *runp
!= *ifsch
)
2329 for (words_offset
= 0 ; words
[words_offset
] ; ++words_offset
)
2330 switch (words
[words_offset
])
2333 error
= parse_backslash (&word
, &word_length
, &max_length
, words
,
2342 error
= parse_dollars (&word
, &word_length
, &max_length
, words
,
2343 &words_offset
, flags
, pwordexp
, ifs
, ifs_white
,
2352 if (flags
& WRDE_NOCMD
)
2354 error
= WRDE_CMDSUB
;
2359 error
= parse_backtick (&word
, &word_length
, &max_length
, words
,
2360 &words_offset
, flags
, pwordexp
, ifs
,
2370 error
= parse_dquote (&word
, &word_length
, &max_length
, words
,
2371 &words_offset
, flags
, pwordexp
, ifs
, ifs_white
);
2378 error
= w_addword (pwordexp
, NULL
);
2388 error
= parse_squote (&word
, &word_length
, &max_length
, words
,
2396 error
= w_addword (pwordexp
, NULL
);
2405 error
= parse_tilde (&word
, &word_length
, &max_length
, words
,
2406 &words_offset
, pwordexp
->we_wordc
);
2416 error
= parse_glob (&word
, &word_length
, &max_length
, words
,
2417 &words_offset
, flags
, pwordexp
, ifs
, ifs_white
);
2425 /* Is it a word separator? */
2426 if (strchr (" \t", words
[words_offset
]) == NULL
)
2428 char ch
= words
[words_offset
];
2430 /* Not a word separator -- but is it a valid word char? */
2431 if (strchr ("\n|&;<>(){}", ch
))
2434 error
= WRDE_BADCHAR
;
2438 /* "Ordinary" character -- add it to word */
2439 word
= w_addchar (word
, &word_length
, &max_length
,
2443 error
= WRDE_NOSPACE
;
2450 /* If a word has been delimited, add it to the list. */
2453 error
= w_addword (pwordexp
, word
);
2458 word
= w_newword (&word_length
, &max_length
);
2463 /* There was a word separator at the end */
2464 if (word
== NULL
) /* i.e. w_newword */
2467 /* There was no field separator at the end */
2468 return w_addword (pwordexp
, word
);
2472 * free memory used (unless error is WRDE_NOSPACE), and
2473 * set pwordexp members back to what they were.
2478 if (error
== WRDE_NOSPACE
)
2479 return WRDE_NOSPACE
;
2481 if ((flags
& WRDE_APPEND
) == 0)
2482 wordfree (pwordexp
);
2484 *pwordexp
= old_word
;