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