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