cmSystemTools.cxx 80 KB

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