cmSystemTools.cxx 40 KB

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