| 1 |
////////////////////////////////////////////////////////////////////////////// |
| 2 |
////////////////////////////////////////////////////////////////////////////// |
| 3 |
// |
| 4 |
// copyright : (C) 2008 by Eran Ifrah |
| 5 |
// file name : winprocess.cpp |
| 6 |
// |
| 7 |
// ------------------------------------------------------------------------- |
| 8 |
// A |
| 9 |
// _____ _ _ _ _ |
| 10 |
// / __ \ | | | | (_) | |
| 11 |
// | / \/ ___ __| | ___| | _| |_ ___ |
| 12 |
// | | / _ \ / _ |/ _ \ | | | __/ _ ) |
| 13 |
// | \__/\ (_) | (_| | __/ |___| | || __/ |
| 14 |
// \____/\___/ \__,_|\___\_____/_|\__\___| |
| 15 |
// |
| 16 |
// F i l e |
| 17 |
// |
| 18 |
// This program is free software; you can redistribute it and/or modify |
| 19 |
// it under the terms of the GNU General Public License as published by |
| 20 |
// the Free Software Foundation; either version 2 of the License, or |
| 21 |
// (at your option) any later version. |
| 22 |
// |
| 23 |
////////////////////////////////////////////////////////////////////////////// |
| 24 |
////////////////////////////////////////////////////////////////////////////// |
| 25 |
|
| 26 |
#ifdef __WXMSW__ |
| 27 |
#include "winprocess_impl.h" |
| 28 |
|
| 29 |
#include "file_logger.h" |
| 30 |
#include "fileutils.h" |
| 31 |
#include "processreaderthread.h" |
| 32 |
#include "procutils.h" |
| 33 |
#include "smart_ptr.h" |
| 34 |
|
| 35 |
#include <atomic> |
| 36 |
#include <memory> |
| 37 |
#include <wx/filefn.h> |
| 38 |
#include <wx/msgqueue.h> |
| 39 |
#include <wx/string.h> |
| 40 |
|
| 41 |
#ifdef _WIN32_WINNT |
| 42 |
#undef _WIN32_WINNT |
| 43 |
#endif |
| 44 |
|
| 45 |
#define _WIN32_WINNT 0x0501 // Make AttachConsole(DWORD) visible |
| 46 |
|
| 47 |
class MyDirGuard |
| 48 |
{ |
| 49 |
wxString _d; |
| 50 |
|
| 51 |
public: |
| 52 |
MyDirGuard() |
| 53 |
: _d(wxGetCwd()) |
| 54 |
{ |
| 55 |
} |
| 56 |
~MyDirGuard() { wxSetWorkingDirectory(_d); } |
| 57 |
}; |
| 58 |
|
| 59 |
/** |
| 60 |
* @class ConsoleAttacher |
| 61 |
* @date 11/03/10 |
| 62 |
* @brief a helper class to attach this process to a process' console |
| 63 |
* this allows us to write directly into that process console-input-buffer |
| 64 |
* One should check isAttached once this object is constructed |
| 65 |
*/ |
| 66 |
class ConsoleAttacher |
| 67 |
{ |
| 68 |
public: |
| 69 |
bool isAttached; |
| 70 |
|
| 71 |
public: |
| 72 |
ConsoleAttacher(long pid) { isAttached = AttachConsole(pid); } |
| 73 |
|
| 74 |
~ConsoleAttacher() |
| 75 |
{ |
| 76 |
if(isAttached) { |
| 77 |
FreeConsole(); |
| 78 |
} |
| 79 |
isAttached = false; |
| 80 |
} |
| 81 |
}; |
| 82 |
|
| 83 |
static bool CheckIsAlive(HANDLE hProcess) |
| 84 |
{ |
| 85 |
DWORD dwExitCode; |
| 86 |
if(GetExitCodeProcess(hProcess, &dwExitCode)) { |
| 87 |
if(dwExitCode == STILL_ACTIVE) |
| 88 |
return true; |
| 89 |
} |
| 90 |
return false; |
| 91 |
} |
| 92 |
|
| 93 |
template <typename T> bool WriteStdin(const T& buffer, HANDLE hStdin, HANDLE hProcess) |
| 94 |
{ |
| 95 |
DWORD dwMode; |
| 96 |
|
| 97 |
// Make the pipe to non-blocking mode |
| 98 |
dwMode = PIPE_READMODE_BYTE | PIPE_WAIT; |
| 99 |
SetNamedPipeHandleState(hStdin, &dwMode, NULL, NULL); |
| 100 |
DWORD bytesLeft = buffer.length(); |
| 101 |
long offset = 0; |
| 102 |
static constexpr int max_retry_count = 100; |
| 103 |
size_t retryCount = 0; |
| 104 |
while(bytesLeft > 0 && (retryCount < max_retry_count)) { |
| 105 |
DWORD dwWritten = 0; |
| 106 |
if(!WriteFile(hStdin, buffer.c_str() + offset, bytesLeft, &dwWritten, NULL)) { |
| 107 |
int errorCode = GetLastError(); |
| 108 |
LOG_IF_DEBUG { clDEBUG() << ">> WriteStdin: (WriteFile) error:" << errorCode << endl; } |
| 109 |
return false; |
| 110 |
} |
| 111 |
if(!CheckIsAlive(hProcess)) { |
| 112 |
LOG_IF_DEBUG { clDEBUG() << "WriteStdin failed. Process is not alive" << endl; } |
| 113 |
return false; |
| 114 |
} |
| 115 |
if(dwWritten == 0) { |
| 116 |
std::this_thread::sleep_for(std::chrono::milliseconds(1)); |
| 117 |
} |
| 118 |
bytesLeft -= dwWritten; |
| 119 |
offset += dwWritten; |
| 120 |
++retryCount; |
| 121 |
} |
| 122 |
|
| 123 |
if(retryCount >= max_retry_count) { |
| 124 |
clERROR() << "Failed to write to process after" << max_retry_count << "retries. Written" |
| 125 |
<< (buffer.length() - bytesLeft) << "/" << buffer.length() << "bytes" << endl; |
| 126 |
return false; |
| 127 |
} |
| 128 |
return true; |
| 129 |
} |
| 130 |
|
| 131 |
class WXDLLIMPEXP_CL WinWriterThread |
| 132 |
{ |
| 133 |
std::thread* m_thread = nullptr; |
| 134 |
wxMessageQueue<std::string> m_outgoingQueue; |
| 135 |
std::atomic_bool m_shutdown; |
| 136 |
HANDLE m_hProcess = INVALID_HANDLE_VALUE; |
| 137 |
HANDLE m_hStdin = INVALID_HANDLE_VALUE; |
| 138 |
|
| 139 |
public: |
| 140 |
WinWriterThread(HANDLE hProcess, HANDLE hStdin) |
| 141 |
: m_hProcess(hProcess) |
| 142 |
, m_hStdin(hStdin) |
| 143 |
{ |
| 144 |
m_shutdown.store(false); |
| 145 |
} |
| 146 |
|
| 147 |
~WinWriterThread() {} |
| 148 |
|
| 149 |
void Start() { m_thread = new std::thread(&WinWriterThread::Entry, this, m_hStdin); } |
| 150 |
void Stop() |
| 151 |
{ |
| 152 |
if(m_thread) { |
| 153 |
m_shutdown.store(true); |
| 154 |
m_thread->join(); |
| 155 |
wxDELETE(m_thread); |
| 156 |
} |
| 157 |
} |
| 158 |
static void Entry(WinWriterThread* thr, HANDLE hStdin) |
| 159 |
{ |
| 160 |
auto& Q = thr->m_outgoingQueue; |
| 161 |
while(!thr->m_shutdown.load()) { |
| 162 |
std::string cstr; |
| 163 |
if(Q.ReceiveTimeout(50, cstr) == wxMSGQUEUE_NO_ERROR) { |
| 164 |
if(WriteStdin(cstr, hStdin, thr->m_hProcess)) { |
| 165 |
LOG_IF_TRACE { clDEBUG1() << "Writer thread: wrote buffer of" << cstr.length() << "bytes"; } |
| 166 |
} |
| 167 |
} |
| 168 |
} |
| 169 |
LOG_IF_TRACE { clDEBUG1() << "Write thread going down"; } |
| 170 |
} |
| 171 |
|
| 172 |
void Write(const std::string& buffer) { m_outgoingQueue.Post(buffer); } |
| 173 |
}; |
| 174 |
|
| 175 |
static wxString __JoinArray(const wxArrayString& args, size_t flags) |
| 176 |
{ |
| 177 |
wxString command; |
| 178 |
if(flags & IProcessWrapInShell) { |
| 179 |
// CMD /C [command] ... |
| 180 |
// Make sure that the first command is wrapped with "" if it contains spaces |
| 181 |
LOG_IF_TRACE |
| 182 |
{ |
| 183 |
clDEBUG1() << "==> __JoinArray called for" << args << endl; |
| 184 |
clDEBUG1() << "args[2] is:" << args[2] << endl; |
| 185 |
} |
| 186 |
|
| 187 |
if((args.size() > 3) && (!args[2].StartsWith("\"")) && (args[2].Contains(" "))) { |
| 188 |
LOG_IF_DEBUG { clDEBUG() << "==> Fixing" << args << endl; } |
| 189 |
wxArrayString tmparr = args; |
| 190 |
wxString& firstCommand = tmparr[2]; |
| 191 |
firstCommand.Prepend("\"").Append("\""); |
| 192 |
command = wxJoin(tmparr, ' ', 0); |
| 193 |
} else { |
| 194 |
command = wxJoin(args, ' ', 0); |
| 195 |
} |
| 196 |
} else if(flags & IProcessCreateSSH) { |
| 197 |
// simple join |
| 198 |
command = wxJoin(args, ' ', 0); |
| 199 |
} else { |
| 200 |
wxArrayString arr; |
| 201 |
arr.reserve(args.size()); |
| 202 |
arr = args; |
| 203 |
for(auto& arg : arr) { |
| 204 |
if(arg.Contains(" ")) { |
| 205 |
// escape any " before we start escaping |
| 206 |
arg.Replace("\"", "\\\""); |
| 207 |
// now wrap with double quotes |
| 208 |
arg.Prepend("\"").Append("\""); |
| 209 |
} |
| 210 |
command << arg << " "; |
| 211 |
} |
| 212 |
} |
| 213 |
command.Trim().Trim(false); |
| 214 |
return command; |
| 215 |
} |
| 216 |
|
| 217 |
IProcess* WinProcessImpl::Execute(wxEvtHandler* parent, const wxArrayString& args, size_t flags, |
| 218 |
const wxString& workingDirectory, IProcessCallback* cb) |
| 219 |
{ |
| 220 |
wxString cmd = __JoinArray(args, flags); |
| 221 |
LOG_IF_TRACE { clDEBUG1() << "Windows process starting:" << cmd << endl; } |
| 222 |
return Execute(parent, cmd, flags, workingDirectory, cb); |
| 223 |
} |
| 224 |
|
| 225 |
/*static*/ |
| 226 |
IProcess* WinProcessImpl::Execute(wxEvtHandler* parent, const wxString& cmd, size_t flags, const wxString& workingDir, |
| 227 |
IProcessCallback* cb) |
| 228 |
{ |
| 229 |
SECURITY_ATTRIBUTES saAttr; |
| 230 |
BOOL fSuccess; |
| 231 |
|
| 232 |
MyDirGuard dg; |
| 233 |
|
| 234 |
wxString wd(workingDir); |
| 235 |
if(workingDir.IsEmpty()) { |
| 236 |
wd = wxGetCwd(); |
| 237 |
} |
| 238 |
wxSetWorkingDirectory(wd); |
| 239 |
|
| 240 |
// Set the bInheritHandle flag so pipe handles are inherited. |
| 241 |
saAttr.nLength = sizeof(SECURITY_ATTRIBUTES); |
| 242 |
saAttr.bInheritHandle = TRUE; |
| 243 |
saAttr.lpSecurityDescriptor = NULL; |
| 244 |
WinProcessImpl* prc = new WinProcessImpl(parent); |
| 245 |
prc->m_callback = cb; |
| 246 |
prc->m_flags = flags; |
| 247 |
|
| 248 |
bool redirectOutput = !(flags & IProcessNoRedirect); |
| 249 |
|
| 250 |
// The steps for redirecting child process's STDOUT: |
| 251 |
// 1. Save current STDOUT, to be restored later. |
| 252 |
// 2. Create anonymous pipe to be STDOUT for child process. |
| 253 |
// 3. Set STDOUT of the parent process to be write handle to |
| 254 |
// the pipe, so it is inherited by the child process. |
| 255 |
// 4. Create a noninheritable duplicate of the read handle and |
| 256 |
// close the inheritable read handle. |
| 257 |
|
| 258 |
if(redirectOutput) { |
| 259 |
// Save the handle to the current STDOUT. |
| 260 |
prc->hSaveStdout = GetStdHandle(STD_OUTPUT_HANDLE); |
| 261 |
|
| 262 |
// Create a pipe for the child process's STDOUT. |
| 263 |
if(!CreatePipe(&prc->hChildStdoutRd, &prc->hChildStdoutWr, &saAttr, 0)) { |
| 264 |
delete prc; |
| 265 |
return NULL; |
| 266 |
} |
| 267 |
|
| 268 |
// Set a write handle to the pipe to be STDOUT. |
| 269 |
if(!SetStdHandle(STD_OUTPUT_HANDLE, prc->hChildStdoutWr)) { |
| 270 |
delete prc; |
| 271 |
return NULL; |
| 272 |
} |
| 273 |
|
| 274 |
// Create noninheritable read handle and close the inheritable read handle. |
| 275 |
fSuccess = DuplicateHandle(GetCurrentProcess(), prc->hChildStdoutRd, GetCurrentProcess(), |
| 276 |
&prc->hChildStdoutRdDup, 0, FALSE, DUPLICATE_SAME_ACCESS); |
| 277 |
if(!fSuccess) { |
| 278 |
delete prc; |
| 279 |
return NULL; |
| 280 |
} |
| 281 |
CloseHandle(prc->hChildStdoutRd); |
| 282 |
|
| 283 |
// The steps for redirecting child process's STDERR: |
| 284 |
// 1. Save current STDERR, to be restored later. |
| 285 |
// 2. Create anonymous pipe to be STDERR for child process. |
| 286 |
// 3. Set STDERR of the parent process to be write handle to |
| 287 |
// the pipe, so it is inherited by the child process. |
| 288 |
// 4. Create a noninheritable duplicate of the read handle and |
| 289 |
// close the inheritable read handle. |
| 290 |
|
| 291 |
// Save the handle to the current STDERR. |
| 292 |
prc->hSaveStderr = GetStdHandle(STD_ERROR_HANDLE); |
| 293 |
|
| 294 |
// Create a pipe for the child process's STDERR. |
| 295 |
if(!CreatePipe(&prc->hChildStderrRd, &prc->hChildStderrWr, &saAttr, 0)) { |
| 296 |
delete prc; |
| 297 |
return NULL; |
| 298 |
} |
| 299 |
|
| 300 |
// Set a write handle to the pipe to be STDERR. |
| 301 |
if(!SetStdHandle(STD_ERROR_HANDLE, prc->hChildStderrWr)) { |
| 302 |
delete prc; |
| 303 |
return NULL; |
| 304 |
} |
| 305 |
|
| 306 |
// Create noninheritable read handle and close the inheritable read handle. |
| 307 |
fSuccess = DuplicateHandle(GetCurrentProcess(), prc->hChildStderrRd, GetCurrentProcess(), |
| 308 |
&prc->hChildStderrRdDup, 0, FALSE, DUPLICATE_SAME_ACCESS); |
| 309 |
if(!fSuccess) { |
| 310 |
delete prc; |
| 311 |
return NULL; |
| 312 |
} |
| 313 |
CloseHandle(prc->hChildStderrRd); |
| 314 |
|
| 315 |
// The steps for redirecting child process's STDIN: |
| 316 |
// 1. Save current STDIN, to be restored later. |
| 317 |
// 2. Create anonymous pipe to be STDIN for child process. |
| 318 |
// 3. Set STDIN of the parent to be the read handle to the |
| 319 |
// pipe, so it is inherited by the child process. |
| 320 |
// 4. Create a noninheritable duplicate of the write handle, |
| 321 |
// and close the inheritable write handle. |
| 322 |
|
| 323 |
// Save the handle to the current STDIN. |
| 324 |
prc->hSaveStdin = GetStdHandle(STD_INPUT_HANDLE); |
| 325 |
|
| 326 |
// Create a pipe for the child process's STDIN. |
| 327 |
if(!CreatePipe(&prc->hChildStdinRd, &prc->hChildStdinWr, &saAttr, 0)) { |
| 328 |
delete prc; |
| 329 |
return NULL; |
| 330 |
} |
| 331 |
// Set a read handle to the pipe to be STDIN. |
| 332 |
if(!SetStdHandle(STD_INPUT_HANDLE, prc->hChildStdinRd)) { |
| 333 |
delete prc; |
| 334 |
return NULL; |
| 335 |
} |
| 336 |
// Duplicate the write handle to the pipe so it is not inherited. |
| 337 |
fSuccess = |
| 338 |
DuplicateHandle(GetCurrentProcess(), prc->hChildStdinWr, GetCurrentProcess(), &prc->hChildStdinWrDup, 0, |
| 339 |
FALSE, // not inherited |
| 340 |
DUPLICATE_SAME_ACCESS); |
| 341 |
if(!fSuccess) { |
| 342 |
delete prc; |
| 343 |
return NULL; |
| 344 |
} |
| 345 |
CloseHandle(prc->hChildStdinWr); |
| 346 |
} |
| 347 |
|
| 348 |
// Execute the child process |
| 349 |
STARTUPINFO siStartInfo; |
| 350 |
|
| 351 |
// Set up members of STARTUPINFO structure. |
| 352 |
ZeroMemory(&siStartInfo, sizeof(STARTUPINFO)); |
| 353 |
siStartInfo.cb = sizeof(STARTUPINFO); |
| 354 |
|
| 355 |
siStartInfo.dwFlags = STARTF_USESHOWWINDOW; |
| 356 |
if(redirectOutput) { |
| 357 |
siStartInfo.dwFlags |= STARTF_USESTDHANDLES; |
| 358 |
siStartInfo.hStdInput = prc->hChildStdinRd; |
| 359 |
siStartInfo.hStdOutput = prc->hChildStdoutWr; |
| 360 |
siStartInfo.hStdError = prc->hChildStderrWr; |
| 361 |
} |
| 362 |
|
| 363 |
// Set the window to hide |
| 364 |
siStartInfo.wShowWindow = flags & IProcessCreateConsole ? SW_SHOW : SW_HIDE; |
| 365 |
DWORD creationFlags = flags & IProcessCreateConsole ? CREATE_NEW_CONSOLE : CREATE_NO_WINDOW; |
| 366 |
|
| 367 |
if(flags & IProcessCreateWithHiddenConsole) { |
| 368 |
siStartInfo.wShowWindow = SW_HIDE; |
| 369 |
creationFlags = CREATE_NEW_CONSOLE | CREATE_NEW_PROCESS_GROUP; |
| 370 |
} |
| 371 |
LOG_IF_TRACE { clDEBUG1() << "Running process:" << cmd << endl; } |
| 372 |
BOOL ret = CreateProcess(NULL, |
| 373 |
cmd.wchar_str(), // shell line execution command |
| 374 |
NULL, // process security attributes |
| 375 |
NULL, // primary thread security attributes |
| 376 |
TRUE, // handles are inherited |
| 377 |
creationFlags, // creation flags |
| 378 |
NULL, // use parent's environment |
| 379 |
NULL, // CD to tmp dir |
| 380 |
&siStartInfo, // STARTUPINFO pointer |
| 381 |
&prc->piProcInfo); // receives PROCESS_INFORMATION |
| 382 |
if(ret) { |
| 383 |
prc->dwProcessId = prc->piProcInfo.dwProcessId; |
| 384 |
} else { |
| 385 |
int err = GetLastError(); |
| 386 |
wxUnusedVar(err); |
| 387 |
delete prc; |
| 388 |
return NULL; |
| 389 |
} |
| 390 |
|
| 391 |
if(redirectOutput) { |
| 392 |
// After process creation, restore the saved STDIN and STDOUT. |
| 393 |
if(!SetStdHandle(STD_INPUT_HANDLE, prc->hSaveStdin)) { |
| 394 |
delete prc; |
| 395 |
return NULL; |
| 396 |
} |
| 397 |
if(!SetStdHandle(STD_OUTPUT_HANDLE, prc->hSaveStdout)) { |
| 398 |
delete prc; |
| 399 |
return NULL; |
| 400 |
} |
| 401 |
if(!SetStdHandle(STD_OUTPUT_HANDLE, prc->hSaveStderr)) { |
| 402 |
delete prc; |
| 403 |
return NULL; |
| 404 |
} |
| 405 |
} |
| 406 |
|
| 407 |
if((prc->m_flags & IProcessCreateConsole) || (prc->m_flags & IProcessCreateWithHiddenConsole)) { |
| 408 |
ConsoleAttacher ca(prc->GetPid()); |
| 409 |
if(ca.isAttached) { |
| 410 |
freopen("CONOUT$", "wb", stdout); // reopen stout handle as console window output |
| 411 |
freopen("CONOUT$", "wb", stderr); // reopen stderr handle as console window output |
| 412 |
} |
| 413 |
} |
| 414 |
prc->SetPid(prc->dwProcessId); |
| 415 |
if(!(prc->m_flags & IProcessCreateSync)) { |
| 416 |
prc->StartReaderThread(); |
| 417 |
} |
| 418 |
prc->m_writerThread = new WinWriterThread(prc->piProcInfo.hProcess, prc->hChildStdinWrDup); |
| 419 |
prc->m_writerThread->Start(); |
| 420 |
return prc; |
| 421 |
} |
| 422 |
|
| 423 |
WinProcessImpl::WinProcessImpl(wxEvtHandler* parent) |
| 424 |
: IProcess(parent) |
| 425 |
{ |
| 426 |
hChildStdinRd = NULL; |
| 427 |
hChildStdinWrDup = NULL; |
| 428 |
hChildStdoutWr = NULL; |
| 429 |
hChildStdoutRdDup = NULL; |
| 430 |
hChildStderrWr = NULL; |
| 431 |
hChildStderrRdDup = NULL; |
| 432 |
piProcInfo.hProcess = NULL; |
| 433 |
piProcInfo.hThread = NULL; |
| 434 |
} |
| 435 |
|
| 436 |
WinProcessImpl::~WinProcessImpl() { Cleanup(); } |
| 437 |
|
| 438 |
bool WinProcessImpl::Read(wxString& buff, wxString& buffErr) |
| 439 |
{ |
| 440 |
DWORD le1(-1); |
| 441 |
DWORD le2(-1); |
| 442 |
buff.Clear(); |
| 443 |
buffErr.Clear(); |
| 444 |
|
| 445 |
// Sanity |
| 446 |
if(!IsRedirect()) { |
| 447 |
return false; |
| 448 |
} |
| 449 |
|
| 450 |
// Read data from STDOUT and STDERR |
| 451 |
if(!DoReadFromPipe(hChildStderrRdDup, ((m_flags & IProcessStderrEvent) ? buffErr : buff))) { |
| 452 |
le2 = GetLastError(); |
| 453 |
} |
| 454 |
|
| 455 |
if(!DoReadFromPipe(hChildStdoutRdDup, buff)) { |
| 456 |
le1 = GetLastError(); |
| 457 |
} |
| 458 |
if((le1 == ERROR_NO_DATA) && (le2 == ERROR_NO_DATA)) { |
| 459 |
if(IsAlive()) { |
| 460 |
wxThread::Sleep(1); |
| 461 |
return true; |
| 462 |
} |
| 463 |
} |
| 464 |
bool success = !buff.IsEmpty() || !buffErr.IsEmpty(); |
| 465 |
if(!success) { |
| 466 |
DWORD dwExitCode; |
| 467 |
if(GetExitCodeProcess(piProcInfo.hProcess, &dwExitCode)) { |
| 468 |
SetProcessExitCode(GetPid(), (int)dwExitCode); |
| 469 |
} |
| 470 |
} |
| 471 |
return success; |
| 472 |
} |
| 473 |
|
| 474 |
bool WinProcessImpl::Write(const wxString& buff) |
| 475 |
{ |
| 476 |
// Sanity |
| 477 |
return Write(FileUtils::ToStdString(buff)); |
| 478 |
} |
| 479 |
|
| 480 |
bool WinProcessImpl::Write(const std::string& buff) { return WriteRaw(buff + "\r\n"); } |
| 481 |
|
| 482 |
bool WinProcessImpl::WriteRaw(const wxString& buff) { return WriteRaw(FileUtils::ToStdString(buff)); } |
| 483 |
|
| 484 |
bool WinProcessImpl::WriteRaw(const std::string& buff) |
| 485 |
{ |
| 486 |
// Sanity |
| 487 |
if(!IsRedirect()) { |
| 488 |
return false; |
| 489 |
} |
| 490 |
m_writerThread->Write(buff); |
| 491 |
return true; |
| 492 |
} |
| 493 |
|
| 494 |
bool WinProcessImpl::IsAlive() |
| 495 |
{ |
| 496 |
DWORD dwExitCode; |
| 497 |
if(GetExitCodeProcess(piProcInfo.hProcess, &dwExitCode)) { |
| 498 |
if(dwExitCode == STILL_ACTIVE) |
| 499 |
return true; |
| 500 |
} |
| 501 |
return false; |
| 502 |
} |
| 503 |
|
| 504 |
void WinProcessImpl::Cleanup() |
| 505 |
{ |
| 506 |
if(m_writerThread) { |
| 507 |
m_writerThread->Stop(); |
| 508 |
wxDELETE(m_writerThread); |
| 509 |
} |
| 510 |
|
| 511 |
// Under windows, the reader thread is detached |
| 512 |
if(m_thr) { |
| 513 |
// Stop the reader thread |
| 514 |
m_thr->Stop(); |
| 515 |
delete m_thr; |
| 516 |
} |
| 517 |
m_thr = NULL; |
| 518 |
|
| 519 |
// terminate the process |
| 520 |
if(IsAlive()) { |
| 521 |
std::map<unsigned long, bool> tree; |
| 522 |
ProcUtils::GetProcTree(tree, GetPid()); |
| 523 |
|
| 524 |
for(const auto& vt : tree) { |
| 525 |
// don't kill ourself |
| 526 |
if((long)vt.first == GetPid()) { |
| 527 |
continue; |
| 528 |
} |
| 529 |
wxLogNull NoLog; |
| 530 |
wxKillError rc; |
| 531 |
wxKill(vt.first, wxSIGKILL, &rc); |
| 532 |
} |
| 533 |
::TerminateProcess(piProcInfo.hProcess, 0); |
| 534 |
} |
| 535 |
|
| 536 |
if(IsRedirect()) { |
| 537 |
CloseHandle(hChildStdinRd); |
| 538 |
CloseHandle(hChildStdinWrDup); |
| 539 |
CloseHandle(hChildStdoutWr); |
| 540 |
CloseHandle(hChildStdoutRdDup); |
| 541 |
CloseHandle(hChildStderrWr); |
| 542 |
CloseHandle(hChildStderrRdDup); |
| 543 |
} |
| 544 |
|
| 545 |
CloseHandle(piProcInfo.hProcess); |
| 546 |
CloseHandle(piProcInfo.hThread); |
| 547 |
|
| 548 |
hChildStdinRd = NULL; |
| 549 |
hChildStdoutWr = NULL; |
| 550 |
hChildStdinWrDup = NULL; |
| 551 |
hChildStdoutRdDup = NULL; |
| 552 |
hChildStderrWr = NULL; |
| 553 |
hChildStderrRdDup = NULL; |
| 554 |
piProcInfo.hProcess = NULL; |
| 555 |
piProcInfo.hThread = NULL; |
| 556 |
} |
| 557 |
|
| 558 |
void WinProcessImpl::StartReaderThread() |
| 559 |
{ |
| 560 |
// Launch the 'Reader' thread |
| 561 |
m_thr = new ProcessReaderThread(); |
| 562 |
m_thr->SetProcess(this); |
| 563 |
m_thr->SetNotifyWindow(m_parent); |
| 564 |
m_thr->Start(); |
| 565 |
} |
| 566 |
|
| 567 |
bool WinProcessImpl::DoReadFromPipe(HANDLE pipe, wxString& buff) |
| 568 |
{ |
| 569 |
DWORD dwRead = 0; |
| 570 |
DWORD dwMode; |
| 571 |
DWORD dwTimeout; |
| 572 |
|
| 573 |
// Make the pipe to non-blocking mode |
| 574 |
dwMode = PIPE_READMODE_BYTE | PIPE_NOWAIT; |
| 575 |
dwTimeout = 100; |
| 576 |
SetNamedPipeHandleState(pipe, &dwMode, NULL, &dwTimeout); |
| 577 |
|
| 578 |
bool read_something = false; |
| 579 |
while(true) { |
| 580 |
BOOL bRes = ReadFile(pipe, m_buffer, BUFFER_SIZE - 1, &dwRead, NULL); |
| 581 |
if(bRes && (dwRead > 0)) { |
| 582 |
wxString tmpBuff; |
| 583 |
tmpBuff.reserve(dwRead * 2); // make enough room for the conversion |
| 584 |
// Success read |
| 585 |
tmpBuff = wxString(m_buffer, wxConvUTF8, dwRead); |
| 586 |
if(tmpBuff.IsEmpty() && dwRead > 0) { |
| 587 |
// conversion failed |
| 588 |
tmpBuff = wxString::From8BitData(m_buffer, dwRead); |
| 589 |
} |
| 590 |
buff.reserve(buff.size() + tmpBuff.size() + 1); |
| 591 |
buff.Append(tmpBuff); |
| 592 |
read_something = true; |
| 593 |
continue; |
| 594 |
} |
| 595 |
break; |
| 596 |
} |
| 597 |
return read_something; |
| 598 |
} |
| 599 |
|
| 600 |
void WinProcessImpl::Terminate() |
| 601 |
{ |
| 602 |
// terminate the process |
| 603 |
if(IsAlive()) { |
| 604 |
std::map<unsigned long, bool> tree; |
| 605 |
ProcUtils::GetProcTree(tree, GetPid()); |
| 606 |
|
| 607 |
for(const auto& vt : tree) { |
| 608 |
if((long)vt.first == GetPid()) { |
| 609 |
continue; |
| 610 |
} |
| 611 |
wxLogNull NoLOG; |
| 612 |
wxKillError rc; |
| 613 |
wxKill(vt.first, wxSIGKILL, &rc); |
| 614 |
} |
| 615 |
TerminateProcess(piProcInfo.hProcess, 0); |
| 616 |
} |
| 617 |
} |
| 618 |
|
| 619 |
bool WinProcessImpl::WriteToConsole(const wxString& buff) |
| 620 |
{ |
| 621 |
wxString pass(buff); |
| 622 |
pass.Trim().Trim(false); |
| 623 |
|
| 624 |
// To write password, we need to attach to the child process console |
| 625 |
if(!(m_flags & (IProcessCreateWithHiddenConsole | IProcessCreateConsole))) |
| 626 |
return false; |
| 627 |
|
| 628 |
ConsoleAttacher ca(GetPid()); |
| 629 |
if(ca.isAttached == false) |
| 630 |
return false; |
| 631 |
|
| 632 |
HANDLE hStdIn = ::CreateFile(L"CONIN$", GENERIC_WRITE | GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, |
| 633 |
OPEN_EXISTING, 0, 0); |
| 634 |
if(hStdIn == INVALID_HANDLE_VALUE) { |
| 635 |
return false; |
| 636 |
} |
| 637 |
|
| 638 |
pass += wxT("\r\n"); |
| 639 |
SmartPtr<INPUT_RECORD> pKeyEvents(new INPUT_RECORD[pass.Len()]); |
| 640 |
|
| 641 |
for(size_t i = 0; i < pass.Len(); i++) { |
| 642 |
(pKeyEvents.Get())[i].EventType = KEY_EVENT; |
| 643 |
(pKeyEvents.Get())[i].Event.KeyEvent.bKeyDown = TRUE; |
| 644 |
(pKeyEvents.Get())[i].Event.KeyEvent.wRepeatCount = 1; |
| 645 |
(pKeyEvents.Get())[i].Event.KeyEvent.wVirtualKeyCode = LOBYTE(::VkKeyScan(pass[i])); |
| 646 |
(pKeyEvents.Get())[i].Event.KeyEvent.wVirtualScanCode = 0; |
| 647 |
(pKeyEvents.Get())[i].Event.KeyEvent.uChar.UnicodeChar = pass[i]; |
| 648 |
(pKeyEvents.Get())[i].Event.KeyEvent.dwControlKeyState = 0; |
| 649 |
} |
| 650 |
|
| 651 |
DWORD dwTextWritten; |
| 652 |
if(::WriteConsoleInput(hStdIn, pKeyEvents.Get(), pass.Len(), &dwTextWritten) == FALSE) { |
| 653 |
CloseHandle(hStdIn); |
| 654 |
return false; |
| 655 |
} |
| 656 |
CloseHandle(hStdIn); |
| 657 |
return true; |
| 658 |
} |
| 659 |
|
| 660 |
void WinProcessImpl::Detach() |
| 661 |
{ |
| 662 |
if(m_thr) { |
| 663 |
// Stop the reader thread |
| 664 |
m_thr->Stop(); |
| 665 |
delete m_thr; |
| 666 |
} |
| 667 |
m_thr = NULL; |
| 668 |
} |
| 669 |
|
| 670 |
void WinProcessImpl::Signal(wxSignal sig) { wxKill(GetPid(), sig, NULL, wxKILL_CHILDREN); } |
| 671 |
|
| 672 |
#endif //__WXMSW__ |