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