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