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