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