cmSystemTools.cxx 85 KB

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