Linux/ptrace: don't convert ptids when asking inf-ptrace layer to resume LWP
[external/binutils.git] / gdb / inf-ptrace.c
1 /* Low-level child interface to ptrace.
2
3    Copyright (C) 1988-2015 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 "command.h"
22 #include "inferior.h"
23 #include "inflow.h"
24 #include "terminal.h"
25 #include "gdbcore.h"
26 #include "regcache.h"
27 #include "gdb_ptrace.h"
28 #include "gdb_wait.h"
29 #include <signal.h>
30
31 #include "inf-ptrace.h"
32 #include "inf-child.h"
33 #include "gdbthread.h"
34
35 \f
36
37 #ifdef PT_GET_PROCESS_STATE
38
39 /* Target hook for follow_fork.  On entry and at return inferior_ptid is
40    the ptid of the followed inferior.  */
41
42 static int
43 inf_ptrace_follow_fork (struct target_ops *ops, int follow_child,
44                         int detach_fork)
45 {
46   if (!follow_child)
47     {
48       struct thread_info *tp = inferior_thread ();
49       pid_t child_pid = ptid_get_pid (tp->pending_follow.value.related_pid);
50
51       /* Breakpoints have already been detached from the child by
52          infrun.c.  */
53
54       if (ptrace (PT_DETACH, child_pid, (PTRACE_TYPE_ARG3)1, 0) == -1)
55         perror_with_name (("ptrace"));
56     }
57
58   return 0;
59 }
60
61 #endif /* PT_GET_PROCESS_STATE */
62 \f
63
64 /* Prepare to be traced.  */
65
66 static void
67 inf_ptrace_me (void)
68 {
69   /* "Trace me, Dr. Memory!"  */
70   ptrace (PT_TRACE_ME, 0, (PTRACE_TYPE_ARG3)0, 0);
71 }
72
73 /* Start a new inferior Unix child process.  EXEC_FILE is the file to
74    run, ALLARGS is a string containing the arguments to the program.
75    ENV is the environment vector to pass.  If FROM_TTY is non-zero, be
76    chatty about it.  */
77
78 static void
79 inf_ptrace_create_inferior (struct target_ops *ops,
80                             char *exec_file, char *allargs, char **env,
81                             int from_tty)
82 {
83   int pid;
84
85   /* Do not change either targets above or the same target if already present.
86      The reason is the target stack is shared across multiple inferiors.  */
87   int ops_already_pushed = target_is_pushed (ops);
88   struct cleanup *back_to = make_cleanup (null_cleanup, NULL);
89
90   if (! ops_already_pushed)
91     {
92       /* Clear possible core file with its process_stratum.  */
93       push_target (ops);
94       make_cleanup_unpush_target (ops);
95     }
96
97   pid = fork_inferior (exec_file, allargs, env, inf_ptrace_me, NULL,
98                        NULL, NULL, NULL);
99
100   discard_cleanups (back_to);
101
102   startup_inferior (START_INFERIOR_TRAPS_EXPECTED);
103
104   /* On some targets, there must be some explicit actions taken after
105      the inferior has been started up.  */
106   target_post_startup_inferior (pid_to_ptid (pid));
107 }
108
109 #ifdef PT_GET_PROCESS_STATE
110
111 static void
112 inf_ptrace_post_startup_inferior (struct target_ops *self, ptid_t pid)
113 {
114   ptrace_event_t pe;
115
116   /* Set the initial event mask.  */
117   memset (&pe, 0, sizeof pe);
118   pe.pe_set_event |= PTRACE_FORK;
119   if (ptrace (PT_SET_EVENT_MASK, ptid_get_pid (pid),
120               (PTRACE_TYPE_ARG3)&pe, sizeof pe) == -1)
121     perror_with_name (("ptrace"));
122 }
123
124 #endif
125
126 /* Clean up a rotting corpse of an inferior after it died.  */
127
128 static void
129 inf_ptrace_mourn_inferior (struct target_ops *ops)
130 {
131   int status;
132
133   /* Wait just one more time to collect the inferior's exit status.
134      Do not check whether this succeeds though, since we may be
135      dealing with a process that we attached to.  Such a process will
136      only report its exit status to its original parent.  */
137   waitpid (ptid_get_pid (inferior_ptid), &status, 0);
138
139   inf_child_mourn_inferior (ops);
140 }
141
142 /* Attach to the process specified by ARGS.  If FROM_TTY is non-zero,
143    be chatty about it.  */
144
145 static void
146 inf_ptrace_attach (struct target_ops *ops, const char *args, int from_tty)
147 {
148   char *exec_file;
149   pid_t pid;
150   struct inferior *inf;
151
152   /* Do not change either targets above or the same target if already present.
153      The reason is the target stack is shared across multiple inferiors.  */
154   int ops_already_pushed = target_is_pushed (ops);
155   struct cleanup *back_to = make_cleanup (null_cleanup, NULL);
156
157   pid = parse_pid_to_attach (args);
158
159   if (pid == getpid ())         /* Trying to masturbate?  */
160     error (_("I refuse to debug myself!"));
161
162   if (! ops_already_pushed)
163     {
164       /* target_pid_to_str already uses the target.  Also clear possible core
165          file with its process_stratum.  */
166       push_target (ops);
167       make_cleanup_unpush_target (ops);
168     }
169
170   if (from_tty)
171     {
172       exec_file = get_exec_file (0);
173
174       if (exec_file)
175         printf_unfiltered (_("Attaching to program: %s, %s\n"), exec_file,
176                            target_pid_to_str (pid_to_ptid (pid)));
177       else
178         printf_unfiltered (_("Attaching to %s\n"),
179                            target_pid_to_str (pid_to_ptid (pid)));
180
181       gdb_flush (gdb_stdout);
182     }
183
184 #ifdef PT_ATTACH
185   errno = 0;
186   ptrace (PT_ATTACH, pid, (PTRACE_TYPE_ARG3)0, 0);
187   if (errno != 0)
188     perror_with_name (("ptrace"));
189 #else
190   error (_("This system does not support attaching to a process"));
191 #endif
192
193   inf = current_inferior ();
194   inferior_appeared (inf, pid);
195   inf->attach_flag = 1;
196   inferior_ptid = pid_to_ptid (pid);
197
198   /* Always add a main thread.  If some target extends the ptrace
199      target, it should decorate the ptid later with more info.  */
200   add_thread_silent (inferior_ptid);
201
202   discard_cleanups (back_to);
203 }
204
205 #ifdef PT_GET_PROCESS_STATE
206
207 static void
208 inf_ptrace_post_attach (struct target_ops *self, int pid)
209 {
210   ptrace_event_t pe;
211
212   /* Set the initial event mask.  */
213   memset (&pe, 0, sizeof pe);
214   pe.pe_set_event |= PTRACE_FORK;
215   if (ptrace (PT_SET_EVENT_MASK, pid,
216               (PTRACE_TYPE_ARG3)&pe, sizeof pe) == -1)
217     perror_with_name (("ptrace"));
218 }
219
220 #endif
221
222 /* Detach from the inferior, optionally passing it the signal
223    specified by ARGS.  If FROM_TTY is non-zero, be chatty about it.  */
224
225 static void
226 inf_ptrace_detach (struct target_ops *ops, const char *args, int from_tty)
227 {
228   pid_t pid = ptid_get_pid (inferior_ptid);
229   int sig = 0;
230
231   if (from_tty)
232     {
233       char *exec_file = get_exec_file (0);
234       if (exec_file == 0)
235         exec_file = "";
236       printf_unfiltered (_("Detaching from program: %s, %s\n"), exec_file,
237                          target_pid_to_str (pid_to_ptid (pid)));
238       gdb_flush (gdb_stdout);
239     }
240   if (args)
241     sig = atoi (args);
242
243 #ifdef PT_DETACH
244   /* We'd better not have left any breakpoints in the program or it'll
245      die when it hits one.  Also note that this may only work if we
246      previously attached to the inferior.  It *might* work if we
247      started the process ourselves.  */
248   errno = 0;
249   ptrace (PT_DETACH, pid, (PTRACE_TYPE_ARG3)1, sig);
250   if (errno != 0)
251     perror_with_name (("ptrace"));
252 #else
253   error (_("This system does not support detaching from a process"));
254 #endif
255
256   inferior_ptid = null_ptid;
257   detach_inferior (pid);
258
259   inf_child_maybe_unpush_target (ops);
260 }
261
262 /* Kill the inferior.  */
263
264 static void
265 inf_ptrace_kill (struct target_ops *ops)
266 {
267   pid_t pid = ptid_get_pid (inferior_ptid);
268   int status;
269
270   if (pid == 0)
271     return;
272
273   ptrace (PT_KILL, pid, (PTRACE_TYPE_ARG3)0, 0);
274   waitpid (pid, &status, 0);
275
276   target_mourn_inferior ();
277 }
278
279 /* Stop the inferior.  */
280
281 static void
282 inf_ptrace_stop (struct target_ops *self, ptid_t ptid)
283 {
284   /* Send a SIGINT to the process group.  This acts just like the user
285      typed a ^C on the controlling terminal.  Note that using a
286      negative process number in kill() is a System V-ism.  The proper
287      BSD interface is killpg().  However, all modern BSDs support the
288      System V interface too.  */
289   kill (-inferior_process_group (), SIGINT);
290 }
291
292 /* Return which PID to pass to ptrace in order to observe/control the
293    tracee identified by PTID.  */
294
295 static pid_t
296 get_ptrace_pid (ptid_t ptid)
297 {
298   pid_t pid;
299
300   /* If we have an LWPID to work with, use it.  Otherwise, we're
301      dealing with a non-threaded program/target.  */
302   pid = ptid_get_lwp (ptid);
303   if (pid == 0)
304     pid = ptid_get_pid (ptid);
305   return pid;
306 }
307
308 /* Resume execution of thread PTID, or all threads if PTID is -1.  If
309    STEP is nonzero, single-step it.  If SIGNAL is nonzero, give it
310    that signal.  */
311
312 static void
313 inf_ptrace_resume (struct target_ops *ops,
314                    ptid_t ptid, int step, enum gdb_signal signal)
315 {
316   pid_t pid;
317
318   int request;
319
320   if (ptid_equal (minus_one_ptid, ptid))
321     /* Resume all threads.  Traditionally ptrace() only supports
322        single-threaded processes, so simply resume the inferior.  */
323     pid = get_ptrace_pid (inferior_ptid);
324   else
325     pid = get_ptrace_pid (ptid);
326
327   if (catch_syscall_enabled () > 0)
328     request = PT_SYSCALL;
329   else
330     request = PT_CONTINUE;
331
332   if (step)
333     {
334       /* If this system does not support PT_STEP, a higher level
335          function will have called single_step() to transmute the step
336          request into a continue request (by setting breakpoints on
337          all possible successor instructions), so we don't have to
338          worry about that here.  */
339       request = PT_STEP;
340     }
341
342   /* An address of (PTRACE_TYPE_ARG3)1 tells ptrace to continue from
343      where it was.  If GDB wanted it to start some other way, we have
344      already written a new program counter value to the child.  */
345   errno = 0;
346   ptrace (request, pid, (PTRACE_TYPE_ARG3)1, gdb_signal_to_host (signal));
347   if (errno != 0)
348     perror_with_name (("ptrace"));
349 }
350
351 /* Wait for the child specified by PTID to do something.  Return the
352    process ID of the child, or MINUS_ONE_PTID in case of error; store
353    the status in *OURSTATUS.  */
354
355 static ptid_t
356 inf_ptrace_wait (struct target_ops *ops,
357                  ptid_t ptid, struct target_waitstatus *ourstatus, int options)
358 {
359   pid_t pid;
360   int status, save_errno;
361
362   do
363     {
364       set_sigint_trap ();
365
366       do
367         {
368           pid = waitpid (ptid_get_pid (ptid), &status, 0);
369           save_errno = errno;
370         }
371       while (pid == -1 && errno == EINTR);
372
373       clear_sigint_trap ();
374
375       if (pid == -1)
376         {
377           fprintf_unfiltered (gdb_stderr,
378                               _("Child process unexpectedly missing: %s.\n"),
379                               safe_strerror (save_errno));
380
381           /* Claim it exited with unknown signal.  */
382           ourstatus->kind = TARGET_WAITKIND_SIGNALLED;
383           ourstatus->value.sig = GDB_SIGNAL_UNKNOWN;
384           return inferior_ptid;
385         }
386
387       /* Ignore terminated detached child processes.  */
388       if (!WIFSTOPPED (status) && pid != ptid_get_pid (inferior_ptid))
389         pid = -1;
390     }
391   while (pid == -1);
392
393 #ifdef PT_GET_PROCESS_STATE
394   if (WIFSTOPPED (status))
395     {
396       ptrace_state_t pe;
397       pid_t fpid;
398
399       if (ptrace (PT_GET_PROCESS_STATE, pid,
400                   (PTRACE_TYPE_ARG3)&pe, sizeof pe) == -1)
401         perror_with_name (("ptrace"));
402
403       switch (pe.pe_report_event)
404         {
405         case PTRACE_FORK:
406           ourstatus->kind = TARGET_WAITKIND_FORKED;
407           ourstatus->value.related_pid = pid_to_ptid (pe.pe_other_pid);
408
409           /* Make sure the other end of the fork is stopped too.  */
410           fpid = waitpid (pe.pe_other_pid, &status, 0);
411           if (fpid == -1)
412             perror_with_name (("waitpid"));
413
414           if (ptrace (PT_GET_PROCESS_STATE, fpid,
415                       (PTRACE_TYPE_ARG3)&pe, sizeof pe) == -1)
416             perror_with_name (("ptrace"));
417
418           gdb_assert (pe.pe_report_event == PTRACE_FORK);
419           gdb_assert (pe.pe_other_pid == pid);
420           if (fpid == ptid_get_pid (inferior_ptid))
421             {
422               ourstatus->value.related_pid = pid_to_ptid (pe.pe_other_pid);
423               return pid_to_ptid (fpid);
424             }
425
426           return pid_to_ptid (pid);
427         }
428     }
429 #endif
430
431   store_waitstatus (ourstatus, status);
432   return pid_to_ptid (pid);
433 }
434
435 /* Implement the to_xfer_partial target_ops method.  */
436
437 static enum target_xfer_status
438 inf_ptrace_xfer_partial (struct target_ops *ops, enum target_object object,
439                          const char *annex, gdb_byte *readbuf,
440                          const gdb_byte *writebuf,
441                          ULONGEST offset, ULONGEST len, ULONGEST *xfered_len)
442 {
443   pid_t pid = ptid_get_pid (inferior_ptid);
444
445   switch (object)
446     {
447     case TARGET_OBJECT_MEMORY:
448 #ifdef PT_IO
449       /* OpenBSD 3.1, NetBSD 1.6 and FreeBSD 5.0 have a new PT_IO
450          request that promises to be much more efficient in reading
451          and writing data in the traced process's address space.  */
452       {
453         struct ptrace_io_desc piod;
454
455         /* NOTE: We assume that there are no distinct address spaces
456            for instruction and data.  However, on OpenBSD 3.9 and
457            later, PIOD_WRITE_D doesn't allow changing memory that's
458            mapped read-only.  Since most code segments will be
459            read-only, using PIOD_WRITE_D will prevent us from
460            inserting breakpoints, so we use PIOD_WRITE_I instead.  */
461         piod.piod_op = writebuf ? PIOD_WRITE_I : PIOD_READ_D;
462         piod.piod_addr = writebuf ? (void *) writebuf : readbuf;
463         piod.piod_offs = (void *) (long) offset;
464         piod.piod_len = len;
465
466         errno = 0;
467         if (ptrace (PT_IO, pid, (caddr_t)&piod, 0) == 0)
468           {
469             /* Return the actual number of bytes read or written.  */
470             *xfered_len = piod.piod_len;
471             return (piod.piod_len == 0) ? TARGET_XFER_EOF : TARGET_XFER_OK;
472           }
473         /* If the PT_IO request is somehow not supported, fallback on
474            using PT_WRITE_D/PT_READ_D.  Otherwise we will return zero
475            to indicate failure.  */
476         if (errno != EINVAL)
477           return TARGET_XFER_EOF;
478       }
479 #endif
480       {
481         union
482         {
483           PTRACE_TYPE_RET word;
484           gdb_byte byte[sizeof (PTRACE_TYPE_RET)];
485         } buffer;
486         ULONGEST rounded_offset;
487         ULONGEST partial_len;
488
489         /* Round the start offset down to the next long word
490            boundary.  */
491         rounded_offset = offset & -(ULONGEST) sizeof (PTRACE_TYPE_RET);
492
493         /* Since ptrace will transfer a single word starting at that
494            rounded_offset the partial_len needs to be adjusted down to
495            that (remember this function only does a single transfer).
496            Should the required length be even less, adjust it down
497            again.  */
498         partial_len = (rounded_offset + sizeof (PTRACE_TYPE_RET)) - offset;
499         if (partial_len > len)
500           partial_len = len;
501
502         if (writebuf)
503           {
504             /* If OFFSET:PARTIAL_LEN is smaller than
505                ROUNDED_OFFSET:WORDSIZE then a read/modify write will
506                be needed.  Read in the entire word.  */
507             if (rounded_offset < offset
508                 || (offset + partial_len
509                     < rounded_offset + sizeof (PTRACE_TYPE_RET)))
510               /* Need part of initial word -- fetch it.  */
511               buffer.word = ptrace (PT_READ_I, pid,
512                                     (PTRACE_TYPE_ARG3)(uintptr_t)
513                                     rounded_offset, 0);
514
515             /* Copy data to be written over corresponding part of
516                buffer.  */
517             memcpy (buffer.byte + (offset - rounded_offset),
518                     writebuf, partial_len);
519
520             errno = 0;
521             ptrace (PT_WRITE_D, pid,
522                     (PTRACE_TYPE_ARG3)(uintptr_t)rounded_offset,
523                     buffer.word);
524             if (errno)
525               {
526                 /* Using the appropriate one (I or D) is necessary for
527                    Gould NP1, at least.  */
528                 errno = 0;
529                 ptrace (PT_WRITE_I, pid,
530                         (PTRACE_TYPE_ARG3)(uintptr_t)rounded_offset,
531                         buffer.word);
532                 if (errno)
533                   return TARGET_XFER_EOF;
534               }
535           }
536
537         if (readbuf)
538           {
539             errno = 0;
540             buffer.word = ptrace (PT_READ_I, pid,
541                                   (PTRACE_TYPE_ARG3)(uintptr_t)rounded_offset,
542                                   0);
543             if (errno)
544               return TARGET_XFER_EOF;
545             /* Copy appropriate bytes out of the buffer.  */
546             memcpy (readbuf, buffer.byte + (offset - rounded_offset),
547                     partial_len);
548           }
549
550         *xfered_len = partial_len;
551         return TARGET_XFER_OK;
552       }
553
554     case TARGET_OBJECT_UNWIND_TABLE:
555       return TARGET_XFER_E_IO;
556
557     case TARGET_OBJECT_AUXV:
558 #if defined (PT_IO) && defined (PIOD_READ_AUXV)
559       /* OpenBSD 4.5 has a new PIOD_READ_AUXV operation for the PT_IO
560          request that allows us to read the auxilliary vector.  Other
561          BSD's may follow if they feel the need to support PIE.  */
562       {
563         struct ptrace_io_desc piod;
564
565         if (writebuf)
566           return TARGET_XFER_E_IO;
567         piod.piod_op = PIOD_READ_AUXV;
568         piod.piod_addr = readbuf;
569         piod.piod_offs = (void *) (long) offset;
570         piod.piod_len = len;
571
572         errno = 0;
573         if (ptrace (PT_IO, pid, (caddr_t)&piod, 0) == 0)
574           {
575             /* Return the actual number of bytes read or written.  */
576             *xfered_len = piod.piod_len;
577             return (piod.piod_len == 0) ? TARGET_XFER_EOF : TARGET_XFER_OK;
578           }
579       }
580 #endif
581       return TARGET_XFER_E_IO;
582
583     case TARGET_OBJECT_WCOOKIE:
584       return TARGET_XFER_E_IO;
585
586     default:
587       return TARGET_XFER_E_IO;
588     }
589 }
590
591 /* Return non-zero if the thread specified by PTID is alive.  */
592
593 static int
594 inf_ptrace_thread_alive (struct target_ops *ops, ptid_t ptid)
595 {
596   /* ??? Is kill the right way to do this?  */
597   return (kill (ptid_get_pid (ptid), 0) != -1);
598 }
599
600 /* Print status information about what we're accessing.  */
601
602 static void
603 inf_ptrace_files_info (struct target_ops *ignore)
604 {
605   struct inferior *inf = current_inferior ();
606
607   printf_filtered (_("\tUsing the running image of %s %s.\n"),
608                    inf->attach_flag ? "attached" : "child",
609                    target_pid_to_str (inferior_ptid));
610 }
611
612 static char *
613 inf_ptrace_pid_to_str (struct target_ops *ops, ptid_t ptid)
614 {
615   return normal_pid_to_str (ptid);
616 }
617
618 #if defined (PT_IO) && defined (PIOD_READ_AUXV)
619
620 /* Read one auxv entry from *READPTR, not reading locations >= ENDPTR.
621    Return 0 if *READPTR is already at the end of the buffer.
622    Return -1 if there is insufficient buffer for a whole entry.
623    Return 1 if an entry was read into *TYPEP and *VALP.  */
624
625 static int
626 inf_ptrace_auxv_parse (struct target_ops *ops, gdb_byte **readptr,
627                        gdb_byte *endptr, CORE_ADDR *typep, CORE_ADDR *valp)
628 {
629   struct type *int_type = builtin_type (target_gdbarch ())->builtin_int;
630   struct type *ptr_type = builtin_type (target_gdbarch ())->builtin_data_ptr;
631   const int sizeof_auxv_type = TYPE_LENGTH (int_type);
632   const int sizeof_auxv_val = TYPE_LENGTH (ptr_type);
633   enum bfd_endian byte_order = gdbarch_byte_order (target_gdbarch ());
634   gdb_byte *ptr = *readptr;
635
636   if (endptr == ptr)
637     return 0;
638
639   if (endptr - ptr < 2 * sizeof_auxv_val)
640     return -1;
641
642   *typep = extract_unsigned_integer (ptr, sizeof_auxv_type, byte_order);
643   ptr += sizeof_auxv_val;       /* Alignment.  */
644   *valp = extract_unsigned_integer (ptr, sizeof_auxv_val, byte_order);
645   ptr += sizeof_auxv_val;
646
647   *readptr = ptr;
648   return 1;
649 }
650
651 #endif
652
653 /* Create a prototype ptrace target.  The client can override it with
654    local methods.  */
655
656 struct target_ops *
657 inf_ptrace_target (void)
658 {
659   struct target_ops *t = inf_child_target ();
660
661   t->to_attach = inf_ptrace_attach;
662   t->to_detach = inf_ptrace_detach;
663   t->to_resume = inf_ptrace_resume;
664   t->to_wait = inf_ptrace_wait;
665   t->to_files_info = inf_ptrace_files_info;
666   t->to_kill = inf_ptrace_kill;
667   t->to_create_inferior = inf_ptrace_create_inferior;
668 #ifdef PT_GET_PROCESS_STATE
669   t->to_follow_fork = inf_ptrace_follow_fork;
670   t->to_post_startup_inferior = inf_ptrace_post_startup_inferior;
671   t->to_post_attach = inf_ptrace_post_attach;
672 #endif
673   t->to_mourn_inferior = inf_ptrace_mourn_inferior;
674   t->to_thread_alive = inf_ptrace_thread_alive;
675   t->to_pid_to_str = inf_ptrace_pid_to_str;
676   t->to_stop = inf_ptrace_stop;
677   t->to_xfer_partial = inf_ptrace_xfer_partial;
678 #if defined (PT_IO) && defined (PIOD_READ_AUXV)
679   t->to_auxv_parse = inf_ptrace_auxv_parse;
680 #endif
681
682   return t;
683 }
684 \f
685
686 /* Pointer to a function that returns the offset within the user area
687    where a particular register is stored.  */
688 static CORE_ADDR (*inf_ptrace_register_u_offset)(struct gdbarch *, int, int);
689
690 /* Fetch register REGNUM from the inferior.  */
691
692 static void
693 inf_ptrace_fetch_register (struct regcache *regcache, int regnum)
694 {
695   struct gdbarch *gdbarch = get_regcache_arch (regcache);
696   CORE_ADDR addr;
697   size_t size;
698   PTRACE_TYPE_RET *buf;
699   int pid, i;
700
701   /* This isn't really an address, but ptrace thinks of it as one.  */
702   addr = inf_ptrace_register_u_offset (gdbarch, regnum, 0);
703   if (addr == (CORE_ADDR)-1
704       || gdbarch_cannot_fetch_register (gdbarch, regnum))
705     {
706       regcache_raw_supply (regcache, regnum, NULL);
707       return;
708     }
709
710   /* Cater for systems like GNU/Linux, that implement threads as
711      separate processes.  */
712   pid = ptid_get_lwp (inferior_ptid);
713   if (pid == 0)
714     pid = ptid_get_pid (inferior_ptid);
715
716   size = register_size (gdbarch, regnum);
717   gdb_assert ((size % sizeof (PTRACE_TYPE_RET)) == 0);
718   buf = alloca (size);
719
720   /* Read the register contents from the inferior a chunk at a time.  */
721   for (i = 0; i < size / sizeof (PTRACE_TYPE_RET); i++)
722     {
723       errno = 0;
724       buf[i] = ptrace (PT_READ_U, pid, (PTRACE_TYPE_ARG3)(uintptr_t)addr, 0);
725       if (errno != 0)
726         error (_("Couldn't read register %s (#%d): %s."),
727                gdbarch_register_name (gdbarch, regnum),
728                regnum, safe_strerror (errno));
729
730       addr += sizeof (PTRACE_TYPE_RET);
731     }
732   regcache_raw_supply (regcache, regnum, buf);
733 }
734
735 /* Fetch register REGNUM from the inferior.  If REGNUM is -1, do this
736    for all registers.  */
737
738 static void
739 inf_ptrace_fetch_registers (struct target_ops *ops,
740                             struct regcache *regcache, int regnum)
741 {
742   if (regnum == -1)
743     for (regnum = 0;
744          regnum < gdbarch_num_regs (get_regcache_arch (regcache));
745          regnum++)
746       inf_ptrace_fetch_register (regcache, regnum);
747   else
748     inf_ptrace_fetch_register (regcache, regnum);
749 }
750
751 /* Store register REGNUM into the inferior.  */
752
753 static void
754 inf_ptrace_store_register (const struct regcache *regcache, int regnum)
755 {
756   struct gdbarch *gdbarch = get_regcache_arch (regcache);
757   CORE_ADDR addr;
758   size_t size;
759   PTRACE_TYPE_RET *buf;
760   int pid, i;
761
762   /* This isn't really an address, but ptrace thinks of it as one.  */
763   addr = inf_ptrace_register_u_offset (gdbarch, regnum, 1);
764   if (addr == (CORE_ADDR)-1 
765       || gdbarch_cannot_store_register (gdbarch, regnum))
766     return;
767
768   /* Cater for systems like GNU/Linux, that implement threads as
769      separate processes.  */
770   pid = ptid_get_lwp (inferior_ptid);
771   if (pid == 0)
772     pid = ptid_get_pid (inferior_ptid);
773
774   size = register_size (gdbarch, regnum);
775   gdb_assert ((size % sizeof (PTRACE_TYPE_RET)) == 0);
776   buf = alloca (size);
777
778   /* Write the register contents into the inferior a chunk at a time.  */
779   regcache_raw_collect (regcache, regnum, buf);
780   for (i = 0; i < size / sizeof (PTRACE_TYPE_RET); i++)
781     {
782       errno = 0;
783       ptrace (PT_WRITE_U, pid, (PTRACE_TYPE_ARG3)(uintptr_t)addr, buf[i]);
784       if (errno != 0)
785         error (_("Couldn't write register %s (#%d): %s."),
786                gdbarch_register_name (gdbarch, regnum),
787                regnum, safe_strerror (errno));
788
789       addr += sizeof (PTRACE_TYPE_RET);
790     }
791 }
792
793 /* Store register REGNUM back into the inferior.  If REGNUM is -1, do
794    this for all registers.  */
795
796 static void
797 inf_ptrace_store_registers (struct target_ops *ops,
798                             struct regcache *regcache, int regnum)
799 {
800   if (regnum == -1)
801     for (regnum = 0;
802          regnum < gdbarch_num_regs (get_regcache_arch (regcache));
803          regnum++)
804       inf_ptrace_store_register (regcache, regnum);
805   else
806     inf_ptrace_store_register (regcache, regnum);
807 }
808
809 /* Create a "traditional" ptrace target.  REGISTER_U_OFFSET should be
810    a function returning the offset within the user area where a
811    particular register is stored.  */
812
813 struct target_ops *
814 inf_ptrace_trad_target (CORE_ADDR (*register_u_offset)
815                                         (struct gdbarch *, int, int))
816 {
817   struct target_ops *t = inf_ptrace_target();
818
819   gdb_assert (register_u_offset);
820   inf_ptrace_register_u_offset = register_u_offset;
821   t->to_fetch_registers = inf_ptrace_fetch_registers;
822   t->to_store_registers = inf_ptrace_store_registers;
823
824   return t;
825 }