cmSystemTools.cxx 86 KB

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