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