Use class to manage BFD reference counts
[external/binutils.git] / gdb / spu-linux-nat.c
1 /* SPU native-dependent code for GDB, the GNU debugger.
2    Copyright (C) 2006-2017 Free Software Foundation, Inc.
3
4    Contributed by Ulrich Weigand <uweigand@de.ibm.com>.
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 "gdbcore.h"
23 #include "target.h"
24 #include "inferior.h"
25 #include "inf-child.h"
26 #include "inf-ptrace.h"
27 #include "regcache.h"
28 #include "symfile.h"
29 #include "gdb_wait.h"
30 #include "gdbthread.h"
31 #include "gdb_bfd.h"
32
33 #include "nat/gdb_ptrace.h"
34 #include <asm/ptrace.h>
35 #include <sys/types.h>
36
37 #include "spu-tdep.h"
38
39 /* PPU side system calls.  */
40 #define INSTR_SC        0x44000002
41 #define NR_spu_run      0x0116
42
43
44 /* Fetch PPU register REGNO.  */
45 static ULONGEST
46 fetch_ppc_register (int regno)
47 {
48   PTRACE_TYPE_RET res;
49
50   int tid = ptid_get_lwp (inferior_ptid);
51   if (tid == 0)
52     tid = ptid_get_pid (inferior_ptid);
53
54 #ifndef __powerpc64__
55   /* If running as a 32-bit process on a 64-bit system, we attempt
56      to get the full 64-bit register content of the target process.
57      If the PPC special ptrace call fails, we're on a 32-bit system;
58      just fall through to the regular ptrace call in that case.  */
59   {
60     gdb_byte buf[8];
61
62     errno = 0;
63     ptrace (PPC_PTRACE_PEEKUSR_3264, tid,
64             (PTRACE_TYPE_ARG3) (regno * 8), buf);
65     if (errno == 0)
66       ptrace (PPC_PTRACE_PEEKUSR_3264, tid,
67               (PTRACE_TYPE_ARG3) (regno * 8 + 4), buf + 4);
68     if (errno == 0)
69       return (ULONGEST) *(uint64_t *)buf;
70   }
71 #endif
72
73   errno = 0;
74   res = ptrace (PT_READ_U, tid,
75                 (PTRACE_TYPE_ARG3) (regno * sizeof (PTRACE_TYPE_RET)), 0);
76   if (errno != 0)
77     {
78       char mess[128];
79       xsnprintf (mess, sizeof mess, "reading PPC register #%d", regno);
80       perror_with_name (_(mess));
81     }
82
83   return (ULONGEST) (unsigned long) res;
84 }
85
86 /* Fetch WORD from PPU memory at (aligned) MEMADDR in thread TID.  */
87 static int
88 fetch_ppc_memory_1 (int tid, ULONGEST memaddr, PTRACE_TYPE_RET *word)
89 {
90   errno = 0;
91
92 #ifndef __powerpc64__
93   if (memaddr >> 32)
94     {
95       uint64_t addr_8 = (uint64_t) memaddr;
96       ptrace (PPC_PTRACE_PEEKTEXT_3264, tid, (PTRACE_TYPE_ARG3) &addr_8, word);
97     }
98   else
99 #endif
100     *word = ptrace (PT_READ_I, tid, (PTRACE_TYPE_ARG3) (size_t) memaddr, 0);
101
102   return errno;
103 }
104
105 /* Store WORD into PPU memory at (aligned) MEMADDR in thread TID.  */
106 static int
107 store_ppc_memory_1 (int tid, ULONGEST memaddr, PTRACE_TYPE_RET word)
108 {
109   errno = 0;
110
111 #ifndef __powerpc64__
112   if (memaddr >> 32)
113     {
114       uint64_t addr_8 = (uint64_t) memaddr;
115       ptrace (PPC_PTRACE_POKEDATA_3264, tid, (PTRACE_TYPE_ARG3) &addr_8, word);
116     }
117   else
118 #endif
119     ptrace (PT_WRITE_D, tid, (PTRACE_TYPE_ARG3) (size_t) memaddr, word);
120
121   return errno;
122 }
123
124 /* Fetch LEN bytes of PPU memory at MEMADDR to MYADDR.  */
125 static int
126 fetch_ppc_memory (ULONGEST memaddr, gdb_byte *myaddr, int len)
127 {
128   int i, ret;
129
130   ULONGEST addr = memaddr & -(ULONGEST) sizeof (PTRACE_TYPE_RET);
131   int count = ((((memaddr + len) - addr) + sizeof (PTRACE_TYPE_RET) - 1)
132                / sizeof (PTRACE_TYPE_RET));
133   PTRACE_TYPE_RET *buffer;
134
135   int tid = ptid_get_lwp (inferior_ptid);
136   if (tid == 0)
137     tid = ptid_get_pid (inferior_ptid);
138
139   buffer = (PTRACE_TYPE_RET *) alloca (count * sizeof (PTRACE_TYPE_RET));
140   for (i = 0; i < count; i++, addr += sizeof (PTRACE_TYPE_RET))
141     {
142       ret = fetch_ppc_memory_1 (tid, addr, &buffer[i]);
143       if (ret)
144         return ret;
145     }
146
147   memcpy (myaddr,
148           (char *) buffer + (memaddr & (sizeof (PTRACE_TYPE_RET) - 1)),
149           len);
150
151   return 0;
152 }
153
154 /* Store LEN bytes from MYADDR to PPU memory at MEMADDR.  */
155 static int
156 store_ppc_memory (ULONGEST memaddr, const gdb_byte *myaddr, int len)
157 {
158   int i, ret;
159
160   ULONGEST addr = memaddr & -(ULONGEST) sizeof (PTRACE_TYPE_RET);
161   int count = ((((memaddr + len) - addr) + sizeof (PTRACE_TYPE_RET) - 1)
162                / sizeof (PTRACE_TYPE_RET));
163   PTRACE_TYPE_RET *buffer;
164
165   int tid = ptid_get_lwp (inferior_ptid);
166   if (tid == 0)
167     tid = ptid_get_pid (inferior_ptid);
168
169   buffer = (PTRACE_TYPE_RET *) alloca (count * sizeof (PTRACE_TYPE_RET));
170
171   if (addr != memaddr || len < (int) sizeof (PTRACE_TYPE_RET))
172     {
173       ret = fetch_ppc_memory_1 (tid, addr, &buffer[0]);
174       if (ret)
175         return ret;
176     }
177
178   if (count > 1)
179     {
180       ret = fetch_ppc_memory_1 (tid, addr + (count - 1)
181                                                * sizeof (PTRACE_TYPE_RET),
182                                 &buffer[count - 1]);
183       if (ret)
184         return ret;
185     }
186
187   memcpy ((char *) buffer + (memaddr & (sizeof (PTRACE_TYPE_RET) - 1)),
188           myaddr, len);
189
190   for (i = 0; i < count; i++, addr += sizeof (PTRACE_TYPE_RET))
191     {
192       ret = store_ppc_memory_1 (tid, addr, buffer[i]);
193       if (ret)
194         return ret;
195     }
196
197   return 0;
198 }
199
200
201 /* If the PPU thread is currently stopped on a spu_run system call,
202    return to FD and ADDR the file handle and NPC parameter address
203    used with the system call.  Return non-zero if successful.  */
204 static int 
205 parse_spufs_run (int *fd, ULONGEST *addr)
206 {
207   enum bfd_endian byte_order = gdbarch_byte_order (target_gdbarch ());
208   gdb_byte buf[4];
209   ULONGEST pc = fetch_ppc_register (32);  /* nip */
210
211   /* Fetch instruction preceding current NIP.  */
212   if (fetch_ppc_memory (pc-4, buf, 4) != 0)
213     return 0;
214   /* It should be a "sc" instruction.  */
215   if (extract_unsigned_integer (buf, 4, byte_order) != INSTR_SC)
216     return 0;
217   /* System call number should be NR_spu_run.  */
218   if (fetch_ppc_register (0) != NR_spu_run)
219     return 0;
220
221   /* Register 3 contains fd, register 4 the NPC param pointer.  */
222   *fd = fetch_ppc_register (34);  /* orig_gpr3 */
223   *addr = fetch_ppc_register (4);
224   return 1;
225 }
226
227
228 /* Implement the to_xfer_partial target_ops method for TARGET_OBJECT_SPU.
229    Copy LEN bytes at OFFSET in spufs file ANNEX into/from READBUF or WRITEBUF,
230    using the /proc file system.  */
231
232 static enum target_xfer_status
233 spu_proc_xfer_spu (const char *annex, gdb_byte *readbuf,
234                    const gdb_byte *writebuf,
235                    ULONGEST offset, ULONGEST len, ULONGEST *xfered_len)
236 {
237   char buf[128];
238   int fd = 0;
239   int ret = -1;
240   int pid = ptid_get_pid (inferior_ptid);
241
242   if (!annex)
243     return TARGET_XFER_EOF;
244
245   xsnprintf (buf, sizeof buf, "/proc/%d/fd/%s", pid, annex);
246   fd = open (buf, writebuf? O_WRONLY : O_RDONLY);
247   if (fd <= 0)
248     return TARGET_XFER_E_IO;
249
250   if (offset != 0
251       && lseek (fd, (off_t) offset, SEEK_SET) != (off_t) offset)
252     {
253       close (fd);
254       return TARGET_XFER_EOF;
255     }
256
257   if (writebuf)
258     ret = write (fd, writebuf, (size_t) len);
259   else if (readbuf)
260     ret = read (fd, readbuf, (size_t) len);
261
262   close (fd);
263   if (ret < 0)
264     return TARGET_XFER_E_IO;
265   else if (ret == 0)
266     return TARGET_XFER_EOF;
267   else
268     {
269       *xfered_len = (ULONGEST) ret;
270       return TARGET_XFER_OK;
271     }
272 }
273
274
275 /* Inferior memory should contain an SPE executable image at location ADDR.
276    Allocate a BFD representing that executable.  Return NULL on error.  */
277
278 static void *
279 spu_bfd_iovec_open (struct bfd *nbfd, void *open_closure)
280 {
281   return open_closure;
282 }
283
284 static int
285 spu_bfd_iovec_close (struct bfd *nbfd, void *stream)
286 {
287   xfree (stream);
288
289   /* Zero means success.  */
290   return 0;
291 }
292
293 static file_ptr
294 spu_bfd_iovec_pread (struct bfd *abfd, void *stream, void *buf,
295                      file_ptr nbytes, file_ptr offset)
296 {
297   ULONGEST addr = *(ULONGEST *)stream;
298
299   if (fetch_ppc_memory (addr + offset, (gdb_byte *)buf, nbytes) != 0)
300     {
301       bfd_set_error (bfd_error_invalid_operation);
302       return -1;
303     }
304
305   return nbytes;
306 }
307
308 static int
309 spu_bfd_iovec_stat (struct bfd *abfd, void *stream, struct stat *sb)
310 {
311   /* We don't have an easy way of finding the size of embedded spu
312      images.  We could parse the in-memory ELF header and section
313      table to find the extent of the last section but that seems
314      pointless when the size is needed only for checks of other
315      parsed values in dbxread.c.  */
316   memset (sb, 0, sizeof (struct stat));
317   sb->st_size = INT_MAX;
318   return 0;
319 }
320
321 static gdb_bfd_ref_ptr
322 spu_bfd_open (ULONGEST addr)
323 {
324   asection *spu_name;
325
326   ULONGEST *open_closure = XNEW (ULONGEST);
327   *open_closure = addr;
328
329   gdb_bfd_ref_ptr nbfd (gdb_bfd_openr_iovec ("<in-memory>", "elf32-spu",
330                                              spu_bfd_iovec_open, open_closure,
331                                              spu_bfd_iovec_pread,
332                                              spu_bfd_iovec_close,
333                                              spu_bfd_iovec_stat));
334   if (nbfd == NULL)
335     return NULL;
336
337   if (!bfd_check_format (nbfd.get (), bfd_object))
338     return NULL;
339
340   /* Retrieve SPU name note and update BFD name.  */
341   spu_name = bfd_get_section_by_name (nbfd.get (), ".note.spu_name");
342   if (spu_name)
343     {
344       int sect_size = bfd_section_size (nbfd.get (), spu_name);
345       if (sect_size > 20)
346         {
347           char *buf = (char *)alloca (sect_size - 20 + 1);
348           bfd_get_section_contents (nbfd.get (), spu_name, buf, 20,
349                                     sect_size - 20);
350           buf[sect_size - 20] = '\0';
351
352           xfree ((char *)nbfd->filename);
353           nbfd->filename = xstrdup (buf);
354         }
355     }
356
357   return nbfd;
358 }
359
360 /* INFERIOR_FD is a file handle passed by the inferior to the
361    spu_run system call.  Assuming the SPE context was allocated
362    by the libspe library, try to retrieve the main SPE executable
363    file from its copy within the target process.  */
364 static void
365 spu_symbol_file_add_from_memory (int inferior_fd)
366 {
367   ULONGEST addr;
368
369   gdb_byte id[128];
370   char annex[32];
371   ULONGEST len;
372   enum target_xfer_status status;
373
374   /* Read object ID.  */
375   xsnprintf (annex, sizeof annex, "%d/object-id", inferior_fd);
376   status = spu_proc_xfer_spu (annex, id, NULL, 0, sizeof id, &len);
377   if (status != TARGET_XFER_OK || len >= sizeof id)
378     return;
379   id[len] = 0;
380   addr = strtoulst ((const char *) id, NULL, 16);
381   if (!addr)
382     return;
383
384   /* Open BFD representing SPE executable and read its symbols.  */
385   gdb_bfd_ref_ptr nbfd (spu_bfd_open (addr));
386   if (nbfd != NULL)
387     {
388       symbol_file_add_from_bfd (nbfd.get (), bfd_get_filename (nbfd),
389                                 SYMFILE_VERBOSE | SYMFILE_MAINLINE,
390                                 NULL, 0, NULL);
391     }
392 }
393
394
395 /* Override the post_startup_inferior routine to continue running
396    the inferior until the first spu_run system call.  */
397 static void
398 spu_child_post_startup_inferior (struct target_ops *self, ptid_t ptid)
399 {
400   int fd;
401   ULONGEST addr;
402
403   int tid = ptid_get_lwp (ptid);
404   if (tid == 0)
405     tid = ptid_get_pid (ptid);
406   
407   while (!parse_spufs_run (&fd, &addr))
408     {
409       ptrace (PT_SYSCALL, tid, (PTRACE_TYPE_ARG3) 0, 0);
410       waitpid (tid, NULL, __WALL | __WNOTHREAD);
411     }
412 }
413
414 /* Override the post_attach routine to try load the SPE executable
415    file image from its copy inside the target process.  */
416 static void
417 spu_child_post_attach (struct target_ops *self, int pid)
418 {
419   int fd;
420   ULONGEST addr;
421
422   /* Like child_post_startup_inferior, if we happened to attach to
423      the inferior while it wasn't currently in spu_run, continue 
424      running it until we get back there.  */
425   while (!parse_spufs_run (&fd, &addr))
426     {
427       ptrace (PT_SYSCALL, pid, (PTRACE_TYPE_ARG3) 0, 0);
428       waitpid (pid, NULL, __WALL | __WNOTHREAD);
429     }
430
431   /* If the user has not provided an executable file, try to extract
432      the image from inside the target process.  */
433   if (!get_exec_file (0))
434     spu_symbol_file_add_from_memory (fd);
435 }
436
437 /* Wait for child PTID to do something.  Return id of the child,
438    minus_one_ptid in case of error; store status into *OURSTATUS.  */
439 static ptid_t
440 spu_child_wait (struct target_ops *ops,
441                 ptid_t ptid, struct target_waitstatus *ourstatus, int options)
442 {
443   int save_errno;
444   int status;
445   pid_t pid;
446
447   do
448     {
449       set_sigint_trap ();       /* Causes SIGINT to be passed on to the
450                                    attached process.  */
451
452       pid = waitpid (ptid_get_pid (ptid), &status, 0);
453       if (pid == -1 && errno == ECHILD)
454         /* Try again with __WCLONE to check cloned processes.  */
455         pid = waitpid (ptid_get_pid (ptid), &status, __WCLONE);
456
457       save_errno = errno;
458
459       /* Make sure we don't report an event for the exit of the
460          original program, if we've detached from it.  */
461       if (pid != -1 && !WIFSTOPPED (status)
462           && pid != ptid_get_pid (inferior_ptid))
463         {
464           pid = -1;
465           save_errno = EINTR;
466         }
467
468       clear_sigint_trap ();
469     }
470   while (pid == -1 && save_errno == EINTR);
471
472   if (pid == -1)
473     {
474       warning (_("Child process unexpectedly missing: %s"),
475                safe_strerror (save_errno));
476
477       /* Claim it exited with unknown signal.  */
478       ourstatus->kind = TARGET_WAITKIND_SIGNALLED;
479       ourstatus->value.sig = GDB_SIGNAL_UNKNOWN;
480       return inferior_ptid;
481     }
482
483   store_waitstatus (ourstatus, status);
484   return pid_to_ptid (pid);
485 }
486
487 /* Override the fetch_inferior_register routine.  */
488 static void
489 spu_fetch_inferior_registers (struct target_ops *ops,
490                               struct regcache *regcache, int regno)
491 {
492   int fd;
493   ULONGEST addr;
494
495   /* We must be stopped on a spu_run system call.  */
496   if (!parse_spufs_run (&fd, &addr))
497     return;
498
499   /* The ID register holds the spufs file handle.  */
500   if (regno == -1 || regno == SPU_ID_REGNUM)
501     {
502       struct gdbarch *gdbarch = get_regcache_arch (regcache);
503       enum bfd_endian byte_order = gdbarch_byte_order (gdbarch);
504       gdb_byte buf[4];
505       store_unsigned_integer (buf, 4, byte_order, fd);
506       regcache_raw_supply (regcache, SPU_ID_REGNUM, buf);
507     }
508
509   /* The NPC register is found at ADDR.  */
510   if (regno == -1 || regno == SPU_PC_REGNUM)
511     {
512       gdb_byte buf[4];
513       if (fetch_ppc_memory (addr, buf, 4) == 0)
514         regcache_raw_supply (regcache, SPU_PC_REGNUM, buf);
515     }
516
517   /* The GPRs are found in the "regs" spufs file.  */
518   if (regno == -1 || (regno >= 0 && regno < SPU_NUM_GPRS))
519     {
520       gdb_byte buf[16 * SPU_NUM_GPRS];
521       char annex[32];
522       int i;
523       ULONGEST len;
524
525       xsnprintf (annex, sizeof annex, "%d/regs", fd);
526       if ((spu_proc_xfer_spu (annex, buf, NULL, 0, sizeof buf, &len)
527            == TARGET_XFER_OK)
528           && len == sizeof buf)
529         for (i = 0; i < SPU_NUM_GPRS; i++)
530           regcache_raw_supply (regcache, i, buf + i*16);
531     }
532 }
533
534 /* Override the store_inferior_register routine.  */
535 static void
536 spu_store_inferior_registers (struct target_ops *ops,
537                               struct regcache *regcache, int regno)
538 {
539   int fd;
540   ULONGEST addr;
541
542   /* We must be stopped on a spu_run system call.  */
543   if (!parse_spufs_run (&fd, &addr))
544     return;
545
546   /* The NPC register is found at ADDR.  */
547   if (regno == -1 || regno == SPU_PC_REGNUM)
548     {
549       gdb_byte buf[4];
550       regcache_raw_collect (regcache, SPU_PC_REGNUM, buf);
551       store_ppc_memory (addr, buf, 4);
552     }
553
554   /* The GPRs are found in the "regs" spufs file.  */
555   if (regno == -1 || (regno >= 0 && regno < SPU_NUM_GPRS))
556     {
557       gdb_byte buf[16 * SPU_NUM_GPRS];
558       char annex[32];
559       int i;
560       ULONGEST len;
561
562       for (i = 0; i < SPU_NUM_GPRS; i++)
563         regcache_raw_collect (regcache, i, buf + i*16);
564
565       xsnprintf (annex, sizeof annex, "%d/regs", fd);
566       spu_proc_xfer_spu (annex, NULL, buf, 0, sizeof buf, &len);
567     }
568 }
569
570 /* Override the to_xfer_partial routine.  */
571 static enum target_xfer_status
572 spu_xfer_partial (struct target_ops *ops,
573                   enum target_object object, const char *annex,
574                   gdb_byte *readbuf, const gdb_byte *writebuf,
575                   ULONGEST offset, ULONGEST len, ULONGEST *xfered_len)
576 {
577   if (object == TARGET_OBJECT_SPU)
578     return spu_proc_xfer_spu (annex, readbuf, writebuf, offset, len,
579                               xfered_len);
580
581   if (object == TARGET_OBJECT_MEMORY)
582     {
583       int fd;
584       ULONGEST addr;
585       char mem_annex[32], lslr_annex[32];
586       gdb_byte buf[32];
587       ULONGEST lslr;
588       enum target_xfer_status ret;
589
590       /* We must be stopped on a spu_run system call.  */
591       if (!parse_spufs_run (&fd, &addr))
592         return TARGET_XFER_EOF;
593
594       /* Use the "mem" spufs file to access SPU local store.  */
595       xsnprintf (mem_annex, sizeof mem_annex, "%d/mem", fd);
596       ret = spu_proc_xfer_spu (mem_annex, readbuf, writebuf, offset, len,
597                                xfered_len);
598       if (ret == TARGET_XFER_OK)
599         return ret;
600
601       /* SPU local store access wraps the address around at the
602          local store limit.  We emulate this here.  To avoid needing
603          an extra access to retrieve the LSLR, we only do that after
604          trying the original address first, and getting end-of-file.  */
605       xsnprintf (lslr_annex, sizeof lslr_annex, "%d/lslr", fd);
606       memset (buf, 0, sizeof buf);
607       if (spu_proc_xfer_spu (lslr_annex, buf, NULL, 0, sizeof buf, xfered_len)
608           != TARGET_XFER_OK)
609         return ret;
610
611       lslr = strtoulst ((const char *) buf, NULL, 16);
612       return spu_proc_xfer_spu (mem_annex, readbuf, writebuf,
613                                 offset & lslr, len, xfered_len);
614     }
615
616   return TARGET_XFER_E_IO;
617 }
618
619 /* Override the to_can_use_hw_breakpoint routine.  */
620 static int
621 spu_can_use_hw_breakpoint (struct target_ops *self,
622                            enum bptype type, int cnt, int othertype)
623 {
624   return 0;
625 }
626
627 /* -Wmissing-prototypes */
628 extern initialize_file_ftype _initialize_spu_nat;
629
630 /* Initialize SPU native target.  */
631 void 
632 _initialize_spu_nat (void)
633 {
634   /* Generic ptrace methods.  */
635   struct target_ops *t;
636   t = inf_ptrace_target ();
637
638   /* Add SPU methods.  */
639   t->to_post_attach = spu_child_post_attach;  
640   t->to_post_startup_inferior = spu_child_post_startup_inferior;
641   t->to_wait = spu_child_wait;
642   t->to_fetch_registers = spu_fetch_inferior_registers;
643   t->to_store_registers = spu_store_inferior_registers;
644   t->to_xfer_partial = spu_xfer_partial;
645   t->to_can_use_hw_breakpoint = spu_can_use_hw_breakpoint;
646
647   /* Register SPU target.  */
648   add_target (t);
649 }