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