run copyright.sh for 2011.
[platform/upstream/binutils.git] / gdb / charset.c
1 /* Character set conversion support for GDB.
2
3    Copyright (C) 2001, 2003, 2007, 2008, 2009, 2010, 2011
4    Free Software Foundation, Inc.
5
6    This file is part of GDB.
7
8    This program is free software; you can redistribute it and/or modify
9    it under the terms of the GNU General Public License as published by
10    the Free Software Foundation; either version 3 of the License, or
11    (at your option) any later version.
12
13    This program is distributed in the hope that it will be useful,
14    but WITHOUT ANY WARRANTY; without even the implied warranty of
15    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16    GNU General Public License for more details.
17
18    You should have received a copy of the GNU General Public License
19    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
20
21 #include "defs.h"
22 #include "charset.h"
23 #include "gdbcmd.h"
24 #include "gdb_assert.h"
25 #include "gdb_obstack.h"
26 #include "gdb_wait.h"
27 #include "charset-list.h"
28 #include "vec.h"
29 #include "environ.h"
30 #include "arch-utils.h"
31
32 #include <stddef.h>
33 #include "gdb_string.h"
34 #include <ctype.h>
35
36 #ifdef USE_WIN32API
37 #include <windows.h>
38 #endif
39 \f
40 /* How GDB's character set support works
41
42    GDB has three global settings:
43
44    - The `current host character set' is the character set GDB should
45      use in talking to the user, and which (hopefully) the user's
46      terminal knows how to display properly.  Most users should not
47      change this.
48
49    - The `current target character set' is the character set the
50      program being debugged uses.
51
52    - The `current target wide character set' is the wide character set
53      the program being debugged uses, that is, the encoding used for
54      wchar_t.
55
56    There are commands to set each of these, and mechanisms for
57    choosing reasonable default values.  GDB has a global list of
58    character sets that it can use as its host or target character
59    sets.
60
61    The header file `charset.h' declares various functions that
62    different pieces of GDB need to perform tasks like:
63
64    - printing target strings and characters to the user's terminal
65      (mostly target->host conversions),
66
67    - building target-appropriate representations of strings and
68      characters the user enters in expressions (mostly host->target
69      conversions),
70
71      and so on.
72      
73    To avoid excessive code duplication and maintenance efforts,
74    GDB simply requires a capable iconv function.  Users on platforms
75    without a suitable iconv can use the GNU iconv library.  */
76
77 \f
78 #ifdef PHONY_ICONV
79
80 /* Provide a phony iconv that does as little as possible.  Also,
81    arrange for there to be a single available character set.  */
82
83 #undef GDB_DEFAULT_HOST_CHARSET
84 #define GDB_DEFAULT_HOST_CHARSET "ISO-8859-1"
85 #define GDB_DEFAULT_TARGET_CHARSET "ISO-8859-1"
86 #define GDB_DEFAULT_TARGET_WIDE_CHARSET "ISO-8859-1"
87 #undef DEFAULT_CHARSET_NAMES
88 #define DEFAULT_CHARSET_NAMES GDB_DEFAULT_HOST_CHARSET ,
89
90 #undef iconv_t
91 #define iconv_t int
92 #undef iconv_open
93 #define iconv_open phony_iconv_open
94 #undef iconv
95 #define iconv phony_iconv
96 #undef iconv_close
97 #define iconv_close phony_iconv_close
98
99 #undef ICONV_CONST
100 #define ICONV_CONST const
101
102 /* Some systems don't have EILSEQ, so we define it here, but not as
103    EINVAL, because callers of `iconv' want to distinguish EINVAL and
104    EILSEQ.  This is what iconv.h from libiconv does as well.  Note
105    that wchar.h may also define EILSEQ, so this needs to be after we
106    include wchar.h, which happens in defs.h through gdb_wchar.h.  */
107 #ifndef EILSEQ
108 #define EILSEQ ENOENT
109 #endif
110
111 iconv_t
112 phony_iconv_open (const char *to, const char *from)
113 {
114   /* We allow conversions from UTF-32BE, wchar_t, and the host charset.
115      We allow conversions to wchar_t and the host charset.  */
116   if (strcmp (from, "UTF-32BE") && strcmp (from, "wchar_t")
117       && strcmp (from, GDB_DEFAULT_HOST_CHARSET))
118     return -1;
119   if (strcmp (to, "wchar_t") && strcmp (to, GDB_DEFAULT_HOST_CHARSET))
120     return -1;
121
122   /* Return 1 if we are converting from UTF-32BE, 0 otherwise.  This is
123      used as a flag in calls to iconv.  */
124   return !strcmp (from, "UTF-32BE");
125 }
126
127 int
128 phony_iconv_close (iconv_t arg)
129 {
130   return 0;
131 }
132
133 size_t
134 phony_iconv (iconv_t utf_flag, const char **inbuf, size_t *inbytesleft,
135              char **outbuf, size_t *outbytesleft)
136 {
137   if (utf_flag)
138     {
139       while (*inbytesleft >= 4)
140         {
141           size_t j;
142           unsigned long c = 0;
143
144           for (j = 0; j < 4; ++j)
145             {
146               c <<= 8;
147               c += (*inbuf)[j] & 0xff;
148             }
149
150           if (c >= 256)
151             {
152               errno = EILSEQ;
153               return -1;
154             }
155           **outbuf = c & 0xff;
156           ++*outbuf;
157           --*outbytesleft;
158
159           ++*inbuf;
160           *inbytesleft -= 4;
161         }
162       if (*inbytesleft < 4)
163         {
164           errno = EINVAL;
165           return -1;
166         }
167     }
168   else
169     {
170       /* In all other cases we simply copy input bytes to the
171          output.  */
172       size_t amt = *inbytesleft;
173
174       if (amt > *outbytesleft)
175         amt = *outbytesleft;
176       memcpy (*outbuf, *inbuf, amt);
177       *inbuf += amt;
178       *outbuf += amt;
179       *inbytesleft -= amt;
180       *outbytesleft -= amt;
181     }
182
183   if (*inbytesleft)
184     {
185       errno = E2BIG;
186       return -1;
187     }
188
189   /* The number of non-reversible conversions -- but they were all
190      reversible.  */
191   return 0;
192 }
193
194 #endif
195
196
197 \f
198 /* The global lists of character sets and translations.  */
199
200
201 #ifndef GDB_DEFAULT_TARGET_CHARSET
202 #define GDB_DEFAULT_TARGET_CHARSET "ISO-8859-1"
203 #endif
204
205 #ifndef GDB_DEFAULT_TARGET_WIDE_CHARSET
206 #define GDB_DEFAULT_TARGET_WIDE_CHARSET "UTF-32"
207 #endif
208
209 static const char *auto_host_charset_name = GDB_DEFAULT_HOST_CHARSET;
210 static const char *host_charset_name = "auto";
211 static void
212 show_host_charset_name (struct ui_file *file, int from_tty,
213                         struct cmd_list_element *c,
214                         const char *value)
215 {
216   if (!strcmp (value, "auto"))
217     fprintf_filtered (file,
218                       _("The host character set is \"auto; currently %s\".\n"),
219                       auto_host_charset_name);
220   else
221     fprintf_filtered (file, _("The host character set is \"%s\".\n"), value);
222 }
223
224 static const char *target_charset_name = "auto";
225 static void
226 show_target_charset_name (struct ui_file *file, int from_tty,
227                           struct cmd_list_element *c, const char *value)
228 {
229   if (!strcmp (value, "auto"))
230     fprintf_filtered (file,
231                       _("The target character set is \"auto; "
232                         "currently %s\".\n"),
233                       gdbarch_auto_charset (get_current_arch ()));
234   else
235     fprintf_filtered (file, _("The target character set is \"%s\".\n"),
236                       value);
237 }
238
239 static const char *target_wide_charset_name = "auto";
240 static void
241 show_target_wide_charset_name (struct ui_file *file, 
242                                int from_tty,
243                                struct cmd_list_element *c, 
244                                const char *value)
245 {
246   if (!strcmp (value, "auto"))
247     fprintf_filtered (file,
248                       _("The target wide character set is \"auto; "
249                         "currently %s\".\n"),
250                       gdbarch_auto_wide_charset (get_current_arch ()));
251   else
252     fprintf_filtered (file, _("The target wide character set is \"%s\".\n"),
253                       value);
254 }
255
256 static const char *default_charset_names[] =
257 {
258   DEFAULT_CHARSET_NAMES
259   0
260 };
261
262 static const char **charset_enum;
263
264 \f
265 /* If the target wide character set has big- or little-endian
266    variants, these are the corresponding names.  */
267 static const char *target_wide_charset_be_name;
268 static const char *target_wide_charset_le_name;
269
270 /* The architecture for which the BE- and LE-names are valid.  */
271 static struct gdbarch *be_le_arch;
272
273 /* A helper function which sets the target wide big- and little-endian
274    character set names, if possible.  */
275
276 static void
277 set_be_le_names (struct gdbarch *gdbarch)
278 {
279   int i, len;
280   const char *target_wide;
281
282   if (be_le_arch == gdbarch)
283     return;
284   be_le_arch = gdbarch;
285
286   target_wide_charset_le_name = NULL;
287   target_wide_charset_be_name = NULL;
288
289   target_wide = target_wide_charset_name;
290   if (!strcmp (target_wide, "auto"))
291     target_wide = gdbarch_auto_wide_charset (gdbarch);
292
293   len = strlen (target_wide);
294   for (i = 0; charset_enum[i]; ++i)
295     {
296       if (strncmp (target_wide, charset_enum[i], len))
297         continue;
298       if ((charset_enum[i][len] == 'B'
299            || charset_enum[i][len] == 'L')
300           && charset_enum[i][len + 1] == 'E'
301           && charset_enum[i][len + 2] == '\0')
302         {
303           if (charset_enum[i][len] == 'B')
304             target_wide_charset_be_name = charset_enum[i];
305           else
306             target_wide_charset_le_name = charset_enum[i];
307         }
308     }
309 }
310
311 /* 'Set charset', 'set host-charset', 'set target-charset', 'set
312    target-wide-charset', 'set charset' sfunc's.  */
313
314 static void
315 validate (struct gdbarch *gdbarch)
316 {
317   iconv_t desc;
318   const char *host_cset = host_charset ();
319   const char *target_cset = target_charset (gdbarch);
320   const char *target_wide_cset = target_wide_charset_name;
321
322   if (!strcmp (target_wide_cset, "auto"))
323     target_wide_cset = gdbarch_auto_wide_charset (gdbarch);
324
325   desc = iconv_open (target_wide_cset, host_cset);
326   if (desc == (iconv_t) -1)
327     error ("Cannot convert between character sets `%s' and `%s'",
328            target_wide_cset, host_cset);
329   iconv_close (desc);
330
331   desc = iconv_open (target_cset, host_cset);
332   if (desc == (iconv_t) -1)
333     error ("Cannot convert between character sets `%s' and `%s'",
334            target_cset, host_cset);
335   iconv_close (desc);
336
337   /* Clear the cache.  */
338   be_le_arch = NULL;
339 }
340
341 /* This is the sfunc for the 'set charset' command.  */
342 static void
343 set_charset_sfunc (char *charset, int from_tty, 
344                    struct cmd_list_element *c)
345 {
346   /* CAREFUL: set the target charset here as well.  */
347   target_charset_name = host_charset_name;
348   validate (get_current_arch ());
349 }
350
351 /* 'set host-charset' command sfunc.  We need a wrapper here because
352    the function needs to have a specific signature.  */
353 static void
354 set_host_charset_sfunc (char *charset, int from_tty,
355                         struct cmd_list_element *c)
356 {
357   validate (get_current_arch ());
358 }
359
360 /* Wrapper for the 'set target-charset' command.  */
361 static void
362 set_target_charset_sfunc (char *charset, int from_tty,
363                           struct cmd_list_element *c)
364 {
365   validate (get_current_arch ());
366 }
367
368 /* Wrapper for the 'set target-wide-charset' command.  */
369 static void
370 set_target_wide_charset_sfunc (char *charset, int from_tty,
371                                struct cmd_list_element *c)
372 {
373   validate (get_current_arch ());
374 }
375
376 /* sfunc for the 'show charset' command.  */
377 static void
378 show_charset (struct ui_file *file, int from_tty, 
379               struct cmd_list_element *c,
380               const char *name)
381 {
382   show_host_charset_name (file, from_tty, c, host_charset_name);
383   show_target_charset_name (file, from_tty, c, target_charset_name);
384   show_target_wide_charset_name (file, from_tty, c, 
385                                  target_wide_charset_name);
386 }
387
388 \f
389 /* Accessor functions.  */
390
391 const char *
392 host_charset (void)
393 {
394   if (!strcmp (host_charset_name, "auto"))
395     return auto_host_charset_name;
396   return host_charset_name;
397 }
398
399 const char *
400 target_charset (struct gdbarch *gdbarch)
401 {
402   if (!strcmp (target_charset_name, "auto"))
403     return gdbarch_auto_charset (gdbarch);
404   return target_charset_name;
405 }
406
407 const char *
408 target_wide_charset (struct gdbarch *gdbarch)
409 {
410   enum bfd_endian byte_order = gdbarch_byte_order (gdbarch);
411
412   set_be_le_names (gdbarch);
413   if (byte_order == BFD_ENDIAN_BIG)
414     {
415       if (target_wide_charset_be_name)
416         return target_wide_charset_be_name;
417     }
418   else
419     {
420       if (target_wide_charset_le_name)
421         return target_wide_charset_le_name;
422     }
423
424   if (!strcmp (target_wide_charset_name, "auto"))
425     return gdbarch_auto_wide_charset (gdbarch);
426
427   return target_wide_charset_name;
428 }
429
430 \f
431 /* Host character set management.  For the time being, we assume that
432    the host character set is some superset of ASCII.  */
433
434 char
435 host_letter_to_control_character (char c)
436 {
437   if (c == '?')
438     return 0177;
439   return c & 0237;
440 }
441
442 /* Convert a host character, C, to its hex value.  C must already have
443    been validated using isxdigit.  */
444
445 int
446 host_hex_value (char c)
447 {
448   if (isdigit (c))
449     return c - '0';
450   if (c >= 'a' && c <= 'f')
451     return 10 + c - 'a';
452   gdb_assert (c >= 'A' && c <= 'F');
453   return 10 + c - 'A';
454 }
455
456 \f
457 /* Public character management functions.  */
458
459 /* A cleanup function which is run to close an iconv descriptor.  */
460
461 static void
462 cleanup_iconv (void *p)
463 {
464   iconv_t *descp = p;
465   iconv_close (*descp);
466 }
467
468 void
469 convert_between_encodings (const char *from, const char *to,
470                            const gdb_byte *bytes, unsigned int num_bytes,
471                            int width, struct obstack *output,
472                            enum transliterations translit)
473 {
474   iconv_t desc;
475   struct cleanup *cleanups;
476   size_t inleft;
477   char *inp;
478   unsigned int space_request;
479
480   /* Often, the host and target charsets will be the same.  */
481   if (!strcmp (from, to))
482     {
483       obstack_grow (output, bytes, num_bytes);
484       return;
485     }
486
487   desc = iconv_open (to, from);
488   if (desc == (iconv_t) -1)
489     perror_with_name ("Converting character sets");
490   cleanups = make_cleanup (cleanup_iconv, &desc);
491
492   inleft = num_bytes;
493   inp = (char *) bytes;
494
495   space_request = num_bytes;
496
497   while (inleft > 0)
498     {
499       char *outp;
500       size_t outleft, r;
501       int old_size;
502
503       old_size = obstack_object_size (output);
504       obstack_blank (output, space_request);
505
506       outp = obstack_base (output) + old_size;
507       outleft = space_request;
508
509       r = iconv (desc, (ICONV_CONST char **) &inp, &inleft, &outp, &outleft);
510
511       /* Now make sure that the object on the obstack only includes
512          bytes we have converted.  */
513       obstack_blank (output, - (int) outleft);
514
515       if (r == (size_t) -1)
516         {
517           switch (errno)
518             {
519             case EILSEQ:
520               {
521                 int i;
522
523                 /* Invalid input sequence.  */
524                 if (translit == translit_none)
525                   error (_("Could not convert character to `%s' character set"),
526                          to);
527
528                 /* We emit escape sequence for the bytes, skip them,
529                    and try again.  */
530                 for (i = 0; i < width; ++i)
531                   {
532                     char octal[5];
533
534                     sprintf (octal, "\\%.3o", *inp & 0xff);
535                     obstack_grow_str (output, octal);
536
537                     ++inp;
538                     --inleft;
539                   }
540               }
541               break;
542
543             case E2BIG:
544               /* We ran out of space in the output buffer.  Make it
545                  bigger next time around.  */
546               space_request *= 2;
547               break;
548
549             case EINVAL:
550               /* Incomplete input sequence.  FIXME: ought to report this
551                  to the caller somehow.  */
552               inleft = 0;
553               break;
554
555             default:
556               perror_with_name ("Internal error while converting character sets");
557             }
558         }
559     }
560
561   do_cleanups (cleanups);
562 }
563
564 \f
565
566 /* An iterator that returns host wchar_t's from a target string.  */
567 struct wchar_iterator
568 {
569   /* The underlying iconv descriptor.  */
570   iconv_t desc;
571
572   /* The input string.  This is updated as convert characters.  */
573   char *input;
574   /* The number of bytes remaining in the input.  */
575   size_t bytes;
576
577   /* The width of an input character.  */
578   size_t width;
579
580   /* The output buffer and its size.  */
581   gdb_wchar_t *out;
582   size_t out_size;
583 };
584
585 /* Create a new iterator.  */
586 struct wchar_iterator *
587 make_wchar_iterator (const gdb_byte *input, size_t bytes, 
588                      const char *charset, size_t width)
589 {
590   struct wchar_iterator *result;
591   iconv_t desc;
592
593   desc = iconv_open (INTERMEDIATE_ENCODING, charset);
594   if (desc == (iconv_t) -1)
595     perror_with_name ("Converting character sets");
596
597   result = XNEW (struct wchar_iterator);
598   result->desc = desc;
599   result->input = (char *) input;
600   result->bytes = bytes;
601   result->width = width;
602
603   result->out = XNEW (gdb_wchar_t);
604   result->out_size = 1;
605
606   return result;
607 }
608
609 static void
610 do_cleanup_iterator (void *p)
611 {
612   struct wchar_iterator *iter = p;
613
614   iconv_close (iter->desc);
615   xfree (iter->out);
616   xfree (iter);
617 }
618
619 struct cleanup *
620 make_cleanup_wchar_iterator (struct wchar_iterator *iter)
621 {
622   return make_cleanup (do_cleanup_iterator, iter);
623 }
624
625 int
626 wchar_iterate (struct wchar_iterator *iter,
627                enum wchar_iterate_result *out_result,
628                gdb_wchar_t **out_chars,
629                const gdb_byte **ptr,
630                size_t *len)
631 {
632   size_t out_request;
633
634   /* Try to convert some characters.  At first we try to convert just
635      a single character.  The reason for this is that iconv does not
636      necessarily update its outgoing arguments when it encounters an
637      invalid input sequence -- but we want to reliably report this to
638      our caller so it can emit an escape sequence.  */
639   out_request = 1;
640   while (iter->bytes > 0)
641     {
642       char *outptr = (char *) &iter->out[0];
643       char *orig_inptr = iter->input;
644       size_t orig_in = iter->bytes;
645       size_t out_avail = out_request * sizeof (gdb_wchar_t);
646       size_t num;
647       size_t r = iconv (iter->desc,
648                         (ICONV_CONST char **) &iter->input, 
649                         &iter->bytes, &outptr, &out_avail);
650
651       if (r == (size_t) -1)
652         {
653           switch (errno)
654             {
655             case EILSEQ:
656               /* Invalid input sequence.  We still might have
657                  converted a character; if so, return it.  */
658               if (out_avail < out_request * sizeof (gdb_wchar_t))
659                 break;
660               
661               /* Otherwise skip the first invalid character, and let
662                  the caller know about it.  */
663               *out_result = wchar_iterate_invalid;
664               *ptr = iter->input;
665               *len = iter->width;
666               iter->input += iter->width;
667               iter->bytes -= iter->width;
668               return 0;
669
670             case E2BIG:
671               /* We ran out of space.  We still might have converted a
672                  character; if so, return it.  Otherwise, grow the
673                  buffer and try again.  */
674               if (out_avail < out_request * sizeof (gdb_wchar_t))
675                 break;
676
677               ++out_request;
678               if (out_request > iter->out_size)
679                 {
680                   iter->out_size = out_request;
681                   iter->out = xrealloc (iter->out,
682                                         out_request * sizeof (gdb_wchar_t));
683                 }
684               continue;
685
686             case EINVAL:
687               /* Incomplete input sequence.  Let the caller know, and
688                  arrange for future calls to see EOF.  */
689               *out_result = wchar_iterate_incomplete;
690               *ptr = iter->input;
691               *len = iter->bytes;
692               iter->bytes = 0;
693               return 0;
694
695             default:
696               perror_with_name ("Internal error while converting character sets");
697             }
698         }
699
700       /* We converted something.  */
701       num = out_request - out_avail / sizeof (gdb_wchar_t);
702       *out_result = wchar_iterate_ok;
703       *out_chars = iter->out;
704       *ptr = orig_inptr;
705       *len = orig_in - iter->bytes;
706       return num;
707     }
708
709   /* Really done.  */
710   *out_result = wchar_iterate_eof;
711   return -1;
712 }
713
714 \f
715 /* The charset.c module initialization function.  */
716
717 extern initialize_file_ftype _initialize_charset; /* -Wmissing-prototype */
718
719 DEF_VEC_P (char_ptr);
720
721 static VEC (char_ptr) *charsets;
722
723 #ifdef PHONY_ICONV
724
725 static void
726 find_charset_names (void)
727 {
728   VEC_safe_push (char_ptr, charsets, GDB_DEFAULT_HOST_CHARSET);
729   VEC_safe_push (char_ptr, charsets, NULL);
730 }
731
732 #else /* PHONY_ICONV */
733
734 /* Sometimes, libiconv redefines iconvlist as libiconvlist -- but
735    provides different symbols in the static and dynamic libraries.
736    So, configure may see libiconvlist but not iconvlist.  But, calling
737    iconvlist is the right thing to do and will work.  Hence we do a
738    check here but unconditionally call iconvlist below.  */
739 #if defined (HAVE_ICONVLIST) || defined (HAVE_LIBICONVLIST)
740
741 /* A helper function that adds some character sets to the vector of
742    all character sets.  This is a callback function for iconvlist.  */
743
744 static int
745 add_one (unsigned int count, const char *const *names, void *data)
746 {
747   unsigned int i;
748
749   for (i = 0; i < count; ++i)
750     VEC_safe_push (char_ptr, charsets, xstrdup (names[i]));
751
752   return 0;
753 }
754
755 static void
756 find_charset_names (void)
757 {
758   iconvlist (add_one, NULL);
759   VEC_safe_push (char_ptr, charsets, NULL);
760 }
761
762 #else
763
764 /* Return non-zero if LINE (output from iconv) should be ignored.
765    Older iconv programs (e.g. 2.2.2) include the human readable
766    introduction even when stdout is not a tty.  Newer versions omit
767    the intro if stdout is not a tty.  */
768
769 static int
770 ignore_line_p (const char *line)
771 {
772   /* This table is used to filter the output.  If this text appears
773      anywhere in the line, it is ignored (strstr is used).  */
774   static const char * const ignore_lines[] =
775     {
776       "The following",
777       "not necessarily",
778       "the FROM and TO",
779       "listed with several",
780       NULL
781     };
782   int i;
783
784   for (i = 0; ignore_lines[i] != NULL; ++i)
785     {
786       if (strstr (line, ignore_lines[i]) != NULL)
787         return 1;
788     }
789
790   return 0;
791 }
792
793 static void
794 find_charset_names (void)
795 {
796   struct pex_obj *child;
797   char *args[3];
798   int err, status;
799   int fail = 1;
800   struct gdb_environ *iconv_env;
801
802   /* Older iconvs, e.g. 2.2.2, don't omit the intro text if stdout is
803      not a tty.  We need to recognize it and ignore it.  This text is
804      subject to translation, so force LANGUAGE=C.  */
805   iconv_env = make_environ ();
806   init_environ (iconv_env);
807   set_in_environ (iconv_env, "LANGUAGE", "C");
808   set_in_environ (iconv_env, "LC_ALL", "C");
809
810   child = pex_init (PEX_USE_PIPES, "iconv", NULL);
811
812   args[0] = "iconv";
813   args[1] = "-l";
814   args[2] = NULL;
815   /* Note that we simply ignore errors here.  */
816   if (!pex_run_in_environment (child, PEX_SEARCH | PEX_STDERR_TO_STDOUT,
817                                "iconv", args, environ_vector (iconv_env),
818                                NULL, NULL, &err))
819     {
820       FILE *in = pex_read_output (child, 0);
821
822       /* POSIX says that iconv -l uses an unspecified format.  We
823          parse the glibc and libiconv formats; feel free to add others
824          as needed.  */
825
826       while (!feof (in))
827         {
828           /* The size of buf is chosen arbitrarily.  */
829           char buf[1024];
830           char *start, *r;
831           int len;
832
833           r = fgets (buf, sizeof (buf), in);
834           if (!r)
835             break;
836           len = strlen (r);
837           if (len <= 3)
838             continue;
839           if (ignore_line_p (r))
840             continue;
841
842           /* Strip off the newline.  */
843           --len;
844           /* Strip off one or two '/'s.  glibc will print lines like
845              "8859_7//", but also "10646-1:1993/UCS4/".  */
846           if (buf[len - 1] == '/')
847             --len;
848           if (buf[len - 1] == '/')
849             --len;
850           buf[len] = '\0';
851
852           /* libiconv will print multiple entries per line, separated
853              by spaces.  Older iconvs will print multiple entries per
854              line, indented by two spaces, and separated by ", "
855              (i.e. the human readable form).  */
856           start = buf;
857           while (1)
858             {
859               int keep_going;
860               char *p;
861
862               /* Skip leading blanks.  */
863               for (p = start; *p && *p == ' '; ++p)
864                 ;
865               start = p;
866               /* Find the next space, comma, or end-of-line.  */
867               for ( ; *p && *p != ' ' && *p != ','; ++p)
868                 ;
869               /* Ignore an empty result.  */
870               if (p == start)
871                 break;
872               keep_going = *p;
873               *p = '\0';
874               VEC_safe_push (char_ptr, charsets, xstrdup (start));
875               if (!keep_going)
876                 break;
877               /* Skip any extra spaces.  */
878               for (start = p + 1; *start && *start == ' '; ++start)
879                 ;
880             }
881         }
882
883       if (pex_get_status (child, 1, &status)
884           && WIFEXITED (status) && !WEXITSTATUS (status))
885         fail = 0;
886
887     }
888
889   pex_free (child);
890   free_environ (iconv_env);
891
892   if (fail)
893     {
894       /* Some error occurred, so drop the vector.  */
895       int ix;
896       char *elt;
897       for (ix = 0; VEC_iterate (char_ptr, charsets, ix, elt); ++ix)
898         xfree (elt);
899       VEC_truncate (char_ptr, charsets, 0);
900     }
901   else
902     VEC_safe_push (char_ptr, charsets, NULL);
903 }
904
905 #endif /* HAVE_ICONVLIST || HAVE_LIBICONVLIST */
906 #endif /* PHONY_ICONV */
907
908 /* The "auto" target charset used by default_auto_charset.  */
909 static const char *auto_target_charset_name = GDB_DEFAULT_TARGET_CHARSET;
910
911 const char *
912 default_auto_charset (void)
913 {
914   return auto_target_charset_name;
915 }
916
917 const char *
918 default_auto_wide_charset (void)
919 {
920   return GDB_DEFAULT_TARGET_WIDE_CHARSET;
921 }
922
923 void
924 _initialize_charset (void)
925 {
926   /* The first element is always "auto".  */
927   VEC_safe_push (char_ptr, charsets, xstrdup ("auto"));
928   find_charset_names ();
929
930   if (VEC_length (char_ptr, charsets) > 1)
931     charset_enum = (const char **) VEC_address (char_ptr, charsets);
932   else
933     charset_enum = default_charset_names;
934
935 #ifndef PHONY_ICONV
936 #ifdef HAVE_LANGINFO_CODESET
937   /* The result of nl_langinfo may be overwritten later.  This may
938      leak a little memory, if the user later changes the host charset,
939      but that doesn't matter much.  */
940   auto_host_charset_name = xstrdup (nl_langinfo (CODESET));
941   /* Solaris will return `646' here -- but the Solaris iconv then does
942      not accept this.  Darwin (and maybe FreeBSD) may return "" here,
943      which GNU libiconv doesn't like (infinite loop).  */
944   if (!strcmp (auto_host_charset_name, "646") || !*auto_host_charset_name)
945     auto_host_charset_name = "ASCII";
946   auto_target_charset_name = auto_host_charset_name;
947 #elif defined (USE_WIN32API)
948   {
949     static char w32_host_default_charset[16]; /* "CP" + x<=5 digits + paranoia.  */
950
951     snprintf (w32_host_default_charset, sizeof w32_host_default_charset,
952               "CP%d", GetACP());
953     auto_host_charset_name = w32_host_default_charset;
954     auto_target_charset_name = auto_host_charset_name;
955   }
956 #endif
957 #endif
958
959   add_setshow_enum_cmd ("charset", class_support,
960                         charset_enum, &host_charset_name, _("\
961 Set the host and target character sets."), _("\
962 Show the host and target character sets."), _("\
963 The `host character set' is the one used by the system GDB is running on.\n\
964 The `target character set' is the one used by the program being debugged.\n\
965 You may only use supersets of ASCII for your host character set; GDB does\n\
966 not support any others.\n\
967 To see a list of the character sets GDB supports, type `set charset <TAB>'."),
968                         /* Note that the sfunc below needs to set
969                            target_charset_name, because the 'set
970                            charset' command sets two variables.  */
971                         set_charset_sfunc,
972                         show_charset,
973                         &setlist, &showlist);
974
975   add_setshow_enum_cmd ("host-charset", class_support,
976                         charset_enum, &host_charset_name, _("\
977 Set the host character set."), _("\
978 Show the host character set."), _("\
979 The `host character set' is the one used by the system GDB is running on.\n\
980 You may only use supersets of ASCII for your host character set; GDB does\n\
981 not support any others.\n\
982 To see a list of the character sets GDB supports, type `set host-charset <TAB>'."),
983                         set_host_charset_sfunc,
984                         show_host_charset_name,
985                         &setlist, &showlist);
986
987   add_setshow_enum_cmd ("target-charset", class_support,
988                         charset_enum, &target_charset_name, _("\
989 Set the target character set."), _("\
990 Show the target character set."), _("\
991 The `target character set' is the one used by the program being debugged.\n\
992 GDB translates characters and strings between the host and target\n\
993 character sets as needed.\n\
994 To see a list of the character sets GDB supports, type `set target-charset'<TAB>"),
995                         set_target_charset_sfunc,
996                         show_target_charset_name,
997                         &setlist, &showlist);
998
999   add_setshow_enum_cmd ("target-wide-charset", class_support,
1000                         charset_enum, &target_wide_charset_name,
1001                         _("\
1002 Set the target wide character set."), _("\
1003 Show the target wide character set."), _("\
1004 The `target wide character set' is the one used by the program being debugged.\n\
1005 In particular it is the encoding used by `wchar_t'.\n\
1006 GDB translates characters and strings between the host and target\n\
1007 character sets as needed.\n\
1008 To see a list of the character sets GDB supports, type\n\
1009 `set target-wide-charset'<TAB>"),
1010                         set_target_wide_charset_sfunc,
1011                         show_target_wide_charset_name,
1012                         &setlist, &showlist);
1013 }