cmSystemTools.cxx 31 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256
  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. std::cerr << cmsysProcess_GetExceptionString(cp) << "\n";
  434. result = false;
  435. }
  436. else if(cmsysProcess_GetState(cp) == cmsysProcess_State_Error)
  437. {
  438. std::cerr << cmsysProcess_GetErrorString(cp) << "\n";
  439. result = false;
  440. }
  441. else if(cmsysProcess_GetState(cp) == cmsysProcess_State_Expired)
  442. {
  443. std::cerr << "Process terminated due to timeout\n";
  444. result = false;
  445. }
  446. cmsysProcess_Delete(cp);
  447. return result;
  448. }
  449. bool cmSystemTools::RunCommand(const char* command,
  450. std::string& output,
  451. const char* dir,
  452. bool verbose,
  453. int timeout)
  454. {
  455. int dummy;
  456. return cmSystemTools::RunCommand(command, output, dummy,
  457. dir, verbose, timeout);
  458. }
  459. #if defined(WIN32) && !defined(__CYGWIN__)
  460. #include "cmWin32ProcessExecution.h"
  461. // use this for shell commands like echo and dir
  462. bool RunCommandViaWin32(const char* command,
  463. const char* dir,
  464. std::string& output,
  465. int& retVal,
  466. bool verbose,
  467. int timeout)
  468. {
  469. #if defined(__BORLANDC__)
  470. return cmWin32ProcessExecution::BorlandRunCommand(command, dir, output,
  471. retVal,
  472. verbose, timeout,
  473. cmSystemTools::GetRunCommandHideConsole());
  474. #else // Visual studio
  475. ::SetLastError(ERROR_SUCCESS);
  476. if ( ! command )
  477. {
  478. cmSystemTools::Error("No command specified");
  479. return false;
  480. }
  481. cmWin32ProcessExecution resProc;
  482. if(cmSystemTools::GetRunCommandHideConsole())
  483. {
  484. resProc.SetHideWindows(true);
  485. }
  486. if ( cmSystemTools::GetWindows9xComspecSubstitute() )
  487. {
  488. resProc.SetConsoleSpawn(cmSystemTools::GetWindows9xComspecSubstitute() );
  489. }
  490. if ( !resProc.StartProcess(command, dir, verbose) )
  491. {
  492. return false;
  493. }
  494. resProc.Wait(timeout);
  495. output = resProc.GetOutput();
  496. retVal = resProc.GetExitValue();
  497. return true;
  498. #endif
  499. }
  500. // use this for shell commands like echo and dir
  501. bool RunCommandViaSystem(const char* command,
  502. const char* dir,
  503. std::string& output,
  504. int& retVal,
  505. bool verbose)
  506. {
  507. std::cout << "@@ " << command << std::endl;
  508. std::string commandInDir;
  509. if(dir)
  510. {
  511. commandInDir = "cd ";
  512. commandInDir += cmSystemTools::ConvertToOutputPath(dir);
  513. commandInDir += " && ";
  514. commandInDir += command;
  515. }
  516. else
  517. {
  518. commandInDir = command;
  519. }
  520. command = commandInDir.c_str();
  521. std::string commandToFile = command;
  522. commandToFile += " > ";
  523. std::string tempFile;
  524. tempFile += _tempnam(0, "cmake");
  525. commandToFile += tempFile;
  526. retVal = system(commandToFile.c_str());
  527. std::ifstream fin(tempFile.c_str());
  528. if(!fin)
  529. {
  530. if(verbose)
  531. {
  532. std::string errormsg = "RunCommand produced no output: command: \"";
  533. errormsg += command;
  534. errormsg += "\"";
  535. errormsg += "\nOutput file: ";
  536. errormsg += tempFile;
  537. cmSystemTools::Error(errormsg.c_str());
  538. }
  539. fin.close();
  540. cmSystemTools::RemoveFile(tempFile.c_str());
  541. return false;
  542. }
  543. bool multiLine = false;
  544. std::string line;
  545. while(cmSystemTools::GetLineFromStream(fin, line))
  546. {
  547. output += line;
  548. if(multiLine)
  549. {
  550. output += "\n";
  551. }
  552. multiLine = true;
  553. }
  554. fin.close();
  555. cmSystemTools::RemoveFile(tempFile.c_str());
  556. return true;
  557. }
  558. #else // We have popen
  559. bool RunCommandViaPopen(const char* command,
  560. const char* dir,
  561. std::string& output,
  562. int& retVal,
  563. bool verbose,
  564. int /*timeout*/)
  565. {
  566. // if only popen worked on windows.....
  567. std::string commandInDir;
  568. if(dir)
  569. {
  570. commandInDir = "cd \"";
  571. commandInDir += dir;
  572. commandInDir += "\" && ";
  573. commandInDir += command;
  574. }
  575. else
  576. {
  577. commandInDir = command;
  578. }
  579. commandInDir += " 2>&1";
  580. command = commandInDir.c_str();
  581. const int BUFFER_SIZE = 4096;
  582. char buffer[BUFFER_SIZE];
  583. if(verbose)
  584. {
  585. cmSystemTools::Stdout("running ");
  586. cmSystemTools::Stdout(command);
  587. cmSystemTools::Stdout("\n");
  588. }
  589. fflush(stdout);
  590. fflush(stderr);
  591. FILE* cpipe = popen(command, "r");
  592. if(!cpipe)
  593. {
  594. return false;
  595. }
  596. fgets(buffer, BUFFER_SIZE, cpipe);
  597. while(!feof(cpipe))
  598. {
  599. if(verbose)
  600. {
  601. cmSystemTools::Stdout(buffer);
  602. }
  603. output += buffer;
  604. fgets(buffer, BUFFER_SIZE, cpipe);
  605. }
  606. retVal = pclose(cpipe);
  607. if (WIFEXITED(retVal))
  608. {
  609. retVal = WEXITSTATUS(retVal);
  610. return true;
  611. }
  612. if (WIFSIGNALED(retVal))
  613. {
  614. retVal = WTERMSIG(retVal);
  615. cmOStringStream error;
  616. error << "\nProcess terminated due to ";
  617. switch (retVal)
  618. {
  619. #ifdef SIGKILL
  620. case SIGKILL:
  621. error << "SIGKILL";
  622. break;
  623. #endif
  624. #ifdef SIGFPE
  625. case SIGFPE:
  626. error << "SIGFPE";
  627. break;
  628. #endif
  629. #ifdef SIGBUS
  630. case SIGBUS:
  631. error << "SIGBUS";
  632. break;
  633. #endif
  634. #ifdef SIGSEGV
  635. case SIGSEGV:
  636. error << "SIGSEGV";
  637. break;
  638. #endif
  639. default:
  640. error << "signal " << retVal;
  641. break;
  642. }
  643. output += error.str();
  644. }
  645. return false;
  646. }
  647. #endif // endif WIN32 not CYGWIN
  648. // run a command unix uses popen (easy)
  649. // windows uses system and ShortPath
  650. bool cmSystemTools::RunCommand(const char* command,
  651. std::string& output,
  652. int &retVal,
  653. const char* dir,
  654. bool verbose,
  655. int timeout)
  656. {
  657. if(s_DisableRunCommandOutput)
  658. {
  659. verbose = false;
  660. }
  661. #if defined(WIN32) && !defined(__CYGWIN__)
  662. // if the command does not start with a quote, then
  663. // try to find the program, and if the program can not be
  664. // found use system to run the command as it must be a built in
  665. // shell command like echo or dir
  666. int count = 0;
  667. if(command[0] == '\"')
  668. {
  669. // count the number of quotes
  670. for(const char* s = command; *s != 0; ++s)
  671. {
  672. if(*s == '\"')
  673. {
  674. count++;
  675. if(count > 2)
  676. {
  677. break;
  678. }
  679. }
  680. }
  681. // if there are more than two double quotes use
  682. // GetShortPathName, the cmd.exe program in windows which
  683. // is used by system fails to execute if there are more than
  684. // one set of quotes in the arguments
  685. if(count > 2)
  686. {
  687. cmsys::RegularExpression quoted("^\"([^\"]*)\"[ \t](.*)");
  688. if(quoted.find(command))
  689. {
  690. std::string shortCmd;
  691. std::string cmd = quoted.match(1);
  692. std::string args = quoted.match(2);
  693. if(! cmSystemTools::FileExists(cmd.c_str()) )
  694. {
  695. shortCmd = cmd;
  696. }
  697. else if(!cmSystemTools::GetShortPath(cmd.c_str(), shortCmd))
  698. {
  699. cmSystemTools::Error("GetShortPath failed for " , cmd.c_str());
  700. return false;
  701. }
  702. shortCmd += " ";
  703. shortCmd += args;
  704. //return RunCommandViaSystem(shortCmd.c_str(), dir,
  705. // output, retVal, verbose);
  706. //return WindowsRunCommand(shortCmd.c_str(), dir,
  707. //output, retVal, verbose);
  708. return RunCommandViaWin32(shortCmd.c_str(), dir,
  709. output, retVal, verbose, timeout);
  710. }
  711. else
  712. {
  713. cmSystemTools::Error("Could not parse command line with quotes ",
  714. command);
  715. }
  716. }
  717. }
  718. // if there is only one set of quotes or no quotes then just run the command
  719. //return RunCommandViaSystem(command, dir, output, retVal, verbose);
  720. //return WindowsRunCommand(command, dir, output, retVal, verbose);
  721. return ::RunCommandViaWin32(command, dir, output, retVal, verbose, timeout);
  722. #else
  723. return ::RunCommandViaPopen(command, dir, output, retVal, verbose, timeout);
  724. #endif
  725. }
  726. bool cmSystemTools::DoesFileExistWithExtensions(
  727. const char* name,
  728. const std::vector<std::string>& headerExts)
  729. {
  730. std::string hname;
  731. for( std::vector<std::string>::const_iterator ext = headerExts.begin();
  732. ext != headerExts.end(); ++ext )
  733. {
  734. hname = name;
  735. hname += ".";
  736. hname += *ext;
  737. if(cmSystemTools::FileExists(hname.c_str()))
  738. {
  739. return true;
  740. }
  741. }
  742. return false;
  743. }
  744. bool cmSystemTools::cmCopyFile(const char* source, const char* destination)
  745. {
  746. mode_t perm = 0;
  747. return cmSystemTools::GetPermissions(source, perm) &&
  748. Superclass::CopyFileAlways(source, destination) &&
  749. cmSystemTools::SetPermissions(destination, perm);
  750. }
  751. bool cmSystemTools::CopyFileIfDifferent(const char* source,
  752. const char* destination)
  753. {
  754. mode_t perm = 0;
  755. return cmSystemTools::GetPermissions(source, perm) &&
  756. Superclass::CopyFileIfDifferent(source, destination) &&
  757. cmSystemTools::SetPermissions(destination, perm);
  758. }
  759. void cmSystemTools::Glob(const char *directory, const char *regexp,
  760. std::vector<std::string>& files)
  761. {
  762. cmsys::Directory d;
  763. cmsys::RegularExpression reg(regexp);
  764. if (d.Load(directory))
  765. {
  766. size_t numf;
  767. unsigned int i;
  768. numf = d.GetNumberOfFiles();
  769. for (i = 0; i < numf; i++)
  770. {
  771. std::string fname = d.GetFile(i);
  772. if (reg.find(fname))
  773. {
  774. files.push_back(fname);
  775. }
  776. }
  777. }
  778. }
  779. void cmSystemTools::GlobDirs(const char *fullPath,
  780. std::vector<std::string>& files)
  781. {
  782. std::string path = fullPath;
  783. std::string::size_type pos = path.find("/*");
  784. if(pos == std::string::npos)
  785. {
  786. files.push_back(fullPath);
  787. return;
  788. }
  789. std::string startPath = path.substr(0, pos);
  790. std::string finishPath = path.substr(pos+2);
  791. cmsys::Directory d;
  792. if (d.Load(startPath.c_str()))
  793. {
  794. for (unsigned int i = 0; i < d.GetNumberOfFiles(); ++i)
  795. {
  796. if((std::string(d.GetFile(i)) != ".")
  797. && (std::string(d.GetFile(i)) != ".."))
  798. {
  799. std::string fname = startPath;
  800. fname +="/";
  801. fname += d.GetFile(i);
  802. if(cmSystemTools::FileIsDirectory(fname.c_str()))
  803. {
  804. fname += finishPath;
  805. cmSystemTools::GlobDirs(fname.c_str(), files);
  806. }
  807. }
  808. }
  809. }
  810. }
  811. void cmSystemTools::ExpandList(std::vector<std::string> const& arguments,
  812. std::vector<std::string>& newargs)
  813. {
  814. std::vector<std::string>::const_iterator i;
  815. for(i = arguments.begin();i != arguments.end(); ++i)
  816. {
  817. cmSystemTools::ExpandListArgument(*i, newargs);
  818. }
  819. }
  820. void cmSystemTools::ExpandListArgument(const std::string& arg,
  821. std::vector<std::string>& newargs)
  822. {
  823. std::string newarg;
  824. // If argument is empty, it is an empty list.
  825. if(arg.length() == 0)
  826. {
  827. return;
  828. }
  829. // if there are no ; in the name then just copy the current string
  830. if(arg.find(';') == std::string::npos)
  831. {
  832. newargs.push_back(arg);
  833. return;
  834. }
  835. // Break the string at non-escaped semicolons not nested in [].
  836. int squareNesting = 0;
  837. for(const char* c = arg.c_str(); *c; ++c)
  838. {
  839. switch(*c)
  840. {
  841. case '\\':
  842. {
  843. // We only want to allow escaping of semicolons. Other
  844. // escapes should not be processed here.
  845. ++c;
  846. if(*c == ';')
  847. {
  848. newarg += ';';
  849. }
  850. else
  851. {
  852. newarg += '\\';
  853. if(*c)
  854. {
  855. newarg += *c;
  856. }
  857. }
  858. } break;
  859. case '[':
  860. {
  861. ++squareNesting;
  862. newarg += '[';
  863. } break;
  864. case ']':
  865. {
  866. --squareNesting;
  867. newarg += ']';
  868. } break;
  869. case ';':
  870. {
  871. // Break the string here if we are not nested inside square
  872. // brackets.
  873. if(squareNesting == 0)
  874. {
  875. if(newarg.length())
  876. {
  877. // Add an argument if the string is not empty.
  878. newargs.push_back(newarg);
  879. newarg = "";
  880. }
  881. }
  882. else
  883. {
  884. newarg += ';';
  885. }
  886. } break;
  887. default:
  888. {
  889. // Just append this character.
  890. newarg += *c;
  891. } break;
  892. }
  893. }
  894. if(newarg.length())
  895. {
  896. // Add the last argument if the string is not empty.
  897. newargs.push_back(newarg);
  898. }
  899. }
  900. bool cmSystemTools::SimpleGlob(const cmStdString& glob,
  901. std::vector<cmStdString>& files,
  902. int type /* = 0 */)
  903. {
  904. files.clear();
  905. if ( glob[glob.size()-1] != '*' )
  906. {
  907. return false;
  908. }
  909. std::string path = cmSystemTools::GetFilenamePath(glob);
  910. std::string ppath = cmSystemTools::GetFilenameName(glob);
  911. ppath = ppath.substr(0, ppath.size()-1);
  912. if ( path.size() == 0 )
  913. {
  914. path = "/";
  915. }
  916. bool res = false;
  917. cmsys::Directory d;
  918. if (d.Load(path.c_str()))
  919. {
  920. for (unsigned int i = 0; i < d.GetNumberOfFiles(); ++i)
  921. {
  922. if((std::string(d.GetFile(i)) != ".")
  923. && (std::string(d.GetFile(i)) != ".."))
  924. {
  925. std::string fname = path;
  926. if ( path[path.size()-1] != '/' )
  927. {
  928. fname +="/";
  929. }
  930. fname += d.GetFile(i);
  931. std::string sfname = d.GetFile(i);
  932. if ( type > 0 && cmSystemTools::FileIsDirectory(fname.c_str()) )
  933. {
  934. continue;
  935. }
  936. if ( type < 0 && !cmSystemTools::FileIsDirectory(fname.c_str()) )
  937. {
  938. continue;
  939. }
  940. if ( sfname.size() >= ppath.size() &&
  941. sfname.substr(0, ppath.size()) ==
  942. ppath )
  943. {
  944. files.push_back(fname);
  945. res = true;
  946. }
  947. }
  948. }
  949. }
  950. return res;
  951. }
  952. cmSystemTools::FileFormat cmSystemTools::GetFileFormat(const char* cext)
  953. {
  954. if ( ! cext || *cext == 0 )
  955. {
  956. return cmSystemTools::NO_FILE_FORMAT;
  957. }
  958. //std::string ext = cmSystemTools::LowerCase(cext);
  959. std::string ext = cext;
  960. if ( ext == "c" || ext == ".c" ) { return cmSystemTools::C_FILE_FORMAT; }
  961. if (
  962. ext == "C" || ext == ".C" ||
  963. ext == "M" || ext == ".M" ||
  964. ext == "c++" || ext == ".c++" ||
  965. ext == "cc" || ext == ".cc" ||
  966. ext == "cpp" || ext == ".cpp" ||
  967. ext == "cxx" || ext == ".cxx" ||
  968. ext == "m" || ext == ".m" ||
  969. ext == "mm" || ext == ".mm"
  970. ) { return cmSystemTools::CXX_FILE_FORMAT; }
  971. if ( ext == "java" || ext == ".java" ) { return cmSystemTools::JAVA_FILE_FORMAT; }
  972. if (
  973. ext == "H" || ext == ".H" ||
  974. ext == "h" || ext == ".h" ||
  975. ext == "h++" || ext == ".h++" ||
  976. ext == "hm" || ext == ".hm" ||
  977. ext == "hpp" || ext == ".hpp" ||
  978. ext == "hxx" || ext == ".hxx" ||
  979. ext == "in" || ext == ".in" ||
  980. ext == "txx" || ext == ".txx"
  981. ) { return cmSystemTools::HEADER_FILE_FORMAT; }
  982. if ( ext == "rc" || ext == ".rc" ) { return cmSystemTools::RESOURCE_FILE_FORMAT; }
  983. if ( ext == "def" || ext == ".def" ) { return cmSystemTools::DEFINITION_FILE_FORMAT; }
  984. if ( ext == "lib" || ext == ".lib" ||
  985. ext == "a" || ext == ".a") { return cmSystemTools::STATIC_LIBRARY_FILE_FORMAT; }
  986. if ( ext == "o" || ext == ".o" ||
  987. ext == "obj" || ext == ".obj") { return cmSystemTools::OBJECT_FILE_FORMAT; }
  988. #ifdef __APPLE__
  989. if ( ext == "dylib" || ext == ".dylib" )
  990. { return cmSystemTools::SHARED_LIBRARY_FILE_FORMAT; }
  991. if ( ext == "so" || ext == ".so" ||
  992. ext == "bundle" || ext == ".bundle" )
  993. { return cmSystemTools::MODULE_FILE_FORMAT; }
  994. #else // __APPLE__
  995. if ( ext == "so" || ext == ".so" ||
  996. ext == "sl" || ext == ".sl" ||
  997. ext == "dll" || ext == ".dll" )
  998. { return cmSystemTools::SHARED_LIBRARY_FILE_FORMAT; }
  999. #endif // __APPLE__
  1000. return cmSystemTools::UNKNOWN_FILE_FORMAT;
  1001. }
  1002. bool cmSystemTools::Split(const char* s, std::vector<cmStdString>& l)
  1003. {
  1004. std::vector<std::string> temp;
  1005. if(!Superclass::Split(s, temp))
  1006. {
  1007. return false;
  1008. }
  1009. for(std::vector<std::string>::const_iterator i = temp.begin();
  1010. i != temp.end(); ++i)
  1011. {
  1012. l.push_back(*i);
  1013. }
  1014. return true;
  1015. }
  1016. std::string cmSystemTools::ConvertToOutputPath(const char* path)
  1017. {
  1018. #if defined(_WIN32) && !defined(__CYGWIN__)
  1019. if(s_ForceUnixPaths)
  1020. {
  1021. return cmSystemTools::ConvertToUnixOutputPath(path);
  1022. }
  1023. return cmSystemTools::ConvertToWindowsOutputPath(path);
  1024. #else
  1025. return cmSystemTools::ConvertToUnixOutputPath(path);
  1026. #endif
  1027. }
  1028. bool cmSystemTools::StringEndsWith(const char* str1, const char* str2)
  1029. {
  1030. if ( !str1 || !str2 || strlen(str1) < strlen(str2) )
  1031. {
  1032. return 0;
  1033. }
  1034. return !strncmp(str1 + (strlen(str1)-strlen(str2)), str2, strlen(str2));
  1035. }
  1036. #if defined(_WIN32) && !defined(__CYGWIN__)
  1037. bool cmSystemTools::CreateSymlink(const char*, const char*)
  1038. {
  1039. // Should we create a copy here?
  1040. return false;
  1041. }
  1042. #else
  1043. bool cmSystemTools::CreateSymlink(const char* origName, const char* newName)
  1044. {
  1045. return (symlink(origName, newName) >= 0);
  1046. }
  1047. #endif
  1048. std::vector<cmStdString> cmSystemTools::SplitString(const char* p, char sep)
  1049. {
  1050. std::string path = p;
  1051. std::vector<cmStdString> paths;
  1052. std::string::size_type pos1 = 0;
  1053. std::string::size_type pos2 = path.find(sep, pos1+1);
  1054. while(pos2 != std::string::npos)
  1055. {
  1056. paths.push_back(path.substr(pos1, pos2-pos1));
  1057. pos1 = pos2+1;
  1058. pos2 = path.find(sep, pos1+1);
  1059. }
  1060. paths.push_back(path.substr(pos1, pos2-pos1));
  1061. return paths;
  1062. }
  1063. // compute the relative path from here to there
  1064. std::string cmSystemTools::RelativePath(const char* local, const char* remote)
  1065. {
  1066. #ifdef _WIN32
  1067. std::string lowerCaseLocal = cmSystemTools::LowerCase(std::string(local));
  1068. std::string lowerCaseRemote = cmSystemTools::LowerCase(std::string(remote));
  1069. remote = lowerCaseRemote.c_str();
  1070. local = lowerCaseLocal.c_str();
  1071. #endif
  1072. // check for driveletter: as the start of the path
  1073. // if not on the same drive then full path to remote must be used.
  1074. if(local[0] && local[0] != '/')
  1075. {
  1076. if(remote[0] && local[0] != remote[0])
  1077. {
  1078. return remote;
  1079. }
  1080. }
  1081. std::string relativePath; // result string
  1082. // split up both paths into arrays of strings using / as a separator
  1083. std::vector<cmStdString> fileSplit = cmSystemTools::SplitString(local);
  1084. std::vector<cmStdString> relativeSplit = cmSystemTools::SplitString(remote);
  1085. // count up how many mathing directory names there are from the start
  1086. unsigned int sameCount = 0;
  1087. while(sameCount < fileSplit.size()-1 && sameCount < relativeSplit.size()-1 &&
  1088. fileSplit[sameCount] == relativeSplit[sameCount])
  1089. {
  1090. sameCount++;
  1091. }
  1092. if(sameCount == 0)
  1093. {
  1094. return std::string(remote);
  1095. }
  1096. // put in sameCount number of ../ into the path
  1097. unsigned int i;
  1098. for(i = sameCount; i < fileSplit.size(); ++i)
  1099. {
  1100. relativePath += "../";
  1101. }
  1102. // now put the rest of path that did not match back
  1103. for(i = sameCount; i < relativeSplit.size()-1; ++i)
  1104. {
  1105. relativePath += relativeSplit[i] + "/";
  1106. }
  1107. relativePath += relativeSplit[i];
  1108. return relativePath;
  1109. }
  1110. class cmDeletingCharVector : public std::vector<char*>
  1111. {
  1112. public:
  1113. ~cmDeletingCharVector()
  1114. {
  1115. for(std::vector<char*>::iterator i = this->begin();
  1116. i != this->end(); ++i)
  1117. {
  1118. delete []*i;
  1119. }
  1120. }
  1121. };
  1122. bool cmSystemTools::PutEnv(const char* value)
  1123. {
  1124. static cmDeletingCharVector localEnvironment;
  1125. char* envVar = new char[strlen(value)+1];
  1126. strcpy(envVar, value);
  1127. int ret = putenv(envVar);
  1128. // save the pointer in the static vector so that it can
  1129. // be deleted on exit
  1130. localEnvironment.push_back(envVar);
  1131. return ret == 0;
  1132. }
  1133. bool cmSystemTools::GetPermissions(const char* file, mode_t& mode)
  1134. {
  1135. if ( !file )
  1136. {
  1137. return false;
  1138. }
  1139. struct stat st;
  1140. if ( stat(file, &st) < 0 )
  1141. {
  1142. return false;
  1143. }
  1144. mode = st.st_mode;
  1145. return true;
  1146. }
  1147. bool cmSystemTools::SetPermissions(const char* file, mode_t mode)
  1148. {
  1149. if ( !file )
  1150. {
  1151. return false;
  1152. }
  1153. if ( !cmSystemTools::FileExists(file) )
  1154. {
  1155. return false;
  1156. }
  1157. if ( chmod(file, mode) < 0 )
  1158. {
  1159. return false;
  1160. }
  1161. return true;
  1162. }