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