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