cmSystemTools.cxx 101 KB

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