]> git.ipfire.org Git - thirdparty/glibc.git/blobdiff - posix/wordexp.c
Use glibc_likely instead __builtin_expect.
[thirdparty/glibc.git] / posix / wordexp.c
index 0139a99e1a5c17dff5133b7e7556e794abcac563..b6b65dd993ec7e2ee5e3e88f8800c2e254cb9d5f 100644 (file)
@@ -1,56 +1,64 @@
 /* POSIX.2 wordexp implementation.
-   Copyright (C) 1997, 1998 Free Software Foundation, Inc.
+   Copyright (C) 1997-2014 Free Software Foundation, Inc.
    This file is part of the GNU C Library.
    Contributed by Tim Waugh <tim@cyberelk.demon.co.uk>.
 
    The GNU C Library is free software; you can redistribute it and/or
-   modify it under the terms of the GNU Library General Public License as
-   published by the Free Software Foundation; either version 2 of the
-   License, or (at your option) any later version.
+   modify it under the terms of the GNU Lesser General Public
+   License as published by the Free Software Foundation; either
+   version 2.1 of the License, or (at your option) any later version.
 
    The GNU C Library is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
-   Library General Public License for more details.
+   Lesser General Public License for more details.
 
-   You should have received a copy of the GNU Library General Public
-   License along with the GNU C Library; see the file COPYING.LIB.  If not,
-   write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
-   Boston, MA 02111-1307, USA.  */
+   You should have received a copy of the GNU Lesser General Public
+   License along with the GNU C Library; if not, see
+   <http://www.gnu.org/licenses/>.  */
 
-#include <wordexp.h>
+#include <alloca.h>
+#include <ctype.h>
+#include <errno.h>
+#include <fcntl.h>
+#include <fnmatch.h>
+#include <glob.h>
+#include <libintl.h>
+#include <paths.h>
+#include <pwd.h>
 #include <signal.h>
+#include <stdbool.h>
+#include <stdio.h>
 #include <stdlib.h>
-#include <pwd.h>
-#include <sys/types.h>
 #include <string.h>
-#include <glob.h>
-#include <ctype.h>
+#include <sys/param.h>
+#include <sys/stat.h>
 #include <sys/time.h>
 #include <sys/types.h>
+#include <sys/types.h>
 #include <sys/wait.h>
 #include <unistd.h>
-#include <fcntl.h>
-#include <sys/stat.h>
-#include <paths.h>
-#include <errno.h>
-#include <sys/param.h>
-#include <stdio.h>
-#include <fnmatch.h>
+#include <wchar.h>
+#include <wordexp.h>
+#include <kernel-features.h>
 
-#include <stdio-common/_itoa.h>
+#include <bits/libc-lock.h>
+#include <_itoa.h>
 
 /* Undefine the following line for the production version.  */
 /* #define NDEBUG 1 */
 #include <assert.h>
 
+/* Get some device information.  */
+#include <device-nrs.h>
+
 /*
  * This is a recursive-descent-style word expansion routine.
  */
 
 /* These variables are defined and initialized in the startup code.  */
-extern int __libc_argc;
-extern char **__libc_argv;
+extern int __libc_argc attribute_hidden;
+extern char **__libc_argv attribute_hidden;
 
 /* Some forward declarations */
 static int parse_dollars (char **word, size_t *word_length, size_t *max_length,
@@ -74,7 +82,7 @@ static int eval_expr (char *expr, long int *result) internal_function;
 
 #define W_CHUNK        (100)
 
-/* Result of w_newword will be ignored if it the last word. */
+/* Result of w_newword will be ignored if it's the last word. */
 static inline char *
 w_newword (size_t *actlen, size_t *maxlen)
 {
@@ -82,19 +90,18 @@ w_newword (size_t *actlen, size_t *maxlen)
   return NULL;
 }
 
-static inline char *
+static char *
 w_addchar (char *buffer, size_t *actlen, size_t *maxlen, char ch)
      /* (lengths exclude trailing zero) */
 {
-  /* Add a character to the buffer, allocating room for it if needed.
-   */
+  /* Add a character to the buffer, allocating room for it if needed.  */
 
   if (*actlen == *maxlen)
     {
       char *old_buffer = buffer;
       assert (buffer == NULL || *maxlen != 0);
       *maxlen += W_CHUNK;
-      buffer = realloc (buffer, 1 + *maxlen);
+      buffer = (char *) realloc (buffer, 1 + *maxlen);
 
       if (buffer == NULL)
        free (old_buffer);
@@ -158,6 +165,7 @@ w_addword (wordexp_t *pwordexp, char *word)
   /* Add a word to the wordlist */
   size_t num_p;
   char **new_wordv;
+  bool allocated = false;
 
   /* Internally, NULL acts like "".  Convert NULLs to "" before
    * the caller sees them.
@@ -167,6 +175,7 @@ w_addword (wordexp_t *pwordexp, char *word)
       word = __strdup ("");
       if (word == NULL)
        goto no_space;
+      allocated = true;
     }
 
   num_p = 2 + pwordexp->we_wordc + pwordexp->we_offs;
@@ -174,11 +183,14 @@ w_addword (wordexp_t *pwordexp, char *word)
   if (new_wordv != NULL)
     {
       pwordexp->we_wordv = new_wordv;
-      pwordexp->we_wordv[pwordexp->we_wordc++] = word;
-      pwordexp->we_wordv[pwordexp->we_wordc] = NULL;
+      pwordexp->we_wordv[pwordexp->we_offs + pwordexp->we_wordc++] = word;
+      pwordexp->we_wordv[pwordexp->we_offs + pwordexp->we_wordc] = NULL;
       return 0;
     }
 
+  if (allocated)
+    free (word);
+
 no_space:
   return WRDE_NOSPACE;
 }
@@ -299,35 +311,48 @@ parse_tilde (char **word, size_t *word_length, size_t *max_length,
       uid_t uid;
       struct passwd pwd, *tpwd;
       int buflen = 1000;
-      char* buffer = __alloca (buflen);
+      char* home;
+      char* buffer;
       int result;
 
-      uid = __getuid ();
+      /* POSIX.2 says ~ expands to $HOME and if HOME is unset the
+        results are unspecified.  We do a lookup on the uid if
+        HOME is unset. */
 
-      while ((result = __getpwuid_r (uid, &pwd, buffer, buflen, &tpwd)) != 0
-            && errno == ERANGE)
+      home = getenv ("HOME");
+      if (home != NULL)
        {
-         buflen += 1000;
-         buffer = __alloca (buflen);
-       }
-
-      if (result == 0 && pwd.pw_dir != NULL)
-       {
-         *word = w_addstr (*word, word_length, max_length, pwd.pw_dir);
+         *word = w_addstr (*word, word_length, max_length, home);
          if (*word == NULL)
            return WRDE_NOSPACE;
        }
       else
        {
-         *word = w_addchar (*word, word_length, max_length, '~');
-         if (*word == NULL)
-           return WRDE_NOSPACE;
+         uid = __getuid ();
+         buffer = __alloca (buflen);
+
+         while ((result = __getpwuid_r (uid, &pwd, buffer, buflen, &tpwd)) != 0
+                && errno == ERANGE)
+           buffer = extend_alloca (buffer, buflen, buflen + 1000);
+
+         if (result == 0 && tpwd != NULL && pwd.pw_dir != NULL)
+           {
+             *word = w_addstr (*word, word_length, max_length, pwd.pw_dir);
+             if (*word == NULL)
+               return WRDE_NOSPACE;
+           }
+         else
+           {
+             *word = w_addchar (*word, word_length, max_length, '~');
+             if (*word == NULL)
+               return WRDE_NOSPACE;
+           }
        }
     }
   else
     {
       /* Look up user name in database to get home directory */
-      char *user = __strndup (&words[1 + *offset], i - *offset);
+      char *user = strndupa (&words[1 + *offset], i - (1 + *offset));
       struct passwd pwd, *tpwd;
       int buflen = 1000;
       char* buffer = __alloca (buflen);
@@ -335,12 +360,9 @@ parse_tilde (char **word, size_t *word_length, size_t *max_length,
 
       while ((result = __getpwnam_r (user, &pwd, buffer, buflen, &tpwd)) != 0
             && errno == ERANGE)
-       {
-         buflen += 1000;
-         buffer = __alloca (buflen);
-       }
+       buffer = extend_alloca (buffer, buflen, buflen + 1000);
 
-      if (result == 0 && pwd.pw_dir)
+      if (result == 0 && tpwd != NULL && pwd.pw_dir)
        *word = w_addstr (*word, word_length, max_length, pwd.pw_dir);
       else
        {
@@ -363,7 +385,7 @@ do_parse_glob (const char *glob_word, char **word, size_t *word_length,
               const char *ifs_white)
 {
   int error;
-  int match;
+  unsigned int match;
   glob_t globbuf;
 
   error = glob (glob_word, GLOB_NOCHECK, NULL, &globbuf);
@@ -422,7 +444,7 @@ parse_glob (char **word, size_t *word_length, size_t *max_length,
   /* We are poised just after a '*', a '[' or a '?'. */
   int error = WRDE_NOSPACE;
   int quoted = 0; /* 1 if singly-quoted, 2 if doubly */
-  int i;
+  size_t i;
   wordexp_t glob_list; /* List of words to glob */
 
   glob_list.we_wordc = 0;
@@ -430,8 +452,7 @@ parse_glob (char **word, size_t *word_length, size_t *max_length,
   glob_list.we_offs = 0;
   for (; words[*offset] != '\0'; ++*offset)
     {
-      if ((ifs && strchr (ifs, words[*offset])) ||
-         (!ifs && strchr (" \t\n", words[*offset])))
+      if (strchr (ifs, words[*offset]) != NULL)
        /* Reached IFS */
        break;
 
@@ -536,16 +557,13 @@ static int
 internal_function
 eval_expr_val (char **expr, long int *result)
 {
-  int sgn = +1;
   char *digit;
 
   /* Skip white space */
   for (digit = *expr; digit && *digit && isspace (*digit); ++digit);
 
-  switch (*digit)
+  if (*digit == '(')
     {
-    case '(':
-
       /* Scan for closing paren */
       for (++digit; **expr && **expr != ')'; ++(*expr));
 
@@ -559,27 +577,14 @@ eval_expr_val (char **expr, long int *result)
        return WRDE_SYNTAX;
 
       return 0;
-
-    case '+':  /* Positive value */
-      ++digit;
-      break;
-
-    case '-':  /* Negative value */
-      ++digit;
-      sgn = -1;
-      break;
-
-    default:
-      if (!isdigit (*digit))
-       return WRDE_SYNTAX;
     }
 
-  *result = 0;
-  for (; *digit && isdigit (*digit); ++digit)
-    *result = (*result * 10) + (*digit - '0');
+  /* POSIX requires that decimal, octal, and hexadecimal constants are
+     recognized.  Therefore we pass 0 as the third parameter to strtol.  */
+  *result = strtol (digit, expr, 0);
+  if (digit == *expr)
+    return WRDE_SYNTAX;
 
-  *expr = digit;
-  *result *= sgn;
   return 0;
 }
 
@@ -806,6 +811,70 @@ parse_arith (char **word, size_t *word_length, size_t *max_length,
   return WRDE_SYNTAX;
 }
 
+/* Function called by child process in exec_comm() */
+static inline void
+internal_function __attribute__ ((always_inline))
+exec_comm_child (char *comm, int *fildes, int showerr, int noexec)
+{
+  const char *args[4] = { _PATH_BSHELL, "-c", comm, NULL };
+
+  /* Execute the command, or just check syntax? */
+  if (noexec)
+    args[1] = "-nc";
+
+  /* Redirect output.  */
+  if (__glibc_likely (fildes[1] != STDOUT_FILENO))
+    {
+      __dup2 (fildes[1], STDOUT_FILENO);
+      __close (fildes[1]);
+    }
+  else
+    {
+#ifdef O_CLOEXEC
+      /* Reset the close-on-exec flag (if necessary).  */
+# ifndef __ASSUME_PIPE2
+      if (__have_pipe2 > 0)
+# endif
+       __fcntl (fildes[1], F_SETFD, 0);
+#endif
+    }
+
+  /* Redirect stderr to /dev/null if we have to.  */
+  if (showerr == 0)
+    {
+      struct stat64 st;
+      int fd;
+      __close (STDERR_FILENO);
+      fd = __open (_PATH_DEVNULL, O_WRONLY);
+      if (fd >= 0 && fd != STDERR_FILENO)
+       {
+         __dup2 (fd, STDERR_FILENO);
+         __close (fd);
+       }
+      /* Be paranoid.  Check that we actually opened the /dev/null
+        device.  */
+      if (__builtin_expect (__fxstat64 (_STAT_VER, STDERR_FILENO, &st), 0) != 0
+         || __builtin_expect (S_ISCHR (st.st_mode), 1) == 0
+#if defined DEV_NULL_MAJOR && defined DEV_NULL_MINOR
+         || st.st_rdev != makedev (DEV_NULL_MAJOR, DEV_NULL_MINOR)
+#endif
+         )
+       /* It's not the /dev/null device.  Stop right here.  The
+          problem is: how do we stop?  We use _exit() with an
+          hopefully unusual exit code.  */
+       _exit (90);
+    }
+
+  /* Make sure the subshell doesn't field-split on our behalf. */
+  __unsetenv ("IFS");
+
+  __close (fildes[0]);
+  __execve (_PATH_BSHELL, (char *const *) args, __environ);
+
+  /* Bad.  What now?  */
+  abort ();
+}
+
 /* Function to execute a command and retrieve the results */
 /* pwordexp contains NULL if field-splitting is forbidden */
 static int
@@ -815,20 +884,46 @@ exec_comm (char *comm, char **word, size_t *word_length, size_t *max_length,
           const char *ifs_white)
 {
   int fildes[2];
-  int bufsize = 128;
+#define bufsize 128
   int buflen;
   int i;
-  char *buffer;
+  int status = 0;
+  size_t maxnewlines = 0;
+  char buffer[bufsize];
   pid_t pid;
+  int noexec = 0;
 
   /* Don't fork() unless necessary */
   if (!comm || !*comm)
     return 0;
 
-  if (__pipe (fildes))
-    /* Bad */
-    return WRDE_NOSPACE;
+#ifdef O_CLOEXEC
+# ifndef __ASSUME_PIPE2
+  if (__have_pipe2 >= 0)
+# endif
+    {
+      int r = __pipe2 (fildes, O_CLOEXEC);
+# ifndef __ASSUME_PIPE2
+      if (__have_pipe2 == 0)
+       __have_pipe2 = r != -1 || errno != ENOSYS ? 1 : -1;
+
+      if (__have_pipe2 > 0)
+# endif
+       if (r < 0)
+         /* Bad */
+         return WRDE_NOSPACE;
+    }
+#endif
+#ifndef __ASSUME_PIPE2
+# ifdef O_CLOEXEC
+  if (__have_pipe2 < 0)
+# endif
+    if (__pipe (fildes) < 0)
+      /* Bad */
+      return WRDE_NOSPACE;
+#endif
 
+ again:
   if ((pid = __fork ()) < 0)
     {
       /* Bad */
@@ -838,52 +933,40 @@ exec_comm (char *comm, char **word, size_t *word_length, size_t *max_length,
     }
 
   if (pid == 0)
-    {
-      /* Child */
-      const char *args[4] = { _PATH_BSHELL, "-c", comm, NULL };
-
-      /* Redirect output.  */
-      __dup2 (fildes[1], 1);
-      __close (fildes[1]);
-
-      /* Redirect stderr to /dev/null if we have to.  */
-      if ((flags & WRDE_SHOWERR) == 0)
-       {
-         int fd;
-         __close (2);
-         fd = __open (_PATH_DEVNULL, O_WRONLY);
-         if (fd >= 0 && fd != 2)
-           {
-             __dup2 (fd, 2);
-             __close (fd);
-           }
-       }
-
-      __close (fildes[0]);
-      __execve (_PATH_BSHELL, (char *const *) args, __environ);
-
-      /* Bad.  What now?  */
-      abort ();
-    }
+    exec_comm_child (comm, fildes, noexec ? 0 : flags & WRDE_SHOWERR, noexec);
 
   /* Parent */
 
+  /* If we are just testing the syntax, only wait.  */
+  if (noexec)
+    return (TEMP_FAILURE_RETRY (__waitpid (pid, &status, 0)) == pid
+           && status != 0) ? WRDE_SYNTAX : 0;
+
   __close (fildes[1]);
-  buffer = __alloca (bufsize);
+  fildes[1] = -1;
 
   if (!pwordexp)
-    /* Quoted - no field splitting */
-
+    /* Quoted - no field splitting */
+    {
       while (1)
        {
-         if ((buflen = __read (fildes[0], buffer, bufsize)) < 1)
+         if ((buflen = TEMP_FAILURE_RETRY (__read (fildes[0], buffer,
+                                                   bufsize))) < 1)
            {
-             if (__waitpid (pid, NULL, WNOHANG) == 0)
+             /* If read returned 0 then the process has closed its
+                stdout.  Don't use WNOHANG in that case to avoid busy
+                looping until the process eventually exits.  */
+             if (TEMP_FAILURE_RETRY (__waitpid (pid, &status,
+                                                buflen == 0 ? 0 : WNOHANG))
+                 == 0)
                continue;
-             if ((buflen = __read (fildes[0], buffer, bufsize)) < 1)
+             if ((buflen = TEMP_FAILURE_RETRY (__read (fildes[0], buffer,
+                                                       bufsize))) < 1)
                break;
            }
 
+         maxnewlines += buflen;
+
          *word = w_addmem (*word, word_length, max_length, buffer, buflen);
          if (*word == NULL)
            goto no_space;
@@ -897,15 +980,23 @@ exec_comm (char *comm, char **word, size_t *word_length, size_t *max_length,
        *  0 when searching for first character in a field not IFS white space
        *  1 when copying the text of a field
        *  2 when searching for possible non-whitespace IFS
+       *  3 when searching for non-newline after copying field
        */
 
       while (1)
        {
-         if ((buflen = __read (fildes[0], buffer, bufsize)) < 1)
+         if ((buflen = TEMP_FAILURE_RETRY (__read (fildes[0], buffer,
+                                                   bufsize))) < 1)
            {
-             if (__waitpid (pid, NULL, WNOHANG) == 0)
+             /* If read returned 0 then the process has closed its
+                stdout.  Don't use WNOHANG in that case to avoid busy
+                looping until the process eventually exits.  */
+             if (TEMP_FAILURE_RETRY (__waitpid (pid, &status,
+                                                buflen == 0 ? 0 : WNOHANG))
+                 == 0)
                continue;
-             if ((__read (fildes[0], buffer, bufsize)) < 1)
+             if ((buflen = TEMP_FAILURE_RETRY (__read (fildes[0], buffer,
+                                                       bufsize))) < 1)
                break;
            }
 
@@ -935,29 +1026,64 @@ exec_comm (char *comm, char **word, size_t *word_length, size_t *max_length,
                    }
                  else
                    {
-                     /* Current character is IFS white space */
+                     if (buffer[i] == '\n')
+                       {
+                         /* Current character is (IFS) newline */
 
-                     /* If not copying a field, ignore it */
-                     if (copying != 1)
-                       continue;
+                         /* If copying a field, this is the end of it,
+                            but maybe all that's left is trailing newlines.
+                            So start searching for a non-newline. */
+                         if (copying == 1)
+                           copying = 3;
 
-                     /* End of field (search for non-ws IFS afterwards) */
-                     copying = 2;
+                         continue;
+                       }
+                     else
+                       {
+                         /* Current character is IFS white space, but
+                            not a newline */
+
+                         /* If not either copying a field or searching
+                            for non-newline after a field, ignore it */
+                         if (copying != 1 && copying != 3)
+                           continue;
+
+                         /* End of field (search for non-ws IFS afterwards) */
+                         copying = 2;
+                       }
                    }
 
-                 /* First IFS white space, or IFS non-whitespace.
+                 /* First IFS white space (non-newline), or IFS non-whitespace.
                   * Delimit the field.  Nulls are converted by w_addword. */
                  if (w_addword (pwordexp, *word) == WRDE_NOSPACE)
                    goto no_space;
 
                  *word = w_newword (word_length, max_length);
+
+                 maxnewlines = 0;
                  /* fall back round the loop.. */
                }
              else
                {
                  /* Not IFS character */
+
+                 if (copying == 3)
+                   {
+                     /* Nothing but (IFS) newlines since the last field,
+                        so delimit it here before starting new word */
+                     if (w_addword (pwordexp, *word) == WRDE_NOSPACE)
+                       goto no_space;
+
+                     *word = w_newword (word_length, max_length);
+                   }
+
                  copying = 1;
 
+                 if (buffer[i] == '\n') /* happens if newline not in IFS */
+                   maxnewlines++;
+                 else
+                   maxnewlines = 0;
+
                  *word = w_addchar (*word, word_length, max_length,
                                     buffer[i]);
                  if (*word == NULL)
@@ -967,8 +1093,11 @@ exec_comm (char *comm, char **word, size_t *word_length, size_t *max_length,
        }
     }
 
-  /* Bash chops off trailing newlines, which seems sensible.  */
-  while (*word_length > 0 && (*word)[*word_length - 1] == '\n')
+  /* Chop off trailing newlines (required by POSIX.2)  */
+  /* Ensure we don't go back further than the beginning of the
+     substitution (i.e. remove maxnewlines bytes at most) */
+  while (maxnewlines-- != 0 &&
+        *word_length > 0 && (*word)[*word_length - 1] == '\n')
     {
       (*word)[--*word_length] = '\0';
 
@@ -983,11 +1112,20 @@ exec_comm (char *comm, char **word, size_t *word_length, size_t *max_length,
     }
 
   __close (fildes[0]);
+  fildes[0] = -1;
+
+  /* Check for syntax error (re-execute but with "-n" flag) */
+  if (buflen < 1 && status != 0)
+    {
+      noexec = 1;
+      goto again;
+    }
+
   return 0;
 
 no_space:
   __kill (pid, SIGKILL);
-  __waitpid (pid, NULL, 0);
+  TEMP_FAILURE_RETRY (__waitpid (pid, NULL, 0));
   __close (fildes[0]);
   return WRDE_NOSPACE;
 }
@@ -1032,8 +1170,25 @@ parse_comm (char **word, size_t *word_length, size_t *max_length,
              /* Go -- give script to the shell */
              if (comm)
                {
+#ifdef __libc_ptf_call
+                 /* We do not want the exec_comm call to be cut short
+                    by a thread cancellation since cleanup is very
+                    ugly.  Therefore disable cancellation for
+                    now.  */
+                 // XXX Ideally we do want the thread being cancelable.
+                 // XXX If demand is there we'll change it.
+                 int state = PTHREAD_CANCEL_ENABLE;
+                 __libc_ptf_call (pthread_setcancelstate,
+                                  (PTHREAD_CANCEL_DISABLE, &state), 0);
+#endif
+
                  error = exec_comm (comm, word, word_length, max_length,
                                     flags, pwordexp, ifs, ifs_white);
+
+#ifdef __libc_ptf_call
+                 __libc_ptf_call (pthread_setcancelstate, (state, NULL), 0);
+#endif
+
                  free (comm);
                }
 
@@ -1053,9 +1208,8 @@ parse_comm (char **word, size_t *word_length, size_t *max_length,
        return WRDE_NOSPACE;
     }
 
-  /* Premature end */
-  if (comm)
-    free (comm);
+  /* Premature end.  */
+  free (comm);
 
   return WRDE_SYNTAX;
 }
@@ -1203,7 +1357,7 @@ parse_param (char **word, size_t *word_length, size_t *max_length,
          goto syntax;
        }
 
-      /* Now collect the pattern. */
+      /* Now collect the pattern, but don't expand it yet. */
       ++*offset;
       for (; words[*offset]; ++(*offset))
        {
@@ -1224,8 +1378,18 @@ parse_param (char **word, size_t *word_length, size_t *max_length,
              break;
 
            case '\\':
-             if (!pattern_is_quoted && words[++*offset] == '\0')
+             if (pattern_is_quoted)
+               /* Quoted; treat as normal character. */
+               break;
+
+             /* Otherwise, it's an escape: next character is literal. */
+             if (words[++*offset] == '\0')
                goto syntax;
+
+             pattern = w_addchar (pattern, &pat_length, &pat_maxlen, '\\');
+             if (pattern == NULL)
+               goto no_space;
+
              break;
 
            case '\'':
@@ -1306,8 +1470,7 @@ envsubst:
                              &buffer[20], 10, 0);
          *word = w_addstr (*word, word_length, max_length, value);
          free (env);
-         if (pattern)
-           free (pattern);
+         free (pattern);
          return *word ? 0 : WRDE_NOSPACE;
        }
       /* Is it `$*' or `$@' (unquoted) ? */
@@ -1383,6 +1546,150 @@ envsubst:
 
   if (action != ACT_NONE)
     {
+      int expand_pattern = 0;
+
+      /* First, find out if we need to expand pattern (i.e. if we will
+       * use it). */
+      switch (action)
+       {
+       case ACT_RP_SHORT_LEFT:
+       case ACT_RP_LONG_LEFT:
+       case ACT_RP_SHORT_RIGHT:
+       case ACT_RP_LONG_RIGHT:
+         /* Always expand for these. */
+         expand_pattern = 1;
+         break;
+
+       case ACT_NULL_ERROR:
+       case ACT_NULL_SUBST:
+       case ACT_NULL_ASSIGN:
+         if (!value || (!*value && colon_seen))
+           /* If param is unset, or set but null and a colon has been seen,
+              the expansion of the pattern will be needed. */
+           expand_pattern = 1;
+
+         break;
+
+       case ACT_NONNULL_SUBST:
+         /* Expansion of word will be needed if parameter is set and not null,
+            or set null but no colon has been seen. */
+         if (value && (*value || !colon_seen))
+           expand_pattern = 1;
+
+         break;
+
+       default:
+         assert (! "Unrecognised action!");
+       }
+
+      if (expand_pattern)
+       {
+         /* We need to perform tilde expansion, parameter expansion,
+            command substitution, and arithmetic expansion.  We also
+            have to be a bit careful with wildcard characters, as
+            pattern might be given to fnmatch soon.  To do this, we
+            convert quotes to escapes. */
+
+         char *expanded;
+         size_t exp_len;
+         size_t exp_maxl;
+         char *p;
+         int quoted = 0; /* 1: single quotes; 2: double */
+
+         expanded = w_newword (&exp_len, &exp_maxl);
+         for (p = pattern; p && *p; p++)
+           {
+             size_t offset;
+
+             switch (*p)
+               {
+               case '"':
+                 if (quoted == 2)
+                   quoted = 0;
+                 else if (quoted == 0)
+                   quoted = 2;
+                 else break;
+
+                 continue;
+
+               case '\'':
+                 if (quoted == 1)
+                   quoted = 0;
+                 else if (quoted == 0)
+                   quoted = 1;
+                 else break;
+
+                 continue;
+
+               case '*':
+               case '?':
+                 if (quoted)
+                   {
+                     /* Convert quoted wildchar to escaped wildchar. */
+                     expanded = w_addchar (expanded, &exp_len,
+                                           &exp_maxl, '\\');
+
+                     if (expanded == NULL)
+                       goto no_space;
+                   }
+                 break;
+
+               case '$':
+                 offset = 0;
+                 error = parse_dollars (&expanded, &exp_len, &exp_maxl, p,
+                                        &offset, flags, NULL, NULL, NULL, 1);
+                 if (error)
+                   {
+                     if (free_value)
+                       free (value);
+
+                     free (expanded);
+
+                     goto do_error;
+                   }
+
+                 p += offset;
+                 continue;
+
+               case '~':
+                 if (quoted || exp_len)
+                   break;
+
+                 offset = 0;
+                 error = parse_tilde (&expanded, &exp_len, &exp_maxl, p,
+                                      &offset, 0);
+                 if (error)
+                   {
+                     if (free_value)
+                       free (value);
+
+                     free (expanded);
+
+                     goto do_error;
+                   }
+
+                 p += offset;
+                 continue;
+
+               case '\\':
+                 expanded = w_addchar (expanded, &exp_len, &exp_maxl, '\\');
+                 ++p;
+                 assert (*p); /* checked when extracted initially */
+                 if (expanded == NULL)
+                   goto no_space;
+               }
+
+             expanded = w_addchar (expanded, &exp_len, &exp_maxl, *p);
+
+             if (expanded == NULL)
+               goto no_space;
+           }
+
+         free (pattern);
+
+         pattern = expanded;
+       }
+
       switch (action)
        {
        case ACT_RP_SHORT_LEFT:
@@ -1521,37 +1828,18 @@ envsubst:
            /* Substitute parameter */
            break;
 
+         error = 0;
          if (!colon_seen && value)
            /* Substitute NULL */
-           error = 0;
-         else if (*pattern)
+           ;
+         else
            {
-             /* Expand 'pattern' and write it to stderr */
-             wordexp_t we;
-
-             error = wordexp (pattern, &we, flags);
-
-             if (error == 0)
-               {
-                 int i;
+             const char *str = pattern;
 
-                 fprintf (stderr, "%s:", env);
+             if (str[0] == '\0')
+               str = _("parameter null or not set");
 
-                 for (i = 0; i < we.we_wordc; ++i)
-                   {
-                     fprintf (stderr, " %s", we.we_wordv[i]);
-                   }
-
-                 fprintf (stderr, "\n");
-                 error = WRDE_BADVAL;
-               }
-
-             wordfree (&we);
-           }
-         else
-           {
-             fprintf (stderr, "%s: parameter null or not set\n", env);
-             error = WRDE_BADVAL;
+             __fxprintf (NULL, "%s: %s\n", env, str);
            }
 
          if (free_value)
@@ -1563,95 +1851,35 @@ envsubst:
            /* Substitute parameter */
            break;
 
-         if (!colon_seen && value)
-           {
-             /* Substitute NULL */
-             if (free_value)
-               free (value);
-             goto success;
-           }
-
-       subst_word:
-         {
-           /* Substitute word */
-           wordexp_t we;
-           int i;
-
-           if (free_value)
-             free (value);
-
-           if (quoted)
-             {
-               /* No field-splitting is allowed, so imagine
-                  quotes around the word.  */
-               char *qtd_pattern = malloc (3 + strlen (pattern));
-               if (qtd_pattern)
-                 sprintf (qtd_pattern, "\"%s\"", pattern);
-               free (pattern);
-               pattern = qtd_pattern;
-             }
-
-           if (pattern == NULL && (pattern = __strdup ("")) == NULL)
-             goto no_space;
-
-           error = wordexp (pattern, &we, flags);
-           if (error)
-             goto do_error;
-
-           /* Fingers crossed that the quotes worked.. */
-           assert (!quoted || we.we_wordc == 1);
-
-           /* Substitute */
-           for (i = 0; i < we.we_wordc; ++i)
-             if ((error = w_addword (pwordexp, __strdup (we.we_wordv[i])))
-                 != 0)
-               break;
-
-           if (i < we.we_wordc)
-             {
-               /* Ran out of space */
-               wordfree (&we);
-               goto do_error;
-             }
-
-           if (action == ACT_NULL_ASSIGN)
-             {
-               char *words;
-               char *cp;
-               size_t words_size = 0;
+         if (free_value)
+           free (value);
 
-               if (special)
-                 /* Cannot assign special parameters. */
-                 goto syntax;
+         if (!colon_seen && value)
+           /* Substitute NULL */
+           goto success;
 
-               for (i = 0; i < we.we_wordc; i++)
-                 words_size += strlen (we.we_wordv[i]) + 1; /* for <space> */
-               words_size++;
+         value = pattern ? __strdup (pattern) : pattern;
+         free_value = 1;
 
-               cp = words = __alloca (words_size);
-               *words = 0;
-               for (i = 0; i < we.we_wordc - 1; i++)
-                 {
-                   cp = __stpcpy (cp, we.we_wordv[i]);
-                   *cp++ = ' ';
-                 }
+         if (pattern && !value)
+           goto no_space;
 
-               strcpy (cp, we.we_wordv[i]);
+         break;
 
-               /* Also assign */
-               setenv (env, words, 1);
-             }
+       case ACT_NONNULL_SUBST:
+         if (value && (*value || !colon_seen))
+           {
+             if (free_value)
+               free (value);
 
-           wordfree (&we);
-           goto success;
-         }
+             value = pattern ? __strdup (pattern) : pattern;
+             free_value = 1;
 
-       case ACT_NONNULL_SUBST:
-         if (value && *value)
-           goto subst_word;
+             if (pattern && !value)
+               goto no_space;
 
-         if (!colon_seen && value)
-           goto subst_word;
+             break;
+           }
 
          /* Substitute NULL */
          if (free_value)
@@ -1671,16 +1899,27 @@ envsubst:
              goto success;
            }
 
-         /* This checks for '=' so it knows to assign */
-         goto subst_word;
+         if (free_value)
+           free (value);
+
+         value = pattern ? __strdup (pattern) : pattern;
+         free_value = 1;
+
+         if (pattern && !value)
+           goto no_space;
+
+         __setenv (env, value, 1);
+         break;
 
        default:
          assert (! "Unrecognised action!");
        }
     }
 
-  free (env); env = NULL;
-  free (pattern); pattern = NULL;
+  free (env);
+  env = NULL;
+  free (pattern);
+  pattern = NULL;
 
   if (seen_hash)
     {
@@ -1751,7 +1990,7 @@ envsubst:
          field_end = field_begin + strcspn (field_begin, ifs);
 
          /* Set up pointer to the character after end of field and
-             skip whitespace IFS after it. */
+            skip whitespace IFS after it. */
          next_field = field_end + strspn (field_end, ifs_white);
 
          /* Skip at most one non-whitespace IFS character after the field */
@@ -1795,11 +2034,9 @@ syntax:
   error = WRDE_SYNTAX;
 
 do_error:
-  if (env)
-    free (env);
+  free (env);
 
-  if (pattern)
-    free (pattern);
+  free (pattern);
 
   return error;
 }
@@ -1867,6 +2104,7 @@ parse_dollars (char **word, size_t *word_length, size_t *max_length,
 }
 
 static int
+internal_function
 parse_backtick (char **word, size_t *word_length, size_t *max_length,
                const char *words, size_t *offset, int flags,
                wordexp_t *pwordexp, const char *ifs, const char *ifs_white)
@@ -2012,6 +2250,7 @@ wordfree (wordexp_t *pwordexp)
       pwordexp->we_wordv = NULL;
     }
 }
+libc_hidden_def (wordfree)
 
 /*
  * wordexp()
@@ -2020,7 +2259,6 @@ wordfree (wordexp_t *pwordexp)
 int
 wordexp (const char *words, wordexp_t *pwordexp, int flags)
 {
-  size_t wordv_offset;
   size_t words_offset;
   size_t word_length;
   size_t max_length;
@@ -2028,48 +2266,47 @@ wordexp (const char *words, wordexp_t *pwordexp, int flags)
   int error;
   char *ifs;
   char ifs_white[4];
-  char **old_wordv = pwordexp->we_wordv;
-  size_t old_wordc = (flags & WRDE_REUSE) ? pwordexp->we_wordc : 0;
+  wordexp_t old_word = *pwordexp;
 
   if (flags & WRDE_REUSE)
     {
       /* Minimal implementation of WRDE_REUSE for now */
       wordfree (pwordexp);
-      old_wordv = NULL;
+      old_word.we_wordv = NULL;
     }
 
-  if (flags & WRDE_DOOFFS)
+  if ((flags & WRDE_APPEND) == 0)
     {
-      pwordexp->we_wordv = calloc (1 + pwordexp->we_offs, sizeof (char *));
-      if (pwordexp->we_wordv == NULL)
+      pwordexp->we_wordc = 0;
+
+      if (flags & WRDE_DOOFFS)
        {
-         error = WRDE_NOSPACE;
-         goto do_error;
+         pwordexp->we_wordv = calloc (1 + pwordexp->we_offs, sizeof (char *));
+         if (pwordexp->we_wordv == NULL)
+           {
+             error = WRDE_NOSPACE;
+             goto do_error;
+           }
        }
-    }
-  else
-    {
-      pwordexp->we_wordv = calloc (1, sizeof (char *));
-      if (pwordexp->we_wordv == NULL)
+      else
        {
-         error = WRDE_NOSPACE;
-         goto do_error;
-       }
+         pwordexp->we_wordv = calloc (1, sizeof (char *));
+         if (pwordexp->we_wordv == NULL)
+           {
+             error = WRDE_NOSPACE;
+             goto do_error;
+           }
 
-      pwordexp->we_offs = 0;
+         pwordexp->we_offs = 0;
+       }
     }
 
-  if ((flags & WRDE_APPEND) == 0)
-    pwordexp->we_wordc = 0;
-
-  wordv_offset = pwordexp->we_offs + pwordexp->we_wordc;
-
   /* Find out what the field separators are.
    * There are two types: whitespace and non-whitespace.
    */
   ifs = getenv ("IFS");
 
-  if (!ifs)
+  if (ifs == NULL)
     /* IFS unset - use <space><tab><newline>. */
     ifs = strcpy (ifs_white, " \t\n");
   else
@@ -2077,18 +2314,15 @@ wordexp (const char *words, wordexp_t *pwordexp, int flags)
       char *ifsch = ifs;
       char *whch = ifs_white;
 
-      /* Start off with no whitespace IFS characters */
-      ifs_white[0] = '\0';
-
       while (*ifsch != '\0')
        {
-         if ((*ifsch == ' ') || (*ifsch == '\t') || (*ifsch == '\n'))
+         if (*ifsch == ' ' || *ifsch == '\t' || *ifsch == '\n')
            {
              /* Whitespace IFS.  See first whether it is already in our
                 collection.  */
              char *runp = ifs_white;
 
-             while (runp < whch && *runp != '\0' && *runp != *ifsch)
+             while (runp < whch && *runp != *ifsch)
                ++runp;
 
              if (runp == whch)
@@ -2147,6 +2381,14 @@ wordexp (const char *words, wordexp_t *pwordexp, int flags)
        if (error)
          goto do_error;
 
+       if (!word_length)
+         {
+           error = w_addword (pwordexp, NULL);
+
+           if (error)
+             return error;
+         }
+
        break;
 
       case '\'':
@@ -2157,6 +2399,14 @@ wordexp (const char *words, wordexp_t *pwordexp, int flags)
        if (error)
          goto do_error;
 
+       if (!word_length)
+         {
+           error = w_addword (pwordexp, NULL);
+
+           if (error)
+             return error;
+         }
+
        break;
 
       case '~':
@@ -2189,18 +2439,11 @@ wordexp (const char *words, wordexp_t *pwordexp, int flags)
            if (strchr ("\n|&;<>(){}", ch))
              {
                /* Fail */
-               wordfree (pwordexp);
-               pwordexp->we_wordc = 0;
-               pwordexp->we_wordv = old_wordv;
-               return WRDE_BADCHAR;
+               error = WRDE_BADCHAR;
+               goto do_error;
              }
 
            /* "Ordinary" character -- add it to word */
-
-           /* Convert IFS chars to blanks -- bash does this */
-           if (strchr (ifs, ch))
-             ch = ' ';
-
            word = w_addchar (word, &word_length, &max_length,
                              ch);
            if (word == NULL)
@@ -2235,17 +2478,17 @@ wordexp (const char *words, wordexp_t *pwordexp, int flags)
 do_error:
   /* Error:
    *   free memory used (unless error is WRDE_NOSPACE), and
-   *   set we_wordc and wd_wordv back to what they were.
+   *   set pwordexp members back to what they were.
    */
 
-  if (word != NULL)
-    free (word);
+  free (word);
 
   if (error == WRDE_NOSPACE)
     return WRDE_NOSPACE;
 
-  wordfree (pwordexp);
-  pwordexp->we_wordv = old_wordv;
-  pwordexp->we_wordc = old_wordc;
+  if ((flags & WRDE_APPEND) == 0)
+    wordfree (pwordexp);
+
+  *pwordexp = old_word;
   return error;
 }