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