• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 #include <sandboxed_api/util/fileops.h>
27 
28 namespace cuttlefish::process_sandboxer {
29 
30 class PidFd {
31  public:
32   /** Returns a managed pidfd tracking a previously started process with `pid`.
33    *
34    * Only reliably refers to the process `pid` if the caller can guarantee it
35    * was not reaped while this is executing, otherwise it may refer to an
36    * unknown process. */
37   static absl::StatusOr<PidFd> FromRunningProcess(pid_t pid);
38 
39   /** Launches a subprocess and returns a pidfd tracking the newly launched
40    * process. */
41   static absl::StatusOr<PidFd> LaunchSubprocess(
42       absl::Span<const std::string> argv,
43       std::vector<std::pair<sapi::file_util::fileops::FDCloser, int>> fds,
44       absl::Span<const std::string> env);
45 
46   int Get() const;
47 
48   /** Copies file descriptors from the target process, mapping them into the
49    * current process.
50    *
51    * Keys are file descriptor numbers in the target process, values are open
52    * file descriptors in the current process.
53    */
54   absl::StatusOr<
55       std::vector<std::pair<sapi::file_util::fileops::FDCloser, int>>>
56   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(sapi::file_util::fileops::FDCloser, pid_t);
68   absl::Status SendSignal(int signal);
69 
70   sapi::file_util::fileops::FDCloser fd_;
71   pid_t pid_;
72 };
73 
74 }  // namespace cuttlefish::process_sandboxer
75 #endif
76