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