* Makefile.in (MMALLOC_CFLAGS): Eliminate intermediate MMALLOC_DISABLE
[binutils-gdb.git] / gdb / utils.c
1 /* General utility routines for GDB, the GNU debugger.
2 Copyright 1986, 1989, 1990, 1991, 1992, 1995 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */
19
20 #include "defs.h"
21 #if !defined(__GO32__) && !defined(__WIN32__) && !defined(MPW)
22 #include <sys/ioctl.h>
23 #include <sys/param.h>
24 #include <pwd.h>
25 #endif
26 #ifdef ANSI_PROTOTYPES
27 #include <stdarg.h>
28 #else
29 #include <varargs.h>
30 #endif
31 #include <ctype.h>
32 #include "gdb_string.h"
33 #ifdef HAVE_UNISTD_H
34 #include <unistd.h>
35 #endif
36
37 #include "signals.h"
38 #include "gdbcmd.h"
39 #include "serial.h"
40 #include "bfd.h"
41 #include "target.h"
42 #include "demangle.h"
43 #include "expression.h"
44 #include "language.h"
45 #include "annotate.h"
46
47 #include "readline.h"
48
49 /* readline defines this. */
50 #undef savestring
51
52 /* Prototypes for local functions */
53
54 static void
55 fatal_dump_core PARAMS((char *, ...));
56
57 static void
58 prompt_for_continue PARAMS ((void));
59
60 static void
61 set_width_command PARAMS ((char *, int, struct cmd_list_element *));
62
63 /* If this definition isn't overridden by the header files, assume
64 that isatty and fileno exist on this system. */
65 #ifndef ISATTY
66 #define ISATTY(FP) (isatty (fileno (FP)))
67 #endif
68
69 /* Chain of cleanup actions established with make_cleanup,
70 to be executed if an error happens. */
71
72 static struct cleanup *cleanup_chain;
73
74 /* Nonzero if we have job control. */
75
76 int job_control;
77
78 /* Nonzero means a quit has been requested. */
79
80 int quit_flag;
81
82 /* Nonzero means quit immediately if Control-C is typed now, rather
83 than waiting until QUIT is executed. Be careful in setting this;
84 code which executes with immediate_quit set has to be very careful
85 about being able to deal with being interrupted at any time. It is
86 almost always better to use QUIT; the only exception I can think of
87 is being able to quit out of a system call (using EINTR loses if
88 the SIGINT happens between the previous QUIT and the system call).
89 To immediately quit in the case in which a SIGINT happens between
90 the previous QUIT and setting immediate_quit (desirable anytime we
91 expect to block), call QUIT after setting immediate_quit. */
92
93 int immediate_quit;
94
95 /* Nonzero means that encoded C++ names should be printed out in their
96 C++ form rather than raw. */
97
98 int demangle = 1;
99
100 /* Nonzero means that encoded C++ names should be printed out in their
101 C++ form even in assembler language displays. If this is set, but
102 DEMANGLE is zero, names are printed raw, i.e. DEMANGLE controls. */
103
104 int asm_demangle = 0;
105
106 /* Nonzero means that strings with character values >0x7F should be printed
107 as octal escapes. Zero means just print the value (e.g. it's an
108 international character, and the terminal or window can cope.) */
109
110 int sevenbit_strings = 0;
111
112 /* String to be printed before error messages, if any. */
113
114 char *error_pre_print;
115
116 /* String to be printed before quit messages, if any. */
117
118 char *quit_pre_print;
119
120 /* String to be printed before warning messages, if any. */
121
122 char *warning_pre_print = "\nwarning: ";
123 \f
124 /* Add a new cleanup to the cleanup_chain,
125 and return the previous chain pointer
126 to be passed later to do_cleanups or discard_cleanups.
127 Args are FUNCTION to clean up with, and ARG to pass to it. */
128
129 struct cleanup *
130 make_cleanup (function, arg)
131 void (*function) PARAMS ((PTR));
132 PTR arg;
133 {
134 register struct cleanup *new
135 = (struct cleanup *) xmalloc (sizeof (struct cleanup));
136 register struct cleanup *old_chain = cleanup_chain;
137
138 new->next = cleanup_chain;
139 new->function = function;
140 new->arg = arg;
141 cleanup_chain = new;
142
143 return old_chain;
144 }
145
146 /* Discard cleanups and do the actions they describe
147 until we get back to the point OLD_CHAIN in the cleanup_chain. */
148
149 void
150 do_cleanups (old_chain)
151 register struct cleanup *old_chain;
152 {
153 register struct cleanup *ptr;
154 while ((ptr = cleanup_chain) != old_chain)
155 {
156 cleanup_chain = ptr->next; /* Do this first incase recursion */
157 (*ptr->function) (ptr->arg);
158 free (ptr);
159 }
160 }
161
162 /* Discard cleanups, not doing the actions they describe,
163 until we get back to the point OLD_CHAIN in the cleanup_chain. */
164
165 void
166 discard_cleanups (old_chain)
167 register struct cleanup *old_chain;
168 {
169 register struct cleanup *ptr;
170 while ((ptr = cleanup_chain) != old_chain)
171 {
172 cleanup_chain = ptr->next;
173 free ((PTR)ptr);
174 }
175 }
176
177 /* Set the cleanup_chain to 0, and return the old cleanup chain. */
178 struct cleanup *
179 save_cleanups ()
180 {
181 struct cleanup *old_chain = cleanup_chain;
182
183 cleanup_chain = 0;
184 return old_chain;
185 }
186
187 /* Restore the cleanup chain from a previously saved chain. */
188 void
189 restore_cleanups (chain)
190 struct cleanup *chain;
191 {
192 cleanup_chain = chain;
193 }
194
195 /* This function is useful for cleanups.
196 Do
197
198 foo = xmalloc (...);
199 old_chain = make_cleanup (free_current_contents, &foo);
200
201 to arrange to free the object thus allocated. */
202
203 void
204 free_current_contents (location)
205 char **location;
206 {
207 free (*location);
208 }
209
210 /* Provide a known function that does nothing, to use as a base for
211 for a possibly long chain of cleanups. This is useful where we
212 use the cleanup chain for handling normal cleanups as well as dealing
213 with cleanups that need to be done as a result of a call to error().
214 In such cases, we may not be certain where the first cleanup is, unless
215 we have a do-nothing one to always use as the base. */
216
217 /* ARGSUSED */
218 void
219 null_cleanup (arg)
220 char **arg;
221 {
222 }
223
224 \f
225 /* Print a warning message. Way to use this is to call warning_begin,
226 output the warning message (use unfiltered output to gdb_stderr),
227 ending in a newline. There is not currently a warning_end that you
228 call afterwards, but such a thing might be added if it is useful
229 for a GUI to separate warning messages from other output.
230
231 FIXME: Why do warnings use unfiltered output and errors filtered?
232 Is this anything other than a historical accident? */
233
234 void
235 warning_begin ()
236 {
237 target_terminal_ours ();
238 wrap_here(""); /* Force out any buffered output */
239 gdb_flush (gdb_stdout);
240 if (warning_pre_print)
241 fprintf_unfiltered (gdb_stderr, warning_pre_print);
242 }
243
244 /* Print a warning message.
245 The first argument STRING is the warning message, used as a fprintf string,
246 and the remaining args are passed as arguments to it.
247 The primary difference between warnings and errors is that a warning
248 does not force the return to command level. */
249
250 /* VARARGS */
251 void
252 #ifdef ANSI_PROTOTYPES
253 warning (char *string, ...)
254 #else
255 warning (va_alist)
256 va_dcl
257 #endif
258 {
259 va_list args;
260 #ifdef ANSI_PROTOTYPES
261 va_start (args, string);
262 #else
263 char *string;
264
265 va_start (args);
266 string = va_arg (args, char *);
267 #endif
268 warning_begin ();
269 vfprintf_unfiltered (gdb_stderr, string, args);
270 fprintf_unfiltered (gdb_stderr, "\n");
271 va_end (args);
272 }
273
274 /* Start the printing of an error message. Way to use this is to call
275 this, output the error message (use filtered output to gdb_stderr
276 (FIXME: Some callers, like memory_error, use gdb_stdout)), ending
277 in a newline, and then call return_to_top_level (RETURN_ERROR).
278 error() provides a convenient way to do this for the special case
279 that the error message can be formatted with a single printf call,
280 but this is more general. */
281 void
282 error_begin ()
283 {
284 target_terminal_ours ();
285 wrap_here (""); /* Force out any buffered output */
286 gdb_flush (gdb_stdout);
287
288 annotate_error_begin ();
289
290 if (error_pre_print)
291 fprintf_filtered (gdb_stderr, error_pre_print);
292 }
293
294 /* Print an error message and return to command level.
295 The first argument STRING is the error message, used as a fprintf string,
296 and the remaining args are passed as arguments to it. */
297
298 #ifdef ANSI_PROTOTYPES
299 NORETURN void
300 error (char *string, ...)
301 #else
302 void
303 error (va_alist)
304 va_dcl
305 #endif
306 {
307 va_list args;
308 #ifdef ANSI_PROTOTYPES
309 va_start (args, string);
310 #else
311 va_start (args);
312 #endif
313 if (error_hook)
314 (*error_hook) ();
315 else
316 {
317 error_begin ();
318 #ifdef ANSI_PROTOTYPES
319 vfprintf_filtered (gdb_stderr, string, args);
320 #else
321 {
322 char *string1;
323
324 string1 = va_arg (args, char *);
325 vfprintf_filtered (gdb_stderr, string1, args);
326 }
327 #endif
328 fprintf_filtered (gdb_stderr, "\n");
329 va_end (args);
330 return_to_top_level (RETURN_ERROR);
331 }
332 }
333
334
335 /* Print an error message and exit reporting failure.
336 This is for a error that we cannot continue from.
337 The arguments are printed a la printf.
338
339 This function cannot be declared volatile (NORETURN) in an
340 ANSI environment because exit() is not declared volatile. */
341
342 /* VARARGS */
343 NORETURN void
344 #ifdef ANSI_PROTOTYPES
345 fatal (char *string, ...)
346 #else
347 fatal (va_alist)
348 va_dcl
349 #endif
350 {
351 va_list args;
352 #ifdef ANSI_PROTOTYPES
353 va_start (args, string);
354 #else
355 char *string;
356 va_start (args);
357 string = va_arg (args, char *);
358 #endif
359 fprintf_unfiltered (gdb_stderr, "\ngdb: ");
360 vfprintf_unfiltered (gdb_stderr, string, args);
361 fprintf_unfiltered (gdb_stderr, "\n");
362 va_end (args);
363 exit (1);
364 }
365
366 /* Print an error message and exit, dumping core.
367 The arguments are printed a la printf (). */
368
369 /* VARARGS */
370 static void
371 #ifdef ANSI_PROTOTYPES
372 fatal_dump_core (char *string, ...)
373 #else
374 fatal_dump_core (va_alist)
375 va_dcl
376 #endif
377 {
378 va_list args;
379 #ifdef ANSI_PROTOTYPES
380 va_start (args, string);
381 #else
382 char *string;
383
384 va_start (args);
385 string = va_arg (args, char *);
386 #endif
387 /* "internal error" is always correct, since GDB should never dump
388 core, no matter what the input. */
389 fprintf_unfiltered (gdb_stderr, "\ngdb internal error: ");
390 vfprintf_unfiltered (gdb_stderr, string, args);
391 fprintf_unfiltered (gdb_stderr, "\n");
392 va_end (args);
393
394 signal (SIGQUIT, SIG_DFL);
395 kill (getpid (), SIGQUIT);
396 /* We should never get here, but just in case... */
397 exit (1);
398 }
399
400 /* The strerror() function can return NULL for errno values that are
401 out of range. Provide a "safe" version that always returns a
402 printable string. */
403
404 char *
405 safe_strerror (errnum)
406 int errnum;
407 {
408 char *msg;
409 static char buf[32];
410
411 if ((msg = strerror (errnum)) == NULL)
412 {
413 sprintf (buf, "(undocumented errno %d)", errnum);
414 msg = buf;
415 }
416 return (msg);
417 }
418
419 /* The strsignal() function can return NULL for signal values that are
420 out of range. Provide a "safe" version that always returns a
421 printable string. */
422
423 char *
424 safe_strsignal (signo)
425 int signo;
426 {
427 char *msg;
428 static char buf[32];
429
430 if ((msg = strsignal (signo)) == NULL)
431 {
432 sprintf (buf, "(undocumented signal %d)", signo);
433 msg = buf;
434 }
435 return (msg);
436 }
437
438
439 /* Print the system error message for errno, and also mention STRING
440 as the file name for which the error was encountered.
441 Then return to command level. */
442
443 void
444 perror_with_name (string)
445 char *string;
446 {
447 char *err;
448 char *combined;
449
450 err = safe_strerror (errno);
451 combined = (char *) alloca (strlen (err) + strlen (string) + 3);
452 strcpy (combined, string);
453 strcat (combined, ": ");
454 strcat (combined, err);
455
456 /* I understand setting these is a matter of taste. Still, some people
457 may clear errno but not know about bfd_error. Doing this here is not
458 unreasonable. */
459 bfd_set_error (bfd_error_no_error);
460 errno = 0;
461
462 error ("%s.", combined);
463 }
464
465 /* Print the system error message for ERRCODE, and also mention STRING
466 as the file name for which the error was encountered. */
467
468 void
469 print_sys_errmsg (string, errcode)
470 char *string;
471 int errcode;
472 {
473 char *err;
474 char *combined;
475
476 err = safe_strerror (errcode);
477 combined = (char *) alloca (strlen (err) + strlen (string) + 3);
478 strcpy (combined, string);
479 strcat (combined, ": ");
480 strcat (combined, err);
481
482 /* We want anything which was printed on stdout to come out first, before
483 this message. */
484 gdb_flush (gdb_stdout);
485 fprintf_unfiltered (gdb_stderr, "%s.\n", combined);
486 }
487
488 /* Control C eventually causes this to be called, at a convenient time. */
489
490 void
491 quit ()
492 {
493 serial_t gdb_stdout_serial = serial_fdopen (1);
494
495 target_terminal_ours ();
496
497 /* We want all output to appear now, before we print "Quit". We
498 have 3 levels of buffering we have to flush (it's possible that
499 some of these should be changed to flush the lower-level ones
500 too): */
501
502 /* 1. The _filtered buffer. */
503 wrap_here ((char *)0);
504
505 /* 2. The stdio buffer. */
506 gdb_flush (gdb_stdout);
507 gdb_flush (gdb_stderr);
508
509 /* 3. The system-level buffer. */
510 SERIAL_FLUSH_OUTPUT (gdb_stdout_serial);
511 SERIAL_UN_FDOPEN (gdb_stdout_serial);
512
513 annotate_error_begin ();
514
515 /* Don't use *_filtered; we don't want to prompt the user to continue. */
516 if (quit_pre_print)
517 fprintf_unfiltered (gdb_stderr, quit_pre_print);
518
519 if (job_control
520 /* If there is no terminal switching for this target, then we can't
521 possibly get screwed by the lack of job control. */
522 || current_target.to_terminal_ours == NULL)
523 fprintf_unfiltered (gdb_stderr, "Quit\n");
524 else
525 fprintf_unfiltered (gdb_stderr,
526 "Quit (expect signal SIGINT when the program is resumed)\n");
527 return_to_top_level (RETURN_QUIT);
528 }
529
530
531 #if defined(__GO32__)||defined(WINGDB)
532
533 /* In the absence of signals, poll keyboard for a quit.
534 Called from #define QUIT pollquit() in xm-go32.h. */
535
536 void
537 pollquit()
538 {
539 if (kbhit ())
540 {
541 int k = getkey ();
542 if (k == 1) {
543 quit_flag = 1;
544 quit();
545 }
546 else if (k == 2) {
547 immediate_quit = 1;
548 quit ();
549 }
550 else
551 {
552 /* We just ignore it */
553 fprintf_unfiltered (gdb_stderr, "CTRL-A to quit, CTRL-B to quit harder\n");
554 }
555 }
556 }
557
558
559 #endif
560 #if defined(__GO32__)||defined(WINGDB)
561 void notice_quit()
562 {
563 if (kbhit ())
564 {
565 int k = getkey ();
566 if (k == 1) {
567 quit_flag = 1;
568 }
569 else if (k == 2)
570 {
571 immediate_quit = 1;
572 }
573 else
574 {
575 fprintf_unfiltered (gdb_stderr, "CTRL-A to quit, CTRL-B to quit harder\n");
576 }
577 }
578 }
579 #else
580 void notice_quit()
581 {
582 /* Done by signals */
583 }
584 #endif
585 /* Control C comes here */
586
587 void
588 request_quit (signo)
589 int signo;
590 {
591 quit_flag = 1;
592 /* Restore the signal handler. Harmless with BSD-style signals, needed
593 for System V-style signals. So just always do it, rather than worrying
594 about USG defines and stuff like that. */
595 signal (signo, request_quit);
596
597 /* start-sanitize-gm */
598 #ifdef GENERAL_MAGIC
599 target_kill ();
600 #endif /* GENERAL_MAGIC */
601 /* end-sanitize-gm */
602
603 #ifdef REQUEST_QUIT
604 REQUEST_QUIT;
605 #else
606 if (immediate_quit)
607 quit ();
608 #endif
609 }
610
611 \f
612 /* Memory management stuff (malloc friends). */
613
614 #if defined (NO_MMALLOC)
615
616 /* Make a substitute size_t for non-ANSI compilers. */
617
618 #ifdef _AIX
619 #include <stddef.h>
620 #else /* Not AIX */
621 #ifndef __STDC__
622 #ifndef size_t
623 #define size_t unsigned int
624 #endif
625 #endif
626 #endif /* Not AIX */
627
628 PTR
629 mmalloc (md, size)
630 PTR md;
631 size_t size;
632 {
633 return malloc (size);
634 }
635
636 PTR
637 mrealloc (md, ptr, size)
638 PTR md;
639 PTR ptr;
640 size_t size;
641 {
642 if (ptr == 0) /* Guard against old realloc's */
643 return malloc (size);
644 else
645 return realloc (ptr, size);
646 }
647
648 void
649 mfree (md, ptr)
650 PTR md;
651 PTR ptr;
652 {
653 free (ptr);
654 }
655
656 #endif /* NO_MMALLOC */
657
658 #if defined (NO_MMALLOC) || defined (NO_MMCHECK)
659
660 void
661 init_malloc (md)
662 PTR md;
663 {
664 }
665
666 #else /* Have mmalloc and want corruption checking */
667
668 static void
669 malloc_botch ()
670 {
671 fatal_dump_core ("Memory corruption");
672 }
673
674 /* Attempt to install hooks in mmalloc/mrealloc/mfree for the heap specified
675 by MD, to detect memory corruption. Note that MD may be NULL to specify
676 the default heap that grows via sbrk.
677
678 Note that for freshly created regions, we must call mmcheckf prior to any
679 mallocs in the region. Otherwise, any region which was allocated prior to
680 installing the checking hooks, which is later reallocated or freed, will
681 fail the checks! The mmcheck function only allows initial hooks to be
682 installed before the first mmalloc. However, anytime after we have called
683 mmcheck the first time to install the checking hooks, we can call it again
684 to update the function pointer to the memory corruption handler.
685
686 Returns zero on failure, non-zero on success. */
687
688 #ifndef MMCHECK_FORCE
689 #define MMCHECK_FORCE 0
690 #endif
691
692 void
693 init_malloc (md)
694 PTR md;
695 {
696 if (!mmcheckf (md, malloc_botch, MMCHECK_FORCE))
697 {
698 /* Don't use warning(), which relies on current_target being set
699 to something other than dummy_target, until after
700 initialize_all_files(). */
701
702 fprintf_unfiltered
703 (gdb_stderr, "warning: failed to install memory consistency checks; ");
704 fprintf_unfiltered
705 (gdb_stderr, "configuration should define NO_MMCHECK or MMCHECK_FORCE\n");
706 }
707
708 mmtrace ();
709 }
710
711 #endif /* Have mmalloc and want corruption checking */
712
713 /* Called when a memory allocation fails, with the number of bytes of
714 memory requested in SIZE. */
715
716 NORETURN void
717 nomem (size)
718 long size;
719 {
720 if (size > 0)
721 {
722 fatal ("virtual memory exhausted: can't allocate %ld bytes.", size);
723 }
724 else
725 {
726 fatal ("virtual memory exhausted.");
727 }
728 }
729
730 /* Like mmalloc but get error if no storage available, and protect against
731 the caller wanting to allocate zero bytes. Whether to return NULL for
732 a zero byte request, or translate the request into a request for one
733 byte of zero'd storage, is a religious issue. */
734
735 PTR
736 xmmalloc (md, size)
737 PTR md;
738 long size;
739 {
740 register PTR val;
741
742 if (size == 0)
743 {
744 val = NULL;
745 }
746 else if ((val = mmalloc (md, size)) == NULL)
747 {
748 nomem (size);
749 }
750 return (val);
751 }
752
753 /* Like mrealloc but get error if no storage available. */
754
755 PTR
756 xmrealloc (md, ptr, size)
757 PTR md;
758 PTR ptr;
759 long size;
760 {
761 register PTR val;
762
763 if (ptr != NULL)
764 {
765 val = mrealloc (md, ptr, size);
766 }
767 else
768 {
769 val = mmalloc (md, size);
770 }
771 if (val == NULL)
772 {
773 nomem (size);
774 }
775 return (val);
776 }
777
778 /* Like malloc but get error if no storage available, and protect against
779 the caller wanting to allocate zero bytes. */
780
781 PTR
782 xmalloc (size)
783 long size;
784 {
785 return (xmmalloc ((PTR) NULL, size));
786 }
787
788 /* Like mrealloc but get error if no storage available. */
789
790 PTR
791 xrealloc (ptr, size)
792 PTR ptr;
793 long size;
794 {
795 return (xmrealloc ((PTR) NULL, ptr, size));
796 }
797
798 \f
799 /* My replacement for the read system call.
800 Used like `read' but keeps going if `read' returns too soon. */
801
802 int
803 myread (desc, addr, len)
804 int desc;
805 char *addr;
806 int len;
807 {
808 register int val;
809 int orglen = len;
810
811 while (len > 0)
812 {
813 val = read (desc, addr, len);
814 if (val < 0)
815 return val;
816 if (val == 0)
817 return orglen - len;
818 len -= val;
819 addr += val;
820 }
821 return orglen;
822 }
823 \f
824 /* Make a copy of the string at PTR with SIZE characters
825 (and add a null character at the end in the copy).
826 Uses malloc to get the space. Returns the address of the copy. */
827
828 char *
829 savestring (ptr, size)
830 const char *ptr;
831 int size;
832 {
833 register char *p = (char *) xmalloc (size + 1);
834 memcpy (p, ptr, size);
835 p[size] = 0;
836 return p;
837 }
838
839 char *
840 msavestring (md, ptr, size)
841 PTR md;
842 const char *ptr;
843 int size;
844 {
845 register char *p = (char *) xmmalloc (md, size + 1);
846 memcpy (p, ptr, size);
847 p[size] = 0;
848 return p;
849 }
850
851 /* The "const" is so it compiles under DGUX (which prototypes strsave
852 in <string.h>. FIXME: This should be named "xstrsave", shouldn't it?
853 Doesn't real strsave return NULL if out of memory? */
854 char *
855 strsave (ptr)
856 const char *ptr;
857 {
858 return savestring (ptr, strlen (ptr));
859 }
860
861 char *
862 mstrsave (md, ptr)
863 PTR md;
864 const char *ptr;
865 {
866 return (msavestring (md, ptr, strlen (ptr)));
867 }
868
869 void
870 print_spaces (n, file)
871 register int n;
872 register FILE *file;
873 {
874 while (n-- > 0)
875 fputc (' ', file);
876 }
877
878 /* Print a host address. */
879
880 void
881 gdb_print_address (addr, stream)
882 PTR addr;
883 GDB_FILE *stream;
884 {
885
886 /* We could use the %p conversion specifier to fprintf if we had any
887 way of knowing whether this host supports it. But the following
888 should work on the Alpha and on 32 bit machines. */
889
890 fprintf_filtered (stream, "0x%lx", (unsigned long)addr);
891 }
892
893 /* Ask user a y-or-n question and return 1 iff answer is yes.
894 Takes three args which are given to printf to print the question.
895 The first, a control string, should end in "? ".
896 It should not say how to answer, because we do that. */
897
898 /* VARARGS */
899 int
900 #ifdef ANSI_PROTOTYPES
901 query (char *ctlstr, ...)
902 #else
903 query (va_alist)
904 va_dcl
905 #endif
906 {
907 va_list args;
908 register int answer;
909 register int ans2;
910 int retval;
911
912 #ifdef ANSI_PROTOTYPES
913 va_start (args, ctlstr);
914 #else
915 char *ctlstr;
916 va_start (args);
917 ctlstr = va_arg (args, char *);
918 #endif
919
920 if (query_hook)
921 {
922 return query_hook (ctlstr, args);
923 }
924
925 /* Automatically answer "yes" if input is not from a terminal. */
926 if (!input_from_terminal_p ())
927 return 1;
928 #ifdef MPW
929 /* FIXME Automatically answer "yes" if called from MacGDB. */
930 if (mac_app)
931 return 1;
932 #endif /* MPW */
933
934 while (1)
935 {
936 wrap_here (""); /* Flush any buffered output */
937 gdb_flush (gdb_stdout);
938
939 if (annotation_level > 1)
940 printf_filtered ("\n\032\032pre-query\n");
941
942 vfprintf_filtered (gdb_stdout, ctlstr, args);
943 printf_filtered ("(y or n) ");
944
945 if (annotation_level > 1)
946 printf_filtered ("\n\032\032query\n");
947
948 #ifdef MPW
949 /* If not in MacGDB, move to a new line so the entered line doesn't
950 have a prompt on the front of it. */
951 if (!mac_app)
952 fputs_unfiltered ("\n", gdb_stdout);
953 #endif /* MPW */
954
955 gdb_flush (gdb_stdout);
956 answer = fgetc (stdin);
957 clearerr (stdin); /* in case of C-d */
958 if (answer == EOF) /* C-d */
959 {
960 retval = 1;
961 break;
962 }
963 if (answer != '\n') /* Eat rest of input line, to EOF or newline */
964 do
965 {
966 ans2 = fgetc (stdin);
967 clearerr (stdin);
968 }
969 while (ans2 != EOF && ans2 != '\n');
970 if (answer >= 'a')
971 answer -= 040;
972 if (answer == 'Y')
973 {
974 retval = 1;
975 break;
976 }
977 if (answer == 'N')
978 {
979 retval = 0;
980 break;
981 }
982 printf_filtered ("Please answer y or n.\n");
983 }
984
985 if (annotation_level > 1)
986 printf_filtered ("\n\032\032post-query\n");
987 return retval;
988 }
989
990 \f
991 /* Parse a C escape sequence. STRING_PTR points to a variable
992 containing a pointer to the string to parse. That pointer
993 should point to the character after the \. That pointer
994 is updated past the characters we use. The value of the
995 escape sequence is returned.
996
997 A negative value means the sequence \ newline was seen,
998 which is supposed to be equivalent to nothing at all.
999
1000 If \ is followed by a null character, we return a negative
1001 value and leave the string pointer pointing at the null character.
1002
1003 If \ is followed by 000, we return 0 and leave the string pointer
1004 after the zeros. A value of 0 does not mean end of string. */
1005
1006 int
1007 parse_escape (string_ptr)
1008 char **string_ptr;
1009 {
1010 register int c = *(*string_ptr)++;
1011 switch (c)
1012 {
1013 case 'a':
1014 return 007; /* Bell (alert) char */
1015 case 'b':
1016 return '\b';
1017 case 'e': /* Escape character */
1018 return 033;
1019 case 'f':
1020 return '\f';
1021 case 'n':
1022 return '\n';
1023 case 'r':
1024 return '\r';
1025 case 't':
1026 return '\t';
1027 case 'v':
1028 return '\v';
1029 case '\n':
1030 return -2;
1031 case 0:
1032 (*string_ptr)--;
1033 return 0;
1034 case '^':
1035 c = *(*string_ptr)++;
1036 if (c == '\\')
1037 c = parse_escape (string_ptr);
1038 if (c == '?')
1039 return 0177;
1040 return (c & 0200) | (c & 037);
1041
1042 case '0':
1043 case '1':
1044 case '2':
1045 case '3':
1046 case '4':
1047 case '5':
1048 case '6':
1049 case '7':
1050 {
1051 register int i = c - '0';
1052 register int count = 0;
1053 while (++count < 3)
1054 {
1055 if ((c = *(*string_ptr)++) >= '0' && c <= '7')
1056 {
1057 i *= 8;
1058 i += c - '0';
1059 }
1060 else
1061 {
1062 (*string_ptr)--;
1063 break;
1064 }
1065 }
1066 return i;
1067 }
1068 default:
1069 return c;
1070 }
1071 }
1072 \f
1073 /* Print the character C on STREAM as part of the contents of a literal
1074 string whose delimiter is QUOTER. Note that this routine should only
1075 be call for printing things which are independent of the language
1076 of the program being debugged. */
1077
1078 void
1079 gdb_printchar (c, stream, quoter)
1080 register int c;
1081 FILE *stream;
1082 int quoter;
1083 {
1084
1085 c &= 0xFF; /* Avoid sign bit follies */
1086
1087 if ( c < 0x20 || /* Low control chars */
1088 (c >= 0x7F && c < 0xA0) || /* DEL, High controls */
1089 (sevenbit_strings && c >= 0x80)) { /* high order bit set */
1090 switch (c)
1091 {
1092 case '\n':
1093 fputs_filtered ("\\n", stream);
1094 break;
1095 case '\b':
1096 fputs_filtered ("\\b", stream);
1097 break;
1098 case '\t':
1099 fputs_filtered ("\\t", stream);
1100 break;
1101 case '\f':
1102 fputs_filtered ("\\f", stream);
1103 break;
1104 case '\r':
1105 fputs_filtered ("\\r", stream);
1106 break;
1107 case '\033':
1108 fputs_filtered ("\\e", stream);
1109 break;
1110 case '\007':
1111 fputs_filtered ("\\a", stream);
1112 break;
1113 default:
1114 fprintf_filtered (stream, "\\%.3o", (unsigned int) c);
1115 break;
1116 }
1117 } else {
1118 if (c == '\\' || c == quoter)
1119 fputs_filtered ("\\", stream);
1120 fprintf_filtered (stream, "%c", c);
1121 }
1122 }
1123 \f
1124 /* Number of lines per page or UINT_MAX if paging is disabled. */
1125 static unsigned int lines_per_page;
1126 /* Number of chars per line or UNIT_MAX is line folding is disabled. */
1127 static unsigned int chars_per_line;
1128 /* Current count of lines printed on this page, chars on this line. */
1129 static unsigned int lines_printed, chars_printed;
1130
1131 /* Buffer and start column of buffered text, for doing smarter word-
1132 wrapping. When someone calls wrap_here(), we start buffering output
1133 that comes through fputs_filtered(). If we see a newline, we just
1134 spit it out and forget about the wrap_here(). If we see another
1135 wrap_here(), we spit it out and remember the newer one. If we see
1136 the end of the line, we spit out a newline, the indent, and then
1137 the buffered output. */
1138
1139 /* Malloc'd buffer with chars_per_line+2 bytes. Contains characters which
1140 are waiting to be output (they have already been counted in chars_printed).
1141 When wrap_buffer[0] is null, the buffer is empty. */
1142 static char *wrap_buffer;
1143
1144 /* Pointer in wrap_buffer to the next character to fill. */
1145 static char *wrap_pointer;
1146
1147 /* String to indent by if the wrap occurs. Must not be NULL if wrap_column
1148 is non-zero. */
1149 static char *wrap_indent;
1150
1151 /* Column number on the screen where wrap_buffer begins, or 0 if wrapping
1152 is not in effect. */
1153 static int wrap_column;
1154
1155 /* ARGSUSED */
1156 static void
1157 set_width_command (args, from_tty, c)
1158 char *args;
1159 int from_tty;
1160 struct cmd_list_element *c;
1161 {
1162 if (!wrap_buffer)
1163 {
1164 wrap_buffer = (char *) xmalloc (chars_per_line + 2);
1165 wrap_buffer[0] = '\0';
1166 }
1167 else
1168 wrap_buffer = (char *) xrealloc (wrap_buffer, chars_per_line + 2);
1169 wrap_pointer = wrap_buffer; /* Start it at the beginning */
1170 }
1171
1172 /* Wait, so the user can read what's on the screen. Prompt the user
1173 to continue by pressing RETURN. */
1174
1175 static void
1176 prompt_for_continue ()
1177 {
1178 char *ignore;
1179 char cont_prompt[120];
1180
1181 if (annotation_level > 1)
1182 printf_unfiltered ("\n\032\032pre-prompt-for-continue\n");
1183
1184 strcpy (cont_prompt,
1185 "---Type <return> to continue, or q <return> to quit---");
1186 if (annotation_level > 1)
1187 strcat (cont_prompt, "\n\032\032prompt-for-continue\n");
1188
1189 /* We must do this *before* we call gdb_readline, else it will eventually
1190 call us -- thinking that we're trying to print beyond the end of the
1191 screen. */
1192 reinitialize_more_filter ();
1193
1194 immediate_quit++;
1195 /* On a real operating system, the user can quit with SIGINT.
1196 But not on GO32.
1197
1198 'q' is provided on all systems so users don't have to change habits
1199 from system to system, and because telling them what to do in
1200 the prompt is more user-friendly than expecting them to think of
1201 SIGINT. */
1202 /* Call readline, not gdb_readline, because GO32 readline handles control-C
1203 whereas control-C to gdb_readline will cause the user to get dumped
1204 out to DOS. */
1205 ignore = readline (cont_prompt);
1206
1207 if (annotation_level > 1)
1208 printf_unfiltered ("\n\032\032post-prompt-for-continue\n");
1209
1210 if (ignore)
1211 {
1212 char *p = ignore;
1213 while (*p == ' ' || *p == '\t')
1214 ++p;
1215 if (p[0] == 'q')
1216 request_quit (SIGINT);
1217 free (ignore);
1218 }
1219 immediate_quit--;
1220
1221 /* Now we have to do this again, so that GDB will know that it doesn't
1222 need to save the ---Type <return>--- line at the top of the screen. */
1223 reinitialize_more_filter ();
1224
1225 dont_repeat (); /* Forget prev cmd -- CR won't repeat it. */
1226 }
1227
1228 /* Reinitialize filter; ie. tell it to reset to original values. */
1229
1230 void
1231 reinitialize_more_filter ()
1232 {
1233 lines_printed = 0;
1234 chars_printed = 0;
1235 }
1236
1237 /* Indicate that if the next sequence of characters overflows the line,
1238 a newline should be inserted here rather than when it hits the end.
1239 If INDENT is non-null, it is a string to be printed to indent the
1240 wrapped part on the next line. INDENT must remain accessible until
1241 the next call to wrap_here() or until a newline is printed through
1242 fputs_filtered().
1243
1244 If the line is already overfull, we immediately print a newline and
1245 the indentation, and disable further wrapping.
1246
1247 If we don't know the width of lines, but we know the page height,
1248 we must not wrap words, but should still keep track of newlines
1249 that were explicitly printed.
1250
1251 INDENT should not contain tabs, as that will mess up the char count
1252 on the next line. FIXME.
1253
1254 This routine is guaranteed to force out any output which has been
1255 squirreled away in the wrap_buffer, so wrap_here ((char *)0) can be
1256 used to force out output from the wrap_buffer. */
1257
1258 void
1259 wrap_here(indent)
1260 char *indent;
1261 {
1262 /* This should have been allocated, but be paranoid anyway. */
1263 if (!wrap_buffer)
1264 abort ();
1265
1266 if (wrap_buffer[0])
1267 {
1268 *wrap_pointer = '\0';
1269 fputs_unfiltered (wrap_buffer, gdb_stdout);
1270 }
1271 wrap_pointer = wrap_buffer;
1272 wrap_buffer[0] = '\0';
1273 if (chars_per_line == UINT_MAX) /* No line overflow checking */
1274 {
1275 wrap_column = 0;
1276 }
1277 else if (chars_printed >= chars_per_line)
1278 {
1279 puts_filtered ("\n");
1280 if (indent != NULL)
1281 puts_filtered (indent);
1282 wrap_column = 0;
1283 }
1284 else
1285 {
1286 wrap_column = chars_printed;
1287 if (indent == NULL)
1288 wrap_indent = "";
1289 else
1290 wrap_indent = indent;
1291 }
1292 }
1293
1294 /* Ensure that whatever gets printed next, using the filtered output
1295 commands, starts at the beginning of the line. I.E. if there is
1296 any pending output for the current line, flush it and start a new
1297 line. Otherwise do nothing. */
1298
1299 void
1300 begin_line ()
1301 {
1302 if (chars_printed > 0)
1303 {
1304 puts_filtered ("\n");
1305 }
1306 }
1307
1308
1309 GDB_FILE *
1310 gdb_fopen (name, mode)
1311 char * name;
1312 char * mode;
1313 {
1314 return fopen (name, mode);
1315 }
1316
1317 void
1318 gdb_flush (stream)
1319 FILE *stream;
1320 {
1321 if (flush_hook)
1322 {
1323 flush_hook (stream);
1324 return;
1325 }
1326
1327 fflush (stream);
1328 }
1329
1330 /* Like fputs but if FILTER is true, pause after every screenful.
1331
1332 Regardless of FILTER can wrap at points other than the final
1333 character of a line.
1334
1335 Unlike fputs, fputs_maybe_filtered does not return a value.
1336 It is OK for LINEBUFFER to be NULL, in which case just don't print
1337 anything.
1338
1339 Note that a longjmp to top level may occur in this routine (only if
1340 FILTER is true) (since prompt_for_continue may do so) so this
1341 routine should not be called when cleanups are not in place. */
1342
1343 static void
1344 fputs_maybe_filtered (linebuffer, stream, filter)
1345 const char *linebuffer;
1346 FILE *stream;
1347 int filter;
1348 {
1349 const char *lineptr;
1350
1351 if (linebuffer == 0)
1352 return;
1353
1354 /* Don't do any filtering if it is disabled. */
1355 if (stream != gdb_stdout
1356 || (lines_per_page == UINT_MAX && chars_per_line == UINT_MAX))
1357 {
1358 fputs_unfiltered (linebuffer, stream);
1359 return;
1360 }
1361
1362 /* Go through and output each character. Show line extension
1363 when this is necessary; prompt user for new page when this is
1364 necessary. */
1365
1366 lineptr = linebuffer;
1367 while (*lineptr)
1368 {
1369 /* Possible new page. */
1370 if (filter &&
1371 (lines_printed >= lines_per_page - 1))
1372 prompt_for_continue ();
1373
1374 while (*lineptr && *lineptr != '\n')
1375 {
1376 /* Print a single line. */
1377 if (*lineptr == '\t')
1378 {
1379 if (wrap_column)
1380 *wrap_pointer++ = '\t';
1381 else
1382 fputc_unfiltered ('\t', stream);
1383 /* Shifting right by 3 produces the number of tab stops
1384 we have already passed, and then adding one and
1385 shifting left 3 advances to the next tab stop. */
1386 chars_printed = ((chars_printed >> 3) + 1) << 3;
1387 lineptr++;
1388 }
1389 else
1390 {
1391 if (wrap_column)
1392 *wrap_pointer++ = *lineptr;
1393 else
1394 fputc_unfiltered (*lineptr, stream);
1395 chars_printed++;
1396 lineptr++;
1397 }
1398
1399 if (chars_printed >= chars_per_line)
1400 {
1401 unsigned int save_chars = chars_printed;
1402
1403 chars_printed = 0;
1404 lines_printed++;
1405 /* If we aren't actually wrapping, don't output newline --
1406 if chars_per_line is right, we probably just overflowed
1407 anyway; if it's wrong, let us keep going. */
1408 if (wrap_column)
1409 fputc_unfiltered ('\n', stream);
1410
1411 /* Possible new page. */
1412 if (lines_printed >= lines_per_page - 1)
1413 prompt_for_continue ();
1414
1415 /* Now output indentation and wrapped string */
1416 if (wrap_column)
1417 {
1418 fputs_unfiltered (wrap_indent, stream);
1419 *wrap_pointer = '\0'; /* Null-terminate saved stuff */
1420 fputs_unfiltered (wrap_buffer, stream); /* and eject it */
1421 /* FIXME, this strlen is what prevents wrap_indent from
1422 containing tabs. However, if we recurse to print it
1423 and count its chars, we risk trouble if wrap_indent is
1424 longer than (the user settable) chars_per_line.
1425 Note also that this can set chars_printed > chars_per_line
1426 if we are printing a long string. */
1427 chars_printed = strlen (wrap_indent)
1428 + (save_chars - wrap_column);
1429 wrap_pointer = wrap_buffer; /* Reset buffer */
1430 wrap_buffer[0] = '\0';
1431 wrap_column = 0; /* And disable fancy wrap */
1432 }
1433 }
1434 }
1435
1436 if (*lineptr == '\n')
1437 {
1438 chars_printed = 0;
1439 wrap_here ((char *)0); /* Spit out chars, cancel further wraps */
1440 lines_printed++;
1441 fputc_unfiltered ('\n', stream);
1442 lineptr++;
1443 }
1444 }
1445 }
1446
1447 void
1448 fputs_filtered (linebuffer, stream)
1449 const char *linebuffer;
1450 FILE *stream;
1451 {
1452 fputs_maybe_filtered (linebuffer, stream, 1);
1453 }
1454
1455 int
1456 putchar_unfiltered (c)
1457 int c;
1458 {
1459 char buf[2];
1460
1461 buf[0] = c;
1462 buf[1] = 0;
1463 fputs_unfiltered (buf, gdb_stdout);
1464 return c;
1465 }
1466
1467 int
1468 fputc_unfiltered (c, stream)
1469 int c;
1470 FILE * stream;
1471 {
1472 char buf[2];
1473
1474 buf[0] = c;
1475 buf[1] = 0;
1476 fputs_unfiltered (buf, stream);
1477 return c;
1478 }
1479
1480
1481 /* Print a variable number of ARGS using format FORMAT. If this
1482 information is going to put the amount written (since the last call
1483 to REINITIALIZE_MORE_FILTER or the last page break) over the page size,
1484 call prompt_for_continue to get the users permision to continue.
1485
1486 Unlike fprintf, this function does not return a value.
1487
1488 We implement three variants, vfprintf (takes a vararg list and stream),
1489 fprintf (takes a stream to write on), and printf (the usual).
1490
1491 Note also that a longjmp to top level may occur in this routine
1492 (since prompt_for_continue may do so) so this routine should not be
1493 called when cleanups are not in place. */
1494
1495 static void
1496 vfprintf_maybe_filtered (stream, format, args, filter)
1497 FILE *stream;
1498 char *format;
1499 va_list args;
1500 int filter;
1501 {
1502 char *linebuffer;
1503 struct cleanup *old_cleanups;
1504
1505 vasprintf (&linebuffer, format, args);
1506 if (linebuffer == NULL)
1507 {
1508 fputs_unfiltered ("\ngdb: virtual memory exhausted.\n", gdb_stderr);
1509 exit (1);
1510 }
1511 old_cleanups = make_cleanup (free, linebuffer);
1512 fputs_maybe_filtered (linebuffer, stream, filter);
1513 do_cleanups (old_cleanups);
1514 }
1515
1516
1517 void
1518 vfprintf_filtered (stream, format, args)
1519 FILE *stream;
1520 const char *format;
1521 va_list args;
1522 {
1523 vfprintf_maybe_filtered (stream, format, args, 1);
1524 }
1525
1526 void
1527 vfprintf_unfiltered (stream, format, args)
1528 FILE *stream;
1529 const char *format;
1530 va_list args;
1531 {
1532 char *linebuffer;
1533 struct cleanup *old_cleanups;
1534
1535 vasprintf (&linebuffer, format, args);
1536 if (linebuffer == NULL)
1537 {
1538 fputs_unfiltered ("\ngdb: virtual memory exhausted.\n", gdb_stderr);
1539 exit (1);
1540 }
1541 old_cleanups = make_cleanup (free, linebuffer);
1542 fputs_unfiltered (linebuffer, stream);
1543 do_cleanups (old_cleanups);
1544 }
1545
1546 void
1547 vprintf_filtered (format, args)
1548 const char *format;
1549 va_list args;
1550 {
1551 vfprintf_maybe_filtered (gdb_stdout, format, args, 1);
1552 }
1553
1554 void
1555 vprintf_unfiltered (format, args)
1556 const char *format;
1557 va_list args;
1558 {
1559 vfprintf_unfiltered (gdb_stdout, format, args);
1560 }
1561
1562 /* VARARGS */
1563 void
1564 #ifdef ANSI_PROTOTYPES
1565 fprintf_filtered (FILE *stream, const char *format, ...)
1566 #else
1567 fprintf_filtered (va_alist)
1568 va_dcl
1569 #endif
1570 {
1571 va_list args;
1572 #ifdef ANSI_PROTOTYPES
1573 va_start (args, format);
1574 #else
1575 FILE *stream;
1576 char *format;
1577
1578 va_start (args);
1579 stream = va_arg (args, FILE *);
1580 format = va_arg (args, char *);
1581 #endif
1582 vfprintf_filtered (stream, format, args);
1583 va_end (args);
1584 }
1585
1586 /* VARARGS */
1587 void
1588 #ifdef ANSI_PROTOTYPES
1589 fprintf_unfiltered (FILE *stream, const char *format, ...)
1590 #else
1591 fprintf_unfiltered (va_alist)
1592 va_dcl
1593 #endif
1594 {
1595 va_list args;
1596 #ifdef ANSI_PROTOTYPES
1597 va_start (args, format);
1598 #else
1599 FILE *stream;
1600 char *format;
1601
1602 va_start (args);
1603 stream = va_arg (args, FILE *);
1604 format = va_arg (args, char *);
1605 #endif
1606 vfprintf_unfiltered (stream, format, args);
1607 va_end (args);
1608 }
1609
1610 /* Like fprintf_filtered, but prints its result indented.
1611 Called as fprintfi_filtered (spaces, stream, format, ...); */
1612
1613 /* VARARGS */
1614 void
1615 #ifdef ANSI_PROTOTYPES
1616 fprintfi_filtered (int spaces, FILE *stream, const char *format, ...)
1617 #else
1618 fprintfi_filtered (va_alist)
1619 va_dcl
1620 #endif
1621 {
1622 va_list args;
1623 #ifdef ANSI_PROTOTYPES
1624 va_start (args, format);
1625 #else
1626 int spaces;
1627 FILE *stream;
1628 char *format;
1629
1630 va_start (args);
1631 spaces = va_arg (args, int);
1632 stream = va_arg (args, FILE *);
1633 format = va_arg (args, char *);
1634 #endif
1635 print_spaces_filtered (spaces, stream);
1636
1637 vfprintf_filtered (stream, format, args);
1638 va_end (args);
1639 }
1640
1641
1642 /* VARARGS */
1643 void
1644 #ifdef ANSI_PROTOTYPES
1645 printf_filtered (const char *format, ...)
1646 #else
1647 printf_filtered (va_alist)
1648 va_dcl
1649 #endif
1650 {
1651 va_list args;
1652 #ifdef ANSI_PROTOTYPES
1653 va_start (args, format);
1654 #else
1655 char *format;
1656
1657 va_start (args);
1658 format = va_arg (args, char *);
1659 #endif
1660 vfprintf_filtered (gdb_stdout, format, args);
1661 va_end (args);
1662 }
1663
1664
1665 /* VARARGS */
1666 void
1667 #ifdef ANSI_PROTOTYPES
1668 printf_unfiltered (const char *format, ...)
1669 #else
1670 printf_unfiltered (va_alist)
1671 va_dcl
1672 #endif
1673 {
1674 va_list args;
1675 #ifdef ANSI_PROTOTYPES
1676 va_start (args, format);
1677 #else
1678 char *format;
1679
1680 va_start (args);
1681 format = va_arg (args, char *);
1682 #endif
1683 vfprintf_unfiltered (gdb_stdout, format, args);
1684 va_end (args);
1685 }
1686
1687 /* Like printf_filtered, but prints it's result indented.
1688 Called as printfi_filtered (spaces, format, ...); */
1689
1690 /* VARARGS */
1691 void
1692 #ifdef ANSI_PROTOTYPES
1693 printfi_filtered (int spaces, const char *format, ...)
1694 #else
1695 printfi_filtered (va_alist)
1696 va_dcl
1697 #endif
1698 {
1699 va_list args;
1700 #ifdef ANSI_PROTOTYPES
1701 va_start (args, format);
1702 #else
1703 int spaces;
1704 char *format;
1705
1706 va_start (args);
1707 spaces = va_arg (args, int);
1708 format = va_arg (args, char *);
1709 #endif
1710 print_spaces_filtered (spaces, gdb_stdout);
1711 vfprintf_filtered (gdb_stdout, format, args);
1712 va_end (args);
1713 }
1714
1715 /* Easy -- but watch out!
1716
1717 This routine is *not* a replacement for puts()! puts() appends a newline.
1718 This one doesn't, and had better not! */
1719
1720 void
1721 puts_filtered (string)
1722 const char *string;
1723 {
1724 fputs_filtered (string, gdb_stdout);
1725 }
1726
1727 void
1728 puts_unfiltered (string)
1729 const char *string;
1730 {
1731 fputs_unfiltered (string, gdb_stdout);
1732 }
1733
1734 /* Return a pointer to N spaces and a null. The pointer is good
1735 until the next call to here. */
1736 char *
1737 n_spaces (n)
1738 int n;
1739 {
1740 register char *t;
1741 static char *spaces;
1742 static int max_spaces;
1743
1744 if (n > max_spaces)
1745 {
1746 if (spaces)
1747 free (spaces);
1748 spaces = (char *) xmalloc (n+1);
1749 for (t = spaces+n; t != spaces;)
1750 *--t = ' ';
1751 spaces[n] = '\0';
1752 max_spaces = n;
1753 }
1754
1755 return spaces + max_spaces - n;
1756 }
1757
1758 /* Print N spaces. */
1759 void
1760 print_spaces_filtered (n, stream)
1761 int n;
1762 FILE *stream;
1763 {
1764 fputs_filtered (n_spaces (n), stream);
1765 }
1766 \f
1767 /* C++ demangler stuff. */
1768
1769 /* fprintf_symbol_filtered attempts to demangle NAME, a symbol in language
1770 LANG, using demangling args ARG_MODE, and print it filtered to STREAM.
1771 If the name is not mangled, or the language for the name is unknown, or
1772 demangling is off, the name is printed in its "raw" form. */
1773
1774 void
1775 fprintf_symbol_filtered (stream, name, lang, arg_mode)
1776 FILE *stream;
1777 char *name;
1778 enum language lang;
1779 int arg_mode;
1780 {
1781 char *demangled;
1782
1783 if (name != NULL)
1784 {
1785 /* If user wants to see raw output, no problem. */
1786 if (!demangle)
1787 {
1788 fputs_filtered (name, stream);
1789 }
1790 else
1791 {
1792 switch (lang)
1793 {
1794 case language_cplus:
1795 demangled = cplus_demangle (name, arg_mode);
1796 break;
1797 case language_chill:
1798 demangled = chill_demangle (name);
1799 break;
1800 default:
1801 demangled = NULL;
1802 break;
1803 }
1804 fputs_filtered (demangled ? demangled : name, stream);
1805 if (demangled != NULL)
1806 {
1807 free (demangled);
1808 }
1809 }
1810 }
1811 }
1812
1813 /* Do a strcmp() type operation on STRING1 and STRING2, ignoring any
1814 differences in whitespace. Returns 0 if they match, non-zero if they
1815 don't (slightly different than strcmp()'s range of return values).
1816
1817 As an extra hack, string1=="FOO(ARGS)" matches string2=="FOO".
1818 This "feature" is useful when searching for matching C++ function names
1819 (such as if the user types 'break FOO', where FOO is a mangled C++
1820 function). */
1821
1822 int
1823 strcmp_iw (string1, string2)
1824 const char *string1;
1825 const char *string2;
1826 {
1827 while ((*string1 != '\0') && (*string2 != '\0'))
1828 {
1829 while (isspace (*string1))
1830 {
1831 string1++;
1832 }
1833 while (isspace (*string2))
1834 {
1835 string2++;
1836 }
1837 if (*string1 != *string2)
1838 {
1839 break;
1840 }
1841 if (*string1 != '\0')
1842 {
1843 string1++;
1844 string2++;
1845 }
1846 }
1847 return (*string1 != '\0' && *string1 != '(') || (*string2 != '\0');
1848 }
1849
1850 \f
1851 void
1852 initialize_utils ()
1853 {
1854 struct cmd_list_element *c;
1855
1856 c = add_set_cmd ("width", class_support, var_uinteger,
1857 (char *)&chars_per_line,
1858 "Set number of characters gdb thinks are in a line.",
1859 &setlist);
1860 add_show_from_set (c, &showlist);
1861 c->function.sfunc = set_width_command;
1862
1863 add_show_from_set
1864 (add_set_cmd ("height", class_support,
1865 var_uinteger, (char *)&lines_per_page,
1866 "Set number of lines gdb thinks are in a page.", &setlist),
1867 &showlist);
1868
1869 /* These defaults will be used if we are unable to get the correct
1870 values from termcap. */
1871 #if defined(__GO32__) || defined(__WIN32__)
1872 lines_per_page = ScreenRows();
1873 chars_per_line = ScreenCols();
1874 #else
1875 lines_per_page = 24;
1876 chars_per_line = 80;
1877
1878 #ifndef MPW
1879 /* No termcap under MPW, although might be cool to do something
1880 by looking at worksheet or console window sizes. */
1881 /* Initialize the screen height and width from termcap. */
1882 {
1883 char *termtype = getenv ("TERM");
1884
1885 /* Positive means success, nonpositive means failure. */
1886 int status;
1887
1888 /* 2048 is large enough for all known terminals, according to the
1889 GNU termcap manual. */
1890 char term_buffer[2048];
1891
1892 if (termtype)
1893 {
1894 status = tgetent (term_buffer, termtype);
1895 if (status > 0)
1896 {
1897 int val;
1898
1899 val = tgetnum ("li");
1900 if (val >= 0)
1901 lines_per_page = val;
1902 else
1903 /* The number of lines per page is not mentioned
1904 in the terminal description. This probably means
1905 that paging is not useful (e.g. emacs shell window),
1906 so disable paging. */
1907 lines_per_page = UINT_MAX;
1908
1909 val = tgetnum ("co");
1910 if (val >= 0)
1911 chars_per_line = val;
1912 }
1913 }
1914 }
1915 #endif /* MPW */
1916
1917 #if defined(SIGWINCH) && defined(SIGWINCH_HANDLER)
1918
1919 /* If there is a better way to determine the window size, use it. */
1920 SIGWINCH_HANDLER ();
1921 #endif
1922 #endif
1923 /* If the output is not a terminal, don't paginate it. */
1924 if (!ISATTY (gdb_stdout))
1925 lines_per_page = UINT_MAX;
1926
1927 set_width_command ((char *)NULL, 0, c);
1928
1929 add_show_from_set
1930 (add_set_cmd ("demangle", class_support, var_boolean,
1931 (char *)&demangle,
1932 "Set demangling of encoded C++ names when displaying symbols.",
1933 &setprintlist),
1934 &showprintlist);
1935
1936 add_show_from_set
1937 (add_set_cmd ("sevenbit-strings", class_support, var_boolean,
1938 (char *)&sevenbit_strings,
1939 "Set printing of 8-bit characters in strings as \\nnn.",
1940 &setprintlist),
1941 &showprintlist);
1942
1943 add_show_from_set
1944 (add_set_cmd ("asm-demangle", class_support, var_boolean,
1945 (char *)&asm_demangle,
1946 "Set demangling of C++ names in disassembly listings.",
1947 &setprintlist),
1948 &showprintlist);
1949 }
1950
1951 /* Machine specific function to handle SIGWINCH signal. */
1952
1953 #ifdef SIGWINCH_HANDLER_BODY
1954 SIGWINCH_HANDLER_BODY
1955 #endif
1956 \f
1957 /* Support for converting target fp numbers into host DOUBLEST format. */
1958
1959 /* XXX - This code should really be in libiberty/floatformat.c, however
1960 configuration issues with libiberty made this very difficult to do in the
1961 available time. */
1962
1963 #include "floatformat.h"
1964 #include <math.h> /* ldexp */
1965
1966 /* The odds that CHAR_BIT will be anything but 8 are low enough that I'm not
1967 going to bother with trying to muck around with whether it is defined in
1968 a system header, what we do if not, etc. */
1969 #define FLOATFORMAT_CHAR_BIT 8
1970
1971 static unsigned long get_field PARAMS ((unsigned char *,
1972 enum floatformat_byteorders,
1973 unsigned int,
1974 unsigned int,
1975 unsigned int));
1976
1977 /* Extract a field which starts at START and is LEN bytes long. DATA and
1978 TOTAL_LEN are the thing we are extracting it from, in byteorder ORDER. */
1979 static unsigned long
1980 get_field (data, order, total_len, start, len)
1981 unsigned char *data;
1982 enum floatformat_byteorders order;
1983 unsigned int total_len;
1984 unsigned int start;
1985 unsigned int len;
1986 {
1987 unsigned long result;
1988 unsigned int cur_byte;
1989 int cur_bitshift;
1990
1991 /* Start at the least significant part of the field. */
1992 cur_byte = (start + len) / FLOATFORMAT_CHAR_BIT;
1993 if (order == floatformat_little)
1994 cur_byte = (total_len / FLOATFORMAT_CHAR_BIT) - cur_byte - 1;
1995 cur_bitshift =
1996 ((start + len) % FLOATFORMAT_CHAR_BIT) - FLOATFORMAT_CHAR_BIT;
1997 result = *(data + cur_byte) >> (-cur_bitshift);
1998 cur_bitshift += FLOATFORMAT_CHAR_BIT;
1999 if (order == floatformat_little)
2000 ++cur_byte;
2001 else
2002 --cur_byte;
2003
2004 /* Move towards the most significant part of the field. */
2005 while (cur_bitshift < len)
2006 {
2007 if (len - cur_bitshift < FLOATFORMAT_CHAR_BIT)
2008 /* This is the last byte; zero out the bits which are not part of
2009 this field. */
2010 result |=
2011 (*(data + cur_byte) & ((1 << (len - cur_bitshift)) - 1))
2012 << cur_bitshift;
2013 else
2014 result |= *(data + cur_byte) << cur_bitshift;
2015 cur_bitshift += FLOATFORMAT_CHAR_BIT;
2016 if (order == floatformat_little)
2017 ++cur_byte;
2018 else
2019 --cur_byte;
2020 }
2021 return result;
2022 }
2023
2024 /* Convert from FMT to a DOUBLEST.
2025 FROM is the address of the extended float.
2026 Store the DOUBLEST in *TO. */
2027
2028 void
2029 floatformat_to_doublest (fmt, from, to)
2030 const struct floatformat *fmt;
2031 char *from;
2032 DOUBLEST *to;
2033 {
2034 unsigned char *ufrom = (unsigned char *)from;
2035 DOUBLEST dto;
2036 long exponent;
2037 unsigned long mant;
2038 unsigned int mant_bits, mant_off;
2039 int mant_bits_left;
2040 int special_exponent; /* It's a NaN, denorm or zero */
2041
2042 exponent = get_field (ufrom, fmt->byteorder, fmt->totalsize,
2043 fmt->exp_start, fmt->exp_len);
2044 /* Note that if exponent indicates a NaN, we can't really do anything useful
2045 (not knowing if the host has NaN's, or how to build one). So it will
2046 end up as an infinity or something close; that is OK. */
2047
2048 mant_bits_left = fmt->man_len;
2049 mant_off = fmt->man_start;
2050 dto = 0.0;
2051
2052 special_exponent = exponent == 0 || exponent == fmt->exp_nan;
2053
2054 /* Don't bias zero's, denorms or NaNs. */
2055 if (!special_exponent)
2056 exponent -= fmt->exp_bias;
2057
2058 /* Build the result algebraically. Might go infinite, underflow, etc;
2059 who cares. */
2060
2061 /* If this format uses a hidden bit, explicitly add it in now. Otherwise,
2062 increment the exponent by one to account for the integer bit. */
2063
2064 if (!special_exponent)
2065 if (fmt->intbit == floatformat_intbit_no)
2066 dto = ldexp (1.0, exponent);
2067 else
2068 exponent++;
2069
2070 while (mant_bits_left > 0)
2071 {
2072 mant_bits = min (mant_bits_left, 32);
2073
2074 mant = get_field (ufrom, fmt->byteorder, fmt->totalsize,
2075 mant_off, mant_bits);
2076
2077 dto += ldexp ((double)mant, exponent - mant_bits);
2078 exponent -= mant_bits;
2079 mant_off += mant_bits;
2080 mant_bits_left -= mant_bits;
2081 }
2082
2083 /* Negate it if negative. */
2084 if (get_field (ufrom, fmt->byteorder, fmt->totalsize, fmt->sign_start, 1))
2085 dto = -dto;
2086 *to = dto;
2087 }
2088 \f
2089 static void put_field PARAMS ((unsigned char *, enum floatformat_byteorders,
2090 unsigned int,
2091 unsigned int,
2092 unsigned int,
2093 unsigned long));
2094
2095 /* Set a field which starts at START and is LEN bytes long. DATA and
2096 TOTAL_LEN are the thing we are extracting it from, in byteorder ORDER. */
2097 static void
2098 put_field (data, order, total_len, start, len, stuff_to_put)
2099 unsigned char *data;
2100 enum floatformat_byteorders order;
2101 unsigned int total_len;
2102 unsigned int start;
2103 unsigned int len;
2104 unsigned long stuff_to_put;
2105 {
2106 unsigned int cur_byte;
2107 int cur_bitshift;
2108
2109 /* Start at the least significant part of the field. */
2110 cur_byte = (start + len) / FLOATFORMAT_CHAR_BIT;
2111 if (order == floatformat_little)
2112 cur_byte = (total_len / FLOATFORMAT_CHAR_BIT) - cur_byte - 1;
2113 cur_bitshift =
2114 ((start + len) % FLOATFORMAT_CHAR_BIT) - FLOATFORMAT_CHAR_BIT;
2115 *(data + cur_byte) &=
2116 ~(((1 << ((start + len) % FLOATFORMAT_CHAR_BIT)) - 1) << (-cur_bitshift));
2117 *(data + cur_byte) |=
2118 (stuff_to_put & ((1 << FLOATFORMAT_CHAR_BIT) - 1)) << (-cur_bitshift);
2119 cur_bitshift += FLOATFORMAT_CHAR_BIT;
2120 if (order == floatformat_little)
2121 ++cur_byte;
2122 else
2123 --cur_byte;
2124
2125 /* Move towards the most significant part of the field. */
2126 while (cur_bitshift < len)
2127 {
2128 if (len - cur_bitshift < FLOATFORMAT_CHAR_BIT)
2129 {
2130 /* This is the last byte. */
2131 *(data + cur_byte) &=
2132 ~((1 << (len - cur_bitshift)) - 1);
2133 *(data + cur_byte) |= (stuff_to_put >> cur_bitshift);
2134 }
2135 else
2136 *(data + cur_byte) = ((stuff_to_put >> cur_bitshift)
2137 & ((1 << FLOATFORMAT_CHAR_BIT) - 1));
2138 cur_bitshift += FLOATFORMAT_CHAR_BIT;
2139 if (order == floatformat_little)
2140 ++cur_byte;
2141 else
2142 --cur_byte;
2143 }
2144 }
2145
2146 #ifdef HAVE_LONG_DOUBLE
2147 /* Return the fractional part of VALUE, and put the exponent of VALUE in *EPTR.
2148 The range of the returned value is >= 0.5 and < 1.0. This is equivalent to
2149 frexp, but operates on the long double data type. */
2150
2151 static long double ldfrexp PARAMS ((long double value, int *eptr));
2152
2153 static long double
2154 ldfrexp (value, eptr)
2155 long double value;
2156 int *eptr;
2157 {
2158 long double tmp;
2159 int exp;
2160
2161 /* Unfortunately, there are no portable functions for extracting the exponent
2162 of a long double, so we have to do it iteratively by multiplying or dividing
2163 by two until the fraction is between 0.5 and 1.0. */
2164
2165 if (value < 0.0l)
2166 value = -value;
2167
2168 tmp = 1.0l;
2169 exp = 0;
2170
2171 if (value >= tmp) /* Value >= 1.0 */
2172 while (value >= tmp)
2173 {
2174 tmp *= 2.0l;
2175 exp++;
2176 }
2177 else if (value != 0.0l) /* Value < 1.0 and > 0.0 */
2178 {
2179 while (value < tmp)
2180 {
2181 tmp /= 2.0l;
2182 exp--;
2183 }
2184 tmp *= 2.0l;
2185 exp++;
2186 }
2187
2188 *eptr = exp;
2189 return value/tmp;
2190 }
2191 #endif /* HAVE_LONG_DOUBLE */
2192
2193
2194 /* The converse: convert the DOUBLEST *FROM to an extended float
2195 and store where TO points. Neither FROM nor TO have any alignment
2196 restrictions. */
2197
2198 void
2199 floatformat_from_doublest (fmt, from, to)
2200 CONST struct floatformat *fmt;
2201 DOUBLEST *from;
2202 char *to;
2203 {
2204 DOUBLEST dfrom;
2205 int exponent;
2206 DOUBLEST mant;
2207 unsigned int mant_bits, mant_off;
2208 int mant_bits_left;
2209 unsigned char *uto = (unsigned char *)to;
2210
2211 memcpy (&dfrom, from, sizeof (dfrom));
2212 memset (uto, 0, fmt->totalsize / FLOATFORMAT_CHAR_BIT);
2213 if (dfrom == 0)
2214 return; /* Result is zero */
2215 if (dfrom != dfrom)
2216 {
2217 /* From is NaN */
2218 put_field (uto, fmt->byteorder, fmt->totalsize, fmt->exp_start,
2219 fmt->exp_len, fmt->exp_nan);
2220 /* Be sure it's not infinity, but NaN value is irrel */
2221 put_field (uto, fmt->byteorder, fmt->totalsize, fmt->man_start,
2222 32, 1);
2223 return;
2224 }
2225
2226 /* If negative, set the sign bit. */
2227 if (dfrom < 0)
2228 {
2229 put_field (uto, fmt->byteorder, fmt->totalsize, fmt->sign_start, 1, 1);
2230 dfrom = -dfrom;
2231 }
2232
2233 /* How to tell an infinity from an ordinary number? FIXME-someday */
2234
2235 #ifdef HAVE_LONG_DOUBLE
2236 mant = ldfrexp (dfrom, &exponent);
2237 #else
2238 mant = frexp (dfrom, &exponent);
2239 #endif
2240
2241 put_field (uto, fmt->byteorder, fmt->totalsize, fmt->exp_start, fmt->exp_len,
2242 exponent + fmt->exp_bias - 1);
2243
2244 mant_bits_left = fmt->man_len;
2245 mant_off = fmt->man_start;
2246 while (mant_bits_left > 0)
2247 {
2248 unsigned long mant_long;
2249 mant_bits = mant_bits_left < 32 ? mant_bits_left : 32;
2250
2251 mant *= 4294967296.0;
2252 mant_long = (unsigned long)mant;
2253 mant -= mant_long;
2254
2255 /* If the integer bit is implicit, then we need to discard it.
2256 If we are discarding a zero, we should be (but are not) creating
2257 a denormalized number which means adjusting the exponent
2258 (I think). */
2259 if (mant_bits_left == fmt->man_len
2260 && fmt->intbit == floatformat_intbit_no)
2261 {
2262 mant_long &= 0x7fffffff;
2263 mant_bits -= 1;
2264 }
2265 else if (mant_bits < 32)
2266 {
2267 /* The bits we want are in the most significant MANT_BITS bits of
2268 mant_long. Move them to the least significant. */
2269 mant_long >>= 32 - mant_bits;
2270 }
2271
2272 put_field (uto, fmt->byteorder, fmt->totalsize,
2273 mant_off, mant_bits, mant_long);
2274 mant_off += mant_bits;
2275 mant_bits_left -= mant_bits;
2276 }
2277 }