Update.
[glibc.git] / posix / wordexp.c
blobc43d608aba9c5938a9025767c24ee593e0acef81
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 && 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 && 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 __close (fildes[0]);
863 __execve (_PATH_BSHELL, (char *const *) args, __environ);
865 /* Bad. What now? */
866 abort ();
869 /* Parent */
871 __close (fildes[1]);
872 buffer = __alloca (bufsize);
874 if (!pwordexp)
875 { /* Quoted - no field splitting */
877 while (1)
879 if ((buflen = __read (fildes[0], buffer, bufsize)) < 1)
881 if (__waitpid (pid, NULL, WNOHANG) == 0)
882 continue;
883 if ((buflen = __read (fildes[0], buffer, bufsize)) < 1)
884 break;
887 *word = w_addmem (*word, word_length, max_length, buffer, buflen);
888 if (*word == NULL)
889 goto no_space;
892 else
893 /* Not quoted - split fields */
895 int copying = 0;
896 /* 'copying' is:
897 * 0 when searching for first character in a field not IFS white space
898 * 1 when copying the text of a field
899 * 2 when searching for possible non-whitespace IFS
902 while (1)
904 if ((buflen = __read (fildes[0], buffer, bufsize)) < 1)
906 if (__waitpid (pid, NULL, WNOHANG) == 0)
907 continue;
908 if ((__read (fildes[0], buffer, bufsize)) < 1)
909 break;
912 for (i = 0; i < buflen; ++i)
914 if (strchr (ifs, buffer[i]) != NULL)
916 /* Current character is IFS */
917 if (strchr (ifs_white, buffer[i]) == NULL)
919 /* Current character is IFS but not whitespace */
920 if (copying == 2)
922 /* current character
925 * eg: text<space><comma><space>moretext
927 * So, strip whitespace IFS (like at the start)
929 copying = 0;
930 continue;
933 copying = 0;
934 /* fall through and delimit field.. */
936 else
938 /* Current character is IFS white space */
940 /* If not copying a field, ignore it */
941 if (copying != 1)
942 continue;
944 /* End of field (search for non-ws IFS afterwards) */
945 copying = 2;
948 /* First IFS white space, or IFS non-whitespace.
949 * Delimit the field. Nulls are converted by w_addword. */
950 if (w_addword (pwordexp, *word) == WRDE_NOSPACE)
951 goto no_space;
953 *word = w_newword (word_length, max_length);
954 /* fall back round the loop.. */
956 else
958 /* Not IFS character */
959 copying = 1;
961 *word = w_addchar (*word, word_length, max_length,
962 buffer[i]);
963 if (*word == NULL)
964 goto no_space;
970 /* Bash chops off trailing newlines, which seems sensible. */
971 while (*word_length > 0 && (*word)[*word_length - 1] == '\n')
973 (*word)[--*word_length] = '\0';
975 /* If the last word was entirely newlines, turn it into a new word
976 * which can be ignored if there's nothing following it. */
977 if (*word_length == 0)
979 free (*word);
980 *word = w_newword (word_length, max_length);
981 break;
985 __close (fildes[0]);
986 return 0;
988 no_space:
989 __kill (pid, SIGKILL);
990 __waitpid (pid, NULL, 0);
991 __close (fildes[0]);
992 return WRDE_NOSPACE;
995 static int
996 internal_function
997 parse_comm (char **word, size_t *word_length, size_t *max_length,
998 const char *words, size_t *offset, int flags, wordexp_t *pwordexp,
999 const char *ifs, const char *ifs_white)
1001 /* We are poised just after "$(" */
1002 int paren_depth = 1;
1003 int error = 0;
1004 int quoted = 0; /* 1 for singly-quoted, 2 for doubly-quoted */
1005 size_t comm_length;
1006 size_t comm_maxlen;
1007 char *comm = w_newword (&comm_length, &comm_maxlen);
1009 for (; words[*offset]; ++(*offset))
1011 switch (words[*offset])
1013 case '\'':
1014 if (quoted == 0)
1015 quoted = 1;
1016 else if (quoted == 1)
1017 quoted = 0;
1019 break;
1021 case '"':
1022 if (quoted == 0)
1023 quoted = 2;
1024 else if (quoted == 2)
1025 quoted = 0;
1027 break;
1029 case ')':
1030 if (!quoted && --paren_depth == 0)
1032 /* Go -- give script to the shell */
1033 if (comm)
1035 error = exec_comm (comm, word, word_length, max_length,
1036 flags, pwordexp, ifs, ifs_white);
1037 free (comm);
1040 return error;
1043 /* This is just part of the script */
1044 break;
1046 case '(':
1047 if (!quoted)
1048 ++paren_depth;
1051 comm = w_addchar (comm, &comm_length, &comm_maxlen, words[*offset]);
1052 if (comm == NULL)
1053 return WRDE_NOSPACE;
1056 /* Premature end */
1057 if (comm)
1058 free (comm);
1060 return WRDE_SYNTAX;
1063 static int
1064 internal_function
1065 parse_param (char **word, size_t *word_length, size_t *max_length,
1066 const char *words, size_t *offset, int flags, wordexp_t *pwordexp,
1067 const char *ifs, const char *ifs_white, int quoted)
1069 /* We are poised just after "$" */
1070 enum action
1072 ACT_NONE,
1073 ACT_RP_SHORT_LEFT = '#',
1074 ACT_RP_LONG_LEFT = 'L',
1075 ACT_RP_SHORT_RIGHT = '%',
1076 ACT_RP_LONG_RIGHT = 'R',
1077 ACT_NULL_ERROR = '?',
1078 ACT_NULL_SUBST = '-',
1079 ACT_NONNULL_SUBST = '+',
1080 ACT_NULL_ASSIGN = '='
1082 size_t env_length;
1083 size_t env_maxlen;
1084 size_t pat_length;
1085 size_t pat_maxlen;
1086 size_t start = *offset;
1087 char *env;
1088 char *pattern;
1089 char *value = NULL;
1090 enum action action = ACT_NONE;
1091 int depth = 0;
1092 int colon_seen = 0;
1093 int seen_hash = 0;
1094 int free_value = 0;
1095 int pattern_is_quoted = 0; /* 1 for singly-quoted, 2 for doubly-quoted */
1096 int error;
1097 int special = 0;
1098 char buffer[21];
1099 int brace = words[*offset] == '{';
1101 env = w_newword (&env_length, &env_maxlen);
1102 pattern = w_newword (&pat_length, &pat_maxlen);
1104 if (brace)
1105 ++*offset;
1107 /* First collect the parameter name. */
1109 if (words[*offset] == '#')
1111 seen_hash = 1;
1112 if (!brace)
1113 goto envsubst;
1114 ++*offset;
1117 if (isalpha (words[*offset]) || words[*offset] == '_')
1119 /* Normal parameter name. */
1122 env = w_addchar (env, &env_length, &env_maxlen,
1123 words[*offset]);
1124 if (env == NULL)
1125 goto no_space;
1127 while (isalnum (words[++*offset]) || words[*offset] == '_');
1129 else if (isdigit (words[*offset]))
1131 /* Numeric parameter name. */
1132 special = 1;
1135 env = w_addchar (env, &env_length, &env_maxlen,
1136 words[*offset]);
1137 if (env == NULL)
1138 goto no_space;
1139 if (!brace)
1140 goto envsubst;
1142 while (isdigit(words[++*offset]));
1144 else if (strchr ("*@$", words[*offset]) != NULL)
1146 /* Special parameter. */
1147 special = 1;
1148 env = w_addchar (env, &env_length, &env_maxlen,
1149 words[*offset]);
1150 if (env == NULL)
1151 goto no_space;
1152 ++*offset;
1154 else
1156 if (brace)
1157 goto syntax;
1160 if (brace)
1162 /* Check for special action to be applied to the value. */
1163 switch (words[*offset])
1165 case '}':
1166 /* Evaluate. */
1167 goto envsubst;
1169 case '#':
1170 action = ACT_RP_SHORT_LEFT;
1171 if (words[1 + *offset] == '#')
1173 ++*offset;
1174 action = ACT_RP_LONG_LEFT;
1176 break;
1178 case '%':
1179 action = ACT_RP_SHORT_RIGHT;
1180 if (words[1 + *offset] == '%')
1182 ++*offset;
1183 action = ACT_RP_LONG_RIGHT;
1185 break;
1187 case ':':
1188 if (strchr ("-=?+", words[1 + *offset]) == NULL)
1189 goto syntax;
1191 colon_seen = 1;
1192 action = words[++*offset];
1193 break;
1195 case '-':
1196 case '=':
1197 case '?':
1198 case '+':
1199 action = words[*offset];
1200 break;
1202 default:
1203 goto syntax;
1206 /* Now collect the pattern, but don't expand it yet. */
1207 ++*offset;
1208 for (; words[*offset]; ++(*offset))
1210 switch (words[*offset])
1212 case '{':
1213 if (!pattern_is_quoted)
1214 ++depth;
1215 break;
1217 case '}':
1218 if (!pattern_is_quoted)
1220 if (depth == 0)
1221 goto envsubst;
1222 --depth;
1224 break;
1226 case '\\':
1227 if (pattern_is_quoted)
1228 /* Quoted; treat as normal character. */
1229 break;
1231 /* Otherwise, it's an escape: next character is literal. */
1232 if (words[++*offset] == '\0')
1233 goto syntax;
1235 pattern = w_addchar (pattern, &pat_length, &pat_maxlen, '\\');
1236 if (pattern == NULL)
1237 goto no_space;
1239 break;
1241 case '\'':
1242 if (pattern_is_quoted == 0)
1243 pattern_is_quoted = 1;
1244 else if (pattern_is_quoted == 1)
1245 pattern_is_quoted = 0;
1247 break;
1249 case '"':
1250 if (pattern_is_quoted == 0)
1251 pattern_is_quoted = 2;
1252 else if (pattern_is_quoted == 2)
1253 pattern_is_quoted = 0;
1255 break;
1258 pattern = w_addchar (pattern, &pat_length, &pat_maxlen,
1259 words[*offset]);
1260 if (pattern == NULL)
1261 goto no_space;
1265 /* End of input string -- remember to reparse the character that we
1266 * stopped at. */
1267 --(*offset);
1269 envsubst:
1270 if (words[start] == '{' && words[*offset] != '}')
1271 goto syntax;
1273 if (env == NULL)
1275 if (seen_hash)
1277 /* $# expands to the number of positional parameters */
1278 buffer[20] = '\0';
1279 value = _itoa_word (__libc_argc - 1, &buffer[20], 10, 0);
1280 seen_hash = 0;
1282 else
1284 /* Just $ on its own */
1285 *offset = start - 1;
1286 *word = w_addchar (*word, word_length, max_length, '$');
1287 return *word ? 0 : WRDE_NOSPACE;
1290 /* Is it a numeric parameter? */
1291 else if (isdigit (env[0]))
1293 int n = atoi (env);
1295 if (n >= __libc_argc)
1296 /* Substitute NULL. */
1297 value = NULL;
1298 else
1299 /* Replace with appropriate positional parameter. */
1300 value = __libc_argv[n];
1302 /* Is it a special parameter? */
1303 else if (special)
1305 /* Is it `$$'? */
1306 if (*env == '$')
1308 buffer[20] = '\0';
1309 value = _itoa_word (__getpid (), &buffer[20], 10, 0);
1311 /* Is it `${#*}' or `${#@}'? */
1312 else if ((*env == '*' || *env == '@') && seen_hash)
1314 buffer[20] = '\0';
1315 value = _itoa_word (__libc_argc > 0 ? __libc_argc - 1 : 0,
1316 &buffer[20], 10, 0);
1317 *word = w_addstr (*word, word_length, max_length, value);
1318 free (env);
1319 if (pattern)
1320 free (pattern);
1321 return *word ? 0 : WRDE_NOSPACE;
1323 /* Is it `$*' or `$@' (unquoted) ? */
1324 else if (*env == '*' || (*env == '@' && !quoted))
1326 size_t plist_len = 0;
1327 int p;
1328 char *end;
1330 /* Build up value parameter by parameter (copy them) */
1331 for (p = 1; __libc_argv[p]; ++p)
1332 plist_len += strlen (__libc_argv[p]) + 1; /* for space */
1333 value = malloc (plist_len);
1334 if (value == NULL)
1335 goto no_space;
1336 end = value;
1337 *end = 0;
1338 for (p = 1; __libc_argv[p]; ++p)
1340 if (p > 1)
1341 *end++ = ' ';
1342 end = __stpcpy (end, __libc_argv[p]);
1345 free_value = 1;
1347 else
1349 /* Must be a quoted `$@' */
1350 assert (*env == '@' && quoted);
1352 /* Each parameter is a separate word ("$@") */
1353 if (__libc_argc == 2)
1354 value = __libc_argv[1];
1355 else if (__libc_argc > 2)
1357 int p;
1359 /* Append first parameter to current word. */
1360 value = w_addstr (*word, word_length, max_length,
1361 __libc_argv[1]);
1362 if (value == NULL || w_addword (pwordexp, value))
1363 goto no_space;
1365 for (p = 2; __libc_argv[p + 1]; p++)
1367 char *newword = __strdup (__libc_argv[p]);
1368 if (newword == NULL || w_addword (pwordexp, newword))
1369 goto no_space;
1372 /* Start a new word with the last parameter. */
1373 *word = w_newword (word_length, max_length);
1374 value = __libc_argv[p];
1376 else
1378 free (env);
1379 free (pattern);
1380 return 0;
1384 else
1385 value = getenv (env);
1387 if (value == NULL && (flags & WRDE_UNDEF))
1389 /* Variable not defined. */
1390 error = WRDE_BADVAL;
1391 goto do_error;
1394 if (action != ACT_NONE)
1396 int expand_pattern = 0;
1398 /* First, find out if we need to expand pattern (i.e. if we will
1399 * use it). */
1400 switch (action)
1402 case ACT_RP_SHORT_LEFT:
1403 case ACT_RP_LONG_LEFT:
1404 case ACT_RP_SHORT_RIGHT:
1405 case ACT_RP_LONG_RIGHT:
1406 /* Always expand for these. */
1407 expand_pattern = 1;
1408 break;
1410 case ACT_NULL_ERROR:
1411 case ACT_NULL_SUBST:
1412 case ACT_NULL_ASSIGN:
1413 if (!value || (!*value && colon_seen))
1414 /* If param is unset, or set but null and a colon has been seen,
1415 the expansion of the pattern will be needed. */
1416 expand_pattern = 1;
1418 break;
1420 case ACT_NONNULL_SUBST:
1421 /* Expansion of word will be needed if parameter is set and not null,
1422 or set null but no colon has been seen. */
1423 if (value && (*value || !colon_seen))
1424 expand_pattern = 1;
1426 break;
1428 default:
1429 assert (! "Unrecognised action!");
1432 if (expand_pattern)
1434 /* We need to perform tilde expansion, parameter expansion,
1435 command substitution, and arithmetic expansion. We also
1436 have to be a bit careful with wildcard characters, as
1437 pattern might be given to fnmatch soon. To do this, we
1438 convert quotes to escapes. */
1440 char *expanded;
1441 size_t exp_len;
1442 size_t exp_maxl;
1443 char *p;
1444 int quoted = 0; /* 1: single quotes; 2: double */
1446 expanded = w_newword (&exp_len, &exp_maxl);
1447 for (p = pattern; p && *p; p++)
1449 size_t offset;
1451 switch (*p)
1453 case '"':
1454 if (quoted == 2)
1455 quoted = 0;
1456 else if (quoted == 0)
1457 quoted = 2;
1458 else break;
1460 continue;
1462 case '\'':
1463 if (quoted == 1)
1464 quoted = 0;
1465 else if (quoted == 0)
1466 quoted = 1;
1467 else break;
1469 continue;
1471 case '*':
1472 case '?':
1473 if (quoted)
1475 /* Convert quoted wildchar to escaped wildchar. */
1476 expanded = w_addchar (expanded, &exp_len,
1477 &exp_maxl, '\\');
1479 if (expanded == NULL)
1480 goto no_space;
1482 break;
1484 case '$':
1485 offset = 0;
1486 error = parse_dollars (&expanded, &exp_len, &exp_maxl, p,
1487 &offset, flags, NULL, NULL, NULL, 1);
1488 if (error)
1490 if (free_value)
1491 free (value);
1493 if (expanded)
1494 free (expanded);
1496 goto do_error;
1499 p += offset;
1500 continue;
1502 case '~':
1503 if (quoted || exp_len)
1504 break;
1506 offset = 0;
1507 error = parse_tilde (&expanded, &exp_len, &exp_maxl, p,
1508 &offset, 0);
1509 if (error)
1511 if (free_value)
1512 free (value);
1514 if (expanded)
1515 free (expanded);
1517 goto do_error;
1520 p += offset;
1521 continue;
1523 case '\\':
1524 expanded = w_addchar (expanded, &exp_len, &exp_maxl, '\\');
1525 ++p;
1526 assert (*p); /* checked when extracted initially */
1527 if (expanded == NULL)
1528 goto no_space;
1531 expanded = w_addchar (expanded, &exp_len, &exp_maxl, *p);
1533 if (expanded == NULL)
1534 goto no_space;
1537 if (pattern)
1538 free (pattern);
1540 pattern = expanded;
1543 switch (action)
1545 case ACT_RP_SHORT_LEFT:
1546 case ACT_RP_LONG_LEFT:
1547 case ACT_RP_SHORT_RIGHT:
1548 case ACT_RP_LONG_RIGHT:
1550 char *p;
1551 char c;
1552 char *end;
1554 if (value == NULL || pattern == NULL || *pattern == '\0')
1555 break;
1557 end = value + strlen (value);
1559 switch (action)
1561 case ACT_RP_SHORT_LEFT:
1562 for (p = value; p <= end; ++p)
1564 c = *p;
1565 *p = '\0';
1566 if (fnmatch (pattern, value, 0) != FNM_NOMATCH)
1568 *p = c;
1569 if (free_value)
1571 char *newval = __strdup (p);
1572 if (newval == NULL)
1574 free (value);
1575 goto no_space;
1577 free (value);
1578 value = newval;
1580 else
1581 value = p;
1582 break;
1584 *p = c;
1587 break;
1589 case ACT_RP_LONG_LEFT:
1590 for (p = end; p >= value; --p)
1592 c = *p;
1593 *p = '\0';
1594 if (fnmatch (pattern, value, 0) != FNM_NOMATCH)
1596 *p = c;
1597 if (free_value)
1599 char *newval = __strdup (p);
1600 if (newval == NULL)
1602 free (value);
1603 goto no_space;
1605 free (value);
1606 value = newval;
1608 else
1609 value = p;
1610 break;
1612 *p = c;
1615 break;
1617 case ACT_RP_SHORT_RIGHT:
1618 for (p = end; p >= value; --p)
1620 if (fnmatch (pattern, p, 0) != FNM_NOMATCH)
1622 char *newval;
1623 newval = malloc (p - value + 1);
1625 if (newval == NULL)
1627 if (free_value)
1628 free (value);
1629 goto no_space;
1632 *(char *) __mempcpy (newval, value, p - value) = '\0';
1633 if (free_value)
1634 free (value);
1635 value = newval;
1636 free_value = 1;
1637 break;
1641 break;
1643 case ACT_RP_LONG_RIGHT:
1644 for (p = value; p <= end; ++p)
1646 if (fnmatch (pattern, p, 0) != FNM_NOMATCH)
1648 char *newval;
1649 newval = malloc (p - value + 1);
1651 if (newval == NULL)
1653 if (free_value)
1654 free (value);
1655 goto no_space;
1658 *(char *) __mempcpy (newval, value, p - value) = '\0';
1659 if (free_value)
1660 free (value);
1661 value = newval;
1662 free_value = 1;
1663 break;
1667 break;
1669 default:
1670 break;
1673 break;
1676 case ACT_NULL_ERROR:
1677 if (value && *value)
1678 /* Substitute parameter */
1679 break;
1681 error = 0;
1682 if (!colon_seen && value)
1683 /* Substitute NULL */
1685 else if (*pattern)
1686 fprintf (stderr, "%s: %s\n", env, pattern);
1687 else
1689 fprintf (stderr, "%s: parameter null or not set\n", env);
1690 error = WRDE_BADVAL;
1693 if (free_value)
1694 free (value);
1695 goto do_error;
1697 case ACT_NULL_SUBST:
1698 if (value && *value)
1699 /* Substitute parameter */
1700 break;
1702 if (free_value && value)
1703 free (value);
1705 if (!colon_seen && value)
1706 /* Substitute NULL */
1707 goto success;
1709 value = pattern ? __strdup (pattern) : pattern;
1710 free_value = 1;
1712 if (pattern && !value)
1713 goto no_space;
1715 break;
1717 case ACT_NONNULL_SUBST:
1718 if (value && (*value || !colon_seen))
1720 if (free_value && value)
1721 free (value);
1723 value = pattern ? __strdup (pattern) : pattern;
1724 free_value = 1;
1726 if (pattern && !value)
1727 goto no_space;
1729 break;
1732 /* Substitute NULL */
1733 if (free_value)
1734 free (value);
1735 goto success;
1737 case ACT_NULL_ASSIGN:
1738 if (value && *value)
1739 /* Substitute parameter */
1740 break;
1742 if (!colon_seen && value)
1744 /* Substitute NULL */
1745 if (free_value)
1746 free (value);
1747 goto success;
1750 if (free_value && value)
1751 free (value);
1753 value = pattern ? __strdup (pattern) : pattern;
1754 free_value = 1;
1756 if (pattern && !value)
1757 goto no_space;
1759 setenv (env, value, 1);
1760 break;
1762 default:
1763 assert (! "Unrecognised action!");
1767 free (env); env = NULL;
1768 free (pattern); pattern = NULL;
1770 if (seen_hash)
1772 char param_length[21];
1773 param_length[20] = '\0';
1774 *word = w_addstr (*word, word_length, max_length,
1775 _itoa_word (value ? strlen (value) : 0,
1776 &param_length[20], 10, 0));
1777 if (free_value)
1779 assert (value != NULL);
1780 free (value);
1783 return *word ? 0 : WRDE_NOSPACE;
1786 if (value == NULL)
1787 return 0;
1789 if (quoted || !pwordexp)
1791 /* Quoted - no field split */
1792 *word = w_addstr (*word, word_length, max_length, value);
1793 if (free_value)
1794 free (value);
1796 return *word ? 0 : WRDE_NOSPACE;
1798 else
1800 /* Need to field-split */
1801 char *value_copy = __strdup (value); /* Don't modify value */
1802 char *field_begin = value_copy;
1803 int seen_nonws_ifs = 0;
1805 if (free_value)
1806 free (value);
1808 if (value_copy == NULL)
1809 goto no_space;
1813 char *field_end = field_begin;
1814 char *next_field;
1816 /* If this isn't the first field, start a new word */
1817 if (field_begin != value_copy)
1819 if (w_addword (pwordexp, *word) == WRDE_NOSPACE)
1821 free (value_copy);
1822 goto no_space;
1825 *word = w_newword (word_length, max_length);
1828 /* Skip IFS whitespace before the field */
1829 field_begin += strspn (field_begin, ifs_white);
1831 if (!seen_nonws_ifs && *field_begin == 0)
1832 /* Nothing but whitespace */
1833 break;
1835 /* Search for the end of the field */
1836 field_end = field_begin + strcspn (field_begin, ifs);
1838 /* Set up pointer to the character after end of field and
1839 skip whitespace IFS after it. */
1840 next_field = field_end + strspn (field_end, ifs_white);
1842 /* Skip at most one non-whitespace IFS character after the field */
1843 seen_nonws_ifs = 0;
1844 if (*next_field && strchr (ifs, *next_field))
1846 seen_nonws_ifs = 1;
1847 next_field++;
1850 /* Null-terminate it */
1851 *field_end = 0;
1853 /* Tag a copy onto the current word */
1854 *word = w_addstr (*word, word_length, max_length, field_begin);
1856 if (*word == NULL && *field_begin != '\0')
1858 free (value_copy);
1859 goto no_space;
1862 field_begin = next_field;
1864 while (seen_nonws_ifs || *field_begin);
1866 free (value_copy);
1869 return 0;
1871 success:
1872 error = 0;
1873 goto do_error;
1875 no_space:
1876 error = WRDE_NOSPACE;
1877 goto do_error;
1879 syntax:
1880 error = WRDE_SYNTAX;
1882 do_error:
1883 if (env)
1884 free (env);
1886 if (pattern)
1887 free (pattern);
1889 return error;
1892 static int
1893 internal_function
1894 parse_dollars (char **word, size_t *word_length, size_t *max_length,
1895 const char *words, size_t *offset, int flags,
1896 wordexp_t *pwordexp, const char *ifs, const char *ifs_white,
1897 int quoted)
1899 /* We are poised _at_ "$" */
1900 switch (words[1 + *offset])
1902 case '"':
1903 case '\'':
1904 case 0:
1905 *word = w_addchar (*word, word_length, max_length, '$');
1906 return *word ? 0 : WRDE_NOSPACE;
1908 case '(':
1909 if (words[2 + *offset] == '(')
1911 /* Differentiate between $((1+3)) and $((echo);(ls)) */
1912 int i = 3 + *offset;
1913 int depth = 0;
1914 while (words[i] && !(depth == 0 && words[i] == ')'))
1916 if (words[i] == '(')
1917 ++depth;
1918 else if (words[i] == ')')
1919 --depth;
1921 ++i;
1924 if (words[i] == ')' && words[i + 1] == ')')
1926 (*offset) += 3;
1927 /* Call parse_arith -- 0 is for "no brackets" */
1928 return parse_arith (word, word_length, max_length, words, offset,
1929 flags, 0);
1933 if (flags & WRDE_NOCMD)
1934 return WRDE_CMDSUB;
1936 (*offset) += 2;
1937 return parse_comm (word, word_length, max_length, words, offset, flags,
1938 quoted? NULL : pwordexp, ifs, ifs_white);
1940 case '[':
1941 (*offset) += 2;
1942 /* Call parse_arith -- 1 is for "brackets" */
1943 return parse_arith (word, word_length, max_length, words, offset, flags,
1946 case '{':
1947 default:
1948 ++(*offset); /* parse_param needs to know if "{" is there */
1949 return parse_param (word, word_length, max_length, words, offset, flags,
1950 pwordexp, ifs, ifs_white, quoted);
1954 static int
1955 internal_function
1956 parse_backtick (char **word, size_t *word_length, size_t *max_length,
1957 const char *words, size_t *offset, int flags,
1958 wordexp_t *pwordexp, const char *ifs, const char *ifs_white)
1960 /* We are poised just after "`" */
1961 int error;
1962 int squoting = 0;
1963 size_t comm_length;
1964 size_t comm_maxlen;
1965 char *comm = w_newword (&comm_length, &comm_maxlen);
1967 for (; words[*offset]; ++(*offset))
1969 switch (words[*offset])
1971 case '`':
1972 /* Go -- give the script to the shell */
1973 error = exec_comm (comm, word, word_length, max_length, flags,
1974 pwordexp, ifs, ifs_white);
1975 free (comm);
1976 return error;
1978 case '\\':
1979 if (squoting)
1981 error = parse_qtd_backslash (&comm, &comm_length, &comm_maxlen,
1982 words, offset);
1984 if (error)
1986 free (comm);
1987 return error;
1990 break;
1993 ++(*offset);
1994 error = parse_backslash (&comm, &comm_length, &comm_maxlen, words,
1995 offset);
1997 if (error)
1999 free (comm);
2000 return error;
2003 break;
2005 case '\'':
2006 squoting = 1 - squoting;
2007 default:
2008 comm = w_addchar (comm, &comm_length, &comm_maxlen, words[*offset]);
2009 if (comm == NULL)
2010 return WRDE_NOSPACE;
2014 /* Premature end */
2015 free (comm);
2016 return WRDE_SYNTAX;
2019 static int
2020 internal_function
2021 parse_dquote (char **word, size_t *word_length, size_t *max_length,
2022 const char *words, size_t *offset, int flags,
2023 wordexp_t *pwordexp, const char * ifs, const char * ifs_white)
2025 /* We are poised just after a double-quote */
2026 int error;
2028 for (; words[*offset]; ++(*offset))
2030 switch (words[*offset])
2032 case '"':
2033 return 0;
2035 case '$':
2036 error = parse_dollars (word, word_length, max_length, words, offset,
2037 flags, pwordexp, ifs, ifs_white, 1);
2038 /* The ``1'' here is to tell parse_dollars not to
2039 * split the fields. It may need to, however ("$@").
2041 if (error)
2042 return error;
2044 break;
2046 case '`':
2047 if (flags & WRDE_NOCMD)
2048 return WRDE_CMDSUB;
2050 ++(*offset);
2051 error = parse_backtick (word, word_length, max_length, words,
2052 offset, flags, NULL, NULL, NULL);
2053 /* The first NULL here is to tell parse_backtick not to
2054 * split the fields.
2056 if (error)
2057 return error;
2059 break;
2061 case '\\':
2062 error = parse_qtd_backslash (word, word_length, max_length, words,
2063 offset);
2065 if (error)
2066 return error;
2068 break;
2070 default:
2071 *word = w_addchar (*word, word_length, max_length, words[*offset]);
2072 if (*word == NULL)
2073 return WRDE_NOSPACE;
2077 /* Unterminated string */
2078 return WRDE_SYNTAX;
2082 * wordfree() is to be called after pwordexp is finished with.
2085 void
2086 wordfree (wordexp_t *pwordexp)
2089 /* wordexp can set pwordexp to NULL */
2090 if (pwordexp && pwordexp->we_wordv)
2092 char **wordv = pwordexp->we_wordv;
2094 for (wordv += pwordexp->we_offs; *wordv; ++wordv)
2095 free (*wordv);
2097 free (pwordexp->we_wordv);
2098 pwordexp->we_wordv = NULL;
2103 * wordexp()
2107 wordexp (const char *words, wordexp_t *pwordexp, int flags)
2109 size_t wordv_offset;
2110 size_t words_offset;
2111 size_t word_length;
2112 size_t max_length;
2113 char *word = w_newword (&word_length, &max_length);
2114 int error;
2115 char *ifs;
2116 char ifs_white[4];
2117 char **old_wordv = pwordexp->we_wordv;
2118 size_t old_wordc = (flags & WRDE_REUSE) ? pwordexp->we_wordc : 0;
2120 if (flags & WRDE_REUSE)
2122 /* Minimal implementation of WRDE_REUSE for now */
2123 wordfree (pwordexp);
2124 old_wordv = NULL;
2127 if (flags & WRDE_DOOFFS)
2129 pwordexp->we_wordv = calloc (1 + pwordexp->we_offs, sizeof (char *));
2130 if (pwordexp->we_wordv == NULL)
2132 error = WRDE_NOSPACE;
2133 goto do_error;
2136 else
2138 pwordexp->we_wordv = calloc (1, sizeof (char *));
2139 if (pwordexp->we_wordv == NULL)
2141 error = WRDE_NOSPACE;
2142 goto do_error;
2145 pwordexp->we_offs = 0;
2148 if ((flags & WRDE_APPEND) == 0)
2149 pwordexp->we_wordc = 0;
2151 wordv_offset = pwordexp->we_offs + pwordexp->we_wordc;
2153 /* Find out what the field separators are.
2154 * There are two types: whitespace and non-whitespace.
2156 ifs = getenv ("IFS");
2158 if (!ifs)
2159 /* IFS unset - use <space><tab><newline>. */
2160 ifs = strcpy (ifs_white, " \t\n");
2161 else
2163 char *ifsch = ifs;
2164 char *whch = ifs_white;
2166 /* Start off with no whitespace IFS characters */
2167 ifs_white[0] = '\0';
2169 while (*ifsch != '\0')
2171 if ((*ifsch == ' ') || (*ifsch == '\t') || (*ifsch == '\n'))
2173 /* Whitespace IFS. See first whether it is already in our
2174 collection. */
2175 char *runp = ifs_white;
2177 while (runp < whch && *runp != '\0' && *runp != *ifsch)
2178 ++runp;
2180 if (runp == whch)
2181 *whch++ = *ifsch;
2184 ++ifsch;
2186 *whch = '\0';
2189 for (words_offset = 0 ; words[words_offset] ; ++words_offset)
2190 switch (words[words_offset])
2192 case '\\':
2193 error = parse_backslash (&word, &word_length, &max_length, words,
2194 &words_offset);
2196 if (error)
2197 goto do_error;
2199 break;
2201 case '$':
2202 error = parse_dollars (&word, &word_length, &max_length, words,
2203 &words_offset, flags, pwordexp, ifs, ifs_white,
2206 if (error)
2207 goto do_error;
2209 break;
2211 case '`':
2212 if (flags & WRDE_NOCMD)
2214 error = WRDE_CMDSUB;
2215 goto do_error;
2218 ++words_offset;
2219 error = parse_backtick (&word, &word_length, &max_length, words,
2220 &words_offset, flags, pwordexp, ifs,
2221 ifs_white);
2223 if (error)
2224 goto do_error;
2226 break;
2228 case '"':
2229 ++words_offset;
2230 error = parse_dquote (&word, &word_length, &max_length, words,
2231 &words_offset, flags, pwordexp, ifs, ifs_white);
2233 if (error)
2234 goto do_error;
2236 break;
2238 case '\'':
2239 ++words_offset;
2240 error = parse_squote (&word, &word_length, &max_length, words,
2241 &words_offset);
2243 if (error)
2244 goto do_error;
2246 break;
2248 case '~':
2249 error = parse_tilde (&word, &word_length, &max_length, words,
2250 &words_offset, pwordexp->we_wordc);
2252 if (error)
2253 goto do_error;
2255 break;
2257 case '*':
2258 case '[':
2259 case '?':
2260 error = parse_glob (&word, &word_length, &max_length, words,
2261 &words_offset, flags, pwordexp, ifs, ifs_white);
2263 if (error)
2264 goto do_error;
2266 break;
2268 default:
2269 /* Is it a word separator? */
2270 if (strchr (" \t", words[words_offset]) == NULL)
2272 char ch = words[words_offset];
2274 /* Not a word separator -- but is it a valid word char? */
2275 if (strchr ("\n|&;<>(){}", ch))
2277 /* Fail */
2278 error = WRDE_BADCHAR;
2279 goto do_error;
2282 /* "Ordinary" character -- add it to word */
2283 word = w_addchar (word, &word_length, &max_length,
2284 ch);
2285 if (word == NULL)
2287 error = WRDE_NOSPACE;
2288 goto do_error;
2291 break;
2294 /* If a word has been delimited, add it to the list. */
2295 if (word != NULL)
2297 error = w_addword (pwordexp, word);
2298 if (error)
2299 goto do_error;
2302 word = w_newword (&word_length, &max_length);
2305 /* End of string */
2307 /* There was a word separator at the end */
2308 if (word == NULL) /* i.e. w_newword */
2309 return 0;
2311 /* There was no field separator at the end */
2312 return w_addword (pwordexp, word);
2314 do_error:
2315 /* Error:
2316 * free memory used (unless error is WRDE_NOSPACE), and
2317 * set we_wordc and wd_wordv back to what they were.
2320 if (word != NULL)
2321 free (word);
2323 if (error == WRDE_NOSPACE)
2324 return WRDE_NOSPACE;
2326 wordfree (pwordexp);
2327 pwordexp->we_wordv = old_wordv;
2328 pwordexp->we_wordc = old_wordc;
2329 return error;