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