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