cmSystemTools.cxx 47 KB

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