* defs.h: Include ansidecl.h and PARAMS macro. Use PARAMS
[binutils-gdb.git] / gdb / utils.c
1 /* General utility routines for GDB, the GNU debugger.
2 Copyright (C) 1986, 1989, 1990, 1991 Free Software Foundation, Inc.
3
4 This file is part of GDB.
5
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.
10
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.
15
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. */
19
20 #include <stdio.h>
21 #include <sys/ioctl.h>
22 #include <sys/param.h>
23 #include <pwd.h>
24 #include <varargs.h>
25 #include <ctype.h>
26 #include <string.h>
27
28 #include "defs.h"
29 #include "signals.h"
30 #include "gdbcmd.h"
31 #include "terminal.h"
32 #include "bfd.h"
33 #include "target.h"
34
35 extern volatile void return_to_top_level ();
36 extern volatile void exit ();
37 extern char *gdb_readline ();
38 extern char *getenv();
39
40 /* If this definition isn't overridden by the header files, assume
41 that isatty and fileno exist on this system. */
42 #ifndef ISATTY
43 #define ISATTY(FP) (isatty (fileno (FP)))
44 #endif
45
46 /* Chain of cleanup actions established with make_cleanup,
47 to be executed if an error happens. */
48
49 static struct cleanup *cleanup_chain;
50
51 /* Nonzero means a quit has been requested. */
52
53 int quit_flag;
54
55 /* Nonzero means quit immediately if Control-C is typed now,
56 rather than waiting until QUIT is executed. */
57
58 int immediate_quit;
59
60 /* Nonzero means that encoded C++ names should be printed out in their
61 C++ form rather than raw. */
62
63 int demangle = 1;
64
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. */
68
69 int asm_demangle = 0;
70
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.) */
74
75 int sevenbit_strings = 0;
76
77 /* String to be printed before error messages, if any. */
78
79 char *error_pre_print;
80 char *warning_pre_print;
81 \f
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. */
86
87 struct cleanup *
88 make_cleanup (function, arg)
89 void (*function) ();
90 int arg;
91 {
92 register struct cleanup *new
93 = (struct cleanup *) xmalloc (sizeof (struct cleanup));
94 register struct cleanup *old_chain = cleanup_chain;
95
96 new->next = cleanup_chain;
97 new->function = function;
98 new->arg = arg;
99 cleanup_chain = new;
100
101 return old_chain;
102 }
103
104 /* Discard cleanups and do the actions they describe
105 until we get back to the point OLD_CHAIN in the cleanup_chain. */
106
107 void
108 do_cleanups (old_chain)
109 register struct cleanup *old_chain;
110 {
111 register struct cleanup *ptr;
112 while ((ptr = cleanup_chain) != old_chain)
113 {
114 cleanup_chain = ptr->next; /* Do this first incase recursion */
115 (*ptr->function) (ptr->arg);
116 free (ptr);
117 }
118 }
119
120 /* Discard cleanups, not doing the actions they describe,
121 until we get back to the point OLD_CHAIN in the cleanup_chain. */
122
123 void
124 discard_cleanups (old_chain)
125 register struct cleanup *old_chain;
126 {
127 register struct cleanup *ptr;
128 while ((ptr = cleanup_chain) != old_chain)
129 {
130 cleanup_chain = ptr->next;
131 free (ptr);
132 }
133 }
134
135 /* Set the cleanup_chain to 0, and return the old cleanup chain. */
136 struct cleanup *
137 save_cleanups ()
138 {
139 struct cleanup *old_chain = cleanup_chain;
140
141 cleanup_chain = 0;
142 return old_chain;
143 }
144
145 /* Restore the cleanup chain from a previously saved chain. */
146 void
147 restore_cleanups (chain)
148 struct cleanup *chain;
149 {
150 cleanup_chain = chain;
151 }
152
153 /* This function is useful for cleanups.
154 Do
155
156 foo = xmalloc (...);
157 old_chain = make_cleanup (free_current_contents, &foo);
158
159 to arrange to free the object thus allocated. */
160
161 void
162 free_current_contents (location)
163 char **location;
164 {
165 free (*location);
166 }
167
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. */
174
175 /* ARGSUSED */
176 void
177 null_cleanup (arg)
178 char **arg;
179 {
180 }
181
182 \f
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. */
186
187 void
188 warning_setup ()
189 {
190 target_terminal_ours ();
191 wrap_here(""); /* Force out any buffered output */
192 fflush (stdout);
193 }
194
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. */
200
201 /* VARARGS */
202 void
203 warning (va_alist)
204 va_dcl
205 {
206 va_list args;
207 char *string;
208
209 va_start (args);
210 target_terminal_ours ();
211 wrap_here(""); /* Force out any buffered output */
212 fflush (stdout);
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");
218 va_end (args);
219 }
220
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. */
224
225 /* VARARGS */
226 volatile void
227 error (va_alist)
228 va_dcl
229 {
230 va_list args;
231 char *string;
232
233 va_start (args);
234 target_terminal_ours ();
235 wrap_here(""); /* Force out any buffered output */
236 fflush (stdout);
237 if (error_pre_print)
238 fprintf (stderr, error_pre_print);
239 string = va_arg (args, char *);
240 vfprintf (stderr, string, args);
241 fprintf (stderr, "\n");
242 va_end (args);
243 return_to_top_level ();
244 }
245
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. */
249
250 /* VARARGS */
251 volatile void
252 fatal (va_alist)
253 va_dcl
254 {
255 va_list args;
256 char *string;
257
258 va_start (args);
259 string = va_arg (args, char *);
260 fprintf (stderr, "gdb: ");
261 vfprintf (stderr, string, args);
262 fprintf (stderr, "\n");
263 va_end (args);
264 exit (1);
265 }
266
267 /* Print an error message and exit, dumping core.
268 The arguments are printed a la printf (). */
269 /* VARARGS */
270 void
271 fatal_dump_core (va_alist)
272 va_dcl
273 {
274 va_list args;
275 char *string;
276
277 va_start (args);
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");
284 va_end (args);
285
286 signal (SIGQUIT, SIG_DFL);
287 kill (getpid (), SIGQUIT);
288 /* We should never get here, but just in case... */
289 exit (1);
290 }
291 \f
292 /* Memory management stuff (malloc friends). */
293
294 #if defined (NO_MALLOC_CHECK)
295 void
296 init_malloc ()
297 {}
298 #else /* Have mcheck(). */
299 static void
300 malloc_botch ()
301 {
302 fatal_dump_core ("Memory corruption");
303 }
304
305 void
306 init_malloc ()
307 {
308 mcheck (malloc_botch);
309 mtrace ();
310 }
311 #endif /* Have mcheck(). */
312
313 /* Like malloc but get error if no storage available. */
314
315 #ifdef __STDC__
316 void *
317 #else
318 char *
319 #endif
320 xmalloc (size)
321 long size;
322 {
323 register char *val;
324
325 /* At least one place (dbxread.c:condense_misc_bunches where misc_count == 0)
326 GDB wants to allocate zero bytes. */
327 if (size == 0)
328 return NULL;
329
330 val = (char *) malloc (size);
331 if (!val)
332 fatal ("virtual memory exhausted.", 0);
333 return val;
334 }
335
336 /* Like realloc but get error if no storage available. */
337
338 #ifdef __STDC__
339 void *
340 #else
341 char *
342 #endif
343 xrealloc (ptr, size)
344 char *ptr;
345 long size;
346 {
347 register char *val = (char *) realloc (ptr, size);
348 if (!val)
349 fatal ("virtual memory exhausted.", 0);
350 return val;
351 }
352
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. */
356
357 void
358 perror_with_name (string)
359 char *string;
360 {
361 extern int sys_nerr;
362 extern char *sys_errlist[];
363 char *err;
364 char *combined;
365
366 if (errno < sys_nerr)
367 err = sys_errlist[errno];
368 else
369 err = "unknown error";
370
371 combined = (char *) alloca (strlen (err) + strlen (string) + 3);
372 strcpy (combined, string);
373 strcat (combined, ": ");
374 strcat (combined, err);
375
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
378 unreasonable. */
379 bfd_error = no_error;
380 errno = 0;
381
382 error ("%s.", combined);
383 }
384
385 /* Print the system error message for ERRCODE, and also mention STRING
386 as the file name for which the error was encountered. */
387
388 void
389 print_sys_errmsg (string, errcode)
390 char *string;
391 int errcode;
392 {
393 extern int sys_nerr;
394 extern char *sys_errlist[];
395 char *err;
396 char *combined;
397
398 if (errcode < sys_nerr)
399 err = sys_errlist[errcode];
400 else
401 err = "unknown error";
402
403 combined = (char *) alloca (strlen (err) + strlen (string) + 3);
404 strcpy (combined, string);
405 strcat (combined, ": ");
406 strcat (combined, err);
407
408 printf ("%s.\n", combined);
409 }
410
411 /* Control C eventually causes this to be called, at a convenient time. */
412
413 void
414 quit ()
415 {
416 target_terminal_ours ();
417 wrap_here ((char *)0); /* Force out any pending output */
418 #ifdef HAVE_TERMIO
419 ioctl (fileno (stdout), TCFLSH, 1);
420 #else /* not HAVE_TERMIO */
421 ioctl (fileno (stdout), TIOCFLUSH, 0);
422 #endif /* not HAVE_TERMIO */
423 #ifdef TIOCGPGRP
424 error ("Quit");
425 #else
426 error ("Quit (expect signal %d when inferior is resumed)", SIGINT);
427 #endif /* TIOCGPGRP */
428 }
429
430 /* Control C comes here */
431
432 void
433 request_quit (signo)
434 int signo;
435 {
436 quit_flag = 1;
437
438 #ifdef USG
439 /* Restore the signal handler. */
440 signal (signo, request_quit);
441 #endif
442
443 if (immediate_quit)
444 quit ();
445 }
446 \f
447 /* My replacement for the read system call.
448 Used like `read' but keeps going if `read' returns too soon. */
449
450 int
451 myread (desc, addr, len)
452 int desc;
453 char *addr;
454 int len;
455 {
456 register int val;
457 int orglen = len;
458
459 while (len > 0)
460 {
461 val = read (desc, addr, len);
462 if (val < 0)
463 return val;
464 if (val == 0)
465 return orglen - len;
466 len -= val;
467 addr += val;
468 }
469 return orglen;
470 }
471 \f
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. */
475
476 char *
477 savestring (ptr, size)
478 const char *ptr;
479 int size;
480 {
481 register char *p = (char *) xmalloc (size + 1);
482 bcopy (ptr, p, size);
483 p[size] = 0;
484 return p;
485 }
486
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? */
490 char *
491 strsave (ptr)
492 const char *ptr;
493 {
494 return savestring (ptr, strlen (ptr));
495 }
496
497 void
498 print_spaces (n, file)
499 register int n;
500 register FILE *file;
501 {
502 while (n-- > 0)
503 fputc (' ', file);
504 }
505
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. */
510
511 /* VARARGS */
512 int
513 query (va_alist)
514 va_dcl
515 {
516 va_list args;
517 char *ctlstr;
518 register int answer;
519 register int ans2;
520
521 /* Automatically answer "yes" if input is not from a terminal. */
522 if (!input_from_terminal_p ())
523 return 1;
524
525 while (1)
526 {
527 va_start (args);
528 ctlstr = va_arg (args, char *);
529 vfprintf (stdout, ctlstr, args);
530 va_end (args);
531 printf ("(y or n) ");
532 fflush (stdout);
533 answer = fgetc (stdin);
534 clearerr (stdin); /* in case of C-d */
535 if (answer == EOF) /* C-d */
536 return 1;
537 if (answer != '\n') /* Eat rest of input line, to EOF or newline */
538 do
539 {
540 ans2 = fgetc (stdin);
541 clearerr (stdin);
542 }
543 while (ans2 != EOF && ans2 != '\n');
544 if (answer >= 'a')
545 answer -= 040;
546 if (answer == 'Y')
547 return 1;
548 if (answer == 'N')
549 return 0;
550 printf ("Please answer y or n.\n");
551 }
552 }
553 \f
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.
559
560 A negative value means the sequence \ newline was seen,
561 which is supposed to be equivalent to nothing at all.
562
563 If \ is followed by a null character, we return a negative
564 value and leave the string pointer pointing at the null character.
565
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. */
568
569 int
570 parse_escape (string_ptr)
571 char **string_ptr;
572 {
573 register int c = *(*string_ptr)++;
574 switch (c)
575 {
576 case 'a':
577 return 007; /* Bell (alert) char */
578 case 'b':
579 return '\b';
580 case 'e': /* Escape character */
581 return 033;
582 case 'f':
583 return '\f';
584 case 'n':
585 return '\n';
586 case 'r':
587 return '\r';
588 case 't':
589 return '\t';
590 case 'v':
591 return '\v';
592 case '\n':
593 return -2;
594 case 0:
595 (*string_ptr)--;
596 return 0;
597 case '^':
598 c = *(*string_ptr)++;
599 if (c == '\\')
600 c = parse_escape (string_ptr);
601 if (c == '?')
602 return 0177;
603 return (c & 0200) | (c & 037);
604
605 case '0':
606 case '1':
607 case '2':
608 case '3':
609 case '4':
610 case '5':
611 case '6':
612 case '7':
613 {
614 register int i = c - '0';
615 register int count = 0;
616 while (++count < 3)
617 {
618 if ((c = *(*string_ptr)++) >= '0' && c <= '7')
619 {
620 i *= 8;
621 i += c - '0';
622 }
623 else
624 {
625 (*string_ptr)--;
626 break;
627 }
628 }
629 return i;
630 }
631 default:
632 return c;
633 }
634 }
635 \f
636 /* Print the character C on STREAM as part of the contents
637 of a literal string whose delimiter is QUOTER. */
638
639 void
640 printchar (c, stream, quoter)
641 register int c;
642 FILE *stream;
643 int quoter;
644 {
645
646 if (c < 040 || (sevenbit_strings && c >= 0177)) {
647 switch (c)
648 {
649 case '\n':
650 fputs_filtered ("\\n", stream);
651 break;
652 case '\b':
653 fputs_filtered ("\\b", stream);
654 break;
655 case '\t':
656 fputs_filtered ("\\t", stream);
657 break;
658 case '\f':
659 fputs_filtered ("\\f", stream);
660 break;
661 case '\r':
662 fputs_filtered ("\\r", stream);
663 break;
664 case '\033':
665 fputs_filtered ("\\e", stream);
666 break;
667 case '\007':
668 fputs_filtered ("\\a", stream);
669 break;
670 default:
671 fprintf_filtered (stream, "\\%.3o", (unsigned int) c);
672 break;
673 }
674 } else {
675 if (c == '\\' || c == quoter)
676 fputs_filtered ("\\", stream);
677 fprintf_filtered (stream, "%c", c);
678 }
679 }
680 \f
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;
687
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
694 the buffered output.
695
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
702 wrap occurs. */
703
704 static char *wrap_buffer, *wrap_pointer, *wrap_indent;
705 static int wrap_column;
706
707 /* ARGSUSED */
708 static void
709 set_width_command (args, from_tty, c)
710 char *args;
711 int from_tty;
712 struct cmd_list_element *c;
713 {
714 if (!wrap_buffer)
715 {
716 wrap_buffer = (char *) xmalloc (chars_per_line + 2);
717 wrap_buffer[0] = '\0';
718 }
719 else
720 wrap_buffer = (char *) xrealloc (wrap_buffer, chars_per_line + 2);
721 wrap_pointer = wrap_buffer; /* Start it at the beginning */
722 }
723
724 static void
725 prompt_for_continue ()
726 {
727 char *ignore;
728
729 immediate_quit++;
730 ignore = gdb_readline ("---Type <return> to continue---");
731 if (ignore)
732 free (ignore);
733 chars_printed = lines_printed = 0;
734 immediate_quit--;
735 dont_repeat (); /* Forget prev cmd -- CR won't repeat it. */
736 }
737
738 /* Reinitialize filter; ie. tell it to reset to original values. */
739
740 void
741 reinitialize_more_filter ()
742 {
743 lines_printed = 0;
744 chars_printed = 0;
745 }
746
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
752 fputs_filtered().
753
754 If the line is already overfull, we immediately print a newline and
755 the indentation, and disable further wrapping.
756
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.
760
761 INDENT should not contain tabs, as that
762 will mess up the char count on the next line. FIXME. */
763
764 void
765 wrap_here(indent)
766 char *indent;
767 {
768 if (wrap_buffer[0])
769 {
770 *wrap_pointer = '\0';
771 fputs (wrap_buffer, stdout);
772 }
773 wrap_pointer = wrap_buffer;
774 wrap_buffer[0] = '\0';
775 if (chars_per_line == UINT_MAX) /* No line overflow checking */
776 {
777 wrap_column = 0;
778 }
779 else if (chars_printed >= chars_per_line)
780 {
781 puts_filtered ("\n");
782 puts_filtered (indent);
783 wrap_column = 0;
784 }
785 else
786 {
787 wrap_column = chars_printed;
788 wrap_indent = indent;
789 }
790 }
791
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
796 anything.
797
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. */
801
802 void
803 fputs_filtered (linebuffer, stream)
804 const char *linebuffer;
805 FILE *stream;
806 {
807 char *lineptr;
808
809 if (linebuffer == 0)
810 return;
811
812 /* Don't do any filtering if it is disabled. */
813 if (stream != stdout
814 || (lines_per_page == UINT_MAX && chars_per_line == UINT_MAX))
815 {
816 fputs (linebuffer, stream);
817 return;
818 }
819
820 /* Go through and output each character. Show line extension
821 when this is necessary; prompt user for new page when this is
822 necessary. */
823
824 lineptr = linebuffer;
825 while (*lineptr)
826 {
827 /* Possible new page. */
828 if (lines_printed >= lines_per_page - 1)
829 prompt_for_continue ();
830
831 while (*lineptr && *lineptr != '\n')
832 {
833 /* Print a single line. */
834 if (*lineptr == '\t')
835 {
836 if (wrap_column)
837 *wrap_pointer++ = '\t';
838 else
839 putc ('\t', stream);
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;
844 lineptr++;
845 }
846 else
847 {
848 if (wrap_column)
849 *wrap_pointer++ = *lineptr;
850 else
851 putc (*lineptr, stream);
852 chars_printed++;
853 lineptr++;
854 }
855
856 if (chars_printed >= chars_per_line)
857 {
858 unsigned int save_chars = chars_printed;
859
860 chars_printed = 0;
861 lines_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. */
865 if (wrap_column)
866 putc ('\n', stream);
867
868 /* Possible new page. */
869 if (lines_printed >= lines_per_page - 1)
870 prompt_for_continue ();
871
872 /* Now output indentation and wrapped string */
873 if (wrap_column)
874 {
875 if (wrap_indent)
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 */
890 }
891 }
892 }
893
894 if (*lineptr == '\n')
895 {
896 chars_printed = 0;
897 wrap_here ((char *)0); /* Spit out chars, cancel further wraps */
898 lines_printed++;
899 putc ('\n', stream);
900 lineptr++;
901 }
902 }
903 }
904
905
906 /* fputs_demangled is a variant of fputs_filtered that
907 demangles g++ names.*/
908
909 void
910 fputs_demangled (linebuffer, stream, arg_mode)
911 char *linebuffer;
912 FILE *stream;
913 int arg_mode;
914 {
915 #ifdef __STDC__
916 extern char *cplus_demangle (const char *, int);
917 #else
918 extern char *cplus_demangle ();
919 #endif
920 #define SYMBOL_MAX 1024
921
922 #define SYMBOL_CHAR(c) (isascii(c) \
923 && (isalnum(c) || (c) == '_' || (c) == CPLUS_MARKER))
924
925 char buf[SYMBOL_MAX+1];
926 # define SLOP 5 /* How much room to leave in buf */
927 char *p;
928
929 if (linebuffer == NULL)
930 return;
931
932 /* If user wants to see raw output, no problem. */
933 if (!demangle) {
934 fputs_filtered (linebuffer, stream);
935 return;
936 }
937
938 p = linebuffer;
939
940 while ( *p != (char) 0 ) {
941 int i = 0;
942
943 /* collect non-interesting characters into buf */
944 while ( *p != (char) 0 && !SYMBOL_CHAR(*p) && i < (int)sizeof(buf)-SLOP ) {
945 buf[i++] = *p;
946 p++;
947 }
948 if (i > 0) {
949 /* output the non-interesting characters without demangling */
950 buf[i] = (char) 0;
951 fputs_filtered(buf, stream);
952 i = 0; /* reset buf */
953 }
954
955 /* and now the interesting characters */
956 while (i < SYMBOL_MAX
957 && *p != (char) 0
958 && SYMBOL_CHAR(*p)
959 && i < (int)sizeof(buf) - SLOP) {
960 buf[i++] = *p;
961 p++;
962 }
963 buf[i] = (char) 0;
964 if (i > 0) {
965 char * result;
966
967 if ( (result = cplus_demangle(buf, arg_mode)) != NULL ) {
968 fputs_filtered(result, stream);
969 free(result);
970 }
971 else {
972 fputs_filtered(buf, stream);
973 }
974 }
975 }
976 }
977
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.
983
984 Unlike fprintf, this function does not return a value.
985
986 We implement three variants, vfprintf (takes a vararg list and stream),
987 fprintf (takes a stream to write on), and printf (the usual).
988
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.
996
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. */
1000
1001 /* VARARGS */
1002 void
1003 vfprintf_filtered (stream, format, args)
1004 va_list args;
1005 FILE *stream;
1006 char *format;
1007 {
1008 static char *linebuffer = (char *) 0;
1009 static int line_size;
1010 int format_length;
1011
1012 format_length = strlen (format);
1013
1014 /* Allocated linebuffer for the first time. */
1015 if (!linebuffer)
1016 {
1017 linebuffer = (char *) xmalloc (255);
1018 line_size = 255;
1019 }
1020
1021 /* Reallocate buffer to a larger size if this is necessary. */
1022 if (format_length * 2 > line_size)
1023 {
1024 line_size = format_length * 2;
1025
1026 /* You don't have to copy. */
1027 free (linebuffer);
1028 linebuffer = (char *) xmalloc (line_size);
1029 }
1030
1031
1032 /* This won't blow up if the restrictions described above are
1033 followed. */
1034 (void) vsprintf (linebuffer, format, args);
1035
1036 fputs_filtered (linebuffer, stream);
1037 }
1038
1039 /* VARARGS */
1040 void
1041 fprintf_filtered (va_alist)
1042 va_dcl
1043 {
1044 va_list args;
1045 FILE *stream;
1046 char *format;
1047
1048 va_start (args);
1049 stream = va_arg (args, FILE *);
1050 format = va_arg (args, char *);
1051
1052 /* This won't blow up if the restrictions described above are
1053 followed. */
1054 (void) vfprintf_filtered (stream, format, args);
1055 va_end (args);
1056 }
1057
1058 /* VARARGS */
1059 void
1060 printf_filtered (va_alist)
1061 va_dcl
1062 {
1063 va_list args;
1064 char *format;
1065
1066 va_start (args);
1067 format = va_arg (args, char *);
1068
1069 (void) vfprintf_filtered (stdout, format, args);
1070 va_end (args);
1071 }
1072
1073 /* Easy */
1074
1075 void
1076 puts_filtered (string)
1077 char *string;
1078 {
1079 fputs_filtered (string, stdout);
1080 }
1081
1082 /* Return a pointer to N spaces and a null. The pointer is good
1083 until the next call to here. */
1084 char *
1085 n_spaces (n)
1086 int n;
1087 {
1088 register char *t;
1089 static char *spaces;
1090 static int max_spaces;
1091
1092 if (n > max_spaces)
1093 {
1094 if (spaces)
1095 free (spaces);
1096 spaces = malloc (n+1);
1097 for (t = spaces+n; t != spaces;)
1098 *--t = ' ';
1099 spaces[n] = '\0';
1100 max_spaces = n;
1101 }
1102
1103 return spaces + max_spaces - n;
1104 }
1105
1106 /* Print N spaces. */
1107 void
1108 print_spaces_filtered (n, stream)
1109 int n;
1110 FILE *stream;
1111 {
1112 fputs_filtered (n_spaces (n), stream);
1113 }
1114 \f
1115 /* C++ demangler stuff. */
1116 char *cplus_demangle ();
1117
1118 /* Print NAME on STREAM, demangling if necessary. */
1119 void
1120 fprint_symbol (stream, name)
1121 FILE *stream;
1122 char *name;
1123 {
1124 char *demangled;
1125 if ((!demangle) || NULL == (demangled = cplus_demangle (name, 1)))
1126 fputs_filtered (name, stream);
1127 else
1128 {
1129 fputs_filtered (demangled, stream);
1130 free (demangled);
1131 }
1132 }
1133 \f
1134 void
1135 _initialize_utils ()
1136 {
1137 struct cmd_list_element *c;
1138
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.",
1142 &setlist);
1143 add_show_from_set (c, &showlist);
1144 c->function = set_width_command;
1145
1146 add_show_from_set
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),
1150 &showlist);
1151
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. */
1157 {
1158 char *termtype = getenv ("TERM");
1159
1160 /* Positive means success, nonpositive means failure. */
1161 int status;
1162
1163 /* 2048 is large enough for all known terminals, according to the
1164 GNU termcap manual. */
1165 char term_buffer[2048];
1166
1167 if (termtype)
1168 {
1169 status = tgetent (term_buffer, termtype);
1170 if (status > 0)
1171 {
1172 int val;
1173
1174 val = tgetnum ("li");
1175 if (val >= 0)
1176 lines_per_page = val;
1177 else
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;
1183
1184 val = tgetnum ("co");
1185 if (val >= 0)
1186 chars_per_line = val;
1187 }
1188 }
1189 }
1190
1191 /* If the output is not a terminal, don't paginate it. */
1192 if (!ISATTY (stdout))
1193 lines_per_page = UINT_MAX;
1194
1195 set_width_command ((char *)NULL, 0, c);
1196
1197 add_show_from_set
1198 (add_set_cmd ("demangle", class_support, var_boolean,
1199 (char *)&demangle,
1200 "Set demangling of encoded C++ names when displaying symbols.",
1201 &setprintlist),
1202 &showprintlist);
1203
1204 add_show_from_set
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.",
1208 &setprintlist),
1209 &showprintlist);
1210
1211 add_show_from_set
1212 (add_set_cmd ("asm-demangle", class_support, var_boolean,
1213 (char *)&asm_demangle,
1214 "Set demangling of C++ names in disassembly listings.",
1215 &setprintlist),
1216 &showprintlist);
1217 }