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