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