import gdb-1999-07-07 post reformat
[external/binutils.git] / gdb / utils.c
1 /* General utility routines for GDB, the GNU debugger.
2    Copyright 1986, 89, 90, 91, 92, 95, 96, 1998 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,
19    Boston, MA 02111-1307, USA.  */
20
21 #include "defs.h"
22 #include <ctype.h>
23 #include "gdb_string.h"
24 #ifdef HAVE_UNISTD_H
25 #include <unistd.h>
26 #endif
27
28 #ifdef HAVE_CURSES_H
29 #include <curses.h>
30 #endif
31 #ifdef HAVE_TERM_H
32 #include <term.h>
33 #endif
34
35 /* SunOS's curses.h has a '#define reg register' in it.  Thank you Sun. */
36 #ifdef reg
37 #undef reg
38 #endif
39
40 #include "signals.h"
41 #include "gdbcmd.h"
42 #include "serial.h"
43 #include "bfd.h"
44 #include "target.h"
45 #include "demangle.h"
46 #include "expression.h"
47 #include "language.h"
48 #include "annotate.h"
49
50 #include <readline/readline.h>
51
52 /* readline defines this.  */
53 #undef savestring
54
55 void (*error_begin_hook) PARAMS ((void));
56
57 /* Prototypes for local functions */
58
59 static void vfprintf_maybe_filtered PARAMS ((GDB_FILE *, const char *,
60                                              va_list, int));
61
62 static void fputs_maybe_filtered PARAMS ((const char *, GDB_FILE *, int));
63
64 #if defined (USE_MMALLOC) && !defined (NO_MMCHECK)
65 static void malloc_botch PARAMS ((void));
66 #endif
67
68 static void
69 fatal_dump_core PARAMS ((char *,...));
70
71 static void
72 prompt_for_continue PARAMS ((void));
73
74 static void
75 set_width_command PARAMS ((char *, int, struct cmd_list_element *));
76
77 static void
78 set_width PARAMS ((void));
79
80 /* If this definition isn't overridden by the header files, assume
81    that isatty and fileno exist on this system.  */
82 #ifndef ISATTY
83 #define ISATTY(FP)      (isatty (fileno (FP)))
84 #endif
85
86 #ifndef GDB_FILE_ISATTY
87 #define GDB_FILE_ISATTY(GDB_FILE_PTR)   (gdb_file_isatty(GDB_FILE_PTR))
88 #endif
89
90 /* Chain of cleanup actions established with make_cleanup,
91    to be executed if an error happens.  */
92
93 static struct cleanup *cleanup_chain;   /* cleaned up after a failed command */
94 static struct cleanup *final_cleanup_chain;     /* cleaned up when gdb exits */
95 static struct cleanup *run_cleanup_chain;       /* cleaned up on each 'run' */
96 static struct cleanup *exec_cleanup_chain;      /* cleaned up on each execution command */
97
98 /* Pointer to what is left to do for an execution command after the
99    target stops. Used only in asynchronous mode, by targets that
100    support async execution.  The finish and until commands use it. So
101    does the target extended-remote command. */
102 struct continuation *cmd_continuation;
103
104 /* Nonzero if we have job control. */
105
106 int job_control;
107
108 /* Nonzero means a quit has been requested.  */
109
110 int quit_flag;
111
112 /* Nonzero means quit immediately if Control-C is typed now, rather
113    than waiting until QUIT is executed.  Be careful in setting this;
114    code which executes with immediate_quit set has to be very careful
115    about being able to deal with being interrupted at any time.  It is
116    almost always better to use QUIT; the only exception I can think of
117    is being able to quit out of a system call (using EINTR loses if
118    the SIGINT happens between the previous QUIT and the system call).
119    To immediately quit in the case in which a SIGINT happens between
120    the previous QUIT and setting immediate_quit (desirable anytime we
121    expect to block), call QUIT after setting immediate_quit.  */
122
123 int immediate_quit;
124
125 /* Nonzero means that encoded C++ names should be printed out in their
126    C++ form rather than raw.  */
127
128 int demangle = 1;
129
130 /* Nonzero means that encoded C++ names should be printed out in their
131    C++ form even in assembler language displays.  If this is set, but
132    DEMANGLE is zero, names are printed raw, i.e. DEMANGLE controls.  */
133
134 int asm_demangle = 0;
135
136 /* Nonzero means that strings with character values >0x7F should be printed
137    as octal escapes.  Zero means just print the value (e.g. it's an
138    international character, and the terminal or window can cope.)  */
139
140 int sevenbit_strings = 0;
141
142 /* String to be printed before error messages, if any.  */
143
144 char *error_pre_print;
145
146 /* String to be printed before quit messages, if any.  */
147
148 char *quit_pre_print;
149
150 /* String to be printed before warning messages, if any.  */
151
152 char *warning_pre_print = "\nwarning: ";
153
154 int pagination_enabled = 1;
155 \f
156
157 /* Add a new cleanup to the cleanup_chain,
158    and return the previous chain pointer
159    to be passed later to do_cleanups or discard_cleanups.
160    Args are FUNCTION to clean up with, and ARG to pass to it.  */
161
162 struct cleanup *
163 make_cleanup (function, arg)
164      void (*function) PARAMS ((PTR));
165      PTR arg;
166 {
167   return make_my_cleanup (&cleanup_chain, function, arg);
168 }
169
170 struct cleanup *
171 make_final_cleanup (function, arg)
172      void (*function) PARAMS ((PTR));
173      PTR arg;
174 {
175   return make_my_cleanup (&final_cleanup_chain, function, arg);
176 }
177
178 struct cleanup *
179 make_run_cleanup (function, arg)
180      void (*function) PARAMS ((PTR));
181      PTR arg;
182 {
183   return make_my_cleanup (&run_cleanup_chain, function, arg);
184 }
185
186 struct cleanup *
187 make_exec_cleanup (function, arg)
188      void (*function) PARAMS ((PTR));
189      PTR arg;
190 {
191   return make_my_cleanup (&exec_cleanup_chain, function, arg);
192 }
193
194 static void
195 do_freeargv (arg)
196      void *arg;
197 {
198   freeargv ((char **) arg);
199 }
200
201 struct cleanup *
202 make_cleanup_freeargv (arg)
203      char **arg;
204 {
205   return make_my_cleanup (&cleanup_chain, do_freeargv, arg);
206 }
207
208 struct cleanup *
209 make_my_cleanup (pmy_chain, function, arg)
210      struct cleanup **pmy_chain;
211      void (*function) PARAMS ((PTR));
212      PTR arg;
213 {
214   register struct cleanup *new
215   = (struct cleanup *) xmalloc (sizeof (struct cleanup));
216   register struct cleanup *old_chain = *pmy_chain;
217
218   new->next = *pmy_chain;
219   new->function = function;
220   new->arg = arg;
221   *pmy_chain = new;
222
223   return old_chain;
224 }
225
226 /* Discard cleanups and do the actions they describe
227    until we get back to the point OLD_CHAIN in the cleanup_chain.  */
228
229 void
230 do_cleanups (old_chain)
231      register struct cleanup *old_chain;
232 {
233   do_my_cleanups (&cleanup_chain, old_chain);
234 }
235
236 void
237 do_final_cleanups (old_chain)
238      register struct cleanup *old_chain;
239 {
240   do_my_cleanups (&final_cleanup_chain, old_chain);
241 }
242
243 void
244 do_run_cleanups (old_chain)
245      register struct cleanup *old_chain;
246 {
247   do_my_cleanups (&run_cleanup_chain, old_chain);
248 }
249
250 void
251 do_exec_cleanups (old_chain)
252      register struct cleanup *old_chain;
253 {
254   do_my_cleanups (&exec_cleanup_chain, old_chain);
255 }
256
257 void
258 do_my_cleanups (pmy_chain, old_chain)
259      register struct cleanup **pmy_chain;
260      register struct cleanup *old_chain;
261 {
262   register struct cleanup *ptr;
263   while ((ptr = *pmy_chain) != old_chain)
264     {
265       *pmy_chain = ptr->next;   /* Do this first incase recursion */
266       (*ptr->function) (ptr->arg);
267       free (ptr);
268     }
269 }
270
271 /* Discard cleanups, not doing the actions they describe,
272    until we get back to the point OLD_CHAIN in the cleanup_chain.  */
273
274 void
275 discard_cleanups (old_chain)
276      register struct cleanup *old_chain;
277 {
278   discard_my_cleanups (&cleanup_chain, old_chain);
279 }
280
281 void
282 discard_final_cleanups (old_chain)
283      register struct cleanup *old_chain;
284 {
285   discard_my_cleanups (&final_cleanup_chain, old_chain);
286 }
287
288 void
289 discard_my_cleanups (pmy_chain, old_chain)
290      register struct cleanup **pmy_chain;
291      register struct cleanup *old_chain;
292 {
293   register struct cleanup *ptr;
294   while ((ptr = *pmy_chain) != old_chain)
295     {
296       *pmy_chain = ptr->next;
297       free ((PTR) ptr);
298     }
299 }
300
301 /* Set the cleanup_chain to 0, and return the old cleanup chain.  */
302 struct cleanup *
303 save_cleanups ()
304 {
305   return save_my_cleanups (&cleanup_chain);
306 }
307
308 struct cleanup *
309 save_final_cleanups ()
310 {
311   return save_my_cleanups (&final_cleanup_chain);
312 }
313
314 struct cleanup *
315 save_my_cleanups (pmy_chain)
316      struct cleanup **pmy_chain;
317 {
318   struct cleanup *old_chain = *pmy_chain;
319
320   *pmy_chain = 0;
321   return old_chain;
322 }
323
324 /* Restore the cleanup chain from a previously saved chain.  */
325 void
326 restore_cleanups (chain)
327      struct cleanup *chain;
328 {
329   restore_my_cleanups (&cleanup_chain, chain);
330 }
331
332 void
333 restore_final_cleanups (chain)
334      struct cleanup *chain;
335 {
336   restore_my_cleanups (&final_cleanup_chain, chain);
337 }
338
339 void
340 restore_my_cleanups (pmy_chain, chain)
341      struct cleanup **pmy_chain;
342      struct cleanup *chain;
343 {
344   *pmy_chain = chain;
345 }
346
347 /* This function is useful for cleanups.
348    Do
349
350    foo = xmalloc (...);
351    old_chain = make_cleanup (free_current_contents, &foo);
352
353    to arrange to free the object thus allocated.  */
354
355 void
356 free_current_contents (location)
357      char **location;
358 {
359   free (*location);
360 }
361
362 /* Provide a known function that does nothing, to use as a base for
363    for a possibly long chain of cleanups.  This is useful where we
364    use the cleanup chain for handling normal cleanups as well as dealing
365    with cleanups that need to be done as a result of a call to error().
366    In such cases, we may not be certain where the first cleanup is, unless
367    we have a do-nothing one to always use as the base. */
368
369 /* ARGSUSED */
370 void
371 null_cleanup (arg)
372      PTR arg;
373 {
374 }
375
376 /* Add a continuation to the continuation list, the gloabl list
377    cmd_continuation. */
378 void
379 add_continuation (continuation_hook, arg_list)
380      void (*continuation_hook) PARAMS ((struct continuation_arg *));
381      struct continuation_arg *arg_list;
382 {
383   struct continuation *continuation_ptr;
384
385   continuation_ptr = (struct continuation *) xmalloc (sizeof (struct continuation));
386   continuation_ptr->continuation_hook = continuation_hook;
387   continuation_ptr->arg_list = arg_list;
388   continuation_ptr->next = cmd_continuation;
389   cmd_continuation = continuation_ptr;
390 }
391
392 /* Walk down the cmd_continuation list, and execute all the
393    continuations. */
394 void
395 do_all_continuations ()
396 {
397   struct continuation *continuation_ptr;
398
399   while (cmd_continuation)
400     {
401       (cmd_continuation->continuation_hook) (cmd_continuation->arg_list);
402       continuation_ptr = cmd_continuation;
403       cmd_continuation = continuation_ptr->next;
404       free (continuation_ptr);
405     }
406 }
407 \f
408
409 /* Print a warning message.  Way to use this is to call warning_begin,
410    output the warning message (use unfiltered output to gdb_stderr),
411    ending in a newline.  There is not currently a warning_end that you
412    call afterwards, but such a thing might be added if it is useful
413    for a GUI to separate warning messages from other output.
414
415    FIXME: Why do warnings use unfiltered output and errors filtered?
416    Is this anything other than a historical accident?  */
417
418 void
419 warning_begin ()
420 {
421   target_terminal_ours ();
422   wrap_here ("");               /* Force out any buffered output */
423   gdb_flush (gdb_stdout);
424   if (warning_pre_print)
425     fprintf_unfiltered (gdb_stderr, warning_pre_print);
426 }
427
428 /* Print a warning message.
429    The first argument STRING is the warning message, used as a fprintf string,
430    and the remaining args are passed as arguments to it.
431    The primary difference between warnings and errors is that a warning
432    does not force the return to command level.  */
433
434 /* VARARGS */
435 void
436 #ifdef ANSI_PROTOTYPES
437 warning (const char *string,...)
438 #else
439 warning (va_alist)
440      va_dcl
441 #endif
442 {
443   va_list args;
444 #ifdef ANSI_PROTOTYPES
445   va_start (args, string);
446 #else
447   char *string;
448
449   va_start (args);
450   string = va_arg (args, char *);
451 #endif
452   if (warning_hook)
453     (*warning_hook) (string, args);
454   else
455     {
456       warning_begin ();
457       vfprintf_unfiltered (gdb_stderr, string, args);
458       fprintf_unfiltered (gdb_stderr, "\n");
459       va_end (args);
460     }
461 }
462
463 /* Start the printing of an error message.  Way to use this is to call
464    this, output the error message (use filtered output to gdb_stderr
465    (FIXME: Some callers, like memory_error, use gdb_stdout)), ending
466    in a newline, and then call return_to_top_level (RETURN_ERROR).
467    error() provides a convenient way to do this for the special case
468    that the error message can be formatted with a single printf call,
469    but this is more general.  */
470 void
471 error_begin ()
472 {
473   if (error_begin_hook)
474     error_begin_hook ();
475
476   target_terminal_ours ();
477   wrap_here ("");               /* Force out any buffered output */
478   gdb_flush (gdb_stdout);
479
480   annotate_error_begin ();
481
482   if (error_pre_print)
483     fprintf_filtered (gdb_stderr, error_pre_print);
484 }
485
486 /* Print an error message and return to command level.
487    The first argument STRING is the error message, used as a fprintf string,
488    and the remaining args are passed as arguments to it.  */
489
490 /* VARARGS */
491 NORETURN void
492 #ifdef ANSI_PROTOTYPES
493 error (const char *string,...)
494 #else
495 error (va_alist)
496      va_dcl
497 #endif
498 {
499   va_list args;
500 #ifdef ANSI_PROTOTYPES
501   va_start (args, string);
502 #else
503   va_start (args);
504 #endif
505   if (error_hook)
506     (*error_hook) ();
507   else
508     {
509       error_begin ();
510 #ifdef ANSI_PROTOTYPES
511       vfprintf_filtered (gdb_stderr, string, args);
512 #else
513       {
514         char *string1;
515
516         string1 = va_arg (args, char *);
517         vfprintf_filtered (gdb_stderr, string1, args);
518       }
519 #endif
520       fprintf_filtered (gdb_stderr, "\n");
521       va_end (args);
522       return_to_top_level (RETURN_ERROR);
523     }
524 }
525
526
527 /* Print an error message and exit reporting failure.
528    This is for a error that we cannot continue from.
529    The arguments are printed a la printf.
530
531    This function cannot be declared volatile (NORETURN) in an
532    ANSI environment because exit() is not declared volatile. */
533
534 /* VARARGS */
535 NORETURN void
536 #ifdef ANSI_PROTOTYPES
537 fatal (char *string,...)
538 #else
539 fatal (va_alist)
540      va_dcl
541 #endif
542 {
543   va_list args;
544 #ifdef ANSI_PROTOTYPES
545   va_start (args, string);
546 #else
547   char *string;
548   va_start (args);
549   string = va_arg (args, char *);
550 #endif
551   fprintf_unfiltered (gdb_stderr, "\ngdb: ");
552   vfprintf_unfiltered (gdb_stderr, string, args);
553   fprintf_unfiltered (gdb_stderr, "\n");
554   va_end (args);
555   exit (1);
556 }
557
558 /* Print an error message and exit, dumping core.
559    The arguments are printed a la printf ().  */
560
561 /* VARARGS */
562 static void
563 #ifdef ANSI_PROTOTYPES
564 fatal_dump_core (char *string,...)
565 #else
566 fatal_dump_core (va_alist)
567      va_dcl
568 #endif
569 {
570   va_list args;
571 #ifdef ANSI_PROTOTYPES
572   va_start (args, string);
573 #else
574   char *string;
575
576   va_start (args);
577   string = va_arg (args, char *);
578 #endif
579   /* "internal error" is always correct, since GDB should never dump
580      core, no matter what the input.  */
581   fprintf_unfiltered (gdb_stderr, "\ngdb internal error: ");
582   vfprintf_unfiltered (gdb_stderr, string, args);
583   fprintf_unfiltered (gdb_stderr, "\n");
584   va_end (args);
585
586   signal (SIGQUIT, SIG_DFL);
587   kill (getpid (), SIGQUIT);
588   /* We should never get here, but just in case...  */
589   exit (1);
590 }
591
592 /* The strerror() function can return NULL for errno values that are
593    out of range.  Provide a "safe" version that always returns a
594    printable string. */
595
596 char *
597 safe_strerror (errnum)
598      int errnum;
599 {
600   char *msg;
601   static char buf[32];
602
603   if ((msg = strerror (errnum)) == NULL)
604     {
605       sprintf (buf, "(undocumented errno %d)", errnum);
606       msg = buf;
607     }
608   return (msg);
609 }
610
611 /* The strsignal() function can return NULL for signal values that are
612    out of range.  Provide a "safe" version that always returns a
613    printable string. */
614
615 char *
616 safe_strsignal (signo)
617      int signo;
618 {
619   char *msg;
620   static char buf[32];
621
622   if ((msg = strsignal (signo)) == NULL)
623     {
624       sprintf (buf, "(undocumented signal %d)", signo);
625       msg = buf;
626     }
627   return (msg);
628 }
629
630
631 /* Print the system error message for errno, and also mention STRING
632    as the file name for which the error was encountered.
633    Then return to command level.  */
634
635 NORETURN void
636 perror_with_name (string)
637      char *string;
638 {
639   char *err;
640   char *combined;
641
642   err = safe_strerror (errno);
643   combined = (char *) alloca (strlen (err) + strlen (string) + 3);
644   strcpy (combined, string);
645   strcat (combined, ": ");
646   strcat (combined, err);
647
648   /* I understand setting these is a matter of taste.  Still, some people
649      may clear errno but not know about bfd_error.  Doing this here is not
650      unreasonable. */
651   bfd_set_error (bfd_error_no_error);
652   errno = 0;
653
654   error ("%s.", combined);
655 }
656
657 /* Print the system error message for ERRCODE, and also mention STRING
658    as the file name for which the error was encountered.  */
659
660 void
661 print_sys_errmsg (string, errcode)
662      char *string;
663      int errcode;
664 {
665   char *err;
666   char *combined;
667
668   err = safe_strerror (errcode);
669   combined = (char *) alloca (strlen (err) + strlen (string) + 3);
670   strcpy (combined, string);
671   strcat (combined, ": ");
672   strcat (combined, err);
673
674   /* We want anything which was printed on stdout to come out first, before
675      this message.  */
676   gdb_flush (gdb_stdout);
677   fprintf_unfiltered (gdb_stderr, "%s.\n", combined);
678 }
679
680 /* Control C eventually causes this to be called, at a convenient time.  */
681
682 void
683 quit ()
684 {
685   serial_t gdb_stdout_serial = serial_fdopen (1);
686
687   target_terminal_ours ();
688
689   /* We want all output to appear now, before we print "Quit".  We
690      have 3 levels of buffering we have to flush (it's possible that
691      some of these should be changed to flush the lower-level ones
692      too):  */
693
694   /* 1.  The _filtered buffer.  */
695   wrap_here ((char *) 0);
696
697   /* 2.  The stdio buffer.  */
698   gdb_flush (gdb_stdout);
699   gdb_flush (gdb_stderr);
700
701   /* 3.  The system-level buffer.  */
702   SERIAL_DRAIN_OUTPUT (gdb_stdout_serial);
703   SERIAL_UN_FDOPEN (gdb_stdout_serial);
704
705   annotate_error_begin ();
706
707   /* Don't use *_filtered; we don't want to prompt the user to continue.  */
708   if (quit_pre_print)
709     fprintf_unfiltered (gdb_stderr, quit_pre_print);
710
711   if (job_control
712   /* If there is no terminal switching for this target, then we can't
713      possibly get screwed by the lack of job control.  */
714       || current_target.to_terminal_ours == NULL)
715     fprintf_unfiltered (gdb_stderr, "Quit\n");
716   else
717     fprintf_unfiltered (gdb_stderr,
718                "Quit (expect signal SIGINT when the program is resumed)\n");
719   return_to_top_level (RETURN_QUIT);
720 }
721
722
723 #if defined(__GO32__)
724
725 /* In the absence of signals, poll keyboard for a quit.
726    Called from #define QUIT pollquit() in xm-go32.h. */
727
728 void
729 notice_quit ()
730 {
731   if (kbhit ())
732     switch (getkey ())
733       {
734       case 1:
735         quit_flag = 1;
736         break;
737       case 2:
738         immediate_quit = 2;
739         break;
740       default:
741         /* We just ignore it */
742         /* FIXME!! Don't think this actually works! */
743         fprintf_unfiltered (gdb_stderr, "CTRL-A to quit, CTRL-B to quit harder\n");
744         break;
745       }
746 }
747
748 #elif defined(_MSC_VER)         /* should test for wingdb instead? */
749
750 /*
751  * Windows translates all keyboard and mouse events 
752  * into a message which is appended to the message 
753  * queue for the process.
754  */
755
756 void
757 notice_quit ()
758 {
759   int k = win32pollquit ();
760   if (k == 1)
761     quit_flag = 1;
762   else if (k == 2)
763     immediate_quit = 1;
764 }
765
766 #else /* !defined(__GO32__) && !defined(_MSC_VER) */
767
768 void
769 notice_quit ()
770 {
771   /* Done by signals */
772 }
773
774 #endif /* !defined(__GO32__) && !defined(_MSC_VER) */
775
776 /* Control C comes here */
777 void
778 request_quit (signo)
779      int signo;
780 {
781   quit_flag = 1;
782   /* Restore the signal handler.  Harmless with BSD-style signals, needed
783      for System V-style signals.  So just always do it, rather than worrying
784      about USG defines and stuff like that.  */
785   signal (signo, request_quit);
786
787 #ifdef REQUEST_QUIT
788   REQUEST_QUIT;
789 #else
790   if (immediate_quit)
791     quit ();
792 #endif
793 }
794 \f
795 /* Memory management stuff (malloc friends).  */
796
797 /* Make a substitute size_t for non-ANSI compilers. */
798
799 #ifndef HAVE_STDDEF_H
800 #ifndef size_t
801 #define size_t unsigned int
802 #endif
803 #endif
804
805 #if !defined (USE_MMALLOC)
806
807 PTR
808 mmalloc (md, size)
809      PTR md;
810      size_t size;
811 {
812   return malloc (size);
813 }
814
815 PTR
816 mrealloc (md, ptr, size)
817      PTR md;
818      PTR ptr;
819      size_t size;
820 {
821   if (ptr == 0)                 /* Guard against old realloc's */
822     return malloc (size);
823   else
824     return realloc (ptr, size);
825 }
826
827 void
828 mfree (md, ptr)
829      PTR md;
830      PTR ptr;
831 {
832   free (ptr);
833 }
834
835 #endif /* USE_MMALLOC */
836
837 #if !defined (USE_MMALLOC) || defined (NO_MMCHECK)
838
839 void
840 init_malloc (md)
841      PTR md;
842 {
843 }
844
845 #else /* Have mmalloc and want corruption checking */
846
847 static void
848 malloc_botch ()
849 {
850   fatal_dump_core ("Memory corruption");
851 }
852
853 /* Attempt to install hooks in mmalloc/mrealloc/mfree for the heap specified
854    by MD, to detect memory corruption.  Note that MD may be NULL to specify
855    the default heap that grows via sbrk.
856
857    Note that for freshly created regions, we must call mmcheckf prior to any
858    mallocs in the region.  Otherwise, any region which was allocated prior to
859    installing the checking hooks, which is later reallocated or freed, will
860    fail the checks!  The mmcheck function only allows initial hooks to be
861    installed before the first mmalloc.  However, anytime after we have called
862    mmcheck the first time to install the checking hooks, we can call it again
863    to update the function pointer to the memory corruption handler.
864
865    Returns zero on failure, non-zero on success. */
866
867 #ifndef MMCHECK_FORCE
868 #define MMCHECK_FORCE 0
869 #endif
870
871 void
872 init_malloc (md)
873      PTR md;
874 {
875   if (!mmcheckf (md, malloc_botch, MMCHECK_FORCE))
876     {
877       /* Don't use warning(), which relies on current_target being set
878          to something other than dummy_target, until after
879          initialize_all_files(). */
880
881       fprintf_unfiltered
882         (gdb_stderr, "warning: failed to install memory consistency checks; ");
883       fprintf_unfiltered
884         (gdb_stderr, "configuration should define NO_MMCHECK or MMCHECK_FORCE\n");
885     }
886
887   mmtrace ();
888 }
889
890 #endif /* Have mmalloc and want corruption checking  */
891
892 /* Called when a memory allocation fails, with the number of bytes of
893    memory requested in SIZE. */
894
895 NORETURN void
896 nomem (size)
897      long size;
898 {
899   if (size > 0)
900     {
901       fatal ("virtual memory exhausted: can't allocate %ld bytes.", size);
902     }
903   else
904     {
905       fatal ("virtual memory exhausted.");
906     }
907 }
908
909 /* Like mmalloc but get error if no storage available, and protect against
910    the caller wanting to allocate zero bytes.  Whether to return NULL for
911    a zero byte request, or translate the request into a request for one
912    byte of zero'd storage, is a religious issue. */
913
914 PTR
915 xmmalloc (md, size)
916      PTR md;
917      long size;
918 {
919   register PTR val;
920
921   if (size == 0)
922     {
923       val = NULL;
924     }
925   else if ((val = mmalloc (md, size)) == NULL)
926     {
927       nomem (size);
928     }
929   return (val);
930 }
931
932 /* Like mrealloc but get error if no storage available.  */
933
934 PTR
935 xmrealloc (md, ptr, size)
936      PTR md;
937      PTR ptr;
938      long size;
939 {
940   register PTR val;
941
942   if (ptr != NULL)
943     {
944       val = mrealloc (md, ptr, size);
945     }
946   else
947     {
948       val = mmalloc (md, size);
949     }
950   if (val == NULL)
951     {
952       nomem (size);
953     }
954   return (val);
955 }
956
957 /* Like malloc but get error if no storage available, and protect against
958    the caller wanting to allocate zero bytes.  */
959
960 PTR
961 xmalloc (size)
962      size_t size;
963 {
964   return (xmmalloc ((PTR) NULL, size));
965 }
966
967 /* Like mrealloc but get error if no storage available.  */
968
969 PTR
970 xrealloc (ptr, size)
971      PTR ptr;
972      size_t size;
973 {
974   return (xmrealloc ((PTR) NULL, ptr, size));
975 }
976 \f
977
978 /* My replacement for the read system call.
979    Used like `read' but keeps going if `read' returns too soon.  */
980
981 int
982 myread (desc, addr, len)
983      int desc;
984      char *addr;
985      int len;
986 {
987   register int val;
988   int orglen = len;
989
990   while (len > 0)
991     {
992       val = read (desc, addr, len);
993       if (val < 0)
994         return val;
995       if (val == 0)
996         return orglen - len;
997       len -= val;
998       addr += val;
999     }
1000   return orglen;
1001 }
1002 \f
1003 /* Make a copy of the string at PTR with SIZE characters
1004    (and add a null character at the end in the copy).
1005    Uses malloc to get the space.  Returns the address of the copy.  */
1006
1007 char *
1008 savestring (ptr, size)
1009      const char *ptr;
1010      int size;
1011 {
1012   register char *p = (char *) xmalloc (size + 1);
1013   memcpy (p, ptr, size);
1014   p[size] = 0;
1015   return p;
1016 }
1017
1018 char *
1019 msavestring (md, ptr, size)
1020      PTR md;
1021      const char *ptr;
1022      int size;
1023 {
1024   register char *p = (char *) xmmalloc (md, size + 1);
1025   memcpy (p, ptr, size);
1026   p[size] = 0;
1027   return p;
1028 }
1029
1030 /* The "const" is so it compiles under DGUX (which prototypes strsave
1031    in <string.h>.  FIXME: This should be named "xstrsave", shouldn't it?
1032    Doesn't real strsave return NULL if out of memory?  */
1033 char *
1034 strsave (ptr)
1035      const char *ptr;
1036 {
1037   return savestring (ptr, strlen (ptr));
1038 }
1039
1040 char *
1041 mstrsave (md, ptr)
1042      PTR md;
1043      const char *ptr;
1044 {
1045   return (msavestring (md, ptr, strlen (ptr)));
1046 }
1047
1048 void
1049 print_spaces (n, file)
1050      register int n;
1051      register GDB_FILE *file;
1052 {
1053   fputs_unfiltered (n_spaces (n), file);
1054 }
1055
1056 /* Print a host address.  */
1057
1058 void
1059 gdb_print_address (addr, stream)
1060      PTR addr;
1061      GDB_FILE *stream;
1062 {
1063
1064   /* We could use the %p conversion specifier to fprintf if we had any
1065      way of knowing whether this host supports it.  But the following
1066      should work on the Alpha and on 32 bit machines.  */
1067
1068   fprintf_filtered (stream, "0x%lx", (unsigned long) addr);
1069 }
1070
1071 /* Ask user a y-or-n question and return 1 iff answer is yes.
1072    Takes three args which are given to printf to print the question.
1073    The first, a control string, should end in "? ".
1074    It should not say how to answer, because we do that.  */
1075
1076 /* VARARGS */
1077 int
1078 #ifdef ANSI_PROTOTYPES
1079 query (char *ctlstr,...)
1080 #else
1081 query (va_alist)
1082      va_dcl
1083 #endif
1084 {
1085   va_list args;
1086   register int answer;
1087   register int ans2;
1088   int retval;
1089
1090 #ifdef ANSI_PROTOTYPES
1091   va_start (args, ctlstr);
1092 #else
1093   char *ctlstr;
1094   va_start (args);
1095   ctlstr = va_arg (args, char *);
1096 #endif
1097
1098   if (query_hook)
1099     {
1100       return query_hook (ctlstr, args);
1101     }
1102
1103   /* Automatically answer "yes" if input is not from a terminal.  */
1104   if (!input_from_terminal_p ())
1105     return 1;
1106 #ifdef MPW
1107   /* FIXME Automatically answer "yes" if called from MacGDB.  */
1108   if (mac_app)
1109     return 1;
1110 #endif /* MPW */
1111
1112   while (1)
1113     {
1114       wrap_here ("");           /* Flush any buffered output */
1115       gdb_flush (gdb_stdout);
1116
1117       if (annotation_level > 1)
1118         printf_filtered ("\n\032\032pre-query\n");
1119
1120       vfprintf_filtered (gdb_stdout, ctlstr, args);
1121       printf_filtered ("(y or n) ");
1122
1123       if (annotation_level > 1)
1124         printf_filtered ("\n\032\032query\n");
1125
1126 #ifdef MPW
1127       /* If not in MacGDB, move to a new line so the entered line doesn't
1128          have a prompt on the front of it. */
1129       if (!mac_app)
1130         fputs_unfiltered ("\n", gdb_stdout);
1131 #endif /* MPW */
1132
1133       wrap_here ("");
1134       gdb_flush (gdb_stdout);
1135
1136 #if defined(TUI)
1137       if (!tui_version || cmdWin == tuiWinWithFocus ())
1138 #endif
1139         answer = fgetc (stdin);
1140 #if defined(TUI)
1141       else
1142         answer = (unsigned char) tuiBufferGetc ();
1143
1144 #endif
1145       clearerr (stdin);         /* in case of C-d */
1146       if (answer == EOF)        /* C-d */
1147         {
1148           retval = 1;
1149           break;
1150         }
1151       /* Eat rest of input line, to EOF or newline */
1152       if ((answer != '\n') || (tui_version && answer != '\r'))
1153         do
1154           {
1155 #if defined(TUI)
1156             if (!tui_version || cmdWin == tuiWinWithFocus ())
1157 #endif
1158               ans2 = fgetc (stdin);
1159 #if defined(TUI)
1160             else
1161               ans2 = (unsigned char) tuiBufferGetc ();
1162 #endif
1163             clearerr (stdin);
1164           }
1165         while (ans2 != EOF && ans2 != '\n' && ans2 != '\r');
1166       TUIDO (((TuiOpaqueFuncPtr) tui_vStartNewLines, 1));
1167
1168       if (answer >= 'a')
1169         answer -= 040;
1170       if (answer == 'Y')
1171         {
1172           retval = 1;
1173           break;
1174         }
1175       if (answer == 'N')
1176         {
1177           retval = 0;
1178           break;
1179         }
1180       printf_filtered ("Please answer y or n.\n");
1181     }
1182
1183   if (annotation_level > 1)
1184     printf_filtered ("\n\032\032post-query\n");
1185   return retval;
1186 }
1187 \f
1188
1189 /* Parse a C escape sequence.  STRING_PTR points to a variable
1190    containing a pointer to the string to parse.  That pointer
1191    should point to the character after the \.  That pointer
1192    is updated past the characters we use.  The value of the
1193    escape sequence is returned.
1194
1195    A negative value means the sequence \ newline was seen,
1196    which is supposed to be equivalent to nothing at all.
1197
1198    If \ is followed by a null character, we return a negative
1199    value and leave the string pointer pointing at the null character.
1200
1201    If \ is followed by 000, we return 0 and leave the string pointer
1202    after the zeros.  A value of 0 does not mean end of string.  */
1203
1204 int
1205 parse_escape (string_ptr)
1206      char **string_ptr;
1207 {
1208   register int c = *(*string_ptr)++;
1209   switch (c)
1210     {
1211     case 'a':
1212       return 007;               /* Bell (alert) char */
1213     case 'b':
1214       return '\b';
1215     case 'e':                   /* Escape character */
1216       return 033;
1217     case 'f':
1218       return '\f';
1219     case 'n':
1220       return '\n';
1221     case 'r':
1222       return '\r';
1223     case 't':
1224       return '\t';
1225     case 'v':
1226       return '\v';
1227     case '\n':
1228       return -2;
1229     case 0:
1230       (*string_ptr)--;
1231       return 0;
1232     case '^':
1233       c = *(*string_ptr)++;
1234       if (c == '\\')
1235         c = parse_escape (string_ptr);
1236       if (c == '?')
1237         return 0177;
1238       return (c & 0200) | (c & 037);
1239
1240     case '0':
1241     case '1':
1242     case '2':
1243     case '3':
1244     case '4':
1245     case '5':
1246     case '6':
1247     case '7':
1248       {
1249         register int i = c - '0';
1250         register int count = 0;
1251         while (++count < 3)
1252           {
1253             if ((c = *(*string_ptr)++) >= '0' && c <= '7')
1254               {
1255                 i *= 8;
1256                 i += c - '0';
1257               }
1258             else
1259               {
1260                 (*string_ptr)--;
1261                 break;
1262               }
1263           }
1264         return i;
1265       }
1266     default:
1267       return c;
1268     }
1269 }
1270 \f
1271 /* Print the character C on STREAM as part of the contents of a literal
1272    string whose delimiter is QUOTER.  Note that this routine should only
1273    be call for printing things which are independent of the language
1274    of the program being debugged. */
1275
1276 void
1277 gdb_printchar (c, stream, quoter)
1278      register int c;
1279      GDB_FILE *stream;
1280      int quoter;
1281 {
1282
1283   c &= 0xFF;                    /* Avoid sign bit follies */
1284
1285   if (c < 0x20 ||               /* Low control chars */
1286       (c >= 0x7F && c < 0xA0) ||        /* DEL, High controls */
1287       (sevenbit_strings && c >= 0x80))
1288     {                           /* high order bit set */
1289       switch (c)
1290         {
1291         case '\n':
1292           fputs_filtered ("\\n", stream);
1293           break;
1294         case '\b':
1295           fputs_filtered ("\\b", stream);
1296           break;
1297         case '\t':
1298           fputs_filtered ("\\t", stream);
1299           break;
1300         case '\f':
1301           fputs_filtered ("\\f", stream);
1302           break;
1303         case '\r':
1304           fputs_filtered ("\\r", stream);
1305           break;
1306         case '\033':
1307           fputs_filtered ("\\e", stream);
1308           break;
1309         case '\007':
1310           fputs_filtered ("\\a", stream);
1311           break;
1312         default:
1313           fprintf_filtered (stream, "\\%.3o", (unsigned int) c);
1314           break;
1315         }
1316     }
1317   else
1318     {
1319       if (c == '\\' || c == quoter)
1320         fputs_filtered ("\\", stream);
1321       fprintf_filtered (stream, "%c", c);
1322     }
1323 }
1324 \f
1325
1326 /* Number of lines per page or UINT_MAX if paging is disabled.  */
1327 static unsigned int lines_per_page;
1328 /* Number of chars per line or UNIT_MAX is line folding is disabled.  */
1329 static unsigned int chars_per_line;
1330 /* Current count of lines printed on this page, chars on this line.  */
1331 static unsigned int lines_printed, chars_printed;
1332
1333 /* Buffer and start column of buffered text, for doing smarter word-
1334    wrapping.  When someone calls wrap_here(), we start buffering output
1335    that comes through fputs_filtered().  If we see a newline, we just
1336    spit it out and forget about the wrap_here().  If we see another
1337    wrap_here(), we spit it out and remember the newer one.  If we see
1338    the end of the line, we spit out a newline, the indent, and then
1339    the buffered output.  */
1340
1341 /* Malloc'd buffer with chars_per_line+2 bytes.  Contains characters which
1342    are waiting to be output (they have already been counted in chars_printed).
1343    When wrap_buffer[0] is null, the buffer is empty.  */
1344 static char *wrap_buffer;
1345
1346 /* Pointer in wrap_buffer to the next character to fill.  */
1347 static char *wrap_pointer;
1348
1349 /* String to indent by if the wrap occurs.  Must not be NULL if wrap_column
1350    is non-zero.  */
1351 static char *wrap_indent;
1352
1353 /* Column number on the screen where wrap_buffer begins, or 0 if wrapping
1354    is not in effect.  */
1355 static int wrap_column;
1356 \f
1357
1358 /* Inialize the lines and chars per page */
1359 void
1360 init_page_info ()
1361 {
1362 #if defined(TUI)
1363   if (tui_version && m_winPtrNotNull (cmdWin))
1364     {
1365       lines_per_page = cmdWin->generic.height;
1366       chars_per_line = cmdWin->generic.width;
1367     }
1368   else
1369 #endif
1370     {
1371       /* These defaults will be used if we are unable to get the correct
1372          values from termcap.  */
1373 #if defined(__GO32__)
1374       lines_per_page = ScreenRows ();
1375       chars_per_line = ScreenCols ();
1376 #else
1377       lines_per_page = 24;
1378       chars_per_line = 80;
1379
1380 #if !defined (MPW) && !defined (_WIN32)
1381       /* No termcap under MPW, although might be cool to do something
1382          by looking at worksheet or console window sizes. */
1383       /* Initialize the screen height and width from termcap.  */
1384       {
1385         char *termtype = getenv ("TERM");
1386
1387         /* Positive means success, nonpositive means failure.  */
1388         int status;
1389
1390         /* 2048 is large enough for all known terminals, according to the
1391            GNU termcap manual.  */
1392         char term_buffer[2048];
1393
1394         if (termtype)
1395           {
1396             status = tgetent (term_buffer, termtype);
1397             if (status > 0)
1398               {
1399                 int val;
1400                 int running_in_emacs = getenv ("EMACS") != NULL;
1401
1402                 val = tgetnum ("li");
1403                 if (val >= 0 && !running_in_emacs)
1404                   lines_per_page = val;
1405                 else
1406                   /* The number of lines per page is not mentioned
1407                      in the terminal description.  This probably means
1408                      that paging is not useful (e.g. emacs shell window),
1409                      so disable paging.  */
1410                   lines_per_page = UINT_MAX;
1411
1412                 val = tgetnum ("co");
1413                 if (val >= 0)
1414                   chars_per_line = val;
1415               }
1416           }
1417       }
1418 #endif /* MPW */
1419
1420 #if defined(SIGWINCH) && defined(SIGWINCH_HANDLER)
1421
1422       /* If there is a better way to determine the window size, use it. */
1423       SIGWINCH_HANDLER (SIGWINCH);
1424 #endif
1425 #endif
1426       /* If the output is not a terminal, don't paginate it.  */
1427       if (!GDB_FILE_ISATTY (gdb_stdout))
1428         lines_per_page = UINT_MAX;
1429     }                           /* the command_line_version */
1430   set_width ();
1431 }
1432
1433 static void
1434 set_width ()
1435 {
1436   if (chars_per_line == 0)
1437     init_page_info ();
1438
1439   if (!wrap_buffer)
1440     {
1441       wrap_buffer = (char *) xmalloc (chars_per_line + 2);
1442       wrap_buffer[0] = '\0';
1443     }
1444   else
1445     wrap_buffer = (char *) xrealloc (wrap_buffer, chars_per_line + 2);
1446   wrap_pointer = wrap_buffer;   /* Start it at the beginning */
1447 }
1448
1449 /* ARGSUSED */
1450 static void
1451 set_width_command (args, from_tty, c)
1452      char *args;
1453      int from_tty;
1454      struct cmd_list_element *c;
1455 {
1456   set_width ();
1457 }
1458
1459 /* Wait, so the user can read what's on the screen.  Prompt the user
1460    to continue by pressing RETURN.  */
1461
1462 static void
1463 prompt_for_continue ()
1464 {
1465   char *ignore;
1466   char cont_prompt[120];
1467
1468   if (annotation_level > 1)
1469     printf_unfiltered ("\n\032\032pre-prompt-for-continue\n");
1470
1471   strcpy (cont_prompt,
1472           "---Type <return> to continue, or q <return> to quit---");
1473   if (annotation_level > 1)
1474     strcat (cont_prompt, "\n\032\032prompt-for-continue\n");
1475
1476   /* We must do this *before* we call gdb_readline, else it will eventually
1477      call us -- thinking that we're trying to print beyond the end of the 
1478      screen.  */
1479   reinitialize_more_filter ();
1480
1481   immediate_quit++;
1482   /* On a real operating system, the user can quit with SIGINT.
1483      But not on GO32.
1484
1485      'q' is provided on all systems so users don't have to change habits
1486      from system to system, and because telling them what to do in
1487      the prompt is more user-friendly than expecting them to think of
1488      SIGINT.  */
1489   /* Call readline, not gdb_readline, because GO32 readline handles control-C
1490      whereas control-C to gdb_readline will cause the user to get dumped
1491      out to DOS.  */
1492   ignore = readline (cont_prompt);
1493
1494   if (annotation_level > 1)
1495     printf_unfiltered ("\n\032\032post-prompt-for-continue\n");
1496
1497   if (ignore)
1498     {
1499       char *p = ignore;
1500       while (*p == ' ' || *p == '\t')
1501         ++p;
1502       if (p[0] == 'q')
1503         {
1504           if (!async_p)
1505             request_quit (SIGINT);
1506           else
1507             async_request_quit (0);
1508         }
1509       free (ignore);
1510     }
1511   immediate_quit--;
1512
1513   /* Now we have to do this again, so that GDB will know that it doesn't
1514      need to save the ---Type <return>--- line at the top of the screen.  */
1515   reinitialize_more_filter ();
1516
1517   dont_repeat ();               /* Forget prev cmd -- CR won't repeat it. */
1518 }
1519
1520 /* Reinitialize filter; ie. tell it to reset to original values.  */
1521
1522 void
1523 reinitialize_more_filter ()
1524 {
1525   lines_printed = 0;
1526   chars_printed = 0;
1527 }
1528
1529 /* Indicate that if the next sequence of characters overflows the line,
1530    a newline should be inserted here rather than when it hits the end. 
1531    If INDENT is non-null, it is a string to be printed to indent the
1532    wrapped part on the next line.  INDENT must remain accessible until
1533    the next call to wrap_here() or until a newline is printed through
1534    fputs_filtered().
1535
1536    If the line is already overfull, we immediately print a newline and
1537    the indentation, and disable further wrapping.
1538
1539    If we don't know the width of lines, but we know the page height,
1540    we must not wrap words, but should still keep track of newlines
1541    that were explicitly printed.
1542
1543    INDENT should not contain tabs, as that will mess up the char count
1544    on the next line.  FIXME.
1545
1546    This routine is guaranteed to force out any output which has been
1547    squirreled away in the wrap_buffer, so wrap_here ((char *)0) can be
1548    used to force out output from the wrap_buffer.  */
1549
1550 void
1551 wrap_here (indent)
1552      char *indent;
1553 {
1554   /* This should have been allocated, but be paranoid anyway. */
1555   if (!wrap_buffer)
1556     abort ();
1557
1558   if (wrap_buffer[0])
1559     {
1560       *wrap_pointer = '\0';
1561       fputs_unfiltered (wrap_buffer, gdb_stdout);
1562     }
1563   wrap_pointer = wrap_buffer;
1564   wrap_buffer[0] = '\0';
1565   if (chars_per_line == UINT_MAX)       /* No line overflow checking */
1566     {
1567       wrap_column = 0;
1568     }
1569   else if (chars_printed >= chars_per_line)
1570     {
1571       puts_filtered ("\n");
1572       if (indent != NULL)
1573         puts_filtered (indent);
1574       wrap_column = 0;
1575     }
1576   else
1577     {
1578       wrap_column = chars_printed;
1579       if (indent == NULL)
1580         wrap_indent = "";
1581       else
1582         wrap_indent = indent;
1583     }
1584 }
1585
1586 /* Ensure that whatever gets printed next, using the filtered output
1587    commands, starts at the beginning of the line.  I.E. if there is
1588    any pending output for the current line, flush it and start a new
1589    line.  Otherwise do nothing. */
1590
1591 void
1592 begin_line ()
1593 {
1594   if (chars_printed > 0)
1595     {
1596       puts_filtered ("\n");
1597     }
1598 }
1599
1600
1601 /* ``struct gdb_file'' implementation that maps directly onto
1602    <stdio.h>'s FILE. */
1603
1604 static gdb_file_fputs_ftype stdio_file_fputs;
1605 static gdb_file_isatty_ftype stdio_file_isatty;
1606 static gdb_file_delete_ftype stdio_file_delete;
1607 static struct gdb_file *stdio_file_new PARAMS ((FILE * file, int close_p));
1608 static gdb_file_flush_ftype stdio_file_flush;
1609
1610 static int stdio_file_magic;
1611
1612 struct stdio_file
1613   {
1614     int *magic;
1615     FILE *file;
1616     int close_p;
1617   };
1618
1619 static struct gdb_file *
1620 stdio_file_new (file, close_p)
1621      FILE *file;
1622      int close_p;
1623 {
1624   struct gdb_file *gdb_file = gdb_file_new ();
1625   struct stdio_file *stdio = xmalloc (sizeof (struct stdio_file));
1626   stdio->magic = &stdio_file_magic;
1627   stdio->file = file;
1628   stdio->close_p = close_p;
1629   set_gdb_file_data (gdb_file, stdio, stdio_file_delete);
1630   set_gdb_file_flush (gdb_file, stdio_file_flush);
1631   set_gdb_file_fputs (gdb_file, stdio_file_fputs);
1632   set_gdb_file_isatty (gdb_file, stdio_file_isatty);
1633   return gdb_file;
1634 }
1635
1636 static void
1637 stdio_file_delete (file)
1638      struct gdb_file *file;
1639 {
1640   struct stdio_file *stdio = gdb_file_data (file);
1641   if (stdio->magic != &stdio_file_magic)
1642     error ("Internal error: bad magic number");
1643   if (stdio->close_p)
1644     {
1645       fclose (stdio->file);
1646     }
1647   free (stdio);
1648 }
1649
1650 static void
1651 stdio_file_flush (file)
1652      struct gdb_file *file;
1653 {
1654   struct stdio_file *stdio = gdb_file_data (file);
1655   if (stdio->magic != &stdio_file_magic)
1656     error ("Internal error: bad magic number");
1657   fflush (stdio->file);
1658 }
1659
1660 static void
1661 stdio_file_fputs (linebuffer, file)
1662      const char *linebuffer;
1663      struct gdb_file *file;
1664 {
1665   struct stdio_file *stdio = gdb_file_data (file);
1666   if (stdio->magic != &stdio_file_magic)
1667     error ("Internal error: bad magic number");
1668   fputs (linebuffer, stdio->file);
1669 }
1670
1671 static int
1672 stdio_file_isatty (file)
1673      struct gdb_file *file;
1674 {
1675   struct stdio_file *stdio = gdb_file_data (file);
1676   if (stdio->magic != &stdio_file_magic)
1677     error ("Internal error: bad magic number");
1678   return (isatty (fileno (stdio->file)));
1679 }
1680
1681 /* Like fdopen().  Create a gdb_file from a previously opened FILE. */
1682
1683 struct gdb_file *
1684 stdio_fileopen (file)
1685      FILE *file;
1686 {
1687   return stdio_file_new (file, 0);
1688 }
1689
1690
1691 /* A ``struct gdb_file'' that is compatible with all the legacy
1692    code. */
1693
1694 static gdb_file_flush_ftype tui_file_flush;
1695 extern gdb_file_fputs_ftype tui_file_fputs;
1696 static gdb_file_isatty_ftype tui_file_isatty;
1697 static gdb_file_rewind_ftype tui_file_rewind;
1698 static gdb_file_put_ftype tui_file_put;
1699 static gdb_file_delete_ftype tui_file_delete;
1700 static struct gdb_file *tui_file_new PARAMS ((void));
1701 static int tui_file_magic;
1702
1703 static struct gdb_file *
1704 tui_file_new ()
1705 {
1706   struct tui_stream *tui = xmalloc (sizeof (struct tui_stream));
1707   struct gdb_file *file = gdb_file_new ();
1708   set_gdb_file_data (file, tui, tui_file_delete);
1709   set_gdb_file_flush (file, tui_file_flush);
1710   set_gdb_file_fputs (file, tui_file_fputs);
1711   set_gdb_file_isatty (file, tui_file_isatty);
1712   set_gdb_file_rewind (file, tui_file_rewind);
1713   set_gdb_file_put (file, tui_file_put);
1714   tui->ts_magic = &tui_file_magic;
1715   return file;
1716 }
1717
1718 static void
1719 tui_file_delete (file)
1720      struct gdb_file *file;
1721 {
1722   struct tui_stream *tmpstream = gdb_file_data (file);
1723   if (tmpstream->ts_magic != &tui_file_magic)
1724     error ("Internal error: bad magic number");
1725   if ((tmpstream->ts_streamtype == astring) &&
1726       (tmpstream->ts_strbuf != NULL))
1727     {
1728       free (tmpstream->ts_strbuf);
1729     }
1730   free (tmpstream);
1731 }
1732
1733 struct gdb_file *
1734 tui_fileopen (stream)
1735      FILE *stream;
1736 {
1737   struct gdb_file *file = tui_file_new ();
1738   struct tui_stream *tmpstream = gdb_file_data (file);
1739   tmpstream->ts_streamtype = afile;
1740   tmpstream->ts_filestream = stream;
1741   tmpstream->ts_strbuf = NULL;
1742   tmpstream->ts_buflen = 0;
1743   return file;
1744 }
1745
1746 static int
1747 tui_file_isatty (file)
1748      struct gdb_file *file;
1749 {
1750   struct tui_stream *stream = gdb_file_data (file);
1751   if (stream->ts_magic != &tui_file_magic)
1752     error ("Internal error: bad magic number");
1753   if (stream->ts_streamtype == afile)
1754     return (isatty (fileno (stream->ts_filestream)));
1755   else
1756     return 0;
1757 }
1758
1759 static void
1760 tui_file_rewind (file)
1761      struct gdb_file *file;
1762 {
1763   struct tui_stream *stream = gdb_file_data (file);
1764   if (stream->ts_magic != &tui_file_magic)
1765     error ("Internal error: bad magic number");
1766   stream->ts_strbuf[0] = '\0';
1767 }
1768
1769 static void
1770 tui_file_put (file, dest)
1771      struct gdb_file *file;
1772      struct gdb_file *dest;
1773 {
1774   struct tui_stream *stream = gdb_file_data (file);
1775   if (stream->ts_magic != &tui_file_magic)
1776     error ("Internal error: bad magic number");
1777   if (stream->ts_streamtype == astring)
1778     {
1779       fputs_unfiltered (stream->ts_strbuf, dest);
1780     }
1781 }
1782
1783 GDB_FILE *
1784 gdb_file_init_astring (n)
1785      int n;
1786 {
1787   struct gdb_file *file = tui_file_new ();
1788   struct tui_stream *tmpstream = gdb_file_data (file);
1789   if (tmpstream->ts_magic != &tui_file_magic)
1790     error ("Internal error: bad magic number");
1791
1792   tmpstream->ts_streamtype = astring;
1793   tmpstream->ts_filestream = NULL;
1794   if (n > 0)
1795     {
1796       tmpstream->ts_strbuf = xmalloc ((n + 1) * sizeof (char));
1797       tmpstream->ts_strbuf[0] = '\0';
1798     }
1799   else
1800     tmpstream->ts_strbuf = NULL;
1801   tmpstream->ts_buflen = n;
1802
1803   return file;
1804 }
1805
1806 void
1807 gdb_file_deallocate (streamptr)
1808      GDB_FILE **streamptr;
1809 {
1810   gdb_file_delete (*streamptr);
1811   *streamptr = NULL;
1812 }
1813
1814 char *
1815 gdb_file_get_strbuf (file)
1816      GDB_FILE *file;
1817 {
1818   struct tui_stream *stream = gdb_file_data (file);
1819   if (stream->ts_magic != &tui_file_magic)
1820     error ("Internal error: bad magic number");
1821   return (stream->ts_strbuf);
1822 }
1823
1824 /* adjust the length of the buffer by the amount necessary
1825    to accomodate appending a string of length N to the buffer contents */
1826 void
1827 gdb_file_adjust_strbuf (n, file)
1828      int n;
1829      GDB_FILE *file;
1830 {
1831   struct tui_stream *stream = gdb_file_data (file);
1832   int non_null_chars;
1833   if (stream->ts_magic != &tui_file_magic)
1834     error ("Internal error: bad magic number");
1835
1836   if (stream->ts_streamtype != astring)
1837     return;
1838
1839   if (stream->ts_strbuf)
1840     {
1841       /* There is already a buffer allocated */
1842       non_null_chars = strlen (stream->ts_strbuf);
1843
1844       if (n > (stream->ts_buflen - non_null_chars - 1))
1845         {
1846           stream->ts_buflen = n + non_null_chars + 1;
1847           stream->ts_strbuf = xrealloc (stream->ts_strbuf, stream->ts_buflen);
1848         }
1849     }
1850   else
1851     /* No buffer yet, so allocate one of the desired size */
1852     stream->ts_strbuf = xmalloc ((n + 1) * sizeof (char));
1853 }
1854
1855 GDB_FILE *
1856 gdb_fopen (name, mode)
1857      char *name;
1858      char *mode;
1859 {
1860   FILE *f = fopen (name, mode);
1861   if (f == NULL)
1862     return NULL;
1863   return stdio_file_new (f, 1);
1864 }
1865
1866 static void
1867 tui_file_flush (file)
1868      GDB_FILE *file;
1869 {
1870   struct tui_stream *stream = gdb_file_data (file);
1871   if (stream->ts_magic != &tui_file_magic)
1872     error ("Internal error: bad magic number");
1873   if (flush_hook
1874       && (file == gdb_stdout
1875           || file == gdb_stderr))
1876     {
1877       flush_hook (file);
1878       return;
1879     }
1880
1881   fflush (stream->ts_filestream);
1882 }
1883
1884 void
1885 gdb_fclose (streamptr)
1886      GDB_FILE **streamptr;
1887 {
1888   gdb_file_delete (*streamptr);
1889   *streamptr = NULL;
1890 }
1891
1892
1893 /* Implement the ``struct gdb_file'' object. */
1894
1895 static gdb_file_isatty_ftype null_file_isatty;
1896 static gdb_file_fputs_ftype null_file_fputs;
1897 static gdb_file_flush_ftype null_file_flush;
1898 static gdb_file_delete_ftype null_file_delete;
1899 static gdb_file_rewind_ftype null_file_rewind;
1900 static gdb_file_put_ftype null_file_put;
1901
1902 struct gdb_file
1903   {
1904     gdb_file_flush_ftype *to_flush;
1905     gdb_file_fputs_ftype *to_fputs;
1906     gdb_file_delete_ftype *to_delete;
1907     gdb_file_isatty_ftype *to_isatty;
1908     gdb_file_rewind_ftype *to_rewind;
1909     gdb_file_put_ftype *to_put;
1910     void *to_data;
1911   };
1912
1913 struct gdb_file *
1914 gdb_file_new ()
1915 {
1916   struct gdb_file *file = xmalloc (sizeof (struct gdb_file));
1917   set_gdb_file_data (file, NULL, null_file_delete);
1918   set_gdb_file_flush (file, null_file_flush);
1919   set_gdb_file_fputs (file, null_file_fputs);
1920   set_gdb_file_isatty (file, null_file_isatty);
1921   set_gdb_file_rewind (file, null_file_rewind);
1922   set_gdb_file_put (file, null_file_put);
1923   return file;
1924 }
1925
1926 void
1927 gdb_file_delete (file)
1928      struct gdb_file *file;
1929 {
1930   file->to_delete (file);
1931   free (file);
1932 }
1933
1934 static int
1935 null_file_isatty (file)
1936      struct gdb_file *file;
1937 {
1938   return 0;
1939 }
1940
1941 static void
1942 null_file_rewind (file)
1943      struct gdb_file *file;
1944 {
1945   return;
1946 }
1947
1948 static void
1949 null_file_put (file, src)
1950      struct gdb_file *file;
1951      struct gdb_file *src;
1952 {
1953   return;
1954 }
1955
1956 static void
1957 null_file_flush (file)
1958      struct gdb_file *file;
1959 {
1960   return;
1961 }
1962
1963 static void
1964 null_file_fputs (buf, file)
1965      const char *buf;
1966      struct gdb_file *file;
1967 {
1968   return;
1969 }
1970
1971 static void
1972 null_file_delete (file)
1973      struct gdb_file *file;
1974 {
1975   return;
1976 }
1977
1978 void *
1979 gdb_file_data (file)
1980      struct gdb_file *file;
1981 {
1982   return file->to_data;
1983 }
1984
1985 void
1986 gdb_flush (file)
1987      struct gdb_file *file;
1988 {
1989   file->to_flush (file);
1990 }
1991
1992 int
1993 gdb_file_isatty (file)
1994      struct gdb_file *file;
1995 {
1996   return file->to_isatty (file);
1997 }
1998
1999 void
2000 gdb_file_rewind (file)
2001      struct gdb_file *file;
2002 {
2003   file->to_rewind (file);
2004 }
2005
2006 void
2007 gdb_file_put (file, dest)
2008      struct gdb_file *file;
2009      struct gdb_file *dest;
2010 {
2011   file->to_put (file, dest);
2012 }
2013
2014 void
2015 fputs_unfiltered (buf, file)
2016      const char *buf;
2017      struct gdb_file *file;
2018 {
2019   file->to_fputs (buf, file);
2020 }
2021
2022 void
2023 set_gdb_file_flush (file, flush)
2024      struct gdb_file *file;
2025      gdb_file_flush_ftype *flush;
2026 {
2027   file->to_flush = flush;
2028 }
2029
2030 void
2031 set_gdb_file_isatty (file, isatty)
2032      struct gdb_file *file;
2033      gdb_file_isatty_ftype *isatty;
2034 {
2035   file->to_isatty = isatty;
2036 }
2037
2038 void
2039 set_gdb_file_rewind (file, rewind)
2040      struct gdb_file *file;
2041      gdb_file_rewind_ftype *rewind;
2042 {
2043   file->to_rewind = rewind;
2044 }
2045
2046 void
2047 set_gdb_file_put (file, put)
2048      struct gdb_file *file;
2049      gdb_file_put_ftype *put;
2050 {
2051   file->to_put = put;
2052 }
2053
2054 void
2055 set_gdb_file_fputs (file, fputs)
2056      struct gdb_file *file;
2057      gdb_file_fputs_ftype *fputs;
2058 {
2059   file->to_fputs = fputs;
2060 }
2061
2062 void
2063 set_gdb_file_data (file, data, delete)
2064      struct gdb_file *file;
2065      void *data;
2066      gdb_file_delete_ftype *delete;
2067 {
2068   file->to_data = data;
2069   file->to_delete = delete;
2070 }
2071
2072 /* Like fputs but if FILTER is true, pause after every screenful.
2073
2074    Regardless of FILTER can wrap at points other than the final
2075    character of a line.
2076
2077    Unlike fputs, fputs_maybe_filtered does not return a value.
2078    It is OK for LINEBUFFER to be NULL, in which case just don't print
2079    anything.
2080
2081    Note that a longjmp to top level may occur in this routine (only if
2082    FILTER is true) (since prompt_for_continue may do so) so this
2083    routine should not be called when cleanups are not in place.  */
2084
2085 static void
2086 fputs_maybe_filtered (linebuffer, stream, filter)
2087      const char *linebuffer;
2088      GDB_FILE *stream;
2089      int filter;
2090 {
2091   const char *lineptr;
2092
2093   if (linebuffer == 0)
2094     return;
2095
2096   /* Don't do any filtering if it is disabled.  */
2097   if ((stream != gdb_stdout) || !pagination_enabled
2098       || (lines_per_page == UINT_MAX && chars_per_line == UINT_MAX))
2099     {
2100       fputs_unfiltered (linebuffer, stream);
2101       return;
2102     }
2103
2104   /* Go through and output each character.  Show line extension
2105      when this is necessary; prompt user for new page when this is
2106      necessary.  */
2107
2108   lineptr = linebuffer;
2109   while (*lineptr)
2110     {
2111       /* Possible new page.  */
2112       if (filter &&
2113           (lines_printed >= lines_per_page - 1))
2114         prompt_for_continue ();
2115
2116       while (*lineptr && *lineptr != '\n')
2117         {
2118           /* Print a single line.  */
2119           if (*lineptr == '\t')
2120             {
2121               if (wrap_column)
2122                 *wrap_pointer++ = '\t';
2123               else
2124                 fputc_unfiltered ('\t', stream);
2125               /* Shifting right by 3 produces the number of tab stops
2126                  we have already passed, and then adding one and
2127                  shifting left 3 advances to the next tab stop.  */
2128               chars_printed = ((chars_printed >> 3) + 1) << 3;
2129               lineptr++;
2130             }
2131           else
2132             {
2133               if (wrap_column)
2134                 *wrap_pointer++ = *lineptr;
2135               else
2136                 fputc_unfiltered (*lineptr, stream);
2137               chars_printed++;
2138               lineptr++;
2139             }
2140
2141           if (chars_printed >= chars_per_line)
2142             {
2143               unsigned int save_chars = chars_printed;
2144
2145               chars_printed = 0;
2146               lines_printed++;
2147               /* If we aren't actually wrapping, don't output newline --
2148                  if chars_per_line is right, we probably just overflowed
2149                  anyway; if it's wrong, let us keep going.  */
2150               if (wrap_column)
2151                 fputc_unfiltered ('\n', stream);
2152
2153               /* Possible new page.  */
2154               if (lines_printed >= lines_per_page - 1)
2155                 prompt_for_continue ();
2156
2157               /* Now output indentation and wrapped string */
2158               if (wrap_column)
2159                 {
2160                   fputs_unfiltered (wrap_indent, stream);
2161                   *wrap_pointer = '\0';         /* Null-terminate saved stuff */
2162                   fputs_unfiltered (wrap_buffer, stream);       /* and eject it */
2163                   /* FIXME, this strlen is what prevents wrap_indent from
2164                      containing tabs.  However, if we recurse to print it
2165                      and count its chars, we risk trouble if wrap_indent is
2166                      longer than (the user settable) chars_per_line. 
2167                      Note also that this can set chars_printed > chars_per_line
2168                      if we are printing a long string.  */
2169                   chars_printed = strlen (wrap_indent)
2170                     + (save_chars - wrap_column);
2171                   wrap_pointer = wrap_buffer;   /* Reset buffer */
2172                   wrap_buffer[0] = '\0';
2173                   wrap_column = 0;      /* And disable fancy wrap */
2174                 }
2175             }
2176         }
2177
2178       if (*lineptr == '\n')
2179         {
2180           chars_printed = 0;
2181           wrap_here ((char *) 0);       /* Spit out chars, cancel further wraps */
2182           lines_printed++;
2183           fputc_unfiltered ('\n', stream);
2184           lineptr++;
2185         }
2186     }
2187 }
2188
2189 void
2190 fputs_filtered (linebuffer, stream)
2191      const char *linebuffer;
2192      GDB_FILE *stream;
2193 {
2194   fputs_maybe_filtered (linebuffer, stream, 1);
2195 }
2196
2197 int
2198 putchar_unfiltered (c)
2199      int c;
2200 {
2201   char buf[2];
2202
2203   buf[0] = c;
2204   buf[1] = 0;
2205   fputs_unfiltered (buf, gdb_stdout);
2206   return c;
2207 }
2208
2209 int
2210 fputc_unfiltered (c, stream)
2211      int c;
2212      GDB_FILE *stream;
2213 {
2214   char buf[2];
2215
2216   buf[0] = c;
2217   buf[1] = 0;
2218   fputs_unfiltered (buf, stream);
2219   return c;
2220 }
2221
2222 int
2223 fputc_filtered (c, stream)
2224      int c;
2225      GDB_FILE *stream;
2226 {
2227   char buf[2];
2228
2229   buf[0] = c;
2230   buf[1] = 0;
2231   fputs_filtered (buf, stream);
2232   return c;
2233 }
2234
2235 /* puts_debug is like fputs_unfiltered, except it prints special
2236    characters in printable fashion.  */
2237
2238 void
2239 puts_debug (prefix, string, suffix)
2240      char *prefix;
2241      char *string;
2242      char *suffix;
2243 {
2244   int ch;
2245
2246   /* Print prefix and suffix after each line.  */
2247   static int new_line = 1;
2248   static int return_p = 0;
2249   static char *prev_prefix = "";
2250   static char *prev_suffix = "";
2251
2252   if (*string == '\n')
2253     return_p = 0;
2254
2255   /* If the prefix is changing, print the previous suffix, a new line,
2256      and the new prefix.  */
2257   if ((return_p || (strcmp (prev_prefix, prefix) != 0)) && !new_line)
2258     {
2259       fputs_unfiltered (prev_suffix, gdb_stdlog);
2260       fputs_unfiltered ("\n", gdb_stdlog);
2261       fputs_unfiltered (prefix, gdb_stdlog);
2262     }
2263
2264   /* Print prefix if we printed a newline during the previous call.  */
2265   if (new_line)
2266     {
2267       new_line = 0;
2268       fputs_unfiltered (prefix, gdb_stdlog);
2269     }
2270
2271   prev_prefix = prefix;
2272   prev_suffix = suffix;
2273
2274   /* Output characters in a printable format.  */
2275   while ((ch = *string++) != '\0')
2276     {
2277       switch (ch)
2278         {
2279         default:
2280           if (isprint (ch))
2281             fputc_unfiltered (ch, gdb_stdlog);
2282
2283           else
2284             fprintf_unfiltered (gdb_stdlog, "\\x%02x", ch & 0xff);
2285           break;
2286
2287         case '\\':
2288           fputs_unfiltered ("\\\\", gdb_stdlog);
2289           break;
2290         case '\b':
2291           fputs_unfiltered ("\\b", gdb_stdlog);
2292           break;
2293         case '\f':
2294           fputs_unfiltered ("\\f", gdb_stdlog);
2295           break;
2296         case '\n':
2297           new_line = 1;
2298           fputs_unfiltered ("\\n", gdb_stdlog);
2299           break;
2300         case '\r':
2301           fputs_unfiltered ("\\r", gdb_stdlog);
2302           break;
2303         case '\t':
2304           fputs_unfiltered ("\\t", gdb_stdlog);
2305           break;
2306         case '\v':
2307           fputs_unfiltered ("\\v", gdb_stdlog);
2308           break;
2309         }
2310
2311       return_p = ch == '\r';
2312     }
2313
2314   /* Print suffix if we printed a newline.  */
2315   if (new_line)
2316     {
2317       fputs_unfiltered (suffix, gdb_stdlog);
2318       fputs_unfiltered ("\n", gdb_stdlog);
2319     }
2320 }
2321
2322
2323 /* Print a variable number of ARGS using format FORMAT.  If this
2324    information is going to put the amount written (since the last call
2325    to REINITIALIZE_MORE_FILTER or the last page break) over the page size,
2326    call prompt_for_continue to get the users permision to continue.
2327
2328    Unlike fprintf, this function does not return a value.
2329
2330    We implement three variants, vfprintf (takes a vararg list and stream),
2331    fprintf (takes a stream to write on), and printf (the usual).
2332
2333    Note also that a longjmp to top level may occur in this routine
2334    (since prompt_for_continue may do so) so this routine should not be
2335    called when cleanups are not in place.  */
2336
2337 static void
2338 vfprintf_maybe_filtered (stream, format, args, filter)
2339      GDB_FILE *stream;
2340      const char *format;
2341      va_list args;
2342      int filter;
2343 {
2344   char *linebuffer;
2345   struct cleanup *old_cleanups;
2346
2347   vasprintf (&linebuffer, format, args);
2348   if (linebuffer == NULL)
2349     {
2350       fputs_unfiltered ("\ngdb: virtual memory exhausted.\n", gdb_stderr);
2351       exit (1);
2352     }
2353   old_cleanups = make_cleanup (free, linebuffer);
2354   fputs_maybe_filtered (linebuffer, stream, filter);
2355   do_cleanups (old_cleanups);
2356 }
2357
2358
2359 void
2360 vfprintf_filtered (stream, format, args)
2361      GDB_FILE *stream;
2362      const char *format;
2363      va_list args;
2364 {
2365   vfprintf_maybe_filtered (stream, format, args, 1);
2366 }
2367
2368 void
2369 vfprintf_unfiltered (stream, format, args)
2370      GDB_FILE *stream;
2371      const char *format;
2372      va_list args;
2373 {
2374   char *linebuffer;
2375   struct cleanup *old_cleanups;
2376
2377   vasprintf (&linebuffer, format, args);
2378   if (linebuffer == NULL)
2379     {
2380       fputs_unfiltered ("\ngdb: virtual memory exhausted.\n", gdb_stderr);
2381       exit (1);
2382     }
2383   old_cleanups = make_cleanup (free, linebuffer);
2384   fputs_unfiltered (linebuffer, stream);
2385   do_cleanups (old_cleanups);
2386 }
2387
2388 void
2389 vprintf_filtered (format, args)
2390      const char *format;
2391      va_list args;
2392 {
2393   vfprintf_maybe_filtered (gdb_stdout, format, args, 1);
2394 }
2395
2396 void
2397 vprintf_unfiltered (format, args)
2398      const char *format;
2399      va_list args;
2400 {
2401   vfprintf_unfiltered (gdb_stdout, format, args);
2402 }
2403
2404 /* VARARGS */
2405 void
2406 #ifdef ANSI_PROTOTYPES
2407 fprintf_filtered (GDB_FILE * stream, const char *format,...)
2408 #else
2409 fprintf_filtered (va_alist)
2410      va_dcl
2411 #endif
2412 {
2413   va_list args;
2414 #ifdef ANSI_PROTOTYPES
2415   va_start (args, format);
2416 #else
2417   GDB_FILE *stream;
2418   char *format;
2419
2420   va_start (args);
2421   stream = va_arg (args, GDB_FILE *);
2422   format = va_arg (args, char *);
2423 #endif
2424   vfprintf_filtered (stream, format, args);
2425   va_end (args);
2426 }
2427
2428 /* VARARGS */
2429 void
2430 #ifdef ANSI_PROTOTYPES
2431 fprintf_unfiltered (GDB_FILE * stream, const char *format,...)
2432 #else
2433 fprintf_unfiltered (va_alist)
2434      va_dcl
2435 #endif
2436 {
2437   va_list args;
2438 #ifdef ANSI_PROTOTYPES
2439   va_start (args, format);
2440 #else
2441   GDB_FILE *stream;
2442   char *format;
2443
2444   va_start (args);
2445   stream = va_arg (args, GDB_FILE *);
2446   format = va_arg (args, char *);
2447 #endif
2448   vfprintf_unfiltered (stream, format, args);
2449   va_end (args);
2450 }
2451
2452 /* Like fprintf_filtered, but prints its result indented.
2453    Called as fprintfi_filtered (spaces, stream, format, ...);  */
2454
2455 /* VARARGS */
2456 void
2457 #ifdef ANSI_PROTOTYPES
2458 fprintfi_filtered (int spaces, GDB_FILE * stream, const char *format,...)
2459 #else
2460 fprintfi_filtered (va_alist)
2461      va_dcl
2462 #endif
2463 {
2464   va_list args;
2465 #ifdef ANSI_PROTOTYPES
2466   va_start (args, format);
2467 #else
2468   int spaces;
2469   GDB_FILE *stream;
2470   char *format;
2471
2472   va_start (args);
2473   spaces = va_arg (args, int);
2474   stream = va_arg (args, GDB_FILE *);
2475   format = va_arg (args, char *);
2476 #endif
2477   print_spaces_filtered (spaces, stream);
2478
2479   vfprintf_filtered (stream, format, args);
2480   va_end (args);
2481 }
2482
2483
2484 /* VARARGS */
2485 void
2486 #ifdef ANSI_PROTOTYPES
2487 printf_filtered (const char *format,...)
2488 #else
2489 printf_filtered (va_alist)
2490      va_dcl
2491 #endif
2492 {
2493   va_list args;
2494 #ifdef ANSI_PROTOTYPES
2495   va_start (args, format);
2496 #else
2497   char *format;
2498
2499   va_start (args);
2500   format = va_arg (args, char *);
2501 #endif
2502   vfprintf_filtered (gdb_stdout, format, args);
2503   va_end (args);
2504 }
2505
2506
2507 /* VARARGS */
2508 void
2509 #ifdef ANSI_PROTOTYPES
2510 printf_unfiltered (const char *format,...)
2511 #else
2512 printf_unfiltered (va_alist)
2513      va_dcl
2514 #endif
2515 {
2516   va_list args;
2517 #ifdef ANSI_PROTOTYPES
2518   va_start (args, format);
2519 #else
2520   char *format;
2521
2522   va_start (args);
2523   format = va_arg (args, char *);
2524 #endif
2525   vfprintf_unfiltered (gdb_stdout, format, args);
2526   va_end (args);
2527 }
2528
2529 /* Like printf_filtered, but prints it's result indented.
2530    Called as printfi_filtered (spaces, format, ...);  */
2531
2532 /* VARARGS */
2533 void
2534 #ifdef ANSI_PROTOTYPES
2535 printfi_filtered (int spaces, const char *format,...)
2536 #else
2537 printfi_filtered (va_alist)
2538      va_dcl
2539 #endif
2540 {
2541   va_list args;
2542 #ifdef ANSI_PROTOTYPES
2543   va_start (args, format);
2544 #else
2545   int spaces;
2546   char *format;
2547
2548   va_start (args);
2549   spaces = va_arg (args, int);
2550   format = va_arg (args, char *);
2551 #endif
2552   print_spaces_filtered (spaces, gdb_stdout);
2553   vfprintf_filtered (gdb_stdout, format, args);
2554   va_end (args);
2555 }
2556
2557 /* Easy -- but watch out!
2558
2559    This routine is *not* a replacement for puts()!  puts() appends a newline.
2560    This one doesn't, and had better not!  */
2561
2562 void
2563 puts_filtered (string)
2564      const char *string;
2565 {
2566   fputs_filtered (string, gdb_stdout);
2567 }
2568
2569 void
2570 puts_unfiltered (string)
2571      const char *string;
2572 {
2573   fputs_unfiltered (string, gdb_stdout);
2574 }
2575
2576 /* Return a pointer to N spaces and a null.  The pointer is good
2577    until the next call to here.  */
2578 char *
2579 n_spaces (n)
2580      int n;
2581 {
2582   char *t;
2583   static char *spaces = 0;
2584   static int max_spaces = -1;
2585
2586   if (n > max_spaces)
2587     {
2588       if (spaces)
2589         free (spaces);
2590       spaces = (char *) xmalloc (n + 1);
2591       for (t = spaces + n; t != spaces;)
2592         *--t = ' ';
2593       spaces[n] = '\0';
2594       max_spaces = n;
2595     }
2596
2597   return spaces + max_spaces - n;
2598 }
2599
2600 /* Print N spaces.  */
2601 void
2602 print_spaces_filtered (n, stream)
2603      int n;
2604      GDB_FILE *stream;
2605 {
2606   fputs_filtered (n_spaces (n), stream);
2607 }
2608 \f
2609 /* C++ demangler stuff.  */
2610
2611 /* fprintf_symbol_filtered attempts to demangle NAME, a symbol in language
2612    LANG, using demangling args ARG_MODE, and print it filtered to STREAM.
2613    If the name is not mangled, or the language for the name is unknown, or
2614    demangling is off, the name is printed in its "raw" form. */
2615
2616 void
2617 fprintf_symbol_filtered (stream, name, lang, arg_mode)
2618      GDB_FILE *stream;
2619      char *name;
2620      enum language lang;
2621      int arg_mode;
2622 {
2623   char *demangled;
2624
2625   if (name != NULL)
2626     {
2627       /* If user wants to see raw output, no problem.  */
2628       if (!demangle)
2629         {
2630           fputs_filtered (name, stream);
2631         }
2632       else
2633         {
2634           switch (lang)
2635             {
2636             case language_cplus:
2637               demangled = cplus_demangle (name, arg_mode);
2638               break;
2639             case language_java:
2640               demangled = cplus_demangle (name, arg_mode | DMGL_JAVA);
2641               break;
2642             case language_chill:
2643               demangled = chill_demangle (name);
2644               break;
2645             default:
2646               demangled = NULL;
2647               break;
2648             }
2649           fputs_filtered (demangled ? demangled : name, stream);
2650           if (demangled != NULL)
2651             {
2652               free (demangled);
2653             }
2654         }
2655     }
2656 }
2657
2658 /* Do a strcmp() type operation on STRING1 and STRING2, ignoring any
2659    differences in whitespace.  Returns 0 if they match, non-zero if they
2660    don't (slightly different than strcmp()'s range of return values).
2661
2662    As an extra hack, string1=="FOO(ARGS)" matches string2=="FOO".
2663    This "feature" is useful when searching for matching C++ function names
2664    (such as if the user types 'break FOO', where FOO is a mangled C++
2665    function). */
2666
2667 int
2668 strcmp_iw (string1, string2)
2669      const char *string1;
2670      const char *string2;
2671 {
2672   while ((*string1 != '\0') && (*string2 != '\0'))
2673     {
2674       while (isspace (*string1))
2675         {
2676           string1++;
2677         }
2678       while (isspace (*string2))
2679         {
2680           string2++;
2681         }
2682       if (*string1 != *string2)
2683         {
2684           break;
2685         }
2686       if (*string1 != '\0')
2687         {
2688           string1++;
2689           string2++;
2690         }
2691     }
2692   return (*string1 != '\0' && *string1 != '(') || (*string2 != '\0');
2693 }
2694 \f
2695
2696 /*
2697    ** subset_compare()
2698    **    Answer whether string_to_compare is a full or partial match to
2699    **    template_string.  The partial match must be in sequence starting
2700    **    at index 0.
2701  */
2702 int
2703 subset_compare (string_to_compare, template_string)
2704      char *string_to_compare;
2705      char *template_string;
2706 {
2707   int match;
2708   if (template_string != (char *) NULL && string_to_compare != (char *) NULL &&
2709       strlen (string_to_compare) <= strlen (template_string))
2710     match = (strncmp (template_string,
2711                       string_to_compare,
2712                       strlen (string_to_compare)) == 0);
2713   else
2714     match = 0;
2715   return match;
2716 }
2717
2718
2719 static void pagination_on_command PARAMS ((char *arg, int from_tty));
2720 static void
2721 pagination_on_command (arg, from_tty)
2722      char *arg;
2723      int from_tty;
2724 {
2725   pagination_enabled = 1;
2726 }
2727
2728 static void pagination_on_command PARAMS ((char *arg, int from_tty));
2729 static void
2730 pagination_off_command (arg, from_tty)
2731      char *arg;
2732      int from_tty;
2733 {
2734   pagination_enabled = 0;
2735 }
2736 \f
2737
2738 void
2739 initialize_utils ()
2740 {
2741   struct cmd_list_element *c;
2742
2743   c = add_set_cmd ("width", class_support, var_uinteger,
2744                    (char *) &chars_per_line,
2745                    "Set number of characters gdb thinks are in a line.",
2746                    &setlist);
2747   add_show_from_set (c, &showlist);
2748   c->function.sfunc = set_width_command;
2749
2750   add_show_from_set
2751     (add_set_cmd ("height", class_support,
2752                   var_uinteger, (char *) &lines_per_page,
2753                   "Set number of lines gdb thinks are in a page.", &setlist),
2754      &showlist);
2755
2756   init_page_info ();
2757
2758   /* If the output is not a terminal, don't paginate it.  */
2759   if (!GDB_FILE_ISATTY (gdb_stdout))
2760     lines_per_page = UINT_MAX;
2761
2762   set_width_command ((char *) NULL, 0, c);
2763
2764   add_show_from_set
2765     (add_set_cmd ("demangle", class_support, var_boolean,
2766                   (char *) &demangle,
2767              "Set demangling of encoded C++ names when displaying symbols.",
2768                   &setprintlist),
2769      &showprintlist);
2770
2771   add_show_from_set
2772     (add_set_cmd ("pagination", class_support,
2773                   var_boolean, (char *) &pagination_enabled,
2774                   "Set state of pagination.", &setlist),
2775      &showlist);
2776   if (xdb_commands)
2777     {
2778       add_com ("am", class_support, pagination_on_command,
2779                "Enable pagination");
2780       add_com ("sm", class_support, pagination_off_command,
2781                "Disable pagination");
2782     }
2783
2784   add_show_from_set
2785     (add_set_cmd ("sevenbit-strings", class_support, var_boolean,
2786                   (char *) &sevenbit_strings,
2787                   "Set printing of 8-bit characters in strings as \\nnn.",
2788                   &setprintlist),
2789      &showprintlist);
2790
2791   add_show_from_set
2792     (add_set_cmd ("asm-demangle", class_support, var_boolean,
2793                   (char *) &asm_demangle,
2794                   "Set demangling of C++ names in disassembly listings.",
2795                   &setprintlist),
2796      &showprintlist);
2797 }
2798
2799 /* Machine specific function to handle SIGWINCH signal. */
2800
2801 #ifdef  SIGWINCH_HANDLER_BODY
2802 SIGWINCH_HANDLER_BODY
2803 #endif
2804 \f
2805 /* Support for converting target fp numbers into host DOUBLEST format.  */
2806
2807 /* XXX - This code should really be in libiberty/floatformat.c, however
2808    configuration issues with libiberty made this very difficult to do in the
2809    available time.  */
2810
2811 #include "floatformat.h"
2812 #include <math.h>               /* ldexp */
2813
2814 /* The odds that CHAR_BIT will be anything but 8 are low enough that I'm not
2815    going to bother with trying to muck around with whether it is defined in
2816    a system header, what we do if not, etc.  */
2817 #define FLOATFORMAT_CHAR_BIT 8
2818
2819 static unsigned long get_field PARAMS ((unsigned char *,
2820                                         enum floatformat_byteorders,
2821                                         unsigned int,
2822                                         unsigned int,
2823                                         unsigned int));
2824
2825 /* Extract a field which starts at START and is LEN bytes long.  DATA and
2826    TOTAL_LEN are the thing we are extracting it from, in byteorder ORDER.  */
2827 static unsigned long
2828 get_field (data, order, total_len, start, len)
2829      unsigned char *data;
2830      enum floatformat_byteorders order;
2831      unsigned int total_len;
2832      unsigned int start;
2833      unsigned int len;
2834 {
2835   unsigned long result;
2836   unsigned int cur_byte;
2837   int cur_bitshift;
2838
2839   /* Start at the least significant part of the field.  */
2840   cur_byte = (start + len) / FLOATFORMAT_CHAR_BIT;
2841   if (order == floatformat_little || order == floatformat_littlebyte_bigword)
2842     cur_byte = (total_len / FLOATFORMAT_CHAR_BIT) - cur_byte - 1;
2843   cur_bitshift =
2844     ((start + len) % FLOATFORMAT_CHAR_BIT) - FLOATFORMAT_CHAR_BIT;
2845   result = *(data + cur_byte) >> (-cur_bitshift);
2846   cur_bitshift += FLOATFORMAT_CHAR_BIT;
2847   if (order == floatformat_little || order == floatformat_littlebyte_bigword)
2848     ++cur_byte;
2849   else
2850     --cur_byte;
2851
2852   /* Move towards the most significant part of the field.  */
2853   while (cur_bitshift < len)
2854     {
2855       if (len - cur_bitshift < FLOATFORMAT_CHAR_BIT)
2856         /* This is the last byte; zero out the bits which are not part of
2857            this field.  */
2858         result |=
2859           (*(data + cur_byte) & ((1 << (len - cur_bitshift)) - 1))
2860           << cur_bitshift;
2861       else
2862         result |= *(data + cur_byte) << cur_bitshift;
2863       cur_bitshift += FLOATFORMAT_CHAR_BIT;
2864       if (order == floatformat_little || order == floatformat_littlebyte_bigword)
2865         ++cur_byte;
2866       else
2867         --cur_byte;
2868     }
2869   return result;
2870 }
2871
2872 /* Convert from FMT to a DOUBLEST.
2873    FROM is the address of the extended float.
2874    Store the DOUBLEST in *TO.  */
2875
2876 void
2877 floatformat_to_doublest (fmt, from, to)
2878      const struct floatformat *fmt;
2879      char *from;
2880      DOUBLEST *to;
2881 {
2882   unsigned char *ufrom = (unsigned char *) from;
2883   DOUBLEST dto;
2884   long exponent;
2885   unsigned long mant;
2886   unsigned int mant_bits, mant_off;
2887   int mant_bits_left;
2888   int special_exponent;         /* It's a NaN, denorm or zero */
2889
2890   /* If the mantissa bits are not contiguous from one end of the
2891      mantissa to the other, we need to make a private copy of the
2892      source bytes that is in the right order since the unpacking
2893      algorithm assumes that the bits are contiguous.
2894
2895      Swap the bytes individually rather than accessing them through
2896      "long *" since we have no guarantee that they start on a long
2897      alignment, and also sizeof(long) for the host could be different
2898      than sizeof(long) for the target.  FIXME: Assumes sizeof(long)
2899      for the target is 4. */
2900
2901   if (fmt->byteorder == floatformat_littlebyte_bigword)
2902     {
2903       static unsigned char *newfrom;
2904       unsigned char *swapin, *swapout;
2905       int longswaps;
2906
2907       longswaps = fmt->totalsize / FLOATFORMAT_CHAR_BIT;
2908       longswaps >>= 3;
2909
2910       if (newfrom == NULL)
2911         {
2912           newfrom = (unsigned char *) xmalloc (fmt->totalsize);
2913         }
2914       swapout = newfrom;
2915       swapin = ufrom;
2916       ufrom = newfrom;
2917       while (longswaps-- > 0)
2918         {
2919           /* This is ugly, but efficient */
2920           *swapout++ = swapin[4];
2921           *swapout++ = swapin[5];
2922           *swapout++ = swapin[6];
2923           *swapout++ = swapin[7];
2924           *swapout++ = swapin[0];
2925           *swapout++ = swapin[1];
2926           *swapout++ = swapin[2];
2927           *swapout++ = swapin[3];
2928           swapin += 8;
2929         }
2930     }
2931
2932   exponent = get_field (ufrom, fmt->byteorder, fmt->totalsize,
2933                         fmt->exp_start, fmt->exp_len);
2934   /* Note that if exponent indicates a NaN, we can't really do anything useful
2935      (not knowing if the host has NaN's, or how to build one).  So it will
2936      end up as an infinity or something close; that is OK.  */
2937
2938   mant_bits_left = fmt->man_len;
2939   mant_off = fmt->man_start;
2940   dto = 0.0;
2941
2942   special_exponent = exponent == 0 || exponent == fmt->exp_nan;
2943
2944 /* Don't bias zero's, denorms or NaNs.  */
2945   if (!special_exponent)
2946     exponent -= fmt->exp_bias;
2947
2948   /* Build the result algebraically.  Might go infinite, underflow, etc;
2949      who cares. */
2950
2951 /* If this format uses a hidden bit, explicitly add it in now.  Otherwise,
2952    increment the exponent by one to account for the integer bit.  */
2953
2954   if (!special_exponent)
2955     {
2956       if (fmt->intbit == floatformat_intbit_no)
2957         dto = ldexp (1.0, exponent);
2958       else
2959         exponent++;
2960     }
2961
2962   while (mant_bits_left > 0)
2963     {
2964       mant_bits = min (mant_bits_left, 32);
2965
2966       mant = get_field (ufrom, fmt->byteorder, fmt->totalsize,
2967                         mant_off, mant_bits);
2968
2969       dto += ldexp ((double) mant, exponent - mant_bits);
2970       exponent -= mant_bits;
2971       mant_off += mant_bits;
2972       mant_bits_left -= mant_bits;
2973     }
2974
2975   /* Negate it if negative.  */
2976   if (get_field (ufrom, fmt->byteorder, fmt->totalsize, fmt->sign_start, 1))
2977     dto = -dto;
2978   *to = dto;
2979 }
2980 \f
2981 static void put_field PARAMS ((unsigned char *, enum floatformat_byteorders,
2982                                unsigned int,
2983                                unsigned int,
2984                                unsigned int,
2985                                unsigned long));
2986
2987 /* Set a field which starts at START and is LEN bytes long.  DATA and
2988    TOTAL_LEN are the thing we are extracting it from, in byteorder ORDER.  */
2989 static void
2990 put_field (data, order, total_len, start, len, stuff_to_put)
2991      unsigned char *data;
2992      enum floatformat_byteorders order;
2993      unsigned int total_len;
2994      unsigned int start;
2995      unsigned int len;
2996      unsigned long stuff_to_put;
2997 {
2998   unsigned int cur_byte;
2999   int cur_bitshift;
3000
3001   /* Start at the least significant part of the field.  */
3002   cur_byte = (start + len) / FLOATFORMAT_CHAR_BIT;
3003   if (order == floatformat_little || order == floatformat_littlebyte_bigword)
3004     cur_byte = (total_len / FLOATFORMAT_CHAR_BIT) - cur_byte - 1;
3005   cur_bitshift =
3006     ((start + len) % FLOATFORMAT_CHAR_BIT) - FLOATFORMAT_CHAR_BIT;
3007   *(data + cur_byte) &=
3008     ~(((1 << ((start + len) % FLOATFORMAT_CHAR_BIT)) - 1) << (-cur_bitshift));
3009   *(data + cur_byte) |=
3010     (stuff_to_put & ((1 << FLOATFORMAT_CHAR_BIT) - 1)) << (-cur_bitshift);
3011   cur_bitshift += FLOATFORMAT_CHAR_BIT;
3012   if (order == floatformat_little || order == floatformat_littlebyte_bigword)
3013     ++cur_byte;
3014   else
3015     --cur_byte;
3016
3017   /* Move towards the most significant part of the field.  */
3018   while (cur_bitshift < len)
3019     {
3020       if (len - cur_bitshift < FLOATFORMAT_CHAR_BIT)
3021         {
3022           /* This is the last byte.  */
3023           *(data + cur_byte) &=
3024             ~((1 << (len - cur_bitshift)) - 1);
3025           *(data + cur_byte) |= (stuff_to_put >> cur_bitshift);
3026         }
3027       else
3028         *(data + cur_byte) = ((stuff_to_put >> cur_bitshift)
3029                               & ((1 << FLOATFORMAT_CHAR_BIT) - 1));
3030       cur_bitshift += FLOATFORMAT_CHAR_BIT;
3031       if (order == floatformat_little || order == floatformat_littlebyte_bigword)
3032         ++cur_byte;
3033       else
3034         --cur_byte;
3035     }
3036 }
3037
3038 #ifdef HAVE_LONG_DOUBLE
3039 /* Return the fractional part of VALUE, and put the exponent of VALUE in *EPTR.
3040    The range of the returned value is >= 0.5 and < 1.0.  This is equivalent to
3041    frexp, but operates on the long double data type.  */
3042
3043 static long double ldfrexp PARAMS ((long double value, int *eptr));
3044
3045 static long double
3046 ldfrexp (value, eptr)
3047      long double value;
3048      int *eptr;
3049 {
3050   long double tmp;
3051   int exp;
3052
3053   /* Unfortunately, there are no portable functions for extracting the exponent
3054      of a long double, so we have to do it iteratively by multiplying or dividing
3055      by two until the fraction is between 0.5 and 1.0.  */
3056
3057   if (value < 0.0l)
3058     value = -value;
3059
3060   tmp = 1.0l;
3061   exp = 0;
3062
3063   if (value >= tmp)             /* Value >= 1.0 */
3064     while (value >= tmp)
3065       {
3066         tmp *= 2.0l;
3067         exp++;
3068       }
3069   else if (value != 0.0l)       /* Value < 1.0  and > 0.0 */
3070     {
3071       while (value < tmp)
3072         {
3073           tmp /= 2.0l;
3074           exp--;
3075         }
3076       tmp *= 2.0l;
3077       exp++;
3078     }
3079
3080   *eptr = exp;
3081   return value / tmp;
3082 }
3083 #endif /* HAVE_LONG_DOUBLE */
3084
3085
3086 /* The converse: convert the DOUBLEST *FROM to an extended float
3087    and store where TO points.  Neither FROM nor TO have any alignment
3088    restrictions.  */
3089
3090 void
3091 floatformat_from_doublest (fmt, from, to)
3092      CONST struct floatformat *fmt;
3093      DOUBLEST *from;
3094      char *to;
3095 {
3096   DOUBLEST dfrom;
3097   int exponent;
3098   DOUBLEST mant;
3099   unsigned int mant_bits, mant_off;
3100   int mant_bits_left;
3101   unsigned char *uto = (unsigned char *) to;
3102
3103   memcpy (&dfrom, from, sizeof (dfrom));
3104   memset (uto, 0, fmt->totalsize / FLOATFORMAT_CHAR_BIT);
3105   if (dfrom == 0)
3106     return;                     /* Result is zero */
3107   if (dfrom != dfrom)           /* Result is NaN */
3108     {
3109       /* From is NaN */
3110       put_field (uto, fmt->byteorder, fmt->totalsize, fmt->exp_start,
3111                  fmt->exp_len, fmt->exp_nan);
3112       /* Be sure it's not infinity, but NaN value is irrel */
3113       put_field (uto, fmt->byteorder, fmt->totalsize, fmt->man_start,
3114                  32, 1);
3115       return;
3116     }
3117
3118   /* If negative, set the sign bit.  */
3119   if (dfrom < 0)
3120     {
3121       put_field (uto, fmt->byteorder, fmt->totalsize, fmt->sign_start, 1, 1);
3122       dfrom = -dfrom;
3123     }
3124
3125   if (dfrom + dfrom == dfrom && dfrom != 0.0)   /* Result is Infinity */
3126     {
3127       /* Infinity exponent is same as NaN's.  */
3128       put_field (uto, fmt->byteorder, fmt->totalsize, fmt->exp_start,
3129                  fmt->exp_len, fmt->exp_nan);
3130       /* Infinity mantissa is all zeroes.  */
3131       put_field (uto, fmt->byteorder, fmt->totalsize, fmt->man_start,
3132                  fmt->man_len, 0);
3133       return;
3134     }
3135
3136 #ifdef HAVE_LONG_DOUBLE
3137   mant = ldfrexp (dfrom, &exponent);
3138 #else
3139   mant = frexp (dfrom, &exponent);
3140 #endif
3141
3142   put_field (uto, fmt->byteorder, fmt->totalsize, fmt->exp_start, fmt->exp_len,
3143              exponent + fmt->exp_bias - 1);
3144
3145   mant_bits_left = fmt->man_len;
3146   mant_off = fmt->man_start;
3147   while (mant_bits_left > 0)
3148     {
3149       unsigned long mant_long;
3150       mant_bits = mant_bits_left < 32 ? mant_bits_left : 32;
3151
3152       mant *= 4294967296.0;
3153       mant_long = (unsigned long) mant;
3154       mant -= mant_long;
3155
3156       /* If the integer bit is implicit, then we need to discard it.
3157          If we are discarding a zero, we should be (but are not) creating
3158          a denormalized number which means adjusting the exponent
3159          (I think).  */
3160       if (mant_bits_left == fmt->man_len
3161           && fmt->intbit == floatformat_intbit_no)
3162         {
3163           mant_long <<= 1;
3164           mant_bits -= 1;
3165         }
3166
3167       if (mant_bits < 32)
3168         {
3169           /* The bits we want are in the most significant MANT_BITS bits of
3170              mant_long.  Move them to the least significant.  */
3171           mant_long >>= 32 - mant_bits;
3172         }
3173
3174       put_field (uto, fmt->byteorder, fmt->totalsize,
3175                  mant_off, mant_bits, mant_long);
3176       mant_off += mant_bits;
3177       mant_bits_left -= mant_bits;
3178     }
3179   if (fmt->byteorder == floatformat_littlebyte_bigword)
3180     {
3181       int count;
3182       unsigned char *swaplow = uto;
3183       unsigned char *swaphigh = uto + 4;
3184       unsigned char tmp;
3185
3186       for (count = 0; count < 4; count++)
3187         {
3188           tmp = *swaplow;
3189           *swaplow++ = *swaphigh;
3190           *swaphigh++ = tmp;
3191         }
3192     }
3193 }
3194
3195 /* temporary storage using circular buffer */
3196 #define NUMCELLS 16
3197 #define CELLSIZE 32
3198 static char *
3199 get_cell ()
3200 {
3201   static char buf[NUMCELLS][CELLSIZE];
3202   static int cell = 0;
3203   if (++cell >= NUMCELLS)
3204     cell = 0;
3205   return buf[cell];
3206 }
3207
3208 /* print routines to handle variable size regs, etc.
3209
3210    FIXME: Note that t_addr is a bfd_vma, which is currently either an
3211    unsigned long or unsigned long long, determined at configure time.
3212    If t_addr is an unsigned long long and sizeof (unsigned long long)
3213    is greater than sizeof (unsigned long), then I believe this code will
3214    probably lose, at least for little endian machines.  I believe that
3215    it would also be better to eliminate the switch on the absolute size
3216    of t_addr and replace it with a sequence of if statements that compare
3217    sizeof t_addr with sizeof the various types and do the right thing,
3218    which includes knowing whether or not the host supports long long.
3219    -fnf
3220
3221  */
3222
3223 static int thirty_two = 32;     /* eliminate warning from compiler on 32-bit systems */
3224
3225 char *
3226 paddr (addr)
3227      t_addr addr;
3228 {
3229   char *paddr_str = get_cell ();
3230   switch (sizeof (t_addr))
3231     {
3232     case 8:
3233       sprintf (paddr_str, "%08lx%08lx",
3234                (unsigned long) (addr >> thirty_two), (unsigned long) (addr & 0xffffffff));
3235       break;
3236     case 4:
3237       sprintf (paddr_str, "%08lx", (unsigned long) addr);
3238       break;
3239     case 2:
3240       sprintf (paddr_str, "%04x", (unsigned short) (addr & 0xffff));
3241       break;
3242     default:
3243       sprintf (paddr_str, "%lx", (unsigned long) addr);
3244     }
3245   return paddr_str;
3246 }
3247
3248 char *
3249 preg (reg)
3250      t_reg reg;
3251 {
3252   char *preg_str = get_cell ();
3253   switch (sizeof (t_reg))
3254     {
3255     case 8:
3256       sprintf (preg_str, "%08lx%08lx",
3257                (unsigned long) (reg >> thirty_two), (unsigned long) (reg & 0xffffffff));
3258       break;
3259     case 4:
3260       sprintf (preg_str, "%08lx", (unsigned long) reg);
3261       break;
3262     case 2:
3263       sprintf (preg_str, "%04x", (unsigned short) (reg & 0xffff));
3264       break;
3265     default:
3266       sprintf (preg_str, "%lx", (unsigned long) reg);
3267     }
3268   return preg_str;
3269 }
3270
3271 char *
3272 paddr_nz (addr)
3273      t_addr addr;
3274 {
3275   char *paddr_str = get_cell ();
3276   switch (sizeof (t_addr))
3277     {
3278     case 8:
3279       {
3280         unsigned long high = (unsigned long) (addr >> thirty_two);
3281         if (high == 0)
3282           sprintf (paddr_str, "%lx", (unsigned long) (addr & 0xffffffff));
3283         else
3284           sprintf (paddr_str, "%lx%08lx",
3285                    high, (unsigned long) (addr & 0xffffffff));
3286         break;
3287       }
3288     case 4:
3289       sprintf (paddr_str, "%lx", (unsigned long) addr);
3290       break;
3291     case 2:
3292       sprintf (paddr_str, "%x", (unsigned short) (addr & 0xffff));
3293       break;
3294     default:
3295       sprintf (paddr_str, "%lx", (unsigned long) addr);
3296     }
3297   return paddr_str;
3298 }
3299
3300 char *
3301 preg_nz (reg)
3302      t_reg reg;
3303 {
3304   char *preg_str = get_cell ();
3305   switch (sizeof (t_reg))
3306     {
3307     case 8:
3308       {
3309         unsigned long high = (unsigned long) (reg >> thirty_two);
3310         if (high == 0)
3311           sprintf (preg_str, "%lx", (unsigned long) (reg & 0xffffffff));
3312         else
3313           sprintf (preg_str, "%lx%08lx",
3314                    high, (unsigned long) (reg & 0xffffffff));
3315         break;
3316       }
3317     case 4:
3318       sprintf (preg_str, "%lx", (unsigned long) reg);
3319       break;
3320     case 2:
3321       sprintf (preg_str, "%x", (unsigned short) (reg & 0xffff));
3322       break;
3323     default:
3324       sprintf (preg_str, "%lx", (unsigned long) reg);
3325     }
3326   return preg_str;
3327 }
3328
3329 /* Helper functions for INNER_THAN */
3330 int
3331 core_addr_lessthan (lhs, rhs)
3332      CORE_ADDR lhs;
3333      CORE_ADDR rhs;
3334 {
3335   return (lhs < rhs);
3336 }
3337
3338 int
3339 core_addr_greaterthan (lhs, rhs)
3340      CORE_ADDR lhs;
3341      CORE_ADDR rhs;
3342 {
3343   return (lhs > rhs);
3344 }