cmSystemTools.cxx 33 KB

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