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