1 /* General utility routines for GDB, the GNU debugger.
2 Copyright 1986, 1989, 1990-1992, 1995, 1996, 1998, 2000
3 Free Software Foundation, Inc.
5 This file is part of GDB.
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.
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.
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. */
24 #include "gdb_string.h"
25 #include "event-top.h"
38 /* SunOS's curses.h has a '#define reg register' in it. Thank you Sun. */
49 #include "expression.h"
53 #include <readline/readline.h>
56 #define XMALLOC(TYPE) ((TYPE*) xmalloc (sizeof (TYPE)))
58 /* readline defines this. */
61 void (*error_begin_hook) PARAMS ((void));
63 /* Holds the last error message issued by gdb */
65 static struct ui_file *gdb_lasterr;
67 /* Prototypes for local functions */
69 static void vfprintf_maybe_filtered (struct ui_file *, const char *,
72 static void fputs_maybe_filtered (const char *, struct ui_file *, int);
74 #if defined (USE_MMALLOC) && !defined (NO_MMCHECK)
75 static void malloc_botch (void);
78 static void prompt_for_continue (void);
80 static void set_width_command (char *, int, struct cmd_list_element *);
82 static void set_width (void);
84 /* Chain of cleanup actions established with make_cleanup,
85 to be executed if an error happens. */
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;
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;
101 /* Nonzero if we have job control. */
105 /* Nonzero means a quit has been requested. */
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. */
122 /* Nonzero means that encoded C++ names should be printed out in their
123 C++ form rather than raw. */
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. */
131 int asm_demangle = 0;
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.) */
137 int sevenbit_strings = 0;
139 /* String to be printed before error messages, if any. */
141 char *error_pre_print;
143 /* String to be printed before quit messages, if any. */
145 char *quit_pre_print;
147 /* String to be printed before warning messages, if any. */
149 char *warning_pre_print = "\nwarning: ";
151 int pagination_enabled = 1;
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. */
160 make_cleanup (make_cleanup_ftype *function, void *arg)
162 return make_my_cleanup (&cleanup_chain, function, arg);
166 make_final_cleanup (make_cleanup_ftype *function, void *arg)
168 return make_my_cleanup (&final_cleanup_chain, function, arg);
172 make_run_cleanup (make_cleanup_ftype *function, void *arg)
174 return make_my_cleanup (&run_cleanup_chain, function, arg);
178 make_exec_cleanup (make_cleanup_ftype *function, void *arg)
180 return make_my_cleanup (&exec_cleanup_chain, function, arg);
184 make_exec_error_cleanup (make_cleanup_ftype *function, void *arg)
186 return make_my_cleanup (&exec_error_cleanup_chain, function, arg);
193 freeargv ((char **) arg);
197 make_cleanup_freeargv (arg)
200 return make_my_cleanup (&cleanup_chain, do_freeargv, arg);
204 do_bfd_close_cleanup (void *arg)
210 make_cleanup_bfd_close (bfd *abfd)
212 return make_cleanup (do_bfd_close_cleanup, abfd);
216 do_close_cleanup (void *arg)
222 make_cleanup_close (int fd)
224 /* int into void*. Outch!! */
225 return make_cleanup (do_close_cleanup, (void *) fd);
229 do_ui_file_delete (void *arg)
231 ui_file_delete (arg);
235 make_cleanup_ui_file_delete (struct ui_file *arg)
237 return make_my_cleanup (&cleanup_chain, do_ui_file_delete, arg);
241 make_my_cleanup (struct cleanup **pmy_chain, make_cleanup_ftype *function,
244 register struct cleanup *new
245 = (struct cleanup *) xmalloc (sizeof (struct cleanup));
246 register struct cleanup *old_chain = *pmy_chain;
248 new->next = *pmy_chain;
249 new->function = function;
256 /* Discard cleanups and do the actions they describe
257 until we get back to the point OLD_CHAIN in the cleanup_chain. */
260 do_cleanups (old_chain)
261 register struct cleanup *old_chain;
263 do_my_cleanups (&cleanup_chain, old_chain);
267 do_final_cleanups (old_chain)
268 register struct cleanup *old_chain;
270 do_my_cleanups (&final_cleanup_chain, old_chain);
274 do_run_cleanups (old_chain)
275 register struct cleanup *old_chain;
277 do_my_cleanups (&run_cleanup_chain, old_chain);
281 do_exec_cleanups (old_chain)
282 register struct cleanup *old_chain;
284 do_my_cleanups (&exec_cleanup_chain, old_chain);
288 do_exec_error_cleanups (old_chain)
289 register struct cleanup *old_chain;
291 do_my_cleanups (&exec_error_cleanup_chain, old_chain);
295 do_my_cleanups (pmy_chain, old_chain)
296 register struct cleanup **pmy_chain;
297 register struct cleanup *old_chain;
299 register struct cleanup *ptr;
300 while ((ptr = *pmy_chain) != old_chain)
302 *pmy_chain = ptr->next; /* Do this first incase recursion */
303 (*ptr->function) (ptr->arg);
308 /* Discard cleanups, not doing the actions they describe,
309 until we get back to the point OLD_CHAIN in the cleanup_chain. */
312 discard_cleanups (old_chain)
313 register struct cleanup *old_chain;
315 discard_my_cleanups (&cleanup_chain, old_chain);
319 discard_final_cleanups (old_chain)
320 register struct cleanup *old_chain;
322 discard_my_cleanups (&final_cleanup_chain, old_chain);
326 discard_exec_error_cleanups (old_chain)
327 register struct cleanup *old_chain;
329 discard_my_cleanups (&exec_error_cleanup_chain, old_chain);
333 discard_my_cleanups (pmy_chain, old_chain)
334 register struct cleanup **pmy_chain;
335 register struct cleanup *old_chain;
337 register struct cleanup *ptr;
338 while ((ptr = *pmy_chain) != old_chain)
340 *pmy_chain = ptr->next;
345 /* Set the cleanup_chain to 0, and return the old cleanup chain. */
349 return save_my_cleanups (&cleanup_chain);
353 save_final_cleanups ()
355 return save_my_cleanups (&final_cleanup_chain);
359 save_my_cleanups (pmy_chain)
360 struct cleanup **pmy_chain;
362 struct cleanup *old_chain = *pmy_chain;
368 /* Restore the cleanup chain from a previously saved chain. */
370 restore_cleanups (chain)
371 struct cleanup *chain;
373 restore_my_cleanups (&cleanup_chain, chain);
377 restore_final_cleanups (chain)
378 struct cleanup *chain;
380 restore_my_cleanups (&final_cleanup_chain, chain);
384 restore_my_cleanups (pmy_chain, chain)
385 struct cleanup **pmy_chain;
386 struct cleanup *chain;
391 /* This function is useful for cleanups.
395 old_chain = make_cleanup (free_current_contents, &foo);
397 to arrange to free the object thus allocated. */
400 free_current_contents (void *ptr)
402 void **location = ptr;
403 if (location == NULL)
404 internal_error ("free_current_contents: NULL pointer");
405 if (*location != NULL)
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. */
421 null_cleanup (void *arg)
425 /* Add a continuation to the continuation list, the gloabl list
426 cmd_continuation. The new continuation will be added at the front.*/
428 add_continuation (continuation_hook, arg_list)
429 void (*continuation_hook) PARAMS ((struct continuation_arg *));
430 struct continuation_arg *arg_list;
432 struct continuation *continuation_ptr;
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;
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.*/
450 do_all_continuations ()
452 struct continuation *continuation_ptr;
453 struct continuation *saved_continuation;
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;
462 /* Work now on the list we have set aside. */
463 while (continuation_ptr)
465 (continuation_ptr->continuation_hook) (continuation_ptr->arg_list);
466 saved_continuation = continuation_ptr;
467 continuation_ptr = continuation_ptr->next;
468 free (saved_continuation);
472 /* Walk down the cmd_continuation list, and get rid of all the
475 discard_all_continuations ()
477 struct continuation *continuation_ptr;
479 while (cmd_continuation)
481 continuation_ptr = cmd_continuation;
482 cmd_continuation = continuation_ptr->next;
483 free (continuation_ptr);
487 /* Add a continuation to the continuation list, the global list
488 intermediate_continuation. The new continuation will be added at the front.*/
490 add_intermediate_continuation (continuation_hook, arg_list)
491 void (*continuation_hook) PARAMS ((struct continuation_arg *));
492 struct continuation_arg *arg_list;
494 struct continuation *continuation_ptr;
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;
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.*/
512 do_all_intermediate_continuations ()
514 struct continuation *continuation_ptr;
515 struct continuation *saved_continuation;
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;
524 /* Work now on the list we have set aside. */
525 while (continuation_ptr)
527 (continuation_ptr->continuation_hook) (continuation_ptr->arg_list);
528 saved_continuation = continuation_ptr;
529 continuation_ptr = continuation_ptr->next;
530 free (saved_continuation);
534 /* Walk down the cmd_continuation list, and get rid of all the
537 discard_all_intermediate_continuations ()
539 struct continuation *continuation_ptr;
541 while (intermediate_continuation)
543 continuation_ptr = intermediate_continuation;
544 intermediate_continuation = continuation_ptr->next;
545 free (continuation_ptr);
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.
557 FIXME: Why do warnings use unfiltered output and errors filtered?
558 Is this anything other than a historical accident? */
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);
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. */
577 warning (const char *string,...)
580 va_start (args, string);
582 (*warning_hook) (string, args);
586 vfprintf_unfiltered (gdb_stderr, string, args);
587 fprintf_unfiltered (gdb_stderr, "\n");
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. */
602 if (error_begin_hook)
605 target_terminal_ours ();
606 wrap_here (""); /* Force out any buffered output */
607 gdb_flush (gdb_stdout);
609 annotate_error_begin ();
612 fprintf_filtered (gdb_stderr, error_pre_print);
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. */
620 verror (const char *string, va_list args)
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
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
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);
648 error (const char *string,...)
651 va_start (args, string);
652 verror (string, args);
657 error_stream (struct ui_file *stream)
660 char *msg = ui_file_xstrdup (stream, &size);
661 make_cleanup (free, msg);
665 /* Get the last error message issued by gdb */
668 error_last_message (void)
671 return ui_file_xstrdup (gdb_lasterr, &len);
674 /* This is to be called by main() at the very beginning */
679 gdb_lasterr = mem_fileopen ();
682 /* Print a message reporting an internal error. Ask the user if they
683 want to continue, dump core, or just exit. */
686 internal_verror (const char *fmt, va_list ap)
688 static char msg[] = "Internal GDB error: recursive internal error.\n";
689 static int dejavu = 0;
693 /* don't allow infinite error recursion. */
701 fputs_unfiltered (msg, gdb_stderr);
705 write (STDERR_FILENO, msg, sizeof (msg));
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);
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? ");
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? ");
743 return_to_top_level (RETURN_ERROR);
747 internal_error (char *string, ...)
750 va_start (ap, string);
752 internal_verror (string, ap);
756 /* The strerror() function can return NULL for errno values that are
757 out of range. Provide a "safe" version that always returns a
761 safe_strerror (errnum)
767 if ((msg = strerror (errnum)) == NULL)
769 sprintf (buf, "(undocumented errno %d)", errnum);
775 /* The strsignal() function can return NULL for signal values that are
776 out of range. Provide a "safe" version that always returns a
780 safe_strsignal (signo)
786 if ((msg = strsignal (signo)) == NULL)
788 sprintf (buf, "(undocumented signal %d)", signo);
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. */
800 perror_with_name (string)
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);
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
815 bfd_set_error (bfd_error_no_error);
818 error ("%s.", combined);
821 /* Print the system error message for ERRCODE, and also mention STRING
822 as the file name for which the error was encountered. */
825 print_sys_errmsg (string, errcode)
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);
838 /* We want anything which was printed on stdout to come out first, before
840 gdb_flush (gdb_stdout);
841 fprintf_unfiltered (gdb_stderr, "%s.\n", combined);
844 /* Control C eventually causes this to be called, at a convenient time. */
849 serial_t gdb_stdout_serial = serial_fdopen (1);
851 target_terminal_ours ();
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
858 /* 1. The _filtered buffer. */
859 wrap_here ((char *) 0);
861 /* 2. The stdio buffer. */
862 gdb_flush (gdb_stdout);
863 gdb_flush (gdb_stderr);
865 /* 3. The system-level buffer. */
866 SERIAL_DRAIN_OUTPUT (gdb_stdout_serial);
867 SERIAL_UN_FDOPEN (gdb_stdout_serial);
869 annotate_error_begin ();
871 /* Don't use *_filtered; we don't want to prompt the user to continue. */
873 fprintf_unfiltered (gdb_stderr, quit_pre_print);
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");
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");
886 fprintf_unfiltered (gdb_stderr,
887 "Quit (expect signal SIGINT when the program is resumed)\n");
889 return_to_top_level (RETURN_QUIT);
893 #if defined(_MSC_VER) /* should test for wingdb instead? */
896 * Windows translates all keyboard and mouse events
897 * into a message which is appended to the message
898 * queue for the process.
904 int k = win32pollquit ();
911 #else /* !defined(_MSC_VER) */
916 /* Done by signals */
919 #endif /* !defined(_MSC_VER) */
921 /* Control C comes here */
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);
940 /* Memory management stuff (malloc friends). */
942 /* Make a substitute size_t for non-ANSI compilers. */
944 #ifndef HAVE_STDDEF_H
946 #define size_t unsigned int
950 #if !defined (USE_MMALLOC)
953 mcalloc (PTR md, size_t number, size_t size)
955 return calloc (number, size);
963 return malloc (size);
967 mrealloc (md, ptr, size)
972 if (ptr == 0) /* Guard against old realloc's */
973 return malloc (size);
975 return realloc (ptr, size);
986 #endif /* USE_MMALLOC */
988 #if !defined (USE_MMALLOC) || defined (NO_MMCHECK)
991 init_malloc (void *md)
995 #else /* Have mmalloc and want corruption checking */
1000 fprintf_unfiltered (gdb_stderr, "Memory corruption\n");
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.
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.
1016 Returns zero on failure, non-zero on success. */
1018 #ifndef MMCHECK_FORCE
1019 #define MMCHECK_FORCE 0
1023 init_malloc (void *md)
1025 if (!mmcheckf (md, malloc_botch, MMCHECK_FORCE))
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(). */
1032 (gdb_stderr, "warning: failed to install memory consistency checks; ");
1034 (gdb_stderr, "configuration should define NO_MMCHECK or MMCHECK_FORCE\n");
1040 #endif /* Have mmalloc and want corruption checking */
1042 /* Called when a memory allocation fails, with the number of bytes of
1043 memory requested in SIZE. */
1051 internal_error ("virtual memory exhausted: can't allocate %ld bytes.", size);
1055 internal_error ("virtual memory exhausted.");
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. */
1075 else if ((val = mmalloc (md, size)) == NULL)
1082 /* Like mrealloc but get error if no storage available. */
1085 xmrealloc (md, ptr, size)
1094 val = mrealloc (md, ptr, size);
1098 val = mmalloc (md, size);
1107 /* Like malloc but get error if no storage available, and protect against
1108 the caller wanting to allocate zero bytes. */
1114 return (xmmalloc ((PTR) NULL, size));
1117 /* Like calloc but get error if no storage available */
1120 xcalloc (size_t number, size_t size)
1122 void *mem = mcalloc (NULL, number, size);
1124 nomem (number * size);
1128 /* Like mrealloc but get error if no storage available. */
1131 xrealloc (ptr, size)
1135 return (xmrealloc ((PTR) NULL, ptr, size));
1139 /* My replacement for the read system call.
1140 Used like `read' but keeps going if `read' returns too soon. */
1143 myread (desc, addr, len)
1153 val = read (desc, addr, len);
1157 return orglen - len;
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. */
1169 savestring (ptr, size)
1173 register char *p = (char *) xmalloc (size + 1);
1174 memcpy (p, ptr, size);
1180 msavestring (void *md, const char *ptr, int size)
1182 register char *p = (char *) xmmalloc (md, size + 1);
1183 memcpy (p, ptr, size);
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? */
1195 return savestring (ptr, strlen (ptr));
1199 mstrsave (void *md, const char *ptr)
1201 return (msavestring (md, ptr, strlen (ptr)));
1205 print_spaces (n, file)
1207 register struct ui_file *file;
1209 fputs_unfiltered (n_spaces (n), file);
1212 /* Print a host address. */
1215 gdb_print_host_address (void *addr, struct ui_file *stream)
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. */
1222 fprintf_filtered (stream, "0x%lx", (unsigned long) addr);
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. */
1232 query (char *ctlstr,...)
1235 register int answer;
1239 va_start (args, ctlstr);
1243 return query_hook (ctlstr, args);
1246 /* Automatically answer "yes" if input is not from a terminal. */
1247 if (!input_from_terminal_p ())
1250 /* FIXME Automatically answer "yes" if called from MacGDB. */
1257 wrap_here (""); /* Flush any buffered output */
1258 gdb_flush (gdb_stdout);
1260 if (annotation_level > 1)
1261 printf_filtered ("\n\032\032pre-query\n");
1263 vfprintf_filtered (gdb_stdout, ctlstr, args);
1264 printf_filtered ("(y or n) ");
1266 if (annotation_level > 1)
1267 printf_filtered ("\n\032\032query\n");
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. */
1273 fputs_unfiltered ("\n", gdb_stdout);
1277 gdb_flush (gdb_stdout);
1280 if (!tui_version || cmdWin == tuiWinWithFocus ())
1282 answer = fgetc (stdin);
1285 answer = (unsigned char) tuiBufferGetc ();
1288 clearerr (stdin); /* in case of C-d */
1289 if (answer == EOF) /* C-d */
1294 /* Eat rest of input line, to EOF or newline */
1295 if ((answer != '\n') || (tui_version && answer != '\r'))
1299 if (!tui_version || cmdWin == tuiWinWithFocus ())
1301 ans2 = fgetc (stdin);
1304 ans2 = (unsigned char) tuiBufferGetc ();
1308 while (ans2 != EOF && ans2 != '\n' && ans2 != '\r');
1309 TUIDO (((TuiOpaqueFuncPtr) tui_vStartNewLines, 1));
1323 printf_filtered ("Please answer y or n.\n");
1326 if (annotation_level > 1)
1327 printf_filtered ("\n\032\032post-query\n");
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.
1338 A negative value means the sequence \ newline was seen,
1339 which is supposed to be equivalent to nothing at all.
1341 If \ is followed by a null character, we return a negative
1342 value and leave the string pointer pointing at the null character.
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. */
1348 parse_escape (string_ptr)
1351 register int c = *(*string_ptr)++;
1355 return 007; /* Bell (alert) char */
1358 case 'e': /* Escape character */
1376 c = *(*string_ptr)++;
1378 c = parse_escape (string_ptr);
1381 return (c & 0200) | (c & 037);
1392 register int i = c - '0';
1393 register int count = 0;
1396 if ((c = *(*string_ptr)++) >= '0' && c <= '7')
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. */
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);
1422 printchar (c, do_fputs, do_fprintf, stream, quoter)
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;
1430 c &= 0xFF; /* Avoid sign bit follies */
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 */
1439 do_fputs ("\\n", stream);
1442 do_fputs ("\\b", stream);
1445 do_fputs ("\\t", stream);
1448 do_fputs ("\\f", stream);
1451 do_fputs ("\\r", stream);
1454 do_fputs ("\\e", stream);
1457 do_fputs ("\\a", stream);
1460 do_fprintf (stream, "\\%.3o", (unsigned int) c);
1466 if (c == '\\' || c == quoter)
1467 do_fputs ("\\", stream);
1468 do_fprintf (stream, "%c", c);
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. */
1478 fputstr_filtered (str, quoter, stream)
1481 struct ui_file *stream;
1484 printchar (*str++, fputs_filtered, fprintf_filtered, stream, quoter);
1488 fputstr_unfiltered (str, quoter, stream)
1491 struct ui_file *stream;
1494 printchar (*str++, fputs_unfiltered, fprintf_unfiltered, stream, quoter);
1498 fputstrn_unfiltered (str, n, quoter, stream)
1502 struct ui_file *stream;
1505 for (i = 0; i < n; i++)
1506 printchar (str[i], fputs_unfiltered, fprintf_unfiltered, stream, quoter);
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;
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. */
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;
1531 /* Pointer in wrap_buffer to the next character to fill. */
1532 static char *wrap_pointer;
1534 /* String to indent by if the wrap occurs. Must not be NULL if wrap_column
1536 static char *wrap_indent;
1538 /* Column number on the screen where wrap_buffer begins, or 0 if wrapping
1539 is not in effect. */
1540 static int wrap_column;
1543 /* Inialize the lines and chars per page */
1548 if (tui_version && m_winPtrNotNull (cmdWin))
1550 lines_per_page = cmdWin->generic.height;
1551 chars_per_line = cmdWin->generic.width;
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 ();
1562 lines_per_page = 24;
1563 chars_per_line = 80;
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. */
1570 char *termtype = getenv ("TERM");
1572 /* Positive means success, nonpositive means failure. */
1575 /* 2048 is large enough for all known terminals, according to the
1576 GNU termcap manual. */
1577 char term_buffer[2048];
1581 status = tgetent (term_buffer, termtype);
1585 int running_in_emacs = getenv ("EMACS") != NULL;
1587 val = tgetnum ("li");
1588 if (val >= 0 && !running_in_emacs)
1589 lines_per_page = val;
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;
1597 val = tgetnum ("co");
1599 chars_per_line = val;
1605 #if defined(SIGWINCH) && defined(SIGWINCH_HANDLER)
1607 /* If there is a better way to determine the window size, use it. */
1608 SIGWINCH_HANDLER (SIGWINCH);
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 */
1621 if (chars_per_line == 0)
1626 wrap_buffer = (char *) xmalloc (chars_per_line + 2);
1627 wrap_buffer[0] = '\0';
1630 wrap_buffer = (char *) xrealloc (wrap_buffer, chars_per_line + 2);
1631 wrap_pointer = wrap_buffer; /* Start it at the beginning */
1636 set_width_command (args, from_tty, c)
1639 struct cmd_list_element *c;
1644 /* Wait, so the user can read what's on the screen. Prompt the user
1645 to continue by pressing RETURN. */
1648 prompt_for_continue ()
1651 char cont_prompt[120];
1653 if (annotation_level > 1)
1654 printf_unfiltered ("\n\032\032pre-prompt-for-continue\n");
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");
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
1664 reinitialize_more_filter ();
1667 /* On a real operating system, the user can quit with SIGINT.
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
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
1677 ignore = readline (cont_prompt);
1679 if (annotation_level > 1)
1680 printf_unfiltered ("\n\032\032post-prompt-for-continue\n");
1685 while (*p == ' ' || *p == '\t')
1690 request_quit (SIGINT);
1692 async_request_quit (0);
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 ();
1702 dont_repeat (); /* Forget prev cmd -- CR won't repeat it. */
1705 /* Reinitialize filter; ie. tell it to reset to original values. */
1708 reinitialize_more_filter ()
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
1721 If the line is already overfull, we immediately print a newline and
1722 the indentation, and disable further wrapping.
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.
1728 INDENT should not contain tabs, as that will mess up the char count
1729 on the next line. FIXME.
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. */
1739 /* This should have been allocated, but be paranoid anyway. */
1745 *wrap_pointer = '\0';
1746 fputs_unfiltered (wrap_buffer, gdb_stdout);
1748 wrap_pointer = wrap_buffer;
1749 wrap_buffer[0] = '\0';
1750 if (chars_per_line == UINT_MAX) /* No line overflow checking */
1754 else if (chars_printed >= chars_per_line)
1756 puts_filtered ("\n");
1758 puts_filtered (indent);
1763 wrap_column = chars_printed;
1767 wrap_indent = indent;
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. */
1779 if (chars_printed > 0)
1781 puts_filtered ("\n");
1786 /* Like fputs but if FILTER is true, pause after every screenful.
1788 Regardless of FILTER can wrap at points other than the final
1789 character of a line.
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
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. */
1800 fputs_maybe_filtered (linebuffer, stream, filter)
1801 const char *linebuffer;
1802 struct ui_file *stream;
1805 const char *lineptr;
1807 if (linebuffer == 0)
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))
1814 fputs_unfiltered (linebuffer, stream);
1818 /* Go through and output each character. Show line extension
1819 when this is necessary; prompt user for new page when this is
1822 lineptr = linebuffer;
1825 /* Possible new page. */
1827 (lines_printed >= lines_per_page - 1))
1828 prompt_for_continue ();
1830 while (*lineptr && *lineptr != '\n')
1832 /* Print a single line. */
1833 if (*lineptr == '\t')
1836 *wrap_pointer++ = '\t';
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;
1848 *wrap_pointer++ = *lineptr;
1850 fputc_unfiltered (*lineptr, stream);
1855 if (chars_printed >= chars_per_line)
1857 unsigned int save_chars = chars_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. */
1865 fputc_unfiltered ('\n', stream);
1867 /* Possible new page. */
1868 if (lines_printed >= lines_per_page - 1)
1869 prompt_for_continue ();
1871 /* Now output indentation and wrapped string */
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 */
1892 if (*lineptr == '\n')
1895 wrap_here ((char *) 0); /* Spit out chars, cancel further wraps */
1897 fputc_unfiltered ('\n', stream);
1904 fputs_filtered (linebuffer, stream)
1905 const char *linebuffer;
1906 struct ui_file *stream;
1908 fputs_maybe_filtered (linebuffer, stream, 1);
1912 putchar_unfiltered (c)
1916 ui_file_write (gdb_stdout, &buf, 1);
1921 fputc_unfiltered (c, stream)
1923 struct ui_file *stream;
1926 ui_file_write (stream, &buf, 1);
1931 fputc_filtered (c, stream)
1933 struct ui_file *stream;
1939 fputs_filtered (buf, stream);
1943 /* puts_debug is like fputs_unfiltered, except it prints special
1944 characters in printable fashion. */
1947 puts_debug (prefix, string, suffix)
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 = "";
1960 if (*string == '\n')
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)
1967 fputs_unfiltered (prev_suffix, gdb_stdlog);
1968 fputs_unfiltered ("\n", gdb_stdlog);
1969 fputs_unfiltered (prefix, gdb_stdlog);
1972 /* Print prefix if we printed a newline during the previous call. */
1976 fputs_unfiltered (prefix, gdb_stdlog);
1979 prev_prefix = prefix;
1980 prev_suffix = suffix;
1982 /* Output characters in a printable format. */
1983 while ((ch = *string++) != '\0')
1989 fputc_unfiltered (ch, gdb_stdlog);
1992 fprintf_unfiltered (gdb_stdlog, "\\x%02x", ch & 0xff);
1996 fputs_unfiltered ("\\\\", gdb_stdlog);
1999 fputs_unfiltered ("\\b", gdb_stdlog);
2002 fputs_unfiltered ("\\f", gdb_stdlog);
2006 fputs_unfiltered ("\\n", gdb_stdlog);
2009 fputs_unfiltered ("\\r", gdb_stdlog);
2012 fputs_unfiltered ("\\t", gdb_stdlog);
2015 fputs_unfiltered ("\\v", gdb_stdlog);
2019 return_p = ch == '\r';
2022 /* Print suffix if we printed a newline. */
2025 fputs_unfiltered (suffix, gdb_stdlog);
2026 fputs_unfiltered ("\n", gdb_stdlog);
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.
2036 Unlike fprintf, this function does not return a value.
2038 We implement three variants, vfprintf (takes a vararg list and stream),
2039 fprintf (takes a stream to write on), and printf (the usual).
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. */
2046 vfprintf_maybe_filtered (stream, format, args, filter)
2047 struct ui_file *stream;
2053 struct cleanup *old_cleanups;
2055 vasprintf (&linebuffer, format, args);
2056 if (linebuffer == NULL)
2058 fputs_unfiltered ("\ngdb: virtual memory exhausted.\n", gdb_stderr);
2061 old_cleanups = make_cleanup (free, linebuffer);
2062 fputs_maybe_filtered (linebuffer, stream, filter);
2063 do_cleanups (old_cleanups);
2068 vfprintf_filtered (stream, format, args)
2069 struct ui_file *stream;
2073 vfprintf_maybe_filtered (stream, format, args, 1);
2077 vfprintf_unfiltered (stream, format, args)
2078 struct ui_file *stream;
2083 struct cleanup *old_cleanups;
2085 vasprintf (&linebuffer, format, args);
2086 if (linebuffer == NULL)
2088 fputs_unfiltered ("\ngdb: virtual memory exhausted.\n", gdb_stderr);
2091 old_cleanups = make_cleanup (free, linebuffer);
2092 fputs_unfiltered (linebuffer, stream);
2093 do_cleanups (old_cleanups);
2097 vprintf_filtered (format, args)
2101 vfprintf_maybe_filtered (gdb_stdout, format, args, 1);
2105 vprintf_unfiltered (format, args)
2109 vfprintf_unfiltered (gdb_stdout, format, args);
2113 fprintf_filtered (struct ui_file * stream, const char *format,...)
2116 va_start (args, format);
2117 vfprintf_filtered (stream, format, args);
2122 fprintf_unfiltered (struct ui_file * stream, const char *format,...)
2125 va_start (args, format);
2126 vfprintf_unfiltered (stream, format, args);
2130 /* Like fprintf_filtered, but prints its result indented.
2131 Called as fprintfi_filtered (spaces, stream, format, ...); */
2134 fprintfi_filtered (int spaces, struct ui_file * stream, const char *format,...)
2137 va_start (args, format);
2138 print_spaces_filtered (spaces, stream);
2140 vfprintf_filtered (stream, format, args);
2146 printf_filtered (const char *format,...)
2149 va_start (args, format);
2150 vfprintf_filtered (gdb_stdout, format, args);
2156 printf_unfiltered (const char *format,...)
2159 va_start (args, format);
2160 vfprintf_unfiltered (gdb_stdout, format, args);
2164 /* Like printf_filtered, but prints it's result indented.
2165 Called as printfi_filtered (spaces, format, ...); */
2168 printfi_filtered (int spaces, const char *format,...)
2171 va_start (args, format);
2172 print_spaces_filtered (spaces, gdb_stdout);
2173 vfprintf_filtered (gdb_stdout, format, args);
2177 /* Easy -- but watch out!
2179 This routine is *not* a replacement for puts()! puts() appends a newline.
2180 This one doesn't, and had better not! */
2183 puts_filtered (string)
2186 fputs_filtered (string, gdb_stdout);
2190 puts_unfiltered (string)
2193 fputs_unfiltered (string, gdb_stdout);
2196 /* Return a pointer to N spaces and a null. The pointer is good
2197 until the next call to here. */
2203 static char *spaces = 0;
2204 static int max_spaces = -1;
2210 spaces = (char *) xmalloc (n + 1);
2211 for (t = spaces + n; t != spaces;)
2217 return spaces + max_spaces - n;
2220 /* Print N spaces. */
2222 print_spaces_filtered (n, stream)
2224 struct ui_file *stream;
2226 fputs_filtered (n_spaces (n), stream);
2229 /* C++ demangler stuff. */
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. */
2237 fprintf_symbol_filtered (stream, name, lang, arg_mode)
2238 struct ui_file *stream;
2247 /* If user wants to see raw output, no problem. */
2250 fputs_filtered (name, stream);
2256 case language_cplus:
2257 demangled = cplus_demangle (name, arg_mode);
2260 demangled = cplus_demangle (name, arg_mode | DMGL_JAVA);
2262 case language_chill:
2263 demangled = chill_demangle (name);
2269 fputs_filtered (demangled ? demangled : name, stream);
2270 if (demangled != NULL)
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).
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++
2288 strcmp_iw (string1, string2)
2289 const char *string1;
2290 const char *string2;
2292 while ((*string1 != '\0') && (*string2 != '\0'))
2294 while (isspace (*string1))
2298 while (isspace (*string2))
2302 if (*string1 != *string2)
2306 if (*string1 != '\0')
2312 return (*string1 != '\0' && *string1 != '(') || (*string2 != '\0');
2318 ** Answer whether string_to_compare is a full or partial match to
2319 ** template_string. The partial match must be in sequence starting
2323 subset_compare (string_to_compare, template_string)
2324 char *string_to_compare;
2325 char *template_string;
2328 if (template_string != (char *) NULL && string_to_compare != (char *) NULL &&
2329 strlen (string_to_compare) <= strlen (template_string))
2330 match = (strncmp (template_string,
2332 strlen (string_to_compare)) == 0);
2339 static void pagination_on_command (char *arg, int from_tty);
2341 pagination_on_command (arg, from_tty)
2345 pagination_enabled = 1;
2348 static void pagination_on_command (char *arg, int from_tty);
2350 pagination_off_command (arg, from_tty)
2354 pagination_enabled = 0;
2361 struct cmd_list_element *c;
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.",
2367 add_show_from_set (c, &showlist);
2368 c->function.sfunc = set_width_command;
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),
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;
2382 set_width_command ((char *) NULL, 0, c);
2385 (add_set_cmd ("demangle", class_support, var_boolean,
2387 "Set demangling of encoded C++ names when displaying symbols.",
2392 (add_set_cmd ("pagination", class_support,
2393 var_boolean, (char *) &pagination_enabled,
2394 "Set state of pagination.", &setlist),
2399 add_com ("am", class_support, pagination_on_command,
2400 "Enable pagination");
2401 add_com ("sm", class_support, pagination_off_command,
2402 "Disable pagination");
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.",
2413 (add_set_cmd ("asm-demangle", class_support, var_boolean,
2414 (char *) &asm_demangle,
2415 "Set demangling of C++ names in disassembly listings.",
2420 /* Machine specific function to handle SIGWINCH signal. */
2422 #ifdef SIGWINCH_HANDLER_BODY
2423 SIGWINCH_HANDLER_BODY
2426 /* Support for converting target fp numbers into host DOUBLEST format. */
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
2432 #include "floatformat.h"
2433 #include <math.h> /* ldexp */
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
2440 static unsigned long get_field (unsigned char *,
2441 enum floatformat_byteorders,
2442 unsigned int, unsigned int, unsigned int);
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;
2454 unsigned long result;
2455 unsigned int cur_byte;
2458 /* Start at the least significant part of the field. */
2459 if (order == floatformat_little || order == floatformat_littlebyte_bigword)
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;
2476 cur_byte = (start + len) / FLOATFORMAT_CHAR_BIT;
2478 ((start + len) % FLOATFORMAT_CHAR_BIT) - FLOATFORMAT_CHAR_BIT;
2480 if (cur_bitshift > -FLOATFORMAT_CHAR_BIT)
2481 result = *(data + cur_byte) >> (-cur_bitshift);
2484 cur_bitshift += FLOATFORMAT_CHAR_BIT;
2485 if (order == floatformat_little || order == floatformat_littlebyte_bigword)
2490 /* Move towards the most significant part of the field. */
2491 while (cur_bitshift < len)
2493 result |= (unsigned long)*(data + cur_byte) << cur_bitshift;
2494 cur_bitshift += FLOATFORMAT_CHAR_BIT;
2495 if (order == floatformat_little || order == floatformat_littlebyte_bigword)
2500 if (len < sizeof(result) * FLOATFORMAT_CHAR_BIT)
2501 /* Mask out bits which are not part of the field */
2502 result &= ((1UL << len) - 1);
2506 /* Convert from FMT to a DOUBLEST.
2507 FROM is the address of the extended float.
2508 Store the DOUBLEST in *TO. */
2511 floatformat_to_doublest (fmt, from, to)
2512 const struct floatformat *fmt;
2516 unsigned char *ufrom = (unsigned char *) from;
2520 unsigned int mant_bits, mant_off;
2522 int special_exponent; /* It's a NaN, denorm or zero */
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.
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. */
2535 if (fmt->byteorder == floatformat_littlebyte_bigword)
2537 static unsigned char *newfrom;
2538 unsigned char *swapin, *swapout;
2541 longswaps = fmt->totalsize / FLOATFORMAT_CHAR_BIT;
2544 if (newfrom == NULL)
2546 newfrom = (unsigned char *) xmalloc (fmt->totalsize);
2551 while (longswaps-- > 0)
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];
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. */
2572 mant_bits_left = fmt->man_len;
2573 mant_off = fmt->man_start;
2576 special_exponent = exponent == 0 || exponent == fmt->exp_nan;
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;
2585 /* Build the result algebraically. Might go infinite, underflow, etc;
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. */
2591 if (!special_exponent)
2593 if (fmt->intbit == floatformat_intbit_no)
2594 dto = ldexp (1.0, exponent);
2599 while (mant_bits_left > 0)
2601 mant_bits = min (mant_bits_left, 32);
2603 mant = get_field (ufrom, fmt->byteorder, fmt->totalsize,
2604 mant_off, mant_bits);
2606 dto += ldexp ((double) mant, exponent - mant_bits);
2607 exponent -= mant_bits;
2608 mant_off += mant_bits;
2609 mant_bits_left -= mant_bits;
2612 /* Negate it if negative. */
2613 if (get_field (ufrom, fmt->byteorder, fmt->totalsize, fmt->sign_start, 1))
2618 static void put_field (unsigned char *, enum floatformat_byteorders,
2620 unsigned int, unsigned int, unsigned long);
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. */
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;
2631 unsigned long stuff_to_put;
2633 unsigned int cur_byte;
2636 /* Start at the least significant part of the field. */
2637 if (order == floatformat_little || order == floatformat_littlebyte_bigword)
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;
2647 cur_byte = (start + len) / FLOATFORMAT_CHAR_BIT;
2649 ((start + len) % FLOATFORMAT_CHAR_BIT) - FLOATFORMAT_CHAR_BIT;
2651 if (cur_bitshift > -FLOATFORMAT_CHAR_BIT)
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);
2659 cur_bitshift += FLOATFORMAT_CHAR_BIT;
2660 if (order == floatformat_little || order == floatformat_littlebyte_bigword)
2665 /* Move towards the most significant part of the field. */
2666 while (cur_bitshift < len)
2668 if (len - cur_bitshift < FLOATFORMAT_CHAR_BIT)
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);
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)
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. */
2691 static long double ldfrexp (long double value, int *eptr);
2694 ldfrexp (value, eptr)
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. */
2711 if (value >= tmp) /* Value >= 1.0 */
2712 while (value >= tmp)
2717 else if (value != 0.0l) /* Value < 1.0 and > 0.0 */
2731 #endif /* HAVE_LONG_DOUBLE */
2734 /* The converse: convert the DOUBLEST *FROM to an extended float
2735 and store where TO points. Neither FROM nor TO have any alignment
2739 floatformat_from_doublest (fmt, from, to)
2740 CONST struct floatformat *fmt;
2747 unsigned int mant_bits, mant_off;
2749 unsigned char *uto = (unsigned char *) to;
2751 memcpy (&dfrom, from, sizeof (dfrom));
2752 memset (uto, 0, (fmt->totalsize + FLOATFORMAT_CHAR_BIT - 1)
2753 / FLOATFORMAT_CHAR_BIT);
2755 return; /* Result is zero */
2756 if (dfrom != dfrom) /* Result 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,
2767 /* If negative, set the sign bit. */
2770 put_field (uto, fmt->byteorder, fmt->totalsize, fmt->sign_start, 1, 1);
2774 if (dfrom + dfrom == dfrom && dfrom != 0.0) /* Result is Infinity */
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,
2785 #ifdef HAVE_LONG_DOUBLE
2786 mant = ldfrexp (dfrom, &exponent);
2788 mant = frexp (dfrom, &exponent);
2791 put_field (uto, fmt->byteorder, fmt->totalsize, fmt->exp_start, fmt->exp_len,
2792 exponent + fmt->exp_bias - 1);
2794 mant_bits_left = fmt->man_len;
2795 mant_off = fmt->man_start;
2796 while (mant_bits_left > 0)
2798 unsigned long mant_long;
2799 mant_bits = mant_bits_left < 32 ? mant_bits_left : 32;
2801 mant *= 4294967296.0;
2802 mant_long = ((unsigned long) mant) & 0xffffffffL;
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
2809 if (mant_bits_left == fmt->man_len
2810 && fmt->intbit == floatformat_intbit_no)
2813 mant_long &= 0xffffffffL;
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;
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;
2829 if (fmt->byteorder == floatformat_littlebyte_bigword)
2832 unsigned char *swaplow = uto;
2833 unsigned char *swaphigh = uto + 4;
2836 for (count = 0; count < 4; count++)
2839 *swaplow++ = *swaphigh;
2845 /* print routines to handle variable size regs, etc. */
2847 /* temporary storage using circular buffer */
2853 static char buf[NUMCELLS][CELLSIZE];
2854 static int cell = 0;
2855 if (++cell >= NUMCELLS)
2863 return (TARGET_PTR_BIT / 8 * 2);
2867 paddr (CORE_ADDR addr)
2869 return phex (addr, TARGET_PTR_BIT / 8);
2873 paddr_nz (CORE_ADDR addr)
2875 return phex_nz (addr, TARGET_PTR_BIT / 8);
2879 decimal2str (char *paddr_str, char *sign, ULONGEST addr)
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];
2887 temp[i] = addr % (1000 * 1000 * 1000);
2888 addr /= (1000 * 1000 * 1000);
2891 while (addr != 0 && i < (sizeof (temp) / sizeof (temp[0])));
2895 sprintf (paddr_str, "%s%lu",
2899 sprintf (paddr_str, "%s%lu%09lu",
2900 sign, temp[1], temp[0]);
2903 sprintf (paddr_str, "%s%lu%09lu%09lu",
2904 sign, temp[2], temp[1], temp[0]);
2912 paddr_u (CORE_ADDR addr)
2914 char *paddr_str = get_cell ();
2915 decimal2str (paddr_str, "", addr);
2920 paddr_d (LONGEST addr)
2922 char *paddr_str = get_cell ();
2924 decimal2str (paddr_str, "-", -addr);
2926 decimal2str (paddr_str, "", addr);
2930 /* eliminate warning from compiler on 32-bit systems */
2931 static int thirty_two = 32;
2934 phex (ULONGEST l, int sizeof_l)
2936 char *str = get_cell ();
2940 sprintf (str, "%08lx%08lx",
2941 (unsigned long) (l >> thirty_two),
2942 (unsigned long) (l & 0xffffffff));
2945 sprintf (str, "%08lx", (unsigned long) l);
2948 sprintf (str, "%04x", (unsigned short) (l & 0xffff));
2951 phex (l, sizeof (l));
2958 phex_nz (ULONGEST l, int sizeof_l)
2960 char *str = get_cell ();
2965 unsigned long high = (unsigned long) (l >> thirty_two);
2967 sprintf (str, "%lx", (unsigned long) (l & 0xffffffff));
2969 sprintf (str, "%lx%08lx",
2970 high, (unsigned long) (l & 0xffffffff));
2974 sprintf (str, "%lx", (unsigned long) l);
2977 sprintf (str, "%x", (unsigned short) (l & 0xffff));
2980 phex_nz (l, sizeof (l));