cmSystemTools.cxx 74 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844
  1. /*============================================================================
  2. CMake - Cross Platform Makefile Generator
  3. Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
  4. Distributed under the OSI-approved BSD License (the "License");
  5. see accompanying file Copyright.txt for details.
  6. This software is distributed WITHOUT ANY WARRANTY; without even the
  7. implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
  8. See the License for more information.
  9. ============================================================================*/
  10. #if defined(_MSC_VER) && _MSC_VER < 1300
  11. # define _WIN32_WINNT 0x0400 /* for wincrypt.h */
  12. #endif
  13. #include "cmSystemTools.h"
  14. #include <ctype.h>
  15. #include <errno.h>
  16. #include <time.h>
  17. #include <string.h>
  18. #include <stdlib.h>
  19. #ifdef __QNX__
  20. # include <malloc.h> /* for malloc/free on QNX */
  21. #endif
  22. #include <cmsys/Glob.hxx>
  23. #include <cmsys/RegularExpression.hxx>
  24. #include <cmsys/Directory.hxx>
  25. #include <cmsys/System.h>
  26. #include <cmsys/Encoding.hxx>
  27. #if defined(CMAKE_BUILD_WITH_CMAKE)
  28. # include "cmArchiveWrite.h"
  29. # include <cm_libarchive.h>
  30. # include <cmsys/Terminal.h>
  31. #endif
  32. #include <cmsys/stl/algorithm>
  33. #include <cmsys/FStream.hxx>
  34. #if defined(_WIN32)
  35. # include <windows.h>
  36. # include <wincrypt.h>
  37. #else
  38. # include <sys/time.h>
  39. # include <sys/types.h>
  40. # include <unistd.h>
  41. # include <utime.h>
  42. # include <sys/wait.h>
  43. #endif
  44. #if defined(__APPLE__)
  45. # include <mach-o/dyld.h>
  46. #endif
  47. #include <sys/stat.h>
  48. #if defined(_WIN32) && \
  49. (defined(_MSC_VER) || defined(__WATCOMC__) || \
  50. defined(__BORLANDC__) || defined(__MINGW32__))
  51. # include <io.h>
  52. #endif
  53. #if defined(CMAKE_BUILD_WITH_CMAKE)
  54. # include <fcntl.h>
  55. # include "cmCryptoHash.h"
  56. #endif
  57. #if defined(CMAKE_USE_ELF_PARSER)
  58. # include "cmELF.h"
  59. #endif
  60. class cmSystemToolsFileTime
  61. {
  62. public:
  63. #if defined(_WIN32) && !defined(__CYGWIN__)
  64. FILETIME timeCreation;
  65. FILETIME timeLastAccess;
  66. FILETIME timeLastWrite;
  67. #else
  68. struct utimbuf timeBuf;
  69. #endif
  70. };
  71. #if defined(__sgi) && !defined(__GNUC__)
  72. # pragma set woff 1375 /* base class destructor not virtual */
  73. #endif
  74. #if !defined(HAVE_ENVIRON_NOT_REQUIRE_PROTOTYPE)
  75. // For GetEnvironmentVariables
  76. # if defined(_WIN32)
  77. extern __declspec( dllimport ) char** environ;
  78. # else
  79. extern char** environ;
  80. # endif
  81. #endif
  82. #ifdef _WIN32
  83. class cmSystemToolsWindowsHandle
  84. {
  85. public:
  86. cmSystemToolsWindowsHandle(HANDLE h): handle_(h) {}
  87. ~cmSystemToolsWindowsHandle()
  88. {
  89. if(this->handle_ != INVALID_HANDLE_VALUE)
  90. {
  91. CloseHandle(this->handle_);
  92. }
  93. }
  94. operator bool() const { return this->handle_ != INVALID_HANDLE_VALUE; }
  95. bool operator !() const { return this->handle_ == INVALID_HANDLE_VALUE; }
  96. operator HANDLE() const { return this->handle_; }
  97. private:
  98. HANDLE handle_;
  99. };
  100. #elif defined(__APPLE__)
  101. #include <crt_externs.h>
  102. #define environ (*_NSGetEnviron())
  103. #endif
  104. bool cmSystemTools::s_RunCommandHideConsole = false;
  105. bool cmSystemTools::s_DisableRunCommandOutput = false;
  106. bool cmSystemTools::s_ErrorOccured = false;
  107. bool cmSystemTools::s_FatalErrorOccured = false;
  108. bool cmSystemTools::s_DisableMessages = false;
  109. bool cmSystemTools::s_ForceUnixPaths = false;
  110. void (*cmSystemTools::s_ErrorCallback)(const char*, const char*,
  111. bool&, void*);
  112. void (*cmSystemTools::s_StdoutCallback)(const char*, int len, void*);
  113. void* cmSystemTools::s_ErrorCallbackClientData = 0;
  114. void* cmSystemTools::s_StdoutCallbackClientData = 0;
  115. bool (*cmSystemTools::s_InterruptCallback)(void*);
  116. void* cmSystemTools::s_InterruptCallbackClientData = 0;
  117. // replace replace with with as many times as it shows up in source.
  118. // write the result into source.
  119. #if defined(_WIN32) && !defined(__CYGWIN__)
  120. void cmSystemTools::ExpandRegistryValues(std::string& source, KeyWOW64 view)
  121. {
  122. // Regular expression to match anything inside [...] that begins in HKEY.
  123. // Note that there is a special rule for regular expressions to match a
  124. // close square-bracket inside a list delimited by square brackets.
  125. // The "[^]]" part of this expression will match any character except
  126. // a close square-bracket. The ']' character must be the first in the
  127. // list of characters inside the [^...] block of the expression.
  128. cmsys::RegularExpression regEntry("\\[(HKEY[^]]*)\\]");
  129. // check for black line or comment
  130. while (regEntry.find(source))
  131. {
  132. // the arguments are the second match
  133. std::string key = regEntry.match(1);
  134. std::string val;
  135. if (ReadRegistryValue(key.c_str(), val, view))
  136. {
  137. std::string reg = "[";
  138. reg += key + "]";
  139. cmSystemTools::ReplaceString(source, reg.c_str(), val.c_str());
  140. }
  141. else
  142. {
  143. std::string reg = "[";
  144. reg += key + "]";
  145. cmSystemTools::ReplaceString(source, reg.c_str(), "/registry");
  146. }
  147. }
  148. }
  149. #else
  150. void cmSystemTools::ExpandRegistryValues(std::string& source, KeyWOW64)
  151. {
  152. cmsys::RegularExpression regEntry("\\[(HKEY[^]]*)\\]");
  153. while (regEntry.find(source))
  154. {
  155. // the arguments are the second match
  156. std::string key = regEntry.match(1);
  157. std::string val;
  158. std::string reg = "[";
  159. reg += key + "]";
  160. cmSystemTools::ReplaceString(source, reg.c_str(), "/registry");
  161. }
  162. }
  163. #endif
  164. std::string cmSystemTools::EscapeQuotes(const std::string& str)
  165. {
  166. std::string result;
  167. result.reserve(str.size());
  168. for(const char* ch = str.c_str(); *ch != '\0'; ++ch)
  169. {
  170. if(*ch == '"')
  171. {
  172. result += '\\';
  173. }
  174. result += *ch;
  175. }
  176. return result;
  177. }
  178. std::string cmSystemTools::HelpFileName(std::string name)
  179. {
  180. cmSystemTools::ReplaceString(name, "<", "");
  181. cmSystemTools::ReplaceString(name, ">", "");
  182. return name;
  183. }
  184. std::string cmSystemTools::TrimWhitespace(const std::string& s)
  185. {
  186. std::string::const_iterator start = s.begin();
  187. while(start != s.end() && *start <= ' ')
  188. ++start;
  189. if (start == s.end())
  190. return "";
  191. std::string::const_iterator stop = s.end()-1;
  192. while(*stop <= ' ')
  193. --stop;
  194. return std::string(start, stop+1);
  195. }
  196. void cmSystemTools::Error(const char* m1, const char* m2,
  197. const char* m3, const char* m4)
  198. {
  199. std::string message = "CMake Error: ";
  200. if(m1)
  201. {
  202. message += m1;
  203. }
  204. if(m2)
  205. {
  206. message += m2;
  207. }
  208. if(m3)
  209. {
  210. message += m3;
  211. }
  212. if(m4)
  213. {
  214. message += m4;
  215. }
  216. cmSystemTools::s_ErrorOccured = true;
  217. cmSystemTools::Message(message.c_str(),"Error");
  218. }
  219. void cmSystemTools::SetInterruptCallback(InterruptCallback f, void* clientData)
  220. {
  221. s_InterruptCallback = f;
  222. s_InterruptCallbackClientData = clientData;
  223. }
  224. bool cmSystemTools::GetInterruptFlag()
  225. {
  226. if(s_InterruptCallback)
  227. {
  228. return (*s_InterruptCallback)(s_InterruptCallbackClientData);
  229. }
  230. return false;
  231. }
  232. void cmSystemTools::SetErrorCallback(ErrorCallback f, void* clientData)
  233. {
  234. s_ErrorCallback = f;
  235. s_ErrorCallbackClientData = clientData;
  236. }
  237. void cmSystemTools::SetStdoutCallback(StdoutCallback f, void* clientData)
  238. {
  239. s_StdoutCallback = f;
  240. s_StdoutCallbackClientData = clientData;
  241. }
  242. void cmSystemTools::Stdout(const char* s)
  243. {
  244. if(s_StdoutCallback)
  245. {
  246. (*s_StdoutCallback)(s, static_cast<int>(strlen(s)),
  247. s_StdoutCallbackClientData);
  248. }
  249. else
  250. {
  251. std::cout << s;
  252. std::cout.flush();
  253. }
  254. }
  255. void cmSystemTools::Stderr(const char* s, int length)
  256. {
  257. std::cerr.write(s, length);
  258. std::cerr.flush();
  259. }
  260. void cmSystemTools::Stdout(const char* s, int length)
  261. {
  262. if(s_StdoutCallback)
  263. {
  264. (*s_StdoutCallback)(s, length, s_StdoutCallbackClientData);
  265. }
  266. else
  267. {
  268. std::cout.write(s, length);
  269. std::cout.flush();
  270. }
  271. }
  272. void cmSystemTools::Message(const char* m1, const char *title)
  273. {
  274. if(s_DisableMessages)
  275. {
  276. return;
  277. }
  278. if(s_ErrorCallback)
  279. {
  280. (*s_ErrorCallback)(m1, title, s_DisableMessages,
  281. s_ErrorCallbackClientData);
  282. return;
  283. }
  284. else
  285. {
  286. std::cerr << m1 << std::endl << std::flush;
  287. }
  288. }
  289. void cmSystemTools::ReportLastSystemError(const char* msg)
  290. {
  291. std::string m = msg;
  292. m += ": System Error: ";
  293. m += Superclass::GetLastSystemError();
  294. cmSystemTools::Error(m.c_str());
  295. }
  296. bool cmSystemTools::IsInternallyOn(const char* val)
  297. {
  298. if (!val)
  299. {
  300. return false;
  301. }
  302. std::basic_string<char> v = val;
  303. for(std::basic_string<char>::iterator c = v.begin();
  304. c != v.end(); c++)
  305. {
  306. *c = static_cast<char>(toupper(*c));
  307. }
  308. return (v == "I_ON" || v == "i_on");
  309. }
  310. bool cmSystemTools::IsOn(const char* val)
  311. {
  312. if (!val)
  313. {
  314. return false;
  315. }
  316. std::basic_string<char> v = val;
  317. for(std::basic_string<char>::iterator c = v.begin();
  318. c != v.end(); c++)
  319. {
  320. *c = static_cast<char>(toupper(*c));
  321. }
  322. return (v == "ON" || v == "1" || v == "YES" || v == "TRUE" || v == "Y");
  323. }
  324. bool cmSystemTools::IsNOTFOUND(const char* val)
  325. {
  326. if(strcmp(val, "NOTFOUND") == 0)
  327. {
  328. return true;
  329. }
  330. return cmHasLiteralSuffix(val, "-NOTFOUND");
  331. }
  332. bool cmSystemTools::IsOff(const char* val)
  333. {
  334. if (!val || strlen(val) == 0)
  335. {
  336. return true;
  337. }
  338. std::basic_string<char> v = val;
  339. for(std::basic_string<char>::iterator c = v.begin();
  340. c != v.end(); c++)
  341. {
  342. *c = static_cast<char>(toupper(*c));
  343. }
  344. return (v == "OFF" || v == "0" || v == "NO" || v == "FALSE" ||
  345. v == "N" || cmSystemTools::IsNOTFOUND(v.c_str()) || v == "IGNORE");
  346. }
  347. //----------------------------------------------------------------------------
  348. void cmSystemTools::ParseWindowsCommandLine(const char* command,
  349. std::vector<std::string>& args)
  350. {
  351. // See the MSDN document "Parsing C Command-Line Arguments" at
  352. // http://msdn2.microsoft.com/en-us/library/a1y7w461.aspx for rules
  353. // of parsing the windows command line.
  354. bool in_argument = false;
  355. bool in_quotes = false;
  356. int backslashes = 0;
  357. std::string arg;
  358. for(const char* c = command;*c; ++c)
  359. {
  360. if(*c == '\\')
  361. {
  362. ++backslashes;
  363. in_argument = true;
  364. }
  365. else if(*c == '"')
  366. {
  367. int backslash_pairs = backslashes >> 1;
  368. int backslash_escaped = backslashes & 1;
  369. arg.append(backslash_pairs, '\\');
  370. backslashes = 0;
  371. if(backslash_escaped)
  372. {
  373. /* An odd number of backslashes precede this quote.
  374. It is escaped. */
  375. arg.append(1, '"');
  376. }
  377. else
  378. {
  379. /* An even number of backslashes precede this quote.
  380. It is not escaped. */
  381. in_quotes = !in_quotes;
  382. }
  383. in_argument = true;
  384. }
  385. else
  386. {
  387. arg.append(backslashes, '\\');
  388. backslashes = 0;
  389. if(isspace(*c))
  390. {
  391. if(in_quotes)
  392. {
  393. arg.append(1, *c);
  394. }
  395. else if(in_argument)
  396. {
  397. args.push_back(arg);
  398. arg = "";
  399. in_argument = false;
  400. }
  401. }
  402. else
  403. {
  404. in_argument = true;
  405. arg.append(1, *c);
  406. }
  407. }
  408. }
  409. arg.append(backslashes, '\\');
  410. if(in_argument)
  411. {
  412. args.push_back(arg);
  413. }
  414. }
  415. //----------------------------------------------------------------------------
  416. class cmSystemToolsArgV
  417. {
  418. char** ArgV;
  419. public:
  420. cmSystemToolsArgV(char** argv): ArgV(argv) {}
  421. ~cmSystemToolsArgV()
  422. {
  423. for(char** arg = this->ArgV; arg && *arg; ++arg)
  424. {
  425. free(*arg);
  426. }
  427. free(this->ArgV);
  428. }
  429. void Store(std::vector<std::string>& args) const
  430. {
  431. for(char** arg = this->ArgV; arg && *arg; ++arg)
  432. {
  433. args.push_back(*arg);
  434. }
  435. }
  436. };
  437. //----------------------------------------------------------------------------
  438. void cmSystemTools::ParseUnixCommandLine(const char* command,
  439. std::vector<std::string>& args)
  440. {
  441. // Invoke the underlying parser.
  442. cmSystemToolsArgV argv = cmsysSystem_Parse_CommandForUnix(command, 0);
  443. argv.Store(args);
  444. }
  445. std::string cmSystemTools::EscapeWindowsShellArgument(const char* arg,
  446. int shell_flags)
  447. {
  448. char local_buffer[1024];
  449. char* buffer = local_buffer;
  450. int size = cmsysSystem_Shell_GetArgumentSizeForWindows(arg, shell_flags);
  451. if(size > 1024)
  452. {
  453. buffer = new char[size];
  454. }
  455. cmsysSystem_Shell_GetArgumentForWindows(arg, buffer, shell_flags);
  456. std::string result(buffer);
  457. if(buffer != local_buffer)
  458. {
  459. delete [] buffer;
  460. }
  461. return result;
  462. }
  463. std::vector<std::string> cmSystemTools::ParseArguments(const char* command)
  464. {
  465. std::vector<std::string> args;
  466. std::string arg;
  467. bool win_path = false;
  468. if ((command[0] != '/' && command[1] == ':' && command[2] == '\\') ||
  469. (command[0] == '\"' && command[1] != '/' && command[2] == ':'
  470. && command[3] == '\\') ||
  471. (command[0] == '\'' && command[1] != '/' && command[2] == ':'
  472. && command[3] == '\\') ||
  473. (command[0] == '\\' && command[1] == '\\'))
  474. {
  475. win_path = true;
  476. }
  477. // Split the command into an argv array.
  478. for(const char* c = command; *c;)
  479. {
  480. // Skip over whitespace.
  481. while(*c == ' ' || *c == '\t')
  482. {
  483. ++c;
  484. }
  485. arg = "";
  486. if(*c == '"')
  487. {
  488. // Parse a quoted argument.
  489. ++c;
  490. while(*c && *c != '"')
  491. {
  492. arg.append(1, *c);
  493. ++c;
  494. }
  495. if(*c)
  496. {
  497. ++c;
  498. }
  499. args.push_back(arg);
  500. }
  501. else if(*c == '\'')
  502. {
  503. // Parse a quoted argument.
  504. ++c;
  505. while(*c && *c != '\'')
  506. {
  507. arg.append(1, *c);
  508. ++c;
  509. }
  510. if(*c)
  511. {
  512. ++c;
  513. }
  514. args.push_back(arg);
  515. }
  516. else if(*c)
  517. {
  518. // Parse an unquoted argument.
  519. while(*c && *c != ' ' && *c != '\t')
  520. {
  521. if(*c == '\\' && !win_path)
  522. {
  523. ++c;
  524. if(*c)
  525. {
  526. arg.append(1, *c);
  527. ++c;
  528. }
  529. }
  530. else
  531. {
  532. arg.append(1, *c);
  533. ++c;
  534. }
  535. }
  536. args.push_back(arg);
  537. }
  538. }
  539. return args;
  540. }
  541. bool cmSystemTools::RunSingleCommand(std::vector<std::string>const& command,
  542. std::string* output ,
  543. int* retVal , const char* dir ,
  544. OutputOption outputflag ,
  545. double timeout )
  546. {
  547. std::vector<const char*> argv;
  548. for(std::vector<std::string>::const_iterator a = command.begin();
  549. a != command.end(); ++a)
  550. {
  551. argv.push_back(a->c_str());
  552. }
  553. argv.push_back(0);
  554. if ( output )
  555. {
  556. *output = "";
  557. }
  558. cmsysProcess* cp = cmsysProcess_New();
  559. cmsysProcess_SetCommand(cp, &*argv.begin());
  560. cmsysProcess_SetWorkingDirectory(cp, dir);
  561. if(cmSystemTools::GetRunCommandHideConsole())
  562. {
  563. cmsysProcess_SetOption(cp, cmsysProcess_Option_HideWindow, 1);
  564. }
  565. if (outputflag == OUTPUT_PASSTHROUGH)
  566. {
  567. cmsysProcess_SetPipeShared(cp, cmsysProcess_Pipe_STDOUT, 1);
  568. cmsysProcess_SetPipeShared(cp, cmsysProcess_Pipe_STDERR, 1);
  569. }
  570. cmsysProcess_SetTimeout(cp, timeout);
  571. cmsysProcess_Execute(cp);
  572. std::vector<char> tempOutput;
  573. char* data;
  574. int length;
  575. int pipe;
  576. if(outputflag != OUTPUT_PASSTHROUGH && (output || outputflag != OUTPUT_NONE))
  577. {
  578. while((pipe = cmsysProcess_WaitForData(cp, &data, &length, 0)) > 0)
  579. {
  580. if(output || outputflag != OUTPUT_NONE)
  581. {
  582. // Translate NULL characters in the output into valid text.
  583. // Visual Studio 7 puts these characters in the output of its
  584. // build process.
  585. for(int i=0; i < length; ++i)
  586. {
  587. if(data[i] == '\0')
  588. {
  589. data[i] = ' ';
  590. }
  591. }
  592. }
  593. if ( output )
  594. {
  595. tempOutput.insert(tempOutput.end(), data, data+length);
  596. }
  597. if(outputflag != OUTPUT_NONE)
  598. {
  599. if(outputflag == OUTPUT_MERGE)
  600. {
  601. cmSystemTools::Stdout(data, length);
  602. }
  603. else
  604. {
  605. if(pipe == cmsysProcess_Pipe_STDERR)
  606. {
  607. cmSystemTools::Stderr(data, length);
  608. }
  609. else if(pipe == cmsysProcess_Pipe_STDOUT)
  610. {
  611. cmSystemTools::Stdout(data, length);
  612. }
  613. }
  614. }
  615. }
  616. }
  617. cmsysProcess_WaitForExit(cp, 0);
  618. if ( output && tempOutput.begin() != tempOutput.end())
  619. {
  620. output->append(&*tempOutput.begin(), tempOutput.size());
  621. }
  622. bool result = true;
  623. if(cmsysProcess_GetState(cp) == cmsysProcess_State_Exited)
  624. {
  625. if ( retVal )
  626. {
  627. *retVal = cmsysProcess_GetExitValue(cp);
  628. }
  629. else
  630. {
  631. if ( cmsysProcess_GetExitValue(cp) != 0 )
  632. {
  633. result = false;
  634. }
  635. }
  636. }
  637. else if(cmsysProcess_GetState(cp) == cmsysProcess_State_Exception)
  638. {
  639. const char* exception_str = cmsysProcess_GetExceptionString(cp);
  640. if ( outputflag != OUTPUT_NONE )
  641. {
  642. std::cerr << exception_str << std::endl;
  643. }
  644. if ( output )
  645. {
  646. output->append(exception_str, strlen(exception_str));
  647. }
  648. result = false;
  649. }
  650. else if(cmsysProcess_GetState(cp) == cmsysProcess_State_Error)
  651. {
  652. const char* error_str = cmsysProcess_GetErrorString(cp);
  653. if ( outputflag != OUTPUT_NONE )
  654. {
  655. std::cerr << error_str << std::endl;
  656. }
  657. if ( output )
  658. {
  659. output->append(error_str, strlen(error_str));
  660. }
  661. result = false;
  662. }
  663. else if(cmsysProcess_GetState(cp) == cmsysProcess_State_Expired)
  664. {
  665. const char* error_str = "Process terminated due to timeout\n";
  666. if ( outputflag != OUTPUT_NONE )
  667. {
  668. std::cerr << error_str << std::endl;
  669. }
  670. if ( output )
  671. {
  672. output->append(error_str, strlen(error_str));
  673. }
  674. result = false;
  675. }
  676. cmsysProcess_Delete(cp);
  677. return result;
  678. }
  679. bool cmSystemTools::RunSingleCommand(
  680. const char* command,
  681. std::string* output,
  682. int *retVal,
  683. const char* dir,
  684. OutputOption outputflag,
  685. double timeout)
  686. {
  687. if(s_DisableRunCommandOutput)
  688. {
  689. outputflag = OUTPUT_NONE;
  690. }
  691. std::vector<std::string> args = cmSystemTools::ParseArguments(command);
  692. if(args.size() < 1)
  693. {
  694. return false;
  695. }
  696. return cmSystemTools::RunSingleCommand(args, output,retVal,
  697. dir, outputflag, timeout);
  698. }
  699. std::string
  700. cmSystemTools::PrintSingleCommand(std::vector<std::string> const& command)
  701. {
  702. std::string commandStr;
  703. const char* sep = "";
  704. for(std::vector<std::string>::const_iterator i = command.begin();
  705. i != command.end(); ++i)
  706. {
  707. commandStr += sep;
  708. commandStr += "\"";
  709. commandStr += *i;
  710. commandStr += "\"";
  711. sep = " ";
  712. }
  713. return commandStr;
  714. }
  715. bool cmSystemTools::DoesFileExistWithExtensions(
  716. const char* name,
  717. const std::vector<std::string>& headerExts)
  718. {
  719. std::string hname;
  720. for( std::vector<std::string>::const_iterator ext = headerExts.begin();
  721. ext != headerExts.end(); ++ext )
  722. {
  723. hname = name;
  724. hname += ".";
  725. hname += *ext;
  726. if(cmSystemTools::FileExists(hname.c_str()))
  727. {
  728. return true;
  729. }
  730. }
  731. return false;
  732. }
  733. std::string cmSystemTools::FileExistsInParentDirectories(const char* fname,
  734. const char* directory, const char* toplevel)
  735. {
  736. std::string file = fname;
  737. cmSystemTools::ConvertToUnixSlashes(file);
  738. std::string dir = directory;
  739. cmSystemTools::ConvertToUnixSlashes(dir);
  740. std::string prevDir;
  741. while(dir != prevDir)
  742. {
  743. std::string path = dir + "/" + file;
  744. if ( cmSystemTools::FileExists(path.c_str()) )
  745. {
  746. return path;
  747. }
  748. if ( dir.size() < strlen(toplevel) )
  749. {
  750. break;
  751. }
  752. prevDir = dir;
  753. dir = cmSystemTools::GetParentDirectory(dir.c_str());
  754. }
  755. return "";
  756. }
  757. bool cmSystemTools::cmCopyFile(const char* source, const char* destination)
  758. {
  759. return Superclass::CopyFileAlways(source, destination);
  760. }
  761. bool cmSystemTools::CopyFileIfDifferent(const char* source,
  762. const char* destination)
  763. {
  764. return Superclass::CopyFileIfDifferent(source, destination);
  765. }
  766. //----------------------------------------------------------------------------
  767. #ifdef _WIN32
  768. cmSystemTools::WindowsFileRetry cmSystemTools::GetWindowsFileRetry()
  769. {
  770. static WindowsFileRetry retry = {0,0};
  771. if(!retry.Count)
  772. {
  773. unsigned int data[2] = {0,0};
  774. HKEY const keys[2] = {HKEY_CURRENT_USER, HKEY_LOCAL_MACHINE};
  775. wchar_t const* const values[2] = {L"FilesystemRetryCount",
  776. L"FilesystemRetryDelay"};
  777. for(int k=0; k < 2; ++k)
  778. {
  779. HKEY hKey;
  780. if(RegOpenKeyExW(keys[k], L"Software\\Kitware\\CMake\\Config",
  781. 0, KEY_QUERY_VALUE, &hKey) == ERROR_SUCCESS)
  782. {
  783. for(int v=0; v < 2; ++v)
  784. {
  785. DWORD dwData, dwType, dwSize = 4;
  786. if(!data[v] &&
  787. RegQueryValueExW(hKey, values[v], 0, &dwType, (BYTE *)&dwData,
  788. &dwSize) == ERROR_SUCCESS &&
  789. dwType == REG_DWORD && dwSize == 4)
  790. {
  791. data[v] = static_cast<unsigned int>(dwData);
  792. }
  793. }
  794. RegCloseKey(hKey);
  795. }
  796. }
  797. retry.Count = data[0]? data[0] : 5;
  798. retry.Delay = data[1]? data[1] : 500;
  799. }
  800. return retry;
  801. }
  802. #endif
  803. //----------------------------------------------------------------------------
  804. bool cmSystemTools::RenameFile(const char* oldname, const char* newname)
  805. {
  806. #ifdef _WIN32
  807. # ifndef INVALID_FILE_ATTRIBUTES
  808. # define INVALID_FILE_ATTRIBUTES ((DWORD)-1)
  809. # endif
  810. /* Windows MoveFileEx may not replace read-only or in-use files. If it
  811. fails then remove the read-only attribute from any existing destination.
  812. Try multiple times since we may be racing against another process
  813. creating/opening the destination file just before our MoveFileEx. */
  814. WindowsFileRetry retry = cmSystemTools::GetWindowsFileRetry();
  815. while(!MoveFileExW(cmsys::Encoding::ToWide(oldname).c_str(),
  816. cmsys::Encoding::ToWide(newname).c_str(),
  817. MOVEFILE_REPLACE_EXISTING) && --retry.Count)
  818. {
  819. // Try again only if failure was due to access permissions.
  820. if(GetLastError() != ERROR_ACCESS_DENIED)
  821. {
  822. return false;
  823. }
  824. DWORD attrs =
  825. GetFileAttributesW(cmsys::Encoding::ToWide(newname).c_str());
  826. if((attrs != INVALID_FILE_ATTRIBUTES) &&
  827. (attrs & FILE_ATTRIBUTE_READONLY))
  828. {
  829. // Remove the read-only attribute from the destination file.
  830. SetFileAttributesW(cmsys::Encoding::ToWide(newname).c_str(),
  831. attrs & ~FILE_ATTRIBUTE_READONLY);
  832. }
  833. else
  834. {
  835. // The file may be temporarily in use so wait a bit.
  836. cmSystemTools::Delay(retry.Delay);
  837. }
  838. }
  839. return retry.Count > 0;
  840. #else
  841. /* On UNIX we have an OS-provided call to do this atomically. */
  842. return rename(oldname, newname) == 0;
  843. #endif
  844. }
  845. bool cmSystemTools::ComputeFileMD5(const std::string& source, char* md5out)
  846. {
  847. #if defined(CMAKE_BUILD_WITH_CMAKE)
  848. cmCryptoHashMD5 md5;
  849. std::string str = md5.HashFile(source);
  850. strncpy(md5out, str.c_str(), 32);
  851. return !str.empty();
  852. #else
  853. (void)source;
  854. (void)md5out;
  855. cmSystemTools::Message("md5sum not supported in bootstrapping mode","Error");
  856. return false;
  857. #endif
  858. }
  859. std::string cmSystemTools::ComputeStringMD5(const std::string& input)
  860. {
  861. #if defined(CMAKE_BUILD_WITH_CMAKE)
  862. cmCryptoHashMD5 md5;
  863. return md5.HashString(input);
  864. #else
  865. (void)input;
  866. cmSystemTools::Message("md5sum not supported in bootstrapping mode","Error");
  867. return "";
  868. #endif
  869. }
  870. void cmSystemTools::Glob(const std::string& directory,
  871. const std::string& regexp,
  872. std::vector<std::string>& files)
  873. {
  874. cmsys::Directory d;
  875. cmsys::RegularExpression reg(regexp.c_str());
  876. if (d.Load(directory.c_str()))
  877. {
  878. size_t numf;
  879. unsigned int i;
  880. numf = d.GetNumberOfFiles();
  881. for (i = 0; i < numf; i++)
  882. {
  883. std::string fname = d.GetFile(i);
  884. if (reg.find(fname))
  885. {
  886. files.push_back(fname);
  887. }
  888. }
  889. }
  890. }
  891. void cmSystemTools::GlobDirs(const std::string& path,
  892. std::vector<std::string>& files)
  893. {
  894. std::string::size_type pos = path.find("/*");
  895. if(pos == std::string::npos)
  896. {
  897. files.push_back(path);
  898. return;
  899. }
  900. std::string startPath = path.substr(0, pos);
  901. std::string finishPath = path.substr(pos+2);
  902. cmsys::Directory d;
  903. if (d.Load(startPath.c_str()))
  904. {
  905. for (unsigned int i = 0; i < d.GetNumberOfFiles(); ++i)
  906. {
  907. if((std::string(d.GetFile(i)) != ".")
  908. && (std::string(d.GetFile(i)) != ".."))
  909. {
  910. std::string fname = startPath;
  911. fname +="/";
  912. fname += d.GetFile(i);
  913. if(cmSystemTools::FileIsDirectory(fname.c_str()))
  914. {
  915. fname += finishPath;
  916. cmSystemTools::GlobDirs(fname, files);
  917. }
  918. }
  919. }
  920. }
  921. }
  922. void cmSystemTools::ExpandList(std::vector<std::string> const& arguments,
  923. std::vector<std::string>& newargs)
  924. {
  925. std::vector<std::string>::const_iterator i;
  926. for(i = arguments.begin();i != arguments.end(); ++i)
  927. {
  928. cmSystemTools::ExpandListArgument(*i, newargs);
  929. }
  930. }
  931. void cmSystemTools::ExpandListArgument(const std::string& arg,
  932. std::vector<std::string>& newargs,
  933. bool emptyArgs)
  934. {
  935. // If argument is empty, it is an empty list.
  936. if(!emptyArgs && arg.empty())
  937. {
  938. return;
  939. }
  940. // if there are no ; in the name then just copy the current string
  941. if(arg.find(';') == std::string::npos)
  942. {
  943. newargs.push_back(arg);
  944. return;
  945. }
  946. std::string newArg;
  947. const char *last = arg.c_str();
  948. // Break the string at non-escaped semicolons not nested in [].
  949. int squareNesting = 0;
  950. for(const char* c = last; *c; ++c)
  951. {
  952. switch(*c)
  953. {
  954. case '\\':
  955. {
  956. // We only want to allow escaping of semicolons. Other
  957. // escapes should not be processed here.
  958. const char* next = c + 1;
  959. if(*next == ';')
  960. {
  961. newArg.append(last, c - last);
  962. // Skip over the escape character
  963. last = c = next;
  964. }
  965. } break;
  966. case '[':
  967. {
  968. ++squareNesting;
  969. } break;
  970. case ']':
  971. {
  972. --squareNesting;
  973. } break;
  974. case ';':
  975. {
  976. // Break the string here if we are not nested inside square
  977. // brackets.
  978. if(squareNesting == 0)
  979. {
  980. newArg.append(last, c - last);
  981. // Skip over the semicolon
  982. last = c + 1;
  983. if ( !newArg.empty() || emptyArgs )
  984. {
  985. // Add the last argument if the string is not empty.
  986. newargs.push_back(newArg);
  987. newArg = "";
  988. }
  989. }
  990. } break;
  991. default:
  992. {
  993. // Just append this character.
  994. } break;
  995. }
  996. }
  997. newArg.append(last);
  998. if ( !newArg.empty() || emptyArgs )
  999. {
  1000. // Add the last argument if the string is not empty.
  1001. newargs.push_back(newArg);
  1002. }
  1003. }
  1004. bool cmSystemTools::SimpleGlob(const std::string& glob,
  1005. std::vector<std::string>& files,
  1006. int type /* = 0 */)
  1007. {
  1008. files.clear();
  1009. if ( glob[glob.size()-1] != '*' )
  1010. {
  1011. return false;
  1012. }
  1013. std::string path = cmSystemTools::GetFilenamePath(glob);
  1014. std::string ppath = cmSystemTools::GetFilenameName(glob);
  1015. ppath = ppath.substr(0, ppath.size()-1);
  1016. if ( path.size() == 0 )
  1017. {
  1018. path = "/";
  1019. }
  1020. bool res = false;
  1021. cmsys::Directory d;
  1022. if (d.Load(path.c_str()))
  1023. {
  1024. for (unsigned int i = 0; i < d.GetNumberOfFiles(); ++i)
  1025. {
  1026. if((std::string(d.GetFile(i)) != ".")
  1027. && (std::string(d.GetFile(i)) != ".."))
  1028. {
  1029. std::string fname = path;
  1030. if ( path[path.size()-1] != '/' )
  1031. {
  1032. fname +="/";
  1033. }
  1034. fname += d.GetFile(i);
  1035. std::string sfname = d.GetFile(i);
  1036. if ( type > 0 && cmSystemTools::FileIsDirectory(fname.c_str()) )
  1037. {
  1038. continue;
  1039. }
  1040. if ( type < 0 && !cmSystemTools::FileIsDirectory(fname.c_str()) )
  1041. {
  1042. continue;
  1043. }
  1044. if ( sfname.size() >= ppath.size() &&
  1045. sfname.substr(0, ppath.size()) ==
  1046. ppath )
  1047. {
  1048. files.push_back(fname);
  1049. res = true;
  1050. }
  1051. }
  1052. }
  1053. }
  1054. return res;
  1055. }
  1056. cmSystemTools::FileFormat cmSystemTools::GetFileFormat(const char* cext)
  1057. {
  1058. if ( ! cext || *cext == 0 )
  1059. {
  1060. return cmSystemTools::NO_FILE_FORMAT;
  1061. }
  1062. //std::string ext = cmSystemTools::LowerCase(cext);
  1063. std::string ext = cext;
  1064. if ( ext == "c" || ext == ".c" ||
  1065. ext == "m" || ext == ".m"
  1066. ) { return cmSystemTools::C_FILE_FORMAT; }
  1067. if (
  1068. ext == "C" || ext == ".C" ||
  1069. ext == "M" || ext == ".M" ||
  1070. ext == "c++" || ext == ".c++" ||
  1071. ext == "cc" || ext == ".cc" ||
  1072. ext == "cpp" || ext == ".cpp" ||
  1073. ext == "cxx" || ext == ".cxx" ||
  1074. ext == "mm" || ext == ".mm"
  1075. ) { return cmSystemTools::CXX_FILE_FORMAT; }
  1076. if (
  1077. ext == "f" || ext == ".f" ||
  1078. ext == "F" || ext == ".F" ||
  1079. ext == "f77" || ext == ".f77" ||
  1080. ext == "f90" || ext == ".f90" ||
  1081. ext == "for" || ext == ".for" ||
  1082. ext == "f95" || ext == ".f95"
  1083. ) { return cmSystemTools::FORTRAN_FILE_FORMAT; }
  1084. if ( ext == "java" || ext == ".java" )
  1085. { return cmSystemTools::JAVA_FILE_FORMAT; }
  1086. if (
  1087. ext == "H" || ext == ".H" ||
  1088. ext == "h" || ext == ".h" ||
  1089. ext == "h++" || ext == ".h++" ||
  1090. ext == "hm" || ext == ".hm" ||
  1091. ext == "hpp" || ext == ".hpp" ||
  1092. ext == "hxx" || ext == ".hxx" ||
  1093. ext == "in" || ext == ".in" ||
  1094. ext == "txx" || ext == ".txx"
  1095. ) { return cmSystemTools::HEADER_FILE_FORMAT; }
  1096. if ( ext == "rc" || ext == ".rc" )
  1097. { return cmSystemTools::RESOURCE_FILE_FORMAT; }
  1098. if ( ext == "def" || ext == ".def" )
  1099. { return cmSystemTools::DEFINITION_FILE_FORMAT; }
  1100. if ( ext == "lib" || ext == ".lib" ||
  1101. ext == "a" || ext == ".a")
  1102. { return cmSystemTools::STATIC_LIBRARY_FILE_FORMAT; }
  1103. if ( ext == "o" || ext == ".o" ||
  1104. ext == "obj" || ext == ".obj")
  1105. { return cmSystemTools::OBJECT_FILE_FORMAT; }
  1106. #ifdef __APPLE__
  1107. if ( ext == "dylib" || ext == ".dylib" )
  1108. { return cmSystemTools::SHARED_LIBRARY_FILE_FORMAT; }
  1109. if ( ext == "so" || ext == ".so" ||
  1110. ext == "bundle" || ext == ".bundle" )
  1111. { return cmSystemTools::MODULE_FILE_FORMAT; }
  1112. #else // __APPLE__
  1113. if ( ext == "so" || ext == ".so" ||
  1114. ext == "sl" || ext == ".sl" ||
  1115. ext == "dll" || ext == ".dll" )
  1116. { return cmSystemTools::SHARED_LIBRARY_FILE_FORMAT; }
  1117. #endif // __APPLE__
  1118. return cmSystemTools::UNKNOWN_FILE_FORMAT;
  1119. }
  1120. bool cmSystemTools::Split(const char* s, std::vector<std::string>& l)
  1121. {
  1122. std::vector<std::string> temp;
  1123. bool res = Superclass::Split(s, temp);
  1124. for(std::vector<std::string>::const_iterator i = temp.begin();
  1125. i != temp.end(); ++i)
  1126. {
  1127. l.push_back(*i);
  1128. }
  1129. return res;
  1130. }
  1131. std::string cmSystemTools::ConvertToOutputPath(const char* path)
  1132. {
  1133. #if defined(_WIN32) && !defined(__CYGWIN__)
  1134. if(s_ForceUnixPaths)
  1135. {
  1136. return cmSystemTools::ConvertToUnixOutputPath(path);
  1137. }
  1138. return cmSystemTools::ConvertToWindowsOutputPath(path);
  1139. #else
  1140. return cmSystemTools::ConvertToUnixOutputPath(path);
  1141. #endif
  1142. }
  1143. void cmSystemTools::ConvertToOutputSlashes(std::string& path)
  1144. {
  1145. #if defined(_WIN32) && !defined(__CYGWIN__)
  1146. if(!s_ForceUnixPaths)
  1147. {
  1148. // Convert to windows slashes.
  1149. std::string::size_type pos = 0;
  1150. while((pos = path.find('/', pos)) != std::string::npos)
  1151. {
  1152. path[pos++] = '\\';
  1153. }
  1154. }
  1155. #else
  1156. static_cast<void>(path);
  1157. #endif
  1158. }
  1159. std::string cmSystemTools::ConvertToRunCommandPath(const char* path)
  1160. {
  1161. #if defined(_WIN32) && !defined(__CYGWIN__)
  1162. return cmSystemTools::ConvertToWindowsOutputPath(path);
  1163. #else
  1164. return cmSystemTools::ConvertToUnixOutputPath(path);
  1165. #endif
  1166. }
  1167. bool cmSystemTools::StringEndsWith(const char* str1, const char* str2)
  1168. {
  1169. if ( !str1 || !str2 || strlen(str1) < strlen(str2) )
  1170. {
  1171. return 0;
  1172. }
  1173. return !strncmp(str1 + (strlen(str1)-strlen(str2)), str2, strlen(str2));
  1174. }
  1175. // compute the relative path from here to there
  1176. std::string cmSystemTools::RelativePath(const char* local, const char* remote)
  1177. {
  1178. if(!cmSystemTools::FileIsFullPath(local))
  1179. {
  1180. cmSystemTools::Error("RelativePath must be passed a full path to local: ",
  1181. local);
  1182. }
  1183. if(!cmSystemTools::FileIsFullPath(remote))
  1184. {
  1185. cmSystemTools::Error
  1186. ("RelativePath must be passed a full path to remote: ", remote);
  1187. }
  1188. return cmsys::SystemTools::RelativePath(local, remote);
  1189. }
  1190. std::string cmSystemTools::CollapseCombinedPath(std::string const& dir,
  1191. std::string const& file)
  1192. {
  1193. if(dir.empty() || dir == ".")
  1194. {
  1195. return file;
  1196. }
  1197. std::vector<std::string> dirComponents;
  1198. std::vector<std::string> fileComponents;
  1199. cmSystemTools::SplitPath(dir.c_str(), dirComponents);
  1200. cmSystemTools::SplitPath(file.c_str(), fileComponents);
  1201. if(fileComponents.empty())
  1202. {
  1203. return dir;
  1204. }
  1205. if(fileComponents[0] != "")
  1206. {
  1207. // File is not a relative path.
  1208. return file;
  1209. }
  1210. std::vector<std::string>::iterator i = fileComponents.begin()+1;
  1211. while(i != fileComponents.end() && *i == ".." && dirComponents.size() > 1)
  1212. {
  1213. ++i; // Remove ".." file component.
  1214. dirComponents.pop_back(); // Remove last dir component.
  1215. }
  1216. dirComponents.insert(dirComponents.end(), i, fileComponents.end());
  1217. return cmSystemTools::JoinPath(dirComponents);
  1218. }
  1219. #ifdef CMAKE_BUILD_WITH_CMAKE
  1220. //----------------------------------------------------------------------
  1221. bool cmSystemTools::UnsetEnv(const char* value)
  1222. {
  1223. #if !defined(HAVE_UNSETENV)
  1224. std::string var = value;
  1225. var += "=";
  1226. return cmSystemTools::PutEnv(var.c_str());
  1227. #else
  1228. unsetenv(value);
  1229. return true;
  1230. #endif
  1231. }
  1232. //----------------------------------------------------------------------
  1233. std::vector<std::string> cmSystemTools::GetEnvironmentVariables()
  1234. {
  1235. std::vector<std::string> env;
  1236. int cc;
  1237. for ( cc = 0; environ[cc]; ++ cc )
  1238. {
  1239. env.push_back(environ[cc]);
  1240. }
  1241. return env;
  1242. }
  1243. //----------------------------------------------------------------------
  1244. void cmSystemTools::AppendEnv(std::vector<std::string> const& env)
  1245. {
  1246. for(std::vector<std::string>::const_iterator eit = env.begin();
  1247. eit != env.end(); ++eit)
  1248. {
  1249. cmSystemTools::PutEnv(eit->c_str());
  1250. }
  1251. }
  1252. //----------------------------------------------------------------------
  1253. cmSystemTools::SaveRestoreEnvironment::SaveRestoreEnvironment()
  1254. {
  1255. this->Env = cmSystemTools::GetEnvironmentVariables();
  1256. }
  1257. //----------------------------------------------------------------------
  1258. cmSystemTools::SaveRestoreEnvironment::~SaveRestoreEnvironment()
  1259. {
  1260. // First clear everything in the current environment:
  1261. std::vector<std::string> currentEnv = GetEnvironmentVariables();
  1262. for(std::vector<std::string>::const_iterator
  1263. eit = currentEnv.begin(); eit != currentEnv.end(); ++eit)
  1264. {
  1265. std::string var(*eit);
  1266. std::string::size_type pos = var.find("=");
  1267. if (pos != std::string::npos)
  1268. {
  1269. var = var.substr(0, pos);
  1270. }
  1271. cmSystemTools::UnsetEnv(var.c_str());
  1272. }
  1273. // Then put back each entry from the original environment:
  1274. cmSystemTools::AppendEnv(this->Env);
  1275. }
  1276. #endif
  1277. void cmSystemTools::EnableVSConsoleOutput()
  1278. {
  1279. #ifdef _WIN32
  1280. // Visual Studio 8 2005 (devenv.exe or VCExpress.exe) will not
  1281. // display output to the console unless this environment variable is
  1282. // set. We need it to capture the output of these build tools.
  1283. // Note for future work that one could pass "/out \\.\pipe\NAME" to
  1284. // either of these executables where NAME is created with
  1285. // CreateNamedPipe. This would bypass the internal buffering of the
  1286. // output and allow it to be captured on the fly.
  1287. cmSystemTools::PutEnv("vsconsoleoutput=1");
  1288. # ifdef CMAKE_BUILD_WITH_CMAKE
  1289. // VS sets an environment variable to tell MS tools like "cl" to report
  1290. // output through a backdoor pipe instead of stdout/stderr. Unset the
  1291. // environment variable to close this backdoor for any path of process
  1292. // invocations that passes through CMake so we can capture the output.
  1293. cmSystemTools::UnsetEnv("VS_UNICODE_OUTPUT");
  1294. # endif
  1295. #endif
  1296. }
  1297. bool cmSystemTools::IsPathToFramework(const char* path)
  1298. {
  1299. if(cmSystemTools::FileIsFullPath(path))
  1300. {
  1301. std::string libname = path;
  1302. if(libname.find(".framework") == libname.size()+1-sizeof(".framework"))
  1303. {
  1304. return true;
  1305. }
  1306. }
  1307. return false;
  1308. }
  1309. bool cmSystemTools::CreateTar(const char* outFileName,
  1310. const std::vector<std::string>& files,
  1311. bool gzip, bool bzip2, bool verbose)
  1312. {
  1313. #if defined(CMAKE_BUILD_WITH_CMAKE)
  1314. std::string cwd = cmSystemTools::GetCurrentWorkingDirectory();
  1315. cmsys::ofstream fout(outFileName, std::ios::out | cmsys_ios_binary);
  1316. if(!fout)
  1317. {
  1318. std::string e = "Cannot open output file \"";
  1319. e += outFileName;
  1320. e += "\": ";
  1321. e += cmSystemTools::GetLastSystemError();
  1322. cmSystemTools::Error(e.c_str());
  1323. return false;
  1324. }
  1325. cmArchiveWrite a(fout, (gzip? cmArchiveWrite::CompressGZip :
  1326. (bzip2? cmArchiveWrite::CompressBZip2 :
  1327. cmArchiveWrite::CompressNone)),
  1328. cmArchiveWrite::TypeTAR);
  1329. a.SetVerbose(verbose);
  1330. for(std::vector<std::string>::const_iterator i = files.begin();
  1331. i != files.end(); ++i)
  1332. {
  1333. std::string path = *i;
  1334. if(cmSystemTools::FileIsFullPath(path.c_str()))
  1335. {
  1336. // Get the relative path to the file.
  1337. path = cmSystemTools::RelativePath(cwd.c_str(), path.c_str());
  1338. }
  1339. if(!a.Add(path))
  1340. {
  1341. break;
  1342. }
  1343. }
  1344. if(!a)
  1345. {
  1346. cmSystemTools::Error(a.GetError().c_str());
  1347. return false;
  1348. }
  1349. return true;
  1350. #else
  1351. (void)outFileName;
  1352. (void)files;
  1353. (void)gzip;
  1354. (void)verbose;
  1355. return false;
  1356. #endif
  1357. }
  1358. #if defined(CMAKE_BUILD_WITH_CMAKE)
  1359. namespace{
  1360. #define BSDTAR_FILESIZE_PRINTF "%lu"
  1361. #define BSDTAR_FILESIZE_TYPE unsigned long
  1362. void
  1363. list_item_verbose(FILE *out, struct archive_entry *entry)
  1364. {
  1365. char tmp[100];
  1366. size_t w;
  1367. const char *p;
  1368. const char *fmt;
  1369. time_t tim;
  1370. static time_t now;
  1371. size_t u_width = 6;
  1372. size_t gs_width = 13;
  1373. /*
  1374. * We avoid collecting the entire list in memory at once by
  1375. * listing things as we see them. However, that also means we can't
  1376. * just pre-compute the field widths. Instead, we start with guesses
  1377. * and just widen them as necessary. These numbers are completely
  1378. * arbitrary.
  1379. */
  1380. if (!now)
  1381. {
  1382. time(&now);
  1383. }
  1384. fprintf(out, "%s %d ",
  1385. archive_entry_strmode(entry),
  1386. archive_entry_nlink(entry));
  1387. /* Use uname if it's present, else uid. */
  1388. p = archive_entry_uname(entry);
  1389. if ((p == NULL) || (*p == '\0'))
  1390. {
  1391. sprintf(tmp, "%lu ",
  1392. (unsigned long)archive_entry_uid(entry));
  1393. p = tmp;
  1394. }
  1395. w = strlen(p);
  1396. if (w > u_width)
  1397. {
  1398. u_width = w;
  1399. }
  1400. fprintf(out, "%-*s ", (int)u_width, p);
  1401. /* Use gname if it's present, else gid. */
  1402. p = archive_entry_gname(entry);
  1403. if (p != NULL && p[0] != '\0')
  1404. {
  1405. fprintf(out, "%s", p);
  1406. w = strlen(p);
  1407. }
  1408. else
  1409. {
  1410. sprintf(tmp, "%lu",
  1411. (unsigned long)archive_entry_gid(entry));
  1412. w = strlen(tmp);
  1413. fprintf(out, "%s", tmp);
  1414. }
  1415. /*
  1416. * Print device number or file size, right-aligned so as to make
  1417. * total width of group and devnum/filesize fields be gs_width.
  1418. * If gs_width is too small, grow it.
  1419. */
  1420. if (archive_entry_filetype(entry) == AE_IFCHR
  1421. || archive_entry_filetype(entry) == AE_IFBLK)
  1422. {
  1423. sprintf(tmp, "%lu,%lu",
  1424. (unsigned long)archive_entry_rdevmajor(entry),
  1425. (unsigned long)archive_entry_rdevminor(entry));
  1426. }
  1427. else
  1428. {
  1429. /*
  1430. * Note the use of platform-dependent macros to format
  1431. * the filesize here. We need the format string and the
  1432. * corresponding type for the cast.
  1433. */
  1434. sprintf(tmp, BSDTAR_FILESIZE_PRINTF,
  1435. (BSDTAR_FILESIZE_TYPE)archive_entry_size(entry));
  1436. }
  1437. if (w + strlen(tmp) >= gs_width)
  1438. {
  1439. gs_width = w+strlen(tmp)+1;
  1440. }
  1441. fprintf(out, "%*s", (int)(gs_width - w), tmp);
  1442. /* Format the time using 'ls -l' conventions. */
  1443. tim = archive_entry_mtime(entry);
  1444. #define HALF_YEAR (time_t)365 * 86400 / 2
  1445. #if defined(_WIN32) && !defined(__CYGWIN__)
  1446. /* Windows' strftime function does not support %e format. */
  1447. #define DAY_FMT "%d"
  1448. #else
  1449. #define DAY_FMT "%e" /* Day number without leading zeros */
  1450. #endif
  1451. if (tim < now - HALF_YEAR || tim > now + HALF_YEAR)
  1452. {
  1453. fmt = DAY_FMT " %b %Y";
  1454. }
  1455. else
  1456. {
  1457. fmt = DAY_FMT " %b %H:%M";
  1458. }
  1459. strftime(tmp, sizeof(tmp), fmt, localtime(&tim));
  1460. fprintf(out, " %s ", tmp);
  1461. fprintf(out, "%s", archive_entry_pathname(entry));
  1462. /* Extra information for links. */
  1463. if (archive_entry_hardlink(entry)) /* Hard link */
  1464. {
  1465. fprintf(out, " link to %s",
  1466. archive_entry_hardlink(entry));
  1467. }
  1468. else if (archive_entry_symlink(entry)) /* Symbolic link */
  1469. {
  1470. fprintf(out, " -> %s", archive_entry_symlink(entry));
  1471. }
  1472. }
  1473. #ifdef __BORLANDC__
  1474. # pragma warn -8066 /* unreachable code */
  1475. #endif
  1476. long copy_data(struct archive *ar, struct archive *aw)
  1477. {
  1478. long r;
  1479. const void *buff;
  1480. size_t size;
  1481. #if defined(ARCHIVE_VERSION_NUMBER) && ARCHIVE_VERSION_NUMBER >= 3000000
  1482. __LA_INT64_T offset;
  1483. #else
  1484. off_t offset;
  1485. #endif
  1486. for (;;)
  1487. {
  1488. r = archive_read_data_block(ar, &buff, &size, &offset);
  1489. if (r == ARCHIVE_EOF)
  1490. {
  1491. return (ARCHIVE_OK);
  1492. }
  1493. if (r != ARCHIVE_OK)
  1494. {
  1495. return (r);
  1496. }
  1497. r = archive_write_data_block(aw, buff, size, offset);
  1498. if (r != ARCHIVE_OK)
  1499. {
  1500. cmSystemTools::Message("archive_write_data_block()",
  1501. archive_error_string(aw));
  1502. return (r);
  1503. }
  1504. }
  1505. }
  1506. bool extract_tar(const char* outFileName, bool verbose,
  1507. bool extract)
  1508. {
  1509. struct archive* a = archive_read_new();
  1510. struct archive *ext = archive_write_disk_new();
  1511. archive_read_support_compression_all(a);
  1512. archive_read_support_format_all(a);
  1513. struct archive_entry *entry;
  1514. int r = archive_read_open_file(a, outFileName, 10240);
  1515. if(r)
  1516. {
  1517. cmSystemTools::Error("Problem with archive_read_open_file(): ",
  1518. archive_error_string(a));
  1519. return false;
  1520. }
  1521. for (;;)
  1522. {
  1523. r = archive_read_next_header(a, &entry);
  1524. if (r == ARCHIVE_EOF)
  1525. {
  1526. break;
  1527. }
  1528. if (r != ARCHIVE_OK)
  1529. {
  1530. cmSystemTools::Error("Problem with archive_read_next_header(): ",
  1531. archive_error_string(a));
  1532. break;
  1533. }
  1534. if(verbose)
  1535. {
  1536. if(extract)
  1537. {
  1538. cmSystemTools::Stdout("x ");
  1539. cmSystemTools::Stdout(archive_entry_pathname(entry));
  1540. }
  1541. else
  1542. {
  1543. list_item_verbose(stdout, entry);
  1544. }
  1545. cmSystemTools::Stdout("\n");
  1546. }
  1547. else if(!extract)
  1548. {
  1549. cmSystemTools::Stdout(archive_entry_pathname(entry));
  1550. cmSystemTools::Stdout("\n");
  1551. }
  1552. if(extract)
  1553. {
  1554. r = archive_write_disk_set_options(ext, ARCHIVE_EXTRACT_TIME);
  1555. if (r != ARCHIVE_OK)
  1556. {
  1557. cmSystemTools::Error(
  1558. "Problem with archive_write_disk_set_options(): ",
  1559. archive_error_string(ext));
  1560. break;
  1561. }
  1562. r = archive_write_header(ext, entry);
  1563. if (r == ARCHIVE_OK)
  1564. {
  1565. copy_data(a, ext);
  1566. r = archive_write_finish_entry(ext);
  1567. if (r != ARCHIVE_OK)
  1568. {
  1569. cmSystemTools::Error("Problem with archive_write_finish_entry(): ",
  1570. archive_error_string(ext));
  1571. break;
  1572. }
  1573. }
  1574. #ifdef _WIN32
  1575. else if(const char* linktext = archive_entry_symlink(entry))
  1576. {
  1577. std::cerr << "cmake -E tar: warning: skipping symbolic link \""
  1578. << archive_entry_pathname(entry) << "\" -> \""
  1579. << linktext << "\"." << std::endl;
  1580. }
  1581. #endif
  1582. else
  1583. {
  1584. cmSystemTools::Error("Problem with archive_write_header(): ",
  1585. archive_error_string(ext));
  1586. cmSystemTools::Error("Current file: ",
  1587. archive_entry_pathname(entry));
  1588. break;
  1589. }
  1590. }
  1591. }
  1592. archive_read_close(a);
  1593. archive_read_finish(a);
  1594. return r == ARCHIVE_EOF || r == ARCHIVE_OK;
  1595. }
  1596. }
  1597. #endif
  1598. bool cmSystemTools::ExtractTar(const char* outFileName,
  1599. bool , bool verbose)
  1600. {
  1601. #if defined(CMAKE_BUILD_WITH_CMAKE)
  1602. return extract_tar(outFileName, verbose, true);
  1603. #else
  1604. (void)outFileName;
  1605. (void)verbose;
  1606. return false;
  1607. #endif
  1608. }
  1609. bool cmSystemTools::ListTar(const char* outFileName,
  1610. bool ,
  1611. bool verbose)
  1612. {
  1613. #if defined(CMAKE_BUILD_WITH_CMAKE)
  1614. return extract_tar(outFileName, verbose, false);
  1615. #else
  1616. (void)outFileName;
  1617. (void)verbose;
  1618. return false;
  1619. #endif
  1620. }
  1621. int cmSystemTools::WaitForLine(cmsysProcess* process, std::string& line,
  1622. double timeout,
  1623. std::vector<char>& out,
  1624. std::vector<char>& err)
  1625. {
  1626. line = "";
  1627. std::vector<char>::iterator outiter = out.begin();
  1628. std::vector<char>::iterator erriter = err.begin();
  1629. while(1)
  1630. {
  1631. // Check for a newline in stdout.
  1632. for(;outiter != out.end(); ++outiter)
  1633. {
  1634. if((*outiter == '\r') && ((outiter+1) == out.end()))
  1635. {
  1636. break;
  1637. }
  1638. else if(*outiter == '\n' || *outiter == '\0')
  1639. {
  1640. std::vector<char>::size_type length = outiter-out.begin();
  1641. if(length > 1 && *(outiter-1) == '\r')
  1642. {
  1643. --length;
  1644. }
  1645. if(length > 0)
  1646. {
  1647. line.append(&out[0], length);
  1648. }
  1649. out.erase(out.begin(), outiter+1);
  1650. return cmsysProcess_Pipe_STDOUT;
  1651. }
  1652. }
  1653. // Check for a newline in stderr.
  1654. for(;erriter != err.end(); ++erriter)
  1655. {
  1656. if((*erriter == '\r') && ((erriter+1) == err.end()))
  1657. {
  1658. break;
  1659. }
  1660. else if(*erriter == '\n' || *erriter == '\0')
  1661. {
  1662. std::vector<char>::size_type length = erriter-err.begin();
  1663. if(length > 1 && *(erriter-1) == '\r')
  1664. {
  1665. --length;
  1666. }
  1667. if(length > 0)
  1668. {
  1669. line.append(&err[0], length);
  1670. }
  1671. err.erase(err.begin(), erriter+1);
  1672. return cmsysProcess_Pipe_STDERR;
  1673. }
  1674. }
  1675. // No newlines found. Wait for more data from the process.
  1676. int length;
  1677. char* data;
  1678. int pipe = cmsysProcess_WaitForData(process, &data, &length, &timeout);
  1679. if(pipe == cmsysProcess_Pipe_Timeout)
  1680. {
  1681. // Timeout has been exceeded.
  1682. return pipe;
  1683. }
  1684. else if(pipe == cmsysProcess_Pipe_STDOUT)
  1685. {
  1686. // Append to the stdout buffer.
  1687. std::vector<char>::size_type size = out.size();
  1688. out.insert(out.end(), data, data+length);
  1689. outiter = out.begin()+size;
  1690. }
  1691. else if(pipe == cmsysProcess_Pipe_STDERR)
  1692. {
  1693. // Append to the stderr buffer.
  1694. std::vector<char>::size_type size = err.size();
  1695. err.insert(err.end(), data, data+length);
  1696. erriter = err.begin()+size;
  1697. }
  1698. else if(pipe == cmsysProcess_Pipe_None)
  1699. {
  1700. // Both stdout and stderr pipes have broken. Return leftover data.
  1701. if(!out.empty())
  1702. {
  1703. line.append(&out[0], outiter-out.begin());
  1704. out.erase(out.begin(), out.end());
  1705. return cmsysProcess_Pipe_STDOUT;
  1706. }
  1707. else if(!err.empty())
  1708. {
  1709. line.append(&err[0], erriter-err.begin());
  1710. err.erase(err.begin(), err.end());
  1711. return cmsysProcess_Pipe_STDERR;
  1712. }
  1713. else
  1714. {
  1715. return cmsysProcess_Pipe_None;
  1716. }
  1717. }
  1718. }
  1719. }
  1720. void cmSystemTools::DoNotInheritStdPipes()
  1721. {
  1722. #ifdef _WIN32
  1723. // Check to see if we are attached to a console
  1724. // if so, then do not stop the inherited pipes
  1725. // or stdout and stderr will not show up in dos
  1726. // shell windows
  1727. CONSOLE_SCREEN_BUFFER_INFO hOutInfo;
  1728. HANDLE hOut = GetStdHandle(STD_OUTPUT_HANDLE);
  1729. if(GetConsoleScreenBufferInfo(hOut, &hOutInfo))
  1730. {
  1731. return;
  1732. }
  1733. {
  1734. HANDLE out = GetStdHandle(STD_OUTPUT_HANDLE);
  1735. DuplicateHandle(GetCurrentProcess(), out,
  1736. GetCurrentProcess(), &out, 0, FALSE,
  1737. DUPLICATE_SAME_ACCESS | DUPLICATE_CLOSE_SOURCE);
  1738. SetStdHandle(STD_OUTPUT_HANDLE, out);
  1739. }
  1740. {
  1741. HANDLE out = GetStdHandle(STD_ERROR_HANDLE);
  1742. DuplicateHandle(GetCurrentProcess(), out,
  1743. GetCurrentProcess(), &out, 0, FALSE,
  1744. DUPLICATE_SAME_ACCESS | DUPLICATE_CLOSE_SOURCE);
  1745. SetStdHandle(STD_ERROR_HANDLE, out);
  1746. }
  1747. #endif
  1748. }
  1749. //----------------------------------------------------------------------------
  1750. bool cmSystemTools::CopyFileTime(const char* fromFile, const char* toFile)
  1751. {
  1752. #if defined(_WIN32) && !defined(__CYGWIN__)
  1753. cmSystemToolsWindowsHandle hFrom =
  1754. CreateFileW(cmsys::Encoding::ToWide(fromFile).c_str(),
  1755. GENERIC_READ, FILE_SHARE_READ, 0,
  1756. OPEN_EXISTING, 0, 0);
  1757. cmSystemToolsWindowsHandle hTo =
  1758. CreateFileW(cmsys::Encoding::ToWide(toFile).c_str(),
  1759. GENERIC_WRITE, 0, 0, OPEN_EXISTING, 0, 0);
  1760. if(!hFrom || !hTo)
  1761. {
  1762. return false;
  1763. }
  1764. FILETIME timeCreation;
  1765. FILETIME timeLastAccess;
  1766. FILETIME timeLastWrite;
  1767. if(!GetFileTime(hFrom, &timeCreation, &timeLastAccess, &timeLastWrite))
  1768. {
  1769. return false;
  1770. }
  1771. if(!SetFileTime(hTo, &timeCreation, &timeLastAccess, &timeLastWrite))
  1772. {
  1773. return false;
  1774. }
  1775. #else
  1776. struct stat fromStat;
  1777. if(stat(fromFile, &fromStat) < 0)
  1778. {
  1779. return false;
  1780. }
  1781. struct utimbuf buf;
  1782. buf.actime = fromStat.st_atime;
  1783. buf.modtime = fromStat.st_mtime;
  1784. if(utime(toFile, &buf) < 0)
  1785. {
  1786. return false;
  1787. }
  1788. #endif
  1789. return true;
  1790. }
  1791. //----------------------------------------------------------------------------
  1792. cmSystemToolsFileTime* cmSystemTools::FileTimeNew()
  1793. {
  1794. return new cmSystemToolsFileTime;
  1795. }
  1796. //----------------------------------------------------------------------------
  1797. void cmSystemTools::FileTimeDelete(cmSystemToolsFileTime* t)
  1798. {
  1799. delete t;
  1800. }
  1801. //----------------------------------------------------------------------------
  1802. bool cmSystemTools::FileTimeGet(const char* fname, cmSystemToolsFileTime* t)
  1803. {
  1804. #if defined(_WIN32) && !defined(__CYGWIN__)
  1805. cmSystemToolsWindowsHandle h =
  1806. CreateFileW(cmsys::Encoding::ToWide(fname).c_str(),
  1807. GENERIC_READ, FILE_SHARE_READ, 0, OPEN_EXISTING, 0, 0);
  1808. if(!h)
  1809. {
  1810. return false;
  1811. }
  1812. if(!GetFileTime(h, &t->timeCreation, &t->timeLastAccess, &t->timeLastWrite))
  1813. {
  1814. return false;
  1815. }
  1816. #else
  1817. struct stat st;
  1818. if(stat(fname, &st) < 0)
  1819. {
  1820. return false;
  1821. }
  1822. t->timeBuf.actime = st.st_atime;
  1823. t->timeBuf.modtime = st.st_mtime;
  1824. #endif
  1825. return true;
  1826. }
  1827. //----------------------------------------------------------------------------
  1828. bool cmSystemTools::FileTimeSet(const char* fname, cmSystemToolsFileTime* t)
  1829. {
  1830. #if defined(_WIN32) && !defined(__CYGWIN__)
  1831. cmSystemToolsWindowsHandle h =
  1832. CreateFileW(cmsys::Encoding::ToWide(fname).c_str(),
  1833. GENERIC_WRITE, 0, 0, OPEN_EXISTING, 0, 0);
  1834. if(!h)
  1835. {
  1836. return false;
  1837. }
  1838. if(!SetFileTime(h, &t->timeCreation, &t->timeLastAccess, &t->timeLastWrite))
  1839. {
  1840. return false;
  1841. }
  1842. #else
  1843. if(utime(fname, &t->timeBuf) < 0)
  1844. {
  1845. return false;
  1846. }
  1847. #endif
  1848. return true;
  1849. }
  1850. //----------------------------------------------------------------------------
  1851. #ifdef _WIN32
  1852. # ifndef CRYPT_SILENT
  1853. # define CRYPT_SILENT 0x40 /* Not defined by VS 6 version of header. */
  1854. # endif
  1855. static int WinCryptRandom(void* data, size_t size)
  1856. {
  1857. int result = 0;
  1858. HCRYPTPROV hProvider = 0;
  1859. if(CryptAcquireContextW(&hProvider, 0, 0, PROV_RSA_FULL,
  1860. CRYPT_VERIFYCONTEXT | CRYPT_SILENT))
  1861. {
  1862. result = CryptGenRandom(hProvider, (DWORD)size, (BYTE*)data)? 1:0;
  1863. CryptReleaseContext(hProvider, 0);
  1864. }
  1865. return result;
  1866. }
  1867. #endif
  1868. //----------------------------------------------------------------------------
  1869. unsigned int cmSystemTools::RandomSeed()
  1870. {
  1871. #if defined(_WIN32) && !defined(__CYGWIN__)
  1872. unsigned int seed = 0;
  1873. // Try using a real random source.
  1874. if(WinCryptRandom(&seed, sizeof(seed)))
  1875. {
  1876. return seed;
  1877. }
  1878. // Fall back to the time and pid.
  1879. FILETIME ft;
  1880. GetSystemTimeAsFileTime(&ft);
  1881. unsigned int t1 = static_cast<unsigned int>(ft.dwHighDateTime);
  1882. unsigned int t2 = static_cast<unsigned int>(ft.dwLowDateTime);
  1883. unsigned int pid = static_cast<unsigned int>(GetCurrentProcessId());
  1884. return t1 ^ t2 ^ pid;
  1885. #else
  1886. union
  1887. {
  1888. unsigned int integer;
  1889. char bytes[sizeof(unsigned int)];
  1890. } seed;
  1891. // Try using a real random source.
  1892. cmsys::ifstream fin("/dev/urandom");
  1893. if(fin && fin.read(seed.bytes, sizeof(seed)) &&
  1894. fin.gcount() == sizeof(seed))
  1895. {
  1896. return seed.integer;
  1897. }
  1898. // Fall back to the time and pid.
  1899. struct timeval t;
  1900. gettimeofday(&t, 0);
  1901. unsigned int pid = static_cast<unsigned int>(getpid());
  1902. unsigned int tv_sec = static_cast<unsigned int>(t.tv_sec);
  1903. unsigned int tv_usec = static_cast<unsigned int>(t.tv_usec);
  1904. // Since tv_usec never fills more than 11 bits we shift it to fill
  1905. // in the slow-changing high-order bits of tv_sec.
  1906. return tv_sec ^ (tv_usec << 21) ^ pid;
  1907. #endif
  1908. }
  1909. //----------------------------------------------------------------------------
  1910. static std::string cmSystemToolsCMakeCommand;
  1911. static std::string cmSystemToolsCTestCommand;
  1912. static std::string cmSystemToolsCPackCommand;
  1913. static std::string cmSystemToolsCMakeCursesCommand;
  1914. static std::string cmSystemToolsCMakeGUICommand;
  1915. static std::string cmSystemToolsCMakeRoot;
  1916. void cmSystemTools::FindCMakeResources(const char* argv0)
  1917. {
  1918. std::string exe_dir;
  1919. #if defined(_WIN32) && !defined(__CYGWIN__)
  1920. (void)argv0; // ignore this on windows
  1921. wchar_t modulepath[_MAX_PATH];
  1922. ::GetModuleFileNameW(NULL, modulepath, sizeof(modulepath));
  1923. exe_dir =
  1924. cmSystemTools::GetFilenamePath(cmsys::Encoding::ToNarrow(modulepath));
  1925. #elif defined(__APPLE__)
  1926. (void)argv0; // ignore this on OS X
  1927. # define CM_EXE_PATH_LOCAL_SIZE 16384
  1928. char exe_path_local[CM_EXE_PATH_LOCAL_SIZE];
  1929. # if defined(MAC_OS_X_VERSION_10_3) && !defined(MAC_OS_X_VERSION_10_4)
  1930. unsigned long exe_path_size = CM_EXE_PATH_LOCAL_SIZE;
  1931. # else
  1932. uint32_t exe_path_size = CM_EXE_PATH_LOCAL_SIZE;
  1933. # endif
  1934. # undef CM_EXE_PATH_LOCAL_SIZE
  1935. char* exe_path = exe_path_local;
  1936. if(_NSGetExecutablePath(exe_path, &exe_path_size) < 0)
  1937. {
  1938. exe_path = (char*)malloc(exe_path_size);
  1939. _NSGetExecutablePath(exe_path, &exe_path_size);
  1940. }
  1941. exe_dir =
  1942. cmSystemTools::GetFilenamePath(
  1943. cmSystemTools::GetRealPath(exe_path));
  1944. if(exe_path != exe_path_local)
  1945. {
  1946. free(exe_path);
  1947. }
  1948. if(cmSystemTools::GetFilenameName(exe_dir) == "MacOS")
  1949. {
  1950. // The executable is inside an application bundle.
  1951. // Look for ../bin (install tree) and then fall back to
  1952. // ../../../bin (build tree).
  1953. exe_dir = cmSystemTools::GetFilenamePath(exe_dir);
  1954. if(cmSystemTools::FileExists((exe_dir+"/bin/cmake").c_str()))
  1955. {
  1956. exe_dir += "/bin";
  1957. }
  1958. else
  1959. {
  1960. exe_dir = cmSystemTools::GetFilenamePath(exe_dir);
  1961. exe_dir = cmSystemTools::GetFilenamePath(exe_dir);
  1962. }
  1963. }
  1964. #else
  1965. std::string errorMsg;
  1966. std::string exe;
  1967. if(cmSystemTools::FindProgramPath(argv0, exe, errorMsg))
  1968. {
  1969. // remove symlinks
  1970. exe = cmSystemTools::GetRealPath(exe.c_str());
  1971. exe_dir =
  1972. cmSystemTools::GetFilenamePath(exe);
  1973. }
  1974. else
  1975. {
  1976. // ???
  1977. }
  1978. #endif
  1979. cmSystemToolsCMakeCommand = exe_dir;
  1980. cmSystemToolsCMakeCommand += "/cmake";
  1981. cmSystemToolsCMakeCommand += cmSystemTools::GetExecutableExtension();
  1982. cmSystemToolsCTestCommand = exe_dir;
  1983. cmSystemToolsCTestCommand += "/ctest";
  1984. cmSystemToolsCTestCommand += cmSystemTools::GetExecutableExtension();
  1985. cmSystemToolsCPackCommand = exe_dir;
  1986. cmSystemToolsCPackCommand += "/cpack";
  1987. cmSystemToolsCPackCommand += cmSystemTools::GetExecutableExtension();
  1988. cmSystemToolsCMakeGUICommand = exe_dir;
  1989. cmSystemToolsCMakeGUICommand += "/cmake-gui";
  1990. cmSystemToolsCMakeGUICommand += cmSystemTools::GetExecutableExtension();
  1991. if(!cmSystemTools::FileExists(cmSystemToolsCMakeGUICommand.c_str()))
  1992. {
  1993. cmSystemToolsCMakeGUICommand = "";
  1994. }
  1995. cmSystemToolsCMakeCursesCommand = exe_dir;
  1996. cmSystemToolsCMakeCursesCommand += "/ccmake";
  1997. cmSystemToolsCMakeCursesCommand += cmSystemTools::GetExecutableExtension();
  1998. if(!cmSystemTools::FileExists(cmSystemToolsCMakeCursesCommand.c_str()))
  1999. {
  2000. cmSystemToolsCMakeCursesCommand = "";
  2001. }
  2002. #ifdef CMAKE_BUILD_WITH_CMAKE
  2003. // Install tree has "<prefix>/bin/cmake" and "<prefix><CMAKE_DATA_DIR>".
  2004. std::string dir = cmSystemTools::GetFilenamePath(exe_dir);
  2005. cmSystemToolsCMakeRoot = dir + CMAKE_DATA_DIR;
  2006. if(!cmSystemTools::FileExists(
  2007. (cmSystemToolsCMakeRoot+"/Modules/CMake.cmake").c_str()))
  2008. {
  2009. // Build tree has "<build>/bin[/<config>]/cmake" and
  2010. // "<build>/CMakeFiles/CMakeSourceDir.txt".
  2011. std::string src_dir_txt = dir + "/CMakeFiles/CMakeSourceDir.txt";
  2012. cmsys::ifstream fin(src_dir_txt.c_str());
  2013. std::string src_dir;
  2014. if(fin && cmSystemTools::GetLineFromStream(fin, src_dir) &&
  2015. cmSystemTools::FileIsDirectory(src_dir.c_str()))
  2016. {
  2017. cmSystemToolsCMakeRoot = src_dir;
  2018. }
  2019. else
  2020. {
  2021. dir = cmSystemTools::GetFilenamePath(dir);
  2022. src_dir_txt = dir + "/CMakeFiles/CMakeSourceDir.txt";
  2023. cmsys::ifstream fin2(src_dir_txt.c_str());
  2024. if(fin2 && cmSystemTools::GetLineFromStream(fin2, src_dir) &&
  2025. cmSystemTools::FileIsDirectory(src_dir.c_str()))
  2026. {
  2027. cmSystemToolsCMakeRoot = src_dir;
  2028. }
  2029. }
  2030. }
  2031. #else
  2032. // Bootstrap build knows its source.
  2033. cmSystemToolsCMakeRoot = CMAKE_ROOT_DIR;
  2034. #endif
  2035. }
  2036. //----------------------------------------------------------------------------
  2037. std::string const& cmSystemTools::GetCMakeCommand()
  2038. {
  2039. return cmSystemToolsCMakeCommand;
  2040. }
  2041. //----------------------------------------------------------------------------
  2042. std::string const& cmSystemTools::GetCTestCommand()
  2043. {
  2044. return cmSystemToolsCTestCommand;
  2045. }
  2046. //----------------------------------------------------------------------------
  2047. std::string const& cmSystemTools::GetCPackCommand()
  2048. {
  2049. return cmSystemToolsCPackCommand;
  2050. }
  2051. //----------------------------------------------------------------------------
  2052. std::string const& cmSystemTools::GetCMakeCursesCommand()
  2053. {
  2054. return cmSystemToolsCMakeCursesCommand;
  2055. }
  2056. //----------------------------------------------------------------------------
  2057. std::string const& cmSystemTools::GetCMakeGUICommand()
  2058. {
  2059. return cmSystemToolsCMakeGUICommand;
  2060. }
  2061. //----------------------------------------------------------------------------
  2062. std::string const& cmSystemTools::GetCMakeRoot()
  2063. {
  2064. return cmSystemToolsCMakeRoot;
  2065. }
  2066. //----------------------------------------------------------------------------
  2067. #if defined(CMAKE_BUILD_WITH_CMAKE)
  2068. void cmSystemTools::MakefileColorEcho(int color, const char* message,
  2069. bool newline, bool enabled)
  2070. {
  2071. // On some platforms (an MSYS prompt) cmsysTerminal may not be able
  2072. // to determine whether the stream is displayed on a tty. In this
  2073. // case it assumes no unless we tell it otherwise. Since we want
  2074. // color messages to be displayed for users we will assume yes.
  2075. // However, we can test for some situations when the answer is most
  2076. // likely no.
  2077. int assumeTTY = cmsysTerminal_Color_AssumeTTY;
  2078. if(cmSystemTools::GetEnv("DART_TEST_FROM_DART") ||
  2079. cmSystemTools::GetEnv("DASHBOARD_TEST_FROM_CTEST") ||
  2080. cmSystemTools::GetEnv("CTEST_INTERACTIVE_DEBUG_MODE"))
  2081. {
  2082. // Avoid printing color escapes during dashboard builds.
  2083. assumeTTY = 0;
  2084. }
  2085. if(enabled)
  2086. {
  2087. cmsysTerminal_cfprintf(color | assumeTTY, stdout, "%s%s",
  2088. message, newline? "\n" : "");
  2089. }
  2090. else
  2091. {
  2092. // Color is disabled. Print without color.
  2093. fprintf(stdout, "%s%s", message, newline? "\n" : "");
  2094. }
  2095. }
  2096. #endif
  2097. //----------------------------------------------------------------------------
  2098. bool cmSystemTools::GuessLibrarySOName(std::string const& fullPath,
  2099. std::string& soname)
  2100. {
  2101. // For ELF shared libraries use a real parser to get the correct
  2102. // soname.
  2103. #if defined(CMAKE_USE_ELF_PARSER)
  2104. cmELF elf(fullPath.c_str());
  2105. if(elf)
  2106. {
  2107. return elf.GetSOName(soname);
  2108. }
  2109. #endif
  2110. // If the file is not a symlink we have no guess for its soname.
  2111. if(!cmSystemTools::FileIsSymlink(fullPath.c_str()))
  2112. {
  2113. return false;
  2114. }
  2115. if(!cmSystemTools::ReadSymlink(fullPath.c_str(), soname))
  2116. {
  2117. return false;
  2118. }
  2119. // If the symlink has a path component we have no guess for the soname.
  2120. if(!cmSystemTools::GetFilenamePath(soname).empty())
  2121. {
  2122. return false;
  2123. }
  2124. // If the symlink points at an extended version of the same name
  2125. // assume it is the soname.
  2126. std::string name = cmSystemTools::GetFilenameName(fullPath);
  2127. if(soname.length() > name.length() &&
  2128. soname.substr(0, name.length()) == name)
  2129. {
  2130. return true;
  2131. }
  2132. return false;
  2133. }
  2134. //----------------------------------------------------------------------------
  2135. bool cmSystemTools::GuessLibraryInstallName(std::string const& fullPath,
  2136. std::string& soname)
  2137. {
  2138. std::vector<std::string> cmds;
  2139. cmds.push_back("otool");
  2140. cmds.push_back("-D");
  2141. cmds.push_back(fullPath);
  2142. std::string output;
  2143. if(!RunSingleCommand(cmds, &output, 0, 0, OUTPUT_NONE))
  2144. {
  2145. cmds.insert(cmds.begin(), "-r");
  2146. cmds.insert(cmds.begin(), "xcrun");
  2147. if(!RunSingleCommand(cmds, &output, 0, 0, OUTPUT_NONE))
  2148. {
  2149. return false;
  2150. }
  2151. }
  2152. std::vector<std::string> strs = cmSystemTools::tokenize(output, "\n");
  2153. // otool returns extra lines reporting multiple install names
  2154. // in case the binary is multi-arch and none of the architectures
  2155. // is native (e.g. i386;ppc on x86_64)
  2156. if(strs.size() >= 2)
  2157. {
  2158. soname = strs[1];
  2159. return true;
  2160. }
  2161. return false;
  2162. }
  2163. //----------------------------------------------------------------------------
  2164. #if defined(CMAKE_USE_ELF_PARSER)
  2165. std::string::size_type cmSystemToolsFindRPath(std::string const& have,
  2166. std::string const& want)
  2167. {
  2168. // Search for the desired rpath.
  2169. std::string::size_type pos = have.find(want);
  2170. // If the path is not present we are done.
  2171. if(pos == std::string::npos)
  2172. {
  2173. return pos;
  2174. }
  2175. // Build a regex to match a properly separated path instance.
  2176. std::string regex_str = "(^|:)(";
  2177. for(std::string::const_iterator i = want.begin(); i != want.end(); ++i)
  2178. {
  2179. int ch = *i;
  2180. if(!(('a' <= ch && ch <= 'z') ||
  2181. ('A' <= ch && ch <= 'Z') ||
  2182. ('0' <= ch && ch <= '9')))
  2183. {
  2184. // Escape the non-alphanumeric character.
  2185. regex_str += "\\";
  2186. }
  2187. // Store the character.
  2188. regex_str.append(1, static_cast<char>(ch));
  2189. }
  2190. regex_str += ")(:|$)";
  2191. // Look for the separated path.
  2192. cmsys::RegularExpression regex(regex_str.c_str());
  2193. if(regex.find(have))
  2194. {
  2195. // Return the position of the path portion.
  2196. return regex.start(2);
  2197. }
  2198. else
  2199. {
  2200. // The desired rpath was not found.
  2201. return std::string::npos;
  2202. }
  2203. }
  2204. #endif
  2205. #if defined(CMAKE_USE_ELF_PARSER)
  2206. struct cmSystemToolsRPathInfo
  2207. {
  2208. unsigned long Position;
  2209. unsigned long Size;
  2210. std::string Name;
  2211. std::string Value;
  2212. };
  2213. #endif
  2214. //----------------------------------------------------------------------------
  2215. bool cmSystemTools::ChangeRPath(std::string const& file,
  2216. std::string const& oldRPath,
  2217. std::string const& newRPath,
  2218. std::string* emsg,
  2219. bool* changed)
  2220. {
  2221. #if defined(CMAKE_USE_ELF_PARSER)
  2222. if(changed)
  2223. {
  2224. *changed = false;
  2225. }
  2226. int rp_count = 0;
  2227. cmSystemToolsRPathInfo rp[2];
  2228. {
  2229. // Parse the ELF binary.
  2230. cmELF elf(file.c_str());
  2231. // Get the RPATH and RUNPATH entries from it.
  2232. int se_count = 0;
  2233. cmELF::StringEntry const* se[2] = {0, 0};
  2234. const char* se_name[2] = {0, 0};
  2235. if(cmELF::StringEntry const* se_rpath = elf.GetRPath())
  2236. {
  2237. se[se_count] = se_rpath;
  2238. se_name[se_count] = "RPATH";
  2239. ++se_count;
  2240. }
  2241. if(cmELF::StringEntry const* se_runpath = elf.GetRunPath())
  2242. {
  2243. se[se_count] = se_runpath;
  2244. se_name[se_count] = "RUNPATH";
  2245. ++se_count;
  2246. }
  2247. if(se_count == 0)
  2248. {
  2249. if(newRPath.empty())
  2250. {
  2251. // The new rpath is empty and there is no rpath anyway so it is
  2252. // okay.
  2253. return true;
  2254. }
  2255. else
  2256. {
  2257. if(emsg)
  2258. {
  2259. *emsg = "No valid ELF RPATH or RUNPATH entry exists in the file; ";
  2260. *emsg += elf.GetErrorMessage();
  2261. }
  2262. return false;
  2263. }
  2264. }
  2265. for(int i=0; i < se_count; ++i)
  2266. {
  2267. // If both RPATH and RUNPATH refer to the same string literal it
  2268. // needs to be changed only once.
  2269. if(rp_count && rp[0].Position == se[i]->Position)
  2270. {
  2271. continue;
  2272. }
  2273. // Make sure the current rpath contains the old rpath.
  2274. std::string::size_type pos =
  2275. cmSystemToolsFindRPath(se[i]->Value, oldRPath);
  2276. if(pos == std::string::npos)
  2277. {
  2278. // If it contains the new rpath instead then it is okay.
  2279. if(cmSystemToolsFindRPath(se[i]->Value, newRPath) != std::string::npos)
  2280. {
  2281. continue;
  2282. }
  2283. if(emsg)
  2284. {
  2285. cmOStringStream e;
  2286. e << "The current " << se_name[i] << " is:\n"
  2287. << " " << se[i]->Value << "\n"
  2288. << "which does not contain:\n"
  2289. << " " << oldRPath << "\n"
  2290. << "as was expected.";
  2291. *emsg = e.str();
  2292. }
  2293. return false;
  2294. }
  2295. // Store information about the entry in the file.
  2296. rp[rp_count].Position = se[i]->Position;
  2297. rp[rp_count].Size = se[i]->Size;
  2298. rp[rp_count].Name = se_name[i];
  2299. // Construct the new value which preserves the part of the path
  2300. // not being changed.
  2301. rp[rp_count].Value = se[i]->Value.substr(0, pos);
  2302. rp[rp_count].Value += newRPath;
  2303. rp[rp_count].Value += se[i]->Value.substr(pos+oldRPath.length(),
  2304. oldRPath.npos);
  2305. // Make sure there is enough room to store the new rpath and at
  2306. // least one null terminator.
  2307. if(rp[rp_count].Size < rp[rp_count].Value.length()+1)
  2308. {
  2309. if(emsg)
  2310. {
  2311. *emsg = "The replacement path is too long for the ";
  2312. *emsg += se_name[i];
  2313. *emsg += " entry.";
  2314. }
  2315. return false;
  2316. }
  2317. // This entry is ready for update.
  2318. ++rp_count;
  2319. }
  2320. }
  2321. // If no runtime path needs to be changed, we are done.
  2322. if(rp_count == 0)
  2323. {
  2324. return true;
  2325. }
  2326. {
  2327. // Open the file for update.
  2328. cmsys::ofstream f(file.c_str(),
  2329. std::ios::in | std::ios::out | std::ios::binary);
  2330. if(!f)
  2331. {
  2332. if(emsg)
  2333. {
  2334. *emsg = "Error opening file for update.";
  2335. }
  2336. return false;
  2337. }
  2338. // Store the new RPATH and RUNPATH strings.
  2339. for(int i=0; i < rp_count; ++i)
  2340. {
  2341. // Seek to the RPATH position.
  2342. if(!f.seekp(rp[i].Position))
  2343. {
  2344. if(emsg)
  2345. {
  2346. *emsg = "Error seeking to ";
  2347. *emsg += rp[i].Name;
  2348. *emsg += " position.";
  2349. }
  2350. return false;
  2351. }
  2352. // Write the new rpath. Follow it with enough null terminators to
  2353. // fill the string table entry.
  2354. f << rp[i].Value;
  2355. for(unsigned long j=rp[i].Value.length(); j < rp[i].Size; ++j)
  2356. {
  2357. f << '\0';
  2358. }
  2359. // Make sure it wrote correctly.
  2360. if(!f)
  2361. {
  2362. if(emsg)
  2363. {
  2364. *emsg = "Error writing the new ";
  2365. *emsg += rp[i].Name;
  2366. *emsg += " string to the file.";
  2367. }
  2368. return false;
  2369. }
  2370. }
  2371. }
  2372. // Everything was updated successfully.
  2373. if(changed)
  2374. {
  2375. *changed = true;
  2376. }
  2377. return true;
  2378. #else
  2379. (void)file;
  2380. (void)oldRPath;
  2381. (void)newRPath;
  2382. (void)emsg;
  2383. (void)changed;
  2384. return false;
  2385. #endif
  2386. }
  2387. //----------------------------------------------------------------------------
  2388. bool cmSystemTools::VersionCompare(cmSystemTools::CompareOp op,
  2389. const char* lhss, const char* rhss)
  2390. {
  2391. // Parse out up to 8 components.
  2392. unsigned int lhs[8] = {0,0,0,0,0,0,0,0};
  2393. unsigned int rhs[8] = {0,0,0,0,0,0,0,0};
  2394. sscanf(lhss, "%u.%u.%u.%u.%u.%u.%u.%u",
  2395. &lhs[0], &lhs[1], &lhs[2], &lhs[3],
  2396. &lhs[4], &lhs[5], &lhs[6], &lhs[7]);
  2397. sscanf(rhss, "%u.%u.%u.%u.%u.%u.%u.%u",
  2398. &rhs[0], &rhs[1], &rhs[2], &rhs[3],
  2399. &rhs[4], &rhs[5], &rhs[6], &rhs[7]);
  2400. // Do component-wise comparison.
  2401. for(unsigned int i=0; i < 8; ++i)
  2402. {
  2403. if(lhs[i] < rhs[i])
  2404. {
  2405. // lhs < rhs, so true if operation is LESS
  2406. return op == cmSystemTools::OP_LESS;
  2407. }
  2408. else if(lhs[i] > rhs[i])
  2409. {
  2410. // lhs > rhs, so true if operation is GREATER
  2411. return op == cmSystemTools::OP_GREATER;
  2412. }
  2413. }
  2414. // lhs == rhs, so true if operation is EQUAL
  2415. return op == cmSystemTools::OP_EQUAL;
  2416. }
  2417. //----------------------------------------------------------------------------
  2418. bool cmSystemTools::RemoveRPath(std::string const& file, std::string* emsg,
  2419. bool* removed)
  2420. {
  2421. #if defined(CMAKE_USE_ELF_PARSER)
  2422. if(removed)
  2423. {
  2424. *removed = false;
  2425. }
  2426. int zeroCount = 0;
  2427. unsigned long zeroPosition[2] = {0,0};
  2428. unsigned long zeroSize[2] = {0,0};
  2429. unsigned long bytesBegin = 0;
  2430. std::vector<char> bytes;
  2431. {
  2432. // Parse the ELF binary.
  2433. cmELF elf(file.c_str());
  2434. // Get the RPATH and RUNPATH entries from it and sort them by index
  2435. // in the dynamic section header.
  2436. int se_count = 0;
  2437. cmELF::StringEntry const* se[2] = {0, 0};
  2438. if(cmELF::StringEntry const* se_rpath = elf.GetRPath())
  2439. {
  2440. se[se_count++] = se_rpath;
  2441. }
  2442. if(cmELF::StringEntry const* se_runpath = elf.GetRunPath())
  2443. {
  2444. se[se_count++] = se_runpath;
  2445. }
  2446. if(se_count == 0)
  2447. {
  2448. // There is no RPATH or RUNPATH anyway.
  2449. return true;
  2450. }
  2451. if(se_count == 2 && se[1]->IndexInSection < se[0]->IndexInSection)
  2452. {
  2453. cmsys_stl::swap(se[0], se[1]);
  2454. }
  2455. // Get the size of the dynamic section header.
  2456. unsigned int count = elf.GetDynamicEntryCount();
  2457. if(count == 0)
  2458. {
  2459. // This should happen only for invalid ELF files where a DT_NULL
  2460. // appears before the end of the table.
  2461. if(emsg)
  2462. {
  2463. *emsg = "DYNAMIC section contains a DT_NULL before the end.";
  2464. }
  2465. return false;
  2466. }
  2467. // Save information about the string entries to be zeroed.
  2468. zeroCount = se_count;
  2469. for(int i=0; i < se_count; ++i)
  2470. {
  2471. zeroPosition[i] = se[i]->Position;
  2472. zeroSize[i] = se[i]->Size;
  2473. }
  2474. // Get the range of file positions corresponding to each entry and
  2475. // the rest of the table after them.
  2476. unsigned long entryBegin[3] = {0,0,0};
  2477. unsigned long entryEnd[2] = {0,0};
  2478. for(int i=0; i < se_count; ++i)
  2479. {
  2480. entryBegin[i] = elf.GetDynamicEntryPosition(se[i]->IndexInSection);
  2481. entryEnd[i] = elf.GetDynamicEntryPosition(se[i]->IndexInSection+1);
  2482. }
  2483. entryBegin[se_count] = elf.GetDynamicEntryPosition(count);
  2484. // The data are to be written over the old table entries starting at
  2485. // the first one being removed.
  2486. bytesBegin = entryBegin[0];
  2487. unsigned long bytesEnd = entryBegin[se_count];
  2488. // Allocate a buffer to hold the part of the file to be written.
  2489. // Initialize it with zeros.
  2490. bytes.resize(bytesEnd - bytesBegin, 0);
  2491. // Read the part of the DYNAMIC section header that will move.
  2492. // The remainder of the buffer will be left with zeros which
  2493. // represent a DT_NULL entry.
  2494. char* data = &bytes[0];
  2495. for(int i=0; i < se_count; ++i)
  2496. {
  2497. // Read data between the entries being removed.
  2498. unsigned long sz = entryBegin[i+1] - entryEnd[i];
  2499. if(sz > 0 && !elf.ReadBytes(entryEnd[i], sz, data))
  2500. {
  2501. if(emsg)
  2502. {
  2503. *emsg = "Failed to read DYNAMIC section header.";
  2504. }
  2505. return false;
  2506. }
  2507. data += sz;
  2508. }
  2509. }
  2510. // Open the file for update.
  2511. cmsys::ofstream f(file.c_str(),
  2512. std::ios::in | std::ios::out | std::ios::binary);
  2513. if(!f)
  2514. {
  2515. if(emsg)
  2516. {
  2517. *emsg = "Error opening file for update.";
  2518. }
  2519. return false;
  2520. }
  2521. // Write the new DYNAMIC table header.
  2522. if(!f.seekp(bytesBegin))
  2523. {
  2524. if(emsg)
  2525. {
  2526. *emsg = "Error seeking to DYNAMIC table header for RPATH.";
  2527. }
  2528. return false;
  2529. }
  2530. if(!f.write(&bytes[0], bytes.size()))
  2531. {
  2532. if(emsg)
  2533. {
  2534. *emsg = "Error replacing DYNAMIC table header.";
  2535. }
  2536. return false;
  2537. }
  2538. // Fill the RPATH and RUNPATH strings with zero bytes.
  2539. for(int i=0; i < zeroCount; ++i)
  2540. {
  2541. if(!f.seekp(zeroPosition[i]))
  2542. {
  2543. if(emsg)
  2544. {
  2545. *emsg = "Error seeking to RPATH position.";
  2546. }
  2547. return false;
  2548. }
  2549. for(unsigned long j=0; j < zeroSize[i]; ++j)
  2550. {
  2551. f << '\0';
  2552. }
  2553. if(!f)
  2554. {
  2555. if(emsg)
  2556. {
  2557. *emsg = "Error writing the empty rpath string to the file.";
  2558. }
  2559. return false;
  2560. }
  2561. }
  2562. // Everything was updated successfully.
  2563. if(removed)
  2564. {
  2565. *removed = true;
  2566. }
  2567. return true;
  2568. #else
  2569. (void)file;
  2570. (void)emsg;
  2571. (void)removed;
  2572. return false;
  2573. #endif
  2574. }
  2575. //----------------------------------------------------------------------------
  2576. bool cmSystemTools::CheckRPath(std::string const& file,
  2577. std::string const& newRPath)
  2578. {
  2579. #if defined(CMAKE_USE_ELF_PARSER)
  2580. // Parse the ELF binary.
  2581. cmELF elf(file.c_str());
  2582. // Get the RPATH or RUNPATH entry from it.
  2583. cmELF::StringEntry const* se = elf.GetRPath();
  2584. if(!se)
  2585. {
  2586. se = elf.GetRunPath();
  2587. }
  2588. // Make sure the current rpath contains the new rpath.
  2589. if(newRPath.empty())
  2590. {
  2591. if(!se)
  2592. {
  2593. return true;
  2594. }
  2595. }
  2596. else
  2597. {
  2598. if(se &&
  2599. cmSystemToolsFindRPath(se->Value, newRPath) != std::string::npos)
  2600. {
  2601. return true;
  2602. }
  2603. }
  2604. return false;
  2605. #else
  2606. (void)file;
  2607. (void)newRPath;
  2608. return false;
  2609. #endif
  2610. }
  2611. //----------------------------------------------------------------------------
  2612. bool cmSystemTools::RepeatedRemoveDirectory(const char* dir)
  2613. {
  2614. // Windows sometimes locks files temporarily so try a few times.
  2615. for(int i = 0; i < 10; ++i)
  2616. {
  2617. if(cmSystemTools::RemoveADirectory(dir))
  2618. {
  2619. return true;
  2620. }
  2621. cmSystemTools::Delay(100);
  2622. }
  2623. return false;
  2624. }
  2625. //----------------------------------------------------------------------------
  2626. std::vector<std::string> cmSystemTools::tokenize(const std::string& str,
  2627. const std::string& sep)
  2628. {
  2629. std::vector<std::string> tokens;
  2630. std::string::size_type tokend = 0;
  2631. do
  2632. {
  2633. std::string::size_type tokstart=str.find_first_not_of(sep, tokend);
  2634. if (tokstart==std::string::npos)
  2635. {
  2636. break; // no more tokens
  2637. }
  2638. tokend=str.find_first_of(sep,tokstart);
  2639. if (tokend==std::string::npos)
  2640. {
  2641. tokens.push_back(str.substr(tokstart));
  2642. }
  2643. else
  2644. {
  2645. tokens.push_back(str.substr(tokstart,tokend-tokstart));
  2646. }
  2647. } while (tokend!=std::string::npos);
  2648. if (tokens.empty())
  2649. {
  2650. tokens.push_back("");
  2651. }
  2652. return tokens;
  2653. }