]> git.ipfire.org Git - thirdparty/binutils-gdb.git/blob - gdb/utils.c
import gdb-1999-09-21
[thirdparty/binutils-gdb.git] / gdb / utils.c
1 /* General utility routines for GDB, the GNU debugger.
2 Copyright 1986, 89, 90, 91, 92, 95, 96, 1998 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,
19 Boston, MA 02111-1307, USA. */
20
21 #include "defs.h"
22 #include <ctype.h>
23 #include "gdb_string.h"
24 #include "event-loop.h"
25 #include "event-top.h"
26
27 #ifdef HAVE_CURSES_H
28 #include <curses.h>
29 #endif
30 #ifdef HAVE_TERM_H
31 #include <term.h>
32 #endif
33
34 /* SunOS's curses.h has a '#define reg register' in it. Thank you Sun. */
35 #ifdef reg
36 #undef reg
37 #endif
38
39 #include "signals.h"
40 #include "gdbcmd.h"
41 #include "serial.h"
42 #include "bfd.h"
43 #include "target.h"
44 #include "demangle.h"
45 #include "expression.h"
46 #include "language.h"
47 #include "annotate.h"
48
49 #include <readline/readline.h>
50
51 /* readline defines this. */
52 #undef savestring
53
54 void (*error_begin_hook) PARAMS ((void));
55
56 /* Prototypes for local functions */
57
58 static void vfprintf_maybe_filtered PARAMS ((GDB_FILE *, const char *,
59 va_list, int));
60
61 static void fputs_maybe_filtered PARAMS ((const char *, GDB_FILE *, int));
62
63 #if defined (USE_MMALLOC) && !defined (NO_MMCHECK)
64 static void malloc_botch PARAMS ((void));
65 #endif
66
67 static void
68 prompt_for_continue PARAMS ((void));
69
70 static void
71 set_width_command PARAMS ((char *, int, struct cmd_list_element *));
72
73 static void
74 set_width PARAMS ((void));
75
76 #ifndef GDB_FILE_ISATTY
77 #define GDB_FILE_ISATTY(GDB_FILE_PTR) (gdb_file_isatty(GDB_FILE_PTR))
78 #endif
79
80 /* Chain of cleanup actions established with make_cleanup,
81 to be executed if an error happens. */
82
83 static struct cleanup *cleanup_chain; /* cleaned up after a failed command */
84 static struct cleanup *final_cleanup_chain; /* cleaned up when gdb exits */
85 static struct cleanup *run_cleanup_chain; /* cleaned up on each 'run' */
86 static struct cleanup *exec_cleanup_chain; /* cleaned up on each execution command */
87
88 /* Pointer to what is left to do for an execution command after the
89 target stops. Used only in asynchronous mode, by targets that
90 support async execution. The finish and until commands use it. So
91 does the target extended-remote command. */
92 struct continuation *cmd_continuation;
93
94 /* Nonzero if we have job control. */
95
96 int job_control;
97
98 /* Nonzero means a quit has been requested. */
99
100 int quit_flag;
101
102 /* Nonzero means quit immediately if Control-C is typed now, rather
103 than waiting until QUIT is executed. Be careful in setting this;
104 code which executes with immediate_quit set has to be very careful
105 about being able to deal with being interrupted at any time. It is
106 almost always better to use QUIT; the only exception I can think of
107 is being able to quit out of a system call (using EINTR loses if
108 the SIGINT happens between the previous QUIT and the system call).
109 To immediately quit in the case in which a SIGINT happens between
110 the previous QUIT and setting immediate_quit (desirable anytime we
111 expect to block), call QUIT after setting immediate_quit. */
112
113 int immediate_quit;
114
115 /* Nonzero means that encoded C++ names should be printed out in their
116 C++ form rather than raw. */
117
118 int demangle = 1;
119
120 /* Nonzero means that encoded C++ names should be printed out in their
121 C++ form even in assembler language displays. If this is set, but
122 DEMANGLE is zero, names are printed raw, i.e. DEMANGLE controls. */
123
124 int asm_demangle = 0;
125
126 /* Nonzero means that strings with character values >0x7F should be printed
127 as octal escapes. Zero means just print the value (e.g. it's an
128 international character, and the terminal or window can cope.) */
129
130 int sevenbit_strings = 0;
131
132 /* String to be printed before error messages, if any. */
133
134 char *error_pre_print;
135
136 /* String to be printed before quit messages, if any. */
137
138 char *quit_pre_print;
139
140 /* String to be printed before warning messages, if any. */
141
142 char *warning_pre_print = "\nwarning: ";
143
144 int pagination_enabled = 1;
145 \f
146
147 /* Add a new cleanup to the cleanup_chain,
148 and return the previous chain pointer
149 to be passed later to do_cleanups or discard_cleanups.
150 Args are FUNCTION to clean up with, and ARG to pass to it. */
151
152 struct cleanup *
153 make_cleanup (function, arg)
154 void (*function) PARAMS ((PTR));
155 PTR arg;
156 {
157 return make_my_cleanup (&cleanup_chain, function, arg);
158 }
159
160 struct cleanup *
161 make_final_cleanup (function, arg)
162 void (*function) PARAMS ((PTR));
163 PTR arg;
164 {
165 return make_my_cleanup (&final_cleanup_chain, function, arg);
166 }
167
168 struct cleanup *
169 make_run_cleanup (function, arg)
170 void (*function) PARAMS ((PTR));
171 PTR arg;
172 {
173 return make_my_cleanup (&run_cleanup_chain, function, arg);
174 }
175
176 struct cleanup *
177 make_exec_cleanup (function, arg)
178 void (*function) PARAMS ((PTR));
179 PTR arg;
180 {
181 return make_my_cleanup (&exec_cleanup_chain, function, arg);
182 }
183
184 static void
185 do_freeargv (arg)
186 void *arg;
187 {
188 freeargv ((char **) arg);
189 }
190
191 struct cleanup *
192 make_cleanup_freeargv (arg)
193 char **arg;
194 {
195 return make_my_cleanup (&cleanup_chain, do_freeargv, arg);
196 }
197
198 struct cleanup *
199 make_my_cleanup (pmy_chain, function, arg)
200 struct cleanup **pmy_chain;
201 void (*function) PARAMS ((PTR));
202 PTR arg;
203 {
204 register struct cleanup *new
205 = (struct cleanup *) xmalloc (sizeof (struct cleanup));
206 register struct cleanup *old_chain = *pmy_chain;
207
208 new->next = *pmy_chain;
209 new->function = function;
210 new->arg = arg;
211 *pmy_chain = new;
212
213 return old_chain;
214 }
215
216 /* Discard cleanups and do the actions they describe
217 until we get back to the point OLD_CHAIN in the cleanup_chain. */
218
219 void
220 do_cleanups (old_chain)
221 register struct cleanup *old_chain;
222 {
223 do_my_cleanups (&cleanup_chain, old_chain);
224 }
225
226 void
227 do_final_cleanups (old_chain)
228 register struct cleanup *old_chain;
229 {
230 do_my_cleanups (&final_cleanup_chain, old_chain);
231 }
232
233 void
234 do_run_cleanups (old_chain)
235 register struct cleanup *old_chain;
236 {
237 do_my_cleanups (&run_cleanup_chain, old_chain);
238 }
239
240 void
241 do_exec_cleanups (old_chain)
242 register struct cleanup *old_chain;
243 {
244 do_my_cleanups (&exec_cleanup_chain, old_chain);
245 }
246
247 void
248 do_my_cleanups (pmy_chain, old_chain)
249 register struct cleanup **pmy_chain;
250 register struct cleanup *old_chain;
251 {
252 register struct cleanup *ptr;
253 while ((ptr = *pmy_chain) != old_chain)
254 {
255 *pmy_chain = ptr->next; /* Do this first incase recursion */
256 (*ptr->function) (ptr->arg);
257 free (ptr);
258 }
259 }
260
261 /* Discard cleanups, not doing the actions they describe,
262 until we get back to the point OLD_CHAIN in the cleanup_chain. */
263
264 void
265 discard_cleanups (old_chain)
266 register struct cleanup *old_chain;
267 {
268 discard_my_cleanups (&cleanup_chain, old_chain);
269 }
270
271 void
272 discard_final_cleanups (old_chain)
273 register struct cleanup *old_chain;
274 {
275 discard_my_cleanups (&final_cleanup_chain, old_chain);
276 }
277
278 void
279 discard_my_cleanups (pmy_chain, old_chain)
280 register struct cleanup **pmy_chain;
281 register struct cleanup *old_chain;
282 {
283 register struct cleanup *ptr;
284 while ((ptr = *pmy_chain) != old_chain)
285 {
286 *pmy_chain = ptr->next;
287 free ((PTR) ptr);
288 }
289 }
290
291 /* Set the cleanup_chain to 0, and return the old cleanup chain. */
292 struct cleanup *
293 save_cleanups ()
294 {
295 return save_my_cleanups (&cleanup_chain);
296 }
297
298 struct cleanup *
299 save_final_cleanups ()
300 {
301 return save_my_cleanups (&final_cleanup_chain);
302 }
303
304 struct cleanup *
305 save_my_cleanups (pmy_chain)
306 struct cleanup **pmy_chain;
307 {
308 struct cleanup *old_chain = *pmy_chain;
309
310 *pmy_chain = 0;
311 return old_chain;
312 }
313
314 /* Restore the cleanup chain from a previously saved chain. */
315 void
316 restore_cleanups (chain)
317 struct cleanup *chain;
318 {
319 restore_my_cleanups (&cleanup_chain, chain);
320 }
321
322 void
323 restore_final_cleanups (chain)
324 struct cleanup *chain;
325 {
326 restore_my_cleanups (&final_cleanup_chain, chain);
327 }
328
329 void
330 restore_my_cleanups (pmy_chain, chain)
331 struct cleanup **pmy_chain;
332 struct cleanup *chain;
333 {
334 *pmy_chain = chain;
335 }
336
337 /* This function is useful for cleanups.
338 Do
339
340 foo = xmalloc (...);
341 old_chain = make_cleanup (free_current_contents, &foo);
342
343 to arrange to free the object thus allocated. */
344
345 void
346 free_current_contents (location)
347 char **location;
348 {
349 free (*location);
350 }
351
352 /* Provide a known function that does nothing, to use as a base for
353 for a possibly long chain of cleanups. This is useful where we
354 use the cleanup chain for handling normal cleanups as well as dealing
355 with cleanups that need to be done as a result of a call to error().
356 In such cases, we may not be certain where the first cleanup is, unless
357 we have a do-nothing one to always use as the base. */
358
359 /* ARGSUSED */
360 void
361 null_cleanup (arg)
362 PTR arg;
363 {
364 }
365
366 /* Add a continuation to the continuation list, the gloabl list
367 cmd_continuation. */
368 void
369 add_continuation (continuation_hook, arg_list)
370 void (*continuation_hook) PARAMS ((struct continuation_arg *));
371 struct continuation_arg *arg_list;
372 {
373 struct continuation *continuation_ptr;
374
375 continuation_ptr = (struct continuation *) xmalloc (sizeof (struct continuation));
376 continuation_ptr->continuation_hook = continuation_hook;
377 continuation_ptr->arg_list = arg_list;
378 continuation_ptr->next = cmd_continuation;
379 cmd_continuation = continuation_ptr;
380 }
381
382 /* Walk down the cmd_continuation list, and execute all the
383 continuations. */
384 void
385 do_all_continuations ()
386 {
387 struct continuation *continuation_ptr;
388
389 while (cmd_continuation)
390 {
391 (cmd_continuation->continuation_hook) (cmd_continuation->arg_list);
392 continuation_ptr = cmd_continuation;
393 cmd_continuation = continuation_ptr->next;
394 free (continuation_ptr);
395 }
396 }
397
398 /* Walk down the cmd_continuation list, and get rid of all the
399 continuations. */
400 void
401 discard_all_continuations ()
402 {
403 struct continuation *continuation_ptr;
404
405 while (cmd_continuation)
406 {
407 continuation_ptr = cmd_continuation;
408 cmd_continuation = continuation_ptr->next;
409 free (continuation_ptr);
410 }
411 }
412
413 \f
414
415 /* Print a warning message. Way to use this is to call warning_begin,
416 output the warning message (use unfiltered output to gdb_stderr),
417 ending in a newline. There is not currently a warning_end that you
418 call afterwards, but such a thing might be added if it is useful
419 for a GUI to separate warning messages from other output.
420
421 FIXME: Why do warnings use unfiltered output and errors filtered?
422 Is this anything other than a historical accident? */
423
424 void
425 warning_begin ()
426 {
427 target_terminal_ours ();
428 wrap_here (""); /* Force out any buffered output */
429 gdb_flush (gdb_stdout);
430 if (warning_pre_print)
431 fprintf_unfiltered (gdb_stderr, warning_pre_print);
432 }
433
434 /* Print a warning message.
435 The first argument STRING is the warning message, used as a fprintf string,
436 and the remaining args are passed as arguments to it.
437 The primary difference between warnings and errors is that a warning
438 does not force the return to command level. */
439
440 void
441 warning (const char *string,...)
442 {
443 va_list args;
444 va_start (args, string);
445 if (warning_hook)
446 (*warning_hook) (string, args);
447 else
448 {
449 warning_begin ();
450 vfprintf_unfiltered (gdb_stderr, string, args);
451 fprintf_unfiltered (gdb_stderr, "\n");
452 va_end (args);
453 }
454 }
455
456 /* Start the printing of an error message. Way to use this is to call
457 this, output the error message (use filtered output to gdb_stderr
458 (FIXME: Some callers, like memory_error, use gdb_stdout)), ending
459 in a newline, and then call return_to_top_level (RETURN_ERROR).
460 error() provides a convenient way to do this for the special case
461 that the error message can be formatted with a single printf call,
462 but this is more general. */
463 void
464 error_begin ()
465 {
466 if (error_begin_hook)
467 error_begin_hook ();
468
469 target_terminal_ours ();
470 wrap_here (""); /* Force out any buffered output */
471 gdb_flush (gdb_stdout);
472
473 annotate_error_begin ();
474
475 if (error_pre_print)
476 fprintf_filtered (gdb_stderr, error_pre_print);
477 }
478
479 /* Print an error message and return to command level.
480 The first argument STRING is the error message, used as a fprintf string,
481 and the remaining args are passed as arguments to it. */
482
483 NORETURN void
484 error (const char *string,...)
485 {
486 va_list args;
487 va_start (args, string);
488 if (error_hook)
489 (*error_hook) ();
490 else
491 {
492 error_begin ();
493 vfprintf_filtered (gdb_stderr, string, args);
494 fprintf_filtered (gdb_stderr, "\n");
495 va_end (args);
496 return_to_top_level (RETURN_ERROR);
497 }
498 }
499
500
501 /* Print a message reporting an internal error. Ask the user if they
502 want to continue, dump core, or just exit. */
503
504 NORETURN void
505 internal_error (char *string, ...)
506 {
507 static char msg[] = "Internal GDB error: recursive internal error.\n";
508 static int dejavu = 0;
509 va_list args;
510 int continue_p;
511 int dump_core_p;
512
513 /* don't allow infinite error recursion. */
514 switch (dejavu)
515 {
516 case 0:
517 dejavu = 1;
518 break;
519 case 1:
520 dejavu = 2;
521 fputs_unfiltered (msg, gdb_stderr);
522 abort ();
523 default:
524 dejavu = 3;
525 write (STDERR_FILENO, msg, sizeof (msg));
526 exit (1);
527 }
528
529 /* Try to get the message out */
530 fputs_unfiltered ("gdb-internal-error: ", gdb_stderr);
531 va_start (args, string);
532 vfprintf_unfiltered (gdb_stderr, string, args);
533 va_end (args);
534 fputs_unfiltered ("\n", gdb_stderr);
535
536 /* Default (no case) is to quit GDB. When in batch mode this
537 lessens the likelhood of GDB going into an infinate loop. */
538 continue_p = query ("\
539 An internal GDB error was detected. This may make make further\n\
540 debugging unreliable. Continue this debugging session? ");
541
542 /* Default (no case) is to not dump core. Lessen the chance of GDB
543 leaving random core files around. */
544 dump_core_p = query ("\
545 Create a core file containing the current state of GDB? ");
546
547 if (continue_p)
548 {
549 if (dump_core_p)
550 {
551 if (fork () == 0)
552 abort ();
553 }
554 }
555 else
556 {
557 if (dump_core_p)
558 abort ();
559 else
560 exit (1);
561 }
562
563 dejavu = 0;
564 return_to_top_level (RETURN_ERROR);
565 }
566
567 /* The strerror() function can return NULL for errno values that are
568 out of range. Provide a "safe" version that always returns a
569 printable string. */
570
571 char *
572 safe_strerror (errnum)
573 int errnum;
574 {
575 char *msg;
576 static char buf[32];
577
578 if ((msg = strerror (errnum)) == NULL)
579 {
580 sprintf (buf, "(undocumented errno %d)", errnum);
581 msg = buf;
582 }
583 return (msg);
584 }
585
586 /* The strsignal() function can return NULL for signal values that are
587 out of range. Provide a "safe" version that always returns a
588 printable string. */
589
590 char *
591 safe_strsignal (signo)
592 int signo;
593 {
594 char *msg;
595 static char buf[32];
596
597 if ((msg = strsignal (signo)) == NULL)
598 {
599 sprintf (buf, "(undocumented signal %d)", signo);
600 msg = buf;
601 }
602 return (msg);
603 }
604
605
606 /* Print the system error message for errno, and also mention STRING
607 as the file name for which the error was encountered.
608 Then return to command level. */
609
610 NORETURN void
611 perror_with_name (string)
612 char *string;
613 {
614 char *err;
615 char *combined;
616
617 err = safe_strerror (errno);
618 combined = (char *) alloca (strlen (err) + strlen (string) + 3);
619 strcpy (combined, string);
620 strcat (combined, ": ");
621 strcat (combined, err);
622
623 /* I understand setting these is a matter of taste. Still, some people
624 may clear errno but not know about bfd_error. Doing this here is not
625 unreasonable. */
626 bfd_set_error (bfd_error_no_error);
627 errno = 0;
628
629 error ("%s.", combined);
630 }
631
632 /* Print the system error message for ERRCODE, and also mention STRING
633 as the file name for which the error was encountered. */
634
635 void
636 print_sys_errmsg (string, errcode)
637 char *string;
638 int errcode;
639 {
640 char *err;
641 char *combined;
642
643 err = safe_strerror (errcode);
644 combined = (char *) alloca (strlen (err) + strlen (string) + 3);
645 strcpy (combined, string);
646 strcat (combined, ": ");
647 strcat (combined, err);
648
649 /* We want anything which was printed on stdout to come out first, before
650 this message. */
651 gdb_flush (gdb_stdout);
652 fprintf_unfiltered (gdb_stderr, "%s.\n", combined);
653 }
654
655 /* Control C eventually causes this to be called, at a convenient time. */
656
657 void
658 quit ()
659 {
660 serial_t gdb_stdout_serial = serial_fdopen (1);
661
662 target_terminal_ours ();
663
664 /* We want all output to appear now, before we print "Quit". We
665 have 3 levels of buffering we have to flush (it's possible that
666 some of these should be changed to flush the lower-level ones
667 too): */
668
669 /* 1. The _filtered buffer. */
670 wrap_here ((char *) 0);
671
672 /* 2. The stdio buffer. */
673 gdb_flush (gdb_stdout);
674 gdb_flush (gdb_stderr);
675
676 /* 3. The system-level buffer. */
677 SERIAL_DRAIN_OUTPUT (gdb_stdout_serial);
678 SERIAL_UN_FDOPEN (gdb_stdout_serial);
679
680 annotate_error_begin ();
681
682 /* Don't use *_filtered; we don't want to prompt the user to continue. */
683 if (quit_pre_print)
684 fprintf_unfiltered (gdb_stderr, quit_pre_print);
685
686 #ifdef __MSDOS__
687 /* No steenking SIGINT will ever be coming our way when the
688 program is resumed. Don't lie. */
689 fprintf_unfiltered (gdb_stderr, "Quit\n");
690 #else
691 if (job_control
692 /* If there is no terminal switching for this target, then we can't
693 possibly get screwed by the lack of job control. */
694 || current_target.to_terminal_ours == NULL)
695 fprintf_unfiltered (gdb_stderr, "Quit\n");
696 else
697 fprintf_unfiltered (gdb_stderr,
698 "Quit (expect signal SIGINT when the program is resumed)\n");
699 #endif
700 return_to_top_level (RETURN_QUIT);
701 }
702
703
704 #if defined(_MSC_VER) /* should test for wingdb instead? */
705
706 /*
707 * Windows translates all keyboard and mouse events
708 * into a message which is appended to the message
709 * queue for the process.
710 */
711
712 void
713 notice_quit ()
714 {
715 int k = win32pollquit ();
716 if (k == 1)
717 quit_flag = 1;
718 else if (k == 2)
719 immediate_quit = 1;
720 }
721
722 #else /* !defined(__GO32__) && !defined(_MSC_VER) */
723
724 void
725 notice_quit ()
726 {
727 /* Done by signals */
728 }
729
730 #endif /* !defined(__GO32__) && !defined(_MSC_VER) */
731
732 /* Control C comes here */
733 void
734 request_quit (signo)
735 int signo;
736 {
737 quit_flag = 1;
738 /* Restore the signal handler. Harmless with BSD-style signals, needed
739 for System V-style signals. So just always do it, rather than worrying
740 about USG defines and stuff like that. */
741 signal (signo, request_quit);
742
743 #ifdef REQUEST_QUIT
744 REQUEST_QUIT;
745 #else
746 if (immediate_quit)
747 quit ();
748 #endif
749 }
750 \f
751 /* Memory management stuff (malloc friends). */
752
753 /* Make a substitute size_t for non-ANSI compilers. */
754
755 #ifndef HAVE_STDDEF_H
756 #ifndef size_t
757 #define size_t unsigned int
758 #endif
759 #endif
760
761 #if !defined (USE_MMALLOC)
762
763 PTR
764 mmalloc (md, size)
765 PTR md;
766 size_t size;
767 {
768 return malloc (size);
769 }
770
771 PTR
772 mrealloc (md, ptr, size)
773 PTR md;
774 PTR ptr;
775 size_t size;
776 {
777 if (ptr == 0) /* Guard against old realloc's */
778 return malloc (size);
779 else
780 return realloc (ptr, size);
781 }
782
783 void
784 mfree (md, ptr)
785 PTR md;
786 PTR ptr;
787 {
788 free (ptr);
789 }
790
791 #endif /* USE_MMALLOC */
792
793 #if !defined (USE_MMALLOC) || defined (NO_MMCHECK)
794
795 void
796 init_malloc (md)
797 PTR md;
798 {
799 }
800
801 #else /* Have mmalloc and want corruption checking */
802
803 static void
804 malloc_botch ()
805 {
806 fprintf_unfiltered (gdb_stderr, "Memory corruption\n");
807 abort ();
808 }
809
810 /* Attempt to install hooks in mmalloc/mrealloc/mfree for the heap specified
811 by MD, to detect memory corruption. Note that MD may be NULL to specify
812 the default heap that grows via sbrk.
813
814 Note that for freshly created regions, we must call mmcheckf prior to any
815 mallocs in the region. Otherwise, any region which was allocated prior to
816 installing the checking hooks, which is later reallocated or freed, will
817 fail the checks! The mmcheck function only allows initial hooks to be
818 installed before the first mmalloc. However, anytime after we have called
819 mmcheck the first time to install the checking hooks, we can call it again
820 to update the function pointer to the memory corruption handler.
821
822 Returns zero on failure, non-zero on success. */
823
824 #ifndef MMCHECK_FORCE
825 #define MMCHECK_FORCE 0
826 #endif
827
828 void
829 init_malloc (md)
830 PTR md;
831 {
832 if (!mmcheckf (md, malloc_botch, MMCHECK_FORCE))
833 {
834 /* Don't use warning(), which relies on current_target being set
835 to something other than dummy_target, until after
836 initialize_all_files(). */
837
838 fprintf_unfiltered
839 (gdb_stderr, "warning: failed to install memory consistency checks; ");
840 fprintf_unfiltered
841 (gdb_stderr, "configuration should define NO_MMCHECK or MMCHECK_FORCE\n");
842 }
843
844 mmtrace ();
845 }
846
847 #endif /* Have mmalloc and want corruption checking */
848
849 /* Called when a memory allocation fails, with the number of bytes of
850 memory requested in SIZE. */
851
852 NORETURN void
853 nomem (size)
854 long size;
855 {
856 if (size > 0)
857 {
858 internal_error ("virtual memory exhausted: can't allocate %ld bytes.", size);
859 }
860 else
861 {
862 internal_error ("virtual memory exhausted.");
863 }
864 }
865
866 /* Like mmalloc but get error if no storage available, and protect against
867 the caller wanting to allocate zero bytes. Whether to return NULL for
868 a zero byte request, or translate the request into a request for one
869 byte of zero'd storage, is a religious issue. */
870
871 PTR
872 xmmalloc (md, size)
873 PTR md;
874 long size;
875 {
876 register PTR val;
877
878 if (size == 0)
879 {
880 val = NULL;
881 }
882 else if ((val = mmalloc (md, size)) == NULL)
883 {
884 nomem (size);
885 }
886 return (val);
887 }
888
889 /* Like mrealloc but get error if no storage available. */
890
891 PTR
892 xmrealloc (md, ptr, size)
893 PTR md;
894 PTR ptr;
895 long size;
896 {
897 register PTR val;
898
899 if (ptr != NULL)
900 {
901 val = mrealloc (md, ptr, size);
902 }
903 else
904 {
905 val = mmalloc (md, size);
906 }
907 if (val == NULL)
908 {
909 nomem (size);
910 }
911 return (val);
912 }
913
914 /* Like malloc but get error if no storage available, and protect against
915 the caller wanting to allocate zero bytes. */
916
917 PTR
918 xmalloc (size)
919 size_t size;
920 {
921 return (xmmalloc ((PTR) NULL, size));
922 }
923
924 /* Like mrealloc but get error if no storage available. */
925
926 PTR
927 xrealloc (ptr, size)
928 PTR ptr;
929 size_t size;
930 {
931 return (xmrealloc ((PTR) NULL, ptr, size));
932 }
933 \f
934
935 /* My replacement for the read system call.
936 Used like `read' but keeps going if `read' returns too soon. */
937
938 int
939 myread (desc, addr, len)
940 int desc;
941 char *addr;
942 int len;
943 {
944 register int val;
945 int orglen = len;
946
947 while (len > 0)
948 {
949 val = read (desc, addr, len);
950 if (val < 0)
951 return val;
952 if (val == 0)
953 return orglen - len;
954 len -= val;
955 addr += val;
956 }
957 return orglen;
958 }
959 \f
960 /* Make a copy of the string at PTR with SIZE characters
961 (and add a null character at the end in the copy).
962 Uses malloc to get the space. Returns the address of the copy. */
963
964 char *
965 savestring (ptr, size)
966 const char *ptr;
967 int size;
968 {
969 register char *p = (char *) xmalloc (size + 1);
970 memcpy (p, ptr, size);
971 p[size] = 0;
972 return p;
973 }
974
975 char *
976 msavestring (md, ptr, size)
977 PTR md;
978 const char *ptr;
979 int size;
980 {
981 register char *p = (char *) xmmalloc (md, size + 1);
982 memcpy (p, ptr, size);
983 p[size] = 0;
984 return p;
985 }
986
987 /* The "const" is so it compiles under DGUX (which prototypes strsave
988 in <string.h>. FIXME: This should be named "xstrsave", shouldn't it?
989 Doesn't real strsave return NULL if out of memory? */
990 char *
991 strsave (ptr)
992 const char *ptr;
993 {
994 return savestring (ptr, strlen (ptr));
995 }
996
997 char *
998 mstrsave (md, ptr)
999 PTR md;
1000 const char *ptr;
1001 {
1002 return (msavestring (md, ptr, strlen (ptr)));
1003 }
1004
1005 void
1006 print_spaces (n, file)
1007 register int n;
1008 register GDB_FILE *file;
1009 {
1010 fputs_unfiltered (n_spaces (n), file);
1011 }
1012
1013 /* Print a host address. */
1014
1015 void
1016 gdb_print_host_address (void *addr, struct gdb_file *stream)
1017 {
1018
1019 /* We could use the %p conversion specifier to fprintf if we had any
1020 way of knowing whether this host supports it. But the following
1021 should work on the Alpha and on 32 bit machines. */
1022
1023 fprintf_filtered (stream, "0x%lx", (unsigned long) addr);
1024 }
1025
1026 /* Ask user a y-or-n question and return 1 iff answer is yes.
1027 Takes three args which are given to printf to print the question.
1028 The first, a control string, should end in "? ".
1029 It should not say how to answer, because we do that. */
1030
1031 /* VARARGS */
1032 int
1033 query (char *ctlstr,...)
1034 {
1035 va_list args;
1036 register int answer;
1037 register int ans2;
1038 int retval;
1039
1040 va_start (args, ctlstr);
1041
1042 if (query_hook)
1043 {
1044 return query_hook (ctlstr, args);
1045 }
1046
1047 /* Automatically answer "yes" if input is not from a terminal. */
1048 if (!input_from_terminal_p ())
1049 return 1;
1050 #ifdef MPW
1051 /* FIXME Automatically answer "yes" if called from MacGDB. */
1052 if (mac_app)
1053 return 1;
1054 #endif /* MPW */
1055
1056 while (1)
1057 {
1058 wrap_here (""); /* Flush any buffered output */
1059 gdb_flush (gdb_stdout);
1060
1061 if (annotation_level > 1)
1062 printf_filtered ("\n\032\032pre-query\n");
1063
1064 vfprintf_filtered (gdb_stdout, ctlstr, args);
1065 printf_filtered ("(y or n) ");
1066
1067 if (annotation_level > 1)
1068 printf_filtered ("\n\032\032query\n");
1069
1070 #ifdef MPW
1071 /* If not in MacGDB, move to a new line so the entered line doesn't
1072 have a prompt on the front of it. */
1073 if (!mac_app)
1074 fputs_unfiltered ("\n", gdb_stdout);
1075 #endif /* MPW */
1076
1077 wrap_here ("");
1078 gdb_flush (gdb_stdout);
1079
1080 #if defined(TUI)
1081 if (!tui_version || cmdWin == tuiWinWithFocus ())
1082 #endif
1083 answer = fgetc (stdin);
1084 #if defined(TUI)
1085 else
1086 answer = (unsigned char) tuiBufferGetc ();
1087
1088 #endif
1089 clearerr (stdin); /* in case of C-d */
1090 if (answer == EOF) /* C-d */
1091 {
1092 retval = 1;
1093 break;
1094 }
1095 /* Eat rest of input line, to EOF or newline */
1096 if ((answer != '\n') || (tui_version && answer != '\r'))
1097 do
1098 {
1099 #if defined(TUI)
1100 if (!tui_version || cmdWin == tuiWinWithFocus ())
1101 #endif
1102 ans2 = fgetc (stdin);
1103 #if defined(TUI)
1104 else
1105 ans2 = (unsigned char) tuiBufferGetc ();
1106 #endif
1107 clearerr (stdin);
1108 }
1109 while (ans2 != EOF && ans2 != '\n' && ans2 != '\r');
1110 TUIDO (((TuiOpaqueFuncPtr) tui_vStartNewLines, 1));
1111
1112 if (answer >= 'a')
1113 answer -= 040;
1114 if (answer == 'Y')
1115 {
1116 retval = 1;
1117 break;
1118 }
1119 if (answer == 'N')
1120 {
1121 retval = 0;
1122 break;
1123 }
1124 printf_filtered ("Please answer y or n.\n");
1125 }
1126
1127 if (annotation_level > 1)
1128 printf_filtered ("\n\032\032post-query\n");
1129 return retval;
1130 }
1131 \f
1132
1133 /* Parse a C escape sequence. STRING_PTR points to a variable
1134 containing a pointer to the string to parse. That pointer
1135 should point to the character after the \. That pointer
1136 is updated past the characters we use. The value of the
1137 escape sequence is returned.
1138
1139 A negative value means the sequence \ newline was seen,
1140 which is supposed to be equivalent to nothing at all.
1141
1142 If \ is followed by a null character, we return a negative
1143 value and leave the string pointer pointing at the null character.
1144
1145 If \ is followed by 000, we return 0 and leave the string pointer
1146 after the zeros. A value of 0 does not mean end of string. */
1147
1148 int
1149 parse_escape (string_ptr)
1150 char **string_ptr;
1151 {
1152 register int c = *(*string_ptr)++;
1153 switch (c)
1154 {
1155 case 'a':
1156 return 007; /* Bell (alert) char */
1157 case 'b':
1158 return '\b';
1159 case 'e': /* Escape character */
1160 return 033;
1161 case 'f':
1162 return '\f';
1163 case 'n':
1164 return '\n';
1165 case 'r':
1166 return '\r';
1167 case 't':
1168 return '\t';
1169 case 'v':
1170 return '\v';
1171 case '\n':
1172 return -2;
1173 case 0:
1174 (*string_ptr)--;
1175 return 0;
1176 case '^':
1177 c = *(*string_ptr)++;
1178 if (c == '\\')
1179 c = parse_escape (string_ptr);
1180 if (c == '?')
1181 return 0177;
1182 return (c & 0200) | (c & 037);
1183
1184 case '0':
1185 case '1':
1186 case '2':
1187 case '3':
1188 case '4':
1189 case '5':
1190 case '6':
1191 case '7':
1192 {
1193 register int i = c - '0';
1194 register int count = 0;
1195 while (++count < 3)
1196 {
1197 if ((c = *(*string_ptr)++) >= '0' && c <= '7')
1198 {
1199 i *= 8;
1200 i += c - '0';
1201 }
1202 else
1203 {
1204 (*string_ptr)--;
1205 break;
1206 }
1207 }
1208 return i;
1209 }
1210 default:
1211 return c;
1212 }
1213 }
1214 \f
1215 /* Print the character C on STREAM as part of the contents of a literal
1216 string whose delimiter is QUOTER. Note that this routine should only
1217 be call for printing things which are independent of the language
1218 of the program being debugged. */
1219
1220 static void printchar PARAMS ((int c, void (*do_fputs) (const char *, GDB_FILE*), void (*do_fprintf) (GDB_FILE*, const char *, ...), GDB_FILE *stream, int quoter));
1221
1222 static void
1223 printchar (c, do_fputs, do_fprintf, stream, quoter)
1224 int c;
1225 void (*do_fputs) PARAMS ((const char *, GDB_FILE*));
1226 void (*do_fprintf) PARAMS ((GDB_FILE*, const char *, ...));
1227 GDB_FILE *stream;
1228 int quoter;
1229 {
1230
1231 c &= 0xFF; /* Avoid sign bit follies */
1232
1233 if (c < 0x20 || /* Low control chars */
1234 (c >= 0x7F && c < 0xA0) || /* DEL, High controls */
1235 (sevenbit_strings && c >= 0x80))
1236 { /* high order bit set */
1237 switch (c)
1238 {
1239 case '\n':
1240 do_fputs ("\\n", stream);
1241 break;
1242 case '\b':
1243 do_fputs ("\\b", stream);
1244 break;
1245 case '\t':
1246 do_fputs ("\\t", stream);
1247 break;
1248 case '\f':
1249 do_fputs ("\\f", stream);
1250 break;
1251 case '\r':
1252 do_fputs ("\\r", stream);
1253 break;
1254 case '\033':
1255 do_fputs ("\\e", stream);
1256 break;
1257 case '\007':
1258 do_fputs ("\\a", stream);
1259 break;
1260 default:
1261 do_fprintf (stream, "\\%.3o", (unsigned int) c);
1262 break;
1263 }
1264 }
1265 else
1266 {
1267 if (c == '\\' || c == quoter)
1268 do_fputs ("\\", stream);
1269 do_fprintf (stream, "%c", c);
1270 }
1271 }
1272
1273 /* Print the character C on STREAM as part of the contents of a
1274 literal string whose delimiter is QUOTER. Note that these routines
1275 should only be call for printing things which are independent of
1276 the language of the program being debugged. */
1277
1278 void
1279 fputstr_filtered (str, quoter, stream)
1280 const char *str;
1281 int quoter;
1282 GDB_FILE *stream;
1283 {
1284 while (*str)
1285 printchar (*str++, fputs_filtered, fprintf_filtered, stream, quoter);
1286 }
1287
1288 void
1289 fputstr_unfiltered (str, quoter, stream)
1290 const char *str;
1291 int quoter;
1292 GDB_FILE *stream;
1293 {
1294 while (*str)
1295 printchar (*str++, fputs_unfiltered, fprintf_unfiltered, stream, quoter);
1296 }
1297
1298 void
1299 fputstrn_unfiltered (str, n, quoter, stream)
1300 const char *str;
1301 int n;
1302 int quoter;
1303 GDB_FILE *stream;
1304 {
1305 int i;
1306 for (i = 0; i < n; i++)
1307 printchar (str[i], fputs_unfiltered, fprintf_unfiltered, stream, quoter);
1308 }
1309
1310 \f
1311
1312 /* Number of lines per page or UINT_MAX if paging is disabled. */
1313 static unsigned int lines_per_page;
1314 /* Number of chars per line or UNIT_MAX is line folding is disabled. */
1315 static unsigned int chars_per_line;
1316 /* Current count of lines printed on this page, chars on this line. */
1317 static unsigned int lines_printed, chars_printed;
1318
1319 /* Buffer and start column of buffered text, for doing smarter word-
1320 wrapping. When someone calls wrap_here(), we start buffering output
1321 that comes through fputs_filtered(). If we see a newline, we just
1322 spit it out and forget about the wrap_here(). If we see another
1323 wrap_here(), we spit it out and remember the newer one. If we see
1324 the end of the line, we spit out a newline, the indent, and then
1325 the buffered output. */
1326
1327 /* Malloc'd buffer with chars_per_line+2 bytes. Contains characters which
1328 are waiting to be output (they have already been counted in chars_printed).
1329 When wrap_buffer[0] is null, the buffer is empty. */
1330 static char *wrap_buffer;
1331
1332 /* Pointer in wrap_buffer to the next character to fill. */
1333 static char *wrap_pointer;
1334
1335 /* String to indent by if the wrap occurs. Must not be NULL if wrap_column
1336 is non-zero. */
1337 static char *wrap_indent;
1338
1339 /* Column number on the screen where wrap_buffer begins, or 0 if wrapping
1340 is not in effect. */
1341 static int wrap_column;
1342 \f
1343
1344 /* Inialize the lines and chars per page */
1345 void
1346 init_page_info ()
1347 {
1348 #if defined(TUI)
1349 if (tui_version && m_winPtrNotNull (cmdWin))
1350 {
1351 lines_per_page = cmdWin->generic.height;
1352 chars_per_line = cmdWin->generic.width;
1353 }
1354 else
1355 #endif
1356 {
1357 /* These defaults will be used if we are unable to get the correct
1358 values from termcap. */
1359 #if defined(__GO32__)
1360 lines_per_page = ScreenRows ();
1361 chars_per_line = ScreenCols ();
1362 #else
1363 lines_per_page = 24;
1364 chars_per_line = 80;
1365
1366 #if !defined (MPW) && !defined (_WIN32)
1367 /* No termcap under MPW, although might be cool to do something
1368 by looking at worksheet or console window sizes. */
1369 /* Initialize the screen height and width from termcap. */
1370 {
1371 char *termtype = getenv ("TERM");
1372
1373 /* Positive means success, nonpositive means failure. */
1374 int status;
1375
1376 /* 2048 is large enough for all known terminals, according to the
1377 GNU termcap manual. */
1378 char term_buffer[2048];
1379
1380 if (termtype)
1381 {
1382 status = tgetent (term_buffer, termtype);
1383 if (status > 0)
1384 {
1385 int val;
1386 int running_in_emacs = getenv ("EMACS") != NULL;
1387
1388 val = tgetnum ("li");
1389 if (val >= 0 && !running_in_emacs)
1390 lines_per_page = val;
1391 else
1392 /* The number of lines per page is not mentioned
1393 in the terminal description. This probably means
1394 that paging is not useful (e.g. emacs shell window),
1395 so disable paging. */
1396 lines_per_page = UINT_MAX;
1397
1398 val = tgetnum ("co");
1399 if (val >= 0)
1400 chars_per_line = val;
1401 }
1402 }
1403 }
1404 #endif /* MPW */
1405
1406 #if defined(SIGWINCH) && defined(SIGWINCH_HANDLER)
1407
1408 /* If there is a better way to determine the window size, use it. */
1409 SIGWINCH_HANDLER (SIGWINCH);
1410 #endif
1411 #endif
1412 /* If the output is not a terminal, don't paginate it. */
1413 if (!GDB_FILE_ISATTY (gdb_stdout))
1414 lines_per_page = UINT_MAX;
1415 } /* the command_line_version */
1416 set_width ();
1417 }
1418
1419 static void
1420 set_width ()
1421 {
1422 if (chars_per_line == 0)
1423 init_page_info ();
1424
1425 if (!wrap_buffer)
1426 {
1427 wrap_buffer = (char *) xmalloc (chars_per_line + 2);
1428 wrap_buffer[0] = '\0';
1429 }
1430 else
1431 wrap_buffer = (char *) xrealloc (wrap_buffer, chars_per_line + 2);
1432 wrap_pointer = wrap_buffer; /* Start it at the beginning */
1433 }
1434
1435 /* ARGSUSED */
1436 static void
1437 set_width_command (args, from_tty, c)
1438 char *args;
1439 int from_tty;
1440 struct cmd_list_element *c;
1441 {
1442 set_width ();
1443 }
1444
1445 /* Wait, so the user can read what's on the screen. Prompt the user
1446 to continue by pressing RETURN. */
1447
1448 static void
1449 prompt_for_continue ()
1450 {
1451 char *ignore;
1452 char cont_prompt[120];
1453
1454 if (annotation_level > 1)
1455 printf_unfiltered ("\n\032\032pre-prompt-for-continue\n");
1456
1457 strcpy (cont_prompt,
1458 "---Type <return> to continue, or q <return> to quit---");
1459 if (annotation_level > 1)
1460 strcat (cont_prompt, "\n\032\032prompt-for-continue\n");
1461
1462 /* We must do this *before* we call gdb_readline, else it will eventually
1463 call us -- thinking that we're trying to print beyond the end of the
1464 screen. */
1465 reinitialize_more_filter ();
1466
1467 immediate_quit++;
1468 /* On a real operating system, the user can quit with SIGINT.
1469 But not on GO32.
1470
1471 'q' is provided on all systems so users don't have to change habits
1472 from system to system, and because telling them what to do in
1473 the prompt is more user-friendly than expecting them to think of
1474 SIGINT. */
1475 /* Call readline, not gdb_readline, because GO32 readline handles control-C
1476 whereas control-C to gdb_readline will cause the user to get dumped
1477 out to DOS. */
1478 ignore = readline (cont_prompt);
1479
1480 if (annotation_level > 1)
1481 printf_unfiltered ("\n\032\032post-prompt-for-continue\n");
1482
1483 if (ignore)
1484 {
1485 char *p = ignore;
1486 while (*p == ' ' || *p == '\t')
1487 ++p;
1488 if (p[0] == 'q')
1489 {
1490 if (!async_p)
1491 request_quit (SIGINT);
1492 else
1493 async_request_quit (0);
1494 }
1495 free (ignore);
1496 }
1497 immediate_quit--;
1498
1499 /* Now we have to do this again, so that GDB will know that it doesn't
1500 need to save the ---Type <return>--- line at the top of the screen. */
1501 reinitialize_more_filter ();
1502
1503 dont_repeat (); /* Forget prev cmd -- CR won't repeat it. */
1504 }
1505
1506 /* Reinitialize filter; ie. tell it to reset to original values. */
1507
1508 void
1509 reinitialize_more_filter ()
1510 {
1511 lines_printed = 0;
1512 chars_printed = 0;
1513 }
1514
1515 /* Indicate that if the next sequence of characters overflows the line,
1516 a newline should be inserted here rather than when it hits the end.
1517 If INDENT is non-null, it is a string to be printed to indent the
1518 wrapped part on the next line. INDENT must remain accessible until
1519 the next call to wrap_here() or until a newline is printed through
1520 fputs_filtered().
1521
1522 If the line is already overfull, we immediately print a newline and
1523 the indentation, and disable further wrapping.
1524
1525 If we don't know the width of lines, but we know the page height,
1526 we must not wrap words, but should still keep track of newlines
1527 that were explicitly printed.
1528
1529 INDENT should not contain tabs, as that will mess up the char count
1530 on the next line. FIXME.
1531
1532 This routine is guaranteed to force out any output which has been
1533 squirreled away in the wrap_buffer, so wrap_here ((char *)0) can be
1534 used to force out output from the wrap_buffer. */
1535
1536 void
1537 wrap_here (indent)
1538 char *indent;
1539 {
1540 /* This should have been allocated, but be paranoid anyway. */
1541 if (!wrap_buffer)
1542 abort ();
1543
1544 if (wrap_buffer[0])
1545 {
1546 *wrap_pointer = '\0';
1547 fputs_unfiltered (wrap_buffer, gdb_stdout);
1548 }
1549 wrap_pointer = wrap_buffer;
1550 wrap_buffer[0] = '\0';
1551 if (chars_per_line == UINT_MAX) /* No line overflow checking */
1552 {
1553 wrap_column = 0;
1554 }
1555 else if (chars_printed >= chars_per_line)
1556 {
1557 puts_filtered ("\n");
1558 if (indent != NULL)
1559 puts_filtered (indent);
1560 wrap_column = 0;
1561 }
1562 else
1563 {
1564 wrap_column = chars_printed;
1565 if (indent == NULL)
1566 wrap_indent = "";
1567 else
1568 wrap_indent = indent;
1569 }
1570 }
1571
1572 /* Ensure that whatever gets printed next, using the filtered output
1573 commands, starts at the beginning of the line. I.E. if there is
1574 any pending output for the current line, flush it and start a new
1575 line. Otherwise do nothing. */
1576
1577 void
1578 begin_line ()
1579 {
1580 if (chars_printed > 0)
1581 {
1582 puts_filtered ("\n");
1583 }
1584 }
1585
1586
1587 /* ``struct gdb_file'' implementation that maps directly onto
1588 <stdio.h>'s FILE. */
1589
1590 static gdb_file_fputs_ftype stdio_file_fputs;
1591 static gdb_file_isatty_ftype stdio_file_isatty;
1592 static gdb_file_delete_ftype stdio_file_delete;
1593 static struct gdb_file *stdio_file_new PARAMS ((FILE * file, int close_p));
1594 static gdb_file_flush_ftype stdio_file_flush;
1595
1596 static int stdio_file_magic;
1597
1598 struct stdio_file
1599 {
1600 int *magic;
1601 FILE *file;
1602 int close_p;
1603 };
1604
1605 static struct gdb_file *
1606 stdio_file_new (file, close_p)
1607 FILE *file;
1608 int close_p;
1609 {
1610 struct gdb_file *gdb_file = gdb_file_new ();
1611 struct stdio_file *stdio = xmalloc (sizeof (struct stdio_file));
1612 stdio->magic = &stdio_file_magic;
1613 stdio->file = file;
1614 stdio->close_p = close_p;
1615 set_gdb_file_data (gdb_file, stdio, stdio_file_delete);
1616 set_gdb_file_flush (gdb_file, stdio_file_flush);
1617 set_gdb_file_fputs (gdb_file, stdio_file_fputs);
1618 set_gdb_file_isatty (gdb_file, stdio_file_isatty);
1619 return gdb_file;
1620 }
1621
1622 static void
1623 stdio_file_delete (file)
1624 struct gdb_file *file;
1625 {
1626 struct stdio_file *stdio = gdb_file_data (file);
1627 if (stdio->magic != &stdio_file_magic)
1628 error ("Internal error: bad magic number");
1629 if (stdio->close_p)
1630 {
1631 fclose (stdio->file);
1632 }
1633 free (stdio);
1634 }
1635
1636 static void
1637 stdio_file_flush (file)
1638 struct gdb_file *file;
1639 {
1640 struct stdio_file *stdio = gdb_file_data (file);
1641 if (stdio->magic != &stdio_file_magic)
1642 error ("Internal error: bad magic number");
1643 fflush (stdio->file);
1644 }
1645
1646 static void
1647 stdio_file_fputs (linebuffer, file)
1648 const char *linebuffer;
1649 struct gdb_file *file;
1650 {
1651 struct stdio_file *stdio = gdb_file_data (file);
1652 if (stdio->magic != &stdio_file_magic)
1653 error ("Internal error: bad magic number");
1654 fputs (linebuffer, stdio->file);
1655 }
1656
1657 static int
1658 stdio_file_isatty (file)
1659 struct gdb_file *file;
1660 {
1661 struct stdio_file *stdio = gdb_file_data (file);
1662 if (stdio->magic != &stdio_file_magic)
1663 error ("Internal error: bad magic number");
1664 return (isatty (fileno (stdio->file)));
1665 }
1666
1667 /* Like fdopen(). Create a gdb_file from a previously opened FILE. */
1668
1669 struct gdb_file *
1670 stdio_fileopen (file)
1671 FILE *file;
1672 {
1673 return stdio_file_new (file, 0);
1674 }
1675
1676
1677 /* A ``struct gdb_file'' that is compatible with all the legacy
1678 code. */
1679
1680 /* new */
1681 enum streamtype
1682 {
1683 afile,
1684 astring
1685 };
1686
1687 /* new */
1688 struct tui_stream
1689 {
1690 int *ts_magic;
1691 enum streamtype ts_streamtype;
1692 FILE *ts_filestream;
1693 char *ts_strbuf;
1694 int ts_buflen;
1695 };
1696
1697 static gdb_file_flush_ftype tui_file_flush;
1698 extern gdb_file_fputs_ftype tui_file_fputs;
1699 static gdb_file_isatty_ftype tui_file_isatty;
1700 static gdb_file_rewind_ftype tui_file_rewind;
1701 static gdb_file_put_ftype tui_file_put;
1702 static gdb_file_delete_ftype tui_file_delete;
1703 static struct gdb_file *tui_file_new PARAMS ((void));
1704 static int tui_file_magic;
1705
1706 static struct gdb_file *
1707 tui_file_new ()
1708 {
1709 struct tui_stream *tui = xmalloc (sizeof (struct tui_stream));
1710 struct gdb_file *file = gdb_file_new ();
1711 set_gdb_file_data (file, tui, tui_file_delete);
1712 set_gdb_file_flush (file, tui_file_flush);
1713 set_gdb_file_fputs (file, tui_file_fputs);
1714 set_gdb_file_isatty (file, tui_file_isatty);
1715 set_gdb_file_rewind (file, tui_file_rewind);
1716 set_gdb_file_put (file, tui_file_put);
1717 tui->ts_magic = &tui_file_magic;
1718 return file;
1719 }
1720
1721 static void
1722 tui_file_delete (file)
1723 struct gdb_file *file;
1724 {
1725 struct tui_stream *tmpstream = gdb_file_data (file);
1726 if (tmpstream->ts_magic != &tui_file_magic)
1727 error ("Internal error: bad magic number");
1728 if ((tmpstream->ts_streamtype == astring) &&
1729 (tmpstream->ts_strbuf != NULL))
1730 {
1731 free (tmpstream->ts_strbuf);
1732 }
1733 free (tmpstream);
1734 }
1735
1736 struct gdb_file *
1737 tui_fileopen (stream)
1738 FILE *stream;
1739 {
1740 struct gdb_file *file = tui_file_new ();
1741 struct tui_stream *tmpstream = gdb_file_data (file);
1742 tmpstream->ts_streamtype = afile;
1743 tmpstream->ts_filestream = stream;
1744 tmpstream->ts_strbuf = NULL;
1745 tmpstream->ts_buflen = 0;
1746 return file;
1747 }
1748
1749 static int
1750 tui_file_isatty (file)
1751 struct gdb_file *file;
1752 {
1753 struct tui_stream *stream = gdb_file_data (file);
1754 if (stream->ts_magic != &tui_file_magic)
1755 error ("Internal error: bad magic number");
1756 if (stream->ts_streamtype == afile)
1757 return (isatty (fileno (stream->ts_filestream)));
1758 else
1759 return 0;
1760 }
1761
1762 static void
1763 tui_file_rewind (file)
1764 struct gdb_file *file;
1765 {
1766 struct tui_stream *stream = gdb_file_data (file);
1767 if (stream->ts_magic != &tui_file_magic)
1768 error ("Internal error: bad magic number");
1769 stream->ts_strbuf[0] = '\0';
1770 }
1771
1772 static void
1773 tui_file_put (file, dest)
1774 struct gdb_file *file;
1775 struct gdb_file *dest;
1776 {
1777 struct tui_stream *stream = gdb_file_data (file);
1778 if (stream->ts_magic != &tui_file_magic)
1779 error ("Internal error: bad magic number");
1780 if (stream->ts_streamtype == astring)
1781 {
1782 fputs_unfiltered (stream->ts_strbuf, dest);
1783 }
1784 }
1785
1786 /* All TUI I/O sent to the *_filtered and *_unfiltered functions
1787 eventually ends up here. The fputs_unfiltered_hook is primarily
1788 used by GUIs to collect all output and send it to the GUI, instead
1789 of the controlling terminal. Only output to gdb_stdout and
1790 gdb_stderr are sent to the hook. Everything else is sent on to
1791 fputs to allow file I/O to be handled appropriately. */
1792
1793 /* FIXME: Should be broken up and moved to a TUI specific file. */
1794
1795 void
1796 tui_file_fputs (linebuffer, file)
1797 const char *linebuffer;
1798 GDB_FILE *file;
1799 {
1800 struct tui_stream *stream = gdb_file_data (file);
1801 #if defined(TUI)
1802 extern int tui_owns_terminal;
1803 #endif
1804 /* If anything (GUI, TUI) wants to capture GDB output, this is
1805 * the place... the way to do it is to set up
1806 * fputs_unfiltered_hook.
1807 * Our TUI ("gdb -tui") used to hook output, but in the
1808 * new (XDB style) scheme, we do not do that anymore... - RT
1809 */
1810 if (fputs_unfiltered_hook
1811 && (file == gdb_stdout
1812 || file == gdb_stderr))
1813 fputs_unfiltered_hook (linebuffer, file);
1814 else
1815 {
1816 #if defined(TUI)
1817 if (tui_version && tui_owns_terminal)
1818 {
1819 /* If we get here somehow while updating the TUI (from
1820 * within a tuiDo(), then we need to temporarily
1821 * set up the terminal for GDB output. This probably just
1822 * happens on error output.
1823 */
1824
1825 if (stream->ts_streamtype == astring)
1826 {
1827 gdb_file_adjust_strbuf (strlen (linebuffer), stream);
1828 strcat (stream->ts_strbuf, linebuffer);
1829 }
1830 else
1831 {
1832 tuiTermUnsetup (0, (tui_version) ? cmdWin->detail.commandInfo.curch : 0);
1833 fputs (linebuffer, stream->ts_filestream);
1834 tuiTermSetup (0);
1835 if (linebuffer[strlen (linebuffer) - 1] == '\n')
1836 tuiClearCommandCharCount ();
1837 else
1838 tuiIncrCommandCharCountBy (strlen (linebuffer));
1839 }
1840 }
1841 else
1842 {
1843 /* The normal case - just do a fputs() */
1844 if (stream->ts_streamtype == astring)
1845 {
1846 gdb_file_adjust_strbuf (strlen (linebuffer), stream);
1847 strcat (stream->ts_strbuf, linebuffer);
1848 }
1849 else
1850 fputs (linebuffer, stream->ts_filestream);
1851 }
1852
1853
1854 #else
1855 if (stream->ts_streamtype == astring)
1856 {
1857 gdb_file_adjust_strbuf (strlen (linebuffer), file);
1858 strcat (stream->ts_strbuf, linebuffer);
1859 }
1860 else
1861 fputs (linebuffer, stream->ts_filestream);
1862 #endif
1863 }
1864 }
1865
1866 GDB_FILE *
1867 gdb_file_init_astring (n)
1868 int n;
1869 {
1870 struct gdb_file *file = tui_file_new ();
1871 struct tui_stream *tmpstream = gdb_file_data (file);
1872 if (tmpstream->ts_magic != &tui_file_magic)
1873 error ("Internal error: bad magic number");
1874
1875 tmpstream->ts_streamtype = astring;
1876 tmpstream->ts_filestream = NULL;
1877 if (n > 0)
1878 {
1879 tmpstream->ts_strbuf = xmalloc ((n + 1) * sizeof (char));
1880 tmpstream->ts_strbuf[0] = '\0';
1881 }
1882 else
1883 tmpstream->ts_strbuf = NULL;
1884 tmpstream->ts_buflen = n;
1885
1886 return file;
1887 }
1888
1889 void
1890 gdb_file_deallocate (streamptr)
1891 GDB_FILE **streamptr;
1892 {
1893 gdb_file_delete (*streamptr);
1894 *streamptr = NULL;
1895 }
1896
1897 char *
1898 gdb_file_get_strbuf (file)
1899 GDB_FILE *file;
1900 {
1901 struct tui_stream *stream = gdb_file_data (file);
1902 if (stream->ts_magic != &tui_file_magic)
1903 error ("Internal error: bad magic number");
1904 return (stream->ts_strbuf);
1905 }
1906
1907 /* adjust the length of the buffer by the amount necessary
1908 to accomodate appending a string of length N to the buffer contents */
1909 void
1910 gdb_file_adjust_strbuf (n, file)
1911 int n;
1912 GDB_FILE *file;
1913 {
1914 struct tui_stream *stream = gdb_file_data (file);
1915 int non_null_chars;
1916 if (stream->ts_magic != &tui_file_magic)
1917 error ("Internal error: bad magic number");
1918
1919 if (stream->ts_streamtype != astring)
1920 return;
1921
1922 if (stream->ts_strbuf)
1923 {
1924 /* There is already a buffer allocated */
1925 non_null_chars = strlen (stream->ts_strbuf);
1926
1927 if (n > (stream->ts_buflen - non_null_chars - 1))
1928 {
1929 stream->ts_buflen = n + non_null_chars + 1;
1930 stream->ts_strbuf = xrealloc (stream->ts_strbuf, stream->ts_buflen);
1931 }
1932 }
1933 else
1934 /* No buffer yet, so allocate one of the desired size */
1935 stream->ts_strbuf = xmalloc ((n + 1) * sizeof (char));
1936 }
1937
1938 GDB_FILE *
1939 gdb_fopen (name, mode)
1940 char *name;
1941 char *mode;
1942 {
1943 FILE *f = fopen (name, mode);
1944 if (f == NULL)
1945 return NULL;
1946 return stdio_file_new (f, 1);
1947 }
1948
1949 static void
1950 tui_file_flush (file)
1951 GDB_FILE *file;
1952 {
1953 struct tui_stream *stream = gdb_file_data (file);
1954 if (stream->ts_magic != &tui_file_magic)
1955 error ("Internal error: bad magic number");
1956 if (flush_hook
1957 && (file == gdb_stdout
1958 || file == gdb_stderr))
1959 {
1960 flush_hook (file);
1961 return;
1962 }
1963
1964 fflush (stream->ts_filestream);
1965 }
1966
1967 void
1968 gdb_fclose (streamptr)
1969 GDB_FILE **streamptr;
1970 {
1971 gdb_file_delete (*streamptr);
1972 *streamptr = NULL;
1973 }
1974
1975
1976 /* Implement the ``struct gdb_file'' object. */
1977
1978 static gdb_file_isatty_ftype null_file_isatty;
1979 static gdb_file_fputs_ftype null_file_fputs;
1980 static gdb_file_flush_ftype null_file_flush;
1981 static gdb_file_delete_ftype null_file_delete;
1982 static gdb_file_rewind_ftype null_file_rewind;
1983 static gdb_file_put_ftype null_file_put;
1984
1985 struct gdb_file
1986 {
1987 gdb_file_flush_ftype *to_flush;
1988 gdb_file_fputs_ftype *to_fputs;
1989 gdb_file_delete_ftype *to_delete;
1990 gdb_file_isatty_ftype *to_isatty;
1991 gdb_file_rewind_ftype *to_rewind;
1992 gdb_file_put_ftype *to_put;
1993 void *to_data;
1994 };
1995
1996 struct gdb_file *
1997 gdb_file_new ()
1998 {
1999 struct gdb_file *file = xmalloc (sizeof (struct gdb_file));
2000 set_gdb_file_data (file, NULL, null_file_delete);
2001 set_gdb_file_flush (file, null_file_flush);
2002 set_gdb_file_fputs (file, null_file_fputs);
2003 set_gdb_file_isatty (file, null_file_isatty);
2004 set_gdb_file_rewind (file, null_file_rewind);
2005 set_gdb_file_put (file, null_file_put);
2006 return file;
2007 }
2008
2009 void
2010 gdb_file_delete (file)
2011 struct gdb_file *file;
2012 {
2013 file->to_delete (file);
2014 free (file);
2015 }
2016
2017 static int
2018 null_file_isatty (file)
2019 struct gdb_file *file;
2020 {
2021 return 0;
2022 }
2023
2024 static void
2025 null_file_rewind (file)
2026 struct gdb_file *file;
2027 {
2028 return;
2029 }
2030
2031 static void
2032 null_file_put (file, src)
2033 struct gdb_file *file;
2034 struct gdb_file *src;
2035 {
2036 return;
2037 }
2038
2039 static void
2040 null_file_flush (file)
2041 struct gdb_file *file;
2042 {
2043 return;
2044 }
2045
2046 static void
2047 null_file_fputs (buf, file)
2048 const char *buf;
2049 struct gdb_file *file;
2050 {
2051 return;
2052 }
2053
2054 static void
2055 null_file_delete (file)
2056 struct gdb_file *file;
2057 {
2058 return;
2059 }
2060
2061 void *
2062 gdb_file_data (file)
2063 struct gdb_file *file;
2064 {
2065 return file->to_data;
2066 }
2067
2068 void
2069 gdb_flush (file)
2070 struct gdb_file *file;
2071 {
2072 file->to_flush (file);
2073 }
2074
2075 int
2076 gdb_file_isatty (file)
2077 struct gdb_file *file;
2078 {
2079 return file->to_isatty (file);
2080 }
2081
2082 void
2083 gdb_file_rewind (file)
2084 struct gdb_file *file;
2085 {
2086 file->to_rewind (file);
2087 }
2088
2089 void
2090 gdb_file_put (file, dest)
2091 struct gdb_file *file;
2092 struct gdb_file *dest;
2093 {
2094 file->to_put (file, dest);
2095 }
2096
2097 void
2098 fputs_unfiltered (buf, file)
2099 const char *buf;
2100 struct gdb_file *file;
2101 {
2102 file->to_fputs (buf, file);
2103 }
2104
2105 void
2106 set_gdb_file_flush (file, flush)
2107 struct gdb_file *file;
2108 gdb_file_flush_ftype *flush;
2109 {
2110 file->to_flush = flush;
2111 }
2112
2113 void
2114 set_gdb_file_isatty (file, isatty)
2115 struct gdb_file *file;
2116 gdb_file_isatty_ftype *isatty;
2117 {
2118 file->to_isatty = isatty;
2119 }
2120
2121 void
2122 set_gdb_file_rewind (file, rewind)
2123 struct gdb_file *file;
2124 gdb_file_rewind_ftype *rewind;
2125 {
2126 file->to_rewind = rewind;
2127 }
2128
2129 void
2130 set_gdb_file_put (file, put)
2131 struct gdb_file *file;
2132 gdb_file_put_ftype *put;
2133 {
2134 file->to_put = put;
2135 }
2136
2137 void
2138 set_gdb_file_fputs (file, fputs)
2139 struct gdb_file *file;
2140 gdb_file_fputs_ftype *fputs;
2141 {
2142 file->to_fputs = fputs;
2143 }
2144
2145 void
2146 set_gdb_file_data (file, data, delete)
2147 struct gdb_file *file;
2148 void *data;
2149 gdb_file_delete_ftype *delete;
2150 {
2151 file->to_data = data;
2152 file->to_delete = delete;
2153 }
2154
2155 /* Like fputs but if FILTER is true, pause after every screenful.
2156
2157 Regardless of FILTER can wrap at points other than the final
2158 character of a line.
2159
2160 Unlike fputs, fputs_maybe_filtered does not return a value.
2161 It is OK for LINEBUFFER to be NULL, in which case just don't print
2162 anything.
2163
2164 Note that a longjmp to top level may occur in this routine (only if
2165 FILTER is true) (since prompt_for_continue may do so) so this
2166 routine should not be called when cleanups are not in place. */
2167
2168 static void
2169 fputs_maybe_filtered (linebuffer, stream, filter)
2170 const char *linebuffer;
2171 GDB_FILE *stream;
2172 int filter;
2173 {
2174 const char *lineptr;
2175
2176 if (linebuffer == 0)
2177 return;
2178
2179 /* Don't do any filtering if it is disabled. */
2180 if ((stream != gdb_stdout) || !pagination_enabled
2181 || (lines_per_page == UINT_MAX && chars_per_line == UINT_MAX))
2182 {
2183 fputs_unfiltered (linebuffer, stream);
2184 return;
2185 }
2186
2187 /* Go through and output each character. Show line extension
2188 when this is necessary; prompt user for new page when this is
2189 necessary. */
2190
2191 lineptr = linebuffer;
2192 while (*lineptr)
2193 {
2194 /* Possible new page. */
2195 if (filter &&
2196 (lines_printed >= lines_per_page - 1))
2197 prompt_for_continue ();
2198
2199 while (*lineptr && *lineptr != '\n')
2200 {
2201 /* Print a single line. */
2202 if (*lineptr == '\t')
2203 {
2204 if (wrap_column)
2205 *wrap_pointer++ = '\t';
2206 else
2207 fputc_unfiltered ('\t', stream);
2208 /* Shifting right by 3 produces the number of tab stops
2209 we have already passed, and then adding one and
2210 shifting left 3 advances to the next tab stop. */
2211 chars_printed = ((chars_printed >> 3) + 1) << 3;
2212 lineptr++;
2213 }
2214 else
2215 {
2216 if (wrap_column)
2217 *wrap_pointer++ = *lineptr;
2218 else
2219 fputc_unfiltered (*lineptr, stream);
2220 chars_printed++;
2221 lineptr++;
2222 }
2223
2224 if (chars_printed >= chars_per_line)
2225 {
2226 unsigned int save_chars = chars_printed;
2227
2228 chars_printed = 0;
2229 lines_printed++;
2230 /* If we aren't actually wrapping, don't output newline --
2231 if chars_per_line is right, we probably just overflowed
2232 anyway; if it's wrong, let us keep going. */
2233 if (wrap_column)
2234 fputc_unfiltered ('\n', stream);
2235
2236 /* Possible new page. */
2237 if (lines_printed >= lines_per_page - 1)
2238 prompt_for_continue ();
2239
2240 /* Now output indentation and wrapped string */
2241 if (wrap_column)
2242 {
2243 fputs_unfiltered (wrap_indent, stream);
2244 *wrap_pointer = '\0'; /* Null-terminate saved stuff */
2245 fputs_unfiltered (wrap_buffer, stream); /* and eject it */
2246 /* FIXME, this strlen is what prevents wrap_indent from
2247 containing tabs. However, if we recurse to print it
2248 and count its chars, we risk trouble if wrap_indent is
2249 longer than (the user settable) chars_per_line.
2250 Note also that this can set chars_printed > chars_per_line
2251 if we are printing a long string. */
2252 chars_printed = strlen (wrap_indent)
2253 + (save_chars - wrap_column);
2254 wrap_pointer = wrap_buffer; /* Reset buffer */
2255 wrap_buffer[0] = '\0';
2256 wrap_column = 0; /* And disable fancy wrap */
2257 }
2258 }
2259 }
2260
2261 if (*lineptr == '\n')
2262 {
2263 chars_printed = 0;
2264 wrap_here ((char *) 0); /* Spit out chars, cancel further wraps */
2265 lines_printed++;
2266 fputc_unfiltered ('\n', stream);
2267 lineptr++;
2268 }
2269 }
2270 }
2271
2272 void
2273 fputs_filtered (linebuffer, stream)
2274 const char *linebuffer;
2275 GDB_FILE *stream;
2276 {
2277 fputs_maybe_filtered (linebuffer, stream, 1);
2278 }
2279
2280 int
2281 putchar_unfiltered (c)
2282 int c;
2283 {
2284 char buf[2];
2285
2286 buf[0] = c;
2287 buf[1] = 0;
2288 fputs_unfiltered (buf, gdb_stdout);
2289 return c;
2290 }
2291
2292 int
2293 fputc_unfiltered (c, stream)
2294 int c;
2295 GDB_FILE *stream;
2296 {
2297 char buf[2];
2298
2299 buf[0] = c;
2300 buf[1] = 0;
2301 fputs_unfiltered (buf, stream);
2302 return c;
2303 }
2304
2305 int
2306 fputc_filtered (c, stream)
2307 int c;
2308 GDB_FILE *stream;
2309 {
2310 char buf[2];
2311
2312 buf[0] = c;
2313 buf[1] = 0;
2314 fputs_filtered (buf, stream);
2315 return c;
2316 }
2317
2318 /* puts_debug is like fputs_unfiltered, except it prints special
2319 characters in printable fashion. */
2320
2321 void
2322 puts_debug (prefix, string, suffix)
2323 char *prefix;
2324 char *string;
2325 char *suffix;
2326 {
2327 int ch;
2328
2329 /* Print prefix and suffix after each line. */
2330 static int new_line = 1;
2331 static int return_p = 0;
2332 static char *prev_prefix = "";
2333 static char *prev_suffix = "";
2334
2335 if (*string == '\n')
2336 return_p = 0;
2337
2338 /* If the prefix is changing, print the previous suffix, a new line,
2339 and the new prefix. */
2340 if ((return_p || (strcmp (prev_prefix, prefix) != 0)) && !new_line)
2341 {
2342 fputs_unfiltered (prev_suffix, gdb_stdlog);
2343 fputs_unfiltered ("\n", gdb_stdlog);
2344 fputs_unfiltered (prefix, gdb_stdlog);
2345 }
2346
2347 /* Print prefix if we printed a newline during the previous call. */
2348 if (new_line)
2349 {
2350 new_line = 0;
2351 fputs_unfiltered (prefix, gdb_stdlog);
2352 }
2353
2354 prev_prefix = prefix;
2355 prev_suffix = suffix;
2356
2357 /* Output characters in a printable format. */
2358 while ((ch = *string++) != '\0')
2359 {
2360 switch (ch)
2361 {
2362 default:
2363 if (isprint (ch))
2364 fputc_unfiltered (ch, gdb_stdlog);
2365
2366 else
2367 fprintf_unfiltered (gdb_stdlog, "\\x%02x", ch & 0xff);
2368 break;
2369
2370 case '\\':
2371 fputs_unfiltered ("\\\\", gdb_stdlog);
2372 break;
2373 case '\b':
2374 fputs_unfiltered ("\\b", gdb_stdlog);
2375 break;
2376 case '\f':
2377 fputs_unfiltered ("\\f", gdb_stdlog);
2378 break;
2379 case '\n':
2380 new_line = 1;
2381 fputs_unfiltered ("\\n", gdb_stdlog);
2382 break;
2383 case '\r':
2384 fputs_unfiltered ("\\r", gdb_stdlog);
2385 break;
2386 case '\t':
2387 fputs_unfiltered ("\\t", gdb_stdlog);
2388 break;
2389 case '\v':
2390 fputs_unfiltered ("\\v", gdb_stdlog);
2391 break;
2392 }
2393
2394 return_p = ch == '\r';
2395 }
2396
2397 /* Print suffix if we printed a newline. */
2398 if (new_line)
2399 {
2400 fputs_unfiltered (suffix, gdb_stdlog);
2401 fputs_unfiltered ("\n", gdb_stdlog);
2402 }
2403 }
2404
2405
2406 /* Print a variable number of ARGS using format FORMAT. If this
2407 information is going to put the amount written (since the last call
2408 to REINITIALIZE_MORE_FILTER or the last page break) over the page size,
2409 call prompt_for_continue to get the users permision to continue.
2410
2411 Unlike fprintf, this function does not return a value.
2412
2413 We implement three variants, vfprintf (takes a vararg list and stream),
2414 fprintf (takes a stream to write on), and printf (the usual).
2415
2416 Note also that a longjmp to top level may occur in this routine
2417 (since prompt_for_continue may do so) so this routine should not be
2418 called when cleanups are not in place. */
2419
2420 static void
2421 vfprintf_maybe_filtered (stream, format, args, filter)
2422 GDB_FILE *stream;
2423 const char *format;
2424 va_list args;
2425 int filter;
2426 {
2427 char *linebuffer;
2428 struct cleanup *old_cleanups;
2429
2430 vasprintf (&linebuffer, format, args);
2431 if (linebuffer == NULL)
2432 {
2433 fputs_unfiltered ("\ngdb: virtual memory exhausted.\n", gdb_stderr);
2434 exit (1);
2435 }
2436 old_cleanups = make_cleanup (free, linebuffer);
2437 fputs_maybe_filtered (linebuffer, stream, filter);
2438 do_cleanups (old_cleanups);
2439 }
2440
2441
2442 void
2443 vfprintf_filtered (stream, format, args)
2444 GDB_FILE *stream;
2445 const char *format;
2446 va_list args;
2447 {
2448 vfprintf_maybe_filtered (stream, format, args, 1);
2449 }
2450
2451 void
2452 vfprintf_unfiltered (stream, format, args)
2453 GDB_FILE *stream;
2454 const char *format;
2455 va_list args;
2456 {
2457 char *linebuffer;
2458 struct cleanup *old_cleanups;
2459
2460 vasprintf (&linebuffer, format, args);
2461 if (linebuffer == NULL)
2462 {
2463 fputs_unfiltered ("\ngdb: virtual memory exhausted.\n", gdb_stderr);
2464 exit (1);
2465 }
2466 old_cleanups = make_cleanup (free, linebuffer);
2467 fputs_unfiltered (linebuffer, stream);
2468 do_cleanups (old_cleanups);
2469 }
2470
2471 void
2472 vprintf_filtered (format, args)
2473 const char *format;
2474 va_list args;
2475 {
2476 vfprintf_maybe_filtered (gdb_stdout, format, args, 1);
2477 }
2478
2479 void
2480 vprintf_unfiltered (format, args)
2481 const char *format;
2482 va_list args;
2483 {
2484 vfprintf_unfiltered (gdb_stdout, format, args);
2485 }
2486
2487 void
2488 fprintf_filtered (GDB_FILE * stream, const char *format,...)
2489 {
2490 va_list args;
2491 va_start (args, format);
2492 vfprintf_filtered (stream, format, args);
2493 va_end (args);
2494 }
2495
2496 void
2497 fprintf_unfiltered (GDB_FILE * stream, const char *format,...)
2498 {
2499 va_list args;
2500 va_start (args, format);
2501 vfprintf_unfiltered (stream, format, args);
2502 va_end (args);
2503 }
2504
2505 /* Like fprintf_filtered, but prints its result indented.
2506 Called as fprintfi_filtered (spaces, stream, format, ...); */
2507
2508 void
2509 fprintfi_filtered (int spaces, GDB_FILE * stream, const char *format,...)
2510 {
2511 va_list args;
2512 va_start (args, format);
2513 print_spaces_filtered (spaces, stream);
2514
2515 vfprintf_filtered (stream, format, args);
2516 va_end (args);
2517 }
2518
2519
2520 void
2521 printf_filtered (const char *format,...)
2522 {
2523 va_list args;
2524 va_start (args, format);
2525 vfprintf_filtered (gdb_stdout, format, args);
2526 va_end (args);
2527 }
2528
2529
2530 void
2531 printf_unfiltered (const char *format,...)
2532 {
2533 va_list args;
2534 va_start (args, format);
2535 vfprintf_unfiltered (gdb_stdout, format, args);
2536 va_end (args);
2537 }
2538
2539 /* Like printf_filtered, but prints it's result indented.
2540 Called as printfi_filtered (spaces, format, ...); */
2541
2542 void
2543 printfi_filtered (int spaces, const char *format,...)
2544 {
2545 va_list args;
2546 va_start (args, format);
2547 print_spaces_filtered (spaces, gdb_stdout);
2548 vfprintf_filtered (gdb_stdout, format, args);
2549 va_end (args);
2550 }
2551
2552 /* Easy -- but watch out!
2553
2554 This routine is *not* a replacement for puts()! puts() appends a newline.
2555 This one doesn't, and had better not! */
2556
2557 void
2558 puts_filtered (string)
2559 const char *string;
2560 {
2561 fputs_filtered (string, gdb_stdout);
2562 }
2563
2564 void
2565 puts_unfiltered (string)
2566 const char *string;
2567 {
2568 fputs_unfiltered (string, gdb_stdout);
2569 }
2570
2571 /* Return a pointer to N spaces and a null. The pointer is good
2572 until the next call to here. */
2573 char *
2574 n_spaces (n)
2575 int n;
2576 {
2577 char *t;
2578 static char *spaces = 0;
2579 static int max_spaces = -1;
2580
2581 if (n > max_spaces)
2582 {
2583 if (spaces)
2584 free (spaces);
2585 spaces = (char *) xmalloc (n + 1);
2586 for (t = spaces + n; t != spaces;)
2587 *--t = ' ';
2588 spaces[n] = '\0';
2589 max_spaces = n;
2590 }
2591
2592 return spaces + max_spaces - n;
2593 }
2594
2595 /* Print N spaces. */
2596 void
2597 print_spaces_filtered (n, stream)
2598 int n;
2599 GDB_FILE *stream;
2600 {
2601 fputs_filtered (n_spaces (n), stream);
2602 }
2603 \f
2604 /* C++ demangler stuff. */
2605
2606 /* fprintf_symbol_filtered attempts to demangle NAME, a symbol in language
2607 LANG, using demangling args ARG_MODE, and print it filtered to STREAM.
2608 If the name is not mangled, or the language for the name is unknown, or
2609 demangling is off, the name is printed in its "raw" form. */
2610
2611 void
2612 fprintf_symbol_filtered (stream, name, lang, arg_mode)
2613 GDB_FILE *stream;
2614 char *name;
2615 enum language lang;
2616 int arg_mode;
2617 {
2618 char *demangled;
2619
2620 if (name != NULL)
2621 {
2622 /* If user wants to see raw output, no problem. */
2623 if (!demangle)
2624 {
2625 fputs_filtered (name, stream);
2626 }
2627 else
2628 {
2629 switch (lang)
2630 {
2631 case language_cplus:
2632 demangled = cplus_demangle (name, arg_mode);
2633 break;
2634 case language_java:
2635 demangled = cplus_demangle (name, arg_mode | DMGL_JAVA);
2636 break;
2637 case language_chill:
2638 demangled = chill_demangle (name);
2639 break;
2640 default:
2641 demangled = NULL;
2642 break;
2643 }
2644 fputs_filtered (demangled ? demangled : name, stream);
2645 if (demangled != NULL)
2646 {
2647 free (demangled);
2648 }
2649 }
2650 }
2651 }
2652
2653 /* Do a strcmp() type operation on STRING1 and STRING2, ignoring any
2654 differences in whitespace. Returns 0 if they match, non-zero if they
2655 don't (slightly different than strcmp()'s range of return values).
2656
2657 As an extra hack, string1=="FOO(ARGS)" matches string2=="FOO".
2658 This "feature" is useful when searching for matching C++ function names
2659 (such as if the user types 'break FOO', where FOO is a mangled C++
2660 function). */
2661
2662 int
2663 strcmp_iw (string1, string2)
2664 const char *string1;
2665 const char *string2;
2666 {
2667 while ((*string1 != '\0') && (*string2 != '\0'))
2668 {
2669 while (isspace (*string1))
2670 {
2671 string1++;
2672 }
2673 while (isspace (*string2))
2674 {
2675 string2++;
2676 }
2677 if (*string1 != *string2)
2678 {
2679 break;
2680 }
2681 if (*string1 != '\0')
2682 {
2683 string1++;
2684 string2++;
2685 }
2686 }
2687 return (*string1 != '\0' && *string1 != '(') || (*string2 != '\0');
2688 }
2689 \f
2690
2691 /*
2692 ** subset_compare()
2693 ** Answer whether string_to_compare is a full or partial match to
2694 ** template_string. The partial match must be in sequence starting
2695 ** at index 0.
2696 */
2697 int
2698 subset_compare (string_to_compare, template_string)
2699 char *string_to_compare;
2700 char *template_string;
2701 {
2702 int match;
2703 if (template_string != (char *) NULL && string_to_compare != (char *) NULL &&
2704 strlen (string_to_compare) <= strlen (template_string))
2705 match = (strncmp (template_string,
2706 string_to_compare,
2707 strlen (string_to_compare)) == 0);
2708 else
2709 match = 0;
2710 return match;
2711 }
2712
2713
2714 static void pagination_on_command PARAMS ((char *arg, int from_tty));
2715 static void
2716 pagination_on_command (arg, from_tty)
2717 char *arg;
2718 int from_tty;
2719 {
2720 pagination_enabled = 1;
2721 }
2722
2723 static void pagination_on_command PARAMS ((char *arg, int from_tty));
2724 static void
2725 pagination_off_command (arg, from_tty)
2726 char *arg;
2727 int from_tty;
2728 {
2729 pagination_enabled = 0;
2730 }
2731 \f
2732
2733 void
2734 initialize_utils ()
2735 {
2736 struct cmd_list_element *c;
2737
2738 c = add_set_cmd ("width", class_support, var_uinteger,
2739 (char *) &chars_per_line,
2740 "Set number of characters gdb thinks are in a line.",
2741 &setlist);
2742 add_show_from_set (c, &showlist);
2743 c->function.sfunc = set_width_command;
2744
2745 add_show_from_set
2746 (add_set_cmd ("height", class_support,
2747 var_uinteger, (char *) &lines_per_page,
2748 "Set number of lines gdb thinks are in a page.", &setlist),
2749 &showlist);
2750
2751 init_page_info ();
2752
2753 /* If the output is not a terminal, don't paginate it. */
2754 if (!GDB_FILE_ISATTY (gdb_stdout))
2755 lines_per_page = UINT_MAX;
2756
2757 set_width_command ((char *) NULL, 0, c);
2758
2759 add_show_from_set
2760 (add_set_cmd ("demangle", class_support, var_boolean,
2761 (char *) &demangle,
2762 "Set demangling of encoded C++ names when displaying symbols.",
2763 &setprintlist),
2764 &showprintlist);
2765
2766 add_show_from_set
2767 (add_set_cmd ("pagination", class_support,
2768 var_boolean, (char *) &pagination_enabled,
2769 "Set state of pagination.", &setlist),
2770 &showlist);
2771 if (xdb_commands)
2772 {
2773 add_com ("am", class_support, pagination_on_command,
2774 "Enable pagination");
2775 add_com ("sm", class_support, pagination_off_command,
2776 "Disable pagination");
2777 }
2778
2779 add_show_from_set
2780 (add_set_cmd ("sevenbit-strings", class_support, var_boolean,
2781 (char *) &sevenbit_strings,
2782 "Set printing of 8-bit characters in strings as \\nnn.",
2783 &setprintlist),
2784 &showprintlist);
2785
2786 add_show_from_set
2787 (add_set_cmd ("asm-demangle", class_support, var_boolean,
2788 (char *) &asm_demangle,
2789 "Set demangling of C++ names in disassembly listings.",
2790 &setprintlist),
2791 &showprintlist);
2792 }
2793
2794 /* Machine specific function to handle SIGWINCH signal. */
2795
2796 #ifdef SIGWINCH_HANDLER_BODY
2797 SIGWINCH_HANDLER_BODY
2798 #endif
2799 \f
2800 /* Support for converting target fp numbers into host DOUBLEST format. */
2801
2802 /* XXX - This code should really be in libiberty/floatformat.c, however
2803 configuration issues with libiberty made this very difficult to do in the
2804 available time. */
2805
2806 #include "floatformat.h"
2807 #include <math.h> /* ldexp */
2808
2809 /* The odds that CHAR_BIT will be anything but 8 are low enough that I'm not
2810 going to bother with trying to muck around with whether it is defined in
2811 a system header, what we do if not, etc. */
2812 #define FLOATFORMAT_CHAR_BIT 8
2813
2814 static unsigned long get_field PARAMS ((unsigned char *,
2815 enum floatformat_byteorders,
2816 unsigned int,
2817 unsigned int,
2818 unsigned int));
2819
2820 /* Extract a field which starts at START and is LEN bytes long. DATA and
2821 TOTAL_LEN are the thing we are extracting it from, in byteorder ORDER. */
2822 static unsigned long
2823 get_field (data, order, total_len, start, len)
2824 unsigned char *data;
2825 enum floatformat_byteorders order;
2826 unsigned int total_len;
2827 unsigned int start;
2828 unsigned int len;
2829 {
2830 unsigned long result;
2831 unsigned int cur_byte;
2832 int cur_bitshift;
2833
2834 /* Start at the least significant part of the field. */
2835 cur_byte = (start + len) / FLOATFORMAT_CHAR_BIT;
2836 if (order == floatformat_little || order == floatformat_littlebyte_bigword)
2837 cur_byte = (total_len / FLOATFORMAT_CHAR_BIT) - cur_byte - 1;
2838 cur_bitshift =
2839 ((start + len) % FLOATFORMAT_CHAR_BIT) - FLOATFORMAT_CHAR_BIT;
2840 result = *(data + cur_byte) >> (-cur_bitshift);
2841 cur_bitshift += FLOATFORMAT_CHAR_BIT;
2842 if (order == floatformat_little || order == floatformat_littlebyte_bigword)
2843 ++cur_byte;
2844 else
2845 --cur_byte;
2846
2847 /* Move towards the most significant part of the field. */
2848 while (cur_bitshift < len)
2849 {
2850 if (len - cur_bitshift < FLOATFORMAT_CHAR_BIT)
2851 /* This is the last byte; zero out the bits which are not part of
2852 this field. */
2853 result |=
2854 (*(data + cur_byte) & ((1 << (len - cur_bitshift)) - 1))
2855 << cur_bitshift;
2856 else
2857 result |= *(data + cur_byte) << cur_bitshift;
2858 cur_bitshift += FLOATFORMAT_CHAR_BIT;
2859 if (order == floatformat_little || order == floatformat_littlebyte_bigword)
2860 ++cur_byte;
2861 else
2862 --cur_byte;
2863 }
2864 return result;
2865 }
2866
2867 /* Convert from FMT to a DOUBLEST.
2868 FROM is the address of the extended float.
2869 Store the DOUBLEST in *TO. */
2870
2871 void
2872 floatformat_to_doublest (fmt, from, to)
2873 const struct floatformat *fmt;
2874 char *from;
2875 DOUBLEST *to;
2876 {
2877 unsigned char *ufrom = (unsigned char *) from;
2878 DOUBLEST dto;
2879 long exponent;
2880 unsigned long mant;
2881 unsigned int mant_bits, mant_off;
2882 int mant_bits_left;
2883 int special_exponent; /* It's a NaN, denorm or zero */
2884
2885 /* If the mantissa bits are not contiguous from one end of the
2886 mantissa to the other, we need to make a private copy of the
2887 source bytes that is in the right order since the unpacking
2888 algorithm assumes that the bits are contiguous.
2889
2890 Swap the bytes individually rather than accessing them through
2891 "long *" since we have no guarantee that they start on a long
2892 alignment, and also sizeof(long) for the host could be different
2893 than sizeof(long) for the target. FIXME: Assumes sizeof(long)
2894 for the target is 4. */
2895
2896 if (fmt->byteorder == floatformat_littlebyte_bigword)
2897 {
2898 static unsigned char *newfrom;
2899 unsigned char *swapin, *swapout;
2900 int longswaps;
2901
2902 longswaps = fmt->totalsize / FLOATFORMAT_CHAR_BIT;
2903 longswaps >>= 3;
2904
2905 if (newfrom == NULL)
2906 {
2907 newfrom = (unsigned char *) xmalloc (fmt->totalsize);
2908 }
2909 swapout = newfrom;
2910 swapin = ufrom;
2911 ufrom = newfrom;
2912 while (longswaps-- > 0)
2913 {
2914 /* This is ugly, but efficient */
2915 *swapout++ = swapin[4];
2916 *swapout++ = swapin[5];
2917 *swapout++ = swapin[6];
2918 *swapout++ = swapin[7];
2919 *swapout++ = swapin[0];
2920 *swapout++ = swapin[1];
2921 *swapout++ = swapin[2];
2922 *swapout++ = swapin[3];
2923 swapin += 8;
2924 }
2925 }
2926
2927 exponent = get_field (ufrom, fmt->byteorder, fmt->totalsize,
2928 fmt->exp_start, fmt->exp_len);
2929 /* Note that if exponent indicates a NaN, we can't really do anything useful
2930 (not knowing if the host has NaN's, or how to build one). So it will
2931 end up as an infinity or something close; that is OK. */
2932
2933 mant_bits_left = fmt->man_len;
2934 mant_off = fmt->man_start;
2935 dto = 0.0;
2936
2937 special_exponent = exponent == 0 || exponent == fmt->exp_nan;
2938
2939 /* Don't bias zero's, denorms or NaNs. */
2940 if (!special_exponent)
2941 exponent -= fmt->exp_bias;
2942
2943 /* Build the result algebraically. Might go infinite, underflow, etc;
2944 who cares. */
2945
2946 /* If this format uses a hidden bit, explicitly add it in now. Otherwise,
2947 increment the exponent by one to account for the integer bit. */
2948
2949 if (!special_exponent)
2950 {
2951 if (fmt->intbit == floatformat_intbit_no)
2952 dto = ldexp (1.0, exponent);
2953 else
2954 exponent++;
2955 }
2956
2957 while (mant_bits_left > 0)
2958 {
2959 mant_bits = min (mant_bits_left, 32);
2960
2961 mant = get_field (ufrom, fmt->byteorder, fmt->totalsize,
2962 mant_off, mant_bits);
2963
2964 dto += ldexp ((double) mant, exponent - mant_bits);
2965 exponent -= mant_bits;
2966 mant_off += mant_bits;
2967 mant_bits_left -= mant_bits;
2968 }
2969
2970 /* Negate it if negative. */
2971 if (get_field (ufrom, fmt->byteorder, fmt->totalsize, fmt->sign_start, 1))
2972 dto = -dto;
2973 *to = dto;
2974 }
2975 \f
2976 static void put_field PARAMS ((unsigned char *, enum floatformat_byteorders,
2977 unsigned int,
2978 unsigned int,
2979 unsigned int,
2980 unsigned long));
2981
2982 /* Set a field which starts at START and is LEN bytes long. DATA and
2983 TOTAL_LEN are the thing we are extracting it from, in byteorder ORDER. */
2984 static void
2985 put_field (data, order, total_len, start, len, stuff_to_put)
2986 unsigned char *data;
2987 enum floatformat_byteorders order;
2988 unsigned int total_len;
2989 unsigned int start;
2990 unsigned int len;
2991 unsigned long stuff_to_put;
2992 {
2993 unsigned int cur_byte;
2994 int cur_bitshift;
2995
2996 /* Start at the least significant part of the field. */
2997 cur_byte = (start + len) / FLOATFORMAT_CHAR_BIT;
2998 if (order == floatformat_little || order == floatformat_littlebyte_bigword)
2999 cur_byte = (total_len / FLOATFORMAT_CHAR_BIT) - cur_byte - 1;
3000 cur_bitshift =
3001 ((start + len) % FLOATFORMAT_CHAR_BIT) - FLOATFORMAT_CHAR_BIT;
3002 *(data + cur_byte) &=
3003 ~(((1 << ((start + len) % FLOATFORMAT_CHAR_BIT)) - 1) << (-cur_bitshift));
3004 *(data + cur_byte) |=
3005 (stuff_to_put & ((1 << FLOATFORMAT_CHAR_BIT) - 1)) << (-cur_bitshift);
3006 cur_bitshift += FLOATFORMAT_CHAR_BIT;
3007 if (order == floatformat_little || order == floatformat_littlebyte_bigword)
3008 ++cur_byte;
3009 else
3010 --cur_byte;
3011
3012 /* Move towards the most significant part of the field. */
3013 while (cur_bitshift < len)
3014 {
3015 if (len - cur_bitshift < FLOATFORMAT_CHAR_BIT)
3016 {
3017 /* This is the last byte. */
3018 *(data + cur_byte) &=
3019 ~((1 << (len - cur_bitshift)) - 1);
3020 *(data + cur_byte) |= (stuff_to_put >> cur_bitshift);
3021 }
3022 else
3023 *(data + cur_byte) = ((stuff_to_put >> cur_bitshift)
3024 & ((1 << FLOATFORMAT_CHAR_BIT) - 1));
3025 cur_bitshift += FLOATFORMAT_CHAR_BIT;
3026 if (order == floatformat_little || order == floatformat_littlebyte_bigword)
3027 ++cur_byte;
3028 else
3029 --cur_byte;
3030 }
3031 }
3032
3033 #ifdef HAVE_LONG_DOUBLE
3034 /* Return the fractional part of VALUE, and put the exponent of VALUE in *EPTR.
3035 The range of the returned value is >= 0.5 and < 1.0. This is equivalent to
3036 frexp, but operates on the long double data type. */
3037
3038 static long double ldfrexp PARAMS ((long double value, int *eptr));
3039
3040 static long double
3041 ldfrexp (value, eptr)
3042 long double value;
3043 int *eptr;
3044 {
3045 long double tmp;
3046 int exp;
3047
3048 /* Unfortunately, there are no portable functions for extracting the exponent
3049 of a long double, so we have to do it iteratively by multiplying or dividing
3050 by two until the fraction is between 0.5 and 1.0. */
3051
3052 if (value < 0.0l)
3053 value = -value;
3054
3055 tmp = 1.0l;
3056 exp = 0;
3057
3058 if (value >= tmp) /* Value >= 1.0 */
3059 while (value >= tmp)
3060 {
3061 tmp *= 2.0l;
3062 exp++;
3063 }
3064 else if (value != 0.0l) /* Value < 1.0 and > 0.0 */
3065 {
3066 while (value < tmp)
3067 {
3068 tmp /= 2.0l;
3069 exp--;
3070 }
3071 tmp *= 2.0l;
3072 exp++;
3073 }
3074
3075 *eptr = exp;
3076 return value / tmp;
3077 }
3078 #endif /* HAVE_LONG_DOUBLE */
3079
3080
3081 /* The converse: convert the DOUBLEST *FROM to an extended float
3082 and store where TO points. Neither FROM nor TO have any alignment
3083 restrictions. */
3084
3085 void
3086 floatformat_from_doublest (fmt, from, to)
3087 CONST struct floatformat *fmt;
3088 DOUBLEST *from;
3089 char *to;
3090 {
3091 DOUBLEST dfrom;
3092 int exponent;
3093 DOUBLEST mant;
3094 unsigned int mant_bits, mant_off;
3095 int mant_bits_left;
3096 unsigned char *uto = (unsigned char *) to;
3097
3098 memcpy (&dfrom, from, sizeof (dfrom));
3099 memset (uto, 0, fmt->totalsize / FLOATFORMAT_CHAR_BIT);
3100 if (dfrom == 0)
3101 return; /* Result is zero */
3102 if (dfrom != dfrom) /* Result is NaN */
3103 {
3104 /* From is NaN */
3105 put_field (uto, fmt->byteorder, fmt->totalsize, fmt->exp_start,
3106 fmt->exp_len, fmt->exp_nan);
3107 /* Be sure it's not infinity, but NaN value is irrel */
3108 put_field (uto, fmt->byteorder, fmt->totalsize, fmt->man_start,
3109 32, 1);
3110 return;
3111 }
3112
3113 /* If negative, set the sign bit. */
3114 if (dfrom < 0)
3115 {
3116 put_field (uto, fmt->byteorder, fmt->totalsize, fmt->sign_start, 1, 1);
3117 dfrom = -dfrom;
3118 }
3119
3120 if (dfrom + dfrom == dfrom && dfrom != 0.0) /* Result is Infinity */
3121 {
3122 /* Infinity exponent is same as NaN's. */
3123 put_field (uto, fmt->byteorder, fmt->totalsize, fmt->exp_start,
3124 fmt->exp_len, fmt->exp_nan);
3125 /* Infinity mantissa is all zeroes. */
3126 put_field (uto, fmt->byteorder, fmt->totalsize, fmt->man_start,
3127 fmt->man_len, 0);
3128 return;
3129 }
3130
3131 #ifdef HAVE_LONG_DOUBLE
3132 mant = ldfrexp (dfrom, &exponent);
3133 #else
3134 mant = frexp (dfrom, &exponent);
3135 #endif
3136
3137 put_field (uto, fmt->byteorder, fmt->totalsize, fmt->exp_start, fmt->exp_len,
3138 exponent + fmt->exp_bias - 1);
3139
3140 mant_bits_left = fmt->man_len;
3141 mant_off = fmt->man_start;
3142 while (mant_bits_left > 0)
3143 {
3144 unsigned long mant_long;
3145 mant_bits = mant_bits_left < 32 ? mant_bits_left : 32;
3146
3147 mant *= 4294967296.0;
3148 mant_long = (unsigned long) mant;
3149 mant -= mant_long;
3150
3151 /* If the integer bit is implicit, then we need to discard it.
3152 If we are discarding a zero, we should be (but are not) creating
3153 a denormalized number which means adjusting the exponent
3154 (I think). */
3155 if (mant_bits_left == fmt->man_len
3156 && fmt->intbit == floatformat_intbit_no)
3157 {
3158 mant_long <<= 1;
3159 mant_bits -= 1;
3160 }
3161
3162 if (mant_bits < 32)
3163 {
3164 /* The bits we want are in the most significant MANT_BITS bits of
3165 mant_long. Move them to the least significant. */
3166 mant_long >>= 32 - mant_bits;
3167 }
3168
3169 put_field (uto, fmt->byteorder, fmt->totalsize,
3170 mant_off, mant_bits, mant_long);
3171 mant_off += mant_bits;
3172 mant_bits_left -= mant_bits;
3173 }
3174 if (fmt->byteorder == floatformat_littlebyte_bigword)
3175 {
3176 int count;
3177 unsigned char *swaplow = uto;
3178 unsigned char *swaphigh = uto + 4;
3179 unsigned char tmp;
3180
3181 for (count = 0; count < 4; count++)
3182 {
3183 tmp = *swaplow;
3184 *swaplow++ = *swaphigh;
3185 *swaphigh++ = tmp;
3186 }
3187 }
3188 }
3189
3190 /* temporary storage using circular buffer */
3191 #define NUMCELLS 16
3192 #define CELLSIZE 32
3193 static char *
3194 get_cell ()
3195 {
3196 static char buf[NUMCELLS][CELLSIZE];
3197 static int cell = 0;
3198 if (++cell >= NUMCELLS)
3199 cell = 0;
3200 return buf[cell];
3201 }
3202
3203 /* print routines to handle variable size regs, etc.
3204
3205 FIXME: Note that t_addr is a bfd_vma, which is currently either an
3206 unsigned long or unsigned long long, determined at configure time.
3207 If t_addr is an unsigned long long and sizeof (unsigned long long)
3208 is greater than sizeof (unsigned long), then I believe this code will
3209 probably lose, at least for little endian machines. I believe that
3210 it would also be better to eliminate the switch on the absolute size
3211 of t_addr and replace it with a sequence of if statements that compare
3212 sizeof t_addr with sizeof the various types and do the right thing,
3213 which includes knowing whether or not the host supports long long.
3214 -fnf
3215
3216 */
3217
3218 int
3219 strlen_paddr (void)
3220 {
3221 return (TARGET_PTR_BIT / 8 * 2);
3222 }
3223
3224
3225 /* eliminate warning from compiler on 32-bit systems */
3226 static int thirty_two = 32;
3227
3228 char *
3229 paddr (CORE_ADDR addr)
3230 {
3231 char *paddr_str = get_cell ();
3232 switch (TARGET_PTR_BIT / 8)
3233 {
3234 case 8:
3235 sprintf (paddr_str, "%08lx%08lx",
3236 (unsigned long) (addr >> thirty_two), (unsigned long) (addr & 0xffffffff));
3237 break;
3238 case 4:
3239 sprintf (paddr_str, "%08lx", (unsigned long) addr);
3240 break;
3241 case 2:
3242 sprintf (paddr_str, "%04x", (unsigned short) (addr & 0xffff));
3243 break;
3244 default:
3245 sprintf (paddr_str, "%lx", (unsigned long) addr);
3246 }
3247 return paddr_str;
3248 }
3249
3250 char *
3251 paddr_nz (CORE_ADDR addr)
3252 {
3253 char *paddr_str = get_cell ();
3254 switch (TARGET_PTR_BIT / 8)
3255 {
3256 case 8:
3257 {
3258 unsigned long high = (unsigned long) (addr >> thirty_two);
3259 if (high == 0)
3260 sprintf (paddr_str, "%lx", (unsigned long) (addr & 0xffffffff));
3261 else
3262 sprintf (paddr_str, "%lx%08lx",
3263 high, (unsigned long) (addr & 0xffffffff));
3264 break;
3265 }
3266 case 4:
3267 sprintf (paddr_str, "%lx", (unsigned long) addr);
3268 break;
3269 case 2:
3270 sprintf (paddr_str, "%x", (unsigned short) (addr & 0xffff));
3271 break;
3272 default:
3273 sprintf (paddr_str, "%lx", (unsigned long) addr);
3274 }
3275 return paddr_str;
3276 }
3277
3278 static void
3279 decimal2str (char *paddr_str, char *sign, ULONGEST addr)
3280 {
3281 /* steal code from valprint.c:print_decimal(). Should this worry
3282 about the real size of addr as the above does? */
3283 unsigned long temp[3];
3284 int i = 0;
3285 do
3286 {
3287 temp[i] = addr % (1000 * 1000 * 1000);
3288 addr /= (1000 * 1000 * 1000);
3289 i++;
3290 }
3291 while (addr != 0 && i < (sizeof (temp) / sizeof (temp[0])));
3292 switch (i)
3293 {
3294 case 1:
3295 sprintf (paddr_str, "%s%lu",
3296 sign, temp[0]);
3297 break;
3298 case 2:
3299 sprintf (paddr_str, "%s%lu%09lu",
3300 sign, temp[1], temp[0]);
3301 break;
3302 case 3:
3303 sprintf (paddr_str, "%s%lu%09lu%09lu",
3304 sign, temp[2], temp[1], temp[0]);
3305 break;
3306 default:
3307 abort ();
3308 }
3309 }
3310
3311 char *
3312 paddr_u (CORE_ADDR addr)
3313 {
3314 char *paddr_str = get_cell ();
3315 decimal2str (paddr_str, "", addr);
3316 return paddr_str;
3317 }
3318
3319 char *
3320 paddr_d (LONGEST addr)
3321 {
3322 char *paddr_str = get_cell ();
3323 if (addr < 0)
3324 decimal2str (paddr_str, "-", -addr);
3325 else
3326 decimal2str (paddr_str, "", addr);
3327 return paddr_str;
3328 }
3329
3330 char *
3331 preg (reg)
3332 t_reg reg;
3333 {
3334 char *preg_str = get_cell ();
3335 switch (sizeof (t_reg))
3336 {
3337 case 8:
3338 sprintf (preg_str, "%08lx%08lx",
3339 (unsigned long) (reg >> thirty_two), (unsigned long) (reg & 0xffffffff));
3340 break;
3341 case 4:
3342 sprintf (preg_str, "%08lx", (unsigned long) reg);
3343 break;
3344 case 2:
3345 sprintf (preg_str, "%04x", (unsigned short) (reg & 0xffff));
3346 break;
3347 default:
3348 sprintf (preg_str, "%lx", (unsigned long) reg);
3349 }
3350 return preg_str;
3351 }
3352
3353 char *
3354 preg_nz (reg)
3355 t_reg reg;
3356 {
3357 char *preg_str = get_cell ();
3358 switch (sizeof (t_reg))
3359 {
3360 case 8:
3361 {
3362 unsigned long high = (unsigned long) (reg >> thirty_two);
3363 if (high == 0)
3364 sprintf (preg_str, "%lx", (unsigned long) (reg & 0xffffffff));
3365 else
3366 sprintf (preg_str, "%lx%08lx",
3367 high, (unsigned long) (reg & 0xffffffff));
3368 break;
3369 }
3370 case 4:
3371 sprintf (preg_str, "%lx", (unsigned long) reg);
3372 break;
3373 case 2:
3374 sprintf (preg_str, "%x", (unsigned short) (reg & 0xffff));
3375 break;
3376 default:
3377 sprintf (preg_str, "%lx", (unsigned long) reg);
3378 }
3379 return preg_str;
3380 }
3381
3382 /* Helper functions for INNER_THAN */
3383 int
3384 core_addr_lessthan (lhs, rhs)
3385 CORE_ADDR lhs;
3386 CORE_ADDR rhs;
3387 {
3388 return (lhs < rhs);
3389 }
3390
3391 int
3392 core_addr_greaterthan (lhs, rhs)
3393 CORE_ADDR lhs;
3394 CORE_ADDR rhs;
3395 {
3396 return (lhs > rhs);
3397 }