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