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