gdb/utils.c - gdb

Global variables defined

Data types defined

Functions defined

Macros defined

Source code

  1. /* General utility routines for GDB, the GNU debugger.

  2.    Copyright (C) 1986-2015 Free Software Foundation, Inc.

  3.    This file is part of GDB.

  4.    This program is free software; you can redistribute it and/or modify
  5.    it under the terms of the GNU General Public License as published by
  6.    the Free Software Foundation; either version 3 of the License, or
  7.    (at your option) any later version.

  8.    This program is distributed in the hope that it will be useful,
  9.    but WITHOUT ANY WARRANTY; without even the implied warranty of
  10.    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  11.    GNU General Public License for more details.

  12.    You should have received a copy of the GNU General Public License
  13.    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */

  14. #include "defs.h"
  15. #include "dyn-string.h"
  16. #include <ctype.h>
  17. #include "gdb_wait.h"
  18. #include "event-top.h"
  19. #include "gdbthread.h"
  20. #include "fnmatch.h"
  21. #include "gdb_bfd.h"
  22. #ifdef HAVE_SYS_RESOURCE_H
  23. #include <sys/resource.h>
  24. #endif /* HAVE_SYS_RESOURCE_H */

  25. #ifdef TUI
  26. #include "tui/tui.h"                /* For tui_get_command_dimension.   */
  27. #endif

  28. #ifdef __GO32__
  29. #include <pc.h>
  30. #endif

  31. #include <signal.h>
  32. #include "timeval-utils.h"
  33. #include "gdbcmd.h"
  34. #include "serial.h"
  35. #include "bfd.h"
  36. #include "target.h"
  37. #include "gdb-demangle.h"
  38. #include "expression.h"
  39. #include "language.h"
  40. #include "charset.h"
  41. #include "annotate.h"
  42. #include "filenames.h"
  43. #include "symfile.h"
  44. #include "gdb_obstack.h"
  45. #include "gdbcore.h"
  46. #include "top.h"
  47. #include "main.h"
  48. #include "solist.h"

  49. #include "inferior.h"                /* for signed_pointer_to_address */

  50. #include "gdb_curses.h"

  51. #include "readline/readline.h"

  52. #include <sys/time.h>
  53. #include <time.h>

  54. #include "gdb_usleep.h"
  55. #include "interps.h"
  56. #include "gdb_regex.h"

  57. #if !HAVE_DECL_MALLOC
  58. extern PTR malloc ();                /* ARI: PTR */
  59. #endif
  60. #if !HAVE_DECL_REALLOC
  61. extern PTR realloc ();                /* ARI: PTR */
  62. #endif
  63. #if !HAVE_DECL_FREE
  64. extern void free ();
  65. #endif

  66. void (*deprecated_error_begin_hook) (void);

  67. /* Prototypes for local functions */

  68. static void vfprintf_maybe_filtered (struct ui_file *, const char *,
  69.                                      va_list, int) ATTRIBUTE_PRINTF (2, 0);

  70. static void fputs_maybe_filtered (const char *, struct ui_file *, int);

  71. static void prompt_for_continue (void);

  72. static void set_screen_size (void);
  73. static void set_width (void);

  74. /* Time spent in prompt_for_continue in the currently executing command
  75.    waiting for user to respond.
  76.    Initialized in make_command_stats_cleanup.
  77.    Modified in prompt_for_continue and defaulted_query.
  78.    Used in report_command_stats.  */

  79. static struct timeval prompt_for_continue_wait_time;

  80. /* A flag indicating whether to timestamp debugging messages.  */

  81. static int debug_timestamp = 0;

  82. /* Nonzero if we have job control.  */

  83. int job_control;

  84. /* Nonzero means quit immediately if Control-C is typed now, rather
  85.    than waiting until QUIT is executed.  Be careful in setting this;
  86.    code which executes with immediate_quit set has to be very careful
  87.    about being able to deal with being interrupted at any time.  It is
  88.    almost always better to use QUIT; the only exception I can think of
  89.    is being able to quit out of a system call (using EINTR loses if
  90.    the SIGINT happens between the previous QUIT and the system call).
  91.    To immediately quit in the case in which a SIGINT happens between
  92.    the previous QUIT and setting immediate_quit (desirable anytime we
  93.    expect to block), call QUIT after setting immediate_quit.  */

  94. int immediate_quit;

  95. /* Nonzero means that strings with character values >0x7F should be printed
  96.    as octal escapes.  Zero means just print the value (e.g. it's an
  97.    international character, and the terminal or window can cope.)  */

  98. int sevenbit_strings = 0;
  99. static void
  100. show_sevenbit_strings (struct ui_file *file, int from_tty,
  101.                        struct cmd_list_element *c, const char *value)
  102. {
  103.   fprintf_filtered (file, _("Printing of 8-bit characters "
  104.                             "in strings as \\nnn is %s.\n"),
  105.                     value);
  106. }

  107. /* String to be printed before warning messages, if any.  */

  108. char *warning_pre_print = "\nwarning: ";

  109. int pagination_enabled = 1;
  110. static void
  111. show_pagination_enabled (struct ui_file *file, int from_tty,
  112.                          struct cmd_list_element *c, const char *value)
  113. {
  114.   fprintf_filtered (file, _("State of pagination is %s.\n"), value);
  115. }


  116. /* Cleanup utilities.

  117.    These are not defined in cleanups.c (nor declared in cleanups.h)
  118.    because while they use the "cleanup API" they are not part of the
  119.    "cleanup API".  */

  120. static void
  121. do_freeargv (void *arg)
  122. {
  123.   freeargv ((char **) arg);
  124. }

  125. struct cleanup *
  126. make_cleanup_freeargv (char **arg)
  127. {
  128.   return make_cleanup (do_freeargv, arg);
  129. }

  130. static void
  131. do_dyn_string_delete (void *arg)
  132. {
  133.   dyn_string_delete ((dyn_string_t) arg);
  134. }

  135. struct cleanup *
  136. make_cleanup_dyn_string_delete (dyn_string_t arg)
  137. {
  138.   return make_cleanup (do_dyn_string_delete, arg);
  139. }

  140. static void
  141. do_bfd_close_cleanup (void *arg)
  142. {
  143.   gdb_bfd_unref (arg);
  144. }

  145. struct cleanup *
  146. make_cleanup_bfd_unref (bfd *abfd)
  147. {
  148.   return make_cleanup (do_bfd_close_cleanup, abfd);
  149. }

  150. static void
  151. do_close_cleanup (void *arg)
  152. {
  153.   int *fd = arg;

  154.   close (*fd);
  155. }

  156. struct cleanup *
  157. make_cleanup_close (int fd)
  158. {
  159.   int *saved_fd = xmalloc (sizeof (fd));

  160.   *saved_fd = fd;
  161.   return make_cleanup_dtor (do_close_cleanup, saved_fd, xfree);
  162. }

  163. /* Helper function which does the work for make_cleanup_fclose.  */

  164. static void
  165. do_fclose_cleanup (void *arg)
  166. {
  167.   FILE *file = arg;

  168.   fclose (file);
  169. }

  170. /* Return a new cleanup that closes FILE.  */

  171. struct cleanup *
  172. make_cleanup_fclose (FILE *file)
  173. {
  174.   return make_cleanup (do_fclose_cleanup, file);
  175. }

  176. /* Helper function which does the work for make_cleanup_obstack_free.  */

  177. static void
  178. do_obstack_free (void *arg)
  179. {
  180.   struct obstack *ob = arg;

  181.   obstack_free (ob, NULL);
  182. }

  183. /* Return a new cleanup that frees OBSTACK.  */

  184. struct cleanup *
  185. make_cleanup_obstack_free (struct obstack *obstack)
  186. {
  187.   return make_cleanup (do_obstack_free, obstack);
  188. }

  189. static void
  190. do_ui_file_delete (void *arg)
  191. {
  192.   ui_file_delete (arg);
  193. }

  194. struct cleanup *
  195. make_cleanup_ui_file_delete (struct ui_file *arg)
  196. {
  197.   return make_cleanup (do_ui_file_delete, arg);
  198. }

  199. /* Helper function for make_cleanup_ui_out_redirect_pop.  */

  200. static void
  201. do_ui_out_redirect_pop (void *arg)
  202. {
  203.   struct ui_out *uiout = arg;

  204.   if (ui_out_redirect (uiout, NULL) < 0)
  205.     warning (_("Cannot restore redirection of the current output protocol"));
  206. }

  207. /* Return a new cleanup that pops the last redirection by ui_out_redirect
  208.    with NULL parameter.  */

  209. struct cleanup *
  210. make_cleanup_ui_out_redirect_pop (struct ui_out *uiout)
  211. {
  212.   return make_cleanup (do_ui_out_redirect_pop, uiout);
  213. }

  214. static void
  215. do_free_section_addr_info (void *arg)
  216. {
  217.   free_section_addr_info (arg);
  218. }

  219. struct cleanup *
  220. make_cleanup_free_section_addr_info (struct section_addr_info *addrs)
  221. {
  222.   return make_cleanup (do_free_section_addr_info, addrs);
  223. }

  224. struct restore_integer_closure
  225. {
  226.   int *variable;
  227.   int value;
  228. };

  229. static void
  230. restore_integer (void *p)
  231. {
  232.   struct restore_integer_closure *closure = p;

  233.   *(closure->variable) = closure->value;
  234. }

  235. /* Remember the current value of *VARIABLE and make it restored when
  236.    the cleanup is run.  */

  237. struct cleanup *
  238. make_cleanup_restore_integer (int *variable)
  239. {
  240.   struct restore_integer_closure *c =
  241.     xmalloc (sizeof (struct restore_integer_closure));

  242.   c->variable = variable;
  243.   c->value = *variable;

  244.   return make_cleanup_dtor (restore_integer, (void *) c, xfree);
  245. }

  246. /* Remember the current value of *VARIABLE and make it restored when
  247.    the cleanup is run.  */

  248. struct cleanup *
  249. make_cleanup_restore_uinteger (unsigned int *variable)
  250. {
  251.   return make_cleanup_restore_integer ((int *) variable);
  252. }

  253. /* Helper for make_cleanup_unpush_target.  */

  254. static void
  255. do_unpush_target (void *arg)
  256. {
  257.   struct target_ops *ops = arg;

  258.   unpush_target (ops);
  259. }

  260. /* Return a new cleanup that unpushes OPS.  */

  261. struct cleanup *
  262. make_cleanup_unpush_target (struct target_ops *ops)
  263. {
  264.   return make_cleanup (do_unpush_target, ops);
  265. }

  266. /* Helper for make_cleanup_htab_delete compile time checking the types.  */

  267. static void
  268. do_htab_delete_cleanup (void *htab_voidp)
  269. {
  270.   htab_t htab = htab_voidp;

  271.   htab_delete (htab);
  272. }

  273. /* Return a new cleanup that deletes HTAB.  */

  274. struct cleanup *
  275. make_cleanup_htab_delete (htab_t htab)
  276. {
  277.   return make_cleanup (do_htab_delete_cleanup, htab);
  278. }

  279. struct restore_ui_file_closure
  280. {
  281.   struct ui_file **variable;
  282.   struct ui_file *value;
  283. };

  284. static void
  285. do_restore_ui_file (void *p)
  286. {
  287.   struct restore_ui_file_closure *closure = p;

  288.   *(closure->variable) = closure->value;
  289. }

  290. /* Remember the current value of *VARIABLE and make it restored when
  291.    the cleanup is run.  */

  292. struct cleanup *
  293. make_cleanup_restore_ui_file (struct ui_file **variable)
  294. {
  295.   struct restore_ui_file_closure *c = XNEW (struct restore_ui_file_closure);

  296.   c->variable = variable;
  297.   c->value = *variable;

  298.   return make_cleanup_dtor (do_restore_ui_file, (void *) c, xfree);
  299. }

  300. /* Helper for make_cleanup_value_free_to_mark.  */

  301. static void
  302. do_value_free_to_mark (void *value)
  303. {
  304.   value_free_to_mark ((struct value *) value);
  305. }

  306. /* Free all values allocated since MARK was obtained by value_mark
  307.    (except for those released) when the cleanup is run.  */

  308. struct cleanup *
  309. make_cleanup_value_free_to_mark (struct value *mark)
  310. {
  311.   return make_cleanup (do_value_free_to_mark, mark);
  312. }

  313. /* Helper for make_cleanup_value_free.  */

  314. static void
  315. do_value_free (void *value)
  316. {
  317.   value_free (value);
  318. }

  319. /* Free VALUE.  */

  320. struct cleanup *
  321. make_cleanup_value_free (struct value *value)
  322. {
  323.   return make_cleanup (do_value_free, value);
  324. }

  325. /* Helper for make_cleanup_free_so.  */

  326. static void
  327. do_free_so (void *arg)
  328. {
  329.   struct so_list *so = arg;

  330.   free_so (so);
  331. }

  332. /* Make cleanup handler calling free_so for SO.  */

  333. struct cleanup *
  334. make_cleanup_free_so (struct so_list *so)
  335. {
  336.   return make_cleanup (do_free_so, so);
  337. }

  338. /* Helper for make_cleanup_restore_current_language.  */

  339. static void
  340. do_restore_current_language (void *p)
  341. {
  342.   enum language saved_lang = (uintptr_t) p;

  343.   set_language (saved_lang);
  344. }

  345. /* Remember the current value of CURRENT_LANGUAGE and make it restored when
  346.    the cleanup is run.  */

  347. struct cleanup *
  348. make_cleanup_restore_current_language (void)
  349. {
  350.   enum language saved_lang = current_language->la_language;

  351.   return make_cleanup (do_restore_current_language,
  352.                        (void *) (uintptr_t) saved_lang);
  353. }

  354. /* Helper function for make_cleanup_clear_parser_state.  */

  355. static void
  356. do_clear_parser_state (void *ptr)
  357. {
  358.   struct parser_state **p = (struct parser_state **) ptr;

  359.   *p = NULL;
  360. }

  361. /* Clean (i.e., set to NULL) the parser state variable P.  */

  362. struct cleanup *
  363. make_cleanup_clear_parser_state (struct parser_state **p)
  364. {
  365.   return make_cleanup (do_clear_parser_state, (void *) p);
  366. }

  367. /* This function is useful for cleanups.
  368.    Do

  369.    foo = xmalloc (...);
  370.    old_chain = make_cleanup (free_current_contents, &foo);

  371.    to arrange to free the object thus allocated.  */

  372. void
  373. free_current_contents (void *ptr)
  374. {
  375.   void **location = ptr;

  376.   if (location == NULL)
  377.     internal_error (__FILE__, __LINE__,
  378.                     _("free_current_contents: NULL pointer"));
  379.   if (*location != NULL)
  380.     {
  381.       xfree (*location);
  382.       *location = NULL;
  383.     }
  384. }



  385. /* Print a warning message.  The first argument STRING is the warning
  386.    message, used as an fprintf format string, the second is the
  387.    va_list of arguments for that stringA warning is unfiltered (not
  388.    paginated) so that the user does not need to page through each
  389.    screen full of warnings when there are lots of them.  */

  390. void
  391. vwarning (const char *string, va_list args)
  392. {
  393.   if (deprecated_warning_hook)
  394.     (*deprecated_warning_hook) (string, args);
  395.   else
  396.     {
  397.       if (target_supports_terminal_ours ())
  398.         target_terminal_ours ();
  399.       if (filtered_printing_initialized ())
  400.         wrap_here ("");                /* Force out any buffered output.  */
  401.       gdb_flush (gdb_stdout);
  402.       if (warning_pre_print)
  403.         fputs_unfiltered (warning_pre_print, gdb_stderr);
  404.       vfprintf_unfiltered (gdb_stderr, string, args);
  405.       fprintf_unfiltered (gdb_stderr, "\n");
  406.     }
  407. }

  408. /* Print an error message and return to command level.
  409.    The first argument STRING is the error message, used as a fprintf string,
  410.    and the remaining args are passed as arguments to it.  */

  411. void
  412. verror (const char *string, va_list args)
  413. {
  414.   throw_verror (GENERIC_ERROR, string, args);
  415. }

  416. void
  417. error_stream (struct ui_file *stream)
  418. {
  419.   char *message = ui_file_xstrdup (stream, NULL);

  420.   make_cleanup (xfree, message);
  421.   error (("%s"), message);
  422. }

  423. /* Emit a message and abort.  */

  424. static void ATTRIBUTE_NORETURN
  425. abort_with_message (const char *msg)
  426. {
  427.   if (gdb_stderr == NULL)
  428.     fputs (msg, stderr);
  429.   else
  430.     fputs_unfiltered (msg, gdb_stderr);

  431.   abort ();                /* NOTE: GDB has only three calls to abort().  */
  432. }

  433. /* Dump core trying to increase the core soft limit to hard limit first.  */

  434. void
  435. dump_core (void)
  436. {
  437. #ifdef HAVE_SETRLIMIT
  438.   struct rlimit rlim = { RLIM_INFINITY, RLIM_INFINITY };

  439.   setrlimit (RLIMIT_CORE, &rlim);
  440. #endif /* HAVE_SETRLIMIT */

  441.   abort ();                /* NOTE: GDB has only three calls to abort().  */
  442. }

  443. /* Check whether GDB will be able to dump core using the dump_core
  444.    function.  Returns zero if GDB cannot or should not dump core.
  445.    If LIMIT_KIND is LIMIT_CUR the user's soft limit will be respected.
  446.    If LIMIT_KIND is LIMIT_MAX only the hard limit will be respected.  */

  447. int
  448. can_dump_core (enum resource_limit_kind limit_kind)
  449. {
  450. #ifdef HAVE_GETRLIMIT
  451.   struct rlimit rlim;

  452.   /* Be quiet and assume we can dump if an error is returned.  */
  453.   if (getrlimit (RLIMIT_CORE, &rlim) != 0)
  454.     return 1;

  455.   switch (limit_kind)
  456.     {
  457.     case LIMIT_CUR:
  458.       if (rlim.rlim_cur == 0)
  459.         return 0;

  460.     case LIMIT_MAX:
  461.       if (rlim.rlim_max == 0)
  462.         return 0;
  463.     }
  464. #endif /* HAVE_GETRLIMIT */

  465.   return 1;
  466. }

  467. /* Print a warning that we cannot dump core.  */

  468. void
  469. warn_cant_dump_core (const char *reason)
  470. {
  471.   fprintf_unfiltered (gdb_stderr,
  472.                       _("%s\nUnable to dump core, use `ulimit -c"
  473.                         " unlimited' before executing GDB next time.\n"),
  474.                       reason);
  475. }

  476. /* Check whether GDB will be able to dump core using the dump_core
  477.    function, and print a warning if we cannot.  */

  478. static int
  479. can_dump_core_warn (enum resource_limit_kind limit_kind,
  480.                     const char *reason)
  481. {
  482.   int core_dump_allowed = can_dump_core (limit_kind);

  483.   if (!core_dump_allowed)
  484.     warn_cant_dump_core (reason);

  485.   return core_dump_allowed;
  486. }

  487. /* Allow the user to configure the debugger behavior with respect to
  488.    what to do when an internal problem is detected.  */

  489. const char internal_problem_ask[] = "ask";
  490. const char internal_problem_yes[] = "yes";
  491. const char internal_problem_no[] = "no";
  492. static const char *const internal_problem_modes[] =
  493. {
  494.   internal_problem_ask,
  495.   internal_problem_yes,
  496.   internal_problem_no,
  497.   NULL
  498. };

  499. /* Print a message reporting an internal error/warning.  Ask the user
  500.    if they want to continue, dump core, or just exit.  Return
  501.    something to indicate a quit.  */

  502. struct internal_problem
  503. {
  504.   const char *name;
  505.   int user_settable_should_quit;
  506.   const char *should_quit;
  507.   int user_settable_should_dump_core;
  508.   const char *should_dump_core;
  509. };

  510. /* Report a problem, internal to GDB, to the user.  Once the problem
  511.    has been reported, and assuming GDB didn't quit, the caller can
  512.    either allow execution to resume or throw an error.  */

  513. static void ATTRIBUTE_PRINTF (4, 0)
  514. internal_vproblem (struct internal_problem *problem,
  515.                    const char *file, int line, const char *fmt, va_list ap)
  516. {
  517.   static int dejavu;
  518.   int quit_p;
  519.   int dump_core_p;
  520.   char *reason;
  521.   struct cleanup *cleanup = make_cleanup (null_cleanup, NULL);

  522.   /* Don't allow infinite error/warning recursion.  */
  523.   {
  524.     static char msg[] = "Recursive internal problem.\n";

  525.     switch (dejavu)
  526.       {
  527.       case 0:
  528.         dejavu = 1;
  529.         break;
  530.       case 1:
  531.         dejavu = 2;
  532.         abort_with_message (msg);
  533.       default:
  534.         dejavu = 3;
  535.         /* Newer GLIBC versions put the warn_unused_result attribute
  536.            on write, but this is one of those rare cases where
  537.            ignoring the return value is correct.  Casting to (void)
  538.            does not fix this problem.  This is the solution suggested
  539.            at http://gcc.gnu.org/bugzilla/show_bug.cgi?id=25509.  */
  540.         if (write (STDERR_FILENO, msg, sizeof (msg)) != sizeof (msg))
  541.           abort (); /* NOTE: GDB has only three calls to abort().  */
  542.         exit (1);
  543.       }
  544.   }

  545.   /* Create a string containing the full error/warning message.  Need
  546.      to call query with this full string, as otherwize the reason
  547.      (error/warning) and question become separated.  Format using a
  548.      style similar to a compiler error message.  Include extra detail
  549.      so that the user knows that they are living on the edge.  */
  550.   {
  551.     char *msg;

  552.     msg = xstrvprintf (fmt, ap);
  553.     reason = xstrprintf ("%s:%d: %s: %s\n"
  554.                          "A problem internal to GDB has been detected,\n"
  555.                          "further debugging may prove unreliable.",
  556.                          file, line, problem->name, msg);
  557.     xfree (msg);
  558.     make_cleanup (xfree, reason);
  559.   }

  560.   /* Fall back to abort_with_message if gdb_stderr is not set up.  */
  561.   if (gdb_stderr == NULL)
  562.     {
  563.       fputs (reason, stderr);
  564.       abort_with_message ("\n");
  565.     }

  566.   /* Try to get the message out and at the start of a new line.  */
  567.   if (target_supports_terminal_ours ())
  568.     target_terminal_ours ();
  569.   if (filtered_printing_initialized ())
  570.     begin_line ();

  571.   /* Emit the message unless query will emit it below.  */
  572.   if (problem->should_quit != internal_problem_ask
  573.       || !confirm
  574.       || !filtered_printing_initialized ())
  575.     fprintf_unfiltered (gdb_stderr, "%s\n", reason);

  576.   if (problem->should_quit == internal_problem_ask)
  577.     {
  578.       /* Default (yes/batch case) is to quit GDB.  When in batch mode
  579.          this lessens the likelihood of GDB going into an infinite
  580.          loop.  */
  581.       if (!confirm || !filtered_printing_initialized ())
  582.         quit_p = 1;
  583.       else
  584.         quit_p = query (_("%s\nQuit this debugging session? "), reason);
  585.     }
  586.   else if (problem->should_quit == internal_problem_yes)
  587.     quit_p = 1;
  588.   else if (problem->should_quit == internal_problem_no)
  589.     quit_p = 0;
  590.   else
  591.     internal_error (__FILE__, __LINE__, _("bad switch"));

  592.   fputs_unfiltered (_("\nThis is a bug, please report it."), gdb_stderr);
  593.   if (REPORT_BUGS_TO[0])
  594.     fprintf_unfiltered (gdb_stderr, _("  For instructions, see:\n%s."),
  595.                         REPORT_BUGS_TO);
  596.   fputs_unfiltered ("\n\n", gdb_stderr);

  597.   if (problem->should_dump_core == internal_problem_ask)
  598.     {
  599.       if (!can_dump_core_warn (LIMIT_MAX, reason))
  600.         dump_core_p = 0;
  601.       else if (!filtered_printing_initialized ())
  602.         dump_core_p = 1;
  603.       else
  604.         {
  605.           /* Default (yes/batch case) is to dump core.  This leaves a GDB
  606.              `dropping' so that it is easier to see that something went
  607.              wrong in GDB.  */
  608.           dump_core_p = query (_("%s\nCreate a core file of GDB? "), reason);
  609.         }
  610.     }
  611.   else if (problem->should_dump_core == internal_problem_yes)
  612.     dump_core_p = can_dump_core_warn (LIMIT_MAX, reason);
  613.   else if (problem->should_dump_core == internal_problem_no)
  614.     dump_core_p = 0;
  615.   else
  616.     internal_error (__FILE__, __LINE__, _("bad switch"));

  617.   if (quit_p)
  618.     {
  619.       if (dump_core_p)
  620.         dump_core ();
  621.       else
  622.         exit (1);
  623.     }
  624.   else
  625.     {
  626.       if (dump_core_p)
  627.         {
  628. #ifdef HAVE_WORKING_FORK
  629.           if (fork () == 0)
  630.             dump_core ();
  631. #endif
  632.         }
  633.     }

  634.   dejavu = 0;
  635.   do_cleanups (cleanup);
  636. }

  637. static struct internal_problem internal_error_problem = {
  638.   "internal-error", 1, internal_problem_ask, 1, internal_problem_ask
  639. };

  640. void
  641. internal_verror (const char *file, int line, const char *fmt, va_list ap)
  642. {
  643.   internal_vproblem (&internal_error_problem, file, line, fmt, ap);
  644.   throw_quit (_("Command aborted."));
  645. }

  646. static struct internal_problem internal_warning_problem = {
  647.   "internal-warning", 1, internal_problem_ask, 1, internal_problem_ask
  648. };

  649. void
  650. internal_vwarning (const char *file, int line, const char *fmt, va_list ap)
  651. {
  652.   internal_vproblem (&internal_warning_problem, file, line, fmt, ap);
  653. }

  654. static struct internal_problem demangler_warning_problem = {
  655.   "demangler-warning", 1, internal_problem_ask, 0, internal_problem_no
  656. };

  657. void
  658. demangler_vwarning (const char *file, int line, const char *fmt, va_list ap)
  659. {
  660.   internal_vproblem (&demangler_warning_problem, file, line, fmt, ap);
  661. }

  662. void
  663. demangler_warning (const char *file, int line, const char *string, ...)
  664. {
  665.   va_list ap;

  666.   va_start (ap, string);
  667.   demangler_vwarning (file, line, string, ap);
  668.   va_end (ap);
  669. }

  670. /* Dummy functions to keep add_prefix_cmd happy.  */

  671. static void
  672. set_internal_problem_cmd (char *args, int from_tty)
  673. {
  674. }

  675. static void
  676. show_internal_problem_cmd (char *args, int from_tty)
  677. {
  678. }

  679. /* When GDB reports an internal problem (error or warning) it gives
  680.    the user the opportunity to quit GDB and/or create a core file of
  681.    the current debug session.  This function registers a few commands
  682.    that make it possible to specify that GDB should always or never
  683.    quit or create a core file, without asking.  The commands look
  684.    like:

  685.    maint set PROBLEM-NAME quit ask|yes|no
  686.    maint show PROBLEM-NAME quit
  687.    maint set PROBLEM-NAME corefile ask|yes|no
  688.    maint show PROBLEM-NAME corefile

  689.    Where PROBLEM-NAME is currently "internal-error" or
  690.    "internal-warning".  */

  691. static void
  692. add_internal_problem_command (struct internal_problem *problem)
  693. {
  694.   struct cmd_list_element **set_cmd_list;
  695.   struct cmd_list_element **show_cmd_list;
  696.   char *set_doc;
  697.   char *show_doc;

  698.   set_cmd_list = xmalloc (sizeof (*set_cmd_list));
  699.   show_cmd_list = xmalloc (sizeof (*set_cmd_list));
  700.   *set_cmd_list = NULL;
  701.   *show_cmd_list = NULL;

  702.   set_doc = xstrprintf (_("Configure what GDB does when %s is detected."),
  703.                         problem->name);

  704.   show_doc = xstrprintf (_("Show what GDB does when %s is detected."),
  705.                          problem->name);

  706.   add_prefix_cmd ((char*) problem->name,
  707.                   class_maintenance, set_internal_problem_cmd, set_doc,
  708.                   set_cmd_list,
  709.                   concat ("maintenance set ", problem->name, " ",
  710.                           (char *) NULL),
  711.                   0/*allow-unknown*/, &maintenance_set_cmdlist);

  712.   add_prefix_cmd ((char*) problem->name,
  713.                   class_maintenance, show_internal_problem_cmd, show_doc,
  714.                   show_cmd_list,
  715.                   concat ("maintenance show ", problem->name, " ",
  716.                           (char *) NULL),
  717.                   0/*allow-unknown*/, &maintenance_show_cmdlist);

  718.   if (problem->user_settable_should_quit)
  719.     {
  720.       set_doc = xstrprintf (_("Set whether GDB should quit "
  721.                               "when an %s is detected"),
  722.                             problem->name);
  723.       show_doc = xstrprintf (_("Show whether GDB will quit "
  724.                                "when an %s is detected"),
  725.                              problem->name);
  726.       add_setshow_enum_cmd ("quit", class_maintenance,
  727.                             internal_problem_modes,
  728.                             &problem->should_quit,
  729.                             set_doc,
  730.                             show_doc,
  731.                             NULL, /* help_doc */
  732.                             NULL, /* setfunc */
  733.                             NULL, /* showfunc */
  734.                             set_cmd_list,
  735.                             show_cmd_list);

  736.       xfree (set_doc);
  737.       xfree (show_doc);
  738.     }

  739.   if (problem->user_settable_should_dump_core)
  740.     {
  741.       set_doc = xstrprintf (_("Set whether GDB should create a core "
  742.                               "file of GDB when %s is detected"),
  743.                             problem->name);
  744.       show_doc = xstrprintf (_("Show whether GDB will create a core "
  745.                                "file of GDB when %s is detected"),
  746.                              problem->name);
  747.       add_setshow_enum_cmd ("corefile", class_maintenance,
  748.                             internal_problem_modes,
  749.                             &problem->should_dump_core,
  750.                             set_doc,
  751.                             show_doc,
  752.                             NULL, /* help_doc */
  753.                             NULL, /* setfunc */
  754.                             NULL, /* showfunc */
  755.                             set_cmd_list,
  756.                             show_cmd_list);

  757.       xfree (set_doc);
  758.       xfree (show_doc);
  759.     }
  760. }

  761. /* Return a newly allocated string, containing the PREFIX followed
  762.    by the system error message for errno (separated by a colon).

  763.    The result must be deallocated after use.  */

  764. static char *
  765. perror_string (const char *prefix)
  766. {
  767.   char *err;
  768.   char *combined;

  769.   err = safe_strerror (errno);
  770.   combined = (char *) xmalloc (strlen (err) + strlen (prefix) + 3);
  771.   strcpy (combined, prefix);
  772.   strcat (combined, ": ");
  773.   strcat (combined, err);

  774.   return combined;
  775. }

  776. /* Print the system error message for errno, and also mention STRING
  777.    as the file name for which the error was encountered.  Use ERRCODE
  778.    for the thrown exception.  Then return to command level.  */

  779. void
  780. throw_perror_with_name (enum errors errcode, const char *string)
  781. {
  782.   char *combined;

  783.   combined = perror_string (string);
  784.   make_cleanup (xfree, combined);

  785.   /* I understand setting these is a matter of taste.  Still, some people
  786.      may clear errno but not know about bfd_error.  Doing this here is not
  787.      unreasonable.  */
  788.   bfd_set_error (bfd_error_no_error);
  789.   errno = 0;

  790.   throw_error (errcode, _("%s."), combined);
  791. }

  792. /* See throw_perror_with_name, ERRCODE defaults here to GENERIC_ERROR.  */

  793. void
  794. perror_with_name (const char *string)
  795. {
  796.   throw_perror_with_name (GENERIC_ERROR, string);
  797. }

  798. /* Same as perror_with_name except that it prints a warning instead
  799.    of throwing an error.  */

  800. void
  801. perror_warning_with_name (const char *string)
  802. {
  803.   char *combined;

  804.   combined = perror_string (string);
  805.   warning (_("%s"), combined);
  806.   xfree (combined);
  807. }

  808. /* Print the system error message for ERRCODE, and also mention STRING
  809.    as the file name for which the error was encountered.  */

  810. void
  811. print_sys_errmsg (const char *string, int errcode)
  812. {
  813.   char *err;
  814.   char *combined;

  815.   err = safe_strerror (errcode);
  816.   combined = (char *) alloca (strlen (err) + strlen (string) + 3);
  817.   strcpy (combined, string);
  818.   strcat (combined, ": ");
  819.   strcat (combined, err);

  820.   /* We want anything which was printed on stdout to come out first, before
  821.      this message.  */
  822.   gdb_flush (gdb_stdout);
  823.   fprintf_unfiltered (gdb_stderr, "%s.\n", combined);
  824. }

  825. /* Control C eventually causes this to be called, at a convenient time.  */

  826. void
  827. quit (void)
  828. {
  829.   if (sync_quit_force_run)
  830.     {
  831.       sync_quit_force_run = 0;
  832.       quit_force (NULL, stdin == instream);
  833.     }

  834. #ifdef __MSDOS__
  835.   /* No steenking SIGINT will ever be coming our way when the
  836.      program is resumed.  Don't lie.  */
  837.   throw_quit ("Quit");
  838. #else
  839.   if (job_control
  840.       /* If there is no terminal switching for this target, then we can't
  841.          possibly get screwed by the lack of job control.  */
  842.       || !target_supports_terminal_ours ())
  843.     throw_quit ("Quit");
  844.   else
  845.     throw_quit ("Quit (expect signal SIGINT when the program is resumed)");
  846. #endif
  847. }


  848. /* Called when a memory allocation fails, with the number of bytes of
  849.    memory requested in SIZE.  */

  850. void
  851. malloc_failure (long size)
  852. {
  853.   if (size > 0)
  854.     {
  855.       internal_error (__FILE__, __LINE__,
  856.                       _("virtual memory exhausted: can't allocate %ld bytes."),
  857.                       size);
  858.     }
  859.   else
  860.     {
  861.       internal_error (__FILE__, __LINE__, _("virtual memory exhausted."));
  862.     }
  863. }

  864. /* My replacement for the read system call.
  865.    Used like `read' but keeps going if `read' returns too soon.  */

  866. int
  867. myread (int desc, char *addr, int len)
  868. {
  869.   int val;
  870.   int orglen = len;

  871.   while (len > 0)
  872.     {
  873.       val = read (desc, addr, len);
  874.       if (val < 0)
  875.         return val;
  876.       if (val == 0)
  877.         return orglen - len;
  878.       len -= val;
  879.       addr += val;
  880.     }
  881.   return orglen;
  882. }

  883. void
  884. print_spaces (int n, struct ui_file *file)
  885. {
  886.   fputs_unfiltered (n_spaces (n), file);
  887. }

  888. /* Print a host address.  */

  889. void
  890. gdb_print_host_address (const void *addr, struct ui_file *stream)
  891. {
  892.   fprintf_filtered (stream, "%s", host_address_to_string (addr));
  893. }

  894. /* See utils.h.  */

  895. char *
  896. make_hex_string (const gdb_byte *data, size_t length)
  897. {
  898.   char *result = xmalloc (length * 2 + 1);
  899.   char *p;
  900.   size_t i;

  901.   p = result;
  902.   for (i = 0; i < length; ++i)
  903.     p += xsnprintf (p, 3, "%02x", data[i]);
  904.   *p = '\0';
  905.   return result;
  906. }



  907. /* A cleanup function that calls regfree.  */

  908. static void
  909. do_regfree_cleanup (void *r)
  910. {
  911.   regfree (r);
  912. }

  913. /* Create a new cleanup that frees the compiled regular expression R.  */

  914. struct cleanup *
  915. make_regfree_cleanup (regex_t *r)
  916. {
  917.   return make_cleanup (do_regfree_cleanup, r);
  918. }

  919. /* Return an xmalloc'd error message resulting from a regular
  920.    expression compilation failure.  */

  921. char *
  922. get_regcomp_error (int code, regex_t *rx)
  923. {
  924.   size_t length = regerror (code, rx, NULL, 0);
  925.   char *result = xmalloc (length);

  926.   regerror (code, rx, result, length);
  927.   return result;
  928. }

  929. /* Compile a regexp and throw an exception on error.  This returns a
  930.    cleanup to free the resulting pattern on success.  RX must not be
  931.    NULL.  */

  932. struct cleanup *
  933. compile_rx_or_error (regex_t *pattern, const char *rx, const char *message)
  934. {
  935.   int code;

  936.   gdb_assert (rx != NULL);

  937.   code = regcomp (pattern, rx, REG_NOSUB);
  938.   if (code != 0)
  939.     {
  940.       char *err = get_regcomp_error (code, pattern);

  941.       make_cleanup (xfree, err);
  942.       error (("%s: %s"), message, err);
  943.     }

  944.   return make_regfree_cleanup (pattern);
  945. }



  946. /* This function supports the query, nquery, and yquery functions.
  947.    Ask user a y-or-n question and return 0 if answer is no, 1 if
  948.    answer is yes, or default the answer to the specified default
  949.    (for yquery or nquery).  DEFCHAR may be 'y' or 'n' to provide a
  950.    default answer, or '\0' for no default.
  951.    CTLSTR is the control string and should end in "? ".  It should
  952.    not say how to answer, because we do that.
  953.    ARGS are the arguments passed along with the CTLSTR argument to
  954.    printf.  */

  955. static int ATTRIBUTE_PRINTF (1, 0)
  956. defaulted_query (const char *ctlstr, const char defchar, va_list args)
  957. {
  958.   int ans2;
  959.   int retval;
  960.   int def_value;
  961.   char def_answer, not_def_answer;
  962.   char *y_string, *n_string, *question, *prompt;
  963.   /* Used to add duration we waited for user to respond to
  964.      prompt_for_continue_wait_time.  */
  965.   struct timeval prompt_started, prompt_ended, prompt_delta;

  966.   /* Set up according to which answer is the default.  */
  967.   if (defchar == '\0')
  968.     {
  969.       def_value = 1;
  970.       def_answer = 'Y';
  971.       not_def_answer = 'N';
  972.       y_string = "y";
  973.       n_string = "n";
  974.     }
  975.   else if (defchar == 'y')
  976.     {
  977.       def_value = 1;
  978.       def_answer = 'Y';
  979.       not_def_answer = 'N';
  980.       y_string = "[y]";
  981.       n_string = "n";
  982.     }
  983.   else
  984.     {
  985.       def_value = 0;
  986.       def_answer = 'N';
  987.       not_def_answer = 'Y';
  988.       y_string = "y";
  989.       n_string = "[n]";
  990.     }

  991.   /* Automatically answer the default value if the user did not want
  992.      prompts or the command was issued with the server prefix.  */
  993.   if (!confirm || server_command)
  994.     return def_value;

  995.   /* If input isn't coming from the user directly, just say what
  996.      question we're asking, and then answer the default automatically.  This
  997.      way, important error messages don't get lost when talking to GDB
  998.      over a pipe.  */
  999.   if (! input_from_terminal_p ())
  1000.     {
  1001.       wrap_here ("");
  1002.       vfprintf_filtered (gdb_stdout, ctlstr, args);

  1003.       printf_filtered (_("(%s or %s) [answered %c; "
  1004.                          "input not from terminal]\n"),
  1005.                        y_string, n_string, def_answer);
  1006.       gdb_flush (gdb_stdout);

  1007.       return def_value;
  1008.     }

  1009.   if (deprecated_query_hook)
  1010.     {
  1011.       return deprecated_query_hook (ctlstr, args);
  1012.     }

  1013.   /* Format the question outside of the loop, to avoid reusing args.  */
  1014.   question = xstrvprintf (ctlstr, args);
  1015.   prompt = xstrprintf (_("%s%s(%s or %s) %s"),
  1016.                       annotation_level > 1 ? "\n\032\032pre-query\n" : "",
  1017.                       question, y_string, n_string,
  1018.                       annotation_level > 1 ? "\n\032\032query\n" : "");
  1019.   xfree (question);

  1020.   /* Used for calculating time spend waiting for user.  */
  1021.   gettimeofday (&prompt_started, NULL);

  1022.   while (1)
  1023.     {
  1024.       char *response, answer;

  1025.       gdb_flush (gdb_stdout);
  1026.       response = gdb_readline_wrapper (prompt);

  1027.       if (response == NULL)        /* C-d  */
  1028.         {
  1029.           printf_filtered ("EOF [assumed %c]\n", def_answer);
  1030.           retval = def_value;
  1031.           break;
  1032.         }

  1033.       answer = response[0];
  1034.       xfree (response);

  1035.       if (answer >= 'a')
  1036.         answer -= 040;
  1037.       /* Check answer.  For the non-default, the user must specify
  1038.          the non-default explicitly.  */
  1039.       if (answer == not_def_answer)
  1040.         {
  1041.           retval = !def_value;
  1042.           break;
  1043.         }
  1044.       /* Otherwise, if a default was specified, the user may either
  1045.          specify the required input or have it default by entering
  1046.          nothing.  */
  1047.       if (answer == def_answer
  1048.           || (defchar != '\0' && answer == '\0'))
  1049.         {
  1050.           retval = def_value;
  1051.           break;
  1052.         }
  1053.       /* Invalid entries are not defaulted and require another selection.  */
  1054.       printf_filtered (_("Please answer %s or %s.\n"),
  1055.                        y_string, n_string);
  1056.     }

  1057.   /* Add time spend in this routine to prompt_for_continue_wait_time.  */
  1058.   gettimeofday (&prompt_ended, NULL);
  1059.   timeval_sub (&prompt_delta, &prompt_ended, &prompt_started);
  1060.   timeval_add (&prompt_for_continue_wait_time,
  1061.                &prompt_for_continue_wait_time, &prompt_delta);

  1062.   xfree (prompt);
  1063.   if (annotation_level > 1)
  1064.     printf_filtered (("\n\032\032post-query\n"));
  1065.   return retval;
  1066. }


  1067. /* Ask user a y-or-n question and return 0 if answer is no, 1 if
  1068.    answer is yes, or 0 if answer is defaulted.
  1069.    Takes three args which are given to printf to print the question.
  1070.    The first, a control string, should end in "? ".
  1071.    It should not say how to answer, because we do that.  */

  1072. int
  1073. nquery (const char *ctlstr, ...)
  1074. {
  1075.   va_list args;
  1076.   int ret;

  1077.   va_start (args, ctlstr);
  1078.   ret = defaulted_query (ctlstr, 'n', args);
  1079.   va_end (args);
  1080.   return ret;
  1081. }

  1082. /* Ask user a y-or-n question and return 0 if answer is no, 1 if
  1083.    answer is yes, or 1 if answer is defaulted.
  1084.    Takes three args which are given to printf to print the question.
  1085.    The first, a control string, should end in "? ".
  1086.    It should not say how to answer, because we do that.  */

  1087. int
  1088. yquery (const char *ctlstr, ...)
  1089. {
  1090.   va_list args;
  1091.   int ret;

  1092.   va_start (args, ctlstr);
  1093.   ret = defaulted_query (ctlstr, 'y', args);
  1094.   va_end (args);
  1095.   return ret;
  1096. }

  1097. /* Ask user a y-or-n question and return 1 iff answer is yes.
  1098.    Takes three args which are given to printf to print the question.
  1099.    The first, a control string, should end in "? ".
  1100.    It should not say how to answer, because we do that.  */

  1101. int
  1102. query (const char *ctlstr, ...)
  1103. {
  1104.   va_list args;
  1105.   int ret;

  1106.   va_start (args, ctlstr);
  1107.   ret = defaulted_query (ctlstr, '\0', args);
  1108.   va_end (args);
  1109.   return ret;
  1110. }

  1111. /* A helper for parse_escape that converts a host character to a
  1112.    target character.  C is the host character.  If conversion is
  1113.    possible, then the target character is stored in *TARGET_C and the
  1114.    function returns 1.  Otherwise, the function returns 0.  */

  1115. static int
  1116. host_char_to_target (struct gdbarch *gdbarch, int c, int *target_c)
  1117. {
  1118.   struct obstack host_data;
  1119.   char the_char = c;
  1120.   struct cleanup *cleanups;
  1121.   int result = 0;

  1122.   obstack_init (&host_data);
  1123.   cleanups = make_cleanup_obstack_free (&host_data);

  1124.   convert_between_encodings (target_charset (gdbarch), host_charset (),
  1125.                              (gdb_byte *) &the_char, 1, 1,
  1126.                              &host_data, translit_none);

  1127.   if (obstack_object_size (&host_data) == 1)
  1128.     {
  1129.       result = 1;
  1130.       *target_c = *(char *) obstack_base (&host_data);
  1131.     }

  1132.   do_cleanups (cleanups);
  1133.   return result;
  1134. }

  1135. /* Parse a C escape sequence.  STRING_PTR points to a variable
  1136.    containing a pointer to the string to parse.  That pointer
  1137.    should point to the character after the \.  That pointer
  1138.    is updated past the characters we use.  The value of the
  1139.    escape sequence is returned.

  1140.    A negative value means the sequence \ newline was seen,
  1141.    which is supposed to be equivalent to nothing at all.

  1142.    If \ is followed by a null character, we return a negative
  1143.    value and leave the string pointer pointing at the null character.

  1144.    If \ is followed by 000, we return 0 and leave the string pointer
  1145.    after the zeros.  A value of 0 does not mean end of string.  */

  1146. int
  1147. parse_escape (struct gdbarch *gdbarch, const char **string_ptr)
  1148. {
  1149.   int target_char = -2;        /* Initialize to avoid GCC warnings.  */
  1150.   int c = *(*string_ptr)++;

  1151.   switch (c)
  1152.     {
  1153.       case '\n':
  1154.         return -2;
  1155.       case 0:
  1156.         (*string_ptr)--;
  1157.         return 0;

  1158.       case '0':
  1159.       case '1':
  1160.       case '2':
  1161.       case '3':
  1162.       case '4':
  1163.       case '5':
  1164.       case '6':
  1165.       case '7':
  1166.         {
  1167.           int i = host_hex_value (c);
  1168.           int count = 0;
  1169.           while (++count < 3)
  1170.             {
  1171.               c = (**string_ptr);
  1172.               if (isdigit (c) && c != '8' && c != '9')
  1173.                 {
  1174.                   (*string_ptr)++;
  1175.                   i *= 8;
  1176.                   i += host_hex_value (c);
  1177.                 }
  1178.               else
  1179.                 {
  1180.                   break;
  1181.                 }
  1182.             }
  1183.           return i;
  1184.         }

  1185.     case 'a':
  1186.       c = '\a';
  1187.       break;
  1188.     case 'b':
  1189.       c = '\b';
  1190.       break;
  1191.     case 'f':
  1192.       c = '\f';
  1193.       break;
  1194.     case 'n':
  1195.       c = '\n';
  1196.       break;
  1197.     case 'r':
  1198.       c = '\r';
  1199.       break;
  1200.     case 't':
  1201.       c = '\t';
  1202.       break;
  1203.     case 'v':
  1204.       c = '\v';
  1205.       break;

  1206.     default:
  1207.       break;
  1208.     }

  1209.   if (!host_char_to_target (gdbarch, c, &target_char))
  1210.     error (_("The escape sequence `\\%c' is equivalent to plain `%c',"
  1211.              " which has no equivalent\nin the `%s' character set."),
  1212.            c, c, target_charset (gdbarch));
  1213.   return target_char;
  1214. }

  1215. /* Print the character C on STREAM as part of the contents of a literal
  1216.    string whose delimiter is QUOTER.  Note that this routine should only
  1217.    be call for printing things which are independent of the language
  1218.    of the program being debugged.

  1219.    printchar will normally escape backslashes and instances of QUOTER. If
  1220.    QUOTER is 0, printchar won't escape backslashes or any quoting character.
  1221.    As a side effect, if you pass the backslash character as the QUOTER,
  1222.    printchar will escape backslashes as usual, but not any other quoting
  1223.    character. */

  1224. static void
  1225. printchar (int c, void (*do_fputs) (const char *, struct ui_file *),
  1226.            void (*do_fprintf) (struct ui_file *, const char *, ...)
  1227.            ATTRIBUTE_FPTR_PRINTF_2, struct ui_file *stream, int quoter)
  1228. {
  1229.   c &= 0xFF;                        /* Avoid sign bit follies */

  1230.   if (c < 0x20 ||                /* Low control chars */
  1231.       (c >= 0x7F && c < 0xA0) ||        /* DEL, High controls */
  1232.       (sevenbit_strings && c >= 0x80))
  1233.     {                                /* high order bit set */
  1234.       switch (c)
  1235.         {
  1236.         case '\n':
  1237.           do_fputs ("\\n", stream);
  1238.           break;
  1239.         case '\b':
  1240.           do_fputs ("\\b", stream);
  1241.           break;
  1242.         case '\t':
  1243.           do_fputs ("\\t", stream);
  1244.           break;
  1245.         case '\f':
  1246.           do_fputs ("\\f", stream);
  1247.           break;
  1248.         case '\r':
  1249.           do_fputs ("\\r", stream);
  1250.           break;
  1251.         case '\033':
  1252.           do_fputs ("\\e", stream);
  1253.           break;
  1254.         case '\007':
  1255.           do_fputs ("\\a", stream);
  1256.           break;
  1257.         default:
  1258.           do_fprintf (stream, "\\%.3o", (unsigned int) c);
  1259.           break;
  1260.         }
  1261.     }
  1262.   else
  1263.     {
  1264.       if (quoter != 0 && (c == '\\' || c == quoter))
  1265.         do_fputs ("\\", stream);
  1266.       do_fprintf (stream, "%c", c);
  1267.     }
  1268. }

  1269. /* Print the character C on STREAM as part of the contents of a
  1270.    literal string whose delimiter is QUOTER.  Note that these routines
  1271.    should only be call for printing things which are independent of
  1272.    the language of the program being debugged.  */

  1273. void
  1274. fputstr_filtered (const char *str, int quoter, struct ui_file *stream)
  1275. {
  1276.   while (*str)
  1277.     printchar (*str++, fputs_filtered, fprintf_filtered, stream, quoter);
  1278. }

  1279. void
  1280. fputstr_unfiltered (const char *str, int quoter, struct ui_file *stream)
  1281. {
  1282.   while (*str)
  1283.     printchar (*str++, fputs_unfiltered, fprintf_unfiltered, stream, quoter);
  1284. }

  1285. void
  1286. fputstrn_filtered (const char *str, int n, int quoter,
  1287.                    struct ui_file *stream)
  1288. {
  1289.   int i;

  1290.   for (i = 0; i < n; i++)
  1291.     printchar (str[i], fputs_filtered, fprintf_filtered, stream, quoter);
  1292. }

  1293. void
  1294. fputstrn_unfiltered (const char *str, int n, int quoter,
  1295.                      struct ui_file *stream)
  1296. {
  1297.   int i;

  1298.   for (i = 0; i < n; i++)
  1299.     printchar (str[i], fputs_unfiltered, fprintf_unfiltered, stream, quoter);
  1300. }


  1301. /* Number of lines per page or UINT_MAX if paging is disabled.  */
  1302. static unsigned int lines_per_page;
  1303. static void
  1304. show_lines_per_page (struct ui_file *file, int from_tty,
  1305.                      struct cmd_list_element *c, const char *value)
  1306. {
  1307.   fprintf_filtered (file,
  1308.                     _("Number of lines gdb thinks are in a page is %s.\n"),
  1309.                     value);
  1310. }

  1311. /* Number of chars per line or UINT_MAX if line folding is disabled.  */
  1312. static unsigned int chars_per_line;
  1313. static void
  1314. show_chars_per_line (struct ui_file *file, int from_tty,
  1315.                      struct cmd_list_element *c, const char *value)
  1316. {
  1317.   fprintf_filtered (file,
  1318.                     _("Number of characters gdb thinks "
  1319.                       "are in a line is %s.\n"),
  1320.                     value);
  1321. }

  1322. /* Current count of lines printed on this page, chars on this line.  */
  1323. static unsigned int lines_printed, chars_printed;

  1324. /* Buffer and start column of buffered text, for doing smarter word-
  1325.    wrapping.  When someone calls wrap_here(), we start buffering output
  1326.    that comes through fputs_filtered().  If we see a newline, we just
  1327.    spit it out and forget about the wrap_here().  If we see another
  1328.    wrap_here(), we spit it out and remember the newer one.  If we see
  1329.    the end of the line, we spit out a newline, the indent, and then
  1330.    the buffered output.  */

  1331. /* Malloc'd buffer with chars_per_line+2 bytes.  Contains characters which
  1332.    are waiting to be output (they have already been counted in chars_printed).
  1333.    When wrap_buffer[0] is null, the buffer is empty.  */
  1334. static char *wrap_buffer;

  1335. /* Pointer in wrap_buffer to the next character to fill.  */
  1336. static char *wrap_pointer;

  1337. /* String to indent by if the wrap occurs.  Must not be NULL if wrap_column
  1338.    is non-zero.  */
  1339. static char *wrap_indent;

  1340. /* Column number on the screen where wrap_buffer begins, or 0 if wrapping
  1341.    is not in effect.  */
  1342. static int wrap_column;


  1343. /* Inialize the number of lines per page and chars per line.  */

  1344. void
  1345. init_page_info (void)
  1346. {
  1347.   if (batch_flag)
  1348.     {
  1349.       lines_per_page = UINT_MAX;
  1350.       chars_per_line = UINT_MAX;
  1351.     }
  1352.   else
  1353. #if defined(TUI)
  1354.   if (!tui_get_command_dimension (&chars_per_line, &lines_per_page))
  1355. #endif
  1356.     {
  1357.       int rows, cols;

  1358. #if defined(__GO32__)
  1359.       rows = ScreenRows ();
  1360.       cols = ScreenCols ();
  1361.       lines_per_page = rows;
  1362.       chars_per_line = cols;
  1363. #else
  1364.       /* Make sure Readline has initialized its terminal settings.  */
  1365.       rl_reset_terminal (NULL);

  1366.       /* Get the screen size from Readline.  */
  1367.       rl_get_screen_size (&rows, &cols);
  1368.       lines_per_page = rows;
  1369.       chars_per_line = cols;

  1370.       /* Readline should have fetched the termcap entry for us.
  1371.          Only try to use tgetnum function if rl_get_screen_size
  1372.          did not return a useful value. */
  1373.       if (((rows <= 0) && (tgetnum ("li") < 0))
  1374.         /* Also disable paging if inside EMACS.  */
  1375.           || getenv ("EMACS"))
  1376.         {
  1377.           /* The number of lines per page is not mentioned in the terminal
  1378.              description or EMACS evironment variable is set.  This probably
  1379.              means that paging is not useful, so disable paging.  */
  1380.           lines_per_page = UINT_MAX;
  1381.         }

  1382.       /* If the output is not a terminal, don't paginate it.  */
  1383.       if (!ui_file_isatty (gdb_stdout))
  1384.         lines_per_page = UINT_MAX;
  1385. #endif
  1386.     }

  1387.   set_screen_size ();
  1388.   set_width ();
  1389. }

  1390. /* Return nonzero if filtered printing is initialized.  */
  1391. int
  1392. filtered_printing_initialized (void)
  1393. {
  1394.   return wrap_buffer != NULL;
  1395. }

  1396. /* Helper for make_cleanup_restore_page_info.  */

  1397. static void
  1398. do_restore_page_info_cleanup (void *arg)
  1399. {
  1400.   set_screen_size ();
  1401.   set_width ();
  1402. }

  1403. /* Provide cleanup for restoring the terminal size.  */

  1404. struct cleanup *
  1405. make_cleanup_restore_page_info (void)
  1406. {
  1407.   struct cleanup *back_to;

  1408.   back_to = make_cleanup (do_restore_page_info_cleanup, NULL);
  1409.   make_cleanup_restore_uinteger (&lines_per_page);
  1410.   make_cleanup_restore_uinteger (&chars_per_line);

  1411.   return back_to;
  1412. }

  1413. /* Temporarily set BATCH_FLAG and the associated unlimited terminal size.
  1414.    Provide cleanup for restoring the original state.  */

  1415. struct cleanup *
  1416. set_batch_flag_and_make_cleanup_restore_page_info (void)
  1417. {
  1418.   struct cleanup *back_to = make_cleanup_restore_page_info ();

  1419.   make_cleanup_restore_integer (&batch_flag);
  1420.   batch_flag = 1;
  1421.   init_page_info ();

  1422.   return back_to;
  1423. }

  1424. /* Set the screen size based on LINES_PER_PAGE and CHARS_PER_LINE.  */

  1425. static void
  1426. set_screen_size (void)
  1427. {
  1428.   int rows = lines_per_page;
  1429.   int cols = chars_per_line;

  1430.   if (rows <= 0)
  1431.     rows = INT_MAX;

  1432.   if (cols <= 0)
  1433.     cols = INT_MAX;

  1434.   /* Update Readline's idea of the terminal size.  */
  1435.   rl_set_screen_size (rows, cols);
  1436. }

  1437. /* Reinitialize WRAP_BUFFER according to the current value of
  1438.    CHARS_PER_LINE.  */

  1439. static void
  1440. set_width (void)
  1441. {
  1442.   if (chars_per_line == 0)
  1443.     init_page_info ();

  1444.   if (!wrap_buffer)
  1445.     {
  1446.       wrap_buffer = (char *) xmalloc (chars_per_line + 2);
  1447.       wrap_buffer[0] = '\0';
  1448.     }
  1449.   else
  1450.     wrap_buffer = (char *) xrealloc (wrap_buffer, chars_per_line + 2);
  1451.   wrap_pointer = wrap_buffer;        /* Start it at the beginning.  */
  1452. }

  1453. static void
  1454. set_width_command (char *args, int from_tty, struct cmd_list_element *c)
  1455. {
  1456.   set_screen_size ();
  1457.   set_width ();
  1458. }

  1459. static void
  1460. set_height_command (char *args, int from_tty, struct cmd_list_element *c)
  1461. {
  1462.   set_screen_size ();
  1463. }

  1464. /* Wait, so the user can read what's on the screen.  Prompt the user
  1465.    to continue by pressing RETURN.  */

  1466. static void
  1467. prompt_for_continue (void)
  1468. {
  1469.   char *ignore;
  1470.   char cont_prompt[120];
  1471.   /* Used to add duration we waited for user to respond to
  1472.      prompt_for_continue_wait_time.  */
  1473.   struct timeval prompt_started, prompt_ended, prompt_delta;

  1474.   gettimeofday (&prompt_started, NULL);

  1475.   if (annotation_level > 1)
  1476.     printf_unfiltered (("\n\032\032pre-prompt-for-continue\n"));

  1477.   strcpy (cont_prompt,
  1478.           "---Type <return> to continue, or q <return> to quit---");
  1479.   if (annotation_level > 1)
  1480.     strcat (cont_prompt, "\n\032\032prompt-for-continue\n");

  1481.   /* We must do this *before* we call gdb_readline, else it will eventually
  1482.      call us -- thinking that we're trying to print beyond the end of the
  1483.      screen.  */
  1484.   reinitialize_more_filter ();

  1485.   immediate_quit++;
  1486.   QUIT;

  1487.   /* We'll need to handle input.  */
  1488.   target_terminal_ours ();

  1489.   /* On a real operating system, the user can quit with SIGINT.
  1490.      But not on GO32.

  1491.      'q' is provided on all systems so users don't have to change habits
  1492.      from system to system, and because telling them what to do in
  1493.      the prompt is more user-friendly than expecting them to think of
  1494.      SIGINT.  */
  1495.   /* Call readline, not gdb_readline, because GO32 readline handles control-C
  1496.      whereas control-C to gdb_readline will cause the user to get dumped
  1497.      out to DOS.  */
  1498.   ignore = gdb_readline_wrapper (cont_prompt);

  1499.   /* Add time spend in this routine to prompt_for_continue_wait_time.  */
  1500.   gettimeofday (&prompt_ended, NULL);
  1501.   timeval_sub (&prompt_delta, &prompt_ended, &prompt_started);
  1502.   timeval_add (&prompt_for_continue_wait_time,
  1503.                &prompt_for_continue_wait_time, &prompt_delta);

  1504.   if (annotation_level > 1)
  1505.     printf_unfiltered (("\n\032\032post-prompt-for-continue\n"));

  1506.   if (ignore)
  1507.     {
  1508.       char *p = ignore;

  1509.       while (*p == ' ' || *p == '\t')
  1510.         ++p;
  1511.       if (p[0] == 'q')
  1512.         quit ();
  1513.       xfree (ignore);
  1514.     }
  1515.   immediate_quit--;

  1516.   /* Now we have to do this again, so that GDB will know that it doesn't
  1517.      need to save the ---Type <return>--- line at the top of the screen.  */
  1518.   reinitialize_more_filter ();

  1519.   dont_repeat ();                /* Forget prev cmd -- CR won't repeat it.  */
  1520. }

  1521. /* Initalize timer to keep track of how long we waited for the user.  */

  1522. void
  1523. reset_prompt_for_continue_wait_time (void)
  1524. {
  1525.   static const struct timeval zero_timeval = { 0 };

  1526.   prompt_for_continue_wait_time = zero_timeval;
  1527. }

  1528. /* Fetch the cumulative time spent in prompt_for_continue.  */

  1529. struct timeval
  1530. get_prompt_for_continue_wait_time (void)
  1531. {
  1532.   return prompt_for_continue_wait_time;
  1533. }

  1534. /* Reinitialize filter; ie. tell it to reset to original values.  */

  1535. void
  1536. reinitialize_more_filter (void)
  1537. {
  1538.   lines_printed = 0;
  1539.   chars_printed = 0;
  1540. }

  1541. /* Indicate that if the next sequence of characters overflows the line,
  1542.    a newline should be inserted here rather than when it hits the end.
  1543.    If INDENT is non-null, it is a string to be printed to indent the
  1544.    wrapped part on the next line.  INDENT must remain accessible until
  1545.    the next call to wrap_here() or until a newline is printed through
  1546.    fputs_filtered().

  1547.    If the line is already overfull, we immediately print a newline and
  1548.    the indentation, and disable further wrapping.

  1549.    If we don't know the width of lines, but we know the page height,
  1550.    we must not wrap words, but should still keep track of newlines
  1551.    that were explicitly printed.

  1552.    INDENT should not contain tabs, as that will mess up the char count
  1553.    on the next line.  FIXME.

  1554.    This routine is guaranteed to force out any output which has been
  1555.    squirreled away in the wrap_buffer, so wrap_here ((char *)0) can be
  1556.    used to force out output from the wrap_buffer.  */

  1557. void
  1558. wrap_here (char *indent)
  1559. {
  1560.   /* This should have been allocated, but be paranoid anyway.  */
  1561.   if (!wrap_buffer)
  1562.     internal_error (__FILE__, __LINE__,
  1563.                     _("failed internal consistency check"));

  1564.   if (wrap_buffer[0])
  1565.     {
  1566.       *wrap_pointer = '\0';
  1567.       fputs_unfiltered (wrap_buffer, gdb_stdout);
  1568.     }
  1569.   wrap_pointer = wrap_buffer;
  1570.   wrap_buffer[0] = '\0';
  1571.   if (chars_per_line == UINT_MAX)        /* No line overflow checking.  */
  1572.     {
  1573.       wrap_column = 0;
  1574.     }
  1575.   else if (chars_printed >= chars_per_line)
  1576.     {
  1577.       puts_filtered ("\n");
  1578.       if (indent != NULL)
  1579.         puts_filtered (indent);
  1580.       wrap_column = 0;
  1581.     }
  1582.   else
  1583.     {
  1584.       wrap_column = chars_printed;
  1585.       if (indent == NULL)
  1586.         wrap_indent = "";
  1587.       else
  1588.         wrap_indent = indent;
  1589.     }
  1590. }

  1591. /* Print input string to gdb_stdout, filtered, with wrap,
  1592.    arranging strings in columns of n chars.  String can be
  1593.    right or left justified in the column.  Never prints
  1594.    trailing spaces.  String should never be longer than
  1595.    width.  FIXME: this could be useful for the EXAMINE
  1596.    command, which currently doesn't tabulate very well.  */

  1597. void
  1598. puts_filtered_tabular (char *string, int width, int right)
  1599. {
  1600.   int spaces = 0;
  1601.   int stringlen;
  1602.   char *spacebuf;

  1603.   gdb_assert (chars_per_line > 0);
  1604.   if (chars_per_line == UINT_MAX)
  1605.     {
  1606.       fputs_filtered (string, gdb_stdout);
  1607.       fputs_filtered ("\n", gdb_stdout);
  1608.       return;
  1609.     }

  1610.   if (((chars_printed - 1) / width + 2) * width >= chars_per_line)
  1611.     fputs_filtered ("\n", gdb_stdout);

  1612.   if (width >= chars_per_line)
  1613.     width = chars_per_line - 1;

  1614.   stringlen = strlen (string);

  1615.   if (chars_printed > 0)
  1616.     spaces = width - (chars_printed - 1) % width - 1;
  1617.   if (right)
  1618.     spaces += width - stringlen;

  1619.   spacebuf = alloca (spaces + 1);
  1620.   spacebuf[spaces] = '\0';
  1621.   while (spaces--)
  1622.     spacebuf[spaces] = ' ';

  1623.   fputs_filtered (spacebuf, gdb_stdout);
  1624.   fputs_filtered (string, gdb_stdout);
  1625. }


  1626. /* Ensure that whatever gets printed next, using the filtered output
  1627.    commands, starts at the beginning of the line.  I.e. if there is
  1628.    any pending output for the current line, flush it and start a new
  1629.    line.  Otherwise do nothing.  */

  1630. void
  1631. begin_line (void)
  1632. {
  1633.   if (chars_printed > 0)
  1634.     {
  1635.       puts_filtered ("\n");
  1636.     }
  1637. }


  1638. /* Like fputs but if FILTER is true, pause after every screenful.

  1639.    Regardless of FILTER can wrap at points other than the final
  1640.    character of a line.

  1641.    Unlike fputs, fputs_maybe_filtered does not return a value.
  1642.    It is OK for LINEBUFFER to be NULL, in which case just don't print
  1643.    anything.

  1644.    Note that a longjmp to top level may occur in this routine (only if
  1645.    FILTER is true) (since prompt_for_continue may do so) so this
  1646.    routine should not be called when cleanups are not in place.  */

  1647. static void
  1648. fputs_maybe_filtered (const char *linebuffer, struct ui_file *stream,
  1649.                       int filter)
  1650. {
  1651.   const char *lineptr;

  1652.   if (linebuffer == 0)
  1653.     return;

  1654.   /* Don't do any filtering if it is disabled.  */
  1655.   if (stream != gdb_stdout
  1656.       || !pagination_enabled
  1657.       || batch_flag
  1658.       || (lines_per_page == UINT_MAX && chars_per_line == UINT_MAX)
  1659.       || top_level_interpreter () == NULL
  1660.       || ui_out_is_mi_like_p (interp_ui_out (top_level_interpreter ())))
  1661.     {
  1662.       fputs_unfiltered (linebuffer, stream);
  1663.       return;
  1664.     }

  1665.   /* Go through and output each character.  Show line extension
  1666.      when this is necessary; prompt user for new page when this is
  1667.      necessary.  */

  1668.   lineptr = linebuffer;
  1669.   while (*lineptr)
  1670.     {
  1671.       /* Possible new page.  */
  1672.       if (filter && (lines_printed >= lines_per_page - 1))
  1673.         prompt_for_continue ();

  1674.       while (*lineptr && *lineptr != '\n')
  1675.         {
  1676.           /* Print a single line.  */
  1677.           if (*lineptr == '\t')
  1678.             {
  1679.               if (wrap_column)
  1680.                 *wrap_pointer++ = '\t';
  1681.               else
  1682.                 fputc_unfiltered ('\t', stream);
  1683.               /* Shifting right by 3 produces the number of tab stops
  1684.                  we have already passed, and then adding one and
  1685.                  shifting left 3 advances to the next tab stop.  */
  1686.               chars_printed = ((chars_printed >> 3) + 1) << 3;
  1687.               lineptr++;
  1688.             }
  1689.           else
  1690.             {
  1691.               if (wrap_column)
  1692.                 *wrap_pointer++ = *lineptr;
  1693.               else
  1694.                 fputc_unfiltered (*lineptr, stream);
  1695.               chars_printed++;
  1696.               lineptr++;
  1697.             }

  1698.           if (chars_printed >= chars_per_line)
  1699.             {
  1700.               unsigned int save_chars = chars_printed;

  1701.               chars_printed = 0;
  1702.               lines_printed++;
  1703.               /* If we aren't actually wrapping, don't output newline --
  1704.                  if chars_per_line is right, we probably just overflowed
  1705.                  anyway; if it's wrong, let us keep going.  */
  1706.               if (wrap_column)
  1707.                 fputc_unfiltered ('\n', stream);

  1708.               /* Possible new page.  */
  1709.               if (lines_printed >= lines_per_page - 1)
  1710.                 prompt_for_continue ();

  1711.               /* Now output indentation and wrapped string.  */
  1712.               if (wrap_column)
  1713.                 {
  1714.                   fputs_unfiltered (wrap_indent, stream);
  1715.                   *wrap_pointer = '\0';        /* Null-terminate saved stuff, */
  1716.                   fputs_unfiltered (wrap_buffer, stream); /* and eject it.  */
  1717.                   /* FIXME, this strlen is what prevents wrap_indent from
  1718.                      containing tabs.  However, if we recurse to print it
  1719.                      and count its chars, we risk trouble if wrap_indent is
  1720.                      longer than (the user settable) chars_per_line.
  1721.                      Note also that this can set chars_printed > chars_per_line
  1722.                      if we are printing a long string.  */
  1723.                   chars_printed = strlen (wrap_indent)
  1724.                     + (save_chars - wrap_column);
  1725.                   wrap_pointer = wrap_buffer;        /* Reset buffer */
  1726.                   wrap_buffer[0] = '\0';
  1727.                   wrap_column = 0;        /* And disable fancy wrap */
  1728.                 }
  1729.             }
  1730.         }

  1731.       if (*lineptr == '\n')
  1732.         {
  1733.           chars_printed = 0;
  1734.           wrap_here ((char *) 0);        /* Spit out chars, cancel
  1735.                                            further wraps.  */
  1736.           lines_printed++;
  1737.           fputc_unfiltered ('\n', stream);
  1738.           lineptr++;
  1739.         }
  1740.     }
  1741. }

  1742. void
  1743. fputs_filtered (const char *linebuffer, struct ui_file *stream)
  1744. {
  1745.   fputs_maybe_filtered (linebuffer, stream, 1);
  1746. }

  1747. int
  1748. putchar_unfiltered (int c)
  1749. {
  1750.   char buf = c;

  1751.   ui_file_write (gdb_stdout, &buf, 1);
  1752.   return c;
  1753. }

  1754. /* Write character C to gdb_stdout using GDB's paging mechanism and return C.
  1755.    May return nonlocally.  */

  1756. int
  1757. putchar_filtered (int c)
  1758. {
  1759.   return fputc_filtered (c, gdb_stdout);
  1760. }

  1761. int
  1762. fputc_unfiltered (int c, struct ui_file *stream)
  1763. {
  1764.   char buf = c;

  1765.   ui_file_write (stream, &buf, 1);
  1766.   return c;
  1767. }

  1768. int
  1769. fputc_filtered (int c, struct ui_file *stream)
  1770. {
  1771.   char buf[2];

  1772.   buf[0] = c;
  1773.   buf[1] = 0;
  1774.   fputs_filtered (buf, stream);
  1775.   return c;
  1776. }

  1777. /* puts_debug is like fputs_unfiltered, except it prints special
  1778.    characters in printable fashion.  */

  1779. void
  1780. puts_debug (char *prefix, char *string, char *suffix)
  1781. {
  1782.   int ch;

  1783.   /* Print prefix and suffix after each line.  */
  1784.   static int new_line = 1;
  1785.   static int return_p = 0;
  1786.   static char *prev_prefix = "";
  1787.   static char *prev_suffix = "";

  1788.   if (*string == '\n')
  1789.     return_p = 0;

  1790.   /* If the prefix is changing, print the previous suffix, a new line,
  1791.      and the new prefix.  */
  1792.   if ((return_p || (strcmp (prev_prefix, prefix) != 0)) && !new_line)
  1793.     {
  1794.       fputs_unfiltered (prev_suffix, gdb_stdlog);
  1795.       fputs_unfiltered ("\n", gdb_stdlog);
  1796.       fputs_unfiltered (prefix, gdb_stdlog);
  1797.     }

  1798.   /* Print prefix if we printed a newline during the previous call.  */
  1799.   if (new_line)
  1800.     {
  1801.       new_line = 0;
  1802.       fputs_unfiltered (prefix, gdb_stdlog);
  1803.     }

  1804.   prev_prefix = prefix;
  1805.   prev_suffix = suffix;

  1806.   /* Output characters in a printable format.  */
  1807.   while ((ch = *string++) != '\0')
  1808.     {
  1809.       switch (ch)
  1810.         {
  1811.         default:
  1812.           if (isprint (ch))
  1813.             fputc_unfiltered (ch, gdb_stdlog);

  1814.           else
  1815.             fprintf_unfiltered (gdb_stdlog, "\\x%02x", ch & 0xff);
  1816.           break;

  1817.         case '\\':
  1818.           fputs_unfiltered ("\\\\", gdb_stdlog);
  1819.           break;
  1820.         case '\b':
  1821.           fputs_unfiltered ("\\b", gdb_stdlog);
  1822.           break;
  1823.         case '\f':
  1824.           fputs_unfiltered ("\\f", gdb_stdlog);
  1825.           break;
  1826.         case '\n':
  1827.           new_line = 1;
  1828.           fputs_unfiltered ("\\n", gdb_stdlog);
  1829.           break;
  1830.         case '\r':
  1831.           fputs_unfiltered ("\\r", gdb_stdlog);
  1832.           break;
  1833.         case '\t':
  1834.           fputs_unfiltered ("\\t", gdb_stdlog);
  1835.           break;
  1836.         case '\v':
  1837.           fputs_unfiltered ("\\v", gdb_stdlog);
  1838.           break;
  1839.         }

  1840.       return_p = ch == '\r';
  1841.     }

  1842.   /* Print suffix if we printed a newline.  */
  1843.   if (new_line)
  1844.     {
  1845.       fputs_unfiltered (suffix, gdb_stdlog);
  1846.       fputs_unfiltered ("\n", gdb_stdlog);
  1847.     }
  1848. }


  1849. /* Print a variable number of ARGS using format FORMAT.  If this
  1850.    information is going to put the amount written (since the last call
  1851.    to REINITIALIZE_MORE_FILTER or the last page break) over the page size,
  1852.    call prompt_for_continue to get the users permision to continue.

  1853.    Unlike fprintf, this function does not return a value.

  1854.    We implement three variants, vfprintf (takes a vararg list and stream),
  1855.    fprintf (takes a stream to write on), and printf (the usual).

  1856.    Note also that a longjmp to top level may occur in this routine
  1857.    (since prompt_for_continue may do so) so this routine should not be
  1858.    called when cleanups are not in place.  */

  1859. static void
  1860. vfprintf_maybe_filtered (struct ui_file *stream, const char *format,
  1861.                          va_list args, int filter)
  1862. {
  1863.   char *linebuffer;
  1864.   struct cleanup *old_cleanups;

  1865.   linebuffer = xstrvprintf (format, args);
  1866.   old_cleanups = make_cleanup (xfree, linebuffer);
  1867.   fputs_maybe_filtered (linebuffer, stream, filter);
  1868.   do_cleanups (old_cleanups);
  1869. }


  1870. void
  1871. vfprintf_filtered (struct ui_file *stream, const char *format, va_list args)
  1872. {
  1873.   vfprintf_maybe_filtered (stream, format, args, 1);
  1874. }

  1875. void
  1876. vfprintf_unfiltered (struct ui_file *stream, const char *format, va_list args)
  1877. {
  1878.   char *linebuffer;
  1879.   struct cleanup *old_cleanups;

  1880.   linebuffer = xstrvprintf (format, args);
  1881.   old_cleanups = make_cleanup (xfree, linebuffer);
  1882.   if (debug_timestamp && stream == gdb_stdlog)
  1883.     {
  1884.       struct timeval tm;
  1885.       char *timestamp;
  1886.       int len, need_nl;

  1887.       gettimeofday (&tm, NULL);

  1888.       len = strlen (linebuffer);
  1889.       need_nl = (len > 0 && linebuffer[len - 1] != '\n');

  1890.       timestamp = xstrprintf ("%ld:%ld %s%s",
  1891.                               (long) tm.tv_sec, (long) tm.tv_usec,
  1892.                               linebuffer,
  1893.                               need_nl ? "\n": "");
  1894.       make_cleanup (xfree, timestamp);
  1895.       fputs_unfiltered (timestamp, stream);
  1896.     }
  1897.   else
  1898.     fputs_unfiltered (linebuffer, stream);
  1899.   do_cleanups (old_cleanups);
  1900. }

  1901. void
  1902. vprintf_filtered (const char *format, va_list args)
  1903. {
  1904.   vfprintf_maybe_filtered (gdb_stdout, format, args, 1);
  1905. }

  1906. void
  1907. vprintf_unfiltered (const char *format, va_list args)
  1908. {
  1909.   vfprintf_unfiltered (gdb_stdout, format, args);
  1910. }

  1911. void
  1912. fprintf_filtered (struct ui_file *stream, const char *format, ...)
  1913. {
  1914.   va_list args;

  1915.   va_start (args, format);
  1916.   vfprintf_filtered (stream, format, args);
  1917.   va_end (args);
  1918. }

  1919. void
  1920. fprintf_unfiltered (struct ui_file *stream, const char *format, ...)
  1921. {
  1922.   va_list args;

  1923.   va_start (args, format);
  1924.   vfprintf_unfiltered (stream, format, args);
  1925.   va_end (args);
  1926. }

  1927. /* Like fprintf_filtered, but prints its result indented.
  1928.    Called as fprintfi_filtered (spaces, stream, format, ...);  */

  1929. void
  1930. fprintfi_filtered (int spaces, struct ui_file *stream, const char *format,
  1931.                    ...)
  1932. {
  1933.   va_list args;

  1934.   va_start (args, format);
  1935.   print_spaces_filtered (spaces, stream);

  1936.   vfprintf_filtered (stream, format, args);
  1937.   va_end (args);
  1938. }


  1939. void
  1940. printf_filtered (const char *format, ...)
  1941. {
  1942.   va_list args;

  1943.   va_start (args, format);
  1944.   vfprintf_filtered (gdb_stdout, format, args);
  1945.   va_end (args);
  1946. }


  1947. void
  1948. printf_unfiltered (const char *format, ...)
  1949. {
  1950.   va_list args;

  1951.   va_start (args, format);
  1952.   vfprintf_unfiltered (gdb_stdout, format, args);
  1953.   va_end (args);
  1954. }

  1955. /* Like printf_filtered, but prints it's result indented.
  1956.    Called as printfi_filtered (spaces, format, ...);  */

  1957. void
  1958. printfi_filtered (int spaces, const char *format, ...)
  1959. {
  1960.   va_list args;

  1961.   va_start (args, format);
  1962.   print_spaces_filtered (spaces, gdb_stdout);
  1963.   vfprintf_filtered (gdb_stdout, format, args);
  1964.   va_end (args);
  1965. }

  1966. /* Easy -- but watch out!

  1967.    This routine is *not* a replacement for puts()!  puts() appends a newline.
  1968.    This one doesn't, and had better not!  */

  1969. void
  1970. puts_filtered (const char *string)
  1971. {
  1972.   fputs_filtered (string, gdb_stdout);
  1973. }

  1974. void
  1975. puts_unfiltered (const char *string)
  1976. {
  1977.   fputs_unfiltered (string, gdb_stdout);
  1978. }

  1979. /* Return a pointer to N spaces and a null.  The pointer is good
  1980.    until the next call to here.  */
  1981. char *
  1982. n_spaces (int n)
  1983. {
  1984.   char *t;
  1985.   static char *spaces = 0;
  1986.   static int max_spaces = -1;

  1987.   if (n > max_spaces)
  1988.     {
  1989.       if (spaces)
  1990.         xfree (spaces);
  1991.       spaces = (char *) xmalloc (n + 1);
  1992.       for (t = spaces + n; t != spaces;)
  1993.         *--t = ' ';
  1994.       spaces[n] = '\0';
  1995.       max_spaces = n;
  1996.     }

  1997.   return spaces + max_spaces - n;
  1998. }

  1999. /* Print N spaces.  */
  2000. void
  2001. print_spaces_filtered (int n, struct ui_file *stream)
  2002. {
  2003.   fputs_filtered (n_spaces (n), stream);
  2004. }

  2005. /* C++/ObjC demangler stuff.  */

  2006. /* fprintf_symbol_filtered attempts to demangle NAME, a symbol in language
  2007.    LANG, using demangling args ARG_MODE, and print it filtered to STREAM.
  2008.    If the name is not mangled, or the language for the name is unknown, or
  2009.    demangling is off, the name is printed in its "raw" form.  */

  2010. void
  2011. fprintf_symbol_filtered (struct ui_file *stream, const char *name,
  2012.                          enum language lang, int arg_mode)
  2013. {
  2014.   char *demangled;

  2015.   if (name != NULL)
  2016.     {
  2017.       /* If user wants to see raw output, no problem.  */
  2018.       if (!demangle)
  2019.         {
  2020.           fputs_filtered (name, stream);
  2021.         }
  2022.       else
  2023.         {
  2024.           demangled = language_demangle (language_def (lang), name, arg_mode);
  2025.           fputs_filtered (demangled ? demangled : name, stream);
  2026.           if (demangled != NULL)
  2027.             {
  2028.               xfree (demangled);
  2029.             }
  2030.         }
  2031.     }
  2032. }

  2033. /* Do a strcmp() type operation on STRING1 and STRING2, ignoring any
  2034.    differences in whitespace.  Returns 0 if they match, non-zero if they
  2035.    don't (slightly different than strcmp()'s range of return values).

  2036.    As an extra hack, string1=="FOO(ARGS)" matches string2=="FOO".
  2037.    This "feature" is useful when searching for matching C++ function names
  2038.    (such as if the user types 'break FOO', where FOO is a mangled C++
  2039.    function).  */

  2040. int
  2041. strcmp_iw (const char *string1, const char *string2)
  2042. {
  2043.   while ((*string1 != '\0') && (*string2 != '\0'))
  2044.     {
  2045.       while (isspace (*string1))
  2046.         {
  2047.           string1++;
  2048.         }
  2049.       while (isspace (*string2))
  2050.         {
  2051.           string2++;
  2052.         }
  2053.       if (case_sensitivity == case_sensitive_on && *string1 != *string2)
  2054.         break;
  2055.       if (case_sensitivity == case_sensitive_off
  2056.           && (tolower ((unsigned char) *string1)
  2057.               != tolower ((unsigned char) *string2)))
  2058.         break;
  2059.       if (*string1 != '\0')
  2060.         {
  2061.           string1++;
  2062.           string2++;
  2063.         }
  2064.     }
  2065.   return (*string1 != '\0' && *string1 != '(') || (*string2 != '\0');
  2066. }

  2067. /* This is like strcmp except that it ignores whitespace and treats
  2068.    '(' as the first non-NULL character in terms of ordering.  Like
  2069.    strcmp (and unlike strcmp_iw), it returns negative if STRING1 <
  2070.    STRING2, 0 if STRING2 = STRING2, and positive if STRING1 > STRING2
  2071.    according to that ordering.

  2072.    If a list is sorted according to this function and if you want to
  2073.    find names in the list that match some fixed NAME according to
  2074.    strcmp_iw(LIST_ELT, NAME), then the place to start looking is right
  2075.    where this function would put NAME.

  2076.    This function must be neutral to the CASE_SENSITIVITY setting as the user
  2077.    may choose it during later lookup.  Therefore this function always sorts
  2078.    primarily case-insensitively and secondarily case-sensitively.

  2079.    Here are some examples of why using strcmp to sort is a bad idea:

  2080.    Whitespace example:

  2081.    Say your partial symtab contains: "foo<char *>", "goo".  Then, if
  2082.    we try to do a search for "foo<char*>", strcmp will locate this
  2083.    after "foo<char *>" and before "goo".  Then lookup_partial_symbol
  2084.    will start looking at strings beginning with "goo", and will never
  2085.    see the correct match of "foo<char *>".

  2086.    Parenthesis example:

  2087.    In practice, this is less like to be an issue, but I'll give it a
  2088.    shot.  Let's assume that '$' is a legitimate character to occur in
  2089.    symbols.  (Which may well even be the case on some systems.)  Then
  2090.    say that the partial symbol table contains "foo$" and "foo(int)".
  2091.    strcmp will put them in this order, since '$' < '('.  Now, if the
  2092.    user searches for "foo", then strcmp will sort "foo" before "foo$".
  2093.    Then lookup_partial_symbol will notice that strcmp_iw("foo$",
  2094.    "foo") is false, so it won't proceed to the actual match of
  2095.    "foo(int)" with "foo".  */

  2096. int
  2097. strcmp_iw_ordered (const char *string1, const char *string2)
  2098. {
  2099.   const char *saved_string1 = string1, *saved_string2 = string2;
  2100.   enum case_sensitivity case_pass = case_sensitive_off;

  2101.   for (;;)
  2102.     {
  2103.       /* C1 and C2 are valid only if *string1 != '\0' && *string2 != '\0'.
  2104.          Provide stub characters if we are already at the end of one of the
  2105.          strings.  */
  2106.       char c1 = 'X', c2 = 'X';

  2107.       while (*string1 != '\0' && *string2 != '\0')
  2108.         {
  2109.           while (isspace (*string1))
  2110.             string1++;
  2111.           while (isspace (*string2))
  2112.             string2++;

  2113.           switch (case_pass)
  2114.           {
  2115.             case case_sensitive_off:
  2116.               c1 = tolower ((unsigned char) *string1);
  2117.               c2 = tolower ((unsigned char) *string2);
  2118.               break;
  2119.             case case_sensitive_on:
  2120.               c1 = *string1;
  2121.               c2 = *string2;
  2122.               break;
  2123.           }
  2124.           if (c1 != c2)
  2125.             break;

  2126.           if (*string1 != '\0')
  2127.             {
  2128.               string1++;
  2129.               string2++;
  2130.             }
  2131.         }

  2132.       switch (*string1)
  2133.         {
  2134.           /* Characters are non-equal unless they're both '\0'; we want to
  2135.              make sure we get the comparison right according to our
  2136.              comparison in the cases where one of them is '\0' or '('.  */
  2137.         case '\0':
  2138.           if (*string2 == '\0')
  2139.             break;
  2140.           else
  2141.             return -1;
  2142.         case '(':
  2143.           if (*string2 == '\0')
  2144.             return 1;
  2145.           else
  2146.             return -1;
  2147.         default:
  2148.           if (*string2 == '\0' || *string2 == '(')
  2149.             return 1;
  2150.           else if (c1 > c2)
  2151.             return 1;
  2152.           else if (c1 < c2)
  2153.             return -1;
  2154.           /* PASSTHRU */
  2155.         }

  2156.       if (case_pass == case_sensitive_on)
  2157.         return 0;

  2158.       /* Otherwise the strings were equal in case insensitive way, make
  2159.          a more fine grained comparison in a case sensitive way.  */

  2160.       case_pass = case_sensitive_on;
  2161.       string1 = saved_string1;
  2162.       string2 = saved_string2;
  2163.     }
  2164. }

  2165. /* A simple comparison function with opposite semantics to strcmp.  */

  2166. int
  2167. streq (const char *lhs, const char *rhs)
  2168. {
  2169.   return !strcmp (lhs, rhs);
  2170. }


  2171. /*
  2172.    ** subset_compare()
  2173.    **    Answer whether string_to_compare is a full or partial match to
  2174.    **    template_string.  The partial match must be in sequence starting
  2175.    **    at index 0.
  2176. */
  2177. int
  2178. subset_compare (char *string_to_compare, char *template_string)
  2179. {
  2180.   int match;

  2181.   if (template_string != (char *) NULL && string_to_compare != (char *) NULL
  2182.       && strlen (string_to_compare) <= strlen (template_string))
  2183.     match =
  2184.       (strncmp
  2185.        (template_string, string_to_compare, strlen (string_to_compare)) == 0);
  2186.   else
  2187.     match = 0;
  2188.   return match;
  2189. }

  2190. static void
  2191. pagination_on_command (char *arg, int from_tty)
  2192. {
  2193.   pagination_enabled = 1;
  2194. }

  2195. static void
  2196. pagination_off_command (char *arg, int from_tty)
  2197. {
  2198.   pagination_enabled = 0;
  2199. }

  2200. static void
  2201. show_debug_timestamp (struct ui_file *file, int from_tty,
  2202.                       struct cmd_list_element *c, const char *value)
  2203. {
  2204.   fprintf_filtered (file, _("Timestamping debugging messages is %s.\n"),
  2205.                     value);
  2206. }


  2207. void
  2208. initialize_utils (void)
  2209. {
  2210.   add_setshow_uinteger_cmd ("width", class_support, &chars_per_line, _("\
  2211. Set number of characters where GDB should wrap lines of its output."), _("\
  2212. Show number of characters where GDB should wrap lines of its output."), _("\
  2213. This affects where GDB wraps its output to fit the screen width.\n\
  2214. Setting this to \"unlimited\" or zero prevents GDB from wrapping its output."),
  2215.                             set_width_command,
  2216.                             show_chars_per_line,
  2217.                             &setlist, &showlist);

  2218.   add_setshow_uinteger_cmd ("height", class_support, &lines_per_page, _("\
  2219. Set number of lines in a page for GDB output pagination."), _("\
  2220. Show number of lines in a page for GDB output pagination."), _("\
  2221. This affects the number of lines after which GDB will pause\n\
  2222. its output and ask you whether to continue.\n\
  2223. Setting this to \"unlimited\" or zero causes GDB never pause during output."),
  2224.                             set_height_command,
  2225.                             show_lines_per_page,
  2226.                             &setlist, &showlist);

  2227.   init_page_info ();

  2228.   add_setshow_boolean_cmd ("pagination", class_support,
  2229.                            &pagination_enabled, _("\
  2230. Set state of GDB output pagination."), _("\
  2231. Show state of GDB output pagination."), _("\
  2232. When pagination is ON, GDB pauses at end of each screenful of\n\
  2233. its output and asks you whether to continue.\n\
  2234. Turning pagination off is an alternative to \"set height unlimited\"."),
  2235.                            NULL,
  2236.                            show_pagination_enabled,
  2237.                            &setlist, &showlist);

  2238.   if (xdb_commands)
  2239.     {
  2240.       add_com ("am", class_support, pagination_on_command,
  2241.                _("Enable pagination"));
  2242.       add_com ("sm", class_support, pagination_off_command,
  2243.                _("Disable pagination"));
  2244.     }

  2245.   add_setshow_boolean_cmd ("sevenbit-strings", class_support,
  2246.                            &sevenbit_strings, _("\
  2247. Set printing of 8-bit characters in strings as \\nnn."), _("\
  2248. Show printing of 8-bit characters in strings as \\nnn."), NULL,
  2249.                            NULL,
  2250.                            show_sevenbit_strings,
  2251.                            &setprintlist, &showprintlist);

  2252.   add_setshow_boolean_cmd ("timestamp", class_maintenance,
  2253.                             &debug_timestamp, _("\
  2254. Set timestamping of debugging messages."), _("\
  2255. Show timestamping of debugging messages."), _("\
  2256. When set, debugging messages will be marked with seconds and microseconds."),
  2257.                            NULL,
  2258.                            show_debug_timestamp,
  2259.                            &setdebuglist, &showdebuglist);
  2260. }

  2261. const char *
  2262. paddress (struct gdbarch *gdbarch, CORE_ADDR addr)
  2263. {
  2264.   /* Truncate address to the size of a target address, avoiding shifts
  2265.      larger or equal than the width of a CORE_ADDR.  The local
  2266.      variable ADDR_BIT stops the compiler reporting a shift overflow
  2267.      when it won't occur.  */
  2268.   /* NOTE: This assumes that the significant address information is
  2269.      kept in the least significant bits of ADDR - the upper bits were
  2270.      either zero or sign extended.  Should gdbarch_address_to_pointer or
  2271.      some ADDRESS_TO_PRINTABLE() be used to do the conversion?  */

  2272.   int addr_bit = gdbarch_addr_bit (gdbarch);

  2273.   if (addr_bit < (sizeof (CORE_ADDR) * HOST_CHAR_BIT))
  2274.     addr &= ((CORE_ADDR) 1 << addr_bit) - 1;
  2275.   return hex_string (addr);
  2276. }

  2277. /* This function is described in "defs.h".  */

  2278. const char *
  2279. print_core_address (struct gdbarch *gdbarch, CORE_ADDR address)
  2280. {
  2281.   int addr_bit = gdbarch_addr_bit (gdbarch);

  2282.   if (addr_bit < (sizeof (CORE_ADDR) * HOST_CHAR_BIT))
  2283.     address &= ((CORE_ADDR) 1 << addr_bit) - 1;

  2284.   /* FIXME: cagney/2002-05-03: Need local_address_string() function
  2285.      that returns the language localized string formatted to a width
  2286.      based on gdbarch_addr_bit.  */
  2287.   if (addr_bit <= 32)
  2288.     return hex_string_custom (address, 8);
  2289.   else
  2290.     return hex_string_custom (address, 16);
  2291. }

  2292. /* Callback hash_f for htab_create_alloc or htab_create_alloc_ex.  */

  2293. hashval_t
  2294. core_addr_hash (const void *ap)
  2295. {
  2296.   const CORE_ADDR *addrp = ap;

  2297.   return *addrp;
  2298. }

  2299. /* Callback eq_f for htab_create_alloc or htab_create_alloc_ex.  */

  2300. int
  2301. core_addr_eq (const void *ap, const void *bp)
  2302. {
  2303.   const CORE_ADDR *addr_ap = ap;
  2304.   const CORE_ADDR *addr_bp = bp;

  2305.   return *addr_ap == *addr_bp;
  2306. }

  2307. /* Convert a string back into a CORE_ADDR.  */
  2308. CORE_ADDR
  2309. string_to_core_addr (const char *my_string)
  2310. {
  2311.   CORE_ADDR addr = 0;

  2312.   if (my_string[0] == '0' && tolower (my_string[1]) == 'x')
  2313.     {
  2314.       /* Assume that it is in hex.  */
  2315.       int i;

  2316.       for (i = 2; my_string[i] != '\0'; i++)
  2317.         {
  2318.           if (isdigit (my_string[i]))
  2319.             addr = (my_string[i] - '0') + (addr * 16);
  2320.           else if (isxdigit (my_string[i]))
  2321.             addr = (tolower (my_string[i]) - 'a' + 0xa) + (addr * 16);
  2322.           else
  2323.             error (_("invalid hex \"%s\""), my_string);
  2324.         }
  2325.     }
  2326.   else
  2327.     {
  2328.       /* Assume that it is in decimal.  */
  2329.       int i;

  2330.       for (i = 0; my_string[i] != '\0'; i++)
  2331.         {
  2332.           if (isdigit (my_string[i]))
  2333.             addr = (my_string[i] - '0') + (addr * 10);
  2334.           else
  2335.             error (_("invalid decimal \"%s\""), my_string);
  2336.         }
  2337.     }

  2338.   return addr;
  2339. }

  2340. char *
  2341. gdb_realpath (const char *filename)
  2342. {
  2343. /* On most hosts, we rely on canonicalize_file_name to compute
  2344.    the FILENAME's realpath.

  2345.    But the situation is slightly more complex on Windows, due to some
  2346.    versions of GCC which were reported to generate paths where
  2347.    backlashes (the directory separator) were doubled.  For instance:
  2348.       c:\\some\\double\\slashes\\dir
  2349.    ... instead of ...
  2350.       c:\some\double\slashes\dir
  2351.    Those double-slashes were getting in the way when comparing paths,
  2352.    for instance when trying to insert a breakpoint as follow:
  2353.       (gdb) b c:/some/double/slashes/dir/foo.c:4
  2354.       No source file named c:/some/double/slashes/dir/foo.c:4.
  2355.       (gdb) b c:\some\double\slashes\dir\foo.c:4
  2356.       No source file named c:\some\double\slashes\dir\foo.c:4.
  2357.    To prevent this from happening, we need this function to always
  2358.    strip those extra backslashes.  While canonicalize_file_name does
  2359.    perform this simplification, it only works when the path is valid.
  2360.    Since the simplification would be useful even if the path is not
  2361.    valid (one can always set a breakpoint on a file, even if the file
  2362.    does not exist locally), we rely instead on GetFullPathName to
  2363.    perform the canonicalization.  */

  2364. #if defined (_WIN32)
  2365.   {
  2366.     char buf[MAX_PATH];
  2367.     DWORD len = GetFullPathName (filename, MAX_PATH, buf, NULL);

  2368.     /* The file system is case-insensitive but case-preserving.
  2369.        So it is important we do not lowercase the path.  Otherwise,
  2370.        we might not be able to display the original casing in a given
  2371.        path.  */
  2372.     if (len > 0 && len < MAX_PATH)
  2373.       return xstrdup (buf);
  2374.   }
  2375. #else
  2376.   {
  2377.     char *rp = canonicalize_file_name (filename);

  2378.     if (rp != NULL)
  2379.       return rp;
  2380.   }
  2381. #endif

  2382.   /* This system is a lost cause, just dup the buffer.  */
  2383.   return xstrdup (filename);
  2384. }

  2385. /* Return a copy of FILENAME, with its directory prefix canonicalized
  2386.    by gdb_realpath.  */

  2387. char *
  2388. gdb_realpath_keepfile (const char *filename)
  2389. {
  2390.   const char *base_name = lbasename (filename);
  2391.   char *dir_name;
  2392.   char *real_path;
  2393.   char *result;

  2394.   /* Extract the basename of filename, and return immediately
  2395.      a copy of filename if it does not contain any directory prefix.  */
  2396.   if (base_name == filename)
  2397.     return xstrdup (filename);

  2398.   dir_name = alloca ((size_t) (base_name - filename + 2));
  2399.   /* Allocate enough space to store the dir_name + plus one extra
  2400.      character sometimes needed under Windows (see below), and
  2401.      then the closing \000 character.  */
  2402.   strncpy (dir_name, filename, base_name - filename);
  2403.   dir_name[base_name - filename] = '\000';

  2404. #ifdef HAVE_DOS_BASED_FILE_SYSTEM
  2405.   /* We need to be careful when filename is of the form 'd:foo', which
  2406.      is equivalent of d:./foo, which is totally different from d:/foo.  */
  2407.   if (strlen (dir_name) == 2 && isalpha (dir_name[0]) && dir_name[1] == ':')
  2408.     {
  2409.       dir_name[2] = '.';
  2410.       dir_name[3] = '\000';
  2411.     }
  2412. #endif

  2413.   /* Canonicalize the directory prefix, and build the resulting
  2414.      filename.  If the dirname realpath already contains an ending
  2415.      directory separator, avoid doubling it.  */
  2416.   real_path = gdb_realpath (dir_name);
  2417.   if (IS_DIR_SEPARATOR (real_path[strlen (real_path) - 1]))
  2418.     result = concat (real_path, base_name, (char *) NULL);
  2419.   else
  2420.     result = concat (real_path, SLASH_STRING, base_name, (char *) NULL);

  2421.   xfree (real_path);
  2422.   return result;
  2423. }

  2424. /* Return PATH in absolute form, performing tilde-expansion if necessary.
  2425.    PATH cannot be NULL or the empty string.
  2426.    This does not resolve symlinks however, use gdb_realpath for that.
  2427.    Space for the result is allocated with malloc.
  2428.    If the path is already absolute, it is strdup'd.
  2429.    If there is a problem computing the absolute path, the path is returned
  2430.    unchanged (still strdup'd).  */

  2431. char *
  2432. gdb_abspath (const char *path)
  2433. {
  2434.   gdb_assert (path != NULL && path[0] != '\0');

  2435.   if (path[0] == '~')
  2436.     return tilde_expand (path);

  2437.   if (IS_ABSOLUTE_PATH (path))
  2438.     return xstrdup (path);

  2439.   /* Beware the // my son, the Emacs barfs, the botch that catch...  */
  2440.   return concat (current_directory,
  2441.             IS_DIR_SEPARATOR (current_directory[strlen (current_directory) - 1])
  2442.                  ? "" : SLASH_STRING,
  2443.                  path, (char *) NULL);
  2444. }

  2445. ULONGEST
  2446. align_up (ULONGEST v, int n)
  2447. {
  2448.   /* Check that N is really a power of two.  */
  2449.   gdb_assert (n && (n & (n-1)) == 0);
  2450.   return (v + n - 1) & -n;
  2451. }

  2452. ULONGEST
  2453. align_down (ULONGEST v, int n)
  2454. {
  2455.   /* Check that N is really a power of two.  */
  2456.   gdb_assert (n && (n & (n-1)) == 0);
  2457.   return (v & -n);
  2458. }

  2459. /* Allocation function for the libiberty hash table which uses an
  2460.    obstack.  The obstack is passed as DATA.  */

  2461. void *
  2462. hashtab_obstack_allocate (void *data, size_t size, size_t count)
  2463. {
  2464.   size_t total = size * count;
  2465.   void *ptr = obstack_alloc ((struct obstack *) data, total);

  2466.   memset (ptr, 0, total);
  2467.   return ptr;
  2468. }

  2469. /* Trivial deallocation function for the libiberty splay tree and hash
  2470.    table - don't deallocate anything.  Rely on later deletion of the
  2471.    obstack.  DATA will be the obstack, although it is not needed
  2472.    here.  */

  2473. void
  2474. dummy_obstack_deallocate (void *object, void *data)
  2475. {
  2476.   return;
  2477. }

  2478. /* The bit offset of the highest byte in a ULONGEST, for overflow
  2479.    checking.  */

  2480. #define HIGH_BYTE_POSN ((sizeof (ULONGEST) - 1) * HOST_CHAR_BIT)

  2481. /* True (non-zero) iff DIGIT is a valid digit in radix BASE,
  2482.    where 2 <= BASE <= 36.  */

  2483. static int
  2484. is_digit_in_base (unsigned char digit, int base)
  2485. {
  2486.   if (!isalnum (digit))
  2487.     return 0;
  2488.   if (base <= 10)
  2489.     return (isdigit (digit) && digit < base + '0');
  2490.   else
  2491.     return (isdigit (digit) || tolower (digit) < base - 10 + 'a');
  2492. }

  2493. static int
  2494. digit_to_int (unsigned char c)
  2495. {
  2496.   if (isdigit (c))
  2497.     return c - '0';
  2498.   else
  2499.     return tolower (c) - 'a' + 10;
  2500. }

  2501. /* As for strtoul, but for ULONGEST results.  */

  2502. ULONGEST
  2503. strtoulst (const char *num, const char **trailer, int base)
  2504. {
  2505.   unsigned int high_part;
  2506.   ULONGEST result;
  2507.   int minus = 0;
  2508.   int i = 0;

  2509.   /* Skip leading whitespace.  */
  2510.   while (isspace (num[i]))
  2511.     i++;

  2512.   /* Handle prefixes.  */
  2513.   if (num[i] == '+')
  2514.     i++;
  2515.   else if (num[i] == '-')
  2516.     {
  2517.       minus = 1;
  2518.       i++;
  2519.     }

  2520.   if (base == 0 || base == 16)
  2521.     {
  2522.       if (num[i] == '0' && (num[i + 1] == 'x' || num[i + 1] == 'X'))
  2523.         {
  2524.           i += 2;
  2525.           if (base == 0)
  2526.             base = 16;
  2527.         }
  2528.     }

  2529.   if (base == 0 && num[i] == '0')
  2530.     base = 8;

  2531.   if (base == 0)
  2532.     base = 10;

  2533.   if (base < 2 || base > 36)
  2534.     {
  2535.       errno = EINVAL;
  2536.       return 0;
  2537.     }

  2538.   result = high_part = 0;
  2539.   for (; is_digit_in_base (num[i], base); i += 1)
  2540.     {
  2541.       result = result * base + digit_to_int (num[i]);
  2542.       high_part = high_part * base + (unsigned int) (result >> HIGH_BYTE_POSN);
  2543.       result &= ((ULONGEST) 1 << HIGH_BYTE_POSN) - 1;
  2544.       if (high_part > 0xff)
  2545.         {
  2546.           errno = ERANGE;
  2547.           result = ~ (ULONGEST) 0;
  2548.           high_part = 0;
  2549.           minus = 0;
  2550.           break;
  2551.         }
  2552.     }

  2553.   if (trailer != NULL)
  2554.     *trailer = &num[i];

  2555.   result = result + ((ULONGEST) high_part << HIGH_BYTE_POSN);
  2556.   if (minus)
  2557.     return -result;
  2558.   else
  2559.     return result;
  2560. }

  2561. /* Simple, portable version of dirname that does not modify its
  2562.    argument.  */

  2563. char *
  2564. ldirname (const char *filename)
  2565. {
  2566.   const char *base = lbasename (filename);
  2567.   char *dirname;

  2568.   while (base > filename && IS_DIR_SEPARATOR (base[-1]))
  2569.     --base;

  2570.   if (base == filename)
  2571.     return NULL;

  2572.   dirname = xmalloc (base - filename + 2);
  2573.   memcpy (dirname, filename, base - filename);

  2574.   /* On DOS based file systems, convert "d:foo" to "d:.", so that we
  2575.      create "d:./bar" later instead of the (different) "d:/bar".  */
  2576.   if (base - filename == 2 && IS_ABSOLUTE_PATH (base)
  2577.       && !IS_DIR_SEPARATOR (filename[0]))
  2578.     dirname[base++ - filename] = '.';

  2579.   dirname[base - filename] = '\0';
  2580.   return dirname;
  2581. }

  2582. /* Call libiberty's buildargv, and return the result.
  2583.    If buildargv fails due to out-of-memory, call nomem.
  2584.    Therefore, the returned value is guaranteed to be non-NULL,
  2585.    unless the parameter itself is NULL.  */

  2586. char **
  2587. gdb_buildargv (const char *s)
  2588. {
  2589.   char **argv = buildargv (s);

  2590.   if (s != NULL && argv == NULL)
  2591.     malloc_failure (0);
  2592.   return argv;
  2593. }

  2594. int
  2595. compare_positive_ints (const void *ap, const void *bp)
  2596. {
  2597.   /* Because we know we're comparing two ints which are positive,
  2598.      there's no danger of overflow here.  */
  2599.   return * (int *) ap - * (int *) bp;
  2600. }

  2601. /* String compare function for qsort.  */

  2602. int
  2603. compare_strings (const void *arg1, const void *arg2)
  2604. {
  2605.   const char **s1 = (const char **) arg1;
  2606.   const char **s2 = (const char **) arg2;

  2607.   return strcmp (*s1, *s2);
  2608. }

  2609. #define AMBIGUOUS_MESS1        ".\nMatching formats:"
  2610. #define AMBIGUOUS_MESS2        \
  2611.   ".\nUse \"set gnutarget format-name\" to specify the format."

  2612. const char *
  2613. gdb_bfd_errmsg (bfd_error_type error_tag, char **matching)
  2614. {
  2615.   char *ret, *retp;
  2616.   int ret_len;
  2617.   char **p;

  2618.   /* Check if errmsg just need simple return.  */
  2619.   if (error_tag != bfd_error_file_ambiguously_recognized || matching == NULL)
  2620.     return bfd_errmsg (error_tag);

  2621.   ret_len = strlen (bfd_errmsg (error_tag)) + strlen (AMBIGUOUS_MESS1)
  2622.             + strlen (AMBIGUOUS_MESS2);
  2623.   for (p = matching; *p; p++)
  2624.     ret_len += strlen (*p) + 1;
  2625.   ret = xmalloc (ret_len + 1);
  2626.   retp = ret;
  2627.   make_cleanup (xfree, ret);

  2628.   strcpy (retp, bfd_errmsg (error_tag));
  2629.   retp += strlen (retp);

  2630.   strcpy (retp, AMBIGUOUS_MESS1);
  2631.   retp += strlen (retp);

  2632.   for (p = matching; *p; p++)
  2633.     {
  2634.       sprintf (retp, " %s", *p);
  2635.       retp += strlen (retp);
  2636.     }
  2637.   xfree (matching);

  2638.   strcpy (retp, AMBIGUOUS_MESS2);

  2639.   return ret;
  2640. }

  2641. /* Return ARGS parsed as a valid pid, or throw an error.  */

  2642. int
  2643. parse_pid_to_attach (const char *args)
  2644. {
  2645.   unsigned long pid;
  2646.   char *dummy;

  2647.   if (!args)
  2648.     error_no_arg (_("process-id to attach"));

  2649.   dummy = (char *) args;
  2650.   pid = strtoul (args, &dummy, 0);
  2651.   /* Some targets don't set errno on errors, grrr!  */
  2652.   if ((pid == 0 && dummy == args) || dummy != &args[strlen (args)])
  2653.     error (_("Illegal process-id: %s."), args);

  2654.   return pid;
  2655. }

  2656. /* Helper for make_bpstat_clear_actions_cleanup.  */

  2657. static void
  2658. do_bpstat_clear_actions_cleanup (void *unused)
  2659. {
  2660.   bpstat_clear_actions ();
  2661. }

  2662. /* Call bpstat_clear_actions for the case an exception is throw.  You should
  2663.    discard_cleanups if no exception is caught.  */

  2664. struct cleanup *
  2665. make_bpstat_clear_actions_cleanup (void)
  2666. {
  2667.   return make_cleanup (do_bpstat_clear_actions_cleanup, NULL);
  2668. }

  2669. /* Check for GCC >= 4.x according to the symtab->producer string.  Return minor
  2670.    version (x) of 4.x in such case.  If it is not GCC or it is GCC older than
  2671.    4.x return -1.  If it is GCC 5.x or higher return INT_MAX.  */

  2672. int
  2673. producer_is_gcc_ge_4 (const char *producer)
  2674. {
  2675.   const char *cs;
  2676.   int major, minor;

  2677.   if (producer == NULL)
  2678.     {
  2679.       /* For unknown compilers expect their behavior is not compliant.  For GCC
  2680.          this case can also happen for -gdwarf-4 type units supported since
  2681.          gcc-4.5.  */

  2682.       return -1;
  2683.     }

  2684.   /* Skip any identifier after "GNU " - such as "C++" or "Java".  */

  2685.   if (strncmp (producer, "GNU ", strlen ("GNU ")) != 0)
  2686.     {
  2687.       /* For non-GCC compilers expect their behavior is not compliant.  */

  2688.       return -1;
  2689.     }
  2690.   cs = &producer[strlen ("GNU ")];
  2691.   while (*cs && !isdigit (*cs))
  2692.     cs++;
  2693.   if (sscanf (cs, "%d.%d", &major, &minor) != 2)
  2694.     {
  2695.       /* Not recognized as GCC.  */

  2696.       return -1;
  2697.     }

  2698.   if (major < 4)
  2699.     return -1;
  2700.   if (major > 4)
  2701.     return INT_MAX;
  2702.   return minor;
  2703. }

  2704. /* Helper for make_cleanup_free_char_ptr_vec.  */

  2705. static void
  2706. do_free_char_ptr_vec (void *arg)
  2707. {
  2708.   VEC (char_ptr) *char_ptr_vec = arg;

  2709.   free_char_ptr_vec (char_ptr_vec);
  2710. }

  2711. /* Make cleanup handler calling xfree for each element of CHAR_PTR_VEC and
  2712.    final VEC_free for CHAR_PTR_VEC itself.

  2713.    You must not modify CHAR_PTR_VEC after this cleanup registration as the
  2714.    CHAR_PTR_VEC base address may change on its updates.  Contrary to VEC_free
  2715.    this function does not (cannot) clear the pointer.  */

  2716. struct cleanup *
  2717. make_cleanup_free_char_ptr_vec (VEC (char_ptr) *char_ptr_vec)
  2718. {
  2719.   return make_cleanup (do_free_char_ptr_vec, char_ptr_vec);
  2720. }

  2721. /* Substitute all occurences of string FROM by string TO in *STRINGP.  *STRINGP
  2722.    must come from xrealloc-compatible allocator and it may be updated.  FROM
  2723.    needs to be delimited by IS_DIR_SEPARATOR or DIRNAME_SEPARATOR (or be
  2724.    located at the start or end of *STRINGP.  */

  2725. void
  2726. substitute_path_component (char **stringp, const char *from, const char *to)
  2727. {
  2728.   char *string = *stringp, *s;
  2729.   const size_t from_len = strlen (from);
  2730.   const size_t to_len = strlen (to);

  2731.   for (s = string;;)
  2732.     {
  2733.       s = strstr (s, from);
  2734.       if (s == NULL)
  2735.         break;

  2736.       if ((s == string || IS_DIR_SEPARATOR (s[-1])
  2737.            || s[-1] == DIRNAME_SEPARATOR)
  2738.           && (s[from_len] == '\0' || IS_DIR_SEPARATOR (s[from_len])
  2739.               || s[from_len] == DIRNAME_SEPARATOR))
  2740.         {
  2741.           char *string_new;

  2742.           string_new = xrealloc (string, (strlen (string) + to_len + 1));

  2743.           /* Relocate the current S pointer.  */
  2744.           s = s - string + string_new;
  2745.           string = string_new;

  2746.           /* Replace from by to.  */
  2747.           memmove (&s[to_len], &s[from_len], strlen (&s[from_len]) + 1);
  2748.           memcpy (s, to, to_len);

  2749.           s += to_len;
  2750.         }
  2751.       else
  2752.         s++;
  2753.     }

  2754.   *stringp = string;
  2755. }

  2756. #ifdef HAVE_WAITPID

  2757. #ifdef SIGALRM

  2758. /* SIGALRM handler for waitpid_with_timeout.  */

  2759. static void
  2760. sigalrm_handler (int signo)
  2761. {
  2762.   /* Nothing to do.  */
  2763. }

  2764. #endif

  2765. /* Wrapper to wait for child PID to die with TIMEOUT.
  2766.    TIMEOUT is the time to stop waiting in seconds.
  2767.    If TIMEOUT is zero, pass WNOHANG to waitpid.
  2768.    Returns PID if it was successfully waited for, otherwise -1.

  2769.    Timeouts are currently implemented with alarm and SIGALRM.
  2770.    If the host does not support them, this waits "forever".
  2771.    It would be odd though for a host to have waitpid and not SIGALRM.  */

  2772. pid_t
  2773. wait_to_die_with_timeout (pid_t pid, int *status, int timeout)
  2774. {
  2775.   pid_t waitpid_result;

  2776.   gdb_assert (pid > 0);
  2777.   gdb_assert (timeout >= 0);

  2778.   if (timeout > 0)
  2779.     {
  2780. #ifdef SIGALRM
  2781. #if defined (HAVE_SIGACTION) && defined (SA_RESTART)
  2782.       struct sigaction sa, old_sa;

  2783.       sa.sa_handler = sigalrm_handler;
  2784.       sigemptyset (&sa.sa_mask);
  2785.       sa.sa_flags = 0;
  2786.       sigaction (SIGALRM, &sa, &old_sa);
  2787. #else
  2788.       void (*ofunc) ();

  2789.       ofunc = (void (*)()) signal (SIGALRM, sigalrm_handler);
  2790. #endif

  2791.       alarm (timeout);
  2792. #endif

  2793.       waitpid_result = waitpid (pid, status, 0);

  2794. #ifdef SIGALRM
  2795.       alarm (0);
  2796. #if defined (HAVE_SIGACTION) && defined (SA_RESTART)
  2797.       sigaction (SIGALRM, &old_sa, NULL);
  2798. #else
  2799.       signal (SIGALRM, ofunc);
  2800. #endif
  2801. #endif
  2802.     }
  2803.   else
  2804.     waitpid_result = waitpid (pid, status, WNOHANG);

  2805.   if (waitpid_result == pid)
  2806.     return pid;
  2807.   else
  2808.     return -1;
  2809. }

  2810. #endif /* HAVE_WAITPID */

  2811. /* Provide fnmatch compatible function for FNM_FILE_NAME matching of host files.
  2812.    Both FNM_FILE_NAME and FNM_NOESCAPE must be set in FLAGS.

  2813.    It handles correctly HAVE_DOS_BASED_FILE_SYSTEM and
  2814.    HAVE_CASE_INSENSITIVE_FILE_SYSTEM.  */

  2815. int
  2816. gdb_filename_fnmatch (const char *pattern, const char *string, int flags)
  2817. {
  2818.   gdb_assert ((flags & FNM_FILE_NAME) != 0);

  2819.   /* It is unclear how '\' escaping vs. directory separator should coexist.  */
  2820.   gdb_assert ((flags & FNM_NOESCAPE) != 0);

  2821. #ifdef HAVE_DOS_BASED_FILE_SYSTEM
  2822.   {
  2823.     char *pattern_slash, *string_slash;

  2824.     /* Replace '\' by '/' in both strings.  */

  2825.     pattern_slash = alloca (strlen (pattern) + 1);
  2826.     strcpy (pattern_slash, pattern);
  2827.     pattern = pattern_slash;
  2828.     for (; *pattern_slash != 0; pattern_slash++)
  2829.       if (IS_DIR_SEPARATOR (*pattern_slash))
  2830.         *pattern_slash = '/';

  2831.     string_slash = alloca (strlen (string) + 1);
  2832.     strcpy (string_slash, string);
  2833.     string = string_slash;
  2834.     for (; *string_slash != 0; string_slash++)
  2835.       if (IS_DIR_SEPARATOR (*string_slash))
  2836.         *string_slash = '/';
  2837.   }
  2838. #endif /* HAVE_DOS_BASED_FILE_SYSTEM */

  2839. #ifdef HAVE_CASE_INSENSITIVE_FILE_SYSTEM
  2840.   flags |= FNM_CASEFOLD;
  2841. #endif /* HAVE_CASE_INSENSITIVE_FILE_SYSTEM */

  2842.   return fnmatch (pattern, string, flags);
  2843. }

  2844. /* Provide a prototype to silence -Wmissing-prototypes.  */
  2845. extern initialize_file_ftype _initialize_utils;

  2846. void
  2847. _initialize_utils (void)
  2848. {
  2849.   add_internal_problem_command (&internal_error_problem);
  2850.   add_internal_problem_command (&internal_warning_problem);
  2851.   add_internal_problem_command (&demangler_warning_problem);
  2852. }