1 /* General utility routines for GDB, the GNU debugger.
2 Copyright 1986, 89, 90, 91, 92, 95, 1996 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. */
21 #ifdef ANSI_PROTOTYPES
27 #include "gdb_string.h"
38 #include "expression.h"
44 /* readline defines this. */
47 /* Prototypes for local functions */
49 static void vfprintf_maybe_filtered PARAMS ((FILE *, const char *, va_list, int));
51 static void fputs_maybe_filtered PARAMS ((const char *, FILE *, int));
53 #if !defined (NO_MMALLOC) && !defined (NO_MMCHECK)
54 static void malloc_botch PARAMS ((void));
58 fatal_dump_core PARAMS((char *, ...));
61 prompt_for_continue PARAMS ((void));
64 set_width_command PARAMS ((char *, int, struct cmd_list_element *));
66 /* If this definition isn't overridden by the header files, assume
67 that isatty and fileno exist on this system. */
69 #define ISATTY(FP) (isatty (fileno (FP)))
72 /* Chain of cleanup actions established with make_cleanup,
73 to be executed if an error happens. */
75 static struct cleanup *cleanup_chain;
77 /* Nonzero if we have job control. */
81 /* Nonzero means a quit has been requested. */
85 /* Nonzero means quit immediately if Control-C is typed now, rather
86 than waiting until QUIT is executed. Be careful in setting this;
87 code which executes with immediate_quit set has to be very careful
88 about being able to deal with being interrupted at any time. It is
89 almost always better to use QUIT; the only exception I can think of
90 is being able to quit out of a system call (using EINTR loses if
91 the SIGINT happens between the previous QUIT and the system call).
92 To immediately quit in the case in which a SIGINT happens between
93 the previous QUIT and setting immediate_quit (desirable anytime we
94 expect to block), call QUIT after setting immediate_quit. */
98 /* Nonzero means that encoded C++ names should be printed out in their
99 C++ form rather than raw. */
103 /* Nonzero means that encoded C++ names should be printed out in their
104 C++ form even in assembler language displays. If this is set, but
105 DEMANGLE is zero, names are printed raw, i.e. DEMANGLE controls. */
107 int asm_demangle = 0;
109 /* Nonzero means that strings with character values >0x7F should be printed
110 as octal escapes. Zero means just print the value (e.g. it's an
111 international character, and the terminal or window can cope.) */
113 int sevenbit_strings = 0;
115 /* String to be printed before error messages, if any. */
117 char *error_pre_print;
119 /* String to be printed before quit messages, if any. */
121 char *quit_pre_print;
123 /* String to be printed before warning messages, if any. */
125 char *warning_pre_print = "\nwarning: ";
127 /* Add a new cleanup to the cleanup_chain,
128 and return the previous chain pointer
129 to be passed later to do_cleanups or discard_cleanups.
130 Args are FUNCTION to clean up with, and ARG to pass to it. */
133 make_cleanup (function, arg)
134 void (*function) PARAMS ((PTR));
137 register struct cleanup *new
138 = (struct cleanup *) xmalloc (sizeof (struct cleanup));
139 register struct cleanup *old_chain = cleanup_chain;
141 new->next = cleanup_chain;
142 new->function = function;
149 /* Discard cleanups and do the actions they describe
150 until we get back to the point OLD_CHAIN in the cleanup_chain. */
153 do_cleanups (old_chain)
154 register struct cleanup *old_chain;
156 register struct cleanup *ptr;
157 while ((ptr = cleanup_chain) != old_chain)
159 cleanup_chain = ptr->next; /* Do this first incase recursion */
160 (*ptr->function) (ptr->arg);
165 /* Discard cleanups, not doing the actions they describe,
166 until we get back to the point OLD_CHAIN in the cleanup_chain. */
169 discard_cleanups (old_chain)
170 register struct cleanup *old_chain;
172 register struct cleanup *ptr;
173 while ((ptr = cleanup_chain) != old_chain)
175 cleanup_chain = ptr->next;
180 /* Set the cleanup_chain to 0, and return the old cleanup chain. */
184 struct cleanup *old_chain = cleanup_chain;
190 /* Restore the cleanup chain from a previously saved chain. */
192 restore_cleanups (chain)
193 struct cleanup *chain;
195 cleanup_chain = chain;
198 /* This function is useful for cleanups.
202 old_chain = make_cleanup (free_current_contents, &foo);
204 to arrange to free the object thus allocated. */
207 free_current_contents (location)
213 /* Provide a known function that does nothing, to use as a base for
214 for a possibly long chain of cleanups. This is useful where we
215 use the cleanup chain for handling normal cleanups as well as dealing
216 with cleanups that need to be done as a result of a call to error().
217 In such cases, we may not be certain where the first cleanup is, unless
218 we have a do-nothing one to always use as the base. */
228 /* Print a warning message. Way to use this is to call warning_begin,
229 output the warning message (use unfiltered output to gdb_stderr),
230 ending in a newline. There is not currently a warning_end that you
231 call afterwards, but such a thing might be added if it is useful
232 for a GUI to separate warning messages from other output.
234 FIXME: Why do warnings use unfiltered output and errors filtered?
235 Is this anything other than a historical accident? */
240 target_terminal_ours ();
241 wrap_here(""); /* Force out any buffered output */
242 gdb_flush (gdb_stdout);
243 if (warning_pre_print)
244 fprintf_unfiltered (gdb_stderr, warning_pre_print);
247 /* Print a warning message.
248 The first argument STRING is the warning message, used as a fprintf string,
249 and the remaining args are passed as arguments to it.
250 The primary difference between warnings and errors is that a warning
251 does not force the return to command level. */
255 #ifdef ANSI_PROTOTYPES
256 warning (char *string, ...)
263 #ifdef ANSI_PROTOTYPES
264 va_start (args, string);
269 string = va_arg (args, char *);
272 vfprintf_unfiltered (gdb_stderr, string, args);
273 fprintf_unfiltered (gdb_stderr, "\n");
277 /* Start the printing of an error message. Way to use this is to call
278 this, output the error message (use filtered output to gdb_stderr
279 (FIXME: Some callers, like memory_error, use gdb_stdout)), ending
280 in a newline, and then call return_to_top_level (RETURN_ERROR).
281 error() provides a convenient way to do this for the special case
282 that the error message can be formatted with a single printf call,
283 but this is more general. */
287 target_terminal_ours ();
288 wrap_here (""); /* Force out any buffered output */
289 gdb_flush (gdb_stdout);
291 annotate_error_begin ();
294 fprintf_filtered (gdb_stderr, error_pre_print);
297 /* Print an error message and return to command level.
298 The first argument STRING is the error message, used as a fprintf string,
299 and the remaining args are passed as arguments to it. */
301 #ifdef ANSI_PROTOTYPES
303 error (char *string, ...)
311 #ifdef ANSI_PROTOTYPES
312 va_start (args, string);
321 #ifdef ANSI_PROTOTYPES
322 vfprintf_filtered (gdb_stderr, string, args);
327 string1 = va_arg (args, char *);
328 vfprintf_filtered (gdb_stderr, string1, args);
331 fprintf_filtered (gdb_stderr, "\n");
333 return_to_top_level (RETURN_ERROR);
338 /* Print an error message and exit reporting failure.
339 This is for a error that we cannot continue from.
340 The arguments are printed a la printf.
342 This function cannot be declared volatile (NORETURN) in an
343 ANSI environment because exit() is not declared volatile. */
347 #ifdef ANSI_PROTOTYPES
348 fatal (char *string, ...)
355 #ifdef ANSI_PROTOTYPES
356 va_start (args, string);
360 string = va_arg (args, char *);
362 fprintf_unfiltered (gdb_stderr, "\ngdb: ");
363 vfprintf_unfiltered (gdb_stderr, string, args);
364 fprintf_unfiltered (gdb_stderr, "\n");
369 /* Print an error message and exit, dumping core.
370 The arguments are printed a la printf (). */
374 #ifdef ANSI_PROTOTYPES
375 fatal_dump_core (char *string, ...)
377 fatal_dump_core (va_alist)
382 #ifdef ANSI_PROTOTYPES
383 va_start (args, string);
388 string = va_arg (args, char *);
390 /* "internal error" is always correct, since GDB should never dump
391 core, no matter what the input. */
392 fprintf_unfiltered (gdb_stderr, "\ngdb internal error: ");
393 vfprintf_unfiltered (gdb_stderr, string, args);
394 fprintf_unfiltered (gdb_stderr, "\n");
398 signal (SIGQUIT, SIG_DFL);
399 kill (getpid (), SIGQUIT);
401 /* We should never get here, but just in case... */
405 /* The strerror() function can return NULL for errno values that are
406 out of range. Provide a "safe" version that always returns a
410 safe_strerror (errnum)
416 if ((msg = strerror (errnum)) == NULL)
418 sprintf (buf, "(undocumented errno %d)", errnum);
424 /* The strsignal() function can return NULL for signal values that are
425 out of range. Provide a "safe" version that always returns a
429 safe_strsignal (signo)
435 if ((msg = strsignal (signo)) == NULL)
437 sprintf (buf, "(undocumented signal %d)", signo);
444 /* Print the system error message for errno, and also mention STRING
445 as the file name for which the error was encountered.
446 Then return to command level. */
449 perror_with_name (string)
455 err = safe_strerror (errno);
456 combined = (char *) alloca (strlen (err) + strlen (string) + 3);
457 strcpy (combined, string);
458 strcat (combined, ": ");
459 strcat (combined, err);
461 /* I understand setting these is a matter of taste. Still, some people
462 may clear errno but not know about bfd_error. Doing this here is not
464 bfd_set_error (bfd_error_no_error);
467 error ("%s.", combined);
470 /* Print the system error message for ERRCODE, and also mention STRING
471 as the file name for which the error was encountered. */
474 print_sys_errmsg (string, errcode)
481 err = safe_strerror (errcode);
482 combined = (char *) alloca (strlen (err) + strlen (string) + 3);
483 strcpy (combined, string);
484 strcat (combined, ": ");
485 strcat (combined, err);
487 /* We want anything which was printed on stdout to come out first, before
489 gdb_flush (gdb_stdout);
490 fprintf_unfiltered (gdb_stderr, "%s.\n", combined);
493 /* Control C eventually causes this to be called, at a convenient time. */
498 serial_t gdb_stdout_serial = serial_fdopen (1);
500 target_terminal_ours ();
502 /* We want all output to appear now, before we print "Quit". We
503 have 3 levels of buffering we have to flush (it's possible that
504 some of these should be changed to flush the lower-level ones
507 /* 1. The _filtered buffer. */
508 wrap_here ((char *)0);
510 /* 2. The stdio buffer. */
511 gdb_flush (gdb_stdout);
512 gdb_flush (gdb_stderr);
514 /* 3. The system-level buffer. */
515 SERIAL_FLUSH_OUTPUT (gdb_stdout_serial);
516 SERIAL_UN_FDOPEN (gdb_stdout_serial);
518 annotate_error_begin ();
520 /* Don't use *_filtered; we don't want to prompt the user to continue. */
522 fprintf_unfiltered (gdb_stderr, quit_pre_print);
525 /* If there is no terminal switching for this target, then we can't
526 possibly get screwed by the lack of job control. */
527 || current_target.to_terminal_ours == NULL)
528 fprintf_unfiltered (gdb_stderr, "Quit\n");
530 fprintf_unfiltered (gdb_stderr,
531 "Quit (expect signal SIGINT when the program is resumed)\n");
532 return_to_top_level (RETURN_QUIT);
536 #if defined(__GO32__) || defined(_WIN32)
538 /* In the absence of signals, poll keyboard for a quit.
539 Called from #define QUIT pollquit() in xm-go32.h. */
558 /* We just ignore it */
559 fprintf_unfiltered (gdb_stderr, "CTRL-A to quit, CTRL-B to quit harder\n");
569 #if defined(__GO32__) || defined(_WIN32)
585 fprintf_unfiltered (gdb_stderr, "CTRL-A to quit, CTRL-B to quit harder\n");
595 /* Done by signals */
598 /* Control C comes here */
605 /* Restore the signal handler. Harmless with BSD-style signals, needed
606 for System V-style signals. So just always do it, rather than worrying
607 about USG defines and stuff like that. */
608 signal (signo, request_quit);
610 /* start-sanitize-gm */
613 #endif /* GENERAL_MAGIC */
614 /* end-sanitize-gm */
625 /* Memory management stuff (malloc friends). */
627 /* Make a substitute size_t for non-ANSI compilers. */
629 #ifndef HAVE_STDDEF_H
631 #define size_t unsigned int
635 #if defined (NO_MMALLOC)
642 return malloc (size);
646 mrealloc (md, ptr, size)
651 if (ptr == 0) /* Guard against old realloc's */
652 return malloc (size);
654 return realloc (ptr, size);
665 #endif /* NO_MMALLOC */
667 #if defined (NO_MMALLOC) || defined (NO_MMCHECK)
675 #else /* Have mmalloc and want corruption checking */
680 fatal_dump_core ("Memory corruption");
683 /* Attempt to install hooks in mmalloc/mrealloc/mfree for the heap specified
684 by MD, to detect memory corruption. Note that MD may be NULL to specify
685 the default heap that grows via sbrk.
687 Note that for freshly created regions, we must call mmcheckf prior to any
688 mallocs in the region. Otherwise, any region which was allocated prior to
689 installing the checking hooks, which is later reallocated or freed, will
690 fail the checks! The mmcheck function only allows initial hooks to be
691 installed before the first mmalloc. However, anytime after we have called
692 mmcheck the first time to install the checking hooks, we can call it again
693 to update the function pointer to the memory corruption handler.
695 Returns zero on failure, non-zero on success. */
697 #ifndef MMCHECK_FORCE
698 #define MMCHECK_FORCE 0
705 if (!mmcheckf (md, malloc_botch, MMCHECK_FORCE))
707 /* Don't use warning(), which relies on current_target being set
708 to something other than dummy_target, until after
709 initialize_all_files(). */
712 (gdb_stderr, "warning: failed to install memory consistency checks; ");
714 (gdb_stderr, "configuration should define NO_MMCHECK or MMCHECK_FORCE\n");
720 #endif /* Have mmalloc and want corruption checking */
722 /* Called when a memory allocation fails, with the number of bytes of
723 memory requested in SIZE. */
731 fatal ("virtual memory exhausted: can't allocate %ld bytes.", size);
735 fatal ("virtual memory exhausted.");
739 /* Like mmalloc but get error if no storage available, and protect against
740 the caller wanting to allocate zero bytes. Whether to return NULL for
741 a zero byte request, or translate the request into a request for one
742 byte of zero'd storage, is a religious issue. */
755 else if ((val = mmalloc (md, size)) == NULL)
762 /* Like mrealloc but get error if no storage available. */
765 xmrealloc (md, ptr, size)
774 val = mrealloc (md, ptr, size);
778 val = mmalloc (md, size);
787 /* Like malloc but get error if no storage available, and protect against
788 the caller wanting to allocate zero bytes. */
794 return (xmmalloc ((PTR) NULL, size));
797 /* Like mrealloc but get error if no storage available. */
804 return (xmrealloc ((PTR) NULL, ptr, size));
808 /* My replacement for the read system call.
809 Used like `read' but keeps going if `read' returns too soon. */
812 myread (desc, addr, len)
822 val = read (desc, addr, len);
833 /* Make a copy of the string at PTR with SIZE characters
834 (and add a null character at the end in the copy).
835 Uses malloc to get the space. Returns the address of the copy. */
838 savestring (ptr, size)
842 register char *p = (char *) xmalloc (size + 1);
843 memcpy (p, ptr, size);
849 msavestring (md, ptr, size)
854 register char *p = (char *) xmmalloc (md, size + 1);
855 memcpy (p, ptr, size);
860 /* The "const" is so it compiles under DGUX (which prototypes strsave
861 in <string.h>. FIXME: This should be named "xstrsave", shouldn't it?
862 Doesn't real strsave return NULL if out of memory? */
867 return savestring (ptr, strlen (ptr));
875 return (msavestring (md, ptr, strlen (ptr)));
879 print_spaces (n, file)
887 /* Print a host address. */
890 gdb_print_address (addr, stream)
895 /* We could use the %p conversion specifier to fprintf if we had any
896 way of knowing whether this host supports it. But the following
897 should work on the Alpha and on 32 bit machines. */
899 fprintf_filtered (stream, "0x%lx", (unsigned long)addr);
902 /* Ask user a y-or-n question and return 1 iff answer is yes.
903 Takes three args which are given to printf to print the question.
904 The first, a control string, should end in "? ".
905 It should not say how to answer, because we do that. */
909 #ifdef ANSI_PROTOTYPES
910 query (char *ctlstr, ...)
921 #ifdef ANSI_PROTOTYPES
922 va_start (args, ctlstr);
926 ctlstr = va_arg (args, char *);
931 return query_hook (ctlstr, args);
934 /* Automatically answer "yes" if input is not from a terminal. */
935 if (!input_from_terminal_p ())
938 /* FIXME Automatically answer "yes" if called from MacGDB. */
945 wrap_here (""); /* Flush any buffered output */
946 gdb_flush (gdb_stdout);
948 if (annotation_level > 1)
949 printf_filtered ("\n\032\032pre-query\n");
951 vfprintf_filtered (gdb_stdout, ctlstr, args);
952 printf_filtered ("(y or n) ");
954 if (annotation_level > 1)
955 printf_filtered ("\n\032\032query\n");
958 /* If not in MacGDB, move to a new line so the entered line doesn't
959 have a prompt on the front of it. */
961 fputs_unfiltered ("\n", gdb_stdout);
964 gdb_flush (gdb_stdout);
965 answer = fgetc (stdin);
966 clearerr (stdin); /* in case of C-d */
967 if (answer == EOF) /* C-d */
972 if (answer != '\n') /* Eat rest of input line, to EOF or newline */
975 ans2 = fgetc (stdin);
978 while (ans2 != EOF && ans2 != '\n');
991 printf_filtered ("Please answer y or n.\n");
994 if (annotation_level > 1)
995 printf_filtered ("\n\032\032post-query\n");
1000 /* Parse a C escape sequence. STRING_PTR points to a variable
1001 containing a pointer to the string to parse. That pointer
1002 should point to the character after the \. That pointer
1003 is updated past the characters we use. The value of the
1004 escape sequence is returned.
1006 A negative value means the sequence \ newline was seen,
1007 which is supposed to be equivalent to nothing at all.
1009 If \ is followed by a null character, we return a negative
1010 value and leave the string pointer pointing at the null character.
1012 If \ is followed by 000, we return 0 and leave the string pointer
1013 after the zeros. A value of 0 does not mean end of string. */
1016 parse_escape (string_ptr)
1019 register int c = *(*string_ptr)++;
1023 return 007; /* Bell (alert) char */
1026 case 'e': /* Escape character */
1044 c = *(*string_ptr)++;
1046 c = parse_escape (string_ptr);
1049 return (c & 0200) | (c & 037);
1060 register int i = c - '0';
1061 register int count = 0;
1064 if ((c = *(*string_ptr)++) >= '0' && c <= '7')
1082 /* Print the character C on STREAM as part of the contents of a literal
1083 string whose delimiter is QUOTER. Note that this routine should only
1084 be call for printing things which are independent of the language
1085 of the program being debugged. */
1088 gdb_printchar (c, stream, quoter)
1094 c &= 0xFF; /* Avoid sign bit follies */
1096 if ( c < 0x20 || /* Low control chars */
1097 (c >= 0x7F && c < 0xA0) || /* DEL, High controls */
1098 (sevenbit_strings && c >= 0x80)) { /* high order bit set */
1102 fputs_filtered ("\\n", stream);
1105 fputs_filtered ("\\b", stream);
1108 fputs_filtered ("\\t", stream);
1111 fputs_filtered ("\\f", stream);
1114 fputs_filtered ("\\r", stream);
1117 fputs_filtered ("\\e", stream);
1120 fputs_filtered ("\\a", stream);
1123 fprintf_filtered (stream, "\\%.3o", (unsigned int) c);
1127 if (c == '\\' || c == quoter)
1128 fputs_filtered ("\\", stream);
1129 fprintf_filtered (stream, "%c", c);
1133 /* Number of lines per page or UINT_MAX if paging is disabled. */
1134 static unsigned int lines_per_page;
1135 /* Number of chars per line or UNIT_MAX is line folding is disabled. */
1136 static unsigned int chars_per_line;
1137 /* Current count of lines printed on this page, chars on this line. */
1138 static unsigned int lines_printed, chars_printed;
1140 /* Buffer and start column of buffered text, for doing smarter word-
1141 wrapping. When someone calls wrap_here(), we start buffering output
1142 that comes through fputs_filtered(). If we see a newline, we just
1143 spit it out and forget about the wrap_here(). If we see another
1144 wrap_here(), we spit it out and remember the newer one. If we see
1145 the end of the line, we spit out a newline, the indent, and then
1146 the buffered output. */
1148 /* Malloc'd buffer with chars_per_line+2 bytes. Contains characters which
1149 are waiting to be output (they have already been counted in chars_printed).
1150 When wrap_buffer[0] is null, the buffer is empty. */
1151 static char *wrap_buffer;
1153 /* Pointer in wrap_buffer to the next character to fill. */
1154 static char *wrap_pointer;
1156 /* String to indent by if the wrap occurs. Must not be NULL if wrap_column
1158 static char *wrap_indent;
1160 /* Column number on the screen where wrap_buffer begins, or 0 if wrapping
1161 is not in effect. */
1162 static int wrap_column;
1166 set_width_command (args, from_tty, c)
1169 struct cmd_list_element *c;
1173 wrap_buffer = (char *) xmalloc (chars_per_line + 2);
1174 wrap_buffer[0] = '\0';
1177 wrap_buffer = (char *) xrealloc (wrap_buffer, chars_per_line + 2);
1178 wrap_pointer = wrap_buffer; /* Start it at the beginning */
1181 /* Wait, so the user can read what's on the screen. Prompt the user
1182 to continue by pressing RETURN. */
1185 prompt_for_continue ()
1188 char cont_prompt[120];
1190 if (annotation_level > 1)
1191 printf_unfiltered ("\n\032\032pre-prompt-for-continue\n");
1193 strcpy (cont_prompt,
1194 "---Type <return> to continue, or q <return> to quit---");
1195 if (annotation_level > 1)
1196 strcat (cont_prompt, "\n\032\032prompt-for-continue\n");
1198 /* We must do this *before* we call gdb_readline, else it will eventually
1199 call us -- thinking that we're trying to print beyond the end of the
1201 reinitialize_more_filter ();
1204 /* On a real operating system, the user can quit with SIGINT.
1207 'q' is provided on all systems so users don't have to change habits
1208 from system to system, and because telling them what to do in
1209 the prompt is more user-friendly than expecting them to think of
1211 /* Call readline, not gdb_readline, because GO32 readline handles control-C
1212 whereas control-C to gdb_readline will cause the user to get dumped
1214 ignore = readline (cont_prompt);
1216 if (annotation_level > 1)
1217 printf_unfiltered ("\n\032\032post-prompt-for-continue\n");
1222 while (*p == ' ' || *p == '\t')
1225 request_quit (SIGINT);
1230 /* Now we have to do this again, so that GDB will know that it doesn't
1231 need to save the ---Type <return>--- line at the top of the screen. */
1232 reinitialize_more_filter ();
1234 dont_repeat (); /* Forget prev cmd -- CR won't repeat it. */
1237 /* Reinitialize filter; ie. tell it to reset to original values. */
1240 reinitialize_more_filter ()
1246 /* Indicate that if the next sequence of characters overflows the line,
1247 a newline should be inserted here rather than when it hits the end.
1248 If INDENT is non-null, it is a string to be printed to indent the
1249 wrapped part on the next line. INDENT must remain accessible until
1250 the next call to wrap_here() or until a newline is printed through
1253 If the line is already overfull, we immediately print a newline and
1254 the indentation, and disable further wrapping.
1256 If we don't know the width of lines, but we know the page height,
1257 we must not wrap words, but should still keep track of newlines
1258 that were explicitly printed.
1260 INDENT should not contain tabs, as that will mess up the char count
1261 on the next line. FIXME.
1263 This routine is guaranteed to force out any output which has been
1264 squirreled away in the wrap_buffer, so wrap_here ((char *)0) can be
1265 used to force out output from the wrap_buffer. */
1271 /* This should have been allocated, but be paranoid anyway. */
1277 *wrap_pointer = '\0';
1278 fputs_unfiltered (wrap_buffer, gdb_stdout);
1280 wrap_pointer = wrap_buffer;
1281 wrap_buffer[0] = '\0';
1282 if (chars_per_line == UINT_MAX) /* No line overflow checking */
1286 else if (chars_printed >= chars_per_line)
1288 puts_filtered ("\n");
1290 puts_filtered (indent);
1295 wrap_column = chars_printed;
1299 wrap_indent = indent;
1303 /* Ensure that whatever gets printed next, using the filtered output
1304 commands, starts at the beginning of the line. I.E. if there is
1305 any pending output for the current line, flush it and start a new
1306 line. Otherwise do nothing. */
1311 if (chars_printed > 0)
1313 puts_filtered ("\n");
1319 gdb_fopen (name, mode)
1323 return fopen (name, mode);
1332 flush_hook (stream);
1339 /* Like fputs but if FILTER is true, pause after every screenful.
1341 Regardless of FILTER can wrap at points other than the final
1342 character of a line.
1344 Unlike fputs, fputs_maybe_filtered does not return a value.
1345 It is OK for LINEBUFFER to be NULL, in which case just don't print
1348 Note that a longjmp to top level may occur in this routine (only if
1349 FILTER is true) (since prompt_for_continue may do so) so this
1350 routine should not be called when cleanups are not in place. */
1353 fputs_maybe_filtered (linebuffer, stream, filter)
1354 const char *linebuffer;
1358 const char *lineptr;
1360 if (linebuffer == 0)
1363 /* Don't do any filtering if it is disabled. */
1364 if (stream != gdb_stdout
1365 || (lines_per_page == UINT_MAX && chars_per_line == UINT_MAX))
1367 fputs_unfiltered (linebuffer, stream);
1371 /* Go through and output each character. Show line extension
1372 when this is necessary; prompt user for new page when this is
1375 lineptr = linebuffer;
1378 /* Possible new page. */
1380 (lines_printed >= lines_per_page - 1))
1381 prompt_for_continue ();
1383 while (*lineptr && *lineptr != '\n')
1385 /* Print a single line. */
1386 if (*lineptr == '\t')
1389 *wrap_pointer++ = '\t';
1391 fputc_unfiltered ('\t', stream);
1392 /* Shifting right by 3 produces the number of tab stops
1393 we have already passed, and then adding one and
1394 shifting left 3 advances to the next tab stop. */
1395 chars_printed = ((chars_printed >> 3) + 1) << 3;
1401 *wrap_pointer++ = *lineptr;
1403 fputc_unfiltered (*lineptr, stream);
1408 if (chars_printed >= chars_per_line)
1410 unsigned int save_chars = chars_printed;
1414 /* If we aren't actually wrapping, don't output newline --
1415 if chars_per_line is right, we probably just overflowed
1416 anyway; if it's wrong, let us keep going. */
1418 fputc_unfiltered ('\n', stream);
1420 /* Possible new page. */
1421 if (lines_printed >= lines_per_page - 1)
1422 prompt_for_continue ();
1424 /* Now output indentation and wrapped string */
1427 fputs_unfiltered (wrap_indent, stream);
1428 *wrap_pointer = '\0'; /* Null-terminate saved stuff */
1429 fputs_unfiltered (wrap_buffer, stream); /* and eject it */
1430 /* FIXME, this strlen is what prevents wrap_indent from
1431 containing tabs. However, if we recurse to print it
1432 and count its chars, we risk trouble if wrap_indent is
1433 longer than (the user settable) chars_per_line.
1434 Note also that this can set chars_printed > chars_per_line
1435 if we are printing a long string. */
1436 chars_printed = strlen (wrap_indent)
1437 + (save_chars - wrap_column);
1438 wrap_pointer = wrap_buffer; /* Reset buffer */
1439 wrap_buffer[0] = '\0';
1440 wrap_column = 0; /* And disable fancy wrap */
1445 if (*lineptr == '\n')
1448 wrap_here ((char *)0); /* Spit out chars, cancel further wraps */
1450 fputc_unfiltered ('\n', stream);
1457 fputs_filtered (linebuffer, stream)
1458 const char *linebuffer;
1461 fputs_maybe_filtered (linebuffer, stream, 1);
1465 putchar_unfiltered (c)
1472 fputs_unfiltered (buf, gdb_stdout);
1477 fputc_unfiltered (c, stream)
1485 fputs_unfiltered (buf, stream);
1490 /* Print a variable number of ARGS using format FORMAT. If this
1491 information is going to put the amount written (since the last call
1492 to REINITIALIZE_MORE_FILTER or the last page break) over the page size,
1493 call prompt_for_continue to get the users permision to continue.
1495 Unlike fprintf, this function does not return a value.
1497 We implement three variants, vfprintf (takes a vararg list and stream),
1498 fprintf (takes a stream to write on), and printf (the usual).
1500 Note also that a longjmp to top level may occur in this routine
1501 (since prompt_for_continue may do so) so this routine should not be
1502 called when cleanups are not in place. */
1505 vfprintf_maybe_filtered (stream, format, args, filter)
1512 struct cleanup *old_cleanups;
1514 vasprintf (&linebuffer, format, args);
1515 if (linebuffer == NULL)
1517 fputs_unfiltered ("\ngdb: virtual memory exhausted.\n", gdb_stderr);
1520 old_cleanups = make_cleanup (free, linebuffer);
1521 fputs_maybe_filtered (linebuffer, stream, filter);
1522 do_cleanups (old_cleanups);
1527 vfprintf_filtered (stream, format, args)
1532 vfprintf_maybe_filtered (stream, format, args, 1);
1536 vfprintf_unfiltered (stream, format, args)
1542 struct cleanup *old_cleanups;
1544 vasprintf (&linebuffer, format, args);
1545 if (linebuffer == NULL)
1547 fputs_unfiltered ("\ngdb: virtual memory exhausted.\n", gdb_stderr);
1550 old_cleanups = make_cleanup (free, linebuffer);
1551 fputs_unfiltered (linebuffer, stream);
1552 do_cleanups (old_cleanups);
1556 vprintf_filtered (format, args)
1560 vfprintf_maybe_filtered (gdb_stdout, format, args, 1);
1564 vprintf_unfiltered (format, args)
1568 vfprintf_unfiltered (gdb_stdout, format, args);
1573 #ifdef ANSI_PROTOTYPES
1574 fprintf_filtered (FILE *stream, const char *format, ...)
1576 fprintf_filtered (va_alist)
1581 #ifdef ANSI_PROTOTYPES
1582 va_start (args, format);
1588 stream = va_arg (args, FILE *);
1589 format = va_arg (args, char *);
1591 vfprintf_filtered (stream, format, args);
1597 #ifdef ANSI_PROTOTYPES
1598 fprintf_unfiltered (FILE *stream, const char *format, ...)
1600 fprintf_unfiltered (va_alist)
1605 #ifdef ANSI_PROTOTYPES
1606 va_start (args, format);
1612 stream = va_arg (args, FILE *);
1613 format = va_arg (args, char *);
1615 vfprintf_unfiltered (stream, format, args);
1619 /* Like fprintf_filtered, but prints its result indented.
1620 Called as fprintfi_filtered (spaces, stream, format, ...); */
1624 #ifdef ANSI_PROTOTYPES
1625 fprintfi_filtered (int spaces, FILE *stream, const char *format, ...)
1627 fprintfi_filtered (va_alist)
1632 #ifdef ANSI_PROTOTYPES
1633 va_start (args, format);
1640 spaces = va_arg (args, int);
1641 stream = va_arg (args, FILE *);
1642 format = va_arg (args, char *);
1644 print_spaces_filtered (spaces, stream);
1646 vfprintf_filtered (stream, format, args);
1653 #ifdef ANSI_PROTOTYPES
1654 printf_filtered (const char *format, ...)
1656 printf_filtered (va_alist)
1661 #ifdef ANSI_PROTOTYPES
1662 va_start (args, format);
1667 format = va_arg (args, char *);
1669 vfprintf_filtered (gdb_stdout, format, args);
1676 #ifdef ANSI_PROTOTYPES
1677 printf_unfiltered (const char *format, ...)
1679 printf_unfiltered (va_alist)
1684 #ifdef ANSI_PROTOTYPES
1685 va_start (args, format);
1690 format = va_arg (args, char *);
1692 vfprintf_unfiltered (gdb_stdout, format, args);
1696 /* Like printf_filtered, but prints it's result indented.
1697 Called as printfi_filtered (spaces, format, ...); */
1701 #ifdef ANSI_PROTOTYPES
1702 printfi_filtered (int spaces, const char *format, ...)
1704 printfi_filtered (va_alist)
1709 #ifdef ANSI_PROTOTYPES
1710 va_start (args, format);
1716 spaces = va_arg (args, int);
1717 format = va_arg (args, char *);
1719 print_spaces_filtered (spaces, gdb_stdout);
1720 vfprintf_filtered (gdb_stdout, format, args);
1724 /* Easy -- but watch out!
1726 This routine is *not* a replacement for puts()! puts() appends a newline.
1727 This one doesn't, and had better not! */
1730 puts_filtered (string)
1733 fputs_filtered (string, gdb_stdout);
1737 puts_unfiltered (string)
1740 fputs_unfiltered (string, gdb_stdout);
1743 /* Return a pointer to N spaces and a null. The pointer is good
1744 until the next call to here. */
1750 static char *spaces;
1751 static int max_spaces;
1757 spaces = (char *) xmalloc (n+1);
1758 for (t = spaces+n; t != spaces;)
1764 return spaces + max_spaces - n;
1767 /* Print N spaces. */
1769 print_spaces_filtered (n, stream)
1773 fputs_filtered (n_spaces (n), stream);
1776 /* C++ demangler stuff. */
1778 /* fprintf_symbol_filtered attempts to demangle NAME, a symbol in language
1779 LANG, using demangling args ARG_MODE, and print it filtered to STREAM.
1780 If the name is not mangled, or the language for the name is unknown, or
1781 demangling is off, the name is printed in its "raw" form. */
1784 fprintf_symbol_filtered (stream, name, lang, arg_mode)
1794 /* If user wants to see raw output, no problem. */
1797 fputs_filtered (name, stream);
1803 case language_cplus:
1804 demangled = cplus_demangle (name, arg_mode);
1806 case language_chill:
1807 demangled = chill_demangle (name);
1813 fputs_filtered (demangled ? demangled : name, stream);
1814 if (demangled != NULL)
1822 /* Do a strcmp() type operation on STRING1 and STRING2, ignoring any
1823 differences in whitespace. Returns 0 if they match, non-zero if they
1824 don't (slightly different than strcmp()'s range of return values).
1826 As an extra hack, string1=="FOO(ARGS)" matches string2=="FOO".
1827 This "feature" is useful when searching for matching C++ function names
1828 (such as if the user types 'break FOO', where FOO is a mangled C++
1832 strcmp_iw (string1, string2)
1833 const char *string1;
1834 const char *string2;
1836 while ((*string1 != '\0') && (*string2 != '\0'))
1838 while (isspace (*string1))
1842 while (isspace (*string2))
1846 if (*string1 != *string2)
1850 if (*string1 != '\0')
1856 return (*string1 != '\0' && *string1 != '(') || (*string2 != '\0');
1863 struct cmd_list_element *c;
1865 c = add_set_cmd ("width", class_support, var_uinteger,
1866 (char *)&chars_per_line,
1867 "Set number of characters gdb thinks are in a line.",
1869 add_show_from_set (c, &showlist);
1870 c->function.sfunc = set_width_command;
1873 (add_set_cmd ("height", class_support,
1874 var_uinteger, (char *)&lines_per_page,
1875 "Set number of lines gdb thinks are in a page.", &setlist),
1878 /* These defaults will be used if we are unable to get the correct
1879 values from termcap. */
1880 #if defined(__GO32__)
1881 lines_per_page = ScreenRows();
1882 chars_per_line = ScreenCols();
1884 lines_per_page = 24;
1885 chars_per_line = 80;
1887 #if !defined MPW && !defined _WIN32
1888 /* No termcap under MPW, although might be cool to do something
1889 by looking at worksheet or console window sizes. */
1890 /* Initialize the screen height and width from termcap. */
1892 char *termtype = getenv ("TERM");
1894 /* Positive means success, nonpositive means failure. */
1897 /* 2048 is large enough for all known terminals, according to the
1898 GNU termcap manual. */
1899 char term_buffer[2048];
1903 status = tgetent (term_buffer, termtype);
1908 val = tgetnum ("li");
1910 lines_per_page = val;
1912 /* The number of lines per page is not mentioned
1913 in the terminal description. This probably means
1914 that paging is not useful (e.g. emacs shell window),
1915 so disable paging. */
1916 lines_per_page = UINT_MAX;
1918 val = tgetnum ("co");
1920 chars_per_line = val;
1926 #if defined(SIGWINCH) && defined(SIGWINCH_HANDLER)
1928 /* If there is a better way to determine the window size, use it. */
1929 SIGWINCH_HANDLER ();
1932 /* If the output is not a terminal, don't paginate it. */
1933 if (!ISATTY (gdb_stdout))
1934 lines_per_page = UINT_MAX;
1936 set_width_command ((char *)NULL, 0, c);
1939 (add_set_cmd ("demangle", class_support, var_boolean,
1941 "Set demangling of encoded C++ names when displaying symbols.",
1946 (add_set_cmd ("sevenbit-strings", class_support, var_boolean,
1947 (char *)&sevenbit_strings,
1948 "Set printing of 8-bit characters in strings as \\nnn.",
1953 (add_set_cmd ("asm-demangle", class_support, var_boolean,
1954 (char *)&asm_demangle,
1955 "Set demangling of C++ names in disassembly listings.",
1960 /* Machine specific function to handle SIGWINCH signal. */
1962 #ifdef SIGWINCH_HANDLER_BODY
1963 SIGWINCH_HANDLER_BODY
1966 /* Support for converting target fp numbers into host DOUBLEST format. */
1968 /* XXX - This code should really be in libiberty/floatformat.c, however
1969 configuration issues with libiberty made this very difficult to do in the
1972 #include "floatformat.h"
1973 #include <math.h> /* ldexp */
1975 /* The odds that CHAR_BIT will be anything but 8 are low enough that I'm not
1976 going to bother with trying to muck around with whether it is defined in
1977 a system header, what we do if not, etc. */
1978 #define FLOATFORMAT_CHAR_BIT 8
1980 static unsigned long get_field PARAMS ((unsigned char *,
1981 enum floatformat_byteorders,
1986 /* Extract a field which starts at START and is LEN bytes long. DATA and
1987 TOTAL_LEN are the thing we are extracting it from, in byteorder ORDER. */
1988 static unsigned long
1989 get_field (data, order, total_len, start, len)
1990 unsigned char *data;
1991 enum floatformat_byteorders order;
1992 unsigned int total_len;
1996 unsigned long result;
1997 unsigned int cur_byte;
2000 /* Start at the least significant part of the field. */
2001 cur_byte = (start + len) / FLOATFORMAT_CHAR_BIT;
2002 if (order == floatformat_little)
2003 cur_byte = (total_len / FLOATFORMAT_CHAR_BIT) - cur_byte - 1;
2005 ((start + len) % FLOATFORMAT_CHAR_BIT) - FLOATFORMAT_CHAR_BIT;
2006 result = *(data + cur_byte) >> (-cur_bitshift);
2007 cur_bitshift += FLOATFORMAT_CHAR_BIT;
2008 if (order == floatformat_little)
2013 /* Move towards the most significant part of the field. */
2014 while (cur_bitshift < len)
2016 if (len - cur_bitshift < FLOATFORMAT_CHAR_BIT)
2017 /* This is the last byte; zero out the bits which are not part of
2020 (*(data + cur_byte) & ((1 << (len - cur_bitshift)) - 1))
2023 result |= *(data + cur_byte) << cur_bitshift;
2024 cur_bitshift += FLOATFORMAT_CHAR_BIT;
2025 if (order == floatformat_little)
2033 /* Convert from FMT to a DOUBLEST.
2034 FROM is the address of the extended float.
2035 Store the DOUBLEST in *TO. */
2038 floatformat_to_doublest (fmt, from, to)
2039 const struct floatformat *fmt;
2043 unsigned char *ufrom = (unsigned char *)from;
2047 unsigned int mant_bits, mant_off;
2049 int special_exponent; /* It's a NaN, denorm or zero */
2051 exponent = get_field (ufrom, fmt->byteorder, fmt->totalsize,
2052 fmt->exp_start, fmt->exp_len);
2053 /* Note that if exponent indicates a NaN, we can't really do anything useful
2054 (not knowing if the host has NaN's, or how to build one). So it will
2055 end up as an infinity or something close; that is OK. */
2057 mant_bits_left = fmt->man_len;
2058 mant_off = fmt->man_start;
2061 special_exponent = exponent == 0 || exponent == fmt->exp_nan;
2063 /* Don't bias zero's, denorms or NaNs. */
2064 if (!special_exponent)
2065 exponent -= fmt->exp_bias;
2067 /* Build the result algebraically. Might go infinite, underflow, etc;
2070 /* If this format uses a hidden bit, explicitly add it in now. Otherwise,
2071 increment the exponent by one to account for the integer bit. */
2073 if (!special_exponent)
2074 if (fmt->intbit == floatformat_intbit_no)
2075 dto = ldexp (1.0, exponent);
2079 while (mant_bits_left > 0)
2081 mant_bits = min (mant_bits_left, 32);
2083 mant = get_field (ufrom, fmt->byteorder, fmt->totalsize,
2084 mant_off, mant_bits);
2086 dto += ldexp ((double)mant, exponent - mant_bits);
2087 exponent -= mant_bits;
2088 mant_off += mant_bits;
2089 mant_bits_left -= mant_bits;
2092 /* Negate it if negative. */
2093 if (get_field (ufrom, fmt->byteorder, fmt->totalsize, fmt->sign_start, 1))
2098 static void put_field PARAMS ((unsigned char *, enum floatformat_byteorders,
2104 /* Set a field which starts at START and is LEN bytes long. DATA and
2105 TOTAL_LEN are the thing we are extracting it from, in byteorder ORDER. */
2107 put_field (data, order, total_len, start, len, stuff_to_put)
2108 unsigned char *data;
2109 enum floatformat_byteorders order;
2110 unsigned int total_len;
2113 unsigned long stuff_to_put;
2115 unsigned int cur_byte;
2118 /* Start at the least significant part of the field. */
2119 cur_byte = (start + len) / FLOATFORMAT_CHAR_BIT;
2120 if (order == floatformat_little)
2121 cur_byte = (total_len / FLOATFORMAT_CHAR_BIT) - cur_byte - 1;
2123 ((start + len) % FLOATFORMAT_CHAR_BIT) - FLOATFORMAT_CHAR_BIT;
2124 *(data + cur_byte) &=
2125 ~(((1 << ((start + len) % FLOATFORMAT_CHAR_BIT)) - 1) << (-cur_bitshift));
2126 *(data + cur_byte) |=
2127 (stuff_to_put & ((1 << FLOATFORMAT_CHAR_BIT) - 1)) << (-cur_bitshift);
2128 cur_bitshift += FLOATFORMAT_CHAR_BIT;
2129 if (order == floatformat_little)
2134 /* Move towards the most significant part of the field. */
2135 while (cur_bitshift < len)
2137 if (len - cur_bitshift < FLOATFORMAT_CHAR_BIT)
2139 /* This is the last byte. */
2140 *(data + cur_byte) &=
2141 ~((1 << (len - cur_bitshift)) - 1);
2142 *(data + cur_byte) |= (stuff_to_put >> cur_bitshift);
2145 *(data + cur_byte) = ((stuff_to_put >> cur_bitshift)
2146 & ((1 << FLOATFORMAT_CHAR_BIT) - 1));
2147 cur_bitshift += FLOATFORMAT_CHAR_BIT;
2148 if (order == floatformat_little)
2155 #ifdef HAVE_LONG_DOUBLE
2156 /* Return the fractional part of VALUE, and put the exponent of VALUE in *EPTR.
2157 The range of the returned value is >= 0.5 and < 1.0. This is equivalent to
2158 frexp, but operates on the long double data type. */
2160 static long double ldfrexp PARAMS ((long double value, int *eptr));
2163 ldfrexp (value, eptr)
2170 /* Unfortunately, there are no portable functions for extracting the exponent
2171 of a long double, so we have to do it iteratively by multiplying or dividing
2172 by two until the fraction is between 0.5 and 1.0. */
2180 if (value >= tmp) /* Value >= 1.0 */
2181 while (value >= tmp)
2186 else if (value != 0.0l) /* Value < 1.0 and > 0.0 */
2200 #endif /* HAVE_LONG_DOUBLE */
2203 /* The converse: convert the DOUBLEST *FROM to an extended float
2204 and store where TO points. Neither FROM nor TO have any alignment
2208 floatformat_from_doublest (fmt, from, to)
2209 CONST struct floatformat *fmt;
2216 unsigned int mant_bits, mant_off;
2218 unsigned char *uto = (unsigned char *)to;
2220 memcpy (&dfrom, from, sizeof (dfrom));
2221 memset (uto, 0, fmt->totalsize / FLOATFORMAT_CHAR_BIT);
2223 return; /* Result is zero */
2227 put_field (uto, fmt->byteorder, fmt->totalsize, fmt->exp_start,
2228 fmt->exp_len, fmt->exp_nan);
2229 /* Be sure it's not infinity, but NaN value is irrel */
2230 put_field (uto, fmt->byteorder, fmt->totalsize, fmt->man_start,
2235 /* If negative, set the sign bit. */
2238 put_field (uto, fmt->byteorder, fmt->totalsize, fmt->sign_start, 1, 1);
2242 /* How to tell an infinity from an ordinary number? FIXME-someday */
2244 #ifdef HAVE_LONG_DOUBLE
2245 mant = ldfrexp (dfrom, &exponent);
2247 mant = frexp (dfrom, &exponent);
2250 put_field (uto, fmt->byteorder, fmt->totalsize, fmt->exp_start, fmt->exp_len,
2251 exponent + fmt->exp_bias - 1);
2253 mant_bits_left = fmt->man_len;
2254 mant_off = fmt->man_start;
2255 while (mant_bits_left > 0)
2257 unsigned long mant_long;
2258 mant_bits = mant_bits_left < 32 ? mant_bits_left : 32;
2260 mant *= 4294967296.0;
2261 mant_long = (unsigned long)mant;
2264 /* If the integer bit is implicit, then we need to discard it.
2265 If we are discarding a zero, we should be (but are not) creating
2266 a denormalized number which means adjusting the exponent
2268 if (mant_bits_left == fmt->man_len
2269 && fmt->intbit == floatformat_intbit_no)
2277 /* The bits we want are in the most significant MANT_BITS bits of
2278 mant_long. Move them to the least significant. */
2279 mant_long >>= 32 - mant_bits;
2282 put_field (uto, fmt->byteorder, fmt->totalsize,
2283 mant_off, mant_bits, mant_long);
2284 mant_off += mant_bits;
2285 mant_bits_left -= mant_bits;
2289 /* temporary storage using circular buffer */
2295 static char buf[MAXCELLS][CELLSIZE];
2297 if (++cell>MAXCELLS) cell=0;
2301 /* print routines to handle variable size regs, etc */
2306 char *paddr_str=get_cell();
2307 switch (sizeof(t_addr))
2310 sprintf(paddr_str,"%08x%08x",
2311 (unsigned long)(addr>>32),(unsigned long)(addr&0xffffffff));
2314 sprintf(paddr_str,"%08x",(unsigned long)addr);
2317 sprintf(paddr_str,"%04x",(unsigned short)(addr&0xffff));
2320 sprintf(paddr_str,"%x",addr);
2329 char *preg_str=get_cell();
2330 switch (sizeof(t_reg))
2333 sprintf(preg_str,"%08x%08x",
2334 (unsigned long)(reg>>32),(unsigned long)(reg&0xffffffff));
2337 sprintf(preg_str,"%08x",(unsigned long)reg);
2340 sprintf(preg_str,"%04x",(unsigned short)(reg&0xffff));
2343 sprintf(preg_str,"%x",reg);