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