This source file includes following definitions.
- RouteStdioToConsole
- LaunchProcess
- LaunchProcess
- LaunchElevatedProcess
- SetJobObjectLimitFlags
- GetAppOutput
- GetAppOutput
- RaiseProcessToHighPriority
#include "base/process/launch.h"
#include <fcntl.h>
#include <io.h>
#include <shellapi.h>
#include <windows.h>
#include <userenv.h>
#include <psapi.h>
#include <ios>
#include <limits>
#include "base/bind.h"
#include "base/bind_helpers.h"
#include "base/command_line.h"
#include "base/debug/stack_trace.h"
#include "base/logging.h"
#include "base/memory/scoped_ptr.h"
#include "base/message_loop/message_loop.h"
#include "base/metrics/histogram.h"
#include "base/process/kill.h"
#include "base/sys_info.h"
#include "base/win/object_watcher.h"
#include "base/win/scoped_handle.h"
#include "base/win/scoped_process_information.h"
#include "base/win/startup_information.h"
#include "base/win/windows_version.h"
#pragma comment(lib, "userenv.lib")
namespace base {
namespace {
const DWORD kProcessKilledExitCode = 1;
}
void RouteStdioToConsole() {
if (_fileno(stdout) >= 0 || _fileno(stderr) >= 0)
return;
if (!AttachConsole(ATTACH_PARENT_PROCESS)) {
unsigned int result = GetLastError();
if (result == ERROR_ACCESS_DENIED)
return;
if (result == ERROR_GEN_FAILURE)
return;
AllocConsole();
}
enum { kOutputBufferSize = 64 * 1024 };
if (freopen("CONOUT$", "w", stdout)) {
setvbuf(stdout, NULL, _IOLBF, kOutputBufferSize);
_dup2(_fileno(stdout), 1);
}
if (freopen("CONOUT$", "w", stderr)) {
setvbuf(stderr, NULL, _IOLBF, kOutputBufferSize);
_dup2(_fileno(stderr), 2);
}
std::ios::sync_with_stdio();
}
bool LaunchProcess(const string16& cmdline,
const LaunchOptions& options,
win::ScopedHandle* process_handle) {
win::StartupInformation startup_info_wrapper;
STARTUPINFO* startup_info = startup_info_wrapper.startup_info();
bool inherit_handles = options.inherit_handles;
DWORD flags = 0;
if (options.handles_to_inherit) {
if (options.handles_to_inherit->empty()) {
inherit_handles = false;
} else {
if (base::win::GetVersion() < base::win::VERSION_VISTA) {
DLOG(ERROR) << "Specifying handles to inherit requires Vista or later.";
return false;
}
if (options.handles_to_inherit->size() >
std::numeric_limits<DWORD>::max() / sizeof(HANDLE)) {
DLOG(ERROR) << "Too many handles to inherit.";
return false;
}
if (!startup_info_wrapper.InitializeProcThreadAttributeList(1)) {
DPLOG(ERROR);
return false;
}
if (!startup_info_wrapper.UpdateProcThreadAttribute(
PROC_THREAD_ATTRIBUTE_HANDLE_LIST,
const_cast<HANDLE*>(&options.handles_to_inherit->at(0)),
static_cast<DWORD>(options.handles_to_inherit->size() *
sizeof(HANDLE)))) {
DPLOG(ERROR);
return false;
}
inherit_handles = true;
flags |= EXTENDED_STARTUPINFO_PRESENT;
}
}
if (options.empty_desktop_name)
startup_info->lpDesktop = L"";
startup_info->dwFlags = STARTF_USESHOWWINDOW;
startup_info->wShowWindow = options.start_hidden ? SW_HIDE : SW_SHOW;
if (options.stdin_handle || options.stdout_handle || options.stderr_handle) {
DCHECK(inherit_handles);
DCHECK(options.stdin_handle);
DCHECK(options.stdout_handle);
DCHECK(options.stderr_handle);
startup_info->dwFlags |= STARTF_USESTDHANDLES;
startup_info->hStdInput = options.stdin_handle;
startup_info->hStdOutput = options.stdout_handle;
startup_info->hStdError = options.stderr_handle;
}
if (options.job_handle) {
flags |= CREATE_SUSPENDED;
flags |= CREATE_BREAKAWAY_FROM_JOB;
}
if (options.force_breakaway_from_job_)
flags |= CREATE_BREAKAWAY_FROM_JOB;
PROCESS_INFORMATION temp_process_info = {};
if (options.as_user) {
flags |= CREATE_UNICODE_ENVIRONMENT;
void* enviroment_block = NULL;
if (!CreateEnvironmentBlock(&enviroment_block, options.as_user, FALSE)) {
DPLOG(ERROR);
return false;
}
BOOL launched =
CreateProcessAsUser(options.as_user, NULL,
const_cast<wchar_t*>(cmdline.c_str()),
NULL, NULL, inherit_handles, flags,
enviroment_block, NULL, startup_info,
&temp_process_info);
DestroyEnvironmentBlock(enviroment_block);
if (!launched) {
DPLOG(ERROR);
return false;
}
} else {
if (!CreateProcess(NULL,
const_cast<wchar_t*>(cmdline.c_str()), NULL, NULL,
inherit_handles, flags, NULL, NULL,
startup_info, &temp_process_info)) {
DPLOG(ERROR);
return false;
}
}
base::win::ScopedProcessInformation process_info(temp_process_info);
if (options.job_handle) {
if (0 == AssignProcessToJobObject(options.job_handle,
process_info.process_handle())) {
DLOG(ERROR) << "Could not AssignProcessToObject.";
KillProcess(process_info.process_handle(), kProcessKilledExitCode, true);
return false;
}
ResumeThread(process_info.thread_handle());
}
if (options.wait)
WaitForSingleObject(process_info.process_handle(), INFINITE);
if (process_handle)
process_handle->Set(process_info.TakeProcessHandle());
return true;
}
bool LaunchProcess(const CommandLine& cmdline,
const LaunchOptions& options,
ProcessHandle* process_handle) {
if (!process_handle)
return LaunchProcess(cmdline.GetCommandLineString(), options, NULL);
win::ScopedHandle process;
bool rv = LaunchProcess(cmdline.GetCommandLineString(), options, &process);
*process_handle = process.Take();
return rv;
}
bool LaunchElevatedProcess(const CommandLine& cmdline,
const LaunchOptions& options,
ProcessHandle* process_handle) {
const string16 file = cmdline.GetProgram().value();
const string16 arguments = cmdline.GetArgumentsString();
SHELLEXECUTEINFO shex_info = {0};
shex_info.cbSize = sizeof(shex_info);
shex_info.fMask = SEE_MASK_NOCLOSEPROCESS;
shex_info.hwnd = GetActiveWindow();
shex_info.lpVerb = L"runas";
shex_info.lpFile = file.c_str();
shex_info.lpParameters = arguments.c_str();
shex_info.lpDirectory = NULL;
shex_info.nShow = options.start_hidden ? SW_HIDE : SW_SHOW;
shex_info.hInstApp = NULL;
if (!ShellExecuteEx(&shex_info)) {
DPLOG(ERROR);
return false;
}
if (options.wait)
WaitForSingleObject(shex_info.hProcess, INFINITE);
if (process_handle)
*process_handle = shex_info.hProcess;
else
CloseHandle(shex_info.hProcess);
return true;
}
bool SetJobObjectLimitFlags(HANDLE job_object, DWORD limit_flags) {
JOBOBJECT_EXTENDED_LIMIT_INFORMATION limit_info = {0};
limit_info.BasicLimitInformation.LimitFlags = limit_flags;
return 0 != SetInformationJobObject(
job_object,
JobObjectExtendedLimitInformation,
&limit_info,
sizeof(limit_info));
}
bool GetAppOutput(const CommandLine& cl, std::string* output) {
return GetAppOutput(cl.GetCommandLineString(), output);
}
bool GetAppOutput(const StringPiece16& cl, std::string* output) {
HANDLE out_read = NULL;
HANDLE out_write = NULL;
SECURITY_ATTRIBUTES sa_attr;
sa_attr.nLength = sizeof(SECURITY_ATTRIBUTES);
sa_attr.bInheritHandle = TRUE;
sa_attr.lpSecurityDescriptor = NULL;
if (!CreatePipe(&out_read, &out_write, &sa_attr, 0)) {
NOTREACHED() << "Failed to create pipe";
return false;
}
win::ScopedHandle scoped_out_read(out_read);
win::ScopedHandle scoped_out_write(out_write);
if (!SetHandleInformation(out_read, HANDLE_FLAG_INHERIT, 0)) {
NOTREACHED() << "Failed to disabled pipe inheritance";
return false;
}
FilePath::StringType writable_command_line_string;
writable_command_line_string.assign(cl.data(), cl.size());
STARTUPINFO start_info = {};
start_info.cb = sizeof(STARTUPINFO);
start_info.hStdOutput = out_write;
start_info.hStdInput = GetStdHandle(STD_INPUT_HANDLE);
start_info.hStdError = GetStdHandle(STD_ERROR_HANDLE);
start_info.dwFlags |= STARTF_USESTDHANDLES;
PROCESS_INFORMATION temp_process_info = {};
if (!CreateProcess(NULL,
&writable_command_line_string[0],
NULL, NULL,
TRUE,
0, NULL, NULL, &start_info, &temp_process_info)) {
NOTREACHED() << "Failed to start process";
return false;
}
base::win::ScopedProcessInformation proc_info(temp_process_info);
scoped_out_write.Close();
const int kBufferSize = 1024;
char buffer[kBufferSize];
for (;;) {
DWORD bytes_read = 0;
BOOL success = ReadFile(out_read, buffer, kBufferSize, &bytes_read, NULL);
if (!success || bytes_read == 0)
break;
output->append(buffer, bytes_read);
}
WaitForSingleObject(proc_info.process_handle(), INFINITE);
return true;
}
void RaiseProcessToHighPriority() {
SetPriorityClass(GetCurrentProcess(), HIGH_PRIORITY_CLASS);
}
}