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