* buildsym.h (struct subfile): Add debugformat member.
[external/binutils.git] / gdb / source.c
1 /* List lines of source files for GDB, the GNU debugger.
2    Copyright 1986, 1987, 1988, 1989, 1991, 1992, 1993, 1994, 1995
3    Free Software Foundation, Inc.
4
5 This file is part of GDB.
6
7 This program is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 2 of the License, or
10 (at your option) any later version.
11
12 This program is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 GNU General Public License for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with this program; if not, write to the Free Software
19 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.  */
20
21 #include "defs.h"
22 #include "symtab.h"
23 #include "expression.h"
24 #include "language.h"
25 #include "command.h"
26 #include "gdbcmd.h"
27 #include "frame.h"
28 #include "value.h"
29
30 #include <sys/types.h>
31 #include "gdb_string.h"
32 #include "gdb_stat.h"
33 #include <fcntl.h>
34 #ifdef HAVE_UNISTD_H
35 #include <unistd.h>
36 #endif
37 #include "gdbcore.h"
38 #include "gnu-regex.h"
39 #include "symfile.h"
40 #include "objfiles.h"
41 #include "annotate.h"
42 #include "gdbtypes.h"
43
44 /* Prototypes for local functions. */
45
46 static int open_source_file PARAMS ((struct symtab *));
47
48 static int get_filename_and_charpos PARAMS ((struct symtab *, char **));
49
50 static void reverse_search_command PARAMS ((char *, int));
51
52 static void forward_search_command PARAMS ((char *, int));
53
54 static void line_info PARAMS ((char *, int));
55
56 static void list_command PARAMS ((char *, int));
57
58 static void ambiguous_line_spec PARAMS ((struct symtabs_and_lines *));
59
60 static void source_info PARAMS ((char *, int));
61
62 static void show_directories PARAMS ((char *, int));
63
64 static void find_source_lines PARAMS ((struct symtab *, int));
65
66 /* If we use this declaration, it breaks because of fucking ANSI "const" stuff
67    on some systems.  We just have to not declare it at all, have it default
68    to int, and possibly botch on a few systems.  Thanks, ANSIholes... */
69 /* extern char *strstr(); */
70
71 /* Path of directories to search for source files.
72    Same format as the PATH environment variable's value.  */
73
74 char *source_path;
75
76 /* Symtab of default file for listing lines of.  */
77
78 struct symtab *current_source_symtab;
79
80 /* Default next line to list.  */
81
82 int current_source_line;
83
84 /* Default number of lines to print with commands like "list".
85    This is based on guessing how many long (i.e. more than chars_per_line
86    characters) lines there will be.  To be completely correct, "list"
87    and friends should be rewritten to count characters and see where
88    things are wrapping, but that would be a fair amount of work.  */
89
90 int lines_to_list = 10;
91
92 /* Line number of last line printed.  Default for various commands.
93    current_source_line is usually, but not always, the same as this.  */
94
95 static int last_line_listed;
96
97 /* First line number listed by last listing command.  */
98
99 static int first_line_listed;
100
101 \f
102 /* Set the source file default for the "list" command to be S.
103
104    If S is NULL, and we don't have a default, find one.  This
105    should only be called when the user actually tries to use the
106    default, since we produce an error if we can't find a reasonable
107    default.  Also, since this can cause symbols to be read, doing it
108    before we need to would make things slower than necessary.  */
109
110 void
111 select_source_symtab (s)
112      register struct symtab *s;
113 {
114   struct symtabs_and_lines sals;
115   struct symtab_and_line sal;
116   struct partial_symtab *ps;
117   struct partial_symtab *cs_pst = 0;
118   struct objfile *ofp;
119   
120   if (s)
121     {
122       current_source_symtab = s;
123       current_source_line = 1;
124       return;
125     }
126
127   if (current_source_symtab)
128     return;
129
130   /* Make the default place to list be the function `main'
131      if one exists.  */
132   if (lookup_symbol ("main", 0, VAR_NAMESPACE, 0, NULL))
133     {
134       sals = decode_line_spec ("main", 1);
135       sal = sals.sals[0];
136       free (sals.sals);
137       current_source_symtab = sal.symtab;
138       current_source_line = max (sal.line - (lines_to_list - 1), 1);
139       if (current_source_symtab)
140         return;
141     }
142   
143   /* All right; find the last file in the symtab list (ignoring .h's).  */
144
145   current_source_line = 1;
146
147   for (ofp = object_files; ofp != NULL; ofp = ofp -> next)
148     {
149       for (s = ofp -> symtabs; s; s = s->next)
150         {
151           char *name = s -> filename;
152           int len = strlen (name);
153           if (! (len > 2 && (STREQ (&name[len - 2], ".h"))))
154             {
155               current_source_symtab = s;
156             }
157         }
158     }
159   if (current_source_symtab)
160     return;
161
162   /* Howabout the partial symbol tables? */
163
164   for (ofp = object_files; ofp != NULL; ofp = ofp -> next)
165     {
166       for (ps = ofp -> psymtabs; ps != NULL; ps = ps -> next)
167         {
168           char *name = ps -> filename;
169           int len = strlen (name);
170           if (! (len > 2 && (STREQ (&name[len - 2], ".h"))))
171             {
172               cs_pst = ps;
173             }
174         }
175     }
176   if (cs_pst)
177     {
178       if (cs_pst -> readin)
179         {
180           fatal ("Internal: select_source_symtab: readin pst found and no symtabs.");
181         }
182       else
183         {
184           current_source_symtab = PSYMTAB_TO_SYMTAB (cs_pst);
185         }
186     }
187
188   error ("Can't find a default source file");
189 }
190 \f
191 static void
192 show_directories (ignore, from_tty)
193      char *ignore;
194      int from_tty;
195 {
196   puts_filtered ("Source directories searched: ");
197   puts_filtered (source_path);
198   puts_filtered ("\n");
199 }
200
201 /* Forget what we learned about line positions in source files, and
202    which directories contain them; must check again now since files
203    may be found in a different directory now.  */
204
205 void
206 forget_cached_source_info ()
207 {
208   register struct symtab *s;
209   register struct objfile *objfile;
210
211   for (objfile = object_files; objfile != NULL; objfile = objfile -> next)
212     {
213       for (s = objfile -> symtabs; s != NULL; s = s -> next)
214         {
215           if (s -> line_charpos != NULL)
216             {
217               mfree (objfile -> md, s -> line_charpos);
218               s -> line_charpos = NULL;
219             }
220           if (s -> fullname != NULL)
221             {
222               mfree (objfile -> md, s -> fullname);
223               s -> fullname = NULL;
224             }
225         }
226     }
227 }
228
229 void
230 init_source_path ()
231 {
232   char buf[20];
233
234   sprintf (buf, "$cdir%c$cwd", DIRNAME_SEPARATOR);
235   source_path = strsave (buf);
236   forget_cached_source_info ();
237 }
238
239 /* Add zero or more directories to the front of the source path.  */
240  
241 void
242 directory_command (dirname, from_tty)
243      char *dirname;
244      int from_tty;
245 {
246   dont_repeat ();
247   /* FIXME, this goes to "delete dir"... */
248   if (dirname == 0)
249     {
250       if (query ("Reinitialize source path to empty? "))
251         {
252           free (source_path);
253           init_source_path ();
254         }
255     }
256   else
257     mod_path (dirname, &source_path);
258   if (from_tty)
259     show_directories ((char *)0, from_tty);
260   forget_cached_source_info ();
261 }
262
263 /* Add zero or more directories to the front of an arbitrary path.  */
264
265 void
266 mod_path (dirname, which_path)
267      char *dirname;
268      char **which_path;
269 {
270   char *old = *which_path;
271   int prefix = 0;
272
273   if (dirname == 0)
274     return;
275
276   dirname = strsave (dirname);
277   make_cleanup (free, dirname);
278
279   do
280     {
281       char *name = dirname;
282       register char *p;
283       struct stat st;
284
285       {
286         char *separator = strchr (name, DIRNAME_SEPARATOR);
287         char *space = strchr (name, ' ');
288         char *tab = strchr (name, '\t');
289
290         if (separator == 0 && space == 0 && tab ==  0)
291           p = dirname = name + strlen (name);
292         else
293           {
294             p = 0;
295             if (separator != 0 && (p == 0 || separator < p))
296               p = separator;
297             if (space != 0 && (p == 0 || space < p))
298               p = space;
299             if (tab != 0 && (p == 0 || tab < p))
300               p = tab;
301             dirname = p + 1;
302             while (*dirname == DIRNAME_SEPARATOR
303                    || *dirname == ' '
304                    || *dirname == '\t')
305               ++dirname;
306           }
307       }
308
309 #ifndef WIN32 
310       /* On win32 h:\ is different to h: */
311       if (SLASH_P (p[-1]))
312         /* Sigh. "foo/" => "foo" */
313         --p;
314 #endif
315       *p = '\0';
316
317       while (p[-1] == '.')
318         {
319           if (p - name == 1)
320             {
321               /* "." => getwd ().  */
322               name = current_directory;
323               goto append;
324             }
325           else if (SLASH_P (p[-2]))
326             {
327               if (p - name == 2)
328                 {
329                   /* "/." => "/".  */
330                   *--p = '\0';
331                   goto append;
332                 }
333               else
334                 {
335                   /* "...foo/." => "...foo".  */
336                   p -= 2;
337                   *p = '\0';
338                   continue;
339                 }
340             }
341           else
342             break;
343         }
344
345       if (name[0] == '~')
346         name = tilde_expand (name);
347       else if (!ROOTED_P (name) && name[0] != '$') 
348           name = concat (current_directory, SLASH_STRING, name, NULL);
349       else
350         name = savestring (name, p - name);
351       make_cleanup (free, name);
352
353       /* Unless it's a variable, check existence.  */
354       if (name[0] != '$') {
355         /* These are warnings, not errors, since we don't want a
356            non-existent directory in a .gdbinit file to stop processing
357            of the .gdbinit file.
358
359            Whether they get added to the path is more debatable.  Current
360            answer is yes, in case the user wants to go make the directory
361            or whatever.  If the directory continues to not exist/not be
362            a directory/etc, then having them in the path should be
363            harmless.  */
364         if (stat (name, &st) < 0)
365           {
366             int save_errno = errno;
367             fprintf_unfiltered (gdb_stderr, "Warning: ");
368             print_sys_errmsg (name, save_errno);
369           }
370         else if ((st.st_mode & S_IFMT) != S_IFDIR)
371           warning ("%s is not a directory.", name);
372       }
373
374     append:
375       {
376         register unsigned int len = strlen (name);
377
378         p = *which_path;
379         while (1)
380           {
381             if (!strncmp (p, name, len)
382                 && (p[len] == '\0' || p[len] == DIRNAME_SEPARATOR))
383               {
384                 /* Found it in the search path, remove old copy */
385                 if (p > *which_path)
386                   p--;                  /* Back over leading separator */
387                 if (prefix > p - *which_path)
388                   goto skip_dup;        /* Same dir twice in one cmd */
389                 strcpy (p, &p[len+1]);  /* Copy from next \0 or  : */
390               }
391             p = strchr (p, DIRNAME_SEPARATOR);
392             if (p != 0)
393               ++p;
394             else
395               break;
396           }
397         if (p == 0)
398           {
399             char tinybuf[2];
400
401             tinybuf[0] = DIRNAME_SEPARATOR;
402             tinybuf[1] = '\0';
403
404             /* If we have already tacked on a name(s) in this command,                     be sure they stay on the front as we tack on some more.  */
405             if (prefix)
406               {
407                 char *temp, c;
408
409                 c = old[prefix];
410                 old[prefix] = '\0';
411                 temp = concat (old, tinybuf, name, NULL);
412                 old[prefix] = c;
413                 *which_path = concat (temp, "", &old[prefix], NULL);
414                 prefix = strlen (temp);
415                 free (temp);
416               }
417             else
418               {
419                 *which_path = concat (name, (old[0] ? tinybuf : old), old, NULL);
420                 prefix = strlen (name);
421               }
422             free (old);
423             old = *which_path;
424           }
425       }
426   skip_dup: ;
427     } while (*dirname != '\0');
428 }
429
430
431 static void
432 source_info (ignore, from_tty)
433      char *ignore;
434      int from_tty;
435 {
436   register struct symtab *s = current_source_symtab;
437
438   if (!s)
439     {
440       printf_filtered("No current source file.\n");
441       return;
442     }
443   printf_filtered ("Current source file is %s\n", s->filename);
444   if (s->dirname)
445     printf_filtered ("Compilation directory is %s\n", s->dirname);
446   if (s->fullname)
447     printf_filtered ("Located in %s\n", s->fullname);
448   if (s->nlines)
449     printf_filtered ("Contains %d line%s.\n", s->nlines,
450                      s->nlines == 1 ? "" : "s");
451
452   printf_filtered ("Source language is %s.\n", language_str (s->language));
453   printf_filtered ("Compiled with %s debugging format.\n", s->debugformat);
454 }
455
456
457 \f
458 /* Open a file named STRING, searching path PATH (dir names sep by some char)
459    using mode MODE and protection bits PROT in the calls to open.
460
461    If TRY_CWD_FIRST, try to open ./STRING before searching PATH.
462    (ie pretend the first element of PATH is ".").  This also indicates
463    that a slash in STRING disables searching of the path (this is
464    so that "exec-file ./foo" or "symbol-file ./foo" insures that you
465    get that particular version of foo or an error message).
466
467    If FILENAMED_OPENED is non-null, set it to a newly allocated string naming
468    the actual file opened (this string will always start with a "/".  We
469    have to take special pains to avoid doubling the "/" between the directory
470    and the file, sigh!  Emacs gets confuzzed by this when we print the
471    source file name!!! 
472
473    If a file is found, return the descriptor.
474    Otherwise, return -1, with errno set for the last name we tried to open.  */
475
476 /*  >>>> This should only allow files of certain types,
477     >>>>  eg executable, non-directory */
478 int
479 openp (path, try_cwd_first, string, mode, prot, filename_opened)
480      char *path;
481      int try_cwd_first;
482      char *string;
483      int mode;
484      int prot;
485      char **filename_opened;
486 {
487   register int fd;
488   register char *filename;
489   register char *p, *p1;
490   register int len;
491   int alloclen;
492
493   if (!path)
494     path = ".";
495
496 #ifdef WIN32
497   mode |= O_BINARY;
498 #endif
499
500   if (try_cwd_first || SLASH_P (string[0]))
501     {
502       int i;
503       filename = string;
504       fd = open (filename, mode, prot);
505       if (fd >= 0)
506         goto done;
507       for (i = 0; string[i]; i++)
508         if (SLASH_P (string[i]))
509           goto done;
510     }
511
512   /* ./foo => foo */
513   while (string[0] == '.' && SLASH_P (string[1]))
514     string += 2;
515
516   alloclen = strlen (path) + strlen (string) + 2;
517   filename = (char *) alloca (alloclen);
518   fd = -1;
519   for (p = path; p; p = p1 ? p1 + 1 : 0)
520     {
521       p1 = (char *) strchr (p, DIRNAME_SEPARATOR);
522       if (p1)
523         len = p1 - p;
524       else
525         len = strlen (p);
526
527       if (len == 4 && p[0] == '$' && p[1] == 'c'
528           && p[2] == 'w' && p[3] == 'd') {
529         /* Name is $cwd -- insert current directory name instead.  */
530         int newlen;
531
532         /* First, realloc the filename buffer if too short. */
533         len = strlen (current_directory);
534         newlen = len + strlen (string) + 2;
535         if (newlen > alloclen) {
536           alloclen = newlen;
537           filename = (char *) alloca (alloclen);
538         }
539         strcpy (filename, current_directory);
540       } else {
541         /* Normal file name in path -- just use it.  */
542         strncpy (filename, p, len);
543         filename[len] = 0;
544       }
545
546       /* Remove trailing slashes */
547       while (len > 0 && SLASH_P (filename[len-1]))
548         filename[--len] = 0;
549
550       strcat (filename+len, SLASH_STRING);
551       strcat (filename, string);
552
553       fd = open (filename, mode);
554       if (fd >= 0) break;
555     }
556
557  done:
558   if (filename_opened)
559     {
560       if (fd < 0)
561         *filename_opened = (char *) 0;
562       else if (ROOTED_P (filename))
563         *filename_opened = savestring (filename, strlen (filename));
564       else
565         {
566           /* Beware the // my son, the Emacs barfs, the botch that catch... */
567           
568           *filename_opened = concat (current_directory, 
569                                      SLASH_CHAR
570                                      == current_directory[strlen(current_directory)-1] 
571                                      ? "": SLASH_STRING,
572                                      filename, NULL);
573         }
574     }
575 #ifdef MPW
576   /* This is a debugging hack that can go away when all combinations
577      of Mac and Unix names are handled reasonably.  */
578   {
579     extern int debug_openp;
580
581     if (debug_openp)
582       {
583         printf("openp on %s, path %s mode %d prot %d\n  returned %d",
584                string, path, mode, prot, fd);
585         if (*filename_opened)
586           printf(" (filename is %s)", *filename_opened);
587         printf("\n");
588       }
589   }
590 #endif /* MPW */
591
592   return fd;
593 }
594
595 /* Open a source file given a symtab S.  Returns a file descriptor or
596    negative number for error.  */
597
598 static int
599 open_source_file (s)
600      struct symtab *s;
601 {
602   char *path = source_path;
603   char *p;
604   int result;
605   char *fullname;
606
607   /* Quick way out if we already know its full name */
608   if (s->fullname) 
609     {
610       result = open (s->fullname, O_RDONLY);
611       if (result >= 0)
612         return result;
613       /* Didn't work -- free old one, try again. */
614       mfree (s->objfile->md, s->fullname);
615       s->fullname = NULL;
616     }
617
618   if (s->dirname != NULL)
619     {
620       /* Replace a path entry of  $cdir  with the compilation directory name */
621 #define cdir_len        5
622       /* We cast strstr's result in case an ANSIhole has made it const,
623          which produces a "required warning" when assigned to a nonconst. */
624       p = (char *)strstr (source_path, "$cdir");
625       if (p && (p == path || p[-1] == DIRNAME_SEPARATOR)
626             && (p[cdir_len] == DIRNAME_SEPARATOR || p[cdir_len] == '\0'))
627         {
628           int len;
629
630           path = (char *)
631             alloca (strlen (source_path) + 1 + strlen (s->dirname) + 1);
632           len = p - source_path;
633           strncpy (path, source_path, len);             /* Before $cdir */
634           strcpy (path + len, s->dirname);              /* new stuff */
635           strcat (path + len, source_path + len + cdir_len); /* After $cdir */
636         }
637     }
638
639   result = openp (path, 0, s->filename, O_RDONLY, 0, &s->fullname);
640   if (result < 0)
641     {
642       /* Didn't work.  Try using just the basename. */
643       p = basename (s->filename);
644       if (p != s->filename)
645         result = openp (path, 0, p, O_RDONLY, 0, &s->fullname);
646     }
647 #ifdef MPW
648   if (result < 0)
649     {
650       /* Didn't work.  Try using just the MPW basename. */
651       p = (char *) mpw_basename (s->filename);
652       if (p != s->filename)
653         result = openp (path, 0, p, O_RDONLY, 0, &s->fullname);
654     }
655   if (result < 0)
656     {
657       /* Didn't work.  Try using the mixed Unix/MPW basename. */
658       p = (char *) mpw_mixed_basename (s->filename);
659       if (p != s->filename)
660         result = openp (path, 0, p, O_RDONLY, 0, &s->fullname);
661     }
662 #endif /* MPW */
663
664   if (result >= 0)
665     {
666       fullname = s->fullname;
667       s->fullname = mstrsave (s->objfile->md, s->fullname);
668       free (fullname);
669     }
670   return result;
671 }
672
673 /* Return the path to the source file associated with symtab.  Returns NULL
674    if no symtab.  */
675
676 char *
677 symtab_to_filename (s)
678      struct symtab *s;
679 {
680   int fd;
681
682   if (!s)
683     return NULL;
684
685   /* If we've seen the file before, just return fullname. */
686
687   if (s->fullname)
688     return s->fullname;
689
690   /* Try opening the file to setup fullname */
691
692   fd = open_source_file (s);
693   if (fd < 0)
694     return s->filename;         /* File not found.  Just use short name */
695
696   /* Found the file.  Cleanup and return the full name */
697
698   close (fd);
699   return s->fullname;
700 }
701
702 \f
703 /* Create and initialize the table S->line_charpos that records
704    the positions of the lines in the source file, which is assumed
705    to be open on descriptor DESC.
706    All set S->nlines to the number of such lines.  */
707
708 static void
709 find_source_lines (s, desc)
710      struct symtab *s;
711      int desc;
712 {
713   struct stat st;
714   register char *data, *p, *end;
715   int nlines = 0;
716   int lines_allocated = 1000;
717   int *line_charpos;
718   long mtime;
719   int size;
720
721   line_charpos = (int *) xmmalloc (s -> objfile -> md,
722                                    lines_allocated * sizeof (int));
723   if (fstat (desc, &st) < 0)
724     perror_with_name (s->filename);
725
726   if (s && s->objfile && s->objfile->obfd)
727     {
728       mtime = bfd_get_mtime(s->objfile->obfd);
729       if (mtime && mtime < st.st_mtime)
730         printf_filtered ("Source file is more recent than executable.\n");
731     }
732   else if (exec_bfd)
733     {
734       mtime = bfd_get_mtime(exec_bfd);
735       if (mtime && mtime < st.st_mtime)
736         printf_filtered ("Source file is more recent than executable.\n");
737     }
738
739 #ifdef LSEEK_NOT_LINEAR
740   {
741     char c;
742
743     /* Have to read it byte by byte to find out where the chars live */
744
745     line_charpos[0] = lseek (desc, 0, SEEK_CUR);
746     nlines = 1;
747     while (myread(desc, &c, 1)>0) 
748       {
749         if (c == '\n') 
750           {
751             if (nlines == lines_allocated) 
752               {
753                 lines_allocated *= 2;
754                 line_charpos =
755                   (int *) xmrealloc (s -> objfile -> md, (char *) line_charpos,
756                                      sizeof (int) * lines_allocated);
757               }
758             line_charpos[nlines++] = lseek (desc, 0, SEEK_CUR);
759           }
760       }
761   }
762 #else /* lseek linear.  */
763   {
764     struct cleanup *old_cleanups;
765
766     /* st_size might be a large type, but we only support source files whose 
767        size fits in an int.  */
768     size = (int) st.st_size;
769
770     /* Use malloc, not alloca, because this may be pretty large, and we may
771        run into various kinds of limits on stack size.  */
772     data = (char *) xmalloc (size);
773     old_cleanups = make_cleanup (free, data);
774
775     /* Reassign `size' to result of read for systems where \r\n -> \n.  */
776     size = myread (desc, data, size);
777     if (size < 0)
778       perror_with_name (s->filename);
779     end = data + size;
780     p = data;
781     line_charpos[0] = 0;
782     nlines = 1;
783     while (p != end)
784       {
785         if (*p++ == '\n'
786             /* A newline at the end does not start a new line.  */
787             && p != end)
788           {
789             if (nlines == lines_allocated)
790               {
791                 lines_allocated *= 2;
792                 line_charpos =
793                   (int *) xmrealloc (s -> objfile -> md, (char *) line_charpos,
794                                      sizeof (int) * lines_allocated);
795               }
796             line_charpos[nlines++] = p - data;
797           }
798       }
799     do_cleanups (old_cleanups);
800   }
801 #endif /* lseek linear.  */
802   s->nlines = nlines;
803   s->line_charpos =
804    (int *) xmrealloc (s -> objfile -> md, (char *) line_charpos,
805                       nlines * sizeof (int));
806
807 }
808
809 /* Return the character position of a line LINE in symtab S.
810    Return 0 if anything is invalid.  */
811
812 #if 0   /* Currently unused */
813
814 int
815 source_line_charpos (s, line)
816      struct symtab *s;
817      int line;
818 {
819   if (!s) return 0;
820   if (!s->line_charpos || line <= 0) return 0;
821   if (line > s->nlines)
822     line = s->nlines;
823   return s->line_charpos[line - 1];
824 }
825
826 /* Return the line number of character position POS in symtab S.  */
827
828 int
829 source_charpos_line (s, chr)
830     register struct symtab *s;
831     register int chr;
832 {
833   register int line = 0;
834   register int *lnp;
835     
836   if (s == 0 || s->line_charpos == 0) return 0;
837   lnp = s->line_charpos;
838   /* Files are usually short, so sequential search is Ok */
839   while (line < s->nlines  && *lnp <= chr)
840     {
841       line++;
842       lnp++;
843     }
844   if (line >= s->nlines)
845     line = s->nlines;
846   return line;
847 }
848
849 #endif  /* 0 */
850
851 \f
852 /* Get full pathname and line number positions for a symtab.
853    Return nonzero if line numbers may have changed.
854    Set *FULLNAME to actual name of the file as found by `openp',
855    or to 0 if the file is not found.  */
856
857 static int
858 get_filename_and_charpos (s, fullname)
859      struct symtab *s;
860      char **fullname;
861 {
862   register int desc, linenums_changed = 0;
863   
864   desc = open_source_file (s);
865   if (desc < 0)
866     {
867       if (fullname)
868         *fullname = NULL;
869       return 0;
870     }  
871   if (fullname)
872     *fullname = s->fullname;
873   if (s->line_charpos == 0) linenums_changed = 1;
874   if (linenums_changed) find_source_lines (s, desc);
875   close (desc);
876   return linenums_changed;
877 }
878
879 /* Print text describing the full name of the source file S
880    and the line number LINE and its corresponding character position.
881    The text starts with two Ctrl-z so that the Emacs-GDB interface
882    can easily find it.
883
884    MID_STATEMENT is nonzero if the PC is not at the beginning of that line.
885
886    Return 1 if successful, 0 if could not find the file.  */
887
888 int
889 identify_source_line (s, line, mid_statement, pc)
890      struct symtab *s;
891      int line;
892      int mid_statement;
893      CORE_ADDR pc;
894 {
895   if (s->line_charpos == 0)
896     get_filename_and_charpos (s, (char **)NULL);
897   if (s->fullname == 0)
898     return 0;
899   if (line > s->nlines)
900     /* Don't index off the end of the line_charpos array.  */
901     return 0;
902   annotate_source (s->fullname, line, s->line_charpos[line - 1],
903                    mid_statement, pc);
904
905   current_source_line = line;
906   first_line_listed = line;
907   last_line_listed = line;
908   current_source_symtab = s;
909   return 1;
910 }
911 \f
912 /* Print source lines from the file of symtab S,
913    starting with line number LINE and stopping before line number STOPLINE.  */
914
915 void
916 print_source_lines (s, line, stopline, noerror)
917      struct symtab *s;
918      int line, stopline;
919      int noerror;
920 {
921   register int c;
922   register int desc;
923   register FILE *stream;
924   int nlines = stopline - line;
925
926   /* Regardless of whether we can open the file, set current_source_symtab. */
927   current_source_symtab = s;
928   current_source_line = line;
929   first_line_listed = line;
930
931   desc = open_source_file (s);
932   if (desc < 0)
933     {
934       if (! noerror) {
935         char *name = alloca (strlen (s->filename) + 100);
936         sprintf (name, "%s:%d", s->filename, line);
937         print_sys_errmsg (name, errno);
938       }
939       return;
940     }
941
942   if (s->line_charpos == 0)
943     find_source_lines (s, desc);
944
945   if (line < 1 || line > s->nlines)
946     {
947       close (desc);
948       error ("Line number %d out of range; %s has %d lines.",
949              line, s->filename, s->nlines);
950     }
951
952   if (lseek (desc, s->line_charpos[line - 1], 0) < 0)
953     {
954       close (desc);
955       perror_with_name (s->filename);
956     }
957
958   stream = fdopen (desc, FOPEN_RT);
959   clearerr (stream);
960
961   while (nlines-- > 0)
962     {
963       c = fgetc (stream);
964       if (c == EOF) break;
965       last_line_listed = current_source_line;
966       printf_filtered ("%d\t", current_source_line++);
967       do
968         {
969           if (c < 040 && c != '\t' && c != '\n' && c != '\r')
970               printf_filtered ("^%c", c + 0100);
971           else if (c == 0177)
972             printf_filtered ("^?");
973           else
974             printf_filtered ("%c", c);
975         } while (c != '\n' && (c = fgetc (stream)) >= 0);
976     }
977
978   fclose (stream);
979 }
980 \f
981
982
983 /* Print a list of files and line numbers which a user may choose from
984   in order to list a function which was specified ambiguously (as with
985   `list classname::overloadedfuncname', for example).  The vector in
986   SALS provides the filenames and line numbers.  */
987
988 static void
989 ambiguous_line_spec (sals)
990      struct symtabs_and_lines *sals;
991 {
992   int i;
993
994   for (i = 0; i < sals->nelts; ++i)
995     printf_filtered("file: \"%s\", line number: %d\n",
996                     sals->sals[i].symtab->filename, sals->sals[i].line);
997 }
998
999 static void
1000 list_command (arg, from_tty)
1001      char *arg;
1002      int from_tty;
1003 {
1004   struct symtabs_and_lines sals, sals_end;
1005   struct symtab_and_line sal, sal_end;
1006   struct symbol *sym;
1007   char *arg1;
1008   int no_end = 1;
1009   int dummy_end = 0;
1010   int dummy_beg = 0;
1011   int linenum_beg = 0;
1012   char *p;
1013
1014   if (!have_full_symbols () && !have_partial_symbols())
1015     error ("No symbol table is loaded.  Use the \"file\" command.");
1016
1017   /* Pull in a current source symtab if necessary */
1018   if (current_source_symtab == 0 &&
1019       (arg == 0 || arg[0] == '+' || arg[0] == '-'))
1020     select_source_symtab (0);
1021
1022   /* "l" or "l +" lists next ten lines.  */
1023
1024   if (arg == 0 || STREQ (arg, "+"))
1025     {
1026       if (current_source_symtab == 0)
1027         error ("No default source file yet.  Do \"help list\".");
1028       print_source_lines (current_source_symtab, current_source_line,
1029                           current_source_line + lines_to_list, 0);
1030       return;
1031     }
1032
1033   /* "l -" lists previous ten lines, the ones before the ten just listed.  */
1034   if (STREQ (arg, "-"))
1035     {
1036       if (current_source_symtab == 0)
1037         error ("No default source file yet.  Do \"help list\".");
1038       print_source_lines (current_source_symtab,
1039                           max (first_line_listed - lines_to_list, 1),
1040                           first_line_listed, 0);
1041       return;
1042     }
1043
1044   /* Now if there is only one argument, decode it in SAL
1045      and set NO_END.
1046      If there are two arguments, decode them in SAL and SAL_END
1047      and clear NO_END; however, if one of the arguments is blank,
1048      set DUMMY_BEG or DUMMY_END to record that fact.  */
1049
1050   arg1 = arg;
1051   if (*arg1 == ',')
1052     dummy_beg = 1;
1053   else
1054     {
1055       sals = decode_line_1 (&arg1, 0, 0, 0, 0);
1056
1057       if (! sals.nelts) return;  /*  C++  */
1058       if (sals.nelts > 1)
1059         {
1060           ambiguous_line_spec (&sals);
1061           free (sals.sals);
1062           return;
1063         }
1064
1065       sal = sals.sals[0];
1066       free (sals.sals);
1067     }
1068
1069   /* Record whether the BEG arg is all digits.  */
1070
1071   for (p = arg; p != arg1 && *p >= '0' && *p <= '9'; p++);
1072   linenum_beg = (p == arg1);
1073
1074   while (*arg1 == ' ' || *arg1 == '\t')
1075     arg1++;
1076   if (*arg1 == ',')
1077     {
1078       no_end = 0;
1079       arg1++;
1080       while (*arg1 == ' ' || *arg1 == '\t')
1081         arg1++;
1082       if (*arg1 == 0)
1083         dummy_end = 1;
1084       else
1085         {
1086           if (dummy_beg)
1087             sals_end = decode_line_1 (&arg1, 0, 0, 0, 0);
1088           else
1089             sals_end = decode_line_1 (&arg1, 0, sal.symtab, sal.line, 0);
1090           if (sals_end.nelts == 0) 
1091             return;
1092           if (sals_end.nelts > 1)
1093             {
1094               ambiguous_line_spec (&sals_end);
1095               free (sals_end.sals);
1096               return;
1097             }
1098           sal_end = sals_end.sals[0];
1099           free (sals_end.sals);
1100         }
1101     }
1102
1103   if (*arg1)
1104     error ("Junk at end of line specification.");
1105
1106   if (!no_end && !dummy_beg && !dummy_end
1107       && sal.symtab != sal_end.symtab)
1108     error ("Specified start and end are in different files.");
1109   if (dummy_beg && dummy_end)
1110     error ("Two empty args do not say what lines to list.");
1111  
1112   /* if line was specified by address,
1113      first print exactly which line, and which file.
1114      In this case, sal.symtab == 0 means address is outside
1115      of all known source files, not that user failed to give a filename.  */
1116   if (*arg == '*')
1117     {
1118       if (sal.symtab == 0)
1119         /* FIXME-32x64--assumes sal.pc fits in long.  */
1120         error ("No source file for address %s.",
1121                 local_hex_string((unsigned long) sal.pc));
1122       sym = find_pc_function (sal.pc);
1123       if (sym)
1124         {
1125           print_address_numeric (sal.pc, 1, gdb_stdout);
1126           printf_filtered (" is in ");
1127           fputs_filtered (SYMBOL_SOURCE_NAME (sym), gdb_stdout);
1128           printf_filtered (" (%s:%d).\n", sal.symtab->filename, sal.line);
1129         }
1130       else
1131         {
1132           print_address_numeric (sal.pc, 1, gdb_stdout);
1133           printf_filtered (" is at %s:%d.\n",
1134                            sal.symtab->filename, sal.line);
1135         }
1136     }
1137
1138   /* If line was not specified by just a line number,
1139      and it does not imply a symtab, it must be an undebuggable symbol
1140      which means no source code.  */
1141
1142   if (! linenum_beg && sal.symtab == 0)
1143     error ("No line number known for %s.", arg);
1144
1145   /* If this command is repeated with RET,
1146      turn it into the no-arg variant.  */
1147
1148   if (from_tty)
1149     *arg = 0;
1150
1151   if (dummy_beg && sal_end.symtab == 0)
1152     error ("No default source file yet.  Do \"help list\".");
1153   if (dummy_beg)
1154     print_source_lines (sal_end.symtab,
1155                         max (sal_end.line - (lines_to_list - 1), 1),
1156                         sal_end.line + 1, 0);
1157   else if (sal.symtab == 0)
1158     error ("No default source file yet.  Do \"help list\".");
1159   else if (no_end)
1160     print_source_lines (sal.symtab,
1161                         max (sal.line - (lines_to_list / 2), 1),
1162                         sal.line + (lines_to_list / 2), 0);
1163   else
1164     print_source_lines (sal.symtab, sal.line,
1165                         (dummy_end
1166                          ? sal.line + lines_to_list
1167                          : sal_end.line + 1),
1168                         0);
1169 }
1170 \f
1171 /* Print info on range of pc's in a specified line.  */
1172
1173 static void
1174 line_info (arg, from_tty)
1175      char *arg;
1176      int from_tty;
1177 {
1178   struct symtabs_and_lines sals;
1179   struct symtab_and_line sal;
1180   CORE_ADDR start_pc, end_pc;
1181   int i;
1182
1183   INIT_SAL (&sal);      /* initialize to zeroes */
1184
1185   if (arg == 0)
1186     {
1187       sal.symtab = current_source_symtab;
1188       sal.line = last_line_listed;
1189       sals.nelts = 1;
1190       sals.sals = (struct symtab_and_line *)
1191         xmalloc (sizeof (struct symtab_and_line));
1192       sals.sals[0] = sal;
1193     }
1194   else
1195     {
1196       sals = decode_line_spec_1 (arg, 0);
1197       
1198       dont_repeat ();
1199     }
1200
1201   /* C++  More than one line may have been specified, as when the user
1202      specifies an overloaded function name. Print info on them all. */
1203   for (i = 0; i < sals.nelts; i++)
1204     {
1205       sal = sals.sals[i];
1206       
1207       if (sal.symtab == 0)
1208         {
1209           printf_filtered ("No line number information available");
1210           if (sal.pc != 0)
1211             {
1212               /* This is useful for "info line *0x7f34".  If we can't tell the
1213                  user about a source line, at least let them have the symbolic
1214                  address.  */
1215               printf_filtered (" for address ");
1216               wrap_here ("  ");
1217               print_address (sal.pc, gdb_stdout);
1218             }
1219           else
1220             printf_filtered (".");
1221           printf_filtered ("\n");
1222         }
1223       else if (sal.line > 0
1224                && find_line_pc_range (sal, &start_pc, &end_pc))
1225         {
1226           if (start_pc == end_pc)
1227             {
1228               printf_filtered ("Line %d of \"%s\"",
1229                                sal.line, sal.symtab->filename);
1230               wrap_here ("  ");
1231               printf_filtered (" is at address ");
1232               print_address (start_pc, gdb_stdout);
1233               wrap_here ("  ");
1234               printf_filtered (" but contains no code.\n");
1235             }
1236           else
1237             {
1238               printf_filtered ("Line %d of \"%s\"",
1239                                sal.line, sal.symtab->filename);
1240               wrap_here ("  ");
1241               printf_filtered (" starts at address ");
1242               print_address (start_pc, gdb_stdout);
1243               wrap_here ("  ");
1244               printf_filtered (" and ends at ");
1245               print_address (end_pc, gdb_stdout);
1246               printf_filtered (".\n");
1247             }
1248
1249           /* x/i should display this line's code.  */
1250           set_next_address (start_pc);
1251
1252           /* Repeating "info line" should do the following line.  */
1253           last_line_listed = sal.line + 1;
1254
1255           /* If this is the only line, show the source code.  If it could
1256              not find the file, don't do anything special.  */
1257           if (annotation_level && sals.nelts == 1)
1258             identify_source_line (sal.symtab, sal.line, 0, start_pc);
1259         }
1260       else
1261         /* Is there any case in which we get here, and have an address
1262            which the user would want to see?  If we have debugging symbols
1263            and no line numbers?  */
1264         printf_filtered ("Line number %d is out of range for \"%s\".\n",
1265                          sal.line, sal.symtab->filename);
1266     }
1267   free (sals.sals);
1268 }
1269 \f
1270 /* Commands to search the source file for a regexp.  */
1271
1272 /* ARGSUSED */
1273 static void
1274 forward_search_command (regex, from_tty)
1275      char *regex;
1276      int from_tty;
1277 {
1278   register int c;
1279   register int desc;
1280   register FILE *stream;
1281   int line = last_line_listed + 1;
1282   char *msg;
1283
1284   msg = (char *) re_comp (regex);
1285   if (msg)
1286     error (msg);
1287
1288   if (current_source_symtab == 0)
1289     select_source_symtab (0);
1290
1291   /* Search from last_line_listed+1 in current_source_symtab */
1292
1293   desc = open_source_file (current_source_symtab);
1294   if (desc < 0)
1295     perror_with_name (current_source_symtab->filename);
1296
1297   if (current_source_symtab->line_charpos == 0)
1298     find_source_lines (current_source_symtab, desc);
1299
1300   if (line < 1 || line > current_source_symtab->nlines)
1301     {
1302       close (desc);
1303       error ("Expression not found");
1304     }
1305
1306   if (lseek (desc, current_source_symtab->line_charpos[line - 1], 0) < 0)
1307     {
1308       close (desc);
1309       perror_with_name (current_source_symtab->filename);
1310     }
1311
1312   stream = fdopen (desc, FOPEN_RT);
1313   clearerr (stream);
1314   while (1) {
1315     static char *buf = NULL;
1316     register char *p;
1317     int cursize, newsize;
1318
1319     cursize = 256;
1320     buf = xmalloc (cursize);
1321     p = buf;
1322
1323     c = getc (stream);
1324     if (c == EOF)
1325       break;
1326     do {
1327       *p++ = c;
1328       if (p - buf == cursize)
1329         {
1330           newsize = cursize + cursize / 2;
1331           buf = xrealloc (buf, newsize);
1332           p = buf + cursize;
1333           cursize = newsize;
1334         }
1335     } while (c != '\n' && (c = getc (stream)) >= 0);
1336
1337     /* we now have a source line in buf, null terminate and match */
1338     *p = 0;
1339     if (re_exec (buf) > 0)
1340       {
1341         /* Match! */
1342         fclose (stream);
1343         print_source_lines (current_source_symtab, line, line+1, 0);
1344         set_internalvar (lookup_internalvar ("_"),
1345                          value_from_longest (builtin_type_int,
1346                                              (LONGEST) line));
1347         current_source_line = max (line - lines_to_list / 2, 1);
1348         return;
1349       }
1350     line++;
1351   }
1352
1353   printf_filtered ("Expression not found\n");
1354   fclose (stream);
1355 }
1356
1357 /* ARGSUSED */
1358 static void
1359 reverse_search_command (regex, from_tty)
1360      char *regex;
1361      int from_tty;
1362 {
1363   register int c;
1364   register int desc;
1365   register FILE *stream;
1366   int line = last_line_listed - 1;
1367   char *msg;
1368
1369   msg = (char *) re_comp (regex);
1370   if (msg)
1371     error (msg);
1372
1373   if (current_source_symtab == 0)
1374     select_source_symtab (0);
1375
1376   /* Search from last_line_listed-1 in current_source_symtab */
1377
1378   desc = open_source_file (current_source_symtab);
1379   if (desc < 0)
1380     perror_with_name (current_source_symtab->filename);
1381
1382   if (current_source_symtab->line_charpos == 0)
1383     find_source_lines (current_source_symtab, desc);
1384
1385   if (line < 1 || line > current_source_symtab->nlines)
1386     {
1387       close (desc);
1388       error ("Expression not found");
1389     }
1390
1391   if (lseek (desc, current_source_symtab->line_charpos[line - 1], 0) < 0)
1392     {
1393       close (desc);
1394       perror_with_name (current_source_symtab->filename);
1395     }
1396
1397   stream = fdopen (desc, FOPEN_RT);
1398   clearerr (stream);
1399   while (line > 1)
1400     {
1401 /* FIXME!!!  We walk right off the end of buf if we get a long line!!! */
1402       char buf[4096];           /* Should be reasonable??? */
1403       register char *p = buf;
1404
1405       c = getc (stream);
1406       if (c == EOF)
1407         break;
1408       do {
1409         *p++ = c;
1410       } while (c != '\n' && (c = getc (stream)) >= 0);
1411
1412       /* We now have a source line in buf; null terminate and match.  */
1413       *p = 0;
1414       if (re_exec (buf) > 0)
1415         {
1416           /* Match! */
1417           fclose (stream);
1418           print_source_lines (current_source_symtab,
1419                               line, line+1, 0);
1420           set_internalvar (lookup_internalvar ("_"),
1421                            value_from_longest (builtin_type_int,
1422                                                (LONGEST) line));
1423           current_source_line = max (line - lines_to_list / 2, 1);
1424           return;
1425         }
1426       line--;
1427       if (fseek (stream, current_source_symtab->line_charpos[line - 1], 0) < 0)
1428         {
1429           fclose (stream);
1430           perror_with_name (current_source_symtab->filename);
1431         }
1432     }
1433
1434   printf_filtered ("Expression not found\n");
1435   fclose (stream);
1436   return;
1437 }
1438 \f
1439 void
1440 _initialize_source ()
1441 {
1442   struct cmd_list_element *c;
1443   current_source_symtab = 0;
1444   init_source_path ();
1445
1446   /* The intention is to use POSIX Basic Regular Expressions.
1447      Always use the GNU regex routine for consistency across all hosts.
1448      Our current GNU regex.c does not have all the POSIX features, so this is
1449      just an approximation.  */
1450   re_set_syntax (RE_SYNTAX_GREP);
1451
1452   c = add_cmd ("directory", class_files, directory_command,
1453            "Add directory DIR to beginning of search path for source files.\n\
1454 Forget cached info on source file locations and line positions.\n\
1455 DIR can also be $cwd for the current working directory, or $cdir for the\n\
1456 directory in which the source file was compiled into object code.\n\
1457 With no argument, reset the search path to $cdir:$cwd, the default.",
1458                &cmdlist);
1459   c->completer = filename_completer;
1460
1461   add_cmd ("directories", no_class, show_directories,
1462            "Current search path for finding source files.\n\
1463 $cwd in the path means the current working directory.\n\
1464 $cdir in the path means the compilation directory of the source file.",
1465            &showlist);
1466
1467   add_info ("source", source_info,
1468             "Information about the current source file.");
1469
1470   add_info ("line", line_info,
1471             concat ("Core addresses of the code for a source line.\n\
1472 Line can be specified as\n\
1473   LINENUM, to list around that line in current file,\n\
1474   FILE:LINENUM, to list around that line in that file,\n\
1475   FUNCTION, to list around beginning of that function,\n\
1476   FILE:FUNCTION, to distinguish among like-named static functions.\n\
1477 ", "\
1478 Default is to describe the last source line that was listed.\n\n\
1479 This sets the default address for \"x\" to the line's first instruction\n\
1480 so that \"x/i\" suffices to start examining the machine code.\n\
1481 The address is also stored as the value of \"$_\".", NULL));
1482
1483   add_com ("forward-search", class_files, forward_search_command,
1484            "Search for regular expression (see regex(3)) from last line listed.\n\
1485 The matching line number is also stored as the value of \"$_\".");
1486   add_com_alias ("search", "forward-search", class_files, 0);
1487
1488   add_com ("reverse-search", class_files, reverse_search_command,
1489            "Search backward for regular expression (see regex(3)) from last line listed.\n\
1490 The matching line number is also stored as the value of \"$_\".");
1491
1492   add_com ("list", class_files, list_command,
1493            concat ("List specified function or line.\n\
1494 With no argument, lists ten more lines after or around previous listing.\n\
1495 \"list -\" lists the ten lines before a previous ten-line listing.\n\
1496 One argument specifies a line, and ten lines are listed around that line.\n\
1497 Two arguments with comma between specify starting and ending lines to list.\n\
1498 ", "\
1499 Lines can be specified in these ways:\n\
1500   LINENUM, to list around that line in current file,\n\
1501   FILE:LINENUM, to list around that line in that file,\n\
1502   FUNCTION, to list around beginning of that function,\n\
1503   FILE:FUNCTION, to distinguish among like-named static functions.\n\
1504   *ADDRESS, to list around the line containing that address.\n\
1505 With two args if one is empty it stands for ten lines away from the other arg.", NULL));
1506
1507   add_com_alias ("l", "list", class_files, 1);
1508
1509   add_show_from_set
1510     (add_set_cmd ("listsize", class_support, var_uinteger,
1511                   (char *)&lines_to_list,
1512         "Set number of source lines gdb will list by default.",
1513                   &setlist),
1514      &showlist);
1515 }