cmSystemTools.cxx 87 KB

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