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