cmSystemTools.cxx 32 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310
  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. int 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 ( ext == "java" || ext == ".java" ) { return cmSystemTools::JAVA_FILE_FORMAT; }
  1019. if (
  1020. ext == "H" || ext == ".H" ||
  1021. ext == "h" || ext == ".h" ||
  1022. ext == "h++" || ext == ".h++" ||
  1023. ext == "hm" || ext == ".hm" ||
  1024. ext == "hpp" || ext == ".hpp" ||
  1025. ext == "hxx" || ext == ".hxx" ||
  1026. ext == "in" || ext == ".in" ||
  1027. ext == "txx" || ext == ".txx"
  1028. ) { return cmSystemTools::HEADER_FILE_FORMAT; }
  1029. if ( ext == "rc" || ext == ".rc" ) { return cmSystemTools::RESOURCE_FILE_FORMAT; }
  1030. if ( ext == "def" || ext == ".def" ) { return cmSystemTools::DEFINITION_FILE_FORMAT; }
  1031. if ( ext == "lib" || ext == ".lib" ||
  1032. ext == "a" || ext == ".a") { return cmSystemTools::STATIC_LIBRARY_FILE_FORMAT; }
  1033. if ( ext == "o" || ext == ".o" ||
  1034. ext == "obj" || ext == ".obj") { return cmSystemTools::OBJECT_FILE_FORMAT; }
  1035. #ifdef __APPLE__
  1036. if ( ext == "dylib" || ext == ".dylib" )
  1037. { return cmSystemTools::SHARED_LIBRARY_FILE_FORMAT; }
  1038. if ( ext == "so" || ext == ".so" ||
  1039. ext == "bundle" || ext == ".bundle" )
  1040. { return cmSystemTools::MODULE_FILE_FORMAT; }
  1041. #else // __APPLE__
  1042. if ( ext == "so" || ext == ".so" ||
  1043. ext == "sl" || ext == ".sl" ||
  1044. ext == "dll" || ext == ".dll" )
  1045. { return cmSystemTools::SHARED_LIBRARY_FILE_FORMAT; }
  1046. #endif // __APPLE__
  1047. return cmSystemTools::UNKNOWN_FILE_FORMAT;
  1048. }
  1049. bool cmSystemTools::Split(const char* s, std::vector<cmStdString>& l)
  1050. {
  1051. std::vector<std::string> temp;
  1052. bool res = Superclass::Split(s, temp);
  1053. for(std::vector<std::string>::const_iterator i = temp.begin();
  1054. i != temp.end(); ++i)
  1055. {
  1056. l.push_back(*i);
  1057. }
  1058. return res;
  1059. }
  1060. std::string cmSystemTools::ConvertToOutputPath(const char* path)
  1061. {
  1062. #if defined(_WIN32) && !defined(__CYGWIN__)
  1063. if(s_ForceUnixPaths)
  1064. {
  1065. return cmSystemTools::ConvertToUnixOutputPath(path);
  1066. }
  1067. return cmSystemTools::ConvertToWindowsOutputPath(path);
  1068. #else
  1069. return cmSystemTools::ConvertToUnixOutputPath(path);
  1070. #endif
  1071. }
  1072. std::string cmSystemTools::ConvertToRunCommandPath(const char* path)
  1073. {
  1074. #if defined(_WIN32) && !defined(__CYGWIN__)
  1075. return cmSystemTools::ConvertToWindowsOutputPath(path);
  1076. #else
  1077. return cmSystemTools::ConvertToUnixOutputPath(path);
  1078. #endif
  1079. }
  1080. bool cmSystemTools::StringEndsWith(const char* str1, const char* str2)
  1081. {
  1082. if ( !str1 || !str2 || strlen(str1) < strlen(str2) )
  1083. {
  1084. return 0;
  1085. }
  1086. return !strncmp(str1 + (strlen(str1)-strlen(str2)), str2, strlen(str2));
  1087. }
  1088. #if defined(_WIN32) && !defined(__CYGWIN__)
  1089. bool cmSystemTools::CreateSymlink(const char*, const char*)
  1090. {
  1091. // Should we create a copy here?
  1092. return false;
  1093. }
  1094. #else
  1095. bool cmSystemTools::CreateSymlink(const char* origName, const char* newName)
  1096. {
  1097. return (symlink(origName, newName) >= 0);
  1098. }
  1099. #endif
  1100. std::vector<cmStdString> cmSystemTools::SplitString(const char* p, char sep)
  1101. {
  1102. std::string path = p;
  1103. std::vector<cmStdString> paths;
  1104. std::string::size_type pos1 = 0;
  1105. std::string::size_type pos2 = path.find(sep, pos1+1);
  1106. while(pos2 != std::string::npos)
  1107. {
  1108. paths.push_back(path.substr(pos1, pos2-pos1));
  1109. pos1 = pos2+1;
  1110. pos2 = path.find(sep, pos1+1);
  1111. }
  1112. paths.push_back(path.substr(pos1, pos2-pos1));
  1113. return paths;
  1114. }
  1115. // compute the relative path from here to there
  1116. std::string cmSystemTools::RelativePath(const char* local, const char* remote)
  1117. {
  1118. #ifdef _WIN32
  1119. std::string lowerCaseLocal = cmSystemTools::LowerCase(std::string(local));
  1120. std::string lowerCaseRemote = cmSystemTools::LowerCase(std::string(remote));
  1121. remote = lowerCaseRemote.c_str();
  1122. local = lowerCaseLocal.c_str();
  1123. #endif
  1124. // check for driveletter: as the start of the path
  1125. // if not on the same drive then full path to remote must be used.
  1126. if(local[0] && local[0] != '/')
  1127. {
  1128. if(remote[0] && local[0] != remote[0])
  1129. {
  1130. return remote;
  1131. }
  1132. }
  1133. std::string relativePath; // result string
  1134. // split up both paths into arrays of strings using / as a separator
  1135. std::vector<cmStdString> fileSplit = cmSystemTools::SplitString(local);
  1136. std::vector<cmStdString> relativeSplit = cmSystemTools::SplitString(remote);
  1137. // count up how many mathing directory names there are from the start
  1138. unsigned int sameCount = 0;
  1139. while(sameCount < fileSplit.size()-1 && sameCount < relativeSplit.size()-1 &&
  1140. fileSplit[sameCount] == relativeSplit[sameCount])
  1141. {
  1142. sameCount++;
  1143. }
  1144. if(sameCount == 0)
  1145. {
  1146. return std::string(remote);
  1147. }
  1148. // put in sameCount number of ../ into the path
  1149. unsigned int i;
  1150. for(i = sameCount; i < fileSplit.size(); ++i)
  1151. {
  1152. relativePath += "../";
  1153. }
  1154. // now put the rest of path that did not match back
  1155. for(i = sameCount; i < relativeSplit.size()-1; ++i)
  1156. {
  1157. relativePath += relativeSplit[i] + "/";
  1158. }
  1159. relativePath += relativeSplit[i];
  1160. return relativePath;
  1161. }
  1162. class cmDeletingCharVector : public std::vector<char*>
  1163. {
  1164. public:
  1165. ~cmDeletingCharVector()
  1166. {
  1167. for(std::vector<char*>::iterator i = this->begin();
  1168. i != this->end(); ++i)
  1169. {
  1170. delete []*i;
  1171. }
  1172. }
  1173. };
  1174. bool cmSystemTools::PutEnv(const char* value)
  1175. {
  1176. static cmDeletingCharVector localEnvironment;
  1177. char* envVar = new char[strlen(value)+1];
  1178. strcpy(envVar, value);
  1179. int ret = putenv(envVar);
  1180. // save the pointer in the static vector so that it can
  1181. // be deleted on exit
  1182. localEnvironment.push_back(envVar);
  1183. return ret == 0;
  1184. }
  1185. bool cmSystemTools::GetPermissions(const char* file, mode_t& mode)
  1186. {
  1187. if ( !file )
  1188. {
  1189. return false;
  1190. }
  1191. struct stat st;
  1192. if ( stat(file, &st) < 0 )
  1193. {
  1194. return false;
  1195. }
  1196. mode = st.st_mode;
  1197. return true;
  1198. }
  1199. bool cmSystemTools::SetPermissions(const char* file, mode_t mode)
  1200. {
  1201. if ( !file )
  1202. {
  1203. return false;
  1204. }
  1205. if ( !cmSystemTools::FileExists(file) )
  1206. {
  1207. return false;
  1208. }
  1209. if ( chmod(file, mode) < 0 )
  1210. {
  1211. return false;
  1212. }
  1213. return true;
  1214. }