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