Remove local BSD/USG hacks that are now in libiberty.
[external/binutils.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 "param.h"
30 #include "signals.h"
31 #include "gdbcmd.h"
32 #include "terminal.h"
33 #include "bfd.h"
34 #include "target.h"
35
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();
42
43 /* If this definition isn't overridden by the header files, assume
44    that isatty and fileno exist on this system.  */
45 #ifndef ISATTY
46 #define ISATTY(FP)      (isatty (fileno (FP)))
47 #endif
48
49 #ifdef MISSING_VPRINTF
50 #ifdef __GNU_LIBRARY
51 #undef MISSING_VPRINTF
52 #else  /* !__GNU_LIBRARY */
53
54 #ifndef vfprintf
55 /* Can't #define it since language.c needs it (though FIXME it shouldn't) */
56 void
57 vfprintf (file, format, ap)
58      FILE *file;
59      char *format;
60      va_list ap;
61 {
62   _doprnt (format, ap, file);
63 }
64 #endif /* vfprintf */
65
66 #ifndef vprintf
67 /* Can't #define it since printcmd.c needs it */
68 void
69 vprintf (format, ap)
70      char *format;
71      va_list ap;
72 {
73   vfprintf (stdout, format, ap);
74 }
75 #endif /* vprintf */
76
77 #endif /* GNU_LIBRARY */
78 #endif /* MISSING_VPRINTF */
79
80 void error ();
81 void fatal ();
82
83 /* Chain of cleanup actions established with make_cleanup,
84    to be executed if an error happens.  */
85
86 static struct cleanup *cleanup_chain;
87
88 /* Nonzero means a quit has been requested.  */
89
90 int quit_flag;
91
92 /* Nonzero means quit immediately if Control-C is typed now,
93    rather than waiting until QUIT is executed.  */
94
95 int immediate_quit;
96
97 /* Nonzero means that encoded C++ names should be printed out in their
98    C++ form rather than raw.  */
99
100 int demangle = 1;
101
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.  */
105
106 int asm_demangle = 0;
107
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.)  */
111
112 int sevenbit_strings = 0;
113
114 /* String to be printed before error messages, if any.  */
115
116 char *error_pre_print;
117 char *warning_pre_print;
118 \f
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.  */
123
124 struct cleanup *
125 make_cleanup (function, arg)
126      void (*function) ();
127      int arg;
128 {
129   register struct cleanup *new
130     = (struct cleanup *) xmalloc (sizeof (struct cleanup));
131   register struct cleanup *old_chain = cleanup_chain;
132
133   new->next = cleanup_chain;
134   new->function = function;
135   new->arg = arg;
136   cleanup_chain = new;
137
138   return old_chain;
139 }
140
141 /* Discard cleanups and do the actions they describe
142    until we get back to the point OLD_CHAIN in the cleanup_chain.  */
143
144 void
145 do_cleanups (old_chain)
146      register struct cleanup *old_chain;
147 {
148   register struct cleanup *ptr;
149   while ((ptr = cleanup_chain) != old_chain)
150     {
151       cleanup_chain = ptr->next;        /* Do this first incase recursion */
152       (*ptr->function) (ptr->arg);
153       free (ptr);
154     }
155 }
156
157 /* Discard cleanups, not doing the actions they describe,
158    until we get back to the point OLD_CHAIN in the cleanup_chain.  */
159
160 void
161 discard_cleanups (old_chain)
162      register struct cleanup *old_chain;
163 {
164   register struct cleanup *ptr;
165   while ((ptr = cleanup_chain) != old_chain)
166     {
167       cleanup_chain = ptr->next;
168       free (ptr);
169     }
170 }
171
172 /* Set the cleanup_chain to 0, and return the old cleanup chain.  */
173 struct cleanup *
174 save_cleanups ()
175 {
176   struct cleanup *old_chain = cleanup_chain;
177
178   cleanup_chain = 0;
179   return old_chain;
180 }
181
182 /* Restore the cleanup chain from a previously saved chain.  */
183 void
184 restore_cleanups (chain)
185      struct cleanup *chain;
186 {
187   cleanup_chain = chain;
188 }
189
190 /* This function is useful for cleanups.
191    Do
192
193      foo = xmalloc (...);
194      old_chain = make_cleanup (free_current_contents, &foo);
195
196    to arrange to free the object thus allocated.  */
197
198 void
199 free_current_contents (location)
200      char **location;
201 {
202   free (*location);
203 }
204 \f
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. */
208
209 void
210 warning_setup ()
211 {
212   target_terminal_ours ();
213   wrap_here("");                        /* Force out any buffered output */
214   fflush (stdout);
215 }
216
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. */
222
223 /* VARARGS */
224 void
225 warning (va_alist)
226      va_dcl
227 {
228   va_list args;
229   char *string;
230
231   va_start (args);
232   target_terminal_ours ();
233   wrap_here("");                        /* Force out any buffered output */
234   fflush (stdout);
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");
240   va_end (args);
241 }
242
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.  */
246
247 /* VARARGS */
248 void
249 error (va_alist)
250      va_dcl
251 {
252   va_list args;
253   char *string;
254
255   va_start (args);
256   target_terminal_ours ();
257   wrap_here("");                        /* Force out any buffered output */
258   fflush (stdout);
259   if (error_pre_print)
260     fprintf (stderr, error_pre_print);
261   string = va_arg (args, char *);
262   vfprintf (stderr, string, args);
263   fprintf (stderr, "\n");
264   va_end (args);
265   return_to_top_level ();
266 }
267
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.  */
271
272 /* VARARGS */
273 void
274 fatal (va_alist)
275      va_dcl
276 {
277   va_list args;
278   char *string;
279
280   va_start (args);
281   string = va_arg (args, char *);
282   fprintf (stderr, "gdb: ");
283   vfprintf (stderr, string, args);
284   fprintf (stderr, "\n");
285   va_end (args);
286   exit (1);
287 }
288
289 /* Print an error message and exit, dumping core.
290    The arguments are printed a la printf ().  */
291 /* VARARGS */
292 void
293 fatal_dump_core (va_alist)
294      va_dcl
295 {
296   va_list args;
297   char *string;
298
299   va_start (args);
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");
306   va_end (args);
307
308   signal (SIGQUIT, SIG_DFL);
309   kill (getpid (), SIGQUIT);
310   /* We should never get here, but just in case...  */
311   exit (1);
312 }
313 \f
314 /* Memory management stuff (malloc friends).  */
315
316 #if defined (NO_MALLOC_CHECK)
317 void
318 init_malloc ()
319 {}
320 #else /* Have mcheck().  */
321 static void
322 malloc_botch ()
323 {
324   fatal_dump_core ("Memory corruption");
325 }
326
327 void
328 init_malloc ()
329 {
330   mcheck (malloc_botch);
331   mtrace ();
332 }
333 #endif /* Have mcheck().  */
334
335 /* Like malloc but get error if no storage available.  */
336
337 #ifdef __STDC__
338 void *
339 #else
340 char *
341 #endif
342 xmalloc (size)
343      long size;
344 {
345   register char *val;
346
347   /* At least one place (dbxread.c:condense_misc_bunches where misc_count == 0)
348      GDB wants to allocate zero bytes.  */
349   if (size == 0)
350     return NULL;
351   
352   val = (char *) malloc (size);
353   if (!val)
354     fatal ("virtual memory exhausted.", 0);
355   return val;
356 }
357
358 /* Like realloc but get error if no storage available.  */
359
360 #ifdef __STDC__
361 void *
362 #else
363 char *
364 #endif
365 xrealloc (ptr, size)
366      char *ptr;
367      long size;
368 {
369   register char *val = (char *) realloc (ptr, size);
370   if (!val)
371     fatal ("virtual memory exhausted.", 0);
372   return val;
373 }
374
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.  */
378
379 void
380 perror_with_name (string)
381      char *string;
382 {
383   extern int sys_nerr;
384   extern char *sys_errlist[];
385   char *err;
386   char *combined;
387
388   if (errno < sys_nerr)
389     err = sys_errlist[errno];
390   else
391     err = "unknown error";
392
393   combined = (char *) alloca (strlen (err) + strlen (string) + 3);
394   strcpy (combined, string);
395   strcat (combined, ": ");
396   strcat (combined, err);
397
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
400      unreasonable. */
401   bfd_error = no_error;
402   errno = 0;
403
404   error ("%s.", combined);
405 }
406
407 /* Print the system error message for ERRCODE, and also mention STRING
408    as the file name for which the error was encountered.  */
409
410 void
411 print_sys_errmsg (string, errcode)
412      char *string;
413      int errcode;
414 {
415   extern int sys_nerr;
416   extern char *sys_errlist[];
417   char *err;
418   char *combined;
419
420   if (errcode < sys_nerr)
421     err = sys_errlist[errcode];
422   else
423     err = "unknown error";
424
425   combined = (char *) alloca (strlen (err) + strlen (string) + 3);
426   strcpy (combined, string);
427   strcat (combined, ": ");
428   strcat (combined, err);
429
430   printf ("%s.\n", combined);
431 }
432
433 /* Control C eventually causes this to be called, at a convenient time.  */
434
435 void
436 quit ()
437 {
438   target_terminal_ours ();
439   wrap_here ((char *)0);                /* Force out any pending output */
440 #ifdef HAVE_TERMIO
441   ioctl (fileno (stdout), TCFLSH, 1);
442 #else /* not HAVE_TERMIO */
443   ioctl (fileno (stdout), TIOCFLUSH, 0);
444 #endif /* not HAVE_TERMIO */
445 #ifdef TIOCGPGRP
446   error ("Quit");
447 #else
448   error ("Quit (expect signal %d when inferior is resumed)", SIGINT);
449 #endif /* TIOCGPGRP */
450 }
451
452 /* Control C comes here */
453
454 void
455 request_quit ()
456 {
457   quit_flag = 1;
458
459 #ifdef USG
460   /* Restore the signal handler.  */
461   signal (SIGINT, request_quit);
462 #endif
463
464   if (immediate_quit)
465     quit ();
466 }
467 \f
468 /* My replacement for the read system call.
469    Used like `read' but keeps going if `read' returns too soon.  */
470
471 int
472 myread (desc, addr, len)
473      int desc;
474      char *addr;
475      int len;
476 {
477   register int val;
478   int orglen = len;
479
480   while (len > 0)
481     {
482       val = read (desc, addr, len);
483       if (val < 0)
484         return val;
485       if (val == 0)
486         return orglen - len;
487       len -= val;
488       addr += val;
489     }
490   return orglen;
491 }
492 \f
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.  */
496
497 char *
498 savestring (ptr, size)
499      char *ptr;
500      int size;
501 {
502   register char *p = (char *) xmalloc (size + 1);
503   bcopy (ptr, p, size);
504   p[size] = 0;
505   return p;
506 }
507
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?  */
511 char *
512 strsave (ptr)
513      const char *ptr;
514 {
515   return savestring (ptr, strlen (ptr));
516 }
517
518 char *
519 concat (s1, s2, s3)
520      char *s1, *s2, *s3;
521 {
522   register int len = strlen (s1) + strlen (s2) + strlen (s3) + 1;
523   register char *val = (char *) xmalloc (len);
524   strcpy (val, s1);
525   strcat (val, s2);
526   strcat (val, s3);
527   return val;
528 }
529
530 void
531 print_spaces (n, file)
532      register int n;
533      register FILE *file;
534 {
535   while (n-- > 0)
536     fputc (' ', file);
537 }
538
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.  */
543
544 /* VARARGS */
545 int
546 query (va_alist)
547      va_dcl
548 {
549   va_list args;
550   char *ctlstr;
551   register int answer;
552   register int ans2;
553
554   /* Automatically answer "yes" if input is not from a terminal.  */
555   if (!input_from_terminal_p ())
556     return 1;
557
558   while (1)
559     {
560       va_start (args);
561       ctlstr = va_arg (args, char *);
562       vfprintf (stdout, ctlstr, args);
563       va_end (args);
564       printf ("(y or n) ");
565       fflush (stdout);
566       answer = fgetc (stdin);
567       clearerr (stdin);         /* in case of C-d */
568       if (answer == EOF)        /* C-d */
569         return 1;
570       if (answer != '\n')       /* Eat rest of input line, to EOF or newline */
571         do 
572           {
573             ans2 = fgetc (stdin);
574             clearerr (stdin);
575           }
576         while (ans2 != EOF && ans2 != '\n');
577       if (answer >= 'a')
578         answer -= 040;
579       if (answer == 'Y')
580         return 1;
581       if (answer == 'N')
582         return 0;
583       printf ("Please answer y or n.\n");
584     }
585 }
586 \f
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.
592
593    A negative value means the sequence \ newline was seen,
594    which is supposed to be equivalent to nothing at all.
595
596    If \ is followed by a null character, we return a negative
597    value and leave the string pointer pointing at the null character.
598
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.  */
601
602 int
603 parse_escape (string_ptr)
604      char **string_ptr;
605 {
606   register int c = *(*string_ptr)++;
607   switch (c)
608     {
609     case 'a':
610       return 007;               /* Bell (alert) char */
611     case 'b':
612       return '\b';
613     case 'e':                   /* Escape character */
614       return 033;
615     case 'f':
616       return '\f';
617     case 'n':
618       return '\n';
619     case 'r':
620       return '\r';
621     case 't':
622       return '\t';
623     case 'v':
624       return '\v';
625     case '\n':
626       return -2;
627     case 0:
628       (*string_ptr)--;
629       return 0;
630     case '^':
631       c = *(*string_ptr)++;
632       if (c == '\\')
633         c = parse_escape (string_ptr);
634       if (c == '?')
635         return 0177;
636       return (c & 0200) | (c & 037);
637       
638     case '0':
639     case '1':
640     case '2':
641     case '3':
642     case '4':
643     case '5':
644     case '6':
645     case '7':
646       {
647         register int i = c - '0';
648         register int count = 0;
649         while (++count < 3)
650           {
651             if ((c = *(*string_ptr)++) >= '0' && c <= '7')
652               {
653                 i *= 8;
654                 i += c - '0';
655               }
656             else
657               {
658                 (*string_ptr)--;
659                 break;
660               }
661           }
662         return i;
663       }
664     default:
665       return c;
666     }
667 }
668 \f
669 /* Print the character CH on STREAM as part of the contents
670    of a literal string whose delimiter is QUOTER.  */
671
672 void
673 printchar (ch, stream, quoter)
674      unsigned char ch;
675      FILE *stream;
676      int quoter;
677 {
678   register int c = ch;
679
680   if (c < 040 || (sevenbit_strings && c >= 0177)) {
681     switch (c)
682       {
683       case '\n':
684         fputs_filtered ("\\n", stream);
685         break;
686       case '\b':
687         fputs_filtered ("\\b", stream);
688         break;
689       case '\t':
690         fputs_filtered ("\\t", stream);
691         break;
692       case '\f':
693         fputs_filtered ("\\f", stream);
694         break;
695       case '\r':
696         fputs_filtered ("\\r", stream);
697         break;
698       case '\033':
699         fputs_filtered ("\\e", stream);
700         break;
701       case '\007':
702         fputs_filtered ("\\a", stream);
703         break;
704       default:
705         fprintf_filtered (stream, "\\%.3o", (unsigned int) c);
706         break;
707       }
708   } else {
709     if (c == '\\' || c == quoter)
710       fputs_filtered ("\\", stream);
711     fprintf_filtered (stream, "%c", c);
712   }
713 }
714 \f
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;
721
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
728    the buffered output.
729
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
736      wrap occurs.  */
737
738 static char *wrap_buffer, *wrap_pointer, *wrap_indent;
739 static int wrap_column;
740
741 /* ARGSUSED */
742 static void 
743 set_width_command (args, from_tty, c)
744      char *args;
745      int from_tty;
746      struct cmd_list_element *c;
747 {
748   if (!wrap_buffer)
749     {
750       wrap_buffer = (char *) xmalloc (chars_per_line + 2);
751       wrap_buffer[0] = '\0';
752     }
753   else
754     wrap_buffer = (char *) xrealloc (wrap_buffer, chars_per_line + 2);
755   wrap_pointer = wrap_buffer;   /* Start it at the beginning */
756 }
757
758 static void
759 prompt_for_continue ()
760 {
761   char *ignore;
762
763   immediate_quit++;
764   ignore = gdb_readline ("---Type <return> to continue---");
765   if (ignore)
766     free (ignore);
767   chars_printed = lines_printed = 0;
768   immediate_quit--;
769   dont_repeat ();               /* Forget prev cmd -- CR won't repeat it. */
770 }
771
772 /* Reinitialize filter; ie. tell it to reset to original values.  */
773
774 void
775 reinitialize_more_filter ()
776 {
777   lines_printed = 0;
778   chars_printed = 0;
779 }
780
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
786    fputs_filtered().
787
788    If the line is already overfull, we immediately print a newline and
789    the indentation, and disable further wrapping.
790
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.
794
795    INDENT should not contain tabs, as that
796    will mess up the char count on the next line.  FIXME.  */
797
798 void
799 wrap_here(indent)
800   char *indent;
801 {
802   if (wrap_buffer[0])
803     {
804       *wrap_pointer = '\0';
805       fputs (wrap_buffer, stdout);
806     }
807   wrap_pointer = wrap_buffer;
808   wrap_buffer[0] = '\0';
809   if (chars_per_line == UINT_MAX)               /* No line overflow checking */
810     {
811       wrap_column = 0;
812     }
813   else if (chars_printed >= chars_per_line)
814     {
815       puts_filtered ("\n");
816       puts_filtered (indent);
817       wrap_column = 0;
818     }
819   else
820     {
821       wrap_column = chars_printed;
822       wrap_indent = indent;
823     }
824 }
825
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
830    anything.
831
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.  */
835
836 void
837 fputs_filtered (linebuffer, stream)
838      char *linebuffer;
839      FILE *stream;
840 {
841   char *lineptr;
842
843   if (linebuffer == 0)
844     return;
845   
846   /* Don't do any filtering if it is disabled.  */
847   if (stream != stdout
848    || (lines_per_page == UINT_MAX && chars_per_line == UINT_MAX))
849     {
850       fputs (linebuffer, stream);
851       return;
852     }
853
854   /* Go through and output each character.  Show line extension
855      when this is necessary; prompt user for new page when this is
856      necessary.  */
857   
858   lineptr = linebuffer;
859   while (*lineptr)
860     {
861       /* Possible new page.  */
862       if (lines_printed >= lines_per_page - 1)
863         prompt_for_continue ();
864
865       while (*lineptr && *lineptr != '\n')
866         {
867           /* Print a single line.  */
868           if (*lineptr == '\t')
869             {
870               if (wrap_column)
871                 *wrap_pointer++ = '\t';
872               else
873                 putc ('\t', stream);
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;
878               lineptr++;
879             }
880           else
881             {
882               if (wrap_column)
883                 *wrap_pointer++ = *lineptr;
884               else
885                 putc (*lineptr, stream);
886               chars_printed++;
887               lineptr++;
888             }
889       
890           if (chars_printed >= chars_per_line)
891             {
892               unsigned int save_chars = chars_printed;
893
894               chars_printed = 0;
895               lines_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.  */
899               if (wrap_column)
900                 putc ('\n', stream);
901
902               /* Possible new page.  */
903               if (lines_printed >= lines_per_page - 1)
904                 prompt_for_continue ();
905
906               /* Now output indentation and wrapped string */
907               if (wrap_column)
908                 {
909                   if (wrap_indent)
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 */
924                 }
925             }
926         }
927
928       if (*lineptr == '\n')
929         {
930           chars_printed = 0;
931           wrap_here ((char *)0);  /* Spit out chars, cancel further wraps */
932           lines_printed++;
933           putc ('\n', stream);
934           lineptr++;
935         }
936     }
937 }
938
939
940 /* fputs_demangled is a variant of fputs_filtered that
941    demangles g++ names.*/
942
943 void
944 fputs_demangled (linebuffer, stream, arg_mode)
945      char *linebuffer;
946      FILE *stream;
947      int arg_mode;
948 {
949 #ifdef __STDC__
950   extern char *cplus_demangle (const char *, int);
951 #else
952   extern char *cplus_demangle ();
953 #endif
954 #define SYMBOL_MAX 1024
955
956 #define SYMBOL_CHAR(c) (isascii(c) \
957   && (isalnum(c) || (c) == '_' || (c) == CPLUS_MARKER))
958
959   char buf[SYMBOL_MAX+1];
960 # define SLOP 5         /* How much room to leave in buf */
961   char *p;
962
963   if (linebuffer == NULL)
964     return;
965
966   /* If user wants to see raw output, no problem.  */
967   if (!demangle) {
968     fputs_filtered (linebuffer, stream);
969     return;
970   }
971
972   p = linebuffer;
973
974   while ( *p != (char) 0 ) {
975     int i = 0;
976
977     /* collect non-interesting characters into buf */
978     while ( *p != (char) 0 && !SYMBOL_CHAR(*p) && i < (int)sizeof(buf)-SLOP ) {
979       buf[i++] = *p;
980       p++;
981     }
982     if (i > 0) {
983       /* output the non-interesting characters without demangling */
984       buf[i] = (char) 0;
985       fputs_filtered(buf, stream);
986       i = 0;  /* reset buf */
987     }
988
989     /* and now the interesting characters */
990     while (i < SYMBOL_MAX
991      && *p != (char) 0
992      && SYMBOL_CHAR(*p)
993      && i < (int)sizeof(buf) - SLOP) {
994       buf[i++] = *p;
995       p++;
996     }
997     buf[i] = (char) 0;
998     if (i > 0) {
999       char * result;
1000       
1001       if ( (result = cplus_demangle(buf, arg_mode)) != NULL ) {
1002         fputs_filtered(result, stream);
1003         free(result);
1004       }
1005       else {
1006         fputs_filtered(buf, stream);
1007       }
1008     }
1009   }
1010 }
1011
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.
1017
1018    Unlike fprintf, this function does not return a value.
1019
1020    We implement three variants, vfprintf (takes a vararg list and stream),
1021    fprintf (takes a stream to write on), and printf (the usual).
1022
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.
1030
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.  */
1034
1035 #if !defined(MISSING_VPRINTF) || defined (vsprintf)
1036 /* VARARGS */
1037 void
1038 vfprintf_filtered (stream, format, args)
1039      va_list args;
1040 #else
1041 void fprintf_filtered (stream, format, arg1, arg2, arg3, arg4, arg5, arg6)
1042 #endif
1043      FILE *stream;
1044      char *format;
1045 {
1046   static char *linebuffer = (char *) 0;
1047   static int line_size;
1048   int format_length;
1049
1050   format_length = strlen (format);
1051
1052   /* Allocated linebuffer for the first time.  */
1053   if (!linebuffer)
1054     {
1055       linebuffer = (char *) xmalloc (255);
1056       line_size = 255;
1057     }
1058
1059   /* Reallocate buffer to a larger size if this is necessary.  */
1060   if (format_length * 2 > line_size)
1061     {
1062       line_size = format_length * 2;
1063
1064       /* You don't have to copy.  */
1065       free (linebuffer);
1066       linebuffer = (char *) xmalloc (line_size);
1067     }
1068
1069
1070   /* This won't blow up if the restrictions described above are
1071      followed.   */
1072 #if !defined(MISSING_VPRINTF) || defined (vsprintf)
1073   (void) vsprintf (linebuffer, format, args);
1074 #else
1075   (void) sprintf (linebuffer, format, arg1, arg2, arg3, arg4, arg5, arg6);
1076 #endif
1077
1078   fputs_filtered (linebuffer, stream);
1079 }
1080
1081 #if !defined(MISSING_VPRINTF) || defined (vsprintf)
1082 /* VARARGS */
1083 void
1084 fprintf_filtered (va_alist)
1085      va_dcl
1086 {
1087   va_list args;
1088   FILE *stream;
1089   char *format;
1090
1091   va_start (args);
1092   stream = va_arg (args, FILE *);
1093   format = va_arg (args, char *);
1094
1095   /* This won't blow up if the restrictions described above are
1096      followed.   */
1097   (void) vfprintf_filtered (stream, format, args);
1098   va_end (args);
1099 }
1100
1101 /* VARARGS */
1102 void
1103 printf_filtered (va_alist)
1104      va_dcl
1105 {
1106   va_list args;
1107   char *format;
1108
1109   va_start (args);
1110   format = va_arg (args, char *);
1111
1112   (void) vfprintf_filtered (stdout, format, args);
1113   va_end (args);
1114 }
1115 #else
1116 void
1117 printf_filtered (format, arg1, arg2, arg3, arg4, arg5, arg6)
1118      char *format;
1119      int arg1, arg2, arg3, arg4, arg5, arg6;
1120 {
1121   fprintf_filtered (stdout, format, arg1, arg2, arg3, arg4, arg5, arg6);
1122 }
1123 #endif
1124
1125 /* Easy */
1126
1127 void
1128 puts_filtered (string)
1129      char *string;
1130 {
1131   fputs_filtered (string, stdout);
1132 }
1133
1134 /* Return a pointer to N spaces and a null.  The pointer is good
1135    until the next call to here.  */
1136 char *
1137 n_spaces (n)
1138      int n;
1139 {
1140   register char *t;
1141   static char *spaces;
1142   static int max_spaces;
1143
1144   if (n > max_spaces)
1145     {
1146       if (spaces)
1147         free (spaces);
1148       spaces = malloc (n+1);
1149       for (t = spaces+n; t != spaces;)
1150         *--t = ' ';
1151       spaces[n] = '\0';
1152       max_spaces = n;
1153     }
1154
1155   return spaces + max_spaces - n;
1156 }
1157
1158 /* Print N spaces.  */
1159 void
1160 print_spaces_filtered (n, stream)
1161      int n;
1162      FILE *stream;
1163 {
1164   fputs_filtered (n_spaces (n), stream);
1165 }
1166 \f
1167 /* C++ demangler stuff.  */
1168 char *cplus_demangle ();
1169
1170 /* Print NAME on STREAM, demangling if necessary.  */
1171 void
1172 fprint_symbol (stream, name)
1173      FILE *stream;
1174      char *name;
1175 {
1176   char *demangled;
1177   if ((!demangle) || NULL == (demangled = cplus_demangle (name, 1)))
1178     fputs_filtered (name, stream);
1179   else
1180     {
1181       fputs_filtered (demangled, stream);
1182       free (demangled);
1183     }
1184 }
1185 \f
1186 void
1187 _initialize_utils ()
1188 {
1189   struct cmd_list_element *c;
1190
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.",
1194                   &setlist);
1195   add_show_from_set (c, &showlist);
1196   c->function = set_width_command;
1197
1198   add_show_from_set
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),
1202      &showlist);
1203   
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.  */
1209   {
1210     char *termtype = getenv ("TERM");
1211
1212     /* Positive means success, nonpositive means failure.  */
1213     int status;
1214
1215     /* 2048 is large enough for all known terminals, according to the
1216        GNU termcap manual.  */
1217     char term_buffer[2048];
1218
1219     if (termtype)
1220       {
1221         status = tgetent (term_buffer, termtype);
1222         if (status > 0)
1223           {
1224             int val;
1225             
1226             val = tgetnum ("li");
1227             if (val >= 0)
1228               lines_per_page = val;
1229             else
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;
1235             
1236             val = tgetnum ("co");
1237             if (val >= 0)
1238               chars_per_line = val;
1239           }
1240       }
1241   }
1242
1243   /* If the output is not a terminal, don't paginate it.  */
1244   if (!ISATTY (stdout))
1245     lines_per_page = UINT_MAX;
1246
1247   set_width_command ((char *)NULL, 0, c);
1248
1249   add_show_from_set
1250     (add_set_cmd ("demangle", class_support, var_boolean, 
1251                   (char *)&demangle,
1252                 "Set demangling of encoded C++ names when displaying symbols.",
1253                   &setprintlist),
1254      &showprintlist);
1255
1256   add_show_from_set
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.",
1260                   &setprintlist),
1261      &showprintlist);
1262
1263   add_show_from_set
1264     (add_set_cmd ("asm-demangle", class_support, var_boolean, 
1265                   (char *)&asm_demangle,
1266         "Set demangling of C++ names in disassembly listings.",
1267                   &setprintlist),
1268      &showprintlist);
1269 }