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_util.h"
15 #include "base/bind.h"
16 #include "base/bind_helpers.h"
17 #include "base/command_line.h"
18 #include "base/debug/stack_trace.h"
19 #include "base/logging.h"
20 #include "base/memory/scoped_ptr.h"
21 #include "base/message_loop.h"
22 #include "base/metrics/histogram.h"
23 #include "base/sys_info.h"
24 #include "base/win/object_watcher.h"
25 #include "base/win/scoped_handle.h"
26 #include "base/win/scoped_process_information.h"
27 #include "base/win/windows_version.h"
29 // userenv.dll is required for CreateEnvironmentBlock().
30 #pragma comment(lib, "userenv.lib")
36 // This exit code is used by the Windows task manager when it kills a
37 // process. It's value is obviously not that unique, and it's
38 // surprising to me that the task manager uses this value, but it
39 // seems to be common practice on Windows to test for it as an
40 // indication that the task manager has killed something if the
42 const DWORD kProcessKilledExitCode
= 1;
46 void RouteStdioToConsole() {
47 // Don't change anything if stdout or stderr already point to a
50 // If we are running under Buildbot or under Cygwin's default
51 // terminal (mintty), stderr and stderr will be pipe handles. In
52 // that case, we don't want to open CONOUT$, because its output
53 // likely does not go anywhere.
55 // We don't use GetStdHandle() to check stdout/stderr here because
56 // it can return dangling IDs of handles that were never inherited
57 // by this process. These IDs could have been reused by the time
58 // this function is called. The CRT checks the validity of
59 // stdout/stderr on startup (before the handle IDs can be reused).
60 // _fileno(stdout) will return -2 (_NO_CONSOLE_FILENO) if stdout was
62 if (_fileno(stdout
) >= 0 || _fileno(stderr
) >= 0)
65 if (!AttachConsole(ATTACH_PARENT_PROCESS
)) {
66 unsigned int result
= GetLastError();
67 // Was probably already attached.
68 if (result
== ERROR_ACCESS_DENIED
)
70 // Don't bother creating a new console for each child process if the
71 // parent process is invalid (eg: crashed).
72 if (result
== ERROR_GEN_FAILURE
)
74 // Make a new console if attaching to parent fails with any other error.
75 // It should be ERROR_INVALID_HANDLE at this point, which means the browser
76 // was likely not started from a console.
80 // Arbitrary byte count to use when buffering output lines. More
81 // means potential waste, less means more risk of interleaved
82 // log-lines in output.
83 enum { kOutputBufferSize
= 64 * 1024 };
85 if (freopen("CONOUT$", "w", stdout
)) {
86 setvbuf(stdout
, NULL
, _IOLBF
, kOutputBufferSize
);
87 // Overwrite FD 1 for the benefit of any code that uses this FD
88 // directly. This is safe because the CRT allocates FDs 0, 1 and
89 // 2 at startup even if they don't have valid underlying Windows
90 // handles. This means we won't be overwriting an FD created by
91 // _open() after startup.
92 _dup2(_fileno(stdout
), 1);
94 if (freopen("CONOUT$", "w", stderr
)) {
95 setvbuf(stderr
, NULL
, _IOLBF
, kOutputBufferSize
);
96 _dup2(_fileno(stderr
), 2);
99 // Fix all cout, wcout, cin, wcin, cerr, wcerr, clog and wclog.
100 std::ios::sync_with_stdio();
103 bool LaunchProcess(const string16
& cmdline
,
104 const LaunchOptions
& options
,
105 ProcessHandle
* process_handle
) {
106 STARTUPINFO startup_info
= {};
107 startup_info
.cb
= sizeof(startup_info
);
108 if (options
.empty_desktop_name
)
109 startup_info
.lpDesktop
= L
"";
110 startup_info
.dwFlags
= STARTF_USESHOWWINDOW
;
111 startup_info
.wShowWindow
= options
.start_hidden
? SW_HIDE
: SW_SHOW
;
113 if (options
.stdin_handle
|| options
.stdout_handle
|| options
.stderr_handle
) {
114 DCHECK(options
.inherit_handles
);
115 DCHECK(options
.stdin_handle
);
116 DCHECK(options
.stdout_handle
);
117 DCHECK(options
.stderr_handle
);
118 startup_info
.dwFlags
|= STARTF_USESTDHANDLES
;
119 startup_info
.hStdInput
= options
.stdin_handle
;
120 startup_info
.hStdOutput
= options
.stdout_handle
;
121 startup_info
.hStdError
= options
.stderr_handle
;
126 if (options
.job_handle
) {
127 flags
|= CREATE_SUSPENDED
;
129 // If this code is run under a debugger, the launched process is
130 // automatically associated with a job object created by the debugger.
131 // The CREATE_BREAKAWAY_FROM_JOB flag is used to prevent this.
132 flags
|= CREATE_BREAKAWAY_FROM_JOB
;
135 if (options
.force_breakaway_from_job_
)
136 flags
|= CREATE_BREAKAWAY_FROM_JOB
;
138 base::win::ScopedProcessInformation process_info
;
140 if (options
.as_user
) {
141 flags
|= CREATE_UNICODE_ENVIRONMENT
;
142 void* enviroment_block
= NULL
;
144 if (!CreateEnvironmentBlock(&enviroment_block
, options
.as_user
, FALSE
)) {
150 CreateProcessAsUser(options
.as_user
, NULL
,
151 const_cast<wchar_t*>(cmdline
.c_str()),
152 NULL
, NULL
, options
.inherit_handles
, flags
,
153 enviroment_block
, NULL
, &startup_info
,
154 process_info
.Receive());
155 DestroyEnvironmentBlock(enviroment_block
);
161 if (!CreateProcess(NULL
,
162 const_cast<wchar_t*>(cmdline
.c_str()), NULL
, NULL
,
163 options
.inherit_handles
, flags
, NULL
, NULL
,
164 &startup_info
, process_info
.Receive())) {
170 if (options
.job_handle
) {
171 if (0 == AssignProcessToJobObject(options
.job_handle
,
172 process_info
.process_handle())) {
173 DLOG(ERROR
) << "Could not AssignProcessToObject.";
174 KillProcess(process_info
.process_handle(), kProcessKilledExitCode
, true);
178 ResumeThread(process_info
.thread_handle());
182 WaitForSingleObject(process_info
.process_handle(), INFINITE
);
184 // If the caller wants the process handle, we won't close it.
186 *process_handle
= process_info
.TakeProcessHandle();
191 bool LaunchProcess(const CommandLine
& cmdline
,
192 const LaunchOptions
& options
,
193 ProcessHandle
* process_handle
) {
194 return LaunchProcess(cmdline
.GetCommandLineString(), options
, process_handle
);
197 bool SetJobObjectAsKillOnJobClose(HANDLE job_object
) {
198 JOBOBJECT_EXTENDED_LIMIT_INFORMATION limit_info
= {0};
199 limit_info
.BasicLimitInformation
.LimitFlags
=
200 JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE
;
201 return 0 != SetInformationJobObject(
203 JobObjectExtendedLimitInformation
,
208 bool GetAppOutput(const CommandLine
& cl
, std::string
* output
) {
209 HANDLE out_read
= NULL
;
210 HANDLE out_write
= NULL
;
212 SECURITY_ATTRIBUTES sa_attr
;
213 // Set the bInheritHandle flag so pipe handles are inherited.
214 sa_attr
.nLength
= sizeof(SECURITY_ATTRIBUTES
);
215 sa_attr
.bInheritHandle
= TRUE
;
216 sa_attr
.lpSecurityDescriptor
= NULL
;
218 // Create the pipe for the child process's STDOUT.
219 if (!CreatePipe(&out_read
, &out_write
, &sa_attr
, 0)) {
220 NOTREACHED() << "Failed to create pipe";
224 // Ensure we don't leak the handles.
225 win::ScopedHandle
scoped_out_read(out_read
);
226 win::ScopedHandle
scoped_out_write(out_write
);
228 // Ensure the read handle to the pipe for STDOUT is not inherited.
229 if (!SetHandleInformation(out_read
, HANDLE_FLAG_INHERIT
, 0)) {
230 NOTREACHED() << "Failed to disabled pipe inheritance";
234 FilePath::StringType
writable_command_line_string(cl
.GetCommandLineString());
236 base::win::ScopedProcessInformation proc_info
;
237 STARTUPINFO start_info
= { 0 };
239 start_info
.cb
= sizeof(STARTUPINFO
);
240 start_info
.hStdOutput
= out_write
;
241 // Keep the normal stdin and stderr.
242 start_info
.hStdInput
= GetStdHandle(STD_INPUT_HANDLE
);
243 start_info
.hStdError
= GetStdHandle(STD_ERROR_HANDLE
);
244 start_info
.dwFlags
|= STARTF_USESTDHANDLES
;
246 // Create the child process.
247 if (!CreateProcess(NULL
,
248 &writable_command_line_string
[0],
250 TRUE
, // Handles are inherited.
251 0, NULL
, NULL
, &start_info
, proc_info
.Receive())) {
252 NOTREACHED() << "Failed to start process";
256 // Close our writing end of pipe now. Otherwise later read would not be able
257 // to detect end of child's output.
258 scoped_out_write
.Close();
260 // Read output from the child process's pipe for STDOUT
261 const int kBufferSize
= 1024;
262 char buffer
[kBufferSize
];
265 DWORD bytes_read
= 0;
266 BOOL success
= ReadFile(out_read
, buffer
, kBufferSize
, &bytes_read
, NULL
);
267 if (!success
|| bytes_read
== 0)
269 output
->append(buffer
, bytes_read
);
272 // Let's wait for the process to finish.
273 WaitForSingleObject(proc_info
.process_handle(), INFINITE
);
278 void RaiseProcessToHighPriority() {
279 SetPriorityClass(GetCurrentProcess(), HIGH_PRIORITY_CLASS
);