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