gdb/source.c - gdb

Global variables defined

Data types defined

Functions defined

Macros defined

Source code

  1. /* List lines of source files for GDB, the GNU debugger.
  2.    Copyright (C) 1986-2015 Free Software Foundation, Inc.

  3.    This file is part of GDB.

  4.    This program is free software; you can redistribute it and/or modify
  5.    it under the terms of the GNU General Public License as published by
  6.    the Free Software Foundation; either version 3 of the License, or
  7.    (at your option) any later version.

  8.    This program is distributed in the hope that it will be useful,
  9.    but WITHOUT ANY WARRANTY; without even the implied warranty of
  10.    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  11.    GNU General Public License for more details.

  12.    You should have received a copy of the GNU General Public License
  13.    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */

  14. #include "defs.h"
  15. #include "arch-utils.h"
  16. #include "symtab.h"
  17. #include "expression.h"
  18. #include "language.h"
  19. #include "command.h"
  20. #include "source.h"
  21. #include "gdbcmd.h"
  22. #include "frame.h"
  23. #include "value.h"
  24. #include "filestuff.h"

  25. #include <sys/types.h>
  26. #include <sys/stat.h>
  27. #include <fcntl.h>
  28. #include "gdbcore.h"
  29. #include "gdb_regex.h"
  30. #include "symfile.h"
  31. #include "objfiles.h"
  32. #include "annotate.h"
  33. #include "gdbtypes.h"
  34. #include "linespec.h"
  35. #include "filenames.h"                /* for DOSish file names */
  36. #include "completer.h"
  37. #include "ui-out.h"
  38. #include "readline/readline.h"

  39. #define OPEN_MODE (O_RDONLY | O_BINARY)
  40. #define FDOPEN_MODE FOPEN_RB

  41. /* Prototypes for exported functions.  */

  42. void _initialize_source (void);

  43. /* Prototypes for local functions.  */

  44. static int get_filename_and_charpos (struct symtab *, char **);

  45. static void reverse_search_command (char *, int);

  46. static void forward_search_command (char *, int);

  47. static void line_info (char *, int);

  48. static void source_info (char *, int);

  49. /* Path of directories to search for source files.
  50.    Same format as the PATH environment variable's value.  */

  51. char *source_path;

  52. /* Support for source path substitution commands.  */

  53. struct substitute_path_rule
  54. {
  55.   char *from;
  56.   char *to;
  57.   struct substitute_path_rule *next;
  58. };

  59. static struct substitute_path_rule *substitute_path_rules = NULL;

  60. /* Symtab of default file for listing lines of.  */

  61. static struct symtab *current_source_symtab;

  62. /* Default next line to list.  */

  63. static int current_source_line;

  64. static struct program_space *current_source_pspace;

  65. /* Default number of lines to print with commands like "list".
  66.    This is based on guessing how many long (i.e. more than chars_per_line
  67.    characters) lines there will be.  To be completely correct, "list"
  68.    and friends should be rewritten to count characters and see where
  69.    things are wrapping, but that would be a fair amount of work.  */

  70. int lines_to_list = 10;
  71. static void
  72. show_lines_to_list (struct ui_file *file, int from_tty,
  73.                     struct cmd_list_element *c, const char *value)
  74. {
  75.   fprintf_filtered (file,
  76.                     _("Number of source lines gdb "
  77.                       "will list by default is %s.\n"),
  78.                     value);
  79. }

  80. /* Possible values of 'set filename-display'.  */
  81. static const char filename_display_basename[] = "basename";
  82. static const char filename_display_relative[] = "relative";
  83. static const char filename_display_absolute[] = "absolute";

  84. static const char *const filename_display_kind_names[] = {
  85.   filename_display_basename,
  86.   filename_display_relative,
  87.   filename_display_absolute,
  88.   NULL
  89. };

  90. static const char *filename_display_string = filename_display_relative;

  91. static void
  92. show_filename_display_string (struct ui_file *file, int from_tty,
  93.                               struct cmd_list_element *c, const char *value)
  94. {
  95.   fprintf_filtered (file, _("Filenames are displayed as \"%s\".\n"), value);
  96. }

  97. /* Line number of last line printed.  Default for various commands.
  98.    current_source_line is usually, but not always, the same as this.  */

  99. static int last_line_listed;

  100. /* First line number listed by last listing command.  If 0, then no
  101.    source lines have yet been listed since the last time the current
  102.    source line was changed.  */

  103. static int first_line_listed;

  104. /* Saves the name of the last source file visited and a possible error code.
  105.    Used to prevent repeating annoying "No such file or directories" msgs.  */

  106. static struct symtab *last_source_visited = NULL;
  107. static int last_source_error = 0;

  108. /* Return the first line listed by print_source_lines.
  109.    Used by command interpreters to request listing from
  110.    a previous point.  */

  111. int
  112. get_first_line_listed (void)
  113. {
  114.   return first_line_listed;
  115. }

  116. /* Clear line listed range.  This makes the next "list" center the
  117.    printed source lines around the current source line.  */

  118. static void
  119. clear_lines_listed_range (void)
  120. {
  121.   first_line_listed = 0;
  122.   last_line_listed = 0;
  123. }

  124. /* Return the default number of lines to print with commands like the
  125.    cli "list".  The caller of print_source_lines must use this to
  126.    calculate the end line and use it in the call to print_source_lines
  127.    as it does not automatically use this value.  */

  128. int
  129. get_lines_to_list (void)
  130. {
  131.   return lines_to_list;
  132. }

  133. /* Return the current source file for listing and next line to list.
  134.    NOTE: The returned sal pc and end fields are not valid.  */

  135. struct symtab_and_line
  136. get_current_source_symtab_and_line (void)
  137. {
  138.   struct symtab_and_line cursal = { 0 };

  139.   cursal.pspace = current_source_pspace;
  140.   cursal.symtab = current_source_symtab;
  141.   cursal.line = current_source_line;
  142.   cursal.pc = 0;
  143.   cursal.end = 0;

  144.   return cursal;
  145. }

  146. /* If the current source file for listing is not set, try and get a default.
  147.    Usually called before get_current_source_symtab_and_line() is called.
  148.    It may err out if a default cannot be determined.
  149.    We must be cautious about where it is called, as it can recurse as the
  150.    process of determining a new default may call the caller!
  151.    Use get_current_source_symtab_and_line only to get whatever
  152.    we have without erroring out or trying to get a default.  */

  153. void
  154. set_default_source_symtab_and_line (void)
  155. {
  156.   if (!have_full_symbols () && !have_partial_symbols ())
  157.     error (_("No symbol table is loaded.  Use the \"file\" command."));

  158.   /* Pull in a current source symtab if necessary.  */
  159.   if (current_source_symtab == 0)
  160.     select_source_symtab (0);
  161. }

  162. /* Return the current default file for listing and next line to list
  163.    (the returned sal pc and end fields are not valid.)
  164.    and set the current default to whatever is in SAL.
  165.    NOTE: The returned sal pc and end fields are not valid.  */

  166. struct symtab_and_line
  167. set_current_source_symtab_and_line (const struct symtab_and_line *sal)
  168. {
  169.   struct symtab_and_line cursal = { 0 };

  170.   cursal.pspace = current_source_pspace;
  171.   cursal.symtab = current_source_symtab;
  172.   cursal.line = current_source_line;
  173.   cursal.pc = 0;
  174.   cursal.end = 0;

  175.   current_source_pspace = sal->pspace;
  176.   current_source_symtab = sal->symtab;
  177.   current_source_line = sal->line;

  178.   /* Force the next "list" to center around the current line.  */
  179.   clear_lines_listed_range ();

  180.   return cursal;
  181. }

  182. /* Reset any information stored about a default file and line to print.  */

  183. void
  184. clear_current_source_symtab_and_line (void)
  185. {
  186.   current_source_symtab = 0;
  187.   current_source_line = 0;
  188. }

  189. /* Set the source file default for the "list" command to be S.

  190.    If S is NULL, and we don't have a default, find one.  This
  191.    should only be called when the user actually tries to use the
  192.    default, since we produce an error if we can't find a reasonable
  193.    default.  Also, since this can cause symbols to be read, doing it
  194.    before we need to would make things slower than necessary.  */

  195. void
  196. select_source_symtab (struct symtab *s)
  197. {
  198.   struct symtabs_and_lines sals;
  199.   struct symtab_and_line sal;
  200.   struct objfile *ofp;
  201.   struct compunit_symtab *cu;

  202.   if (s)
  203.     {
  204.       current_source_symtab = s;
  205.       current_source_line = 1;
  206.       current_source_pspace = SYMTAB_PSPACE (s);
  207.       return;
  208.     }

  209.   if (current_source_symtab)
  210.     return;

  211.   /* Make the default place to list be the function `main'
  212.      if one exists.  */
  213.   if (lookup_symbol (main_name (), 0, VAR_DOMAIN, 0))
  214.     {
  215.       sals = decode_line_with_current_source (main_name (),
  216.                                               DECODE_LINE_FUNFIRSTLINE);
  217.       sal = sals.sals[0];
  218.       xfree (sals.sals);
  219.       current_source_pspace = sal.pspace;
  220.       current_source_symtab = sal.symtab;
  221.       current_source_line = max (sal.line - (lines_to_list - 1), 1);
  222.       if (current_source_symtab)
  223.         return;
  224.     }

  225.   /* Alright; find the last file in the symtab list (ignoring .h's
  226.      and namespace symtabs).  */

  227.   current_source_line = 1;

  228.   ALL_FILETABS (ofp, cu, s)
  229.     {
  230.       const char *name = s->filename;
  231.       int len = strlen (name);

  232.       if (!(len > 2 && (strcmp (&name[len - 2], ".h") == 0
  233.                         || strcmp (name, "<<C++-namespaces>>") == 0)))
  234.         {
  235.           current_source_pspace = current_program_space;
  236.           current_source_symtab = s;
  237.         }
  238.     }

  239.   if (current_source_symtab)
  240.     return;

  241.   ALL_OBJFILES (ofp)
  242.   {
  243.     if (ofp->sf)
  244.       s = ofp->sf->qf->find_last_source_symtab (ofp);
  245.     if (s)
  246.       current_source_symtab = s;
  247.   }
  248.   if (current_source_symtab)
  249.     return;

  250.   error (_("Can't find a default source file"));
  251. }

  252. /* Handler for "set directories path-list" command.
  253.    "set dir mumble" doesn't prepend paths, it resets the entire
  254.    path list.  The theory is that set(show(dir)) should be a no-op.  */

  255. static void
  256. set_directories_command (char *args, int from_tty, struct cmd_list_element *c)
  257. {
  258.   /* This is the value that was set.
  259.      It needs to be processed to maintain $cdir:$cwd and remove dups.  */
  260.   char *set_path = source_path;

  261.   /* We preserve the invariant that $cdir:$cwd begins life at the end of
  262.      the list by calling init_source_path.  If they appear earlier in
  263.      SET_PATH then mod_path will move them appropriately.
  264.      mod_path will also remove duplicates.  */
  265.   init_source_path ();
  266.   if (*set_path != '\0')
  267.     mod_path (set_path, &source_path);

  268.   xfree (set_path);
  269. }

  270. /* Print the list of source directories.
  271.    This is used by the "ld" command, so it has the signature of a command
  272.    function.  */

  273. static void
  274. show_directories_1 (char *ignore, int from_tty)
  275. {
  276.   puts_filtered ("Source directories searched: ");
  277.   puts_filtered (source_path);
  278.   puts_filtered ("\n");
  279. }

  280. /* Handler for "show directories" command.  */

  281. static void
  282. show_directories_command (struct ui_file *file, int from_tty,
  283.                           struct cmd_list_element *c, const char *value)
  284. {
  285.   show_directories_1 (NULL, from_tty);
  286. }

  287. /* Forget line positions and file names for the symtabs in a
  288.    particular objfile.  */

  289. void
  290. forget_cached_source_info_for_objfile (struct objfile *objfile)
  291. {
  292.   struct compunit_symtab *cu;
  293.   struct symtab *s;

  294.   ALL_OBJFILE_FILETABS (objfile, cu, s)
  295.     {
  296.       if (s->line_charpos != NULL)
  297.         {
  298.           xfree (s->line_charpos);
  299.           s->line_charpos = NULL;
  300.         }
  301.       if (s->fullname != NULL)
  302.         {
  303.           xfree (s->fullname);
  304.           s->fullname = NULL;
  305.         }
  306.     }

  307.   if (objfile->sf)
  308.     objfile->sf->qf->forget_cached_source_info (objfile);
  309. }

  310. /* Forget what we learned about line positions in source files, and
  311.    which directories contain them; must check again now since files
  312.    may be found in a different directory now.  */

  313. void
  314. forget_cached_source_info (void)
  315. {
  316.   struct program_space *pspace;
  317.   struct objfile *objfile;

  318.   ALL_PSPACES (pspace)
  319.     ALL_PSPACE_OBJFILES (pspace, objfile)
  320.     {
  321.       forget_cached_source_info_for_objfile (objfile);
  322.     }

  323.   last_source_visited = NULL;
  324. }

  325. void
  326. init_source_path (void)
  327. {
  328.   char buf[20];

  329.   xsnprintf (buf, sizeof (buf), "$cdir%c$cwd", DIRNAME_SEPARATOR);
  330.   source_path = xstrdup (buf);
  331.   forget_cached_source_info ();
  332. }

  333. /* Add zero or more directories to the front of the source path.  */

  334. static void
  335. directory_command (char *dirname, int from_tty)
  336. {
  337.   dont_repeat ();
  338.   /* FIXME, this goes to "delete dir"...  */
  339.   if (dirname == 0)
  340.     {
  341.       if (!from_tty || query (_("Reinitialize source path to empty? ")))
  342.         {
  343.           xfree (source_path);
  344.           init_source_path ();
  345.         }
  346.     }
  347.   else
  348.     {
  349.       mod_path (dirname, &source_path);
  350.       forget_cached_source_info ();
  351.     }
  352.   if (from_tty)
  353.     show_directories_1 ((char *) 0, from_tty);
  354. }

  355. /* Add a path given with the -d command line switch.
  356.    This will not be quoted so we must not treat spaces as separators.  */

  357. void
  358. directory_switch (char *dirname, int from_tty)
  359. {
  360.   add_path (dirname, &source_path, 0);
  361. }

  362. /* Add zero or more directories to the front of an arbitrary path.  */

  363. void
  364. mod_path (char *dirname, char **which_path)
  365. {
  366.   add_path (dirname, which_path, 1);
  367. }

  368. /* Workhorse of mod_path.  Takes an extra argument to determine
  369.    if dirname should be parsed for separators that indicate multiple
  370.    directories.  This allows for interfaces that pre-parse the dirname
  371.    and allow specification of traditional separator characters such
  372.    as space or tab.  */

  373. void
  374. add_path (char *dirname, char **which_path, int parse_separators)
  375. {
  376.   char *old = *which_path;
  377.   int prefix = 0;
  378.   VEC (char_ptr) *dir_vec = NULL;
  379.   struct cleanup *back_to;
  380.   int ix;
  381.   char *name;

  382.   if (dirname == 0)
  383.     return;

  384.   if (parse_separators)
  385.     {
  386.       char **argv, **argvp;

  387.       /* This will properly parse the space and tab separators
  388.          and any quotes that may exist.  */
  389.       argv = gdb_buildargv (dirname);

  390.       for (argvp = argv; *argvp; argvp++)
  391.         dirnames_to_char_ptr_vec_append (&dir_vec, *argvp);

  392.       freeargv (argv);
  393.     }
  394.   else
  395.     VEC_safe_push (char_ptr, dir_vec, xstrdup (dirname));
  396.   back_to = make_cleanup_free_char_ptr_vec (dir_vec);

  397.   for (ix = 0; VEC_iterate (char_ptr, dir_vec, ix, name); ++ix)
  398.     {
  399.       char *p;
  400.       struct stat st;

  401.       /* Spaces and tabs will have been removed by buildargv().
  402.          NAME is the start of the directory.
  403.          P is the '\0' following the end.  */
  404.       p = name + strlen (name);

  405.       while (!(IS_DIR_SEPARATOR (*name) && p <= name + 1)        /* "/" */
  406. #ifdef HAVE_DOS_BASED_FILE_SYSTEM
  407.       /* On MS-DOS and MS-Windows, h:\ is different from h: */
  408.              && !(p == name + 3 && name[1] == ':')                /* "d:/" */
  409. #endif
  410.              && IS_DIR_SEPARATOR (p[-1]))
  411.         /* Sigh.  "foo/" => "foo" */
  412.         --p;
  413.       *p = '\0';

  414.       while (p > name && p[-1] == '.')
  415.         {
  416.           if (p - name == 1)
  417.             {
  418.               /* "." => getwd ().  */
  419.               name = current_directory;
  420.               goto append;
  421.             }
  422.           else if (p > name + 1 && IS_DIR_SEPARATOR (p[-2]))
  423.             {
  424.               if (p - name == 2)
  425.                 {
  426.                   /* "/." => "/".  */
  427.                   *--p = '\0';
  428.                   goto append;
  429.                 }
  430.               else
  431.                 {
  432.                   /* "...foo/." => "...foo".  */
  433.                   p -= 2;
  434.                   *p = '\0';
  435.                   continue;
  436.                 }
  437.             }
  438.           else
  439.             break;
  440.         }

  441.       if (name[0] == '~')
  442.         name = tilde_expand (name);
  443. #ifdef HAVE_DOS_BASED_FILE_SYSTEM
  444.       else if (IS_ABSOLUTE_PATH (name) && p == name + 2) /* "d:" => "d:." */
  445.         name = concat (name, ".", (char *)NULL);
  446. #endif
  447.       else if (!IS_ABSOLUTE_PATH (name) && name[0] != '$')
  448.         name = concat (current_directory, SLASH_STRING, name, (char *)NULL);
  449.       else
  450.         name = savestring (name, p - name);
  451.       make_cleanup (xfree, name);

  452.       /* Unless it's a variable, check existence.  */
  453.       if (name[0] != '$')
  454.         {
  455.           /* These are warnings, not errors, since we don't want a
  456.              non-existent directory in a .gdbinit file to stop processing
  457.              of the .gdbinit file.

  458.              Whether they get added to the path is more debatable.  Current
  459.              answer is yes, in case the user wants to go make the directory
  460.              or whatever.  If the directory continues to not exist/not be
  461.              a directory/etc, then having them in the path should be
  462.              harmless.  */
  463.           if (stat (name, &st) < 0)
  464.             {
  465.               int save_errno = errno;

  466.               fprintf_unfiltered (gdb_stderr, "Warning: ");
  467.               print_sys_errmsg (name, save_errno);
  468.             }
  469.           else if ((st.st_mode & S_IFMT) != S_IFDIR)
  470.             warning (_("%s is not a directory."), name);
  471.         }

  472.     append:
  473.       {
  474.         unsigned int len = strlen (name);
  475.         char tinybuf[2];

  476.         p = *which_path;
  477.         while (1)
  478.           {
  479.             /* FIXME: we should use realpath() or its work-alike
  480.                before comparing.  Then all the code above which
  481.                removes excess slashes and dots could simply go away.  */
  482.             if (!filename_ncmp (p, name, len)
  483.                 && (p[len] == '\0' || p[len] == DIRNAME_SEPARATOR))
  484.               {
  485.                 /* Found it in the search path, remove old copy.  */
  486.                 if (p > *which_path)
  487.                   {
  488.                     /* Back over leading separator.  */
  489.                     p--;
  490.                   }
  491.                 if (prefix > p - *which_path)
  492.                   {
  493.                     /* Same dir twice in one cmd.  */
  494.                     goto skip_dup;
  495.                   }
  496.                 /* Copy from next '\0' or ':'.  */
  497.                 memmove (p, &p[len + 1], strlen (&p[len + 1]) + 1);
  498.               }
  499.             p = strchr (p, DIRNAME_SEPARATOR);
  500.             if (p != 0)
  501.               ++p;
  502.             else
  503.               break;
  504.           }

  505.         tinybuf[0] = DIRNAME_SEPARATOR;
  506.         tinybuf[1] = '\0';

  507.         /* If we have already tacked on a name(s) in this command,
  508.            be sure they stay on the front as we tack on some
  509.            more.  */
  510.         if (prefix)
  511.           {
  512.             char *temp, c;

  513.             c = old[prefix];
  514.             old[prefix] = '\0';
  515.             temp = concat (old, tinybuf, name, (char *)NULL);
  516.             old[prefix] = c;
  517.             *which_path = concat (temp, "", &old[prefix], (char *) NULL);
  518.             prefix = strlen (temp);
  519.             xfree (temp);
  520.           }
  521.         else
  522.           {
  523.             *which_path = concat (name, (old[0] ? tinybuf : old),
  524.                                   old, (char *)NULL);
  525.             prefix = strlen (name);
  526.           }
  527.         xfree (old);
  528.         old = *which_path;
  529.       }
  530.     skip_dup:
  531.       ;
  532.     }

  533.   do_cleanups (back_to);
  534. }


  535. static void
  536. source_info (char *ignore, int from_tty)
  537. {
  538.   struct symtab *s = current_source_symtab;

  539.   if (!s)
  540.     {
  541.       printf_filtered (_("No current source file.\n"));
  542.       return;
  543.     }
  544.   printf_filtered (_("Current source file is %s\n"), s->filename);
  545.   if (SYMTAB_DIRNAME (s) != NULL)
  546.     printf_filtered (_("Compilation directory is %s\n"), SYMTAB_DIRNAME (s));
  547.   if (s->fullname)
  548.     printf_filtered (_("Located in %s\n"), s->fullname);
  549.   if (s->nlines)
  550.     printf_filtered (_("Contains %d line%s.\n"), s->nlines,
  551.                      s->nlines == 1 ? "" : "s");

  552.   printf_filtered (_("Source language is %s.\n"), language_str (s->language));
  553.   printf_filtered (_("Compiled with %s debugging format.\n"),
  554.                    COMPUNIT_DEBUGFORMAT (SYMTAB_COMPUNIT (s)));
  555.   printf_filtered (_("%s preprocessor macro info.\n"),
  556.                    COMPUNIT_MACRO_TABLE (SYMTAB_COMPUNIT (s)) != NULL
  557.                    ? "Includes" : "Does not include");
  558. }


  559. /* Return True if the file NAME exists and is a regular file.  */
  560. static int
  561. is_regular_file (const char *name)
  562. {
  563.   struct stat st;
  564.   const int status = stat (name, &st);

  565.   /* Stat should never fail except when the file does not exist.
  566.      If stat fails, analyze the source of error and return True
  567.      unless the file does not exist, to avoid returning false results
  568.      on obscure systems where stat does not work as expected.  */

  569.   if (status != 0)
  570.     return (errno != ENOENT);

  571.   return S_ISREG (st.st_mode);
  572. }

  573. /* Open a file named STRING, searching path PATH (dir names sep by some char)
  574.    using mode MODE in the calls to open.  You cannot use this function to
  575.    create files (O_CREAT).

  576.    OPTS specifies the function behaviour in specific cases.

  577.    If OPF_TRY_CWD_FIRST, try to open ./STRING before searching PATH.
  578.    (ie pretend the first element of PATH is ".").  This also indicates
  579.    that, unless OPF_SEARCH_IN_PATH is also specified, a slash in STRING
  580.    disables searching of the path (this is so that "exec-file ./foo" or
  581.    "symbol-file ./foo" insures that you get that particular version of
  582.    foo or an error message).

  583.    If OPTS has OPF_SEARCH_IN_PATH set, absolute names will also be
  584.    searched in path (we usually want this for source files but not for
  585.    executables).

  586.    If FILENAME_OPENED is non-null, set it to a newly allocated string naming
  587.    the actual file opened (this string will always start with a "/").  We
  588.    have to take special pains to avoid doubling the "/" between the directory
  589.    and the file, sigh!  Emacs gets confuzzed by this when we print the
  590.    source file name!!!

  591.    If OPTS has OPF_RETURN_REALPATH set return FILENAME_OPENED resolved by
  592.    gdb_realpath.  Even without OPF_RETURN_REALPATH this function still returns
  593.    filename starting with "/".  If FILENAME_OPENED is NULL this option has no
  594.    effect.

  595.    If a file is found, return the descriptor.
  596.    Otherwise, return -1, with errno set for the last name we tried to open.  */

  597. /*  >>>> This should only allow files of certain types,
  598.     >>>>  eg executable, non-directory.  */
  599. int
  600. openp (const char *path, int opts, const char *string,
  601.        int mode, char **filename_opened)
  602. {
  603.   int fd;
  604.   char *filename;
  605.   int alloclen;
  606.   VEC (char_ptr) *dir_vec;
  607.   struct cleanup *back_to;
  608.   int ix;
  609.   char *dir;

  610.   /* The open syscall MODE parameter is not specified.  */
  611.   gdb_assert ((mode & O_CREAT) == 0);
  612.   gdb_assert (string != NULL);

  613.   /* A file with an empty name cannot possibly exist.  Report a failure
  614.      without further checking.

  615.      This is an optimization which also defends us against buggy
  616.      implementations of the "stat" function.  For instance, we have
  617.      noticed that a MinGW debugger built on Windows XP 32bits crashes
  618.      when the debugger is started with an empty argument.  */
  619.   if (string[0] == '\0')
  620.     {
  621.       errno = ENOENT;
  622.       return -1;
  623.     }

  624.   if (!path)
  625.     path = ".";

  626.   mode |= O_BINARY;

  627.   if ((opts & OPF_TRY_CWD_FIRST) || IS_ABSOLUTE_PATH (string))
  628.     {
  629.       int i;

  630.       if (is_regular_file (string))
  631.         {
  632.           filename = alloca (strlen (string) + 1);
  633.           strcpy (filename, string);
  634.           fd = gdb_open_cloexec (filename, mode, 0);
  635.           if (fd >= 0)
  636.             goto done;
  637.         }
  638.       else
  639.         {
  640.           filename = NULL;
  641.           fd = -1;
  642.         }

  643.       if (!(opts & OPF_SEARCH_IN_PATH))
  644.         for (i = 0; string[i]; i++)
  645.           if (IS_DIR_SEPARATOR (string[i]))
  646.             goto done;
  647.     }

  648.   /* For dos paths, d:/foo -> /foo, and d:foo -> foo.  */
  649.   if (HAS_DRIVE_SPEC (string))
  650.     string = STRIP_DRIVE_SPEC (string);

  651.   /* /foo => foo, to avoid multiple slashes that Emacs doesn't like.  */
  652.   while (IS_DIR_SEPARATOR(string[0]))
  653.     string++;

  654.   /* ./foo => foo */
  655.   while (string[0] == '.' && IS_DIR_SEPARATOR (string[1]))
  656.     string += 2;

  657.   alloclen = strlen (path) + strlen (string) + 2;
  658.   filename = alloca (alloclen);
  659.   fd = -1;

  660.   dir_vec = dirnames_to_char_ptr_vec (path);
  661.   back_to = make_cleanup_free_char_ptr_vec (dir_vec);

  662.   for (ix = 0; VEC_iterate (char_ptr, dir_vec, ix, dir); ++ix)
  663.     {
  664.       size_t len = strlen (dir);

  665.       if (strcmp (dir, "$cwd") == 0)
  666.         {
  667.           /* Name is $cwd -- insert current directory name instead.  */
  668.           int newlen;

  669.           /* First, realloc the filename buffer if too short.  */
  670.           len = strlen (current_directory);
  671.           newlen = len + strlen (string) + 2;
  672.           if (newlen > alloclen)
  673.             {
  674.               alloclen = newlen;
  675.               filename = alloca (alloclen);
  676.             }
  677.           strcpy (filename, current_directory);
  678.         }
  679.       else if (strchr(dir, '~'))
  680.         {
  681.          /* See whether we need to expand the tilde.  */
  682.           int newlen;
  683.           char *tilde_expanded;

  684.           tilde_expanded  = tilde_expand (dir);

  685.           /* First, realloc the filename buffer if too short.  */
  686.           len = strlen (tilde_expanded);
  687.           newlen = len + strlen (string) + 2;
  688.           if (newlen > alloclen)
  689.             {
  690.               alloclen = newlen;
  691.               filename = alloca (alloclen);
  692.             }
  693.           strcpy (filename, tilde_expanded);
  694.           xfree (tilde_expanded);
  695.         }
  696.       else
  697.         {
  698.           /* Normal file name in path -- just use it.  */
  699.           strcpy (filename, dir);

  700.           /* Don't search $cdir.  It's also a magic path like $cwd, but we
  701.              don't have enough information to expand it.  The user *could*
  702.              have an actual directory named '$cdir' but handling that would
  703.              be confusing, it would mean different things in different
  704.              contexts.  If the user really has '$cdir' one can use './$cdir'.
  705.              We can get $cdir when loading scripts.  When loading source files
  706.              $cdir must have already been expanded to the correct value.  */
  707.           if (strcmp (dir, "$cdir") == 0)
  708.             continue;
  709.         }

  710.       /* Remove trailing slashes.  */
  711.       while (len > 0 && IS_DIR_SEPARATOR (filename[len - 1]))
  712.         filename[--len] = 0;

  713.       strcat (filename + len, SLASH_STRING);
  714.       strcat (filename, string);

  715.       if (is_regular_file (filename))
  716.         {
  717.           fd = gdb_open_cloexec (filename, mode, 0);
  718.           if (fd >= 0)
  719.             break;
  720.         }
  721.     }

  722.   do_cleanups (back_to);

  723. done:
  724.   if (filename_opened)
  725.     {
  726.       /* If a file was opened, canonicalize its filename.  */
  727.       if (fd < 0)
  728.         *filename_opened = NULL;
  729.       else if ((opts & OPF_RETURN_REALPATH) != 0)
  730.         *filename_opened = gdb_realpath (filename);
  731.       else
  732.         *filename_opened = gdb_abspath (filename);
  733.     }

  734.   return fd;
  735. }


  736. /* This is essentially a convenience, for clients that want the behaviour
  737.    of openp, using source_path, but that really don't want the file to be
  738.    opened but want instead just to know what the full pathname is (as
  739.    qualified against source_path).

  740.    The current working directory is searched first.

  741.    If the file was found, this function returns 1, and FULL_PATHNAME is
  742.    set to the fully-qualified pathname.

  743.    Else, this functions returns 0, and FULL_PATHNAME is set to NULL.  */
  744. int
  745. source_full_path_of (const char *filename, char **full_pathname)
  746. {
  747.   int fd;

  748.   fd = openp (source_path,
  749.               OPF_TRY_CWD_FIRST | OPF_SEARCH_IN_PATH | OPF_RETURN_REALPATH,
  750.               filename, O_RDONLY, full_pathname);
  751.   if (fd < 0)
  752.     {
  753.       *full_pathname = NULL;
  754.       return 0;
  755.     }

  756.   close (fd);
  757.   return 1;
  758. }

  759. /* Return non-zero if RULE matches PATH, that is if the rule can be
  760.    applied to PATH.  */

  761. static int
  762. substitute_path_rule_matches (const struct substitute_path_rule *rule,
  763.                               const char *path)
  764. {
  765.   const int from_len = strlen (rule->from);
  766.   const int path_len = strlen (path);

  767.   if (path_len < from_len)
  768.     return 0;

  769.   /* The substitution rules are anchored at the start of the path,
  770.      so the path should start with rule->from.  */

  771.   if (filename_ncmp (path, rule->from, from_len) != 0)
  772.     return 0;

  773.   /* Make sure that the region in the path that matches the substitution
  774.      rule is immediately followed by a directory separator (or the end of
  775.      string character).  */

  776.   if (path[from_len] != '\0' && !IS_DIR_SEPARATOR (path[from_len]))
  777.     return 0;

  778.   return 1;
  779. }

  780. /* Find the substitute-path rule that applies to PATH and return it.
  781.    Return NULL if no rule applies.  */

  782. static struct substitute_path_rule *
  783. get_substitute_path_rule (const char *path)
  784. {
  785.   struct substitute_path_rule *rule = substitute_path_rules;

  786.   while (rule != NULL && !substitute_path_rule_matches (rule, path))
  787.     rule = rule->next;

  788.   return rule;
  789. }

  790. /* If the user specified a source path substitution rule that applies
  791.    to PATH, then apply it and return the new path.  This new path must
  792.    be deallocated afterwards.

  793.    Return NULL if no substitution rule was specified by the user,
  794.    or if no rule applied to the given PATH.  */

  795. char *
  796. rewrite_source_path (const char *path)
  797. {
  798.   const struct substitute_path_rule *rule = get_substitute_path_rule (path);
  799.   char *new_path;
  800.   int from_len;

  801.   if (rule == NULL)
  802.     return NULL;

  803.   from_len = strlen (rule->from);

  804.   /* Compute the rewritten path and return it.  */

  805.   new_path =
  806.     (char *) xmalloc (strlen (path) + 1 + strlen (rule->to) - from_len);
  807.   strcpy (new_path, rule->to);
  808.   strcat (new_path, path + from_len);

  809.   return new_path;
  810. }

  811. int
  812. find_and_open_source (const char *filename,
  813.                       const char *dirname,
  814.                       char **fullname)
  815. {
  816.   char *path = source_path;
  817.   const char *p;
  818.   int result;
  819.   struct cleanup *cleanup;

  820.   /* Quick way out if we already know its full name.  */

  821.   if (*fullname)
  822.     {
  823.       /* The user may have requested that source paths be rewritten
  824.          according to substitution rules he provided.  If a substitution
  825.          rule applies to this path, then apply it.  */
  826.       char *rewritten_fullname = rewrite_source_path (*fullname);

  827.       if (rewritten_fullname != NULL)
  828.         {
  829.           xfree (*fullname);
  830.           *fullname = rewritten_fullname;
  831.         }

  832.       result = gdb_open_cloexec (*fullname, OPEN_MODE, 0);
  833.       if (result >= 0)
  834.         {
  835.           char *lpath = gdb_realpath (*fullname);

  836.           xfree (*fullname);
  837.           *fullname = lpath;
  838.           return result;
  839.         }

  840.       /* Didn't work -- free old one, try again.  */
  841.       xfree (*fullname);
  842.       *fullname = NULL;
  843.     }

  844.   cleanup = make_cleanup (null_cleanup, NULL);

  845.   if (dirname != NULL)
  846.     {
  847.       /* If necessary, rewrite the compilation directory name according
  848.          to the source path substitution rules specified by the user.  */

  849.       char *rewritten_dirname = rewrite_source_path (dirname);

  850.       if (rewritten_dirname != NULL)
  851.         {
  852.           make_cleanup (xfree, rewritten_dirname);
  853.           dirname = rewritten_dirname;
  854.         }

  855.       /* Replace a path entry of $cdir with the compilation directory
  856.          name.  */
  857. #define        cdir_len        5
  858.       /* We cast strstr's result in case an ANSIhole has made it const,
  859.          which produces a "required warning" when assigned to a nonconst.  */
  860.       p = (char *) strstr (source_path, "$cdir");
  861.       if (p && (p == path || p[-1] == DIRNAME_SEPARATOR)
  862.           && (p[cdir_len] == DIRNAME_SEPARATOR || p[cdir_len] == '\0'))
  863.         {
  864.           int len;

  865.           path = (char *)
  866.             alloca (strlen (source_path) + 1 + strlen (dirname) + 1);
  867.           len = p - source_path;
  868.           strncpy (path, source_path, len);        /* Before $cdir */
  869.           strcpy (path + len, dirname);                /* new stuff */
  870.           strcat (path + len, source_path + len + cdir_len);        /* After
  871.                                                                    $cdir */
  872.         }
  873.     }

  874.   if (IS_ABSOLUTE_PATH (filename))
  875.     {
  876.       /* If filename is absolute path, try the source path
  877.          substitution on it.  */
  878.       char *rewritten_filename = rewrite_source_path (filename);

  879.       if (rewritten_filename != NULL)
  880.         {
  881.           make_cleanup (xfree, rewritten_filename);
  882.           filename = rewritten_filename;
  883.         }
  884.     }

  885.   result = openp (path, OPF_SEARCH_IN_PATH | OPF_RETURN_REALPATH, filename,
  886.                   OPEN_MODE, fullname);
  887.   if (result < 0)
  888.     {
  889.       /* Didn't work.  Try using just the basename.  */
  890.       p = lbasename (filename);
  891.       if (p != filename)
  892.         result = openp (path, OPF_SEARCH_IN_PATH | OPF_RETURN_REALPATH, p,
  893.                         OPEN_MODE, fullname);
  894.     }

  895.   do_cleanups (cleanup);
  896.   return result;
  897. }

  898. /* Open a source file given a symtab S.  Returns a file descriptor or
  899.    negative number for error.

  900.    This function is a convience function to find_and_open_source.  */

  901. int
  902. open_source_file (struct symtab *s)
  903. {
  904.   if (!s)
  905.     return -1;

  906.   return find_and_open_source (s->filename, SYMTAB_DIRNAME (s), &s->fullname);
  907. }

  908. /* Finds the fullname that a symtab represents.

  909.    This functions finds the fullname and saves it in s->fullname.
  910.    It will also return the value.

  911.    If this function fails to find the file that this symtab represents,
  912.    the expected fullname is used.  Therefore the files does not have to
  913.    exist.  */

  914. const char *
  915. symtab_to_fullname (struct symtab *s)
  916. {
  917.   /* Use cached copy if we have it.
  918.      We rely on forget_cached_source_info being called appropriately
  919.      to handle cases like the file being moved.  */
  920.   if (s->fullname == NULL)
  921.     {
  922.       int fd = find_and_open_source (s->filename, SYMTAB_DIRNAME (s),
  923.                                      &s->fullname);

  924.       if (fd >= 0)
  925.         close (fd);
  926.       else
  927.         {
  928.           char *fullname;
  929.           struct cleanup *back_to;

  930.           /* rewrite_source_path would be applied by find_and_open_source, we
  931.              should report the pathname where GDB tried to find the file.  */

  932.           if (SYMTAB_DIRNAME (s) == NULL || IS_ABSOLUTE_PATH (s->filename))
  933.             fullname = xstrdup (s->filename);
  934.           else
  935.             fullname = concat (SYMTAB_DIRNAME (s), SLASH_STRING, s->filename,
  936.                                NULL);

  937.           back_to = make_cleanup (xfree, fullname);
  938.           s->fullname = rewrite_source_path (fullname);
  939.           if (s->fullname == NULL)
  940.             s->fullname = xstrdup (fullname);
  941.           do_cleanups (back_to);
  942.         }
  943.     }

  944.   return s->fullname;
  945. }

  946. /* See commentary in source.h.  */

  947. const char *
  948. symtab_to_filename_for_display (struct symtab *symtab)
  949. {
  950.   if (filename_display_string == filename_display_basename)
  951.     return lbasename (symtab->filename);
  952.   else if (filename_display_string == filename_display_absolute)
  953.     return symtab_to_fullname (symtab);
  954.   else if (filename_display_string == filename_display_relative)
  955.     return symtab->filename;
  956.   else
  957.     internal_error (__FILE__, __LINE__, _("invalid filename_display_string"));
  958. }

  959. /* Create and initialize the table S->line_charpos that records
  960.    the positions of the lines in the source file, which is assumed
  961.    to be open on descriptor DESC.
  962.    All set S->nlines to the number of such lines.  */

  963. void
  964. find_source_lines (struct symtab *s, int desc)
  965. {
  966.   struct stat st;
  967.   char *data, *p, *end;
  968.   int nlines = 0;
  969.   int lines_allocated = 1000;
  970.   int *line_charpos;
  971.   long mtime = 0;
  972.   int size;

  973.   gdb_assert (s);
  974.   line_charpos = (int *) xmalloc (lines_allocated * sizeof (int));
  975.   if (fstat (desc, &st) < 0)
  976.     perror_with_name (symtab_to_filename_for_display (s));

  977.   if (SYMTAB_OBJFILE (s) != NULL && SYMTAB_OBJFILE (s)->obfd != NULL)
  978.     mtime = SYMTAB_OBJFILE (s)->mtime;
  979.   else if (exec_bfd)
  980.     mtime = exec_bfd_mtime;

  981.   if (mtime && mtime < st.st_mtime)
  982.     warning (_("Source file is more recent than executable."));

  983.   {
  984.     struct cleanup *old_cleanups;

  985.     /* st_size might be a large type, but we only support source files whose
  986.        size fits in an int.  */
  987.     size = (int) st.st_size;

  988.     /* Use malloc, not alloca, because this may be pretty large, and we may
  989.        run into various kinds of limits on stack size.  */
  990.     data = (char *) xmalloc (size);
  991.     old_cleanups = make_cleanup (xfree, data);

  992.     /* Reassign `size' to result of read for systems where \r\n -> \n.  */
  993.     size = myread (desc, data, size);
  994.     if (size < 0)
  995.       perror_with_name (symtab_to_filename_for_display (s));
  996.     end = data + size;
  997.     p = data;
  998.     line_charpos[0] = 0;
  999.     nlines = 1;
  1000.     while (p != end)
  1001.       {
  1002.         if (*p++ == '\n'
  1003.         /* A newline at the end does not start a new line.  */
  1004.             && p != end)
  1005.           {
  1006.             if (nlines == lines_allocated)
  1007.               {
  1008.                 lines_allocated *= 2;
  1009.                 line_charpos =
  1010.                   (int *) xrealloc ((char *) line_charpos,
  1011.                                     sizeof (int) * lines_allocated);
  1012.               }
  1013.             line_charpos[nlines++] = p - data;
  1014.           }
  1015.       }
  1016.     do_cleanups (old_cleanups);
  1017.   }

  1018.   s->nlines = nlines;
  1019.   s->line_charpos =
  1020.     (int *) xrealloc ((char *) line_charpos, nlines * sizeof (int));

  1021. }



  1022. /* Get full pathname and line number positions for a symtab.
  1023.    Return nonzero if line numbers may have changed.
  1024.    Set *FULLNAME to actual name of the file as found by `openp',
  1025.    or to 0 if the file is not found.  */

  1026. static int
  1027. get_filename_and_charpos (struct symtab *s, char **fullname)
  1028. {
  1029.   int desc, linenums_changed = 0;
  1030.   struct cleanup *cleanups;

  1031.   desc = open_source_file (s);
  1032.   if (desc < 0)
  1033.     {
  1034.       if (fullname)
  1035.         *fullname = NULL;
  1036.       return 0;
  1037.     }
  1038.   cleanups = make_cleanup_close (desc);
  1039.   if (fullname)
  1040.     *fullname = s->fullname;
  1041.   if (s->line_charpos == 0)
  1042.     linenums_changed = 1;
  1043.   if (linenums_changed)
  1044.     find_source_lines (s, desc);
  1045.   do_cleanups (cleanups);
  1046.   return linenums_changed;
  1047. }

  1048. /* Print text describing the full name of the source file S
  1049.    and the line number LINE and its corresponding character position.
  1050.    The text starts with two Ctrl-z so that the Emacs-GDB interface
  1051.    can easily find it.

  1052.    MID_STATEMENT is nonzero if the PC is not at the beginning of that line.

  1053.    Return 1 if successful, 0 if could not find the file.  */

  1054. int
  1055. identify_source_line (struct symtab *s, int line, int mid_statement,
  1056.                       CORE_ADDR pc)
  1057. {
  1058.   if (s->line_charpos == 0)
  1059.     get_filename_and_charpos (s, (char **) NULL);
  1060.   if (s->fullname == 0)
  1061.     return 0;
  1062.   if (line > s->nlines)
  1063.     /* Don't index off the end of the line_charpos array.  */
  1064.     return 0;
  1065.   annotate_source (s->fullname, line, s->line_charpos[line - 1],
  1066.                    mid_statement, get_objfile_arch (SYMTAB_OBJFILE (s)), pc);

  1067.   current_source_line = line;
  1068.   current_source_symtab = s;
  1069.   clear_lines_listed_range ();
  1070.   return 1;
  1071. }


  1072. /* Print source lines from the file of symtab S,
  1073.    starting with line number LINE and stopping before line number STOPLINE.  */

  1074. static void
  1075. print_source_lines_base (struct symtab *s, int line, int stopline,
  1076.                          enum print_source_lines_flags flags)
  1077. {
  1078.   int c;
  1079.   int desc;
  1080.   int noprint = 0;
  1081.   FILE *stream;
  1082.   int nlines = stopline - line;
  1083.   struct cleanup *cleanup;
  1084.   struct ui_out *uiout = current_uiout;

  1085.   /* Regardless of whether we can open the file, set current_source_symtab.  */
  1086.   current_source_symtab = s;
  1087.   current_source_line = line;
  1088.   first_line_listed = line;

  1089.   /* If printing of source lines is disabled, just print file and line
  1090.      number.  */
  1091.   if (ui_out_test_flags (uiout, ui_source_list))
  1092.     {
  1093.       /* Only prints "No such file or directory" once.  */
  1094.       if ((s != last_source_visited) || (!last_source_error))
  1095.         {
  1096.           last_source_visited = s;
  1097.           desc = open_source_file (s);
  1098.         }
  1099.       else
  1100.         {
  1101.           desc = last_source_error;
  1102.           flags |= PRINT_SOURCE_LINES_NOERROR;
  1103.         }
  1104.     }
  1105.   else
  1106.     {
  1107.       desc = last_source_error;
  1108.           flags |= PRINT_SOURCE_LINES_NOERROR;
  1109.       noprint = 1;
  1110.     }

  1111.   if (desc < 0 || noprint)
  1112.     {
  1113.       last_source_error = desc;

  1114.       if (!(flags & PRINT_SOURCE_LINES_NOERROR))
  1115.         {
  1116.           const char *filename = symtab_to_filename_for_display (s);
  1117.           int len = strlen (filename) + 100;
  1118.           char *name = alloca (len);

  1119.           xsnprintf (name, len, "%d\t%s", line, filename);
  1120.           print_sys_errmsg (name, errno);
  1121.         }
  1122.       else
  1123.         {
  1124.           ui_out_field_int (uiout, "line", line);
  1125.           ui_out_text (uiout, "\tin ");

  1126.           /* CLI expects only the "file" field.  TUI expects only the
  1127.              "fullname" field (and TUI does break if "file" is printed).
  1128.              MI expects both fields.  ui_source_list is set only for CLI,
  1129.              not for TUI.  */
  1130.           if (ui_out_is_mi_like_p (uiout)
  1131.               || ui_out_test_flags (uiout, ui_source_list))
  1132.             ui_out_field_string (uiout, "file",
  1133.                                  symtab_to_filename_for_display (s));
  1134.           if (ui_out_is_mi_like_p (uiout)
  1135.               || !ui_out_test_flags (uiout, ui_source_list))
  1136.              {
  1137.               const char *s_fullname = symtab_to_fullname (s);
  1138.               char *local_fullname;

  1139.               /* ui_out_field_string may free S_FULLNAME by calling
  1140.                  open_source_file for it again.  See e.g.,
  1141.                  tui_field_string->tui_show_source.  */
  1142.               local_fullname = alloca (strlen (s_fullname) + 1);
  1143.               strcpy (local_fullname, s_fullname);

  1144.               ui_out_field_string (uiout, "fullname", local_fullname);
  1145.              }

  1146.           ui_out_text (uiout, "\n");
  1147.         }

  1148.       return;
  1149.     }

  1150.   last_source_error = 0;

  1151.   if (s->line_charpos == 0)
  1152.     find_source_lines (s, desc);

  1153.   if (line < 1 || line > s->nlines)
  1154.     {
  1155.       close (desc);
  1156.       error (_("Line number %d out of range; %s has %d lines."),
  1157.              line, symtab_to_filename_for_display (s), s->nlines);
  1158.     }

  1159.   if (lseek (desc, s->line_charpos[line - 1], 0) < 0)
  1160.     {
  1161.       close (desc);
  1162.       perror_with_name (symtab_to_filename_for_display (s));
  1163.     }

  1164.   stream = fdopen (desc, FDOPEN_MODE);
  1165.   clearerr (stream);
  1166.   cleanup = make_cleanup_fclose (stream);

  1167.   while (nlines-- > 0)
  1168.     {
  1169.       char buf[20];

  1170.       c = fgetc (stream);
  1171.       if (c == EOF)
  1172.         break;
  1173.       last_line_listed = current_source_line;
  1174.       if (flags & PRINT_SOURCE_LINES_FILENAME)
  1175.         {
  1176.           ui_out_text (uiout, symtab_to_filename_for_display (s));
  1177.           ui_out_text (uiout, ":");
  1178.         }
  1179.       xsnprintf (buf, sizeof (buf), "%d\t", current_source_line++);
  1180.       ui_out_text (uiout, buf);
  1181.       do
  1182.         {
  1183.           if (c < 040 && c != '\t' && c != '\n' && c != '\r')
  1184.             {
  1185.               xsnprintf (buf, sizeof (buf), "^%c", c + 0100);
  1186.               ui_out_text (uiout, buf);
  1187.             }
  1188.           else if (c == 0177)
  1189.             ui_out_text (uiout, "^?");
  1190.           else if (c == '\r')
  1191.             {
  1192.               /* Skip a \r character, but only before a \n.  */
  1193.               int c1 = fgetc (stream);

  1194.               if (c1 != '\n')
  1195.                 printf_filtered ("^%c", c + 0100);
  1196.               if (c1 != EOF)
  1197.                 ungetc (c1, stream);
  1198.             }
  1199.           else
  1200.             {
  1201.               xsnprintf (buf, sizeof (buf), "%c", c);
  1202.               ui_out_text (uiout, buf);
  1203.             }
  1204.         }
  1205.       while (c != '\n' && (c = fgetc (stream)) >= 0);
  1206.     }

  1207.   do_cleanups (cleanup);
  1208. }

  1209. /* Show source lines from the file of symtab S, starting with line
  1210.    number LINE and stopping before line number STOPLINE.  If this is
  1211.    not the command line version, then the source is shown in the source
  1212.    window otherwise it is simply printed.  */

  1213. void
  1214. print_source_lines (struct symtab *s, int line, int stopline,
  1215.                     enum print_source_lines_flags flags)
  1216. {
  1217.   print_source_lines_base (s, line, stopline, flags);
  1218. }

  1219. /* Print info on range of pc's in a specified line.  */

  1220. static void
  1221. line_info (char *arg, int from_tty)
  1222. {
  1223.   struct symtabs_and_lines sals;
  1224.   struct symtab_and_line sal;
  1225.   CORE_ADDR start_pc, end_pc;
  1226.   int i;
  1227.   struct cleanup *cleanups;

  1228.   init_sal (&sal);                /* initialize to zeroes */

  1229.   if (arg == 0)
  1230.     {
  1231.       sal.symtab = current_source_symtab;
  1232.       sal.pspace = current_program_space;
  1233.       if (last_line_listed != 0)
  1234.         sal.line = last_line_listed;
  1235.       else
  1236.         sal.line = current_source_line;

  1237.       sals.nelts = 1;
  1238.       sals.sals = (struct symtab_and_line *)
  1239.         xmalloc (sizeof (struct symtab_and_line));
  1240.       sals.sals[0] = sal;
  1241.     }
  1242.   else
  1243.     {
  1244.       sals = decode_line_with_last_displayed (arg, DECODE_LINE_LIST_MODE);

  1245.       dont_repeat ();
  1246.     }

  1247.   cleanups = make_cleanup (xfree, sals.sals);

  1248.   /* C++  More than one line may have been specified, as when the user
  1249.      specifies an overloaded function name.  Print info on them all.  */
  1250.   for (i = 0; i < sals.nelts; i++)
  1251.     {
  1252.       sal = sals.sals[i];
  1253.       if (sal.pspace != current_program_space)
  1254.         continue;

  1255.       if (sal.symtab == 0)
  1256.         {
  1257.           struct gdbarch *gdbarch = get_current_arch ();

  1258.           printf_filtered (_("No line number information available"));
  1259.           if (sal.pc != 0)
  1260.             {
  1261.               /* This is useful for "info line *0x7f34".  If we can't tell the
  1262.                  user about a source line, at least let them have the symbolic
  1263.                  address.  */
  1264.               printf_filtered (" for address ");
  1265.               wrap_here ("  ");
  1266.               print_address (gdbarch, sal.pc, gdb_stdout);
  1267.             }
  1268.           else
  1269.             printf_filtered (".");
  1270.           printf_filtered ("\n");
  1271.         }
  1272.       else if (sal.line > 0
  1273.                && find_line_pc_range (sal, &start_pc, &end_pc))
  1274.         {
  1275.           struct gdbarch *gdbarch
  1276.             = get_objfile_arch (SYMTAB_OBJFILE (sal.symtab));

  1277.           if (start_pc == end_pc)
  1278.             {
  1279.               printf_filtered ("Line %d of \"%s\"",
  1280.                                sal.line,
  1281.                                symtab_to_filename_for_display (sal.symtab));
  1282.               wrap_here ("  ");
  1283.               printf_filtered (" is at address ");
  1284.               print_address (gdbarch, start_pc, gdb_stdout);
  1285.               wrap_here ("  ");
  1286.               printf_filtered (" but contains no code.\n");
  1287.             }
  1288.           else
  1289.             {
  1290.               printf_filtered ("Line %d of \"%s\"",
  1291.                                sal.line,
  1292.                                symtab_to_filename_for_display (sal.symtab));
  1293.               wrap_here ("  ");
  1294.               printf_filtered (" starts at address ");
  1295.               print_address (gdbarch, start_pc, gdb_stdout);
  1296.               wrap_here ("  ");
  1297.               printf_filtered (" and ends at ");
  1298.               print_address (gdbarch, end_pc, gdb_stdout);
  1299.               printf_filtered (".\n");
  1300.             }

  1301.           /* x/i should display this line's code.  */
  1302.           set_next_address (gdbarch, start_pc);

  1303.           /* Repeating "info line" should do the following line.  */
  1304.           last_line_listed = sal.line + 1;

  1305.           /* If this is the only line, show the source code.  If it could
  1306.              not find the file, don't do anything special.  */
  1307.           if (annotation_level && sals.nelts == 1)
  1308.             identify_source_line (sal.symtab, sal.line, 0, start_pc);
  1309.         }
  1310.       else
  1311.         /* Is there any case in which we get here, and have an address
  1312.            which the user would want to see?  If we have debugging symbols
  1313.            and no line numbers?  */
  1314.         printf_filtered (_("Line number %d is out of range for \"%s\".\n"),
  1315.                          sal.line, symtab_to_filename_for_display (sal.symtab));
  1316.     }
  1317.   do_cleanups (cleanups);
  1318. }

  1319. /* Commands to search the source file for a regexp.  */

  1320. static void
  1321. forward_search_command (char *regex, int from_tty)
  1322. {
  1323.   int c;
  1324.   int desc;
  1325.   FILE *stream;
  1326.   int line;
  1327.   char *msg;
  1328.   struct cleanup *cleanups;

  1329.   line = last_line_listed + 1;

  1330.   msg = (char *) re_comp (regex);
  1331.   if (msg)
  1332.     error (("%s"), msg);

  1333.   if (current_source_symtab == 0)
  1334.     select_source_symtab (0);

  1335.   desc = open_source_file (current_source_symtab);
  1336.   if (desc < 0)
  1337.     perror_with_name (symtab_to_filename_for_display (current_source_symtab));
  1338.   cleanups = make_cleanup_close (desc);

  1339.   if (current_source_symtab->line_charpos == 0)
  1340.     find_source_lines (current_source_symtab, desc);

  1341.   if (line < 1 || line > current_source_symtab->nlines)
  1342.     error (_("Expression not found"));

  1343.   if (lseek (desc, current_source_symtab->line_charpos[line - 1], 0) < 0)
  1344.     perror_with_name (symtab_to_filename_for_display (current_source_symtab));

  1345.   discard_cleanups (cleanups);
  1346.   stream = fdopen (desc, FDOPEN_MODE);
  1347.   clearerr (stream);
  1348.   cleanups = make_cleanup_fclose (stream);
  1349.   while (1)
  1350.     {
  1351.       static char *buf = NULL;
  1352.       char *p;
  1353.       int cursize, newsize;

  1354.       cursize = 256;
  1355.       buf = xmalloc (cursize);
  1356.       p = buf;

  1357.       c = fgetc (stream);
  1358.       if (c == EOF)
  1359.         break;
  1360.       do
  1361.         {
  1362.           *p++ = c;
  1363.           if (p - buf == cursize)
  1364.             {
  1365.               newsize = cursize + cursize / 2;
  1366.               buf = xrealloc (buf, newsize);
  1367.               p = buf + cursize;
  1368.               cursize = newsize;
  1369.             }
  1370.         }
  1371.       while (c != '\n' && (c = fgetc (stream)) >= 0);

  1372.       /* Remove the \r, if any, at the end of the line, otherwise
  1373.          regular expressions that end with $ or \n won't work.  */
  1374.       if (p - buf > 1 && p[-2] == '\r')
  1375.         {
  1376.           p--;
  1377.           p[-1] = '\n';
  1378.         }

  1379.       /* We now have a source line in buf, null terminate and match.  */
  1380.       *p = 0;
  1381.       if (re_exec (buf) > 0)
  1382.         {
  1383.           /* Match!  */
  1384.           do_cleanups (cleanups);
  1385.           print_source_lines (current_source_symtab, line, line + 1, 0);
  1386.           set_internalvar_integer (lookup_internalvar ("_"), line);
  1387.           current_source_line = max (line - lines_to_list / 2, 1);
  1388.           return;
  1389.         }
  1390.       line++;
  1391.     }

  1392.   printf_filtered (_("Expression not found\n"));
  1393.   do_cleanups (cleanups);
  1394. }

  1395. static void
  1396. reverse_search_command (char *regex, int from_tty)
  1397. {
  1398.   int c;
  1399.   int desc;
  1400.   FILE *stream;
  1401.   int line;
  1402.   char *msg;
  1403.   struct cleanup *cleanups;

  1404.   line = last_line_listed - 1;

  1405.   msg = (char *) re_comp (regex);
  1406.   if (msg)
  1407.     error (("%s"), msg);

  1408.   if (current_source_symtab == 0)
  1409.     select_source_symtab (0);

  1410.   desc = open_source_file (current_source_symtab);
  1411.   if (desc < 0)
  1412.     perror_with_name (symtab_to_filename_for_display (current_source_symtab));
  1413.   cleanups = make_cleanup_close (desc);

  1414.   if (current_source_symtab->line_charpos == 0)
  1415.     find_source_lines (current_source_symtab, desc);

  1416.   if (line < 1 || line > current_source_symtab->nlines)
  1417.     error (_("Expression not found"));

  1418.   if (lseek (desc, current_source_symtab->line_charpos[line - 1], 0) < 0)
  1419.     perror_with_name (symtab_to_filename_for_display (current_source_symtab));

  1420.   discard_cleanups (cleanups);
  1421.   stream = fdopen (desc, FDOPEN_MODE);
  1422.   clearerr (stream);
  1423.   cleanups = make_cleanup_fclose (stream);
  1424.   while (line > 1)
  1425.     {
  1426. /* FIXME!!!  We walk right off the end of buf if we get a long line!!!  */
  1427.       char buf[4096];                /* Should be reasonable???  */
  1428.       char *p = buf;

  1429.       c = fgetc (stream);
  1430.       if (c == EOF)
  1431.         break;
  1432.       do
  1433.         {
  1434.           *p++ = c;
  1435.         }
  1436.       while (c != '\n' && (c = fgetc (stream)) >= 0);

  1437.       /* Remove the \r, if any, at the end of the line, otherwise
  1438.          regular expressions that end with $ or \n won't work.  */
  1439.       if (p - buf > 1 && p[-2] == '\r')
  1440.         {
  1441.           p--;
  1442.           p[-1] = '\n';
  1443.         }

  1444.       /* We now have a source line in buf; null terminate and match.  */
  1445.       *p = 0;
  1446.       if (re_exec (buf) > 0)
  1447.         {
  1448.           /* Match!  */
  1449.           do_cleanups (cleanups);
  1450.           print_source_lines (current_source_symtab, line, line + 1, 0);
  1451.           set_internalvar_integer (lookup_internalvar ("_"), line);
  1452.           current_source_line = max (line - lines_to_list / 2, 1);
  1453.           return;
  1454.         }
  1455.       line--;
  1456.       if (fseek (stream, current_source_symtab->line_charpos[line - 1], 0) < 0)
  1457.         {
  1458.           const char *filename;

  1459.           do_cleanups (cleanups);
  1460.           filename = symtab_to_filename_for_display (current_source_symtab);
  1461.           perror_with_name (filename);
  1462.         }
  1463.     }

  1464.   printf_filtered (_("Expression not found\n"));
  1465.   do_cleanups (cleanups);
  1466.   return;
  1467. }

  1468. /* If the last character of PATH is a directory separator, then strip it.  */

  1469. static void
  1470. strip_trailing_directory_separator (char *path)
  1471. {
  1472.   const int last = strlen (path) - 1;

  1473.   if (last < 0)
  1474.     return/* No stripping is needed if PATH is the empty string.  */

  1475.   if (IS_DIR_SEPARATOR (path[last]))
  1476.     path[last] = '\0';
  1477. }

  1478. /* Return the path substitution rule that matches FROM.
  1479.    Return NULL if no rule matches.  */

  1480. static struct substitute_path_rule *
  1481. find_substitute_path_rule (const char *from)
  1482. {
  1483.   struct substitute_path_rule *rule = substitute_path_rules;

  1484.   while (rule != NULL)
  1485.     {
  1486.       if (FILENAME_CMP (rule->from, from) == 0)
  1487.         return rule;
  1488.       rule = rule->next;
  1489.     }

  1490.   return NULL;
  1491. }

  1492. /* Add a new substitute-path rule at the end of the current list of rules.
  1493.    The new rule will replace FROM into TO.  */

  1494. void
  1495. add_substitute_path_rule (char *from, char *to)
  1496. {
  1497.   struct substitute_path_rule *rule;
  1498.   struct substitute_path_rule *new_rule;

  1499.   new_rule = xmalloc (sizeof (struct substitute_path_rule));
  1500.   new_rule->from = xstrdup (from);
  1501.   new_rule->to = xstrdup (to);
  1502.   new_rule->next = NULL;

  1503.   /* If the list of rules are empty, then insert the new rule
  1504.      at the head of the list.  */

  1505.   if (substitute_path_rules == NULL)
  1506.     {
  1507.       substitute_path_rules = new_rule;
  1508.       return;
  1509.     }

  1510.   /* Otherwise, skip to the last rule in our list and then append
  1511.      the new rule.  */

  1512.   rule = substitute_path_rules;
  1513.   while (rule->next != NULL)
  1514.     rule = rule->next;

  1515.   rule->next = new_rule;
  1516. }

  1517. /* Remove the given source path substitution rule from the current list
  1518.    of rules.  The memory allocated for that rule is also deallocated.  */

  1519. static void
  1520. delete_substitute_path_rule (struct substitute_path_rule *rule)
  1521. {
  1522.   if (rule == substitute_path_rules)
  1523.     substitute_path_rules = rule->next;
  1524.   else
  1525.     {
  1526.       struct substitute_path_rule *prev = substitute_path_rules;

  1527.       while (prev != NULL && prev->next != rule)
  1528.         prev = prev->next;

  1529.       gdb_assert (prev != NULL);

  1530.       prev->next = rule->next;
  1531.     }

  1532.   xfree (rule->from);
  1533.   xfree (rule->to);
  1534.   xfree (rule);
  1535. }

  1536. /* Implement the "show substitute-path" command.  */

  1537. static void
  1538. show_substitute_path_command (char *args, int from_tty)
  1539. {
  1540.   struct substitute_path_rule *rule = substitute_path_rules;
  1541.   char **argv;
  1542.   char *from = NULL;
  1543.   struct cleanup *cleanup;

  1544.   argv = gdb_buildargv (args);
  1545.   cleanup = make_cleanup_freeargv (argv);

  1546.   /* We expect zero or one argument.  */

  1547.   if (argv != NULL && argv[0] != NULL && argv[1] != NULL)
  1548.     error (_("Too many arguments in command"));

  1549.   if (argv != NULL && argv[0] != NULL)
  1550.     from = argv[0];

  1551.   /* Print the substitution rules.  */

  1552.   if (from != NULL)
  1553.     printf_filtered
  1554.       (_("Source path substitution rule matching `%s':\n"), from);
  1555.   else
  1556.     printf_filtered (_("List of all source path substitution rules:\n"));

  1557.   while (rule != NULL)
  1558.     {
  1559.       if (from == NULL || substitute_path_rule_matches (rule, from) != 0)
  1560.         printf_filtered ("  `%s' -> `%s'.\n", rule->from, rule->to);
  1561.       rule = rule->next;
  1562.     }

  1563.   do_cleanups (cleanup);
  1564. }

  1565. /* Implement the "unset substitute-path" command.  */

  1566. static void
  1567. unset_substitute_path_command (char *args, int from_tty)
  1568. {
  1569.   struct substitute_path_rule *rule = substitute_path_rules;
  1570.   char **argv = gdb_buildargv (args);
  1571.   char *from = NULL;
  1572.   int rule_found = 0;
  1573.   struct cleanup *cleanup;

  1574.   /* This function takes either 0 or 1 argument.  */

  1575.   cleanup = make_cleanup_freeargv (argv);
  1576.   if (argv != NULL && argv[0] != NULL && argv[1] != NULL)
  1577.     error (_("Incorrect usage, too many arguments in command"));

  1578.   if (argv != NULL && argv[0] != NULL)
  1579.     from = argv[0];

  1580.   /* If the user asked for all the rules to be deleted, ask him
  1581.      to confirm and give him a chance to abort before the action
  1582.      is performed.  */

  1583.   if (from == NULL
  1584.       && !query (_("Delete all source path substitution rules? ")))
  1585.     error (_("Canceled"));

  1586.   /* Delete the rule matching the argument.  No argument means that
  1587.      all rules should be deleted.  */

  1588.   while (rule != NULL)
  1589.     {
  1590.       struct substitute_path_rule *next = rule->next;

  1591.       if (from == NULL || FILENAME_CMP (from, rule->from) == 0)
  1592.         {
  1593.           delete_substitute_path_rule (rule);
  1594.           rule_found = 1;
  1595.         }

  1596.       rule = next;
  1597.     }

  1598.   /* If the user asked for a specific rule to be deleted but
  1599.      we could not find it, then report an error.  */

  1600.   if (from != NULL && !rule_found)
  1601.     error (_("No substitution rule defined for `%s'"), from);

  1602.   forget_cached_source_info ();

  1603.   do_cleanups (cleanup);
  1604. }

  1605. /* Add a new source path substitution rule.  */

  1606. static void
  1607. set_substitute_path_command (char *args, int from_tty)
  1608. {
  1609.   char **argv;
  1610.   struct substitute_path_rule *rule;
  1611.   struct cleanup *cleanup;

  1612.   argv = gdb_buildargv (args);
  1613.   cleanup = make_cleanup_freeargv (argv);

  1614.   if (argv == NULL || argv[0] == NULL || argv [1] == NULL)
  1615.     error (_("Incorrect usage, too few arguments in command"));

  1616.   if (argv[2] != NULL)
  1617.     error (_("Incorrect usage, too many arguments in command"));

  1618.   if (*(argv[0]) == '\0')
  1619.     error (_("First argument must be at least one character long"));

  1620.   /* Strip any trailing directory separator character in either FROM
  1621.      or TO.  The substitution rule already implicitly contains them.  */
  1622.   strip_trailing_directory_separator (argv[0]);
  1623.   strip_trailing_directory_separator (argv[1]);

  1624.   /* If a rule with the same "from" was previously defined, then
  1625.      delete it.  This new rule replaces it.  */

  1626.   rule = find_substitute_path_rule (argv[0]);
  1627.   if (rule != NULL)
  1628.     delete_substitute_path_rule (rule);

  1629.   /* Insert the new substitution rule.  */

  1630.   add_substitute_path_rule (argv[0], argv[1]);
  1631.   forget_cached_source_info ();

  1632.   do_cleanups (cleanup);
  1633. }


  1634. void
  1635. _initialize_source (void)
  1636. {
  1637.   struct cmd_list_element *c;

  1638.   current_source_symtab = 0;
  1639.   init_source_path ();

  1640.   /* The intention is to use POSIX Basic Regular Expressions.
  1641.      Always use the GNU regex routine for consistency across all hosts.
  1642.      Our current GNU regex.c does not have all the POSIX features, so this is
  1643.      just an approximation.  */
  1644.   re_set_syntax (RE_SYNTAX_GREP);

  1645.   c = add_cmd ("directory", class_files, directory_command, _("\
  1646. Add directory DIR to beginning of search path for source files.\n\
  1647. Forget cached info on source file locations and line positions.\n\
  1648. DIR can also be $cwd for the current working directory, or $cdir for the\n\
  1649. directory in which the source file was compiled into object code.\n\
  1650. With no argument, reset the search path to $cdir:$cwd, the default."),
  1651.                &cmdlist);

  1652.   if (dbx_commands)
  1653.     add_com_alias ("use", "directory", class_files, 0);

  1654.   set_cmd_completer (c, filename_completer);

  1655.   add_setshow_optional_filename_cmd ("directories",
  1656.                                      class_files,
  1657.                                      &source_path,
  1658.                                      _("\
  1659. Set the search path for finding source files."),
  1660.                                      _("\
  1661. Show the search path for finding source files."),
  1662.                                      _("\
  1663. $cwd in the path means the current working directory.\n\
  1664. $cdir in the path means the compilation directory of the source file.\n\
  1665. GDB ensures the search path always ends with $cdir:$cwd by\n\
  1666. appending these directories if necessary.\n\
  1667. Setting the value to an empty string sets it to $cdir:$cwd, the default."),
  1668.                             set_directories_command,
  1669.                             show_directories_command,
  1670.                             &setlist, &showlist);

  1671.   if (xdb_commands)
  1672.     {
  1673.       add_com_alias ("D", "directory", class_files, 0);
  1674.       add_cmd ("ld", no_class, show_directories_1, _("\
  1675. Current search path for finding source files.\n\
  1676. $cwd in the path means the current working directory.\n\
  1677. $cdir in the path means the compilation directory of the source file."),
  1678.                &cmdlist);
  1679.     }

  1680.   add_info ("source", source_info,
  1681.             _("Information about the current source file."));

  1682.   add_info ("line", line_info, _("\
  1683. Core addresses of the code for a source line.\n\
  1684. Line can be specified as\n\
  1685.   LINENUM, to list around that line in current file,\n\
  1686.   FILE:LINENUM, to list around that line in that file,\n\
  1687.   FUNCTION, to list around beginning of that function,\n\
  1688.   FILE:FUNCTION, to distinguish among like-named static functions.\n\
  1689. Default is to describe the last source line that was listed.\n\n\
  1690. This sets the default address for \"x\" to the line's first instruction\n\
  1691. so that \"x/i\" suffices to start examining the machine code.\n\
  1692. The address is also stored as the value of \"$_\"."));

  1693.   add_com ("forward-search", class_files, forward_search_command, _("\
  1694. Search for regular expression (see regex(3)) from last line listed.\n\
  1695. The matching line number is also stored as the value of \"$_\"."));
  1696.   add_com_alias ("search", "forward-search", class_files, 0);
  1697.   add_com_alias ("fo", "forward-search", class_files, 1);

  1698.   add_com ("reverse-search", class_files, reverse_search_command, _("\
  1699. Search backward for regular expression (see regex(3)) from last line listed.\n\
  1700. The matching line number is also stored as the value of \"$_\"."));
  1701.   add_com_alias ("rev", "reverse-search", class_files, 1);

  1702.   if (xdb_commands)
  1703.     {
  1704.       add_com_alias ("/", "forward-search", class_files, 0);
  1705.       add_com_alias ("?", "reverse-search", class_files, 0);
  1706.     }

  1707.   add_setshow_integer_cmd ("listsize", class_support, &lines_to_list, _("\
  1708. Set number of source lines gdb will list by default."), _("\
  1709. Show number of source lines gdb will list by default."), _("\
  1710. Use this to choose how many source lines the \"list\" displays (unless\n\
  1711. the \"list\" argument explicitly specifies some other number).\n\
  1712. A value of \"unlimited\", or zero, means there's no limit."),
  1713.                             NULL,
  1714.                             show_lines_to_list,
  1715.                             &setlist, &showlist);

  1716.   add_cmd ("substitute-path", class_files, set_substitute_path_command,
  1717.            _("\
  1718. Usage: set substitute-path FROM TO\n\
  1719. Add a substitution rule replacing FROM into TO in source file names.\n\
  1720. If a substitution rule was previously set for FROM, the old rule\n\
  1721. is replaced by the new one."),
  1722.            &setlist);

  1723.   add_cmd ("substitute-path", class_files, unset_substitute_path_command,
  1724.            _("\
  1725. Usage: unset substitute-path [FROM]\n\
  1726. Delete the rule for substituting FROM in source file names.  If FROM\n\
  1727. is not specified, all substituting rules are deleted.\n\
  1728. If the debugger cannot find a rule for FROM, it will display a warning."),
  1729.            &unsetlist);

  1730.   add_cmd ("substitute-path", class_files, show_substitute_path_command,
  1731.            _("\
  1732. Usage: show substitute-path [FROM]\n\
  1733. Print the rule for substituting FROM in source file names. If FROM\n\
  1734. is not specified, print all substitution rules."),
  1735.            &showlist);

  1736.   add_setshow_enum_cmd ("filename-display", class_files,
  1737.                         filename_display_kind_names,
  1738.                         &filename_display_string, _("\
  1739. Set how to display filenames."), _("\
  1740. Show how to display filenames."), _("\
  1741. filename-display can be:\n\
  1742.   basename - display only basename of a filename\n\
  1743.   relative - display a filename relative to the compilation directory\n\
  1744.   absolute - display an absolute filename\n\
  1745. By default, relative filenames are displayed."),
  1746.                         NULL,
  1747.                         show_filename_display_string,
  1748.                         &setlist, &showlist);

  1749. }