1 /*
2  * Copyright (C) 2024 The Android Open Source Project
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 #ifndef ANDROID_DEVICE_GOOGLE_CUTTLEFISH_HOST_COMMANDS_SANDBOX_PROCESS_PIDFD_H
17 #define ANDROID_DEVICE_GOOGLE_CUTTLEFISH_HOST_COMMANDS_SANDBOX_PROCESS_PIDFD_H
18 
19 #include <sys/types.h>
20 
21 #include <utility>
22 #include <vector>
23 
24 #include <absl/status/statusor.h>
25 #include <absl/types/span.h>
26 
27 #include "host/commands/process_sandboxer/unique_fd.h"
28 
29 namespace cuttlefish {
30 namespace process_sandboxer {
31 
32 class PidFd {
33  public:
34   /** Returns a managed pidfd tracking a previously started process with `pid`.
35    *
36    * Only reliably refers to the process `pid` if the caller can guarantee it
37    * was not reaped while this is executing, otherwise it may refer to an
38    * unknown process. */
39   static absl::StatusOr<PidFd> FromRunningProcess(pid_t pid);
40 
41   /** Launches a subprocess and returns a pidfd tracking the newly launched
42    * process. */
43   static absl::StatusOr<PidFd> LaunchSubprocess(
44       absl::Span<const std::string> argv,
45       std::vector<std::pair<UniqueFd, int>> fds,
46       absl::Span<const std::string> env);
47 
48   int Get() const;
49 
50   /** Copies file descriptors from the target process, mapping them into the
51    * current process.
52    *
53    * Keys are file descriptor numbers in the target process, values are open
54    * file descriptors in the current process.
55    */
56   absl::StatusOr<std::vector<std::pair<UniqueFd, int>>> AllFds();
57   absl::StatusOr<std::vector<std::string>> Argv();
58   absl::StatusOr<std::vector<std::string>> Env();
59 
60   /** Halt the process and all its descendants. */
61   absl::Status HaltHierarchy();
62   /** Halt all descendants of the process. Only safe to use if the caller
63    * guarantees the process doesn't spawn or reap any children while running. */
64   absl::Status HaltChildHierarchy();
65 
66  private:
67   PidFd(UniqueFd, pid_t);
68   absl::Status SendSignal(int signal);
69 
70   UniqueFd fd_;
71   pid_t pid_;
72 };
73 
74 }  // namespace process_sandboxer
75 }  // namespace cuttlefish
76 #endif
77