Sat Oct 28 23:51:48 1995 steve chamberlain <sac@slash.cygnus.com>
[external/binutils.git] / gdb / utils.c
1 /* General utility routines for GDB, the GNU debugger.
2    Copyright 1986, 1989, 1990, 1991, 1992, 1995 Free Software Foundation, Inc.
3
4 This file is part of GDB.
5
6 This program is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 2 of the License, or
9 (at your option) any later version.
10
11 This program is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 GNU General Public License for more details.
15
16 You should have received a copy of the GNU General Public License
17 along with this program; if not, write to the Free Software
18 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.  */
19
20 #include "defs.h"
21 #if !defined(__GO32__) && !defined(__WIN32__)
22 #include <sys/ioctl.h>
23 #include <sys/param.h>
24 #include <pwd.h>
25 #endif
26 #ifdef ANSI_PROTOTYPES
27 #include <stdarg.h>
28 #else
29 #include <varargs.h>
30 #endif
31 #include <ctype.h>
32 #include "gdb_string.h"
33 #ifdef HAVE_UNISTD_H
34 #include <unistd.h>
35 #endif
36
37 #include "signals.h"
38 #include "gdbcmd.h"
39 #include "serial.h"
40 #include "bfd.h"
41 #include "target.h"
42 #include "demangle.h"
43 #include "expression.h"
44 #include "language.h"
45 #include "annotate.h"
46
47 #include "readline.h"
48
49 /* readline defines this.  */
50 #undef savestring
51
52 /* Prototypes for local functions */
53
54 #if defined (NO_MMALLOC) || defined (NO_MMALLOC_CHECK)
55 #else
56
57 static void
58 malloc_botch PARAMS ((void));
59
60 #endif /* NO_MMALLOC, etc */
61
62 static void
63 fatal_dump_core PARAMS((char *, ...));
64
65 static void
66 prompt_for_continue PARAMS ((void));
67
68 static void 
69 set_width_command PARAMS ((char *, int, struct cmd_list_element *));
70
71 /* If this definition isn't overridden by the header files, assume
72    that isatty and fileno exist on this system.  */
73 #ifndef ISATTY
74 #define ISATTY(FP)      (isatty (fileno (FP)))
75 #endif
76
77 /* Chain of cleanup actions established with make_cleanup,
78    to be executed if an error happens.  */
79
80 static struct cleanup *cleanup_chain;
81
82 /* Nonzero if we have job control. */
83
84 int job_control;
85
86 /* Nonzero means a quit has been requested.  */
87
88 int quit_flag;
89
90 /* Nonzero means quit immediately if Control-C is typed now, rather
91    than waiting until QUIT is executed.  Be careful in setting this;
92    code which executes with immediate_quit set has to be very careful
93    about being able to deal with being interrupted at any time.  It is
94    almost always better to use QUIT; the only exception I can think of
95    is being able to quit out of a system call (using EINTR loses if
96    the SIGINT happens between the previous QUIT and the system call).
97    To immediately quit in the case in which a SIGINT happens between
98    the previous QUIT and setting immediate_quit (desirable anytime we
99    expect to block), call QUIT after setting immediate_quit.  */
100
101 int immediate_quit;
102
103 /* Nonzero means that encoded C++ names should be printed out in their
104    C++ form rather than raw.  */
105
106 int demangle = 1;
107
108 /* Nonzero means that encoded C++ names should be printed out in their
109    C++ form even in assembler language displays.  If this is set, but
110    DEMANGLE is zero, names are printed raw, i.e. DEMANGLE controls.  */
111
112 int asm_demangle = 0;
113
114 /* Nonzero means that strings with character values >0x7F should be printed
115    as octal escapes.  Zero means just print the value (e.g. it's an
116    international character, and the terminal or window can cope.)  */
117
118 int sevenbit_strings = 0;
119
120 /* String to be printed before error messages, if any.  */
121
122 char *error_pre_print;
123
124 /* String to be printed before quit messages, if any.  */
125
126 char *quit_pre_print;
127
128 /* String to be printed before warning messages, if any.  */
129
130 char *warning_pre_print = "\nwarning: ";
131 \f
132 /* Add a new cleanup to the cleanup_chain,
133    and return the previous chain pointer
134    to be passed later to do_cleanups or discard_cleanups.
135    Args are FUNCTION to clean up with, and ARG to pass to it.  */
136
137 struct cleanup *
138 make_cleanup (function, arg)
139      void (*function) PARAMS ((PTR));
140      PTR arg;
141 {
142   register struct cleanup *new
143     = (struct cleanup *) xmalloc (sizeof (struct cleanup));
144   register struct cleanup *old_chain = cleanup_chain;
145
146   new->next = cleanup_chain;
147   new->function = function;
148   new->arg = arg;
149   cleanup_chain = new;
150
151   return old_chain;
152 }
153
154 /* Discard cleanups and do the actions they describe
155    until we get back to the point OLD_CHAIN in the cleanup_chain.  */
156
157 void
158 do_cleanups (old_chain)
159      register struct cleanup *old_chain;
160 {
161   register struct cleanup *ptr;
162   while ((ptr = cleanup_chain) != old_chain)
163     {
164       cleanup_chain = ptr->next;        /* Do this first incase recursion */
165       (*ptr->function) (ptr->arg);
166       free (ptr);
167     }
168 }
169
170 /* Discard cleanups, not doing the actions they describe,
171    until we get back to the point OLD_CHAIN in the cleanup_chain.  */
172
173 void
174 discard_cleanups (old_chain)
175      register struct cleanup *old_chain;
176 {
177   register struct cleanup *ptr;
178   while ((ptr = cleanup_chain) != old_chain)
179     {
180       cleanup_chain = ptr->next;
181       free ((PTR)ptr);
182     }
183 }
184
185 /* Set the cleanup_chain to 0, and return the old cleanup chain.  */
186 struct cleanup *
187 save_cleanups ()
188 {
189   struct cleanup *old_chain = cleanup_chain;
190
191   cleanup_chain = 0;
192   return old_chain;
193 }
194
195 /* Restore the cleanup chain from a previously saved chain.  */
196 void
197 restore_cleanups (chain)
198      struct cleanup *chain;
199 {
200   cleanup_chain = chain;
201 }
202
203 /* This function is useful for cleanups.
204    Do
205
206      foo = xmalloc (...);
207      old_chain = make_cleanup (free_current_contents, &foo);
208
209    to arrange to free the object thus allocated.  */
210
211 void
212 free_current_contents (location)
213      char **location;
214 {
215   free (*location);
216 }
217
218 /* Provide a known function that does nothing, to use as a base for
219    for a possibly long chain of cleanups.  This is useful where we
220    use the cleanup chain for handling normal cleanups as well as dealing
221    with cleanups that need to be done as a result of a call to error().
222    In such cases, we may not be certain where the first cleanup is, unless
223    we have a do-nothing one to always use as the base. */
224
225 /* ARGSUSED */
226 void
227 null_cleanup (arg)
228     char **arg;
229 {
230 }
231
232 \f
233 /* Print a warning message.  Way to use this is to call warning_begin,
234    output the warning message (use unfiltered output to gdb_stderr),
235    ending in a newline.  There is not currently a warning_end that you
236    call afterwards, but such a thing might be added if it is useful
237    for a GUI to separate warning messages from other output.
238
239    FIXME: Why do warnings use unfiltered output and errors filtered?
240    Is this anything other than a historical accident?  */
241
242 void
243 warning_begin ()
244 {
245   target_terminal_ours ();
246   wrap_here("");                        /* Force out any buffered output */
247   gdb_flush (gdb_stdout);
248   if (warning_pre_print)
249     fprintf_unfiltered (gdb_stderr, warning_pre_print);
250 }
251
252 /* Print a warning message.
253    The first argument STRING is the warning message, used as a fprintf string,
254    and the remaining args are passed as arguments to it.
255    The primary difference between warnings and errors is that a warning
256    does not force the return to command level.  */
257
258 /* VARARGS */
259 void
260 #ifdef ANSI_PROTOTYPES
261 warning (char *string, ...)
262 #else
263 warning (va_alist)
264      va_dcl
265 #endif
266 {
267   va_list args;
268 #ifdef ANSI_PROTOTYPES
269   va_start (args, string);
270 #else
271   char *string;
272
273   va_start (args);
274   string = va_arg (args, char *);
275 #endif
276   warning_begin ();
277   vfprintf_unfiltered (gdb_stderr, string, args);
278   fprintf_unfiltered (gdb_stderr, "\n");
279   va_end (args);
280 }
281
282 /* Start the printing of an error message.  Way to use this is to call
283    this, output the error message (use filtered output to gdb_stderr
284    (FIXME: Some callers, like memory_error, use gdb_stdout)), ending
285    in a newline, and then call return_to_top_level (RETURN_ERROR).
286    error() provides a convenient way to do this for the special case
287    that the error message can be formatted with a single printf call,
288    but this is more general.  */
289 void
290 error_begin ()
291 {
292   target_terminal_ours ();
293   wrap_here ("");                       /* Force out any buffered output */
294   gdb_flush (gdb_stdout);
295
296   annotate_error_begin ();
297
298   if (error_pre_print)
299     fprintf_filtered (gdb_stderr, error_pre_print);
300 }
301
302 /* Print an error message and return to command level.
303    The first argument STRING is the error message, used as a fprintf string,
304    and the remaining args are passed as arguments to it.  */
305
306 #ifdef ANSI_PROTOTYPES
307 NORETURN void
308 error (char *string, ...)
309 #else
310 void
311 error (va_alist)
312      va_dcl
313 #endif
314 {
315   va_list args;
316 #ifdef ANSI_PROTOTYPES
317   va_start (args, string);
318 #else
319   va_start (args);
320 #endif
321   if (error_hook)
322     (*error_hook) ();
323   else 
324     {
325       error_begin ();
326 #ifdef ANSI_PROTOTYPES
327       vfprintf_filtered (gdb_stderr, string, args);
328 #else
329       {
330         char *string1;
331
332         string1 = va_arg (args, char *);
333         vfprintf_filtered (gdb_stderr, string1, args);
334       }
335 #endif
336       fprintf_filtered (gdb_stderr, "\n");
337       va_end (args);
338       return_to_top_level (RETURN_ERROR);
339     }
340 }
341
342
343 /* Print an error message and exit reporting failure.
344    This is for a error that we cannot continue from.
345    The arguments are printed a la printf.
346
347    This function cannot be declared volatile (NORETURN) in an
348    ANSI environment because exit() is not declared volatile. */
349
350 /* VARARGS */
351 NORETURN void
352 #ifdef ANSI_PROTOTYPES
353 fatal (char *string, ...)
354 #else
355 fatal (va_alist)
356      va_dcl
357 #endif
358 {
359   va_list args;
360 #ifdef ANSI_PROTOTYPES
361   va_start (args, string);
362 #else
363   char *string;
364   va_start (args);
365   string = va_arg (args, char *);
366 #endif
367   fprintf_unfiltered (gdb_stderr, "\ngdb: ");
368   vfprintf_unfiltered (gdb_stderr, string, args);
369   fprintf_unfiltered (gdb_stderr, "\n");
370   va_end (args);
371   exit (1);
372 }
373
374 /* Print an error message and exit, dumping core.
375    The arguments are printed a la printf ().  */
376
377 /* VARARGS */
378 static void
379 #ifdef ANSI_PROTOTYPES
380 fatal_dump_core (char *string, ...)
381 #else
382 fatal_dump_core (va_alist)
383      va_dcl
384 #endif
385 {
386   va_list args;
387 #ifdef ANSI_PROTOTYPES
388   va_start (args, string);
389 #else
390   char *string;
391
392   va_start (args);
393   string = va_arg (args, char *);
394 #endif
395   /* "internal error" is always correct, since GDB should never dump
396      core, no matter what the input.  */
397   fprintf_unfiltered (gdb_stderr, "\ngdb internal error: ");
398   vfprintf_unfiltered (gdb_stderr, string, args);
399   fprintf_unfiltered (gdb_stderr, "\n");
400   va_end (args);
401
402   signal (SIGQUIT, SIG_DFL);
403   kill (getpid (), SIGQUIT);
404   /* We should never get here, but just in case...  */
405   exit (1);
406 }
407
408 /* The strerror() function can return NULL for errno values that are
409    out of range.  Provide a "safe" version that always returns a
410    printable string. */
411
412 char *
413 safe_strerror (errnum)
414      int errnum;
415 {
416   char *msg;
417   static char buf[32];
418
419   if ((msg = strerror (errnum)) == NULL)
420     {
421       sprintf (buf, "(undocumented errno %d)", errnum);
422       msg = buf;
423     }
424   return (msg);
425 }
426
427 /* The strsignal() function can return NULL for signal values that are
428    out of range.  Provide a "safe" version that always returns a
429    printable string. */
430
431 char *
432 safe_strsignal (signo)
433      int signo;
434 {
435   char *msg;
436   static char buf[32];
437
438   if ((msg = strsignal (signo)) == NULL)
439     {
440       sprintf (buf, "(undocumented signal %d)", signo);
441       msg = buf;
442     }
443   return (msg);
444 }
445
446
447 /* Print the system error message for errno, and also mention STRING
448    as the file name for which the error was encountered.
449    Then return to command level.  */
450
451 void
452 perror_with_name (string)
453      char *string;
454 {
455   char *err;
456   char *combined;
457
458   err = safe_strerror (errno);
459   combined = (char *) alloca (strlen (err) + strlen (string) + 3);
460   strcpy (combined, string);
461   strcat (combined, ": ");
462   strcat (combined, err);
463
464   /* I understand setting these is a matter of taste.  Still, some people
465      may clear errno but not know about bfd_error.  Doing this here is not
466      unreasonable. */
467   bfd_set_error (bfd_error_no_error);
468   errno = 0;
469
470   error ("%s.", combined);
471 }
472
473 /* Print the system error message for ERRCODE, and also mention STRING
474    as the file name for which the error was encountered.  */
475
476 void
477 print_sys_errmsg (string, errcode)
478      char *string;
479      int errcode;
480 {
481   char *err;
482   char *combined;
483
484   err = safe_strerror (errcode);
485   combined = (char *) alloca (strlen (err) + strlen (string) + 3);
486   strcpy (combined, string);
487   strcat (combined, ": ");
488   strcat (combined, err);
489
490   /* We want anything which was printed on stdout to come out first, before
491      this message.  */
492   gdb_flush (gdb_stdout);
493   fprintf_unfiltered (gdb_stderr, "%s.\n", combined);
494 }
495
496 /* Control C eventually causes this to be called, at a convenient time.  */
497
498 void
499 quit ()
500 {
501   serial_t gdb_stdout_serial = serial_fdopen (1);
502
503   target_terminal_ours ();
504
505   /* We want all output to appear now, before we print "Quit".  We
506      have 3 levels of buffering we have to flush (it's possible that
507      some of these should be changed to flush the lower-level ones
508      too):  */
509
510   /* 1.  The _filtered buffer.  */
511   wrap_here ((char *)0);
512
513   /* 2.  The stdio buffer.  */
514   gdb_flush (gdb_stdout);
515   gdb_flush (gdb_stderr);
516
517   /* 3.  The system-level buffer.  */
518   SERIAL_FLUSH_OUTPUT (gdb_stdout_serial);
519   SERIAL_UN_FDOPEN (gdb_stdout_serial);
520
521   annotate_error_begin ();
522
523   /* Don't use *_filtered; we don't want to prompt the user to continue.  */
524   if (quit_pre_print)
525     fprintf_unfiltered (gdb_stderr, quit_pre_print);
526
527   if (job_control
528       /* If there is no terminal switching for this target, then we can't
529          possibly get screwed by the lack of job control.  */
530       || current_target.to_terminal_ours == NULL)
531     fprintf_unfiltered (gdb_stderr, "Quit\n");
532   else
533     fprintf_unfiltered (gdb_stderr,
534              "Quit (expect signal SIGINT when the program is resumed)\n");
535   return_to_top_level (RETURN_QUIT);
536 }
537
538
539 #if defined(__GO32__)||defined(WINGDB)
540
541 /* In the absence of signals, poll keyboard for a quit.
542    Called from #define QUIT pollquit() in xm-go32.h. */
543
544 void
545 pollquit()
546 {
547   if (kbhit ())
548     {
549       int k = getkey ();
550       if (k == 1) {
551         quit_flag = 1;
552         quit();
553       }
554       else if (k == 2) {
555         immediate_quit = 1;
556         quit ();
557       }
558       else 
559         {
560           /* We just ignore it */
561           fprintf_unfiltered (gdb_stderr, "CTRL-A to quit, CTRL-B to quit harder\n");
562         }
563     }
564 }
565
566
567 #endif
568 #if defined(__GO32__)||defined(WINGDB)
569 void notice_quit()
570 {
571   if (kbhit ())
572     {
573       int k = getkey ();
574       if (k == 1) {
575         quit_flag = 1;
576       }
577       else if (k == 2)
578         {
579           immediate_quit = 1;
580         }
581       else 
582         {
583           fprintf_unfiltered (gdb_stderr, "CTRL-A to quit, CTRL-B to quit harder\n");
584         }
585     }
586 }
587 #else
588 void notice_quit()
589 {
590   /* Done by signals */
591 }
592 #endif
593 /* Control C comes here */
594
595 void
596 request_quit (signo)
597      int signo;
598 {
599   quit_flag = 1;
600   /* Restore the signal handler.  Harmless with BSD-style signals, needed
601      for System V-style signals.  So just always do it, rather than worrying
602      about USG defines and stuff like that.  */
603   signal (signo, request_quit);
604
605 /* start-sanitize-gm */
606 #ifdef GENERAL_MAGIC_HACKS
607   target_kill ();
608 #endif /* GENERAL_MAGIC_HACKS */
609 /* end-sanitize-gm */
610
611 #ifdef REQUEST_QUIT
612   REQUEST_QUIT;
613 #else
614   if (immediate_quit) 
615     quit ();
616 #endif
617 }
618
619 \f
620 /* Memory management stuff (malloc friends).  */
621
622 #if defined (NO_MMALLOC)
623
624 /* Make a substitute size_t for non-ANSI compilers. */
625
626 #ifdef _AIX
627 #include <stddef.h>
628 #else /* Not AIX */
629 #ifndef __STDC__
630 #ifndef size_t
631 #define size_t unsigned int
632 #endif
633 #endif
634 #endif /* Not AIX */
635
636 PTR
637 mmalloc (md, size)
638      PTR md;
639      size_t size;
640 {
641   return malloc (size);
642 }
643
644 PTR
645 mrealloc (md, ptr, size)
646      PTR md;
647      PTR ptr;
648      size_t size;
649 {
650   if (ptr == 0)         /* Guard against old realloc's */
651     return malloc (size);
652   else
653     return realloc (ptr, size);
654 }
655
656 void
657 mfree (md, ptr)
658      PTR md;
659      PTR ptr;
660 {
661   free (ptr);
662 }
663
664 #endif  /* NO_MMALLOC */
665
666 #if defined (NO_MMALLOC) || defined (NO_MMALLOC_CHECK)
667
668 void
669 init_malloc (md)
670      PTR md;
671 {
672 }
673
674 #else /* have mmalloc and want corruption checking  */
675
676 static void
677 malloc_botch ()
678 {
679   fatal_dump_core ("Memory corruption");
680 }
681
682 /* Attempt to install hooks in mmalloc/mrealloc/mfree for the heap specified
683    by MD, to detect memory corruption.  Note that MD may be NULL to specify
684    the default heap that grows via sbrk.
685
686    Note that for freshly created regions, we must call mmcheck prior to any
687    mallocs in the region.  Otherwise, any region which was allocated prior to
688    installing the checking hooks, which is later reallocated or freed, will
689    fail the checks!  The mmcheck function only allows initial hooks to be
690    installed before the first mmalloc.  However, anytime after we have called
691    mmcheck the first time to install the checking hooks, we can call it again
692    to update the function pointer to the memory corruption handler.
693
694    Returns zero on failure, non-zero on success. */
695
696 void
697 init_malloc (md)
698      PTR md;
699 {
700   if (!mmcheck (md, malloc_botch))
701     {
702       warning ("internal error: failed to install memory consistency checks");
703     }
704
705   mmtrace ();
706 }
707
708 #endif /* Have mmalloc and want corruption checking  */
709
710 /* Called when a memory allocation fails, with the number of bytes of
711    memory requested in SIZE. */
712
713 NORETURN void
714 nomem (size)
715      long size;
716 {
717   if (size > 0)
718     {
719       fatal ("virtual memory exhausted: can't allocate %ld bytes.", size);
720     }
721   else
722     {
723       fatal ("virtual memory exhausted.");
724     }
725 }
726
727 /* Like mmalloc but get error if no storage available, and protect against
728    the caller wanting to allocate zero bytes.  Whether to return NULL for
729    a zero byte request, or translate the request into a request for one
730    byte of zero'd storage, is a religious issue. */
731
732 PTR
733 xmmalloc (md, size)
734      PTR md;
735      long size;
736 {
737   register PTR val;
738
739   if (size == 0)
740     {
741       val = NULL;
742     }
743   else if ((val = mmalloc (md, size)) == NULL)
744     {
745       nomem (size);
746     }
747   return (val);
748 }
749
750 /* Like mrealloc but get error if no storage available.  */
751
752 PTR
753 xmrealloc (md, ptr, size)
754      PTR md;
755      PTR ptr;
756      long size;
757 {
758   register PTR val;
759
760   if (ptr != NULL)
761     {
762       val = mrealloc (md, ptr, size);
763     }
764   else
765     {
766       val = mmalloc (md, size);
767     }
768   if (val == NULL)
769     {
770       nomem (size);
771     }
772   return (val);
773 }
774
775 /* Like malloc but get error if no storage available, and protect against
776    the caller wanting to allocate zero bytes.  */
777
778 PTR
779 xmalloc (size)
780      long size;
781 {
782   return (xmmalloc ((PTR) NULL, size));
783 }
784
785 /* Like mrealloc but get error if no storage available.  */
786
787 PTR
788 xrealloc (ptr, size)
789      PTR ptr;
790      long size;
791 {
792   return (xmrealloc ((PTR) NULL, ptr, size));
793 }
794
795 \f
796 /* My replacement for the read system call.
797    Used like `read' but keeps going if `read' returns too soon.  */
798
799 int
800 myread (desc, addr, len)
801      int desc;
802      char *addr;
803      int len;
804 {
805   register int val;
806   int orglen = len;
807
808   while (len > 0)
809     {
810       val = read (desc, addr, len);
811       if (val < 0)
812         return val;
813       if (val == 0)
814         return orglen - len;
815       len -= val;
816       addr += val;
817     }
818   return orglen;
819 }
820 \f
821 /* Make a copy of the string at PTR with SIZE characters
822    (and add a null character at the end in the copy).
823    Uses malloc to get the space.  Returns the address of the copy.  */
824
825 char *
826 savestring (ptr, size)
827      const char *ptr;
828      int size;
829 {
830   register char *p = (char *) xmalloc (size + 1);
831   memcpy (p, ptr, size);
832   p[size] = 0;
833   return p;
834 }
835
836 char *
837 msavestring (md, ptr, size)
838      PTR md;
839      const char *ptr;
840      int size;
841 {
842   register char *p = (char *) xmmalloc (md, size + 1);
843   memcpy (p, ptr, size);
844   p[size] = 0;
845   return p;
846 }
847
848 /* The "const" is so it compiles under DGUX (which prototypes strsave
849    in <string.h>.  FIXME: This should be named "xstrsave", shouldn't it?
850    Doesn't real strsave return NULL if out of memory?  */
851 char *
852 strsave (ptr)
853      const char *ptr;
854 {
855   return savestring (ptr, strlen (ptr));
856 }
857
858 char *
859 mstrsave (md, ptr)
860      PTR md;
861      const char *ptr;
862 {
863   return (msavestring (md, ptr, strlen (ptr)));
864 }
865
866 void
867 print_spaces (n, file)
868      register int n;
869      register FILE *file;
870 {
871   while (n-- > 0)
872     fputc (' ', file);
873 }
874
875 /* Print a host address.  */
876
877 void
878 gdb_print_address (addr, stream)
879      PTR addr;
880      GDB_FILE *stream;
881 {
882
883   /* We could use the %p conversion specifier to fprintf if we had any
884      way of knowing whether this host supports it.  But the following
885      should work on the Alpha and on 32 bit machines.  */
886
887   fprintf_filtered (stream, "0x%lx", (unsigned long)addr);
888 }
889
890 /* Ask user a y-or-n question and return 1 iff answer is yes.
891    Takes three args which are given to printf to print the question.
892    The first, a control string, should end in "? ".
893    It should not say how to answer, because we do that.  */
894
895 /* VARARGS */
896 int
897 #ifdef ANSI_PROTOTYPES
898 query (char *ctlstr, ...)
899 #else
900 query (va_alist)
901      va_dcl
902 #endif
903 {
904   va_list args;
905   register int answer;
906   register int ans2;
907   int retval;
908
909 #ifdef ANSI_PROTOTYPES
910   va_start (args, ctlstr);
911 #else
912   char *ctlstr;
913   va_start (args);
914   ctlstr = va_arg (args, char *);
915 #endif
916
917   if (query_hook)
918     {
919       return query_hook (ctlstr, args);
920     }
921
922   /* Automatically answer "yes" if input is not from a terminal.  */
923   if (!input_from_terminal_p ())
924     return 1;
925 #ifdef MPW
926   /* FIXME Automatically answer "yes" if called from MacGDB.  */
927   if (mac_app)
928     return 1;
929 #endif /* MPW */
930
931   while (1)
932     {
933       wrap_here ("");           /* Flush any buffered output */
934       gdb_flush (gdb_stdout);
935
936       if (annotation_level > 1)
937         printf_filtered ("\n\032\032pre-query\n");
938
939       vfprintf_filtered (gdb_stdout, ctlstr, args);
940       printf_filtered ("(y or n) ");
941
942       if (annotation_level > 1)
943         printf_filtered ("\n\032\032query\n");
944
945 #ifdef MPW
946       /* If not in MacGDB, move to a new line so the entered line doesn't
947          have a prompt on the front of it. */
948       if (!mac_app)
949         fputs_unfiltered ("\n", gdb_stdout);
950 #endif /* MPW */
951
952       gdb_flush (gdb_stdout);
953       answer = fgetc (stdin);
954       clearerr (stdin);         /* in case of C-d */
955       if (answer == EOF)        /* C-d */
956         {
957           retval = 1;
958           break;
959         }
960       if (answer != '\n')       /* Eat rest of input line, to EOF or newline */
961         do 
962           {
963             ans2 = fgetc (stdin);
964             clearerr (stdin);
965           }
966         while (ans2 != EOF && ans2 != '\n');
967       if (answer >= 'a')
968         answer -= 040;
969       if (answer == 'Y')
970         {
971           retval = 1;
972           break;
973         }
974       if (answer == 'N')
975         {
976           retval = 0;
977           break;
978         }
979       printf_filtered ("Please answer y or n.\n");
980     }
981
982   if (annotation_level > 1)
983     printf_filtered ("\n\032\032post-query\n");
984   return retval;
985 }
986
987 \f
988 /* Parse a C escape sequence.  STRING_PTR points to a variable
989    containing a pointer to the string to parse.  That pointer
990    should point to the character after the \.  That pointer
991    is updated past the characters we use.  The value of the
992    escape sequence is returned.
993
994    A negative value means the sequence \ newline was seen,
995    which is supposed to be equivalent to nothing at all.
996
997    If \ is followed by a null character, we return a negative
998    value and leave the string pointer pointing at the null character.
999
1000    If \ is followed by 000, we return 0 and leave the string pointer
1001    after the zeros.  A value of 0 does not mean end of string.  */
1002
1003 int
1004 parse_escape (string_ptr)
1005      char **string_ptr;
1006 {
1007   register int c = *(*string_ptr)++;
1008   switch (c)
1009     {
1010     case 'a':
1011       return 007;               /* Bell (alert) char */
1012     case 'b':
1013       return '\b';
1014     case 'e':                   /* Escape character */
1015       return 033;
1016     case 'f':
1017       return '\f';
1018     case 'n':
1019       return '\n';
1020     case 'r':
1021       return '\r';
1022     case 't':
1023       return '\t';
1024     case 'v':
1025       return '\v';
1026     case '\n':
1027       return -2;
1028     case 0:
1029       (*string_ptr)--;
1030       return 0;
1031     case '^':
1032       c = *(*string_ptr)++;
1033       if (c == '\\')
1034         c = parse_escape (string_ptr);
1035       if (c == '?')
1036         return 0177;
1037       return (c & 0200) | (c & 037);
1038       
1039     case '0':
1040     case '1':
1041     case '2':
1042     case '3':
1043     case '4':
1044     case '5':
1045     case '6':
1046     case '7':
1047       {
1048         register int i = c - '0';
1049         register int count = 0;
1050         while (++count < 3)
1051           {
1052             if ((c = *(*string_ptr)++) >= '0' && c <= '7')
1053               {
1054                 i *= 8;
1055                 i += c - '0';
1056               }
1057             else
1058               {
1059                 (*string_ptr)--;
1060                 break;
1061               }
1062           }
1063         return i;
1064       }
1065     default:
1066       return c;
1067     }
1068 }
1069 \f
1070 /* Print the character C on STREAM as part of the contents of a literal
1071    string whose delimiter is QUOTER.  Note that this routine should only
1072    be call for printing things which are independent of the language
1073    of the program being debugged. */
1074
1075 void
1076 gdb_printchar (c, stream, quoter)
1077      register int c;
1078      FILE *stream;
1079      int quoter;
1080 {
1081
1082   c &= 0xFF;                    /* Avoid sign bit follies */
1083
1084   if (              c < 0x20  ||                /* Low control chars */ 
1085       (c >= 0x7F && c < 0xA0) ||                /* DEL, High controls */
1086       (sevenbit_strings && c >= 0x80)) {        /* high order bit set */
1087     switch (c)
1088       {
1089       case '\n':
1090         fputs_filtered ("\\n", stream);
1091         break;
1092       case '\b':
1093         fputs_filtered ("\\b", stream);
1094         break;
1095       case '\t':
1096         fputs_filtered ("\\t", stream);
1097         break;
1098       case '\f':
1099         fputs_filtered ("\\f", stream);
1100         break;
1101       case '\r':
1102         fputs_filtered ("\\r", stream);
1103         break;
1104       case '\033':
1105         fputs_filtered ("\\e", stream);
1106         break;
1107       case '\007':
1108         fputs_filtered ("\\a", stream);
1109         break;
1110       default:
1111         fprintf_filtered (stream, "\\%.3o", (unsigned int) c);
1112         break;
1113       }
1114   } else {
1115     if (c == '\\' || c == quoter)
1116       fputs_filtered ("\\", stream);
1117     fprintf_filtered (stream, "%c", c);
1118   }
1119 }
1120 \f
1121 /* Number of lines per page or UINT_MAX if paging is disabled.  */
1122 static unsigned int lines_per_page;
1123 /* Number of chars per line or UNIT_MAX is line folding is disabled.  */
1124 static unsigned int chars_per_line;
1125 /* Current count of lines printed on this page, chars on this line.  */
1126 static unsigned int lines_printed, chars_printed;
1127
1128 /* Buffer and start column of buffered text, for doing smarter word-
1129    wrapping.  When someone calls wrap_here(), we start buffering output
1130    that comes through fputs_filtered().  If we see a newline, we just
1131    spit it out and forget about the wrap_here().  If we see another
1132    wrap_here(), we spit it out and remember the newer one.  If we see
1133    the end of the line, we spit out a newline, the indent, and then
1134    the buffered output.  */
1135
1136 /* Malloc'd buffer with chars_per_line+2 bytes.  Contains characters which
1137    are waiting to be output (they have already been counted in chars_printed).
1138    When wrap_buffer[0] is null, the buffer is empty.  */
1139 static char *wrap_buffer;
1140
1141 /* Pointer in wrap_buffer to the next character to fill.  */
1142 static char *wrap_pointer;
1143
1144 /* String to indent by if the wrap occurs.  Must not be NULL if wrap_column
1145    is non-zero.  */
1146 static char *wrap_indent;
1147
1148 /* Column number on the screen where wrap_buffer begins, or 0 if wrapping
1149    is not in effect.  */
1150 static int wrap_column;
1151
1152 /* ARGSUSED */
1153 static void 
1154 set_width_command (args, from_tty, c)
1155      char *args;
1156      int from_tty;
1157      struct cmd_list_element *c;
1158 {
1159   if (!wrap_buffer)
1160     {
1161       wrap_buffer = (char *) xmalloc (chars_per_line + 2);
1162       wrap_buffer[0] = '\0';
1163     }
1164   else
1165     wrap_buffer = (char *) xrealloc (wrap_buffer, chars_per_line + 2);
1166   wrap_pointer = wrap_buffer;   /* Start it at the beginning */
1167 }
1168
1169 /* Wait, so the user can read what's on the screen.  Prompt the user
1170    to continue by pressing RETURN.  */
1171
1172 static void
1173 prompt_for_continue ()
1174 {
1175   char *ignore;
1176   char cont_prompt[120];
1177
1178   if (annotation_level > 1)
1179     printf_unfiltered ("\n\032\032pre-prompt-for-continue\n");
1180
1181   strcpy (cont_prompt,
1182           "---Type <return> to continue, or q <return> to quit---");
1183   if (annotation_level > 1)
1184     strcat (cont_prompt, "\n\032\032prompt-for-continue\n");
1185
1186   /* We must do this *before* we call gdb_readline, else it will eventually
1187      call us -- thinking that we're trying to print beyond the end of the 
1188      screen.  */
1189   reinitialize_more_filter ();
1190
1191   immediate_quit++;
1192   /* On a real operating system, the user can quit with SIGINT.
1193      But not on GO32.
1194
1195      'q' is provided on all systems so users don't have to change habits
1196      from system to system, and because telling them what to do in
1197      the prompt is more user-friendly than expecting them to think of
1198      SIGINT.  */
1199   /* Call readline, not gdb_readline, because GO32 readline handles control-C
1200      whereas control-C to gdb_readline will cause the user to get dumped
1201      out to DOS.  */
1202   ignore = readline (cont_prompt);
1203
1204   if (annotation_level > 1)
1205     printf_unfiltered ("\n\032\032post-prompt-for-continue\n");
1206
1207   if (ignore)
1208     {
1209       char *p = ignore;
1210       while (*p == ' ' || *p == '\t')
1211         ++p;
1212       if (p[0] == 'q')
1213         request_quit (SIGINT);
1214       free (ignore);
1215     }
1216   immediate_quit--;
1217
1218   /* Now we have to do this again, so that GDB will know that it doesn't
1219      need to save the ---Type <return>--- line at the top of the screen.  */
1220   reinitialize_more_filter ();
1221
1222   dont_repeat ();               /* Forget prev cmd -- CR won't repeat it. */
1223 }
1224
1225 /* Reinitialize filter; ie. tell it to reset to original values.  */
1226
1227 void
1228 reinitialize_more_filter ()
1229 {
1230   lines_printed = 0;
1231   chars_printed = 0;
1232 }
1233
1234 /* Indicate that if the next sequence of characters overflows the line,
1235    a newline should be inserted here rather than when it hits the end. 
1236    If INDENT is non-null, it is a string to be printed to indent the
1237    wrapped part on the next line.  INDENT must remain accessible until
1238    the next call to wrap_here() or until a newline is printed through
1239    fputs_filtered().
1240
1241    If the line is already overfull, we immediately print a newline and
1242    the indentation, and disable further wrapping.
1243
1244    If we don't know the width of lines, but we know the page height,
1245    we must not wrap words, but should still keep track of newlines
1246    that were explicitly printed.
1247
1248    INDENT should not contain tabs, as that will mess up the char count
1249    on the next line.  FIXME.
1250
1251    This routine is guaranteed to force out any output which has been
1252    squirreled away in the wrap_buffer, so wrap_here ((char *)0) can be
1253    used to force out output from the wrap_buffer.  */
1254
1255 void
1256 wrap_here(indent)
1257      char *indent;
1258 {
1259   /* This should have been allocated, but be paranoid anyway. */
1260   if (!wrap_buffer)
1261     abort ();
1262
1263   if (wrap_buffer[0])
1264     {
1265       *wrap_pointer = '\0';
1266       fputs_unfiltered (wrap_buffer, gdb_stdout);
1267     }
1268   wrap_pointer = wrap_buffer;
1269   wrap_buffer[0] = '\0';
1270   if (chars_per_line == UINT_MAX)               /* No line overflow checking */
1271     {
1272       wrap_column = 0;
1273     }
1274   else if (chars_printed >= chars_per_line)
1275     {
1276       puts_filtered ("\n");
1277       if (indent != NULL)
1278         puts_filtered (indent);
1279       wrap_column = 0;
1280     }
1281   else
1282     {
1283       wrap_column = chars_printed;
1284       if (indent == NULL)
1285         wrap_indent = "";
1286       else
1287         wrap_indent = indent;
1288     }
1289 }
1290
1291 /* Ensure that whatever gets printed next, using the filtered output
1292    commands, starts at the beginning of the line.  I.E. if there is
1293    any pending output for the current line, flush it and start a new
1294    line.  Otherwise do nothing. */
1295
1296 void
1297 begin_line ()
1298 {
1299   if (chars_printed > 0)
1300     {
1301       puts_filtered ("\n");
1302     }
1303 }
1304
1305
1306 GDB_FILE *
1307 gdb_fopen (name, mode)
1308      char * name;
1309      char * mode;
1310 {
1311   return fopen (name, mode);
1312 }
1313
1314 void
1315 gdb_flush (stream)
1316      FILE *stream;
1317 {
1318   if (flush_hook)
1319     {
1320       flush_hook (stream);
1321       return;
1322     }
1323
1324   fflush (stream);
1325 }
1326
1327 /* Like fputs but if FILTER is true, pause after every screenful.
1328
1329    Regardless of FILTER can wrap at points other than the final
1330    character of a line.
1331
1332    Unlike fputs, fputs_maybe_filtered does not return a value.
1333    It is OK for LINEBUFFER to be NULL, in which case just don't print
1334    anything.
1335
1336    Note that a longjmp to top level may occur in this routine (only if
1337    FILTER is true) (since prompt_for_continue may do so) so this
1338    routine should not be called when cleanups are not in place.  */
1339
1340 static void
1341 fputs_maybe_filtered (linebuffer, stream, filter)
1342      const char *linebuffer;
1343      FILE *stream;
1344      int filter;
1345 {
1346   const char *lineptr;
1347
1348   if (linebuffer == 0)
1349     return;
1350
1351   /* Don't do any filtering if it is disabled.  */
1352   if (stream != gdb_stdout
1353    || (lines_per_page == UINT_MAX && chars_per_line == UINT_MAX))
1354     {
1355       fputs_unfiltered (linebuffer, stream);
1356       return;
1357     }
1358
1359   /* Go through and output each character.  Show line extension
1360      when this is necessary; prompt user for new page when this is
1361      necessary.  */
1362   
1363   lineptr = linebuffer;
1364   while (*lineptr)
1365     {
1366       /* Possible new page.  */
1367       if (filter &&
1368           (lines_printed >= lines_per_page - 1))
1369         prompt_for_continue ();
1370
1371       while (*lineptr && *lineptr != '\n')
1372         {
1373           /* Print a single line.  */
1374           if (*lineptr == '\t')
1375             {
1376               if (wrap_column)
1377                 *wrap_pointer++ = '\t';
1378               else
1379                 fputc_unfiltered ('\t', stream);
1380               /* Shifting right by 3 produces the number of tab stops
1381                  we have already passed, and then adding one and
1382                  shifting left 3 advances to the next tab stop.  */
1383               chars_printed = ((chars_printed >> 3) + 1) << 3;
1384               lineptr++;
1385             }
1386           else
1387             {
1388               if (wrap_column)
1389                 *wrap_pointer++ = *lineptr;
1390               else
1391                 fputc_unfiltered (*lineptr, stream);
1392               chars_printed++;
1393               lineptr++;
1394             }
1395       
1396           if (chars_printed >= chars_per_line)
1397             {
1398               unsigned int save_chars = chars_printed;
1399
1400               chars_printed = 0;
1401               lines_printed++;
1402               /* If we aren't actually wrapping, don't output newline --
1403                  if chars_per_line is right, we probably just overflowed
1404                  anyway; if it's wrong, let us keep going.  */
1405               if (wrap_column)
1406                 fputc_unfiltered ('\n', stream);
1407
1408               /* Possible new page.  */
1409               if (lines_printed >= lines_per_page - 1)
1410                 prompt_for_continue ();
1411
1412               /* Now output indentation and wrapped string */
1413               if (wrap_column)
1414                 {
1415                   fputs_unfiltered (wrap_indent, stream);
1416                   *wrap_pointer = '\0'; /* Null-terminate saved stuff */
1417                   fputs_unfiltered (wrap_buffer, stream); /* and eject it */
1418                   /* FIXME, this strlen is what prevents wrap_indent from
1419                      containing tabs.  However, if we recurse to print it
1420                      and count its chars, we risk trouble if wrap_indent is
1421                      longer than (the user settable) chars_per_line. 
1422                      Note also that this can set chars_printed > chars_per_line
1423                      if we are printing a long string.  */
1424                   chars_printed = strlen (wrap_indent)
1425                                 + (save_chars - wrap_column);
1426                   wrap_pointer = wrap_buffer;   /* Reset buffer */
1427                   wrap_buffer[0] = '\0';
1428                   wrap_column = 0;              /* And disable fancy wrap */
1429                 }
1430             }
1431         }
1432
1433       if (*lineptr == '\n')
1434         {
1435           chars_printed = 0;
1436           wrap_here ((char *)0);  /* Spit out chars, cancel further wraps */
1437           lines_printed++;
1438           fputc_unfiltered ('\n', stream);
1439           lineptr++;
1440         }
1441     }
1442 }
1443
1444 void
1445 fputs_filtered (linebuffer, stream)
1446      const char *linebuffer;
1447      FILE *stream;
1448 {
1449   fputs_maybe_filtered (linebuffer, stream, 1);
1450 }
1451
1452 int
1453 putchar_unfiltered (c)
1454      int c;
1455 {
1456   char buf[2];
1457
1458   buf[0] = c;
1459   buf[1] = 0;
1460   fputs_unfiltered (buf, gdb_stdout);
1461   return c;
1462 }
1463
1464 int
1465 fputc_unfiltered (c, stream)
1466      int c;
1467      FILE * stream;
1468 {
1469   char buf[2];
1470
1471   buf[0] = c;
1472   buf[1] = 0;
1473   fputs_unfiltered (buf, stream);
1474   return c;
1475 }
1476
1477
1478 /* Print a variable number of ARGS using format FORMAT.  If this
1479    information is going to put the amount written (since the last call
1480    to REINITIALIZE_MORE_FILTER or the last page break) over the page size,
1481    call prompt_for_continue to get the users permision to continue.
1482
1483    Unlike fprintf, this function does not return a value.
1484
1485    We implement three variants, vfprintf (takes a vararg list and stream),
1486    fprintf (takes a stream to write on), and printf (the usual).
1487
1488    Note also that a longjmp to top level may occur in this routine
1489    (since prompt_for_continue may do so) so this routine should not be
1490    called when cleanups are not in place.  */
1491
1492 static void
1493 vfprintf_maybe_filtered (stream, format, args, filter)
1494      FILE *stream;
1495      char *format;
1496      va_list args;
1497      int filter;
1498 {
1499   char *linebuffer;
1500   struct cleanup *old_cleanups;
1501
1502   vasprintf (&linebuffer, format, args);
1503   if (linebuffer == NULL)
1504     {
1505       fputs_unfiltered ("\ngdb: virtual memory exhausted.\n", gdb_stderr);
1506       exit (1);
1507     }
1508   old_cleanups = make_cleanup (free, linebuffer);
1509   fputs_maybe_filtered (linebuffer, stream, filter);
1510   do_cleanups (old_cleanups);
1511 }
1512
1513
1514 void
1515 vfprintf_filtered (stream, format, args)
1516      FILE *stream;
1517      const char *format;
1518      va_list args;
1519 {
1520   vfprintf_maybe_filtered (stream, format, args, 1);
1521 }
1522
1523 void
1524 vfprintf_unfiltered (stream, format, args)
1525      FILE *stream;
1526      const char *format;
1527      va_list args;
1528 {
1529   char *linebuffer;
1530   struct cleanup *old_cleanups;
1531
1532   vasprintf (&linebuffer, format, args);
1533   if (linebuffer == NULL)
1534     {
1535       fputs_unfiltered ("\ngdb: virtual memory exhausted.\n", gdb_stderr);
1536       exit (1);
1537     }
1538   old_cleanups = make_cleanup (free, linebuffer);
1539   fputs_unfiltered (linebuffer, stream);
1540   do_cleanups (old_cleanups);
1541 }
1542
1543 void
1544 vprintf_filtered (format, args)
1545      const char *format;
1546      va_list args;
1547 {
1548   vfprintf_maybe_filtered (gdb_stdout, format, args, 1);
1549 }
1550
1551 void
1552 vprintf_unfiltered (format, args)
1553      const char *format;
1554      va_list args;
1555 {
1556   vfprintf_unfiltered (gdb_stdout, format, args);
1557 }
1558
1559 /* VARARGS */
1560 void
1561 #ifdef ANSI_PROTOTYPES
1562 fprintf_filtered (FILE *stream, const char *format, ...)
1563 #else
1564 fprintf_filtered (va_alist)
1565      va_dcl
1566 #endif
1567 {
1568   va_list args;
1569 #ifdef ANSI_PROTOTYPES
1570   va_start (args, format);
1571 #else
1572   FILE *stream;
1573   char *format;
1574
1575   va_start (args);
1576   stream = va_arg (args, FILE *);
1577   format = va_arg (args, char *);
1578 #endif
1579   vfprintf_filtered (stream, format, args);
1580   va_end (args);
1581 }
1582
1583 /* VARARGS */
1584 void
1585 #ifdef ANSI_PROTOTYPES
1586 fprintf_unfiltered (FILE *stream, const char *format, ...)
1587 #else
1588 fprintf_unfiltered (va_alist)
1589      va_dcl
1590 #endif
1591 {
1592   va_list args;
1593 #ifdef ANSI_PROTOTYPES
1594   va_start (args, format);
1595 #else
1596   FILE *stream;
1597   char *format;
1598
1599   va_start (args);
1600   stream = va_arg (args, FILE *);
1601   format = va_arg (args, char *);
1602 #endif
1603   vfprintf_unfiltered (stream, format, args);
1604   va_end (args);
1605 }
1606
1607 /* Like fprintf_filtered, but prints its result indented.
1608    Called as fprintfi_filtered (spaces, stream, format, ...);  */
1609
1610 /* VARARGS */
1611 void
1612 #ifdef ANSI_PROTOTYPES
1613 fprintfi_filtered (int spaces, FILE *stream, const char *format, ...)
1614 #else
1615 fprintfi_filtered (va_alist)
1616      va_dcl
1617 #endif
1618 {
1619   va_list args;
1620 #ifdef ANSI_PROTOTYPES
1621   va_start (args, format);
1622 #else
1623   int spaces;
1624   FILE *stream;
1625   char *format;
1626
1627   va_start (args);
1628   spaces = va_arg (args, int);
1629   stream = va_arg (args, FILE *);
1630   format = va_arg (args, char *);
1631 #endif
1632   print_spaces_filtered (spaces, stream);
1633
1634   vfprintf_filtered (stream, format, args);
1635   va_end (args);
1636 }
1637
1638
1639 /* VARARGS */
1640 void
1641 #ifdef ANSI_PROTOTYPES
1642 printf_filtered (const char *format, ...)
1643 #else
1644 printf_filtered (va_alist)
1645      va_dcl
1646 #endif
1647 {
1648   va_list args;
1649 #ifdef ANSI_PROTOTYPES
1650   va_start (args, format);
1651 #else
1652   char *format;
1653
1654   va_start (args);
1655   format = va_arg (args, char *);
1656 #endif
1657   vfprintf_filtered (gdb_stdout, format, args);
1658   va_end (args);
1659 }
1660
1661
1662 /* VARARGS */
1663 void
1664 #ifdef ANSI_PROTOTYPES
1665 printf_unfiltered (const char *format, ...)
1666 #else
1667 printf_unfiltered (va_alist)
1668      va_dcl
1669 #endif
1670 {
1671   va_list args;
1672 #ifdef ANSI_PROTOTYPES
1673   va_start (args, format);
1674 #else
1675   char *format;
1676
1677   va_start (args);
1678   format = va_arg (args, char *);
1679 #endif
1680   vfprintf_unfiltered (gdb_stdout, format, args);
1681   va_end (args);
1682 }
1683
1684 /* Like printf_filtered, but prints it's result indented.
1685    Called as printfi_filtered (spaces, format, ...);  */
1686
1687 /* VARARGS */
1688 void
1689 #ifdef ANSI_PROTOTYPES
1690 printfi_filtered (int spaces, const char *format, ...)
1691 #else
1692 printfi_filtered (va_alist)
1693      va_dcl
1694 #endif
1695 {
1696   va_list args;
1697 #ifdef ANSI_PROTOTYPES
1698   va_start (args, format);
1699 #else
1700   int spaces;
1701   char *format;
1702
1703   va_start (args);
1704   spaces = va_arg (args, int);
1705   format = va_arg (args, char *);
1706 #endif
1707   print_spaces_filtered (spaces, gdb_stdout);
1708   vfprintf_filtered (gdb_stdout, format, args);
1709   va_end (args);
1710 }
1711
1712 /* Easy -- but watch out!
1713
1714    This routine is *not* a replacement for puts()!  puts() appends a newline.
1715    This one doesn't, and had better not!  */
1716
1717 void
1718 puts_filtered (string)
1719      const char *string;
1720 {
1721   fputs_filtered (string, gdb_stdout);
1722 }
1723
1724 void
1725 puts_unfiltered (string)
1726      const char *string;
1727 {
1728   fputs_unfiltered (string, gdb_stdout);
1729 }
1730
1731 /* Return a pointer to N spaces and a null.  The pointer is good
1732    until the next call to here.  */
1733 char *
1734 n_spaces (n)
1735      int n;
1736 {
1737   register char *t;
1738   static char *spaces;
1739   static int max_spaces;
1740
1741   if (n > max_spaces)
1742     {
1743       if (spaces)
1744         free (spaces);
1745       spaces = (char *) xmalloc (n+1);
1746       for (t = spaces+n; t != spaces;)
1747         *--t = ' ';
1748       spaces[n] = '\0';
1749       max_spaces = n;
1750     }
1751
1752   return spaces + max_spaces - n;
1753 }
1754
1755 /* Print N spaces.  */
1756 void
1757 print_spaces_filtered (n, stream)
1758      int n;
1759      FILE *stream;
1760 {
1761   fputs_filtered (n_spaces (n), stream);
1762 }
1763 \f
1764 /* C++ demangler stuff.  */
1765
1766 /* fprintf_symbol_filtered attempts to demangle NAME, a symbol in language
1767    LANG, using demangling args ARG_MODE, and print it filtered to STREAM.
1768    If the name is not mangled, or the language for the name is unknown, or
1769    demangling is off, the name is printed in its "raw" form. */
1770
1771 void
1772 fprintf_symbol_filtered (stream, name, lang, arg_mode)
1773      FILE *stream;
1774      char *name;
1775      enum language lang;
1776      int arg_mode;
1777 {
1778   char *demangled;
1779
1780   if (name != NULL)
1781     {
1782       /* If user wants to see raw output, no problem.  */
1783       if (!demangle)
1784         {
1785           fputs_filtered (name, stream);
1786         }
1787       else
1788         {
1789           switch (lang)
1790             {
1791             case language_cplus:
1792               demangled = cplus_demangle (name, arg_mode);
1793               break;
1794             case language_chill:
1795               demangled = chill_demangle (name);
1796               break;
1797             default:
1798               demangled = NULL;
1799               break;
1800             }
1801           fputs_filtered (demangled ? demangled : name, stream);
1802           if (demangled != NULL)
1803             {
1804               free (demangled);
1805             }
1806         }
1807     }
1808 }
1809
1810 /* Do a strcmp() type operation on STRING1 and STRING2, ignoring any
1811    differences in whitespace.  Returns 0 if they match, non-zero if they
1812    don't (slightly different than strcmp()'s range of return values).
1813    
1814    As an extra hack, string1=="FOO(ARGS)" matches string2=="FOO".
1815    This "feature" is useful when searching for matching C++ function names
1816    (such as if the user types 'break FOO', where FOO is a mangled C++
1817    function). */
1818
1819 int
1820 strcmp_iw (string1, string2)
1821      const char *string1;
1822      const char *string2;
1823 {
1824   while ((*string1 != '\0') && (*string2 != '\0'))
1825     {
1826       while (isspace (*string1))
1827         {
1828           string1++;
1829         }
1830       while (isspace (*string2))
1831         {
1832           string2++;
1833         }
1834       if (*string1 != *string2)
1835         {
1836           break;
1837         }
1838       if (*string1 != '\0')
1839         {
1840           string1++;
1841           string2++;
1842         }
1843     }
1844   return (*string1 != '\0' && *string1 != '(') || (*string2 != '\0');
1845 }
1846
1847 \f
1848 void
1849 initialize_utils ()
1850 {
1851   struct cmd_list_element *c;
1852
1853   c = add_set_cmd ("width", class_support, var_uinteger, 
1854                   (char *)&chars_per_line,
1855                   "Set number of characters gdb thinks are in a line.",
1856                   &setlist);
1857   add_show_from_set (c, &showlist);
1858   c->function.sfunc = set_width_command;
1859
1860   add_show_from_set
1861     (add_set_cmd ("height", class_support,
1862                   var_uinteger, (char *)&lines_per_page,
1863                   "Set number of lines gdb thinks are in a page.", &setlist),
1864      &showlist);
1865   
1866   /* These defaults will be used if we are unable to get the correct
1867      values from termcap.  */
1868 #if defined(__GO32__) || defined(__WIN32__)
1869   lines_per_page = ScreenRows();
1870   chars_per_line = ScreenCols();
1871 #else  
1872   lines_per_page = 24;
1873   chars_per_line = 80;
1874
1875 #ifndef MPW
1876   /* No termcap under MPW, although might be cool to do something
1877      by looking at worksheet or console window sizes. */
1878   /* Initialize the screen height and width from termcap.  */
1879   {
1880     char *termtype = getenv ("TERM");
1881
1882     /* Positive means success, nonpositive means failure.  */
1883     int status;
1884
1885     /* 2048 is large enough for all known terminals, according to the
1886        GNU termcap manual.  */
1887     char term_buffer[2048];
1888
1889     if (termtype)
1890       {
1891         status = tgetent (term_buffer, termtype);
1892         if (status > 0)
1893           {
1894             int val;
1895             
1896             val = tgetnum ("li");
1897             if (val >= 0)
1898               lines_per_page = val;
1899             else
1900               /* The number of lines per page is not mentioned
1901                  in the terminal description.  This probably means
1902                  that paging is not useful (e.g. emacs shell window),
1903                  so disable paging.  */
1904               lines_per_page = UINT_MAX;
1905             
1906             val = tgetnum ("co");
1907             if (val >= 0)
1908               chars_per_line = val;
1909           }
1910       }
1911   }
1912 #endif /* MPW */
1913
1914 #if defined(SIGWINCH) && defined(SIGWINCH_HANDLER)
1915
1916   /* If there is a better way to determine the window size, use it. */
1917   SIGWINCH_HANDLER ();
1918 #endif
1919 #endif
1920   /* If the output is not a terminal, don't paginate it.  */
1921   if (!ISATTY (gdb_stdout))
1922     lines_per_page = UINT_MAX;
1923
1924   set_width_command ((char *)NULL, 0, c);
1925
1926   add_show_from_set
1927     (add_set_cmd ("demangle", class_support, var_boolean, 
1928                   (char *)&demangle,
1929                 "Set demangling of encoded C++ names when displaying symbols.",
1930                   &setprintlist),
1931      &showprintlist);
1932
1933   add_show_from_set
1934     (add_set_cmd ("sevenbit-strings", class_support, var_boolean, 
1935                   (char *)&sevenbit_strings,
1936    "Set printing of 8-bit characters in strings as \\nnn.",
1937                   &setprintlist),
1938      &showprintlist);
1939
1940   add_show_from_set
1941     (add_set_cmd ("asm-demangle", class_support, var_boolean, 
1942                   (char *)&asm_demangle,
1943         "Set demangling of C++ names in disassembly listings.",
1944                   &setprintlist),
1945      &showprintlist);
1946 }
1947
1948 /* Machine specific function to handle SIGWINCH signal. */
1949
1950 #ifdef  SIGWINCH_HANDLER_BODY
1951         SIGWINCH_HANDLER_BODY
1952 #endif
1953