• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2015 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 "workload.h"
18 
19 #include <errno.h>
20 #include <fcntl.h>
21 #include <sched.h>
22 #include <sys/prctl.h>
23 #include <sys/wait.h>
24 #include <unistd.h>
25 
26 #include <android-base/logging.h>
27 #include <android-base/strings.h>
28 
29 #include "environment.h"
30 
31 namespace simpleperf {
32 
CreateWorkload(const std::vector<std::string> & args)33 std::unique_ptr<Workload> Workload::CreateWorkload(const std::vector<std::string>& args) {
34 #if defined(__ANDROID__)
35   if (IsInAppUid()) {
36     LOG(ERROR) << "Running child command in app uid isn't allowed.";
37     return nullptr;
38   }
39 #endif
40   std::unique_ptr<Workload> workload(new Workload(args, std::function<void()>()));
41   if (workload != nullptr && workload->CreateNewProcess()) {
42     return workload;
43   }
44   return nullptr;
45 }
46 
CreateWorkload(const std::function<void ()> & function)47 std::unique_ptr<Workload> Workload::CreateWorkload(const std::function<void()>& function) {
48   std::unique_ptr<Workload> workload(new Workload(std::vector<std::string>(), function));
49   if (workload != nullptr && workload->CreateNewProcess()) {
50     return workload;
51   }
52   return nullptr;
53 }
54 
RunCmd(const std::vector<std::string> & args,bool report_error)55 bool Workload::RunCmd(const std::vector<std::string>& args, bool report_error) {
56   std::string arg_str = android::base::Join(args, ' ');
57   int ret = system(arg_str.c_str());
58   if (ret != 0 && report_error) {
59     LOG(ERROR) << "Failed to run cmd " << arg_str << ", exitcode " << ret;
60     return false;
61   }
62   return ret == 0;
63 }
64 
Workload(const std::vector<std::string> & args,const std::function<void ()> & function)65 Workload::Workload(const std::vector<std::string>& args, const std::function<void()>& function)
66     : work_state_(NotYetCreateNewProcess),
67       child_proc_args_(args),
68       child_proc_function_(function),
69       work_pid_(-1),
70       start_signal_fd_(-1),
71       exec_child_fd_(-1) {
72   kill_function_ = [](pid_t pid) { kill(pid, SIGKILL); };
73 }
74 
~Workload()75 Workload::~Workload() {
76   if (work_pid_ != -1 && work_state_ != NotYetCreateNewProcess) {
77     if (!Workload::WaitChildProcess(false, false, nullptr)) {
78       kill_function_(work_pid_);
79       Workload::WaitChildProcess(true, true, nullptr);
80     }
81   }
82   if (start_signal_fd_ != -1) {
83     close(start_signal_fd_);
84   }
85   if (exec_child_fd_ != -1) {
86     close(exec_child_fd_);
87   }
88 }
89 
GetCommandName()90 std::string Workload::GetCommandName() {
91   if (child_proc_args_.empty()) {
92     return "";
93   }
94   std::string name = child_proc_args_[0];
95   if (auto split_pos = name.rfind('/'); split_pos != std::string::npos) {
96     name = name.substr(split_pos + 1);
97   }
98   return name;
99 }
100 
CreateNewProcess()101 bool Workload::CreateNewProcess() {
102   CHECK_EQ(work_state_, NotYetCreateNewProcess);
103 
104   int start_signal_pipe[2];
105   if (pipe2(start_signal_pipe, O_CLOEXEC) != 0) {
106     PLOG(ERROR) << "pipe2() failed";
107     return false;
108   }
109 
110   int exec_child_pipe[2];
111   if (pipe2(exec_child_pipe, O_CLOEXEC) != 0) {
112     PLOG(ERROR) << "pipe2() failed";
113     close(start_signal_pipe[0]);
114     close(start_signal_pipe[1]);
115     return false;
116   }
117 
118   pid_t pid = fork();
119   if (pid == -1) {
120     PLOG(ERROR) << "fork() failed";
121     close(start_signal_pipe[0]);
122     close(start_signal_pipe[1]);
123     close(exec_child_pipe[0]);
124     close(exec_child_pipe[1]);
125     return false;
126   } else if (pid == 0) {
127     // In child process.
128     close(start_signal_pipe[1]);
129     close(exec_child_pipe[0]);
130     ChildProcessFn(start_signal_pipe[0], exec_child_pipe[1]);
131     _exit(0);
132   }
133   // In parent process.
134   close(start_signal_pipe[0]);
135   close(exec_child_pipe[1]);
136   start_signal_fd_ = start_signal_pipe[1];
137   exec_child_fd_ = exec_child_pipe[0];
138   work_pid_ = pid;
139   work_state_ = NotYetStartNewProcess;
140   return true;
141 }
142 
ChildProcessFn(int start_signal_fd,int exec_child_fd)143 void Workload::ChildProcessFn(int start_signal_fd, int exec_child_fd) {
144   // Die if parent exits.
145   prctl(PR_SET_PDEATHSIG, SIGHUP, 0, 0, 0);
146 
147   char start_signal = 0;
148   ssize_t nread = TEMP_FAILURE_RETRY(read(start_signal_fd, &start_signal, 1));
149   if (nread == 1 && start_signal == 1) {
150     close(start_signal_fd);
151     if (child_proc_function_) {
152       close(exec_child_fd);
153       child_proc_function_();
154     } else {
155       char* argv[child_proc_args_.size() + 1];
156       for (size_t i = 0; i < child_proc_args_.size(); ++i) {
157         argv[i] = &child_proc_args_[i][0];
158       }
159       argv[child_proc_args_.size()] = nullptr;
160       execvp(argv[0], argv);
161       // If execvp() succeed, we will not arrive here. But if it failed, we need to
162       // report the failure to the parent process by writing 1 to exec_child_fd.
163       int saved_errno = errno;
164       char exec_child_failed = 1;
165       TEMP_FAILURE_RETRY(write(exec_child_fd, &exec_child_failed, 1));
166       close(exec_child_fd);
167       errno = saved_errno;
168       PLOG(ERROR) << "child process failed to execvp(" << argv[0] << ")";
169     }
170   } else {
171     PLOG(ERROR) << "child process failed to receive start_signal, nread = " << nread;
172   }
173 }
174 
SetCpuAffinity(int cpu)175 bool Workload::SetCpuAffinity(int cpu) {
176   CHECK_EQ(work_state_, NotYetStartNewProcess);
177   cpu_set_t mask;
178   CPU_ZERO(&mask);
179   CPU_SET(cpu, &mask);
180   if (sched_setaffinity(GetPid(), sizeof(mask), &mask) != 0) {
181     PLOG(WARNING) << "sched_setaffinity failed";
182     return false;
183   }
184   return true;
185 }
186 
Start()187 bool Workload::Start() {
188   CHECK_EQ(work_state_, NotYetStartNewProcess);
189   char start_signal = 1;
190   ssize_t nwrite = TEMP_FAILURE_RETRY(write(start_signal_fd_, &start_signal, 1));
191   if (nwrite != 1) {
192     PLOG(ERROR) << "write start signal failed";
193     return false;
194   }
195   char exec_child_failed;
196   ssize_t nread = TEMP_FAILURE_RETRY(read(exec_child_fd_, &exec_child_failed, 1));
197   if (nread != 0) {
198     if (nread == -1) {
199       PLOG(ERROR) << "failed to receive error message from child process";
200     } else {
201       LOG(ERROR) << "received error message from child process";
202     }
203     return false;
204   }
205   work_state_ = Started;
206   return true;
207 }
208 
WaitChildProcess(bool wait_forever,int * exit_code)209 bool Workload::WaitChildProcess(bool wait_forever, int* exit_code) {
210   return WaitChildProcess(wait_forever, false, exit_code);
211 }
212 
WaitChildProcess(bool wait_forever,bool is_child_killed,int * exit_code)213 bool Workload::WaitChildProcess(bool wait_forever, bool is_child_killed, int* exit_code) {
214   if (work_state_ == Finished) {
215     return true;
216   }
217   bool finished = false;
218   int status;
219   pid_t result = TEMP_FAILURE_RETRY(waitpid(work_pid_, &status, (wait_forever ? 0 : WNOHANG)));
220   if (result == work_pid_) {
221     finished = true;
222     work_state_ = Finished;
223     if (WIFSIGNALED(status)) {
224       if (!(is_child_killed && WTERMSIG(status) == SIGKILL)) {
225         LOG(WARNING) << "child process was terminated by signal " << strsignal(WTERMSIG(status));
226       }
227     } else if (WIFEXITED(status)) {
228       if (exit_code != nullptr) {
229         *exit_code = WEXITSTATUS(status);
230       } else if (WEXITSTATUS(status) != 0) {
231         LOG(WARNING) << "child process exited with exit code " << WEXITSTATUS(status);
232       }
233     }
234   } else if (result == -1) {
235     PLOG(ERROR) << "waitpid() failed";
236   }
237   return finished;
238 }
239 
240 }  // namespace simpleperf
241