* windows-nat.c (windows_make_so): Use gdb_bfd_open.
[external/binutils.git] / gdb / rs6000-nat.c
1 /* IBM RS/6000 native-dependent code for GDB, the GNU debugger.
2
3    Copyright (C) 1986-1987, 1989, 1991-2004, 2007-2012 Free Software
4    Foundation, Inc.
5
6    This file is part of GDB.
7
8    This program is free software; you can redistribute it and/or modify
9    it under the terms of the GNU General Public License as published by
10    the Free Software Foundation; either version 3 of the License, or
11    (at your option) any later version.
12
13    This program is distributed in the hope that it will be useful,
14    but WITHOUT ANY WARRANTY; without even the implied warranty of
15    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16    GNU General Public License for more details.
17
18    You should have received a copy of the GNU General Public License
19    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
20
21 #include "defs.h"
22 #include "inferior.h"
23 #include "target.h"
24 #include "gdbcore.h"
25 #include "xcoffsolib.h"
26 #include "symfile.h"
27 #include "objfiles.h"
28 #include "libbfd.h"             /* For bfd_default_set_arch_mach (FIXME) */
29 #include "bfd.h"
30 #include "exceptions.h"
31 #include "gdb-stabs.h"
32 #include "regcache.h"
33 #include "arch-utils.h"
34 #include "inf-child.h"
35 #include "inf-ptrace.h"
36 #include "ppc-tdep.h"
37 #include "rs6000-tdep.h"
38 #include "exec.h"
39 #include "observer.h"
40 #include "xcoffread.h"
41
42 #include <sys/ptrace.h>
43 #include <sys/reg.h>
44
45 #include <sys/param.h>
46 #include <sys/dir.h>
47 #include <sys/user.h>
48 #include <signal.h>
49 #include <sys/ioctl.h>
50 #include <fcntl.h>
51 #include <errno.h>
52
53 #include <a.out.h>
54 #include <sys/file.h>
55 #include "gdb_stat.h"
56 #include <sys/core.h>
57 #define __LDINFO_PTRACE32__     /* for __ld_info32 */
58 #define __LDINFO_PTRACE64__     /* for __ld_info64 */
59 #include <sys/ldr.h>
60 #include <sys/systemcfg.h>
61
62 /* On AIX4.3+, sys/ldr.h provides different versions of struct ld_info for
63    debugging 32-bit and 64-bit processes.  Define a typedef and macros for
64    accessing fields in the appropriate structures.  */
65
66 /* In 32-bit compilation mode (which is the only mode from which ptrace()
67    works on 4.3), __ld_info32 is #defined as equivalent to ld_info.  */
68
69 #ifdef __ld_info32
70 # define ARCH3264
71 #endif
72
73 /* Return whether the current architecture is 64-bit.  */
74
75 #ifndef ARCH3264
76 # define ARCH64() 0
77 #else
78 # define ARCH64() (register_size (target_gdbarch, 0) == 8)
79 #endif
80
81 /* Union of 32-bit and 64-bit versions of ld_info.  */
82
83 typedef union {
84 #ifndef ARCH3264
85   struct ld_info l32;
86   struct ld_info l64;
87 #else
88   struct __ld_info32 l32;
89   struct __ld_info64 l64;
90 #endif
91 } LdInfo;
92
93 /* If compiling with 32-bit and 64-bit debugging capability (e.g. AIX 4.x),
94    declare and initialize a variable named VAR suitable for use as the arch64
95    parameter to the various LDI_*() macros.  */
96
97 #ifndef ARCH3264
98 # define ARCH64_DECL(var)
99 #else
100 # define ARCH64_DECL(var) int var = ARCH64 ()
101 #endif
102
103 /* Return LDI's FIELD for a 64-bit process if ARCH64 and for a 32-bit process
104    otherwise.  This technique only works for FIELDs with the same data type in
105    32-bit and 64-bit versions of ld_info.  */
106
107 #ifndef ARCH3264
108 # define LDI_FIELD(ldi, arch64, field) (ldi)->l32.ldinfo_##field
109 #else
110 # define LDI_FIELD(ldi, arch64, field) \
111   (arch64 ? (ldi)->l64.ldinfo_##field : (ldi)->l32.ldinfo_##field)
112 #endif
113
114 /* Return various LDI fields for a 64-bit process if ARCH64 and for a 32-bit
115    process otherwise.  */
116
117 #define LDI_NEXT(ldi, arch64)           LDI_FIELD(ldi, arch64, next)
118 #define LDI_FD(ldi, arch64)             LDI_FIELD(ldi, arch64, fd)
119 #define LDI_FILENAME(ldi, arch64)       LDI_FIELD(ldi, arch64, filename)
120
121 extern struct vmap *map_vmap (bfd * bf, bfd * arch);
122
123 static void vmap_exec (void);
124
125 static void vmap_ldinfo (LdInfo *);
126
127 static struct vmap *add_vmap (LdInfo *);
128
129 static int objfile_symbol_add (void *);
130
131 static void vmap_symtab (struct vmap *);
132
133 static void exec_one_dummy_insn (struct regcache *);
134
135 extern void fixup_breakpoints (CORE_ADDR low, CORE_ADDR high, CORE_ADDR delta);
136
137 /* Given REGNO, a gdb register number, return the corresponding
138    number suitable for use as a ptrace() parameter.  Return -1 if
139    there's no suitable mapping.  Also, set the int pointed to by
140    ISFLOAT to indicate whether REGNO is a floating point register.  */
141
142 static int
143 regmap (struct gdbarch *gdbarch, int regno, int *isfloat)
144 {
145   struct gdbarch_tdep *tdep = gdbarch_tdep (gdbarch);
146
147   *isfloat = 0;
148   if (tdep->ppc_gp0_regnum <= regno
149       && regno < tdep->ppc_gp0_regnum + ppc_num_gprs)
150     return regno;
151   else if (tdep->ppc_fp0_regnum >= 0
152            && tdep->ppc_fp0_regnum <= regno
153            && regno < tdep->ppc_fp0_regnum + ppc_num_fprs)
154     {
155       *isfloat = 1;
156       return regno - tdep->ppc_fp0_regnum + FPR0;
157     }
158   else if (regno == gdbarch_pc_regnum (gdbarch))
159     return IAR;
160   else if (regno == tdep->ppc_ps_regnum)
161     return MSR;
162   else if (regno == tdep->ppc_cr_regnum)
163     return CR;
164   else if (regno == tdep->ppc_lr_regnum)
165     return LR;
166   else if (regno == tdep->ppc_ctr_regnum)
167     return CTR;
168   else if (regno == tdep->ppc_xer_regnum)
169     return XER;
170   else if (tdep->ppc_fpscr_regnum >= 0
171            && regno == tdep->ppc_fpscr_regnum)
172     return FPSCR;
173   else if (tdep->ppc_mq_regnum >= 0 && regno == tdep->ppc_mq_regnum)
174     return MQ;
175   else
176     return -1;
177 }
178
179 /* Call ptrace(REQ, ID, ADDR, DATA, BUF).  */
180
181 static int
182 rs6000_ptrace32 (int req, int id, int *addr, int data, int *buf)
183 {
184   int ret = ptrace (req, id, (int *)addr, data, buf);
185 #if 0
186   printf ("rs6000_ptrace32 (%d, %d, 0x%x, %08x, 0x%x) = 0x%x\n",
187           req, id, (unsigned int)addr, data, (unsigned int)buf, ret);
188 #endif
189   return ret;
190 }
191
192 /* Call ptracex(REQ, ID, ADDR, DATA, BUF).  */
193
194 static int
195 rs6000_ptrace64 (int req, int id, long long addr, int data, void *buf)
196 {
197 #ifdef ARCH3264
198   int ret = ptracex (req, id, addr, data, buf);
199 #else
200   int ret = 0;
201 #endif
202 #if 0
203   printf ("rs6000_ptrace64 (%d, %d, %s, %08x, 0x%x) = 0x%x\n",
204           req, id, hex_string (addr), data, (unsigned int)buf, ret);
205 #endif
206   return ret;
207 }
208
209 /* Fetch register REGNO from the inferior.  */
210
211 static void
212 fetch_register (struct regcache *regcache, int regno)
213 {
214   struct gdbarch *gdbarch = get_regcache_arch (regcache);
215   int addr[MAX_REGISTER_SIZE];
216   int nr, isfloat;
217
218   /* Retrieved values may be -1, so infer errors from errno.  */
219   errno = 0;
220
221   nr = regmap (gdbarch, regno, &isfloat);
222
223   /* Floating-point registers.  */
224   if (isfloat)
225     rs6000_ptrace32 (PT_READ_FPR, PIDGET (inferior_ptid), addr, nr, 0);
226
227   /* Bogus register number.  */
228   else if (nr < 0)
229     {
230       if (regno >= gdbarch_num_regs (gdbarch))
231         fprintf_unfiltered (gdb_stderr,
232                             "gdb error: register no %d not implemented.\n",
233                             regno);
234       return;
235     }
236
237   /* Fixed-point registers.  */
238   else
239     {
240       if (!ARCH64 ())
241         *addr = rs6000_ptrace32 (PT_READ_GPR, PIDGET (inferior_ptid),
242                                  (int *) nr, 0, 0);
243       else
244         {
245           /* PT_READ_GPR requires the buffer parameter to point to long long,
246              even if the register is really only 32 bits.  */
247           long long buf;
248           rs6000_ptrace64 (PT_READ_GPR, PIDGET (inferior_ptid), nr, 0, &buf);
249           if (register_size (gdbarch, regno) == 8)
250             memcpy (addr, &buf, 8);
251           else
252             *addr = buf;
253         }
254     }
255
256   if (!errno)
257     regcache_raw_supply (regcache, regno, (char *) addr);
258   else
259     {
260 #if 0
261       /* FIXME: this happens 3 times at the start of each 64-bit program.  */
262       perror (_("ptrace read"));
263 #endif
264       errno = 0;
265     }
266 }
267
268 /* Store register REGNO back into the inferior.  */
269
270 static void
271 store_register (struct regcache *regcache, int regno)
272 {
273   struct gdbarch *gdbarch = get_regcache_arch (regcache);
274   int addr[MAX_REGISTER_SIZE];
275   int nr, isfloat;
276
277   /* Fetch the register's value from the register cache.  */
278   regcache_raw_collect (regcache, regno, addr);
279
280   /* -1 can be a successful return value, so infer errors from errno.  */
281   errno = 0;
282
283   nr = regmap (gdbarch, regno, &isfloat);
284
285   /* Floating-point registers.  */
286   if (isfloat)
287     rs6000_ptrace32 (PT_WRITE_FPR, PIDGET (inferior_ptid), addr, nr, 0);
288
289   /* Bogus register number.  */
290   else if (nr < 0)
291     {
292       if (regno >= gdbarch_num_regs (gdbarch))
293         fprintf_unfiltered (gdb_stderr,
294                             "gdb error: register no %d not implemented.\n",
295                             regno);
296     }
297
298   /* Fixed-point registers.  */
299   else
300     {
301       if (regno == gdbarch_sp_regnum (gdbarch))
302         /* Execute one dummy instruction (which is a breakpoint) in inferior
303            process to give kernel a chance to do internal housekeeping.
304            Otherwise the following ptrace(2) calls will mess up user stack
305            since kernel will get confused about the bottom of the stack
306            (%sp).  */
307         exec_one_dummy_insn (regcache);
308
309       /* The PT_WRITE_GPR operation is rather odd.  For 32-bit inferiors,
310          the register's value is passed by value, but for 64-bit inferiors,
311          the address of a buffer containing the value is passed.  */
312       if (!ARCH64 ())
313         rs6000_ptrace32 (PT_WRITE_GPR, PIDGET (inferior_ptid),
314                          (int *) nr, *addr, 0);
315       else
316         {
317           /* PT_WRITE_GPR requires the buffer parameter to point to an 8-byte
318              area, even if the register is really only 32 bits.  */
319           long long buf;
320           if (register_size (gdbarch, regno) == 8)
321             memcpy (&buf, addr, 8);
322           else
323             buf = *addr;
324           rs6000_ptrace64 (PT_WRITE_GPR, PIDGET (inferior_ptid), nr, 0, &buf);
325         }
326     }
327
328   if (errno)
329     {
330       perror (_("ptrace write"));
331       errno = 0;
332     }
333 }
334
335 /* Read from the inferior all registers if REGNO == -1 and just register
336    REGNO otherwise.  */
337
338 static void
339 rs6000_fetch_inferior_registers (struct target_ops *ops,
340                                  struct regcache *regcache, int regno)
341 {
342   struct gdbarch *gdbarch = get_regcache_arch (regcache);
343   if (regno != -1)
344     fetch_register (regcache, regno);
345
346   else
347     {
348       struct gdbarch_tdep *tdep = gdbarch_tdep (gdbarch);
349
350       /* Read 32 general purpose registers.  */
351       for (regno = tdep->ppc_gp0_regnum;
352            regno < tdep->ppc_gp0_regnum + ppc_num_gprs;
353            regno++)
354         {
355           fetch_register (regcache, regno);
356         }
357
358       /* Read general purpose floating point registers.  */
359       if (tdep->ppc_fp0_regnum >= 0)
360         for (regno = 0; regno < ppc_num_fprs; regno++)
361           fetch_register (regcache, tdep->ppc_fp0_regnum + regno);
362
363       /* Read special registers.  */
364       fetch_register (regcache, gdbarch_pc_regnum (gdbarch));
365       fetch_register (regcache, tdep->ppc_ps_regnum);
366       fetch_register (regcache, tdep->ppc_cr_regnum);
367       fetch_register (regcache, tdep->ppc_lr_regnum);
368       fetch_register (regcache, tdep->ppc_ctr_regnum);
369       fetch_register (regcache, tdep->ppc_xer_regnum);
370       if (tdep->ppc_fpscr_regnum >= 0)
371         fetch_register (regcache, tdep->ppc_fpscr_regnum);
372       if (tdep->ppc_mq_regnum >= 0)
373         fetch_register (regcache, tdep->ppc_mq_regnum);
374     }
375 }
376
377 /* Store our register values back into the inferior.
378    If REGNO is -1, do this for all registers.
379    Otherwise, REGNO specifies which register (so we can save time).  */
380
381 static void
382 rs6000_store_inferior_registers (struct target_ops *ops,
383                                  struct regcache *regcache, int regno)
384 {
385   struct gdbarch *gdbarch = get_regcache_arch (regcache);
386   if (regno != -1)
387     store_register (regcache, regno);
388
389   else
390     {
391       struct gdbarch_tdep *tdep = gdbarch_tdep (gdbarch);
392
393       /* Write general purpose registers first.  */
394       for (regno = tdep->ppc_gp0_regnum;
395            regno < tdep->ppc_gp0_regnum + ppc_num_gprs;
396            regno++)
397         {
398           store_register (regcache, regno);
399         }
400
401       /* Write floating point registers.  */
402       if (tdep->ppc_fp0_regnum >= 0)
403         for (regno = 0; regno < ppc_num_fprs; regno++)
404           store_register (regcache, tdep->ppc_fp0_regnum + regno);
405
406       /* Write special registers.  */
407       store_register (regcache, gdbarch_pc_regnum (gdbarch));
408       store_register (regcache, tdep->ppc_ps_regnum);
409       store_register (regcache, tdep->ppc_cr_regnum);
410       store_register (regcache, tdep->ppc_lr_regnum);
411       store_register (regcache, tdep->ppc_ctr_regnum);
412       store_register (regcache, tdep->ppc_xer_regnum);
413       if (tdep->ppc_fpscr_regnum >= 0)
414         store_register (regcache, tdep->ppc_fpscr_regnum);
415       if (tdep->ppc_mq_regnum >= 0)
416         store_register (regcache, tdep->ppc_mq_regnum);
417     }
418 }
419
420
421 /* Attempt a transfer all LEN bytes starting at OFFSET between the
422    inferior's OBJECT:ANNEX space and GDB's READBUF/WRITEBUF buffer.
423    Return the number of bytes actually transferred.  */
424
425 static LONGEST
426 rs6000_xfer_partial (struct target_ops *ops, enum target_object object,
427                      const char *annex, gdb_byte *readbuf,
428                      const gdb_byte *writebuf,
429                      ULONGEST offset, LONGEST len)
430 {
431   pid_t pid = ptid_get_pid (inferior_ptid);
432   int arch64 = ARCH64 ();
433
434   switch (object)
435     {
436     case TARGET_OBJECT_MEMORY:
437       {
438         union
439         {
440           PTRACE_TYPE_RET word;
441           gdb_byte byte[sizeof (PTRACE_TYPE_RET)];
442         } buffer;
443         ULONGEST rounded_offset;
444         LONGEST partial_len;
445
446         /* Round the start offset down to the next long word
447            boundary.  */
448         rounded_offset = offset & -(ULONGEST) sizeof (PTRACE_TYPE_RET);
449
450         /* Since ptrace will transfer a single word starting at that
451            rounded_offset the partial_len needs to be adjusted down to
452            that (remember this function only does a single transfer).
453            Should the required length be even less, adjust it down
454            again.  */
455         partial_len = (rounded_offset + sizeof (PTRACE_TYPE_RET)) - offset;
456         if (partial_len > len)
457           partial_len = len;
458
459         if (writebuf)
460           {
461             /* If OFFSET:PARTIAL_LEN is smaller than
462                ROUNDED_OFFSET:WORDSIZE then a read/modify write will
463                be needed.  Read in the entire word.  */
464             if (rounded_offset < offset
465                 || (offset + partial_len
466                     < rounded_offset + sizeof (PTRACE_TYPE_RET)))
467               {
468                 /* Need part of initial word -- fetch it.  */
469                 if (arch64)
470                   buffer.word = rs6000_ptrace64 (PT_READ_I, pid,
471                                                  rounded_offset, 0, NULL);
472                 else
473                   buffer.word = rs6000_ptrace32 (PT_READ_I, pid,
474                                                  (int *) (uintptr_t)
475                                                  rounded_offset,
476                                                  0, NULL);
477               }
478
479             /* Copy data to be written over corresponding part of
480                buffer.  */
481             memcpy (buffer.byte + (offset - rounded_offset),
482                     writebuf, partial_len);
483
484             errno = 0;
485             if (arch64)
486               rs6000_ptrace64 (PT_WRITE_D, pid,
487                                rounded_offset, buffer.word, NULL);
488             else
489               rs6000_ptrace32 (PT_WRITE_D, pid,
490                                (int *) (uintptr_t) rounded_offset,
491                                buffer.word, NULL);
492             if (errno)
493               return 0;
494           }
495
496         if (readbuf)
497           {
498             errno = 0;
499             if (arch64)
500               buffer.word = rs6000_ptrace64 (PT_READ_I, pid,
501                                              rounded_offset, 0, NULL);
502             else
503               buffer.word = rs6000_ptrace32 (PT_READ_I, pid,
504                                              (int *)(uintptr_t)rounded_offset,
505                                              0, NULL);
506             if (errno)
507               return 0;
508
509             /* Copy appropriate bytes out of the buffer.  */
510             memcpy (readbuf, buffer.byte + (offset - rounded_offset),
511                     partial_len);
512           }
513
514         return partial_len;
515       }
516
517     default:
518       return -1;
519     }
520 }
521
522 /* Wait for the child specified by PTID to do something.  Return the
523    process ID of the child, or MINUS_ONE_PTID in case of error; store
524    the status in *OURSTATUS.  */
525
526 static ptid_t
527 rs6000_wait (struct target_ops *ops,
528              ptid_t ptid, struct target_waitstatus *ourstatus, int options)
529 {
530   pid_t pid;
531   int status, save_errno;
532
533   do
534     {
535       set_sigint_trap ();
536
537       do
538         {
539           pid = waitpid (ptid_get_pid (ptid), &status, 0);
540           save_errno = errno;
541         }
542       while (pid == -1 && errno == EINTR);
543
544       clear_sigint_trap ();
545
546       if (pid == -1)
547         {
548           fprintf_unfiltered (gdb_stderr,
549                               _("Child process unexpectedly missing: %s.\n"),
550                               safe_strerror (save_errno));
551
552           /* Claim it exited with unknown signal.  */
553           ourstatus->kind = TARGET_WAITKIND_SIGNALLED;
554           ourstatus->value.sig = GDB_SIGNAL_UNKNOWN;
555           return inferior_ptid;
556         }
557
558       /* Ignore terminated detached child processes.  */
559       if (!WIFSTOPPED (status) && pid != ptid_get_pid (inferior_ptid))
560         pid = -1;
561     }
562   while (pid == -1);
563
564   /* AIX has a couple of strange returns from wait().  */
565
566   /* stop after load" status.  */
567   if (status == 0x57c)
568     ourstatus->kind = TARGET_WAITKIND_LOADED;
569   /* signal 0.  I have no idea why wait(2) returns with this status word.  */
570   else if (status == 0x7f)
571     ourstatus->kind = TARGET_WAITKIND_SPURIOUS;
572   /* A normal waitstatus.  Let the usual macros deal with it.  */
573   else
574     store_waitstatus (ourstatus, status);
575
576   return pid_to_ptid (pid);
577 }
578
579 /* Execute one dummy breakpoint instruction.  This way we give the kernel
580    a chance to do some housekeeping and update inferior's internal data,
581    including u_area.  */
582
583 static void
584 exec_one_dummy_insn (struct regcache *regcache)
585 {
586 #define DUMMY_INSN_ADDR AIX_TEXT_SEGMENT_BASE+0x200
587
588   struct gdbarch *gdbarch = get_regcache_arch (regcache);
589   int ret, status, pid;
590   CORE_ADDR prev_pc;
591   void *bp;
592
593   /* We plant one dummy breakpoint into DUMMY_INSN_ADDR address.  We
594      assume that this address will never be executed again by the real
595      code.  */
596
597   bp = deprecated_insert_raw_breakpoint (gdbarch, NULL, DUMMY_INSN_ADDR);
598
599   /* You might think this could be done with a single ptrace call, and
600      you'd be correct for just about every platform I've ever worked
601      on.  However, rs6000-ibm-aix4.1.3 seems to have screwed this up --
602      the inferior never hits the breakpoint (it's also worth noting
603      powerpc-ibm-aix4.1.3 works correctly).  */
604   prev_pc = regcache_read_pc (regcache);
605   regcache_write_pc (regcache, DUMMY_INSN_ADDR);
606   if (ARCH64 ())
607     ret = rs6000_ptrace64 (PT_CONTINUE, PIDGET (inferior_ptid), 1, 0, NULL);
608   else
609     ret = rs6000_ptrace32 (PT_CONTINUE, PIDGET (inferior_ptid),
610                            (int *) 1, 0, NULL);
611
612   if (ret != 0)
613     perror (_("pt_continue"));
614
615   do
616     {
617       pid = waitpid (PIDGET (inferior_ptid), &status, 0);
618     }
619   while (pid != PIDGET (inferior_ptid));
620
621   regcache_write_pc (regcache, prev_pc);
622   deprecated_remove_raw_breakpoint (gdbarch, bp);
623 }
624 \f
625
626 /* Copy information about text and data sections from LDI to VP for a 64-bit
627    process if ARCH64 and for a 32-bit process otherwise.  */
628
629 static void
630 vmap_secs (struct vmap *vp, LdInfo *ldi, int arch64)
631 {
632   if (arch64)
633     {
634       vp->tstart = (CORE_ADDR) ldi->l64.ldinfo_textorg;
635       vp->tend = vp->tstart + ldi->l64.ldinfo_textsize;
636       vp->dstart = (CORE_ADDR) ldi->l64.ldinfo_dataorg;
637       vp->dend = vp->dstart + ldi->l64.ldinfo_datasize;
638     }
639   else
640     {
641       vp->tstart = (unsigned long) ldi->l32.ldinfo_textorg;
642       vp->tend = vp->tstart + ldi->l32.ldinfo_textsize;
643       vp->dstart = (unsigned long) ldi->l32.ldinfo_dataorg;
644       vp->dend = vp->dstart + ldi->l32.ldinfo_datasize;
645     }
646
647   /* The run time loader maps the file header in addition to the text
648      section and returns a pointer to the header in ldinfo_textorg.
649      Adjust the text start address to point to the real start address
650      of the text section.  */
651   vp->tstart += vp->toffs;
652 }
653
654 /* Handle symbol translation on vmapping.  */
655
656 static void
657 vmap_symtab (struct vmap *vp)
658 {
659   struct objfile *objfile;
660   struct section_offsets *new_offsets;
661   int i;
662
663   objfile = vp->objfile;
664   if (objfile == NULL)
665     {
666       /* OK, it's not an objfile we opened ourselves.
667          Currently, that can only happen with the exec file, so
668          relocate the symbols for the symfile.  */
669       if (symfile_objfile == NULL)
670         return;
671       objfile = symfile_objfile;
672     }
673   else if (!vp->loaded)
674     /* If symbols are not yet loaded, offsets are not yet valid.  */
675     return;
676
677   new_offsets =
678     (struct section_offsets *)
679     alloca (SIZEOF_N_SECTION_OFFSETS (objfile->num_sections));
680
681   for (i = 0; i < objfile->num_sections; ++i)
682     new_offsets->offsets[i] = ANOFFSET (objfile->section_offsets, i);
683
684   /* The symbols in the object file are linked to the VMA of the section,
685      relocate them VMA relative.  */
686   new_offsets->offsets[SECT_OFF_TEXT (objfile)] = vp->tstart - vp->tvma;
687   new_offsets->offsets[SECT_OFF_DATA (objfile)] = vp->dstart - vp->dvma;
688   new_offsets->offsets[SECT_OFF_BSS (objfile)] = vp->dstart - vp->dvma;
689
690   objfile_relocate (objfile, new_offsets);
691 }
692 \f
693 /* Add symbols for an objfile.  */
694
695 static int
696 objfile_symbol_add (void *arg)
697 {
698   struct objfile *obj = (struct objfile *) arg;
699
700   syms_from_objfile (obj, NULL, 0, 0, 0);
701   new_symfile_objfile (obj, 0);
702   return 1;
703 }
704
705 /* Add symbols for a vmap. Return zero upon error.  */
706
707 int
708 vmap_add_symbols (struct vmap *vp)
709 {
710   if (catch_errors (objfile_symbol_add, vp->objfile,
711                     "Error while reading shared library symbols:\n",
712                     RETURN_MASK_ALL))
713     {
714       /* Note this is only done if symbol reading was successful.  */
715       vp->loaded = 1;
716       vmap_symtab (vp);
717       return 1;
718     }
719   return 0;
720 }
721
722 /* Add a new vmap entry based on ldinfo() information.
723
724    If ldi->ldinfo_fd is not valid (e.g. this struct ld_info is from a
725    core file), the caller should set it to -1, and we will open the file.
726
727    Return the vmap new entry.  */
728
729 static struct vmap *
730 add_vmap (LdInfo *ldi)
731 {
732   bfd *abfd, *last;
733   char *mem, *filename;
734   struct objfile *obj;
735   struct vmap *vp;
736   int fd;
737   ARCH64_DECL (arch64);
738
739   /* This ldi structure was allocated using alloca() in 
740      xcoff_relocate_symtab().  Now we need to have persistent object 
741      and member names, so we should save them.  */
742
743   filename = LDI_FILENAME (ldi, arch64);
744   mem = filename + strlen (filename) + 1;
745   mem = xstrdup (mem);
746
747   fd = LDI_FD (ldi, arch64);
748   abfd = gdb_bfd_open (filename, gnutarget, fd < 0 ? -1 : fd);
749   if (!abfd)
750     {
751       warning (_("Could not open `%s' as an executable file: %s"),
752                filename, bfd_errmsg (bfd_get_error ()));
753       return NULL;
754     }
755
756   /* Make sure we have an object file.  */
757
758   if (bfd_check_format (abfd, bfd_object))
759     vp = map_vmap (abfd, 0);
760
761   else if (bfd_check_format (abfd, bfd_archive))
762     {
763       last = gdb_bfd_openr_next_archived_file (abfd, NULL);
764       while (last != NULL)
765         {
766           bfd *next;
767
768           if (strcmp (mem, last->filename) == 0)
769             break;
770
771           next = gdb_bfd_openr_next_archived_file (abfd, last);
772           gdb_bfd_unref (last);
773         }
774
775       if (!last)
776         {
777           warning (_("\"%s\": member \"%s\" missing."), filename, mem);
778           gdb_bfd_unref (abfd);
779           return NULL;
780         }
781
782       if (!bfd_check_format (last, bfd_object))
783         {
784           warning (_("\"%s\": member \"%s\" not in executable format: %s."),
785                    filename, mem, bfd_errmsg (bfd_get_error ()));
786           gdb_bfd_unref (last);
787           gdb_bfd_unref (abfd);
788           return NULL;
789         }
790
791       vp = map_vmap (last, abfd);
792       /* map_vmap acquired a reference to LAST, so we can release
793          ours.  */
794       gdb_bfd_unref (last);
795     }
796   else
797     {
798       warning (_("\"%s\": not in executable format: %s."),
799                filename, bfd_errmsg (bfd_get_error ()));
800       gdb_bfd_unref (abfd);
801       return NULL;
802     }
803   obj = allocate_objfile (vp->bfd, 0);
804   vp->objfile = obj;
805
806   /* Always add symbols for the main objfile.  */
807   if (vp == vmap || auto_solib_add)
808     vmap_add_symbols (vp);
809
810   /* Anything needing a reference to ABFD has already acquired it, so
811      release our local reference.  */
812   gdb_bfd_unref (abfd);
813
814   return vp;
815 }
816 \f
817 /* update VMAP info with ldinfo() information
818    Input is ptr to ldinfo() results.  */
819
820 static void
821 vmap_ldinfo (LdInfo *ldi)
822 {
823   struct stat ii, vi;
824   struct vmap *vp;
825   int got_one, retried;
826   int got_exec_file = 0;
827   uint next;
828   int arch64 = ARCH64 ();
829
830   /* For each *ldi, see if we have a corresponding *vp.
831      If so, update the mapping, and symbol table.
832      If not, add an entry and symbol table.  */
833
834   do
835     {
836       char *name = LDI_FILENAME (ldi, arch64);
837       char *memb = name + strlen (name) + 1;
838       int fd = LDI_FD (ldi, arch64);
839
840       retried = 0;
841
842       if (fstat (fd, &ii) < 0)
843         {
844           /* The kernel sets ld_info to -1, if the process is still using the
845              object, and the object is removed.  Keep the symbol info for the
846              removed object and issue a warning.  */
847           warning (_("%s (fd=%d) has disappeared, keeping its symbols"),
848                    name, fd);
849           continue;
850         }
851     retry:
852       for (got_one = 0, vp = vmap; vp; vp = vp->nxt)
853         {
854           struct objfile *objfile;
855
856           /* First try to find a `vp', which is the same as in ldinfo.
857              If not the same, just continue and grep the next `vp'.  If same,
858              relocate its tstart, tend, dstart, dend values.  If no such `vp'
859              found, get out of this for loop, add this ldi entry as a new vmap
860              (add_vmap) and come back, find its `vp' and so on...  */
861
862           /* The filenames are not always sufficient to match on.  */
863
864           if ((name[0] == '/' && strcmp (name, vp->name) != 0)
865               || (memb[0] && strcmp (memb, vp->member) != 0))
866             continue;
867
868           /* See if we are referring to the same file.
869              We have to check objfile->obfd, symfile.c:reread_symbols might
870              have updated the obfd after a change.  */
871           objfile = vp->objfile == NULL ? symfile_objfile : vp->objfile;
872           if (objfile == NULL
873               || objfile->obfd == NULL
874               || bfd_stat (objfile->obfd, &vi) < 0)
875             {
876               warning (_("Unable to stat %s, keeping its symbols"), name);
877               continue;
878             }
879
880           if (ii.st_dev != vi.st_dev || ii.st_ino != vi.st_ino)
881             continue;
882
883           if (!retried)
884             close (fd);
885
886           ++got_one;
887
888           /* Found a corresponding VMAP.  Remap!  */
889
890           vmap_secs (vp, ldi, arch64);
891
892           /* The objfile is only NULL for the exec file.  */
893           if (vp->objfile == NULL)
894             got_exec_file = 1;
895
896           /* relocate symbol table(s).  */
897           vmap_symtab (vp);
898
899           /* Announce new object files.  Doing this after symbol relocation
900              makes aix-thread.c's job easier.  */
901           if (vp->objfile)
902             observer_notify_new_objfile (vp->objfile);
903
904           /* There may be more, so we don't break out of the loop.  */
905         }
906
907       /* If there was no matching *vp, we must perforce create the
908          sucker(s). */
909       if (!got_one && !retried)
910         {
911           add_vmap (ldi);
912           ++retried;
913           goto retry;
914         }
915     }
916   while ((next = LDI_NEXT (ldi, arch64))
917          && (ldi = (void *) (next + (char *) ldi)));
918
919   /* If we don't find the symfile_objfile anywhere in the ldinfo, it
920      is unlikely that the symbol file is relocated to the proper
921      address.  And we might have attached to a process which is
922      running a different copy of the same executable.  */
923   if (symfile_objfile != NULL && !got_exec_file)
924     {
925       warning (_("Symbol file %s\nis not mapped; discarding it.\n\
926 If in fact that file has symbols which the mapped files listed by\n\
927 \"info files\" lack, you can load symbols with the \"symbol-file\" or\n\
928 \"add-symbol-file\" commands (note that you must take care of relocating\n\
929 symbols to the proper address)."),
930                symfile_objfile->name);
931       free_objfile (symfile_objfile);
932       gdb_assert (symfile_objfile == NULL);
933     }
934   breakpoint_re_set ();
935 }
936 \f
937 /* As well as symbol tables, exec_sections need relocation.  After
938    the inferior process' termination, there will be a relocated symbol
939    table exist with no corresponding inferior process.  At that time, we
940    need to use `exec' bfd, rather than the inferior process's memory space
941    to look up symbols.
942
943    `exec_sections' need to be relocated only once, as long as the exec
944    file remains unchanged.  */
945
946 static void
947 vmap_exec (void)
948 {
949   static bfd *execbfd;
950   int i;
951   struct target_section_table *table = target_get_section_table (&exec_ops);
952
953   if (execbfd == exec_bfd)
954     return;
955
956   execbfd = exec_bfd;
957
958   if (!vmap || !table->sections)
959     error (_("vmap_exec: vmap or table->sections == 0."));
960
961   for (i = 0; &table->sections[i] < table->sections_end; i++)
962     {
963       if (strcmp (".text", table->sections[i].the_bfd_section->name) == 0)
964         {
965           table->sections[i].addr += vmap->tstart - vmap->tvma;
966           table->sections[i].endaddr += vmap->tstart - vmap->tvma;
967         }
968       else if (strcmp (".data", table->sections[i].the_bfd_section->name) == 0)
969         {
970           table->sections[i].addr += vmap->dstart - vmap->dvma;
971           table->sections[i].endaddr += vmap->dstart - vmap->dvma;
972         }
973       else if (strcmp (".bss", table->sections[i].the_bfd_section->name) == 0)
974         {
975           table->sections[i].addr += vmap->dstart - vmap->dvma;
976           table->sections[i].endaddr += vmap->dstart - vmap->dvma;
977         }
978     }
979 }
980
981 /* Set the current architecture from the host running GDB.  Called when
982    starting a child process.  */
983
984 static void (*super_create_inferior) (struct target_ops *,char *exec_file, 
985                                       char *allargs, char **env, int from_tty);
986 static void
987 rs6000_create_inferior (struct target_ops * ops, char *exec_file,
988                         char *allargs, char **env, int from_tty)
989 {
990   enum bfd_architecture arch;
991   unsigned long mach;
992   bfd abfd;
993   struct gdbarch_info info;
994
995   super_create_inferior (ops, exec_file, allargs, env, from_tty);
996
997   if (__power_rs ())
998     {
999       arch = bfd_arch_rs6000;
1000       mach = bfd_mach_rs6k;
1001     }
1002   else
1003     {
1004       arch = bfd_arch_powerpc;
1005       mach = bfd_mach_ppc;
1006     }
1007
1008   /* FIXME: schauer/2002-02-25:
1009      We don't know if we are executing a 32 or 64 bit executable,
1010      and have no way to pass the proper word size to rs6000_gdbarch_init.
1011      So we have to avoid switching to a new architecture, if the architecture
1012      matches already.
1013      Blindly calling rs6000_gdbarch_init used to work in older versions of
1014      GDB, as rs6000_gdbarch_init incorrectly used the previous tdep to
1015      determine the wordsize.  */
1016   if (exec_bfd)
1017     {
1018       const struct bfd_arch_info *exec_bfd_arch_info;
1019
1020       exec_bfd_arch_info = bfd_get_arch_info (exec_bfd);
1021       if (arch == exec_bfd_arch_info->arch)
1022         return;
1023     }
1024
1025   bfd_default_set_arch_mach (&abfd, arch, mach);
1026
1027   gdbarch_info_init (&info);
1028   info.bfd_arch_info = bfd_get_arch_info (&abfd);
1029   info.abfd = exec_bfd;
1030
1031   if (!gdbarch_update_p (info))
1032     internal_error (__FILE__, __LINE__,
1033                     _("rs6000_create_inferior: failed "
1034                       "to select architecture"));
1035 }
1036
1037 \f
1038 /* xcoff_relocate_symtab -      hook for symbol table relocation.
1039    
1040    This is only applicable to live processes, and is a no-op when
1041    debugging a core file.  */
1042
1043 void
1044 xcoff_relocate_symtab (unsigned int pid)
1045 {
1046   int load_segs = 64; /* number of load segments */
1047   int rc;
1048   LdInfo *ldi = NULL;
1049   int arch64 = ARCH64 ();
1050   int ldisize = arch64 ? sizeof (ldi->l64) : sizeof (ldi->l32);
1051   int size;
1052
1053   /* Nothing to do if we are debugging a core file.  */
1054   if (!target_has_execution)
1055     return;
1056
1057   do
1058     {
1059       size = load_segs * ldisize;
1060       ldi = (void *) xrealloc (ldi, size);
1061
1062 #if 0
1063       /* According to my humble theory, AIX has some timing problems and
1064          when the user stack grows, kernel doesn't update stack info in time
1065          and ptrace calls step on user stack.  That is why we sleep here a
1066          little, and give kernel to update its internals.  */
1067       usleep (36000);
1068 #endif
1069
1070       if (arch64)
1071         rc = rs6000_ptrace64 (PT_LDINFO, pid, (unsigned long) ldi, size, NULL);
1072       else
1073         rc = rs6000_ptrace32 (PT_LDINFO, pid, (int *) ldi, size, NULL);
1074
1075       if (rc == -1)
1076         {
1077           if (errno == ENOMEM)
1078             load_segs *= 2;
1079           else
1080             perror_with_name (_("ptrace ldinfo"));
1081         }
1082       else
1083         {
1084           vmap_ldinfo (ldi);
1085           vmap_exec (); /* relocate the exec and core sections as well.  */
1086         }
1087     } while (rc == -1);
1088   if (ldi)
1089     xfree (ldi);
1090 }
1091 \f
1092 /* Core file stuff.  */
1093
1094 /* Relocate symtabs and read in shared library info, based on symbols
1095    from the core file.  */
1096
1097 void
1098 xcoff_relocate_core (struct target_ops *target)
1099 {
1100   struct bfd_section *ldinfo_sec;
1101   int offset = 0;
1102   LdInfo *ldi;
1103   struct vmap *vp;
1104   int arch64 = ARCH64 ();
1105
1106   /* Size of a struct ld_info except for the variable-length filename.  */
1107   int nonfilesz = (int)LDI_FILENAME ((LdInfo *)0, arch64);
1108
1109   /* Allocated size of buffer.  */
1110   int buffer_size = nonfilesz;
1111   char *buffer = xmalloc (buffer_size);
1112   struct cleanup *old = make_cleanup (free_current_contents, &buffer);
1113
1114   ldinfo_sec = bfd_get_section_by_name (core_bfd, ".ldinfo");
1115   if (ldinfo_sec == NULL)
1116     {
1117     bfd_err:
1118       fprintf_filtered (gdb_stderr, "Couldn't get ldinfo from core file: %s\n",
1119                         bfd_errmsg (bfd_get_error ()));
1120       do_cleanups (old);
1121       return;
1122     }
1123   do
1124     {
1125       int i;
1126       int names_found = 0;
1127
1128       /* Read in everything but the name.  */
1129       if (bfd_get_section_contents (core_bfd, ldinfo_sec, buffer,
1130                                     offset, nonfilesz) == 0)
1131         goto bfd_err;
1132
1133       /* Now the name.  */
1134       i = nonfilesz;
1135       do
1136         {
1137           if (i == buffer_size)
1138             {
1139               buffer_size *= 2;
1140               buffer = xrealloc (buffer, buffer_size);
1141             }
1142           if (bfd_get_section_contents (core_bfd, ldinfo_sec, &buffer[i],
1143                                         offset + i, 1) == 0)
1144             goto bfd_err;
1145           if (buffer[i++] == '\0')
1146             ++names_found;
1147         }
1148       while (names_found < 2);
1149
1150       ldi = (LdInfo *) buffer;
1151
1152       /* Can't use a file descriptor from the core file; need to open it.  */
1153       if (arch64)
1154         ldi->l64.ldinfo_fd = -1;
1155       else
1156         ldi->l32.ldinfo_fd = -1;
1157
1158       /* The first ldinfo is for the exec file, allocated elsewhere.  */
1159       if (offset == 0 && vmap != NULL)
1160         vp = vmap;
1161       else
1162         vp = add_vmap (ldi);
1163
1164       /* Process next shared library upon error.  */
1165       offset += LDI_NEXT (ldi, arch64);
1166       if (vp == NULL)
1167         continue;
1168
1169       vmap_secs (vp, ldi, arch64);
1170
1171       /* Unless this is the exec file,
1172          add our sections to the section table for the core target.  */
1173       if (vp != vmap)
1174         {
1175           struct target_section *stp;
1176
1177           stp = deprecated_core_resize_section_table (2);
1178
1179           stp->bfd = vp->bfd;
1180           stp->the_bfd_section = bfd_get_section_by_name (stp->bfd, ".text");
1181           stp->addr = vp->tstart;
1182           stp->endaddr = vp->tend;
1183           stp++;
1184
1185           stp->bfd = vp->bfd;
1186           stp->the_bfd_section = bfd_get_section_by_name (stp->bfd, ".data");
1187           stp->addr = vp->dstart;
1188           stp->endaddr = vp->dend;
1189         }
1190
1191       vmap_symtab (vp);
1192
1193       if (vp != vmap && vp->objfile)
1194         observer_notify_new_objfile (vp->objfile);
1195     }
1196   while (LDI_NEXT (ldi, arch64) != 0);
1197   vmap_exec ();
1198   breakpoint_re_set ();
1199   do_cleanups (old);
1200 }
1201 \f
1202 /* Under AIX, we have to pass the correct TOC pointer to a function
1203    when calling functions in the inferior.
1204    We try to find the relative toc offset of the objfile containing PC
1205    and add the current load address of the data segment from the vmap.  */
1206
1207 static CORE_ADDR
1208 find_toc_address (CORE_ADDR pc)
1209 {
1210   struct vmap *vp;
1211
1212   for (vp = vmap; vp; vp = vp->nxt)
1213     {
1214       if (pc >= vp->tstart && pc < vp->tend)
1215         {
1216           /* vp->objfile is only NULL for the exec file.  */
1217           return vp->dstart + xcoff_get_toc_offset (vp->objfile == NULL
1218                                                     ? symfile_objfile
1219                                                     : vp->objfile);
1220         }
1221     }
1222   error (_("Unable to find TOC entry for pc %s."), hex_string (pc));
1223 }
1224 \f
1225
1226 void _initialize_rs6000_nat (void);
1227
1228 void
1229 _initialize_rs6000_nat (void)
1230 {
1231   struct target_ops *t;
1232
1233   t = inf_ptrace_target ();
1234   t->to_fetch_registers = rs6000_fetch_inferior_registers;
1235   t->to_store_registers = rs6000_store_inferior_registers;
1236   t->to_xfer_partial = rs6000_xfer_partial;
1237
1238   super_create_inferior = t->to_create_inferior;
1239   t->to_create_inferior = rs6000_create_inferior;
1240
1241   t->to_wait = rs6000_wait;
1242
1243   add_target (t);
1244
1245   /* Initialize hook in rs6000-tdep.c for determining the TOC address
1246      when calling functions in the inferior.  */
1247   rs6000_find_toc_address_hook = find_toc_address;
1248 }