cmSystemTools.cxx 81 KB

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