cmSystemTools.cxx 74 KB

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