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