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