cmSystemTools.cxx 77 KB

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