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