cmSystemTools.cxx 40 KB

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