cmSystemTools.cxx 33 KB

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