cmSystemTools.cxx 30 KB

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