This commit was generated by cvs2svn to track changes on a CVS vendor
[deliverable/binutils-gdb.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 (NO_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_FLUSH_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 (NO_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 /* NO_MMALLOC */
745
746 #if defined (NO_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 \f
1212 /* Number of lines per page or UINT_MAX if paging is disabled. */
1213 static unsigned int lines_per_page;
1214 /* Number of chars per line or UNIT_MAX is line folding is disabled. */
1215 static unsigned int chars_per_line;
1216 /* Current count of lines printed on this page, chars on this line. */
1217 static unsigned int lines_printed, chars_printed;
1218
1219 /* Buffer and start column of buffered text, for doing smarter word-
1220 wrapping. When someone calls wrap_here(), we start buffering output
1221 that comes through fputs_filtered(). If we see a newline, we just
1222 spit it out and forget about the wrap_here(). If we see another
1223 wrap_here(), we spit it out and remember the newer one. If we see
1224 the end of the line, we spit out a newline, the indent, and then
1225 the buffered output. */
1226
1227 /* Malloc'd buffer with chars_per_line+2 bytes. Contains characters which
1228 are waiting to be output (they have already been counted in chars_printed).
1229 When wrap_buffer[0] is null, the buffer is empty. */
1230 static char *wrap_buffer;
1231
1232 /* Pointer in wrap_buffer to the next character to fill. */
1233 static char *wrap_pointer;
1234
1235 /* String to indent by if the wrap occurs. Must not be NULL if wrap_column
1236 is non-zero. */
1237 static char *wrap_indent;
1238
1239 /* Column number on the screen where wrap_buffer begins, or 0 if wrapping
1240 is not in effect. */
1241 static int wrap_column;
1242
1243 /* ARGSUSED */
1244 static void
1245 set_width_command (args, from_tty, c)
1246 char *args;
1247 int from_tty;
1248 struct cmd_list_element *c;
1249 {
1250 if (!wrap_buffer)
1251 {
1252 wrap_buffer = (char *) xmalloc (chars_per_line + 2);
1253 wrap_buffer[0] = '\0';
1254 }
1255 else
1256 wrap_buffer = (char *) xrealloc (wrap_buffer, chars_per_line + 2);
1257 wrap_pointer = wrap_buffer; /* Start it at the beginning */
1258 }
1259
1260 /* Wait, so the user can read what's on the screen. Prompt the user
1261 to continue by pressing RETURN. */
1262
1263 static void
1264 prompt_for_continue ()
1265 {
1266 char *ignore;
1267 char cont_prompt[120];
1268
1269 if (annotation_level > 1)
1270 printf_unfiltered ("\n\032\032pre-prompt-for-continue\n");
1271
1272 strcpy (cont_prompt,
1273 "---Type <return> to continue, or q <return> to quit---");
1274 if (annotation_level > 1)
1275 strcat (cont_prompt, "\n\032\032prompt-for-continue\n");
1276
1277 /* We must do this *before* we call gdb_readline, else it will eventually
1278 call us -- thinking that we're trying to print beyond the end of the
1279 screen. */
1280 reinitialize_more_filter ();
1281
1282 immediate_quit++;
1283 /* On a real operating system, the user can quit with SIGINT.
1284 But not on GO32.
1285
1286 'q' is provided on all systems so users don't have to change habits
1287 from system to system, and because telling them what to do in
1288 the prompt is more user-friendly than expecting them to think of
1289 SIGINT. */
1290 /* Call readline, not gdb_readline, because GO32 readline handles control-C
1291 whereas control-C to gdb_readline will cause the user to get dumped
1292 out to DOS. */
1293 ignore = readline (cont_prompt);
1294
1295 if (annotation_level > 1)
1296 printf_unfiltered ("\n\032\032post-prompt-for-continue\n");
1297
1298 if (ignore)
1299 {
1300 char *p = ignore;
1301 while (*p == ' ' || *p == '\t')
1302 ++p;
1303 if (p[0] == 'q')
1304 request_quit (SIGINT);
1305 free (ignore);
1306 }
1307 immediate_quit--;
1308
1309 /* Now we have to do this again, so that GDB will know that it doesn't
1310 need to save the ---Type <return>--- line at the top of the screen. */
1311 reinitialize_more_filter ();
1312
1313 dont_repeat (); /* Forget prev cmd -- CR won't repeat it. */
1314 }
1315
1316 /* Reinitialize filter; ie. tell it to reset to original values. */
1317
1318 void
1319 reinitialize_more_filter ()
1320 {
1321 lines_printed = 0;
1322 chars_printed = 0;
1323 }
1324
1325 /* Indicate that if the next sequence of characters overflows the line,
1326 a newline should be inserted here rather than when it hits the end.
1327 If INDENT is non-null, it is a string to be printed to indent the
1328 wrapped part on the next line. INDENT must remain accessible until
1329 the next call to wrap_here() or until a newline is printed through
1330 fputs_filtered().
1331
1332 If the line is already overfull, we immediately print a newline and
1333 the indentation, and disable further wrapping.
1334
1335 If we don't know the width of lines, but we know the page height,
1336 we must not wrap words, but should still keep track of newlines
1337 that were explicitly printed.
1338
1339 INDENT should not contain tabs, as that will mess up the char count
1340 on the next line. FIXME.
1341
1342 This routine is guaranteed to force out any output which has been
1343 squirreled away in the wrap_buffer, so wrap_here ((char *)0) can be
1344 used to force out output from the wrap_buffer. */
1345
1346 void
1347 wrap_here(indent)
1348 char *indent;
1349 {
1350 /* This should have been allocated, but be paranoid anyway. */
1351 if (!wrap_buffer)
1352 abort ();
1353
1354 if (wrap_buffer[0])
1355 {
1356 *wrap_pointer = '\0';
1357 fputs_unfiltered (wrap_buffer, gdb_stdout);
1358 }
1359 wrap_pointer = wrap_buffer;
1360 wrap_buffer[0] = '\0';
1361 if (chars_per_line == UINT_MAX) /* No line overflow checking */
1362 {
1363 wrap_column = 0;
1364 }
1365 else if (chars_printed >= chars_per_line)
1366 {
1367 puts_filtered ("\n");
1368 if (indent != NULL)
1369 puts_filtered (indent);
1370 wrap_column = 0;
1371 }
1372 else
1373 {
1374 wrap_column = chars_printed;
1375 if (indent == NULL)
1376 wrap_indent = "";
1377 else
1378 wrap_indent = indent;
1379 }
1380 }
1381
1382 /* Ensure that whatever gets printed next, using the filtered output
1383 commands, starts at the beginning of the line. I.E. if there is
1384 any pending output for the current line, flush it and start a new
1385 line. Otherwise do nothing. */
1386
1387 void
1388 begin_line ()
1389 {
1390 if (chars_printed > 0)
1391 {
1392 puts_filtered ("\n");
1393 }
1394 }
1395
1396
1397 GDB_FILE *
1398 gdb_fopen (name, mode)
1399 char * name;
1400 char * mode;
1401 {
1402 return fopen (name, mode);
1403 }
1404
1405 void
1406 gdb_flush (stream)
1407 FILE *stream;
1408 {
1409 if (flush_hook
1410 && (stream == gdb_stdout
1411 || stream == gdb_stderr))
1412 {
1413 flush_hook (stream);
1414 return;
1415 }
1416
1417 fflush (stream);
1418 }
1419
1420 /* Like fputs but if FILTER is true, pause after every screenful.
1421
1422 Regardless of FILTER can wrap at points other than the final
1423 character of a line.
1424
1425 Unlike fputs, fputs_maybe_filtered does not return a value.
1426 It is OK for LINEBUFFER to be NULL, in which case just don't print
1427 anything.
1428
1429 Note that a longjmp to top level may occur in this routine (only if
1430 FILTER is true) (since prompt_for_continue may do so) so this
1431 routine should not be called when cleanups are not in place. */
1432
1433 static void
1434 fputs_maybe_filtered (linebuffer, stream, filter)
1435 const char *linebuffer;
1436 FILE *stream;
1437 int filter;
1438 {
1439 const char *lineptr;
1440
1441 if (linebuffer == 0)
1442 return;
1443
1444 /* Don't do any filtering if it is disabled. */
1445 if (stream != gdb_stdout
1446 || (lines_per_page == UINT_MAX && chars_per_line == UINT_MAX))
1447 {
1448 fputs_unfiltered (linebuffer, stream);
1449 return;
1450 }
1451
1452 /* Go through and output each character. Show line extension
1453 when this is necessary; prompt user for new page when this is
1454 necessary. */
1455
1456 lineptr = linebuffer;
1457 while (*lineptr)
1458 {
1459 /* Possible new page. */
1460 if (filter &&
1461 (lines_printed >= lines_per_page - 1))
1462 prompt_for_continue ();
1463
1464 while (*lineptr && *lineptr != '\n')
1465 {
1466 /* Print a single line. */
1467 if (*lineptr == '\t')
1468 {
1469 if (wrap_column)
1470 *wrap_pointer++ = '\t';
1471 else
1472 fputc_unfiltered ('\t', stream);
1473 /* Shifting right by 3 produces the number of tab stops
1474 we have already passed, and then adding one and
1475 shifting left 3 advances to the next tab stop. */
1476 chars_printed = ((chars_printed >> 3) + 1) << 3;
1477 lineptr++;
1478 }
1479 else
1480 {
1481 if (wrap_column)
1482 *wrap_pointer++ = *lineptr;
1483 else
1484 fputc_unfiltered (*lineptr, stream);
1485 chars_printed++;
1486 lineptr++;
1487 }
1488
1489 if (chars_printed >= chars_per_line)
1490 {
1491 unsigned int save_chars = chars_printed;
1492
1493 chars_printed = 0;
1494 lines_printed++;
1495 /* If we aren't actually wrapping, don't output newline --
1496 if chars_per_line is right, we probably just overflowed
1497 anyway; if it's wrong, let us keep going. */
1498 if (wrap_column)
1499 fputc_unfiltered ('\n', stream);
1500
1501 /* Possible new page. */
1502 if (lines_printed >= lines_per_page - 1)
1503 prompt_for_continue ();
1504
1505 /* Now output indentation and wrapped string */
1506 if (wrap_column)
1507 {
1508 fputs_unfiltered (wrap_indent, stream);
1509 *wrap_pointer = '\0'; /* Null-terminate saved stuff */
1510 fputs_unfiltered (wrap_buffer, stream); /* and eject it */
1511 /* FIXME, this strlen is what prevents wrap_indent from
1512 containing tabs. However, if we recurse to print it
1513 and count its chars, we risk trouble if wrap_indent is
1514 longer than (the user settable) chars_per_line.
1515 Note also that this can set chars_printed > chars_per_line
1516 if we are printing a long string. */
1517 chars_printed = strlen (wrap_indent)
1518 + (save_chars - wrap_column);
1519 wrap_pointer = wrap_buffer; /* Reset buffer */
1520 wrap_buffer[0] = '\0';
1521 wrap_column = 0; /* And disable fancy wrap */
1522 }
1523 }
1524 }
1525
1526 if (*lineptr == '\n')
1527 {
1528 chars_printed = 0;
1529 wrap_here ((char *)0); /* Spit out chars, cancel further wraps */
1530 lines_printed++;
1531 fputc_unfiltered ('\n', stream);
1532 lineptr++;
1533 }
1534 }
1535 }
1536
1537 void
1538 fputs_filtered (linebuffer, stream)
1539 const char *linebuffer;
1540 FILE *stream;
1541 {
1542 fputs_maybe_filtered (linebuffer, stream, 1);
1543 }
1544
1545 int
1546 putchar_unfiltered (c)
1547 int c;
1548 {
1549 char buf[2];
1550
1551 buf[0] = c;
1552 buf[1] = 0;
1553 fputs_unfiltered (buf, gdb_stdout);
1554 return c;
1555 }
1556
1557 int
1558 fputc_unfiltered (c, stream)
1559 int c;
1560 FILE * stream;
1561 {
1562 char buf[2];
1563
1564 buf[0] = c;
1565 buf[1] = 0;
1566 fputs_unfiltered (buf, stream);
1567 return c;
1568 }
1569
1570
1571 /* puts_debug is like fputs_unfiltered, except it prints special
1572 characters in printable fashion. */
1573
1574 void
1575 puts_debug (prefix, string, suffix)
1576 char *prefix;
1577 char *string;
1578 char *suffix;
1579 {
1580 int ch;
1581
1582 /* Print prefix and suffix after each line. */
1583 static int new_line = 1;
1584 static int carriage_return = 0;
1585 static char *prev_prefix = "";
1586 static char *prev_suffix = "";
1587
1588 if (*string == '\n')
1589 carriage_return = 0;
1590
1591 /* If the prefix is changing, print the previous suffix, a new line,
1592 and the new prefix. */
1593 if ((carriage_return || (strcmp(prev_prefix, prefix) != 0)) && !new_line)
1594 {
1595 fputs_unfiltered (prev_suffix, gdb_stderr);
1596 fputs_unfiltered ("\n", gdb_stderr);
1597 fputs_unfiltered (prefix, gdb_stderr);
1598 }
1599
1600 /* Print prefix if we printed a newline during the previous call. */
1601 if (new_line)
1602 {
1603 new_line = 0;
1604 fputs_unfiltered (prefix, gdb_stderr);
1605 }
1606
1607 prev_prefix = prefix;
1608 prev_suffix = suffix;
1609
1610 /* Output characters in a printable format. */
1611 while ((ch = *string++) != '\0')
1612 {
1613 switch (ch)
1614 {
1615 default:
1616 if (isprint (ch))
1617 fputc_unfiltered (ch, gdb_stderr);
1618
1619 else
1620 fprintf_unfiltered (gdb_stderr, "\\%03o", ch);
1621 break;
1622
1623 case '\\': fputs_unfiltered ("\\\\", gdb_stderr); break;
1624 case '\b': fputs_unfiltered ("\\b", gdb_stderr); break;
1625 case '\f': fputs_unfiltered ("\\f", gdb_stderr); break;
1626 case '\n': new_line = 1;
1627 fputs_unfiltered ("\\n", gdb_stderr); break;
1628 case '\r': fputs_unfiltered ("\\r", gdb_stderr); break;
1629 case '\t': fputs_unfiltered ("\\t", gdb_stderr); break;
1630 case '\v': fputs_unfiltered ("\\v", gdb_stderr); break;
1631 }
1632
1633 carriage_return = ch == '\r';
1634 }
1635
1636 /* Print suffix if we printed a newline. */
1637 if (new_line)
1638 {
1639 fputs_unfiltered (suffix, gdb_stderr);
1640 fputs_unfiltered ("\n", gdb_stderr);
1641 }
1642 }
1643
1644
1645 /* Print a variable number of ARGS using format FORMAT. If this
1646 information is going to put the amount written (since the last call
1647 to REINITIALIZE_MORE_FILTER or the last page break) over the page size,
1648 call prompt_for_continue to get the users permision to continue.
1649
1650 Unlike fprintf, this function does not return a value.
1651
1652 We implement three variants, vfprintf (takes a vararg list and stream),
1653 fprintf (takes a stream to write on), and printf (the usual).
1654
1655 Note also that a longjmp to top level may occur in this routine
1656 (since prompt_for_continue may do so) so this routine should not be
1657 called when cleanups are not in place. */
1658
1659 static void
1660 vfprintf_maybe_filtered (stream, format, args, filter)
1661 FILE *stream;
1662 const char *format;
1663 va_list args;
1664 int filter;
1665 {
1666 char *linebuffer;
1667 struct cleanup *old_cleanups;
1668
1669 vasprintf (&linebuffer, format, args);
1670 if (linebuffer == NULL)
1671 {
1672 fputs_unfiltered ("\ngdb: virtual memory exhausted.\n", gdb_stderr);
1673 exit (1);
1674 }
1675 old_cleanups = make_cleanup (free, linebuffer);
1676 fputs_maybe_filtered (linebuffer, stream, filter);
1677 do_cleanups (old_cleanups);
1678 }
1679
1680
1681 void
1682 vfprintf_filtered (stream, format, args)
1683 FILE *stream;
1684 const char *format;
1685 va_list args;
1686 {
1687 vfprintf_maybe_filtered (stream, format, args, 1);
1688 }
1689
1690 void
1691 vfprintf_unfiltered (stream, format, args)
1692 FILE *stream;
1693 const char *format;
1694 va_list args;
1695 {
1696 char *linebuffer;
1697 struct cleanup *old_cleanups;
1698
1699 vasprintf (&linebuffer, format, args);
1700 if (linebuffer == NULL)
1701 {
1702 fputs_unfiltered ("\ngdb: virtual memory exhausted.\n", gdb_stderr);
1703 exit (1);
1704 }
1705 old_cleanups = make_cleanup (free, linebuffer);
1706 fputs_unfiltered (linebuffer, stream);
1707 do_cleanups (old_cleanups);
1708 }
1709
1710 void
1711 vprintf_filtered (format, args)
1712 const char *format;
1713 va_list args;
1714 {
1715 vfprintf_maybe_filtered (gdb_stdout, format, args, 1);
1716 }
1717
1718 void
1719 vprintf_unfiltered (format, args)
1720 const char *format;
1721 va_list args;
1722 {
1723 vfprintf_unfiltered (gdb_stdout, format, args);
1724 }
1725
1726 /* VARARGS */
1727 void
1728 #ifdef ANSI_PROTOTYPES
1729 fprintf_filtered (FILE *stream, const char *format, ...)
1730 #else
1731 fprintf_filtered (va_alist)
1732 va_dcl
1733 #endif
1734 {
1735 va_list args;
1736 #ifdef ANSI_PROTOTYPES
1737 va_start (args, format);
1738 #else
1739 FILE *stream;
1740 char *format;
1741
1742 va_start (args);
1743 stream = va_arg (args, FILE *);
1744 format = va_arg (args, char *);
1745 #endif
1746 vfprintf_filtered (stream, format, args);
1747 va_end (args);
1748 }
1749
1750 /* VARARGS */
1751 void
1752 #ifdef ANSI_PROTOTYPES
1753 fprintf_unfiltered (FILE *stream, const char *format, ...)
1754 #else
1755 fprintf_unfiltered (va_alist)
1756 va_dcl
1757 #endif
1758 {
1759 va_list args;
1760 #ifdef ANSI_PROTOTYPES
1761 va_start (args, format);
1762 #else
1763 FILE *stream;
1764 char *format;
1765
1766 va_start (args);
1767 stream = va_arg (args, FILE *);
1768 format = va_arg (args, char *);
1769 #endif
1770 vfprintf_unfiltered (stream, format, args);
1771 va_end (args);
1772 }
1773
1774 /* Like fprintf_filtered, but prints its result indented.
1775 Called as fprintfi_filtered (spaces, stream, format, ...); */
1776
1777 /* VARARGS */
1778 void
1779 #ifdef ANSI_PROTOTYPES
1780 fprintfi_filtered (int spaces, FILE *stream, const char *format, ...)
1781 #else
1782 fprintfi_filtered (va_alist)
1783 va_dcl
1784 #endif
1785 {
1786 va_list args;
1787 #ifdef ANSI_PROTOTYPES
1788 va_start (args, format);
1789 #else
1790 int spaces;
1791 FILE *stream;
1792 char *format;
1793
1794 va_start (args);
1795 spaces = va_arg (args, int);
1796 stream = va_arg (args, FILE *);
1797 format = va_arg (args, char *);
1798 #endif
1799 print_spaces_filtered (spaces, stream);
1800
1801 vfprintf_filtered (stream, format, args);
1802 va_end (args);
1803 }
1804
1805
1806 /* VARARGS */
1807 void
1808 #ifdef ANSI_PROTOTYPES
1809 printf_filtered (const char *format, ...)
1810 #else
1811 printf_filtered (va_alist)
1812 va_dcl
1813 #endif
1814 {
1815 va_list args;
1816 #ifdef ANSI_PROTOTYPES
1817 va_start (args, format);
1818 #else
1819 char *format;
1820
1821 va_start (args);
1822 format = va_arg (args, char *);
1823 #endif
1824 vfprintf_filtered (gdb_stdout, format, args);
1825 va_end (args);
1826 }
1827
1828
1829 /* VARARGS */
1830 void
1831 #ifdef ANSI_PROTOTYPES
1832 printf_unfiltered (const char *format, ...)
1833 #else
1834 printf_unfiltered (va_alist)
1835 va_dcl
1836 #endif
1837 {
1838 va_list args;
1839 #ifdef ANSI_PROTOTYPES
1840 va_start (args, format);
1841 #else
1842 char *format;
1843
1844 va_start (args);
1845 format = va_arg (args, char *);
1846 #endif
1847 vfprintf_unfiltered (gdb_stdout, format, args);
1848 va_end (args);
1849 }
1850
1851 /* Like printf_filtered, but prints it's result indented.
1852 Called as printfi_filtered (spaces, format, ...); */
1853
1854 /* VARARGS */
1855 void
1856 #ifdef ANSI_PROTOTYPES
1857 printfi_filtered (int spaces, const char *format, ...)
1858 #else
1859 printfi_filtered (va_alist)
1860 va_dcl
1861 #endif
1862 {
1863 va_list args;
1864 #ifdef ANSI_PROTOTYPES
1865 va_start (args, format);
1866 #else
1867 int spaces;
1868 char *format;
1869
1870 va_start (args);
1871 spaces = va_arg (args, int);
1872 format = va_arg (args, char *);
1873 #endif
1874 print_spaces_filtered (spaces, gdb_stdout);
1875 vfprintf_filtered (gdb_stdout, format, args);
1876 va_end (args);
1877 }
1878
1879 /* Easy -- but watch out!
1880
1881 This routine is *not* a replacement for puts()! puts() appends a newline.
1882 This one doesn't, and had better not! */
1883
1884 void
1885 puts_filtered (string)
1886 const char *string;
1887 {
1888 fputs_filtered (string, gdb_stdout);
1889 }
1890
1891 void
1892 puts_unfiltered (string)
1893 const char *string;
1894 {
1895 fputs_unfiltered (string, gdb_stdout);
1896 }
1897
1898 /* Return a pointer to N spaces and a null. The pointer is good
1899 until the next call to here. */
1900 char *
1901 n_spaces (n)
1902 int n;
1903 {
1904 register char *t;
1905 static char *spaces;
1906 static int max_spaces;
1907
1908 if (n > max_spaces)
1909 {
1910 if (spaces)
1911 free (spaces);
1912 spaces = (char *) xmalloc (n+1);
1913 for (t = spaces+n; t != spaces;)
1914 *--t = ' ';
1915 spaces[n] = '\0';
1916 max_spaces = n;
1917 }
1918
1919 return spaces + max_spaces - n;
1920 }
1921
1922 /* Print N spaces. */
1923 void
1924 print_spaces_filtered (n, stream)
1925 int n;
1926 FILE *stream;
1927 {
1928 fputs_filtered (n_spaces (n), stream);
1929 }
1930 \f
1931 /* C++ demangler stuff. */
1932
1933 /* fprintf_symbol_filtered attempts to demangle NAME, a symbol in language
1934 LANG, using demangling args ARG_MODE, and print it filtered to STREAM.
1935 If the name is not mangled, or the language for the name is unknown, or
1936 demangling is off, the name is printed in its "raw" form. */
1937
1938 void
1939 fprintf_symbol_filtered (stream, name, lang, arg_mode)
1940 FILE *stream;
1941 char *name;
1942 enum language lang;
1943 int arg_mode;
1944 {
1945 char *demangled;
1946
1947 if (name != NULL)
1948 {
1949 /* If user wants to see raw output, no problem. */
1950 if (!demangle)
1951 {
1952 fputs_filtered (name, stream);
1953 }
1954 else
1955 {
1956 switch (lang)
1957 {
1958 case language_cplus:
1959 demangled = cplus_demangle (name, arg_mode);
1960 break;
1961 case language_java:
1962 demangled = cplus_demangle (name, arg_mode | DMGL_JAVA);
1963 break;
1964 case language_chill:
1965 demangled = chill_demangle (name);
1966 break;
1967 default:
1968 demangled = NULL;
1969 break;
1970 }
1971 fputs_filtered (demangled ? demangled : name, stream);
1972 if (demangled != NULL)
1973 {
1974 free (demangled);
1975 }
1976 }
1977 }
1978 }
1979
1980 /* Do a strcmp() type operation on STRING1 and STRING2, ignoring any
1981 differences in whitespace. Returns 0 if they match, non-zero if they
1982 don't (slightly different than strcmp()'s range of return values).
1983
1984 As an extra hack, string1=="FOO(ARGS)" matches string2=="FOO".
1985 This "feature" is useful when searching for matching C++ function names
1986 (such as if the user types 'break FOO', where FOO is a mangled C++
1987 function). */
1988
1989 int
1990 strcmp_iw (string1, string2)
1991 const char *string1;
1992 const char *string2;
1993 {
1994 while ((*string1 != '\0') && (*string2 != '\0'))
1995 {
1996 while (isspace (*string1))
1997 {
1998 string1++;
1999 }
2000 while (isspace (*string2))
2001 {
2002 string2++;
2003 }
2004 if (*string1 != *string2)
2005 {
2006 break;
2007 }
2008 if (*string1 != '\0')
2009 {
2010 string1++;
2011 string2++;
2012 }
2013 }
2014 return (*string1 != '\0' && *string1 != '(') || (*string2 != '\0');
2015 }
2016
2017 \f
2018 void
2019 initialize_utils ()
2020 {
2021 struct cmd_list_element *c;
2022
2023 c = add_set_cmd ("width", class_support, var_uinteger,
2024 (char *)&chars_per_line,
2025 "Set number of characters gdb thinks are in a line.",
2026 &setlist);
2027 add_show_from_set (c, &showlist);
2028 c->function.sfunc = set_width_command;
2029
2030 add_show_from_set
2031 (add_set_cmd ("height", class_support,
2032 var_uinteger, (char *)&lines_per_page,
2033 "Set number of lines gdb thinks are in a page.", &setlist),
2034 &showlist);
2035
2036 /* These defaults will be used if we are unable to get the correct
2037 values from termcap. */
2038 #if defined(__GO32__)
2039 lines_per_page = ScreenRows();
2040 chars_per_line = ScreenCols();
2041 #else
2042 lines_per_page = 24;
2043 chars_per_line = 80;
2044
2045 #if !defined (MPW) && !defined (_WIN32)
2046 /* No termcap under MPW, although might be cool to do something
2047 by looking at worksheet or console window sizes. */
2048 /* Initialize the screen height and width from termcap. */
2049 {
2050 char *termtype = getenv ("TERM");
2051
2052 /* Positive means success, nonpositive means failure. */
2053 int status;
2054
2055 /* 2048 is large enough for all known terminals, according to the
2056 GNU termcap manual. */
2057 char term_buffer[2048];
2058
2059 if (termtype)
2060 {
2061 status = tgetent (term_buffer, termtype);
2062 if (status > 0)
2063 {
2064 int val;
2065
2066 val = tgetnum ("li");
2067 if (val >= 0)
2068 lines_per_page = val;
2069 else
2070 /* The number of lines per page is not mentioned
2071 in the terminal description. This probably means
2072 that paging is not useful (e.g. emacs shell window),
2073 so disable paging. */
2074 lines_per_page = UINT_MAX;
2075
2076 val = tgetnum ("co");
2077 if (val >= 0)
2078 chars_per_line = val;
2079 }
2080 }
2081 }
2082 #endif /* MPW */
2083
2084 #if defined(SIGWINCH) && defined(SIGWINCH_HANDLER)
2085
2086 /* If there is a better way to determine the window size, use it. */
2087 SIGWINCH_HANDLER ();
2088 #endif
2089 #endif
2090 /* If the output is not a terminal, don't paginate it. */
2091 if (!ISATTY (gdb_stdout))
2092 lines_per_page = UINT_MAX;
2093
2094 set_width_command ((char *)NULL, 0, c);
2095
2096 add_show_from_set
2097 (add_set_cmd ("demangle", class_support, var_boolean,
2098 (char *)&demangle,
2099 "Set demangling of encoded C++ names when displaying symbols.",
2100 &setprintlist),
2101 &showprintlist);
2102
2103 add_show_from_set
2104 (add_set_cmd ("sevenbit-strings", class_support, var_boolean,
2105 (char *)&sevenbit_strings,
2106 "Set printing of 8-bit characters in strings as \\nnn.",
2107 &setprintlist),
2108 &showprintlist);
2109
2110 add_show_from_set
2111 (add_set_cmd ("asm-demangle", class_support, var_boolean,
2112 (char *)&asm_demangle,
2113 "Set demangling of C++ names in disassembly listings.",
2114 &setprintlist),
2115 &showprintlist);
2116 }
2117
2118 /* Machine specific function to handle SIGWINCH signal. */
2119
2120 #ifdef SIGWINCH_HANDLER_BODY
2121 SIGWINCH_HANDLER_BODY
2122 #endif
2123 \f
2124 /* Support for converting target fp numbers into host DOUBLEST format. */
2125
2126 /* XXX - This code should really be in libiberty/floatformat.c, however
2127 configuration issues with libiberty made this very difficult to do in the
2128 available time. */
2129
2130 #include "floatformat.h"
2131 #include <math.h> /* ldexp */
2132
2133 /* The odds that CHAR_BIT will be anything but 8 are low enough that I'm not
2134 going to bother with trying to muck around with whether it is defined in
2135 a system header, what we do if not, etc. */
2136 #define FLOATFORMAT_CHAR_BIT 8
2137
2138 static unsigned long get_field PARAMS ((unsigned char *,
2139 enum floatformat_byteorders,
2140 unsigned int,
2141 unsigned int,
2142 unsigned int));
2143
2144 /* Extract a field which starts at START and is LEN bytes long. DATA and
2145 TOTAL_LEN are the thing we are extracting it from, in byteorder ORDER. */
2146 static unsigned long
2147 get_field (data, order, total_len, start, len)
2148 unsigned char *data;
2149 enum floatformat_byteorders order;
2150 unsigned int total_len;
2151 unsigned int start;
2152 unsigned int len;
2153 {
2154 unsigned long result;
2155 unsigned int cur_byte;
2156 int cur_bitshift;
2157
2158 /* Start at the least significant part of the field. */
2159 cur_byte = (start + len) / FLOATFORMAT_CHAR_BIT;
2160 if (order == floatformat_little || order == floatformat_littlebyte_bigword)
2161 cur_byte = (total_len / FLOATFORMAT_CHAR_BIT) - cur_byte - 1;
2162 cur_bitshift =
2163 ((start + len) % FLOATFORMAT_CHAR_BIT) - FLOATFORMAT_CHAR_BIT;
2164 result = *(data + cur_byte) >> (-cur_bitshift);
2165 cur_bitshift += FLOATFORMAT_CHAR_BIT;
2166 if (order == floatformat_little || order == floatformat_littlebyte_bigword)
2167 ++cur_byte;
2168 else
2169 --cur_byte;
2170
2171 /* Move towards the most significant part of the field. */
2172 while (cur_bitshift < len)
2173 {
2174 if (len - cur_bitshift < FLOATFORMAT_CHAR_BIT)
2175 /* This is the last byte; zero out the bits which are not part of
2176 this field. */
2177 result |=
2178 (*(data + cur_byte) & ((1 << (len - cur_bitshift)) - 1))
2179 << cur_bitshift;
2180 else
2181 result |= *(data + cur_byte) << cur_bitshift;
2182 cur_bitshift += FLOATFORMAT_CHAR_BIT;
2183 if (order == floatformat_little || order == floatformat_littlebyte_bigword)
2184 ++cur_byte;
2185 else
2186 --cur_byte;
2187 }
2188 return result;
2189 }
2190
2191 /* Convert from FMT to a DOUBLEST.
2192 FROM is the address of the extended float.
2193 Store the DOUBLEST in *TO. */
2194
2195 void
2196 floatformat_to_doublest (fmt, from, to)
2197 const struct floatformat *fmt;
2198 char *from;
2199 DOUBLEST *to;
2200 {
2201 unsigned char *ufrom = (unsigned char *)from;
2202 DOUBLEST dto;
2203 long exponent;
2204 unsigned long mant;
2205 unsigned int mant_bits, mant_off;
2206 int mant_bits_left;
2207 int special_exponent; /* It's a NaN, denorm or zero */
2208
2209 /* If the mantissa bits are not contiguous from one end of the
2210 mantissa to the other, we need to make a private copy of the
2211 source bytes that is in the right order since the unpacking
2212 algorithm assumes that the bits are contiguous.
2213
2214 Swap the bytes individually rather than accessing them through
2215 "long *" since we have no guarantee that they start on a long
2216 alignment, and also sizeof(long) for the host could be different
2217 than sizeof(long) for the target. FIXME: Assumes sizeof(long)
2218 for the target is 4. */
2219
2220 if (fmt -> byteorder == floatformat_littlebyte_bigword)
2221 {
2222 static unsigned char *newfrom;
2223 unsigned char *swapin, *swapout;
2224 int longswaps;
2225
2226 longswaps = fmt -> totalsize / FLOATFORMAT_CHAR_BIT;
2227 longswaps >>= 3;
2228
2229 if (newfrom == NULL)
2230 {
2231 newfrom = xmalloc (fmt -> totalsize);
2232 }
2233 swapout = newfrom;
2234 swapin = ufrom;
2235 ufrom = newfrom;
2236 while (longswaps-- > 0)
2237 {
2238 /* This is ugly, but efficient */
2239 *swapout++ = swapin[4];
2240 *swapout++ = swapin[5];
2241 *swapout++ = swapin[6];
2242 *swapout++ = swapin[7];
2243 *swapout++ = swapin[0];
2244 *swapout++ = swapin[1];
2245 *swapout++ = swapin[2];
2246 *swapout++ = swapin[3];
2247 swapin += 8;
2248 }
2249 }
2250
2251 exponent = get_field (ufrom, fmt->byteorder, fmt->totalsize,
2252 fmt->exp_start, fmt->exp_len);
2253 /* Note that if exponent indicates a NaN, we can't really do anything useful
2254 (not knowing if the host has NaN's, or how to build one). So it will
2255 end up as an infinity or something close; that is OK. */
2256
2257 mant_bits_left = fmt->man_len;
2258 mant_off = fmt->man_start;
2259 dto = 0.0;
2260
2261 special_exponent = exponent == 0 || exponent == fmt->exp_nan;
2262
2263 /* Don't bias zero's, denorms or NaNs. */
2264 if (!special_exponent)
2265 exponent -= fmt->exp_bias;
2266
2267 /* Build the result algebraically. Might go infinite, underflow, etc;
2268 who cares. */
2269
2270 /* If this format uses a hidden bit, explicitly add it in now. Otherwise,
2271 increment the exponent by one to account for the integer bit. */
2272
2273 if (!special_exponent)
2274 if (fmt->intbit == floatformat_intbit_no)
2275 dto = ldexp (1.0, exponent);
2276 else
2277 exponent++;
2278
2279 while (mant_bits_left > 0)
2280 {
2281 mant_bits = min (mant_bits_left, 32);
2282
2283 mant = get_field (ufrom, fmt->byteorder, fmt->totalsize,
2284 mant_off, mant_bits);
2285
2286 dto += ldexp ((double)mant, exponent - mant_bits);
2287 exponent -= mant_bits;
2288 mant_off += mant_bits;
2289 mant_bits_left -= mant_bits;
2290 }
2291
2292 /* Negate it if negative. */
2293 if (get_field (ufrom, fmt->byteorder, fmt->totalsize, fmt->sign_start, 1))
2294 dto = -dto;
2295 *to = dto;
2296 }
2297 \f
2298 static void put_field PARAMS ((unsigned char *, enum floatformat_byteorders,
2299 unsigned int,
2300 unsigned int,
2301 unsigned int,
2302 unsigned long));
2303
2304 /* Set a field which starts at START and is LEN bytes long. DATA and
2305 TOTAL_LEN are the thing we are extracting it from, in byteorder ORDER. */
2306 static void
2307 put_field (data, order, total_len, start, len, stuff_to_put)
2308 unsigned char *data;
2309 enum floatformat_byteorders order;
2310 unsigned int total_len;
2311 unsigned int start;
2312 unsigned int len;
2313 unsigned long stuff_to_put;
2314 {
2315 unsigned int cur_byte;
2316 int cur_bitshift;
2317
2318 /* Start at the least significant part of the field. */
2319 cur_byte = (start + len) / FLOATFORMAT_CHAR_BIT;
2320 if (order == floatformat_little || order == floatformat_littlebyte_bigword)
2321 cur_byte = (total_len / FLOATFORMAT_CHAR_BIT) - cur_byte - 1;
2322 cur_bitshift =
2323 ((start + len) % FLOATFORMAT_CHAR_BIT) - FLOATFORMAT_CHAR_BIT;
2324 *(data + cur_byte) &=
2325 ~(((1 << ((start + len) % FLOATFORMAT_CHAR_BIT)) - 1) << (-cur_bitshift));
2326 *(data + cur_byte) |=
2327 (stuff_to_put & ((1 << FLOATFORMAT_CHAR_BIT) - 1)) << (-cur_bitshift);
2328 cur_bitshift += FLOATFORMAT_CHAR_BIT;
2329 if (order == floatformat_little || order == floatformat_littlebyte_bigword)
2330 ++cur_byte;
2331 else
2332 --cur_byte;
2333
2334 /* Move towards the most significant part of the field. */
2335 while (cur_bitshift < len)
2336 {
2337 if (len - cur_bitshift < FLOATFORMAT_CHAR_BIT)
2338 {
2339 /* This is the last byte. */
2340 *(data + cur_byte) &=
2341 ~((1 << (len - cur_bitshift)) - 1);
2342 *(data + cur_byte) |= (stuff_to_put >> cur_bitshift);
2343 }
2344 else
2345 *(data + cur_byte) = ((stuff_to_put >> cur_bitshift)
2346 & ((1 << FLOATFORMAT_CHAR_BIT) - 1));
2347 cur_bitshift += FLOATFORMAT_CHAR_BIT;
2348 if (order == floatformat_little || order == floatformat_littlebyte_bigword)
2349 ++cur_byte;
2350 else
2351 --cur_byte;
2352 }
2353 }
2354
2355 #ifdef HAVE_LONG_DOUBLE
2356 /* Return the fractional part of VALUE, and put the exponent of VALUE in *EPTR.
2357 The range of the returned value is >= 0.5 and < 1.0. This is equivalent to
2358 frexp, but operates on the long double data type. */
2359
2360 static long double ldfrexp PARAMS ((long double value, int *eptr));
2361
2362 static long double
2363 ldfrexp (value, eptr)
2364 long double value;
2365 int *eptr;
2366 {
2367 long double tmp;
2368 int exp;
2369
2370 /* Unfortunately, there are no portable functions for extracting the exponent
2371 of a long double, so we have to do it iteratively by multiplying or dividing
2372 by two until the fraction is between 0.5 and 1.0. */
2373
2374 if (value < 0.0l)
2375 value = -value;
2376
2377 tmp = 1.0l;
2378 exp = 0;
2379
2380 if (value >= tmp) /* Value >= 1.0 */
2381 while (value >= tmp)
2382 {
2383 tmp *= 2.0l;
2384 exp++;
2385 }
2386 else if (value != 0.0l) /* Value < 1.0 and > 0.0 */
2387 {
2388 while (value < tmp)
2389 {
2390 tmp /= 2.0l;
2391 exp--;
2392 }
2393 tmp *= 2.0l;
2394 exp++;
2395 }
2396
2397 *eptr = exp;
2398 return value/tmp;
2399 }
2400 #endif /* HAVE_LONG_DOUBLE */
2401
2402
2403 /* The converse: convert the DOUBLEST *FROM to an extended float
2404 and store where TO points. Neither FROM nor TO have any alignment
2405 restrictions. */
2406
2407 void
2408 floatformat_from_doublest (fmt, from, to)
2409 CONST struct floatformat *fmt;
2410 DOUBLEST *from;
2411 char *to;
2412 {
2413 DOUBLEST dfrom;
2414 int exponent;
2415 DOUBLEST mant;
2416 unsigned int mant_bits, mant_off;
2417 int mant_bits_left;
2418 unsigned char *uto = (unsigned char *)to;
2419
2420 memcpy (&dfrom, from, sizeof (dfrom));
2421 memset (uto, 0, fmt->totalsize / FLOATFORMAT_CHAR_BIT);
2422 if (dfrom == 0)
2423 return; /* Result is zero */
2424 if (dfrom != dfrom) /* Result is NaN */
2425 {
2426 /* From is NaN */
2427 put_field (uto, fmt->byteorder, fmt->totalsize, fmt->exp_start,
2428 fmt->exp_len, fmt->exp_nan);
2429 /* Be sure it's not infinity, but NaN value is irrel */
2430 put_field (uto, fmt->byteorder, fmt->totalsize, fmt->man_start,
2431 32, 1);
2432 return;
2433 }
2434
2435 /* If negative, set the sign bit. */
2436 if (dfrom < 0)
2437 {
2438 put_field (uto, fmt->byteorder, fmt->totalsize, fmt->sign_start, 1, 1);
2439 dfrom = -dfrom;
2440 }
2441
2442 if (dfrom + dfrom == dfrom && dfrom != 0.0) /* Result is Infinity */
2443 {
2444 /* Infinity exponent is same as NaN's. */
2445 put_field (uto, fmt->byteorder, fmt->totalsize, fmt->exp_start,
2446 fmt->exp_len, fmt->exp_nan);
2447 /* Infinity mantissa is all zeroes. */
2448 put_field (uto, fmt->byteorder, fmt->totalsize, fmt->man_start,
2449 fmt->man_len, 0);
2450 return;
2451 }
2452
2453 #ifdef HAVE_LONG_DOUBLE
2454 mant = ldfrexp (dfrom, &exponent);
2455 #else
2456 mant = frexp (dfrom, &exponent);
2457 #endif
2458
2459 put_field (uto, fmt->byteorder, fmt->totalsize, fmt->exp_start, fmt->exp_len,
2460 exponent + fmt->exp_bias - 1);
2461
2462 mant_bits_left = fmt->man_len;
2463 mant_off = fmt->man_start;
2464 while (mant_bits_left > 0)
2465 {
2466 unsigned long mant_long;
2467 mant_bits = mant_bits_left < 32 ? mant_bits_left : 32;
2468
2469 mant *= 4294967296.0;
2470 mant_long = (unsigned long)mant;
2471 mant -= mant_long;
2472
2473 /* If the integer bit is implicit, then we need to discard it.
2474 If we are discarding a zero, we should be (but are not) creating
2475 a denormalized number which means adjusting the exponent
2476 (I think). */
2477 if (mant_bits_left == fmt->man_len
2478 && fmt->intbit == floatformat_intbit_no)
2479 {
2480 mant_long <<= 1;
2481 mant_bits -= 1;
2482 }
2483
2484 if (mant_bits < 32)
2485 {
2486 /* The bits we want are in the most significant MANT_BITS bits of
2487 mant_long. Move them to the least significant. */
2488 mant_long >>= 32 - mant_bits;
2489 }
2490
2491 put_field (uto, fmt->byteorder, fmt->totalsize,
2492 mant_off, mant_bits, mant_long);
2493 mant_off += mant_bits;
2494 mant_bits_left -= mant_bits;
2495 }
2496 if (fmt -> byteorder == floatformat_littlebyte_bigword)
2497 {
2498 int count;
2499 unsigned char *swaplow = uto;
2500 unsigned char *swaphigh = uto + 4;
2501 unsigned char tmp;
2502
2503 for (count = 0; count < 4; count++)
2504 {
2505 tmp = *swaplow;
2506 *swaplow++ = *swaphigh;
2507 *swaphigh++ = tmp;
2508 }
2509 }
2510 }
2511
2512 /* temporary storage using circular buffer */
2513 #define NUMCELLS 16
2514 #define CELLSIZE 32
2515 static char*
2516 get_cell()
2517 {
2518 static char buf[NUMCELLS][CELLSIZE];
2519 static int cell=0;
2520 if (++cell>=NUMCELLS) cell=0;
2521 return buf[cell];
2522 }
2523
2524 /* print routines to handle variable size regs, etc.
2525
2526 FIXME: Note that t_addr is a bfd_vma, which is currently either an
2527 unsigned long or unsigned long long, determined at configure time.
2528 If t_addr is an unsigned long long and sizeof (unsigned long long)
2529 is greater than sizeof (unsigned long), then I believe this code will
2530 probably lose, at least for little endian machines. I believe that
2531 it would also be better to eliminate the switch on the absolute size
2532 of t_addr and replace it with a sequence of if statements that compare
2533 sizeof t_addr with sizeof the various types and do the right thing,
2534 which includes knowing whether or not the host supports long long.
2535 -fnf
2536
2537 */
2538
2539 static int thirty_two = 32; /* eliminate warning from compiler on 32-bit systems */
2540
2541 char*
2542 paddr(addr)
2543 t_addr addr;
2544 {
2545 char *paddr_str=get_cell();
2546 switch (sizeof(t_addr))
2547 {
2548 case 8:
2549 sprintf (paddr_str, "%08lx%08lx",
2550 (unsigned long) (addr >> thirty_two), (unsigned long) (addr & 0xffffffff));
2551 break;
2552 case 4:
2553 sprintf (paddr_str, "%08lx", (unsigned long) addr);
2554 break;
2555 case 2:
2556 sprintf (paddr_str, "%04x", (unsigned short) (addr & 0xffff));
2557 break;
2558 default:
2559 sprintf (paddr_str, "%lx", (unsigned long) addr);
2560 }
2561 return paddr_str;
2562 }
2563
2564 char*
2565 preg(reg)
2566 t_reg reg;
2567 {
2568 char *preg_str=get_cell();
2569 switch (sizeof(t_reg))
2570 {
2571 case 8:
2572 sprintf (preg_str, "%08lx%08lx",
2573 (unsigned long) (reg >> thirty_two), (unsigned long) (reg & 0xffffffff));
2574 break;
2575 case 4:
2576 sprintf (preg_str, "%08lx", (unsigned long) reg);
2577 break;
2578 case 2:
2579 sprintf (preg_str, "%04x", (unsigned short) (reg & 0xffff));
2580 break;
2581 default:
2582 sprintf (preg_str, "%lx", (unsigned long) reg);
2583 }
2584 return preg_str;
2585 }
2586
2587 char*
2588 paddr_nz(addr)
2589 t_addr addr;
2590 {
2591 char *paddr_str=get_cell();
2592 switch (sizeof(t_addr))
2593 {
2594 case 8:
2595 {
2596 unsigned long high = (unsigned long) (addr >> thirty_two);
2597 if (high == 0)
2598 sprintf (paddr_str, "%lx", (unsigned long) (addr & 0xffffffff));
2599 else
2600 sprintf (paddr_str, "%lx%08lx",
2601 high, (unsigned long) (addr & 0xffffffff));
2602 break;
2603 }
2604 case 4:
2605 sprintf (paddr_str, "%lx", (unsigned long) addr);
2606 break;
2607 case 2:
2608 sprintf (paddr_str, "%x", (unsigned short) (addr & 0xffff));
2609 break;
2610 default:
2611 sprintf (paddr_str,"%lx", (unsigned long) addr);
2612 }
2613 return paddr_str;
2614 }
2615
2616 char*
2617 preg_nz(reg)
2618 t_reg reg;
2619 {
2620 char *preg_str=get_cell();
2621 switch (sizeof(t_reg))
2622 {
2623 case 8:
2624 {
2625 unsigned long high = (unsigned long) (reg >> thirty_two);
2626 if (high == 0)
2627 sprintf (preg_str, "%lx", (unsigned long) (reg & 0xffffffff));
2628 else
2629 sprintf (preg_str, "%lx%08lx",
2630 high, (unsigned long) (reg & 0xffffffff));
2631 break;
2632 }
2633 case 4:
2634 sprintf (preg_str, "%lx", (unsigned long) reg);
2635 break;
2636 case 2:
2637 sprintf (preg_str, "%x", (unsigned short) (reg & 0xffff));
2638 break;
2639 default:
2640 sprintf (preg_str, "%lx", (unsigned long) reg);
2641 }
2642 return preg_str;
2643 }
This page took 0.123577 seconds and 5 git commands to generate.