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