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