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