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