cmSystemTools.cxx 87 KB

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