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