cmSystemTools.cxx 39 KB

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