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