* gas/nios2/nios2.exp: Add copyright.
[deliverable/binutils-gdb.git] / gdb / utils.c
1 /* General utility routines for GDB, the GNU debugger.
2
3 Copyright (C) 1986-2013 Free Software Foundation, Inc.
4
5 This file is part of GDB.
6
7 This program is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 3 of the License, or
10 (at your option) any later version.
11
12 This program is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with this program. If not, see <http://www.gnu.org/licenses/>. */
19
20 #include "defs.h"
21 #include "dyn-string.h"
22 #include "gdb_assert.h"
23 #include <ctype.h>
24 #include "gdb_string.h"
25 #include "gdb_wait.h"
26 #include "event-top.h"
27 #include "exceptions.h"
28 #include "gdbthread.h"
29 #include "fnmatch.h"
30 #include "gdb_bfd.h"
31 #ifdef HAVE_SYS_RESOURCE_H
32 #include <sys/resource.h>
33 #endif /* HAVE_SYS_RESOURCE_H */
34
35 #ifdef TUI
36 #include "tui/tui.h" /* For tui_get_command_dimension. */
37 #endif
38
39 #ifdef __GO32__
40 #include <pc.h>
41 #endif
42
43 /* SunOS's curses.h has a '#define reg register' in it. Thank you Sun. */
44 #ifdef reg
45 #undef reg
46 #endif
47
48 #include <signal.h>
49 #include "timeval-utils.h"
50 #include "gdbcmd.h"
51 #include "serial.h"
52 #include "bfd.h"
53 #include "target.h"
54 #include "gdb-demangle.h"
55 #include "expression.h"
56 #include "language.h"
57 #include "charset.h"
58 #include "annotate.h"
59 #include "filenames.h"
60 #include "symfile.h"
61 #include "gdb_obstack.h"
62 #include "gdbcore.h"
63 #include "top.h"
64 #include "main.h"
65 #include "solist.h"
66
67 #include "inferior.h" /* for signed_pointer_to_address */
68
69 #include <sys/param.h> /* For MAXPATHLEN */
70
71 #include "gdb_curses.h"
72
73 #include "readline/readline.h"
74
75 #include <sys/time.h>
76 #include <time.h>
77
78 #include "gdb_usleep.h"
79 #include "interps.h"
80 #include "gdb_regex.h"
81
82 #if !HAVE_DECL_MALLOC
83 extern PTR malloc (); /* ARI: PTR */
84 #endif
85 #if !HAVE_DECL_REALLOC
86 extern PTR realloc (); /* ARI: PTR */
87 #endif
88 #if !HAVE_DECL_FREE
89 extern void free ();
90 #endif
91
92 /* readline defines this. */
93 #undef savestring
94
95 void (*deprecated_error_begin_hook) (void);
96
97 /* Prototypes for local functions */
98
99 static void vfprintf_maybe_filtered (struct ui_file *, const char *,
100 va_list, int) ATTRIBUTE_PRINTF (2, 0);
101
102 static void fputs_maybe_filtered (const char *, struct ui_file *, int);
103
104 static void prompt_for_continue (void);
105
106 static void set_screen_size (void);
107 static void set_width (void);
108
109 /* Time spent in prompt_for_continue in the currently executing command
110 waiting for user to respond.
111 Initialized in make_command_stats_cleanup.
112 Modified in prompt_for_continue and defaulted_query.
113 Used in report_command_stats. */
114
115 static struct timeval prompt_for_continue_wait_time;
116
117 /* A flag indicating whether to timestamp debugging messages. */
118
119 static int debug_timestamp = 0;
120
121 /* Nonzero if we have job control. */
122
123 int job_control;
124
125 #ifndef HAVE_PYTHON
126 /* Nonzero means a quit has been requested. */
127
128 int quit_flag;
129 #endif /* HAVE_PYTHON */
130
131 /* Nonzero means quit immediately if Control-C is typed now, rather
132 than waiting until QUIT is executed. Be careful in setting this;
133 code which executes with immediate_quit set has to be very careful
134 about being able to deal with being interrupted at any time. It is
135 almost always better to use QUIT; the only exception I can think of
136 is being able to quit out of a system call (using EINTR loses if
137 the SIGINT happens between the previous QUIT and the system call).
138 To immediately quit in the case in which a SIGINT happens between
139 the previous QUIT and setting immediate_quit (desirable anytime we
140 expect to block), call QUIT after setting immediate_quit. */
141
142 int immediate_quit;
143
144 #ifndef HAVE_PYTHON
145
146 /* Clear the quit flag. */
147
148 void
149 clear_quit_flag (void)
150 {
151 quit_flag = 0;
152 }
153
154 /* Set the quit flag. */
155
156 void
157 set_quit_flag (void)
158 {
159 quit_flag = 1;
160 }
161
162 /* Return true if the quit flag has been set, false otherwise. */
163
164 int
165 check_quit_flag (void)
166 {
167 /* This is written in a particular way to avoid races. */
168 if (quit_flag)
169 {
170 quit_flag = 0;
171 return 1;
172 }
173
174 return 0;
175 }
176
177 #endif /* HAVE_PYTHON */
178
179 /* Nonzero means that strings with character values >0x7F should be printed
180 as octal escapes. Zero means just print the value (e.g. it's an
181 international character, and the terminal or window can cope.) */
182
183 int sevenbit_strings = 0;
184 static void
185 show_sevenbit_strings (struct ui_file *file, int from_tty,
186 struct cmd_list_element *c, const char *value)
187 {
188 fprintf_filtered (file, _("Printing of 8-bit characters "
189 "in strings as \\nnn is %s.\n"),
190 value);
191 }
192
193 /* String to be printed before error messages, if any. */
194
195 char *error_pre_print;
196
197 /* String to be printed before quit messages, if any. */
198
199 char *quit_pre_print;
200
201 /* String to be printed before warning messages, if any. */
202
203 char *warning_pre_print = "\nwarning: ";
204
205 int pagination_enabled = 1;
206 static void
207 show_pagination_enabled (struct ui_file *file, int from_tty,
208 struct cmd_list_element *c, const char *value)
209 {
210 fprintf_filtered (file, _("State of pagination is %s.\n"), value);
211 }
212
213 \f
214 /* Cleanup utilities.
215
216 These are not defined in cleanups.c (nor declared in cleanups.h)
217 because while they use the "cleanup API" they are not part of the
218 "cleanup API". */
219
220 static void
221 do_freeargv (void *arg)
222 {
223 freeargv ((char **) arg);
224 }
225
226 struct cleanup *
227 make_cleanup_freeargv (char **arg)
228 {
229 return make_cleanup (do_freeargv, arg);
230 }
231
232 static void
233 do_dyn_string_delete (void *arg)
234 {
235 dyn_string_delete ((dyn_string_t) arg);
236 }
237
238 struct cleanup *
239 make_cleanup_dyn_string_delete (dyn_string_t arg)
240 {
241 return make_cleanup (do_dyn_string_delete, arg);
242 }
243
244 static void
245 do_bfd_close_cleanup (void *arg)
246 {
247 gdb_bfd_unref (arg);
248 }
249
250 struct cleanup *
251 make_cleanup_bfd_unref (bfd *abfd)
252 {
253 return make_cleanup (do_bfd_close_cleanup, abfd);
254 }
255
256 static void
257 do_close_cleanup (void *arg)
258 {
259 int *fd = arg;
260
261 close (*fd);
262 }
263
264 struct cleanup *
265 make_cleanup_close (int fd)
266 {
267 int *saved_fd = xmalloc (sizeof (fd));
268
269 *saved_fd = fd;
270 return make_cleanup_dtor (do_close_cleanup, saved_fd, xfree);
271 }
272
273 /* Helper function which does the work for make_cleanup_fclose. */
274
275 static void
276 do_fclose_cleanup (void *arg)
277 {
278 FILE *file = arg;
279
280 fclose (file);
281 }
282
283 /* Return a new cleanup that closes FILE. */
284
285 struct cleanup *
286 make_cleanup_fclose (FILE *file)
287 {
288 return make_cleanup (do_fclose_cleanup, file);
289 }
290
291 /* Helper function which does the work for make_cleanup_obstack_free. */
292
293 static void
294 do_obstack_free (void *arg)
295 {
296 struct obstack *ob = arg;
297
298 obstack_free (ob, NULL);
299 }
300
301 /* Return a new cleanup that frees OBSTACK. */
302
303 struct cleanup *
304 make_cleanup_obstack_free (struct obstack *obstack)
305 {
306 return make_cleanup (do_obstack_free, obstack);
307 }
308
309 static void
310 do_ui_file_delete (void *arg)
311 {
312 ui_file_delete (arg);
313 }
314
315 struct cleanup *
316 make_cleanup_ui_file_delete (struct ui_file *arg)
317 {
318 return make_cleanup (do_ui_file_delete, arg);
319 }
320
321 /* Helper function for make_cleanup_ui_out_redirect_pop. */
322
323 static void
324 do_ui_out_redirect_pop (void *arg)
325 {
326 struct ui_out *uiout = arg;
327
328 if (ui_out_redirect (uiout, NULL) < 0)
329 warning (_("Cannot restore redirection of the current output protocol"));
330 }
331
332 /* Return a new cleanup that pops the last redirection by ui_out_redirect
333 with NULL parameter. */
334
335 struct cleanup *
336 make_cleanup_ui_out_redirect_pop (struct ui_out *uiout)
337 {
338 return make_cleanup (do_ui_out_redirect_pop, uiout);
339 }
340
341 static void
342 do_free_section_addr_info (void *arg)
343 {
344 free_section_addr_info (arg);
345 }
346
347 struct cleanup *
348 make_cleanup_free_section_addr_info (struct section_addr_info *addrs)
349 {
350 return make_cleanup (do_free_section_addr_info, addrs);
351 }
352
353 struct restore_integer_closure
354 {
355 int *variable;
356 int value;
357 };
358
359 static void
360 restore_integer (void *p)
361 {
362 struct restore_integer_closure *closure = p;
363
364 *(closure->variable) = closure->value;
365 }
366
367 /* Remember the current value of *VARIABLE and make it restored when
368 the cleanup is run. */
369
370 struct cleanup *
371 make_cleanup_restore_integer (int *variable)
372 {
373 struct restore_integer_closure *c =
374 xmalloc (sizeof (struct restore_integer_closure));
375
376 c->variable = variable;
377 c->value = *variable;
378
379 return make_cleanup_dtor (restore_integer, (void *) c, xfree);
380 }
381
382 /* Remember the current value of *VARIABLE and make it restored when
383 the cleanup is run. */
384
385 struct cleanup *
386 make_cleanup_restore_uinteger (unsigned int *variable)
387 {
388 return make_cleanup_restore_integer ((int *) variable);
389 }
390
391 /* Helper for make_cleanup_unpush_target. */
392
393 static void
394 do_unpush_target (void *arg)
395 {
396 struct target_ops *ops = arg;
397
398 unpush_target (ops);
399 }
400
401 /* Return a new cleanup that unpushes OPS. */
402
403 struct cleanup *
404 make_cleanup_unpush_target (struct target_ops *ops)
405 {
406 return make_cleanup (do_unpush_target, ops);
407 }
408
409 /* Helper for make_cleanup_htab_delete compile time checking the types. */
410
411 static void
412 do_htab_delete_cleanup (void *htab_voidp)
413 {
414 htab_t htab = htab_voidp;
415
416 htab_delete (htab);
417 }
418
419 /* Return a new cleanup that deletes HTAB. */
420
421 struct cleanup *
422 make_cleanup_htab_delete (htab_t htab)
423 {
424 return make_cleanup (do_htab_delete_cleanup, htab);
425 }
426
427 struct restore_ui_file_closure
428 {
429 struct ui_file **variable;
430 struct ui_file *value;
431 };
432
433 static void
434 do_restore_ui_file (void *p)
435 {
436 struct restore_ui_file_closure *closure = p;
437
438 *(closure->variable) = closure->value;
439 }
440
441 /* Remember the current value of *VARIABLE and make it restored when
442 the cleanup is run. */
443
444 struct cleanup *
445 make_cleanup_restore_ui_file (struct ui_file **variable)
446 {
447 struct restore_ui_file_closure *c = XNEW (struct restore_ui_file_closure);
448
449 c->variable = variable;
450 c->value = *variable;
451
452 return make_cleanup_dtor (do_restore_ui_file, (void *) c, xfree);
453 }
454
455 /* Helper for make_cleanup_value_free_to_mark. */
456
457 static void
458 do_value_free_to_mark (void *value)
459 {
460 value_free_to_mark ((struct value *) value);
461 }
462
463 /* Free all values allocated since MARK was obtained by value_mark
464 (except for those released) when the cleanup is run. */
465
466 struct cleanup *
467 make_cleanup_value_free_to_mark (struct value *mark)
468 {
469 return make_cleanup (do_value_free_to_mark, mark);
470 }
471
472 /* Helper for make_cleanup_value_free. */
473
474 static void
475 do_value_free (void *value)
476 {
477 value_free (value);
478 }
479
480 /* Free VALUE. */
481
482 struct cleanup *
483 make_cleanup_value_free (struct value *value)
484 {
485 return make_cleanup (do_value_free, value);
486 }
487
488 /* Helper for make_cleanup_free_so. */
489
490 static void
491 do_free_so (void *arg)
492 {
493 struct so_list *so = arg;
494
495 free_so (so);
496 }
497
498 /* Make cleanup handler calling free_so for SO. */
499
500 struct cleanup *
501 make_cleanup_free_so (struct so_list *so)
502 {
503 return make_cleanup (do_free_so, so);
504 }
505
506 /* Helper for make_cleanup_restore_current_language. */
507
508 static void
509 do_restore_current_language (void *p)
510 {
511 enum language saved_lang = (uintptr_t) p;
512
513 set_language (saved_lang);
514 }
515
516 /* Remember the current value of CURRENT_LANGUAGE and make it restored when
517 the cleanup is run. */
518
519 struct cleanup *
520 make_cleanup_restore_current_language (void)
521 {
522 enum language saved_lang = current_language->la_language;
523
524 return make_cleanup (do_restore_current_language,
525 (void *) (uintptr_t) saved_lang);
526 }
527
528 /* This function is useful for cleanups.
529 Do
530
531 foo = xmalloc (...);
532 old_chain = make_cleanup (free_current_contents, &foo);
533
534 to arrange to free the object thus allocated. */
535
536 void
537 free_current_contents (void *ptr)
538 {
539 void **location = ptr;
540
541 if (location == NULL)
542 internal_error (__FILE__, __LINE__,
543 _("free_current_contents: NULL pointer"));
544 if (*location != NULL)
545 {
546 xfree (*location);
547 *location = NULL;
548 }
549 }
550
551 /* If nonzero, display time usage both at startup and for each command. */
552
553 static int display_time;
554
555 /* If nonzero, display space usage both at startup and for each command. */
556
557 static int display_space;
558
559 /* Records a run time and space usage to be used as a base for
560 reporting elapsed time or change in space. In addition,
561 the msg_type field indicates whether the saved time is from the
562 beginning of GDB execution (0) or the beginning of an individual
563 command execution (1). */
564 struct cmd_stats
565 {
566 int msg_type;
567 long start_cpu_time;
568 struct timeval start_wall_time;
569 long start_space;
570 };
571
572 /* Set whether to display time statistics to NEW_VALUE (non-zero
573 means true). */
574 void
575 set_display_time (int new_value)
576 {
577 display_time = new_value;
578 }
579
580 /* Set whether to display space statistics to NEW_VALUE (non-zero
581 means true). */
582 void
583 set_display_space (int new_value)
584 {
585 display_space = new_value;
586 }
587
588 /* As indicated by display_time and display_space, report GDB's elapsed time
589 and space usage from the base time and space provided in ARG, which
590 must be a pointer to a struct cmd_stat. This function is intended
591 to be called as a cleanup. */
592 static void
593 report_command_stats (void *arg)
594 {
595 struct cmd_stats *start_stats = (struct cmd_stats *) arg;
596 int msg_type = start_stats->msg_type;
597
598 if (display_time)
599 {
600 long cmd_time = get_run_time () - start_stats->start_cpu_time;
601 struct timeval now_wall_time, delta_wall_time;
602
603 gettimeofday (&now_wall_time, NULL);
604 timeval_sub (&delta_wall_time,
605 &now_wall_time, &start_stats->start_wall_time);
606
607 /* Subtract time spend in prompt_for_continue from walltime. */
608 timeval_sub (&delta_wall_time,
609 &delta_wall_time, &prompt_for_continue_wait_time);
610
611 printf_unfiltered (msg_type == 0
612 ? _("Startup time: %ld.%06ld (cpu), %ld.%06ld (wall)\n")
613 : _("Command execution time: %ld.%06ld (cpu), %ld.%06ld (wall)\n"),
614 cmd_time / 1000000, cmd_time % 1000000,
615 (long) delta_wall_time.tv_sec,
616 (long) delta_wall_time.tv_usec);
617 }
618
619 if (display_space)
620 {
621 #ifdef HAVE_SBRK
622 char *lim = (char *) sbrk (0);
623
624 long space_now = lim - lim_at_start;
625 long space_diff = space_now - start_stats->start_space;
626
627 printf_unfiltered (msg_type == 0
628 ? _("Space used: %ld (%s%ld during startup)\n")
629 : _("Space used: %ld (%s%ld for this command)\n"),
630 space_now,
631 (space_diff >= 0 ? "+" : ""),
632 space_diff);
633 #endif
634 }
635 }
636
637 /* Create a cleanup that reports time and space used since its
638 creation. Precise messages depend on MSG_TYPE:
639 0: Initial time/space
640 1: Individual command time/space. */
641 struct cleanup *
642 make_command_stats_cleanup (int msg_type)
643 {
644 static const struct timeval zero_timeval = { 0 };
645 struct cmd_stats *new_stat = XMALLOC (struct cmd_stats);
646
647 #ifdef HAVE_SBRK
648 char *lim = (char *) sbrk (0);
649 new_stat->start_space = lim - lim_at_start;
650 #endif
651
652 new_stat->msg_type = msg_type;
653 new_stat->start_cpu_time = get_run_time ();
654 gettimeofday (&new_stat->start_wall_time, NULL);
655
656 /* Initalize timer to keep track of how long we waited for the user. */
657 prompt_for_continue_wait_time = zero_timeval;
658
659 return make_cleanup_dtor (report_command_stats, new_stat, xfree);
660 }
661 \f
662
663
664 /* Print a warning message. The first argument STRING is the warning
665 message, used as an fprintf format string, the second is the
666 va_list of arguments for that string. A warning is unfiltered (not
667 paginated) so that the user does not need to page through each
668 screen full of warnings when there are lots of them. */
669
670 void
671 vwarning (const char *string, va_list args)
672 {
673 if (deprecated_warning_hook)
674 (*deprecated_warning_hook) (string, args);
675 else
676 {
677 target_terminal_ours ();
678 wrap_here (""); /* Force out any buffered output. */
679 gdb_flush (gdb_stdout);
680 if (warning_pre_print)
681 fputs_unfiltered (warning_pre_print, gdb_stderr);
682 vfprintf_unfiltered (gdb_stderr, string, args);
683 fprintf_unfiltered (gdb_stderr, "\n");
684 va_end (args);
685 }
686 }
687
688 /* Print a warning message.
689 The first argument STRING is the warning message, used as a fprintf string,
690 and the remaining args are passed as arguments to it.
691 The primary difference between warnings and errors is that a warning
692 does not force the return to command level. */
693
694 void
695 warning (const char *string, ...)
696 {
697 va_list args;
698
699 va_start (args, string);
700 vwarning (string, args);
701 va_end (args);
702 }
703
704 /* Print an error message and return to command level.
705 The first argument STRING is the error message, used as a fprintf string,
706 and the remaining args are passed as arguments to it. */
707
708 void
709 verror (const char *string, va_list args)
710 {
711 throw_verror (GENERIC_ERROR, string, args);
712 }
713
714 void
715 error (const char *string, ...)
716 {
717 va_list args;
718
719 va_start (args, string);
720 throw_verror (GENERIC_ERROR, string, args);
721 va_end (args);
722 }
723
724 /* Print an error message and quit.
725 The first argument STRING is the error message, used as a fprintf string,
726 and the remaining args are passed as arguments to it. */
727
728 void
729 vfatal (const char *string, va_list args)
730 {
731 throw_vfatal (string, args);
732 }
733
734 void
735 fatal (const char *string, ...)
736 {
737 va_list args;
738
739 va_start (args, string);
740 throw_vfatal (string, args);
741 va_end (args);
742 }
743
744 void
745 error_stream (struct ui_file *stream)
746 {
747 char *message = ui_file_xstrdup (stream, NULL);
748
749 make_cleanup (xfree, message);
750 error (("%s"), message);
751 }
752
753 /* Dump core trying to increase the core soft limit to hard limit first. */
754
755 static void
756 dump_core (void)
757 {
758 #ifdef HAVE_SETRLIMIT
759 struct rlimit rlim = { RLIM_INFINITY, RLIM_INFINITY };
760
761 setrlimit (RLIMIT_CORE, &rlim);
762 #endif /* HAVE_SETRLIMIT */
763
764 abort (); /* NOTE: GDB has only three calls to abort(). */
765 }
766
767 /* Check whether GDB will be able to dump core using the dump_core
768 function. */
769
770 static int
771 can_dump_core (const char *reason)
772 {
773 #ifdef HAVE_GETRLIMIT
774 struct rlimit rlim;
775
776 /* Be quiet and assume we can dump if an error is returned. */
777 if (getrlimit (RLIMIT_CORE, &rlim) != 0)
778 return 1;
779
780 if (rlim.rlim_max == 0)
781 {
782 fprintf_unfiltered (gdb_stderr,
783 _("%s\nUnable to dump core, use `ulimit -c"
784 " unlimited' before executing GDB next time.\n"),
785 reason);
786 return 0;
787 }
788 #endif /* HAVE_GETRLIMIT */
789
790 return 1;
791 }
792
793 /* Allow the user to configure the debugger behavior with respect to
794 what to do when an internal problem is detected. */
795
796 const char internal_problem_ask[] = "ask";
797 const char internal_problem_yes[] = "yes";
798 const char internal_problem_no[] = "no";
799 static const char *const internal_problem_modes[] =
800 {
801 internal_problem_ask,
802 internal_problem_yes,
803 internal_problem_no,
804 NULL
805 };
806
807 /* Print a message reporting an internal error/warning. Ask the user
808 if they want to continue, dump core, or just exit. Return
809 something to indicate a quit. */
810
811 struct internal_problem
812 {
813 const char *name;
814 const char *should_quit;
815 const char *should_dump_core;
816 };
817
818 /* Report a problem, internal to GDB, to the user. Once the problem
819 has been reported, and assuming GDB didn't quit, the caller can
820 either allow execution to resume or throw an error. */
821
822 static void ATTRIBUTE_PRINTF (4, 0)
823 internal_vproblem (struct internal_problem *problem,
824 const char *file, int line, const char *fmt, va_list ap)
825 {
826 static int dejavu;
827 int quit_p;
828 int dump_core_p;
829 char *reason;
830
831 /* Don't allow infinite error/warning recursion. */
832 {
833 static char msg[] = "Recursive internal problem.\n";
834
835 switch (dejavu)
836 {
837 case 0:
838 dejavu = 1;
839 break;
840 case 1:
841 dejavu = 2;
842 fputs_unfiltered (msg, gdb_stderr);
843 abort (); /* NOTE: GDB has only three calls to abort(). */
844 default:
845 dejavu = 3;
846 /* Newer GLIBC versions put the warn_unused_result attribute
847 on write, but this is one of those rare cases where
848 ignoring the return value is correct. Casting to (void)
849 does not fix this problem. This is the solution suggested
850 at http://gcc.gnu.org/bugzilla/show_bug.cgi?id=25509. */
851 if (write (STDERR_FILENO, msg, sizeof (msg)) != sizeof (msg))
852 abort (); /* NOTE: GDB has only three calls to abort(). */
853 exit (1);
854 }
855 }
856
857 /* Try to get the message out and at the start of a new line. */
858 target_terminal_ours ();
859 begin_line ();
860
861 /* Create a string containing the full error/warning message. Need
862 to call query with this full string, as otherwize the reason
863 (error/warning) and question become separated. Format using a
864 style similar to a compiler error message. Include extra detail
865 so that the user knows that they are living on the edge. */
866 {
867 char *msg;
868
869 msg = xstrvprintf (fmt, ap);
870 reason = xstrprintf ("%s:%d: %s: %s\n"
871 "A problem internal to GDB has been detected,\n"
872 "further debugging may prove unreliable.",
873 file, line, problem->name, msg);
874 xfree (msg);
875 make_cleanup (xfree, reason);
876 }
877
878 if (problem->should_quit == internal_problem_ask)
879 {
880 /* Default (yes/batch case) is to quit GDB. When in batch mode
881 this lessens the likelihood of GDB going into an infinite
882 loop. */
883 if (!confirm)
884 {
885 /* Emit the message and quit. */
886 fputs_unfiltered (reason, gdb_stderr);
887 fputs_unfiltered ("\n", gdb_stderr);
888 quit_p = 1;
889 }
890 else
891 quit_p = query (_("%s\nQuit this debugging session? "), reason);
892 }
893 else if (problem->should_quit == internal_problem_yes)
894 quit_p = 1;
895 else if (problem->should_quit == internal_problem_no)
896 quit_p = 0;
897 else
898 internal_error (__FILE__, __LINE__, _("bad switch"));
899
900 if (problem->should_dump_core == internal_problem_ask)
901 {
902 if (!can_dump_core (reason))
903 dump_core_p = 0;
904 else
905 {
906 /* Default (yes/batch case) is to dump core. This leaves a GDB
907 `dropping' so that it is easier to see that something went
908 wrong in GDB. */
909 dump_core_p = query (_("%s\nCreate a core file of GDB? "), reason);
910 }
911 }
912 else if (problem->should_dump_core == internal_problem_yes)
913 dump_core_p = can_dump_core (reason);
914 else if (problem->should_dump_core == internal_problem_no)
915 dump_core_p = 0;
916 else
917 internal_error (__FILE__, __LINE__, _("bad switch"));
918
919 if (quit_p)
920 {
921 if (dump_core_p)
922 dump_core ();
923 else
924 exit (1);
925 }
926 else
927 {
928 if (dump_core_p)
929 {
930 #ifdef HAVE_WORKING_FORK
931 if (fork () == 0)
932 dump_core ();
933 #endif
934 }
935 }
936
937 dejavu = 0;
938 }
939
940 static struct internal_problem internal_error_problem = {
941 "internal-error", internal_problem_ask, internal_problem_ask
942 };
943
944 void
945 internal_verror (const char *file, int line, const char *fmt, va_list ap)
946 {
947 internal_vproblem (&internal_error_problem, file, line, fmt, ap);
948 deprecated_throw_reason (RETURN_ERROR);
949 }
950
951 void
952 internal_error (const char *file, int line, const char *string, ...)
953 {
954 va_list ap;
955
956 va_start (ap, string);
957 internal_verror (file, line, string, ap);
958 va_end (ap);
959 }
960
961 static struct internal_problem internal_warning_problem = {
962 "internal-warning", internal_problem_ask, internal_problem_ask
963 };
964
965 void
966 internal_vwarning (const char *file, int line, const char *fmt, va_list ap)
967 {
968 internal_vproblem (&internal_warning_problem, file, line, fmt, ap);
969 }
970
971 void
972 internal_warning (const char *file, int line, const char *string, ...)
973 {
974 va_list ap;
975
976 va_start (ap, string);
977 internal_vwarning (file, line, string, ap);
978 va_end (ap);
979 }
980
981 /* Dummy functions to keep add_prefix_cmd happy. */
982
983 static void
984 set_internal_problem_cmd (char *args, int from_tty)
985 {
986 }
987
988 static void
989 show_internal_problem_cmd (char *args, int from_tty)
990 {
991 }
992
993 /* When GDB reports an internal problem (error or warning) it gives
994 the user the opportunity to quit GDB and/or create a core file of
995 the current debug session. This function registers a few commands
996 that make it possible to specify that GDB should always or never
997 quit or create a core file, without asking. The commands look
998 like:
999
1000 maint set PROBLEM-NAME quit ask|yes|no
1001 maint show PROBLEM-NAME quit
1002 maint set PROBLEM-NAME corefile ask|yes|no
1003 maint show PROBLEM-NAME corefile
1004
1005 Where PROBLEM-NAME is currently "internal-error" or
1006 "internal-warning". */
1007
1008 static void
1009 add_internal_problem_command (struct internal_problem *problem)
1010 {
1011 struct cmd_list_element **set_cmd_list;
1012 struct cmd_list_element **show_cmd_list;
1013 char *set_doc;
1014 char *show_doc;
1015
1016 set_cmd_list = xmalloc (sizeof (*set_cmd_list));
1017 show_cmd_list = xmalloc (sizeof (*set_cmd_list));
1018 *set_cmd_list = NULL;
1019 *show_cmd_list = NULL;
1020
1021 set_doc = xstrprintf (_("Configure what GDB does when %s is detected."),
1022 problem->name);
1023
1024 show_doc = xstrprintf (_("Show what GDB does when %s is detected."),
1025 problem->name);
1026
1027 add_prefix_cmd ((char*) problem->name,
1028 class_maintenance, set_internal_problem_cmd, set_doc,
1029 set_cmd_list,
1030 concat ("maintenance set ", problem->name, " ",
1031 (char *) NULL),
1032 0/*allow-unknown*/, &maintenance_set_cmdlist);
1033
1034 add_prefix_cmd ((char*) problem->name,
1035 class_maintenance, show_internal_problem_cmd, show_doc,
1036 show_cmd_list,
1037 concat ("maintenance show ", problem->name, " ",
1038 (char *) NULL),
1039 0/*allow-unknown*/, &maintenance_show_cmdlist);
1040
1041 set_doc = xstrprintf (_("Set whether GDB should quit "
1042 "when an %s is detected"),
1043 problem->name);
1044 show_doc = xstrprintf (_("Show whether GDB will quit "
1045 "when an %s is detected"),
1046 problem->name);
1047 add_setshow_enum_cmd ("quit", class_maintenance,
1048 internal_problem_modes,
1049 &problem->should_quit,
1050 set_doc,
1051 show_doc,
1052 NULL, /* help_doc */
1053 NULL, /* setfunc */
1054 NULL, /* showfunc */
1055 set_cmd_list,
1056 show_cmd_list);
1057
1058 xfree (set_doc);
1059 xfree (show_doc);
1060
1061 set_doc = xstrprintf (_("Set whether GDB should create a core "
1062 "file of GDB when %s is detected"),
1063 problem->name);
1064 show_doc = xstrprintf (_("Show whether GDB will create a core "
1065 "file of GDB when %s is detected"),
1066 problem->name);
1067 add_setshow_enum_cmd ("corefile", class_maintenance,
1068 internal_problem_modes,
1069 &problem->should_dump_core,
1070 set_doc,
1071 show_doc,
1072 NULL, /* help_doc */
1073 NULL, /* setfunc */
1074 NULL, /* showfunc */
1075 set_cmd_list,
1076 show_cmd_list);
1077
1078 xfree (set_doc);
1079 xfree (show_doc);
1080 }
1081
1082 /* Print the system error message for errno, and also mention STRING
1083 as the file name for which the error was encountered.
1084 Then return to command level. */
1085
1086 void
1087 perror_with_name (const char *string)
1088 {
1089 char *err;
1090 char *combined;
1091
1092 err = safe_strerror (errno);
1093 combined = (char *) alloca (strlen (err) + strlen (string) + 3);
1094 strcpy (combined, string);
1095 strcat (combined, ": ");
1096 strcat (combined, err);
1097
1098 /* I understand setting these is a matter of taste. Still, some people
1099 may clear errno but not know about bfd_error. Doing this here is not
1100 unreasonable. */
1101 bfd_set_error (bfd_error_no_error);
1102 errno = 0;
1103
1104 error (_("%s."), combined);
1105 }
1106
1107 /* Print the system error message for ERRCODE, and also mention STRING
1108 as the file name for which the error was encountered. */
1109
1110 void
1111 print_sys_errmsg (const char *string, int errcode)
1112 {
1113 char *err;
1114 char *combined;
1115
1116 err = safe_strerror (errcode);
1117 combined = (char *) alloca (strlen (err) + strlen (string) + 3);
1118 strcpy (combined, string);
1119 strcat (combined, ": ");
1120 strcat (combined, err);
1121
1122 /* We want anything which was printed on stdout to come out first, before
1123 this message. */
1124 gdb_flush (gdb_stdout);
1125 fprintf_unfiltered (gdb_stderr, "%s.\n", combined);
1126 }
1127
1128 /* Control C eventually causes this to be called, at a convenient time. */
1129
1130 void
1131 quit (void)
1132 {
1133 #ifdef __MSDOS__
1134 /* No steenking SIGINT will ever be coming our way when the
1135 program is resumed. Don't lie. */
1136 fatal ("Quit");
1137 #else
1138 if (job_control
1139 /* If there is no terminal switching for this target, then we can't
1140 possibly get screwed by the lack of job control. */
1141 || current_target.to_terminal_ours == NULL)
1142 fatal ("Quit");
1143 else
1144 fatal ("Quit (expect signal SIGINT when the program is resumed)");
1145 #endif
1146 }
1147
1148 \f
1149 /* Called when a memory allocation fails, with the number of bytes of
1150 memory requested in SIZE. */
1151
1152 void
1153 malloc_failure (long size)
1154 {
1155 if (size > 0)
1156 {
1157 internal_error (__FILE__, __LINE__,
1158 _("virtual memory exhausted: can't allocate %ld bytes."),
1159 size);
1160 }
1161 else
1162 {
1163 internal_error (__FILE__, __LINE__, _("virtual memory exhausted."));
1164 }
1165 }
1166
1167 /* My replacement for the read system call.
1168 Used like `read' but keeps going if `read' returns too soon. */
1169
1170 int
1171 myread (int desc, char *addr, int len)
1172 {
1173 int val;
1174 int orglen = len;
1175
1176 while (len > 0)
1177 {
1178 val = read (desc, addr, len);
1179 if (val < 0)
1180 return val;
1181 if (val == 0)
1182 return orglen - len;
1183 len -= val;
1184 addr += val;
1185 }
1186 return orglen;
1187 }
1188
1189 /* Make a copy of the string at PTR with SIZE characters
1190 (and add a null character at the end in the copy).
1191 Uses malloc to get the space. Returns the address of the copy. */
1192
1193 char *
1194 savestring (const char *ptr, size_t size)
1195 {
1196 char *p = (char *) xmalloc (size + 1);
1197
1198 memcpy (p, ptr, size);
1199 p[size] = 0;
1200 return p;
1201 }
1202
1203 void
1204 print_spaces (int n, struct ui_file *file)
1205 {
1206 fputs_unfiltered (n_spaces (n), file);
1207 }
1208
1209 /* Print a host address. */
1210
1211 void
1212 gdb_print_host_address (const void *addr, struct ui_file *stream)
1213 {
1214 fprintf_filtered (stream, "%s", host_address_to_string (addr));
1215 }
1216 \f
1217
1218 /* A cleanup function that calls regfree. */
1219
1220 static void
1221 do_regfree_cleanup (void *r)
1222 {
1223 regfree (r);
1224 }
1225
1226 /* Create a new cleanup that frees the compiled regular expression R. */
1227
1228 struct cleanup *
1229 make_regfree_cleanup (regex_t *r)
1230 {
1231 return make_cleanup (do_regfree_cleanup, r);
1232 }
1233
1234 /* Return an xmalloc'd error message resulting from a regular
1235 expression compilation failure. */
1236
1237 char *
1238 get_regcomp_error (int code, regex_t *rx)
1239 {
1240 size_t length = regerror (code, rx, NULL, 0);
1241 char *result = xmalloc (length);
1242
1243 regerror (code, rx, result, length);
1244 return result;
1245 }
1246
1247 \f
1248
1249 /* This function supports the query, nquery, and yquery functions.
1250 Ask user a y-or-n question and return 0 if answer is no, 1 if
1251 answer is yes, or default the answer to the specified default
1252 (for yquery or nquery). DEFCHAR may be 'y' or 'n' to provide a
1253 default answer, or '\0' for no default.
1254 CTLSTR is the control string and should end in "? ". It should
1255 not say how to answer, because we do that.
1256 ARGS are the arguments passed along with the CTLSTR argument to
1257 printf. */
1258
1259 static int ATTRIBUTE_PRINTF (1, 0)
1260 defaulted_query (const char *ctlstr, const char defchar, va_list args)
1261 {
1262 int answer;
1263 int ans2;
1264 int retval;
1265 int def_value;
1266 char def_answer, not_def_answer;
1267 char *y_string, *n_string, *question;
1268 /* Used to add duration we waited for user to respond to
1269 prompt_for_continue_wait_time. */
1270 struct timeval prompt_started, prompt_ended, prompt_delta;
1271
1272 /* Set up according to which answer is the default. */
1273 if (defchar == '\0')
1274 {
1275 def_value = 1;
1276 def_answer = 'Y';
1277 not_def_answer = 'N';
1278 y_string = "y";
1279 n_string = "n";
1280 }
1281 else if (defchar == 'y')
1282 {
1283 def_value = 1;
1284 def_answer = 'Y';
1285 not_def_answer = 'N';
1286 y_string = "[y]";
1287 n_string = "n";
1288 }
1289 else
1290 {
1291 def_value = 0;
1292 def_answer = 'N';
1293 not_def_answer = 'Y';
1294 y_string = "y";
1295 n_string = "[n]";
1296 }
1297
1298 /* Automatically answer the default value if the user did not want
1299 prompts or the command was issued with the server prefix. */
1300 if (!confirm || server_command)
1301 return def_value;
1302
1303 /* If input isn't coming from the user directly, just say what
1304 question we're asking, and then answer the default automatically. This
1305 way, important error messages don't get lost when talking to GDB
1306 over a pipe. */
1307 if (! input_from_terminal_p ())
1308 {
1309 wrap_here ("");
1310 vfprintf_filtered (gdb_stdout, ctlstr, args);
1311
1312 printf_filtered (_("(%s or %s) [answered %c; "
1313 "input not from terminal]\n"),
1314 y_string, n_string, def_answer);
1315 gdb_flush (gdb_stdout);
1316
1317 return def_value;
1318 }
1319
1320 if (deprecated_query_hook)
1321 {
1322 return deprecated_query_hook (ctlstr, args);
1323 }
1324
1325 /* Format the question outside of the loop, to avoid reusing args. */
1326 question = xstrvprintf (ctlstr, args);
1327
1328 /* Used for calculating time spend waiting for user. */
1329 gettimeofday (&prompt_started, NULL);
1330
1331 while (1)
1332 {
1333 wrap_here (""); /* Flush any buffered output. */
1334 gdb_flush (gdb_stdout);
1335
1336 if (annotation_level > 1)
1337 printf_filtered (("\n\032\032pre-query\n"));
1338
1339 fputs_filtered (question, gdb_stdout);
1340 printf_filtered (_("(%s or %s) "), y_string, n_string);
1341
1342 if (annotation_level > 1)
1343 printf_filtered (("\n\032\032query\n"));
1344
1345 wrap_here ("");
1346 gdb_flush (gdb_stdout);
1347
1348 answer = fgetc (stdin);
1349
1350 /* We expect fgetc to block until a character is read. But
1351 this may not be the case if the terminal was opened with
1352 the NONBLOCK flag. In that case, if there is nothing to
1353 read on stdin, fgetc returns EOF, but also sets the error
1354 condition flag on stdin and errno to EAGAIN. With a true
1355 EOF, stdin's error condition flag is not set.
1356
1357 A situation where this behavior was observed is a pseudo
1358 terminal on AIX. */
1359 while (answer == EOF && ferror (stdin) && errno == EAGAIN)
1360 {
1361 /* Not a real EOF. Wait a little while and try again until
1362 we read something. */
1363 clearerr (stdin);
1364 gdb_usleep (10000);
1365 answer = fgetc (stdin);
1366 }
1367
1368 clearerr (stdin); /* in case of C-d */
1369 if (answer == EOF) /* C-d */
1370 {
1371 printf_filtered ("EOF [assumed %c]\n", def_answer);
1372 retval = def_value;
1373 break;
1374 }
1375 /* Eat rest of input line, to EOF or newline. */
1376 if (answer != '\n')
1377 do
1378 {
1379 ans2 = fgetc (stdin);
1380 clearerr (stdin);
1381 }
1382 while (ans2 != EOF && ans2 != '\n' && ans2 != '\r');
1383
1384 if (answer >= 'a')
1385 answer -= 040;
1386 /* Check answer. For the non-default, the user must specify
1387 the non-default explicitly. */
1388 if (answer == not_def_answer)
1389 {
1390 retval = !def_value;
1391 break;
1392 }
1393 /* Otherwise, if a default was specified, the user may either
1394 specify the required input or have it default by entering
1395 nothing. */
1396 if (answer == def_answer
1397 || (defchar != '\0' &&
1398 (answer == '\n' || answer == '\r' || answer == EOF)))
1399 {
1400 retval = def_value;
1401 break;
1402 }
1403 /* Invalid entries are not defaulted and require another selection. */
1404 printf_filtered (_("Please answer %s or %s.\n"),
1405 y_string, n_string);
1406 }
1407
1408 /* Add time spend in this routine to prompt_for_continue_wait_time. */
1409 gettimeofday (&prompt_ended, NULL);
1410 timeval_sub (&prompt_delta, &prompt_ended, &prompt_started);
1411 timeval_add (&prompt_for_continue_wait_time,
1412 &prompt_for_continue_wait_time, &prompt_delta);
1413
1414 xfree (question);
1415 if (annotation_level > 1)
1416 printf_filtered (("\n\032\032post-query\n"));
1417 return retval;
1418 }
1419 \f
1420
1421 /* Ask user a y-or-n question and return 0 if answer is no, 1 if
1422 answer is yes, or 0 if answer is defaulted.
1423 Takes three args which are given to printf to print the question.
1424 The first, a control string, should end in "? ".
1425 It should not say how to answer, because we do that. */
1426
1427 int
1428 nquery (const char *ctlstr, ...)
1429 {
1430 va_list args;
1431 int ret;
1432
1433 va_start (args, ctlstr);
1434 ret = defaulted_query (ctlstr, 'n', args);
1435 va_end (args);
1436 return ret;
1437 }
1438
1439 /* Ask user a y-or-n question and return 0 if answer is no, 1 if
1440 answer is yes, or 1 if answer is defaulted.
1441 Takes three args which are given to printf to print the question.
1442 The first, a control string, should end in "? ".
1443 It should not say how to answer, because we do that. */
1444
1445 int
1446 yquery (const char *ctlstr, ...)
1447 {
1448 va_list args;
1449 int ret;
1450
1451 va_start (args, ctlstr);
1452 ret = defaulted_query (ctlstr, 'y', args);
1453 va_end (args);
1454 return ret;
1455 }
1456
1457 /* Ask user a y-or-n question and return 1 iff answer is yes.
1458 Takes three args which are given to printf to print the question.
1459 The first, a control string, should end in "? ".
1460 It should not say how to answer, because we do that. */
1461
1462 int
1463 query (const char *ctlstr, ...)
1464 {
1465 va_list args;
1466 int ret;
1467
1468 va_start (args, ctlstr);
1469 ret = defaulted_query (ctlstr, '\0', args);
1470 va_end (args);
1471 return ret;
1472 }
1473
1474 /* A helper for parse_escape that converts a host character to a
1475 target character. C is the host character. If conversion is
1476 possible, then the target character is stored in *TARGET_C and the
1477 function returns 1. Otherwise, the function returns 0. */
1478
1479 static int
1480 host_char_to_target (struct gdbarch *gdbarch, int c, int *target_c)
1481 {
1482 struct obstack host_data;
1483 char the_char = c;
1484 struct cleanup *cleanups;
1485 int result = 0;
1486
1487 obstack_init (&host_data);
1488 cleanups = make_cleanup_obstack_free (&host_data);
1489
1490 convert_between_encodings (target_charset (gdbarch), host_charset (),
1491 &the_char, 1, 1, &host_data, translit_none);
1492
1493 if (obstack_object_size (&host_data) == 1)
1494 {
1495 result = 1;
1496 *target_c = *(char *) obstack_base (&host_data);
1497 }
1498
1499 do_cleanups (cleanups);
1500 return result;
1501 }
1502
1503 /* Parse a C escape sequence. STRING_PTR points to a variable
1504 containing a pointer to the string to parse. That pointer
1505 should point to the character after the \. That pointer
1506 is updated past the characters we use. The value of the
1507 escape sequence is returned.
1508
1509 A negative value means the sequence \ newline was seen,
1510 which is supposed to be equivalent to nothing at all.
1511
1512 If \ is followed by a null character, we return a negative
1513 value and leave the string pointer pointing at the null character.
1514
1515 If \ is followed by 000, we return 0 and leave the string pointer
1516 after the zeros. A value of 0 does not mean end of string. */
1517
1518 int
1519 parse_escape (struct gdbarch *gdbarch, char **string_ptr)
1520 {
1521 int target_char = -2; /* Initialize to avoid GCC warnings. */
1522 int c = *(*string_ptr)++;
1523
1524 switch (c)
1525 {
1526 case '\n':
1527 return -2;
1528 case 0:
1529 (*string_ptr)--;
1530 return 0;
1531
1532 case '0':
1533 case '1':
1534 case '2':
1535 case '3':
1536 case '4':
1537 case '5':
1538 case '6':
1539 case '7':
1540 {
1541 int i = host_hex_value (c);
1542 int count = 0;
1543 while (++count < 3)
1544 {
1545 c = (**string_ptr);
1546 if (isdigit (c) && c != '8' && c != '9')
1547 {
1548 (*string_ptr)++;
1549 i *= 8;
1550 i += host_hex_value (c);
1551 }
1552 else
1553 {
1554 break;
1555 }
1556 }
1557 return i;
1558 }
1559
1560 case 'a':
1561 c = '\a';
1562 break;
1563 case 'b':
1564 c = '\b';
1565 break;
1566 case 'f':
1567 c = '\f';
1568 break;
1569 case 'n':
1570 c = '\n';
1571 break;
1572 case 'r':
1573 c = '\r';
1574 break;
1575 case 't':
1576 c = '\t';
1577 break;
1578 case 'v':
1579 c = '\v';
1580 break;
1581
1582 default:
1583 break;
1584 }
1585
1586 if (!host_char_to_target (gdbarch, c, &target_char))
1587 error (_("The escape sequence `\\%c' is equivalent to plain `%c',"
1588 " which has no equivalent\nin the `%s' character set."),
1589 c, c, target_charset (gdbarch));
1590 return target_char;
1591 }
1592 \f
1593 /* Print the character C on STREAM as part of the contents of a literal
1594 string whose delimiter is QUOTER. Note that this routine should only
1595 be call for printing things which are independent of the language
1596 of the program being debugged. */
1597
1598 static void
1599 printchar (int c, void (*do_fputs) (const char *, struct ui_file *),
1600 void (*do_fprintf) (struct ui_file *, const char *, ...)
1601 ATTRIBUTE_FPTR_PRINTF_2, struct ui_file *stream, int quoter)
1602 {
1603 c &= 0xFF; /* Avoid sign bit follies */
1604
1605 if (c < 0x20 || /* Low control chars */
1606 (c >= 0x7F && c < 0xA0) || /* DEL, High controls */
1607 (sevenbit_strings && c >= 0x80))
1608 { /* high order bit set */
1609 switch (c)
1610 {
1611 case '\n':
1612 do_fputs ("\\n", stream);
1613 break;
1614 case '\b':
1615 do_fputs ("\\b", stream);
1616 break;
1617 case '\t':
1618 do_fputs ("\\t", stream);
1619 break;
1620 case '\f':
1621 do_fputs ("\\f", stream);
1622 break;
1623 case '\r':
1624 do_fputs ("\\r", stream);
1625 break;
1626 case '\033':
1627 do_fputs ("\\e", stream);
1628 break;
1629 case '\007':
1630 do_fputs ("\\a", stream);
1631 break;
1632 default:
1633 do_fprintf (stream, "\\%.3o", (unsigned int) c);
1634 break;
1635 }
1636 }
1637 else
1638 {
1639 if (c == '\\' || c == quoter)
1640 do_fputs ("\\", stream);
1641 do_fprintf (stream, "%c", c);
1642 }
1643 }
1644
1645 /* Print the character C on STREAM as part of the contents of a
1646 literal string whose delimiter is QUOTER. Note that these routines
1647 should only be call for printing things which are independent of
1648 the language of the program being debugged. */
1649
1650 void
1651 fputstr_filtered (const char *str, int quoter, struct ui_file *stream)
1652 {
1653 while (*str)
1654 printchar (*str++, fputs_filtered, fprintf_filtered, stream, quoter);
1655 }
1656
1657 void
1658 fputstr_unfiltered (const char *str, int quoter, struct ui_file *stream)
1659 {
1660 while (*str)
1661 printchar (*str++, fputs_unfiltered, fprintf_unfiltered, stream, quoter);
1662 }
1663
1664 void
1665 fputstrn_filtered (const char *str, int n, int quoter,
1666 struct ui_file *stream)
1667 {
1668 int i;
1669
1670 for (i = 0; i < n; i++)
1671 printchar (str[i], fputs_filtered, fprintf_filtered, stream, quoter);
1672 }
1673
1674 void
1675 fputstrn_unfiltered (const char *str, int n, int quoter,
1676 struct ui_file *stream)
1677 {
1678 int i;
1679
1680 for (i = 0; i < n; i++)
1681 printchar (str[i], fputs_unfiltered, fprintf_unfiltered, stream, quoter);
1682 }
1683 \f
1684
1685 /* Number of lines per page or UINT_MAX if paging is disabled. */
1686 static unsigned int lines_per_page;
1687 static void
1688 show_lines_per_page (struct ui_file *file, int from_tty,
1689 struct cmd_list_element *c, const char *value)
1690 {
1691 fprintf_filtered (file,
1692 _("Number of lines gdb thinks are in a page is %s.\n"),
1693 value);
1694 }
1695
1696 /* Number of chars per line or UINT_MAX if line folding is disabled. */
1697 static unsigned int chars_per_line;
1698 static void
1699 show_chars_per_line (struct ui_file *file, int from_tty,
1700 struct cmd_list_element *c, const char *value)
1701 {
1702 fprintf_filtered (file,
1703 _("Number of characters gdb thinks "
1704 "are in a line is %s.\n"),
1705 value);
1706 }
1707
1708 /* Current count of lines printed on this page, chars on this line. */
1709 static unsigned int lines_printed, chars_printed;
1710
1711 /* Buffer and start column of buffered text, for doing smarter word-
1712 wrapping. When someone calls wrap_here(), we start buffering output
1713 that comes through fputs_filtered(). If we see a newline, we just
1714 spit it out and forget about the wrap_here(). If we see another
1715 wrap_here(), we spit it out and remember the newer one. If we see
1716 the end of the line, we spit out a newline, the indent, and then
1717 the buffered output. */
1718
1719 /* Malloc'd buffer with chars_per_line+2 bytes. Contains characters which
1720 are waiting to be output (they have already been counted in chars_printed).
1721 When wrap_buffer[0] is null, the buffer is empty. */
1722 static char *wrap_buffer;
1723
1724 /* Pointer in wrap_buffer to the next character to fill. */
1725 static char *wrap_pointer;
1726
1727 /* String to indent by if the wrap occurs. Must not be NULL if wrap_column
1728 is non-zero. */
1729 static char *wrap_indent;
1730
1731 /* Column number on the screen where wrap_buffer begins, or 0 if wrapping
1732 is not in effect. */
1733 static int wrap_column;
1734 \f
1735
1736 /* Inialize the number of lines per page and chars per line. */
1737
1738 void
1739 init_page_info (void)
1740 {
1741 if (batch_flag)
1742 {
1743 lines_per_page = UINT_MAX;
1744 chars_per_line = UINT_MAX;
1745 }
1746 else
1747 #if defined(TUI)
1748 if (!tui_get_command_dimension (&chars_per_line, &lines_per_page))
1749 #endif
1750 {
1751 int rows, cols;
1752
1753 #if defined(__GO32__)
1754 rows = ScreenRows ();
1755 cols = ScreenCols ();
1756 lines_per_page = rows;
1757 chars_per_line = cols;
1758 #else
1759 /* Make sure Readline has initialized its terminal settings. */
1760 rl_reset_terminal (NULL);
1761
1762 /* Get the screen size from Readline. */
1763 rl_get_screen_size (&rows, &cols);
1764 lines_per_page = rows;
1765 chars_per_line = cols;
1766
1767 /* Readline should have fetched the termcap entry for us. */
1768 if (tgetnum ("li") < 0 || getenv ("EMACS"))
1769 {
1770 /* The number of lines per page is not mentioned in the
1771 terminal description. This probably means that paging is
1772 not useful (e.g. emacs shell window), so disable paging. */
1773 lines_per_page = UINT_MAX;
1774 }
1775
1776 /* If the output is not a terminal, don't paginate it. */
1777 if (!ui_file_isatty (gdb_stdout))
1778 lines_per_page = UINT_MAX;
1779 #endif
1780 }
1781
1782 set_screen_size ();
1783 set_width ();
1784 }
1785
1786 /* Helper for make_cleanup_restore_page_info. */
1787
1788 static void
1789 do_restore_page_info_cleanup (void *arg)
1790 {
1791 set_screen_size ();
1792 set_width ();
1793 }
1794
1795 /* Provide cleanup for restoring the terminal size. */
1796
1797 struct cleanup *
1798 make_cleanup_restore_page_info (void)
1799 {
1800 struct cleanup *back_to;
1801
1802 back_to = make_cleanup (do_restore_page_info_cleanup, NULL);
1803 make_cleanup_restore_uinteger (&lines_per_page);
1804 make_cleanup_restore_uinteger (&chars_per_line);
1805
1806 return back_to;
1807 }
1808
1809 /* Temporarily set BATCH_FLAG and the associated unlimited terminal size.
1810 Provide cleanup for restoring the original state. */
1811
1812 struct cleanup *
1813 set_batch_flag_and_make_cleanup_restore_page_info (void)
1814 {
1815 struct cleanup *back_to = make_cleanup_restore_page_info ();
1816
1817 make_cleanup_restore_integer (&batch_flag);
1818 batch_flag = 1;
1819 init_page_info ();
1820
1821 return back_to;
1822 }
1823
1824 /* Set the screen size based on LINES_PER_PAGE and CHARS_PER_LINE. */
1825
1826 static void
1827 set_screen_size (void)
1828 {
1829 int rows = lines_per_page;
1830 int cols = chars_per_line;
1831
1832 if (rows <= 0)
1833 rows = INT_MAX;
1834
1835 if (cols <= 0)
1836 cols = INT_MAX;
1837
1838 /* Update Readline's idea of the terminal size. */
1839 rl_set_screen_size (rows, cols);
1840 }
1841
1842 /* Reinitialize WRAP_BUFFER according to the current value of
1843 CHARS_PER_LINE. */
1844
1845 static void
1846 set_width (void)
1847 {
1848 if (chars_per_line == 0)
1849 init_page_info ();
1850
1851 if (!wrap_buffer)
1852 {
1853 wrap_buffer = (char *) xmalloc (chars_per_line + 2);
1854 wrap_buffer[0] = '\0';
1855 }
1856 else
1857 wrap_buffer = (char *) xrealloc (wrap_buffer, chars_per_line + 2);
1858 wrap_pointer = wrap_buffer; /* Start it at the beginning. */
1859 }
1860
1861 static void
1862 set_width_command (char *args, int from_tty, struct cmd_list_element *c)
1863 {
1864 set_screen_size ();
1865 set_width ();
1866 }
1867
1868 static void
1869 set_height_command (char *args, int from_tty, struct cmd_list_element *c)
1870 {
1871 set_screen_size ();
1872 }
1873
1874 /* Wait, so the user can read what's on the screen. Prompt the user
1875 to continue by pressing RETURN. */
1876
1877 static void
1878 prompt_for_continue (void)
1879 {
1880 char *ignore;
1881 char cont_prompt[120];
1882 /* Used to add duration we waited for user to respond to
1883 prompt_for_continue_wait_time. */
1884 struct timeval prompt_started, prompt_ended, prompt_delta;
1885
1886 gettimeofday (&prompt_started, NULL);
1887
1888 if (annotation_level > 1)
1889 printf_unfiltered (("\n\032\032pre-prompt-for-continue\n"));
1890
1891 strcpy (cont_prompt,
1892 "---Type <return> to continue, or q <return> to quit---");
1893 if (annotation_level > 1)
1894 strcat (cont_prompt, "\n\032\032prompt-for-continue\n");
1895
1896 /* We must do this *before* we call gdb_readline, else it will eventually
1897 call us -- thinking that we're trying to print beyond the end of the
1898 screen. */
1899 reinitialize_more_filter ();
1900
1901 immediate_quit++;
1902 QUIT;
1903 /* On a real operating system, the user can quit with SIGINT.
1904 But not on GO32.
1905
1906 'q' is provided on all systems so users don't have to change habits
1907 from system to system, and because telling them what to do in
1908 the prompt is more user-friendly than expecting them to think of
1909 SIGINT. */
1910 /* Call readline, not gdb_readline, because GO32 readline handles control-C
1911 whereas control-C to gdb_readline will cause the user to get dumped
1912 out to DOS. */
1913 ignore = gdb_readline_wrapper (cont_prompt);
1914
1915 /* Add time spend in this routine to prompt_for_continue_wait_time. */
1916 gettimeofday (&prompt_ended, NULL);
1917 timeval_sub (&prompt_delta, &prompt_ended, &prompt_started);
1918 timeval_add (&prompt_for_continue_wait_time,
1919 &prompt_for_continue_wait_time, &prompt_delta);
1920
1921 if (annotation_level > 1)
1922 printf_unfiltered (("\n\032\032post-prompt-for-continue\n"));
1923
1924 if (ignore)
1925 {
1926 char *p = ignore;
1927
1928 while (*p == ' ' || *p == '\t')
1929 ++p;
1930 if (p[0] == 'q')
1931 quit ();
1932 xfree (ignore);
1933 }
1934 immediate_quit--;
1935
1936 /* Now we have to do this again, so that GDB will know that it doesn't
1937 need to save the ---Type <return>--- line at the top of the screen. */
1938 reinitialize_more_filter ();
1939
1940 dont_repeat (); /* Forget prev cmd -- CR won't repeat it. */
1941 }
1942
1943 /* Reinitialize filter; ie. tell it to reset to original values. */
1944
1945 void
1946 reinitialize_more_filter (void)
1947 {
1948 lines_printed = 0;
1949 chars_printed = 0;
1950 }
1951
1952 /* Indicate that if the next sequence of characters overflows the line,
1953 a newline should be inserted here rather than when it hits the end.
1954 If INDENT is non-null, it is a string to be printed to indent the
1955 wrapped part on the next line. INDENT must remain accessible until
1956 the next call to wrap_here() or until a newline is printed through
1957 fputs_filtered().
1958
1959 If the line is already overfull, we immediately print a newline and
1960 the indentation, and disable further wrapping.
1961
1962 If we don't know the width of lines, but we know the page height,
1963 we must not wrap words, but should still keep track of newlines
1964 that were explicitly printed.
1965
1966 INDENT should not contain tabs, as that will mess up the char count
1967 on the next line. FIXME.
1968
1969 This routine is guaranteed to force out any output which has been
1970 squirreled away in the wrap_buffer, so wrap_here ((char *)0) can be
1971 used to force out output from the wrap_buffer. */
1972
1973 void
1974 wrap_here (char *indent)
1975 {
1976 /* This should have been allocated, but be paranoid anyway. */
1977 if (!wrap_buffer)
1978 internal_error (__FILE__, __LINE__,
1979 _("failed internal consistency check"));
1980
1981 if (wrap_buffer[0])
1982 {
1983 *wrap_pointer = '\0';
1984 fputs_unfiltered (wrap_buffer, gdb_stdout);
1985 }
1986 wrap_pointer = wrap_buffer;
1987 wrap_buffer[0] = '\0';
1988 if (chars_per_line == UINT_MAX) /* No line overflow checking. */
1989 {
1990 wrap_column = 0;
1991 }
1992 else if (chars_printed >= chars_per_line)
1993 {
1994 puts_filtered ("\n");
1995 if (indent != NULL)
1996 puts_filtered (indent);
1997 wrap_column = 0;
1998 }
1999 else
2000 {
2001 wrap_column = chars_printed;
2002 if (indent == NULL)
2003 wrap_indent = "";
2004 else
2005 wrap_indent = indent;
2006 }
2007 }
2008
2009 /* Print input string to gdb_stdout, filtered, with wrap,
2010 arranging strings in columns of n chars. String can be
2011 right or left justified in the column. Never prints
2012 trailing spaces. String should never be longer than
2013 width. FIXME: this could be useful for the EXAMINE
2014 command, which currently doesn't tabulate very well. */
2015
2016 void
2017 puts_filtered_tabular (char *string, int width, int right)
2018 {
2019 int spaces = 0;
2020 int stringlen;
2021 char *spacebuf;
2022
2023 gdb_assert (chars_per_line > 0);
2024 if (chars_per_line == UINT_MAX)
2025 {
2026 fputs_filtered (string, gdb_stdout);
2027 fputs_filtered ("\n", gdb_stdout);
2028 return;
2029 }
2030
2031 if (((chars_printed - 1) / width + 2) * width >= chars_per_line)
2032 fputs_filtered ("\n", gdb_stdout);
2033
2034 if (width >= chars_per_line)
2035 width = chars_per_line - 1;
2036
2037 stringlen = strlen (string);
2038
2039 if (chars_printed > 0)
2040 spaces = width - (chars_printed - 1) % width - 1;
2041 if (right)
2042 spaces += width - stringlen;
2043
2044 spacebuf = alloca (spaces + 1);
2045 spacebuf[spaces] = '\0';
2046 while (spaces--)
2047 spacebuf[spaces] = ' ';
2048
2049 fputs_filtered (spacebuf, gdb_stdout);
2050 fputs_filtered (string, gdb_stdout);
2051 }
2052
2053
2054 /* Ensure that whatever gets printed next, using the filtered output
2055 commands, starts at the beginning of the line. I.e. if there is
2056 any pending output for the current line, flush it and start a new
2057 line. Otherwise do nothing. */
2058
2059 void
2060 begin_line (void)
2061 {
2062 if (chars_printed > 0)
2063 {
2064 puts_filtered ("\n");
2065 }
2066 }
2067
2068
2069 /* Like fputs but if FILTER is true, pause after every screenful.
2070
2071 Regardless of FILTER can wrap at points other than the final
2072 character of a line.
2073
2074 Unlike fputs, fputs_maybe_filtered does not return a value.
2075 It is OK for LINEBUFFER to be NULL, in which case just don't print
2076 anything.
2077
2078 Note that a longjmp to top level may occur in this routine (only if
2079 FILTER is true) (since prompt_for_continue may do so) so this
2080 routine should not be called when cleanups are not in place. */
2081
2082 static void
2083 fputs_maybe_filtered (const char *linebuffer, struct ui_file *stream,
2084 int filter)
2085 {
2086 const char *lineptr;
2087
2088 if (linebuffer == 0)
2089 return;
2090
2091 /* Don't do any filtering if it is disabled. */
2092 if (stream != gdb_stdout
2093 || !pagination_enabled
2094 || batch_flag
2095 || (lines_per_page == UINT_MAX && chars_per_line == UINT_MAX)
2096 || top_level_interpreter () == NULL
2097 || ui_out_is_mi_like_p (interp_ui_out (top_level_interpreter ())))
2098 {
2099 fputs_unfiltered (linebuffer, stream);
2100 return;
2101 }
2102
2103 /* Go through and output each character. Show line extension
2104 when this is necessary; prompt user for new page when this is
2105 necessary. */
2106
2107 lineptr = linebuffer;
2108 while (*lineptr)
2109 {
2110 /* Possible new page. */
2111 if (filter && (lines_printed >= lines_per_page - 1))
2112 prompt_for_continue ();
2113
2114 while (*lineptr && *lineptr != '\n')
2115 {
2116 /* Print a single line. */
2117 if (*lineptr == '\t')
2118 {
2119 if (wrap_column)
2120 *wrap_pointer++ = '\t';
2121 else
2122 fputc_unfiltered ('\t', stream);
2123 /* Shifting right by 3 produces the number of tab stops
2124 we have already passed, and then adding one and
2125 shifting left 3 advances to the next tab stop. */
2126 chars_printed = ((chars_printed >> 3) + 1) << 3;
2127 lineptr++;
2128 }
2129 else
2130 {
2131 if (wrap_column)
2132 *wrap_pointer++ = *lineptr;
2133 else
2134 fputc_unfiltered (*lineptr, stream);
2135 chars_printed++;
2136 lineptr++;
2137 }
2138
2139 if (chars_printed >= chars_per_line)
2140 {
2141 unsigned int save_chars = chars_printed;
2142
2143 chars_printed = 0;
2144 lines_printed++;
2145 /* If we aren't actually wrapping, don't output newline --
2146 if chars_per_line is right, we probably just overflowed
2147 anyway; if it's wrong, let us keep going. */
2148 if (wrap_column)
2149 fputc_unfiltered ('\n', stream);
2150
2151 /* Possible new page. */
2152 if (lines_printed >= lines_per_page - 1)
2153 prompt_for_continue ();
2154
2155 /* Now output indentation and wrapped string. */
2156 if (wrap_column)
2157 {
2158 fputs_unfiltered (wrap_indent, stream);
2159 *wrap_pointer = '\0'; /* Null-terminate saved stuff, */
2160 fputs_unfiltered (wrap_buffer, stream); /* and eject it. */
2161 /* FIXME, this strlen is what prevents wrap_indent from
2162 containing tabs. However, if we recurse to print it
2163 and count its chars, we risk trouble if wrap_indent is
2164 longer than (the user settable) chars_per_line.
2165 Note also that this can set chars_printed > chars_per_line
2166 if we are printing a long string. */
2167 chars_printed = strlen (wrap_indent)
2168 + (save_chars - wrap_column);
2169 wrap_pointer = wrap_buffer; /* Reset buffer */
2170 wrap_buffer[0] = '\0';
2171 wrap_column = 0; /* And disable fancy wrap */
2172 }
2173 }
2174 }
2175
2176 if (*lineptr == '\n')
2177 {
2178 chars_printed = 0;
2179 wrap_here ((char *) 0); /* Spit out chars, cancel
2180 further wraps. */
2181 lines_printed++;
2182 fputc_unfiltered ('\n', stream);
2183 lineptr++;
2184 }
2185 }
2186 }
2187
2188 void
2189 fputs_filtered (const char *linebuffer, struct ui_file *stream)
2190 {
2191 fputs_maybe_filtered (linebuffer, stream, 1);
2192 }
2193
2194 int
2195 putchar_unfiltered (int c)
2196 {
2197 char buf = c;
2198
2199 ui_file_write (gdb_stdout, &buf, 1);
2200 return c;
2201 }
2202
2203 /* Write character C to gdb_stdout using GDB's paging mechanism and return C.
2204 May return nonlocally. */
2205
2206 int
2207 putchar_filtered (int c)
2208 {
2209 return fputc_filtered (c, gdb_stdout);
2210 }
2211
2212 int
2213 fputc_unfiltered (int c, struct ui_file *stream)
2214 {
2215 char buf = c;
2216
2217 ui_file_write (stream, &buf, 1);
2218 return c;
2219 }
2220
2221 int
2222 fputc_filtered (int c, struct ui_file *stream)
2223 {
2224 char buf[2];
2225
2226 buf[0] = c;
2227 buf[1] = 0;
2228 fputs_filtered (buf, stream);
2229 return c;
2230 }
2231
2232 /* puts_debug is like fputs_unfiltered, except it prints special
2233 characters in printable fashion. */
2234
2235 void
2236 puts_debug (char *prefix, char *string, char *suffix)
2237 {
2238 int ch;
2239
2240 /* Print prefix and suffix after each line. */
2241 static int new_line = 1;
2242 static int return_p = 0;
2243 static char *prev_prefix = "";
2244 static char *prev_suffix = "";
2245
2246 if (*string == '\n')
2247 return_p = 0;
2248
2249 /* If the prefix is changing, print the previous suffix, a new line,
2250 and the new prefix. */
2251 if ((return_p || (strcmp (prev_prefix, prefix) != 0)) && !new_line)
2252 {
2253 fputs_unfiltered (prev_suffix, gdb_stdlog);
2254 fputs_unfiltered ("\n", gdb_stdlog);
2255 fputs_unfiltered (prefix, gdb_stdlog);
2256 }
2257
2258 /* Print prefix if we printed a newline during the previous call. */
2259 if (new_line)
2260 {
2261 new_line = 0;
2262 fputs_unfiltered (prefix, gdb_stdlog);
2263 }
2264
2265 prev_prefix = prefix;
2266 prev_suffix = suffix;
2267
2268 /* Output characters in a printable format. */
2269 while ((ch = *string++) != '\0')
2270 {
2271 switch (ch)
2272 {
2273 default:
2274 if (isprint (ch))
2275 fputc_unfiltered (ch, gdb_stdlog);
2276
2277 else
2278 fprintf_unfiltered (gdb_stdlog, "\\x%02x", ch & 0xff);
2279 break;
2280
2281 case '\\':
2282 fputs_unfiltered ("\\\\", gdb_stdlog);
2283 break;
2284 case '\b':
2285 fputs_unfiltered ("\\b", gdb_stdlog);
2286 break;
2287 case '\f':
2288 fputs_unfiltered ("\\f", gdb_stdlog);
2289 break;
2290 case '\n':
2291 new_line = 1;
2292 fputs_unfiltered ("\\n", gdb_stdlog);
2293 break;
2294 case '\r':
2295 fputs_unfiltered ("\\r", gdb_stdlog);
2296 break;
2297 case '\t':
2298 fputs_unfiltered ("\\t", gdb_stdlog);
2299 break;
2300 case '\v':
2301 fputs_unfiltered ("\\v", gdb_stdlog);
2302 break;
2303 }
2304
2305 return_p = ch == '\r';
2306 }
2307
2308 /* Print suffix if we printed a newline. */
2309 if (new_line)
2310 {
2311 fputs_unfiltered (suffix, gdb_stdlog);
2312 fputs_unfiltered ("\n", gdb_stdlog);
2313 }
2314 }
2315
2316
2317 /* Print a variable number of ARGS using format FORMAT. If this
2318 information is going to put the amount written (since the last call
2319 to REINITIALIZE_MORE_FILTER or the last page break) over the page size,
2320 call prompt_for_continue to get the users permision to continue.
2321
2322 Unlike fprintf, this function does not return a value.
2323
2324 We implement three variants, vfprintf (takes a vararg list and stream),
2325 fprintf (takes a stream to write on), and printf (the usual).
2326
2327 Note also that a longjmp to top level may occur in this routine
2328 (since prompt_for_continue may do so) so this routine should not be
2329 called when cleanups are not in place. */
2330
2331 static void
2332 vfprintf_maybe_filtered (struct ui_file *stream, const char *format,
2333 va_list args, int filter)
2334 {
2335 char *linebuffer;
2336 struct cleanup *old_cleanups;
2337
2338 linebuffer = xstrvprintf (format, args);
2339 old_cleanups = make_cleanup (xfree, linebuffer);
2340 fputs_maybe_filtered (linebuffer, stream, filter);
2341 do_cleanups (old_cleanups);
2342 }
2343
2344
2345 void
2346 vfprintf_filtered (struct ui_file *stream, const char *format, va_list args)
2347 {
2348 vfprintf_maybe_filtered (stream, format, args, 1);
2349 }
2350
2351 void
2352 vfprintf_unfiltered (struct ui_file *stream, const char *format, va_list args)
2353 {
2354 char *linebuffer;
2355 struct cleanup *old_cleanups;
2356
2357 linebuffer = xstrvprintf (format, args);
2358 old_cleanups = make_cleanup (xfree, linebuffer);
2359 if (debug_timestamp && stream == gdb_stdlog)
2360 {
2361 struct timeval tm;
2362 char *timestamp;
2363 int len, need_nl;
2364
2365 gettimeofday (&tm, NULL);
2366
2367 len = strlen (linebuffer);
2368 need_nl = (len > 0 && linebuffer[len - 1] != '\n');
2369
2370 timestamp = xstrprintf ("%ld:%ld %s%s",
2371 (long) tm.tv_sec, (long) tm.tv_usec,
2372 linebuffer,
2373 need_nl ? "\n": "");
2374 make_cleanup (xfree, timestamp);
2375 fputs_unfiltered (timestamp, stream);
2376 }
2377 else
2378 fputs_unfiltered (linebuffer, stream);
2379 do_cleanups (old_cleanups);
2380 }
2381
2382 void
2383 vprintf_filtered (const char *format, va_list args)
2384 {
2385 vfprintf_maybe_filtered (gdb_stdout, format, args, 1);
2386 }
2387
2388 void
2389 vprintf_unfiltered (const char *format, va_list args)
2390 {
2391 vfprintf_unfiltered (gdb_stdout, format, args);
2392 }
2393
2394 void
2395 fprintf_filtered (struct ui_file *stream, const char *format, ...)
2396 {
2397 va_list args;
2398
2399 va_start (args, format);
2400 vfprintf_filtered (stream, format, args);
2401 va_end (args);
2402 }
2403
2404 void
2405 fprintf_unfiltered (struct ui_file *stream, const char *format, ...)
2406 {
2407 va_list args;
2408
2409 va_start (args, format);
2410 vfprintf_unfiltered (stream, format, args);
2411 va_end (args);
2412 }
2413
2414 /* Like fprintf_filtered, but prints its result indented.
2415 Called as fprintfi_filtered (spaces, stream, format, ...); */
2416
2417 void
2418 fprintfi_filtered (int spaces, struct ui_file *stream, const char *format,
2419 ...)
2420 {
2421 va_list args;
2422
2423 va_start (args, format);
2424 print_spaces_filtered (spaces, stream);
2425
2426 vfprintf_filtered (stream, format, args);
2427 va_end (args);
2428 }
2429
2430
2431 void
2432 printf_filtered (const char *format, ...)
2433 {
2434 va_list args;
2435
2436 va_start (args, format);
2437 vfprintf_filtered (gdb_stdout, format, args);
2438 va_end (args);
2439 }
2440
2441
2442 void
2443 printf_unfiltered (const char *format, ...)
2444 {
2445 va_list args;
2446
2447 va_start (args, format);
2448 vfprintf_unfiltered (gdb_stdout, format, args);
2449 va_end (args);
2450 }
2451
2452 /* Like printf_filtered, but prints it's result indented.
2453 Called as printfi_filtered (spaces, format, ...); */
2454
2455 void
2456 printfi_filtered (int spaces, const char *format, ...)
2457 {
2458 va_list args;
2459
2460 va_start (args, format);
2461 print_spaces_filtered (spaces, gdb_stdout);
2462 vfprintf_filtered (gdb_stdout, format, args);
2463 va_end (args);
2464 }
2465
2466 /* Easy -- but watch out!
2467
2468 This routine is *not* a replacement for puts()! puts() appends a newline.
2469 This one doesn't, and had better not! */
2470
2471 void
2472 puts_filtered (const char *string)
2473 {
2474 fputs_filtered (string, gdb_stdout);
2475 }
2476
2477 void
2478 puts_unfiltered (const char *string)
2479 {
2480 fputs_unfiltered (string, gdb_stdout);
2481 }
2482
2483 /* Return a pointer to N spaces and a null. The pointer is good
2484 until the next call to here. */
2485 char *
2486 n_spaces (int n)
2487 {
2488 char *t;
2489 static char *spaces = 0;
2490 static int max_spaces = -1;
2491
2492 if (n > max_spaces)
2493 {
2494 if (spaces)
2495 xfree (spaces);
2496 spaces = (char *) xmalloc (n + 1);
2497 for (t = spaces + n; t != spaces;)
2498 *--t = ' ';
2499 spaces[n] = '\0';
2500 max_spaces = n;
2501 }
2502
2503 return spaces + max_spaces - n;
2504 }
2505
2506 /* Print N spaces. */
2507 void
2508 print_spaces_filtered (int n, struct ui_file *stream)
2509 {
2510 fputs_filtered (n_spaces (n), stream);
2511 }
2512 \f
2513 /* C++/ObjC demangler stuff. */
2514
2515 /* fprintf_symbol_filtered attempts to demangle NAME, a symbol in language
2516 LANG, using demangling args ARG_MODE, and print it filtered to STREAM.
2517 If the name is not mangled, or the language for the name is unknown, or
2518 demangling is off, the name is printed in its "raw" form. */
2519
2520 void
2521 fprintf_symbol_filtered (struct ui_file *stream, const char *name,
2522 enum language lang, int arg_mode)
2523 {
2524 char *demangled;
2525
2526 if (name != NULL)
2527 {
2528 /* If user wants to see raw output, no problem. */
2529 if (!demangle)
2530 {
2531 fputs_filtered (name, stream);
2532 }
2533 else
2534 {
2535 demangled = language_demangle (language_def (lang), name, arg_mode);
2536 fputs_filtered (demangled ? demangled : name, stream);
2537 if (demangled != NULL)
2538 {
2539 xfree (demangled);
2540 }
2541 }
2542 }
2543 }
2544
2545 /* Do a strcmp() type operation on STRING1 and STRING2, ignoring any
2546 differences in whitespace. Returns 0 if they match, non-zero if they
2547 don't (slightly different than strcmp()'s range of return values).
2548
2549 As an extra hack, string1=="FOO(ARGS)" matches string2=="FOO".
2550 This "feature" is useful when searching for matching C++ function names
2551 (such as if the user types 'break FOO', where FOO is a mangled C++
2552 function). */
2553
2554 int
2555 strcmp_iw (const char *string1, const char *string2)
2556 {
2557 while ((*string1 != '\0') && (*string2 != '\0'))
2558 {
2559 while (isspace (*string1))
2560 {
2561 string1++;
2562 }
2563 while (isspace (*string2))
2564 {
2565 string2++;
2566 }
2567 if (case_sensitivity == case_sensitive_on && *string1 != *string2)
2568 break;
2569 if (case_sensitivity == case_sensitive_off
2570 && (tolower ((unsigned char) *string1)
2571 != tolower ((unsigned char) *string2)))
2572 break;
2573 if (*string1 != '\0')
2574 {
2575 string1++;
2576 string2++;
2577 }
2578 }
2579 return (*string1 != '\0' && *string1 != '(') || (*string2 != '\0');
2580 }
2581
2582 /* This is like strcmp except that it ignores whitespace and treats
2583 '(' as the first non-NULL character in terms of ordering. Like
2584 strcmp (and unlike strcmp_iw), it returns negative if STRING1 <
2585 STRING2, 0 if STRING2 = STRING2, and positive if STRING1 > STRING2
2586 according to that ordering.
2587
2588 If a list is sorted according to this function and if you want to
2589 find names in the list that match some fixed NAME according to
2590 strcmp_iw(LIST_ELT, NAME), then the place to start looking is right
2591 where this function would put NAME.
2592
2593 This function must be neutral to the CASE_SENSITIVITY setting as the user
2594 may choose it during later lookup. Therefore this function always sorts
2595 primarily case-insensitively and secondarily case-sensitively.
2596
2597 Here are some examples of why using strcmp to sort is a bad idea:
2598
2599 Whitespace example:
2600
2601 Say your partial symtab contains: "foo<char *>", "goo". Then, if
2602 we try to do a search for "foo<char*>", strcmp will locate this
2603 after "foo<char *>" and before "goo". Then lookup_partial_symbol
2604 will start looking at strings beginning with "goo", and will never
2605 see the correct match of "foo<char *>".
2606
2607 Parenthesis example:
2608
2609 In practice, this is less like to be an issue, but I'll give it a
2610 shot. Let's assume that '$' is a legitimate character to occur in
2611 symbols. (Which may well even be the case on some systems.) Then
2612 say that the partial symbol table contains "foo$" and "foo(int)".
2613 strcmp will put them in this order, since '$' < '('. Now, if the
2614 user searches for "foo", then strcmp will sort "foo" before "foo$".
2615 Then lookup_partial_symbol will notice that strcmp_iw("foo$",
2616 "foo") is false, so it won't proceed to the actual match of
2617 "foo(int)" with "foo". */
2618
2619 int
2620 strcmp_iw_ordered (const char *string1, const char *string2)
2621 {
2622 const char *saved_string1 = string1, *saved_string2 = string2;
2623 enum case_sensitivity case_pass = case_sensitive_off;
2624
2625 for (;;)
2626 {
2627 /* C1 and C2 are valid only if *string1 != '\0' && *string2 != '\0'.
2628 Provide stub characters if we are already at the end of one of the
2629 strings. */
2630 char c1 = 'X', c2 = 'X';
2631
2632 while (*string1 != '\0' && *string2 != '\0')
2633 {
2634 while (isspace (*string1))
2635 string1++;
2636 while (isspace (*string2))
2637 string2++;
2638
2639 switch (case_pass)
2640 {
2641 case case_sensitive_off:
2642 c1 = tolower ((unsigned char) *string1);
2643 c2 = tolower ((unsigned char) *string2);
2644 break;
2645 case case_sensitive_on:
2646 c1 = *string1;
2647 c2 = *string2;
2648 break;
2649 }
2650 if (c1 != c2)
2651 break;
2652
2653 if (*string1 != '\0')
2654 {
2655 string1++;
2656 string2++;
2657 }
2658 }
2659
2660 switch (*string1)
2661 {
2662 /* Characters are non-equal unless they're both '\0'; we want to
2663 make sure we get the comparison right according to our
2664 comparison in the cases where one of them is '\0' or '('. */
2665 case '\0':
2666 if (*string2 == '\0')
2667 break;
2668 else
2669 return -1;
2670 case '(':
2671 if (*string2 == '\0')
2672 return 1;
2673 else
2674 return -1;
2675 default:
2676 if (*string2 == '\0' || *string2 == '(')
2677 return 1;
2678 else if (c1 > c2)
2679 return 1;
2680 else if (c1 < c2)
2681 return -1;
2682 /* PASSTHRU */
2683 }
2684
2685 if (case_pass == case_sensitive_on)
2686 return 0;
2687
2688 /* Otherwise the strings were equal in case insensitive way, make
2689 a more fine grained comparison in a case sensitive way. */
2690
2691 case_pass = case_sensitive_on;
2692 string1 = saved_string1;
2693 string2 = saved_string2;
2694 }
2695 }
2696
2697 /* A simple comparison function with opposite semantics to strcmp. */
2698
2699 int
2700 streq (const char *lhs, const char *rhs)
2701 {
2702 return !strcmp (lhs, rhs);
2703 }
2704 \f
2705
2706 /*
2707 ** subset_compare()
2708 ** Answer whether string_to_compare is a full or partial match to
2709 ** template_string. The partial match must be in sequence starting
2710 ** at index 0.
2711 */
2712 int
2713 subset_compare (char *string_to_compare, char *template_string)
2714 {
2715 int match;
2716
2717 if (template_string != (char *) NULL && string_to_compare != (char *) NULL
2718 && strlen (string_to_compare) <= strlen (template_string))
2719 match =
2720 (strncmp
2721 (template_string, string_to_compare, strlen (string_to_compare)) == 0);
2722 else
2723 match = 0;
2724 return match;
2725 }
2726
2727 static void
2728 pagination_on_command (char *arg, int from_tty)
2729 {
2730 pagination_enabled = 1;
2731 }
2732
2733 static void
2734 pagination_off_command (char *arg, int from_tty)
2735 {
2736 pagination_enabled = 0;
2737 }
2738
2739 static void
2740 show_debug_timestamp (struct ui_file *file, int from_tty,
2741 struct cmd_list_element *c, const char *value)
2742 {
2743 fprintf_filtered (file, _("Timestamping debugging messages is %s.\n"),
2744 value);
2745 }
2746 \f
2747
2748 void
2749 initialize_utils (void)
2750 {
2751 add_setshow_uinteger_cmd ("width", class_support, &chars_per_line, _("\
2752 Set number of characters gdb thinks are in a line."), _("\
2753 Show number of characters gdb thinks are in a line."), NULL,
2754 set_width_command,
2755 show_chars_per_line,
2756 &setlist, &showlist);
2757
2758 add_setshow_uinteger_cmd ("height", class_support, &lines_per_page, _("\
2759 Set number of lines gdb thinks are in a page."), _("\
2760 Show number of lines gdb thinks are in a page."), NULL,
2761 set_height_command,
2762 show_lines_per_page,
2763 &setlist, &showlist);
2764
2765 init_page_info ();
2766
2767 add_setshow_boolean_cmd ("pagination", class_support,
2768 &pagination_enabled, _("\
2769 Set state of pagination."), _("\
2770 Show state of pagination."), NULL,
2771 NULL,
2772 show_pagination_enabled,
2773 &setlist, &showlist);
2774
2775 if (xdb_commands)
2776 {
2777 add_com ("am", class_support, pagination_on_command,
2778 _("Enable pagination"));
2779 add_com ("sm", class_support, pagination_off_command,
2780 _("Disable pagination"));
2781 }
2782
2783 add_setshow_boolean_cmd ("sevenbit-strings", class_support,
2784 &sevenbit_strings, _("\
2785 Set printing of 8-bit characters in strings as \\nnn."), _("\
2786 Show printing of 8-bit characters in strings as \\nnn."), NULL,
2787 NULL,
2788 show_sevenbit_strings,
2789 &setprintlist, &showprintlist);
2790
2791 add_setshow_boolean_cmd ("timestamp", class_maintenance,
2792 &debug_timestamp, _("\
2793 Set timestamping of debugging messages."), _("\
2794 Show timestamping of debugging messages."), _("\
2795 When set, debugging messages will be marked with seconds and microseconds."),
2796 NULL,
2797 show_debug_timestamp,
2798 &setdebuglist, &showdebuglist);
2799 }
2800
2801 /* Print routines to handle variable size regs, etc. */
2802 /* Temporary storage using circular buffer. */
2803 #define NUMCELLS 16
2804 #define CELLSIZE 50
2805 static char *
2806 get_cell (void)
2807 {
2808 static char buf[NUMCELLS][CELLSIZE];
2809 static int cell = 0;
2810
2811 if (++cell >= NUMCELLS)
2812 cell = 0;
2813 return buf[cell];
2814 }
2815
2816 const char *
2817 paddress (struct gdbarch *gdbarch, CORE_ADDR addr)
2818 {
2819 /* Truncate address to the size of a target address, avoiding shifts
2820 larger or equal than the width of a CORE_ADDR. The local
2821 variable ADDR_BIT stops the compiler reporting a shift overflow
2822 when it won't occur. */
2823 /* NOTE: This assumes that the significant address information is
2824 kept in the least significant bits of ADDR - the upper bits were
2825 either zero or sign extended. Should gdbarch_address_to_pointer or
2826 some ADDRESS_TO_PRINTABLE() be used to do the conversion? */
2827
2828 int addr_bit = gdbarch_addr_bit (gdbarch);
2829
2830 if (addr_bit < (sizeof (CORE_ADDR) * HOST_CHAR_BIT))
2831 addr &= ((CORE_ADDR) 1 << addr_bit) - 1;
2832 return hex_string (addr);
2833 }
2834
2835 /* This function is described in "defs.h". */
2836
2837 const char *
2838 print_core_address (struct gdbarch *gdbarch, CORE_ADDR address)
2839 {
2840 int addr_bit = gdbarch_addr_bit (gdbarch);
2841
2842 if (addr_bit < (sizeof (CORE_ADDR) * HOST_CHAR_BIT))
2843 address &= ((CORE_ADDR) 1 << addr_bit) - 1;
2844
2845 /* FIXME: cagney/2002-05-03: Need local_address_string() function
2846 that returns the language localized string formatted to a width
2847 based on gdbarch_addr_bit. */
2848 if (addr_bit <= 32)
2849 return hex_string_custom (address, 8);
2850 else
2851 return hex_string_custom (address, 16);
2852 }
2853
2854 /* Callback hash_f for htab_create_alloc or htab_create_alloc_ex. */
2855
2856 hashval_t
2857 core_addr_hash (const void *ap)
2858 {
2859 const CORE_ADDR *addrp = ap;
2860
2861 return *addrp;
2862 }
2863
2864 /* Callback eq_f for htab_create_alloc or htab_create_alloc_ex. */
2865
2866 int
2867 core_addr_eq (const void *ap, const void *bp)
2868 {
2869 const CORE_ADDR *addr_ap = ap;
2870 const CORE_ADDR *addr_bp = bp;
2871
2872 return *addr_ap == *addr_bp;
2873 }
2874
2875 static char *
2876 decimal2str (char *sign, ULONGEST addr, int width)
2877 {
2878 /* Steal code from valprint.c:print_decimal(). Should this worry
2879 about the real size of addr as the above does? */
2880 unsigned long temp[3];
2881 char *str = get_cell ();
2882 int i = 0;
2883
2884 do
2885 {
2886 temp[i] = addr % (1000 * 1000 * 1000);
2887 addr /= (1000 * 1000 * 1000);
2888 i++;
2889 width -= 9;
2890 }
2891 while (addr != 0 && i < (sizeof (temp) / sizeof (temp[0])));
2892
2893 width += 9;
2894 if (width < 0)
2895 width = 0;
2896
2897 switch (i)
2898 {
2899 case 1:
2900 xsnprintf (str, CELLSIZE, "%s%0*lu", sign, width, temp[0]);
2901 break;
2902 case 2:
2903 xsnprintf (str, CELLSIZE, "%s%0*lu%09lu", sign, width,
2904 temp[1], temp[0]);
2905 break;
2906 case 3:
2907 xsnprintf (str, CELLSIZE, "%s%0*lu%09lu%09lu", sign, width,
2908 temp[2], temp[1], temp[0]);
2909 break;
2910 default:
2911 internal_error (__FILE__, __LINE__,
2912 _("failed internal consistency check"));
2913 }
2914
2915 return str;
2916 }
2917
2918 static char *
2919 octal2str (ULONGEST addr, int width)
2920 {
2921 unsigned long temp[3];
2922 char *str = get_cell ();
2923 int i = 0;
2924
2925 do
2926 {
2927 temp[i] = addr % (0100000 * 0100000);
2928 addr /= (0100000 * 0100000);
2929 i++;
2930 width -= 10;
2931 }
2932 while (addr != 0 && i < (sizeof (temp) / sizeof (temp[0])));
2933
2934 width += 10;
2935 if (width < 0)
2936 width = 0;
2937
2938 switch (i)
2939 {
2940 case 1:
2941 if (temp[0] == 0)
2942 xsnprintf (str, CELLSIZE, "%*o", width, 0);
2943 else
2944 xsnprintf (str, CELLSIZE, "0%0*lo", width, temp[0]);
2945 break;
2946 case 2:
2947 xsnprintf (str, CELLSIZE, "0%0*lo%010lo", width, temp[1], temp[0]);
2948 break;
2949 case 3:
2950 xsnprintf (str, CELLSIZE, "0%0*lo%010lo%010lo", width,
2951 temp[2], temp[1], temp[0]);
2952 break;
2953 default:
2954 internal_error (__FILE__, __LINE__,
2955 _("failed internal consistency check"));
2956 }
2957
2958 return str;
2959 }
2960
2961 char *
2962 pulongest (ULONGEST u)
2963 {
2964 return decimal2str ("", u, 0);
2965 }
2966
2967 char *
2968 plongest (LONGEST l)
2969 {
2970 if (l < 0)
2971 return decimal2str ("-", -l, 0);
2972 else
2973 return decimal2str ("", l, 0);
2974 }
2975
2976 /* Eliminate warning from compiler on 32-bit systems. */
2977 static int thirty_two = 32;
2978
2979 char *
2980 phex (ULONGEST l, int sizeof_l)
2981 {
2982 char *str;
2983
2984 switch (sizeof_l)
2985 {
2986 case 8:
2987 str = get_cell ();
2988 xsnprintf (str, CELLSIZE, "%08lx%08lx",
2989 (unsigned long) (l >> thirty_two),
2990 (unsigned long) (l & 0xffffffff));
2991 break;
2992 case 4:
2993 str = get_cell ();
2994 xsnprintf (str, CELLSIZE, "%08lx", (unsigned long) l);
2995 break;
2996 case 2:
2997 str = get_cell ();
2998 xsnprintf (str, CELLSIZE, "%04x", (unsigned short) (l & 0xffff));
2999 break;
3000 default:
3001 str = phex (l, sizeof (l));
3002 break;
3003 }
3004
3005 return str;
3006 }
3007
3008 char *
3009 phex_nz (ULONGEST l, int sizeof_l)
3010 {
3011 char *str;
3012
3013 switch (sizeof_l)
3014 {
3015 case 8:
3016 {
3017 unsigned long high = (unsigned long) (l >> thirty_two);
3018
3019 str = get_cell ();
3020 if (high == 0)
3021 xsnprintf (str, CELLSIZE, "%lx",
3022 (unsigned long) (l & 0xffffffff));
3023 else
3024 xsnprintf (str, CELLSIZE, "%lx%08lx", high,
3025 (unsigned long) (l & 0xffffffff));
3026 break;
3027 }
3028 case 4:
3029 str = get_cell ();
3030 xsnprintf (str, CELLSIZE, "%lx", (unsigned long) l);
3031 break;
3032 case 2:
3033 str = get_cell ();
3034 xsnprintf (str, CELLSIZE, "%x", (unsigned short) (l & 0xffff));
3035 break;
3036 default:
3037 str = phex_nz (l, sizeof (l));
3038 break;
3039 }
3040
3041 return str;
3042 }
3043
3044 /* Converts a LONGEST to a C-format hexadecimal literal and stores it
3045 in a static string. Returns a pointer to this string. */
3046 char *
3047 hex_string (LONGEST num)
3048 {
3049 char *result = get_cell ();
3050
3051 xsnprintf (result, CELLSIZE, "0x%s", phex_nz (num, sizeof (num)));
3052 return result;
3053 }
3054
3055 /* Converts a LONGEST number to a C-format hexadecimal literal and
3056 stores it in a static string. Returns a pointer to this string
3057 that is valid until the next call. The number is padded on the
3058 left with 0s to at least WIDTH characters. */
3059 char *
3060 hex_string_custom (LONGEST num, int width)
3061 {
3062 char *result = get_cell ();
3063 char *result_end = result + CELLSIZE - 1;
3064 const char *hex = phex_nz (num, sizeof (num));
3065 int hex_len = strlen (hex);
3066
3067 if (hex_len > width)
3068 width = hex_len;
3069 if (width + 2 >= CELLSIZE)
3070 internal_error (__FILE__, __LINE__, _("\
3071 hex_string_custom: insufficient space to store result"));
3072
3073 strcpy (result_end - width - 2, "0x");
3074 memset (result_end - width, '0', width);
3075 strcpy (result_end - hex_len, hex);
3076 return result_end - width - 2;
3077 }
3078
3079 /* Convert VAL to a numeral in the given radix. For
3080 * radix 10, IS_SIGNED may be true, indicating a signed quantity;
3081 * otherwise VAL is interpreted as unsigned. If WIDTH is supplied,
3082 * it is the minimum width (0-padded if needed). USE_C_FORMAT means
3083 * to use C format in all cases. If it is false, then 'x'
3084 * and 'o' formats do not include a prefix (0x or leading 0). */
3085
3086 char *
3087 int_string (LONGEST val, int radix, int is_signed, int width,
3088 int use_c_format)
3089 {
3090 switch (radix)
3091 {
3092 case 16:
3093 {
3094 char *result;
3095
3096 if (width == 0)
3097 result = hex_string (val);
3098 else
3099 result = hex_string_custom (val, width);
3100 if (! use_c_format)
3101 result += 2;
3102 return result;
3103 }
3104 case 10:
3105 {
3106 if (is_signed && val < 0)
3107 return decimal2str ("-", -val, width);
3108 else
3109 return decimal2str ("", val, width);
3110 }
3111 case 8:
3112 {
3113 char *result = octal2str (val, width);
3114
3115 if (use_c_format || val == 0)
3116 return result;
3117 else
3118 return result + 1;
3119 }
3120 default:
3121 internal_error (__FILE__, __LINE__,
3122 _("failed internal consistency check"));
3123 }
3124 }
3125
3126 /* Convert a CORE_ADDR into a string. */
3127 const char *
3128 core_addr_to_string (const CORE_ADDR addr)
3129 {
3130 char *str = get_cell ();
3131
3132 strcpy (str, "0x");
3133 strcat (str, phex (addr, sizeof (addr)));
3134 return str;
3135 }
3136
3137 const char *
3138 core_addr_to_string_nz (const CORE_ADDR addr)
3139 {
3140 char *str = get_cell ();
3141
3142 strcpy (str, "0x");
3143 strcat (str, phex_nz (addr, sizeof (addr)));
3144 return str;
3145 }
3146
3147 /* Convert a string back into a CORE_ADDR. */
3148 CORE_ADDR
3149 string_to_core_addr (const char *my_string)
3150 {
3151 CORE_ADDR addr = 0;
3152
3153 if (my_string[0] == '0' && tolower (my_string[1]) == 'x')
3154 {
3155 /* Assume that it is in hex. */
3156 int i;
3157
3158 for (i = 2; my_string[i] != '\0'; i++)
3159 {
3160 if (isdigit (my_string[i]))
3161 addr = (my_string[i] - '0') + (addr * 16);
3162 else if (isxdigit (my_string[i]))
3163 addr = (tolower (my_string[i]) - 'a' + 0xa) + (addr * 16);
3164 else
3165 error (_("invalid hex \"%s\""), my_string);
3166 }
3167 }
3168 else
3169 {
3170 /* Assume that it is in decimal. */
3171 int i;
3172
3173 for (i = 0; my_string[i] != '\0'; i++)
3174 {
3175 if (isdigit (my_string[i]))
3176 addr = (my_string[i] - '0') + (addr * 10);
3177 else
3178 error (_("invalid decimal \"%s\""), my_string);
3179 }
3180 }
3181
3182 return addr;
3183 }
3184
3185 const char *
3186 host_address_to_string (const void *addr)
3187 {
3188 char *str = get_cell ();
3189
3190 xsnprintf (str, CELLSIZE, "0x%s", phex_nz ((uintptr_t) addr, sizeof (addr)));
3191 return str;
3192 }
3193
3194 char *
3195 gdb_realpath (const char *filename)
3196 {
3197 /* Method 1: The system has a compile time upper bound on a filename
3198 path. Use that and realpath() to canonicalize the name. This is
3199 the most common case. Note that, if there isn't a compile time
3200 upper bound, you want to avoid realpath() at all costs. */
3201 #if defined(HAVE_REALPATH)
3202 {
3203 # if defined (PATH_MAX)
3204 char buf[PATH_MAX];
3205 # define USE_REALPATH
3206 # elif defined (MAXPATHLEN)
3207 char buf[MAXPATHLEN];
3208 # define USE_REALPATH
3209 # endif
3210 # if defined (USE_REALPATH)
3211 const char *rp = realpath (filename, buf);
3212
3213 if (rp == NULL)
3214 rp = filename;
3215 return xstrdup (rp);
3216 # endif
3217 }
3218 #endif /* HAVE_REALPATH */
3219
3220 /* Method 2: The host system (i.e., GNU) has the function
3221 canonicalize_file_name() which malloc's a chunk of memory and
3222 returns that, use that. */
3223 #if defined(HAVE_CANONICALIZE_FILE_NAME)
3224 {
3225 char *rp = canonicalize_file_name (filename);
3226
3227 if (rp == NULL)
3228 return xstrdup (filename);
3229 else
3230 return rp;
3231 }
3232 #endif
3233
3234 /* FIXME: cagney/2002-11-13:
3235
3236 Method 2a: Use realpath() with a NULL buffer. Some systems, due
3237 to the problems described in method 3, have modified their
3238 realpath() implementation so that it will allocate a buffer when
3239 NULL is passed in. Before this can be used, though, some sort of
3240 configure time test would need to be added. Otherwize the code
3241 will likely core dump. */
3242
3243 /* Method 3: Now we're getting desperate! The system doesn't have a
3244 compile time buffer size and no alternative function. Query the
3245 OS, using pathconf(), for the buffer limit. Care is needed
3246 though, some systems do not limit PATH_MAX (return -1 for
3247 pathconf()) making it impossible to pass a correctly sized buffer
3248 to realpath() (it could always overflow). On those systems, we
3249 skip this. */
3250 #if defined (HAVE_REALPATH) && defined (HAVE_UNISTD_H) && defined(HAVE_ALLOCA)
3251 {
3252 /* Find out the max path size. */
3253 long path_max = pathconf ("/", _PC_PATH_MAX);
3254
3255 if (path_max > 0)
3256 {
3257 /* PATH_MAX is bounded. */
3258 char *buf = alloca (path_max);
3259 char *rp = realpath (filename, buf);
3260
3261 return xstrdup (rp ? rp : filename);
3262 }
3263 }
3264 #endif
3265
3266 /* The MS Windows method. If we don't have realpath, we assume we
3267 don't have symlinks and just canonicalize to a Windows absolute
3268 path. GetFullPath converts ../ and ./ in relative paths to
3269 absolute paths, filling in current drive if one is not given
3270 or using the current directory of a specified drive (eg, "E:foo").
3271 It also converts all forward slashes to back slashes. */
3272 /* The file system is case-insensitive but case-preserving.
3273 So we do not lowercase the path. Otherwise, we might not
3274 be able to display the original casing in a given path. */
3275 #if defined (_WIN32)
3276 {
3277 char buf[MAX_PATH];
3278 DWORD len = GetFullPathName (filename, MAX_PATH, buf, NULL);
3279
3280 if (len > 0 && len < MAX_PATH)
3281 return xstrdup (buf);
3282 }
3283 #endif
3284
3285 /* This system is a lost cause, just dup the buffer. */
3286 return xstrdup (filename);
3287 }
3288
3289 ULONGEST
3290 align_up (ULONGEST v, int n)
3291 {
3292 /* Check that N is really a power of two. */
3293 gdb_assert (n && (n & (n-1)) == 0);
3294 return (v + n - 1) & -n;
3295 }
3296
3297 ULONGEST
3298 align_down (ULONGEST v, int n)
3299 {
3300 /* Check that N is really a power of two. */
3301 gdb_assert (n && (n & (n-1)) == 0);
3302 return (v & -n);
3303 }
3304
3305 /* Allocation function for the libiberty hash table which uses an
3306 obstack. The obstack is passed as DATA. */
3307
3308 void *
3309 hashtab_obstack_allocate (void *data, size_t size, size_t count)
3310 {
3311 unsigned int total = size * count;
3312 void *ptr = obstack_alloc ((struct obstack *) data, total);
3313
3314 memset (ptr, 0, total);
3315 return ptr;
3316 }
3317
3318 /* Trivial deallocation function for the libiberty splay tree and hash
3319 table - don't deallocate anything. Rely on later deletion of the
3320 obstack. DATA will be the obstack, although it is not needed
3321 here. */
3322
3323 void
3324 dummy_obstack_deallocate (void *object, void *data)
3325 {
3326 return;
3327 }
3328
3329 /* The bit offset of the highest byte in a ULONGEST, for overflow
3330 checking. */
3331
3332 #define HIGH_BYTE_POSN ((sizeof (ULONGEST) - 1) * HOST_CHAR_BIT)
3333
3334 /* True (non-zero) iff DIGIT is a valid digit in radix BASE,
3335 where 2 <= BASE <= 36. */
3336
3337 static int
3338 is_digit_in_base (unsigned char digit, int base)
3339 {
3340 if (!isalnum (digit))
3341 return 0;
3342 if (base <= 10)
3343 return (isdigit (digit) && digit < base + '0');
3344 else
3345 return (isdigit (digit) || tolower (digit) < base - 10 + 'a');
3346 }
3347
3348 static int
3349 digit_to_int (unsigned char c)
3350 {
3351 if (isdigit (c))
3352 return c - '0';
3353 else
3354 return tolower (c) - 'a' + 10;
3355 }
3356
3357 /* As for strtoul, but for ULONGEST results. */
3358
3359 ULONGEST
3360 strtoulst (const char *num, const char **trailer, int base)
3361 {
3362 unsigned int high_part;
3363 ULONGEST result;
3364 int minus = 0;
3365 int i = 0;
3366
3367 /* Skip leading whitespace. */
3368 while (isspace (num[i]))
3369 i++;
3370
3371 /* Handle prefixes. */
3372 if (num[i] == '+')
3373 i++;
3374 else if (num[i] == '-')
3375 {
3376 minus = 1;
3377 i++;
3378 }
3379
3380 if (base == 0 || base == 16)
3381 {
3382 if (num[i] == '0' && (num[i + 1] == 'x' || num[i + 1] == 'X'))
3383 {
3384 i += 2;
3385 if (base == 0)
3386 base = 16;
3387 }
3388 }
3389
3390 if (base == 0 && num[i] == '0')
3391 base = 8;
3392
3393 if (base == 0)
3394 base = 10;
3395
3396 if (base < 2 || base > 36)
3397 {
3398 errno = EINVAL;
3399 return 0;
3400 }
3401
3402 result = high_part = 0;
3403 for (; is_digit_in_base (num[i], base); i += 1)
3404 {
3405 result = result * base + digit_to_int (num[i]);
3406 high_part = high_part * base + (unsigned int) (result >> HIGH_BYTE_POSN);
3407 result &= ((ULONGEST) 1 << HIGH_BYTE_POSN) - 1;
3408 if (high_part > 0xff)
3409 {
3410 errno = ERANGE;
3411 result = ~ (ULONGEST) 0;
3412 high_part = 0;
3413 minus = 0;
3414 break;
3415 }
3416 }
3417
3418 if (trailer != NULL)
3419 *trailer = &num[i];
3420
3421 result = result + ((ULONGEST) high_part << HIGH_BYTE_POSN);
3422 if (minus)
3423 return -result;
3424 else
3425 return result;
3426 }
3427
3428 /* Simple, portable version of dirname that does not modify its
3429 argument. */
3430
3431 char *
3432 ldirname (const char *filename)
3433 {
3434 const char *base = lbasename (filename);
3435 char *dirname;
3436
3437 while (base > filename && IS_DIR_SEPARATOR (base[-1]))
3438 --base;
3439
3440 if (base == filename)
3441 return NULL;
3442
3443 dirname = xmalloc (base - filename + 2);
3444 memcpy (dirname, filename, base - filename);
3445
3446 /* On DOS based file systems, convert "d:foo" to "d:.", so that we
3447 create "d:./bar" later instead of the (different) "d:/bar". */
3448 if (base - filename == 2 && IS_ABSOLUTE_PATH (base)
3449 && !IS_DIR_SEPARATOR (filename[0]))
3450 dirname[base++ - filename] = '.';
3451
3452 dirname[base - filename] = '\0';
3453 return dirname;
3454 }
3455
3456 /* Call libiberty's buildargv, and return the result.
3457 If buildargv fails due to out-of-memory, call nomem.
3458 Therefore, the returned value is guaranteed to be non-NULL,
3459 unless the parameter itself is NULL. */
3460
3461 char **
3462 gdb_buildargv (const char *s)
3463 {
3464 char **argv = buildargv (s);
3465
3466 if (s != NULL && argv == NULL)
3467 malloc_failure (0);
3468 return argv;
3469 }
3470
3471 int
3472 compare_positive_ints (const void *ap, const void *bp)
3473 {
3474 /* Because we know we're comparing two ints which are positive,
3475 there's no danger of overflow here. */
3476 return * (int *) ap - * (int *) bp;
3477 }
3478
3479 /* String compare function for qsort. */
3480
3481 int
3482 compare_strings (const void *arg1, const void *arg2)
3483 {
3484 const char **s1 = (const char **) arg1;
3485 const char **s2 = (const char **) arg2;
3486
3487 return strcmp (*s1, *s2);
3488 }
3489
3490 #define AMBIGUOUS_MESS1 ".\nMatching formats:"
3491 #define AMBIGUOUS_MESS2 \
3492 ".\nUse \"set gnutarget format-name\" to specify the format."
3493
3494 const char *
3495 gdb_bfd_errmsg (bfd_error_type error_tag, char **matching)
3496 {
3497 char *ret, *retp;
3498 int ret_len;
3499 char **p;
3500
3501 /* Check if errmsg just need simple return. */
3502 if (error_tag != bfd_error_file_ambiguously_recognized || matching == NULL)
3503 return bfd_errmsg (error_tag);
3504
3505 ret_len = strlen (bfd_errmsg (error_tag)) + strlen (AMBIGUOUS_MESS1)
3506 + strlen (AMBIGUOUS_MESS2);
3507 for (p = matching; *p; p++)
3508 ret_len += strlen (*p) + 1;
3509 ret = xmalloc (ret_len + 1);
3510 retp = ret;
3511 make_cleanup (xfree, ret);
3512
3513 strcpy (retp, bfd_errmsg (error_tag));
3514 retp += strlen (retp);
3515
3516 strcpy (retp, AMBIGUOUS_MESS1);
3517 retp += strlen (retp);
3518
3519 for (p = matching; *p; p++)
3520 {
3521 sprintf (retp, " %s", *p);
3522 retp += strlen (retp);
3523 }
3524 xfree (matching);
3525
3526 strcpy (retp, AMBIGUOUS_MESS2);
3527
3528 return ret;
3529 }
3530
3531 /* Return ARGS parsed as a valid pid, or throw an error. */
3532
3533 int
3534 parse_pid_to_attach (char *args)
3535 {
3536 unsigned long pid;
3537 char *dummy;
3538
3539 if (!args)
3540 error_no_arg (_("process-id to attach"));
3541
3542 dummy = args;
3543 pid = strtoul (args, &dummy, 0);
3544 /* Some targets don't set errno on errors, grrr! */
3545 if ((pid == 0 && dummy == args) || dummy != &args[strlen (args)])
3546 error (_("Illegal process-id: %s."), args);
3547
3548 return pid;
3549 }
3550
3551 /* Helper for make_bpstat_clear_actions_cleanup. */
3552
3553 static void
3554 do_bpstat_clear_actions_cleanup (void *unused)
3555 {
3556 bpstat_clear_actions ();
3557 }
3558
3559 /* Call bpstat_clear_actions for the case an exception is throw. You should
3560 discard_cleanups if no exception is caught. */
3561
3562 struct cleanup *
3563 make_bpstat_clear_actions_cleanup (void)
3564 {
3565 return make_cleanup (do_bpstat_clear_actions_cleanup, NULL);
3566 }
3567
3568 /* Check for GCC >= 4.x according to the symtab->producer string. Return minor
3569 version (x) of 4.x in such case. If it is not GCC or it is GCC older than
3570 4.x return -1. If it is GCC 5.x or higher return INT_MAX. */
3571
3572 int
3573 producer_is_gcc_ge_4 (const char *producer)
3574 {
3575 const char *cs;
3576 int major, minor;
3577
3578 if (producer == NULL)
3579 {
3580 /* For unknown compilers expect their behavior is not compliant. For GCC
3581 this case can also happen for -gdwarf-4 type units supported since
3582 gcc-4.5. */
3583
3584 return -1;
3585 }
3586
3587 /* Skip any identifier after "GNU " - such as "C++" or "Java". */
3588
3589 if (strncmp (producer, "GNU ", strlen ("GNU ")) != 0)
3590 {
3591 /* For non-GCC compilers expect their behavior is not compliant. */
3592
3593 return -1;
3594 }
3595 cs = &producer[strlen ("GNU ")];
3596 while (*cs && !isdigit (*cs))
3597 cs++;
3598 if (sscanf (cs, "%d.%d", &major, &minor) != 2)
3599 {
3600 /* Not recognized as GCC. */
3601
3602 return -1;
3603 }
3604
3605 if (major < 4)
3606 return -1;
3607 if (major > 4)
3608 return INT_MAX;
3609 return minor;
3610 }
3611
3612 /* Helper for make_cleanup_free_char_ptr_vec. */
3613
3614 static void
3615 do_free_char_ptr_vec (void *arg)
3616 {
3617 VEC (char_ptr) *char_ptr_vec = arg;
3618
3619 free_char_ptr_vec (char_ptr_vec);
3620 }
3621
3622 /* Make cleanup handler calling xfree for each element of CHAR_PTR_VEC and
3623 final VEC_free for CHAR_PTR_VEC itself.
3624
3625 You must not modify CHAR_PTR_VEC after this cleanup registration as the
3626 CHAR_PTR_VEC base address may change on its updates. Contrary to VEC_free
3627 this function does not (cannot) clear the pointer. */
3628
3629 struct cleanup *
3630 make_cleanup_free_char_ptr_vec (VEC (char_ptr) *char_ptr_vec)
3631 {
3632 return make_cleanup (do_free_char_ptr_vec, char_ptr_vec);
3633 }
3634
3635 /* Substitute all occurences of string FROM by string TO in *STRINGP. *STRINGP
3636 must come from xrealloc-compatible allocator and it may be updated. FROM
3637 needs to be delimited by IS_DIR_SEPARATOR or DIRNAME_SEPARATOR (or be
3638 located at the start or end of *STRINGP. */
3639
3640 void
3641 substitute_path_component (char **stringp, const char *from, const char *to)
3642 {
3643 char *string = *stringp, *s;
3644 const size_t from_len = strlen (from);
3645 const size_t to_len = strlen (to);
3646
3647 for (s = string;;)
3648 {
3649 s = strstr (s, from);
3650 if (s == NULL)
3651 break;
3652
3653 if ((s == string || IS_DIR_SEPARATOR (s[-1])
3654 || s[-1] == DIRNAME_SEPARATOR)
3655 && (s[from_len] == '\0' || IS_DIR_SEPARATOR (s[from_len])
3656 || s[from_len] == DIRNAME_SEPARATOR))
3657 {
3658 char *string_new;
3659
3660 string_new = xrealloc (string, (strlen (string) + to_len + 1));
3661
3662 /* Relocate the current S pointer. */
3663 s = s - string + string_new;
3664 string = string_new;
3665
3666 /* Replace from by to. */
3667 memmove (&s[to_len], &s[from_len], strlen (&s[from_len]) + 1);
3668 memcpy (s, to, to_len);
3669
3670 s += to_len;
3671 }
3672 else
3673 s++;
3674 }
3675
3676 *stringp = string;
3677 }
3678
3679 #ifdef HAVE_WAITPID
3680
3681 #ifdef SIGALRM
3682
3683 /* SIGALRM handler for waitpid_with_timeout. */
3684
3685 static void
3686 sigalrm_handler (int signo)
3687 {
3688 /* Nothing to do. */
3689 }
3690
3691 #endif
3692
3693 /* Wrapper to wait for child PID to die with TIMEOUT.
3694 TIMEOUT is the time to stop waiting in seconds.
3695 If TIMEOUT is zero, pass WNOHANG to waitpid.
3696 Returns PID if it was successfully waited for, otherwise -1.
3697
3698 Timeouts are currently implemented with alarm and SIGALRM.
3699 If the host does not support them, this waits "forever".
3700 It would be odd though for a host to have waitpid and not SIGALRM. */
3701
3702 pid_t
3703 wait_to_die_with_timeout (pid_t pid, int *status, int timeout)
3704 {
3705 pid_t waitpid_result;
3706
3707 gdb_assert (pid > 0);
3708 gdb_assert (timeout >= 0);
3709
3710 if (timeout > 0)
3711 {
3712 #ifdef SIGALRM
3713 #if defined (HAVE_SIGACTION) && defined (SA_RESTART)
3714 struct sigaction sa, old_sa;
3715
3716 sa.sa_handler = sigalrm_handler;
3717 sigemptyset (&sa.sa_mask);
3718 sa.sa_flags = 0;
3719 sigaction (SIGALRM, &sa, &old_sa);
3720 #else
3721 void (*ofunc) ();
3722
3723 ofunc = (void (*)()) signal (SIGALRM, sigalrm_handler);
3724 #endif
3725
3726 alarm (timeout);
3727 #endif
3728
3729 waitpid_result = waitpid (pid, status, 0);
3730
3731 #ifdef SIGALRM
3732 alarm (0);
3733 #if defined (HAVE_SIGACTION) && defined (SA_RESTART)
3734 sigaction (SIGALRM, &old_sa, NULL);
3735 #else
3736 signal (SIGALRM, ofunc);
3737 #endif
3738 #endif
3739 }
3740 else
3741 waitpid_result = waitpid (pid, status, WNOHANG);
3742
3743 if (waitpid_result == pid)
3744 return pid;
3745 else
3746 return -1;
3747 }
3748
3749 #endif /* HAVE_WAITPID */
3750
3751 /* Provide fnmatch compatible function for FNM_FILE_NAME matching of host files.
3752 Both FNM_FILE_NAME and FNM_NOESCAPE must be set in FLAGS.
3753
3754 It handles correctly HAVE_DOS_BASED_FILE_SYSTEM and
3755 HAVE_CASE_INSENSITIVE_FILE_SYSTEM. */
3756
3757 int
3758 gdb_filename_fnmatch (const char *pattern, const char *string, int flags)
3759 {
3760 gdb_assert ((flags & FNM_FILE_NAME) != 0);
3761
3762 /* It is unclear how '\' escaping vs. directory separator should coexist. */
3763 gdb_assert ((flags & FNM_NOESCAPE) != 0);
3764
3765 #ifdef HAVE_DOS_BASED_FILE_SYSTEM
3766 {
3767 char *pattern_slash, *string_slash;
3768
3769 /* Replace '\' by '/' in both strings. */
3770
3771 pattern_slash = alloca (strlen (pattern) + 1);
3772 strcpy (pattern_slash, pattern);
3773 pattern = pattern_slash;
3774 for (; *pattern_slash != 0; pattern_slash++)
3775 if (IS_DIR_SEPARATOR (*pattern_slash))
3776 *pattern_slash = '/';
3777
3778 string_slash = alloca (strlen (string) + 1);
3779 strcpy (string_slash, string);
3780 string = string_slash;
3781 for (; *string_slash != 0; string_slash++)
3782 if (IS_DIR_SEPARATOR (*string_slash))
3783 *string_slash = '/';
3784 }
3785 #endif /* HAVE_DOS_BASED_FILE_SYSTEM */
3786
3787 #ifdef HAVE_CASE_INSENSITIVE_FILE_SYSTEM
3788 flags |= FNM_CASEFOLD;
3789 #endif /* HAVE_CASE_INSENSITIVE_FILE_SYSTEM */
3790
3791 return fnmatch (pattern, string, flags);
3792 }
3793
3794 /* Provide a prototype to silence -Wmissing-prototypes. */
3795 extern initialize_file_ftype _initialize_utils;
3796
3797 void
3798 _initialize_utils (void)
3799 {
3800 add_internal_problem_command (&internal_error_problem);
3801 add_internal_problem_command (&internal_warning_problem);
3802 }
This page took 0.143874 seconds and 4 git commands to generate.