1 /* General utility routines for GDB, the GNU debugger.
2 Copyright 1986, 89, 90, 91, 92, 95, 96, 1998 Free Software Foundation, Inc.
4 This file is part of GDB.
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.
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.
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. */
20 /* $FreeBSD: src/contrib/gdb/gdb/utils.c,v 1.1.1.2.2.1 2002/09/01 23:30:00 obrien Exp $ */
24 #include "gdb_string.h"
36 /* SunOS's curses.h has a '#define reg register' in it. Thank you Sun. */
47 #include "expression.h"
51 #include <readline/readline.h>
53 /* readline defines this. */
56 void (*error_begin_hook) PARAMS ((void));
58 /* Prototypes for local functions */
60 static void vfprintf_maybe_filtered PARAMS ((GDB_FILE *, const char *,
63 static void fputs_maybe_filtered PARAMS ((const char *, GDB_FILE *, int));
65 #if defined (USE_MMALLOC) && !defined (NO_MMCHECK)
66 static void malloc_botch PARAMS ((void));
70 fatal_dump_core PARAMS((char *, ...));
73 prompt_for_continue PARAMS ((void));
76 set_width_command PARAMS ((char *, int, struct cmd_list_element *));
79 set_width PARAMS ((void));
81 /* If this definition isn't overridden by the header files, assume
82 that isatty and fileno exist on this system. */
84 #define ISATTY(FP) (isatty (fileno (FP)))
87 #ifndef GDB_FILE_ISATTY
88 #define GDB_FILE_ISATTY(GDB_FILE_PTR) (gdb_file_isatty(GDB_FILE_PTR))
91 /* Chain of cleanup actions established with make_cleanup,
92 to be executed if an error happens. */
94 static struct cleanup *cleanup_chain; /* cleaned up after a failed command */
95 static struct cleanup *final_cleanup_chain; /* cleaned up when gdb exits */
96 static struct cleanup *run_cleanup_chain; /* cleaned up on each 'run' */
98 /* Nonzero if we have job control. */
102 /* Nonzero means a quit has been requested. */
106 /* Nonzero means quit immediately if Control-C is typed now, rather
107 than waiting until QUIT is executed. Be careful in setting this;
108 code which executes with immediate_quit set has to be very careful
109 about being able to deal with being interrupted at any time. It is
110 almost always better to use QUIT; the only exception I can think of
111 is being able to quit out of a system call (using EINTR loses if
112 the SIGINT happens between the previous QUIT and the system call).
113 To immediately quit in the case in which a SIGINT happens between
114 the previous QUIT and setting immediate_quit (desirable anytime we
115 expect to block), call QUIT after setting immediate_quit. */
119 /* Nonzero means that encoded C++ names should be printed out in their
120 C++ form rather than raw. */
124 /* Nonzero means that encoded C++ names should be printed out in their
125 C++ form even in assembler language displays. If this is set, but
126 DEMANGLE is zero, names are printed raw, i.e. DEMANGLE controls. */
128 int asm_demangle = 0;
130 /* Nonzero means that strings with character values >0x7F should be printed
131 as octal escapes. Zero means just print the value (e.g. it's an
132 international character, and the terminal or window can cope.) */
134 int sevenbit_strings = 0;
136 /* String to be printed before error messages, if any. */
138 char *error_pre_print;
140 /* String to be printed before quit messages, if any. */
142 char *quit_pre_print;
144 /* String to be printed before warning messages, if any. */
146 char *warning_pre_print = "\nwarning: ";
148 int pagination_enabled = 1;
151 /* Add a new cleanup to the cleanup_chain,
152 and return the previous chain pointer
153 to be passed later to do_cleanups or discard_cleanups.
154 Args are FUNCTION to clean up with, and ARG to pass to it. */
157 make_cleanup (function, arg)
158 void (*function) PARAMS ((PTR));
161 return make_my_cleanup (&cleanup_chain, function, arg);
165 make_final_cleanup (function, arg)
166 void (*function) PARAMS ((PTR));
169 return make_my_cleanup (&final_cleanup_chain, function, arg);
172 make_run_cleanup (function, arg)
173 void (*function) PARAMS ((PTR));
176 return make_my_cleanup (&run_cleanup_chain, function, arg);
179 make_my_cleanup (pmy_chain, function, arg)
180 struct cleanup **pmy_chain;
181 void (*function) PARAMS ((PTR));
184 register struct cleanup *new
185 = (struct cleanup *) xmalloc (sizeof (struct cleanup));
186 register struct cleanup *old_chain = *pmy_chain;
188 new->next = *pmy_chain;
189 new->function = function;
196 /* Discard cleanups and do the actions they describe
197 until we get back to the point OLD_CHAIN in the cleanup_chain. */
200 do_cleanups (old_chain)
201 register struct cleanup *old_chain;
203 do_my_cleanups (&cleanup_chain, old_chain);
207 do_final_cleanups (old_chain)
208 register struct cleanup *old_chain;
210 do_my_cleanups (&final_cleanup_chain, old_chain);
214 do_run_cleanups (old_chain)
215 register struct cleanup *old_chain;
217 do_my_cleanups (&run_cleanup_chain, old_chain);
221 do_my_cleanups (pmy_chain, old_chain)
222 register struct cleanup **pmy_chain;
223 register struct cleanup *old_chain;
225 register struct cleanup *ptr;
226 while ((ptr = *pmy_chain) != old_chain)
228 *pmy_chain = ptr->next; /* Do this first incase recursion */
229 (*ptr->function) (ptr->arg);
234 /* Discard cleanups, not doing the actions they describe,
235 until we get back to the point OLD_CHAIN in the cleanup_chain. */
238 discard_cleanups (old_chain)
239 register struct cleanup *old_chain;
241 discard_my_cleanups (&cleanup_chain, old_chain);
245 discard_final_cleanups (old_chain)
246 register struct cleanup *old_chain;
248 discard_my_cleanups (&final_cleanup_chain, old_chain);
252 discard_my_cleanups (pmy_chain, old_chain)
253 register struct cleanup **pmy_chain;
254 register struct cleanup *old_chain;
256 register struct cleanup *ptr;
257 while ((ptr = *pmy_chain) != old_chain)
259 *pmy_chain = ptr->next;
264 /* Set the cleanup_chain to 0, and return the old cleanup chain. */
268 return save_my_cleanups (&cleanup_chain);
272 save_final_cleanups ()
274 return save_my_cleanups (&final_cleanup_chain);
278 save_my_cleanups (pmy_chain)
279 struct cleanup **pmy_chain;
281 struct cleanup *old_chain = *pmy_chain;
287 /* Restore the cleanup chain from a previously saved chain. */
289 restore_cleanups (chain)
290 struct cleanup *chain;
292 restore_my_cleanups (&cleanup_chain, chain);
296 restore_final_cleanups (chain)
297 struct cleanup *chain;
299 restore_my_cleanups (&final_cleanup_chain, chain);
303 restore_my_cleanups (pmy_chain, chain)
304 struct cleanup **pmy_chain;
305 struct cleanup *chain;
310 /* This function is useful for cleanups.
314 old_chain = make_cleanup (free_current_contents, &foo);
316 to arrange to free the object thus allocated. */
319 free_current_contents (location)
325 /* Provide a known function that does nothing, to use as a base for
326 for a possibly long chain of cleanups. This is useful where we
327 use the cleanup chain for handling normal cleanups as well as dealing
328 with cleanups that need to be done as a result of a call to error().
329 In such cases, we may not be certain where the first cleanup is, unless
330 we have a do-nothing one to always use as the base. */
340 /* Print a warning message. Way to use this is to call warning_begin,
341 output the warning message (use unfiltered output to gdb_stderr),
342 ending in a newline. There is not currently a warning_end that you
343 call afterwards, but such a thing might be added if it is useful
344 for a GUI to separate warning messages from other output.
346 FIXME: Why do warnings use unfiltered output and errors filtered?
347 Is this anything other than a historical accident? */
352 target_terminal_ours ();
353 wrap_here(""); /* Force out any buffered output */
354 gdb_flush (gdb_stdout);
355 if (warning_pre_print)
356 fprintf_unfiltered (gdb_stderr, warning_pre_print);
359 /* Print a warning message.
360 The first argument STRING is the warning message, used as a fprintf string,
361 and the remaining args are passed as arguments to it.
362 The primary difference between warnings and errors is that a warning
363 does not force the return to command level. */
367 #ifdef ANSI_PROTOTYPES
368 warning (const char *string, ...)
375 #ifdef ANSI_PROTOTYPES
376 va_start (args, string);
381 string = va_arg (args, char *);
384 (*warning_hook) (string, args);
388 vfprintf_unfiltered (gdb_stderr, string, args);
389 fprintf_unfiltered (gdb_stderr, "\n");
394 /* Start the printing of an error message. Way to use this is to call
395 this, output the error message (use filtered output to gdb_stderr
396 (FIXME: Some callers, like memory_error, use gdb_stdout)), ending
397 in a newline, and then call return_to_top_level (RETURN_ERROR).
398 error() provides a convenient way to do this for the special case
399 that the error message can be formatted with a single printf call,
400 but this is more general. */
404 if (error_begin_hook)
407 target_terminal_ours ();
408 wrap_here (""); /* Force out any buffered output */
409 gdb_flush (gdb_stdout);
411 annotate_error_begin ();
414 fprintf_filtered (gdb_stderr, error_pre_print);
417 /* Print an error message and return to command level.
418 The first argument STRING is the error message, used as a fprintf string,
419 and the remaining args are passed as arguments to it. */
423 #ifdef ANSI_PROTOTYPES
424 error (const char *string, ...)
431 #ifdef ANSI_PROTOTYPES
432 va_start (args, string);
441 #ifdef ANSI_PROTOTYPES
442 vfprintf_filtered (gdb_stderr, string, args);
447 string1 = va_arg (args, char *);
448 vfprintf_filtered (gdb_stderr, string1, args);
451 fprintf_filtered (gdb_stderr, "\n");
453 return_to_top_level (RETURN_ERROR);
458 /* Print an error message and exit reporting failure.
459 This is for a error that we cannot continue from.
460 The arguments are printed a la printf.
462 This function cannot be declared volatile (NORETURN) in an
463 ANSI environment because exit() is not declared volatile. */
467 #ifdef ANSI_PROTOTYPES
468 fatal (char *string, ...)
475 #ifdef ANSI_PROTOTYPES
476 va_start (args, string);
480 string = va_arg (args, char *);
482 fprintf_unfiltered (gdb_stderr, "\ngdb: ");
483 vfprintf_unfiltered (gdb_stderr, string, args);
484 fprintf_unfiltered (gdb_stderr, "\n");
489 /* Print an error message and exit, dumping core.
490 The arguments are printed a la printf (). */
494 #ifdef ANSI_PROTOTYPES
495 fatal_dump_core (char *string, ...)
497 fatal_dump_core (va_alist)
502 #ifdef ANSI_PROTOTYPES
503 va_start (args, string);
508 string = va_arg (args, char *);
510 /* "internal error" is always correct, since GDB should never dump
511 core, no matter what the input. */
512 fprintf_unfiltered (gdb_stderr, "\ngdb internal error: ");
513 vfprintf_unfiltered (gdb_stderr, string, args);
514 fprintf_unfiltered (gdb_stderr, "\n");
517 signal (SIGQUIT, SIG_DFL);
518 kill (getpid (), SIGQUIT);
519 /* We should never get here, but just in case... */
523 /* The strerror() function can return NULL for errno values that are
524 out of range. Provide a "safe" version that always returns a
528 safe_strerror (errnum)
534 if ((msg = strerror (errnum)) == NULL)
536 sprintf (buf, "(undocumented errno %d)", errnum);
542 /* The strsignal() function can return NULL for signal values that are
543 out of range. Provide a "safe" version that always returns a
547 safe_strsignal (signo)
553 if ((msg = strsignal (signo)) == NULL)
555 sprintf (buf, "(undocumented signal %d)", signo);
562 /* Print the system error message for errno, and also mention STRING
563 as the file name for which the error was encountered.
564 Then return to command level. */
567 perror_with_name (string)
573 err = safe_strerror (errno);
574 combined = (char *) alloca (strlen (err) + strlen (string) + 3);
575 strcpy (combined, string);
576 strcat (combined, ": ");
577 strcat (combined, err);
579 /* I understand setting these is a matter of taste. Still, some people
580 may clear errno but not know about bfd_error. Doing this here is not
582 bfd_set_error (bfd_error_no_error);
585 error ("%s.", combined);
588 /* Print the system error message for ERRCODE, and also mention STRING
589 as the file name for which the error was encountered. */
592 print_sys_errmsg (string, errcode)
599 err = safe_strerror (errcode);
600 combined = (char *) alloca (strlen (err) + strlen (string) + 3);
601 strcpy (combined, string);
602 strcat (combined, ": ");
603 strcat (combined, err);
605 /* We want anything which was printed on stdout to come out first, before
607 gdb_flush (gdb_stdout);
608 fprintf_unfiltered (gdb_stderr, "%s.\n", combined);
611 /* Control C eventually causes this to be called, at a convenient time. */
616 serial_t gdb_stdout_serial = serial_fdopen (1);
618 target_terminal_ours ();
620 /* We want all output to appear now, before we print "Quit". We
621 have 3 levels of buffering we have to flush (it's possible that
622 some of these should be changed to flush the lower-level ones
625 /* 1. The _filtered buffer. */
626 wrap_here ((char *)0);
628 /* 2. The stdio buffer. */
629 gdb_flush (gdb_stdout);
630 gdb_flush (gdb_stderr);
632 /* 3. The system-level buffer. */
633 SERIAL_DRAIN_OUTPUT (gdb_stdout_serial);
634 SERIAL_UN_FDOPEN (gdb_stdout_serial);
636 annotate_error_begin ();
638 /* Don't use *_filtered; we don't want to prompt the user to continue. */
640 fprintf_unfiltered (gdb_stderr, quit_pre_print);
643 /* If there is no terminal switching for this target, then we can't
644 possibly get screwed by the lack of job control. */
645 || current_target.to_terminal_ours == NULL)
646 fprintf_unfiltered (gdb_stderr, "Quit\n");
648 fprintf_unfiltered (gdb_stderr,
649 "Quit (expect signal SIGINT when the program is resumed)\n");
650 return_to_top_level (RETURN_QUIT);
654 #if defined(__GO32__)
656 /* In the absence of signals, poll keyboard for a quit.
657 Called from #define QUIT pollquit() in xm-go32.h. */
672 /* We just ignore it */
673 /* FIXME!! Don't think this actually works! */
674 fprintf_unfiltered (gdb_stderr, "CTRL-A to quit, CTRL-B to quit harder\n");
679 #elif defined(_MSC_VER) /* should test for wingdb instead? */
682 * Windows translates all keyboard and mouse events
683 * into a message which is appended to the message
684 * queue for the process.
689 int k = win32pollquit();
696 #else /* !defined(__GO32__) && !defined(_MSC_VER) */
700 /* Done by signals */
703 #endif /* !defined(__GO32__) && !defined(_MSC_VER) */
709 if (quit_flag || immediate_quit)
713 /* Control C comes here */
720 /* Restore the signal handler. Harmless with BSD-style signals, needed
721 for System V-style signals. So just always do it, rather than worrying
722 about USG defines and stuff like that. */
723 signal (signo, request_quit);
734 /* Memory management stuff (malloc friends). */
736 /* Make a substitute size_t for non-ANSI compilers. */
738 #ifndef HAVE_STDDEF_H
740 #define size_t unsigned int
744 #if !defined (USE_MMALLOC)
751 return malloc (size);
755 mrealloc (md, ptr, size)
760 if (ptr == 0) /* Guard against old realloc's */
761 return malloc (size);
763 return realloc (ptr, size);
774 #endif /* USE_MMALLOC */
776 #if !defined (USE_MMALLOC) || defined (NO_MMCHECK)
784 #else /* Have mmalloc and want corruption checking */
789 fatal_dump_core ("Memory corruption");
792 /* Attempt to install hooks in mmalloc/mrealloc/mfree for the heap specified
793 by MD, to detect memory corruption. Note that MD may be NULL to specify
794 the default heap that grows via sbrk.
796 Note that for freshly created regions, we must call mmcheckf prior to any
797 mallocs in the region. Otherwise, any region which was allocated prior to
798 installing the checking hooks, which is later reallocated or freed, will
799 fail the checks! The mmcheck function only allows initial hooks to be
800 installed before the first mmalloc. However, anytime after we have called
801 mmcheck the first time to install the checking hooks, we can call it again
802 to update the function pointer to the memory corruption handler.
804 Returns zero on failure, non-zero on success. */
806 #ifndef MMCHECK_FORCE
807 #define MMCHECK_FORCE 0
814 if (!mmcheckf (md, malloc_botch, MMCHECK_FORCE))
816 /* Don't use warning(), which relies on current_target being set
817 to something other than dummy_target, until after
818 initialize_all_files(). */
821 (gdb_stderr, "warning: failed to install memory consistency checks; ");
823 (gdb_stderr, "configuration should define NO_MMCHECK or MMCHECK_FORCE\n");
829 #endif /* Have mmalloc and want corruption checking */
831 /* Called when a memory allocation fails, with the number of bytes of
832 memory requested in SIZE. */
840 fatal ("virtual memory exhausted: can't allocate %ld bytes.", size);
844 fatal ("virtual memory exhausted.");
848 /* Like mmalloc but get error if no storage available, and protect against
849 the caller wanting to allocate zero bytes. Whether to return NULL for
850 a zero byte request, or translate the request into a request for one
851 byte of zero'd storage, is a religious issue. */
864 else if ((val = mmalloc (md, size)) == NULL)
871 /* Like mrealloc but get error if no storage available. */
874 xmrealloc (md, ptr, size)
883 val = mrealloc (md, ptr, size);
887 val = mmalloc (md, size);
896 /* Like malloc but get error if no storage available, and protect against
897 the caller wanting to allocate zero bytes. */
900 USE_FROM_LIBIBERTY_NOW_xmalloc (size)
903 return (xmmalloc ((PTR) NULL, size));
906 /* Like mrealloc but get error if no storage available. */
909 USE_FROM_LIBIBERTY_NOW_xrealloc (ptr, size)
913 return (xmrealloc ((PTR) NULL, ptr, size));
917 /* My replacement for the read system call.
918 Used like `read' but keeps going if `read' returns too soon. */
921 myread (desc, addr, len)
931 val = read (desc, addr, len);
942 /* Make a copy of the string at PTR with SIZE characters
943 (and add a null character at the end in the copy).
944 Uses malloc to get the space. Returns the address of the copy. */
947 savestring (ptr, size)
951 register char *p = (char *) xmalloc (size + 1);
952 memcpy (p, ptr, size);
958 msavestring (md, ptr, size)
963 register char *p = (char *) xmmalloc (md, size + 1);
964 memcpy (p, ptr, size);
969 /* The "const" is so it compiles under DGUX (which prototypes strsave
970 in <string.h>. FIXME: This should be named "xstrsave", shouldn't it?
971 Doesn't real strsave return NULL if out of memory? */
976 return savestring (ptr, strlen (ptr));
984 return (msavestring (md, ptr, strlen (ptr)));
988 print_spaces (n, file)
990 register GDB_FILE *file;
992 if (file->ts_streamtype == astring)
996 gdb_file_adjust_strbuf (n, file);
997 p = file->ts_strbuf + strlen (file->ts_strbuf);
1005 fputc (' ', file->ts_filestream);
1009 /* Print a host address. */
1012 gdb_print_address (addr, stream)
1017 /* We could use the %p conversion specifier to fprintf if we had any
1018 way of knowing whether this host supports it. But the following
1019 should work on the Alpha and on 32 bit machines. */
1021 fprintf_filtered (stream, "0x%lx", (unsigned long)addr);
1024 /* Ask user a y-or-n question and return 1 iff answer is yes.
1025 Takes three args which are given to printf to print the question.
1026 The first, a control string, should end in "? ".
1027 It should not say how to answer, because we do that. */
1031 #ifdef ANSI_PROTOTYPES
1032 query (char *ctlstr, ...)
1039 register int answer;
1043 #ifdef ANSI_PROTOTYPES
1044 va_start (args, ctlstr);
1048 ctlstr = va_arg (args, char *);
1053 return query_hook (ctlstr, args);
1056 /* Automatically answer "yes" if input is not from a terminal. */
1057 if (!input_from_terminal_p ())
1060 /* FIXME Automatically answer "yes" if called from MacGDB. */
1067 wrap_here (""); /* Flush any buffered output */
1068 gdb_flush (gdb_stdout);
1070 if (annotation_level > 1)
1071 printf_filtered ("\n\032\032pre-query\n");
1073 vfprintf_filtered (gdb_stdout, ctlstr, args);
1074 printf_filtered ("(y or n) ");
1076 if (annotation_level > 1)
1077 printf_filtered ("\n\032\032query\n");
1080 /* If not in MacGDB, move to a new line so the entered line doesn't
1081 have a prompt on the front of it. */
1083 fputs_unfiltered ("\n", gdb_stdout);
1087 gdb_flush (gdb_stdout);
1090 if (!tui_version || cmdWin == tuiWinWithFocus())
1092 answer = fgetc (stdin);
1096 answer = (unsigned char)tuiBufferGetc();
1099 clearerr (stdin); /* in case of C-d */
1100 if (answer == EOF) /* C-d */
1105 /* Eat rest of input line, to EOF or newline */
1106 if ((answer != '\n') || (tui_version && answer != '\r'))
1110 if (!tui_version || cmdWin == tuiWinWithFocus())
1112 ans2 = fgetc (stdin);
1116 ans2 = (unsigned char)tuiBufferGetc();
1120 while (ans2 != EOF && ans2 != '\n' && ans2 != '\r');
1121 TUIDO(((TuiOpaqueFuncPtr)tui_vStartNewLines, 1));
1135 printf_filtered ("Please answer y or n.\n");
1138 if (annotation_level > 1)
1139 printf_filtered ("\n\032\032post-query\n");
1144 /* Parse a C escape sequence. STRING_PTR points to a variable
1145 containing a pointer to the string to parse. That pointer
1146 should point to the character after the \. That pointer
1147 is updated past the characters we use. The value of the
1148 escape sequence is returned.
1150 A negative value means the sequence \ newline was seen,
1151 which is supposed to be equivalent to nothing at all.
1153 If \ is followed by a null character, we return a negative
1154 value and leave the string pointer pointing at the null character.
1156 If \ is followed by 000, we return 0 and leave the string pointer
1157 after the zeros. A value of 0 does not mean end of string. */
1160 parse_escape (string_ptr)
1163 register int c = *(*string_ptr)++;
1167 return 007; /* Bell (alert) char */
1170 case 'e': /* Escape character */
1188 c = *(*string_ptr)++;
1190 c = parse_escape (string_ptr);
1193 return (c & 0200) | (c & 037);
1204 register int i = c - '0';
1205 register int count = 0;
1208 if ((c = *(*string_ptr)++) >= '0' && c <= '7')
1226 /* Print the character C on STREAM as part of the contents of a literal
1227 string whose delimiter is QUOTER. Note that this routine should only
1228 be call for printing things which are independent of the language
1229 of the program being debugged. */
1232 gdb_printchar (c, stream, quoter)
1238 c &= 0xFF; /* Avoid sign bit follies */
1240 if ( c < 0x20 || /* Low control chars */
1241 (c >= 0x7F && c < 0xA0) || /* DEL, High controls */
1242 (sevenbit_strings && c >= 0x80)) { /* high order bit set */
1246 fputs_filtered ("\\n", stream);
1249 fputs_filtered ("\\b", stream);
1252 fputs_filtered ("\\t", stream);
1255 fputs_filtered ("\\f", stream);
1258 fputs_filtered ("\\r", stream);
1261 fputs_filtered ("\\e", stream);
1264 fputs_filtered ("\\a", stream);
1267 fprintf_filtered (stream, "\\%.3o", (unsigned int) c);
1271 if (c == '\\' || c == quoter)
1272 fputs_filtered ("\\", stream);
1273 fprintf_filtered (stream, "%c", c);
1280 static char * hexlate = "0123456789abcdef" ;
1281 int fmthex(inbuf,outbuff,length,linelength)
1282 unsigned char * inbuf ;
1283 unsigned char * outbuff;
1287 unsigned char byte , nib ;
1292 if (outlength >= linelength) break ;
1296 *outbuff++ = hexlate[nib] ;
1298 *outbuff++ = hexlate[nib] ;
1303 *outbuff = '\0' ; /* null terminate our output line */
1308 /* Number of lines per page or UINT_MAX if paging is disabled. */
1309 static unsigned int lines_per_page;
1310 /* Number of chars per line or UNIT_MAX is line folding is disabled. */
1311 static unsigned int chars_per_line;
1312 /* Current count of lines printed on this page, chars on this line. */
1313 static unsigned int lines_printed, chars_printed;
1315 /* Buffer and start column of buffered text, for doing smarter word-
1316 wrapping. When someone calls wrap_here(), we start buffering output
1317 that comes through fputs_filtered(). If we see a newline, we just
1318 spit it out and forget about the wrap_here(). If we see another
1319 wrap_here(), we spit it out and remember the newer one. If we see
1320 the end of the line, we spit out a newline, the indent, and then
1321 the buffered output. */
1323 /* Malloc'd buffer with chars_per_line+2 bytes. Contains characters which
1324 are waiting to be output (they have already been counted in chars_printed).
1325 When wrap_buffer[0] is null, the buffer is empty. */
1326 static char *wrap_buffer;
1328 /* Pointer in wrap_buffer to the next character to fill. */
1329 static char *wrap_pointer;
1331 /* String to indent by if the wrap occurs. Must not be NULL if wrap_column
1333 static char *wrap_indent;
1335 /* Column number on the screen where wrap_buffer begins, or 0 if wrapping
1336 is not in effect. */
1337 static int wrap_column;
1340 /* Inialize the lines and chars per page */
1345 if (tui_version && m_winPtrNotNull(cmdWin))
1347 lines_per_page = cmdWin->generic.height;
1348 chars_per_line = cmdWin->generic.width;
1353 /* These defaults will be used if we are unable to get the correct
1354 values from termcap. */
1355 #if defined(__GO32__)
1356 lines_per_page = ScreenRows();
1357 chars_per_line = ScreenCols();
1359 lines_per_page = 24;
1360 chars_per_line = 80;
1362 #if !defined (MPW) && !defined (_WIN32)
1363 /* No termcap under MPW, although might be cool to do something
1364 by looking at worksheet or console window sizes. */
1365 /* Initialize the screen height and width from termcap. */
1367 char *termtype = getenv ("TERM");
1369 /* Positive means success, nonpositive means failure. */
1372 /* 2048 is large enough for all known terminals, according to the
1373 GNU termcap manual. */
1374 char term_buffer[2048];
1378 status = tgetent (term_buffer, termtype);
1382 int running_in_emacs = getenv ("EMACS") != NULL;
1384 val = tgetnum ("li");
1385 if (val >= 0 && !running_in_emacs)
1386 lines_per_page = val;
1388 /* The number of lines per page is not mentioned
1389 in the terminal description. This probably means
1390 that paging is not useful (e.g. emacs shell window),
1391 so disable paging. */
1392 lines_per_page = UINT_MAX;
1394 val = tgetnum ("co");
1396 chars_per_line = val;
1402 #if defined(SIGWINCH) && defined(SIGWINCH_HANDLER)
1404 /* If there is a better way to determine the window size, use it. */
1405 SIGWINCH_HANDLER (SIGWINCH);
1408 /* If the output is not a terminal, don't paginate it. */
1409 if (!GDB_FILE_ISATTY (gdb_stdout))
1410 lines_per_page = UINT_MAX;
1411 } /* the command_line_version */
1418 if (chars_per_line == 0)
1423 wrap_buffer = (char *) xmalloc (chars_per_line + 2);
1424 wrap_buffer[0] = '\0';
1427 wrap_buffer = (char *) xrealloc (wrap_buffer, chars_per_line + 2);
1428 wrap_pointer = wrap_buffer; /* Start it at the beginning */
1433 set_width_command (args, from_tty, c)
1436 struct cmd_list_element *c;
1441 /* Wait, so the user can read what's on the screen. Prompt the user
1442 to continue by pressing RETURN. */
1445 prompt_for_continue ()
1448 char cont_prompt[120];
1450 if (annotation_level > 1)
1451 printf_unfiltered ("\n\032\032pre-prompt-for-continue\n");
1453 strcpy (cont_prompt,
1454 "---Type <return> to continue, or q <return> to quit---");
1455 if (annotation_level > 1)
1456 strcat (cont_prompt, "\n\032\032prompt-for-continue\n");
1458 /* We must do this *before* we call gdb_readline, else it will eventually
1459 call us -- thinking that we're trying to print beyond the end of the
1461 reinitialize_more_filter ();
1464 /* On a real operating system, the user can quit with SIGINT.
1467 'q' is provided on all systems so users don't have to change habits
1468 from system to system, and because telling them what to do in
1469 the prompt is more user-friendly than expecting them to think of
1471 /* Call readline, not gdb_readline, because GO32 readline handles control-C
1472 whereas control-C to gdb_readline will cause the user to get dumped
1474 ignore = readline (cont_prompt);
1476 if (annotation_level > 1)
1477 printf_unfiltered ("\n\032\032post-prompt-for-continue\n");
1482 while (*p == ' ' || *p == '\t')
1485 request_quit (SIGINT);
1490 /* Now we have to do this again, so that GDB will know that it doesn't
1491 need to save the ---Type <return>--- line at the top of the screen. */
1492 reinitialize_more_filter ();
1494 dont_repeat (); /* Forget prev cmd -- CR won't repeat it. */
1497 /* Reinitialize filter; ie. tell it to reset to original values. */
1500 reinitialize_more_filter ()
1506 /* Indicate that if the next sequence of characters overflows the line,
1507 a newline should be inserted here rather than when it hits the end.
1508 If INDENT is non-null, it is a string to be printed to indent the
1509 wrapped part on the next line. INDENT must remain accessible until
1510 the next call to wrap_here() or until a newline is printed through
1513 If the line is already overfull, we immediately print a newline and
1514 the indentation, and disable further wrapping.
1516 If we don't know the width of lines, but we know the page height,
1517 we must not wrap words, but should still keep track of newlines
1518 that were explicitly printed.
1520 INDENT should not contain tabs, as that will mess up the char count
1521 on the next line. FIXME.
1523 This routine is guaranteed to force out any output which has been
1524 squirreled away in the wrap_buffer, so wrap_here ((char *)0) can be
1525 used to force out output from the wrap_buffer. */
1531 /* This should have been allocated, but be paranoid anyway. */
1537 *wrap_pointer = '\0';
1538 fputs_unfiltered (wrap_buffer, gdb_stdout);
1540 wrap_pointer = wrap_buffer;
1541 wrap_buffer[0] = '\0';
1542 if (chars_per_line == UINT_MAX) /* No line overflow checking */
1546 else if (chars_printed >= chars_per_line)
1548 puts_filtered ("\n");
1550 puts_filtered (indent);
1555 wrap_column = chars_printed;
1559 wrap_indent = indent;
1563 /* Ensure that whatever gets printed next, using the filtered output
1564 commands, starts at the beginning of the line. I.E. if there is
1565 any pending output for the current line, flush it and start a new
1566 line. Otherwise do nothing. */
1571 if (chars_printed > 0)
1573 puts_filtered ("\n");
1578 gdb_file_isatty (stream)
1582 if (stream->ts_streamtype == afile)
1583 return (isatty(fileno(stream->ts_filestream)));
1588 gdb_file_init_astring (n)
1591 GDB_FILE *tmpstream;
1593 tmpstream = xmalloc (sizeof(GDB_FILE));
1594 tmpstream->ts_streamtype = astring;
1595 tmpstream->ts_filestream = NULL;
1598 tmpstream->ts_strbuf = xmalloc ((n + 1)*sizeof(char));
1599 tmpstream->ts_strbuf[0] = '\0';
1602 tmpstream->ts_strbuf = NULL;
1603 tmpstream->ts_buflen = n;
1609 gdb_file_deallocate (streamptr)
1610 GDB_FILE **streamptr;
1612 GDB_FILE *tmpstream;
1614 tmpstream = *streamptr;
1615 if ((tmpstream->ts_streamtype == astring) &&
1616 (tmpstream->ts_strbuf != NULL))
1618 free (tmpstream->ts_strbuf);
1626 gdb_file_get_strbuf (stream)
1629 return (stream->ts_strbuf);
1632 /* adjust the length of the buffer by the amount necessary
1633 to accomodate appending a string of length N to the buffer contents */
1635 gdb_file_adjust_strbuf (n, stream)
1641 non_null_chars = strlen(stream->ts_strbuf);
1643 if (n > (stream->ts_buflen - non_null_chars - 1))
1645 stream->ts_buflen = n + non_null_chars + 1;
1646 stream->ts_strbuf = xrealloc (stream->ts_strbuf, stream->ts_buflen);
1651 gdb_fopen (name, mode)
1658 gdb_file_size = sizeof(GDB_FILE);
1659 tmp = (GDB_FILE *) xmalloc (gdb_file_size);
1660 tmp->ts_streamtype = afile;
1661 tmp->ts_filestream = fopen (name, mode);
1662 tmp->ts_strbuf = NULL;
1673 && (stream == gdb_stdout
1674 || stream == gdb_stderr))
1676 flush_hook (stream);
1680 fflush (stream->ts_filestream);
1684 gdb_fclose(streamptr)
1685 GDB_FILE **streamptr;
1687 GDB_FILE *tmpstream;
1689 tmpstream = *streamptr;
1690 fclose (tmpstream->ts_filestream);
1691 gdb_file_deallocate (streamptr);
1694 /* Like fputs but if FILTER is true, pause after every screenful.
1696 Regardless of FILTER can wrap at points other than the final
1697 character of a line.
1699 Unlike fputs, fputs_maybe_filtered does not return a value.
1700 It is OK for LINEBUFFER to be NULL, in which case just don't print
1703 Note that a longjmp to top level may occur in this routine (only if
1704 FILTER is true) (since prompt_for_continue may do so) so this
1705 routine should not be called when cleanups are not in place. */
1708 fputs_maybe_filtered (linebuffer, stream, filter)
1709 const char *linebuffer;
1713 const char *lineptr;
1715 if (linebuffer == 0)
1718 /* Don't do any filtering if it is disabled. */
1719 if (stream != gdb_stdout
1720 || (lines_per_page == UINT_MAX && chars_per_line == UINT_MAX))
1722 fputs_unfiltered (linebuffer, stream);
1726 /* Go through and output each character. Show line extension
1727 when this is necessary; prompt user for new page when this is
1730 lineptr = linebuffer;
1733 /* Possible new page. */
1735 (lines_printed >= lines_per_page - 1))
1736 prompt_for_continue ();
1738 while (*lineptr && *lineptr != '\n')
1740 /* Print a single line. */
1741 if (*lineptr == '\t')
1744 *wrap_pointer++ = '\t';
1746 fputc_unfiltered ('\t', stream);
1747 /* Shifting right by 3 produces the number of tab stops
1748 we have already passed, and then adding one and
1749 shifting left 3 advances to the next tab stop. */
1750 chars_printed = ((chars_printed >> 3) + 1) << 3;
1756 *wrap_pointer++ = *lineptr;
1758 fputc_unfiltered (*lineptr, stream);
1763 if (chars_printed >= chars_per_line)
1765 unsigned int save_chars = chars_printed;
1769 /* If we aren't actually wrapping, don't output newline --
1770 if chars_per_line is right, we probably just overflowed
1771 anyway; if it's wrong, let us keep going. */
1773 fputc_unfiltered ('\n', stream);
1775 /* Possible new page. */
1776 if (lines_printed >= lines_per_page - 1)
1777 prompt_for_continue ();
1779 /* Now output indentation and wrapped string */
1782 fputs_unfiltered (wrap_indent, stream);
1783 *wrap_pointer = '\0'; /* Null-terminate saved stuff */
1784 fputs_unfiltered (wrap_buffer, stream); /* and eject it */
1785 /* FIXME, this strlen is what prevents wrap_indent from
1786 containing tabs. However, if we recurse to print it
1787 and count its chars, we risk trouble if wrap_indent is
1788 longer than (the user settable) chars_per_line.
1789 Note also that this can set chars_printed > chars_per_line
1790 if we are printing a long string. */
1791 chars_printed = strlen (wrap_indent)
1792 + (save_chars - wrap_column);
1793 wrap_pointer = wrap_buffer; /* Reset buffer */
1794 wrap_buffer[0] = '\0';
1795 wrap_column = 0; /* And disable fancy wrap */
1800 if (*lineptr == '\n')
1803 wrap_here ((char *)0); /* Spit out chars, cancel further wraps */
1805 fputc_unfiltered ('\n', stream);
1812 fputs_filtered (linebuffer, stream)
1813 const char *linebuffer;
1816 fputs_maybe_filtered (linebuffer, stream, 1);
1820 putchar_unfiltered (c)
1827 fputs_unfiltered (buf, gdb_stdout);
1832 fputc_unfiltered (c, stream)
1840 fputs_unfiltered (buf, stream);
1845 fputc_filtered (c, stream)
1853 fputs_filtered (buf, stream);
1857 /* puts_debug is like fputs_unfiltered, except it prints special
1858 characters in printable fashion. */
1861 puts_debug (prefix, string, suffix)
1868 /* Print prefix and suffix after each line. */
1869 static int new_line = 1;
1870 static int return_p = 0;
1871 static char *prev_prefix = "";
1872 static char *prev_suffix = "";
1874 if (*string == '\n')
1877 /* If the prefix is changing, print the previous suffix, a new line,
1878 and the new prefix. */
1879 if ((return_p || (strcmp(prev_prefix, prefix) != 0)) && !new_line)
1881 fputs_unfiltered (prev_suffix, gdb_stderr);
1882 fputs_unfiltered ("\n", gdb_stderr);
1883 fputs_unfiltered (prefix, gdb_stderr);
1886 /* Print prefix if we printed a newline during the previous call. */
1890 fputs_unfiltered (prefix, gdb_stderr);
1893 prev_prefix = prefix;
1894 prev_suffix = suffix;
1896 /* Output characters in a printable format. */
1897 while ((ch = *string++) != '\0')
1903 fputc_unfiltered (ch, gdb_stderr);
1906 fprintf_unfiltered (gdb_stderr, "\\x%02x", ch & 0xff);
1909 case '\\': fputs_unfiltered ("\\\\", gdb_stderr); break;
1910 case '\b': fputs_unfiltered ("\\b", gdb_stderr); break;
1911 case '\f': fputs_unfiltered ("\\f", gdb_stderr); break;
1912 case '\n': new_line = 1;
1913 fputs_unfiltered ("\\n", gdb_stderr); break;
1914 case '\r': fputs_unfiltered ("\\r", gdb_stderr); break;
1915 case '\t': fputs_unfiltered ("\\t", gdb_stderr); break;
1916 case '\v': fputs_unfiltered ("\\v", gdb_stderr); break;
1919 return_p = ch == '\r';
1922 /* Print suffix if we printed a newline. */
1925 fputs_unfiltered (suffix, gdb_stderr);
1926 fputs_unfiltered ("\n", gdb_stderr);
1931 /* Print a variable number of ARGS using format FORMAT. If this
1932 information is going to put the amount written (since the last call
1933 to REINITIALIZE_MORE_FILTER or the last page break) over the page size,
1934 call prompt_for_continue to get the users permision to continue.
1936 Unlike fprintf, this function does not return a value.
1938 We implement three variants, vfprintf (takes a vararg list and stream),
1939 fprintf (takes a stream to write on), and printf (the usual).
1941 Note also that a longjmp to top level may occur in this routine
1942 (since prompt_for_continue may do so) so this routine should not be
1943 called when cleanups are not in place. */
1946 vfprintf_maybe_filtered (stream, format, args, filter)
1953 struct cleanup *old_cleanups;
1955 vasprintf (&linebuffer, format, args);
1956 if (linebuffer == NULL)
1958 fputs_unfiltered ("\ngdb: virtual memory exhausted.\n", gdb_stderr);
1961 old_cleanups = make_cleanup (free, linebuffer);
1962 fputs_maybe_filtered (linebuffer, stream, filter);
1963 do_cleanups (old_cleanups);
1968 vfprintf_filtered (stream, format, args)
1973 vfprintf_maybe_filtered (stream, format, args, 1);
1977 vfprintf_unfiltered (stream, format, args)
1983 struct cleanup *old_cleanups;
1985 vasprintf (&linebuffer, format, args);
1986 if (linebuffer == NULL)
1988 fputs_unfiltered ("\ngdb: virtual memory exhausted.\n", gdb_stderr);
1991 old_cleanups = make_cleanup (free, linebuffer);
1992 fputs_unfiltered (linebuffer, stream);
1993 do_cleanups (old_cleanups);
1997 vprintf_filtered (format, args)
2001 vfprintf_maybe_filtered (gdb_stdout, format, args, 1);
2005 vprintf_unfiltered (format, args)
2009 vfprintf_unfiltered (gdb_stdout, format, args);
2014 #ifdef ANSI_PROTOTYPES
2015 fprintf_filtered (GDB_FILE *stream, const char *format, ...)
2017 fprintf_filtered (va_alist)
2022 #ifdef ANSI_PROTOTYPES
2023 va_start (args, format);
2029 stream = va_arg (args, GDB_FILE *);
2030 format = va_arg (args, char *);
2032 vfprintf_filtered (stream, format, args);
2038 #ifdef ANSI_PROTOTYPES
2039 fprintf_unfiltered (GDB_FILE *stream, const char *format, ...)
2041 fprintf_unfiltered (va_alist)
2046 #ifdef ANSI_PROTOTYPES
2047 va_start (args, format);
2053 stream = va_arg (args, GDB_FILE *);
2054 format = va_arg (args, char *);
2056 vfprintf_unfiltered (stream, format, args);
2060 /* Like fprintf_filtered, but prints its result indented.
2061 Called as fprintfi_filtered (spaces, stream, format, ...); */
2065 #ifdef ANSI_PROTOTYPES
2066 fprintfi_filtered (int spaces, GDB_FILE *stream, const char *format, ...)
2068 fprintfi_filtered (va_alist)
2073 #ifdef ANSI_PROTOTYPES
2074 va_start (args, format);
2081 spaces = va_arg (args, int);
2082 stream = va_arg (args, GDB_FILE *);
2083 format = va_arg (args, char *);
2085 print_spaces_filtered (spaces, stream);
2087 vfprintf_filtered (stream, format, args);
2094 #ifdef ANSI_PROTOTYPES
2095 printf_filtered (const char *format, ...)
2097 printf_filtered (va_alist)
2102 #ifdef ANSI_PROTOTYPES
2103 va_start (args, format);
2108 format = va_arg (args, char *);
2110 vfprintf_filtered (gdb_stdout, format, args);
2117 #ifdef ANSI_PROTOTYPES
2118 printf_unfiltered (const char *format, ...)
2120 printf_unfiltered (va_alist)
2125 #ifdef ANSI_PROTOTYPES
2126 va_start (args, format);
2131 format = va_arg (args, char *);
2133 vfprintf_unfiltered (gdb_stdout, format, args);
2137 /* Like printf_filtered, but prints it's result indented.
2138 Called as printfi_filtered (spaces, format, ...); */
2142 #ifdef ANSI_PROTOTYPES
2143 printfi_filtered (int spaces, const char *format, ...)
2145 printfi_filtered (va_alist)
2150 #ifdef ANSI_PROTOTYPES
2151 va_start (args, format);
2157 spaces = va_arg (args, int);
2158 format = va_arg (args, char *);
2160 print_spaces_filtered (spaces, gdb_stdout);
2161 vfprintf_filtered (gdb_stdout, format, args);
2165 /* Easy -- but watch out!
2167 This routine is *not* a replacement for puts()! puts() appends a newline.
2168 This one doesn't, and had better not! */
2171 puts_filtered (string)
2174 fputs_filtered (string, gdb_stdout);
2178 puts_unfiltered (string)
2181 fputs_unfiltered (string, gdb_stdout);
2184 /* Return a pointer to N spaces and a null. The pointer is good
2185 until the next call to here. */
2191 static char *spaces;
2192 static int max_spaces;
2198 spaces = (char *) xmalloc (n+1);
2199 for (t = spaces+n; t != spaces;)
2205 return spaces + max_spaces - n;
2208 /* Print N spaces. */
2210 print_spaces_filtered (n, stream)
2214 fputs_filtered (n_spaces (n), stream);
2217 /* C++ demangler stuff. */
2219 /* fprintf_symbol_filtered attempts to demangle NAME, a symbol in language
2220 LANG, using demangling args ARG_MODE, and print it filtered to STREAM.
2221 If the name is not mangled, or the language for the name is unknown, or
2222 demangling is off, the name is printed in its "raw" form. */
2225 fprintf_symbol_filtered (stream, name, lang, arg_mode)
2235 /* If user wants to see raw output, no problem. */
2238 fputs_filtered (name, stream);
2244 case language_cplus:
2245 demangled = cplus_demangle (name, arg_mode);
2248 demangled = cplus_demangle (name, arg_mode | DMGL_JAVA);
2250 case language_chill:
2251 demangled = chill_demangle (name);
2257 fputs_filtered (demangled ? demangled : name, stream);
2258 if (demangled != NULL)
2266 /* Do a strcmp() type operation on STRING1 and STRING2, ignoring any
2267 differences in whitespace. Returns 0 if they match, non-zero if they
2268 don't (slightly different than strcmp()'s range of return values).
2270 As an extra hack, string1=="FOO(ARGS)" matches string2=="FOO".
2271 This "feature" is useful when searching for matching C++ function names
2272 (such as if the user types 'break FOO', where FOO is a mangled C++
2276 strcmp_iw (string1, string2)
2277 const char *string1;
2278 const char *string2;
2280 while ((*string1 != '\0') && (*string2 != '\0'))
2282 while (isspace (*string1))
2286 while (isspace (*string2))
2290 if (*string1 != *string2)
2294 if (*string1 != '\0')
2300 return (*string1 != '\0' && *string1 != '(') || (*string2 != '\0');
2306 ** Answer whether stringToCompare is a full or partial match to
2307 ** templateString. The partial match must be in sequence starting
2313 char *stringToCompare,
2314 char *templateString)
2316 subsetCompare(stringToCompare, templateString)
2317 char *stringToCompare;
2318 char *templateString;
2323 if (templateString != (char *)NULL && stringToCompare != (char *)NULL &&
2324 strlen(stringToCompare) <= strlen(templateString))
2325 match = (strncmp(templateString,
2327 strlen(stringToCompare)) == 0);
2330 } /* subsetCompare */
2333 void pagination_on_command(arg, from_tty)
2337 pagination_enabled = 1;
2340 void pagination_off_command(arg, from_tty)
2344 pagination_enabled = 0;
2351 struct cmd_list_element *c;
2353 c = add_set_cmd ("width", class_support, var_uinteger,
2354 (char *)&chars_per_line,
2355 "Set number of characters gdb thinks are in a line.",
2357 add_show_from_set (c, &showlist);
2358 c->function.sfunc = set_width_command;
2361 (add_set_cmd ("height", class_support,
2362 var_uinteger, (char *)&lines_per_page,
2363 "Set number of lines gdb thinks are in a page.", &setlist),
2368 /* If the output is not a terminal, don't paginate it. */
2369 if (!GDB_FILE_ISATTY (gdb_stdout))
2370 lines_per_page = UINT_MAX;
2372 set_width_command ((char *)NULL, 0, c);
2375 (add_set_cmd ("demangle", class_support, var_boolean,
2377 "Set demangling of encoded C++ names when displaying symbols.",
2382 (add_set_cmd ("pagination", class_support,
2383 var_boolean, (char *)&pagination_enabled,
2384 "Set state of pagination.", &setlist),
2388 add_com("am", class_support, pagination_on_command,
2389 "Enable pagination");
2390 add_com("sm", class_support, pagination_off_command,
2391 "Disable pagination");
2395 (add_set_cmd ("sevenbit-strings", class_support, var_boolean,
2396 (char *)&sevenbit_strings,
2397 "Set printing of 8-bit characters in strings as \\nnn.",
2402 (add_set_cmd ("asm-demangle", class_support, var_boolean,
2403 (char *)&asm_demangle,
2404 "Set demangling of C++ names in disassembly listings.",
2409 /* Machine specific function to handle SIGWINCH signal. */
2411 #ifdef SIGWINCH_HANDLER_BODY
2412 SIGWINCH_HANDLER_BODY
2415 /* Support for converting target fp numbers into host DOUBLEST format. */
2417 /* XXX - This code should really be in libiberty/floatformat.c, however
2418 configuration issues with libiberty made this very difficult to do in the
2421 #include "floatformat.h"
2422 #include <math.h> /* ldexp */
2424 /* The odds that CHAR_BIT will be anything but 8 are low enough that I'm not
2425 going to bother with trying to muck around with whether it is defined in
2426 a system header, what we do if not, etc. */
2427 #define FLOATFORMAT_CHAR_BIT 8
2429 static unsigned long get_field PARAMS ((unsigned char *,
2430 enum floatformat_byteorders,
2435 /* Extract a field which starts at START and is LEN bytes long. DATA and
2436 TOTAL_LEN are the thing we are extracting it from, in byteorder ORDER. */
2437 static unsigned long
2438 get_field (data, order, total_len, start, len)
2439 unsigned char *data;
2440 enum floatformat_byteorders order;
2441 unsigned int total_len;
2445 unsigned long result;
2446 unsigned int cur_byte;
2449 /* Start at the least significant part of the field. */
2450 cur_byte = (start + len) / FLOATFORMAT_CHAR_BIT;
2451 if (order == floatformat_little || order == floatformat_littlebyte_bigword)
2452 cur_byte = (total_len / FLOATFORMAT_CHAR_BIT) - cur_byte - 1;
2454 ((start + len) % FLOATFORMAT_CHAR_BIT) - FLOATFORMAT_CHAR_BIT;
2455 result = *(data + cur_byte) >> (-cur_bitshift);
2456 cur_bitshift += FLOATFORMAT_CHAR_BIT;
2457 if (order == floatformat_little || order == floatformat_littlebyte_bigword)
2462 /* Move towards the most significant part of the field. */
2463 while (cur_bitshift < len)
2465 if (len - cur_bitshift < FLOATFORMAT_CHAR_BIT)
2466 /* This is the last byte; zero out the bits which are not part of
2469 (*(data + cur_byte) & ((1 << (len - cur_bitshift)) - 1))
2472 result |= *(data + cur_byte) << cur_bitshift;
2473 cur_bitshift += FLOATFORMAT_CHAR_BIT;
2474 if (order == floatformat_little || order == floatformat_littlebyte_bigword)
2482 /* Convert from FMT to a DOUBLEST.
2483 FROM is the address of the extended float.
2484 Store the DOUBLEST in *TO. */
2487 floatformat_to_doublest (fmt, from, to)
2488 const struct floatformat *fmt;
2492 unsigned char *ufrom = (unsigned char *)from;
2496 unsigned int mant_bits, mant_off;
2498 int special_exponent; /* It's a NaN, denorm or zero */
2500 /* If the mantissa bits are not contiguous from one end of the
2501 mantissa to the other, we need to make a private copy of the
2502 source bytes that is in the right order since the unpacking
2503 algorithm assumes that the bits are contiguous.
2505 Swap the bytes individually rather than accessing them through
2506 "long *" since we have no guarantee that they start on a long
2507 alignment, and also sizeof(long) for the host could be different
2508 than sizeof(long) for the target. FIXME: Assumes sizeof(long)
2509 for the target is 4. */
2511 if (fmt -> byteorder == floatformat_littlebyte_bigword)
2513 static unsigned char *newfrom;
2514 unsigned char *swapin, *swapout;
2517 longswaps = fmt -> totalsize / FLOATFORMAT_CHAR_BIT;
2520 if (newfrom == NULL)
2522 newfrom = (unsigned char *) xmalloc (fmt -> totalsize);
2527 while (longswaps-- > 0)
2529 /* This is ugly, but efficient */
2530 *swapout++ = swapin[4];
2531 *swapout++ = swapin[5];
2532 *swapout++ = swapin[6];
2533 *swapout++ = swapin[7];
2534 *swapout++ = swapin[0];
2535 *swapout++ = swapin[1];
2536 *swapout++ = swapin[2];
2537 *swapout++ = swapin[3];
2542 exponent = get_field (ufrom, fmt->byteorder, fmt->totalsize,
2543 fmt->exp_start, fmt->exp_len);
2544 /* Note that if exponent indicates a NaN, we can't really do anything useful
2545 (not knowing if the host has NaN's, or how to build one). So it will
2546 end up as an infinity or something close; that is OK. */
2548 mant_bits_left = fmt->man_len;
2549 mant_off = fmt->man_start;
2552 special_exponent = exponent == 0 || exponent == fmt->exp_nan;
2554 /* Don't bias zero's, denorms or NaNs. */
2555 if (!special_exponent)
2556 exponent -= fmt->exp_bias;
2558 /* Build the result algebraically. Might go infinite, underflow, etc;
2561 /* If this format uses a hidden bit, explicitly add it in now. Otherwise,
2562 increment the exponent by one to account for the integer bit. */
2564 if (!special_exponent)
2565 if (fmt->intbit == floatformat_intbit_no)
2566 dto = ldexp (1.0, exponent);
2570 while (mant_bits_left > 0)
2572 mant_bits = min (mant_bits_left, 32);
2574 mant = get_field (ufrom, fmt->byteorder, fmt->totalsize,
2575 mant_off, mant_bits);
2577 dto += ldexp ((double)mant, exponent - mant_bits);
2578 exponent -= mant_bits;
2579 mant_off += mant_bits;
2580 mant_bits_left -= mant_bits;
2583 /* Negate it if negative. */
2584 if (get_field (ufrom, fmt->byteorder, fmt->totalsize, fmt->sign_start, 1))
2589 static void put_field PARAMS ((unsigned char *, enum floatformat_byteorders,
2595 /* Set a field which starts at START and is LEN bytes long. DATA and
2596 TOTAL_LEN are the thing we are extracting it from, in byteorder ORDER. */
2598 put_field (data, order, total_len, start, len, stuff_to_put)
2599 unsigned char *data;
2600 enum floatformat_byteorders order;
2601 unsigned int total_len;
2604 unsigned long stuff_to_put;
2606 unsigned int cur_byte;
2609 /* Start at the least significant part of the field. */
2610 cur_byte = (start + len) / FLOATFORMAT_CHAR_BIT;
2611 if (order == floatformat_little || order == floatformat_littlebyte_bigword)
2612 cur_byte = (total_len / FLOATFORMAT_CHAR_BIT) - cur_byte - 1;
2614 ((start + len) % FLOATFORMAT_CHAR_BIT) - FLOATFORMAT_CHAR_BIT;
2615 *(data + cur_byte) &=
2616 ~(((1 << ((start + len) % FLOATFORMAT_CHAR_BIT)) - 1) << (-cur_bitshift));
2617 *(data + cur_byte) |=
2618 (stuff_to_put & ((1 << FLOATFORMAT_CHAR_BIT) - 1)) << (-cur_bitshift);
2619 cur_bitshift += FLOATFORMAT_CHAR_BIT;
2620 if (order == floatformat_little || order == floatformat_littlebyte_bigword)
2625 /* Move towards the most significant part of the field. */
2626 while (cur_bitshift < len)
2628 if (len - cur_bitshift < FLOATFORMAT_CHAR_BIT)
2630 /* This is the last byte. */
2631 *(data + cur_byte) &=
2632 ~((1 << (len - cur_bitshift)) - 1);
2633 *(data + cur_byte) |= (stuff_to_put >> cur_bitshift);
2636 *(data + cur_byte) = ((stuff_to_put >> cur_bitshift)
2637 & ((1 << FLOATFORMAT_CHAR_BIT) - 1));
2638 cur_bitshift += FLOATFORMAT_CHAR_BIT;
2639 if (order == floatformat_little || order == floatformat_littlebyte_bigword)
2646 #ifdef HAVE_LONG_DOUBLE
2647 /* Return the fractional part of VALUE, and put the exponent of VALUE in *EPTR.
2648 The range of the returned value is >= 0.5 and < 1.0. This is equivalent to
2649 frexp, but operates on the long double data type. */
2651 static long double ldfrexp PARAMS ((long double value, int *eptr));
2654 ldfrexp (value, eptr)
2661 /* Unfortunately, there are no portable functions for extracting the exponent
2662 of a long double, so we have to do it iteratively by multiplying or dividing
2663 by two until the fraction is between 0.5 and 1.0. */
2671 if (value >= tmp) /* Value >= 1.0 */
2672 while (value >= tmp)
2677 else if (value != 0.0l) /* Value < 1.0 and > 0.0 */
2691 #endif /* HAVE_LONG_DOUBLE */
2694 /* The converse: convert the DOUBLEST *FROM to an extended float
2695 and store where TO points. Neither FROM nor TO have any alignment
2699 floatformat_from_doublest (fmt, from, to)
2700 CONST struct floatformat *fmt;
2707 unsigned int mant_bits, mant_off;
2709 unsigned char *uto = (unsigned char *)to;
2711 memcpy (&dfrom, from, sizeof (dfrom));
2712 memset (uto, 0, fmt->totalsize / FLOATFORMAT_CHAR_BIT);
2714 return; /* Result is zero */
2715 if (dfrom != dfrom) /* Result is NaN */
2718 put_field (uto, fmt->byteorder, fmt->totalsize, fmt->exp_start,
2719 fmt->exp_len, fmt->exp_nan);
2720 /* Be sure it's not infinity, but NaN value is irrel */
2721 put_field (uto, fmt->byteorder, fmt->totalsize, fmt->man_start,
2726 /* If negative, set the sign bit. */
2729 put_field (uto, fmt->byteorder, fmt->totalsize, fmt->sign_start, 1, 1);
2733 if (dfrom + dfrom == dfrom && dfrom != 0.0) /* Result is Infinity */
2735 /* Infinity exponent is same as NaN's. */
2736 put_field (uto, fmt->byteorder, fmt->totalsize, fmt->exp_start,
2737 fmt->exp_len, fmt->exp_nan);
2738 /* Infinity mantissa is all zeroes. */
2739 put_field (uto, fmt->byteorder, fmt->totalsize, fmt->man_start,
2744 #ifdef HAVE_LONG_DOUBLE
2745 mant = ldfrexp (dfrom, &exponent);
2747 mant = frexp (dfrom, &exponent);
2750 put_field (uto, fmt->byteorder, fmt->totalsize, fmt->exp_start, fmt->exp_len,
2751 exponent + fmt->exp_bias - 1);
2753 mant_bits_left = fmt->man_len;
2754 mant_off = fmt->man_start;
2755 while (mant_bits_left > 0)
2757 unsigned long mant_long;
2758 mant_bits = mant_bits_left < 32 ? mant_bits_left : 32;
2760 mant *= 4294967296.0;
2761 mant_long = (unsigned long)mant;
2764 /* If the integer bit is implicit, then we need to discard it.
2765 If we are discarding a zero, we should be (but are not) creating
2766 a denormalized number which means adjusting the exponent
2768 if (mant_bits_left == fmt->man_len
2769 && fmt->intbit == floatformat_intbit_no)
2777 /* The bits we want are in the most significant MANT_BITS bits of
2778 mant_long. Move them to the least significant. */
2779 mant_long >>= 32 - mant_bits;
2782 put_field (uto, fmt->byteorder, fmt->totalsize,
2783 mant_off, mant_bits, mant_long);
2784 mant_off += mant_bits;
2785 mant_bits_left -= mant_bits;
2787 if (fmt -> byteorder == floatformat_littlebyte_bigword)
2790 unsigned char *swaplow = uto;
2791 unsigned char *swaphigh = uto + 4;
2794 for (count = 0; count < 4; count++)
2797 *swaplow++ = *swaphigh;
2803 /* temporary storage using circular buffer */
2809 static char buf[NUMCELLS][CELLSIZE];
2811 if (++cell>=NUMCELLS) cell=0;
2815 /* print routines to handle variable size regs, etc.
2817 FIXME: Note that t_addr is a bfd_vma, which is currently either an
2818 unsigned long or unsigned long long, determined at configure time.
2819 If t_addr is an unsigned long long and sizeof (unsigned long long)
2820 is greater than sizeof (unsigned long), then I believe this code will
2821 probably lose, at least for little endian machines. I believe that
2822 it would also be better to eliminate the switch on the absolute size
2823 of t_addr and replace it with a sequence of if statements that compare
2824 sizeof t_addr with sizeof the various types and do the right thing,
2825 which includes knowing whether or not the host supports long long.
2830 static int thirty_two = 32; /* eliminate warning from compiler on 32-bit systems */
2836 char *paddr_str=get_cell();
2837 switch (sizeof(t_addr))
2840 sprintf (paddr_str, "%08lx%08lx",
2841 (unsigned long) (addr >> thirty_two), (unsigned long) (addr & 0xffffffff));
2844 sprintf (paddr_str, "%08lx", (unsigned long) addr);
2847 sprintf (paddr_str, "%04x", (unsigned short) (addr & 0xffff));
2850 sprintf (paddr_str, "%lx", (unsigned long) addr);
2859 char *preg_str=get_cell();
2860 switch (sizeof(t_reg))
2863 sprintf (preg_str, "%08lx%08lx",
2864 (unsigned long) (reg >> thirty_two), (unsigned long) (reg & 0xffffffff));
2867 sprintf (preg_str, "%08lx", (unsigned long) reg);
2870 sprintf (preg_str, "%04x", (unsigned short) (reg & 0xffff));
2873 sprintf (preg_str, "%lx", (unsigned long) reg);
2882 char *paddr_str=get_cell();
2883 switch (sizeof(t_addr))
2887 unsigned long high = (unsigned long) (addr >> thirty_two);
2889 sprintf (paddr_str, "%lx", (unsigned long) (addr & 0xffffffff));
2891 sprintf (paddr_str, "%lx%08lx",
2892 high, (unsigned long) (addr & 0xffffffff));
2896 sprintf (paddr_str, "%lx", (unsigned long) addr);
2899 sprintf (paddr_str, "%x", (unsigned short) (addr & 0xffff));
2902 sprintf (paddr_str,"%lx", (unsigned long) addr);
2911 char *preg_str=get_cell();
2912 switch (sizeof(t_reg))
2916 unsigned long high = (unsigned long) (reg >> thirty_two);
2918 sprintf (preg_str, "%lx", (unsigned long) (reg & 0xffffffff));
2920 sprintf (preg_str, "%lx%08lx",
2921 high, (unsigned long) (reg & 0xffffffff));
2925 sprintf (preg_str, "%lx", (unsigned long) reg);
2928 sprintf (preg_str, "%x", (unsigned short) (reg & 0xffff));
2931 sprintf (preg_str, "%lx", (unsigned long) reg);