1 // Copyright 2014 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #include "gn/exec_process.h"
6
7 #include <stddef.h>
8
9 #include <memory>
10
11 #include "base/command_line.h"
12 #include "base/files/file_util.h"
13 #include "base/logging.h"
14 #include "util/build_config.h"
15
16 #if defined(OS_WIN)
17 #include <windows.h>
18
19 #include "base/win/scoped_handle.h"
20 #include "base/win/scoped_process_information.h"
21 #include "base/win/win_util.h"
22 #else
23 #include <errno.h>
24 #include <fcntl.h>
25 #include <signal.h>
26 #include <sys/time.h>
27 #include <sys/wait.h>
28 #include <unistd.h>
29
30 #include "base/posix/eintr_wrapper.h"
31 #include "base/posix/file_descriptor_shuffle.h"
32 #endif
33
34 namespace internal {
35
36 #if defined(OS_WIN)
ExecProcess(const base::CommandLine & cmdline,const base::FilePath & startup_dir,std::string * std_out,std::string * std_err,int * exit_code)37 bool ExecProcess(const base::CommandLine& cmdline,
38 const base::FilePath& startup_dir,
39 std::string* std_out,
40 std::string* std_err,
41 int* exit_code) {
42 return ExecProcess(cmdline.GetCommandLineString(), startup_dir, std_out,
43 std_err, exit_code);
44 }
45
ExecProcess(const std::u16string & cmdline_str,const base::FilePath & startup_dir,std::string * std_out,std::string * std_err,int * exit_code)46 bool ExecProcess(const std::u16string& cmdline_str,
47 const base::FilePath& startup_dir,
48 std::string* std_out,
49 std::string* std_err,
50 int* exit_code) {
51 SECURITY_ATTRIBUTES sa_attr;
52 // Set the bInheritHandle flag so pipe handles are inherited.
53 sa_attr.nLength = sizeof(SECURITY_ATTRIBUTES);
54 sa_attr.bInheritHandle = TRUE;
55 sa_attr.lpSecurityDescriptor = nullptr;
56
57 // Create the pipe for the child process's STDOUT.
58 HANDLE out_read = nullptr;
59 HANDLE out_write = nullptr;
60 if (!CreatePipe(&out_read, &out_write, &sa_attr, 0)) {
61 NOTREACHED() << "Failed to create pipe";
62 return false;
63 }
64 base::win::ScopedHandle scoped_out_read(out_read);
65 base::win::ScopedHandle scoped_out_write(out_write);
66
67 // Create the pipe for the child process's STDERR.
68 HANDLE err_read = nullptr;
69 HANDLE err_write = nullptr;
70 if (!CreatePipe(&err_read, &err_write, &sa_attr, 0)) {
71 NOTREACHED() << "Failed to create pipe";
72 return false;
73 }
74 base::win::ScopedHandle scoped_err_read(err_read);
75 base::win::ScopedHandle scoped_err_write(err_write);
76
77 // Ensure the read handle to the pipe for STDOUT/STDERR is not inherited.
78 if (!SetHandleInformation(out_read, HANDLE_FLAG_INHERIT, 0)) {
79 NOTREACHED() << "Failed to disable pipe inheritance";
80 return false;
81 }
82 if (!SetHandleInformation(err_read, HANDLE_FLAG_INHERIT, 0)) {
83 NOTREACHED() << "Failed to disable pipe inheritance";
84 return false;
85 }
86
87 STARTUPINFO start_info = {};
88
89 start_info.cb = sizeof(STARTUPINFO);
90 start_info.hStdOutput = out_write;
91 // Keep the normal stdin.
92 start_info.hStdInput = GetStdHandle(STD_INPUT_HANDLE);
93 // FIXME(brettw) set stderr here when we actually read it below.
94 // start_info.hStdError = err_write;
95 start_info.hStdError = GetStdHandle(STD_ERROR_HANDLE);
96 start_info.dwFlags |= STARTF_USESTDHANDLES;
97
98 std::u16string cmdline_writable = cmdline_str;
99
100 // Create the child process.
101 PROCESS_INFORMATION temp_process_info = {};
102 if (!CreateProcess(
103 nullptr, base::ToWCharT(&cmdline_writable[0]), nullptr, nullptr,
104 TRUE, // Handles are inherited.
105 NORMAL_PRIORITY_CLASS, nullptr, base::ToWCharT(&startup_dir.value()),
106 &start_info, &temp_process_info)) {
107 return false;
108 }
109 base::win::ScopedProcessInformation proc_info(temp_process_info);
110
111 // Close our writing end of pipes now. Otherwise later read would not be
112 // able to detect end of child's output.
113 scoped_out_write.Close();
114 scoped_err_write.Close();
115
116 // Read output from the child process's pipe for STDOUT
117 const int kBufferSize = 1024;
118 char buffer[kBufferSize];
119
120 // FIXME(brettw) read from stderr here! This is complicated because we want
121 // to read both of them at the same time, probably need overlapped I/O.
122 // Also uncomment start_info code above.
123 for (;;) {
124 DWORD bytes_read = 0;
125 BOOL success =
126 ReadFile(out_read, buffer, kBufferSize, &bytes_read, nullptr);
127 if (!success || bytes_read == 0)
128 break;
129 std_out->append(buffer, bytes_read);
130 }
131
132 // Let's wait for the process to finish.
133 WaitForSingleObject(proc_info.process_handle(), INFINITE);
134
135 DWORD dw_exit_code;
136 GetExitCodeProcess(proc_info.process_handle(), &dw_exit_code);
137 *exit_code = static_cast<int>(dw_exit_code);
138
139 return true;
140 }
141 #else
142 // Reads from the provided file descriptor and appends to output. Returns false
143 // if the fd is closed or there is an unexpected error (not
144 // EINTR/EAGAIN/EWOULDBLOCK).
145 bool ReadFromPipe(int fd, std::string* output) {
146 char buffer[256];
147 int bytes_read = HANDLE_EINTR(read(fd, buffer, sizeof(buffer)));
148 if (bytes_read == -1) {
149 return errno == EAGAIN || errno == EWOULDBLOCK;
150 } else if (bytes_read <= 0) {
151 return false;
152 }
153 output->append(buffer, bytes_read);
154 return true;
155 }
156
157 bool WaitForExit(int pid, int* exit_code) {
158 int status;
159 if (waitpid(pid, &status, 0) < 0) {
160 PLOG(ERROR) << "waitpid";
161 return false;
162 }
163
164 if (WIFEXITED(status)) {
165 *exit_code = WEXITSTATUS(status);
166 return true;
167 } else if (WIFSIGNALED(status)) {
168 if (WTERMSIG(status) == SIGINT || WTERMSIG(status) == SIGTERM ||
169 WTERMSIG(status) == SIGHUP)
170 return false;
171 }
172 return false;
173 }
174
175 bool ExecProcess(const base::CommandLine& cmdline,
176 const base::FilePath& startup_dir,
177 std::string* std_out,
178 std::string* std_err,
179 int* exit_code) {
180 *exit_code = EXIT_FAILURE;
181
182 std::vector<std::string> argv = cmdline.argv();
183
184 int out_fd[2], err_fd[2];
185 pid_t pid;
186 base::InjectiveMultimap fd_shuffle1, fd_shuffle2;
187 std::unique_ptr<char*[]> argv_cstr(new char*[argv.size() + 1]);
188
189 fd_shuffle1.reserve(3);
190 fd_shuffle2.reserve(3);
191
192 if (pipe(out_fd) < 0)
193 return false;
194 base::ScopedFD out_read(out_fd[0]), out_write(out_fd[1]);
195
196 if (pipe(err_fd) < 0)
197 return false;
198 base::ScopedFD err_read(err_fd[0]), err_write(err_fd[1]);
199
200 if (out_read.get() >= FD_SETSIZE || err_read.get() >= FD_SETSIZE)
201 return false;
202
203 switch (pid = fork()) {
204 case -1: // error
205 return false;
206 case 0: // child
207 {
208 #if defined(OS_MAC)
209 // When debugging the app under Xcode, the child will receive a SIGTRAP
210 // signal which will terminate the child process. Ignore the signal to
211 // allow debugging under macOS.
212 sigignore(SIGTRAP);
213 #endif
214
215 // DANGER: no calls to malloc are allowed from now on:
216 // http://crbug.com/36678
217 //
218 // STL iterators are also not allowed (including those implied
219 // by range-based for loops), since debug iterators use locks.
220
221 // Obscure fork() rule: in the child, if you don't end up doing exec*(),
222 // you call _exit() instead of exit(). This is because _exit() does not
223 // call any previously-registered (in the parent) exit handlers, which
224 // might do things like block waiting for threads that don't even exist
225 // in the child.
226 int dev_null = open("/dev/null", O_WRONLY);
227 if (dev_null < 0)
228 _exit(127);
229
230 fd_shuffle1.push_back(
231 base::InjectionArc(out_write.get(), STDOUT_FILENO, true));
232 fd_shuffle1.push_back(
233 base::InjectionArc(err_write.get(), STDERR_FILENO, true));
234 fd_shuffle1.push_back(base::InjectionArc(dev_null, STDIN_FILENO, true));
235 // Adding another element here? Remember to increase the argument to
236 // reserve(), above.
237
238 // DANGER: Do NOT convert to range-based for loop!
239 for (size_t i = 0; i < fd_shuffle1.size(); ++i)
240 fd_shuffle2.push_back(fd_shuffle1[i]);
241
242 if (!ShuffleFileDescriptors(&fd_shuffle1))
243 _exit(127);
244
245 base::SetCurrentDirectory(startup_dir);
246
247 // TODO(brettw) the base version GetAppOutput does a
248 // CloseSuperfluousFds call here. Do we need this?
249
250 // DANGER: Do NOT convert to range-based for loop!
251 for (size_t i = 0; i < argv.size(); i++)
252 argv_cstr[i] = const_cast<char*>(argv[i].c_str());
253 argv_cstr[argv.size()] = nullptr;
254 execvp(argv_cstr[0], argv_cstr.get());
255 _exit(127);
256 }
257 default: // parent
258 {
259 // Close our writing end of pipe now. Otherwise later read would not
260 // be able to detect end of child's output (in theory we could still
261 // write to the pipe).
262 out_write.reset();
263 err_write.reset();
264
265 bool out_open = true, err_open = true;
266 while (out_open || err_open) {
267 fd_set read_fds;
268 FD_ZERO(&read_fds);
269 FD_SET(out_read.get(), &read_fds);
270 FD_SET(err_read.get(), &read_fds);
271 int res =
272 HANDLE_EINTR(select(std::max(out_read.get(), err_read.get()) + 1,
273 &read_fds, nullptr, nullptr, nullptr));
274 if (res <= 0)
275 break;
276 if (FD_ISSET(out_read.get(), &read_fds))
277 out_open = ReadFromPipe(out_read.get(), std_out);
278 if (FD_ISSET(err_read.get(), &read_fds))
279 err_open = ReadFromPipe(err_read.get(), std_err);
280 }
281
282 return WaitForExit(pid, exit_code);
283 }
284 }
285
286 return false;
287 }
288 #endif
289
290 } // namespace internal
291