cmSystemTools.cxx 83 KB

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