GDB (API)
/home/stan/gdb/src/gdb/source.c
Go to the documentation of this file.
00001 /* List lines of source files for GDB, the GNU debugger.
00002    Copyright (C) 1986-2013 Free Software Foundation, Inc.
00003 
00004    This file is part of GDB.
00005 
00006    This program is free software; you can redistribute it and/or modify
00007    it under the terms of the GNU General Public License as published by
00008    the Free Software Foundation; either version 3 of the License, or
00009    (at your option) any later version.
00010 
00011    This program is distributed in the hope that it will be useful,
00012    but WITHOUT ANY WARRANTY; without even the implied warranty of
00013    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
00014    GNU General Public License for more details.
00015 
00016    You should have received a copy of the GNU General Public License
00017    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
00018 
00019 #include "defs.h"
00020 #include "arch-utils.h"
00021 #include "symtab.h"
00022 #include "expression.h"
00023 #include "language.h"
00024 #include "command.h"
00025 #include "source.h"
00026 #include "gdbcmd.h"
00027 #include "frame.h"
00028 #include "value.h"
00029 #include "gdb_assert.h"
00030 #include "filestuff.h"
00031 
00032 #include <sys/types.h>
00033 #include "gdb_string.h"
00034 #include "gdb_stat.h"
00035 #include <fcntl.h>
00036 #include "gdbcore.h"
00037 #include "gdb_regex.h"
00038 #include "symfile.h"
00039 #include "objfiles.h"
00040 #include "annotate.h"
00041 #include "gdbtypes.h"
00042 #include "linespec.h"
00043 #include "filenames.h"          /* for DOSish file names */
00044 #include "completer.h"
00045 #include "ui-out.h"
00046 #include "readline/readline.h"
00047 
00048 #define OPEN_MODE (O_RDONLY | O_BINARY)
00049 #define FDOPEN_MODE FOPEN_RB
00050 
00051 /* Prototypes for exported functions.  */
00052 
00053 void _initialize_source (void);
00054 
00055 /* Prototypes for local functions.  */
00056 
00057 static int get_filename_and_charpos (struct symtab *, char **);
00058 
00059 static void reverse_search_command (char *, int);
00060 
00061 static void forward_search_command (char *, int);
00062 
00063 static void line_info (char *, int);
00064 
00065 static void source_info (char *, int);
00066 
00067 /* Path of directories to search for source files.
00068    Same format as the PATH environment variable's value.  */
00069 
00070 char *source_path;
00071 
00072 /* Support for source path substitution commands.  */
00073 
00074 struct substitute_path_rule
00075 {
00076   char *from;
00077   char *to;
00078   struct substitute_path_rule *next;
00079 };
00080 
00081 static struct substitute_path_rule *substitute_path_rules = NULL;
00082 
00083 /* Symtab of default file for listing lines of.  */
00084 
00085 static struct symtab *current_source_symtab;
00086 
00087 /* Default next line to list.  */
00088 
00089 static int current_source_line;
00090 
00091 static struct program_space *current_source_pspace;
00092 
00093 /* Default number of lines to print with commands like "list".
00094    This is based on guessing how many long (i.e. more than chars_per_line
00095    characters) lines there will be.  To be completely correct, "list"
00096    and friends should be rewritten to count characters and see where
00097    things are wrapping, but that would be a fair amount of work.  */
00098 
00099 int lines_to_list = 10;
00100 static void
00101 show_lines_to_list (struct ui_file *file, int from_tty,
00102                     struct cmd_list_element *c, const char *value)
00103 {
00104   fprintf_filtered (file,
00105                     _("Number of source lines gdb "
00106                       "will list by default is %s.\n"),
00107                     value);
00108 }
00109 
00110 /* Possible values of 'set filename-display'.  */
00111 static const char filename_display_basename[] = "basename";
00112 static const char filename_display_relative[] = "relative";
00113 static const char filename_display_absolute[] = "absolute";
00114 
00115 static const char *const filename_display_kind_names[] = {
00116   filename_display_basename,
00117   filename_display_relative,
00118   filename_display_absolute,
00119   NULL
00120 };
00121 
00122 static const char *filename_display_string = filename_display_relative;
00123 
00124 static void
00125 show_filename_display_string (struct ui_file *file, int from_tty,
00126                               struct cmd_list_element *c, const char *value)
00127 {
00128   fprintf_filtered (file, _("Filenames are displayed as \"%s\".\n"), value);
00129 }
00130  
00131 /* Line number of last line printed.  Default for various commands.
00132    current_source_line is usually, but not always, the same as this.  */
00133 
00134 static int last_line_listed;
00135 
00136 /* First line number listed by last listing command.  */
00137 
00138 static int first_line_listed;
00139 
00140 /* Saves the name of the last source file visited and a possible error code.
00141    Used to prevent repeating annoying "No such file or directories" msgs.  */
00142 
00143 static struct symtab *last_source_visited = NULL;
00144 static int last_source_error = 0;
00145 
00146 /* Return the first line listed by print_source_lines.
00147    Used by command interpreters to request listing from
00148    a previous point.  */
00149 
00150 int
00151 get_first_line_listed (void)
00152 {
00153   return first_line_listed;
00154 }
00155 
00156 /* Return the default number of lines to print with commands like the
00157    cli "list".  The caller of print_source_lines must use this to
00158    calculate the end line and use it in the call to print_source_lines
00159    as it does not automatically use this value.  */
00160 
00161 int
00162 get_lines_to_list (void)
00163 {
00164   return lines_to_list;
00165 }
00166 
00167 /* Return the current source file for listing and next line to list.
00168    NOTE: The returned sal pc and end fields are not valid.  */
00169    
00170 struct symtab_and_line
00171 get_current_source_symtab_and_line (void)
00172 {
00173   struct symtab_and_line cursal = { 0 };
00174 
00175   cursal.pspace = current_source_pspace;
00176   cursal.symtab = current_source_symtab;
00177   cursal.line = current_source_line;
00178   cursal.pc = 0;
00179   cursal.end = 0;
00180   
00181   return cursal;
00182 }
00183 
00184 /* If the current source file for listing is not set, try and get a default.
00185    Usually called before get_current_source_symtab_and_line() is called.
00186    It may err out if a default cannot be determined.
00187    We must be cautious about where it is called, as it can recurse as the
00188    process of determining a new default may call the caller!
00189    Use get_current_source_symtab_and_line only to get whatever
00190    we have without erroring out or trying to get a default.  */
00191    
00192 void
00193 set_default_source_symtab_and_line (void)
00194 {
00195   if (!have_full_symbols () && !have_partial_symbols ())
00196     error (_("No symbol table is loaded.  Use the \"file\" command."));
00197 
00198   /* Pull in a current source symtab if necessary.  */
00199   if (current_source_symtab == 0)
00200     select_source_symtab (0);
00201 }
00202 
00203 /* Return the current default file for listing and next line to list
00204    (the returned sal pc and end fields are not valid.)
00205    and set the current default to whatever is in SAL.
00206    NOTE: The returned sal pc and end fields are not valid.  */
00207    
00208 struct symtab_and_line
00209 set_current_source_symtab_and_line (const struct symtab_and_line *sal)
00210 {
00211   struct symtab_and_line cursal = { 0 };
00212 
00213   cursal.pspace = current_source_pspace;
00214   cursal.symtab = current_source_symtab;
00215   cursal.line = current_source_line;
00216   cursal.pc = 0;
00217   cursal.end = 0;
00218 
00219   current_source_pspace = sal->pspace;
00220   current_source_symtab = sal->symtab;
00221   current_source_line = sal->line;
00222 
00223   return cursal;
00224 }
00225 
00226 /* Reset any information stored about a default file and line to print.  */
00227 
00228 void
00229 clear_current_source_symtab_and_line (void)
00230 {
00231   current_source_symtab = 0;
00232   current_source_line = 0;
00233 }
00234 
00235 /* Set the source file default for the "list" command to be S.
00236 
00237    If S is NULL, and we don't have a default, find one.  This
00238    should only be called when the user actually tries to use the
00239    default, since we produce an error if we can't find a reasonable
00240    default.  Also, since this can cause symbols to be read, doing it
00241    before we need to would make things slower than necessary.  */
00242 
00243 void
00244 select_source_symtab (struct symtab *s)
00245 {
00246   struct symtabs_and_lines sals;
00247   struct symtab_and_line sal;
00248   struct objfile *ofp;
00249 
00250   if (s)
00251     {
00252       current_source_symtab = s;
00253       current_source_line = 1;
00254       current_source_pspace = SYMTAB_PSPACE (s);
00255       return;
00256     }
00257 
00258   if (current_source_symtab)
00259     return;
00260 
00261   /* Make the default place to list be the function `main'
00262      if one exists.  */
00263   if (lookup_symbol (main_name (), 0, VAR_DOMAIN, 0))
00264     {
00265       sals = decode_line_with_current_source (main_name (),
00266                                               DECODE_LINE_FUNFIRSTLINE);
00267       sal = sals.sals[0];
00268       xfree (sals.sals);
00269       current_source_pspace = sal.pspace;
00270       current_source_symtab = sal.symtab;
00271       current_source_line = max (sal.line - (lines_to_list - 1), 1);
00272       if (current_source_symtab)
00273         return;
00274     }
00275 
00276   /* Alright; find the last file in the symtab list (ignoring .h's
00277      and namespace symtabs).  */
00278 
00279   current_source_line = 1;
00280 
00281   ALL_OBJFILES (ofp)
00282     {
00283       for (s = ofp->symtabs; s; s = s->next)
00284         {
00285           const char *name = s->filename;
00286           int len = strlen (name);
00287 
00288           if (!(len > 2 && (strcmp (&name[len - 2], ".h") == 0
00289               || strcmp (name, "<<C++-namespaces>>") == 0)))
00290             {
00291               current_source_pspace = current_program_space;
00292               current_source_symtab = s;
00293             }
00294         }
00295     }
00296 
00297   if (current_source_symtab)
00298     return;
00299 
00300   ALL_OBJFILES (ofp)
00301   {
00302     if (ofp->sf)
00303       s = ofp->sf->qf->find_last_source_symtab (ofp);
00304     if (s)
00305       current_source_symtab = s;
00306   }
00307   if (current_source_symtab)
00308     return;
00309 
00310   error (_("Can't find a default source file"));
00311 }
00312 
00313 /* Handler for "set directories path-list" command.
00314    "set dir mumble" doesn't prepend paths, it resets the entire
00315    path list.  The theory is that set(show(dir)) should be a no-op.  */
00316 
00317 static void
00318 set_directories_command (char *args, int from_tty, struct cmd_list_element *c)
00319 {
00320   /* This is the value that was set.
00321      It needs to be processed to maintain $cdir:$cwd and remove dups.  */
00322   char *set_path = source_path;
00323 
00324   /* We preserve the invariant that $cdir:$cwd begins life at the end of
00325      the list by calling init_source_path.  If they appear earlier in
00326      SET_PATH then mod_path will move them appropriately.
00327      mod_path will also remove duplicates.  */
00328   init_source_path ();
00329   if (*set_path != '\0')
00330     mod_path (set_path, &source_path);
00331 
00332   xfree (set_path);
00333 }
00334 
00335 /* Print the list of source directories.
00336    This is used by the "ld" command, so it has the signature of a command
00337    function.  */
00338 
00339 static void
00340 show_directories_1 (char *ignore, int from_tty)
00341 {
00342   puts_filtered ("Source directories searched: ");
00343   puts_filtered (source_path);
00344   puts_filtered ("\n");
00345 }
00346 
00347 /* Handler for "show directories" command.  */
00348 
00349 static void
00350 show_directories_command (struct ui_file *file, int from_tty,
00351                           struct cmd_list_element *c, const char *value)
00352 {
00353   show_directories_1 (NULL, from_tty);
00354 }
00355 
00356 /* Forget line positions and file names for the symtabs in a
00357    particular objfile.  */
00358 
00359 void
00360 forget_cached_source_info_for_objfile (struct objfile *objfile)
00361 {
00362   struct symtab *s;
00363 
00364   ALL_OBJFILE_SYMTABS (objfile, s)
00365     {
00366       if (s->line_charpos != NULL)
00367         {
00368           xfree (s->line_charpos);
00369           s->line_charpos = NULL;
00370         }
00371       if (s->fullname != NULL)
00372         {
00373           xfree (s->fullname);
00374           s->fullname = NULL;
00375         }
00376     }
00377 
00378   if (objfile->sf)
00379     objfile->sf->qf->forget_cached_source_info (objfile);
00380 }
00381 
00382 /* Forget what we learned about line positions in source files, and
00383    which directories contain them; must check again now since files
00384    may be found in a different directory now.  */
00385 
00386 void
00387 forget_cached_source_info (void)
00388 {
00389   struct program_space *pspace;
00390   struct objfile *objfile;
00391 
00392   ALL_PSPACES (pspace)
00393     ALL_PSPACE_OBJFILES (pspace, objfile)
00394     {
00395       forget_cached_source_info_for_objfile (objfile);
00396     }
00397 
00398   last_source_visited = NULL;
00399 }
00400 
00401 void
00402 init_source_path (void)
00403 {
00404   char buf[20];
00405 
00406   xsnprintf (buf, sizeof (buf), "$cdir%c$cwd", DIRNAME_SEPARATOR);
00407   source_path = xstrdup (buf);
00408   forget_cached_source_info ();
00409 }
00410 
00411 /* Add zero or more directories to the front of the source path.  */
00412 
00413 static void
00414 directory_command (char *dirname, int from_tty)
00415 {
00416   dont_repeat ();
00417   /* FIXME, this goes to "delete dir"...  */
00418   if (dirname == 0)
00419     {
00420       if (!from_tty || query (_("Reinitialize source path to empty? ")))
00421         {
00422           xfree (source_path);
00423           init_source_path ();
00424         }
00425     }
00426   else
00427     {
00428       mod_path (dirname, &source_path);
00429       forget_cached_source_info ();
00430     }
00431   if (from_tty)
00432     show_directories_1 ((char *) 0, from_tty);
00433 }
00434 
00435 /* Add a path given with the -d command line switch.
00436    This will not be quoted so we must not treat spaces as separators.  */
00437 
00438 void
00439 directory_switch (char *dirname, int from_tty)
00440 {
00441   add_path (dirname, &source_path, 0);
00442 }
00443 
00444 /* Add zero or more directories to the front of an arbitrary path.  */
00445 
00446 void
00447 mod_path (char *dirname, char **which_path)
00448 {
00449   add_path (dirname, which_path, 1);
00450 }
00451 
00452 /* Workhorse of mod_path.  Takes an extra argument to determine
00453    if dirname should be parsed for separators that indicate multiple
00454    directories.  This allows for interfaces that pre-parse the dirname
00455    and allow specification of traditional separator characters such
00456    as space or tab.  */
00457 
00458 void
00459 add_path (char *dirname, char **which_path, int parse_separators)
00460 {
00461   char *old = *which_path;
00462   int prefix = 0;
00463   VEC (char_ptr) *dir_vec = NULL;
00464   struct cleanup *back_to;
00465   int ix;
00466   char *name;
00467 
00468   if (dirname == 0)
00469     return;
00470 
00471   if (parse_separators)
00472     {
00473       char **argv, **argvp;
00474 
00475       /* This will properly parse the space and tab separators
00476          and any quotes that may exist.  */
00477       argv = gdb_buildargv (dirname);
00478 
00479       for (argvp = argv; *argvp; argvp++)
00480         dirnames_to_char_ptr_vec_append (&dir_vec, *argvp);
00481 
00482       freeargv (argv);
00483     }
00484   else
00485     VEC_safe_push (char_ptr, dir_vec, xstrdup (dirname));
00486   back_to = make_cleanup_free_char_ptr_vec (dir_vec);
00487 
00488   for (ix = 0; VEC_iterate (char_ptr, dir_vec, ix, name); ++ix)
00489     {
00490       char *p;
00491       struct stat st;
00492 
00493       /* Spaces and tabs will have been removed by buildargv().
00494          NAME is the start of the directory.
00495          P is the '\0' following the end.  */
00496       p = name + strlen (name);
00497 
00498       while (!(IS_DIR_SEPARATOR (*name) && p <= name + 1)       /* "/" */
00499 #ifdef HAVE_DOS_BASED_FILE_SYSTEM
00500       /* On MS-DOS and MS-Windows, h:\ is different from h: */
00501              && !(p == name + 3 && name[1] == ':')              /* "d:/" */
00502 #endif
00503              && IS_DIR_SEPARATOR (p[-1]))
00504         /* Sigh.  "foo/" => "foo" */
00505         --p;
00506       *p = '\0';
00507 
00508       while (p > name && p[-1] == '.')
00509         {
00510           if (p - name == 1)
00511             {
00512               /* "." => getwd ().  */
00513               name = current_directory;
00514               goto append;
00515             }
00516           else if (p > name + 1 && IS_DIR_SEPARATOR (p[-2]))
00517             {
00518               if (p - name == 2)
00519                 {
00520                   /* "/." => "/".  */
00521                   *--p = '\0';
00522                   goto append;
00523                 }
00524               else
00525                 {
00526                   /* "...foo/." => "...foo".  */
00527                   p -= 2;
00528                   *p = '\0';
00529                   continue;
00530                 }
00531             }
00532           else
00533             break;
00534         }
00535 
00536       if (name[0] == '~')
00537         name = tilde_expand (name);
00538 #ifdef HAVE_DOS_BASED_FILE_SYSTEM
00539       else if (IS_ABSOLUTE_PATH (name) && p == name + 2) /* "d:" => "d:." */
00540         name = concat (name, ".", (char *)NULL);
00541 #endif
00542       else if (!IS_ABSOLUTE_PATH (name) && name[0] != '$')
00543         name = concat (current_directory, SLASH_STRING, name, (char *)NULL);
00544       else
00545         name = savestring (name, p - name);
00546       make_cleanup (xfree, name);
00547 
00548       /* Unless it's a variable, check existence.  */
00549       if (name[0] != '$')
00550         {
00551           /* These are warnings, not errors, since we don't want a
00552              non-existent directory in a .gdbinit file to stop processing
00553              of the .gdbinit file.
00554 
00555              Whether they get added to the path is more debatable.  Current
00556              answer is yes, in case the user wants to go make the directory
00557              or whatever.  If the directory continues to not exist/not be
00558              a directory/etc, then having them in the path should be
00559              harmless.  */
00560           if (stat (name, &st) < 0)
00561             {
00562               int save_errno = errno;
00563 
00564               fprintf_unfiltered (gdb_stderr, "Warning: ");
00565               print_sys_errmsg (name, save_errno);
00566             }
00567           else if ((st.st_mode & S_IFMT) != S_IFDIR)
00568             warning (_("%s is not a directory."), name);
00569         }
00570 
00571     append:
00572       {
00573         unsigned int len = strlen (name);
00574         char tinybuf[2];
00575 
00576         p = *which_path;
00577         /* FIXME: we should use realpath() or its work-alike
00578            before comparing.  Then all the code above which
00579            removes excess slashes and dots could simply go away.  */
00580         if (!filename_cmp (p, name))
00581           {
00582             /* Found it in the search path, remove old copy.  */
00583             if (p > *which_path)
00584               p--;              /* Back over leading separator.  */
00585             if (prefix > p - *which_path)
00586               goto skip_dup;    /* Same dir twice in one cmd.  */
00587             memmove (p, &p[len + 1], strlen (&p[len + 1]) + 1); /* Copy from next \0 or  : */
00588           }
00589 
00590         tinybuf[0] = DIRNAME_SEPARATOR;
00591         tinybuf[1] = '\0';
00592 
00593         /* If we have already tacked on a name(s) in this command,
00594            be sure they stay on the front as we tack on some
00595            more.  */
00596         if (prefix)
00597           {
00598             char *temp, c;
00599 
00600             c = old[prefix];
00601             old[prefix] = '\0';
00602             temp = concat (old, tinybuf, name, (char *)NULL);
00603             old[prefix] = c;
00604             *which_path = concat (temp, "", &old[prefix], (char *) NULL);
00605             prefix = strlen (temp);
00606             xfree (temp);
00607           }
00608         else
00609           {
00610             *which_path = concat (name, (old[0] ? tinybuf : old),
00611                                   old, (char *)NULL);
00612             prefix = strlen (name);
00613           }
00614         xfree (old);
00615         old = *which_path;
00616       }
00617     skip_dup:
00618       ;
00619     }
00620 
00621   do_cleanups (back_to);
00622 }
00623 
00624 
00625 static void
00626 source_info (char *ignore, int from_tty)
00627 {
00628   struct symtab *s = current_source_symtab;
00629 
00630   if (!s)
00631     {
00632       printf_filtered (_("No current source file.\n"));
00633       return;
00634     }
00635   printf_filtered (_("Current source file is %s\n"), s->filename);
00636   if (s->dirname)
00637     printf_filtered (_("Compilation directory is %s\n"), s->dirname);
00638   if (s->fullname)
00639     printf_filtered (_("Located in %s\n"), s->fullname);
00640   if (s->nlines)
00641     printf_filtered (_("Contains %d line%s.\n"), s->nlines,
00642                      s->nlines == 1 ? "" : "s");
00643 
00644   printf_filtered (_("Source language is %s.\n"), language_str (s->language));
00645   printf_filtered (_("Compiled with %s debugging format.\n"), s->debugformat);
00646   printf_filtered (_("%s preprocessor macro info.\n"),
00647                    s->macro_table ? "Includes" : "Does not include");
00648 }
00649 
00650 
00651 /* Return True if the file NAME exists and is a regular file.  */
00652 static int
00653 is_regular_file (const char *name)
00654 {
00655   struct stat st;
00656   const int status = stat (name, &st);
00657 
00658   /* Stat should never fail except when the file does not exist.
00659      If stat fails, analyze the source of error and return True
00660      unless the file does not exist, to avoid returning false results
00661      on obscure systems where stat does not work as expected.  */
00662 
00663   if (status != 0)
00664     return (errno != ENOENT);
00665 
00666   return S_ISREG (st.st_mode);
00667 }
00668 
00669 /* Open a file named STRING, searching path PATH (dir names sep by some char)
00670    using mode MODE in the calls to open.  You cannot use this function to
00671    create files (O_CREAT).
00672 
00673    OPTS specifies the function behaviour in specific cases.
00674 
00675    If OPF_TRY_CWD_FIRST, try to open ./STRING before searching PATH.
00676    (ie pretend the first element of PATH is ".").  This also indicates
00677    that, unless OPF_SEARCH_IN_PATH is also specified, a slash in STRING
00678    disables searching of the path (this is so that "exec-file ./foo" or
00679    "symbol-file ./foo" insures that you get that particular version of
00680    foo or an error message).
00681 
00682    If OPTS has OPF_SEARCH_IN_PATH set, absolute names will also be
00683    searched in path (we usually want this for source files but not for
00684    executables).
00685 
00686    If FILENAME_OPENED is non-null, set it to a newly allocated string naming
00687    the actual file opened (this string will always start with a "/").  We
00688    have to take special pains to avoid doubling the "/" between the directory
00689    and the file, sigh!  Emacs gets confuzzed by this when we print the
00690    source file name!!! 
00691 
00692    If OPTS has OPF_RETURN_REALPATH set return FILENAME_OPENED resolved by
00693    gdb_realpath.  Even without OPF_RETURN_REALPATH this function still returns
00694    filename starting with "/".  If FILENAME_OPENED is NULL this option has no
00695    effect.
00696 
00697    If a file is found, return the descriptor.
00698    Otherwise, return -1, with errno set for the last name we tried to open.  */
00699 
00700 /*  >>>> This should only allow files of certain types,
00701     >>>>  eg executable, non-directory.  */
00702 int
00703 openp (const char *path, int opts, const char *string,
00704        int mode, char **filename_opened)
00705 {
00706   int fd;
00707   char *filename;
00708   int alloclen;
00709   VEC (char_ptr) *dir_vec;
00710   struct cleanup *back_to;
00711   int ix;
00712   char *dir;
00713 
00714   /* The open syscall MODE parameter is not specified.  */
00715   gdb_assert ((mode & O_CREAT) == 0);
00716   gdb_assert (string != NULL);
00717 
00718   /* A file with an empty name cannot possibly exist.  Report a failure
00719      without further checking.
00720 
00721      This is an optimization which also defends us against buggy
00722      implementations of the "stat" function.  For instance, we have
00723      noticed that a MinGW debugger built on Windows XP 32bits crashes
00724      when the debugger is started with an empty argument.  */
00725   if (string[0] == '\0')
00726     {
00727       errno = ENOENT;
00728       return -1;
00729     }
00730 
00731   if (!path)
00732     path = ".";
00733 
00734   mode |= O_BINARY;
00735 
00736   if ((opts & OPF_TRY_CWD_FIRST) || IS_ABSOLUTE_PATH (string))
00737     {
00738       int i;
00739 
00740       if (is_regular_file (string))
00741         {
00742           filename = alloca (strlen (string) + 1);
00743           strcpy (filename, string);
00744           fd = gdb_open_cloexec (filename, mode, 0);
00745           if (fd >= 0)
00746             goto done;
00747         }
00748       else
00749         {
00750           filename = NULL;
00751           fd = -1;
00752         }
00753 
00754       if (!(opts & OPF_SEARCH_IN_PATH))
00755         for (i = 0; string[i]; i++)
00756           if (IS_DIR_SEPARATOR (string[i]))
00757             goto done;
00758     }
00759 
00760   /* For dos paths, d:/foo -> /foo, and d:foo -> foo.  */
00761   if (HAS_DRIVE_SPEC (string))
00762     string = STRIP_DRIVE_SPEC (string);
00763 
00764   /* /foo => foo, to avoid multiple slashes that Emacs doesn't like.  */
00765   while (IS_DIR_SEPARATOR(string[0]))
00766     string++;
00767 
00768   /* ./foo => foo */
00769   while (string[0] == '.' && IS_DIR_SEPARATOR (string[1]))
00770     string += 2;
00771 
00772   alloclen = strlen (path) + strlen (string) + 2;
00773   filename = alloca (alloclen);
00774   fd = -1;
00775 
00776   dir_vec = dirnames_to_char_ptr_vec (path);
00777   back_to = make_cleanup_free_char_ptr_vec (dir_vec);
00778 
00779   for (ix = 0; VEC_iterate (char_ptr, dir_vec, ix, dir); ++ix)
00780     {
00781       size_t len = strlen (dir);
00782 
00783       if (strcmp (dir, "$cwd") == 0)
00784         {
00785           /* Name is $cwd -- insert current directory name instead.  */
00786           int newlen;
00787 
00788           /* First, realloc the filename buffer if too short.  */
00789           len = strlen (current_directory);
00790           newlen = len + strlen (string) + 2;
00791           if (newlen > alloclen)
00792             {
00793               alloclen = newlen;
00794               filename = alloca (alloclen);
00795             }
00796           strcpy (filename, current_directory);
00797         }
00798       else if (strchr(dir, '~'))
00799         {
00800          /* See whether we need to expand the tilde.  */
00801           int newlen;
00802           char *tilde_expanded;
00803 
00804           tilde_expanded  = tilde_expand (dir);
00805 
00806           /* First, realloc the filename buffer if too short.  */
00807           len = strlen (tilde_expanded);
00808           newlen = len + strlen (string) + 2;
00809           if (newlen > alloclen)
00810             {
00811               alloclen = newlen;
00812               filename = alloca (alloclen);
00813             }
00814           strcpy (filename, tilde_expanded);
00815           xfree (tilde_expanded);
00816         }
00817       else
00818         {
00819           /* Normal file name in path -- just use it.  */
00820           strcpy (filename, dir);
00821 
00822           /* Don't search $cdir.  It's also a magic path like $cwd, but we
00823              don't have enough information to expand it.  The user *could*
00824              have an actual directory named '$cdir' but handling that would
00825              be confusing, it would mean different things in different
00826              contexts.  If the user really has '$cdir' one can use './$cdir'.
00827              We can get $cdir when loading scripts.  When loading source files
00828              $cdir must have already been expanded to the correct value.  */
00829           if (strcmp (dir, "$cdir") == 0)
00830             continue;
00831         }
00832 
00833       /* Remove trailing slashes.  */
00834       while (len > 0 && IS_DIR_SEPARATOR (filename[len - 1]))
00835         filename[--len] = 0;
00836 
00837       strcat (filename + len, SLASH_STRING);
00838       strcat (filename, string);
00839 
00840       if (is_regular_file (filename))
00841         {
00842           fd = gdb_open_cloexec (filename, mode, 0);
00843           if (fd >= 0)
00844             break;
00845         }
00846     }
00847 
00848   do_cleanups (back_to);
00849 
00850 done:
00851   if (filename_opened)
00852     {
00853       /* If a file was opened, canonicalize its filename.  */
00854       if (fd < 0)
00855         *filename_opened = NULL;
00856       else
00857         {
00858           char *(*realpath_fptr) (const char *);
00859 
00860           realpath_fptr = ((opts & OPF_RETURN_REALPATH) != 0
00861                            ? gdb_realpath : xstrdup);
00862 
00863           if (IS_ABSOLUTE_PATH (filename))
00864             *filename_opened = realpath_fptr (filename);
00865           else
00866             {
00867               /* Beware the // my son, the Emacs barfs, the botch that catch...  */
00868 
00869               char *f = concat (current_directory,
00870                                 IS_DIR_SEPARATOR (current_directory[strlen (current_directory) - 1])
00871                                 ? "" : SLASH_STRING,
00872                                 filename, (char *)NULL);
00873 
00874               *filename_opened = realpath_fptr (f);
00875               xfree (f);
00876             }
00877         }
00878     }
00879 
00880   return fd;
00881 }
00882 
00883 
00884 /* This is essentially a convenience, for clients that want the behaviour
00885    of openp, using source_path, but that really don't want the file to be
00886    opened but want instead just to know what the full pathname is (as
00887    qualified against source_path).
00888 
00889    The current working directory is searched first.
00890 
00891    If the file was found, this function returns 1, and FULL_PATHNAME is
00892    set to the fully-qualified pathname.
00893 
00894    Else, this functions returns 0, and FULL_PATHNAME is set to NULL.  */
00895 int
00896 source_full_path_of (const char *filename, char **full_pathname)
00897 {
00898   int fd;
00899 
00900   fd = openp (source_path,
00901               OPF_TRY_CWD_FIRST | OPF_SEARCH_IN_PATH | OPF_RETURN_REALPATH,
00902               filename, O_RDONLY, full_pathname);
00903   if (fd < 0)
00904     {
00905       *full_pathname = NULL;
00906       return 0;
00907     }
00908 
00909   close (fd);
00910   return 1;
00911 }
00912 
00913 /* Return non-zero if RULE matches PATH, that is if the rule can be
00914    applied to PATH.  */
00915 
00916 static int
00917 substitute_path_rule_matches (const struct substitute_path_rule *rule,
00918                               const char *path)
00919 {
00920   const int from_len = strlen (rule->from);
00921   const int path_len = strlen (path);
00922   char *path_start;
00923 
00924   if (path_len < from_len)
00925     return 0;
00926 
00927   /* The substitution rules are anchored at the start of the path,
00928      so the path should start with rule->from.  There is no filename
00929      comparison routine, so we need to extract the first FROM_LEN
00930      characters from PATH first and use that to do the comparison.  */
00931 
00932   path_start = alloca (from_len + 1);
00933   strncpy (path_start, path, from_len);
00934   path_start[from_len] = '\0';
00935 
00936   if (FILENAME_CMP (path_start, rule->from) != 0)
00937     return 0;
00938 
00939   /* Make sure that the region in the path that matches the substitution
00940      rule is immediately followed by a directory separator (or the end of
00941      string character).  */
00942   
00943   if (path[from_len] != '\0' && !IS_DIR_SEPARATOR (path[from_len]))
00944     return 0;
00945 
00946   return 1;
00947 }
00948 
00949 /* Find the substitute-path rule that applies to PATH and return it.
00950    Return NULL if no rule applies.  */
00951 
00952 static struct substitute_path_rule *
00953 get_substitute_path_rule (const char *path)
00954 {
00955   struct substitute_path_rule *rule = substitute_path_rules;
00956 
00957   while (rule != NULL && !substitute_path_rule_matches (rule, path))
00958     rule = rule->next;
00959 
00960   return rule;
00961 }
00962 
00963 /* If the user specified a source path substitution rule that applies
00964    to PATH, then apply it and return the new path.  This new path must
00965    be deallocated afterwards.
00966    
00967    Return NULL if no substitution rule was specified by the user,
00968    or if no rule applied to the given PATH.  */
00969    
00970 char *
00971 rewrite_source_path (const char *path)
00972 {
00973   const struct substitute_path_rule *rule = get_substitute_path_rule (path);
00974   char *new_path;
00975   int from_len;
00976   
00977   if (rule == NULL)
00978     return NULL;
00979 
00980   from_len = strlen (rule->from);
00981 
00982   /* Compute the rewritten path and return it.  */
00983 
00984   new_path =
00985     (char *) xmalloc (strlen (path) + 1 + strlen (rule->to) - from_len);
00986   strcpy (new_path, rule->to);
00987   strcat (new_path, path + from_len);
00988 
00989   return new_path;
00990 }
00991 
00992 int
00993 find_and_open_source (const char *filename,
00994                       const char *dirname,
00995                       char **fullname)
00996 {
00997   char *path = source_path;
00998   const char *p;
00999   int result;
01000   struct cleanup *cleanup;
01001 
01002   /* Quick way out if we already know its full name.  */
01003 
01004   if (*fullname)
01005     {
01006       /* The user may have requested that source paths be rewritten
01007          according to substitution rules he provided.  If a substitution
01008          rule applies to this path, then apply it.  */
01009       char *rewritten_fullname = rewrite_source_path (*fullname);
01010 
01011       if (rewritten_fullname != NULL)
01012         {
01013           xfree (*fullname);
01014           *fullname = rewritten_fullname;
01015         }
01016 
01017       result = gdb_open_cloexec (*fullname, OPEN_MODE, 0);
01018       if (result >= 0)
01019         {
01020           char *lpath = gdb_realpath (*fullname);
01021 
01022           xfree (*fullname);
01023           *fullname = lpath;
01024           return result;
01025         }
01026 
01027       /* Didn't work -- free old one, try again.  */
01028       xfree (*fullname);
01029       *fullname = NULL;
01030     }
01031 
01032   cleanup = make_cleanup (null_cleanup, NULL);
01033 
01034   if (dirname != NULL)
01035     {
01036       /* If necessary, rewrite the compilation directory name according
01037          to the source path substitution rules specified by the user.  */
01038 
01039       char *rewritten_dirname = rewrite_source_path (dirname);
01040 
01041       if (rewritten_dirname != NULL)
01042         {
01043           make_cleanup (xfree, rewritten_dirname);
01044           dirname = rewritten_dirname;
01045         }
01046       
01047       /* Replace a path entry of $cdir with the compilation directory
01048          name.  */
01049 #define cdir_len        5
01050       /* We cast strstr's result in case an ANSIhole has made it const,
01051          which produces a "required warning" when assigned to a nonconst.  */
01052       p = (char *) strstr (source_path, "$cdir");
01053       if (p && (p == path || p[-1] == DIRNAME_SEPARATOR)
01054           && (p[cdir_len] == DIRNAME_SEPARATOR || p[cdir_len] == '\0'))
01055         {
01056           int len;
01057 
01058           path = (char *)
01059             alloca (strlen (source_path) + 1 + strlen (dirname) + 1);
01060           len = p - source_path;
01061           strncpy (path, source_path, len);     /* Before $cdir */
01062           strcpy (path + len, dirname);         /* new stuff */
01063           strcat (path + len, source_path + len + cdir_len);    /* After
01064                                                                    $cdir */
01065         }
01066     }
01067 
01068   if (IS_ABSOLUTE_PATH (filename))
01069     {
01070       /* If filename is absolute path, try the source path
01071          substitution on it.  */
01072       char *rewritten_filename = rewrite_source_path (filename);
01073 
01074       if (rewritten_filename != NULL)
01075         {
01076           make_cleanup (xfree, rewritten_filename);
01077           filename = rewritten_filename;
01078         }
01079     }
01080 
01081   result = openp (path, OPF_SEARCH_IN_PATH | OPF_RETURN_REALPATH, filename,
01082                   OPEN_MODE, fullname);
01083   if (result < 0)
01084     {
01085       /* Didn't work.  Try using just the basename.  */
01086       p = lbasename (filename);
01087       if (p != filename)
01088         result = openp (path, OPF_SEARCH_IN_PATH | OPF_RETURN_REALPATH, p,
01089                         OPEN_MODE, fullname);
01090     }
01091 
01092   do_cleanups (cleanup);
01093   return result;
01094 }
01095 
01096 /* Open a source file given a symtab S.  Returns a file descriptor or
01097    negative number for error.  
01098    
01099    This function is a convience function to find_and_open_source.  */
01100 
01101 int
01102 open_source_file (struct symtab *s)
01103 {
01104   if (!s)
01105     return -1;
01106 
01107   return find_and_open_source (s->filename, s->dirname, &s->fullname);
01108 }
01109 
01110 /* Finds the fullname that a symtab represents.
01111 
01112    This functions finds the fullname and saves it in s->fullname.
01113    It will also return the value.
01114 
01115    If this function fails to find the file that this symtab represents,
01116    the expected fullname is used.  Therefore the files does not have to
01117    exist.  */
01118 
01119 const char *
01120 symtab_to_fullname (struct symtab *s)
01121 {
01122   /* Use cached copy if we have it.
01123      We rely on forget_cached_source_info being called appropriately
01124      to handle cases like the file being moved.  */
01125   if (s->fullname == NULL)
01126     {
01127       int fd = find_and_open_source (s->filename, s->dirname, &s->fullname);
01128 
01129       if (fd >= 0)
01130         close (fd);
01131       else
01132         {
01133           char *fullname;
01134           struct cleanup *back_to;
01135 
01136           /* rewrite_source_path would be applied by find_and_open_source, we
01137              should report the pathname where GDB tried to find the file.  */
01138 
01139           if (s->dirname == NULL || IS_ABSOLUTE_PATH (s->filename))
01140             fullname = xstrdup (s->filename);
01141           else
01142             fullname = concat (s->dirname, SLASH_STRING, s->filename, NULL);
01143 
01144           back_to = make_cleanup (xfree, fullname);
01145           s->fullname = rewrite_source_path (fullname);
01146           if (s->fullname == NULL)
01147             s->fullname = xstrdup (fullname);
01148           do_cleanups (back_to);
01149         }
01150     } 
01151 
01152   return s->fullname;
01153 }
01154 
01155 /* See commentary in source.h.  */
01156 
01157 const char *
01158 symtab_to_filename_for_display (struct symtab *symtab)
01159 {
01160   if (filename_display_string == filename_display_basename)
01161     return lbasename (symtab->filename);
01162   else if (filename_display_string == filename_display_absolute)
01163     return symtab_to_fullname (symtab);
01164   else if (filename_display_string == filename_display_relative)
01165     return symtab->filename;
01166   else
01167     internal_error (__FILE__, __LINE__, _("invalid filename_display_string"));
01168 }
01169 
01170 /* Create and initialize the table S->line_charpos that records
01171    the positions of the lines in the source file, which is assumed
01172    to be open on descriptor DESC.
01173    All set S->nlines to the number of such lines.  */
01174 
01175 void
01176 find_source_lines (struct symtab *s, int desc)
01177 {
01178   struct stat st;
01179   char *data, *p, *end;
01180   int nlines = 0;
01181   int lines_allocated = 1000;
01182   int *line_charpos;
01183   long mtime = 0;
01184   int size;
01185 
01186   gdb_assert (s);
01187   line_charpos = (int *) xmalloc (lines_allocated * sizeof (int));
01188   if (fstat (desc, &st) < 0)
01189     perror_with_name (symtab_to_filename_for_display (s));
01190 
01191   if (s->objfile && s->objfile->obfd)
01192     mtime = s->objfile->mtime;
01193   else if (exec_bfd)
01194     mtime = exec_bfd_mtime;
01195 
01196   if (mtime && mtime < st.st_mtime)
01197     warning (_("Source file is more recent than executable."));
01198 
01199   {
01200     struct cleanup *old_cleanups;
01201 
01202     /* st_size might be a large type, but we only support source files whose 
01203        size fits in an int.  */
01204     size = (int) st.st_size;
01205 
01206     /* Use malloc, not alloca, because this may be pretty large, and we may
01207        run into various kinds of limits on stack size.  */
01208     data = (char *) xmalloc (size);
01209     old_cleanups = make_cleanup (xfree, data);
01210 
01211     /* Reassign `size' to result of read for systems where \r\n -> \n.  */
01212     size = myread (desc, data, size);
01213     if (size < 0)
01214       perror_with_name (symtab_to_filename_for_display (s));
01215     end = data + size;
01216     p = data;
01217     line_charpos[0] = 0;
01218     nlines = 1;
01219     while (p != end)
01220       {
01221         if (*p++ == '\n'
01222         /* A newline at the end does not start a new line.  */
01223             && p != end)
01224           {
01225             if (nlines == lines_allocated)
01226               {
01227                 lines_allocated *= 2;
01228                 line_charpos =
01229                   (int *) xrealloc ((char *) line_charpos,
01230                                     sizeof (int) * lines_allocated);
01231               }
01232             line_charpos[nlines++] = p - data;
01233           }
01234       }
01235     do_cleanups (old_cleanups);
01236   }
01237 
01238   s->nlines = nlines;
01239   s->line_charpos =
01240     (int *) xrealloc ((char *) line_charpos, nlines * sizeof (int));
01241 
01242 }
01243 
01244 
01245 
01246 /* Get full pathname and line number positions for a symtab.
01247    Return nonzero if line numbers may have changed.
01248    Set *FULLNAME to actual name of the file as found by `openp',
01249    or to 0 if the file is not found.  */
01250 
01251 static int
01252 get_filename_and_charpos (struct symtab *s, char **fullname)
01253 {
01254   int desc, linenums_changed = 0;
01255   struct cleanup *cleanups;
01256 
01257   desc = open_source_file (s);
01258   if (desc < 0)
01259     {
01260       if (fullname)
01261         *fullname = NULL;
01262       return 0;
01263     }
01264   cleanups = make_cleanup_close (desc);
01265   if (fullname)
01266     *fullname = s->fullname;
01267   if (s->line_charpos == 0)
01268     linenums_changed = 1;
01269   if (linenums_changed)
01270     find_source_lines (s, desc);
01271   do_cleanups (cleanups);
01272   return linenums_changed;
01273 }
01274 
01275 /* Print text describing the full name of the source file S
01276    and the line number LINE and its corresponding character position.
01277    The text starts with two Ctrl-z so that the Emacs-GDB interface
01278    can easily find it.
01279 
01280    MID_STATEMENT is nonzero if the PC is not at the beginning of that line.
01281 
01282    Return 1 if successful, 0 if could not find the file.  */
01283 
01284 int
01285 identify_source_line (struct symtab *s, int line, int mid_statement,
01286                       CORE_ADDR pc)
01287 {
01288   if (s->line_charpos == 0)
01289     get_filename_and_charpos (s, (char **) NULL);
01290   if (s->fullname == 0)
01291     return 0;
01292   if (line > s->nlines)
01293     /* Don't index off the end of the line_charpos array.  */
01294     return 0;
01295   annotate_source (s->fullname, line, s->line_charpos[line - 1],
01296                    mid_statement, get_objfile_arch (s->objfile), pc);
01297 
01298   current_source_line = line;
01299   first_line_listed = line;
01300   last_line_listed = line;
01301   current_source_symtab = s;
01302   return 1;
01303 }
01304 
01305 
01306 /* Print source lines from the file of symtab S,
01307    starting with line number LINE and stopping before line number STOPLINE.  */
01308 
01309 static void
01310 print_source_lines_base (struct symtab *s, int line, int stopline,
01311                          enum print_source_lines_flags flags)
01312 {
01313   int c;
01314   int desc;
01315   int noprint = 0;
01316   FILE *stream;
01317   int nlines = stopline - line;
01318   struct cleanup *cleanup;
01319   struct ui_out *uiout = current_uiout;
01320 
01321   /* Regardless of whether we can open the file, set current_source_symtab.  */
01322   current_source_symtab = s;
01323   current_source_line = line;
01324   first_line_listed = line;
01325 
01326   /* If printing of source lines is disabled, just print file and line
01327      number.  */
01328   if (ui_out_test_flags (uiout, ui_source_list))
01329     {
01330       /* Only prints "No such file or directory" once.  */
01331       if ((s != last_source_visited) || (!last_source_error))
01332         {
01333           last_source_visited = s;
01334           desc = open_source_file (s);
01335         }
01336       else
01337         {
01338           desc = last_source_error;
01339           flags |= PRINT_SOURCE_LINES_NOERROR;
01340         }
01341     }
01342   else
01343     {
01344       desc = last_source_error;
01345           flags |= PRINT_SOURCE_LINES_NOERROR;
01346       noprint = 1;
01347     }
01348 
01349   if (desc < 0 || noprint)
01350     {
01351       last_source_error = desc;
01352 
01353       if (!(flags & PRINT_SOURCE_LINES_NOERROR))
01354         {
01355           const char *filename = symtab_to_filename_for_display (s);
01356           int len = strlen (filename) + 100;
01357           char *name = alloca (len);
01358 
01359           xsnprintf (name, len, "%d\t%s", line, filename);
01360           print_sys_errmsg (name, errno);
01361         }
01362       else
01363         {
01364           ui_out_field_int (uiout, "line", line);
01365           ui_out_text (uiout, "\tin ");
01366 
01367           /* CLI expects only the "file" field.  TUI expects only the
01368              "fullname" field (and TUI does break if "file" is printed).
01369              MI expects both fields.  ui_source_list is set only for CLI,
01370              not for TUI.  */
01371           if (ui_out_is_mi_like_p (uiout)
01372               || ui_out_test_flags (uiout, ui_source_list))
01373             ui_out_field_string (uiout, "file",
01374                                  symtab_to_filename_for_display (s));
01375           if (ui_out_is_mi_like_p (uiout)
01376               || !ui_out_test_flags (uiout, ui_source_list))
01377             {
01378               const char *s_fullname = symtab_to_fullname (s);
01379               char *local_fullname;
01380 
01381               /* ui_out_field_string may free S_FULLNAME by calling
01382                  open_source_file for it again.  See e.g.,
01383                  tui_field_string->tui_show_source.  */
01384               local_fullname = alloca (strlen (s_fullname) + 1);
01385               strcpy (local_fullname, s_fullname);
01386 
01387               ui_out_field_string (uiout, "fullname", local_fullname);
01388             }
01389 
01390           ui_out_text (uiout, "\n");
01391         }
01392 
01393       return;
01394     }
01395 
01396   last_source_error = 0;
01397 
01398   if (s->line_charpos == 0)
01399     find_source_lines (s, desc);
01400 
01401   if (line < 1 || line > s->nlines)
01402     {
01403       close (desc);
01404       error (_("Line number %d out of range; %s has %d lines."),
01405              line, symtab_to_filename_for_display (s), s->nlines);
01406     }
01407 
01408   if (lseek (desc, s->line_charpos[line - 1], 0) < 0)
01409     {
01410       close (desc);
01411       perror_with_name (symtab_to_filename_for_display (s));
01412     }
01413 
01414   stream = fdopen (desc, FDOPEN_MODE);
01415   clearerr (stream);
01416   cleanup = make_cleanup_fclose (stream);
01417 
01418   while (nlines-- > 0)
01419     {
01420       char buf[20];
01421 
01422       c = fgetc (stream);
01423       if (c == EOF)
01424         break;
01425       last_line_listed = current_source_line;
01426       if (flags & PRINT_SOURCE_LINES_FILENAME)
01427         {
01428           ui_out_text (uiout, symtab_to_filename_for_display (s));
01429           ui_out_text (uiout, ":");
01430         }
01431       xsnprintf (buf, sizeof (buf), "%d\t", current_source_line++);
01432       ui_out_text (uiout, buf);
01433       do
01434         {
01435           if (c < 040 && c != '\t' && c != '\n' && c != '\r')
01436             {
01437               xsnprintf (buf, sizeof (buf), "^%c", c + 0100);
01438               ui_out_text (uiout, buf);
01439             }
01440           else if (c == 0177)
01441             ui_out_text (uiout, "^?");
01442           else if (c == '\r')
01443             {
01444               /* Skip a \r character, but only before a \n.  */
01445               int c1 = fgetc (stream);
01446 
01447               if (c1 != '\n')
01448                 printf_filtered ("^%c", c + 0100);
01449               if (c1 != EOF)
01450                 ungetc (c1, stream);
01451             }
01452           else
01453             {
01454               xsnprintf (buf, sizeof (buf), "%c", c);
01455               ui_out_text (uiout, buf);
01456             }
01457         }
01458       while (c != '\n' && (c = fgetc (stream)) >= 0);
01459     }
01460 
01461   do_cleanups (cleanup);
01462 }
01463 
01464 /* Show source lines from the file of symtab S, starting with line
01465    number LINE and stopping before line number STOPLINE.  If this is
01466    not the command line version, then the source is shown in the source
01467    window otherwise it is simply printed.  */
01468 
01469 void
01470 print_source_lines (struct symtab *s, int line, int stopline,
01471                     enum print_source_lines_flags flags)
01472 {
01473   print_source_lines_base (s, line, stopline, flags);
01474 }
01475 
01476 /* Print info on range of pc's in a specified line.  */
01477 
01478 static void
01479 line_info (char *arg, int from_tty)
01480 {
01481   struct symtabs_and_lines sals;
01482   struct symtab_and_line sal;
01483   CORE_ADDR start_pc, end_pc;
01484   int i;
01485   struct cleanup *cleanups;
01486 
01487   init_sal (&sal);              /* initialize to zeroes */
01488 
01489   if (arg == 0)
01490     {
01491       sal.symtab = current_source_symtab;
01492       sal.pspace = current_program_space;
01493       sal.line = last_line_listed;
01494       sals.nelts = 1;
01495       sals.sals = (struct symtab_and_line *)
01496         xmalloc (sizeof (struct symtab_and_line));
01497       sals.sals[0] = sal;
01498     }
01499   else
01500     {
01501       sals = decode_line_with_last_displayed (arg, DECODE_LINE_LIST_MODE);
01502 
01503       dont_repeat ();
01504     }
01505 
01506   cleanups = make_cleanup (xfree, sals.sals);
01507 
01508   /* C++  More than one line may have been specified, as when the user
01509      specifies an overloaded function name.  Print info on them all.  */
01510   for (i = 0; i < sals.nelts; i++)
01511     {
01512       sal = sals.sals[i];
01513       if (sal.pspace != current_program_space)
01514         continue;
01515 
01516       if (sal.symtab == 0)
01517         {
01518           struct gdbarch *gdbarch = get_current_arch ();
01519 
01520           printf_filtered (_("No line number information available"));
01521           if (sal.pc != 0)
01522             {
01523               /* This is useful for "info line *0x7f34".  If we can't tell the
01524                  user about a source line, at least let them have the symbolic
01525                  address.  */
01526               printf_filtered (" for address ");
01527               wrap_here ("  ");
01528               print_address (gdbarch, sal.pc, gdb_stdout);
01529             }
01530           else
01531             printf_filtered (".");
01532           printf_filtered ("\n");
01533         }
01534       else if (sal.line > 0
01535                && find_line_pc_range (sal, &start_pc, &end_pc))
01536         {
01537           struct gdbarch *gdbarch = get_objfile_arch (sal.symtab->objfile);
01538 
01539           if (start_pc == end_pc)
01540             {
01541               printf_filtered ("Line %d of \"%s\"",
01542                                sal.line,
01543                                symtab_to_filename_for_display (sal.symtab));
01544               wrap_here ("  ");
01545               printf_filtered (" is at address ");
01546               print_address (gdbarch, start_pc, gdb_stdout);
01547               wrap_here ("  ");
01548               printf_filtered (" but contains no code.\n");
01549             }
01550           else
01551             {
01552               printf_filtered ("Line %d of \"%s\"",
01553                                sal.line,
01554                                symtab_to_filename_for_display (sal.symtab));
01555               wrap_here ("  ");
01556               printf_filtered (" starts at address ");
01557               print_address (gdbarch, start_pc, gdb_stdout);
01558               wrap_here ("  ");
01559               printf_filtered (" and ends at ");
01560               print_address (gdbarch, end_pc, gdb_stdout);
01561               printf_filtered (".\n");
01562             }
01563 
01564           /* x/i should display this line's code.  */
01565           set_next_address (gdbarch, start_pc);
01566 
01567           /* Repeating "info line" should do the following line.  */
01568           last_line_listed = sal.line + 1;
01569 
01570           /* If this is the only line, show the source code.  If it could
01571              not find the file, don't do anything special.  */
01572           if (annotation_level && sals.nelts == 1)
01573             identify_source_line (sal.symtab, sal.line, 0, start_pc);
01574         }
01575       else
01576         /* Is there any case in which we get here, and have an address
01577            which the user would want to see?  If we have debugging symbols
01578            and no line numbers?  */
01579         printf_filtered (_("Line number %d is out of range for \"%s\".\n"),
01580                          sal.line, symtab_to_filename_for_display (sal.symtab));
01581     }
01582   do_cleanups (cleanups);
01583 }
01584 
01585 /* Commands to search the source file for a regexp.  */
01586 
01587 static void
01588 forward_search_command (char *regex, int from_tty)
01589 {
01590   int c;
01591   int desc;
01592   FILE *stream;
01593   int line;
01594   char *msg;
01595   struct cleanup *cleanups;
01596 
01597   line = last_line_listed + 1;
01598 
01599   msg = (char *) re_comp (regex);
01600   if (msg)
01601     error (("%s"), msg);
01602 
01603   if (current_source_symtab == 0)
01604     select_source_symtab (0);
01605 
01606   desc = open_source_file (current_source_symtab);
01607   if (desc < 0)
01608     perror_with_name (symtab_to_filename_for_display (current_source_symtab));
01609   cleanups = make_cleanup_close (desc);
01610 
01611   if (current_source_symtab->line_charpos == 0)
01612     find_source_lines (current_source_symtab, desc);
01613 
01614   if (line < 1 || line > current_source_symtab->nlines)
01615     error (_("Expression not found"));
01616 
01617   if (lseek (desc, current_source_symtab->line_charpos[line - 1], 0) < 0)
01618     perror_with_name (symtab_to_filename_for_display (current_source_symtab));
01619 
01620   discard_cleanups (cleanups);
01621   stream = fdopen (desc, FDOPEN_MODE);
01622   clearerr (stream);
01623   cleanups = make_cleanup_fclose (stream);
01624   while (1)
01625     {
01626       static char *buf = NULL;
01627       char *p;
01628       int cursize, newsize;
01629 
01630       cursize = 256;
01631       buf = xmalloc (cursize);
01632       p = buf;
01633 
01634       c = fgetc (stream);
01635       if (c == EOF)
01636         break;
01637       do
01638         {
01639           *p++ = c;
01640           if (p - buf == cursize)
01641             {
01642               newsize = cursize + cursize / 2;
01643               buf = xrealloc (buf, newsize);
01644               p = buf + cursize;
01645               cursize = newsize;
01646             }
01647         }
01648       while (c != '\n' && (c = fgetc (stream)) >= 0);
01649 
01650       /* Remove the \r, if any, at the end of the line, otherwise
01651          regular expressions that end with $ or \n won't work.  */
01652       if (p - buf > 1 && p[-2] == '\r')
01653         {
01654           p--;
01655           p[-1] = '\n';
01656         }
01657 
01658       /* We now have a source line in buf, null terminate and match.  */
01659       *p = 0;
01660       if (re_exec (buf) > 0)
01661         {
01662           /* Match!  */
01663           do_cleanups (cleanups);
01664           print_source_lines (current_source_symtab, line, line + 1, 0);
01665           set_internalvar_integer (lookup_internalvar ("_"), line);
01666           current_source_line = max (line - lines_to_list / 2, 1);
01667           return;
01668         }
01669       line++;
01670     }
01671 
01672   printf_filtered (_("Expression not found\n"));
01673   do_cleanups (cleanups);
01674 }
01675 
01676 static void
01677 reverse_search_command (char *regex, int from_tty)
01678 {
01679   int c;
01680   int desc;
01681   FILE *stream;
01682   int line;
01683   char *msg;
01684   struct cleanup *cleanups;
01685 
01686   line = last_line_listed - 1;
01687 
01688   msg = (char *) re_comp (regex);
01689   if (msg)
01690     error (("%s"), msg);
01691 
01692   if (current_source_symtab == 0)
01693     select_source_symtab (0);
01694 
01695   desc = open_source_file (current_source_symtab);
01696   if (desc < 0)
01697     perror_with_name (symtab_to_filename_for_display (current_source_symtab));
01698   cleanups = make_cleanup_close (desc);
01699 
01700   if (current_source_symtab->line_charpos == 0)
01701     find_source_lines (current_source_symtab, desc);
01702 
01703   if (line < 1 || line > current_source_symtab->nlines)
01704     error (_("Expression not found"));
01705 
01706   if (lseek (desc, current_source_symtab->line_charpos[line - 1], 0) < 0)
01707     perror_with_name (symtab_to_filename_for_display (current_source_symtab));
01708 
01709   discard_cleanups (cleanups);
01710   stream = fdopen (desc, FDOPEN_MODE);
01711   clearerr (stream);
01712   cleanups = make_cleanup_fclose (stream);
01713   while (line > 1)
01714     {
01715 /* FIXME!!!  We walk right off the end of buf if we get a long line!!!  */
01716       char buf[4096];           /* Should be reasonable???  */
01717       char *p = buf;
01718 
01719       c = fgetc (stream);
01720       if (c == EOF)
01721         break;
01722       do
01723         {
01724           *p++ = c;
01725         }
01726       while (c != '\n' && (c = fgetc (stream)) >= 0);
01727 
01728       /* Remove the \r, if any, at the end of the line, otherwise
01729          regular expressions that end with $ or \n won't work.  */
01730       if (p - buf > 1 && p[-2] == '\r')
01731         {
01732           p--;
01733           p[-1] = '\n';
01734         }
01735 
01736       /* We now have a source line in buf; null terminate and match.  */
01737       *p = 0;
01738       if (re_exec (buf) > 0)
01739         {
01740           /* Match!  */
01741           do_cleanups (cleanups);
01742           print_source_lines (current_source_symtab, line, line + 1, 0);
01743           set_internalvar_integer (lookup_internalvar ("_"), line);
01744           current_source_line = max (line - lines_to_list / 2, 1);
01745           return;
01746         }
01747       line--;
01748       if (fseek (stream, current_source_symtab->line_charpos[line - 1], 0) < 0)
01749         {
01750           const char *filename;
01751 
01752           do_cleanups (cleanups);
01753           filename = symtab_to_filename_for_display (current_source_symtab);
01754           perror_with_name (filename);
01755         }
01756     }
01757 
01758   printf_filtered (_("Expression not found\n"));
01759   do_cleanups (cleanups);
01760   return;
01761 }
01762 
01763 /* If the last character of PATH is a directory separator, then strip it.  */
01764 
01765 static void
01766 strip_trailing_directory_separator (char *path)
01767 {
01768   const int last = strlen (path) - 1;
01769 
01770   if (last < 0)
01771     return;  /* No stripping is needed if PATH is the empty string.  */
01772 
01773   if (IS_DIR_SEPARATOR (path[last]))
01774     path[last] = '\0';
01775 }
01776 
01777 /* Return the path substitution rule that matches FROM.
01778    Return NULL if no rule matches.  */
01779 
01780 static struct substitute_path_rule *
01781 find_substitute_path_rule (const char *from)
01782 {
01783   struct substitute_path_rule *rule = substitute_path_rules;
01784 
01785   while (rule != NULL)
01786     {
01787       if (FILENAME_CMP (rule->from, from) == 0)
01788         return rule;
01789       rule = rule->next;
01790     }
01791 
01792   return NULL;
01793 }
01794 
01795 /* Add a new substitute-path rule at the end of the current list of rules.
01796    The new rule will replace FROM into TO.  */
01797 
01798 void
01799 add_substitute_path_rule (char *from, char *to)
01800 {
01801   struct substitute_path_rule *rule;
01802   struct substitute_path_rule *new_rule;
01803 
01804   new_rule = xmalloc (sizeof (struct substitute_path_rule));
01805   new_rule->from = xstrdup (from);
01806   new_rule->to = xstrdup (to);
01807   new_rule->next = NULL;
01808 
01809   /* If the list of rules are empty, then insert the new rule
01810      at the head of the list.  */
01811 
01812   if (substitute_path_rules == NULL)
01813     {
01814       substitute_path_rules = new_rule;
01815       return;
01816     }
01817 
01818   /* Otherwise, skip to the last rule in our list and then append
01819      the new rule.  */
01820 
01821   rule = substitute_path_rules;
01822   while (rule->next != NULL)
01823     rule = rule->next;
01824 
01825   rule->next = new_rule;
01826 }
01827 
01828 /* Remove the given source path substitution rule from the current list
01829    of rules.  The memory allocated for that rule is also deallocated.  */
01830 
01831 static void
01832 delete_substitute_path_rule (struct substitute_path_rule *rule)
01833 {
01834   if (rule == substitute_path_rules)
01835     substitute_path_rules = rule->next;
01836   else
01837     {
01838       struct substitute_path_rule *prev = substitute_path_rules;
01839 
01840       while (prev != NULL && prev->next != rule)
01841         prev = prev->next;
01842 
01843       gdb_assert (prev != NULL);
01844 
01845       prev->next = rule->next;
01846     }
01847 
01848   xfree (rule->from);
01849   xfree (rule->to);
01850   xfree (rule);
01851 }
01852 
01853 /* Implement the "show substitute-path" command.  */
01854 
01855 static void
01856 show_substitute_path_command (char *args, int from_tty)
01857 {
01858   struct substitute_path_rule *rule = substitute_path_rules;
01859   char **argv;
01860   char *from = NULL;
01861   struct cleanup *cleanup;
01862   
01863   argv = gdb_buildargv (args);
01864   cleanup = make_cleanup_freeargv (argv);
01865 
01866   /* We expect zero or one argument.  */
01867 
01868   if (argv != NULL && argv[0] != NULL && argv[1] != NULL)
01869     error (_("Too many arguments in command"));
01870 
01871   if (argv != NULL && argv[0] != NULL)
01872     from = argv[0];
01873 
01874   /* Print the substitution rules.  */
01875 
01876   if (from != NULL)
01877     printf_filtered
01878       (_("Source path substitution rule matching `%s':\n"), from);
01879   else
01880     printf_filtered (_("List of all source path substitution rules:\n"));
01881 
01882   while (rule != NULL)
01883     {
01884       if (from == NULL || FILENAME_CMP (rule->from, from) == 0)
01885         printf_filtered ("  `%s' -> `%s'.\n", rule->from, rule->to);
01886       rule = rule->next;
01887     }
01888 
01889   do_cleanups (cleanup);
01890 }
01891 
01892 /* Implement the "unset substitute-path" command.  */
01893 
01894 static void
01895 unset_substitute_path_command (char *args, int from_tty)
01896 {
01897   struct substitute_path_rule *rule = substitute_path_rules;
01898   char **argv = gdb_buildargv (args);
01899   char *from = NULL;
01900   int rule_found = 0;
01901   struct cleanup *cleanup;
01902 
01903   /* This function takes either 0 or 1 argument.  */
01904 
01905   cleanup = make_cleanup_freeargv (argv);
01906   if (argv != NULL && argv[0] != NULL && argv[1] != NULL)
01907     error (_("Incorrect usage, too many arguments in command"));
01908 
01909   if (argv != NULL && argv[0] != NULL)
01910     from = argv[0];
01911 
01912   /* If the user asked for all the rules to be deleted, ask him
01913      to confirm and give him a chance to abort before the action
01914      is performed.  */
01915 
01916   if (from == NULL
01917       && !query (_("Delete all source path substitution rules? ")))
01918     error (_("Canceled"));
01919 
01920   /* Delete the rule matching the argument.  No argument means that
01921      all rules should be deleted.  */
01922 
01923   while (rule != NULL)
01924     {
01925       struct substitute_path_rule *next = rule->next;
01926 
01927       if (from == NULL || FILENAME_CMP (from, rule->from) == 0)
01928         {
01929           delete_substitute_path_rule (rule);
01930           rule_found = 1;
01931         }
01932 
01933       rule = next;
01934     }
01935   
01936   /* If the user asked for a specific rule to be deleted but
01937      we could not find it, then report an error.  */
01938 
01939   if (from != NULL && !rule_found)
01940     error (_("No substitution rule defined for `%s'"), from);
01941 
01942   forget_cached_source_info ();
01943 
01944   do_cleanups (cleanup);
01945 }
01946 
01947 /* Add a new source path substitution rule.  */
01948 
01949 static void
01950 set_substitute_path_command (char *args, int from_tty)
01951 {
01952   char **argv;
01953   struct substitute_path_rule *rule;
01954   struct cleanup *cleanup;
01955   
01956   argv = gdb_buildargv (args);
01957   cleanup = make_cleanup_freeargv (argv);
01958 
01959   if (argv == NULL || argv[0] == NULL || argv [1] == NULL)
01960     error (_("Incorrect usage, too few arguments in command"));
01961 
01962   if (argv[2] != NULL)
01963     error (_("Incorrect usage, too many arguments in command"));
01964 
01965   if (*(argv[0]) == '\0')
01966     error (_("First argument must be at least one character long"));
01967 
01968   /* Strip any trailing directory separator character in either FROM
01969      or TO.  The substitution rule already implicitly contains them.  */
01970   strip_trailing_directory_separator (argv[0]);
01971   strip_trailing_directory_separator (argv[1]);
01972 
01973   /* If a rule with the same "from" was previously defined, then
01974      delete it.  This new rule replaces it.  */
01975 
01976   rule = find_substitute_path_rule (argv[0]);
01977   if (rule != NULL)
01978     delete_substitute_path_rule (rule);
01979       
01980   /* Insert the new substitution rule.  */
01981 
01982   add_substitute_path_rule (argv[0], argv[1]);
01983   forget_cached_source_info ();
01984 
01985   do_cleanups (cleanup);
01986 }
01987 
01988 
01989 void
01990 _initialize_source (void)
01991 {
01992   struct cmd_list_element *c;
01993 
01994   current_source_symtab = 0;
01995   init_source_path ();
01996 
01997   /* The intention is to use POSIX Basic Regular Expressions.
01998      Always use the GNU regex routine for consistency across all hosts.
01999      Our current GNU regex.c does not have all the POSIX features, so this is
02000      just an approximation.  */
02001   re_set_syntax (RE_SYNTAX_GREP);
02002 
02003   c = add_cmd ("directory", class_files, directory_command, _("\
02004 Add directory DIR to beginning of search path for source files.\n\
02005 Forget cached info on source file locations and line positions.\n\
02006 DIR can also be $cwd for the current working directory, or $cdir for the\n\
02007 directory in which the source file was compiled into object code.\n\
02008 With no argument, reset the search path to $cdir:$cwd, the default."),
02009                &cmdlist);
02010 
02011   if (dbx_commands)
02012     add_com_alias ("use", "directory", class_files, 0);
02013 
02014   set_cmd_completer (c, filename_completer);
02015 
02016   add_setshow_optional_filename_cmd ("directories",
02017                                      class_files,
02018                                      &source_path,
02019                                      _("\
02020 Set the search path for finding source files."),
02021                                      _("\
02022 Show the search path for finding source files."),
02023                                      _("\
02024 $cwd in the path means the current working directory.\n\
02025 $cdir in the path means the compilation directory of the source file.\n\
02026 GDB ensures the search path always ends with $cdir:$cwd by\n\
02027 appending these directories if necessary.\n\
02028 Setting the value to an empty string sets it to $cdir:$cwd, the default."),
02029                             set_directories_command,
02030                             show_directories_command,
02031                             &setlist, &showlist);
02032 
02033   if (xdb_commands)
02034     {
02035       add_com_alias ("D", "directory", class_files, 0);
02036       add_cmd ("ld", no_class, show_directories_1, _("\
02037 Current search path for finding source files.\n\
02038 $cwd in the path means the current working directory.\n\
02039 $cdir in the path means the compilation directory of the source file."),
02040                &cmdlist);
02041     }
02042 
02043   add_info ("source", source_info,
02044             _("Information about the current source file."));
02045 
02046   add_info ("line", line_info, _("\
02047 Core addresses of the code for a source line.\n\
02048 Line can be specified as\n\
02049   LINENUM, to list around that line in current file,\n\
02050   FILE:LINENUM, to list around that line in that file,\n\
02051   FUNCTION, to list around beginning of that function,\n\
02052   FILE:FUNCTION, to distinguish among like-named static functions.\n\
02053 Default is to describe the last source line that was listed.\n\n\
02054 This sets the default address for \"x\" to the line's first instruction\n\
02055 so that \"x/i\" suffices to start examining the machine code.\n\
02056 The address is also stored as the value of \"$_\"."));
02057 
02058   add_com ("forward-search", class_files, forward_search_command, _("\
02059 Search for regular expression (see regex(3)) from last line listed.\n\
02060 The matching line number is also stored as the value of \"$_\"."));
02061   add_com_alias ("search", "forward-search", class_files, 0);
02062   add_com_alias ("fo", "forward-search", class_files, 1);
02063 
02064   add_com ("reverse-search", class_files, reverse_search_command, _("\
02065 Search backward for regular expression (see regex(3)) from last line listed.\n\
02066 The matching line number is also stored as the value of \"$_\"."));
02067   add_com_alias ("rev", "reverse-search", class_files, 1);
02068 
02069   if (xdb_commands)
02070     {
02071       add_com_alias ("/", "forward-search", class_files, 0);
02072       add_com_alias ("?", "reverse-search", class_files, 0);
02073     }
02074 
02075   add_setshow_integer_cmd ("listsize", class_support, &lines_to_list, _("\
02076 Set number of source lines gdb will list by default."), _("\
02077 Show number of source lines gdb will list by default."), _("\
02078 Use this to choose how many source lines the \"list\" displays (unless\n\
02079 the \"list\" argument explicitly specifies some other number).\n\
02080 A value of \"unlimited\", or zero, means there's no limit."),
02081                             NULL,
02082                             show_lines_to_list,
02083                             &setlist, &showlist);
02084 
02085   add_cmd ("substitute-path", class_files, set_substitute_path_command,
02086            _("\
02087 Usage: set substitute-path FROM TO\n\
02088 Add a substitution rule replacing FROM into TO in source file names.\n\
02089 If a substitution rule was previously set for FROM, the old rule\n\
02090 is replaced by the new one."),
02091            &setlist);
02092 
02093   add_cmd ("substitute-path", class_files, unset_substitute_path_command,
02094            _("\
02095 Usage: unset substitute-path [FROM]\n\
02096 Delete the rule for substituting FROM in source file names.  If FROM\n\
02097 is not specified, all substituting rules are deleted.\n\
02098 If the debugger cannot find a rule for FROM, it will display a warning."),
02099            &unsetlist);
02100 
02101   add_cmd ("substitute-path", class_files, show_substitute_path_command,
02102            _("\
02103 Usage: show substitute-path [FROM]\n\
02104 Print the rule for substituting FROM in source file names. If FROM\n\
02105 is not specified, print all substitution rules."),
02106            &showlist);
02107 
02108   add_setshow_enum_cmd ("filename-display", class_files,
02109                         filename_display_kind_names,
02110                         &filename_display_string, _("\
02111 Set how to display filenames."), _("\
02112 Show how to display filenames."), _("\
02113 filename-display can be:\n\
02114   basename - display only basename of a filename\n\
02115   relative - display a filename relative to the compilation directory\n\
02116   absolute - display an absolute filename\n\
02117 By default, relative filenames are displayed."),
02118                         NULL,
02119                         show_filename_display_string,
02120                         &setlist, &showlist);
02121 
02122 }
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Defines