cmSystemTools.cxx 32 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318
  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. mode_t perm = 0;
  794. return cmSystemTools::GetPermissions(source, perm) &&
  795. Superclass::CopyFileAlways(source, destination) &&
  796. cmSystemTools::SetPermissions(destination, perm);
  797. }
  798. bool cmSystemTools::CopyFileIfDifferent(const char* source,
  799. const char* destination)
  800. {
  801. mode_t perm = 0;
  802. return cmSystemTools::GetPermissions(source, perm) &&
  803. Superclass::CopyFileIfDifferent(source, destination) &&
  804. cmSystemTools::SetPermissions(destination, perm);
  805. }
  806. void cmSystemTools::Glob(const char *directory, const char *regexp,
  807. std::vector<std::string>& files)
  808. {
  809. cmsys::Directory d;
  810. cmsys::RegularExpression reg(regexp);
  811. if (d.Load(directory))
  812. {
  813. size_t numf;
  814. unsigned int i;
  815. numf = d.GetNumberOfFiles();
  816. for (i = 0; i < numf; i++)
  817. {
  818. std::string fname = d.GetFile(i);
  819. if (reg.find(fname))
  820. {
  821. files.push_back(fname);
  822. }
  823. }
  824. }
  825. }
  826. void cmSystemTools::GlobDirs(const char *fullPath,
  827. std::vector<std::string>& files)
  828. {
  829. std::string path = fullPath;
  830. std::string::size_type pos = path.find("/*");
  831. if(pos == std::string::npos)
  832. {
  833. files.push_back(fullPath);
  834. return;
  835. }
  836. std::string startPath = path.substr(0, pos);
  837. std::string finishPath = path.substr(pos+2);
  838. cmsys::Directory d;
  839. if (d.Load(startPath.c_str()))
  840. {
  841. for (unsigned int i = 0; i < d.GetNumberOfFiles(); ++i)
  842. {
  843. if((std::string(d.GetFile(i)) != ".")
  844. && (std::string(d.GetFile(i)) != ".."))
  845. {
  846. std::string fname = startPath;
  847. fname +="/";
  848. fname += d.GetFile(i);
  849. if(cmSystemTools::FileIsDirectory(fname.c_str()))
  850. {
  851. fname += finishPath;
  852. cmSystemTools::GlobDirs(fname.c_str(), files);
  853. }
  854. }
  855. }
  856. }
  857. }
  858. void cmSystemTools::ExpandList(std::vector<std::string> const& arguments,
  859. std::vector<std::string>& newargs)
  860. {
  861. std::vector<std::string>::const_iterator i;
  862. for(i = arguments.begin();i != arguments.end(); ++i)
  863. {
  864. cmSystemTools::ExpandListArgument(*i, newargs);
  865. }
  866. }
  867. void cmSystemTools::ExpandListArgument(const std::string& arg,
  868. std::vector<std::string>& newargs)
  869. {
  870. std::string newarg;
  871. // If argument is empty, it is an empty list.
  872. if(arg.length() == 0)
  873. {
  874. return;
  875. }
  876. // if there are no ; in the name then just copy the current string
  877. if(arg.find(';') == std::string::npos)
  878. {
  879. newargs.push_back(arg);
  880. return;
  881. }
  882. // Break the string at non-escaped semicolons not nested in [].
  883. int squareNesting = 0;
  884. for(const char* c = arg.c_str(); *c; ++c)
  885. {
  886. switch(*c)
  887. {
  888. case '\\':
  889. {
  890. // We only want to allow escaping of semicolons. Other
  891. // escapes should not be processed here.
  892. ++c;
  893. if(*c == ';')
  894. {
  895. newarg += ';';
  896. }
  897. else
  898. {
  899. newarg += '\\';
  900. if(*c)
  901. {
  902. newarg += *c;
  903. }
  904. }
  905. } break;
  906. case '[':
  907. {
  908. ++squareNesting;
  909. newarg += '[';
  910. } break;
  911. case ']':
  912. {
  913. --squareNesting;
  914. newarg += ']';
  915. } break;
  916. case ';':
  917. {
  918. // Break the string here if we are not nested inside square
  919. // brackets.
  920. if(squareNesting == 0)
  921. {
  922. if(newarg.length())
  923. {
  924. // Add an argument if the string is not empty.
  925. newargs.push_back(newarg);
  926. newarg = "";
  927. }
  928. }
  929. else
  930. {
  931. newarg += ';';
  932. }
  933. } break;
  934. default:
  935. {
  936. // Just append this character.
  937. newarg += *c;
  938. } break;
  939. }
  940. }
  941. if(newarg.length())
  942. {
  943. // Add the last argument if the string is not empty.
  944. newargs.push_back(newarg);
  945. }
  946. }
  947. bool cmSystemTools::SimpleGlob(const cmStdString& glob,
  948. std::vector<cmStdString>& files,
  949. int type /* = 0 */)
  950. {
  951. files.clear();
  952. if ( glob[glob.size()-1] != '*' )
  953. {
  954. return false;
  955. }
  956. std::string path = cmSystemTools::GetFilenamePath(glob);
  957. std::string ppath = cmSystemTools::GetFilenameName(glob);
  958. ppath = ppath.substr(0, ppath.size()-1);
  959. if ( path.size() == 0 )
  960. {
  961. path = "/";
  962. }
  963. bool res = false;
  964. cmsys::Directory d;
  965. if (d.Load(path.c_str()))
  966. {
  967. for (unsigned int i = 0; i < d.GetNumberOfFiles(); ++i)
  968. {
  969. if((std::string(d.GetFile(i)) != ".")
  970. && (std::string(d.GetFile(i)) != ".."))
  971. {
  972. std::string fname = path;
  973. if ( path[path.size()-1] != '/' )
  974. {
  975. fname +="/";
  976. }
  977. fname += d.GetFile(i);
  978. std::string sfname = d.GetFile(i);
  979. if ( type > 0 && cmSystemTools::FileIsDirectory(fname.c_str()) )
  980. {
  981. continue;
  982. }
  983. if ( type < 0 && !cmSystemTools::FileIsDirectory(fname.c_str()) )
  984. {
  985. continue;
  986. }
  987. if ( sfname.size() >= ppath.size() &&
  988. sfname.substr(0, ppath.size()) ==
  989. ppath )
  990. {
  991. files.push_back(fname);
  992. res = true;
  993. }
  994. }
  995. }
  996. }
  997. return res;
  998. }
  999. cmSystemTools::FileFormat cmSystemTools::GetFileFormat(const char* cext)
  1000. {
  1001. if ( ! cext || *cext == 0 )
  1002. {
  1003. return cmSystemTools::NO_FILE_FORMAT;
  1004. }
  1005. //std::string ext = cmSystemTools::LowerCase(cext);
  1006. std::string ext = cext;
  1007. if ( ext == "c" || ext == ".c" ) { return cmSystemTools::C_FILE_FORMAT; }
  1008. if (
  1009. ext == "C" || ext == ".C" ||
  1010. ext == "M" || ext == ".M" ||
  1011. ext == "c++" || ext == ".c++" ||
  1012. ext == "cc" || ext == ".cc" ||
  1013. ext == "cpp" || ext == ".cpp" ||
  1014. ext == "cxx" || ext == ".cxx" ||
  1015. ext == "m" || ext == ".m" ||
  1016. ext == "mm" || ext == ".mm"
  1017. ) { return cmSystemTools::CXX_FILE_FORMAT; }
  1018. if (
  1019. ext == "f" || ext == ".f" ||
  1020. ext == "F" || ext == ".F" ||
  1021. ext == "f77" || ext == ".f77" ||
  1022. ext == "f90" || ext == ".f90" ||
  1023. ext == "for" || ext == ".for" ||
  1024. ext == "f95" || ext == ".f95"
  1025. ) { return cmSystemTools::FORTRAN_FILE_FORMAT; }
  1026. if ( ext == "java" || ext == ".java" ) { return cmSystemTools::JAVA_FILE_FORMAT; }
  1027. if (
  1028. ext == "H" || ext == ".H" ||
  1029. ext == "h" || ext == ".h" ||
  1030. ext == "h++" || ext == ".h++" ||
  1031. ext == "hm" || ext == ".hm" ||
  1032. ext == "hpp" || ext == ".hpp" ||
  1033. ext == "hxx" || ext == ".hxx" ||
  1034. ext == "in" || ext == ".in" ||
  1035. ext == "txx" || ext == ".txx"
  1036. ) { return cmSystemTools::HEADER_FILE_FORMAT; }
  1037. if ( ext == "rc" || ext == ".rc" ) { return cmSystemTools::RESOURCE_FILE_FORMAT; }
  1038. if ( ext == "def" || ext == ".def" ) { return cmSystemTools::DEFINITION_FILE_FORMAT; }
  1039. if ( ext == "lib" || ext == ".lib" ||
  1040. ext == "a" || ext == ".a") { return cmSystemTools::STATIC_LIBRARY_FILE_FORMAT; }
  1041. if ( ext == "o" || ext == ".o" ||
  1042. ext == "obj" || ext == ".obj") { return cmSystemTools::OBJECT_FILE_FORMAT; }
  1043. #ifdef __APPLE__
  1044. if ( ext == "dylib" || ext == ".dylib" )
  1045. { return cmSystemTools::SHARED_LIBRARY_FILE_FORMAT; }
  1046. if ( ext == "so" || ext == ".so" ||
  1047. ext == "bundle" || ext == ".bundle" )
  1048. { return cmSystemTools::MODULE_FILE_FORMAT; }
  1049. #else // __APPLE__
  1050. if ( ext == "so" || ext == ".so" ||
  1051. ext == "sl" || ext == ".sl" ||
  1052. ext == "dll" || ext == ".dll" )
  1053. { return cmSystemTools::SHARED_LIBRARY_FILE_FORMAT; }
  1054. #endif // __APPLE__
  1055. return cmSystemTools::UNKNOWN_FILE_FORMAT;
  1056. }
  1057. bool cmSystemTools::Split(const char* s, std::vector<cmStdString>& l)
  1058. {
  1059. std::vector<std::string> temp;
  1060. bool res = Superclass::Split(s, temp);
  1061. for(std::vector<std::string>::const_iterator i = temp.begin();
  1062. i != temp.end(); ++i)
  1063. {
  1064. l.push_back(*i);
  1065. }
  1066. return res;
  1067. }
  1068. std::string cmSystemTools::ConvertToOutputPath(const char* path)
  1069. {
  1070. #if defined(_WIN32) && !defined(__CYGWIN__)
  1071. if(s_ForceUnixPaths)
  1072. {
  1073. return cmSystemTools::ConvertToUnixOutputPath(path);
  1074. }
  1075. return cmSystemTools::ConvertToWindowsOutputPath(path);
  1076. #else
  1077. return cmSystemTools::ConvertToUnixOutputPath(path);
  1078. #endif
  1079. }
  1080. std::string cmSystemTools::ConvertToRunCommandPath(const char* path)
  1081. {
  1082. #if defined(_WIN32) && !defined(__CYGWIN__)
  1083. return cmSystemTools::ConvertToWindowsOutputPath(path);
  1084. #else
  1085. return cmSystemTools::ConvertToUnixOutputPath(path);
  1086. #endif
  1087. }
  1088. bool cmSystemTools::StringEndsWith(const char* str1, const char* str2)
  1089. {
  1090. if ( !str1 || !str2 || strlen(str1) < strlen(str2) )
  1091. {
  1092. return 0;
  1093. }
  1094. return !strncmp(str1 + (strlen(str1)-strlen(str2)), str2, strlen(str2));
  1095. }
  1096. #if defined(_WIN32) && !defined(__CYGWIN__)
  1097. bool cmSystemTools::CreateSymlink(const char*, const char*)
  1098. {
  1099. // Should we create a copy here?
  1100. return false;
  1101. }
  1102. #else
  1103. bool cmSystemTools::CreateSymlink(const char* origName, const char* newName)
  1104. {
  1105. return (symlink(origName, newName) >= 0);
  1106. }
  1107. #endif
  1108. std::vector<cmStdString> cmSystemTools::SplitString(const char* p, char sep)
  1109. {
  1110. std::string path = p;
  1111. std::vector<cmStdString> paths;
  1112. std::string::size_type pos1 = 0;
  1113. std::string::size_type pos2 = path.find(sep, pos1+1);
  1114. while(pos2 != std::string::npos)
  1115. {
  1116. paths.push_back(path.substr(pos1, pos2-pos1));
  1117. pos1 = pos2+1;
  1118. pos2 = path.find(sep, pos1+1);
  1119. }
  1120. paths.push_back(path.substr(pos1, pos2-pos1));
  1121. return paths;
  1122. }
  1123. // compute the relative path from here to there
  1124. std::string cmSystemTools::RelativePath(const char* local, const char* remote)
  1125. {
  1126. #ifdef _WIN32
  1127. std::string lowerCaseLocal = cmSystemTools::LowerCase(std::string(local));
  1128. std::string lowerCaseRemote = cmSystemTools::LowerCase(std::string(remote));
  1129. remote = lowerCaseRemote.c_str();
  1130. local = lowerCaseLocal.c_str();
  1131. #endif
  1132. // check for driveletter: as the start of the path
  1133. // if not on the same drive then full path to remote must be used.
  1134. if(local[0] && local[0] != '/')
  1135. {
  1136. if(remote[0] && local[0] != remote[0])
  1137. {
  1138. return remote;
  1139. }
  1140. }
  1141. std::string relativePath; // result string
  1142. // split up both paths into arrays of strings using / as a separator
  1143. std::vector<cmStdString> fileSplit = cmSystemTools::SplitString(local);
  1144. std::vector<cmStdString> relativeSplit = cmSystemTools::SplitString(remote);
  1145. // count up how many mathing directory names there are from the start
  1146. unsigned int sameCount = 0;
  1147. while(sameCount < fileSplit.size()-1 && sameCount < relativeSplit.size()-1 &&
  1148. fileSplit[sameCount] == relativeSplit[sameCount])
  1149. {
  1150. sameCount++;
  1151. }
  1152. if(sameCount == 0)
  1153. {
  1154. return std::string(remote);
  1155. }
  1156. // put in sameCount number of ../ into the path
  1157. unsigned int i;
  1158. for(i = sameCount; i < fileSplit.size(); ++i)
  1159. {
  1160. relativePath += "../";
  1161. }
  1162. // now put the rest of path that did not match back
  1163. for(i = sameCount; i < relativeSplit.size()-1; ++i)
  1164. {
  1165. relativePath += relativeSplit[i] + "/";
  1166. }
  1167. relativePath += relativeSplit[i];
  1168. return relativePath;
  1169. }
  1170. class cmDeletingCharVector : public std::vector<char*>
  1171. {
  1172. public:
  1173. ~cmDeletingCharVector()
  1174. {
  1175. for(std::vector<char*>::iterator i = this->begin();
  1176. i != this->end(); ++i)
  1177. {
  1178. delete []*i;
  1179. }
  1180. }
  1181. };
  1182. bool cmSystemTools::PutEnv(const char* value)
  1183. {
  1184. static cmDeletingCharVector localEnvironment;
  1185. char* envVar = new char[strlen(value)+1];
  1186. strcpy(envVar, value);
  1187. int ret = putenv(envVar);
  1188. // save the pointer in the static vector so that it can
  1189. // be deleted on exit
  1190. localEnvironment.push_back(envVar);
  1191. return ret == 0;
  1192. }
  1193. bool cmSystemTools::GetPermissions(const char* file, mode_t& mode)
  1194. {
  1195. if ( !file )
  1196. {
  1197. return false;
  1198. }
  1199. struct stat st;
  1200. if ( stat(file, &st) < 0 )
  1201. {
  1202. return false;
  1203. }
  1204. mode = st.st_mode;
  1205. return true;
  1206. }
  1207. bool cmSystemTools::SetPermissions(const char* file, mode_t mode)
  1208. {
  1209. if ( !file )
  1210. {
  1211. return false;
  1212. }
  1213. if ( !cmSystemTools::FileExists(file) )
  1214. {
  1215. return false;
  1216. }
  1217. if ( chmod(file, mode) < 0 )
  1218. {
  1219. return false;
  1220. }
  1221. return true;
  1222. }