cmSystemTools.cxx 57 KB

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