xref: /netbsd-src/external/gpl3/gdb.old/dist/gdb/inf-ptrace.c (revision 8b657b0747480f8989760d71343d6dd33f8d4cf9)
1 /* Low-level child interface to ptrace.
2 
3    Copyright (C) 1988-2023 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 "terminal.h"
24 #include "gdbcore.h"
25 #include "regcache.h"
26 #include "nat/gdb_ptrace.h"
27 #include "gdbsupport/gdb_wait.h"
28 #include <signal.h>
29 
30 #include "inf-ptrace.h"
31 #include "inf-child.h"
32 #include "gdbthread.h"
33 #include "nat/fork-inferior.h"
34 #include "utils.h"
35 #include "gdbarch.h"
36 
37 
38 
39 static PTRACE_TYPE_RET
40 gdb_ptrace (PTRACE_TYPE_ARG1 request, ptid_t ptid, PTRACE_TYPE_ARG3 addr,
41 	    PTRACE_TYPE_ARG4 data)
42 {
43 #ifdef __NetBSD__
44   /*
45    * On NetBSD the data field of PT_STEP contains the thread
46    * to be stepped; all other threads are continued if this value is > 0
47    */
48   if (request == PT_STEP)
49      data = ptid.lwp ();
50   return ptrace (request, ptid.pid (), addr, data);
51 #else
52   pid_t pid = get_ptrace_pid (ptid);
53   return ptrace (request, pid, addr, data);
54 #endif
55 }
56 
57 /* The event pipe registered as a waitable file in the event loop.  */
58 event_pipe inf_ptrace_target::m_event_pipe;
59 
60 inf_ptrace_target::~inf_ptrace_target ()
61 {}
62 
63 
64 
65 /* Prepare to be traced.  */
66 
67 static void
68 inf_ptrace_me (void)
69 {
70   /* "Trace me, Dr. Memory!"  */
71   if (ptrace (PT_TRACE_ME, 0, (PTRACE_TYPE_ARG3) 0, 0) < 0)
72     trace_start_error_with_name ("ptrace");
73 }
74 
75 /* Start a new inferior Unix child process.  EXEC_FILE is the file to
76    run, ALLARGS is a string containing the arguments to the program.
77    ENV is the environment vector to pass.  If FROM_TTY is non-zero, be
78    chatty about it.  */
79 
80 void
81 inf_ptrace_target::create_inferior (const char *exec_file,
82 				    const std::string &allargs,
83 				    char **env, int from_tty)
84 {
85   inferior *inf = current_inferior ();
86 
87   /* Do not change either targets above or the same target if already present.
88      The reason is the target stack is shared across multiple inferiors.  */
89   int ops_already_pushed = inf->target_is_pushed (this);
90 
91   target_unpush_up unpusher;
92   if (! ops_already_pushed)
93     {
94       /* Clear possible core file with its process_stratum.  */
95       inf->push_target (this);
96       unpusher.reset (this);
97     }
98 
99   pid_t pid = fork_inferior (exec_file, allargs, env, inf_ptrace_me, NULL,
100 			     NULL, NULL, NULL);
101 
102   ptid_t ptid (pid);
103   /* We have something that executes now.  We'll be running through
104      the shell at this point (if startup-with-shell is true), but the
105      pid shouldn't change.  */
106   thread_info *thr = add_thread_silent (this, ptid);
107   switch_to_thread (thr);
108 
109   unpusher.release ();
110 
111   gdb_startup_inferior (pid, START_INFERIOR_TRAPS_EXPECTED);
112 
113   /* On some targets, there must be some explicit actions taken after
114      the inferior has been started up.  */
115   post_startup_inferior (ptid);
116 }
117 
118 /* Clean up a rotting corpse of an inferior after it died.  */
119 
120 void
121 inf_ptrace_target::mourn_inferior ()
122 {
123   int status;
124 
125   /* Wait just one more time to collect the inferior's exit status.
126      Do not check whether this succeeds though, since we may be
127      dealing with a process that we attached to.  Such a process will
128      only report its exit status to its original parent.  */
129   waitpid (inferior_ptid.pid (), &status, 0);
130 
131   inf_child_target::mourn_inferior ();
132 }
133 
134 /* Attach to the process specified by ARGS.  If FROM_TTY is non-zero,
135    be chatty about it.  */
136 
137 void
138 inf_ptrace_target::attach (const char *args, int from_tty)
139 {
140   inferior *inf = current_inferior ();
141 
142   /* Do not change either targets above or the same target if already present.
143      The reason is the target stack is shared across multiple inferiors.  */
144   int ops_already_pushed = inf->target_is_pushed (this);
145 
146   pid_t pid = parse_pid_to_attach (args);
147 
148   if (pid == getpid ())		/* Trying to masturbate?  */
149     error (_("I refuse to debug myself!"));
150 
151   target_unpush_up unpusher;
152   if (! ops_already_pushed)
153     {
154       /* target_pid_to_str already uses the target.  Also clear possible core
155 	 file with its process_stratum.  */
156       inf->push_target (this);
157       unpusher.reset (this);
158     }
159 
160   target_announce_attach (from_tty, pid);
161 
162 #ifdef PT_ATTACH
163   errno = 0;
164   ptrace (PT_ATTACH, pid, (PTRACE_TYPE_ARG3)0, 0);
165   if (errno != 0)
166     perror_with_name (("ptrace"));
167 #else
168   error (_("This system does not support attaching to a process"));
169 #endif
170 
171   inferior_appeared (inf, pid);
172   inf->attach_flag = true;
173 
174   /* Always add a main thread.  If some target extends the ptrace
175      target, it should decorate the ptid later with more info.  */
176   thread_info *thr = add_thread_silent (this, ptid_t (pid));
177   switch_to_thread (thr);
178 
179   /* Don't consider the thread stopped until we've processed its
180      initial SIGSTOP stop.  */
181   set_executing (this, thr->ptid, true);
182 
183   unpusher.release ();
184 }
185 
186 /* Detach from the inferior.  If FROM_TTY is non-zero, be chatty about it.  */
187 
188 void
189 inf_ptrace_target::detach (inferior *inf, int from_tty)
190 {
191   pid_t pid = inferior_ptid.pid ();
192 
193   target_announce_detach (from_tty);
194 
195 #ifdef PT_DETACH
196   /* We'd better not have left any breakpoints in the program or it'll
197      die when it hits one.  Also note that this may only work if we
198      previously attached to the inferior.  It *might* work if we
199      started the process ourselves.  */
200   errno = 0;
201   ptrace (PT_DETACH, pid, (PTRACE_TYPE_ARG3)1, 0);
202   if (errno != 0)
203     perror_with_name (("ptrace"));
204 #else
205   error (_("This system does not support detaching from a process"));
206 #endif
207 
208   detach_success (inf);
209 }
210 
211 /* See inf-ptrace.h.  */
212 
213 void
214 inf_ptrace_target::detach_success (inferior *inf)
215 {
216   switch_to_no_thread ();
217   detach_inferior (inf);
218 
219   maybe_unpush_target ();
220 }
221 
222 /* Kill the inferior.  */
223 
224 void
225 inf_ptrace_target::kill ()
226 {
227   pid_t pid = inferior_ptid.pid ();
228   int status;
229 
230   if (pid == 0)
231     return;
232 
233   ptrace (PT_KILL, pid, (PTRACE_TYPE_ARG3)0, 0);
234   waitpid (pid, &status, 0);
235 
236   target_mourn_inferior (inferior_ptid);
237 }
238 
239 #ifndef __NetBSD__
240 
241 /* See inf-ptrace.h.  */
242 
243 pid_t
244 get_ptrace_pid (ptid_t ptid)
245 {
246   pid_t pid;
247 
248   /* If we have an LWPID to work with, use it.  Otherwise, we're
249      dealing with a non-threaded program/target.  */
250   pid = ptid.lwp ();
251   if (pid == 0)
252     pid = ptid.pid ();
253   return pid;
254 }
255 #endif
256 
257 /* Resume execution of thread PTID, or all threads if PTID is -1.  If
258    STEP is nonzero, single-step it.  If SIGNAL is nonzero, give it
259    that signal.  */
260 
261 void
262 inf_ptrace_target::resume (ptid_t ptid, int step, enum gdb_signal signal)
263 {
264   PTRACE_TYPE_ARG1 request;
265 
266   if (minus_one_ptid == ptid)
267     /* Resume all threads.  Traditionally ptrace() only supports
268        single-threaded processes, so simply resume the inferior.  */
269     ptid = ptid_t (inferior_ptid.pid ());
270 
271   if (catch_syscall_enabled () > 0)
272     request = PT_SYSCALL;
273   else
274     request = PT_CONTINUE;
275 
276   if (step)
277     {
278       /* If this system does not support PT_STEP, a higher level
279 	 function will have called the appropriate functions to transmute the
280 	 step request into a continue request (by setting breakpoints on
281 	 all possible successor instructions), so we don't have to
282 	 worry about that here.  */
283       request = PT_STEP;
284     }
285 
286   /* An address of (PTRACE_TYPE_ARG3)1 tells ptrace to continue from
287      where it was.  If GDB wanted it to start some other way, we have
288      already written a new program counter value to the child.  */
289   errno = 0;
290   gdb_ptrace (request, ptid, (PTRACE_TYPE_ARG3)1, gdb_signal_to_host (signal));
291   if (errno != 0)
292     perror_with_name (("ptrace"));
293 }
294 
295 /* Wait for the child specified by PTID to do something.  Return the
296    process ID of the child, or MINUS_ONE_PTID in case of error; store
297    the status in *OURSTATUS.  */
298 
299 ptid_t
300 inf_ptrace_target::wait (ptid_t ptid, struct target_waitstatus *ourstatus,
301 			 target_wait_flags target_options)
302 {
303   pid_t pid;
304   int options, status, save_errno;
305 
306   options = 0;
307   if (target_options & TARGET_WNOHANG)
308     options |= WNOHANG;
309 
310   do
311     {
312       set_sigint_trap ();
313 
314       do
315 	{
316 	  pid = waitpid (ptid.pid (), &status, options);
317 	  save_errno = errno;
318 	}
319       while (pid == -1 && errno == EINTR);
320 
321       clear_sigint_trap ();
322 
323       if (pid == 0)
324 	{
325 	  gdb_assert (target_options & TARGET_WNOHANG);
326 	  ourstatus->set_ignore ();
327 	  return minus_one_ptid;
328 	}
329 
330       if (pid == -1)
331 	{
332 	  /* In async mode the SIGCHLD might have raced and triggered
333 	     a check for an event that had already been reported.  If
334 	     the event was the exit of the only remaining child,
335 	     waitpid() will fail with ECHILD.  */
336 	  if (ptid == minus_one_ptid && save_errno == ECHILD)
337 	    {
338 	      ourstatus->set_no_resumed ();
339 	      return minus_one_ptid;
340 	    }
341 
342 	  gdb_printf (gdb_stderr,
343 		      _("Child process unexpectedly missing: %s.\n"),
344 		      safe_strerror (save_errno));
345 
346 	  ourstatus->set_ignore ();
347 	  return minus_one_ptid;
348 	}
349 
350       /* Ignore terminated detached child processes.  */
351       if (!WIFSTOPPED (status) && find_inferior_pid (this, pid) == nullptr)
352 	pid = -1;
353     }
354   while (pid == -1);
355 
356   *ourstatus = host_status_to_waitstatus (status);
357 
358   return ptid_t (pid);
359 }
360 
361 /* Transfer data via ptrace into process PID's memory from WRITEBUF, or
362    from process PID's memory into READBUF.  Start at target address ADDR
363    and transfer up to LEN bytes.  Exactly one of READBUF and WRITEBUF must
364    be non-null.  Return the number of transferred bytes.  */
365 
366 static ULONGEST
367 inf_ptrace_peek_poke (ptid_t ptid, gdb_byte *readbuf,
368 		      const gdb_byte *writebuf,
369 		      ULONGEST addr, ULONGEST len)
370 {
371   ULONGEST n;
372   unsigned int chunk;
373 
374   /* We transfer aligned words.  Thus align ADDR down to a word
375      boundary and determine how many bytes to skip at the
376      beginning.  */
377   ULONGEST skip = addr & (sizeof (PTRACE_TYPE_RET) - 1);
378   addr -= skip;
379 
380   for (n = 0;
381        n < len;
382        n += chunk, addr += sizeof (PTRACE_TYPE_RET), skip = 0)
383     {
384       /* Restrict to a chunk that fits in the current word.  */
385       chunk = std::min (sizeof (PTRACE_TYPE_RET) - skip, len - n);
386 
387       /* Use a union for type punning.  */
388       union
389       {
390 	PTRACE_TYPE_RET word;
391 	gdb_byte byte[sizeof (PTRACE_TYPE_RET)];
392       } buf;
393 
394       /* Read the word, also when doing a partial word write.  */
395       if (readbuf != NULL || chunk < sizeof (PTRACE_TYPE_RET))
396 	{
397 	  errno = 0;
398 	  buf.word = gdb_ptrace (PT_READ_I, ptid,
399 				 (PTRACE_TYPE_ARG3)(uintptr_t) addr, 0);
400 	  if (errno != 0)
401 	    break;
402 	  if (readbuf != NULL)
403 	    memcpy (readbuf + n, buf.byte + skip, chunk);
404 	}
405       if (writebuf != NULL)
406 	{
407 	  memcpy (buf.byte + skip, writebuf + n, chunk);
408 	  errno = 0;
409 	  gdb_ptrace (PT_WRITE_D, ptid, (PTRACE_TYPE_ARG3)(uintptr_t) addr,
410 		  buf.word);
411 	  if (errno != 0)
412 	    {
413 	      /* Using the appropriate one (I or D) is necessary for
414 		 Gould NP1, at least.  */
415 	      errno = 0;
416 	      gdb_ptrace (PT_WRITE_I, ptid, (PTRACE_TYPE_ARG3)(uintptr_t) addr,
417 			  buf.word);
418 	      if (errno != 0)
419 		break;
420 	    }
421 	}
422     }
423 
424   return n;
425 }
426 
427 /* Implement the to_xfer_partial target_ops method.  */
428 
429 enum target_xfer_status
430 inf_ptrace_target::xfer_partial (enum target_object object,
431 				 const char *annex, gdb_byte *readbuf,
432 				 const gdb_byte *writebuf,
433 				 ULONGEST offset, ULONGEST len, ULONGEST *xfered_len)
434 {
435   ptid_t ptid = inferior_ptid;
436 
437   switch (object)
438     {
439     case TARGET_OBJECT_MEMORY:
440 #ifdef PT_IO
441       /* OpenBSD 3.1, NetBSD 1.6 and FreeBSD 5.0 have a new PT_IO
442 	 request that promises to be much more efficient in reading
443 	 and writing data in the traced process's address space.  */
444       {
445 	struct ptrace_io_desc piod;
446 
447 	/* NOTE: We assume that there are no distinct address spaces
448 	   for instruction and data.  However, on OpenBSD 3.9 and
449 	   later, PIOD_WRITE_D doesn't allow changing memory that's
450 	   mapped read-only.  Since most code segments will be
451 	   read-only, using PIOD_WRITE_D will prevent us from
452 	   inserting breakpoints, so we use PIOD_WRITE_I instead.  */
453 	piod.piod_op = writebuf ? PIOD_WRITE_I : PIOD_READ_D;
454 	piod.piod_addr = writebuf ? (void *) writebuf : readbuf;
455 	piod.piod_offs = (void *) (long) offset;
456 	piod.piod_len = len;
457 
458 	errno = 0;
459 	if (gdb_ptrace (PT_IO, ptid, (caddr_t)&piod, 0) == 0)
460 	  {
461 	    /* Return the actual number of bytes read or written.  */
462 	    *xfered_len = piod.piod_len;
463 	    return (piod.piod_len == 0) ? TARGET_XFER_EOF : TARGET_XFER_OK;
464 	  }
465 	/* If the PT_IO request is somehow not supported, fallback on
466 	   using PT_WRITE_D/PT_READ_D.  Otherwise we will return zero
467 	   to indicate failure.  */
468 	if (errno != EINVAL)
469 	  return TARGET_XFER_EOF;
470       }
471 #endif
472       *xfered_len = inf_ptrace_peek_poke (ptid, readbuf, writebuf,
473 					  offset, len);
474       return *xfered_len != 0 ? TARGET_XFER_OK : TARGET_XFER_EOF;
475 
476     case TARGET_OBJECT_UNWIND_TABLE:
477       return TARGET_XFER_E_IO;
478 
479     case TARGET_OBJECT_AUXV:
480 #if defined (PT_IO) && defined (PIOD_READ_AUXV)
481       /* OpenBSD 4.5 has a new PIOD_READ_AUXV operation for the PT_IO
482 	 request that allows us to read the auxilliary vector.  Other
483 	 BSD's may follow if they feel the need to support PIE.  */
484       {
485 	struct ptrace_io_desc piod;
486 
487 	if (writebuf)
488 	  return TARGET_XFER_E_IO;
489 	piod.piod_op = PIOD_READ_AUXV;
490 	piod.piod_addr = readbuf;
491 	piod.piod_offs = (void *) (long) offset;
492 	piod.piod_len = len;
493 
494 	errno = 0;
495 	if (gdb_ptrace (PT_IO, ptid, (caddr_t)&piod, 0) == 0)
496 	  {
497 	    /* Return the actual number of bytes read or written.  */
498 	    *xfered_len = piod.piod_len;
499 	    return (piod.piod_len == 0) ? TARGET_XFER_EOF : TARGET_XFER_OK;
500 	  }
501       }
502 #endif
503       return TARGET_XFER_E_IO;
504 
505     case TARGET_OBJECT_WCOOKIE:
506       return TARGET_XFER_E_IO;
507 
508     default:
509       return TARGET_XFER_E_IO;
510     }
511 }
512 
513 /* Return non-zero if the thread specified by PTID is alive.  */
514 
515 bool
516 inf_ptrace_target::thread_alive (ptid_t ptid)
517 {
518   /* ??? Is kill the right way to do this?  */
519   return (::kill (ptid.pid (), 0) != -1);
520 }
521 
522 /* Print status information about what we're accessing.  */
523 
524 void
525 inf_ptrace_target::files_info ()
526 {
527   struct inferior *inf = current_inferior ();
528 
529   gdb_printf (_("\tUsing the running image of %s %s.\n"),
530 	      inf->attach_flag ? "attached" : "child",
531 	      target_pid_to_str (inferior_ptid).c_str ());
532 }
533 
534 std::string
535 inf_ptrace_target::pid_to_str (ptid_t ptid)
536 {
537   return normal_pid_to_str (ptid);
538 }
539 
540 /* Implement the "close" target method.  */
541 
542 void
543 inf_ptrace_target::close ()
544 {
545   /* Unregister from the event loop.  */
546   if (is_async_p ())
547     async (false);
548 
549   inf_child_target::close ();
550 }
551