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();
40 /* If this definition isn't overridden by the header files, assume
41 that isatty and fileno exist on this system. */
43 #define ISATTY(FP) (isatty (fileno (FP)))
46 /* Chain of cleanup actions established with make_cleanup,
47 to be executed if an error happens. */
49 static struct cleanup
*cleanup_chain
;
51 /* Nonzero means a quit has been requested. */
55 /* Nonzero means quit immediately if Control-C is typed now,
56 rather than waiting until QUIT is executed. */
60 /* Nonzero means that encoded C++ names should be printed out in their
61 C++ form rather than raw. */
65 /* Nonzero means that encoded C++ names should be printed out in their
66 C++ form even in assembler language displays. If this is set, but
67 DEMANGLE is zero, names are printed raw, i.e. DEMANGLE controls. */
71 /* Nonzero means that strings with character values >0x7F should be printed
72 as octal escapes. Zero means just print the value (e.g. it's an
73 international character, and the terminal or window can cope.) */
75 int sevenbit_strings
= 0;
77 /* String to be printed before error messages, if any. */
79 char *error_pre_print
;
80 char *warning_pre_print
;
82 /* Add a new cleanup to the cleanup_chain,
83 and return the previous chain pointer
84 to be passed later to do_cleanups or discard_cleanups.
85 Args are FUNCTION to clean up with, and ARG to pass to it. */
88 make_cleanup (function
, arg
)
92 register struct cleanup
*new
93 = (struct cleanup
*) xmalloc (sizeof (struct cleanup
));
94 register struct cleanup
*old_chain
= cleanup_chain
;
96 new->next
= cleanup_chain
;
97 new->function
= function
;
104 /* Discard cleanups and do the actions they describe
105 until we get back to the point OLD_CHAIN in the cleanup_chain. */
108 do_cleanups (old_chain
)
109 register struct cleanup
*old_chain
;
111 register struct cleanup
*ptr
;
112 while ((ptr
= cleanup_chain
) != old_chain
)
114 cleanup_chain
= ptr
->next
; /* Do this first incase recursion */
115 (*ptr
->function
) (ptr
->arg
);
120 /* Discard cleanups, not doing the actions they describe,
121 until we get back to the point OLD_CHAIN in the cleanup_chain. */
124 discard_cleanups (old_chain
)
125 register struct cleanup
*old_chain
;
127 register struct cleanup
*ptr
;
128 while ((ptr
= cleanup_chain
) != old_chain
)
130 cleanup_chain
= ptr
->next
;
135 /* Set the cleanup_chain to 0, and return the old cleanup chain. */
139 struct cleanup
*old_chain
= cleanup_chain
;
145 /* Restore the cleanup chain from a previously saved chain. */
147 restore_cleanups (chain
)
148 struct cleanup
*chain
;
150 cleanup_chain
= chain
;
153 /* This function is useful for cleanups.
157 old_chain = make_cleanup (free_current_contents, &foo);
159 to arrange to free the object thus allocated. */
162 free_current_contents (location
)
168 /* Provide a known function that does nothing, to use as a base for
169 for a possibly long chain of cleanups. This is useful where we
170 use the cleanup chain for handling normal cleanups as well as dealing
171 with cleanups that need to be done as a result of a call to error().
172 In such cases, we may not be certain where the first cleanup is, unless
173 we have a do-nothing one to always use as the base. */
183 /* Provide a hook for modules wishing to print their own warning messages
184 to set up the terminal state in a compatible way, without them having
185 to import all the target_<...> macros. */
190 target_terminal_ours ();
191 wrap_here(""); /* Force out any buffered output */
195 /* Print a warning message.
196 The first argument STRING is the warning message, used as a fprintf string,
197 and the remaining args are passed as arguments to it.
198 The primary difference between warnings and errors is that a warning
199 does not force the return to command level. */
210 target_terminal_ours ();
211 wrap_here(""); /* Force out any buffered output */
213 if (warning_pre_print
)
214 fprintf (stderr
, warning_pre_print
);
215 string
= va_arg (args
, char *);
216 vfprintf (stderr
, string
, args
);
217 fprintf (stderr
, "\n");
221 /* Print an error message and return to command level.
222 The first argument STRING is the error message, used as a fprintf string,
223 and the remaining args are passed as arguments to it. */
234 target_terminal_ours ();
235 wrap_here(""); /* Force out any buffered output */
238 fprintf (stderr
, error_pre_print
);
239 string
= va_arg (args
, char *);
240 vfprintf (stderr
, string
, args
);
241 fprintf (stderr
, "\n");
243 return_to_top_level ();
246 /* Print an error message and exit reporting failure.
247 This is for a error that we cannot continue from.
248 The arguments are printed a la printf. */
259 string
= va_arg (args
, char *);
260 fprintf (stderr
, "gdb: ");
261 vfprintf (stderr
, string
, args
);
262 fprintf (stderr
, "\n");
267 /* Print an error message and exit, dumping core.
268 The arguments are printed a la printf (). */
271 fatal_dump_core (va_alist
)
278 string
= va_arg (args
, char *);
279 /* "internal error" is always correct, since GDB should never dump
280 core, no matter what the input. */
281 fprintf (stderr
, "gdb internal error: ");
282 vfprintf (stderr
, string
, args
);
283 fprintf (stderr
, "\n");
286 signal (SIGQUIT
, SIG_DFL
);
287 kill (getpid (), SIGQUIT
);
288 /* We should never get here, but just in case... */
292 /* Memory management stuff (malloc friends). */
294 #if defined (NO_MALLOC_CHECK)
298 #else /* Have mcheck(). */
302 fatal_dump_core ("Memory corruption");
308 mcheck (malloc_botch
);
311 #endif /* Have mcheck(). */
313 /* Like malloc but get error if no storage available. */
325 /* At least one place (dbxread.c:condense_misc_bunches where misc_count == 0)
326 GDB wants to allocate zero bytes. */
330 val
= (char *) malloc (size
);
332 fatal ("virtual memory exhausted.", 0);
336 /* Like realloc but get error if no storage available. */
347 register char *val
= (char *) realloc (ptr
, size
);
349 fatal ("virtual memory exhausted.", 0);
353 /* Print the system error message for errno, and also mention STRING
354 as the file name for which the error was encountered.
355 Then return to command level. */
358 perror_with_name (string
)
362 extern char *sys_errlist
[];
366 if (errno
< sys_nerr
)
367 err
= sys_errlist
[errno
];
369 err
= "unknown error";
371 combined
= (char *) alloca (strlen (err
) + strlen (string
) + 3);
372 strcpy (combined
, string
);
373 strcat (combined
, ": ");
374 strcat (combined
, err
);
376 /* I understand setting these is a matter of taste. Still, some people
377 may clear errno but not know about bfd_error. Doing this here is not
379 bfd_error
= no_error
;
382 error ("%s.", combined
);
385 /* Print the system error message for ERRCODE, and also mention STRING
386 as the file name for which the error was encountered. */
389 print_sys_errmsg (string
, errcode
)
394 extern char *sys_errlist
[];
398 if (errcode
< sys_nerr
)
399 err
= sys_errlist
[errcode
];
401 err
= "unknown error";
403 combined
= (char *) alloca (strlen (err
) + strlen (string
) + 3);
404 strcpy (combined
, string
);
405 strcat (combined
, ": ");
406 strcat (combined
, err
);
408 printf ("%s.\n", combined
);
411 /* Control C eventually causes this to be called, at a convenient time. */
416 target_terminal_ours ();
417 wrap_here ((char *)0); /* Force out any pending output */
419 ioctl (fileno (stdout
), TCFLSH
, 1);
420 #else /* not HAVE_TERMIO */
421 ioctl (fileno (stdout
), TIOCFLUSH
, 0);
422 #endif /* not HAVE_TERMIO */
426 error ("Quit (expect signal %d when inferior is resumed)", SIGINT
);
427 #endif /* TIOCGPGRP */
430 /* Control C comes here */
439 /* Restore the signal handler. */
440 signal (signo
, request_quit
);
447 /* My replacement for the read system call.
448 Used like `read' but keeps going if `read' returns too soon. */
451 myread (desc
, addr
, len
)
461 val
= read (desc
, addr
, len
);
472 /* Make a copy of the string at PTR with SIZE characters
473 (and add a null character at the end in the copy).
474 Uses malloc to get the space. Returns the address of the copy. */
477 savestring (ptr
, size
)
481 register char *p
= (char *) xmalloc (size
+ 1);
482 bcopy (ptr
, p
, size
);
487 /* The "const" is so it compiles under DGUX (which prototypes strsave
488 in <string.h>. FIXME: This should be named "xstrsave", shouldn't it?
489 Doesn't real strsave return NULL if out of memory? */
494 return savestring (ptr
, strlen (ptr
));
498 print_spaces (n
, file
)
506 /* Ask user a y-or-n question and return 1 iff answer is yes.
507 Takes three args which are given to printf to print the question.
508 The first, a control string, should end in "? ".
509 It should not say how to answer, because we do that. */
521 /* Automatically answer "yes" if input is not from a terminal. */
522 if (!input_from_terminal_p ())
528 ctlstr
= va_arg (args
, char *);
529 vfprintf (stdout
, ctlstr
, args
);
531 printf ("(y or n) ");
533 answer
= fgetc (stdin
);
534 clearerr (stdin
); /* in case of C-d */
535 if (answer
== EOF
) /* C-d */
537 if (answer
!= '\n') /* Eat rest of input line, to EOF or newline */
540 ans2
= fgetc (stdin
);
543 while (ans2
!= EOF
&& ans2
!= '\n');
550 printf ("Please answer y or n.\n");
554 /* Parse a C escape sequence. STRING_PTR points to a variable
555 containing a pointer to the string to parse. That pointer
556 should point to the character after the \. That pointer
557 is updated past the characters we use. The value of the
558 escape sequence is returned.
560 A negative value means the sequence \ newline was seen,
561 which is supposed to be equivalent to nothing at all.
563 If \ is followed by a null character, we return a negative
564 value and leave the string pointer pointing at the null character.
566 If \ is followed by 000, we return 0 and leave the string pointer
567 after the zeros. A value of 0 does not mean end of string. */
570 parse_escape (string_ptr
)
573 register int c
= *(*string_ptr
)++;
577 return 007; /* Bell (alert) char */
580 case 'e': /* Escape character */
598 c
= *(*string_ptr
)++;
600 c
= parse_escape (string_ptr
);
603 return (c
& 0200) | (c
& 037);
614 register int i
= c
- '0';
615 register int count
= 0;
618 if ((c
= *(*string_ptr
)++) >= '0' && c
<= '7')
636 /* Print the character C on STREAM as part of the contents
637 of a literal string whose delimiter is QUOTER. */
640 printchar (c
, stream
, quoter
)
646 if (c
< 040 || (sevenbit_strings
&& c
>= 0177)) {
650 fputs_filtered ("\\n", stream
);
653 fputs_filtered ("\\b", stream
);
656 fputs_filtered ("\\t", stream
);
659 fputs_filtered ("\\f", stream
);
662 fputs_filtered ("\\r", stream
);
665 fputs_filtered ("\\e", stream
);
668 fputs_filtered ("\\a", stream
);
671 fprintf_filtered (stream
, "\\%.3o", (unsigned int) c
);
675 if (c
== '\\' || c
== quoter
)
676 fputs_filtered ("\\", stream
);
677 fprintf_filtered (stream
, "%c", c
);
681 /* Number of lines per page or UINT_MAX if paging is disabled. */
682 static unsigned int lines_per_page
;
683 /* Number of chars per line or UNIT_MAX is line folding is disabled. */
684 static unsigned int chars_per_line
;
685 /* Current count of lines printed on this page, chars on this line. */
686 static unsigned int lines_printed
, chars_printed
;
688 /* Buffer and start column of buffered text, for doing smarter word-
689 wrapping. When someone calls wrap_here(), we start buffering output
690 that comes through fputs_filtered(). If we see a newline, we just
691 spit it out and forget about the wrap_here(). If we see another
692 wrap_here(), we spit it out and remember the newer one. If we see
693 the end of the line, we spit out a newline, the indent, and then
696 wrap_column is the column number on the screen where wrap_buffer begins.
697 When wrap_column is zero, wrapping is not in effect.
698 wrap_buffer is malloc'd with chars_per_line+2 bytes.
699 When wrap_buffer[0] is null, the buffer is empty.
700 wrap_pointer points into it at the next character to fill.
701 wrap_indent is the string that should be used as indentation if the
704 static char *wrap_buffer
, *wrap_pointer
, *wrap_indent
;
705 static int wrap_column
;
709 set_width_command (args
, from_tty
, c
)
712 struct cmd_list_element
*c
;
716 wrap_buffer
= (char *) xmalloc (chars_per_line
+ 2);
717 wrap_buffer
[0] = '\0';
720 wrap_buffer
= (char *) xrealloc (wrap_buffer
, chars_per_line
+ 2);
721 wrap_pointer
= wrap_buffer
; /* Start it at the beginning */
725 prompt_for_continue ()
730 ignore
= gdb_readline ("---Type <return> to continue---");
733 chars_printed
= lines_printed
= 0;
735 dont_repeat (); /* Forget prev cmd -- CR won't repeat it. */
738 /* Reinitialize filter; ie. tell it to reset to original values. */
741 reinitialize_more_filter ()
747 /* Indicate that if the next sequence of characters overflows the line,
748 a newline should be inserted here rather than when it hits the end.
749 If INDENT is nonzero, it is a string to be printed to indent the
750 wrapped part on the next line. INDENT must remain accessible until
751 the next call to wrap_here() or until a newline is printed through
754 If the line is already overfull, we immediately print a newline and
755 the indentation, and disable further wrapping.
757 If we don't know the width of lines, but we know the page height,
758 we must not wrap words, but should still keep track of newlines
759 that were explicitly printed.
761 INDENT should not contain tabs, as that
762 will mess up the char count on the next line. FIXME. */
770 *wrap_pointer
= '\0';
771 fputs (wrap_buffer
, stdout
);
773 wrap_pointer
= wrap_buffer
;
774 wrap_buffer
[0] = '\0';
775 if (chars_per_line
== UINT_MAX
) /* No line overflow checking */
779 else if (chars_printed
>= chars_per_line
)
781 puts_filtered ("\n");
782 puts_filtered (indent
);
787 wrap_column
= chars_printed
;
788 wrap_indent
= indent
;
792 /* Like fputs but pause after every screenful, and can wrap at points
793 other than the final character of a line.
794 Unlike fputs, fputs_filtered does not return a value.
795 It is OK for LINEBUFFER to be NULL, in which case just don't print
798 Note that a longjmp to top level may occur in this routine
799 (since prompt_for_continue may do so) so this routine should not be
800 called when cleanups are not in place. */
803 fputs_filtered (linebuffer
, stream
)
804 const char *linebuffer
;
812 /* Don't do any filtering if it is disabled. */
814 || (lines_per_page
== UINT_MAX
&& chars_per_line
== UINT_MAX
))
816 fputs (linebuffer
, stream
);
820 /* Go through and output each character. Show line extension
821 when this is necessary; prompt user for new page when this is
824 lineptr
= linebuffer
;
827 /* Possible new page. */
828 if (lines_printed
>= lines_per_page
- 1)
829 prompt_for_continue ();
831 while (*lineptr
&& *lineptr
!= '\n')
833 /* Print a single line. */
834 if (*lineptr
== '\t')
837 *wrap_pointer
++ = '\t';
840 /* Shifting right by 3 produces the number of tab stops
841 we have already passed, and then adding one and
842 shifting left 3 advances to the next tab stop. */
843 chars_printed
= ((chars_printed
>> 3) + 1) << 3;
849 *wrap_pointer
++ = *lineptr
;
851 putc (*lineptr
, stream
);
856 if (chars_printed
>= chars_per_line
)
858 unsigned int save_chars
= chars_printed
;
862 /* If we aren't actually wrapping, don't output newline --
863 if chars_per_line is right, we probably just overflowed
864 anyway; if it's wrong, let us keep going. */
868 /* Possible new page. */
869 if (lines_printed
>= lines_per_page
- 1)
870 prompt_for_continue ();
872 /* Now output indentation and wrapped string */
876 fputs (wrap_indent
, stream
);
877 *wrap_pointer
= '\0'; /* Null-terminate saved stuff */
878 fputs (wrap_buffer
, stream
); /* and eject it */
879 /* FIXME, this strlen is what prevents wrap_indent from
880 containing tabs. However, if we recurse to print it
881 and count its chars, we risk trouble if wrap_indent is
882 longer than (the user settable) chars_per_line.
883 Note also that this can set chars_printed > chars_per_line
884 if we are printing a long string. */
885 chars_printed
= strlen (wrap_indent
)
886 + (save_chars
- wrap_column
);
887 wrap_pointer
= wrap_buffer
; /* Reset buffer */
888 wrap_buffer
[0] = '\0';
889 wrap_column
= 0; /* And disable fancy wrap */
894 if (*lineptr
== '\n')
897 wrap_here ((char *)0); /* Spit out chars, cancel further wraps */
906 /* fputs_demangled is a variant of fputs_filtered that
907 demangles g++ names.*/
910 fputs_demangled (linebuffer
, stream
, arg_mode
)
916 extern char *cplus_demangle (const char *, int);
918 extern char *cplus_demangle ();
920 #define SYMBOL_MAX 1024
922 #define SYMBOL_CHAR(c) (isascii(c) \
923 && (isalnum(c) || (c) == '_' || (c) == CPLUS_MARKER))
925 char buf
[SYMBOL_MAX
+1];
926 # define SLOP 5 /* How much room to leave in buf */
929 if (linebuffer
== NULL
)
932 /* If user wants to see raw output, no problem. */
934 fputs_filtered (linebuffer
, stream
);
940 while ( *p
!= (char) 0 ) {
943 /* collect non-interesting characters into buf */
944 while ( *p
!= (char) 0 && !SYMBOL_CHAR(*p
) && i
< (int)sizeof(buf
)-SLOP
) {
949 /* output the non-interesting characters without demangling */
951 fputs_filtered(buf
, stream
);
952 i
= 0; /* reset buf */
955 /* and now the interesting characters */
956 while (i
< SYMBOL_MAX
959 && i
< (int)sizeof(buf
) - SLOP
) {
967 if ( (result
= cplus_demangle(buf
, arg_mode
)) != NULL
) {
968 fputs_filtered(result
, stream
);
972 fputs_filtered(buf
, stream
);
978 /* Print a variable number of ARGS using format FORMAT. If this
979 information is going to put the amount written (since the last call
980 to INITIALIZE_MORE_FILTER or the last page break) over the page size,
981 print out a pause message and do a gdb_readline to get the users
982 permision to continue.
984 Unlike fprintf, this function does not return a value.
986 We implement three variants, vfprintf (takes a vararg list and stream),
987 fprintf (takes a stream to write on), and printf (the usual).
989 Note that this routine has a restriction that the length of the
990 final output line must be less than 255 characters *or* it must be
991 less than twice the size of the format string. This is a very
992 arbitrary restriction, but it is an internal restriction, so I'll
993 put it in. This means that the %s format specifier is almost
994 useless; unless the caller can GUARANTEE that the string is short
995 enough, fputs_filtered should be used instead.
997 Note also that a longjmp to top level may occur in this routine
998 (since prompt_for_continue may do so) so this routine should not be
999 called when cleanups are not in place. */
1003 vfprintf_filtered (stream
, format
, args
)
1008 static char *linebuffer
= (char *) 0;
1009 static int line_size
;
1012 format_length
= strlen (format
);
1014 /* Allocated linebuffer for the first time. */
1017 linebuffer
= (char *) xmalloc (255);
1021 /* Reallocate buffer to a larger size if this is necessary. */
1022 if (format_length
* 2 > line_size
)
1024 line_size
= format_length
* 2;
1026 /* You don't have to copy. */
1028 linebuffer
= (char *) xmalloc (line_size
);
1032 /* This won't blow up if the restrictions described above are
1034 (void) vsprintf (linebuffer
, format
, args
);
1036 fputs_filtered (linebuffer
, stream
);
1041 fprintf_filtered (va_alist
)
1049 stream
= va_arg (args
, FILE *);
1050 format
= va_arg (args
, char *);
1052 /* This won't blow up if the restrictions described above are
1054 (void) vfprintf_filtered (stream
, format
, args
);
1060 printf_filtered (va_alist
)
1067 format
= va_arg (args
, char *);
1069 (void) vfprintf_filtered (stdout
, format
, args
);
1076 puts_filtered (string
)
1079 fputs_filtered (string
, stdout
);
1082 /* Return a pointer to N spaces and a null. The pointer is good
1083 until the next call to here. */
1089 static char *spaces
;
1090 static int max_spaces
;
1096 spaces
= malloc (n
+1);
1097 for (t
= spaces
+n
; t
!= spaces
;)
1103 return spaces
+ max_spaces
- n
;
1106 /* Print N spaces. */
1108 print_spaces_filtered (n
, stream
)
1112 fputs_filtered (n_spaces (n
), stream
);
1115 /* C++ demangler stuff. */
1116 char *cplus_demangle ();
1118 /* Print NAME on STREAM, demangling if necessary. */
1120 fprint_symbol (stream
, name
)
1125 if ((!demangle
) || NULL
== (demangled
= cplus_demangle (name
, 1)))
1126 fputs_filtered (name
, stream
);
1129 fputs_filtered (demangled
, stream
);
1135 _initialize_utils ()
1137 struct cmd_list_element
*c
;
1139 c
= add_set_cmd ("width", class_support
, var_uinteger
,
1140 (char *)&chars_per_line
,
1141 "Set number of characters gdb thinks are in a line.",
1143 add_show_from_set (c
, &showlist
);
1144 c
->function
= set_width_command
;
1147 (add_set_cmd ("height", class_support
,
1148 var_uinteger
, (char *)&lines_per_page
,
1149 "Set number of lines gdb thinks are in a page.", &setlist
),
1152 /* These defaults will be used if we are unable to get the correct
1153 values from termcap. */
1154 lines_per_page
= 24;
1155 chars_per_line
= 80;
1156 /* Initialize the screen height and width from termcap. */
1158 char *termtype
= getenv ("TERM");
1160 /* Positive means success, nonpositive means failure. */
1163 /* 2048 is large enough for all known terminals, according to the
1164 GNU termcap manual. */
1165 char term_buffer
[2048];
1169 status
= tgetent (term_buffer
, termtype
);
1174 val
= tgetnum ("li");
1176 lines_per_page
= val
;
1178 /* The number of lines per page is not mentioned
1179 in the terminal description. This probably means
1180 that paging is not useful (e.g. emacs shell window),
1181 so disable paging. */
1182 lines_per_page
= UINT_MAX
;
1184 val
= tgetnum ("co");
1186 chars_per_line
= val
;
1191 /* If the output is not a terminal, don't paginate it. */
1192 if (!ISATTY (stdout
))
1193 lines_per_page
= UINT_MAX
;
1195 set_width_command ((char *)NULL
, 0, c
);
1198 (add_set_cmd ("demangle", class_support
, var_boolean
,
1200 "Set demangling of encoded C++ names when displaying symbols.",
1205 (add_set_cmd ("sevenbit-strings", class_support
, var_boolean
,
1206 (char *)&sevenbit_strings
,
1207 "Set printing of 8-bit characters in strings as \\nnn.",
1212 (add_set_cmd ("asm-demangle", class_support
, var_boolean
,
1213 (char *)&asm_demangle
,
1214 "Set demangling of C++ names in disassembly listings.",