Bump to 1.14.1
[platform/upstream/augeas.git] / lib / quotearg.c
1 /* quotearg.c - quote arguments for output
2
3    Copyright (C) 1998-2002, 2004-2016 Free Software Foundation, Inc.
4
5    This program is free software: you can redistribute it and/or modify
6    it under the terms of the GNU General Public License as published by
7    the Free Software Foundation; either version 3 of the License, or
8    (at your option) any later version.
9
10    This program is distributed in the hope that it will be useful,
11    but WITHOUT ANY WARRANTY; without even the implied warranty of
12    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13    GNU General Public License for more details.
14
15    You should have received a copy of the GNU General Public License
16    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
17
18 /* Written by Paul Eggert <eggert@twinsun.com> */
19
20 /* Without this pragma, gcc 4.7.0 20111124 mistakenly suggests that
21    the quoting_options_from_style function might be candidate for
22    attribute 'pure'  */
23 #if (__GNUC__ == 4 && 6 <= __GNUC_MINOR__) || 4 < __GNUC__
24 # pragma GCC diagnostic ignored "-Wsuggest-attribute=pure"
25 #endif
26
27 #include <config.h>
28
29 #include "quotearg.h"
30 #include "quote.h"
31
32 #include "xalloc.h"
33 #include "c-strcaseeq.h"
34 #include "localcharset.h"
35
36 #include <ctype.h>
37 #include <errno.h>
38 #include <limits.h>
39 #include <stdbool.h>
40 #include <stdlib.h>
41 #include <string.h>
42 #include <wchar.h>
43 #include <wctype.h>
44
45 #include "gettext.h"
46 #define _(msgid) gettext (msgid)
47 #define N_(msgid) msgid
48
49 #ifndef SIZE_MAX
50 # define SIZE_MAX ((size_t) -1)
51 #endif
52
53 #define INT_BITS (sizeof (int) * CHAR_BIT)
54
55 struct quoting_options
56 {
57   /* Basic quoting style.  */
58   enum quoting_style style;
59
60   /* Additional flags.  Bitwise combination of enum quoting_flags.  */
61   int flags;
62
63   /* Quote the characters indicated by this bit vector even if the
64      quoting style would not normally require them to be quoted.  */
65   unsigned int quote_these_too[(UCHAR_MAX / INT_BITS) + 1];
66
67   /* The left quote for custom_quoting_style.  */
68   char const *left_quote;
69
70   /* The right quote for custom_quoting_style.  */
71   char const *right_quote;
72 };
73
74 /* Names of quoting styles.  */
75 char const *const quoting_style_args[] =
76 {
77   "literal",
78   "shell",
79   "shell-always",
80   "shell-escape",
81   "shell-escape-always",
82   "c",
83   "c-maybe",
84   "escape",
85   "locale",
86   "clocale",
87   0
88 };
89
90 /* Correspondences to quoting style names.  */
91 enum quoting_style const quoting_style_vals[] =
92 {
93   literal_quoting_style,
94   shell_quoting_style,
95   shell_always_quoting_style,
96   shell_escape_quoting_style,
97   shell_escape_always_quoting_style,
98   c_quoting_style,
99   c_maybe_quoting_style,
100   escape_quoting_style,
101   locale_quoting_style,
102   clocale_quoting_style
103 };
104
105 /* The default quoting options.  */
106 static struct quoting_options default_quoting_options;
107
108 /* Allocate a new set of quoting options, with contents initially identical
109    to O if O is not null, or to the default if O is null.
110    It is the caller's responsibility to free the result.  */
111 struct quoting_options *
112 clone_quoting_options (struct quoting_options *o)
113 {
114   int e = errno;
115   struct quoting_options *p = xmemdup (o ? o : &default_quoting_options,
116                                        sizeof *o);
117   errno = e;
118   return p;
119 }
120
121 /* Get the value of O's quoting style.  If O is null, use the default.  */
122 enum quoting_style
123 get_quoting_style (struct quoting_options const *o)
124 {
125   return (o ? o : &default_quoting_options)->style;
126 }
127
128 /* In O (or in the default if O is null),
129    set the value of the quoting style to S.  */
130 void
131 set_quoting_style (struct quoting_options *o, enum quoting_style s)
132 {
133   (o ? o : &default_quoting_options)->style = s;
134 }
135
136 /* In O (or in the default if O is null),
137    set the value of the quoting options for character C to I.
138    Return the old value.  Currently, the only values defined for I are
139    0 (the default) and 1 (which means to quote the character even if
140    it would not otherwise be quoted).  */
141 int
142 set_char_quoting (struct quoting_options *o, char c, int i)
143 {
144   unsigned char uc = c;
145   unsigned int *p =
146     (o ? o : &default_quoting_options)->quote_these_too + uc / INT_BITS;
147   int shift = uc % INT_BITS;
148   int r = (*p >> shift) & 1;
149   *p ^= ((i & 1) ^ r) << shift;
150   return r;
151 }
152
153 /* In O (or in the default if O is null),
154    set the value of the quoting options flag to I, which can be a
155    bitwise combination of enum quoting_flags, or 0 for default
156    behavior.  Return the old value.  */
157 int
158 set_quoting_flags (struct quoting_options *o, int i)
159 {
160   int r;
161   if (!o)
162     o = &default_quoting_options;
163   r = o->flags;
164   o->flags = i;
165   return r;
166 }
167
168 void
169 set_custom_quoting (struct quoting_options *o,
170                     char const *left_quote, char const *right_quote)
171 {
172   if (!o)
173     o = &default_quoting_options;
174   o->style = custom_quoting_style;
175   if (!left_quote || !right_quote)
176     abort ();
177   o->left_quote = left_quote;
178   o->right_quote = right_quote;
179 }
180
181 /* Return quoting options for STYLE, with no extra quoting.  */
182 static struct quoting_options /* NOT PURE!! */
183 quoting_options_from_style (enum quoting_style style)
184 {
185   struct quoting_options o = { literal_quoting_style, 0, { 0 }, NULL, NULL };
186   if (style == custom_quoting_style)
187     abort ();
188   o.style = style;
189   return o;
190 }
191
192 /* MSGID approximates a quotation mark.  Return its translation if it
193    has one; otherwise, return either it or "\"", depending on S.
194
195    S is either clocale_quoting_style or locale_quoting_style.  */
196 static char const *
197 gettext_quote (char const *msgid, enum quoting_style s)
198 {
199   char const *translation = _(msgid);
200   char const *locale_code;
201
202   if (translation != msgid)
203     return translation;
204
205   /* For UTF-8 and GB-18030, use single quotes U+2018 and U+2019.
206      Here is a list of other locales that include U+2018 and U+2019:
207
208         ISO-8859-7   0xA1                 KOI8-T       0x91
209         CP869        0x8B                 CP874        0x91
210         CP932        0x81 0x65            CP936        0xA1 0xAE
211         CP949        0xA1 0xAE            CP950        0xA1 0xA5
212         CP1250       0x91                 CP1251       0x91
213         CP1252       0x91                 CP1253       0x91
214         CP1254       0x91                 CP1255       0x91
215         CP1256       0x91                 CP1257       0x91
216         EUC-JP       0xA1 0xC6            EUC-KR       0xA1 0xAE
217         EUC-TW       0xA1 0xE4            BIG5         0xA1 0xA5
218         BIG5-HKSCS   0xA1 0xA5            EUC-CN       0xA1 0xAE
219         GBK          0xA1 0xAE            Georgian-PS  0x91
220         PT154        0x91
221
222      None of these is still in wide use; using iconv is overkill.  */
223   locale_code = locale_charset ();
224   if (STRCASEEQ (locale_code, "UTF-8", 'U','T','F','-','8',0,0,0,0))
225     return msgid[0] == '`' ? "\xe2\x80\x98": "\xe2\x80\x99";
226   if (STRCASEEQ (locale_code, "GB18030", 'G','B','1','8','0','3','0',0,0))
227     return msgid[0] == '`' ? "\xa1\ae": "\xa1\xaf";
228
229   return (s == clocale_quoting_style ? "\"" : "'");
230 }
231
232 /* Place into buffer BUFFER (of size BUFFERSIZE) a quoted version of
233    argument ARG (of size ARGSIZE), using QUOTING_STYLE, FLAGS, and
234    QUOTE_THESE_TOO to control quoting.
235    Terminate the output with a null character, and return the written
236    size of the output, not counting the terminating null.
237    If BUFFERSIZE is too small to store the output string, return the
238    value that would have been returned had BUFFERSIZE been large enough.
239    If ARGSIZE is SIZE_MAX, use the string length of the argument for ARGSIZE.
240
241    This function acts like quotearg_buffer (BUFFER, BUFFERSIZE, ARG,
242    ARGSIZE, O), except it breaks O into its component pieces and is
243    not careful about errno.  */
244
245 static size_t
246 quotearg_buffer_restyled (char *buffer, size_t buffersize,
247                           char const *arg, size_t argsize,
248                           enum quoting_style quoting_style, int flags,
249                           unsigned int const *quote_these_too,
250                           char const *left_quote,
251                           char const *right_quote)
252 {
253   size_t i;
254   size_t len = 0;
255   char const *quote_string = 0;
256   size_t quote_string_len = 0;
257   bool backslash_escapes = false;
258   bool unibyte_locale = MB_CUR_MAX == 1;
259   bool elide_outer_quotes = (flags & QA_ELIDE_OUTER_QUOTES) != 0;
260   bool pending_shell_escape_end = false;
261   bool encountered_single_quote = false;
262   bool all_c_and_shell_quote_compat = true;
263
264 #define STORE(c) \
265     do \
266       { \
267         if (len < buffersize) \
268           buffer[len] = (c); \
269         len++; \
270       } \
271     while (0)
272
273 #define START_ESC() \
274     do \
275       { \
276         if (elide_outer_quotes) \
277           goto force_outer_quoting_style; \
278         escaping = true; \
279         if (quoting_style == shell_always_quoting_style \
280             && ! pending_shell_escape_end) \
281           { \
282             STORE ('\''); \
283             STORE ('$'); \
284             STORE ('\''); \
285             pending_shell_escape_end = true; \
286           } \
287         STORE ('\\'); \
288       } \
289     while (0)
290
291 #define END_ESC() \
292     do \
293       { \
294         if (pending_shell_escape_end && ! escaping) \
295           { \
296             STORE ('\''); \
297             STORE ('\''); \
298             pending_shell_escape_end = false; \
299           } \
300       } \
301     while (0)
302
303   switch (quoting_style)
304     {
305     case c_maybe_quoting_style:
306       quoting_style = c_quoting_style;
307       elide_outer_quotes = true;
308       /* Fall through.  */
309     case c_quoting_style:
310       if (!elide_outer_quotes)
311         STORE ('"');
312       backslash_escapes = true;
313       quote_string = "\"";
314       quote_string_len = 1;
315       break;
316
317     case escape_quoting_style:
318       backslash_escapes = true;
319       elide_outer_quotes = false;
320       break;
321
322     case locale_quoting_style:
323     case clocale_quoting_style:
324     case custom_quoting_style:
325       {
326         if (quoting_style != custom_quoting_style)
327           {
328             /* TRANSLATORS:
329                Get translations for open and closing quotation marks.
330                The message catalog should translate "`" to a left
331                quotation mark suitable for the locale, and similarly for
332                "'".  For example, a French Unicode local should translate
333                these to U+00AB (LEFT-POINTING DOUBLE ANGLE
334                QUOTATION MARK), and U+00BB (RIGHT-POINTING DOUBLE ANGLE
335                QUOTATION MARK), respectively.
336
337                If the catalog has no translation, we will try to
338                use Unicode U+2018 (LEFT SINGLE QUOTATION MARK) and
339                Unicode U+2019 (RIGHT SINGLE QUOTATION MARK).  If the
340                current locale is not Unicode, locale_quoting_style
341                will quote 'like this', and clocale_quoting_style will
342                quote "like this".  You should always include translations
343                for "`" and "'" even if U+2018 and U+2019 are appropriate
344                for your locale.
345
346                If you don't know what to put here, please see
347                <http://en.wikipedia.org/wiki/Quotation_marks_in_other_languages>
348                and use glyphs suitable for your language.  */
349             left_quote = gettext_quote (N_("`"), quoting_style);
350             right_quote = gettext_quote (N_("'"), quoting_style);
351           }
352         if (!elide_outer_quotes)
353           for (quote_string = left_quote; *quote_string; quote_string++)
354             STORE (*quote_string);
355         backslash_escapes = true;
356         quote_string = right_quote;
357         quote_string_len = strlen (quote_string);
358       }
359       break;
360
361     case shell_escape_quoting_style:
362       backslash_escapes = true;
363       /* Fall through.  */
364     case shell_quoting_style:
365       elide_outer_quotes = true;
366       /* Fall through.  */
367     case shell_escape_always_quoting_style:
368       if (!elide_outer_quotes)
369         backslash_escapes = true;
370       /* Fall through.  */
371     case shell_always_quoting_style:
372       quoting_style = shell_always_quoting_style;
373       if (!elide_outer_quotes)
374         STORE ('\'');
375       quote_string = "'";
376       quote_string_len = 1;
377       break;
378
379     case literal_quoting_style:
380       elide_outer_quotes = false;
381       break;
382
383     default:
384       abort ();
385     }
386
387   for (i = 0;  ! (argsize == SIZE_MAX ? arg[i] == '\0' : i == argsize);  i++)
388     {
389       unsigned char c;
390       unsigned char esc;
391       bool is_right_quote = false;
392       bool escaping = false;
393       bool c_and_shell_quote_compat = false;
394
395       if (backslash_escapes
396           && quoting_style != shell_always_quoting_style
397           && quote_string_len
398           && (i + quote_string_len
399               <= (argsize == SIZE_MAX && 1 < quote_string_len
400                   /* Use strlen only if we must: when argsize is SIZE_MAX,
401                      and when the quote string is more than 1 byte long.
402                      If we do call strlen, save the result.  */
403                   ? (argsize = strlen (arg)) : argsize))
404           && memcmp (arg + i, quote_string, quote_string_len) == 0)
405         {
406           if (elide_outer_quotes)
407             goto force_outer_quoting_style;
408           is_right_quote = true;
409         }
410
411       c = arg[i];
412       switch (c)
413         {
414         case '\0':
415           if (backslash_escapes)
416             {
417               START_ESC ();
418               /* If quote_string were to begin with digits, we'd need to
419                  test for the end of the arg as well.  However, it's
420                  hard to imagine any locale that would use digits in
421                  quotes, and set_custom_quoting is documented not to
422                  accept them.  Use only a single \0 with shell-escape
423                  as currently digits are not printed within $'...'  */
424               if (quoting_style != shell_always_quoting_style
425                   && i + 1 < argsize && '0' <= arg[i + 1] && arg[i + 1] <= '9')
426                 {
427                   STORE ('0');
428                   STORE ('0');
429                 }
430               c = '0';
431               /* We don't have to worry that this last '0' will be
432                  backslash-escaped because, again, quote_string should
433                  not start with it and because quote_these_too is
434                  documented as not accepting it.  */
435             }
436           else if (flags & QA_ELIDE_NULL_BYTES)
437             continue;
438           break;
439
440         case '?':
441           switch (quoting_style)
442             {
443             case shell_always_quoting_style:
444               if (elide_outer_quotes)
445                 goto force_outer_quoting_style;
446               break;
447
448             case c_quoting_style:
449               if ((flags & QA_SPLIT_TRIGRAPHS)
450                   && i + 2 < argsize && arg[i + 1] == '?')
451                 switch (arg[i + 2])
452                   {
453                   case '!': case '\'':
454                   case '(': case ')': case '-': case '/':
455                   case '<': case '=': case '>':
456                     /* Escape the second '?' in what would otherwise be
457                        a trigraph.  */
458                     if (elide_outer_quotes)
459                       goto force_outer_quoting_style;
460                     c = arg[i + 2];
461                     i += 2;
462                     STORE ('?');
463                     STORE ('"');
464                     STORE ('"');
465                     STORE ('?');
466                     break;
467
468                   default:
469                     break;
470                   }
471               break;
472
473             default:
474               break;
475             }
476           break;
477
478         case '\a': esc = 'a'; goto c_escape;
479         case '\b': esc = 'b'; goto c_escape;
480         case '\f': esc = 'f'; goto c_escape;
481         case '\n': esc = 'n'; goto c_and_shell_escape;
482         case '\r': esc = 'r'; goto c_and_shell_escape;
483         case '\t': esc = 't'; goto c_and_shell_escape;
484         case '\v': esc = 'v'; goto c_escape;
485         case '\\': esc = c;
486           /* Never need to escape '\' in shell case.  */
487           if (quoting_style == shell_always_quoting_style)
488             {
489               if (elide_outer_quotes)
490                 goto force_outer_quoting_style;
491               goto store_c;
492             }
493
494           /* No need to escape the escape if we are trying to elide
495              outer quotes and nothing else is problematic.  */
496           if (backslash_escapes && elide_outer_quotes && quote_string_len)
497             goto store_c;
498
499         c_and_shell_escape:
500           if (quoting_style == shell_always_quoting_style
501               && elide_outer_quotes)
502             goto force_outer_quoting_style;
503           /* Fall through.  */
504         c_escape:
505           if (backslash_escapes)
506             {
507               c = esc;
508               goto store_escape;
509             }
510           break;
511
512         case '{': case '}': /* sometimes special if isolated */
513           if (! (argsize == SIZE_MAX ? arg[1] == '\0' : argsize == 1))
514             break;
515           /* Fall through.  */
516         case '#': case '~':
517           if (i != 0)
518             break;
519           /* Fall through.  */
520         case ' ':
521           c_and_shell_quote_compat = true;
522           /* Fall through.  */
523         case '!': /* special in bash */
524         case '"': case '$': case '&':
525         case '(': case ')': case '*': case ';':
526         case '<':
527         case '=': /* sometimes special in 0th or (with "set -k") later args */
528         case '>': case '[':
529         case '^': /* special in old /bin/sh, e.g. SunOS 4.1.4 */
530         case '`': case '|':
531           /* A shell special character.  In theory, '$' and '`' could
532              be the first bytes of multibyte characters, which means
533              we should check them with mbrtowc, but in practice this
534              doesn't happen so it's not worth worrying about.  */
535           if (quoting_style == shell_always_quoting_style
536               && elide_outer_quotes)
537             goto force_outer_quoting_style;
538           break;
539
540         case '\'':
541           encountered_single_quote = true;
542           c_and_shell_quote_compat = true;
543           if (quoting_style == shell_always_quoting_style)
544             {
545               if (elide_outer_quotes)
546                 goto force_outer_quoting_style;
547               STORE ('\'');
548               STORE ('\\');
549               STORE ('\'');
550               pending_shell_escape_end = false;
551             }
552           break;
553
554         case '%': case '+': case ',': case '-': case '.': case '/':
555         case '0': case '1': case '2': case '3': case '4': case '5':
556         case '6': case '7': case '8': case '9': case ':':
557         case 'A': case 'B': case 'C': case 'D': case 'E': case 'F':
558         case 'G': case 'H': case 'I': case 'J': case 'K': case 'L':
559         case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R':
560         case 'S': case 'T': case 'U': case 'V': case 'W': case 'X':
561         case 'Y': case 'Z': case ']': case '_': case 'a': case 'b':
562         case 'c': case 'd': case 'e': case 'f': case 'g': case 'h':
563         case 'i': case 'j': case 'k': case 'l': case 'm': case 'n':
564         case 'o': case 'p': case 'q': case 'r': case 's': case 't':
565         case 'u': case 'v': case 'w': case 'x': case 'y': case 'z':
566           /* These characters don't cause problems, no matter what the
567              quoting style is.  They cannot start multibyte sequences.
568              A digit or a special letter would cause trouble if it
569              appeared at the beginning of quote_string because we'd then
570              escape by prepending a backslash.  However, it's hard to
571              imagine any locale that would use digits or letters as
572              quotes, and set_custom_quoting is documented not to accept
573              them.  Also, a digit or a special letter would cause
574              trouble if it appeared in quote_these_too, but that's also
575              documented as not accepting them.  */
576           c_and_shell_quote_compat = true;
577           break;
578
579         default:
580           /* If we have a multibyte sequence, copy it until we reach
581              its end, find an error, or come back to the initial shift
582              state.  For C-like styles, if the sequence has
583              unprintable characters, escape the whole sequence, since
584              we can't easily escape single characters within it.  */
585           {
586             /* Length of multibyte sequence found so far.  */
587             size_t m;
588
589             bool printable;
590
591             if (unibyte_locale)
592               {
593                 m = 1;
594                 printable = isprint (c) != 0;
595               }
596             else
597               {
598                 mbstate_t mbstate;
599                 memset (&mbstate, 0, sizeof mbstate);
600
601                 m = 0;
602                 printable = true;
603                 if (argsize == SIZE_MAX)
604                   argsize = strlen (arg);
605
606                 do
607                   {
608                     wchar_t w;
609                     size_t bytes = mbrtowc (&w, &arg[i + m],
610                                             argsize - (i + m), &mbstate);
611                     if (bytes == 0)
612                       break;
613                     else if (bytes == (size_t) -1)
614                       {
615                         printable = false;
616                         break;
617                       }
618                     else if (bytes == (size_t) -2)
619                       {
620                         printable = false;
621                         while (i + m < argsize && arg[i + m])
622                           m++;
623                         break;
624                       }
625                     else
626                       {
627                         /* Work around a bug with older shells that "see" a '\'
628                            that is really the 2nd byte of a multibyte character.
629                            In practice the problem is limited to ASCII
630                            chars >= '@' that are shell special chars.  */
631                         if ('[' == 0x5b && elide_outer_quotes
632                             && quoting_style == shell_always_quoting_style)
633                           {
634                             size_t j;
635                             for (j = 1; j < bytes; j++)
636                               switch (arg[i + m + j])
637                                 {
638                                 case '[': case '\\': case '^':
639                                 case '`': case '|':
640                                   goto force_outer_quoting_style;
641
642                                 default:
643                                   break;
644                                 }
645                           }
646
647                         if (! iswprint (w))
648                           printable = false;
649                         m += bytes;
650                       }
651                   }
652                 while (! mbsinit (&mbstate));
653               }
654
655             c_and_shell_quote_compat = printable;
656
657             if (1 < m || (backslash_escapes && ! printable))
658               {
659                 /* Output a multibyte sequence, or an escaped
660                    unprintable unibyte character.  */
661                 size_t ilim = i + m;
662
663                 for (;;)
664                   {
665                     if (backslash_escapes && ! printable)
666                       {
667                         START_ESC ();
668                         STORE ('0' + (c >> 6));
669                         STORE ('0' + ((c >> 3) & 7));
670                         c = '0' + (c & 7);
671                       }
672                     else if (is_right_quote)
673                       {
674                         STORE ('\\');
675                         is_right_quote = false;
676                       }
677                     if (ilim <= i + 1)
678                       break;
679                     END_ESC ();
680                     STORE (c);
681                     c = arg[++i];
682                   }
683
684                 goto store_c;
685               }
686           }
687         }
688
689       if (! (((backslash_escapes && quoting_style != shell_always_quoting_style)
690               || elide_outer_quotes)
691              && quote_these_too
692              && quote_these_too[c / INT_BITS] >> (c % INT_BITS) & 1)
693           && !is_right_quote)
694         goto store_c;
695
696     store_escape:
697       START_ESC ();
698
699     store_c:
700       END_ESC ();
701       STORE (c);
702
703       if (! c_and_shell_quote_compat)
704         all_c_and_shell_quote_compat = false;
705     }
706
707   if (len == 0 && quoting_style == shell_always_quoting_style
708       && elide_outer_quotes)
709     goto force_outer_quoting_style;
710
711   /* Single shell quotes (') are commonly enough used as an apostrophe,
712      that we attempt to minimize the quoting in this case.  Note itʼs
713      better to use the apostrophe modifier "\u02BC" if possible, as that
714      renders better and works with the word match regex \W+ etc.  */
715   if (quoting_style == shell_always_quoting_style && ! elide_outer_quotes
716       && all_c_and_shell_quote_compat && encountered_single_quote)
717     return quotearg_buffer_restyled (buffer, buffersize, arg, argsize,
718                                      c_quoting_style,
719                                      flags, quote_these_too,
720                                      left_quote, right_quote);
721
722   if (quote_string && !elide_outer_quotes)
723     for (; *quote_string; quote_string++)
724       STORE (*quote_string);
725
726   if (len < buffersize)
727     buffer[len] = '\0';
728   return len;
729
730  force_outer_quoting_style:
731   /* Don't reuse quote_these_too, since the addition of outer quotes
732      sufficiently quotes the specified characters.  */
733   if (quoting_style == shell_always_quoting_style && backslash_escapes)
734     quoting_style = shell_escape_always_quoting_style;
735   return quotearg_buffer_restyled (buffer, buffersize, arg, argsize,
736                                    quoting_style,
737                                    flags & ~QA_ELIDE_OUTER_QUOTES, NULL,
738                                    left_quote, right_quote);
739 }
740
741 /* Place into buffer BUFFER (of size BUFFERSIZE) a quoted version of
742    argument ARG (of size ARGSIZE), using O to control quoting.
743    If O is null, use the default.
744    Terminate the output with a null character, and return the written
745    size of the output, not counting the terminating null.
746    If BUFFERSIZE is too small to store the output string, return the
747    value that would have been returned had BUFFERSIZE been large enough.
748    If ARGSIZE is SIZE_MAX, use the string length of the argument for
749    ARGSIZE.  */
750 size_t
751 quotearg_buffer (char *buffer, size_t buffersize,
752                  char const *arg, size_t argsize,
753                  struct quoting_options const *o)
754 {
755   struct quoting_options const *p = o ? o : &default_quoting_options;
756   int e = errno;
757   size_t r = quotearg_buffer_restyled (buffer, buffersize, arg, argsize,
758                                        p->style, p->flags, p->quote_these_too,
759                                        p->left_quote, p->right_quote);
760   errno = e;
761   return r;
762 }
763
764 /* Equivalent to quotearg_alloc (ARG, ARGSIZE, NULL, O).  */
765 char *
766 quotearg_alloc (char const *arg, size_t argsize,
767                 struct quoting_options const *o)
768 {
769   return quotearg_alloc_mem (arg, argsize, NULL, o);
770 }
771
772 /* Like quotearg_buffer (..., ARG, ARGSIZE, O), except return newly
773    allocated storage containing the quoted string, and store the
774    resulting size into *SIZE, if non-NULL.  The result can contain
775    embedded null bytes only if ARGSIZE is not SIZE_MAX, SIZE is not
776    NULL, and set_quoting_flags has not set the null byte elision
777    flag.  */
778 char *
779 quotearg_alloc_mem (char const *arg, size_t argsize, size_t *size,
780                     struct quoting_options const *o)
781 {
782   struct quoting_options const *p = o ? o : &default_quoting_options;
783   int e = errno;
784   /* Elide embedded null bytes if we can't return a size.  */
785   int flags = p->flags | (size ? 0 : QA_ELIDE_NULL_BYTES);
786   size_t bufsize = quotearg_buffer_restyled (0, 0, arg, argsize, p->style,
787                                              flags, p->quote_these_too,
788                                              p->left_quote,
789                                              p->right_quote) + 1;
790   char *buf = xcharalloc (bufsize);
791   quotearg_buffer_restyled (buf, bufsize, arg, argsize, p->style, flags,
792                             p->quote_these_too,
793                             p->left_quote, p->right_quote);
794   errno = e;
795   if (size)
796     *size = bufsize - 1;
797   return buf;
798 }
799
800 /* A storage slot with size and pointer to a value.  */
801 struct slotvec
802 {
803   size_t size;
804   char *val;
805 };
806
807 /* Preallocate a slot 0 buffer, so that the caller can always quote
808    one small component of a "memory exhausted" message in slot 0.  */
809 static char slot0[256];
810 static unsigned int nslots = 1;
811 static struct slotvec slotvec0 = {sizeof slot0, slot0};
812 static struct slotvec *slotvec = &slotvec0;
813
814 void
815 quotearg_free (void)
816 {
817   struct slotvec *sv = slotvec;
818   unsigned int i;
819   for (i = 1; i < nslots; i++)
820     free (sv[i].val);
821   if (sv[0].val != slot0)
822     {
823       free (sv[0].val);
824       slotvec0.size = sizeof slot0;
825       slotvec0.val = slot0;
826     }
827   if (sv != &slotvec0)
828     {
829       free (sv);
830       slotvec = &slotvec0;
831     }
832   nslots = 1;
833 }
834
835 /* Use storage slot N to return a quoted version of argument ARG.
836    ARG is of size ARGSIZE, but if that is SIZE_MAX, ARG is a
837    null-terminated string.
838    OPTIONS specifies the quoting options.
839    The returned value points to static storage that can be
840    reused by the next call to this function with the same value of N.
841    N must be nonnegative.  N is deliberately declared with type "int"
842    to allow for future extensions (using negative values).  */
843 static char *
844 quotearg_n_options (int n, char const *arg, size_t argsize,
845                     struct quoting_options const *options)
846 {
847   int e = errno;
848
849   unsigned int n0 = n;
850   struct slotvec *sv = slotvec;
851
852   if (n < 0)
853     abort ();
854
855   if (nslots <= n0)
856     {
857       /* FIXME: technically, the type of n1 should be 'unsigned int',
858          but that evokes an unsuppressible warning from gcc-4.0.1 and
859          older.  If gcc ever provides an option to suppress that warning,
860          revert to the original type, so that the test in xalloc_oversized
861          is once again performed only at compile time.  */
862       size_t n1 = n0 + 1;
863       bool preallocated = (sv == &slotvec0);
864
865       if (xalloc_oversized (n1, sizeof *sv))
866         xalloc_die ();
867
868       slotvec = sv = xrealloc (preallocated ? NULL : sv, n1 * sizeof *sv);
869       if (preallocated)
870         *sv = slotvec0;
871       memset (sv + nslots, 0, (n1 - nslots) * sizeof *sv);
872       nslots = n1;
873     }
874
875   {
876     size_t size = sv[n].size;
877     char *val = sv[n].val;
878     /* Elide embedded null bytes since we don't return a size.  */
879     int flags = options->flags | QA_ELIDE_NULL_BYTES;
880     size_t qsize = quotearg_buffer_restyled (val, size, arg, argsize,
881                                              options->style, flags,
882                                              options->quote_these_too,
883                                              options->left_quote,
884                                              options->right_quote);
885
886     if (size <= qsize)
887       {
888         sv[n].size = size = qsize + 1;
889         if (val != slot0)
890           free (val);
891         sv[n].val = val = xcharalloc (size);
892         quotearg_buffer_restyled (val, size, arg, argsize, options->style,
893                                   flags, options->quote_these_too,
894                                   options->left_quote,
895                                   options->right_quote);
896       }
897
898     errno = e;
899     return val;
900   }
901 }
902
903 char *
904 quotearg_n (int n, char const *arg)
905 {
906   return quotearg_n_options (n, arg, SIZE_MAX, &default_quoting_options);
907 }
908
909 char *
910 quotearg_n_mem (int n, char const *arg, size_t argsize)
911 {
912   return quotearg_n_options (n, arg, argsize, &default_quoting_options);
913 }
914
915 char *
916 quotearg (char const *arg)
917 {
918   return quotearg_n (0, arg);
919 }
920
921 char *
922 quotearg_mem (char const *arg, size_t argsize)
923 {
924   return quotearg_n_mem (0, arg, argsize);
925 }
926
927 char *
928 quotearg_n_style (int n, enum quoting_style s, char const *arg)
929 {
930   struct quoting_options const o = quoting_options_from_style (s);
931   return quotearg_n_options (n, arg, SIZE_MAX, &o);
932 }
933
934 char *
935 quotearg_n_style_mem (int n, enum quoting_style s,
936                       char const *arg, size_t argsize)
937 {
938   struct quoting_options const o = quoting_options_from_style (s);
939   return quotearg_n_options (n, arg, argsize, &o);
940 }
941
942 char *
943 quotearg_style (enum quoting_style s, char const *arg)
944 {
945   return quotearg_n_style (0, s, arg);
946 }
947
948 char *
949 quotearg_style_mem (enum quoting_style s, char const *arg, size_t argsize)
950 {
951   return quotearg_n_style_mem (0, s, arg, argsize);
952 }
953
954 char *
955 quotearg_char_mem (char const *arg, size_t argsize, char ch)
956 {
957   struct quoting_options options;
958   options = default_quoting_options;
959   set_char_quoting (&options, ch, 1);
960   return quotearg_n_options (0, arg, argsize, &options);
961 }
962
963 char *
964 quotearg_char (char const *arg, char ch)
965 {
966   return quotearg_char_mem (arg, SIZE_MAX, ch);
967 }
968
969 char *
970 quotearg_colon (char const *arg)
971 {
972   return quotearg_char (arg, ':');
973 }
974
975 char *
976 quotearg_colon_mem (char const *arg, size_t argsize)
977 {
978   return quotearg_char_mem (arg, argsize, ':');
979 }
980
981 char *
982 quotearg_n_style_colon (int n, enum quoting_style s, char const *arg)
983 {
984   struct quoting_options options;
985   options = quoting_options_from_style (s);
986   set_char_quoting (&options, ':', 1);
987   return quotearg_n_options (n, arg, SIZE_MAX, &options);
988 }
989
990 char *
991 quotearg_n_custom (int n, char const *left_quote,
992                    char const *right_quote, char const *arg)
993 {
994   return quotearg_n_custom_mem (n, left_quote, right_quote, arg,
995                                 SIZE_MAX);
996 }
997
998 char *
999 quotearg_n_custom_mem (int n, char const *left_quote,
1000                        char const *right_quote,
1001                        char const *arg, size_t argsize)
1002 {
1003   struct quoting_options o = default_quoting_options;
1004   set_custom_quoting (&o, left_quote, right_quote);
1005   return quotearg_n_options (n, arg, argsize, &o);
1006 }
1007
1008 char *
1009 quotearg_custom (char const *left_quote, char const *right_quote,
1010                  char const *arg)
1011 {
1012   return quotearg_n_custom (0, left_quote, right_quote, arg);
1013 }
1014
1015 char *
1016 quotearg_custom_mem (char const *left_quote, char const *right_quote,
1017                      char const *arg, size_t argsize)
1018 {
1019   return quotearg_n_custom_mem (0, left_quote, right_quote, arg,
1020                                 argsize);
1021 }
1022
1023
1024 /* The quoting option used by the functions of quote.h.  */
1025 struct quoting_options quote_quoting_options =
1026   {
1027     locale_quoting_style,
1028     0,
1029     { 0 },
1030     NULL, NULL
1031   };
1032
1033 char const *
1034 quote_n_mem (int n, char const *arg, size_t argsize)
1035 {
1036   return quotearg_n_options (n, arg, argsize, &quote_quoting_options);
1037 }
1038
1039 char const *
1040 quote_mem (char const *arg, size_t argsize)
1041 {
1042   return quote_n_mem (0, arg, argsize);
1043 }
1044
1045 char const *
1046 quote_n (int n, char const *arg)
1047 {
1048   return quote_n_mem (n, arg, SIZE_MAX);
1049 }
1050
1051 char const *
1052 quote (char const *arg)
1053 {
1054   return quote_n (0, arg);
1055 }