cmSystemTools.cxx 80 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069
  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. // FIXME remove if statement once kwsys SystemTools get support for
  826. // source is directory handling in CopyFileAlways function
  827. if(cmSystemTools::FileIsDirectory(source))
  828. {
  829. return Superclass::MakeDirectory(destination);
  830. }
  831. return Superclass::CopyFileAlways(source, destination);
  832. }
  833. bool cmSystemTools::CopyFileIfDifferent(const char* source,
  834. const char* destination)
  835. {
  836. // FIXME remove if statement once kwsys SystemTools get support for
  837. // source is directory handling in CopyFileIfDifferent function
  838. if(cmSystemTools::FileIsDirectory(source))
  839. {
  840. if(SystemTools::FileExists(destination))
  841. {
  842. return true;
  843. }
  844. else
  845. {
  846. return Superclass::MakeDirectory(destination);
  847. }
  848. }
  849. return Superclass::CopyFileIfDifferent(source, destination);
  850. }
  851. //----------------------------------------------------------------------------
  852. #ifdef _WIN32
  853. cmSystemTools::WindowsFileRetry cmSystemTools::GetWindowsFileRetry()
  854. {
  855. static WindowsFileRetry retry = {0,0};
  856. if(!retry.Count)
  857. {
  858. unsigned int data[2] = {0,0};
  859. HKEY const keys[2] = {HKEY_CURRENT_USER, HKEY_LOCAL_MACHINE};
  860. wchar_t const* const values[2] = {L"FilesystemRetryCount",
  861. L"FilesystemRetryDelay"};
  862. for(int k=0; k < 2; ++k)
  863. {
  864. HKEY hKey;
  865. if(RegOpenKeyExW(keys[k], L"Software\\Kitware\\CMake\\Config",
  866. 0, KEY_QUERY_VALUE, &hKey) == ERROR_SUCCESS)
  867. {
  868. for(int v=0; v < 2; ++v)
  869. {
  870. DWORD dwData, dwType, dwSize = 4;
  871. if(!data[v] &&
  872. RegQueryValueExW(hKey, values[v], 0, &dwType, (BYTE *)&dwData,
  873. &dwSize) == ERROR_SUCCESS &&
  874. dwType == REG_DWORD && dwSize == 4)
  875. {
  876. data[v] = static_cast<unsigned int>(dwData);
  877. }
  878. }
  879. RegCloseKey(hKey);
  880. }
  881. }
  882. retry.Count = data[0]? data[0] : 5;
  883. retry.Delay = data[1]? data[1] : 500;
  884. }
  885. return retry;
  886. }
  887. #endif
  888. //----------------------------------------------------------------------------
  889. bool cmSystemTools::RenameFile(const char* oldname, const char* newname)
  890. {
  891. #ifdef _WIN32
  892. # ifndef INVALID_FILE_ATTRIBUTES
  893. # define INVALID_FILE_ATTRIBUTES ((DWORD)-1)
  894. # endif
  895. /* Windows MoveFileEx may not replace read-only or in-use files. If it
  896. fails then remove the read-only attribute from any existing destination.
  897. Try multiple times since we may be racing against another process
  898. creating/opening the destination file just before our MoveFileEx. */
  899. WindowsFileRetry retry = cmSystemTools::GetWindowsFileRetry();
  900. while(!MoveFileExW(
  901. SystemTools::ConvertToWindowsExtendedPath(oldname).c_str(),
  902. SystemTools::ConvertToWindowsExtendedPath(newname).c_str(),
  903. MOVEFILE_REPLACE_EXISTING) && --retry.Count)
  904. {
  905. DWORD last_error = GetLastError();
  906. // Try again only if failure was due to access/sharing permissions.
  907. if(last_error != ERROR_ACCESS_DENIED &&
  908. last_error != ERROR_SHARING_VIOLATION)
  909. {
  910. return false;
  911. }
  912. DWORD attrs =
  913. GetFileAttributesW(
  914. SystemTools::ConvertToWindowsExtendedPath(newname).c_str());
  915. if((attrs != INVALID_FILE_ATTRIBUTES) &&
  916. (attrs & FILE_ATTRIBUTE_READONLY))
  917. {
  918. // Remove the read-only attribute from the destination file.
  919. SetFileAttributesW(
  920. SystemTools::ConvertToWindowsExtendedPath(newname).c_str(),
  921. attrs & ~FILE_ATTRIBUTE_READONLY);
  922. }
  923. else
  924. {
  925. // The file may be temporarily in use so wait a bit.
  926. cmSystemTools::Delay(retry.Delay);
  927. }
  928. }
  929. return retry.Count > 0;
  930. #else
  931. /* On UNIX we have an OS-provided call to do this atomically. */
  932. return rename(oldname, newname) == 0;
  933. #endif
  934. }
  935. bool cmSystemTools::ComputeFileMD5(const std::string& source, char* md5out)
  936. {
  937. #if defined(CMAKE_BUILD_WITH_CMAKE)
  938. cmCryptoHashMD5 md5;
  939. std::string str = md5.HashFile(source);
  940. strncpy(md5out, str.c_str(), 32);
  941. return !str.empty();
  942. #else
  943. (void)source;
  944. (void)md5out;
  945. cmSystemTools::Message("md5sum not supported in bootstrapping mode","Error");
  946. return false;
  947. #endif
  948. }
  949. std::string cmSystemTools::ComputeStringMD5(const std::string& input)
  950. {
  951. #if defined(CMAKE_BUILD_WITH_CMAKE)
  952. cmCryptoHashMD5 md5;
  953. return md5.HashString(input);
  954. #else
  955. (void)input;
  956. cmSystemTools::Message("md5sum not supported in bootstrapping mode","Error");
  957. return "";
  958. #endif
  959. }
  960. //----------------------------------------------------------------------------
  961. std::string cmSystemTools::ComputeCertificateThumbprint(
  962. const std::string& source)
  963. {
  964. std::string thumbprint;
  965. #if defined(CMAKE_BUILD_WITH_CMAKE) && defined(_WIN32)
  966. BYTE* certData = NULL;
  967. CRYPT_INTEGER_BLOB cryptBlob;
  968. HCERTSTORE certStore = NULL;
  969. PCCERT_CONTEXT certContext = NULL;
  970. HANDLE certFile =
  971. CreateFileW(cmsys::Encoding::ToWide(source.c_str()).c_str(),
  972. GENERIC_READ,
  973. FILE_SHARE_READ,
  974. NULL,
  975. OPEN_EXISTING,
  976. FILE_ATTRIBUTE_NORMAL,
  977. NULL);
  978. if (certFile != INVALID_HANDLE_VALUE && certFile != NULL)
  979. {
  980. DWORD fileSize = GetFileSize(certFile, NULL);
  981. if (fileSize != INVALID_FILE_SIZE)
  982. {
  983. certData = new BYTE[fileSize];
  984. if (certData != NULL)
  985. {
  986. DWORD dwRead = 0;
  987. if (ReadFile(certFile, certData, fileSize, &dwRead, NULL))
  988. {
  989. cryptBlob.cbData = fileSize;
  990. cryptBlob.pbData = certData;
  991. // Verify that this is a valid cert
  992. if (PFXIsPFXBlob(&cryptBlob))
  993. {
  994. // Open the certificate as a store
  995. certStore = PFXImportCertStore(
  996. &cryptBlob, NULL, CRYPT_EXPORTABLE);
  997. if (certStore != NULL)
  998. {
  999. // There should only be 1 cert.
  1000. certContext = CertEnumCertificatesInStore(certStore,
  1001. certContext);
  1002. if (certContext != NULL)
  1003. {
  1004. // The hash is 20 bytes
  1005. BYTE hashData[20];
  1006. DWORD hashLength = 20;
  1007. // Buffer to print the hash. Each byte takes 2 chars +
  1008. // terminating character
  1009. char hashPrint[41];
  1010. char *pHashPrint = hashPrint;
  1011. // Get the hash property from the certificate
  1012. if (CertGetCertificateContextProperty(certContext,
  1013. CERT_HASH_PROP_ID, hashData, &hashLength))
  1014. {
  1015. for (DWORD i = 0; i < hashLength; i++)
  1016. {
  1017. // Convert each byte to hexadecimal
  1018. sprintf(pHashPrint, "%02X", hashData[i]);
  1019. pHashPrint += 2;
  1020. }
  1021. *pHashPrint = '\0';
  1022. thumbprint = hashPrint;
  1023. }
  1024. CertFreeCertificateContext(certContext);
  1025. }
  1026. CertCloseStore(certStore, 0);
  1027. }
  1028. }
  1029. }
  1030. delete[] certData;
  1031. }
  1032. }
  1033. CloseHandle(certFile);
  1034. }
  1035. #else
  1036. (void)source;
  1037. cmSystemTools::Message("ComputeCertificateThumbprint is not implemented",
  1038. "Error");
  1039. #endif
  1040. return thumbprint;
  1041. }
  1042. void cmSystemTools::Glob(const std::string& directory,
  1043. const std::string& regexp,
  1044. std::vector<std::string>& files)
  1045. {
  1046. cmsys::Directory d;
  1047. cmsys::RegularExpression reg(regexp.c_str());
  1048. if (d.Load(directory))
  1049. {
  1050. size_t numf;
  1051. unsigned int i;
  1052. numf = d.GetNumberOfFiles();
  1053. for (i = 0; i < numf; i++)
  1054. {
  1055. std::string fname = d.GetFile(i);
  1056. if (reg.find(fname))
  1057. {
  1058. files.push_back(fname);
  1059. }
  1060. }
  1061. }
  1062. }
  1063. void cmSystemTools::GlobDirs(const std::string& path,
  1064. std::vector<std::string>& files)
  1065. {
  1066. std::string::size_type pos = path.find("/*");
  1067. if(pos == std::string::npos)
  1068. {
  1069. files.push_back(path);
  1070. return;
  1071. }
  1072. std::string startPath = path.substr(0, pos);
  1073. std::string finishPath = path.substr(pos+2);
  1074. cmsys::Directory d;
  1075. if (d.Load(startPath))
  1076. {
  1077. for (unsigned int i = 0; i < d.GetNumberOfFiles(); ++i)
  1078. {
  1079. if((std::string(d.GetFile(i)) != ".")
  1080. && (std::string(d.GetFile(i)) != ".."))
  1081. {
  1082. std::string fname = startPath;
  1083. fname +="/";
  1084. fname += d.GetFile(i);
  1085. if(cmSystemTools::FileIsDirectory(fname))
  1086. {
  1087. fname += finishPath;
  1088. cmSystemTools::GlobDirs(fname, files);
  1089. }
  1090. }
  1091. }
  1092. }
  1093. }
  1094. void cmSystemTools::ExpandList(std::vector<std::string> const& arguments,
  1095. std::vector<std::string>& newargs)
  1096. {
  1097. std::vector<std::string>::const_iterator i;
  1098. for(i = arguments.begin();i != arguments.end(); ++i)
  1099. {
  1100. cmSystemTools::ExpandListArgument(*i, newargs);
  1101. }
  1102. }
  1103. void cmSystemTools::ExpandListArgument(const std::string& arg,
  1104. std::vector<std::string>& newargs,
  1105. bool emptyArgs)
  1106. {
  1107. // If argument is empty, it is an empty list.
  1108. if(!emptyArgs && arg.empty())
  1109. {
  1110. return;
  1111. }
  1112. // if there are no ; in the name then just copy the current string
  1113. if(arg.find(';') == std::string::npos)
  1114. {
  1115. newargs.push_back(arg);
  1116. return;
  1117. }
  1118. std::string newArg;
  1119. const char *last = arg.c_str();
  1120. // Break the string at non-escaped semicolons not nested in [].
  1121. int squareNesting = 0;
  1122. for(const char* c = last; *c; ++c)
  1123. {
  1124. switch(*c)
  1125. {
  1126. case '\\':
  1127. {
  1128. // We only want to allow escaping of semicolons. Other
  1129. // escapes should not be processed here.
  1130. const char* next = c + 1;
  1131. if(*next == ';')
  1132. {
  1133. newArg.append(last, c - last);
  1134. // Skip over the escape character
  1135. last = c = next;
  1136. }
  1137. } break;
  1138. case '[':
  1139. {
  1140. ++squareNesting;
  1141. } break;
  1142. case ']':
  1143. {
  1144. --squareNesting;
  1145. } break;
  1146. case ';':
  1147. {
  1148. // Break the string here if we are not nested inside square
  1149. // brackets.
  1150. if(squareNesting == 0)
  1151. {
  1152. newArg.append(last, c - last);
  1153. // Skip over the semicolon
  1154. last = c + 1;
  1155. if ( !newArg.empty() || emptyArgs )
  1156. {
  1157. // Add the last argument if the string is not empty.
  1158. newargs.push_back(newArg);
  1159. newArg = "";
  1160. }
  1161. }
  1162. } break;
  1163. default:
  1164. {
  1165. // Just append this character.
  1166. } break;
  1167. }
  1168. }
  1169. newArg.append(last);
  1170. if ( !newArg.empty() || emptyArgs )
  1171. {
  1172. // Add the last argument if the string is not empty.
  1173. newargs.push_back(newArg);
  1174. }
  1175. }
  1176. bool cmSystemTools::SimpleGlob(const std::string& glob,
  1177. std::vector<std::string>& files,
  1178. int type /* = 0 */)
  1179. {
  1180. files.clear();
  1181. if ( glob[glob.size()-1] != '*' )
  1182. {
  1183. return false;
  1184. }
  1185. std::string path = cmSystemTools::GetFilenamePath(glob);
  1186. std::string ppath = cmSystemTools::GetFilenameName(glob);
  1187. ppath = ppath.substr(0, ppath.size()-1);
  1188. if (path.empty())
  1189. {
  1190. path = "/";
  1191. }
  1192. bool res = false;
  1193. cmsys::Directory d;
  1194. if (d.Load(path))
  1195. {
  1196. for (unsigned int i = 0; i < d.GetNumberOfFiles(); ++i)
  1197. {
  1198. if((std::string(d.GetFile(i)) != ".")
  1199. && (std::string(d.GetFile(i)) != ".."))
  1200. {
  1201. std::string fname = path;
  1202. if ( path[path.size()-1] != '/' )
  1203. {
  1204. fname +="/";
  1205. }
  1206. fname += d.GetFile(i);
  1207. std::string sfname = d.GetFile(i);
  1208. if ( type > 0 && cmSystemTools::FileIsDirectory(fname) )
  1209. {
  1210. continue;
  1211. }
  1212. if ( type < 0 && !cmSystemTools::FileIsDirectory(fname) )
  1213. {
  1214. continue;
  1215. }
  1216. if ( sfname.size() >= ppath.size() &&
  1217. sfname.substr(0, ppath.size()) ==
  1218. ppath )
  1219. {
  1220. files.push_back(fname);
  1221. res = true;
  1222. }
  1223. }
  1224. }
  1225. }
  1226. return res;
  1227. }
  1228. cmSystemTools::FileFormat cmSystemTools::GetFileFormat(const char* cext)
  1229. {
  1230. if ( ! cext || *cext == 0 )
  1231. {
  1232. return cmSystemTools::NO_FILE_FORMAT;
  1233. }
  1234. //std::string ext = cmSystemTools::LowerCase(cext);
  1235. std::string ext = cext;
  1236. if ( ext == "c" || ext == ".c" ||
  1237. ext == "m" || ext == ".m"
  1238. ) { return cmSystemTools::C_FILE_FORMAT; }
  1239. if (
  1240. ext == "C" || ext == ".C" ||
  1241. ext == "M" || ext == ".M" ||
  1242. ext == "c++" || ext == ".c++" ||
  1243. ext == "cc" || ext == ".cc" ||
  1244. ext == "cpp" || ext == ".cpp" ||
  1245. ext == "cxx" || ext == ".cxx" ||
  1246. ext == "mm" || ext == ".mm"
  1247. ) { return cmSystemTools::CXX_FILE_FORMAT; }
  1248. if (
  1249. ext == "f" || ext == ".f" ||
  1250. ext == "F" || ext == ".F" ||
  1251. ext == "f77" || ext == ".f77" ||
  1252. ext == "f90" || ext == ".f90" ||
  1253. ext == "for" || ext == ".for" ||
  1254. ext == "f95" || ext == ".f95"
  1255. ) { return cmSystemTools::FORTRAN_FILE_FORMAT; }
  1256. if ( ext == "java" || ext == ".java" )
  1257. { return cmSystemTools::JAVA_FILE_FORMAT; }
  1258. if (
  1259. ext == "H" || ext == ".H" ||
  1260. ext == "h" || ext == ".h" ||
  1261. ext == "h++" || ext == ".h++" ||
  1262. ext == "hm" || ext == ".hm" ||
  1263. ext == "hpp" || ext == ".hpp" ||
  1264. ext == "hxx" || ext == ".hxx" ||
  1265. ext == "in" || ext == ".in" ||
  1266. ext == "txx" || ext == ".txx"
  1267. ) { return cmSystemTools::HEADER_FILE_FORMAT; }
  1268. if ( ext == "rc" || ext == ".rc" )
  1269. { return cmSystemTools::RESOURCE_FILE_FORMAT; }
  1270. if ( ext == "def" || ext == ".def" )
  1271. { return cmSystemTools::DEFINITION_FILE_FORMAT; }
  1272. if ( ext == "lib" || ext == ".lib" ||
  1273. ext == "a" || ext == ".a")
  1274. { return cmSystemTools::STATIC_LIBRARY_FILE_FORMAT; }
  1275. if ( ext == "o" || ext == ".o" ||
  1276. ext == "obj" || ext == ".obj")
  1277. { return cmSystemTools::OBJECT_FILE_FORMAT; }
  1278. #ifdef __APPLE__
  1279. if ( ext == "dylib" || ext == ".dylib" )
  1280. { return cmSystemTools::SHARED_LIBRARY_FILE_FORMAT; }
  1281. if ( ext == "so" || ext == ".so" ||
  1282. ext == "bundle" || ext == ".bundle" )
  1283. { return cmSystemTools::MODULE_FILE_FORMAT; }
  1284. #else // __APPLE__
  1285. if ( ext == "so" || ext == ".so" ||
  1286. ext == "sl" || ext == ".sl" ||
  1287. ext == "dll" || ext == ".dll" )
  1288. { return cmSystemTools::SHARED_LIBRARY_FILE_FORMAT; }
  1289. #endif // __APPLE__
  1290. return cmSystemTools::UNKNOWN_FILE_FORMAT;
  1291. }
  1292. bool cmSystemTools::Split(const char* s, std::vector<std::string>& l)
  1293. {
  1294. std::vector<std::string> temp;
  1295. bool res = Superclass::Split(s, temp);
  1296. l.insert(l.end(), temp.begin(), temp.end());
  1297. return res;
  1298. }
  1299. std::string cmSystemTools::ConvertToOutputPath(const char* path)
  1300. {
  1301. #if defined(_WIN32) && !defined(__CYGWIN__)
  1302. if(s_ForceUnixPaths)
  1303. {
  1304. return cmSystemTools::ConvertToUnixOutputPath(path);
  1305. }
  1306. return cmSystemTools::ConvertToWindowsOutputPath(path);
  1307. #else
  1308. return cmSystemTools::ConvertToUnixOutputPath(path);
  1309. #endif
  1310. }
  1311. void cmSystemTools::ConvertToOutputSlashes(std::string& path)
  1312. {
  1313. #if defined(_WIN32) && !defined(__CYGWIN__)
  1314. if(!s_ForceUnixPaths)
  1315. {
  1316. // Convert to windows slashes.
  1317. std::string::size_type pos = 0;
  1318. while((pos = path.find('/', pos)) != std::string::npos)
  1319. {
  1320. path[pos++] = '\\';
  1321. }
  1322. }
  1323. #else
  1324. static_cast<void>(path);
  1325. #endif
  1326. }
  1327. std::string cmSystemTools::ConvertToRunCommandPath(const char* path)
  1328. {
  1329. #if defined(_WIN32) && !defined(__CYGWIN__)
  1330. return cmSystemTools::ConvertToWindowsOutputPath(path);
  1331. #else
  1332. return cmSystemTools::ConvertToUnixOutputPath(path);
  1333. #endif
  1334. }
  1335. // compute the relative path from here to there
  1336. std::string cmSystemTools::RelativePath(const char* local, const char* remote)
  1337. {
  1338. if(!cmSystemTools::FileIsFullPath(local))
  1339. {
  1340. cmSystemTools::Error("RelativePath must be passed a full path to local: ",
  1341. local);
  1342. }
  1343. if(!cmSystemTools::FileIsFullPath(remote))
  1344. {
  1345. cmSystemTools::Error
  1346. ("RelativePath must be passed a full path to remote: ", remote);
  1347. }
  1348. return cmsys::SystemTools::RelativePath(local, remote);
  1349. }
  1350. std::string cmSystemTools::CollapseCombinedPath(std::string const& dir,
  1351. std::string const& file)
  1352. {
  1353. if(dir.empty() || dir == ".")
  1354. {
  1355. return file;
  1356. }
  1357. std::vector<std::string> dirComponents;
  1358. std::vector<std::string> fileComponents;
  1359. cmSystemTools::SplitPath(dir, dirComponents);
  1360. cmSystemTools::SplitPath(file, fileComponents);
  1361. if(fileComponents.empty())
  1362. {
  1363. return dir;
  1364. }
  1365. if(fileComponents[0] != "")
  1366. {
  1367. // File is not a relative path.
  1368. return file;
  1369. }
  1370. std::vector<std::string>::iterator i = fileComponents.begin()+1;
  1371. while(i != fileComponents.end() && *i == ".." && dirComponents.size() > 1)
  1372. {
  1373. ++i; // Remove ".." file component.
  1374. dirComponents.pop_back(); // Remove last dir component.
  1375. }
  1376. dirComponents.insert(dirComponents.end(), i, fileComponents.end());
  1377. return cmSystemTools::JoinPath(dirComponents);
  1378. }
  1379. #ifdef CMAKE_BUILD_WITH_CMAKE
  1380. //----------------------------------------------------------------------
  1381. bool cmSystemTools::UnsetEnv(const char* value)
  1382. {
  1383. #if !defined(HAVE_UNSETENV)
  1384. std::string var = value;
  1385. var += "=";
  1386. return cmSystemTools::PutEnv(var.c_str());
  1387. #else
  1388. unsetenv(value);
  1389. return true;
  1390. #endif
  1391. }
  1392. //----------------------------------------------------------------------
  1393. std::vector<std::string> cmSystemTools::GetEnvironmentVariables()
  1394. {
  1395. std::vector<std::string> env;
  1396. int cc;
  1397. for ( cc = 0; environ[cc]; ++ cc )
  1398. {
  1399. env.push_back(environ[cc]);
  1400. }
  1401. return env;
  1402. }
  1403. //----------------------------------------------------------------------
  1404. void cmSystemTools::AppendEnv(std::vector<std::string> const& env)
  1405. {
  1406. for(std::vector<std::string>::const_iterator eit = env.begin();
  1407. eit != env.end(); ++eit)
  1408. {
  1409. cmSystemTools::PutEnv(*eit);
  1410. }
  1411. }
  1412. //----------------------------------------------------------------------
  1413. cmSystemTools::SaveRestoreEnvironment::SaveRestoreEnvironment()
  1414. {
  1415. this->Env = cmSystemTools::GetEnvironmentVariables();
  1416. }
  1417. //----------------------------------------------------------------------
  1418. cmSystemTools::SaveRestoreEnvironment::~SaveRestoreEnvironment()
  1419. {
  1420. // First clear everything in the current environment:
  1421. std::vector<std::string> currentEnv = GetEnvironmentVariables();
  1422. for(std::vector<std::string>::const_iterator
  1423. eit = currentEnv.begin(); eit != currentEnv.end(); ++eit)
  1424. {
  1425. std::string var(*eit);
  1426. std::string::size_type pos = var.find("=");
  1427. if (pos != std::string::npos)
  1428. {
  1429. var = var.substr(0, pos);
  1430. }
  1431. cmSystemTools::UnsetEnv(var.c_str());
  1432. }
  1433. // Then put back each entry from the original environment:
  1434. cmSystemTools::AppendEnv(this->Env);
  1435. }
  1436. #endif
  1437. void cmSystemTools::EnableVSConsoleOutput()
  1438. {
  1439. #ifdef _WIN32
  1440. // Visual Studio 8 2005 (devenv.exe or VCExpress.exe) will not
  1441. // display output to the console unless this environment variable is
  1442. // set. We need it to capture the output of these build tools.
  1443. // Note for future work that one could pass "/out \\.\pipe\NAME" to
  1444. // either of these executables where NAME is created with
  1445. // CreateNamedPipe. This would bypass the internal buffering of the
  1446. // output and allow it to be captured on the fly.
  1447. cmSystemTools::PutEnv("vsconsoleoutput=1");
  1448. # ifdef CMAKE_BUILD_WITH_CMAKE
  1449. // VS sets an environment variable to tell MS tools like "cl" to report
  1450. // output through a backdoor pipe instead of stdout/stderr. Unset the
  1451. // environment variable to close this backdoor for any path of process
  1452. // invocations that passes through CMake so we can capture the output.
  1453. cmSystemTools::UnsetEnv("VS_UNICODE_OUTPUT");
  1454. # endif
  1455. #endif
  1456. }
  1457. bool cmSystemTools::IsPathToFramework(const char* path)
  1458. {
  1459. return (cmSystemTools::FileIsFullPath(path) &&
  1460. cmHasLiteralSuffix(path, ".framework"));
  1461. }
  1462. bool cmSystemTools::CreateTar(const char* outFileName,
  1463. const std::vector<std::string>& files,
  1464. cmTarCompression compressType,
  1465. bool verbose, std::string const& mtime,
  1466. std::string const& format)
  1467. {
  1468. #if defined(CMAKE_BUILD_WITH_CMAKE)
  1469. std::string cwd = cmSystemTools::GetCurrentWorkingDirectory();
  1470. cmsys::ofstream fout(outFileName, std::ios::out | std::ios::binary);
  1471. if(!fout)
  1472. {
  1473. std::string e = "Cannot open output file \"";
  1474. e += outFileName;
  1475. e += "\": ";
  1476. e += cmSystemTools::GetLastSystemError();
  1477. cmSystemTools::Error(e.c_str());
  1478. return false;
  1479. }
  1480. cmArchiveWrite::Compress compress = cmArchiveWrite::CompressNone;
  1481. switch (compressType)
  1482. {
  1483. case TarCompressGZip:
  1484. compress = cmArchiveWrite::CompressGZip;
  1485. break;
  1486. case TarCompressBZip2:
  1487. compress = cmArchiveWrite::CompressBZip2;
  1488. break;
  1489. case TarCompressXZ:
  1490. compress = cmArchiveWrite::CompressXZ;
  1491. break;
  1492. case TarCompressNone:
  1493. compress = cmArchiveWrite::CompressNone;
  1494. break;
  1495. }
  1496. cmArchiveWrite a(fout, compress,
  1497. format.empty() ? "paxr" : format);
  1498. a.SetMTime(mtime);
  1499. a.SetVerbose(verbose);
  1500. for(std::vector<std::string>::const_iterator i = files.begin();
  1501. i != files.end(); ++i)
  1502. {
  1503. std::string path = *i;
  1504. if(cmSystemTools::FileIsFullPath(path.c_str()))
  1505. {
  1506. // Get the relative path to the file.
  1507. path = cmSystemTools::RelativePath(cwd.c_str(), path.c_str());
  1508. }
  1509. if(!a.Add(path))
  1510. {
  1511. break;
  1512. }
  1513. }
  1514. if(!a)
  1515. {
  1516. cmSystemTools::Error(a.GetError().c_str());
  1517. return false;
  1518. }
  1519. return true;
  1520. #else
  1521. (void)outFileName;
  1522. (void)files;
  1523. (void)verbose;
  1524. return false;
  1525. #endif
  1526. }
  1527. #if defined(CMAKE_BUILD_WITH_CMAKE)
  1528. namespace{
  1529. #define BSDTAR_FILESIZE_PRINTF "%lu"
  1530. #define BSDTAR_FILESIZE_TYPE unsigned long
  1531. void
  1532. list_item_verbose(FILE *out, struct archive_entry *entry)
  1533. {
  1534. char tmp[100];
  1535. size_t w;
  1536. const char *p;
  1537. const char *fmt;
  1538. time_t tim;
  1539. static time_t now;
  1540. size_t u_width = 6;
  1541. size_t gs_width = 13;
  1542. /*
  1543. * We avoid collecting the entire list in memory at once by
  1544. * listing things as we see them. However, that also means we can't
  1545. * just pre-compute the field widths. Instead, we start with guesses
  1546. * and just widen them as necessary. These numbers are completely
  1547. * arbitrary.
  1548. */
  1549. if (!now)
  1550. {
  1551. time(&now);
  1552. }
  1553. fprintf(out, "%s %d ",
  1554. archive_entry_strmode(entry),
  1555. archive_entry_nlink(entry));
  1556. /* Use uname if it's present, else uid. */
  1557. p = archive_entry_uname(entry);
  1558. if ((p == NULL) || (*p == '\0'))
  1559. {
  1560. sprintf(tmp, "%lu ",
  1561. (unsigned long)archive_entry_uid(entry));
  1562. p = tmp;
  1563. }
  1564. w = strlen(p);
  1565. if (w > u_width)
  1566. {
  1567. u_width = w;
  1568. }
  1569. fprintf(out, "%-*s ", (int)u_width, p);
  1570. /* Use gname if it's present, else gid. */
  1571. p = archive_entry_gname(entry);
  1572. if (p != NULL && p[0] != '\0')
  1573. {
  1574. fprintf(out, "%s", p);
  1575. w = strlen(p);
  1576. }
  1577. else
  1578. {
  1579. sprintf(tmp, "%lu",
  1580. (unsigned long)archive_entry_gid(entry));
  1581. w = strlen(tmp);
  1582. fprintf(out, "%s", tmp);
  1583. }
  1584. /*
  1585. * Print device number or file size, right-aligned so as to make
  1586. * total width of group and devnum/filesize fields be gs_width.
  1587. * If gs_width is too small, grow it.
  1588. */
  1589. if (archive_entry_filetype(entry) == AE_IFCHR
  1590. || archive_entry_filetype(entry) == AE_IFBLK)
  1591. {
  1592. sprintf(tmp, "%lu,%lu",
  1593. (unsigned long)archive_entry_rdevmajor(entry),
  1594. (unsigned long)archive_entry_rdevminor(entry));
  1595. }
  1596. else
  1597. {
  1598. /*
  1599. * Note the use of platform-dependent macros to format
  1600. * the filesize here. We need the format string and the
  1601. * corresponding type for the cast.
  1602. */
  1603. sprintf(tmp, BSDTAR_FILESIZE_PRINTF,
  1604. (BSDTAR_FILESIZE_TYPE)archive_entry_size(entry));
  1605. }
  1606. if (w + strlen(tmp) >= gs_width)
  1607. {
  1608. gs_width = w+strlen(tmp)+1;
  1609. }
  1610. fprintf(out, "%*s", (int)(gs_width - w), tmp);
  1611. /* Format the time using 'ls -l' conventions. */
  1612. tim = archive_entry_mtime(entry);
  1613. #define HALF_YEAR (time_t)365 * 86400 / 2
  1614. #if defined(_WIN32) && !defined(__CYGWIN__)
  1615. /* Windows' strftime function does not support %e format. */
  1616. #define DAY_FMT "%d"
  1617. #else
  1618. #define DAY_FMT "%e" /* Day number without leading zeros */
  1619. #endif
  1620. if (tim < now - HALF_YEAR || tim > now + HALF_YEAR)
  1621. {
  1622. fmt = DAY_FMT " %b %Y";
  1623. }
  1624. else
  1625. {
  1626. fmt = DAY_FMT " %b %H:%M";
  1627. }
  1628. strftime(tmp, sizeof(tmp), fmt, localtime(&tim));
  1629. fprintf(out, " %s ", tmp);
  1630. fprintf(out, "%s", cm_archive_entry_pathname(entry).c_str());
  1631. /* Extra information for links. */
  1632. if (archive_entry_hardlink(entry)) /* Hard link */
  1633. {
  1634. fprintf(out, " link to %s",
  1635. archive_entry_hardlink(entry));
  1636. }
  1637. else if (archive_entry_symlink(entry)) /* Symbolic link */
  1638. {
  1639. fprintf(out, " -> %s", archive_entry_symlink(entry));
  1640. }
  1641. }
  1642. long copy_data(struct archive *ar, struct archive *aw)
  1643. {
  1644. long r;
  1645. const void *buff;
  1646. size_t size;
  1647. #if defined(ARCHIVE_VERSION_NUMBER) && ARCHIVE_VERSION_NUMBER >= 3000000
  1648. __LA_INT64_T offset;
  1649. #else
  1650. off_t offset;
  1651. #endif
  1652. for (;;)
  1653. {
  1654. r = archive_read_data_block(ar, &buff, &size, &offset);
  1655. if (r == ARCHIVE_EOF)
  1656. {
  1657. return (ARCHIVE_OK);
  1658. }
  1659. if (r != ARCHIVE_OK)
  1660. {
  1661. return (r);
  1662. }
  1663. r = archive_write_data_block(aw, buff, size, offset);
  1664. if (r != ARCHIVE_OK)
  1665. {
  1666. cmSystemTools::Message("archive_write_data_block()",
  1667. archive_error_string(aw));
  1668. return (r);
  1669. }
  1670. }
  1671. #if !defined(__clang__) && !defined(__HP_aCC)
  1672. return r; /* this should not happen but it quiets some compilers */
  1673. #endif
  1674. }
  1675. bool extract_tar(const char* outFileName, bool verbose,
  1676. bool extract)
  1677. {
  1678. cmLocaleRAII localeRAII;
  1679. static_cast<void>(localeRAII);
  1680. struct archive* a = archive_read_new();
  1681. struct archive *ext = archive_write_disk_new();
  1682. archive_read_support_filter_all(a);
  1683. archive_read_support_format_all(a);
  1684. struct archive_entry *entry;
  1685. int r = cm_archive_read_open_file(a, outFileName, 10240);
  1686. if(r)
  1687. {
  1688. cmSystemTools::Error("Problem with archive_read_open_file(): ",
  1689. archive_error_string(a));
  1690. archive_write_free(ext);
  1691. archive_read_close(a);
  1692. return false;
  1693. }
  1694. for (;;)
  1695. {
  1696. r = archive_read_next_header(a, &entry);
  1697. if (r == ARCHIVE_EOF)
  1698. {
  1699. break;
  1700. }
  1701. if (r != ARCHIVE_OK)
  1702. {
  1703. cmSystemTools::Error("Problem with archive_read_next_header(): ",
  1704. archive_error_string(a));
  1705. break;
  1706. }
  1707. if(verbose)
  1708. {
  1709. if(extract)
  1710. {
  1711. cmSystemTools::Stdout("x ");
  1712. cmSystemTools::Stdout(cm_archive_entry_pathname(entry).c_str());
  1713. }
  1714. else
  1715. {
  1716. list_item_verbose(stdout, entry);
  1717. }
  1718. cmSystemTools::Stdout("\n");
  1719. }
  1720. else if(!extract)
  1721. {
  1722. cmSystemTools::Stdout(cm_archive_entry_pathname(entry).c_str());
  1723. cmSystemTools::Stdout("\n");
  1724. }
  1725. if(extract)
  1726. {
  1727. r = archive_write_disk_set_options(ext, ARCHIVE_EXTRACT_TIME);
  1728. if (r != ARCHIVE_OK)
  1729. {
  1730. cmSystemTools::Error(
  1731. "Problem with archive_write_disk_set_options(): ",
  1732. archive_error_string(ext));
  1733. break;
  1734. }
  1735. r = archive_write_header(ext, entry);
  1736. if (r == ARCHIVE_OK)
  1737. {
  1738. copy_data(a, ext);
  1739. r = archive_write_finish_entry(ext);
  1740. if (r != ARCHIVE_OK)
  1741. {
  1742. cmSystemTools::Error("Problem with archive_write_finish_entry(): ",
  1743. archive_error_string(ext));
  1744. break;
  1745. }
  1746. }
  1747. #ifdef _WIN32
  1748. else if(const char* linktext = archive_entry_symlink(entry))
  1749. {
  1750. std::cerr << "cmake -E tar: warning: skipping symbolic link \""
  1751. << cm_archive_entry_pathname(entry)
  1752. << "\" -> \""
  1753. << linktext << "\"." << std::endl;
  1754. }
  1755. #endif
  1756. else
  1757. {
  1758. cmSystemTools::Error("Problem with archive_write_header(): ",
  1759. archive_error_string(ext));
  1760. cmSystemTools::Error("Current file: ",
  1761. cm_archive_entry_pathname(entry).c_str());
  1762. break;
  1763. }
  1764. }
  1765. }
  1766. archive_write_free(ext);
  1767. archive_read_close(a);
  1768. archive_read_free(a);
  1769. return r == ARCHIVE_EOF || r == ARCHIVE_OK;
  1770. }
  1771. }
  1772. #endif
  1773. bool cmSystemTools::ExtractTar(const char* outFileName,
  1774. bool verbose)
  1775. {
  1776. #if defined(CMAKE_BUILD_WITH_CMAKE)
  1777. return extract_tar(outFileName, verbose, true);
  1778. #else
  1779. (void)outFileName;
  1780. (void)verbose;
  1781. return false;
  1782. #endif
  1783. }
  1784. bool cmSystemTools::ListTar(const char* outFileName,
  1785. bool verbose)
  1786. {
  1787. #if defined(CMAKE_BUILD_WITH_CMAKE)
  1788. return extract_tar(outFileName, verbose, false);
  1789. #else
  1790. (void)outFileName;
  1791. (void)verbose;
  1792. return false;
  1793. #endif
  1794. }
  1795. int cmSystemTools::WaitForLine(cmsysProcess* process, std::string& line,
  1796. double timeout,
  1797. std::vector<char>& out,
  1798. std::vector<char>& err)
  1799. {
  1800. line = "";
  1801. std::vector<char>::iterator outiter = out.begin();
  1802. std::vector<char>::iterator erriter = err.begin();
  1803. while(1)
  1804. {
  1805. // Check for a newline in stdout.
  1806. for(;outiter != out.end(); ++outiter)
  1807. {
  1808. if((*outiter == '\r') && ((outiter+1) == out.end()))
  1809. {
  1810. break;
  1811. }
  1812. else if(*outiter == '\n' || *outiter == '\0')
  1813. {
  1814. std::vector<char>::size_type length = outiter-out.begin();
  1815. if(length > 1 && *(outiter-1) == '\r')
  1816. {
  1817. --length;
  1818. }
  1819. if(length > 0)
  1820. {
  1821. line.append(&out[0], length);
  1822. }
  1823. out.erase(out.begin(), outiter+1);
  1824. return cmsysProcess_Pipe_STDOUT;
  1825. }
  1826. }
  1827. // Check for a newline in stderr.
  1828. for(;erriter != err.end(); ++erriter)
  1829. {
  1830. if((*erriter == '\r') && ((erriter+1) == err.end()))
  1831. {
  1832. break;
  1833. }
  1834. else if(*erriter == '\n' || *erriter == '\0')
  1835. {
  1836. std::vector<char>::size_type length = erriter-err.begin();
  1837. if(length > 1 && *(erriter-1) == '\r')
  1838. {
  1839. --length;
  1840. }
  1841. if(length > 0)
  1842. {
  1843. line.append(&err[0], length);
  1844. }
  1845. err.erase(err.begin(), erriter+1);
  1846. return cmsysProcess_Pipe_STDERR;
  1847. }
  1848. }
  1849. // No newlines found. Wait for more data from the process.
  1850. int length;
  1851. char* data;
  1852. int pipe = cmsysProcess_WaitForData(process, &data, &length, &timeout);
  1853. if(pipe == cmsysProcess_Pipe_Timeout)
  1854. {
  1855. // Timeout has been exceeded.
  1856. return pipe;
  1857. }
  1858. else if(pipe == cmsysProcess_Pipe_STDOUT)
  1859. {
  1860. // Append to the stdout buffer.
  1861. std::vector<char>::size_type size = out.size();
  1862. out.insert(out.end(), data, data+length);
  1863. outiter = out.begin()+size;
  1864. }
  1865. else if(pipe == cmsysProcess_Pipe_STDERR)
  1866. {
  1867. // Append to the stderr buffer.
  1868. std::vector<char>::size_type size = err.size();
  1869. err.insert(err.end(), data, data+length);
  1870. erriter = err.begin()+size;
  1871. }
  1872. else if(pipe == cmsysProcess_Pipe_None)
  1873. {
  1874. // Both stdout and stderr pipes have broken. Return leftover data.
  1875. if(!out.empty())
  1876. {
  1877. line.append(&out[0], outiter-out.begin());
  1878. out.erase(out.begin(), out.end());
  1879. return cmsysProcess_Pipe_STDOUT;
  1880. }
  1881. else if(!err.empty())
  1882. {
  1883. line.append(&err[0], erriter-err.begin());
  1884. err.erase(err.begin(), err.end());
  1885. return cmsysProcess_Pipe_STDERR;
  1886. }
  1887. else
  1888. {
  1889. return cmsysProcess_Pipe_None;
  1890. }
  1891. }
  1892. }
  1893. }
  1894. void cmSystemTools::DoNotInheritStdPipes()
  1895. {
  1896. #ifdef _WIN32
  1897. // Check to see if we are attached to a console
  1898. // if so, then do not stop the inherited pipes
  1899. // or stdout and stderr will not show up in dos
  1900. // shell windows
  1901. CONSOLE_SCREEN_BUFFER_INFO hOutInfo;
  1902. HANDLE hOut = GetStdHandle(STD_OUTPUT_HANDLE);
  1903. if(GetConsoleScreenBufferInfo(hOut, &hOutInfo))
  1904. {
  1905. return;
  1906. }
  1907. {
  1908. HANDLE out = GetStdHandle(STD_OUTPUT_HANDLE);
  1909. DuplicateHandle(GetCurrentProcess(), out,
  1910. GetCurrentProcess(), &out, 0, FALSE,
  1911. DUPLICATE_SAME_ACCESS | DUPLICATE_CLOSE_SOURCE);
  1912. SetStdHandle(STD_OUTPUT_HANDLE, out);
  1913. }
  1914. {
  1915. HANDLE out = GetStdHandle(STD_ERROR_HANDLE);
  1916. DuplicateHandle(GetCurrentProcess(), out,
  1917. GetCurrentProcess(), &out, 0, FALSE,
  1918. DUPLICATE_SAME_ACCESS | DUPLICATE_CLOSE_SOURCE);
  1919. SetStdHandle(STD_ERROR_HANDLE, out);
  1920. }
  1921. #endif
  1922. }
  1923. //----------------------------------------------------------------------------
  1924. bool cmSystemTools::CopyFileTime(const char* fromFile, const char* toFile)
  1925. {
  1926. #if defined(_WIN32) && !defined(__CYGWIN__)
  1927. cmSystemToolsWindowsHandle hFrom =
  1928. CreateFileW(SystemTools::ConvertToWindowsExtendedPath(fromFile).c_str(),
  1929. GENERIC_READ, FILE_SHARE_READ, 0,
  1930. OPEN_EXISTING, 0, 0);
  1931. cmSystemToolsWindowsHandle hTo =
  1932. CreateFileW(SystemTools::ConvertToWindowsExtendedPath(toFile).c_str(),
  1933. GENERIC_WRITE, 0, 0, OPEN_EXISTING, 0, 0);
  1934. if(!hFrom || !hTo)
  1935. {
  1936. return false;
  1937. }
  1938. FILETIME timeCreation;
  1939. FILETIME timeLastAccess;
  1940. FILETIME timeLastWrite;
  1941. if(!GetFileTime(hFrom, &timeCreation, &timeLastAccess, &timeLastWrite))
  1942. {
  1943. return false;
  1944. }
  1945. if(!SetFileTime(hTo, &timeCreation, &timeLastAccess, &timeLastWrite))
  1946. {
  1947. return false;
  1948. }
  1949. #else
  1950. struct stat fromStat;
  1951. if(stat(fromFile, &fromStat) < 0)
  1952. {
  1953. return false;
  1954. }
  1955. struct utimbuf buf;
  1956. buf.actime = fromStat.st_atime;
  1957. buf.modtime = fromStat.st_mtime;
  1958. if(utime(toFile, &buf) < 0)
  1959. {
  1960. return false;
  1961. }
  1962. #endif
  1963. return true;
  1964. }
  1965. //----------------------------------------------------------------------------
  1966. cmSystemToolsFileTime* cmSystemTools::FileTimeNew()
  1967. {
  1968. return new cmSystemToolsFileTime;
  1969. }
  1970. //----------------------------------------------------------------------------
  1971. void cmSystemTools::FileTimeDelete(cmSystemToolsFileTime* t)
  1972. {
  1973. delete t;
  1974. }
  1975. //----------------------------------------------------------------------------
  1976. bool cmSystemTools::FileTimeGet(const char* fname, cmSystemToolsFileTime* t)
  1977. {
  1978. #if defined(_WIN32) && !defined(__CYGWIN__)
  1979. cmSystemToolsWindowsHandle h =
  1980. CreateFileW(SystemTools::ConvertToWindowsExtendedPath(fname).c_str(),
  1981. GENERIC_READ, FILE_SHARE_READ, 0, OPEN_EXISTING, 0, 0);
  1982. if(!h)
  1983. {
  1984. return false;
  1985. }
  1986. if(!GetFileTime(h, &t->timeCreation, &t->timeLastAccess, &t->timeLastWrite))
  1987. {
  1988. return false;
  1989. }
  1990. #else
  1991. struct stat st;
  1992. if(stat(fname, &st) < 0)
  1993. {
  1994. return false;
  1995. }
  1996. t->timeBuf.actime = st.st_atime;
  1997. t->timeBuf.modtime = st.st_mtime;
  1998. #endif
  1999. return true;
  2000. }
  2001. //----------------------------------------------------------------------------
  2002. bool cmSystemTools::FileTimeSet(const char* fname, cmSystemToolsFileTime* t)
  2003. {
  2004. #if defined(_WIN32) && !defined(__CYGWIN__)
  2005. cmSystemToolsWindowsHandle h =
  2006. CreateFileW(SystemTools::ConvertToWindowsExtendedPath(fname).c_str(),
  2007. GENERIC_WRITE, 0, 0, OPEN_EXISTING, 0, 0);
  2008. if(!h)
  2009. {
  2010. return false;
  2011. }
  2012. if(!SetFileTime(h, &t->timeCreation, &t->timeLastAccess, &t->timeLastWrite))
  2013. {
  2014. return false;
  2015. }
  2016. #else
  2017. if(utime(fname, &t->timeBuf) < 0)
  2018. {
  2019. return false;
  2020. }
  2021. #endif
  2022. return true;
  2023. }
  2024. //----------------------------------------------------------------------------
  2025. #ifdef _WIN32
  2026. # ifndef CRYPT_SILENT
  2027. # define CRYPT_SILENT 0x40 /* Not defined by VS 6 version of header. */
  2028. # endif
  2029. static int WinCryptRandom(void* data, size_t size)
  2030. {
  2031. int result = 0;
  2032. HCRYPTPROV hProvider = 0;
  2033. if(CryptAcquireContextW(&hProvider, 0, 0, PROV_RSA_FULL,
  2034. CRYPT_VERIFYCONTEXT | CRYPT_SILENT))
  2035. {
  2036. result = CryptGenRandom(hProvider, (DWORD)size, (BYTE*)data)? 1:0;
  2037. CryptReleaseContext(hProvider, 0);
  2038. }
  2039. return result;
  2040. }
  2041. #endif
  2042. //----------------------------------------------------------------------------
  2043. unsigned int cmSystemTools::RandomSeed()
  2044. {
  2045. #if defined(_WIN32) && !defined(__CYGWIN__)
  2046. unsigned int seed = 0;
  2047. // Try using a real random source.
  2048. if(WinCryptRandom(&seed, sizeof(seed)))
  2049. {
  2050. return seed;
  2051. }
  2052. // Fall back to the time and pid.
  2053. FILETIME ft;
  2054. GetSystemTimeAsFileTime(&ft);
  2055. unsigned int t1 = static_cast<unsigned int>(ft.dwHighDateTime);
  2056. unsigned int t2 = static_cast<unsigned int>(ft.dwLowDateTime);
  2057. unsigned int pid = static_cast<unsigned int>(GetCurrentProcessId());
  2058. return t1 ^ t2 ^ pid;
  2059. #else
  2060. union
  2061. {
  2062. unsigned int integer;
  2063. char bytes[sizeof(unsigned int)];
  2064. } seed;
  2065. // Try using a real random source.
  2066. cmsys::ifstream fin("/dev/urandom");
  2067. if(fin && fin.read(seed.bytes, sizeof(seed)) &&
  2068. fin.gcount() == sizeof(seed))
  2069. {
  2070. return seed.integer;
  2071. }
  2072. // Fall back to the time and pid.
  2073. struct timeval t;
  2074. gettimeofday(&t, 0);
  2075. unsigned int pid = static_cast<unsigned int>(getpid());
  2076. unsigned int tv_sec = static_cast<unsigned int>(t.tv_sec);
  2077. unsigned int tv_usec = static_cast<unsigned int>(t.tv_usec);
  2078. // Since tv_usec never fills more than 11 bits we shift it to fill
  2079. // in the slow-changing high-order bits of tv_sec.
  2080. return tv_sec ^ (tv_usec << 21) ^ pid;
  2081. #endif
  2082. }
  2083. //----------------------------------------------------------------------------
  2084. static std::string cmSystemToolsCMakeCommand;
  2085. static std::string cmSystemToolsCTestCommand;
  2086. static std::string cmSystemToolsCPackCommand;
  2087. static std::string cmSystemToolsCMakeCursesCommand;
  2088. static std::string cmSystemToolsCMakeGUICommand;
  2089. static std::string cmSystemToolsCMClDepsCommand;
  2090. static std::string cmSystemToolsCMakeRoot;
  2091. void cmSystemTools::FindCMakeResources(const char* argv0)
  2092. {
  2093. std::string exe_dir;
  2094. #if defined(_WIN32) && !defined(__CYGWIN__)
  2095. (void)argv0; // ignore this on windows
  2096. wchar_t modulepath[_MAX_PATH];
  2097. ::GetModuleFileNameW(NULL, modulepath, sizeof(modulepath));
  2098. exe_dir =
  2099. cmSystemTools::GetFilenamePath(cmsys::Encoding::ToNarrow(modulepath));
  2100. #elif defined(__APPLE__)
  2101. (void)argv0; // ignore this on OS X
  2102. # define CM_EXE_PATH_LOCAL_SIZE 16384
  2103. char exe_path_local[CM_EXE_PATH_LOCAL_SIZE];
  2104. # if defined(MAC_OS_X_VERSION_10_3) && !defined(MAC_OS_X_VERSION_10_4)
  2105. unsigned long exe_path_size = CM_EXE_PATH_LOCAL_SIZE;
  2106. # else
  2107. uint32_t exe_path_size = CM_EXE_PATH_LOCAL_SIZE;
  2108. # endif
  2109. # undef CM_EXE_PATH_LOCAL_SIZE
  2110. char* exe_path = exe_path_local;
  2111. if(_NSGetExecutablePath(exe_path, &exe_path_size) < 0)
  2112. {
  2113. exe_path = (char*)malloc(exe_path_size);
  2114. _NSGetExecutablePath(exe_path, &exe_path_size);
  2115. }
  2116. exe_dir =
  2117. cmSystemTools::GetFilenamePath(
  2118. cmSystemTools::GetRealPath(exe_path));
  2119. if(exe_path != exe_path_local)
  2120. {
  2121. free(exe_path);
  2122. }
  2123. if(cmSystemTools::GetFilenameName(exe_dir) == "MacOS")
  2124. {
  2125. // The executable is inside an application bundle.
  2126. // Look for ../bin (install tree) and then fall back to
  2127. // ../../../bin (build tree).
  2128. exe_dir = cmSystemTools::GetFilenamePath(exe_dir);
  2129. if(cmSystemTools::FileExists((exe_dir+"/bin/cmake").c_str()))
  2130. {
  2131. exe_dir += "/bin";
  2132. }
  2133. else
  2134. {
  2135. exe_dir = cmSystemTools::GetFilenamePath(exe_dir);
  2136. exe_dir = cmSystemTools::GetFilenamePath(exe_dir);
  2137. }
  2138. }
  2139. #else
  2140. std::string errorMsg;
  2141. std::string exe;
  2142. if(cmSystemTools::FindProgramPath(argv0, exe, errorMsg))
  2143. {
  2144. // remove symlinks
  2145. exe = cmSystemTools::GetRealPath(exe);
  2146. exe_dir =
  2147. cmSystemTools::GetFilenamePath(exe);
  2148. }
  2149. else
  2150. {
  2151. // ???
  2152. }
  2153. #endif
  2154. cmSystemToolsCMakeCommand = exe_dir;
  2155. cmSystemToolsCMakeCommand += "/cmake";
  2156. cmSystemToolsCMakeCommand += cmSystemTools::GetExecutableExtension();
  2157. #ifndef CMAKE_BUILD_WITH_CMAKE
  2158. // The bootstrap cmake does not provide the other tools,
  2159. // so use the directory where they are about to be built.
  2160. exe_dir = CMAKE_BOOTSTRAP_BINARY_DIR "/bin";
  2161. #endif
  2162. cmSystemToolsCTestCommand = exe_dir;
  2163. cmSystemToolsCTestCommand += "/ctest";
  2164. cmSystemToolsCTestCommand += cmSystemTools::GetExecutableExtension();
  2165. cmSystemToolsCPackCommand = exe_dir;
  2166. cmSystemToolsCPackCommand += "/cpack";
  2167. cmSystemToolsCPackCommand += cmSystemTools::GetExecutableExtension();
  2168. cmSystemToolsCMakeGUICommand = exe_dir;
  2169. cmSystemToolsCMakeGUICommand += "/cmake-gui";
  2170. cmSystemToolsCMakeGUICommand += cmSystemTools::GetExecutableExtension();
  2171. if(!cmSystemTools::FileExists(cmSystemToolsCMakeGUICommand.c_str()))
  2172. {
  2173. cmSystemToolsCMakeGUICommand = "";
  2174. }
  2175. cmSystemToolsCMakeCursesCommand = exe_dir;
  2176. cmSystemToolsCMakeCursesCommand += "/ccmake";
  2177. cmSystemToolsCMakeCursesCommand += cmSystemTools::GetExecutableExtension();
  2178. if(!cmSystemTools::FileExists(cmSystemToolsCMakeCursesCommand.c_str()))
  2179. {
  2180. cmSystemToolsCMakeCursesCommand = "";
  2181. }
  2182. cmSystemToolsCMClDepsCommand = exe_dir;
  2183. cmSystemToolsCMClDepsCommand += "/cmcldeps";
  2184. cmSystemToolsCMClDepsCommand += cmSystemTools::GetExecutableExtension();
  2185. if(!cmSystemTools::FileExists(cmSystemToolsCMClDepsCommand.c_str()))
  2186. {
  2187. cmSystemToolsCMClDepsCommand = "";
  2188. }
  2189. #ifdef CMAKE_BUILD_WITH_CMAKE
  2190. // Install tree has "<prefix>/bin/cmake" and "<prefix><CMAKE_DATA_DIR>".
  2191. std::string dir = cmSystemTools::GetFilenamePath(exe_dir);
  2192. cmSystemToolsCMakeRoot = dir + CMAKE_DATA_DIR;
  2193. if(!cmSystemTools::FileExists(
  2194. (cmSystemToolsCMakeRoot+"/Modules/CMake.cmake").c_str()))
  2195. {
  2196. // Build tree has "<build>/bin[/<config>]/cmake" and
  2197. // "<build>/CMakeFiles/CMakeSourceDir.txt".
  2198. std::string src_dir_txt = dir + "/CMakeFiles/CMakeSourceDir.txt";
  2199. cmsys::ifstream fin(src_dir_txt.c_str());
  2200. std::string src_dir;
  2201. if(fin && cmSystemTools::GetLineFromStream(fin, src_dir) &&
  2202. cmSystemTools::FileIsDirectory(src_dir))
  2203. {
  2204. cmSystemToolsCMakeRoot = src_dir;
  2205. }
  2206. else
  2207. {
  2208. dir = cmSystemTools::GetFilenamePath(dir);
  2209. src_dir_txt = dir + "/CMakeFiles/CMakeSourceDir.txt";
  2210. cmsys::ifstream fin2(src_dir_txt.c_str());
  2211. if(fin2 && cmSystemTools::GetLineFromStream(fin2, src_dir) &&
  2212. cmSystemTools::FileIsDirectory(src_dir))
  2213. {
  2214. cmSystemToolsCMakeRoot = src_dir;
  2215. }
  2216. }
  2217. }
  2218. #else
  2219. // Bootstrap build knows its source.
  2220. cmSystemToolsCMakeRoot = CMAKE_BOOTSTRAP_SOURCE_DIR;
  2221. #endif
  2222. }
  2223. //----------------------------------------------------------------------------
  2224. std::string const& cmSystemTools::GetCMakeCommand()
  2225. {
  2226. return cmSystemToolsCMakeCommand;
  2227. }
  2228. //----------------------------------------------------------------------------
  2229. std::string const& cmSystemTools::GetCTestCommand()
  2230. {
  2231. return cmSystemToolsCTestCommand;
  2232. }
  2233. //----------------------------------------------------------------------------
  2234. std::string const& cmSystemTools::GetCPackCommand()
  2235. {
  2236. return cmSystemToolsCPackCommand;
  2237. }
  2238. //----------------------------------------------------------------------------
  2239. std::string const& cmSystemTools::GetCMakeCursesCommand()
  2240. {
  2241. return cmSystemToolsCMakeCursesCommand;
  2242. }
  2243. //----------------------------------------------------------------------------
  2244. std::string const& cmSystemTools::GetCMakeGUICommand()
  2245. {
  2246. return cmSystemToolsCMakeGUICommand;
  2247. }
  2248. //----------------------------------------------------------------------------
  2249. std::string const& cmSystemTools::GetCMClDepsCommand()
  2250. {
  2251. return cmSystemToolsCMClDepsCommand;
  2252. }
  2253. //----------------------------------------------------------------------------
  2254. std::string const& cmSystemTools::GetCMakeRoot()
  2255. {
  2256. return cmSystemToolsCMakeRoot;
  2257. }
  2258. //----------------------------------------------------------------------------
  2259. void cmSystemTools::MakefileColorEcho(int color, const char* message,
  2260. bool newline, bool enabled)
  2261. {
  2262. // On some platforms (an MSYS prompt) cmsysTerminal may not be able
  2263. // to determine whether the stream is displayed on a tty. In this
  2264. // case it assumes no unless we tell it otherwise. Since we want
  2265. // color messages to be displayed for users we will assume yes.
  2266. // However, we can test for some situations when the answer is most
  2267. // likely no.
  2268. int assumeTTY = cmsysTerminal_Color_AssumeTTY;
  2269. if(cmSystemTools::GetEnv("DART_TEST_FROM_DART") ||
  2270. cmSystemTools::GetEnv("DASHBOARD_TEST_FROM_CTEST") ||
  2271. cmSystemTools::GetEnv("CTEST_INTERACTIVE_DEBUG_MODE"))
  2272. {
  2273. // Avoid printing color escapes during dashboard builds.
  2274. assumeTTY = 0;
  2275. }
  2276. if(enabled && color != cmsysTerminal_Color_Normal)
  2277. {
  2278. // Print with color. Delay the newline until later so that
  2279. // all color restore sequences appear before it.
  2280. cmsysTerminal_cfprintf(color | assumeTTY, stdout, "%s", message);
  2281. }
  2282. else
  2283. {
  2284. // Color is disabled. Print without color.
  2285. fprintf(stdout, "%s", message);
  2286. }
  2287. if(newline)
  2288. {
  2289. fprintf(stdout, "\n");
  2290. }
  2291. }
  2292. //----------------------------------------------------------------------------
  2293. bool cmSystemTools::GuessLibrarySOName(std::string const& fullPath,
  2294. std::string& soname)
  2295. {
  2296. // For ELF shared libraries use a real parser to get the correct
  2297. // soname.
  2298. #if defined(CMAKE_USE_ELF_PARSER)
  2299. cmELF elf(fullPath.c_str());
  2300. if(elf)
  2301. {
  2302. return elf.GetSOName(soname);
  2303. }
  2304. #endif
  2305. // If the file is not a symlink we have no guess for its soname.
  2306. if(!cmSystemTools::FileIsSymlink(fullPath))
  2307. {
  2308. return false;
  2309. }
  2310. if(!cmSystemTools::ReadSymlink(fullPath, soname))
  2311. {
  2312. return false;
  2313. }
  2314. // If the symlink has a path component we have no guess for the soname.
  2315. if(!cmSystemTools::GetFilenamePath(soname).empty())
  2316. {
  2317. return false;
  2318. }
  2319. // If the symlink points at an extended version of the same name
  2320. // assume it is the soname.
  2321. std::string name = cmSystemTools::GetFilenameName(fullPath);
  2322. if(soname.length() > name.length() &&
  2323. soname.substr(0, name.length()) == name)
  2324. {
  2325. return true;
  2326. }
  2327. return false;
  2328. }
  2329. //----------------------------------------------------------------------------
  2330. bool cmSystemTools::GuessLibraryInstallName(std::string const& fullPath,
  2331. std::string& soname)
  2332. {
  2333. #if defined(CMAKE_USE_MACH_PARSER)
  2334. cmMachO macho(fullPath.c_str());
  2335. if(macho)
  2336. {
  2337. return macho.GetInstallName(soname);
  2338. }
  2339. #else
  2340. (void)fullPath;
  2341. (void)soname;
  2342. #endif
  2343. return false;
  2344. }
  2345. //----------------------------------------------------------------------------
  2346. #if defined(CMAKE_USE_ELF_PARSER)
  2347. std::string::size_type cmSystemToolsFindRPath(std::string const& have,
  2348. std::string const& want)
  2349. {
  2350. // Search for the desired rpath.
  2351. std::string::size_type pos = have.find(want);
  2352. // If the path is not present we are done.
  2353. if(pos == std::string::npos)
  2354. {
  2355. return pos;
  2356. }
  2357. // Build a regex to match a properly separated path instance.
  2358. std::string regex_str = "(^|:)(";
  2359. for(std::string::const_iterator i = want.begin(); i != want.end(); ++i)
  2360. {
  2361. int ch = *i;
  2362. if(!(('a' <= ch && ch <= 'z') ||
  2363. ('A' <= ch && ch <= 'Z') ||
  2364. ('0' <= ch && ch <= '9')))
  2365. {
  2366. // Escape the non-alphanumeric character.
  2367. regex_str += "\\";
  2368. }
  2369. // Store the character.
  2370. regex_str.append(1, static_cast<char>(ch));
  2371. }
  2372. regex_str += ")(:|$)";
  2373. // Look for the separated path.
  2374. cmsys::RegularExpression regex(regex_str.c_str());
  2375. if(regex.find(have))
  2376. {
  2377. // Return the position of the path portion.
  2378. return regex.start(2);
  2379. }
  2380. else
  2381. {
  2382. // The desired rpath was not found.
  2383. return std::string::npos;
  2384. }
  2385. }
  2386. #endif
  2387. #if defined(CMAKE_USE_ELF_PARSER)
  2388. struct cmSystemToolsRPathInfo
  2389. {
  2390. unsigned long Position;
  2391. unsigned long Size;
  2392. std::string Name;
  2393. std::string Value;
  2394. };
  2395. #endif
  2396. //----------------------------------------------------------------------------
  2397. bool cmSystemTools::ChangeRPath(std::string const& file,
  2398. std::string const& oldRPath,
  2399. std::string const& newRPath,
  2400. std::string* emsg,
  2401. bool* changed)
  2402. {
  2403. #if defined(CMAKE_USE_ELF_PARSER)
  2404. if(changed)
  2405. {
  2406. *changed = false;
  2407. }
  2408. int rp_count = 0;
  2409. cmSystemToolsRPathInfo rp[2];
  2410. {
  2411. // Parse the ELF binary.
  2412. cmELF elf(file.c_str());
  2413. // Get the RPATH and RUNPATH entries from it.
  2414. int se_count = 0;
  2415. cmELF::StringEntry const* se[2] = {0, 0};
  2416. const char* se_name[2] = {0, 0};
  2417. if(cmELF::StringEntry const* se_rpath = elf.GetRPath())
  2418. {
  2419. se[se_count] = se_rpath;
  2420. se_name[se_count] = "RPATH";
  2421. ++se_count;
  2422. }
  2423. if(cmELF::StringEntry const* se_runpath = elf.GetRunPath())
  2424. {
  2425. se[se_count] = se_runpath;
  2426. se_name[se_count] = "RUNPATH";
  2427. ++se_count;
  2428. }
  2429. if(se_count == 0)
  2430. {
  2431. if(newRPath.empty())
  2432. {
  2433. // The new rpath is empty and there is no rpath anyway so it is
  2434. // okay.
  2435. return true;
  2436. }
  2437. else
  2438. {
  2439. if(emsg)
  2440. {
  2441. *emsg = "No valid ELF RPATH or RUNPATH entry exists in the file; ";
  2442. *emsg += elf.GetErrorMessage();
  2443. }
  2444. return false;
  2445. }
  2446. }
  2447. for(int i=0; i < se_count; ++i)
  2448. {
  2449. // If both RPATH and RUNPATH refer to the same string literal it
  2450. // needs to be changed only once.
  2451. if(rp_count && rp[0].Position == se[i]->Position)
  2452. {
  2453. continue;
  2454. }
  2455. // Make sure the current rpath contains the old rpath.
  2456. std::string::size_type pos =
  2457. cmSystemToolsFindRPath(se[i]->Value, oldRPath);
  2458. if(pos == std::string::npos)
  2459. {
  2460. // If it contains the new rpath instead then it is okay.
  2461. if(cmSystemToolsFindRPath(se[i]->Value, newRPath) != std::string::npos)
  2462. {
  2463. continue;
  2464. }
  2465. if(emsg)
  2466. {
  2467. std::ostringstream e;
  2468. e << "The current " << se_name[i] << " is:\n"
  2469. << " " << se[i]->Value << "\n"
  2470. << "which does not contain:\n"
  2471. << " " << oldRPath << "\n"
  2472. << "as was expected.";
  2473. *emsg = e.str();
  2474. }
  2475. return false;
  2476. }
  2477. // Store information about the entry in the file.
  2478. rp[rp_count].Position = se[i]->Position;
  2479. rp[rp_count].Size = se[i]->Size;
  2480. rp[rp_count].Name = se_name[i];
  2481. // Construct the new value which preserves the part of the path
  2482. // not being changed.
  2483. rp[rp_count].Value = se[i]->Value.substr(0, pos);
  2484. rp[rp_count].Value += newRPath;
  2485. rp[rp_count].Value += se[i]->Value.substr(pos+oldRPath.length(),
  2486. oldRPath.npos);
  2487. // Make sure there is enough room to store the new rpath and at
  2488. // least one null terminator.
  2489. if(rp[rp_count].Size < rp[rp_count].Value.length()+1)
  2490. {
  2491. if(emsg)
  2492. {
  2493. *emsg = "The replacement path is too long for the ";
  2494. *emsg += se_name[i];
  2495. *emsg += " entry.";
  2496. }
  2497. return false;
  2498. }
  2499. // This entry is ready for update.
  2500. ++rp_count;
  2501. }
  2502. }
  2503. // If no runtime path needs to be changed, we are done.
  2504. if(rp_count == 0)
  2505. {
  2506. return true;
  2507. }
  2508. {
  2509. // Open the file for update.
  2510. cmsys::ofstream f(file.c_str(),
  2511. std::ios::in | std::ios::out | std::ios::binary);
  2512. if(!f)
  2513. {
  2514. if(emsg)
  2515. {
  2516. *emsg = "Error opening file for update.";
  2517. }
  2518. return false;
  2519. }
  2520. // Store the new RPATH and RUNPATH strings.
  2521. for(int i=0; i < rp_count; ++i)
  2522. {
  2523. // Seek to the RPATH position.
  2524. if(!f.seekp(rp[i].Position))
  2525. {
  2526. if(emsg)
  2527. {
  2528. *emsg = "Error seeking to ";
  2529. *emsg += rp[i].Name;
  2530. *emsg += " position.";
  2531. }
  2532. return false;
  2533. }
  2534. // Write the new rpath. Follow it with enough null terminators to
  2535. // fill the string table entry.
  2536. f << rp[i].Value;
  2537. for(unsigned long j=rp[i].Value.length(); j < rp[i].Size; ++j)
  2538. {
  2539. f << '\0';
  2540. }
  2541. // Make sure it wrote correctly.
  2542. if(!f)
  2543. {
  2544. if(emsg)
  2545. {
  2546. *emsg = "Error writing the new ";
  2547. *emsg += rp[i].Name;
  2548. *emsg += " string to the file.";
  2549. }
  2550. return false;
  2551. }
  2552. }
  2553. }
  2554. // Everything was updated successfully.
  2555. if(changed)
  2556. {
  2557. *changed = true;
  2558. }
  2559. return true;
  2560. #else
  2561. (void)file;
  2562. (void)oldRPath;
  2563. (void)newRPath;
  2564. (void)emsg;
  2565. (void)changed;
  2566. return false;
  2567. #endif
  2568. }
  2569. //----------------------------------------------------------------------------
  2570. bool cmSystemTools::VersionCompare(cmSystemTools::CompareOp op,
  2571. const char* lhss, const char* rhss)
  2572. {
  2573. const char *endl = lhss;
  2574. const char *endr = rhss;
  2575. unsigned long lhs, rhs;
  2576. while (((*endl >= '0') && (*endl <= '9')) ||
  2577. ((*endr >= '0') && (*endr <= '9')))
  2578. {
  2579. // Do component-wise comparison.
  2580. lhs = strtoul(endl, const_cast<char**>(&endl), 10);
  2581. rhs = strtoul(endr, const_cast<char**>(&endr), 10);
  2582. if(lhs < rhs)
  2583. {
  2584. // lhs < rhs, so true if operation is LESS
  2585. return op == cmSystemTools::OP_LESS;
  2586. }
  2587. else if(lhs > rhs)
  2588. {
  2589. // lhs > rhs, so true if operation is GREATER
  2590. return op == cmSystemTools::OP_GREATER;
  2591. }
  2592. if (*endr == '.')
  2593. {
  2594. endr++;
  2595. }
  2596. if (*endl == '.')
  2597. {
  2598. endl++;
  2599. }
  2600. }
  2601. // lhs == rhs, so true if operation is EQUAL
  2602. return op == cmSystemTools::OP_EQUAL;
  2603. }
  2604. //----------------------------------------------------------------------------
  2605. bool cmSystemTools::RemoveRPath(std::string const& file, std::string* emsg,
  2606. bool* removed)
  2607. {
  2608. #if defined(CMAKE_USE_ELF_PARSER)
  2609. if(removed)
  2610. {
  2611. *removed = false;
  2612. }
  2613. int zeroCount = 0;
  2614. unsigned long zeroPosition[2] = {0,0};
  2615. unsigned long zeroSize[2] = {0,0};
  2616. unsigned long bytesBegin = 0;
  2617. std::vector<char> bytes;
  2618. {
  2619. // Parse the ELF binary.
  2620. cmELF elf(file.c_str());
  2621. // Get the RPATH and RUNPATH entries from it and sort them by index
  2622. // in the dynamic section header.
  2623. int se_count = 0;
  2624. cmELF::StringEntry const* se[2] = {0, 0};
  2625. if(cmELF::StringEntry const* se_rpath = elf.GetRPath())
  2626. {
  2627. se[se_count++] = se_rpath;
  2628. }
  2629. if(cmELF::StringEntry const* se_runpath = elf.GetRunPath())
  2630. {
  2631. se[se_count++] = se_runpath;
  2632. }
  2633. if(se_count == 0)
  2634. {
  2635. // There is no RPATH or RUNPATH anyway.
  2636. return true;
  2637. }
  2638. if(se_count == 2 && se[1]->IndexInSection < se[0]->IndexInSection)
  2639. {
  2640. std::swap(se[0], se[1]);
  2641. }
  2642. // Get the size of the dynamic section header.
  2643. unsigned int count = elf.GetDynamicEntryCount();
  2644. if(count == 0)
  2645. {
  2646. // This should happen only for invalid ELF files where a DT_NULL
  2647. // appears before the end of the table.
  2648. if(emsg)
  2649. {
  2650. *emsg = "DYNAMIC section contains a DT_NULL before the end.";
  2651. }
  2652. return false;
  2653. }
  2654. // Save information about the string entries to be zeroed.
  2655. zeroCount = se_count;
  2656. for(int i=0; i < se_count; ++i)
  2657. {
  2658. zeroPosition[i] = se[i]->Position;
  2659. zeroSize[i] = se[i]->Size;
  2660. }
  2661. // Get the range of file positions corresponding to each entry and
  2662. // the rest of the table after them.
  2663. unsigned long entryBegin[3] = {0,0,0};
  2664. unsigned long entryEnd[2] = {0,0};
  2665. for(int i=0; i < se_count; ++i)
  2666. {
  2667. entryBegin[i] = elf.GetDynamicEntryPosition(se[i]->IndexInSection);
  2668. entryEnd[i] = elf.GetDynamicEntryPosition(se[i]->IndexInSection+1);
  2669. }
  2670. entryBegin[se_count] = elf.GetDynamicEntryPosition(count);
  2671. // The data are to be written over the old table entries starting at
  2672. // the first one being removed.
  2673. bytesBegin = entryBegin[0];
  2674. unsigned long bytesEnd = entryBegin[se_count];
  2675. // Allocate a buffer to hold the part of the file to be written.
  2676. // Initialize it with zeros.
  2677. bytes.resize(bytesEnd - bytesBegin, 0);
  2678. // Read the part of the DYNAMIC section header that will move.
  2679. // The remainder of the buffer will be left with zeros which
  2680. // represent a DT_NULL entry.
  2681. char* data = &bytes[0];
  2682. for(int i=0; i < se_count; ++i)
  2683. {
  2684. // Read data between the entries being removed.
  2685. unsigned long sz = entryBegin[i+1] - entryEnd[i];
  2686. if(sz > 0 && !elf.ReadBytes(entryEnd[i], sz, data))
  2687. {
  2688. if(emsg)
  2689. {
  2690. *emsg = "Failed to read DYNAMIC section header.";
  2691. }
  2692. return false;
  2693. }
  2694. data += sz;
  2695. }
  2696. }
  2697. // Open the file for update.
  2698. cmsys::ofstream f(file.c_str(),
  2699. std::ios::in | std::ios::out | std::ios::binary);
  2700. if(!f)
  2701. {
  2702. if(emsg)
  2703. {
  2704. *emsg = "Error opening file for update.";
  2705. }
  2706. return false;
  2707. }
  2708. // Write the new DYNAMIC table header.
  2709. if(!f.seekp(bytesBegin))
  2710. {
  2711. if(emsg)
  2712. {
  2713. *emsg = "Error seeking to DYNAMIC table header for RPATH.";
  2714. }
  2715. return false;
  2716. }
  2717. if(!f.write(&bytes[0], bytes.size()))
  2718. {
  2719. if(emsg)
  2720. {
  2721. *emsg = "Error replacing DYNAMIC table header.";
  2722. }
  2723. return false;
  2724. }
  2725. // Fill the RPATH and RUNPATH strings with zero bytes.
  2726. for(int i=0; i < zeroCount; ++i)
  2727. {
  2728. if(!f.seekp(zeroPosition[i]))
  2729. {
  2730. if(emsg)
  2731. {
  2732. *emsg = "Error seeking to RPATH position.";
  2733. }
  2734. return false;
  2735. }
  2736. for(unsigned long j=0; j < zeroSize[i]; ++j)
  2737. {
  2738. f << '\0';
  2739. }
  2740. if(!f)
  2741. {
  2742. if(emsg)
  2743. {
  2744. *emsg = "Error writing the empty rpath string to the file.";
  2745. }
  2746. return false;
  2747. }
  2748. }
  2749. // Everything was updated successfully.
  2750. if(removed)
  2751. {
  2752. *removed = true;
  2753. }
  2754. return true;
  2755. #else
  2756. (void)file;
  2757. (void)emsg;
  2758. (void)removed;
  2759. return false;
  2760. #endif
  2761. }
  2762. //----------------------------------------------------------------------------
  2763. bool cmSystemTools::CheckRPath(std::string const& file,
  2764. std::string const& newRPath)
  2765. {
  2766. #if defined(CMAKE_USE_ELF_PARSER)
  2767. // Parse the ELF binary.
  2768. cmELF elf(file.c_str());
  2769. // Get the RPATH or RUNPATH entry from it.
  2770. cmELF::StringEntry const* se = elf.GetRPath();
  2771. if(!se)
  2772. {
  2773. se = elf.GetRunPath();
  2774. }
  2775. // Make sure the current rpath contains the new rpath.
  2776. if(newRPath.empty())
  2777. {
  2778. if(!se)
  2779. {
  2780. return true;
  2781. }
  2782. }
  2783. else
  2784. {
  2785. if(se &&
  2786. cmSystemToolsFindRPath(se->Value, newRPath) != std::string::npos)
  2787. {
  2788. return true;
  2789. }
  2790. }
  2791. return false;
  2792. #else
  2793. (void)file;
  2794. (void)newRPath;
  2795. return false;
  2796. #endif
  2797. }
  2798. //----------------------------------------------------------------------------
  2799. bool cmSystemTools::RepeatedRemoveDirectory(const char* dir)
  2800. {
  2801. // Windows sometimes locks files temporarily so try a few times.
  2802. for(int i = 0; i < 10; ++i)
  2803. {
  2804. if(cmSystemTools::RemoveADirectory(dir))
  2805. {
  2806. return true;
  2807. }
  2808. cmSystemTools::Delay(100);
  2809. }
  2810. return false;
  2811. }
  2812. //----------------------------------------------------------------------------
  2813. std::vector<std::string> cmSystemTools::tokenize(const std::string& str,
  2814. const std::string& sep)
  2815. {
  2816. std::vector<std::string> tokens;
  2817. std::string::size_type tokend = 0;
  2818. do
  2819. {
  2820. std::string::size_type tokstart=str.find_first_not_of(sep, tokend);
  2821. if (tokstart==std::string::npos)
  2822. {
  2823. break; // no more tokens
  2824. }
  2825. tokend=str.find_first_of(sep,tokstart);
  2826. if (tokend==std::string::npos)
  2827. {
  2828. tokens.push_back(str.substr(tokstart));
  2829. }
  2830. else
  2831. {
  2832. tokens.push_back(str.substr(tokstart,tokend-tokstart));
  2833. }
  2834. } while (tokend!=std::string::npos);
  2835. if (tokens.empty())
  2836. {
  2837. tokens.push_back("");
  2838. }
  2839. return tokens;
  2840. }
  2841. //----------------------------------------------------------------------------
  2842. bool cmSystemTools::StringToLong(const char* str, long* value)
  2843. {
  2844. errno = 0;
  2845. char *endp;
  2846. *value = strtol(str, &endp, 10);
  2847. return (*endp == '\0') && (endp != str) && (errno == 0);
  2848. }
  2849. //----------------------------------------------------------------------------
  2850. bool cmSystemTools::StringToULong(const char* str, unsigned long* value)
  2851. {
  2852. errno = 0;
  2853. char *endp;
  2854. *value = strtoul(str, &endp, 10);
  2855. return (*endp == '\0') && (endp != str) && (errno == 0);
  2856. }