cmSystemTools.cxx 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776
  1. /*=========================================================================
  2. Program: CMake - Cross-Platform Makefile Generator
  3. Module: $RCSfile$
  4. Language: C++
  5. Date: $Date$
  6. Version: $Revision$
  7. Copyright (c) 2002 Kitware, Inc., Insight Consortium. All rights reserved.
  8. See Copyright.txt or http://www.cmake.org/HTML/Copyright.html for details.
  9. This software is distributed WITHOUT ANY WARRANTY; without even
  10. the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
  11. PURPOSE. See the above copyright notices for more information.
  12. =========================================================================*/
  13. #include "cmSystemTools.h"
  14. #include <ctype.h>
  15. #include <errno.h>
  16. #include <time.h>
  17. #include <cmsys/RegularExpression.hxx>
  18. #include <cmsys/Directory.hxx>
  19. // support for realpath call
  20. #ifndef _WIN32
  21. #include <limits.h>
  22. #include <stdlib.h>
  23. #include <sys/param.h>
  24. #include <sys/wait.h>
  25. #endif
  26. #if defined(_WIN32) && (defined(_MSC_VER) || defined(__BORLANDC__))
  27. #include <string.h>
  28. #include <windows.h>
  29. #include <direct.h>
  30. #include <io.h>
  31. #define _unlink unlink
  32. #else
  33. #include <sys/types.h>
  34. #include <fcntl.h>
  35. #include <unistd.h>
  36. #endif
  37. #include <sys/stat.h>
  38. #if defined(CMAKE_BUILD_WITH_CMAKE)
  39. # include <libtar/libtar.h>
  40. # include <memory> // auto_ptr
  41. # include <fcntl.h>
  42. # include <cmzlib/zlib.h>
  43. #endif
  44. #if defined(__sgi) && !defined(__GNUC__)
  45. # pragma set woff 1375 /* base class destructor not virtual */
  46. #endif
  47. #if !defined(HAVE_ENVIRON_NOT_REQUIRE_PROTOTYPE)
  48. // For GetEnvironmentVariables
  49. # if defined(_WIN32)
  50. extern __declspec( dllimport ) char** environ;
  51. # else
  52. extern char** environ;
  53. # endif
  54. #endif
  55. bool cmSystemTools::s_RunCommandHideConsole = false;
  56. bool cmSystemTools::s_DisableRunCommandOutput = false;
  57. bool cmSystemTools::s_ErrorOccured = false;
  58. bool cmSystemTools::s_FatalErrorOccured = false;
  59. bool cmSystemTools::s_DisableMessages = false;
  60. bool cmSystemTools::s_ForceUnixPaths = false;
  61. std::string cmSystemTools::s_Windows9xComspecSubstitute = "command.com";
  62. void cmSystemTools::SetWindows9xComspecSubstitute(const char* str)
  63. {
  64. if ( str )
  65. {
  66. cmSystemTools::s_Windows9xComspecSubstitute = str;
  67. }
  68. }
  69. const char* cmSystemTools::GetWindows9xComspecSubstitute()
  70. {
  71. return cmSystemTools::s_Windows9xComspecSubstitute.c_str();
  72. }
  73. void (*cmSystemTools::s_ErrorCallback)(const char*, const char*,
  74. 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
  1172. ("RelativePath must be passed a full path to remote: ", 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. }
  1548. int cmSystemTools::WaitForLine(cmsysProcess* process, std::string& line,
  1549. double timeout,
  1550. std::vector<char>& out,
  1551. std::vector<char>& err)
  1552. {
  1553. line = "";
  1554. std::vector<char>::iterator outiter = out.begin();
  1555. std::vector<char>::iterator erriter = err.begin();
  1556. while(1)
  1557. {
  1558. // Check for a newline in stdout.
  1559. for(;outiter != out.end(); ++outiter)
  1560. {
  1561. if((*outiter == '\r') && ((outiter+1) == out.end()))
  1562. {
  1563. break;
  1564. }
  1565. else if(*outiter == '\n' || *outiter == '\0')
  1566. {
  1567. int length = outiter-out.begin();
  1568. if(length > 1 && *(outiter-1) == '\r')
  1569. {
  1570. --length;
  1571. }
  1572. if(length > 0)
  1573. {
  1574. line.append(&out[0], length);
  1575. }
  1576. out.erase(out.begin(), outiter+1);
  1577. return cmsysProcess_Pipe_STDOUT;
  1578. }
  1579. }
  1580. // Check for a newline in stderr.
  1581. for(;erriter != err.end(); ++erriter)
  1582. {
  1583. if((*erriter == '\r') && ((erriter+1) == err.end()))
  1584. {
  1585. break;
  1586. }
  1587. else if(*erriter == '\n' || *erriter == '\0')
  1588. {
  1589. int length = erriter-err.begin();
  1590. if(length > 1 && *(erriter-1) == '\r')
  1591. {
  1592. --length;
  1593. }
  1594. if(length > 0)
  1595. {
  1596. line.append(&err[0], length);
  1597. }
  1598. err.erase(err.begin(), erriter+1);
  1599. return cmsysProcess_Pipe_STDERR;
  1600. }
  1601. }
  1602. // No newlines found. Wait for more data from the process.
  1603. int length;
  1604. char* data;
  1605. int pipe = cmsysProcess_WaitForData(process, &data, &length, &timeout);
  1606. if(pipe == cmsysProcess_Pipe_Timeout)
  1607. {
  1608. // Timeout has been exceeded.
  1609. return pipe;
  1610. }
  1611. else if(pipe == cmsysProcess_Pipe_STDOUT)
  1612. {
  1613. // Append to the stdout buffer.
  1614. std::vector<char>::size_type size = out.size();
  1615. out.insert(out.end(), data, data+length);
  1616. outiter = out.begin()+size;
  1617. }
  1618. else if(pipe == cmsysProcess_Pipe_STDERR)
  1619. {
  1620. // Append to the stderr buffer.
  1621. std::vector<char>::size_type size = err.size();
  1622. err.insert(err.end(), data, data+length);
  1623. erriter = err.begin()+size;
  1624. }
  1625. else if(pipe == cmsysProcess_Pipe_None)
  1626. {
  1627. // Both stdout and stderr pipes have broken. Return leftover data.
  1628. if(!out.empty())
  1629. {
  1630. line.append(&out[0], outiter-out.begin());
  1631. out.erase(out.begin(), out.end());
  1632. return cmsysProcess_Pipe_STDOUT;
  1633. }
  1634. else if(!err.empty())
  1635. {
  1636. line.append(&err[0], erriter-err.begin());
  1637. err.erase(err.begin(), err.end());
  1638. return cmsysProcess_Pipe_STDERR;
  1639. }
  1640. else
  1641. {
  1642. return cmsysProcess_Pipe_None;
  1643. }
  1644. }
  1645. }
  1646. }