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