1 /* General utility routines for GDB, the GNU debugger.
2 Copyright 1986, 1989, 1990, 1991, 1992, 1995 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 #if !defined(__GO32__) && !defined(__WIN32__) && !defined(MPW)
22 #include <sys/ioctl.h>
23 #include <sys/param.h>
26 #ifdef ANSI_PROTOTYPES
32 #include "gdb_string.h"
43 #include "expression.h"
49 /* readline defines this. */
52 /* Prototypes for local functions */
55 fatal_dump_core PARAMS((char *, ...));
58 prompt_for_continue PARAMS ((void));
61 set_width_command PARAMS ((char *, int, struct cmd_list_element *));
63 /* If this definition isn't overridden by the header files, assume
64 that isatty and fileno exist on this system. */
66 #define ISATTY(FP) (isatty (fileno (FP)))
69 /* Chain of cleanup actions established with make_cleanup,
70 to be executed if an error happens. */
72 static struct cleanup *cleanup_chain;
74 /* Nonzero if we have job control. */
78 /* Nonzero means a quit has been requested. */
82 /* Nonzero means quit immediately if Control-C is typed now, rather
83 than waiting until QUIT is executed. Be careful in setting this;
84 code which executes with immediate_quit set has to be very careful
85 about being able to deal with being interrupted at any time. It is
86 almost always better to use QUIT; the only exception I can think of
87 is being able to quit out of a system call (using EINTR loses if
88 the SIGINT happens between the previous QUIT and the system call).
89 To immediately quit in the case in which a SIGINT happens between
90 the previous QUIT and setting immediate_quit (desirable anytime we
91 expect to block), call QUIT after setting immediate_quit. */
95 /* Nonzero means that encoded C++ names should be printed out in their
96 C++ form rather than raw. */
100 /* Nonzero means that encoded C++ names should be printed out in their
101 C++ form even in assembler language displays. If this is set, but
102 DEMANGLE is zero, names are printed raw, i.e. DEMANGLE controls. */
104 int asm_demangle = 0;
106 /* Nonzero means that strings with character values >0x7F should be printed
107 as octal escapes. Zero means just print the value (e.g. it's an
108 international character, and the terminal or window can cope.) */
110 int sevenbit_strings = 0;
112 /* String to be printed before error messages, if any. */
114 char *error_pre_print;
116 /* String to be printed before quit messages, if any. */
118 char *quit_pre_print;
120 /* String to be printed before warning messages, if any. */
122 char *warning_pre_print = "\nwarning: ";
124 /* Add a new cleanup to the cleanup_chain,
125 and return the previous chain pointer
126 to be passed later to do_cleanups or discard_cleanups.
127 Args are FUNCTION to clean up with, and ARG to pass to it. */
130 make_cleanup (function, arg)
131 void (*function) PARAMS ((PTR));
134 register struct cleanup *new
135 = (struct cleanup *) xmalloc (sizeof (struct cleanup));
136 register struct cleanup *old_chain = cleanup_chain;
138 new->next = cleanup_chain;
139 new->function = function;
146 /* Discard cleanups and do the actions they describe
147 until we get back to the point OLD_CHAIN in the cleanup_chain. */
150 do_cleanups (old_chain)
151 register struct cleanup *old_chain;
153 register struct cleanup *ptr;
154 while ((ptr = cleanup_chain) != old_chain)
156 cleanup_chain = ptr->next; /* Do this first incase recursion */
157 (*ptr->function) (ptr->arg);
162 /* Discard cleanups, not doing the actions they describe,
163 until we get back to the point OLD_CHAIN in the cleanup_chain. */
166 discard_cleanups (old_chain)
167 register struct cleanup *old_chain;
169 register struct cleanup *ptr;
170 while ((ptr = cleanup_chain) != old_chain)
172 cleanup_chain = ptr->next;
177 /* Set the cleanup_chain to 0, and return the old cleanup chain. */
181 struct cleanup *old_chain = cleanup_chain;
187 /* Restore the cleanup chain from a previously saved chain. */
189 restore_cleanups (chain)
190 struct cleanup *chain;
192 cleanup_chain = chain;
195 /* This function is useful for cleanups.
199 old_chain = make_cleanup (free_current_contents, &foo);
201 to arrange to free the object thus allocated. */
204 free_current_contents (location)
210 /* Provide a known function that does nothing, to use as a base for
211 for a possibly long chain of cleanups. This is useful where we
212 use the cleanup chain for handling normal cleanups as well as dealing
213 with cleanups that need to be done as a result of a call to error().
214 In such cases, we may not be certain where the first cleanup is, unless
215 we have a do-nothing one to always use as the base. */
225 /* Print a warning message. Way to use this is to call warning_begin,
226 output the warning message (use unfiltered output to gdb_stderr),
227 ending in a newline. There is not currently a warning_end that you
228 call afterwards, but such a thing might be added if it is useful
229 for a GUI to separate warning messages from other output.
231 FIXME: Why do warnings use unfiltered output and errors filtered?
232 Is this anything other than a historical accident? */
237 target_terminal_ours ();
238 wrap_here(""); /* Force out any buffered output */
239 gdb_flush (gdb_stdout);
240 if (warning_pre_print)
241 fprintf_unfiltered (gdb_stderr, warning_pre_print);
244 /* Print a warning message.
245 The first argument STRING is the warning message, used as a fprintf string,
246 and the remaining args are passed as arguments to it.
247 The primary difference between warnings and errors is that a warning
248 does not force the return to command level. */
252 #ifdef ANSI_PROTOTYPES
253 warning (char *string, ...)
260 #ifdef ANSI_PROTOTYPES
261 va_start (args, string);
266 string = va_arg (args, char *);
269 vfprintf_unfiltered (gdb_stderr, string, args);
270 fprintf_unfiltered (gdb_stderr, "\n");
274 /* Start the printing of an error message. Way to use this is to call
275 this, output the error message (use filtered output to gdb_stderr
276 (FIXME: Some callers, like memory_error, use gdb_stdout)), ending
277 in a newline, and then call return_to_top_level (RETURN_ERROR).
278 error() provides a convenient way to do this for the special case
279 that the error message can be formatted with a single printf call,
280 but this is more general. */
284 target_terminal_ours ();
285 wrap_here (""); /* Force out any buffered output */
286 gdb_flush (gdb_stdout);
288 annotate_error_begin ();
291 fprintf_filtered (gdb_stderr, error_pre_print);
294 /* Print an error message and return to command level.
295 The first argument STRING is the error message, used as a fprintf string,
296 and the remaining args are passed as arguments to it. */
298 #ifdef ANSI_PROTOTYPES
300 error (char *string, ...)
308 #ifdef ANSI_PROTOTYPES
309 va_start (args, string);
318 #ifdef ANSI_PROTOTYPES
319 vfprintf_filtered (gdb_stderr, string, args);
324 string1 = va_arg (args, char *);
325 vfprintf_filtered (gdb_stderr, string1, args);
328 fprintf_filtered (gdb_stderr, "\n");
330 return_to_top_level (RETURN_ERROR);
335 /* Print an error message and exit reporting failure.
336 This is for a error that we cannot continue from.
337 The arguments are printed a la printf.
339 This function cannot be declared volatile (NORETURN) in an
340 ANSI environment because exit() is not declared volatile. */
344 #ifdef ANSI_PROTOTYPES
345 fatal (char *string, ...)
352 #ifdef ANSI_PROTOTYPES
353 va_start (args, string);
357 string = va_arg (args, char *);
359 fprintf_unfiltered (gdb_stderr, "\ngdb: ");
360 vfprintf_unfiltered (gdb_stderr, string, args);
361 fprintf_unfiltered (gdb_stderr, "\n");
366 /* Print an error message and exit, dumping core.
367 The arguments are printed a la printf (). */
371 #ifdef ANSI_PROTOTYPES
372 fatal_dump_core (char *string, ...)
374 fatal_dump_core (va_alist)
379 #ifdef ANSI_PROTOTYPES
380 va_start (args, string);
385 string = va_arg (args, char *);
387 /* "internal error" is always correct, since GDB should never dump
388 core, no matter what the input. */
389 fprintf_unfiltered (gdb_stderr, "\ngdb internal error: ");
390 vfprintf_unfiltered (gdb_stderr, string, args);
391 fprintf_unfiltered (gdb_stderr, "\n");
394 signal (SIGQUIT, SIG_DFL);
395 kill (getpid (), SIGQUIT);
396 /* We should never get here, but just in case... */
400 /* The strerror() function can return NULL for errno values that are
401 out of range. Provide a "safe" version that always returns a
405 safe_strerror (errnum)
411 if ((msg = strerror (errnum)) == NULL)
413 sprintf (buf, "(undocumented errno %d)", errnum);
419 /* The strsignal() function can return NULL for signal values that are
420 out of range. Provide a "safe" version that always returns a
424 safe_strsignal (signo)
430 if ((msg = strsignal (signo)) == NULL)
432 sprintf (buf, "(undocumented signal %d)", signo);
439 /* Print the system error message for errno, and also mention STRING
440 as the file name for which the error was encountered.
441 Then return to command level. */
444 perror_with_name (string)
450 err = safe_strerror (errno);
451 combined = (char *) alloca (strlen (err) + strlen (string) + 3);
452 strcpy (combined, string);
453 strcat (combined, ": ");
454 strcat (combined, err);
456 /* I understand setting these is a matter of taste. Still, some people
457 may clear errno but not know about bfd_error. Doing this here is not
459 bfd_set_error (bfd_error_no_error);
462 error ("%s.", combined);
465 /* Print the system error message for ERRCODE, and also mention STRING
466 as the file name for which the error was encountered. */
469 print_sys_errmsg (string, errcode)
476 err = safe_strerror (errcode);
477 combined = (char *) alloca (strlen (err) + strlen (string) + 3);
478 strcpy (combined, string);
479 strcat (combined, ": ");
480 strcat (combined, err);
482 /* We want anything which was printed on stdout to come out first, before
484 gdb_flush (gdb_stdout);
485 fprintf_unfiltered (gdb_stderr, "%s.\n", combined);
488 /* Control C eventually causes this to be called, at a convenient time. */
493 serial_t gdb_stdout_serial = serial_fdopen (1);
495 target_terminal_ours ();
497 /* We want all output to appear now, before we print "Quit". We
498 have 3 levels of buffering we have to flush (it's possible that
499 some of these should be changed to flush the lower-level ones
502 /* 1. The _filtered buffer. */
503 wrap_here ((char *)0);
505 /* 2. The stdio buffer. */
506 gdb_flush (gdb_stdout);
507 gdb_flush (gdb_stderr);
509 /* 3. The system-level buffer. */
510 SERIAL_FLUSH_OUTPUT (gdb_stdout_serial);
511 SERIAL_UN_FDOPEN (gdb_stdout_serial);
513 annotate_error_begin ();
515 /* Don't use *_filtered; we don't want to prompt the user to continue. */
517 fprintf_unfiltered (gdb_stderr, quit_pre_print);
520 /* If there is no terminal switching for this target, then we can't
521 possibly get screwed by the lack of job control. */
522 || current_target.to_terminal_ours == NULL)
523 fprintf_unfiltered (gdb_stderr, "Quit\n");
525 fprintf_unfiltered (gdb_stderr,
526 "Quit (expect signal SIGINT when the program is resumed)\n");
527 return_to_top_level (RETURN_QUIT);
531 #if defined(__GO32__)||defined(WINGDB)
533 /* In the absence of signals, poll keyboard for a quit.
534 Called from #define QUIT pollquit() in xm-go32.h. */
552 /* We just ignore it */
553 fprintf_unfiltered (gdb_stderr, "CTRL-A to quit, CTRL-B to quit harder\n");
560 #if defined(__GO32__)||defined(WINGDB)
575 fprintf_unfiltered (gdb_stderr, "CTRL-A to quit, CTRL-B to quit harder\n");
582 /* Done by signals */
585 /* Control C comes here */
592 /* Restore the signal handler. Harmless with BSD-style signals, needed
593 for System V-style signals. So just always do it, rather than worrying
594 about USG defines and stuff like that. */
595 signal (signo, request_quit);
597 /* start-sanitize-gm */
600 #endif /* GENERAL_MAGIC */
601 /* end-sanitize-gm */
612 /* Memory management stuff (malloc friends). */
614 #if defined (NO_MMALLOC)
616 /* Make a substitute size_t for non-ANSI compilers. */
623 #define size_t unsigned int
633 return malloc (size);
637 mrealloc (md, ptr, size)
642 if (ptr == 0) /* Guard against old realloc's */
643 return malloc (size);
645 return realloc (ptr, size);
656 #endif /* NO_MMALLOC */
658 #if defined (NO_MMALLOC) || defined (NO_MMCHECK)
666 #else /* Have mmalloc and want corruption checking */
671 fatal_dump_core ("Memory corruption");
674 /* Attempt to install hooks in mmalloc/mrealloc/mfree for the heap specified
675 by MD, to detect memory corruption. Note that MD may be NULL to specify
676 the default heap that grows via sbrk.
678 Note that for freshly created regions, we must call mmcheckf prior to any
679 mallocs in the region. Otherwise, any region which was allocated prior to
680 installing the checking hooks, which is later reallocated or freed, will
681 fail the checks! The mmcheck function only allows initial hooks to be
682 installed before the first mmalloc. However, anytime after we have called
683 mmcheck the first time to install the checking hooks, we can call it again
684 to update the function pointer to the memory corruption handler.
686 Returns zero on failure, non-zero on success. */
688 #ifndef MMCHECK_FORCE
689 #define MMCHECK_FORCE 0
696 if (!mmcheckf (md, malloc_botch, MMCHECK_FORCE))
698 /* Don't use warning(), which relies on current_target being set
699 to something other than dummy_target, until after
700 initialize_all_files(). */
703 (gdb_stderr, "warning: failed to install memory consistency checks; ");
705 (gdb_stderr, "configuration should define NO_MMCHECK or MMCHECK_FORCE\n");
711 #endif /* Have mmalloc and want corruption checking */
713 /* Called when a memory allocation fails, with the number of bytes of
714 memory requested in SIZE. */
722 fatal ("virtual memory exhausted: can't allocate %ld bytes.", size);
726 fatal ("virtual memory exhausted.");
730 /* Like mmalloc but get error if no storage available, and protect against
731 the caller wanting to allocate zero bytes. Whether to return NULL for
732 a zero byte request, or translate the request into a request for one
733 byte of zero'd storage, is a religious issue. */
746 else if ((val = mmalloc (md, size)) == NULL)
753 /* Like mrealloc but get error if no storage available. */
756 xmrealloc (md, ptr, size)
765 val = mrealloc (md, ptr, size);
769 val = mmalloc (md, size);
778 /* Like malloc but get error if no storage available, and protect against
779 the caller wanting to allocate zero bytes. */
785 return (xmmalloc ((PTR) NULL, size));
788 /* Like mrealloc but get error if no storage available. */
795 return (xmrealloc ((PTR) NULL, ptr, size));
799 /* My replacement for the read system call.
800 Used like `read' but keeps going if `read' returns too soon. */
803 myread (desc, addr, len)
813 val = read (desc, addr, len);
824 /* Make a copy of the string at PTR with SIZE characters
825 (and add a null character at the end in the copy).
826 Uses malloc to get the space. Returns the address of the copy. */
829 savestring (ptr, size)
833 register char *p = (char *) xmalloc (size + 1);
834 memcpy (p, ptr, size);
840 msavestring (md, ptr, size)
845 register char *p = (char *) xmmalloc (md, size + 1);
846 memcpy (p, ptr, size);
851 /* The "const" is so it compiles under DGUX (which prototypes strsave
852 in <string.h>. FIXME: This should be named "xstrsave", shouldn't it?
853 Doesn't real strsave return NULL if out of memory? */
858 return savestring (ptr, strlen (ptr));
866 return (msavestring (md, ptr, strlen (ptr)));
870 print_spaces (n, file)
878 /* Print a host address. */
881 gdb_print_address (addr, stream)
886 /* We could use the %p conversion specifier to fprintf if we had any
887 way of knowing whether this host supports it. But the following
888 should work on the Alpha and on 32 bit machines. */
890 fprintf_filtered (stream, "0x%lx", (unsigned long)addr);
893 /* Ask user a y-or-n question and return 1 iff answer is yes.
894 Takes three args which are given to printf to print the question.
895 The first, a control string, should end in "? ".
896 It should not say how to answer, because we do that. */
900 #ifdef ANSI_PROTOTYPES
901 query (char *ctlstr, ...)
912 #ifdef ANSI_PROTOTYPES
913 va_start (args, ctlstr);
917 ctlstr = va_arg (args, char *);
922 return query_hook (ctlstr, args);
925 /* Automatically answer "yes" if input is not from a terminal. */
926 if (!input_from_terminal_p ())
929 /* FIXME Automatically answer "yes" if called from MacGDB. */
936 wrap_here (""); /* Flush any buffered output */
937 gdb_flush (gdb_stdout);
939 if (annotation_level > 1)
940 printf_filtered ("\n\032\032pre-query\n");
942 vfprintf_filtered (gdb_stdout, ctlstr, args);
943 printf_filtered ("(y or n) ");
945 if (annotation_level > 1)
946 printf_filtered ("\n\032\032query\n");
949 /* If not in MacGDB, move to a new line so the entered line doesn't
950 have a prompt on the front of it. */
952 fputs_unfiltered ("\n", gdb_stdout);
955 gdb_flush (gdb_stdout);
956 answer = fgetc (stdin);
957 clearerr (stdin); /* in case of C-d */
958 if (answer == EOF) /* C-d */
963 if (answer != '\n') /* Eat rest of input line, to EOF or newline */
966 ans2 = fgetc (stdin);
969 while (ans2 != EOF && ans2 != '\n');
982 printf_filtered ("Please answer y or n.\n");
985 if (annotation_level > 1)
986 printf_filtered ("\n\032\032post-query\n");
991 /* Parse a C escape sequence. STRING_PTR points to a variable
992 containing a pointer to the string to parse. That pointer
993 should point to the character after the \. That pointer
994 is updated past the characters we use. The value of the
995 escape sequence is returned.
997 A negative value means the sequence \ newline was seen,
998 which is supposed to be equivalent to nothing at all.
1000 If \ is followed by a null character, we return a negative
1001 value and leave the string pointer pointing at the null character.
1003 If \ is followed by 000, we return 0 and leave the string pointer
1004 after the zeros. A value of 0 does not mean end of string. */
1007 parse_escape (string_ptr)
1010 register int c = *(*string_ptr)++;
1014 return 007; /* Bell (alert) char */
1017 case 'e': /* Escape character */
1035 c = *(*string_ptr)++;
1037 c = parse_escape (string_ptr);
1040 return (c & 0200) | (c & 037);
1051 register int i = c - '0';
1052 register int count = 0;
1055 if ((c = *(*string_ptr)++) >= '0' && c <= '7')
1073 /* Print the character C on STREAM as part of the contents of a literal
1074 string whose delimiter is QUOTER. Note that this routine should only
1075 be call for printing things which are independent of the language
1076 of the program being debugged. */
1079 gdb_printchar (c, stream, quoter)
1085 c &= 0xFF; /* Avoid sign bit follies */
1087 if ( c < 0x20 || /* Low control chars */
1088 (c >= 0x7F && c < 0xA0) || /* DEL, High controls */
1089 (sevenbit_strings && c >= 0x80)) { /* high order bit set */
1093 fputs_filtered ("\\n", stream);
1096 fputs_filtered ("\\b", stream);
1099 fputs_filtered ("\\t", stream);
1102 fputs_filtered ("\\f", stream);
1105 fputs_filtered ("\\r", stream);
1108 fputs_filtered ("\\e", stream);
1111 fputs_filtered ("\\a", stream);
1114 fprintf_filtered (stream, "\\%.3o", (unsigned int) c);
1118 if (c == '\\' || c == quoter)
1119 fputs_filtered ("\\", stream);
1120 fprintf_filtered (stream, "%c", c);
1124 /* Number of lines per page or UINT_MAX if paging is disabled. */
1125 static unsigned int lines_per_page;
1126 /* Number of chars per line or UNIT_MAX is line folding is disabled. */
1127 static unsigned int chars_per_line;
1128 /* Current count of lines printed on this page, chars on this line. */
1129 static unsigned int lines_printed, chars_printed;
1131 /* Buffer and start column of buffered text, for doing smarter word-
1132 wrapping. When someone calls wrap_here(), we start buffering output
1133 that comes through fputs_filtered(). If we see a newline, we just
1134 spit it out and forget about the wrap_here(). If we see another
1135 wrap_here(), we spit it out and remember the newer one. If we see
1136 the end of the line, we spit out a newline, the indent, and then
1137 the buffered output. */
1139 /* Malloc'd buffer with chars_per_line+2 bytes. Contains characters which
1140 are waiting to be output (they have already been counted in chars_printed).
1141 When wrap_buffer[0] is null, the buffer is empty. */
1142 static char *wrap_buffer;
1144 /* Pointer in wrap_buffer to the next character to fill. */
1145 static char *wrap_pointer;
1147 /* String to indent by if the wrap occurs. Must not be NULL if wrap_column
1149 static char *wrap_indent;
1151 /* Column number on the screen where wrap_buffer begins, or 0 if wrapping
1152 is not in effect. */
1153 static int wrap_column;
1157 set_width_command (args, from_tty, c)
1160 struct cmd_list_element *c;
1164 wrap_buffer = (char *) xmalloc (chars_per_line + 2);
1165 wrap_buffer[0] = '\0';
1168 wrap_buffer = (char *) xrealloc (wrap_buffer, chars_per_line + 2);
1169 wrap_pointer = wrap_buffer; /* Start it at the beginning */
1172 /* Wait, so the user can read what's on the screen. Prompt the user
1173 to continue by pressing RETURN. */
1176 prompt_for_continue ()
1179 char cont_prompt[120];
1181 if (annotation_level > 1)
1182 printf_unfiltered ("\n\032\032pre-prompt-for-continue\n");
1184 strcpy (cont_prompt,
1185 "---Type <return> to continue, or q <return> to quit---");
1186 if (annotation_level > 1)
1187 strcat (cont_prompt, "\n\032\032prompt-for-continue\n");
1189 /* We must do this *before* we call gdb_readline, else it will eventually
1190 call us -- thinking that we're trying to print beyond the end of the
1192 reinitialize_more_filter ();
1195 /* On a real operating system, the user can quit with SIGINT.
1198 'q' is provided on all systems so users don't have to change habits
1199 from system to system, and because telling them what to do in
1200 the prompt is more user-friendly than expecting them to think of
1202 /* Call readline, not gdb_readline, because GO32 readline handles control-C
1203 whereas control-C to gdb_readline will cause the user to get dumped
1205 ignore = readline (cont_prompt);
1207 if (annotation_level > 1)
1208 printf_unfiltered ("\n\032\032post-prompt-for-continue\n");
1213 while (*p == ' ' || *p == '\t')
1216 request_quit (SIGINT);
1221 /* Now we have to do this again, so that GDB will know that it doesn't
1222 need to save the ---Type <return>--- line at the top of the screen. */
1223 reinitialize_more_filter ();
1225 dont_repeat (); /* Forget prev cmd -- CR won't repeat it. */
1228 /* Reinitialize filter; ie. tell it to reset to original values. */
1231 reinitialize_more_filter ()
1237 /* Indicate that if the next sequence of characters overflows the line,
1238 a newline should be inserted here rather than when it hits the end.
1239 If INDENT is non-null, it is a string to be printed to indent the
1240 wrapped part on the next line. INDENT must remain accessible until
1241 the next call to wrap_here() or until a newline is printed through
1244 If the line is already overfull, we immediately print a newline and
1245 the indentation, and disable further wrapping.
1247 If we don't know the width of lines, but we know the page height,
1248 we must not wrap words, but should still keep track of newlines
1249 that were explicitly printed.
1251 INDENT should not contain tabs, as that will mess up the char count
1252 on the next line. FIXME.
1254 This routine is guaranteed to force out any output which has been
1255 squirreled away in the wrap_buffer, so wrap_here ((char *)0) can be
1256 used to force out output from the wrap_buffer. */
1262 /* This should have been allocated, but be paranoid anyway. */
1268 *wrap_pointer = '\0';
1269 fputs_unfiltered (wrap_buffer, gdb_stdout);
1271 wrap_pointer = wrap_buffer;
1272 wrap_buffer[0] = '\0';
1273 if (chars_per_line == UINT_MAX) /* No line overflow checking */
1277 else if (chars_printed >= chars_per_line)
1279 puts_filtered ("\n");
1281 puts_filtered (indent);
1286 wrap_column = chars_printed;
1290 wrap_indent = indent;
1294 /* Ensure that whatever gets printed next, using the filtered output
1295 commands, starts at the beginning of the line. I.E. if there is
1296 any pending output for the current line, flush it and start a new
1297 line. Otherwise do nothing. */
1302 if (chars_printed > 0)
1304 puts_filtered ("\n");
1310 gdb_fopen (name, mode)
1314 return fopen (name, mode);
1323 flush_hook (stream);
1330 /* Like fputs but if FILTER is true, pause after every screenful.
1332 Regardless of FILTER can wrap at points other than the final
1333 character of a line.
1335 Unlike fputs, fputs_maybe_filtered does not return a value.
1336 It is OK for LINEBUFFER to be NULL, in which case just don't print
1339 Note that a longjmp to top level may occur in this routine (only if
1340 FILTER is true) (since prompt_for_continue may do so) so this
1341 routine should not be called when cleanups are not in place. */
1344 fputs_maybe_filtered (linebuffer, stream, filter)
1345 const char *linebuffer;
1349 const char *lineptr;
1351 if (linebuffer == 0)
1354 /* Don't do any filtering if it is disabled. */
1355 if (stream != gdb_stdout
1356 || (lines_per_page == UINT_MAX && chars_per_line == UINT_MAX))
1358 fputs_unfiltered (linebuffer, stream);
1362 /* Go through and output each character. Show line extension
1363 when this is necessary; prompt user for new page when this is
1366 lineptr = linebuffer;
1369 /* Possible new page. */
1371 (lines_printed >= lines_per_page - 1))
1372 prompt_for_continue ();
1374 while (*lineptr && *lineptr != '\n')
1376 /* Print a single line. */
1377 if (*lineptr == '\t')
1380 *wrap_pointer++ = '\t';
1382 fputc_unfiltered ('\t', stream);
1383 /* Shifting right by 3 produces the number of tab stops
1384 we have already passed, and then adding one and
1385 shifting left 3 advances to the next tab stop. */
1386 chars_printed = ((chars_printed >> 3) + 1) << 3;
1392 *wrap_pointer++ = *lineptr;
1394 fputc_unfiltered (*lineptr, stream);
1399 if (chars_printed >= chars_per_line)
1401 unsigned int save_chars = chars_printed;
1405 /* If we aren't actually wrapping, don't output newline --
1406 if chars_per_line is right, we probably just overflowed
1407 anyway; if it's wrong, let us keep going. */
1409 fputc_unfiltered ('\n', stream);
1411 /* Possible new page. */
1412 if (lines_printed >= lines_per_page - 1)
1413 prompt_for_continue ();
1415 /* Now output indentation and wrapped string */
1418 fputs_unfiltered (wrap_indent, stream);
1419 *wrap_pointer = '\0'; /* Null-terminate saved stuff */
1420 fputs_unfiltered (wrap_buffer, stream); /* and eject it */
1421 /* FIXME, this strlen is what prevents wrap_indent from
1422 containing tabs. However, if we recurse to print it
1423 and count its chars, we risk trouble if wrap_indent is
1424 longer than (the user settable) chars_per_line.
1425 Note also that this can set chars_printed > chars_per_line
1426 if we are printing a long string. */
1427 chars_printed = strlen (wrap_indent)
1428 + (save_chars - wrap_column);
1429 wrap_pointer = wrap_buffer; /* Reset buffer */
1430 wrap_buffer[0] = '\0';
1431 wrap_column = 0; /* And disable fancy wrap */
1436 if (*lineptr == '\n')
1439 wrap_here ((char *)0); /* Spit out chars, cancel further wraps */
1441 fputc_unfiltered ('\n', stream);
1448 fputs_filtered (linebuffer, stream)
1449 const char *linebuffer;
1452 fputs_maybe_filtered (linebuffer, stream, 1);
1456 putchar_unfiltered (c)
1463 fputs_unfiltered (buf, gdb_stdout);
1468 fputc_unfiltered (c, stream)
1476 fputs_unfiltered (buf, stream);
1481 /* Print a variable number of ARGS using format FORMAT. If this
1482 information is going to put the amount written (since the last call
1483 to REINITIALIZE_MORE_FILTER or the last page break) over the page size,
1484 call prompt_for_continue to get the users permision to continue.
1486 Unlike fprintf, this function does not return a value.
1488 We implement three variants, vfprintf (takes a vararg list and stream),
1489 fprintf (takes a stream to write on), and printf (the usual).
1491 Note also that a longjmp to top level may occur in this routine
1492 (since prompt_for_continue may do so) so this routine should not be
1493 called when cleanups are not in place. */
1496 vfprintf_maybe_filtered (stream, format, args, filter)
1503 struct cleanup *old_cleanups;
1505 vasprintf (&linebuffer, format, args);
1506 if (linebuffer == NULL)
1508 fputs_unfiltered ("\ngdb: virtual memory exhausted.\n", gdb_stderr);
1511 old_cleanups = make_cleanup (free, linebuffer);
1512 fputs_maybe_filtered (linebuffer, stream, filter);
1513 do_cleanups (old_cleanups);
1518 vfprintf_filtered (stream, format, args)
1523 vfprintf_maybe_filtered (stream, format, args, 1);
1527 vfprintf_unfiltered (stream, format, args)
1533 struct cleanup *old_cleanups;
1535 vasprintf (&linebuffer, format, args);
1536 if (linebuffer == NULL)
1538 fputs_unfiltered ("\ngdb: virtual memory exhausted.\n", gdb_stderr);
1541 old_cleanups = make_cleanup (free, linebuffer);
1542 fputs_unfiltered (linebuffer, stream);
1543 do_cleanups (old_cleanups);
1547 vprintf_filtered (format, args)
1551 vfprintf_maybe_filtered (gdb_stdout, format, args, 1);
1555 vprintf_unfiltered (format, args)
1559 vfprintf_unfiltered (gdb_stdout, format, args);
1564 #ifdef ANSI_PROTOTYPES
1565 fprintf_filtered (FILE *stream, const char *format, ...)
1567 fprintf_filtered (va_alist)
1572 #ifdef ANSI_PROTOTYPES
1573 va_start (args, format);
1579 stream = va_arg (args, FILE *);
1580 format = va_arg (args, char *);
1582 vfprintf_filtered (stream, format, args);
1588 #ifdef ANSI_PROTOTYPES
1589 fprintf_unfiltered (FILE *stream, const char *format, ...)
1591 fprintf_unfiltered (va_alist)
1596 #ifdef ANSI_PROTOTYPES
1597 va_start (args, format);
1603 stream = va_arg (args, FILE *);
1604 format = va_arg (args, char *);
1606 vfprintf_unfiltered (stream, format, args);
1610 /* Like fprintf_filtered, but prints its result indented.
1611 Called as fprintfi_filtered (spaces, stream, format, ...); */
1615 #ifdef ANSI_PROTOTYPES
1616 fprintfi_filtered (int spaces, FILE *stream, const char *format, ...)
1618 fprintfi_filtered (va_alist)
1623 #ifdef ANSI_PROTOTYPES
1624 va_start (args, format);
1631 spaces = va_arg (args, int);
1632 stream = va_arg (args, FILE *);
1633 format = va_arg (args, char *);
1635 print_spaces_filtered (spaces, stream);
1637 vfprintf_filtered (stream, format, args);
1644 #ifdef ANSI_PROTOTYPES
1645 printf_filtered (const char *format, ...)
1647 printf_filtered (va_alist)
1652 #ifdef ANSI_PROTOTYPES
1653 va_start (args, format);
1658 format = va_arg (args, char *);
1660 vfprintf_filtered (gdb_stdout, format, args);
1667 #ifdef ANSI_PROTOTYPES
1668 printf_unfiltered (const char *format, ...)
1670 printf_unfiltered (va_alist)
1675 #ifdef ANSI_PROTOTYPES
1676 va_start (args, format);
1681 format = va_arg (args, char *);
1683 vfprintf_unfiltered (gdb_stdout, format, args);
1687 /* Like printf_filtered, but prints it's result indented.
1688 Called as printfi_filtered (spaces, format, ...); */
1692 #ifdef ANSI_PROTOTYPES
1693 printfi_filtered (int spaces, const char *format, ...)
1695 printfi_filtered (va_alist)
1700 #ifdef ANSI_PROTOTYPES
1701 va_start (args, format);
1707 spaces = va_arg (args, int);
1708 format = va_arg (args, char *);
1710 print_spaces_filtered (spaces, gdb_stdout);
1711 vfprintf_filtered (gdb_stdout, format, args);
1715 /* Easy -- but watch out!
1717 This routine is *not* a replacement for puts()! puts() appends a newline.
1718 This one doesn't, and had better not! */
1721 puts_filtered (string)
1724 fputs_filtered (string, gdb_stdout);
1728 puts_unfiltered (string)
1731 fputs_unfiltered (string, gdb_stdout);
1734 /* Return a pointer to N spaces and a null. The pointer is good
1735 until the next call to here. */
1741 static char *spaces;
1742 static int max_spaces;
1748 spaces = (char *) xmalloc (n+1);
1749 for (t = spaces+n; t != spaces;)
1755 return spaces + max_spaces - n;
1758 /* Print N spaces. */
1760 print_spaces_filtered (n, stream)
1764 fputs_filtered (n_spaces (n), stream);
1767 /* C++ demangler stuff. */
1769 /* fprintf_symbol_filtered attempts to demangle NAME, a symbol in language
1770 LANG, using demangling args ARG_MODE, and print it filtered to STREAM.
1771 If the name is not mangled, or the language for the name is unknown, or
1772 demangling is off, the name is printed in its "raw" form. */
1775 fprintf_symbol_filtered (stream, name, lang, arg_mode)
1785 /* If user wants to see raw output, no problem. */
1788 fputs_filtered (name, stream);
1794 case language_cplus:
1795 demangled = cplus_demangle (name, arg_mode);
1797 case language_chill:
1798 demangled = chill_demangle (name);
1804 fputs_filtered (demangled ? demangled : name, stream);
1805 if (demangled != NULL)
1813 /* Do a strcmp() type operation on STRING1 and STRING2, ignoring any
1814 differences in whitespace. Returns 0 if they match, non-zero if they
1815 don't (slightly different than strcmp()'s range of return values).
1817 As an extra hack, string1=="FOO(ARGS)" matches string2=="FOO".
1818 This "feature" is useful when searching for matching C++ function names
1819 (such as if the user types 'break FOO', where FOO is a mangled C++
1823 strcmp_iw (string1, string2)
1824 const char *string1;
1825 const char *string2;
1827 while ((*string1 != '\0') && (*string2 != '\0'))
1829 while (isspace (*string1))
1833 while (isspace (*string2))
1837 if (*string1 != *string2)
1841 if (*string1 != '\0')
1847 return (*string1 != '\0' && *string1 != '(') || (*string2 != '\0');
1854 struct cmd_list_element *c;
1856 c = add_set_cmd ("width", class_support, var_uinteger,
1857 (char *)&chars_per_line,
1858 "Set number of characters gdb thinks are in a line.",
1860 add_show_from_set (c, &showlist);
1861 c->function.sfunc = set_width_command;
1864 (add_set_cmd ("height", class_support,
1865 var_uinteger, (char *)&lines_per_page,
1866 "Set number of lines gdb thinks are in a page.", &setlist),
1869 /* These defaults will be used if we are unable to get the correct
1870 values from termcap. */
1871 #if defined(__GO32__) || defined(__WIN32__)
1872 lines_per_page = ScreenRows();
1873 chars_per_line = ScreenCols();
1875 lines_per_page = 24;
1876 chars_per_line = 80;
1879 /* No termcap under MPW, although might be cool to do something
1880 by looking at worksheet or console window sizes. */
1881 /* Initialize the screen height and width from termcap. */
1883 char *termtype = getenv ("TERM");
1885 /* Positive means success, nonpositive means failure. */
1888 /* 2048 is large enough for all known terminals, according to the
1889 GNU termcap manual. */
1890 char term_buffer[2048];
1894 status = tgetent (term_buffer, termtype);
1899 val = tgetnum ("li");
1901 lines_per_page = val;
1903 /* The number of lines per page is not mentioned
1904 in the terminal description. This probably means
1905 that paging is not useful (e.g. emacs shell window),
1906 so disable paging. */
1907 lines_per_page = UINT_MAX;
1909 val = tgetnum ("co");
1911 chars_per_line = val;
1917 #if defined(SIGWINCH) && defined(SIGWINCH_HANDLER)
1919 /* If there is a better way to determine the window size, use it. */
1920 SIGWINCH_HANDLER ();
1923 /* If the output is not a terminal, don't paginate it. */
1924 if (!ISATTY (gdb_stdout))
1925 lines_per_page = UINT_MAX;
1927 set_width_command ((char *)NULL, 0, c);
1930 (add_set_cmd ("demangle", class_support, var_boolean,
1932 "Set demangling of encoded C++ names when displaying symbols.",
1937 (add_set_cmd ("sevenbit-strings", class_support, var_boolean,
1938 (char *)&sevenbit_strings,
1939 "Set printing of 8-bit characters in strings as \\nnn.",
1944 (add_set_cmd ("asm-demangle", class_support, var_boolean,
1945 (char *)&asm_demangle,
1946 "Set demangling of C++ names in disassembly listings.",
1951 /* Machine specific function to handle SIGWINCH signal. */
1953 #ifdef SIGWINCH_HANDLER_BODY
1954 SIGWINCH_HANDLER_BODY
1957 /* Support for converting target fp numbers into host DOUBLEST format. */
1959 /* XXX - This code should really be in libiberty/floatformat.c, however
1960 configuration issues with libiberty made this very difficult to do in the
1963 #include "floatformat.h"
1964 #include <math.h> /* ldexp */
1966 /* The odds that CHAR_BIT will be anything but 8 are low enough that I'm not
1967 going to bother with trying to muck around with whether it is defined in
1968 a system header, what we do if not, etc. */
1969 #define FLOATFORMAT_CHAR_BIT 8
1971 static unsigned long get_field PARAMS ((unsigned char *,
1972 enum floatformat_byteorders,
1977 /* Extract a field which starts at START and is LEN bytes long. DATA and
1978 TOTAL_LEN are the thing we are extracting it from, in byteorder ORDER. */
1979 static unsigned long
1980 get_field (data, order, total_len, start, len)
1981 unsigned char *data;
1982 enum floatformat_byteorders order;
1983 unsigned int total_len;
1987 unsigned long result;
1988 unsigned int cur_byte;
1991 /* Start at the least significant part of the field. */
1992 cur_byte = (start + len) / FLOATFORMAT_CHAR_BIT;
1993 if (order == floatformat_little)
1994 cur_byte = (total_len / FLOATFORMAT_CHAR_BIT) - cur_byte - 1;
1996 ((start + len) % FLOATFORMAT_CHAR_BIT) - FLOATFORMAT_CHAR_BIT;
1997 result = *(data + cur_byte) >> (-cur_bitshift);
1998 cur_bitshift += FLOATFORMAT_CHAR_BIT;
1999 if (order == floatformat_little)
2004 /* Move towards the most significant part of the field. */
2005 while (cur_bitshift < len)
2007 if (len - cur_bitshift < FLOATFORMAT_CHAR_BIT)
2008 /* This is the last byte; zero out the bits which are not part of
2011 (*(data + cur_byte) & ((1 << (len - cur_bitshift)) - 1))
2014 result |= *(data + cur_byte) << cur_bitshift;
2015 cur_bitshift += FLOATFORMAT_CHAR_BIT;
2016 if (order == floatformat_little)
2024 /* Convert from FMT to a DOUBLEST.
2025 FROM is the address of the extended float.
2026 Store the DOUBLEST in *TO. */
2029 floatformat_to_doublest (fmt, from, to)
2030 const struct floatformat *fmt;
2034 unsigned char *ufrom = (unsigned char *)from;
2038 unsigned int mant_bits, mant_off;
2040 int special_exponent; /* It's a NaN, denorm or zero */
2042 exponent = get_field (ufrom, fmt->byteorder, fmt->totalsize,
2043 fmt->exp_start, fmt->exp_len);
2044 /* Note that if exponent indicates a NaN, we can't really do anything useful
2045 (not knowing if the host has NaN's, or how to build one). So it will
2046 end up as an infinity or something close; that is OK. */
2048 mant_bits_left = fmt->man_len;
2049 mant_off = fmt->man_start;
2052 special_exponent = exponent == 0 || exponent == fmt->exp_nan;
2054 /* Don't bias zero's, denorms or NaNs. */
2055 if (!special_exponent)
2056 exponent -= fmt->exp_bias;
2058 /* Build the result algebraically. Might go infinite, underflow, etc;
2061 /* If this format uses a hidden bit, explicitly add it in now. Otherwise,
2062 increment the exponent by one to account for the integer bit. */
2064 if (!special_exponent)
2065 if (fmt->intbit == floatformat_intbit_no)
2066 dto = ldexp (1.0, exponent);
2070 while (mant_bits_left > 0)
2072 mant_bits = min (mant_bits_left, 32);
2074 mant = get_field (ufrom, fmt->byteorder, fmt->totalsize,
2075 mant_off, mant_bits);
2077 dto += ldexp ((double)mant, exponent - mant_bits);
2078 exponent -= mant_bits;
2079 mant_off += mant_bits;
2080 mant_bits_left -= mant_bits;
2083 /* Negate it if negative. */
2084 if (get_field (ufrom, fmt->byteorder, fmt->totalsize, fmt->sign_start, 1))
2089 static void put_field PARAMS ((unsigned char *, enum floatformat_byteorders,
2095 /* Set a field which starts at START and is LEN bytes long. DATA and
2096 TOTAL_LEN are the thing we are extracting it from, in byteorder ORDER. */
2098 put_field (data, order, total_len, start, len, stuff_to_put)
2099 unsigned char *data;
2100 enum floatformat_byteorders order;
2101 unsigned int total_len;
2104 unsigned long stuff_to_put;
2106 unsigned int cur_byte;
2109 /* Start at the least significant part of the field. */
2110 cur_byte = (start + len) / FLOATFORMAT_CHAR_BIT;
2111 if (order == floatformat_little)
2112 cur_byte = (total_len / FLOATFORMAT_CHAR_BIT) - cur_byte - 1;
2114 ((start + len) % FLOATFORMAT_CHAR_BIT) - FLOATFORMAT_CHAR_BIT;
2115 *(data + cur_byte) &=
2116 ~(((1 << ((start + len) % FLOATFORMAT_CHAR_BIT)) - 1) << (-cur_bitshift));
2117 *(data + cur_byte) |=
2118 (stuff_to_put & ((1 << FLOATFORMAT_CHAR_BIT) - 1)) << (-cur_bitshift);
2119 cur_bitshift += FLOATFORMAT_CHAR_BIT;
2120 if (order == floatformat_little)
2125 /* Move towards the most significant part of the field. */
2126 while (cur_bitshift < len)
2128 if (len - cur_bitshift < FLOATFORMAT_CHAR_BIT)
2130 /* This is the last byte. */
2131 *(data + cur_byte) &=
2132 ~((1 << (len - cur_bitshift)) - 1);
2133 *(data + cur_byte) |= (stuff_to_put >> cur_bitshift);
2136 *(data + cur_byte) = ((stuff_to_put >> cur_bitshift)
2137 & ((1 << FLOATFORMAT_CHAR_BIT) - 1));
2138 cur_bitshift += FLOATFORMAT_CHAR_BIT;
2139 if (order == floatformat_little)
2146 #ifdef HAVE_LONG_DOUBLE
2147 /* Return the fractional part of VALUE, and put the exponent of VALUE in *EPTR.
2148 The range of the returned value is >= 0.5 and < 1.0. This is equivalent to
2149 frexp, but operates on the long double data type. */
2151 static long double ldfrexp PARAMS ((long double value, int *eptr));
2154 ldfrexp (value, eptr)
2161 /* Unfortunately, there are no portable functions for extracting the exponent
2162 of a long double, so we have to do it iteratively by multiplying or dividing
2163 by two until the fraction is between 0.5 and 1.0. */
2171 if (value >= tmp) /* Value >= 1.0 */
2172 while (value >= tmp)
2177 else if (value != 0.0l) /* Value < 1.0 and > 0.0 */
2191 #endif /* HAVE_LONG_DOUBLE */
2194 /* The converse: convert the DOUBLEST *FROM to an extended float
2195 and store where TO points. Neither FROM nor TO have any alignment
2199 floatformat_from_doublest (fmt, from, to)
2200 CONST struct floatformat *fmt;
2207 unsigned int mant_bits, mant_off;
2209 unsigned char *uto = (unsigned char *)to;
2211 memcpy (&dfrom, from, sizeof (dfrom));
2212 memset (uto, 0, fmt->totalsize / FLOATFORMAT_CHAR_BIT);
2214 return; /* Result is zero */
2218 put_field (uto, fmt->byteorder, fmt->totalsize, fmt->exp_start,
2219 fmt->exp_len, fmt->exp_nan);
2220 /* Be sure it's not infinity, but NaN value is irrel */
2221 put_field (uto, fmt->byteorder, fmt->totalsize, fmt->man_start,
2226 /* If negative, set the sign bit. */
2229 put_field (uto, fmt->byteorder, fmt->totalsize, fmt->sign_start, 1, 1);
2233 /* How to tell an infinity from an ordinary number? FIXME-someday */
2235 #ifdef HAVE_LONG_DOUBLE
2236 mant = ldfrexp (dfrom, &exponent);
2238 mant = frexp (dfrom, &exponent);
2241 put_field (uto, fmt->byteorder, fmt->totalsize, fmt->exp_start, fmt->exp_len,
2242 exponent + fmt->exp_bias - 1);
2244 mant_bits_left = fmt->man_len;
2245 mant_off = fmt->man_start;
2246 while (mant_bits_left > 0)
2248 unsigned long mant_long;
2249 mant_bits = mant_bits_left < 32 ? mant_bits_left : 32;
2251 mant *= 4294967296.0;
2252 mant_long = (unsigned long)mant;
2255 /* If the integer bit is implicit, then we need to discard it.
2256 If we are discarding a zero, we should be (but are not) creating
2257 a denormalized number which means adjusting the exponent
2259 if (mant_bits_left == fmt->man_len
2260 && fmt->intbit == floatformat_intbit_no)
2262 mant_long &= 0x7fffffff;
2265 else if (mant_bits < 32)
2267 /* The bits we want are in the most significant MANT_BITS bits of
2268 mant_long. Move them to the least significant. */
2269 mant_long >>= 32 - mant_bits;
2272 put_field (uto, fmt->byteorder, fmt->totalsize,
2273 mant_off, mant_bits, mant_long);
2274 mant_off += mant_bits;
2275 mant_bits_left -= mant_bits;