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