cmSystemTools.cxx 105 KB

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