1
0

cmSystemTools.cxx 33 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334
  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 "cmSystemTools.h"
  14. #include <ctype.h>
  15. #include <errno.h>
  16. #include <time.h>
  17. #include <cmsys/RegularExpression.hxx>
  18. #include <cmsys/Directory.hxx>
  19. #include <cmsys/Process.h>
  20. // support for realpath call
  21. #ifndef _WIN32
  22. #include <limits.h>
  23. #include <stdlib.h>
  24. #include <sys/param.h>
  25. #include <sys/wait.h>
  26. #endif
  27. #if defined(_WIN32) && (defined(_MSC_VER) || defined(__BORLANDC__))
  28. #include <string.h>
  29. #include <windows.h>
  30. #include <direct.h>
  31. #include <io.h>
  32. #define _unlink unlink
  33. #else
  34. #include <sys/types.h>
  35. #include <fcntl.h>
  36. #include <unistd.h>
  37. #endif
  38. #include <sys/stat.h>
  39. #if defined(__sgi) && !defined(__GNUC__)
  40. # pragma set woff 1375 /* base class destructor not virtual */
  41. #endif
  42. bool cmSystemTools::s_RunCommandHideConsole = false;
  43. bool cmSystemTools::s_DisableRunCommandOutput = false;
  44. bool cmSystemTools::s_ErrorOccured = false;
  45. bool cmSystemTools::s_FatalErrorOccured = false;
  46. bool cmSystemTools::s_DisableMessages = false;
  47. bool cmSystemTools::s_ForceUnixPaths = false;
  48. std::string cmSystemTools::s_Windows9xComspecSubstitute = "command.com";
  49. void cmSystemTools::SetWindows9xComspecSubstitute(const char* str)
  50. {
  51. if ( str )
  52. {
  53. cmSystemTools::s_Windows9xComspecSubstitute = str;
  54. }
  55. }
  56. const char* cmSystemTools::GetWindows9xComspecSubstitute()
  57. {
  58. return cmSystemTools::s_Windows9xComspecSubstitute.c_str();
  59. }
  60. void (*cmSystemTools::s_ErrorCallback)(const char*, const char*, bool&, void*);
  61. void (*cmSystemTools::s_StdoutCallback)(const char*, int len, void*);
  62. void* cmSystemTools::s_ErrorCallbackClientData = 0;
  63. void* cmSystemTools::s_StdoutCallbackClientData = 0;
  64. // replace replace with with as many times as it shows up in source.
  65. // write the result into source.
  66. #if defined(_WIN32) && !defined(__CYGWIN__)
  67. void cmSystemTools::ExpandRegistryValues(std::string& source)
  68. {
  69. // Regular expression to match anything inside [...] that begins in HKEY.
  70. // Note that there is a special rule for regular expressions to match a
  71. // close square-bracket inside a list delimited by square brackets.
  72. // The "[^]]" part of this expression will match any character except
  73. // a close square-bracket. The ']' character must be the first in the
  74. // list of characters inside the [^...] block of the expression.
  75. cmsys::RegularExpression regEntry("\\[(HKEY[^]]*)\\]");
  76. // check for black line or comment
  77. while (regEntry.find(source))
  78. {
  79. // the arguments are the second match
  80. std::string key = regEntry.match(1);
  81. std::string val;
  82. if (ReadRegistryValue(key.c_str(), val))
  83. {
  84. std::string reg = "[";
  85. reg += key + "]";
  86. cmSystemTools::ReplaceString(source, reg.c_str(), val.c_str());
  87. }
  88. else
  89. {
  90. std::string reg = "[";
  91. reg += key + "]";
  92. cmSystemTools::ReplaceString(source, reg.c_str(), "/registry");
  93. }
  94. }
  95. }
  96. #else
  97. void cmSystemTools::ExpandRegistryValues(std::string&)
  98. {
  99. }
  100. #endif
  101. std::string cmSystemTools::EscapeQuotes(const char* str)
  102. {
  103. std::string result = "";
  104. for(const char* ch = str; *ch != '\0'; ++ch)
  105. {
  106. if(*ch == '"')
  107. {
  108. result += '\\';
  109. }
  110. result += *ch;
  111. }
  112. return result;
  113. }
  114. std::string cmSystemTools::EscapeSpaces(const char* str)
  115. {
  116. #if defined(_WIN32) && !defined(__CYGWIN__)
  117. bool useDoubleQ = true;
  118. #else
  119. bool useDoubleQ = false;
  120. #endif
  121. if(cmSystemTools::s_ForceUnixPaths)
  122. {
  123. useDoubleQ = false;
  124. }
  125. if(useDoubleQ)
  126. {
  127. std::string result;
  128. // if there are spaces
  129. std::string temp = str;
  130. if (temp.find(" ") != std::string::npos &&
  131. temp.find("\"")==std::string::npos)
  132. {
  133. result = "\"";
  134. result += str;
  135. result += "\"";
  136. return result;
  137. }
  138. return str;
  139. }
  140. else
  141. {
  142. std::string result = "";
  143. for(const char* ch = str; *ch != '\0'; ++ch)
  144. {
  145. if(*ch == ' ')
  146. {
  147. result += '\\';
  148. }
  149. result += *ch;
  150. }
  151. return result;
  152. }
  153. }
  154. std::string cmSystemTools::RemoveEscapes(const char* s)
  155. {
  156. std::string result = "";
  157. for(const char* ch = s; *ch; ++ch)
  158. {
  159. if(*ch == '\\' && *(ch+1) != ';')
  160. {
  161. ++ch;
  162. switch (*ch)
  163. {
  164. case '\\': result.insert(result.end(), '\\'); break;
  165. case '"': result.insert(result.end(), '"'); break;
  166. case ' ': result.insert(result.end(), ' '); break;
  167. case 't': result.insert(result.end(), '\t'); break;
  168. case 'n': result.insert(result.end(), '\n'); break;
  169. case 'r': result.insert(result.end(), '\r'); break;
  170. case '#': result.insert(result.end(), '#'); break;
  171. case '(': result.insert(result.end(), '('); break;
  172. case ')': result.insert(result.end(), ')'); break;
  173. case '0': result.insert(result.end(), '\0'); break;
  174. case '\0':
  175. {
  176. cmSystemTools::Error("Trailing backslash in argument:\n", s);
  177. return result;
  178. }
  179. default:
  180. {
  181. std::string chStr(1, *ch);
  182. cmSystemTools::Error("Invalid escape sequence \\", chStr.c_str(),
  183. "\nin argument ", s);
  184. }
  185. }
  186. }
  187. else
  188. {
  189. result.insert(result.end(), *ch);
  190. }
  191. }
  192. return result;
  193. }
  194. void cmSystemTools::Error(const char* m1, const char* m2,
  195. const char* m3, const char* m4)
  196. {
  197. std::string message = "CMake Error: ";
  198. if(m1)
  199. {
  200. message += m1;
  201. }
  202. if(m2)
  203. {
  204. message += m2;
  205. }
  206. if(m3)
  207. {
  208. message += m3;
  209. }
  210. if(m4)
  211. {
  212. message += m4;
  213. }
  214. cmSystemTools::s_ErrorOccured = true;
  215. cmSystemTools::Message(message.c_str(),"Error");
  216. }
  217. void cmSystemTools::SetErrorCallback(ErrorCallback f, void* clientData)
  218. {
  219. s_ErrorCallback = f;
  220. s_ErrorCallbackClientData = clientData;
  221. }
  222. void cmSystemTools::SetStdoutCallback(StdoutCallback f, void* clientData)
  223. {
  224. s_StdoutCallback = f;
  225. s_StdoutCallbackClientData = clientData;
  226. }
  227. void cmSystemTools::Stdout(const char* s)
  228. {
  229. if(s_StdoutCallback)
  230. {
  231. (*s_StdoutCallback)(s, strlen(s), s_StdoutCallbackClientData);
  232. }
  233. else
  234. {
  235. std::cout << s;
  236. std::cout.flush();
  237. }
  238. }
  239. void cmSystemTools::Stdout(const char* s, int length)
  240. {
  241. if(s_StdoutCallback)
  242. {
  243. (*s_StdoutCallback)(s, length, s_StdoutCallbackClientData);
  244. }
  245. else
  246. {
  247. std::cout.write(s, length);
  248. std::cout.flush();
  249. }
  250. }
  251. void cmSystemTools::Message(const char* m1, const char *title)
  252. {
  253. if(s_DisableMessages)
  254. {
  255. return;
  256. }
  257. if(s_ErrorCallback)
  258. {
  259. (*s_ErrorCallback)(m1, title, s_DisableMessages, s_ErrorCallbackClientData);
  260. return;
  261. }
  262. else
  263. {
  264. std::cerr << m1 << std::endl << std::flush;
  265. }
  266. }
  267. void cmSystemTools::ReportLastSystemError(const char* msg)
  268. {
  269. std::string m = msg;
  270. m += ": System Error: ";
  271. m += Superclass::GetLastSystemError();
  272. cmSystemTools::Error(m.c_str());
  273. }
  274. bool cmSystemTools::IsOn(const char* val)
  275. {
  276. if (!val)
  277. {
  278. return false;
  279. }
  280. std::basic_string<char> v = val;
  281. for(std::basic_string<char>::iterator c = v.begin();
  282. c != v.end(); c++)
  283. {
  284. *c = toupper(*c);
  285. }
  286. return (v == "ON" || v == "1" || v == "YES" || v == "TRUE" || v == "Y");
  287. }
  288. bool cmSystemTools::IsNOTFOUND(const char* val)
  289. {
  290. int len = strlen(val);
  291. const char* notfound = "-NOTFOUND";
  292. const int lenNotFound = 9;
  293. if(len < lenNotFound-1)
  294. {
  295. return false;
  296. }
  297. if(len == lenNotFound-1)
  298. {
  299. return ( strcmp(val, "NOTFOUND") == 0);
  300. }
  301. return ((strncmp((val + (len - lenNotFound)), notfound, lenNotFound) == 0));
  302. }
  303. bool cmSystemTools::IsOff(const char* val)
  304. {
  305. if (!val || strlen(val) == 0)
  306. {
  307. return true;
  308. }
  309. std::basic_string<char> v = val;
  310. for(std::basic_string<char>::iterator c = v.begin();
  311. c != v.end(); c++)
  312. {
  313. *c = toupper(*c);
  314. }
  315. return (v == "OFF" || v == "0" || v == "NO" || v == "FALSE" ||
  316. v == "N" || cmSystemTools::IsNOTFOUND(v.c_str()) || v == "IGNORE");
  317. }
  318. std::vector<cmStdString> cmSystemTools::ParseArguments(const char* command)
  319. {
  320. std::vector<cmStdString> args;
  321. std::string arg;
  322. bool win_path = false;
  323. if ( command[0] != '/' && command[1] == ':' && command[2] == '\\' ||
  324. command[0] == '\"' && command[1] != '/' && command[2] == ':' && command[3] == '\\' ||
  325. command[0] == '\'' && command[1] != '/' && command[2] == ':' && command[3] == '\\' ||
  326. command[0] == '\\' && command[1] == '\\')
  327. {
  328. win_path = true;
  329. }
  330. // Split the command into an argv array.
  331. for(const char* c = command; *c;)
  332. {
  333. // Skip over whitespace.
  334. while(*c == ' ' || *c == '\t')
  335. {
  336. ++c;
  337. }
  338. arg = "";
  339. if(*c == '"')
  340. {
  341. // Parse a quoted argument.
  342. ++c;
  343. while(*c && *c != '"')
  344. {
  345. arg.append(1, *c);
  346. ++c;
  347. }
  348. if(*c)
  349. {
  350. ++c;
  351. }
  352. args.push_back(arg);
  353. }
  354. else if(*c == '\'')
  355. {
  356. // Parse a quoted argument.
  357. ++c;
  358. while(*c && *c != '\'')
  359. {
  360. arg.append(1, *c);
  361. ++c;
  362. }
  363. if(*c)
  364. {
  365. ++c;
  366. }
  367. args.push_back(arg);
  368. }
  369. else if(*c)
  370. {
  371. // Parse an unquoted argument.
  372. while(*c && *c != ' ' && *c != '\t')
  373. {
  374. if(*c == '\\' && !win_path)
  375. {
  376. ++c;
  377. if(*c)
  378. {
  379. arg.append(1, *c);
  380. ++c;
  381. }
  382. }
  383. else
  384. {
  385. arg.append(1, *c);
  386. ++c;
  387. }
  388. }
  389. args.push_back(arg);
  390. }
  391. }
  392. return args;
  393. }
  394. bool cmSystemTools::RunSingleCommand(
  395. const char* command,
  396. std::string* output,
  397. int *retVal,
  398. const char* dir,
  399. bool verbose,
  400. double timeout)
  401. {
  402. if(s_DisableRunCommandOutput)
  403. {
  404. verbose = false;
  405. }
  406. std::vector<cmStdString> args = cmSystemTools::ParseArguments(command);
  407. if(args.size() < 1)
  408. {
  409. return false;
  410. }
  411. std::vector<const char*> argv;
  412. for(std::vector<cmStdString>::const_iterator a = args.begin();
  413. a != args.end(); ++a)
  414. {
  415. argv.push_back(a->c_str());
  416. }
  417. argv.push_back(0);
  418. if ( output )
  419. {
  420. *output = "";
  421. }
  422. cmsysProcess* cp = cmsysProcess_New();
  423. cmsysProcess_SetCommand(cp, &*argv.begin());
  424. cmsysProcess_SetWorkingDirectory(cp, dir);
  425. if(cmSystemTools::GetRunCommandHideConsole())
  426. {
  427. cmsysProcess_SetOption(cp, cmsysProcess_Option_HideWindow, 1);
  428. }
  429. cmsysProcess_SetTimeout(cp, timeout);
  430. cmsysProcess_Execute(cp);
  431. std::vector<char> tempOutput;
  432. char* data;
  433. int length;
  434. if ( output || verbose )
  435. {
  436. while(cmsysProcess_WaitForData(cp, &data, &length, 0))
  437. {
  438. if ( output )
  439. {
  440. tempOutput.insert(tempOutput.end(), data, data+length);
  441. }
  442. if(verbose)
  443. {
  444. cmSystemTools::Stdout(data, length);
  445. }
  446. }
  447. }
  448. cmsysProcess_WaitForExit(cp, 0);
  449. if ( output )
  450. {
  451. output->append(&*tempOutput.begin(), tempOutput.size());
  452. }
  453. bool result = true;
  454. if(cmsysProcess_GetState(cp) == cmsysProcess_State_Exited)
  455. {
  456. if ( retVal )
  457. {
  458. *retVal = cmsysProcess_GetExitValue(cp);
  459. }
  460. else
  461. {
  462. if ( cmsysProcess_GetExitValue(cp) != 0 )
  463. {
  464. result = false;
  465. }
  466. }
  467. }
  468. else if(cmsysProcess_GetState(cp) == cmsysProcess_State_Exception)
  469. {
  470. const char* exception_str = cmsysProcess_GetExceptionString(cp);
  471. if ( verbose )
  472. {
  473. std::cerr << exception_str << std::endl;
  474. }
  475. if ( output )
  476. {
  477. output->append(exception_str, strlen(exception_str));
  478. }
  479. result = false;
  480. }
  481. else if(cmsysProcess_GetState(cp) == cmsysProcess_State_Error)
  482. {
  483. const char* error_str = cmsysProcess_GetErrorString(cp);
  484. if ( verbose )
  485. {
  486. std::cerr << error_str << std::endl;
  487. }
  488. if ( output )
  489. {
  490. output->append(error_str, strlen(error_str));
  491. }
  492. result = false;
  493. }
  494. else if(cmsysProcess_GetState(cp) == cmsysProcess_State_Expired)
  495. {
  496. const char* error_str = "Process terminated due to timeout\n";
  497. if ( verbose )
  498. {
  499. std::cerr << error_str << std::endl;
  500. }
  501. if ( output )
  502. {
  503. output->append(error_str, strlen(error_str));
  504. }
  505. result = false;
  506. }
  507. cmsysProcess_Delete(cp);
  508. return result;
  509. }
  510. bool cmSystemTools::RunCommand(const char* command,
  511. std::string& output,
  512. const char* dir,
  513. bool verbose,
  514. int timeout)
  515. {
  516. int dummy;
  517. return cmSystemTools::RunCommand(command, output, dummy,
  518. dir, verbose, timeout);
  519. }
  520. #if defined(WIN32) && !defined(__CYGWIN__)
  521. #include "cmWin32ProcessExecution.h"
  522. // use this for shell commands like echo and dir
  523. bool RunCommandViaWin32(const char* command,
  524. const char* dir,
  525. std::string& output,
  526. int& retVal,
  527. bool verbose,
  528. int timeout)
  529. {
  530. #if defined(__BORLANDC__)
  531. return cmWin32ProcessExecution::BorlandRunCommand(command, dir, output,
  532. retVal,
  533. verbose, timeout,
  534. cmSystemTools::GetRunCommandHideConsole());
  535. #else // Visual studio
  536. ::SetLastError(ERROR_SUCCESS);
  537. if ( ! command )
  538. {
  539. cmSystemTools::Error("No command specified");
  540. return false;
  541. }
  542. cmWin32ProcessExecution resProc;
  543. if(cmSystemTools::GetRunCommandHideConsole())
  544. {
  545. resProc.SetHideWindows(true);
  546. }
  547. if ( cmSystemTools::GetWindows9xComspecSubstitute() )
  548. {
  549. resProc.SetConsoleSpawn(cmSystemTools::GetWindows9xComspecSubstitute() );
  550. }
  551. if ( !resProc.StartProcess(command, dir, verbose) )
  552. {
  553. output = resProc.GetOutput();
  554. if(verbose)
  555. {
  556. cmSystemTools::Stdout(output.c_str());
  557. }
  558. return false;
  559. }
  560. resProc.Wait(timeout);
  561. output = resProc.GetOutput();
  562. retVal = resProc.GetExitValue();
  563. return true;
  564. #endif
  565. }
  566. // use this for shell commands like echo and dir
  567. bool RunCommandViaSystem(const char* command,
  568. const char* dir,
  569. std::string& output,
  570. int& retVal,
  571. bool verbose)
  572. {
  573. std::cout << "@@ " << command << std::endl;
  574. std::string commandInDir;
  575. if(dir)
  576. {
  577. commandInDir = "cd ";
  578. commandInDir += cmSystemTools::ConvertToOutputPath(dir);
  579. commandInDir += " && ";
  580. commandInDir += command;
  581. }
  582. else
  583. {
  584. commandInDir = command;
  585. }
  586. command = commandInDir.c_str();
  587. std::string commandToFile = command;
  588. commandToFile += " > ";
  589. std::string tempFile;
  590. tempFile += _tempnam(0, "cmake");
  591. commandToFile += tempFile;
  592. retVal = system(commandToFile.c_str());
  593. std::ifstream fin(tempFile.c_str());
  594. if(!fin)
  595. {
  596. if(verbose)
  597. {
  598. std::string errormsg = "RunCommand produced no output: command: \"";
  599. errormsg += command;
  600. errormsg += "\"";
  601. errormsg += "\nOutput file: ";
  602. errormsg += tempFile;
  603. cmSystemTools::Error(errormsg.c_str());
  604. }
  605. fin.close();
  606. cmSystemTools::RemoveFile(tempFile.c_str());
  607. return false;
  608. }
  609. bool multiLine = false;
  610. std::string line;
  611. while(cmSystemTools::GetLineFromStream(fin, line))
  612. {
  613. output += line;
  614. if(multiLine)
  615. {
  616. output += "\n";
  617. }
  618. multiLine = true;
  619. }
  620. fin.close();
  621. cmSystemTools::RemoveFile(tempFile.c_str());
  622. return true;
  623. }
  624. #else // We have popen
  625. bool RunCommandViaPopen(const char* command,
  626. const char* dir,
  627. std::string& output,
  628. int& retVal,
  629. bool verbose,
  630. int /*timeout*/)
  631. {
  632. // if only popen worked on windows.....
  633. std::string commandInDir;
  634. if(dir)
  635. {
  636. commandInDir = "cd \"";
  637. commandInDir += dir;
  638. commandInDir += "\" && ";
  639. commandInDir += command;
  640. }
  641. else
  642. {
  643. commandInDir = command;
  644. }
  645. commandInDir += " 2>&1";
  646. command = commandInDir.c_str();
  647. const int BUFFER_SIZE = 4096;
  648. char buffer[BUFFER_SIZE];
  649. if(verbose)
  650. {
  651. cmSystemTools::Stdout("running ");
  652. cmSystemTools::Stdout(command);
  653. cmSystemTools::Stdout("\n");
  654. }
  655. fflush(stdout);
  656. fflush(stderr);
  657. FILE* cpipe = popen(command, "r");
  658. if(!cpipe)
  659. {
  660. return false;
  661. }
  662. fgets(buffer, BUFFER_SIZE, cpipe);
  663. while(!feof(cpipe))
  664. {
  665. if(verbose)
  666. {
  667. cmSystemTools::Stdout(buffer);
  668. }
  669. output += buffer;
  670. fgets(buffer, BUFFER_SIZE, cpipe);
  671. }
  672. retVal = pclose(cpipe);
  673. if (WIFEXITED(retVal))
  674. {
  675. retVal = WEXITSTATUS(retVal);
  676. return true;
  677. }
  678. if (WIFSIGNALED(retVal))
  679. {
  680. retVal = WTERMSIG(retVal);
  681. cmOStringStream error;
  682. error << "\nProcess terminated due to ";
  683. switch (retVal)
  684. {
  685. #ifdef SIGKILL
  686. case SIGKILL:
  687. error << "SIGKILL";
  688. break;
  689. #endif
  690. #ifdef SIGFPE
  691. case SIGFPE:
  692. error << "SIGFPE";
  693. break;
  694. #endif
  695. #ifdef SIGBUS
  696. case SIGBUS:
  697. error << "SIGBUS";
  698. break;
  699. #endif
  700. #ifdef SIGSEGV
  701. case SIGSEGV:
  702. error << "SIGSEGV";
  703. break;
  704. #endif
  705. default:
  706. error << "signal " << retVal;
  707. break;
  708. }
  709. output += error.str();
  710. }
  711. return false;
  712. }
  713. #endif // endif WIN32 not CYGWIN
  714. // run a command unix uses popen (easy)
  715. // windows uses system and ShortPath
  716. bool cmSystemTools::RunCommand(const char* command,
  717. std::string& output,
  718. int &retVal,
  719. const char* dir,
  720. bool verbose,
  721. int timeout)
  722. {
  723. if(s_DisableRunCommandOutput)
  724. {
  725. verbose = false;
  726. }
  727. #if defined(WIN32) && !defined(__CYGWIN__)
  728. // if the command does not start with a quote, then
  729. // try to find the program, and if the program can not be
  730. // found use system to run the command as it must be a built in
  731. // shell command like echo or dir
  732. int count = 0;
  733. if(command[0] == '\"')
  734. {
  735. // count the number of quotes
  736. for(const char* s = command; *s != 0; ++s)
  737. {
  738. if(*s == '\"')
  739. {
  740. count++;
  741. if(count > 2)
  742. {
  743. break;
  744. }
  745. }
  746. }
  747. // if there are more than two double quotes use
  748. // GetShortPathName, the cmd.exe program in windows which
  749. // is used by system fails to execute if there are more than
  750. // one set of quotes in the arguments
  751. if(count > 2)
  752. {
  753. cmsys::RegularExpression quoted("^\"([^\"]*)\"[ \t](.*)");
  754. if(quoted.find(command))
  755. {
  756. std::string shortCmd;
  757. std::string cmd = quoted.match(1);
  758. std::string args = quoted.match(2);
  759. if(! cmSystemTools::FileExists(cmd.c_str()) )
  760. {
  761. shortCmd = cmd;
  762. }
  763. else if(!cmSystemTools::GetShortPath(cmd.c_str(), shortCmd))
  764. {
  765. cmSystemTools::Error("GetShortPath failed for " , cmd.c_str());
  766. return false;
  767. }
  768. shortCmd += " ";
  769. shortCmd += args;
  770. //return RunCommandViaSystem(shortCmd.c_str(), dir,
  771. // output, retVal, verbose);
  772. //return WindowsRunCommand(shortCmd.c_str(), dir,
  773. //output, retVal, verbose);
  774. return RunCommandViaWin32(shortCmd.c_str(), dir,
  775. output, retVal, verbose, timeout);
  776. }
  777. else
  778. {
  779. cmSystemTools::Error("Could not parse command line with quotes ",
  780. command);
  781. }
  782. }
  783. }
  784. // if there is only one set of quotes or no quotes then just run the command
  785. //return RunCommandViaSystem(command, dir, output, retVal, verbose);
  786. //return WindowsRunCommand(command, dir, output, retVal, verbose);
  787. return ::RunCommandViaWin32(command, dir, output, retVal, verbose, timeout);
  788. #else
  789. return ::RunCommandViaPopen(command, dir, output, retVal, verbose, timeout);
  790. #endif
  791. }
  792. bool cmSystemTools::DoesFileExistWithExtensions(
  793. const char* name,
  794. const std::vector<std::string>& headerExts)
  795. {
  796. std::string hname;
  797. for( std::vector<std::string>::const_iterator ext = headerExts.begin();
  798. ext != headerExts.end(); ++ext )
  799. {
  800. hname = name;
  801. hname += ".";
  802. hname += *ext;
  803. if(cmSystemTools::FileExists(hname.c_str()))
  804. {
  805. return true;
  806. }
  807. }
  808. return false;
  809. }
  810. bool cmSystemTools::cmCopyFile(const char* source, const char* destination)
  811. {
  812. return Superclass::CopyFileAlways(source, destination);
  813. }
  814. bool cmSystemTools::CopyFileIfDifferent(const char* source,
  815. const char* destination)
  816. {
  817. return Superclass::CopyFileIfDifferent(source, destination);
  818. }
  819. void cmSystemTools::Glob(const char *directory, const char *regexp,
  820. std::vector<std::string>& files)
  821. {
  822. cmsys::Directory d;
  823. cmsys::RegularExpression reg(regexp);
  824. if (d.Load(directory))
  825. {
  826. size_t numf;
  827. unsigned int i;
  828. numf = d.GetNumberOfFiles();
  829. for (i = 0; i < numf; i++)
  830. {
  831. std::string fname = d.GetFile(i);
  832. if (reg.find(fname))
  833. {
  834. files.push_back(fname);
  835. }
  836. }
  837. }
  838. }
  839. void cmSystemTools::GlobDirs(const char *fullPath,
  840. std::vector<std::string>& files)
  841. {
  842. std::string path = fullPath;
  843. std::string::size_type pos = path.find("/*");
  844. if(pos == std::string::npos)
  845. {
  846. files.push_back(fullPath);
  847. return;
  848. }
  849. std::string startPath = path.substr(0, pos);
  850. std::string finishPath = path.substr(pos+2);
  851. cmsys::Directory d;
  852. if (d.Load(startPath.c_str()))
  853. {
  854. for (unsigned int i = 0; i < d.GetNumberOfFiles(); ++i)
  855. {
  856. if((std::string(d.GetFile(i)) != ".")
  857. && (std::string(d.GetFile(i)) != ".."))
  858. {
  859. std::string fname = startPath;
  860. fname +="/";
  861. fname += d.GetFile(i);
  862. if(cmSystemTools::FileIsDirectory(fname.c_str()))
  863. {
  864. fname += finishPath;
  865. cmSystemTools::GlobDirs(fname.c_str(), files);
  866. }
  867. }
  868. }
  869. }
  870. }
  871. void cmSystemTools::ExpandList(std::vector<std::string> const& arguments,
  872. std::vector<std::string>& newargs)
  873. {
  874. std::vector<std::string>::const_iterator i;
  875. for(i = arguments.begin();i != arguments.end(); ++i)
  876. {
  877. cmSystemTools::ExpandListArgument(*i, newargs);
  878. }
  879. }
  880. void cmSystemTools::ExpandListArgument(const std::string& arg,
  881. std::vector<std::string>& newargs)
  882. {
  883. // If argument is empty, it is an empty list.
  884. if(arg.length() == 0)
  885. {
  886. return;
  887. }
  888. // if there are no ; in the name then just copy the current string
  889. if(arg.find(';') == std::string::npos)
  890. {
  891. newargs.push_back(arg);
  892. return;
  893. }
  894. std::vector<char> newArgVec;
  895. // Break the string at non-escaped semicolons not nested in [].
  896. int squareNesting = 0;
  897. for(const char* c = arg.c_str(); *c; ++c)
  898. {
  899. switch(*c)
  900. {
  901. case '\\':
  902. {
  903. // We only want to allow escaping of semicolons. Other
  904. // escapes should not be processed here.
  905. ++c;
  906. if(*c == ';')
  907. {
  908. newArgVec.push_back(*c);
  909. }
  910. else
  911. {
  912. newArgVec.push_back('\\');
  913. if(*c)
  914. {
  915. newArgVec.push_back(*c);
  916. }
  917. }
  918. } break;
  919. case '[':
  920. {
  921. ++squareNesting;
  922. newArgVec.push_back(*c);
  923. } break;
  924. case ']':
  925. {
  926. --squareNesting;
  927. newArgVec.push_back(*c);
  928. } break;
  929. case ';':
  930. {
  931. // Break the string here if we are not nested inside square
  932. // brackets.
  933. if(squareNesting == 0)
  934. {
  935. if ( newArgVec.size() )
  936. {
  937. // Add the last argument if the string is not empty.
  938. newArgVec.push_back(0);
  939. newargs.push_back(&*newArgVec.begin());
  940. newArgVec.clear();
  941. }
  942. }
  943. else
  944. {
  945. newArgVec.push_back(*c);
  946. }
  947. } break;
  948. default:
  949. {
  950. // Just append this character.
  951. newArgVec.push_back(*c);
  952. } break;
  953. }
  954. }
  955. if ( newArgVec.size() )
  956. {
  957. // Add the last argument if the string is not empty.
  958. newArgVec.push_back(0);
  959. newargs.push_back(&*newArgVec.begin());
  960. }
  961. }
  962. bool cmSystemTools::SimpleGlob(const cmStdString& glob,
  963. std::vector<cmStdString>& files,
  964. int type /* = 0 */)
  965. {
  966. files.clear();
  967. if ( glob[glob.size()-1] != '*' )
  968. {
  969. return false;
  970. }
  971. std::string path = cmSystemTools::GetFilenamePath(glob);
  972. std::string ppath = cmSystemTools::GetFilenameName(glob);
  973. ppath = ppath.substr(0, ppath.size()-1);
  974. if ( path.size() == 0 )
  975. {
  976. path = "/";
  977. }
  978. bool res = false;
  979. cmsys::Directory d;
  980. if (d.Load(path.c_str()))
  981. {
  982. for (unsigned int i = 0; i < d.GetNumberOfFiles(); ++i)
  983. {
  984. if((std::string(d.GetFile(i)) != ".")
  985. && (std::string(d.GetFile(i)) != ".."))
  986. {
  987. std::string fname = path;
  988. if ( path[path.size()-1] != '/' )
  989. {
  990. fname +="/";
  991. }
  992. fname += d.GetFile(i);
  993. std::string sfname = d.GetFile(i);
  994. if ( type > 0 && cmSystemTools::FileIsDirectory(fname.c_str()) )
  995. {
  996. continue;
  997. }
  998. if ( type < 0 && !cmSystemTools::FileIsDirectory(fname.c_str()) )
  999. {
  1000. continue;
  1001. }
  1002. if ( sfname.size() >= ppath.size() &&
  1003. sfname.substr(0, ppath.size()) ==
  1004. ppath )
  1005. {
  1006. files.push_back(fname);
  1007. res = true;
  1008. }
  1009. }
  1010. }
  1011. }
  1012. return res;
  1013. }
  1014. cmSystemTools::FileFormat cmSystemTools::GetFileFormat(const char* cext)
  1015. {
  1016. if ( ! cext || *cext == 0 )
  1017. {
  1018. return cmSystemTools::NO_FILE_FORMAT;
  1019. }
  1020. //std::string ext = cmSystemTools::LowerCase(cext);
  1021. std::string ext = cext;
  1022. if ( ext == "c" || ext == ".c" ) { return cmSystemTools::C_FILE_FORMAT; }
  1023. if (
  1024. ext == "C" || ext == ".C" ||
  1025. ext == "M" || ext == ".M" ||
  1026. ext == "c++" || ext == ".c++" ||
  1027. ext == "cc" || ext == ".cc" ||
  1028. ext == "cpp" || ext == ".cpp" ||
  1029. ext == "cxx" || ext == ".cxx" ||
  1030. ext == "m" || ext == ".m" ||
  1031. ext == "mm" || ext == ".mm"
  1032. ) { return cmSystemTools::CXX_FILE_FORMAT; }
  1033. if (
  1034. ext == "f" || ext == ".f" ||
  1035. ext == "F" || ext == ".F" ||
  1036. ext == "f77" || ext == ".f77" ||
  1037. ext == "f90" || ext == ".f90" ||
  1038. ext == "for" || ext == ".for" ||
  1039. ext == "f95" || ext == ".f95"
  1040. ) { return cmSystemTools::FORTRAN_FILE_FORMAT; }
  1041. if ( ext == "java" || ext == ".java" ) { return cmSystemTools::JAVA_FILE_FORMAT; }
  1042. if (
  1043. ext == "H" || ext == ".H" ||
  1044. ext == "h" || ext == ".h" ||
  1045. ext == "h++" || ext == ".h++" ||
  1046. ext == "hm" || ext == ".hm" ||
  1047. ext == "hpp" || ext == ".hpp" ||
  1048. ext == "hxx" || ext == ".hxx" ||
  1049. ext == "in" || ext == ".in" ||
  1050. ext == "txx" || ext == ".txx"
  1051. ) { return cmSystemTools::HEADER_FILE_FORMAT; }
  1052. if ( ext == "rc" || ext == ".rc" ) { return cmSystemTools::RESOURCE_FILE_FORMAT; }
  1053. if ( ext == "def" || ext == ".def" ) { return cmSystemTools::DEFINITION_FILE_FORMAT; }
  1054. if ( ext == "lib" || ext == ".lib" ||
  1055. ext == "a" || ext == ".a") { return cmSystemTools::STATIC_LIBRARY_FILE_FORMAT; }
  1056. if ( ext == "o" || ext == ".o" ||
  1057. ext == "obj" || ext == ".obj") { return cmSystemTools::OBJECT_FILE_FORMAT; }
  1058. #ifdef __APPLE__
  1059. if ( ext == "dylib" || ext == ".dylib" )
  1060. { return cmSystemTools::SHARED_LIBRARY_FILE_FORMAT; }
  1061. if ( ext == "so" || ext == ".so" ||
  1062. ext == "bundle" || ext == ".bundle" )
  1063. { return cmSystemTools::MODULE_FILE_FORMAT; }
  1064. #else // __APPLE__
  1065. if ( ext == "so" || ext == ".so" ||
  1066. ext == "sl" || ext == ".sl" ||
  1067. ext == "dll" || ext == ".dll" )
  1068. { return cmSystemTools::SHARED_LIBRARY_FILE_FORMAT; }
  1069. #endif // __APPLE__
  1070. return cmSystemTools::UNKNOWN_FILE_FORMAT;
  1071. }
  1072. bool cmSystemTools::Split(const char* s, std::vector<cmStdString>& l)
  1073. {
  1074. std::vector<std::string> temp;
  1075. bool res = Superclass::Split(s, temp);
  1076. for(std::vector<std::string>::const_iterator i = temp.begin();
  1077. i != temp.end(); ++i)
  1078. {
  1079. l.push_back(*i);
  1080. }
  1081. return res;
  1082. }
  1083. std::string cmSystemTools::ConvertToOutputPath(const char* path)
  1084. {
  1085. #if defined(_WIN32) && !defined(__CYGWIN__)
  1086. if(s_ForceUnixPaths)
  1087. {
  1088. return cmSystemTools::ConvertToUnixOutputPath(path);
  1089. }
  1090. return cmSystemTools::ConvertToWindowsOutputPath(path);
  1091. #else
  1092. return cmSystemTools::ConvertToUnixOutputPath(path);
  1093. #endif
  1094. }
  1095. std::string cmSystemTools::ConvertToRunCommandPath(const char* path)
  1096. {
  1097. #if defined(_WIN32) && !defined(__CYGWIN__)
  1098. return cmSystemTools::ConvertToWindowsOutputPath(path);
  1099. #else
  1100. return cmSystemTools::ConvertToUnixOutputPath(path);
  1101. #endif
  1102. }
  1103. bool cmSystemTools::StringEndsWith(const char* str1, const char* str2)
  1104. {
  1105. if ( !str1 || !str2 || strlen(str1) < strlen(str2) )
  1106. {
  1107. return 0;
  1108. }
  1109. return !strncmp(str1 + (strlen(str1)-strlen(str2)), str2, strlen(str2));
  1110. }
  1111. #if defined(_WIN32) && !defined(__CYGWIN__)
  1112. bool cmSystemTools::CreateSymlink(const char*, const char*)
  1113. {
  1114. // Should we create a copy here?
  1115. return false;
  1116. }
  1117. #else
  1118. bool cmSystemTools::CreateSymlink(const char* origName, const char* newName)
  1119. {
  1120. return (symlink(origName, newName) >= 0);
  1121. }
  1122. #endif
  1123. std::vector<cmStdString> cmSystemTools::SplitString(const char* p, char sep, bool isPath)
  1124. {
  1125. std::string path = p;
  1126. std::vector<cmStdString> paths;
  1127. if(isPath && path[0] == '/')
  1128. {
  1129. path.erase(path.begin());
  1130. paths.push_back("/");
  1131. }
  1132. std::string::size_type pos1 = 0;
  1133. std::string::size_type pos2 = path.find(sep, pos1+1);
  1134. while(pos2 != std::string::npos)
  1135. {
  1136. paths.push_back(path.substr(pos1, pos2-pos1));
  1137. pos1 = pos2+1;
  1138. pos2 = path.find(sep, pos1+1);
  1139. }
  1140. paths.push_back(path.substr(pos1, pos2-pos1));
  1141. return paths;
  1142. }
  1143. // compute the relative path from here to there
  1144. std::string cmSystemTools::RelativePath(const char* local, const char* remote)
  1145. {
  1146. if(!cmSystemTools::FileIsFullPath(local))
  1147. {
  1148. cmSystemTools::Error("RelativePath must be passed a full path to local: ", local);
  1149. }
  1150. if(!cmSystemTools::FileIsFullPath(remote))
  1151. {
  1152. cmSystemTools::Error("RelativePath must be passed a full path to remote: ", remote);
  1153. }
  1154. // split up both paths into arrays of strings using / as a separator
  1155. std::vector<cmStdString> localSplit = cmSystemTools::SplitString(local, '/', true);
  1156. std::vector<cmStdString> remoteSplit = cmSystemTools::SplitString(remote, '/', true);
  1157. std::vector<cmStdString> commonPath; // store shared parts of path in this array
  1158. std::vector<cmStdString> finalPath; // store the final relative path here
  1159. // count up how many matching directory names there are from the start
  1160. unsigned int sameCount = 0;
  1161. while(
  1162. ((sameCount <= (localSplit.size()-1)) && (sameCount <= (remoteSplit.size()-1)))
  1163. &&
  1164. // for windows and apple do a case insensitive string compare
  1165. #if defined(_WIN32) || defined(__APPLE__)
  1166. cmSystemTools::Strucmp(localSplit[sameCount].c_str(),
  1167. remoteSplit[sameCount].c_str()) == 0
  1168. #else
  1169. localSplit[sameCount] == remoteSplit[sameCount]
  1170. #endif
  1171. )
  1172. {
  1173. // put the common parts of the path into the commonPath array
  1174. commonPath.push_back(localSplit[sameCount]);
  1175. // erase the common parts of the path from the original path arrays
  1176. localSplit[sameCount] = "";
  1177. remoteSplit[sameCount] = "";
  1178. sameCount++;
  1179. }
  1180. // If there is nothing in common but the root directory, then just
  1181. // return the full path.
  1182. if(sameCount <= 1)
  1183. {
  1184. return remote;
  1185. }
  1186. // for each entry that is not common in the local path
  1187. // add a ../ to the finalpath array, this gets us out of the local
  1188. // path into the remote dir
  1189. for(unsigned int i = 0; i < localSplit.size(); ++i)
  1190. {
  1191. if(localSplit[i].size())
  1192. {
  1193. finalPath.push_back("../");
  1194. }
  1195. }
  1196. // for each entry that is not common in the remote path add it
  1197. // to the final path.
  1198. for(std::vector<cmStdString>::iterator i = remoteSplit.begin();
  1199. i != remoteSplit.end(); ++i)
  1200. {
  1201. if(i->size())
  1202. {
  1203. finalPath.push_back(*i);
  1204. }
  1205. }
  1206. std::string relativePath; // result string
  1207. // now turn the array of directories into a unix path by puttint /
  1208. // between each entry that does not already have one
  1209. for(std::vector<cmStdString>::iterator i = finalPath.begin();
  1210. i != finalPath.end(); ++i)
  1211. {
  1212. if(relativePath.size() && relativePath[relativePath.size()-1] != '/')
  1213. {
  1214. relativePath += "/";
  1215. }
  1216. relativePath += *i;
  1217. }
  1218. return relativePath;
  1219. }
  1220. class cmDeletingCharVector : public std::vector<char*>
  1221. {
  1222. public:
  1223. ~cmDeletingCharVector()
  1224. {
  1225. for(std::vector<char*>::iterator i = this->begin();
  1226. i != this->end(); ++i)
  1227. {
  1228. delete []*i;
  1229. }
  1230. }
  1231. };
  1232. bool cmSystemTools::PutEnv(const char* value)
  1233. {
  1234. static cmDeletingCharVector localEnvironment;
  1235. char* envVar = new char[strlen(value)+1];
  1236. strcpy(envVar, value);
  1237. int ret = putenv(envVar);
  1238. // save the pointer in the static vector so that it can
  1239. // be deleted on exit
  1240. localEnvironment.push_back(envVar);
  1241. return ret == 0;
  1242. }