cmSystemTools.cxx 76 KB

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