* common/gdb_vecs.h: Moved here from ./gdb_vecs.h.
[platform/upstream/binutils.git] / gdb / utils.c
1 /* General utility routines for GDB, the GNU debugger.
2
3    Copyright (C) 1986, 1988-2012 Free Software Foundation, Inc.
4
5    This file is part of GDB.
6
7    This program is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 3 of the License, or
10    (at your option) any later version.
11
12    This program is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16
17    You should have received a copy of the GNU General Public License
18    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
19
20 #include "defs.h"
21 #include "dyn-string.h"
22 #include "gdb_assert.h"
23 #include <ctype.h>
24 #include "gdb_string.h"
25 #include "gdb_wait.h"
26 #include "event-top.h"
27 #include "exceptions.h"
28 #include "gdbthread.h"
29 #include "fnmatch.h"
30 #include "gdb_bfd.h"
31 #ifdef HAVE_SYS_RESOURCE_H
32 #include <sys/resource.h>
33 #endif /* HAVE_SYS_RESOURCE_H */
34
35 #ifdef TUI
36 #include "tui/tui.h"            /* For tui_get_command_dimension.   */
37 #endif
38
39 #ifdef __GO32__
40 #include <pc.h>
41 #endif
42
43 /* SunOS's curses.h has a '#define reg register' in it.  Thank you Sun.  */
44 #ifdef reg
45 #undef reg
46 #endif
47
48 #include <signal.h>
49 #include "timeval-utils.h"
50 #include "gdbcmd.h"
51 #include "serial.h"
52 #include "bfd.h"
53 #include "target.h"
54 #include "gdb-demangle.h"
55 #include "expression.h"
56 #include "language.h"
57 #include "charset.h"
58 #include "annotate.h"
59 #include "filenames.h"
60 #include "symfile.h"
61 #include "gdb_obstack.h"
62 #include "gdbcore.h"
63 #include "top.h"
64 #include "main.h"
65 #include "solist.h"
66
67 #include "inferior.h"           /* for signed_pointer_to_address */
68
69 #include <sys/param.h>          /* For MAXPATHLEN */
70
71 #include "gdb_curses.h"
72
73 #include "readline/readline.h"
74
75 #include <sys/time.h>
76 #include <time.h>
77
78 #include "gdb_usleep.h"
79 #include "interps.h"
80 #include "gdb_regex.h"
81
82 #if !HAVE_DECL_MALLOC
83 extern PTR malloc ();           /* ARI: PTR */
84 #endif
85 #if !HAVE_DECL_REALLOC
86 extern PTR realloc ();          /* ARI: PTR */
87 #endif
88 #if !HAVE_DECL_FREE
89 extern void free ();
90 #endif
91
92 /* readline defines this.  */
93 #undef savestring
94
95 void (*deprecated_error_begin_hook) (void);
96
97 /* Prototypes for local functions */
98
99 static void vfprintf_maybe_filtered (struct ui_file *, const char *,
100                                      va_list, int) ATTRIBUTE_PRINTF (2, 0);
101
102 static void fputs_maybe_filtered (const char *, struct ui_file *, int);
103
104 static void prompt_for_continue (void);
105
106 static void set_screen_size (void);
107 static void set_width (void);
108
109 /* A flag indicating whether to timestamp debugging messages.  */
110
111 static int debug_timestamp = 0;
112
113 /* Nonzero if we have job control.  */
114
115 int job_control;
116
117 /* Nonzero means a quit has been requested.  */
118
119 int quit_flag;
120
121 /* Nonzero means quit immediately if Control-C is typed now, rather
122    than waiting until QUIT is executed.  Be careful in setting this;
123    code which executes with immediate_quit set has to be very careful
124    about being able to deal with being interrupted at any time.  It is
125    almost always better to use QUIT; the only exception I can think of
126    is being able to quit out of a system call (using EINTR loses if
127    the SIGINT happens between the previous QUIT and the system call).
128    To immediately quit in the case in which a SIGINT happens between
129    the previous QUIT and setting immediate_quit (desirable anytime we
130    expect to block), call QUIT after setting immediate_quit.  */
131
132 int immediate_quit;
133
134 /* Nonzero means that strings with character values >0x7F should be printed
135    as octal escapes.  Zero means just print the value (e.g. it's an
136    international character, and the terminal or window can cope.)  */
137
138 int sevenbit_strings = 0;
139 static void
140 show_sevenbit_strings (struct ui_file *file, int from_tty,
141                        struct cmd_list_element *c, const char *value)
142 {
143   fprintf_filtered (file, _("Printing of 8-bit characters "
144                             "in strings as \\nnn is %s.\n"),
145                     value);
146 }
147
148 /* String to be printed before error messages, if any.  */
149
150 char *error_pre_print;
151
152 /* String to be printed before quit messages, if any.  */
153
154 char *quit_pre_print;
155
156 /* String to be printed before warning messages, if any.  */
157
158 char *warning_pre_print = "\nwarning: ";
159
160 int pagination_enabled = 1;
161 static void
162 show_pagination_enabled (struct ui_file *file, int from_tty,
163                          struct cmd_list_element *c, const char *value)
164 {
165   fprintf_filtered (file, _("State of pagination is %s.\n"), value);
166 }
167
168 \f
169 /* Cleanup utilities.
170
171    These are not defined in cleanups.c (nor declared in cleanups.h)
172    because while they use the "cleanup API" they are not part of the
173    "cleanup API".  */
174
175 static void
176 do_freeargv (void *arg)
177 {
178   freeargv ((char **) arg);
179 }
180
181 struct cleanup *
182 make_cleanup_freeargv (char **arg)
183 {
184   return make_cleanup (do_freeargv, arg);
185 }
186
187 static void
188 do_dyn_string_delete (void *arg)
189 {
190   dyn_string_delete ((dyn_string_t) arg);
191 }
192
193 struct cleanup *
194 make_cleanup_dyn_string_delete (dyn_string_t arg)
195 {
196   return make_cleanup (do_dyn_string_delete, arg);
197 }
198
199 static void
200 do_bfd_close_cleanup (void *arg)
201 {
202   gdb_bfd_unref (arg);
203 }
204
205 struct cleanup *
206 make_cleanup_bfd_unref (bfd *abfd)
207 {
208   return make_cleanup (do_bfd_close_cleanup, abfd);
209 }
210
211 static void
212 do_close_cleanup (void *arg)
213 {
214   int *fd = arg;
215
216   close (*fd);
217 }
218
219 struct cleanup *
220 make_cleanup_close (int fd)
221 {
222   int *saved_fd = xmalloc (sizeof (fd));
223
224   *saved_fd = fd;
225   return make_cleanup_dtor (do_close_cleanup, saved_fd, xfree);
226 }
227
228 /* Helper function which does the work for make_cleanup_fclose.  */
229
230 static void
231 do_fclose_cleanup (void *arg)
232 {
233   FILE *file = arg;
234
235   fclose (file);
236 }
237
238 /* Return a new cleanup that closes FILE.  */
239
240 struct cleanup *
241 make_cleanup_fclose (FILE *file)
242 {
243   return make_cleanup (do_fclose_cleanup, file);
244 }
245
246 /* Helper function which does the work for make_cleanup_obstack_free.  */
247
248 static void
249 do_obstack_free (void *arg)
250 {
251   struct obstack *ob = arg;
252
253   obstack_free (ob, NULL);
254 }
255
256 /* Return a new cleanup that frees OBSTACK.  */
257
258 struct cleanup *
259 make_cleanup_obstack_free (struct obstack *obstack)
260 {
261   return make_cleanup (do_obstack_free, obstack);
262 }
263
264 static void
265 do_ui_file_delete (void *arg)
266 {
267   ui_file_delete (arg);
268 }
269
270 struct cleanup *
271 make_cleanup_ui_file_delete (struct ui_file *arg)
272 {
273   return make_cleanup (do_ui_file_delete, arg);
274 }
275
276 /* Helper function for make_cleanup_ui_out_redirect_pop.  */
277
278 static void
279 do_ui_out_redirect_pop (void *arg)
280 {
281   struct ui_out *uiout = arg;
282
283   if (ui_out_redirect (uiout, NULL) < 0)
284     warning (_("Cannot restore redirection of the current output protocol"));
285 }
286
287 /* Return a new cleanup that pops the last redirection by ui_out_redirect
288    with NULL parameter.  */
289
290 struct cleanup *
291 make_cleanup_ui_out_redirect_pop (struct ui_out *uiout)
292 {
293   return make_cleanup (do_ui_out_redirect_pop, uiout);
294 }
295
296 static void
297 do_free_section_addr_info (void *arg)
298 {
299   free_section_addr_info (arg);
300 }
301
302 struct cleanup *
303 make_cleanup_free_section_addr_info (struct section_addr_info *addrs)
304 {
305   return make_cleanup (do_free_section_addr_info, addrs);
306 }
307
308 struct restore_integer_closure
309 {
310   int *variable;
311   int value;
312 };
313
314 static void
315 restore_integer (void *p)
316 {
317   struct restore_integer_closure *closure = p;
318
319   *(closure->variable) = closure->value;
320 }
321
322 /* Remember the current value of *VARIABLE and make it restored when
323    the cleanup is run.  */
324
325 struct cleanup *
326 make_cleanup_restore_integer (int *variable)
327 {
328   struct restore_integer_closure *c =
329     xmalloc (sizeof (struct restore_integer_closure));
330
331   c->variable = variable;
332   c->value = *variable;
333
334   return make_cleanup_dtor (restore_integer, (void *) c, xfree);
335 }
336
337 /* Remember the current value of *VARIABLE and make it restored when
338    the cleanup is run.  */
339
340 struct cleanup *
341 make_cleanup_restore_uinteger (unsigned int *variable)
342 {
343   return make_cleanup_restore_integer ((int *) variable);
344 }
345
346 /* Helper for make_cleanup_unpush_target.  */
347
348 static void
349 do_unpush_target (void *arg)
350 {
351   struct target_ops *ops = arg;
352
353   unpush_target (ops);
354 }
355
356 /* Return a new cleanup that unpushes OPS.  */
357
358 struct cleanup *
359 make_cleanup_unpush_target (struct target_ops *ops)
360 {
361   return make_cleanup (do_unpush_target, ops);
362 }
363
364 /* Helper for make_cleanup_htab_delete compile time checking the types.  */
365
366 static void
367 do_htab_delete_cleanup (void *htab_voidp)
368 {
369   htab_t htab = htab_voidp;
370
371   htab_delete (htab);
372 }
373
374 /* Return a new cleanup that deletes HTAB.  */
375
376 struct cleanup *
377 make_cleanup_htab_delete (htab_t htab)
378 {
379   return make_cleanup (do_htab_delete_cleanup, htab);
380 }
381
382 struct restore_ui_file_closure
383 {
384   struct ui_file **variable;
385   struct ui_file *value;
386 };
387
388 static void
389 do_restore_ui_file (void *p)
390 {
391   struct restore_ui_file_closure *closure = p;
392
393   *(closure->variable) = closure->value;
394 }
395
396 /* Remember the current value of *VARIABLE and make it restored when
397    the cleanup is run.  */
398
399 struct cleanup *
400 make_cleanup_restore_ui_file (struct ui_file **variable)
401 {
402   struct restore_ui_file_closure *c = XNEW (struct restore_ui_file_closure);
403
404   c->variable = variable;
405   c->value = *variable;
406
407   return make_cleanup_dtor (do_restore_ui_file, (void *) c, xfree);
408 }
409
410 /* Helper for make_cleanup_value_free_to_mark.  */
411
412 static void
413 do_value_free_to_mark (void *value)
414 {
415   value_free_to_mark ((struct value *) value);
416 }
417
418 /* Free all values allocated since MARK was obtained by value_mark
419    (except for those released) when the cleanup is run.  */
420
421 struct cleanup *
422 make_cleanup_value_free_to_mark (struct value *mark)
423 {
424   return make_cleanup (do_value_free_to_mark, mark);
425 }
426
427 /* Helper for make_cleanup_value_free.  */
428
429 static void
430 do_value_free (void *value)
431 {
432   value_free (value);
433 }
434
435 /* Free VALUE.  */
436
437 struct cleanup *
438 make_cleanup_value_free (struct value *value)
439 {
440   return make_cleanup (do_value_free, value);
441 }
442
443 /* Helper for make_cleanup_free_so.  */
444
445 static void
446 do_free_so (void *arg)
447 {
448   struct so_list *so = arg;
449
450   free_so (so);
451 }
452
453 /* Make cleanup handler calling free_so for SO.  */
454
455 struct cleanup *
456 make_cleanup_free_so (struct so_list *so)
457 {
458   return make_cleanup (do_free_so, so);
459 }
460
461 /* This function is useful for cleanups.
462    Do
463
464    foo = xmalloc (...);
465    old_chain = make_cleanup (free_current_contents, &foo);
466
467    to arrange to free the object thus allocated.  */
468
469 void
470 free_current_contents (void *ptr)
471 {
472   void **location = ptr;
473
474   if (location == NULL)
475     internal_error (__FILE__, __LINE__,
476                     _("free_current_contents: NULL pointer"));
477   if (*location != NULL)
478     {
479       xfree (*location);
480       *location = NULL;
481     }
482 }
483
484 /* If nonzero, display time usage both at startup and for each command.  */
485
486 static int display_time;
487
488 /* If nonzero, display space usage both at startup and for each command.  */
489
490 static int display_space;
491
492 /* Records a run time and space usage to be used as a base for
493    reporting elapsed time or change in space.  In addition,
494    the msg_type field indicates whether the saved time is from the
495    beginning of GDB execution (0) or the beginning of an individual 
496    command execution (1).  */
497 struct cmd_stats 
498 {
499   int msg_type;
500   long start_cpu_time;
501   struct timeval start_wall_time;
502   long start_space;
503 };
504
505 /* Set whether to display time statistics to NEW_VALUE (non-zero 
506    means true).  */
507 void
508 set_display_time (int new_value)
509 {
510   display_time = new_value;
511 }
512
513 /* Set whether to display space statistics to NEW_VALUE (non-zero
514    means true).  */
515 void
516 set_display_space (int new_value)
517 {
518   display_space = new_value;
519 }
520
521 /* As indicated by display_time and display_space, report GDB's elapsed time
522    and space usage from the base time and space provided in ARG, which
523    must be a pointer to a struct cmd_stat.  This function is intended
524    to be called as a cleanup.  */
525 static void
526 report_command_stats (void *arg)
527 {
528   struct cmd_stats *start_stats = (struct cmd_stats *) arg;
529   int msg_type = start_stats->msg_type;
530
531   if (display_time)
532     {
533       long cmd_time = get_run_time () - start_stats->start_cpu_time;
534       struct timeval now_wall_time, delta_wall_time;
535
536       gettimeofday (&now_wall_time, NULL);
537       timeval_sub (&delta_wall_time,
538                    &now_wall_time, &start_stats->start_wall_time);
539
540       printf_unfiltered (msg_type == 0
541                          ? _("Startup time: %ld.%06ld (cpu), %ld.%06ld (wall)\n")
542                          : _("Command execution time: %ld.%06ld (cpu), %ld.%06ld (wall)\n"),
543                          cmd_time / 1000000, cmd_time % 1000000,
544                          (long) delta_wall_time.tv_sec,
545                          (long) delta_wall_time.tv_usec);
546     }
547
548   if (display_space)
549     {
550 #ifdef HAVE_SBRK
551       char *lim = (char *) sbrk (0);
552
553       long space_now = lim - lim_at_start;
554       long space_diff = space_now - start_stats->start_space;
555
556       printf_unfiltered (msg_type == 0
557                          ? _("Space used: %ld (%s%ld during startup)\n")
558                          : _("Space used: %ld (%s%ld for this command)\n"),
559                          space_now,
560                          (space_diff >= 0 ? "+" : ""),
561                          space_diff);
562 #endif
563     }
564 }
565
566 /* Create a cleanup that reports time and space used since its
567    creation.  Precise messages depend on MSG_TYPE:
568       0:  Initial time/space
569       1:  Individual command time/space.  */
570 struct cleanup *
571 make_command_stats_cleanup (int msg_type)
572 {
573   struct cmd_stats *new_stat = XMALLOC (struct cmd_stats);
574   
575 #ifdef HAVE_SBRK
576   char *lim = (char *) sbrk (0);
577   new_stat->start_space = lim - lim_at_start;
578 #endif
579
580   new_stat->msg_type = msg_type;
581   new_stat->start_cpu_time = get_run_time ();
582   gettimeofday (&new_stat->start_wall_time, NULL);
583
584   return make_cleanup_dtor (report_command_stats, new_stat, xfree);
585 }
586 \f
587
588
589 /* Print a warning message.  The first argument STRING is the warning
590    message, used as an fprintf format string, the second is the
591    va_list of arguments for that string.  A warning is unfiltered (not
592    paginated) so that the user does not need to page through each
593    screen full of warnings when there are lots of them.  */
594
595 void
596 vwarning (const char *string, va_list args)
597 {
598   if (deprecated_warning_hook)
599     (*deprecated_warning_hook) (string, args);
600   else
601     {
602       target_terminal_ours ();
603       wrap_here ("");           /* Force out any buffered output.  */
604       gdb_flush (gdb_stdout);
605       if (warning_pre_print)
606         fputs_unfiltered (warning_pre_print, gdb_stderr);
607       vfprintf_unfiltered (gdb_stderr, string, args);
608       fprintf_unfiltered (gdb_stderr, "\n");
609       va_end (args);
610     }
611 }
612
613 /* Print a warning message.
614    The first argument STRING is the warning message, used as a fprintf string,
615    and the remaining args are passed as arguments to it.
616    The primary difference between warnings and errors is that a warning
617    does not force the return to command level.  */
618
619 void
620 warning (const char *string, ...)
621 {
622   va_list args;
623
624   va_start (args, string);
625   vwarning (string, args);
626   va_end (args);
627 }
628
629 /* Print an error message and return to command level.
630    The first argument STRING is the error message, used as a fprintf string,
631    and the remaining args are passed as arguments to it.  */
632
633 void
634 verror (const char *string, va_list args)
635 {
636   throw_verror (GENERIC_ERROR, string, args);
637 }
638
639 void
640 error (const char *string, ...)
641 {
642   va_list args;
643
644   va_start (args, string);
645   throw_verror (GENERIC_ERROR, string, args);
646   va_end (args);
647 }
648
649 /* Print an error message and quit.
650    The first argument STRING is the error message, used as a fprintf string,
651    and the remaining args are passed as arguments to it.  */
652
653 void
654 vfatal (const char *string, va_list args)
655 {
656   throw_vfatal (string, args);
657 }
658
659 void
660 fatal (const char *string, ...)
661 {
662   va_list args;
663
664   va_start (args, string);
665   throw_vfatal (string, args);
666   va_end (args);
667 }
668
669 void
670 error_stream (struct ui_file *stream)
671 {
672   char *message = ui_file_xstrdup (stream, NULL);
673
674   make_cleanup (xfree, message);
675   error (("%s"), message);
676 }
677
678 /* Dump core trying to increase the core soft limit to hard limit first.  */
679
680 static void
681 dump_core (void)
682 {
683 #ifdef HAVE_SETRLIMIT
684   struct rlimit rlim = { RLIM_INFINITY, RLIM_INFINITY };
685
686   setrlimit (RLIMIT_CORE, &rlim);
687 #endif /* HAVE_SETRLIMIT */
688
689   abort ();             /* NOTE: GDB has only three calls to abort().  */
690 }
691
692 /* Check whether GDB will be able to dump core using the dump_core
693    function.  */
694
695 static int
696 can_dump_core (const char *reason)
697 {
698 #ifdef HAVE_GETRLIMIT
699   struct rlimit rlim;
700
701   /* Be quiet and assume we can dump if an error is returned.  */
702   if (getrlimit (RLIMIT_CORE, &rlim) != 0)
703     return 1;
704
705   if (rlim.rlim_max == 0)
706     {
707       fprintf_unfiltered (gdb_stderr,
708                           _("%s\nUnable to dump core, use `ulimit -c"
709                             " unlimited' before executing GDB next time.\n"),
710                           reason);
711       return 0;
712     }
713 #endif /* HAVE_GETRLIMIT */
714
715   return 1;
716 }
717
718 /* Allow the user to configure the debugger behavior with respect to
719    what to do when an internal problem is detected.  */
720
721 const char internal_problem_ask[] = "ask";
722 const char internal_problem_yes[] = "yes";
723 const char internal_problem_no[] = "no";
724 static const char *const internal_problem_modes[] =
725 {
726   internal_problem_ask,
727   internal_problem_yes,
728   internal_problem_no,
729   NULL
730 };
731
732 /* Print a message reporting an internal error/warning.  Ask the user
733    if they want to continue, dump core, or just exit.  Return
734    something to indicate a quit.  */
735
736 struct internal_problem
737 {
738   const char *name;
739   const char *should_quit;
740   const char *should_dump_core;
741 };
742
743 /* Report a problem, internal to GDB, to the user.  Once the problem
744    has been reported, and assuming GDB didn't quit, the caller can
745    either allow execution to resume or throw an error.  */
746
747 static void ATTRIBUTE_PRINTF (4, 0)
748 internal_vproblem (struct internal_problem *problem,
749                    const char *file, int line, const char *fmt, va_list ap)
750 {
751   static int dejavu;
752   int quit_p;
753   int dump_core_p;
754   char *reason;
755
756   /* Don't allow infinite error/warning recursion.  */
757   {
758     static char msg[] = "Recursive internal problem.\n";
759
760     switch (dejavu)
761       {
762       case 0:
763         dejavu = 1;
764         break;
765       case 1:
766         dejavu = 2;
767         fputs_unfiltered (msg, gdb_stderr);
768         abort ();       /* NOTE: GDB has only three calls to abort().  */
769       default:
770         dejavu = 3;
771         /* Newer GLIBC versions put the warn_unused_result attribute
772            on write, but this is one of those rare cases where
773            ignoring the return value is correct.  Casting to (void)
774            does not fix this problem.  This is the solution suggested
775            at http://gcc.gnu.org/bugzilla/show_bug.cgi?id=25509.  */
776         if (write (STDERR_FILENO, msg, sizeof (msg)) != sizeof (msg))
777           abort (); /* NOTE: GDB has only three calls to abort().  */
778         exit (1);
779       }
780   }
781
782   /* Try to get the message out and at the start of a new line.  */
783   target_terminal_ours ();
784   begin_line ();
785
786   /* Create a string containing the full error/warning message.  Need
787      to call query with this full string, as otherwize the reason
788      (error/warning) and question become separated.  Format using a
789      style similar to a compiler error message.  Include extra detail
790      so that the user knows that they are living on the edge.  */
791   {
792     char *msg;
793
794     msg = xstrvprintf (fmt, ap);
795     reason = xstrprintf ("%s:%d: %s: %s\n"
796                          "A problem internal to GDB has been detected,\n"
797                          "further debugging may prove unreliable.",
798                          file, line, problem->name, msg);
799     xfree (msg);
800     make_cleanup (xfree, reason);
801   }
802
803   if (problem->should_quit == internal_problem_ask)
804     {
805       /* Default (yes/batch case) is to quit GDB.  When in batch mode
806          this lessens the likelihood of GDB going into an infinite
807          loop.  */
808       if (!confirm)
809         {
810           /* Emit the message and quit.  */
811           fputs_unfiltered (reason, gdb_stderr);
812           fputs_unfiltered ("\n", gdb_stderr);
813           quit_p = 1;
814         }
815       else
816         quit_p = query (_("%s\nQuit this debugging session? "), reason);
817     }
818   else if (problem->should_quit == internal_problem_yes)
819     quit_p = 1;
820   else if (problem->should_quit == internal_problem_no)
821     quit_p = 0;
822   else
823     internal_error (__FILE__, __LINE__, _("bad switch"));
824
825   if (problem->should_dump_core == internal_problem_ask)
826     {
827       if (!can_dump_core (reason))
828         dump_core_p = 0;
829       else
830         {
831           /* Default (yes/batch case) is to dump core.  This leaves a GDB
832              `dropping' so that it is easier to see that something went
833              wrong in GDB.  */
834           dump_core_p = query (_("%s\nCreate a core file of GDB? "), reason);
835         }
836     }
837   else if (problem->should_dump_core == internal_problem_yes)
838     dump_core_p = can_dump_core (reason);
839   else if (problem->should_dump_core == internal_problem_no)
840     dump_core_p = 0;
841   else
842     internal_error (__FILE__, __LINE__, _("bad switch"));
843
844   if (quit_p)
845     {
846       if (dump_core_p)
847         dump_core ();
848       else
849         exit (1);
850     }
851   else
852     {
853       if (dump_core_p)
854         {
855 #ifdef HAVE_WORKING_FORK
856           if (fork () == 0)
857             dump_core ();
858 #endif
859         }
860     }
861
862   dejavu = 0;
863 }
864
865 static struct internal_problem internal_error_problem = {
866   "internal-error", internal_problem_ask, internal_problem_ask
867 };
868
869 void
870 internal_verror (const char *file, int line, const char *fmt, va_list ap)
871 {
872   internal_vproblem (&internal_error_problem, file, line, fmt, ap);
873   deprecated_throw_reason (RETURN_ERROR);
874 }
875
876 void
877 internal_error (const char *file, int line, const char *string, ...)
878 {
879   va_list ap;
880
881   va_start (ap, string);
882   internal_verror (file, line, string, ap);
883   va_end (ap);
884 }
885
886 static struct internal_problem internal_warning_problem = {
887   "internal-warning", internal_problem_ask, internal_problem_ask
888 };
889
890 void
891 internal_vwarning (const char *file, int line, const char *fmt, va_list ap)
892 {
893   internal_vproblem (&internal_warning_problem, file, line, fmt, ap);
894 }
895
896 void
897 internal_warning (const char *file, int line, const char *string, ...)
898 {
899   va_list ap;
900
901   va_start (ap, string);
902   internal_vwarning (file, line, string, ap);
903   va_end (ap);
904 }
905
906 /* Dummy functions to keep add_prefix_cmd happy.  */
907
908 static void
909 set_internal_problem_cmd (char *args, int from_tty)
910 {
911 }
912
913 static void
914 show_internal_problem_cmd (char *args, int from_tty)
915 {
916 }
917
918 /* When GDB reports an internal problem (error or warning) it gives
919    the user the opportunity to quit GDB and/or create a core file of
920    the current debug session.  This function registers a few commands
921    that make it possible to specify that GDB should always or never
922    quit or create a core file, without asking.  The commands look
923    like:
924
925    maint set PROBLEM-NAME quit ask|yes|no
926    maint show PROBLEM-NAME quit
927    maint set PROBLEM-NAME corefile ask|yes|no
928    maint show PROBLEM-NAME corefile
929
930    Where PROBLEM-NAME is currently "internal-error" or
931    "internal-warning".  */
932
933 static void
934 add_internal_problem_command (struct internal_problem *problem)
935 {
936   struct cmd_list_element **set_cmd_list;
937   struct cmd_list_element **show_cmd_list;
938   char *set_doc;
939   char *show_doc;
940
941   set_cmd_list = xmalloc (sizeof (*set_cmd_list));
942   show_cmd_list = xmalloc (sizeof (*set_cmd_list));
943   *set_cmd_list = NULL;
944   *show_cmd_list = NULL;
945
946   set_doc = xstrprintf (_("Configure what GDB does when %s is detected."),
947                         problem->name);
948
949   show_doc = xstrprintf (_("Show what GDB does when %s is detected."),
950                          problem->name);
951
952   add_prefix_cmd ((char*) problem->name,
953                   class_maintenance, set_internal_problem_cmd, set_doc,
954                   set_cmd_list,
955                   concat ("maintenance set ", problem->name, " ",
956                           (char *) NULL),
957                   0/*allow-unknown*/, &maintenance_set_cmdlist);
958
959   add_prefix_cmd ((char*) problem->name,
960                   class_maintenance, show_internal_problem_cmd, show_doc,
961                   show_cmd_list,
962                   concat ("maintenance show ", problem->name, " ",
963                           (char *) NULL),
964                   0/*allow-unknown*/, &maintenance_show_cmdlist);
965
966   set_doc = xstrprintf (_("Set whether GDB should quit "
967                           "when an %s is detected"),
968                         problem->name);
969   show_doc = xstrprintf (_("Show whether GDB will quit "
970                            "when an %s is detected"),
971                          problem->name);
972   add_setshow_enum_cmd ("quit", class_maintenance,
973                         internal_problem_modes,
974                         &problem->should_quit,
975                         set_doc,
976                         show_doc,
977                         NULL, /* help_doc */
978                         NULL, /* setfunc */
979                         NULL, /* showfunc */
980                         set_cmd_list,
981                         show_cmd_list);
982
983   xfree (set_doc);
984   xfree (show_doc);
985
986   set_doc = xstrprintf (_("Set whether GDB should create a core "
987                           "file of GDB when %s is detected"),
988                         problem->name);
989   show_doc = xstrprintf (_("Show whether GDB will create a core "
990                            "file of GDB when %s is detected"),
991                          problem->name);
992   add_setshow_enum_cmd ("corefile", class_maintenance,
993                         internal_problem_modes,
994                         &problem->should_dump_core,
995                         set_doc,
996                         show_doc,
997                         NULL, /* help_doc */
998                         NULL, /* setfunc */
999                         NULL, /* showfunc */
1000                         set_cmd_list,
1001                         show_cmd_list);
1002
1003   xfree (set_doc);
1004   xfree (show_doc);
1005 }
1006
1007 /* Print the system error message for errno, and also mention STRING
1008    as the file name for which the error was encountered.
1009    Then return to command level.  */
1010
1011 void
1012 perror_with_name (const char *string)
1013 {
1014   char *err;
1015   char *combined;
1016
1017   err = safe_strerror (errno);
1018   combined = (char *) alloca (strlen (err) + strlen (string) + 3);
1019   strcpy (combined, string);
1020   strcat (combined, ": ");
1021   strcat (combined, err);
1022
1023   /* I understand setting these is a matter of taste.  Still, some people
1024      may clear errno but not know about bfd_error.  Doing this here is not
1025      unreasonable.  */
1026   bfd_set_error (bfd_error_no_error);
1027   errno = 0;
1028
1029   error (_("%s."), combined);
1030 }
1031
1032 /* Print the system error message for ERRCODE, and also mention STRING
1033    as the file name for which the error was encountered.  */
1034
1035 void
1036 print_sys_errmsg (const char *string, int errcode)
1037 {
1038   char *err;
1039   char *combined;
1040
1041   err = safe_strerror (errcode);
1042   combined = (char *) alloca (strlen (err) + strlen (string) + 3);
1043   strcpy (combined, string);
1044   strcat (combined, ": ");
1045   strcat (combined, err);
1046
1047   /* We want anything which was printed on stdout to come out first, before
1048      this message.  */
1049   gdb_flush (gdb_stdout);
1050   fprintf_unfiltered (gdb_stderr, "%s.\n", combined);
1051 }
1052
1053 /* Control C eventually causes this to be called, at a convenient time.  */
1054
1055 void
1056 quit (void)
1057 {
1058 #ifdef __MSDOS__
1059   /* No steenking SIGINT will ever be coming our way when the
1060      program is resumed.  Don't lie.  */
1061   fatal ("Quit");
1062 #else
1063   if (job_control
1064       /* If there is no terminal switching for this target, then we can't
1065          possibly get screwed by the lack of job control.  */
1066       || current_target.to_terminal_ours == NULL)
1067     fatal ("Quit");
1068   else
1069     fatal ("Quit (expect signal SIGINT when the program is resumed)");
1070 #endif
1071 }
1072
1073 \f
1074 /* Called when a memory allocation fails, with the number of bytes of
1075    memory requested in SIZE.  */
1076
1077 void
1078 malloc_failure (long size)
1079 {
1080   if (size > 0)
1081     {
1082       internal_error (__FILE__, __LINE__,
1083                       _("virtual memory exhausted: can't allocate %ld bytes."),
1084                       size);
1085     }
1086   else
1087     {
1088       internal_error (__FILE__, __LINE__, _("virtual memory exhausted."));
1089     }
1090 }
1091
1092 /* My replacement for the read system call.
1093    Used like `read' but keeps going if `read' returns too soon.  */
1094
1095 int
1096 myread (int desc, char *addr, int len)
1097 {
1098   int val;
1099   int orglen = len;
1100
1101   while (len > 0)
1102     {
1103       val = read (desc, addr, len);
1104       if (val < 0)
1105         return val;
1106       if (val == 0)
1107         return orglen - len;
1108       len -= val;
1109       addr += val;
1110     }
1111   return orglen;
1112 }
1113
1114 /* Make a copy of the string at PTR with SIZE characters
1115    (and add a null character at the end in the copy).
1116    Uses malloc to get the space.  Returns the address of the copy.  */
1117
1118 char *
1119 savestring (const char *ptr, size_t size)
1120 {
1121   char *p = (char *) xmalloc (size + 1);
1122
1123   memcpy (p, ptr, size);
1124   p[size] = 0;
1125   return p;
1126 }
1127
1128 void
1129 print_spaces (int n, struct ui_file *file)
1130 {
1131   fputs_unfiltered (n_spaces (n), file);
1132 }
1133
1134 /* Print a host address.  */
1135
1136 void
1137 gdb_print_host_address (const void *addr, struct ui_file *stream)
1138 {
1139   fprintf_filtered (stream, "%s", host_address_to_string (addr));
1140 }
1141 \f
1142
1143 /* A cleanup function that calls regfree.  */
1144
1145 static void
1146 do_regfree_cleanup (void *r)
1147 {
1148   regfree (r);
1149 }
1150
1151 /* Create a new cleanup that frees the compiled regular expression R.  */
1152
1153 struct cleanup *
1154 make_regfree_cleanup (regex_t *r)
1155 {
1156   return make_cleanup (do_regfree_cleanup, r);
1157 }
1158
1159 /* Return an xmalloc'd error message resulting from a regular
1160    expression compilation failure.  */
1161
1162 char *
1163 get_regcomp_error (int code, regex_t *rx)
1164 {
1165   size_t length = regerror (code, rx, NULL, 0);
1166   char *result = xmalloc (length);
1167
1168   regerror (code, rx, result, length);
1169   return result;
1170 }
1171
1172 \f
1173
1174 /* This function supports the query, nquery, and yquery functions.
1175    Ask user a y-or-n question and return 0 if answer is no, 1 if
1176    answer is yes, or default the answer to the specified default
1177    (for yquery or nquery).  DEFCHAR may be 'y' or 'n' to provide a
1178    default answer, or '\0' for no default.
1179    CTLSTR is the control string and should end in "? ".  It should
1180    not say how to answer, because we do that.
1181    ARGS are the arguments passed along with the CTLSTR argument to
1182    printf.  */
1183
1184 static int ATTRIBUTE_PRINTF (1, 0)
1185 defaulted_query (const char *ctlstr, const char defchar, va_list args)
1186 {
1187   int answer;
1188   int ans2;
1189   int retval;
1190   int def_value;
1191   char def_answer, not_def_answer;
1192   char *y_string, *n_string, *question;
1193
1194   /* Set up according to which answer is the default.  */
1195   if (defchar == '\0')
1196     {
1197       def_value = 1;
1198       def_answer = 'Y';
1199       not_def_answer = 'N';
1200       y_string = "y";
1201       n_string = "n";
1202     }
1203   else if (defchar == 'y')
1204     {
1205       def_value = 1;
1206       def_answer = 'Y';
1207       not_def_answer = 'N';
1208       y_string = "[y]";
1209       n_string = "n";
1210     }
1211   else
1212     {
1213       def_value = 0;
1214       def_answer = 'N';
1215       not_def_answer = 'Y';
1216       y_string = "y";
1217       n_string = "[n]";
1218     }
1219
1220   /* Automatically answer the default value if the user did not want
1221      prompts or the command was issued with the server prefix.  */
1222   if (!confirm || server_command)
1223     return def_value;
1224
1225   /* If input isn't coming from the user directly, just say what
1226      question we're asking, and then answer the default automatically.  This
1227      way, important error messages don't get lost when talking to GDB
1228      over a pipe.  */
1229   if (! input_from_terminal_p ())
1230     {
1231       wrap_here ("");
1232       vfprintf_filtered (gdb_stdout, ctlstr, args);
1233
1234       printf_filtered (_("(%s or %s) [answered %c; "
1235                          "input not from terminal]\n"),
1236                        y_string, n_string, def_answer);
1237       gdb_flush (gdb_stdout);
1238
1239       return def_value;
1240     }
1241
1242   if (deprecated_query_hook)
1243     {
1244       return deprecated_query_hook (ctlstr, args);
1245     }
1246
1247   /* Format the question outside of the loop, to avoid reusing args.  */
1248   question = xstrvprintf (ctlstr, args);
1249
1250   while (1)
1251     {
1252       wrap_here ("");           /* Flush any buffered output.  */
1253       gdb_flush (gdb_stdout);
1254
1255       if (annotation_level > 1)
1256         printf_filtered (("\n\032\032pre-query\n"));
1257
1258       fputs_filtered (question, gdb_stdout);
1259       printf_filtered (_("(%s or %s) "), y_string, n_string);
1260
1261       if (annotation_level > 1)
1262         printf_filtered (("\n\032\032query\n"));
1263
1264       wrap_here ("");
1265       gdb_flush (gdb_stdout);
1266
1267       answer = fgetc (stdin);
1268
1269       /* We expect fgetc to block until a character is read.  But
1270          this may not be the case if the terminal was opened with
1271          the NONBLOCK flag.  In that case, if there is nothing to
1272          read on stdin, fgetc returns EOF, but also sets the error
1273          condition flag on stdin and errno to EAGAIN.  With a true
1274          EOF, stdin's error condition flag is not set.
1275
1276          A situation where this behavior was observed is a pseudo
1277          terminal on AIX.  */
1278       while (answer == EOF && ferror (stdin) && errno == EAGAIN)
1279         {
1280           /* Not a real EOF.  Wait a little while and try again until
1281              we read something.  */
1282           clearerr (stdin);
1283           gdb_usleep (10000);
1284           answer = fgetc (stdin);
1285         }
1286
1287       clearerr (stdin);         /* in case of C-d */
1288       if (answer == EOF)        /* C-d */
1289         {
1290           printf_filtered ("EOF [assumed %c]\n", def_answer);
1291           retval = def_value;
1292           break;
1293         }
1294       /* Eat rest of input line, to EOF or newline.  */
1295       if (answer != '\n')
1296         do
1297           {
1298             ans2 = fgetc (stdin);
1299             clearerr (stdin);
1300           }
1301         while (ans2 != EOF && ans2 != '\n' && ans2 != '\r');
1302
1303       if (answer >= 'a')
1304         answer -= 040;
1305       /* Check answer.  For the non-default, the user must specify
1306          the non-default explicitly.  */
1307       if (answer == not_def_answer)
1308         {
1309           retval = !def_value;
1310           break;
1311         }
1312       /* Otherwise, if a default was specified, the user may either
1313          specify the required input or have it default by entering
1314          nothing.  */
1315       if (answer == def_answer
1316           || (defchar != '\0' &&
1317               (answer == '\n' || answer == '\r' || answer == EOF)))
1318         {
1319           retval = def_value;
1320           break;
1321         }
1322       /* Invalid entries are not defaulted and require another selection.  */
1323       printf_filtered (_("Please answer %s or %s.\n"),
1324                        y_string, n_string);
1325     }
1326
1327   xfree (question);
1328   if (annotation_level > 1)
1329     printf_filtered (("\n\032\032post-query\n"));
1330   return retval;
1331 }
1332 \f
1333
1334 /* Ask user a y-or-n question and return 0 if answer is no, 1 if
1335    answer is yes, or 0 if answer is defaulted.
1336    Takes three args which are given to printf to print the question.
1337    The first, a control string, should end in "? ".
1338    It should not say how to answer, because we do that.  */
1339
1340 int
1341 nquery (const char *ctlstr, ...)
1342 {
1343   va_list args;
1344   int ret;
1345
1346   va_start (args, ctlstr);
1347   ret = defaulted_query (ctlstr, 'n', args);
1348   va_end (args);
1349   return ret;
1350 }
1351
1352 /* Ask user a y-or-n question and return 0 if answer is no, 1 if
1353    answer is yes, or 1 if answer is defaulted.
1354    Takes three args which are given to printf to print the question.
1355    The first, a control string, should end in "? ".
1356    It should not say how to answer, because we do that.  */
1357
1358 int
1359 yquery (const char *ctlstr, ...)
1360 {
1361   va_list args;
1362   int ret;
1363
1364   va_start (args, ctlstr);
1365   ret = defaulted_query (ctlstr, 'y', args);
1366   va_end (args);
1367   return ret;
1368 }
1369
1370 /* Ask user a y-or-n question and return 1 iff answer is yes.
1371    Takes three args which are given to printf to print the question.
1372    The first, a control string, should end in "? ".
1373    It should not say how to answer, because we do that.  */
1374
1375 int
1376 query (const char *ctlstr, ...)
1377 {
1378   va_list args;
1379   int ret;
1380
1381   va_start (args, ctlstr);
1382   ret = defaulted_query (ctlstr, '\0', args);
1383   va_end (args);
1384   return ret;
1385 }
1386
1387 /* A helper for parse_escape that converts a host character to a
1388    target character.  C is the host character.  If conversion is
1389    possible, then the target character is stored in *TARGET_C and the
1390    function returns 1.  Otherwise, the function returns 0.  */
1391
1392 static int
1393 host_char_to_target (struct gdbarch *gdbarch, int c, int *target_c)
1394 {
1395   struct obstack host_data;
1396   char the_char = c;
1397   struct cleanup *cleanups;
1398   int result = 0;
1399
1400   obstack_init (&host_data);
1401   cleanups = make_cleanup_obstack_free (&host_data);
1402
1403   convert_between_encodings (target_charset (gdbarch), host_charset (),
1404                              &the_char, 1, 1, &host_data, translit_none);
1405
1406   if (obstack_object_size (&host_data) == 1)
1407     {
1408       result = 1;
1409       *target_c = *(char *) obstack_base (&host_data);
1410     }
1411
1412   do_cleanups (cleanups);
1413   return result;
1414 }
1415
1416 /* Parse a C escape sequence.  STRING_PTR points to a variable
1417    containing a pointer to the string to parse.  That pointer
1418    should point to the character after the \.  That pointer
1419    is updated past the characters we use.  The value of the
1420    escape sequence is returned.
1421
1422    A negative value means the sequence \ newline was seen,
1423    which is supposed to be equivalent to nothing at all.
1424
1425    If \ is followed by a null character, we return a negative
1426    value and leave the string pointer pointing at the null character.
1427
1428    If \ is followed by 000, we return 0 and leave the string pointer
1429    after the zeros.  A value of 0 does not mean end of string.  */
1430
1431 int
1432 parse_escape (struct gdbarch *gdbarch, char **string_ptr)
1433 {
1434   int target_char = -2; /* Initialize to avoid GCC warnings.  */
1435   int c = *(*string_ptr)++;
1436
1437   switch (c)
1438     {
1439       case '\n':
1440         return -2;
1441       case 0:
1442         (*string_ptr)--;
1443         return 0;
1444
1445       case '0':
1446       case '1':
1447       case '2':
1448       case '3':
1449       case '4':
1450       case '5':
1451       case '6':
1452       case '7':
1453         {
1454           int i = host_hex_value (c);
1455           int count = 0;
1456           while (++count < 3)
1457             {
1458               c = (**string_ptr);
1459               if (isdigit (c) && c != '8' && c != '9')
1460                 {
1461                   (*string_ptr)++;
1462                   i *= 8;
1463                   i += host_hex_value (c);
1464                 }
1465               else
1466                 {
1467                   break;
1468                 }
1469             }
1470           return i;
1471         }
1472
1473     case 'a':
1474       c = '\a';
1475       break;
1476     case 'b':
1477       c = '\b';
1478       break;
1479     case 'f':
1480       c = '\f';
1481       break;
1482     case 'n':
1483       c = '\n';
1484       break;
1485     case 'r':
1486       c = '\r';
1487       break;
1488     case 't':
1489       c = '\t';
1490       break;
1491     case 'v':
1492       c = '\v';
1493       break;
1494
1495     default:
1496       break;
1497     }
1498
1499   if (!host_char_to_target (gdbarch, c, &target_char))
1500     error (_("The escape sequence `\\%c' is equivalent to plain `%c',"
1501              " which has no equivalent\nin the `%s' character set."),
1502            c, c, target_charset (gdbarch));
1503   return target_char;
1504 }
1505 \f
1506 /* Print the character C on STREAM as part of the contents of a literal
1507    string whose delimiter is QUOTER.  Note that this routine should only
1508    be call for printing things which are independent of the language
1509    of the program being debugged.  */
1510
1511 static void
1512 printchar (int c, void (*do_fputs) (const char *, struct ui_file *),
1513            void (*do_fprintf) (struct ui_file *, const char *, ...)
1514            ATTRIBUTE_FPTR_PRINTF_2, struct ui_file *stream, int quoter)
1515 {
1516   c &= 0xFF;                    /* Avoid sign bit follies */
1517
1518   if (c < 0x20 ||               /* Low control chars */
1519       (c >= 0x7F && c < 0xA0) ||        /* DEL, High controls */
1520       (sevenbit_strings && c >= 0x80))
1521     {                           /* high order bit set */
1522       switch (c)
1523         {
1524         case '\n':
1525           do_fputs ("\\n", stream);
1526           break;
1527         case '\b':
1528           do_fputs ("\\b", stream);
1529           break;
1530         case '\t':
1531           do_fputs ("\\t", stream);
1532           break;
1533         case '\f':
1534           do_fputs ("\\f", stream);
1535           break;
1536         case '\r':
1537           do_fputs ("\\r", stream);
1538           break;
1539         case '\033':
1540           do_fputs ("\\e", stream);
1541           break;
1542         case '\007':
1543           do_fputs ("\\a", stream);
1544           break;
1545         default:
1546           do_fprintf (stream, "\\%.3o", (unsigned int) c);
1547           break;
1548         }
1549     }
1550   else
1551     {
1552       if (c == '\\' || c == quoter)
1553         do_fputs ("\\", stream);
1554       do_fprintf (stream, "%c", c);
1555     }
1556 }
1557
1558 /* Print the character C on STREAM as part of the contents of a
1559    literal string whose delimiter is QUOTER.  Note that these routines
1560    should only be call for printing things which are independent of
1561    the language of the program being debugged.  */
1562
1563 void
1564 fputstr_filtered (const char *str, int quoter, struct ui_file *stream)
1565 {
1566   while (*str)
1567     printchar (*str++, fputs_filtered, fprintf_filtered, stream, quoter);
1568 }
1569
1570 void
1571 fputstr_unfiltered (const char *str, int quoter, struct ui_file *stream)
1572 {
1573   while (*str)
1574     printchar (*str++, fputs_unfiltered, fprintf_unfiltered, stream, quoter);
1575 }
1576
1577 void
1578 fputstrn_filtered (const char *str, int n, int quoter,
1579                    struct ui_file *stream)
1580 {
1581   int i;
1582
1583   for (i = 0; i < n; i++)
1584     printchar (str[i], fputs_filtered, fprintf_filtered, stream, quoter);
1585 }
1586
1587 void
1588 fputstrn_unfiltered (const char *str, int n, int quoter,
1589                      struct ui_file *stream)
1590 {
1591   int i;
1592
1593   for (i = 0; i < n; i++)
1594     printchar (str[i], fputs_unfiltered, fprintf_unfiltered, stream, quoter);
1595 }
1596 \f
1597
1598 /* Number of lines per page or UINT_MAX if paging is disabled.  */
1599 static unsigned int lines_per_page;
1600 static void
1601 show_lines_per_page (struct ui_file *file, int from_tty,
1602                      struct cmd_list_element *c, const char *value)
1603 {
1604   fprintf_filtered (file,
1605                     _("Number of lines gdb thinks are in a page is %s.\n"),
1606                     value);
1607 }
1608
1609 /* Number of chars per line or UINT_MAX if line folding is disabled.  */
1610 static unsigned int chars_per_line;
1611 static void
1612 show_chars_per_line (struct ui_file *file, int from_tty,
1613                      struct cmd_list_element *c, const char *value)
1614 {
1615   fprintf_filtered (file,
1616                     _("Number of characters gdb thinks "
1617                       "are in a line is %s.\n"),
1618                     value);
1619 }
1620
1621 /* Current count of lines printed on this page, chars on this line.  */
1622 static unsigned int lines_printed, chars_printed;
1623
1624 /* Buffer and start column of buffered text, for doing smarter word-
1625    wrapping.  When someone calls wrap_here(), we start buffering output
1626    that comes through fputs_filtered().  If we see a newline, we just
1627    spit it out and forget about the wrap_here().  If we see another
1628    wrap_here(), we spit it out and remember the newer one.  If we see
1629    the end of the line, we spit out a newline, the indent, and then
1630    the buffered output.  */
1631
1632 /* Malloc'd buffer with chars_per_line+2 bytes.  Contains characters which
1633    are waiting to be output (they have already been counted in chars_printed).
1634    When wrap_buffer[0] is null, the buffer is empty.  */
1635 static char *wrap_buffer;
1636
1637 /* Pointer in wrap_buffer to the next character to fill.  */
1638 static char *wrap_pointer;
1639
1640 /* String to indent by if the wrap occurs.  Must not be NULL if wrap_column
1641    is non-zero.  */
1642 static char *wrap_indent;
1643
1644 /* Column number on the screen where wrap_buffer begins, or 0 if wrapping
1645    is not in effect.  */
1646 static int wrap_column;
1647 \f
1648
1649 /* Inialize the number of lines per page and chars per line.  */
1650
1651 void
1652 init_page_info (void)
1653 {
1654   if (batch_flag)
1655     {
1656       lines_per_page = UINT_MAX;
1657       chars_per_line = UINT_MAX;
1658     }
1659   else
1660 #if defined(TUI)
1661   if (!tui_get_command_dimension (&chars_per_line, &lines_per_page))
1662 #endif
1663     {
1664       int rows, cols;
1665
1666 #if defined(__GO32__)
1667       rows = ScreenRows ();
1668       cols = ScreenCols ();
1669       lines_per_page = rows;
1670       chars_per_line = cols;
1671 #else
1672       /* Make sure Readline has initialized its terminal settings.  */
1673       rl_reset_terminal (NULL);
1674
1675       /* Get the screen size from Readline.  */
1676       rl_get_screen_size (&rows, &cols);
1677       lines_per_page = rows;
1678       chars_per_line = cols;
1679
1680       /* Readline should have fetched the termcap entry for us.  */
1681       if (tgetnum ("li") < 0 || getenv ("EMACS"))
1682         {
1683           /* The number of lines per page is not mentioned in the
1684              terminal description.  This probably means that paging is
1685              not useful (e.g. emacs shell window), so disable paging.  */
1686           lines_per_page = UINT_MAX;
1687         }
1688
1689       /* FIXME: Get rid of this junk.  */
1690 #if defined(SIGWINCH) && defined(SIGWINCH_HANDLER)
1691       SIGWINCH_HANDLER (SIGWINCH);
1692 #endif
1693
1694       /* If the output is not a terminal, don't paginate it.  */
1695       if (!ui_file_isatty (gdb_stdout))
1696         lines_per_page = UINT_MAX;
1697 #endif
1698     }
1699
1700   set_screen_size ();
1701   set_width ();
1702 }
1703
1704 /* Helper for make_cleanup_restore_page_info.  */
1705
1706 static void
1707 do_restore_page_info_cleanup (void *arg)
1708 {
1709   set_screen_size ();
1710   set_width ();
1711 }
1712
1713 /* Provide cleanup for restoring the terminal size.  */
1714
1715 struct cleanup *
1716 make_cleanup_restore_page_info (void)
1717 {
1718   struct cleanup *back_to;
1719
1720   back_to = make_cleanup (do_restore_page_info_cleanup, NULL);
1721   make_cleanup_restore_uinteger (&lines_per_page);
1722   make_cleanup_restore_uinteger (&chars_per_line);
1723
1724   return back_to;
1725 }
1726
1727 /* Temporarily set BATCH_FLAG and the associated unlimited terminal size.
1728    Provide cleanup for restoring the original state.  */
1729
1730 struct cleanup *
1731 set_batch_flag_and_make_cleanup_restore_page_info (void)
1732 {
1733   struct cleanup *back_to = make_cleanup_restore_page_info ();
1734   
1735   make_cleanup_restore_integer (&batch_flag);
1736   batch_flag = 1;
1737   init_page_info ();
1738
1739   return back_to;
1740 }
1741
1742 /* Set the screen size based on LINES_PER_PAGE and CHARS_PER_LINE.  */
1743
1744 static void
1745 set_screen_size (void)
1746 {
1747   int rows = lines_per_page;
1748   int cols = chars_per_line;
1749
1750   if (rows <= 0)
1751     rows = INT_MAX;
1752
1753   if (cols <= 0)
1754     cols = INT_MAX;
1755
1756   /* Update Readline's idea of the terminal size.  */
1757   rl_set_screen_size (rows, cols);
1758 }
1759
1760 /* Reinitialize WRAP_BUFFER according to the current value of
1761    CHARS_PER_LINE.  */
1762
1763 static void
1764 set_width (void)
1765 {
1766   if (chars_per_line == 0)
1767     init_page_info ();
1768
1769   if (!wrap_buffer)
1770     {
1771       wrap_buffer = (char *) xmalloc (chars_per_line + 2);
1772       wrap_buffer[0] = '\0';
1773     }
1774   else
1775     wrap_buffer = (char *) xrealloc (wrap_buffer, chars_per_line + 2);
1776   wrap_pointer = wrap_buffer;   /* Start it at the beginning.  */
1777 }
1778
1779 static void
1780 set_width_command (char *args, int from_tty, struct cmd_list_element *c)
1781 {
1782   set_screen_size ();
1783   set_width ();
1784 }
1785
1786 static void
1787 set_height_command (char *args, int from_tty, struct cmd_list_element *c)
1788 {
1789   set_screen_size ();
1790 }
1791
1792 /* Wait, so the user can read what's on the screen.  Prompt the user
1793    to continue by pressing RETURN.  */
1794
1795 static void
1796 prompt_for_continue (void)
1797 {
1798   char *ignore;
1799   char cont_prompt[120];
1800
1801   if (annotation_level > 1)
1802     printf_unfiltered (("\n\032\032pre-prompt-for-continue\n"));
1803
1804   strcpy (cont_prompt,
1805           "---Type <return> to continue, or q <return> to quit---");
1806   if (annotation_level > 1)
1807     strcat (cont_prompt, "\n\032\032prompt-for-continue\n");
1808
1809   /* We must do this *before* we call gdb_readline, else it will eventually
1810      call us -- thinking that we're trying to print beyond the end of the 
1811      screen.  */
1812   reinitialize_more_filter ();
1813
1814   immediate_quit++;
1815   /* On a real operating system, the user can quit with SIGINT.
1816      But not on GO32.
1817
1818      'q' is provided on all systems so users don't have to change habits
1819      from system to system, and because telling them what to do in
1820      the prompt is more user-friendly than expecting them to think of
1821      SIGINT.  */
1822   /* Call readline, not gdb_readline, because GO32 readline handles control-C
1823      whereas control-C to gdb_readline will cause the user to get dumped
1824      out to DOS.  */
1825   ignore = gdb_readline_wrapper (cont_prompt);
1826
1827   if (annotation_level > 1)
1828     printf_unfiltered (("\n\032\032post-prompt-for-continue\n"));
1829
1830   if (ignore)
1831     {
1832       char *p = ignore;
1833
1834       while (*p == ' ' || *p == '\t')
1835         ++p;
1836       if (p[0] == 'q')
1837         async_request_quit (0);
1838       xfree (ignore);
1839     }
1840   immediate_quit--;
1841
1842   /* Now we have to do this again, so that GDB will know that it doesn't
1843      need to save the ---Type <return>--- line at the top of the screen.  */
1844   reinitialize_more_filter ();
1845
1846   dont_repeat ();               /* Forget prev cmd -- CR won't repeat it.  */
1847 }
1848
1849 /* Reinitialize filter; ie. tell it to reset to original values.  */
1850
1851 void
1852 reinitialize_more_filter (void)
1853 {
1854   lines_printed = 0;
1855   chars_printed = 0;
1856 }
1857
1858 /* Indicate that if the next sequence of characters overflows the line,
1859    a newline should be inserted here rather than when it hits the end.
1860    If INDENT is non-null, it is a string to be printed to indent the
1861    wrapped part on the next line.  INDENT must remain accessible until
1862    the next call to wrap_here() or until a newline is printed through
1863    fputs_filtered().
1864
1865    If the line is already overfull, we immediately print a newline and
1866    the indentation, and disable further wrapping.
1867
1868    If we don't know the width of lines, but we know the page height,
1869    we must not wrap words, but should still keep track of newlines
1870    that were explicitly printed.
1871
1872    INDENT should not contain tabs, as that will mess up the char count
1873    on the next line.  FIXME.
1874
1875    This routine is guaranteed to force out any output which has been
1876    squirreled away in the wrap_buffer, so wrap_here ((char *)0) can be
1877    used to force out output from the wrap_buffer.  */
1878
1879 void
1880 wrap_here (char *indent)
1881 {
1882   /* This should have been allocated, but be paranoid anyway.  */
1883   if (!wrap_buffer)
1884     internal_error (__FILE__, __LINE__,
1885                     _("failed internal consistency check"));
1886
1887   if (wrap_buffer[0])
1888     {
1889       *wrap_pointer = '\0';
1890       fputs_unfiltered (wrap_buffer, gdb_stdout);
1891     }
1892   wrap_pointer = wrap_buffer;
1893   wrap_buffer[0] = '\0';
1894   if (chars_per_line == UINT_MAX)       /* No line overflow checking.  */
1895     {
1896       wrap_column = 0;
1897     }
1898   else if (chars_printed >= chars_per_line)
1899     {
1900       puts_filtered ("\n");
1901       if (indent != NULL)
1902         puts_filtered (indent);
1903       wrap_column = 0;
1904     }
1905   else
1906     {
1907       wrap_column = chars_printed;
1908       if (indent == NULL)
1909         wrap_indent = "";
1910       else
1911         wrap_indent = indent;
1912     }
1913 }
1914
1915 /* Print input string to gdb_stdout, filtered, with wrap, 
1916    arranging strings in columns of n chars.  String can be
1917    right or left justified in the column.  Never prints 
1918    trailing spaces.  String should never be longer than
1919    width.  FIXME: this could be useful for the EXAMINE 
1920    command, which currently doesn't tabulate very well.  */
1921
1922 void
1923 puts_filtered_tabular (char *string, int width, int right)
1924 {
1925   int spaces = 0;
1926   int stringlen;
1927   char *spacebuf;
1928
1929   gdb_assert (chars_per_line > 0);
1930   if (chars_per_line == UINT_MAX)
1931     {
1932       fputs_filtered (string, gdb_stdout);
1933       fputs_filtered ("\n", gdb_stdout);
1934       return;
1935     }
1936
1937   if (((chars_printed - 1) / width + 2) * width >= chars_per_line)
1938     fputs_filtered ("\n", gdb_stdout);
1939
1940   if (width >= chars_per_line)
1941     width = chars_per_line - 1;
1942
1943   stringlen = strlen (string);
1944
1945   if (chars_printed > 0)
1946     spaces = width - (chars_printed - 1) % width - 1;
1947   if (right)
1948     spaces += width - stringlen;
1949
1950   spacebuf = alloca (spaces + 1);
1951   spacebuf[spaces] = '\0';
1952   while (spaces--)
1953     spacebuf[spaces] = ' ';
1954
1955   fputs_filtered (spacebuf, gdb_stdout);
1956   fputs_filtered (string, gdb_stdout);
1957 }
1958
1959
1960 /* Ensure that whatever gets printed next, using the filtered output
1961    commands, starts at the beginning of the line.  I.e. if there is
1962    any pending output for the current line, flush it and start a new
1963    line.  Otherwise do nothing.  */
1964
1965 void
1966 begin_line (void)
1967 {
1968   if (chars_printed > 0)
1969     {
1970       puts_filtered ("\n");
1971     }
1972 }
1973
1974
1975 /* Like fputs but if FILTER is true, pause after every screenful.
1976
1977    Regardless of FILTER can wrap at points other than the final
1978    character of a line.
1979
1980    Unlike fputs, fputs_maybe_filtered does not return a value.
1981    It is OK for LINEBUFFER to be NULL, in which case just don't print
1982    anything.
1983
1984    Note that a longjmp to top level may occur in this routine (only if
1985    FILTER is true) (since prompt_for_continue may do so) so this
1986    routine should not be called when cleanups are not in place.  */
1987
1988 static void
1989 fputs_maybe_filtered (const char *linebuffer, struct ui_file *stream,
1990                       int filter)
1991 {
1992   const char *lineptr;
1993
1994   if (linebuffer == 0)
1995     return;
1996
1997   /* Don't do any filtering if it is disabled.  */
1998   if (stream != gdb_stdout
1999       || !pagination_enabled
2000       || batch_flag
2001       || (lines_per_page == UINT_MAX && chars_per_line == UINT_MAX)
2002       || top_level_interpreter () == NULL
2003       || ui_out_is_mi_like_p (interp_ui_out (top_level_interpreter ())))
2004     {
2005       fputs_unfiltered (linebuffer, stream);
2006       return;
2007     }
2008
2009   /* Go through and output each character.  Show line extension
2010      when this is necessary; prompt user for new page when this is
2011      necessary.  */
2012
2013   lineptr = linebuffer;
2014   while (*lineptr)
2015     {
2016       /* Possible new page.  */
2017       if (filter && (lines_printed >= lines_per_page - 1))
2018         prompt_for_continue ();
2019
2020       while (*lineptr && *lineptr != '\n')
2021         {
2022           /* Print a single line.  */
2023           if (*lineptr == '\t')
2024             {
2025               if (wrap_column)
2026                 *wrap_pointer++ = '\t';
2027               else
2028                 fputc_unfiltered ('\t', stream);
2029               /* Shifting right by 3 produces the number of tab stops
2030                  we have already passed, and then adding one and
2031                  shifting left 3 advances to the next tab stop.  */
2032               chars_printed = ((chars_printed >> 3) + 1) << 3;
2033               lineptr++;
2034             }
2035           else
2036             {
2037               if (wrap_column)
2038                 *wrap_pointer++ = *lineptr;
2039               else
2040                 fputc_unfiltered (*lineptr, stream);
2041               chars_printed++;
2042               lineptr++;
2043             }
2044
2045           if (chars_printed >= chars_per_line)
2046             {
2047               unsigned int save_chars = chars_printed;
2048
2049               chars_printed = 0;
2050               lines_printed++;
2051               /* If we aren't actually wrapping, don't output newline --
2052                  if chars_per_line is right, we probably just overflowed
2053                  anyway; if it's wrong, let us keep going.  */
2054               if (wrap_column)
2055                 fputc_unfiltered ('\n', stream);
2056
2057               /* Possible new page.  */
2058               if (lines_printed >= lines_per_page - 1)
2059                 prompt_for_continue ();
2060
2061               /* Now output indentation and wrapped string.  */
2062               if (wrap_column)
2063                 {
2064                   fputs_unfiltered (wrap_indent, stream);
2065                   *wrap_pointer = '\0'; /* Null-terminate saved stuff, */
2066                   fputs_unfiltered (wrap_buffer, stream); /* and eject it.  */
2067                   /* FIXME, this strlen is what prevents wrap_indent from
2068                      containing tabs.  However, if we recurse to print it
2069                      and count its chars, we risk trouble if wrap_indent is
2070                      longer than (the user settable) chars_per_line.
2071                      Note also that this can set chars_printed > chars_per_line
2072                      if we are printing a long string.  */
2073                   chars_printed = strlen (wrap_indent)
2074                     + (save_chars - wrap_column);
2075                   wrap_pointer = wrap_buffer;   /* Reset buffer */
2076                   wrap_buffer[0] = '\0';
2077                   wrap_column = 0;      /* And disable fancy wrap */
2078                 }
2079             }
2080         }
2081
2082       if (*lineptr == '\n')
2083         {
2084           chars_printed = 0;
2085           wrap_here ((char *) 0);       /* Spit out chars, cancel
2086                                            further wraps.  */
2087           lines_printed++;
2088           fputc_unfiltered ('\n', stream);
2089           lineptr++;
2090         }
2091     }
2092 }
2093
2094 void
2095 fputs_filtered (const char *linebuffer, struct ui_file *stream)
2096 {
2097   fputs_maybe_filtered (linebuffer, stream, 1);
2098 }
2099
2100 int
2101 putchar_unfiltered (int c)
2102 {
2103   char buf = c;
2104
2105   ui_file_write (gdb_stdout, &buf, 1);
2106   return c;
2107 }
2108
2109 /* Write character C to gdb_stdout using GDB's paging mechanism and return C.
2110    May return nonlocally.  */
2111
2112 int
2113 putchar_filtered (int c)
2114 {
2115   return fputc_filtered (c, gdb_stdout);
2116 }
2117
2118 int
2119 fputc_unfiltered (int c, struct ui_file *stream)
2120 {
2121   char buf = c;
2122
2123   ui_file_write (stream, &buf, 1);
2124   return c;
2125 }
2126
2127 int
2128 fputc_filtered (int c, struct ui_file *stream)
2129 {
2130   char buf[2];
2131
2132   buf[0] = c;
2133   buf[1] = 0;
2134   fputs_filtered (buf, stream);
2135   return c;
2136 }
2137
2138 /* puts_debug is like fputs_unfiltered, except it prints special
2139    characters in printable fashion.  */
2140
2141 void
2142 puts_debug (char *prefix, char *string, char *suffix)
2143 {
2144   int ch;
2145
2146   /* Print prefix and suffix after each line.  */
2147   static int new_line = 1;
2148   static int return_p = 0;
2149   static char *prev_prefix = "";
2150   static char *prev_suffix = "";
2151
2152   if (*string == '\n')
2153     return_p = 0;
2154
2155   /* If the prefix is changing, print the previous suffix, a new line,
2156      and the new prefix.  */
2157   if ((return_p || (strcmp (prev_prefix, prefix) != 0)) && !new_line)
2158     {
2159       fputs_unfiltered (prev_suffix, gdb_stdlog);
2160       fputs_unfiltered ("\n", gdb_stdlog);
2161       fputs_unfiltered (prefix, gdb_stdlog);
2162     }
2163
2164   /* Print prefix if we printed a newline during the previous call.  */
2165   if (new_line)
2166     {
2167       new_line = 0;
2168       fputs_unfiltered (prefix, gdb_stdlog);
2169     }
2170
2171   prev_prefix = prefix;
2172   prev_suffix = suffix;
2173
2174   /* Output characters in a printable format.  */
2175   while ((ch = *string++) != '\0')
2176     {
2177       switch (ch)
2178         {
2179         default:
2180           if (isprint (ch))
2181             fputc_unfiltered (ch, gdb_stdlog);
2182
2183           else
2184             fprintf_unfiltered (gdb_stdlog, "\\x%02x", ch & 0xff);
2185           break;
2186
2187         case '\\':
2188           fputs_unfiltered ("\\\\", gdb_stdlog);
2189           break;
2190         case '\b':
2191           fputs_unfiltered ("\\b", gdb_stdlog);
2192           break;
2193         case '\f':
2194           fputs_unfiltered ("\\f", gdb_stdlog);
2195           break;
2196         case '\n':
2197           new_line = 1;
2198           fputs_unfiltered ("\\n", gdb_stdlog);
2199           break;
2200         case '\r':
2201           fputs_unfiltered ("\\r", gdb_stdlog);
2202           break;
2203         case '\t':
2204           fputs_unfiltered ("\\t", gdb_stdlog);
2205           break;
2206         case '\v':
2207           fputs_unfiltered ("\\v", gdb_stdlog);
2208           break;
2209         }
2210
2211       return_p = ch == '\r';
2212     }
2213
2214   /* Print suffix if we printed a newline.  */
2215   if (new_line)
2216     {
2217       fputs_unfiltered (suffix, gdb_stdlog);
2218       fputs_unfiltered ("\n", gdb_stdlog);
2219     }
2220 }
2221
2222
2223 /* Print a variable number of ARGS using format FORMAT.  If this
2224    information is going to put the amount written (since the last call
2225    to REINITIALIZE_MORE_FILTER or the last page break) over the page size,
2226    call prompt_for_continue to get the users permision to continue.
2227
2228    Unlike fprintf, this function does not return a value.
2229
2230    We implement three variants, vfprintf (takes a vararg list and stream),
2231    fprintf (takes a stream to write on), and printf (the usual).
2232
2233    Note also that a longjmp to top level may occur in this routine
2234    (since prompt_for_continue may do so) so this routine should not be
2235    called when cleanups are not in place.  */
2236
2237 static void
2238 vfprintf_maybe_filtered (struct ui_file *stream, const char *format,
2239                          va_list args, int filter)
2240 {
2241   char *linebuffer;
2242   struct cleanup *old_cleanups;
2243
2244   linebuffer = xstrvprintf (format, args);
2245   old_cleanups = make_cleanup (xfree, linebuffer);
2246   fputs_maybe_filtered (linebuffer, stream, filter);
2247   do_cleanups (old_cleanups);
2248 }
2249
2250
2251 void
2252 vfprintf_filtered (struct ui_file *stream, const char *format, va_list args)
2253 {
2254   vfprintf_maybe_filtered (stream, format, args, 1);
2255 }
2256
2257 void
2258 vfprintf_unfiltered (struct ui_file *stream, const char *format, va_list args)
2259 {
2260   char *linebuffer;
2261   struct cleanup *old_cleanups;
2262
2263   linebuffer = xstrvprintf (format, args);
2264   old_cleanups = make_cleanup (xfree, linebuffer);
2265   if (debug_timestamp && stream == gdb_stdlog)
2266     {
2267       struct timeval tm;
2268       char *timestamp;
2269       int len, need_nl;
2270
2271       gettimeofday (&tm, NULL);
2272
2273       len = strlen (linebuffer);
2274       need_nl = (len > 0 && linebuffer[len - 1] != '\n');
2275
2276       timestamp = xstrprintf ("%ld:%ld %s%s",
2277                               (long) tm.tv_sec, (long) tm.tv_usec,
2278                               linebuffer,
2279                               need_nl ? "\n": "");
2280       make_cleanup (xfree, timestamp);
2281       fputs_unfiltered (timestamp, stream);
2282     }
2283   else
2284     fputs_unfiltered (linebuffer, stream);
2285   do_cleanups (old_cleanups);
2286 }
2287
2288 void
2289 vprintf_filtered (const char *format, va_list args)
2290 {
2291   vfprintf_maybe_filtered (gdb_stdout, format, args, 1);
2292 }
2293
2294 void
2295 vprintf_unfiltered (const char *format, va_list args)
2296 {
2297   vfprintf_unfiltered (gdb_stdout, format, args);
2298 }
2299
2300 void
2301 fprintf_filtered (struct ui_file *stream, const char *format, ...)
2302 {
2303   va_list args;
2304
2305   va_start (args, format);
2306   vfprintf_filtered (stream, format, args);
2307   va_end (args);
2308 }
2309
2310 void
2311 fprintf_unfiltered (struct ui_file *stream, const char *format, ...)
2312 {
2313   va_list args;
2314
2315   va_start (args, format);
2316   vfprintf_unfiltered (stream, format, args);
2317   va_end (args);
2318 }
2319
2320 /* Like fprintf_filtered, but prints its result indented.
2321    Called as fprintfi_filtered (spaces, stream, format, ...);  */
2322
2323 void
2324 fprintfi_filtered (int spaces, struct ui_file *stream, const char *format,
2325                    ...)
2326 {
2327   va_list args;
2328
2329   va_start (args, format);
2330   print_spaces_filtered (spaces, stream);
2331
2332   vfprintf_filtered (stream, format, args);
2333   va_end (args);
2334 }
2335
2336
2337 void
2338 printf_filtered (const char *format, ...)
2339 {
2340   va_list args;
2341
2342   va_start (args, format);
2343   vfprintf_filtered (gdb_stdout, format, args);
2344   va_end (args);
2345 }
2346
2347
2348 void
2349 printf_unfiltered (const char *format, ...)
2350 {
2351   va_list args;
2352
2353   va_start (args, format);
2354   vfprintf_unfiltered (gdb_stdout, format, args);
2355   va_end (args);
2356 }
2357
2358 /* Like printf_filtered, but prints it's result indented.
2359    Called as printfi_filtered (spaces, format, ...);  */
2360
2361 void
2362 printfi_filtered (int spaces, const char *format, ...)
2363 {
2364   va_list args;
2365
2366   va_start (args, format);
2367   print_spaces_filtered (spaces, gdb_stdout);
2368   vfprintf_filtered (gdb_stdout, format, args);
2369   va_end (args);
2370 }
2371
2372 /* Easy -- but watch out!
2373
2374    This routine is *not* a replacement for puts()!  puts() appends a newline.
2375    This one doesn't, and had better not!  */
2376
2377 void
2378 puts_filtered (const char *string)
2379 {
2380   fputs_filtered (string, gdb_stdout);
2381 }
2382
2383 void
2384 puts_unfiltered (const char *string)
2385 {
2386   fputs_unfiltered (string, gdb_stdout);
2387 }
2388
2389 /* Return a pointer to N spaces and a null.  The pointer is good
2390    until the next call to here.  */
2391 char *
2392 n_spaces (int n)
2393 {
2394   char *t;
2395   static char *spaces = 0;
2396   static int max_spaces = -1;
2397
2398   if (n > max_spaces)
2399     {
2400       if (spaces)
2401         xfree (spaces);
2402       spaces = (char *) xmalloc (n + 1);
2403       for (t = spaces + n; t != spaces;)
2404         *--t = ' ';
2405       spaces[n] = '\0';
2406       max_spaces = n;
2407     }
2408
2409   return spaces + max_spaces - n;
2410 }
2411
2412 /* Print N spaces.  */
2413 void
2414 print_spaces_filtered (int n, struct ui_file *stream)
2415 {
2416   fputs_filtered (n_spaces (n), stream);
2417 }
2418 \f
2419 /* C++/ObjC demangler stuff.  */
2420
2421 /* fprintf_symbol_filtered attempts to demangle NAME, a symbol in language
2422    LANG, using demangling args ARG_MODE, and print it filtered to STREAM.
2423    If the name is not mangled, or the language for the name is unknown, or
2424    demangling is off, the name is printed in its "raw" form.  */
2425
2426 void
2427 fprintf_symbol_filtered (struct ui_file *stream, const char *name,
2428                          enum language lang, int arg_mode)
2429 {
2430   char *demangled;
2431
2432   if (name != NULL)
2433     {
2434       /* If user wants to see raw output, no problem.  */
2435       if (!demangle)
2436         {
2437           fputs_filtered (name, stream);
2438         }
2439       else
2440         {
2441           demangled = language_demangle (language_def (lang), name, arg_mode);
2442           fputs_filtered (demangled ? demangled : name, stream);
2443           if (demangled != NULL)
2444             {
2445               xfree (demangled);
2446             }
2447         }
2448     }
2449 }
2450
2451 /* Do a strcmp() type operation on STRING1 and STRING2, ignoring any
2452    differences in whitespace.  Returns 0 if they match, non-zero if they
2453    don't (slightly different than strcmp()'s range of return values).
2454
2455    As an extra hack, string1=="FOO(ARGS)" matches string2=="FOO".
2456    This "feature" is useful when searching for matching C++ function names
2457    (such as if the user types 'break FOO', where FOO is a mangled C++
2458    function).  */
2459
2460 int
2461 strcmp_iw (const char *string1, const char *string2)
2462 {
2463   while ((*string1 != '\0') && (*string2 != '\0'))
2464     {
2465       while (isspace (*string1))
2466         {
2467           string1++;
2468         }
2469       while (isspace (*string2))
2470         {
2471           string2++;
2472         }
2473       if (case_sensitivity == case_sensitive_on && *string1 != *string2)
2474         break;
2475       if (case_sensitivity == case_sensitive_off
2476           && (tolower ((unsigned char) *string1)
2477               != tolower ((unsigned char) *string2)))
2478         break;
2479       if (*string1 != '\0')
2480         {
2481           string1++;
2482           string2++;
2483         }
2484     }
2485   return (*string1 != '\0' && *string1 != '(') || (*string2 != '\0');
2486 }
2487
2488 /* This is like strcmp except that it ignores whitespace and treats
2489    '(' as the first non-NULL character in terms of ordering.  Like
2490    strcmp (and unlike strcmp_iw), it returns negative if STRING1 <
2491    STRING2, 0 if STRING2 = STRING2, and positive if STRING1 > STRING2
2492    according to that ordering.
2493
2494    If a list is sorted according to this function and if you want to
2495    find names in the list that match some fixed NAME according to
2496    strcmp_iw(LIST_ELT, NAME), then the place to start looking is right
2497    where this function would put NAME.
2498
2499    This function must be neutral to the CASE_SENSITIVITY setting as the user
2500    may choose it during later lookup.  Therefore this function always sorts
2501    primarily case-insensitively and secondarily case-sensitively.
2502
2503    Here are some examples of why using strcmp to sort is a bad idea:
2504
2505    Whitespace example:
2506
2507    Say your partial symtab contains: "foo<char *>", "goo".  Then, if
2508    we try to do a search for "foo<char*>", strcmp will locate this
2509    after "foo<char *>" and before "goo".  Then lookup_partial_symbol
2510    will start looking at strings beginning with "goo", and will never
2511    see the correct match of "foo<char *>".
2512
2513    Parenthesis example:
2514
2515    In practice, this is less like to be an issue, but I'll give it a
2516    shot.  Let's assume that '$' is a legitimate character to occur in
2517    symbols.  (Which may well even be the case on some systems.)  Then
2518    say that the partial symbol table contains "foo$" and "foo(int)".
2519    strcmp will put them in this order, since '$' < '('.  Now, if the
2520    user searches for "foo", then strcmp will sort "foo" before "foo$".
2521    Then lookup_partial_symbol will notice that strcmp_iw("foo$",
2522    "foo") is false, so it won't proceed to the actual match of
2523    "foo(int)" with "foo".  */
2524
2525 int
2526 strcmp_iw_ordered (const char *string1, const char *string2)
2527 {
2528   const char *saved_string1 = string1, *saved_string2 = string2;
2529   enum case_sensitivity case_pass = case_sensitive_off;
2530
2531   for (;;)
2532     {
2533       /* C1 and C2 are valid only if *string1 != '\0' && *string2 != '\0'.
2534          Provide stub characters if we are already at the end of one of the
2535          strings.  */
2536       char c1 = 'X', c2 = 'X';
2537
2538       while (*string1 != '\0' && *string2 != '\0')
2539         {
2540           while (isspace (*string1))
2541             string1++;
2542           while (isspace (*string2))
2543             string2++;
2544
2545           switch (case_pass)
2546           {
2547             case case_sensitive_off:
2548               c1 = tolower ((unsigned char) *string1);
2549               c2 = tolower ((unsigned char) *string2);
2550               break;
2551             case case_sensitive_on:
2552               c1 = *string1;
2553               c2 = *string2;
2554               break;
2555           }
2556           if (c1 != c2)
2557             break;
2558
2559           if (*string1 != '\0')
2560             {
2561               string1++;
2562               string2++;
2563             }
2564         }
2565
2566       switch (*string1)
2567         {
2568           /* Characters are non-equal unless they're both '\0'; we want to
2569              make sure we get the comparison right according to our
2570              comparison in the cases where one of them is '\0' or '('.  */
2571         case '\0':
2572           if (*string2 == '\0')
2573             break;
2574           else
2575             return -1;
2576         case '(':
2577           if (*string2 == '\0')
2578             return 1;
2579           else
2580             return -1;
2581         default:
2582           if (*string2 == '\0' || *string2 == '(')
2583             return 1;
2584           else if (c1 > c2)
2585             return 1;
2586           else if (c1 < c2)
2587             return -1;
2588           /* PASSTHRU */
2589         }
2590
2591       if (case_pass == case_sensitive_on)
2592         return 0;
2593       
2594       /* Otherwise the strings were equal in case insensitive way, make
2595          a more fine grained comparison in a case sensitive way.  */
2596
2597       case_pass = case_sensitive_on;
2598       string1 = saved_string1;
2599       string2 = saved_string2;
2600     }
2601 }
2602
2603 /* A simple comparison function with opposite semantics to strcmp.  */
2604
2605 int
2606 streq (const char *lhs, const char *rhs)
2607 {
2608   return !strcmp (lhs, rhs);
2609 }
2610 \f
2611
2612 /*
2613    ** subset_compare()
2614    **    Answer whether string_to_compare is a full or partial match to
2615    **    template_string.  The partial match must be in sequence starting
2616    **    at index 0.
2617  */
2618 int
2619 subset_compare (char *string_to_compare, char *template_string)
2620 {
2621   int match;
2622
2623   if (template_string != (char *) NULL && string_to_compare != (char *) NULL
2624       && strlen (string_to_compare) <= strlen (template_string))
2625     match =
2626       (strncmp
2627        (template_string, string_to_compare, strlen (string_to_compare)) == 0);
2628   else
2629     match = 0;
2630   return match;
2631 }
2632
2633 static void
2634 pagination_on_command (char *arg, int from_tty)
2635 {
2636   pagination_enabled = 1;
2637 }
2638
2639 static void
2640 pagination_off_command (char *arg, int from_tty)
2641 {
2642   pagination_enabled = 0;
2643 }
2644
2645 static void
2646 show_debug_timestamp (struct ui_file *file, int from_tty,
2647                       struct cmd_list_element *c, const char *value)
2648 {
2649   fprintf_filtered (file, _("Timestamping debugging messages is %s.\n"),
2650                     value);
2651 }
2652 \f
2653
2654 void
2655 initialize_utils (void)
2656 {
2657   add_setshow_uinteger_cmd ("width", class_support, &chars_per_line, _("\
2658 Set number of characters gdb thinks are in a line."), _("\
2659 Show number of characters gdb thinks are in a line."), NULL,
2660                             set_width_command,
2661                             show_chars_per_line,
2662                             &setlist, &showlist);
2663
2664   add_setshow_uinteger_cmd ("height", class_support, &lines_per_page, _("\
2665 Set number of lines gdb thinks are in a page."), _("\
2666 Show number of lines gdb thinks are in a page."), NULL,
2667                             set_height_command,
2668                             show_lines_per_page,
2669                             &setlist, &showlist);
2670
2671   init_page_info ();
2672
2673   add_setshow_boolean_cmd ("pagination", class_support,
2674                            &pagination_enabled, _("\
2675 Set state of pagination."), _("\
2676 Show state of pagination."), NULL,
2677                            NULL,
2678                            show_pagination_enabled,
2679                            &setlist, &showlist);
2680
2681   if (xdb_commands)
2682     {
2683       add_com ("am", class_support, pagination_on_command,
2684                _("Enable pagination"));
2685       add_com ("sm", class_support, pagination_off_command,
2686                _("Disable pagination"));
2687     }
2688
2689   add_setshow_boolean_cmd ("sevenbit-strings", class_support,
2690                            &sevenbit_strings, _("\
2691 Set printing of 8-bit characters in strings as \\nnn."), _("\
2692 Show printing of 8-bit characters in strings as \\nnn."), NULL,
2693                            NULL,
2694                            show_sevenbit_strings,
2695                            &setprintlist, &showprintlist);
2696
2697   add_setshow_boolean_cmd ("timestamp", class_maintenance,
2698                             &debug_timestamp, _("\
2699 Set timestamping of debugging messages."), _("\
2700 Show timestamping of debugging messages."), _("\
2701 When set, debugging messages will be marked with seconds and microseconds."),
2702                            NULL,
2703                            show_debug_timestamp,
2704                            &setdebuglist, &showdebuglist);
2705 }
2706
2707 /* Machine specific function to handle SIGWINCH signal.  */
2708
2709 #ifdef  SIGWINCH_HANDLER_BODY
2710 SIGWINCH_HANDLER_BODY
2711 #endif
2712 /* Print routines to handle variable size regs, etc.  */
2713 /* Temporary storage using circular buffer.  */
2714 #define NUMCELLS 16
2715 #define CELLSIZE 50
2716 static char *
2717 get_cell (void)
2718 {
2719   static char buf[NUMCELLS][CELLSIZE];
2720   static int cell = 0;
2721
2722   if (++cell >= NUMCELLS)
2723     cell = 0;
2724   return buf[cell];
2725 }
2726
2727 const char *
2728 paddress (struct gdbarch *gdbarch, CORE_ADDR addr)
2729 {
2730   /* Truncate address to the size of a target address, avoiding shifts
2731      larger or equal than the width of a CORE_ADDR.  The local
2732      variable ADDR_BIT stops the compiler reporting a shift overflow
2733      when it won't occur.  */
2734   /* NOTE: This assumes that the significant address information is
2735      kept in the least significant bits of ADDR - the upper bits were
2736      either zero or sign extended.  Should gdbarch_address_to_pointer or
2737      some ADDRESS_TO_PRINTABLE() be used to do the conversion?  */
2738
2739   int addr_bit = gdbarch_addr_bit (gdbarch);
2740
2741   if (addr_bit < (sizeof (CORE_ADDR) * HOST_CHAR_BIT))
2742     addr &= ((CORE_ADDR) 1 << addr_bit) - 1;
2743   return hex_string (addr);
2744 }
2745
2746 /* This function is described in "defs.h".  */
2747
2748 const char *
2749 print_core_address (struct gdbarch *gdbarch, CORE_ADDR address)
2750 {
2751   int addr_bit = gdbarch_addr_bit (gdbarch);
2752
2753   if (addr_bit < (sizeof (CORE_ADDR) * HOST_CHAR_BIT))
2754     address &= ((CORE_ADDR) 1 << addr_bit) - 1;
2755
2756   /* FIXME: cagney/2002-05-03: Need local_address_string() function
2757      that returns the language localized string formatted to a width
2758      based on gdbarch_addr_bit.  */
2759   if (addr_bit <= 32)
2760     return hex_string_custom (address, 8);
2761   else
2762     return hex_string_custom (address, 16);
2763 }
2764
2765 /* Callback hash_f for htab_create_alloc or htab_create_alloc_ex.  */
2766
2767 hashval_t
2768 core_addr_hash (const void *ap)
2769 {
2770   const CORE_ADDR *addrp = ap;
2771
2772   return *addrp;
2773 }
2774
2775 /* Callback eq_f for htab_create_alloc or htab_create_alloc_ex.  */
2776
2777 int
2778 core_addr_eq (const void *ap, const void *bp)
2779 {
2780   const CORE_ADDR *addr_ap = ap;
2781   const CORE_ADDR *addr_bp = bp;
2782
2783   return *addr_ap == *addr_bp;
2784 }
2785
2786 static char *
2787 decimal2str (char *sign, ULONGEST addr, int width)
2788 {
2789   /* Steal code from valprint.c:print_decimal().  Should this worry
2790      about the real size of addr as the above does?  */
2791   unsigned long temp[3];
2792   char *str = get_cell ();
2793   int i = 0;
2794
2795   do
2796     {
2797       temp[i] = addr % (1000 * 1000 * 1000);
2798       addr /= (1000 * 1000 * 1000);
2799       i++;
2800       width -= 9;
2801     }
2802   while (addr != 0 && i < (sizeof (temp) / sizeof (temp[0])));
2803
2804   width += 9;
2805   if (width < 0)
2806     width = 0;
2807
2808   switch (i)
2809     {
2810     case 1:
2811       xsnprintf (str, CELLSIZE, "%s%0*lu", sign, width, temp[0]);
2812       break;
2813     case 2:
2814       xsnprintf (str, CELLSIZE, "%s%0*lu%09lu", sign, width,
2815                  temp[1], temp[0]);
2816       break;
2817     case 3:
2818       xsnprintf (str, CELLSIZE, "%s%0*lu%09lu%09lu", sign, width,
2819                  temp[2], temp[1], temp[0]);
2820       break;
2821     default:
2822       internal_error (__FILE__, __LINE__,
2823                       _("failed internal consistency check"));
2824     }
2825
2826   return str;
2827 }
2828
2829 static char *
2830 octal2str (ULONGEST addr, int width)
2831 {
2832   unsigned long temp[3];
2833   char *str = get_cell ();
2834   int i = 0;
2835
2836   do
2837     {
2838       temp[i] = addr % (0100000 * 0100000);
2839       addr /= (0100000 * 0100000);
2840       i++;
2841       width -= 10;
2842     }
2843   while (addr != 0 && i < (sizeof (temp) / sizeof (temp[0])));
2844
2845   width += 10;
2846   if (width < 0)
2847     width = 0;
2848
2849   switch (i)
2850     {
2851     case 1:
2852       if (temp[0] == 0)
2853         xsnprintf (str, CELLSIZE, "%*o", width, 0);
2854       else
2855         xsnprintf (str, CELLSIZE, "0%0*lo", width, temp[0]);
2856       break;
2857     case 2:
2858       xsnprintf (str, CELLSIZE, "0%0*lo%010lo", width, temp[1], temp[0]);
2859       break;
2860     case 3:
2861       xsnprintf (str, CELLSIZE, "0%0*lo%010lo%010lo", width,
2862                  temp[2], temp[1], temp[0]);
2863       break;
2864     default:
2865       internal_error (__FILE__, __LINE__,
2866                       _("failed internal consistency check"));
2867     }
2868
2869   return str;
2870 }
2871
2872 char *
2873 pulongest (ULONGEST u)
2874 {
2875   return decimal2str ("", u, 0);
2876 }
2877
2878 char *
2879 plongest (LONGEST l)
2880 {
2881   if (l < 0)
2882     return decimal2str ("-", -l, 0);
2883   else
2884     return decimal2str ("", l, 0);
2885 }
2886
2887 /* Eliminate warning from compiler on 32-bit systems.  */
2888 static int thirty_two = 32;
2889
2890 char *
2891 phex (ULONGEST l, int sizeof_l)
2892 {
2893   char *str;
2894
2895   switch (sizeof_l)
2896     {
2897     case 8:
2898       str = get_cell ();
2899       xsnprintf (str, CELLSIZE, "%08lx%08lx",
2900                  (unsigned long) (l >> thirty_two),
2901                  (unsigned long) (l & 0xffffffff));
2902       break;
2903     case 4:
2904       str = get_cell ();
2905       xsnprintf (str, CELLSIZE, "%08lx", (unsigned long) l);
2906       break;
2907     case 2:
2908       str = get_cell ();
2909       xsnprintf (str, CELLSIZE, "%04x", (unsigned short) (l & 0xffff));
2910       break;
2911     default:
2912       str = phex (l, sizeof (l));
2913       break;
2914     }
2915
2916   return str;
2917 }
2918
2919 char *
2920 phex_nz (ULONGEST l, int sizeof_l)
2921 {
2922   char *str;
2923
2924   switch (sizeof_l)
2925     {
2926     case 8:
2927       {
2928         unsigned long high = (unsigned long) (l >> thirty_two);
2929
2930         str = get_cell ();
2931         if (high == 0)
2932           xsnprintf (str, CELLSIZE, "%lx",
2933                      (unsigned long) (l & 0xffffffff));
2934         else
2935           xsnprintf (str, CELLSIZE, "%lx%08lx", high,
2936                      (unsigned long) (l & 0xffffffff));
2937         break;
2938       }
2939     case 4:
2940       str = get_cell ();
2941       xsnprintf (str, CELLSIZE, "%lx", (unsigned long) l);
2942       break;
2943     case 2:
2944       str = get_cell ();
2945       xsnprintf (str, CELLSIZE, "%x", (unsigned short) (l & 0xffff));
2946       break;
2947     default:
2948       str = phex_nz (l, sizeof (l));
2949       break;
2950     }
2951
2952   return str;
2953 }
2954
2955 /* Converts a LONGEST to a C-format hexadecimal literal and stores it
2956    in a static string.  Returns a pointer to this string.  */
2957 char *
2958 hex_string (LONGEST num)
2959 {
2960   char *result = get_cell ();
2961
2962   xsnprintf (result, CELLSIZE, "0x%s", phex_nz (num, sizeof (num)));
2963   return result;
2964 }
2965
2966 /* Converts a LONGEST number to a C-format hexadecimal literal and
2967    stores it in a static string.  Returns a pointer to this string
2968    that is valid until the next call.  The number is padded on the
2969    left with 0s to at least WIDTH characters.  */
2970 char *
2971 hex_string_custom (LONGEST num, int width)
2972 {
2973   char *result = get_cell ();
2974   char *result_end = result + CELLSIZE - 1;
2975   const char *hex = phex_nz (num, sizeof (num));
2976   int hex_len = strlen (hex);
2977
2978   if (hex_len > width)
2979     width = hex_len;
2980   if (width + 2 >= CELLSIZE)
2981     internal_error (__FILE__, __LINE__, _("\
2982 hex_string_custom: insufficient space to store result"));
2983
2984   strcpy (result_end - width - 2, "0x");
2985   memset (result_end - width, '0', width);
2986   strcpy (result_end - hex_len, hex);
2987   return result_end - width - 2;
2988 }
2989
2990 /* Convert VAL to a numeral in the given radix.  For
2991  * radix 10, IS_SIGNED may be true, indicating a signed quantity;
2992  * otherwise VAL is interpreted as unsigned.  If WIDTH is supplied, 
2993  * it is the minimum width (0-padded if needed).  USE_C_FORMAT means
2994  * to use C format in all cases.  If it is false, then 'x' 
2995  * and 'o' formats do not include a prefix (0x or leading 0).  */
2996
2997 char *
2998 int_string (LONGEST val, int radix, int is_signed, int width, 
2999             int use_c_format)
3000 {
3001   switch (radix) 
3002     {
3003     case 16:
3004       {
3005         char *result;
3006
3007         if (width == 0)
3008           result = hex_string (val);
3009         else
3010           result = hex_string_custom (val, width);
3011         if (! use_c_format)
3012           result += 2;
3013         return result;
3014       }
3015     case 10:
3016       {
3017         if (is_signed && val < 0)
3018           return decimal2str ("-", -val, width);
3019         else
3020           return decimal2str ("", val, width);
3021       }
3022     case 8:
3023       {
3024         char *result = octal2str (val, width);
3025
3026         if (use_c_format || val == 0)
3027           return result;
3028         else
3029           return result + 1;
3030       }
3031     default:
3032       internal_error (__FILE__, __LINE__,
3033                       _("failed internal consistency check"));
3034     }
3035 }       
3036
3037 /* Convert a CORE_ADDR into a string.  */
3038 const char *
3039 core_addr_to_string (const CORE_ADDR addr)
3040 {
3041   char *str = get_cell ();
3042
3043   strcpy (str, "0x");
3044   strcat (str, phex (addr, sizeof (addr)));
3045   return str;
3046 }
3047
3048 const char *
3049 core_addr_to_string_nz (const CORE_ADDR addr)
3050 {
3051   char *str = get_cell ();
3052
3053   strcpy (str, "0x");
3054   strcat (str, phex_nz (addr, sizeof (addr)));
3055   return str;
3056 }
3057
3058 /* Convert a string back into a CORE_ADDR.  */
3059 CORE_ADDR
3060 string_to_core_addr (const char *my_string)
3061 {
3062   CORE_ADDR addr = 0;
3063
3064   if (my_string[0] == '0' && tolower (my_string[1]) == 'x')
3065     {
3066       /* Assume that it is in hex.  */
3067       int i;
3068
3069       for (i = 2; my_string[i] != '\0'; i++)
3070         {
3071           if (isdigit (my_string[i]))
3072             addr = (my_string[i] - '0') + (addr * 16);
3073           else if (isxdigit (my_string[i]))
3074             addr = (tolower (my_string[i]) - 'a' + 0xa) + (addr * 16);
3075           else
3076             error (_("invalid hex \"%s\""), my_string);
3077         }
3078     }
3079   else
3080     {
3081       /* Assume that it is in decimal.  */
3082       int i;
3083
3084       for (i = 0; my_string[i] != '\0'; i++)
3085         {
3086           if (isdigit (my_string[i]))
3087             addr = (my_string[i] - '0') + (addr * 10);
3088           else
3089             error (_("invalid decimal \"%s\""), my_string);
3090         }
3091     }
3092
3093   return addr;
3094 }
3095
3096 const char *
3097 host_address_to_string (const void *addr)
3098 {
3099   char *str = get_cell ();
3100
3101   xsnprintf (str, CELLSIZE, "0x%s", phex_nz ((uintptr_t) addr, sizeof (addr)));
3102   return str;
3103 }
3104
3105 char *
3106 gdb_realpath (const char *filename)
3107 {
3108   /* Method 1: The system has a compile time upper bound on a filename
3109      path.  Use that and realpath() to canonicalize the name.  This is
3110      the most common case.  Note that, if there isn't a compile time
3111      upper bound, you want to avoid realpath() at all costs.  */
3112 #if defined(HAVE_REALPATH)
3113   {
3114 # if defined (PATH_MAX)
3115     char buf[PATH_MAX];
3116 #  define USE_REALPATH
3117 # elif defined (MAXPATHLEN)
3118     char buf[MAXPATHLEN];
3119 #  define USE_REALPATH
3120 # endif
3121 # if defined (USE_REALPATH)
3122     const char *rp = realpath (filename, buf);
3123
3124     if (rp == NULL)
3125       rp = filename;
3126     return xstrdup (rp);
3127 # endif
3128   }
3129 #endif /* HAVE_REALPATH */
3130
3131   /* Method 2: The host system (i.e., GNU) has the function
3132      canonicalize_file_name() which malloc's a chunk of memory and
3133      returns that, use that.  */
3134 #if defined(HAVE_CANONICALIZE_FILE_NAME)
3135   {
3136     char *rp = canonicalize_file_name (filename);
3137
3138     if (rp == NULL)
3139       return xstrdup (filename);
3140     else
3141       return rp;
3142   }
3143 #endif
3144
3145   /* FIXME: cagney/2002-11-13:
3146
3147      Method 2a: Use realpath() with a NULL buffer.  Some systems, due
3148      to the problems described in method 3, have modified their
3149      realpath() implementation so that it will allocate a buffer when
3150      NULL is passed in.  Before this can be used, though, some sort of
3151      configure time test would need to be added.  Otherwize the code
3152      will likely core dump.  */
3153
3154   /* Method 3: Now we're getting desperate!  The system doesn't have a
3155      compile time buffer size and no alternative function.  Query the
3156      OS, using pathconf(), for the buffer limit.  Care is needed
3157      though, some systems do not limit PATH_MAX (return -1 for
3158      pathconf()) making it impossible to pass a correctly sized buffer
3159      to realpath() (it could always overflow).  On those systems, we
3160      skip this.  */
3161 #if defined (HAVE_REALPATH) && defined (HAVE_UNISTD_H) && defined(HAVE_ALLOCA)
3162   {
3163     /* Find out the max path size.  */
3164     long path_max = pathconf ("/", _PC_PATH_MAX);
3165
3166     if (path_max > 0)
3167       {
3168         /* PATH_MAX is bounded.  */
3169         char *buf = alloca (path_max);
3170         char *rp = realpath (filename, buf);
3171
3172         return xstrdup (rp ? rp : filename);
3173       }
3174   }
3175 #endif
3176
3177   /* The MS Windows method.  If we don't have realpath, we assume we
3178      don't have symlinks and just canonicalize to a Windows absolute
3179      path.  GetFullPath converts ../ and ./ in relative paths to
3180      absolute paths, filling in current drive if one is not given
3181      or using the current directory of a specified drive (eg, "E:foo").
3182      It also converts all forward slashes to back slashes.  */
3183   /* The file system is case-insensitive but case-preserving.
3184      So we do not lowercase the path.  Otherwise, we might not
3185      be able to display the original casing in a given path.  */
3186 #if defined (_WIN32)
3187   {
3188     char buf[MAX_PATH];
3189     DWORD len = GetFullPathName (filename, MAX_PATH, buf, NULL);
3190
3191     if (len > 0 && len < MAX_PATH)
3192       return xstrdup (buf);
3193   }
3194 #endif
3195
3196   /* This system is a lost cause, just dup the buffer.  */
3197   return xstrdup (filename);
3198 }
3199
3200 /* Return a copy of FILENAME, with its directory prefix canonicalized
3201    by gdb_realpath.  */
3202
3203 char *
3204 xfullpath (const char *filename)
3205 {
3206   const char *base_name = lbasename (filename);
3207   char *dir_name;
3208   char *real_path;
3209   char *result;
3210
3211   /* Extract the basename of filename, and return immediately 
3212      a copy of filename if it does not contain any directory prefix.  */
3213   if (base_name == filename)
3214     return xstrdup (filename);
3215
3216   dir_name = alloca ((size_t) (base_name - filename + 2));
3217   /* Allocate enough space to store the dir_name + plus one extra
3218      character sometimes needed under Windows (see below), and
3219      then the closing \000 character.  */
3220   strncpy (dir_name, filename, base_name - filename);
3221   dir_name[base_name - filename] = '\000';
3222
3223 #ifdef HAVE_DOS_BASED_FILE_SYSTEM
3224   /* We need to be careful when filename is of the form 'd:foo', which
3225      is equivalent of d:./foo, which is totally different from d:/foo.  */
3226   if (strlen (dir_name) == 2 && isalpha (dir_name[0]) && dir_name[1] == ':')
3227     {
3228       dir_name[2] = '.';
3229       dir_name[3] = '\000';
3230     }
3231 #endif
3232
3233   /* Canonicalize the directory prefix, and build the resulting
3234      filename.  If the dirname realpath already contains an ending
3235      directory separator, avoid doubling it.  */
3236   real_path = gdb_realpath (dir_name);
3237   if (IS_DIR_SEPARATOR (real_path[strlen (real_path) - 1]))
3238     result = concat (real_path, base_name, (char *) NULL);
3239   else
3240     result = concat (real_path, SLASH_STRING, base_name, (char *) NULL);
3241
3242   xfree (real_path);
3243   return result;
3244 }
3245
3246
3247 /* This is the 32-bit CRC function used by the GNU separate debug
3248    facility.  An executable may contain a section named
3249    .gnu_debuglink, which holds the name of a separate executable file
3250    containing its debug info, and a checksum of that file's contents,
3251    computed using this function.  */
3252 unsigned long
3253 gnu_debuglink_crc32 (unsigned long crc, unsigned char *buf, size_t len)
3254 {
3255   static const unsigned int crc32_table[256] = {
3256     0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419,
3257     0x706af48f, 0xe963a535, 0x9e6495a3, 0x0edb8832, 0x79dcb8a4,
3258     0xe0d5e91e, 0x97d2d988, 0x09b64c2b, 0x7eb17cbd, 0xe7b82d07,
3259     0x90bf1d91, 0x1db71064, 0x6ab020f2, 0xf3b97148, 0x84be41de,
3260     0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7, 0x136c9856,
3261     0x646ba8c0, 0xfd62f97a, 0x8a65c9ec, 0x14015c4f, 0x63066cd9,
3262     0xfa0f3d63, 0x8d080df5, 0x3b6e20c8, 0x4c69105e, 0xd56041e4,
3263     0xa2677172, 0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b,
3264     0x35b5a8fa, 0x42b2986c, 0xdbbbc9d6, 0xacbcf940, 0x32d86ce3,
3265     0x45df5c75, 0xdcd60dcf, 0xabd13d59, 0x26d930ac, 0x51de003a,
3266     0xc8d75180, 0xbfd06116, 0x21b4f4b5, 0x56b3c423, 0xcfba9599,
3267     0xb8bda50f, 0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924,
3268     0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d, 0x76dc4190,
3269     0x01db7106, 0x98d220bc, 0xefd5102a, 0x71b18589, 0x06b6b51f,
3270     0x9fbfe4a5, 0xe8b8d433, 0x7807c9a2, 0x0f00f934, 0x9609a88e,
3271     0xe10e9818, 0x7f6a0dbb, 0x086d3d2d, 0x91646c97, 0xe6635c01,
3272     0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e, 0x6c0695ed,
3273     0x1b01a57b, 0x8208f4c1, 0xf50fc457, 0x65b0d9c6, 0x12b7e950,
3274     0x8bbeb8ea, 0xfcb9887c, 0x62dd1ddf, 0x15da2d49, 0x8cd37cf3,
3275     0xfbd44c65, 0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2,
3276     0x4adfa541, 0x3dd895d7, 0xa4d1c46d, 0xd3d6f4fb, 0x4369e96a,
3277     0x346ed9fc, 0xad678846, 0xda60b8d0, 0x44042d73, 0x33031de5,
3278     0xaa0a4c5f, 0xdd0d7cc9, 0x5005713c, 0x270241aa, 0xbe0b1010,
3279     0xc90c2086, 0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f,
3280     0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4, 0x59b33d17,
3281     0x2eb40d81, 0xb7bd5c3b, 0xc0ba6cad, 0xedb88320, 0x9abfb3b6,
3282     0x03b6e20c, 0x74b1d29a, 0xead54739, 0x9dd277af, 0x04db2615,
3283     0x73dc1683, 0xe3630b12, 0x94643b84, 0x0d6d6a3e, 0x7a6a5aa8,
3284     0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1, 0xf00f9344,
3285     0x8708a3d2, 0x1e01f268, 0x6906c2fe, 0xf762575d, 0x806567cb,
3286     0x196c3671, 0x6e6b06e7, 0xfed41b76, 0x89d32be0, 0x10da7a5a,
3287     0x67dd4acc, 0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5,
3288     0xd6d6a3e8, 0xa1d1937e, 0x38d8c2c4, 0x4fdff252, 0xd1bb67f1,
3289     0xa6bc5767, 0x3fb506dd, 0x48b2364b, 0xd80d2bda, 0xaf0a1b4c,
3290     0x36034af6, 0x41047a60, 0xdf60efc3, 0xa867df55, 0x316e8eef,
3291     0x4669be79, 0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236,
3292     0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f, 0xc5ba3bbe,
3293     0xb2bd0b28, 0x2bb45a92, 0x5cb36a04, 0xc2d7ffa7, 0xb5d0cf31,
3294     0x2cd99e8b, 0x5bdeae1d, 0x9b64c2b0, 0xec63f226, 0x756aa39c,
3295     0x026d930a, 0x9c0906a9, 0xeb0e363f, 0x72076785, 0x05005713,
3296     0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38, 0x92d28e9b,
3297     0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21, 0x86d3d2d4, 0xf1d4e242,
3298     0x68ddb3f8, 0x1fda836e, 0x81be16cd, 0xf6b9265b, 0x6fb077e1,
3299     0x18b74777, 0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c,
3300     0x8f659eff, 0xf862ae69, 0x616bffd3, 0x166ccf45, 0xa00ae278,
3301     0xd70dd2ee, 0x4e048354, 0x3903b3c2, 0xa7672661, 0xd06016f7,
3302     0x4969474d, 0x3e6e77db, 0xaed16a4a, 0xd9d65adc, 0x40df0b66,
3303     0x37d83bf0, 0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9,
3304     0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6, 0xbad03605,
3305     0xcdd70693, 0x54de5729, 0x23d967bf, 0xb3667a2e, 0xc4614ab8,
3306     0x5d681b02, 0x2a6f2b94, 0xb40bbe37, 0xc30c8ea1, 0x5a05df1b,
3307     0x2d02ef8d
3308   };
3309   unsigned char *end;
3310
3311   crc = ~crc & 0xffffffff;
3312   for (end = buf + len; buf < end; ++buf)
3313     crc = crc32_table[(crc ^ *buf) & 0xff] ^ (crc >> 8);
3314   return ~crc & 0xffffffff;
3315 }
3316
3317 ULONGEST
3318 align_up (ULONGEST v, int n)
3319 {
3320   /* Check that N is really a power of two.  */
3321   gdb_assert (n && (n & (n-1)) == 0);
3322   return (v + n - 1) & -n;
3323 }
3324
3325 ULONGEST
3326 align_down (ULONGEST v, int n)
3327 {
3328   /* Check that N is really a power of two.  */
3329   gdb_assert (n && (n & (n-1)) == 0);
3330   return (v & -n);
3331 }
3332
3333 /* Allocation function for the libiberty hash table which uses an
3334    obstack.  The obstack is passed as DATA.  */
3335
3336 void *
3337 hashtab_obstack_allocate (void *data, size_t size, size_t count)
3338 {
3339   unsigned int total = size * count;
3340   void *ptr = obstack_alloc ((struct obstack *) data, total);
3341
3342   memset (ptr, 0, total);
3343   return ptr;
3344 }
3345
3346 /* Trivial deallocation function for the libiberty splay tree and hash
3347    table - don't deallocate anything.  Rely on later deletion of the
3348    obstack.  DATA will be the obstack, although it is not needed
3349    here.  */
3350
3351 void
3352 dummy_obstack_deallocate (void *object, void *data)
3353 {
3354   return;
3355 }
3356
3357 /* The bit offset of the highest byte in a ULONGEST, for overflow
3358    checking.  */
3359
3360 #define HIGH_BYTE_POSN ((sizeof (ULONGEST) - 1) * HOST_CHAR_BIT)
3361
3362 /* True (non-zero) iff DIGIT is a valid digit in radix BASE,
3363    where 2 <= BASE <= 36.  */
3364
3365 static int
3366 is_digit_in_base (unsigned char digit, int base)
3367 {
3368   if (!isalnum (digit))
3369     return 0;
3370   if (base <= 10)
3371     return (isdigit (digit) && digit < base + '0');
3372   else
3373     return (isdigit (digit) || tolower (digit) < base - 10 + 'a');
3374 }
3375
3376 static int
3377 digit_to_int (unsigned char c)
3378 {
3379   if (isdigit (c))
3380     return c - '0';
3381   else
3382     return tolower (c) - 'a' + 10;
3383 }
3384
3385 /* As for strtoul, but for ULONGEST results.  */
3386
3387 ULONGEST
3388 strtoulst (const char *num, const char **trailer, int base)
3389 {
3390   unsigned int high_part;
3391   ULONGEST result;
3392   int minus = 0;
3393   int i = 0;
3394
3395   /* Skip leading whitespace.  */
3396   while (isspace (num[i]))
3397     i++;
3398
3399   /* Handle prefixes.  */
3400   if (num[i] == '+')
3401     i++;
3402   else if (num[i] == '-')
3403     {
3404       minus = 1;
3405       i++;
3406     }
3407
3408   if (base == 0 || base == 16)
3409     {
3410       if (num[i] == '0' && (num[i + 1] == 'x' || num[i + 1] == 'X'))
3411         {
3412           i += 2;
3413           if (base == 0)
3414             base = 16;
3415         }
3416     }
3417
3418   if (base == 0 && num[i] == '0')
3419     base = 8;
3420
3421   if (base == 0)
3422     base = 10;
3423
3424   if (base < 2 || base > 36)
3425     {
3426       errno = EINVAL;
3427       return 0;
3428     }
3429
3430   result = high_part = 0;
3431   for (; is_digit_in_base (num[i], base); i += 1)
3432     {
3433       result = result * base + digit_to_int (num[i]);
3434       high_part = high_part * base + (unsigned int) (result >> HIGH_BYTE_POSN);
3435       result &= ((ULONGEST) 1 << HIGH_BYTE_POSN) - 1;
3436       if (high_part > 0xff)
3437         {
3438           errno = ERANGE;
3439           result = ~ (ULONGEST) 0;
3440           high_part = 0;
3441           minus = 0;
3442           break;
3443         }
3444     }
3445
3446   if (trailer != NULL)
3447     *trailer = &num[i];
3448
3449   result = result + ((ULONGEST) high_part << HIGH_BYTE_POSN);
3450   if (minus)
3451     return -result;
3452   else
3453     return result;
3454 }
3455
3456 /* Simple, portable version of dirname that does not modify its
3457    argument.  */
3458
3459 char *
3460 ldirname (const char *filename)
3461 {
3462   const char *base = lbasename (filename);
3463   char *dirname;
3464
3465   while (base > filename && IS_DIR_SEPARATOR (base[-1]))
3466     --base;
3467
3468   if (base == filename)
3469     return NULL;
3470
3471   dirname = xmalloc (base - filename + 2);
3472   memcpy (dirname, filename, base - filename);
3473
3474   /* On DOS based file systems, convert "d:foo" to "d:.", so that we
3475      create "d:./bar" later instead of the (different) "d:/bar".  */
3476   if (base - filename == 2 && IS_ABSOLUTE_PATH (base)
3477       && !IS_DIR_SEPARATOR (filename[0]))
3478     dirname[base++ - filename] = '.';
3479
3480   dirname[base - filename] = '\0';
3481   return dirname;
3482 }
3483
3484 /* Call libiberty's buildargv, and return the result.
3485    If buildargv fails due to out-of-memory, call nomem.
3486    Therefore, the returned value is guaranteed to be non-NULL,
3487    unless the parameter itself is NULL.  */
3488
3489 char **
3490 gdb_buildargv (const char *s)
3491 {
3492   char **argv = buildargv (s);
3493
3494   if (s != NULL && argv == NULL)
3495     malloc_failure (0);
3496   return argv;
3497 }
3498
3499 int
3500 compare_positive_ints (const void *ap, const void *bp)
3501 {
3502   /* Because we know we're comparing two ints which are positive,
3503      there's no danger of overflow here.  */
3504   return * (int *) ap - * (int *) bp;
3505 }
3506
3507 /* String compare function for qsort.  */
3508
3509 int
3510 compare_strings (const void *arg1, const void *arg2)
3511 {
3512   const char **s1 = (const char **) arg1;
3513   const char **s2 = (const char **) arg2;
3514
3515   return strcmp (*s1, *s2);
3516 }
3517
3518 #define AMBIGUOUS_MESS1 ".\nMatching formats:"
3519 #define AMBIGUOUS_MESS2 \
3520   ".\nUse \"set gnutarget format-name\" to specify the format."
3521
3522 const char *
3523 gdb_bfd_errmsg (bfd_error_type error_tag, char **matching)
3524 {
3525   char *ret, *retp;
3526   int ret_len;
3527   char **p;
3528
3529   /* Check if errmsg just need simple return.  */
3530   if (error_tag != bfd_error_file_ambiguously_recognized || matching == NULL)
3531     return bfd_errmsg (error_tag);
3532
3533   ret_len = strlen (bfd_errmsg (error_tag)) + strlen (AMBIGUOUS_MESS1)
3534             + strlen (AMBIGUOUS_MESS2);
3535   for (p = matching; *p; p++)
3536     ret_len += strlen (*p) + 1;
3537   ret = xmalloc (ret_len + 1);
3538   retp = ret;
3539   make_cleanup (xfree, ret);
3540
3541   strcpy (retp, bfd_errmsg (error_tag));
3542   retp += strlen (retp);
3543
3544   strcpy (retp, AMBIGUOUS_MESS1);
3545   retp += strlen (retp);
3546
3547   for (p = matching; *p; p++)
3548     {
3549       sprintf (retp, " %s", *p);
3550       retp += strlen (retp);
3551     }
3552   xfree (matching);
3553
3554   strcpy (retp, AMBIGUOUS_MESS2);
3555
3556   return ret;
3557 }
3558
3559 /* Return ARGS parsed as a valid pid, or throw an error.  */
3560
3561 int
3562 parse_pid_to_attach (char *args)
3563 {
3564   unsigned long pid;
3565   char *dummy;
3566
3567   if (!args)
3568     error_no_arg (_("process-id to attach"));
3569
3570   dummy = args;
3571   pid = strtoul (args, &dummy, 0);
3572   /* Some targets don't set errno on errors, grrr!  */
3573   if ((pid == 0 && dummy == args) || dummy != &args[strlen (args)])
3574     error (_("Illegal process-id: %s."), args);
3575
3576   return pid;
3577 }
3578
3579 /* Helper for make_bpstat_clear_actions_cleanup.  */
3580
3581 static void
3582 do_bpstat_clear_actions_cleanup (void *unused)
3583 {
3584   bpstat_clear_actions ();
3585 }
3586
3587 /* Call bpstat_clear_actions for the case an exception is throw.  You should
3588    discard_cleanups if no exception is caught.  */
3589
3590 struct cleanup *
3591 make_bpstat_clear_actions_cleanup (void)
3592 {
3593   return make_cleanup (do_bpstat_clear_actions_cleanup, NULL);
3594 }
3595
3596 /* Check for GCC >= 4.x according to the symtab->producer string.  Return minor
3597    version (x) of 4.x in such case.  If it is not GCC or it is GCC older than
3598    4.x return -1.  If it is GCC 5.x or higher return INT_MAX.  */
3599
3600 int
3601 producer_is_gcc_ge_4 (const char *producer)
3602 {
3603   const char *cs;
3604   int major, minor;
3605
3606   if (producer == NULL)
3607     {
3608       /* For unknown compilers expect their behavior is not compliant.  For GCC
3609          this case can also happen for -gdwarf-4 type units supported since
3610          gcc-4.5.  */
3611
3612       return -1;
3613     }
3614
3615   /* Skip any identifier after "GNU " - such as "C++" or "Java".  */
3616
3617   if (strncmp (producer, "GNU ", strlen ("GNU ")) != 0)
3618     {
3619       /* For non-GCC compilers expect their behavior is not compliant.  */
3620
3621       return -1;
3622     }
3623   cs = &producer[strlen ("GNU ")];
3624   while (*cs && !isdigit (*cs))
3625     cs++;
3626   if (sscanf (cs, "%d.%d", &major, &minor) != 2)
3627     {
3628       /* Not recognized as GCC.  */
3629
3630       return -1;
3631     }
3632
3633   if (major < 4)
3634     return -1;
3635   if (major > 4)
3636     return INT_MAX;
3637   return minor;
3638 }
3639
3640 /* Helper for make_cleanup_free_char_ptr_vec.  */
3641
3642 static void
3643 do_free_char_ptr_vec (void *arg)
3644 {
3645   VEC (char_ptr) *char_ptr_vec = arg;
3646
3647   free_char_ptr_vec (char_ptr_vec);
3648 }
3649
3650 /* Make cleanup handler calling xfree for each element of CHAR_PTR_VEC and
3651    final VEC_free for CHAR_PTR_VEC itself.
3652
3653    You must not modify CHAR_PTR_VEC after this cleanup registration as the
3654    CHAR_PTR_VEC base address may change on its updates.  Contrary to VEC_free
3655    this function does not (cannot) clear the pointer.  */
3656
3657 struct cleanup *
3658 make_cleanup_free_char_ptr_vec (VEC (char_ptr) *char_ptr_vec)
3659 {
3660   return make_cleanup (do_free_char_ptr_vec, char_ptr_vec);
3661 }
3662
3663 /* Substitute all occurences of string FROM by string TO in *STRINGP.  *STRINGP
3664    must come from xrealloc-compatible allocator and it may be updated.  FROM
3665    needs to be delimited by IS_DIR_SEPARATOR or DIRNAME_SEPARATOR (or be
3666    located at the start or end of *STRINGP.  */
3667
3668 void
3669 substitute_path_component (char **stringp, const char *from, const char *to)
3670 {
3671   char *string = *stringp, *s;
3672   const size_t from_len = strlen (from);
3673   const size_t to_len = strlen (to);
3674
3675   for (s = string;;)
3676     {
3677       s = strstr (s, from);
3678       if (s == NULL)
3679         break;
3680
3681       if ((s == string || IS_DIR_SEPARATOR (s[-1])
3682            || s[-1] == DIRNAME_SEPARATOR)
3683           && (s[from_len] == '\0' || IS_DIR_SEPARATOR (s[from_len])
3684               || s[from_len] == DIRNAME_SEPARATOR))
3685         {
3686           char *string_new;
3687
3688           string_new = xrealloc (string, (strlen (string) + to_len + 1));
3689
3690           /* Relocate the current S pointer.  */
3691           s = s - string + string_new;
3692           string = string_new;
3693
3694           /* Replace from by to.  */
3695           memmove (&s[to_len], &s[from_len], strlen (&s[from_len]) + 1);
3696           memcpy (s, to, to_len);
3697
3698           s += to_len;
3699         }
3700       else
3701         s++;
3702     }
3703
3704   *stringp = string;
3705 }
3706
3707 #ifdef HAVE_WAITPID
3708
3709 #ifdef SIGALRM
3710
3711 /* SIGALRM handler for waitpid_with_timeout.  */
3712
3713 static void
3714 sigalrm_handler (int signo)
3715 {
3716   /* Nothing to do.  */
3717 }
3718
3719 #endif
3720
3721 /* Wrapper to wait for child PID to die with TIMEOUT.
3722    TIMEOUT is the time to stop waiting in seconds.
3723    If TIMEOUT is zero, pass WNOHANG to waitpid.
3724    Returns PID if it was successfully waited for, otherwise -1.
3725
3726    Timeouts are currently implemented with alarm and SIGALRM.
3727    If the host does not support them, this waits "forever".
3728    It would be odd though for a host to have waitpid and not SIGALRM.  */
3729
3730 pid_t
3731 wait_to_die_with_timeout (pid_t pid, int *status, int timeout)
3732 {
3733   pid_t waitpid_result;
3734
3735   gdb_assert (pid > 0);
3736   gdb_assert (timeout >= 0);
3737
3738   if (timeout > 0)
3739     {
3740 #ifdef SIGALRM
3741 #if defined (HAVE_SIGACTION) && defined (SA_RESTART)
3742       struct sigaction sa, old_sa;
3743
3744       sa.sa_handler = sigalrm_handler;
3745       sigemptyset (&sa.sa_mask);
3746       sa.sa_flags = 0;
3747       sigaction (SIGALRM, &sa, &old_sa);
3748 #else
3749       void (*ofunc) ();
3750
3751       ofunc = (void (*)()) signal (SIGALRM, sigalrm_handler);
3752 #endif
3753
3754       alarm (timeout);
3755 #endif
3756
3757       waitpid_result = waitpid (pid, status, 0);
3758
3759 #ifdef SIGALRM
3760       alarm (0);
3761 #if defined (HAVE_SIGACTION) && defined (SA_RESTART)
3762       sigaction (SIGALRM, &old_sa, NULL);
3763 #else
3764       signal (SIGALRM, ofunc);
3765 #endif
3766 #endif
3767     }
3768   else
3769     waitpid_result = waitpid (pid, status, WNOHANG);
3770
3771   if (waitpid_result == pid)
3772     return pid;
3773   else
3774     return -1;
3775 }
3776
3777 #endif /* HAVE_WAITPID */
3778
3779 /* Provide fnmatch compatible function for FNM_FILE_NAME matching of host files.
3780    Both FNM_FILE_NAME and FNM_NOESCAPE must be set in FLAGS.
3781
3782    It handles correctly HAVE_DOS_BASED_FILE_SYSTEM and
3783    HAVE_CASE_INSENSITIVE_FILE_SYSTEM.  */
3784
3785 int
3786 gdb_filename_fnmatch (const char *pattern, const char *string, int flags)
3787 {
3788   gdb_assert ((flags & FNM_FILE_NAME) != 0);
3789
3790   /* It is unclear how '\' escaping vs. directory separator should coexist.  */
3791   gdb_assert ((flags & FNM_NOESCAPE) != 0);
3792
3793 #ifdef HAVE_DOS_BASED_FILE_SYSTEM
3794   {
3795     char *pattern_slash, *string_slash;
3796
3797     /* Replace '\' by '/' in both strings.  */
3798
3799     pattern_slash = alloca (strlen (pattern) + 1);
3800     strcpy (pattern_slash, pattern);
3801     pattern = pattern_slash;
3802     for (; *pattern_slash != 0; pattern_slash++)
3803       if (IS_DIR_SEPARATOR (*pattern_slash))
3804         *pattern_slash = '/';
3805
3806     string_slash = alloca (strlen (string) + 1);
3807     strcpy (string_slash, string);
3808     string = string_slash;
3809     for (; *string_slash != 0; string_slash++)
3810       if (IS_DIR_SEPARATOR (*string_slash))
3811         *string_slash = '/';
3812   }
3813 #endif /* HAVE_DOS_BASED_FILE_SYSTEM */
3814
3815 #ifdef HAVE_CASE_INSENSITIVE_FILE_SYSTEM
3816   flags |= FNM_CASEFOLD;
3817 #endif /* HAVE_CASE_INSENSITIVE_FILE_SYSTEM */
3818
3819   return fnmatch (pattern, string, flags);
3820 }
3821
3822 /* Provide a prototype to silence -Wmissing-prototypes.  */
3823 extern initialize_file_ftype _initialize_utils;
3824
3825 void
3826 _initialize_utils (void)
3827 {
3828   add_internal_problem_command (&internal_error_problem);
3829   add_internal_problem_command (&internal_warning_problem);
3830 }