cmSystemTools.cxx 76 KB

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