1 // Copyright (c) 2012 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/process/launch.h"
17 #include "base/bind.h"
18 #include "base/bind_helpers.h"
19 #include "base/command_line.h"
20 #include "base/debug/stack_trace.h"
21 #include "base/logging.h"
22 #include "base/memory/scoped_ptr.h"
23 #include "base/message_loop/message_loop.h"
24 #include "base/metrics/histogram.h"
25 #include "base/process/kill.h"
26 #include "base/strings/utf_string_conversions.h"
27 #include "base/sys_info.h"
28 #include "base/win/object_watcher.h"
29 #include "base/win/scoped_handle.h"
30 #include "base/win/scoped_process_information.h"
31 #include "base/win/startup_information.h"
32 #include "base/win/windows_version.h"
34 // userenv.dll is required for CreateEnvironmentBlock().
35 #pragma comment(lib, "userenv.lib")
41 // This exit code is used by the Windows task manager when it kills a
42 // process. It's value is obviously not that unique, and it's
43 // surprising to me that the task manager uses this value, but it
44 // seems to be common practice on Windows to test for it as an
45 // indication that the task manager has killed something if the
47 const DWORD kProcessKilledExitCode
= 1;
49 bool GetAppOutputInternal(const StringPiece16
& cl
,
51 std::string
* output
) {
52 HANDLE out_read
= NULL
;
53 HANDLE out_write
= NULL
;
55 SECURITY_ATTRIBUTES sa_attr
;
56 // Set the bInheritHandle flag so pipe handles are inherited.
57 sa_attr
.nLength
= sizeof(SECURITY_ATTRIBUTES
);
58 sa_attr
.bInheritHandle
= TRUE
;
59 sa_attr
.lpSecurityDescriptor
= NULL
;
61 // Create the pipe for the child process's STDOUT.
62 if (!CreatePipe(&out_read
, &out_write
, &sa_attr
, 0)) {
63 NOTREACHED() << "Failed to create pipe";
67 // Ensure we don't leak the handles.
68 win::ScopedHandle
scoped_out_read(out_read
);
69 win::ScopedHandle
scoped_out_write(out_write
);
71 // Ensure the read handles to the pipes are not inherited.
72 if (!SetHandleInformation(out_read
, HANDLE_FLAG_INHERIT
, 0)) {
73 NOTREACHED() << "Failed to disabled pipe inheritance";
77 FilePath::StringType writable_command_line_string
;
78 writable_command_line_string
.assign(cl
.data(), cl
.size());
80 STARTUPINFO start_info
= {};
82 start_info
.cb
= sizeof(STARTUPINFO
);
83 start_info
.hStdOutput
= out_write
;
84 // Keep the normal stdin.
85 start_info
.hStdInput
= GetStdHandle(STD_INPUT_HANDLE
);
87 start_info
.hStdError
= out_write
;
89 start_info
.hStdError
= GetStdHandle(STD_ERROR_HANDLE
);
91 start_info
.dwFlags
|= STARTF_USESTDHANDLES
;
93 // Create the child process.
94 PROCESS_INFORMATION temp_process_info
= {};
95 if (!CreateProcess(NULL
,
96 &writable_command_line_string
[0],
98 TRUE
, // Handles are inherited.
99 0, NULL
, NULL
, &start_info
, &temp_process_info
)) {
100 NOTREACHED() << "Failed to start process";
103 base::win::ScopedProcessInformation
proc_info(temp_process_info
);
105 // Close our writing end of pipe now. Otherwise later read would not be able
106 // to detect end of child's output.
107 scoped_out_write
.Close();
109 // Read output from the child process's pipe for STDOUT
110 const int kBufferSize
= 1024;
111 char buffer
[kBufferSize
];
114 DWORD bytes_read
= 0;
115 BOOL success
= ReadFile(out_read
, buffer
, kBufferSize
, &bytes_read
, NULL
);
116 if (!success
|| bytes_read
== 0)
118 output
->append(buffer
, bytes_read
);
121 // Let's wait for the process to finish.
122 WaitForSingleObject(proc_info
.process_handle(), INFINITE
);
125 base::TerminationStatus status
= GetTerminationStatus(
126 proc_info
.process_handle(), &exit_code
);
127 return status
!= base::TERMINATION_STATUS_PROCESS_CRASHED
&&
128 status
!= base::TERMINATION_STATUS_ABNORMAL_TERMINATION
;
133 void RouteStdioToConsole(bool create_console_if_not_found
) {
134 // Don't change anything if stdout or stderr already point to a
137 // If we are running under Buildbot or under Cygwin's default
138 // terminal (mintty), stderr and stderr will be pipe handles. In
139 // that case, we don't want to open CONOUT$, because its output
140 // likely does not go anywhere.
142 // We don't use GetStdHandle() to check stdout/stderr here because
143 // it can return dangling IDs of handles that were never inherited
144 // by this process. These IDs could have been reused by the time
145 // this function is called. The CRT checks the validity of
146 // stdout/stderr on startup (before the handle IDs can be reused).
147 // _fileno(stdout) will return -2 (_NO_CONSOLE_FILENO) if stdout was
149 if (_fileno(stdout
) >= 0 || _fileno(stderr
) >= 0) {
150 // _fileno was broken for SUBSYSTEM:WINDOWS from VS2010 to VS2012/2013.
151 // http://crbug.com/358267. Confirm that the underlying HANDLE is valid
154 // This causes NaCl tests to hang on XP for reasons unclear, perhaps due
155 // to not being able to inherit handles. Since it's only for debugging,
156 // and redirecting still works, punt for now.
157 if (base::win::GetVersion() < base::win::VERSION_VISTA
)
160 intptr_t stdout_handle
= _get_osfhandle(_fileno(stdout
));
161 intptr_t stderr_handle
= _get_osfhandle(_fileno(stderr
));
162 if (stdout_handle
>= 0 || stderr_handle
>= 0)
166 if (!AttachConsole(ATTACH_PARENT_PROCESS
)) {
167 unsigned int result
= GetLastError();
168 // Was probably already attached.
169 if (result
== ERROR_ACCESS_DENIED
)
171 // Don't bother creating a new console for each child process if the
172 // parent process is invalid (eg: crashed).
173 if (result
== ERROR_GEN_FAILURE
)
175 if (create_console_if_not_found
) {
176 // Make a new console if attaching to parent fails with any other error.
177 // It should be ERROR_INVALID_HANDLE at this point, which means the
178 // browser was likely not started from a console.
185 // Arbitrary byte count to use when buffering output lines. More
186 // means potential waste, less means more risk of interleaved
187 // log-lines in output.
188 enum { kOutputBufferSize
= 64 * 1024 };
190 if (freopen("CONOUT$", "w", stdout
)) {
191 setvbuf(stdout
, NULL
, _IOLBF
, kOutputBufferSize
);
192 // Overwrite FD 1 for the benefit of any code that uses this FD
193 // directly. This is safe because the CRT allocates FDs 0, 1 and
194 // 2 at startup even if they don't have valid underlying Windows
195 // handles. This means we won't be overwriting an FD created by
196 // _open() after startup.
197 _dup2(_fileno(stdout
), 1);
199 if (freopen("CONOUT$", "w", stderr
)) {
200 setvbuf(stderr
, NULL
, _IOLBF
, kOutputBufferSize
);
201 _dup2(_fileno(stderr
), 2);
204 // Fix all cout, wcout, cin, wcin, cerr, wcerr, clog and wclog.
205 std::ios::sync_with_stdio();
208 Process
LaunchProcess(const CommandLine
& cmdline
,
209 const LaunchOptions
& options
) {
210 return LaunchProcess(cmdline
.GetCommandLineString(), options
);
213 Process
LaunchProcess(const string16
& cmdline
,
214 const LaunchOptions
& options
) {
215 win::StartupInformation startup_info_wrapper
;
216 STARTUPINFO
* startup_info
= startup_info_wrapper
.startup_info();
218 bool inherit_handles
= options
.inherit_handles
;
220 if (options
.handles_to_inherit
) {
221 if (options
.handles_to_inherit
->empty()) {
222 inherit_handles
= false;
224 if (base::win::GetVersion() < base::win::VERSION_VISTA
) {
225 DLOG(ERROR
) << "Specifying handles to inherit requires Vista or later.";
229 if (options
.handles_to_inherit
->size() >
230 std::numeric_limits
<DWORD
>::max() / sizeof(HANDLE
)) {
231 DLOG(ERROR
) << "Too many handles to inherit.";
235 if (!startup_info_wrapper
.InitializeProcThreadAttributeList(1)) {
240 if (!startup_info_wrapper
.UpdateProcThreadAttribute(
241 PROC_THREAD_ATTRIBUTE_HANDLE_LIST
,
242 const_cast<HANDLE
*>(&options
.handles_to_inherit
->at(0)),
243 static_cast<DWORD
>(options
.handles_to_inherit
->size() *
249 inherit_handles
= true;
250 flags
|= EXTENDED_STARTUPINFO_PRESENT
;
254 if (options
.empty_desktop_name
)
255 startup_info
->lpDesktop
= const_cast<wchar_t*>(L
"");
256 startup_info
->dwFlags
= STARTF_USESHOWWINDOW
;
257 startup_info
->wShowWindow
= options
.start_hidden
? SW_HIDE
: SW_SHOW
;
259 if (options
.stdin_handle
|| options
.stdout_handle
|| options
.stderr_handle
) {
260 DCHECK(inherit_handles
);
261 DCHECK(options
.stdin_handle
);
262 DCHECK(options
.stdout_handle
);
263 DCHECK(options
.stderr_handle
);
264 startup_info
->dwFlags
|= STARTF_USESTDHANDLES
;
265 startup_info
->hStdInput
= options
.stdin_handle
;
266 startup_info
->hStdOutput
= options
.stdout_handle
;
267 startup_info
->hStdError
= options
.stderr_handle
;
270 if (options
.job_handle
) {
271 flags
|= CREATE_SUSPENDED
;
273 // If this code is run under a debugger, the launched process is
274 // automatically associated with a job object created by the debugger.
275 // The CREATE_BREAKAWAY_FROM_JOB flag is used to prevent this.
276 flags
|= CREATE_BREAKAWAY_FROM_JOB
;
279 if (options
.force_breakaway_from_job_
)
280 flags
|= CREATE_BREAKAWAY_FROM_JOB
;
282 PROCESS_INFORMATION temp_process_info
= {};
284 string16
writable_cmdline(cmdline
);
285 if (options
.as_user
) {
286 flags
|= CREATE_UNICODE_ENVIRONMENT
;
287 void* enviroment_block
= NULL
;
289 if (!CreateEnvironmentBlock(&enviroment_block
, options
.as_user
, FALSE
)) {
295 CreateProcessAsUser(options
.as_user
, NULL
,
296 &writable_cmdline
[0],
297 NULL
, NULL
, inherit_handles
, flags
,
298 enviroment_block
, NULL
, startup_info
,
300 DestroyEnvironmentBlock(enviroment_block
);
302 DPLOG(ERROR
) << "Command line:" << std::endl
<< UTF16ToUTF8(cmdline
)
307 if (!CreateProcess(NULL
,
308 &writable_cmdline
[0], NULL
, NULL
,
309 inherit_handles
, flags
, NULL
, NULL
,
310 startup_info
, &temp_process_info
)) {
311 DPLOG(ERROR
) << "Command line:" << std::endl
<< UTF16ToUTF8(cmdline
)
316 base::win::ScopedProcessInformation
process_info(temp_process_info
);
318 if (options
.job_handle
) {
319 if (0 == AssignProcessToJobObject(options
.job_handle
,
320 process_info
.process_handle())) {
321 DLOG(ERROR
) << "Could not AssignProcessToObject.";
322 Process
scoped_process(process_info
.TakeProcessHandle());
323 scoped_process
.Terminate(kProcessKilledExitCode
, true);
327 ResumeThread(process_info
.thread_handle());
331 WaitForSingleObject(process_info
.process_handle(), INFINITE
);
333 return Process(process_info
.TakeProcessHandle());
336 Process
LaunchElevatedProcess(const CommandLine
& cmdline
,
337 const LaunchOptions
& options
) {
338 const string16 file
= cmdline
.GetProgram().value();
339 const string16 arguments
= cmdline
.GetArgumentsString();
341 SHELLEXECUTEINFO shex_info
= {};
342 shex_info
.cbSize
= sizeof(shex_info
);
343 shex_info
.fMask
= SEE_MASK_NOCLOSEPROCESS
;
344 shex_info
.hwnd
= GetActiveWindow();
345 shex_info
.lpVerb
= L
"runas";
346 shex_info
.lpFile
= file
.c_str();
347 shex_info
.lpParameters
= arguments
.c_str();
348 shex_info
.lpDirectory
= NULL
;
349 shex_info
.nShow
= options
.start_hidden
? SW_HIDE
: SW_SHOW
;
350 shex_info
.hInstApp
= NULL
;
352 if (!ShellExecuteEx(&shex_info
)) {
358 WaitForSingleObject(shex_info
.hProcess
, INFINITE
);
360 return Process(shex_info
.hProcess
);
363 bool SetJobObjectLimitFlags(HANDLE job_object
, DWORD limit_flags
) {
364 JOBOBJECT_EXTENDED_LIMIT_INFORMATION limit_info
= {};
365 limit_info
.BasicLimitInformation
.LimitFlags
= limit_flags
;
366 return 0 != SetInformationJobObject(
368 JobObjectExtendedLimitInformation
,
373 bool GetAppOutput(const CommandLine
& cl
, std::string
* output
) {
374 return GetAppOutput(cl
.GetCommandLineString(), output
);
377 bool GetAppOutputAndError(const CommandLine
& cl
, std::string
* output
) {
378 return GetAppOutputInternal(cl
.GetCommandLineString(), true, output
);
381 bool GetAppOutput(const StringPiece16
& cl
, std::string
* output
) {
382 return GetAppOutputInternal(cl
, false, output
);
385 void RaiseProcessToHighPriority() {
386 SetPriorityClass(GetCurrentProcess(), HIGH_PRIORITY_CLASS
);