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