cmSystemTools.cxx 40 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657
  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. return unsetenv(value) == 0;
  1195. }
  1196. std::vector<std::string> cmSystemTools::GetEnvironmentVariables()
  1197. {
  1198. std::vector<std::string> env;
  1199. int cc;
  1200. for ( cc = 0; environ[cc]; ++ cc )
  1201. {
  1202. env.push_back(environ[cc]);
  1203. }
  1204. return env;
  1205. }
  1206. void cmSystemTools::EnableVSConsoleOutput()
  1207. {
  1208. // Visual Studio 8 2005 (devenv.exe or VCExpress.exe) will not
  1209. // display output to the console unless this environment variable is
  1210. // set. We need it to capture the output of these build tools.
  1211. // Note for future work that one could pass "/out \\.\pipe\NAME" to
  1212. // either of these executables where NAME is created with
  1213. // CreateNamedPipe. This would bypass the internal buffering of the
  1214. // output and allow it to be captured on the fly.
  1215. #ifdef _WIN32
  1216. cmSystemTools::PutEnv("vsconsoleoutput=1");
  1217. #endif
  1218. }
  1219. std::string cmSystemTools::MakeXMLSafe(const char* str)
  1220. {
  1221. std::vector<char> result;
  1222. result.reserve(500);
  1223. const char* pos = str;
  1224. for ( ;*pos; ++pos)
  1225. {
  1226. char ch = *pos;
  1227. if ( (ch > 126 || ch < 32) && ch != 9 && ch != 10 && ch != 13
  1228. && ch != '\r' )
  1229. {
  1230. char buffer[33];
  1231. sprintf(buffer, "&lt;%d&gt;", (int)ch);
  1232. //sprintf(buffer, "&#x%0x;", (unsigned int)ch);
  1233. result.insert(result.end(), buffer, buffer+strlen(buffer));
  1234. }
  1235. else
  1236. {
  1237. const char* const encodedChars[] = {
  1238. "&amp;",
  1239. "&lt;",
  1240. "&gt;"
  1241. };
  1242. switch ( ch )
  1243. {
  1244. case '&':
  1245. result.insert(result.end(), encodedChars[0], encodedChars[0]+5);
  1246. break;
  1247. case '<':
  1248. result.insert(result.end(), encodedChars[1], encodedChars[1]+4);
  1249. break;
  1250. case '>':
  1251. result.insert(result.end(), encodedChars[2], encodedChars[2]+4);
  1252. break;
  1253. case '\n':
  1254. result.push_back('\n');
  1255. break;
  1256. case '\r': break; // Ignore \r
  1257. default:
  1258. result.push_back(ch);
  1259. }
  1260. }
  1261. }
  1262. if ( result.size() == 0 )
  1263. {
  1264. return "";
  1265. }
  1266. return std::string(&*result.begin(), result.size());
  1267. }
  1268. bool cmSystemTools::IsPathToFramework(const char* path)
  1269. {
  1270. if(cmSystemTools::FileIsFullPath(path))
  1271. {
  1272. std::string libname = path;
  1273. if(libname.find(".framework") == libname.size()+1-sizeof(".framework"))
  1274. {
  1275. return true;
  1276. }
  1277. }
  1278. return false;
  1279. }
  1280. #if defined(CMAKE_BUILD_WITH_CMAKE)
  1281. struct cmSystemToolsGZStruct
  1282. {
  1283. gzFile GZFile;
  1284. };
  1285. extern "C" {
  1286. int cmSystemToolsGZStructOpen(void* call_data, const char *pathname,
  1287. int oflags, mode_t mode);
  1288. int cmSystemToolsGZStructClose(void* call_data);
  1289. ssize_t cmSystemToolsGZStructRead(void* call_data, void* buf, size_t count);
  1290. ssize_t cmSystemToolsGZStructWrite(void* call_data, const void* buf,
  1291. size_t count);
  1292. }
  1293. int cmSystemToolsGZStructOpen(void* call_data, const char *pathname,
  1294. int oflags, mode_t mode)
  1295. {
  1296. const char *gzoflags;
  1297. int fd;
  1298. cmSystemToolsGZStruct* gzf = static_cast<cmSystemToolsGZStruct*>(call_data);
  1299. switch (oflags & O_ACCMODE)
  1300. {
  1301. case O_WRONLY:
  1302. gzoflags = "wb";
  1303. break;
  1304. case O_RDONLY:
  1305. gzoflags = "rb";
  1306. break;
  1307. default:
  1308. case O_RDWR:
  1309. errno = EINVAL;
  1310. return -1;
  1311. }
  1312. fd = open(pathname, oflags, mode);
  1313. if (fd == -1)
  1314. {
  1315. return -1;
  1316. }
  1317. #if !defined(_WIN32) || defined(__CYGWIN__)
  1318. if ((oflags & O_CREAT) && fchmod(fd, mode))
  1319. {
  1320. return -1;
  1321. }
  1322. #endif
  1323. gzf->GZFile = cm_zlib_gzdopen(fd, gzoflags);
  1324. if (!gzf->GZFile)
  1325. {
  1326. errno = ENOMEM;
  1327. return -1;
  1328. }
  1329. return fd;
  1330. }
  1331. int cmSystemToolsGZStructClose(void* call_data)
  1332. {
  1333. cmSystemToolsGZStruct* gzf = static_cast<cmSystemToolsGZStruct*>(call_data);
  1334. return cm_zlib_gzclose(gzf->GZFile);
  1335. }
  1336. ssize_t cmSystemToolsGZStructRead(void* call_data, void* buf, size_t count)
  1337. {
  1338. cmSystemToolsGZStruct* gzf = static_cast<cmSystemToolsGZStruct*>(call_data);
  1339. return cm_zlib_gzread(gzf->GZFile, buf, count);
  1340. }
  1341. ssize_t cmSystemToolsGZStructWrite(void* call_data, const void* buf,
  1342. size_t count)
  1343. {
  1344. cmSystemToolsGZStruct* gzf = static_cast<cmSystemToolsGZStruct*>(call_data);
  1345. return cm_zlib_gzwrite(gzf->GZFile, (void*)buf, count);
  1346. }
  1347. #endif
  1348. bool cmSystemTools::CreateTar(const char* outFileName,
  1349. const std::vector<cmStdString>& files,
  1350. bool gzip, bool verbose)
  1351. {
  1352. #if defined(CMAKE_BUILD_WITH_CMAKE)
  1353. TAR *t;
  1354. char buf[TAR_MAXPATHLEN];
  1355. char pathname[TAR_MAXPATHLEN];
  1356. cmSystemToolsGZStruct gzs;
  1357. tartype_t gztype = {
  1358. (openfunc_t)cmSystemToolsGZStructOpen,
  1359. (closefunc_t)cmSystemToolsGZStructClose,
  1360. (readfunc_t)cmSystemToolsGZStructRead,
  1361. (writefunc_t)cmSystemToolsGZStructWrite,
  1362. &gzs
  1363. };
  1364. // Ok, this libtar is not const safe. for now use auto_ptr hack
  1365. char* realName = new char[ strlen(outFileName) + 1 ];
  1366. std::auto_ptr<char> realNamePtr(realName);
  1367. strcpy(realName, outFileName);
  1368. if (tar_open(&t, realName,
  1369. (gzip? &gztype : NULL),
  1370. O_WRONLY | O_CREAT, 0644,
  1371. (verbose?TAR_VERBOSE:0)
  1372. | 0) == -1)
  1373. {
  1374. cmSystemTools::Error("Problem with tar_open(): ", strerror(errno));
  1375. return false;
  1376. }
  1377. std::vector<cmStdString>::const_iterator it;
  1378. for (it = files.begin(); it != files.end(); ++ it )
  1379. {
  1380. strncpy(pathname, it->c_str(), sizeof(pathname));
  1381. pathname[sizeof(pathname)-1] = 0;
  1382. strncpy(buf, pathname, sizeof(buf));
  1383. buf[sizeof(buf)-1] = 0;
  1384. if (tar_append_tree(t, buf, pathname) != 0)
  1385. {
  1386. cmOStringStream ostr;
  1387. ostr << "Problem with tar_append_tree(\"" << buf << "\", \""
  1388. << pathname << "\"): "
  1389. << strerror(errno);
  1390. cmSystemTools::Error(ostr.str().c_str());
  1391. tar_close(t);
  1392. return false;
  1393. }
  1394. }
  1395. if (tar_append_eof(t) != 0)
  1396. {
  1397. cmSystemTools::Error("Problem with tar_append_eof(): ", strerror(errno));
  1398. tar_close(t);
  1399. return false;
  1400. }
  1401. if (tar_close(t) != 0)
  1402. {
  1403. cmSystemTools::Error("Problem with tar_close(): ", strerror(errno));
  1404. return false;
  1405. }
  1406. return true;
  1407. #else
  1408. (void)outFileName;
  1409. (void)files;
  1410. (void)gzip;
  1411. (void)verbose;
  1412. return false;
  1413. #endif
  1414. }
  1415. bool cmSystemTools::ExtractTar(const char* outFileName,
  1416. const std::vector<cmStdString>& files,
  1417. bool gzip, bool verbose)
  1418. {
  1419. (void)files;
  1420. #if defined(CMAKE_BUILD_WITH_CMAKE)
  1421. TAR *t;
  1422. cmSystemToolsGZStruct gzs;
  1423. tartype_t gztype = {
  1424. cmSystemToolsGZStructOpen,
  1425. cmSystemToolsGZStructClose,
  1426. cmSystemToolsGZStructRead,
  1427. cmSystemToolsGZStructWrite,
  1428. &gzs
  1429. };
  1430. // Ok, this libtar is not const safe. for now use auto_ptr hack
  1431. char* realName = new char[ strlen(outFileName) + 1 ];
  1432. std::auto_ptr<char> realNamePtr(realName);
  1433. strcpy(realName, outFileName);
  1434. if (tar_open(&t, realName,
  1435. (gzip? &gztype : NULL),
  1436. O_RDONLY
  1437. #ifdef _WIN32
  1438. | O_BINARY
  1439. #endif
  1440. , 0,
  1441. (verbose?TAR_VERBOSE:0)
  1442. | 0) == -1)
  1443. {
  1444. cmSystemTools::Error("Problem with tar_open(): ", strerror(errno));
  1445. return false;
  1446. }
  1447. if (tar_extract_all(t, 0) != 0)
  1448. {
  1449. cmSystemTools::Error("Problem with tar_extract_all(): ", strerror(errno));
  1450. return false;
  1451. }
  1452. if (tar_close(t) != 0)
  1453. {
  1454. cmSystemTools::Error("Problem with tar_close(): ", strerror(errno));
  1455. return false;
  1456. }
  1457. return true;
  1458. #else
  1459. (void)outFileName;
  1460. (void)gzip;
  1461. (void)verbose;
  1462. return false;
  1463. #endif
  1464. }
  1465. bool cmSystemTools::ListTar(const char* outFileName,
  1466. std::vector<cmStdString>& files, bool gzip,
  1467. bool verbose)
  1468. {
  1469. #if defined(CMAKE_BUILD_WITH_CMAKE)
  1470. TAR *t;
  1471. cmSystemToolsGZStruct gzs;
  1472. tartype_t gztype = {
  1473. cmSystemToolsGZStructOpen,
  1474. cmSystemToolsGZStructClose,
  1475. cmSystemToolsGZStructRead,
  1476. cmSystemToolsGZStructWrite,
  1477. &gzs
  1478. };
  1479. // Ok, this libtar is not const safe. for now use auto_ptr hack
  1480. char* realName = new char[ strlen(outFileName) + 1 ];
  1481. std::auto_ptr<char> realNamePtr(realName);
  1482. strcpy(realName, outFileName);
  1483. if (tar_open(&t, realName,
  1484. (gzip? &gztype : NULL),
  1485. O_RDONLY
  1486. #ifdef _WIN32
  1487. | O_BINARY
  1488. #endif
  1489. , 0,
  1490. (verbose?TAR_VERBOSE:0)
  1491. | 0) == -1)
  1492. {
  1493. cmSystemTools::Error("Problem with tar_open(): ", strerror(errno));
  1494. return false;
  1495. }
  1496. while ((th_read(t)) == 0)
  1497. {
  1498. const char* filename = th_get_pathname(t);
  1499. files.push_back(filename);
  1500. if ( verbose )
  1501. {
  1502. th_print_long_ls(t);
  1503. }
  1504. else
  1505. {
  1506. std::cout << filename << std::endl;
  1507. }
  1508. #ifdef DEBUG
  1509. th_print(t);
  1510. #endif
  1511. if (TH_ISREG(t) && tar_skip_regfile(t) != 0)
  1512. {
  1513. cmSystemTools::Error("Problem with tar_skip_regfile(): ",
  1514. strerror(errno));
  1515. return false;
  1516. }
  1517. }
  1518. if (tar_close(t) != 0)
  1519. {
  1520. cmSystemTools::Error("Problem with tar_close(): ", strerror(errno));
  1521. return false;
  1522. }
  1523. return true;
  1524. #else
  1525. (void)outFileName;
  1526. (void)files;
  1527. (void)gzip;
  1528. (void)verbose;
  1529. return false;
  1530. #endif
  1531. }