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