cmWin32ProcessExecution.cxx 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910
  1. /*=========================================================================
  2. Program: CMake - Cross-Platform Makefile Generator
  3. Module: $RCSfile$
  4. Language: C++
  5. Date: $Date$
  6. Version: $Revision$
  7. Copyright (c) 2002 Kitware, Inc., Insight Consortium. All rights reserved.
  8. See Copyright.txt or http://www.cmake.org/HTML/Copyright.html for details.
  9. This software is distributed WITHOUT ANY WARRANTY; without even
  10. the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
  11. PURPOSE. See the above copyright notices for more information.
  12. =========================================================================*/
  13. #include "cmWin32ProcessExecution.h"
  14. #include "cmSystemTools.h"
  15. #include <malloc.h>
  16. #include <io.h>
  17. #include <fcntl.h>
  18. #include <sys/stat.h>
  19. #include <windows.h>
  20. #if defined(__BORLANDC__)
  21. # define STRICMP stricmp
  22. # define TO_INTPTR(x) ((long)(x))
  23. #else // Visual studio
  24. # if ( _MSC_VER >= 1300 )
  25. # include <stddef.h>
  26. # define TO_INTPTR(x) ((intptr_t)(x))
  27. # else // Visual Studio 6
  28. # define TO_INTPTR(x) ((long)(x))
  29. # endif // Visual studio .NET
  30. # define STRICMP _stricmp
  31. #endif // Borland
  32. #define POPEN_1 1
  33. #define POPEN_2 2
  34. #define POPEN_3 3
  35. #define POPEN_4 4
  36. #define cmMAX(x,y) (((x)<(y))?(y):(x))
  37. void DisplayErrorMessage()
  38. {
  39. LPVOID lpMsgBuf;
  40. FormatMessage(
  41. FORMAT_MESSAGE_ALLOCATE_BUFFER |
  42. FORMAT_MESSAGE_FROM_SYSTEM |
  43. FORMAT_MESSAGE_IGNORE_INSERTS,
  44. NULL,
  45. GetLastError(),
  46. MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
  47. (LPTSTR) &lpMsgBuf,
  48. 0,
  49. NULL
  50. );
  51. // Process any inserts in lpMsgBuf.
  52. // ...
  53. // Display the string.
  54. MessageBox( NULL, (LPCTSTR)lpMsgBuf, "Error", MB_OK | MB_ICONINFORMATION );
  55. // Free the buffer.
  56. LocalFree( lpMsgBuf );
  57. }
  58. // Code from a Borland web site with the following explaination :
  59. /* In this article, I will explain how to spawn a console application
  60. * and redirect its standard input/output using anonymous pipes. An
  61. * anonymous pipe is a pipe that goes only in one direction (read
  62. * pipe, write pipe, etc.). Maybe you are asking, "why would I ever
  63. * need to do this sort of thing?" One example would be a Windows
  64. * telnet server, where you spawn a shell and listen on a port and
  65. * send and receive data between the shell and the socket
  66. * client. (Windows does not really have a built-in remote
  67. * shell). First, we should talk about pipes. A pipe in Windows is
  68. * simply a method of communication, often between process. The SDK
  69. * defines a pipe as "a communication conduit with two ends;
  70. a process
  71. * with a handle to one end can communicate with a process having a
  72. * handle to the other end." In our case, we are using "anonymous"
  73. * pipes, one-way pipes that "transfer data between a parent process
  74. * and a child process or between two child processes of the same
  75. * parent process." It's easiest to imagine a pipe as its namesake. An
  76. * actual pipe running between processes that can carry data. We are
  77. * using anonymous pipes because the console app we are spawning is a
  78. * child process. We use the CreatePipe function which will create an
  79. * anonymous pipe and return a read handle and a write handle. We will
  80. * create two pipes, on for stdin and one for stdout. We will then
  81. * monitor the read end of the stdout pipe to check for display on our
  82. * child process. Every time there is something availabe for reading,
  83. * we will display it in our app. Consequently, we check for input in
  84. * our app and send it off to the write end of the stdin pipe. */
  85. inline bool IsWinNT()
  86. //check if we're running NT
  87. {
  88. OSVERSIONINFO osv;
  89. osv.dwOSVersionInfoSize = sizeof(osv);
  90. GetVersionEx(&osv);
  91. return (osv.dwPlatformId == VER_PLATFORM_WIN32_NT);
  92. }
  93. //---------------------------------------------------------------------------
  94. bool cmWin32ProcessExecution::BorlandRunCommand(
  95. const char* command, const char* dir,
  96. std::string& output, int& retVal, bool verbose, int /* timeout */, bool hideWindows)
  97. {
  98. //verbose = true;
  99. //std::cerr << std::endl
  100. // << "WindowsRunCommand(" << command << ")" << std::endl
  101. // << std::flush;
  102. const int BUFFER_SIZE = 4096;
  103. char buf[BUFFER_SIZE];
  104. //i/o buffer
  105. STARTUPINFO si;
  106. SECURITY_ATTRIBUTES sa;
  107. SECURITY_DESCRIPTOR sd;
  108. //security information for pipes
  109. PROCESS_INFORMATION pi;
  110. HANDLE newstdin,newstdout,read_stdout,write_stdin;
  111. //pipe handles
  112. if (IsWinNT())
  113. //initialize security descriptor (Windows NT)
  114. {
  115. InitializeSecurityDescriptor(&sd,SECURITY_DESCRIPTOR_REVISION);
  116. SetSecurityDescriptorDacl(&sd, true, NULL, false);
  117. sa.lpSecurityDescriptor = &sd;
  118. }
  119. else sa.lpSecurityDescriptor = NULL;
  120. sa.nLength = sizeof(SECURITY_ATTRIBUTES);
  121. sa.bInheritHandle = true;
  122. //allow inheritable handles
  123. if (!CreatePipe(&newstdin,&write_stdin,&sa,0))
  124. //create stdin pipe
  125. {
  126. std::cerr << "CreatePipe" << std::endl;
  127. return false;
  128. }
  129. if (!CreatePipe(&read_stdout,&newstdout,&sa,0))
  130. //create stdout pipe
  131. {
  132. std::cerr << "CreatePipe" << std::endl;
  133. CloseHandle(newstdin);
  134. CloseHandle(write_stdin);
  135. return false;
  136. }
  137. GetStartupInfo(&si);
  138. //set startupinfo for the spawned process
  139. /* The dwFlags member tells CreateProcess how to make the
  140. * process. STARTF_USESTDHANDLES validates the hStd*
  141. * members. STARTF_USESHOWWINDOW validates the wShowWindow
  142. * member. */
  143. si.cb = sizeof(STARTUPINFO);
  144. si.dwFlags = STARTF_USESTDHANDLES|STARTF_USESHOWWINDOW;
  145. si.hStdOutput = newstdout;
  146. si.hStdError = newstdout;
  147. si.wShowWindow = SW_SHOWDEFAULT;
  148. if(hideWindows)
  149. {
  150. si.wShowWindow = SW_HIDE;
  151. }
  152. //set the new handles for the child process si.hStdInput = newstdin;
  153. char* commandAndArgs = strcpy(new char[strlen(command)+1], command);
  154. if (!CreateProcess(NULL,commandAndArgs,NULL,NULL,TRUE,
  155. 0, // CREATE_NEW_CONSOLE,
  156. NULL,dir,&si,&pi))
  157. {
  158. std::cerr << "CreateProcess failed " << commandAndArgs << std::endl;
  159. CloseHandle(newstdin);
  160. CloseHandle(newstdout);
  161. CloseHandle(read_stdout);
  162. CloseHandle(write_stdin);
  163. delete [] commandAndArgs;
  164. return false;
  165. }
  166. delete [] commandAndArgs;
  167. unsigned long exit=0;
  168. //process exit code unsigned
  169. unsigned long bread;
  170. //bytes read unsigned
  171. unsigned long avail;
  172. //bytes available
  173. memset(buf, 0, sizeof(buf));
  174. for(;;)
  175. //main program loop
  176. {
  177. Sleep(10);
  178. //check to see if there is any data to read from stdout
  179. //std::cout << "Peek for data..." << std::endl;
  180. PeekNamedPipe(read_stdout,buf,1023,&bread,&avail,NULL);
  181. if (bread != 0)
  182. {
  183. memset(buf, 0, sizeof(buf));
  184. if (avail > 1023)
  185. {
  186. while (bread >= 1023)
  187. {
  188. //std::cout << "Read data..." << std::endl;
  189. ReadFile(read_stdout,buf,1023,&bread,NULL);
  190. //read the stdout pipe
  191. memset(buf, 0, sizeof(buf));
  192. output += buf;
  193. if (verbose)
  194. {
  195. cmSystemTools::Stdout(buf);
  196. }
  197. }
  198. }
  199. else
  200. {
  201. ReadFile(read_stdout,buf,1023,&bread,NULL);
  202. output += buf;
  203. if(verbose)
  204. {
  205. cmSystemTools::Stdout(buf);
  206. }
  207. }
  208. }
  209. //std::cout << "Check for process..." << std::endl;
  210. GetExitCodeProcess(pi.hProcess,&exit);
  211. //while the process is running
  212. if (exit != STILL_ACTIVE) break;
  213. }
  214. WaitForSingleObject(pi.hProcess, INFINITE);
  215. GetExitCodeProcess(pi.hProcess,&exit);
  216. CloseHandle(pi.hThread);
  217. CloseHandle(pi.hProcess);
  218. CloseHandle(newstdin);
  219. //clean stuff up
  220. CloseHandle(newstdout);
  221. CloseHandle(read_stdout);
  222. CloseHandle(write_stdin);
  223. retVal = exit;
  224. return true;
  225. }
  226. bool cmWin32ProcessExecution::StartProcess(
  227. const char* cmd, const char* path, bool verbose)
  228. {
  229. this->Initialize();
  230. m_Verbose = verbose;
  231. return this->PrivateOpen(cmd, path, _O_RDONLY | _O_TEXT, POPEN_3);
  232. }
  233. bool cmWin32ProcessExecution::Wait(int timeout)
  234. {
  235. return this->PrivateClose(timeout);
  236. }
  237. /*
  238. * Internal dictionary mapping popen* file pointers to process handles,
  239. * for use when retrieving the process exit code. See _PyPclose() below
  240. * for more information on this dictionary's use.
  241. */
  242. static void *_PyPopenProcs = NULL;
  243. static BOOL RealPopenCreateProcess(const char *cmdstring,
  244. const char *path,
  245. const char *szConsoleSpawn,
  246. HANDLE hStdin,
  247. HANDLE hStdout,
  248. HANDLE hStderr,
  249. HANDLE *hProcess,
  250. bool hideWindows,
  251. std::string& output)
  252. {
  253. PROCESS_INFORMATION piProcInfo;
  254. STARTUPINFO siStartInfo;
  255. char *s1=0,*s2=0, *s3 = " /c ";
  256. int i;
  257. int x;
  258. if (i = GetEnvironmentVariable("COMSPEC",NULL,0))
  259. {
  260. char *comshell;
  261. s1 = (char *)malloc(i);
  262. if (!(x = GetEnvironmentVariable("COMSPEC", s1, i)))
  263. {
  264. free(s1);
  265. return x;
  266. }
  267. /* Explicitly check if we are using COMMAND.COM. If we are
  268. * then use the w9xpopen hack.
  269. */
  270. comshell = s1 + x;
  271. while (comshell >= s1 && *comshell != '\\')
  272. --comshell;
  273. ++comshell;
  274. if (GetVersion() < 0x80000000 &&
  275. STRICMP(comshell, "command.com") != 0)
  276. {
  277. /* NT/2000 and not using command.com. */
  278. x = i + (int)strlen(s3) + (int)strlen(cmdstring) + 1;
  279. s2 = (char *)malloc(x);
  280. ZeroMemory(s2, x);
  281. //sprintf(s2, "%s%s%s", s1, s3, cmdstring);
  282. sprintf(s2, "%s", cmdstring);
  283. }
  284. else
  285. {
  286. /*
  287. * Oh gag, we're on Win9x or using COMMAND.COM. Use
  288. * the workaround listed in KB: Q150956
  289. */
  290. char modulepath[_MAX_PATH];
  291. struct stat statinfo;
  292. GetModuleFileName(NULL, modulepath, sizeof(modulepath));
  293. for (i = x = 0; modulepath[i]; i++)
  294. if (modulepath[i] == '\\')
  295. x = i+1;
  296. modulepath[x] = '\0';
  297. /* Create the full-name to w9xpopen, so we can test it exists */
  298. strncat(modulepath,
  299. szConsoleSpawn,
  300. (sizeof(modulepath)/sizeof(modulepath[0]))
  301. -strlen(modulepath));
  302. if (stat(modulepath, &statinfo) != 0)
  303. {
  304. /* Eeek - file-not-found - possibly an embedding
  305. situation - see if we can locate it in sys.prefix
  306. */
  307. strncpy(modulepath,
  308. ".",
  309. sizeof(modulepath)/sizeof(modulepath[0]));
  310. if (modulepath[strlen(modulepath)-1] != '\\')
  311. strcat(modulepath, "\\");
  312. strncat(modulepath,
  313. szConsoleSpawn,
  314. (sizeof(modulepath)/sizeof(modulepath[0]))
  315. -strlen(modulepath));
  316. /* No where else to look - raise an easily identifiable
  317. error, rather than leaving Windows to report
  318. "file not found" - as the user is probably blissfully
  319. unaware this shim EXE is used, and it will confuse them.
  320. (well, it confused me for a while ;-)
  321. */
  322. if (stat(modulepath, &statinfo) != 0)
  323. {
  324. std::cout
  325. << "Can not locate '" << modulepath
  326. << "' which is needed "
  327. "for popen to work with your shell "
  328. "or platform." << std::endl;
  329. free(s1);
  330. free(s2);
  331. return FALSE;
  332. }
  333. }
  334. x = i + (int)strlen(s3) + (int)strlen(cmdstring) + 1 +
  335. (int)strlen(modulepath) +
  336. (int)strlen(szConsoleSpawn) + 1;
  337. if(s2)
  338. {
  339. free(s2);
  340. }
  341. s2 = (char *)malloc(x);
  342. ZeroMemory(s2, x);
  343. sprintf(
  344. s2,
  345. "%s %s%s%s",
  346. modulepath,
  347. s1,
  348. s3,
  349. cmdstring);
  350. sprintf(
  351. s2,
  352. "%s %s",
  353. modulepath,
  354. cmdstring);
  355. }
  356. }
  357. /* Could be an else here to try cmd.exe / command.com in the path
  358. Now we'll just error out.. */
  359. else
  360. {
  361. std::cout << "Cannot locate a COMSPEC environment variable to "
  362. << "use as the shell" << std::endl;
  363. free(s2);
  364. free(s1);
  365. return FALSE;
  366. }
  367. ZeroMemory(&siStartInfo, sizeof(STARTUPINFO));
  368. siStartInfo.cb = sizeof(STARTUPINFO);
  369. siStartInfo.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
  370. siStartInfo.hStdInput = hStdin;
  371. siStartInfo.hStdOutput = hStdout;
  372. siStartInfo.hStdError = hStderr;
  373. siStartInfo.wShowWindow = SW_SHOWDEFAULT;
  374. if(hideWindows)
  375. {
  376. siStartInfo.wShowWindow = SW_HIDE;
  377. }
  378. //std::cout << "Create process: " << s2 << std::endl;
  379. if (CreateProcess(NULL,
  380. s2,
  381. NULL,
  382. NULL,
  383. TRUE,
  384. 0, //CREATE_NEW_CONSOLE,
  385. NULL,
  386. path,
  387. &siStartInfo,
  388. &piProcInfo) )
  389. {
  390. /* Close the handles now so anyone waiting is woken. */
  391. CloseHandle(piProcInfo.hThread);
  392. /* Return process handle */
  393. *hProcess = piProcInfo.hProcess;
  394. //std::cout << "Process created..." << std::endl;
  395. free(s2);
  396. free(s1);
  397. return TRUE;
  398. }
  399. LPVOID lpMsgBuf;
  400. FormatMessage(
  401. FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
  402. NULL,
  403. GetLastError(),
  404. MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
  405. (LPTSTR) &lpMsgBuf,
  406. 0,
  407. NULL
  408. );
  409. // Free the buffer.
  410. char* str = strcpy(new char[strlen((char*)lpMsgBuf)+1], (char*)lpMsgBuf);
  411. LocalFree( lpMsgBuf );
  412. output += "CreateProcessError: ";
  413. output += str;
  414. output += "\n";
  415. output += "for command: ";
  416. output += s2;
  417. if(path)
  418. {
  419. output += "\nin dir: ";
  420. output += path;
  421. }
  422. output += "\n";
  423. delete [] str;
  424. free(s2);
  425. free(s1);
  426. return FALSE;
  427. }
  428. /* The following code is based off of KB: Q190351 */
  429. bool cmWin32ProcessExecution::PrivateOpen(const char *cmdstring,
  430. const char* path,
  431. int mode,
  432. int n)
  433. {
  434. HANDLE hProcess;
  435. SECURITY_ATTRIBUTES saAttr;
  436. BOOL fSuccess;
  437. int fd1, fd2, fd3;
  438. this->hChildStdinRd = 0;
  439. this->hChildStdinWr = 0;
  440. this->hChildStdoutRd = 0;
  441. this->hChildStdoutWr = 0;
  442. this->hChildStderrRd = 0;
  443. this->hChildStderrWr = 0;
  444. this->hChildStdinWrDup = 0;
  445. this->hChildStdoutRdDup = 0;
  446. this->hChildStderrRdDup = 0;
  447. saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
  448. saAttr.bInheritHandle = TRUE;
  449. saAttr.lpSecurityDescriptor = NULL;
  450. if (!CreatePipe(&this->hChildStdinRd, &this->hChildStdinWr, &saAttr, 0))
  451. {
  452. m_Output += "CreatePipeError\n";
  453. return false;
  454. }
  455. /* Create new output read handle and the input write handle. Set
  456. * the inheritance properties to FALSE. Otherwise, the child inherits
  457. * the these handles; resulting in non-closeable handles to the pipes
  458. * being created. */
  459. fSuccess = DuplicateHandle(GetCurrentProcess(), this->hChildStdinWr,
  460. GetCurrentProcess(), &this->hChildStdinWrDup, 0,
  461. FALSE,
  462. DUPLICATE_SAME_ACCESS);
  463. if (!fSuccess)
  464. {
  465. m_Output += "DuplicateHandleError\n";
  466. return false;
  467. }
  468. /* Close the inheritable version of ChildStdin
  469. that we're using. */
  470. CloseHandle(hChildStdinWr);
  471. if (!CreatePipe(&this->hChildStdoutRd, &this->hChildStdoutWr, &saAttr, 0))
  472. {
  473. m_Output += "CreatePipeError\n";
  474. return false;
  475. }
  476. fSuccess = DuplicateHandle(GetCurrentProcess(), this->hChildStdoutRd,
  477. GetCurrentProcess(), &this->hChildStdoutRdDup, 0,
  478. FALSE, DUPLICATE_SAME_ACCESS);
  479. if (!fSuccess)
  480. {
  481. m_Output += "DuplicateHandleError\n";
  482. return false;
  483. }
  484. /* Close the inheritable version of ChildStdout
  485. that we're using. */
  486. CloseHandle(hChildStdoutRd);
  487. if (n != POPEN_4)
  488. {
  489. if (!CreatePipe(&this->hChildStderrRd, &this->hChildStderrWr, &saAttr, 0))
  490. {
  491. m_Output += "CreatePipeError\n";
  492. return false;
  493. }
  494. fSuccess = DuplicateHandle(GetCurrentProcess(),
  495. this->hChildStderrRd,
  496. GetCurrentProcess(),
  497. &this->hChildStderrRdDup, 0,
  498. FALSE, DUPLICATE_SAME_ACCESS);
  499. if (!fSuccess)
  500. {
  501. m_Output += "DuplicateHandleError\n";
  502. return false;
  503. }
  504. /* Close the inheritable version of ChildStdErr that we're using. */
  505. CloseHandle(hChildStderrRd);
  506. }
  507. switch (n)
  508. {
  509. case POPEN_1:
  510. switch (mode & (_O_RDONLY | _O_TEXT | _O_BINARY | _O_WRONLY))
  511. {
  512. case _O_WRONLY | _O_TEXT:
  513. /* Case for writing to child Stdin in text mode. */
  514. fd1 = _open_osfhandle(TO_INTPTR(this->hChildStdinWrDup), mode);
  515. /* We don't care about these pipes anymore,
  516. so close them. */
  517. break;
  518. case _O_RDONLY | _O_TEXT:
  519. /* Case for reading from child Stdout in text mode. */
  520. fd1 = _open_osfhandle(TO_INTPTR(this->hChildStdoutRdDup), mode);
  521. /* We don't care about these pipes anymore,
  522. so close them. */
  523. break;
  524. case _O_RDONLY | _O_BINARY:
  525. /* Case for readinig from child Stdout in
  526. binary mode. */
  527. fd1 = _open_osfhandle(TO_INTPTR(this->hChildStdoutRdDup), mode);
  528. /* We don't care about these pipes anymore,
  529. so close them. */
  530. break;
  531. case _O_WRONLY | _O_BINARY:
  532. /* Case for writing to child Stdin in binary mode. */
  533. fd1 = _open_osfhandle(TO_INTPTR(this->hChildStdinWrDup), mode);
  534. /* We don't care about these pipes anymore,
  535. so close them. */
  536. break;
  537. }
  538. break;
  539. case POPEN_2:
  540. case POPEN_4:
  541. if ( 1 )
  542. {
  543. fd1 = _open_osfhandle(TO_INTPTR(this->hChildStdinWrDup), mode);
  544. fd2 = _open_osfhandle(TO_INTPTR(this->hChildStdoutRdDup), mode);
  545. break;
  546. }
  547. case POPEN_3:
  548. if ( 1)
  549. {
  550. fd1 = _open_osfhandle(TO_INTPTR(this->hChildStdinWrDup), mode);
  551. fd2 = _open_osfhandle(TO_INTPTR(this->hChildStdoutRdDup), mode);
  552. fd3 = _open_osfhandle(TO_INTPTR(this->hChildStderrRdDup), mode);
  553. break;
  554. }
  555. }
  556. if (n == POPEN_4)
  557. {
  558. if (!RealPopenCreateProcess(cmdstring,
  559. path,
  560. m_ConsoleSpawn.c_str(),
  561. this->hChildStdinRd,
  562. this->hChildStdoutWr,
  563. this->hChildStdoutWr,
  564. &hProcess, m_HideWindows,
  565. m_Output))
  566. return 0;
  567. }
  568. else
  569. {
  570. if (!RealPopenCreateProcess(cmdstring,
  571. path,
  572. m_ConsoleSpawn.c_str(),
  573. this->hChildStdinRd,
  574. this->hChildStdoutWr,
  575. this->hChildStderrWr,
  576. &hProcess, m_HideWindows,
  577. m_Output))
  578. return 0;
  579. }
  580. /*
  581. * Insert the files we've created into the process dictionary
  582. * all referencing the list with the process handle and the
  583. * initial number of files (see description below in _PyPclose).
  584. * Since if _PyPclose later tried to wait on a process when all
  585. * handles weren't closed, it could create a deadlock with the
  586. * child, we spend some energy here to try to ensure that we
  587. * either insert all file handles into the dictionary or none
  588. * at all. It's a little clumsy with the various popen modes
  589. * and variable number of files involved.
  590. */
  591. /* Child is launched. Close the parents copy of those pipe
  592. * handles that only the child should have open. You need to
  593. * make sure that no handles to the write end of the output pipe
  594. * are maintained in this process or else the pipe will not close
  595. * when the child process exits and the ReadFile will hang. */
  596. m_ProcessHandle = hProcess;
  597. if ( fd1 >= 0 )
  598. {
  599. // m_StdIn = f1;
  600. m_pStdIn = fd1;
  601. }
  602. if ( fd2 >= 0 )
  603. {
  604. // m_StdOut = f2;
  605. m_pStdOut = fd2;
  606. }
  607. if ( fd3 >= 0 )
  608. {
  609. // m_StdErr = f3;
  610. m_pStdErr = fd3;
  611. }
  612. return true;
  613. }
  614. bool cmWin32ProcessExecution::CloseHandles()
  615. {
  616. bool ret = true;
  617. if (this->hChildStdinRd && !CloseHandle(this->hChildStdinRd))
  618. {
  619. m_Output += "CloseHandleError\n";
  620. ret = false;
  621. }
  622. this->hChildStdinRd = 0;
  623. if(this->hChildStdoutRdDup && !CloseHandle(this->hChildStdoutRdDup))
  624. {
  625. m_Output += "CloseHandleError\n";
  626. ret = false;
  627. }
  628. this->hChildStdoutRdDup = 0;
  629. if(this->hChildStderrRdDup && !CloseHandle(this->hChildStderrRdDup))
  630. {
  631. m_Output += "CloseHandleError\n";
  632. ret = false;
  633. }
  634. this->hChildStderrRdDup = 0;
  635. if(this->hChildStdinWrDup && !CloseHandle(this->hChildStdinWrDup))
  636. {
  637. m_Output += "CloseHandleError\n";
  638. ret = false;
  639. }
  640. this->hChildStdinWrDup = 0;
  641. if (this->hChildStdoutWr && !CloseHandle(this->hChildStdoutWr))
  642. {
  643. m_Output += "CloseHandleError\n";
  644. ret = false;
  645. }
  646. this->hChildStdoutWr = 0;
  647. if (this->hChildStderrWr && !CloseHandle(this->hChildStderrWr))
  648. {
  649. m_Output += "CloseHandleError\n";
  650. ret = false;
  651. }
  652. this->hChildStderrWr = 0;
  653. return ret;
  654. }
  655. cmWin32ProcessExecution::~cmWin32ProcessExecution()
  656. {
  657. this->CloseHandles();
  658. }
  659. /*
  660. * Wrapper for fclose() to use for popen* files, so we can retrieve the
  661. * exit code for the child process and return as a result of the close.
  662. *
  663. * This function uses the _PyPopenProcs dictionary in order to map the
  664. * input file pointer to information about the process that was
  665. * originally created by the popen* call that created the file pointer.
  666. * The dictionary uses the file pointer as a key (with one entry
  667. * inserted for each file returned by the original popen* call) and a
  668. * single list object as the value for all files from a single call.
  669. * The list object contains the Win32 process handle at [0], and a file
  670. * count at [1], which is initialized to the total number of file
  671. * handles using that list.
  672. *
  673. * This function closes whichever handle it is passed, and decrements
  674. * the file count in the dictionary for the process handle pointed to
  675. * by this file. On the last close (when the file count reaches zero),
  676. * this function will wait for the child process and then return its
  677. * exit code as the result of the close() operation. This permits the
  678. * files to be closed in any order - it is always the close() of the
  679. * final handle that will return the exit code.
  680. */
  681. /* RED_FLAG 31-Aug-2000 Tim
  682. * This is always called (today!) between a pair of
  683. * Py_BEGIN_ALLOW_THREADS/ Py_END_ALLOW_THREADS
  684. * macros. So the thread running this has no valid thread state, as
  685. * far as Python is concerned. However, this calls some Python API
  686. * functions that cannot be called safely without a valid thread
  687. * state, in particular PyDict_GetItem.
  688. * As a temporary hack (although it may last for years ...), we
  689. * *rely* on not having a valid thread state in this function, in
  690. * order to create our own "from scratch".
  691. * This will deadlock if _PyPclose is ever called by a thread
  692. * holding the global lock.
  693. */
  694. bool cmWin32ProcessExecution::PrivateClose(int /* timeout */)
  695. {
  696. HANDLE hProcess = m_ProcessHandle;
  697. int result = -1;
  698. DWORD exit_code;
  699. std::string output = "";
  700. bool done = false;
  701. while(!done)
  702. {
  703. Sleep(10);
  704. bool have_some = false;
  705. struct _stat fsout;
  706. struct _stat fserr;
  707. int rout = _fstat(m_pStdOut, &fsout);
  708. int rerr = _fstat(m_pStdErr, &fserr);
  709. if ( rout && rerr )
  710. {
  711. break;
  712. }
  713. if (fserr.st_size > 0)
  714. {
  715. char buffer[1023];
  716. int len = read(m_pStdErr, buffer, 1023);
  717. buffer[len] = 0;
  718. if ( m_Verbose )
  719. {
  720. cmSystemTools::Stdout(buffer);
  721. }
  722. output += buffer;
  723. have_some = true;
  724. }
  725. if (fsout.st_size > 0)
  726. {
  727. char buffer[1023];
  728. int len = read(m_pStdOut, buffer, 1023);
  729. buffer[len] = 0;
  730. if ( m_Verbose )
  731. {
  732. cmSystemTools::Stdout(buffer);
  733. }
  734. output += buffer;
  735. have_some = true;
  736. }
  737. unsigned long exitCode;
  738. if ( ! have_some )
  739. {
  740. GetExitCodeProcess(hProcess,&exitCode);
  741. if (exitCode != STILL_ACTIVE)
  742. {
  743. break;
  744. }
  745. }
  746. }
  747. if (WaitForSingleObject(hProcess, INFINITE) != WAIT_FAILED &&
  748. GetExitCodeProcess(hProcess, &exit_code))
  749. {
  750. result = exit_code;
  751. }
  752. else
  753. {
  754. /* Indicate failure - this will cause the file object
  755. * to raise an I/O error and translate the last Win32
  756. * error code from errno. We do have a problem with
  757. * last errors that overlap the normal errno table,
  758. * but that's a consistent problem with the file object.
  759. */
  760. if (result != EOF)
  761. {
  762. /* If the error wasn't from the fclose(), then
  763. * set errno for the file object error handling.
  764. */
  765. errno = GetLastError();
  766. }
  767. result = -1;
  768. }
  769. /* Free up the native handle at this point */
  770. CloseHandle(hProcess);
  771. m_ExitValue = result;
  772. m_Output += output;
  773. bool ret = this->CloseHandles();
  774. if ( result < 0 || !ret)
  775. {
  776. return false;
  777. }
  778. return true;
  779. }
  780. int cmWin32ProcessExecution::Windows9xHack(const char* command)
  781. {
  782. BOOL bRet;
  783. STARTUPINFO si;
  784. PROCESS_INFORMATION pi;
  785. DWORD exit_code=0;
  786. if (!command)
  787. {
  788. cmSystemTools::Error("Windows9xHack: Command not specified");
  789. return 1;
  790. }
  791. /* Make child process use this app's standard files. */
  792. ZeroMemory(&si, sizeof si);
  793. si.cb = sizeof si;
  794. si.dwFlags = STARTF_USESTDHANDLES;
  795. si.hStdInput = GetStdHandle(STD_INPUT_HANDLE);
  796. si.hStdOutput = GetStdHandle(STD_OUTPUT_HANDLE);
  797. si.hStdError = GetStdHandle(STD_ERROR_HANDLE);
  798. char * app = 0;
  799. char* cmd = new char[ strlen(command) + 1 ];
  800. strcpy(cmd, command);
  801. bRet = CreateProcess(
  802. app, cmd,
  803. 0, 0,
  804. TRUE, 0,
  805. 0, 0,
  806. &si, &pi
  807. );
  808. delete [] cmd;
  809. if (bRet)
  810. {
  811. if (WaitForSingleObject(pi.hProcess, INFINITE) != WAIT_FAILED)
  812. {
  813. GetExitCodeProcess(pi.hProcess, &exit_code);
  814. }
  815. CloseHandle(pi.hProcess);
  816. CloseHandle(pi.hThread);
  817. return exit_code;
  818. }
  819. return 1;
  820. }