cmWin32ProcessExecution.cxx 26 KB

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