Update.
[glibc.git] / posix / wordexp.c
blob302cf0884f161db8bcf12193cbafa43d816e0223
1 /* POSIX.2 wordexp implementation.
2 Copyright (C) 1997, 1998, 1999 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 Library General Public License as
8 published by the Free Software Foundation; either version 2 of the
9 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 Library General Public License for more details.
16 You should have received a copy of the GNU Library General Public
17 License along with the GNU C Library; see the file COPYING.LIB. If not,
18 write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
19 Boston, MA 02111-1307, USA. */
21 #include <wordexp.h>
22 #include <signal.h>
23 #include <stdlib.h>
24 #include <pwd.h>
25 #include <sys/types.h>
26 #include <string.h>
27 #include <glob.h>
28 #include <ctype.h>
29 #include <sys/time.h>
30 #include <sys/types.h>
31 #include <sys/wait.h>
32 #include <unistd.h>
33 #include <fcntl.h>
34 #include <sys/stat.h>
35 #include <paths.h>
36 #include <errno.h>
37 #include <sys/param.h>
38 #include <stdio.h>
39 #include <fnmatch.h>
41 #include <stdio-common/_itoa.h>
43 /* Undefine the following line for the production version. */
44 /* #define NDEBUG 1 */
45 #include <assert.h>
48 * This is a recursive-descent-style word expansion routine.
51 /* These variables are defined and initialized in the startup code. */
52 extern int __libc_argc;
53 extern char **__libc_argv;
55 /* Some forward declarations */
56 static int parse_dollars (char **word, size_t *word_length, size_t *max_length,
57 const char *words, size_t *offset, int flags,
58 wordexp_t *pwordexp, const char *ifs,
59 const char *ifs_white, int quoted)
60 internal_function;
61 static int parse_backtick (char **word, size_t *word_length,
62 size_t *max_length, const char *words,
63 size_t *offset, int flags, wordexp_t *pwordexp,
64 const char *ifs, const char *ifs_white)
65 internal_function;
66 static int parse_dquote (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)
70 internal_function;
71 static int eval_expr (char *expr, long int *result) internal_function;
73 /* The w_*() functions manipulate word lists. */
75 #define W_CHUNK (100)
77 /* Result of w_newword will be ignored if it's the last word. */
78 static inline char *
79 w_newword (size_t *actlen, size_t *maxlen)
81 *actlen = *maxlen = 0;
82 return NULL;
85 static inline char *
86 w_addchar (char *buffer, size_t *actlen, size_t *maxlen, char ch)
87 /* (lengths exclude trailing zero) */
89 /* Add a character to the buffer, allocating room for it if needed.
92 if (*actlen == *maxlen)
94 char *old_buffer = buffer;
95 assert (buffer == NULL || *maxlen != 0);
96 *maxlen += W_CHUNK;
97 buffer = realloc (buffer, 1 + *maxlen);
99 if (buffer == NULL)
100 free (old_buffer);
103 if (buffer != NULL)
105 buffer[*actlen] = ch;
106 buffer[++(*actlen)] = '\0';
109 return buffer;
112 static char *
113 internal_function
114 w_addmem (char *buffer, size_t *actlen, size_t *maxlen, const char *str,
115 size_t len)
117 /* Add a string to the buffer, allocating room for it if needed.
119 if (*actlen + len > *maxlen)
121 char *old_buffer = buffer;
122 assert (buffer == NULL || *maxlen != 0);
123 *maxlen += MAX (2 * len, W_CHUNK);
124 buffer = realloc (old_buffer, 1 + *maxlen);
126 if (buffer == NULL)
127 free (old_buffer);
130 if (buffer != NULL)
132 *((char *) __mempcpy (&buffer[*actlen], str, len)) = '\0';
133 *actlen += len;
136 return buffer;
139 static char *
140 internal_function
141 w_addstr (char *buffer, size_t *actlen, size_t *maxlen, const char *str)
142 /* (lengths exclude trailing zero) */
144 /* Add a string to the buffer, allocating room for it if needed.
146 size_t len;
148 assert (str != NULL); /* w_addstr only called from this file */
149 len = strlen (str);
151 return w_addmem (buffer, actlen, maxlen, str, len);
154 static int
155 internal_function
156 w_addword (wordexp_t *pwordexp, char *word)
158 /* Add a word to the wordlist */
159 size_t num_p;
160 char **new_wordv;
162 /* Internally, NULL acts like "". Convert NULLs to "" before
163 * the caller sees them.
165 if (word == NULL)
167 word = __strdup ("");
168 if (word == NULL)
169 goto no_space;
172 num_p = 2 + pwordexp->we_wordc + pwordexp->we_offs;
173 new_wordv = realloc (pwordexp->we_wordv, sizeof (char *) * num_p);
174 if (new_wordv != NULL)
176 pwordexp->we_wordv = new_wordv;
177 pwordexp->we_wordv[pwordexp->we_wordc++] = word;
178 pwordexp->we_wordv[pwordexp->we_wordc] = NULL;
179 return 0;
182 no_space:
183 return WRDE_NOSPACE;
186 /* The parse_*() functions should leave *offset being the offset in 'words'
187 * to the last character processed.
190 static int
191 internal_function
192 parse_backslash (char **word, size_t *word_length, size_t *max_length,
193 const char *words, size_t *offset)
195 /* We are poised _at_ a backslash, not in quotes */
197 switch (words[1 + *offset])
199 case 0:
200 /* Backslash is last character of input words */
201 return WRDE_SYNTAX;
203 case '\n':
204 ++(*offset);
205 break;
207 default:
208 *word = w_addchar (*word, word_length, max_length, words[1 + *offset]);
209 if (*word == NULL)
210 return WRDE_NOSPACE;
212 ++(*offset);
213 break;
216 return 0;
219 static int
220 internal_function
221 parse_qtd_backslash (char **word, size_t *word_length, size_t *max_length,
222 const char *words, size_t *offset)
224 /* We are poised _at_ a backslash, inside quotes */
226 switch (words[1 + *offset])
228 case 0:
229 /* Backslash is last character of input words */
230 return WRDE_SYNTAX;
232 case '\n':
233 ++(*offset);
234 break;
236 case '$':
237 case '`':
238 case '"':
239 case '\\':
240 *word = w_addchar (*word, word_length, max_length, words[1 + *offset]);
241 if (*word == NULL)
242 return WRDE_NOSPACE;
244 ++(*offset);
245 break;
247 default:
248 *word = w_addchar (*word, word_length, max_length, words[*offset]);
249 if (*word != NULL)
250 *word = w_addchar (*word, word_length, max_length, words[1 + *offset]);
252 if (*word == NULL)
253 return WRDE_NOSPACE;
255 ++(*offset);
256 break;
259 return 0;
262 static int
263 internal_function
264 parse_tilde (char **word, size_t *word_length, size_t *max_length,
265 const char *words, size_t *offset, size_t wordc)
267 /* We are poised _at_ a tilde */
268 size_t i;
270 if (*word_length != 0)
272 if (!((*word)[*word_length - 1] == '=' && wordc == 0))
274 if (!((*word)[*word_length - 1] == ':'
275 && strchr (*word, '=') && wordc == 0))
277 *word = w_addchar (*word, word_length, max_length, '~');
278 return *word ? 0 : WRDE_NOSPACE;
283 for (i = 1 + *offset; words[i]; i++)
285 if (words[i] == ':' || words[i] == '/' || words[i] == ' ' ||
286 words[i] == '\t' || words[i] == 0 )
287 break;
289 if (words[i] == '\\')
291 *word = w_addchar (*word, word_length, max_length, '~');
292 return *word ? 0 : WRDE_NOSPACE;
296 if (i == 1 + *offset)
298 /* Tilde appears on its own */
299 uid_t uid;
300 struct passwd pwd, *tpwd;
301 int buflen = 1000;
302 char* buffer = __alloca (buflen);
303 int result;
305 uid = __getuid ();
307 while ((result = __getpwuid_r (uid, &pwd, buffer, buflen, &tpwd)) != 0
308 && errno == ERANGE)
310 buflen += 1000;
311 buffer = __alloca (buflen);
314 if (result == 0 && tpwd != NULL && pwd.pw_dir != NULL)
316 *word = w_addstr (*word, word_length, max_length, pwd.pw_dir);
317 if (*word == NULL)
318 return WRDE_NOSPACE;
320 else
322 *word = w_addchar (*word, word_length, max_length, '~');
323 if (*word == NULL)
324 return WRDE_NOSPACE;
327 else
329 /* Look up user name in database to get home directory */
330 char *user = __strndup (&words[1 + *offset], i - *offset);
331 struct passwd pwd, *tpwd;
332 int buflen = 1000;
333 char* buffer = __alloca (buflen);
334 int result;
336 while ((result = __getpwnam_r (user, &pwd, buffer, buflen, &tpwd)) != 0
337 && errno == ERANGE)
339 buflen += 1000;
340 buffer = __alloca (buflen);
343 if (result == 0 && tpwd != NULL && pwd.pw_dir)
344 *word = w_addstr (*word, word_length, max_length, pwd.pw_dir);
345 else
347 /* (invalid login name) */
348 *word = w_addchar (*word, word_length, max_length, '~');
349 if (*word != NULL)
350 *word = w_addstr (*word, word_length, max_length, user);
353 *offset = i - 1;
355 return *word ? 0 : WRDE_NOSPACE;
359 static int
360 internal_function
361 do_parse_glob (const char *glob_word, char **word, size_t *word_length,
362 size_t *max_length, wordexp_t *pwordexp, const char *ifs,
363 const char *ifs_white)
365 int error;
366 int match;
367 glob_t globbuf;
369 error = glob (glob_word, GLOB_NOCHECK, NULL, &globbuf);
371 if (error != 0)
373 /* We can only run into memory problems. */
374 assert (error == GLOB_NOSPACE);
375 return WRDE_NOSPACE;
378 if (ifs && !*ifs)
380 /* No field splitting allowed. */
381 assert (globbuf.gl_pathv[0] != NULL);
382 *word = w_addstr (*word, word_length, max_length, globbuf.gl_pathv[0]);
383 for (match = 1; match < globbuf.gl_pathc && *word != NULL; ++match)
385 *word = w_addchar (*word, word_length, max_length, ' ');
386 if (*word != NULL)
387 *word = w_addstr (*word, word_length, max_length,
388 globbuf.gl_pathv[match]);
391 globfree (&globbuf);
392 return *word ? 0 : WRDE_NOSPACE;
395 assert (ifs == NULL || *ifs != '\0');
396 if (*word != NULL)
398 free (*word);
399 *word = w_newword (word_length, max_length);
402 for (match = 0; match < globbuf.gl_pathc; ++match)
404 char *matching_word = __strdup (globbuf.gl_pathv[match]);
405 if (matching_word == NULL || w_addword (pwordexp, matching_word))
407 globfree (&globbuf);
408 return WRDE_NOSPACE;
412 globfree (&globbuf);
413 return 0;
416 static int
417 internal_function
418 parse_glob (char **word, size_t *word_length, size_t *max_length,
419 const char *words, size_t *offset, int flags,
420 wordexp_t *pwordexp, const char *ifs, const char *ifs_white)
422 /* We are poised just after a '*', a '[' or a '?'. */
423 int error = WRDE_NOSPACE;
424 int quoted = 0; /* 1 if singly-quoted, 2 if doubly */
425 int i;
426 wordexp_t glob_list; /* List of words to glob */
428 glob_list.we_wordc = 0;
429 glob_list.we_wordv = NULL;
430 glob_list.we_offs = 0;
431 for (; words[*offset] != '\0'; ++*offset)
433 if ((ifs && strchr (ifs, words[*offset])) ||
434 (!ifs && strchr (" \t\n", words[*offset])))
435 /* Reached IFS */
436 break;
438 /* Sort out quoting */
439 if (words[*offset] == '\'')
441 if (quoted == 0)
443 quoted = 1;
444 continue;
446 else if (quoted == 1)
448 quoted = 0;
449 continue;
452 else if (words[*offset] == '"')
454 if (quoted == 0)
456 quoted = 2;
457 continue;
459 else if (quoted == 2)
461 quoted = 0;
462 continue;
466 /* Sort out other special characters */
467 if (quoted != 1 && words[*offset] == '$')
469 error = parse_dollars (word, word_length, max_length, words,
470 offset, flags, &glob_list, ifs, ifs_white,
471 quoted == 2);
472 if (error)
473 goto tidy_up;
475 continue;
477 else if (words[*offset] == '\\')
479 if (quoted)
480 error = parse_qtd_backslash (word, word_length, max_length,
481 words, offset);
482 else
483 error = parse_backslash (word, word_length, max_length,
484 words, offset);
486 if (error)
487 goto tidy_up;
489 continue;
492 *word = w_addchar (*word, word_length, max_length, words[*offset]);
493 if (*word == NULL)
494 goto tidy_up;
497 /* Don't forget to re-parse the character we stopped at. */
498 --*offset;
500 /* Glob the words */
501 error = w_addword (&glob_list, *word);
502 *word = w_newword (word_length, max_length);
503 for (i = 0; error == 0 && i < glob_list.we_wordc; i++)
504 error = do_parse_glob (glob_list.we_wordv[i], word, word_length,
505 max_length, pwordexp, ifs, ifs_white);
507 /* Now tidy up */
508 tidy_up:
509 wordfree (&glob_list);
510 return error;
513 static int
514 internal_function
515 parse_squote (char **word, size_t *word_length, size_t *max_length,
516 const char *words, size_t *offset)
518 /* We are poised just after a single quote */
519 for (; words[*offset]; ++(*offset))
521 if (words[*offset] != '\'')
523 *word = w_addchar (*word, word_length, max_length, words[*offset]);
524 if (*word == NULL)
525 return WRDE_NOSPACE;
527 else return 0;
530 /* Unterminated string */
531 return WRDE_SYNTAX;
534 /* Functions to evaluate an arithmetic expression */
535 static int
536 internal_function
537 eval_expr_val (char **expr, long int *result)
539 int sgn = +1;
540 char *digit;
542 /* Skip white space */
543 for (digit = *expr; digit && *digit && isspace (*digit); ++digit);
545 switch (*digit)
547 case '(':
549 /* Scan for closing paren */
550 for (++digit; **expr && **expr != ')'; ++(*expr));
552 /* Is there one? */
553 if (!**expr)
554 return WRDE_SYNTAX;
556 *(*expr)++ = 0;
558 if (eval_expr (digit, result))
559 return WRDE_SYNTAX;
561 return 0;
563 case '+': /* Positive value */
564 ++digit;
565 break;
567 case '-': /* Negative value */
568 ++digit;
569 sgn = -1;
570 break;
572 default:
573 if (!isdigit (*digit))
574 return WRDE_SYNTAX;
577 *result = 0;
578 for (; *digit && isdigit (*digit); ++digit)
579 *result = (*result * 10) + (*digit - '0');
581 *expr = digit;
582 *result *= sgn;
583 return 0;
586 static int
587 internal_function
588 eval_expr_multdiv (char **expr, long int *result)
590 long int arg;
592 /* Read a Value */
593 if (eval_expr_val (expr, result) != 0)
594 return WRDE_SYNTAX;
596 while (**expr)
598 /* Skip white space */
599 for (; *expr && **expr && isspace (**expr); ++(*expr));
601 if (**expr == '*')
603 ++(*expr);
604 if (eval_expr_val (expr, &arg) != 0)
605 return WRDE_SYNTAX;
607 *result *= arg;
609 else if (**expr == '/')
611 ++(*expr);
612 if (eval_expr_val (expr, &arg) != 0)
613 return WRDE_SYNTAX;
615 *result /= arg;
617 else break;
620 return 0;
623 static int
624 internal_function
625 eval_expr (char *expr, long int *result)
627 long int arg;
629 /* Read a Multdiv */
630 if (eval_expr_multdiv (&expr, result) != 0)
631 return WRDE_SYNTAX;
633 while (*expr)
635 /* Skip white space */
636 for (; expr && *expr && isspace (*expr); ++expr);
638 if (*expr == '+')
640 ++expr;
641 if (eval_expr_multdiv (&expr, &arg) != 0)
642 return WRDE_SYNTAX;
644 *result += arg;
646 else if (*expr == '-')
648 ++expr;
649 if (eval_expr_multdiv (&expr, &arg) != 0)
650 return WRDE_SYNTAX;
652 *result -= arg;
654 else break;
657 return 0;
660 static int
661 internal_function
662 parse_arith (char **word, size_t *word_length, size_t *max_length,
663 const char *words, size_t *offset, int flags, int bracket)
665 /* We are poised just after "$((" or "$[" */
666 int error;
667 int paren_depth = 1;
668 size_t expr_length;
669 size_t expr_maxlen;
670 char *expr;
672 expr = w_newword (&expr_length, &expr_maxlen);
673 for (; words[*offset]; ++(*offset))
675 switch (words[*offset])
677 case '$':
678 error = parse_dollars (&expr, &expr_length, &expr_maxlen,
679 words, offset, flags, NULL, NULL, NULL, 1);
680 /* The ``1'' here is to tell parse_dollars not to
681 * split the fields.
683 if (error)
685 free (expr);
686 return error;
688 break;
690 case '`':
691 (*offset)++;
692 error = parse_backtick (&expr, &expr_length, &expr_maxlen,
693 words, offset, flags, NULL, NULL, NULL);
694 /* The first NULL here is to tell parse_backtick not to
695 * split the fields.
697 if (error)
699 free (expr);
700 return error;
702 break;
704 case '\\':
705 error = parse_qtd_backslash (&expr, &expr_length, &expr_maxlen,
706 words, offset);
707 if (error)
709 free (expr);
710 return error;
712 /* I think that a backslash within an
713 * arithmetic expansion is bound to
714 * cause an error sooner or later anyway though.
716 break;
718 case ')':
719 if (--paren_depth == 0)
721 char result[21]; /* 21 = ceil(log10(2^64)) + 1 */
722 long int numresult = 0;
723 long long int convertme;
725 if (bracket || words[1 + *offset] != ')')
727 free (expr);
728 return WRDE_SYNTAX;
731 ++(*offset);
733 /* Go - evaluate. */
734 if (*expr && eval_expr (expr, &numresult) != 0)
736 free (expr);
737 return WRDE_SYNTAX;
740 if (numresult < 0)
742 convertme = -numresult;
743 *word = w_addchar (*word, word_length, max_length, '-');
744 if (!*word)
746 free (expr);
747 return WRDE_NOSPACE;
750 else
751 convertme = numresult;
753 result[20] = '\0';
754 *word = w_addstr (*word, word_length, max_length,
755 _itoa (convertme, &result[20], 10, 0));
756 free (expr);
757 return *word ? 0 : WRDE_NOSPACE;
759 expr = w_addchar (expr, &expr_length, &expr_maxlen, words[*offset]);
760 if (expr == NULL)
761 return WRDE_NOSPACE;
763 break;
765 case ']':
766 if (bracket && paren_depth == 1)
768 char result[21]; /* 21 = ceil(log10(2^64)) + 1 */
769 long int numresult = 0;
771 /* Go - evaluate. */
772 if (*expr && eval_expr (expr, &numresult) != 0)
774 free (expr);
775 return WRDE_SYNTAX;
778 result[20] = '\0';
779 *word = w_addstr (*word, word_length, max_length,
780 _itoa_word (numresult, &result[20], 10, 0));
781 free (expr);
782 return *word ? 0 : WRDE_NOSPACE;
785 free (expr);
786 return WRDE_SYNTAX;
788 case '\n':
789 case ';':
790 case '{':
791 case '}':
792 free (expr);
793 return WRDE_BADCHAR;
795 case '(':
796 ++paren_depth;
797 default:
798 expr = w_addchar (expr, &expr_length, &expr_maxlen, words[*offset]);
799 if (expr == NULL)
800 return WRDE_NOSPACE;
804 /* Premature end */
805 free (expr);
806 return WRDE_SYNTAX;
809 /* Function to execute a command and retrieve the results */
810 /* pwordexp contains NULL if field-splitting is forbidden */
811 static int
812 internal_function
813 exec_comm (char *comm, char **word, size_t *word_length, size_t *max_length,
814 int flags, wordexp_t *pwordexp, const char *ifs,
815 const char *ifs_white)
817 int fildes[2];
818 int bufsize = 128;
819 int buflen;
820 int i;
821 char *buffer;
822 pid_t pid;
824 /* Don't fork() unless necessary */
825 if (!comm || !*comm)
826 return 0;
828 if (__pipe (fildes))
829 /* Bad */
830 return WRDE_NOSPACE;
832 if ((pid = __fork ()) < 0)
834 /* Bad */
835 __close (fildes[0]);
836 __close (fildes[1]);
837 return WRDE_NOSPACE;
840 if (pid == 0)
842 /* Child */
843 const char *args[4] = { _PATH_BSHELL, "-c", comm, NULL };
845 /* Redirect output. */
846 __dup2 (fildes[1], 1);
847 __close (fildes[1]);
849 /* Redirect stderr to /dev/null if we have to. */
850 if ((flags & WRDE_SHOWERR) == 0)
852 int fd;
853 __close (2);
854 fd = __open (_PATH_DEVNULL, O_WRONLY);
855 if (fd >= 0 && fd != 2)
857 __dup2 (fd, 2);
858 __close (fd);
862 /* Make sure the subshell doesn't field-split on our behalf. */
863 unsetenv ("IFS");
865 __close (fildes[0]);
866 __execve (_PATH_BSHELL, (char *const *) args, __environ);
868 /* Bad. What now? */
869 abort ();
872 /* Parent */
874 __close (fildes[1]);
875 buffer = __alloca (bufsize);
877 if (!pwordexp)
878 { /* Quoted - no field splitting */
880 while (1)
882 if ((buflen = __read (fildes[0], buffer, bufsize)) < 1)
884 if (__waitpid (pid, NULL, WNOHANG) == 0)
885 continue;
886 if ((buflen = __read (fildes[0], buffer, bufsize)) < 1)
887 break;
890 *word = w_addmem (*word, word_length, max_length, buffer, buflen);
891 if (*word == NULL)
892 goto no_space;
895 else
896 /* Not quoted - split fields */
898 int copying = 0;
899 /* 'copying' is:
900 * 0 when searching for first character in a field not IFS white space
901 * 1 when copying the text of a field
902 * 2 when searching for possible non-whitespace IFS
905 while (1)
907 if ((buflen = __read (fildes[0], buffer, bufsize)) < 1)
909 if (__waitpid (pid, NULL, WNOHANG) == 0)
910 continue;
911 if ((__read (fildes[0], buffer, bufsize)) < 1)
912 break;
915 for (i = 0; i < buflen; ++i)
917 if (strchr (ifs, buffer[i]) != NULL)
919 /* Current character is IFS */
920 if (strchr (ifs_white, buffer[i]) == NULL)
922 /* Current character is IFS but not whitespace */
923 if (copying == 2)
925 /* current character
928 * eg: text<space><comma><space>moretext
930 * So, strip whitespace IFS (like at the start)
932 copying = 0;
933 continue;
936 copying = 0;
937 /* fall through and delimit field.. */
939 else
941 /* Current character is IFS white space */
943 /* If not copying a field, ignore it */
944 if (copying != 1)
945 continue;
947 /* End of field (search for non-ws IFS afterwards) */
948 copying = 2;
951 /* First IFS white space, or IFS non-whitespace.
952 * Delimit the field. Nulls are converted by w_addword. */
953 if (w_addword (pwordexp, *word) == WRDE_NOSPACE)
954 goto no_space;
956 *word = w_newword (word_length, max_length);
957 /* fall back round the loop.. */
959 else
961 /* Not IFS character */
962 copying = 1;
964 *word = w_addchar (*word, word_length, max_length,
965 buffer[i]);
966 if (*word == NULL)
967 goto no_space;
973 /* Bash chops off trailing newlines, which seems sensible. */
974 while (*word_length > 0 && (*word)[*word_length - 1] == '\n')
976 (*word)[--*word_length] = '\0';
978 /* If the last word was entirely newlines, turn it into a new word
979 * which can be ignored if there's nothing following it. */
980 if (*word_length == 0)
982 free (*word);
983 *word = w_newword (word_length, max_length);
984 break;
988 __close (fildes[0]);
989 return 0;
991 no_space:
992 __kill (pid, SIGKILL);
993 __waitpid (pid, NULL, 0);
994 __close (fildes[0]);
995 return WRDE_NOSPACE;
998 static int
999 internal_function
1000 parse_comm (char **word, size_t *word_length, size_t *max_length,
1001 const char *words, size_t *offset, int flags, wordexp_t *pwordexp,
1002 const char *ifs, const char *ifs_white)
1004 /* We are poised just after "$(" */
1005 int paren_depth = 1;
1006 int error = 0;
1007 int quoted = 0; /* 1 for singly-quoted, 2 for doubly-quoted */
1008 size_t comm_length;
1009 size_t comm_maxlen;
1010 char *comm = w_newword (&comm_length, &comm_maxlen);
1012 for (; words[*offset]; ++(*offset))
1014 switch (words[*offset])
1016 case '\'':
1017 if (quoted == 0)
1018 quoted = 1;
1019 else if (quoted == 1)
1020 quoted = 0;
1022 break;
1024 case '"':
1025 if (quoted == 0)
1026 quoted = 2;
1027 else if (quoted == 2)
1028 quoted = 0;
1030 break;
1032 case ')':
1033 if (!quoted && --paren_depth == 0)
1035 /* Go -- give script to the shell */
1036 if (comm)
1038 error = exec_comm (comm, word, word_length, max_length,
1039 flags, pwordexp, ifs, ifs_white);
1040 free (comm);
1043 return error;
1046 /* This is just part of the script */
1047 break;
1049 case '(':
1050 if (!quoted)
1051 ++paren_depth;
1054 comm = w_addchar (comm, &comm_length, &comm_maxlen, words[*offset]);
1055 if (comm == NULL)
1056 return WRDE_NOSPACE;
1059 /* Premature end */
1060 if (comm)
1061 free (comm);
1063 return WRDE_SYNTAX;
1066 static int
1067 internal_function
1068 parse_param (char **word, size_t *word_length, size_t *max_length,
1069 const char *words, size_t *offset, int flags, wordexp_t *pwordexp,
1070 const char *ifs, const char *ifs_white, int quoted)
1072 /* We are poised just after "$" */
1073 enum action
1075 ACT_NONE,
1076 ACT_RP_SHORT_LEFT = '#',
1077 ACT_RP_LONG_LEFT = 'L',
1078 ACT_RP_SHORT_RIGHT = '%',
1079 ACT_RP_LONG_RIGHT = 'R',
1080 ACT_NULL_ERROR = '?',
1081 ACT_NULL_SUBST = '-',
1082 ACT_NONNULL_SUBST = '+',
1083 ACT_NULL_ASSIGN = '='
1085 size_t env_length;
1086 size_t env_maxlen;
1087 size_t pat_length;
1088 size_t pat_maxlen;
1089 size_t start = *offset;
1090 char *env;
1091 char *pattern;
1092 char *value = NULL;
1093 enum action action = ACT_NONE;
1094 int depth = 0;
1095 int colon_seen = 0;
1096 int seen_hash = 0;
1097 int free_value = 0;
1098 int pattern_is_quoted = 0; /* 1 for singly-quoted, 2 for doubly-quoted */
1099 int error;
1100 int special = 0;
1101 char buffer[21];
1102 int brace = words[*offset] == '{';
1104 env = w_newword (&env_length, &env_maxlen);
1105 pattern = w_newword (&pat_length, &pat_maxlen);
1107 if (brace)
1108 ++*offset;
1110 /* First collect the parameter name. */
1112 if (words[*offset] == '#')
1114 seen_hash = 1;
1115 if (!brace)
1116 goto envsubst;
1117 ++*offset;
1120 if (isalpha (words[*offset]) || words[*offset] == '_')
1122 /* Normal parameter name. */
1125 env = w_addchar (env, &env_length, &env_maxlen,
1126 words[*offset]);
1127 if (env == NULL)
1128 goto no_space;
1130 while (isalnum (words[++*offset]) || words[*offset] == '_');
1132 else if (isdigit (words[*offset]))
1134 /* Numeric parameter name. */
1135 special = 1;
1138 env = w_addchar (env, &env_length, &env_maxlen,
1139 words[*offset]);
1140 if (env == NULL)
1141 goto no_space;
1142 if (!brace)
1143 goto envsubst;
1145 while (isdigit(words[++*offset]));
1147 else if (strchr ("*@$", words[*offset]) != NULL)
1149 /* Special parameter. */
1150 special = 1;
1151 env = w_addchar (env, &env_length, &env_maxlen,
1152 words[*offset]);
1153 if (env == NULL)
1154 goto no_space;
1155 ++*offset;
1157 else
1159 if (brace)
1160 goto syntax;
1163 if (brace)
1165 /* Check for special action to be applied to the value. */
1166 switch (words[*offset])
1168 case '}':
1169 /* Evaluate. */
1170 goto envsubst;
1172 case '#':
1173 action = ACT_RP_SHORT_LEFT;
1174 if (words[1 + *offset] == '#')
1176 ++*offset;
1177 action = ACT_RP_LONG_LEFT;
1179 break;
1181 case '%':
1182 action = ACT_RP_SHORT_RIGHT;
1183 if (words[1 + *offset] == '%')
1185 ++*offset;
1186 action = ACT_RP_LONG_RIGHT;
1188 break;
1190 case ':':
1191 if (strchr ("-=?+", words[1 + *offset]) == NULL)
1192 goto syntax;
1194 colon_seen = 1;
1195 action = words[++*offset];
1196 break;
1198 case '-':
1199 case '=':
1200 case '?':
1201 case '+':
1202 action = words[*offset];
1203 break;
1205 default:
1206 goto syntax;
1209 /* Now collect the pattern, but don't expand it yet. */
1210 ++*offset;
1211 for (; words[*offset]; ++(*offset))
1213 switch (words[*offset])
1215 case '{':
1216 if (!pattern_is_quoted)
1217 ++depth;
1218 break;
1220 case '}':
1221 if (!pattern_is_quoted)
1223 if (depth == 0)
1224 goto envsubst;
1225 --depth;
1227 break;
1229 case '\\':
1230 if (pattern_is_quoted)
1231 /* Quoted; treat as normal character. */
1232 break;
1234 /* Otherwise, it's an escape: next character is literal. */
1235 if (words[++*offset] == '\0')
1236 goto syntax;
1238 pattern = w_addchar (pattern, &pat_length, &pat_maxlen, '\\');
1239 if (pattern == NULL)
1240 goto no_space;
1242 break;
1244 case '\'':
1245 if (pattern_is_quoted == 0)
1246 pattern_is_quoted = 1;
1247 else if (pattern_is_quoted == 1)
1248 pattern_is_quoted = 0;
1250 break;
1252 case '"':
1253 if (pattern_is_quoted == 0)
1254 pattern_is_quoted = 2;
1255 else if (pattern_is_quoted == 2)
1256 pattern_is_quoted = 0;
1258 break;
1261 pattern = w_addchar (pattern, &pat_length, &pat_maxlen,
1262 words[*offset]);
1263 if (pattern == NULL)
1264 goto no_space;
1268 /* End of input string -- remember to reparse the character that we
1269 * stopped at. */
1270 --(*offset);
1272 envsubst:
1273 if (words[start] == '{' && words[*offset] != '}')
1274 goto syntax;
1276 if (env == NULL)
1278 if (seen_hash)
1280 /* $# expands to the number of positional parameters */
1281 buffer[20] = '\0';
1282 value = _itoa_word (__libc_argc - 1, &buffer[20], 10, 0);
1283 seen_hash = 0;
1285 else
1287 /* Just $ on its own */
1288 *offset = start - 1;
1289 *word = w_addchar (*word, word_length, max_length, '$');
1290 return *word ? 0 : WRDE_NOSPACE;
1293 /* Is it a numeric parameter? */
1294 else if (isdigit (env[0]))
1296 int n = atoi (env);
1298 if (n >= __libc_argc)
1299 /* Substitute NULL. */
1300 value = NULL;
1301 else
1302 /* Replace with appropriate positional parameter. */
1303 value = __libc_argv[n];
1305 /* Is it a special parameter? */
1306 else if (special)
1308 /* Is it `$$'? */
1309 if (*env == '$')
1311 buffer[20] = '\0';
1312 value = _itoa_word (__getpid (), &buffer[20], 10, 0);
1314 /* Is it `${#*}' or `${#@}'? */
1315 else if ((*env == '*' || *env == '@') && seen_hash)
1317 buffer[20] = '\0';
1318 value = _itoa_word (__libc_argc > 0 ? __libc_argc - 1 : 0,
1319 &buffer[20], 10, 0);
1320 *word = w_addstr (*word, word_length, max_length, value);
1321 free (env);
1322 if (pattern)
1323 free (pattern);
1324 return *word ? 0 : WRDE_NOSPACE;
1326 /* Is it `$*' or `$@' (unquoted) ? */
1327 else if (*env == '*' || (*env == '@' && !quoted))
1329 size_t plist_len = 0;
1330 int p;
1331 char *end;
1333 /* Build up value parameter by parameter (copy them) */
1334 for (p = 1; __libc_argv[p]; ++p)
1335 plist_len += strlen (__libc_argv[p]) + 1; /* for space */
1336 value = malloc (plist_len);
1337 if (value == NULL)
1338 goto no_space;
1339 end = value;
1340 *end = 0;
1341 for (p = 1; __libc_argv[p]; ++p)
1343 if (p > 1)
1344 *end++ = ' ';
1345 end = __stpcpy (end, __libc_argv[p]);
1348 free_value = 1;
1350 else
1352 /* Must be a quoted `$@' */
1353 assert (*env == '@' && quoted);
1355 /* Each parameter is a separate word ("$@") */
1356 if (__libc_argc == 2)
1357 value = __libc_argv[1];
1358 else if (__libc_argc > 2)
1360 int p;
1362 /* Append first parameter to current word. */
1363 value = w_addstr (*word, word_length, max_length,
1364 __libc_argv[1]);
1365 if (value == NULL || w_addword (pwordexp, value))
1366 goto no_space;
1368 for (p = 2; __libc_argv[p + 1]; p++)
1370 char *newword = __strdup (__libc_argv[p]);
1371 if (newword == NULL || w_addword (pwordexp, newword))
1372 goto no_space;
1375 /* Start a new word with the last parameter. */
1376 *word = w_newword (word_length, max_length);
1377 value = __libc_argv[p];
1379 else
1381 free (env);
1382 free (pattern);
1383 return 0;
1387 else
1388 value = getenv (env);
1390 if (value == NULL && (flags & WRDE_UNDEF))
1392 /* Variable not defined. */
1393 error = WRDE_BADVAL;
1394 goto do_error;
1397 if (action != ACT_NONE)
1399 int expand_pattern = 0;
1401 /* First, find out if we need to expand pattern (i.e. if we will
1402 * use it). */
1403 switch (action)
1405 case ACT_RP_SHORT_LEFT:
1406 case ACT_RP_LONG_LEFT:
1407 case ACT_RP_SHORT_RIGHT:
1408 case ACT_RP_LONG_RIGHT:
1409 /* Always expand for these. */
1410 expand_pattern = 1;
1411 break;
1413 case ACT_NULL_ERROR:
1414 case ACT_NULL_SUBST:
1415 case ACT_NULL_ASSIGN:
1416 if (!value || (!*value && colon_seen))
1417 /* If param is unset, or set but null and a colon has been seen,
1418 the expansion of the pattern will be needed. */
1419 expand_pattern = 1;
1421 break;
1423 case ACT_NONNULL_SUBST:
1424 /* Expansion of word will be needed if parameter is set and not null,
1425 or set null but no colon has been seen. */
1426 if (value && (*value || !colon_seen))
1427 expand_pattern = 1;
1429 break;
1431 default:
1432 assert (! "Unrecognised action!");
1435 if (expand_pattern)
1437 /* We need to perform tilde expansion, parameter expansion,
1438 command substitution, and arithmetic expansion. We also
1439 have to be a bit careful with wildcard characters, as
1440 pattern might be given to fnmatch soon. To do this, we
1441 convert quotes to escapes. */
1443 char *expanded;
1444 size_t exp_len;
1445 size_t exp_maxl;
1446 char *p;
1447 int quoted = 0; /* 1: single quotes; 2: double */
1449 expanded = w_newword (&exp_len, &exp_maxl);
1450 for (p = pattern; p && *p; p++)
1452 size_t offset;
1454 switch (*p)
1456 case '"':
1457 if (quoted == 2)
1458 quoted = 0;
1459 else if (quoted == 0)
1460 quoted = 2;
1461 else break;
1463 continue;
1465 case '\'':
1466 if (quoted == 1)
1467 quoted = 0;
1468 else if (quoted == 0)
1469 quoted = 1;
1470 else break;
1472 continue;
1474 case '*':
1475 case '?':
1476 if (quoted)
1478 /* Convert quoted wildchar to escaped wildchar. */
1479 expanded = w_addchar (expanded, &exp_len,
1480 &exp_maxl, '\\');
1482 if (expanded == NULL)
1483 goto no_space;
1485 break;
1487 case '$':
1488 offset = 0;
1489 error = parse_dollars (&expanded, &exp_len, &exp_maxl, p,
1490 &offset, flags, NULL, NULL, NULL, 1);
1491 if (error)
1493 if (free_value)
1494 free (value);
1496 if (expanded)
1497 free (expanded);
1499 goto do_error;
1502 p += offset;
1503 continue;
1505 case '~':
1506 if (quoted || exp_len)
1507 break;
1509 offset = 0;
1510 error = parse_tilde (&expanded, &exp_len, &exp_maxl, p,
1511 &offset, 0);
1512 if (error)
1514 if (free_value)
1515 free (value);
1517 if (expanded)
1518 free (expanded);
1520 goto do_error;
1523 p += offset;
1524 continue;
1526 case '\\':
1527 expanded = w_addchar (expanded, &exp_len, &exp_maxl, '\\');
1528 ++p;
1529 assert (*p); /* checked when extracted initially */
1530 if (expanded == NULL)
1531 goto no_space;
1534 expanded = w_addchar (expanded, &exp_len, &exp_maxl, *p);
1536 if (expanded == NULL)
1537 goto no_space;
1540 if (pattern)
1541 free (pattern);
1543 pattern = expanded;
1546 switch (action)
1548 case ACT_RP_SHORT_LEFT:
1549 case ACT_RP_LONG_LEFT:
1550 case ACT_RP_SHORT_RIGHT:
1551 case ACT_RP_LONG_RIGHT:
1553 char *p;
1554 char c;
1555 char *end;
1557 if (value == NULL || pattern == NULL || *pattern == '\0')
1558 break;
1560 end = value + strlen (value);
1562 switch (action)
1564 case ACT_RP_SHORT_LEFT:
1565 for (p = value; p <= end; ++p)
1567 c = *p;
1568 *p = '\0';
1569 if (fnmatch (pattern, value, 0) != FNM_NOMATCH)
1571 *p = c;
1572 if (free_value)
1574 char *newval = __strdup (p);
1575 if (newval == NULL)
1577 free (value);
1578 goto no_space;
1580 free (value);
1581 value = newval;
1583 else
1584 value = p;
1585 break;
1587 *p = c;
1590 break;
1592 case ACT_RP_LONG_LEFT:
1593 for (p = end; p >= value; --p)
1595 c = *p;
1596 *p = '\0';
1597 if (fnmatch (pattern, value, 0) != FNM_NOMATCH)
1599 *p = c;
1600 if (free_value)
1602 char *newval = __strdup (p);
1603 if (newval == NULL)
1605 free (value);
1606 goto no_space;
1608 free (value);
1609 value = newval;
1611 else
1612 value = p;
1613 break;
1615 *p = c;
1618 break;
1620 case ACT_RP_SHORT_RIGHT:
1621 for (p = end; p >= value; --p)
1623 if (fnmatch (pattern, p, 0) != FNM_NOMATCH)
1625 char *newval;
1626 newval = malloc (p - value + 1);
1628 if (newval == NULL)
1630 if (free_value)
1631 free (value);
1632 goto no_space;
1635 *(char *) __mempcpy (newval, value, p - value) = '\0';
1636 if (free_value)
1637 free (value);
1638 value = newval;
1639 free_value = 1;
1640 break;
1644 break;
1646 case ACT_RP_LONG_RIGHT:
1647 for (p = value; p <= end; ++p)
1649 if (fnmatch (pattern, p, 0) != FNM_NOMATCH)
1651 char *newval;
1652 newval = malloc (p - value + 1);
1654 if (newval == NULL)
1656 if (free_value)
1657 free (value);
1658 goto no_space;
1661 *(char *) __mempcpy (newval, value, p - value) = '\0';
1662 if (free_value)
1663 free (value);
1664 value = newval;
1665 free_value = 1;
1666 break;
1670 break;
1672 default:
1673 break;
1676 break;
1679 case ACT_NULL_ERROR:
1680 if (value && *value)
1681 /* Substitute parameter */
1682 break;
1684 error = 0;
1685 if (!colon_seen && value)
1686 /* Substitute NULL */
1688 else if (*pattern)
1689 fprintf (stderr, "%s: %s\n", env, pattern);
1690 else
1692 fprintf (stderr, "%s: parameter null or not set\n", env);
1693 error = WRDE_BADVAL;
1696 if (free_value)
1697 free (value);
1698 goto do_error;
1700 case ACT_NULL_SUBST:
1701 if (value && *value)
1702 /* Substitute parameter */
1703 break;
1705 if (free_value && value)
1706 free (value);
1708 if (!colon_seen && value)
1709 /* Substitute NULL */
1710 goto success;
1712 value = pattern ? __strdup (pattern) : pattern;
1713 free_value = 1;
1715 if (pattern && !value)
1716 goto no_space;
1718 break;
1720 case ACT_NONNULL_SUBST:
1721 if (value && (*value || !colon_seen))
1723 if (free_value && value)
1724 free (value);
1726 value = pattern ? __strdup (pattern) : pattern;
1727 free_value = 1;
1729 if (pattern && !value)
1730 goto no_space;
1732 break;
1735 /* Substitute NULL */
1736 if (free_value)
1737 free (value);
1738 goto success;
1740 case ACT_NULL_ASSIGN:
1741 if (value && *value)
1742 /* Substitute parameter */
1743 break;
1745 if (!colon_seen && value)
1747 /* Substitute NULL */
1748 if (free_value)
1749 free (value);
1750 goto success;
1753 if (free_value && value)
1754 free (value);
1756 value = pattern ? __strdup (pattern) : pattern;
1757 free_value = 1;
1759 if (pattern && !value)
1760 goto no_space;
1762 setenv (env, value, 1);
1763 break;
1765 default:
1766 assert (! "Unrecognised action!");
1770 free (env); env = NULL;
1771 free (pattern); pattern = NULL;
1773 if (seen_hash)
1775 char param_length[21];
1776 param_length[20] = '\0';
1777 *word = w_addstr (*word, word_length, max_length,
1778 _itoa_word (value ? strlen (value) : 0,
1779 &param_length[20], 10, 0));
1780 if (free_value)
1782 assert (value != NULL);
1783 free (value);
1786 return *word ? 0 : WRDE_NOSPACE;
1789 if (value == NULL)
1790 return 0;
1792 if (quoted || !pwordexp)
1794 /* Quoted - no field split */
1795 *word = w_addstr (*word, word_length, max_length, value);
1796 if (free_value)
1797 free (value);
1799 return *word ? 0 : WRDE_NOSPACE;
1801 else
1803 /* Need to field-split */
1804 char *value_copy = __strdup (value); /* Don't modify value */
1805 char *field_begin = value_copy;
1806 int seen_nonws_ifs = 0;
1808 if (free_value)
1809 free (value);
1811 if (value_copy == NULL)
1812 goto no_space;
1816 char *field_end = field_begin;
1817 char *next_field;
1819 /* If this isn't the first field, start a new word */
1820 if (field_begin != value_copy)
1822 if (w_addword (pwordexp, *word) == WRDE_NOSPACE)
1824 free (value_copy);
1825 goto no_space;
1828 *word = w_newword (word_length, max_length);
1831 /* Skip IFS whitespace before the field */
1832 field_begin += strspn (field_begin, ifs_white);
1834 if (!seen_nonws_ifs && *field_begin == 0)
1835 /* Nothing but whitespace */
1836 break;
1838 /* Search for the end of the field */
1839 field_end = field_begin + strcspn (field_begin, ifs);
1841 /* Set up pointer to the character after end of field and
1842 skip whitespace IFS after it. */
1843 next_field = field_end + strspn (field_end, ifs_white);
1845 /* Skip at most one non-whitespace IFS character after the field */
1846 seen_nonws_ifs = 0;
1847 if (*next_field && strchr (ifs, *next_field))
1849 seen_nonws_ifs = 1;
1850 next_field++;
1853 /* Null-terminate it */
1854 *field_end = 0;
1856 /* Tag a copy onto the current word */
1857 *word = w_addstr (*word, word_length, max_length, field_begin);
1859 if (*word == NULL && *field_begin != '\0')
1861 free (value_copy);
1862 goto no_space;
1865 field_begin = next_field;
1867 while (seen_nonws_ifs || *field_begin);
1869 free (value_copy);
1872 return 0;
1874 success:
1875 error = 0;
1876 goto do_error;
1878 no_space:
1879 error = WRDE_NOSPACE;
1880 goto do_error;
1882 syntax:
1883 error = WRDE_SYNTAX;
1885 do_error:
1886 if (env)
1887 free (env);
1889 if (pattern)
1890 free (pattern);
1892 return error;
1895 static int
1896 internal_function
1897 parse_dollars (char **word, size_t *word_length, size_t *max_length,
1898 const char *words, size_t *offset, int flags,
1899 wordexp_t *pwordexp, const char *ifs, const char *ifs_white,
1900 int quoted)
1902 /* We are poised _at_ "$" */
1903 switch (words[1 + *offset])
1905 case '"':
1906 case '\'':
1907 case 0:
1908 *word = w_addchar (*word, word_length, max_length, '$');
1909 return *word ? 0 : WRDE_NOSPACE;
1911 case '(':
1912 if (words[2 + *offset] == '(')
1914 /* Differentiate between $((1+3)) and $((echo);(ls)) */
1915 int i = 3 + *offset;
1916 int depth = 0;
1917 while (words[i] && !(depth == 0 && words[i] == ')'))
1919 if (words[i] == '(')
1920 ++depth;
1921 else if (words[i] == ')')
1922 --depth;
1924 ++i;
1927 if (words[i] == ')' && words[i + 1] == ')')
1929 (*offset) += 3;
1930 /* Call parse_arith -- 0 is for "no brackets" */
1931 return parse_arith (word, word_length, max_length, words, offset,
1932 flags, 0);
1936 if (flags & WRDE_NOCMD)
1937 return WRDE_CMDSUB;
1939 (*offset) += 2;
1940 return parse_comm (word, word_length, max_length, words, offset, flags,
1941 quoted? NULL : pwordexp, ifs, ifs_white);
1943 case '[':
1944 (*offset) += 2;
1945 /* Call parse_arith -- 1 is for "brackets" */
1946 return parse_arith (word, word_length, max_length, words, offset, flags,
1949 case '{':
1950 default:
1951 ++(*offset); /* parse_param needs to know if "{" is there */
1952 return parse_param (word, word_length, max_length, words, offset, flags,
1953 pwordexp, ifs, ifs_white, quoted);
1957 static int
1958 internal_function
1959 parse_backtick (char **word, size_t *word_length, size_t *max_length,
1960 const char *words, size_t *offset, int flags,
1961 wordexp_t *pwordexp, const char *ifs, const char *ifs_white)
1963 /* We are poised just after "`" */
1964 int error;
1965 int squoting = 0;
1966 size_t comm_length;
1967 size_t comm_maxlen;
1968 char *comm = w_newword (&comm_length, &comm_maxlen);
1970 for (; words[*offset]; ++(*offset))
1972 switch (words[*offset])
1974 case '`':
1975 /* Go -- give the script to the shell */
1976 error = exec_comm (comm, word, word_length, max_length, flags,
1977 pwordexp, ifs, ifs_white);
1978 free (comm);
1979 return error;
1981 case '\\':
1982 if (squoting)
1984 error = parse_qtd_backslash (&comm, &comm_length, &comm_maxlen,
1985 words, offset);
1987 if (error)
1989 free (comm);
1990 return error;
1993 break;
1996 ++(*offset);
1997 error = parse_backslash (&comm, &comm_length, &comm_maxlen, words,
1998 offset);
2000 if (error)
2002 free (comm);
2003 return error;
2006 break;
2008 case '\'':
2009 squoting = 1 - squoting;
2010 default:
2011 comm = w_addchar (comm, &comm_length, &comm_maxlen, words[*offset]);
2012 if (comm == NULL)
2013 return WRDE_NOSPACE;
2017 /* Premature end */
2018 free (comm);
2019 return WRDE_SYNTAX;
2022 static int
2023 internal_function
2024 parse_dquote (char **word, size_t *word_length, size_t *max_length,
2025 const char *words, size_t *offset, int flags,
2026 wordexp_t *pwordexp, const char * ifs, const char * ifs_white)
2028 /* We are poised just after a double-quote */
2029 int error;
2031 for (; words[*offset]; ++(*offset))
2033 switch (words[*offset])
2035 case '"':
2036 return 0;
2038 case '$':
2039 error = parse_dollars (word, word_length, max_length, words, offset,
2040 flags, pwordexp, ifs, ifs_white, 1);
2041 /* The ``1'' here is to tell parse_dollars not to
2042 * split the fields. It may need to, however ("$@").
2044 if (error)
2045 return error;
2047 break;
2049 case '`':
2050 if (flags & WRDE_NOCMD)
2051 return WRDE_CMDSUB;
2053 ++(*offset);
2054 error = parse_backtick (word, word_length, max_length, words,
2055 offset, flags, NULL, NULL, NULL);
2056 /* The first NULL here is to tell parse_backtick not to
2057 * split the fields.
2059 if (error)
2060 return error;
2062 break;
2064 case '\\':
2065 error = parse_qtd_backslash (word, word_length, max_length, words,
2066 offset);
2068 if (error)
2069 return error;
2071 break;
2073 default:
2074 *word = w_addchar (*word, word_length, max_length, words[*offset]);
2075 if (*word == NULL)
2076 return WRDE_NOSPACE;
2080 /* Unterminated string */
2081 return WRDE_SYNTAX;
2085 * wordfree() is to be called after pwordexp is finished with.
2088 void
2089 wordfree (wordexp_t *pwordexp)
2092 /* wordexp can set pwordexp to NULL */
2093 if (pwordexp && pwordexp->we_wordv)
2095 char **wordv = pwordexp->we_wordv;
2097 for (wordv += pwordexp->we_offs; *wordv; ++wordv)
2098 free (*wordv);
2100 free (pwordexp->we_wordv);
2101 pwordexp->we_wordv = NULL;
2106 * wordexp()
2110 wordexp (const char *words, wordexp_t *pwordexp, int flags)
2112 size_t wordv_offset;
2113 size_t words_offset;
2114 size_t word_length;
2115 size_t max_length;
2116 char *word = w_newword (&word_length, &max_length);
2117 int error;
2118 char *ifs;
2119 char ifs_white[4];
2120 char **old_wordv = pwordexp->we_wordv;
2121 size_t old_wordc = (flags & WRDE_REUSE) ? pwordexp->we_wordc : 0;
2123 if (flags & WRDE_REUSE)
2125 /* Minimal implementation of WRDE_REUSE for now */
2126 wordfree (pwordexp);
2127 old_wordv = NULL;
2130 if (flags & WRDE_DOOFFS)
2132 pwordexp->we_wordv = calloc (1 + pwordexp->we_offs, sizeof (char *));
2133 if (pwordexp->we_wordv == NULL)
2135 error = WRDE_NOSPACE;
2136 goto do_error;
2139 else
2141 pwordexp->we_wordv = calloc (1, sizeof (char *));
2142 if (pwordexp->we_wordv == NULL)
2144 error = WRDE_NOSPACE;
2145 goto do_error;
2148 pwordexp->we_offs = 0;
2151 if ((flags & WRDE_APPEND) == 0)
2152 pwordexp->we_wordc = 0;
2154 wordv_offset = pwordexp->we_offs + pwordexp->we_wordc;
2156 /* Find out what the field separators are.
2157 * There are two types: whitespace and non-whitespace.
2159 ifs = getenv ("IFS");
2161 if (!ifs)
2162 /* IFS unset - use <space><tab><newline>. */
2163 ifs = strcpy (ifs_white, " \t\n");
2164 else
2166 char *ifsch = ifs;
2167 char *whch = ifs_white;
2169 /* Start off with no whitespace IFS characters */
2170 ifs_white[0] = '\0';
2172 while (*ifsch != '\0')
2174 if ((*ifsch == ' ') || (*ifsch == '\t') || (*ifsch == '\n'))
2176 /* Whitespace IFS. See first whether it is already in our
2177 collection. */
2178 char *runp = ifs_white;
2180 while (runp < whch && *runp != '\0' && *runp != *ifsch)
2181 ++runp;
2183 if (runp == whch)
2184 *whch++ = *ifsch;
2187 ++ifsch;
2189 *whch = '\0';
2192 for (words_offset = 0 ; words[words_offset] ; ++words_offset)
2193 switch (words[words_offset])
2195 case '\\':
2196 error = parse_backslash (&word, &word_length, &max_length, words,
2197 &words_offset);
2199 if (error)
2200 goto do_error;
2202 break;
2204 case '$':
2205 error = parse_dollars (&word, &word_length, &max_length, words,
2206 &words_offset, flags, pwordexp, ifs, ifs_white,
2209 if (error)
2210 goto do_error;
2212 break;
2214 case '`':
2215 if (flags & WRDE_NOCMD)
2217 error = WRDE_CMDSUB;
2218 goto do_error;
2221 ++words_offset;
2222 error = parse_backtick (&word, &word_length, &max_length, words,
2223 &words_offset, flags, pwordexp, ifs,
2224 ifs_white);
2226 if (error)
2227 goto do_error;
2229 break;
2231 case '"':
2232 ++words_offset;
2233 error = parse_dquote (&word, &word_length, &max_length, words,
2234 &words_offset, flags, pwordexp, ifs, ifs_white);
2236 if (error)
2237 goto do_error;
2239 if (!word_length)
2241 error = w_addword (pwordexp, NULL);
2243 if (error)
2244 return error;
2247 break;
2249 case '\'':
2250 ++words_offset;
2251 error = parse_squote (&word, &word_length, &max_length, words,
2252 &words_offset);
2254 if (error)
2255 goto do_error;
2257 if (!word_length)
2259 error = w_addword (pwordexp, NULL);
2261 if (error)
2262 return error;
2265 break;
2267 case '~':
2268 error = parse_tilde (&word, &word_length, &max_length, words,
2269 &words_offset, pwordexp->we_wordc);
2271 if (error)
2272 goto do_error;
2274 break;
2276 case '*':
2277 case '[':
2278 case '?':
2279 error = parse_glob (&word, &word_length, &max_length, words,
2280 &words_offset, flags, pwordexp, ifs, ifs_white);
2282 if (error)
2283 goto do_error;
2285 break;
2287 default:
2288 /* Is it a word separator? */
2289 if (strchr (" \t", words[words_offset]) == NULL)
2291 char ch = words[words_offset];
2293 /* Not a word separator -- but is it a valid word char? */
2294 if (strchr ("\n|&;<>(){}", ch))
2296 /* Fail */
2297 error = WRDE_BADCHAR;
2298 goto do_error;
2301 /* "Ordinary" character -- add it to word */
2302 word = w_addchar (word, &word_length, &max_length,
2303 ch);
2304 if (word == NULL)
2306 error = WRDE_NOSPACE;
2307 goto do_error;
2310 break;
2313 /* If a word has been delimited, add it to the list. */
2314 if (word != NULL)
2316 error = w_addword (pwordexp, word);
2317 if (error)
2318 goto do_error;
2321 word = w_newword (&word_length, &max_length);
2324 /* End of string */
2326 /* There was a word separator at the end */
2327 if (word == NULL) /* i.e. w_newword */
2328 return 0;
2330 /* There was no field separator at the end */
2331 return w_addword (pwordexp, word);
2333 do_error:
2334 /* Error:
2335 * free memory used (unless error is WRDE_NOSPACE), and
2336 * set we_wordc and wd_wordv back to what they were.
2339 if (word != NULL)
2340 free (word);
2342 if (error == WRDE_NOSPACE)
2343 return WRDE_NOSPACE;
2345 wordfree (pwordexp);
2346 pwordexp->we_wordv = old_wordv;
2347 pwordexp->we_wordc = old_wordc;
2348 return error;