Serenity Operating System
1/*
2 * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
3 *
4 * SPDX-License-Identifier: BSD-2-Clause
5 */
6
7#include <AK/Variant.h>
8#include <Kernel/Debug.h>
9#include <Kernel/Process.h>
10
11namespace Kernel {
12
13ErrorOr<siginfo_t> Process::do_waitid(Variant<Empty, NonnullLockRefPtr<Process>, NonnullLockRefPtr<ProcessGroup>> waitee, int options)
14{
15 ErrorOr<siginfo_t> result = siginfo_t {};
16 if (Thread::current()->block<Thread::WaitBlocker>({}, options, move(waitee), result).was_interrupted())
17 return EINTR;
18 VERIFY(!result.is_error() || (options & WNOHANG));
19 return result;
20}
21
22ErrorOr<FlatPtr> Process::sys$waitid(Userspace<Syscall::SC_waitid_params const*> user_params)
23{
24 VERIFY_PROCESS_BIG_LOCK_ACQUIRED(this);
25 TRY(require_promise(Pledge::proc));
26 auto params = TRY(copy_typed_from_user(user_params));
27
28 Variant<Empty, NonnullLockRefPtr<Process>, NonnullLockRefPtr<ProcessGroup>> waitee;
29 switch (params.idtype) {
30 case P_ALL:
31 break;
32 case P_PID: {
33 auto waitee_process = Process::from_pid_in_same_jail(params.id);
34 if (!waitee_process)
35 return ECHILD;
36 bool waitee_is_child = waitee_process->ppid() == Process::current().pid();
37 bool waitee_is_our_tracee = waitee_process->has_tracee_thread(Process::current().pid());
38 if (!waitee_is_child && !waitee_is_our_tracee)
39 return ECHILD;
40 waitee = waitee_process.release_nonnull();
41 break;
42 }
43 case P_PGID: {
44 auto waitee_group = ProcessGroup::from_pgid(params.id);
45 if (!waitee_group) {
46 return ECHILD;
47 }
48 waitee = waitee_group.release_nonnull();
49 break;
50 }
51 default:
52 return EINVAL;
53 }
54
55 dbgln_if(PROCESS_DEBUG, "sys$waitid({}, {}, {}, {})", params.idtype, params.id, params.infop, params.options);
56
57 auto siginfo = TRY(do_waitid(move(waitee), params.options));
58 TRY(copy_to_user(params.infop, &siginfo));
59 return 0;
60}
61
62}