cmSystemTools.cxx 77 KB

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