GNU Linux-libre 4.14.290-gnu1
[releases.git] / kernel / ptrace.c
1 /*
2  * linux/kernel/ptrace.c
3  *
4  * (C) Copyright 1999 Linus Torvalds
5  *
6  * Common interfaces for "ptrace()" which we do not want
7  * to continually duplicate across every architecture.
8  */
9
10 #include <linux/capability.h>
11 #include <linux/export.h>
12 #include <linux/sched.h>
13 #include <linux/sched/mm.h>
14 #include <linux/sched/coredump.h>
15 #include <linux/sched/task.h>
16 #include <linux/errno.h>
17 #include <linux/mm.h>
18 #include <linux/highmem.h>
19 #include <linux/pagemap.h>
20 #include <linux/ptrace.h>
21 #include <linux/security.h>
22 #include <linux/signal.h>
23 #include <linux/uio.h>
24 #include <linux/audit.h>
25 #include <linux/pid_namespace.h>
26 #include <linux/syscalls.h>
27 #include <linux/uaccess.h>
28 #include <linux/regset.h>
29 #include <linux/hw_breakpoint.h>
30 #include <linux/cn_proc.h>
31 #include <linux/compat.h>
32 #include <linux/sched/signal.h>
33
34 /*
35  * Access another process' address space via ptrace.
36  * Source/target buffer must be kernel space,
37  * Do not walk the page table directly, use get_user_pages
38  */
39 int ptrace_access_vm(struct task_struct *tsk, unsigned long addr,
40                      void *buf, int len, unsigned int gup_flags)
41 {
42         struct mm_struct *mm;
43         int ret;
44
45         mm = get_task_mm(tsk);
46         if (!mm)
47                 return 0;
48
49         if (!tsk->ptrace ||
50             (current != tsk->parent) ||
51             ((get_dumpable(mm) != SUID_DUMP_USER) &&
52              !ptracer_capable(tsk, mm->user_ns))) {
53                 mmput(mm);
54                 return 0;
55         }
56
57         ret = __access_remote_vm(tsk, mm, addr, buf, len, gup_flags);
58         mmput(mm);
59
60         return ret;
61 }
62
63
64 void __ptrace_link(struct task_struct *child, struct task_struct *new_parent,
65                    const struct cred *ptracer_cred)
66 {
67         BUG_ON(!list_empty(&child->ptrace_entry));
68         list_add(&child->ptrace_entry, &new_parent->ptraced);
69         child->parent = new_parent;
70         child->ptracer_cred = get_cred(ptracer_cred);
71 }
72
73 /*
74  * ptrace a task: make the debugger its new parent and
75  * move it to the ptrace list.
76  *
77  * Must be called with the tasklist lock write-held.
78  */
79 static void ptrace_link(struct task_struct *child, struct task_struct *new_parent)
80 {
81         __ptrace_link(child, new_parent, current_cred());
82 }
83
84 /**
85  * __ptrace_unlink - unlink ptracee and restore its execution state
86  * @child: ptracee to be unlinked
87  *
88  * Remove @child from the ptrace list, move it back to the original parent,
89  * and restore the execution state so that it conforms to the group stop
90  * state.
91  *
92  * Unlinking can happen via two paths - explicit PTRACE_DETACH or ptracer
93  * exiting.  For PTRACE_DETACH, unless the ptracee has been killed between
94  * ptrace_check_attach() and here, it's guaranteed to be in TASK_TRACED.
95  * If the ptracer is exiting, the ptracee can be in any state.
96  *
97  * After detach, the ptracee should be in a state which conforms to the
98  * group stop.  If the group is stopped or in the process of stopping, the
99  * ptracee should be put into TASK_STOPPED; otherwise, it should be woken
100  * up from TASK_TRACED.
101  *
102  * If the ptracee is in TASK_TRACED and needs to be moved to TASK_STOPPED,
103  * it goes through TRACED -> RUNNING -> STOPPED transition which is similar
104  * to but in the opposite direction of what happens while attaching to a
105  * stopped task.  However, in this direction, the intermediate RUNNING
106  * state is not hidden even from the current ptracer and if it immediately
107  * re-attaches and performs a WNOHANG wait(2), it may fail.
108  *
109  * CONTEXT:
110  * write_lock_irq(tasklist_lock)
111  */
112 void __ptrace_unlink(struct task_struct *child)
113 {
114         const struct cred *old_cred;
115         BUG_ON(!child->ptrace);
116
117         clear_tsk_thread_flag(child, TIF_SYSCALL_TRACE);
118
119         child->parent = child->real_parent;
120         list_del_init(&child->ptrace_entry);
121         old_cred = child->ptracer_cred;
122         child->ptracer_cred = NULL;
123         put_cred(old_cred);
124
125         spin_lock(&child->sighand->siglock);
126         child->ptrace = 0;
127         /*
128          * Clear all pending traps and TRAPPING.  TRAPPING should be
129          * cleared regardless of JOBCTL_STOP_PENDING.  Do it explicitly.
130          */
131         task_clear_jobctl_pending(child, JOBCTL_TRAP_MASK);
132         task_clear_jobctl_trapping(child);
133
134         /*
135          * Reinstate JOBCTL_STOP_PENDING if group stop is in effect and
136          * @child isn't dead.
137          */
138         if (!(child->flags & PF_EXITING) &&
139             (child->signal->flags & SIGNAL_STOP_STOPPED ||
140              child->signal->group_stop_count)) {
141                 child->jobctl |= JOBCTL_STOP_PENDING;
142
143                 /*
144                  * This is only possible if this thread was cloned by the
145                  * traced task running in the stopped group, set the signal
146                  * for the future reports.
147                  * FIXME: we should change ptrace_init_task() to handle this
148                  * case.
149                  */
150                 if (!(child->jobctl & JOBCTL_STOP_SIGMASK))
151                         child->jobctl |= SIGSTOP;
152         }
153
154         /*
155          * If transition to TASK_STOPPED is pending or in TASK_TRACED, kick
156          * @child in the butt.  Note that @resume should be used iff @child
157          * is in TASK_TRACED; otherwise, we might unduly disrupt
158          * TASK_KILLABLE sleeps.
159          */
160         if (child->jobctl & JOBCTL_STOP_PENDING || task_is_traced(child))
161                 ptrace_signal_wake_up(child, true);
162
163         spin_unlock(&child->sighand->siglock);
164 }
165
166 static bool looks_like_a_spurious_pid(struct task_struct *task)
167 {
168         if (task->exit_code != ((PTRACE_EVENT_EXEC << 8) | SIGTRAP))
169                 return false;
170
171         if (task_pid_vnr(task) == task->ptrace_message)
172                 return false;
173         /*
174          * The tracee changed its pid but the PTRACE_EVENT_EXEC event
175          * was not wait()'ed, most probably debugger targets the old
176          * leader which was destroyed in de_thread().
177          */
178         return true;
179 }
180
181 /* Ensure that nothing can wake it up, even SIGKILL */
182 static bool ptrace_freeze_traced(struct task_struct *task)
183 {
184         bool ret = false;
185
186         /* Lockless, nobody but us can set this flag */
187         if (task->jobctl & JOBCTL_LISTENING)
188                 return ret;
189
190         spin_lock_irq(&task->sighand->siglock);
191         if (task_is_traced(task) && !looks_like_a_spurious_pid(task) &&
192             !__fatal_signal_pending(task)) {
193                 task->state = __TASK_TRACED;
194                 ret = true;
195         }
196         spin_unlock_irq(&task->sighand->siglock);
197
198         return ret;
199 }
200
201 static void ptrace_unfreeze_traced(struct task_struct *task)
202 {
203         if (task->state != __TASK_TRACED)
204                 return;
205
206         WARN_ON(!task->ptrace || task->parent != current);
207
208         /*
209          * PTRACE_LISTEN can allow ptrace_trap_notify to wake us up remotely.
210          * Recheck state under the lock to close this race.
211          */
212         spin_lock_irq(&task->sighand->siglock);
213         if (task->state == __TASK_TRACED) {
214                 if (__fatal_signal_pending(task))
215                         wake_up_state(task, __TASK_TRACED);
216                 else
217                         task->state = TASK_TRACED;
218         }
219         spin_unlock_irq(&task->sighand->siglock);
220 }
221
222 /**
223  * ptrace_check_attach - check whether ptracee is ready for ptrace operation
224  * @child: ptracee to check for
225  * @ignore_state: don't check whether @child is currently %TASK_TRACED
226  *
227  * Check whether @child is being ptraced by %current and ready for further
228  * ptrace operations.  If @ignore_state is %false, @child also should be in
229  * %TASK_TRACED state and on return the child is guaranteed to be traced
230  * and not executing.  If @ignore_state is %true, @child can be in any
231  * state.
232  *
233  * CONTEXT:
234  * Grabs and releases tasklist_lock and @child->sighand->siglock.
235  *
236  * RETURNS:
237  * 0 on success, -ESRCH if %child is not ready.
238  */
239 static int ptrace_check_attach(struct task_struct *child, bool ignore_state)
240 {
241         int ret = -ESRCH;
242
243         /*
244          * We take the read lock around doing both checks to close a
245          * possible race where someone else was tracing our child and
246          * detached between these two checks.  After this locked check,
247          * we are sure that this is our traced child and that can only
248          * be changed by us so it's not changing right after this.
249          */
250         read_lock(&tasklist_lock);
251         if (child->ptrace && child->parent == current) {
252                 WARN_ON(child->state == __TASK_TRACED);
253                 /*
254                  * child->sighand can't be NULL, release_task()
255                  * does ptrace_unlink() before __exit_signal().
256                  */
257                 if (ignore_state || ptrace_freeze_traced(child))
258                         ret = 0;
259         }
260         read_unlock(&tasklist_lock);
261
262         if (!ret && !ignore_state) {
263                 if (!wait_task_inactive(child, __TASK_TRACED)) {
264                         /*
265                          * This can only happen if may_ptrace_stop() fails and
266                          * ptrace_stop() changes ->state back to TASK_RUNNING,
267                          * so we should not worry about leaking __TASK_TRACED.
268                          */
269                         WARN_ON(child->state == __TASK_TRACED);
270                         ret = -ESRCH;
271                 }
272         }
273
274         return ret;
275 }
276
277 static bool ptrace_has_cap(const struct cred *cred, struct user_namespace *ns,
278                            unsigned int mode)
279 {
280         int ret;
281
282         if (mode & PTRACE_MODE_NOAUDIT)
283                 ret = security_capable(cred, ns, CAP_SYS_PTRACE);
284         else
285                 ret = security_capable(cred, ns, CAP_SYS_PTRACE);
286
287         return ret == 0;
288 }
289
290 /* Returns 0 on success, -errno on denial. */
291 static int __ptrace_may_access(struct task_struct *task, unsigned int mode)
292 {
293         const struct cred *cred = current_cred(), *tcred;
294         struct mm_struct *mm;
295         kuid_t caller_uid;
296         kgid_t caller_gid;
297
298         if (!(mode & PTRACE_MODE_FSCREDS) == !(mode & PTRACE_MODE_REALCREDS)) {
299                 WARN(1, "denying ptrace access check without PTRACE_MODE_*CREDS\n");
300                 return -EPERM;
301         }
302
303         /* May we inspect the given task?
304          * This check is used both for attaching with ptrace
305          * and for allowing access to sensitive information in /proc.
306          *
307          * ptrace_attach denies several cases that /proc allows
308          * because setting up the necessary parent/child relationship
309          * or halting the specified task is impossible.
310          */
311
312         /* Don't let security modules deny introspection */
313         if (same_thread_group(task, current))
314                 return 0;
315         rcu_read_lock();
316         if (mode & PTRACE_MODE_FSCREDS) {
317                 caller_uid = cred->fsuid;
318                 caller_gid = cred->fsgid;
319         } else {
320                 /*
321                  * Using the euid would make more sense here, but something
322                  * in userland might rely on the old behavior, and this
323                  * shouldn't be a security problem since
324                  * PTRACE_MODE_REALCREDS implies that the caller explicitly
325                  * used a syscall that requests access to another process
326                  * (and not a filesystem syscall to procfs).
327                  */
328                 caller_uid = cred->uid;
329                 caller_gid = cred->gid;
330         }
331         tcred = __task_cred(task);
332         if (uid_eq(caller_uid, tcred->euid) &&
333             uid_eq(caller_uid, tcred->suid) &&
334             uid_eq(caller_uid, tcred->uid)  &&
335             gid_eq(caller_gid, tcred->egid) &&
336             gid_eq(caller_gid, tcred->sgid) &&
337             gid_eq(caller_gid, tcred->gid))
338                 goto ok;
339         if (ptrace_has_cap(cred, tcred->user_ns, mode))
340                 goto ok;
341         rcu_read_unlock();
342         return -EPERM;
343 ok:
344         rcu_read_unlock();
345         /*
346          * If a task drops privileges and becomes nondumpable (through a syscall
347          * like setresuid()) while we are trying to access it, we must ensure
348          * that the dumpability is read after the credentials; otherwise,
349          * we may be able to attach to a task that we shouldn't be able to
350          * attach to (as if the task had dropped privileges without becoming
351          * nondumpable).
352          * Pairs with a write barrier in commit_creds().
353          */
354         smp_rmb();
355         mm = task->mm;
356         if (mm &&
357             ((get_dumpable(mm) != SUID_DUMP_USER) &&
358              !ptrace_has_cap(cred, mm->user_ns, mode)))
359             return -EPERM;
360
361         return security_ptrace_access_check(task, mode);
362 }
363
364 bool ptrace_may_access(struct task_struct *task, unsigned int mode)
365 {
366         int err;
367         task_lock(task);
368         err = __ptrace_may_access(task, mode);
369         task_unlock(task);
370         return !err;
371 }
372
373 static int check_ptrace_options(unsigned long data)
374 {
375         if (data & ~(unsigned long)PTRACE_O_MASK)
376                 return -EINVAL;
377
378         if (unlikely(data & PTRACE_O_SUSPEND_SECCOMP)) {
379                 if (!IS_ENABLED(CONFIG_CHECKPOINT_RESTORE) ||
380                     !IS_ENABLED(CONFIG_SECCOMP))
381                         return -EINVAL;
382
383                 if (!capable(CAP_SYS_ADMIN))
384                         return -EPERM;
385
386                 if (seccomp_mode(&current->seccomp) != SECCOMP_MODE_DISABLED ||
387                     current->ptrace & PT_SUSPEND_SECCOMP)
388                         return -EPERM;
389         }
390         return 0;
391 }
392
393 static int ptrace_attach(struct task_struct *task, long request,
394                          unsigned long addr,
395                          unsigned long flags)
396 {
397         bool seize = (request == PTRACE_SEIZE);
398         int retval;
399
400         retval = -EIO;
401         if (seize) {
402                 if (addr != 0)
403                         goto out;
404                 /*
405                  * This duplicates the check in check_ptrace_options() because
406                  * ptrace_attach() and ptrace_setoptions() have historically
407                  * used different error codes for unknown ptrace options.
408                  */
409                 if (flags & ~(unsigned long)PTRACE_O_MASK)
410                         goto out;
411                 retval = check_ptrace_options(flags);
412                 if (retval)
413                         return retval;
414                 flags = PT_PTRACED | PT_SEIZED | (flags << PT_OPT_FLAG_SHIFT);
415         } else {
416                 flags = PT_PTRACED;
417         }
418
419         audit_ptrace(task);
420
421         retval = -EPERM;
422         if (unlikely(task->flags & PF_KTHREAD))
423                 goto out;
424         if (same_thread_group(task, current))
425                 goto out;
426
427         /*
428          * Protect exec's credential calculations against our interference;
429          * SUID, SGID and LSM creds get determined differently
430          * under ptrace.
431          */
432         retval = -ERESTARTNOINTR;
433         if (mutex_lock_interruptible(&task->signal->cred_guard_mutex))
434                 goto out;
435
436         task_lock(task);
437         retval = __ptrace_may_access(task, PTRACE_MODE_ATTACH_REALCREDS);
438         task_unlock(task);
439         if (retval)
440                 goto unlock_creds;
441
442         write_lock_irq(&tasklist_lock);
443         retval = -EPERM;
444         if (unlikely(task->exit_state))
445                 goto unlock_tasklist;
446         if (task->ptrace)
447                 goto unlock_tasklist;
448
449         if (seize)
450                 flags |= PT_SEIZED;
451         task->ptrace = flags;
452
453         ptrace_link(task, current);
454
455         /* SEIZE doesn't trap tracee on attach */
456         if (!seize)
457                 send_sig_info(SIGSTOP, SEND_SIG_FORCED, task);
458
459         spin_lock(&task->sighand->siglock);
460
461         /*
462          * If the task is already STOPPED, set JOBCTL_TRAP_STOP and
463          * TRAPPING, and kick it so that it transits to TRACED.  TRAPPING
464          * will be cleared if the child completes the transition or any
465          * event which clears the group stop states happens.  We'll wait
466          * for the transition to complete before returning from this
467          * function.
468          *
469          * This hides STOPPED -> RUNNING -> TRACED transition from the
470          * attaching thread but a different thread in the same group can
471          * still observe the transient RUNNING state.  IOW, if another
472          * thread's WNOHANG wait(2) on the stopped tracee races against
473          * ATTACH, the wait(2) may fail due to the transient RUNNING.
474          *
475          * The following task_is_stopped() test is safe as both transitions
476          * in and out of STOPPED are protected by siglock.
477          */
478         if (task_is_stopped(task) &&
479             task_set_jobctl_pending(task, JOBCTL_TRAP_STOP | JOBCTL_TRAPPING))
480                 signal_wake_up_state(task, __TASK_STOPPED);
481
482         spin_unlock(&task->sighand->siglock);
483
484         retval = 0;
485 unlock_tasklist:
486         write_unlock_irq(&tasklist_lock);
487 unlock_creds:
488         mutex_unlock(&task->signal->cred_guard_mutex);
489 out:
490         if (!retval) {
491                 /*
492                  * We do not bother to change retval or clear JOBCTL_TRAPPING
493                  * if wait_on_bit() was interrupted by SIGKILL. The tracer will
494                  * not return to user-mode, it will exit and clear this bit in
495                  * __ptrace_unlink() if it wasn't already cleared by the tracee;
496                  * and until then nobody can ptrace this task.
497                  */
498                 wait_on_bit(&task->jobctl, JOBCTL_TRAPPING_BIT, TASK_KILLABLE);
499                 proc_ptrace_connector(task, PTRACE_ATTACH);
500         }
501
502         return retval;
503 }
504
505 /**
506  * ptrace_traceme  --  helper for PTRACE_TRACEME
507  *
508  * Performs checks and sets PT_PTRACED.
509  * Should be used by all ptrace implementations for PTRACE_TRACEME.
510  */
511 static int ptrace_traceme(void)
512 {
513         int ret = -EPERM;
514
515         write_lock_irq(&tasklist_lock);
516         /* Are we already being traced? */
517         if (!current->ptrace) {
518                 ret = security_ptrace_traceme(current->parent);
519                 /*
520                  * Check PF_EXITING to ensure ->real_parent has not passed
521                  * exit_ptrace(). Otherwise we don't report the error but
522                  * pretend ->real_parent untraces us right after return.
523                  */
524                 if (!ret && !(current->real_parent->flags & PF_EXITING)) {
525                         current->ptrace = PT_PTRACED;
526                         ptrace_link(current, current->real_parent);
527                 }
528         }
529         write_unlock_irq(&tasklist_lock);
530
531         return ret;
532 }
533
534 /*
535  * Called with irqs disabled, returns true if childs should reap themselves.
536  */
537 static int ignoring_children(struct sighand_struct *sigh)
538 {
539         int ret;
540         spin_lock(&sigh->siglock);
541         ret = (sigh->action[SIGCHLD-1].sa.sa_handler == SIG_IGN) ||
542               (sigh->action[SIGCHLD-1].sa.sa_flags & SA_NOCLDWAIT);
543         spin_unlock(&sigh->siglock);
544         return ret;
545 }
546
547 /*
548  * Called with tasklist_lock held for writing.
549  * Unlink a traced task, and clean it up if it was a traced zombie.
550  * Return true if it needs to be reaped with release_task().
551  * (We can't call release_task() here because we already hold tasklist_lock.)
552  *
553  * If it's a zombie, our attachedness prevented normal parent notification
554  * or self-reaping.  Do notification now if it would have happened earlier.
555  * If it should reap itself, return true.
556  *
557  * If it's our own child, there is no notification to do. But if our normal
558  * children self-reap, then this child was prevented by ptrace and we must
559  * reap it now, in that case we must also wake up sub-threads sleeping in
560  * do_wait().
561  */
562 static bool __ptrace_detach(struct task_struct *tracer, struct task_struct *p)
563 {
564         bool dead;
565
566         __ptrace_unlink(p);
567
568         if (p->exit_state != EXIT_ZOMBIE)
569                 return false;
570
571         dead = !thread_group_leader(p);
572
573         if (!dead && thread_group_empty(p)) {
574                 if (!same_thread_group(p->real_parent, tracer))
575                         dead = do_notify_parent(p, p->exit_signal);
576                 else if (ignoring_children(tracer->sighand)) {
577                         __wake_up_parent(p, tracer);
578                         dead = true;
579                 }
580         }
581         /* Mark it as in the process of being reaped. */
582         if (dead)
583                 p->exit_state = EXIT_DEAD;
584         return dead;
585 }
586
587 static int ptrace_detach(struct task_struct *child, unsigned int data)
588 {
589         if (!valid_signal(data))
590                 return -EIO;
591
592         /* Architecture-specific hardware disable .. */
593         ptrace_disable(child);
594
595         write_lock_irq(&tasklist_lock);
596         /*
597          * We rely on ptrace_freeze_traced(). It can't be killed and
598          * untraced by another thread, it can't be a zombie.
599          */
600         WARN_ON(!child->ptrace || child->exit_state);
601         /*
602          * tasklist_lock avoids the race with wait_task_stopped(), see
603          * the comment in ptrace_resume().
604          */
605         child->exit_code = data;
606         __ptrace_detach(current, child);
607         write_unlock_irq(&tasklist_lock);
608
609         proc_ptrace_connector(child, PTRACE_DETACH);
610
611         return 0;
612 }
613
614 /*
615  * Detach all tasks we were using ptrace on. Called with tasklist held
616  * for writing.
617  */
618 void exit_ptrace(struct task_struct *tracer, struct list_head *dead)
619 {
620         struct task_struct *p, *n;
621
622         list_for_each_entry_safe(p, n, &tracer->ptraced, ptrace_entry) {
623                 if (unlikely(p->ptrace & PT_EXITKILL))
624                         send_sig_info(SIGKILL, SEND_SIG_FORCED, p);
625
626                 if (__ptrace_detach(tracer, p))
627                         list_add(&p->ptrace_entry, dead);
628         }
629 }
630
631 int ptrace_readdata(struct task_struct *tsk, unsigned long src, char __user *dst, int len)
632 {
633         int copied = 0;
634
635         while (len > 0) {
636                 char buf[128];
637                 int this_len, retval;
638
639                 this_len = (len > sizeof(buf)) ? sizeof(buf) : len;
640                 retval = ptrace_access_vm(tsk, src, buf, this_len, FOLL_FORCE);
641
642                 if (!retval) {
643                         if (copied)
644                                 break;
645                         return -EIO;
646                 }
647                 if (copy_to_user(dst, buf, retval))
648                         return -EFAULT;
649                 copied += retval;
650                 src += retval;
651                 dst += retval;
652                 len -= retval;
653         }
654         return copied;
655 }
656
657 int ptrace_writedata(struct task_struct *tsk, char __user *src, unsigned long dst, int len)
658 {
659         int copied = 0;
660
661         while (len > 0) {
662                 char buf[128];
663                 int this_len, retval;
664
665                 this_len = (len > sizeof(buf)) ? sizeof(buf) : len;
666                 if (copy_from_user(buf, src, this_len))
667                         return -EFAULT;
668                 retval = ptrace_access_vm(tsk, dst, buf, this_len,
669                                 FOLL_FORCE | FOLL_WRITE);
670                 if (!retval) {
671                         if (copied)
672                                 break;
673                         return -EIO;
674                 }
675                 copied += retval;
676                 src += retval;
677                 dst += retval;
678                 len -= retval;
679         }
680         return copied;
681 }
682
683 static int ptrace_setoptions(struct task_struct *child, unsigned long data)
684 {
685         unsigned flags;
686         int ret;
687
688         ret = check_ptrace_options(data);
689         if (ret)
690                 return ret;
691
692         /* Avoid intermediate state when all opts are cleared */
693         flags = child->ptrace;
694         flags &= ~(PTRACE_O_MASK << PT_OPT_FLAG_SHIFT);
695         flags |= (data << PT_OPT_FLAG_SHIFT);
696         child->ptrace = flags;
697
698         return 0;
699 }
700
701 static int ptrace_getsiginfo(struct task_struct *child, siginfo_t *info)
702 {
703         unsigned long flags;
704         int error = -ESRCH;
705
706         if (lock_task_sighand(child, &flags)) {
707                 error = -EINVAL;
708                 if (likely(child->last_siginfo != NULL)) {
709                         *info = *child->last_siginfo;
710                         error = 0;
711                 }
712                 unlock_task_sighand(child, &flags);
713         }
714         return error;
715 }
716
717 static int ptrace_setsiginfo(struct task_struct *child, const siginfo_t *info)
718 {
719         unsigned long flags;
720         int error = -ESRCH;
721
722         if (lock_task_sighand(child, &flags)) {
723                 error = -EINVAL;
724                 if (likely(child->last_siginfo != NULL)) {
725                         *child->last_siginfo = *info;
726                         error = 0;
727                 }
728                 unlock_task_sighand(child, &flags);
729         }
730         return error;
731 }
732
733 static int ptrace_peek_siginfo(struct task_struct *child,
734                                 unsigned long addr,
735                                 unsigned long data)
736 {
737         struct ptrace_peeksiginfo_args arg;
738         struct sigpending *pending;
739         struct sigqueue *q;
740         int ret, i;
741
742         ret = copy_from_user(&arg, (void __user *) addr,
743                                 sizeof(struct ptrace_peeksiginfo_args));
744         if (ret)
745                 return -EFAULT;
746
747         if (arg.flags & ~PTRACE_PEEKSIGINFO_SHARED)
748                 return -EINVAL; /* unknown flags */
749
750         if (arg.nr < 0)
751                 return -EINVAL;
752
753         /* Ensure arg.off fits in an unsigned long */
754         if (arg.off > ULONG_MAX)
755                 return 0;
756
757         if (arg.flags & PTRACE_PEEKSIGINFO_SHARED)
758                 pending = &child->signal->shared_pending;
759         else
760                 pending = &child->pending;
761
762         for (i = 0; i < arg.nr; ) {
763                 siginfo_t info;
764                 unsigned long off = arg.off + i;
765                 bool found = false;
766
767                 spin_lock_irq(&child->sighand->siglock);
768                 list_for_each_entry(q, &pending->list, list) {
769                         if (!off--) {
770                                 found = true;
771                                 copy_siginfo(&info, &q->info);
772                                 break;
773                         }
774                 }
775                 spin_unlock_irq(&child->sighand->siglock);
776
777                 if (!found) /* beyond the end of the list */
778                         break;
779
780 #ifdef CONFIG_COMPAT
781                 if (unlikely(in_compat_syscall())) {
782                         compat_siginfo_t __user *uinfo = compat_ptr(data);
783
784                         if (copy_siginfo_to_user32(uinfo, &info)) {
785                                 ret = -EFAULT;
786                                 break;
787                         }
788
789                 } else
790 #endif
791                 {
792                         siginfo_t __user *uinfo = (siginfo_t __user *) data;
793
794                         if (copy_siginfo_to_user(uinfo, &info)) {
795                                 ret = -EFAULT;
796                                 break;
797                         }
798                 }
799
800                 data += sizeof(siginfo_t);
801                 i++;
802
803                 if (signal_pending(current))
804                         break;
805
806                 cond_resched();
807         }
808
809         if (i > 0)
810                 return i;
811
812         return ret;
813 }
814
815 #ifdef PTRACE_SINGLESTEP
816 #define is_singlestep(request)          ((request) == PTRACE_SINGLESTEP)
817 #else
818 #define is_singlestep(request)          0
819 #endif
820
821 #ifdef PTRACE_SINGLEBLOCK
822 #define is_singleblock(request)         ((request) == PTRACE_SINGLEBLOCK)
823 #else
824 #define is_singleblock(request)         0
825 #endif
826
827 #ifdef PTRACE_SYSEMU
828 #define is_sysemu_singlestep(request)   ((request) == PTRACE_SYSEMU_SINGLESTEP)
829 #else
830 #define is_sysemu_singlestep(request)   0
831 #endif
832
833 static int ptrace_resume(struct task_struct *child, long request,
834                          unsigned long data)
835 {
836         bool need_siglock;
837
838         if (!valid_signal(data))
839                 return -EIO;
840
841         if (request == PTRACE_SYSCALL)
842                 set_tsk_thread_flag(child, TIF_SYSCALL_TRACE);
843         else
844                 clear_tsk_thread_flag(child, TIF_SYSCALL_TRACE);
845
846 #ifdef TIF_SYSCALL_EMU
847         if (request == PTRACE_SYSEMU || request == PTRACE_SYSEMU_SINGLESTEP)
848                 set_tsk_thread_flag(child, TIF_SYSCALL_EMU);
849         else
850                 clear_tsk_thread_flag(child, TIF_SYSCALL_EMU);
851 #endif
852
853         if (is_singleblock(request)) {
854                 if (unlikely(!arch_has_block_step()))
855                         return -EIO;
856                 user_enable_block_step(child);
857         } else if (is_singlestep(request) || is_sysemu_singlestep(request)) {
858                 if (unlikely(!arch_has_single_step()))
859                         return -EIO;
860                 user_enable_single_step(child);
861         } else {
862                 user_disable_single_step(child);
863         }
864
865         /*
866          * Change ->exit_code and ->state under siglock to avoid the race
867          * with wait_task_stopped() in between; a non-zero ->exit_code will
868          * wrongly look like another report from tracee.
869          *
870          * Note that we need siglock even if ->exit_code == data and/or this
871          * status was not reported yet, the new status must not be cleared by
872          * wait_task_stopped() after resume.
873          *
874          * If data == 0 we do not care if wait_task_stopped() reports the old
875          * status and clears the code too; this can't race with the tracee, it
876          * takes siglock after resume.
877          */
878         need_siglock = data && !thread_group_empty(current);
879         if (need_siglock)
880                 spin_lock_irq(&child->sighand->siglock);
881         child->exit_code = data;
882         wake_up_state(child, __TASK_TRACED);
883         if (need_siglock)
884                 spin_unlock_irq(&child->sighand->siglock);
885
886         return 0;
887 }
888
889 #ifdef CONFIG_HAVE_ARCH_TRACEHOOK
890
891 static const struct user_regset *
892 find_regset(const struct user_regset_view *view, unsigned int type)
893 {
894         const struct user_regset *regset;
895         int n;
896
897         for (n = 0; n < view->n; ++n) {
898                 regset = view->regsets + n;
899                 if (regset->core_note_type == type)
900                         return regset;
901         }
902
903         return NULL;
904 }
905
906 static int ptrace_regset(struct task_struct *task, int req, unsigned int type,
907                          struct iovec *kiov)
908 {
909         const struct user_regset_view *view = task_user_regset_view(task);
910         const struct user_regset *regset = find_regset(view, type);
911         int regset_no;
912
913         if (!regset || (kiov->iov_len % regset->size) != 0)
914                 return -EINVAL;
915
916         regset_no = regset - view->regsets;
917         kiov->iov_len = min(kiov->iov_len,
918                             (__kernel_size_t) (regset->n * regset->size));
919
920         if (req == PTRACE_GETREGSET)
921                 return copy_regset_to_user(task, view, regset_no, 0,
922                                            kiov->iov_len, kiov->iov_base);
923         else
924                 return copy_regset_from_user(task, view, regset_no, 0,
925                                              kiov->iov_len, kiov->iov_base);
926 }
927
928 /*
929  * This is declared in linux/regset.h and defined in machine-dependent
930  * code.  We put the export here, near the primary machine-neutral use,
931  * to ensure no machine forgets it.
932  */
933 EXPORT_SYMBOL_GPL(task_user_regset_view);
934 #endif
935
936 int ptrace_request(struct task_struct *child, long request,
937                    unsigned long addr, unsigned long data)
938 {
939         bool seized = child->ptrace & PT_SEIZED;
940         int ret = -EIO;
941         siginfo_t siginfo, *si;
942         void __user *datavp = (void __user *) data;
943         unsigned long __user *datalp = datavp;
944         unsigned long flags;
945
946         switch (request) {
947         case PTRACE_PEEKTEXT:
948         case PTRACE_PEEKDATA:
949                 return generic_ptrace_peekdata(child, addr, data);
950         case PTRACE_POKETEXT:
951         case PTRACE_POKEDATA:
952                 return generic_ptrace_pokedata(child, addr, data);
953
954 #ifdef PTRACE_OLDSETOPTIONS
955         case PTRACE_OLDSETOPTIONS:
956 #endif
957         case PTRACE_SETOPTIONS:
958                 ret = ptrace_setoptions(child, data);
959                 break;
960         case PTRACE_GETEVENTMSG:
961                 ret = put_user(child->ptrace_message, datalp);
962                 break;
963
964         case PTRACE_PEEKSIGINFO:
965                 ret = ptrace_peek_siginfo(child, addr, data);
966                 break;
967
968         case PTRACE_GETSIGINFO:
969                 ret = ptrace_getsiginfo(child, &siginfo);
970                 if (!ret)
971                         ret = copy_siginfo_to_user(datavp, &siginfo);
972                 break;
973
974         case PTRACE_SETSIGINFO:
975                 if (copy_from_user(&siginfo, datavp, sizeof siginfo))
976                         ret = -EFAULT;
977                 else
978                         ret = ptrace_setsiginfo(child, &siginfo);
979                 break;
980
981         case PTRACE_GETSIGMASK: {
982                 sigset_t *mask;
983
984                 if (addr != sizeof(sigset_t)) {
985                         ret = -EINVAL;
986                         break;
987                 }
988
989                 if (test_tsk_restore_sigmask(child))
990                         mask = &child->saved_sigmask;
991                 else
992                         mask = &child->blocked;
993
994                 if (copy_to_user(datavp, mask, sizeof(sigset_t)))
995                         ret = -EFAULT;
996                 else
997                         ret = 0;
998
999                 break;
1000         }
1001
1002         case PTRACE_SETSIGMASK: {
1003                 sigset_t new_set;
1004
1005                 if (addr != sizeof(sigset_t)) {
1006                         ret = -EINVAL;
1007                         break;
1008                 }
1009
1010                 if (copy_from_user(&new_set, datavp, sizeof(sigset_t))) {
1011                         ret = -EFAULT;
1012                         break;
1013                 }
1014
1015                 sigdelsetmask(&new_set, sigmask(SIGKILL)|sigmask(SIGSTOP));
1016
1017                 /*
1018                  * Every thread does recalc_sigpending() after resume, so
1019                  * retarget_shared_pending() and recalc_sigpending() are not
1020                  * called here.
1021                  */
1022                 spin_lock_irq(&child->sighand->siglock);
1023                 child->blocked = new_set;
1024                 spin_unlock_irq(&child->sighand->siglock);
1025
1026                 clear_tsk_restore_sigmask(child);
1027
1028                 ret = 0;
1029                 break;
1030         }
1031
1032         case PTRACE_INTERRUPT:
1033                 /*
1034                  * Stop tracee without any side-effect on signal or job
1035                  * control.  At least one trap is guaranteed to happen
1036                  * after this request.  If @child is already trapped, the
1037                  * current trap is not disturbed and another trap will
1038                  * happen after the current trap is ended with PTRACE_CONT.
1039                  *
1040                  * The actual trap might not be PTRACE_EVENT_STOP trap but
1041                  * the pending condition is cleared regardless.
1042                  */
1043                 if (unlikely(!seized || !lock_task_sighand(child, &flags)))
1044                         break;
1045
1046                 /*
1047                  * INTERRUPT doesn't disturb existing trap sans one
1048                  * exception.  If ptracer issued LISTEN for the current
1049                  * STOP, this INTERRUPT should clear LISTEN and re-trap
1050                  * tracee into STOP.
1051                  */
1052                 if (likely(task_set_jobctl_pending(child, JOBCTL_TRAP_STOP)))
1053                         ptrace_signal_wake_up(child, child->jobctl & JOBCTL_LISTENING);
1054
1055                 unlock_task_sighand(child, &flags);
1056                 ret = 0;
1057                 break;
1058
1059         case PTRACE_LISTEN:
1060                 /*
1061                  * Listen for events.  Tracee must be in STOP.  It's not
1062                  * resumed per-se but is not considered to be in TRACED by
1063                  * wait(2) or ptrace(2).  If an async event (e.g. group
1064                  * stop state change) happens, tracee will enter STOP trap
1065                  * again.  Alternatively, ptracer can issue INTERRUPT to
1066                  * finish listening and re-trap tracee into STOP.
1067                  */
1068                 if (unlikely(!seized || !lock_task_sighand(child, &flags)))
1069                         break;
1070
1071                 si = child->last_siginfo;
1072                 if (likely(si && (si->si_code >> 8) == PTRACE_EVENT_STOP)) {
1073                         child->jobctl |= JOBCTL_LISTENING;
1074                         /*
1075                          * If NOTIFY is set, it means event happened between
1076                          * start of this trap and now.  Trigger re-trap.
1077                          */
1078                         if (child->jobctl & JOBCTL_TRAP_NOTIFY)
1079                                 ptrace_signal_wake_up(child, true);
1080                         ret = 0;
1081                 }
1082                 unlock_task_sighand(child, &flags);
1083                 break;
1084
1085         case PTRACE_DETACH:      /* detach a process that was attached. */
1086                 ret = ptrace_detach(child, data);
1087                 break;
1088
1089 #ifdef CONFIG_BINFMT_ELF_FDPIC
1090         case PTRACE_GETFDPIC: {
1091                 struct mm_struct *mm = get_task_mm(child);
1092                 unsigned long tmp = 0;
1093
1094                 ret = -ESRCH;
1095                 if (!mm)
1096                         break;
1097
1098                 switch (addr) {
1099                 case PTRACE_GETFDPIC_EXEC:
1100                         tmp = mm->context.exec_fdpic_loadmap;
1101                         break;
1102                 case PTRACE_GETFDPIC_INTERP:
1103                         tmp = mm->context.interp_fdpic_loadmap;
1104                         break;
1105                 default:
1106                         break;
1107                 }
1108                 mmput(mm);
1109
1110                 ret = put_user(tmp, datalp);
1111                 break;
1112         }
1113 #endif
1114
1115 #ifdef PTRACE_SINGLESTEP
1116         case PTRACE_SINGLESTEP:
1117 #endif
1118 #ifdef PTRACE_SINGLEBLOCK
1119         case PTRACE_SINGLEBLOCK:
1120 #endif
1121 #ifdef PTRACE_SYSEMU
1122         case PTRACE_SYSEMU:
1123         case PTRACE_SYSEMU_SINGLESTEP:
1124 #endif
1125         case PTRACE_SYSCALL:
1126         case PTRACE_CONT:
1127                 return ptrace_resume(child, request, data);
1128
1129         case PTRACE_KILL:
1130                 send_sig_info(SIGKILL, SEND_SIG_NOINFO, child);
1131                 return 0;
1132
1133 #ifdef CONFIG_HAVE_ARCH_TRACEHOOK
1134         case PTRACE_GETREGSET:
1135         case PTRACE_SETREGSET: {
1136                 struct iovec kiov;
1137                 struct iovec __user *uiov = datavp;
1138
1139                 if (!access_ok(VERIFY_WRITE, uiov, sizeof(*uiov)))
1140                         return -EFAULT;
1141
1142                 if (__get_user(kiov.iov_base, &uiov->iov_base) ||
1143                     __get_user(kiov.iov_len, &uiov->iov_len))
1144                         return -EFAULT;
1145
1146                 ret = ptrace_regset(child, request, addr, &kiov);
1147                 if (!ret)
1148                         ret = __put_user(kiov.iov_len, &uiov->iov_len);
1149                 break;
1150         }
1151 #endif
1152
1153         case PTRACE_SECCOMP_GET_FILTER:
1154                 ret = seccomp_get_filter(child, addr, datavp);
1155                 break;
1156
1157         default:
1158                 break;
1159         }
1160
1161         return ret;
1162 }
1163
1164 static struct task_struct *ptrace_get_task_struct(pid_t pid)
1165 {
1166         struct task_struct *child;
1167
1168         rcu_read_lock();
1169         child = find_task_by_vpid(pid);
1170         if (child)
1171                 get_task_struct(child);
1172         rcu_read_unlock();
1173
1174         if (!child)
1175                 return ERR_PTR(-ESRCH);
1176         return child;
1177 }
1178
1179 #ifndef arch_ptrace_attach
1180 #define arch_ptrace_attach(child)       do { } while (0)
1181 #endif
1182
1183 SYSCALL_DEFINE4(ptrace, long, request, long, pid, unsigned long, addr,
1184                 unsigned long, data)
1185 {
1186         struct task_struct *child;
1187         long ret;
1188
1189         if (request == PTRACE_TRACEME) {
1190                 ret = ptrace_traceme();
1191                 if (!ret)
1192                         arch_ptrace_attach(current);
1193                 goto out;
1194         }
1195
1196         child = ptrace_get_task_struct(pid);
1197         if (IS_ERR(child)) {
1198                 ret = PTR_ERR(child);
1199                 goto out;
1200         }
1201
1202         if (request == PTRACE_ATTACH || request == PTRACE_SEIZE) {
1203                 ret = ptrace_attach(child, request, addr, data);
1204                 /*
1205                  * Some architectures need to do book-keeping after
1206                  * a ptrace attach.
1207                  */
1208                 if (!ret)
1209                         arch_ptrace_attach(child);
1210                 goto out_put_task_struct;
1211         }
1212
1213         ret = ptrace_check_attach(child, request == PTRACE_KILL ||
1214                                   request == PTRACE_INTERRUPT);
1215         if (ret < 0)
1216                 goto out_put_task_struct;
1217
1218         ret = arch_ptrace(child, request, addr, data);
1219         if (ret || request != PTRACE_DETACH)
1220                 ptrace_unfreeze_traced(child);
1221
1222  out_put_task_struct:
1223         put_task_struct(child);
1224  out:
1225         return ret;
1226 }
1227
1228 int generic_ptrace_peekdata(struct task_struct *tsk, unsigned long addr,
1229                             unsigned long data)
1230 {
1231         unsigned long tmp;
1232         int copied;
1233
1234         copied = ptrace_access_vm(tsk, addr, &tmp, sizeof(tmp), FOLL_FORCE);
1235         if (copied != sizeof(tmp))
1236                 return -EIO;
1237         return put_user(tmp, (unsigned long __user *)data);
1238 }
1239
1240 int generic_ptrace_pokedata(struct task_struct *tsk, unsigned long addr,
1241                             unsigned long data)
1242 {
1243         int copied;
1244
1245         copied = ptrace_access_vm(tsk, addr, &data, sizeof(data),
1246                         FOLL_FORCE | FOLL_WRITE);
1247         return (copied == sizeof(data)) ? 0 : -EIO;
1248 }
1249
1250 #if defined CONFIG_COMPAT
1251
1252 int compat_ptrace_request(struct task_struct *child, compat_long_t request,
1253                           compat_ulong_t addr, compat_ulong_t data)
1254 {
1255         compat_ulong_t __user *datap = compat_ptr(data);
1256         compat_ulong_t word;
1257         siginfo_t siginfo;
1258         int ret;
1259
1260         switch (request) {
1261         case PTRACE_PEEKTEXT:
1262         case PTRACE_PEEKDATA:
1263                 ret = ptrace_access_vm(child, addr, &word, sizeof(word),
1264                                 FOLL_FORCE);
1265                 if (ret != sizeof(word))
1266                         ret = -EIO;
1267                 else
1268                         ret = put_user(word, datap);
1269                 break;
1270
1271         case PTRACE_POKETEXT:
1272         case PTRACE_POKEDATA:
1273                 ret = ptrace_access_vm(child, addr, &data, sizeof(data),
1274                                 FOLL_FORCE | FOLL_WRITE);
1275                 ret = (ret != sizeof(data) ? -EIO : 0);
1276                 break;
1277
1278         case PTRACE_GETEVENTMSG:
1279                 ret = put_user((compat_ulong_t) child->ptrace_message, datap);
1280                 break;
1281
1282         case PTRACE_GETSIGINFO:
1283                 ret = ptrace_getsiginfo(child, &siginfo);
1284                 if (!ret)
1285                         ret = copy_siginfo_to_user32(
1286                                 (struct compat_siginfo __user *) datap,
1287                                 &siginfo);
1288                 break;
1289
1290         case PTRACE_SETSIGINFO:
1291                 memset(&siginfo, 0, sizeof siginfo);
1292                 if (copy_siginfo_from_user32(
1293                             &siginfo, (struct compat_siginfo __user *) datap))
1294                         ret = -EFAULT;
1295                 else
1296                         ret = ptrace_setsiginfo(child, &siginfo);
1297                 break;
1298 #ifdef CONFIG_HAVE_ARCH_TRACEHOOK
1299         case PTRACE_GETREGSET:
1300         case PTRACE_SETREGSET:
1301         {
1302                 struct iovec kiov;
1303                 struct compat_iovec __user *uiov =
1304                         (struct compat_iovec __user *) datap;
1305                 compat_uptr_t ptr;
1306                 compat_size_t len;
1307
1308                 if (!access_ok(VERIFY_WRITE, uiov, sizeof(*uiov)))
1309                         return -EFAULT;
1310
1311                 if (__get_user(ptr, &uiov->iov_base) ||
1312                     __get_user(len, &uiov->iov_len))
1313                         return -EFAULT;
1314
1315                 kiov.iov_base = compat_ptr(ptr);
1316                 kiov.iov_len = len;
1317
1318                 ret = ptrace_regset(child, request, addr, &kiov);
1319                 if (!ret)
1320                         ret = __put_user(kiov.iov_len, &uiov->iov_len);
1321                 break;
1322         }
1323 #endif
1324
1325         default:
1326                 ret = ptrace_request(child, request, addr, data);
1327         }
1328
1329         return ret;
1330 }
1331
1332 COMPAT_SYSCALL_DEFINE4(ptrace, compat_long_t, request, compat_long_t, pid,
1333                        compat_long_t, addr, compat_long_t, data)
1334 {
1335         struct task_struct *child;
1336         long ret;
1337
1338         if (request == PTRACE_TRACEME) {
1339                 ret = ptrace_traceme();
1340                 goto out;
1341         }
1342
1343         child = ptrace_get_task_struct(pid);
1344         if (IS_ERR(child)) {
1345                 ret = PTR_ERR(child);
1346                 goto out;
1347         }
1348
1349         if (request == PTRACE_ATTACH || request == PTRACE_SEIZE) {
1350                 ret = ptrace_attach(child, request, addr, data);
1351                 /*
1352                  * Some architectures need to do book-keeping after
1353                  * a ptrace attach.
1354                  */
1355                 if (!ret)
1356                         arch_ptrace_attach(child);
1357                 goto out_put_task_struct;
1358         }
1359
1360         ret = ptrace_check_attach(child, request == PTRACE_KILL ||
1361                                   request == PTRACE_INTERRUPT);
1362         if (!ret) {
1363                 ret = compat_arch_ptrace(child, request, addr, data);
1364                 if (ret || request != PTRACE_DETACH)
1365                         ptrace_unfreeze_traced(child);
1366         }
1367
1368  out_put_task_struct:
1369         put_task_struct(child);
1370  out:
1371         return ret;
1372 }
1373 #endif  /* CONFIG_COMPAT */