* gdb.c++/classes.exp: Add test for static member function.
[deliverable/binutils-gdb.git] / gdb / top.c
1 /* Top level stuff for GDB, the GNU debugger.
2 Copyright 1986, 1987, 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995,
3 1996, 1997, 1998, 1999, 2000, 2001 Free Software Foundation, Inc.
4
5 This file is part of GDB.
6
7 This program is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 2 of the License, or
10 (at your option) any later version.
11
12 This program is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with this program; if not, write to the Free Software
19 Foundation, Inc., 59 Temple Place - Suite 330,
20 Boston, MA 02111-1307, USA. */
21
22 #include "defs.h"
23 #include "gdbcmd.h"
24 #include "call-cmds.h"
25 #include "cli/cli-cmds.h"
26 #include "cli/cli-script.h"
27 #include "cli/cli-setshow.h"
28 #include "symtab.h"
29 #include "inferior.h"
30 #include <signal.h>
31 #include "target.h"
32 #include "breakpoint.h"
33 #include "gdbtypes.h"
34 #include "expression.h"
35 #include "value.h"
36 #include "language.h"
37 #include "terminal.h" /* For job_control. */
38 #include "annotate.h"
39 #include "completer.h"
40 #include "top.h"
41 #include "version.h"
42 #include "serial.h"
43 #include "doublest.h"
44 #include "gdb_assert.h"
45
46 /* readline include files */
47 #include <readline/readline.h>
48 #include <readline/history.h>
49
50 /* readline defines this. */
51 #undef savestring
52
53 #include <sys/types.h>
54
55 #include <setjmp.h>
56
57 #include "event-top.h"
58 #include "gdb_string.h"
59 #include "gdb_stat.h"
60 #include <ctype.h>
61 #ifdef UI_OUT
62 #include "ui-out.h"
63 #include "cli-out.h"
64 #endif
65
66 /* Default command line prompt. This is overriden in some configs. */
67
68 #ifndef DEFAULT_PROMPT
69 #define DEFAULT_PROMPT "(gdb) "
70 #endif
71
72 /* Initialization file name for gdb. This is overridden in some configs. */
73
74 #ifndef GDBINIT_FILENAME
75 #define GDBINIT_FILENAME ".gdbinit"
76 #endif
77 char gdbinit[] = GDBINIT_FILENAME;
78
79 int inhibit_gdbinit = 0;
80
81 /* If nonzero, and GDB has been configured to be able to use windows,
82 attempt to open them upon startup. */
83
84 int use_windows = 1;
85
86 extern char lang_frame_mismatch_warn[]; /* language.c */
87
88 /* Flag for whether we want all the "from_tty" gubbish printed. */
89
90 int caution = 1; /* Default is yes, sigh. */
91
92 /* stdio stream that command input is being read from. Set to stdin normally.
93 Set by source_command to the file we are sourcing. Set to NULL if we are
94 executing a user-defined command or interacting via a GUI. */
95
96 FILE *instream;
97
98 /* Current working directory. */
99
100 char *current_directory;
101
102 /* The directory name is actually stored here (usually). */
103 char gdb_dirbuf[1024];
104
105 /* Function to call before reading a command, if nonzero.
106 The function receives two args: an input stream,
107 and a prompt string. */
108
109 void (*window_hook) (FILE *, char *);
110
111 int epoch_interface;
112 int xgdb_verbose;
113
114 /* gdb prints this when reading a command interactively */
115 static char *gdb_prompt_string; /* the global prompt string */
116
117 /* Buffer used for reading command lines, and the size
118 allocated for it so far. */
119
120 char *line;
121 int linesize = 100;
122
123 /* Nonzero if the current command is modified by "server ". This
124 affects things like recording into the command history, commands
125 repeating on RETURN, etc. This is so a user interface (emacs, GUI,
126 whatever) can issue its own commands and also send along commands
127 from the user, and have the user not notice that the user interface
128 is issuing commands too. */
129 int server_command;
130
131 /* Baud rate specified for talking to serial target systems. Default
132 is left as -1, so targets can choose their own defaults. */
133 /* FIXME: This means that "show remotebaud" and gr_files_info can print -1
134 or (unsigned int)-1. This is a Bad User Interface. */
135
136 int baud_rate = -1;
137
138 /* Timeout limit for response from target. */
139
140 /* The default value has been changed many times over the years. It
141 was originally 5 seconds. But that was thought to be a long time
142 to sit and wait, so it was changed to 2 seconds. That was thought
143 to be plenty unless the connection was going through some terminal
144 server or multiplexer or other form of hairy serial connection.
145
146 In mid-1996, remote_timeout was moved from remote.c to top.c and
147 it began being used in other remote-* targets. It appears that the
148 default was changed to 20 seconds at that time, perhaps because the
149 Hitachi E7000 ICE didn't always respond in a timely manner.
150
151 But if 5 seconds is a long time to sit and wait for retransmissions,
152 20 seconds is far worse. This demonstrates the difficulty of using
153 a single variable for all protocol timeouts.
154
155 As remote.c is used much more than remote-e7000.c, it was changed
156 back to 2 seconds in 1999. */
157
158 int remote_timeout = 2;
159
160 /* Non-zero tells remote* modules to output debugging info. */
161
162 int remote_debug = 0;
163
164 /* Non-zero means the target is running. Note: this is different from
165 saying that there is an active target and we are stopped at a
166 breakpoint, for instance. This is a real indicator whether the
167 target is off and running, which gdb is doing something else. */
168 int target_executing = 0;
169
170 /* Level of control structure. */
171 static int control_level;
172
173 /* Signal to catch ^Z typed while reading a command: SIGTSTP or SIGCONT. */
174
175 #ifndef STOP_SIGNAL
176 #ifdef SIGTSTP
177 #define STOP_SIGNAL SIGTSTP
178 static void stop_sig (int);
179 #endif
180 #endif
181
182 /* Hooks for alternate command interfaces. */
183
184 /* Called after most modules have been initialized, but before taking users
185 command file.
186
187 If the UI fails to initialize and it wants GDB to continue
188 using the default UI, then it should clear this hook before returning. */
189
190 void (*init_ui_hook) (char *argv0);
191
192 /* This hook is called from within gdb's many mini-event loops which could
193 steal control from a real user interface's event loop. It returns
194 non-zero if the user is requesting a detach, zero otherwise. */
195
196 int (*ui_loop_hook) (int);
197
198 /* Called instead of command_loop at top level. Can be invoked via
199 return_to_top_level. */
200
201 void (*command_loop_hook) (void);
202
203
204 /* Called from print_frame_info to list the line we stopped in. */
205
206 void (*print_frame_info_listing_hook) (struct symtab * s, int line,
207 int stopline, int noerror);
208 /* Replaces most of query. */
209
210 int (*query_hook) (const char *, va_list);
211
212 /* Replaces most of warning. */
213
214 void (*warning_hook) (const char *, va_list);
215
216 /* These three functions support getting lines of text from the user. They
217 are used in sequence. First readline_begin_hook is called with a text
218 string that might be (for example) a message for the user to type in a
219 sequence of commands to be executed at a breakpoint. If this function
220 calls back to a GUI, it might take this opportunity to pop up a text
221 interaction window with this message. Next, readline_hook is called
222 with a prompt that is emitted prior to collecting the user input.
223 It can be called multiple times. Finally, readline_end_hook is called
224 to notify the GUI that we are done with the interaction window and it
225 can close it. */
226
227 void (*readline_begin_hook) (char *, ...);
228 char *(*readline_hook) (char *);
229 void (*readline_end_hook) (void);
230
231 /* Called as appropriate to notify the interface of the specified breakpoint
232 conditions. */
233
234 void (*create_breakpoint_hook) (struct breakpoint * bpt);
235 void (*delete_breakpoint_hook) (struct breakpoint * bpt);
236 void (*modify_breakpoint_hook) (struct breakpoint * bpt);
237
238 /* Called as appropriate to notify the interface that we have attached
239 to or detached from an already running process. */
240
241 void (*attach_hook) (void);
242 void (*detach_hook) (void);
243
244 /* Called during long calculations to allow GUI to repair window damage, and to
245 check for stop buttons, etc... */
246
247 void (*interactive_hook) (void);
248
249 /* Called when the registers have changed, as a hint to a GUI
250 to minimize window update. */
251
252 void (*registers_changed_hook) (void);
253
254 /* Tell the GUI someone changed the register REGNO. -1 means
255 that the caller does not know which register changed or
256 that several registers have changed (see value_assign). */
257 void (*register_changed_hook) (int regno);
258
259 /* Tell the GUI someone changed LEN bytes of memory at ADDR */
260 void (*memory_changed_hook) (CORE_ADDR addr, int len);
261
262 /* Called when going to wait for the target. Usually allows the GUI to run
263 while waiting for target events. */
264
265 ptid_t (*target_wait_hook) (ptid_t ptid,
266 struct target_waitstatus * status);
267
268 /* Used by UI as a wrapper around command execution. May do various things
269 like enabling/disabling buttons, etc... */
270
271 void (*call_command_hook) (struct cmd_list_element * c, char *cmd,
272 int from_tty);
273
274 /* Called after a `set' command has finished. Is only run if the
275 `set' command succeeded. */
276
277 void (*set_hook) (struct cmd_list_element * c);
278
279 /* Called when the current thread changes. Argument is thread id. */
280
281 void (*context_hook) (int id);
282
283 /* Takes control from error (). Typically used to prevent longjmps out of the
284 middle of the GUI. Usually used in conjunction with a catch routine. */
285
286 NORETURN void (*error_hook) (void) ATTR_NORETURN;
287 \f
288
289 /* One should use catch_errors rather than manipulating these
290 directly. */
291 #if defined(HAVE_SIGSETJMP)
292 #define SIGJMP_BUF sigjmp_buf
293 #define SIGSETJMP(buf) sigsetjmp((buf), 1)
294 #define SIGLONGJMP(buf,val) siglongjmp((buf), (val))
295 #else
296 #define SIGJMP_BUF jmp_buf
297 #define SIGSETJMP(buf) setjmp(buf)
298 #define SIGLONGJMP(buf,val) longjmp((buf), (val))
299 #endif
300
301 /* Where to go for return_to_top_level. */
302 static SIGJMP_BUF *catch_return;
303
304 /* Return for reason REASON to the nearest containing catch_errors(). */
305
306 NORETURN void
307 return_to_top_level (enum return_reason reason)
308 {
309 quit_flag = 0;
310 immediate_quit = 0;
311
312 /* Perhaps it would be cleaner to do this via the cleanup chain (not sure
313 I can think of a reason why that is vital, though). */
314 bpstat_clear_actions (stop_bpstat); /* Clear queued breakpoint commands */
315
316 disable_current_display ();
317 do_cleanups (ALL_CLEANUPS);
318 if (event_loop_p && target_can_async_p () && !target_executing)
319 do_exec_cleanups (ALL_CLEANUPS);
320 if (event_loop_p && sync_execution)
321 do_exec_error_cleanups (ALL_CLEANUPS);
322
323 if (annotation_level > 1)
324 switch (reason)
325 {
326 case RETURN_QUIT:
327 annotate_quit ();
328 break;
329 case RETURN_ERROR:
330 annotate_error ();
331 break;
332 }
333
334 /* Jump to the containing catch_errors() call, communicating REASON
335 to that call via setjmp's return value. Note that REASON can't
336 be zero, by definition in defs.h. */
337
338 (NORETURN void) SIGLONGJMP (*catch_return, (int) reason);
339 }
340
341 /* Call FUNC() with args FUNC_UIOUT and FUNC_ARGS, catching any
342 errors. Set FUNC_CAUGHT to an ``enum return_reason'' if the
343 function is aborted (using return_to_top_level() or zero if the
344 function returns normally. Set FUNC_VAL to the value returned by
345 the function or 0 if the function was aborted.
346
347 Must not be called with immediate_quit in effect (bad things might
348 happen, say we got a signal in the middle of a memcpy to quit_return).
349 This is an OK restriction; with very few exceptions immediate_quit can
350 be replaced by judicious use of QUIT.
351
352 MASK specifies what to catch; it is normally set to
353 RETURN_MASK_ALL, if for no other reason than that the code which
354 calls catch_errors might not be set up to deal with a quit which
355 isn't caught. But if the code can deal with it, it generally
356 should be RETURN_MASK_ERROR, unless for some reason it is more
357 useful to abort only the portion of the operation inside the
358 catch_errors. Note that quit should return to the command line
359 fairly quickly, even if some further processing is being done. */
360
361 /* MAYBE: cagney/1999-11-05: catch_errors() in conjunction with
362 error() et.al. could maintain a set of flags that indicate the the
363 current state of each of the longjmp buffers. This would give the
364 longjmp code the chance to detect a longjmp botch (before it gets
365 to longjmperror()). Prior to 1999-11-05 this wasn't possible as
366 code also randomly used a SET_TOP_LEVEL macro that directly
367 initialize the longjmp buffers. */
368
369 /* MAYBE: cagney/1999-11-05: Should the catch_errors and cleanups code
370 be consolidated into a single file instead of being distributed
371 between utils.c and top.c? */
372
373 static void
374 catcher (catch_exceptions_ftype *func,
375 struct ui_out *func_uiout,
376 void *func_args,
377 int *func_val,
378 enum return_reason *func_caught,
379 char *errstring,
380 return_mask mask)
381 {
382 SIGJMP_BUF *saved_catch;
383 SIGJMP_BUF catch;
384 struct cleanup *saved_cleanup_chain;
385 char *saved_error_pre_print;
386 char *saved_quit_pre_print;
387 struct ui_out *saved_uiout;
388
389 /* Return value from SIGSETJMP(): enum return_reason if error or
390 quit caught, 0 otherwise. */
391 int caught;
392
393 /* Return value from FUNC(): Hopefully non-zero. Explicitly set to
394 zero if an error quit was caught. */
395 int val;
396
397 /* Override error/quit messages during FUNC. */
398
399 saved_error_pre_print = error_pre_print;
400 saved_quit_pre_print = quit_pre_print;
401
402 if (mask & RETURN_MASK_ERROR)
403 error_pre_print = errstring;
404 if (mask & RETURN_MASK_QUIT)
405 quit_pre_print = errstring;
406
407 /* Override the global ``struct ui_out'' builder. */
408
409 saved_uiout = uiout;
410 uiout = func_uiout;
411
412 /* Prevent error/quit during FUNC from calling cleanups established
413 prior to here. */
414
415 saved_cleanup_chain = save_cleanups ();
416
417 /* Call FUNC, catching error/quit events. */
418
419 saved_catch = catch_return;
420 catch_return = &catch;
421 caught = SIGSETJMP (catch);
422 if (!caught)
423 val = (*func) (func_uiout, func_args);
424 else
425 val = 0;
426 catch_return = saved_catch;
427
428 /* FIXME: cagney/1999-11-05: A correct FUNC implementation will
429 clean things up (restoring the cleanup chain) to the state they
430 were just prior to the call. Unfortunately, many FUNC's are not
431 that well behaved. This could be fixed by adding either a
432 do_cleanups call (to cover the problem) or an assertion check to
433 detect bad FUNCs code. */
434
435 /* Restore the cleanup chain, the error/quit messages, and the uiout
436 builder, to their original states. */
437
438 restore_cleanups (saved_cleanup_chain);
439
440 uiout = saved_uiout;
441
442 if (mask & RETURN_MASK_QUIT)
443 quit_pre_print = saved_quit_pre_print;
444 if (mask & RETURN_MASK_ERROR)
445 error_pre_print = saved_error_pre_print;
446
447 /* Return normally if no error/quit event occurred or this catcher
448 can handle this exception. The caller analyses the func return
449 values. */
450
451 if (!caught || (mask & RETURN_MASK (caught)))
452 {
453 *func_val = val;
454 *func_caught = caught;
455 return;
456 }
457
458 /* The caller didn't request that the event be caught, relay the
459 event to the next containing catch_errors(). */
460
461 return_to_top_level (caught);
462 }
463
464 int
465 catch_exceptions (struct ui_out *uiout,
466 catch_exceptions_ftype *func,
467 void *func_args,
468 char *errstring,
469 return_mask mask)
470 {
471 int val;
472 enum return_reason caught;
473 catcher (func, uiout, func_args, &val, &caught, errstring, mask);
474 gdb_assert (val >= 0);
475 gdb_assert (caught <= 0);
476 if (caught < 0)
477 return caught;
478 return val;
479 }
480
481 struct catch_errors_args
482 {
483 catch_errors_ftype *func;
484 void *func_args;
485 };
486
487 int
488 do_catch_errors (struct ui_out *uiout, void *data)
489 {
490 struct catch_errors_args *args = data;
491 return args->func (args->func_args);
492 }
493
494 int
495 catch_errors (catch_errors_ftype *func, void *func_args, char *errstring,
496 return_mask mask)
497 {
498 int val;
499 enum return_reason caught;
500 struct catch_errors_args args;
501 args.func = func;
502 args.func_args = func_args;
503 catcher (do_catch_errors, uiout, &args, &val, &caught, errstring, mask);
504 if (caught != 0)
505 return 0;
506 return val;
507 }
508
509 struct captured_command_args
510 {
511 catch_command_errors_ftype *command;
512 char *arg;
513 int from_tty;
514 };
515
516 static int
517 do_captured_command (void *data)
518 {
519 struct captured_command_args *context = data;
520 context->command (context->arg, context->from_tty);
521 /* FIXME: cagney/1999-11-07: Technically this do_cleanups() call
522 isn't needed. Instead an assertion check could be made that
523 simply confirmed that the called function correctly cleaned up
524 after itself. Unfortunately, old code (prior to 1999-11-04) in
525 main.c was calling SET_TOP_LEVEL(), calling the command function,
526 and then *always* calling do_cleanups(). For the moment we
527 remain ``bug compatible'' with that old code.. */
528 do_cleanups (ALL_CLEANUPS);
529 return 1;
530 }
531
532 int
533 catch_command_errors (catch_command_errors_ftype * command,
534 char *arg, int from_tty, return_mask mask)
535 {
536 struct captured_command_args args;
537 args.command = command;
538 args.arg = arg;
539 args.from_tty = from_tty;
540 return catch_errors (do_captured_command, &args, "", mask);
541 }
542
543
544 /* Handler for SIGHUP. */
545
546 #ifdef SIGHUP
547 /* Just a little helper function for disconnect(). */
548
549 /* NOTE 1999-04-29: This function will be static again, once we modify
550 gdb to use the event loop as the default command loop and we merge
551 event-top.c into this file, top.c */
552 /* static */ int
553 quit_cover (void *s)
554 {
555 caution = 0; /* Throw caution to the wind -- we're exiting.
556 This prevents asking the user dumb questions. */
557 quit_command ((char *) 0, 0);
558 return 0;
559 }
560
561 static void
562 disconnect (int signo)
563 {
564 catch_errors (quit_cover, NULL,
565 "Could not kill the program being debugged", RETURN_MASK_ALL);
566 signal (SIGHUP, SIG_DFL);
567 kill (getpid (), SIGHUP);
568 }
569 #endif /* defined SIGHUP */
570 \f
571 /* Line number we are currently in in a file which is being sourced. */
572 /* NOTE 1999-04-29: This variable will be static again, once we modify
573 gdb to use the event loop as the default command loop and we merge
574 event-top.c into this file, top.c */
575 /* static */ int source_line_number;
576
577 /* Name of the file we are sourcing. */
578 /* NOTE 1999-04-29: This variable will be static again, once we modify
579 gdb to use the event loop as the default command loop and we merge
580 event-top.c into this file, top.c */
581 /* static */ char *source_file_name;
582
583 /* Buffer containing the error_pre_print used by the source stuff.
584 Malloc'd. */
585 /* NOTE 1999-04-29: This variable will be static again, once we modify
586 gdb to use the event loop as the default command loop and we merge
587 event-top.c into this file, top.c */
588 /* static */ char *source_error;
589 static int source_error_allocated;
590
591 /* Something to glom on to the start of error_pre_print if source_file_name
592 is set. */
593 /* NOTE 1999-04-29: This variable will be static again, once we modify
594 gdb to use the event loop as the default command loop and we merge
595 event-top.c into this file, top.c */
596 /* static */ char *source_pre_error;
597
598 /* Clean up on error during a "source" command (or execution of a
599 user-defined command). */
600
601 void
602 do_restore_instream_cleanup (void *stream)
603 {
604 /* Restore the previous input stream. */
605 instream = stream;
606 }
607
608 /* Read commands from STREAM. */
609 void
610 read_command_file (FILE *stream)
611 {
612 struct cleanup *cleanups;
613
614 cleanups = make_cleanup (do_restore_instream_cleanup, instream);
615 instream = stream;
616 command_loop ();
617 do_cleanups (cleanups);
618 }
619 \f
620 void (*pre_init_ui_hook) (void);
621
622 #ifdef __MSDOS__
623 void
624 do_chdir_cleanup (void *old_dir)
625 {
626 chdir (old_dir);
627 xfree (old_dir);
628 }
629 #endif
630
631 /* Execute the line P as a command.
632 Pass FROM_TTY as second argument to the defining function. */
633
634 void
635 execute_command (char *p, int from_tty)
636 {
637 register struct cmd_list_element *c;
638 register enum language flang;
639 static int warned = 0;
640 char *line;
641
642 free_all_values ();
643
644 /* Force cleanup of any alloca areas if using C alloca instead of
645 a builtin alloca. */
646 alloca (0);
647
648 /* This can happen when command_line_input hits end of file. */
649 if (p == NULL)
650 return;
651
652 serial_log_command (p);
653
654 while (*p == ' ' || *p == '\t')
655 p++;
656 if (*p)
657 {
658 char *arg;
659 line = p;
660
661 c = lookup_cmd (&p, cmdlist, "", 0, 1);
662
663 /* If the target is running, we allow only a limited set of
664 commands. */
665 if (event_loop_p && target_can_async_p () && target_executing)
666 if (!strcmp (c->name, "help")
667 && !strcmp (c->name, "pwd")
668 && !strcmp (c->name, "show")
669 && !strcmp (c->name, "stop"))
670 error ("Cannot execute this command while the target is running.");
671
672 /* Pass null arg rather than an empty one. */
673 arg = *p ? p : 0;
674
675 /* Clear off trailing whitespace, except for set and complete command. */
676 if (arg
677 && c->type != set_cmd
678 && !is_complete_command (c->function.cfunc))
679 {
680 p = arg + strlen (arg) - 1;
681 while (p >= arg && (*p == ' ' || *p == '\t'))
682 p--;
683 *(p + 1) = '\0';
684 }
685
686 /* If this command has been pre-hooked, run the hook first. */
687 if ((c->hook_pre) && (!c->hook_in))
688 {
689 c->hook_in = 1; /* Prevent recursive hooking */
690 execute_user_command (c->hook_pre, (char *) 0);
691 c->hook_in = 0; /* Allow hook to work again once it is complete */
692 }
693
694 if (c->flags & DEPRECATED_WARN_USER)
695 deprecated_cmd_warning (&line);
696
697 if (c->class == class_user)
698 execute_user_command (c, arg);
699 else if (c->type == set_cmd || c->type == show_cmd)
700 do_setshow_command (arg, from_tty & caution, c);
701 else if (c->function.cfunc == NO_FUNCTION)
702 error ("That is not a command, just a help topic.");
703 else if (call_command_hook)
704 call_command_hook (c, arg, from_tty & caution);
705 else
706 (*c->function.cfunc) (arg, from_tty & caution);
707
708 /* If this command has been post-hooked, run the hook last. */
709 if ((c->hook_post) && (!c->hook_in))
710 {
711 c->hook_in = 1; /* Prevent recursive hooking */
712 execute_user_command (c->hook_post, (char *) 0);
713 c->hook_in = 0; /* allow hook to work again once it is complete */
714 }
715
716 }
717
718 /* Tell the user if the language has changed (except first time). */
719 if (current_language != expected_language)
720 {
721 if (language_mode == language_mode_auto)
722 {
723 language_info (1); /* Print what changed. */
724 }
725 warned = 0;
726 }
727
728 /* Warn the user if the working language does not match the
729 language of the current frame. Only warn the user if we are
730 actually running the program, i.e. there is a stack. */
731 /* FIXME: This should be cacheing the frame and only running when
732 the frame changes. */
733
734 if (target_has_stack)
735 {
736 flang = get_frame_language ();
737 if (!warned
738 && flang != language_unknown
739 && flang != current_language->la_language)
740 {
741 printf_filtered ("%s\n", lang_frame_mismatch_warn);
742 warned = 1;
743 }
744 }
745 }
746
747 /* Read commands from `instream' and execute them
748 until end of file or error reading instream. */
749
750 void
751 command_loop (void)
752 {
753 struct cleanup *old_chain;
754 char *command;
755 int stdin_is_tty = ISATTY (stdin);
756 long time_at_cmd_start;
757 #ifdef HAVE_SBRK
758 long space_at_cmd_start = 0;
759 #endif
760 extern int display_time;
761 extern int display_space;
762
763 while (instream && !feof (instream))
764 {
765 if (window_hook && instream == stdin)
766 (*window_hook) (instream, get_prompt ());
767
768 quit_flag = 0;
769 if (instream == stdin && stdin_is_tty)
770 reinitialize_more_filter ();
771 old_chain = make_cleanup (null_cleanup, 0);
772
773 /* Get a command-line. This calls the readline package. */
774 command = command_line_input (instream == stdin ?
775 get_prompt () : (char *) NULL,
776 instream == stdin, "prompt");
777 if (command == 0)
778 return;
779
780 time_at_cmd_start = get_run_time ();
781
782 if (display_space)
783 {
784 #ifdef HAVE_SBRK
785 extern char **environ;
786 char *lim = (char *) sbrk (0);
787
788 space_at_cmd_start = (long) (lim - (char *) &environ);
789 #endif
790 }
791
792 execute_command (command, instream == stdin);
793 /* Do any commands attached to breakpoint we stopped at. */
794 bpstat_do_actions (&stop_bpstat);
795 do_cleanups (old_chain);
796
797 if (display_time)
798 {
799 long cmd_time = get_run_time () - time_at_cmd_start;
800
801 printf_unfiltered ("Command execution time: %ld.%06ld\n",
802 cmd_time / 1000000, cmd_time % 1000000);
803 }
804
805 if (display_space)
806 {
807 #ifdef HAVE_SBRK
808 extern char **environ;
809 char *lim = (char *) sbrk (0);
810 long space_now = lim - (char *) &environ;
811 long space_diff = space_now - space_at_cmd_start;
812
813 printf_unfiltered ("Space used: %ld (%c%ld for this command)\n",
814 space_now,
815 (space_diff >= 0 ? '+' : '-'),
816 space_diff);
817 #endif
818 }
819 }
820 }
821
822 /* Read commands from `instream' and execute them until end of file or
823 error reading instream. This command loop doesnt care about any
824 such things as displaying time and space usage. If the user asks
825 for those, they won't work. */
826 void
827 simplified_command_loop (char *(*read_input_func) (char *),
828 void (*execute_command_func) (char *, int))
829 {
830 struct cleanup *old_chain;
831 char *command;
832 int stdin_is_tty = ISATTY (stdin);
833
834 while (instream && !feof (instream))
835 {
836 quit_flag = 0;
837 if (instream == stdin && stdin_is_tty)
838 reinitialize_more_filter ();
839 old_chain = make_cleanup (null_cleanup, 0);
840
841 /* Get a command-line. */
842 command = (*read_input_func) (instream == stdin ?
843 get_prompt () : (char *) NULL);
844
845 if (command == 0)
846 return;
847
848 (*execute_command_func) (command, instream == stdin);
849
850 /* Do any commands attached to breakpoint we stopped at. */
851 bpstat_do_actions (&stop_bpstat);
852
853 do_cleanups (old_chain);
854 }
855 }
856 \f
857 /* Commands call this if they do not want to be repeated by null lines. */
858
859 void
860 dont_repeat (void)
861 {
862 if (server_command)
863 return;
864
865 /* If we aren't reading from standard input, we are saving the last
866 thing read from stdin in line and don't want to delete it. Null lines
867 won't repeat here in any case. */
868 if (instream == stdin)
869 *line = 0;
870 }
871 \f
872 /* Read a line from the stream "instream" without command line editing.
873
874 It prints PROMPT_ARG once at the start.
875 Action is compatible with "readline", e.g. space for the result is
876 malloc'd and should be freed by the caller.
877
878 A NULL return means end of file. */
879 char *
880 gdb_readline (char *prompt_arg)
881 {
882 int c;
883 char *result;
884 int input_index = 0;
885 int result_size = 80;
886
887 if (prompt_arg)
888 {
889 /* Don't use a _filtered function here. It causes the assumed
890 character position to be off, since the newline we read from
891 the user is not accounted for. */
892 fputs_unfiltered (prompt_arg, gdb_stdout);
893 /* OBSOLETE #ifdef MPW */
894 /* OBSOLETE Move to a new line so the entered line doesn't have a prompt */
895 /* OBSOLETE on the front of it. */
896 /* OBSOLETE fputs_unfiltered ("\n", gdb_stdout); */
897 /* OBSOLETE #endif *//* MPW */
898 gdb_flush (gdb_stdout);
899 }
900
901 result = (char *) xmalloc (result_size);
902
903 while (1)
904 {
905 /* Read from stdin if we are executing a user defined command.
906 This is the right thing for prompt_for_continue, at least. */
907 c = fgetc (instream ? instream : stdin);
908
909 if (c == EOF)
910 {
911 if (input_index > 0)
912 /* The last line does not end with a newline. Return it, and
913 if we are called again fgetc will still return EOF and
914 we'll return NULL then. */
915 break;
916 xfree (result);
917 return NULL;
918 }
919
920 if (c == '\n')
921 #ifndef CRLF_SOURCE_FILES
922 break;
923 #else
924 {
925 if (input_index > 0 && result[input_index - 1] == '\r')
926 input_index--;
927 break;
928 }
929 #endif
930
931 result[input_index++] = c;
932 while (input_index >= result_size)
933 {
934 result_size *= 2;
935 result = (char *) xrealloc (result, result_size);
936 }
937 }
938
939 result[input_index++] = '\0';
940 return result;
941 }
942
943 /* Variables which control command line editing and history
944 substitution. These variables are given default values at the end
945 of this file. */
946 static int command_editing_p;
947 /* NOTE 1999-04-29: This variable will be static again, once we modify
948 gdb to use the event loop as the default command loop and we merge
949 event-top.c into this file, top.c */
950 /* static */ int history_expansion_p;
951 static int write_history_p;
952 static int history_size;
953 static char *history_filename;
954
955 \f
956 #ifdef STOP_SIGNAL
957 static void
958 stop_sig (int signo)
959 {
960 #if STOP_SIGNAL == SIGTSTP
961 signal (SIGTSTP, SIG_DFL);
962 #if HAVE_SIGPROCMASK
963 {
964 sigset_t zero;
965
966 sigemptyset (&zero);
967 sigprocmask (SIG_SETMASK, &zero, 0);
968 }
969 #elif HAVE_SIGSETMASK
970 sigsetmask (0);
971 #endif
972 kill (getpid (), SIGTSTP);
973 signal (SIGTSTP, stop_sig);
974 #else
975 signal (STOP_SIGNAL, stop_sig);
976 #endif
977 printf_unfiltered ("%s", get_prompt ());
978 gdb_flush (gdb_stdout);
979
980 /* Forget about any previous command -- null line now will do nothing. */
981 dont_repeat ();
982 }
983 #endif /* STOP_SIGNAL */
984
985 /* Initialize signal handlers. */
986 static void
987 float_handler (int signo)
988 {
989 /* This message is based on ANSI C, section 4.7. Note that integer
990 divide by zero causes this, so "float" is a misnomer. */
991 signal (SIGFPE, float_handler);
992 error ("Erroneous arithmetic operation.");
993 }
994
995 static void
996 do_nothing (int signo)
997 {
998 /* Under System V the default disposition of a signal is reinstated after
999 the signal is caught and delivered to an application process. On such
1000 systems one must restore the replacement signal handler if one wishes
1001 to continue handling the signal in one's program. On BSD systems this
1002 is not needed but it is harmless, and it simplifies the code to just do
1003 it unconditionally. */
1004 signal (signo, do_nothing);
1005 }
1006
1007 static void
1008 init_signals (void)
1009 {
1010 signal (SIGINT, request_quit);
1011
1012 /* If SIGTRAP was set to SIG_IGN, then the SIG_IGN will get passed
1013 to the inferior and breakpoints will be ignored. */
1014 #ifdef SIGTRAP
1015 signal (SIGTRAP, SIG_DFL);
1016 #endif
1017
1018 /* If we initialize SIGQUIT to SIG_IGN, then the SIG_IGN will get
1019 passed to the inferior, which we don't want. It would be
1020 possible to do a "signal (SIGQUIT, SIG_DFL)" after we fork, but
1021 on BSD4.3 systems using vfork, that can affect the
1022 GDB process as well as the inferior (the signal handling tables
1023 might be in memory, shared between the two). Since we establish
1024 a handler for SIGQUIT, when we call exec it will set the signal
1025 to SIG_DFL for us. */
1026 signal (SIGQUIT, do_nothing);
1027 #ifdef SIGHUP
1028 if (signal (SIGHUP, do_nothing) != SIG_IGN)
1029 signal (SIGHUP, disconnect);
1030 #endif
1031 signal (SIGFPE, float_handler);
1032
1033 #if defined(SIGWINCH) && defined(SIGWINCH_HANDLER)
1034 signal (SIGWINCH, SIGWINCH_HANDLER);
1035 #endif
1036 }
1037 \f
1038 /* The current saved history number from operate-and-get-next.
1039 This is -1 if not valid. */
1040 static int operate_saved_history = -1;
1041
1042 /* This is put on the appropriate hook and helps operate-and-get-next
1043 do its work. */
1044 void
1045 gdb_rl_operate_and_get_next_completion ()
1046 {
1047 int delta = where_history () - operate_saved_history;
1048 /* The `key' argument to rl_get_previous_history is ignored. */
1049 rl_get_previous_history (delta, 0);
1050 operate_saved_history = -1;
1051
1052 /* readline doesn't automatically update the display for us. */
1053 rl_redisplay ();
1054
1055 after_char_processing_hook = NULL;
1056 rl_pre_input_hook = NULL;
1057 }
1058
1059 /* This is a gdb-local readline command handler. It accepts the
1060 current command line (like RET does) and, if this command was taken
1061 from the history, arranges for the next command in the history to
1062 appear on the command line when the prompt returns.
1063 We ignore the arguments. */
1064 static int
1065 gdb_rl_operate_and_get_next (int count, int key)
1066 {
1067 if (event_loop_p)
1068 {
1069 /* Use the async hook. */
1070 after_char_processing_hook = gdb_rl_operate_and_get_next_completion;
1071 }
1072 else
1073 {
1074 /* This hook only works correctly when we are using the
1075 synchronous readline. */
1076 rl_pre_input_hook = (Function *) gdb_rl_operate_and_get_next_completion;
1077 }
1078
1079 /* Add 1 because we eventually want the next line. */
1080 operate_saved_history = where_history () + 1;
1081 return rl_newline (1, key);
1082 }
1083 \f
1084 /* Read one line from the command input stream `instream'
1085 into the local static buffer `linebuffer' (whose current length
1086 is `linelength').
1087 The buffer is made bigger as necessary.
1088 Returns the address of the start of the line.
1089
1090 NULL is returned for end of file.
1091
1092 *If* the instream == stdin & stdin is a terminal, the line read
1093 is copied into the file line saver (global var char *line,
1094 length linesize) so that it can be duplicated.
1095
1096 This routine either uses fancy command line editing or
1097 simple input as the user has requested. */
1098
1099 char *
1100 command_line_input (char *prompt_arg, int repeat, char *annotation_suffix)
1101 {
1102 static char *linebuffer = 0;
1103 static unsigned linelength = 0;
1104 register char *p;
1105 char *p1;
1106 char *rl;
1107 char *local_prompt = prompt_arg;
1108 char *nline;
1109 char got_eof = 0;
1110
1111 /* The annotation suffix must be non-NULL. */
1112 if (annotation_suffix == NULL)
1113 annotation_suffix = "";
1114
1115 if (annotation_level > 1 && instream == stdin)
1116 {
1117 local_prompt = alloca ((prompt_arg == NULL ? 0 : strlen (prompt_arg))
1118 + strlen (annotation_suffix) + 40);
1119 if (prompt_arg == NULL)
1120 local_prompt[0] = '\0';
1121 else
1122 strcpy (local_prompt, prompt_arg);
1123 strcat (local_prompt, "\n\032\032");
1124 strcat (local_prompt, annotation_suffix);
1125 strcat (local_prompt, "\n");
1126 }
1127
1128 if (linebuffer == 0)
1129 {
1130 linelength = 80;
1131 linebuffer = (char *) xmalloc (linelength);
1132 }
1133
1134 p = linebuffer;
1135
1136 /* Control-C quits instantly if typed while in this loop
1137 since it should not wait until the user types a newline. */
1138 immediate_quit++;
1139 #ifdef STOP_SIGNAL
1140 if (job_control)
1141 {
1142 if (event_loop_p)
1143 signal (STOP_SIGNAL, handle_stop_sig);
1144 else
1145 signal (STOP_SIGNAL, stop_sig);
1146 }
1147 #endif
1148
1149 while (1)
1150 {
1151 /* Make sure that all output has been output. Some machines may let
1152 you get away with leaving out some of the gdb_flush, but not all. */
1153 wrap_here ("");
1154 gdb_flush (gdb_stdout);
1155 gdb_flush (gdb_stderr);
1156
1157 if (source_file_name != NULL)
1158 {
1159 ++source_line_number;
1160 sprintf (source_error,
1161 "%s%s:%d: Error in sourced command file:\n",
1162 source_pre_error,
1163 source_file_name,
1164 source_line_number);
1165 error_pre_print = source_error;
1166 }
1167
1168 if (annotation_level > 1 && instream == stdin)
1169 {
1170 printf_unfiltered ("\n\032\032pre-");
1171 printf_unfiltered (annotation_suffix);
1172 printf_unfiltered ("\n");
1173 }
1174
1175 /* Don't use fancy stuff if not talking to stdin. */
1176 if (readline_hook && instream == NULL)
1177 {
1178 rl = (*readline_hook) (local_prompt);
1179 }
1180 else if (command_editing_p && instream == stdin && ISATTY (instream))
1181 {
1182 rl = readline (local_prompt);
1183 }
1184 else
1185 {
1186 rl = gdb_readline (local_prompt);
1187 }
1188
1189 if (annotation_level > 1 && instream == stdin)
1190 {
1191 printf_unfiltered ("\n\032\032post-");
1192 printf_unfiltered (annotation_suffix);
1193 printf_unfiltered ("\n");
1194 }
1195
1196 if (!rl || rl == (char *) EOF)
1197 {
1198 got_eof = 1;
1199 break;
1200 }
1201 if (strlen (rl) + 1 + (p - linebuffer) > linelength)
1202 {
1203 linelength = strlen (rl) + 1 + (p - linebuffer);
1204 nline = (char *) xrealloc (linebuffer, linelength);
1205 p += nline - linebuffer;
1206 linebuffer = nline;
1207 }
1208 p1 = rl;
1209 /* Copy line. Don't copy null at end. (Leaves line alone
1210 if this was just a newline) */
1211 while (*p1)
1212 *p++ = *p1++;
1213
1214 xfree (rl); /* Allocated in readline. */
1215
1216 if (p == linebuffer || *(p - 1) != '\\')
1217 break;
1218
1219 p--; /* Put on top of '\'. */
1220 local_prompt = (char *) 0;
1221 }
1222
1223 #ifdef STOP_SIGNAL
1224 if (job_control)
1225 signal (STOP_SIGNAL, SIG_DFL);
1226 #endif
1227 immediate_quit--;
1228
1229 if (got_eof)
1230 return NULL;
1231
1232 #define SERVER_COMMAND_LENGTH 7
1233 server_command =
1234 (p - linebuffer > SERVER_COMMAND_LENGTH)
1235 && STREQN (linebuffer, "server ", SERVER_COMMAND_LENGTH);
1236 if (server_command)
1237 {
1238 /* Note that we don't set `line'. Between this and the check in
1239 dont_repeat, this insures that repeating will still do the
1240 right thing. */
1241 *p = '\0';
1242 return linebuffer + SERVER_COMMAND_LENGTH;
1243 }
1244
1245 /* Do history expansion if that is wished. */
1246 if (history_expansion_p && instream == stdin
1247 && ISATTY (instream))
1248 {
1249 char *history_value;
1250 int expanded;
1251
1252 *p = '\0'; /* Insert null now. */
1253 expanded = history_expand (linebuffer, &history_value);
1254 if (expanded)
1255 {
1256 /* Print the changes. */
1257 printf_unfiltered ("%s\n", history_value);
1258
1259 /* If there was an error, call this function again. */
1260 if (expanded < 0)
1261 {
1262 xfree (history_value);
1263 return command_line_input (prompt_arg, repeat, annotation_suffix);
1264 }
1265 if (strlen (history_value) > linelength)
1266 {
1267 linelength = strlen (history_value) + 1;
1268 linebuffer = (char *) xrealloc (linebuffer, linelength);
1269 }
1270 strcpy (linebuffer, history_value);
1271 p = linebuffer + strlen (linebuffer);
1272 xfree (history_value);
1273 }
1274 }
1275
1276 /* If we just got an empty line, and that is supposed
1277 to repeat the previous command, return the value in the
1278 global buffer. */
1279 if (repeat && p == linebuffer)
1280 return line;
1281 for (p1 = linebuffer; *p1 == ' ' || *p1 == '\t'; p1++);
1282 if (repeat && !*p1)
1283 return line;
1284
1285 *p = 0;
1286
1287 /* Add line to history if appropriate. */
1288 if (instream == stdin
1289 && ISATTY (stdin) && *linebuffer)
1290 add_history (linebuffer);
1291
1292 /* Note: lines consisting solely of comments are added to the command
1293 history. This is useful when you type a command, and then
1294 realize you don't want to execute it quite yet. You can comment
1295 out the command and then later fetch it from the value history
1296 and remove the '#'. The kill ring is probably better, but some
1297 people are in the habit of commenting things out. */
1298 if (*p1 == '#')
1299 *p1 = '\0'; /* Found a comment. */
1300
1301 /* Save into global buffer if appropriate. */
1302 if (repeat)
1303 {
1304 if (linelength > linesize)
1305 {
1306 line = xrealloc (line, linelength);
1307 linesize = linelength;
1308 }
1309 strcpy (line, linebuffer);
1310 return line;
1311 }
1312
1313 return linebuffer;
1314 }
1315 \f
1316 /* Print the GDB banner. */
1317 void
1318 print_gdb_version (struct ui_file *stream)
1319 {
1320 /* From GNU coding standards, first line is meant to be easy for a
1321 program to parse, and is just canonical program name and version
1322 number, which starts after last space. */
1323
1324 fprintf_filtered (stream, "GNU gdb %s\n", version);
1325
1326 /* Second line is a copyright notice. */
1327
1328 fprintf_filtered (stream, "Copyright 2001 Free Software Foundation, Inc.\n");
1329
1330 /* Following the copyright is a brief statement that the program is
1331 free software, that users are free to copy and change it on
1332 certain conditions, that it is covered by the GNU GPL, and that
1333 there is no warranty. */
1334
1335 fprintf_filtered (stream, "\
1336 GDB is free software, covered by the GNU General Public License, and you are\n\
1337 welcome to change it and/or distribute copies of it under certain conditions.\n\
1338 Type \"show copying\" to see the conditions.\n\
1339 There is absolutely no warranty for GDB. Type \"show warranty\" for details.\n");
1340
1341 /* After the required info we print the configuration information. */
1342
1343 fprintf_filtered (stream, "This GDB was configured as \"");
1344 if (!STREQ (host_name, target_name))
1345 {
1346 fprintf_filtered (stream, "--host=%s --target=%s", host_name, target_name);
1347 }
1348 else
1349 {
1350 fprintf_filtered (stream, "%s", host_name);
1351 }
1352 fprintf_filtered (stream, "\".");
1353 }
1354 \f
1355 /* get_prompt: access method for the GDB prompt string. */
1356
1357 #define MAX_PROMPT_SIZE 256
1358
1359 /*
1360 * int get_prompt_1 (char * buf);
1361 *
1362 * Work-horse for get_prompt (called via catch_errors).
1363 * Argument is buffer to hold the formatted prompt.
1364 *
1365 * Returns: 1 for success (use formatted prompt)
1366 * 0 for failure (use gdb_prompt_string).
1367 */
1368
1369 static int gdb_prompt_escape;
1370
1371 static int
1372 get_prompt_1 (void *data)
1373 {
1374 char *formatted_prompt = data;
1375 char *local_prompt;
1376
1377 if (event_loop_p)
1378 local_prompt = PROMPT (0);
1379 else
1380 local_prompt = gdb_prompt_string;
1381
1382
1383 if (gdb_prompt_escape == 0)
1384 {
1385 return 0; /* do no formatting */
1386 }
1387 else
1388 /* formatted prompt */
1389 {
1390 char fmt[40], *promptp, *outp, *tmp;
1391 struct value *arg_val;
1392 DOUBLEST doubleval;
1393 LONGEST longval;
1394 CORE_ADDR addrval;
1395
1396 int i, len;
1397 struct type *arg_type, *elt_type;
1398
1399 promptp = local_prompt;
1400 outp = formatted_prompt;
1401
1402 while (*promptp != '\0')
1403 {
1404 int available = MAX_PROMPT_SIZE - (outp - formatted_prompt) - 1;
1405
1406 if (*promptp != gdb_prompt_escape)
1407 {
1408 if (available >= 1) /* overflow protect */
1409 *outp++ = *promptp++;
1410 }
1411 else
1412 {
1413 /* GDB prompt string contains escape char. Parse for arg.
1414 Two consecutive escape chars followed by arg followed by
1415 a comma means to insert the arg using a default format.
1416 Otherwise a printf format string may be included between
1417 the two escape chars. eg:
1418 %%foo, insert foo using default format
1419 %2.2f%foo, insert foo using "%2.2f" format
1420 A mismatch between the format string and the data type
1421 of "foo" is an error (which we don't know how to protect
1422 against). */
1423
1424 fmt[0] = '\0'; /* assume null format string */
1425 if (promptp[1] == gdb_prompt_escape) /* double esc char */
1426 {
1427 promptp += 2; /* skip past two escape chars. */
1428 }
1429 else
1430 {
1431 /* extract format string from between two esc chars */
1432 i = 0;
1433 do
1434 {
1435 fmt[i++] = *promptp++; /* copy format string */
1436 }
1437 while (i < sizeof (fmt) - 1 &&
1438 *promptp != gdb_prompt_escape &&
1439 *promptp != '\0');
1440
1441 if (*promptp != gdb_prompt_escape)
1442 error ("Syntax error at prompt position %d",
1443 promptp - local_prompt);
1444 else
1445 {
1446 promptp++; /* skip second escape char */
1447 fmt[i++] = '\0'; /* terminate the format string */
1448 }
1449 }
1450
1451 arg_val = parse_to_comma_and_eval (&promptp);
1452 if (*promptp == ',')
1453 promptp++; /* skip past the comma */
1454 arg_type = check_typedef (VALUE_TYPE (arg_val));
1455 switch (TYPE_CODE (arg_type))
1456 {
1457 case TYPE_CODE_ARRAY:
1458 elt_type = check_typedef (TYPE_TARGET_TYPE (arg_type));
1459 if (TYPE_LENGTH (arg_type) > 0 &&
1460 TYPE_LENGTH (elt_type) == 1 &&
1461 TYPE_CODE (elt_type) == TYPE_CODE_INT)
1462 {
1463 int len = TYPE_LENGTH (arg_type);
1464
1465 if (VALUE_LAZY (arg_val))
1466 value_fetch_lazy (arg_val);
1467 tmp = VALUE_CONTENTS (arg_val);
1468
1469 if (len > available)
1470 len = available; /* overflow protect */
1471
1472 /* FIXME: how to protect GDB from crashing
1473 from bad user-supplied format string? */
1474 if (fmt[0] != 0)
1475 sprintf (outp, fmt, tmp);
1476 else
1477 strncpy (outp, tmp, len);
1478 outp[len] = '\0';
1479 }
1480 break;
1481 case TYPE_CODE_PTR:
1482 elt_type = check_typedef (TYPE_TARGET_TYPE (arg_type));
1483 addrval = value_as_address (arg_val);
1484
1485 if (TYPE_LENGTH (elt_type) == 1 &&
1486 TYPE_CODE (elt_type) == TYPE_CODE_INT &&
1487 addrval != 0)
1488 {
1489 /* display it as a string */
1490 char *default_fmt = "%s";
1491 char *tmp;
1492 int err = 0;
1493
1494 /* Limiting the number of bytes that the following call
1495 will read protects us from sprintf overflow later. */
1496 i = target_read_string (addrval, /* src */
1497 &tmp, /* dest */
1498 available, /* len */
1499 &err);
1500 if (err) /* read failed */
1501 error ("%s on target_read", safe_strerror (err));
1502
1503 tmp[i] = '\0'; /* force-terminate string */
1504 /* FIXME: how to protect GDB from crashing
1505 from bad user-supplied format string? */
1506 sprintf (outp, fmt[0] == 0 ? default_fmt : fmt,
1507 tmp);
1508 xfree (tmp);
1509 }
1510 else
1511 {
1512 /* display it as a pointer */
1513 char *default_fmt = "0x%x";
1514
1515 /* FIXME: how to protect GDB from crashing
1516 from bad user-supplied format string? */
1517 if (available >= 16 /*? */ ) /* overflow protect */
1518 sprintf (outp, fmt[0] == 0 ? default_fmt : fmt,
1519 (long) addrval);
1520 }
1521 break;
1522 case TYPE_CODE_FLT:
1523 {
1524 char *default_fmt = "%g";
1525
1526 doubleval = value_as_double (arg_val);
1527 /* FIXME: how to protect GDB from crashing
1528 from bad user-supplied format string? */
1529 if (available >= 16 /*? */ ) /* overflow protect */
1530 sprintf (outp, fmt[0] == 0 ? default_fmt : fmt,
1531 (double) doubleval);
1532 break;
1533 }
1534 case TYPE_CODE_INT:
1535 {
1536 char *default_fmt = "%d";
1537
1538 longval = value_as_long (arg_val);
1539 /* FIXME: how to protect GDB from crashing
1540 from bad user-supplied format string? */
1541 if (available >= 16 /*? */ ) /* overflow protect */
1542 sprintf (outp, fmt[0] == 0 ? default_fmt : fmt,
1543 (long) longval);
1544 break;
1545 }
1546 case TYPE_CODE_BOOL:
1547 {
1548 /* no default format for bool */
1549 longval = value_as_long (arg_val);
1550 if (available >= 8 /*? */ ) /* overflow protect */
1551 {
1552 if (longval)
1553 strcpy (outp, "<true>");
1554 else
1555 strcpy (outp, "<false>");
1556 }
1557 break;
1558 }
1559 case TYPE_CODE_ENUM:
1560 {
1561 /* no default format for enum */
1562 longval = value_as_long (arg_val);
1563 len = TYPE_NFIELDS (arg_type);
1564 /* find enum name if possible */
1565 for (i = 0; i < len; i++)
1566 if (TYPE_FIELD_BITPOS (arg_type, i) == longval)
1567 break; /* match -- end loop */
1568
1569 if (i < len) /* enum name found */
1570 {
1571 char *name = TYPE_FIELD_NAME (arg_type, i);
1572
1573 strncpy (outp, name, available);
1574 /* in casel available < strlen (name), */
1575 outp[available] = '\0';
1576 }
1577 else
1578 {
1579 if (available >= 16 /*? */ ) /* overflow protect */
1580 sprintf (outp, "%ld", (long) longval);
1581 }
1582 break;
1583 }
1584 case TYPE_CODE_VOID:
1585 *outp = '\0';
1586 break; /* void type -- no output */
1587 default:
1588 error ("bad data type at prompt position %d",
1589 promptp - local_prompt);
1590 break;
1591 }
1592 outp += strlen (outp);
1593 }
1594 }
1595 *outp++ = '\0'; /* terminate prompt string */
1596 return 1;
1597 }
1598 }
1599
1600 char *
1601 get_prompt (void)
1602 {
1603 static char buf[MAX_PROMPT_SIZE];
1604
1605 if (catch_errors (get_prompt_1, buf, "bad formatted prompt: ",
1606 RETURN_MASK_ALL))
1607 {
1608 return &buf[0]; /* successful formatted prompt */
1609 }
1610 else
1611 {
1612 /* Prompt could not be formatted. */
1613 if (event_loop_p)
1614 return PROMPT (0);
1615 else
1616 return gdb_prompt_string;
1617 }
1618 }
1619
1620 void
1621 set_prompt (char *s)
1622 {
1623 /* ??rehrauer: I don't know why this fails, since it looks as though
1624 assignments to prompt are wrapped in calls to savestring...
1625 if (prompt != NULL)
1626 xfree (prompt);
1627 */
1628 if (event_loop_p)
1629 PROMPT (0) = savestring (s, strlen (s));
1630 else
1631 gdb_prompt_string = savestring (s, strlen (s));
1632 }
1633 \f
1634
1635 /* If necessary, make the user confirm that we should quit. Return
1636 non-zero if we should quit, zero if we shouldn't. */
1637
1638 int
1639 quit_confirm (void)
1640 {
1641 if (! ptid_equal (inferior_ptid, null_ptid) && target_has_execution)
1642 {
1643 char *s;
1644
1645 /* This is something of a hack. But there's no reliable way to
1646 see if a GUI is running. The `use_windows' variable doesn't
1647 cut it. */
1648 if (init_ui_hook)
1649 s = "A debugging session is active.\nDo you still want to close the debugger?";
1650 else if (attach_flag)
1651 s = "The program is running. Quit anyway (and detach it)? ";
1652 else
1653 s = "The program is running. Exit anyway? ";
1654
1655 if (!query (s))
1656 return 0;
1657 }
1658
1659 return 1;
1660 }
1661
1662 /* Quit without asking for confirmation. */
1663
1664 void
1665 quit_force (char *args, int from_tty)
1666 {
1667 int exit_code = 0;
1668
1669 /* An optional expression may be used to cause gdb to terminate with the
1670 value of that expression. */
1671 if (args)
1672 {
1673 struct value *val = parse_and_eval (args);
1674
1675 exit_code = (int) value_as_long (val);
1676 }
1677
1678 if (! ptid_equal (inferior_ptid, null_ptid) && target_has_execution)
1679 {
1680 if (attach_flag)
1681 target_detach (args, from_tty);
1682 else
1683 target_kill ();
1684 }
1685
1686 /* UDI wants this, to kill the TIP. */
1687 target_close (1);
1688
1689 /* Save the history information if it is appropriate to do so. */
1690 if (write_history_p && history_filename)
1691 write_history (history_filename);
1692
1693 do_final_cleanups (ALL_CLEANUPS); /* Do any final cleanups before exiting */
1694
1695 exit (exit_code);
1696 }
1697
1698 /* Returns whether GDB is running on a terminal and whether the user
1699 desires that questions be asked of them on that terminal. */
1700
1701 int
1702 input_from_terminal_p (void)
1703 {
1704 return gdb_has_a_terminal () && (instream == stdin) & caution;
1705 }
1706 \f
1707 /* ARGSUSED */
1708 static void
1709 dont_repeat_command (char *ignored, int from_tty)
1710 {
1711 *line = 0; /* Can't call dont_repeat here because we're not
1712 necessarily reading from stdin. */
1713 }
1714 \f
1715 /* Functions to manipulate command line editing control variables. */
1716
1717 /* Number of commands to print in each call to show_commands. */
1718 #define Hist_print 10
1719 void
1720 show_commands (char *args, int from_tty)
1721 {
1722 /* Index for history commands. Relative to history_base. */
1723 int offset;
1724
1725 /* Number of the history entry which we are planning to display next.
1726 Relative to history_base. */
1727 static int num = 0;
1728
1729 /* The first command in the history which doesn't exist (i.e. one more
1730 than the number of the last command). Relative to history_base. */
1731 int hist_len;
1732
1733 /* Print out some of the commands from the command history. */
1734 /* First determine the length of the history list. */
1735 hist_len = history_size;
1736 for (offset = 0; offset < history_size; offset++)
1737 {
1738 if (!history_get (history_base + offset))
1739 {
1740 hist_len = offset;
1741 break;
1742 }
1743 }
1744
1745 if (args)
1746 {
1747 if (args[0] == '+' && args[1] == '\0')
1748 /* "info editing +" should print from the stored position. */
1749 ;
1750 else
1751 /* "info editing <exp>" should print around command number <exp>. */
1752 num = (parse_and_eval_long (args) - history_base) - Hist_print / 2;
1753 }
1754 /* "show commands" means print the last Hist_print commands. */
1755 else
1756 {
1757 num = hist_len - Hist_print;
1758 }
1759
1760 if (num < 0)
1761 num = 0;
1762
1763 /* If there are at least Hist_print commands, we want to display the last
1764 Hist_print rather than, say, the last 6. */
1765 if (hist_len - num < Hist_print)
1766 {
1767 num = hist_len - Hist_print;
1768 if (num < 0)
1769 num = 0;
1770 }
1771
1772 for (offset = num; offset < num + Hist_print && offset < hist_len; offset++)
1773 {
1774 printf_filtered ("%5d %s\n", history_base + offset,
1775 (history_get (history_base + offset))->line);
1776 }
1777
1778 /* The next command we want to display is the next one that we haven't
1779 displayed yet. */
1780 num += Hist_print;
1781
1782 /* If the user repeats this command with return, it should do what
1783 "show commands +" does. This is unnecessary if arg is null,
1784 because "show commands +" is not useful after "show commands". */
1785 if (from_tty && args)
1786 {
1787 args[0] = '+';
1788 args[1] = '\0';
1789 }
1790 }
1791
1792 /* Called by do_setshow_command. */
1793 /* ARGSUSED */
1794 static void
1795 set_history_size_command (char *args, int from_tty, struct cmd_list_element *c)
1796 {
1797 if (history_size == INT_MAX)
1798 unstifle_history ();
1799 else if (history_size >= 0)
1800 stifle_history (history_size);
1801 else
1802 {
1803 history_size = INT_MAX;
1804 error ("History size must be non-negative");
1805 }
1806 }
1807
1808 /* ARGSUSED */
1809 void
1810 set_history (char *args, int from_tty)
1811 {
1812 printf_unfiltered ("\"set history\" must be followed by the name of a history subcommand.\n");
1813 help_list (sethistlist, "set history ", -1, gdb_stdout);
1814 }
1815
1816 /* ARGSUSED */
1817 void
1818 show_history (char *args, int from_tty)
1819 {
1820 cmd_show_list (showhistlist, from_tty, "");
1821 }
1822
1823 int info_verbose = 0; /* Default verbose msgs off */
1824
1825 /* Called by do_setshow_command. An elaborate joke. */
1826 /* ARGSUSED */
1827 void
1828 set_verbose (char *args, int from_tty, struct cmd_list_element *c)
1829 {
1830 char *cmdname = "verbose";
1831 struct cmd_list_element *showcmd;
1832
1833 showcmd = lookup_cmd_1 (&cmdname, showlist, NULL, 1);
1834
1835 if (info_verbose)
1836 {
1837 c->doc = "Set verbose printing of informational messages.";
1838 showcmd->doc = "Show verbose printing of informational messages.";
1839 }
1840 else
1841 {
1842 c->doc = "Set verbosity.";
1843 showcmd->doc = "Show verbosity.";
1844 }
1845 }
1846
1847 /* Init the history buffer. Note that we are called after the init file(s)
1848 * have been read so that the user can change the history file via his
1849 * .gdbinit file (for instance). The GDBHISTFILE environment variable
1850 * overrides all of this.
1851 */
1852
1853 void
1854 init_history (void)
1855 {
1856 char *tmpenv;
1857
1858 tmpenv = getenv ("HISTSIZE");
1859 if (tmpenv)
1860 history_size = atoi (tmpenv);
1861 else if (!history_size)
1862 history_size = 256;
1863
1864 stifle_history (history_size);
1865
1866 tmpenv = getenv ("GDBHISTFILE");
1867 if (tmpenv)
1868 history_filename = savestring (tmpenv, strlen (tmpenv));
1869 else if (!history_filename)
1870 {
1871 /* We include the current directory so that if the user changes
1872 directories the file written will be the same as the one
1873 that was read. */
1874 #ifdef __MSDOS__
1875 /* No leading dots in file names are allowed on MSDOS. */
1876 history_filename = concat (current_directory, "/_gdb_history", NULL);
1877 #else
1878 history_filename = concat (current_directory, "/.gdb_history", NULL);
1879 #endif
1880 }
1881 read_history (history_filename);
1882 }
1883
1884 static void
1885 init_main (void)
1886 {
1887 struct cmd_list_element *c;
1888
1889 /* If we are running the asynchronous version,
1890 we initialize the prompts differently. */
1891 if (!event_loop_p)
1892 {
1893 gdb_prompt_string = savestring (DEFAULT_PROMPT, strlen (DEFAULT_PROMPT));
1894 }
1895 else
1896 {
1897 /* initialize the prompt stack to a simple "(gdb) " prompt or to
1898 whatever the DEFAULT_PROMPT is. */
1899 the_prompts.top = 0;
1900 PREFIX (0) = "";
1901 PROMPT (0) = savestring (DEFAULT_PROMPT, strlen (DEFAULT_PROMPT));
1902 SUFFIX (0) = "";
1903 /* Set things up for annotation_level > 1, if the user ever decides
1904 to use it. */
1905 async_annotation_suffix = "prompt";
1906 /* Set the variable associated with the setshow prompt command. */
1907 new_async_prompt = savestring (PROMPT (0), strlen (PROMPT (0)));
1908
1909 /* If gdb was started with --annotate=2, this is equivalent to
1910 the user entering the command 'set annotate 2' at the gdb
1911 prompt, so we need to do extra processing. */
1912 if (annotation_level > 1)
1913 set_async_annotation_level (NULL, 0, NULL);
1914 }
1915 gdb_prompt_escape = 0; /* default to none. */
1916
1917 /* Set the important stuff up for command editing. */
1918 command_editing_p = 1;
1919 history_expansion_p = 0;
1920 write_history_p = 0;
1921
1922 /* Setup important stuff for command line editing. */
1923 rl_completion_entry_function = (int (*)()) readline_line_completion_function;
1924 rl_completer_word_break_characters =
1925 get_gdb_completer_word_break_characters ();
1926 rl_completer_quote_characters = get_gdb_completer_quote_characters ();
1927 rl_readline_name = "gdb";
1928
1929 /* The name for this defun comes from Bash, where it originated.
1930 15 is Control-o, the same binding this function has in Bash. */
1931 rl_add_defun ("operate-and-get-next", gdb_rl_operate_and_get_next, 15);
1932
1933 /* The set prompt command is different depending whether or not the
1934 async version is run. NOTE: this difference is going to
1935 disappear as we make the event loop be the default engine of
1936 gdb. */
1937 if (!event_loop_p)
1938 {
1939 add_show_from_set
1940 (add_set_cmd ("prompt", class_support, var_string,
1941 (char *) &gdb_prompt_string, "Set gdb's prompt",
1942 &setlist),
1943 &showlist);
1944 }
1945 else
1946 {
1947 c = add_set_cmd ("prompt", class_support, var_string,
1948 (char *) &new_async_prompt, "Set gdb's prompt",
1949 &setlist);
1950 add_show_from_set (c, &showlist);
1951 c->function.sfunc = set_async_prompt;
1952 }
1953
1954 add_show_from_set
1955 (add_set_cmd ("prompt-escape-char", class_support, var_zinteger,
1956 (char *) &gdb_prompt_escape,
1957 "Set escape character for formatting of gdb's prompt",
1958 &setlist),
1959 &showlist);
1960
1961 add_com ("dont-repeat", class_support, dont_repeat_command, "Don't repeat this command.\n\
1962 Primarily used inside of user-defined commands that should not be repeated when\n\
1963 hitting return.");
1964
1965 /* The set editing command is different depending whether or not the
1966 async version is run. NOTE: this difference is going to disappear
1967 as we make the event loop be the default engine of gdb. */
1968 if (!event_loop_p)
1969 {
1970 add_show_from_set
1971 (add_set_cmd ("editing", class_support, var_boolean, (char *) &command_editing_p,
1972 "Set editing of command lines as they are typed.\n\
1973 Use \"on\" to enable the editing, and \"off\" to disable it.\n\
1974 Without an argument, command line editing is enabled. To edit, use\n\
1975 EMACS-like or VI-like commands like control-P or ESC.", &setlist),
1976 &showlist);
1977 }
1978 else
1979 {
1980 c = add_set_cmd ("editing", class_support, var_boolean, (char *) &async_command_editing_p,
1981 "Set editing of command lines as they are typed.\n\
1982 Use \"on\" to enable the editing, and \"off\" to disable it.\n\
1983 Without an argument, command line editing is enabled. To edit, use\n\
1984 EMACS-like or VI-like commands like control-P or ESC.", &setlist);
1985
1986 add_show_from_set (c, &showlist);
1987 c->function.sfunc = set_async_editing_command;
1988 }
1989
1990 add_show_from_set
1991 (add_set_cmd ("save", no_class, var_boolean, (char *) &write_history_p,
1992 "Set saving of the history record on exit.\n\
1993 Use \"on\" to enable the saving, and \"off\" to disable it.\n\
1994 Without an argument, saving is enabled.", &sethistlist),
1995 &showhistlist);
1996
1997 c = add_set_cmd ("size", no_class, var_integer, (char *) &history_size,
1998 "Set the size of the command history, \n\
1999 ie. the number of previous commands to keep a record of.", &sethistlist);
2000 add_show_from_set (c, &showhistlist);
2001 c->function.sfunc = set_history_size_command;
2002
2003 c = add_set_cmd ("filename", no_class, var_filename,
2004 (char *) &history_filename,
2005 "Set the filename in which to record the command history\n\
2006 (the list of previous commands of which a record is kept).", &sethistlist);
2007 c->completer = filename_completer;
2008 add_show_from_set (c, &showhistlist);
2009
2010 add_show_from_set
2011 (add_set_cmd ("confirm", class_support, var_boolean,
2012 (char *) &caution,
2013 "Set whether to confirm potentially dangerous operations.",
2014 &setlist),
2015 &showlist);
2016
2017 /* The set annotate command is different depending whether or not
2018 the async version is run. NOTE: this difference is going to
2019 disappear as we make the event loop be the default engine of
2020 gdb. */
2021 if (!event_loop_p)
2022 {
2023 c = add_set_cmd ("annotate", class_obscure, var_zinteger,
2024 (char *) &annotation_level, "Set annotation_level.\n\
2025 0 == normal; 1 == fullname (for use when running under emacs)\n\
2026 2 == output annotated suitably for use by programs that control GDB.",
2027 &setlist);
2028 c = add_show_from_set (c, &showlist);
2029 }
2030 else
2031 {
2032 c = add_set_cmd ("annotate", class_obscure, var_zinteger,
2033 (char *) &annotation_level, "Set annotation_level.\n\
2034 0 == normal; 1 == fullname (for use when running under emacs)\n\
2035 2 == output annotated suitably for use by programs that control GDB.",
2036 &setlist);
2037 add_show_from_set (c, &showlist);
2038 c->function.sfunc = set_async_annotation_level;
2039 }
2040 if (event_loop_p)
2041 {
2042 add_show_from_set
2043 (add_set_cmd ("exec-done-display", class_support, var_boolean, (char *) &exec_done_display_p,
2044 "Set notification of completion for asynchronous execution commands.\n\
2045 Use \"on\" to enable the notification, and \"off\" to disable it.", &setlist),
2046 &showlist);
2047 }
2048 }
2049
2050 void
2051 gdb_init (char *argv0)
2052 {
2053 if (pre_init_ui_hook)
2054 pre_init_ui_hook ();
2055
2056 /* Run the init function of each source file */
2057
2058 getcwd (gdb_dirbuf, sizeof (gdb_dirbuf));
2059 current_directory = gdb_dirbuf;
2060
2061 #ifdef __MSDOS__
2062 /* Make sure we return to the original directory upon exit, come
2063 what may, since the OS doesn't do that for us. */
2064 make_final_cleanup (do_chdir_cleanup, xstrdup (current_directory));
2065 #endif
2066
2067 init_cmd_lists (); /* This needs to be done first */
2068 initialize_targets (); /* Setup target_terminal macros for utils.c */
2069 initialize_utils (); /* Make errors and warnings possible */
2070 initialize_all_files ();
2071 initialize_current_architecture ();
2072 init_cli_cmds();
2073 init_main (); /* But that omits this file! Do it now */
2074
2075 /* The signal handling mechanism is different depending whether or
2076 not the async version is run. NOTE: in the future we plan to make
2077 the event loop be the default engine of gdb, and this difference
2078 will disappear. */
2079 if (event_loop_p)
2080 async_init_signals ();
2081 else
2082 init_signals ();
2083
2084 /* We need a default language for parsing expressions, so simple things like
2085 "set width 0" won't fail if no language is explicitly set in a config file
2086 or implicitly set by reading an executable during startup. */
2087 set_language (language_c);
2088 expected_language = current_language; /* don't warn about the change. */
2089
2090 /* Allow another UI to initialize. If the UI fails to initialize, and
2091 it wants GDB to revert to the CLI, it should clear init_ui_hook. */
2092 if (init_ui_hook)
2093 init_ui_hook (argv0);
2094
2095 #ifdef UI_OUT
2096 /* Install the default UI */
2097 if (!init_ui_hook)
2098 {
2099 uiout = cli_out_new (gdb_stdout);
2100
2101 /* All the interpreters should have had a look at things by now.
2102 Initialize the selected interpreter. */
2103 if (interpreter_p)
2104 {
2105 fprintf_unfiltered (gdb_stderr, "Interpreter `%s' unrecognized.\n",
2106 interpreter_p);
2107 exit (1);
2108 }
2109 }
2110 #endif
2111 }
This page took 0.07142 seconds and 4 git commands to generate.