exec.c 31 KB

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