Add UMA for ServiceWorkerURLRequestJob.
[chromium-blink-merge.git] / tools / gn / exec_process.cc
blobe15f595d1541c5a424e975e72ac89880279eb032
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.
5 #include "base/command_line.h"
6 #include "base/files/file_util.h"
7 #include "base/logging.h"
8 #include "base/process/kill.h"
9 #include "base/process/launch.h"
10 #include "base/process/process.h"
12 #if defined(OS_WIN)
13 #include <windows.h>
15 #include "base/win/scoped_handle.h"
16 #include "base/win/scoped_process_information.h"
17 #endif
19 #if defined(OS_POSIX)
20 #include <fcntl.h>
21 #include <unistd.h>
23 #include "base/posix/eintr_wrapper.h"
24 #include "base/posix/file_descriptor_shuffle.h"
25 #endif
27 namespace internal {
29 #if defined(OS_WIN)
30 bool ExecProcess(const base::CommandLine& cmdline,
31 const base::FilePath& startup_dir,
32 std::string* std_out,
33 std::string* std_err,
34 int* exit_code) {
35 SECURITY_ATTRIBUTES sa_attr;
36 // Set the bInheritHandle flag so pipe handles are inherited.
37 sa_attr.nLength = sizeof(SECURITY_ATTRIBUTES);
38 sa_attr.bInheritHandle = TRUE;
39 sa_attr.lpSecurityDescriptor = nullptr;
41 // Create the pipe for the child process's STDOUT.
42 HANDLE out_read = nullptr;
43 HANDLE out_write = nullptr;
44 if (!CreatePipe(&out_read, &out_write, &sa_attr, 0)) {
45 NOTREACHED() << "Failed to create pipe";
46 return false;
48 base::win::ScopedHandle scoped_out_read(out_read);
49 base::win::ScopedHandle scoped_out_write(out_write);
51 // Create the pipe for the child process's STDERR.
52 HANDLE err_read = nullptr;
53 HANDLE err_write = nullptr;
54 if (!CreatePipe(&err_read, &err_write, &sa_attr, 0)) {
55 NOTREACHED() << "Failed to create pipe";
56 return false;
58 base::win::ScopedHandle scoped_err_read(err_read);
59 base::win::ScopedHandle scoped_err_write(err_write);
61 // Ensure the read handle to the pipe for STDOUT/STDERR is not inherited.
62 if (!SetHandleInformation(out_read, HANDLE_FLAG_INHERIT, 0)) {
63 NOTREACHED() << "Failed to disabled pipe inheritance";
64 return false;
66 if (!SetHandleInformation(err_read, HANDLE_FLAG_INHERIT, 0)) {
67 NOTREACHED() << "Failed to disabled pipe inheritance";
68 return false;
71 base::FilePath::StringType cmdline_str(cmdline.GetCommandLineString());
73 STARTUPINFO start_info = {};
75 start_info.cb = sizeof(STARTUPINFO);
76 start_info.hStdOutput = out_write;
77 // Keep the normal stdin.
78 start_info.hStdInput = GetStdHandle(STD_INPUT_HANDLE);
79 // FIXME(brettw) set stderr here when we actually read it below.
80 //start_info.hStdError = err_write;
81 start_info.hStdError = GetStdHandle(STD_ERROR_HANDLE);
82 start_info.dwFlags |= STARTF_USESTDHANDLES;
84 // Create the child process.
85 PROCESS_INFORMATION temp_process_info = {};
86 if (!CreateProcess(nullptr,
87 &cmdline_str[0],
88 nullptr, nullptr,
89 TRUE, // Handles are inherited.
90 0, nullptr,
91 startup_dir.value().c_str(),
92 &start_info, &temp_process_info)) {
93 return false;
95 base::win::ScopedProcessInformation proc_info(temp_process_info);
97 // Close our writing end of pipes now. Otherwise later read would not be able
98 // to detect end of child's output.
99 scoped_out_write.Close();
100 scoped_err_write.Close();
102 // Read output from the child process's pipe for STDOUT
103 const int kBufferSize = 1024;
104 char buffer[kBufferSize];
106 // FIXME(brettw) read from stderr here! This is complicated because we want
107 // to read both of them at the same time, probably need overlapped I/O.
108 // Also uncomment start_info code above.
109 for (;;) {
110 DWORD bytes_read = 0;
111 BOOL success =
112 ReadFile(out_read, buffer, kBufferSize, &bytes_read, nullptr);
113 if (!success || bytes_read == 0)
114 break;
115 std_out->append(buffer, bytes_read);
118 // Let's wait for the process to finish.
119 WaitForSingleObject(proc_info.process_handle(), INFINITE);
121 DWORD dw_exit_code;
122 GetExitCodeProcess(proc_info.process_handle(), &dw_exit_code);
123 *exit_code = static_cast<int>(dw_exit_code);
125 return true;
127 #else
128 // Reads from the provided file descriptor and appends to output. Returns false
129 // if the fd is closed or there is an unexpected error (not
130 // EINTR/EAGAIN/EWOULDBLOCK).
131 bool ReadFromPipe(int fd, std::string* output) {
132 char buffer[256];
133 int bytes_read = HANDLE_EINTR(read(fd, buffer, sizeof(buffer)));
134 if (bytes_read == -1) {
135 return errno == EAGAIN || errno == EWOULDBLOCK;
136 } else if (bytes_read <= 0) {
137 return false;
139 output->append(buffer, bytes_read);
140 return true;
143 bool ExecProcess(const base::CommandLine& cmdline,
144 const base::FilePath& startup_dir,
145 std::string* std_out,
146 std::string* std_err,
147 int* exit_code) {
148 *exit_code = EXIT_FAILURE;
150 std::vector<std::string> argv = cmdline.argv();
152 int out_fd[2], err_fd[2];
153 pid_t pid;
154 base::InjectiveMultimap fd_shuffle1, fd_shuffle2;
155 scoped_ptr<char*[]> argv_cstr(new char*[argv.size() + 1]);
157 fd_shuffle1.reserve(3);
158 fd_shuffle2.reserve(3);
160 if (pipe(out_fd) < 0)
161 return false;
162 base::ScopedFD out_read(out_fd[0]), out_write(out_fd[1]);
164 if (pipe(err_fd) < 0)
165 return false;
166 base::ScopedFD err_read(err_fd[0]), err_write(err_fd[1]);
168 if (out_read.get() >= FD_SETSIZE || err_read.get() >= FD_SETSIZE)
169 return false;
171 switch (pid = fork()) {
172 case -1: // error
173 return false;
174 case 0: // child
176 // DANGER: no calls to malloc are allowed from now on:
177 // http://crbug.com/36678
179 // STL iterators are also not allowed (including those implied
180 // by range-based for loops), since debug iterators use locks.
182 // Obscure fork() rule: in the child, if you don't end up doing exec*(),
183 // you call _exit() instead of exit(). This is because _exit() does not
184 // call any previously-registered (in the parent) exit handlers, which
185 // might do things like block waiting for threads that don't even exist
186 // in the child.
187 int dev_null = open("/dev/null", O_WRONLY);
188 if (dev_null < 0)
189 _exit(127);
191 fd_shuffle1.push_back(
192 base::InjectionArc(out_write.get(), STDOUT_FILENO, true));
193 fd_shuffle1.push_back(
194 base::InjectionArc(err_write.get(), STDERR_FILENO, true));
195 fd_shuffle1.push_back(
196 base::InjectionArc(dev_null, STDIN_FILENO, true));
197 // Adding another element here? Remeber to increase the argument to
198 // reserve(), above.
200 // DANGER: Do NOT convert to range-based for loop!
201 for (size_t i = 0; i < fd_shuffle1.size(); ++i)
202 fd_shuffle2.push_back(fd_shuffle1[i]);
204 if (!ShuffleFileDescriptors(&fd_shuffle1))
205 _exit(127);
207 base::SetCurrentDirectory(startup_dir);
209 // TODO(brettw) the base version GetAppOutput does a
210 // CloseSuperfluousFds call here. Do we need this?
212 // DANGER: Do NOT convert to range-based for loop!
213 for (size_t i = 0; i < argv.size(); i++)
214 argv_cstr[i] = const_cast<char*>(argv[i].c_str());
215 argv_cstr[argv.size()] = nullptr;
216 execvp(argv_cstr[0], argv_cstr.get());
217 _exit(127);
219 default: // parent
221 // Close our writing end of pipe now. Otherwise later read would not
222 // be able to detect end of child's output (in theory we could still
223 // write to the pipe).
224 out_write.reset();
225 err_write.reset();
227 bool out_open = true, err_open = true;
228 while (out_open || err_open) {
229 fd_set read_fds;
230 FD_ZERO(&read_fds);
231 FD_SET(out_read.get(), &read_fds);
232 FD_SET(err_read.get(), &read_fds);
233 int res =
234 HANDLE_EINTR(select(std::max(out_read.get(), err_read.get()) + 1,
235 &read_fds, nullptr, nullptr, nullptr));
236 if (res <= 0)
237 break;
238 if (FD_ISSET(out_read.get(), &read_fds))
239 out_open = ReadFromPipe(out_read.get(), std_out);
240 if (FD_ISSET(err_read.get(), &read_fds))
241 err_open = ReadFromPipe(err_read.get(), std_err);
244 base::Process process(pid);
245 return process.WaitForExit(exit_code);
249 return false;
251 #endif
253 } // namespace internal