cmSystemTools.cxx 31 KB

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