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