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