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