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