import gdb-1999-08-30 snapshot
[external/binutils.git] / gdb / main.c
1 /* Top level stuff for GDB, the GNU debugger.
2    Copyright 1986, 87, 88, 89, 90, 91, 92, 93, 94, 95, 1999
3    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 "top.h"
24 #include "target.h"
25 #include "inferior.h"
26 #include "call-cmds.h"
27
28 #include "getopt.h"
29
30 #include <sys/types.h>
31 #include "gdb_stat.h"
32 #include <ctype.h>
33
34 #include "gdb_string.h"
35 #include "event-loop.h"
36
37 /* If nonzero, display time usage both at startup and for each command.  */
38
39 int display_time;
40
41 /* If nonzero, display space usage both at startup and for each command.  */
42
43 int display_space;
44
45 /* Whether this is the async version or not.  The async version is
46    invoked on the command line with the -nw --async options.  In this
47    version, the usual command_loop is substituted by and event loop which
48    processes UI events asynchronously. */
49 int async_p = 1;
50
51 /* Whether this is the command line version or not */
52 int tui_version = 0;
53
54 /* Whether xdb commands will be handled */
55 int xdb_commands = 0;
56
57 /* Whether dbx commands will be handled */
58 int dbx_commands = 0;
59
60 GDB_FILE *gdb_stdout;
61 GDB_FILE *gdb_stderr;
62 GDB_FILE *gdb_stdlog;
63 GDB_FILE *gdb_stdtarg;
64
65 /* Whether to enable writing into executable and core files */
66 extern int write_files;
67
68 static void print_gdb_help PARAMS ((GDB_FILE *));
69
70 /* These two are used to set the external editor commands when gdb is farming
71    out files to be edited by another program. */
72
73 extern int enable_external_editor;
74 extern char *external_editor_command;
75
76 #ifdef __CYGWIN__
77 #include <windows.h>            /* for MAX_PATH */
78 #include <sys/cygwin.h>         /* for cygwin32_conv_to_posix_path */
79 #endif
80
81 int
82 main (argc, argv)
83      int argc;
84      char **argv;
85 {
86   int count;
87   static int quiet = 0;
88   static int batch = 0;
89
90   /* Pointers to various arguments from command line.  */
91   char *symarg = NULL;
92   char *execarg = NULL;
93   char *corearg = NULL;
94   char *cdarg = NULL;
95   char *ttyarg = NULL;
96
97   /* These are static so that we can take their address in an initializer.  */
98   static int print_help;
99   static int print_version;
100
101   /* Pointers to all arguments of --command option.  */
102   char **cmdarg;
103   /* Allocated size of cmdarg.  */
104   int cmdsize;
105   /* Number of elements of cmdarg used.  */
106   int ncmd;
107
108   /* Indices of all arguments of --directory option.  */
109   char **dirarg;
110   /* Allocated size.  */
111   int dirsize;
112   /* Number of elements used.  */
113   int ndir;
114
115   struct stat homebuf, cwdbuf;
116   char *homedir, *homeinit;
117
118   register int i;
119
120   long time_at_startup = get_run_time ();
121
122   int gdb_file_size;
123
124   START_PROGRESS (argv[0], 0);
125
126 #ifdef MPW
127   /* Do all Mac-specific setup. */
128   mac_init ();
129 #endif /* MPW */
130
131   /* This needs to happen before the first use of malloc.  */
132   init_malloc ((PTR) NULL);
133
134 #if defined (ALIGN_STACK_ON_STARTUP)
135   i = (int) &count & 0x3;
136   if (i != 0)
137     alloca (4 - i);
138 #endif
139
140   /* If error() is called from initialization code, just exit */
141   if (SET_TOP_LEVEL ())
142     {
143       exit (1);
144     }
145
146   cmdsize = 1;
147   cmdarg = (char **) xmalloc (cmdsize * sizeof (*cmdarg));
148   ncmd = 0;
149   dirsize = 1;
150   dirarg = (char **) xmalloc (dirsize * sizeof (*dirarg));
151   ndir = 0;
152
153   quit_flag = 0;
154   line = (char *) xmalloc (linesize);
155   line[0] = '\0';               /* Terminate saved (now empty) cmd line */
156   instream = stdin;
157
158   getcwd (gdb_dirbuf, sizeof (gdb_dirbuf));
159   current_directory = gdb_dirbuf;
160
161 #if 0
162   /* not yet */
163   gdb_stdout = stdio_fileopen (stdout);
164   gdb_stderr = stdio_fileopen (stderr);
165   gdb_stdlog = gdb_stderr;      /* for moment */
166   gdb_stdtarg = gdb_stderr;     /* for moment */
167 #else
168   gdb_stdout = tui_fileopen (stdout);
169   gdb_stderr = tui_fileopen (stderr);
170   gdb_stdlog = gdb_stdout;      /* for moment */
171   gdb_stdtarg = gdb_stderr;     /* for moment */
172 #endif
173
174   /* Parse arguments and options.  */
175   {
176     int c;
177     /* When var field is 0, use flag field to record the equivalent
178        short option (or arbitrary numbers starting at 10 for those
179        with no equivalent).  */
180     static struct option long_options[] =
181     {
182       {"async", no_argument, &async_p, 1},
183       {"noasync", no_argument, &async_p, 0},
184 #if defined(TUI)
185       {"tui", no_argument, &tui_version, 1},
186 #endif
187       {"xdb", no_argument, &xdb_commands, 1},
188       {"dbx", no_argument, &dbx_commands, 1},
189       {"readnow", no_argument, &readnow_symbol_files, 1},
190       {"r", no_argument, &readnow_symbol_files, 1},
191       {"mapped", no_argument, &mapped_symbol_files, 1},
192       {"m", no_argument, &mapped_symbol_files, 1},
193       {"quiet", no_argument, &quiet, 1},
194       {"q", no_argument, &quiet, 1},
195       {"silent", no_argument, &quiet, 1},
196       {"nx", no_argument, &inhibit_gdbinit, 1},
197       {"n", no_argument, &inhibit_gdbinit, 1},
198       {"batch", no_argument, &batch, 1},
199       {"epoch", no_argument, &epoch_interface, 1},
200
201     /* This is a synonym for "--annotate=1".  --annotate is now preferred,
202        but keep this here for a long time because people will be running
203        emacses which use --fullname.  */
204       {"fullname", no_argument, 0, 'f'},
205       {"f", no_argument, 0, 'f'},
206
207       {"annotate", required_argument, 0, 12},
208       {"help", no_argument, &print_help, 1},
209       {"se", required_argument, 0, 10},
210       {"symbols", required_argument, 0, 's'},
211       {"s", required_argument, 0, 's'},
212       {"exec", required_argument, 0, 'e'},
213       {"e", required_argument, 0, 'e'},
214       {"core", required_argument, 0, 'c'},
215       {"c", required_argument, 0, 'c'},
216       {"command", required_argument, 0, 'x'},
217       {"version", no_argument, &print_version, 1},
218       {"x", required_argument, 0, 'x'},
219       {"directory", required_argument, 0, 'd'},
220       {"cd", required_argument, 0, 11},
221       {"tty", required_argument, 0, 't'},
222       {"baud", required_argument, 0, 'b'},
223       {"b", required_argument, 0, 'b'},
224       {"nw", no_argument, &use_windows, 0},
225       {"nowindows", no_argument, &use_windows, 0},
226       {"w", no_argument, &use_windows, 1},
227       {"windows", no_argument, &use_windows, 1},
228       {"statistics", no_argument, 0, 13},
229       {"write", no_argument, &write_files, 1},
230 /* Allow machine descriptions to add more options... */
231 #ifdef ADDITIONAL_OPTIONS
232       ADDITIONAL_OPTIONS
233 #endif
234       {0, no_argument, 0, 0}
235     };
236
237     while (1)
238       {
239         int option_index;
240
241         c = getopt_long_only (argc, argv, "",
242                               long_options, &option_index);
243         if (c == EOF)
244           break;
245
246         /* Long option that takes an argument.  */
247         if (c == 0 && long_options[option_index].flag == 0)
248           c = long_options[option_index].val;
249
250         switch (c)
251           {
252           case 0:
253             /* Long option that just sets a flag.  */
254             break;
255           case 10:
256             symarg = optarg;
257             execarg = optarg;
258             break;
259           case 11:
260             cdarg = optarg;
261             break;
262           case 12:
263             /* FIXME: what if the syntax is wrong (e.g. not digits)?  */
264             annotation_level = atoi (optarg);
265             break;
266           case 13:
267             /* Enable the display of both time and space usage.  */
268             display_time = 1;
269             display_space = 1;
270             break;
271           case 'f':
272             annotation_level = 1;
273 /* We have probably been invoked from emacs.  Disable window interface.  */
274             use_windows = 0;
275             break;
276           case 's':
277             symarg = optarg;
278             break;
279           case 'e':
280             execarg = optarg;
281             break;
282           case 'c':
283             corearg = optarg;
284             break;
285           case 'x':
286             cmdarg[ncmd++] = optarg;
287             if (ncmd >= cmdsize)
288               {
289                 cmdsize *= 2;
290                 cmdarg = (char **) xrealloc ((char *) cmdarg,
291                                              cmdsize * sizeof (*cmdarg));
292               }
293             break;
294           case 'd':
295             dirarg[ndir++] = optarg;
296             if (ndir >= dirsize)
297               {
298                 dirsize *= 2;
299                 dirarg = (char **) xrealloc ((char *) dirarg,
300                                              dirsize * sizeof (*dirarg));
301               }
302             break;
303           case 't':
304             ttyarg = optarg;
305             break;
306           case 'q':
307             quiet = 1;
308             break;
309           case 'b':
310             {
311               int i;
312               char *p;
313
314               i = strtol (optarg, &p, 0);
315               if (i == 0 && p == optarg)
316
317                 /* Don't use *_filtered or warning() (which relies on
318                    current_target) until after initialize_all_files(). */
319
320                 fprintf_unfiltered
321                   (gdb_stderr,
322                    "warning: could not set baud rate to `%s'.\n", optarg);
323               else
324                 baud_rate = i;
325             }
326           case 'l':
327             {
328               int i;
329               char *p;
330
331               i = strtol (optarg, &p, 0);
332               if (i == 0 && p == optarg)
333
334                 /* Don't use *_filtered or warning() (which relies on
335                    current_target) until after initialize_all_files(). */
336
337                 fprintf_unfiltered
338                   (gdb_stderr,
339                  "warning: could not set timeout limit to `%s'.\n", optarg);
340               else
341                 remote_timeout = i;
342             }
343             break;
344
345 #ifdef ADDITIONAL_OPTION_CASES
346             ADDITIONAL_OPTION_CASES
347 #endif
348           case '?':
349             fprintf_unfiltered (gdb_stderr,
350                         "Use `%s --help' for a complete list of options.\n",
351                                 argv[0]);
352             exit (1);
353           }
354       }
355
356     /* If --help or --version, disable window interface.  */
357     if (print_help || print_version)
358       {
359         use_windows = 0;
360 #ifdef TUI
361         /* Disable the TUI as well.  */
362         tui_version = 0;
363 #endif
364       }
365
366 #ifdef TUI
367     /* An explicit --tui flag overrides the default UI, which is the
368        window system.  */
369     if (tui_version)
370       use_windows = 0;
371 #endif
372
373     /* OK, that's all the options.  The other arguments are filenames.  */
374     count = 0;
375     for (; optind < argc; optind++)
376       switch (++count)
377         {
378         case 1:
379           symarg = argv[optind];
380           execarg = argv[optind];
381           break;
382         case 2:
383           corearg = argv[optind];
384           break;
385         case 3:
386           fprintf_unfiltered (gdb_stderr,
387                           "Excess command line arguments ignored. (%s%s)\n",
388                           argv[optind], (optind == argc - 1) ? "" : " ...");
389           break;
390         }
391     if (batch)
392       quiet = 1;
393   }
394
395 #if defined(TUI)
396   /* Should this be moved to tui-top.c:_initialize_tui()? */
397   if (tui_version)
398     init_ui_hook = tuiInit;
399 #endif
400
401   /* Initialize all files.  Give the interpreter a chance to take
402      control of the console via the init_ui_hook()) */
403   gdb_init (argv[0]);
404
405   /* Do these (and anything which might call wrap_here or *_filtered)
406      after initialize_all_files.  */
407   if (print_version)
408     {
409       print_gdb_version (gdb_stdout);
410       wrap_here ("");
411       printf_filtered ("\n");
412       exit (0);
413     }
414
415   if (print_help)
416     {
417       print_gdb_help (gdb_stdout);
418       fputs_unfiltered ("\n", gdb_stdout);
419       exit (0);
420     }
421
422   if (!quiet)
423     {
424       /* Print all the junk at the top, with trailing "..." if we are about
425          to read a symbol file (possibly slowly).  */
426       print_gdb_version (gdb_stdout);
427       if (symarg)
428         printf_filtered ("..");
429       wrap_here ("");
430       gdb_flush (gdb_stdout);   /* Force to screen during slow operations */
431     }
432
433   error_pre_print = "\n\n";
434   quit_pre_print = error_pre_print;
435
436   /* We may get more than one warning, don't double space all of them... */
437   warning_pre_print = "\nwarning: ";
438
439   /* Read and execute $HOME/.gdbinit file, if it exists.  This is done
440      *before* all the command line arguments are processed; it sets
441      global parameters, which are independent of what file you are
442      debugging or what directory you are in.  */
443 #ifdef __CYGWIN32__
444   {
445     char *tmp = getenv ("HOME");
446
447     if (tmp != NULL)
448       {
449         homedir = (char *) alloca (MAX_PATH + 1);
450         cygwin32_conv_to_posix_path (tmp, homedir);
451       }
452     else
453       homedir = NULL;
454   }
455 #else
456   homedir = getenv ("HOME");
457 #endif
458   if (homedir)
459     {
460       homeinit = (char *) alloca (strlen (homedir) +
461                                   strlen (gdbinit) + 10);
462       strcpy (homeinit, homedir);
463       strcat (homeinit, "/");
464       strcat (homeinit, gdbinit);
465
466       if (!inhibit_gdbinit)
467         {
468           if (!SET_TOP_LEVEL ())
469             source_command (homeinit, 0);
470         }
471       do_cleanups (ALL_CLEANUPS);
472
473       /* Do stats; no need to do them elsewhere since we'll only
474          need them if homedir is set.  Make sure that they are
475          zero in case one of them fails (this guarantees that they
476          won't match if either exists).  */
477
478       memset (&homebuf, 0, sizeof (struct stat));
479       memset (&cwdbuf, 0, sizeof (struct stat));
480
481       stat (homeinit, &homebuf);
482       stat (gdbinit, &cwdbuf);  /* We'll only need this if
483                                    homedir was set.  */
484     }
485
486   /* Now perform all the actions indicated by the arguments.  */
487   if (cdarg != NULL)
488     {
489       if (!SET_TOP_LEVEL ())
490         {
491           cd_command (cdarg, 0);
492         }
493     }
494   do_cleanups (ALL_CLEANUPS);
495
496   for (i = 0; i < ndir; i++)
497     if (!SET_TOP_LEVEL ())
498       directory_command (dirarg[i], 0);
499   free ((PTR) dirarg);
500   do_cleanups (ALL_CLEANUPS);
501
502   if (execarg != NULL
503       && symarg != NULL
504       && STREQ (execarg, symarg))
505     {
506       /* The exec file and the symbol-file are the same.  If we can't open
507          it, better only print one error message.  */
508       if (!SET_TOP_LEVEL ())
509         {
510           exec_file_command (execarg, !batch);
511           symbol_file_command (symarg, 0);
512         }
513     }
514   else
515     {
516       if (execarg != NULL)
517         if (!SET_TOP_LEVEL ())
518           exec_file_command (execarg, !batch);
519       if (symarg != NULL)
520         if (!SET_TOP_LEVEL ())
521           symbol_file_command (symarg, 0);
522     }
523   do_cleanups (ALL_CLEANUPS);
524
525   /* After the symbol file has been read, print a newline to get us
526      beyond the copyright line...  But errors should still set off
527      the error message with a (single) blank line.  */
528   if (!quiet)
529     printf_filtered ("\n");
530   error_pre_print = "\n";
531   quit_pre_print = error_pre_print;
532   warning_pre_print = "\nwarning: ";
533
534   if (corearg != NULL)
535     {
536       if (!SET_TOP_LEVEL ())
537         core_file_command (corearg, !batch);
538       else if (isdigit (corearg[0]) && !SET_TOP_LEVEL ())
539         attach_command (corearg, !batch);
540     }
541   do_cleanups (ALL_CLEANUPS);
542
543   if (ttyarg != NULL)
544     if (!SET_TOP_LEVEL ())
545       tty_command (ttyarg, !batch);
546   do_cleanups (ALL_CLEANUPS);
547
548 #ifdef ADDITIONAL_OPTION_HANDLER
549   ADDITIONAL_OPTION_HANDLER;
550 #endif
551
552   /* Error messages should no longer be distinguished with extra output. */
553   error_pre_print = NULL;
554   quit_pre_print = NULL;
555   warning_pre_print = "warning: ";
556
557   /* Read the .gdbinit file in the current directory, *if* it isn't
558      the same as the $HOME/.gdbinit file (it should exist, also).  */
559
560   if (!homedir
561       || memcmp ((char *) &homebuf, (char *) &cwdbuf, sizeof (struct stat)))
562     if (!inhibit_gdbinit)
563       {
564         if (!SET_TOP_LEVEL ())
565           source_command (gdbinit, 0);
566       }
567   do_cleanups (ALL_CLEANUPS);
568
569   for (i = 0; i < ncmd; i++)
570     {
571       if (!SET_TOP_LEVEL ())
572         {
573           /* NOTE: I am commenting this out, because it is not clear
574              where this feature is used. It is very old and
575              undocumented. ezannoni: 1999-05-04 */
576 #if 0
577           if (cmdarg[i][0] == '-' && cmdarg[i][1] == '\0')
578             read_command_file (stdin);
579           else
580 #endif
581             source_command (cmdarg[i], !batch);
582           do_cleanups (ALL_CLEANUPS);
583         }
584     }
585   free ((PTR) cmdarg);
586
587   /* Read in the old history after all the command files have been read. */
588   init_history ();
589
590   if (batch)
591     {
592       /* We have hit the end of the batch file.  */
593       exit (0);
594     }
595
596   /* Do any host- or target-specific hacks.  This is used for i960 targets
597      to force the user to set a nindy target and spec its parameters.  */
598
599 #ifdef BEFORE_MAIN_LOOP_HOOK
600   BEFORE_MAIN_LOOP_HOOK;
601 #endif
602
603   END_PROGRESS (argv[0]);
604
605   /* Show time and/or space usage.  */
606
607   if (display_time)
608     {
609       long init_time = get_run_time () - time_at_startup;
610
611       printf_unfiltered ("Startup time: %ld.%06ld\n",
612                          init_time / 1000000, init_time % 1000000);
613     }
614
615   if (display_space)
616     {
617 #ifdef HAVE_SBRK
618       extern char **environ;
619       char *lim = (char *) sbrk (0);
620
621       printf_unfiltered ("Startup size: data size %ld\n",
622                          (long) (lim - (char *) &environ));
623 #endif
624     }
625
626   /* The default command loop. 
627      The WIN32 Gui calls this main to set up gdb's state, and 
628      has its own command loop. */
629 #if !defined _WIN32 || defined __GNUC__
630   while (1)
631     {
632       if (!SET_TOP_LEVEL ())
633         {
634           do_cleanups (ALL_CLEANUPS);   /* Do complete cleanup */
635           /* GUIs generally have their own command loop, mainloop, or whatever.
636              This is a good place to gain control because many error
637              conditions will end up here via longjmp(). */
638           if (command_loop_hook)
639             command_loop_hook ();
640           else
641             command_loop ();
642           quit_command ((char *) 0, instream == stdin);
643         }
644     }
645   /* No exit -- exit is through quit_command.  */
646 #endif
647
648 }
649
650 /* Don't use *_filtered for printing help.  We don't want to prompt
651    for continue no matter how small the screen or how much we're going
652    to print.  */
653
654 static void
655 print_gdb_help (stream)
656      GDB_FILE *stream;
657 {
658   fputs_unfiltered ("\
659 This is the GNU debugger.  Usage:\n\n\
660     gdb [options] [executable-file [core-file or process-id]]\n\n\
661 Options:\n\n\
662 ", stream);
663   fputs_unfiltered ("\
664   --[no]async        Enable (disable) asynchronous version of CLI\n\
665 ", stream);
666   fputs_unfiltered ("\
667   -b BAUDRATE        Set serial port baud rate used for remote debugging.\n\
668   --batch            Exit after processing options.\n\
669   --cd=DIR           Change current directory to DIR.\n\
670   --command=FILE     Execute GDB commands from FILE.\n\
671   --core=COREFILE    Analyze the core dump COREFILE.\n\
672 ", stream);
673   fputs_unfiltered ("\
674   --dbx              DBX compatibility mode.\n\
675   --directory=DIR    Search for source files in DIR.\n\
676   --epoch            Output information used by epoch emacs-GDB interface.\n\
677   --exec=EXECFILE    Use EXECFILE as the executable.\n\
678   --fullname         Output information used by emacs-GDB interface.\n\
679   --help             Print this message.\n\
680 ", stream);
681   fputs_unfiltered ("\
682   --mapped           Use mapped symbol files if supported on this system.\n\
683   --nw               Do not use a window interface.\n\
684   --nx               Do not read ", stream);
685   fputs_unfiltered (gdbinit, stream);
686   fputs_unfiltered (" file.\n\
687   --quiet            Do not print version number on startup.\n\
688   --readnow          Fully read symbol files on first access.\n\
689 ", stream);
690   fputs_unfiltered ("\
691   --se=FILE          Use FILE as symbol file and executable file.\n\
692   --symbols=SYMFILE  Read symbols from SYMFILE.\n\
693   --tty=TTY          Use TTY for input/output by the program being debugged.\n\
694 ", stream);
695 #if defined(TUI)
696   fputs_unfiltered ("\
697   --tui              Use a terminal user interface.\n\
698 ", stream);
699 #endif
700   fputs_unfiltered ("\
701   --version          Print version information and then exit.\n\
702   -w                 Use a window interface.\n\
703   --write            Set writing into executable and core files.\n\
704   --xdb              XDB compatibility mode.\n\
705 ", stream);
706 #ifdef ADDITIONAL_OPTION_HELP
707   fputs_unfiltered (ADDITIONAL_OPTION_HELP, stream);
708 #endif
709   fputs_unfiltered ("\n\
710 For more information, type \"help\" from within GDB, or consult the\n\
711 GDB manual (available as on-line info or a printed manual).\n\
712 Report bugs to \"bug-gdb@prep.ai.mit.edu\".\
713 ", stream);
714 }