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