]> git.ipfire.org Git - thirdparty/binutils-gdb.git/blame_incremental - gdb/exec.c
Automatic date update in version.in
[thirdparty/binutils-gdb.git] / gdb / exec.c
... / ...
CommitLineData
1/* Work with executable files, for GDB.
2
3 Copyright (C) 1988-2025 Free Software Foundation, Inc.
4
5 This file is part of GDB.
6
7 This program is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 3 of the License, or
10 (at your option) any later version.
11
12 This program is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with this program. If not, see <http://www.gnu.org/licenses/>. */
19
20#include "frame.h"
21#include "inferior.h"
22#include "target.h"
23#include "cli/cli-cmds.h"
24#include "language.h"
25#include "filenames.h"
26#include "symfile.h"
27#include "objfiles.h"
28#include "completer.h"
29#include "value.h"
30#include "exec.h"
31#include "observable.h"
32#include "arch-utils.h"
33#include "gdbthread.h"
34#include "progspace.h"
35#include "progspace-and-thread.h"
36#include "gdb_bfd.h"
37#include "gcore.h"
38#include "source.h"
39#include "build-id.h"
40
41#include <fcntl.h>
42#include "readline/tilde.h"
43#include "gdbcore.h"
44
45#include <ctype.h>
46#include <sys/stat.h>
47#include "solib.h"
48#include <algorithm>
49#include "gdbsupport/pathstuff.h"
50#include "cli/cli-style.h"
51#include "gdbsupport/buildargv.h"
52
53void (*deprecated_file_changed_hook) (const char *);
54
55static const target_info exec_target_info = {
56 "exec",
57 N_("Local exec file"),
58 N_("Use an executable file as a target.\n\
59Specify the filename of the executable file.")
60};
61
62/* The target vector for executable files. */
63
64struct exec_target final : public target_ops
65{
66 const target_info &info () const override
67 { return exec_target_info; }
68
69 strata stratum () const override { return file_stratum; }
70
71 void close () override;
72 enum target_xfer_status xfer_partial (enum target_object object,
73 const char *annex,
74 gdb_byte *readbuf,
75 const gdb_byte *writebuf,
76 ULONGEST offset, ULONGEST len,
77 ULONGEST *xfered_len) override;
78 void files_info () override;
79
80 bool has_memory () override;
81 gdb::unique_xmalloc_ptr<char> make_corefile_notes (bfd *, int *) override;
82 int find_memory_regions (find_memory_region_ftype func, void *data) override;
83};
84
85static exec_target exec_ops;
86
87/* How to handle a mismatch between the current exec file and the exec
88 file determined from target. */
89
90static const char *const exec_file_mismatch_names[]
91 = {"ask", "warn", "off", NULL };
92enum exec_file_mismatch_mode
93 {
94 exec_file_mismatch_ask, exec_file_mismatch_warn, exec_file_mismatch_off
95 };
96static const char *exec_file_mismatch = exec_file_mismatch_names[0];
97static enum exec_file_mismatch_mode exec_file_mismatch_mode
98 = exec_file_mismatch_ask;
99
100/* Show command. */
101static void
102show_exec_file_mismatch_command (struct ui_file *file, int from_tty,
103 struct cmd_list_element *c, const char *value)
104{
105 gdb_printf (file,
106 _("exec-file-mismatch handling is currently \"%s\".\n"),
107 exec_file_mismatch_names[exec_file_mismatch_mode]);
108}
109
110/* Set command. Change the setting for range checking. */
111static void
112set_exec_file_mismatch_command (const char *ignore,
113 int from_tty, struct cmd_list_element *c)
114{
115 for (enum exec_file_mismatch_mode mode = exec_file_mismatch_ask;
116 ;
117 mode = static_cast<enum exec_file_mismatch_mode>(1 + (int) mode))
118 {
119 if (strcmp (exec_file_mismatch, exec_file_mismatch_names[mode]) == 0)
120 {
121 exec_file_mismatch_mode = mode;
122 return;
123 }
124 if (mode == exec_file_mismatch_off)
125 internal_error (_("Unrecognized exec-file-mismatch setting: \"%s\""),
126 exec_file_mismatch);
127 }
128}
129
130/* Whether to open exec and core files read-only or read-write. */
131
132bool write_files = false;
133static void
134show_write_files (struct ui_file *file, int from_tty,
135 struct cmd_list_element *c, const char *value)
136{
137 gdb_printf (file, _("Writing into executable and core files is %s.\n"),
138 value);
139}
140
141
142static void
143exec_target_open (const char *args, int from_tty)
144{
145 target_preopen (from_tty);
146
147 std::string filename = extract_single_filename_arg (args);
148 exec_file_attach (filename.empty () ? nullptr : filename.c_str (),
149 from_tty);
150}
151
152/* This is the target_close implementation. Clears all target
153 sections and closes all executable bfds from all program spaces. */
154
155void
156exec_target::close ()
157{
158 for (struct program_space *ss : program_spaces)
159 {
160 ss->clear_target_sections ();
161 ss->exec_close ();
162 }
163}
164
165/* See gdbcore.h. */
166
167void
168try_open_exec_file (const char *exec_file_host, struct inferior *inf,
169 symfile_add_flags add_flags)
170{
171 struct gdb_exception prev_err;
172
173 /* exec_file_attach and symbol_file_add_main may throw an error if the file
174 cannot be opened either locally or remotely.
175
176 This happens for example, when the file is first found in the local
177 sysroot (above), and then disappears (a TOCTOU race), or when it doesn't
178 exist in the target filesystem, or when the file does exist, but
179 is not readable.
180
181 Even without a symbol file, the remote-based debugging session should
182 continue normally instead of ending abruptly. Hence we catch thrown
183 errors/exceptions in the following code. */
184 try
185 {
186 /* We must do this step even if exec_file_host is NULL, so that
187 exec_file_attach will clear state. */
188 exec_file_attach (exec_file_host, add_flags & SYMFILE_VERBOSE);
189 }
190 catch (gdb_exception_error &err)
191 {
192 if (err.message != NULL)
193 warning ("%s", err.what ());
194
195 prev_err = std::move (err);
196 }
197
198 if (exec_file_host != NULL)
199 {
200 try
201 {
202 symbol_file_add_main (exec_file_host, add_flags);
203 }
204 catch (const gdb_exception_error &err)
205 {
206 if (prev_err != err)
207 warning ("%s", err.what ());
208 }
209 }
210}
211
212/* See gdbcore.h. */
213
214void
215validate_exec_file (int from_tty)
216{
217 /* If user asked to ignore the mismatch, do nothing. */
218 if (exec_file_mismatch_mode == exec_file_mismatch_off)
219 return;
220
221 /* If there's no current executable, then there's nothing to
222 validate against, so we're done. */
223 const char *current_exec_file = current_program_space->exec_filename ();
224 if (current_exec_file == nullptr)
225 return;
226
227 /* Try to determine a filename from the process itself. If we
228 cannot get an executable from the process, then no validation is
229 possible. */
230 const char *pid_exec_file
231 = target_pid_to_exec_file (current_inferior ()->pid);
232 if (pid_exec_file == nullptr)
233 return;
234
235 /* In case current_exec_file was changed, reopen_exec_file ensures an up
236 to date build_id (will do nothing if the file timestamp did not
237 change). If exec file changed, reopen_exec_file has allocated another
238 file name, so get_exec_file again. */
239 reopen_exec_file ();
240 current_exec_file = current_program_space->exec_filename ();
241
242 /* Try validating via build-id, if available. This is the most reliable
243 check. */
244 const bfd_build_id *exec_file_build_id
245 = build_id_bfd_get (current_program_space->exec_bfd ());
246 bool build_id_mismatch = false;
247 if (exec_file_build_id != nullptr)
248 {
249 /* Prepend the target prefix, to force gdb_bfd_open to open the
250 file on the remote file system (if indeed remote). */
251 std::string target_pid_exec_file
252 = std::string (TARGET_SYSROOT_PREFIX) + pid_exec_file;
253
254 gdb_bfd_ref_ptr abfd (gdb_bfd_open (target_pid_exec_file.c_str (),
255 gnutarget, -1, false));
256 if (abfd != nullptr)
257 {
258 const bfd_build_id *target_exec_file_build_id
259 = build_id_bfd_get (abfd.get ());
260
261 if (target_exec_file_build_id != nullptr)
262 {
263 if (build_id_equal (exec_file_build_id,
264 target_exec_file_build_id))
265 {
266 /* Match. */
267 return;
268 }
269 else
270 build_id_mismatch = true;
271 }
272 }
273 }
274
275 if (build_id_mismatch)
276 {
277 std::string exec_file_target (pid_exec_file);
278
279 /* In case the exec file is not local, exec_file_target has to point at
280 the target file system. */
281 if (is_target_filename (current_exec_file) && !target_filesystem_is_local ())
282 exec_file_target = TARGET_SYSROOT_PREFIX + exec_file_target;
283
284 warning
285 (_("Build ID mismatch between current exec-file %ps\n"
286 "and automatically determined exec-file %ps\n"
287 "exec-file-mismatch handling is currently \"%s\""),
288 styled_string (file_name_style.style (), current_exec_file),
289 styled_string (file_name_style.style (), exec_file_target.c_str ()),
290 exec_file_mismatch_names[exec_file_mismatch_mode]);
291 if (exec_file_mismatch_mode == exec_file_mismatch_ask)
292 {
293 symfile_add_flags add_flags = SYMFILE_MAINLINE;
294 if (from_tty)
295 {
296 add_flags |= SYMFILE_VERBOSE;
297 add_flags |= SYMFILE_ALWAYS_CONFIRM;
298 }
299 try
300 {
301 symbol_file_add_main (exec_file_target.c_str (), add_flags);
302 exec_file_attach (exec_file_target.c_str (), from_tty);
303 }
304 catch (const gdb_exception_error &err)
305 {
306 warning (_("loading %ps %s"),
307 styled_string (file_name_style.style (),
308 exec_file_target.c_str ()),
309 err.message != NULL ? err.what () : "error");
310 }
311 }
312 }
313}
314
315/* See gdbcore.h. */
316
317void
318exec_file_locate_attach (int pid, int defer_bp_reset, int from_tty)
319{
320 const char *exec_file_target;
321 symfile_add_flags add_flags = 0;
322
323 /* Do nothing if we already have an executable filename. */
324 if (current_program_space->exec_filename () != nullptr)
325 return;
326
327 /* Try to determine a filename from the process itself. */
328 exec_file_target = target_pid_to_exec_file (pid);
329 if (exec_file_target == NULL)
330 {
331 warning (_("No executable has been specified and target does not "
332 "support\n"
333 "determining executable automatically. "
334 "Try using the \"%ps\" command."),
335 styled_string (command_style.style (), "file"));
336 return;
337 }
338
339 gdb::unique_xmalloc_ptr<char> exec_file_host
340 = exec_file_find (exec_file_target, NULL);
341 if (exec_file_host == nullptr)
342 {
343 warning (_("No executable has been specified, and target executable "
344 "%ps could not be found. Try using the \"%ps\" command."),
345 styled_string (file_name_style.style (), exec_file_target),
346 styled_string (command_style.style (), "file"));
347 return;
348 }
349
350 if (defer_bp_reset)
351 add_flags |= SYMFILE_DEFER_BP_RESET;
352
353 if (from_tty)
354 add_flags |= SYMFILE_VERBOSE;
355
356 /* Attempt to open the exec file. */
357 try_open_exec_file (exec_file_host.get (), current_inferior (), add_flags);
358}
359
360/* Set FILENAME as the new exec file.
361
362 This function is intended to be behave essentially the same
363 as exec_file_command, except that the latter will detect when
364 a target is being debugged, and will ask the user whether it
365 should be shut down first. (If the answer is "no", then the
366 new file is ignored.)
367
368 This file is used by exec_file_command, to do the work of opening
369 and processing the exec file after any prompting has happened.
370
371 And, it is used by child_attach, when the attach command was
372 given a pid but not a exec pathname, and the attach command could
373 figure out the pathname from the pid. (In this case, we shouldn't
374 ask the user whether the current target should be shut down --
375 we're supplying the exec pathname late for good reason.) */
376
377void
378exec_file_attach (const char *filename, int from_tty)
379{
380 /* First, acquire a reference to the exec_bfd. We release
381 this at the end of the function; but acquiring it now lets the
382 BFD cache return it if this call refers to the same file. */
383 gdb_bfd_ref_ptr exec_bfd_holder
384 = gdb_bfd_ref_ptr::new_reference (current_program_space->exec_bfd ());
385
386 /* Remove any previous exec file. */
387 current_program_space->exec_close ();
388
389 /* Now open and digest the file the user requested, if any. */
390
391 if (!filename)
392 {
393 if (from_tty)
394 gdb_printf (_("No executable file now.\n"));
395
396 set_gdbarch_from_file (NULL);
397 }
398 else
399 {
400 int load_via_target = 0;
401 const char *scratch_pathname, *canonical_pathname;
402 int scratch_chan;
403 char **matching;
404
405 if (is_target_filename (filename))
406 {
407 if (target_filesystem_is_local ())
408 filename += strlen (TARGET_SYSROOT_PREFIX);
409 else
410 load_via_target = 1;
411 }
412
413 gdb::unique_xmalloc_ptr<char> canonical_storage, scratch_storage;
414 if (load_via_target)
415 {
416 /* gdb_bfd_fopen does not support "target:" filenames. */
417 if (write_files)
418 warning (_("writing into executable files is "
419 "not supported for %s sysroots"),
420 TARGET_SYSROOT_PREFIX);
421
422 scratch_pathname = filename;
423 scratch_chan = -1;
424 canonical_pathname = scratch_pathname;
425 }
426 else
427 {
428 scratch_chan = openp (getenv ("PATH"), OPF_TRY_CWD_FIRST,
429 filename, write_files ?
430 O_RDWR | O_BINARY : O_RDONLY | O_BINARY,
431 &scratch_storage);
432#if defined(__GO32__) || defined(_WIN32) || defined(__CYGWIN__)
433 if (scratch_chan < 0)
434 {
435 int first_errno = errno;
436 char *exename = (char *) alloca (strlen (filename) + 5);
437
438 strcat (strcpy (exename, filename), ".exe");
439 scratch_chan = openp (getenv ("PATH"), OPF_TRY_CWD_FIRST,
440 exename, write_files ?
441 O_RDWR | O_BINARY
442 : O_RDONLY | O_BINARY,
443 &scratch_storage);
444 if (scratch_chan < 0)
445 errno = first_errno;
446 }
447#endif
448 if (scratch_chan < 0)
449 perror_with_name (filename);
450
451 scratch_pathname = scratch_storage.get ();
452
453 /* gdb_bfd_open (and its variants) prefers canonicalized
454 pathname for better BFD caching. */
455 canonical_storage = gdb_realpath (scratch_pathname);
456 canonical_pathname = canonical_storage.get ();
457 }
458
459 gdb_bfd_ref_ptr temp;
460 if (write_files && !load_via_target)
461 temp = gdb_bfd_fopen (canonical_pathname, gnutarget,
462 FOPEN_RUB, scratch_chan);
463 else
464 temp = gdb_bfd_open (canonical_pathname, gnutarget, scratch_chan);
465 current_program_space->set_exec_bfd (std::move (temp));
466
467 if (!current_program_space->exec_bfd ())
468 {
469 error (_("\"%s\": could not open as an executable file: %s."),
470 scratch_pathname, bfd_errmsg (bfd_get_error ()));
471 }
472
473 /* gdb_realpath_keepfile resolves symlinks on the local
474 filesystem and so cannot be used for "target:" files. */
475 gdb_assert (current_program_space->exec_filename () == nullptr);
476 if (load_via_target)
477 current_program_space->set_exec_filename
478 (make_unique_xstrdup
479 (bfd_get_filename (current_program_space->exec_bfd ())));
480 else
481 current_program_space->set_exec_filename
482 (make_unique_xstrdup (gdb_realpath_keepfile
483 (scratch_pathname).c_str ()));
484
485 if (!bfd_check_format_matches (current_program_space->exec_bfd (),
486 bfd_object, &matching))
487 {
488 /* Make sure to close exec_bfd, or else "run" might try to use
489 it. */
490 current_program_space->exec_close ();
491 error (_("\"%s\": not in executable format: %s"), scratch_pathname,
492 gdb_bfd_errmsg (bfd_get_error (), matching).c_str ());
493 }
494
495 std::vector<target_section> sections
496 = build_section_table (current_program_space->exec_bfd ());
497
498 current_program_space->ebfd_mtime
499 = gdb_bfd_get_mtime (current_program_space->exec_bfd ());
500
501 validate_files ();
502
503 set_gdbarch_from_file (current_program_space->exec_bfd ());
504
505 /* Add the executable's sections to the current address spaces'
506 list of sections. This possibly pushes the exec_ops
507 target. */
508 current_program_space->add_target_sections
509 (current_program_space->ebfd.get (), sections);
510 }
511
512 /* Are are loading the same executable? */
513 bfd *prev_bfd = exec_bfd_holder.get ();
514 bfd *curr_bfd = current_program_space->exec_bfd ();
515 bool reload_p = (((prev_bfd != nullptr) == (curr_bfd != nullptr))
516 && (prev_bfd == nullptr
517 || (strcmp (bfd_get_filename (prev_bfd),
518 bfd_get_filename (curr_bfd)) == 0)));
519
520 gdb::observers::executable_changed.notify (current_program_space, reload_p);
521}
522
523/* See exec.h. */
524
525void
526no_executable_specified_error ()
527{
528 error (_("No executable file specified.\n\
529Use the \"file\" or \"exec-file\" command."));
530}
531
532/* Process the first arg in ARGS as the new exec file.
533
534 Note that we have to explicitly ignore additional args, since we can
535 be called from file_command(), which also calls symbol_file_command()
536 which can take multiple args.
537
538 If ARGS is NULL, we just want to close the exec file. */
539
540static void
541exec_file_command (const char *args, int from_tty)
542{
543 if (from_tty && target_has_execution ()
544 && !query (_("A program is being debugged already.\n"
545 "Are you sure you want to change the file? ")))
546 error (_("File not changed."));
547
548 if (args)
549 {
550 /* Scan through the args and pick up the first non option arg
551 as the filename. */
552
553 gdb_argv built_argv (args);
554 char **argv = built_argv.get ();
555
556 for (; (*argv != NULL) && (**argv == '-'); argv++)
557 {;
558 }
559 if (*argv == NULL)
560 error (_("No executable file name was specified"));
561
562 gdb::unique_xmalloc_ptr<char> filename (tilde_expand (*argv));
563 exec_file_attach (filename.get (), from_tty);
564 }
565 else
566 exec_file_attach (NULL, from_tty);
567}
568
569/* Set both the exec file and the symbol file, in one command.
570 What a novelty. Why did GDB go through four major releases before this
571 command was added? */
572
573static void
574file_command (const char *arg, int from_tty)
575{
576 /* FIXME, if we lose on reading the symbol file, we should revert
577 the exec file, but that's rough. */
578 exec_file_command (arg, from_tty);
579 symbol_file_command (arg, from_tty);
580 if (deprecated_file_changed_hook)
581 deprecated_file_changed_hook (arg);
582}
583\f
584
585/* Builds a section table, given args BFD, TABLE. */
586
587std::vector<target_section>
588build_section_table (struct bfd *some_bfd)
589{
590 std::vector<target_section> table;
591
592 for (asection *asect : gdb_bfd_sections (some_bfd))
593 {
594 flagword aflag;
595
596 /* Check the section flags, but do not discard zero-length
597 sections, since some symbols may still be attached to this
598 section. For instance, we encountered on sparc-solaris 2.10
599 a shared library with an empty .bss section to which a symbol
600 named "_end" was attached. The address of this symbol still
601 needs to be relocated. */
602 aflag = bfd_section_flags (asect);
603 if (!(aflag & SEC_ALLOC))
604 continue;
605
606 table.emplace_back (bfd_section_vma (asect),
607 bfd_section_vma (asect) + bfd_section_size (asect),
608 asect);
609 }
610
611 return table;
612}
613
614/* Add the sections array defined by [SECTIONS..SECTIONS_END[ to the
615 current set of target sections. */
616
617void
618program_space::add_target_sections
619 (target_section_owner owner, const std::vector<target_section> &sections)
620{
621 if (!sections.empty ())
622 {
623 for (const target_section &s : sections)
624 {
625 m_target_sections.push_back (s);
626 m_target_sections.back ().owner = owner;
627 }
628
629 scoped_restore_current_pspace_and_thread restore_pspace_thread;
630
631 /* If these are the first file sections we can provide memory
632 from, push the file_stratum target. Must do this in all
633 inferiors sharing the program space. */
634 for (inferior *inf : all_inferiors ())
635 {
636 if (inf->pspace != this)
637 continue;
638
639 if (inf->target_is_pushed (&exec_ops))
640 continue;
641
642 switch_to_inferior_no_thread (inf);
643 inf->push_target (&exec_ops);
644 }
645 }
646}
647
648/* Add the sections of OBJFILE to the current set of target sections. */
649
650void
651program_space::add_target_sections (struct objfile *objfile)
652{
653 gdb_assert (objfile != nullptr);
654
655 /* Compute the number of sections to add. */
656 for (obj_section *osect : objfile->sections ())
657 {
658 if (bfd_section_size (osect->the_bfd_section) == 0)
659 continue;
660
661 m_target_sections.emplace_back (osect->addr (), osect->endaddr (),
662 osect->the_bfd_section, objfile);
663 }
664}
665
666/* Remove all target sections owned by OWNER.
667 OWNER must be the same value passed to add_target_sections. */
668
669void
670program_space::remove_target_sections (target_section_owner owner)
671{
672 gdb_assert (owner.v () != nullptr);
673
674 auto it = std::remove_if (m_target_sections.begin (),
675 m_target_sections.end (),
676 [&] (target_section &sect)
677 {
678 return sect.owner.v () == owner.v ();
679 });
680 m_target_sections.erase (it, m_target_sections.end ());
681
682 /* If we don't have any more sections to read memory from,
683 remove the file_stratum target from the stack of each
684 inferior sharing the program space. */
685 if (m_target_sections.empty ())
686 {
687 scoped_restore_current_pspace_and_thread restore_pspace_thread;
688
689 for (inferior *inf : all_inferiors ())
690 {
691 if (inf->pspace != this)
692 continue;
693
694 switch_to_inferior_no_thread (inf);
695 inf->unpush_target (&exec_ops);
696 }
697 }
698}
699
700/* See exec.h. */
701
702void
703exec_on_vfork (inferior *vfork_child)
704{
705 if (!vfork_child->pspace->target_sections ().empty ())
706 vfork_child->push_target (&exec_ops);
707}
708
709\f
710
711enum target_xfer_status
712exec_read_partial_read_only (gdb_byte *readbuf, ULONGEST offset,
713 ULONGEST len, ULONGEST *xfered_len)
714{
715 /* It's unduly pedantic to refuse to look at the executable for
716 read-only pieces; so do the equivalent of readonly regions aka
717 QTro packet. */
718 if (current_program_space->exec_bfd () != NULL)
719 {
720 asection *s;
721 bfd_size_type size;
722 bfd_vma vma;
723
724 for (s = current_program_space->exec_bfd ()->sections; s; s = s->next)
725 {
726 if ((s->flags & SEC_LOAD) == 0
727 || (s->flags & SEC_READONLY) == 0)
728 continue;
729
730 vma = s->vma;
731 size = bfd_section_size (s);
732 if (vma <= offset && offset < (vma + size))
733 {
734 ULONGEST amt;
735
736 amt = (vma + size) - offset;
737 if (amt > len)
738 amt = len;
739
740 amt = bfd_get_section_contents (current_program_space->exec_bfd (), s,
741 readbuf, offset - vma, amt);
742
743 if (amt == 0)
744 return TARGET_XFER_EOF;
745 else
746 {
747 *xfered_len = amt;
748 return TARGET_XFER_OK;
749 }
750 }
751 }
752 }
753
754 /* Indicate failure to find the requested memory block. */
755 return TARGET_XFER_E_IO;
756}
757
758/* Return all read-only memory ranges found in the target section
759 table defined by SECTIONS and SECTIONS_END, starting at (and
760 intersected with) MEMADDR for LEN bytes. */
761
762static std::vector<mem_range>
763section_table_available_memory (CORE_ADDR memaddr, ULONGEST len,
764 const std::vector<target_section> &sections)
765{
766 std::vector<mem_range> memory;
767
768 for (const target_section &p : sections)
769 {
770 if ((bfd_section_flags (p.the_bfd_section) & SEC_READONLY) == 0)
771 continue;
772
773 /* Copy the meta-data, adjusted. */
774 if (mem_ranges_overlap (p.addr, p.endaddr - p.addr, memaddr, len))
775 {
776 ULONGEST lo1, hi1, lo2, hi2;
777
778 lo1 = memaddr;
779 hi1 = memaddr + len;
780
781 lo2 = p.addr;
782 hi2 = p.endaddr;
783
784 CORE_ADDR start = std::max (lo1, lo2);
785 int length = std::min (hi1, hi2) - start;
786
787 memory.emplace_back (start, length);
788 }
789 }
790
791 return memory;
792}
793
794enum target_xfer_status
795section_table_read_available_memory (gdb_byte *readbuf, ULONGEST offset,
796 ULONGEST len, ULONGEST *xfered_len)
797{
798 const std::vector<target_section> *table
799 = target_get_section_table (current_inferior ()->top_target ());
800 std::vector<mem_range> available_memory
801 = section_table_available_memory (offset, len, *table);
802
803 normalize_mem_ranges (&available_memory);
804
805 for (const mem_range &r : available_memory)
806 {
807 if (mem_ranges_overlap (r.start, r.length, offset, len))
808 {
809 CORE_ADDR end;
810 enum target_xfer_status status;
811
812 /* Get the intersection window. */
813 end = std::min<CORE_ADDR> (offset + len, r.start + r.length);
814
815 gdb_assert (end - offset <= len);
816
817 if (offset >= r.start)
818 status = exec_read_partial_read_only (readbuf, offset,
819 end - offset,
820 xfered_len);
821 else
822 {
823 *xfered_len = r.start - offset;
824 status = TARGET_XFER_UNAVAILABLE;
825 }
826 return status;
827 }
828 }
829
830 *xfered_len = len;
831 return TARGET_XFER_UNAVAILABLE;
832}
833
834enum target_xfer_status
835section_table_xfer_memory_partial (gdb_byte *readbuf, const gdb_byte *writebuf,
836 ULONGEST offset, ULONGEST len,
837 ULONGEST *xfered_len,
838 const std::vector<target_section> &sections,
839 gdb::function_view<bool
840 (const struct target_section *)> match_cb)
841{
842 int res;
843 ULONGEST memaddr = offset;
844 ULONGEST memend = memaddr + len;
845
846 gdb_assert (len != 0);
847
848 for (const target_section &p : sections)
849 {
850 struct bfd_section *asect = p.the_bfd_section;
851 bfd *abfd = asect->owner;
852
853 if (match_cb != nullptr && !match_cb (&p))
854 continue; /* not the section we need. */
855 if (memaddr >= p.addr)
856 {
857 if (memend <= p.endaddr)
858 {
859 /* Entire transfer is within this section. */
860 if (writebuf)
861 res = bfd_set_section_contents (abfd, asect,
862 writebuf, memaddr - p.addr,
863 len);
864 else
865 res = bfd_get_section_contents (abfd, asect,
866 readbuf, memaddr - p.addr,
867 len);
868
869 if (res != 0)
870 {
871 *xfered_len = len;
872 return TARGET_XFER_OK;
873 }
874 else
875 return TARGET_XFER_EOF;
876 }
877 else if (memaddr >= p.endaddr)
878 {
879 /* This section ends before the transfer starts. */
880 continue;
881 }
882 else
883 {
884 /* This section overlaps the transfer. Just do half. */
885 len = p.endaddr - memaddr;
886 if (writebuf)
887 res = bfd_set_section_contents (abfd, asect,
888 writebuf, memaddr - p.addr,
889 len);
890 else
891 res = bfd_get_section_contents (abfd, asect,
892 readbuf, memaddr - p.addr,
893 len);
894 if (res != 0)
895 {
896 *xfered_len = len;
897 return TARGET_XFER_OK;
898 }
899 else
900 return TARGET_XFER_EOF;
901 }
902 }
903 }
904
905 return TARGET_XFER_EOF; /* We can't help. */
906}
907
908enum target_xfer_status
909exec_target::xfer_partial (enum target_object object,
910 const char *annex, gdb_byte *readbuf,
911 const gdb_byte *writebuf,
912 ULONGEST offset, ULONGEST len, ULONGEST *xfered_len)
913{
914 const std::vector<target_section> *table = target_get_section_table (this);
915
916 if (object == TARGET_OBJECT_MEMORY)
917 return section_table_xfer_memory_partial (readbuf, writebuf,
918 offset, len, xfered_len,
919 *table);
920 else
921 return TARGET_XFER_E_IO;
922}
923\f
924
925void
926print_section_info (const std::vector<target_section> *t, bfd *abfd)
927{
928 struct gdbarch *gdbarch = gdbarch_from_bfd (abfd);
929 /* FIXME: 16 is not wide enough when gdbarch_addr_bit > 64. */
930 int wid = gdbarch_addr_bit (gdbarch) <= 32 ? 8 : 16;
931
932 gdb_printf ("\t`%ps', ",
933 styled_string (file_name_style.style (),
934 bfd_get_filename (abfd)));
935 gdb_stdout->wrap_here (8);
936 gdb_printf (_("file type %s.\n"), bfd_get_target (abfd));
937 if (abfd == current_program_space->exec_bfd ())
938 {
939 /* gcc-3.4 does not like the initialization in
940 <p == t->sections_end>. */
941 bfd_vma displacement = 0;
942 bfd_vma entry_point;
943 bool found = false;
944
945 for (const target_section &p : *t)
946 {
947 struct bfd_section *psect = p.the_bfd_section;
948
949 if ((bfd_section_flags (psect) & (SEC_ALLOC | SEC_LOAD))
950 != (SEC_ALLOC | SEC_LOAD))
951 continue;
952
953 if (bfd_section_vma (psect) <= abfd->start_address
954 && abfd->start_address < (bfd_section_vma (psect)
955 + bfd_section_size (psect)))
956 {
957 displacement = p.addr - bfd_section_vma (psect);
958 found = true;
959 break;
960 }
961 }
962 if (!found)
963 warning (_("Cannot find section for the entry point of %ps."),
964 styled_string (file_name_style.style (),
965 bfd_get_filename (abfd)));
966
967 entry_point = gdbarch_addr_bits_remove (gdbarch,
968 bfd_get_start_address (abfd)
969 + displacement);
970 gdb_printf (_("\tEntry point: %s\n"),
971 paddress (gdbarch, entry_point));
972 }
973 for (const target_section &p : *t)
974 {
975 struct bfd_section *psect = p.the_bfd_section;
976 bfd *pbfd = psect->owner;
977
978 gdb_printf ("\t%s", hex_string_custom (p.addr, wid));
979 gdb_printf (" - %s", hex_string_custom (p.endaddr, wid));
980
981 /* FIXME: A format of "08l" is not wide enough for file offsets
982 larger than 4GB. OTOH, making it "016l" isn't desirable either
983 since most output will then be much wider than necessary. It
984 may make sense to test the size of the file and choose the
985 format string accordingly. */
986 /* FIXME: i18n: Need to rewrite this sentence. */
987 if (info_verbose)
988 gdb_printf (" @ %s",
989 hex_string_custom (psect->filepos, 8));
990 gdb_printf (" is %s", bfd_section_name (psect));
991 if (pbfd != abfd)
992 gdb_printf (" in %ps",
993 styled_string (file_name_style.style (),
994 bfd_get_filename (pbfd)));
995 gdb_printf ("\n");
996 }
997}
998
999void
1000exec_target::files_info ()
1001{
1002 if (current_program_space->exec_bfd ())
1003 print_section_info (&current_program_space->target_sections (),
1004 current_program_space->exec_bfd ());
1005 else
1006 gdb_puts (_("\t<no file loaded>\n"));
1007}
1008
1009static void
1010set_section_command (const char *args, int from_tty)
1011{
1012 const char *secname;
1013
1014 if (args == 0)
1015 error (_("Must specify section name and its virtual address"));
1016
1017 /* Parse out section name. */
1018 for (secname = args; !isspace (*args); args++);
1019 unsigned seclen = args - secname;
1020
1021 /* Parse out new virtual address. */
1022 CORE_ADDR secaddr = parse_and_eval_address (args);
1023
1024 for (target_section &p : current_program_space->target_sections ())
1025 {
1026 if (!strncmp (secname, bfd_section_name (p.the_bfd_section), seclen)
1027 && bfd_section_name (p.the_bfd_section)[seclen] == '\0')
1028 {
1029 long offset = secaddr - p.addr;
1030 p.addr += offset;
1031 p.endaddr += offset;
1032 if (from_tty)
1033 exec_ops.files_info ();
1034 return;
1035 }
1036 }
1037
1038 std::string secprint (secname, seclen);
1039 error (_("Section %s not found"), secprint.c_str ());
1040}
1041
1042/* If we can find a section in FILENAME with BFD index INDEX, adjust
1043 it to ADDRESS. */
1044
1045void
1046exec_set_section_address (const char *filename, int index, CORE_ADDR address)
1047{
1048 for (target_section &p : current_program_space->target_sections ())
1049 {
1050 if (filename_cmp (filename,
1051 bfd_get_filename (p.the_bfd_section->owner)) == 0
1052 && index == p.the_bfd_section->index)
1053 {
1054 p.endaddr += address - p.addr;
1055 p.addr = address;
1056 }
1057 }
1058}
1059
1060bool
1061exec_target::has_memory ()
1062{
1063 /* We can provide memory if we have any file/target sections to read
1064 from. */
1065 return !current_program_space->target_sections ().empty ();
1066}
1067
1068gdb::unique_xmalloc_ptr<char>
1069exec_target::make_corefile_notes (bfd *obfd, int *note_size)
1070{
1071 error (_("Can't create a corefile"));
1072}
1073
1074int
1075exec_target::find_memory_regions (find_memory_region_ftype func, void *data)
1076{
1077 return objfile_find_memory_regions (this, func, data);
1078}
1079
1080INIT_GDB_FILE (exec)
1081{
1082 struct cmd_list_element *c;
1083
1084 c = add_cmd ("file", class_files, file_command, _("\
1085Use FILE as program to be debugged.\n\
1086It is read for its symbols, for getting the contents of pure memory,\n\
1087and it is the program executed when you use the `run' command.\n\
1088If FILE cannot be found as specified, your execution directory path\n\
1089($PATH) is searched for a command of that name.\n\
1090No arg means to have no executable file and no symbols."), &cmdlist);
1091 set_cmd_completer (c, filename_maybe_quoted_completer);
1092
1093 c = add_cmd ("exec-file", class_files, exec_file_command, _("\
1094Use FILE as program for getting contents of pure memory.\n\
1095If FILE cannot be found as specified, your execution directory path\n\
1096is searched for a command of that name.\n\
1097No arg means have no executable file."), &cmdlist);
1098 set_cmd_completer (c, filename_maybe_quoted_completer);
1099
1100 add_com ("section", class_files, set_section_command, _("\
1101Change the base address of section SECTION of the exec file to ADDR.\n\
1102This can be used if the exec file does not contain section addresses,\n\
1103(such as in the a.out format), or when the addresses specified in the\n\
1104file itself are wrong. Each section must be changed separately. The\n\
1105``info files'' command lists all the sections and their addresses."));
1106
1107 add_setshow_boolean_cmd ("write", class_support, &write_files, _("\
1108Set writing into executable and core files."), _("\
1109Show writing into executable and core files."), NULL,
1110 NULL,
1111 show_write_files,
1112 &setlist, &showlist);
1113
1114 add_setshow_enum_cmd ("exec-file-mismatch", class_support,
1115 exec_file_mismatch_names,
1116 &exec_file_mismatch,
1117 _("\
1118Set exec-file-mismatch handling (ask|warn|off)."),
1119 _("\
1120Show exec-file-mismatch handling (ask|warn|off)."),
1121 _("\
1122Specifies how to handle a mismatch between the current exec-file\n\
1123loaded by GDB and the exec-file automatically determined when attaching\n\
1124to a process:\n\n\
1125 ask - warn the user and ask whether to load the determined exec-file.\n\
1126 warn - warn the user, but do not change the exec-file.\n\
1127 off - do not check for mismatch.\n\
1128\n\
1129GDB detects a mismatch by comparing the build IDs of the files.\n\
1130If the user confirms loading the determined exec-file, then its symbols\n\
1131will be loaded as well."),
1132 set_exec_file_mismatch_command,
1133 show_exec_file_mismatch_command,
1134 &setlist, &showlist);
1135
1136 add_target (exec_target_info, exec_target_open,
1137 filename_maybe_quoted_completer);
1138}