cmSystemTools.cxx 49 KB

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