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