1PTRACE(2)                  Linux Programmer's Manual                 PTRACE(2)


6       ptrace - process trace


9       #include <sys/ptrace.h>
11       long ptrace(enum __ptrace_request request, pid_t pid,
12                   void *addr, void *data);


15       The  ptrace()  system  call  provides a means by which one process (the
16       "tracer") may observe and control the execution of another process (the
17       "tracee"),  and  examine  and change the tracee's memory and registers.
18       It is primarily used to implement breakpoint debugging and system  call
19       tracing.
21       A tracee first needs to be attached to the tracer.  Attachment and sub‐
22       sequent commands are per thread:  in  a  multithreaded  process,  every
23       thread  can  be  individually  attached  to  a  (potentially different)
24       tracer, or  left  not  attached  and  thus  not  debugged.   Therefore,
25       "tracee" always means "(one) thread", never "a (possibly multithreaded)
26       process".  Ptrace commands are always sent to a specific tracee using a
27       call of the form
29           ptrace(PTRACE_foo, pid, ...)
31       where pid is the thread ID of the corresponding Linux thread.
33       (Note that in this page, a "multithreaded process" means a thread group
34       consisting of threads created using the clone(2) CLONE_THREAD flag.)
36       A process can initiate a  trace  by  calling  fork(2)  and  having  the
37       resulting  child  do  a  PTRACE_TRACEME,  followed  (typically)  by  an
38       execve(2).  Alternatively, one process  may  commence  tracing  another
39       process using PTRACE_ATTACH or PTRACE_SEIZE.
41       While  being  traced, the tracee will stop each time a signal is deliv‐
42       ered, even if the signal is being ignored.  (An exception  is  SIGKILL,
43       which  has  its usual effect.)  The tracer will be notified at its next
44       call to waitpid(2) (or one of the related "wait"  system  calls);  that
45       call  will  return a status value containing information that indicates
46       the cause of the stop in the tracee.  While the tracee is stopped,  the
47       tracer  can  use  various  ptrace  requests  to  inspect and modify the
48       tracee.  The tracer then causes  the  tracee  to  continue,  optionally
49       ignoring  the  delivered  signal (or even delivering a different signal
50       instead).
52       If the PTRACE_O_TRACEEXEC option is not in effect, all successful calls
53       to  execve(2)  by the traced process will cause it to be sent a SIGTRAP
54       signal, giving the parent a chance to gain control before the new  pro‐
55       gram begins execution.
57       When  the  tracer  is finished tracing, it can cause the tracee to con‐
58       tinue executing in a normal, untraced mode via PTRACE_DETACH.
60       The value of request determines the action to be performed:
63              Indicate that this process is to be traced  by  its  parent.   A
64              process probably shouldn't make this request if its parent isn't
65              expecting to trace it.  (pid, addr, and data are ignored.)
67              The PTRACE_TRACEME request is  used  only  by  the  tracee;  the
68              remaining  requests are used only by the tracer.  In the follow‐
69              ing requests, pid specifies the thread ID of the  tracee  to  be
70              acted  on.  For requests other than PTRACE_ATTACH, PTRACE_SEIZE,
71              PTRACE_INTERRUPT, and PTRACE_KILL, the tracee must be stopped.
74              Read a word at the address addr in the tracee's memory,  return‐
75              ing the word as the result of the ptrace() call.  Linux does not
76              have separate  text  and  data  address  spaces,  so  these  two
77              requests  are  currently  equivalent.  (data is ignored; but see
78              NOTES.)
81              Read a word at offset addr in  the  tracee's  USER  area,  which
82              holds the registers and other information about the process (see
83              <sys/user.h>).  The word  is  returned  as  the  result  of  the
84              ptrace()  call.   Typically,  the  offset  must be word-aligned,
85              though this might vary by architecture.  See  NOTES.   (data  is
86              ignored; but see NOTES.)
89              Copy  the  word data to the address addr in the tracee's memory.
90              As for PTRACE_PEEKTEXT and PTRACE_PEEKDATA, these  two  requests
91              are currently equivalent.
94              Copy the word data to offset addr in the tracee's USER area.  As
95              for PTRACE_PEEKUSER, the offset must typically be  word-aligned.
96              In order to maintain the integrity of the kernel, some modifica‐
97              tions to the USER area are disallowed.
100              Copy the tracee's general-purpose or  floating-point  registers,
101              respectively,   to   the   address  data  in  the  tracer.   See
102              <sys/user.h> for information on the format of this data.   (addr
103              is  ignored.)   Note that SPARC systems have the meaning of data
104              and addr reversed; that is, data is ignored  and  the  registers
105              are copied to the address addr.  PTRACE_GETREGS and PTRACE_GETF‐
106              PREGS are not present on all architectures.
108       PTRACE_GETREGSET (since Linux 2.6.34)
109              Read the tracee's registers.  addr specifies,  in  an  architec‐
110              ture-dependent way, the type of registers to be read.  NT_PRSTA‐
111              TUS (with numerical value 1) usually results in reading of  gen‐
112              eral-purpose  registers.  If the CPU has, for example, floating-
113              point and/or vector registers, they can be retrieved by  setting
114              addr  to  the  corresponding  NT_foo constant.  data points to a
115              struct iovec, which describes the destination buffer's  location
116              and  length.  On return, the kernel modifies iov.len to indicate
117              the actual number of bytes returned.
120              Modify the tracee's general-purpose or floating-point registers,
121              respectively,  from  the  address  data  in  the tracer.  As for
122              PTRACE_POKEUSER, some general-purpose register modifications may
123              be disallowed.  (addr is ignored.)  Note that SPARC systems have
124              the meaning of data and addr reversed; that is, data is  ignored
125              and   the   registers   are   copied   from  the  address  addr.
126              PTRACE_SETREGS and  PTRACE_SETFPREGS  are  not  present  on  all
127              architectures.
129       PTRACE_SETREGSET (since Linux 2.6.34)
130              Modify  the tracee's registers.  The meaning of addr and data is
131              analogous to PTRACE_GETREGSET.
133       PTRACE_GETSIGINFO (since Linux 2.3.99-pre6)
134              Retrieve information about the  signal  that  caused  the  stop.
135              Copy a siginfo_t structure (see sigaction(2)) from the tracee to
136              the address data in the tracer.  (addr is ignored.)
138       PTRACE_SETSIGINFO (since Linux 2.3.99-pre6)
139              Set signal information: copy  a  siginfo_t  structure  from  the
140              address data in the tracer to the tracee.  This will affect only
141              signals that would normally be delivered to the tracee and  were
142              caught  by the tracer.  It may be difficult to tell these normal
143              signals from synthetic signals  generated  by  ptrace()  itself.
144              (addr is ignored.)
146       PTRACE_PEEKSIGINFO (since Linux 3.10)
147              Retrieve  siginfo_t  structures  without removing signals from a
148              queue.  addr points to a ptrace_peeksiginfo_args structure  that
149              specifies  the  ordinal  position  from which copying of signals
150              should start, and the number  of  signals  to  copy.   siginfo_t
151              structures  are  copied into the buffer pointed to by data.  The
152              return value contains the number of copied signals  (zero  indi‐
153              cates  that  there  is  no signal corresponding to the specified
154              ordinal position).  Within the returned siginfo structures,  the
155              si_code field includes information (__SI_CHLD, __SI_FAULT, etc.)
156              that are not otherwise exposed to user space.
158           struct ptrace_peeksiginfo_args {
159               u64 off;    /* Ordinal position in queue at which
160                              to start copying signals */
161               u32 flags;  /* PTRACE_PEEKSIGINFO_SHARED or 0 */
162               s32 nr;     /* Number of signals to copy */
163           };
165              Currently, there is only  one  flag,  PTRACE_PEEKSIGINFO_SHARED,
166              for dumping signals from the process-wide signal queue.  If this
167              flag is not set, signals are read from the per-thread  queue  of
168              the specified thread.
170       PTRACE_GETSIGMASK (since Linux 3.11)
171              Place a copy of the mask of blocked signals (see sigprocmask(2))
172              in the buffer pointed to by data, which should be a pointer to a
173              buffer of type sigset_t.  The addr argument contains the size of
174              the buffer pointed to by data (i.e., sizeof(sigset_t)).
176       PTRACE_SETSIGMASK (since Linux 3.11)
177              Change the mask of blocked signals (see sigprocmask(2))  to  the
178              value  specified  in the buffer pointed to by data, which should
179              be a pointer to a buffer of type sigset_t.   The  addr  argument
180              contains  the  size  of  the  buffer  pointed  to by data (i.e.,
181              sizeof(sigset_t)).
183       PTRACE_SETOPTIONS (since Linux 2.4.6; see BUGS for caveats)
184              Set ptrace options from  data.   (addr  is  ignored.)   data  is
185              interpreted as a bit mask of options, which are specified by the
186              following flags:
188              PTRACE_O_EXITKILL (since Linux 3.8)
189                     Send a SIGKILL signal to the tracee if the tracer  exits.
190                     This  option  is  useful  for ptrace jailers that want to
191                     ensure that tracees can never escape  the  tracer's  con‐
192                     trol.
194              PTRACE_O_TRACECLONE (since Linux 2.5.46)
195                     Stop  the  tracee  at the next clone(2) and automatically
196                     start tracing the newly cloned process, which will  start
197                     with  a SIGSTOP, or PTRACE_EVENT_STOP if PTRACE_SEIZE was
198                     used.  A waitpid(2) by the tracer will  return  a  status
199                     value such that
201                       status>>8 == (SIGTRAP | (PTRACE_EVENT_CLONE<<8))
203                     The  PID  of  the  new  process  can  be  retrieved  with
204                     PTRACE_GETEVENTMSG.
206                     This option may not catch clone(2) calls  in  all  cases.
207                     If  the  tracee calls clone(2) with the CLONE_VFORK flag,
208                     PTRACE_EVENT_VFORK   will   be   delivered   instead   if
209                     PTRACE_O_TRACEVFORK is set; otherwise if the tracee calls
210                     clone(2)  with  the   exit   signal   set   to   SIGCHLD,
211                     PTRACE_EVENT_FORK will be delivered if PTRACE_O_TRACEFORK
212                     is set.
214              PTRACE_O_TRACEEXEC (since Linux 2.5.46)
215                     Stop the tracee at the next execve(2).  A  waitpid(2)  by
216                     the tracer will return a status value such that
218                       status>>8 == (SIGTRAP | (PTRACE_EVENT_EXEC<<8))
220                     If  the  execing thread is not a thread group leader, the
221                     thread ID is reset to thread  group  leader's  ID  before
222                     this  stop.  Since Linux 3.0, the former thread ID can be
223                     retrieved with PTRACE_GETEVENTMSG.
225              PTRACE_O_TRACEEXIT (since Linux 2.5.60)
226                     Stop the tracee at exit.  A waitpid(2) by the tracer will
227                     return a status value such that
229                       status>>8 == (SIGTRAP | (PTRACE_EVENT_EXIT<<8))
231                     The   tracee's   exit   status   can  be  retrieved  with
232                     PTRACE_GETEVENTMSG.
234                     The tracee is stopped early  during  process  exit,  when
235                     registers are still available, allowing the tracer to see
236                     where the exit occurred, whereas the normal exit  notifi‐
237                     cation  is  done  after  the process is finished exiting.
238                     Even though context is available, the tracer cannot  pre‐
239                     vent the exit from happening at this point.
241              PTRACE_O_TRACEFORK (since Linux 2.5.46)
242                     Stop  the  tracee  at  the next fork(2) and automatically
243                     start tracing the newly forked process, which will  start
244                     with  a SIGSTOP, or PTRACE_EVENT_STOP if PTRACE_SEIZE was
245                     used.  A waitpid(2) by the tracer will  return  a  status
246                     value such that
248                       status>>8 == (SIGTRAP | (PTRACE_EVENT_FORK<<8))
250                     The  PID  of  the  new  process  can  be  retrieved  with
251                     PTRACE_GETEVENTMSG.
253              PTRACE_O_TRACESYSGOOD (since Linux 2.4.6)
254                     When delivering system call traps, set bit 7 in the  sig‐
255                     nal  number  (i.e., deliver SIGTRAP|0x80).  This makes it
256                     easy for the tracer  to  distinguish  normal  traps  from
257                     those  caused  by  a system call.  (PTRACE_O_TRACESYSGOOD
258                     may not work on all architectures.)
260              PTRACE_O_TRACEVFORK (since Linux 2.5.46)
261                     Stop the tracee at the next  vfork(2)  and  automatically
262                     start tracing the newly vforked process, which will start
263                     with a SIGSTOP, or PTRACE_EVENT_STOP if PTRACE_SEIZE  was
264                     used.   A  waitpid(2)  by the tracer will return a status
265                     value such that
267                       status>>8 == (SIGTRAP | (PTRACE_EVENT_VFORK<<8))
269                     The  PID  of  the  new  process  can  be  retrieved  with
270                     PTRACE_GETEVENTMSG.
272              PTRACE_O_TRACEVFORKDONE (since Linux 2.5.60)
273                     Stop  the  tracee at the completion of the next vfork(2).
274                     A waitpid(2) by the tracer will  return  a  status  value
275                     such that
277                       status>>8 == (SIGTRAP | (PTRACE_EVENT_VFORK_DONE<<8))
279                     The  PID  of  the new process can (since Linux 2.6.18) be
280                     retrieved with PTRACE_GETEVENTMSG.
282              PTRACE_O_TRACESECCOMP (since Linux 3.5)
283                     Stop the tracee when a seccomp(2) SECCOMP_RET_TRACE  rule
284                     is  triggered.   A waitpid(2) by the tracer will return a
285                     status value such that
287                       status>>8 == (SIGTRAP | (PTRACE_EVENT_SECCOMP<<8))
289                     While this triggers a PTRACE_EVENT stop, it is similar to
290                     a  syscall-enter-stop.   For  details,  see  the  note on
291                     PTRACE_EVENT_SECCOMP below.  The  seccomp  event  message
292                     data  (from  the  SECCOMP_RET_DATA portion of the seccomp
293                     filter rule) can be retrieved with PTRACE_GETEVENTMSG.
295              PTRACE_O_SUSPEND_SECCOMP (since Linux 4.3)
296                     Suspend the tracee's seccomp protections.   This  applies
297                     regardless  of  mode, and can be used when the tracee has
298                     not yet installed seccomp filters.  That is, a valid  use
299                     case  is to suspend a tracee's seccomp protections before
300                     they are installed by the tracee, let the tracee  install
301                     the  filters,  and  then clear this flag when the filters
302                     should be resumed.  Setting this option requires that the
303                     tracer  have  the  CAP_SYS_ADMIN capability, not have any
304                     seccomp protections installed, and not have PTRACE_O_SUS‐
305                     PEND_SECCOMP set on itself.
307       PTRACE_GETEVENTMSG (since Linux 2.5.46)
308              Retrieve  a message (as an unsigned long) about the ptrace event
309              that just happened, placing  it  at  the  address  data  in  the
310              tracer.   For  PTRACE_EVENT_EXIT, this is the tracee's exit sta‐
311              tus.       For      PTRACE_EVENT_FORK,       PTRACE_EVENT_VFORK,
312              PTRACE_EVENT_VFORK_DONE, and PTRACE_EVENT_CLONE, this is the PID
313              of the new process.  For PTRACE_EVENT_SECCOMP, this is the  sec‐
314              comp(2)  filter's SECCOMP_RET_DATA associated with the triggered
315              rule.  (addr is ignored.)
317       PTRACE_CONT
318              Restart the stopped tracee process.  If data is nonzero,  it  is
319              interpreted  as  the  number  of a signal to be delivered to the
320              tracee; otherwise, no signal is delivered.  Thus,  for  example,
321              the  tracer  can  control whether a signal sent to the tracee is
322              delivered or not.  (addr is ignored.)
325              Restart the stopped tracee as for PTRACE_CONT, but  arrange  for
326              the  tracee  to  be  stopped at the next entry to or exit from a
327              system call, or after execution of a single instruction, respec‐
328              tively.   (The  tracee  will  also,  as  usual,  be stopped upon
329              receipt of a signal.)  From the tracer's perspective, the tracee
330              will  appear  to have been stopped by receipt of a SIGTRAP.  So,
331              for PTRACE_SYSCALL, for example, the  idea  is  to  inspect  the
332              arguments  to the system call at the first stop, then do another
333              PTRACE_SYSCALL and inspect the return value of the  system  call
334              at  the  second  stop.   The  data  argument  is  treated as for
335              PTRACE_CONT.  (addr is ignored.)
337       PTRACE_SYSEMU, PTRACE_SYSEMU_SINGLESTEP (since Linux 2.6.14)
338              For PTRACE_SYSEMU, continue and stop on entry to the next system
339              call,  which  will  not  be  executed.  See the documentation on
340              syscall-stops below.  For PTRACE_SYSEMU_SINGLESTEP, do the  same
341              but  also singlestep if not a system call.  This call is used by
342              programs like User Mode Linux  that  want  to  emulate  all  the
343              tracee's  system  calls.   The  data  argument is treated as for
344              PTRACE_CONT.  The addr argument is ignored.  These requests  are
345              currently supported only on x86.
347       PTRACE_LISTEN (since Linux 3.4)
348              Restart  the stopped tracee, but prevent it from executing.  The
349              resulting state of the tracee is similar to a process which  has
350              been  stopped  by a SIGSTOP (or other stopping signal).  See the
351              "group-stop" subsection for additional information.  PTRACE_LIS‐
352              TEN works only on tracees attached by PTRACE_SEIZE.
354       PTRACE_KILL
355              Send  the  tracee a SIGKILL to terminate it.  (addr and data are
356              ignored.)
358              This operation is deprecated; do not use it!   Instead,  send  a
359              SIGKILL  directly  using kill(2) or tgkill(2).  The problem with
360              PTRACE_KILL is that it requires the  tracee  to  be  in  signal-
361              delivery-stop,  otherwise  it  may  not work (i.e., may complete
362              successfully but won't kill the tracee).  By contrast, sending a
363              SIGKILL directly has no such limitation.
365       PTRACE_INTERRUPT (since Linux 3.4)
366              Stop  a  tracee.  If the tracee is running or sleeping in kernel
367              space and PTRACE_SYSCALL is in effect, the system call is inter‐
368              rupted and syscall-exit-stop is reported.  (The interrupted sys‐
369              tem call is restarted when the tracee  is  restarted.)   If  the
370              tracee  was  already  stopped  by a signal and PTRACE_LISTEN was
371              sent to it, the tracee stops with PTRACE_EVENT_STOP  and  WSTOP‐
372              SIG(status)  returns  the stop signal.  If any other ptrace-stop
373              is generated at the same time (for example, if a signal is  sent
374              to  the tracee), this ptrace-stop happens.  If none of the above
375              applies (for example, if the tracee is running in  user  space),
376              it  stops  with  PTRACE_EVENT_STOP with WSTOPSIG(status) == SIG‐
377              TRAP.   PTRACE_INTERRUPT  only  works  on  tracees  attached  by
378              PTRACE_SEIZE.
381              Attach  to  the  process specified in pid, making it a tracee of
382              the calling process.  The tracee is sent a SIGSTOP, but will not
383              necessarily  have  stopped  by  the completion of this call; use
384              waitpid(2) to wait for the tracee to stop.  See  the  "Attaching
385              and detaching" subsection for additional information.  (addr and
386              data are ignored.)
388              Permission to perform a PTRACE_ATTACH is governed  by  a  ptrace
389              access mode PTRACE_MODE_ATTACH_REALCREDS check; see below.
391       PTRACE_SEIZE (since Linux 3.4)
392              Attach  to  the  process specified in pid, making it a tracee of
393              the calling process.  Unlike  PTRACE_ATTACH,  PTRACE_SEIZE  does
394              not   stop   the   process.    Group-stops   are   reported   as
395              PTRACE_EVENT_STOP and WSTOPSIG(status) returns the stop  signal.
396              Automatically  attached children stop with PTRACE_EVENT_STOP and
397              WSTOPSIG(status) returns SIGTRAP instead of having SIGSTOP  sig‐
398              nal delivered to them.  execve(2) does not deliver an extra SIG‐
399              TRAP.  Only a PTRACE_SEIZEd process can accept  PTRACE_INTERRUPT
400              and   PTRACE_LISTEN   commands.    The  "seized"  behavior  just
401              described  is  inherited  by  children  that  are  automatically
402              attached   using  PTRACE_O_TRACEFORK,  PTRACE_O_TRACEVFORK,  and
403              PTRACE_O_TRACECLONE.  addr must be zero.  data  contains  a  bit
404              mask of ptrace options to activate immediately.
406              Permission  to  perform  a  PTRACE_SEIZE is governed by a ptrace
407              access mode PTRACE_MODE_ATTACH_REALCREDS check; see below.
409       PTRACE_SECCOMP_GET_FILTER (since Linux 4.4)
410              This operation allows the tracer to dump  the  tracee's  classic
411              BPF filters.
413              addr  is  an  integer  specifying  the index of the filter to be
414              dumped.  The most recently installed filter has the index 0.  If
415              addr is greater than the number of installed filters, the opera‐
416              tion fails with the error ENOENT.
418              data is either a pointer to a struct sock_filter array  that  is
419              large enough to store the BPF program, or NULL if the program is
420              not to be stored.
422              Upon success, the return value is the number of instructions  in
423              the  BPF  program.  If data was NULL, then this return value can
424              be used to correctly size the struct sock_filter array passed in
425              a subsequent call.
427              This  operation  fails with the error EACCESS if the caller does
428              not have the CAP_SYS_ADMIN capability or if  the  caller  is  in
429              strict  or  filter  seccomp  mode.  If the filter referred to by
430              addr is not a classic BPF filter, the operation fails  with  the
431              error EMEDIUMTYPE.
433              This  operation  is  available if the kernel was configured with
435              options.
438              Restart  the stopped tracee as for PTRACE_CONT, but first detach
439              from it.  Under Linux, a tracee can  be  detached  in  this  way
440              regardless  of which method was used to initiate tracing.  (addr
441              is ignored.)
443       PTRACE_GET_THREAD_AREA (since Linux 2.6.0)
444              This operation performs a similar  task  to  get_thread_area(2).
445              It  reads the TLS entry in the GDT whose index is given in addr,
446              placing a copy of the entry into the struct user_desc pointed to
447              by data.  (By contrast with get_thread_area(2), the entry_number
448              of the struct user_desc is ignored.)
450       PTRACE_SET_THREAD_AREA (since Linux 2.6.0)
451              This operation performs a similar  task  to  set_thread_area(2).
452              It  sets  the TLS entry in the GDT whose index is given in addr,
453              assigning it the data supplied in the struct  user_desc  pointed
454              to   by   data.    (By  contrast  with  set_thread_area(2),  the
455              entry_number of the struct user_desc is ignored; in other words,
456              this  ptrace  operation  can't  be  used  to allocate a free TLS
457              entry.)
459   Death under ptrace
460       When a (possibly multithreaded) process receives a killing signal  (one
461       whose disposition is set to SIG_DFL and whose default action is to kill
462       the process), all threads exit.  Tracees report their  death  to  their
463       tracer(s).  Notification of this event is delivered via waitpid(2).
465       Note  that the killing signal will first cause signal-delivery-stop (on
466       one tracee only), and only after it is injected by the tracer (or after
467       it  was dispatched to a thread which isn't traced), will death from the
468       signal happen on all tracees within a multithreaded process.  (The term
469       "signal-delivery-stop" is explained below.)
471       SIGKILL does not generate signal-delivery-stop and therefore the tracer
472       can't suppress it.  SIGKILL kills even within  system  calls  (syscall-
473       exit-stop  is not generated prior to death by SIGKILL).  The net effect
474       is that SIGKILL always kills the process (all  its  threads),  even  if
475       some threads of the process are ptraced.
477       When  the  tracee  calls  _exit(2), it reports its death to its tracer.
478       Other threads are not affected.
480       When any thread executes exit_group(2),  every  tracee  in  its  thread
481       group reports its death to its tracer.
483       If  the  PTRACE_O_TRACEEXIT option is on, PTRACE_EVENT_EXIT will happen
484       before actual death.  This applies to exits via exit(2), exit_group(2),
485       and signal deaths (except SIGKILL, depending on the kernel version; see
486       BUGS below), and when threads are torn down on execve(2)  in  a  multi‐
487       threaded process.
489       The  tracer cannot assume that the ptrace-stopped tracee exists.  There
490       are many scenarios when the tracee  may  die  while  stopped  (such  as
491       SIGKILL).   Therefore,  the  tracer must be prepared to handle an ESRCH
492       error on any  ptrace  operation.   Unfortunately,  the  same  error  is
493       returned  if  the tracee exists but is not ptrace-stopped (for commands
494       which require a stopped tracee), or if it is not traced by the  process
495       which  issued  the  ptrace call.  The tracer needs to keep track of the
496       stopped/running state of the tracee, and  interpret  ESRCH  as  "tracee
497       died  unexpectedly"  only if it knows that the tracee has been observed
498       to enter ptrace-stop.  Note that  there  is  no  guarantee  that  wait‐
499       pid(WNOHANG) will reliably report the tracee's death status if a ptrace
500       operation returned ESRCH.  waitpid(WNOHANG) may return 0  instead.   In
501       other words, the tracee may be "not yet fully dead", but already refus‐
502       ing ptrace requests.
504       The tracer can't assume that the tracee always ends its life by report‐
505       ing  WIFEXITED(status)  or  WIFSIGNALED(status);  there are cases where
506       this does not occur.  For example, if a thread other than thread  group
507       leader  does  an  execve(2),  it disappears; its PID will never be seen
508       again, and any subsequent ptrace  stops  will  be  reported  under  the
509       thread group leader's PID.
511   Stopped states
512       A tracee can be in two states: running or stopped.  For the purposes of
513       ptrace, a tracee which is blocked in a system call  (such  as  read(2),
514       pause(2),  etc.)  is nevertheless considered to be running, even if the
515       tracee is blocked for a long time.   The  state  of  the  tracee  after
516       PTRACE_LISTEN  is somewhat of a gray area: it is not in any ptrace-stop
517       (ptrace commands won't work on it, and it will deliver waitpid(2) noti‐
518       fications),  but  it also may be considered "stopped" because it is not
519       executing instructions (is not scheduled), and if it was in  group-stop
520       before  PTRACE_LISTEN,  it will not respond to signals until SIGCONT is
521       received.
523       There are many kinds of states when  the  tracee  is  stopped,  and  in
524       ptrace  discussions  they are often conflated.  Therefore, it is impor‐
525       tant to use precise terms.
527       In this manual page, any stopped state in which the tracee is ready  to
528       accept  ptrace commands from the tracer is called ptrace-stop.  Ptrace-
529       stops can be further subdivided into signal-delivery-stop,  group-stop,
530       syscall-stop,  PTRACE_EVENTstops,  and so on.  These stopped states are
531       described in detail below.
533       When the running tracee enters  ptrace-stop,  it  notifies  its  tracer
534       using  waitpid(2)  (or  one of the other "wait" system calls).  Most of
535       this manual page assumes that the tracer waits with:
537           pid = waitpid(pid_or_minus_1, &status, __WALL);
539       Ptrace-stopped tracees are reported as returns with pid greater than  0
540       and WIFSTOPPED(status) true.
542       The  __WALL  flag  does not include the WSTOPPED and WEXITED flags, but
543       implies their functionality.
545       Setting the WCONTINUED flag when calling waitpid(2) is not recommended:
546       the  "continued"  state is per-process and consuming it can confuse the
547       real parent of the tracee.
549       Use of the WNOHANG flag may cause waitpid(2)  to  return  0  ("no  wait
550       results  available  yet")  even  if  the tracer knows there should be a
551       notification.  Example:
553           errno = 0;
554           ptrace(PTRACE_CONT, pid, 0L, 0L);
555           if (errno == ESRCH) {
556               /* tracee is dead */
557               r = waitpid(tracee, &status, __WALL | WNOHANG);
558               /* r can still be 0 here! */
559           }
561       The  following  kinds  of  ptrace-stops  exist:  signal-delivery-stops,
562       group-stops,  PTRACE_EVENT stops, syscall-stops.  They all are reported
563       by waitpid(2) with WIFSTOPPED(status) true.  They may be differentiated
564       by  examining  the  value  status>>8, and if there is ambiguity in that
565       value, by  querying  PTRACE_GETSIGINFO.   (Note:  the  WSTOPSIG(status)
566       macro can't be used to perform this examination, because it returns the
567       value (status>>8) & 0xff.)
569   Signal-delivery-stop
570       When a (possibly multithreaded)  process  receives  any  signal  except
571       SIGKILL,  the kernel selects an arbitrary thread which handles the sig‐
572       nal.  (If the signal is generated with tgkill(2), the target thread can
573       be  explicitly  selected  by  the  caller.)   If the selected thread is
574       traced, it enters signal-delivery-stop.  At this point, the  signal  is
575       not  yet delivered to the process, and can be suppressed by the tracer.
576       If the tracer doesn't suppress the signal, it passes the signal to  the
577       tracee  in the next ptrace restart request.  This second step of signal
578       delivery is called signal injection in this manual page.  Note that  if
579       the  signal  is  blocked, signal-delivery-stop doesn't happen until the
580       signal is unblocked, with the usual exception  that  SIGSTOP  can't  be
581       blocked.
583       Signal-delivery-stop  is observed by the tracer as waitpid(2) returning
584       with WIFSTOPPED(status) true, with the signal returned by WSTOPSIG(sta‐
585       tus).   If  the  signal  is  SIGTRAP,  this  may be a different kind of
586       ptrace-stop; see the "Syscall-stops" and "execve"  sections  below  for
587       details.   If WSTOPSIG(status) returns a stopping signal, this may be a
588       group-stop; see below.
590   Signal injection and suppression
591       After signal-delivery-stop is observed by the tracer, the tracer should
592       restart the tracee with the call
594           ptrace(PTRACE_restart, pid, 0, sig)
596       where  PTRACE_restart is one of the restarting ptrace requests.  If sig
597       is 0, then a signal is not delivered.  Otherwise,  the  signal  sig  is
598       delivered.   This  operation  is called signal injection in this manual
599       page, to distinguish it from signal-delivery-stop.
601       The sig value may be different from  the  WSTOPSIG(status)  value:  the
602       tracer can cause a different signal to be injected.
604       Note  that a suppressed signal still causes system calls to return pre‐
605       maturely.  In this case, system calls will  be  restarted:  the  tracer
606       will  observe  the  tracee to reexecute the interrupted system call (or
607       restart_syscall(2) system call for a few system calls which use a  dif‐
608       ferent  mechanism  for  restarting)  if the tracer uses PTRACE_SYSCALL.
609       Even system calls (such as poll(2)) which  are  not  restartable  after
610       signal  are  restarted after signal is suppressed; however, kernel bugs
611       exist which cause some system calls to fail with EINTR even  though  no
612       observable signal is injected to the tracee.
614       Restarting  ptrace  commands  issued in ptrace-stops other than signal-
615       delivery-stop are not guaranteed to inject a signal,  even  if  sig  is
616       nonzero.   No  error  is reported; a nonzero sig may simply be ignored.
617       Ptrace users should not try to "create a  new  signal"  this  way:  use
618       tgkill(2) instead.
620       The  fact that signal injection requests may be ignored when restarting
621       the tracee after ptrace stops that are not signal-delivery-stops  is  a
622       cause  of  confusion  among ptrace users.  One typical scenario is that
623       the tracer observes group-stop, mistakes it  for  signal-delivery-stop,
624       restarts the tracee with
626           ptrace(PTRACE_restart, pid, 0, stopsig)
628       with  the  intention of injecting stopsig, but stopsig gets ignored and
629       the tracee continues to run.
631       The SIGCONT signal has a side effect of waking up (all  threads  of)  a
632       group-stopped  process.   This side effect happens before signal-deliv‐
633       ery-stop.  The tracer can't suppress this side effect (it can only sup‐
634       press signal injection, which only causes the SIGCONT handler to not be
635       executed in the tracee, if such a handler is installed).  In fact, wak‐
636       ing up from group-stop may be followed by signal-delivery-stop for sig‐
637       nal(s) other than SIGCONT, if they were pending when SIGCONT was deliv‐
638       ered.   In other words, SIGCONT may be not the first signal observed by
639       the tracee after it was sent.
641       Stopping signals cause (all threads of) a process to enter  group-stop.
642       This  side  effect happens after signal injection, and therefore can be
643       suppressed by the tracer.
645       In Linux 2.4 and earlier, the SIGSTOP signal can't be injected.
647       PTRACE_GETSIGINFO can be used to retrieve a siginfo_t  structure  which
648       corresponds  to the delivered signal.  PTRACE_SETSIGINFO may be used to
649       modify it.  If PTRACE_SETSIGINFO has been used to alter siginfo_t,  the
650       si_signo  field  and  the  sig parameter in the restarting command must
651       match, otherwise the result is undefined.
653   Group-stop
654       When a (possibly multithreaded) process receives a stopping signal, all
655       threads  stop.   If  some  threads are traced, they enter a group-stop.
656       Note that the stopping signal will first cause signal-delivery-stop (on
657       one tracee only), and only after it is injected by the tracer (or after
658       it was dispatched to a thread which isn't traced), will  group-stop  be
659       initiated  on  all tracees within the multithreaded process.  As usual,
660       every tracee reports its group-stop  separately  to  the  corresponding
661       tracer.
663       Group-stop  is observed by the tracer as waitpid(2) returning with WIF‐
664       STOPPED(status) true, with the stopping  signal  available  via  WSTOP‐
665       SIG(status).   The  same  result  is  returned by some other classes of
666       ptrace-stops, therefore the recommended practice is to perform the call
668           ptrace(PTRACE_GETSIGINFO, pid, 0, &siginfo)
670       The call can be avoided if the signal is not SIGSTOP, SIGTSTP, SIGTTIN,
671       or  SIGTTOU;  only  these  four  signals  are stopping signals.  If the
672       tracer sees something else, it can't be a group-stop.   Otherwise,  the
673       tracer  needs  to  call  PTRACE_GETSIGINFO.  If PTRACE_GETSIGINFO fails
674       with EINVAL, then it is definitely a group-stop.  (Other failure  codes
675       are possible, such as ESRCH ("no such process") if a SIGKILL killed the
676       tracee.)
678       If tracee was attached using PTRACE_SEIZE, group-stop is  indicated  by
679       PTRACE_EVENT_STOP: status>>16 == PTRACE_EVENT_STOP.  This allows detec‐
680       tion of group-stops without requiring an extra PTRACE_GETSIGINFO call.
682       As of Linux 2.6.38, after the tracer sees the  tracee  ptrace-stop  and
683       until  it  restarts  or kills it, the tracee will not run, and will not
684       send notifications (except SIGKILL death) to the tracer,  even  if  the
685       tracer enters into another waitpid(2) call.
687       The  kernel behavior described in the previous paragraph causes a prob‐
688       lem with transparent handling  of  stopping  signals.   If  the  tracer
689       restarts  the  tracee  after  group-stop, the stopping signal is effec‐
690       tively ignored—the tracee doesn't remain  stopped,  it  runs.   If  the
691       tracer  doesn't  restart the tracee before entering into the next wait‐
692       pid(2), future SIGCONT signals will not be reported to the tracer; this
693       would cause the SIGCONT signals to have no effect on the tracee.
695       Since Linux 3.4, there is a method to overcome this problem: instead of
696       PTRACE_CONT, a PTRACE_LISTEN command can be used to restart a tracee in
697       a way where it does not execute, but waits for a new event which it can
698       report via waitpid(2) (such as when it is restarted by a SIGCONT).
700   PTRACE_EVENT stops
701       If the tracer sets PTRACE_O_TRACE_*  options,  the  tracee  will  enter
702       ptrace-stops called PTRACE_EVENT stops.
704       PTRACE_EVENT  stops  are observed by the tracer as waitpid(2) returning
705       with WIFSTOPPED(status),  and  WSTOPSIG(status)  returns  SIGTRAP.   An
706       additional  bit is set in the higher byte of the status word: the value
707       status>>8 will be
709           (SIGTRAP | PTRACE_EVENT_foo << 8).
711       The following events exist:
714              Stop  before  return  from  vfork(2)  or   clone(2)   with   the
715              CLONE_VFORK flag.  When the tracee is continued after this stop,
716              it will wait for child to exit/exec before continuing its execu‐
717              tion (in other words, the usual behavior on vfork(2)).
720              Stop before return from fork(2) or clone(2) with the exit signal
721              set to SIGCHLD.
724              Stop before return from clone(2).
727              Stop  before  return  from  vfork(2)  or   clone(2)   with   the
728              CLONE_VFORK  flag,  but after the child unblocked this tracee by
729              exiting or execing.
731       For all four stops described above,  the  stop  occurs  in  the  parent
732       (i.e.,    the    tracee),    not   in   the   newly   created   thread.
733       PTRACE_GETEVENTMSG can be used to retrieve the new thread's ID.
736              Stop  before  return   from   execve(2).    Since   Linux   3.0,
737              PTRACE_GETEVENTMSG returns the former thread ID.
740              Stop  before  exit  (including death from exit_group(2)), signal
741              death, or exit caused by execve(2) in a  multithreaded  process.
742              PTRACE_GETEVENTMSG  returns  the  exit status.  Registers can be
743              examined (unlike when "real" exit happens).  The tracee is still
744              alive; it needs to be PTRACE_CONTed or PTRACE_DETACHed to finish
745              exiting.
748              Stop induced by PTRACE_INTERRUPT command, or group-stop, or ini‐
749              tial  ptrace-stop when a new child is attached (only if attached
750              using PTRACE_SEIZE).
753              Stop triggered by a seccomp(2) rule on tracee syscall entry when
754              PTRACE_O_TRACESECCOMP  has  been set by the tracer.  The seccomp
755              event message data (from the  SECCOMP_RET_DATA  portion  of  the
756              seccomp  filter  rule) can be retrieved with PTRACE_GETEVENTMSG.
757              The semantics of this stop are described in detail in a separate
758              section below.
760       PTRACE_GETSIGINFO  on  PTRACE_EVENT  stops returns SIGTRAP in si_signo,
761       with si_code set to (event<<8) | SIGTRAP.
763   Syscall-stops
764       If the tracee was restarted by  PTRACE_SYSCALL  or  PTRACE_SYSEMU,  the
765       tracee enters syscall-enter-stop just prior to entering any system call
766       (which will not be executed if the  restart  was  using  PTRACE_SYSEMU,
767       regardless  of  any  change  made to registers at this point or how the
768       tracee is restarted after this stop).  No matter  which  method  caused
769       the   syscall-entry-stop,  if  the  tracer  restarts  the  tracee  with
770       PTRACE_SYSCALL, the tracee enters  syscall-exit-stop  when  the  system
771       call  is finished, or if it is interrupted by a signal.  (That is, sig‐
772       nal-delivery-stop never happens between syscall-enter-stop and syscall-
773       exit-stop; it happens after syscall-exit-stop.).  If the tracee is con‐
774       tinued using any other method (including  PTRACE_SYSEMU),  no  syscall-
775       exit-stop  occurs.   Note that all mentions PTRACE_SYSEMU apply equally
778       However, even if the tracee was continued using PTRACE_SYSCALL , it  is
779       not  guaranteed  that the next stop will be a syscall-exit-stop.  Other
780       possibilities are that the tracee  may  stop  in  a  PTRACE_EVENT  stop
781       (including   seccomp   stops),   exit   (if   it  entered  _exit(2)  or
782       exit_group(2)), be killed by SIGKILL, or  die  silently  (if  it  is  a
783       thread group leader, the execve(2) happened in another thread, and that
784       thread is not traced by the same tracer; this  situation  is  discussed
785       later).
787       Syscall-enter-stop  and syscall-exit-stop are observed by the tracer as
788       waitpid(2) returning with WIFSTOPPED(status) true, and WSTOPSIG(status)
789       giving  SIGTRAP.   If  the  PTRACE_O_TRACESYSGOOD option was set by the
790       tracer, then WSTOPSIG(status) will give the value (SIGTRAP | 0x80).
792       Syscall-stops can be distinguished from signal-delivery-stop with  SIG‐
793       TRAP by querying PTRACE_GETSIGINFO for the following cases:
795       si_code <= 0
796              SIGTRAP  was  delivered  as a result of a user-space action, for
797              example, a system call (tgkill(2), kill(2), sigqueue(3),  etc.),
798              expiration  of a POSIX timer, change of state on a POSIX message
799              queue, or completion of an asynchronous I/O request.
801       si_code == SI_KERNEL (0x80)
802              SIGTRAP was sent by the kernel.
804       si_code == SIGTRAP or si_code == (SIGTRAP|0x80)
805              This is a syscall-stop.
807       However, syscall-stops happen very often (twice per system  call),  and
808       performing  PTRACE_GETSIGINFO  for  every  syscall-stop may be somewhat
809       expensive.
811       Some architectures allow the cases to  be  distinguished  by  examining
812       registers.   For example, on x86, rax == -ENOSYS in syscall-enter-stop.
813       Since SIGTRAP (like any other signal)  always  happens  after  syscall-
814       exit-stop,  and  at  this  point rax almost never contains -ENOSYS, the
815       SIGTRAP looks like "syscall-stop which is not  syscall-enter-stop";  in
816       other  words,  it  looks  like  a  "stray syscall-exit-stop" and can be
817       detected this way.  But such detection is fragile and is best avoided.
819       Using the PTRACE_O_TRACESYSGOOD option is  the  recommended  method  to
820       distinguish syscall-stops from other kinds of ptrace-stops, since it is
821       reliable and does not incur a performance penalty.
823       Syscall-enter-stop and  syscall-exit-stop  are  indistinguishable  from
824       each  other  by  the  tracer.   The  tracer  needs to keep track of the
825       sequence of ptrace-stops in order to  not  misinterpret  syscall-enter-
826       stop  as syscall-exit-stop or vice versa.  In general, a syscall-enter-
827       stop is always followed by syscall-exit-stop, PTRACE_EVENT stop, or the
828       tracee's  death;  no  other  kinds of ptrace-stop can occur in between.
829       However, note that seccomp stops (see below)  can  cause  syscall-exit-
830       stops,  without  preceding  syscall-entry-stops.  If seccomp is in use,
831       care needs to be taken not to misinterpret such stops as syscall-entry-
832       stops.
834       If after syscall-enter-stop, the tracer uses a restarting command other
835       than PTRACE_SYSCALL, syscall-exit-stop is not generated.
837       PTRACE_GETSIGINFO on syscall-stops returns SIGTRAP  in  si_signo,  with
838       si_code set to SIGTRAP or (SIGTRAP|0x80).
840   PTRACE_EVENT_SECCOMP stops (Linux 3.5 to 4.7)
841       The  behavior  of PTRACE_EVENT_SECCOMP stops and their interaction with
842       other kinds of ptrace stops has changed between kernel versions.   This
843       documents  the behavior from their introduction until Linux 4.7 (inclu‐
844       sive).  The behavior in later kernel versions is documented in the next
845       section.
847       A PTRACE_EVENT_SECCOMP stop occurs whenever a SECCOMP_RET_TRACE rule is
848       triggered.  This is independent of which methods was  used  to  restart
849       the  system  call.   Notably, seccomp still runs even if the tracee was
850       restarted using PTRACE_SYSEMU and this system call  is  unconditionally
851       skipped.
853       Restarts  from  this stop will behave as if the stop had occurred right
854       before the system call in question.  In particular, both PTRACE_SYSCALL
855       and  PTRACE_SYSEMU will normally cause a subsequent syscall-entry-stop.
856       However, if after the PTRACE_EVENT_SECCOMP the system  call  number  is
857       negative,  both  the syscall-entry-stop and the system call itself will
858       be skipped.  This means that if the  system  call  number  is  negative
859       after   a  PTRACE_EVENT_SECCOMP  and  the  tracee  is  restarted  using
860       PTRACE_SYSCALL, the next observed stop  will  be  a  syscall-exit-stop,
861       rather than the syscall-entry-stop that might have been expected.
863   PTRACE_EVENT_SECCOMP stops (since Linux 4.8)
864       Starting with Linux 4.8, the PTRACE_EVENT_SECCOMP stop was reordered to
865       occur between syscall-entry-stop and syscall-exit-stop.  Note that sec‐
866       comp  no  longer runs (and no PTRACE_EVENT_SECCOMP will be reported) if
867       the system call is skipped due to PTRACE_SYSEMU.
869       Functionally, a PTRACE_EVENT_SECCOMP stop  functions  comparably  to  a
870       syscall-entry-stop (i.e., continuations using PTRACE_SYSCALL will cause
871       syscall-exit-stops, the system call number may be changed and any other
872       modified  registers  are  visible  to the to-be-executed system call as
873       well).  Note that there may be, but need  not  have  been  a  preceding
874       syscall-entry-stop.
876       After  a  PTRACE_EVENT_SECCOMP stop, seccomp will be rerun, with a SEC‐
877       COMP_RET_TRACE rule now functioning the same  as  a  SECCOMP_RET_ALLOW.
878       Specifically,  this means that if registers are not modified during the
879       PTRACE_EVENT_SECCOMP stop, the system call will then be allowed.
882       [Details of these kinds of stops are yet to be documented.]
884   Informational and restarting ptrace commands
885       Most  ptrace  commands   (all   except   PTRACE_ATTACH,   PTRACE_SEIZE,
886       PTRACE_TRACEME,  PTRACE_INTERRUPT,  and PTRACE_KILL) require the tracee
887       to be in a ptrace-stop, otherwise they fail with ESRCH.
889       When the tracee is in ptrace-stop, the tracer can read and  write  data
890       to  the  tracee using informational commands.  These commands leave the
891       tracee in ptrace-stopped state:
893           ptrace(PTRACE_PEEKTEXT/PEEKDATA/PEEKUSER, pid, addr, 0);
894           ptrace(PTRACE_POKETEXT/POKEDATA/POKEUSER, pid, addr, long_val);
895           ptrace(PTRACE_GETREGS/GETFPREGS, pid, 0, &struct);
896           ptrace(PTRACE_SETREGS/SETFPREGS, pid, 0, &struct);
897           ptrace(PTRACE_GETREGSET, pid, NT_foo, &iov);
898           ptrace(PTRACE_SETREGSET, pid, NT_foo, &iov);
899           ptrace(PTRACE_GETSIGINFO, pid, 0, &siginfo);
900           ptrace(PTRACE_SETSIGINFO, pid, 0, &siginfo);
901           ptrace(PTRACE_GETEVENTMSG, pid, 0, &long_var);
902           ptrace(PTRACE_SETOPTIONS, pid, 0, PTRACE_O_flags);
904       Note that some errors are not reported.  For  example,  setting  signal
905       information  (siginfo) may have no effect in some ptrace-stops, yet the
906       call  may  succeed   (return   0   and   not   set   errno);   querying
907       PTRACE_GETEVENTMSG  may succeed and return some random value if current
908       ptrace-stop is not documented as returning a meaningful event message.
910       The call
912           ptrace(PTRACE_SETOPTIONS, pid, 0, PTRACE_O_flags);
914       affects one tracee.  The tracee's current flags  are  replaced.   Flags
915       are  inherited  by  new  tracees created and "auto-attached" via active
917       options.
919       Another  group  of  commands makes the ptrace-stopped tracee run.  They
920       have the form:
922           ptrace(cmd, pid, 0, sig);
926       tracee is in signal-delivery-stop, sig is the signal to be injected (if
927       it  is  nonzero).   Otherwise,  sig may be ignored.  (When restarting a
928       tracee from a ptrace-stop other than signal-delivery-stop,  recommended
929       practice is to always pass 0 in sig.)
931   Attaching and detaching
932       A thread can be attached to the tracer using the call
934           ptrace(PTRACE_ATTACH, pid, 0, 0);
936       or
938           ptrace(PTRACE_SEIZE, pid, 0, PTRACE_O_flags);
940       PTRACE_ATTACH  sends  SIGSTOP to this thread.  If the tracer wants this
941       SIGSTOP to have no effect, it needs to suppress it.  Note that if other
942       signals  are concurrently sent to this thread during attach, the tracer
943       may see the tracee  enter  signal-delivery-stop  with  other  signal(s)
944       first!   The  usual practice is to reinject these signals until SIGSTOP
945       is seen, then suppress SIGSTOP injection.  The design bug here is  that
946       a  ptrace  attach and a concurrently delivered SIGSTOP may race and the
947       concurrent SIGSTOP may be lost.
949       Since attaching sends SIGSTOP and the  tracer  usually  suppresses  it,
950       this may cause a stray EINTR return from the currently executing system
951       call in the tracee, as described in the "Signal injection and  suppres‐
952       sion" section.
954       Since  Linux  3.4,  PTRACE_SEIZE  can be used instead of PTRACE_ATTACH.
955       PTRACE_SEIZE does not stop the attached process.  If you need  to  stop
956       it  after attach (or at any other time) without sending it any signals,
957       use PTRACE_INTERRUPT command.
959       The request
961           ptrace(PTRACE_TRACEME, 0, 0, 0);
963       turns the calling thread into a tracee.  The thread  continues  to  run
964       (doesn't  enter  ptrace-stop).   A  common  practice  is  to follow the
965       PTRACE_TRACEME with
967           raise(SIGSTOP);
969       and allow the parent (which is our tracer now) to observe  our  signal-
970       delivery-stop.
973       options are in effect, then children created by, respectively, vfork(2)
974       or  clone(2)  with  the  CLONE_VFORK flag, fork(2) or clone(2) with the
975       exit signal set to SIGCHLD, and other kinds of clone(2), are  automati‐
976       cally  attached  to the same tracer which traced their parent.  SIGSTOP
977       is delivered to the children, causing them  to  enter  signal-delivery-
978       stop after they exit the system call which created them.
980       Detaching of the tracee is performed by:
982           ptrace(PTRACE_DETACH, pid, 0, sig);
984       PTRACE_DETACH  is  a  restarting  operation;  therefore it requires the
985       tracee to be in ptrace-stop.  If the tracee is in signal-delivery-stop,
986       a signal can be injected.  Otherwise, the sig parameter may be silently
987       ignored.
989       If the tracee is running when the tracer wants to detach it, the  usual
990       solution  is  to send SIGSTOP (using tgkill(2), to make sure it goes to
991       the correct thread), wait for the tracee to  stop  in  signal-delivery-
992       stop for SIGSTOP and then detach it (suppressing SIGSTOP injection).  A
993       design bug is that this can race  with  concurrent  SIGSTOPs.   Another
994       complication  is that the tracee may enter other ptrace-stops and needs
995       to be restarted and waited for  again,  until  SIGSTOP  is  seen.   Yet
996       another  complication  is  to  be  sure  that the tracee is not already
997       ptrace-stopped, because no signal delivery happens while it is—not even
998       SIGSTOP.
1000       If  the  tracer  dies,  all  tracees  are  automatically  detached  and
1001       restarted, unless they were in group-stop.  Handling  of  restart  from
1002       group-stop  is  currently  buggy,  but  the "as planned" behavior is to
1003       leave tracee stopped  and  waiting  for  SIGCONT.   If  the  tracee  is
1004       restarted from signal-delivery-stop, the pending signal is injected.
1006   execve(2) under ptrace
1007       When  one thread in a multithreaded process calls execve(2), the kernel
1008       destroys all other threads in the process, and resets the thread ID  of
1009       the  execing  thread  to the thread group ID (process ID).  (Or, to put
1010       things another way, when a multithreaded process does an execve(2),  at
1011       completion  of the call, it appears as though the execve(2) occurred in
1012       the thread group leader, regardless of which thread did the execve(2).)
1013       This resetting of the thread ID looks very confusing to tracers:
1015       *  All   other   threads   stop   in  PTRACE_EVENT_EXIT  stop,  if  the
1016          PTRACE_O_TRACEEXIT option was turned on.   Then  all  other  threads
1017          except  the  thread  group leader report death as if they exited via
1018          _exit(2) with exit code 0.
1020       *  The execing tracee  changes  its  thread  ID  while  it  is  in  the
1021          execve(2).   (Remember,  under ptrace, the "pid" returned from wait‐
1022          pid(2), or fed into ptrace calls, is the tracee's thread ID.)   That
1023          is,  the  tracee's  thread ID is reset to be the same as its process
1024          ID, which is the same as the thread group leader's thread ID.
1026       *  Then a PTRACE_EVENT_EXEC stop  happens,  if  the  PTRACE_O_TRACEEXEC
1027          option was turned on.
1029       *  If  the  thread group leader has reported its PTRACE_EVENT_EXIT stop
1030          by this time, it appears to the tracer that the dead  thread  leader
1031          "reappears  from  nowhere".  (Note: the thread group leader does not
1032          report death via WIFEXITED(status) until there is at least one other
1033          live  thread.   This eliminates the possibility that the tracer will
1034          see it dying and then reappearing.)  If the thread group leader  was
1035          still  alive, for the tracer this may look as if thread group leader
1036          returns from a different  system  call  than  it  entered,  or  even
1037          "returned  from  a  system call even though it was not in any system
1038          call".  If the thread group leader was not traced (or was traced  by
1039          a  different  tracer), then during execve(2) it will appear as if it
1040          has become a tracee of the tracer of the execing tracee.
1042       All of the above effects are the artifacts of the thread ID  change  in
1043       the tracee.
1045       The  PTRACE_O_TRACEEXEC option is the recommended tool for dealing with
1046       this situation.  First, it enables PTRACE_EVENT_EXEC stop, which occurs
1047       before   execve(2)   returns.    In  this  stop,  the  tracer  can  use
1048       PTRACE_GETEVENTMSG to retrieve the tracee's former  thread  ID.   (This
1049       feature  was  introduced in Linux 3.0.)  Second, the PTRACE_O_TRACEEXEC
1050       option disables legacy SIGTRAP generation on execve(2).
1052       When the tracer receives PTRACE_EVENT_EXEC  stop  notification,  it  is
1053       guaranteed  that  except  this  tracee  and the thread group leader, no
1054       other threads from the process are alive.
1056       On receiving the PTRACE_EVENT_EXEC stop notification, the tracer should
1057       clean  up  all  its  internal data structures describing the threads of
1058       this process, and retain only one data  structure—one  which  describes
1059       the single still running tracee, with
1061           thread ID == thread group ID == process ID.
1063       Example: two threads call execve(2) at the same time:
1065       *** we get syscall-enter-stop in thread 1: **
1066       PID1 execve("/bin/foo", "foo" <unfinished ...>
1067       *** we issue PTRACE_SYSCALL for thread 1 **
1068       *** we get syscall-enter-stop in thread 2: **
1069       PID2 execve("/bin/bar", "bar" <unfinished ...>
1070       *** we issue PTRACE_SYSCALL for thread 2 **
1071       *** we get PTRACE_EVENT_EXEC for PID0, we issue PTRACE_SYSCALL **
1072       *** we get syscall-exit-stop for PID0: **
1073       PID0 <... execve resumed> )             = 0
1075       If  the  PTRACE_O_TRACEEXEC  option  is  not  in effect for the execing
1076       tracee,  and  if   the   tracee   was   PTRACE_ATTACHed   rather   that
1077       PTRACE_SEIZEd, the kernel delivers an extra SIGTRAP to the tracee after
1078       execve(2) returns.  This is an ordinary signal (similar  to  one  which
1079       can  be  generated  by  kill -TRAP), not a special kind of ptrace-stop.
1080       Employing PTRACE_GETSIGINFO for this signal returns si_code  set  to  0
1081       (SI_USER).   This signal may be blocked by signal mask, and thus may be
1082       delivered (much) later.
1084       Usually, the tracer (for example, strace(1)) would  not  want  to  show
1085       this  extra  post-execve SIGTRAP signal to the user, and would suppress
1086       its delivery to the tracee (if SIGTRAP is  set  to  SIG_DFL,  it  is  a
1087       killing signal).  However, determining which SIGTRAP to suppress is not
1088       easy.  Setting the PTRACE_O_TRACEEXEC option or using PTRACE_SEIZE  and
1089       thus suppressing this extra SIGTRAP is the recommended approach.
1091   Real parent
1092       The  ptrace  API (ab)uses the standard UNIX parent/child signaling over
1093       waitpid(2).  This used to cause the real parent of the process to  stop
1094       receiving  several  kinds  of  waitpid(2)  notifications when the child
1095       process is traced by some other process.
1097       Many of these bugs have been fixed, but  as  of  Linux  2.6.38  several
1098       still exist; see BUGS below.
1100       As of Linux 2.6.38, the following is believed to work correctly:
1102       *  exit/death by signal is reported first to the tracer, then, when the
1103          tracer consumes the waitpid(2) result, to the real  parent  (to  the
1104          real  parent  only  when the whole multithreaded process exits).  If
1105          the tracer and the real parent are the same process, the  report  is
1106          sent only once.


1109       On  success,  the  PTRACE_PEEK* requests return the requested data (but
1110       see NOTES), while other requests return zero.
1112       On error, all requests return  -1,  and  errno  is  set  appropriately.
1113       Since  the  value  returned by a successful PTRACE_PEEK* request may be
1114       -1, the caller must clear errno before the  call,  and  then  check  it
1115       afterward to determine whether or not an error occurred.


1118       EBUSY  (i386  only)  There  was  an  error with allocating or freeing a
1119              debug register.
1121       EFAULT There was an attempt to read from or write to an invalid area in
1122              the  tracer's  or the tracee's memory, probably because the area
1123              wasn't mapped or accessible.  Unfortunately, under  Linux,  dif‐
1124              ferent  variations  of this fault will return EIO or EFAULT more
1125              or less arbitrarily.
1127       EINVAL An attempt was made to set an invalid option.
1129       EIO    request is invalid, or an attempt was made to read from or write
1130              to  an  invalid  area in the tracer's or the tracee's memory, or
1131              there was a word-alignment violation, or an invalid  signal  was
1132              specified during a restart request.
1134       EPERM  The  specified  process cannot be traced.  This could be because
1135              the tracer has insufficient privileges (the required  capability
1136              is  CAP_SYS_PTRACE);  unprivileged  processes  cannot trace pro‐
1137              cesses that they cannot send signals to or  those  running  set-
1138              user-ID/set-group-ID  programs,  for  obvious reasons.  Alterna‐
1139              tively, the process may already be being traced, or (on  kernels
1140              before 2.6.26) be init(1) (PID 1).
1142       ESRCH  The  specified process does not exist, or is not currently being
1143              traced by the caller, or  is  not  stopped  (for  requests  that
1144              require a stopped tracee).


1147       SVr4, 4.3BSD.


1150       Although  arguments to ptrace() are interpreted according to the proto‐
1151       type given, glibc currently declares ptrace() as  a  variadic  function
1152       with only the request argument fixed.  It is recommended to always sup‐
1153       ply four arguments, even if the requested operation does not use  them,
1154       setting unused/ignored arguments to 0L or (void *) 0.
1156       In  Linux  kernels  before 2.6.26, init(1), the process with PID 1, may
1157       not be traced.
1159       A tracees parent continues to be the tracer even if that  tracer  calls
1160       execve(2).
1162       The  layout of the contents of memory and the USER area are quite oper‐
1163       ating-system- and architecture-specific.  The offset supplied, and  the
1164       data  returned,  might not entirely match with the definition of struct
1165       user.
1167       The size of a "word" is  determined  by  the  operating-system  variant
1168       (e.g., for 32-bit Linux it is 32 bits).
1170       This page documents the way the ptrace() call works currently in Linux.
1171       Its behavior differs significantly on other flavors of  UNIX.   In  any
1172       case,  use  of  ptrace() is highly specific to the operating system and
1173       architecture.
1175   Ptrace access mode checking
1176       Various parts of the kernel-user-space API (not  just  ptrace()  opera‐
1177       tions),  require  so-called  "ptrace access mode" checks, whose outcome
1178       determines whether an operation is  permitted  (or,  in  a  few  cases,
1179       causes  a "read" operation to return sanitized data).  These checks are
1180       performed in cases where one process can inspect sensitive  information
1181       about,  or  in  some  cases  modify the state of, another process.  The
1182       checks are based on factors such as the credentials and capabilities of
1183       the two processes, whether or not the "target" process is dumpable, and
1184       the results of checks performed by any enabled  Linux  Security  Module
1185       (LSM)—for  example,  SELinux,  Yama,  or Smack—and by the commoncap LSM
1186       (which is always invoked).
1188       Prior to Linux 2.6.27, all access checks were of a single type.   Since
1189       Linux 2.6.27, two access mode levels are distinguished:
1192              For  "read" operations or other operations that are less danger‐
1193              ous,   such    as:    get_robust_list(2);    kcmp(2);    reading
1194              /proc/[pid]/auxv,  /proc/[pid]/environ,  or /proc/[pid]/stat; or
1195              readlink(2) of a /proc/[pid]/ns/* file.
1198              For "write" operations, or other operations that are  more  dan‐
1199              gerous,  such  as:  ptrace  attaching (PTRACE_ATTACH) to another
1200              process or  calling  process_vm_writev(2).   (PTRACE_MODE_ATTACH
1201              was effectively the default before Linux 2.6.27.)
1203       Since  Linux 4.5, the above access mode checks are combined (ORed) with
1204       one of the following modifiers:
1207              Use the caller's filesystem UID and GID (see credentials(7))  or
1208              effective capabilities for LSM checks.
1211              Use  the caller's real UID and GID or permitted capabilities for
1212              LSM checks.  This was effectively the default before Linux 4.5.
1214       Because combining one of the  credential  modifiers  with  one  of  the
1215       aforementioned  access modes is typical, some macros are defined in the
1216       kernel sources for the combinations:
1219              Defined as PTRACE_MODE_READ | PTRACE_MODE_FSCREDS.
1222              Defined as PTRACE_MODE_READ | PTRACE_MODE_REALCREDS.
1225              Defined as PTRACE_MODE_ATTACH | PTRACE_MODE_FSCREDS.
1228              Defined as PTRACE_MODE_ATTACH | PTRACE_MODE_REALCREDS.
1230       One further modifier can be ORed with the access mode:
1232       PTRACE_MODE_NOAUDIT (since Linux 3.3)
1233              Don't audit this access mode check.  This modifier  is  employed
1234              for  ptrace  access  mode  checks  (such  as checks when reading
1235              /proc/[pid]/stat) that merely cause the output to be filtered or
1236              sanitized,  rather  than  causing an error to be returned to the
1237              caller.  In these cases, accessing the file is  not  a  security
1238              violation  and  there  is no reason to generate a security audit
1239              record.  This modifier suppresses  the  generation  of  such  an
1240              audit record for the particular access check.
1242       Note  that all of the PTRACE_MODE_* constants described in this subsec‐
1243       tion are kernel-internal, and not visible to user space.  The  constant
1244       names  are mentioned here in order to label the various kinds of ptrace
1245       access mode checks that are performed  for  various  system  calls  and
1246       accesses  to  various pseudofiles (e.g., under /proc).  These names are
1247       used in other manual pages to provide a simple shorthand  for  labeling
1248       the different kernel checks.
1250       The  algorithm  employed  for  ptrace  access  mode checking determines
1251       whether the calling process is allowed  to  perform  the  corresponding
1252       action  on  the  target  process.   (In the case of opening /proc/[pid]
1253       files, the "calling process" is the  one  opening  the  file,  and  the
1254       process with the corresponding PID is the "target process".)  The algo‐
1255       rithm is as follows:
1257       1. If the calling thread and the target thread are in the  same  thread
1258          group, access is always allowed.
1260       2. If  the  access  mode  specifies  PTRACE_MODE_FSCREDS, then, for the
1261          check in the next step, employ the caller's filesystem UID and  GID.
1262          (As  noted  in  credentials(7),  the  filesystem  UID and GID almost
1263          always have the same values as the corresponding effective IDs.)
1265          Otherwise, the access mode specifies PTRACE_MODE_REALCREDS,  so  use
1266          the  caller's  real  UID  and  GID  for the checks in the next step.
1267          (Most APIs that check the caller's UID and  GID  use  the  effective
1268          IDs.   For  historical reasons, the PTRACE_MODE_REALCREDS check uses
1269          the real IDs instead.)
1271       3. Deny access if neither of the following is true:
1273          · The real, effective, and saved-set user IDs of  the  target  match
1274            the caller's user ID, and the real, effective, and saved-set group
1275            IDs of the target match the caller's group ID.
1277          · The caller has the CAP_SYS_PTRACE capability in the user namespace
1278            of the target.
1280       4. Deny  access  if the target process "dumpable" attribute has a value
1281          other than 1 (SUID_DUMP_USER; see the discussion of  PR_SET_DUMPABLE
1282          in  prctl(2)), and the caller does not have the CAP_SYS_PTRACE capa‐
1283          bility in the user namespace of the target process.
1285       5. The kernel LSM security_ptrace_access_check() interface  is  invoked
1286          to  see  if  ptrace  access is permitted.  The results depend on the
1287          LSM(s).  The implementation of this interface in the  commoncap  LSM
1288          performs the following steps:
1290          a) If  the  access  mode  includes PTRACE_MODE_FSCREDS, then use the
1291             caller's effective capability set in the following check;  other‐
1292             wise  (the  access  mode specifies PTRACE_MODE_REALCREDS, so) use
1293             the caller's permitted capability set.
1295          b) Deny access if neither of the following is true:
1297             · The caller and the target process are in the same  user  names‐
1298               pace,  and  the  caller's capabilities are a proper superset of
1299               the target process's permitted capabilities.
1301             · The caller has the  CAP_SYS_PTRACE  capability  in  the  target
1302               process's user namespace.
1304             Note   that  the  commoncap  LSM  does  not  distinguish  between
1307       6. If access has not been denied by any of the  preceding  steps,  then
1308          access is allowed.
1310   /proc/sys/kernel/yama/ptrace_scope
1311       On  systems  with the Yama Linux Security Module (LSM) installed (i.e.,
1312       the   kernel   was   configured   with    CONFIG_SECURITY_YAMA),    the
1313       /proc/sys/kernel/yama/ptrace_scope file (available since Linux 3.4) can
1314       be used to restrict the ability to trace a process with  ptrace()  (and
1315       thus  also the ability to use tools such as strace(1) and gdb(1)).  The
1316       goal of such restrictions is to prevent  attack  escalation  whereby  a
1317       compromised  process  can  ptrace-attach  to  other sensitive processes
1318       (e.g., a GPG agent or an SSH session) owned by the  user  in  order  to
1319       gain  additional  credentials  that may exist in memory and thus expand
1320       the scope of the attack.
1322       More precisely, the Yama LSM limits two types of operations:
1324       *  Any operation that performs a ptrace access mode  PTRACE_MODE_ATTACH
1325          check—for  example, ptrace() PTRACE_ATTACH.  (See the "Ptrace access
1326          mode checking" discussion above.)
1328       *  ptrace() PTRACE_TRACEME.
1330       A process  that  has  the  CAP_SYS_PTRACE  capability  can  update  the
1331       /proc/sys/kernel/yama/ptrace_scope  file with one of the following val‐
1332       ues:
1334       0 ("classic ptrace permissions")
1335              No  additional   restrictions   on   operations   that   perform
1336              PTRACE_MODE_ATTACH checks (beyond those imposed by the commoncap
1337              and other LSMs).
1339              The use of PTRACE_TRACEME is unchanged.
1341       1 ("restricted ptrace") [default value]
1342              When performing an operation that requires a  PTRACE_MODE_ATTACH
1343              check,  the  calling process must either have the CAP_SYS_PTRACE
1344              capability in the user namespace of the  target  process  or  it
1345              must have a predefined relationship with the target process.  By
1346              default, the predefined relationship is that the target  process
1347              must be a descendant of the caller.
1349              A  target  process can employ the prctl(2) PR_SET_PTRACER opera‐
1350              tion to declare an additional PID that  is  allowed  to  perform
1351              PTRACE_MODE_ATTACH  operations  on  the  target.  See the kernel
1352              source file Documentation/admin-guide/LSM/Yama.rst (or  Documen‐
1353              tation/security/Yama.txt before Linux 4.13) for further details.
1355              The use of PTRACE_TRACEME is unchanged.
1357       2 ("admin-only attach")
1358              Only  processes  with  the CAP_SYS_PTRACE capability in the user
1359              namespace of the target process may  perform  PTRACE_MODE_ATTACH
1360              operations or trace children that employ PTRACE_TRACEME.
1362       3 ("no attach")
1363              No  process  may  perform PTRACE_MODE_ATTACH operations or trace
1364              children that employ PTRACE_TRACEME.
1366              Once this value has been written  to  the  file,  it  cannot  be
1367              changed.
1369       With respect to values 1 and 2, note that creating a new user namespace
1370       effectively removes the protection offered by Yama.  This is because  a
1371       process  in  the  parent user namespace whose effective UID matches the
1372       UID of the creator of a child namespace has all capabilities (including
1373       CAP_SYS_PTRACE) when performing operations within the child user names‐
1374       pace (and  further-removed  descendants  of  that  namespace).   Conse‐
1375       quently, when a process tries to use user namespaces to sandbox itself,
1376       it inadvertently weakens the protections offered by the Yama LSM.
1378   C library/kernel differences
1379       At the system call level,  the  PTRACE_PEEKTEXT,  PTRACE_PEEKDATA,  and
1380       PTRACE_PEEKUSER requests have a different API: they store the result at
1381       the address specified by the data parameter, and the  return  value  is
1382       the  error  flag.  The glibc wrapper function provides the API given in
1383       DESCRIPTION above, with the result  being  returned  via  the  function
1384       return value.


1387       On  hosts with 2.6 kernel headers, PTRACE_SETOPTIONS is declared with a
1388       different value than the one for 2.4.  This leads to applications  com‐
1389       piled  with  2.6  kernel headers failing when run on 2.4 kernels.  This
1390       can be worked around by redefining PTRACE_SETOPTIONS  to  PTRACE_OLDSE‐
1391       TOPTIONS, if that is defined.
1393       Group-stop  notifications  are sent to the tracer, but not to real par‐
1394       ent.  Last confirmed on
1396       If a thread group leader is traced and exits  by  calling  _exit(2),  a
1397       PTRACE_EVENT_EXIT  stop will happen for it (if requested), but the sub‐
1398       sequent WIFEXITED notification will not be delivered  until  all  other
1399       threads  exit.   As  explained  above,  if  one  of other threads calls
1400       execve(2), the death of the thread group leader will never be reported.
1401       If  the  execed  thread  is  not traced by this tracer, the tracer will
1402       never know that execve(2) happened.   One  possible  workaround  is  to
1403       PTRACE_DETACH  the thread group leader instead of restarting it in this
1404       case.  Last confirmed on
1406       A SIGKILL signal may still cause a PTRACE_EVENT_EXIT stop before actual
1407       signal  death.   This may be changed in the future; SIGKILL is meant to
1408       always immediately kill tasks even under  ptrace.   Last  confirmed  on
1409       Linux 3.13.
1411       Some  system  calls return with EINTR if a signal was sent to a tracee,
1412       but delivery was suppressed by the tracer.  (This is very typical oper‐
1413       ation: it is usually done by debuggers on every attach, in order to not
1414       introduce a bogus SIGSTOP).  As of Linux 3.2.9,  the  following  system
1415       calls are affected (this list is likely incomplete): epoll_wait(2), and
1416       read(2) from an inotify(7) file descriptor.  The usual symptom of  this
1417       bug is that when you attach to a quiescent process with the command
1419           strace -p <process-ID>
1421       then, instead of the usual and expected one-line output such as
1423           restart_syscall(<... resuming interrupted call ...>_
1425       or
1427           select(6, [5], NULL, [5], NULL_
1429       ('_' denotes the cursor position), you observe more than one line.  For
1430       example:
1432               clock_gettime(CLOCK_MONOTONIC, {15370, 690928118}) = 0
1433               epoll_wait(4,_
1435       What  is  not  visible  here  is  that  the  process  was  blocked   in
1436       epoll_wait(2)  before  strace(1)  has attached to it.  Attaching caused
1437       epoll_wait(2) to return to user space with the error  EINTR.   In  this
1438       particular  case,  the program reacted to EINTR by checking the current
1439       time, and then executing epoll_wait(2) again.  (Programs which  do  not
1440       expect  such  "stray" EINTR errors may behave in an unintended way upon
1441       an strace(1) attach.)


1444       gdb(1), ltrace(1), strace(1), clone(2), execve(2), fork(2),  gettid(2),
1445       prctl(2),  seccomp(2),  sigaction(2),  tgkill(2), vfork(2), waitpid(2),
1446       exec(3), capabilities(7), signal(7)


1449       This page is part of release 4.15 of the Linux  man-pages  project.   A
1450       description  of  the project, information about reporting bugs, and the
1451       latest    version    of    this    page,    can     be     found     at
1452       https://www.kernel.org/doc/man-pages/.
1456Linux                             2017-09-15                         PTRACE(2)