1/* List lines of source files for GDB, the GNU debugger.
2   Copyright (C) 1986, 1987, 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995,
3   1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2007
4   Free Software Foundation, Inc.
5
6   This file is part of GDB.
7
8   This program is free software; you can redistribute it and/or modify
9   it under the terms of the GNU General Public License as published by
10   the Free Software Foundation; either version 3 of the License, or
11   (at your option) any later version.
12
13   This program is distributed in the hope that it will be useful,
14   but WITHOUT ANY WARRANTY; without even the implied warranty of
15   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16   GNU General Public License for more details.
17
18   You should have received a copy of the GNU General Public License
19   along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
20
21#include "defs.h"
22#include "symtab.h"
23#include "expression.h"
24#include "language.h"
25#include "command.h"
26#include "source.h"
27#include "gdbcmd.h"
28#include "frame.h"
29#include "value.h"
30#include "gdb_assert.h"
31
32#include <sys/types.h>
33#include "gdb_string.h"
34#include "gdb_stat.h"
35#include <fcntl.h>
36#include "gdbcore.h"
37#include "gdb_regex.h"
38#include "symfile.h"
39#include "objfiles.h"
40#include "annotate.h"
41#include "gdbtypes.h"
42#include "linespec.h"
43#include "filenames.h"		/* for DOSish file names */
44#include "completer.h"
45#include "ui-out.h"
46#include "readline/readline.h"
47
48
49#define OPEN_MODE (O_RDONLY | O_BINARY)
50#define FDOPEN_MODE FOPEN_RB
51
52/* Prototypes for exported functions. */
53
54void _initialize_source (void);
55
56/* Prototypes for local functions. */
57
58static int get_filename_and_charpos (struct symtab *, char **);
59
60static void reverse_search_command (char *, int);
61
62static void forward_search_command (char *, int);
63
64static void line_info (char *, int);
65
66static void source_info (char *, int);
67
68static void show_directories (char *, int);
69
70/* Path of directories to search for source files.
71   Same format as the PATH environment variable's value.  */
72
73char *source_path;
74
75/* Support for source path substitution commands.  */
76
77struct substitute_path_rule
78{
79  char *from;
80  char *to;
81  struct substitute_path_rule *next;
82};
83
84static struct substitute_path_rule *substitute_path_rules = NULL;
85
86/* Symtab of default file for listing lines of.  */
87
88static struct symtab *current_source_symtab;
89
90/* Default next line to list.  */
91
92static int current_source_line;
93
94/* Default number of lines to print with commands like "list".
95   This is based on guessing how many long (i.e. more than chars_per_line
96   characters) lines there will be.  To be completely correct, "list"
97   and friends should be rewritten to count characters and see where
98   things are wrapping, but that would be a fair amount of work.  */
99
100int lines_to_list = 10;
101static void
102show_lines_to_list (struct ui_file *file, int from_tty,
103		    struct cmd_list_element *c, const char *value)
104{
105  fprintf_filtered (file, _("\
106Number of source lines gdb will list by default is %s.\n"),
107		    value);
108}
109
110/* Line number of last line printed.  Default for various commands.
111   current_source_line is usually, but not always, the same as this.  */
112
113static int last_line_listed;
114
115/* First line number listed by last listing command.  */
116
117static int first_line_listed;
118
119/* Saves the name of the last source file visited and a possible error code.
120   Used to prevent repeating annoying "No such file or directories" msgs */
121
122static struct symtab *last_source_visited = NULL;
123static int last_source_error = 0;
124
125/* Return the first line listed by print_source_lines.
126   Used by command interpreters to request listing from
127   a previous point. */
128
129int
130get_first_line_listed (void)
131{
132  return first_line_listed;
133}
134
135/* Return the default number of lines to print with commands like the
136   cli "list".  The caller of print_source_lines must use this to
137   calculate the end line and use it in the call to print_source_lines
138   as it does not automatically use this value. */
139
140int
141get_lines_to_list (void)
142{
143  return lines_to_list;
144}
145
146/* Return the current source file for listing and next line to list.
147   NOTE: The returned sal pc and end fields are not valid. */
148
149struct symtab_and_line
150get_current_source_symtab_and_line (void)
151{
152  struct symtab_and_line cursal = { 0 };
153
154  cursal.symtab = current_source_symtab;
155  cursal.line = current_source_line;
156  cursal.pc = 0;
157  cursal.end = 0;
158
159  return cursal;
160}
161
162/* If the current source file for listing is not set, try and get a default.
163   Usually called before get_current_source_symtab_and_line() is called.
164   It may err out if a default cannot be determined.
165   We must be cautious about where it is called, as it can recurse as the
166   process of determining a new default may call the caller!
167   Use get_current_source_symtab_and_line only to get whatever
168   we have without erroring out or trying to get a default. */
169
170void
171set_default_source_symtab_and_line (void)
172{
173  struct symtab_and_line cursal;
174
175  if (!have_full_symbols () && !have_partial_symbols ())
176    error (_("No symbol table is loaded.  Use the \"file\" command."));
177
178  /* Pull in a current source symtab if necessary */
179  if (current_source_symtab == 0)
180    select_source_symtab (0);
181}
182
183/* Return the current default file for listing and next line to list
184   (the returned sal pc and end fields are not valid.)
185   and set the current default to whatever is in SAL.
186   NOTE: The returned sal pc and end fields are not valid. */
187
188struct symtab_and_line
189set_current_source_symtab_and_line (const struct symtab_and_line *sal)
190{
191  struct symtab_and_line cursal = { 0 };
192
193  cursal.symtab = current_source_symtab;
194  cursal.line = current_source_line;
195
196  current_source_symtab = sal->symtab;
197  current_source_line = sal->line;
198  cursal.pc = 0;
199  cursal.end = 0;
200
201  return cursal;
202}
203
204/* Reset any information stored about a default file and line to print. */
205
206void
207clear_current_source_symtab_and_line (void)
208{
209  current_source_symtab = 0;
210  current_source_line = 0;
211}
212
213/* Set the source file default for the "list" command to be S.
214
215   If S is NULL, and we don't have a default, find one.  This
216   should only be called when the user actually tries to use the
217   default, since we produce an error if we can't find a reasonable
218   default.  Also, since this can cause symbols to be read, doing it
219   before we need to would make things slower than necessary.  */
220
221void
222select_source_symtab (struct symtab *s)
223{
224  struct symtabs_and_lines sals;
225  struct symtab_and_line sal;
226  struct partial_symtab *ps;
227  struct partial_symtab *cs_pst = 0;
228  struct objfile *ofp;
229
230  if (s)
231    {
232      current_source_symtab = s;
233      current_source_line = 1;
234      return;
235    }
236
237  if (current_source_symtab)
238    return;
239
240  /* Make the default place to list be the function `main'
241     if one exists.  */
242  if (lookup_symbol (main_name (), 0, VAR_DOMAIN, 0, NULL))
243    {
244      sals = decode_line_spec (main_name (), 1);
245      sal = sals.sals[0];
246      xfree (sals.sals);
247      current_source_symtab = sal.symtab;
248      current_source_line = max (sal.line - (lines_to_list - 1), 1);
249      if (current_source_symtab)
250	return;
251    }
252
253  /* All right; find the last file in the symtab list (ignoring .h's).  */
254
255  current_source_line = 1;
256
257  for (ofp = object_files; ofp != NULL; ofp = ofp->next)
258    {
259      for (s = ofp->symtabs; s; s = s->next)
260	{
261	  const char *name = s->filename;
262	  int len = strlen (name);
263	  if (!(len > 2 && strcmp(&name[len - 2], ".h") == 0))
264	    current_source_symtab = s;
265	}
266    }
267  if (current_source_symtab)
268    return;
269
270  /* Howabout the partial symbol tables? */
271
272  for (ofp = object_files; ofp != NULL; ofp = ofp->next)
273    {
274      for (ps = ofp->psymtabs; ps != NULL; ps = ps->next)
275	{
276	  const char *name = ps->filename;
277	  int len = strlen (name);
278	  if (!(len > 2 && strcmp (&name[len - 2], ".h") == 0))
279	    cs_pst = ps;
280	}
281    }
282  if (cs_pst)
283    {
284      if (cs_pst->readin)
285	{
286	  internal_error (__FILE__, __LINE__,
287			  _("select_source_symtab: "
288			  "readin pst found and no symtabs."));
289	}
290      else
291	{
292	  current_source_symtab = PSYMTAB_TO_SYMTAB (cs_pst);
293	}
294    }
295  if (current_source_symtab)
296    return;
297
298  error (_("Can't find a default source file"));
299}
300
301static void
302show_directories (char *ignore, int from_tty)
303{
304  puts_filtered ("Source directories searched: ");
305  puts_filtered (source_path);
306  puts_filtered ("\n");
307}
308
309/* Forget what we learned about line positions in source files, and
310   which directories contain them; must check again now since files
311   may be found in a different directory now.  */
312
313void
314forget_cached_source_info (void)
315{
316  struct symtab *s;
317  struct objfile *objfile;
318  struct partial_symtab *pst;
319
320  for (objfile = object_files; objfile != NULL; objfile = objfile->next)
321    {
322      for (s = objfile->symtabs; s != NULL; s = s->next)
323	{
324	  if (s->line_charpos != NULL)
325	    {
326	      xfree (s->line_charpos);
327	      s->line_charpos = NULL;
328	    }
329	  if (s->fullname != NULL)
330	    {
331	      xfree (s->fullname);
332	      s->fullname = NULL;
333	    }
334	}
335
336      ALL_OBJFILE_PSYMTABS (objfile, pst)
337      {
338	if (pst->fullname != NULL)
339	  {
340	    xfree (pst->fullname);
341	    pst->fullname = NULL;
342	  }
343      }
344    }
345}
346
347void
348init_source_path (void)
349{
350  char buf[20];
351
352  sprintf (buf, "$cdir%c$cwd", DIRNAME_SEPARATOR);
353  source_path = xstrdup (buf);
354  forget_cached_source_info ();
355}
356
357void
358init_last_source_visited (void)
359{
360  last_source_visited = NULL;
361}
362
363/* Add zero or more directories to the front of the source path.  */
364
365void
366directory_command (char *dirname, int from_tty)
367{
368  dont_repeat ();
369  /* FIXME, this goes to "delete dir"... */
370  if (dirname == 0)
371    {
372      if (from_tty && query (_("Reinitialize source path to empty? ")))
373	{
374	  xfree (source_path);
375	  init_source_path ();
376	}
377    }
378  else
379    {
380      mod_path (dirname, &source_path);
381      last_source_visited = NULL;
382    }
383  if (from_tty)
384    show_directories ((char *) 0, from_tty);
385  forget_cached_source_info ();
386}
387
388/* Add a path given with the -d command line switch.
389   This will not be quoted so we must not treat spaces as separators.  */
390
391void
392directory_switch (char *dirname, int from_tty)
393{
394  add_path (dirname, &source_path, 0);
395}
396
397/* Add zero or more directories to the front of an arbitrary path.  */
398
399void
400mod_path (char *dirname, char **which_path)
401{
402  add_path (dirname, which_path, 1);
403}
404
405/* Workhorse of mod_path.  Takes an extra argument to determine
406   if dirname should be parsed for separators that indicate multiple
407   directories.  This allows for interfaces that pre-parse the dirname
408   and allow specification of traditional separator characters such
409   as space or tab. */
410
411void
412add_path (char *dirname, char **which_path, int parse_separators)
413{
414  char *old = *which_path;
415  int prefix = 0;
416  char **argv = NULL;
417  char *arg;
418  int argv_index = 0;
419
420  if (dirname == 0)
421    return;
422
423  if (parse_separators)
424    {
425      /* This will properly parse the space and tab separators
426	 and any quotes that may exist. DIRNAME_SEPARATOR will
427	 be dealt with later.  */
428      argv = buildargv (dirname);
429      make_cleanup_freeargv (argv);
430
431      if (argv == NULL)
432	nomem (0);
433
434      arg = argv[0];
435    }
436  else
437    {
438      arg = xstrdup (dirname);
439      make_cleanup (xfree, arg);
440    }
441
442  do
443    {
444      char *name = arg;
445      char *p;
446      struct stat st;
447
448      {
449	char *separator = NULL;
450
451	/* Spaces and tabs will have been removed by buildargv().
452	   The directories will there be split into a list but
453	   each entry may still contain DIRNAME_SEPARATOR.  */
454	if (parse_separators)
455	  separator = strchr (name, DIRNAME_SEPARATOR);
456
457	if (separator == 0)
458	  p = arg = name + strlen (name);
459	else
460	  {
461	    p = separator;
462	    arg = p + 1;
463	    while (*arg == DIRNAME_SEPARATOR)
464	      ++arg;
465	  }
466
467	/* If there are no more directories in this argument then start
468	   on the next argument next time round the loop (if any).  */
469	if (*arg == '\0')
470	  arg = parse_separators ? argv[++argv_index] : NULL;
471      }
472
473      /* name is the start of the directory.
474	 p is the separator (or null) following the end.  */
475
476      while (!(IS_DIR_SEPARATOR (*name) && p <= name + 1)	/* "/" */
477#ifdef HAVE_DOS_BASED_FILE_SYSTEM
478      /* On MS-DOS and MS-Windows, h:\ is different from h: */
479	     && !(p == name + 3 && name[1] == ':')		/* "d:/" */
480#endif
481	     && IS_DIR_SEPARATOR (p[-1]))
482	/* Sigh. "foo/" => "foo" */
483	--p;
484      *p = '\0';
485
486      while (p > name && p[-1] == '.')
487	{
488	  if (p - name == 1)
489	    {
490	      /* "." => getwd ().  */
491	      name = current_directory;
492	      goto append;
493	    }
494	  else if (p > name + 1 && IS_DIR_SEPARATOR (p[-2]))
495	    {
496	      if (p - name == 2)
497		{
498		  /* "/." => "/".  */
499		  *--p = '\0';
500		  goto append;
501		}
502	      else
503		{
504		  /* "...foo/." => "...foo".  */
505		  p -= 2;
506		  *p = '\0';
507		  continue;
508		}
509	    }
510	  else
511	    break;
512	}
513
514      if (name[0] == '~')
515	name = tilde_expand (name);
516#ifdef HAVE_DOS_BASED_FILE_SYSTEM
517      else if (IS_ABSOLUTE_PATH (name) && p == name + 2) /* "d:" => "d:." */
518	name = concat (name, ".", (char *)NULL);
519#endif
520      else if (!IS_ABSOLUTE_PATH (name) && name[0] != '$')
521	name = concat (current_directory, SLASH_STRING, name, (char *)NULL);
522      else
523	name = savestring (name, p - name);
524      make_cleanup (xfree, name);
525
526      /* Unless it's a variable, check existence.  */
527      if (name[0] != '$')
528	{
529	  /* These are warnings, not errors, since we don't want a
530	     non-existent directory in a .gdbinit file to stop processing
531	     of the .gdbinit file.
532
533	     Whether they get added to the path is more debatable.  Current
534	     answer is yes, in case the user wants to go make the directory
535	     or whatever.  If the directory continues to not exist/not be
536	     a directory/etc, then having them in the path should be
537	     harmless.  */
538	  if (stat (name, &st) < 0)
539	    {
540	      int save_errno = errno;
541	      fprintf_unfiltered (gdb_stderr, "Warning: ");
542	      print_sys_errmsg (name, save_errno);
543	    }
544	  else if ((st.st_mode & S_IFMT) != S_IFDIR)
545	    warning (_("%s is not a directory."), name);
546	}
547
548    append:
549      {
550	unsigned int len = strlen (name);
551
552	p = *which_path;
553	while (1)
554	  {
555	    /* FIXME: strncmp loses in interesting ways on MS-DOS and
556	       MS-Windows because of case-insensitivity and two different
557	       but functionally identical slash characters.  We need a
558	       special filesystem-dependent file-name comparison function.
559
560	       Actually, even on Unix I would use realpath() or its work-
561	       alike before comparing.  Then all the code above which
562	       removes excess slashes and dots could simply go away.  */
563	    if (!strncmp (p, name, len)
564		&& (p[len] == '\0' || p[len] == DIRNAME_SEPARATOR))
565	      {
566		/* Found it in the search path, remove old copy */
567		if (p > *which_path)
568		  p--;		/* Back over leading separator */
569		if (prefix > p - *which_path)
570		  goto skip_dup;	/* Same dir twice in one cmd */
571		strcpy (p, &p[len + 1]);	/* Copy from next \0 or  : */
572	      }
573	    p = strchr (p, DIRNAME_SEPARATOR);
574	    if (p != 0)
575	      ++p;
576	    else
577	      break;
578	  }
579	if (p == 0)
580	  {
581	    char tinybuf[2];
582
583	    tinybuf[0] = DIRNAME_SEPARATOR;
584	    tinybuf[1] = '\0';
585
586	    /* If we have already tacked on a name(s) in this command, be sure they stay
587	       on the front as we tack on some more.  */
588	    if (prefix)
589	      {
590		char *temp, c;
591
592		c = old[prefix];
593		old[prefix] = '\0';
594		temp = concat (old, tinybuf, name, (char *)NULL);
595		old[prefix] = c;
596		*which_path = concat (temp, "", &old[prefix], (char *)NULL);
597		prefix = strlen (temp);
598		xfree (temp);
599	      }
600	    else
601	      {
602		*which_path = concat (name, (old[0] ? tinybuf : old),
603				      old, (char *)NULL);
604		prefix = strlen (name);
605	      }
606	    xfree (old);
607	    old = *which_path;
608	  }
609      }
610    skip_dup:;
611    }
612  while (arg != NULL);
613}
614
615
616static void
617source_info (char *ignore, int from_tty)
618{
619  struct symtab *s = current_source_symtab;
620
621  if (!s)
622    {
623      printf_filtered (_("No current source file.\n"));
624      return;
625    }
626  printf_filtered (_("Current source file is %s\n"), s->filename);
627  if (s->dirname)
628    printf_filtered (_("Compilation directory is %s\n"), s->dirname);
629  if (s->fullname)
630    printf_filtered (_("Located in %s\n"), s->fullname);
631  if (s->nlines)
632    printf_filtered (_("Contains %d line%s.\n"), s->nlines,
633		     s->nlines == 1 ? "" : "s");
634
635  printf_filtered (_("Source language is %s.\n"), language_str (s->language));
636  printf_filtered (_("Compiled with %s debugging format.\n"), s->debugformat);
637  printf_filtered (_("%s preprocessor macro info.\n"),
638                   s->macro_table ? "Includes" : "Does not include");
639}
640
641
642/* Return True if the file NAME exists and is a regular file */
643static int
644is_regular_file (const char *name)
645{
646  struct stat st;
647  const int status = stat (name, &st);
648
649  /* Stat should never fail except when the file does not exist.
650     If stat fails, analyze the source of error and return True
651     unless the file does not exist, to avoid returning false results
652     on obscure systems where stat does not work as expected.
653   */
654  if (status != 0)
655    return (errno != ENOENT);
656
657  return S_ISREG (st.st_mode);
658}
659
660/* Open a file named STRING, searching path PATH (dir names sep by some char)
661   using mode MODE and protection bits PROT in the calls to open.
662
663   OPTS specifies the function behaviour in specific cases.
664
665   If OPF_TRY_CWD_FIRST, try to open ./STRING before searching PATH.
666   (ie pretend the first element of PATH is ".").  This also indicates
667   that a slash in STRING disables searching of the path (this is
668   so that "exec-file ./foo" or "symbol-file ./foo" insures that you
669   get that particular version of foo or an error message).
670
671   If OPTS has OPF_SEARCH_IN_PATH set, absolute names will also be
672   searched in path (we usually want this for source files but not for
673   executables).
674
675   If FILENAME_OPENED is non-null, set it to a newly allocated string naming
676   the actual file opened (this string will always start with a "/").  We
677   have to take special pains to avoid doubling the "/" between the directory
678   and the file, sigh!  Emacs gets confuzzed by this when we print the
679   source file name!!!
680
681   If a file is found, return the descriptor.
682   Otherwise, return -1, with errno set for the last name we tried to open.  */
683
684/*  >>>> This should only allow files of certain types,
685    >>>>  eg executable, non-directory */
686int
687openp (const char *path, int opts, const char *string,
688       int mode, int prot,
689       char **filename_opened)
690{
691  int fd;
692  char *filename;
693  const char *p;
694  const char *p1;
695  int len;
696  int alloclen;
697
698  if (!path)
699    path = ".";
700
701  mode |= O_BINARY;
702
703  if ((opts & OPF_TRY_CWD_FIRST) || IS_ABSOLUTE_PATH (string))
704    {
705      int i;
706
707      if (is_regular_file (string))
708	{
709	  filename = alloca (strlen (string) + 1);
710	  strcpy (filename, string);
711	  fd = open (filename, mode, prot);
712	  if (fd >= 0)
713	    goto done;
714	}
715      else
716	{
717	  filename = NULL;
718	  fd = -1;
719	}
720
721      if (!(opts & OPF_SEARCH_IN_PATH))
722	for (i = 0; string[i]; i++)
723	  if (IS_DIR_SEPARATOR (string[i]))
724	    goto done;
725    }
726
727  /* /foo => foo, to avoid multiple slashes that Emacs doesn't like. */
728  while (IS_DIR_SEPARATOR(string[0]))
729    string++;
730
731  /* ./foo => foo */
732  while (string[0] == '.' && IS_DIR_SEPARATOR (string[1]))
733    string += 2;
734
735  alloclen = strlen (path) + strlen (string) + 2;
736  filename = alloca (alloclen);
737  fd = -1;
738  for (p = path; p; p = p1 ? p1 + 1 : 0)
739    {
740      p1 = strchr (p, DIRNAME_SEPARATOR);
741      if (p1)
742	len = p1 - p;
743      else
744	len = strlen (p);
745
746      if (len == 4 && p[0] == '$' && p[1] == 'c'
747	  && p[2] == 'w' && p[3] == 'd')
748	{
749	  /* Name is $cwd -- insert current directory name instead.  */
750	  int newlen;
751
752	  /* First, realloc the filename buffer if too short. */
753	  len = strlen (current_directory);
754	  newlen = len + strlen (string) + 2;
755	  if (newlen > alloclen)
756	    {
757	      alloclen = newlen;
758	      filename = alloca (alloclen);
759	    }
760	  strcpy (filename, current_directory);
761	}
762      else
763	{
764	  /* Normal file name in path -- just use it.  */
765	  strncpy (filename, p, len);
766	  filename[len] = 0;
767	}
768
769      /* Remove trailing slashes */
770      while (len > 0 && IS_DIR_SEPARATOR (filename[len - 1]))
771	filename[--len] = 0;
772
773      strcat (filename + len, SLASH_STRING);
774      strcat (filename, string);
775
776      if (is_regular_file (filename))
777	{
778	  fd = open (filename, mode);
779	  if (fd >= 0)
780	    break;
781	}
782    }
783
784done:
785  if (filename_opened)
786    {
787      /* If a file was opened, canonicalize its filename. Use xfullpath
788         rather than gdb_realpath to avoid resolving the basename part
789         of filenames when the associated file is a symbolic link. This
790         fixes a potential inconsistency between the filenames known to
791         GDB and the filenames it prints in the annotations.  */
792      if (fd < 0)
793	*filename_opened = NULL;
794      else if (IS_ABSOLUTE_PATH (filename))
795	*filename_opened = xfullpath (filename);
796      else
797	{
798	  /* Beware the // my son, the Emacs barfs, the botch that catch... */
799
800	  char *f = concat (current_directory,
801			    IS_DIR_SEPARATOR (current_directory[strlen (current_directory) - 1])
802			    ? "" : SLASH_STRING,
803			    filename, (char *)NULL);
804	  *filename_opened = xfullpath (f);
805	  xfree (f);
806	}
807    }
808
809  return fd;
810}
811
812
813/* This is essentially a convenience, for clients that want the behaviour
814   of openp, using source_path, but that really don't want the file to be
815   opened but want instead just to know what the full pathname is (as
816   qualified against source_path).
817
818   The current working directory is searched first.
819
820   If the file was found, this function returns 1, and FULL_PATHNAME is
821   set to the fully-qualified pathname.
822
823   Else, this functions returns 0, and FULL_PATHNAME is set to NULL.  */
824int
825source_full_path_of (char *filename, char **full_pathname)
826{
827  int fd;
828
829  fd = openp (source_path, OPF_TRY_CWD_FIRST | OPF_SEARCH_IN_PATH, filename,
830	      O_RDONLY, 0, full_pathname);
831  if (fd < 0)
832    {
833      *full_pathname = NULL;
834      return 0;
835    }
836
837  close (fd);
838  return 1;
839}
840
841/* Return non-zero if RULE matches PATH, that is if the rule can be
842   applied to PATH.  */
843
844static int
845substitute_path_rule_matches (const struct substitute_path_rule *rule,
846                              const char *path)
847{
848  const int from_len = strlen (rule->from);
849  const int path_len = strlen (path);
850  char *path_start;
851
852  if (path_len < from_len)
853    return 0;
854
855  /* The substitution rules are anchored at the start of the path,
856     so the path should start with rule->from.  There is no filename
857     comparison routine, so we need to extract the first FROM_LEN
858     characters from PATH first and use that to do the comparison.  */
859
860  path_start = alloca (from_len + 1);
861  strncpy (path_start, path, from_len);
862  path_start[from_len] = '\0';
863
864  if (FILENAME_CMP (path_start, rule->from) != 0)
865    return 0;
866
867  /* Make sure that the region in the path that matches the substitution
868     rule is immediately followed by a directory separator (or the end of
869     string character).  */
870
871  if (path[from_len] != '\0' && !IS_DIR_SEPARATOR (path[from_len]))
872    return 0;
873
874  return 1;
875}
876
877/* Find the substitute-path rule that applies to PATH and return it.
878   Return NULL if no rule applies.  */
879
880static struct substitute_path_rule *
881get_substitute_path_rule (const char *path)
882{
883  struct substitute_path_rule *rule = substitute_path_rules;
884
885  while (rule != NULL && !substitute_path_rule_matches (rule, path))
886    rule = rule->next;
887
888  return rule;
889}
890
891/* If the user specified a source path substitution rule that applies
892   to PATH, then apply it and return the new path.  This new path must
893   be deallocated afterwards.
894
895   Return NULL if no substitution rule was specified by the user,
896   or if no rule applied to the given PATH.  */
897
898static char *
899rewrite_source_path (const char *path)
900{
901  const struct substitute_path_rule *rule = get_substitute_path_rule (path);
902  char *new_path;
903  int from_len;
904
905  if (rule == NULL)
906    return NULL;
907
908  from_len = strlen (rule->from);
909
910  /* Compute the rewritten path and return it.  */
911
912  new_path =
913    (char *) xmalloc (strlen (path) + 1 + strlen (rule->to) - from_len);
914  strcpy (new_path, rule->to);
915  strcat (new_path, path + from_len);
916
917  return new_path;
918}
919
920/* This function is capable of finding the absolute path to a
921   source file, and opening it, provided you give it an
922   OBJFILE and FILENAME. Both the DIRNAME and FULLNAME are only
923   added suggestions on where to find the file.
924
925   OBJFILE should be the objfile associated with a psymtab or symtab.
926   FILENAME should be the filename to open.
927   DIRNAME is the compilation directory of a particular source file.
928           Only some debug formats provide this info.
929   FULLNAME can be the last known absolute path to the file in question.
930
931   On Success
932     A valid file descriptor is returned. ( the return value is positive )
933     FULLNAME is set to the absolute path to the file just opened.
934
935   On Failure
936     An invalid file descriptor is returned. ( the return value is negative )
937     FULLNAME is set to NULL.  */
938int
939find_and_open_source (struct objfile *objfile,
940		      const char *filename,
941		      const char *dirname,
942		      char **fullname)
943{
944  char *path = source_path;
945  const char *p;
946  int result;
947
948  /* Quick way out if we already know its full name */
949
950  if (*fullname)
951    {
952      /* The user may have requested that source paths be rewritten
953         according to substitution rules he provided.  If a substitution
954         rule applies to this path, then apply it.  */
955      char *rewritten_fullname = rewrite_source_path (*fullname);
956
957      if (rewritten_fullname != NULL)
958        {
959          xfree (*fullname);
960          *fullname = rewritten_fullname;
961        }
962
963      result = open (*fullname, OPEN_MODE);
964      if (result >= 0)
965	return result;
966      /* Didn't work -- free old one, try again. */
967      xfree (*fullname);
968      *fullname = NULL;
969    }
970
971  if (dirname != NULL)
972    {
973      /* If necessary, rewrite the compilation directory name according
974         to the source path substitution rules specified by the user.  */
975
976      char *rewritten_dirname = rewrite_source_path (dirname);
977
978      if (rewritten_dirname != NULL)
979        {
980          make_cleanup (xfree, rewritten_dirname);
981          dirname = rewritten_dirname;
982        }
983
984      /* Replace a path entry of  $cdir  with the compilation directory name */
985#define	cdir_len	5
986      /* We cast strstr's result in case an ANSIhole has made it const,
987         which produces a "required warning" when assigned to a nonconst. */
988      p = (char *) strstr (source_path, "$cdir");
989      if (p && (p == path || p[-1] == DIRNAME_SEPARATOR)
990	  && (p[cdir_len] == DIRNAME_SEPARATOR || p[cdir_len] == '\0'))
991	{
992	  int len;
993
994	  path = (char *)
995	    alloca (strlen (source_path) + 1 + strlen (dirname) + 1);
996	  len = p - source_path;
997	  strncpy (path, source_path, len);	/* Before $cdir */
998	  strcpy (path + len, dirname);	/* new stuff */
999	  strcat (path + len, source_path + len + cdir_len);	/* After $cdir */
1000	}
1001    }
1002  else
1003    {
1004      /* If dirname is NULL, chances are the path is embedded in
1005         the filename.  Try the source path substitution on it.  */
1006      char *rewritten_filename = rewrite_source_path (filename);
1007
1008      if (rewritten_filename != NULL)
1009        {
1010          make_cleanup (xfree, rewritten_filename);
1011          filename = rewritten_filename;
1012        }
1013    }
1014
1015  result = openp (path, OPF_SEARCH_IN_PATH, filename, OPEN_MODE, 0, fullname);
1016  if (result < 0)
1017    {
1018      /* Didn't work.  Try using just the basename. */
1019      p = lbasename (filename);
1020      if (p != filename)
1021	result = openp (path, OPF_SEARCH_IN_PATH, p, OPEN_MODE, 0, fullname);
1022    }
1023
1024  if (result >= 0)
1025    {
1026      char *tmp_fullname;
1027      tmp_fullname = *fullname;
1028      *fullname = xstrdup (tmp_fullname);
1029      xfree (tmp_fullname);
1030    }
1031  return result;
1032}
1033
1034/* Open a source file given a symtab S.  Returns a file descriptor or
1035   negative number for error.
1036
1037   This function is a convience function to find_and_open_source. */
1038
1039int
1040open_source_file (struct symtab *s)
1041{
1042  if (!s)
1043    return -1;
1044
1045  return find_and_open_source (s->objfile, s->filename, s->dirname,
1046			       &s->fullname);
1047}
1048
1049/* Finds the fullname that a symtab represents.
1050
1051   If this functions finds the fullname, it will save it in ps->fullname
1052   and it will also return the value.
1053
1054   If this function fails to find the file that this symtab represents,
1055   NULL will be returned and ps->fullname will be set to NULL.  */
1056char *
1057symtab_to_fullname (struct symtab *s)
1058{
1059  int r;
1060
1061  if (!s)
1062    return NULL;
1063
1064  /* Don't check s->fullname here, the file could have been
1065     deleted/moved/..., look for it again */
1066  r = find_and_open_source (s->objfile, s->filename, s->dirname,
1067			    &s->fullname);
1068
1069  if (r)
1070    {
1071      close (r);
1072      return s->fullname;
1073    }
1074
1075  return NULL;
1076}
1077
1078/* Finds the fullname that a partial_symtab represents.
1079
1080   If this functions finds the fullname, it will save it in ps->fullname
1081   and it will also return the value.
1082
1083   If this function fails to find the file that this partial_symtab represents,
1084   NULL will be returned and ps->fullname will be set to NULL.  */
1085char *
1086psymtab_to_fullname (struct partial_symtab *ps)
1087{
1088  int r;
1089
1090  if (!ps)
1091    return NULL;
1092
1093  /* Don't check ps->fullname here, the file could have been
1094     deleted/moved/..., look for it again */
1095  r = find_and_open_source (ps->objfile, ps->filename, ps->dirname,
1096			    &ps->fullname);
1097
1098  if (r)
1099    {
1100      close (r);
1101      return ps->fullname;
1102    }
1103
1104  return NULL;
1105}
1106
1107/* Create and initialize the table S->line_charpos that records
1108   the positions of the lines in the source file, which is assumed
1109   to be open on descriptor DESC.
1110   All set S->nlines to the number of such lines.  */
1111
1112void
1113find_source_lines (struct symtab *s, int desc)
1114{
1115  struct stat st;
1116  char *data, *p, *end;
1117  int nlines = 0;
1118  int lines_allocated = 1000;
1119  int *line_charpos;
1120  long mtime = 0;
1121  int size;
1122
1123  gdb_assert (s);
1124  line_charpos = (int *) xmalloc (lines_allocated * sizeof (int));
1125  if (fstat (desc, &st) < 0)
1126    perror_with_name (s->filename);
1127
1128  if (s->objfile && s->objfile->obfd)
1129    mtime = bfd_get_mtime (s->objfile->obfd);
1130  else if (exec_bfd)
1131    mtime = bfd_get_mtime (exec_bfd);
1132
1133  if (mtime && mtime < st.st_mtime)
1134    warning (_("Source file is more recent than executable."));
1135
1136#ifdef LSEEK_NOT_LINEAR
1137  {
1138    char c;
1139
1140    /* Have to read it byte by byte to find out where the chars live */
1141
1142    line_charpos[0] = lseek (desc, 0, SEEK_CUR);
1143    nlines = 1;
1144    while (myread (desc, &c, 1) > 0)
1145      {
1146	if (c == '\n')
1147	  {
1148	    if (nlines == lines_allocated)
1149	      {
1150		lines_allocated *= 2;
1151		line_charpos =
1152		  (int *) xrealloc ((char *) line_charpos,
1153				    sizeof (int) * lines_allocated);
1154	      }
1155	    line_charpos[nlines++] = lseek (desc, 0, SEEK_CUR);
1156	  }
1157      }
1158  }
1159#else /* lseek linear.  */
1160  {
1161    struct cleanup *old_cleanups;
1162
1163    /* st_size might be a large type, but we only support source files whose
1164       size fits in an int.  */
1165    size = (int) st.st_size;
1166
1167    /* Use malloc, not alloca, because this may be pretty large, and we may
1168       run into various kinds of limits on stack size.  */
1169    data = (char *) xmalloc (size);
1170    old_cleanups = make_cleanup (xfree, data);
1171
1172    /* Reassign `size' to result of read for systems where \r\n -> \n.  */
1173    size = myread (desc, data, size);
1174    if (size < 0)
1175      perror_with_name (s->filename);
1176    end = data + size;
1177    p = data;
1178    line_charpos[0] = 0;
1179    nlines = 1;
1180    while (p != end)
1181      {
1182	if (*p++ == '\n'
1183	/* A newline at the end does not start a new line.  */
1184	    && p != end)
1185	  {
1186	    if (nlines == lines_allocated)
1187	      {
1188		lines_allocated *= 2;
1189		line_charpos =
1190		  (int *) xrealloc ((char *) line_charpos,
1191				    sizeof (int) * lines_allocated);
1192	      }
1193	    line_charpos[nlines++] = p - data;
1194	  }
1195      }
1196    do_cleanups (old_cleanups);
1197  }
1198#endif /* lseek linear.  */
1199  s->nlines = nlines;
1200  s->line_charpos =
1201    (int *) xrealloc ((char *) line_charpos, nlines * sizeof (int));
1202
1203}
1204
1205/* Return the character position of a line LINE in symtab S.
1206   Return 0 if anything is invalid.  */
1207
1208#if 0				/* Currently unused */
1209
1210int
1211source_line_charpos (struct symtab *s, int line)
1212{
1213  if (!s)
1214    return 0;
1215  if (!s->line_charpos || line <= 0)
1216    return 0;
1217  if (line > s->nlines)
1218    line = s->nlines;
1219  return s->line_charpos[line - 1];
1220}
1221
1222/* Return the line number of character position POS in symtab S.  */
1223
1224int
1225source_charpos_line (struct symtab *s, int chr)
1226{
1227  int line = 0;
1228  int *lnp;
1229
1230  if (s == 0 || s->line_charpos == 0)
1231    return 0;
1232  lnp = s->line_charpos;
1233  /* Files are usually short, so sequential search is Ok */
1234  while (line < s->nlines && *lnp <= chr)
1235    {
1236      line++;
1237      lnp++;
1238    }
1239  if (line >= s->nlines)
1240    line = s->nlines;
1241  return line;
1242}
1243
1244#endif /* 0 */
1245
1246
1247/* Get full pathname and line number positions for a symtab.
1248   Return nonzero if line numbers may have changed.
1249   Set *FULLNAME to actual name of the file as found by `openp',
1250   or to 0 if the file is not found.  */
1251
1252static int
1253get_filename_and_charpos (struct symtab *s, char **fullname)
1254{
1255  int desc, linenums_changed = 0;
1256
1257  desc = open_source_file (s);
1258  if (desc < 0)
1259    {
1260      if (fullname)
1261	*fullname = NULL;
1262      return 0;
1263    }
1264  if (fullname)
1265    *fullname = s->fullname;
1266  if (s->line_charpos == 0)
1267    linenums_changed = 1;
1268  if (linenums_changed)
1269    find_source_lines (s, desc);
1270  close (desc);
1271  return linenums_changed;
1272}
1273
1274/* Print text describing the full name of the source file S
1275   and the line number LINE and its corresponding character position.
1276   The text starts with two Ctrl-z so that the Emacs-GDB interface
1277   can easily find it.
1278
1279   MID_STATEMENT is nonzero if the PC is not at the beginning of that line.
1280
1281   Return 1 if successful, 0 if could not find the file.  */
1282
1283int
1284identify_source_line (struct symtab *s, int line, int mid_statement,
1285		      CORE_ADDR pc)
1286{
1287  if (s->line_charpos == 0)
1288    get_filename_and_charpos (s, (char **) NULL);
1289  if (s->fullname == 0)
1290    return 0;
1291  if (line > s->nlines)
1292    /* Don't index off the end of the line_charpos array.  */
1293    return 0;
1294  annotate_source (s->fullname, line, s->line_charpos[line - 1],
1295		   mid_statement, pc);
1296
1297  current_source_line = line;
1298  first_line_listed = line;
1299  last_line_listed = line;
1300  current_source_symtab = s;
1301  return 1;
1302}
1303
1304
1305/* Print source lines from the file of symtab S,
1306   starting with line number LINE and stopping before line number STOPLINE. */
1307
1308static void print_source_lines_base (struct symtab *s, int line, int stopline,
1309				     int noerror);
1310static void
1311print_source_lines_base (struct symtab *s, int line, int stopline, int noerror)
1312{
1313  int c;
1314  int desc;
1315  FILE *stream;
1316  int nlines = stopline - line;
1317
1318  /* Regardless of whether we can open the file, set current_source_symtab. */
1319  current_source_symtab = s;
1320  current_source_line = line;
1321  first_line_listed = line;
1322
1323  /* If printing of source lines is disabled, just print file and line number */
1324  if (ui_out_test_flags (uiout, ui_source_list))
1325    {
1326      /* Only prints "No such file or directory" once */
1327      if ((s != last_source_visited) || (!last_source_error))
1328	{
1329	  last_source_visited = s;
1330	  desc = open_source_file (s);
1331	}
1332      else
1333	{
1334	  desc = last_source_error;
1335	  noerror = 1;
1336	}
1337    }
1338  else
1339    {
1340      desc = -1;
1341      noerror = 1;
1342    }
1343
1344  if (desc < 0)
1345    {
1346      last_source_error = desc;
1347
1348      if (!noerror)
1349	{
1350	  char *name = alloca (strlen (s->filename) + 100);
1351	  sprintf (name, "%d\t%s", line, s->filename);
1352	  print_sys_errmsg (name, errno);
1353	}
1354      else
1355	ui_out_field_int (uiout, "line", line);
1356      ui_out_text (uiout, "\tin ");
1357      ui_out_field_string (uiout, "file", s->filename);
1358      ui_out_text (uiout, "\n");
1359
1360      return;
1361    }
1362
1363  last_source_error = 0;
1364
1365  if (s->line_charpos == 0)
1366    find_source_lines (s, desc);
1367
1368  if (line < 1 || line > s->nlines)
1369    {
1370      close (desc);
1371      error (_("Line number %d out of range; %s has %d lines."),
1372	     line, s->filename, s->nlines);
1373    }
1374
1375  if (lseek (desc, s->line_charpos[line - 1], 0) < 0)
1376    {
1377      close (desc);
1378      perror_with_name (s->filename);
1379    }
1380
1381  stream = fdopen (desc, FDOPEN_MODE);
1382  clearerr (stream);
1383
1384  while (nlines-- > 0)
1385    {
1386      char buf[20];
1387
1388      c = fgetc (stream);
1389      if (c == EOF)
1390	break;
1391      last_line_listed = current_source_line;
1392      sprintf (buf, "%d\t", current_source_line++);
1393      ui_out_text (uiout, buf);
1394      do
1395	{
1396	  if (c < 040 && c != '\t' && c != '\n' && c != '\r')
1397	    {
1398	      sprintf (buf, "^%c", c + 0100);
1399	      ui_out_text (uiout, buf);
1400	    }
1401	  else if (c == 0177)
1402	    ui_out_text (uiout, "^?");
1403	  else if (c == '\r')
1404	    {
1405	      /* Skip a \r character, but only before a \n.  */
1406	      int c1 = fgetc (stream);
1407
1408	      if (c1 != '\n')
1409		printf_filtered ("^%c", c + 0100);
1410	      if (c1 != EOF)
1411		ungetc (c1, stream);
1412	    }
1413	  else
1414	    {
1415	      sprintf (buf, "%c", c);
1416	      ui_out_text (uiout, buf);
1417	    }
1418	}
1419      while (c != '\n' && (c = fgetc (stream)) >= 0);
1420    }
1421
1422  fclose (stream);
1423}
1424
1425/* Show source lines from the file of symtab S, starting with line
1426   number LINE and stopping before line number STOPLINE.  If this is the
1427   not the command line version, then the source is shown in the source
1428   window otherwise it is simply printed */
1429
1430void
1431print_source_lines (struct symtab *s, int line, int stopline, int noerror)
1432{
1433  print_source_lines_base (s, line, stopline, noerror);
1434}
1435
1436/* Print info on range of pc's in a specified line.  */
1437
1438static void
1439line_info (char *arg, int from_tty)
1440{
1441  struct symtabs_and_lines sals;
1442  struct symtab_and_line sal;
1443  CORE_ADDR start_pc, end_pc;
1444  int i;
1445
1446  init_sal (&sal);		/* initialize to zeroes */
1447
1448  if (arg == 0)
1449    {
1450      sal.symtab = current_source_symtab;
1451      sal.line = last_line_listed;
1452      sals.nelts = 1;
1453      sals.sals = (struct symtab_and_line *)
1454	xmalloc (sizeof (struct symtab_and_line));
1455      sals.sals[0] = sal;
1456    }
1457  else
1458    {
1459      sals = decode_line_spec_1 (arg, 0);
1460
1461      dont_repeat ();
1462    }
1463
1464  /* C++  More than one line may have been specified, as when the user
1465     specifies an overloaded function name. Print info on them all. */
1466  for (i = 0; i < sals.nelts; i++)
1467    {
1468      sal = sals.sals[i];
1469
1470      if (sal.symtab == 0)
1471	{
1472	  printf_filtered (_("No line number information available"));
1473	  if (sal.pc != 0)
1474	    {
1475	      /* This is useful for "info line *0x7f34".  If we can't tell the
1476	         user about a source line, at least let them have the symbolic
1477	         address.  */
1478	      printf_filtered (" for address ");
1479	      wrap_here ("  ");
1480	      print_address (sal.pc, gdb_stdout);
1481	    }
1482	  else
1483	    printf_filtered (".");
1484	  printf_filtered ("\n");
1485	}
1486      else if (sal.line > 0
1487	       && find_line_pc_range (sal, &start_pc, &end_pc))
1488	{
1489	  if (start_pc == end_pc)
1490	    {
1491	      printf_filtered ("Line %d of \"%s\"",
1492			       sal.line, sal.symtab->filename);
1493	      wrap_here ("  ");
1494	      printf_filtered (" is at address ");
1495	      print_address (start_pc, gdb_stdout);
1496	      wrap_here ("  ");
1497	      printf_filtered (" but contains no code.\n");
1498	    }
1499	  else
1500	    {
1501	      printf_filtered ("Line %d of \"%s\"",
1502			       sal.line, sal.symtab->filename);
1503	      wrap_here ("  ");
1504	      printf_filtered (" starts at address ");
1505	      print_address (start_pc, gdb_stdout);
1506	      wrap_here ("  ");
1507	      printf_filtered (" and ends at ");
1508	      print_address (end_pc, gdb_stdout);
1509	      printf_filtered (".\n");
1510	    }
1511
1512	  /* x/i should display this line's code.  */
1513	  set_next_address (start_pc);
1514
1515	  /* Repeating "info line" should do the following line.  */
1516	  last_line_listed = sal.line + 1;
1517
1518	  /* If this is the only line, show the source code.  If it could
1519	     not find the file, don't do anything special.  */
1520	  if (annotation_level && sals.nelts == 1)
1521	    identify_source_line (sal.symtab, sal.line, 0, start_pc);
1522	}
1523      else
1524	/* Is there any case in which we get here, and have an address
1525	   which the user would want to see?  If we have debugging symbols
1526	   and no line numbers?  */
1527	printf_filtered (_("Line number %d is out of range for \"%s\".\n"),
1528			 sal.line, sal.symtab->filename);
1529    }
1530  xfree (sals.sals);
1531}
1532
1533/* Commands to search the source file for a regexp.  */
1534
1535static void
1536forward_search_command (char *regex, int from_tty)
1537{
1538  int c;
1539  int desc;
1540  FILE *stream;
1541  int line;
1542  char *msg;
1543
1544  line = last_line_listed + 1;
1545
1546  msg = (char *) re_comp (regex);
1547  if (msg)
1548    error (("%s"), msg);
1549
1550  if (current_source_symtab == 0)
1551    select_source_symtab (0);
1552
1553  desc = open_source_file (current_source_symtab);
1554  if (desc < 0)
1555    perror_with_name (current_source_symtab->filename);
1556
1557  if (current_source_symtab->line_charpos == 0)
1558    find_source_lines (current_source_symtab, desc);
1559
1560  if (line < 1 || line > current_source_symtab->nlines)
1561    {
1562      close (desc);
1563      error (_("Expression not found"));
1564    }
1565
1566  if (lseek (desc, current_source_symtab->line_charpos[line - 1], 0) < 0)
1567    {
1568      close (desc);
1569      perror_with_name (current_source_symtab->filename);
1570    }
1571
1572  stream = fdopen (desc, FDOPEN_MODE);
1573  clearerr (stream);
1574  while (1)
1575    {
1576      static char *buf = NULL;
1577      char *p;
1578      int cursize, newsize;
1579
1580      cursize = 256;
1581      buf = xmalloc (cursize);
1582      p = buf;
1583
1584      c = getc (stream);
1585      if (c == EOF)
1586	break;
1587      do
1588	{
1589	  *p++ = c;
1590	  if (p - buf == cursize)
1591	    {
1592	      newsize = cursize + cursize / 2;
1593	      buf = xrealloc (buf, newsize);
1594	      p = buf + cursize;
1595	      cursize = newsize;
1596	    }
1597	}
1598      while (c != '\n' && (c = getc (stream)) >= 0);
1599
1600      /* Remove the \r, if any, at the end of the line, otherwise
1601         regular expressions that end with $ or \n won't work.  */
1602      if (p - buf > 1 && p[-2] == '\r')
1603	{
1604	  p--;
1605	  p[-1] = '\n';
1606	}
1607
1608      /* we now have a source line in buf, null terminate and match */
1609      *p = 0;
1610      if (re_exec (buf) > 0)
1611	{
1612	  /* Match! */
1613	  fclose (stream);
1614	  print_source_lines (current_source_symtab, line, line + 1, 0);
1615	  set_internalvar (lookup_internalvar ("_"),
1616			   value_from_longest (builtin_type_int,
1617					       (LONGEST) line));
1618	  current_source_line = max (line - lines_to_list / 2, 1);
1619	  return;
1620	}
1621      line++;
1622    }
1623
1624  printf_filtered (_("Expression not found\n"));
1625  fclose (stream);
1626}
1627
1628static void
1629reverse_search_command (char *regex, int from_tty)
1630{
1631  int c;
1632  int desc;
1633  FILE *stream;
1634  int line;
1635  char *msg;
1636
1637  line = last_line_listed - 1;
1638
1639  msg = (char *) re_comp (regex);
1640  if (msg)
1641    error (("%s"), msg);
1642
1643  if (current_source_symtab == 0)
1644    select_source_symtab (0);
1645
1646  desc = open_source_file (current_source_symtab);
1647  if (desc < 0)
1648    perror_with_name (current_source_symtab->filename);
1649
1650  if (current_source_symtab->line_charpos == 0)
1651    find_source_lines (current_source_symtab, desc);
1652
1653  if (line < 1 || line > current_source_symtab->nlines)
1654    {
1655      close (desc);
1656      error (_("Expression not found"));
1657    }
1658
1659  if (lseek (desc, current_source_symtab->line_charpos[line - 1], 0) < 0)
1660    {
1661      close (desc);
1662      perror_with_name (current_source_symtab->filename);
1663    }
1664
1665  stream = fdopen (desc, FDOPEN_MODE);
1666  clearerr (stream);
1667  while (line > 1)
1668    {
1669/* FIXME!!!  We walk right off the end of buf if we get a long line!!! */
1670      char buf[4096];		/* Should be reasonable??? */
1671      char *p = buf;
1672
1673      c = getc (stream);
1674      if (c == EOF)
1675	break;
1676      do
1677	{
1678	  *p++ = c;
1679	}
1680      while (c != '\n' && (c = getc (stream)) >= 0);
1681
1682      /* Remove the \r, if any, at the end of the line, otherwise
1683         regular expressions that end with $ or \n won't work.  */
1684      if (p - buf > 1 && p[-2] == '\r')
1685	{
1686	  p--;
1687	  p[-1] = '\n';
1688	}
1689
1690      /* We now have a source line in buf; null terminate and match.  */
1691      *p = 0;
1692      if (re_exec (buf) > 0)
1693	{
1694	  /* Match! */
1695	  fclose (stream);
1696	  print_source_lines (current_source_symtab, line, line + 1, 0);
1697	  set_internalvar (lookup_internalvar ("_"),
1698			   value_from_longest (builtin_type_int,
1699					       (LONGEST) line));
1700	  current_source_line = max (line - lines_to_list / 2, 1);
1701	  return;
1702	}
1703      line--;
1704      if (fseek (stream, current_source_symtab->line_charpos[line - 1], 0) < 0)
1705	{
1706	  fclose (stream);
1707	  perror_with_name (current_source_symtab->filename);
1708	}
1709    }
1710
1711  printf_filtered (_("Expression not found\n"));
1712  fclose (stream);
1713  return;
1714}
1715
1716/* If the last character of PATH is a directory separator, then strip it.  */
1717
1718static void
1719strip_trailing_directory_separator (char *path)
1720{
1721  const int last = strlen (path) - 1;
1722
1723  if (last < 0)
1724    return;  /* No stripping is needed if PATH is the empty string.  */
1725
1726  if (IS_DIR_SEPARATOR (path[last]))
1727    path[last] = '\0';
1728}
1729
1730/* Return the path substitution rule that matches FROM.
1731   Return NULL if no rule matches.  */
1732
1733static struct substitute_path_rule *
1734find_substitute_path_rule (const char *from)
1735{
1736  struct substitute_path_rule *rule = substitute_path_rules;
1737
1738  while (rule != NULL)
1739    {
1740      if (FILENAME_CMP (rule->from, from) == 0)
1741        return rule;
1742      rule = rule->next;
1743    }
1744
1745  return NULL;
1746}
1747
1748/* Add a new substitute-path rule at the end of the current list of rules.
1749   The new rule will replace FROM into TO.  */
1750
1751static void
1752add_substitute_path_rule (char *from, char *to)
1753{
1754  struct substitute_path_rule *rule;
1755  struct substitute_path_rule *new_rule;
1756
1757  new_rule = xmalloc (sizeof (struct substitute_path_rule));
1758  new_rule->from = xstrdup (from);
1759  new_rule->to = xstrdup (to);
1760  new_rule->next = NULL;
1761
1762  /* If the list of rules are empty, then insert the new rule
1763     at the head of the list.  */
1764
1765  if (substitute_path_rules == NULL)
1766    {
1767      substitute_path_rules = new_rule;
1768      return;
1769    }
1770
1771  /* Otherwise, skip to the last rule in our list and then append
1772     the new rule.  */
1773
1774  rule = substitute_path_rules;
1775  while (rule->next != NULL)
1776    rule = rule->next;
1777
1778  rule->next = new_rule;
1779}
1780
1781/* Remove the given source path substitution rule from the current list
1782   of rules.  The memory allocated for that rule is also deallocated.  */
1783
1784static void
1785delete_substitute_path_rule (struct substitute_path_rule *rule)
1786{
1787  if (rule == substitute_path_rules)
1788    substitute_path_rules = rule->next;
1789  else
1790    {
1791      struct substitute_path_rule *prev = substitute_path_rules;
1792
1793      while (prev != NULL && prev->next != rule)
1794        prev = prev->next;
1795
1796      gdb_assert (prev != NULL);
1797
1798      prev->next = rule->next;
1799    }
1800
1801  xfree (rule->from);
1802  xfree (rule->to);
1803  xfree (rule);
1804}
1805
1806/* Implement the "show substitute-path" command.  */
1807
1808static void
1809show_substitute_path_command (char *args, int from_tty)
1810{
1811  struct substitute_path_rule *rule = substitute_path_rules;
1812  char **argv;
1813  char *from = NULL;
1814
1815  argv = buildargv (args);
1816  make_cleanup_freeargv (argv);
1817
1818  /* We expect zero or one argument.  */
1819
1820  if (argv != NULL && argv[0] != NULL && argv[1] != NULL)
1821    error (_("Too many arguments in command"));
1822
1823  if (argv != NULL && argv[0] != NULL)
1824    from = argv[0];
1825
1826  /* Print the substitution rules.  */
1827
1828  if (from != NULL)
1829    printf_filtered
1830      (_("Source path substitution rule matching `%s':\n"), from);
1831  else
1832    printf_filtered (_("List of all source path substitution rules:\n"));
1833
1834  while (rule != NULL)
1835    {
1836      if (from == NULL || FILENAME_CMP (rule->from, from) == 0)
1837        printf_filtered ("  `%s' -> `%s'.\n", rule->from, rule->to);
1838      rule = rule->next;
1839    }
1840}
1841
1842/* Implement the "unset substitute-path" command.  */
1843
1844static void
1845unset_substitute_path_command (char *args, int from_tty)
1846{
1847  struct substitute_path_rule *rule = substitute_path_rules;
1848  char **argv = buildargv (args);
1849  char *from = NULL;
1850  int rule_found = 0;
1851
1852  /* This function takes either 0 or 1 argument.  */
1853
1854  make_cleanup_freeargv (argv);
1855  if (argv != NULL && argv[0] != NULL && argv[1] != NULL)
1856    error (_("Incorrect usage, too many arguments in command"));
1857
1858  if (argv != NULL && argv[0] != NULL)
1859    from = argv[0];
1860
1861  /* If the user asked for all the rules to be deleted, ask him
1862     to confirm and give him a chance to abort before the action
1863     is performed.  */
1864
1865  if (from == NULL
1866      && !query (_("Delete all source path substitution rules? ")))
1867    error (_("Canceled"));
1868
1869  /* Delete the rule matching the argument.  No argument means that
1870     all rules should be deleted.  */
1871
1872  while (rule != NULL)
1873    {
1874      struct substitute_path_rule *next = rule->next;
1875
1876      if (from == NULL || FILENAME_CMP (from, rule->from) == 0)
1877        {
1878          delete_substitute_path_rule (rule);
1879          rule_found = 1;
1880        }
1881
1882      rule = next;
1883    }
1884
1885  /* If the user asked for a specific rule to be deleted but
1886     we could not find it, then report an error.  */
1887
1888  if (from != NULL && !rule_found)
1889    error (_("No substitution rule defined for `%s'"), from);
1890}
1891
1892/* Add a new source path substitution rule.  */
1893
1894static void
1895set_substitute_path_command (char *args, int from_tty)
1896{
1897  char *from_path, *to_path;
1898  char **argv;
1899  struct substitute_path_rule *rule;
1900
1901  argv = buildargv (args);
1902  make_cleanup_freeargv (argv);
1903
1904  if (argv == NULL || argv[0] == NULL || argv [1] == NULL)
1905    error (_("Incorrect usage, too few arguments in command"));
1906
1907  if (argv[2] != NULL)
1908    error (_("Incorrect usage, too many arguments in command"));
1909
1910  if (*(argv[0]) == '\0')
1911    error (_("First argument must be at least one character long"));
1912
1913  /* Strip any trailing directory separator character in either FROM
1914     or TO.  The substitution rule already implicitly contains them.  */
1915  strip_trailing_directory_separator (argv[0]);
1916  strip_trailing_directory_separator (argv[1]);
1917
1918  /* If a rule with the same "from" was previously defined, then
1919     delete it.  This new rule replaces it.  */
1920
1921  rule = find_substitute_path_rule (argv[0]);
1922  if (rule != NULL)
1923    delete_substitute_path_rule (rule);
1924
1925  /* Insert the new substitution rule.  */
1926
1927  add_substitute_path_rule (argv[0], argv[1]);
1928}
1929
1930
1931void
1932_initialize_source (void)
1933{
1934  struct cmd_list_element *c;
1935  current_source_symtab = 0;
1936  init_source_path ();
1937
1938  /* The intention is to use POSIX Basic Regular Expressions.
1939     Always use the GNU regex routine for consistency across all hosts.
1940     Our current GNU regex.c does not have all the POSIX features, so this is
1941     just an approximation.  */
1942  re_set_syntax (RE_SYNTAX_GREP);
1943
1944  c = add_cmd ("directory", class_files, directory_command, _("\
1945Add directory DIR to beginning of search path for source files.\n\
1946Forget cached info on source file locations and line positions.\n\
1947DIR can also be $cwd for the current working directory, or $cdir for the\n\
1948directory in which the source file was compiled into object code.\n\
1949With no argument, reset the search path to $cdir:$cwd, the default."),
1950	       &cmdlist);
1951
1952  if (dbx_commands)
1953    add_com_alias ("use", "directory", class_files, 0);
1954
1955  set_cmd_completer (c, filename_completer);
1956
1957  add_cmd ("directories", no_class, show_directories, _("\
1958Current search path for finding source files.\n\
1959$cwd in the path means the current working directory.\n\
1960$cdir in the path means the compilation directory of the source file."),
1961	   &showlist);
1962
1963  if (xdb_commands)
1964    {
1965      add_com_alias ("D", "directory", class_files, 0);
1966      add_cmd ("ld", no_class, show_directories, _("\
1967Current search path for finding source files.\n\
1968$cwd in the path means the current working directory.\n\
1969$cdir in the path means the compilation directory of the source file."),
1970	       &cmdlist);
1971    }
1972
1973  add_info ("source", source_info,
1974	    _("Information about the current source file."));
1975
1976  add_info ("line", line_info, _("\
1977Core addresses of the code for a source line.\n\
1978Line can be specified as\n\
1979  LINENUM, to list around that line in current file,\n\
1980  FILE:LINENUM, to list around that line in that file,\n\
1981  FUNCTION, to list around beginning of that function,\n\
1982  FILE:FUNCTION, to distinguish among like-named static functions.\n\
1983Default is to describe the last source line that was listed.\n\n\
1984This sets the default address for \"x\" to the line's first instruction\n\
1985so that \"x/i\" suffices to start examining the machine code.\n\
1986The address is also stored as the value of \"$_\"."));
1987
1988  add_com ("forward-search", class_files, forward_search_command, _("\
1989Search for regular expression (see regex(3)) from last line listed.\n\
1990The matching line number is also stored as the value of \"$_\"."));
1991  add_com_alias ("search", "forward-search", class_files, 0);
1992
1993  add_com ("reverse-search", class_files, reverse_search_command, _("\
1994Search backward for regular expression (see regex(3)) from last line listed.\n\
1995The matching line number is also stored as the value of \"$_\"."));
1996
1997  if (xdb_commands)
1998    {
1999      add_com_alias ("/", "forward-search", class_files, 0);
2000      add_com_alias ("?", "reverse-search", class_files, 0);
2001    }
2002
2003  add_setshow_integer_cmd ("listsize", class_support, &lines_to_list, _("\
2004Set number of source lines gdb will list by default."), _("\
2005Show number of source lines gdb will list by default."), NULL,
2006			    NULL,
2007			    show_lines_to_list,
2008			    &setlist, &showlist);
2009
2010  add_cmd ("substitute-path", class_files, set_substitute_path_command,
2011           _("\
2012Usage: set substitute-path FROM TO\n\
2013Add a substitution rule replacing FROM into TO in source file names.\n\
2014If a substitution rule was previously set for FROM, the old rule\n\
2015is replaced by the new one."),
2016           &setlist);
2017
2018  add_cmd ("substitute-path", class_files, unset_substitute_path_command,
2019           _("\
2020Usage: unset substitute-path [FROM]\n\
2021Delete the rule for substituting FROM in source file names.  If FROM\n\
2022is not specified, all substituting rules are deleted.\n\
2023If the debugger cannot find a rule for FROM, it will display a warning."),
2024           &unsetlist);
2025
2026  add_cmd ("substitute-path", class_files, show_substitute_path_command,
2027           _("\
2028Usage: show substitute-path [FROM]\n\
2029Print the rule for substituting FROM in source file names. If FROM\n\
2030is not specified, print all substitution rules."),
2031           &showlist);
2032}
2033