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