]> Git Repo - binutils.git/blob - gdb/utils.c
* infrun.c (child_attach): Don't allow gdb to attach to itself.
[binutils.git] / gdb / utils.c
1 /* General utility routines for GDB, the GNU debugger.
2    Copyright 1986, 1989, 1990, 1991, 1992 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 "defs.h"
21
22 #include <sys/ioctl.h>
23 #include <sys/param.h>
24 #include <pwd.h>
25 #include <varargs.h>
26 #include <ctype.h>
27 #include <string.h>
28
29 #include "signals.h"
30 #include "gdbcmd.h"
31 #include "terminal.h"
32 #include "bfd.h"
33 #include "target.h"
34 #include "demangle.h"
35
36 /* Prototypes for local functions */
37
38 #if !defined (NO_MALLOC_CHECK)
39
40 static void
41 malloc_botch PARAMS ((void));
42
43 #endif /* NO_MALLOC_CHECK  */
44
45 static void
46 fatal_dump_core ();     /* Can't prototype with <varargs.h> usage... */
47
48 static void
49 prompt_for_continue PARAMS ((void));
50
51 static void 
52 set_width_command PARAMS ((char *, int, struct cmd_list_element *));
53
54 static void
55 vfprintf_filtered PARAMS ((FILE *, char *, va_list));
56
57 /* If this definition isn't overridden by the header files, assume
58    that isatty and fileno exist on this system.  */
59 #ifndef ISATTY
60 #define ISATTY(FP)      (isatty (fileno (FP)))
61 #endif
62
63 /* Chain of cleanup actions established with make_cleanup,
64    to be executed if an error happens.  */
65
66 static struct cleanup *cleanup_chain;
67
68 /* Nonzero means a quit has been requested.  */
69
70 int quit_flag;
71
72 /* Nonzero means quit immediately if Control-C is typed now,
73    rather than waiting until QUIT is executed.  */
74
75 int immediate_quit;
76
77 /* Nonzero means that encoded C++ names should be printed out in their
78    C++ form rather than raw.  */
79
80 int demangle = 1;
81
82 /* Nonzero means that encoded C++ names should be printed out in their
83    C++ form even in assembler language displays.  If this is set, but
84    DEMANGLE is zero, names are printed raw, i.e. DEMANGLE controls.  */
85
86 int asm_demangle = 0;
87
88 /* Nonzero means that strings with character values >0x7F should be printed
89    as octal escapes.  Zero means just print the value (e.g. it's an
90    international character, and the terminal or window can cope.)  */
91
92 int sevenbit_strings = 0;
93
94 /* String to be printed before error messages, if any.  */
95
96 char *error_pre_print;
97 char *warning_pre_print = "\nwarning: ";
98 \f
99 /* Add a new cleanup to the cleanup_chain,
100    and return the previous chain pointer
101    to be passed later to do_cleanups or discard_cleanups.
102    Args are FUNCTION to clean up with, and ARG to pass to it.  */
103
104 struct cleanup *
105 make_cleanup (function, arg)
106      void (*function) PARAMS ((PTR));
107      PTR arg;
108 {
109   register struct cleanup *new
110     = (struct cleanup *) xmalloc (sizeof (struct cleanup));
111   register struct cleanup *old_chain = cleanup_chain;
112
113   new->next = cleanup_chain;
114   new->function = function;
115   new->arg = arg;
116   cleanup_chain = new;
117
118   return old_chain;
119 }
120
121 /* Discard cleanups and do the actions they describe
122    until we get back to the point OLD_CHAIN in the cleanup_chain.  */
123
124 void
125 do_cleanups (old_chain)
126      register struct cleanup *old_chain;
127 {
128   register struct cleanup *ptr;
129   while ((ptr = cleanup_chain) != old_chain)
130     {
131       cleanup_chain = ptr->next;        /* Do this first incase recursion */
132       (*ptr->function) (ptr->arg);
133       free (ptr);
134     }
135 }
136
137 /* Discard cleanups, not doing the actions they describe,
138    until we get back to the point OLD_CHAIN in the cleanup_chain.  */
139
140 void
141 discard_cleanups (old_chain)
142      register struct cleanup *old_chain;
143 {
144   register struct cleanup *ptr;
145   while ((ptr = cleanup_chain) != old_chain)
146     {
147       cleanup_chain = ptr->next;
148       free ((PTR)ptr);
149     }
150 }
151
152 /* Set the cleanup_chain to 0, and return the old cleanup chain.  */
153 struct cleanup *
154 save_cleanups ()
155 {
156   struct cleanup *old_chain = cleanup_chain;
157
158   cleanup_chain = 0;
159   return old_chain;
160 }
161
162 /* Restore the cleanup chain from a previously saved chain.  */
163 void
164 restore_cleanups (chain)
165      struct cleanup *chain;
166 {
167   cleanup_chain = chain;
168 }
169
170 /* This function is useful for cleanups.
171    Do
172
173      foo = xmalloc (...);
174      old_chain = make_cleanup (free_current_contents, &foo);
175
176    to arrange to free the object thus allocated.  */
177
178 void
179 free_current_contents (location)
180      char **location;
181 {
182   free (*location);
183 }
184
185 /* Provide a known function that does nothing, to use as a base for
186    for a possibly long chain of cleanups.  This is useful where we
187    use the cleanup chain for handling normal cleanups as well as dealing
188    with cleanups that need to be done as a result of a call to error().
189    In such cases, we may not be certain where the first cleanup is, unless
190    we have a do-nothing one to always use as the base. */
191
192 /* ARGSUSED */
193 void
194 null_cleanup (arg)
195     char **arg;
196 {
197 }
198
199 \f
200 /* Provide a hook for modules wishing to print their own warning messages
201    to set up the terminal state in a compatible way, without them having
202    to import all the target_<...> macros. */
203
204 void
205 warning_setup ()
206 {
207   target_terminal_ours ();
208   wrap_here("");                        /* Force out any buffered output */
209   fflush (stdout);
210 }
211
212 /* Print a warning message.
213    The first argument STRING is the warning message, used as a fprintf string,
214    and the remaining args are passed as arguments to it.
215    The primary difference between warnings and errors is that a warning
216    does not force the return to command level. */
217
218 /* VARARGS */
219 void
220 warning (va_alist)
221      va_dcl
222 {
223   va_list args;
224   char *string;
225
226   va_start (args);
227   target_terminal_ours ();
228   wrap_here("");                        /* Force out any buffered output */
229   fflush (stdout);
230   if (warning_pre_print)
231     fprintf (stderr, warning_pre_print);
232   string = va_arg (args, char *);
233   vfprintf (stderr, string, args);
234   fprintf (stderr, "\n");
235   va_end (args);
236 }
237
238 /* Print an error message and return to command level.
239    The first argument STRING is the error message, used as a fprintf string,
240    and the remaining args are passed as arguments to it.  */
241
242 /* VARARGS */
243 NORETURN void
244 error (va_alist)
245      va_dcl
246 {
247   va_list args;
248   char *string;
249
250   va_start (args);
251   target_terminal_ours ();
252   wrap_here("");                        /* Force out any buffered output */
253   fflush (stdout);
254   if (error_pre_print)
255     fprintf_filtered (stderr, error_pre_print);
256   string = va_arg (args, char *);
257   vfprintf_filtered (stderr, string, args);
258   fprintf_filtered (stderr, "\n");
259   va_end (args);
260   return_to_top_level ();
261 }
262
263 /* Print an error message and exit reporting failure.
264    This is for a error that we cannot continue from.
265    The arguments are printed a la printf.
266
267    This function cannot be declared volatile (NORETURN) in an
268    ANSI environment because exit() is not declared volatile. */
269
270 /* VARARGS */
271 NORETURN void
272 fatal (va_alist)
273      va_dcl
274 {
275   va_list args;
276   char *string;
277
278   va_start (args);
279   string = va_arg (args, char *);
280   fprintf (stderr, "\ngdb: ");
281   vfprintf (stderr, string, args);
282   fprintf (stderr, "\n");
283   va_end (args);
284   exit (1);
285 }
286
287 /* Print an error message and exit, dumping core.
288    The arguments are printed a la printf ().  */
289
290 /* VARARGS */
291 static void
292 fatal_dump_core (va_alist)
293      va_dcl
294 {
295   va_list args;
296   char *string;
297
298   va_start (args);
299   string = va_arg (args, char *);
300   /* "internal error" is always correct, since GDB should never dump
301      core, no matter what the input.  */
302   fprintf (stderr, "\ngdb internal error: ");
303   vfprintf (stderr, string, args);
304   fprintf (stderr, "\n");
305   va_end (args);
306
307   signal (SIGQUIT, SIG_DFL);
308   kill (getpid (), SIGQUIT);
309   /* We should never get here, but just in case...  */
310   exit (1);
311 }
312
313 /* The strerror() function can return NULL for errno values that are
314    out of range.  Provide a "safe" version that always returns a
315    printable string. */
316
317 char *
318 safe_strerror (errnum)
319      int errnum;
320 {
321   char *msg;
322   static char buf[32];
323
324   if ((msg = strerror (errnum)) == NULL)
325     {
326       sprintf (buf, "(undocumented errno %d)", errnum);
327       msg = buf;
328     }
329   return (msg);
330 }
331
332 /* The strsignal() function can return NULL for signal values that are
333    out of range.  Provide a "safe" version that always returns a
334    printable string. */
335
336 char *
337 safe_strsignal (signo)
338      int signo;
339 {
340   char *msg;
341   static char buf[32];
342
343   if ((msg = strsignal (signo)) == NULL)
344     {
345       sprintf (buf, "(undocumented signal %d)", signo);
346       msg = buf;
347     }
348   return (msg);
349 }
350
351
352 /* Print the system error message for errno, and also mention STRING
353    as the file name for which the error was encountered.
354    Then return to command level.  */
355
356 void
357 perror_with_name (string)
358      char *string;
359 {
360   char *err;
361   char *combined;
362
363   err = safe_strerror (errno);
364   combined = (char *) alloca (strlen (err) + strlen (string) + 3);
365   strcpy (combined, string);
366   strcat (combined, ": ");
367   strcat (combined, err);
368
369   /* I understand setting these is a matter of taste.  Still, some people
370      may clear errno but not know about bfd_error.  Doing this here is not
371      unreasonable. */
372   bfd_error = no_error;
373   errno = 0;
374
375   error ("%s.", combined);
376 }
377
378 /* Print the system error message for ERRCODE, and also mention STRING
379    as the file name for which the error was encountered.  */
380
381 void
382 print_sys_errmsg (string, errcode)
383      char *string;
384      int errcode;
385 {
386   char *err;
387   char *combined;
388
389   err = safe_strerror (errcode);
390   combined = (char *) alloca (strlen (err) + strlen (string) + 3);
391   strcpy (combined, string);
392   strcat (combined, ": ");
393   strcat (combined, err);
394
395   fprintf (stderr, "%s.\n", combined);
396 }
397
398 /* Control C eventually causes this to be called, at a convenient time.  */
399
400 void
401 quit ()
402 {
403   target_terminal_ours ();
404   wrap_here ((char *)0);                /* Force out any pending output */
405 #ifdef HAVE_TERMIO
406   ioctl (fileno (stdout), TCFLSH, 1);
407 #else /* not HAVE_TERMIO */
408   ioctl (fileno (stdout), TIOCFLUSH, 0);
409 #endif /* not HAVE_TERMIO */
410 #ifdef TIOCGPGRP
411   error ("Quit");
412 #else
413   error ("Quit (expect signal %d when inferior is resumed)", SIGINT);
414 #endif /* TIOCGPGRP */
415 }
416
417 /* Control C comes here */
418
419 void
420 request_quit (signo)
421      int signo;
422 {
423   quit_flag = 1;
424
425 #ifdef USG
426   /* Restore the signal handler.  */
427   signal (signo, request_quit);
428 #endif
429
430   if (immediate_quit)
431     quit ();
432 }
433
434 \f
435 /* Memory management stuff (malloc friends).  */
436
437 #if defined (NO_MMALLOC)
438
439 PTR
440 mmalloc (md, size)
441      PTR md;
442      long size;
443 {
444   return (malloc (size));
445 }
446
447 PTR
448 mrealloc (md, ptr, size)
449      PTR md;
450      PTR ptr;
451      long size;
452 {
453   if (ptr == 0)         /* Guard against old realloc's */
454     return malloc (size);
455   else
456     return realloc (ptr, size);
457 }
458
459 void
460 mfree (md, ptr)
461      PTR md;
462      PTR ptr;
463 {
464   free (ptr);
465 }
466
467 #endif  /* NO_MMALLOC */
468
469 #if defined (NO_MMALLOC) || defined (NO_MMALLOC_CHECK)
470
471 void
472 init_malloc (md)
473      PTR md;
474 {
475 }
476
477 #else /* have mmalloc and want corruption checking  */
478
479 static void
480 malloc_botch ()
481 {
482   fatal_dump_core ("Memory corruption");
483 }
484
485 /* Attempt to install hooks in mmalloc/mrealloc/mfree for the heap specified
486    by MD, to detect memory corruption.  Note that MD may be NULL to specify
487    the default heap that grows via sbrk.
488
489    Note that for freshly created regions, we must call mmcheck prior to any
490    mallocs in the region.  Otherwise, any region which was allocated prior to
491    installing the checking hooks, which is later reallocated or freed, will
492    fail the checks!  The mmcheck function only allows initial hooks to be
493    installed before the first mmalloc.  However, anytime after we have called
494    mmcheck the first time to install the checking hooks, we can call it again
495    to update the function pointer to the memory corruption handler.
496
497    Returns zero on failure, non-zero on success. */
498
499 void
500 init_malloc (md)
501      PTR md;
502 {
503   if (!mmcheck (md, malloc_botch))
504     {
505       warning ("internal error: failed to install memory consistency checks");
506     }
507
508   (void) mmtrace ();
509 }
510
511 #endif /* Have mmalloc and want corruption checking  */
512
513 /* Called when a memory allocation fails, with the number of bytes of
514    memory requested in SIZE. */
515
516 NORETURN void
517 nomem (size)
518      long size;
519 {
520   if (size > 0)
521     {
522       fatal ("virtual memory exhausted: can't allocate %ld bytes.", size);
523     }
524   else
525     {
526       fatal ("virtual memory exhausted.");
527     }
528 }
529
530 /* Like mmalloc but get error if no storage available, and protect against
531    the caller wanting to allocate zero bytes.  Whether to return NULL for
532    a zero byte request, or translate the request into a request for one
533    byte of zero'd storage, is a religious issue. */
534
535 PTR
536 xmmalloc (md, size)
537      PTR md;
538      long size;
539 {
540   register PTR val;
541
542   if (size == 0)
543     {
544       val = NULL;
545     }
546   else if ((val = mmalloc (md, size)) == NULL)
547     {
548       nomem (size);
549     }
550   return (val);
551 }
552
553 /* Like mrealloc but get error if no storage available.  */
554
555 PTR
556 xmrealloc (md, ptr, size)
557      PTR md;
558      PTR ptr;
559      long size;
560 {
561   register PTR val;
562
563   if (ptr != NULL)
564     {
565       val = mrealloc (md, ptr, size);
566     }
567   else
568     {
569       val = mmalloc (md, size);
570     }
571   if (val == NULL)
572     {
573       nomem (size);
574     }
575   return (val);
576 }
577
578 /* Like malloc but get error if no storage available, and protect against
579    the caller wanting to allocate zero bytes.  */
580
581 PTR
582 xmalloc (size)
583      long size;
584 {
585   return (xmmalloc ((void *) NULL, size));
586 }
587
588 /* Like mrealloc but get error if no storage available.  */
589
590 PTR
591 xrealloc (ptr, size)
592      PTR ptr;
593      long size;
594 {
595   return (xmrealloc ((void *) NULL, ptr, size));
596 }
597
598 \f
599 /* My replacement for the read system call.
600    Used like `read' but keeps going if `read' returns too soon.  */
601
602 int
603 myread (desc, addr, len)
604      int desc;
605      char *addr;
606      int len;
607 {
608   register int val;
609   int orglen = len;
610
611   while (len > 0)
612     {
613       val = read (desc, addr, len);
614       if (val < 0)
615         return val;
616       if (val == 0)
617         return orglen - len;
618       len -= val;
619       addr += val;
620     }
621   return orglen;
622 }
623 \f
624 /* Make a copy of the string at PTR with SIZE characters
625    (and add a null character at the end in the copy).
626    Uses malloc to get the space.  Returns the address of the copy.  */
627
628 char *
629 savestring (ptr, size)
630      const char *ptr;
631      int size;
632 {
633   register char *p = (char *) xmalloc (size + 1);
634   bcopy (ptr, p, size);
635   p[size] = 0;
636   return p;
637 }
638
639 char *
640 msavestring (md, ptr, size)
641      void *md;
642      const char *ptr;
643      int size;
644 {
645   register char *p = (char *) xmmalloc (md, size + 1);
646   bcopy (ptr, p, size);
647   p[size] = 0;
648   return p;
649 }
650
651 /* The "const" is so it compiles under DGUX (which prototypes strsave
652    in <string.h>.  FIXME: This should be named "xstrsave", shouldn't it?
653    Doesn't real strsave return NULL if out of memory?  */
654 char *
655 strsave (ptr)
656      const char *ptr;
657 {
658   return savestring (ptr, strlen (ptr));
659 }
660
661 char *
662 mstrsave (md, ptr)
663      void *md;
664      const char *ptr;
665 {
666   return (msavestring (md, ptr, strlen (ptr)));
667 }
668
669 void
670 print_spaces (n, file)
671      register int n;
672      register FILE *file;
673 {
674   while (n-- > 0)
675     fputc (' ', file);
676 }
677
678 /* Ask user a y-or-n question and return 1 iff answer is yes.
679    Takes three args which are given to printf to print the question.
680    The first, a control string, should end in "? ".
681    It should not say how to answer, because we do that.  */
682
683 /* VARARGS */
684 int
685 query (va_alist)
686      va_dcl
687 {
688   va_list args;
689   char *ctlstr;
690   register int answer;
691   register int ans2;
692
693   /* Automatically answer "yes" if input is not from a terminal.  */
694   if (!input_from_terminal_p ())
695     return 1;
696
697   while (1)
698     {
699       va_start (args);
700       ctlstr = va_arg (args, char *);
701       vfprintf_filtered (stdout, ctlstr, args);
702       va_end (args);
703       printf_filtered ("(y or n) ");
704       fflush (stdout);
705       answer = fgetc (stdin);
706       clearerr (stdin);         /* in case of C-d */
707       if (answer == EOF)        /* C-d */
708         return 1;
709       if (answer != '\n')       /* Eat rest of input line, to EOF or newline */
710         do 
711           {
712             ans2 = fgetc (stdin);
713             clearerr (stdin);
714           }
715         while (ans2 != EOF && ans2 != '\n');
716       if (answer >= 'a')
717         answer -= 040;
718       if (answer == 'Y')
719         return 1;
720       if (answer == 'N')
721         return 0;
722       printf_filtered ("Please answer y or n.\n");
723     }
724 }
725
726 \f
727 /* Parse a C escape sequence.  STRING_PTR points to a variable
728    containing a pointer to the string to parse.  That pointer
729    should point to the character after the \.  That pointer
730    is updated past the characters we use.  The value of the
731    escape sequence is returned.
732
733    A negative value means the sequence \ newline was seen,
734    which is supposed to be equivalent to nothing at all.
735
736    If \ is followed by a null character, we return a negative
737    value and leave the string pointer pointing at the null character.
738
739    If \ is followed by 000, we return 0 and leave the string pointer
740    after the zeros.  A value of 0 does not mean end of string.  */
741
742 int
743 parse_escape (string_ptr)
744      char **string_ptr;
745 {
746   register int c = *(*string_ptr)++;
747   switch (c)
748     {
749     case 'a':
750       return 007;               /* Bell (alert) char */
751     case 'b':
752       return '\b';
753     case 'e':                   /* Escape character */
754       return 033;
755     case 'f':
756       return '\f';
757     case 'n':
758       return '\n';
759     case 'r':
760       return '\r';
761     case 't':
762       return '\t';
763     case 'v':
764       return '\v';
765     case '\n':
766       return -2;
767     case 0:
768       (*string_ptr)--;
769       return 0;
770     case '^':
771       c = *(*string_ptr)++;
772       if (c == '\\')
773         c = parse_escape (string_ptr);
774       if (c == '?')
775         return 0177;
776       return (c & 0200) | (c & 037);
777       
778     case '0':
779     case '1':
780     case '2':
781     case '3':
782     case '4':
783     case '5':
784     case '6':
785     case '7':
786       {
787         register int i = c - '0';
788         register int count = 0;
789         while (++count < 3)
790           {
791             if ((c = *(*string_ptr)++) >= '0' && c <= '7')
792               {
793                 i *= 8;
794                 i += c - '0';
795               }
796             else
797               {
798                 (*string_ptr)--;
799                 break;
800               }
801           }
802         return i;
803       }
804     default:
805       return c;
806     }
807 }
808 \f
809 /* Print the character C on STREAM as part of the contents
810    of a literal string whose delimiter is QUOTER.  */
811
812 void
813 printchar (c, stream, quoter)
814      register int c;
815      FILE *stream;
816      int quoter;
817 {
818
819   c &= 0xFF;                    /* Avoid sign bit follies */
820
821   if (              c < 0x20  ||                /* Low control chars */ 
822       (c >= 0x7F && c < 0xA0) ||                /* DEL, High controls */
823       (sevenbit_strings && c >= 0x80)) {        /* high order bit set */
824     switch (c)
825       {
826       case '\n':
827         fputs_filtered ("\\n", stream);
828         break;
829       case '\b':
830         fputs_filtered ("\\b", stream);
831         break;
832       case '\t':
833         fputs_filtered ("\\t", stream);
834         break;
835       case '\f':
836         fputs_filtered ("\\f", stream);
837         break;
838       case '\r':
839         fputs_filtered ("\\r", stream);
840         break;
841       case '\033':
842         fputs_filtered ("\\e", stream);
843         break;
844       case '\007':
845         fputs_filtered ("\\a", stream);
846         break;
847       default:
848         fprintf_filtered (stream, "\\%.3o", (unsigned int) c);
849         break;
850       }
851   } else {
852     if (c == '\\' || c == quoter)
853       fputs_filtered ("\\", stream);
854     fprintf_filtered (stream, "%c", c);
855   }
856 }
857 \f
858 /* Number of lines per page or UINT_MAX if paging is disabled.  */
859 static unsigned int lines_per_page;
860 /* Number of chars per line or UNIT_MAX is line folding is disabled.  */
861 static unsigned int chars_per_line;
862 /* Current count of lines printed on this page, chars on this line.  */
863 static unsigned int lines_printed, chars_printed;
864
865 /* Buffer and start column of buffered text, for doing smarter word-
866    wrapping.  When someone calls wrap_here(), we start buffering output
867    that comes through fputs_filtered().  If we see a newline, we just
868    spit it out and forget about the wrap_here().  If we see another
869    wrap_here(), we spit it out and remember the newer one.  If we see
870    the end of the line, we spit out a newline, the indent, and then
871    the buffered output.
872
873    wrap_column is the column number on the screen where wrap_buffer begins.
874      When wrap_column is zero, wrapping is not in effect.
875    wrap_buffer is malloc'd with chars_per_line+2 bytes. 
876      When wrap_buffer[0] is null, the buffer is empty.
877    wrap_pointer points into it at the next character to fill.
878    wrap_indent is the string that should be used as indentation if the
879      wrap occurs.  */
880
881 static char *wrap_buffer, *wrap_pointer, *wrap_indent;
882 static int wrap_column;
883
884 /* ARGSUSED */
885 static void 
886 set_width_command (args, from_tty, c)
887      char *args;
888      int from_tty;
889      struct cmd_list_element *c;
890 {
891   if (!wrap_buffer)
892     {
893       wrap_buffer = (char *) xmalloc (chars_per_line + 2);
894       wrap_buffer[0] = '\0';
895     }
896   else
897     wrap_buffer = (char *) xrealloc (wrap_buffer, chars_per_line + 2);
898   wrap_pointer = wrap_buffer;   /* Start it at the beginning */
899 }
900
901 static void
902 prompt_for_continue ()
903 {
904   char *ignore;
905
906   immediate_quit++;
907   ignore = gdb_readline ("---Type <return> to continue---");
908   if (ignore)
909     free (ignore);
910   chars_printed = lines_printed = 0;
911   immediate_quit--;
912   dont_repeat ();               /* Forget prev cmd -- CR won't repeat it. */
913 }
914
915 /* Reinitialize filter; ie. tell it to reset to original values.  */
916
917 void
918 reinitialize_more_filter ()
919 {
920   lines_printed = 0;
921   chars_printed = 0;
922 }
923
924 /* Indicate that if the next sequence of characters overflows the line,
925    a newline should be inserted here rather than when it hits the end. 
926    If INDENT is nonzero, it is a string to be printed to indent the
927    wrapped part on the next line.  INDENT must remain accessible until
928    the next call to wrap_here() or until a newline is printed through
929    fputs_filtered().
930
931    If the line is already overfull, we immediately print a newline and
932    the indentation, and disable further wrapping.
933
934    If we don't know the width of lines, but we know the page height,
935    we must not wrap words, but should still keep track of newlines
936    that were explicitly printed.
937
938    INDENT should not contain tabs, as that
939    will mess up the char count on the next line.  FIXME.  */
940
941 void
942 wrap_here(indent)
943   char *indent;
944 {
945   if (wrap_buffer[0])
946     {
947       *wrap_pointer = '\0';
948       fputs (wrap_buffer, stdout);
949     }
950   wrap_pointer = wrap_buffer;
951   wrap_buffer[0] = '\0';
952   if (chars_per_line == UINT_MAX)               /* No line overflow checking */
953     {
954       wrap_column = 0;
955     }
956   else if (chars_printed >= chars_per_line)
957     {
958       puts_filtered ("\n");
959       puts_filtered (indent);
960       wrap_column = 0;
961     }
962   else
963     {
964       wrap_column = chars_printed;
965       wrap_indent = indent;
966     }
967 }
968
969 /* Like fputs but pause after every screenful, and can wrap at points
970    other than the final character of a line.
971    Unlike fputs, fputs_filtered does not return a value.
972    It is OK for LINEBUFFER to be NULL, in which case just don't print
973    anything.
974
975    Note that a longjmp to top level may occur in this routine
976    (since prompt_for_continue may do so) so this routine should not be
977    called when cleanups are not in place.  */
978
979 void
980 fputs_filtered (linebuffer, stream)
981      const char *linebuffer;
982      FILE *stream;
983 {
984   const char *lineptr;
985
986   if (linebuffer == 0)
987     return;
988   
989   /* Don't do any filtering if it is disabled.  */
990   if (stream != stdout
991    || (lines_per_page == UINT_MAX && chars_per_line == UINT_MAX))
992     {
993       fputs (linebuffer, stream);
994       return;
995     }
996
997   /* Go through and output each character.  Show line extension
998      when this is necessary; prompt user for new page when this is
999      necessary.  */
1000   
1001   lineptr = linebuffer;
1002   while (*lineptr)
1003     {
1004       /* Possible new page.  */
1005       if (lines_printed >= lines_per_page - 1)
1006         prompt_for_continue ();
1007
1008       while (*lineptr && *lineptr != '\n')
1009         {
1010           /* Print a single line.  */
1011           if (*lineptr == '\t')
1012             {
1013               if (wrap_column)
1014                 *wrap_pointer++ = '\t';
1015               else
1016                 putc ('\t', stream);
1017               /* Shifting right by 3 produces the number of tab stops
1018                  we have already passed, and then adding one and
1019                  shifting left 3 advances to the next tab stop.  */
1020               chars_printed = ((chars_printed >> 3) + 1) << 3;
1021               lineptr++;
1022             }
1023           else
1024             {
1025               if (wrap_column)
1026                 *wrap_pointer++ = *lineptr;
1027               else
1028                 putc (*lineptr, stream);
1029               chars_printed++;
1030               lineptr++;
1031             }
1032       
1033           if (chars_printed >= chars_per_line)
1034             {
1035               unsigned int save_chars = chars_printed;
1036
1037               chars_printed = 0;
1038               lines_printed++;
1039               /* If we aren't actually wrapping, don't output newline --
1040                  if chars_per_line is right, we probably just overflowed
1041                  anyway; if it's wrong, let us keep going.  */
1042               if (wrap_column)
1043                 putc ('\n', stream);
1044
1045               /* Possible new page.  */
1046               if (lines_printed >= lines_per_page - 1)
1047                 prompt_for_continue ();
1048
1049               /* Now output indentation and wrapped string */
1050               if (wrap_column)
1051                 {
1052                   if (wrap_indent)
1053                     fputs (wrap_indent, stream);
1054                   *wrap_pointer = '\0';         /* Null-terminate saved stuff */
1055                   fputs (wrap_buffer, stream);  /* and eject it */
1056                   /* FIXME, this strlen is what prevents wrap_indent from
1057                      containing tabs.  However, if we recurse to print it
1058                      and count its chars, we risk trouble if wrap_indent is
1059                      longer than (the user settable) chars_per_line. 
1060                      Note also that this can set chars_printed > chars_per_line
1061                      if we are printing a long string.  */
1062                   chars_printed = strlen (wrap_indent)
1063                                 + (save_chars - wrap_column);
1064                   wrap_pointer = wrap_buffer;   /* Reset buffer */
1065                   wrap_buffer[0] = '\0';
1066                   wrap_column = 0;              /* And disable fancy wrap */
1067                 }
1068             }
1069         }
1070
1071       if (*lineptr == '\n')
1072         {
1073           chars_printed = 0;
1074           wrap_here ((char *)0);  /* Spit out chars, cancel further wraps */
1075           lines_printed++;
1076           putc ('\n', stream);
1077           lineptr++;
1078         }
1079     }
1080 }
1081
1082
1083 /* fputs_demangled is a variant of fputs_filtered that
1084    demangles g++ names.*/
1085
1086 void
1087 fputs_demangled (linebuffer, stream, arg_mode)
1088      char *linebuffer;
1089      FILE *stream;
1090      int arg_mode;
1091 {
1092 #define SYMBOL_MAX 1024
1093
1094 #define SYMBOL_CHAR(c) (isascii(c) \
1095   && (isalnum(c) || (c) == '_' || (c) == CPLUS_MARKER))
1096
1097   char buf[SYMBOL_MAX+1];
1098 # define SLOP 5         /* How much room to leave in buf */
1099   char *p;
1100
1101   if (linebuffer == NULL)
1102     return;
1103
1104   /* If user wants to see raw output, no problem.  */
1105   if (!demangle) {
1106     fputs_filtered (linebuffer, stream);
1107     return;
1108   }
1109
1110   p = linebuffer;
1111
1112   while ( *p != (char) 0 ) {
1113     int i = 0;
1114
1115     /* collect non-interesting characters into buf */
1116     while ( *p != (char) 0 && !SYMBOL_CHAR(*p) && i < (int)sizeof(buf)-SLOP ) {
1117       buf[i++] = *p;
1118       p++;
1119     }
1120     if (i > 0) {
1121       /* output the non-interesting characters without demangling */
1122       buf[i] = (char) 0;
1123       fputs_filtered(buf, stream);
1124       i = 0;  /* reset buf */
1125     }
1126
1127     /* and now the interesting characters */
1128     while (i < SYMBOL_MAX
1129      && *p != (char) 0
1130      && SYMBOL_CHAR(*p)
1131      && i < (int)sizeof(buf) - SLOP) {
1132       buf[i++] = *p;
1133       p++;
1134     }
1135     buf[i] = (char) 0;
1136     if (i > 0) {
1137       char * result;
1138       
1139       if ( (result = cplus_demangle(buf, arg_mode)) != NULL ) {
1140         fputs_filtered(result, stream);
1141         free(result);
1142       }
1143       else {
1144         fputs_filtered(buf, stream);
1145       }
1146     }
1147   }
1148 }
1149
1150 /* Print a variable number of ARGS using format FORMAT.  If this
1151    information is going to put the amount written (since the last call
1152    to INITIALIZE_MORE_FILTER or the last page break) over the page size,
1153    print out a pause message and do a gdb_readline to get the users
1154    permision to continue.
1155
1156    Unlike fprintf, this function does not return a value.
1157
1158    We implement three variants, vfprintf (takes a vararg list and stream),
1159    fprintf (takes a stream to write on), and printf (the usual).
1160
1161    Note that this routine has a restriction that the length of the
1162    final output line must be less than 255 characters *or* it must be
1163    less than twice the size of the format string.  This is a very
1164    arbitrary restriction, but it is an internal restriction, so I'll
1165    put it in.  This means that the %s format specifier is almost
1166    useless; unless the caller can GUARANTEE that the string is short
1167    enough, fputs_filtered should be used instead.
1168
1169    Note also that a longjmp to top level may occur in this routine
1170    (since prompt_for_continue may do so) so this routine should not be
1171    called when cleanups are not in place.  */
1172
1173 static void
1174 vfprintf_filtered (stream, format, args)
1175      FILE *stream;
1176      char *format;
1177      va_list args;
1178 {
1179   static char *linebuffer = (char *) 0;
1180   static int line_size;
1181   int format_length;
1182
1183   format_length = strlen (format);
1184
1185   /* Allocated linebuffer for the first time.  */
1186   if (!linebuffer)
1187     {
1188       linebuffer = (char *) xmalloc (255);
1189       line_size = 255;
1190     }
1191
1192   /* Reallocate buffer to a larger size if this is necessary.  */
1193   if (format_length * 2 > line_size)
1194     {
1195       line_size = format_length * 2;
1196
1197       /* You don't have to copy.  */
1198       free (linebuffer);
1199       linebuffer = (char *) xmalloc (line_size);
1200     }
1201
1202
1203   /* This won't blow up if the restrictions described above are
1204      followed.   */
1205   (void) vsprintf (linebuffer, format, args);
1206
1207   fputs_filtered (linebuffer, stream);
1208 }
1209
1210 /* VARARGS */
1211 void
1212 fprintf_filtered (va_alist)
1213      va_dcl
1214 {
1215   FILE *stream;
1216   char *format;
1217   va_list args;
1218
1219   va_start (args);
1220   stream = va_arg (args, FILE *);
1221   format = va_arg (args, char *);
1222
1223   /* This won't blow up if the restrictions described above are
1224      followed.   */
1225   vfprintf_filtered (stream, format, args);
1226   va_end (args);
1227 }
1228
1229 /* VARARGS */
1230 void
1231 printf_filtered (va_alist)
1232      va_dcl
1233 {
1234   va_list args;
1235   char *format;
1236
1237   va_start (args);
1238   format = va_arg (args, char *);
1239
1240   vfprintf_filtered (stdout, format, args);
1241   va_end (args);
1242 }
1243
1244 /* Easy */
1245
1246 void
1247 puts_filtered (string)
1248      char *string;
1249 {
1250   fputs_filtered (string, stdout);
1251 }
1252
1253 /* Return a pointer to N spaces and a null.  The pointer is good
1254    until the next call to here.  */
1255 char *
1256 n_spaces (n)
1257      int n;
1258 {
1259   register char *t;
1260   static char *spaces;
1261   static int max_spaces;
1262
1263   if (n > max_spaces)
1264     {
1265       if (spaces)
1266         free (spaces);
1267       spaces = (char *) xmalloc (n+1);
1268       for (t = spaces+n; t != spaces;)
1269         *--t = ' ';
1270       spaces[n] = '\0';
1271       max_spaces = n;
1272     }
1273
1274   return spaces + max_spaces - n;
1275 }
1276
1277 /* Print N spaces.  */
1278 void
1279 print_spaces_filtered (n, stream)
1280      int n;
1281      FILE *stream;
1282 {
1283   fputs_filtered (n_spaces (n), stream);
1284 }
1285 \f
1286 /* C++ demangler stuff.  */
1287
1288 /* Print NAME on STREAM, demangling if necessary.  */
1289 void
1290 fprint_symbol (stream, name)
1291      FILE *stream;
1292      char *name;
1293 {
1294   char *demangled;
1295   if ((!demangle)
1296       || NULL == (demangled = cplus_demangle (name, DMGL_PARAMS | DMGL_ANSI)))
1297     fputs_filtered (name, stream);
1298   else
1299     {
1300       fputs_filtered (demangled, stream);
1301       free (demangled);
1302     }
1303 }
1304 \f
1305 void
1306 _initialize_utils ()
1307 {
1308   struct cmd_list_element *c;
1309
1310   c = add_set_cmd ("width", class_support, var_uinteger, 
1311                   (char *)&chars_per_line,
1312                   "Set number of characters gdb thinks are in a line.",
1313                   &setlist);
1314   add_show_from_set (c, &showlist);
1315   c->function.sfunc = set_width_command;
1316
1317   add_show_from_set
1318     (add_set_cmd ("height", class_support,
1319                   var_uinteger, (char *)&lines_per_page,
1320                   "Set number of lines gdb thinks are in a page.", &setlist),
1321      &showlist);
1322   
1323   /* These defaults will be used if we are unable to get the correct
1324      values from termcap.  */
1325   lines_per_page = 24;
1326   chars_per_line = 80;
1327   /* Initialize the screen height and width from termcap.  */
1328   {
1329     char *termtype = getenv ("TERM");
1330
1331     /* Positive means success, nonpositive means failure.  */
1332     int status;
1333
1334     /* 2048 is large enough for all known terminals, according to the
1335        GNU termcap manual.  */
1336     char term_buffer[2048];
1337
1338     if (termtype)
1339       {
1340         status = tgetent (term_buffer, termtype);
1341         if (status > 0)
1342           {
1343             int val;
1344             
1345             val = tgetnum ("li");
1346             if (val >= 0)
1347               lines_per_page = val;
1348             else
1349               /* The number of lines per page is not mentioned
1350                  in the terminal description.  This probably means
1351                  that paging is not useful (e.g. emacs shell window),
1352                  so disable paging.  */
1353               lines_per_page = UINT_MAX;
1354             
1355             val = tgetnum ("co");
1356             if (val >= 0)
1357               chars_per_line = val;
1358           }
1359       }
1360   }
1361
1362 #if defined(SIGWINCH) && defined(SIGWINCH_HANDLER)
1363
1364   /* If there is a better way to determine the window size, use it. */
1365   SIGWINCH_HANDLER ();
1366 #endif
1367
1368   /* If the output is not a terminal, don't paginate it.  */
1369   if (!ISATTY (stdout))
1370     lines_per_page = UINT_MAX;
1371
1372   set_width_command ((char *)NULL, 0, c);
1373
1374   add_show_from_set
1375     (add_set_cmd ("demangle", class_support, var_boolean, 
1376                   (char *)&demangle,
1377                 "Set demangling of encoded C++ names when displaying symbols.",
1378                   &setprintlist),
1379      &showprintlist);
1380
1381   add_show_from_set
1382     (add_set_cmd ("sevenbit-strings", class_support, var_boolean, 
1383                   (char *)&sevenbit_strings,
1384    "Set printing of 8-bit characters in strings as \\nnn.",
1385                   &setprintlist),
1386      &showprintlist);
1387
1388   add_show_from_set
1389     (add_set_cmd ("asm-demangle", class_support, var_boolean, 
1390                   (char *)&asm_demangle,
1391         "Set demangling of C++ names in disassembly listings.",
1392                   &setprintlist),
1393      &showprintlist);
1394 }
1395
1396 /* Machine specific function to handle SIGWINCH signal. */
1397
1398 #ifdef  SIGWINCH_HANDLER_BODY
1399         SIGWINCH_HANDLER_BODY
1400 #endif
This page took 0.096496 seconds and 4 git commands to generate.