cmSystemTools.cxx 94 KB

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