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