cmWin32ProcessExecution.cxx 26 KB

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