cmSystemTools.cxx 82 KB

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