• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2022 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 
17 #include <stdlib.h>
18 #include <sys/capability.h>
19 #include <sys/resource.h>
20 #include <unistd.h>
21 
22 #include <filesystem>
23 #include <iostream>
24 #include <iterator>
25 #include <optional>
26 #include <string>
27 #include <string_view>
28 #include <system_error>
29 #include <unordered_map>
30 #include <unordered_set>
31 #include <vector>
32 
33 #include "android-base/logging.h"
34 #include "android-base/parseint.h"
35 #include "android-base/result.h"
36 #include "android-base/strings.h"
37 #include "base/macros.h"
38 #include "base/scoped_cap.h"
39 #include "fmt/format.h"
40 #include "palette/palette.h"
41 #include "system/thread_defs.h"
42 
43 namespace {
44 
45 using ::android::base::ConsumePrefix;
46 using ::android::base::Join;
47 using ::android::base::ParseInt;
48 using ::android::base::Result;
49 using ::android::base::Split;
50 
51 using ::fmt::literals::operator""_format;  // NOLINT
52 
53 constexpr const char* kUsage =
54     R"(A wrapper binary that configures the process and executes a command.
55 
56 By default, it closes all open file descriptors except stdin, stdout, and stderr. `--keep-fds` can
57 be passed to keep some more file descriptors open.
58 
59 Usage: art_exec [OPTIONS]... -- [COMMAND]...
60 
61 Supported options:
62   --help: Print this text.
63   --set-task-profile=PROFILES: Apply a set of task profiles (see
64       https://source.android.com/devices/tech/perf/cgroups). Requires root access. PROFILES can be a
65       comma-separated list of task profile names.
66   --set-priority=PRIORITY: Apply the process priority. Currently, the only supported value of
67       PRIORITY is "background".
68   --drop-capabilities: Drop all root capabilities. Note that this has effect only if `art_exec` runs
69       with some root capabilities but not as the root user.
70   --keep-fds=FILE_DESCRIPTORS: A semicolon-separated list of file descriptors to keep open.
71   --env=KEY=VALUE: Set an environment variable. This flag can be passed multiple times to set
72       multiple environment variables.
73 )";
74 
75 constexpr int kErrorUsage = 100;
76 constexpr int kErrorOther = 101;
77 
78 struct Options {
79   int command_pos = -1;
80   std::vector<std::string> task_profiles;
81   std::optional<int> priority = std::nullopt;
82   bool drop_capabilities = false;
83   std::unordered_set<int> keep_fds{fileno(stdin), fileno(stdout), fileno(stderr)};
84   std::unordered_map<std::string, std::string> envs;
85 };
86 
Usage(const std::string & error_msg)87 [[noreturn]] void Usage(const std::string& error_msg) {
88   LOG(ERROR) << error_msg;
89   std::cerr << error_msg << "\n" << kUsage << "\n";
90   exit(kErrorUsage);
91 }
92 
ParseOptions(int argc,char ** argv)93 Options ParseOptions(int argc, char** argv) {
94   Options options;
95   for (int i = 1; i < argc; i++) {
96     std::string_view arg = argv[i];
97     if (arg == "--help") {
98       std::cerr << kUsage << "\n";
99       exit(0);
100     } else if (ConsumePrefix(&arg, "--set-task-profile=")) {
101       options.task_profiles = Split(std::string(arg), ",");
102       if (options.task_profiles.empty()) {
103         Usage("Empty task profile list");
104       }
105     } else if (ConsumePrefix(&arg, "--set-priority=")) {
106       if (arg == "background") {
107         options.priority = ANDROID_PRIORITY_BACKGROUND;
108       } else {
109         Usage("Unknown priority " + std::string(arg));
110       }
111     } else if (arg == "--drop-capabilities") {
112       options.drop_capabilities = true;
113     } else if (ConsumePrefix(&arg, "--keep-fds=")) {
114       for (const std::string& fd_str : Split(std::string(arg), ":")) {
115         int fd;
116         if (!ParseInt(fd_str, &fd)) {
117           Usage("Invalid fd " + fd_str);
118         }
119         options.keep_fds.insert(fd);
120       }
121     } else if (ConsumePrefix(&arg, "--env=")) {
122       size_t pos = arg.find('=');
123       if (pos == std::string_view::npos) {
124         Usage("Malformed environment variable. Must contain '='");
125       }
126       options.envs[std::string(arg.substr(/*pos=*/0, /*n=*/pos))] =
127           std::string(arg.substr(pos + 1));
128     } else if (arg == "--") {
129       if (i + 1 >= argc) {
130         Usage("Missing command after '--'");
131       }
132       options.command_pos = i + 1;
133       return options;
134     } else {
135       Usage("Unknown option " + std::string(arg));
136     }
137   }
138   Usage("Missing '--'");
139 }
140 
DropInheritableCaps()141 Result<void> DropInheritableCaps() {
142   art::ScopedCap cap(cap_get_proc());
143   if (cap.Get() == nullptr) {
144     return ErrnoErrorf("Failed to call cap_get_proc");
145   }
146   if (cap_clear_flag(cap.Get(), CAP_INHERITABLE) != 0) {
147     return ErrnoErrorf("Failed to call cap_clear_flag");
148   }
149   if (cap_set_proc(cap.Get()) != 0) {
150     return ErrnoErrorf("Failed to call cap_set_proc");
151   }
152   return {};
153 }
154 
CloseFds(const std::unordered_set<int> & keep_fds)155 Result<void> CloseFds(const std::unordered_set<int>& keep_fds) {
156   std::vector<int> open_fds;
157   std::error_code ec;
158   for (const std::filesystem::directory_entry& dir_entry :
159        std::filesystem::directory_iterator("/proc/self/fd", ec)) {
160     int fd;
161     if (!ParseInt(dir_entry.path().filename(), &fd)) {
162       return Errorf("Invalid entry in /proc/self/fd {}", dir_entry.path().filename());
163     }
164     open_fds.push_back(fd);
165   }
166   if (ec) {
167     return Errorf("Failed to list open FDs: {}", ec.message());
168   }
169   for (int fd : open_fds) {
170     if (keep_fds.find(fd) == keep_fds.end()) {
171       if (close(fd) != 0) {
172         Result<void> error = ErrnoErrorf("Failed to close FD {}", fd);
173         if (std::filesystem::exists("/proc/self/fd/{}"_format(fd))) {
174           return error;
175         }
176       }
177     }
178   }
179   return {};
180 }
181 
182 }  // namespace
183 
main(int argc,char ** argv)184 int main(int argc, char** argv) {
185   android::base::InitLogging(argv);
186 
187   Options options = ParseOptions(argc, argv);
188 
189   if (auto result = CloseFds(options.keep_fds); !result.ok()) {
190     LOG(ERROR) << "Failed to close open FDs: " << result.error();
191     return kErrorOther;
192   }
193 
194   if (!options.task_profiles.empty()) {
195     if (int ret = PaletteSetTaskProfiles(/*tid=*/0, options.task_profiles);
196         ret != PALETTE_STATUS_OK) {
197       LOG(ERROR) << "Failed to set task profile: " << ret;
198       return kErrorOther;
199     }
200   }
201 
202   if (options.priority.has_value()) {
203     if (setpriority(PRIO_PROCESS, /*who=*/0, options.priority.value()) != 0) {
204       PLOG(ERROR) << "Failed to setpriority";
205       return kErrorOther;
206     }
207   }
208 
209   if (options.drop_capabilities) {
210     if (auto result = DropInheritableCaps(); !result.ok()) {
211       LOG(ERROR) << "Failed to drop inheritable capabilities: " << result.error();
212       return kErrorOther;
213     }
214   }
215 
216   for (const auto& [key, value] : options.envs) {
217     setenv(key.c_str(), value.c_str(), /*overwrite=*/1);
218   }
219 
220   execv(argv[options.command_pos], argv + options.command_pos);
221 
222   std::vector<const char*> command_args(argv + options.command_pos, argv + argc);
223   PLOG(FATAL) << "Failed to execute (" << Join(command_args, ' ') << ")";
224   UNREACHABLE();
225 }
226