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