launch_win.cc revision a3f6a49ab37290eeeb8db0f41ec0f1cb74a68be7
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.
4
5#include "base/process/launch.h"
6
7#include <fcntl.h>
8#include <io.h>
9#include <windows.h>
10#include <userenv.h>
11#include <psapi.h>
12
13#include <ios>
14
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/message_loop.h"
22#include "base/metrics/histogram.h"
23#include "base/process/kill.h"
24#include "base/sys_info.h"
25#include "base/win/object_watcher.h"
26#include "base/win/scoped_handle.h"
27#include "base/win/scoped_process_information.h"
28#include "base/win/startup_information.h"
29#include "base/win/windows_version.h"
30
31// userenv.dll is required for CreateEnvironmentBlock().
32#pragma comment(lib, "userenv.lib")
33
34namespace base {
35
36namespace {
37
38// This exit code is used by the Windows task manager when it kills a
39// process.  It's value is obviously not that unique, and it's
40// surprising to me that the task manager uses this value, but it
41// seems to be common practice on Windows to test for it as an
42// indication that the task manager has killed something if the
43// process goes away.
44const DWORD kProcessKilledExitCode = 1;
45
46}  // namespace
47
48void RouteStdioToConsole() {
49  // Don't change anything if stdout or stderr already point to a
50  // valid stream.
51  //
52  // If we are running under Buildbot or under Cygwin's default
53  // terminal (mintty), stderr and stderr will be pipe handles.  In
54  // that case, we don't want to open CONOUT$, because its output
55  // likely does not go anywhere.
56  //
57  // We don't use GetStdHandle() to check stdout/stderr here because
58  // it can return dangling IDs of handles that were never inherited
59  // by this process.  These IDs could have been reused by the time
60  // this function is called.  The CRT checks the validity of
61  // stdout/stderr on startup (before the handle IDs can be reused).
62  // _fileno(stdout) will return -2 (_NO_CONSOLE_FILENO) if stdout was
63  // invalid.
64  if (_fileno(stdout) >= 0 || _fileno(stderr) >= 0)
65    return;
66
67  if (!AttachConsole(ATTACH_PARENT_PROCESS)) {
68    unsigned int result = GetLastError();
69    // Was probably already attached.
70    if (result == ERROR_ACCESS_DENIED)
71      return;
72    // Don't bother creating a new console for each child process if the
73    // parent process is invalid (eg: crashed).
74    if (result == ERROR_GEN_FAILURE)
75      return;
76    // Make a new console if attaching to parent fails with any other error.
77    // It should be ERROR_INVALID_HANDLE at this point, which means the browser
78    // was likely not started from a console.
79    AllocConsole();
80  }
81
82  // Arbitrary byte count to use when buffering output lines.  More
83  // means potential waste, less means more risk of interleaved
84  // log-lines in output.
85  enum { kOutputBufferSize = 64 * 1024 };
86
87  if (freopen("CONOUT$", "w", stdout)) {
88    setvbuf(stdout, NULL, _IOLBF, kOutputBufferSize);
89    // Overwrite FD 1 for the benefit of any code that uses this FD
90    // directly.  This is safe because the CRT allocates FDs 0, 1 and
91    // 2 at startup even if they don't have valid underlying Windows
92    // handles.  This means we won't be overwriting an FD created by
93    // _open() after startup.
94    _dup2(_fileno(stdout), 1);
95  }
96  if (freopen("CONOUT$", "w", stderr)) {
97    setvbuf(stderr, NULL, _IOLBF, kOutputBufferSize);
98    _dup2(_fileno(stderr), 2);
99  }
100
101  // Fix all cout, wcout, cin, wcin, cerr, wcerr, clog and wclog.
102  std::ios::sync_with_stdio();
103}
104
105bool LaunchProcess(const string16& cmdline,
106                   const LaunchOptions& options,
107                   win::ScopedHandle* process_handle) {
108  win::StartupInformation startup_info_wrapper;
109  STARTUPINFO* startup_info = startup_info_wrapper.startup_info();
110
111  if (options.empty_desktop_name)
112    startup_info->lpDesktop = L"";
113  startup_info->dwFlags = STARTF_USESHOWWINDOW;
114  startup_info->wShowWindow = options.start_hidden ? SW_HIDE : SW_SHOW;
115
116  if (options.stdin_handle || options.stdout_handle || options.stderr_handle) {
117    DCHECK(options.inherit_handles);
118    DCHECK(options.stdin_handle);
119    DCHECK(options.stdout_handle);
120    DCHECK(options.stderr_handle);
121    startup_info->dwFlags |= STARTF_USESTDHANDLES;
122    startup_info->hStdInput = options.stdin_handle;
123    startup_info->hStdOutput = options.stdout_handle;
124    startup_info->hStdError = options.stderr_handle;
125  }
126
127  DWORD flags = 0;
128
129  if (options.job_handle) {
130    flags |= CREATE_SUSPENDED;
131
132    // If this code is run under a debugger, the launched process is
133    // automatically associated with a job object created by the debugger.
134    // The CREATE_BREAKAWAY_FROM_JOB flag is used to prevent this.
135    flags |= CREATE_BREAKAWAY_FROM_JOB;
136  }
137
138  if (options.force_breakaway_from_job_)
139    flags |= CREATE_BREAKAWAY_FROM_JOB;
140
141  PROCESS_INFORMATION temp_process_info = {};
142
143  if (options.as_user) {
144    flags |= CREATE_UNICODE_ENVIRONMENT;
145    void* enviroment_block = NULL;
146
147    if (!CreateEnvironmentBlock(&enviroment_block, options.as_user, FALSE)) {
148      DPLOG(ERROR);
149      return false;
150    }
151
152    BOOL launched =
153        CreateProcessAsUser(options.as_user, NULL,
154                            const_cast<wchar_t*>(cmdline.c_str()),
155                            NULL, NULL, options.inherit_handles, flags,
156                            enviroment_block, NULL, startup_info,
157                            &temp_process_info);
158    DestroyEnvironmentBlock(enviroment_block);
159    if (!launched) {
160      DPLOG(ERROR);
161      return false;
162    }
163  } else {
164    if (!CreateProcess(NULL,
165                       const_cast<wchar_t*>(cmdline.c_str()), NULL, NULL,
166                       options.inherit_handles, flags, NULL, NULL,
167                       startup_info, &temp_process_info)) {
168      DPLOG(ERROR);
169      return false;
170    }
171  }
172  base::win::ScopedProcessInformation process_info(temp_process_info);
173
174  if (options.job_handle) {
175    if (0 == AssignProcessToJobObject(options.job_handle,
176                                      process_info.process_handle())) {
177      DLOG(ERROR) << "Could not AssignProcessToObject.";
178      KillProcess(process_info.process_handle(), kProcessKilledExitCode, true);
179      return false;
180    }
181
182    ResumeThread(process_info.thread_handle());
183  }
184
185  if (options.wait)
186    WaitForSingleObject(process_info.process_handle(), INFINITE);
187
188  // If the caller wants the process handle, we won't close it.
189  if (process_handle)
190    process_handle->Set(process_info.TakeProcessHandle());
191
192  return true;
193}
194
195bool LaunchProcess(const CommandLine& cmdline,
196                   const LaunchOptions& options,
197                   ProcessHandle* process_handle) {
198  if (!process_handle)
199    return LaunchProcess(cmdline.GetCommandLineString(), options, NULL);
200
201  win::ScopedHandle process;
202  bool rv = LaunchProcess(cmdline.GetCommandLineString(), options, &process);
203  *process_handle = process.Take();
204  return rv;
205}
206
207bool SetJobObjectLimitFlags(HANDLE job_object, DWORD limit_flags) {
208  JOBOBJECT_EXTENDED_LIMIT_INFORMATION limit_info = {0};
209  limit_info.BasicLimitInformation.LimitFlags = limit_flags;
210  return 0 != SetInformationJobObject(
211      job_object,
212      JobObjectExtendedLimitInformation,
213      &limit_info,
214      sizeof(limit_info));
215}
216
217bool GetAppOutput(const CommandLine& cl, std::string* output) {
218  return GetAppOutput(cl.GetCommandLineString(), output);
219}
220
221bool GetAppOutput(const StringPiece16& cl, std::string* output) {
222  HANDLE out_read = NULL;
223  HANDLE out_write = NULL;
224
225  SECURITY_ATTRIBUTES sa_attr;
226  // Set the bInheritHandle flag so pipe handles are inherited.
227  sa_attr.nLength = sizeof(SECURITY_ATTRIBUTES);
228  sa_attr.bInheritHandle = TRUE;
229  sa_attr.lpSecurityDescriptor = NULL;
230
231  // Create the pipe for the child process's STDOUT.
232  if (!CreatePipe(&out_read, &out_write, &sa_attr, 0)) {
233    NOTREACHED() << "Failed to create pipe";
234    return false;
235  }
236
237  // Ensure we don't leak the handles.
238  win::ScopedHandle scoped_out_read(out_read);
239  win::ScopedHandle scoped_out_write(out_write);
240
241  // Ensure the read handle to the pipe for STDOUT is not inherited.
242  if (!SetHandleInformation(out_read, HANDLE_FLAG_INHERIT, 0)) {
243    NOTREACHED() << "Failed to disabled pipe inheritance";
244    return false;
245  }
246
247  FilePath::StringType writable_command_line_string;
248  writable_command_line_string.assign(cl.data(), cl.size());
249
250  STARTUPINFO start_info = {};
251
252  start_info.cb = sizeof(STARTUPINFO);
253  start_info.hStdOutput = out_write;
254  // Keep the normal stdin and stderr.
255  start_info.hStdInput = GetStdHandle(STD_INPUT_HANDLE);
256  start_info.hStdError = GetStdHandle(STD_ERROR_HANDLE);
257  start_info.dwFlags |= STARTF_USESTDHANDLES;
258
259  // Create the child process.
260  PROCESS_INFORMATION temp_process_info = {};
261  if (!CreateProcess(NULL,
262                     &writable_command_line_string[0],
263                     NULL, NULL,
264                     TRUE,  // Handles are inherited.
265                     0, NULL, NULL, &start_info, &temp_process_info)) {
266    NOTREACHED() << "Failed to start process";
267    return false;
268  }
269  base::win::ScopedProcessInformation proc_info(temp_process_info);
270
271  // Close our writing end of pipe now. Otherwise later read would not be able
272  // to detect end of child's output.
273  scoped_out_write.Close();
274
275  // Read output from the child process's pipe for STDOUT
276  const int kBufferSize = 1024;
277  char buffer[kBufferSize];
278
279  for (;;) {
280    DWORD bytes_read = 0;
281    BOOL success = ReadFile(out_read, buffer, kBufferSize, &bytes_read, NULL);
282    if (!success || bytes_read == 0)
283      break;
284    output->append(buffer, bytes_read);
285  }
286
287  // Let's wait for the process to finish.
288  WaitForSingleObject(proc_info.process_handle(), INFINITE);
289
290  return true;
291}
292
293void RaiseProcessToHighPriority() {
294  SetPriorityClass(GetCurrentProcess(), HIGH_PRIORITY_CLASS);
295}
296
297}  // namespace base
298