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