1 /* General utility routines for GDB, the GNU debugger.
3 Copyright (C) 1986, 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995, 1996,
4 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008,
5 2009, 2010 Free Software Foundation, Inc.
7 This file is part of GDB.
9 This program is free software; you can redistribute it and/or modify
10 it under the terms of the GNU General Public License as published by
11 the Free Software Foundation; either version 3 of the License, or
12 (at your option) any later version.
14 This program is distributed in the hope that it will be useful,
15 but WITHOUT ANY WARRANTY; without even the implied warranty of
16 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 GNU General Public License for more details.
19 You should have received a copy of the GNU General Public License
20 along with this program. If not, see <http://www.gnu.org/licenses/>. */
23 #include "gdb_assert.h"
25 #include "gdb_string.h"
26 #include "event-top.h"
27 #include "exceptions.h"
28 #include "gdbthread.h"
29 #ifdef HAVE_SYS_RESOURCE_H
30 #include <sys/resource.h>
31 #endif /* HAVE_SYS_RESOURCE_H */
34 #include "tui/tui.h" /* For tui_get_command_dimension. */
41 /* SunOS's curses.h has a '#define reg register' in it. Thank you Sun. */
52 #include "expression.h"
56 #include "filenames.h"
58 #include "gdb_obstack.h"
63 #include "inferior.h" /* for signed_pointer_to_address */
65 #include <sys/param.h> /* For MAXPATHLEN */
67 #include "gdb_curses.h"
69 #include "readline/readline.h"
74 #include "gdb_usleep.h"
78 extern PTR malloc (); /* ARI: PTR */
80 #if !HAVE_DECL_REALLOC
81 extern PTR realloc (); /* ARI: PTR */
87 /* readline defines this. */
90 void (*deprecated_error_begin_hook) (void);
92 /* Prototypes for local functions */
94 static void vfprintf_maybe_filtered (struct ui_file *, const char *,
95 va_list, int) ATTRIBUTE_PRINTF (2, 0);
97 static void fputs_maybe_filtered (const char *, struct ui_file *, int);
99 static void do_my_cleanups (struct cleanup **, struct cleanup *);
101 static void prompt_for_continue (void);
103 static void set_screen_size (void);
104 static void set_width (void);
106 /* A flag indicating whether to timestamp debugging messages. */
108 static int debug_timestamp = 0;
110 /* Chain of cleanup actions established with make_cleanup,
111 to be executed if an error happens. */
113 static struct cleanup *cleanup_chain; /* cleaned up after a failed command */
114 static struct cleanup *final_cleanup_chain; /* cleaned up when gdb exits */
116 /* Nonzero if we have job control. */
120 /* Nonzero means a quit has been requested. */
124 /* Nonzero means quit immediately if Control-C is typed now, rather
125 than waiting until QUIT is executed. Be careful in setting this;
126 code which executes with immediate_quit set has to be very careful
127 about being able to deal with being interrupted at any time. It is
128 almost always better to use QUIT; the only exception I can think of
129 is being able to quit out of a system call (using EINTR loses if
130 the SIGINT happens between the previous QUIT and the system call).
131 To immediately quit in the case in which a SIGINT happens between
132 the previous QUIT and setting immediate_quit (desirable anytime we
133 expect to block), call QUIT after setting immediate_quit. */
137 /* Nonzero means that encoded C++/ObjC names should be printed out in their
138 C++/ObjC form rather than raw. */
142 show_demangle (struct ui_file *file, int from_tty,
143 struct cmd_list_element *c, const char *value)
145 fprintf_filtered (file, _("\
146 Demangling of encoded C++/ObjC names when displaying symbols is %s.\n"),
150 /* Nonzero means that encoded C++/ObjC names should be printed out in their
151 C++/ObjC form even in assembler language displays. If this is set, but
152 DEMANGLE is zero, names are printed raw, i.e. DEMANGLE controls. */
154 int asm_demangle = 0;
156 show_asm_demangle (struct ui_file *file, int from_tty,
157 struct cmd_list_element *c, const char *value)
159 fprintf_filtered (file, _("\
160 Demangling of C++/ObjC names in disassembly listings is %s.\n"),
164 /* Nonzero means that strings with character values >0x7F should be printed
165 as octal escapes. Zero means just print the value (e.g. it's an
166 international character, and the terminal or window can cope.) */
168 int sevenbit_strings = 0;
170 show_sevenbit_strings (struct ui_file *file, int from_tty,
171 struct cmd_list_element *c, const char *value)
173 fprintf_filtered (file, _("\
174 Printing of 8-bit characters in strings as \\nnn is %s.\n"),
178 /* String to be printed before error messages, if any. */
180 char *error_pre_print;
182 /* String to be printed before quit messages, if any. */
184 char *quit_pre_print;
186 /* String to be printed before warning messages, if any. */
188 char *warning_pre_print = "\nwarning: ";
190 int pagination_enabled = 1;
192 show_pagination_enabled (struct ui_file *file, int from_tty,
193 struct cmd_list_element *c, const char *value)
195 fprintf_filtered (file, _("State of pagination is %s.\n"), value);
200 /* Add a new cleanup to the cleanup_chain,
201 and return the previous chain pointer
202 to be passed later to do_cleanups or discard_cleanups.
203 Args are FUNCTION to clean up with, and ARG to pass to it. */
206 make_cleanup (make_cleanup_ftype *function, void *arg)
208 return make_my_cleanup (&cleanup_chain, function, arg);
212 make_cleanup_dtor (make_cleanup_ftype *function, void *arg,
213 void (*dtor) (void *))
215 return make_my_cleanup2 (&cleanup_chain,
216 function, arg, dtor);
220 make_final_cleanup (make_cleanup_ftype *function, void *arg)
222 return make_my_cleanup (&final_cleanup_chain, function, arg);
226 do_freeargv (void *arg)
228 freeargv ((char **) arg);
232 make_cleanup_freeargv (char **arg)
234 return make_my_cleanup (&cleanup_chain, do_freeargv, arg);
238 do_bfd_close_cleanup (void *arg)
244 make_cleanup_bfd_close (bfd *abfd)
246 return make_cleanup (do_bfd_close_cleanup, abfd);
250 do_close_cleanup (void *arg)
258 make_cleanup_close (int fd)
260 int *saved_fd = xmalloc (sizeof (fd));
263 return make_cleanup_dtor (do_close_cleanup, saved_fd, xfree);
266 /* Helper function which does the work for make_cleanup_fclose. */
269 do_fclose_cleanup (void *arg)
276 /* Return a new cleanup that closes FILE. */
279 make_cleanup_fclose (FILE *file)
281 return make_cleanup (do_fclose_cleanup, file);
284 /* Helper function which does the work for make_cleanup_obstack_free. */
287 do_obstack_free (void *arg)
289 struct obstack *ob = arg;
291 obstack_free (ob, NULL);
294 /* Return a new cleanup that frees OBSTACK. */
297 make_cleanup_obstack_free (struct obstack *obstack)
299 return make_cleanup (do_obstack_free, obstack);
303 do_ui_file_delete (void *arg)
305 ui_file_delete (arg);
309 make_cleanup_ui_file_delete (struct ui_file *arg)
311 return make_my_cleanup (&cleanup_chain, do_ui_file_delete, arg);
315 do_free_section_addr_info (void *arg)
317 free_section_addr_info (arg);
321 make_cleanup_free_section_addr_info (struct section_addr_info *addrs)
323 return make_my_cleanup (&cleanup_chain, do_free_section_addr_info, addrs);
326 struct restore_integer_closure
333 restore_integer (void *p)
335 struct restore_integer_closure *closure = p;
337 *(closure->variable) = closure->value;
340 /* Remember the current value of *VARIABLE and make it restored when the cleanup
344 make_cleanup_restore_integer (int *variable)
346 struct restore_integer_closure *c =
347 xmalloc (sizeof (struct restore_integer_closure));
349 c->variable = variable;
350 c->value = *variable;
352 return make_my_cleanup2 (&cleanup_chain, restore_integer, (void *)c,
356 /* Remember the current value of *VARIABLE and make it restored when the cleanup
360 make_cleanup_restore_uinteger (unsigned int *variable)
362 return make_cleanup_restore_integer ((int *) variable);
365 struct restore_ui_file_closure
367 struct ui_file **variable;
368 struct ui_file *value;
372 do_restore_ui_file (void *p)
374 struct restore_ui_file_closure *closure = p;
376 *(closure->variable) = closure->value;
379 /* Remember the current value of *VARIABLE and make it restored when
380 the cleanup is run. */
383 make_cleanup_restore_ui_file (struct ui_file **variable)
385 struct restore_ui_file_closure *c = XNEW (struct restore_ui_file_closure);
387 c->variable = variable;
388 c->value = *variable;
390 return make_cleanup_dtor (do_restore_ui_file, (void *) c, xfree);
394 make_my_cleanup2 (struct cleanup **pmy_chain, make_cleanup_ftype *function,
395 void *arg, void (*free_arg) (void *))
398 = (struct cleanup *) xmalloc (sizeof (struct cleanup));
399 struct cleanup *old_chain = *pmy_chain;
401 new->next = *pmy_chain;
402 new->function = function;
403 new->free_arg = free_arg;
411 make_my_cleanup (struct cleanup **pmy_chain, make_cleanup_ftype *function,
414 return make_my_cleanup2 (pmy_chain, function, arg, NULL);
417 /* Discard cleanups and do the actions they describe
418 until we get back to the point OLD_CHAIN in the cleanup_chain. */
421 do_cleanups (struct cleanup *old_chain)
423 do_my_cleanups (&cleanup_chain, old_chain);
427 do_final_cleanups (struct cleanup *old_chain)
429 do_my_cleanups (&final_cleanup_chain, old_chain);
433 do_my_cleanups (struct cleanup **pmy_chain,
434 struct cleanup *old_chain)
438 while ((ptr = *pmy_chain) != old_chain)
440 *pmy_chain = ptr->next; /* Do this first incase recursion */
441 (*ptr->function) (ptr->arg);
443 (*ptr->free_arg) (ptr->arg);
448 /* Discard cleanups, not doing the actions they describe,
449 until we get back to the point OLD_CHAIN in the cleanup_chain. */
452 discard_cleanups (struct cleanup *old_chain)
454 discard_my_cleanups (&cleanup_chain, old_chain);
458 discard_final_cleanups (struct cleanup *old_chain)
460 discard_my_cleanups (&final_cleanup_chain, old_chain);
464 discard_my_cleanups (struct cleanup **pmy_chain,
465 struct cleanup *old_chain)
469 while ((ptr = *pmy_chain) != old_chain)
471 *pmy_chain = ptr->next;
473 (*ptr->free_arg) (ptr->arg);
478 /* Set the cleanup_chain to 0, and return the old cleanup chain. */
482 return save_my_cleanups (&cleanup_chain);
486 save_final_cleanups (void)
488 return save_my_cleanups (&final_cleanup_chain);
492 save_my_cleanups (struct cleanup **pmy_chain)
494 struct cleanup *old_chain = *pmy_chain;
500 /* Restore the cleanup chain from a previously saved chain. */
502 restore_cleanups (struct cleanup *chain)
504 restore_my_cleanups (&cleanup_chain, chain);
508 restore_final_cleanups (struct cleanup *chain)
510 restore_my_cleanups (&final_cleanup_chain, chain);
514 restore_my_cleanups (struct cleanup **pmy_chain, struct cleanup *chain)
519 /* This function is useful for cleanups.
523 old_chain = make_cleanup (free_current_contents, &foo);
525 to arrange to free the object thus allocated. */
528 free_current_contents (void *ptr)
530 void **location = ptr;
532 if (location == NULL)
533 internal_error (__FILE__, __LINE__,
534 _("free_current_contents: NULL pointer"));
535 if (*location != NULL)
542 /* Provide a known function that does nothing, to use as a base for
543 for a possibly long chain of cleanups. This is useful where we
544 use the cleanup chain for handling normal cleanups as well as dealing
545 with cleanups that need to be done as a result of a call to error().
546 In such cases, we may not be certain where the first cleanup is, unless
547 we have a do-nothing one to always use as the base. */
550 null_cleanup (void *arg)
554 /* If nonzero, display time usage both at startup and for each command. */
556 static int display_time;
558 /* If nonzero, display space usage both at startup and for each command. */
560 static int display_space;
562 /* Records a run time and space usage to be used as a base for
563 reporting elapsed time or change in space. In addition,
564 the msg_type field indicates whether the saved time is from the
565 beginning of GDB execution (0) or the beginning of an individual
566 command execution (1). */
574 /* Set whether to display time statistics to NEW_VALUE (non-zero
577 set_display_time (int new_value)
579 display_time = new_value;
582 /* Set whether to display space statistics to NEW_VALUE (non-zero
585 set_display_space (int new_value)
587 display_space = new_value;
590 /* As indicated by display_time and display_space, report GDB's elapsed time
591 and space usage from the base time and space provided in ARG, which
592 must be a pointer to a struct cmd_stat. This function is intended
593 to be called as a cleanup. */
595 report_command_stats (void *arg)
597 struct cmd_stats *start_stats = (struct cmd_stats *) arg;
598 int msg_type = start_stats->msg_type;
602 long cmd_time = get_run_time () - start_stats->start_time;
604 printf_unfiltered (msg_type == 0
605 ? _("Startup time: %ld.%06ld\n")
606 : _("Command execution time: %ld.%06ld\n"),
607 cmd_time / 1000000, cmd_time % 1000000);
613 char *lim = (char *) sbrk (0);
615 long space_now = lim - lim_at_start;
616 long space_diff = space_now - start_stats->start_space;
618 printf_unfiltered (msg_type == 0
619 ? _("Space used: %ld (%c%ld during startup)\n")
620 : _("Space used: %ld (%c%ld for this command)\n"),
622 (space_diff >= 0 ? '+' : '-'),
628 /* Create a cleanup that reports time and space used since its
629 creation. Precise messages depend on MSG_TYPE:
630 0: Initial time/space
631 1: Individual command time/space. */
633 make_command_stats_cleanup (int msg_type)
635 struct cmd_stats *new_stat = XMALLOC (struct cmd_stats);
638 char *lim = (char *) sbrk (0);
639 new_stat->start_space = lim - lim_at_start;
642 new_stat->msg_type = msg_type;
643 new_stat->start_time = get_run_time ();
645 return make_cleanup_dtor (report_command_stats, new_stat, xfree);
648 /* Continuations are implemented as cleanups internally. Inherit from
655 /* Add a continuation to the continuation list of THREAD. The new
656 continuation will be added at the front. */
658 add_continuation (struct thread_info *thread,
659 void (*continuation_hook) (void *), void *args,
660 void (*continuation_free_args) (void *))
662 struct cleanup *as_cleanup = &thread->continuations->base;
663 make_cleanup_ftype *continuation_hook_fn = continuation_hook;
665 make_my_cleanup2 (&as_cleanup,
666 continuation_hook_fn,
668 continuation_free_args);
670 thread->continuations = (struct continuation *) as_cleanup;
673 /* Add a continuation to the continuation list of INFERIOR. The new
674 continuation will be added at the front. */
677 add_inferior_continuation (void (*continuation_hook) (void *), void *args,
678 void (*continuation_free_args) (void *))
680 struct inferior *inf = current_inferior ();
681 struct cleanup *as_cleanup = &inf->continuations->base;
682 make_cleanup_ftype *continuation_hook_fn = continuation_hook;
684 make_my_cleanup2 (&as_cleanup,
685 continuation_hook_fn,
687 continuation_free_args);
689 inf->continuations = (struct continuation *) as_cleanup;
692 /* Do all continuations of the current inferior. */
695 do_all_inferior_continuations (void)
697 struct cleanup *as_cleanup;
698 struct inferior *inf = current_inferior ();
700 if (inf->continuations == NULL)
703 /* Copy the list header into another pointer, and set the global
704 list header to null, so that the global list can change as a side
705 effect of invoking the continuations and the processing of the
706 preexisting continuations will not be affected. */
708 as_cleanup = &inf->continuations->base;
709 inf->continuations = NULL;
711 /* Work now on the list we have set aside. */
712 do_my_cleanups (&as_cleanup, NULL);
715 /* Get rid of all the inferior-wide continuations of INF. */
718 discard_all_inferior_continuations (struct inferior *inf)
720 struct cleanup *continuation_ptr = &inf->continuations->base;
722 discard_my_cleanups (&continuation_ptr, NULL);
723 inf->continuations = NULL;
727 restore_thread_cleanup (void *arg)
729 ptid_t *ptid_p = arg;
731 switch_to_thread (*ptid_p);
734 /* Walk down the continuation list of PTID, and execute all the
735 continuations. There is a problem though. In some cases new
736 continuations may be added while we are in the middle of this loop.
737 If this happens they will be added in the front, and done before we
738 have a chance of exhausting those that were already there. We need
739 to then save the beginning of the list in a pointer and do the
740 continuations from there on, instead of using the global beginning
741 of list as our iteration pointer. */
743 do_all_continuations_ptid (ptid_t ptid,
744 struct continuation **continuations_p)
746 struct cleanup *old_chain;
747 ptid_t current_thread;
748 struct cleanup *as_cleanup;
750 if (*continuations_p == NULL)
753 current_thread = inferior_ptid;
755 /* Restore selected thread on exit. Don't try to restore the frame
758 - When running continuations, the selected frame is always #0.
760 - The continuations may trigger symbol file loads, which may
761 change the frame layout (frame ids change), which would trigger
762 a warning if we used make_cleanup_restore_current_thread. */
764 old_chain = make_cleanup (restore_thread_cleanup, ¤t_thread);
766 /* Let the continuation see this thread as selected. */
767 switch_to_thread (ptid);
769 /* Copy the list header into another pointer, and set the global
770 list header to null, so that the global list can change as a side
771 effect of invoking the continuations and the processing of the
772 preexisting continuations will not be affected. */
774 as_cleanup = &(*continuations_p)->base;
775 *continuations_p = NULL;
777 /* Work now on the list we have set aside. */
778 do_my_cleanups (&as_cleanup, NULL);
780 do_cleanups (old_chain);
783 /* Callback for iterate over threads. */
785 do_all_continuations_thread_callback (struct thread_info *thread, void *data)
787 do_all_continuations_ptid (thread->ptid, &thread->continuations);
791 /* Do all continuations of thread THREAD. */
793 do_all_continuations_thread (struct thread_info *thread)
795 do_all_continuations_thread_callback (thread, NULL);
798 /* Do all continuations of all threads. */
800 do_all_continuations (void)
802 iterate_over_threads (do_all_continuations_thread_callback, NULL);
805 /* Callback for iterate over threads. */
807 discard_all_continuations_thread_callback (struct thread_info *thread,
810 struct cleanup *continuation_ptr = &thread->continuations->base;
812 discard_my_cleanups (&continuation_ptr, NULL);
813 thread->continuations = NULL;
817 /* Get rid of all the continuations of THREAD. */
819 discard_all_continuations_thread (struct thread_info *thread)
821 discard_all_continuations_thread_callback (thread, NULL);
824 /* Get rid of all the continuations of all threads. */
826 discard_all_continuations (void)
828 iterate_over_threads (discard_all_continuations_thread_callback, NULL);
832 /* Add a continuation to the intermediate continuation list of THREAD.
833 The new continuation will be added at the front. */
835 add_intermediate_continuation (struct thread_info *thread,
836 void (*continuation_hook)
837 (void *), void *args,
838 void (*continuation_free_args) (void *))
840 struct cleanup *as_cleanup = &thread->intermediate_continuations->base;
841 make_cleanup_ftype *continuation_hook_fn = continuation_hook;
843 make_my_cleanup2 (&as_cleanup,
844 continuation_hook_fn,
846 continuation_free_args);
848 thread->intermediate_continuations = (struct continuation *) as_cleanup;
851 /* Walk down the cmd_continuation list, and execute all the
852 continuations. There is a problem though. In some cases new
853 continuations may be added while we are in the middle of this
854 loop. If this happens they will be added in the front, and done
855 before we have a chance of exhausting those that were already
856 there. We need to then save the beginning of the list in a pointer
857 and do the continuations from there on, instead of using the
858 global beginning of list as our iteration pointer.*/
860 do_all_intermediate_continuations_thread_callback (struct thread_info *thread,
863 do_all_continuations_ptid (thread->ptid,
864 &thread->intermediate_continuations);
868 /* Do all intermediate continuations of thread THREAD. */
870 do_all_intermediate_continuations_thread (struct thread_info *thread)
872 do_all_intermediate_continuations_thread_callback (thread, NULL);
875 /* Do all intermediate continuations of all threads. */
877 do_all_intermediate_continuations (void)
879 iterate_over_threads (do_all_intermediate_continuations_thread_callback, NULL);
882 /* Callback for iterate over threads. */
884 discard_all_intermediate_continuations_thread_callback (struct thread_info *thread,
887 struct cleanup *continuation_ptr = &thread->intermediate_continuations->base;
889 discard_my_cleanups (&continuation_ptr, NULL);
890 thread->intermediate_continuations = NULL;
894 /* Get rid of all the intermediate continuations of THREAD. */
896 discard_all_intermediate_continuations_thread (struct thread_info *thread)
898 discard_all_intermediate_continuations_thread_callback (thread, NULL);
901 /* Get rid of all the intermediate continuations of all threads. */
903 discard_all_intermediate_continuations (void)
905 iterate_over_threads (discard_all_intermediate_continuations_thread_callback, NULL);
910 /* Print a warning message. The first argument STRING is the warning
911 message, used as an fprintf format string, the second is the
912 va_list of arguments for that string. A warning is unfiltered (not
913 paginated) so that the user does not need to page through each
914 screen full of warnings when there are lots of them. */
917 vwarning (const char *string, va_list args)
919 if (deprecated_warning_hook)
920 (*deprecated_warning_hook) (string, args);
923 target_terminal_ours ();
924 wrap_here (""); /* Force out any buffered output */
925 gdb_flush (gdb_stdout);
926 if (warning_pre_print)
927 fputs_unfiltered (warning_pre_print, gdb_stderr);
928 vfprintf_unfiltered (gdb_stderr, string, args);
929 fprintf_unfiltered (gdb_stderr, "\n");
934 /* Print a warning message.
935 The first argument STRING is the warning message, used as a fprintf string,
936 and the remaining args are passed as arguments to it.
937 The primary difference between warnings and errors is that a warning
938 does not force the return to command level. */
941 warning (const char *string, ...)
945 va_start (args, string);
946 vwarning (string, args);
950 /* Print an error message and return to command level.
951 The first argument STRING is the error message, used as a fprintf string,
952 and the remaining args are passed as arguments to it. */
955 verror (const char *string, va_list args)
957 throw_verror (GENERIC_ERROR, string, args);
961 error (const char *string, ...)
965 va_start (args, string);
966 throw_verror (GENERIC_ERROR, string, args);
970 /* Print an error message and quit.
971 The first argument STRING is the error message, used as a fprintf string,
972 and the remaining args are passed as arguments to it. */
975 vfatal (const char *string, va_list args)
977 throw_vfatal (string, args);
981 fatal (const char *string, ...)
985 va_start (args, string);
986 throw_vfatal (string, args);
991 error_stream (struct ui_file *stream)
993 char *message = ui_file_xstrdup (stream, NULL);
995 make_cleanup (xfree, message);
996 error (("%s"), message);
999 /* Dump core trying to increase the core soft limit to hard limit first. */
1004 #ifdef HAVE_SETRLIMIT
1005 struct rlimit rlim = { RLIM_INFINITY, RLIM_INFINITY };
1007 setrlimit (RLIMIT_CORE, &rlim);
1008 #endif /* HAVE_SETRLIMIT */
1010 abort (); /* NOTE: GDB has only three calls to abort(). */
1013 /* Check whether GDB will be able to dump core using the dump_core function. */
1016 can_dump_core (const char *reason)
1018 #ifdef HAVE_GETRLIMIT
1021 /* Be quiet and assume we can dump if an error is returned. */
1022 if (getrlimit (RLIMIT_CORE, &rlim) != 0)
1025 if (rlim.rlim_max == 0)
1027 fprintf_unfiltered (gdb_stderr,
1028 _("%s\nUnable to dump core, use `ulimit -c unlimited'"
1029 " before executing GDB next time.\n"), reason);
1032 #endif /* HAVE_GETRLIMIT */
1037 /* Allow the user to configure the debugger behavior with respect to
1038 what to do when an internal problem is detected. */
1040 const char internal_problem_ask[] = "ask";
1041 const char internal_problem_yes[] = "yes";
1042 const char internal_problem_no[] = "no";
1043 static const char *internal_problem_modes[] =
1045 internal_problem_ask,
1046 internal_problem_yes,
1047 internal_problem_no,
1051 /* Print a message reporting an internal error/warning. Ask the user
1052 if they want to continue, dump core, or just exit. Return
1053 something to indicate a quit. */
1055 struct internal_problem
1058 const char *should_quit;
1059 const char *should_dump_core;
1062 /* Report a problem, internal to GDB, to the user. Once the problem
1063 has been reported, and assuming GDB didn't quit, the caller can
1064 either allow execution to resume or throw an error. */
1066 static void ATTRIBUTE_PRINTF (4, 0)
1067 internal_vproblem (struct internal_problem *problem,
1068 const char *file, int line, const char *fmt, va_list ap)
1075 /* Don't allow infinite error/warning recursion. */
1077 static char msg[] = "Recursive internal problem.\n";
1086 fputs_unfiltered (msg, gdb_stderr);
1087 abort (); /* NOTE: GDB has only three calls to abort(). */
1090 /* Newer GLIBC versions put the warn_unused_result attribute
1091 on write, but this is one of those rare cases where
1092 ignoring the return value is correct. Casting to (void)
1093 does not fix this problem. This is the solution suggested
1094 at http://gcc.gnu.org/bugzilla/show_bug.cgi?id=25509. */
1095 if (write (STDERR_FILENO, msg, sizeof (msg)) != sizeof (msg))
1096 abort (); /* NOTE: GDB has only three calls to abort(). */
1101 /* Try to get the message out and at the start of a new line. */
1102 target_terminal_ours ();
1105 /* Create a string containing the full error/warning message. Need
1106 to call query with this full string, as otherwize the reason
1107 (error/warning) and question become separated. Format using a
1108 style similar to a compiler error message. Include extra detail
1109 so that the user knows that they are living on the edge. */
1113 msg = xstrvprintf (fmt, ap);
1114 reason = xstrprintf ("\
1116 A problem internal to GDB has been detected,\n\
1117 further debugging may prove unreliable.", file, line, problem->name, msg);
1119 make_cleanup (xfree, reason);
1122 if (problem->should_quit == internal_problem_ask)
1124 /* Default (yes/batch case) is to quit GDB. When in batch mode
1125 this lessens the likelihood of GDB going into an infinite
1129 /* Emit the message and quit. */
1130 fputs_unfiltered (reason, gdb_stderr);
1131 fputs_unfiltered ("\n", gdb_stderr);
1135 quit_p = query (_("%s\nQuit this debugging session? "), reason);
1137 else if (problem->should_quit == internal_problem_yes)
1139 else if (problem->should_quit == internal_problem_no)
1142 internal_error (__FILE__, __LINE__, _("bad switch"));
1144 if (problem->should_dump_core == internal_problem_ask)
1146 if (!can_dump_core (reason))
1150 /* Default (yes/batch case) is to dump core. This leaves a GDB
1151 `dropping' so that it is easier to see that something went
1153 dump_core_p = query (_("%s\nCreate a core file of GDB? "), reason);
1156 else if (problem->should_dump_core == internal_problem_yes)
1157 dump_core_p = can_dump_core (reason);
1158 else if (problem->should_dump_core == internal_problem_no)
1161 internal_error (__FILE__, __LINE__, _("bad switch"));
1174 #ifdef HAVE_WORKING_FORK
1184 static struct internal_problem internal_error_problem = {
1185 "internal-error", internal_problem_ask, internal_problem_ask
1189 internal_verror (const char *file, int line, const char *fmt, va_list ap)
1191 internal_vproblem (&internal_error_problem, file, line, fmt, ap);
1192 deprecated_throw_reason (RETURN_ERROR);
1196 internal_error (const char *file, int line, const char *string, ...)
1200 va_start (ap, string);
1201 internal_verror (file, line, string, ap);
1205 static struct internal_problem internal_warning_problem = {
1206 "internal-warning", internal_problem_ask, internal_problem_ask
1210 internal_vwarning (const char *file, int line, const char *fmt, va_list ap)
1212 internal_vproblem (&internal_warning_problem, file, line, fmt, ap);
1216 internal_warning (const char *file, int line, const char *string, ...)
1220 va_start (ap, string);
1221 internal_vwarning (file, line, string, ap);
1225 /* Dummy functions to keep add_prefix_cmd happy. */
1228 set_internal_problem_cmd (char *args, int from_tty)
1233 show_internal_problem_cmd (char *args, int from_tty)
1237 /* When GDB reports an internal problem (error or warning) it gives
1238 the user the opportunity to quit GDB and/or create a core file of
1239 the current debug session. This function registers a few commands
1240 that make it possible to specify that GDB should always or never
1241 quit or create a core file, without asking. The commands look
1244 maint set PROBLEM-NAME quit ask|yes|no
1245 maint show PROBLEM-NAME quit
1246 maint set PROBLEM-NAME corefile ask|yes|no
1247 maint show PROBLEM-NAME corefile
1249 Where PROBLEM-NAME is currently "internal-error" or
1250 "internal-warning". */
1253 add_internal_problem_command (struct internal_problem *problem)
1255 struct cmd_list_element **set_cmd_list;
1256 struct cmd_list_element **show_cmd_list;
1260 set_cmd_list = xmalloc (sizeof (*set_cmd_list));
1261 show_cmd_list = xmalloc (sizeof (*set_cmd_list));
1262 *set_cmd_list = NULL;
1263 *show_cmd_list = NULL;
1265 set_doc = xstrprintf (_("Configure what GDB does when %s is detected."),
1268 show_doc = xstrprintf (_("Show what GDB does when %s is detected."),
1271 add_prefix_cmd ((char*) problem->name,
1272 class_maintenance, set_internal_problem_cmd, set_doc,
1274 concat ("maintenance set ", problem->name, " ",
1276 0/*allow-unknown*/, &maintenance_set_cmdlist);
1278 add_prefix_cmd ((char*) problem->name,
1279 class_maintenance, show_internal_problem_cmd, show_doc,
1281 concat ("maintenance show ", problem->name, " ",
1283 0/*allow-unknown*/, &maintenance_show_cmdlist);
1285 set_doc = xstrprintf (_("\
1286 Set whether GDB should quit when an %s is detected"),
1288 show_doc = xstrprintf (_("\
1289 Show whether GDB will quit when an %s is detected"),
1291 add_setshow_enum_cmd ("quit", class_maintenance,
1292 internal_problem_modes,
1293 &problem->should_quit,
1296 NULL, /* help_doc */
1298 NULL, /* showfunc */
1305 set_doc = xstrprintf (_("\
1306 Set whether GDB should create a core file of GDB when %s is detected"),
1308 show_doc = xstrprintf (_("\
1309 Show whether GDB will create a core file of GDB when %s is detected"),
1311 add_setshow_enum_cmd ("corefile", class_maintenance,
1312 internal_problem_modes,
1313 &problem->should_dump_core,
1316 NULL, /* help_doc */
1318 NULL, /* showfunc */
1326 /* Print the system error message for errno, and also mention STRING
1327 as the file name for which the error was encountered.
1328 Then return to command level. */
1331 perror_with_name (const char *string)
1336 err = safe_strerror (errno);
1337 combined = (char *) alloca (strlen (err) + strlen (string) + 3);
1338 strcpy (combined, string);
1339 strcat (combined, ": ");
1340 strcat (combined, err);
1342 /* I understand setting these is a matter of taste. Still, some people
1343 may clear errno but not know about bfd_error. Doing this here is not
1345 bfd_set_error (bfd_error_no_error);
1348 error (_("%s."), combined);
1351 /* Print the system error message for ERRCODE, and also mention STRING
1352 as the file name for which the error was encountered. */
1355 print_sys_errmsg (const char *string, int errcode)
1360 err = safe_strerror (errcode);
1361 combined = (char *) alloca (strlen (err) + strlen (string) + 3);
1362 strcpy (combined, string);
1363 strcat (combined, ": ");
1364 strcat (combined, err);
1366 /* We want anything which was printed on stdout to come out first, before
1368 gdb_flush (gdb_stdout);
1369 fprintf_unfiltered (gdb_stderr, "%s.\n", combined);
1372 /* Control C eventually causes this to be called, at a convenient time. */
1378 /* No steenking SIGINT will ever be coming our way when the
1379 program is resumed. Don't lie. */
1383 /* If there is no terminal switching for this target, then we can't
1384 possibly get screwed by the lack of job control. */
1385 || current_target.to_terminal_ours == NULL)
1388 fatal ("Quit (expect signal SIGINT when the program is resumed)");
1393 /* Called when a memory allocation fails, with the number of bytes of
1394 memory requested in SIZE. */
1401 internal_error (__FILE__, __LINE__,
1402 _("virtual memory exhausted: can't allocate %ld bytes."),
1407 internal_error (__FILE__, __LINE__, _("virtual memory exhausted."));
1411 /* The xmalloc() (libiberty.h) family of memory management routines.
1413 These are like the ISO-C malloc() family except that they implement
1414 consistent semantics and guard against typical memory management
1417 /* NOTE: These are declared using PTR to ensure consistency with
1418 "libiberty.h". xfree() is GDB local. */
1421 xmalloc (size_t size)
1425 /* See libiberty/xmalloc.c. This function need's to match that's
1426 semantics. It never returns NULL. */
1430 val = malloc (size); /* ARI: malloc */
1438 xzalloc (size_t size)
1440 return xcalloc (1, size);
1444 xrealloc (PTR ptr, size_t size) /* ARI: PTR */
1448 /* See libiberty/xmalloc.c. This function need's to match that's
1449 semantics. It never returns NULL. */
1454 val = realloc (ptr, size); /* ARI: realloc */
1456 val = malloc (size); /* ARI: malloc */
1464 xcalloc (size_t number, size_t size)
1468 /* See libiberty/xmalloc.c. This function need's to match that's
1469 semantics. It never returns NULL. */
1470 if (number == 0 || size == 0)
1476 mem = calloc (number, size); /* ARI: xcalloc */
1478 nomem (number * size);
1487 free (ptr); /* ARI: free */
1491 /* Like asprintf/vasprintf but get an internal_error if the call
1495 xstrprintf (const char *format, ...)
1500 va_start (args, format);
1501 ret = xstrvprintf (format, args);
1507 xasprintf (char **ret, const char *format, ...)
1511 va_start (args, format);
1512 (*ret) = xstrvprintf (format, args);
1517 xvasprintf (char **ret, const char *format, va_list ap)
1519 (*ret) = xstrvprintf (format, ap);
1523 xstrvprintf (const char *format, va_list ap)
1526 int status = vasprintf (&ret, format, ap);
1528 /* NULL is returned when there was a memory allocation problem, or
1529 any other error (for instance, a bad format string). A negative
1530 status (the printed length) with a non-NULL buffer should never
1531 happen, but just to be sure. */
1532 if (ret == NULL || status < 0)
1533 internal_error (__FILE__, __LINE__, _("vasprintf call failed"));
1538 xsnprintf (char *str, size_t size, const char *format, ...)
1543 va_start (args, format);
1544 ret = vsnprintf (str, size, format, args);
1545 gdb_assert (ret < size);
1551 /* My replacement for the read system call.
1552 Used like `read' but keeps going if `read' returns too soon. */
1555 myread (int desc, char *addr, int len)
1562 val = read (desc, addr, len);
1566 return orglen - len;
1573 /* Make a copy of the string at PTR with SIZE characters
1574 (and add a null character at the end in the copy).
1575 Uses malloc to get the space. Returns the address of the copy. */
1578 savestring (const char *ptr, size_t size)
1580 char *p = (char *) xmalloc (size + 1);
1582 memcpy (p, ptr, size);
1588 print_spaces (int n, struct ui_file *file)
1590 fputs_unfiltered (n_spaces (n), file);
1593 /* Print a host address. */
1596 gdb_print_host_address (const void *addr, struct ui_file *stream)
1598 fprintf_filtered (stream, "%s", host_address_to_string (addr));
1602 /* This function supports the query, nquery, and yquery functions.
1603 Ask user a y-or-n question and return 0 if answer is no, 1 if
1604 answer is yes, or default the answer to the specified default
1605 (for yquery or nquery). DEFCHAR may be 'y' or 'n' to provide a
1606 default answer, or '\0' for no default.
1607 CTLSTR is the control string and should end in "? ". It should
1608 not say how to answer, because we do that.
1609 ARGS are the arguments passed along with the CTLSTR argument to
1612 static int ATTRIBUTE_PRINTF (1, 0)
1613 defaulted_query (const char *ctlstr, const char defchar, va_list args)
1619 char def_answer, not_def_answer;
1620 char *y_string, *n_string, *question;
1622 /* Set up according to which answer is the default. */
1623 if (defchar == '\0')
1627 not_def_answer = 'N';
1631 else if (defchar == 'y')
1635 not_def_answer = 'N';
1643 not_def_answer = 'Y';
1648 /* Automatically answer the default value if the user did not want
1649 prompts or the command was issued with the server prefix. */
1650 if (! caution || server_command)
1653 /* If input isn't coming from the user directly, just say what
1654 question we're asking, and then answer the default automatically. This
1655 way, important error messages don't get lost when talking to GDB
1657 if (! input_from_terminal_p ())
1660 vfprintf_filtered (gdb_stdout, ctlstr, args);
1662 printf_filtered (_("(%s or %s) [answered %c; input not from terminal]\n"),
1663 y_string, n_string, def_answer);
1664 gdb_flush (gdb_stdout);
1669 if (deprecated_query_hook)
1671 return deprecated_query_hook (ctlstr, args);
1674 /* Format the question outside of the loop, to avoid reusing args. */
1675 question = xstrvprintf (ctlstr, args);
1679 wrap_here (""); /* Flush any buffered output */
1680 gdb_flush (gdb_stdout);
1682 if (annotation_level > 1)
1683 printf_filtered (("\n\032\032pre-query\n"));
1685 fputs_filtered (question, gdb_stdout);
1686 printf_filtered (_("(%s or %s) "), y_string, n_string);
1688 if (annotation_level > 1)
1689 printf_filtered (("\n\032\032query\n"));
1692 gdb_flush (gdb_stdout);
1694 answer = fgetc (stdin);
1696 /* We expect fgetc to block until a character is read. But
1697 this may not be the case if the terminal was opened with
1698 the NONBLOCK flag. In that case, if there is nothing to
1699 read on stdin, fgetc returns EOF, but also sets the error
1700 condition flag on stdin and errno to EAGAIN. With a true
1701 EOF, stdin's error condition flag is not set.
1703 A situation where this behavior was observed is a pseudo
1705 while (answer == EOF && ferror (stdin) && errno == EAGAIN)
1707 /* Not a real EOF. Wait a little while and try again until
1708 we read something. */
1711 answer = fgetc (stdin);
1714 clearerr (stdin); /* in case of C-d */
1715 if (answer == EOF) /* C-d */
1717 printf_filtered ("EOF [assumed %c]\n", def_answer);
1721 /* Eat rest of input line, to EOF or newline */
1725 ans2 = fgetc (stdin);
1728 while (ans2 != EOF && ans2 != '\n' && ans2 != '\r');
1732 /* Check answer. For the non-default, the user must specify
1733 the non-default explicitly. */
1734 if (answer == not_def_answer)
1736 retval = !def_value;
1739 /* Otherwise, if a default was specified, the user may either
1740 specify the required input or have it default by entering
1742 if (answer == def_answer
1743 || (defchar != '\0' &&
1744 (answer == '\n' || answer == '\r' || answer == EOF)))
1749 /* Invalid entries are not defaulted and require another selection. */
1750 printf_filtered (_("Please answer %s or %s.\n"),
1751 y_string, n_string);
1755 if (annotation_level > 1)
1756 printf_filtered (("\n\032\032post-query\n"));
1761 /* Ask user a y-or-n question and return 0 if answer is no, 1 if
1762 answer is yes, or 0 if answer is defaulted.
1763 Takes three args which are given to printf to print the question.
1764 The first, a control string, should end in "? ".
1765 It should not say how to answer, because we do that. */
1768 nquery (const char *ctlstr, ...)
1772 va_start (args, ctlstr);
1773 return defaulted_query (ctlstr, 'n', args);
1777 /* Ask user a y-or-n question and return 0 if answer is no, 1 if
1778 answer is yes, or 1 if answer is defaulted.
1779 Takes three args which are given to printf to print the question.
1780 The first, a control string, should end in "? ".
1781 It should not say how to answer, because we do that. */
1784 yquery (const char *ctlstr, ...)
1788 va_start (args, ctlstr);
1789 return defaulted_query (ctlstr, 'y', args);
1793 /* Ask user a y-or-n question and return 1 iff answer is yes.
1794 Takes three args which are given to printf to print the question.
1795 The first, a control string, should end in "? ".
1796 It should not say how to answer, because we do that. */
1799 query (const char *ctlstr, ...)
1803 va_start (args, ctlstr);
1804 return defaulted_query (ctlstr, '\0', args);
1808 /* A helper for parse_escape that converts a host character to a
1809 target character. C is the host character. If conversion is
1810 possible, then the target character is stored in *TARGET_C and the
1811 function returns 1. Otherwise, the function returns 0. */
1814 host_char_to_target (struct gdbarch *gdbarch, int c, int *target_c)
1816 struct obstack host_data;
1818 struct cleanup *cleanups;
1821 obstack_init (&host_data);
1822 cleanups = make_cleanup_obstack_free (&host_data);
1824 convert_between_encodings (target_charset (gdbarch), host_charset (),
1825 &the_char, 1, 1, &host_data, translit_none);
1827 if (obstack_object_size (&host_data) == 1)
1830 *target_c = *(char *) obstack_base (&host_data);
1833 do_cleanups (cleanups);
1837 /* Parse a C escape sequence. STRING_PTR points to a variable
1838 containing a pointer to the string to parse. That pointer
1839 should point to the character after the \. That pointer
1840 is updated past the characters we use. The value of the
1841 escape sequence is returned.
1843 A negative value means the sequence \ newline was seen,
1844 which is supposed to be equivalent to nothing at all.
1846 If \ is followed by a null character, we return a negative
1847 value and leave the string pointer pointing at the null character.
1849 If \ is followed by 000, we return 0 and leave the string pointer
1850 after the zeros. A value of 0 does not mean end of string. */
1853 parse_escape (struct gdbarch *gdbarch, char **string_ptr)
1855 int target_char = -2; /* initialize to avoid GCC warnings */
1856 int c = *(*string_ptr)++;
1875 int i = host_hex_value (c);
1880 if (isdigit (c) && c != '8' && c != '9')
1884 i += host_hex_value (c);
1920 if (!host_char_to_target (gdbarch, c, &target_char))
1922 ("The escape sequence `\%c' is equivalent to plain `%c', which"
1923 " has no equivalent\n" "in the `%s' character set.", c, c,
1924 target_charset (gdbarch));
1928 /* Print the character C on STREAM as part of the contents of a literal
1929 string whose delimiter is QUOTER. Note that this routine should only
1930 be call for printing things which are independent of the language
1931 of the program being debugged. */
1934 printchar (int c, void (*do_fputs) (const char *, struct ui_file *),
1935 void (*do_fprintf) (struct ui_file *, const char *, ...)
1936 ATTRIBUTE_FPTR_PRINTF_2, struct ui_file *stream, int quoter)
1938 c &= 0xFF; /* Avoid sign bit follies */
1940 if (c < 0x20 || /* Low control chars */
1941 (c >= 0x7F && c < 0xA0) || /* DEL, High controls */
1942 (sevenbit_strings && c >= 0x80))
1943 { /* high order bit set */
1947 do_fputs ("\\n", stream);
1950 do_fputs ("\\b", stream);
1953 do_fputs ("\\t", stream);
1956 do_fputs ("\\f", stream);
1959 do_fputs ("\\r", stream);
1962 do_fputs ("\\e", stream);
1965 do_fputs ("\\a", stream);
1968 do_fprintf (stream, "\\%.3o", (unsigned int) c);
1974 if (c == '\\' || c == quoter)
1975 do_fputs ("\\", stream);
1976 do_fprintf (stream, "%c", c);
1980 /* Print the character C on STREAM as part of the contents of a
1981 literal string whose delimiter is QUOTER. Note that these routines
1982 should only be call for printing things which are independent of
1983 the language of the program being debugged. */
1986 fputstr_filtered (const char *str, int quoter, struct ui_file *stream)
1989 printchar (*str++, fputs_filtered, fprintf_filtered, stream, quoter);
1993 fputstr_unfiltered (const char *str, int quoter, struct ui_file *stream)
1996 printchar (*str++, fputs_unfiltered, fprintf_unfiltered, stream, quoter);
2000 fputstrn_filtered (const char *str, int n, int quoter,
2001 struct ui_file *stream)
2005 for (i = 0; i < n; i++)
2006 printchar (str[i], fputs_filtered, fprintf_filtered, stream, quoter);
2010 fputstrn_unfiltered (const char *str, int n, int quoter,
2011 struct ui_file *stream)
2015 for (i = 0; i < n; i++)
2016 printchar (str[i], fputs_unfiltered, fprintf_unfiltered, stream, quoter);
2020 /* Number of lines per page or UINT_MAX if paging is disabled. */
2021 static unsigned int lines_per_page;
2023 show_lines_per_page (struct ui_file *file, int from_tty,
2024 struct cmd_list_element *c, const char *value)
2026 fprintf_filtered (file, _("\
2027 Number of lines gdb thinks are in a page is %s.\n"),
2031 /* Number of chars per line or UINT_MAX if line folding is disabled. */
2032 static unsigned int chars_per_line;
2034 show_chars_per_line (struct ui_file *file, int from_tty,
2035 struct cmd_list_element *c, const char *value)
2037 fprintf_filtered (file, _("\
2038 Number of characters gdb thinks are in a line is %s.\n"),
2042 /* Current count of lines printed on this page, chars on this line. */
2043 static unsigned int lines_printed, chars_printed;
2045 /* Buffer and start column of buffered text, for doing smarter word-
2046 wrapping. When someone calls wrap_here(), we start buffering output
2047 that comes through fputs_filtered(). If we see a newline, we just
2048 spit it out and forget about the wrap_here(). If we see another
2049 wrap_here(), we spit it out and remember the newer one. If we see
2050 the end of the line, we spit out a newline, the indent, and then
2051 the buffered output. */
2053 /* Malloc'd buffer with chars_per_line+2 bytes. Contains characters which
2054 are waiting to be output (they have already been counted in chars_printed).
2055 When wrap_buffer[0] is null, the buffer is empty. */
2056 static char *wrap_buffer;
2058 /* Pointer in wrap_buffer to the next character to fill. */
2059 static char *wrap_pointer;
2061 /* String to indent by if the wrap occurs. Must not be NULL if wrap_column
2063 static char *wrap_indent;
2065 /* Column number on the screen where wrap_buffer begins, or 0 if wrapping
2066 is not in effect. */
2067 static int wrap_column;
2070 /* Inialize the number of lines per page and chars per line. */
2073 init_page_info (void)
2077 lines_per_page = UINT_MAX;
2078 chars_per_line = UINT_MAX;
2082 if (!tui_get_command_dimension (&chars_per_line, &lines_per_page))
2087 #if defined(__GO32__)
2088 rows = ScreenRows ();
2089 cols = ScreenCols ();
2090 lines_per_page = rows;
2091 chars_per_line = cols;
2093 /* Make sure Readline has initialized its terminal settings. */
2094 rl_reset_terminal (NULL);
2096 /* Get the screen size from Readline. */
2097 rl_get_screen_size (&rows, &cols);
2098 lines_per_page = rows;
2099 chars_per_line = cols;
2101 /* Readline should have fetched the termcap entry for us. */
2102 if (tgetnum ("li") < 0 || getenv ("EMACS"))
2104 /* The number of lines per page is not mentioned in the
2105 terminal description. This probably means that paging is
2106 not useful (e.g. emacs shell window), so disable paging. */
2107 lines_per_page = UINT_MAX;
2110 /* FIXME: Get rid of this junk. */
2111 #if defined(SIGWINCH) && defined(SIGWINCH_HANDLER)
2112 SIGWINCH_HANDLER (SIGWINCH);
2115 /* If the output is not a terminal, don't paginate it. */
2116 if (!ui_file_isatty (gdb_stdout))
2117 lines_per_page = UINT_MAX;
2125 /* Helper for make_cleanup_restore_page_info. */
2128 do_restore_page_info_cleanup (void *arg)
2134 /* Provide cleanup for restoring the terminal size. */
2137 make_cleanup_restore_page_info (void)
2139 struct cleanup *back_to;
2141 back_to = make_cleanup (do_restore_page_info_cleanup, NULL);
2142 make_cleanup_restore_uinteger (&lines_per_page);
2143 make_cleanup_restore_uinteger (&chars_per_line);
2148 /* Temporarily set BATCH_FLAG and the associated unlimited terminal size.
2149 Provide cleanup for restoring the original state. */
2152 set_batch_flag_and_make_cleanup_restore_page_info (void)
2154 struct cleanup *back_to = make_cleanup_restore_page_info ();
2156 make_cleanup_restore_integer (&batch_flag);
2163 /* Set the screen size based on LINES_PER_PAGE and CHARS_PER_LINE. */
2166 set_screen_size (void)
2168 int rows = lines_per_page;
2169 int cols = chars_per_line;
2177 /* Update Readline's idea of the terminal size. */
2178 rl_set_screen_size (rows, cols);
2181 /* Reinitialize WRAP_BUFFER according to the current value of
2187 if (chars_per_line == 0)
2192 wrap_buffer = (char *) xmalloc (chars_per_line + 2);
2193 wrap_buffer[0] = '\0';
2196 wrap_buffer = (char *) xrealloc (wrap_buffer, chars_per_line + 2);
2197 wrap_pointer = wrap_buffer; /* Start it at the beginning. */
2201 set_width_command (char *args, int from_tty, struct cmd_list_element *c)
2208 set_height_command (char *args, int from_tty, struct cmd_list_element *c)
2213 /* Wait, so the user can read what's on the screen. Prompt the user
2214 to continue by pressing RETURN. */
2217 prompt_for_continue (void)
2220 char cont_prompt[120];
2222 if (annotation_level > 1)
2223 printf_unfiltered (("\n\032\032pre-prompt-for-continue\n"));
2225 strcpy (cont_prompt,
2226 "---Type <return> to continue, or q <return> to quit---");
2227 if (annotation_level > 1)
2228 strcat (cont_prompt, "\n\032\032prompt-for-continue\n");
2230 /* We must do this *before* we call gdb_readline, else it will eventually
2231 call us -- thinking that we're trying to print beyond the end of the
2233 reinitialize_more_filter ();
2236 /* On a real operating system, the user can quit with SIGINT.
2239 'q' is provided on all systems so users don't have to change habits
2240 from system to system, and because telling them what to do in
2241 the prompt is more user-friendly than expecting them to think of
2243 /* Call readline, not gdb_readline, because GO32 readline handles control-C
2244 whereas control-C to gdb_readline will cause the user to get dumped
2246 ignore = gdb_readline_wrapper (cont_prompt);
2248 if (annotation_level > 1)
2249 printf_unfiltered (("\n\032\032post-prompt-for-continue\n"));
2255 while (*p == ' ' || *p == '\t')
2258 async_request_quit (0);
2263 /* Now we have to do this again, so that GDB will know that it doesn't
2264 need to save the ---Type <return>--- line at the top of the screen. */
2265 reinitialize_more_filter ();
2267 dont_repeat (); /* Forget prev cmd -- CR won't repeat it. */
2270 /* Reinitialize filter; ie. tell it to reset to original values. */
2273 reinitialize_more_filter (void)
2279 /* Indicate that if the next sequence of characters overflows the line,
2280 a newline should be inserted here rather than when it hits the end.
2281 If INDENT is non-null, it is a string to be printed to indent the
2282 wrapped part on the next line. INDENT must remain accessible until
2283 the next call to wrap_here() or until a newline is printed through
2286 If the line is already overfull, we immediately print a newline and
2287 the indentation, and disable further wrapping.
2289 If we don't know the width of lines, but we know the page height,
2290 we must not wrap words, but should still keep track of newlines
2291 that were explicitly printed.
2293 INDENT should not contain tabs, as that will mess up the char count
2294 on the next line. FIXME.
2296 This routine is guaranteed to force out any output which has been
2297 squirreled away in the wrap_buffer, so wrap_here ((char *)0) can be
2298 used to force out output from the wrap_buffer. */
2301 wrap_here (char *indent)
2303 /* This should have been allocated, but be paranoid anyway. */
2305 internal_error (__FILE__, __LINE__, _("failed internal consistency check"));
2309 *wrap_pointer = '\0';
2310 fputs_unfiltered (wrap_buffer, gdb_stdout);
2312 wrap_pointer = wrap_buffer;
2313 wrap_buffer[0] = '\0';
2314 if (chars_per_line == UINT_MAX) /* No line overflow checking */
2318 else if (chars_printed >= chars_per_line)
2320 puts_filtered ("\n");
2322 puts_filtered (indent);
2327 wrap_column = chars_printed;
2331 wrap_indent = indent;
2335 /* Print input string to gdb_stdout, filtered, with wrap,
2336 arranging strings in columns of n chars. String can be
2337 right or left justified in the column. Never prints
2338 trailing spaces. String should never be longer than
2339 width. FIXME: this could be useful for the EXAMINE
2340 command, which currently doesn't tabulate very well */
2343 puts_filtered_tabular (char *string, int width, int right)
2349 gdb_assert (chars_per_line > 0);
2350 if (chars_per_line == UINT_MAX)
2352 fputs_filtered (string, gdb_stdout);
2353 fputs_filtered ("\n", gdb_stdout);
2357 if (((chars_printed - 1) / width + 2) * width >= chars_per_line)
2358 fputs_filtered ("\n", gdb_stdout);
2360 if (width >= chars_per_line)
2361 width = chars_per_line - 1;
2363 stringlen = strlen (string);
2365 if (chars_printed > 0)
2366 spaces = width - (chars_printed - 1) % width - 1;
2368 spaces += width - stringlen;
2370 spacebuf = alloca (spaces + 1);
2371 spacebuf[spaces] = '\0';
2373 spacebuf[spaces] = ' ';
2375 fputs_filtered (spacebuf, gdb_stdout);
2376 fputs_filtered (string, gdb_stdout);
2380 /* Ensure that whatever gets printed next, using the filtered output
2381 commands, starts at the beginning of the line. I.E. if there is
2382 any pending output for the current line, flush it and start a new
2383 line. Otherwise do nothing. */
2388 if (chars_printed > 0)
2390 puts_filtered ("\n");
2395 /* Like fputs but if FILTER is true, pause after every screenful.
2397 Regardless of FILTER can wrap at points other than the final
2398 character of a line.
2400 Unlike fputs, fputs_maybe_filtered does not return a value.
2401 It is OK for LINEBUFFER to be NULL, in which case just don't print
2404 Note that a longjmp to top level may occur in this routine (only if
2405 FILTER is true) (since prompt_for_continue may do so) so this
2406 routine should not be called when cleanups are not in place. */
2409 fputs_maybe_filtered (const char *linebuffer, struct ui_file *stream,
2412 const char *lineptr;
2414 if (linebuffer == 0)
2417 /* Don't do any filtering if it is disabled. */
2418 if (stream != gdb_stdout
2419 || ! pagination_enabled
2420 || ! input_from_terminal_p ()
2421 || (lines_per_page == UINT_MAX && chars_per_line == UINT_MAX)
2422 || top_level_interpreter () == NULL
2423 || ui_out_is_mi_like_p (interp_ui_out (top_level_interpreter ())))
2425 fputs_unfiltered (linebuffer, stream);
2429 /* Go through and output each character. Show line extension
2430 when this is necessary; prompt user for new page when this is
2433 lineptr = linebuffer;
2436 /* Possible new page. */
2437 if (filter && (lines_printed >= lines_per_page - 1))
2438 prompt_for_continue ();
2440 while (*lineptr && *lineptr != '\n')
2442 /* Print a single line. */
2443 if (*lineptr == '\t')
2446 *wrap_pointer++ = '\t';
2448 fputc_unfiltered ('\t', stream);
2449 /* Shifting right by 3 produces the number of tab stops
2450 we have already passed, and then adding one and
2451 shifting left 3 advances to the next tab stop. */
2452 chars_printed = ((chars_printed >> 3) + 1) << 3;
2458 *wrap_pointer++ = *lineptr;
2460 fputc_unfiltered (*lineptr, stream);
2465 if (chars_printed >= chars_per_line)
2467 unsigned int save_chars = chars_printed;
2471 /* If we aren't actually wrapping, don't output newline --
2472 if chars_per_line is right, we probably just overflowed
2473 anyway; if it's wrong, let us keep going. */
2475 fputc_unfiltered ('\n', stream);
2477 /* Possible new page. */
2478 if (lines_printed >= lines_per_page - 1)
2479 prompt_for_continue ();
2481 /* Now output indentation and wrapped string */
2484 fputs_unfiltered (wrap_indent, stream);
2485 *wrap_pointer = '\0'; /* Null-terminate saved stuff */
2486 fputs_unfiltered (wrap_buffer, stream); /* and eject it */
2487 /* FIXME, this strlen is what prevents wrap_indent from
2488 containing tabs. However, if we recurse to print it
2489 and count its chars, we risk trouble if wrap_indent is
2490 longer than (the user settable) chars_per_line.
2491 Note also that this can set chars_printed > chars_per_line
2492 if we are printing a long string. */
2493 chars_printed = strlen (wrap_indent)
2494 + (save_chars - wrap_column);
2495 wrap_pointer = wrap_buffer; /* Reset buffer */
2496 wrap_buffer[0] = '\0';
2497 wrap_column = 0; /* And disable fancy wrap */
2502 if (*lineptr == '\n')
2505 wrap_here ((char *) 0); /* Spit out chars, cancel further wraps */
2507 fputc_unfiltered ('\n', stream);
2514 fputs_filtered (const char *linebuffer, struct ui_file *stream)
2516 fputs_maybe_filtered (linebuffer, stream, 1);
2520 putchar_unfiltered (int c)
2524 ui_file_write (gdb_stdout, &buf, 1);
2528 /* Write character C to gdb_stdout using GDB's paging mechanism and return C.
2529 May return nonlocally. */
2532 putchar_filtered (int c)
2534 return fputc_filtered (c, gdb_stdout);
2538 fputc_unfiltered (int c, struct ui_file *stream)
2542 ui_file_write (stream, &buf, 1);
2547 fputc_filtered (int c, struct ui_file *stream)
2553 fputs_filtered (buf, stream);
2557 /* puts_debug is like fputs_unfiltered, except it prints special
2558 characters in printable fashion. */
2561 puts_debug (char *prefix, char *string, char *suffix)
2565 /* Print prefix and suffix after each line. */
2566 static int new_line = 1;
2567 static int return_p = 0;
2568 static char *prev_prefix = "";
2569 static char *prev_suffix = "";
2571 if (*string == '\n')
2574 /* If the prefix is changing, print the previous suffix, a new line,
2575 and the new prefix. */
2576 if ((return_p || (strcmp (prev_prefix, prefix) != 0)) && !new_line)
2578 fputs_unfiltered (prev_suffix, gdb_stdlog);
2579 fputs_unfiltered ("\n", gdb_stdlog);
2580 fputs_unfiltered (prefix, gdb_stdlog);
2583 /* Print prefix if we printed a newline during the previous call. */
2587 fputs_unfiltered (prefix, gdb_stdlog);
2590 prev_prefix = prefix;
2591 prev_suffix = suffix;
2593 /* Output characters in a printable format. */
2594 while ((ch = *string++) != '\0')
2600 fputc_unfiltered (ch, gdb_stdlog);
2603 fprintf_unfiltered (gdb_stdlog, "\\x%02x", ch & 0xff);
2607 fputs_unfiltered ("\\\\", gdb_stdlog);
2610 fputs_unfiltered ("\\b", gdb_stdlog);
2613 fputs_unfiltered ("\\f", gdb_stdlog);
2617 fputs_unfiltered ("\\n", gdb_stdlog);
2620 fputs_unfiltered ("\\r", gdb_stdlog);
2623 fputs_unfiltered ("\\t", gdb_stdlog);
2626 fputs_unfiltered ("\\v", gdb_stdlog);
2630 return_p = ch == '\r';
2633 /* Print suffix if we printed a newline. */
2636 fputs_unfiltered (suffix, gdb_stdlog);
2637 fputs_unfiltered ("\n", gdb_stdlog);
2642 /* Print a variable number of ARGS using format FORMAT. If this
2643 information is going to put the amount written (since the last call
2644 to REINITIALIZE_MORE_FILTER or the last page break) over the page size,
2645 call prompt_for_continue to get the users permision to continue.
2647 Unlike fprintf, this function does not return a value.
2649 We implement three variants, vfprintf (takes a vararg list and stream),
2650 fprintf (takes a stream to write on), and printf (the usual).
2652 Note also that a longjmp to top level may occur in this routine
2653 (since prompt_for_continue may do so) so this routine should not be
2654 called when cleanups are not in place. */
2657 vfprintf_maybe_filtered (struct ui_file *stream, const char *format,
2658 va_list args, int filter)
2661 struct cleanup *old_cleanups;
2663 linebuffer = xstrvprintf (format, args);
2664 old_cleanups = make_cleanup (xfree, linebuffer);
2665 fputs_maybe_filtered (linebuffer, stream, filter);
2666 do_cleanups (old_cleanups);
2671 vfprintf_filtered (struct ui_file *stream, const char *format, va_list args)
2673 vfprintf_maybe_filtered (stream, format, args, 1);
2677 vfprintf_unfiltered (struct ui_file *stream, const char *format, va_list args)
2680 struct cleanup *old_cleanups;
2682 linebuffer = xstrvprintf (format, args);
2683 old_cleanups = make_cleanup (xfree, linebuffer);
2684 if (debug_timestamp && stream == gdb_stdlog)
2690 gettimeofday (&tm, NULL);
2692 len = strlen (linebuffer);
2693 need_nl = (len > 0 && linebuffer[len - 1] != '\n');
2695 timestamp = xstrprintf ("%ld:%ld %s%s",
2696 (long) tm.tv_sec, (long) tm.tv_usec,
2698 need_nl ? "\n": "");
2699 make_cleanup (xfree, timestamp);
2700 fputs_unfiltered (timestamp, stream);
2703 fputs_unfiltered (linebuffer, stream);
2704 do_cleanups (old_cleanups);
2708 vprintf_filtered (const char *format, va_list args)
2710 vfprintf_maybe_filtered (gdb_stdout, format, args, 1);
2714 vprintf_unfiltered (const char *format, va_list args)
2716 vfprintf_unfiltered (gdb_stdout, format, args);
2720 fprintf_filtered (struct ui_file *stream, const char *format, ...)
2724 va_start (args, format);
2725 vfprintf_filtered (stream, format, args);
2730 fprintf_unfiltered (struct ui_file *stream, const char *format, ...)
2734 va_start (args, format);
2735 vfprintf_unfiltered (stream, format, args);
2739 /* Like fprintf_filtered, but prints its result indented.
2740 Called as fprintfi_filtered (spaces, stream, format, ...); */
2743 fprintfi_filtered (int spaces, struct ui_file *stream, const char *format,
2748 va_start (args, format);
2749 print_spaces_filtered (spaces, stream);
2751 vfprintf_filtered (stream, format, args);
2757 printf_filtered (const char *format, ...)
2761 va_start (args, format);
2762 vfprintf_filtered (gdb_stdout, format, args);
2768 printf_unfiltered (const char *format, ...)
2772 va_start (args, format);
2773 vfprintf_unfiltered (gdb_stdout, format, args);
2777 /* Like printf_filtered, but prints it's result indented.
2778 Called as printfi_filtered (spaces, format, ...); */
2781 printfi_filtered (int spaces, const char *format, ...)
2785 va_start (args, format);
2786 print_spaces_filtered (spaces, gdb_stdout);
2787 vfprintf_filtered (gdb_stdout, format, args);
2791 /* Easy -- but watch out!
2793 This routine is *not* a replacement for puts()! puts() appends a newline.
2794 This one doesn't, and had better not! */
2797 puts_filtered (const char *string)
2799 fputs_filtered (string, gdb_stdout);
2803 puts_unfiltered (const char *string)
2805 fputs_unfiltered (string, gdb_stdout);
2808 /* Return a pointer to N spaces and a null. The pointer is good
2809 until the next call to here. */
2814 static char *spaces = 0;
2815 static int max_spaces = -1;
2821 spaces = (char *) xmalloc (n + 1);
2822 for (t = spaces + n; t != spaces;)
2828 return spaces + max_spaces - n;
2831 /* Print N spaces. */
2833 print_spaces_filtered (int n, struct ui_file *stream)
2835 fputs_filtered (n_spaces (n), stream);
2838 /* C++/ObjC demangler stuff. */
2840 /* fprintf_symbol_filtered attempts to demangle NAME, a symbol in language
2841 LANG, using demangling args ARG_MODE, and print it filtered to STREAM.
2842 If the name is not mangled, or the language for the name is unknown, or
2843 demangling is off, the name is printed in its "raw" form. */
2846 fprintf_symbol_filtered (struct ui_file *stream, char *name,
2847 enum language lang, int arg_mode)
2853 /* If user wants to see raw output, no problem. */
2856 fputs_filtered (name, stream);
2860 demangled = language_demangle (language_def (lang), name, arg_mode);
2861 fputs_filtered (demangled ? demangled : name, stream);
2862 if (demangled != NULL)
2870 /* Do a strcmp() type operation on STRING1 and STRING2, ignoring any
2871 differences in whitespace. Returns 0 if they match, non-zero if they
2872 don't (slightly different than strcmp()'s range of return values).
2874 As an extra hack, string1=="FOO(ARGS)" matches string2=="FOO".
2875 This "feature" is useful when searching for matching C++ function names
2876 (such as if the user types 'break FOO', where FOO is a mangled C++
2880 strcmp_iw (const char *string1, const char *string2)
2882 while ((*string1 != '\0') && (*string2 != '\0'))
2884 while (isspace (*string1))
2888 while (isspace (*string2))
2892 if (*string1 != *string2)
2896 if (*string1 != '\0')
2902 return (*string1 != '\0' && *string1 != '(') || (*string2 != '\0');
2905 /* This is like strcmp except that it ignores whitespace and treats
2906 '(' as the first non-NULL character in terms of ordering. Like
2907 strcmp (and unlike strcmp_iw), it returns negative if STRING1 <
2908 STRING2, 0 if STRING2 = STRING2, and positive if STRING1 > STRING2
2909 according to that ordering.
2911 If a list is sorted according to this function and if you want to
2912 find names in the list that match some fixed NAME according to
2913 strcmp_iw(LIST_ELT, NAME), then the place to start looking is right
2914 where this function would put NAME.
2916 Here are some examples of why using strcmp to sort is a bad idea:
2920 Say your partial symtab contains: "foo<char *>", "goo". Then, if
2921 we try to do a search for "foo<char*>", strcmp will locate this
2922 after "foo<char *>" and before "goo". Then lookup_partial_symbol
2923 will start looking at strings beginning with "goo", and will never
2924 see the correct match of "foo<char *>".
2926 Parenthesis example:
2928 In practice, this is less like to be an issue, but I'll give it a
2929 shot. Let's assume that '$' is a legitimate character to occur in
2930 symbols. (Which may well even be the case on some systems.) Then
2931 say that the partial symbol table contains "foo$" and "foo(int)".
2932 strcmp will put them in this order, since '$' < '('. Now, if the
2933 user searches for "foo", then strcmp will sort "foo" before "foo$".
2934 Then lookup_partial_symbol will notice that strcmp_iw("foo$",
2935 "foo") is false, so it won't proceed to the actual match of
2936 "foo(int)" with "foo". */
2939 strcmp_iw_ordered (const char *string1, const char *string2)
2941 while ((*string1 != '\0') && (*string2 != '\0'))
2943 while (isspace (*string1))
2947 while (isspace (*string2))
2951 if (*string1 != *string2)
2955 if (*string1 != '\0')
2964 /* Characters are non-equal unless they're both '\0'; we want to
2965 make sure we get the comparison right according to our
2966 comparison in the cases where one of them is '\0' or '('. */
2968 if (*string2 == '\0')
2973 if (*string2 == '\0')
2978 if (*string2 == '(')
2981 return *string1 - *string2;
2985 /* A simple comparison function with opposite semantics to strcmp. */
2988 streq (const char *lhs, const char *rhs)
2990 return !strcmp (lhs, rhs);
2996 ** Answer whether string_to_compare is a full or partial match to
2997 ** template_string. The partial match must be in sequence starting
3001 subset_compare (char *string_to_compare, char *template_string)
3005 if (template_string != (char *) NULL && string_to_compare != (char *) NULL
3006 && strlen (string_to_compare) <= strlen (template_string))
3009 (template_string, string_to_compare, strlen (string_to_compare)) == 0);
3016 pagination_on_command (char *arg, int from_tty)
3018 pagination_enabled = 1;
3022 pagination_off_command (char *arg, int from_tty)
3024 pagination_enabled = 0;
3028 show_debug_timestamp (struct ui_file *file, int from_tty,
3029 struct cmd_list_element *c, const char *value)
3031 fprintf_filtered (file, _("Timestamping debugging messages is %s.\n"), value);
3036 initialize_utils (void)
3038 add_setshow_uinteger_cmd ("width", class_support, &chars_per_line, _("\
3039 Set number of characters gdb thinks are in a line."), _("\
3040 Show number of characters gdb thinks are in a line."), NULL,
3042 show_chars_per_line,
3043 &setlist, &showlist);
3045 add_setshow_uinteger_cmd ("height", class_support, &lines_per_page, _("\
3046 Set number of lines gdb thinks are in a page."), _("\
3047 Show number of lines gdb thinks are in a page."), NULL,
3049 show_lines_per_page,
3050 &setlist, &showlist);
3054 add_setshow_boolean_cmd ("demangle", class_support, &demangle, _("\
3055 Set demangling of encoded C++/ObjC names when displaying symbols."), _("\
3056 Show demangling of encoded C++/ObjC names when displaying symbols."), NULL,
3059 &setprintlist, &showprintlist);
3061 add_setshow_boolean_cmd ("pagination", class_support,
3062 &pagination_enabled, _("\
3063 Set state of pagination."), _("\
3064 Show state of pagination."), NULL,
3066 show_pagination_enabled,
3067 &setlist, &showlist);
3071 add_com ("am", class_support, pagination_on_command,
3072 _("Enable pagination"));
3073 add_com ("sm", class_support, pagination_off_command,
3074 _("Disable pagination"));
3077 add_setshow_boolean_cmd ("sevenbit-strings", class_support,
3078 &sevenbit_strings, _("\
3079 Set printing of 8-bit characters in strings as \\nnn."), _("\
3080 Show printing of 8-bit characters in strings as \\nnn."), NULL,
3082 show_sevenbit_strings,
3083 &setprintlist, &showprintlist);
3085 add_setshow_boolean_cmd ("asm-demangle", class_support, &asm_demangle, _("\
3086 Set demangling of C++/ObjC names in disassembly listings."), _("\
3087 Show demangling of C++/ObjC names in disassembly listings."), NULL,
3090 &setprintlist, &showprintlist);
3092 add_setshow_boolean_cmd ("timestamp", class_maintenance,
3093 &debug_timestamp, _("\
3094 Set timestamping of debugging messages."), _("\
3095 Show timestamping of debugging messages."), _("\
3096 When set, debugging messages will be marked with seconds and microseconds."),
3098 show_debug_timestamp,
3099 &setdebuglist, &showdebuglist);
3102 /* Machine specific function to handle SIGWINCH signal. */
3104 #ifdef SIGWINCH_HANDLER_BODY
3105 SIGWINCH_HANDLER_BODY
3107 /* print routines to handle variable size regs, etc. */
3108 /* temporary storage using circular buffer */
3114 static char buf[NUMCELLS][CELLSIZE];
3115 static int cell = 0;
3117 if (++cell >= NUMCELLS)
3123 paddress (struct gdbarch *gdbarch, CORE_ADDR addr)
3125 /* Truncate address to the size of a target address, avoiding shifts
3126 larger or equal than the width of a CORE_ADDR. The local
3127 variable ADDR_BIT stops the compiler reporting a shift overflow
3128 when it won't occur. */
3129 /* NOTE: This assumes that the significant address information is
3130 kept in the least significant bits of ADDR - the upper bits were
3131 either zero or sign extended. Should gdbarch_address_to_pointer or
3132 some ADDRESS_TO_PRINTABLE() be used to do the conversion? */
3134 int addr_bit = gdbarch_addr_bit (gdbarch);
3136 if (addr_bit < (sizeof (CORE_ADDR) * HOST_CHAR_BIT))
3137 addr &= ((CORE_ADDR) 1 << addr_bit) - 1;
3138 return hex_string (addr);
3142 decimal2str (char *sign, ULONGEST addr, int width)
3144 /* Steal code from valprint.c:print_decimal(). Should this worry
3145 about the real size of addr as the above does? */
3146 unsigned long temp[3];
3147 char *str = get_cell ();
3152 temp[i] = addr % (1000 * 1000 * 1000);
3153 addr /= (1000 * 1000 * 1000);
3157 while (addr != 0 && i < (sizeof (temp) / sizeof (temp[0])));
3166 xsnprintf (str, CELLSIZE, "%s%0*lu", sign, width, temp[0]);
3169 xsnprintf (str, CELLSIZE, "%s%0*lu%09lu", sign, width,
3173 xsnprintf (str, CELLSIZE, "%s%0*lu%09lu%09lu", sign, width,
3174 temp[2], temp[1], temp[0]);
3177 internal_error (__FILE__, __LINE__,
3178 _("failed internal consistency check"));
3185 octal2str (ULONGEST addr, int width)
3187 unsigned long temp[3];
3188 char *str = get_cell ();
3193 temp[i] = addr % (0100000 * 0100000);
3194 addr /= (0100000 * 0100000);
3198 while (addr != 0 && i < (sizeof (temp) / sizeof (temp[0])));
3208 xsnprintf (str, CELLSIZE, "%*o", width, 0);
3210 xsnprintf (str, CELLSIZE, "0%0*lo", width, temp[0]);
3213 xsnprintf (str, CELLSIZE, "0%0*lo%010lo", width, temp[1], temp[0]);
3216 xsnprintf (str, CELLSIZE, "0%0*lo%010lo%010lo", width,
3217 temp[2], temp[1], temp[0]);
3220 internal_error (__FILE__, __LINE__,
3221 _("failed internal consistency check"));
3228 pulongest (ULONGEST u)
3230 return decimal2str ("", u, 0);
3234 plongest (LONGEST l)
3237 return decimal2str ("-", -l, 0);
3239 return decimal2str ("", l, 0);
3242 /* Eliminate warning from compiler on 32-bit systems. */
3243 static int thirty_two = 32;
3246 phex (ULONGEST l, int sizeof_l)
3254 xsnprintf (str, CELLSIZE, "%08lx%08lx",
3255 (unsigned long) (l >> thirty_two),
3256 (unsigned long) (l & 0xffffffff));
3260 xsnprintf (str, CELLSIZE, "%08lx", (unsigned long) l);
3264 xsnprintf (str, CELLSIZE, "%04x", (unsigned short) (l & 0xffff));
3267 str = phex (l, sizeof (l));
3275 phex_nz (ULONGEST l, int sizeof_l)
3283 unsigned long high = (unsigned long) (l >> thirty_two);
3287 xsnprintf (str, CELLSIZE, "%lx",
3288 (unsigned long) (l & 0xffffffff));
3290 xsnprintf (str, CELLSIZE, "%lx%08lx", high,
3291 (unsigned long) (l & 0xffffffff));
3296 xsnprintf (str, CELLSIZE, "%lx", (unsigned long) l);
3300 xsnprintf (str, CELLSIZE, "%x", (unsigned short) (l & 0xffff));
3303 str = phex_nz (l, sizeof (l));
3310 /* Converts a LONGEST to a C-format hexadecimal literal and stores it
3311 in a static string. Returns a pointer to this string. */
3313 hex_string (LONGEST num)
3315 char *result = get_cell ();
3317 xsnprintf (result, CELLSIZE, "0x%s", phex_nz (num, sizeof (num)));
3321 /* Converts a LONGEST number to a C-format hexadecimal literal and
3322 stores it in a static string. Returns a pointer to this string
3323 that is valid until the next call. The number is padded on the
3324 left with 0s to at least WIDTH characters. */
3326 hex_string_custom (LONGEST num, int width)
3328 char *result = get_cell ();
3329 char *result_end = result + CELLSIZE - 1;
3330 const char *hex = phex_nz (num, sizeof (num));
3331 int hex_len = strlen (hex);
3333 if (hex_len > width)
3335 if (width + 2 >= CELLSIZE)
3336 internal_error (__FILE__, __LINE__,
3337 _("hex_string_custom: insufficient space to store result"));
3339 strcpy (result_end - width - 2, "0x");
3340 memset (result_end - width, '0', width);
3341 strcpy (result_end - hex_len, hex);
3342 return result_end - width - 2;
3345 /* Convert VAL to a numeral in the given radix. For
3346 * radix 10, IS_SIGNED may be true, indicating a signed quantity;
3347 * otherwise VAL is interpreted as unsigned. If WIDTH is supplied,
3348 * it is the minimum width (0-padded if needed). USE_C_FORMAT means
3349 * to use C format in all cases. If it is false, then 'x'
3350 * and 'o' formats do not include a prefix (0x or leading 0). */
3353 int_string (LONGEST val, int radix, int is_signed, int width,
3363 result = hex_string (val);
3365 result = hex_string_custom (val, width);
3372 if (is_signed && val < 0)
3373 return decimal2str ("-", -val, width);
3375 return decimal2str ("", val, width);
3379 char *result = octal2str (val, width);
3381 if (use_c_format || val == 0)
3387 internal_error (__FILE__, __LINE__,
3388 _("failed internal consistency check"));
3392 /* Convert a CORE_ADDR into a string. */
3394 core_addr_to_string (const CORE_ADDR addr)
3396 char *str = get_cell ();
3399 strcat (str, phex (addr, sizeof (addr)));
3404 core_addr_to_string_nz (const CORE_ADDR addr)
3406 char *str = get_cell ();
3409 strcat (str, phex_nz (addr, sizeof (addr)));
3413 /* Convert a string back into a CORE_ADDR. */
3415 string_to_core_addr (const char *my_string)
3419 if (my_string[0] == '0' && tolower (my_string[1]) == 'x')
3421 /* Assume that it is in hex. */
3424 for (i = 2; my_string[i] != '\0'; i++)
3426 if (isdigit (my_string[i]))
3427 addr = (my_string[i] - '0') + (addr * 16);
3428 else if (isxdigit (my_string[i]))
3429 addr = (tolower (my_string[i]) - 'a' + 0xa) + (addr * 16);
3431 error (_("invalid hex \"%s\""), my_string);
3436 /* Assume that it is in decimal. */
3439 for (i = 0; my_string[i] != '\0'; i++)
3441 if (isdigit (my_string[i]))
3442 addr = (my_string[i] - '0') + (addr * 10);
3444 error (_("invalid decimal \"%s\""), my_string);
3452 host_address_to_string (const void *addr)
3454 char *str = get_cell ();
3456 xsnprintf (str, CELLSIZE, "0x%s", phex_nz ((uintptr_t) addr, sizeof (addr)));
3461 gdb_realpath (const char *filename)
3463 /* Method 1: The system has a compile time upper bound on a filename
3464 path. Use that and realpath() to canonicalize the name. This is
3465 the most common case. Note that, if there isn't a compile time
3466 upper bound, you want to avoid realpath() at all costs. */
3467 #if defined(HAVE_REALPATH)
3469 # if defined (PATH_MAX)
3471 # define USE_REALPATH
3472 # elif defined (MAXPATHLEN)
3473 char buf[MAXPATHLEN];
3474 # define USE_REALPATH
3476 # if defined (USE_REALPATH)
3477 const char *rp = realpath (filename, buf);
3481 return xstrdup (rp);
3484 #endif /* HAVE_REALPATH */
3486 /* Method 2: The host system (i.e., GNU) has the function
3487 canonicalize_file_name() which malloc's a chunk of memory and
3488 returns that, use that. */
3489 #if defined(HAVE_CANONICALIZE_FILE_NAME)
3491 char *rp = canonicalize_file_name (filename);
3494 return xstrdup (filename);
3500 /* FIXME: cagney/2002-11-13:
3502 Method 2a: Use realpath() with a NULL buffer. Some systems, due
3503 to the problems described in in method 3, have modified their
3504 realpath() implementation so that it will allocate a buffer when
3505 NULL is passed in. Before this can be used, though, some sort of
3506 configure time test would need to be added. Otherwize the code
3507 will likely core dump. */
3509 /* Method 3: Now we're getting desperate! The system doesn't have a
3510 compile time buffer size and no alternative function. Query the
3511 OS, using pathconf(), for the buffer limit. Care is needed
3512 though, some systems do not limit PATH_MAX (return -1 for
3513 pathconf()) making it impossible to pass a correctly sized buffer
3514 to realpath() (it could always overflow). On those systems, we
3516 #if defined (HAVE_REALPATH) && defined (HAVE_UNISTD_H) && defined(HAVE_ALLOCA)
3518 /* Find out the max path size. */
3519 long path_max = pathconf ("/", _PC_PATH_MAX);
3523 /* PATH_MAX is bounded. */
3524 char *buf = alloca (path_max);
3525 char *rp = realpath (filename, buf);
3527 return xstrdup (rp ? rp : filename);
3532 /* This system is a lost cause, just dup the buffer. */
3533 return xstrdup (filename);
3536 /* Return a copy of FILENAME, with its directory prefix canonicalized
3540 xfullpath (const char *filename)
3542 const char *base_name = lbasename (filename);
3547 /* Extract the basename of filename, and return immediately
3548 a copy of filename if it does not contain any directory prefix. */
3549 if (base_name == filename)
3550 return xstrdup (filename);
3552 dir_name = alloca ((size_t) (base_name - filename + 2));
3553 /* Allocate enough space to store the dir_name + plus one extra
3554 character sometimes needed under Windows (see below), and
3555 then the closing \000 character */
3556 strncpy (dir_name, filename, base_name - filename);
3557 dir_name[base_name - filename] = '\000';
3559 #ifdef HAVE_DOS_BASED_FILE_SYSTEM
3560 /* We need to be careful when filename is of the form 'd:foo', which
3561 is equivalent of d:./foo, which is totally different from d:/foo. */
3562 if (strlen (dir_name) == 2 && isalpha (dir_name[0]) && dir_name[1] == ':')
3565 dir_name[3] = '\000';
3569 /* Canonicalize the directory prefix, and build the resulting
3570 filename. If the dirname realpath already contains an ending
3571 directory separator, avoid doubling it. */
3572 real_path = gdb_realpath (dir_name);
3573 if (IS_DIR_SEPARATOR (real_path[strlen (real_path) - 1]))
3574 result = concat (real_path, base_name, (char *) NULL);
3576 result = concat (real_path, SLASH_STRING, base_name, (char *) NULL);
3583 /* This is the 32-bit CRC function used by the GNU separate debug
3584 facility. An executable may contain a section named
3585 .gnu_debuglink, which holds the name of a separate executable file
3586 containing its debug info, and a checksum of that file's contents,
3587 computed using this function. */
3589 gnu_debuglink_crc32 (unsigned long crc, unsigned char *buf, size_t len)
3591 static const unsigned int crc32_table[256] = {
3592 0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419,
3593 0x706af48f, 0xe963a535, 0x9e6495a3, 0x0edb8832, 0x79dcb8a4,
3594 0xe0d5e91e, 0x97d2d988, 0x09b64c2b, 0x7eb17cbd, 0xe7b82d07,
3595 0x90bf1d91, 0x1db71064, 0x6ab020f2, 0xf3b97148, 0x84be41de,
3596 0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7, 0x136c9856,
3597 0x646ba8c0, 0xfd62f97a, 0x8a65c9ec, 0x14015c4f, 0x63066cd9,
3598 0xfa0f3d63, 0x8d080df5, 0x3b6e20c8, 0x4c69105e, 0xd56041e4,
3599 0xa2677172, 0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b,
3600 0x35b5a8fa, 0x42b2986c, 0xdbbbc9d6, 0xacbcf940, 0x32d86ce3,
3601 0x45df5c75, 0xdcd60dcf, 0xabd13d59, 0x26d930ac, 0x51de003a,
3602 0xc8d75180, 0xbfd06116, 0x21b4f4b5, 0x56b3c423, 0xcfba9599,
3603 0xb8bda50f, 0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924,
3604 0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d, 0x76dc4190,
3605 0x01db7106, 0x98d220bc, 0xefd5102a, 0x71b18589, 0x06b6b51f,
3606 0x9fbfe4a5, 0xe8b8d433, 0x7807c9a2, 0x0f00f934, 0x9609a88e,
3607 0xe10e9818, 0x7f6a0dbb, 0x086d3d2d, 0x91646c97, 0xe6635c01,
3608 0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e, 0x6c0695ed,
3609 0x1b01a57b, 0x8208f4c1, 0xf50fc457, 0x65b0d9c6, 0x12b7e950,
3610 0x8bbeb8ea, 0xfcb9887c, 0x62dd1ddf, 0x15da2d49, 0x8cd37cf3,
3611 0xfbd44c65, 0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2,
3612 0x4adfa541, 0x3dd895d7, 0xa4d1c46d, 0xd3d6f4fb, 0x4369e96a,
3613 0x346ed9fc, 0xad678846, 0xda60b8d0, 0x44042d73, 0x33031de5,
3614 0xaa0a4c5f, 0xdd0d7cc9, 0x5005713c, 0x270241aa, 0xbe0b1010,
3615 0xc90c2086, 0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f,
3616 0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4, 0x59b33d17,
3617 0x2eb40d81, 0xb7bd5c3b, 0xc0ba6cad, 0xedb88320, 0x9abfb3b6,
3618 0x03b6e20c, 0x74b1d29a, 0xead54739, 0x9dd277af, 0x04db2615,
3619 0x73dc1683, 0xe3630b12, 0x94643b84, 0x0d6d6a3e, 0x7a6a5aa8,
3620 0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1, 0xf00f9344,
3621 0x8708a3d2, 0x1e01f268, 0x6906c2fe, 0xf762575d, 0x806567cb,
3622 0x196c3671, 0x6e6b06e7, 0xfed41b76, 0x89d32be0, 0x10da7a5a,
3623 0x67dd4acc, 0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5,
3624 0xd6d6a3e8, 0xa1d1937e, 0x38d8c2c4, 0x4fdff252, 0xd1bb67f1,
3625 0xa6bc5767, 0x3fb506dd, 0x48b2364b, 0xd80d2bda, 0xaf0a1b4c,
3626 0x36034af6, 0x41047a60, 0xdf60efc3, 0xa867df55, 0x316e8eef,
3627 0x4669be79, 0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236,
3628 0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f, 0xc5ba3bbe,
3629 0xb2bd0b28, 0x2bb45a92, 0x5cb36a04, 0xc2d7ffa7, 0xb5d0cf31,
3630 0x2cd99e8b, 0x5bdeae1d, 0x9b64c2b0, 0xec63f226, 0x756aa39c,
3631 0x026d930a, 0x9c0906a9, 0xeb0e363f, 0x72076785, 0x05005713,
3632 0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38, 0x92d28e9b,
3633 0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21, 0x86d3d2d4, 0xf1d4e242,
3634 0x68ddb3f8, 0x1fda836e, 0x81be16cd, 0xf6b9265b, 0x6fb077e1,
3635 0x18b74777, 0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c,
3636 0x8f659eff, 0xf862ae69, 0x616bffd3, 0x166ccf45, 0xa00ae278,
3637 0xd70dd2ee, 0x4e048354, 0x3903b3c2, 0xa7672661, 0xd06016f7,
3638 0x4969474d, 0x3e6e77db, 0xaed16a4a, 0xd9d65adc, 0x40df0b66,
3639 0x37d83bf0, 0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9,
3640 0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6, 0xbad03605,
3641 0xcdd70693, 0x54de5729, 0x23d967bf, 0xb3667a2e, 0xc4614ab8,
3642 0x5d681b02, 0x2a6f2b94, 0xb40bbe37, 0xc30c8ea1, 0x5a05df1b,
3647 crc = ~crc & 0xffffffff;
3648 for (end = buf + len; buf < end; ++buf)
3649 crc = crc32_table[(crc ^ *buf) & 0xff] ^ (crc >> 8);
3650 return ~crc & 0xffffffff;;
3654 align_up (ULONGEST v, int n)
3656 /* Check that N is really a power of two. */
3657 gdb_assert (n && (n & (n-1)) == 0);
3658 return (v + n - 1) & -n;
3662 align_down (ULONGEST v, int n)
3664 /* Check that N is really a power of two. */
3665 gdb_assert (n && (n & (n-1)) == 0);
3669 /* Allocation function for the libiberty hash table which uses an
3670 obstack. The obstack is passed as DATA. */
3673 hashtab_obstack_allocate (void *data, size_t size, size_t count)
3675 unsigned int total = size * count;
3676 void *ptr = obstack_alloc ((struct obstack *) data, total);
3678 memset (ptr, 0, total);
3682 /* Trivial deallocation function for the libiberty splay tree and hash
3683 table - don't deallocate anything. Rely on later deletion of the
3684 obstack. DATA will be the obstack, although it is not needed
3688 dummy_obstack_deallocate (void *object, void *data)
3693 /* The bit offset of the highest byte in a ULONGEST, for overflow
3696 #define HIGH_BYTE_POSN ((sizeof (ULONGEST) - 1) * HOST_CHAR_BIT)
3698 /* True (non-zero) iff DIGIT is a valid digit in radix BASE,
3699 where 2 <= BASE <= 36. */
3702 is_digit_in_base (unsigned char digit, int base)
3704 if (!isalnum (digit))
3707 return (isdigit (digit) && digit < base + '0');
3709 return (isdigit (digit) || tolower (digit) < base - 10 + 'a');
3713 digit_to_int (unsigned char c)
3718 return tolower (c) - 'a' + 10;
3721 /* As for strtoul, but for ULONGEST results. */
3724 strtoulst (const char *num, const char **trailer, int base)
3726 unsigned int high_part;
3731 /* Skip leading whitespace. */
3732 while (isspace (num[i]))
3735 /* Handle prefixes. */
3738 else if (num[i] == '-')
3744 if (base == 0 || base == 16)
3746 if (num[i] == '0' && (num[i + 1] == 'x' || num[i + 1] == 'X'))
3754 if (base == 0 && num[i] == '0')
3760 if (base < 2 || base > 36)
3766 result = high_part = 0;
3767 for (; is_digit_in_base (num[i], base); i += 1)
3769 result = result * base + digit_to_int (num[i]);
3770 high_part = high_part * base + (unsigned int) (result >> HIGH_BYTE_POSN);
3771 result &= ((ULONGEST) 1 << HIGH_BYTE_POSN) - 1;
3772 if (high_part > 0xff)
3775 result = ~ (ULONGEST) 0;
3782 if (trailer != NULL)
3785 result = result + ((ULONGEST) high_part << HIGH_BYTE_POSN);
3792 /* Simple, portable version of dirname that does not modify its
3796 ldirname (const char *filename)
3798 const char *base = lbasename (filename);
3801 while (base > filename && IS_DIR_SEPARATOR (base[-1]))
3804 if (base == filename)
3807 dirname = xmalloc (base - filename + 2);
3808 memcpy (dirname, filename, base - filename);
3810 /* On DOS based file systems, convert "d:foo" to "d:.", so that we
3811 create "d:./bar" later instead of the (different) "d:/bar". */
3812 if (base - filename == 2 && IS_ABSOLUTE_PATH (base)
3813 && !IS_DIR_SEPARATOR (filename[0]))
3814 dirname[base++ - filename] = '.';
3816 dirname[base - filename] = '\0';
3820 /* Call libiberty's buildargv, and return the result.
3821 If buildargv fails due to out-of-memory, call nomem.
3822 Therefore, the returned value is guaranteed to be non-NULL,
3823 unless the parameter itself is NULL. */
3826 gdb_buildargv (const char *s)
3828 char **argv = buildargv (s);
3830 if (s != NULL && argv == NULL)
3836 compare_positive_ints (const void *ap, const void *bp)
3838 /* Because we know we're comparing two ints which are positive,
3839 there's no danger of overflow here. */
3840 return * (int *) ap - * (int *) bp;
3843 #define AMBIGUOUS_MESS1 ".\nMatching formats:"
3844 #define AMBIGUOUS_MESS2 ".\nUse \"set gnutarget format-name\" to specify the format."
3847 gdb_bfd_errmsg (bfd_error_type error_tag, char **matching)
3853 /* Check if errmsg just need simple return. */
3854 if (error_tag != bfd_error_file_ambiguously_recognized || matching == NULL)
3855 return bfd_errmsg (error_tag);
3857 ret_len = strlen (bfd_errmsg (error_tag)) + strlen (AMBIGUOUS_MESS1)
3858 + strlen (AMBIGUOUS_MESS2);
3859 for (p = matching; *p; p++)
3860 ret_len += strlen (*p) + 1;
3861 ret = xmalloc (ret_len + 1);
3863 make_cleanup (xfree, ret);
3865 strcpy (retp, bfd_errmsg (error_tag));
3866 retp += strlen (retp);
3868 strcpy (retp, AMBIGUOUS_MESS1);
3869 retp += strlen (retp);
3871 for (p = matching; *p; p++)
3873 sprintf (retp, " %s", *p);
3874 retp += strlen (retp);
3878 strcpy (retp, AMBIGUOUS_MESS2);
3883 /* Return ARGS parsed as a valid pid, or throw an error. */
3886 parse_pid_to_attach (char *args)
3892 error_no_arg (_("process-id to attach"));
3895 pid = strtoul (args, &dummy, 0);
3896 /* Some targets don't set errno on errors, grrr! */
3897 if ((pid == 0 && dummy == args) || dummy != &args[strlen (args)])
3898 error (_("Illegal process-id: %s."), args);
3903 /* Provide a prototype to silence -Wmissing-prototypes. */
3904 extern initialize_file_ftype _initialize_utils;
3907 _initialize_utils (void)
3909 add_internal_problem_command (&internal_error_problem);
3910 add_internal_problem_command (&internal_warning_problem);