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