]> git.ipfire.org Git - thirdparty/binutils-gdb.git/blame - gdb/exec.c
Automatic date update in version.in
[thirdparty/binutils-gdb.git] / gdb / exec.c
CommitLineData
c906108c 1/* Work with executable files, for GDB.
4646aa9d 2
d01e8234 3 Copyright (C) 1988-2025 Free Software Foundation, Inc.
c906108c 4
c5aa993b 5 This file is part of GDB.
c906108c 6
c5aa993b
JM
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
a9762ec7 9 the Free Software Foundation; either version 3 of the License, or
c5aa993b 10 (at your option) any later version.
c906108c 11
c5aa993b
JM
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.
c906108c 16
c5aa993b 17 You should have received a copy of the GNU General Public License
a9762ec7 18 along with this program. If not, see <http://www.gnu.org/licenses/>. */
c906108c 19
c906108c 20#include "frame.h"
d55e5aa6 21#include "inferior.h"
4de283e4 22#include "target.h"
5b9707eb 23#include "cli/cli-cmds.h"
c906108c 24#include "language.h"
4de283e4
TT
25#include "filenames.h"
26#include "symfile.h"
c906108c 27#include "objfiles.h"
4de283e4
TT
28#include "completer.h"
29#include "value.h"
30#include "exec.h"
76727919 31#include "observable.h"
4de283e4
TT
32#include "arch-utils.h"
33#include "gdbthread.h"
6c95b8df 34#include "progspace.h"
53af73bf 35#include "progspace-and-thread.h"
4de283e4
TT
36#include "gdb_bfd.h"
37#include "gcore.h"
38#include "source.h"
98c59b52 39#include "build-id.h"
4de283e4
TT
40
41#include <fcntl.h>
e0eac551 42#include "readline/tilde.h"
4de283e4
TT
43#include "gdbcore.h"
44
45#include <ctype.h>
46#include <sys/stat.h>
2c3e1c3f 47#include "solib.h"
4de283e4 48#include <algorithm>
268a13a5 49#include "gdbsupport/pathstuff.h"
a2fedca9 50#include "cli/cli-style.h"
7904e961 51#include "gdbsupport/buildargv.h"
c906108c 52
1d8b34a7 53void (*deprecated_file_changed_hook) (const char *);
c906108c 54
d9f719f1
PA
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
c906108c
SS
62/* The target vector for executable files. */
63
f6ac5f3d
PA
64struct exec_target final : public target_ops
65{
d9f719f1
PA
66 const target_info &info () const override
67 { return exec_target_info; }
f6ac5f3d 68
66b4deae
PA
69 strata stratum () const override { return file_stratum; }
70
f6ac5f3d
PA
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;
f6ac5f3d
PA
78 void files_info () override;
79
57810aa7 80 bool has_memory () override;
24f5300a 81 gdb::unique_xmalloc_ptr<char> make_corefile_notes (bfd *, int *) override;
f6ac5f3d
PA
82 int find_memory_regions (find_memory_region_ftype func, void *data) override;
83};
84
85static exec_target exec_ops;
c906108c 86
a2fedca9
PW
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{
6cb06a8c
TT
105 gdb_printf (file,
106 _("exec-file-mismatch handling is currently \"%s\".\n"),
107 exec_file_mismatch_names[exec_file_mismatch_mode]);
a2fedca9
PW
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)
f34652de 125 internal_error (_("Unrecognized exec-file-mismatch setting: \"%s\""),
a2fedca9
PW
126 exec_file_mismatch);
127 }
128}
129
c906108c
SS
130/* Whether to open exec and core files read-only or read-write. */
131
491144b5 132bool write_files = false;
920d2a44
AC
133static void
134show_write_files (struct ui_file *file, int from_tty,
135 struct cmd_list_element *c, const char *value)
136{
6cb06a8c
TT
137 gdb_printf (file, _("Writing into executable and core files is %s.\n"),
138 value);
920d2a44
AC
139}
140
c906108c 141
d9f719f1
PA
142static void
143exec_target_open (const char *args, int from_tty)
1adeb98a
FN
144{
145 target_preopen (from_tty);
03ad29c8
AB
146
147 std::string filename = extract_single_filename_arg (args);
148 exec_file_attach (filename.empty () ? nullptr : filename.c_str (),
149 from_tty);
1adeb98a
FN
150}
151
6c95b8df
PA
152/* This is the target_close implementation. Clears all target
153 sections and closes all executable bfds from all program spaces. */
154
f6ac5f3d
PA
155void
156exec_target::close ()
c906108c 157{
94c93c35 158 for (struct program_space *ss : program_spaces)
5ed8105e 159 {
02f7d26b 160 ss->clear_target_sections ();
8a4f1402 161 ss->exec_close ();
5ed8105e 162 }
c906108c
SS
163}
164
f6ac5f3d 165/* See gdbcore.h. */
a10de604
GB
166
167void
ecf45d2c
SL
168try_open_exec_file (const char *exec_file_host, struct inferior *inf,
169 symfile_add_flags add_flags)
a10de604 170{
cc06b668 171 struct gdb_exception prev_err;
a10de604 172
57d1de9c
LM
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.
88178e82 180
57d1de9c
LM
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. */
a70b8144 184 try
57d1de9c 185 {
ecf45d2c
SL
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);
57d1de9c 189 }
94aeb44b 190 catch (gdb_exception_error &err)
57d1de9c
LM
191 {
192 if (err.message != NULL)
3d6e9d23 193 warning ("%s", err.what ());
57d1de9c 194
94aeb44b 195 prev_err = std::move (err);
57d1de9c 196 }
57d1de9c 197
ecf45d2c 198 if (exec_file_host != NULL)
57d1de9c 199 {
a70b8144 200 try
ecf45d2c
SL
201 {
202 symbol_file_add_main (exec_file_host, add_flags);
203 }
230d2906 204 catch (const gdb_exception_error &err)
ecf45d2c 205 {
785e5700 206 if (prev_err != err)
3d6e9d23 207 warning ("%s", err.what ());
ecf45d2c 208 }
57d1de9c 209 }
ecf45d2c
SL
210}
211
212/* See gdbcore.h. */
213
a2fedca9
PW
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
ebed2c2c
AB
221 /* If there's no current executable, then there's nothing to
222 validate against, so we're done. */
0a70e1a8 223 const char *current_exec_file = current_program_space->exec_filename ();
ebed2c2c 224 if (current_exec_file == nullptr)
a2fedca9
PW
225 return;
226
ebed2c2c
AB
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;
48e9cc84 234
ebed2c2c
AB
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. */
48e9cc84 239 reopen_exec_file ();
0a70e1a8 240 current_exec_file = current_program_space->exec_filename ();
48e9cc84 241
ebed2c2c
AB
242 /* Try validating via build-id, if available. This is the most reliable
243 check. */
7e10abd1
TT
244 const bfd_build_id *exec_file_build_id
245 = build_id_bfd_get (current_program_space->exec_bfd ());
ebed2c2c 246 bool build_id_mismatch = false;
98c59b52
PA
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 ());
a2fedca9 260
98c59b52
PA
261 if (target_exec_file_build_id != nullptr)
262 {
cb1a6b85
AB
263 if (build_id_equal (exec_file_build_id,
264 target_exec_file_build_id))
98c59b52
PA
265 {
266 /* Match. */
267 return;
268 }
269 else
270 build_id_mismatch = true;
271 }
272 }
273 }
a2fedca9 274
98c59b52 275 if (build_id_mismatch)
a2fedca9 276 {
98c59b52
PA
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
a2fedca9 284 warning
0a278aa7 285 (_("Build ID mismatch between current exec-file %ps\n"
a2fedca9
PW
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)
a8654e7d
PW
295 {
296 add_flags |= SYMFILE_VERBOSE;
297 add_flags |= SYMFILE_ALWAYS_CONFIRM;
298 }
a2fedca9
PW
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 }
50f8a398 304 catch (const gdb_exception_error &err)
a2fedca9
PW
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
ecf45d2c
SL
317void
318exec_file_locate_attach (int pid, int defer_bp_reset, int from_tty)
319{
0e90c441 320 const char *exec_file_target;
ecf45d2c
SL
321 symfile_add_flags add_flags = 0;
322
323 /* Do nothing if we already have an executable filename. */
0a70e1a8 324 if (current_program_space->exec_filename () != nullptr)
ecf45d2c
SL
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)
57d1de9c 330 {
ecf45d2c
SL
331 warning (_("No executable has been specified and target does not "
332 "support\n"
333 "determining executable automatically. "
9e69a2e1
TT
334 "Try using the \"%ps\" command."),
335 styled_string (command_style.style (), "file"));
ecf45d2c 336 return;
57d1de9c 337 }
88178e82 338
797bc1cb
TT
339 gdb::unique_xmalloc_ptr<char> exec_file_host
340 = exec_file_find (exec_file_target, NULL);
bed15c77
AB
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 }
ecf45d2c
SL
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. */
797bc1cb 357 try_open_exec_file (exec_file_host.get (), current_inferior (), add_flags);
a10de604
GB
358}
359
907083d1 360/* Set FILENAME as the new exec file.
c906108c 361
c5aa993b
JM
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.)
c906108c 367
c5aa993b
JM
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.
c906108c 370
c5aa993b
JM
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 --
907083d1 375 we're supplying the exec pathname late for good reason.) */
c906108c
SS
376
377void
5f08566b 378exec_file_attach (const char *filename, int from_tty)
c906108c 379{
7e10abd1 380 /* First, acquire a reference to the exec_bfd. We release
9b333ba3
TT
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. */
7e10abd1
TT
383 gdb_bfd_ref_ptr exec_bfd_holder
384 = gdb_bfd_ref_ptr::new_reference (current_program_space->exec_bfd ());
192b62ce 385
c906108c 386 /* Remove any previous exec file. */
8a4f1402 387 current_program_space->exec_close ();
c906108c
SS
388
389 /* Now open and digest the file the user requested, if any. */
390
1adeb98a
FN
391 if (!filename)
392 {
393 if (from_tty)
6cb06a8c 394 gdb_printf (_("No executable file now.\n"));
7a107747
DJ
395
396 set_gdbarch_from_file (NULL);
1adeb98a
FN
397 }
398 else
c906108c 399 {
64c0b5de 400 int load_via_target = 0;
14278e1f 401 const char *scratch_pathname, *canonical_pathname;
c906108c 402 int scratch_chan;
d18b8b7a 403 char **matching;
c5aa993b 404
64c0b5de
GB
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
14278e1f 413 gdb::unique_xmalloc_ptr<char> canonical_storage, scratch_storage;
64c0b5de 414 if (load_via_target)
c5aa993b 415 {
64c0b5de
GB
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
14278e1f 422 scratch_pathname = filename;
64c0b5de 423 scratch_chan = -1;
64c0b5de 424 canonical_pathname = scratch_pathname;
c5aa993b 425 }
64c0b5de
GB
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,
e0cc99a6 431 &scratch_storage);
64c0b5de
GB
432#if defined(__GO32__) || defined(_WIN32) || defined(__CYGWIN__)
433 if (scratch_chan < 0)
434 {
96445f0b 435 int first_errno = errno;
0ae1c716 436 char *exename = (char *) alloca (strlen (filename) + 5);
64c0b5de
GB
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,
e0cc99a6 443 &scratch_storage);
96445f0b
HD
444 if (scratch_chan < 0)
445 errno = first_errno;
64c0b5de 446 }
c906108c 447#endif
64c0b5de
GB
448 if (scratch_chan < 0)
449 perror_with_name (filename);
a4453b7e 450
e0cc99a6 451 scratch_pathname = scratch_storage.get ();
a4453b7e 452
64c0b5de
GB
453 /* gdb_bfd_open (and its variants) prefers canonicalized
454 pathname for better BFD caching. */
14278e1f
TT
455 canonical_storage = gdb_realpath (scratch_pathname);
456 canonical_pathname = canonical_storage.get ();
64c0b5de 457 }
1f0c4988 458
192b62ce 459 gdb_bfd_ref_ptr temp;
64c0b5de 460 if (write_files && !load_via_target)
192b62ce
TT
461 temp = gdb_bfd_fopen (canonical_pathname, gnutarget,
462 FOPEN_RUB, scratch_chan);
1c00ec6b 463 else
192b62ce 464 temp = gdb_bfd_open (canonical_pathname, gnutarget, scratch_chan);
19f6550e 465 current_program_space->set_exec_bfd (std::move (temp));
c906108c 466
7e10abd1 467 if (!current_program_space->exec_bfd ())
9fe4a216 468 {
a9680e0e
TV
469 error (_("\"%s\": could not open as an executable file: %s."),
470 scratch_pathname, bfd_errmsg (bfd_get_error ()));
9fe4a216 471 }
c906108c 472
64c0b5de
GB
473 /* gdb_realpath_keepfile resolves symlinks on the local
474 filesystem and so cannot be used for "target:" files. */
9ad8c583 475 gdb_assert (current_program_space->exec_filename () == nullptr);
64c0b5de 476 if (load_via_target)
9ad8c583
SM
477 current_program_space->set_exec_filename
478 (make_unique_xstrdup
7e10abd1 479 (bfd_get_filename (current_program_space->exec_bfd ())));
64c0b5de 480 else
9ad8c583
SM
481 current_program_space->set_exec_filename
482 (make_unique_xstrdup (gdb_realpath_keepfile
483 (scratch_pathname).c_str ()));
1f0c4988 484
7e10abd1
TT
485 if (!bfd_check_format_matches (current_program_space->exec_bfd (),
486 bfd_object, &matching))
c906108c
SS
487 {
488 /* Make sure to close exec_bfd, or else "run" might try to use
489 it. */
8a4f1402 490 current_program_space->exec_close ();
a9680e0e 491 error (_("\"%s\": not in executable format: %s"), scratch_pathname,
803c08d0 492 gdb_bfd_errmsg (bfd_get_error (), matching).c_str ());
c906108c
SS
493 }
494
25b5a04e
SM
495 std::vector<target_section> sections
496 = build_section_table (current_program_space->exec_bfd ());
c906108c 497
7e10abd1 498 current_program_space->ebfd_mtime
a357defd 499 = gdb_bfd_get_mtime (current_program_space->exec_bfd ());
c04ea773 500
c906108c
SS
501 validate_files ();
502
7e10abd1 503 set_gdbarch_from_file (current_program_space->exec_bfd ());
c906108c 504
07b82ea5 505 /* Add the executable's sections to the current address spaces'
6c95b8df
PA
506 list of sections. This possibly pushes the exec_ops
507 target. */
0e17d3fc
SM
508 current_program_space->add_target_sections
509 (current_program_space->ebfd.get (), sections);
c906108c 510 }
9b333ba3 511
063453b1
AB
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);
c906108c
SS
521}
522
7831bc91
SM
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
c906108c
SS
532/* Process the first arg in ARGS as the new exec file.
533
c5aa993b
JM
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()
1adeb98a
FN
536 which can take multiple args.
537
0963b4bd 538 If ARGS is NULL, we just want to close the exec file. */
c906108c 539
1adeb98a 540static void
1d8b34a7 541exec_file_command (const char *args, int from_tty)
c906108c 542{
55f6301a 543 if (from_tty && target_has_execution ()
4c42eaff
DJ
544 && !query (_("A program is being debugged already.\n"
545 "Are you sure you want to change the file? ")))
546 error (_("File not changed."));
1adeb98a
FN
547
548 if (args)
549 {
550 /* Scan through the args and pick up the first non option arg
dda83cd7 551 as the filename. */
1adeb98a 552
773a1edc
TT
553 gdb_argv built_argv (args);
554 char **argv = built_argv.get ();
1adeb98a
FN
555
556 for (; (*argv != NULL) && (**argv == '-'); argv++)
dda83cd7
SM
557 {;
558 }
1adeb98a 559 if (*argv == NULL)
dda83cd7 560 error (_("No executable file name was specified"));
1adeb98a 561
773a1edc
TT
562 gdb::unique_xmalloc_ptr<char> filename (tilde_expand (*argv));
563 exec_file_attach (filename.get (), from_tty);
1adeb98a
FN
564 }
565 else
566 exec_file_attach (NULL, from_tty);
c906108c
SS
567}
568
0963b4bd 569/* Set both the exec file and the symbol file, in one command.
c906108c
SS
570 What a novelty. Why did GDB go through four major releases before this
571 command was added? */
572
573static void
1d8b34a7 574file_command (const char *arg, int from_tty)
c906108c
SS
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);
9a4105ab
AC
580 if (deprecated_file_changed_hook)
581 deprecated_file_changed_hook (arg);
c906108c 582}
c906108c 583\f
c5aa993b 584
2d128614 585/* Builds a section table, given args BFD, TABLE. */
c906108c 586
25b5a04e 587std::vector<target_section>
2d128614 588build_section_table (struct bfd *some_bfd)
c906108c 589{
25b5a04e 590 std::vector<target_section> table;
2d128614 591
8a6bb1d1
TT
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
6be2a9ab
TT
606 table.emplace_back (bfd_section_vma (asect),
607 bfd_section_vma (asect) + bfd_section_size (asect),
608 asect);
8a6bb1d1 609 }
e2ff18a0 610
2d128614 611 return table;
c906108c 612}
07b82ea5
PA
613
614/* Add the sections array defined by [SECTIONS..SECTIONS_END[ to the
615 current set of target sections. */
616
617void
0e17d3fc
SM
618program_space::add_target_sections
619 (target_section_owner owner, const std::vector<target_section> &sections)
07b82ea5 620{
d7a78e5c 621 if (!sections.empty ())
07b82ea5 622 {
d7a78e5c 623 for (const target_section &s : sections)
ed9eebaf 624 {
02f7d26b
AB
625 m_target_sections.push_back (s);
626 m_target_sections.back ().owner = owner;
ed9eebaf 627 }
07b82ea5 628
53af73bf 629 scoped_restore_current_pspace_and_thread restore_pspace_thread;
5b6d1e4f 630
07b82ea5 631 /* If these are the first file sections we can provide memory
5b6d1e4f
PA
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 {
3769e227 636 if (inf->pspace != this)
5b6d1e4f
PA
637 continue;
638
639 if (inf->target_is_pushed (&exec_ops))
640 continue;
641
642 switch_to_inferior_no_thread (inf);
02980c56 643 inf->push_target (&exec_ops);
5b6d1e4f 644 }
07b82ea5
PA
645 }
646}
647
76ad5e1e
NB
648/* Add the sections of OBJFILE to the current set of target sections. */
649
650void
d9eebde0 651program_space::add_target_sections (struct objfile *objfile)
76ad5e1e 652{
91840ee3 653 gdb_assert (objfile != nullptr);
76ad5e1e
NB
654
655 /* Compute the number of sections to add. */
5250cbc8 656 for (obj_section *osect : objfile->sections ())
76ad5e1e 657 {
fd361982 658 if (bfd_section_size (osect->the_bfd_section) == 0)
76ad5e1e
NB
659 continue;
660
0c1bcd23 661 m_target_sections.emplace_back (osect->addr (), osect->endaddr (),
0e17d3fc 662 osect->the_bfd_section, objfile);
76ad5e1e
NB
663 }
664}
665
046ac79f
JK
666/* Remove all target sections owned by OWNER.
667 OWNER must be the same value passed to add_target_sections. */
07b82ea5
PA
668
669void
0e17d3fc 670program_space::remove_target_sections (target_section_owner owner)
07b82ea5 671{
0e17d3fc 672 gdb_assert (owner.v () != nullptr);
046ac79f 673
02f7d26b
AB
674 auto it = std::remove_if (m_target_sections.begin (),
675 m_target_sections.end (),
bb2a6777
TT
676 [&] (target_section &sect)
677 {
0e17d3fc 678 return sect.owner.v () == owner.v ();
bb2a6777 679 });
02f7d26b 680 m_target_sections.erase (it, m_target_sections.end ());
bb2a6777
TT
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. */
02f7d26b 685 if (m_target_sections.empty ())
07b82ea5 686 {
bb2a6777 687 scoped_restore_current_pspace_and_thread restore_pspace_thread;
07b82ea5 688
bb2a6777 689 for (inferior *inf : all_inferiors ())
6c95b8df 690 {
2a3f84af 691 if (inf->pspace != this)
bb2a6777 692 continue;
6c95b8df 693
bb2a6777 694 switch_to_inferior_no_thread (inf);
fadf6add 695 inf->unpush_target (&exec_ops);
6c95b8df 696 }
07b82ea5
PA
697 }
698}
699
5b6d1e4f
PA
700/* See exec.h. */
701
702void
82d1f134 703exec_on_vfork (inferior *vfork_child)
5b6d1e4f 704{
82d1f134
SM
705 if (!vfork_child->pspace->target_sections ().empty ())
706 vfork_child->push_target (&exec_ops);
5b6d1e4f
PA
707}
708
c906108c 709\f
348f8c02 710
1ca49d37
YQ
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. */
7e10abd1 718 if (current_program_space->exec_bfd () != NULL)
1ca49d37
YQ
719 {
720 asection *s;
721 bfd_size_type size;
722 bfd_vma vma;
723
7e10abd1 724 for (s = current_program_space->exec_bfd ()->sections; s; s = s->next)
1ca49d37
YQ
725 {
726 if ((s->flags & SEC_LOAD) == 0
727 || (s->flags & SEC_READONLY) == 0)
728 continue;
729
730 vma = s->vma;
fd361982 731 size = bfd_section_size (s);
1ca49d37
YQ
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
7e10abd1 740 amt = bfd_get_section_contents (current_program_space->exec_bfd (), s,
1ca49d37
YQ
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
a79b1bc6 758/* Return all read-only memory ranges found in the target section
5a2eb0ef 759 table defined by SECTIONS and SECTIONS_END, starting at (and
a79b1bc6 760 intersected with) MEMADDR for LEN bytes. */
5a2eb0ef 761
a79b1bc6
SM
762static std::vector<mem_range>
763section_table_available_memory (CORE_ADDR memaddr, ULONGEST len,
25b5a04e 764 const std::vector<target_section> &sections)
e6ca34fc 765{
a79b1bc6 766 std::vector<mem_range> memory;
e6ca34fc 767
d7a78e5c 768 for (const target_section &p : sections)
e6ca34fc 769 {
bb2a6777 770 if ((bfd_section_flags (p.the_bfd_section) & SEC_READONLY) == 0)
e6ca34fc
PA
771 continue;
772
773 /* Copy the meta-data, adjusted. */
bb2a6777 774 if (mem_ranges_overlap (p.addr, p.endaddr - p.addr, memaddr, len))
e6ca34fc
PA
775 {
776 ULONGEST lo1, hi1, lo2, hi2;
e6ca34fc
PA
777
778 lo1 = memaddr;
779 hi1 = memaddr + len;
780
bb2a6777
TT
781 lo2 = p.addr;
782 hi2 = p.endaddr;
e6ca34fc 783
a79b1bc6
SM
784 CORE_ADDR start = std::max (lo1, lo2);
785 int length = std::min (hi1, hi2) - start;
e6ca34fc 786
a79b1bc6 787 memory.emplace_back (start, length);
e6ca34fc
PA
788 }
789 }
790
791 return memory;
792}
793
1ee79381
YQ
794enum target_xfer_status
795section_table_read_available_memory (gdb_byte *readbuf, ULONGEST offset,
796 ULONGEST len, ULONGEST *xfered_len)
797{
25b5a04e 798 const std::vector<target_section> *table
328d42d8 799 = target_get_section_table (current_inferior ()->top_target ());
a79b1bc6 800 std::vector<mem_range> available_memory
bb2a6777 801 = section_table_available_memory (offset, len, *table);
1ee79381 802
a79b1bc6 803 normalize_mem_ranges (&available_memory);
1ee79381 804
a79b1bc6 805 for (const mem_range &r : available_memory)
1ee79381 806 {
a79b1bc6 807 if (mem_ranges_overlap (r.start, r.length, offset, len))
1ee79381
YQ
808 {
809 CORE_ADDR end;
810 enum target_xfer_status status;
811
812 /* Get the intersection window. */
a79b1bc6 813 end = std::min<CORE_ADDR> (offset + len, r.start + r.length);
1ee79381
YQ
814
815 gdb_assert (end - offset <= len);
816
a79b1bc6 817 if (offset >= r.start)
1ee79381
YQ
818 status = exec_read_partial_read_only (readbuf, offset,
819 end - offset,
820 xfered_len);
821 else
822 {
a79b1bc6 823 *xfered_len = r.start - offset;
bc113b4e 824 status = TARGET_XFER_UNAVAILABLE;
1ee79381 825 }
1ee79381
YQ
826 return status;
827 }
828 }
1ee79381
YQ
829
830 *xfered_len = len;
bc113b4e 831 return TARGET_XFER_UNAVAILABLE;
1ee79381
YQ
832}
833
9b409511 834enum target_xfer_status
07b82ea5 835section_table_xfer_memory_partial (gdb_byte *readbuf, const gdb_byte *writebuf,
b55e14c7 836 ULONGEST offset, ULONGEST len,
9b409511 837 ULONGEST *xfered_len,
25b5a04e 838 const std::vector<target_section> &sections,
e56cb451
KB
839 gdb::function_view<bool
840 (const struct target_section *)> match_cb)
c906108c 841{
020cc13c 842 int res;
07b82ea5
PA
843 ULONGEST memaddr = offset;
844 ULONGEST memend = memaddr + len;
c906108c 845
e2ff18a0 846 gdb_assert (len != 0);
c906108c 847
d7a78e5c 848 for (const target_section &p : sections)
c906108c 849 {
bb2a6777 850 struct bfd_section *asect = p.the_bfd_section;
2b2848e2
DE
851 bfd *abfd = asect->owner;
852
bb2a6777 853 if (match_cb != nullptr && !match_cb (&p))
0963b4bd 854 continue; /* not the section we need. */
bb2a6777 855 if (memaddr >= p.addr)
dda83cd7 856 {
bb2a6777 857 if (memend <= p.endaddr)
3db26b01
JB
858 {
859 /* Entire transfer is within this section. */
07b82ea5 860 if (writebuf)
2b2848e2 861 res = bfd_set_section_contents (abfd, asect,
bb2a6777 862 writebuf, memaddr - p.addr,
85302095
AC
863 len);
864 else
2b2848e2 865 res = bfd_get_section_contents (abfd, asect,
bb2a6777 866 readbuf, memaddr - p.addr,
85302095 867 len);
9b409511
YQ
868
869 if (res != 0)
870 {
871 *xfered_len = len;
872 return TARGET_XFER_OK;
873 }
874 else
875 return TARGET_XFER_EOF;
3db26b01 876 }
bb2a6777 877 else if (memaddr >= p.endaddr)
3db26b01
JB
878 {
879 /* This section ends before the transfer starts. */
880 continue;
881 }
882 else
883 {
884 /* This section overlaps the transfer. Just do half. */
bb2a6777 885 len = p.endaddr - memaddr;
07b82ea5 886 if (writebuf)
2b2848e2 887 res = bfd_set_section_contents (abfd, asect,
bb2a6777 888 writebuf, memaddr - p.addr,
85302095
AC
889 len);
890 else
2b2848e2 891 res = bfd_get_section_contents (abfd, asect,
bb2a6777 892 readbuf, memaddr - p.addr,
85302095 893 len);
9b409511
YQ
894 if (res != 0)
895 {
896 *xfered_len = len;
897 return TARGET_XFER_OK;
898 }
899 else
900 return TARGET_XFER_EOF;
3db26b01 901 }
dda83cd7 902 }
c906108c
SS
903 }
904
9b409511 905 return TARGET_XFER_EOF; /* We can't help. */
c906108c 906}
348f8c02 907
f6ac5f3d
PA
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)
348f8c02 913{
25b5a04e 914 const std::vector<target_section> *table = target_get_section_table (this);
07b82ea5
PA
915
916 if (object == TARGET_OBJECT_MEMORY)
917 return section_table_xfer_memory_partial (readbuf, writebuf,
9b409511 918 offset, len, xfered_len,
bb2a6777 919 *table);
07b82ea5 920 else
2ed4b548 921 return TARGET_XFER_E_IO;
348f8c02 922}
c906108c 923\f
c5aa993b 924
c906108c 925void
25b5a04e 926print_section_info (const std::vector<target_section> *t, bfd *abfd)
c906108c 927{
5af949e3 928 struct gdbarch *gdbarch = gdbarch_from_bfd (abfd);
17a912b6 929 /* FIXME: 16 is not wide enough when gdbarch_addr_bit > 64. */
5af949e3 930 int wid = gdbarch_addr_bit (gdbarch) <= 32 ? 8 : 16;
c906108c 931
6cb06a8c
TT
932 gdb_printf ("\t`%ps', ",
933 styled_string (file_name_style.style (),
934 bfd_get_filename (abfd)));
1285ce86 935 gdb_stdout->wrap_here (8);
6cb06a8c 936 gdb_printf (_("file type %s.\n"), bfd_get_target (abfd));
7e10abd1 937 if (abfd == current_program_space->exec_bfd ())
51bee8e9 938 {
3e43a32a
MS
939 /* gcc-3.4 does not like the initialization in
940 <p == t->sections_end>. */
d904de5b 941 bfd_vma displacement = 0;
2f1bdd26 942 bfd_vma entry_point;
bb2a6777 943 bool found = false;
51bee8e9 944
d7a78e5c 945 for (const target_section &p : *t)
51bee8e9 946 {
bb2a6777 947 struct bfd_section *psect = p.the_bfd_section;
51bee8e9 948
fd361982 949 if ((bfd_section_flags (psect) & (SEC_ALLOC | SEC_LOAD))
51bee8e9
JK
950 != (SEC_ALLOC | SEC_LOAD))
951 continue;
952
fd361982
AM
953 if (bfd_section_vma (psect) <= abfd->start_address
954 && abfd->start_address < (bfd_section_vma (psect)
955 + bfd_section_size (psect)))
51bee8e9 956 {
bb2a6777
TT
957 displacement = p.addr - bfd_section_vma (psect);
958 found = true;
51bee8e9
JK
959 break;
960 }
961 }
bb2a6777 962 if (!found)
a2fedca9
PW
963 warning (_("Cannot find section for the entry point of %ps."),
964 styled_string (file_name_style.style (),
965 bfd_get_filename (abfd)));
51bee8e9 966
2f1bdd26
MGD
967 entry_point = gdbarch_addr_bits_remove (gdbarch,
968 bfd_get_start_address (abfd)
969 + displacement);
6cb06a8c
TT
970 gdb_printf (_("\tEntry point: %s\n"),
971 paddress (gdbarch, entry_point));
51bee8e9 972 }
d7a78e5c 973 for (const target_section &p : *t)
c906108c 974 {
bb2a6777 975 struct bfd_section *psect = p.the_bfd_section;
2b2848e2
DE
976 bfd *pbfd = psect->owner;
977
6cb06a8c
TT
978 gdb_printf ("\t%s", hex_string_custom (p.addr, wid));
979 gdb_printf (" - %s", hex_string_custom (p.endaddr, wid));
bcf16802
KB
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. */
a3f17187 986 /* FIXME: i18n: Need to rewrite this sentence. */
c906108c 987 if (info_verbose)
6cb06a8c
TT
988 gdb_printf (" @ %s",
989 hex_string_custom (psect->filepos, 8));
990 gdb_printf (" is %s", bfd_section_name (psect));
2b2848e2 991 if (pbfd != abfd)
6cb06a8c
TT
992 gdb_printf (" in %ps",
993 styled_string (file_name_style.style (),
994 bfd_get_filename (pbfd)));
995 gdb_printf ("\n");
c906108c
SS
996 }
997}
998
f6ac5f3d
PA
999void
1000exec_target::files_info ()
c906108c 1001{
7e10abd1 1002 if (current_program_space->exec_bfd ())
02f7d26b 1003 print_section_info (&current_program_space->target_sections (),
7e10abd1 1004 current_program_space->exec_bfd ());
57008375 1005 else
0426ad51 1006 gdb_puts (_("\t<no file loaded>\n"));
c906108c
SS
1007}
1008
1009static void
0b39b52e 1010set_section_command (const char *args, int from_tty)
c906108c 1011{
0b39b52e 1012 const char *secname;
c906108c
SS
1013
1014 if (args == 0)
8a3fe4f8 1015 error (_("Must specify section name and its virtual address"));
c906108c 1016
0963b4bd 1017 /* Parse out section name. */
c5aa993b 1018 for (secname = args; !isspace (*args); args++);
dd80d750 1019 unsigned seclen = args - secname;
c906108c 1020
0963b4bd 1021 /* Parse out new virtual address. */
dd80d750 1022 CORE_ADDR secaddr = parse_and_eval_address (args);
c906108c 1023
02f7d26b 1024 for (target_section &p : current_program_space->target_sections ())
c5aa993b 1025 {
bb2a6777
TT
1026 if (!strncmp (secname, bfd_section_name (p.the_bfd_section), seclen)
1027 && bfd_section_name (p.the_bfd_section)[seclen] == '\0')
c5aa993b 1028 {
dd80d750 1029 long offset = secaddr - p.addr;
bb2a6777
TT
1030 p.addr += offset;
1031 p.endaddr += offset;
c5aa993b 1032 if (from_tty)
f6ac5f3d 1033 exec_ops.files_info ();
c5aa993b
JM
1034 return;
1035 }
c906108c 1036 }
dd80d750
AB
1037
1038 std::string secprint (secname, seclen);
1039 error (_("Section %s not found"), secprint.c_str ());
c906108c
SS
1040}
1041
30510692
DJ
1042/* If we can find a section in FILENAME with BFD index INDEX, adjust
1043 it to ADDRESS. */
c1bd25fd
DJ
1044
1045void
1046exec_set_section_address (const char *filename, int index, CORE_ADDR address)
1047{
02f7d26b 1048 for (target_section &p : current_program_space->target_sections ())
c1bd25fd 1049 {
c7e97679 1050 if (filename_cmp (filename,
bb2a6777
TT
1051 bfd_get_filename (p.the_bfd_section->owner)) == 0
1052 && index == p.the_bfd_section->index)
c1bd25fd 1053 {
bb2a6777
TT
1054 p.endaddr += address - p.addr;
1055 p.addr = address;
c1bd25fd
DJ
1056 }
1057 }
1058}
1059
57810aa7 1060bool
f6ac5f3d 1061exec_target::has_memory ()
c35b1492
PA
1062{
1063 /* We can provide memory if we have any file/target sections to read
1064 from. */
02f7d26b 1065 return !current_program_space->target_sections ().empty ();
c35b1492
PA
1066}
1067
24f5300a 1068gdb::unique_xmalloc_ptr<char>
f6ac5f3d 1069exec_target::make_corefile_notes (bfd *obfd, int *note_size)
83814951
TT
1070{
1071 error (_("Can't create a corefile"));
1072}
be4d1333 1073
f6ac5f3d
PA
1074int
1075exec_target::find_memory_regions (find_memory_region_ftype func, void *data)
c906108c 1076{
f6ac5f3d 1077 return objfile_find_memory_regions (this, func, data);
c906108c
SS
1078}
1079
5fe70629 1080INIT_GDB_FILE (exec)
c906108c
SS
1081{
1082 struct cmd_list_element *c;
1083
49a82d50 1084 c = add_cmd ("file", class_files, file_command, _("\
1a966eab 1085Use FILE as program to be debugged.\n\
c906108c
SS
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\
1a966eab 1090No arg means to have no executable file and no symbols."), &cmdlist);
4076f962 1091 set_cmd_completer (c, filename_maybe_quoted_completer);
c906108c 1092
1a966eab
AC
1093 c = add_cmd ("exec-file", class_files, exec_file_command, _("\
1094Use FILE as program for getting contents of pure memory.\n\
c906108c
SS
1095If FILE cannot be found as specified, your execution directory path\n\
1096is searched for a command of that name.\n\
1a966eab 1097No arg means have no executable file."), &cmdlist);
4076f962 1098 set_cmd_completer (c, filename_maybe_quoted_completer);
c906108c 1099
1bedd215
AC
1100 add_com ("section", class_files, set_section_command, _("\
1101Change the base address of section SECTION of the exec file to ADDR.\n\
c906108c
SS
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\
1bedd215 1105``info files'' command lists all the sections and their addresses."));
c906108c 1106
5bf193a2
AC
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,
920d2a44 1111 show_write_files,
5bf193a2 1112 &setlist, &showlist);
c5aa993b 1113
a2fedca9
PW
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 _("\
98c59b52
PA
1122Specifies how to handle a mismatch between the current exec-file\n\
1123loaded by GDB and the exec-file automatically determined when attaching\n\
a2fedca9
PW
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\
0a278aa7
PW
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."),
a2fedca9
PW
1132 set_exec_file_mismatch_command,
1133 show_exec_file_mismatch_command,
1134 &setlist, &showlist);
1135
dc22ab49 1136 add_target (exec_target_info, exec_target_open,
03ad29c8 1137 filename_maybe_quoted_completer);
c906108c 1138}