cmSystemTools.cxx 47 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910
  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/System.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. #if defined(CMAKE_BUILD_WITH_CMAKE)
  40. # include <libtar/libtar.h>
  41. # include <memory> // auto_ptr
  42. # include <fcntl.h>
  43. # include <cm_zlib.h>
  44. #endif
  45. #if defined(__sgi) && !defined(__GNUC__)
  46. # pragma set woff 1375 /* base class destructor not virtual */
  47. #endif
  48. #if !defined(HAVE_ENVIRON_NOT_REQUIRE_PROTOTYPE)
  49. // For GetEnvironmentVariables
  50. # if defined(_WIN32)
  51. extern __declspec( dllimport ) char** environ;
  52. # else
  53. extern char** environ;
  54. # endif
  55. #endif
  56. bool cmSystemTools::s_RunCommandHideConsole = false;
  57. bool cmSystemTools::s_DisableRunCommandOutput = false;
  58. bool cmSystemTools::s_ErrorOccured = false;
  59. bool cmSystemTools::s_FatalErrorOccured = false;
  60. bool cmSystemTools::s_DisableMessages = false;
  61. bool cmSystemTools::s_ForceUnixPaths = false;
  62. std::string cmSystemTools::s_Windows9xComspecSubstitute = "command.com";
  63. void cmSystemTools::SetWindows9xComspecSubstitute(const char* str)
  64. {
  65. if ( str )
  66. {
  67. cmSystemTools::s_Windows9xComspecSubstitute = str;
  68. }
  69. }
  70. const char* cmSystemTools::GetWindows9xComspecSubstitute()
  71. {
  72. return cmSystemTools::s_Windows9xComspecSubstitute.c_str();
  73. }
  74. void (*cmSystemTools::s_ErrorCallback)(const char*, const char*,
  75. bool&, void*);
  76. void (*cmSystemTools::s_StdoutCallback)(const char*, int len, void*);
  77. void* cmSystemTools::s_ErrorCallbackClientData = 0;
  78. void* cmSystemTools::s_StdoutCallbackClientData = 0;
  79. // replace replace with with as many times as it shows up in source.
  80. // write the result into source.
  81. #if defined(_WIN32) && !defined(__CYGWIN__)
  82. void cmSystemTools::ExpandRegistryValues(std::string& source)
  83. {
  84. // Regular expression to match anything inside [...] that begins in HKEY.
  85. // Note that there is a special rule for regular expressions to match a
  86. // close square-bracket inside a list delimited by square brackets.
  87. // The "[^]]" part of this expression will match any character except
  88. // a close square-bracket. The ']' character must be the first in the
  89. // list of characters inside the [^...] block of the expression.
  90. cmsys::RegularExpression regEntry("\\[(HKEY[^]]*)\\]");
  91. // check for black line or comment
  92. while (regEntry.find(source))
  93. {
  94. // the arguments are the second match
  95. std::string key = regEntry.match(1);
  96. std::string val;
  97. if (ReadRegistryValue(key.c_str(), val))
  98. {
  99. std::string reg = "[";
  100. reg += key + "]";
  101. cmSystemTools::ReplaceString(source, reg.c_str(), val.c_str());
  102. }
  103. else
  104. {
  105. std::string reg = "[";
  106. reg += key + "]";
  107. cmSystemTools::ReplaceString(source, reg.c_str(), "/registry");
  108. }
  109. }
  110. }
  111. #else
  112. void cmSystemTools::ExpandRegistryValues(std::string&)
  113. {
  114. }
  115. #endif
  116. std::string cmSystemTools::EscapeQuotes(const char* str)
  117. {
  118. std::string result = "";
  119. for(const char* ch = str; *ch != '\0'; ++ch)
  120. {
  121. if(*ch == '"')
  122. {
  123. result += '\\';
  124. }
  125. result += *ch;
  126. }
  127. return result;
  128. }
  129. std::string cmSystemTools::EscapeSpaces(const char* str)
  130. {
  131. #if defined(_WIN32) && !defined(__CYGWIN__)
  132. bool useDoubleQ = true;
  133. #else
  134. bool useDoubleQ = false;
  135. #endif
  136. if(cmSystemTools::s_ForceUnixPaths)
  137. {
  138. useDoubleQ = false;
  139. }
  140. if(useDoubleQ)
  141. {
  142. std::string result;
  143. // if there are spaces
  144. std::string temp = str;
  145. if (temp.find(" ") != std::string::npos &&
  146. temp.find("\"")==std::string::npos)
  147. {
  148. result = "\"";
  149. result += str;
  150. result += "\"";
  151. return result;
  152. }
  153. return str;
  154. }
  155. else
  156. {
  157. std::string result = "";
  158. for(const char* ch = str; *ch != '\0'; ++ch)
  159. {
  160. if(*ch == ' ')
  161. {
  162. result += '\\';
  163. }
  164. result += *ch;
  165. }
  166. return result;
  167. }
  168. }
  169. std::string cmSystemTools::RemoveEscapes(const char* s)
  170. {
  171. std::string result = "";
  172. for(const char* ch = s; *ch; ++ch)
  173. {
  174. if(*ch == '\\' && *(ch+1) != ';')
  175. {
  176. ++ch;
  177. switch (*ch)
  178. {
  179. case '\\': result.insert(result.end(), '\\'); break;
  180. case '"': result.insert(result.end(), '"'); break;
  181. case ' ': result.insert(result.end(), ' '); break;
  182. case 't': result.insert(result.end(), '\t'); break;
  183. case 'n': result.insert(result.end(), '\n'); break;
  184. case 'r': result.insert(result.end(), '\r'); break;
  185. case '#': result.insert(result.end(), '#'); break;
  186. case '(': result.insert(result.end(), '('); break;
  187. case ')': result.insert(result.end(), ')'); break;
  188. case '0': result.insert(result.end(), '\0'); break;
  189. case '\0':
  190. {
  191. cmSystemTools::Error("Trailing backslash in argument:\n", s);
  192. return result;
  193. }
  194. default:
  195. {
  196. std::string chStr(1, *ch);
  197. cmSystemTools::Error("Invalid escape sequence \\", chStr.c_str(),
  198. "\nin argument ", s);
  199. }
  200. }
  201. }
  202. else
  203. {
  204. result.insert(result.end(), *ch);
  205. }
  206. }
  207. return result;
  208. }
  209. void cmSystemTools::Error(const char* m1, const char* m2,
  210. const char* m3, const char* m4)
  211. {
  212. std::string message = "CMake Error: ";
  213. if(m1)
  214. {
  215. message += m1;
  216. }
  217. if(m2)
  218. {
  219. message += m2;
  220. }
  221. if(m3)
  222. {
  223. message += m3;
  224. }
  225. if(m4)
  226. {
  227. message += m4;
  228. }
  229. cmSystemTools::s_ErrorOccured = true;
  230. cmSystemTools::Message(message.c_str(),"Error");
  231. }
  232. void cmSystemTools::SetErrorCallback(ErrorCallback f, void* clientData)
  233. {
  234. s_ErrorCallback = f;
  235. s_ErrorCallbackClientData = clientData;
  236. }
  237. void cmSystemTools::SetStdoutCallback(StdoutCallback f, void* clientData)
  238. {
  239. s_StdoutCallback = f;
  240. s_StdoutCallbackClientData = clientData;
  241. }
  242. void cmSystemTools::Stdout(const char* s)
  243. {
  244. if(s_StdoutCallback)
  245. {
  246. (*s_StdoutCallback)(s, strlen(s), s_StdoutCallbackClientData);
  247. }
  248. else
  249. {
  250. std::cout << s;
  251. std::cout.flush();
  252. }
  253. }
  254. void cmSystemTools::Stdout(const char* s, int length)
  255. {
  256. if(s_StdoutCallback)
  257. {
  258. (*s_StdoutCallback)(s, length, s_StdoutCallbackClientData);
  259. }
  260. else
  261. {
  262. std::cout.write(s, length);
  263. std::cout.flush();
  264. }
  265. }
  266. void cmSystemTools::Message(const char* m1, const char *title)
  267. {
  268. if(s_DisableMessages)
  269. {
  270. return;
  271. }
  272. if(s_ErrorCallback)
  273. {
  274. (*s_ErrorCallback)(m1, title, s_DisableMessages,
  275. s_ErrorCallbackClientData);
  276. return;
  277. }
  278. else
  279. {
  280. std::cerr << m1 << std::endl << std::flush;
  281. }
  282. }
  283. void cmSystemTools::ReportLastSystemError(const char* msg)
  284. {
  285. std::string m = msg;
  286. m += ": System Error: ";
  287. m += Superclass::GetLastSystemError();
  288. cmSystemTools::Error(m.c_str());
  289. }
  290. bool cmSystemTools::IsOn(const char* val)
  291. {
  292. if (!val)
  293. {
  294. return false;
  295. }
  296. std::basic_string<char> v = val;
  297. for(std::basic_string<char>::iterator c = v.begin();
  298. c != v.end(); c++)
  299. {
  300. *c = toupper(*c);
  301. }
  302. return (v == "ON" || v == "1" || v == "YES" || v == "TRUE" || v == "Y");
  303. }
  304. bool cmSystemTools::IsNOTFOUND(const char* val)
  305. {
  306. int len = strlen(val);
  307. const char* notfound = "-NOTFOUND";
  308. const int lenNotFound = 9;
  309. if(len < lenNotFound-1)
  310. {
  311. return false;
  312. }
  313. if(len == lenNotFound-1)
  314. {
  315. return ( strcmp(val, "NOTFOUND") == 0);
  316. }
  317. return ((strncmp((val + (len - lenNotFound)), notfound, lenNotFound) == 0));
  318. }
  319. bool cmSystemTools::IsOff(const char* val)
  320. {
  321. if (!val || strlen(val) == 0)
  322. {
  323. return true;
  324. }
  325. std::basic_string<char> v = val;
  326. for(std::basic_string<char>::iterator c = v.begin();
  327. c != v.end(); c++)
  328. {
  329. *c = toupper(*c);
  330. }
  331. return (v == "OFF" || v == "0" || v == "NO" || v == "FALSE" ||
  332. v == "N" || cmSystemTools::IsNOTFOUND(v.c_str()) || v == "IGNORE");
  333. }
  334. //----------------------------------------------------------------------------
  335. void cmSystemTools::ParseWindowsCommandLine(const char* command,
  336. std::vector<std::string>& args)
  337. {
  338. // See the MSDN document "Parsing C Command-Line Arguments" at
  339. // http://msdn2.microsoft.com/en-us/library/a1y7w461.aspx for rules
  340. // of parsing the windows command line.
  341. bool in_argument = false;
  342. bool in_quotes = false;
  343. int backslashes = 0;
  344. std::string arg;
  345. for(const char* c = command;*c; ++c)
  346. {
  347. if(*c == '\\')
  348. {
  349. ++backslashes;
  350. in_argument = true;
  351. }
  352. else if(*c == '"')
  353. {
  354. int backslash_pairs = backslashes >> 1;
  355. int backslash_escaped = backslashes & 1;
  356. arg.append(backslash_pairs, '\\');
  357. backslashes = 0;
  358. if(backslash_escaped)
  359. {
  360. /* An odd number of backslashes precede this quote.
  361. It is escaped. */
  362. arg.append(1, '"');
  363. }
  364. else
  365. {
  366. /* An even number of backslashes precede this quote.
  367. It is not escaped. */
  368. in_quotes = !in_quotes;
  369. }
  370. in_argument = true;
  371. }
  372. else
  373. {
  374. arg.append(backslashes, '\\');
  375. backslashes = 0;
  376. if(isspace(*c))
  377. {
  378. if(in_quotes)
  379. {
  380. arg.append(1, *c);
  381. }
  382. else if(in_argument)
  383. {
  384. args.push_back(arg);
  385. arg = "";
  386. in_argument = false;
  387. }
  388. }
  389. else
  390. {
  391. in_argument = true;
  392. arg.append(1, *c);
  393. }
  394. }
  395. }
  396. arg.append(backslashes, '\\');
  397. if(in_argument)
  398. {
  399. args.push_back(arg);
  400. }
  401. }
  402. std::string cmSystemTools::EscapeWindowsShellArgument(const char* arg,
  403. int shell_flags)
  404. {
  405. char local_buffer[1024];
  406. char* buffer = local_buffer;
  407. int size = cmsysSystem_Shell_GetArgumentSizeForWindows(arg, shell_flags);
  408. if(size > 1024)
  409. {
  410. buffer = new char[size];
  411. }
  412. cmsysSystem_Shell_GetArgumentForWindows(arg, buffer, shell_flags);
  413. std::string result(buffer);
  414. if(buffer != local_buffer)
  415. {
  416. delete [] buffer;
  417. }
  418. return result;
  419. }
  420. std::vector<cmStdString> cmSystemTools::ParseArguments(const char* command)
  421. {
  422. std::vector<cmStdString> args;
  423. std::string arg;
  424. bool win_path = false;
  425. if ( command[0] != '/' && command[1] == ':' && command[2] == '\\' ||
  426. command[0] == '\"' && command[1] != '/' && command[2] == ':'
  427. && command[3] == '\\' ||
  428. command[0] == '\'' && command[1] != '/' && command[2] == ':'
  429. && command[3] == '\\' ||
  430. command[0] == '\\' && command[1] == '\\')
  431. {
  432. win_path = true;
  433. }
  434. // Split the command into an argv array.
  435. for(const char* c = command; *c;)
  436. {
  437. // Skip over whitespace.
  438. while(*c == ' ' || *c == '\t')
  439. {
  440. ++c;
  441. }
  442. arg = "";
  443. if(*c == '"')
  444. {
  445. // Parse a quoted argument.
  446. ++c;
  447. while(*c && *c != '"')
  448. {
  449. arg.append(1, *c);
  450. ++c;
  451. }
  452. if(*c)
  453. {
  454. ++c;
  455. }
  456. args.push_back(arg);
  457. }
  458. else if(*c == '\'')
  459. {
  460. // Parse a quoted argument.
  461. ++c;
  462. while(*c && *c != '\'')
  463. {
  464. arg.append(1, *c);
  465. ++c;
  466. }
  467. if(*c)
  468. {
  469. ++c;
  470. }
  471. args.push_back(arg);
  472. }
  473. else if(*c)
  474. {
  475. // Parse an unquoted argument.
  476. while(*c && *c != ' ' && *c != '\t')
  477. {
  478. if(*c == '\\' && !win_path)
  479. {
  480. ++c;
  481. if(*c)
  482. {
  483. arg.append(1, *c);
  484. ++c;
  485. }
  486. }
  487. else
  488. {
  489. arg.append(1, *c);
  490. ++c;
  491. }
  492. }
  493. args.push_back(arg);
  494. }
  495. }
  496. return args;
  497. }
  498. bool cmSystemTools::RunSingleCommand(
  499. const char* command,
  500. std::string* output,
  501. int *retVal,
  502. const char* dir,
  503. bool verbose,
  504. double timeout)
  505. {
  506. if(s_DisableRunCommandOutput)
  507. {
  508. verbose = false;
  509. }
  510. std::vector<cmStdString> args = cmSystemTools::ParseArguments(command);
  511. if(args.size() < 1)
  512. {
  513. return false;
  514. }
  515. std::vector<const char*> argv;
  516. for(std::vector<cmStdString>::const_iterator a = args.begin();
  517. a != args.end(); ++a)
  518. {
  519. argv.push_back(a->c_str());
  520. }
  521. argv.push_back(0);
  522. if ( output )
  523. {
  524. *output = "";
  525. }
  526. cmsysProcess* cp = cmsysProcess_New();
  527. cmsysProcess_SetCommand(cp, &*argv.begin());
  528. cmsysProcess_SetWorkingDirectory(cp, dir);
  529. if(cmSystemTools::GetRunCommandHideConsole())
  530. {
  531. cmsysProcess_SetOption(cp, cmsysProcess_Option_HideWindow, 1);
  532. }
  533. cmsysProcess_SetTimeout(cp, timeout);
  534. cmsysProcess_Execute(cp);
  535. std::vector<char> tempOutput;
  536. char* data;
  537. int length;
  538. if ( output || verbose )
  539. {
  540. while(cmsysProcess_WaitForData(cp, &data, &length, 0))
  541. {
  542. if(output || verbose)
  543. {
  544. // Translate NULL characters in the output into valid text.
  545. // Visual Studio 7 puts these characters in the output of its
  546. // build process.
  547. for(int i=0; i < length; ++i)
  548. {
  549. if(data[i] == '\0')
  550. {
  551. data[i] = ' ';
  552. }
  553. }
  554. }
  555. if ( output )
  556. {
  557. tempOutput.insert(tempOutput.end(), data, data+length);
  558. }
  559. if(verbose)
  560. {
  561. cmSystemTools::Stdout(data, length);
  562. }
  563. }
  564. }
  565. cmsysProcess_WaitForExit(cp, 0);
  566. if ( output && tempOutput.begin() != tempOutput.end())
  567. {
  568. output->append(&*tempOutput.begin(), tempOutput.size());
  569. }
  570. bool result = true;
  571. if(cmsysProcess_GetState(cp) == cmsysProcess_State_Exited)
  572. {
  573. if ( retVal )
  574. {
  575. *retVal = cmsysProcess_GetExitValue(cp);
  576. }
  577. else
  578. {
  579. if ( cmsysProcess_GetExitValue(cp) != 0 )
  580. {
  581. result = false;
  582. }
  583. }
  584. }
  585. else if(cmsysProcess_GetState(cp) == cmsysProcess_State_Exception)
  586. {
  587. const char* exception_str = cmsysProcess_GetExceptionString(cp);
  588. if ( verbose )
  589. {
  590. std::cerr << exception_str << std::endl;
  591. }
  592. if ( output )
  593. {
  594. output->append(exception_str, strlen(exception_str));
  595. }
  596. result = false;
  597. }
  598. else if(cmsysProcess_GetState(cp) == cmsysProcess_State_Error)
  599. {
  600. const char* error_str = cmsysProcess_GetErrorString(cp);
  601. if ( verbose )
  602. {
  603. std::cerr << error_str << std::endl;
  604. }
  605. if ( output )
  606. {
  607. output->append(error_str, strlen(error_str));
  608. }
  609. result = false;
  610. }
  611. else if(cmsysProcess_GetState(cp) == cmsysProcess_State_Expired)
  612. {
  613. const char* error_str = "Process terminated due to timeout\n";
  614. if ( verbose )
  615. {
  616. std::cerr << error_str << std::endl;
  617. }
  618. if ( output )
  619. {
  620. output->append(error_str, strlen(error_str));
  621. }
  622. result = false;
  623. }
  624. cmsysProcess_Delete(cp);
  625. return result;
  626. }
  627. bool cmSystemTools::RunCommand(const char* command,
  628. std::string& output,
  629. const char* dir,
  630. bool verbose,
  631. int timeout)
  632. {
  633. int dummy;
  634. return cmSystemTools::RunCommand(command, output, dummy,
  635. dir, verbose, timeout);
  636. }
  637. #if defined(WIN32) && !defined(__CYGWIN__)
  638. #include "cmWin32ProcessExecution.h"
  639. // use this for shell commands like echo and dir
  640. bool RunCommandViaWin32(const char* command,
  641. const char* dir,
  642. std::string& output,
  643. int& retVal,
  644. bool verbose,
  645. int timeout)
  646. {
  647. #if defined(__BORLANDC__)
  648. return
  649. cmWin32ProcessExecution::
  650. BorlandRunCommand(command, dir, output,
  651. retVal,
  652. verbose, timeout,
  653. cmSystemTools::GetRunCommandHideConsole());
  654. #else // Visual studio
  655. ::SetLastError(ERROR_SUCCESS);
  656. if ( ! command )
  657. {
  658. cmSystemTools::Error("No command specified");
  659. return false;
  660. }
  661. cmWin32ProcessExecution resProc;
  662. if(cmSystemTools::GetRunCommandHideConsole())
  663. {
  664. resProc.SetHideWindows(true);
  665. }
  666. if ( cmSystemTools::GetWindows9xComspecSubstitute() )
  667. {
  668. resProc.SetConsoleSpawn(cmSystemTools::GetWindows9xComspecSubstitute() );
  669. }
  670. if ( !resProc.StartProcess(command, dir, verbose) )
  671. {
  672. output = resProc.GetOutput();
  673. if(verbose)
  674. {
  675. cmSystemTools::Stdout(output.c_str());
  676. }
  677. return false;
  678. }
  679. resProc.Wait(timeout);
  680. output = resProc.GetOutput();
  681. retVal = resProc.GetExitValue();
  682. return true;
  683. #endif
  684. }
  685. // use this for shell commands like echo and dir
  686. bool RunCommandViaSystem(const char* command,
  687. const char* dir,
  688. std::string& output,
  689. int& retVal,
  690. bool verbose)
  691. {
  692. std::cout << "@@ " << command << std::endl;
  693. std::string commandInDir;
  694. if(dir)
  695. {
  696. commandInDir = "cd ";
  697. commandInDir += cmSystemTools::ConvertToOutputPath(dir);
  698. commandInDir += " && ";
  699. commandInDir += command;
  700. }
  701. else
  702. {
  703. commandInDir = command;
  704. }
  705. command = commandInDir.c_str();
  706. std::string commandToFile = command;
  707. commandToFile += " > ";
  708. std::string tempFile;
  709. tempFile += _tempnam(0, "cmake");
  710. commandToFile += tempFile;
  711. retVal = system(commandToFile.c_str());
  712. std::ifstream fin(tempFile.c_str());
  713. if(!fin)
  714. {
  715. if(verbose)
  716. {
  717. std::string errormsg = "RunCommand produced no output: command: \"";
  718. errormsg += command;
  719. errormsg += "\"";
  720. errormsg += "\nOutput file: ";
  721. errormsg += tempFile;
  722. cmSystemTools::Error(errormsg.c_str());
  723. }
  724. fin.close();
  725. cmSystemTools::RemoveFile(tempFile.c_str());
  726. return false;
  727. }
  728. bool multiLine = false;
  729. std::string line;
  730. while(cmSystemTools::GetLineFromStream(fin, line))
  731. {
  732. output += line;
  733. if(multiLine)
  734. {
  735. output += "\n";
  736. }
  737. multiLine = true;
  738. }
  739. fin.close();
  740. cmSystemTools::RemoveFile(tempFile.c_str());
  741. return true;
  742. }
  743. #else // We have popen
  744. // BeOS seems to return from a successful pclose() before the process has
  745. // legitimately exited, or at least before SIGCHLD is thrown...the signal may
  746. // come quite some time after pclose returns! This causes havoc with later
  747. // parts of CMake that expect to catch the signal from other child processes,
  748. // so we explicitly wait to catch it here. This should be safe to do with
  749. // popen() so long as we don't actually collect the zombie process ourselves.
  750. #ifdef __BEOS__
  751. #include <signal.h>
  752. #undef SIGBUS // this is the same as SIGSEGV on BeOS and causes issues below.
  753. static volatile bool beos_seen_signal = false;
  754. static void beos_popen_workaround(int sig)
  755. {
  756. beos_seen_signal = true;
  757. }
  758. #endif
  759. bool RunCommandViaPopen(const char* command,
  760. const char* dir,
  761. std::string& output,
  762. int& retVal,
  763. bool verbose,
  764. int /*timeout*/)
  765. {
  766. // if only popen worked on windows.....
  767. std::string commandInDir;
  768. if(dir)
  769. {
  770. commandInDir = "cd \"";
  771. commandInDir += dir;
  772. commandInDir += "\" && ";
  773. commandInDir += command;
  774. }
  775. else
  776. {
  777. commandInDir = command;
  778. }
  779. commandInDir += " 2>&1";
  780. command = commandInDir.c_str();
  781. const int BUFFER_SIZE = 4096;
  782. char buffer[BUFFER_SIZE];
  783. if(verbose)
  784. {
  785. cmSystemTools::Stdout("running ");
  786. cmSystemTools::Stdout(command);
  787. cmSystemTools::Stdout("\n");
  788. }
  789. fflush(stdout);
  790. fflush(stderr);
  791. #ifdef __BEOS__
  792. beos_seen_signal = false;
  793. signal(SIGCHLD, beos_popen_workaround);
  794. #endif
  795. FILE* cpipe = popen(command, "r");
  796. if(!cpipe)
  797. {
  798. #ifdef __BEOS__
  799. signal(SIGCHLD, SIG_DFL);
  800. #endif
  801. return false;
  802. }
  803. fgets(buffer, BUFFER_SIZE, cpipe);
  804. while(!feof(cpipe))
  805. {
  806. if(verbose)
  807. {
  808. cmSystemTools::Stdout(buffer);
  809. }
  810. output += buffer;
  811. fgets(buffer, BUFFER_SIZE, cpipe);
  812. }
  813. retVal = pclose(cpipe);
  814. #ifdef __BEOS__
  815. for (int i = 0; (!beos_seen_signal) && (i < 3); i++)
  816. {
  817. ::sleep(1); // signals should interrupt this...
  818. }
  819. if (!beos_seen_signal)
  820. {
  821. signal(SIGCHLD, SIG_DFL); // oh well, didn't happen. Go on anyhow.
  822. }
  823. #endif
  824. if (WIFEXITED(retVal))
  825. {
  826. retVal = WEXITSTATUS(retVal);
  827. return true;
  828. }
  829. if (WIFSIGNALED(retVal))
  830. {
  831. retVal = WTERMSIG(retVal);
  832. cmOStringStream error;
  833. error << "\nProcess terminated due to ";
  834. switch (retVal)
  835. {
  836. #ifdef SIGKILL
  837. case SIGKILL:
  838. error << "SIGKILL";
  839. break;
  840. #endif
  841. #ifdef SIGFPE
  842. case SIGFPE:
  843. error << "SIGFPE";
  844. break;
  845. #endif
  846. #ifdef SIGBUS
  847. case SIGBUS:
  848. error << "SIGBUS";
  849. break;
  850. #endif
  851. #ifdef SIGSEGV
  852. case SIGSEGV:
  853. error << "SIGSEGV";
  854. break;
  855. #endif
  856. default:
  857. error << "signal " << retVal;
  858. break;
  859. }
  860. output += error.str();
  861. }
  862. return false;
  863. }
  864. #endif // endif WIN32 not CYGWIN
  865. // run a command unix uses popen (easy)
  866. // windows uses system and ShortPath
  867. bool cmSystemTools::RunCommand(const char* command,
  868. std::string& output,
  869. int &retVal,
  870. const char* dir,
  871. bool verbose,
  872. int timeout)
  873. {
  874. if(s_DisableRunCommandOutput)
  875. {
  876. verbose = false;
  877. }
  878. #if defined(WIN32) && !defined(__CYGWIN__)
  879. // if the command does not start with a quote, then
  880. // try to find the program, and if the program can not be
  881. // found use system to run the command as it must be a built in
  882. // shell command like echo or dir
  883. int count = 0;
  884. if(command[0] == '\"')
  885. {
  886. // count the number of quotes
  887. for(const char* s = command; *s != 0; ++s)
  888. {
  889. if(*s == '\"')
  890. {
  891. count++;
  892. if(count > 2)
  893. {
  894. break;
  895. }
  896. }
  897. }
  898. // if there are more than two double quotes use
  899. // GetShortPathName, the cmd.exe program in windows which
  900. // is used by system fails to execute if there are more than
  901. // one set of quotes in the arguments
  902. if(count > 2)
  903. {
  904. cmsys::RegularExpression quoted("^\"([^\"]*)\"[ \t](.*)");
  905. if(quoted.find(command))
  906. {
  907. std::string shortCmd;
  908. std::string cmd = quoted.match(1);
  909. std::string args = quoted.match(2);
  910. if(! cmSystemTools::FileExists(cmd.c_str()) )
  911. {
  912. shortCmd = cmd;
  913. }
  914. else if(!cmSystemTools::GetShortPath(cmd.c_str(), shortCmd))
  915. {
  916. cmSystemTools::Error("GetShortPath failed for " , cmd.c_str());
  917. return false;
  918. }
  919. shortCmd += " ";
  920. shortCmd += args;
  921. //return RunCommandViaSystem(shortCmd.c_str(), dir,
  922. // output, retVal, verbose);
  923. //return WindowsRunCommand(shortCmd.c_str(), dir,
  924. //output, retVal, verbose);
  925. return RunCommandViaWin32(shortCmd.c_str(), dir,
  926. output, retVal, verbose, timeout);
  927. }
  928. else
  929. {
  930. cmSystemTools::Error("Could not parse command line with quotes ",
  931. command);
  932. }
  933. }
  934. }
  935. // if there is only one set of quotes or no quotes then just run the command
  936. //return RunCommandViaSystem(command, dir, output, retVal, verbose);
  937. //return WindowsRunCommand(command, dir, output, retVal, verbose);
  938. return ::RunCommandViaWin32(command, dir, output, retVal, verbose, timeout);
  939. #else
  940. return ::RunCommandViaPopen(command, dir, output, retVal, verbose, timeout);
  941. #endif
  942. }
  943. bool cmSystemTools::DoesFileExistWithExtensions(
  944. const char* name,
  945. const std::vector<std::string>& headerExts)
  946. {
  947. std::string hname;
  948. for( std::vector<std::string>::const_iterator ext = headerExts.begin();
  949. ext != headerExts.end(); ++ext )
  950. {
  951. hname = name;
  952. hname += ".";
  953. hname += *ext;
  954. if(cmSystemTools::FileExists(hname.c_str()))
  955. {
  956. return true;
  957. }
  958. }
  959. return false;
  960. }
  961. bool cmSystemTools::cmCopyFile(const char* source, const char* destination)
  962. {
  963. return Superclass::CopyFileAlways(source, destination);
  964. }
  965. bool cmSystemTools::CopyFileIfDifferent(const char* source,
  966. const char* destination)
  967. {
  968. return Superclass::CopyFileIfDifferent(source, destination);
  969. }
  970. void cmSystemTools::Glob(const char *directory, const char *regexp,
  971. std::vector<std::string>& files)
  972. {
  973. cmsys::Directory d;
  974. cmsys::RegularExpression reg(regexp);
  975. if (d.Load(directory))
  976. {
  977. size_t numf;
  978. unsigned int i;
  979. numf = d.GetNumberOfFiles();
  980. for (i = 0; i < numf; i++)
  981. {
  982. std::string fname = d.GetFile(i);
  983. if (reg.find(fname))
  984. {
  985. files.push_back(fname);
  986. }
  987. }
  988. }
  989. }
  990. void cmSystemTools::GlobDirs(const char *fullPath,
  991. std::vector<std::string>& files)
  992. {
  993. std::string path = fullPath;
  994. std::string::size_type pos = path.find("/*");
  995. if(pos == std::string::npos)
  996. {
  997. files.push_back(fullPath);
  998. return;
  999. }
  1000. std::string startPath = path.substr(0, pos);
  1001. std::string finishPath = path.substr(pos+2);
  1002. cmsys::Directory d;
  1003. if (d.Load(startPath.c_str()))
  1004. {
  1005. for (unsigned int i = 0; i < d.GetNumberOfFiles(); ++i)
  1006. {
  1007. if((std::string(d.GetFile(i)) != ".")
  1008. && (std::string(d.GetFile(i)) != ".."))
  1009. {
  1010. std::string fname = startPath;
  1011. fname +="/";
  1012. fname += d.GetFile(i);
  1013. if(cmSystemTools::FileIsDirectory(fname.c_str()))
  1014. {
  1015. fname += finishPath;
  1016. cmSystemTools::GlobDirs(fname.c_str(), files);
  1017. }
  1018. }
  1019. }
  1020. }
  1021. }
  1022. void cmSystemTools::ExpandList(std::vector<std::string> const& arguments,
  1023. std::vector<std::string>& newargs)
  1024. {
  1025. std::vector<std::string>::const_iterator i;
  1026. for(i = arguments.begin();i != arguments.end(); ++i)
  1027. {
  1028. cmSystemTools::ExpandListArgument(*i, newargs);
  1029. }
  1030. }
  1031. void cmSystemTools::ExpandListArgument(const std::string& arg,
  1032. std::vector<std::string>& newargs,
  1033. bool emptyArgs)
  1034. {
  1035. // If argument is empty, it is an empty list.
  1036. if(arg.length() == 0 && !emptyArgs)
  1037. {
  1038. return;
  1039. }
  1040. // if there are no ; in the name then just copy the current string
  1041. if(arg.find(';') == std::string::npos)
  1042. {
  1043. newargs.push_back(arg);
  1044. return;
  1045. }
  1046. std::vector<char> newArgVec;
  1047. // Break the string at non-escaped semicolons not nested in [].
  1048. int squareNesting = 0;
  1049. for(const char* c = arg.c_str(); *c; ++c)
  1050. {
  1051. switch(*c)
  1052. {
  1053. case '\\':
  1054. {
  1055. // We only want to allow escaping of semicolons. Other
  1056. // escapes should not be processed here.
  1057. ++c;
  1058. if(*c == ';')
  1059. {
  1060. newArgVec.push_back(*c);
  1061. }
  1062. else
  1063. {
  1064. newArgVec.push_back('\\');
  1065. if(*c)
  1066. {
  1067. newArgVec.push_back(*c);
  1068. }
  1069. }
  1070. } break;
  1071. case '[':
  1072. {
  1073. ++squareNesting;
  1074. newArgVec.push_back(*c);
  1075. } break;
  1076. case ']':
  1077. {
  1078. --squareNesting;
  1079. newArgVec.push_back(*c);
  1080. } break;
  1081. case ';':
  1082. {
  1083. // Break the string here if we are not nested inside square
  1084. // brackets.
  1085. if(squareNesting == 0)
  1086. {
  1087. if ( newArgVec.size() || emptyArgs )
  1088. {
  1089. // Add the last argument if the string is not empty.
  1090. newArgVec.push_back(0);
  1091. newargs.push_back(&*newArgVec.begin());
  1092. newArgVec.clear();
  1093. }
  1094. }
  1095. else
  1096. {
  1097. newArgVec.push_back(*c);
  1098. }
  1099. } break;
  1100. default:
  1101. {
  1102. // Just append this character.
  1103. newArgVec.push_back(*c);
  1104. } break;
  1105. }
  1106. }
  1107. if ( newArgVec.size() || emptyArgs )
  1108. {
  1109. // Add the last argument if the string is not empty.
  1110. newArgVec.push_back(0);
  1111. newargs.push_back(&*newArgVec.begin());
  1112. }
  1113. }
  1114. bool cmSystemTools::SimpleGlob(const cmStdString& glob,
  1115. std::vector<cmStdString>& files,
  1116. int type /* = 0 */)
  1117. {
  1118. files.clear();
  1119. if ( glob[glob.size()-1] != '*' )
  1120. {
  1121. return false;
  1122. }
  1123. std::string path = cmSystemTools::GetFilenamePath(glob);
  1124. std::string ppath = cmSystemTools::GetFilenameName(glob);
  1125. ppath = ppath.substr(0, ppath.size()-1);
  1126. if ( path.size() == 0 )
  1127. {
  1128. path = "/";
  1129. }
  1130. bool res = false;
  1131. cmsys::Directory d;
  1132. if (d.Load(path.c_str()))
  1133. {
  1134. for (unsigned int i = 0; i < d.GetNumberOfFiles(); ++i)
  1135. {
  1136. if((std::string(d.GetFile(i)) != ".")
  1137. && (std::string(d.GetFile(i)) != ".."))
  1138. {
  1139. std::string fname = path;
  1140. if ( path[path.size()-1] != '/' )
  1141. {
  1142. fname +="/";
  1143. }
  1144. fname += d.GetFile(i);
  1145. std::string sfname = d.GetFile(i);
  1146. if ( type > 0 && cmSystemTools::FileIsDirectory(fname.c_str()) )
  1147. {
  1148. continue;
  1149. }
  1150. if ( type < 0 && !cmSystemTools::FileIsDirectory(fname.c_str()) )
  1151. {
  1152. continue;
  1153. }
  1154. if ( sfname.size() >= ppath.size() &&
  1155. sfname.substr(0, ppath.size()) ==
  1156. ppath )
  1157. {
  1158. files.push_back(fname);
  1159. res = true;
  1160. }
  1161. }
  1162. }
  1163. }
  1164. return res;
  1165. }
  1166. cmSystemTools::FileFormat cmSystemTools::GetFileFormat(const char* cext)
  1167. {
  1168. if ( ! cext || *cext == 0 )
  1169. {
  1170. return cmSystemTools::NO_FILE_FORMAT;
  1171. }
  1172. //std::string ext = cmSystemTools::LowerCase(cext);
  1173. std::string ext = cext;
  1174. if ( ext == "c" || ext == ".c" ) { return cmSystemTools::C_FILE_FORMAT; }
  1175. if (
  1176. ext == "C" || ext == ".C" ||
  1177. ext == "M" || ext == ".M" ||
  1178. ext == "c++" || ext == ".c++" ||
  1179. ext == "cc" || ext == ".cc" ||
  1180. ext == "cpp" || ext == ".cpp" ||
  1181. ext == "cxx" || ext == ".cxx" ||
  1182. ext == "m" || ext == ".m" ||
  1183. ext == "mm" || ext == ".mm"
  1184. ) { return cmSystemTools::CXX_FILE_FORMAT; }
  1185. if (
  1186. ext == "f" || ext == ".f" ||
  1187. ext == "F" || ext == ".F" ||
  1188. ext == "f77" || ext == ".f77" ||
  1189. ext == "f90" || ext == ".f90" ||
  1190. ext == "for" || ext == ".for" ||
  1191. ext == "f95" || ext == ".f95"
  1192. ) { return cmSystemTools::FORTRAN_FILE_FORMAT; }
  1193. if ( ext == "java" || ext == ".java" )
  1194. { return cmSystemTools::JAVA_FILE_FORMAT; }
  1195. if (
  1196. ext == "H" || ext == ".H" ||
  1197. ext == "h" || ext == ".h" ||
  1198. ext == "h++" || ext == ".h++" ||
  1199. ext == "hm" || ext == ".hm" ||
  1200. ext == "hpp" || ext == ".hpp" ||
  1201. ext == "hxx" || ext == ".hxx" ||
  1202. ext == "in" || ext == ".in" ||
  1203. ext == "txx" || ext == ".txx"
  1204. ) { return cmSystemTools::HEADER_FILE_FORMAT; }
  1205. if ( ext == "rc" || ext == ".rc" )
  1206. { return cmSystemTools::RESOURCE_FILE_FORMAT; }
  1207. if ( ext == "def" || ext == ".def" )
  1208. { return cmSystemTools::DEFINITION_FILE_FORMAT; }
  1209. if ( ext == "lib" || ext == ".lib" ||
  1210. ext == "a" || ext == ".a")
  1211. { return cmSystemTools::STATIC_LIBRARY_FILE_FORMAT; }
  1212. if ( ext == "o" || ext == ".o" ||
  1213. ext == "obj" || ext == ".obj")
  1214. { return cmSystemTools::OBJECT_FILE_FORMAT; }
  1215. #ifdef __APPLE__
  1216. if ( ext == "dylib" || ext == ".dylib" )
  1217. { return cmSystemTools::SHARED_LIBRARY_FILE_FORMAT; }
  1218. if ( ext == "so" || ext == ".so" ||
  1219. ext == "bundle" || ext == ".bundle" )
  1220. { return cmSystemTools::MODULE_FILE_FORMAT; }
  1221. #else // __APPLE__
  1222. if ( ext == "so" || ext == ".so" ||
  1223. ext == "sl" || ext == ".sl" ||
  1224. ext == "dll" || ext == ".dll" )
  1225. { return cmSystemTools::SHARED_LIBRARY_FILE_FORMAT; }
  1226. #endif // __APPLE__
  1227. return cmSystemTools::UNKNOWN_FILE_FORMAT;
  1228. }
  1229. bool cmSystemTools::Split(const char* s, std::vector<cmStdString>& l)
  1230. {
  1231. std::vector<std::string> temp;
  1232. bool res = Superclass::Split(s, temp);
  1233. for(std::vector<std::string>::const_iterator i = temp.begin();
  1234. i != temp.end(); ++i)
  1235. {
  1236. l.push_back(*i);
  1237. }
  1238. return res;
  1239. }
  1240. std::string cmSystemTools::ConvertToOutputPath(const char* path)
  1241. {
  1242. #if defined(_WIN32) && !defined(__CYGWIN__)
  1243. if(s_ForceUnixPaths)
  1244. {
  1245. return cmSystemTools::ConvertToUnixOutputPath(path);
  1246. }
  1247. return cmSystemTools::ConvertToWindowsOutputPath(path);
  1248. #else
  1249. return cmSystemTools::ConvertToUnixOutputPath(path);
  1250. #endif
  1251. }
  1252. std::string cmSystemTools::ConvertToRunCommandPath(const char* path)
  1253. {
  1254. #if defined(_WIN32) && !defined(__CYGWIN__)
  1255. return cmSystemTools::ConvertToWindowsOutputPath(path);
  1256. #else
  1257. return cmSystemTools::ConvertToUnixOutputPath(path);
  1258. #endif
  1259. }
  1260. bool cmSystemTools::StringEndsWith(const char* str1, const char* str2)
  1261. {
  1262. if ( !str1 || !str2 || strlen(str1) < strlen(str2) )
  1263. {
  1264. return 0;
  1265. }
  1266. return !strncmp(str1 + (strlen(str1)-strlen(str2)), str2, strlen(str2));
  1267. }
  1268. #if defined(_WIN32) && !defined(__CYGWIN__)
  1269. bool cmSystemTools::CreateSymlink(const char*, const char*)
  1270. {
  1271. // Should we create a copy here?
  1272. return false;
  1273. }
  1274. #else
  1275. bool cmSystemTools::CreateSymlink(const char* origName, const char* newName)
  1276. {
  1277. return (symlink(origName, newName) >= 0);
  1278. }
  1279. #endif
  1280. // compute the relative path from here to there
  1281. std::string cmSystemTools::RelativePath(const char* local, const char* remote)
  1282. {
  1283. if(!cmSystemTools::FileIsFullPath(local))
  1284. {
  1285. cmSystemTools::Error("RelativePath must be passed a full path to local: ",
  1286. local);
  1287. }
  1288. if(!cmSystemTools::FileIsFullPath(remote))
  1289. {
  1290. cmSystemTools::Error
  1291. ("RelativePath must be passed a full path to remote: ", remote);
  1292. }
  1293. return cmsys::SystemTools::RelativePath(local, remote);
  1294. }
  1295. class cmDeletingCharVector : public std::vector<char*>
  1296. {
  1297. public:
  1298. ~cmDeletingCharVector()
  1299. {
  1300. for(std::vector<char*>::iterator i = this->begin();
  1301. i != this->end(); ++i)
  1302. {
  1303. delete []*i;
  1304. }
  1305. }
  1306. };
  1307. bool cmSystemTools::PutEnv(const char* value)
  1308. {
  1309. static cmDeletingCharVector localEnvironment;
  1310. char* envVar = new char[strlen(value)+1];
  1311. strcpy(envVar, value);
  1312. int ret = putenv(envVar);
  1313. // save the pointer in the static vector so that it can
  1314. // be deleted on exit
  1315. localEnvironment.push_back(envVar);
  1316. return ret == 0;
  1317. }
  1318. #ifdef CMAKE_BUILD_WITH_CMAKE
  1319. bool cmSystemTools::UnsetEnv(const char* value)
  1320. {
  1321. #if !defined(HAVE_UNSETENV)
  1322. std::string var = value;
  1323. var += "=";
  1324. return cmSystemTools::PutEnv(var.c_str());
  1325. #else
  1326. unsetenv(value);
  1327. return true;
  1328. #endif
  1329. }
  1330. std::vector<std::string> cmSystemTools::GetEnvironmentVariables()
  1331. {
  1332. std::vector<std::string> env;
  1333. int cc;
  1334. for ( cc = 0; environ[cc]; ++ cc )
  1335. {
  1336. env.push_back(environ[cc]);
  1337. }
  1338. return env;
  1339. }
  1340. #endif
  1341. void cmSystemTools::EnableVSConsoleOutput()
  1342. {
  1343. // Visual Studio 8 2005 (devenv.exe or VCExpress.exe) will not
  1344. // display output to the console unless this environment variable is
  1345. // set. We need it to capture the output of these build tools.
  1346. // Note for future work that one could pass "/out \\.\pipe\NAME" to
  1347. // either of these executables where NAME is created with
  1348. // CreateNamedPipe. This would bypass the internal buffering of the
  1349. // output and allow it to be captured on the fly.
  1350. #ifdef _WIN32
  1351. cmSystemTools::PutEnv("vsconsoleoutput=1");
  1352. #endif
  1353. }
  1354. std::string cmSystemTools::MakeXMLSafe(const char* str)
  1355. {
  1356. std::vector<char> result;
  1357. result.reserve(500);
  1358. const char* pos = str;
  1359. for ( ;*pos; ++pos)
  1360. {
  1361. char ch = *pos;
  1362. if ( (ch > 126 || ch < 32) && ch != 9 && ch != 10 && ch != 13
  1363. && ch != '\r' )
  1364. {
  1365. char buffer[33];
  1366. sprintf(buffer, "&lt;%d&gt;", static_cast<int>(ch));
  1367. //sprintf(buffer, "&#x%0x;", (unsigned int)ch);
  1368. result.insert(result.end(), buffer, buffer+strlen(buffer));
  1369. }
  1370. else
  1371. {
  1372. const char* const encodedChars[] = {
  1373. "&amp;",
  1374. "&lt;",
  1375. "&gt;"
  1376. };
  1377. switch ( ch )
  1378. {
  1379. case '&':
  1380. result.insert(result.end(), encodedChars[0], encodedChars[0]+5);
  1381. break;
  1382. case '<':
  1383. result.insert(result.end(), encodedChars[1], encodedChars[1]+4);
  1384. break;
  1385. case '>':
  1386. result.insert(result.end(), encodedChars[2], encodedChars[2]+4);
  1387. break;
  1388. case '\n':
  1389. result.push_back('\n');
  1390. break;
  1391. case '\r': break; // Ignore \r
  1392. default:
  1393. result.push_back(ch);
  1394. }
  1395. }
  1396. }
  1397. if ( result.size() == 0 )
  1398. {
  1399. return "";
  1400. }
  1401. return std::string(&*result.begin(), result.size());
  1402. }
  1403. bool cmSystemTools::IsPathToFramework(const char* path)
  1404. {
  1405. if(cmSystemTools::FileIsFullPath(path))
  1406. {
  1407. std::string libname = path;
  1408. if(libname.find(".framework") == libname.size()+1-sizeof(".framework"))
  1409. {
  1410. return true;
  1411. }
  1412. }
  1413. return false;
  1414. }
  1415. #if defined(CMAKE_BUILD_WITH_CMAKE)
  1416. struct cmSystemToolsGZStruct
  1417. {
  1418. gzFile GZFile;
  1419. };
  1420. extern "C" {
  1421. int cmSystemToolsGZStructOpen(void* call_data, const char *pathname,
  1422. int oflags, mode_t mode);
  1423. int cmSystemToolsGZStructClose(void* call_data);
  1424. ssize_t cmSystemToolsGZStructRead(void* call_data, void* buf, size_t count);
  1425. ssize_t cmSystemToolsGZStructWrite(void* call_data, const void* buf,
  1426. size_t count);
  1427. }
  1428. int cmSystemToolsGZStructOpen(void* call_data, const char *pathname,
  1429. int oflags, mode_t mode)
  1430. {
  1431. const char *gzoflags;
  1432. int fd;
  1433. cmSystemToolsGZStruct* gzf = static_cast<cmSystemToolsGZStruct*>(call_data);
  1434. switch (oflags & O_ACCMODE)
  1435. {
  1436. case O_WRONLY:
  1437. gzoflags = "wb";
  1438. break;
  1439. case O_RDONLY:
  1440. gzoflags = "rb";
  1441. break;
  1442. default:
  1443. case O_RDWR:
  1444. errno = EINVAL;
  1445. return -1;
  1446. }
  1447. fd = open(pathname, oflags, mode);
  1448. if (fd == -1)
  1449. {
  1450. return -1;
  1451. }
  1452. // no fchmod on BeOS 5...do pathname instead.
  1453. #if defined(__BEOS__) && !defined(__ZETA__)
  1454. if ((oflags & O_CREAT) && chmod(pathname, mode))
  1455. {
  1456. return -1;
  1457. }
  1458. #elif !defined(_WIN32) || defined(__CYGWIN__)
  1459. if ((oflags & O_CREAT) && fchmod(fd, mode))
  1460. {
  1461. return -1;
  1462. }
  1463. #endif
  1464. gzf->GZFile = gzdopen(fd, gzoflags);
  1465. if (!gzf->GZFile)
  1466. {
  1467. errno = ENOMEM;
  1468. return -1;
  1469. }
  1470. return fd;
  1471. }
  1472. int cmSystemToolsGZStructClose(void* call_data)
  1473. {
  1474. cmSystemToolsGZStruct* gzf = static_cast<cmSystemToolsGZStruct*>(call_data);
  1475. return gzclose(gzf->GZFile);
  1476. }
  1477. ssize_t cmSystemToolsGZStructRead(void* call_data, void* buf, size_t count)
  1478. {
  1479. cmSystemToolsGZStruct* gzf = static_cast<cmSystemToolsGZStruct*>(call_data);
  1480. return gzread(gzf->GZFile, buf, count);
  1481. }
  1482. ssize_t cmSystemToolsGZStructWrite(void* call_data, const void* buf,
  1483. size_t count)
  1484. {
  1485. cmSystemToolsGZStruct* gzf = static_cast<cmSystemToolsGZStruct*>(call_data);
  1486. return gzwrite(gzf->GZFile, (void*)buf, count);
  1487. }
  1488. #endif
  1489. bool cmSystemTools::CreateTar(const char* outFileName,
  1490. const std::vector<cmStdString>& files,
  1491. bool gzip, bool verbose)
  1492. {
  1493. #if defined(CMAKE_BUILD_WITH_CMAKE)
  1494. TAR *t;
  1495. char buf[TAR_MAXPATHLEN];
  1496. char pathname[TAR_MAXPATHLEN];
  1497. cmSystemToolsGZStruct gzs;
  1498. tartype_t gztype = {
  1499. (openfunc_t)cmSystemToolsGZStructOpen,
  1500. (closefunc_t)cmSystemToolsGZStructClose,
  1501. (readfunc_t)cmSystemToolsGZStructRead,
  1502. (writefunc_t)cmSystemToolsGZStructWrite,
  1503. &gzs
  1504. };
  1505. // Ok, this libtar is not const safe. for now use auto_ptr hack
  1506. char* realName = new char[ strlen(outFileName) + 1 ];
  1507. std::auto_ptr<char> realNamePtr(realName);
  1508. strcpy(realName, outFileName);
  1509. if (tar_open(&t, realName,
  1510. (gzip? &gztype : NULL),
  1511. O_WRONLY | O_CREAT, 0644,
  1512. (verbose?TAR_VERBOSE:0)
  1513. | 0) == -1)
  1514. {
  1515. cmSystemTools::Error("Problem with tar_open(): ", strerror(errno));
  1516. return false;
  1517. }
  1518. std::vector<cmStdString>::const_iterator it;
  1519. for (it = files.begin(); it != files.end(); ++ it )
  1520. {
  1521. strncpy(pathname, it->c_str(), sizeof(pathname));
  1522. pathname[sizeof(pathname)-1] = 0;
  1523. strncpy(buf, pathname, sizeof(buf));
  1524. buf[sizeof(buf)-1] = 0;
  1525. if (tar_append_tree(t, buf, pathname) != 0)
  1526. {
  1527. cmOStringStream ostr;
  1528. ostr << "Problem with tar_append_tree(\"" << buf << "\", \""
  1529. << pathname << "\"): "
  1530. << strerror(errno);
  1531. cmSystemTools::Error(ostr.str().c_str());
  1532. tar_close(t);
  1533. return false;
  1534. }
  1535. }
  1536. if (tar_append_eof(t) != 0)
  1537. {
  1538. cmSystemTools::Error("Problem with tar_append_eof(): ", strerror(errno));
  1539. tar_close(t);
  1540. return false;
  1541. }
  1542. if (tar_close(t) != 0)
  1543. {
  1544. cmSystemTools::Error("Problem with tar_close(): ", strerror(errno));
  1545. return false;
  1546. }
  1547. return true;
  1548. #else
  1549. (void)outFileName;
  1550. (void)files;
  1551. (void)gzip;
  1552. (void)verbose;
  1553. return false;
  1554. #endif
  1555. }
  1556. bool cmSystemTools::ExtractTar(const char* outFileName,
  1557. const std::vector<cmStdString>& files,
  1558. bool gzip, bool verbose)
  1559. {
  1560. (void)files;
  1561. #if defined(CMAKE_BUILD_WITH_CMAKE)
  1562. TAR *t;
  1563. cmSystemToolsGZStruct gzs;
  1564. tartype_t gztype = {
  1565. cmSystemToolsGZStructOpen,
  1566. cmSystemToolsGZStructClose,
  1567. cmSystemToolsGZStructRead,
  1568. cmSystemToolsGZStructWrite,
  1569. &gzs
  1570. };
  1571. // Ok, this libtar is not const safe. for now use auto_ptr hack
  1572. char* realName = new char[ strlen(outFileName) + 1 ];
  1573. std::auto_ptr<char> realNamePtr(realName);
  1574. strcpy(realName, outFileName);
  1575. if (tar_open(&t, realName,
  1576. (gzip? &gztype : NULL),
  1577. O_RDONLY
  1578. #ifdef _WIN32
  1579. | O_BINARY
  1580. #endif
  1581. , 0,
  1582. (verbose?TAR_VERBOSE:0)
  1583. | 0) == -1)
  1584. {
  1585. cmSystemTools::Error("Problem with tar_open(): ", strerror(errno));
  1586. return false;
  1587. }
  1588. if (tar_extract_all(t, 0) != 0)
  1589. {
  1590. cmSystemTools::Error("Problem with tar_extract_all(): ", strerror(errno));
  1591. return false;
  1592. }
  1593. if (tar_close(t) != 0)
  1594. {
  1595. cmSystemTools::Error("Problem with tar_close(): ", strerror(errno));
  1596. return false;
  1597. }
  1598. return true;
  1599. #else
  1600. (void)outFileName;
  1601. (void)gzip;
  1602. (void)verbose;
  1603. return false;
  1604. #endif
  1605. }
  1606. bool cmSystemTools::ListTar(const char* outFileName,
  1607. std::vector<cmStdString>& files, bool gzip,
  1608. bool verbose)
  1609. {
  1610. #if defined(CMAKE_BUILD_WITH_CMAKE)
  1611. TAR *t;
  1612. cmSystemToolsGZStruct gzs;
  1613. tartype_t gztype = {
  1614. cmSystemToolsGZStructOpen,
  1615. cmSystemToolsGZStructClose,
  1616. cmSystemToolsGZStructRead,
  1617. cmSystemToolsGZStructWrite,
  1618. &gzs
  1619. };
  1620. // Ok, this libtar is not const safe. for now use auto_ptr hack
  1621. char* realName = new char[ strlen(outFileName) + 1 ];
  1622. std::auto_ptr<char> realNamePtr(realName);
  1623. strcpy(realName, outFileName);
  1624. if (tar_open(&t, realName,
  1625. (gzip? &gztype : NULL),
  1626. O_RDONLY
  1627. #ifdef _WIN32
  1628. | O_BINARY
  1629. #endif
  1630. , 0,
  1631. (verbose?TAR_VERBOSE:0)
  1632. | 0) == -1)
  1633. {
  1634. cmSystemTools::Error("Problem with tar_open(): ", strerror(errno));
  1635. return false;
  1636. }
  1637. while ((th_read(t)) == 0)
  1638. {
  1639. const char* filename = th_get_pathname(t);
  1640. files.push_back(filename);
  1641. if ( verbose )
  1642. {
  1643. th_print_long_ls(t);
  1644. }
  1645. else
  1646. {
  1647. std::cout << filename << std::endl;
  1648. }
  1649. #ifdef DEBUG
  1650. th_print(t);
  1651. #endif
  1652. if (TH_ISREG(t) && tar_skip_regfile(t) != 0)
  1653. {
  1654. cmSystemTools::Error("Problem with tar_skip_regfile(): ",
  1655. strerror(errno));
  1656. return false;
  1657. }
  1658. }
  1659. if (tar_close(t) != 0)
  1660. {
  1661. cmSystemTools::Error("Problem with tar_close(): ", strerror(errno));
  1662. return false;
  1663. }
  1664. return true;
  1665. #else
  1666. (void)outFileName;
  1667. (void)files;
  1668. (void)gzip;
  1669. (void)verbose;
  1670. return false;
  1671. #endif
  1672. }
  1673. int cmSystemTools::WaitForLine(cmsysProcess* process, std::string& line,
  1674. double timeout,
  1675. std::vector<char>& out,
  1676. std::vector<char>& err)
  1677. {
  1678. line = "";
  1679. std::vector<char>::iterator outiter = out.begin();
  1680. std::vector<char>::iterator erriter = err.begin();
  1681. while(1)
  1682. {
  1683. // Check for a newline in stdout.
  1684. for(;outiter != out.end(); ++outiter)
  1685. {
  1686. if((*outiter == '\r') && ((outiter+1) == out.end()))
  1687. {
  1688. break;
  1689. }
  1690. else if(*outiter == '\n' || *outiter == '\0')
  1691. {
  1692. int length = outiter-out.begin();
  1693. if(length > 1 && *(outiter-1) == '\r')
  1694. {
  1695. --length;
  1696. }
  1697. if(length > 0)
  1698. {
  1699. line.append(&out[0], length);
  1700. }
  1701. out.erase(out.begin(), outiter+1);
  1702. return cmsysProcess_Pipe_STDOUT;
  1703. }
  1704. }
  1705. // Check for a newline in stderr.
  1706. for(;erriter != err.end(); ++erriter)
  1707. {
  1708. if((*erriter == '\r') && ((erriter+1) == err.end()))
  1709. {
  1710. break;
  1711. }
  1712. else if(*erriter == '\n' || *erriter == '\0')
  1713. {
  1714. int length = erriter-err.begin();
  1715. if(length > 1 && *(erriter-1) == '\r')
  1716. {
  1717. --length;
  1718. }
  1719. if(length > 0)
  1720. {
  1721. line.append(&err[0], length);
  1722. }
  1723. err.erase(err.begin(), erriter+1);
  1724. return cmsysProcess_Pipe_STDERR;
  1725. }
  1726. }
  1727. // No newlines found. Wait for more data from the process.
  1728. int length;
  1729. char* data;
  1730. int pipe = cmsysProcess_WaitForData(process, &data, &length, &timeout);
  1731. if(pipe == cmsysProcess_Pipe_Timeout)
  1732. {
  1733. // Timeout has been exceeded.
  1734. return pipe;
  1735. }
  1736. else if(pipe == cmsysProcess_Pipe_STDOUT)
  1737. {
  1738. // Append to the stdout buffer.
  1739. std::vector<char>::size_type size = out.size();
  1740. out.insert(out.end(), data, data+length);
  1741. outiter = out.begin()+size;
  1742. }
  1743. else if(pipe == cmsysProcess_Pipe_STDERR)
  1744. {
  1745. // Append to the stderr buffer.
  1746. std::vector<char>::size_type size = err.size();
  1747. err.insert(err.end(), data, data+length);
  1748. erriter = err.begin()+size;
  1749. }
  1750. else if(pipe == cmsysProcess_Pipe_None)
  1751. {
  1752. // Both stdout and stderr pipes have broken. Return leftover data.
  1753. if(!out.empty())
  1754. {
  1755. line.append(&out[0], outiter-out.begin());
  1756. out.erase(out.begin(), out.end());
  1757. return cmsysProcess_Pipe_STDOUT;
  1758. }
  1759. else if(!err.empty())
  1760. {
  1761. line.append(&err[0], erriter-err.begin());
  1762. err.erase(err.begin(), err.end());
  1763. return cmsysProcess_Pipe_STDERR;
  1764. }
  1765. else
  1766. {
  1767. return cmsysProcess_Pipe_None;
  1768. }
  1769. }
  1770. }
  1771. }