cmSystemTools.cxx 43 KB

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