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