blob: ff4158e8ba85abd61eabcfb1213134f1d4344cfd [file] [log] [blame]
Alex Deymoaea4c1c2015-08-19 20:24:43 -07001//
2// Copyright (C) 2012 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//
adlr@google.com3defe6a2009-12-04 20:57:17 +000016
Alex Deymo39910dc2015-11-09 17:04:30 -080017#include "update_engine/common/subprocess.h"
Alex Deymoaab50e32014-11-10 19:55:35 -080018
Alex Deymo5d527802014-07-18 14:24:13 -070019#include <fcntl.h>
Gilad Arnoldb6c562a2013-07-01 02:19:26 -070020#include <poll.h>
adlr@google.com3defe6a2009-12-04 20:57:17 +000021#include <sys/types.h>
22#include <unistd.h>
Gilad Arnold8e3f1262013-01-08 14:59:54 -080023
Alex Deymo461b2592015-07-24 20:10:52 -070024#include <set>
adlr@google.com3defe6a2009-12-04 20:57:17 +000025#include <string>
26#include <vector>
Gilad Arnold8e3f1262013-01-08 14:59:54 -080027
Alex Deymo60ca1a72015-06-18 18:19:15 -070028#include <base/bind.h>
Alex Deymo279bbab2016-02-12 16:26:17 -080029#include <base/files/scoped_temp_dir.h>
Alex Deymo60ca1a72015-06-18 18:19:15 -070030#include <base/location.h>
Qijiang Fanb0b6cc22020-10-15 21:54:11 +090031#if BASE_VER < 780000 // Android
Alex Deymo0b3db6b2015-08-10 15:19:37 -070032#include <base/message_loop/message_loop.h>
Qijiang Fanb0b6cc22020-10-15 21:54:11 +090033#endif // BASE_VER < 780000
Alex Vakulenko75039d72014-03-25 12:36:28 -070034#include <base/strings/string_util.h>
35#include <base/strings/stringprintf.h>
Qijiang Fanb0b6cc22020-10-15 21:54:11 +090036#if BASE_VER >= 780000 // Chrome OS
37#include <base/task/single_thread_task_executor.h>
38#endif // BASE_VER >= 780000
Alex Vakulenko75039d72014-03-25 12:36:28 -070039#include <base/time/time.h>
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -070040#include <brillo/message_loops/base_message_loop.h>
41#include <brillo/message_loops/message_loop.h>
42#include <brillo/message_loops/message_loop_utils.h>
43#include <brillo/strings/string_utils.h>
Alex Deymoe384bb22016-03-29 17:23:33 -070044#include <brillo/unittest_utils.h>
adlr@google.com3defe6a2009-12-04 20:57:17 +000045#include <gtest/gtest.h>
Gilad Arnold8e3f1262013-01-08 14:59:54 -080046
Alex Deymo39910dc2015-11-09 17:04:30 -080047#include "update_engine/common/test_utils.h"
48#include "update_engine/common/utils.h"
adlr@google.com3defe6a2009-12-04 20:57:17 +000049
Gilad Arnold8e3f1262013-01-08 14:59:54 -080050using base::TimeDelta;
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -070051using brillo::MessageLoop;
adlr@google.com3defe6a2009-12-04 20:57:17 +000052using std::string;
Qijiang Fan6955bcc2019-11-19 20:33:43 +090053using std::unique_ptr;
adlr@google.com3defe6a2009-12-04 20:57:17 +000054using std::vector;
55
Alex Deymo279bbab2016-02-12 16:26:17 -080056namespace {
57
58#ifdef __ANDROID__
59#define kBinPath "/system/bin"
60#define kUsrBinPath "/system/bin"
61#else
62#define kBinPath "/bin"
63#define kUsrBinPath "/usr/bin"
64#endif // __ANDROID__
65
66} // namespace
67
adlr@google.com3defe6a2009-12-04 20:57:17 +000068namespace chromeos_update_engine {
69
70class SubprocessTest : public ::testing::Test {
71 protected:
Alex Deymo60ca1a72015-06-18 18:19:15 -070072 void SetUp() override {
73 loop_.SetAsCurrent();
Alex Deymob7ca0962014-10-01 17:58:07 -070074 async_signal_handler_.Init();
75 subprocess_.Init(&async_signal_handler_);
Alex Deymo60ca1a72015-06-18 18:19:15 -070076 }
77
Qijiang Fanb0b6cc22020-10-15 21:54:11 +090078#if BASE_VER < 780000 // Android
Alex Deymo0b3db6b2015-08-10 15:19:37 -070079 base::MessageLoopForIO base_loop_;
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -070080 brillo::BaseMessageLoop loop_{&base_loop_};
Qijiang Fanb0b6cc22020-10-15 21:54:11 +090081#else // Chrome OS
82 base::SingleThreadTaskExecutor base_loop_{base::MessagePumpType::IO};
83 brillo::BaseMessageLoop loop_{base_loop_.task_runner()};
84#endif // BASE_VER < 780000
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -070085 brillo::AsynchronousSignalHandler async_signal_handler_;
Alex Deymo461b2592015-07-24 20:10:52 -070086 Subprocess subprocess_;
Qijiang Fan6955bcc2019-11-19 20:33:43 +090087 unique_ptr<base::FileDescriptorWatcher::Controller> watcher_;
adlr@google.com3defe6a2009-12-04 20:57:17 +000088};
89
90namespace {
Alex Deymo461b2592015-07-24 20:10:52 -070091
Amin Hassanib2689592019-01-13 17:04:28 -080092void ExpectedResults(int expected_return_code,
93 const string& expected_output,
94 int return_code,
95 const string& output) {
Alex Deymo461b2592015-07-24 20:10:52 -070096 EXPECT_EQ(expected_return_code, return_code);
97 EXPECT_EQ(expected_output, output);
Alex Deymo60ca1a72015-06-18 18:19:15 -070098 MessageLoop::current()->BreakLoop();
adlr@google.com3defe6a2009-12-04 20:57:17 +000099}
100
Alex Deymo461b2592015-07-24 20:10:52 -0700101void ExpectedEnvVars(int return_code, const string& output) {
Darin Petkov6f03a3b2010-11-10 14:27:14 -0800102 EXPECT_EQ(0, return_code);
Alex Deymo461b2592015-07-24 20:10:52 -0700103 const std::set<string> allowed_envs = {"LD_LIBRARY_PATH", "PATH"};
Chih-Hung Hsieh5c6bb1d2016-07-27 13:33:15 -0700104 for (const string& key_value : brillo::string_utils::Split(output, "\n")) {
Amin Hassanib2689592019-01-13 17:04:28 -0800105 auto key_value_pair =
106 brillo::string_utils::SplitAtFirst(key_value, "=", true);
Alex Deymo461b2592015-07-24 20:10:52 -0700107 EXPECT_NE(allowed_envs.end(), allowed_envs.find(key_value_pair.first));
108 }
Alex Deymo29b81532015-07-09 11:51:49 -0700109 MessageLoop::current()->BreakLoop();
110}
111
Alex Deymoe384bb22016-03-29 17:23:33 -0700112void ExpectedDataOnPipe(const Subprocess* subprocess,
113 pid_t* pid,
114 int child_fd,
115 const string& child_fd_data,
116 int expected_return_code,
117 int return_code,
118 const string& /* output */) {
119 EXPECT_EQ(expected_return_code, return_code);
120
121 // Verify that we can read the data from our end of |child_fd|.
122 int fd = subprocess->GetPipeFd(*pid, child_fd);
123 EXPECT_NE(-1, fd);
124 vector<char> buf(child_fd_data.size() + 1);
125 EXPECT_EQ(static_cast<ssize_t>(child_fd_data.size()),
126 HANDLE_EINTR(read(fd, buf.data(), buf.size())));
127 EXPECT_EQ(child_fd_data,
128 string(buf.begin(), buf.begin() + child_fd_data.size()));
129
130 MessageLoop::current()->BreakLoop();
131}
132
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700133} // namespace
adlr@google.com3defe6a2009-12-04 20:57:17 +0000134
Alex Deymo461b2592015-07-24 20:10:52 -0700135TEST_F(SubprocessTest, IsASingleton) {
136 EXPECT_EQ(&subprocess_, &Subprocess::Get());
137}
138
139TEST_F(SubprocessTest, InactiveInstancesDontChangeTheSingleton) {
140 std::unique_ptr<Subprocess> another_subprocess(new Subprocess());
141 EXPECT_EQ(&subprocess_, &Subprocess::Get());
142 another_subprocess.reset();
143 EXPECT_EQ(&subprocess_, &Subprocess::Get());
144}
145
Alex Deymo60ca1a72015-06-18 18:19:15 -0700146TEST_F(SubprocessTest, SimpleTest) {
Alex Deymo279bbab2016-02-12 16:26:17 -0800147 EXPECT_TRUE(subprocess_.Exec({kBinPath "/false"},
Alex Deymo461b2592015-07-24 20:10:52 -0700148 base::Bind(&ExpectedResults, 1, "")));
Alex Deymo60ca1a72015-06-18 18:19:15 -0700149 loop_.Run();
adlr@google.com3defe6a2009-12-04 20:57:17 +0000150}
151
Alex Deymo60ca1a72015-06-18 18:19:15 -0700152TEST_F(SubprocessTest, EchoTest) {
Alex Deymo461b2592015-07-24 20:10:52 -0700153 EXPECT_TRUE(subprocess_.Exec(
Alex Deymo279bbab2016-02-12 16:26:17 -0800154 {kBinPath "/sh", "-c", "echo this is stdout; echo this is stderr >&2"},
Alex Deymo461b2592015-07-24 20:10:52 -0700155 base::Bind(&ExpectedResults, 0, "this is stdout\nthis is stderr\n")));
Alex Deymo29b81532015-07-09 11:51:49 -0700156 loop_.Run();
157}
158
159TEST_F(SubprocessTest, StderrNotIncludedInOutputTest) {
Alex Deymo461b2592015-07-24 20:10:52 -0700160 EXPECT_TRUE(subprocess_.ExecFlags(
Alex Deymo279bbab2016-02-12 16:26:17 -0800161 {kBinPath "/sh", "-c", "echo on stdout; echo on stderr >&2"},
Alex Deymo461b2592015-07-24 20:10:52 -0700162 0,
Alex Deymoe384bb22016-03-29 17:23:33 -0700163 {},
Alex Deymo461b2592015-07-24 20:10:52 -0700164 base::Bind(&ExpectedResults, 0, "on stdout\n")));
Alex Deymo60ca1a72015-06-18 18:19:15 -0700165 loop_.Run();
Darin Petkov6f03a3b2010-11-10 14:27:14 -0800166}
167
Alex Deymoe384bb22016-03-29 17:23:33 -0700168TEST_F(SubprocessTest, PipeRedirectFdTest) {
169 pid_t pid;
170 pid = subprocess_.ExecFlags(
171 {kBinPath "/sh", "-c", "echo on pipe >&3"},
172 0,
173 {3},
174 base::Bind(&ExpectedDataOnPipe, &subprocess_, &pid, 3, "on pipe\n", 0));
175 EXPECT_NE(0, pid);
176
177 // Wrong file descriptor values should return -1.
178 EXPECT_EQ(-1, subprocess_.GetPipeFd(pid, 123));
179 loop_.Run();
180 // Calling GetPipeFd() after the callback runs is invalid.
181 EXPECT_EQ(-1, subprocess_.GetPipeFd(pid, 3));
182}
183
184// Test that a pipe file descriptor open in the parent is not open in the child.
185TEST_F(SubprocessTest, PipeClosedWhenNotRedirectedTest) {
186 brillo::ScopedPipe pipe;
Alex Deymo279d5722016-04-07 16:22:13 -0700187
188 // test_subprocess will return with the errno of fstat, which should be EBADF
189 // if the passed file descriptor is closed in the child.
190 const vector<string> cmd = {
191 test_utils::GetBuildArtifactsPath("test_subprocess"),
192 "fstat",
193 std::to_string(pipe.writer)};
Alex Deymoe384bb22016-03-29 17:23:33 -0700194 EXPECT_TRUE(subprocess_.ExecFlags(
Alex Deymo279d5722016-04-07 16:22:13 -0700195 cmd, 0, {}, base::Bind(&ExpectedResults, EBADF, "")));
Alex Deymoe384bb22016-03-29 17:23:33 -0700196 loop_.Run();
197}
198
Alex Deymo461b2592015-07-24 20:10:52 -0700199TEST_F(SubprocessTest, EnvVarsAreFiltered) {
Alex Deymo279bbab2016-02-12 16:26:17 -0800200 EXPECT_TRUE(
201 subprocess_.Exec({kUsrBinPath "/env"}, base::Bind(&ExpectedEnvVars)));
Alex Deymo461b2592015-07-24 20:10:52 -0700202 loop_.Run();
203}
204
205TEST_F(SubprocessTest, SynchronousTrueSearchsOnPath) {
206 int rc = -1;
207 EXPECT_TRUE(Subprocess::SynchronousExecFlags(
Amin Hassani3a4caa12019-11-06 11:12:28 -0800208 {"true"}, Subprocess::kSearchPath, &rc, nullptr, nullptr));
Alex Deymo461b2592015-07-24 20:10:52 -0700209 EXPECT_EQ(0, rc);
210}
211
Alex Deymo60ca1a72015-06-18 18:19:15 -0700212TEST_F(SubprocessTest, SynchronousEchoTest) {
213 vector<string> cmd = {
Amin Hassanib2689592019-01-13 17:04:28 -0800214 kBinPath "/sh", "-c", "echo -n stdout-here; echo -n stderr-there >&2"};
Darin Petkov85d02b72011-05-17 13:25:51 -0700215 int rc = -1;
Amin Hassani3a4caa12019-11-06 11:12:28 -0800216 string stdout, stderr;
217 ASSERT_TRUE(Subprocess::SynchronousExec(cmd, &rc, &stdout, &stderr));
Darin Petkov85d02b72011-05-17 13:25:51 -0700218 EXPECT_EQ(0, rc);
Amin Hassani3a4caa12019-11-06 11:12:28 -0800219 EXPECT_EQ("stdout-here", stdout);
220 EXPECT_EQ("stderr-there", stderr);
Darin Petkov85d02b72011-05-17 13:25:51 -0700221}
222
Alex Deymo60ca1a72015-06-18 18:19:15 -0700223TEST_F(SubprocessTest, SynchronousEchoNoOutputTest) {
Darin Petkov85d02b72011-05-17 13:25:51 -0700224 int rc = -1;
Alex Deymo461b2592015-07-24 20:10:52 -0700225 ASSERT_TRUE(Subprocess::SynchronousExec(
Amin Hassani3a4caa12019-11-06 11:12:28 -0800226 {kBinPath "/sh", "-c", "echo test"}, &rc, nullptr, nullptr));
Darin Petkov85d02b72011-05-17 13:25:51 -0700227 EXPECT_EQ(0, rc);
228}
229
adlr@google.com3defe6a2009-12-04 20:57:17 +0000230namespace {
Alex Deymo461b2592015-07-24 20:10:52 -0700231void CallbackBad(int return_code, const string& output) {
232 ADD_FAILURE() << "should never be called.";
adlr@google.com3defe6a2009-12-04 20:57:17 +0000233}
Alex Deymo60ca1a72015-06-18 18:19:15 -0700234} // namespace
235
Alex Deymo279bbab2016-02-12 16:26:17 -0800236// Test that you can cancel a program that's already running.
Alex Deymo60ca1a72015-06-18 18:19:15 -0700237TEST_F(SubprocessTest, CancelTest) {
Alex Deymo279bbab2016-02-12 16:26:17 -0800238 base::ScopedTempDir tempdir;
239 ASSERT_TRUE(tempdir.CreateUniqueTempDir());
Hidehiko Abe2b9d2412017-12-13 18:56:18 +0900240 string fifo_path = tempdir.GetPath().Append("fifo").value();
Alex Deymo279bbab2016-02-12 16:26:17 -0800241 EXPECT_EQ(0, mkfifo(fifo_path.c_str(), 0666));
242
243 // Start a process, make sure it is running and try to cancel it. We write
244 // two bytes to the fifo, the first one marks that the program is running and
245 // the second one marks that the process waited for a timeout and was not
246 // killed. We should read the first byte but not the second one.
247 vector<string> cmd = {
248 kBinPath "/sh",
249 "-c",
250 base::StringPrintf(
Ben Chan70a21192017-01-10 19:56:50 -0800251 // The 'sleep' launched below could be left behind as an orphaned
252 // process when the 'sh' process is terminated by SIGTERM. As a
253 // remedy, trap SIGTERM and kill the 'sleep' process, which requires
254 // launching 'sleep' in background and then waiting for it.
255 "cleanup() { kill \"${sleep_pid}\"; exit 0; }; "
256 "trap cleanup TERM; "
257 "sleep 60 & "
258 "sleep_pid=$!; "
259 "printf X >\"%s\"; "
260 "wait; "
261 "printf Y >\"%s\"; "
262 "exit 1",
Alex Deymo279bbab2016-02-12 16:26:17 -0800263 fifo_path.c_str(),
264 fifo_path.c_str())};
265 uint32_t tag = Subprocess::Get().Exec(cmd, base::Bind(&CallbackBad));
266 EXPECT_NE(0U, tag);
267
268 int fifo_fd = HANDLE_EINTR(open(fifo_path.c_str(), O_RDONLY));
269 EXPECT_GE(fifo_fd, 0);
270
Qijiang Fan6955bcc2019-11-19 20:33:43 +0900271 watcher_ = base::FileDescriptorWatcher::WatchReadable(
272 fifo_fd,
273 base::Bind(
274 [](unique_ptr<base::FileDescriptorWatcher::Controller>* watcher,
275 int fifo_fd,
276 uint32_t tag) {
277 char c;
278 EXPECT_EQ(1, HANDLE_EINTR(read(fifo_fd, &c, 1)));
279 EXPECT_EQ('X', c);
280 LOG(INFO) << "Killing tag " << tag;
281 Subprocess::Get().KillExec(tag);
282 *watcher = nullptr;
283 },
284 // watcher_ is no longer used outside the clousure.
285 base::Unretained(&watcher_),
286 fifo_fd,
287 tag));
Alex Deymo279bbab2016-02-12 16:26:17 -0800288
Alex Deymo60ca1a72015-06-18 18:19:15 -0700289 // This test would leak a callback that runs when the child process exits
290 // unless we wait for it to run.
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -0700291 brillo::MessageLoopRunUntil(
Qijiang Fan15a6ead2020-07-25 17:19:49 +0900292 &loop_, TimeDelta::FromSeconds(20), base::Bind([] {
Amin Hassanib2689592019-01-13 17:04:28 -0800293 return Subprocess::Get().subprocess_records_.empty();
294 }));
Alex Deymo279bbab2016-02-12 16:26:17 -0800295 EXPECT_TRUE(Subprocess::Get().subprocess_records_.empty());
296 // Check that there isn't anything else to read from the pipe.
297 char c;
298 EXPECT_EQ(0, HANDLE_EINTR(read(fifo_fd, &c, 1)));
299 IGNORE_EINTR(close(fifo_fd));
adlr@google.com3defe6a2009-12-04 20:57:17 +0000300}
301
302} // namespace chromeos_update_engine