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"
14 #include "base/win/scoped_handle.h"
15 #include "base/win/scoped_process_information.h"
22 #include "base/posix/eintr_wrapper.h"
23 #include "base/posix/file_descriptor_shuffle.h"
29 bool ExecProcess(const base::CommandLine
& cmdline
,
30 const base::FilePath
& startup_dir
,
34 SECURITY_ATTRIBUTES sa_attr
;
35 // Set the bInheritHandle flag so pipe handles are inherited.
36 sa_attr
.nLength
= sizeof(SECURITY_ATTRIBUTES
);
37 sa_attr
.bInheritHandle
= TRUE
;
38 sa_attr
.lpSecurityDescriptor
= nullptr;
40 // Create the pipe for the child process's STDOUT.
41 HANDLE out_read
= nullptr;
42 HANDLE out_write
= nullptr;
43 if (!CreatePipe(&out_read
, &out_write
, &sa_attr
, 0)) {
44 NOTREACHED() << "Failed to create pipe";
47 base::win::ScopedHandle
scoped_out_read(out_read
);
48 base::win::ScopedHandle
scoped_out_write(out_write
);
50 // Create the pipe for the child process's STDERR.
51 HANDLE err_read
= nullptr;
52 HANDLE err_write
= nullptr;
53 if (!CreatePipe(&err_read
, &err_write
, &sa_attr
, 0)) {
54 NOTREACHED() << "Failed to create pipe";
57 base::win::ScopedHandle
scoped_err_read(err_read
);
58 base::win::ScopedHandle
scoped_err_write(err_write
);
60 // Ensure the read handle to the pipe for STDOUT/STDERR is not inherited.
61 if (!SetHandleInformation(out_read
, HANDLE_FLAG_INHERIT
, 0)) {
62 NOTREACHED() << "Failed to disabled pipe inheritance";
65 if (!SetHandleInformation(err_read
, HANDLE_FLAG_INHERIT
, 0)) {
66 NOTREACHED() << "Failed to disabled pipe inheritance";
70 base::FilePath::StringType
cmdline_str(cmdline
.GetCommandLineString());
72 STARTUPINFO start_info
= {};
74 start_info
.cb
= sizeof(STARTUPINFO
);
75 start_info
.hStdOutput
= out_write
;
76 // Keep the normal stdin.
77 start_info
.hStdInput
= GetStdHandle(STD_INPUT_HANDLE
);
78 // FIXME(brettw) set stderr here when we actually read it below.
79 //start_info.hStdError = err_write;
80 start_info
.hStdError
= GetStdHandle(STD_ERROR_HANDLE
);
81 start_info
.dwFlags
|= STARTF_USESTDHANDLES
;
83 // Create the child process.
84 PROCESS_INFORMATION temp_process_info
= {};
85 if (!CreateProcess(nullptr,
88 TRUE
, // Handles are inherited.
90 startup_dir
.value().c_str(),
91 &start_info
, &temp_process_info
)) {
94 base::win::ScopedProcessInformation
proc_info(temp_process_info
);
96 // Close our writing end of pipes now. Otherwise later read would not be able
97 // to detect end of child's output.
98 scoped_out_write
.Close();
99 scoped_err_write
.Close();
101 // Read output from the child process's pipe for STDOUT
102 const int kBufferSize
= 1024;
103 char buffer
[kBufferSize
];
105 // FIXME(brettw) read from stderr here! This is complicated because we want
106 // to read both of them at the same time, probably need overlapped I/O.
107 // Also uncomment start_info code above.
109 DWORD bytes_read
= 0;
111 ReadFile(out_read
, buffer
, kBufferSize
, &bytes_read
, nullptr);
112 if (!success
|| bytes_read
== 0)
114 std_out
->append(buffer
, bytes_read
);
117 // Let's wait for the process to finish.
118 WaitForSingleObject(proc_info
.process_handle(), INFINITE
);
121 GetExitCodeProcess(proc_info
.process_handle(), &dw_exit_code
);
122 *exit_code
= static_cast<int>(dw_exit_code
);
127 // Reads from the provided file descriptor and appends to output. Returns false
128 // if the fd is closed or there is an unexpected error (not
129 // EINTR/EAGAIN/EWOULDBLOCK).
130 bool ReadFromPipe(int fd
, std::string
* output
) {
132 int bytes_read
= HANDLE_EINTR(read(fd
, buffer
, sizeof(buffer
)));
133 if (bytes_read
== -1) {
134 return errno
== EAGAIN
|| errno
== EWOULDBLOCK
;
135 } else if (bytes_read
<= 0) {
138 output
->append(buffer
, bytes_read
);
142 bool ExecProcess(const base::CommandLine
& cmdline
,
143 const base::FilePath
& startup_dir
,
144 std::string
* std_out
,
145 std::string
* std_err
,
147 *exit_code
= EXIT_FAILURE
;
149 std::vector
<std::string
> argv
= cmdline
.argv();
151 int out_fd
[2], err_fd
[2];
153 base::InjectiveMultimap fd_shuffle1
, fd_shuffle2
;
154 scoped_ptr
<char*[]> argv_cstr(new char*[argv
.size() + 1]);
156 fd_shuffle1
.reserve(3);
157 fd_shuffle2
.reserve(3);
159 if (pipe(out_fd
) < 0)
161 base::ScopedFD
out_read(out_fd
[0]), out_write(out_fd
[1]);
163 if (pipe(err_fd
) < 0)
165 base::ScopedFD
err_read(err_fd
[0]), err_write(err_fd
[1]);
167 if (out_read
.get() >= FD_SETSIZE
|| err_read
.get() >= FD_SETSIZE
)
170 switch (pid
= fork()) {
175 // DANGER: no calls to malloc are allowed from now on:
176 // http://crbug.com/36678
178 // Obscure fork() rule: in the child, if you don't end up doing exec*(),
179 // you call _exit() instead of exit(). This is because _exit() does not
180 // call any previously-registered (in the parent) exit handlers, which
181 // might do things like block waiting for threads that don't even exist
183 int dev_null
= open("/dev/null", O_WRONLY
);
187 fd_shuffle1
.push_back(
188 base::InjectionArc(out_write
.get(), STDOUT_FILENO
, true));
189 fd_shuffle1
.push_back(
190 base::InjectionArc(err_write
.get(), STDERR_FILENO
, true));
191 fd_shuffle1
.push_back(
192 base::InjectionArc(dev_null
, STDIN_FILENO
, true));
193 // Adding another element here? Remeber to increase the argument to
196 for (size_t i
= 0; i
< fd_shuffle1
.size(); ++i
)
197 fd_shuffle2
.push_back(fd_shuffle1
[i
]);
199 if (!ShuffleFileDescriptors(&fd_shuffle1
))
202 base::SetCurrentDirectory(startup_dir
);
204 // TODO(brettw) the base version GetAppOutput does a
205 // CloseSuperfluousFds call here. Do we need this?
207 for (size_t i
= 0; i
< argv
.size(); i
++)
208 argv_cstr
[i
] = const_cast<char*>(argv
[i
].c_str());
209 argv_cstr
[argv
.size()] = nullptr;
210 execvp(argv_cstr
[0], argv_cstr
.get());
215 // Close our writing end of pipe now. Otherwise later read would not
216 // be able to detect end of child's output (in theory we could still
217 // write to the pipe).
221 bool out_open
= true, err_open
= true;
222 while (out_open
|| err_open
) {
225 FD_SET(out_read
.get(), &read_fds
);
226 FD_SET(err_read
.get(), &read_fds
);
228 HANDLE_EINTR(select(std::max(out_read
.get(), err_read
.get()) + 1,
229 &read_fds
, nullptr, nullptr, nullptr));
232 if (FD_ISSET(out_read
.get(), &read_fds
))
233 out_open
= ReadFromPipe(out_read
.get(), std_out
);
234 if (FD_ISSET(err_read
.get(), &read_fds
))
235 err_open
= ReadFromPipe(err_read
.get(), std_err
);
238 return base::WaitForExitCode(pid
, exit_code
);
246 } // namespace internal