* source.c (symtab_to_fullname): Test 'r >= 0'.
[deliverable/binutils-gdb.git] / gdb / utils.c
CommitLineData
c906108c 1/* General utility routines for GDB, the GNU debugger.
1bac305b 2
6aba47ca 3 Copyright (C) 1986, 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995, 1996,
9b254dd1 4 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008
46e9880c 5 Free Software Foundation, Inc.
c906108c 6
c5aa993b 7 This file is part of GDB.
c906108c 8
c5aa993b
JM
9 This program is free software; you can redistribute it and/or modify
10 it under the terms of the GNU General Public License as published by
a9762ec7 11 the Free Software Foundation; either version 3 of the License, or
c5aa993b 12 (at your option) any later version.
c906108c 13
c5aa993b
JM
14 This program is distributed in the hope that it will be useful,
15 but WITHOUT ANY WARRANTY; without even the implied warranty of
16 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 GNU General Public License for more details.
c906108c 18
c5aa993b 19 You should have received a copy of the GNU General Public License
a9762ec7 20 along with this program. If not, see <http://www.gnu.org/licenses/>. */
c906108c 21
4e8f7a8b
DJ
22#include "defs.h"
23#include "gdb_assert.h"
24#include <ctype.h>
25#include "gdb_string.h"
26#include "event-top.h"
60250e8b 27#include "exceptions.h"
95e54da7 28#include "gdbthread.h"
4e8f7a8b 29
6a83354a
AC
30#ifdef TUI
31#include "tui/tui.h" /* For tui_get_command_dimension. */
32#endif
33
9d271fd8
AC
34#ifdef __GO32__
35#include <pc.h>
36#endif
37
c906108c
SS
38/* SunOS's curses.h has a '#define reg register' in it. Thank you Sun. */
39#ifdef reg
40#undef reg
41#endif
42
042be3a9 43#include <signal.h>
c906108c
SS
44#include "gdbcmd.h"
45#include "serial.h"
46#include "bfd.h"
47#include "target.h"
48#include "demangle.h"
49#include "expression.h"
50#include "language.h"
234b45d4 51#include "charset.h"
c906108c 52#include "annotate.h"
303c8ebd 53#include "filenames.h"
7b90c3f9 54#include "symfile.h"
ae5a43e0 55#include "gdb_obstack.h"
9544c605 56#include "gdbcore.h"
698ba934 57#include "top.h"
c906108c 58
8731e58e 59#include "inferior.h" /* for signed_pointer_to_address */
ac2e2ef7 60
2d1b2124
AC
61#include <sys/param.h> /* For MAXPATHLEN */
62
3b78cdbb 63#include "gdb_curses.h"
020cc13c 64
dbda9972 65#include "readline/readline.h"
c906108c 66
75feb17d
DJ
67#include <sys/time.h>
68#include <time.h>
69
a3828db0 70#if !HAVE_DECL_MALLOC
8dbb1c65 71extern PTR malloc (); /* OK: PTR */
3c37485b 72#endif
a3828db0 73#if !HAVE_DECL_REALLOC
8dbb1c65 74extern PTR realloc (); /* OK: PTR */
0e52036f 75#endif
a3828db0 76#if !HAVE_DECL_FREE
81b8eb80
AC
77extern void free ();
78#endif
81b8eb80 79
c906108c
SS
80/* readline defines this. */
81#undef savestring
82
9a4105ab 83void (*deprecated_error_begin_hook) (void);
c906108c
SS
84
85/* Prototypes for local functions */
86
d9fcf2fb 87static void vfprintf_maybe_filtered (struct ui_file *, const char *,
bee0189a 88 va_list, int) ATTR_FORMAT (printf, 2, 0);
c906108c 89
d9fcf2fb 90static void fputs_maybe_filtered (const char *, struct ui_file *, int);
c906108c 91
e42c9534
AC
92static void do_my_cleanups (struct cleanup **, struct cleanup *);
93
a14ed312 94static void prompt_for_continue (void);
c906108c 95
eb0d3137 96static void set_screen_size (void);
a14ed312 97static void set_width (void);
c906108c 98
75feb17d
DJ
99/* A flag indicating whether to timestamp debugging messages. */
100
101static int debug_timestamp = 0;
102
c906108c
SS
103/* Chain of cleanup actions established with make_cleanup,
104 to be executed if an error happens. */
105
c5aa993b
JM
106static struct cleanup *cleanup_chain; /* cleaned up after a failed command */
107static struct cleanup *final_cleanup_chain; /* cleaned up when gdb exits */
43ff13b4 108
c906108c
SS
109/* Nonzero if we have job control. */
110
111int job_control;
112
113/* Nonzero means a quit has been requested. */
114
115int quit_flag;
116
117/* Nonzero means quit immediately if Control-C is typed now, rather
118 than waiting until QUIT is executed. Be careful in setting this;
119 code which executes with immediate_quit set has to be very careful
120 about being able to deal with being interrupted at any time. It is
121 almost always better to use QUIT; the only exception I can think of
122 is being able to quit out of a system call (using EINTR loses if
123 the SIGINT happens between the previous QUIT and the system call).
124 To immediately quit in the case in which a SIGINT happens between
125 the previous QUIT and setting immediate_quit (desirable anytime we
126 expect to block), call QUIT after setting immediate_quit. */
127
128int immediate_quit;
129
4a351cef
AF
130/* Nonzero means that encoded C++/ObjC names should be printed out in their
131 C++/ObjC form rather than raw. */
c906108c
SS
132
133int demangle = 1;
920d2a44
AC
134static void
135show_demangle (struct ui_file *file, int from_tty,
136 struct cmd_list_element *c, const char *value)
137{
138 fprintf_filtered (file, _("\
139Demangling of encoded C++/ObjC names when displaying symbols is %s.\n"),
140 value);
141}
c906108c 142
4a351cef
AF
143/* Nonzero means that encoded C++/ObjC names should be printed out in their
144 C++/ObjC form even in assembler language displays. If this is set, but
c906108c
SS
145 DEMANGLE is zero, names are printed raw, i.e. DEMANGLE controls. */
146
147int asm_demangle = 0;
920d2a44
AC
148static void
149show_asm_demangle (struct ui_file *file, int from_tty,
150 struct cmd_list_element *c, const char *value)
151{
152 fprintf_filtered (file, _("\
153Demangling of C++/ObjC names in disassembly listings is %s.\n"),
154 value);
155}
c906108c
SS
156
157/* Nonzero means that strings with character values >0x7F should be printed
158 as octal escapes. Zero means just print the value (e.g. it's an
159 international character, and the terminal or window can cope.) */
160
161int sevenbit_strings = 0;
920d2a44
AC
162static void
163show_sevenbit_strings (struct ui_file *file, int from_tty,
164 struct cmd_list_element *c, const char *value)
165{
166 fprintf_filtered (file, _("\
167Printing of 8-bit characters in strings as \\nnn is %s.\n"),
168 value);
169}
c906108c
SS
170
171/* String to be printed before error messages, if any. */
172
173char *error_pre_print;
174
175/* String to be printed before quit messages, if any. */
176
177char *quit_pre_print;
178
179/* String to be printed before warning messages, if any. */
180
181char *warning_pre_print = "\nwarning: ";
182
183int pagination_enabled = 1;
920d2a44
AC
184static void
185show_pagination_enabled (struct ui_file *file, int from_tty,
186 struct cmd_list_element *c, const char *value)
187{
188 fprintf_filtered (file, _("State of pagination is %s.\n"), value);
189}
190
c906108c 191\f
c5aa993b 192
c906108c
SS
193/* Add a new cleanup to the cleanup_chain,
194 and return the previous chain pointer
195 to be passed later to do_cleanups or discard_cleanups.
196 Args are FUNCTION to clean up with, and ARG to pass to it. */
197
198struct cleanup *
e4005526 199make_cleanup (make_cleanup_ftype *function, void *arg)
c906108c 200{
c5aa993b 201 return make_my_cleanup (&cleanup_chain, function, arg);
c906108c
SS
202}
203
4f8d22e3
PA
204struct cleanup *
205make_cleanup_dtor (make_cleanup_ftype *function, void *arg,
206 void (*dtor) (void *))
207{
208 return make_my_cleanup2 (&cleanup_chain,
209 function, arg, dtor);
210}
211
c906108c 212struct cleanup *
e4005526 213make_final_cleanup (make_cleanup_ftype *function, void *arg)
c906108c 214{
c5aa993b 215 return make_my_cleanup (&final_cleanup_chain, function, arg);
c906108c 216}
7a292a7a 217
7a292a7a 218static void
fba45db2 219do_freeargv (void *arg)
7a292a7a 220{
c5aa993b 221 freeargv ((char **) arg);
7a292a7a
SS
222}
223
224struct cleanup *
fba45db2 225make_cleanup_freeargv (char **arg)
7a292a7a
SS
226{
227 return make_my_cleanup (&cleanup_chain, do_freeargv, arg);
228}
229
5c65bbb6
AC
230static void
231do_bfd_close_cleanup (void *arg)
232{
233 bfd_close (arg);
234}
235
236struct cleanup *
237make_cleanup_bfd_close (bfd *abfd)
238{
239 return make_cleanup (do_bfd_close_cleanup, abfd);
240}
241
f5ff8c83
AC
242static void
243do_close_cleanup (void *arg)
244{
f042532c
AC
245 int *fd = arg;
246 close (*fd);
247 xfree (fd);
f5ff8c83
AC
248}
249
250struct cleanup *
251make_cleanup_close (int fd)
252{
f042532c
AC
253 int *saved_fd = xmalloc (sizeof (fd));
254 *saved_fd = fd;
255 return make_cleanup (do_close_cleanup, saved_fd);
f5ff8c83
AC
256}
257
7c8a8b04
TT
258/* Helper function which does the work for make_cleanup_fclose. */
259
260static void
261do_fclose_cleanup (void *arg)
262{
263 FILE *file = arg;
264 fclose (arg);
265}
266
267/* Return a new cleanup that closes FILE. */
268
269struct cleanup *
270make_cleanup_fclose (FILE *file)
271{
272 return make_cleanup (do_fclose_cleanup, file);
273}
274
11cf8741 275static void
d9fcf2fb 276do_ui_file_delete (void *arg)
11cf8741 277{
d9fcf2fb 278 ui_file_delete (arg);
11cf8741
JM
279}
280
281struct cleanup *
d9fcf2fb 282make_cleanup_ui_file_delete (struct ui_file *arg)
11cf8741 283{
d9fcf2fb 284 return make_my_cleanup (&cleanup_chain, do_ui_file_delete, arg);
11cf8741
JM
285}
286
7b90c3f9
JB
287static void
288do_free_section_addr_info (void *arg)
289{
290 free_section_addr_info (arg);
291}
292
293struct cleanup *
294make_cleanup_free_section_addr_info (struct section_addr_info *addrs)
295{
296 return make_my_cleanup (&cleanup_chain, do_free_section_addr_info, addrs);
297}
298
0b080f59
VP
299struct restore_integer_closure
300{
301 int *variable;
302 int value;
303};
304
305static void
306restore_integer (void *p)
307{
308 struct restore_integer_closure *closure = p;
309 *(closure->variable) = closure->value;
310}
7b90c3f9 311
0b080f59
VP
312/* Remember the current value of *VARIABLE and make it restored when the cleanup
313 is run. */
c906108c 314struct cleanup *
0b080f59
VP
315make_cleanup_restore_integer (int *variable)
316{
317 struct restore_integer_closure *c =
318 xmalloc (sizeof (struct restore_integer_closure));
319 c->variable = variable;
320 c->value = *variable;
321
322 return make_my_cleanup2 (&cleanup_chain, restore_integer, (void *)c,
323 xfree);
324}
325
326struct cleanup *
327make_my_cleanup2 (struct cleanup **pmy_chain, make_cleanup_ftype *function,
328 void *arg, void (*free_arg) (void *))
c906108c 329{
52f0bd74 330 struct cleanup *new
8731e58e 331 = (struct cleanup *) xmalloc (sizeof (struct cleanup));
52f0bd74 332 struct cleanup *old_chain = *pmy_chain;
c906108c
SS
333
334 new->next = *pmy_chain;
335 new->function = function;
0b080f59 336 new->free_arg = free_arg;
c906108c
SS
337 new->arg = arg;
338 *pmy_chain = new;
339
340 return old_chain;
341}
342
0b080f59
VP
343struct cleanup *
344make_my_cleanup (struct cleanup **pmy_chain, make_cleanup_ftype *function,
345 void *arg)
346{
347 return make_my_cleanup2 (pmy_chain, function, arg, NULL);
348}
349
c906108c
SS
350/* Discard cleanups and do the actions they describe
351 until we get back to the point OLD_CHAIN in the cleanup_chain. */
352
353void
aa1ee363 354do_cleanups (struct cleanup *old_chain)
c906108c 355{
c5aa993b 356 do_my_cleanups (&cleanup_chain, old_chain);
c906108c
SS
357}
358
359void
aa1ee363 360do_final_cleanups (struct cleanup *old_chain)
c906108c 361{
c5aa993b 362 do_my_cleanups (&final_cleanup_chain, old_chain);
c906108c
SS
363}
364
e42c9534 365static void
aa1ee363
AC
366do_my_cleanups (struct cleanup **pmy_chain,
367 struct cleanup *old_chain)
c906108c 368{
52f0bd74 369 struct cleanup *ptr;
c906108c
SS
370 while ((ptr = *pmy_chain) != old_chain)
371 {
372 *pmy_chain = ptr->next; /* Do this first incase recursion */
373 (*ptr->function) (ptr->arg);
0b080f59
VP
374 if (ptr->free_arg)
375 (*ptr->free_arg) (ptr->arg);
b8c9b27d 376 xfree (ptr);
c906108c
SS
377 }
378}
379
380/* Discard cleanups, not doing the actions they describe,
381 until we get back to the point OLD_CHAIN in the cleanup_chain. */
382
383void
aa1ee363 384discard_cleanups (struct cleanup *old_chain)
c906108c 385{
c5aa993b 386 discard_my_cleanups (&cleanup_chain, old_chain);
c906108c
SS
387}
388
389void
aa1ee363 390discard_final_cleanups (struct cleanup *old_chain)
c906108c 391{
c5aa993b 392 discard_my_cleanups (&final_cleanup_chain, old_chain);
c906108c
SS
393}
394
395void
aa1ee363
AC
396discard_my_cleanups (struct cleanup **pmy_chain,
397 struct cleanup *old_chain)
c906108c 398{
52f0bd74 399 struct cleanup *ptr;
c906108c
SS
400 while ((ptr = *pmy_chain) != old_chain)
401 {
402 *pmy_chain = ptr->next;
0b080f59
VP
403 if (ptr->free_arg)
404 (*ptr->free_arg) (ptr->arg);
b8c9b27d 405 xfree (ptr);
c906108c
SS
406 }
407}
408
409/* Set the cleanup_chain to 0, and return the old cleanup chain. */
410struct cleanup *
fba45db2 411save_cleanups (void)
c906108c 412{
c5aa993b 413 return save_my_cleanups (&cleanup_chain);
c906108c
SS
414}
415
416struct cleanup *
fba45db2 417save_final_cleanups (void)
c906108c 418{
c5aa993b 419 return save_my_cleanups (&final_cleanup_chain);
c906108c
SS
420}
421
422struct cleanup *
fba45db2 423save_my_cleanups (struct cleanup **pmy_chain)
c906108c
SS
424{
425 struct cleanup *old_chain = *pmy_chain;
426
427 *pmy_chain = 0;
428 return old_chain;
429}
430
431/* Restore the cleanup chain from a previously saved chain. */
432void
fba45db2 433restore_cleanups (struct cleanup *chain)
c906108c 434{
c5aa993b 435 restore_my_cleanups (&cleanup_chain, chain);
c906108c
SS
436}
437
438void
fba45db2 439restore_final_cleanups (struct cleanup *chain)
c906108c 440{
c5aa993b 441 restore_my_cleanups (&final_cleanup_chain, chain);
c906108c
SS
442}
443
444void
fba45db2 445restore_my_cleanups (struct cleanup **pmy_chain, struct cleanup *chain)
c906108c
SS
446{
447 *pmy_chain = chain;
448}
449
450/* This function is useful for cleanups.
451 Do
452
c5aa993b
JM
453 foo = xmalloc (...);
454 old_chain = make_cleanup (free_current_contents, &foo);
c906108c
SS
455
456 to arrange to free the object thus allocated. */
457
458void
2f9429ae 459free_current_contents (void *ptr)
c906108c 460{
2f9429ae 461 void **location = ptr;
e2f9c474 462 if (location == NULL)
8e65ff28 463 internal_error (__FILE__, __LINE__,
e2e0b3e5 464 _("free_current_contents: NULL pointer"));
2f9429ae 465 if (*location != NULL)
e2f9c474 466 {
b8c9b27d 467 xfree (*location);
e2f9c474
AC
468 *location = NULL;
469 }
c906108c
SS
470}
471
472/* Provide a known function that does nothing, to use as a base for
473 for a possibly long chain of cleanups. This is useful where we
474 use the cleanup chain for handling normal cleanups as well as dealing
475 with cleanups that need to be done as a result of a call to error().
476 In such cases, we may not be certain where the first cleanup is, unless
477 we have a do-nothing one to always use as the base. */
478
c906108c 479void
e4005526 480null_cleanup (void *arg)
c906108c
SS
481{
482}
483
0ffe5012
PA
484/* Continuations are implemented as cleanups internally. Inherit from
485 cleanups. */
486struct continuation
487{
488 struct cleanup base;
489};
490
95e54da7
PA
491/* Add a continuation to the continuation list of THREAD. The new
492 continuation will be added at the front. */
43ff13b4 493void
95e54da7
PA
494add_continuation (struct thread_info *thread,
495 void (*continuation_hook) (void *), void *args,
604ead4a 496 void (*continuation_free_args) (void *))
43ff13b4 497{
95e54da7 498 struct cleanup *as_cleanup = &thread->continuations->base;
604ead4a 499 make_cleanup_ftype *continuation_hook_fn = continuation_hook;
43ff13b4 500
0ffe5012 501 make_my_cleanup2 (&as_cleanup,
604ead4a
PA
502 continuation_hook_fn,
503 args,
504 continuation_free_args);
0ffe5012 505
95e54da7 506 thread->continuations = (struct continuation *) as_cleanup;
43ff13b4
JM
507}
508
95e54da7
PA
509static void
510restore_thread_cleanup (void *arg)
511{
512 ptid_t *ptid_p = arg;
513 switch_to_thread (*ptid_p);
514}
515
516/* Walk down the continuation list of PTID, and execute all the
517 continuations. There is a problem though. In some cases new
518 continuations may be added while we are in the middle of this loop.
519 If this happens they will be added in the front, and done before we
520 have a chance of exhausting those that were already there. We need
521 to then save the beginning of the list in a pointer and do the
522 continuations from there on, instead of using the global beginning
523 of list as our iteration pointer. */
524static void
525do_all_continuations_ptid (ptid_t ptid,
526 struct continuation **continuations_p)
c2d11a7d 527{
95e54da7
PA
528 struct cleanup *old_chain;
529 ptid_t current_thread;
530 struct cleanup *as_cleanup;
531
532 if (*continuations_p == NULL)
533 return;
534
535 current_thread = inferior_ptid;
536
537 /* Restore selected thread on exit. Don't try to restore the frame
538 as well, because:
539
540 - When running continuations, the selected frame is always #0.
541
542 - The continuations may trigger symbol file loads, which may
543 change the frame layout (frame ids change), which would trigger
544 a warning if we used make_cleanup_restore_current_thread. */
545
546 old_chain = make_cleanup (restore_thread_cleanup, &current_thread);
547
548 /* Let the continuation see this thread as selected. */
549 switch_to_thread (ptid);
c2d11a7d
JM
550
551 /* Copy the list header into another pointer, and set the global
552 list header to null, so that the global list can change as a side
604ead4a
PA
553 effect of invoking the continuations and the processing of the
554 preexisting continuations will not be affected. */
555
95e54da7
PA
556 as_cleanup = &(*continuations_p)->base;
557 *continuations_p = NULL;
c2d11a7d 558
0a4a0819 559 /* Work now on the list we have set aside. */
95e54da7
PA
560 do_my_cleanups (&as_cleanup, NULL);
561
562 do_cleanups (old_chain);
563}
564
565/* Callback for iterate over threads. */
566static int
567do_all_continuations_thread_callback (struct thread_info *thread, void *data)
568{
569 do_all_continuations_ptid (thread->ptid, &thread->continuations);
570 return 0;
c2d11a7d
JM
571}
572
95e54da7 573/* Do all continuations of thread THREAD. */
c2d11a7d 574void
95e54da7
PA
575do_all_continuations_thread (struct thread_info *thread)
576{
577 do_all_continuations_thread_callback (thread, NULL);
578}
579
580/* Do all continuations of all threads. */
581void
582do_all_continuations (void)
43ff13b4 583{
95e54da7
PA
584 iterate_over_threads (do_all_continuations_thread_callback, NULL);
585}
586
587/* Callback for iterate over threads. */
588static int
589discard_all_continuations_thread_callback (struct thread_info *thread,
590 void *data)
591{
592 struct cleanup *continuation_ptr = &thread->continuations->base;
0ffe5012 593 discard_my_cleanups (&continuation_ptr, NULL);
95e54da7
PA
594 thread->continuations = NULL;
595 return 0;
596}
597
598/* Get rid of all the continuations of THREAD. */
599void
600discard_all_continuations_thread (struct thread_info *thread)
601{
602 discard_all_continuations_thread_callback (thread, NULL);
603}
604
605/* Get rid of all the continuations of all threads. */
606void
607discard_all_continuations (void)
608{
609 iterate_over_threads (discard_all_continuations_thread_callback, NULL);
43ff13b4 610}
c2c6d25f 611
95e54da7
PA
612
613/* Add a continuation to the intermediate continuation list of THREAD.
614 The new continuation will be added at the front. */
c2d11a7d 615void
95e54da7
PA
616add_intermediate_continuation (struct thread_info *thread,
617 void (*continuation_hook)
604ead4a
PA
618 (void *), void *args,
619 void (*continuation_free_args) (void *))
c2d11a7d 620{
95e54da7 621 struct cleanup *as_cleanup = &thread->intermediate_continuations->base;
604ead4a 622 make_cleanup_ftype *continuation_hook_fn = continuation_hook;
c2d11a7d 623
0ffe5012 624 make_my_cleanup2 (&as_cleanup,
604ead4a
PA
625 continuation_hook_fn,
626 args,
627 continuation_free_args);
0ffe5012 628
95e54da7 629 thread->intermediate_continuations = (struct continuation *) as_cleanup;
c2d11a7d
JM
630}
631
632/* Walk down the cmd_continuation list, and execute all the
633 continuations. There is a problem though. In some cases new
634 continuations may be added while we are in the middle of this
635 loop. If this happens they will be added in the front, and done
636 before we have a chance of exhausting those that were already
637 there. We need to then save the beginning of the list in a pointer
638 and do the continuations from there on, instead of using the
639 global beginning of list as our iteration pointer.*/
95e54da7
PA
640static int
641do_all_intermediate_continuations_thread_callback (struct thread_info *thread,
642 void *data)
643{
644 do_all_continuations_ptid (thread->ptid,
645 &thread->intermediate_continuations);
646 return 0;
647}
648
649/* Do all intermediate continuations of thread THREAD. */
c2d11a7d 650void
95e54da7 651do_all_intermediate_continuations_thread (struct thread_info *thread)
c2d11a7d 652{
95e54da7
PA
653 do_all_intermediate_continuations_thread_callback (thread, NULL);
654}
c2d11a7d 655
95e54da7
PA
656/* Do all intermediate continuations of all threads. */
657void
658do_all_intermediate_continuations (void)
659{
660 iterate_over_threads (do_all_intermediate_continuations_thread_callback, NULL);
661}
604ead4a 662
95e54da7
PA
663/* Callback for iterate over threads. */
664static int
665discard_all_intermediate_continuations_thread_callback (struct thread_info *thread,
666 void *data)
667{
668 struct cleanup *continuation_ptr = &thread->intermediate_continuations->base;
669 discard_my_cleanups (&continuation_ptr, NULL);
670 thread->intermediate_continuations = NULL;
671 return 0;
672}
c2d11a7d 673
95e54da7
PA
674/* Get rid of all the intermediate continuations of THREAD. */
675void
676discard_all_intermediate_continuations_thread (struct thread_info *thread)
677{
678 discard_all_intermediate_continuations_thread_callback (thread, NULL);
c2d11a7d
JM
679}
680
95e54da7 681/* Get rid of all the intermediate continuations of all threads. */
c2c6d25f 682void
fba45db2 683discard_all_intermediate_continuations (void)
c2c6d25f 684{
95e54da7 685 iterate_over_threads (discard_all_intermediate_continuations_thread_callback, NULL);
c2c6d25f 686}
c906108c 687\f
c5aa993b 688
8731e58e 689
f5a96129
AC
690/* Print a warning message. The first argument STRING is the warning
691 message, used as an fprintf format string, the second is the
692 va_list of arguments for that string. A warning is unfiltered (not
693 paginated) so that the user does not need to page through each
694 screen full of warnings when there are lots of them. */
c906108c
SS
695
696void
f5a96129 697vwarning (const char *string, va_list args)
c906108c 698{
9a4105ab
AC
699 if (deprecated_warning_hook)
700 (*deprecated_warning_hook) (string, args);
f5a96129
AC
701 else
702 {
703 target_terminal_ours ();
704 wrap_here (""); /* Force out any buffered output */
705 gdb_flush (gdb_stdout);
706 if (warning_pre_print)
306d9ac5 707 fputs_unfiltered (warning_pre_print, gdb_stderr);
f5a96129
AC
708 vfprintf_unfiltered (gdb_stderr, string, args);
709 fprintf_unfiltered (gdb_stderr, "\n");
710 va_end (args);
711 }
c906108c
SS
712}
713
714/* Print a warning message.
715 The first argument STRING is the warning message, used as a fprintf string,
716 and the remaining args are passed as arguments to it.
717 The primary difference between warnings and errors is that a warning
718 does not force the return to command level. */
719
c906108c 720void
8731e58e 721warning (const char *string, ...)
c906108c
SS
722{
723 va_list args;
c906108c 724 va_start (args, string);
f5a96129
AC
725 vwarning (string, args);
726 va_end (args);
c906108c
SS
727}
728
c906108c
SS
729/* Print an error message and return to command level.
730 The first argument STRING is the error message, used as a fprintf string,
731 and the remaining args are passed as arguments to it. */
732
4ce44c66
JM
733NORETURN void
734verror (const char *string, va_list args)
735{
6b1b7650 736 throw_verror (GENERIC_ERROR, string, args);
4ce44c66
JM
737}
738
c906108c 739NORETURN void
8731e58e 740error (const char *string, ...)
c906108c
SS
741{
742 va_list args;
c906108c 743 va_start (args, string);
6b1b7650 744 throw_verror (GENERIC_ERROR, string, args);
4ce44c66 745 va_end (args);
c906108c
SS
746}
747
d75e3c94
JJ
748/* Print an error message and quit.
749 The first argument STRING is the error message, used as a fprintf string,
750 and the remaining args are passed as arguments to it. */
751
752NORETURN void
753vfatal (const char *string, va_list args)
754{
6b1b7650 755 throw_vfatal (string, args);
d75e3c94
JJ
756}
757
758NORETURN void
759fatal (const char *string, ...)
760{
761 va_list args;
762 va_start (args, string);
6b1b7650 763 throw_vfatal (string, args);
d75e3c94
JJ
764 va_end (args);
765}
766
d75e3c94
JJ
767NORETURN void
768error_stream (struct ui_file *stream)
2acceee2 769{
4ce44c66 770 long len;
6b1b7650
AC
771 char *message = ui_file_xstrdup (stream, &len);
772 make_cleanup (xfree, message);
8a3fe4f8 773 error (("%s"), message);
2acceee2 774}
c906108c 775
dec43320
AC
776/* Print a message reporting an internal error/warning. Ask the user
777 if they want to continue, dump core, or just exit. Return
778 something to indicate a quit. */
c906108c 779
dec43320 780struct internal_problem
c906108c 781{
dec43320
AC
782 const char *name;
783 /* FIXME: cagney/2002-08-15: There should be ``maint set/show''
784 commands available for controlling these variables. */
785 enum auto_boolean should_quit;
786 enum auto_boolean should_dump_core;
787};
788
789/* Report a problem, internal to GDB, to the user. Once the problem
790 has been reported, and assuming GDB didn't quit, the caller can
791 either allow execution to resume or throw an error. */
792
bee0189a 793static void ATTR_FORMAT (printf, 4, 0)
dec43320 794internal_vproblem (struct internal_problem *problem,
8731e58e 795 const char *file, int line, const char *fmt, va_list ap)
dec43320 796{
dec43320 797 static int dejavu;
375fc983 798 int quit_p;
7be570e7 799 int dump_core_p;
714b1282 800 char *reason;
c906108c 801
dec43320 802 /* Don't allow infinite error/warning recursion. */
714b1282
AC
803 {
804 static char msg[] = "Recursive internal problem.\n";
805 switch (dejavu)
806 {
807 case 0:
808 dejavu = 1;
809 break;
810 case 1:
811 dejavu = 2;
812 fputs_unfiltered (msg, gdb_stderr);
813 abort (); /* NOTE: GDB has only three calls to abort(). */
814 default:
815 dejavu = 3;
816 write (STDERR_FILENO, msg, sizeof (msg));
817 exit (1);
818 }
819 }
c906108c 820
dec43320 821 /* Try to get the message out and at the start of a new line. */
4261bedc 822 target_terminal_ours ();
dec43320
AC
823 begin_line ();
824
714b1282
AC
825 /* Create a string containing the full error/warning message. Need
826 to call query with this full string, as otherwize the reason
827 (error/warning) and question become separated. Format using a
828 style similar to a compiler error message. Include extra detail
829 so that the user knows that they are living on the edge. */
830 {
831 char *msg;
e623b504 832 msg = xstrvprintf (fmt, ap);
b435e160 833 reason = xstrprintf ("\
714b1282
AC
834%s:%d: %s: %s\n\
835A problem internal to GDB has been detected,\n\
836further debugging may prove unreliable.", file, line, problem->name, msg);
837 xfree (msg);
838 make_cleanup (xfree, reason);
839 }
7be570e7 840
dec43320
AC
841 switch (problem->should_quit)
842 {
843 case AUTO_BOOLEAN_AUTO:
844 /* Default (yes/batch case) is to quit GDB. When in batch mode
8731e58e
AC
845 this lessens the likelhood of GDB going into an infinate
846 loop. */
e2e0b3e5 847 quit_p = query (_("%s\nQuit this debugging session? "), reason);
dec43320
AC
848 break;
849 case AUTO_BOOLEAN_TRUE:
850 quit_p = 1;
851 break;
852 case AUTO_BOOLEAN_FALSE:
853 quit_p = 0;
854 break;
855 default:
e2e0b3e5 856 internal_error (__FILE__, __LINE__, _("bad switch"));
dec43320
AC
857 }
858
859 switch (problem->should_dump_core)
860 {
861 case AUTO_BOOLEAN_AUTO:
862 /* Default (yes/batch case) is to dump core. This leaves a GDB
8731e58e
AC
863 `dropping' so that it is easier to see that something went
864 wrong in GDB. */
e2e0b3e5 865 dump_core_p = query (_("%s\nCreate a core file of GDB? "), reason);
dec43320
AC
866 break;
867 break;
868 case AUTO_BOOLEAN_TRUE:
869 dump_core_p = 1;
870 break;
871 case AUTO_BOOLEAN_FALSE:
872 dump_core_p = 0;
873 break;
874 default:
e2e0b3e5 875 internal_error (__FILE__, __LINE__, _("bad switch"));
dec43320 876 }
7be570e7 877
375fc983 878 if (quit_p)
7be570e7
JM
879 {
880 if (dump_core_p)
8731e58e 881 abort (); /* NOTE: GDB has only three calls to abort(). */
375fc983
AC
882 else
883 exit (1);
7be570e7
JM
884 }
885 else
886 {
887 if (dump_core_p)
375fc983 888 {
9b265ec2 889#ifdef HAVE_WORKING_FORK
375fc983 890 if (fork () == 0)
8731e58e 891 abort (); /* NOTE: GDB has only three calls to abort(). */
9b265ec2 892#endif
375fc983 893 }
7be570e7 894 }
96baa820
JM
895
896 dejavu = 0;
dec43320
AC
897}
898
899static struct internal_problem internal_error_problem = {
900 "internal-error", AUTO_BOOLEAN_AUTO, AUTO_BOOLEAN_AUTO
901};
902
903NORETURN void
8731e58e 904internal_verror (const char *file, int line, const char *fmt, va_list ap)
dec43320
AC
905{
906 internal_vproblem (&internal_error_problem, file, line, fmt, ap);
315a522e 907 deprecated_throw_reason (RETURN_ERROR);
c906108c
SS
908}
909
4ce44c66 910NORETURN void
8e65ff28 911internal_error (const char *file, int line, const char *string, ...)
4ce44c66
JM
912{
913 va_list ap;
914 va_start (ap, string);
8e65ff28 915 internal_verror (file, line, string, ap);
4ce44c66
JM
916 va_end (ap);
917}
918
dec43320 919static struct internal_problem internal_warning_problem = {
d833db3b 920 "internal-warning", AUTO_BOOLEAN_AUTO, AUTO_BOOLEAN_AUTO
dec43320
AC
921};
922
923void
8731e58e 924internal_vwarning (const char *file, int line, const char *fmt, va_list ap)
dec43320
AC
925{
926 internal_vproblem (&internal_warning_problem, file, line, fmt, ap);
927}
928
929void
930internal_warning (const char *file, int line, const char *string, ...)
931{
932 va_list ap;
933 va_start (ap, string);
934 internal_vwarning (file, line, string, ap);
935 va_end (ap);
936}
937
c906108c
SS
938/* Print the system error message for errno, and also mention STRING
939 as the file name for which the error was encountered.
940 Then return to command level. */
941
942NORETURN void
6972bc8b 943perror_with_name (const char *string)
c906108c
SS
944{
945 char *err;
946 char *combined;
947
948 err = safe_strerror (errno);
949 combined = (char *) alloca (strlen (err) + strlen (string) + 3);
950 strcpy (combined, string);
951 strcat (combined, ": ");
952 strcat (combined, err);
953
954 /* I understand setting these is a matter of taste. Still, some people
955 may clear errno but not know about bfd_error. Doing this here is not
956 unreasonable. */
957 bfd_set_error (bfd_error_no_error);
958 errno = 0;
959
8a3fe4f8 960 error (_("%s."), combined);
c906108c
SS
961}
962
963/* Print the system error message for ERRCODE, and also mention STRING
964 as the file name for which the error was encountered. */
965
966void
6972bc8b 967print_sys_errmsg (const char *string, int errcode)
c906108c
SS
968{
969 char *err;
970 char *combined;
971
972 err = safe_strerror (errcode);
973 combined = (char *) alloca (strlen (err) + strlen (string) + 3);
974 strcpy (combined, string);
975 strcat (combined, ": ");
976 strcat (combined, err);
977
978 /* We want anything which was printed on stdout to come out first, before
979 this message. */
980 gdb_flush (gdb_stdout);
981 fprintf_unfiltered (gdb_stderr, "%s.\n", combined);
982}
983
984/* Control C eventually causes this to be called, at a convenient time. */
985
986void
fba45db2 987quit (void)
c906108c 988{
7be570e7
JM
989#ifdef __MSDOS__
990 /* No steenking SIGINT will ever be coming our way when the
991 program is resumed. Don't lie. */
e06e2353 992 fatal ("Quit");
7be570e7 993#else
c906108c 994 if (job_control
8731e58e
AC
995 /* If there is no terminal switching for this target, then we can't
996 possibly get screwed by the lack of job control. */
c906108c 997 || current_target.to_terminal_ours == NULL)
e06e2353 998 fatal ("Quit");
c906108c 999 else
e06e2353 1000 fatal ("Quit (expect signal SIGINT when the program is resumed)");
7be570e7 1001#endif
c906108c
SS
1002}
1003
c906108c 1004\f
c906108c
SS
1005/* Called when a memory allocation fails, with the number of bytes of
1006 memory requested in SIZE. */
1007
1008NORETURN void
fba45db2 1009nomem (long size)
c906108c
SS
1010{
1011 if (size > 0)
1012 {
8e65ff28 1013 internal_error (__FILE__, __LINE__,
e2e0b3e5 1014 _("virtual memory exhausted: can't allocate %ld bytes."),
8731e58e 1015 size);
c906108c
SS
1016 }
1017 else
1018 {
e2e0b3e5 1019 internal_error (__FILE__, __LINE__, _("virtual memory exhausted."));
c906108c
SS
1020 }
1021}
1022
c0e61796
AC
1023/* The xmalloc() (libiberty.h) family of memory management routines.
1024
1025 These are like the ISO-C malloc() family except that they implement
1026 consistent semantics and guard against typical memory management
7936743b 1027 problems. */
c0e61796
AC
1028
1029/* NOTE: These are declared using PTR to ensure consistency with
1030 "libiberty.h". xfree() is GDB local. */
1031
8dbb1c65 1032PTR /* OK: PTR */
c0e61796
AC
1033xmalloc (size_t size)
1034{
7936743b
AC
1035 void *val;
1036
1037 /* See libiberty/xmalloc.c. This function need's to match that's
1038 semantics. It never returns NULL. */
1039 if (size == 0)
1040 size = 1;
1041
1042 val = malloc (size); /* OK: malloc */
1043 if (val == NULL)
1044 nomem (size);
1045
1046 return (val);
c0e61796 1047}
c906108c 1048
5b90c7b5
AC
1049void *
1050xzalloc (size_t size)
1051{
1052 return xcalloc (1, size);
1053}
1054
8dbb1c65
AC
1055PTR /* OK: PTR */
1056xrealloc (PTR ptr, size_t size) /* OK: PTR */
c906108c 1057{
0efffb96
AC
1058 void *val;
1059
1060 /* See libiberty/xmalloc.c. This function need's to match that's
1061 semantics. It never returns NULL. */
1062 if (size == 0)
1063 size = 1;
1064
1065 if (ptr != NULL)
1066 val = realloc (ptr, size); /* OK: realloc */
1067 else
1068 val = malloc (size); /* OK: malloc */
1069 if (val == NULL)
1070 nomem (size);
1071
1072 return (val);
c906108c 1073}
b8c9b27d 1074
8dbb1c65 1075PTR /* OK: PTR */
c0e61796
AC
1076xcalloc (size_t number, size_t size)
1077{
aa2ee5f6
AC
1078 void *mem;
1079
1080 /* See libiberty/xmalloc.c. This function need's to match that's
1081 semantics. It never returns NULL. */
1082 if (number == 0 || size == 0)
1083 {
1084 number = 1;
1085 size = 1;
1086 }
1087
1088 mem = calloc (number, size); /* OK: xcalloc */
1089 if (mem == NULL)
1090 nomem (number * size);
1091
1092 return mem;
c0e61796 1093}
b8c9b27d
KB
1094
1095void
1096xfree (void *ptr)
1097{
2dc74dc1
AC
1098 if (ptr != NULL)
1099 free (ptr); /* OK: free */
b8c9b27d 1100}
c906108c 1101\f
c5aa993b 1102
76995688
AC
1103/* Like asprintf/vasprintf but get an internal_error if the call
1104 fails. */
1105
9ebf4acf
AC
1106char *
1107xstrprintf (const char *format, ...)
1108{
1109 char *ret;
1110 va_list args;
1111 va_start (args, format);
e623b504 1112 ret = xstrvprintf (format, args);
9ebf4acf
AC
1113 va_end (args);
1114 return ret;
1115}
1116
76995688
AC
1117void
1118xasprintf (char **ret, const char *format, ...)
1119{
1120 va_list args;
1121 va_start (args, format);
e623b504 1122 (*ret) = xstrvprintf (format, args);
76995688
AC
1123 va_end (args);
1124}
1125
1126void
1127xvasprintf (char **ret, const char *format, va_list ap)
1128{
a552edd9 1129 (*ret) = xstrvprintf (format, ap);
76995688
AC
1130}
1131
e623b504
AC
1132char *
1133xstrvprintf (const char *format, va_list ap)
1134{
1135 char *ret = NULL;
1136 int status = vasprintf (&ret, format, ap);
46e9880c
DJ
1137 /* NULL is returned when there was a memory allocation problem, or
1138 any other error (for instance, a bad format string). A negative
1139 status (the printed length) with a non-NULL buffer should never
1140 happen, but just to be sure. */
1141 if (ret == NULL || status < 0)
1142 internal_error (__FILE__, __LINE__, _("vasprintf call failed"));
e623b504
AC
1143 return ret;
1144}
76995688 1145
bde2058d
MK
1146int
1147xsnprintf (char *str, size_t size, const char *format, ...)
1148{
1149 va_list args;
1150 int ret;
1151
1152 va_start (args, format);
1153 ret = vsnprintf (str, size, format, args);
1154 gdb_assert (ret < size);
1155 va_end (args);
1156
1157 return ret;
1158}
1159
c906108c
SS
1160/* My replacement for the read system call.
1161 Used like `read' but keeps going if `read' returns too soon. */
1162
1163int
fba45db2 1164myread (int desc, char *addr, int len)
c906108c 1165{
52f0bd74 1166 int val;
c906108c
SS
1167 int orglen = len;
1168
1169 while (len > 0)
1170 {
1171 val = read (desc, addr, len);
1172 if (val < 0)
1173 return val;
1174 if (val == 0)
1175 return orglen - len;
1176 len -= val;
1177 addr += val;
1178 }
1179 return orglen;
1180}
1181\f
1182/* Make a copy of the string at PTR with SIZE characters
1183 (and add a null character at the end in the copy).
1184 Uses malloc to get the space. Returns the address of the copy. */
1185
1186char *
5565b556 1187savestring (const char *ptr, size_t size)
c906108c 1188{
52f0bd74 1189 char *p = (char *) xmalloc (size + 1);
c906108c
SS
1190 memcpy (p, ptr, size);
1191 p[size] = 0;
1192 return p;
1193}
1194
c906108c 1195void
aa1ee363 1196print_spaces (int n, struct ui_file *file)
c906108c 1197{
392a587b 1198 fputs_unfiltered (n_spaces (n), file);
c906108c
SS
1199}
1200
1201/* Print a host address. */
1202
1203void
ac16bf07 1204gdb_print_host_address (const void *addr, struct ui_file *stream)
c906108c
SS
1205{
1206
1207 /* We could use the %p conversion specifier to fprintf if we had any
1208 way of knowing whether this host supports it. But the following
1209 should work on the Alpha and on 32 bit machines. */
1210
c5aa993b 1211 fprintf_filtered (stream, "0x%lx", (unsigned long) addr);
c906108c 1212}
c906108c 1213\f
c5aa993b 1214
981c7f5a 1215/* This function supports the query, nquery, and yquery functions.
cbdeadca 1216 Ask user a y-or-n question and return 0 if answer is no, 1 if
981c7f5a
DJ
1217 answer is yes, or default the answer to the specified default
1218 (for yquery or nquery). DEFCHAR may be 'y' or 'n' to provide a
1219 default answer, or '\0' for no default.
cbdeadca
JJ
1220 CTLSTR is the control string and should end in "? ". It should
1221 not say how to answer, because we do that.
1222 ARGS are the arguments passed along with the CTLSTR argument to
1223 printf. */
1224
bee0189a 1225static int ATTR_FORMAT (printf, 1, 0)
cbdeadca
JJ
1226defaulted_query (const char *ctlstr, const char defchar, va_list args)
1227{
1228 int answer;
1229 int ans2;
1230 int retval;
1231 int def_value;
1232 char def_answer, not_def_answer;
981c7f5a 1233 char *y_string, *n_string, *question;
cbdeadca
JJ
1234
1235 /* Set up according to which answer is the default. */
981c7f5a
DJ
1236 if (defchar == '\0')
1237 {
1238 def_value = 1;
1239 def_answer = 'Y';
1240 not_def_answer = 'N';
1241 y_string = "y";
1242 n_string = "n";
1243 }
1244 else if (defchar == 'y')
cbdeadca
JJ
1245 {
1246 def_value = 1;
1247 def_answer = 'Y';
1248 not_def_answer = 'N';
1249 y_string = "[y]";
1250 n_string = "n";
1251 }
1252 else
1253 {
1254 def_value = 0;
1255 def_answer = 'N';
1256 not_def_answer = 'Y';
1257 y_string = "y";
1258 n_string = "[n]";
1259 }
1260
981c7f5a
DJ
1261 /* Automatically answer the default value if the user did not want
1262 prompts. */
1263 if (! caution)
1264 return def_value;
1265
1266 /* If input isn't coming from the user directly, just say what
1267 question we're asking, and then answer "yes" automatically. This
1268 way, important error messages don't get lost when talking to GDB
1269 over a pipe. */
1270 if (! input_from_terminal_p ())
1271 {
1272 wrap_here ("");
1273 vfprintf_filtered (gdb_stdout, ctlstr, args);
1274
1275 printf_filtered (_("(%s or %s) [answered %c; input not from terminal]\n"),
1276 y_string, n_string, def_answer);
1277 gdb_flush (gdb_stdout);
1278
1279 return def_value;
1280 }
1281
698ba934
DJ
1282 /* Automatically answer the default value if input is not from the user
1283 directly, or if the user did not want prompts. */
1284 if (!input_from_terminal_p () || !caution)
1285 return def_value;
1286
9a4105ab 1287 if (deprecated_query_hook)
cbdeadca 1288 {
9a4105ab 1289 return deprecated_query_hook (ctlstr, args);
cbdeadca
JJ
1290 }
1291
981c7f5a
DJ
1292 /* Format the question outside of the loop, to avoid reusing args. */
1293 question = xstrvprintf (ctlstr, args);
1294
cbdeadca
JJ
1295 while (1)
1296 {
1297 wrap_here (""); /* Flush any buffered output */
1298 gdb_flush (gdb_stdout);
1299
1300 if (annotation_level > 1)
a3f17187 1301 printf_filtered (("\n\032\032pre-query\n"));
cbdeadca 1302
981c7f5a 1303 fputs_filtered (question, gdb_stdout);
a3f17187 1304 printf_filtered (_("(%s or %s) "), y_string, n_string);
cbdeadca
JJ
1305
1306 if (annotation_level > 1)
a3f17187 1307 printf_filtered (("\n\032\032query\n"));
cbdeadca
JJ
1308
1309 wrap_here ("");
1310 gdb_flush (gdb_stdout);
1311
1312 answer = fgetc (stdin);
1313 clearerr (stdin); /* in case of C-d */
1314 if (answer == EOF) /* C-d */
1315 {
fa3fd85b 1316 printf_filtered ("EOF [assumed %c]\n", def_answer);
cbdeadca
JJ
1317 retval = def_value;
1318 break;
1319 }
1320 /* Eat rest of input line, to EOF or newline */
1321 if (answer != '\n')
1322 do
1323 {
1324 ans2 = fgetc (stdin);
1325 clearerr (stdin);
1326 }
1327 while (ans2 != EOF && ans2 != '\n' && ans2 != '\r');
1328
1329 if (answer >= 'a')
1330 answer -= 040;
1331 /* Check answer. For the non-default, the user must specify
1332 the non-default explicitly. */
1333 if (answer == not_def_answer)
1334 {
1335 retval = !def_value;
1336 break;
1337 }
981c7f5a
DJ
1338 /* Otherwise, if a default was specified, the user may either
1339 specify the required input or have it default by entering
1340 nothing. */
1341 if (answer == def_answer
1342 || (defchar != '\0' &&
1343 (answer == '\n' || answer == '\r' || answer == EOF)))
cbdeadca
JJ
1344 {
1345 retval = def_value;
1346 break;
1347 }
1348 /* Invalid entries are not defaulted and require another selection. */
a3f17187 1349 printf_filtered (_("Please answer %s or %s.\n"),
cbdeadca
JJ
1350 y_string, n_string);
1351 }
1352
981c7f5a 1353 xfree (question);
cbdeadca 1354 if (annotation_level > 1)
a3f17187 1355 printf_filtered (("\n\032\032post-query\n"));
cbdeadca
JJ
1356 return retval;
1357}
1358\f
1359
1360/* Ask user a y-or-n question and return 0 if answer is no, 1 if
1361 answer is yes, or 0 if answer is defaulted.
1362 Takes three args which are given to printf to print the question.
1363 The first, a control string, should end in "? ".
1364 It should not say how to answer, because we do that. */
1365
1366int
1367nquery (const char *ctlstr, ...)
1368{
1369 va_list args;
1370
1371 va_start (args, ctlstr);
1372 return defaulted_query (ctlstr, 'n', args);
1373 va_end (args);
1374}
1375
1376/* Ask user a y-or-n question and return 0 if answer is no, 1 if
1377 answer is yes, or 1 if answer is defaulted.
1378 Takes three args which are given to printf to print the question.
1379 The first, a control string, should end in "? ".
1380 It should not say how to answer, because we do that. */
1381
1382int
1383yquery (const char *ctlstr, ...)
1384{
1385 va_list args;
1386
1387 va_start (args, ctlstr);
1388 return defaulted_query (ctlstr, 'y', args);
1389 va_end (args);
1390}
1391
981c7f5a
DJ
1392/* Ask user a y-or-n question and return 1 iff answer is yes.
1393 Takes three args which are given to printf to print the question.
1394 The first, a control string, should end in "? ".
1395 It should not say how to answer, because we do that. */
1396
1397int
1398query (const char *ctlstr, ...)
1399{
1400 va_list args;
1401
1402 va_start (args, ctlstr);
1403 return defaulted_query (ctlstr, '\0', args);
1404 va_end (args);
1405}
1406
234b45d4
KB
1407/* Print an error message saying that we couldn't make sense of a
1408 \^mumble sequence in a string or character constant. START and END
1409 indicate a substring of some larger string that contains the
1410 erroneous backslash sequence, missing the initial backslash. */
1411static NORETURN int
1412no_control_char_error (const char *start, const char *end)
1413{
1414 int len = end - start;
1415 char *copy = alloca (end - start + 1);
1416
1417 memcpy (copy, start, len);
1418 copy[len] = '\0';
1419
8a3fe4f8 1420 error (_("There is no control character `\\%s' in the `%s' character set."),
8731e58e 1421 copy, target_charset ());
234b45d4
KB
1422}
1423
c906108c
SS
1424/* Parse a C escape sequence. STRING_PTR points to a variable
1425 containing a pointer to the string to parse. That pointer
1426 should point to the character after the \. That pointer
1427 is updated past the characters we use. The value of the
1428 escape sequence is returned.
1429
1430 A negative value means the sequence \ newline was seen,
1431 which is supposed to be equivalent to nothing at all.
1432
1433 If \ is followed by a null character, we return a negative
1434 value and leave the string pointer pointing at the null character.
1435
1436 If \ is followed by 000, we return 0 and leave the string pointer
1437 after the zeros. A value of 0 does not mean end of string. */
1438
1439int
fba45db2 1440parse_escape (char **string_ptr)
c906108c 1441{
234b45d4 1442 int target_char;
52f0bd74 1443 int c = *(*string_ptr)++;
234b45d4
KB
1444 if (c_parse_backslash (c, &target_char))
1445 return target_char;
8731e58e
AC
1446 else
1447 switch (c)
234b45d4 1448 {
8731e58e
AC
1449 case '\n':
1450 return -2;
1451 case 0:
1452 (*string_ptr)--;
1453 return 0;
1454 case '^':
1455 {
1456 /* Remember where this escape sequence started, for reporting
1457 errors. */
1458 char *sequence_start_pos = *string_ptr - 1;
234b45d4 1459
8731e58e
AC
1460 c = *(*string_ptr)++;
1461
1462 if (c == '?')
1463 {
1464 /* XXXCHARSET: What is `delete' in the host character set? */
1465 c = 0177;
1466
1467 if (!host_char_to_target (c, &target_char))
8a3fe4f8
AC
1468 error (_("There is no character corresponding to `Delete' "
1469 "in the target character set `%s'."), host_charset ());
8731e58e
AC
1470
1471 return target_char;
1472 }
1473 else if (c == '\\')
1474 target_char = parse_escape (string_ptr);
1475 else
1476 {
1477 if (!host_char_to_target (c, &target_char))
1478 no_control_char_error (sequence_start_pos, *string_ptr);
1479 }
1480
1481 /* Now target_char is something like `c', and we want to find
1482 its control-character equivalent. */
1483 if (!target_char_to_control_char (target_char, &target_char))
1484 no_control_char_error (sequence_start_pos, *string_ptr);
1485
1486 return target_char;
1487 }
1488
1489 /* XXXCHARSET: we need to use isdigit and value-of-digit
1490 methods of the host character set here. */
1491
1492 case '0':
1493 case '1':
1494 case '2':
1495 case '3':
1496 case '4':
1497 case '5':
1498 case '6':
1499 case '7':
1500 {
aa1ee363
AC
1501 int i = c - '0';
1502 int count = 0;
8731e58e
AC
1503 while (++count < 3)
1504 {
5cb316ef
AC
1505 c = (**string_ptr);
1506 if (c >= '0' && c <= '7')
8731e58e 1507 {
5cb316ef 1508 (*string_ptr)++;
8731e58e
AC
1509 i *= 8;
1510 i += c - '0';
1511 }
1512 else
1513 {
8731e58e
AC
1514 break;
1515 }
1516 }
1517 return i;
1518 }
1519 default:
1520 if (!host_char_to_target (c, &target_char))
1521 error
1522 ("The escape sequence `\%c' is equivalent to plain `%c', which"
1523 " has no equivalent\n" "in the `%s' character set.", c, c,
1524 target_charset ());
1525 return target_char;
c906108c 1526 }
c906108c
SS
1527}
1528\f
1529/* Print the character C on STREAM as part of the contents of a literal
1530 string whose delimiter is QUOTER. Note that this routine should only
1531 be call for printing things which are independent of the language
1532 of the program being debugged. */
1533
43e526b9 1534static void
74f832da 1535printchar (int c, void (*do_fputs) (const char *, struct ui_file *),
bee0189a
DJ
1536 void (*do_fprintf) (struct ui_file *, const char *, ...)
1537 ATTRIBUTE_FPTR_PRINTF_2, struct ui_file *stream, int quoter)
c906108c
SS
1538{
1539
1540 c &= 0xFF; /* Avoid sign bit follies */
1541
c5aa993b
JM
1542 if (c < 0x20 || /* Low control chars */
1543 (c >= 0x7F && c < 0xA0) || /* DEL, High controls */
1544 (sevenbit_strings && c >= 0x80))
1545 { /* high order bit set */
1546 switch (c)
1547 {
1548 case '\n':
43e526b9 1549 do_fputs ("\\n", stream);
c5aa993b
JM
1550 break;
1551 case '\b':
43e526b9 1552 do_fputs ("\\b", stream);
c5aa993b
JM
1553 break;
1554 case '\t':
43e526b9 1555 do_fputs ("\\t", stream);
c5aa993b
JM
1556 break;
1557 case '\f':
43e526b9 1558 do_fputs ("\\f", stream);
c5aa993b
JM
1559 break;
1560 case '\r':
43e526b9 1561 do_fputs ("\\r", stream);
c5aa993b
JM
1562 break;
1563 case '\033':
43e526b9 1564 do_fputs ("\\e", stream);
c5aa993b
JM
1565 break;
1566 case '\007':
43e526b9 1567 do_fputs ("\\a", stream);
c5aa993b
JM
1568 break;
1569 default:
43e526b9 1570 do_fprintf (stream, "\\%.3o", (unsigned int) c);
c5aa993b
JM
1571 break;
1572 }
1573 }
1574 else
1575 {
1576 if (c == '\\' || c == quoter)
43e526b9
JM
1577 do_fputs ("\\", stream);
1578 do_fprintf (stream, "%c", c);
c5aa993b 1579 }
c906108c 1580}
43e526b9
JM
1581
1582/* Print the character C on STREAM as part of the contents of a
1583 literal string whose delimiter is QUOTER. Note that these routines
1584 should only be call for printing things which are independent of
1585 the language of the program being debugged. */
1586
1587void
fba45db2 1588fputstr_filtered (const char *str, int quoter, struct ui_file *stream)
43e526b9
JM
1589{
1590 while (*str)
1591 printchar (*str++, fputs_filtered, fprintf_filtered, stream, quoter);
1592}
1593
1594void
fba45db2 1595fputstr_unfiltered (const char *str, int quoter, struct ui_file *stream)
43e526b9
JM
1596{
1597 while (*str)
1598 printchar (*str++, fputs_unfiltered, fprintf_unfiltered, stream, quoter);
1599}
1600
0876f84a
DJ
1601void
1602fputstrn_filtered (const char *str, int n, int quoter,
1603 struct ui_file *stream)
1604{
1605 int i;
1606 for (i = 0; i < n; i++)
1607 printchar (str[i], fputs_filtered, fprintf_filtered, stream, quoter);
1608}
1609
43e526b9 1610void
8731e58e
AC
1611fputstrn_unfiltered (const char *str, int n, int quoter,
1612 struct ui_file *stream)
43e526b9
JM
1613{
1614 int i;
1615 for (i = 0; i < n; i++)
1616 printchar (str[i], fputs_unfiltered, fprintf_unfiltered, stream, quoter);
1617}
c906108c 1618\f
c5aa993b 1619
c906108c
SS
1620/* Number of lines per page or UINT_MAX if paging is disabled. */
1621static unsigned int lines_per_page;
920d2a44
AC
1622static void
1623show_lines_per_page (struct ui_file *file, int from_tty,
1624 struct cmd_list_element *c, const char *value)
1625{
1626 fprintf_filtered (file, _("\
1627Number of lines gdb thinks are in a page is %s.\n"),
1628 value);
1629}
eb0d3137 1630
cbfbd72a 1631/* Number of chars per line or UINT_MAX if line folding is disabled. */
c906108c 1632static unsigned int chars_per_line;
920d2a44
AC
1633static void
1634show_chars_per_line (struct ui_file *file, int from_tty,
1635 struct cmd_list_element *c, const char *value)
1636{
1637 fprintf_filtered (file, _("\
1638Number of characters gdb thinks are in a line is %s.\n"),
1639 value);
1640}
eb0d3137 1641
c906108c
SS
1642/* Current count of lines printed on this page, chars on this line. */
1643static unsigned int lines_printed, chars_printed;
1644
1645/* Buffer and start column of buffered text, for doing smarter word-
1646 wrapping. When someone calls wrap_here(), we start buffering output
1647 that comes through fputs_filtered(). If we see a newline, we just
1648 spit it out and forget about the wrap_here(). If we see another
1649 wrap_here(), we spit it out and remember the newer one. If we see
1650 the end of the line, we spit out a newline, the indent, and then
1651 the buffered output. */
1652
1653/* Malloc'd buffer with chars_per_line+2 bytes. Contains characters which
1654 are waiting to be output (they have already been counted in chars_printed).
1655 When wrap_buffer[0] is null, the buffer is empty. */
1656static char *wrap_buffer;
1657
1658/* Pointer in wrap_buffer to the next character to fill. */
1659static char *wrap_pointer;
1660
1661/* String to indent by if the wrap occurs. Must not be NULL if wrap_column
1662 is non-zero. */
1663static char *wrap_indent;
1664
1665/* Column number on the screen where wrap_buffer begins, or 0 if wrapping
1666 is not in effect. */
1667static int wrap_column;
c906108c 1668\f
c5aa993b 1669
eb0d3137
MK
1670/* Inialize the number of lines per page and chars per line. */
1671
c906108c 1672void
fba45db2 1673init_page_info (void)
c906108c
SS
1674{
1675#if defined(TUI)
5ecb1806 1676 if (!tui_get_command_dimension (&chars_per_line, &lines_per_page))
c906108c
SS
1677#endif
1678 {
eb0d3137 1679 int rows, cols;
c906108c 1680
ec145965
EZ
1681#if defined(__GO32__)
1682 rows = ScreenRows ();
1683 cols = ScreenCols ();
1684 lines_per_page = rows;
1685 chars_per_line = cols;
1686#else
eb0d3137
MK
1687 /* Make sure Readline has initialized its terminal settings. */
1688 rl_reset_terminal (NULL);
c906108c 1689
eb0d3137
MK
1690 /* Get the screen size from Readline. */
1691 rl_get_screen_size (&rows, &cols);
1692 lines_per_page = rows;
1693 chars_per_line = cols;
c906108c 1694
eb0d3137
MK
1695 /* Readline should have fetched the termcap entry for us. */
1696 if (tgetnum ("li") < 0 || getenv ("EMACS"))
1697 {
1698 /* The number of lines per page is not mentioned in the
1699 terminal description. This probably means that paging is
1700 not useful (e.g. emacs shell window), so disable paging. */
1701 lines_per_page = UINT_MAX;
1702 }
c906108c 1703
eb0d3137 1704 /* FIXME: Get rid of this junk. */
c906108c 1705#if defined(SIGWINCH) && defined(SIGWINCH_HANDLER)
c906108c
SS
1706 SIGWINCH_HANDLER (SIGWINCH);
1707#endif
eb0d3137 1708
c906108c 1709 /* If the output is not a terminal, don't paginate it. */
d9fcf2fb 1710 if (!ui_file_isatty (gdb_stdout))
c5aa993b 1711 lines_per_page = UINT_MAX;
eb0d3137 1712#endif
ec145965 1713 }
eb0d3137
MK
1714
1715 set_screen_size ();
c5aa993b 1716 set_width ();
c906108c
SS
1717}
1718
eb0d3137
MK
1719/* Set the screen size based on LINES_PER_PAGE and CHARS_PER_LINE. */
1720
1721static void
1722set_screen_size (void)
1723{
1724 int rows = lines_per_page;
1725 int cols = chars_per_line;
1726
1727 if (rows <= 0)
1728 rows = INT_MAX;
1729
1730 if (cols <= 0)
0caa462c 1731 cols = INT_MAX;
eb0d3137
MK
1732
1733 /* Update Readline's idea of the terminal size. */
1734 rl_set_screen_size (rows, cols);
1735}
1736
1737/* Reinitialize WRAP_BUFFER according to the current value of
1738 CHARS_PER_LINE. */
1739
c906108c 1740static void
fba45db2 1741set_width (void)
c906108c
SS
1742{
1743 if (chars_per_line == 0)
c5aa993b 1744 init_page_info ();
c906108c
SS
1745
1746 if (!wrap_buffer)
1747 {
1748 wrap_buffer = (char *) xmalloc (chars_per_line + 2);
1749 wrap_buffer[0] = '\0';
1750 }
1751 else
1752 wrap_buffer = (char *) xrealloc (wrap_buffer, chars_per_line + 2);
eb0d3137 1753 wrap_pointer = wrap_buffer; /* Start it at the beginning. */
c906108c
SS
1754}
1755
c5aa993b 1756static void
fba45db2 1757set_width_command (char *args, int from_tty, struct cmd_list_element *c)
c906108c 1758{
eb0d3137 1759 set_screen_size ();
c906108c
SS
1760 set_width ();
1761}
1762
eb0d3137
MK
1763static void
1764set_height_command (char *args, int from_tty, struct cmd_list_element *c)
1765{
1766 set_screen_size ();
1767}
1768
c906108c
SS
1769/* Wait, so the user can read what's on the screen. Prompt the user
1770 to continue by pressing RETURN. */
1771
1772static void
fba45db2 1773prompt_for_continue (void)
c906108c
SS
1774{
1775 char *ignore;
1776 char cont_prompt[120];
1777
1778 if (annotation_level > 1)
a3f17187 1779 printf_unfiltered (("\n\032\032pre-prompt-for-continue\n"));
c906108c
SS
1780
1781 strcpy (cont_prompt,
1782 "---Type <return> to continue, or q <return> to quit---");
1783 if (annotation_level > 1)
1784 strcat (cont_prompt, "\n\032\032prompt-for-continue\n");
1785
1786 /* We must do this *before* we call gdb_readline, else it will eventually
1787 call us -- thinking that we're trying to print beyond the end of the
1788 screen. */
1789 reinitialize_more_filter ();
1790
1791 immediate_quit++;
1792 /* On a real operating system, the user can quit with SIGINT.
1793 But not on GO32.
1794
1795 'q' is provided on all systems so users don't have to change habits
1796 from system to system, and because telling them what to do in
1797 the prompt is more user-friendly than expecting them to think of
1798 SIGINT. */
1799 /* Call readline, not gdb_readline, because GO32 readline handles control-C
1800 whereas control-C to gdb_readline will cause the user to get dumped
1801 out to DOS. */
b4f5539f 1802 ignore = gdb_readline_wrapper (cont_prompt);
c906108c
SS
1803
1804 if (annotation_level > 1)
a3f17187 1805 printf_unfiltered (("\n\032\032post-prompt-for-continue\n"));
c906108c
SS
1806
1807 if (ignore)
1808 {
1809 char *p = ignore;
1810 while (*p == ' ' || *p == '\t')
1811 ++p;
1812 if (p[0] == 'q')
362646f5 1813 async_request_quit (0);
b8c9b27d 1814 xfree (ignore);
c906108c
SS
1815 }
1816 immediate_quit--;
1817
1818 /* Now we have to do this again, so that GDB will know that it doesn't
1819 need to save the ---Type <return>--- line at the top of the screen. */
1820 reinitialize_more_filter ();
1821
1822 dont_repeat (); /* Forget prev cmd -- CR won't repeat it. */
1823}
1824
1825/* Reinitialize filter; ie. tell it to reset to original values. */
1826
1827void
fba45db2 1828reinitialize_more_filter (void)
c906108c
SS
1829{
1830 lines_printed = 0;
1831 chars_printed = 0;
1832}
1833
1834/* Indicate that if the next sequence of characters overflows the line,
1835 a newline should be inserted here rather than when it hits the end.
1836 If INDENT is non-null, it is a string to be printed to indent the
1837 wrapped part on the next line. INDENT must remain accessible until
1838 the next call to wrap_here() or until a newline is printed through
1839 fputs_filtered().
1840
1841 If the line is already overfull, we immediately print a newline and
1842 the indentation, and disable further wrapping.
1843
1844 If we don't know the width of lines, but we know the page height,
1845 we must not wrap words, but should still keep track of newlines
1846 that were explicitly printed.
1847
1848 INDENT should not contain tabs, as that will mess up the char count
1849 on the next line. FIXME.
1850
1851 This routine is guaranteed to force out any output which has been
1852 squirreled away in the wrap_buffer, so wrap_here ((char *)0) can be
1853 used to force out output from the wrap_buffer. */
1854
1855void
fba45db2 1856wrap_here (char *indent)
c906108c
SS
1857{
1858 /* This should have been allocated, but be paranoid anyway. */
1859 if (!wrap_buffer)
e2e0b3e5 1860 internal_error (__FILE__, __LINE__, _("failed internal consistency check"));
c906108c
SS
1861
1862 if (wrap_buffer[0])
1863 {
1864 *wrap_pointer = '\0';
1865 fputs_unfiltered (wrap_buffer, gdb_stdout);
1866 }
1867 wrap_pointer = wrap_buffer;
1868 wrap_buffer[0] = '\0';
c5aa993b 1869 if (chars_per_line == UINT_MAX) /* No line overflow checking */
c906108c
SS
1870 {
1871 wrap_column = 0;
1872 }
1873 else if (chars_printed >= chars_per_line)
1874 {
1875 puts_filtered ("\n");
1876 if (indent != NULL)
1877 puts_filtered (indent);
1878 wrap_column = 0;
1879 }
1880 else
1881 {
1882 wrap_column = chars_printed;
1883 if (indent == NULL)
1884 wrap_indent = "";
1885 else
1886 wrap_indent = indent;
1887 }
1888}
1889
4a351cef
AF
1890/* Print input string to gdb_stdout, filtered, with wrap,
1891 arranging strings in columns of n chars. String can be
1892 right or left justified in the column. Never prints
1893 trailing spaces. String should never be longer than
1894 width. FIXME: this could be useful for the EXAMINE
1895 command, which currently doesn't tabulate very well */
1896
1897void
1898puts_filtered_tabular (char *string, int width, int right)
1899{
1900 int spaces = 0;
1901 int stringlen;
1902 char *spacebuf;
1903
1904 gdb_assert (chars_per_line > 0);
1905 if (chars_per_line == UINT_MAX)
1906 {
1907 fputs_filtered (string, gdb_stdout);
1908 fputs_filtered ("\n", gdb_stdout);
1909 return;
1910 }
1911
1912 if (((chars_printed - 1) / width + 2) * width >= chars_per_line)
1913 fputs_filtered ("\n", gdb_stdout);
1914
1915 if (width >= chars_per_line)
1916 width = chars_per_line - 1;
1917
1918 stringlen = strlen (string);
1919
1920 if (chars_printed > 0)
1921 spaces = width - (chars_printed - 1) % width - 1;
1922 if (right)
1923 spaces += width - stringlen;
1924
1925 spacebuf = alloca (spaces + 1);
1926 spacebuf[spaces] = '\0';
1927 while (spaces--)
1928 spacebuf[spaces] = ' ';
1929
1930 fputs_filtered (spacebuf, gdb_stdout);
1931 fputs_filtered (string, gdb_stdout);
1932}
1933
1934
c906108c
SS
1935/* Ensure that whatever gets printed next, using the filtered output
1936 commands, starts at the beginning of the line. I.E. if there is
1937 any pending output for the current line, flush it and start a new
1938 line. Otherwise do nothing. */
1939
1940void
fba45db2 1941begin_line (void)
c906108c
SS
1942{
1943 if (chars_printed > 0)
1944 {
1945 puts_filtered ("\n");
1946 }
1947}
1948
ac9a91a7 1949
c906108c
SS
1950/* Like fputs but if FILTER is true, pause after every screenful.
1951
1952 Regardless of FILTER can wrap at points other than the final
1953 character of a line.
1954
1955 Unlike fputs, fputs_maybe_filtered does not return a value.
1956 It is OK for LINEBUFFER to be NULL, in which case just don't print
1957 anything.
1958
1959 Note that a longjmp to top level may occur in this routine (only if
1960 FILTER is true) (since prompt_for_continue may do so) so this
1961 routine should not be called when cleanups are not in place. */
1962
1963static void
fba45db2
KB
1964fputs_maybe_filtered (const char *linebuffer, struct ui_file *stream,
1965 int filter)
c906108c
SS
1966{
1967 const char *lineptr;
1968
1969 if (linebuffer == 0)
1970 return;
1971
1972 /* Don't do any filtering if it is disabled. */
7a292a7a 1973 if ((stream != gdb_stdout) || !pagination_enabled
c5aa993b 1974 || (lines_per_page == UINT_MAX && chars_per_line == UINT_MAX))
c906108c
SS
1975 {
1976 fputs_unfiltered (linebuffer, stream);
1977 return;
1978 }
1979
1980 /* Go through and output each character. Show line extension
1981 when this is necessary; prompt user for new page when this is
1982 necessary. */
c5aa993b 1983
c906108c
SS
1984 lineptr = linebuffer;
1985 while (*lineptr)
1986 {
1987 /* Possible new page. */
8731e58e 1988 if (filter && (lines_printed >= lines_per_page - 1))
c906108c
SS
1989 prompt_for_continue ();
1990
1991 while (*lineptr && *lineptr != '\n')
1992 {
1993 /* Print a single line. */
1994 if (*lineptr == '\t')
1995 {
1996 if (wrap_column)
1997 *wrap_pointer++ = '\t';
1998 else
1999 fputc_unfiltered ('\t', stream);
2000 /* Shifting right by 3 produces the number of tab stops
2001 we have already passed, and then adding one and
c5aa993b 2002 shifting left 3 advances to the next tab stop. */
c906108c
SS
2003 chars_printed = ((chars_printed >> 3) + 1) << 3;
2004 lineptr++;
2005 }
2006 else
2007 {
2008 if (wrap_column)
2009 *wrap_pointer++ = *lineptr;
2010 else
c5aa993b 2011 fputc_unfiltered (*lineptr, stream);
c906108c
SS
2012 chars_printed++;
2013 lineptr++;
2014 }
c5aa993b 2015
c906108c
SS
2016 if (chars_printed >= chars_per_line)
2017 {
2018 unsigned int save_chars = chars_printed;
2019
2020 chars_printed = 0;
2021 lines_printed++;
2022 /* If we aren't actually wrapping, don't output newline --
c5aa993b
JM
2023 if chars_per_line is right, we probably just overflowed
2024 anyway; if it's wrong, let us keep going. */
c906108c
SS
2025 if (wrap_column)
2026 fputc_unfiltered ('\n', stream);
2027
2028 /* Possible new page. */
2029 if (lines_printed >= lines_per_page - 1)
2030 prompt_for_continue ();
2031
2032 /* Now output indentation and wrapped string */
2033 if (wrap_column)
2034 {
2035 fputs_unfiltered (wrap_indent, stream);
8731e58e 2036 *wrap_pointer = '\0'; /* Null-terminate saved stuff */
c5aa993b 2037 fputs_unfiltered (wrap_buffer, stream); /* and eject it */
c906108c
SS
2038 /* FIXME, this strlen is what prevents wrap_indent from
2039 containing tabs. However, if we recurse to print it
2040 and count its chars, we risk trouble if wrap_indent is
2041 longer than (the user settable) chars_per_line.
2042 Note also that this can set chars_printed > chars_per_line
2043 if we are printing a long string. */
2044 chars_printed = strlen (wrap_indent)
c5aa993b 2045 + (save_chars - wrap_column);
c906108c
SS
2046 wrap_pointer = wrap_buffer; /* Reset buffer */
2047 wrap_buffer[0] = '\0';
c5aa993b
JM
2048 wrap_column = 0; /* And disable fancy wrap */
2049 }
c906108c
SS
2050 }
2051 }
2052
2053 if (*lineptr == '\n')
2054 {
2055 chars_printed = 0;
c5aa993b 2056 wrap_here ((char *) 0); /* Spit out chars, cancel further wraps */
c906108c
SS
2057 lines_printed++;
2058 fputc_unfiltered ('\n', stream);
2059 lineptr++;
2060 }
2061 }
2062}
2063
2064void
fba45db2 2065fputs_filtered (const char *linebuffer, struct ui_file *stream)
c906108c
SS
2066{
2067 fputs_maybe_filtered (linebuffer, stream, 1);
2068}
2069
2070int
fba45db2 2071putchar_unfiltered (int c)
c906108c 2072{
11cf8741 2073 char buf = c;
d9fcf2fb 2074 ui_file_write (gdb_stdout, &buf, 1);
c906108c
SS
2075 return c;
2076}
2077
d1f4cff8
AC
2078/* Write character C to gdb_stdout using GDB's paging mechanism and return C.
2079 May return nonlocally. */
2080
2081int
2082putchar_filtered (int c)
2083{
2084 return fputc_filtered (c, gdb_stdout);
2085}
2086
c906108c 2087int
fba45db2 2088fputc_unfiltered (int c, struct ui_file *stream)
c906108c 2089{
11cf8741 2090 char buf = c;
d9fcf2fb 2091 ui_file_write (stream, &buf, 1);
c906108c
SS
2092 return c;
2093}
2094
2095int
fba45db2 2096fputc_filtered (int c, struct ui_file *stream)
c906108c
SS
2097{
2098 char buf[2];
2099
2100 buf[0] = c;
2101 buf[1] = 0;
2102 fputs_filtered (buf, stream);
2103 return c;
2104}
2105
2106/* puts_debug is like fputs_unfiltered, except it prints special
2107 characters in printable fashion. */
2108
2109void
fba45db2 2110puts_debug (char *prefix, char *string, char *suffix)
c906108c
SS
2111{
2112 int ch;
2113
2114 /* Print prefix and suffix after each line. */
2115 static int new_line = 1;
2116 static int return_p = 0;
2117 static char *prev_prefix = "";
2118 static char *prev_suffix = "";
2119
2120 if (*string == '\n')
2121 return_p = 0;
2122
2123 /* If the prefix is changing, print the previous suffix, a new line,
2124 and the new prefix. */
c5aa993b 2125 if ((return_p || (strcmp (prev_prefix, prefix) != 0)) && !new_line)
c906108c 2126 {
9846de1b
JM
2127 fputs_unfiltered (prev_suffix, gdb_stdlog);
2128 fputs_unfiltered ("\n", gdb_stdlog);
2129 fputs_unfiltered (prefix, gdb_stdlog);
c906108c
SS
2130 }
2131
2132 /* Print prefix if we printed a newline during the previous call. */
2133 if (new_line)
2134 {
2135 new_line = 0;
9846de1b 2136 fputs_unfiltered (prefix, gdb_stdlog);
c906108c
SS
2137 }
2138
2139 prev_prefix = prefix;
2140 prev_suffix = suffix;
2141
2142 /* Output characters in a printable format. */
2143 while ((ch = *string++) != '\0')
2144 {
2145 switch (ch)
c5aa993b 2146 {
c906108c
SS
2147 default:
2148 if (isprint (ch))
9846de1b 2149 fputc_unfiltered (ch, gdb_stdlog);
c906108c
SS
2150
2151 else
9846de1b 2152 fprintf_unfiltered (gdb_stdlog, "\\x%02x", ch & 0xff);
c906108c
SS
2153 break;
2154
c5aa993b
JM
2155 case '\\':
2156 fputs_unfiltered ("\\\\", gdb_stdlog);
2157 break;
2158 case '\b':
2159 fputs_unfiltered ("\\b", gdb_stdlog);
2160 break;
2161 case '\f':
2162 fputs_unfiltered ("\\f", gdb_stdlog);
2163 break;
2164 case '\n':
2165 new_line = 1;
2166 fputs_unfiltered ("\\n", gdb_stdlog);
2167 break;
2168 case '\r':
2169 fputs_unfiltered ("\\r", gdb_stdlog);
2170 break;
2171 case '\t':
2172 fputs_unfiltered ("\\t", gdb_stdlog);
2173 break;
2174 case '\v':
2175 fputs_unfiltered ("\\v", gdb_stdlog);
2176 break;
2177 }
c906108c
SS
2178
2179 return_p = ch == '\r';
2180 }
2181
2182 /* Print suffix if we printed a newline. */
2183 if (new_line)
2184 {
9846de1b
JM
2185 fputs_unfiltered (suffix, gdb_stdlog);
2186 fputs_unfiltered ("\n", gdb_stdlog);
c906108c
SS
2187 }
2188}
2189
2190
2191/* Print a variable number of ARGS using format FORMAT. If this
2192 information is going to put the amount written (since the last call
2193 to REINITIALIZE_MORE_FILTER or the last page break) over the page size,
2194 call prompt_for_continue to get the users permision to continue.
2195
2196 Unlike fprintf, this function does not return a value.
2197
2198 We implement three variants, vfprintf (takes a vararg list and stream),
2199 fprintf (takes a stream to write on), and printf (the usual).
2200
2201 Note also that a longjmp to top level may occur in this routine
2202 (since prompt_for_continue may do so) so this routine should not be
2203 called when cleanups are not in place. */
2204
2205static void
fba45db2
KB
2206vfprintf_maybe_filtered (struct ui_file *stream, const char *format,
2207 va_list args, int filter)
c906108c
SS
2208{
2209 char *linebuffer;
2210 struct cleanup *old_cleanups;
2211
e623b504 2212 linebuffer = xstrvprintf (format, args);
b8c9b27d 2213 old_cleanups = make_cleanup (xfree, linebuffer);
c906108c
SS
2214 fputs_maybe_filtered (linebuffer, stream, filter);
2215 do_cleanups (old_cleanups);
2216}
2217
2218
2219void
fba45db2 2220vfprintf_filtered (struct ui_file *stream, const char *format, va_list args)
c906108c
SS
2221{
2222 vfprintf_maybe_filtered (stream, format, args, 1);
2223}
2224
2225void
fba45db2 2226vfprintf_unfiltered (struct ui_file *stream, const char *format, va_list args)
c906108c
SS
2227{
2228 char *linebuffer;
2229 struct cleanup *old_cleanups;
2230
e623b504 2231 linebuffer = xstrvprintf (format, args);
b8c9b27d 2232 old_cleanups = make_cleanup (xfree, linebuffer);
75feb17d
DJ
2233 if (debug_timestamp && stream == gdb_stdlog)
2234 {
2235 struct timeval tm;
2236 char *timestamp;
2237
2238 gettimeofday (&tm, NULL);
2239 timestamp = xstrprintf ("%ld:%ld ", (long) tm.tv_sec, (long) tm.tv_usec);
2240 make_cleanup (xfree, timestamp);
2241 fputs_unfiltered (timestamp, stream);
2242 }
c906108c
SS
2243 fputs_unfiltered (linebuffer, stream);
2244 do_cleanups (old_cleanups);
2245}
2246
2247void
fba45db2 2248vprintf_filtered (const char *format, va_list args)
c906108c
SS
2249{
2250 vfprintf_maybe_filtered (gdb_stdout, format, args, 1);
2251}
2252
2253void
fba45db2 2254vprintf_unfiltered (const char *format, va_list args)
c906108c
SS
2255{
2256 vfprintf_unfiltered (gdb_stdout, format, args);
2257}
2258
c906108c 2259void
8731e58e 2260fprintf_filtered (struct ui_file *stream, const char *format, ...)
c906108c
SS
2261{
2262 va_list args;
c906108c 2263 va_start (args, format);
c906108c
SS
2264 vfprintf_filtered (stream, format, args);
2265 va_end (args);
2266}
2267
c906108c 2268void
8731e58e 2269fprintf_unfiltered (struct ui_file *stream, const char *format, ...)
c906108c
SS
2270{
2271 va_list args;
c906108c 2272 va_start (args, format);
c906108c
SS
2273 vfprintf_unfiltered (stream, format, args);
2274 va_end (args);
2275}
2276
2277/* Like fprintf_filtered, but prints its result indented.
2278 Called as fprintfi_filtered (spaces, stream, format, ...); */
2279
c906108c 2280void
8731e58e
AC
2281fprintfi_filtered (int spaces, struct ui_file *stream, const char *format,
2282 ...)
c906108c
SS
2283{
2284 va_list args;
c906108c 2285 va_start (args, format);
c906108c
SS
2286 print_spaces_filtered (spaces, stream);
2287
2288 vfprintf_filtered (stream, format, args);
2289 va_end (args);
2290}
2291
2292
c906108c 2293void
8731e58e 2294printf_filtered (const char *format, ...)
c906108c
SS
2295{
2296 va_list args;
c906108c 2297 va_start (args, format);
c906108c
SS
2298 vfprintf_filtered (gdb_stdout, format, args);
2299 va_end (args);
2300}
2301
2302
c906108c 2303void
8731e58e 2304printf_unfiltered (const char *format, ...)
c906108c
SS
2305{
2306 va_list args;
c906108c 2307 va_start (args, format);
c906108c
SS
2308 vfprintf_unfiltered (gdb_stdout, format, args);
2309 va_end (args);
2310}
2311
2312/* Like printf_filtered, but prints it's result indented.
2313 Called as printfi_filtered (spaces, format, ...); */
2314
c906108c 2315void
8731e58e 2316printfi_filtered (int spaces, const char *format, ...)
c906108c
SS
2317{
2318 va_list args;
c906108c 2319 va_start (args, format);
c906108c
SS
2320 print_spaces_filtered (spaces, gdb_stdout);
2321 vfprintf_filtered (gdb_stdout, format, args);
2322 va_end (args);
2323}
2324
2325/* Easy -- but watch out!
2326
2327 This routine is *not* a replacement for puts()! puts() appends a newline.
2328 This one doesn't, and had better not! */
2329
2330void
fba45db2 2331puts_filtered (const char *string)
c906108c
SS
2332{
2333 fputs_filtered (string, gdb_stdout);
2334}
2335
2336void
fba45db2 2337puts_unfiltered (const char *string)
c906108c
SS
2338{
2339 fputs_unfiltered (string, gdb_stdout);
2340}
2341
2342/* Return a pointer to N spaces and a null. The pointer is good
2343 until the next call to here. */
2344char *
fba45db2 2345n_spaces (int n)
c906108c 2346{
392a587b
JM
2347 char *t;
2348 static char *spaces = 0;
2349 static int max_spaces = -1;
c906108c
SS
2350
2351 if (n > max_spaces)
2352 {
2353 if (spaces)
b8c9b27d 2354 xfree (spaces);
c5aa993b
JM
2355 spaces = (char *) xmalloc (n + 1);
2356 for (t = spaces + n; t != spaces;)
c906108c
SS
2357 *--t = ' ';
2358 spaces[n] = '\0';
2359 max_spaces = n;
2360 }
2361
2362 return spaces + max_spaces - n;
2363}
2364
2365/* Print N spaces. */
2366void
fba45db2 2367print_spaces_filtered (int n, struct ui_file *stream)
c906108c
SS
2368{
2369 fputs_filtered (n_spaces (n), stream);
2370}
2371\f
4a351cef 2372/* C++/ObjC demangler stuff. */
c906108c 2373
389e51db
AC
2374/* fprintf_symbol_filtered attempts to demangle NAME, a symbol in language
2375 LANG, using demangling args ARG_MODE, and print it filtered to STREAM.
2376 If the name is not mangled, or the language for the name is unknown, or
2377 demangling is off, the name is printed in its "raw" form. */
c906108c
SS
2378
2379void
8731e58e
AC
2380fprintf_symbol_filtered (struct ui_file *stream, char *name,
2381 enum language lang, int arg_mode)
c906108c
SS
2382{
2383 char *demangled;
2384
2385 if (name != NULL)
2386 {
2387 /* If user wants to see raw output, no problem. */
2388 if (!demangle)
2389 {
2390 fputs_filtered (name, stream);
2391 }
2392 else
2393 {
9a3d7dfd 2394 demangled = language_demangle (language_def (lang), name, arg_mode);
c906108c
SS
2395 fputs_filtered (demangled ? demangled : name, stream);
2396 if (demangled != NULL)
2397 {
b8c9b27d 2398 xfree (demangled);
c906108c
SS
2399 }
2400 }
2401 }
2402}
2403
2404/* Do a strcmp() type operation on STRING1 and STRING2, ignoring any
2405 differences in whitespace. Returns 0 if they match, non-zero if they
2406 don't (slightly different than strcmp()'s range of return values).
c5aa993b 2407
c906108c
SS
2408 As an extra hack, string1=="FOO(ARGS)" matches string2=="FOO".
2409 This "feature" is useful when searching for matching C++ function names
2410 (such as if the user types 'break FOO', where FOO is a mangled C++
2411 function). */
2412
2413int
fba45db2 2414strcmp_iw (const char *string1, const char *string2)
c906108c
SS
2415{
2416 while ((*string1 != '\0') && (*string2 != '\0'))
2417 {
2418 while (isspace (*string1))
2419 {
2420 string1++;
2421 }
2422 while (isspace (*string2))
2423 {
2424 string2++;
2425 }
2426 if (*string1 != *string2)
2427 {
2428 break;
2429 }
2430 if (*string1 != '\0')
2431 {
2432 string1++;
2433 string2++;
2434 }
2435 }
2436 return (*string1 != '\0' && *string1 != '(') || (*string2 != '\0');
2437}
2de7ced7 2438
0fe19209
DC
2439/* This is like strcmp except that it ignores whitespace and treats
2440 '(' as the first non-NULL character in terms of ordering. Like
2441 strcmp (and unlike strcmp_iw), it returns negative if STRING1 <
2442 STRING2, 0 if STRING2 = STRING2, and positive if STRING1 > STRING2
2443 according to that ordering.
2444
2445 If a list is sorted according to this function and if you want to
2446 find names in the list that match some fixed NAME according to
2447 strcmp_iw(LIST_ELT, NAME), then the place to start looking is right
2448 where this function would put NAME.
2449
2450 Here are some examples of why using strcmp to sort is a bad idea:
2451
2452 Whitespace example:
2453
2454 Say your partial symtab contains: "foo<char *>", "goo". Then, if
2455 we try to do a search for "foo<char*>", strcmp will locate this
2456 after "foo<char *>" and before "goo". Then lookup_partial_symbol
2457 will start looking at strings beginning with "goo", and will never
2458 see the correct match of "foo<char *>".
2459
2460 Parenthesis example:
2461
2462 In practice, this is less like to be an issue, but I'll give it a
2463 shot. Let's assume that '$' is a legitimate character to occur in
2464 symbols. (Which may well even be the case on some systems.) Then
2465 say that the partial symbol table contains "foo$" and "foo(int)".
2466 strcmp will put them in this order, since '$' < '('. Now, if the
2467 user searches for "foo", then strcmp will sort "foo" before "foo$".
2468 Then lookup_partial_symbol will notice that strcmp_iw("foo$",
2469 "foo") is false, so it won't proceed to the actual match of
2470 "foo(int)" with "foo". */
2471
2472int
2473strcmp_iw_ordered (const char *string1, const char *string2)
2474{
2475 while ((*string1 != '\0') && (*string2 != '\0'))
2476 {
2477 while (isspace (*string1))
2478 {
2479 string1++;
2480 }
2481 while (isspace (*string2))
2482 {
2483 string2++;
2484 }
2485 if (*string1 != *string2)
2486 {
2487 break;
2488 }
2489 if (*string1 != '\0')
2490 {
2491 string1++;
2492 string2++;
2493 }
2494 }
2495
2496 switch (*string1)
2497 {
2498 /* Characters are non-equal unless they're both '\0'; we want to
2499 make sure we get the comparison right according to our
2500 comparison in the cases where one of them is '\0' or '('. */
2501 case '\0':
2502 if (*string2 == '\0')
2503 return 0;
2504 else
2505 return -1;
2506 case '(':
2507 if (*string2 == '\0')
2508 return 1;
2509 else
2510 return -1;
2511 default:
2512 if (*string2 == '(')
2513 return 1;
2514 else
2515 return *string1 - *string2;
2516 }
2517}
2518
2de7ced7
DJ
2519/* A simple comparison function with opposite semantics to strcmp. */
2520
2521int
2522streq (const char *lhs, const char *rhs)
2523{
2524 return !strcmp (lhs, rhs);
2525}
c906108c 2526\f
c5aa993b 2527
c906108c 2528/*
c5aa993b
JM
2529 ** subset_compare()
2530 ** Answer whether string_to_compare is a full or partial match to
2531 ** template_string. The partial match must be in sequence starting
2532 ** at index 0.
2533 */
c906108c 2534int
fba45db2 2535subset_compare (char *string_to_compare, char *template_string)
7a292a7a
SS
2536{
2537 int match;
8731e58e
AC
2538 if (template_string != (char *) NULL && string_to_compare != (char *) NULL
2539 && strlen (string_to_compare) <= strlen (template_string))
2540 match =
2541 (strncmp
2542 (template_string, string_to_compare, strlen (string_to_compare)) == 0);
7a292a7a
SS
2543 else
2544 match = 0;
2545 return match;
2546}
c906108c 2547
7a292a7a 2548static void
fba45db2 2549pagination_on_command (char *arg, int from_tty)
c906108c
SS
2550{
2551 pagination_enabled = 1;
2552}
2553
7a292a7a 2554static void
fba45db2 2555pagination_off_command (char *arg, int from_tty)
c906108c
SS
2556{
2557 pagination_enabled = 0;
2558}
75feb17d
DJ
2559
2560static void
2561show_debug_timestamp (struct ui_file *file, int from_tty,
2562 struct cmd_list_element *c, const char *value)
2563{
2564 fprintf_filtered (file, _("Timestamping debugging messages is %s.\n"), value);
2565}
c906108c 2566\f
c5aa993b 2567
c906108c 2568void
fba45db2 2569initialize_utils (void)
c906108c
SS
2570{
2571 struct cmd_list_element *c;
2572
35096d9d
AC
2573 add_setshow_uinteger_cmd ("width", class_support, &chars_per_line, _("\
2574Set number of characters gdb thinks are in a line."), _("\
2575Show number of characters gdb thinks are in a line."), NULL,
2576 set_width_command,
920d2a44 2577 show_chars_per_line,
35096d9d
AC
2578 &setlist, &showlist);
2579
2580 add_setshow_uinteger_cmd ("height", class_support, &lines_per_page, _("\
2581Set number of lines gdb thinks are in a page."), _("\
2582Show number of lines gdb thinks are in a page."), NULL,
2583 set_height_command,
920d2a44 2584 show_lines_per_page,
35096d9d 2585 &setlist, &showlist);
c5aa993b 2586
c906108c
SS
2587 init_page_info ();
2588
5bf193a2
AC
2589 add_setshow_boolean_cmd ("demangle", class_support, &demangle, _("\
2590Set demangling of encoded C++/ObjC names when displaying symbols."), _("\
2591Show demangling of encoded C++/ObjC names when displaying symbols."), NULL,
2592 NULL,
920d2a44 2593 show_demangle,
5bf193a2
AC
2594 &setprintlist, &showprintlist);
2595
2596 add_setshow_boolean_cmd ("pagination", class_support,
2597 &pagination_enabled, _("\
2598Set state of pagination."), _("\
2599Show state of pagination."), NULL,
2600 NULL,
920d2a44 2601 show_pagination_enabled,
5bf193a2 2602 &setlist, &showlist);
4261bedc 2603
c906108c
SS
2604 if (xdb_commands)
2605 {
c5aa993b 2606 add_com ("am", class_support, pagination_on_command,
1bedd215 2607 _("Enable pagination"));
c5aa993b 2608 add_com ("sm", class_support, pagination_off_command,
1bedd215 2609 _("Disable pagination"));
c906108c
SS
2610 }
2611
5bf193a2
AC
2612 add_setshow_boolean_cmd ("sevenbit-strings", class_support,
2613 &sevenbit_strings, _("\
2614Set printing of 8-bit characters in strings as \\nnn."), _("\
2615Show printing of 8-bit characters in strings as \\nnn."), NULL,
2616 NULL,
920d2a44 2617 show_sevenbit_strings,
5bf193a2
AC
2618 &setprintlist, &showprintlist);
2619
2620 add_setshow_boolean_cmd ("asm-demangle", class_support, &asm_demangle, _("\
2621Set demangling of C++/ObjC names in disassembly listings."), _("\
2622Show demangling of C++/ObjC names in disassembly listings."), NULL,
2623 NULL,
920d2a44 2624 show_asm_demangle,
5bf193a2 2625 &setprintlist, &showprintlist);
75feb17d
DJ
2626
2627 add_setshow_boolean_cmd ("timestamp", class_maintenance,
2628 &debug_timestamp, _("\
2629Set timestamping of debugging messages."), _("\
2630Show timestamping of debugging messages."), _("\
2631When set, debugging messages will be marked with seconds and microseconds."),
2632 NULL,
2633 show_debug_timestamp,
2634 &setdebuglist, &showdebuglist);
c906108c
SS
2635}
2636
2637/* Machine specific function to handle SIGWINCH signal. */
2638
2639#ifdef SIGWINCH_HANDLER_BODY
c5aa993b 2640SIGWINCH_HANDLER_BODY
c906108c 2641#endif
5683e87a 2642/* print routines to handle variable size regs, etc. */
c906108c
SS
2643/* temporary storage using circular buffer */
2644#define NUMCELLS 16
0759e0bf 2645#define CELLSIZE 50
c5aa993b 2646static char *
fba45db2 2647get_cell (void)
c906108c
SS
2648{
2649 static char buf[NUMCELLS][CELLSIZE];
c5aa993b
JM
2650 static int cell = 0;
2651 if (++cell >= NUMCELLS)
2652 cell = 0;
c906108c
SS
2653 return buf[cell];
2654}
2655
d4f3574e
SS
2656int
2657strlen_paddr (void)
2658{
17a912b6 2659 return (gdbarch_addr_bit (current_gdbarch) / 8 * 2);
d4f3574e
SS
2660}
2661
c5aa993b 2662char *
104c1213 2663paddr (CORE_ADDR addr)
c906108c 2664{
17a912b6 2665 return phex (addr, gdbarch_addr_bit (current_gdbarch) / 8);
c906108c
SS
2666}
2667
c5aa993b 2668char *
104c1213 2669paddr_nz (CORE_ADDR addr)
c906108c 2670{
17a912b6 2671 return phex_nz (addr, gdbarch_addr_bit (current_gdbarch) / 8);
c906108c
SS
2672}
2673
66bf4b3a
AC
2674const char *
2675paddress (CORE_ADDR addr)
2676{
2677 /* Truncate address to the size of a target address, avoiding shifts
2678 larger or equal than the width of a CORE_ADDR. The local
2679 variable ADDR_BIT stops the compiler reporting a shift overflow
2680 when it won't occur. */
2681 /* NOTE: This assumes that the significant address information is
2682 kept in the least significant bits of ADDR - the upper bits were
76e71323 2683 either zero or sign extended. Should gdbarch_address_to_pointer or
66bf4b3a
AC
2684 some ADDRESS_TO_PRINTABLE() be used to do the conversion? */
2685
17a912b6 2686 int addr_bit = gdbarch_addr_bit (current_gdbarch);
66bf4b3a
AC
2687
2688 if (addr_bit < (sizeof (CORE_ADDR) * HOST_CHAR_BIT))
2689 addr &= ((CORE_ADDR) 1 << addr_bit) - 1;
2690 return hex_string (addr);
2691}
2692
8cf46f62
MK
2693static char *
2694decimal2str (char *sign, ULONGEST addr, int width)
104c1213 2695{
8cf46f62 2696 /* Steal code from valprint.c:print_decimal(). Should this worry
104c1213
JM
2697 about the real size of addr as the above does? */
2698 unsigned long temp[3];
8cf46f62
MK
2699 char *str = get_cell ();
2700
104c1213
JM
2701 int i = 0;
2702 do
2703 {
2704 temp[i] = addr % (1000 * 1000 * 1000);
2705 addr /= (1000 * 1000 * 1000);
2706 i++;
bb599908 2707 width -= 9;
104c1213
JM
2708 }
2709 while (addr != 0 && i < (sizeof (temp) / sizeof (temp[0])));
8cf46f62 2710
bb599908
PH
2711 width += 9;
2712 if (width < 0)
2713 width = 0;
8cf46f62 2714
104c1213
JM
2715 switch (i)
2716 {
2717 case 1:
8cf46f62 2718 xsnprintf (str, CELLSIZE, "%s%0*lu", sign, width, temp[0]);
104c1213
JM
2719 break;
2720 case 2:
8cf46f62
MK
2721 xsnprintf (str, CELLSIZE, "%s%0*lu%09lu", sign, width,
2722 temp[1], temp[0]);
104c1213
JM
2723 break;
2724 case 3:
8cf46f62
MK
2725 xsnprintf (str, CELLSIZE, "%s%0*lu%09lu%09lu", sign, width,
2726 temp[2], temp[1], temp[0]);
bb599908
PH
2727 break;
2728 default:
2729 internal_error (__FILE__, __LINE__,
e2e0b3e5 2730 _("failed internal consistency check"));
bb599908 2731 }
8cf46f62
MK
2732
2733 return str;
bb599908
PH
2734}
2735
8cf46f62
MK
2736static char *
2737octal2str (ULONGEST addr, int width)
bb599908
PH
2738{
2739 unsigned long temp[3];
8cf46f62
MK
2740 char *str = get_cell ();
2741
bb599908
PH
2742 int i = 0;
2743 do
2744 {
2745 temp[i] = addr % (0100000 * 0100000);
2746 addr /= (0100000 * 0100000);
2747 i++;
2748 width -= 10;
2749 }
2750 while (addr != 0 && i < (sizeof (temp) / sizeof (temp[0])));
8cf46f62 2751
bb599908
PH
2752 width += 10;
2753 if (width < 0)
2754 width = 0;
8cf46f62 2755
bb599908
PH
2756 switch (i)
2757 {
2758 case 1:
2759 if (temp[0] == 0)
8cf46f62 2760 xsnprintf (str, CELLSIZE, "%*o", width, 0);
bb599908 2761 else
8cf46f62 2762 xsnprintf (str, CELLSIZE, "0%0*lo", width, temp[0]);
bb599908
PH
2763 break;
2764 case 2:
8cf46f62 2765 xsnprintf (str, CELLSIZE, "0%0*lo%010lo", width, temp[1], temp[0]);
bb599908
PH
2766 break;
2767 case 3:
8cf46f62
MK
2768 xsnprintf (str, CELLSIZE, "0%0*lo%010lo%010lo", width,
2769 temp[2], temp[1], temp[0]);
104c1213
JM
2770 break;
2771 default:
8731e58e 2772 internal_error (__FILE__, __LINE__,
e2e0b3e5 2773 _("failed internal consistency check"));
104c1213 2774 }
8cf46f62
MK
2775
2776 return str;
104c1213
JM
2777}
2778
2779char *
623d3eb1 2780pulongest (ULONGEST u)
104c1213 2781{
623d3eb1 2782 return decimal2str ("", u, 0);
104c1213
JM
2783}
2784
2785char *
623d3eb1 2786plongest (LONGEST l)
104c1213 2787{
623d3eb1
DE
2788 if (l < 0)
2789 return decimal2str ("-", -l, 0);
104c1213 2790 else
623d3eb1 2791 return decimal2str ("", l, 0);
104c1213
JM
2792}
2793
8cf46f62 2794/* Eliminate warning from compiler on 32-bit systems. */
5683e87a
AC
2795static int thirty_two = 32;
2796
104c1213 2797char *
5683e87a 2798phex (ULONGEST l, int sizeof_l)
104c1213 2799{
45a1e866 2800 char *str;
8cf46f62 2801
5683e87a 2802 switch (sizeof_l)
104c1213
JM
2803 {
2804 case 8:
45a1e866 2805 str = get_cell ();
8cf46f62
MK
2806 xsnprintf (str, CELLSIZE, "%08lx%08lx",
2807 (unsigned long) (l >> thirty_two),
2808 (unsigned long) (l & 0xffffffff));
104c1213
JM
2809 break;
2810 case 4:
45a1e866 2811 str = get_cell ();
8cf46f62 2812 xsnprintf (str, CELLSIZE, "%08lx", (unsigned long) l);
104c1213
JM
2813 break;
2814 case 2:
45a1e866 2815 str = get_cell ();
8cf46f62 2816 xsnprintf (str, CELLSIZE, "%04x", (unsigned short) (l & 0xffff));
104c1213
JM
2817 break;
2818 default:
45a1e866 2819 str = phex (l, sizeof (l));
5683e87a 2820 break;
104c1213 2821 }
8cf46f62 2822
5683e87a 2823 return str;
104c1213
JM
2824}
2825
c5aa993b 2826char *
5683e87a 2827phex_nz (ULONGEST l, int sizeof_l)
c906108c 2828{
faf833ca 2829 char *str;
8cf46f62 2830
5683e87a 2831 switch (sizeof_l)
c906108c 2832 {
c5aa993b
JM
2833 case 8:
2834 {
5683e87a 2835 unsigned long high = (unsigned long) (l >> thirty_two);
faf833ca 2836 str = get_cell ();
c5aa993b 2837 if (high == 0)
8cf46f62
MK
2838 xsnprintf (str, CELLSIZE, "%lx",
2839 (unsigned long) (l & 0xffffffff));
c5aa993b 2840 else
8cf46f62
MK
2841 xsnprintf (str, CELLSIZE, "%lx%08lx", high,
2842 (unsigned long) (l & 0xffffffff));
c906108c 2843 break;
c5aa993b
JM
2844 }
2845 case 4:
faf833ca 2846 str = get_cell ();
8cf46f62 2847 xsnprintf (str, CELLSIZE, "%lx", (unsigned long) l);
c5aa993b
JM
2848 break;
2849 case 2:
faf833ca 2850 str = get_cell ();
8cf46f62 2851 xsnprintf (str, CELLSIZE, "%x", (unsigned short) (l & 0xffff));
c5aa993b
JM
2852 break;
2853 default:
faf833ca 2854 str = phex_nz (l, sizeof (l));
5683e87a 2855 break;
c906108c 2856 }
8cf46f62 2857
5683e87a 2858 return str;
c906108c 2859}
ac2e2ef7 2860
0759e0bf
AC
2861/* Converts a LONGEST to a C-format hexadecimal literal and stores it
2862 in a static string. Returns a pointer to this string. */
2863char *
2864hex_string (LONGEST num)
2865{
2866 char *result = get_cell ();
8cf46f62 2867 xsnprintf (result, CELLSIZE, "0x%s", phex_nz (num, sizeof (num)));
0759e0bf
AC
2868 return result;
2869}
2870
2871/* Converts a LONGEST number to a C-format hexadecimal literal and
2872 stores it in a static string. Returns a pointer to this string
2873 that is valid until the next call. The number is padded on the
2874 left with 0s to at least WIDTH characters. */
2875char *
2876hex_string_custom (LONGEST num, int width)
2877{
2878 char *result = get_cell ();
2879 char *result_end = result + CELLSIZE - 1;
2880 const char *hex = phex_nz (num, sizeof (num));
2881 int hex_len = strlen (hex);
2882
2883 if (hex_len > width)
2884 width = hex_len;
2885 if (width + 2 >= CELLSIZE)
2886 internal_error (__FILE__, __LINE__,
e2e0b3e5 2887 _("hex_string_custom: insufficient space to store result"));
0759e0bf
AC
2888
2889 strcpy (result_end - width - 2, "0x");
2890 memset (result_end - width, '0', width);
2891 strcpy (result_end - hex_len, hex);
2892 return result_end - width - 2;
2893}
ac2e2ef7 2894
bb599908
PH
2895/* Convert VAL to a numeral in the given radix. For
2896 * radix 10, IS_SIGNED may be true, indicating a signed quantity;
2897 * otherwise VAL is interpreted as unsigned. If WIDTH is supplied,
2898 * it is the minimum width (0-padded if needed). USE_C_FORMAT means
2899 * to use C format in all cases. If it is false, then 'x'
2900 * and 'o' formats do not include a prefix (0x or leading 0). */
2901
2902char *
2903int_string (LONGEST val, int radix, int is_signed, int width,
2904 int use_c_format)
2905{
2906 switch (radix)
2907 {
2908 case 16:
2909 {
2910 char *result;
2911 if (width == 0)
2912 result = hex_string (val);
2913 else
2914 result = hex_string_custom (val, width);
2915 if (! use_c_format)
2916 result += 2;
2917 return result;
2918 }
2919 case 10:
2920 {
bb599908 2921 if (is_signed && val < 0)
8cf46f62 2922 return decimal2str ("-", -val, width);
bb599908 2923 else
8cf46f62 2924 return decimal2str ("", val, width);
bb599908
PH
2925 }
2926 case 8:
2927 {
8cf46f62 2928 char *result = octal2str (val, width);
bb599908
PH
2929 if (use_c_format || val == 0)
2930 return result;
2931 else
2932 return result + 1;
2933 }
2934 default:
2935 internal_error (__FILE__, __LINE__,
e2e0b3e5 2936 _("failed internal consistency check"));
bb599908
PH
2937 }
2938}
2939
03dd37c3
AC
2940/* Convert a CORE_ADDR into a string. */
2941const char *
2942core_addr_to_string (const CORE_ADDR addr)
49b563f9
KS
2943{
2944 char *str = get_cell ();
2945 strcpy (str, "0x");
2946 strcat (str, phex (addr, sizeof (addr)));
2947 return str;
2948}
2949
2950const char *
2951core_addr_to_string_nz (const CORE_ADDR addr)
03dd37c3
AC
2952{
2953 char *str = get_cell ();
2954 strcpy (str, "0x");
2955 strcat (str, phex_nz (addr, sizeof (addr)));
2956 return str;
2957}
2958
2959/* Convert a string back into a CORE_ADDR. */
2960CORE_ADDR
2961string_to_core_addr (const char *my_string)
2962{
9544c605 2963 int addr_bit = gdbarch_addr_bit (current_gdbarch);
03dd37c3 2964 CORE_ADDR addr = 0;
9544c605 2965
03dd37c3
AC
2966 if (my_string[0] == '0' && tolower (my_string[1]) == 'x')
2967 {
ced572fe 2968 /* Assume that it is in hex. */
03dd37c3
AC
2969 int i;
2970 for (i = 2; my_string[i] != '\0'; i++)
2971 {
2972 if (isdigit (my_string[i]))
2973 addr = (my_string[i] - '0') + (addr * 16);
8731e58e 2974 else if (isxdigit (my_string[i]))
03dd37c3
AC
2975 addr = (tolower (my_string[i]) - 'a' + 0xa) + (addr * 16);
2976 else
63f06803 2977 error (_("invalid hex \"%s\""), my_string);
03dd37c3 2978 }
9544c605
MR
2979
2980 /* Not very modular, but if the executable format expects
2981 addresses to be sign-extended, then do so if the address was
2982 specified with only 32 significant bits. Really this should
2983 be determined by the target architecture, not by the object
2984 file. */
2985 if (i - 2 == addr_bit / 4
2986 && exec_bfd
2987 && bfd_get_sign_extend_vma (exec_bfd))
2988 addr = (addr ^ ((CORE_ADDR) 1 << (addr_bit - 1)))
2989 - ((CORE_ADDR) 1 << (addr_bit - 1));
03dd37c3
AC
2990 }
2991 else
2992 {
2993 /* Assume that it is in decimal. */
2994 int i;
2995 for (i = 0; my_string[i] != '\0'; i++)
2996 {
2997 if (isdigit (my_string[i]))
2998 addr = (my_string[i] - '0') + (addr * 10);
2999 else
63f06803 3000 error (_("invalid decimal \"%s\""), my_string);
03dd37c3
AC
3001 }
3002 }
9544c605 3003
03dd37c3
AC
3004 return addr;
3005}
58d370e0 3006
17ea7499
CES
3007const char *
3008host_address_to_string (const void *addr)
3009{
3010 char *str = get_cell ();
3011 sprintf (str, "0x%lx", (unsigned long) addr);
3012 return str;
3013}
3014
58d370e0
TT
3015char *
3016gdb_realpath (const char *filename)
3017{
70d35819
AC
3018 /* Method 1: The system has a compile time upper bound on a filename
3019 path. Use that and realpath() to canonicalize the name. This is
3020 the most common case. Note that, if there isn't a compile time
3021 upper bound, you want to avoid realpath() at all costs. */
a4db0f07 3022#if defined(HAVE_REALPATH)
70d35819 3023 {
a4db0f07 3024# if defined (PATH_MAX)
70d35819 3025 char buf[PATH_MAX];
a4db0f07
RH
3026# define USE_REALPATH
3027# elif defined (MAXPATHLEN)
70d35819 3028 char buf[MAXPATHLEN];
a4db0f07
RH
3029# define USE_REALPATH
3030# endif
70d35819 3031# if defined (USE_REALPATH)
82c0260e 3032 const char *rp = realpath (filename, buf);
70d35819
AC
3033 if (rp == NULL)
3034 rp = filename;
3035 return xstrdup (rp);
70d35819 3036# endif
6f88d630 3037 }
a4db0f07
RH
3038#endif /* HAVE_REALPATH */
3039
70d35819
AC
3040 /* Method 2: The host system (i.e., GNU) has the function
3041 canonicalize_file_name() which malloc's a chunk of memory and
3042 returns that, use that. */
3043#if defined(HAVE_CANONICALIZE_FILE_NAME)
3044 {
3045 char *rp = canonicalize_file_name (filename);
3046 if (rp == NULL)
3047 return xstrdup (filename);
3048 else
3049 return rp;
3050 }
58d370e0 3051#endif
70d35819 3052
6411e720
AC
3053 /* FIXME: cagney/2002-11-13:
3054
3055 Method 2a: Use realpath() with a NULL buffer. Some systems, due
3056 to the problems described in in method 3, have modified their
3057 realpath() implementation so that it will allocate a buffer when
3058 NULL is passed in. Before this can be used, though, some sort of
3059 configure time test would need to be added. Otherwize the code
3060 will likely core dump. */
3061
70d35819
AC
3062 /* Method 3: Now we're getting desperate! The system doesn't have a
3063 compile time buffer size and no alternative function. Query the
3064 OS, using pathconf(), for the buffer limit. Care is needed
3065 though, some systems do not limit PATH_MAX (return -1 for
3066 pathconf()) making it impossible to pass a correctly sized buffer
3067 to realpath() (it could always overflow). On those systems, we
3068 skip this. */
3069#if defined (HAVE_REALPATH) && defined (HAVE_UNISTD_H) && defined(HAVE_ALLOCA)
3070 {
3071 /* Find out the max path size. */
3072 long path_max = pathconf ("/", _PC_PATH_MAX);
3073 if (path_max > 0)
3074 {
3075 /* PATH_MAX is bounded. */
3076 char *buf = alloca (path_max);
3077 char *rp = realpath (filename, buf);
3078 return xstrdup (rp ? rp : filename);
3079 }
3080 }
3081#endif
3082
3083 /* This system is a lost cause, just dup the buffer. */
3084 return xstrdup (filename);
58d370e0 3085}
303c8ebd
JB
3086
3087/* Return a copy of FILENAME, with its directory prefix canonicalized
3088 by gdb_realpath. */
3089
3090char *
3091xfullpath (const char *filename)
3092{
3093 const char *base_name = lbasename (filename);
3094 char *dir_name;
3095 char *real_path;
3096 char *result;
3097
3098 /* Extract the basename of filename, and return immediately
3099 a copy of filename if it does not contain any directory prefix. */
3100 if (base_name == filename)
3101 return xstrdup (filename);
3102
3103 dir_name = alloca ((size_t) (base_name - filename + 2));
3104 /* Allocate enough space to store the dir_name + plus one extra
3105 character sometimes needed under Windows (see below), and
3106 then the closing \000 character */
3107 strncpy (dir_name, filename, base_name - filename);
3108 dir_name[base_name - filename] = '\000';
3109
3110#ifdef HAVE_DOS_BASED_FILE_SYSTEM
3111 /* We need to be careful when filename is of the form 'd:foo', which
3112 is equivalent of d:./foo, which is totally different from d:/foo. */
8731e58e 3113 if (strlen (dir_name) == 2 && isalpha (dir_name[0]) && dir_name[1] == ':')
303c8ebd
JB
3114 {
3115 dir_name[2] = '.';
3116 dir_name[3] = '\000';
3117 }
3118#endif
3119
3120 /* Canonicalize the directory prefix, and build the resulting
3121 filename. If the dirname realpath already contains an ending
3122 directory separator, avoid doubling it. */
3123 real_path = gdb_realpath (dir_name);
3124 if (IS_DIR_SEPARATOR (real_path[strlen (real_path) - 1]))
1754f103 3125 result = concat (real_path, base_name, (char *)NULL);
303c8ebd 3126 else
1754f103 3127 result = concat (real_path, SLASH_STRING, base_name, (char *)NULL);
303c8ebd
JB
3128
3129 xfree (real_path);
3130 return result;
3131}
5b5d99cf
JB
3132
3133
3134/* This is the 32-bit CRC function used by the GNU separate debug
3135 facility. An executable may contain a section named
3136 .gnu_debuglink, which holds the name of a separate executable file
3137 containing its debug info, and a checksum of that file's contents,
3138 computed using this function. */
3139unsigned long
3140gnu_debuglink_crc32 (unsigned long crc, unsigned char *buf, size_t len)
3141{
8731e58e
AC
3142 static const unsigned long crc32_table[256] = {
3143 0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419,
3144 0x706af48f, 0xe963a535, 0x9e6495a3, 0x0edb8832, 0x79dcb8a4,
3145 0xe0d5e91e, 0x97d2d988, 0x09b64c2b, 0x7eb17cbd, 0xe7b82d07,
3146 0x90bf1d91, 0x1db71064, 0x6ab020f2, 0xf3b97148, 0x84be41de,
3147 0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7, 0x136c9856,
3148 0x646ba8c0, 0xfd62f97a, 0x8a65c9ec, 0x14015c4f, 0x63066cd9,
3149 0xfa0f3d63, 0x8d080df5, 0x3b6e20c8, 0x4c69105e, 0xd56041e4,
3150 0xa2677172, 0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b,
3151 0x35b5a8fa, 0x42b2986c, 0xdbbbc9d6, 0xacbcf940, 0x32d86ce3,
3152 0x45df5c75, 0xdcd60dcf, 0xabd13d59, 0x26d930ac, 0x51de003a,
3153 0xc8d75180, 0xbfd06116, 0x21b4f4b5, 0x56b3c423, 0xcfba9599,
3154 0xb8bda50f, 0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924,
3155 0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d, 0x76dc4190,
3156 0x01db7106, 0x98d220bc, 0xefd5102a, 0x71b18589, 0x06b6b51f,
3157 0x9fbfe4a5, 0xe8b8d433, 0x7807c9a2, 0x0f00f934, 0x9609a88e,
3158 0xe10e9818, 0x7f6a0dbb, 0x086d3d2d, 0x91646c97, 0xe6635c01,
3159 0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e, 0x6c0695ed,
3160 0x1b01a57b, 0x8208f4c1, 0xf50fc457, 0x65b0d9c6, 0x12b7e950,
3161 0x8bbeb8ea, 0xfcb9887c, 0x62dd1ddf, 0x15da2d49, 0x8cd37cf3,
3162 0xfbd44c65, 0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2,
3163 0x4adfa541, 0x3dd895d7, 0xa4d1c46d, 0xd3d6f4fb, 0x4369e96a,
3164 0x346ed9fc, 0xad678846, 0xda60b8d0, 0x44042d73, 0x33031de5,
3165 0xaa0a4c5f, 0xdd0d7cc9, 0x5005713c, 0x270241aa, 0xbe0b1010,
3166 0xc90c2086, 0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f,
3167 0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4, 0x59b33d17,
3168 0x2eb40d81, 0xb7bd5c3b, 0xc0ba6cad, 0xedb88320, 0x9abfb3b6,
3169 0x03b6e20c, 0x74b1d29a, 0xead54739, 0x9dd277af, 0x04db2615,
3170 0x73dc1683, 0xe3630b12, 0x94643b84, 0x0d6d6a3e, 0x7a6a5aa8,
3171 0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1, 0xf00f9344,
3172 0x8708a3d2, 0x1e01f268, 0x6906c2fe, 0xf762575d, 0x806567cb,
3173 0x196c3671, 0x6e6b06e7, 0xfed41b76, 0x89d32be0, 0x10da7a5a,
3174 0x67dd4acc, 0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5,
3175 0xd6d6a3e8, 0xa1d1937e, 0x38d8c2c4, 0x4fdff252, 0xd1bb67f1,
3176 0xa6bc5767, 0x3fb506dd, 0x48b2364b, 0xd80d2bda, 0xaf0a1b4c,
3177 0x36034af6, 0x41047a60, 0xdf60efc3, 0xa867df55, 0x316e8eef,
3178 0x4669be79, 0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236,
3179 0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f, 0xc5ba3bbe,
3180 0xb2bd0b28, 0x2bb45a92, 0x5cb36a04, 0xc2d7ffa7, 0xb5d0cf31,
3181 0x2cd99e8b, 0x5bdeae1d, 0x9b64c2b0, 0xec63f226, 0x756aa39c,
3182 0x026d930a, 0x9c0906a9, 0xeb0e363f, 0x72076785, 0x05005713,
3183 0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38, 0x92d28e9b,
3184 0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21, 0x86d3d2d4, 0xf1d4e242,
3185 0x68ddb3f8, 0x1fda836e, 0x81be16cd, 0xf6b9265b, 0x6fb077e1,
3186 0x18b74777, 0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c,
3187 0x8f659eff, 0xf862ae69, 0x616bffd3, 0x166ccf45, 0xa00ae278,
3188 0xd70dd2ee, 0x4e048354, 0x3903b3c2, 0xa7672661, 0xd06016f7,
3189 0x4969474d, 0x3e6e77db, 0xaed16a4a, 0xd9d65adc, 0x40df0b66,
3190 0x37d83bf0, 0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9,
3191 0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6, 0xbad03605,
3192 0xcdd70693, 0x54de5729, 0x23d967bf, 0xb3667a2e, 0xc4614ab8,
3193 0x5d681b02, 0x2a6f2b94, 0xb40bbe37, 0xc30c8ea1, 0x5a05df1b,
3194 0x2d02ef8d
3195 };
5b5d99cf
JB
3196 unsigned char *end;
3197
3198 crc = ~crc & 0xffffffff;
3199 for (end = buf + len; buf < end; ++buf)
3200 crc = crc32_table[(crc ^ *buf) & 0xff] ^ (crc >> 8);
3201 return ~crc & 0xffffffff;;
3202}
5b03f266
AC
3203
3204ULONGEST
3205align_up (ULONGEST v, int n)
3206{
3207 /* Check that N is really a power of two. */
3208 gdb_assert (n && (n & (n-1)) == 0);
3209 return (v + n - 1) & -n;
3210}
3211
3212ULONGEST
3213align_down (ULONGEST v, int n)
3214{
3215 /* Check that N is really a power of two. */
3216 gdb_assert (n && (n & (n-1)) == 0);
3217 return (v & -n);
3218}
ae5a43e0
DJ
3219
3220/* Allocation function for the libiberty hash table which uses an
3221 obstack. The obstack is passed as DATA. */
3222
3223void *
3224hashtab_obstack_allocate (void *data, size_t size, size_t count)
3225{
3226 unsigned int total = size * count;
3227 void *ptr = obstack_alloc ((struct obstack *) data, total);
3228 memset (ptr, 0, total);
3229 return ptr;
3230}
3231
3232/* Trivial deallocation function for the libiberty splay tree and hash
3233 table - don't deallocate anything. Rely on later deletion of the
3234 obstack. DATA will be the obstack, although it is not needed
3235 here. */
3236
3237void
3238dummy_obstack_deallocate (void *object, void *data)
3239{
3240 return;
3241}
253c8abb
DJ
3242
3243/* The bit offset of the highest byte in a ULONGEST, for overflow
3244 checking. */
3245
3246#define HIGH_BYTE_POSN ((sizeof (ULONGEST) - 1) * HOST_CHAR_BIT)
3247
3248/* True (non-zero) iff DIGIT is a valid digit in radix BASE,
3249 where 2 <= BASE <= 36. */
3250
3251static int
3252is_digit_in_base (unsigned char digit, int base)
3253{
3254 if (!isalnum (digit))
3255 return 0;
3256 if (base <= 10)
3257 return (isdigit (digit) && digit < base + '0');
3258 else
3259 return (isdigit (digit) || tolower (digit) < base - 10 + 'a');
3260}
3261
3262static int
3263digit_to_int (unsigned char c)
3264{
3265 if (isdigit (c))
3266 return c - '0';
3267 else
3268 return tolower (c) - 'a' + 10;
3269}
3270
3271/* As for strtoul, but for ULONGEST results. */
3272
3273ULONGEST
3274strtoulst (const char *num, const char **trailer, int base)
3275{
3276 unsigned int high_part;
3277 ULONGEST result;
3278 int minus = 0;
3279 int i = 0;
3280
3281 /* Skip leading whitespace. */
3282 while (isspace (num[i]))
3283 i++;
3284
3285 /* Handle prefixes. */
3286 if (num[i] == '+')
3287 i++;
3288 else if (num[i] == '-')
3289 {
3290 minus = 1;
3291 i++;
3292 }
3293
3294 if (base == 0 || base == 16)
3295 {
3296 if (num[i] == '0' && (num[i + 1] == 'x' || num[i + 1] == 'X'))
3297 {
3298 i += 2;
3299 if (base == 0)
3300 base = 16;
3301 }
3302 }
3303
3304 if (base == 0 && num[i] == '0')
3305 base = 8;
3306
3307 if (base == 0)
3308 base = 10;
3309
3310 if (base < 2 || base > 36)
3311 {
3312 errno = EINVAL;
3313 return 0;
3314 }
3315
3316 result = high_part = 0;
3317 for (; is_digit_in_base (num[i], base); i += 1)
3318 {
3319 result = result * base + digit_to_int (num[i]);
3320 high_part = high_part * base + (unsigned int) (result >> HIGH_BYTE_POSN);
3321 result &= ((ULONGEST) 1 << HIGH_BYTE_POSN) - 1;
3322 if (high_part > 0xff)
3323 {
3324 errno = ERANGE;
3325 result = ~ (ULONGEST) 0;
3326 high_part = 0;
3327 minus = 0;
3328 break;
3329 }
3330 }
3331
3332 if (trailer != NULL)
3333 *trailer = &num[i];
3334
3335 result = result + ((ULONGEST) high_part << HIGH_BYTE_POSN);
3336 if (minus)
3337 return -result;
3338 else
3339 return result;
3340}
e1024ff1
DJ
3341
3342/* Simple, portable version of dirname that does not modify its
3343 argument. */
3344
3345char *
3346ldirname (const char *filename)
3347{
3348 const char *base = lbasename (filename);
3349 char *dirname;
3350
3351 while (base > filename && IS_DIR_SEPARATOR (base[-1]))
3352 --base;
3353
3354 if (base == filename)
3355 return NULL;
3356
3357 dirname = xmalloc (base - filename + 2);
3358 memcpy (dirname, filename, base - filename);
3359
3360 /* On DOS based file systems, convert "d:foo" to "d:.", so that we
3361 create "d:./bar" later instead of the (different) "d:/bar". */
3362 if (base - filename == 2 && IS_ABSOLUTE_PATH (base)
3363 && !IS_DIR_SEPARATOR (filename[0]))
3364 dirname[base++ - filename] = '.';
3365
3366 dirname[base - filename] = '\0';
3367 return dirname;
3368}
d1a41061
PP
3369
3370/* Call libiberty's buildargv, and return the result.
3371 If buildargv fails due to out-of-memory, call nomem.
3372 Therefore, the returned value is guaranteed to be non-NULL,
3373 unless the parameter itself is NULL. */
3374
3375char **
3376gdb_buildargv (const char *s)
3377{
3378 char **argv = buildargv (s);
3379 if (s != NULL && argv == NULL)
3380 nomem (0);
3381 return argv;
3382}
This page took 1.224867 seconds and 4 git commands to generate.