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