1 /* POSIX.2 wordexp implementation.
2 Copyright (C) 1997-2002, 2003, 2005, 2006 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>
46 #include <bits/libc-lock.h>
47 #include <stdio-common/_itoa.h>
49 /* Undefine the following line for the production version. */
50 /* #define NDEBUG 1 */
53 /* Get some device information. */
54 #include <device-nrs.h>
57 * This is a recursive-descent-style word expansion routine.
60 /* These variables are defined and initialized in the startup code. */
61 extern int __libc_argc attribute_hidden
;
62 extern char **__libc_argv attribute_hidden
;
64 /* Some forward declarations */
65 static int parse_dollars (char **word
, size_t *word_length
, size_t *max_length
,
66 const char *words
, size_t *offset
, int flags
,
67 wordexp_t
*pwordexp
, const char *ifs
,
68 const char *ifs_white
, int quoted
)
70 static int parse_backtick (char **word
, size_t *word_length
,
71 size_t *max_length
, const char *words
,
72 size_t *offset
, int flags
, wordexp_t
*pwordexp
,
73 const char *ifs
, const char *ifs_white
)
75 static int parse_dquote (char **word
, size_t *word_length
, size_t *max_length
,
76 const char *words
, size_t *offset
, int flags
,
77 wordexp_t
*pwordexp
, const char *ifs
,
78 const char *ifs_white
)
80 static int eval_expr (char *expr
, long int *result
) internal_function
;
82 /* The w_*() functions manipulate word lists. */
86 /* Result of w_newword will be ignored if it's the last word. */
88 w_newword (size_t *actlen
, size_t *maxlen
)
90 *actlen
= *maxlen
= 0;
95 w_addchar (char *buffer
, size_t *actlen
, size_t *maxlen
, char ch
)
96 /* (lengths exclude trailing zero) */
98 /* Add a character to the buffer, allocating room for it if needed. */
100 if (*actlen
== *maxlen
)
102 char *old_buffer
= buffer
;
103 assert (buffer
== NULL
|| *maxlen
!= 0);
105 buffer
= (char *) realloc (buffer
, 1 + *maxlen
);
113 buffer
[*actlen
] = ch
;
114 buffer
[++(*actlen
)] = '\0';
122 w_addmem (char *buffer
, size_t *actlen
, size_t *maxlen
, const char *str
,
125 /* Add a string to the buffer, allocating room for it if needed.
127 if (*actlen
+ len
> *maxlen
)
129 char *old_buffer
= buffer
;
130 assert (buffer
== NULL
|| *maxlen
!= 0);
131 *maxlen
+= MAX (2 * len
, W_CHUNK
);
132 buffer
= realloc (old_buffer
, 1 + *maxlen
);
140 *((char *) __mempcpy (&buffer
[*actlen
], str
, len
)) = '\0';
149 w_addstr (char *buffer
, size_t *actlen
, size_t *maxlen
, const char *str
)
150 /* (lengths exclude trailing zero) */
152 /* Add a string to the buffer, allocating room for it if needed.
156 assert (str
!= NULL
); /* w_addstr only called from this file */
159 return w_addmem (buffer
, actlen
, maxlen
, str
, len
);
164 w_addword (wordexp_t
*pwordexp
, char *word
)
166 /* Add a word to the wordlist */
169 bool allocated
= false;
171 /* Internally, NULL acts like "". Convert NULLs to "" before
172 * the caller sees them.
176 word
= __strdup ("");
182 num_p
= 2 + pwordexp
->we_wordc
+ pwordexp
->we_offs
;
183 new_wordv
= realloc (pwordexp
->we_wordv
, sizeof (char *) * num_p
);
184 if (new_wordv
!= NULL
)
186 pwordexp
->we_wordv
= new_wordv
;
187 pwordexp
->we_wordv
[pwordexp
->we_offs
+ pwordexp
->we_wordc
++] = word
;
188 pwordexp
->we_wordv
[pwordexp
->we_offs
+ pwordexp
->we_wordc
] = NULL
;
199 /* The parse_*() functions should leave *offset being the offset in 'words'
200 * to the last character processed.
205 parse_backslash (char **word
, size_t *word_length
, size_t *max_length
,
206 const char *words
, size_t *offset
)
208 /* We are poised _at_ a backslash, not in quotes */
210 switch (words
[1 + *offset
])
213 /* Backslash is last character of input words */
221 *word
= w_addchar (*word
, word_length
, max_length
, words
[1 + *offset
]);
234 parse_qtd_backslash (char **word
, size_t *word_length
, size_t *max_length
,
235 const char *words
, size_t *offset
)
237 /* We are poised _at_ a backslash, inside quotes */
239 switch (words
[1 + *offset
])
242 /* Backslash is last character of input words */
253 *word
= w_addchar (*word
, word_length
, max_length
, words
[1 + *offset
]);
261 *word
= w_addchar (*word
, word_length
, max_length
, words
[*offset
]);
263 *word
= w_addchar (*word
, word_length
, max_length
, words
[1 + *offset
]);
277 parse_tilde (char **word
, size_t *word_length
, size_t *max_length
,
278 const char *words
, size_t *offset
, size_t wordc
)
280 /* We are poised _at_ a tilde */
283 if (*word_length
!= 0)
285 if (!((*word
)[*word_length
- 1] == '=' && wordc
== 0))
287 if (!((*word
)[*word_length
- 1] == ':'
288 && strchr (*word
, '=') && wordc
== 0))
290 *word
= w_addchar (*word
, word_length
, max_length
, '~');
291 return *word
? 0 : WRDE_NOSPACE
;
296 for (i
= 1 + *offset
; words
[i
]; i
++)
298 if (words
[i
] == ':' || words
[i
] == '/' || words
[i
] == ' ' ||
299 words
[i
] == '\t' || words
[i
] == 0 )
302 if (words
[i
] == '\\')
304 *word
= w_addchar (*word
, word_length
, max_length
, '~');
305 return *word
? 0 : WRDE_NOSPACE
;
309 if (i
== 1 + *offset
)
311 /* Tilde appears on its own */
313 struct passwd pwd
, *tpwd
;
319 /* POSIX.2 says ~ expands to $HOME and if HOME is unset the
320 results are unspecified. We do a lookup on the uid if
323 home
= getenv ("HOME");
326 *word
= w_addstr (*word
, word_length
, max_length
, home
);
333 buffer
= __alloca (buflen
);
335 while ((result
= __getpwuid_r (uid
, &pwd
, buffer
, buflen
, &tpwd
)) != 0
337 buffer
= extend_alloca (buffer
, buflen
, buflen
+ 1000);
339 if (result
== 0 && tpwd
!= NULL
&& pwd
.pw_dir
!= NULL
)
341 *word
= w_addstr (*word
, word_length
, max_length
, pwd
.pw_dir
);
347 *word
= w_addchar (*word
, word_length
, max_length
, '~');
355 /* Look up user name in database to get home directory */
356 char *user
= strndupa (&words
[1 + *offset
], i
- (1 + *offset
));
357 struct passwd pwd
, *tpwd
;
359 char* buffer
= __alloca (buflen
);
362 while ((result
= __getpwnam_r (user
, &pwd
, buffer
, buflen
, &tpwd
)) != 0
364 buffer
= extend_alloca (buffer
, buflen
, buflen
+ 1000);
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
);
378 return *word
? 0 : WRDE_NOSPACE
;
384 do_parse_glob (const char *glob_word
, char **word
, size_t *word_length
,
385 size_t *max_length
, wordexp_t
*pwordexp
, const char *ifs
,
386 const char *ifs_white
)
392 error
= glob (glob_word
, GLOB_NOCHECK
, NULL
, &globbuf
);
396 /* We can only run into memory problems. */
397 assert (error
== GLOB_NOSPACE
);
403 /* No field splitting allowed. */
404 assert (globbuf
.gl_pathv
[0] != NULL
);
405 *word
= w_addstr (*word
, word_length
, max_length
, globbuf
.gl_pathv
[0]);
406 for (match
= 1; match
< globbuf
.gl_pathc
&& *word
!= NULL
; ++match
)
408 *word
= w_addchar (*word
, word_length
, max_length
, ' ');
410 *word
= w_addstr (*word
, word_length
, max_length
,
411 globbuf
.gl_pathv
[match
]);
415 return *word
? 0 : WRDE_NOSPACE
;
418 assert (ifs
== NULL
|| *ifs
!= '\0');
422 *word
= w_newword (word_length
, max_length
);
425 for (match
= 0; match
< globbuf
.gl_pathc
; ++match
)
427 char *matching_word
= __strdup (globbuf
.gl_pathv
[match
]);
428 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 ((ifs
&& strchr (ifs
, words
[*offset
])) ||
457 (!ifs
&& strchr (" \t\n", words
[*offset
])))
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 __dup2 (fildes
[1], STDOUT_FILENO
);
831 /* Redirect stderr to /dev/null if we have to. */
837 fd
= __open (_PATH_DEVNULL
, O_WRONLY
);
838 if (fd
>= 0 && fd
!= 2)
840 __dup2 (fd
, STDERR_FILENO
);
843 /* Be paranoid. Check that we actually opened the /dev/null
845 if (__builtin_expect (__fxstat64 (_STAT_VER
, STDERR_FILENO
, &st
), 0) != 0
846 || __builtin_expect (S_ISCHR (st
.st_mode
), 1) == 0
847 #if defined DEV_NULL_MAJOR && defined DEV_NULL_MINOR
848 || st
.st_rdev
!= makedev (DEV_NULL_MAJOR
, DEV_NULL_MINOR
)
851 /* It's not the /dev/null device. Stop right here. The
852 problem is: how do we stop? We use _exit() with an
853 hopefully unusual exit code. */
857 /* Make sure the subshell doesn't field-split on our behalf. */
861 __execve (_PATH_BSHELL
, (char *const *) args
, __environ
);
867 /* Function to execute a command and retrieve the results */
868 /* pwordexp contains NULL if field-splitting is forbidden */
871 exec_comm (char *comm
, char **word
, size_t *word_length
, size_t *max_length
,
872 int flags
, wordexp_t
*pwordexp
, const char *ifs
,
873 const char *ifs_white
)
880 size_t maxnewlines
= 0;
881 char buffer
[bufsize
];
885 /* Don't fork() unless necessary */
894 if ((pid
= __fork ()) < 0)
905 exec_comm_child (comm
, fildes
, noexec
? 0 : flags
& WRDE_SHOWERR
, noexec
);
909 /* If we are just testing the syntax, only wait. */
911 return (TEMP_FAILURE_RETRY (__waitpid (pid
, &status
, 0)) == pid
912 && status
!= 0) ? WRDE_SYNTAX
: 0;
918 /* Quoted - no field splitting */
922 if ((buflen
= TEMP_FAILURE_RETRY (__read (fildes
[0], buffer
,
925 if (TEMP_FAILURE_RETRY (__waitpid (pid
, &status
, WNOHANG
)) == 0)
927 if ((buflen
= TEMP_FAILURE_RETRY (__read (fildes
[0], buffer
,
932 maxnewlines
+= buflen
;
934 *word
= w_addmem (*word
, word_length
, max_length
, buffer
, buflen
);
940 /* Not quoted - split fields */
944 * 0 when searching for first character in a field not IFS white space
945 * 1 when copying the text of a field
946 * 2 when searching for possible non-whitespace IFS
947 * 3 when searching for non-newline after copying field
952 if ((buflen
= TEMP_FAILURE_RETRY (__read (fildes
[0], buffer
,
955 if (TEMP_FAILURE_RETRY (__waitpid (pid
, &status
, WNOHANG
)) == 0)
957 if ((buflen
= TEMP_FAILURE_RETRY (__read (fildes
[0], buffer
,
962 for (i
= 0; i
< buflen
; ++i
)
964 if (strchr (ifs
, buffer
[i
]) != NULL
)
966 /* Current character is IFS */
967 if (strchr (ifs_white
, buffer
[i
]) == NULL
)
969 /* Current character is IFS but not whitespace */
975 * eg: text<space><comma><space>moretext
977 * So, strip whitespace IFS (like at the start)
984 /* fall through and delimit field.. */
988 if (buffer
[i
] == '\n')
990 /* Current character is (IFS) newline */
992 /* If copying a field, this is the end of it,
993 but maybe all that's left is trailing newlines.
994 So start searching for a non-newline. */
1002 /* Current character is IFS white space, but
1005 /* If not either copying a field or searching
1006 for non-newline after a field, ignore it */
1007 if (copying
!= 1 && copying
!= 3)
1010 /* End of field (search for non-ws IFS afterwards) */
1015 /* First IFS white space (non-newline), or IFS non-whitespace.
1016 * Delimit the field. Nulls are converted by w_addword. */
1017 if (w_addword (pwordexp
, *word
) == WRDE_NOSPACE
)
1020 *word
= w_newword (word_length
, max_length
);
1023 /* fall back round the loop.. */
1027 /* Not IFS character */
1031 /* Nothing but (IFS) newlines since the last field,
1032 so delimit it here before starting new word */
1033 if (w_addword (pwordexp
, *word
) == WRDE_NOSPACE
)
1036 *word
= w_newword (word_length
, max_length
);
1041 if (buffer
[i
] == '\n') /* happens if newline not in IFS */
1046 *word
= w_addchar (*word
, word_length
, max_length
,
1055 /* Chop off trailing newlines (required by POSIX.2) */
1056 /* Ensure we don't go back further than the beginning of the
1057 substitution (i.e. remove maxnewlines bytes at most) */
1058 while (maxnewlines
-- != 0 &&
1059 *word_length
> 0 && (*word
)[*word_length
- 1] == '\n')
1061 (*word
)[--*word_length
] = '\0';
1063 /* If the last word was entirely newlines, turn it into a new word
1064 * which can be ignored if there's nothing following it. */
1065 if (*word_length
== 0)
1068 *word
= w_newword (word_length
, max_length
);
1073 __close (fildes
[0]);
1076 /* Check for syntax error (re-execute but with "-n" flag) */
1077 if (buflen
< 1 && status
!= 0)
1086 __kill (pid
, SIGKILL
);
1087 TEMP_FAILURE_RETRY (__waitpid (pid
, NULL
, 0));
1088 __close (fildes
[0]);
1089 return WRDE_NOSPACE
;
1094 parse_comm (char **word
, size_t *word_length
, size_t *max_length
,
1095 const char *words
, size_t *offset
, int flags
, wordexp_t
*pwordexp
,
1096 const char *ifs
, const char *ifs_white
)
1098 /* We are poised just after "$(" */
1099 int paren_depth
= 1;
1101 int quoted
= 0; /* 1 for singly-quoted, 2 for doubly-quoted */
1104 char *comm
= w_newword (&comm_length
, &comm_maxlen
);
1106 for (; words
[*offset
]; ++(*offset
))
1108 switch (words
[*offset
])
1113 else if (quoted
== 1)
1121 else if (quoted
== 2)
1127 if (!quoted
&& --paren_depth
== 0)
1129 /* Go -- give script to the shell */
1132 #ifdef __libc_ptf_call
1133 /* We do not want the exec_comm call to be cut short
1134 by a thread cancellation since cleanup is very
1135 ugly. Therefore disable cancellation for
1137 // XXX Ideally we do want the thread being cancelable.
1138 // XXX If demand is there we'll change it.
1139 int state
= PTHREAD_CANCEL_ENABLE
;
1140 __libc_ptf_call (pthread_setcancelstate
,
1141 (PTHREAD_CANCEL_DISABLE
, &state
), 0);
1144 error
= exec_comm (comm
, word
, word_length
, max_length
,
1145 flags
, pwordexp
, ifs
, ifs_white
);
1147 #ifdef __libc_ptf_call
1148 __libc_ptf_call (pthread_setcancelstate
, (state
, NULL
), 0);
1157 /* This is just part of the script */
1165 comm
= w_addchar (comm
, &comm_length
, &comm_maxlen
, words
[*offset
]);
1167 return WRDE_NOSPACE
;
1170 /* Premature end. */
1178 parse_param (char **word
, size_t *word_length
, size_t *max_length
,
1179 const char *words
, size_t *offset
, int flags
, wordexp_t
*pwordexp
,
1180 const char *ifs
, const char *ifs_white
, int quoted
)
1182 /* We are poised just after "$" */
1186 ACT_RP_SHORT_LEFT
= '#',
1187 ACT_RP_LONG_LEFT
= 'L',
1188 ACT_RP_SHORT_RIGHT
= '%',
1189 ACT_RP_LONG_RIGHT
= 'R',
1190 ACT_NULL_ERROR
= '?',
1191 ACT_NULL_SUBST
= '-',
1192 ACT_NONNULL_SUBST
= '+',
1193 ACT_NULL_ASSIGN
= '='
1199 size_t start
= *offset
;
1203 enum action action
= ACT_NONE
;
1208 int pattern_is_quoted
= 0; /* 1 for singly-quoted, 2 for doubly-quoted */
1212 int brace
= words
[*offset
] == '{';
1214 env
= w_newword (&env_length
, &env_maxlen
);
1215 pattern
= w_newword (&pat_length
, &pat_maxlen
);
1220 /* First collect the parameter name. */
1222 if (words
[*offset
] == '#')
1230 if (isalpha (words
[*offset
]) || words
[*offset
] == '_')
1232 /* Normal parameter name. */
1235 env
= w_addchar (env
, &env_length
, &env_maxlen
,
1240 while (isalnum (words
[++*offset
]) || words
[*offset
] == '_');
1242 else if (isdigit (words
[*offset
]))
1244 /* Numeric parameter name. */
1248 env
= w_addchar (env
, &env_length
, &env_maxlen
,
1255 while (isdigit(words
[++*offset
]));
1257 else if (strchr ("*@$", words
[*offset
]) != NULL
)
1259 /* Special parameter. */
1261 env
= w_addchar (env
, &env_length
, &env_maxlen
,
1275 /* Check for special action to be applied to the value. */
1276 switch (words
[*offset
])
1283 action
= ACT_RP_SHORT_LEFT
;
1284 if (words
[1 + *offset
] == '#')
1287 action
= ACT_RP_LONG_LEFT
;
1292 action
= ACT_RP_SHORT_RIGHT
;
1293 if (words
[1 + *offset
] == '%')
1296 action
= ACT_RP_LONG_RIGHT
;
1301 if (strchr ("-=?+", words
[1 + *offset
]) == NULL
)
1305 action
= words
[++*offset
];
1312 action
= words
[*offset
];
1319 /* Now collect the pattern, but don't expand it yet. */
1321 for (; words
[*offset
]; ++(*offset
))
1323 switch (words
[*offset
])
1326 if (!pattern_is_quoted
)
1331 if (!pattern_is_quoted
)
1340 if (pattern_is_quoted
)
1341 /* Quoted; treat as normal character. */
1344 /* Otherwise, it's an escape: next character is literal. */
1345 if (words
[++*offset
] == '\0')
1348 pattern
= w_addchar (pattern
, &pat_length
, &pat_maxlen
, '\\');
1349 if (pattern
== NULL
)
1355 if (pattern_is_quoted
== 0)
1356 pattern_is_quoted
= 1;
1357 else if (pattern_is_quoted
== 1)
1358 pattern_is_quoted
= 0;
1363 if (pattern_is_quoted
== 0)
1364 pattern_is_quoted
= 2;
1365 else if (pattern_is_quoted
== 2)
1366 pattern_is_quoted
= 0;
1371 pattern
= w_addchar (pattern
, &pat_length
, &pat_maxlen
,
1373 if (pattern
== NULL
)
1378 /* End of input string -- remember to reparse the character that we
1383 if (words
[start
] == '{' && words
[*offset
] != '}')
1390 /* $# expands to the number of positional parameters */
1392 value
= _itoa_word (__libc_argc
- 1, &buffer
[20], 10, 0);
1397 /* Just $ on its own */
1398 *offset
= start
- 1;
1399 *word
= w_addchar (*word
, word_length
, max_length
, '$');
1400 return *word
? 0 : WRDE_NOSPACE
;
1403 /* Is it a numeric parameter? */
1404 else if (isdigit (env
[0]))
1408 if (n
>= __libc_argc
)
1409 /* Substitute NULL. */
1412 /* Replace with appropriate positional parameter. */
1413 value
= __libc_argv
[n
];
1415 /* Is it a special parameter? */
1422 value
= _itoa_word (__getpid (), &buffer
[20], 10, 0);
1424 /* Is it `${#*}' or `${#@}'? */
1425 else if ((*env
== '*' || *env
== '@') && seen_hash
)
1428 value
= _itoa_word (__libc_argc
> 0 ? __libc_argc
- 1 : 0,
1429 &buffer
[20], 10, 0);
1430 *word
= w_addstr (*word
, word_length
, max_length
, value
);
1433 return *word
? 0 : WRDE_NOSPACE
;
1435 /* Is it `$*' or `$@' (unquoted) ? */
1436 else if (*env
== '*' || (*env
== '@' && !quoted
))
1438 size_t plist_len
= 0;
1442 /* Build up value parameter by parameter (copy them) */
1443 for (p
= 1; __libc_argv
[p
]; ++p
)
1444 plist_len
+= strlen (__libc_argv
[p
]) + 1; /* for space */
1445 value
= malloc (plist_len
);
1450 for (p
= 1; __libc_argv
[p
]; ++p
)
1454 end
= __stpcpy (end
, __libc_argv
[p
]);
1461 /* Must be a quoted `$@' */
1462 assert (*env
== '@' && quoted
);
1464 /* Each parameter is a separate word ("$@") */
1465 if (__libc_argc
== 2)
1466 value
= __libc_argv
[1];
1467 else if (__libc_argc
> 2)
1471 /* Append first parameter to current word. */
1472 value
= w_addstr (*word
, word_length
, max_length
,
1474 if (value
== NULL
|| w_addword (pwordexp
, value
))
1477 for (p
= 2; __libc_argv
[p
+ 1]; p
++)
1479 char *newword
= __strdup (__libc_argv
[p
]);
1480 if (newword
== NULL
|| w_addword (pwordexp
, newword
))
1484 /* Start a new word with the last parameter. */
1485 *word
= w_newword (word_length
, max_length
);
1486 value
= __libc_argv
[p
];
1497 value
= getenv (env
);
1499 if (value
== NULL
&& (flags
& WRDE_UNDEF
))
1501 /* Variable not defined. */
1502 error
= WRDE_BADVAL
;
1506 if (action
!= ACT_NONE
)
1508 int expand_pattern
= 0;
1510 /* First, find out if we need to expand pattern (i.e. if we will
1514 case ACT_RP_SHORT_LEFT
:
1515 case ACT_RP_LONG_LEFT
:
1516 case ACT_RP_SHORT_RIGHT
:
1517 case ACT_RP_LONG_RIGHT
:
1518 /* Always expand for these. */
1522 case ACT_NULL_ERROR
:
1523 case ACT_NULL_SUBST
:
1524 case ACT_NULL_ASSIGN
:
1525 if (!value
|| (!*value
&& colon_seen
))
1526 /* If param is unset, or set but null and a colon has been seen,
1527 the expansion of the pattern will be needed. */
1532 case ACT_NONNULL_SUBST
:
1533 /* Expansion of word will be needed if parameter is set and not null,
1534 or set null but no colon has been seen. */
1535 if (value
&& (*value
|| !colon_seen
))
1541 assert (! "Unrecognised action!");
1546 /* We need to perform tilde expansion, parameter expansion,
1547 command substitution, and arithmetic expansion. We also
1548 have to be a bit careful with wildcard characters, as
1549 pattern might be given to fnmatch soon. To do this, we
1550 convert quotes to escapes. */
1556 int quoted
= 0; /* 1: single quotes; 2: double */
1558 expanded
= w_newword (&exp_len
, &exp_maxl
);
1559 for (p
= pattern
; p
&& *p
; p
++)
1568 else if (quoted
== 0)
1577 else if (quoted
== 0)
1587 /* Convert quoted wildchar to escaped wildchar. */
1588 expanded
= w_addchar (expanded
, &exp_len
,
1591 if (expanded
== NULL
)
1598 error
= parse_dollars (&expanded
, &exp_len
, &exp_maxl
, p
,
1599 &offset
, flags
, NULL
, NULL
, NULL
, 1);
1614 if (quoted
|| exp_len
)
1618 error
= parse_tilde (&expanded
, &exp_len
, &exp_maxl
, p
,
1634 expanded
= w_addchar (expanded
, &exp_len
, &exp_maxl
, '\\');
1636 assert (*p
); /* checked when extracted initially */
1637 if (expanded
== NULL
)
1641 expanded
= w_addchar (expanded
, &exp_len
, &exp_maxl
, *p
);
1643 if (expanded
== NULL
)
1654 case ACT_RP_SHORT_LEFT
:
1655 case ACT_RP_LONG_LEFT
:
1656 case ACT_RP_SHORT_RIGHT
:
1657 case ACT_RP_LONG_RIGHT
:
1663 if (value
== NULL
|| pattern
== NULL
|| *pattern
== '\0')
1666 end
= value
+ strlen (value
);
1670 case ACT_RP_SHORT_LEFT
:
1671 for (p
= value
; p
<= end
; ++p
)
1675 if (fnmatch (pattern
, value
, 0) != FNM_NOMATCH
)
1680 char *newval
= __strdup (p
);
1698 case ACT_RP_LONG_LEFT
:
1699 for (p
= end
; p
>= value
; --p
)
1703 if (fnmatch (pattern
, value
, 0) != FNM_NOMATCH
)
1708 char *newval
= __strdup (p
);
1726 case ACT_RP_SHORT_RIGHT
:
1727 for (p
= end
; p
>= value
; --p
)
1729 if (fnmatch (pattern
, p
, 0) != FNM_NOMATCH
)
1732 newval
= malloc (p
- value
+ 1);
1741 *(char *) __mempcpy (newval
, value
, p
- value
) = '\0';
1752 case ACT_RP_LONG_RIGHT
:
1753 for (p
= value
; p
<= end
; ++p
)
1755 if (fnmatch (pattern
, p
, 0) != FNM_NOMATCH
)
1758 newval
= malloc (p
- value
+ 1);
1767 *(char *) __mempcpy (newval
, value
, p
- value
) = '\0';
1785 case ACT_NULL_ERROR
:
1786 if (value
&& *value
)
1787 /* Substitute parameter */
1791 if (!colon_seen
&& value
)
1792 /* Substitute NULL */
1796 const char *str
= pattern
;
1799 str
= _("parameter null or not set");
1801 __fxprintf (NULL
, "%s: %s\n", env
, str
);
1808 case ACT_NULL_SUBST
:
1809 if (value
&& *value
)
1810 /* Substitute parameter */
1813 if (free_value
&& value
)
1816 if (!colon_seen
&& value
)
1817 /* Substitute NULL */
1820 value
= pattern
? __strdup (pattern
) : pattern
;
1823 if (pattern
&& !value
)
1828 case ACT_NONNULL_SUBST
:
1829 if (value
&& (*value
|| !colon_seen
))
1831 if (free_value
&& value
)
1834 value
= pattern
? __strdup (pattern
) : pattern
;
1837 if (pattern
&& !value
)
1843 /* Substitute NULL */
1848 case ACT_NULL_ASSIGN
:
1849 if (value
&& *value
)
1850 /* Substitute parameter */
1853 if (!colon_seen
&& value
)
1855 /* Substitute NULL */
1864 value
= pattern
? __strdup (pattern
) : pattern
;
1867 if (pattern
&& !value
)
1870 __setenv (env
, value
, 1);
1874 assert (! "Unrecognised action!");
1885 char param_length
[21];
1886 param_length
[20] = '\0';
1887 *word
= w_addstr (*word
, word_length
, max_length
,
1888 _itoa_word (value
? strlen (value
) : 0,
1889 ¶m_length
[20], 10, 0));
1892 assert (value
!= NULL
);
1896 return *word
? 0 : WRDE_NOSPACE
;
1902 if (quoted
|| !pwordexp
)
1904 /* Quoted - no field split */
1905 *word
= w_addstr (*word
, word_length
, max_length
, value
);
1909 return *word
? 0 : WRDE_NOSPACE
;
1913 /* Need to field-split */
1914 char *value_copy
= __strdup (value
); /* Don't modify value */
1915 char *field_begin
= value_copy
;
1916 int seen_nonws_ifs
= 0;
1921 if (value_copy
== NULL
)
1926 char *field_end
= field_begin
;
1929 /* If this isn't the first field, start a new word */
1930 if (field_begin
!= value_copy
)
1932 if (w_addword (pwordexp
, *word
) == WRDE_NOSPACE
)
1938 *word
= w_newword (word_length
, max_length
);
1941 /* Skip IFS whitespace before the field */
1942 field_begin
+= strspn (field_begin
, ifs_white
);
1944 if (!seen_nonws_ifs
&& *field_begin
== 0)
1945 /* Nothing but whitespace */
1948 /* Search for the end of the field */
1949 field_end
= field_begin
+ strcspn (field_begin
, ifs
);
1951 /* Set up pointer to the character after end of field and
1952 skip whitespace IFS after it. */
1953 next_field
= field_end
+ strspn (field_end
, ifs_white
);
1955 /* Skip at most one non-whitespace IFS character after the field */
1957 if (*next_field
&& strchr (ifs
, *next_field
))
1963 /* Null-terminate it */
1966 /* Tag a copy onto the current word */
1967 *word
= w_addstr (*word
, word_length
, max_length
, field_begin
);
1969 if (*word
== NULL
&& *field_begin
!= '\0')
1975 field_begin
= next_field
;
1977 while (seen_nonws_ifs
|| *field_begin
);
1989 error
= WRDE_NOSPACE
;
1993 error
= WRDE_SYNTAX
;
2005 parse_dollars (char **word
, size_t *word_length
, size_t *max_length
,
2006 const char *words
, size_t *offset
, int flags
,
2007 wordexp_t
*pwordexp
, const char *ifs
, const char *ifs_white
,
2010 /* We are poised _at_ "$" */
2011 switch (words
[1 + *offset
])
2016 *word
= w_addchar (*word
, word_length
, max_length
, '$');
2017 return *word
? 0 : WRDE_NOSPACE
;
2020 if (words
[2 + *offset
] == '(')
2022 /* Differentiate between $((1+3)) and $((echo);(ls)) */
2023 int i
= 3 + *offset
;
2025 while (words
[i
] && !(depth
== 0 && words
[i
] == ')'))
2027 if (words
[i
] == '(')
2029 else if (words
[i
] == ')')
2035 if (words
[i
] == ')' && words
[i
+ 1] == ')')
2038 /* Call parse_arith -- 0 is for "no brackets" */
2039 return parse_arith (word
, word_length
, max_length
, words
, offset
,
2044 if (flags
& WRDE_NOCMD
)
2048 return parse_comm (word
, word_length
, max_length
, words
, offset
, flags
,
2049 quoted
? NULL
: pwordexp
, ifs
, ifs_white
);
2053 /* Call parse_arith -- 1 is for "brackets" */
2054 return parse_arith (word
, word_length
, max_length
, words
, offset
, flags
,
2059 ++(*offset
); /* parse_param needs to know if "{" is there */
2060 return parse_param (word
, word_length
, max_length
, words
, offset
, flags
,
2061 pwordexp
, ifs
, ifs_white
, quoted
);
2067 parse_backtick (char **word
, size_t *word_length
, size_t *max_length
,
2068 const char *words
, size_t *offset
, int flags
,
2069 wordexp_t
*pwordexp
, const char *ifs
, const char *ifs_white
)
2071 /* We are poised just after "`" */
2076 char *comm
= w_newword (&comm_length
, &comm_maxlen
);
2078 for (; words
[*offset
]; ++(*offset
))
2080 switch (words
[*offset
])
2083 /* Go -- give the script to the shell */
2084 error
= exec_comm (comm
, word
, word_length
, max_length
, flags
,
2085 pwordexp
, ifs
, ifs_white
);
2092 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
;
2132 parse_dquote (char **word
, size_t *word_length
, size_t *max_length
,
2133 const char *words
, size_t *offset
, int flags
,
2134 wordexp_t
*pwordexp
, const char * ifs
, const char * ifs_white
)
2136 /* We are poised just after a double-quote */
2139 for (; words
[*offset
]; ++(*offset
))
2141 switch (words
[*offset
])
2147 error
= parse_dollars (word
, word_length
, max_length
, words
, offset
,
2148 flags
, pwordexp
, ifs
, ifs_white
, 1);
2149 /* The ``1'' here is to tell parse_dollars not to
2150 * split the fields. It may need to, however ("$@").
2158 if (flags
& WRDE_NOCMD
)
2162 error
= parse_backtick (word
, word_length
, max_length
, words
,
2163 offset
, flags
, NULL
, NULL
, NULL
);
2164 /* The first NULL here is to tell parse_backtick not to
2173 error
= parse_qtd_backslash (word
, word_length
, max_length
, words
,
2182 *word
= w_addchar (*word
, word_length
, max_length
, words
[*offset
]);
2184 return WRDE_NOSPACE
;
2188 /* Unterminated string */
2193 * wordfree() is to be called after pwordexp is finished with.
2197 wordfree (wordexp_t
*pwordexp
)
2200 /* wordexp can set pwordexp to NULL */
2201 if (pwordexp
&& pwordexp
->we_wordv
)
2203 char **wordv
= pwordexp
->we_wordv
;
2205 for (wordv
+= pwordexp
->we_offs
; *wordv
; ++wordv
)
2208 free (pwordexp
->we_wordv
);
2209 pwordexp
->we_wordv
= NULL
;
2212 libc_hidden_def (wordfree
)
2219 wordexp (const char *words
, wordexp_t
*pwordexp
, int flags
)
2221 size_t words_offset
;
2224 char *word
= w_newword (&word_length
, &max_length
);
2228 wordexp_t old_word
= *pwordexp
;
2230 if (flags
& WRDE_REUSE
)
2232 /* Minimal implementation of WRDE_REUSE for now */
2233 wordfree (pwordexp
);
2234 old_word
.we_wordv
= NULL
;
2237 if ((flags
& WRDE_APPEND
) == 0)
2239 pwordexp
->we_wordc
= 0;
2241 if (flags
& WRDE_DOOFFS
)
2243 pwordexp
->we_wordv
= calloc (1 + pwordexp
->we_offs
, sizeof (char *));
2244 if (pwordexp
->we_wordv
== NULL
)
2246 error
= WRDE_NOSPACE
;
2252 pwordexp
->we_wordv
= calloc (1, sizeof (char *));
2253 if (pwordexp
->we_wordv
== NULL
)
2255 error
= WRDE_NOSPACE
;
2259 pwordexp
->we_offs
= 0;
2263 /* Find out what the field separators are.
2264 * There are two types: whitespace and non-whitespace.
2266 ifs
= getenv ("IFS");
2269 /* IFS unset - use <space><tab><newline>. */
2270 ifs
= strcpy (ifs_white
, " \t\n");
2274 char *whch
= ifs_white
;
2276 /* Start off with no whitespace IFS characters */
2277 ifs_white
[0] = '\0';
2279 while (*ifsch
!= '\0')
2281 if ((*ifsch
== ' ') || (*ifsch
== '\t') || (*ifsch
== '\n'))
2283 /* Whitespace IFS. See first whether it is already in our
2285 char *runp
= ifs_white
;
2287 while (runp
< whch
&& *runp
!= '\0' && *runp
!= *ifsch
)
2299 for (words_offset
= 0 ; words
[words_offset
] ; ++words_offset
)
2300 switch (words
[words_offset
])
2303 error
= parse_backslash (&word
, &word_length
, &max_length
, words
,
2312 error
= parse_dollars (&word
, &word_length
, &max_length
, words
,
2313 &words_offset
, flags
, pwordexp
, ifs
, ifs_white
,
2322 if (flags
& WRDE_NOCMD
)
2324 error
= WRDE_CMDSUB
;
2329 error
= parse_backtick (&word
, &word_length
, &max_length
, words
,
2330 &words_offset
, flags
, pwordexp
, ifs
,
2340 error
= parse_dquote (&word
, &word_length
, &max_length
, words
,
2341 &words_offset
, flags
, pwordexp
, ifs
, ifs_white
);
2348 error
= w_addword (pwordexp
, NULL
);
2358 error
= parse_squote (&word
, &word_length
, &max_length
, words
,
2366 error
= w_addword (pwordexp
, NULL
);
2375 error
= parse_tilde (&word
, &word_length
, &max_length
, words
,
2376 &words_offset
, pwordexp
->we_wordc
);
2386 error
= parse_glob (&word
, &word_length
, &max_length
, words
,
2387 &words_offset
, flags
, pwordexp
, ifs
, ifs_white
);
2395 /* Is it a word separator? */
2396 if (strchr (" \t", words
[words_offset
]) == NULL
)
2398 char ch
= words
[words_offset
];
2400 /* Not a word separator -- but is it a valid word char? */
2401 if (strchr ("\n|&;<>(){}", ch
))
2404 error
= WRDE_BADCHAR
;
2408 /* "Ordinary" character -- add it to word */
2409 word
= w_addchar (word
, &word_length
, &max_length
,
2413 error
= WRDE_NOSPACE
;
2420 /* If a word has been delimited, add it to the list. */
2423 error
= w_addword (pwordexp
, word
);
2428 word
= w_newword (&word_length
, &max_length
);
2433 /* There was a word separator at the end */
2434 if (word
== NULL
) /* i.e. w_newword */
2437 /* There was no field separator at the end */
2438 return w_addword (pwordexp
, word
);
2442 * free memory used (unless error is WRDE_NOSPACE), and
2443 * set pwordexp members back to what they were.
2448 if (error
== WRDE_NOSPACE
)
2449 return WRDE_NOSPACE
;
2451 if ((flags
& WRDE_APPEND
) == 0)
2452 wordfree (pwordexp
);
2454 *pwordexp
= old_word
;