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