1 /* General utility routines for GDB, the GNU debugger.
2 Copyright (C) 1986, 1989, 1990, 1991 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>
36 extern volatile void return_to_top_level ();
37 extern volatile void exit ();
38 extern char *gdb_readline ();
39 extern char *getenv();
40 extern char *malloc();
41 extern char *realloc();
43 /* If this definition isn't overridden by the header files, assume
44 that isatty and fileno exist on this system. */
46 #define ISATTY(FP) (isatty (fileno (FP)))
49 #ifdef MISSING_VPRINTF
51 #undef MISSING_VPRINTF
52 #else /* !__GNU_LIBRARY */
55 /* Can't #define it since language.c needs it (though FIXME it shouldn't) */
57 vfprintf (file, format, ap)
62 _doprnt (format, ap, file);
67 /* Can't #define it since printcmd.c needs it */
73 vfprintf (stdout, format, ap);
77 #endif /* GNU_LIBRARY */
78 #endif /* MISSING_VPRINTF */
83 /* Chain of cleanup actions established with make_cleanup,
84 to be executed if an error happens. */
86 static struct cleanup *cleanup_chain;
88 /* Nonzero means a quit has been requested. */
92 /* Nonzero means quit immediately if Control-C is typed now,
93 rather than waiting until QUIT is executed. */
97 /* Nonzero means that encoded C++ names should be printed out in their
98 C++ form rather than raw. */
102 /* Nonzero means that encoded C++ names should be printed out in their
103 C++ form even in assembler language displays. If this is set, but
104 DEMANGLE is zero, names are printed raw, i.e. DEMANGLE controls. */
106 int asm_demangle = 0;
108 /* Nonzero means that strings with character values >0x7F should be printed
109 as octal escapes. Zero means just print the value (e.g. it's an
110 international character, and the terminal or window can cope.) */
112 int sevenbit_strings = 0;
114 /* String to be printed before error messages, if any. */
116 char *error_pre_print;
117 char *warning_pre_print;
119 /* Add a new cleanup to the cleanup_chain,
120 and return the previous chain pointer
121 to be passed later to do_cleanups or discard_cleanups.
122 Args are FUNCTION to clean up with, and ARG to pass to it. */
125 make_cleanup (function, arg)
129 register struct cleanup *new
130 = (struct cleanup *) xmalloc (sizeof (struct cleanup));
131 register struct cleanup *old_chain = cleanup_chain;
133 new->next = cleanup_chain;
134 new->function = function;
141 /* Discard cleanups and do the actions they describe
142 until we get back to the point OLD_CHAIN in the cleanup_chain. */
145 do_cleanups (old_chain)
146 register struct cleanup *old_chain;
148 register struct cleanup *ptr;
149 while ((ptr = cleanup_chain) != old_chain)
151 cleanup_chain = ptr->next; /* Do this first incase recursion */
152 (*ptr->function) (ptr->arg);
157 /* Discard cleanups, not doing the actions they describe,
158 until we get back to the point OLD_CHAIN in the cleanup_chain. */
161 discard_cleanups (old_chain)
162 register struct cleanup *old_chain;
164 register struct cleanup *ptr;
165 while ((ptr = cleanup_chain) != old_chain)
167 cleanup_chain = ptr->next;
172 /* Set the cleanup_chain to 0, and return the old cleanup chain. */
176 struct cleanup *old_chain = cleanup_chain;
182 /* Restore the cleanup chain from a previously saved chain. */
184 restore_cleanups (chain)
185 struct cleanup *chain;
187 cleanup_chain = chain;
190 /* This function is useful for cleanups.
194 old_chain = make_cleanup (free_current_contents, &foo);
196 to arrange to free the object thus allocated. */
199 free_current_contents (location)
205 /* Provide a hook for modules wishing to print their own warning messages
206 to set up the terminal state in a compatible way, without them having
207 to import all the target_<...> macros. */
212 target_terminal_ours ();
213 wrap_here(""); /* Force out any buffered output */
217 /* Print a warning message.
218 The first argument STRING is the warning message, used as a fprintf string,
219 and the remaining args are passed as arguments to it.
220 The primary difference between warnings and errors is that a warning
221 does not force the return to command level. */
232 target_terminal_ours ();
233 wrap_here(""); /* Force out any buffered output */
235 if (warning_pre_print)
236 fprintf (stderr, warning_pre_print);
237 string = va_arg (args, char *);
238 vfprintf (stderr, string, args);
239 fprintf (stderr, "\n");
243 /* Print an error message and return to command level.
244 The first argument STRING is the error message, used as a fprintf string,
245 and the remaining args are passed as arguments to it. */
256 target_terminal_ours ();
257 wrap_here(""); /* Force out any buffered output */
260 fprintf (stderr, error_pre_print);
261 string = va_arg (args, char *);
262 vfprintf (stderr, string, args);
263 fprintf (stderr, "\n");
265 return_to_top_level ();
268 /* Print an error message and exit reporting failure.
269 This is for a error that we cannot continue from.
270 The arguments are printed a la printf. */
281 string = va_arg (args, char *);
282 fprintf (stderr, "gdb: ");
283 vfprintf (stderr, string, args);
284 fprintf (stderr, "\n");
289 /* Print an error message and exit, dumping core.
290 The arguments are printed a la printf (). */
293 fatal_dump_core (va_alist)
300 string = va_arg (args, char *);
301 /* "internal error" is always correct, since GDB should never dump
302 core, no matter what the input. */
303 fprintf (stderr, "gdb internal error: ");
304 vfprintf (stderr, string, args);
305 fprintf (stderr, "\n");
308 signal (SIGQUIT, SIG_DFL);
309 kill (getpid (), SIGQUIT);
310 /* We should never get here, but just in case... */
314 /* Memory management stuff (malloc friends). */
316 #if defined (NO_MALLOC_CHECK)
320 #else /* Have mcheck(). */
324 fatal_dump_core ("Memory corruption");
330 mcheck (malloc_botch);
333 #endif /* Have mcheck(). */
335 /* Like malloc but get error if no storage available. */
347 /* At least one place (dbxread.c:condense_misc_bunches where misc_count == 0)
348 GDB wants to allocate zero bytes. */
352 val = (char *) malloc (size);
354 fatal ("virtual memory exhausted.", 0);
358 /* Like realloc but get error if no storage available. */
369 register char *val = (char *) realloc (ptr, size);
371 fatal ("virtual memory exhausted.", 0);
375 /* Print the system error message for errno, and also mention STRING
376 as the file name for which the error was encountered.
377 Then return to command level. */
380 perror_with_name (string)
384 extern char *sys_errlist[];
388 if (errno < sys_nerr)
389 err = sys_errlist[errno];
391 err = "unknown error";
393 combined = (char *) alloca (strlen (err) + strlen (string) + 3);
394 strcpy (combined, string);
395 strcat (combined, ": ");
396 strcat (combined, err);
398 /* I understand setting these is a matter of taste. Still, some people
399 may clear errno but not know about bfd_error. Doing this here is not
401 bfd_error = no_error;
404 error ("%s.", combined);
407 /* Print the system error message for ERRCODE, and also mention STRING
408 as the file name for which the error was encountered. */
411 print_sys_errmsg (string, errcode)
416 extern char *sys_errlist[];
420 if (errcode < sys_nerr)
421 err = sys_errlist[errcode];
423 err = "unknown error";
425 combined = (char *) alloca (strlen (err) + strlen (string) + 3);
426 strcpy (combined, string);
427 strcat (combined, ": ");
428 strcat (combined, err);
430 printf ("%s.\n", combined);
433 /* Control C eventually causes this to be called, at a convenient time. */
438 target_terminal_ours ();
439 wrap_here ((char *)0); /* Force out any pending output */
441 ioctl (fileno (stdout), TCFLSH, 1);
442 #else /* not HAVE_TERMIO */
443 ioctl (fileno (stdout), TIOCFLUSH, 0);
444 #endif /* not HAVE_TERMIO */
448 error ("Quit (expect signal %d when inferior is resumed)", SIGINT);
449 #endif /* TIOCGPGRP */
452 /* Control C comes here */
460 /* Restore the signal handler. */
461 signal (SIGINT, request_quit);
468 /* My replacement for the read system call.
469 Used like `read' but keeps going if `read' returns too soon. */
472 myread (desc, addr, len)
482 val = read (desc, addr, len);
493 /* Make a copy of the string at PTR with SIZE characters
494 (and add a null character at the end in the copy).
495 Uses malloc to get the space. Returns the address of the copy. */
498 savestring (ptr, size)
502 register char *p = (char *) xmalloc (size + 1);
503 bcopy (ptr, p, size);
508 /* The "const" is so it compiles under DGUX (which prototypes strsave
509 in <string.h>. FIXME: This should be named "xstrsave", shouldn't it?
510 Doesn't real strsave return NULL if out of memory? */
515 return savestring (ptr, strlen (ptr));
522 register int len = strlen (s1) + strlen (s2) + strlen (s3) + 1;
523 register char *val = (char *) xmalloc (len);
531 print_spaces (n, file)
539 /* Ask user a y-or-n question and return 1 iff answer is yes.
540 Takes three args which are given to printf to print the question.
541 The first, a control string, should end in "? ".
542 It should not say how to answer, because we do that. */
554 /* Automatically answer "yes" if input is not from a terminal. */
555 if (!input_from_terminal_p ())
561 ctlstr = va_arg (args, char *);
562 vfprintf (stdout, ctlstr, args);
564 printf ("(y or n) ");
566 answer = fgetc (stdin);
567 clearerr (stdin); /* in case of C-d */
568 if (answer == EOF) /* C-d */
570 if (answer != '\n') /* Eat rest of input line, to EOF or newline */
573 ans2 = fgetc (stdin);
576 while (ans2 != EOF && ans2 != '\n');
583 printf ("Please answer y or n.\n");
587 /* Parse a C escape sequence. STRING_PTR points to a variable
588 containing a pointer to the string to parse. That pointer
589 should point to the character after the \. That pointer
590 is updated past the characters we use. The value of the
591 escape sequence is returned.
593 A negative value means the sequence \ newline was seen,
594 which is supposed to be equivalent to nothing at all.
596 If \ is followed by a null character, we return a negative
597 value and leave the string pointer pointing at the null character.
599 If \ is followed by 000, we return 0 and leave the string pointer
600 after the zeros. A value of 0 does not mean end of string. */
603 parse_escape (string_ptr)
606 register int c = *(*string_ptr)++;
610 return 007; /* Bell (alert) char */
613 case 'e': /* Escape character */
631 c = *(*string_ptr)++;
633 c = parse_escape (string_ptr);
636 return (c & 0200) | (c & 037);
647 register int i = c - '0';
648 register int count = 0;
651 if ((c = *(*string_ptr)++) >= '0' && c <= '7')
669 /* Print the character CH on STREAM as part of the contents
670 of a literal string whose delimiter is QUOTER. */
673 printchar (ch, stream, quoter)
680 if (c < 040 || (sevenbit_strings && c >= 0177)) {
684 fputs_filtered ("\\n", stream);
687 fputs_filtered ("\\b", stream);
690 fputs_filtered ("\\t", stream);
693 fputs_filtered ("\\f", stream);
696 fputs_filtered ("\\r", stream);
699 fputs_filtered ("\\e", stream);
702 fputs_filtered ("\\a", stream);
705 fprintf_filtered (stream, "\\%.3o", (unsigned int) c);
709 if (c == '\\' || c == quoter)
710 fputs_filtered ("\\", stream);
711 fprintf_filtered (stream, "%c", c);
715 /* Number of lines per page or UINT_MAX if paging is disabled. */
716 static unsigned int lines_per_page;
717 /* Number of chars per line or UNIT_MAX is line folding is disabled. */
718 static unsigned int chars_per_line;
719 /* Current count of lines printed on this page, chars on this line. */
720 static unsigned int lines_printed, chars_printed;
722 /* Buffer and start column of buffered text, for doing smarter word-
723 wrapping. When someone calls wrap_here(), we start buffering output
724 that comes through fputs_filtered(). If we see a newline, we just
725 spit it out and forget about the wrap_here(). If we see another
726 wrap_here(), we spit it out and remember the newer one. If we see
727 the end of the line, we spit out a newline, the indent, and then
730 wrap_column is the column number on the screen where wrap_buffer begins.
731 When wrap_column is zero, wrapping is not in effect.
732 wrap_buffer is malloc'd with chars_per_line+2 bytes.
733 When wrap_buffer[0] is null, the buffer is empty.
734 wrap_pointer points into it at the next character to fill.
735 wrap_indent is the string that should be used as indentation if the
738 static char *wrap_buffer, *wrap_pointer, *wrap_indent;
739 static int wrap_column;
743 set_width_command (args, from_tty, c)
746 struct cmd_list_element *c;
750 wrap_buffer = (char *) xmalloc (chars_per_line + 2);
751 wrap_buffer[0] = '\0';
754 wrap_buffer = (char *) xrealloc (wrap_buffer, chars_per_line + 2);
755 wrap_pointer = wrap_buffer; /* Start it at the beginning */
759 prompt_for_continue ()
764 ignore = gdb_readline ("---Type <return> to continue---");
767 chars_printed = lines_printed = 0;
769 dont_repeat (); /* Forget prev cmd -- CR won't repeat it. */
772 /* Reinitialize filter; ie. tell it to reset to original values. */
775 reinitialize_more_filter ()
781 /* Indicate that if the next sequence of characters overflows the line,
782 a newline should be inserted here rather than when it hits the end.
783 If INDENT is nonzero, it is a string to be printed to indent the
784 wrapped part on the next line. INDENT must remain accessible until
785 the next call to wrap_here() or until a newline is printed through
788 If the line is already overfull, we immediately print a newline and
789 the indentation, and disable further wrapping.
791 If we don't know the width of lines, but we know the page height,
792 we must not wrap words, but should still keep track of newlines
793 that were explicitly printed.
795 INDENT should not contain tabs, as that
796 will mess up the char count on the next line. FIXME. */
804 *wrap_pointer = '\0';
805 fputs (wrap_buffer, stdout);
807 wrap_pointer = wrap_buffer;
808 wrap_buffer[0] = '\0';
809 if (chars_per_line == UINT_MAX) /* No line overflow checking */
813 else if (chars_printed >= chars_per_line)
815 puts_filtered ("\n");
816 puts_filtered (indent);
821 wrap_column = chars_printed;
822 wrap_indent = indent;
826 /* Like fputs but pause after every screenful, and can wrap at points
827 other than the final character of a line.
828 Unlike fputs, fputs_filtered does not return a value.
829 It is OK for LINEBUFFER to be NULL, in which case just don't print
832 Note that a longjmp to top level may occur in this routine
833 (since prompt_for_continue may do so) so this routine should not be
834 called when cleanups are not in place. */
837 fputs_filtered (linebuffer, stream)
846 /* Don't do any filtering if it is disabled. */
848 || (lines_per_page == UINT_MAX && chars_per_line == UINT_MAX))
850 fputs (linebuffer, stream);
854 /* Go through and output each character. Show line extension
855 when this is necessary; prompt user for new page when this is
858 lineptr = linebuffer;
861 /* Possible new page. */
862 if (lines_printed >= lines_per_page - 1)
863 prompt_for_continue ();
865 while (*lineptr && *lineptr != '\n')
867 /* Print a single line. */
868 if (*lineptr == '\t')
871 *wrap_pointer++ = '\t';
874 /* Shifting right by 3 produces the number of tab stops
875 we have already passed, and then adding one and
876 shifting left 3 advances to the next tab stop. */
877 chars_printed = ((chars_printed >> 3) + 1) << 3;
883 *wrap_pointer++ = *lineptr;
885 putc (*lineptr, stream);
890 if (chars_printed >= chars_per_line)
892 unsigned int save_chars = chars_printed;
896 /* If we aren't actually wrapping, don't output newline --
897 if chars_per_line is right, we probably just overflowed
898 anyway; if it's wrong, let us keep going. */
902 /* Possible new page. */
903 if (lines_printed >= lines_per_page - 1)
904 prompt_for_continue ();
906 /* Now output indentation and wrapped string */
910 fputs (wrap_indent, stream);
911 *wrap_pointer = '\0'; /* Null-terminate saved stuff */
912 fputs (wrap_buffer, stream); /* and eject it */
913 /* FIXME, this strlen is what prevents wrap_indent from
914 containing tabs. However, if we recurse to print it
915 and count its chars, we risk trouble if wrap_indent is
916 longer than (the user settable) chars_per_line.
917 Note also that this can set chars_printed > chars_per_line
918 if we are printing a long string. */
919 chars_printed = strlen (wrap_indent)
920 + (save_chars - wrap_column);
921 wrap_pointer = wrap_buffer; /* Reset buffer */
922 wrap_buffer[0] = '\0';
923 wrap_column = 0; /* And disable fancy wrap */
928 if (*lineptr == '\n')
931 wrap_here ((char *)0); /* Spit out chars, cancel further wraps */
940 /* fputs_demangled is a variant of fputs_filtered that
941 demangles g++ names.*/
944 fputs_demangled (linebuffer, stream, arg_mode)
950 extern char *cplus_demangle (const char *, int);
952 extern char *cplus_demangle ();
954 #define SYMBOL_MAX 1024
956 #define SYMBOL_CHAR(c) (isascii(c) \
957 && (isalnum(c) || (c) == '_' || (c) == CPLUS_MARKER))
959 char buf[SYMBOL_MAX+1];
960 # define SLOP 5 /* How much room to leave in buf */
963 if (linebuffer == NULL)
966 /* If user wants to see raw output, no problem. */
968 fputs_filtered (linebuffer, stream);
974 while ( *p != (char) 0 ) {
977 /* collect non-interesting characters into buf */
978 while ( *p != (char) 0 && !SYMBOL_CHAR(*p) && i < (int)sizeof(buf)-SLOP ) {
983 /* output the non-interesting characters without demangling */
985 fputs_filtered(buf, stream);
986 i = 0; /* reset buf */
989 /* and now the interesting characters */
990 while (i < SYMBOL_MAX
993 && i < (int)sizeof(buf) - SLOP) {
1001 if ( (result = cplus_demangle(buf, arg_mode)) != NULL ) {
1002 fputs_filtered(result, stream);
1006 fputs_filtered(buf, stream);
1012 /* Print a variable number of ARGS using format FORMAT. If this
1013 information is going to put the amount written (since the last call
1014 to INITIALIZE_MORE_FILTER or the last page break) over the page size,
1015 print out a pause message and do a gdb_readline to get the users
1016 permision to continue.
1018 Unlike fprintf, this function does not return a value.
1020 We implement three variants, vfprintf (takes a vararg list and stream),
1021 fprintf (takes a stream to write on), and printf (the usual).
1023 Note that this routine has a restriction that the length of the
1024 final output line must be less than 255 characters *or* it must be
1025 less than twice the size of the format string. This is a very
1026 arbitrary restriction, but it is an internal restriction, so I'll
1027 put it in. This means that the %s format specifier is almost
1028 useless; unless the caller can GUARANTEE that the string is short
1029 enough, fputs_filtered should be used instead.
1031 Note also that a longjmp to top level may occur in this routine
1032 (since prompt_for_continue may do so) so this routine should not be
1033 called when cleanups are not in place. */
1035 #if !defined(MISSING_VPRINTF) || defined (vsprintf)
1038 vfprintf_filtered (stream, format, args)
1041 void fprintf_filtered (stream, format, arg1, arg2, arg3, arg4, arg5, arg6)
1046 static char *linebuffer = (char *) 0;
1047 static int line_size;
1050 format_length = strlen (format);
1052 /* Allocated linebuffer for the first time. */
1055 linebuffer = (char *) xmalloc (255);
1059 /* Reallocate buffer to a larger size if this is necessary. */
1060 if (format_length * 2 > line_size)
1062 line_size = format_length * 2;
1064 /* You don't have to copy. */
1066 linebuffer = (char *) xmalloc (line_size);
1070 /* This won't blow up if the restrictions described above are
1072 #if !defined(MISSING_VPRINTF) || defined (vsprintf)
1073 (void) vsprintf (linebuffer, format, args);
1075 (void) sprintf (linebuffer, format, arg1, arg2, arg3, arg4, arg5, arg6);
1078 fputs_filtered (linebuffer, stream);
1081 #if !defined(MISSING_VPRINTF) || defined (vsprintf)
1084 fprintf_filtered (va_alist)
1092 stream = va_arg (args, FILE *);
1093 format = va_arg (args, char *);
1095 /* This won't blow up if the restrictions described above are
1097 (void) vfprintf_filtered (stream, format, args);
1103 printf_filtered (va_alist)
1110 format = va_arg (args, char *);
1112 (void) vfprintf_filtered (stdout, format, args);
1117 printf_filtered (format, arg1, arg2, arg3, arg4, arg5, arg6)
1119 int arg1, arg2, arg3, arg4, arg5, arg6;
1121 fprintf_filtered (stdout, format, arg1, arg2, arg3, arg4, arg5, arg6);
1128 puts_filtered (string)
1131 fputs_filtered (string, stdout);
1134 /* Return a pointer to N spaces and a null. The pointer is good
1135 until the next call to here. */
1141 static char *spaces;
1142 static int max_spaces;
1148 spaces = malloc (n+1);
1149 for (t = spaces+n; t != spaces;)
1155 return spaces + max_spaces - n;
1158 /* Print N spaces. */
1160 print_spaces_filtered (n, stream)
1164 fputs_filtered (n_spaces (n), stream);
1167 /* C++ demangler stuff. */
1168 char *cplus_demangle ();
1170 /* Print NAME on STREAM, demangling if necessary. */
1172 fprint_symbol (stream, name)
1177 if ((!demangle) || NULL == (demangled = cplus_demangle (name, 1)))
1178 fputs_filtered (name, stream);
1181 fputs_filtered (demangled, stream);
1187 _initialize_utils ()
1189 struct cmd_list_element *c;
1191 c = add_set_cmd ("width", class_support, var_uinteger,
1192 (char *)&chars_per_line,
1193 "Set number of characters gdb thinks are in a line.",
1195 add_show_from_set (c, &showlist);
1196 c->function = set_width_command;
1199 (add_set_cmd ("height", class_support,
1200 var_uinteger, (char *)&lines_per_page,
1201 "Set number of lines gdb thinks are in a page.", &setlist),
1204 /* These defaults will be used if we are unable to get the correct
1205 values from termcap. */
1206 lines_per_page = 24;
1207 chars_per_line = 80;
1208 /* Initialize the screen height and width from termcap. */
1210 char *termtype = getenv ("TERM");
1212 /* Positive means success, nonpositive means failure. */
1215 /* 2048 is large enough for all known terminals, according to the
1216 GNU termcap manual. */
1217 char term_buffer[2048];
1221 status = tgetent (term_buffer, termtype);
1226 val = tgetnum ("li");
1228 lines_per_page = val;
1230 /* The number of lines per page is not mentioned
1231 in the terminal description. This probably means
1232 that paging is not useful (e.g. emacs shell window),
1233 so disable paging. */
1234 lines_per_page = UINT_MAX;
1236 val = tgetnum ("co");
1238 chars_per_line = val;
1243 /* If the output is not a terminal, don't paginate it. */
1244 if (!ISATTY (stdout))
1245 lines_per_page = UINT_MAX;
1247 set_width_command ((char *)NULL, 0, c);
1250 (add_set_cmd ("demangle", class_support, var_boolean,
1252 "Set demangling of encoded C++ names when displaying symbols.",
1257 (add_set_cmd ("sevenbit-strings", class_support, var_boolean,
1258 (char *)&sevenbit_strings,
1259 "Set printing of 8-bit characters in strings as \\nnn.",
1264 (add_set_cmd ("asm-demangle", class_support, var_boolean,
1265 (char *)&asm_demangle,
1266 "Set demangling of C++ names in disassembly listings.",