Upgrade GDB from 7.4.1 to 7.6.1 on the vendor branch
[dragonfly.git] / contrib / gdb-7 / gdb / utils.c
CommitLineData
5796c8dc
SS
1/* General utility routines for GDB, the GNU debugger.
2
ef5ccd6c 3 Copyright (C) 1986-2013 Free Software Foundation, Inc.
5796c8dc
SS
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"
a45ae5f8 21#include "dyn-string.h"
5796c8dc
SS
22#include "gdb_assert.h"
23#include <ctype.h>
24#include "gdb_string.h"
ef5ccd6c 25#include "gdb_wait.h"
5796c8dc
SS
26#include "event-top.h"
27#include "exceptions.h"
28#include "gdbthread.h"
ef5ccd6c
JM
29#include "fnmatch.h"
30#include "gdb_bfd.h"
cf7f2e2d
JM
31#ifdef HAVE_SYS_RESOURCE_H
32#include <sys/resource.h>
33#endif /* HAVE_SYS_RESOURCE_H */
5796c8dc
SS
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
c50c785c 43/* SunOS's curses.h has a '#define reg register' in it. Thank you Sun. */
5796c8dc
SS
44#ifdef reg
45#undef reg
46#endif
47
48#include <signal.h>
a45ae5f8 49#include "timeval-utils.h"
5796c8dc
SS
50#include "gdbcmd.h"
51#include "serial.h"
52#include "bfd.h"
53#include "target.h"
a45ae5f8 54#include "gdb-demangle.h"
5796c8dc
SS
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"
cf7f2e2d 64#include "main.h"
a45ae5f8 65#include "solist.h"
5796c8dc
SS
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"
cf7f2e2d 79#include "interps.h"
c50c785c 80#include "gdb_regex.h"
5796c8dc
SS
81
82#if !HAVE_DECL_MALLOC
83extern PTR malloc (); /* ARI: PTR */
84#endif
85#if !HAVE_DECL_REALLOC
86extern PTR realloc (); /* ARI: PTR */
87#endif
88#if !HAVE_DECL_FREE
89extern void free ();
90#endif
91
5796c8dc
SS
92void (*deprecated_error_begin_hook) (void);
93
94/* Prototypes for local functions */
95
96static void vfprintf_maybe_filtered (struct ui_file *, const char *,
cf7f2e2d 97 va_list, int) ATTRIBUTE_PRINTF (2, 0);
5796c8dc
SS
98
99static void fputs_maybe_filtered (const char *, struct ui_file *, int);
100
5796c8dc
SS
101static void prompt_for_continue (void);
102
103static void set_screen_size (void);
104static void set_width (void);
105
ef5ccd6c
JM
106/* Time spent in prompt_for_continue in the currently executing command
107 waiting for user to respond.
108 Initialized in make_command_stats_cleanup.
109 Modified in prompt_for_continue and defaulted_query.
110 Used in report_command_stats. */
5796c8dc 111
ef5ccd6c 112static struct timeval prompt_for_continue_wait_time;
5796c8dc 113
ef5ccd6c 114/* A flag indicating whether to timestamp debugging messages. */
5796c8dc 115
ef5ccd6c 116static int debug_timestamp = 0;
5796c8dc 117
c50c785c 118/* Nonzero if we have job control. */
5796c8dc
SS
119
120int job_control;
121
ef5ccd6c 122#ifndef HAVE_PYTHON
5796c8dc
SS
123/* Nonzero means a quit has been requested. */
124
125int quit_flag;
ef5ccd6c 126#endif /* HAVE_PYTHON */
5796c8dc
SS
127
128/* Nonzero means quit immediately if Control-C is typed now, rather
129 than waiting until QUIT is executed. Be careful in setting this;
130 code which executes with immediate_quit set has to be very careful
131 about being able to deal with being interrupted at any time. It is
132 almost always better to use QUIT; the only exception I can think of
133 is being able to quit out of a system call (using EINTR loses if
134 the SIGINT happens between the previous QUIT and the system call).
135 To immediately quit in the case in which a SIGINT happens between
136 the previous QUIT and setting immediate_quit (desirable anytime we
137 expect to block), call QUIT after setting immediate_quit. */
138
139int immediate_quit;
140
ef5ccd6c
JM
141#ifndef HAVE_PYTHON
142
143/* Clear the quit flag. */
144
145void
146clear_quit_flag (void)
147{
148 quit_flag = 0;
149}
150
151/* Set the quit flag. */
152
153void
154set_quit_flag (void)
155{
156 quit_flag = 1;
157}
158
159/* Return true if the quit flag has been set, false otherwise. */
160
161int
162check_quit_flag (void)
163{
164 /* This is written in a particular way to avoid races. */
165 if (quit_flag)
166 {
167 quit_flag = 0;
168 return 1;
169 }
170
171 return 0;
172}
173
174#endif /* HAVE_PYTHON */
175
5796c8dc
SS
176/* Nonzero means that strings with character values >0x7F should be printed
177 as octal escapes. Zero means just print the value (e.g. it's an
178 international character, and the terminal or window can cope.) */
179
180int sevenbit_strings = 0;
181static void
182show_sevenbit_strings (struct ui_file *file, int from_tty,
183 struct cmd_list_element *c, const char *value)
184{
c50c785c
JM
185 fprintf_filtered (file, _("Printing of 8-bit characters "
186 "in strings as \\nnn is %s.\n"),
5796c8dc
SS
187 value);
188}
189
190/* String to be printed before error messages, if any. */
191
192char *error_pre_print;
193
194/* String to be printed before quit messages, if any. */
195
196char *quit_pre_print;
197
198/* String to be printed before warning messages, if any. */
199
200char *warning_pre_print = "\nwarning: ";
201
202int pagination_enabled = 1;
203static void
204show_pagination_enabled (struct ui_file *file, int from_tty,
205 struct cmd_list_element *c, const char *value)
206{
207 fprintf_filtered (file, _("State of pagination is %s.\n"), value);
208}
209
210\f
ef5ccd6c 211/* Cleanup utilities.
5796c8dc 212
ef5ccd6c
JM
213 These are not defined in cleanups.c (nor declared in cleanups.h)
214 because while they use the "cleanup API" they are not part of the
215 "cleanup API". */
5796c8dc
SS
216
217static void
218do_freeargv (void *arg)
219{
220 freeargv ((char **) arg);
221}
222
223struct cleanup *
224make_cleanup_freeargv (char **arg)
225{
ef5ccd6c 226 return make_cleanup (do_freeargv, arg);
5796c8dc
SS
227}
228
a45ae5f8
JM
229static void
230do_dyn_string_delete (void *arg)
231{
232 dyn_string_delete ((dyn_string_t) arg);
233}
234
235struct cleanup *
236make_cleanup_dyn_string_delete (dyn_string_t arg)
237{
ef5ccd6c 238 return make_cleanup (do_dyn_string_delete, arg);
a45ae5f8
JM
239}
240
5796c8dc
SS
241static void
242do_bfd_close_cleanup (void *arg)
243{
ef5ccd6c 244 gdb_bfd_unref (arg);
5796c8dc
SS
245}
246
247struct cleanup *
ef5ccd6c 248make_cleanup_bfd_unref (bfd *abfd)
5796c8dc
SS
249{
250 return make_cleanup (do_bfd_close_cleanup, abfd);
251}
252
253static void
254do_close_cleanup (void *arg)
255{
256 int *fd = arg;
cf7f2e2d 257
5796c8dc
SS
258 close (*fd);
259}
260
261struct cleanup *
262make_cleanup_close (int fd)
263{
264 int *saved_fd = xmalloc (sizeof (fd));
cf7f2e2d 265
5796c8dc
SS
266 *saved_fd = fd;
267 return make_cleanup_dtor (do_close_cleanup, saved_fd, xfree);
268}
269
270/* Helper function which does the work for make_cleanup_fclose. */
271
272static void
273do_fclose_cleanup (void *arg)
274{
275 FILE *file = arg;
cf7f2e2d
JM
276
277 fclose (file);
5796c8dc
SS
278}
279
280/* Return a new cleanup that closes FILE. */
281
282struct cleanup *
283make_cleanup_fclose (FILE *file)
284{
285 return make_cleanup (do_fclose_cleanup, file);
286}
287
288/* Helper function which does the work for make_cleanup_obstack_free. */
289
290static void
291do_obstack_free (void *arg)
292{
293 struct obstack *ob = arg;
cf7f2e2d 294
5796c8dc
SS
295 obstack_free (ob, NULL);
296}
297
298/* Return a new cleanup that frees OBSTACK. */
299
300struct cleanup *
301make_cleanup_obstack_free (struct obstack *obstack)
302{
303 return make_cleanup (do_obstack_free, obstack);
304}
305
306static void
307do_ui_file_delete (void *arg)
308{
309 ui_file_delete (arg);
310}
311
312struct cleanup *
313make_cleanup_ui_file_delete (struct ui_file *arg)
314{
ef5ccd6c 315 return make_cleanup (do_ui_file_delete, arg);
5796c8dc
SS
316}
317
c50c785c
JM
318/* Helper function for make_cleanup_ui_out_redirect_pop. */
319
320static void
321do_ui_out_redirect_pop (void *arg)
322{
323 struct ui_out *uiout = arg;
324
325 if (ui_out_redirect (uiout, NULL) < 0)
326 warning (_("Cannot restore redirection of the current output protocol"));
327}
328
329/* Return a new cleanup that pops the last redirection by ui_out_redirect
330 with NULL parameter. */
331
332struct cleanup *
333make_cleanup_ui_out_redirect_pop (struct ui_out *uiout)
334{
ef5ccd6c 335 return make_cleanup (do_ui_out_redirect_pop, uiout);
c50c785c
JM
336}
337
5796c8dc
SS
338static void
339do_free_section_addr_info (void *arg)
340{
341 free_section_addr_info (arg);
342}
343
344struct cleanup *
345make_cleanup_free_section_addr_info (struct section_addr_info *addrs)
346{
ef5ccd6c 347 return make_cleanup (do_free_section_addr_info, addrs);
5796c8dc
SS
348}
349
350struct restore_integer_closure
351{
352 int *variable;
353 int value;
354};
355
356static void
357restore_integer (void *p)
358{
359 struct restore_integer_closure *closure = p;
cf7f2e2d 360
5796c8dc
SS
361 *(closure->variable) = closure->value;
362}
363
c50c785c
JM
364/* Remember the current value of *VARIABLE and make it restored when
365 the cleanup is run. */
cf7f2e2d 366
5796c8dc
SS
367struct cleanup *
368make_cleanup_restore_integer (int *variable)
369{
370 struct restore_integer_closure *c =
371 xmalloc (sizeof (struct restore_integer_closure));
cf7f2e2d 372
5796c8dc
SS
373 c->variable = variable;
374 c->value = *variable;
375
ef5ccd6c 376 return make_cleanup_dtor (restore_integer, (void *) c, xfree);
5796c8dc
SS
377}
378
c50c785c
JM
379/* Remember the current value of *VARIABLE and make it restored when
380 the cleanup is run. */
cf7f2e2d
JM
381
382struct cleanup *
383make_cleanup_restore_uinteger (unsigned int *variable)
384{
385 return make_cleanup_restore_integer ((int *) variable);
386}
387
c50c785c
JM
388/* Helper for make_cleanup_unpush_target. */
389
390static void
391do_unpush_target (void *arg)
392{
393 struct target_ops *ops = arg;
394
395 unpush_target (ops);
396}
397
398/* Return a new cleanup that unpushes OPS. */
399
400struct cleanup *
401make_cleanup_unpush_target (struct target_ops *ops)
402{
ef5ccd6c 403 return make_cleanup (do_unpush_target, ops);
c50c785c
JM
404}
405
a45ae5f8
JM
406/* Helper for make_cleanup_htab_delete compile time checking the types. */
407
408static void
409do_htab_delete_cleanup (void *htab_voidp)
410{
411 htab_t htab = htab_voidp;
412
413 htab_delete (htab);
414}
415
416/* Return a new cleanup that deletes HTAB. */
417
418struct cleanup *
419make_cleanup_htab_delete (htab_t htab)
420{
421 return make_cleanup (do_htab_delete_cleanup, htab);
422}
423
cf7f2e2d
JM
424struct restore_ui_file_closure
425{
426 struct ui_file **variable;
427 struct ui_file *value;
428};
429
430static void
431do_restore_ui_file (void *p)
432{
433 struct restore_ui_file_closure *closure = p;
434
435 *(closure->variable) = closure->value;
436}
437
438/* Remember the current value of *VARIABLE and make it restored when
439 the cleanup is run. */
440
441struct cleanup *
442make_cleanup_restore_ui_file (struct ui_file **variable)
443{
444 struct restore_ui_file_closure *c = XNEW (struct restore_ui_file_closure);
445
446 c->variable = variable;
447 c->value = *variable;
448
449 return make_cleanup_dtor (do_restore_ui_file, (void *) c, xfree);
450}
451
a45ae5f8
JM
452/* Helper for make_cleanup_value_free_to_mark. */
453
454static void
455do_value_free_to_mark (void *value)
456{
457 value_free_to_mark ((struct value *) value);
458}
459
460/* Free all values allocated since MARK was obtained by value_mark
461 (except for those released) when the cleanup is run. */
462
463struct cleanup *
464make_cleanup_value_free_to_mark (struct value *mark)
465{
ef5ccd6c 466 return make_cleanup (do_value_free_to_mark, mark);
a45ae5f8
JM
467}
468
469/* Helper for make_cleanup_value_free. */
470
471static void
472do_value_free (void *value)
473{
474 value_free (value);
475}
476
477/* Free VALUE. */
478
479struct cleanup *
480make_cleanup_value_free (struct value *value)
481{
ef5ccd6c 482 return make_cleanup (do_value_free, value);
a45ae5f8
JM
483}
484
485/* Helper for make_cleanup_free_so. */
486
487static void
488do_free_so (void *arg)
489{
490 struct so_list *so = arg;
491
492 free_so (so);
493}
494
495/* Make cleanup handler calling free_so for SO. */
496
497struct cleanup *
498make_cleanup_free_so (struct so_list *so)
499{
ef5ccd6c 500 return make_cleanup (do_free_so, so);
5796c8dc
SS
501}
502
ef5ccd6c 503/* Helper for make_cleanup_restore_current_language. */
5796c8dc
SS
504
505static void
ef5ccd6c 506do_restore_current_language (void *p)
5796c8dc 507{
ef5ccd6c 508 enum language saved_lang = (uintptr_t) p;
cf7f2e2d 509
ef5ccd6c 510 set_language (saved_lang);
5796c8dc
SS
511}
512
ef5ccd6c
JM
513/* Remember the current value of CURRENT_LANGUAGE and make it restored when
514 the cleanup is run. */
5796c8dc
SS
515
516struct cleanup *
ef5ccd6c 517make_cleanup_restore_current_language (void)
5796c8dc 518{
ef5ccd6c 519 enum language saved_lang = current_language->la_language;
5796c8dc 520
ef5ccd6c
JM
521 return make_cleanup (do_restore_current_language,
522 (void *) (uintptr_t) saved_lang);
5796c8dc
SS
523}
524
525/* This function is useful for cleanups.
526 Do
527
528 foo = xmalloc (...);
529 old_chain = make_cleanup (free_current_contents, &foo);
530
531 to arrange to free the object thus allocated. */
532
533void
534free_current_contents (void *ptr)
535{
536 void **location = ptr;
cf7f2e2d 537
5796c8dc
SS
538 if (location == NULL)
539 internal_error (__FILE__, __LINE__,
540 _("free_current_contents: NULL pointer"));
541 if (*location != NULL)
542 {
543 xfree (*location);
544 *location = NULL;
545 }
546}
547
cf7f2e2d
JM
548/* If nonzero, display time usage both at startup and for each command. */
549
550static int display_time;
551
552/* If nonzero, display space usage both at startup and for each command. */
553
554static int display_space;
555
556/* Records a run time and space usage to be used as a base for
557 reporting elapsed time or change in space. In addition,
558 the msg_type field indicates whether the saved time is from the
559 beginning of GDB execution (0) or the beginning of an individual
560 command execution (1). */
561struct cmd_stats
562{
563 int msg_type;
a45ae5f8
JM
564 long start_cpu_time;
565 struct timeval start_wall_time;
cf7f2e2d
JM
566 long start_space;
567};
568
569/* Set whether to display time statistics to NEW_VALUE (non-zero
570 means true). */
571void
572set_display_time (int new_value)
573{
574 display_time = new_value;
575}
576
577/* Set whether to display space statistics to NEW_VALUE (non-zero
578 means true). */
579void
580set_display_space (int new_value)
581{
582 display_space = new_value;
583}
584
585/* As indicated by display_time and display_space, report GDB's elapsed time
586 and space usage from the base time and space provided in ARG, which
c50c785c
JM
587 must be a pointer to a struct cmd_stat. This function is intended
588 to be called as a cleanup. */
cf7f2e2d
JM
589static void
590report_command_stats (void *arg)
591{
592 struct cmd_stats *start_stats = (struct cmd_stats *) arg;
593 int msg_type = start_stats->msg_type;
594
595 if (display_time)
596 {
a45ae5f8
JM
597 long cmd_time = get_run_time () - start_stats->start_cpu_time;
598 struct timeval now_wall_time, delta_wall_time;
599
600 gettimeofday (&now_wall_time, NULL);
601 timeval_sub (&delta_wall_time,
602 &now_wall_time, &start_stats->start_wall_time);
cf7f2e2d 603
ef5ccd6c
JM
604 /* Subtract time spend in prompt_for_continue from walltime. */
605 timeval_sub (&delta_wall_time,
606 &delta_wall_time, &prompt_for_continue_wait_time);
607
cf7f2e2d 608 printf_unfiltered (msg_type == 0
a45ae5f8
JM
609 ? _("Startup time: %ld.%06ld (cpu), %ld.%06ld (wall)\n")
610 : _("Command execution time: %ld.%06ld (cpu), %ld.%06ld (wall)\n"),
611 cmd_time / 1000000, cmd_time % 1000000,
612 (long) delta_wall_time.tv_sec,
613 (long) delta_wall_time.tv_usec);
cf7f2e2d
JM
614 }
615
616 if (display_space)
617 {
618#ifdef HAVE_SBRK
619 char *lim = (char *) sbrk (0);
620
621 long space_now = lim - lim_at_start;
622 long space_diff = space_now - start_stats->start_space;
623
624 printf_unfiltered (msg_type == 0
c50c785c
JM
625 ? _("Space used: %ld (%s%ld during startup)\n")
626 : _("Space used: %ld (%s%ld for this command)\n"),
cf7f2e2d 627 space_now,
c50c785c 628 (space_diff >= 0 ? "+" : ""),
cf7f2e2d
JM
629 space_diff);
630#endif
631 }
632}
633
634/* Create a cleanup that reports time and space used since its
635 creation. Precise messages depend on MSG_TYPE:
636 0: Initial time/space
637 1: Individual command time/space. */
638struct cleanup *
639make_command_stats_cleanup (int msg_type)
640{
ef5ccd6c 641 static const struct timeval zero_timeval = { 0 };
cf7f2e2d
JM
642 struct cmd_stats *new_stat = XMALLOC (struct cmd_stats);
643
644#ifdef HAVE_SBRK
645 char *lim = (char *) sbrk (0);
646 new_stat->start_space = lim - lim_at_start;
647#endif
648
649 new_stat->msg_type = msg_type;
a45ae5f8
JM
650 new_stat->start_cpu_time = get_run_time ();
651 gettimeofday (&new_stat->start_wall_time, NULL);
cf7f2e2d 652
ef5ccd6c
JM
653 /* Initalize timer to keep track of how long we waited for the user. */
654 prompt_for_continue_wait_time = zero_timeval;
655
cf7f2e2d
JM
656 return make_cleanup_dtor (report_command_stats, new_stat, xfree);
657}
5796c8dc
SS
658\f
659
660
661/* Print a warning message. The first argument STRING is the warning
662 message, used as an fprintf format string, the second is the
663 va_list of arguments for that string. A warning is unfiltered (not
664 paginated) so that the user does not need to page through each
665 screen full of warnings when there are lots of them. */
666
667void
668vwarning (const char *string, va_list args)
669{
670 if (deprecated_warning_hook)
671 (*deprecated_warning_hook) (string, args);
672 else
673 {
674 target_terminal_ours ();
c50c785c 675 wrap_here (""); /* Force out any buffered output. */
5796c8dc
SS
676 gdb_flush (gdb_stdout);
677 if (warning_pre_print)
678 fputs_unfiltered (warning_pre_print, gdb_stderr);
679 vfprintf_unfiltered (gdb_stderr, string, args);
680 fprintf_unfiltered (gdb_stderr, "\n");
681 va_end (args);
682 }
683}
684
685/* Print a warning message.
686 The first argument STRING is the warning message, used as a fprintf string,
687 and the remaining args are passed as arguments to it.
688 The primary difference between warnings and errors is that a warning
689 does not force the return to command level. */
690
691void
692warning (const char *string, ...)
693{
694 va_list args;
cf7f2e2d 695
5796c8dc
SS
696 va_start (args, string);
697 vwarning (string, args);
698 va_end (args);
699}
700
701/* Print an error message and return to command level.
702 The first argument STRING is the error message, used as a fprintf string,
703 and the remaining args are passed as arguments to it. */
704
cf7f2e2d 705void
5796c8dc
SS
706verror (const char *string, va_list args)
707{
708 throw_verror (GENERIC_ERROR, string, args);
709}
710
cf7f2e2d 711void
5796c8dc
SS
712error (const char *string, ...)
713{
714 va_list args;
cf7f2e2d 715
5796c8dc
SS
716 va_start (args, string);
717 throw_verror (GENERIC_ERROR, string, args);
718 va_end (args);
719}
720
721/* Print an error message and quit.
722 The first argument STRING is the error message, used as a fprintf string,
723 and the remaining args are passed as arguments to it. */
724
cf7f2e2d 725void
5796c8dc
SS
726vfatal (const char *string, va_list args)
727{
728 throw_vfatal (string, args);
729}
730
cf7f2e2d 731void
5796c8dc
SS
732fatal (const char *string, ...)
733{
734 va_list args;
cf7f2e2d 735
5796c8dc
SS
736 va_start (args, string);
737 throw_vfatal (string, args);
738 va_end (args);
739}
740
cf7f2e2d 741void
5796c8dc
SS
742error_stream (struct ui_file *stream)
743{
744 char *message = ui_file_xstrdup (stream, NULL);
cf7f2e2d 745
5796c8dc
SS
746 make_cleanup (xfree, message);
747 error (("%s"), message);
748}
749
cf7f2e2d
JM
750/* Dump core trying to increase the core soft limit to hard limit first. */
751
752static void
753dump_core (void)
754{
755#ifdef HAVE_SETRLIMIT
756 struct rlimit rlim = { RLIM_INFINITY, RLIM_INFINITY };
757
758 setrlimit (RLIMIT_CORE, &rlim);
759#endif /* HAVE_SETRLIMIT */
760
761 abort (); /* NOTE: GDB has only three calls to abort(). */
762}
763
c50c785c
JM
764/* Check whether GDB will be able to dump core using the dump_core
765 function. */
cf7f2e2d
JM
766
767static int
768can_dump_core (const char *reason)
769{
770#ifdef HAVE_GETRLIMIT
771 struct rlimit rlim;
772
773 /* Be quiet and assume we can dump if an error is returned. */
774 if (getrlimit (RLIMIT_CORE, &rlim) != 0)
775 return 1;
776
777 if (rlim.rlim_max == 0)
778 {
779 fprintf_unfiltered (gdb_stderr,
c50c785c
JM
780 _("%s\nUnable to dump core, use `ulimit -c"
781 " unlimited' before executing GDB next time.\n"),
782 reason);
cf7f2e2d
JM
783 return 0;
784 }
785#endif /* HAVE_GETRLIMIT */
786
787 return 1;
788}
789
5796c8dc
SS
790/* Allow the user to configure the debugger behavior with respect to
791 what to do when an internal problem is detected. */
792
793const char internal_problem_ask[] = "ask";
794const char internal_problem_yes[] = "yes";
795const char internal_problem_no[] = "no";
ef5ccd6c 796static const char *const internal_problem_modes[] =
5796c8dc
SS
797{
798 internal_problem_ask,
799 internal_problem_yes,
800 internal_problem_no,
801 NULL
802};
5796c8dc 803
c50c785c 804/* Print a message reporting an internal error/warning. Ask the user
5796c8dc
SS
805 if they want to continue, dump core, or just exit. Return
806 something to indicate a quit. */
807
808struct internal_problem
809{
810 const char *name;
811 const char *should_quit;
812 const char *should_dump_core;
813};
814
815/* Report a problem, internal to GDB, to the user. Once the problem
816 has been reported, and assuming GDB didn't quit, the caller can
817 either allow execution to resume or throw an error. */
818
cf7f2e2d 819static void ATTRIBUTE_PRINTF (4, 0)
5796c8dc
SS
820internal_vproblem (struct internal_problem *problem,
821 const char *file, int line, const char *fmt, va_list ap)
822{
823 static int dejavu;
824 int quit_p;
825 int dump_core_p;
826 char *reason;
827
828 /* Don't allow infinite error/warning recursion. */
829 {
830 static char msg[] = "Recursive internal problem.\n";
cf7f2e2d 831
5796c8dc
SS
832 switch (dejavu)
833 {
834 case 0:
835 dejavu = 1;
836 break;
837 case 1:
838 dejavu = 2;
839 fputs_unfiltered (msg, gdb_stderr);
cf7f2e2d 840 abort (); /* NOTE: GDB has only three calls to abort(). */
5796c8dc
SS
841 default:
842 dejavu = 3;
843 /* Newer GLIBC versions put the warn_unused_result attribute
844 on write, but this is one of those rare cases where
845 ignoring the return value is correct. Casting to (void)
846 does not fix this problem. This is the solution suggested
847 at http://gcc.gnu.org/bugzilla/show_bug.cgi?id=25509. */
848 if (write (STDERR_FILENO, msg, sizeof (msg)) != sizeof (msg))
cf7f2e2d 849 abort (); /* NOTE: GDB has only three calls to abort(). */
5796c8dc
SS
850 exit (1);
851 }
852 }
853
854 /* Try to get the message out and at the start of a new line. */
855 target_terminal_ours ();
856 begin_line ();
857
858 /* Create a string containing the full error/warning message. Need
859 to call query with this full string, as otherwize the reason
860 (error/warning) and question become separated. Format using a
861 style similar to a compiler error message. Include extra detail
862 so that the user knows that they are living on the edge. */
863 {
864 char *msg;
cf7f2e2d 865
5796c8dc 866 msg = xstrvprintf (fmt, ap);
c50c785c
JM
867 reason = xstrprintf ("%s:%d: %s: %s\n"
868 "A problem internal to GDB has been detected,\n"
869 "further debugging may prove unreliable.",
870 file, line, problem->name, msg);
5796c8dc
SS
871 xfree (msg);
872 make_cleanup (xfree, reason);
873 }
874
875 if (problem->should_quit == internal_problem_ask)
876 {
877 /* Default (yes/batch case) is to quit GDB. When in batch mode
878 this lessens the likelihood of GDB going into an infinite
879 loop. */
ef5ccd6c 880 if (!confirm)
5796c8dc
SS
881 {
882 /* Emit the message and quit. */
883 fputs_unfiltered (reason, gdb_stderr);
884 fputs_unfiltered ("\n", gdb_stderr);
885 quit_p = 1;
886 }
887 else
888 quit_p = query (_("%s\nQuit this debugging session? "), reason);
889 }
890 else if (problem->should_quit == internal_problem_yes)
891 quit_p = 1;
892 else if (problem->should_quit == internal_problem_no)
893 quit_p = 0;
894 else
895 internal_error (__FILE__, __LINE__, _("bad switch"));
896
897 if (problem->should_dump_core == internal_problem_ask)
898 {
cf7f2e2d
JM
899 if (!can_dump_core (reason))
900 dump_core_p = 0;
901 else
902 {
903 /* Default (yes/batch case) is to dump core. This leaves a GDB
904 `dropping' so that it is easier to see that something went
905 wrong in GDB. */
906 dump_core_p = query (_("%s\nCreate a core file of GDB? "), reason);
907 }
5796c8dc
SS
908 }
909 else if (problem->should_dump_core == internal_problem_yes)
cf7f2e2d 910 dump_core_p = can_dump_core (reason);
5796c8dc
SS
911 else if (problem->should_dump_core == internal_problem_no)
912 dump_core_p = 0;
913 else
914 internal_error (__FILE__, __LINE__, _("bad switch"));
915
916 if (quit_p)
917 {
918 if (dump_core_p)
cf7f2e2d 919 dump_core ();
5796c8dc
SS
920 else
921 exit (1);
922 }
923 else
924 {
925 if (dump_core_p)
926 {
927#ifdef HAVE_WORKING_FORK
928 if (fork () == 0)
cf7f2e2d 929 dump_core ();
5796c8dc
SS
930#endif
931 }
932 }
933
934 dejavu = 0;
935}
936
937static struct internal_problem internal_error_problem = {
938 "internal-error", internal_problem_ask, internal_problem_ask
939};
940
cf7f2e2d 941void
5796c8dc
SS
942internal_verror (const char *file, int line, const char *fmt, va_list ap)
943{
944 internal_vproblem (&internal_error_problem, file, line, fmt, ap);
945 deprecated_throw_reason (RETURN_ERROR);
946}
947
cf7f2e2d 948void
5796c8dc
SS
949internal_error (const char *file, int line, const char *string, ...)
950{
951 va_list ap;
cf7f2e2d 952
5796c8dc
SS
953 va_start (ap, string);
954 internal_verror (file, line, string, ap);
955 va_end (ap);
956}
957
958static struct internal_problem internal_warning_problem = {
959 "internal-warning", internal_problem_ask, internal_problem_ask
960};
961
962void
963internal_vwarning (const char *file, int line, const char *fmt, va_list ap)
964{
965 internal_vproblem (&internal_warning_problem, file, line, fmt, ap);
966}
967
968void
969internal_warning (const char *file, int line, const char *string, ...)
970{
971 va_list ap;
cf7f2e2d 972
5796c8dc
SS
973 va_start (ap, string);
974 internal_vwarning (file, line, string, ap);
975 va_end (ap);
976}
977
978/* Dummy functions to keep add_prefix_cmd happy. */
979
980static void
981set_internal_problem_cmd (char *args, int from_tty)
982{
983}
984
985static void
986show_internal_problem_cmd (char *args, int from_tty)
987{
988}
989
990/* When GDB reports an internal problem (error or warning) it gives
991 the user the opportunity to quit GDB and/or create a core file of
992 the current debug session. This function registers a few commands
993 that make it possible to specify that GDB should always or never
994 quit or create a core file, without asking. The commands look
995 like:
996
997 maint set PROBLEM-NAME quit ask|yes|no
998 maint show PROBLEM-NAME quit
999 maint set PROBLEM-NAME corefile ask|yes|no
1000 maint show PROBLEM-NAME corefile
1001
1002 Where PROBLEM-NAME is currently "internal-error" or
1003 "internal-warning". */
1004
1005static void
1006add_internal_problem_command (struct internal_problem *problem)
1007{
1008 struct cmd_list_element **set_cmd_list;
1009 struct cmd_list_element **show_cmd_list;
1010 char *set_doc;
1011 char *show_doc;
1012
1013 set_cmd_list = xmalloc (sizeof (*set_cmd_list));
1014 show_cmd_list = xmalloc (sizeof (*set_cmd_list));
1015 *set_cmd_list = NULL;
1016 *show_cmd_list = NULL;
1017
1018 set_doc = xstrprintf (_("Configure what GDB does when %s is detected."),
1019 problem->name);
1020
1021 show_doc = xstrprintf (_("Show what GDB does when %s is detected."),
1022 problem->name);
1023
1024 add_prefix_cmd ((char*) problem->name,
1025 class_maintenance, set_internal_problem_cmd, set_doc,
1026 set_cmd_list,
cf7f2e2d
JM
1027 concat ("maintenance set ", problem->name, " ",
1028 (char *) NULL),
5796c8dc
SS
1029 0/*allow-unknown*/, &maintenance_set_cmdlist);
1030
1031 add_prefix_cmd ((char*) problem->name,
1032 class_maintenance, show_internal_problem_cmd, show_doc,
1033 show_cmd_list,
cf7f2e2d
JM
1034 concat ("maintenance show ", problem->name, " ",
1035 (char *) NULL),
5796c8dc
SS
1036 0/*allow-unknown*/, &maintenance_show_cmdlist);
1037
c50c785c
JM
1038 set_doc = xstrprintf (_("Set whether GDB should quit "
1039 "when an %s is detected"),
5796c8dc 1040 problem->name);
c50c785c
JM
1041 show_doc = xstrprintf (_("Show whether GDB will quit "
1042 "when an %s is detected"),
5796c8dc
SS
1043 problem->name);
1044 add_setshow_enum_cmd ("quit", class_maintenance,
1045 internal_problem_modes,
1046 &problem->should_quit,
1047 set_doc,
1048 show_doc,
1049 NULL, /* help_doc */
1050 NULL, /* setfunc */
1051 NULL, /* showfunc */
1052 set_cmd_list,
1053 show_cmd_list);
1054
1055 xfree (set_doc);
1056 xfree (show_doc);
1057
c50c785c
JM
1058 set_doc = xstrprintf (_("Set whether GDB should create a core "
1059 "file of GDB when %s is detected"),
5796c8dc 1060 problem->name);
c50c785c
JM
1061 show_doc = xstrprintf (_("Show whether GDB will create a core "
1062 "file of GDB when %s is detected"),
5796c8dc
SS
1063 problem->name);
1064 add_setshow_enum_cmd ("corefile", class_maintenance,
1065 internal_problem_modes,
1066 &problem->should_dump_core,
1067 set_doc,
1068 show_doc,
1069 NULL, /* help_doc */
1070 NULL, /* setfunc */
1071 NULL, /* showfunc */
1072 set_cmd_list,
1073 show_cmd_list);
1074
1075 xfree (set_doc);
1076 xfree (show_doc);
1077}
1078
1079/* Print the system error message for errno, and also mention STRING
ef5ccd6c
JM
1080 as the file name for which the error was encountered. Use ERRCODE
1081 for the thrown exception. Then return to command level. */
5796c8dc 1082
cf7f2e2d 1083void
ef5ccd6c 1084throw_perror_with_name (enum errors errcode, const char *string)
5796c8dc
SS
1085{
1086 char *err;
1087 char *combined;
1088
1089 err = safe_strerror (errno);
1090 combined = (char *) alloca (strlen (err) + strlen (string) + 3);
1091 strcpy (combined, string);
1092 strcat (combined, ": ");
1093 strcat (combined, err);
1094
1095 /* I understand setting these is a matter of taste. Still, some people
1096 may clear errno but not know about bfd_error. Doing this here is not
c50c785c 1097 unreasonable. */
5796c8dc
SS
1098 bfd_set_error (bfd_error_no_error);
1099 errno = 0;
1100
ef5ccd6c
JM
1101 throw_error (errcode, _("%s."), combined);
1102}
1103
1104/* See throw_perror_with_name, ERRCODE defaults here to GENERIC_ERROR. */
1105
1106void
1107perror_with_name (const char *string)
1108{
1109 throw_perror_with_name (GENERIC_ERROR, string);
5796c8dc
SS
1110}
1111
1112/* Print the system error message for ERRCODE, and also mention STRING
1113 as the file name for which the error was encountered. */
1114
1115void
1116print_sys_errmsg (const char *string, int errcode)
1117{
1118 char *err;
1119 char *combined;
1120
1121 err = safe_strerror (errcode);
1122 combined = (char *) alloca (strlen (err) + strlen (string) + 3);
1123 strcpy (combined, string);
1124 strcat (combined, ": ");
1125 strcat (combined, err);
1126
1127 /* We want anything which was printed on stdout to come out first, before
1128 this message. */
1129 gdb_flush (gdb_stdout);
1130 fprintf_unfiltered (gdb_stderr, "%s.\n", combined);
1131}
1132
1133/* Control C eventually causes this to be called, at a convenient time. */
1134
1135void
1136quit (void)
1137{
1138#ifdef __MSDOS__
1139 /* No steenking SIGINT will ever be coming our way when the
1140 program is resumed. Don't lie. */
1141 fatal ("Quit");
1142#else
1143 if (job_control
1144 /* If there is no terminal switching for this target, then we can't
1145 possibly get screwed by the lack of job control. */
1146 || current_target.to_terminal_ours == NULL)
1147 fatal ("Quit");
1148 else
1149 fatal ("Quit (expect signal SIGINT when the program is resumed)");
1150#endif
1151}
1152
1153\f
1154/* Called when a memory allocation fails, with the number of bytes of
c50c785c 1155 memory requested in SIZE. */
5796c8dc 1156
cf7f2e2d 1157void
a45ae5f8 1158malloc_failure (long size)
5796c8dc
SS
1159{
1160 if (size > 0)
1161 {
1162 internal_error (__FILE__, __LINE__,
1163 _("virtual memory exhausted: can't allocate %ld bytes."),
1164 size);
1165 }
1166 else
1167 {
1168 internal_error (__FILE__, __LINE__, _("virtual memory exhausted."));
1169 }
1170}
1171
5796c8dc
SS
1172/* My replacement for the read system call.
1173 Used like `read' but keeps going if `read' returns too soon. */
1174
1175int
1176myread (int desc, char *addr, int len)
1177{
1178 int val;
1179 int orglen = len;
1180
1181 while (len > 0)
1182 {
1183 val = read (desc, addr, len);
1184 if (val < 0)
1185 return val;
1186 if (val == 0)
1187 return orglen - len;
1188 len -= val;
1189 addr += val;
1190 }
1191 return orglen;
1192}
a45ae5f8 1193
5796c8dc
SS
1194void
1195print_spaces (int n, struct ui_file *file)
1196{
1197 fputs_unfiltered (n_spaces (n), file);
1198}
1199
1200/* Print a host address. */
1201
1202void
1203gdb_print_host_address (const void *addr, struct ui_file *stream)
1204{
1205 fprintf_filtered (stream, "%s", host_address_to_string (addr));
1206}
1207\f
1208
c50c785c
JM
1209/* A cleanup function that calls regfree. */
1210
1211static void
1212do_regfree_cleanup (void *r)
1213{
1214 regfree (r);
1215}
1216
1217/* Create a new cleanup that frees the compiled regular expression R. */
1218
1219struct cleanup *
1220make_regfree_cleanup (regex_t *r)
1221{
1222 return make_cleanup (do_regfree_cleanup, r);
1223}
1224
1225/* Return an xmalloc'd error message resulting from a regular
1226 expression compilation failure. */
1227
1228char *
1229get_regcomp_error (int code, regex_t *rx)
1230{
1231 size_t length = regerror (code, rx, NULL, 0);
1232 char *result = xmalloc (length);
1233
1234 regerror (code, rx, result, length);
1235 return result;
1236}
1237
1238\f
1239
5796c8dc
SS
1240/* This function supports the query, nquery, and yquery functions.
1241 Ask user a y-or-n question and return 0 if answer is no, 1 if
1242 answer is yes, or default the answer to the specified default
1243 (for yquery or nquery). DEFCHAR may be 'y' or 'n' to provide a
1244 default answer, or '\0' for no default.
1245 CTLSTR is the control string and should end in "? ". It should
1246 not say how to answer, because we do that.
1247 ARGS are the arguments passed along with the CTLSTR argument to
1248 printf. */
1249
cf7f2e2d 1250static int ATTRIBUTE_PRINTF (1, 0)
5796c8dc
SS
1251defaulted_query (const char *ctlstr, const char defchar, va_list args)
1252{
1253 int answer;
1254 int ans2;
1255 int retval;
1256 int def_value;
1257 char def_answer, not_def_answer;
1258 char *y_string, *n_string, *question;
ef5ccd6c
JM
1259 /* Used to add duration we waited for user to respond to
1260 prompt_for_continue_wait_time. */
1261 struct timeval prompt_started, prompt_ended, prompt_delta;
5796c8dc
SS
1262
1263 /* Set up according to which answer is the default. */
1264 if (defchar == '\0')
1265 {
1266 def_value = 1;
1267 def_answer = 'Y';
1268 not_def_answer = 'N';
1269 y_string = "y";
1270 n_string = "n";
1271 }
1272 else if (defchar == 'y')
1273 {
1274 def_value = 1;
1275 def_answer = 'Y';
1276 not_def_answer = 'N';
1277 y_string = "[y]";
1278 n_string = "n";
1279 }
1280 else
1281 {
1282 def_value = 0;
1283 def_answer = 'N';
1284 not_def_answer = 'Y';
1285 y_string = "y";
1286 n_string = "[n]";
1287 }
1288
1289 /* Automatically answer the default value if the user did not want
1290 prompts or the command was issued with the server prefix. */
ef5ccd6c 1291 if (!confirm || server_command)
5796c8dc
SS
1292 return def_value;
1293
1294 /* If input isn't coming from the user directly, just say what
1295 question we're asking, and then answer the default automatically. This
1296 way, important error messages don't get lost when talking to GDB
1297 over a pipe. */
1298 if (! input_from_terminal_p ())
1299 {
1300 wrap_here ("");
1301 vfprintf_filtered (gdb_stdout, ctlstr, args);
1302
c50c785c
JM
1303 printf_filtered (_("(%s or %s) [answered %c; "
1304 "input not from terminal]\n"),
5796c8dc
SS
1305 y_string, n_string, def_answer);
1306 gdb_flush (gdb_stdout);
1307
1308 return def_value;
1309 }
1310
1311 if (deprecated_query_hook)
1312 {
1313 return deprecated_query_hook (ctlstr, args);
1314 }
1315
1316 /* Format the question outside of the loop, to avoid reusing args. */
1317 question = xstrvprintf (ctlstr, args);
1318
ef5ccd6c
JM
1319 /* Used for calculating time spend waiting for user. */
1320 gettimeofday (&prompt_started, NULL);
1321
5796c8dc
SS
1322 while (1)
1323 {
c50c785c 1324 wrap_here (""); /* Flush any buffered output. */
5796c8dc
SS
1325 gdb_flush (gdb_stdout);
1326
1327 if (annotation_level > 1)
1328 printf_filtered (("\n\032\032pre-query\n"));
1329
1330 fputs_filtered (question, gdb_stdout);
1331 printf_filtered (_("(%s or %s) "), y_string, n_string);
1332
1333 if (annotation_level > 1)
1334 printf_filtered (("\n\032\032query\n"));
1335
1336 wrap_here ("");
1337 gdb_flush (gdb_stdout);
1338
1339 answer = fgetc (stdin);
1340
1341 /* We expect fgetc to block until a character is read. But
1342 this may not be the case if the terminal was opened with
1343 the NONBLOCK flag. In that case, if there is nothing to
1344 read on stdin, fgetc returns EOF, but also sets the error
1345 condition flag on stdin and errno to EAGAIN. With a true
1346 EOF, stdin's error condition flag is not set.
1347
1348 A situation where this behavior was observed is a pseudo
1349 terminal on AIX. */
1350 while (answer == EOF && ferror (stdin) && errno == EAGAIN)
1351 {
1352 /* Not a real EOF. Wait a little while and try again until
1353 we read something. */
1354 clearerr (stdin);
1355 gdb_usleep (10000);
1356 answer = fgetc (stdin);
1357 }
1358
1359 clearerr (stdin); /* in case of C-d */
1360 if (answer == EOF) /* C-d */
1361 {
1362 printf_filtered ("EOF [assumed %c]\n", def_answer);
1363 retval = def_value;
1364 break;
1365 }
c50c785c 1366 /* Eat rest of input line, to EOF or newline. */
5796c8dc
SS
1367 if (answer != '\n')
1368 do
1369 {
1370 ans2 = fgetc (stdin);
1371 clearerr (stdin);
1372 }
1373 while (ans2 != EOF && ans2 != '\n' && ans2 != '\r');
1374
1375 if (answer >= 'a')
1376 answer -= 040;
1377 /* Check answer. For the non-default, the user must specify
1378 the non-default explicitly. */
1379 if (answer == not_def_answer)
1380 {
1381 retval = !def_value;
1382 break;
1383 }
1384 /* Otherwise, if a default was specified, the user may either
1385 specify the required input or have it default by entering
1386 nothing. */
1387 if (answer == def_answer
1388 || (defchar != '\0' &&
1389 (answer == '\n' || answer == '\r' || answer == EOF)))
1390 {
1391 retval = def_value;
1392 break;
1393 }
1394 /* Invalid entries are not defaulted and require another selection. */
1395 printf_filtered (_("Please answer %s or %s.\n"),
1396 y_string, n_string);
1397 }
1398
ef5ccd6c
JM
1399 /* Add time spend in this routine to prompt_for_continue_wait_time. */
1400 gettimeofday (&prompt_ended, NULL);
1401 timeval_sub (&prompt_delta, &prompt_ended, &prompt_started);
1402 timeval_add (&prompt_for_continue_wait_time,
1403 &prompt_for_continue_wait_time, &prompt_delta);
1404
5796c8dc
SS
1405 xfree (question);
1406 if (annotation_level > 1)
1407 printf_filtered (("\n\032\032post-query\n"));
1408 return retval;
1409}
1410\f
1411
1412/* Ask user a y-or-n question and return 0 if answer is no, 1 if
1413 answer is yes, or 0 if answer is defaulted.
1414 Takes three args which are given to printf to print the question.
1415 The first, a control string, should end in "? ".
1416 It should not say how to answer, because we do that. */
1417
1418int
1419nquery (const char *ctlstr, ...)
1420{
1421 va_list args;
c50c785c 1422 int ret;
5796c8dc
SS
1423
1424 va_start (args, ctlstr);
c50c785c 1425 ret = defaulted_query (ctlstr, 'n', args);
5796c8dc 1426 va_end (args);
c50c785c 1427 return ret;
5796c8dc
SS
1428}
1429
1430/* Ask user a y-or-n question and return 0 if answer is no, 1 if
1431 answer is yes, or 1 if answer is defaulted.
1432 Takes three args which are given to printf to print the question.
1433 The first, a control string, should end in "? ".
1434 It should not say how to answer, because we do that. */
1435
1436int
1437yquery (const char *ctlstr, ...)
1438{
1439 va_list args;
c50c785c 1440 int ret;
5796c8dc
SS
1441
1442 va_start (args, ctlstr);
c50c785c 1443 ret = defaulted_query (ctlstr, 'y', args);
5796c8dc 1444 va_end (args);
c50c785c 1445 return ret;
5796c8dc
SS
1446}
1447
1448/* Ask user a y-or-n question and return 1 iff answer is yes.
1449 Takes three args which are given to printf to print the question.
1450 The first, a control string, should end in "? ".
1451 It should not say how to answer, because we do that. */
1452
1453int
1454query (const char *ctlstr, ...)
1455{
1456 va_list args;
c50c785c 1457 int ret;
5796c8dc
SS
1458
1459 va_start (args, ctlstr);
c50c785c 1460 ret = defaulted_query (ctlstr, '\0', args);
5796c8dc 1461 va_end (args);
c50c785c 1462 return ret;
5796c8dc
SS
1463}
1464
1465/* A helper for parse_escape that converts a host character to a
1466 target character. C is the host character. If conversion is
1467 possible, then the target character is stored in *TARGET_C and the
1468 function returns 1. Otherwise, the function returns 0. */
1469
1470static int
cf7f2e2d 1471host_char_to_target (struct gdbarch *gdbarch, int c, int *target_c)
5796c8dc
SS
1472{
1473 struct obstack host_data;
1474 char the_char = c;
1475 struct cleanup *cleanups;
1476 int result = 0;
1477
1478 obstack_init (&host_data);
1479 cleanups = make_cleanup_obstack_free (&host_data);
1480
cf7f2e2d 1481 convert_between_encodings (target_charset (gdbarch), host_charset (),
ef5ccd6c
JM
1482 (gdb_byte *) &the_char, 1, 1,
1483 &host_data, translit_none);
5796c8dc
SS
1484
1485 if (obstack_object_size (&host_data) == 1)
1486 {
1487 result = 1;
1488 *target_c = *(char *) obstack_base (&host_data);
1489 }
1490
1491 do_cleanups (cleanups);
1492 return result;
1493}
1494
1495/* Parse a C escape sequence. STRING_PTR points to a variable
1496 containing a pointer to the string to parse. That pointer
1497 should point to the character after the \. That pointer
1498 is updated past the characters we use. The value of the
1499 escape sequence is returned.
1500
1501 A negative value means the sequence \ newline was seen,
1502 which is supposed to be equivalent to nothing at all.
1503
1504 If \ is followed by a null character, we return a negative
1505 value and leave the string pointer pointing at the null character.
1506
1507 If \ is followed by 000, we return 0 and leave the string pointer
1508 after the zeros. A value of 0 does not mean end of string. */
1509
1510int
cf7f2e2d 1511parse_escape (struct gdbarch *gdbarch, char **string_ptr)
5796c8dc 1512{
c50c785c 1513 int target_char = -2; /* Initialize to avoid GCC warnings. */
5796c8dc 1514 int c = *(*string_ptr)++;
cf7f2e2d 1515
5796c8dc
SS
1516 switch (c)
1517 {
1518 case '\n':
1519 return -2;
1520 case 0:
1521 (*string_ptr)--;
1522 return 0;
1523
1524 case '0':
1525 case '1':
1526 case '2':
1527 case '3':
1528 case '4':
1529 case '5':
1530 case '6':
1531 case '7':
1532 {
1533 int i = host_hex_value (c);
1534 int count = 0;
1535 while (++count < 3)
1536 {
1537 c = (**string_ptr);
1538 if (isdigit (c) && c != '8' && c != '9')
1539 {
1540 (*string_ptr)++;
1541 i *= 8;
1542 i += host_hex_value (c);
1543 }
1544 else
1545 {
1546 break;
1547 }
1548 }
1549 return i;
1550 }
1551
1552 case 'a':
1553 c = '\a';
1554 break;
1555 case 'b':
1556 c = '\b';
1557 break;
1558 case 'f':
1559 c = '\f';
1560 break;
1561 case 'n':
1562 c = '\n';
1563 break;
1564 case 'r':
1565 c = '\r';
1566 break;
1567 case 't':
1568 c = '\t';
1569 break;
1570 case 'v':
1571 c = '\v';
1572 break;
1573
1574 default:
1575 break;
1576 }
1577
cf7f2e2d 1578 if (!host_char_to_target (gdbarch, c, &target_char))
c50c785c
JM
1579 error (_("The escape sequence `\\%c' is equivalent to plain `%c',"
1580 " which has no equivalent\nin the `%s' character set."),
1581 c, c, target_charset (gdbarch));
5796c8dc
SS
1582 return target_char;
1583}
1584\f
1585/* Print the character C on STREAM as part of the contents of a literal
1586 string whose delimiter is QUOTER. Note that this routine should only
1587 be call for printing things which are independent of the language
c50c785c 1588 of the program being debugged. */
5796c8dc
SS
1589
1590static void
1591printchar (int c, void (*do_fputs) (const char *, struct ui_file *),
1592 void (*do_fprintf) (struct ui_file *, const char *, ...)
1593 ATTRIBUTE_FPTR_PRINTF_2, struct ui_file *stream, int quoter)
1594{
5796c8dc
SS
1595 c &= 0xFF; /* Avoid sign bit follies */
1596
1597 if (c < 0x20 || /* Low control chars */
1598 (c >= 0x7F && c < 0xA0) || /* DEL, High controls */
1599 (sevenbit_strings && c >= 0x80))
1600 { /* high order bit set */
1601 switch (c)
1602 {
1603 case '\n':
1604 do_fputs ("\\n", stream);
1605 break;
1606 case '\b':
1607 do_fputs ("\\b", stream);
1608 break;
1609 case '\t':
1610 do_fputs ("\\t", stream);
1611 break;
1612 case '\f':
1613 do_fputs ("\\f", stream);
1614 break;
1615 case '\r':
1616 do_fputs ("\\r", stream);
1617 break;
1618 case '\033':
1619 do_fputs ("\\e", stream);
1620 break;
1621 case '\007':
1622 do_fputs ("\\a", stream);
1623 break;
1624 default:
1625 do_fprintf (stream, "\\%.3o", (unsigned int) c);
1626 break;
1627 }
1628 }
1629 else
1630 {
1631 if (c == '\\' || c == quoter)
1632 do_fputs ("\\", stream);
1633 do_fprintf (stream, "%c", c);
1634 }
1635}
1636
1637/* Print the character C on STREAM as part of the contents of a
1638 literal string whose delimiter is QUOTER. Note that these routines
1639 should only be call for printing things which are independent of
c50c785c 1640 the language of the program being debugged. */
5796c8dc
SS
1641
1642void
1643fputstr_filtered (const char *str, int quoter, struct ui_file *stream)
1644{
1645 while (*str)
1646 printchar (*str++, fputs_filtered, fprintf_filtered, stream, quoter);
1647}
1648
1649void
1650fputstr_unfiltered (const char *str, int quoter, struct ui_file *stream)
1651{
1652 while (*str)
1653 printchar (*str++, fputs_unfiltered, fprintf_unfiltered, stream, quoter);
1654}
1655
1656void
1657fputstrn_filtered (const char *str, int n, int quoter,
1658 struct ui_file *stream)
1659{
1660 int i;
cf7f2e2d 1661
5796c8dc
SS
1662 for (i = 0; i < n; i++)
1663 printchar (str[i], fputs_filtered, fprintf_filtered, stream, quoter);
1664}
1665
1666void
1667fputstrn_unfiltered (const char *str, int n, int quoter,
1668 struct ui_file *stream)
1669{
1670 int i;
cf7f2e2d 1671
5796c8dc
SS
1672 for (i = 0; i < n; i++)
1673 printchar (str[i], fputs_unfiltered, fprintf_unfiltered, stream, quoter);
1674}
1675\f
1676
1677/* Number of lines per page or UINT_MAX if paging is disabled. */
1678static unsigned int lines_per_page;
1679static void
1680show_lines_per_page (struct ui_file *file, int from_tty,
1681 struct cmd_list_element *c, const char *value)
1682{
c50c785c
JM
1683 fprintf_filtered (file,
1684 _("Number of lines gdb thinks are in a page is %s.\n"),
5796c8dc
SS
1685 value);
1686}
1687
1688/* Number of chars per line or UINT_MAX if line folding is disabled. */
1689static unsigned int chars_per_line;
1690static void
1691show_chars_per_line (struct ui_file *file, int from_tty,
1692 struct cmd_list_element *c, const char *value)
1693{
c50c785c
JM
1694 fprintf_filtered (file,
1695 _("Number of characters gdb thinks "
1696 "are in a line is %s.\n"),
5796c8dc
SS
1697 value);
1698}
1699
1700/* Current count of lines printed on this page, chars on this line. */
1701static unsigned int lines_printed, chars_printed;
1702
1703/* Buffer and start column of buffered text, for doing smarter word-
1704 wrapping. When someone calls wrap_here(), we start buffering output
1705 that comes through fputs_filtered(). If we see a newline, we just
1706 spit it out and forget about the wrap_here(). If we see another
1707 wrap_here(), we spit it out and remember the newer one. If we see
1708 the end of the line, we spit out a newline, the indent, and then
1709 the buffered output. */
1710
1711/* Malloc'd buffer with chars_per_line+2 bytes. Contains characters which
1712 are waiting to be output (they have already been counted in chars_printed).
1713 When wrap_buffer[0] is null, the buffer is empty. */
1714static char *wrap_buffer;
1715
1716/* Pointer in wrap_buffer to the next character to fill. */
1717static char *wrap_pointer;
1718
1719/* String to indent by if the wrap occurs. Must not be NULL if wrap_column
1720 is non-zero. */
1721static char *wrap_indent;
1722
1723/* Column number on the screen where wrap_buffer begins, or 0 if wrapping
1724 is not in effect. */
1725static int wrap_column;
1726\f
1727
1728/* Inialize the number of lines per page and chars per line. */
1729
1730void
1731init_page_info (void)
1732{
cf7f2e2d
JM
1733 if (batch_flag)
1734 {
1735 lines_per_page = UINT_MAX;
1736 chars_per_line = UINT_MAX;
1737 }
1738 else
5796c8dc
SS
1739#if defined(TUI)
1740 if (!tui_get_command_dimension (&chars_per_line, &lines_per_page))
1741#endif
1742 {
1743 int rows, cols;
1744
1745#if defined(__GO32__)
1746 rows = ScreenRows ();
1747 cols = ScreenCols ();
1748 lines_per_page = rows;
1749 chars_per_line = cols;
1750#else
1751 /* Make sure Readline has initialized its terminal settings. */
1752 rl_reset_terminal (NULL);
1753
1754 /* Get the screen size from Readline. */
1755 rl_get_screen_size (&rows, &cols);
1756 lines_per_page = rows;
1757 chars_per_line = cols;
1758
1759 /* Readline should have fetched the termcap entry for us. */
1760 if (tgetnum ("li") < 0 || getenv ("EMACS"))
1761 {
1762 /* The number of lines per page is not mentioned in the
1763 terminal description. This probably means that paging is
1764 not useful (e.g. emacs shell window), so disable paging. */
1765 lines_per_page = UINT_MAX;
1766 }
1767
5796c8dc
SS
1768 /* If the output is not a terminal, don't paginate it. */
1769 if (!ui_file_isatty (gdb_stdout))
1770 lines_per_page = UINT_MAX;
1771#endif
1772 }
1773
1774 set_screen_size ();
1775 set_width ();
1776}
1777
cf7f2e2d
JM
1778/* Helper for make_cleanup_restore_page_info. */
1779
1780static void
1781do_restore_page_info_cleanup (void *arg)
1782{
1783 set_screen_size ();
1784 set_width ();
1785}
1786
1787/* Provide cleanup for restoring the terminal size. */
1788
1789struct cleanup *
1790make_cleanup_restore_page_info (void)
1791{
1792 struct cleanup *back_to;
1793
1794 back_to = make_cleanup (do_restore_page_info_cleanup, NULL);
1795 make_cleanup_restore_uinteger (&lines_per_page);
1796 make_cleanup_restore_uinteger (&chars_per_line);
1797
1798 return back_to;
1799}
1800
1801/* Temporarily set BATCH_FLAG and the associated unlimited terminal size.
1802 Provide cleanup for restoring the original state. */
1803
1804struct cleanup *
1805set_batch_flag_and_make_cleanup_restore_page_info (void)
1806{
1807 struct cleanup *back_to = make_cleanup_restore_page_info ();
1808
1809 make_cleanup_restore_integer (&batch_flag);
1810 batch_flag = 1;
1811 init_page_info ();
1812
1813 return back_to;
1814}
1815
5796c8dc
SS
1816/* Set the screen size based on LINES_PER_PAGE and CHARS_PER_LINE. */
1817
1818static void
1819set_screen_size (void)
1820{
1821 int rows = lines_per_page;
1822 int cols = chars_per_line;
1823
1824 if (rows <= 0)
1825 rows = INT_MAX;
1826
1827 if (cols <= 0)
1828 cols = INT_MAX;
1829
1830 /* Update Readline's idea of the terminal size. */
1831 rl_set_screen_size (rows, cols);
1832}
1833
1834/* Reinitialize WRAP_BUFFER according to the current value of
1835 CHARS_PER_LINE. */
1836
1837static void
1838set_width (void)
1839{
1840 if (chars_per_line == 0)
1841 init_page_info ();
1842
1843 if (!wrap_buffer)
1844 {
1845 wrap_buffer = (char *) xmalloc (chars_per_line + 2);
1846 wrap_buffer[0] = '\0';
1847 }
1848 else
1849 wrap_buffer = (char *) xrealloc (wrap_buffer, chars_per_line + 2);
1850 wrap_pointer = wrap_buffer; /* Start it at the beginning. */
1851}
1852
1853static void
1854set_width_command (char *args, int from_tty, struct cmd_list_element *c)
1855{
1856 set_screen_size ();
1857 set_width ();
1858}
1859
1860static void
1861set_height_command (char *args, int from_tty, struct cmd_list_element *c)
1862{
1863 set_screen_size ();
1864}
1865
1866/* Wait, so the user can read what's on the screen. Prompt the user
1867 to continue by pressing RETURN. */
1868
1869static void
1870prompt_for_continue (void)
1871{
1872 char *ignore;
1873 char cont_prompt[120];
ef5ccd6c
JM
1874 /* Used to add duration we waited for user to respond to
1875 prompt_for_continue_wait_time. */
1876 struct timeval prompt_started, prompt_ended, prompt_delta;
1877
1878 gettimeofday (&prompt_started, NULL);
5796c8dc
SS
1879
1880 if (annotation_level > 1)
1881 printf_unfiltered (("\n\032\032pre-prompt-for-continue\n"));
1882
1883 strcpy (cont_prompt,
1884 "---Type <return> to continue, or q <return> to quit---");
1885 if (annotation_level > 1)
1886 strcat (cont_prompt, "\n\032\032prompt-for-continue\n");
1887
1888 /* We must do this *before* we call gdb_readline, else it will eventually
1889 call us -- thinking that we're trying to print beyond the end of the
1890 screen. */
1891 reinitialize_more_filter ();
1892
1893 immediate_quit++;
ef5ccd6c 1894 QUIT;
5796c8dc
SS
1895 /* On a real operating system, the user can quit with SIGINT.
1896 But not on GO32.
1897
1898 'q' is provided on all systems so users don't have to change habits
1899 from system to system, and because telling them what to do in
1900 the prompt is more user-friendly than expecting them to think of
1901 SIGINT. */
1902 /* Call readline, not gdb_readline, because GO32 readline handles control-C
1903 whereas control-C to gdb_readline will cause the user to get dumped
1904 out to DOS. */
1905 ignore = gdb_readline_wrapper (cont_prompt);
1906
ef5ccd6c
JM
1907 /* Add time spend in this routine to prompt_for_continue_wait_time. */
1908 gettimeofday (&prompt_ended, NULL);
1909 timeval_sub (&prompt_delta, &prompt_ended, &prompt_started);
1910 timeval_add (&prompt_for_continue_wait_time,
1911 &prompt_for_continue_wait_time, &prompt_delta);
1912
5796c8dc
SS
1913 if (annotation_level > 1)
1914 printf_unfiltered (("\n\032\032post-prompt-for-continue\n"));
1915
1916 if (ignore)
1917 {
1918 char *p = ignore;
cf7f2e2d 1919
5796c8dc
SS
1920 while (*p == ' ' || *p == '\t')
1921 ++p;
1922 if (p[0] == 'q')
ef5ccd6c 1923 quit ();
5796c8dc
SS
1924 xfree (ignore);
1925 }
1926 immediate_quit--;
1927
1928 /* Now we have to do this again, so that GDB will know that it doesn't
1929 need to save the ---Type <return>--- line at the top of the screen. */
1930 reinitialize_more_filter ();
1931
c50c785c 1932 dont_repeat (); /* Forget prev cmd -- CR won't repeat it. */
5796c8dc
SS
1933}
1934
1935/* Reinitialize filter; ie. tell it to reset to original values. */
1936
1937void
1938reinitialize_more_filter (void)
1939{
1940 lines_printed = 0;
1941 chars_printed = 0;
1942}
1943
1944/* Indicate that if the next sequence of characters overflows the line,
c50c785c 1945 a newline should be inserted here rather than when it hits the end.
5796c8dc
SS
1946 If INDENT is non-null, it is a string to be printed to indent the
1947 wrapped part on the next line. INDENT must remain accessible until
1948 the next call to wrap_here() or until a newline is printed through
1949 fputs_filtered().
1950
1951 If the line is already overfull, we immediately print a newline and
1952 the indentation, and disable further wrapping.
1953
1954 If we don't know the width of lines, but we know the page height,
1955 we must not wrap words, but should still keep track of newlines
1956 that were explicitly printed.
1957
1958 INDENT should not contain tabs, as that will mess up the char count
1959 on the next line. FIXME.
1960
1961 This routine is guaranteed to force out any output which has been
1962 squirreled away in the wrap_buffer, so wrap_here ((char *)0) can be
1963 used to force out output from the wrap_buffer. */
1964
1965void
1966wrap_here (char *indent)
1967{
c50c785c 1968 /* This should have been allocated, but be paranoid anyway. */
5796c8dc 1969 if (!wrap_buffer)
c50c785c
JM
1970 internal_error (__FILE__, __LINE__,
1971 _("failed internal consistency check"));
5796c8dc
SS
1972
1973 if (wrap_buffer[0])
1974 {
1975 *wrap_pointer = '\0';
1976 fputs_unfiltered (wrap_buffer, gdb_stdout);
1977 }
1978 wrap_pointer = wrap_buffer;
1979 wrap_buffer[0] = '\0';
c50c785c 1980 if (chars_per_line == UINT_MAX) /* No line overflow checking. */
5796c8dc
SS
1981 {
1982 wrap_column = 0;
1983 }
1984 else if (chars_printed >= chars_per_line)
1985 {
1986 puts_filtered ("\n");
1987 if (indent != NULL)
1988 puts_filtered (indent);
1989 wrap_column = 0;
1990 }
1991 else
1992 {
1993 wrap_column = chars_printed;
1994 if (indent == NULL)
1995 wrap_indent = "";
1996 else
1997 wrap_indent = indent;
1998 }
1999}
2000
2001/* Print input string to gdb_stdout, filtered, with wrap,
c50c785c 2002 arranging strings in columns of n chars. String can be
5796c8dc
SS
2003 right or left justified in the column. Never prints
2004 trailing spaces. String should never be longer than
2005 width. FIXME: this could be useful for the EXAMINE
c50c785c 2006 command, which currently doesn't tabulate very well. */
5796c8dc
SS
2007
2008void
2009puts_filtered_tabular (char *string, int width, int right)
2010{
2011 int spaces = 0;
2012 int stringlen;
2013 char *spacebuf;
2014
2015 gdb_assert (chars_per_line > 0);
2016 if (chars_per_line == UINT_MAX)
2017 {
2018 fputs_filtered (string, gdb_stdout);
2019 fputs_filtered ("\n", gdb_stdout);
2020 return;
2021 }
2022
2023 if (((chars_printed - 1) / width + 2) * width >= chars_per_line)
2024 fputs_filtered ("\n", gdb_stdout);
2025
2026 if (width >= chars_per_line)
2027 width = chars_per_line - 1;
2028
2029 stringlen = strlen (string);
2030
2031 if (chars_printed > 0)
2032 spaces = width - (chars_printed - 1) % width - 1;
2033 if (right)
2034 spaces += width - stringlen;
2035
2036 spacebuf = alloca (spaces + 1);
2037 spacebuf[spaces] = '\0';
2038 while (spaces--)
2039 spacebuf[spaces] = ' ';
2040
2041 fputs_filtered (spacebuf, gdb_stdout);
2042 fputs_filtered (string, gdb_stdout);
2043}
2044
2045
2046/* Ensure that whatever gets printed next, using the filtered output
c50c785c 2047 commands, starts at the beginning of the line. I.e. if there is
5796c8dc 2048 any pending output for the current line, flush it and start a new
c50c785c 2049 line. Otherwise do nothing. */
5796c8dc
SS
2050
2051void
2052begin_line (void)
2053{
2054 if (chars_printed > 0)
2055 {
2056 puts_filtered ("\n");
2057 }
2058}
2059
2060
2061/* Like fputs but if FILTER is true, pause after every screenful.
2062
2063 Regardless of FILTER can wrap at points other than the final
2064 character of a line.
2065
2066 Unlike fputs, fputs_maybe_filtered does not return a value.
2067 It is OK for LINEBUFFER to be NULL, in which case just don't print
2068 anything.
2069
2070 Note that a longjmp to top level may occur in this routine (only if
2071 FILTER is true) (since prompt_for_continue may do so) so this
2072 routine should not be called when cleanups are not in place. */
2073
2074static void
2075fputs_maybe_filtered (const char *linebuffer, struct ui_file *stream,
2076 int filter)
2077{
2078 const char *lineptr;
2079
2080 if (linebuffer == 0)
2081 return;
2082
2083 /* Don't do any filtering if it is disabled. */
cf7f2e2d 2084 if (stream != gdb_stdout
a45ae5f8
JM
2085 || !pagination_enabled
2086 || batch_flag
cf7f2e2d
JM
2087 || (lines_per_page == UINT_MAX && chars_per_line == UINT_MAX)
2088 || top_level_interpreter () == NULL
2089 || ui_out_is_mi_like_p (interp_ui_out (top_level_interpreter ())))
5796c8dc
SS
2090 {
2091 fputs_unfiltered (linebuffer, stream);
2092 return;
2093 }
2094
2095 /* Go through and output each character. Show line extension
2096 when this is necessary; prompt user for new page when this is
2097 necessary. */
2098
2099 lineptr = linebuffer;
2100 while (*lineptr)
2101 {
2102 /* Possible new page. */
2103 if (filter && (lines_printed >= lines_per_page - 1))
2104 prompt_for_continue ();
2105
2106 while (*lineptr && *lineptr != '\n')
2107 {
2108 /* Print a single line. */
2109 if (*lineptr == '\t')
2110 {
2111 if (wrap_column)
2112 *wrap_pointer++ = '\t';
2113 else
2114 fputc_unfiltered ('\t', stream);
2115 /* Shifting right by 3 produces the number of tab stops
2116 we have already passed, and then adding one and
2117 shifting left 3 advances to the next tab stop. */
2118 chars_printed = ((chars_printed >> 3) + 1) << 3;
2119 lineptr++;
2120 }
2121 else
2122 {
2123 if (wrap_column)
2124 *wrap_pointer++ = *lineptr;
2125 else
2126 fputc_unfiltered (*lineptr, stream);
2127 chars_printed++;
2128 lineptr++;
2129 }
2130
2131 if (chars_printed >= chars_per_line)
2132 {
2133 unsigned int save_chars = chars_printed;
2134
2135 chars_printed = 0;
2136 lines_printed++;
2137 /* If we aren't actually wrapping, don't output newline --
2138 if chars_per_line is right, we probably just overflowed
2139 anyway; if it's wrong, let us keep going. */
2140 if (wrap_column)
2141 fputc_unfiltered ('\n', stream);
2142
2143 /* Possible new page. */
2144 if (lines_printed >= lines_per_page - 1)
2145 prompt_for_continue ();
2146
c50c785c 2147 /* Now output indentation and wrapped string. */
5796c8dc
SS
2148 if (wrap_column)
2149 {
2150 fputs_unfiltered (wrap_indent, stream);
c50c785c
JM
2151 *wrap_pointer = '\0'; /* Null-terminate saved stuff, */
2152 fputs_unfiltered (wrap_buffer, stream); /* and eject it. */
5796c8dc
SS
2153 /* FIXME, this strlen is what prevents wrap_indent from
2154 containing tabs. However, if we recurse to print it
2155 and count its chars, we risk trouble if wrap_indent is
c50c785c 2156 longer than (the user settable) chars_per_line.
5796c8dc
SS
2157 Note also that this can set chars_printed > chars_per_line
2158 if we are printing a long string. */
2159 chars_printed = strlen (wrap_indent)
2160 + (save_chars - wrap_column);
2161 wrap_pointer = wrap_buffer; /* Reset buffer */
2162 wrap_buffer[0] = '\0';
2163 wrap_column = 0; /* And disable fancy wrap */
2164 }
2165 }
2166 }
2167
2168 if (*lineptr == '\n')
2169 {
2170 chars_printed = 0;
c50c785c
JM
2171 wrap_here ((char *) 0); /* Spit out chars, cancel
2172 further wraps. */
5796c8dc
SS
2173 lines_printed++;
2174 fputc_unfiltered ('\n', stream);
2175 lineptr++;
2176 }
2177 }
2178}
2179
2180void
2181fputs_filtered (const char *linebuffer, struct ui_file *stream)
2182{
2183 fputs_maybe_filtered (linebuffer, stream, 1);
2184}
2185
2186int
2187putchar_unfiltered (int c)
2188{
2189 char buf = c;
cf7f2e2d 2190
5796c8dc
SS
2191 ui_file_write (gdb_stdout, &buf, 1);
2192 return c;
2193}
2194
2195/* Write character C to gdb_stdout using GDB's paging mechanism and return C.
2196 May return nonlocally. */
2197
2198int
2199putchar_filtered (int c)
2200{
2201 return fputc_filtered (c, gdb_stdout);
2202}
2203
2204int
2205fputc_unfiltered (int c, struct ui_file *stream)
2206{
2207 char buf = c;
cf7f2e2d 2208
5796c8dc
SS
2209 ui_file_write (stream, &buf, 1);
2210 return c;
2211}
2212
2213int
2214fputc_filtered (int c, struct ui_file *stream)
2215{
2216 char buf[2];
2217
2218 buf[0] = c;
2219 buf[1] = 0;
2220 fputs_filtered (buf, stream);
2221 return c;
2222}
2223
2224/* puts_debug is like fputs_unfiltered, except it prints special
2225 characters in printable fashion. */
2226
2227void
2228puts_debug (char *prefix, char *string, char *suffix)
2229{
2230 int ch;
2231
2232 /* Print prefix and suffix after each line. */
2233 static int new_line = 1;
2234 static int return_p = 0;
2235 static char *prev_prefix = "";
2236 static char *prev_suffix = "";
2237
2238 if (*string == '\n')
2239 return_p = 0;
2240
2241 /* If the prefix is changing, print the previous suffix, a new line,
2242 and the new prefix. */
2243 if ((return_p || (strcmp (prev_prefix, prefix) != 0)) && !new_line)
2244 {
2245 fputs_unfiltered (prev_suffix, gdb_stdlog);
2246 fputs_unfiltered ("\n", gdb_stdlog);
2247 fputs_unfiltered (prefix, gdb_stdlog);
2248 }
2249
2250 /* Print prefix if we printed a newline during the previous call. */
2251 if (new_line)
2252 {
2253 new_line = 0;
2254 fputs_unfiltered (prefix, gdb_stdlog);
2255 }
2256
2257 prev_prefix = prefix;
2258 prev_suffix = suffix;
2259
2260 /* Output characters in a printable format. */
2261 while ((ch = *string++) != '\0')
2262 {
2263 switch (ch)
2264 {
2265 default:
2266 if (isprint (ch))
2267 fputc_unfiltered (ch, gdb_stdlog);
2268
2269 else
2270 fprintf_unfiltered (gdb_stdlog, "\\x%02x", ch & 0xff);
2271 break;
2272
2273 case '\\':
2274 fputs_unfiltered ("\\\\", gdb_stdlog);
2275 break;
2276 case '\b':
2277 fputs_unfiltered ("\\b", gdb_stdlog);
2278 break;
2279 case '\f':
2280 fputs_unfiltered ("\\f", gdb_stdlog);
2281 break;
2282 case '\n':
2283 new_line = 1;
2284 fputs_unfiltered ("\\n", gdb_stdlog);
2285 break;
2286 case '\r':
2287 fputs_unfiltered ("\\r", gdb_stdlog);
2288 break;
2289 case '\t':
2290 fputs_unfiltered ("\\t", gdb_stdlog);
2291 break;
2292 case '\v':
2293 fputs_unfiltered ("\\v", gdb_stdlog);
2294 break;
2295 }
2296
2297 return_p = ch == '\r';
2298 }
2299
2300 /* Print suffix if we printed a newline. */
2301 if (new_line)
2302 {
2303 fputs_unfiltered (suffix, gdb_stdlog);
2304 fputs_unfiltered ("\n", gdb_stdlog);
2305 }
2306}
2307
2308
2309/* Print a variable number of ARGS using format FORMAT. If this
2310 information is going to put the amount written (since the last call
2311 to REINITIALIZE_MORE_FILTER or the last page break) over the page size,
2312 call prompt_for_continue to get the users permision to continue.
2313
2314 Unlike fprintf, this function does not return a value.
2315
2316 We implement three variants, vfprintf (takes a vararg list and stream),
2317 fprintf (takes a stream to write on), and printf (the usual).
2318
2319 Note also that a longjmp to top level may occur in this routine
2320 (since prompt_for_continue may do so) so this routine should not be
2321 called when cleanups are not in place. */
2322
2323static void
2324vfprintf_maybe_filtered (struct ui_file *stream, const char *format,
2325 va_list args, int filter)
2326{
2327 char *linebuffer;
2328 struct cleanup *old_cleanups;
2329
2330 linebuffer = xstrvprintf (format, args);
2331 old_cleanups = make_cleanup (xfree, linebuffer);
2332 fputs_maybe_filtered (linebuffer, stream, filter);
2333 do_cleanups (old_cleanups);
2334}
2335
2336
2337void
2338vfprintf_filtered (struct ui_file *stream, const char *format, va_list args)
2339{
2340 vfprintf_maybe_filtered (stream, format, args, 1);
2341}
2342
2343void
2344vfprintf_unfiltered (struct ui_file *stream, const char *format, va_list args)
2345{
2346 char *linebuffer;
2347 struct cleanup *old_cleanups;
2348
2349 linebuffer = xstrvprintf (format, args);
2350 old_cleanups = make_cleanup (xfree, linebuffer);
2351 if (debug_timestamp && stream == gdb_stdlog)
2352 {
2353 struct timeval tm;
2354 char *timestamp;
2355 int len, need_nl;
2356
2357 gettimeofday (&tm, NULL);
2358
2359 len = strlen (linebuffer);
2360 need_nl = (len > 0 && linebuffer[len - 1] != '\n');
2361
2362 timestamp = xstrprintf ("%ld:%ld %s%s",
2363 (long) tm.tv_sec, (long) tm.tv_usec,
2364 linebuffer,
2365 need_nl ? "\n": "");
2366 make_cleanup (xfree, timestamp);
2367 fputs_unfiltered (timestamp, stream);
2368 }
2369 else
2370 fputs_unfiltered (linebuffer, stream);
2371 do_cleanups (old_cleanups);
2372}
2373
2374void
2375vprintf_filtered (const char *format, va_list args)
2376{
2377 vfprintf_maybe_filtered (gdb_stdout, format, args, 1);
2378}
2379
2380void
2381vprintf_unfiltered (const char *format, va_list args)
2382{
2383 vfprintf_unfiltered (gdb_stdout, format, args);
2384}
2385
2386void
2387fprintf_filtered (struct ui_file *stream, const char *format, ...)
2388{
2389 va_list args;
cf7f2e2d 2390
5796c8dc
SS
2391 va_start (args, format);
2392 vfprintf_filtered (stream, format, args);
2393 va_end (args);
2394}
2395
2396void
2397fprintf_unfiltered (struct ui_file *stream, const char *format, ...)
2398{
2399 va_list args;
cf7f2e2d 2400
5796c8dc
SS
2401 va_start (args, format);
2402 vfprintf_unfiltered (stream, format, args);
2403 va_end (args);
2404}
2405
2406/* Like fprintf_filtered, but prints its result indented.
2407 Called as fprintfi_filtered (spaces, stream, format, ...); */
2408
2409void
2410fprintfi_filtered (int spaces, struct ui_file *stream, const char *format,
2411 ...)
2412{
2413 va_list args;
cf7f2e2d 2414
5796c8dc
SS
2415 va_start (args, format);
2416 print_spaces_filtered (spaces, stream);
2417
2418 vfprintf_filtered (stream, format, args);
2419 va_end (args);
2420}
2421
2422
2423void
2424printf_filtered (const char *format, ...)
2425{
2426 va_list args;
cf7f2e2d 2427
5796c8dc
SS
2428 va_start (args, format);
2429 vfprintf_filtered (gdb_stdout, format, args);
2430 va_end (args);
2431}
2432
2433
2434void
2435printf_unfiltered (const char *format, ...)
2436{
2437 va_list args;
cf7f2e2d 2438
5796c8dc
SS
2439 va_start (args, format);
2440 vfprintf_unfiltered (gdb_stdout, format, args);
2441 va_end (args);
2442}
2443
2444/* Like printf_filtered, but prints it's result indented.
2445 Called as printfi_filtered (spaces, format, ...); */
2446
2447void
2448printfi_filtered (int spaces, const char *format, ...)
2449{
2450 va_list args;
cf7f2e2d 2451
5796c8dc
SS
2452 va_start (args, format);
2453 print_spaces_filtered (spaces, gdb_stdout);
2454 vfprintf_filtered (gdb_stdout, format, args);
2455 va_end (args);
2456}
2457
2458/* Easy -- but watch out!
2459
2460 This routine is *not* a replacement for puts()! puts() appends a newline.
2461 This one doesn't, and had better not! */
2462
2463void
2464puts_filtered (const char *string)
2465{
2466 fputs_filtered (string, gdb_stdout);
2467}
2468
2469void
2470puts_unfiltered (const char *string)
2471{
2472 fputs_unfiltered (string, gdb_stdout);
2473}
2474
2475/* Return a pointer to N spaces and a null. The pointer is good
2476 until the next call to here. */
2477char *
2478n_spaces (int n)
2479{
2480 char *t;
2481 static char *spaces = 0;
2482 static int max_spaces = -1;
2483
2484 if (n > max_spaces)
2485 {
2486 if (spaces)
2487 xfree (spaces);
2488 spaces = (char *) xmalloc (n + 1);
2489 for (t = spaces + n; t != spaces;)
2490 *--t = ' ';
2491 spaces[n] = '\0';
2492 max_spaces = n;
2493 }
2494
2495 return spaces + max_spaces - n;
2496}
2497
2498/* Print N spaces. */
2499void
2500print_spaces_filtered (int n, struct ui_file *stream)
2501{
2502 fputs_filtered (n_spaces (n), stream);
2503}
2504\f
2505/* C++/ObjC demangler stuff. */
2506
2507/* fprintf_symbol_filtered attempts to demangle NAME, a symbol in language
2508 LANG, using demangling args ARG_MODE, and print it filtered to STREAM.
2509 If the name is not mangled, or the language for the name is unknown, or
c50c785c 2510 demangling is off, the name is printed in its "raw" form. */
5796c8dc
SS
2511
2512void
ef5ccd6c 2513fprintf_symbol_filtered (struct ui_file *stream, const char *name,
5796c8dc
SS
2514 enum language lang, int arg_mode)
2515{
2516 char *demangled;
2517
2518 if (name != NULL)
2519 {
2520 /* If user wants to see raw output, no problem. */
2521 if (!demangle)
2522 {
2523 fputs_filtered (name, stream);
2524 }
2525 else
2526 {
2527 demangled = language_demangle (language_def (lang), name, arg_mode);
2528 fputs_filtered (demangled ? demangled : name, stream);
2529 if (demangled != NULL)
2530 {
2531 xfree (demangled);
2532 }
2533 }
2534 }
2535}
2536
2537/* Do a strcmp() type operation on STRING1 and STRING2, ignoring any
2538 differences in whitespace. Returns 0 if they match, non-zero if they
2539 don't (slightly different than strcmp()'s range of return values).
2540
2541 As an extra hack, string1=="FOO(ARGS)" matches string2=="FOO".
2542 This "feature" is useful when searching for matching C++ function names
2543 (such as if the user types 'break FOO', where FOO is a mangled C++
c50c785c 2544 function). */
5796c8dc
SS
2545
2546int
2547strcmp_iw (const char *string1, const char *string2)
2548{
2549 while ((*string1 != '\0') && (*string2 != '\0'))
2550 {
2551 while (isspace (*string1))
2552 {
2553 string1++;
2554 }
2555 while (isspace (*string2))
2556 {
2557 string2++;
2558 }
a45ae5f8
JM
2559 if (case_sensitivity == case_sensitive_on && *string1 != *string2)
2560 break;
2561 if (case_sensitivity == case_sensitive_off
2562 && (tolower ((unsigned char) *string1)
2563 != tolower ((unsigned char) *string2)))
2564 break;
5796c8dc
SS
2565 if (*string1 != '\0')
2566 {
2567 string1++;
2568 string2++;
2569 }
2570 }
2571 return (*string1 != '\0' && *string1 != '(') || (*string2 != '\0');
2572}
2573
2574/* This is like strcmp except that it ignores whitespace and treats
2575 '(' as the first non-NULL character in terms of ordering. Like
2576 strcmp (and unlike strcmp_iw), it returns negative if STRING1 <
2577 STRING2, 0 if STRING2 = STRING2, and positive if STRING1 > STRING2
2578 according to that ordering.
2579
2580 If a list is sorted according to this function and if you want to
2581 find names in the list that match some fixed NAME according to
2582 strcmp_iw(LIST_ELT, NAME), then the place to start looking is right
2583 where this function would put NAME.
2584
a45ae5f8
JM
2585 This function must be neutral to the CASE_SENSITIVITY setting as the user
2586 may choose it during later lookup. Therefore this function always sorts
2587 primarily case-insensitively and secondarily case-sensitively.
2588
5796c8dc
SS
2589 Here are some examples of why using strcmp to sort is a bad idea:
2590
2591 Whitespace example:
2592
2593 Say your partial symtab contains: "foo<char *>", "goo". Then, if
2594 we try to do a search for "foo<char*>", strcmp will locate this
2595 after "foo<char *>" and before "goo". Then lookup_partial_symbol
2596 will start looking at strings beginning with "goo", and will never
2597 see the correct match of "foo<char *>".
2598
2599 Parenthesis example:
2600
2601 In practice, this is less like to be an issue, but I'll give it a
2602 shot. Let's assume that '$' is a legitimate character to occur in
2603 symbols. (Which may well even be the case on some systems.) Then
2604 say that the partial symbol table contains "foo$" and "foo(int)".
2605 strcmp will put them in this order, since '$' < '('. Now, if the
2606 user searches for "foo", then strcmp will sort "foo" before "foo$".
2607 Then lookup_partial_symbol will notice that strcmp_iw("foo$",
2608 "foo") is false, so it won't proceed to the actual match of
2609 "foo(int)" with "foo". */
2610
2611int
2612strcmp_iw_ordered (const char *string1, const char *string2)
2613{
a45ae5f8
JM
2614 const char *saved_string1 = string1, *saved_string2 = string2;
2615 enum case_sensitivity case_pass = case_sensitive_off;
2616
2617 for (;;)
5796c8dc 2618 {
a45ae5f8
JM
2619 /* C1 and C2 are valid only if *string1 != '\0' && *string2 != '\0'.
2620 Provide stub characters if we are already at the end of one of the
2621 strings. */
2622 char c1 = 'X', c2 = 'X';
2623
2624 while (*string1 != '\0' && *string2 != '\0')
5796c8dc 2625 {
a45ae5f8
JM
2626 while (isspace (*string1))
2627 string1++;
2628 while (isspace (*string2))
2629 string2++;
2630
2631 switch (case_pass)
2632 {
2633 case case_sensitive_off:
2634 c1 = tolower ((unsigned char) *string1);
2635 c2 = tolower ((unsigned char) *string2);
2636 break;
2637 case case_sensitive_on:
2638 c1 = *string1;
2639 c2 = *string2;
2640 break;
2641 }
2642 if (c1 != c2)
2643 break;
2644
2645 if (*string1 != '\0')
2646 {
2647 string1++;
2648 string2++;
2649 }
5796c8dc 2650 }
a45ae5f8
JM
2651
2652 switch (*string1)
5796c8dc 2653 {
a45ae5f8
JM
2654 /* Characters are non-equal unless they're both '\0'; we want to
2655 make sure we get the comparison right according to our
2656 comparison in the cases where one of them is '\0' or '('. */
2657 case '\0':
2658 if (*string2 == '\0')
2659 break;
2660 else
2661 return -1;
2662 case '(':
2663 if (*string2 == '\0')
2664 return 1;
2665 else
2666 return -1;
2667 default:
2668 if (*string2 == '\0' || *string2 == '(')
2669 return 1;
2670 else if (c1 > c2)
2671 return 1;
2672 else if (c1 < c2)
2673 return -1;
2674 /* PASSTHRU */
5796c8dc 2675 }
5796c8dc 2676
a45ae5f8 2677 if (case_pass == case_sensitive_on)
5796c8dc 2678 return 0;
a45ae5f8
JM
2679
2680 /* Otherwise the strings were equal in case insensitive way, make
2681 a more fine grained comparison in a case sensitive way. */
2682
2683 case_pass = case_sensitive_on;
2684 string1 = saved_string1;
2685 string2 = saved_string2;
5796c8dc
SS
2686 }
2687}
2688
2689/* A simple comparison function with opposite semantics to strcmp. */
2690
2691int
2692streq (const char *lhs, const char *rhs)
2693{
2694 return !strcmp (lhs, rhs);
2695}
2696\f
2697
2698/*
2699 ** subset_compare()
2700 ** Answer whether string_to_compare is a full or partial match to
2701 ** template_string. The partial match must be in sequence starting
2702 ** at index 0.
2703 */
2704int
2705subset_compare (char *string_to_compare, char *template_string)
2706{
2707 int match;
cf7f2e2d 2708
5796c8dc
SS
2709 if (template_string != (char *) NULL && string_to_compare != (char *) NULL
2710 && strlen (string_to_compare) <= strlen (template_string))
2711 match =
2712 (strncmp
2713 (template_string, string_to_compare, strlen (string_to_compare)) == 0);
2714 else
2715 match = 0;
2716 return match;
2717}
2718
2719static void
2720pagination_on_command (char *arg, int from_tty)
2721{
2722 pagination_enabled = 1;
2723}
2724
2725static void
2726pagination_off_command (char *arg, int from_tty)
2727{
2728 pagination_enabled = 0;
2729}
2730
2731static void
2732show_debug_timestamp (struct ui_file *file, int from_tty,
2733 struct cmd_list_element *c, const char *value)
2734{
c50c785c
JM
2735 fprintf_filtered (file, _("Timestamping debugging messages is %s.\n"),
2736 value);
5796c8dc
SS
2737}
2738\f
2739
2740void
2741initialize_utils (void)
2742{
5796c8dc 2743 add_setshow_uinteger_cmd ("width", class_support, &chars_per_line, _("\
ef5ccd6c
JM
2744Set number of characters where GDB should wrap lines of its output."), _("\
2745Show number of characters where GDB should wrap lines of its output."), _("\
2746This affects where GDB wraps its output to fit the screen width.\n\
2747Setting this to zero prevents GDB from wrapping its output."),
5796c8dc
SS
2748 set_width_command,
2749 show_chars_per_line,
2750 &setlist, &showlist);
2751
2752 add_setshow_uinteger_cmd ("height", class_support, &lines_per_page, _("\
ef5ccd6c
JM
2753Set number of lines in a page for GDB output pagination."), _("\
2754Show number of lines in a page for GDB output pagination."), _("\
2755This affects the number of lines after which GDB will pause\n\
2756its output and ask you whether to continue.\n\
2757Setting this to zero causes GDB never pause during output."),
5796c8dc
SS
2758 set_height_command,
2759 show_lines_per_page,
2760 &setlist, &showlist);
2761
2762 init_page_info ();
2763
5796c8dc
SS
2764 add_setshow_boolean_cmd ("pagination", class_support,
2765 &pagination_enabled, _("\
ef5ccd6c
JM
2766Set state of GDB output pagination."), _("\
2767Show state of GDB output pagination."), _("\
2768When pagination is ON, GDB pauses at end of each screenful of\n\
2769its output and asks you whether to continue.\n\
2770Turning pagination off is an alternative to \"set height 0\"."),
5796c8dc
SS
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, _("\
2785Set printing of 8-bit characters in strings as \\nnn."), _("\
2786Show printing of 8-bit characters in strings as \\nnn."), NULL,
2787 NULL,
2788 show_sevenbit_strings,
2789 &setprintlist, &showprintlist);
2790
5796c8dc
SS
2791 add_setshow_boolean_cmd ("timestamp", class_maintenance,
2792 &debug_timestamp, _("\
2793Set timestamping of debugging messages."), _("\
2794Show timestamping of debugging messages."), _("\
2795When set, debugging messages will be marked with seconds and microseconds."),
2796 NULL,
2797 show_debug_timestamp,
2798 &setdebuglist, &showdebuglist);
2799}
2800
c50c785c
JM
2801/* Print routines to handle variable size regs, etc. */
2802/* Temporary storage using circular buffer. */
5796c8dc
SS
2803#define NUMCELLS 16
2804#define CELLSIZE 50
2805static char *
2806get_cell (void)
2807{
2808 static char buf[NUMCELLS][CELLSIZE];
2809 static int cell = 0;
cf7f2e2d 2810
5796c8dc
SS
2811 if (++cell >= NUMCELLS)
2812 cell = 0;
2813 return buf[cell];
2814}
2815
2816const char *
2817paddress (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
c50c785c 2822 when it won't occur. */
5796c8dc
SS
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
c50c785c
JM
2835/* This function is described in "defs.h". */
2836
2837const char *
2838print_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
a45ae5f8
JM
2854/* Callback hash_f for htab_create_alloc or htab_create_alloc_ex. */
2855
2856hashval_t
2857core_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
2866int
2867core_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
5796c8dc
SS
2875static char *
2876decimal2str (char *sign, ULONGEST addr, int width)
2877{
2878 /* Steal code from valprint.c:print_decimal(). Should this worry
c50c785c 2879 about the real size of addr as the above does? */
5796c8dc
SS
2880 unsigned long temp[3];
2881 char *str = get_cell ();
5796c8dc 2882 int i = 0;
cf7f2e2d 2883
5796c8dc
SS
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
2918static char *
2919octal2str (ULONGEST addr, int width)
2920{
2921 unsigned long temp[3];
2922 char *str = get_cell ();
5796c8dc 2923 int i = 0;
cf7f2e2d 2924
5796c8dc
SS
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
2961char *
2962pulongest (ULONGEST u)
2963{
2964 return decimal2str ("", u, 0);
2965}
2966
2967char *
2968plongest (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. */
2977static int thirty_two = 32;
2978
2979char *
2980phex (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
3008char *
3009phex_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);
cf7f2e2d 3018
5796c8dc
SS
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. */
3046char *
3047hex_string (LONGEST num)
3048{
3049 char *result = get_cell ();
cf7f2e2d 3050
5796c8dc
SS
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. */
3059char *
3060hex_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)
c50c785c
JM
3070 internal_error (__FILE__, __LINE__, _("\
3071hex_string_custom: insufficient space to store result"));
5796c8dc
SS
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'
c50c785c 3084 * and 'o' formats do not include a prefix (0x or leading 0). */
5796c8dc
SS
3085
3086char *
3087int_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;
cf7f2e2d 3095
5796c8dc
SS
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);
cf7f2e2d 3114
5796c8dc
SS
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. */
3127const char *
3128core_addr_to_string (const CORE_ADDR addr)
3129{
3130 char *str = get_cell ();
cf7f2e2d 3131
5796c8dc
SS
3132 strcpy (str, "0x");
3133 strcat (str, phex (addr, sizeof (addr)));
3134 return str;
3135}
3136
3137const char *
3138core_addr_to_string_nz (const CORE_ADDR addr)
3139{
3140 char *str = get_cell ();
cf7f2e2d 3141
5796c8dc
SS
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. */
3148CORE_ADDR
3149string_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;
cf7f2e2d 3157
5796c8dc
SS
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;
cf7f2e2d 3172
5796c8dc
SS
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
3185const char *
3186host_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
3194char *
3195gdb_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);
cf7f2e2d 3212
5796c8dc
SS
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);
cf7f2e2d 3226
5796c8dc
SS
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
a45ae5f8 3237 to the problems described in method 3, have modified their
5796c8dc
SS
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);
cf7f2e2d 3254
5796c8dc
SS
3255 if (path_max > 0)
3256 {
3257 /* PATH_MAX is bounded. */
3258 char *buf = alloca (path_max);
3259 char *rp = realpath (filename, buf);
cf7f2e2d 3260
5796c8dc
SS
3261 return xstrdup (rp ? rp : filename);
3262 }
3263 }
3264#endif
3265
ef5ccd6c
JM
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);
5796c8dc 3279
ef5ccd6c
JM
3280 if (len > 0 && len < MAX_PATH)
3281 return xstrdup (buf);
3282 }
5796c8dc
SS
3283#endif
3284
ef5ccd6c
JM
3285 /* This system is a lost cause, just dup the buffer. */
3286 return xstrdup (filename);
5796c8dc
SS
3287}
3288
3289ULONGEST
3290align_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
3297ULONGEST
3298align_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
3308void *
3309hashtab_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);
cf7f2e2d 3313
5796c8dc
SS
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
3323void
3324dummy_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
3337static int
3338is_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
3348static int
3349digit_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
3359ULONGEST
3360strtoulst (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
3431char *
3432ldirname (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
3461char **
3462gdb_buildargv (const char *s)
3463{
3464 char **argv = buildargv (s);
cf7f2e2d 3465
5796c8dc 3466 if (s != NULL && argv == NULL)
a45ae5f8 3467 malloc_failure (0);
5796c8dc
SS
3468 return argv;
3469}
3470
cf7f2e2d
JM
3471int
3472compare_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
a45ae5f8
JM
3479/* String compare function for qsort. */
3480
3481int
3482compare_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
cf7f2e2d 3490#define AMBIGUOUS_MESS1 ".\nMatching formats:"
c50c785c
JM
3491#define AMBIGUOUS_MESS2 \
3492 ".\nUse \"set gnutarget format-name\" to specify the format."
cf7f2e2d
JM
3493
3494const char *
3495gdb_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
3533int
3534parse_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
a45ae5f8
JM
3551/* Helper for make_bpstat_clear_actions_cleanup. */
3552
3553static void
3554do_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
3562struct cleanup *
3563make_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
3572int
3573producer_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
ef5ccd6c
JM
3612/* Helper for make_cleanup_free_char_ptr_vec. */
3613
3614static void
3615do_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
3629struct cleanup *
3630make_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
3640void
3641substitute_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
3685static void
3686sigalrm_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
3702pid_t
3703wait_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
3757int
3758gdb_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