cmSystemTools.cxx 74 KB

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