2005-12-13 Ulrich Drepper <drepper@redhat.com>
[platform/upstream/linaro-glibc.git] / sysdeps / generic / wordexp.c
1 /* POSIX.2 wordexp implementation.
2    Copyright (C) 1997-2002, 2003, 2005 Free Software Foundation, Inc.
3    This file is part of the GNU C Library.
4    Contributed by Tim Waugh <tim@cyberelk.demon.co.uk>.
5
6    The GNU C Library is free software; you can redistribute it and/or
7    modify it under the terms of the GNU Lesser General Public
8    License as published by the Free Software Foundation; either
9    version 2.1 of the License, or (at your option) any later version.
10
11    The GNU C Library is distributed in the hope that it will be useful,
12    but WITHOUT ANY WARRANTY; without even the implied warranty of
13    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14    Lesser General Public License for more details.
15
16    You should have received a copy of the GNU Lesser General Public
17    License along with the GNU C Library; if not, write to the Free
18    Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
19    02111-1307 USA.  */
20
21 #include <alloca.h>
22 #include <ctype.h>
23 #include <errno.h>
24 #include <fcntl.h>
25 #include <fnmatch.h>
26 #include <glob.h>
27 #include <libintl.h>
28 #include <paths.h>
29 #include <pwd.h>
30 #include <signal.h>
31 #include <stdio.h>
32 #include <stdlib.h>
33 #include <string.h>
34 #include <sys/param.h>
35 #include <sys/stat.h>
36 #include <sys/time.h>
37 #include <sys/types.h>
38 #include <sys/types.h>
39 #include <sys/wait.h>
40 #include <unistd.h>
41 #ifdef USE_IN_LIBIO
42 # include <wchar.h>
43 #endif
44 #include <wordexp.h>
45
46 #include <bits/libc-lock.h>
47 #include <stdio-common/_itoa.h>
48
49 /* Undefine the following line for the production version.  */
50 /* #define NDEBUG 1 */
51 #include <assert.h>
52
53 /* Get some device information.  */
54 #include <device-nrs.h>
55
56 /*
57  * This is a recursive-descent-style word expansion routine.
58  */
59
60 /* These variables are defined and initialized in the startup code.  */
61 extern int __libc_argc attribute_hidden;
62 extern char **__libc_argv attribute_hidden;
63
64 /* Some forward declarations */
65 static int parse_dollars (char **word, size_t *word_length, size_t *max_length,
66                           const char *words, size_t *offset, int flags,
67                           wordexp_t *pwordexp, const char *ifs,
68                           const char *ifs_white, int quoted)
69      internal_function;
70 static int parse_backtick (char **word, size_t *word_length,
71                            size_t *max_length, const char *words,
72                            size_t *offset, int flags, wordexp_t *pwordexp,
73                            const char *ifs, const char *ifs_white)
74      internal_function;
75 static int parse_dquote (char **word, size_t *word_length, size_t *max_length,
76                          const char *words, size_t *offset, int flags,
77                          wordexp_t *pwordexp, const char *ifs,
78                          const char *ifs_white)
79      internal_function;
80 static int eval_expr (char *expr, long int *result) internal_function;
81
82 /* The w_*() functions manipulate word lists. */
83
84 #define W_CHUNK (100)
85
86 /* Result of w_newword will be ignored if it's the last word. */
87 static inline char *
88 w_newword (size_t *actlen, size_t *maxlen)
89 {
90   *actlen = *maxlen = 0;
91   return NULL;
92 }
93
94 static char *
95 w_addchar (char *buffer, size_t *actlen, size_t *maxlen, char ch)
96      /* (lengths exclude trailing zero) */
97 {
98   /* Add a character to the buffer, allocating room for it if needed.  */
99
100   if (*actlen == *maxlen)
101     {
102       char *old_buffer = buffer;
103       assert (buffer == NULL || *maxlen != 0);
104       *maxlen += W_CHUNK;
105       buffer = (char *) realloc (buffer, 1 + *maxlen);
106
107       if (buffer == NULL)
108         free (old_buffer);
109     }
110
111   if (buffer != NULL)
112     {
113       buffer[*actlen] = ch;
114       buffer[++(*actlen)] = '\0';
115     }
116
117   return buffer;
118 }
119
120 static char *
121 internal_function
122 w_addmem (char *buffer, size_t *actlen, size_t *maxlen, const char *str,
123           size_t len)
124 {
125   /* Add a string to the buffer, allocating room for it if needed.
126    */
127   if (*actlen + len > *maxlen)
128     {
129       char *old_buffer = buffer;
130       assert (buffer == NULL || *maxlen != 0);
131       *maxlen += MAX (2 * len, W_CHUNK);
132       buffer = realloc (old_buffer, 1 + *maxlen);
133
134       if (buffer == NULL)
135         free (old_buffer);
136     }
137
138   if (buffer != NULL)
139     {
140       *((char *) __mempcpy (&buffer[*actlen], str, len)) = '\0';
141       *actlen += len;
142     }
143
144   return buffer;
145 }
146
147 static char *
148 internal_function
149 w_addstr (char *buffer, size_t *actlen, size_t *maxlen, const char *str)
150      /* (lengths exclude trailing zero) */
151 {
152   /* Add a string to the buffer, allocating room for it if needed.
153    */
154   size_t len;
155
156   assert (str != NULL); /* w_addstr only called from this file */
157   len = strlen (str);
158
159   return w_addmem (buffer, actlen, maxlen, str, len);
160 }
161
162 static int
163 internal_function
164 w_addword (wordexp_t *pwordexp, char *word)
165 {
166   /* Add a word to the wordlist */
167   size_t num_p;
168   char **new_wordv;
169
170   /* Internally, NULL acts like "".  Convert NULLs to "" before
171    * the caller sees them.
172    */
173   if (word == NULL)
174     {
175       word = __strdup ("");
176       if (word == NULL)
177         goto no_space;
178     }
179
180   num_p = 2 + pwordexp->we_wordc + pwordexp->we_offs;
181   new_wordv = realloc (pwordexp->we_wordv, sizeof (char *) * num_p);
182   if (new_wordv != NULL)
183     {
184       pwordexp->we_wordv = new_wordv;
185       pwordexp->we_wordv[pwordexp->we_offs + pwordexp->we_wordc++] = word;
186       pwordexp->we_wordv[pwordexp->we_offs + pwordexp->we_wordc] = NULL;
187       return 0;
188     }
189
190 no_space:
191   return WRDE_NOSPACE;
192 }
193
194 /* The parse_*() functions should leave *offset being the offset in 'words'
195  * to the last character processed.
196  */
197
198 static int
199 internal_function
200 parse_backslash (char **word, size_t *word_length, size_t *max_length,
201                  const char *words, size_t *offset)
202 {
203   /* We are poised _at_ a backslash, not in quotes */
204
205   switch (words[1 + *offset])
206     {
207     case 0:
208       /* Backslash is last character of input words */
209       return WRDE_SYNTAX;
210
211     case '\n':
212       ++(*offset);
213       break;
214
215     default:
216       *word = w_addchar (*word, word_length, max_length, words[1 + *offset]);
217       if (*word == NULL)
218         return WRDE_NOSPACE;
219
220       ++(*offset);
221       break;
222     }
223
224   return 0;
225 }
226
227 static int
228 internal_function
229 parse_qtd_backslash (char **word, size_t *word_length, size_t *max_length,
230                      const char *words, size_t *offset)
231 {
232   /* We are poised _at_ a backslash, inside quotes */
233
234   switch (words[1 + *offset])
235     {
236     case 0:
237       /* Backslash is last character of input words */
238       return WRDE_SYNTAX;
239
240     case '\n':
241       ++(*offset);
242       break;
243
244     case '$':
245     case '`':
246     case '"':
247     case '\\':
248       *word = w_addchar (*word, word_length, max_length, words[1 + *offset]);
249       if (*word == NULL)
250         return WRDE_NOSPACE;
251
252       ++(*offset);
253       break;
254
255     default:
256       *word = w_addchar (*word, word_length, max_length, words[*offset]);
257       if (*word != NULL)
258         *word = w_addchar (*word, word_length, max_length, words[1 + *offset]);
259
260       if (*word == NULL)
261         return WRDE_NOSPACE;
262
263       ++(*offset);
264       break;
265     }
266
267   return 0;
268 }
269
270 static int
271 internal_function
272 parse_tilde (char **word, size_t *word_length, size_t *max_length,
273              const char *words, size_t *offset, size_t wordc)
274 {
275   /* We are poised _at_ a tilde */
276   size_t i;
277
278   if (*word_length != 0)
279     {
280       if (!((*word)[*word_length - 1] == '=' && wordc == 0))
281         {
282           if (!((*word)[*word_length - 1] == ':'
283                 && strchr (*word, '=') && wordc == 0))
284             {
285               *word = w_addchar (*word, word_length, max_length, '~');
286               return *word ? 0 : WRDE_NOSPACE;
287             }
288         }
289     }
290
291   for (i = 1 + *offset; words[i]; i++)
292     {
293       if (words[i] == ':' || words[i] == '/' || words[i] == ' ' ||
294           words[i] == '\t' || words[i] == 0 )
295         break;
296
297       if (words[i] == '\\')
298         {
299           *word = w_addchar (*word, word_length, max_length, '~');
300           return *word ? 0 : WRDE_NOSPACE;
301         }
302     }
303
304   if (i == 1 + *offset)
305     {
306       /* Tilde appears on its own */
307       uid_t uid;
308       struct passwd pwd, *tpwd;
309       int buflen = 1000;
310       char* home;
311       char* buffer;
312       int result;
313
314       /* POSIX.2 says ~ expands to $HOME and if HOME is unset the
315          results are unspecified.  We do a lookup on the uid if
316          HOME is unset. */
317
318       home = getenv ("HOME");
319       if (home != NULL)
320         {
321           *word = w_addstr (*word, word_length, max_length, home);
322           if (*word == NULL)
323             return WRDE_NOSPACE;
324         }
325       else
326         {
327           uid = __getuid ();
328           buffer = __alloca (buflen);
329
330           while ((result = __getpwuid_r (uid, &pwd, buffer, buflen, &tpwd)) != 0
331                  && errno == ERANGE)
332             buffer = extend_alloca (buffer, buflen, buflen + 1000);
333
334           if (result == 0 && tpwd != NULL && pwd.pw_dir != NULL)
335             {
336               *word = w_addstr (*word, word_length, max_length, pwd.pw_dir);
337               if (*word == NULL)
338                 return WRDE_NOSPACE;
339             }
340           else
341             {
342               *word = w_addchar (*word, word_length, max_length, '~');
343               if (*word == NULL)
344                 return WRDE_NOSPACE;
345             }
346         }
347     }
348   else
349     {
350       /* Look up user name in database to get home directory */
351       char *user = strndupa (&words[1 + *offset], i - (1 + *offset));
352       struct passwd pwd, *tpwd;
353       int buflen = 1000;
354       char* buffer = __alloca (buflen);
355       int result;
356
357       while ((result = __getpwnam_r (user, &pwd, buffer, buflen, &tpwd)) != 0
358              && errno == ERANGE)
359         buffer = extend_alloca (buffer, buflen, buflen + 1000);
360
361       if (result == 0 && tpwd != NULL && pwd.pw_dir)
362         *word = w_addstr (*word, word_length, max_length, pwd.pw_dir);
363       else
364         {
365           /* (invalid login name) */
366           *word = w_addchar (*word, word_length, max_length, '~');
367           if (*word != NULL)
368             *word = w_addstr (*word, word_length, max_length, user);
369         }
370
371       *offset = i - 1;
372     }
373   return *word ? 0 : WRDE_NOSPACE;
374 }
375
376
377 static int
378 internal_function
379 do_parse_glob (const char *glob_word, char **word, size_t *word_length,
380                size_t *max_length, wordexp_t *pwordexp, const char *ifs,
381                const char *ifs_white)
382 {
383   int error;
384   unsigned int match;
385   glob_t globbuf;
386
387   error = glob (glob_word, GLOB_NOCHECK, NULL, &globbuf);
388
389   if (error != 0)
390     {
391       /* We can only run into memory problems.  */
392       assert (error == GLOB_NOSPACE);
393       return WRDE_NOSPACE;
394     }
395
396   if (ifs && !*ifs)
397     {
398       /* No field splitting allowed. */
399       assert (globbuf.gl_pathv[0] != NULL);
400       *word = w_addstr (*word, word_length, max_length, globbuf.gl_pathv[0]);
401       for (match = 1; match < globbuf.gl_pathc && *word != NULL; ++match)
402         {
403           *word = w_addchar (*word, word_length, max_length, ' ');
404           if (*word != NULL)
405             *word = w_addstr (*word, word_length, max_length,
406                               globbuf.gl_pathv[match]);
407         }
408
409       globfree (&globbuf);
410       return *word ? 0 : WRDE_NOSPACE;
411     }
412
413   assert (ifs == NULL || *ifs != '\0');
414   if (*word != NULL)
415     {
416       free (*word);
417       *word = w_newword (word_length, max_length);
418     }
419
420   for (match = 0; match < globbuf.gl_pathc; ++match)
421     {
422       char *matching_word = __strdup (globbuf.gl_pathv[match]);
423       if (matching_word == NULL || w_addword (pwordexp, matching_word))
424         {
425           globfree (&globbuf);
426           return WRDE_NOSPACE;
427         }
428     }
429
430   globfree (&globbuf);
431   return 0;
432 }
433
434 static int
435 internal_function
436 parse_glob (char **word, size_t *word_length, size_t *max_length,
437             const char *words, size_t *offset, int flags,
438             wordexp_t *pwordexp, const char *ifs, const char *ifs_white)
439 {
440   /* We are poised just after a '*', a '[' or a '?'. */
441   int error = WRDE_NOSPACE;
442   int quoted = 0; /* 1 if singly-quoted, 2 if doubly */
443   size_t i;
444   wordexp_t glob_list; /* List of words to glob */
445
446   glob_list.we_wordc = 0;
447   glob_list.we_wordv = NULL;
448   glob_list.we_offs = 0;
449   for (; words[*offset] != '\0'; ++*offset)
450     {
451       if ((ifs && strchr (ifs, words[*offset])) ||
452           (!ifs && strchr (" \t\n", words[*offset])))
453         /* Reached IFS */
454         break;
455
456       /* Sort out quoting */
457       if (words[*offset] == '\'')
458         {
459           if (quoted == 0)
460             {
461               quoted = 1;
462               continue;
463             }
464           else if (quoted == 1)
465             {
466               quoted = 0;
467               continue;
468             }
469         }
470       else if (words[*offset] == '"')
471         {
472           if (quoted == 0)
473             {
474               quoted = 2;
475               continue;
476             }
477           else if (quoted == 2)
478             {
479               quoted = 0;
480               continue;
481             }
482         }
483
484       /* Sort out other special characters */
485       if (quoted != 1 && words[*offset] == '$')
486         {
487           error = parse_dollars (word, word_length, max_length, words,
488                                  offset, flags, &glob_list, ifs, ifs_white,
489                                  quoted == 2);
490           if (error)
491             goto tidy_up;
492
493           continue;
494         }
495       else if (words[*offset] == '\\')
496         {
497           if (quoted)
498             error = parse_qtd_backslash (word, word_length, max_length,
499                                          words, offset);
500           else
501             error = parse_backslash (word, word_length, max_length,
502                                      words, offset);
503
504           if (error)
505             goto tidy_up;
506
507           continue;
508         }
509
510       *word = w_addchar (*word, word_length, max_length, words[*offset]);
511       if (*word == NULL)
512         goto tidy_up;
513     }
514
515   /* Don't forget to re-parse the character we stopped at. */
516   --*offset;
517
518   /* Glob the words */
519   error = w_addword (&glob_list, *word);
520   *word = w_newword (word_length, max_length);
521   for (i = 0; error == 0 && i < glob_list.we_wordc; i++)
522     error = do_parse_glob (glob_list.we_wordv[i], word, word_length,
523                            max_length, pwordexp, ifs, ifs_white);
524
525   /* Now tidy up */
526 tidy_up:
527   wordfree (&glob_list);
528   return error;
529 }
530
531 static int
532 internal_function
533 parse_squote (char **word, size_t *word_length, size_t *max_length,
534               const char *words, size_t *offset)
535 {
536   /* We are poised just after a single quote */
537   for (; words[*offset]; ++(*offset))
538     {
539       if (words[*offset] != '\'')
540         {
541           *word = w_addchar (*word, word_length, max_length, words[*offset]);
542           if (*word == NULL)
543             return WRDE_NOSPACE;
544         }
545       else return 0;
546     }
547
548   /* Unterminated string */
549   return WRDE_SYNTAX;
550 }
551
552 /* Functions to evaluate an arithmetic expression */
553 static int
554 internal_function
555 eval_expr_val (char **expr, long int *result)
556 {
557   char *digit;
558
559   /* Skip white space */
560   for (digit = *expr; digit && *digit && isspace (*digit); ++digit);
561
562   if (*digit == '(')
563     {
564       /* Scan for closing paren */
565       for (++digit; **expr && **expr != ')'; ++(*expr));
566
567       /* Is there one? */
568       if (!**expr)
569         return WRDE_SYNTAX;
570
571       *(*expr)++ = 0;
572
573       if (eval_expr (digit, result))
574         return WRDE_SYNTAX;
575
576       return 0;
577     }
578
579   /* POSIX requires that decimal, octal, and hexadecimal constants are
580      recognized.  Therefore we pass 0 as the third parameter to strtol.  */
581   *result = strtol (digit, expr, 0);
582   if (digit == *expr)
583     return WRDE_SYNTAX;
584
585   return 0;
586 }
587
588 static int
589 internal_function
590 eval_expr_multdiv (char **expr, long int *result)
591 {
592   long int arg;
593
594   /* Read a Value */
595   if (eval_expr_val (expr, result) != 0)
596     return WRDE_SYNTAX;
597
598   while (**expr)
599     {
600       /* Skip white space */
601       for (; *expr && **expr && isspace (**expr); ++(*expr));
602
603       if (**expr == '*')
604         {
605           ++(*expr);
606           if (eval_expr_val (expr, &arg) != 0)
607             return WRDE_SYNTAX;
608
609           *result *= arg;
610         }
611       else if (**expr == '/')
612         {
613           ++(*expr);
614           if (eval_expr_val (expr, &arg) != 0)
615             return WRDE_SYNTAX;
616
617           *result /= arg;
618         }
619       else break;
620     }
621
622   return 0;
623 }
624
625 static int
626 internal_function
627 eval_expr (char *expr, long int *result)
628 {
629   long int arg;
630
631   /* Read a Multdiv */
632   if (eval_expr_multdiv (&expr, result) != 0)
633     return WRDE_SYNTAX;
634
635   while (*expr)
636     {
637       /* Skip white space */
638       for (; expr && *expr && isspace (*expr); ++expr);
639
640       if (*expr == '+')
641         {
642           ++expr;
643           if (eval_expr_multdiv (&expr, &arg) != 0)
644             return WRDE_SYNTAX;
645
646           *result += arg;
647         }
648       else if (*expr == '-')
649         {
650           ++expr;
651           if (eval_expr_multdiv (&expr, &arg) != 0)
652             return WRDE_SYNTAX;
653
654           *result -= arg;
655         }
656       else break;
657     }
658
659   return 0;
660 }
661
662 static int
663 internal_function
664 parse_arith (char **word, size_t *word_length, size_t *max_length,
665              const char *words, size_t *offset, int flags, int bracket)
666 {
667   /* We are poised just after "$((" or "$[" */
668   int error;
669   int paren_depth = 1;
670   size_t expr_length;
671   size_t expr_maxlen;
672   char *expr;
673
674   expr = w_newword (&expr_length, &expr_maxlen);
675   for (; words[*offset]; ++(*offset))
676     {
677       switch (words[*offset])
678         {
679         case '$':
680           error = parse_dollars (&expr, &expr_length, &expr_maxlen,
681                                  words, offset, flags, NULL, NULL, NULL, 1);
682           /* The ``1'' here is to tell parse_dollars not to
683            * split the fields.
684            */
685           if (error)
686             {
687               free (expr);
688               return error;
689             }
690           break;
691
692         case '`':
693           (*offset)++;
694           error = parse_backtick (&expr, &expr_length, &expr_maxlen,
695                                   words, offset, flags, NULL, NULL, NULL);
696           /* The first NULL here is to tell parse_backtick not to
697            * split the fields.
698            */
699           if (error)
700             {
701               free (expr);
702               return error;
703             }
704           break;
705
706         case '\\':
707           error = parse_qtd_backslash (&expr, &expr_length, &expr_maxlen,
708                                        words, offset);
709           if (error)
710             {
711               free (expr);
712               return error;
713             }
714           /* I think that a backslash within an
715            * arithmetic expansion is bound to
716            * cause an error sooner or later anyway though.
717            */
718           break;
719
720         case ')':
721           if (--paren_depth == 0)
722             {
723               char result[21];  /* 21 = ceil(log10(2^64)) + 1 */
724               long int numresult = 0;
725               long long int convertme;
726
727               if (bracket || words[1 + *offset] != ')')
728                 {
729                   free (expr);
730                   return WRDE_SYNTAX;
731                 }
732
733               ++(*offset);
734
735               /* Go - evaluate. */
736               if (*expr && eval_expr (expr, &numresult) != 0)
737                 {
738                   free (expr);
739                   return WRDE_SYNTAX;
740                 }
741
742               if (numresult < 0)
743                 {
744                   convertme = -numresult;
745                   *word = w_addchar (*word, word_length, max_length, '-');
746                   if (!*word)
747                     {
748                       free (expr);
749                       return WRDE_NOSPACE;
750                     }
751                 }
752               else
753                 convertme = numresult;
754
755               result[20] = '\0';
756               *word = w_addstr (*word, word_length, max_length,
757                                 _itoa (convertme, &result[20], 10, 0));
758               free (expr);
759               return *word ? 0 : WRDE_NOSPACE;
760             }
761           expr = w_addchar (expr, &expr_length, &expr_maxlen, words[*offset]);
762           if (expr == NULL)
763             return WRDE_NOSPACE;
764
765           break;
766
767         case ']':
768           if (bracket && paren_depth == 1)
769             {
770               char result[21];  /* 21 = ceil(log10(2^64)) + 1 */
771               long int numresult = 0;
772
773               /* Go - evaluate. */
774               if (*expr && eval_expr (expr, &numresult) != 0)
775                 {
776                   free (expr);
777                   return WRDE_SYNTAX;
778                 }
779
780               result[20] = '\0';
781               *word = w_addstr (*word, word_length, max_length,
782                                 _itoa_word (numresult, &result[20], 10, 0));
783               free (expr);
784               return *word ? 0 : WRDE_NOSPACE;
785             }
786
787           free (expr);
788           return WRDE_SYNTAX;
789
790         case '\n':
791         case ';':
792         case '{':
793         case '}':
794           free (expr);
795           return WRDE_BADCHAR;
796
797         case '(':
798           ++paren_depth;
799         default:
800           expr = w_addchar (expr, &expr_length, &expr_maxlen, words[*offset]);
801           if (expr == NULL)
802             return WRDE_NOSPACE;
803         }
804     }
805
806   /* Premature end */
807   free (expr);
808   return WRDE_SYNTAX;
809 }
810
811 /* Function called by child process in exec_comm() */
812 static inline void
813 internal_function __attribute__ ((always_inline))
814 exec_comm_child (char *comm, int *fildes, int showerr, int noexec)
815 {
816   const char *args[4] = { _PATH_BSHELL, "-c", comm, NULL };
817
818   /* Execute the command, or just check syntax? */
819   if (noexec)
820     args[1] = "-nc";
821
822   /* Redirect output.  */
823   __dup2 (fildes[1], STDOUT_FILENO);
824   __close (fildes[1]);
825
826   /* Redirect stderr to /dev/null if we have to.  */
827   if (showerr == 0)
828     {
829       struct stat64 st;
830       int fd;
831       __close (2);
832       fd = __open (_PATH_DEVNULL, O_WRONLY);
833       if (fd >= 0 && fd != 2)
834         {
835           __dup2 (fd, STDERR_FILENO);
836           __close (fd);
837         }
838       /* Be paranoid.  Check that we actually opened the /dev/null
839          device.  */
840       if (__builtin_expect (__fxstat64 (_STAT_VER, STDERR_FILENO, &st), 0) != 0
841           || __builtin_expect (S_ISCHR (st.st_mode), 1) == 0
842 #if defined DEV_NULL_MAJOR && defined DEV_NULL_MINOR
843           || st.st_rdev != makedev (DEV_NULL_MAJOR, DEV_NULL_MINOR)
844 #endif
845           )
846         /* It's not the /dev/null device.  Stop right here.  The
847            problem is: how do we stop?  We use _exit() with an
848            hopefully unusual exit code.  */
849         _exit (90);
850     }
851
852   /* Make sure the subshell doesn't field-split on our behalf. */
853   __unsetenv ("IFS");
854
855   __close (fildes[0]);
856   __execve (_PATH_BSHELL, (char *const *) args, __environ);
857
858   /* Bad.  What now?  */
859   abort ();
860 }
861
862 /* Function to execute a command and retrieve the results */
863 /* pwordexp contains NULL if field-splitting is forbidden */
864 static int
865 internal_function
866 exec_comm (char *comm, char **word, size_t *word_length, size_t *max_length,
867            int flags, wordexp_t *pwordexp, const char *ifs,
868            const char *ifs_white)
869 {
870   int fildes[2];
871 #define bufsize 128
872   int buflen;
873   int i;
874   int status = 0;
875   size_t maxnewlines = 0;
876   char buffer[bufsize];
877   pid_t pid;
878   int noexec = 0;
879
880   /* Don't fork() unless necessary */
881   if (!comm || !*comm)
882     return 0;
883
884   if (__pipe (fildes))
885     /* Bad */
886     return WRDE_NOSPACE;
887
888  again:
889   if ((pid = __fork ()) < 0)
890     {
891       /* Bad */
892       if (fildes[0] != -1)
893         __close (fildes[0]);
894       if (fildes[1] != -1)
895         __close (fildes[1]);
896       return WRDE_NOSPACE;
897     }
898
899   if (pid == 0)
900     exec_comm_child (comm, fildes, noexec ? 0 : flags & WRDE_SHOWERR, noexec);
901
902   /* Parent */
903
904   /* If we are just testing the syntax, only wait.  */
905   if (noexec)
906     return (TEMP_FAILURE_RETRY (__waitpid (pid, &status, 0)) == pid
907             && status != 0) ? WRDE_SYNTAX : 0;
908
909   __close (fildes[1]);
910   fildes[1] = -1;
911
912   if (!pwordexp)
913     /* Quoted - no field splitting */
914     {
915       while (1)
916         {
917           if ((buflen = TEMP_FAILURE_RETRY (__read (fildes[0], buffer,
918                                                     bufsize))) < 1)
919             {
920               if (TEMP_FAILURE_RETRY (__waitpid (pid, &status, WNOHANG)) == 0)
921                 continue;
922               if ((buflen = TEMP_FAILURE_RETRY (__read (fildes[0], buffer,
923                                                         bufsize))) < 1)
924                 break;
925             }
926
927           maxnewlines += buflen;
928
929           *word = w_addmem (*word, word_length, max_length, buffer, buflen);
930           if (*word == NULL)
931             goto no_space;
932         }
933     }
934   else
935     /* Not quoted - split fields */
936     {
937       int copying = 0;
938       /* 'copying' is:
939        *  0 when searching for first character in a field not IFS white space
940        *  1 when copying the text of a field
941        *  2 when searching for possible non-whitespace IFS
942        *  3 when searching for non-newline after copying field
943        */
944
945       while (1)
946         {
947           if ((buflen = TEMP_FAILURE_RETRY (__read (fildes[0], buffer,
948                                                     bufsize))) < 1)
949             {
950               if (TEMP_FAILURE_RETRY (__waitpid (pid, &status, WNOHANG)) == 0)
951                 continue;
952               if ((buflen = TEMP_FAILURE_RETRY (__read (fildes[0], buffer,
953                                                         bufsize))) < 1)
954                 break;
955             }
956
957           for (i = 0; i < buflen; ++i)
958             {
959               if (strchr (ifs, buffer[i]) != NULL)
960                 {
961                   /* Current character is IFS */
962                   if (strchr (ifs_white, buffer[i]) == NULL)
963                     {
964                       /* Current character is IFS but not whitespace */
965                       if (copying == 2)
966                         {
967                           /*            current character
968                            *                   |
969                            *                   V
970                            * eg: text<space><comma><space>moretext
971                            *
972                            * So, strip whitespace IFS (like at the start)
973                            */
974                           copying = 0;
975                           continue;
976                         }
977
978                       copying = 0;
979                       /* fall through and delimit field.. */
980                     }
981                   else
982                     {
983                       if (buffer[i] == '\n')
984                         {
985                           /* Current character is (IFS) newline */
986
987                           /* If copying a field, this is the end of it,
988                              but maybe all that's left is trailing newlines.
989                              So start searching for a non-newline. */
990                           if (copying == 1)
991                             copying = 3;
992
993                           continue;
994                         }
995                       else
996                         {
997                           /* Current character is IFS white space, but
998                              not a newline */
999
1000                           /* If not either copying a field or searching
1001                              for non-newline after a field, ignore it */
1002                           if (copying != 1 && copying != 3)
1003                             continue;
1004
1005                           /* End of field (search for non-ws IFS afterwards) */
1006                           copying = 2;
1007                         }
1008                     }
1009
1010                   /* First IFS white space (non-newline), or IFS non-whitespace.
1011                    * Delimit the field.  Nulls are converted by w_addword. */
1012                   if (w_addword (pwordexp, *word) == WRDE_NOSPACE)
1013                     goto no_space;
1014
1015                   *word = w_newword (word_length, max_length);
1016
1017                   maxnewlines = 0;
1018                   /* fall back round the loop.. */
1019                 }
1020               else
1021                 {
1022                   /* Not IFS character */
1023
1024                   if (copying == 3)
1025                     {
1026                       /* Nothing but (IFS) newlines since the last field,
1027                          so delimit it here before starting new word */
1028                       if (w_addword (pwordexp, *word) == WRDE_NOSPACE)
1029                         goto no_space;
1030
1031                       *word = w_newword (word_length, max_length);
1032                     }
1033
1034                   copying = 1;
1035
1036                   if (buffer[i] == '\n') /* happens if newline not in IFS */
1037                     maxnewlines++;
1038                   else
1039                     maxnewlines = 0;
1040
1041                   *word = w_addchar (*word, word_length, max_length,
1042                                      buffer[i]);
1043                   if (*word == NULL)
1044                     goto no_space;
1045                 }
1046             }
1047         }
1048     }
1049
1050   /* Chop off trailing newlines (required by POSIX.2)  */
1051   /* Ensure we don't go back further than the beginning of the
1052      substitution (i.e. remove maxnewlines bytes at most) */
1053   while (maxnewlines-- != 0 &&
1054          *word_length > 0 && (*word)[*word_length - 1] == '\n')
1055     {
1056       (*word)[--*word_length] = '\0';
1057
1058       /* If the last word was entirely newlines, turn it into a new word
1059        * which can be ignored if there's nothing following it. */
1060       if (*word_length == 0)
1061         {
1062           free (*word);
1063           *word = w_newword (word_length, max_length);
1064           break;
1065         }
1066     }
1067
1068   __close (fildes[0]);
1069   fildes[0] = -1;
1070
1071   /* Check for syntax error (re-execute but with "-n" flag) */
1072   if (buflen < 1 && status != 0)
1073     {
1074       noexec = 1;
1075       goto again;
1076     }
1077
1078   return 0;
1079
1080 no_space:
1081   __kill (pid, SIGKILL);
1082   TEMP_FAILURE_RETRY (__waitpid (pid, NULL, 0));
1083   __close (fildes[0]);
1084   return WRDE_NOSPACE;
1085 }
1086
1087 static int
1088 internal_function
1089 parse_comm (char **word, size_t *word_length, size_t *max_length,
1090             const char *words, size_t *offset, int flags, wordexp_t *pwordexp,
1091             const char *ifs, const char *ifs_white)
1092 {
1093   /* We are poised just after "$(" */
1094   int paren_depth = 1;
1095   int error = 0;
1096   int quoted = 0; /* 1 for singly-quoted, 2 for doubly-quoted */
1097   size_t comm_length;
1098   size_t comm_maxlen;
1099   char *comm = w_newword (&comm_length, &comm_maxlen);
1100
1101   for (; words[*offset]; ++(*offset))
1102     {
1103       switch (words[*offset])
1104         {
1105         case '\'':
1106           if (quoted == 0)
1107             quoted = 1;
1108           else if (quoted == 1)
1109             quoted = 0;
1110
1111           break;
1112
1113         case '"':
1114           if (quoted == 0)
1115             quoted = 2;
1116           else if (quoted == 2)
1117             quoted = 0;
1118
1119           break;
1120
1121         case ')':
1122           if (!quoted && --paren_depth == 0)
1123             {
1124               /* Go -- give script to the shell */
1125               if (comm)
1126                 {
1127 #ifdef __libc_ptf_call
1128                   /* We do not want the exec_comm call to be cut short
1129                      by a thread cancellation since cleanup is very
1130                      ugly.  Therefore disable cancellation for
1131                      now.  */
1132                   // XXX Ideally we do want the thread being cancelable.
1133                   // XXX If demand is there we'll change it.
1134                   int state = PTHREAD_CANCEL_ENABLE;
1135                   __libc_ptf_call (pthread_setcancelstate,
1136                                    (PTHREAD_CANCEL_DISABLE, &state), 0);
1137 #endif
1138
1139                   error = exec_comm (comm, word, word_length, max_length,
1140                                      flags, pwordexp, ifs, ifs_white);
1141
1142 #ifdef __libc_ptf_call
1143                   __libc_ptf_call (pthread_setcancelstate, (state, NULL), 0);
1144 #endif
1145
1146                   free (comm);
1147                 }
1148
1149               return error;
1150             }
1151
1152           /* This is just part of the script */
1153           break;
1154
1155         case '(':
1156           if (!quoted)
1157             ++paren_depth;
1158         }
1159
1160       comm = w_addchar (comm, &comm_length, &comm_maxlen, words[*offset]);
1161       if (comm == NULL)
1162         return WRDE_NOSPACE;
1163     }
1164
1165   /* Premature end */
1166   if (comm)
1167     free (comm);
1168
1169   return WRDE_SYNTAX;
1170 }
1171
1172 static int
1173 internal_function
1174 parse_param (char **word, size_t *word_length, size_t *max_length,
1175              const char *words, size_t *offset, int flags, wordexp_t *pwordexp,
1176              const char *ifs, const char *ifs_white, int quoted)
1177 {
1178   /* We are poised just after "$" */
1179   enum action
1180   {
1181     ACT_NONE,
1182     ACT_RP_SHORT_LEFT = '#',
1183     ACT_RP_LONG_LEFT = 'L',
1184     ACT_RP_SHORT_RIGHT = '%',
1185     ACT_RP_LONG_RIGHT = 'R',
1186     ACT_NULL_ERROR = '?',
1187     ACT_NULL_SUBST = '-',
1188     ACT_NONNULL_SUBST = '+',
1189     ACT_NULL_ASSIGN = '='
1190   };
1191   size_t env_length;
1192   size_t env_maxlen;
1193   size_t pat_length;
1194   size_t pat_maxlen;
1195   size_t start = *offset;
1196   char *env;
1197   char *pattern;
1198   char *value = NULL;
1199   enum action action = ACT_NONE;
1200   int depth = 0;
1201   int colon_seen = 0;
1202   int seen_hash = 0;
1203   int free_value = 0;
1204   int pattern_is_quoted = 0; /* 1 for singly-quoted, 2 for doubly-quoted */
1205   int error;
1206   int special = 0;
1207   char buffer[21];
1208   int brace = words[*offset] == '{';
1209
1210   env = w_newword (&env_length, &env_maxlen);
1211   pattern = w_newword (&pat_length, &pat_maxlen);
1212
1213   if (brace)
1214     ++*offset;
1215
1216   /* First collect the parameter name. */
1217
1218   if (words[*offset] == '#')
1219     {
1220       seen_hash = 1;
1221       if (!brace)
1222         goto envsubst;
1223       ++*offset;
1224     }
1225
1226   if (isalpha (words[*offset]) || words[*offset] == '_')
1227     {
1228       /* Normal parameter name. */
1229       do
1230         {
1231           env = w_addchar (env, &env_length, &env_maxlen,
1232                            words[*offset]);
1233           if (env == NULL)
1234             goto no_space;
1235         }
1236       while (isalnum (words[++*offset]) || words[*offset] == '_');
1237     }
1238   else if (isdigit (words[*offset]))
1239     {
1240       /* Numeric parameter name. */
1241       special = 1;
1242       do
1243         {
1244           env = w_addchar (env, &env_length, &env_maxlen,
1245                            words[*offset]);
1246           if (env == NULL)
1247             goto no_space;
1248           if (!brace)
1249             goto envsubst;
1250         }
1251       while (isdigit(words[++*offset]));
1252     }
1253   else if (strchr ("*@$", words[*offset]) != NULL)
1254     {
1255       /* Special parameter. */
1256       special = 1;
1257       env = w_addchar (env, &env_length, &env_maxlen,
1258                        words[*offset]);
1259       if (env == NULL)
1260         goto no_space;
1261       ++*offset;
1262     }
1263   else
1264     {
1265       if (brace)
1266         goto syntax;
1267     }
1268
1269   if (brace)
1270     {
1271       /* Check for special action to be applied to the value. */
1272       switch (words[*offset])
1273         {
1274         case '}':
1275           /* Evaluate. */
1276           goto envsubst;
1277
1278         case '#':
1279           action = ACT_RP_SHORT_LEFT;
1280           if (words[1 + *offset] == '#')
1281             {
1282               ++*offset;
1283               action = ACT_RP_LONG_LEFT;
1284             }
1285           break;
1286
1287         case '%':
1288           action = ACT_RP_SHORT_RIGHT;
1289           if (words[1 + *offset] == '%')
1290             {
1291               ++*offset;
1292               action = ACT_RP_LONG_RIGHT;
1293             }
1294           break;
1295
1296         case ':':
1297           if (strchr ("-=?+", words[1 + *offset]) == NULL)
1298             goto syntax;
1299
1300           colon_seen = 1;
1301           action = words[++*offset];
1302           break;
1303
1304         case '-':
1305         case '=':
1306         case '?':
1307         case '+':
1308           action = words[*offset];
1309           break;
1310
1311         default:
1312           goto syntax;
1313         }
1314
1315       /* Now collect the pattern, but don't expand it yet. */
1316       ++*offset;
1317       for (; words[*offset]; ++(*offset))
1318         {
1319           switch (words[*offset])
1320             {
1321             case '{':
1322               if (!pattern_is_quoted)
1323                 ++depth;
1324               break;
1325
1326             case '}':
1327               if (!pattern_is_quoted)
1328                 {
1329                   if (depth == 0)
1330                     goto envsubst;
1331                   --depth;
1332                 }
1333               break;
1334
1335             case '\\':
1336               if (pattern_is_quoted)
1337                 /* Quoted; treat as normal character. */
1338                 break;
1339
1340               /* Otherwise, it's an escape: next character is literal. */
1341               if (words[++*offset] == '\0')
1342                 goto syntax;
1343
1344               pattern = w_addchar (pattern, &pat_length, &pat_maxlen, '\\');
1345               if (pattern == NULL)
1346                 goto no_space;
1347
1348               break;
1349
1350             case '\'':
1351               if (pattern_is_quoted == 0)
1352                 pattern_is_quoted = 1;
1353               else if (pattern_is_quoted == 1)
1354                 pattern_is_quoted = 0;
1355
1356               break;
1357
1358             case '"':
1359               if (pattern_is_quoted == 0)
1360                 pattern_is_quoted = 2;
1361               else if (pattern_is_quoted == 2)
1362                 pattern_is_quoted = 0;
1363
1364               break;
1365             }
1366
1367           pattern = w_addchar (pattern, &pat_length, &pat_maxlen,
1368                                words[*offset]);
1369           if (pattern == NULL)
1370             goto no_space;
1371         }
1372     }
1373
1374   /* End of input string -- remember to reparse the character that we
1375    * stopped at.  */
1376   --(*offset);
1377
1378 envsubst:
1379   if (words[start] == '{' && words[*offset] != '}')
1380     goto syntax;
1381
1382   if (env == NULL)
1383     {
1384       if (seen_hash)
1385         {
1386           /* $# expands to the number of positional parameters */
1387           buffer[20] = '\0';
1388           value = _itoa_word (__libc_argc - 1, &buffer[20], 10, 0);
1389           seen_hash = 0;
1390         }
1391       else
1392         {
1393           /* Just $ on its own */
1394           *offset = start - 1;
1395           *word = w_addchar (*word, word_length, max_length, '$');
1396           return *word ? 0 : WRDE_NOSPACE;
1397         }
1398     }
1399   /* Is it a numeric parameter? */
1400   else if (isdigit (env[0]))
1401     {
1402       int n = atoi (env);
1403
1404       if (n >= __libc_argc)
1405         /* Substitute NULL. */
1406         value = NULL;
1407       else
1408         /* Replace with appropriate positional parameter. */
1409         value = __libc_argv[n];
1410     }
1411   /* Is it a special parameter? */
1412   else if (special)
1413     {
1414       /* Is it `$$'? */
1415       if (*env == '$')
1416         {
1417           buffer[20] = '\0';
1418           value = _itoa_word (__getpid (), &buffer[20], 10, 0);
1419         }
1420       /* Is it `${#*}' or `${#@}'? */
1421       else if ((*env == '*' || *env == '@') && seen_hash)
1422         {
1423           buffer[20] = '\0';
1424           value = _itoa_word (__libc_argc > 0 ? __libc_argc - 1 : 0,
1425                               &buffer[20], 10, 0);
1426           *word = w_addstr (*word, word_length, max_length, value);
1427           free (env);
1428           if (pattern)
1429             free (pattern);
1430           return *word ? 0 : WRDE_NOSPACE;
1431         }
1432       /* Is it `$*' or `$@' (unquoted) ? */
1433       else if (*env == '*' || (*env == '@' && !quoted))
1434         {
1435           size_t plist_len = 0;
1436           int p;
1437           char *end;
1438
1439           /* Build up value parameter by parameter (copy them) */
1440           for (p = 1; __libc_argv[p]; ++p)
1441             plist_len += strlen (__libc_argv[p]) + 1; /* for space */
1442           value = malloc (plist_len);
1443           if (value == NULL)
1444             goto no_space;
1445           end = value;
1446           *end = 0;
1447           for (p = 1; __libc_argv[p]; ++p)
1448             {
1449               if (p > 1)
1450                 *end++ = ' ';
1451               end = __stpcpy (end, __libc_argv[p]);
1452             }
1453
1454           free_value = 1;
1455         }
1456       else
1457         {
1458           /* Must be a quoted `$@' */
1459           assert (*env == '@' && quoted);
1460
1461           /* Each parameter is a separate word ("$@") */
1462           if (__libc_argc == 2)
1463             value = __libc_argv[1];
1464           else if (__libc_argc > 2)
1465             {
1466               int p;
1467
1468               /* Append first parameter to current word. */
1469               value = w_addstr (*word, word_length, max_length,
1470                                 __libc_argv[1]);
1471               if (value == NULL || w_addword (pwordexp, value))
1472                 goto no_space;
1473
1474               for (p = 2; __libc_argv[p + 1]; p++)
1475                 {
1476                   char *newword = __strdup (__libc_argv[p]);
1477                   if (newword == NULL || w_addword (pwordexp, newword))
1478                     goto no_space;
1479                 }
1480
1481               /* Start a new word with the last parameter. */
1482               *word = w_newword (word_length, max_length);
1483               value = __libc_argv[p];
1484             }
1485           else
1486             {
1487               free (env);
1488               free (pattern);
1489               return 0;
1490             }
1491         }
1492     }
1493   else
1494     value = getenv (env);
1495
1496   if (value == NULL && (flags & WRDE_UNDEF))
1497     {
1498       /* Variable not defined. */
1499       error = WRDE_BADVAL;
1500       goto do_error;
1501     }
1502
1503   if (action != ACT_NONE)
1504     {
1505       int expand_pattern = 0;
1506
1507       /* First, find out if we need to expand pattern (i.e. if we will
1508        * use it). */
1509       switch (action)
1510         {
1511         case ACT_RP_SHORT_LEFT:
1512         case ACT_RP_LONG_LEFT:
1513         case ACT_RP_SHORT_RIGHT:
1514         case ACT_RP_LONG_RIGHT:
1515           /* Always expand for these. */
1516           expand_pattern = 1;
1517           break;
1518
1519         case ACT_NULL_ERROR:
1520         case ACT_NULL_SUBST:
1521         case ACT_NULL_ASSIGN:
1522           if (!value || (!*value && colon_seen))
1523             /* If param is unset, or set but null and a colon has been seen,
1524                the expansion of the pattern will be needed. */
1525             expand_pattern = 1;
1526
1527           break;
1528
1529         case ACT_NONNULL_SUBST:
1530           /* Expansion of word will be needed if parameter is set and not null,
1531              or set null but no colon has been seen. */
1532           if (value && (*value || !colon_seen))
1533             expand_pattern = 1;
1534
1535           break;
1536
1537         default:
1538           assert (! "Unrecognised action!");
1539         }
1540
1541       if (expand_pattern)
1542         {
1543           /* We need to perform tilde expansion, parameter expansion,
1544              command substitution, and arithmetic expansion.  We also
1545              have to be a bit careful with wildcard characters, as
1546              pattern might be given to fnmatch soon.  To do this, we
1547              convert quotes to escapes. */
1548
1549           char *expanded;
1550           size_t exp_len;
1551           size_t exp_maxl;
1552           char *p;
1553           int quoted = 0; /* 1: single quotes; 2: double */
1554
1555           expanded = w_newword (&exp_len, &exp_maxl);
1556           for (p = pattern; p && *p; p++)
1557             {
1558               size_t offset;
1559
1560               switch (*p)
1561                 {
1562                 case '"':
1563                   if (quoted == 2)
1564                     quoted = 0;
1565                   else if (quoted == 0)
1566                     quoted = 2;
1567                   else break;
1568
1569                   continue;
1570
1571                 case '\'':
1572                   if (quoted == 1)
1573                     quoted = 0;
1574                   else if (quoted == 0)
1575                     quoted = 1;
1576                   else break;
1577
1578                   continue;
1579
1580                 case '*':
1581                 case '?':
1582                   if (quoted)
1583                     {
1584                       /* Convert quoted wildchar to escaped wildchar. */
1585                       expanded = w_addchar (expanded, &exp_len,
1586                                             &exp_maxl, '\\');
1587
1588                       if (expanded == NULL)
1589                         goto no_space;
1590                     }
1591                   break;
1592
1593                 case '$':
1594                   offset = 0;
1595                   error = parse_dollars (&expanded, &exp_len, &exp_maxl, p,
1596                                          &offset, flags, NULL, NULL, NULL, 1);
1597                   if (error)
1598                     {
1599                       if (free_value)
1600                         free (value);
1601
1602                       if (expanded)
1603                         free (expanded);
1604
1605                       goto do_error;
1606                     }
1607
1608                   p += offset;
1609                   continue;
1610
1611                 case '~':
1612                   if (quoted || exp_len)
1613                     break;
1614
1615                   offset = 0;
1616                   error = parse_tilde (&expanded, &exp_len, &exp_maxl, p,
1617                                        &offset, 0);
1618                   if (error)
1619                     {
1620                       if (free_value)
1621                         free (value);
1622
1623                       if (expanded)
1624                         free (expanded);
1625
1626                       goto do_error;
1627                     }
1628
1629                   p += offset;
1630                   continue;
1631
1632                 case '\\':
1633                   expanded = w_addchar (expanded, &exp_len, &exp_maxl, '\\');
1634                   ++p;
1635                   assert (*p); /* checked when extracted initially */
1636                   if (expanded == NULL)
1637                     goto no_space;
1638                 }
1639
1640               expanded = w_addchar (expanded, &exp_len, &exp_maxl, *p);
1641
1642               if (expanded == NULL)
1643                 goto no_space;
1644             }
1645
1646           if (pattern)
1647                   free (pattern);
1648
1649           pattern = expanded;
1650         }
1651
1652       switch (action)
1653         {
1654         case ACT_RP_SHORT_LEFT:
1655         case ACT_RP_LONG_LEFT:
1656         case ACT_RP_SHORT_RIGHT:
1657         case ACT_RP_LONG_RIGHT:
1658           {
1659             char *p;
1660             char c;
1661             char *end;
1662
1663             if (value == NULL || pattern == NULL || *pattern == '\0')
1664               break;
1665
1666             end = value + strlen (value);
1667
1668             switch (action)
1669               {
1670               case ACT_RP_SHORT_LEFT:
1671                 for (p = value; p <= end; ++p)
1672                   {
1673                     c = *p;
1674                     *p = '\0';
1675                     if (fnmatch (pattern, value, 0) != FNM_NOMATCH)
1676                       {
1677                         *p = c;
1678                         if (free_value)
1679                           {
1680                             char *newval = __strdup (p);
1681                             if (newval == NULL)
1682                               {
1683                                 free (value);
1684                                 goto no_space;
1685                               }
1686                             free (value);
1687                             value = newval;
1688                           }
1689                         else
1690                           value = p;
1691                         break;
1692                       }
1693                     *p = c;
1694                   }
1695
1696                 break;
1697
1698               case ACT_RP_LONG_LEFT:
1699                 for (p = end; p >= value; --p)
1700                   {
1701                     c = *p;
1702                     *p = '\0';
1703                     if (fnmatch (pattern, value, 0) != FNM_NOMATCH)
1704                       {
1705                         *p = c;
1706                         if (free_value)
1707                           {
1708                             char *newval = __strdup (p);
1709                             if (newval == NULL)
1710                               {
1711                                 free (value);
1712                                 goto no_space;
1713                               }
1714                             free (value);
1715                             value = newval;
1716                           }
1717                         else
1718                           value = p;
1719                         break;
1720                       }
1721                     *p = c;
1722                   }
1723
1724                 break;
1725
1726               case ACT_RP_SHORT_RIGHT:
1727                 for (p = end; p >= value; --p)
1728                   {
1729                     if (fnmatch (pattern, p, 0) != FNM_NOMATCH)
1730                       {
1731                         char *newval;
1732                         newval = malloc (p - value + 1);
1733
1734                         if (newval == NULL)
1735                           {
1736                             if (free_value)
1737                               free (value);
1738                             goto no_space;
1739                           }
1740
1741                         *(char *) __mempcpy (newval, value, p - value) = '\0';
1742                         if (free_value)
1743                           free (value);
1744                         value = newval;
1745                         free_value = 1;
1746                         break;
1747                       }
1748                   }
1749
1750                 break;
1751
1752               case ACT_RP_LONG_RIGHT:
1753                 for (p = value; p <= end; ++p)
1754                   {
1755                     if (fnmatch (pattern, p, 0) != FNM_NOMATCH)
1756                       {
1757                         char *newval;
1758                         newval = malloc (p - value + 1);
1759
1760                         if (newval == NULL)
1761                           {
1762                             if (free_value)
1763                               free (value);
1764                             goto no_space;
1765                           }
1766
1767                         *(char *) __mempcpy (newval, value, p - value) = '\0';
1768                         if (free_value)
1769                           free (value);
1770                         value = newval;
1771                         free_value = 1;
1772                         break;
1773                       }
1774                   }
1775
1776                 break;
1777
1778               default:
1779                 break;
1780               }
1781
1782             break;
1783           }
1784
1785         case ACT_NULL_ERROR:
1786           if (value && *value)
1787             /* Substitute parameter */
1788             break;
1789
1790           error = 0;
1791           if (!colon_seen && value)
1792             /* Substitute NULL */
1793             ;
1794           else
1795             {
1796               const char *str = pattern;
1797
1798               if (str[0] == '\0')
1799                 str = _("parameter null or not set");
1800
1801               __fxprintf (NULL, "%s: %s\n", env, str);
1802             }
1803
1804           if (free_value)
1805             free (value);
1806           goto do_error;
1807
1808         case ACT_NULL_SUBST:
1809           if (value && *value)
1810             /* Substitute parameter */
1811             break;
1812
1813           if (free_value && value)
1814             free (value);
1815
1816           if (!colon_seen && value)
1817             /* Substitute NULL */
1818             goto success;
1819
1820           value = pattern ? __strdup (pattern) : pattern;
1821           free_value = 1;
1822
1823           if (pattern && !value)
1824             goto no_space;
1825
1826           break;
1827
1828         case ACT_NONNULL_SUBST:
1829           if (value && (*value || !colon_seen))
1830             {
1831               if (free_value && value)
1832                 free (value);
1833
1834               value = pattern ? __strdup (pattern) : pattern;
1835               free_value = 1;
1836
1837               if (pattern && !value)
1838                 goto no_space;
1839
1840               break;
1841             }
1842
1843           /* Substitute NULL */
1844           if (free_value)
1845             free (value);
1846           goto success;
1847
1848         case ACT_NULL_ASSIGN:
1849           if (value && *value)
1850             /* Substitute parameter */
1851             break;
1852
1853           if (!colon_seen && value)
1854             {
1855               /* Substitute NULL */
1856               if (free_value)
1857                 free (value);
1858               goto success;
1859             }
1860
1861           if (free_value && value)
1862             free (value);
1863
1864           value = pattern ? __strdup (pattern) : pattern;
1865           free_value = 1;
1866
1867           if (pattern && !value)
1868             goto no_space;
1869
1870           __setenv (env, value, 1);
1871           break;
1872
1873         default:
1874           assert (! "Unrecognised action!");
1875         }
1876     }
1877
1878   free (env); env = NULL;
1879   free (pattern); pattern = NULL;
1880
1881   if (seen_hash)
1882     {
1883       char param_length[21];
1884       param_length[20] = '\0';
1885       *word = w_addstr (*word, word_length, max_length,
1886                         _itoa_word (value ? strlen (value) : 0,
1887                                     &param_length[20], 10, 0));
1888       if (free_value)
1889         {
1890           assert (value != NULL);
1891           free (value);
1892         }
1893
1894       return *word ? 0 : WRDE_NOSPACE;
1895     }
1896
1897   if (value == NULL)
1898     return 0;
1899
1900   if (quoted || !pwordexp)
1901     {
1902       /* Quoted - no field split */
1903       *word = w_addstr (*word, word_length, max_length, value);
1904       if (free_value)
1905         free (value);
1906
1907       return *word ? 0 : WRDE_NOSPACE;
1908     }
1909   else
1910     {
1911       /* Need to field-split */
1912       char *value_copy = __strdup (value); /* Don't modify value */
1913       char *field_begin = value_copy;
1914       int seen_nonws_ifs = 0;
1915
1916       if (free_value)
1917         free (value);
1918
1919       if (value_copy == NULL)
1920         goto no_space;
1921
1922       do
1923         {
1924           char *field_end = field_begin;
1925           char *next_field;
1926
1927           /* If this isn't the first field, start a new word */
1928           if (field_begin != value_copy)
1929             {
1930               if (w_addword (pwordexp, *word) == WRDE_NOSPACE)
1931                 {
1932                   free (value_copy);
1933                   goto no_space;
1934                 }
1935
1936               *word = w_newword (word_length, max_length);
1937             }
1938
1939           /* Skip IFS whitespace before the field */
1940           field_begin += strspn (field_begin, ifs_white);
1941
1942           if (!seen_nonws_ifs && *field_begin == 0)
1943             /* Nothing but whitespace */
1944             break;
1945
1946           /* Search for the end of the field */
1947           field_end = field_begin + strcspn (field_begin, ifs);
1948
1949           /* Set up pointer to the character after end of field and
1950              skip whitespace IFS after it. */
1951           next_field = field_end + strspn (field_end, ifs_white);
1952
1953           /* Skip at most one non-whitespace IFS character after the field */
1954           seen_nonws_ifs = 0;
1955           if (*next_field && strchr (ifs, *next_field))
1956             {
1957               seen_nonws_ifs = 1;
1958               next_field++;
1959             }
1960
1961           /* Null-terminate it */
1962           *field_end = 0;
1963
1964           /* Tag a copy onto the current word */
1965           *word = w_addstr (*word, word_length, max_length, field_begin);
1966
1967           if (*word == NULL && *field_begin != '\0')
1968             {
1969               free (value_copy);
1970               goto no_space;
1971             }
1972
1973           field_begin = next_field;
1974         }
1975       while (seen_nonws_ifs || *field_begin);
1976
1977       free (value_copy);
1978     }
1979
1980   return 0;
1981
1982 success:
1983   error = 0;
1984   goto do_error;
1985
1986 no_space:
1987   error = WRDE_NOSPACE;
1988   goto do_error;
1989
1990 syntax:
1991   error = WRDE_SYNTAX;
1992
1993 do_error:
1994   if (env)
1995     free (env);
1996
1997   if (pattern)
1998     free (pattern);
1999
2000   return error;
2001 }
2002
2003 static int
2004 internal_function
2005 parse_dollars (char **word, size_t *word_length, size_t *max_length,
2006                const char *words, size_t *offset, int flags,
2007                wordexp_t *pwordexp, const char *ifs, const char *ifs_white,
2008                int quoted)
2009 {
2010   /* We are poised _at_ "$" */
2011   switch (words[1 + *offset])
2012     {
2013     case '"':
2014     case '\'':
2015     case 0:
2016       *word = w_addchar (*word, word_length, max_length, '$');
2017       return *word ? 0 : WRDE_NOSPACE;
2018
2019     case '(':
2020       if (words[2 + *offset] == '(')
2021         {
2022           /* Differentiate between $((1+3)) and $((echo);(ls)) */
2023           int i = 3 + *offset;
2024           int depth = 0;
2025           while (words[i] && !(depth == 0 && words[i] == ')'))
2026             {
2027               if (words[i] == '(')
2028                 ++depth;
2029               else if (words[i] == ')')
2030                 --depth;
2031
2032               ++i;
2033             }
2034
2035           if (words[i] == ')' && words[i + 1] == ')')
2036             {
2037               (*offset) += 3;
2038               /* Call parse_arith -- 0 is for "no brackets" */
2039               return parse_arith (word, word_length, max_length, words, offset,
2040                                   flags, 0);
2041             }
2042         }
2043
2044       if (flags & WRDE_NOCMD)
2045         return WRDE_CMDSUB;
2046
2047       (*offset) += 2;
2048       return parse_comm (word, word_length, max_length, words, offset, flags,
2049                          quoted? NULL : pwordexp, ifs, ifs_white);
2050
2051     case '[':
2052       (*offset) += 2;
2053       /* Call parse_arith -- 1 is for "brackets" */
2054       return parse_arith (word, word_length, max_length, words, offset, flags,
2055                           1);
2056
2057     case '{':
2058     default:
2059       ++(*offset);      /* parse_param needs to know if "{" is there */
2060       return parse_param (word, word_length, max_length, words, offset, flags,
2061                            pwordexp, ifs, ifs_white, quoted);
2062     }
2063 }
2064
2065 static int
2066 internal_function
2067 parse_backtick (char **word, size_t *word_length, size_t *max_length,
2068                 const char *words, size_t *offset, int flags,
2069                 wordexp_t *pwordexp, const char *ifs, const char *ifs_white)
2070 {
2071   /* We are poised just after "`" */
2072   int error;
2073   int squoting = 0;
2074   size_t comm_length;
2075   size_t comm_maxlen;
2076   char *comm = w_newword (&comm_length, &comm_maxlen);
2077
2078   for (; words[*offset]; ++(*offset))
2079     {
2080       switch (words[*offset])
2081         {
2082         case '`':
2083           /* Go -- give the script to the shell */
2084           error = exec_comm (comm, word, word_length, max_length, flags,
2085                              pwordexp, ifs, ifs_white);
2086           free (comm);
2087           return error;
2088
2089         case '\\':
2090           if (squoting)
2091             {
2092               error = parse_qtd_backslash (&comm, &comm_length, &comm_maxlen,
2093                                            words, offset);
2094
2095               if (error)
2096                 {
2097                   free (comm);
2098                   return error;
2099                 }
2100
2101               break;
2102             }
2103
2104           ++(*offset);
2105           error = parse_backslash (&comm, &comm_length, &comm_maxlen, words,
2106                                    offset);
2107
2108           if (error)
2109             {
2110               free (comm);
2111               return error;
2112             }
2113
2114           break;
2115
2116         case '\'':
2117           squoting = 1 - squoting;
2118         default:
2119           comm = w_addchar (comm, &comm_length, &comm_maxlen, words[*offset]);
2120           if (comm == NULL)
2121             return WRDE_NOSPACE;
2122         }
2123     }
2124
2125   /* Premature end */
2126   free (comm);
2127   return WRDE_SYNTAX;
2128 }
2129
2130 static int
2131 internal_function
2132 parse_dquote (char **word, size_t *word_length, size_t *max_length,
2133               const char *words, size_t *offset, int flags,
2134               wordexp_t *pwordexp, const char * ifs, const char * ifs_white)
2135 {
2136   /* We are poised just after a double-quote */
2137   int error;
2138
2139   for (; words[*offset]; ++(*offset))
2140     {
2141       switch (words[*offset])
2142         {
2143         case '"':
2144           return 0;
2145
2146         case '$':
2147           error = parse_dollars (word, word_length, max_length, words, offset,
2148                                  flags, pwordexp, ifs, ifs_white, 1);
2149           /* The ``1'' here is to tell parse_dollars not to
2150            * split the fields.  It may need to, however ("$@").
2151            */
2152           if (error)
2153             return error;
2154
2155           break;
2156
2157         case '`':
2158           if (flags & WRDE_NOCMD)
2159             return WRDE_CMDSUB;
2160
2161           ++(*offset);
2162           error = parse_backtick (word, word_length, max_length, words,
2163                                   offset, flags, NULL, NULL, NULL);
2164           /* The first NULL here is to tell parse_backtick not to
2165            * split the fields.
2166            */
2167           if (error)
2168             return error;
2169
2170           break;
2171
2172         case '\\':
2173           error = parse_qtd_backslash (word, word_length, max_length, words,
2174                                        offset);
2175
2176           if (error)
2177             return error;
2178
2179           break;
2180
2181         default:
2182           *word = w_addchar (*word, word_length, max_length, words[*offset]);
2183           if (*word == NULL)
2184             return WRDE_NOSPACE;
2185         }
2186     }
2187
2188   /* Unterminated string */
2189   return WRDE_SYNTAX;
2190 }
2191
2192 /*
2193  * wordfree() is to be called after pwordexp is finished with.
2194  */
2195
2196 void
2197 wordfree (wordexp_t *pwordexp)
2198 {
2199
2200   /* wordexp can set pwordexp to NULL */
2201   if (pwordexp && pwordexp->we_wordv)
2202     {
2203       char **wordv = pwordexp->we_wordv;
2204
2205       for (wordv += pwordexp->we_offs; *wordv; ++wordv)
2206         free (*wordv);
2207
2208       free (pwordexp->we_wordv);
2209       pwordexp->we_wordv = NULL;
2210     }
2211 }
2212 libc_hidden_def (wordfree)
2213
2214 /*
2215  * wordexp()
2216  */
2217
2218 int
2219 wordexp (const char *words, wordexp_t *pwordexp, int flags)
2220 {
2221   size_t words_offset;
2222   size_t word_length;
2223   size_t max_length;
2224   char *word = w_newword (&word_length, &max_length);
2225   int error;
2226   char *ifs;
2227   char ifs_white[4];
2228   wordexp_t old_word = *pwordexp;
2229
2230   if (flags & WRDE_REUSE)
2231     {
2232       /* Minimal implementation of WRDE_REUSE for now */
2233       wordfree (pwordexp);
2234       old_word.we_wordv = NULL;
2235     }
2236
2237   if ((flags & WRDE_APPEND) == 0)
2238     {
2239       pwordexp->we_wordc = 0;
2240
2241       if (flags & WRDE_DOOFFS)
2242         {
2243           pwordexp->we_wordv = calloc (1 + pwordexp->we_offs, sizeof (char *));
2244           if (pwordexp->we_wordv == NULL)
2245             {
2246               error = WRDE_NOSPACE;
2247               goto do_error;
2248             }
2249         }
2250       else
2251         {
2252           pwordexp->we_wordv = calloc (1, sizeof (char *));
2253           if (pwordexp->we_wordv == NULL)
2254             {
2255               error = WRDE_NOSPACE;
2256               goto do_error;
2257             }
2258
2259           pwordexp->we_offs = 0;
2260         }
2261     }
2262
2263   /* Find out what the field separators are.
2264    * There are two types: whitespace and non-whitespace.
2265    */
2266   ifs = getenv ("IFS");
2267
2268   if (!ifs)
2269     /* IFS unset - use <space><tab><newline>. */
2270     ifs = strcpy (ifs_white, " \t\n");
2271   else
2272     {
2273       char *ifsch = ifs;
2274       char *whch = ifs_white;
2275
2276       /* Start off with no whitespace IFS characters */
2277       ifs_white[0] = '\0';
2278
2279       while (*ifsch != '\0')
2280         {
2281           if ((*ifsch == ' ') || (*ifsch == '\t') || (*ifsch == '\n'))
2282             {
2283               /* Whitespace IFS.  See first whether it is already in our
2284                  collection.  */
2285               char *runp = ifs_white;
2286
2287               while (runp < whch && *runp != '\0' && *runp != *ifsch)
2288                 ++runp;
2289
2290               if (runp == whch)
2291                 *whch++ = *ifsch;
2292             }
2293
2294           ++ifsch;
2295         }
2296       *whch = '\0';
2297     }
2298
2299   for (words_offset = 0 ; words[words_offset] ; ++words_offset)
2300     switch (words[words_offset])
2301       {
2302       case '\\':
2303         error = parse_backslash (&word, &word_length, &max_length, words,
2304                                  &words_offset);
2305
2306         if (error)
2307           goto do_error;
2308
2309         break;
2310
2311       case '$':
2312         error = parse_dollars (&word, &word_length, &max_length, words,
2313                                &words_offset, flags, pwordexp, ifs, ifs_white,
2314                                0);
2315
2316         if (error)
2317           goto do_error;
2318
2319         break;
2320
2321       case '`':
2322         if (flags & WRDE_NOCMD)
2323           {
2324             error = WRDE_CMDSUB;
2325             goto do_error;
2326           }
2327
2328         ++words_offset;
2329         error = parse_backtick (&word, &word_length, &max_length, words,
2330                                 &words_offset, flags, pwordexp, ifs,
2331                                 ifs_white);
2332
2333         if (error)
2334           goto do_error;
2335
2336         break;
2337
2338       case '"':
2339         ++words_offset;
2340         error = parse_dquote (&word, &word_length, &max_length, words,
2341                               &words_offset, flags, pwordexp, ifs, ifs_white);
2342
2343         if (error)
2344           goto do_error;
2345
2346         if (!word_length)
2347           {
2348             error = w_addword (pwordexp, NULL);
2349
2350             if (error)
2351               return error;
2352           }
2353
2354         break;
2355
2356       case '\'':
2357         ++words_offset;
2358         error = parse_squote (&word, &word_length, &max_length, words,
2359                               &words_offset);
2360
2361         if (error)
2362           goto do_error;
2363
2364         if (!word_length)
2365           {
2366             error = w_addword (pwordexp, NULL);
2367
2368             if (error)
2369               return error;
2370           }
2371
2372         break;
2373
2374       case '~':
2375         error = parse_tilde (&word, &word_length, &max_length, words,
2376                              &words_offset, pwordexp->we_wordc);
2377
2378         if (error)
2379           goto do_error;
2380
2381         break;
2382
2383       case '*':
2384       case '[':
2385       case '?':
2386         error = parse_glob (&word, &word_length, &max_length, words,
2387                             &words_offset, flags, pwordexp, ifs, ifs_white);
2388
2389         if (error)
2390           goto do_error;
2391
2392         break;
2393
2394       default:
2395         /* Is it a word separator? */
2396         if (strchr (" \t", words[words_offset]) == NULL)
2397           {
2398             char ch = words[words_offset];
2399
2400             /* Not a word separator -- but is it a valid word char? */
2401             if (strchr ("\n|&;<>(){}", ch))
2402               {
2403                 /* Fail */
2404                 error = WRDE_BADCHAR;
2405                 goto do_error;
2406               }
2407
2408             /* "Ordinary" character -- add it to word */
2409             word = w_addchar (word, &word_length, &max_length,
2410                               ch);
2411             if (word == NULL)
2412               {
2413                 error = WRDE_NOSPACE;
2414                 goto do_error;
2415               }
2416
2417             break;
2418           }
2419
2420         /* If a word has been delimited, add it to the list. */
2421         if (word != NULL)
2422           {
2423             error = w_addword (pwordexp, word);
2424             if (error)
2425               goto do_error;
2426           }
2427
2428         word = w_newword (&word_length, &max_length);
2429       }
2430
2431   /* End of string */
2432
2433   /* There was a word separator at the end */
2434   if (word == NULL) /* i.e. w_newword */
2435     return 0;
2436
2437   /* There was no field separator at the end */
2438   return w_addword (pwordexp, word);
2439
2440 do_error:
2441   /* Error:
2442    *    free memory used (unless error is WRDE_NOSPACE), and
2443    *    set pwordexp members back to what they were.
2444    */
2445
2446   if (word != NULL)
2447     free (word);
2448
2449   if (error == WRDE_NOSPACE)
2450     return WRDE_NOSPACE;
2451
2452   if ((flags & WRDE_APPEND) == 0)
2453     wordfree (pwordexp);
2454
2455   *pwordexp = old_word;
2456   return error;
2457 }