cmWin32ProcessExecution.cxx 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904
  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. std::cout << buf << std::flush;
  196. }
  197. }
  198. }
  199. else
  200. {
  201. ReadFile(read_stdout,buf,1023,&bread,NULL);
  202. output += buf;
  203. if(verbose)
  204. {
  205. std::cout << buf << std::flush;
  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. output += "CreateProcessError ";
  400. output += s2;
  401. output += "\n";
  402. free(s2);
  403. free(s1);
  404. return FALSE;
  405. }
  406. /* The following code is based off of KB: Q190351 */
  407. bool cmWin32ProcessExecution::PrivateOpen(const char *cmdstring,
  408. const char* path,
  409. int mode,
  410. int n)
  411. {
  412. HANDLE hChildStdinRd, hChildStdinWr, hChildStdoutRd, hChildStdoutWr,
  413. hChildStderrRd, hChildStderrWr, hChildStdinWrDup, hChildStdoutRdDup,
  414. hChildStderrRdDup, hProcess; /* hChildStdoutWrDup; */
  415. SECURITY_ATTRIBUTES saAttr;
  416. BOOL fSuccess;
  417. int fd1, fd2, fd3;
  418. //FILE *f1, *f2, *f3;
  419. saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
  420. saAttr.bInheritHandle = TRUE;
  421. saAttr.lpSecurityDescriptor = NULL;
  422. if (!CreatePipe(&hChildStdinRd, &hChildStdinWr, &saAttr, 0))
  423. {
  424. m_Output += "CreatePipeError\n";
  425. return false;
  426. }
  427. /* Create new output read handle and the input write handle. Set
  428. * the inheritance properties to FALSE. Otherwise, the child inherits
  429. * the these handles; resulting in non-closeable handles to the pipes
  430. * being created. */
  431. fSuccess = DuplicateHandle(GetCurrentProcess(), hChildStdinWr,
  432. GetCurrentProcess(), &hChildStdinWrDup, 0,
  433. FALSE,
  434. DUPLICATE_SAME_ACCESS);
  435. if (!fSuccess)
  436. {
  437. m_Output += "DuplicateHandleError\n";
  438. return false;
  439. }
  440. /* Close the inheritable version of ChildStdin
  441. that we're using. */
  442. CloseHandle(hChildStdinWr);
  443. if (!CreatePipe(&hChildStdoutRd, &hChildStdoutWr, &saAttr, 0))
  444. {
  445. m_Output += "CreatePipeError\n";
  446. return false;
  447. }
  448. fSuccess = DuplicateHandle(GetCurrentProcess(), hChildStdoutRd,
  449. GetCurrentProcess(), &hChildStdoutRdDup, 0,
  450. FALSE, DUPLICATE_SAME_ACCESS);
  451. if (!fSuccess)
  452. {
  453. m_Output += "DuplicateHandleError\n";
  454. return false;
  455. }
  456. /* Close the inheritable version of ChildStdout
  457. that we're using. */
  458. CloseHandle(hChildStdoutRd);
  459. if (n != POPEN_4)
  460. {
  461. if (!CreatePipe(&hChildStderrRd, &hChildStderrWr, &saAttr, 0))
  462. {
  463. m_Output += "CreatePipeError\n";
  464. return false;
  465. }
  466. fSuccess = DuplicateHandle(GetCurrentProcess(),
  467. hChildStderrRd,
  468. GetCurrentProcess(),
  469. &hChildStderrRdDup, 0,
  470. FALSE, DUPLICATE_SAME_ACCESS);
  471. if (!fSuccess)
  472. {
  473. m_Output += "DuplicateHandleError\n";
  474. return false;
  475. }
  476. /* Close the inheritable version of ChildStdErr that we're using. */
  477. CloseHandle(hChildStderrRd);
  478. }
  479. switch (n)
  480. {
  481. case POPEN_1:
  482. switch (mode & (_O_RDONLY | _O_TEXT | _O_BINARY | _O_WRONLY))
  483. {
  484. case _O_WRONLY | _O_TEXT:
  485. /* Case for writing to child Stdin in text mode. */
  486. fd1 = _open_osfhandle(TO_INTPTR(hChildStdinWrDup), mode);
  487. //f1 = _fdopen(fd1, "w");
  488. /* We don't care about these pipes anymore,
  489. so close them. */
  490. CloseHandle(hChildStdoutRdDup);
  491. CloseHandle(hChildStderrRdDup);
  492. break;
  493. case _O_RDONLY | _O_TEXT:
  494. /* Case for reading from child Stdout in text mode. */
  495. fd1 = _open_osfhandle(TO_INTPTR(hChildStdoutRdDup), mode);
  496. //f1 = _fdopen(fd1, "r");
  497. /* We don't care about these pipes anymore,
  498. so close them. */
  499. CloseHandle(hChildStdinWrDup);
  500. CloseHandle(hChildStderrRdDup);
  501. break;
  502. case _O_RDONLY | _O_BINARY:
  503. /* Case for readinig from child Stdout in
  504. binary mode. */
  505. fd1 = _open_osfhandle(TO_INTPTR(hChildStdoutRdDup), mode);
  506. //f1 = _fdopen(fd1, "rb");
  507. /* We don't care about these pipes anymore,
  508. so close them. */
  509. CloseHandle(hChildStdinWrDup);
  510. CloseHandle(hChildStderrRdDup);
  511. break;
  512. case _O_WRONLY | _O_BINARY:
  513. /* Case for writing to child Stdin in binary mode. */
  514. fd1 = _open_osfhandle(TO_INTPTR(hChildStdinWrDup), mode);
  515. //f1 = _fdopen(fd1, "wb");
  516. /* We don't care about these pipes anymore,
  517. so close them. */
  518. CloseHandle(hChildStdoutRdDup);
  519. CloseHandle(hChildStderrRdDup);
  520. break;
  521. }
  522. break;
  523. case POPEN_2:
  524. case POPEN_4:
  525. if ( 1 )
  526. {
  527. // Comment this out. Maybe we will need it in the future.
  528. // file IO access to the process might be cool.
  529. //char *m1, *m2;
  530. //if (mode && _O_TEXT)
  531. // {
  532. // m1 = "r";
  533. // m2 = "w";
  534. // }
  535. //else
  536. // {
  537. // m1 = "rb";
  538. // m2 = "wb";
  539. // }
  540. fd1 = _open_osfhandle(TO_INTPTR(hChildStdinWrDup), mode);
  541. //f1 = _fdopen(fd1, m2);
  542. fd2 = _open_osfhandle(TO_INTPTR(hChildStdoutRdDup), mode);
  543. //f2 = _fdopen(fd2, m1);
  544. if (n != 4)
  545. {
  546. CloseHandle(hChildStderrRdDup);
  547. }
  548. break;
  549. }
  550. case POPEN_3:
  551. if ( 1)
  552. {
  553. // Comment this out. Maybe we will need it in the future.
  554. // file IO access to the process might be cool.
  555. //char *m1, *m2;
  556. //if (mode && _O_TEXT)
  557. // {
  558. // m1 = "r";
  559. // m2 = "w";
  560. // }
  561. //else
  562. // {
  563. // m1 = "rb";
  564. // m2 = "wb";
  565. // }
  566. fd1 = _open_osfhandle(TO_INTPTR(hChildStdinWrDup), mode);
  567. //f1 = _fdopen(fd1, m2);
  568. fd2 = _open_osfhandle(TO_INTPTR(hChildStdoutRdDup), mode);
  569. //f2 = _fdopen(fd2, m1);
  570. fd3 = _open_osfhandle(TO_INTPTR(hChildStderrRdDup), mode);
  571. //f3 = _fdopen(fd3, m1);
  572. break;
  573. }
  574. }
  575. if (n == POPEN_4)
  576. {
  577. if (!RealPopenCreateProcess(cmdstring,
  578. path,
  579. m_ConsoleSpawn.c_str(),
  580. hChildStdinRd,
  581. hChildStdoutWr,
  582. hChildStdoutWr,
  583. &hProcess, m_HideWindows,
  584. m_Output))
  585. return NULL;
  586. }
  587. else
  588. {
  589. if (!RealPopenCreateProcess(cmdstring,
  590. path,
  591. m_ConsoleSpawn.c_str(),
  592. hChildStdinRd,
  593. hChildStdoutWr,
  594. hChildStderrWr,
  595. &hProcess, m_HideWindows,
  596. m_Output))
  597. return NULL;
  598. }
  599. /*
  600. * Insert the files we've created into the process dictionary
  601. * all referencing the list with the process handle and the
  602. * initial number of files (see description below in _PyPclose).
  603. * Since if _PyPclose later tried to wait on a process when all
  604. * handles weren't closed, it could create a deadlock with the
  605. * child, we spend some energy here to try to ensure that we
  606. * either insert all file handles into the dictionary or none
  607. * at all. It's a little clumsy with the various popen modes
  608. * and variable number of files involved.
  609. */
  610. /* Child is launched. Close the parents copy of those pipe
  611. * handles that only the child should have open. You need to
  612. * make sure that no handles to the write end of the output pipe
  613. * are maintained in this process or else the pipe will not close
  614. * when the child process exits and the ReadFile will hang. */
  615. if (!CloseHandle(hChildStdinRd))
  616. {
  617. m_Output += "CloseHandleError\n";
  618. return false;
  619. }
  620. if (!CloseHandle(hChildStdoutWr))
  621. {
  622. m_Output += "CloseHandleError\n";
  623. return false;
  624. }
  625. if ((n != 4) && (!CloseHandle(hChildStderrWr)))
  626. {
  627. m_Output += "CloseHandleError\n";
  628. return false;
  629. }
  630. m_ProcessHandle = hProcess;
  631. if ( fd1 >= 0 )
  632. {
  633. // m_StdIn = f1;
  634. m_pStdIn = fd1;
  635. }
  636. if ( fd2 >= 0 )
  637. {
  638. // m_StdOut = f2;
  639. m_pStdOut = fd2;
  640. }
  641. if ( fd3 >= 0 )
  642. {
  643. // m_StdErr = f3;
  644. m_pStdErr = fd3;
  645. }
  646. return true;
  647. }
  648. /*
  649. * Wrapper for fclose() to use for popen* files, so we can retrieve the
  650. * exit code for the child process and return as a result of the close.
  651. *
  652. * This function uses the _PyPopenProcs dictionary in order to map the
  653. * input file pointer to information about the process that was
  654. * originally created by the popen* call that created the file pointer.
  655. * The dictionary uses the file pointer as a key (with one entry
  656. * inserted for each file returned by the original popen* call) and a
  657. * single list object as the value for all files from a single call.
  658. * The list object contains the Win32 process handle at [0], and a file
  659. * count at [1], which is initialized to the total number of file
  660. * handles using that list.
  661. *
  662. * This function closes whichever handle it is passed, and decrements
  663. * the file count in the dictionary for the process handle pointed to
  664. * by this file. On the last close (when the file count reaches zero),
  665. * this function will wait for the child process and then return its
  666. * exit code as the result of the close() operation. This permits the
  667. * files to be closed in any order - it is always the close() of the
  668. * final handle that will return the exit code.
  669. */
  670. /* RED_FLAG 31-Aug-2000 Tim
  671. * This is always called (today!) between a pair of
  672. * Py_BEGIN_ALLOW_THREADS/ Py_END_ALLOW_THREADS
  673. * macros. So the thread running this has no valid thread state, as
  674. * far as Python is concerned. However, this calls some Python API
  675. * functions that cannot be called safely without a valid thread
  676. * state, in particular PyDict_GetItem.
  677. * As a temporary hack (although it may last for years ...), we
  678. * *rely* on not having a valid thread state in this function, in
  679. * order to create our own "from scratch".
  680. * This will deadlock if _PyPclose is ever called by a thread
  681. * holding the global lock.
  682. */
  683. bool cmWin32ProcessExecution::PrivateClose(int /* timeout */)
  684. {
  685. HANDLE hProcess = m_ProcessHandle;
  686. int result = -1;
  687. DWORD exit_code;
  688. std::string output = "";
  689. bool done = false;
  690. while(!done)
  691. {
  692. Sleep(10);
  693. bool have_some = false;
  694. struct _stat fsout;
  695. struct _stat fserr;
  696. int rout = _fstat(m_pStdOut, &fsout);
  697. int rerr = _fstat(m_pStdErr, &fserr);
  698. if ( rout && rerr )
  699. {
  700. break;
  701. }
  702. if (fserr.st_size > 0)
  703. {
  704. char buffer[1023];
  705. int len = read(m_pStdErr, 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. if (fsout.st_size > 0)
  715. {
  716. char buffer[1023];
  717. int len = read(m_pStdOut, buffer, 1023);
  718. buffer[len] = 0;
  719. if ( m_Verbose )
  720. {
  721. std::cout << buffer << std::flush;
  722. }
  723. output += buffer;
  724. have_some = true;
  725. }
  726. unsigned long exitCode;
  727. if ( ! have_some )
  728. {
  729. GetExitCodeProcess(hProcess,&exitCode);
  730. if (exitCode != STILL_ACTIVE)
  731. {
  732. break;
  733. }
  734. }
  735. }
  736. if (WaitForSingleObject(hProcess, INFINITE) != WAIT_FAILED &&
  737. GetExitCodeProcess(hProcess, &exit_code))
  738. {
  739. result = exit_code;
  740. }
  741. else
  742. {
  743. /* Indicate failure - this will cause the file object
  744. * to raise an I/O error and translate the last Win32
  745. * error code from errno. We do have a problem with
  746. * last errors that overlap the normal errno table,
  747. * but that's a consistent problem with the file object.
  748. */
  749. if (result != EOF)
  750. {
  751. /* If the error wasn't from the fclose(), then
  752. * set errno for the file object error handling.
  753. */
  754. errno = GetLastError();
  755. }
  756. result = -1;
  757. }
  758. /* Free up the native handle at this point */
  759. CloseHandle(hProcess);
  760. m_ExitValue = result;
  761. m_Output += output;
  762. if ( result < 0 )
  763. {
  764. return false;
  765. }
  766. return true;
  767. }
  768. int cmWin32ProcessExecution::Windows9xHack(const char* command)
  769. {
  770. BOOL bRet;
  771. STARTUPINFO si;
  772. PROCESS_INFORMATION pi;
  773. DWORD exit_code=0;
  774. if (!command)
  775. {
  776. cmSystemTools::Error("Windows9xHack: Command not specified");
  777. return 1;
  778. }
  779. /* Make child process use this app's standard files. */
  780. ZeroMemory(&si, sizeof si);
  781. si.cb = sizeof si;
  782. si.dwFlags = STARTF_USESTDHANDLES;
  783. si.hStdInput = GetStdHandle(STD_INPUT_HANDLE);
  784. si.hStdOutput = GetStdHandle(STD_OUTPUT_HANDLE);
  785. si.hStdError = GetStdHandle(STD_ERROR_HANDLE);
  786. char * app = 0;
  787. char* cmd = new char[ strlen(command) + 1 ];
  788. strcpy(cmd, command);
  789. bRet = CreateProcess(
  790. app, cmd,
  791. NULL, NULL,
  792. TRUE, 0,
  793. NULL, NULL,
  794. &si, &pi
  795. );
  796. delete [] cmd;
  797. if (bRet)
  798. {
  799. if (WaitForSingleObject(pi.hProcess, INFINITE) != WAIT_FAILED)
  800. {
  801. GetExitCodeProcess(pi.hProcess, &exit_code);
  802. }
  803. CloseHandle(pi.hProcess);
  804. CloseHandle(pi.hThread);
  805. return exit_code;
  806. }
  807. return 1;
  808. }