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