1 /* General utility routines for GDB, the GNU debugger.
2 Copyright 1986, 1989, 1990, 1991, 1992 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., 675 Mass Ave, Cambridge, MA 02139, USA. */
21 #include <sys/ioctl.h>
22 #include <sys/param.h>
35 /* Prototypes for local functions */
37 #if !defined (NO_MALLOC_CHECK)
39 malloc_botch PARAMS ((void));
40 #endif /* NO_MALLOC_CHECK */
43 fatal_dump_core (); /* Can't prototype with <varargs.h> usage... */
46 prompt_for_continue PARAMS ((void));
49 set_width_command PARAMS ((char *, int, struct cmd_list_element *));
52 vfprintf_filtered PARAMS ((FILE *, char *, va_list));
54 /* If this definition isn't overridden by the header files, assume
55 that isatty and fileno exist on this system. */
57 #define ISATTY(FP) (isatty (fileno (FP)))
60 /* Chain of cleanup actions established with make_cleanup,
61 to be executed if an error happens. */
63 static struct cleanup *cleanup_chain;
65 /* Nonzero means a quit has been requested. */
69 /* Nonzero means quit immediately if Control-C is typed now,
70 rather than waiting until QUIT is executed. */
74 /* Nonzero means that encoded C++ names should be printed out in their
75 C++ form rather than raw. */
79 /* Nonzero means that encoded C++ names should be printed out in their
80 C++ form even in assembler language displays. If this is set, but
81 DEMANGLE is zero, names are printed raw, i.e. DEMANGLE controls. */
85 /* Nonzero means that strings with character values >0x7F should be printed
86 as octal escapes. Zero means just print the value (e.g. it's an
87 international character, and the terminal or window can cope.) */
89 int sevenbit_strings = 0;
91 /* String to be printed before error messages, if any. */
93 char *error_pre_print;
94 char *warning_pre_print;
96 /* Add a new cleanup to the cleanup_chain,
97 and return the previous chain pointer
98 to be passed later to do_cleanups or discard_cleanups.
99 Args are FUNCTION to clean up with, and ARG to pass to it. */
102 make_cleanup (function, arg)
103 void (*function) PARAMS ((PTR));
106 register struct cleanup *new
107 = (struct cleanup *) xmalloc (sizeof (struct cleanup));
108 register struct cleanup *old_chain = cleanup_chain;
110 new->next = cleanup_chain;
111 new->function = function;
118 /* Discard cleanups and do the actions they describe
119 until we get back to the point OLD_CHAIN in the cleanup_chain. */
122 do_cleanups (old_chain)
123 register struct cleanup *old_chain;
125 register struct cleanup *ptr;
126 while ((ptr = cleanup_chain) != old_chain)
128 cleanup_chain = ptr->next; /* Do this first incase recursion */
129 (*ptr->function) (ptr->arg);
134 /* Discard cleanups, not doing the actions they describe,
135 until we get back to the point OLD_CHAIN in the cleanup_chain. */
138 discard_cleanups (old_chain)
139 register struct cleanup *old_chain;
141 register struct cleanup *ptr;
142 while ((ptr = cleanup_chain) != old_chain)
144 cleanup_chain = ptr->next;
149 /* Set the cleanup_chain to 0, and return the old cleanup chain. */
153 struct cleanup *old_chain = cleanup_chain;
159 /* Restore the cleanup chain from a previously saved chain. */
161 restore_cleanups (chain)
162 struct cleanup *chain;
164 cleanup_chain = chain;
167 /* This function is useful for cleanups.
171 old_chain = make_cleanup (free_current_contents, &foo);
173 to arrange to free the object thus allocated. */
176 free_current_contents (location)
182 /* Provide a known function that does nothing, to use as a base for
183 for a possibly long chain of cleanups. This is useful where we
184 use the cleanup chain for handling normal cleanups as well as dealing
185 with cleanups that need to be done as a result of a call to error().
186 In such cases, we may not be certain where the first cleanup is, unless
187 we have a do-nothing one to always use as the base. */
197 /* Provide a hook for modules wishing to print their own warning messages
198 to set up the terminal state in a compatible way, without them having
199 to import all the target_<...> macros. */
204 target_terminal_ours ();
205 wrap_here(""); /* Force out any buffered output */
209 /* Print a warning message.
210 The first argument STRING is the warning message, used as a fprintf string,
211 and the remaining args are passed as arguments to it.
212 The primary difference between warnings and errors is that a warning
213 does not force the return to command level. */
224 target_terminal_ours ();
225 wrap_here(""); /* Force out any buffered output */
227 if (warning_pre_print)
228 fprintf (stderr, warning_pre_print);
229 string = va_arg (args, char *);
230 vfprintf (stderr, string, args);
231 fprintf (stderr, "\n");
235 /* Print an error message and return to command level.
236 The first argument STRING is the error message, used as a fprintf string,
237 and the remaining args are passed as arguments to it. */
248 target_terminal_ours ();
249 wrap_here(""); /* Force out any buffered output */
252 fprintf (stderr, error_pre_print);
253 string = va_arg (args, char *);
254 vfprintf (stderr, string, args);
255 fprintf (stderr, "\n");
257 return_to_top_level ();
260 /* Print an error message and exit reporting failure.
261 This is for a error that we cannot continue from.
262 The arguments are printed a la printf.
264 This function cannot be declared volatile (NORETURN) in an
265 ANSI environment because exit() is not declared volatile. */
276 string = va_arg (args, char *);
277 fprintf (stderr, "gdb: ");
278 vfprintf (stderr, string, args);
279 fprintf (stderr, "\n");
284 /* Print an error message and exit, dumping core.
285 The arguments are printed a la printf (). */
289 fatal_dump_core (va_alist)
296 string = va_arg (args, char *);
297 /* "internal error" is always correct, since GDB should never dump
298 core, no matter what the input. */
299 fprintf (stderr, "gdb internal error: ");
300 vfprintf (stderr, string, args);
301 fprintf (stderr, "\n");
304 signal (SIGQUIT, SIG_DFL);
305 kill (getpid (), SIGQUIT);
306 /* We should never get here, but just in case... */
311 /* Memory management stuff (malloc friends). */
313 #if defined (NO_MALLOC_CHECK)
317 #else /* Have mcheck(). */
321 fatal_dump_core ("Memory corruption");
327 extern PTR (*__morecore) PARAMS ((long));
329 mcheck (malloc_botch);
332 #endif /* Have mcheck(). */
334 /* Like malloc but get error if no storage available. */
342 /* Protect against gdb wanting to allocate zero bytes. */
346 val = (char *) malloc (size);
348 fatal ("virtual memory exhausted.", 0);
352 /* Like realloc but get error if no storage available. */
359 register char *val = (char *) realloc (ptr, size);
361 fatal ("virtual memory exhausted.", 0);
365 /* Print the system error message for errno, and also mention STRING
366 as the file name for which the error was encountered.
367 Then return to command level. */
370 perror_with_name (string)
374 extern char *sys_errlist[];
378 if (errno < sys_nerr)
379 err = sys_errlist[errno];
381 err = "unknown error";
383 combined = (char *) alloca (strlen (err) + strlen (string) + 3);
384 strcpy (combined, string);
385 strcat (combined, ": ");
386 strcat (combined, err);
388 /* I understand setting these is a matter of taste. Still, some people
389 may clear errno but not know about bfd_error. Doing this here is not
391 bfd_error = no_error;
394 error ("%s.", combined);
397 /* Print the system error message for ERRCODE, and also mention STRING
398 as the file name for which the error was encountered. */
401 print_sys_errmsg (string, errcode)
406 extern char *sys_errlist[];
410 if (errcode < sys_nerr)
411 err = sys_errlist[errcode];
413 err = "unknown error";
415 combined = (char *) alloca (strlen (err) + strlen (string) + 3);
416 strcpy (combined, string);
417 strcat (combined, ": ");
418 strcat (combined, err);
420 printf ("%s.\n", combined);
423 /* Control C eventually causes this to be called, at a convenient time. */
428 target_terminal_ours ();
429 wrap_here ((char *)0); /* Force out any pending output */
431 ioctl (fileno (stdout), TCFLSH, 1);
432 #else /* not HAVE_TERMIO */
433 ioctl (fileno (stdout), TIOCFLUSH, 0);
434 #endif /* not HAVE_TERMIO */
438 error ("Quit (expect signal %d when inferior is resumed)", SIGINT);
439 #endif /* TIOCGPGRP */
442 /* Control C comes here */
451 /* Restore the signal handler. */
452 signal (signo, request_quit);
459 /* My replacement for the read system call.
460 Used like `read' but keeps going if `read' returns too soon. */
463 myread (desc, addr, len)
473 val = read (desc, addr, len);
484 /* Make a copy of the string at PTR with SIZE characters
485 (and add a null character at the end in the copy).
486 Uses malloc to get the space. Returns the address of the copy. */
489 savestring (ptr, size)
493 register char *p = (char *) xmalloc (size + 1);
494 bcopy (ptr, p, size);
499 /* The "const" is so it compiles under DGUX (which prototypes strsave
500 in <string.h>. FIXME: This should be named "xstrsave", shouldn't it?
501 Doesn't real strsave return NULL if out of memory? */
506 return savestring (ptr, strlen (ptr));
510 print_spaces (n, file)
518 /* Ask user a y-or-n question and return 1 iff answer is yes.
519 Takes three args which are given to printf to print the question.
520 The first, a control string, should end in "? ".
521 It should not say how to answer, because we do that. */
533 /* Automatically answer "yes" if input is not from a terminal. */
534 if (!input_from_terminal_p ())
540 ctlstr = va_arg (args, char *);
541 vfprintf (stdout, ctlstr, args);
543 printf ("(y or n) ");
545 answer = fgetc (stdin);
546 clearerr (stdin); /* in case of C-d */
547 if (answer == EOF) /* C-d */
549 if (answer != '\n') /* Eat rest of input line, to EOF or newline */
552 ans2 = fgetc (stdin);
555 while (ans2 != EOF && ans2 != '\n');
562 printf ("Please answer y or n.\n");
567 /* Parse a C escape sequence. STRING_PTR points to a variable
568 containing a pointer to the string to parse. That pointer
569 should point to the character after the \. That pointer
570 is updated past the characters we use. The value of the
571 escape sequence is returned.
573 A negative value means the sequence \ newline was seen,
574 which is supposed to be equivalent to nothing at all.
576 If \ is followed by a null character, we return a negative
577 value and leave the string pointer pointing at the null character.
579 If \ is followed by 000, we return 0 and leave the string pointer
580 after the zeros. A value of 0 does not mean end of string. */
583 parse_escape (string_ptr)
586 register int c = *(*string_ptr)++;
590 return 007; /* Bell (alert) char */
593 case 'e': /* Escape character */
611 c = *(*string_ptr)++;
613 c = parse_escape (string_ptr);
616 return (c & 0200) | (c & 037);
627 register int i = c - '0';
628 register int count = 0;
631 if ((c = *(*string_ptr)++) >= '0' && c <= '7')
649 /* Print the character C on STREAM as part of the contents
650 of a literal string whose delimiter is QUOTER. */
653 printchar (c, stream, quoter)
659 if (c < 040 || (sevenbit_strings && c >= 0177)) {
663 fputs_filtered ("\\n", stream);
666 fputs_filtered ("\\b", stream);
669 fputs_filtered ("\\t", stream);
672 fputs_filtered ("\\f", stream);
675 fputs_filtered ("\\r", stream);
678 fputs_filtered ("\\e", stream);
681 fputs_filtered ("\\a", stream);
684 fprintf_filtered (stream, "\\%.3o", (unsigned int) c);
688 if (c == '\\' || c == quoter)
689 fputs_filtered ("\\", stream);
690 fprintf_filtered (stream, "%c", c);
694 /* Number of lines per page or UINT_MAX if paging is disabled. */
695 static unsigned int lines_per_page;
696 /* Number of chars per line or UNIT_MAX is line folding is disabled. */
697 static unsigned int chars_per_line;
698 /* Current count of lines printed on this page, chars on this line. */
699 static unsigned int lines_printed, chars_printed;
701 /* Buffer and start column of buffered text, for doing smarter word-
702 wrapping. When someone calls wrap_here(), we start buffering output
703 that comes through fputs_filtered(). If we see a newline, we just
704 spit it out and forget about the wrap_here(). If we see another
705 wrap_here(), we spit it out and remember the newer one. If we see
706 the end of the line, we spit out a newline, the indent, and then
709 wrap_column is the column number on the screen where wrap_buffer begins.
710 When wrap_column is zero, wrapping is not in effect.
711 wrap_buffer is malloc'd with chars_per_line+2 bytes.
712 When wrap_buffer[0] is null, the buffer is empty.
713 wrap_pointer points into it at the next character to fill.
714 wrap_indent is the string that should be used as indentation if the
717 static char *wrap_buffer, *wrap_pointer, *wrap_indent;
718 static int wrap_column;
722 set_width_command (args, from_tty, c)
725 struct cmd_list_element *c;
729 wrap_buffer = (char *) xmalloc (chars_per_line + 2);
730 wrap_buffer[0] = '\0';
733 wrap_buffer = (char *) xrealloc (wrap_buffer, chars_per_line + 2);
734 wrap_pointer = wrap_buffer; /* Start it at the beginning */
738 prompt_for_continue ()
743 ignore = gdb_readline ("---Type <return> to continue---");
746 chars_printed = lines_printed = 0;
748 dont_repeat (); /* Forget prev cmd -- CR won't repeat it. */
751 /* Reinitialize filter; ie. tell it to reset to original values. */
754 reinitialize_more_filter ()
760 /* Indicate that if the next sequence of characters overflows the line,
761 a newline should be inserted here rather than when it hits the end.
762 If INDENT is nonzero, it is a string to be printed to indent the
763 wrapped part on the next line. INDENT must remain accessible until
764 the next call to wrap_here() or until a newline is printed through
767 If the line is already overfull, we immediately print a newline and
768 the indentation, and disable further wrapping.
770 If we don't know the width of lines, but we know the page height,
771 we must not wrap words, but should still keep track of newlines
772 that were explicitly printed.
774 INDENT should not contain tabs, as that
775 will mess up the char count on the next line. FIXME. */
783 *wrap_pointer = '\0';
784 fputs (wrap_buffer, stdout);
786 wrap_pointer = wrap_buffer;
787 wrap_buffer[0] = '\0';
788 if (chars_per_line == UINT_MAX) /* No line overflow checking */
792 else if (chars_printed >= chars_per_line)
794 puts_filtered ("\n");
795 puts_filtered (indent);
800 wrap_column = chars_printed;
801 wrap_indent = indent;
805 /* Like fputs but pause after every screenful, and can wrap at points
806 other than the final character of a line.
807 Unlike fputs, fputs_filtered does not return a value.
808 It is OK for LINEBUFFER to be NULL, in which case just don't print
811 Note that a longjmp to top level may occur in this routine
812 (since prompt_for_continue may do so) so this routine should not be
813 called when cleanups are not in place. */
816 fputs_filtered (linebuffer, stream)
817 const char *linebuffer;
825 /* Don't do any filtering if it is disabled. */
827 || (lines_per_page == UINT_MAX && chars_per_line == UINT_MAX))
829 fputs (linebuffer, stream);
833 /* Go through and output each character. Show line extension
834 when this is necessary; prompt user for new page when this is
837 lineptr = linebuffer;
840 /* Possible new page. */
841 if (lines_printed >= lines_per_page - 1)
842 prompt_for_continue ();
844 while (*lineptr && *lineptr != '\n')
846 /* Print a single line. */
847 if (*lineptr == '\t')
850 *wrap_pointer++ = '\t';
853 /* Shifting right by 3 produces the number of tab stops
854 we have already passed, and then adding one and
855 shifting left 3 advances to the next tab stop. */
856 chars_printed = ((chars_printed >> 3) + 1) << 3;
862 *wrap_pointer++ = *lineptr;
864 putc (*lineptr, stream);
869 if (chars_printed >= chars_per_line)
871 unsigned int save_chars = chars_printed;
875 /* If we aren't actually wrapping, don't output newline --
876 if chars_per_line is right, we probably just overflowed
877 anyway; if it's wrong, let us keep going. */
881 /* Possible new page. */
882 if (lines_printed >= lines_per_page - 1)
883 prompt_for_continue ();
885 /* Now output indentation and wrapped string */
889 fputs (wrap_indent, stream);
890 *wrap_pointer = '\0'; /* Null-terminate saved stuff */
891 fputs (wrap_buffer, stream); /* and eject it */
892 /* FIXME, this strlen is what prevents wrap_indent from
893 containing tabs. However, if we recurse to print it
894 and count its chars, we risk trouble if wrap_indent is
895 longer than (the user settable) chars_per_line.
896 Note also that this can set chars_printed > chars_per_line
897 if we are printing a long string. */
898 chars_printed = strlen (wrap_indent)
899 + (save_chars - wrap_column);
900 wrap_pointer = wrap_buffer; /* Reset buffer */
901 wrap_buffer[0] = '\0';
902 wrap_column = 0; /* And disable fancy wrap */
907 if (*lineptr == '\n')
910 wrap_here ((char *)0); /* Spit out chars, cancel further wraps */
919 /* fputs_demangled is a variant of fputs_filtered that
920 demangles g++ names.*/
923 fputs_demangled (linebuffer, stream, arg_mode)
928 #define SYMBOL_MAX 1024
930 #define SYMBOL_CHAR(c) (isascii(c) \
931 && (isalnum(c) || (c) == '_' || (c) == CPLUS_MARKER))
933 char buf[SYMBOL_MAX+1];
934 # define SLOP 5 /* How much room to leave in buf */
937 if (linebuffer == NULL)
940 /* If user wants to see raw output, no problem. */
942 fputs_filtered (linebuffer, stream);
948 while ( *p != (char) 0 ) {
951 /* collect non-interesting characters into buf */
952 while ( *p != (char) 0 && !SYMBOL_CHAR(*p) && i < (int)sizeof(buf)-SLOP ) {
957 /* output the non-interesting characters without demangling */
959 fputs_filtered(buf, stream);
960 i = 0; /* reset buf */
963 /* and now the interesting characters */
964 while (i < SYMBOL_MAX
967 && i < (int)sizeof(buf) - SLOP) {
975 if ( (result = cplus_demangle(buf, arg_mode)) != NULL ) {
976 fputs_filtered(result, stream);
980 fputs_filtered(buf, stream);
986 /* Print a variable number of ARGS using format FORMAT. If this
987 information is going to put the amount written (since the last call
988 to INITIALIZE_MORE_FILTER or the last page break) over the page size,
989 print out a pause message and do a gdb_readline to get the users
990 permision to continue.
992 Unlike fprintf, this function does not return a value.
994 We implement three variants, vfprintf (takes a vararg list and stream),
995 fprintf (takes a stream to write on), and printf (the usual).
997 Note that this routine has a restriction that the length of the
998 final output line must be less than 255 characters *or* it must be
999 less than twice the size of the format string. This is a very
1000 arbitrary restriction, but it is an internal restriction, so I'll
1001 put it in. This means that the %s format specifier is almost
1002 useless; unless the caller can GUARANTEE that the string is short
1003 enough, fputs_filtered should be used instead.
1005 Note also that a longjmp to top level may occur in this routine
1006 (since prompt_for_continue may do so) so this routine should not be
1007 called when cleanups are not in place. */
1010 vfprintf_filtered (stream, format, args)
1015 static char *linebuffer = (char *) 0;
1016 static int line_size;
1019 format_length = strlen (format);
1021 /* Allocated linebuffer for the first time. */
1024 linebuffer = (char *) xmalloc (255);
1028 /* Reallocate buffer to a larger size if this is necessary. */
1029 if (format_length * 2 > line_size)
1031 line_size = format_length * 2;
1033 /* You don't have to copy. */
1035 linebuffer = (char *) xmalloc (line_size);
1039 /* This won't blow up if the restrictions described above are
1041 (void) vsprintf (linebuffer, format, args);
1043 fputs_filtered (linebuffer, stream);
1048 fprintf_filtered (va_alist)
1056 stream = va_arg (args, FILE *);
1057 format = va_arg (args, char *);
1059 /* This won't blow up if the restrictions described above are
1061 vfprintf_filtered (stream, format, args);
1067 printf_filtered (va_alist)
1074 format = va_arg (args, char *);
1076 vfprintf_filtered (stdout, format, args);
1083 puts_filtered (string)
1086 fputs_filtered (string, stdout);
1089 /* Return a pointer to N spaces and a null. The pointer is good
1090 until the next call to here. */
1096 static char *spaces;
1097 static int max_spaces;
1103 spaces = malloc (n+1);
1104 for (t = spaces+n; t != spaces;)
1110 return spaces + max_spaces - n;
1113 /* Print N spaces. */
1115 print_spaces_filtered (n, stream)
1119 fputs_filtered (n_spaces (n), stream);
1122 /* C++ demangler stuff. */
1124 /* Print NAME on STREAM, demangling if necessary. */
1126 fprint_symbol (stream, name)
1131 if ((!demangle) || NULL == (demangled = cplus_demangle (name, 1)))
1132 fputs_filtered (name, stream);
1135 fputs_filtered (demangled, stream);
1141 _initialize_utils ()
1143 struct cmd_list_element *c;
1145 c = add_set_cmd ("width", class_support, var_uinteger,
1146 (char *)&chars_per_line,
1147 "Set number of characters gdb thinks are in a line.",
1149 add_show_from_set (c, &showlist);
1150 c->function = set_width_command;
1153 (add_set_cmd ("height", class_support,
1154 var_uinteger, (char *)&lines_per_page,
1155 "Set number of lines gdb thinks are in a page.", &setlist),
1158 /* These defaults will be used if we are unable to get the correct
1159 values from termcap. */
1160 lines_per_page = 24;
1161 chars_per_line = 80;
1162 /* Initialize the screen height and width from termcap. */
1164 char *termtype = getenv ("TERM");
1166 /* Positive means success, nonpositive means failure. */
1169 /* 2048 is large enough for all known terminals, according to the
1170 GNU termcap manual. */
1171 char term_buffer[2048];
1175 status = tgetent (term_buffer, termtype);
1180 val = tgetnum ("li");
1182 lines_per_page = val;
1184 /* The number of lines per page is not mentioned
1185 in the terminal description. This probably means
1186 that paging is not useful (e.g. emacs shell window),
1187 so disable paging. */
1188 lines_per_page = UINT_MAX;
1190 val = tgetnum ("co");
1192 chars_per_line = val;
1197 /* If the output is not a terminal, don't paginate it. */
1198 if (!ISATTY (stdout))
1199 lines_per_page = UINT_MAX;
1201 set_width_command ((char *)NULL, 0, c);
1204 (add_set_cmd ("demangle", class_support, var_boolean,
1206 "Set demangling of encoded C++ names when displaying symbols.",
1211 (add_set_cmd ("sevenbit-strings", class_support, var_boolean,
1212 (char *)&sevenbit_strings,
1213 "Set printing of 8-bit characters in strings as \\nnn.",
1218 (add_set_cmd ("asm-demangle", class_support, var_boolean,
1219 (char *)&asm_demangle,
1220 "Set demangling of C++ names in disassembly listings.",