blob: e20d89227395d72673261a5225ab9701497e9d6e [file] [log] [blame]
Suren Baghdasaryan7c3addb2021-06-11 12:12:56 -07001/*
2 * Copyright 2021 Google, Inc
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#pragma once
18
19#include <condition_variable>
20#include <mutex>
21#include <vector>
22
23class Reaper {
24public:
25 struct target_proc {
26 int pidfd;
27 int pid;
Suren Baghdasaryan2bdf7f02022-01-20 18:48:52 -080028 uid_t uid;
Suren Baghdasaryan7c3addb2021-06-11 12:12:56 -070029 };
30private:
31 // mutex_ and cond_ are used to wakeup the reaper thread.
32 std::mutex mutex_;
33 std::condition_variable cond_;
34 // mutex_ protects queue_ and active_requests_ access.
35 std::vector<struct target_proc> queue_;
36 int active_requests_;
37 // write side of the pipe to communicate kill failures with the main thread
38 int comm_fd_;
39 int thread_cnt_;
40 pthread_t* thread_pool_;
41 bool debug_enabled_;
42
43 bool async_kill(const struct target_proc& target);
44public:
45 Reaper() : active_requests_(0), thread_cnt_(0), debug_enabled_(false) {}
46
47 static bool is_reaping_supported();
48
49 bool init(int comm_fd);
50 int thread_cnt() const { return thread_cnt_; }
51 void enable_debug(bool enable) { debug_enabled_ = enable; }
52 bool debug_enabled() const { return debug_enabled_; }
53
54 // return 0 on success or error code returned by the syscall
Suren Baghdasaryanaf1b0e02021-11-16 11:50:29 -080055 int kill(const struct target_proc& target, bool synchronous);
Suren Baghdasaryan7c3addb2021-06-11 12:12:56 -070056 // below members are used only by reaper_main
57 target_proc dequeue_request();
58 void request_complete();
59 void notify_kill_failure(int pid);
60};