cmSystemTools.cxx 34 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360
  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] != '/' && command[2] == ':' && command[3] == '\\' ||
  323. command[0] == '\\' && command[1] == '\\')
  324. {
  325. win_path = true;
  326. }
  327. // Split the command into an argv array.
  328. for(const char* c = command; *c;)
  329. {
  330. // Skip over whitespace.
  331. while(*c == ' ' || *c == '\t')
  332. {
  333. ++c;
  334. }
  335. arg = "";
  336. if(*c == '"')
  337. {
  338. // Parse a quoted argument.
  339. ++c;
  340. while(*c && *c != '"')
  341. {
  342. arg.append(1, *c);
  343. ++c;
  344. }
  345. if(*c)
  346. {
  347. ++c;
  348. }
  349. args.push_back(arg);
  350. }
  351. else if(*c == '\'')
  352. {
  353. // Parse a quoted argument.
  354. ++c;
  355. while(*c && *c != '\'')
  356. {
  357. arg.append(1, *c);
  358. ++c;
  359. }
  360. if(*c)
  361. {
  362. ++c;
  363. }
  364. args.push_back(arg);
  365. }
  366. else if(*c)
  367. {
  368. // Parse an unquoted argument.
  369. while(*c && *c != ' ' && *c != '\t')
  370. {
  371. if(*c == '\\' && !win_path)
  372. {
  373. ++c;
  374. if(*c)
  375. {
  376. arg.append(1, *c);
  377. ++c;
  378. }
  379. }
  380. else
  381. {
  382. arg.append(1, *c);
  383. ++c;
  384. }
  385. }
  386. args.push_back(arg);
  387. }
  388. }
  389. return args;
  390. }
  391. bool cmSystemTools::RunSingleCommand(
  392. const char* command,
  393. std::string* output,
  394. int *retVal,
  395. const char* dir,
  396. bool verbose,
  397. double timeout)
  398. {
  399. if(s_DisableRunCommandOutput)
  400. {
  401. verbose = false;
  402. }
  403. std::vector<cmStdString> args = cmSystemTools::ParseArguments(command);
  404. if(args.size() < 1)
  405. {
  406. return false;
  407. }
  408. std::vector<const char*> argv;
  409. for(std::vector<cmStdString>::const_iterator a = args.begin();
  410. a != args.end(); ++a)
  411. {
  412. argv.push_back(a->c_str());
  413. }
  414. argv.push_back(0);
  415. if ( output )
  416. {
  417. *output = "";
  418. }
  419. cmsysProcess* cp = cmsysProcess_New();
  420. cmsysProcess_SetCommand(cp, &*argv.begin());
  421. cmsysProcess_SetWorkingDirectory(cp, dir);
  422. if(cmSystemTools::GetRunCommandHideConsole())
  423. {
  424. cmsysProcess_SetOption(cp, cmsysProcess_Option_HideWindow, 1);
  425. }
  426. cmsysProcess_SetTimeout(cp, timeout);
  427. cmsysProcess_Execute(cp);
  428. std::vector<char> tempOutput;
  429. char* data;
  430. int length;
  431. if ( output || verbose )
  432. {
  433. while(cmsysProcess_WaitForData(cp, &data, &length, 0))
  434. {
  435. if ( output )
  436. {
  437. tempOutput.insert(tempOutput.end(), data, data+length);
  438. }
  439. if(verbose)
  440. {
  441. cmSystemTools::Stdout(data, length);
  442. }
  443. }
  444. }
  445. cmsysProcess_WaitForExit(cp, 0);
  446. if ( output )
  447. {
  448. output->append(&*tempOutput.begin(), tempOutput.size());
  449. }
  450. bool result = true;
  451. if(cmsysProcess_GetState(cp) == cmsysProcess_State_Exited)
  452. {
  453. if ( retVal )
  454. {
  455. *retVal = cmsysProcess_GetExitValue(cp);
  456. }
  457. else
  458. {
  459. if ( cmsysProcess_GetExitValue(cp) != 0 )
  460. {
  461. result = false;
  462. }
  463. }
  464. }
  465. else if(cmsysProcess_GetState(cp) == cmsysProcess_State_Exception)
  466. {
  467. const char* exception_str = cmsysProcess_GetExceptionString(cp);
  468. if ( verbose )
  469. {
  470. std::cerr << exception_str << std::endl;
  471. }
  472. if ( output )
  473. {
  474. output->append(exception_str, strlen(exception_str));
  475. }
  476. result = false;
  477. }
  478. else if(cmsysProcess_GetState(cp) == cmsysProcess_State_Error)
  479. {
  480. const char* error_str = cmsysProcess_GetErrorString(cp);
  481. if ( verbose )
  482. {
  483. std::cerr << error_str << std::endl;
  484. }
  485. if ( output )
  486. {
  487. output->append(error_str, strlen(error_str));
  488. }
  489. result = false;
  490. }
  491. else if(cmsysProcess_GetState(cp) == cmsysProcess_State_Expired)
  492. {
  493. const char* error_str = "Process terminated due to timeout\n";
  494. if ( verbose )
  495. {
  496. std::cerr << error_str << std::endl;
  497. }
  498. if ( output )
  499. {
  500. output->append(error_str, strlen(error_str));
  501. }
  502. result = false;
  503. }
  504. cmsysProcess_Delete(cp);
  505. return result;
  506. }
  507. bool cmSystemTools::RunCommand(const char* command,
  508. std::string& output,
  509. const char* dir,
  510. bool verbose,
  511. int timeout)
  512. {
  513. int dummy;
  514. return cmSystemTools::RunCommand(command, output, dummy,
  515. dir, verbose, timeout);
  516. }
  517. #if defined(WIN32) && !defined(__CYGWIN__)
  518. #include "cmWin32ProcessExecution.h"
  519. // use this for shell commands like echo and dir
  520. bool RunCommandViaWin32(const char* command,
  521. const char* dir,
  522. std::string& output,
  523. int& retVal,
  524. bool verbose,
  525. int timeout)
  526. {
  527. #if defined(__BORLANDC__)
  528. return cmWin32ProcessExecution::BorlandRunCommand(command, dir, output,
  529. retVal,
  530. verbose, timeout,
  531. cmSystemTools::GetRunCommandHideConsole());
  532. #else // Visual studio
  533. ::SetLastError(ERROR_SUCCESS);
  534. if ( ! command )
  535. {
  536. cmSystemTools::Error("No command specified");
  537. return false;
  538. }
  539. cmWin32ProcessExecution resProc;
  540. if(cmSystemTools::GetRunCommandHideConsole())
  541. {
  542. resProc.SetHideWindows(true);
  543. }
  544. if ( cmSystemTools::GetWindows9xComspecSubstitute() )
  545. {
  546. resProc.SetConsoleSpawn(cmSystemTools::GetWindows9xComspecSubstitute() );
  547. }
  548. if ( !resProc.StartProcess(command, dir, verbose) )
  549. {
  550. output = resProc.GetOutput();
  551. if(verbose)
  552. {
  553. cmSystemTools::Stdout(output.c_str());
  554. }
  555. return false;
  556. }
  557. resProc.Wait(timeout);
  558. output = resProc.GetOutput();
  559. retVal = resProc.GetExitValue();
  560. return true;
  561. #endif
  562. }
  563. // use this for shell commands like echo and dir
  564. bool RunCommandViaSystem(const char* command,
  565. const char* dir,
  566. std::string& output,
  567. int& retVal,
  568. bool verbose)
  569. {
  570. std::cout << "@@ " << command << std::endl;
  571. std::string commandInDir;
  572. if(dir)
  573. {
  574. commandInDir = "cd ";
  575. commandInDir += cmSystemTools::ConvertToOutputPath(dir);
  576. commandInDir += " && ";
  577. commandInDir += command;
  578. }
  579. else
  580. {
  581. commandInDir = command;
  582. }
  583. command = commandInDir.c_str();
  584. std::string commandToFile = command;
  585. commandToFile += " > ";
  586. std::string tempFile;
  587. tempFile += _tempnam(0, "cmake");
  588. commandToFile += tempFile;
  589. retVal = system(commandToFile.c_str());
  590. std::ifstream fin(tempFile.c_str());
  591. if(!fin)
  592. {
  593. if(verbose)
  594. {
  595. std::string errormsg = "RunCommand produced no output: command: \"";
  596. errormsg += command;
  597. errormsg += "\"";
  598. errormsg += "\nOutput file: ";
  599. errormsg += tempFile;
  600. cmSystemTools::Error(errormsg.c_str());
  601. }
  602. fin.close();
  603. cmSystemTools::RemoveFile(tempFile.c_str());
  604. return false;
  605. }
  606. bool multiLine = false;
  607. std::string line;
  608. while(cmSystemTools::GetLineFromStream(fin, line))
  609. {
  610. output += line;
  611. if(multiLine)
  612. {
  613. output += "\n";
  614. }
  615. multiLine = true;
  616. }
  617. fin.close();
  618. cmSystemTools::RemoveFile(tempFile.c_str());
  619. return true;
  620. }
  621. #else // We have popen
  622. bool RunCommandViaPopen(const char* command,
  623. const char* dir,
  624. std::string& output,
  625. int& retVal,
  626. bool verbose,
  627. int /*timeout*/)
  628. {
  629. // if only popen worked on windows.....
  630. std::string commandInDir;
  631. if(dir)
  632. {
  633. commandInDir = "cd \"";
  634. commandInDir += dir;
  635. commandInDir += "\" && ";
  636. commandInDir += command;
  637. }
  638. else
  639. {
  640. commandInDir = command;
  641. }
  642. commandInDir += " 2>&1";
  643. command = commandInDir.c_str();
  644. const int BUFFER_SIZE = 4096;
  645. char buffer[BUFFER_SIZE];
  646. if(verbose)
  647. {
  648. cmSystemTools::Stdout("running ");
  649. cmSystemTools::Stdout(command);
  650. cmSystemTools::Stdout("\n");
  651. }
  652. fflush(stdout);
  653. fflush(stderr);
  654. FILE* cpipe = popen(command, "r");
  655. if(!cpipe)
  656. {
  657. return false;
  658. }
  659. fgets(buffer, BUFFER_SIZE, cpipe);
  660. while(!feof(cpipe))
  661. {
  662. if(verbose)
  663. {
  664. cmSystemTools::Stdout(buffer);
  665. }
  666. output += buffer;
  667. fgets(buffer, BUFFER_SIZE, cpipe);
  668. }
  669. retVal = pclose(cpipe);
  670. if (WIFEXITED(retVal))
  671. {
  672. retVal = WEXITSTATUS(retVal);
  673. return true;
  674. }
  675. if (WIFSIGNALED(retVal))
  676. {
  677. retVal = WTERMSIG(retVal);
  678. cmOStringStream error;
  679. error << "\nProcess terminated due to ";
  680. switch (retVal)
  681. {
  682. #ifdef SIGKILL
  683. case SIGKILL:
  684. error << "SIGKILL";
  685. break;
  686. #endif
  687. #ifdef SIGFPE
  688. case SIGFPE:
  689. error << "SIGFPE";
  690. break;
  691. #endif
  692. #ifdef SIGBUS
  693. case SIGBUS:
  694. error << "SIGBUS";
  695. break;
  696. #endif
  697. #ifdef SIGSEGV
  698. case SIGSEGV:
  699. error << "SIGSEGV";
  700. break;
  701. #endif
  702. default:
  703. error << "signal " << retVal;
  704. break;
  705. }
  706. output += error.str();
  707. }
  708. return false;
  709. }
  710. #endif // endif WIN32 not CYGWIN
  711. // run a command unix uses popen (easy)
  712. // windows uses system and ShortPath
  713. bool cmSystemTools::RunCommand(const char* command,
  714. std::string& output,
  715. int &retVal,
  716. const char* dir,
  717. bool verbose,
  718. int timeout)
  719. {
  720. if(s_DisableRunCommandOutput)
  721. {
  722. verbose = false;
  723. }
  724. #if defined(WIN32) && !defined(__CYGWIN__)
  725. // if the command does not start with a quote, then
  726. // try to find the program, and if the program can not be
  727. // found use system to run the command as it must be a built in
  728. // shell command like echo or dir
  729. int count = 0;
  730. if(command[0] == '\"')
  731. {
  732. // count the number of quotes
  733. for(const char* s = command; *s != 0; ++s)
  734. {
  735. if(*s == '\"')
  736. {
  737. count++;
  738. if(count > 2)
  739. {
  740. break;
  741. }
  742. }
  743. }
  744. // if there are more than two double quotes use
  745. // GetShortPathName, the cmd.exe program in windows which
  746. // is used by system fails to execute if there are more than
  747. // one set of quotes in the arguments
  748. if(count > 2)
  749. {
  750. cmsys::RegularExpression quoted("^\"([^\"]*)\"[ \t](.*)");
  751. if(quoted.find(command))
  752. {
  753. std::string shortCmd;
  754. std::string cmd = quoted.match(1);
  755. std::string args = quoted.match(2);
  756. if(! cmSystemTools::FileExists(cmd.c_str()) )
  757. {
  758. shortCmd = cmd;
  759. }
  760. else if(!cmSystemTools::GetShortPath(cmd.c_str(), shortCmd))
  761. {
  762. cmSystemTools::Error("GetShortPath failed for " , cmd.c_str());
  763. return false;
  764. }
  765. shortCmd += " ";
  766. shortCmd += args;
  767. //return RunCommandViaSystem(shortCmd.c_str(), dir,
  768. // output, retVal, verbose);
  769. //return WindowsRunCommand(shortCmd.c_str(), dir,
  770. //output, retVal, verbose);
  771. return RunCommandViaWin32(shortCmd.c_str(), dir,
  772. output, retVal, verbose, timeout);
  773. }
  774. else
  775. {
  776. cmSystemTools::Error("Could not parse command line with quotes ",
  777. command);
  778. }
  779. }
  780. }
  781. // if there is only one set of quotes or no quotes then just run the command
  782. //return RunCommandViaSystem(command, dir, output, retVal, verbose);
  783. //return WindowsRunCommand(command, dir, output, retVal, verbose);
  784. return ::RunCommandViaWin32(command, dir, output, retVal, verbose, timeout);
  785. #else
  786. return ::RunCommandViaPopen(command, dir, output, retVal, verbose, timeout);
  787. #endif
  788. }
  789. bool cmSystemTools::DoesFileExistWithExtensions(
  790. const char* name,
  791. const std::vector<std::string>& headerExts)
  792. {
  793. std::string hname;
  794. for( std::vector<std::string>::const_iterator ext = headerExts.begin();
  795. ext != headerExts.end(); ++ext )
  796. {
  797. hname = name;
  798. hname += ".";
  799. hname += *ext;
  800. if(cmSystemTools::FileExists(hname.c_str()))
  801. {
  802. return true;
  803. }
  804. }
  805. return false;
  806. }
  807. bool cmSystemTools::cmCopyFile(const char* source, const char* destination)
  808. {
  809. return Superclass::CopyFileAlways(source, destination);
  810. }
  811. bool cmSystemTools::CopyFileIfDifferent(const char* source,
  812. const char* destination)
  813. {
  814. return Superclass::CopyFileIfDifferent(source, destination);
  815. }
  816. void cmSystemTools::Glob(const char *directory, const char *regexp,
  817. std::vector<std::string>& files)
  818. {
  819. cmsys::Directory d;
  820. cmsys::RegularExpression reg(regexp);
  821. if (d.Load(directory))
  822. {
  823. size_t numf;
  824. unsigned int i;
  825. numf = d.GetNumberOfFiles();
  826. for (i = 0; i < numf; i++)
  827. {
  828. std::string fname = d.GetFile(i);
  829. if (reg.find(fname))
  830. {
  831. files.push_back(fname);
  832. }
  833. }
  834. }
  835. }
  836. void cmSystemTools::GlobDirs(const char *fullPath,
  837. std::vector<std::string>& files)
  838. {
  839. std::string path = fullPath;
  840. std::string::size_type pos = path.find("/*");
  841. if(pos == std::string::npos)
  842. {
  843. files.push_back(fullPath);
  844. return;
  845. }
  846. std::string startPath = path.substr(0, pos);
  847. std::string finishPath = path.substr(pos+2);
  848. cmsys::Directory d;
  849. if (d.Load(startPath.c_str()))
  850. {
  851. for (unsigned int i = 0; i < d.GetNumberOfFiles(); ++i)
  852. {
  853. if((std::string(d.GetFile(i)) != ".")
  854. && (std::string(d.GetFile(i)) != ".."))
  855. {
  856. std::string fname = startPath;
  857. fname +="/";
  858. fname += d.GetFile(i);
  859. if(cmSystemTools::FileIsDirectory(fname.c_str()))
  860. {
  861. fname += finishPath;
  862. cmSystemTools::GlobDirs(fname.c_str(), files);
  863. }
  864. }
  865. }
  866. }
  867. }
  868. void cmSystemTools::ExpandList(std::vector<std::string> const& arguments,
  869. std::vector<std::string>& newargs)
  870. {
  871. std::vector<std::string>::const_iterator i;
  872. for(i = arguments.begin();i != arguments.end(); ++i)
  873. {
  874. cmSystemTools::ExpandListArgument(*i, newargs);
  875. }
  876. }
  877. void cmSystemTools::ExpandListArgument(const std::string& arg,
  878. std::vector<std::string>& newargs)
  879. {
  880. std::string newarg;
  881. // If argument is empty, it is an empty list.
  882. if(arg.length() == 0)
  883. {
  884. return;
  885. }
  886. // if there are no ; in the name then just copy the current string
  887. if(arg.find(';') == std::string::npos)
  888. {
  889. newargs.push_back(arg);
  890. return;
  891. }
  892. // Break the string at non-escaped semicolons not nested in [].
  893. int squareNesting = 0;
  894. for(const char* c = arg.c_str(); *c; ++c)
  895. {
  896. switch(*c)
  897. {
  898. case '\\':
  899. {
  900. // We only want to allow escaping of semicolons. Other
  901. // escapes should not be processed here.
  902. ++c;
  903. if(*c == ';')
  904. {
  905. newarg += ';';
  906. }
  907. else
  908. {
  909. newarg += '\\';
  910. if(*c)
  911. {
  912. newarg += *c;
  913. }
  914. }
  915. } break;
  916. case '[':
  917. {
  918. ++squareNesting;
  919. newarg += '[';
  920. } break;
  921. case ']':
  922. {
  923. --squareNesting;
  924. newarg += ']';
  925. } break;
  926. case ';':
  927. {
  928. // Break the string here if we are not nested inside square
  929. // brackets.
  930. if(squareNesting == 0)
  931. {
  932. if(newarg.length())
  933. {
  934. // Add an argument if the string is not empty.
  935. newargs.push_back(newarg);
  936. newarg = "";
  937. }
  938. }
  939. else
  940. {
  941. newarg += ';';
  942. }
  943. } break;
  944. default:
  945. {
  946. // Just append this character.
  947. newarg += *c;
  948. } break;
  949. }
  950. }
  951. if(newarg.length())
  952. {
  953. // Add the last argument if the string is not empty.
  954. newargs.push_back(newarg);
  955. }
  956. }
  957. bool cmSystemTools::SimpleGlob(const cmStdString& glob,
  958. std::vector<cmStdString>& files,
  959. int type /* = 0 */)
  960. {
  961. files.clear();
  962. if ( glob[glob.size()-1] != '*' )
  963. {
  964. return false;
  965. }
  966. std::string path = cmSystemTools::GetFilenamePath(glob);
  967. std::string ppath = cmSystemTools::GetFilenameName(glob);
  968. ppath = ppath.substr(0, ppath.size()-1);
  969. if ( path.size() == 0 )
  970. {
  971. path = "/";
  972. }
  973. bool res = false;
  974. cmsys::Directory d;
  975. if (d.Load(path.c_str()))
  976. {
  977. for (unsigned int i = 0; i < d.GetNumberOfFiles(); ++i)
  978. {
  979. if((std::string(d.GetFile(i)) != ".")
  980. && (std::string(d.GetFile(i)) != ".."))
  981. {
  982. std::string fname = path;
  983. if ( path[path.size()-1] != '/' )
  984. {
  985. fname +="/";
  986. }
  987. fname += d.GetFile(i);
  988. std::string sfname = d.GetFile(i);
  989. if ( type > 0 && cmSystemTools::FileIsDirectory(fname.c_str()) )
  990. {
  991. continue;
  992. }
  993. if ( type < 0 && !cmSystemTools::FileIsDirectory(fname.c_str()) )
  994. {
  995. continue;
  996. }
  997. if ( sfname.size() >= ppath.size() &&
  998. sfname.substr(0, ppath.size()) ==
  999. ppath )
  1000. {
  1001. files.push_back(fname);
  1002. res = true;
  1003. }
  1004. }
  1005. }
  1006. }
  1007. return res;
  1008. }
  1009. cmSystemTools::FileFormat cmSystemTools::GetFileFormat(const char* cext)
  1010. {
  1011. if ( ! cext || *cext == 0 )
  1012. {
  1013. return cmSystemTools::NO_FILE_FORMAT;
  1014. }
  1015. //std::string ext = cmSystemTools::LowerCase(cext);
  1016. std::string ext = cext;
  1017. if ( ext == "c" || ext == ".c" ) { return cmSystemTools::C_FILE_FORMAT; }
  1018. if (
  1019. ext == "C" || ext == ".C" ||
  1020. ext == "M" || ext == ".M" ||
  1021. ext == "c++" || ext == ".c++" ||
  1022. ext == "cc" || ext == ".cc" ||
  1023. ext == "cpp" || ext == ".cpp" ||
  1024. ext == "cxx" || ext == ".cxx" ||
  1025. ext == "m" || ext == ".m" ||
  1026. ext == "mm" || ext == ".mm"
  1027. ) { return cmSystemTools::CXX_FILE_FORMAT; }
  1028. if (
  1029. ext == "f" || ext == ".f" ||
  1030. ext == "F" || ext == ".F" ||
  1031. ext == "f77" || ext == ".f77" ||
  1032. ext == "f90" || ext == ".f90" ||
  1033. ext == "for" || ext == ".for" ||
  1034. ext == "f95" || ext == ".f95"
  1035. ) { return cmSystemTools::FORTRAN_FILE_FORMAT; }
  1036. if ( ext == "java" || ext == ".java" ) { return cmSystemTools::JAVA_FILE_FORMAT; }
  1037. if (
  1038. ext == "H" || ext == ".H" ||
  1039. ext == "h" || ext == ".h" ||
  1040. ext == "h++" || ext == ".h++" ||
  1041. ext == "hm" || ext == ".hm" ||
  1042. ext == "hpp" || ext == ".hpp" ||
  1043. ext == "hxx" || ext == ".hxx" ||
  1044. ext == "in" || ext == ".in" ||
  1045. ext == "txx" || ext == ".txx"
  1046. ) { return cmSystemTools::HEADER_FILE_FORMAT; }
  1047. if ( ext == "rc" || ext == ".rc" ) { return cmSystemTools::RESOURCE_FILE_FORMAT; }
  1048. if ( ext == "def" || ext == ".def" ) { return cmSystemTools::DEFINITION_FILE_FORMAT; }
  1049. if ( ext == "lib" || ext == ".lib" ||
  1050. ext == "a" || ext == ".a") { return cmSystemTools::STATIC_LIBRARY_FILE_FORMAT; }
  1051. if ( ext == "o" || ext == ".o" ||
  1052. ext == "obj" || ext == ".obj") { return cmSystemTools::OBJECT_FILE_FORMAT; }
  1053. #ifdef __APPLE__
  1054. if ( ext == "dylib" || ext == ".dylib" )
  1055. { return cmSystemTools::SHARED_LIBRARY_FILE_FORMAT; }
  1056. if ( ext == "so" || ext == ".so" ||
  1057. ext == "bundle" || ext == ".bundle" )
  1058. { return cmSystemTools::MODULE_FILE_FORMAT; }
  1059. #else // __APPLE__
  1060. if ( ext == "so" || ext == ".so" ||
  1061. ext == "sl" || ext == ".sl" ||
  1062. ext == "dll" || ext == ".dll" )
  1063. { return cmSystemTools::SHARED_LIBRARY_FILE_FORMAT; }
  1064. #endif // __APPLE__
  1065. return cmSystemTools::UNKNOWN_FILE_FORMAT;
  1066. }
  1067. bool cmSystemTools::Split(const char* s, std::vector<cmStdString>& l)
  1068. {
  1069. std::vector<std::string> temp;
  1070. bool res = Superclass::Split(s, temp);
  1071. for(std::vector<std::string>::const_iterator i = temp.begin();
  1072. i != temp.end(); ++i)
  1073. {
  1074. l.push_back(*i);
  1075. }
  1076. return res;
  1077. }
  1078. std::string cmSystemTools::ConvertToOutputPath(const char* path)
  1079. {
  1080. #if defined(_WIN32) && !defined(__CYGWIN__)
  1081. if(s_ForceUnixPaths)
  1082. {
  1083. return cmSystemTools::ConvertToUnixOutputPath(path);
  1084. }
  1085. return cmSystemTools::ConvertToWindowsOutputPath(path);
  1086. #else
  1087. return cmSystemTools::ConvertToUnixOutputPath(path);
  1088. #endif
  1089. }
  1090. std::string cmSystemTools::ConvertToRunCommandPath(const char* path)
  1091. {
  1092. #if defined(_WIN32) && !defined(__CYGWIN__)
  1093. return cmSystemTools::ConvertToWindowsOutputPath(path);
  1094. #else
  1095. return cmSystemTools::ConvertToUnixOutputPath(path);
  1096. #endif
  1097. }
  1098. bool cmSystemTools::StringEndsWith(const char* str1, const char* str2)
  1099. {
  1100. if ( !str1 || !str2 || strlen(str1) < strlen(str2) )
  1101. {
  1102. return 0;
  1103. }
  1104. return !strncmp(str1 + (strlen(str1)-strlen(str2)), str2, strlen(str2));
  1105. }
  1106. #if defined(_WIN32) && !defined(__CYGWIN__)
  1107. bool cmSystemTools::CreateSymlink(const char*, const char*)
  1108. {
  1109. // Should we create a copy here?
  1110. return false;
  1111. }
  1112. #else
  1113. bool cmSystemTools::CreateSymlink(const char* origName, const char* newName)
  1114. {
  1115. return (symlink(origName, newName) >= 0);
  1116. }
  1117. #endif
  1118. std::vector<cmStdString> cmSystemTools::SplitString(const char* p, char sep, bool isPath)
  1119. {
  1120. std::string path = p;
  1121. std::vector<cmStdString> paths;
  1122. if(isPath && path[0] == '/')
  1123. {
  1124. path.erase(path.begin());
  1125. paths.push_back("/");
  1126. }
  1127. std::string::size_type pos1 = 0;
  1128. std::string::size_type pos2 = path.find(sep, pos1+1);
  1129. while(pos2 != std::string::npos)
  1130. {
  1131. paths.push_back(path.substr(pos1, pos2-pos1));
  1132. pos1 = pos2+1;
  1133. pos2 = path.find(sep, pos1+1);
  1134. }
  1135. paths.push_back(path.substr(pos1, pos2-pos1));
  1136. return paths;
  1137. }
  1138. // compute the relative path from here to there
  1139. std::string cmSystemTools::RelativePath(const char* local, const char* remote)
  1140. {
  1141. if(!cmSystemTools::FileIsFullPath(local))
  1142. {
  1143. cmSystemTools::Error("RelativePath must be passed a full path to local: ", local);
  1144. }
  1145. if(!cmSystemTools::FileIsFullPath(remote))
  1146. {
  1147. cmSystemTools::Error("RelativePath must be passed a full path to remote: ", remote);
  1148. }
  1149. // split up both paths into arrays of strings using / as a separator
  1150. std::vector<cmStdString> localSplit = cmSystemTools::SplitString(local, '/', true);
  1151. std::vector<cmStdString> remoteSplit = cmSystemTools::SplitString(remote, '/', true);
  1152. std::vector<cmStdString> commonPath; // store shared parts of path in this array
  1153. std::vector<cmStdString> finalPath; // store the final relative path here
  1154. // count up how many matching directory names there are from the start
  1155. unsigned int sameCount = 0;
  1156. while(
  1157. ((sameCount <= (localSplit.size()-1)) && (sameCount <= (remoteSplit.size()-1)))
  1158. &&
  1159. // for windows and apple do a case insensitive string compare
  1160. #if defined(_WIN32) || defined(__APPLE__)
  1161. cmSystemTools::Strucmp(localSplit[sameCount].c_str(),
  1162. remoteSplit[sameCount].c_str()) == 0
  1163. #else
  1164. localSplit[sameCount] == remoteSplit[sameCount]
  1165. #endif
  1166. )
  1167. {
  1168. // put the common parts of the path into the commonPath array
  1169. commonPath.push_back(localSplit[sameCount]);
  1170. // erase the common parts of the path from the original path arrays
  1171. localSplit[sameCount] = "";
  1172. remoteSplit[sameCount] = "";
  1173. sameCount++;
  1174. }
  1175. // If there is nothing in common but the root directory, then just
  1176. // return the full path.
  1177. if(sameCount <= 1)
  1178. {
  1179. return remote;
  1180. }
  1181. // for each entry that is not common in the local path
  1182. // add a ../ to the finalpath array, this gets us out of the local
  1183. // path into the remote dir
  1184. for(unsigned int i = 0; i < localSplit.size(); ++i)
  1185. {
  1186. if(localSplit[i].size())
  1187. {
  1188. finalPath.push_back("../");
  1189. }
  1190. }
  1191. // for each entry that is not common in the remote path add it
  1192. // to the final path.
  1193. for(std::vector<cmStdString>::iterator i = remoteSplit.begin();
  1194. i != remoteSplit.end(); ++i)
  1195. {
  1196. if(i->size())
  1197. {
  1198. finalPath.push_back(*i);
  1199. }
  1200. }
  1201. std::string relativePath; // result string
  1202. // now turn the array of directories into a unix path by puttint /
  1203. // between each entry that does not already have one
  1204. for(std::vector<cmStdString>::iterator i = finalPath.begin();
  1205. i != finalPath.end(); ++i)
  1206. {
  1207. if(relativePath.size() && relativePath[relativePath.size()-1] != '/')
  1208. {
  1209. relativePath += "/";
  1210. }
  1211. relativePath += *i;
  1212. }
  1213. return relativePath;
  1214. }
  1215. class cmDeletingCharVector : public std::vector<char*>
  1216. {
  1217. public:
  1218. ~cmDeletingCharVector()
  1219. {
  1220. for(std::vector<char*>::iterator i = this->begin();
  1221. i != this->end(); ++i)
  1222. {
  1223. delete []*i;
  1224. }
  1225. }
  1226. };
  1227. bool cmSystemTools::PutEnv(const char* value)
  1228. {
  1229. static cmDeletingCharVector localEnvironment;
  1230. char* envVar = new char[strlen(value)+1];
  1231. strcpy(envVar, value);
  1232. int ret = putenv(envVar);
  1233. // save the pointer in the static vector so that it can
  1234. // be deleted on exit
  1235. localEnvironment.push_back(envVar);
  1236. return ret == 0;
  1237. }
  1238. bool cmSystemTools::FileTimeCompare(const char* f1, const char* f2,
  1239. int* result)
  1240. {
  1241. struct stat stat1, stat2;
  1242. if(stat(f1, &stat1) == 0 && stat(f2, &stat2) == 0)
  1243. {
  1244. *result = 0;
  1245. if(stat1.st_mtime < stat2.st_mtime)
  1246. {
  1247. *result = -1;
  1248. }
  1249. else if(stat1.st_mtime > stat2.st_mtime)
  1250. {
  1251. *result = 1;
  1252. }
  1253. #if 0
  1254. // TODO: Support resolution higher than one second.
  1255. // Use st_mtim.tv_nsec if available and GetFileTime on Windows.
  1256. else if(stat1.st_mtim.tv_nsec < stat2.st_mtim.tv_nsec)
  1257. {
  1258. *result = 1;
  1259. }
  1260. #endif
  1261. return true;
  1262. }
  1263. else
  1264. {
  1265. return false;
  1266. }
  1267. }