• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2011 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 "exec_utils.h"
18 
19 #include <sys/utsname.h>
20 
21 #include <csignal>
22 #include <cstring>
23 #include <filesystem>
24 #include <memory>
25 #include <tuple>
26 
27 #include "android-base/logging.h"
28 #include "android-base/stringprintf.h"
29 #include "base/file_utils.h"
30 #include "base/memory_tool.h"
31 #include "common_runtime_test.h"
32 #include "gmock/gmock.h"
33 #include "gtest/gtest.h"
34 
35 namespace art {
36 
37 using ::testing::_;
38 using ::testing::AllOf;
39 using ::testing::Gt;
40 using ::testing::HasSubstr;
41 using ::testing::InSequence;
42 using ::testing::MockFunction;
43 using ::testing::Ne;
44 using ::testing::Return;
45 
46 std::string PrettyArguments(const char* signature);
47 std::string PrettyReturnType(const char* signature);
48 
GetBin(const std::string & name)49 std::string GetBin(const std::string& name) {
50   if (kIsTargetBuild) {
51     std::string android_root(GetAndroidRoot());
52     return android_root + "/bin/" + name;
53   } else if (std::filesystem::exists("/usr/bin/" + name)) {
54     return "/usr/bin/" + name;
55   } else {
56     return "/bin/" + name;
57   }
58 }
59 
GetKernelVersion()60 std::tuple<int, int> GetKernelVersion() {
61   std::tuple<int, int> version;
62   utsname uts;
63   CHECK_EQ(uname(&uts), 0);
64   CHECK_EQ(sscanf(uts.release, "%d.%d", &std::get<0>(version), &std::get<1>(version)), 2);
65   return version;
66 }
67 
68 class TestingExecUtils : public ExecUtils {
69  public:
70   MOCK_METHOD(std::string, GetProcStat, (pid_t pid), (const, override));
71   MOCK_METHOD(int64_t, GetUptimeMs, (), (const, override));
72   MOCK_METHOD(int64_t, GetTicksPerSec, (), (const, override));
73 };
74 
75 class AlwaysFallbackExecUtils : public TestingExecUtils {
76  protected:
PidfdOpen(pid_t) const77   android::base::unique_fd PidfdOpen(pid_t) const override { return android::base::unique_fd(-1); }
78 };
79 
80 class NeverFallbackExecUtils : public TestingExecUtils {
81  protected:
PidfdOpen(pid_t pid) const82   android::base::unique_fd PidfdOpen(pid_t pid) const override {
83     android::base::unique_fd pidfd = ExecUtils::PidfdOpen(pid);
84     CHECK_GE(pidfd.get(), 0) << strerror(errno);
85     return pidfd;
86   }
87 };
88 
89 class ExecUtilsTest : public CommonRuntimeTest, public testing::WithParamInterface<bool> {
90  protected:
SetUp()91   void SetUp() override {
92     CommonRuntimeTest::SetUp();
93     bool always_fallback = GetParam();
94     if (always_fallback) {
95       exec_utils_ = std::make_unique<AlwaysFallbackExecUtils>();
96     } else {
97       if (GetKernelVersion() >= std::make_tuple(5, 4)) {
98         exec_utils_ = std::make_unique<NeverFallbackExecUtils>();
99       } else {
100         GTEST_SKIP() << "Kernel version older than 5.4";
101       }
102     }
103   }
104 
105   std::unique_ptr<TestingExecUtils> exec_utils_;
106 };
107 
TEST_P(ExecUtilsTest,ExecSuccess)108 TEST_P(ExecUtilsTest, ExecSuccess) {
109   std::vector<std::string> command;
110   command.push_back(GetBin("id"));
111   std::string error_msg;
112   // Historical note: Running on Valgrind failed due to some memory
113   // that leaks in thread alternate signal stacks.
114   EXPECT_TRUE(exec_utils_->Exec(command, &error_msg));
115   EXPECT_EQ(0U, error_msg.size()) << error_msg;
116 }
117 
TEST_P(ExecUtilsTest,ExecError)118 TEST_P(ExecUtilsTest, ExecError) {
119   std::vector<std::string> command;
120   command.push_back("bogus");
121   std::string error_msg;
122   // Historical note: Running on Valgrind failed due to some memory
123   // that leaks in thread alternate signal stacks.
124   ExecResult result = exec_utils_->ExecAndReturnResult(command, /*timeout_sec=*/-1, &error_msg);
125   EXPECT_EQ(result.status, ExecResult::kSignaled);
126   EXPECT_EQ(result.signal, SIGABRT);
127   EXPECT_FALSE(error_msg.empty());
128 }
129 
TEST_P(ExecUtilsTest,EnvSnapshotAdditionsAreNotVisible)130 TEST_P(ExecUtilsTest, EnvSnapshotAdditionsAreNotVisible) {
131   static constexpr const char* kModifiedVariable = "EXEC_SHOULD_NOT_EXPORT_THIS";
132   static constexpr int kOverwrite = 1;
133   // Set an variable in the current environment.
134   EXPECT_EQ(setenv(kModifiedVariable, "NEVER", kOverwrite), 0);
135   // Test that it is not exported.
136   std::vector<std::string> command;
137   command.push_back(GetBin("printenv"));
138   command.push_back(kModifiedVariable);
139   std::string error_msg;
140   // Historical note: Running on Valgrind failed due to some memory
141   // that leaks in thread alternate signal stacks.
142   EXPECT_FALSE(exec_utils_->Exec(command, &error_msg));
143   EXPECT_NE(0U, error_msg.size()) << error_msg;
144 }
145 
TEST_P(ExecUtilsTest,EnvSnapshotDeletionsAreNotVisible)146 TEST_P(ExecUtilsTest, EnvSnapshotDeletionsAreNotVisible) {
147   static constexpr const char* kDeletedVariable = "PATH";
148   static constexpr int kOverwrite = 1;
149   // Save the variable's value.
150   const char* save_value = getenv(kDeletedVariable);
151   EXPECT_NE(save_value, nullptr);
152   // Delete the variable.
153   EXPECT_EQ(unsetenv(kDeletedVariable), 0);
154   // Test that it is not exported.
155   std::vector<std::string> command;
156   command.push_back(GetBin("printenv"));
157   command.push_back(kDeletedVariable);
158   std::string error_msg;
159   // Historical note: Running on Valgrind failed due to some memory
160   // that leaks in thread alternate signal stacks.
161   EXPECT_TRUE(exec_utils_->Exec(command, &error_msg));
162   EXPECT_EQ(0U, error_msg.size()) << error_msg;
163   // Restore the variable's value.
164   EXPECT_EQ(setenv(kDeletedVariable, save_value, kOverwrite), 0);
165 }
166 
SleepCommand(int sleep_seconds)167 static std::vector<std::string> SleepCommand(int sleep_seconds) {
168   std::vector<std::string> command;
169   command.push_back(GetBin("sleep"));
170   command.push_back(android::base::StringPrintf("%d", sleep_seconds));
171   return command;
172 }
173 
TEST_P(ExecUtilsTest,ExecTimeout)174 TEST_P(ExecUtilsTest, ExecTimeout) {
175   static constexpr int kSleepSeconds = 5;
176   static constexpr int kWaitSeconds = 1;
177   std::vector<std::string> command = SleepCommand(kSleepSeconds);
178   std::string error_msg;
179   EXPECT_EQ(exec_utils_->ExecAndReturnResult(command, kWaitSeconds, &error_msg).status,
180             ExecResult::kTimedOut)
181       << error_msg;
182   EXPECT_THAT(error_msg, HasSubstr("timed out"));
183 }
184 
TEST_P(ExecUtilsTest,ExecNoTimeout)185 TEST_P(ExecUtilsTest, ExecNoTimeout) {
186   static constexpr int kSleepSeconds = 1;
187   static constexpr int kWaitSeconds = 5;
188   std::vector<std::string> command = SleepCommand(kSleepSeconds);
189   std::string error_msg;
190   EXPECT_EQ(exec_utils_->ExecAndReturnResult(command, kWaitSeconds, &error_msg).status,
191             ExecResult::kExited)
192       << error_msg;
193 }
194 
TEST_P(ExecUtilsTest,ExecStat)195 TEST_P(ExecUtilsTest, ExecStat) {
196   std::vector<std::string> command;
197   command.push_back(GetBin("id"));
198 
199   std::string error_msg;
200   ProcessStat stat;
201 
202   // The process filename is "a) b".
203   EXPECT_CALL(*exec_utils_, GetProcStat(_))
204       .WillOnce(Return(
205           "14963 (a) b) Z 6067 14963 1 0 -1 4228108 105 0 0 0 94 5 0 0 39 19 1 0 162034388 0 0 "
206           "18446744073709551615 0 0 0 0 0 0 20999 0 0 1 0 0 17 71 0 0 0 0 0 0 0 0 0 0 0 0 9"));
207   EXPECT_CALL(*exec_utils_, GetUptimeMs()).WillOnce(Return(1620344887ll));
208   EXPECT_CALL(*exec_utils_, GetTicksPerSec()).WillOnce(Return(100));
209 
210   ASSERT_EQ(
211       exec_utils_
212           ->ExecAndReturnResult(command, /*timeout_sec=*/-1, ExecCallbacks(), &stat, &error_msg)
213           .status,
214       ExecResult::kExited)
215       << error_msg;
216 
217   EXPECT_EQ(stat.cpu_time_ms, 990);
218   EXPECT_EQ(stat.wall_time_ms, 1007);
219 }
220 
TEST_P(ExecUtilsTest,ExecStatFailed)221 TEST_P(ExecUtilsTest, ExecStatFailed) {
222   std::vector<std::string> command = SleepCommand(5);
223 
224   std::string error_msg;
225   ProcessStat stat;
226 
227   EXPECT_CALL(*exec_utils_, GetProcStat(_))
228       .WillOnce(Return(
229           "14963 (a) b) Z 6067 14963 1 0 -1 4228108 105 0 0 0 94 5 0 0 39 19 1 0 162034388 0 0 "
230           "18446744073709551615 0 0 0 0 0 0 20999 0 0 1 0 0 17 71 0 0 0 0 0 0 0 0 0 0 0 0 9"));
231   EXPECT_CALL(*exec_utils_, GetUptimeMs()).WillOnce(Return(1620344887ll));
232   EXPECT_CALL(*exec_utils_, GetTicksPerSec()).WillOnce(Return(100));
233 
234   // This will always time out.
235   ASSERT_EQ(
236       exec_utils_
237           ->ExecAndReturnResult(command, /*timeout_sec=*/1, ExecCallbacks(), &stat, &error_msg)
238           .status,
239       ExecResult::kTimedOut);
240 
241   EXPECT_EQ(stat.cpu_time_ms, 990);
242   EXPECT_EQ(stat.wall_time_ms, 1007);
243 }
244 
TEST_P(ExecUtilsTest,ExecCallbacks)245 TEST_P(ExecUtilsTest, ExecCallbacks) {
246   MockFunction<void(pid_t)> on_start;
247   MockFunction<void(pid_t)> on_end;
248 
249   {
250     InSequence s;
251     EXPECT_CALL(on_start, Call(AllOf(Gt(0), Ne(getpid()))));
252     EXPECT_CALL(on_end, Call(AllOf(Gt(0), Ne(getpid()))));
253   }
254 
255   std::vector<std::string> command;
256   command.push_back(GetBin("id"));
257 
258   std::string error_msg;
259   exec_utils_->ExecAndReturnResult(command,
260                                    /*timeout_sec=*/-1,
261                                    ExecCallbacks{
262                                        .on_start = on_start.AsStdFunction(),
263                                        .on_end = on_end.AsStdFunction(),
264                                    },
265                                    /*stat=*/nullptr,
266                                    &error_msg);
267 }
268 
269 INSTANTIATE_TEST_SUITE_P(AlwaysOrNeverFallback, ExecUtilsTest, testing::Values(true, false));
270 
271 }  // namespace art
272