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