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