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>
35 extern volatile void return_to_top_level ();
36 extern volatile void exit ();
37 extern char *gdb_readline ();
38 extern char *getenv();
39 extern char *malloc();
40 extern char *realloc();
42 /* If this definition isn't overridden by the header files, assume
43 that isatty and fileno exist on this system. */
45 #define ISATTY(FP) (isatty (fileno (FP)))
48 #ifdef MISSING_VPRINTF
50 #undef MISSING_VPRINTF
51 #else /* !__GNU_LIBRARY */
54 #define vfprintf(file, format, ap) _doprnt (format, ap, file)
58 /* Can't #define it since printcmd.c needs it */
64 vfprintf (stdout, format, ap);
68 #endif /* GNU_LIBRARY */
69 #endif /* MISSING_VPRINTF */
74 /* Chain of cleanup actions established with make_cleanup,
75 to be executed if an error happens. */
77 static struct cleanup *cleanup_chain;
79 /* Nonzero means a quit has been requested. */
83 /* Nonzero means quit immediately if Control-C is typed now,
84 rather than waiting until QUIT is executed. */
88 /* Nonzero means that encoded C++ names should be printed out in their
89 C++ form rather than raw. */
93 /* Nonzero means that encoded C++ names should be printed out in their
94 C++ form even in assembler language displays. If this is set, but
95 DEMANGLE is zero, names are printed raw, i.e. DEMANGLE controls. */
99 /* Nonzero means that strings with character values >0x7F should be printed
100 as octal escapes. Zero means just print the value (e.g. it's an
101 international character, and the terminal or window can cope.) */
103 int sevenbit_strings = 0;
105 /* Add a new cleanup to the cleanup_chain,
106 and return the previous chain pointer
107 to be passed later to do_cleanups or discard_cleanups.
108 Args are FUNCTION to clean up with, and ARG to pass to it. */
111 make_cleanup (function, arg)
115 register struct cleanup *new
116 = (struct cleanup *) xmalloc (sizeof (struct cleanup));
117 register struct cleanup *old_chain = cleanup_chain;
119 new->next = cleanup_chain;
120 new->function = function;
127 /* Discard cleanups and do the actions they describe
128 until we get back to the point OLD_CHAIN in the cleanup_chain. */
131 do_cleanups (old_chain)
132 register struct cleanup *old_chain;
134 register struct cleanup *ptr;
135 while ((ptr = cleanup_chain) != old_chain)
137 cleanup_chain = ptr->next; /* Do this first incase recursion */
138 (*ptr->function) (ptr->arg);
143 /* Discard cleanups, not doing the actions they describe,
144 until we get back to the point OLD_CHAIN in the cleanup_chain. */
147 discard_cleanups (old_chain)
148 register struct cleanup *old_chain;
150 register struct cleanup *ptr;
151 while ((ptr = cleanup_chain) != old_chain)
153 cleanup_chain = ptr->next;
158 /* Set the cleanup_chain to 0, and return the old cleanup chain. */
162 struct cleanup *old_chain = cleanup_chain;
168 /* Restore the cleanup chain from a previously saved chain. */
170 restore_cleanups (chain)
171 struct cleanup *chain;
173 cleanup_chain = chain;
176 /* This function is useful for cleanups.
180 old_chain = make_cleanup (free_current_contents, &foo);
182 to arrange to free the object thus allocated. */
185 free_current_contents (location)
191 /* Print an error message and return to command level.
192 The first argument STRING is the error message, used as a fprintf string,
193 and the remaining args are passed as arguments to it. */
204 target_terminal_ours ();
206 string = va_arg (args, char *);
207 vfprintf (stderr, string, args);
208 fprintf (stderr, "\n");
210 return_to_top_level ();
213 /* Print an error message and exit reporting failure.
214 This is for a error that we cannot continue from.
215 The arguments are printed a la printf. */
226 string = va_arg (args, char *);
227 fprintf (stderr, "gdb: ");
228 vfprintf (stderr, string, args);
229 fprintf (stderr, "\n");
234 /* Print an error message and exit, dumping core.
235 The arguments are printed a la printf (). */
238 fatal_dump_core (va_alist)
245 string = va_arg (args, char *);
246 /* "internal error" is always correct, since GDB should never dump
247 core, no matter what the input. */
248 fprintf (stderr, "gdb internal error: ");
249 vfprintf (stderr, string, args);
250 fprintf (stderr, "\n");
253 signal (SIGQUIT, SIG_DFL);
254 kill (getpid (), SIGQUIT);
255 /* We should never get here, but just in case... */
259 /* Memory management stuff (malloc friends). */
261 #if defined (NO_MALLOC_CHECK)
265 #else /* Have mcheck(). */
269 fatal_dump_core ("Memory corruption");
275 mcheck (malloc_botch);
278 #endif /* Have mcheck(). */
280 /* Like malloc but get error if no storage available. */
292 /* At least one place (dbxread.c:condense_misc_bunches where misc_count == 0)
293 GDB wants to allocate zero bytes. */
297 val = (char *) malloc (size);
299 fatal ("virtual memory exhausted.", 0);
303 /* Like realloc but get error if no storage available. */
314 register char *val = (char *) realloc (ptr, size);
316 fatal ("virtual memory exhausted.", 0);
320 /* Print the system error message for errno, and also mention STRING
321 as the file name for which the error was encountered.
322 Then return to command level. */
325 perror_with_name (string)
329 extern char *sys_errlist[];
333 if (errno < sys_nerr)
334 err = sys_errlist[errno];
336 err = "unknown error";
338 combined = (char *) alloca (strlen (err) + strlen (string) + 3);
339 strcpy (combined, string);
340 strcat (combined, ": ");
341 strcat (combined, err);
343 /* I understand setting these is a matter of taste. Still, some people
344 may clear errno but not know about bfd_error. Doing this here is not
346 bfd_error = no_error;
349 error ("%s.", combined);
352 /* Print the system error message for ERRCODE, and also mention STRING
353 as the file name for which the error was encountered. */
356 print_sys_errmsg (string, errcode)
361 extern char *sys_errlist[];
365 if (errcode < sys_nerr)
366 err = sys_errlist[errcode];
368 err = "unknown error";
370 combined = (char *) alloca (strlen (err) + strlen (string) + 3);
371 strcpy (combined, string);
372 strcat (combined, ": ");
373 strcat (combined, err);
375 printf ("%s.\n", combined);
378 /* Control C eventually causes this to be called, at a convenient time. */
383 target_terminal_ours ();
384 wrap_here ((char *)0); /* Force out any pending output */
386 ioctl (fileno (stdout), TCFLSH, 1);
387 #else /* not HAVE_TERMIO */
388 ioctl (fileno (stdout), TIOCFLUSH, 0);
389 #endif /* not HAVE_TERMIO */
393 error ("Quit (expect signal %d when inferior is resumed)", SIGINT);
394 #endif /* TIOCGPGRP */
397 /* Control C comes here */
405 /* Restore the signal handler. */
406 signal (SIGINT, request_quit);
413 /* My replacement for the read system call.
414 Used like `read' but keeps going if `read' returns too soon. */
417 myread (desc, addr, len)
427 val = read (desc, addr, len);
438 /* Make a copy of the string at PTR with SIZE characters
439 (and add a null character at the end in the copy).
440 Uses malloc to get the space. Returns the address of the copy. */
443 savestring (ptr, size)
447 register char *p = (char *) xmalloc (size + 1);
448 bcopy (ptr, p, size);
453 /* The "const" is so it compiles under DGUX (which prototypes strsave
454 in <string.h>. FIXME: This should be named "xstrsave", shouldn't it?
455 Doesn't real strsave return NULL if out of memory? */
460 return savestring (ptr, strlen (ptr));
467 register int len = strlen (s1) + strlen (s2) + strlen (s3) + 1;
468 register char *val = (char *) xmalloc (len);
476 print_spaces (n, file)
484 /* Ask user a y-or-n question and return 1 iff answer is yes.
485 Takes three args which are given to printf to print the question.
486 The first, a control string, should end in "? ".
487 It should not say how to answer, because we do that. */
499 /* Automatically answer "yes" if input is not from a terminal. */
500 if (!input_from_terminal_p ())
506 ctlstr = va_arg (args, char *);
507 vfprintf (stdout, ctlstr, args);
509 printf ("(y or n) ");
511 answer = fgetc (stdin);
512 clearerr (stdin); /* in case of C-d */
513 if (answer == EOF) /* C-d */
515 if (answer != '\n') /* Eat rest of input line, to EOF or newline */
518 ans2 = fgetc (stdin);
521 while (ans2 != EOF && ans2 != '\n');
528 printf ("Please answer y or n.\n");
532 /* Parse a C escape sequence. STRING_PTR points to a variable
533 containing a pointer to the string to parse. That pointer
534 should point to the character after the \. That pointer
535 is updated past the characters we use. The value of the
536 escape sequence is returned.
538 A negative value means the sequence \ newline was seen,
539 which is supposed to be equivalent to nothing at all.
541 If \ is followed by a null character, we return a negative
542 value and leave the string pointer pointing at the null character.
544 If \ is followed by 000, we return 0 and leave the string pointer
545 after the zeros. A value of 0 does not mean end of string. */
548 parse_escape (string_ptr)
551 register int c = *(*string_ptr)++;
576 c = *(*string_ptr)++;
578 c = parse_escape (string_ptr);
581 return (c & 0200) | (c & 037);
592 register int i = c - '0';
593 register int count = 0;
596 if ((c = *(*string_ptr)++) >= '0' && c <= '7')
614 /* Print the character CH on STREAM as part of the contents
615 of a literal string whose delimiter is QUOTER. */
618 printchar (ch, stream, quoter)
625 if (c < 040 || (sevenbit_strings && c >= 0177))
629 fputs_filtered ("\\n", stream);
632 fputs_filtered ("\\b", stream);
635 fputs_filtered ("\\t", stream);
638 fputs_filtered ("\\f", stream);
641 fputs_filtered ("\\r", stream);
644 fputs_filtered ("\\e", stream);
647 fputs_filtered ("\\a", stream);
650 fprintf_filtered (stream, "\\%.3o", (unsigned int) c);
655 if (c == '\\' || c == quoter)
656 fputs_filtered ("\\", stream);
657 fprintf_filtered (stream, "%c", c);
661 /* Number of lines per page or UINT_MAX if paging is disabled. */
662 static unsigned int lines_per_page;
663 /* Number of chars per line or UNIT_MAX is line folding is disabled. */
664 static unsigned int chars_per_line;
665 /* Current count of lines printed on this page, chars on this line. */
666 static unsigned int lines_printed, chars_printed;
668 /* Buffer and start column of buffered text, for doing smarter word-
669 wrapping. When someone calls wrap_here(), we start buffering output
670 that comes through fputs_filtered(). If we see a newline, we just
671 spit it out and forget about the wrap_here(). If we see another
672 wrap_here(), we spit it out and remember the newer one. If we see
673 the end of the line, we spit out a newline, the indent, and then
676 wrap_column is the column number on the screen where wrap_buffer begins.
677 When wrap_column is zero, wrapping is not in effect.
678 wrap_buffer is malloc'd with chars_per_line+2 bytes.
679 When wrap_buffer[0] is null, the buffer is empty.
680 wrap_pointer points into it at the next character to fill.
681 wrap_indent is the string that should be used as indentation if the
684 static char *wrap_buffer, *wrap_pointer, *wrap_indent;
685 static int wrap_column;
687 /* Get the number of lines to print with commands like "list".
688 This is based on guessing how many long (i.e. more than chars_per_line
689 characters) lines there will be. To be completely correct, "list"
690 and friends should be rewritten to count characters and see where
691 things are wrapping, but that would be a fair amount of work. */
695 /* RMS didn't like the following algorithm. Let's set it back to
696 10 and see if anyone else complains. */
697 /* return lines_per_page == UINT_MAX ? 10 : lines_per_page / 2; */
703 set_width_command (args, from_tty, c)
706 struct cmd_list_element *c;
710 wrap_buffer = (char *) xmalloc (chars_per_line + 2);
711 wrap_buffer[0] = '\0';
714 wrap_buffer = (char *) xrealloc (wrap_buffer, chars_per_line + 2);
715 wrap_pointer = wrap_buffer; /* Start it at the beginning */
719 prompt_for_continue ()
724 ignore = gdb_readline ("---Type <return> to continue---");
727 chars_printed = lines_printed = 0;
729 dont_repeat (); /* Forget prev cmd -- CR won't repeat it. */
732 /* Reinitialize filter; ie. tell it to reset to original values. */
735 reinitialize_more_filter ()
741 /* Indicate that if the next sequence of characters overflows the line,
742 a newline should be inserted here rather than when it hits the end.
743 If INDENT is nonzero, it is a string to be printed to indent the
744 wrapped part on the next line. INDENT must remain accessible until
745 the next call to wrap_here() or until a newline is printed through
748 If the line is already overfull, we immediately print a newline and
749 the indentation, and disable further wrapping.
751 INDENT should not contain tabs, as that
752 will mess up the char count on the next line. FIXME. */
760 *wrap_pointer = '\0';
761 fputs (wrap_buffer, stdout);
763 wrap_pointer = wrap_buffer;
764 wrap_buffer[0] = '\0';
765 if (chars_printed >= chars_per_line)
767 puts_filtered ("\n");
768 puts_filtered (indent);
773 wrap_column = chars_printed;
774 wrap_indent = indent;
778 /* Like fputs but pause after every screenful, and can wrap at points
779 other than the final character of a line.
780 Unlike fputs, fputs_filtered does not return a value.
781 It is OK for LINEBUFFER to be NULL, in which case just don't print
784 Note that a longjmp to top level may occur in this routine
785 (since prompt_for_continue may do so) so this routine should not be
786 called when cleanups are not in place. */
789 fputs_filtered (linebuffer, stream)
798 /* Don't do any filtering if it is disabled. */
800 || (lines_per_page == UINT_MAX && chars_per_line == UINT_MAX))
802 fputs (linebuffer, stream);
806 /* Go through and output each character. Show line extension
807 when this is necessary; prompt user for new page when this is
810 lineptr = linebuffer;
813 /* Possible new page. */
814 if (lines_printed >= lines_per_page - 1)
815 prompt_for_continue ();
817 while (*lineptr && *lineptr != '\n')
819 /* Print a single line. */
820 if (*lineptr == '\t')
823 *wrap_pointer++ = '\t';
826 /* Shifting right by 3 produces the number of tab stops
827 we have already passed, and then adding one and
828 shifting left 3 advances to the next tab stop. */
829 chars_printed = ((chars_printed >> 3) + 1) << 3;
835 *wrap_pointer++ = *lineptr;
837 putc (*lineptr, stream);
842 if (chars_printed >= chars_per_line)
844 unsigned int save_chars = chars_printed;
848 /* If we aren't actually wrapping, don't output newline --
849 if chars_per_line is right, we probably just overflowed
850 anyway; if it's wrong, let us keep going. */
854 /* Possible new page. */
855 if (lines_printed >= lines_per_page - 1)
856 prompt_for_continue ();
858 /* Now output indentation and wrapped string */
862 fputs (wrap_indent, stream);
863 *wrap_pointer = '\0'; /* Null-terminate saved stuff */
864 fputs (wrap_buffer, stream); /* and eject it */
865 /* FIXME, this strlen is what prevents wrap_indent from
866 containing tabs. However, if we recurse to print it
867 and count its chars, we risk trouble if wrap_indent is
868 longer than (the user settable) chars_per_line.
869 Note also that this can set chars_printed > chars_per_line
870 if we are printing a long string. */
871 chars_printed = strlen (wrap_indent)
872 + (save_chars - wrap_column);
873 wrap_pointer = wrap_buffer; /* Reset buffer */
874 wrap_buffer[0] = '\0';
875 wrap_column = 0; /* And disable fancy wrap */
880 if (*lineptr == '\n')
883 wrap_here ((char *)0); /* Spit out chars, cancel further wraps */
892 /* fputs_demangled is a variant of fputs_filtered that
893 demangles g++ names.*/
896 fputs_demangled (linebuffer, stream, arg_mode)
902 extern char *cplus_demangle (const char *, int);
904 extern char *cplus_demangle ();
906 #define SYMBOL_MAX 1024
908 #define SYMBOL_CHAR(c) (isascii(c) \
909 && (isalnum(c) || (c) == '_' || (c) == CPLUS_MARKER))
911 char buf[SYMBOL_MAX+1];
912 # define SLOP 5 /* How much room to leave in buf */
915 if (linebuffer == NULL)
918 /* If user wants to see raw output, no problem. */
920 fputs_filtered (linebuffer, stream);
926 while ( *p != (char) 0 ) {
929 /* collect non-interesting characters into buf */
930 while ( *p != (char) 0 && !SYMBOL_CHAR(*p) && i < (int)sizeof(buf)-SLOP ) {
935 /* output the non-interesting characters without demangling */
937 fputs_filtered(buf, stream);
938 i = 0; /* reset buf */
941 /* and now the interesting characters */
942 while (i < SYMBOL_MAX
945 && i < (int)sizeof(buf) - SLOP) {
953 if ( (result = cplus_demangle(buf, arg_mode)) != NULL ) {
954 fputs_filtered(result, stream);
958 fputs_filtered(buf, stream);
964 /* Print a variable number of ARGS using format FORMAT. If this
965 information is going to put the amount written (since the last call
966 to INITIALIZE_MORE_FILTER or the last page break) over the page size,
967 print out a pause message and do a gdb_readline to get the users
968 permision to continue.
970 Unlike fprintf, this function does not return a value.
972 We implement three variants, vfprintf (takes a vararg list and stream),
973 fprintf (takes a stream to write on), and printf (the usual).
975 Note that this routine has a restriction that the length of the
976 final output line must be less than 255 characters *or* it must be
977 less than twice the size of the format string. This is a very
978 arbitrary restriction, but it is an internal restriction, so I'll
979 put it in. This means that the %s format specifier is almost
980 useless; unless the caller can GUARANTEE that the string is short
981 enough, fputs_filtered should be used instead.
983 Note also that a longjmp to top level may occur in this routine
984 (since prompt_for_continue may do so) so this routine should not be
985 called when cleanups are not in place. */
987 #if !defined(MISSING_VPRINTF) || defined (vsprintf)
990 vfprintf_filtered (stream, format, args)
993 void fprintf_filtered (stream, format, arg1, arg2, arg3, arg4, arg5, arg6)
998 static char *linebuffer = (char *) 0;
999 static int line_size;
1002 format_length = strlen (format);
1004 /* Allocated linebuffer for the first time. */
1007 linebuffer = (char *) xmalloc (255);
1011 /* Reallocate buffer to a larger size if this is necessary. */
1012 if (format_length * 2 > line_size)
1014 line_size = format_length * 2;
1016 /* You don't have to copy. */
1018 linebuffer = (char *) xmalloc (line_size);
1022 /* This won't blow up if the restrictions described above are
1024 #if !defined(MISSING_VPRINTF) || defined (vsprintf)
1025 (void) vsprintf (linebuffer, format, args);
1027 (void) sprintf (linebuffer, format, arg1, arg2, arg3, arg4, arg5, arg6);
1030 fputs_filtered (linebuffer, stream);
1033 #if !defined(MISSING_VPRINTF) || defined (vsprintf)
1036 fprintf_filtered (va_alist)
1044 stream = va_arg (args, FILE *);
1045 format = va_arg (args, char *);
1047 /* This won't blow up if the restrictions described above are
1049 (void) vfprintf_filtered (stream, format, args);
1055 printf_filtered (va_alist)
1062 format = va_arg (args, char *);
1064 (void) vfprintf_filtered (stdout, format, args);
1069 printf_filtered (format, arg1, arg2, arg3, arg4, arg5, arg6)
1071 int arg1, arg2, arg3, arg4, arg5, arg6;
1073 fprintf_filtered (stdout, format, arg1, arg2, arg3, arg4, arg5, arg6);
1080 puts_filtered (string)
1083 fputs_filtered (string, stdout);
1086 /* Return a pointer to N spaces and a null. The pointer is good
1087 until the next call to here. */
1093 static char *spaces;
1094 static int max_spaces;
1100 spaces = malloc (n+1);
1101 for (t = spaces+n; t != spaces;)
1107 return spaces + max_spaces - n;
1110 /* Print N spaces. */
1112 print_spaces_filtered (n, stream)
1116 fputs_filtered (n_spaces (n), stream);
1119 /* C++ demangler stuff. */
1120 char *cplus_demangle ();
1122 /* Print NAME on STREAM, demangling if necessary. */
1124 fprint_symbol (stream, name)
1129 if ((!demangle) || NULL == (demangled = cplus_demangle (name, 1)))
1130 fputs_filtered (name, stream);
1133 fputs_filtered (demangled, stream);
1138 #if !defined (USG_UTILS)
1139 #define USG_UTILS defined (USG)
1143 bcopy (from, to, count)
1146 memcpy (to, from, count);
1149 bcmp (from, to, count)
1151 return (memcmp (to, from, count));
1164 getcwd (buf, MAXPATHLEN);
1172 return strchr (s, c);
1180 return strrchr (s, c);
1182 #endif /* USG_UTILS. */
1184 #if !defined (QUEUE_MISSING)
1185 #define QUEUE_MISSING defined (USG)
1189 /* Queue routines */
1196 insque (item, after)
1198 struct queue *after;
1200 item->forw = after->forw;
1201 after->forw->back = item;
1210 item->forw->back = item->back;
1211 item->back->forw = item->forw;
1213 #endif /* QUEUE_MISSING */
1216 /* Simple implementation of strstr, since some implementations lack it. */
1219 const char *in, *find;
1221 register const char *p = in - 1;
1223 while (0 != (p = strchr (p+1, *find))) {
1224 if (strcmp (p, find))
1229 #endif /* do not HAVE_STRSTR */
1232 _initialize_utils ()
1234 struct cmd_list_element *c;
1236 c = add_set_cmd ("width", class_support, var_uinteger,
1237 (char *)&chars_per_line,
1238 "Set number of characters gdb thinks are in a line.",
1240 add_show_from_set (c, &showlist);
1241 c->function = set_width_command;
1244 (add_set_cmd ("height", class_support,
1245 var_uinteger, (char *)&lines_per_page,
1246 "Set number of lines gdb thinks are in a page.", &setlist),
1249 /* These defaults will be used if we are unable to get the correct
1250 values from termcap. */
1251 lines_per_page = 24;
1252 chars_per_line = 80;
1253 /* Initialize the screen height and width from termcap. */
1255 char *termtype = getenv ("TERM");
1257 /* Positive means success, nonpositive means failure. */
1260 /* 2048 is large enough for all known terminals, according to the
1261 GNU termcap manual. */
1262 char term_buffer[2048];
1266 status = tgetent (term_buffer, termtype);
1271 val = tgetnum ("li");
1273 lines_per_page = val;
1275 /* The number of lines per page is not mentioned
1276 in the terminal description. This probably means
1277 that paging is not useful (e.g. emacs shell window),
1278 so disable paging. */
1279 lines_per_page = UINT_MAX;
1281 val = tgetnum ("co");
1283 chars_per_line = val;
1288 set_width_command ((char *)NULL, 0, c);
1291 (add_set_cmd ("demangle", class_support, var_boolean,
1293 "Set demangling of encoded C++ names when displaying symbols.",
1298 (add_set_cmd ("sevenbit-strings", class_support, var_boolean,
1299 (char *)&sevenbit_strings,
1300 "Set printing of 8-bit characters in strings as \\nnn.",
1305 (add_set_cmd ("asm-demangle", class_support, var_boolean,
1306 (char *)&asm_demangle,
1307 "Set demangling of C++ names in disassembly listings.",