cmSystemTools.cxx 41 KB

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